@johnhenry/browsermesh-apps 0.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,547 @@
1
+ /**
2
+ * clawser-peer-agent.js -- Remote agent interaction over peer sessions.
3
+ *
4
+ * Allows one peer to chat with, invoke tools on, and query memories of
5
+ * another peer's AI agent. AgentHost serves the local ClawserAgent to
6
+ * remote peers, while AgentClient provides a promise-based interface for
7
+ * interacting with a remote peer's agent. Built on top of PeerSession's
8
+ * service handler system using the 'agent' service type.
9
+ *
10
+ * Dependencies are injected (PeerSession, agent interface).
11
+ * No browser-only imports at module level.
12
+ *
13
+ * Run tests:
14
+ * node --import ./web/test/_setup-globals.mjs --test web/test/clawser-peer-agent.test.mjs
15
+ */
16
+
17
+ // ---------------------------------------------------------------------------
18
+ // Constants
19
+ // ---------------------------------------------------------------------------
20
+
21
+ export const AGENT_DEFAULTS = Object.freeze({
22
+ timeout: 60000, // 60s -- agent calls can be slow
23
+ })
24
+
25
+ export const AGENT_ACTIONS = Object.freeze({
26
+ CHAT: 'chat',
27
+ TOOL: 'tool',
28
+ MEMORIES: 'memories',
29
+ })
30
+
31
+ export const AGENT_CAPABILITIES = Object.freeze({
32
+ CHAT: 'agent:chat',
33
+ TOOLS: 'agent:tools',
34
+ MEMORY: 'agent:memory',
35
+ })
36
+
37
+ // ---------------------------------------------------------------------------
38
+ // Internal -- map actions to required capabilities
39
+ // ---------------------------------------------------------------------------
40
+
41
+ const ACTION_CAPABILITY = Object.freeze({
42
+ [AGENT_ACTIONS.CHAT]: AGENT_CAPABILITIES.CHAT,
43
+ [AGENT_ACTIONS.TOOL]: AGENT_CAPABILITIES.TOOLS,
44
+ [AGENT_ACTIONS.MEMORIES]: AGENT_CAPABILITIES.MEMORY,
45
+ })
46
+
47
+ // ---------------------------------------------------------------------------
48
+ // AgentHost
49
+ // ---------------------------------------------------------------------------
50
+
51
+ /**
52
+ * Serves agent operations from the local ClawserAgent to remote peers.
53
+ *
54
+ * Registers a handler on the PeerSession for the 'agent' service type.
55
+ * Incoming requests are validated against capability requirements before
56
+ * execution. The remote peer must hold the appropriate capability on the
57
+ * session (agent:chat, agent:tools, agent:memory).
58
+ *
59
+ * When a ChannelGateway is provided, CHAT actions are routed through
60
+ * the gateway for unified queuing, event recording, and UI mirroring.
61
+ */
62
+ export class AgentHost {
63
+ /** @type {object} PeerSession */
64
+ #session
65
+
66
+ /**
67
+ * @type {object} Agent interface (duck-typed)
68
+ * async run(message) -> { response: string, usage?: object }
69
+ * async executeTool(name, args) -> { success, output, error? }
70
+ * searchMemories(query) -> MemoryEntry[]
71
+ */
72
+ #agent
73
+
74
+ /** @type {import('./clawser-gateway.js').ChannelGateway|null} */
75
+ #gateway
76
+
77
+ /** @type {object|null} { recordUsage(peerId, usage) } */
78
+ #costTracker
79
+
80
+ /** @type {Function} */
81
+ #onLog
82
+
83
+ /** @type {number} requests handled */
84
+ #requestCount = 0
85
+
86
+ /**
87
+ * @param {object} opts
88
+ * @param {object} opts.session - PeerSession instance
89
+ * @param {object} opts.agent - Agent interface with run/executeTool/searchMemories
90
+ * @param {import('./clawser-gateway.js').ChannelGateway} [opts.gateway] - Channel gateway for unified routing
91
+ * @param {object} [opts.costTracker] - Cost tracker with recordUsage(peerId, usage)
92
+ * @param {Function} [opts.onLog] - Logging callback
93
+ */
94
+ constructor({ session, agent, costTracker, gateway, onLog }) {
95
+ if (!session) {
96
+ throw new Error('session is required')
97
+ }
98
+ if (!agent || typeof agent.run !== 'function') {
99
+ throw new Error('agent with run() method is required')
100
+ }
101
+
102
+ this.#session = session
103
+ this.#agent = agent
104
+ this.#gateway = gateway || null
105
+ this.#costTracker = costTracker || null
106
+ this.#onLog = onLog || (() => {})
107
+
108
+ // Register handler on session for 'agent' service type
109
+ this.#session.registerHandler('agent', (envelope) => this.#handleRequest(envelope))
110
+ }
111
+
112
+ /** Set or replace the gateway reference. */
113
+ setGateway(gateway) { this.#gateway = gateway }
114
+
115
+ // -- Request handling (private) -------------------------------------------
116
+
117
+ /**
118
+ * Handle an incoming agent request.
119
+ *
120
+ * 1. Validates the action
121
+ * 2. Checks the required capability on the session
122
+ * 3. Dispatches to the appropriate agent method
123
+ * 4. Tracks cost attribution if costTracker is configured
124
+ * 5. Sends the response back via session
125
+ *
126
+ * @param {object} envelope - Session envelope with payload
127
+ */
128
+ async #handleRequest(envelope) {
129
+ const payload = envelope.payload || envelope
130
+ const { action, requestId } = payload
131
+
132
+ // Build base response
133
+ const response = {
134
+ requestId: requestId || null,
135
+ action: action || null,
136
+ success: false,
137
+ }
138
+
139
+ try {
140
+ // 1. Validate action
141
+ if (!action || !Object.values(AGENT_ACTIONS).includes(action)) {
142
+ response.error = `Unknown action: ${action}`
143
+ this.#session.send('agent', response)
144
+ return
145
+ }
146
+
147
+ // 2. Check capability
148
+ const requiredCap = ACTION_CAPABILITY[action]
149
+ if (requiredCap) {
150
+ this.#session.requireCapability(requiredCap)
151
+ }
152
+
153
+ // 3. Dispatch to the appropriate agent method
154
+ switch (action) {
155
+ case AGENT_ACTIONS.CHAT: {
156
+ const { message } = payload
157
+ if (!message || typeof message !== 'string') {
158
+ response.error = 'message must be a non-empty string'
159
+ this.#session.send('agent', response)
160
+ return
161
+ }
162
+
163
+ this.#onLog(2, `Agent chat request from ${this.#session.remotePodId}`)
164
+
165
+ if (this.#gateway) {
166
+ // Route through gateway for unified queuing, event recording, and UI mirroring
167
+ const channelId = `mesh:${this.#session.remotePodId}`
168
+ const gatewayResponse = await this.#gateway.ingest({
169
+ id: `peer_${requestId || Date.now()}`,
170
+ channel: 'mesh',
171
+ channelId: this.#session.remotePodId,
172
+ sender: {
173
+ id: this.#session.remotePodId,
174
+ name: this.#session.remotePodId,
175
+ username: null,
176
+ },
177
+ content: message,
178
+ attachments: [],
179
+ replyTo: null,
180
+ timestamp: Date.now(),
181
+ }, channelId)
182
+ this.#requestCount++
183
+
184
+ response.success = true
185
+ response.result = {
186
+ response: gatewayResponse,
187
+ }
188
+ } else {
189
+ // Direct agent call (original behavior)
190
+ const chatResult = await this.#agent.run(message)
191
+ this.#requestCount++
192
+
193
+ response.success = true
194
+ response.result = {
195
+ response: chatResult.response,
196
+ }
197
+ if (chatResult.usage) {
198
+ response.result.usage = chatResult.usage
199
+ }
200
+
201
+ // Track cost attribution
202
+ if (this.#costTracker && chatResult.usage) {
203
+ try {
204
+ this.#costTracker.recordUsage(this.#session.remotePodId, chatResult.usage)
205
+ } catch {
206
+ /* cost tracking errors do not propagate */
207
+ }
208
+ }
209
+ }
210
+ break
211
+ }
212
+
213
+ case AGENT_ACTIONS.TOOL: {
214
+ const { name, args } = payload
215
+ if (!name || typeof name !== 'string') {
216
+ response.error = 'tool name must be a non-empty string'
217
+ this.#session.send('agent', response)
218
+ return
219
+ }
220
+
221
+ this.#onLog(2, `Agent tool request from ${this.#session.remotePodId}: ${name}`)
222
+ const toolResult = await this.#agent.executeTool(name, args || {})
223
+ this.#requestCount++
224
+
225
+ response.success = true
226
+ response.result = {
227
+ success: toolResult.success,
228
+ output: toolResult.output,
229
+ }
230
+ if (toolResult.error) {
231
+ response.result.error = toolResult.error
232
+ }
233
+ break
234
+ }
235
+
236
+ case AGENT_ACTIONS.MEMORIES: {
237
+ const { query } = payload
238
+ if (!query || typeof query !== 'string') {
239
+ response.error = 'query must be a non-empty string'
240
+ this.#session.send('agent', response)
241
+ return
242
+ }
243
+
244
+ this.#onLog(2, `Agent memory search from ${this.#session.remotePodId}: ${query}`)
245
+ const memories = this.#agent.searchMemories(query)
246
+ this.#requestCount++
247
+
248
+ response.success = true
249
+ response.result = memories
250
+ break
251
+ }
252
+ }
253
+ } catch (err) {
254
+ response.error = err.message
255
+ this.#onLog(0, `Agent request error (${action}): ${err.message}`)
256
+ }
257
+
258
+ // Send response back
259
+ this.#session.send('agent', response)
260
+ }
261
+
262
+ // -- Lifecycle ------------------------------------------------------------
263
+
264
+ /**
265
+ * Close the agent host. Removes the handler from the session.
266
+ */
267
+ close() {
268
+ this.#session.removeHandler('agent')
269
+ }
270
+
271
+ // -- Serialization --------------------------------------------------------
272
+
273
+ /**
274
+ * Serialize to a JSON-safe object.
275
+ *
276
+ * @returns {object}
277
+ */
278
+ toJSON() {
279
+ return {
280
+ sessionId: this.#session.sessionId,
281
+ localPodId: this.#session.localPodId,
282
+ remotePodId: this.#session.remotePodId,
283
+ requestCount: this.#requestCount,
284
+ hasCostTracker: this.#costTracker !== null,
285
+ }
286
+ }
287
+ }
288
+
289
+ // ---------------------------------------------------------------------------
290
+ // AgentClient
291
+ // ---------------------------------------------------------------------------
292
+
293
+ /**
294
+ * Client-side interface for interacting with a remote peer's agent.
295
+ *
296
+ * Sends agent requests via the PeerSession and waits for responses
297
+ * matched by requestId. Supports configurable timeout per request and
298
+ * provides promise-based methods for chat, tool execution, and memory
299
+ * search.
300
+ */
301
+ export class AgentClient {
302
+ /** @type {object} PeerSession */
303
+ #session
304
+
305
+ /** @type {Map<string, { resolve: Function, reject: Function, timer: * }>} */
306
+ #pendingRequests = new Map()
307
+
308
+ /** @type {number} default timeout in ms */
309
+ #timeout
310
+
311
+ /** @type {Function} */
312
+ #onLog
313
+
314
+ /**
315
+ * @param {object} opts
316
+ * @param {object} opts.session - PeerSession instance
317
+ * @param {number} [opts.timeout=60000] - Default timeout for requests in ms
318
+ * @param {Function} [opts.onLog] - Logging callback
319
+ */
320
+ constructor({ session, timeout, onLog }) {
321
+ if (!session) {
322
+ throw new Error('session is required')
323
+ }
324
+
325
+ this.#session = session
326
+ this.#timeout = timeout ?? AGENT_DEFAULTS.timeout
327
+ this.#onLog = onLog || (() => {})
328
+
329
+ // Register handler on session for 'agent' response messages
330
+ this.#session.registerHandler('agent', (envelope) => this.#handleResponse(envelope))
331
+ }
332
+
333
+ // -- Agent operations -----------------------------------------------------
334
+
335
+ /**
336
+ * Send a chat message to the remote peer's agent.
337
+ *
338
+ * @param {string} message - Message to send to the agent
339
+ * @returns {Promise<{ response: string, usage?: object }>}
340
+ */
341
+ async chat(message) {
342
+ if (!message || typeof message !== 'string') {
343
+ throw new Error('message must be a non-empty string')
344
+ }
345
+
346
+ const response = await this.#request({
347
+ action: AGENT_ACTIONS.CHAT,
348
+ message,
349
+ })
350
+ return response.result
351
+ }
352
+
353
+ /**
354
+ * Execute a tool on the remote peer's agent.
355
+ *
356
+ * @param {string} toolName - Name of the tool to execute
357
+ * @param {object} [args={}] - Tool arguments
358
+ * @returns {Promise<{ success: boolean, output: *, error?: string }>}
359
+ */
360
+ async runTool(toolName, args) {
361
+ if (!toolName || typeof toolName !== 'string') {
362
+ throw new Error('toolName must be a non-empty string')
363
+ }
364
+
365
+ const response = await this.#request({
366
+ action: AGENT_ACTIONS.TOOL,
367
+ name: toolName,
368
+ args: args || {},
369
+ })
370
+ return response.result
371
+ }
372
+
373
+ /**
374
+ * Search memories on the remote peer's agent.
375
+ *
376
+ * @param {string} query - Search query
377
+ * @returns {Promise<MemoryEntry[]>}
378
+ */
379
+ async searchMemories(query) {
380
+ if (!query || typeof query !== 'string') {
381
+ throw new Error('query must be a non-empty string')
382
+ }
383
+
384
+ const response = await this.#request({
385
+ action: AGENT_ACTIONS.MEMORIES,
386
+ query,
387
+ })
388
+ return response.result
389
+ }
390
+
391
+ // -- Internal request handling --------------------------------------------
392
+
393
+ /**
394
+ * Send an agent request and wait for the matching response.
395
+ *
396
+ * Creates a unique requestId, sends the request via the session,
397
+ * and returns a promise that resolves when the response arrives
398
+ * or rejects on timeout.
399
+ *
400
+ * @param {object} payload - Request payload (must include action)
401
+ * @returns {Promise<{ requestId, action, success, result?, error? }>}
402
+ */
403
+ async #request(payload) {
404
+ const requestId = crypto.randomUUID()
405
+ const timeoutMs = this.#timeout
406
+
407
+ return new Promise((resolve, reject) => {
408
+ // Set up timeout
409
+ const timer = setTimeout(() => {
410
+ const pending = this.#pendingRequests.get(requestId)
411
+ if (pending) {
412
+ this.#pendingRequests.delete(requestId)
413
+ const err = new Error(`Agent request timed out after ${timeoutMs}ms`)
414
+ err.code = 'AGENT_TIMEOUT'
415
+ reject(err)
416
+ }
417
+ }, timeoutMs)
418
+
419
+ // Register pending request
420
+ this.#pendingRequests.set(requestId, { resolve, reject, timer })
421
+
422
+ // Build and send request
423
+ const message = { ...payload, requestId }
424
+
425
+ try {
426
+ this.#session.send('agent', message)
427
+ this.#onLog(2, `Sent agent ${payload.action} request to ${this.#session.remotePodId}`)
428
+ } catch (err) {
429
+ clearTimeout(timer)
430
+ this.#pendingRequests.delete(requestId)
431
+ reject(err)
432
+ }
433
+ })
434
+ }
435
+
436
+ // -- Response handling (private) ------------------------------------------
437
+
438
+ /**
439
+ * Handle an incoming agent response from the remote host.
440
+ * Matches by requestId and resolves or rejects the pending promise.
441
+ *
442
+ * @param {object} envelope - Session envelope with payload
443
+ */
444
+ #handleResponse(envelope) {
445
+ const payload = envelope.payload || envelope
446
+ const { requestId } = payload
447
+
448
+ if (!requestId) return
449
+
450
+ const pending = this.#pendingRequests.get(requestId)
451
+ if (!pending) return
452
+
453
+ // Clean up
454
+ clearTimeout(pending.timer)
455
+ this.#pendingRequests.delete(requestId)
456
+
457
+ // Check for errors
458
+ if (payload.error) {
459
+ const err = new Error(payload.error)
460
+ err.code = 'AGENT_REMOTE_ERROR'
461
+ pending.reject(err)
462
+ return
463
+ }
464
+
465
+ // Resolve with the full response
466
+ pending.resolve(payload)
467
+ }
468
+
469
+ // -- Lifecycle ------------------------------------------------------------
470
+
471
+ /**
472
+ * Close the agent client. Removes the handler from the session
473
+ * and rejects all pending requests.
474
+ */
475
+ close() {
476
+ // Reject all pending requests
477
+ for (const [requestId, pending] of this.#pendingRequests) {
478
+ clearTimeout(pending.timer)
479
+ pending.reject(new Error('AgentClient closed'))
480
+ }
481
+ this.#pendingRequests.clear()
482
+
483
+ // Remove handler from session
484
+ this.#session.removeHandler('agent')
485
+ }
486
+
487
+ // -- Serialization --------------------------------------------------------
488
+
489
+ /**
490
+ * Serialize to a JSON-safe object.
491
+ *
492
+ * @returns {object}
493
+ */
494
+ toJSON() {
495
+ return {
496
+ sessionId: this.#session.sessionId,
497
+ localPodId: this.#session.localPodId,
498
+ remotePodId: this.#session.remotePodId,
499
+ pendingRequests: this.#pendingRequests.size,
500
+ timeout: this.#timeout,
501
+ }
502
+ }
503
+ }
504
+
505
+ // ---------------------------------------------------------------------------
506
+ // Factory helper
507
+ // ---------------------------------------------------------------------------
508
+
509
+ /**
510
+ * Create an AgentHost wired to a ChannelGateway for unified routing.
511
+ *
512
+ * Registers a lightweight mesh plugin on the gateway so outbound responses
513
+ * route back through the session transport. Returns the AgentHost instance.
514
+ *
515
+ * @param {object} session - PeerSession instance
516
+ * @param {object} agent - Agent with run/executeTool/searchMemories
517
+ * @param {import('./clawser-gateway.js').ChannelGateway} gateway - Channel gateway
518
+ * @param {Function} [onLog] - Logging callback
519
+ * @returns {AgentHost}
520
+ */
521
+ export function bridgePeerAgent(session, agent, gateway, onLog) {
522
+ const channelId = `mesh:${session.remotePodId}`
523
+
524
+ // Register a lightweight plugin on the gateway for this peer
525
+ // so gateway.respond() can send outbound messages via the session.
526
+ const plugin = {
527
+ running: true,
528
+ start() { this.running = true },
529
+ stop() { this.running = false },
530
+ onMessage() {}, // Inbound handled by AgentHost, not plugin polling
531
+ async sendMessage(text) {
532
+ try {
533
+ session.send('agent', {
534
+ success: true,
535
+ result: { response: text },
536
+ })
537
+ return true
538
+ } catch {
539
+ return false
540
+ }
541
+ },
542
+ }
543
+
544
+ gateway.register(channelId, plugin, { scope: 'shared' })
545
+
546
+ return new AgentHost({ session, agent, gateway, onLog })
547
+ }