@johnhenry/browsermesh-apps 0.1.1 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (50) hide show
  1. package/README.md +443 -1
  2. package/package.json +18 -3
  3. package/src/agent-runtime.mjs +342 -0
  4. package/src/chunk-replication.mjs +751 -0
  5. package/src/cloud-storage-backend.mjs +932 -0
  6. package/src/cloud-storage.mjs +799 -0
  7. package/src/compat.mjs +98 -0
  8. package/src/gpu-kernel.mjs +242 -0
  9. package/src/gpu.mjs +101 -7
  10. package/src/grant-log.mjs +840 -0
  11. package/src/index.mjs +32 -2
  12. package/src/kernel-mesh.mjs +56 -0
  13. package/src/key-distribution.mjs +525 -0
  14. package/src/manifest-sync.mjs +363 -0
  15. package/src/mesh-agent-swarm.mjs +376 -0
  16. package/src/mesh-bootstrap.mjs +1481 -0
  17. package/src/mesh-compute.mjs +397 -0
  18. package/src/mesh-dht.mjs +182 -0
  19. package/src/mesh-fetch.mjs +246 -0
  20. package/src/mesh-hardening.mjs +226 -0
  21. package/src/mesh-health.mjs +282 -0
  22. package/src/mesh-keepalive.mjs +353 -0
  23. package/src/mesh-kv.mjs +673 -0
  24. package/src/mesh-orchestrator-tools.mjs +251 -0
  25. package/src/mesh-orchestrator.mjs +343 -0
  26. package/src/mesh-relay-backend.mjs +289 -0
  27. package/src/mesh-relay-host.mjs +362 -0
  28. package/src/mesh-rpc.mjs +300 -0
  29. package/src/mesh-service.mjs +403 -0
  30. package/src/mesh-swarm.mjs +677 -0
  31. package/src/mesh-sync.mjs +253 -0
  32. package/src/mesh-timestamp.mjs +265 -0
  33. package/src/mesh-torrent.mjs +683 -0
  34. package/src/mesh-verification.mjs +367 -0
  35. package/src/mesh-websocket.mjs +722 -0
  36. package/src/observability-bridge.mjs +453 -0
  37. package/src/orchestrator.mjs +18 -5
  38. package/src/peer-agent-swarm.mjs +12 -1
  39. package/src/peer-chat.mjs +230 -61
  40. package/src/peer-compute.mjs +66 -3
  41. package/src/peer-escrow.mjs +350 -1
  42. package/src/peer-files.mjs +362 -168
  43. package/src/peer-ipfs.mjs +205 -10
  44. package/src/peer-node.mjs +127 -19
  45. package/src/peer-registry.mjs +242 -18
  46. package/src/peer-routing.mjs +369 -5
  47. package/src/peer-terminal.mjs +400 -130
  48. package/src/signaling.mjs +231 -0
  49. package/src/webrtc-negotiator.mjs +209 -0
  50. package/src/peer-session.mjs +0 -937
@@ -0,0 +1,251 @@
1
+ /**
2
+ * mesh-orchestrator-tools.mjs -- Phase 4 of the agent-runtime plan (issues
3
+ * #90/#92): registers `orchestrator.mjs`'s 8 real `Meshctl*Tool` classes
4
+ * (`MeshctlPodsTool`/`MeshctlStatusTool`/`MeshctlExecTool`/`MeshctlDeployTool`/
5
+ * `MeshctlTopTool`/`MeshctlComputeTool`/`MeshctlExposeTool`/`MeshctlDrainTool`,
6
+ * built via that file's own `createMeshctlTools(orchestrator)` helper) into a
7
+ * `compat.mjs` `BrowserToolRegistry` (Phase 1), wired against a real, attached
8
+ * `MeshOrchestrator` (Phase 3, `mesh-orchestrator.mjs`'s `createOrchestratorService()`).
9
+ * Once registered, `agent-runtime.mjs`'s `createAgentRuntime({registry, llmFn})`
10
+ * (Phase 2) can dispatch LLM-requested `meshctl_*` tool calls straight through
11
+ * to a real mesh -- this is the file that finally connects all three prior
12
+ * phases end to end.
13
+ *
14
+ * This is a standalone composition-root helper, the same category as
15
+ * `agent-runtime.mjs` itself -- not a `MeshService`, no `attach()`/`ctx`. A
16
+ * caller who already has both a `BrowserToolRegistry` and an attached
17
+ * orchestrator (e.g. `node.orchestrator.api` from `createMeshNode({
18
+ * enableOrchestrator: true })`) calls `registerOrchestratorTools(registry,
19
+ * node.orchestrator.api)` directly; `createMeshNode({ enableAgentRuntime: true,
20
+ * enableOrchestrator: true })` also wires this internally (see
21
+ * `mesh-bootstrap.mjs`'s own doc comment for that opt-in's exact shape and its
22
+ * `enableAgentRuntime`-without-`enableOrchestrator` decision).
23
+ *
24
+ * ---------------------------------------------------------------------------
25
+ * TWO ACCEPTED SHAPES FOR THE `orchestrator` ARGUMENT -- AND WHY THAT MATTERS
26
+ * FOR `meshctl_exec`/`meshctl_deploy`/`meshctl_drain`'S AUTHORIZATION
27
+ *
28
+ * `Meshctl*Tool`'s real constructor (`orchestrator.mjs`) is `constructor(orchestrator)`,
29
+ * storing whatever is passed in a private field and calling plain methods on
30
+ * it (`this.#orchestrator.execOnPod(...)`, `.listPods(...)`, etc.) -- it never
31
+ * checks `instanceof MeshOrchestrator`, so any object exposing the right method
32
+ * names works. This file accepts EITHER:
33
+ *
34
+ * 1. The mesh-orchestrator.mjs SERVICE's own `api` (e.g. `node.orchestrator.api`,
35
+ * or `createOrchestratorService().attach(peerNode, ctx).api` directly) --
36
+ * detected by the presence of `.orchestrator` (the raw instance) alongside
37
+ * `execOnPod`/`deploySkill`/`drainPod`/`listPods`/`getPodStatus`/`topPods`.
38
+ * **This is the recommended, and expected, shape** -- see "GATING" below.
39
+ * 2. A raw `MeshOrchestrator` instance directly (e.g. `node.orchestrator.api.orchestrator`,
40
+ * or a hand-constructed `new MeshOrchestrator({...})` never wrapped by
41
+ * `createOrchestratorService()` at all) -- detected by the presence of
42
+ * `execOnPod`/`deploySkill`/`drainPod`/`listPods`/`getPodStatus`/`topPods`/
43
+ * `runComputeTask`/`exposePod` all directly on the object itself (no
44
+ * `.orchestrator` wrapper).
45
+ *
46
+ * GATING -- why shape (1) is preferred, and what changes if shape (2) is used
47
+ * instead:
48
+ *
49
+ * `mesh-orchestrator.mjs`'s own doc comment (Phase 3) already flagged this
50
+ * exactly: "A future phase wiring Meshctl*Tool into an LLM-drivable registry
51
+ * should prefer this service's own gated api.execOnPod/api.deploySkill/
52
+ * api.drainPod (...) for any tool surface an untrusted remote actor could
53
+ * ultimately trigger; api.orchestrator itself does not re-add the gate
54
+ * MeshOrchestrator's own methods never had." Concretely: `MeshOrchestrator
55
+ * .execOnPod()`/`.deploySkill()`/`.drainPod()` (the RAW methods) only ever
56
+ * reach a remote pod via a callback pre-registered through the raw instance's
57
+ * own `addPeer()` (or `remoteSessionBroker`/`runtimeRegistry`, neither wired
58
+ * by this plan -- see mesh-orchestrator.mjs's header) -- if such a callback IS
59
+ * registered, calling the raw method invokes it directly, in-process, with NO
60
+ * authorization check at all (`checkAccess()` only guards the WIRE protocol's
61
+ * inbound handler, which the raw path never goes through). The service's
62
+ * `api.execOnPod`/`api.deploySkill`/`api.drainPod`, by contrast, always
63
+ * dispatch a real `'orchestrator-request'` over the wire to the target peer
64
+ * (unless the target is this node itself, a documented no-network shortcut)
65
+ * and that peer's own `checkAccess(fromPubKey, 'orchestrator', action)` gate
66
+ * decides whether to honor it -- the actual, real authorization path this
67
+ * whole plan's "risky, peer-initiated action" design exists for.
68
+ *
69
+ * So: when shape (1) (the service `api`) is supplied, this file wires
70
+ * `meshctl_exec`/`meshctl_deploy`/`meshctl_drain` through `api.execOnPod`/
71
+ * `api.deploySkill`/`api.drainPod` specifically (real wire dispatch + the
72
+ * target's real `checkAccess()` gate for a remote target; a genuine no-network
73
+ * shortcut for a self-targeted call) -- NOT through `api.orchestrator`'s raw
74
+ * methods, even though the raw instance is reachable and would otherwise be
75
+ * the more literal reading of "construct `Meshctl*Tool` against the raw
76
+ * instance." `meshctl_pods`/`meshctl_status`/`meshctl_top` (local-only
77
+ * aggregation, never gated even at the service layer -- see
78
+ * mesh-orchestrator.mjs's own "AUTHORIZATION" section) and `meshctl_compute`/
79
+ * `meshctl_expose` (see next section) still go straight to the raw instance,
80
+ * since the service exposes no gated equivalent for any of those five.
81
+ *
82
+ * When shape (2) (a raw orchestrator, no service) is supplied instead, ALL
83
+ * eight tools run straight off the raw instance with no gate whatsoever --
84
+ * this file does not invent authorization that has no wire protocol to
85
+ * enforce it. This is a legitimate, intentional shape for a single
86
+ * trusted-local-operator use case (no mesh service attached at all, e.g. a
87
+ * standalone `MeshOrchestrator` driving only this node's own pod), just not
88
+ * the one a caller wiring both `enableOrchestrator` and `enableAgentRuntime`
89
+ * through `createMeshNode()` gets -- that path always supplies shape (1).
90
+ *
91
+ * ---------------------------------------------------------------------------
92
+ * `meshctl_compute`/`meshctl_expose` -- NOT WIRED BY PHASE 3 AT ALL, NOTED
93
+ * HERE RATHER THAN SILENTLY WORKED AROUND
94
+ *
95
+ * `MeshctlComputeTool`/`MeshctlExposeTool` call `orchestrator.runComputeTask()`/
96
+ * `orchestrator.exposePod()` -- both are real, implemented methods on
97
+ * `MeshOrchestrator` (confirmed directly in `orchestrator.mjs`: `runComputeTask()`
98
+ * resolves a target via `ResourceScorer`/`#resourceRegistry`/`#knownPeers` and
99
+ * either runs locally (`peerNode.exec()`) or through whatever peer callback is
100
+ * registered; `exposePod()` is a purely local bookkeeping call recording an
101
+ * exposed-service address, optionally announced via `serviceAdvertiser` if one
102
+ * were ever wired). Neither one, however, is part of `mesh-orchestrator.mjs`'s
103
+ * own wire protocol -- Phase 3's `RISKY_ACTIONS` is exactly `['exec', 'deploy',
104
+ * 'drain']` (`mesh-orchestrator.mjs`), so there is no `api.runComputeTask`/
105
+ * `api.exposePod` gated equivalent to prefer the way there is for exec/deploy/
106
+ * drain. Both tools are therefore ALWAYS wired straight to the raw instance's
107
+ * own methods here, regardless of which of the two input shapes above is
108
+ * supplied -- they run local-only, ungated, exactly like `meshctl_pods`/
109
+ * `meshctl_status`/`meshctl_top` already do at the service layer. A future
110
+ * phase wanting a real gated/remote-dispatchable `meshctl_compute`/
111
+ * `meshctl_expose` would need to extend `mesh-orchestrator.mjs`'s own wire
112
+ * protocol first (out of scope here, exactly per this plan's Phase 4 section).
113
+ *
114
+ * ---------------------------------------------------------------------------
115
+ * No browser-only imports at module level.
116
+ */
117
+
118
+ import { BrowserToolRegistry } from './compat.mjs'
119
+ import { createMeshctlTools } from './orchestrator.mjs'
120
+
121
+ /**
122
+ * @param {unknown} x
123
+ * @returns {boolean} true if `x` looks like `mesh-orchestrator.mjs`'s
124
+ * service `api` -- see module doc comment's "TWO ACCEPTED SHAPES" section.
125
+ */
126
+ function looksLikeOrchestratorServiceApi(x) {
127
+ return !!x
128
+ && x.orchestrator && typeof x.orchestrator === 'object'
129
+ && typeof x.execOnPod === 'function'
130
+ && typeof x.deploySkill === 'function'
131
+ && typeof x.drainPod === 'function'
132
+ && typeof x.listPods === 'function'
133
+ && typeof x.getPodStatus === 'function'
134
+ && typeof x.topPods === 'function'
135
+ }
136
+
137
+ /**
138
+ * @param {unknown} x
139
+ * @returns {boolean} true if `x` looks like a raw `MeshOrchestrator` instance
140
+ * itself -- see module doc comment's "TWO ACCEPTED SHAPES" section.
141
+ */
142
+ function looksLikeRawOrchestrator(x) {
143
+ return !!x
144
+ && typeof x.execOnPod === 'function'
145
+ && typeof x.deploySkill === 'function'
146
+ && typeof x.drainPod === 'function'
147
+ && typeof x.listPods === 'function'
148
+ && typeof x.getPodStatus === 'function'
149
+ && typeof x.topPods === 'function'
150
+ && typeof x.runComputeTask === 'function'
151
+ && typeof x.exposePod === 'function'
152
+ }
153
+
154
+ /**
155
+ * Build the object actually handed to `createMeshctlTools()` -- see module
156
+ * doc comment's "GATING" section for exactly which methods route through the
157
+ * service's gated wire dispatch vs. straight to the raw instance, and why.
158
+ * @param {object} orchestrator - Either shape from the module doc comment.
159
+ * @returns {object} duck-typed stand-in for a raw `MeshOrchestrator`
160
+ */
161
+ function buildToolFacade(orchestrator) {
162
+ if (looksLikeOrchestratorServiceApi(orchestrator)) {
163
+ const raw = orchestrator.orchestrator
164
+ return {
165
+ // meshctl_exec/meshctl_deploy/meshctl_drain -- real wire dispatch +
166
+ // the target's real checkAccess() gate for a remote target (a genuine
167
+ // no-network shortcut for a self-targeted call). See "GATING" above.
168
+ execOnPod: (...args) => orchestrator.execOnPod(...args),
169
+ deploySkill: (...args) => orchestrator.deploySkill(...args),
170
+ drainPod: (...args) => orchestrator.drainPod(...args),
171
+ // meshctl_pods/meshctl_status/meshctl_top -- local-only aggregation,
172
+ // never gated even at the service layer -- straight to the raw
173
+ // instance, identical to what api.listPods()/etc. already do.
174
+ listPods: (...args) => raw.listPods(...args),
175
+ getPodStatus: (...args) => raw.getPodStatus(...args),
176
+ topPods: (...args) => raw.topPods(...args),
177
+ // meshctl_compute/meshctl_expose -- no gated equivalent exists at the
178
+ // service layer at all (see module doc comment). Straight to the raw
179
+ // instance either way.
180
+ runComputeTask: (...args) => raw.runComputeTask(...args),
181
+ exposePod: (...args) => raw.exposePod(...args),
182
+ // MeshctlExposeTool reads `this.#orchestrator.peerNode` directly for
183
+ // its own default-podId fallback.
184
+ get peerNode() { return raw.peerNode },
185
+ }
186
+ }
187
+ if (looksLikeRawOrchestrator(orchestrator)) {
188
+ // No wrapping service supplied -- every action, including exec/deploy/
189
+ // drain, runs straight off the raw instance with no gate. See module doc
190
+ // comment's "GATING" section for exactly what that means.
191
+ return orchestrator
192
+ }
193
+ throw new TypeError(
194
+ 'registerOrchestratorTools: orchestrator must be either the mesh-orchestrator.mjs ' +
195
+ 'service\'s own `api` (e.g. node.orchestrator.api -- has `.orchestrator` plus ' +
196
+ 'execOnPod/deploySkill/drainPod/listPods/getPodStatus/topPods) or a raw MeshOrchestrator ' +
197
+ 'instance (orchestrator.mjs, has all eight of those methods directly) -- got ' +
198
+ (orchestrator && orchestrator.constructor ? orchestrator.constructor.name : String(orchestrator))
199
+ )
200
+ }
201
+
202
+ /**
203
+ * Construct all 8 `Meshctl*Tool` instances (`orchestrator.mjs`'s own
204
+ * `createMeshctlTools()`) against `orchestrator` and register each into
205
+ * `registry`. See module doc comment for the full design writeup (the two
206
+ * accepted `orchestrator` shapes, the exec/deploy/drain gating decision, and
207
+ * the compute/expose "not wired by Phase 3 at all" note).
208
+ *
209
+ * @param {import('./compat.mjs').BrowserToolRegistry} registry - REQUIRED.
210
+ * Duck-typed (`.register` a function), matching this package's established
211
+ * "duck-type collaborators, don't require exact class identity" convention
212
+ * (see `agent-runtime.mjs`'s own `looksLikeRegistry()`).
213
+ * @param {object} orchestrator - REQUIRED. Either `mesh-orchestrator.mjs`'s
214
+ * service `api` (recommended -- e.g. `node.orchestrator.api`) or a raw
215
+ * `MeshOrchestrator` instance -- see module doc comment.
216
+ * @returns {import('./orchestrator.mjs').BrowserTool[]} the 8 registered tool
217
+ * instances, in `createMeshctlTools()`'s own order (pods, status, exec,
218
+ * deploy, top, compute, expose, drain).
219
+ */
220
+ export function registerOrchestratorTools(registry, orchestrator) {
221
+ if (!registry || typeof registry.register !== 'function') {
222
+ throw new TypeError(
223
+ 'registerOrchestratorTools: registry is required (a BrowserToolRegistry-shaped object ' +
224
+ 'implementing register(tool) -- see compat.mjs\'s BrowserToolRegistry) -- got ' +
225
+ (registry && registry.constructor ? registry.constructor.name : String(registry))
226
+ )
227
+ }
228
+ const facade = buildToolFacade(orchestrator)
229
+ const tools = createMeshctlTools(facade)
230
+ for (const tool of tools) {
231
+ registry.register(tool)
232
+ }
233
+ return tools
234
+ }
235
+
236
+ /**
237
+ * Convenience factory: build a brand-new `BrowserToolRegistry` and
238
+ * pre-populate it with all 8 `Meshctl*Tool`s via `registerOrchestratorTools()`.
239
+ * Equivalent to `registerOrchestratorTools(new BrowserToolRegistry(), orchestrator)`,
240
+ * for a caller who doesn't already have a registry of their own to reuse (see
241
+ * `registerOrchestratorTools()` directly if you do -- e.g. to add
242
+ * non-orchestrator tools into the same registry alongside these 8).
243
+ *
244
+ * @param {object} orchestrator - See `registerOrchestratorTools()`.
245
+ * @returns {import('./compat.mjs').BrowserToolRegistry}
246
+ */
247
+ export function createOrchestratorToolRegistry(orchestrator) {
248
+ const registry = new BrowserToolRegistry()
249
+ registerOrchestratorTools(registry, orchestrator)
250
+ return registry
251
+ }
@@ -0,0 +1,343 @@
1
+ /**
2
+ * mesh-orchestrator.mjs -- Phase 3 of the agent-runtime plan (issue #92):
3
+ * wraps `orchestrator.mjs`'s `MeshOrchestrator` as a `MeshService`
4
+ * (`mesh-service.mjs`, Phase C's `attach()`/`ctx` convention), mirroring
5
+ * `mesh-compute.mjs`/`mesh-verification.mjs`/`mesh-agent-swarm.mjs`/
6
+ * `mesh-swarm.mjs`'s own established structure for "wrap a real, dormant
7
+ * class with a real request/response wire protocol and a `checkAccess()`
8
+ * gate for the peer-initiated actions."
9
+ *
10
+ * ---------------------------------------------------------------------------
11
+ * WHAT `MeshOrchestrator` ITSELF DOES AND DOES NOT DO (read directly off
12
+ * `orchestrator.mjs`):
13
+ *
14
+ * `MeshOrchestrator` requires `peerNode` and optionally accepts
15
+ * `serviceAdvertiser`/`serviceBrowser` (both confirmed still unwired
16
+ * anywhere in this repo -- `ServiceAdvertiser`/`ServiceBrowser` from
17
+ * `peer-services.mjs` are never constructed by real code -- left `null`
18
+ * here per this phase's plan; reviving `peer-services.mjs` stays a
19
+ * separate, smaller follow-up), `router`, `runtimeRegistry`,
20
+ * `remoteSessionBroker`, `resourceRegistry`, `auditRecorder`,
21
+ * `peerRegistry` -- all default `null`. `listPods()`/`getPodStatus()`/
22
+ * `topPods()` are pure LOCAL aggregation over this node's own
23
+ * `peerNode`/known-peers/`runtimeRegistry` state -- no network round-trip,
24
+ * no peer-initiated authorization concern, so this file exposes them on
25
+ * `api` as thin, ungated passthroughs.
26
+ *
27
+ * `execOnPod()`/`deploySkill()`/`drainPod()` are different: each already
28
+ * has its OWN internal local-vs-remote branch (local when `podId ===
29
+ * peerNode.podId`; otherwise via `#remoteSessionBroker`/`runtimeRegistry`
30
+ * if wired, or a registered `#knownPeers` entry's own `exec`/`send`/
31
+ * `drain`/`deploySkill` callback). Without `remoteSessionBroker` wired
32
+ * (not part of this phase's scope -- see module doc comment above) and
33
+ * with no peer pre-registered via `orchestrator.addPeer()`, calling any of
34
+ * these three against a REAL remote pod that this node has no other
35
+ * channel to would simply throw/fail locally with no network traffic ever
36
+ * sent. That is exactly the gap this file closes: a real request/response
37
+ * wire protocol, modeled directly on `mesh-compute.mjs`'s single-target
38
+ * dispatch shape (an orchestrator action always targets exactly one named
39
+ * pod, never a broadcast or a pool-selection the way `mesh-compute.mjs`'s
40
+ * own `ResourceScorer`-driven `runComputeTask()` does), so `api.execOnPod`/
41
+ * `api.deploySkill`/`api.drainPod` here dispatch a real `ctx.sendTo()`
42
+ * request to the target pod's peer and await a matching response when the
43
+ * target isn't this node itself, and call straight through to the local
44
+ * `MeshOrchestrator` method (no network hop) when it is.
45
+ *
46
+ * ---------------------------------------------------------------------------
47
+ * ROUTER WIRING -- `MeshOrchestrator` calls exactly one method on its
48
+ * injected `router`: `routeService()` calls `this.#router.addRoute(targetPodId,
49
+ * targetPodId, 1)` (guarded by `this.#router && this.#router.addRoute`).
50
+ * `peer-routing.mjs`'s `createMeshRoutingService()` returns an `api` with
51
+ * `addRoute(targetPodId, nextHop, hops, ttl)` -- same arity, same meaning
52
+ * (target, next hop, hop count, optional TTL override) -- so `node.router?.api`
53
+ * (the `attachService()` handle's `.api` field) IS shape-compatible and is
54
+ * wired straight through as `router` below when a caller supplies it (e.g.
55
+ * `mesh-bootstrap.mjs`'s `enableOrchestrator` passing `node.router?.api`
56
+ * when `enableRouting` was also set). No other method is ever called on
57
+ * `router`, so nothing else about `MeshRouter`'s real API needed checking.
58
+ *
59
+ * ---------------------------------------------------------------------------
60
+ * SWARM/LEADER-ELECTION -- `mesh-swarm.mjs` (`SwarmCoordinator`/
61
+ * `LeaderElection`/`TaskDistributor`) has no reference to `MeshOrchestrator`
62
+ * anywhere, and `MeshOrchestrator` has no reference to swarm/leader-election
63
+ * concepts anywhere either (confirmed by reading both files in full) --
64
+ * this remains true after this phase. Pod orchestration (which pod runs
65
+ * what) and swarm task distribution (which peer runs which sub-task of a
66
+ * decomposed goal) are separate concerns this repo has never connected; no
67
+ * connection is forced here.
68
+ *
69
+ * ---------------------------------------------------------------------------
70
+ * AUTHORIZATION -- `execOnPod`/`deploySkill`/`drainPod` are the genuinely
71
+ * PEER-INITIATED, RISKY actions (arbitrary remote command execution,
72
+ * arbitrary content deployed to this node's filesystem-adjacent skill
73
+ * store, and forcibly disconnecting/migrating this node's own workload,
74
+ * respectively) -- exactly `orchestrator.mjs`'s own header comment's
75
+ * "eight `meshctl`-CLI-shaped agent tools", the three whose `BrowserTool`
76
+ * subclasses (`MeshctlExecTool`/`MeshctlDeployTool`/`MeshctlDrainTool`)
77
+ * already declare `get permission() { return 'network' }` (vs. `'read'` for
78
+ * the pods/status/top query tools). Before honoring an inbound
79
+ * `'orchestrator-request'` for any of the three, this node gates it via
80
+ * `ctx.registry.checkAccess(fromPubKey, accessResource, action)` (action is
81
+ * one of `'exec'`/`'deploy'`/`'drain'`), exactly the `registry.checkAccess()`
82
+ * gate `mesh-compute.mjs`/`mesh-verification.mjs`/`mesh-agent-swarm.mjs`/
83
+ * `mesh-swarm.mjs` already established for "a peer wants this node to do
84
+ * something on its behalf." A denied request gets an explicit
85
+ * `{error: 'access denied'}` response (not a silent drop) -- the REQUESTING
86
+ * side's dispatch Promise is already open and waiting, so a silent drop
87
+ * would just make an unauthorized peer indistinguishable from a slow or
88
+ * dead one (same reasoning as `mesh-compute.mjs`'s own "WHY AN EXPLICIT
89
+ * DENIAL RESPONSE" section).
90
+ *
91
+ * `listPods`/`getPodStatus`/`topPods` are NOT gated and have no wire
92
+ * protocol at all here -- they are local-only queries over this node's own
93
+ * knowledge, with no peer-initiated request path this file introduces (a
94
+ * caller wanting a REMOTE pod's live status would need its own mechanism;
95
+ * nothing in `orchestrator.mjs` today asks a remote peer to answer a status
96
+ * query on this node's behalf).
97
+ *
98
+ * ---------------------------------------------------------------------------
99
+ * `api.orchestrator` -- the raw, unwrapped `MeshOrchestrator` instance is
100
+ * also exposed directly on `api` (not just the gated wire-protocol
101
+ * wrappers), so a later phase (registering the 8 `Meshctl*Tool` classes
102
+ * into a `BrowserToolRegistry`) can construct them directly against it --
103
+ * `Meshctl*Tool`'s real constructor is `constructor(orchestrator) { ... }`,
104
+ * expecting a raw `MeshOrchestrator`, not a wrapped service. Anything
105
+ * reached via `api.orchestrator` directly (as opposed to `api.execOnPod`/
106
+ * `api.deploySkill`/`api.drainPod`) runs `MeshOrchestrator`'s own
107
+ * un-gated, local-only logic -- exactly like `api.orchestrator.listPods()`
108
+ * already is unconditionally. A future phase wiring `Meshctl*Tool`s into an
109
+ * LLM-drivable registry should prefer this service's own gated
110
+ * `api.execOnPod`/`api.deploySkill`/`api.drainPod` (or reconstruct
111
+ * equivalent gating) for any tool surface an untrusted remote actor could
112
+ * ultimately trigger; `api.orchestrator` itself does not re-add the gate
113
+ * `MeshOrchestrator`'s own methods never had.
114
+ *
115
+ * ---------------------------------------------------------------------------
116
+ * Observability events (`ctx.emit()`, see `mesh-service.mjs`'s module doc
117
+ * comment for the full convention):
118
+ *
119
+ * - `orchestrator:request-denied` `{from, requestId, action, reason}` --
120
+ * an inbound `'orchestrator-request'` was rejected before the
121
+ * underlying `MeshOrchestrator` method ever ran (`reason`:
122
+ * `'access_denied'` or `'unsupported_action'`).
123
+ * - `orchestrator:request-served` `{from, requestId, action, ok}` -- this
124
+ * node, as the TARGET pod, answered an authorized request (`ok: true`
125
+ * if the underlying `MeshOrchestrator` method resolved, `false` if it
126
+ * threw).
127
+ *
128
+ * No browser-only imports at module level.
129
+ */
130
+
131
+ import { MeshOrchestrator } from './orchestrator.mjs'
132
+
133
+ /** Shared envelope `type` for both orchestrator request/response directions (tagged by `kind`), mirroring `mesh-compute.mjs`'s `'mesh-compute'` shape. */
134
+ const DEFAULT_ORCHESTRATOR_ENVELOPE_TYPE = 'mesh-orchestrator'
135
+
136
+ /** How long `api.execOnPod`/`api.deploySkill`/`api.drainPod` wait for a matching `'orchestrator-response'` before giving up, for a REMOTE target. Mirrors `mesh-compute.mjs`'s own default dispatch timeout. */
137
+ const DEFAULT_ORCHESTRATOR_DISPATCH_TIMEOUT_MS = 30000
138
+
139
+ /** Default `resource` passed to `ctx.registry.checkAccess(fromPubKey, resource, action)` for all three gated actions (`action` is `'exec'`/`'deploy'`/`'drain'`). */
140
+ const DEFAULT_ACCESS_RESOURCE = 'orchestrator'
141
+
142
+ /** The only actions an inbound `'orchestrator-request'` may name -- see module doc comment's "AUTHORIZATION" section for why these three (and only these three) are gated/wire-dispatched at all. */
143
+ const RISKY_ACTIONS = Object.freeze(['exec', 'deploy', 'drain'])
144
+
145
+ /**
146
+ * Build a `MeshService` descriptor (`mesh-service.mjs`, Phase C) wrapping
147
+ * `MeshOrchestrator`. See this file's module doc comment for the full
148
+ * design writeup (what's local-only vs. peer-initiated/gated, the router
149
+ * shape-compatibility finding, the swarm non-relationship finding).
150
+ *
151
+ * @param {object} [opts]
152
+ * @param {object} [opts.router] - Passed straight through to
153
+ * `MeshOrchestrator`'s own `router` constructor option. Compatible shape:
154
+ * `peer-routing.mjs`'s `createMeshRoutingService()` `api` (has
155
+ * `addRoute(targetPodId, nextHop, hops, ttl)`, the only method
156
+ * `MeshOrchestrator` ever calls on it) -- see module doc comment's
157
+ * "ROUTER WIRING" section.
158
+ * @param {object} [opts.runtimeRegistry] - Passed straight through.
159
+ * @param {object} [opts.remoteSessionBroker] - Passed straight through.
160
+ * @param {object} [opts.resourceRegistry] - Passed straight through.
161
+ * @param {object} [opts.auditRecorder] - Passed straight through.
162
+ * @param {number} [opts.dispatchTimeoutMs=30000] - How long
163
+ * `api.execOnPod`/`api.deploySkill`/`api.drainPod` wait for a
164
+ * `'orchestrator-response'` when the target isn't this node itself.
165
+ * @param {string} [opts.envelopeType='mesh-orchestrator']
166
+ * @param {string} [opts.accessResource='orchestrator'] - `resource` passed to
167
+ * `ctx.registry.checkAccess()` for inbound `'orchestrator-request'`s.
168
+ * @param {Function} [opts.onLog]
169
+ * @returns {import('./mesh-service.mjs').MeshService}
170
+ */
171
+ export function createOrchestratorService({
172
+ router,
173
+ runtimeRegistry,
174
+ remoteSessionBroker,
175
+ resourceRegistry,
176
+ auditRecorder,
177
+ dispatchTimeoutMs = DEFAULT_ORCHESTRATOR_DISPATCH_TIMEOUT_MS,
178
+ envelopeType = DEFAULT_ORCHESTRATOR_ENVELOPE_TYPE,
179
+ accessResource = DEFAULT_ACCESS_RESOURCE,
180
+ onLog,
181
+ } = {}) {
182
+ const log = onLog || (() => {})
183
+
184
+ return {
185
+ name: 'orchestrator',
186
+
187
+ attach(peerNode, ctx) {
188
+ const orchestrator = new MeshOrchestrator({
189
+ peerNode,
190
+ router: router ?? null,
191
+ runtimeRegistry: runtimeRegistry ?? null,
192
+ remoteSessionBroker: remoteSessionBroker ?? null,
193
+ resourceRegistry: resourceRegistry ?? null,
194
+ auditRecorder: auditRecorder ?? null,
195
+ peerRegistry: ctx.registry,
196
+ onLog: (msg) => log('mesh-orchestrator:internal', { message: msg }),
197
+ })
198
+
199
+ // -- Outbound dispatch: real request/response wire protocol -----------
200
+ let reqSeq = 0
201
+ const nextRequestId = () => `${peerNode.podId}:${Date.now()}:${++reqSeq}`
202
+
203
+ /** @type {Map<string, {resolve: Function, reject: Function, timer: ReturnType<typeof setTimeout>}>} */
204
+ const pendingDispatches = new Map()
205
+
206
+ function dispatch(podId, action, args) {
207
+ const requestId = nextRequestId()
208
+ const promise = new Promise((resolve, reject) => {
209
+ const timer = setTimeout(() => {
210
+ pendingDispatches.delete(requestId)
211
+ reject(new Error(`mesh-orchestrator: ${action} on ${podId} timed out after ${dispatchTimeoutMs}ms`))
212
+ }, dispatchTimeoutMs)
213
+ pendingDispatches.set(requestId, { resolve, reject, timer })
214
+ })
215
+
216
+ ctx.sendTo(podId, envelopeType, { kind: 'orchestrator-request', requestId, action, args }).catch((err) => {
217
+ const pending = pendingDispatches.get(requestId)
218
+ if (pending) {
219
+ clearTimeout(pending.timer)
220
+ pendingDispatches.delete(requestId)
221
+ pending.reject(err)
222
+ }
223
+ })
224
+
225
+ return promise
226
+ }
227
+
228
+ // -- Inbound wire handling ----------------------------------------------
229
+ async function respond(fromPubKey, requestId, payload) {
230
+ try {
231
+ await ctx.sendTo(fromPubKey, envelopeType, { kind: 'orchestrator-response', requestId, ...payload })
232
+ } catch (err) {
233
+ log('mesh-orchestrator:response-send-failed', { to: fromPubKey, requestId, error: err?.message || String(err) })
234
+ }
235
+ }
236
+
237
+ async function runAction(action, args) {
238
+ if (action === 'exec') return orchestrator.execOnPod(args.podId, args.command)
239
+ if (action === 'deploy') return orchestrator.deploySkill(args.podId, args.skillContent)
240
+ if (action === 'drain') return orchestrator.drainPod(args.podId)
241
+ throw new Error(`unsupported action: ${action}`)
242
+ }
243
+
244
+ async function handleOrchestratorRequest(fromPubKey, msg) {
245
+ const { requestId, action, args = {} } = msg
246
+
247
+ if (!RISKY_ACTIONS.includes(action)) {
248
+ ctx.emit('orchestrator:request-denied', { from: fromPubKey, requestId, action, reason: 'unsupported_action' })
249
+ await respond(fromPubKey, requestId, { error: `unsupported action: ${action}` })
250
+ return
251
+ }
252
+
253
+ const access = ctx.registry.checkAccess(fromPubKey, accessResource, action)
254
+ if (!access.allowed) {
255
+ ctx.emit('orchestrator:request-denied', { from: fromPubKey, requestId, action, reason: 'access_denied' })
256
+ await respond(fromPubKey, requestId, { error: 'access denied' })
257
+ return
258
+ }
259
+
260
+ let response
261
+ try {
262
+ const result = await runAction(action, args)
263
+ response = { result }
264
+ } catch (err) {
265
+ response = { error: err?.message || String(err) }
266
+ }
267
+
268
+ await respond(fromPubKey, requestId, response)
269
+ ctx.emit('orchestrator:request-served', { from: fromPubKey, requestId, action, ok: !response.error })
270
+ }
271
+
272
+ function handleOrchestratorResponse(msg) {
273
+ const pending = pendingDispatches.get(msg.requestId)
274
+ if (!pending) return // no longer waiting (already timed out, or not ours) -- ignore
275
+ pendingDispatches.delete(msg.requestId)
276
+ clearTimeout(pending.timer)
277
+ if (msg.error) {
278
+ pending.reject(new Error(msg.error))
279
+ } else {
280
+ pending.resolve(msg.result)
281
+ }
282
+ }
283
+
284
+ const unsubscribe = ctx.onIncomingData(envelopeType, (fromPubKey, msg) => {
285
+ if (!msg || typeof msg.kind !== 'string') return
286
+ if (msg.kind === 'orchestrator-request') {
287
+ handleOrchestratorRequest(fromPubKey, msg).catch((err) => {
288
+ log('mesh-orchestrator:request-handling-failed', { from: fromPubKey, requestId: msg.requestId, error: err?.message || String(err) })
289
+ })
290
+ } else if (msg.kind === 'orchestrator-response') {
291
+ handleOrchestratorResponse(msg)
292
+ }
293
+ })
294
+
295
+ // -- api ----------------------------------------------------------------
296
+ const localPodId = () => orchestrator.localPodId
297
+
298
+ const api = {
299
+ /** Raw `MeshOrchestrator` instance -- see module doc comment's `api.orchestrator` section. */
300
+ orchestrator,
301
+
302
+ // Local-only aggregation queries -- no wire protocol, no gate. See
303
+ // module doc comment's "AUTHORIZATION" section for why.
304
+ listPods: (filter) => orchestrator.listPods(filter),
305
+ getPodStatus: (podId) => orchestrator.getPodStatus(podId),
306
+ topPods: () => orchestrator.topPods(),
307
+
308
+ // Risky, peer-initiated-capable actions: local call when the target
309
+ // is this node itself (no network round-trip, mirroring
310
+ // mesh-agent-swarm.mjs's own local-self-assignment shortcut), a real
311
+ // gated wire dispatch otherwise.
312
+ execOnPod: (podId, command) => (podId === localPodId()
313
+ ? orchestrator.execOnPod(podId, command)
314
+ : dispatch(podId, 'exec', { podId, command })),
315
+ deploySkill: (podId, skillContent) => (podId === localPodId()
316
+ ? orchestrator.deploySkill(podId, skillContent)
317
+ : dispatch(podId, 'deploy', { podId, skillContent })),
318
+ drainPod: (podId) => (podId === localPodId()
319
+ ? orchestrator.drainPod(podId)
320
+ : dispatch(podId, 'drain', { podId })),
321
+ }
322
+
323
+ return {
324
+ api,
325
+ teardown() {
326
+ unsubscribe()
327
+ for (const pending of pendingDispatches.values()) {
328
+ clearTimeout(pending.timer)
329
+ pending.reject(new Error('mesh-orchestrator: service torn down while a dispatch was still in flight'))
330
+ }
331
+ pendingDispatches.clear()
332
+ },
333
+ }
334
+ },
335
+ }
336
+ }
337
+
338
+ export {
339
+ DEFAULT_ORCHESTRATOR_ENVELOPE_TYPE,
340
+ DEFAULT_ORCHESTRATOR_DISPATCH_TIMEOUT_MS,
341
+ DEFAULT_ACCESS_RESOURCE,
342
+ RISKY_ACTIONS,
343
+ }