@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.
- package/README.md +443 -1
- package/package.json +18 -3
- package/src/agent-runtime.mjs +342 -0
- package/src/chunk-replication.mjs +751 -0
- package/src/cloud-storage-backend.mjs +932 -0
- package/src/cloud-storage.mjs +799 -0
- package/src/compat.mjs +98 -0
- package/src/gpu-kernel.mjs +242 -0
- package/src/gpu.mjs +101 -7
- package/src/grant-log.mjs +840 -0
- package/src/index.mjs +32 -2
- package/src/kernel-mesh.mjs +56 -0
- package/src/key-distribution.mjs +525 -0
- package/src/manifest-sync.mjs +363 -0
- package/src/mesh-agent-swarm.mjs +376 -0
- package/src/mesh-bootstrap.mjs +1481 -0
- package/src/mesh-compute.mjs +397 -0
- package/src/mesh-dht.mjs +182 -0
- package/src/mesh-fetch.mjs +246 -0
- package/src/mesh-hardening.mjs +226 -0
- package/src/mesh-health.mjs +282 -0
- package/src/mesh-keepalive.mjs +353 -0
- package/src/mesh-kv.mjs +673 -0
- package/src/mesh-orchestrator-tools.mjs +251 -0
- package/src/mesh-orchestrator.mjs +343 -0
- package/src/mesh-relay-backend.mjs +289 -0
- package/src/mesh-relay-host.mjs +362 -0
- package/src/mesh-rpc.mjs +300 -0
- package/src/mesh-service.mjs +403 -0
- package/src/mesh-swarm.mjs +677 -0
- package/src/mesh-sync.mjs +253 -0
- package/src/mesh-timestamp.mjs +265 -0
- package/src/mesh-torrent.mjs +683 -0
- package/src/mesh-verification.mjs +367 -0
- package/src/mesh-websocket.mjs +722 -0
- package/src/observability-bridge.mjs +453 -0
- package/src/orchestrator.mjs +18 -5
- package/src/peer-agent-swarm.mjs +12 -1
- package/src/peer-chat.mjs +230 -61
- package/src/peer-compute.mjs +66 -3
- package/src/peer-escrow.mjs +350 -1
- package/src/peer-files.mjs +362 -168
- package/src/peer-ipfs.mjs +205 -10
- package/src/peer-node.mjs +127 -19
- package/src/peer-registry.mjs +242 -18
- package/src/peer-routing.mjs +369 -5
- package/src/peer-terminal.mjs +400 -130
- package/src/signaling.mjs +231 -0
- package/src/webrtc-negotiator.mjs +209 -0
- package/src/peer-session.mjs +0 -937
|
@@ -0,0 +1,376 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* mesh-agent-swarm.mjs -- issue #124: wraps `peer-agent-swarm.mjs`'s
|
|
3
|
+
* `AgentSwarmCoordinator` as a `MeshService` (`mesh-service.mjs`, Phase C's
|
|
4
|
+
* `attach()`/`ctx` convention).
|
|
5
|
+
*
|
|
6
|
+
* Issue #124 was originally filed claiming `AgentSwarmCoordinator` depends on
|
|
7
|
+
* `swarm.mjs`'s SWIM coordination (#88, wired as `mesh-swarm.mjs`) and
|
|
8
|
+
* `peer-compute.mjs` (#118, wired as `mesh-compute.mjs`). Grounded
|
|
9
|
+
* investigation found neither is true: `AgentSwarmCoordinator` has its own,
|
|
10
|
+
* completely separate, self-invented `SwarmInstance`/`SubTask`
|
|
11
|
+
* membership/task model with zero code dependency on `swarm.mjs`'s
|
|
12
|
+
* `SwarmMember`/`SwarmTask`/`LeaderElection`/`TaskDistributor`, and it
|
|
13
|
+
* imports nothing from `peer-compute.mjs`. This file does not compose either
|
|
14
|
+
* of those services -- it is a fresh, self-contained wiring job.
|
|
15
|
+
*
|
|
16
|
+
* ---------------------------------------------------------------------------
|
|
17
|
+
* WHAT `AgentSwarmCoordinator` ITSELF DOES AND DOES NOT DO -- read directly
|
|
18
|
+
* off its constructor and `executeSubTask()`:
|
|
19
|
+
*
|
|
20
|
+
* - `agentProxy.chat(podId, message) -> Promise<string>` is a required
|
|
21
|
+
* constructor dependency (`AgentSwarmCoordinator` throws immediately if
|
|
22
|
+
* it's missing/falsy) -- the real "execute work" boundary, directly
|
|
23
|
+
* analogous to `peer-compute.mjs`'s required `executeFn`/
|
|
24
|
+
* `peer-verification.mjs`'s required `executeFn` (issue #86's resolved
|
|
25
|
+
* "bring-your-own executor, required, no default shipped" design).
|
|
26
|
+
* - `createSwarm()`/`decompose()`/`assign()` are pure local bookkeeping --
|
|
27
|
+
* `assign()` in particular just decides, from the swarm's own `members`
|
|
28
|
+
* list and `strategy`, who each subtask's `assignee` is. None of it does
|
|
29
|
+
* any network I/O.
|
|
30
|
+
* - `executeSubTask(swarmId, subtaskId, assignee)` is the ONE real
|
|
31
|
+
* network-relevant operation: it calls
|
|
32
|
+
* `this.#agentProxy.chat(assignee, subtask.description)` directly,
|
|
33
|
+
* UNCONDITIONALLY -- it never checks whether `assignee` is this node or
|
|
34
|
+
* some other one. In the original, single-node code (a single
|
|
35
|
+
* `AgentSwarmCoordinator` + a single `agentProxy` that happens to be able
|
|
36
|
+
* to `chat()` with several locally-known `podId`s, e.g. several ClawserPod
|
|
37
|
+
* agents in one process), that's fine: every `assignee` is reachable
|
|
38
|
+
* through the same local `agentProxy`. In a real mesh deployment,
|
|
39
|
+
* `assignee` is frequently a REMOTE peer's podId -- so today's code, as
|
|
40
|
+
* written, is fundamentally single-node-only: it has no notion
|
|
41
|
+
* whatsoever of "this assignee lives on another machine, go get the
|
|
42
|
+
* result from them over the network" versus "this assignee is local."
|
|
43
|
+
*
|
|
44
|
+
* ---------------------------------------------------------------------------
|
|
45
|
+
* THE WIRING APPROACH THIS FILE TAKES -- narrower than `mesh-compute.mjs`'s/
|
|
46
|
+
* `mesh-verification.mjs`'s "wrap the injected `scheduler`" shape, and
|
|
47
|
+
* deliberately so:
|
|
48
|
+
*
|
|
49
|
+
* `AgentSwarmCoordinator` funnels ALL of its real work through exactly one
|
|
50
|
+
* injected seam: `agentProxy.chat(podId, message)`. Rather than
|
|
51
|
+
* reimplementing `executeSubTask()`'s status bookkeeping (`'running'` ->
|
|
52
|
+
* `'completed'`/`'failed'`, `st.result`, the `subtask-complete` event, the
|
|
53
|
+
* `swarm.timeoutMs` race) OUTSIDE the class, this file supplies the
|
|
54
|
+
* coordinator with a `meshAgentProxy` wrapper around the caller's real
|
|
55
|
+
* `agentProxy`: `meshAgentProxy.chat(podId, message)` checks whether `podId`
|
|
56
|
+
* is THIS node's own `peerNode.podId` --
|
|
57
|
+
*
|
|
58
|
+
* - if so, it calls the caller-supplied local `agentProxy.chat()` directly
|
|
59
|
+
* -- no network round-trip is ever forced for a self-assigned subtask;
|
|
60
|
+
* - otherwise, it sends a real `'agent-swarm-request'` envelope to `podId`
|
|
61
|
+
* over `ctx.sendTo()` and awaits a matching `'agent-swarm-response'`
|
|
62
|
+
* reply, exactly the request/correlation-id/timeout shape
|
|
63
|
+
* `mesh-compute.mjs`'s default `scheduler.dispatch()` already
|
|
64
|
+
* establishes.
|
|
65
|
+
*
|
|
66
|
+
* Since `executeSubTask()` already calls `this.#agentProxy.chat(assignee,
|
|
67
|
+
* ...)` for every subtask regardless of who `assignee` is, injecting this one
|
|
68
|
+
* wrapper is sufficient to make `executeSubTask()` itself correctly local- or
|
|
69
|
+
* remote-dispatch -- no other method needs touching, and none of
|
|
70
|
+
* `AgentSwarmCoordinator`'s own status/event/timeout logic is duplicated.
|
|
71
|
+
*
|
|
72
|
+
* ---------------------------------------------------------------------------
|
|
73
|
+
* LOCAL/ADMIN vs. PEER-INITIATED:
|
|
74
|
+
*
|
|
75
|
+
* - `api.createSwarm()`/`api.decompose()`/`api.assign()`/
|
|
76
|
+
* `api.executeSubTask()`/`api.collectResults()`/`api.getSwarm()`/
|
|
77
|
+
* `api.listSwarms()`/`api.disbandSwarm()` are all LOCAL calls: this
|
|
78
|
+
* node's own operator/application code driving a swarm it owns. Nothing
|
|
79
|
+
* about calling any of these requires anything from a remote peer first
|
|
80
|
+
* -- `executeSubTask()` may, internally, reach out to a peer (see above),
|
|
81
|
+
* but the decision to call it at all is always local.
|
|
82
|
+
* - Receiving an `'agent-swarm-request'` FROM a peer -- i.e., being asked
|
|
83
|
+
* to run `agentProxy.chat()` on THIS node's behalf, because some other
|
|
84
|
+
* node's coordinator assigned a subtask to this podId -- is the
|
|
85
|
+
* genuinely PEER-INITIATED action, and the one that needs an
|
|
86
|
+
* authorization check: before this node ever runs its local
|
|
87
|
+
* `agentProxy.chat()` for a remote requester, it gates the request
|
|
88
|
+
* through `ctx.registry.checkAccess(fromPubKey, accessResource,
|
|
89
|
+
* accessAction)` (default resource/action: `'agent-swarm'`/`'execute'`),
|
|
90
|
+
* the same `registry.checkAccess()` gate `mesh-compute.mjs`/
|
|
91
|
+
* `mesh-verification.mjs`/`chunk-replication.mjs`/`mesh-kv.mjs` already
|
|
92
|
+
* established for "a peer wants this node to do something on its
|
|
93
|
+
* behalf." A denied peer gets an explicit `{error: 'access denied'}`
|
|
94
|
+
* response (not a silent drop) -- the requesting side's `chat()` Promise
|
|
95
|
+
* is already open and waiting, so silently dropping would just make an
|
|
96
|
+
* unauthorized peer indistinguishable from a slow or dead one, exactly
|
|
97
|
+
* the reasoning `mesh-compute.mjs`'s/`mesh-verification.mjs`'s own header
|
|
98
|
+
* comments already document ("WHY AN EXPLICIT DENIAL RESPONSE").
|
|
99
|
+
*
|
|
100
|
+
* ---------------------------------------------------------------------------
|
|
101
|
+
* `agentProxy` -- REQUIRED, NOT PROVIDED BY THIS FILE, AND CHECKED TWICE.
|
|
102
|
+
* Unlike `mesh-compute.mjs`'s `executeFn`/`mesh-verification.mjs`'s
|
|
103
|
+
* `executeFn` (each OPTIONAL at their respective `createXService()` layer,
|
|
104
|
+
* since a node can legitimately submit-only without ever answering), a
|
|
105
|
+
* usable `agentProxy` is unconditionally required here: `AgentSwarmCoordinator`
|
|
106
|
+
* itself throws in its own constructor if `agentProxy` is falsy, and EVERY
|
|
107
|
+
* real operation this service offers -- including a purely local,
|
|
108
|
+
* self-assigned `executeSubTask()` with no peer involved at all -- ultimately
|
|
109
|
+
* calls into it. Because this file always hands `AgentSwarmCoordinator` its
|
|
110
|
+
* own always-truthy `meshAgentProxy` wrapper (never the caller's raw
|
|
111
|
+
* `agentProxy` directly), that class's own truthy check can never catch a
|
|
112
|
+
* missing caller-supplied `agentProxy` -- so `createAgentSwarmService()`
|
|
113
|
+
* checks for it explicitly and throws immediately, with a clear message,
|
|
114
|
+
* before ever constructing anything. `mesh-bootstrap.mjs`'s
|
|
115
|
+
* `{enableAgentSwarm, agentSwarmOptions}` wiring ALSO checks this up front
|
|
116
|
+
* (mirroring `enableCompute`'s/`enableTerminal`'s established
|
|
117
|
+
* required-dependency check), so a caller going through `createMeshNode()`
|
|
118
|
+
* gets the same clear failure before any service is attached. No default
|
|
119
|
+
* `agentProxy` implementation is built anywhere in this file -- issue #86's
|
|
120
|
+
* resolved "bring-your-own executor" decision applies here exactly as it does
|
|
121
|
+
* for compute/verification/terminal.
|
|
122
|
+
*
|
|
123
|
+
* ---------------------------------------------------------------------------
|
|
124
|
+
* Observability events (`ctx.emit()`, see `mesh-service.mjs`'s module doc
|
|
125
|
+
* comment for the full convention). `AgentSwarmCoordinator`'s own
|
|
126
|
+
* pre-existing `on`/`off` surface is bridged through verbatim, prefixed
|
|
127
|
+
* `agent-swarm:`:
|
|
128
|
+
*
|
|
129
|
+
* - `agent-swarm:created` -- `{swarmId, goal, leader}`.
|
|
130
|
+
* - `agent-swarm:task-assigned` -- `{swarmId, subtaskId, assignee}`.
|
|
131
|
+
* - `agent-swarm:subtask-complete` -- `{swarmId, subtaskId, assignee, result}`.
|
|
132
|
+
* - `agent-swarm:completed` -- `{swarmId, merged, individual}`.
|
|
133
|
+
* - `agent-swarm:disbanded` -- `{swarmId}`.
|
|
134
|
+
*
|
|
135
|
+
* Plus this file's own, for the wire layer (mirroring `mesh-compute.mjs`'s
|
|
136
|
+
* `compute:chunk-served`/`compute:chunk-request-denied`):
|
|
137
|
+
*
|
|
138
|
+
* - `agent-swarm:execute-served` `{from, requestId, ok}` -- this node, AS
|
|
139
|
+
* THE ASSIGNEE, answered an authorized `'agent-swarm-request'` (`ok:
|
|
140
|
+
* true` if the local `agentProxy.chat()` succeeded, `false` if it threw).
|
|
141
|
+
* - `agent-swarm:execute-request-denied` `{from, requestId, reason}` -- an
|
|
142
|
+
* inbound `'agent-swarm-request'` was rejected before `agentProxy.chat()`
|
|
143
|
+
* ever ran (`reason`: `'access_denied'`).
|
|
144
|
+
*
|
|
145
|
+
* No browser-only imports at module level.
|
|
146
|
+
*/
|
|
147
|
+
|
|
148
|
+
import { AgentSwarmCoordinator } from './peer-agent-swarm.mjs'
|
|
149
|
+
|
|
150
|
+
/** Shared envelope `type` for both request/response directions (tagged by `kind`), mirroring `mesh-compute.mjs`'s `'mesh-compute'` shape. */
|
|
151
|
+
const DEFAULT_AGENT_SWARM_ENVELOPE_TYPE = 'mesh-agent-swarm'
|
|
152
|
+
|
|
153
|
+
/** How long the remote-dispatch path of `meshAgentProxy.chat()` waits for a matching `'agent-swarm-response'` before giving up. Independent of (and typically ⩽) `AgentSwarmCoordinator`'s own internal `swarm.timeoutMs` race around the whole `agentProxy.chat()` call -- whichever fires first wins; this one exists purely so a never-answering peer's pending entry is always eventually cleaned up. */
|
|
154
|
+
const DEFAULT_AGENT_SWARM_DISPATCH_TIMEOUT_MS = 30000
|
|
155
|
+
|
|
156
|
+
/** Default `resource`/`action` pair checked via `ctx.registry.checkAccess(fromPubKey, resource, action)` before honoring an inbound `'agent-swarm-request'`. */
|
|
157
|
+
const DEFAULT_AGENT_SWARM_ACCESS_RESOURCE = 'agent-swarm'
|
|
158
|
+
const DEFAULT_AGENT_SWARM_ACCESS_ACTION = 'execute'
|
|
159
|
+
|
|
160
|
+
/**
|
|
161
|
+
* Build a `MeshService` descriptor (`mesh-service.mjs`, Phase C) wrapping
|
|
162
|
+
* `AgentSwarmCoordinator`. See this file's module doc comment for the full
|
|
163
|
+
* design writeup (what's local/admin-only vs. peer-initiated, why
|
|
164
|
+
* `agentProxy` is required and checked here directly rather than left to
|
|
165
|
+
* `AgentSwarmCoordinator`'s own constructor check, the local-vs-remote
|
|
166
|
+
* `meshAgentProxy` wrapper).
|
|
167
|
+
*
|
|
168
|
+
* @param {object} opts
|
|
169
|
+
* @param {{chat: (podId: string, message: string) => Promise<string>}} opts.agentProxy
|
|
170
|
+
* REQUIRED. Called to actually run a chat turn for an agent hosted on THIS
|
|
171
|
+
* node -- both for purely local, self-assigned subtasks (called directly,
|
|
172
|
+
* no network) and for authorized inbound `'agent-swarm-request'`s from a
|
|
173
|
+
* remote peer whose coordinator assigned a subtask to this node (called
|
|
174
|
+
* after `ctx.registry.checkAccess()` authorizes the requester). This
|
|
175
|
+
* function throws immediately if omitted -- see module doc comment.
|
|
176
|
+
* @param {number} [opts.dispatchTimeoutMs=30000] - How long the remote-dispatch
|
|
177
|
+
* path of `meshAgentProxy.chat()` waits for an `'agent-swarm-response'`.
|
|
178
|
+
* @param {string} [opts.envelopeType='mesh-agent-swarm']
|
|
179
|
+
* @param {string} [opts.accessResource='agent-swarm'] - `resource` passed to
|
|
180
|
+
* `ctx.registry.checkAccess()` for inbound `'agent-swarm-request'`s.
|
|
181
|
+
* @param {string} [opts.accessAction='execute'] - `action` passed to
|
|
182
|
+
* `ctx.registry.checkAccess()` for inbound `'agent-swarm-request'`s.
|
|
183
|
+
* @param {Function} [opts.onLog]
|
|
184
|
+
* @returns {import('./mesh-service.mjs').MeshService}
|
|
185
|
+
*/
|
|
186
|
+
export function createAgentSwarmService({
|
|
187
|
+
agentProxy,
|
|
188
|
+
dispatchTimeoutMs = DEFAULT_AGENT_SWARM_DISPATCH_TIMEOUT_MS,
|
|
189
|
+
envelopeType = DEFAULT_AGENT_SWARM_ENVELOPE_TYPE,
|
|
190
|
+
accessResource = DEFAULT_AGENT_SWARM_ACCESS_RESOURCE,
|
|
191
|
+
accessAction = DEFAULT_AGENT_SWARM_ACCESS_ACTION,
|
|
192
|
+
onLog,
|
|
193
|
+
} = {}) {
|
|
194
|
+
if (!agentProxy) {
|
|
195
|
+
throw new Error(
|
|
196
|
+
'createAgentSwarmService: agentProxy is required (an object implementing ' +
|
|
197
|
+
'async chat(podId, message) -> string -- see peer-agent-swarm.mjs\'s ' +
|
|
198
|
+
'AgentSwarmCoordinator). No default agentProxy is provided by this package.',
|
|
199
|
+
)
|
|
200
|
+
}
|
|
201
|
+
const log = onLog || (() => {})
|
|
202
|
+
|
|
203
|
+
return {
|
|
204
|
+
name: 'agent-swarm',
|
|
205
|
+
|
|
206
|
+
attach(peerNode, ctx) {
|
|
207
|
+
// -- Wire protocol state -------------------------------------------
|
|
208
|
+
let reqSeq = 0
|
|
209
|
+
const nextRequestId = () => `${peerNode.podId}:${Date.now()}:${++reqSeq}`
|
|
210
|
+
|
|
211
|
+
/** @type {Map<string, {resolve: Function, reject: Function, timer: ReturnType<typeof setTimeout>}>} */
|
|
212
|
+
const pendingDispatches = new Map()
|
|
213
|
+
|
|
214
|
+
// -- meshAgentProxy: the one seam AgentSwarmCoordinator calls through
|
|
215
|
+
// for every real operation. Local-assignment (podId === this node's
|
|
216
|
+
// own podId) never touches the network -- see module doc comment.
|
|
217
|
+
const meshAgentProxy = {
|
|
218
|
+
async chat(podId, message) {
|
|
219
|
+
if (podId === peerNode.podId) {
|
|
220
|
+
return agentProxy.chat(podId, message)
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
const requestId = nextRequestId()
|
|
224
|
+
const promise = new Promise((resolve, reject) => {
|
|
225
|
+
const timer = setTimeout(() => {
|
|
226
|
+
pendingDispatches.delete(requestId)
|
|
227
|
+
reject(new Error(`mesh-agent-swarm: dispatch to ${podId} timed out after ${dispatchTimeoutMs}ms`))
|
|
228
|
+
}, dispatchTimeoutMs)
|
|
229
|
+
pendingDispatches.set(requestId, { resolve, reject, timer })
|
|
230
|
+
})
|
|
231
|
+
|
|
232
|
+
ctx.sendTo(podId, envelopeType, { kind: 'agent-swarm-request', requestId, message }).catch((err) => {
|
|
233
|
+
const pending = pendingDispatches.get(requestId)
|
|
234
|
+
if (pending) {
|
|
235
|
+
clearTimeout(pending.timer)
|
|
236
|
+
pendingDispatches.delete(requestId)
|
|
237
|
+
pending.reject(err)
|
|
238
|
+
}
|
|
239
|
+
})
|
|
240
|
+
|
|
241
|
+
return promise
|
|
242
|
+
},
|
|
243
|
+
}
|
|
244
|
+
|
|
245
|
+
const coordinator = new AgentSwarmCoordinator({
|
|
246
|
+
agentProxy: meshAgentProxy,
|
|
247
|
+
onLog: (level, msg) => log('mesh-agent-swarm:internal', { level, msg }),
|
|
248
|
+
})
|
|
249
|
+
|
|
250
|
+
// Bridge AgentSwarmCoordinator's own pre-existing on()/off() events
|
|
251
|
+
// through ctx.emit() -- see module doc comment's "Observability
|
|
252
|
+
// events" section.
|
|
253
|
+
const bridgedEvents = [
|
|
254
|
+
'created', 'task-assigned', 'subtask-complete', 'completed', 'disbanded',
|
|
255
|
+
]
|
|
256
|
+
const bridgeHandlers = bridgedEvents.map((event) => {
|
|
257
|
+
const handler = (data) => ctx.emit(`agent-swarm:${event}`, data)
|
|
258
|
+
coordinator.on(event, handler)
|
|
259
|
+
return [event, handler]
|
|
260
|
+
})
|
|
261
|
+
|
|
262
|
+
// -- Inbound wire handling ------------------------------------------
|
|
263
|
+
async function handleAgentSwarmRequest(fromPubKey, msg) {
|
|
264
|
+
const { requestId, message } = msg
|
|
265
|
+
|
|
266
|
+
const access = ctx.registry.checkAccess(fromPubKey, accessResource, accessAction)
|
|
267
|
+
if (!access.allowed) {
|
|
268
|
+
ctx.emit('agent-swarm:execute-request-denied', { from: fromPubKey, requestId, reason: 'access_denied' })
|
|
269
|
+
await ctx.sendTo(fromPubKey, envelopeType, { kind: 'agent-swarm-response', requestId, error: 'access denied' }).catch((err) => {
|
|
270
|
+
log('mesh-agent-swarm:response-send-failed', { to: fromPubKey, requestId, error: err?.message || String(err) })
|
|
271
|
+
})
|
|
272
|
+
return
|
|
273
|
+
}
|
|
274
|
+
|
|
275
|
+
let response
|
|
276
|
+
try {
|
|
277
|
+
const result = await agentProxy.chat(peerNode.podId, message)
|
|
278
|
+
response = { kind: 'agent-swarm-response', requestId, result }
|
|
279
|
+
} catch (err) {
|
|
280
|
+
response = { kind: 'agent-swarm-response', requestId, error: err?.message || String(err) }
|
|
281
|
+
}
|
|
282
|
+
|
|
283
|
+
try {
|
|
284
|
+
await ctx.sendTo(fromPubKey, envelopeType, response)
|
|
285
|
+
ctx.emit('agent-swarm:execute-served', { from: fromPubKey, requestId, ok: !response.error })
|
|
286
|
+
} catch (err) {
|
|
287
|
+
log('mesh-agent-swarm:response-send-failed', { to: fromPubKey, requestId, error: err?.message || String(err) })
|
|
288
|
+
}
|
|
289
|
+
}
|
|
290
|
+
|
|
291
|
+
function handleAgentSwarmResponse(msg) {
|
|
292
|
+
const pending = pendingDispatches.get(msg.requestId)
|
|
293
|
+
if (!pending) return // already resolved (timed out or answered) -- ignore
|
|
294
|
+
pendingDispatches.delete(msg.requestId)
|
|
295
|
+
clearTimeout(pending.timer)
|
|
296
|
+
if (msg.error) {
|
|
297
|
+
pending.reject(new Error(msg.error))
|
|
298
|
+
} else {
|
|
299
|
+
pending.resolve(msg.result)
|
|
300
|
+
}
|
|
301
|
+
}
|
|
302
|
+
|
|
303
|
+
const unsubscribe = ctx.onIncomingData(envelopeType, (fromPubKey, msg) => {
|
|
304
|
+
if (!msg || typeof msg.kind !== 'string') return
|
|
305
|
+
if (msg.kind === 'agent-swarm-request') {
|
|
306
|
+
handleAgentSwarmRequest(fromPubKey, msg).catch((err) => {
|
|
307
|
+
log('mesh-agent-swarm:request-handling-failed', { from: fromPubKey, requestId: msg.requestId, error: err?.message || String(err) })
|
|
308
|
+
})
|
|
309
|
+
} else if (msg.kind === 'agent-swarm-response') {
|
|
310
|
+
handleAgentSwarmResponse(msg)
|
|
311
|
+
}
|
|
312
|
+
})
|
|
313
|
+
|
|
314
|
+
const api = {
|
|
315
|
+
/**
|
|
316
|
+
* @param {string} goal
|
|
317
|
+
* @param {object} [opts]
|
|
318
|
+
* @returns {Promise<import('./peer-agent-swarm.mjs').SwarmInstance>}
|
|
319
|
+
*/
|
|
320
|
+
createSwarm: (goal, createOpts) => coordinator.createSwarm(goal, createOpts),
|
|
321
|
+
|
|
322
|
+
/**
|
|
323
|
+
* @param {string} swarmId
|
|
324
|
+
* @param {Function} [decomposer]
|
|
325
|
+
* @returns {Promise<import('./peer-agent-swarm.mjs').SubTask[]>}
|
|
326
|
+
*/
|
|
327
|
+
decompose: (swarmId, decomposer) => coordinator.decompose(swarmId, decomposer),
|
|
328
|
+
|
|
329
|
+
/** @param {string} swarmId */
|
|
330
|
+
assign: (swarmId) => coordinator.assign(swarmId),
|
|
331
|
+
|
|
332
|
+
/**
|
|
333
|
+
* @param {string} swarmId
|
|
334
|
+
* @param {string} subtaskId
|
|
335
|
+
* @param {string} assignee
|
|
336
|
+
* @returns {Promise<{result: string, success: boolean, error?: string}>}
|
|
337
|
+
*/
|
|
338
|
+
executeSubTask: (swarmId, subtaskId, assignee) => coordinator.executeSubTask(swarmId, subtaskId, assignee),
|
|
339
|
+
|
|
340
|
+
/**
|
|
341
|
+
* @param {string} swarmId
|
|
342
|
+
* @param {Function} [mergeFn]
|
|
343
|
+
*/
|
|
344
|
+
collectResults: (swarmId, mergeFn) => coordinator.collectResults(swarmId, mergeFn),
|
|
345
|
+
|
|
346
|
+
/** @param {string} id */
|
|
347
|
+
getSwarm: (id) => coordinator.getSwarm(id),
|
|
348
|
+
|
|
349
|
+
listSwarms: () => coordinator.listSwarms(),
|
|
350
|
+
|
|
351
|
+
/** @param {string} swarmId */
|
|
352
|
+
disbandSwarm: (swarmId) => coordinator.disbandSwarm(swarmId),
|
|
353
|
+
}
|
|
354
|
+
|
|
355
|
+
return {
|
|
356
|
+
api,
|
|
357
|
+
teardown() {
|
|
358
|
+
for (const [event, handler] of bridgeHandlers) coordinator.off(event, handler)
|
|
359
|
+
unsubscribe()
|
|
360
|
+
for (const pending of pendingDispatches.values()) {
|
|
361
|
+
clearTimeout(pending.timer)
|
|
362
|
+
pending.reject(new Error('mesh-agent-swarm: service torn down while a dispatch was still in flight'))
|
|
363
|
+
}
|
|
364
|
+
pendingDispatches.clear()
|
|
365
|
+
},
|
|
366
|
+
}
|
|
367
|
+
},
|
|
368
|
+
}
|
|
369
|
+
}
|
|
370
|
+
|
|
371
|
+
export {
|
|
372
|
+
DEFAULT_AGENT_SWARM_ENVELOPE_TYPE,
|
|
373
|
+
DEFAULT_AGENT_SWARM_DISPATCH_TIMEOUT_MS,
|
|
374
|
+
DEFAULT_AGENT_SWARM_ACCESS_RESOURCE,
|
|
375
|
+
DEFAULT_AGENT_SWARM_ACCESS_ACTION,
|
|
376
|
+
}
|