@johnhenry/browsermesh-apps 0.10.0 → 0.12.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.
@@ -12,8 +12,14 @@
12
12
  */
13
13
 
14
14
  import { MESH_TYPE } from '@johnhenry/browsermesh-primitives'
15
- import { ComputeRequest, ResourceDescriptor, ResourceScorer } from './resources.mjs'
15
+ import { ComputeRequest, ResourceDescriptor, ResourceScorer, RUNTIME_CLASS, ISOLATION } from './resources.mjs'
16
16
  import { BrowserTool as CompatBrowserTool } from './compat.mjs'
17
+ import {
18
+ validatePodSpec,
19
+ POD_LANE,
20
+ POD_HOST_ERROR,
21
+ PodHostDriverError,
22
+ } from '@johnhenry/browsermesh-pod'
17
23
 
18
24
  // A real browser environment (clawser's web/clawser-tools.js) may already
19
25
  // have defined a real, richer `globalThis.BrowserTool` -- honored first, as
@@ -26,7 +32,7 @@ import { BrowserTool as CompatBrowserTool } from './compat.mjs'
26
32
  // below in Node -- `.spec` composes `{name, description, parameters,
27
33
  // required_permission}` from each subclass's own overridden getters, which
28
34
  // only exists on compat.mjs's real `BrowserTool`, not the old stub. Using the
29
- // real class changes nothing about the 8 Meshctl*Tool subclasses' own bodies
35
+ // real class changes nothing about the 13 Meshctl*Tool subclasses' own bodies
30
36
  // below (their name/description/parameters/permission getters and execute()
31
37
  // methods are all still their own overrides) -- only what `.spec` (and the
32
38
  // default `execute()`/`permission` a subclass doesn't override) resolves to.
@@ -52,6 +58,21 @@ const VALID_POD_STATUSES = Object.freeze([
52
58
  'online', 'offline', 'draining', 'unknown',
53
59
  ])
54
60
 
61
+ /**
62
+ * Placement-lifecycle audit record names (issue #185 §7/§8 WP4). WP4 wires
63
+ * only the vocabulary and the audit path -- actual placement RPC (spawning
64
+ * or restoring a hosted pod on an isolate/microvm host) is WP2/WP3, not
65
+ * implemented here. Mirrors the existing `remote_deploy_*`/`remote_exec_*`
66
+ * audit record naming.
67
+ */
68
+ export const PLACEMENT_AUDIT = Object.freeze({
69
+ REQUESTED: 'placement_requested',
70
+ DENIED: 'placement_denied',
71
+ STARTED: 'placement_started',
72
+ READY: 'placement_ready',
73
+ EVICTED: 'placement_evicted',
74
+ })
75
+
55
76
  // ---------------------------------------------------------------------------
56
77
  // PodInfo
57
78
  // ---------------------------------------------------------------------------
@@ -254,6 +275,14 @@ export class MeshOrchestrator {
254
275
  #auditRecorder
255
276
  /** @type {object|null} */
256
277
  #peerRegistry
278
+ /** @type {object|null} PodHostClient -- injected, or lazily built from #peerNode */
279
+ #podHostClient
280
+ /** @type {Promise<object>|null} In-flight lazy `createPodHostClient()` import */
281
+ #podHostClientPromise = null
282
+ /** @type {object|null} The lazily-created `PodSupervisor` (issue #185 item 6) -- see `getSupervisor()`. */
283
+ #supervisor = null
284
+ /** @type {Promise<object>|null} In-flight lazy `createPodSupervisor()` import/construction. */
285
+ #supervisorPromise = null
257
286
  /** @type {Map<string, object>} podId -> peer info */
258
287
  #knownPeers = new Map()
259
288
  /** @type {Map<string, object>} name -> { podId, port } */
@@ -278,9 +307,13 @@ export class MeshOrchestrator {
278
307
  * @param {object} [opts.resourceRegistry] - ResourceRegistry or null
279
308
  * @param {object} [opts.auditRecorder] - RemoteRuntimeAuditRecorder or null
280
309
  * @param {object} [opts.peerRegistry] - PeerRegistry or null
310
+ * @param {object} [opts.podHostClient] - `PodHostClient`
311
+ * (`pod-host-service.mjs`) used by `spawnPod()`/`snapshotPod()`/
312
+ * `restorePod()`/`listHostedPods()`. Lazily built from `peerNode` on
313
+ * first use when omitted.
281
314
  * @param {Function} [opts.onLog] - Logging callback
282
315
  */
283
- constructor({ peerNode, serviceAdvertiser, serviceBrowser, router, runtimeRegistry, remoteSessionBroker, resourceRegistry, auditRecorder, peerRegistry, onLog }) {
316
+ constructor({ peerNode, serviceAdvertiser, serviceBrowser, router, runtimeRegistry, remoteSessionBroker, resourceRegistry, auditRecorder, peerRegistry, podHostClient, onLog }) {
284
317
  if (!peerNode) {
285
318
  throw new Error('peerNode is required')
286
319
  }
@@ -293,6 +326,7 @@ export class MeshOrchestrator {
293
326
  this.#resourceRegistry = resourceRegistry ?? null
294
327
  this.#auditRecorder = auditRecorder ?? null
295
328
  this.#peerRegistry = peerRegistry ?? null
329
+ this.#podHostClient = podHostClient ?? null
296
330
  this.#onLog = onLog ?? null
297
331
  }
298
332
 
@@ -316,6 +350,218 @@ export class MeshOrchestrator {
316
350
  await this.#auditRecorder?.record?.(operation, data)
317
351
  }
318
352
 
353
+ /**
354
+ * Record a placement-lifecycle audit event (issue #185 §7/§8 WP4): one of
355
+ * `PLACEMENT_AUDIT`'s `placement_requested`/`placement_denied`/
356
+ * `placement_started`/`placement_ready`/`placement_evicted`. Writes
357
+ * through the same `#recordAudit` path as `execOnPod`/`deploySkill`'s
358
+ * `remote_*` records -- a no-op when no `auditRecorder` is wired. This is
359
+ * vocabulary + audit plumbing only: WP4 does not implement the placement
360
+ * RPC itself (spawning/restoring a hosted pod), that is WP2 (isolate pod
361
+ * host) / WP3 (microVM pod host).
362
+ *
363
+ * @param {string} kind - One of `PLACEMENT_AUDIT`'s values
364
+ * @param {object} [details]
365
+ * @returns {Promise<void>}
366
+ */
367
+ async recordPlacement(kind, details = {}) {
368
+ await this.#recordAudit(kind, details)
369
+ }
370
+
371
+ // -- Hosted pods (issue #185 control surface) -----------------------------
372
+
373
+ /**
374
+ * The `PodHostClient` used by `spawnPod()` and friends: the injected one
375
+ * when the constructor was given a `podHostClient`, otherwise one built
376
+ * lazily from this orchestrator's own `peerNode`.
377
+ *
378
+ * `pod-host-service.mjs` is imported DYNAMICALLY rather than at module
379
+ * top level on purpose: that module imports `PLACEMENT_AUDIT` from this
380
+ * one, and a static import in both directions would be a cycle. This is
381
+ * the same lazy-`await import()` convention `mesh-hardening.mjs` /
382
+ * `key-distribution.mjs` already use for the apps<->core pair (see
383
+ * AGENTS.md's "Cross-package relationship" note).
384
+ *
385
+ * @returns {Promise<object>} A `PodHostClient`.
386
+ */
387
+ async #hostClient() {
388
+ if (this.#podHostClient) return this.#podHostClient
389
+ if (!this.#podHostClientPromise) {
390
+ this.#podHostClientPromise = import('./pod-host-service.mjs')
391
+ .then(({ createPodHostClient }) => createPodHostClient({ peerNode: this.#peerNode }))
392
+ }
393
+ this.#podHostClient = await this.#podHostClientPromise
394
+ return this.#podHostClient
395
+ }
396
+
397
+ /**
398
+ * Spawn a hosted pod on a pod host, recording the requester half of the
399
+ * placement audit trail (`placement_requested` on the way out, then
400
+ * `placement_ready` or `placement_denied`). The HOST writes its own,
401
+ * independent `placement_started`/`placement_ready` records -- see
402
+ * `pod-host-service.mjs`'s module doc comment on why the two chains are
403
+ * deliberately separate.
404
+ *
405
+ * @param {string} hostPodId - The host pod's pubKey/podId.
406
+ * @param {object} spec - A podspec (`validatePodSpec()` in
407
+ * `@johnhenry/browsermesh-pod`), validated host-side.
408
+ * @returns {Promise<object>} The host's pod status.
409
+ */
410
+ async spawnPod(hostPodId, spec) {
411
+ const client = await this.#hostClient()
412
+ await this.recordPlacement(PLACEMENT_AUDIT.REQUESTED, {
413
+ actor: 'operator', hostPodId, name: spec?.name ?? null, lane: spec?.lane ?? null,
414
+ })
415
+ try {
416
+ const result = await client.spawn(hostPodId, spec)
417
+ await this.recordPlacement(PLACEMENT_AUDIT.READY, {
418
+ actor: 'operator', hostPodId, name: result?.name ?? spec?.name ?? null,
419
+ lane: result?.lane ?? null, state: result?.state ?? null,
420
+ })
421
+ return result
422
+ } catch (err) {
423
+ if (err?.code === 'EACCES') {
424
+ await this.recordPlacement(PLACEMENT_AUDIT.DENIED, {
425
+ actor: 'operator', hostPodId, name: spec?.name ?? null, reason: err.message,
426
+ })
427
+ }
428
+ throw err
429
+ }
430
+ }
431
+
432
+ /**
433
+ * Snapshot a hosted pod. A snapshotted pod has left the host's live set
434
+ * (§5.3: the VMM is killed), so this records `placement_evicted`.
435
+ *
436
+ * @param {string} hostPodId
437
+ * @param {string} name
438
+ * @returns {Promise<object>}
439
+ */
440
+ async snapshotPod(hostPodId, name) {
441
+ const client = await this.#hostClient()
442
+ const result = await client.snapshot(hostPodId, name)
443
+ await this.recordPlacement(PLACEMENT_AUDIT.EVICTED, {
444
+ actor: 'operator', hostPodId, name, reason: 'snapshot', state: result?.state ?? null,
445
+ })
446
+ return result
447
+ }
448
+
449
+ /**
450
+ * Restore a snapshotted hosted pod, recording the same
451
+ * `placement_requested` -> `placement_ready` pair `spawnPod()` does: from
452
+ * the requester's point of view a restore IS a placement.
453
+ *
454
+ * @param {string} hostPodId
455
+ * @param {string} name
456
+ * @returns {Promise<object>}
457
+ */
458
+ async restorePod(hostPodId, name) {
459
+ const client = await this.#hostClient()
460
+ await this.recordPlacement(PLACEMENT_AUDIT.REQUESTED, {
461
+ actor: 'operator', hostPodId, name, reason: 'restore',
462
+ })
463
+ try {
464
+ const result = await client.restore(hostPodId, name)
465
+ await this.recordPlacement(PLACEMENT_AUDIT.READY, {
466
+ actor: 'operator', hostPodId, name, reason: 'restore', state: result?.state ?? null,
467
+ })
468
+ return result
469
+ } catch (err) {
470
+ if (err?.code === 'EACCES') {
471
+ await this.recordPlacement(PLACEMENT_AUDIT.DENIED, {
472
+ actor: 'operator', hostPodId, name, reason: err.message,
473
+ })
474
+ }
475
+ throw err
476
+ }
477
+ }
478
+
479
+ /**
480
+ * List the pods a host is tracking. Read-only: no audit record, matching
481
+ * `listPods()`.
482
+ *
483
+ * @param {string} hostPodId
484
+ * @returns {Promise<object[]>}
485
+ */
486
+ async listHostedPods(hostPodId) {
487
+ const client = await this.#hostClient()
488
+ return client.list(hostPodId)
489
+ }
490
+
491
+ /**
492
+ * List known pod hosts (issue #185 control surface item 4's `meshctl_hosts`):
493
+ * runtime-registry peers whose `describe()` was projected through
494
+ * `podHostRuntimePeer()` (`pod-host-service.mjs`), i.e. peers carrying a
495
+ * `metadata.podHost` entry. Read-only, from the same `#runtimeDescriptors()`
496
+ * source `#collectComputeDescriptors()` already walks -- no audit record,
497
+ * matching `listHostedPods()`/`listPods()`.
498
+ *
499
+ * Deliberately NOT routed through `#collectComputeDescriptors()` /
500
+ * `listComputeCandidates()`: those drop any pod host with no `exec`
501
+ * (every ISOLATE-lane host, by lane definition -- see
502
+ * `pod-host-service.mjs`'s `podHostRuntimePeer()` doc comment and this
503
+ * package's README "Known limitation" section) before a caller ever gets
504
+ * a chance to filter on lane. Reading `#runtimeDescriptors()` directly
505
+ * sidesteps that filter, so an isolate host is listed here even though it
506
+ * is invisible to `listComputeCandidates()`.
507
+ *
508
+ * @returns {Array<{podId: string, lane: string|null, verbs: string[], runtimeClasses: string[], shellBackend: string|null, resource: string, capabilities: string[], hostedBy: string|null}>}
509
+ */
510
+ async listPodHosts() {
511
+ const hosts = []
512
+ for (const peer of this.#runtimeDescriptors()) {
513
+ const podHost = peer.metadata?.podHost
514
+ if (!podHost) continue
515
+ const podId = this.#descriptorPodId(peer)
516
+ if (!podId) continue
517
+ hosts.push({
518
+ podId,
519
+ lane: (peer.metadata?.runtimeClasses || [])[0] ?? null,
520
+ verbs: [...(podHost.verbs || [])],
521
+ runtimeClasses: [...(peer.metadata?.runtimeClasses || [])],
522
+ shellBackend: peer.shellBackend ?? null,
523
+ resource: podHost.resource || 'pod-host',
524
+ capabilities: [...(peer.capabilities || [])],
525
+ hostedBy: peer.metadata?.hostedBy || null,
526
+ })
527
+ }
528
+ return hosts
529
+ }
530
+
531
+ /**
532
+ * The lazily-created `PodSupervisor` (issue #185 item 6: links, monitors,
533
+ * restart policy over the eight-verb control surface). Built once, on
534
+ * first use, against THIS orchestrator -- `pod-supervisor.mjs` is
535
+ * imported DYNAMICALLY for the same reason `#hostClient()` imports
536
+ * `pod-host-service.mjs` dynamically: `pod-supervisor.mjs` statically
537
+ * imports both `orchestrator.mjs` (for `pickAutoHost()`) and
538
+ * `pod-host-service.mjs`, so a static import here would be a cycle (see
539
+ * AGENTS.md's "Cross-package relationship" note for the established
540
+ * pattern this follows).
541
+ *
542
+ * `drainPod()` reads `#supervisor` directly (not through this method) so
543
+ * that draining a host never SPINS UP a supervisor that was never asked
544
+ * for just to find it has nothing to do.
545
+ *
546
+ * @param {object} [opts] - Forwarded to `createPodSupervisor()`, minus
547
+ * `orchestrator` (always `this`). Pass `{auditChain}` to wire audit
548
+ * records; omitted by default since `MeshOrchestrator`'s own
549
+ * `#auditRecorder` is a different, simpler shape
550
+ * (`.record(operation, data)`, not `AuditChain`'s
551
+ * `.append(author, op, data, signFn)`) and the two are not silently
552
+ * interchangeable.
553
+ * @returns {Promise<object>} A `PodSupervisor` (`pod-supervisor.mjs`).
554
+ */
555
+ async getSupervisor(opts = {}) {
556
+ if (this.#supervisor) return this.#supervisor
557
+ if (!this.#supervisorPromise) {
558
+ this.#supervisorPromise = import('./pod-supervisor.mjs')
559
+ .then(({ createPodSupervisor }) => createPodSupervisor({ orchestrator: this, ...opts }))
560
+ }
561
+ this.#supervisor = await this.#supervisorPromise
562
+ return this.#supervisor
563
+ }
564
+
319
565
  #recordComputeReputation(descriptor, score) {
320
566
  const fingerprint = descriptor?.identity?.fingerprint || null
321
567
  if (!fingerprint || !this.#peerRegistry?.recordObservedTrust) return
@@ -452,6 +698,18 @@ export class MeshOrchestrator {
452
698
  }
453
699
 
454
700
  const runtime = this.#resolveRuntime(podId)
701
+ if (runtime && isIsolateOnlyRuntime(runtime)) {
702
+ await this.#recordAudit('remote_exec_denied', {
703
+ actor: 'operator',
704
+ podId,
705
+ reason: 'isolate runtime cannot execute shell commands',
706
+ layer: 'runtime',
707
+ })
708
+ return {
709
+ output: 'pod runtime "isolate" cannot execute shell commands; use deploySkill or a microvm pod',
710
+ exitCode: 126,
711
+ }
712
+ }
455
713
  if (runtime && this.#remoteSessionBroker) {
456
714
  const result = await this.#remoteSessionBroker.openSession(podId, {
457
715
  intent: 'exec',
@@ -757,6 +1015,25 @@ export class MeshOrchestrator {
757
1015
  * @returns {Promise<{ success: boolean, migrated: number }>}
758
1016
  */
759
1017
  async drainPod(podId) {
1018
+ // Issue #185 item 6: if a supervisor already exists on this orchestrator
1019
+ // (read directly, NOT through `getSupervisor()` -- draining a pod should
1020
+ // never spin one up just to discover it is tracking nothing) and it is
1021
+ // supervising any pods hosted ON `podId`, cascade-drain those FIRST,
1022
+ // through the pod-host client, before the pre-existing mesh-peer drain
1023
+ // logic below runs. `podId` here is a HOST's pod id (the mesh peer being
1024
+ // drained); its hosted pods are a different, separate population from
1025
+ // `#knownPeers` and have to be told to leave on their own.
1026
+ if (this.#supervisor) {
1027
+ const hosted = this.#supervisor.list().filter((p) => p.host === podId && p.state !== 'dead')
1028
+ for (const p of hosted) {
1029
+ try {
1030
+ await this.#supervisor.drain(p.ref, { cascade: true })
1031
+ } catch (err) {
1032
+ this.#log(`drainPod: supervisor drain of '${p.ref.name}' on host ${podId} failed: ${err?.message || err}`)
1033
+ }
1034
+ }
1035
+ }
1036
+
760
1037
  const info = this.#knownPeers.get(podId)
761
1038
  const localPodId = this.localPodId
762
1039
 
@@ -1072,11 +1349,36 @@ function runtimePeerToComputeDescriptor(peer) {
1072
1349
  resources: peer.metadata?.resources || {},
1073
1350
  capabilities,
1074
1351
  availability,
1352
+ hostedBy: peer.metadata?.hostedBy || null,
1075
1353
  })
1076
1354
  descriptor.source = 'runtime-registry'
1077
1355
  return descriptor
1078
1356
  }
1079
1357
 
1358
+ /**
1359
+ * Whether a runtime-registry peer's advertised runtime classes mean it can
1360
+ * only run inside a V8 isolate (issue #185 §6/§8 WP4): `'isolate'` is one
1361
+ * of its `metadata.runtimeClasses`, and nothing else about the peer --
1362
+ * another runtime class of `'microvm'`/`'node'`/`'browser'`, or an
1363
+ * explicit `shellBackend` -- says it can also execute shell commands. Used
1364
+ * by `execOnPod()` to deny shell execution against isolate-only pods
1365
+ * instead of silently dispatching a request the pod has no way to honor.
1366
+ *
1367
+ * @param {object} runtime - A runtime-registry peer, as returned by
1368
+ * `#resolveRuntime()` (the same shape `runtimePeerToComputeDescriptor()`
1369
+ * and `deploySkill()`'s `runtime.metadata?.deploymentSupport` read).
1370
+ * @returns {boolean}
1371
+ */
1372
+ function isIsolateOnlyRuntime(runtime) {
1373
+ const runtimeClasses = runtime?.metadata?.runtimeClasses || []
1374
+ if (!runtimeClasses.includes(RUNTIME_CLASS.ISOLATE)) return false
1375
+ if (runtimeClasses.includes(RUNTIME_CLASS.MICROVM)) return false
1376
+ if (runtimeClasses.includes(RUNTIME_CLASS.NODE)) return false
1377
+ if (runtimeClasses.includes(RUNTIME_CLASS.BROWSER)) return false
1378
+ if (runtime?.shellBackend) return false
1379
+ return true
1380
+ }
1381
+
1080
1382
  function mergeResourceDescriptors(base, incoming) {
1081
1383
  const merged = new ResourceDescriptor({
1082
1384
  podId: base.podId,
@@ -1091,6 +1393,7 @@ function mergeResourceDescriptors(base, incoming) {
1091
1393
  availability: availabilityPriority(incoming.availability) > availabilityPriority(base.availability)
1092
1394
  ? incoming.availability
1093
1395
  : base.availability,
1396
+ hostedBy: incoming.hostedBy || base.hostedBy || null,
1094
1397
  })
1095
1398
  merged.source = incoming.source || base.source || 'resource-registry'
1096
1399
  return merged
@@ -1448,13 +1751,486 @@ export class MeshctlDrainTool extends BrowserTool {
1448
1751
  }
1449
1752
  }
1450
1753
 
1754
+ // ---------------------------------------------------------------------------
1755
+ // Hosted pods control surface (issue #185 §8a item 4) -- meshctl_spawn,
1756
+ // meshctl_snapshot, meshctl_restore, meshctl_hosted_pods, meshctl_hosts
1757
+ // ---------------------------------------------------------------------------
1758
+
1759
+ /**
1760
+ * Lane-aware hints for `POD_HOST_ERROR.ELANE` failures, keyed by verb. Only
1761
+ * `exec`/`snapshot`/`restore` are ever `ELANE` (`POD_LANE_VERBS` in
1762
+ * `host-protocol.mjs`), and only for the `isolate`/`browser` lanes -- a V8
1763
+ * isolate has no shell and no process to freeze to disk; Durable Object
1764
+ * hibernation is automatic, not a verb a caller drives.
1765
+ */
1766
+ const ELANE_HINTS = Object.freeze({
1767
+ exec: 'isolate pods cannot exec; use meshctl_deploy or spawn on a microvm host',
1768
+ snapshot: 'isolate pods cannot snapshot; Durable Object hibernation is automatic, not a verb you drive',
1769
+ restore: 'isolate pods cannot restore; Durable Object hibernation is automatic, not a verb you drive',
1770
+ })
1771
+
1772
+ /**
1773
+ * Turn a `PodHostDriverError` (or anything `PodHostDriverError.from()`
1774
+ * accepts) into a human-readable, lane-aware message for a `meshctl_*`
1775
+ * tool's `error` field or the `meshctl` shell's `stderr`. Never retries or
1776
+ * picks a different host -- "the orchestrator proposes, the host accepts":
1777
+ * an `EACCES` (or any other code) is reported as-is, exactly once.
1778
+ *
1779
+ * @param {*} err
1780
+ * @param {{host?: string, verb?: string}} [ctx]
1781
+ * @returns {string}
1782
+ */
1783
+ function formatPodHostError(err, { host, verb } = {}) {
1784
+ const driverError = PodHostDriverError.from(err)
1785
+ const lane = driverError.details?.lane ?? null
1786
+ const name = driverError.details?.name ?? null
1787
+ const where = host ? ` on host '${host}'` : ''
1788
+ switch (driverError.code) {
1789
+ case POD_HOST_ERROR.EACCES:
1790
+ return `not authorized to '${verb}'${where} (grant pod-host:${verb} to this requester)`
1791
+ case POD_HOST_ERROR.ENOENT:
1792
+ return `no pod${name ? ` named '${name}'` : ''} found${where}`
1793
+ case POD_HOST_ERROR.EEXIST:
1794
+ return `pod${name ? ` '${name}'` : ''} already exists${where}`
1795
+ case POD_HOST_ERROR.EINVAL:
1796
+ return `invalid request: ${driverError.message}`
1797
+ case POD_HOST_ERROR.ENOTSUP:
1798
+ return `host${where} does not implement '${verb}' (its lane could, but this driver has not)`
1799
+ case POD_HOST_ERROR.ELANE:
1800
+ return ELANE_HINTS[verb] || `lane '${lane ?? 'unknown'}' structurally cannot '${verb}'`
1801
+ case POD_HOST_ERROR.ETIMEDOUT:
1802
+ return `host${where} did not respond in time`
1803
+ case POD_HOST_ERROR.EBUSY:
1804
+ return `pod${where} is mid-transition; try again`
1805
+ default:
1806
+ return driverError.message
1807
+ }
1808
+ }
1809
+
1810
+ /**
1811
+ * Pick the best pod host for a given lane -- `meshctl_spawn`'s `host: 'auto'`
1812
+ * path, and the `meshctl spawn <host|auto> ...` shell command's equivalent.
1813
+ * "The orchestrator proposes, the host accepts": this picks exactly one
1814
+ * host and never retries a different one after a refusal (see
1815
+ * `formatPodHostError()` and `MeshctlSpawnTool#execute()`).
1816
+ *
1817
+ * Primary path: `orchestrator.listComputeCandidates()` (the same
1818
+ * `ResourceScorer`-adjacent descriptor list `MeshctlComputeTool` reads),
1819
+ * narrowed to hosts advertising `runtime:<lane>`, preferring one with
1820
+ * `availability: 'online'`.
1821
+ *
1822
+ * Fallback: `orchestrator.listPodHosts()`. This exists because of a
1823
+ * documented gap (`pod-host-service.mjs`'s `podHostRuntimePeer()` doc
1824
+ * comment, and this package's README "Known limitation" section):
1825
+ * `listComputeCandidates()` derives its `compute` capability from `exec`,
1826
+ * so an ISOLATE-lane host (no `exec`, by lane definition -- same for
1827
+ * `browser`) never appears in it at all, regardless of lane filtering.
1828
+ * `listPodHosts()` reads the same runtime-registry peers directly, without
1829
+ * that filter, so it still finds such a host.
1830
+ *
1831
+ * @param {object} orchestrator - A `MeshOrchestrator` (or the tool facade
1832
+ * `mesh-orchestrator-tools.mjs` builds around one).
1833
+ * @param {string} lane - A `POD_LANE` value.
1834
+ * @returns {Promise<{podId: string, reason: string}|null>}
1835
+ */
1836
+ export async function pickAutoHost(orchestrator, lane) {
1837
+ const isolation = lane === POD_LANE.ISOLATE
1838
+ ? ISOLATION.ISOLATE
1839
+ : lane === POD_LANE.MICROVM
1840
+ ? ISOLATION.MICROVM
1841
+ : ISOLATION.ANY
1842
+ const candidates = typeof orchestrator.listComputeCandidates === 'function'
1843
+ ? await orchestrator.listComputeCandidates({ isolation })
1844
+ : []
1845
+ const laneCandidates = candidates.filter((c) => c.capabilities.includes(`runtime:${lane}`))
1846
+ const best = laneCandidates.find((c) => c.availability === 'online') || laneCandidates[0] || null
1847
+ if (best) {
1848
+ return {
1849
+ podId: best.podId,
1850
+ reason: `best compute candidate advertising lane '${lane}' (${best.availability}, via ${best.source})`,
1851
+ }
1852
+ }
1853
+
1854
+ if (typeof orchestrator.listPodHosts !== 'function') return null
1855
+ const hosts = await orchestrator.listPodHosts()
1856
+ const laneHosts = hosts.filter((h) => h.lane === lane)
1857
+ if (laneHosts.length === 0) return null
1858
+ return {
1859
+ podId: laneHosts[0].podId,
1860
+ reason: `only known pod host advertising lane '${lane}' (no exec, so invisible to compute-candidate scoring)`,
1861
+ }
1862
+ }
1863
+
1864
+ /**
1865
+ * Build a podspec from `MeshctlSpawnTool#execute()`'s separate arguments,
1866
+ * omitting any key the caller did not supply -- `validatePodSpec()` treats
1867
+ * an explicit `undefined` the same as a present-but-wrong-typed value
1868
+ * (`rejectUnknownKeys()` walks `Object.keys()`, which includes keys whose
1869
+ * value is `undefined`), so building the object conditionally matters, not
1870
+ * just cosmetically.
1871
+ *
1872
+ * @param {object} args
1873
+ * @returns {object}
1874
+ */
1875
+ function buildPodSpec({ name, lane, run, limits, caps, env, budget, restart, labels, links }) {
1876
+ const spec = { name, run }
1877
+ if (lane !== undefined) spec.lane = lane
1878
+ if (limits !== undefined) spec.limits = limits
1879
+ if (caps !== undefined) spec.caps = caps
1880
+ if (env !== undefined) spec.env = env
1881
+ if (budget !== undefined) spec.budget = budget
1882
+ if (restart !== undefined) spec.restart = restart
1883
+ if (labels !== undefined) spec.labels = labels
1884
+ if (links !== undefined) spec.links = links
1885
+ return spec
1886
+ }
1887
+
1888
+ // ── meshctl_spawn ─────────────────────────────────────────────────────
1889
+
1890
+ export class MeshctlSpawnTool extends BrowserTool {
1891
+ #orchestrator
1892
+
1893
+ constructor(orchestrator) {
1894
+ super()
1895
+ this.#orchestrator = orchestrator
1896
+ }
1897
+
1898
+ get name() { return 'meshctl_spawn' }
1899
+ get description() {
1900
+ return "Spawn a hosted pod (issue #185 control surface) on a pod host, in a V8 isolate or microVM lane. " +
1901
+ "Pass host: 'auto' (or omit it) to let the orchestrator pick a host matching the lane."
1902
+ }
1903
+ get parameters() {
1904
+ return {
1905
+ type: 'object',
1906
+ properties: {
1907
+ host: { type: 'string', description: "Target pod host's pod ID, or 'auto' to let the orchestrator pick one matching the lane (default: auto)" },
1908
+ name: { type: 'string', description: "Pod name, matching [A-Za-z0-9][A-Za-z0-9._-]{0,63}" },
1909
+ lane: { type: 'string', description: "Isolation lane: 'isolate'|'microvm'|'node'|'browser' (default inferred from run.kind: skill/module -> isolate, command/rootfs -> microvm)" },
1910
+ run: {
1911
+ type: 'object',
1912
+ description: 'What to run',
1913
+ properties: {
1914
+ kind: { type: 'string', description: "'skill'|'module'|'rootfs'|'command'" },
1915
+ ref: { type: 'string', description: 'Reference: skill name, module cid, rootfs image, or command path' },
1916
+ entry: { type: 'string', description: 'Entry point, if applicable' },
1917
+ input: { description: 'Input payload, if applicable' },
1918
+ },
1919
+ required: ['kind', 'ref'],
1920
+ },
1921
+ limits: { type: 'object', description: 'Resource limits: vcpus, memMib, timeoutMs, netRateLimiter, blockRateLimiter' },
1922
+ caps: { type: 'array', items: { type: 'string' }, description: 'KERNEL_CAP strings this pod is granted' },
1923
+ env: { type: 'object', description: 'Environment variables (string values)' },
1924
+ budget: { type: 'object', description: 'Budget: credits, currency' },
1925
+ restart: { type: 'object', description: 'Restart policy: policy (never|on-failure|always), maxRestarts, backoffMs' },
1926
+ },
1927
+ required: ['name', 'run'],
1928
+ }
1929
+ }
1930
+ get permission() { return 'network' }
1931
+
1932
+ async execute({ host, name, lane, run, limits, caps, env, budget, restart } = {}) {
1933
+ const validated = validatePodSpec(buildPodSpec({ name, lane, run, limits, caps, env, budget, restart }))
1934
+ if (!validated.ok) {
1935
+ return { success: false, output: '', error: `Invalid podspec: ${validated.errors.join('; ')}` }
1936
+ }
1937
+ const spec = validated.value
1938
+
1939
+ let targetHost = host && host !== 'auto' ? host : null
1940
+ let note = ''
1941
+ if (!targetHost) {
1942
+ const picked = await pickAutoHost(this.#orchestrator, spec.lane)
1943
+ if (!picked) {
1944
+ return { success: false, output: '', error: `No known pod host advertises lane '${spec.lane}' for auto selection` }
1945
+ }
1946
+ targetHost = picked.podId
1947
+ note = `orchestrator proposes host ${targetHost} for lane '${spec.lane}': ${picked.reason}\n`
1948
+ }
1949
+
1950
+ try {
1951
+ const result = await this.#orchestrator.spawnPod(targetHost, spec)
1952
+ return {
1953
+ success: true,
1954
+ output: `${note}spawned '${result.name}' on ${targetHost} (lane '${result.lane}'): state=${result.state}\n${JSON.stringify(result)}`,
1955
+ }
1956
+ } catch (err) {
1957
+ // "The orchestrator proposes, the host accepts": a refusal (EACCES or
1958
+ // otherwise) from the host we picked -- or the one the caller named
1959
+ // explicitly -- is reported as-is, never silently retried elsewhere.
1960
+ return { success: false, output: note, error: formatPodHostError(err, { host: targetHost, verb: 'spawn' }) }
1961
+ }
1962
+ }
1963
+ }
1964
+
1965
+ // ── meshctl_snapshot ──────────────────────────────────────────────────
1966
+
1967
+ export class MeshctlSnapshotTool extends BrowserTool {
1968
+ #orchestrator
1969
+
1970
+ constructor(orchestrator) {
1971
+ super()
1972
+ this.#orchestrator = orchestrator
1973
+ }
1974
+
1975
+ get name() { return 'meshctl_snapshot' }
1976
+ get description() { return 'Freeze a hosted pod to durable storage (microvm/node lanes only; isolate/browser answer ELANE)' }
1977
+ get parameters() {
1978
+ return {
1979
+ type: 'object',
1980
+ properties: {
1981
+ host: { type: 'string', description: 'Pod host pod ID' },
1982
+ name: { type: 'string', description: 'Hosted pod name' },
1983
+ },
1984
+ required: ['host', 'name'],
1985
+ }
1986
+ }
1987
+ get permission() { return 'network' }
1988
+
1989
+ async execute({ host, name } = {}) {
1990
+ try {
1991
+ const result = await this.#orchestrator.snapshotPod(host, name)
1992
+ return { success: true, output: `snapshotted '${name}' on ${host}: state=${result.state}\n${JSON.stringify(result)}` }
1993
+ } catch (err) {
1994
+ return { success: false, output: '', error: formatPodHostError(err, { host, verb: 'snapshot' }) }
1995
+ }
1996
+ }
1997
+ }
1998
+
1999
+ // ── meshctl_restore ───────────────────────────────────────────────────
2000
+
2001
+ export class MeshctlRestoreTool extends BrowserTool {
2002
+ #orchestrator
2003
+
2004
+ constructor(orchestrator) {
2005
+ super()
2006
+ this.#orchestrator = orchestrator
2007
+ }
2008
+
2009
+ get name() { return 'meshctl_restore' }
2010
+ get description() { return 'Thaw a snapshotted hosted pod (microvm/node lanes only; isolate/browser answer ELANE)' }
2011
+ get parameters() {
2012
+ return {
2013
+ type: 'object',
2014
+ properties: {
2015
+ host: { type: 'string', description: 'Pod host pod ID' },
2016
+ name: { type: 'string', description: 'Hosted pod name' },
2017
+ },
2018
+ required: ['host', 'name'],
2019
+ }
2020
+ }
2021
+ get permission() { return 'network' }
2022
+
2023
+ async execute({ host, name } = {}) {
2024
+ try {
2025
+ const result = await this.#orchestrator.restorePod(host, name)
2026
+ return { success: true, output: `restored '${name}' on ${host}: state=${result.state}\n${JSON.stringify(result)}` }
2027
+ } catch (err) {
2028
+ return { success: false, output: '', error: formatPodHostError(err, { host, verb: 'restore' }) }
2029
+ }
2030
+ }
2031
+ }
2032
+
2033
+ // ── meshctl_hosted_pods ───────────────────────────────────────────────
2034
+
2035
+ export class MeshctlHostedPodsTool extends BrowserTool {
2036
+ #orchestrator
2037
+
2038
+ constructor(orchestrator) {
2039
+ super()
2040
+ this.#orchestrator = orchestrator
2041
+ }
2042
+
2043
+ get name() { return 'meshctl_hosted_pods' }
2044
+ get description() { return 'List every pod a pod host is tracking (spawned, snapshotted, or drained tombstones)' }
2045
+ get parameters() {
2046
+ return {
2047
+ type: 'object',
2048
+ properties: {
2049
+ host: { type: 'string', description: 'Pod host pod ID' },
2050
+ },
2051
+ required: ['host'],
2052
+ }
2053
+ }
2054
+ get permission() { return 'read' }
2055
+
2056
+ async execute({ host } = {}) {
2057
+ try {
2058
+ const pods = await this.#orchestrator.listHostedPods(host)
2059
+ if (pods.length === 0) {
2060
+ return { success: true, output: `No hosted pods on ${host}.\n[]` }
2061
+ }
2062
+ const lines = pods.map((p) => `${p.name} | ${p.lane} | ${p.state} | execs:${p.execs ?? 0}`)
2063
+ return {
2064
+ success: true,
2065
+ output: `NAME | LANE | STATE | EXECS\n${lines.join('\n')}\n\n${JSON.stringify(pods)}`,
2066
+ }
2067
+ } catch (err) {
2068
+ return { success: false, output: '', error: formatPodHostError(err, { host, verb: 'list' }) }
2069
+ }
2070
+ }
2071
+ }
2072
+
2073
+ // ── meshctl_hosts ─────────────────────────────────────────────────────
2074
+
2075
+ export class MeshctlHostsTool extends BrowserTool {
2076
+ #orchestrator
2077
+
2078
+ constructor(orchestrator) {
2079
+ super()
2080
+ this.#orchestrator = orchestrator
2081
+ }
2082
+
2083
+ get name() { return 'meshctl_hosts' }
2084
+ get description() { return 'List known pod hosts with their lane, served verbs and runtime classes' }
2085
+ get parameters() {
2086
+ return { type: 'object', properties: {} }
2087
+ }
2088
+ get permission() { return 'read' }
2089
+
2090
+ async execute() {
2091
+ try {
2092
+ const hosts = await this.#orchestrator.listPodHosts()
2093
+ if (hosts.length === 0) {
2094
+ return { success: true, output: 'No pod hosts known.' }
2095
+ }
2096
+ const lines = hosts.map((h) => `${h.podId} | ${h.lane} | verbs: ${h.verbs.join(',')} | runtimeClasses: ${h.runtimeClasses.join(',')}`)
2097
+ return {
2098
+ success: true,
2099
+ output: `HOST | LANE | VERBS | RUNTIME CLASSES\n${lines.join('\n')}`,
2100
+ }
2101
+ } catch (err) {
2102
+ return { success: false, output: '', error: `Failed to list pod hosts: ${err.message}` }
2103
+ }
2104
+ }
2105
+ }
2106
+
2107
+ // ── meshctl_supervise ─────────────────────────────────────────────────
2108
+
2109
+ export class MeshctlSuperviseTool extends BrowserTool {
2110
+ #orchestrator
2111
+
2112
+ constructor(orchestrator) {
2113
+ super()
2114
+ this.#orchestrator = orchestrator
2115
+ }
2116
+
2117
+ get name() { return 'meshctl_supervise' }
2118
+ get description() {
2119
+ return "Spawn a hosted pod under supervision (issue #185 control surface item 6): links, monitors, " +
2120
+ "and restart policy on top of spawn/drain. Pass host: 'auto' (or omit it) to let the orchestrator " +
2121
+ "pick a host matching the lane. A restart is a NEW spawn request the host may refuse."
2122
+ }
2123
+ get parameters() {
2124
+ return {
2125
+ type: 'object',
2126
+ properties: {
2127
+ host: { type: 'string', description: "Target pod host's pod ID, or 'auto' to let the orchestrator pick one matching the lane (default: auto)" },
2128
+ name: { type: 'string', description: "Pod name, matching [A-Za-z0-9][A-Za-z0-9._-]{0,63}" },
2129
+ lane: { type: 'string', description: "Isolation lane: 'isolate'|'microvm'|'node'|'browser' (default inferred from run.kind)" },
2130
+ run: {
2131
+ type: 'object',
2132
+ description: 'What to run',
2133
+ properties: {
2134
+ kind: { type: 'string', description: "'skill'|'module'|'rootfs'|'command'" },
2135
+ ref: { type: 'string', description: 'Reference: skill name, module cid, rootfs image, or command path' },
2136
+ entry: { type: 'string', description: 'Entry point, if applicable' },
2137
+ input: { description: 'Input payload, if applicable' },
2138
+ },
2139
+ required: ['kind', 'ref'],
2140
+ },
2141
+ limits: { type: 'object', description: 'Resource limits: vcpus, memMib, timeoutMs, netRateLimiter, blockRateLimiter' },
2142
+ caps: { type: 'array', items: { type: 'string' }, description: 'KERNEL_CAP strings this pod is granted' },
2143
+ env: { type: 'object', description: 'Environment variables (string values)' },
2144
+ budget: { type: 'object', description: 'Budget: credits, currency' },
2145
+ restart: { type: 'object', description: 'Restart policy: policy (never|on-failure|always), maxRestarts, backoffMs (default: never)' },
2146
+ links: { type: 'object', description: 'links.parent (cascade on drain), links.hostedBy, links.detachOnParentExit' },
2147
+ },
2148
+ required: ['name', 'run'],
2149
+ }
2150
+ }
2151
+ get permission() { return 'network' }
2152
+
2153
+ async execute({ host, name, lane, run, limits, caps, env, budget, restart, links } = {}) {
2154
+ const spec = buildPodSpec({ name, lane, run, limits, caps, env, budget, restart, links })
2155
+ try {
2156
+ const supervisor = await this.#orchestrator.getSupervisor()
2157
+ const { ref, host: targetHost, status } = await supervisor.supervise(host || 'auto', spec)
2158
+ return {
2159
+ success: true,
2160
+ output: `supervising '${ref.name}' on ${targetHost} (lane '${status.lane}'): state=${status.state}\n${JSON.stringify(status)}`,
2161
+ }
2162
+ } catch (err) {
2163
+ return { success: false, output: '', error: formatPodHostError(err, { host: host || null, verb: 'spawn' }) }
2164
+ }
2165
+ }
2166
+ }
2167
+
2168
+ // ── meshctl_supervised ────────────────────────────────────────────────
2169
+
2170
+ export class MeshctlSupervisedTool extends BrowserTool {
2171
+ #orchestrator
2172
+
2173
+ constructor(orchestrator) {
2174
+ super()
2175
+ this.#orchestrator = orchestrator
2176
+ }
2177
+
2178
+ get name() { return 'meshctl_supervised' }
2179
+ get description() { return 'List every pod this orchestrator is supervising, with host, restart count and state' }
2180
+ get parameters() {
2181
+ return { type: 'object', properties: {} }
2182
+ }
2183
+ get permission() { return 'read' }
2184
+
2185
+ async execute() {
2186
+ try {
2187
+ const supervisor = await this.#orchestrator.getSupervisor()
2188
+ const entries = supervisor.list()
2189
+ if (entries.length === 0) {
2190
+ return { success: true, output: 'No supervised pods.\n[]' }
2191
+ }
2192
+ const lines = entries.map((p) => `${p.ref.name} | ${p.host} | ${p.state} | restarts:${p.restarts}`)
2193
+ return {
2194
+ success: true,
2195
+ output: `NAME | HOST | STATE | RESTARTS\n${lines.join('\n')}\n\n${JSON.stringify(entries)}`,
2196
+ }
2197
+ } catch (err) {
2198
+ return { success: false, output: '', error: `Failed to list supervised pods: ${err.message}` }
2199
+ }
2200
+ }
2201
+ }
2202
+
1451
2203
  // ---------------------------------------------------------------------------
1452
2204
  // Shell integration helper
1453
2205
  // ---------------------------------------------------------------------------
1454
2206
 
2207
+ /**
2208
+ * A tiny `--flag value` parser for `meshctl spawn`'s flag-style arguments
2209
+ * (`--lane`, `--kind`, `--ref`, `--entry`). Deliberately minimal rather than
2210
+ * a dependency: every recognized flag takes exactly one value, order does
2211
+ * not matter, and an unrecognized `--flag` is collected too (the caller
2212
+ * only reads the ones it needs).
2213
+ *
2214
+ * @param {string[]} args
2215
+ * @returns {Record<string, string>}
2216
+ */
2217
+ function parseMeshctlFlags(args) {
2218
+ /** @type {Record<string, string>} */
2219
+ const flags = {}
2220
+ for (let i = 0; i < args.length; i += 1) {
2221
+ const arg = args[i]
2222
+ if (arg.startsWith('--')) {
2223
+ flags[arg.slice(2)] = args[i + 1]
2224
+ i += 1
2225
+ }
2226
+ }
2227
+ return flags
2228
+ }
2229
+
1455
2230
  /**
1456
2231
  * Register 'meshctl' as a compound command in the shell registry.
1457
- * Subcommands: pods, status, exec, deploy, top, compute, expose, drain
2232
+ * Subcommands: pods, status, exec, deploy, top, compute, expose, drain,
2233
+ * spawn, snapshot, restore, hosted, hosts, supervise, supervised
1458
2234
  *
1459
2235
  * @param {import('./clawser-shell.js').CommandRegistry} shellRegistry
1460
2236
  * @param {MeshOrchestrator} orchestrator
@@ -1551,10 +2327,112 @@ export function registerMeshctlBuiltins(shellRegistry, orchestrator) {
1551
2327
  return { stdout: '', stderr: `Pod "${podId}" not found.\n`, exitCode: 1 }
1552
2328
  }
1553
2329
 
2330
+ case 'spawn': {
2331
+ const USAGE = 'Usage: meshctl spawn <host|auto> <name> --lane <lane> --kind <kind> --ref <ref> [--entry <entry>]\n'
2332
+ const [hostArg, nameArg, ...flagArgs] = rest
2333
+ if (!hostArg || !nameArg) return { stdout: '', stderr: USAGE, exitCode: 1 }
2334
+ const flags = parseMeshctlFlags(flagArgs)
2335
+ if (!flags.kind || !flags.ref) return { stdout: '', stderr: USAGE, exitCode: 1 }
2336
+ const run = { kind: flags.kind, ref: flags.ref }
2337
+ if (flags.entry) run.entry = flags.entry
2338
+ const spec = buildPodSpec({ name: nameArg, lane: flags.lane, run })
2339
+ const validated = validatePodSpec(spec)
2340
+ if (!validated.ok) return { stdout: '', stderr: `Invalid podspec: ${validated.errors.join('; ')}\n`, exitCode: 1 }
2341
+ try {
2342
+ let host = hostArg
2343
+ let note = ''
2344
+ if (hostArg === 'auto') {
2345
+ const picked = await pickAutoHost(orchestrator, validated.value.lane)
2346
+ if (!picked) return { stdout: '', stderr: `No known pod host advertises lane '${validated.value.lane}'\n`, exitCode: 1 }
2347
+ host = picked.podId
2348
+ note = `orchestrator proposes host ${host} for lane '${validated.value.lane}': ${picked.reason}\n`
2349
+ }
2350
+ const result = await orchestrator.spawnPod(host, validated.value)
2351
+ return { stdout: `${note}spawned '${result.name}' on ${host} (lane '${result.lane}'): state=${result.state}\n`, stderr: '', exitCode: 0 }
2352
+ } catch (err) {
2353
+ return { stdout: '', stderr: formatPodHostError(err, { host: hostArg === 'auto' ? null : hostArg, verb: 'spawn' }) + '\n', exitCode: 1 }
2354
+ }
2355
+ }
2356
+
2357
+ case 'snapshot': {
2358
+ const [host, name] = rest
2359
+ if (!host || !name) return { stdout: '', stderr: 'Usage: meshctl snapshot <host> <name>\n', exitCode: 1 }
2360
+ try {
2361
+ const result = await orchestrator.snapshotPod(host, name)
2362
+ return { stdout: `snapshotted '${name}' on ${host}: state=${result.state}\n`, stderr: '', exitCode: 0 }
2363
+ } catch (err) {
2364
+ return { stdout: '', stderr: formatPodHostError(err, { host, verb: 'snapshot' }) + '\n', exitCode: 1 }
2365
+ }
2366
+ }
2367
+
2368
+ case 'restore': {
2369
+ const [host, name] = rest
2370
+ if (!host || !name) return { stdout: '', stderr: 'Usage: meshctl restore <host> <name>\n', exitCode: 1 }
2371
+ try {
2372
+ const result = await orchestrator.restorePod(host, name)
2373
+ return { stdout: `restored '${name}' on ${host}: state=${result.state}\n`, stderr: '', exitCode: 0 }
2374
+ } catch (err) {
2375
+ return { stdout: '', stderr: formatPodHostError(err, { host, verb: 'restore' }) + '\n', exitCode: 1 }
2376
+ }
2377
+ }
2378
+
2379
+ case 'hosted': {
2380
+ const host = rest[0]
2381
+ if (!host) return { stdout: '', stderr: 'Usage: meshctl hosted <host>\n', exitCode: 1 }
2382
+ try {
2383
+ const pods = await orchestrator.listHostedPods(host)
2384
+ if (pods.length === 0) return { stdout: `No hosted pods on ${host}.\n`, stderr: '', exitCode: 0 }
2385
+ const lines = pods.map((p) => `${p.name}\t${p.lane}\t${p.state}`)
2386
+ return { stdout: lines.join('\n') + '\n', stderr: '', exitCode: 0 }
2387
+ } catch (err) {
2388
+ return { stdout: '', stderr: formatPodHostError(err, { host, verb: 'list' }) + '\n', exitCode: 1 }
2389
+ }
2390
+ }
2391
+
2392
+ case 'hosts': {
2393
+ const hosts = await orchestrator.listPodHosts()
2394
+ if (hosts.length === 0) return { stdout: 'No pod hosts known.\n', stderr: '', exitCode: 0 }
2395
+ const lines = hosts.map((h) => `${h.podId}\t${h.lane}\tverbs:${h.verbs.join(',')}`)
2396
+ return { stdout: lines.join('\n') + '\n', stderr: '', exitCode: 0 }
2397
+ }
2398
+
2399
+ case 'supervise': {
2400
+ const USAGE = 'Usage: meshctl supervise <host|auto> <name> --kind <kind> --ref <ref> '
2401
+ + '[--lane <lane>] [--entry <entry>] [--restart never|on-failure|always] [--parent <name>]\n'
2402
+ const [hostArg, nameArg, ...flagArgs] = rest
2403
+ if (!hostArg || !nameArg) return { stdout: '', stderr: USAGE, exitCode: 1 }
2404
+ const flags = parseMeshctlFlags(flagArgs)
2405
+ if (!flags.kind || !flags.ref) return { stdout: '', stderr: USAGE, exitCode: 1 }
2406
+ const run = { kind: flags.kind, ref: flags.ref }
2407
+ if (flags.entry) run.entry = flags.entry
2408
+ const restart = flags.restart ? { policy: flags.restart } : undefined
2409
+ const links = flags.parent ? { parent: flags.parent } : undefined
2410
+ const spec = buildPodSpec({ name: nameArg, lane: flags.lane, run, restart, links })
2411
+ try {
2412
+ const supervisor = await orchestrator.getSupervisor()
2413
+ const { ref, host, status } = await supervisor.supervise(hostArg, spec)
2414
+ return {
2415
+ stdout: `supervising '${ref.name}' on ${host} (lane '${status.lane}'): state=${status.state}\n`,
2416
+ stderr: '',
2417
+ exitCode: 0,
2418
+ }
2419
+ } catch (err) {
2420
+ return { stdout: '', stderr: formatPodHostError(err, { host: hostArg === 'auto' ? null : hostArg, verb: 'spawn' }) + '\n', exitCode: 1 }
2421
+ }
2422
+ }
2423
+
2424
+ case 'supervised': {
2425
+ const supervisor = await orchestrator.getSupervisor()
2426
+ const entries = supervisor.list()
2427
+ if (entries.length === 0) return { stdout: 'No supervised pods.\n', stderr: '', exitCode: 0 }
2428
+ const lines = entries.map((p) => `${p.ref.name}\t${p.host}\t${p.state}\trestarts:${p.restarts}`)
2429
+ return { stdout: lines.join('\n') + '\n', stderr: '', exitCode: 0 }
2430
+ }
2431
+
1554
2432
  default:
1555
2433
  return {
1556
2434
  stdout: '',
1557
- stderr: `Unknown subcommand: ${subcommand || '(none)'}. Available: pods, status, exec, deploy, top, compute, expose, drain\n`,
2435
+ stderr: `Unknown subcommand: ${subcommand || '(none)'}. Available: pods, status, exec, deploy, top, compute, expose, drain, spawn, snapshot, restore, hosted, hosts, supervise, supervised\n`,
1558
2436
  exitCode: 1,
1559
2437
  }
1560
2438
  }
@@ -1570,7 +2448,11 @@ export function registerMeshctlBuiltins(shellRegistry, orchestrator) {
1570
2448
  // ---------------------------------------------------------------------------
1571
2449
 
1572
2450
  /**
1573
- * Create all meshctl BrowserTool instances for a given orchestrator.
2451
+ * Create all meshctl BrowserTool instances for a given orchestrator -- the
2452
+ * original 8 (`pods`/`status`/`exec`/`deploy`/`top`/`compute`/`expose`/
2453
+ * `drain`) plus the 5 hosted-pods control surface tools (issue #185 §8a
2454
+ * item 4): `spawn`/`snapshot`/`restore`/`hosted_pods`/`hosts`, plus item 6's
2455
+ * 2 supervisor tools: `supervise`/`supervised`. 15 total.
1574
2456
  * @param {MeshOrchestrator} orchestrator
1575
2457
  * @returns {BrowserTool[]}
1576
2458
  */
@@ -1584,5 +2466,12 @@ export function createMeshctlTools(orchestrator) {
1584
2466
  new MeshctlComputeTool(orchestrator),
1585
2467
  new MeshctlExposeTool(orchestrator),
1586
2468
  new MeshctlDrainTool(orchestrator),
2469
+ new MeshctlSpawnTool(orchestrator),
2470
+ new MeshctlSnapshotTool(orchestrator),
2471
+ new MeshctlRestoreTool(orchestrator),
2472
+ new MeshctlHostedPodsTool(orchestrator),
2473
+ new MeshctlHostsTool(orchestrator),
2474
+ new MeshctlSuperviseTool(orchestrator),
2475
+ new MeshctlSupervisedTool(orchestrator),
1587
2476
  ]
1588
2477
  }