@nolag/agents 1.0.0 → 1.1.1

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,1579 @@
1
+ /**
2
+ * Tiny typed event emitter — framework-agnostic base for NoLagAgents and AgentRoom.
3
+ *
4
+ * EventMap is a record of event name -> tuple of handler arguments.
5
+ * e.g. { task: [TaskEnvelope]; result: [ResultEnvelope] }
6
+ */
7
+ class EventEmitter {
8
+ constructor() {
9
+ this._handlers = new Map();
10
+ }
11
+ on(event, handler) {
12
+ if (!this._handlers.has(event)) {
13
+ this._handlers.set(event, new Set());
14
+ }
15
+ this._handlers.get(event).add(handler);
16
+ return this;
17
+ }
18
+ off(event, handler) {
19
+ if (handler) {
20
+ this._handlers.get(event)?.delete(handler);
21
+ }
22
+ else {
23
+ this._handlers.delete(event);
24
+ }
25
+ return this;
26
+ }
27
+ removeAllListeners() {
28
+ this._handlers.clear();
29
+ return this;
30
+ }
31
+ emit(event, ...args) {
32
+ const handlers = this._handlers.get(event);
33
+ if (!handlers)
34
+ return;
35
+ for (const handler of handlers) {
36
+ try {
37
+ // Async handlers don't throw — they return rejected promises, which
38
+ // the catch below never sees. Left unattached, one bad envelope from
39
+ // the wire becomes an unhandled rejection and (Node ≥15) TERMINATES
40
+ // THE HOST PROCESS. An event emitter fed by network input must never
41
+ // hand a remote peer that power, so rejections are contained here
42
+ // exactly like sync throws.
43
+ const result = handler(...args);
44
+ if (result &&
45
+ typeof result.then === "function") {
46
+ result.then(undefined, (e) => {
47
+ console.error(`Error in async ${String(event)} handler:`, e);
48
+ });
49
+ }
50
+ }
51
+ catch (e) {
52
+ console.error(`Error in ${String(event)} handler:`, e);
53
+ }
54
+ }
55
+ }
56
+ listenerCount(event) {
57
+ return this._handlers.get(event)?.size ?? 0;
58
+ }
59
+ }
60
+
61
+ /** Default app name for agent coordination */
62
+ const DEFAULT_APP_NAME = "agents";
63
+ /** Topic name for task dispatch (Handoff pattern) */
64
+ const TOPIC_TASKS = "tasks";
65
+ /** Topic name for task results */
66
+ const TOPIC_RESULTS = "results";
67
+ /** Topic name for shared state (Blackboard pattern) */
68
+ const TOPIC_STATE = "state";
69
+ /** Topic name for observability events (Observe pattern) */
70
+ const TOPIC_EVENTS = "events";
71
+ /** Topic name for per-agent inboxes (Inbox pattern) */
72
+ const TOPIC_INBOX = "inbox";
73
+ /** Topic name for tool invocations (Tools pattern) */
74
+ const TOPIC_TOOLS = "tools";
75
+ /** Topic name for human-in-the-loop approval (Approve pattern) */
76
+ const TOPIC_APPROVAL = "approval";
77
+ /** Default room for agent coordination */
78
+ const DEFAULT_ROOM = "default-workflow";
79
+ /** Delay before the post-setup lobby presence refetch (catches simultaneous joiners) */
80
+ const LOBBY_REFRESH_DELAY_MS = 2000;
81
+ /** Agents-protocol version: 2 = directed replies (filter-routed results),
82
+ * NO_HANDLER NACKs, presence protocol advertisement. Absent/1 = legacy
83
+ * broadcast replies (pre-0.2.0 SDKs). */
84
+ const AGENTS_PROTOCOL_VERSION = 2;
85
+
86
+ /**
87
+ * AgentRoom — a single agent-coordination room (scoped unit).
88
+ *
89
+ * Wraps a RoomContext from @nolag/js-sdk with typed pub/sub for agent
90
+ * coordination topics, presence-based service discovery, and capability
91
+ * routing.
92
+ *
93
+ * Created via `NoLagAgents.room(name)`. Do not instantiate directly. Presence
94
+ * events are routed in by the parent NoLagAgents (which owns the shared
95
+ * client's connection-level presence handlers); the room only wires its own
96
+ * topic handlers on its RoomContext, and cleanup removes exactly those.
97
+ *
98
+ * @example
99
+ * ```typescript
100
+ * const room = agents.room('default-workflow');
101
+ *
102
+ * // Service discovery - see who's connected
103
+ * const connected = room.getConnectedAgents();
104
+ * const summarizers = room.findAgents('summarize');
105
+ *
106
+ * // Capability-filtered task handler
107
+ * room.on('task', (envelope) => console.log('New task:', envelope));
108
+ * ```
109
+ */
110
+ class AgentRoom extends EventEmitter {
111
+ /** @internal */
112
+ constructor(name, roomContext, log, agentId, appName, isConnected, presence) {
113
+ super();
114
+ /** Registry of connected agents discovered via presence */
115
+ this._agents = new Map();
116
+ // Stored topic handler refs — cleanup removes exactly these, never all
117
+ // handlers for a topic (the client may be shared with other consumers).
118
+ this._topicHandlers = [];
119
+ this.name = name;
120
+ this.agentId = agentId;
121
+ this._roomContext = roomContext;
122
+ this._log = log;
123
+ this._appName = appName;
124
+ this._isConnected = isConnected;
125
+ this._presence = presence;
126
+ this._wireTopicListeners();
127
+ // Set presence if provided (with the SDK's protocol version advertised
128
+ // so counterparts can detect incompatible reply semantics, and a __scope
129
+ // tag so co-attached wrappers on other apps filter our presence out).
130
+ if (presence) {
131
+ this._presence = { protocol: AGENTS_PROTOCOL_VERSION, ...presence };
132
+ this._log(`setting presence in room ${name}:`, this._presence);
133
+ this._roomContext.setPresence({ ...this._presence, __scope: appName });
134
+ }
135
+ // Fetch initial presence snapshot
136
+ void this._fetchInitialPresence();
137
+ }
138
+ // ============================================================
139
+ // SERVICE DISCOVERY
140
+ // ============================================================
141
+ /** Get all currently connected agents */
142
+ getConnectedAgents() {
143
+ return Array.from(this._agents.values());
144
+ }
145
+ /** Find agents that have a specific capability */
146
+ findAgents(capability) {
147
+ return Array.from(this._agents.values()).filter((a) => a.capabilities.includes(capability));
148
+ }
149
+ /** Check if any connected agent can handle a capability */
150
+ hasCapability(capability) {
151
+ return this.findAgents(capability).length > 0;
152
+ }
153
+ /** Get all capabilities available across connected agents */
154
+ getAvailableCapabilities() {
155
+ const caps = new Set();
156
+ for (const agent of this._agents.values()) {
157
+ for (const cap of agent.capabilities) {
158
+ caps.add(cap);
159
+ }
160
+ }
161
+ return Array.from(caps);
162
+ }
163
+ // ============================================================
164
+ // PRESENCE
165
+ // ============================================================
166
+ /** Update this agent's presence data (protocol version auto-injected) */
167
+ setPresence(data) {
168
+ this._presence = { protocol: AGENTS_PROTOCOL_VERSION, ...data };
169
+ this._log(`updating presence in room ${this.name}`);
170
+ this._roomContext.setPresence({ ...this._presence, __scope: this._appName });
171
+ }
172
+ /** Fetch current presence snapshot for this room */
173
+ async fetchPresence() {
174
+ try {
175
+ const actors = await this._roomContext.fetchPresence();
176
+ return (actors || []).map((a) => this._toConnectedAgent(a));
177
+ }
178
+ catch {
179
+ return [];
180
+ }
181
+ }
182
+ /** Get the underlying RoomContext for advanced usage */
183
+ get context() {
184
+ return this._roomContext;
185
+ }
186
+ // ============================================================
187
+ // PUBLISH (with automatic agentId injection)
188
+ // ============================================================
189
+ /** Publish to the tasks topic */
190
+ publishTask(envelope) {
191
+ // Auto-set createdBy if not set
192
+ if (!envelope.createdBy) {
193
+ envelope.createdBy = this.agentId;
194
+ }
195
+ this._publish(TOPIC_TASKS, envelope);
196
+ }
197
+ /** Publish to the results topic — directed to the dispatcher via filter when replyTo is set */
198
+ publishResult(envelope) {
199
+ // Auto-set completedBy if not set
200
+ if (!envelope.completedBy) {
201
+ envelope.completedBy = this.agentId;
202
+ }
203
+ if (envelope.replyTo) {
204
+ this._publish(TOPIC_RESULTS, envelope, { filter: envelope.replyTo });
205
+ }
206
+ else {
207
+ // Legacy: no reply address — unfiltered publish (only reaches
208
+ // wildcard subscribers, i.e. pre-0.2.0 SDKs)
209
+ this._publish(TOPIC_RESULTS, envelope);
210
+ }
211
+ }
212
+ /** Publish to the state topic (retained) */
213
+ publishState(data) {
214
+ // Auto-set updatedBy if not set
215
+ if (!data.updatedBy) {
216
+ data.updatedBy = this.agentId;
217
+ }
218
+ this._publish(TOPIC_STATE, data, { retain: true });
219
+ }
220
+ /** Publish to the events topic */
221
+ publishEvent(data) {
222
+ // Auto-set emittedBy if not set
223
+ if (!data.emittedBy) {
224
+ data.emittedBy = this.agentId;
225
+ }
226
+ this._publish(TOPIC_EVENTS, data);
227
+ }
228
+ /** Publish to the inbox topic */
229
+ publishInbox(data) {
230
+ this._publish(TOPIC_INBOX, data);
231
+ }
232
+ /**
233
+ * Publish a tool message.
234
+ * Requests go to the tools topic (load-balanced one-of-N across server
235
+ * replicas). Responses are directed to the requester on the results topic
236
+ * via filter — never load-balanced, never broadcast.
237
+ */
238
+ publishTools(data) {
239
+ if (data?.type === "tool_response" && typeof data.replyTo === "string" && data.replyTo) {
240
+ this._publish(TOPIC_RESULTS, data, { filter: data.replyTo });
241
+ return;
242
+ }
243
+ this._publish(TOPIC_TOOLS, data);
244
+ }
245
+ /** Publish to the approval topic (retained) */
246
+ publishApproval(data) {
247
+ this._publish(TOPIC_APPROVAL, data, { retain: true });
248
+ }
249
+ // ============================================================
250
+ // INTERNAL (called by NoLagAgents)
251
+ // ============================================================
252
+ /** @internal Re-apply local presence after a reconnect (core does not restore it) */
253
+ _updateLocalPresence() {
254
+ if (this._presence) {
255
+ this._roomContext.setPresence({ ...this._presence, __scope: this._appName });
256
+ }
257
+ }
258
+ /** @internal Route a presence:join event in from the parent */
259
+ _handlePresenceJoin(actorId, data) {
260
+ const d = data || {};
261
+ const agent = {
262
+ actorId,
263
+ name: d.name || actorId,
264
+ role: d.role || "agent",
265
+ capabilities: d.capabilities || [],
266
+ metadata: d.metadata,
267
+ connectedAt: Date.now(),
268
+ protocol: typeof d.protocol === "number" ? d.protocol : 1,
269
+ };
270
+ this._agents.set(actorId, agent);
271
+ this._log(`agent joined room ${this.name}:`, agent.name, agent.capabilities);
272
+ this.emit("presenceJoin", actorId, d);
273
+ }
274
+ /** @internal Route a presence:leave event in from the parent */
275
+ _handlePresenceLeave(actorId) {
276
+ const agent = this._agents.get(actorId);
277
+ this._agents.delete(actorId);
278
+ this._log(`agent left room ${this.name}:`, agent?.name || actorId);
279
+ this.emit("presenceLeave", actorId);
280
+ }
281
+ /** @internal Route a presence:update event in from the parent */
282
+ _handlePresenceUpdate(actorId, data) {
283
+ const d = data || {};
284
+ const existing = this._agents.get(actorId);
285
+ const agent = {
286
+ actorId,
287
+ name: d.name || existing?.name || actorId,
288
+ role: d.role || existing?.role || "agent",
289
+ capabilities: d.capabilities || existing?.capabilities || [],
290
+ metadata: d.metadata || existing?.metadata,
291
+ connectedAt: existing?.connectedAt || Date.now(),
292
+ protocol: typeof d.protocol === "number" ? d.protocol : (existing?.protocol ?? 1),
293
+ };
294
+ this._agents.set(actorId, agent);
295
+ this.emit("presenceUpdate", actorId, d);
296
+ }
297
+ /**
298
+ * @internal Unsubscribe topics (when connected) and remove exactly this
299
+ * room's handler refs. Handler-specific removal only: the client may be
300
+ * shared, and a bare off(topic) would strip other consumers' handlers too.
301
+ */
302
+ _cleanup() {
303
+ this._log(`room cleanup: ${this.name}`);
304
+ // Server unsubscribes need a live socket; skip when disconnected
305
+ // (best-effort — the core would no-op with an error callback anyway).
306
+ if (this._isConnected()) {
307
+ const topics = new Set(this._topicHandlers.map((t) => t.topic));
308
+ for (const topic of topics) {
309
+ this._roomContext.unsubscribe(topic);
310
+ }
311
+ }
312
+ for (const { topic, handler } of this._topicHandlers) {
313
+ this._roomContext.off(topic, handler);
314
+ }
315
+ this._topicHandlers = [];
316
+ this._agents.clear();
317
+ this.removeAllListeners();
318
+ }
319
+ // ============================================================
320
+ // INTERNALS
321
+ // ============================================================
322
+ _on(topic, handler) {
323
+ this._topicHandlers.push({ topic, handler });
324
+ this._roomContext.on(topic, handler);
325
+ }
326
+ _publish(topic, data, options) {
327
+ this._log(`publish to ${topic} in room ${this.name}`);
328
+ if (options) {
329
+ this._roomContext.emit(topic, data, options);
330
+ }
331
+ else {
332
+ this._roomContext.emit(topic, data);
333
+ }
334
+ }
335
+ _toConnectedAgent(actor) {
336
+ const presence = (actor.presence || actor.data || {});
337
+ return {
338
+ actorId: actor.actorTokenId || actor.actorId || "",
339
+ name: presence.name || actor.actorTokenId || "",
340
+ role: presence.role || "agent",
341
+ capabilities: presence.capabilities || [],
342
+ metadata: presence.metadata,
343
+ connectedAt: actor.joinedAt || Date.now(),
344
+ protocol: typeof presence.protocol === "number" ? presence.protocol : 1,
345
+ status: actor.status,
346
+ };
347
+ }
348
+ async _fetchInitialPresence() {
349
+ try {
350
+ const actors = await this._roomContext.fetchPresence();
351
+ if (Array.isArray(actors)) {
352
+ for (const actor of actors) {
353
+ const connected = this._toConnectedAgent(actor);
354
+ if (connected.actorId) {
355
+ this._agents.set(connected.actorId, connected);
356
+ }
357
+ }
358
+ this._log(`discovered ${this._agents.size} agents in room ${this.name}`);
359
+ }
360
+ }
361
+ catch {
362
+ // fetchPresence may not be available yet
363
+ }
364
+ }
365
+ _wireTopicListeners() {
366
+ // Work distribution topics honour the connection-level loadBalance
367
+ // setting, so a pool shares each message one-of-N (no double handling):
368
+ // - tasks: each task goes to exactly one worker in the group
369
+ // - tools: each tool REQUEST goes to exactly one tool-server replica
370
+ this._roomContext.subscribe(TOPIC_TASKS);
371
+ this._roomContext.subscribe(TOPIC_TOOLS);
372
+ // Replies are DIRECTED, not broadcast: the results topic carries task
373
+ // results and tool responses published with `filter: <recipient agentId>`,
374
+ // and each agent subscribes only to its own filter sub-topic. The broker
375
+ // routes each reply straight to the requester — no fan-out waste, and
376
+ // immune to load-balance groups (a broadcast or LB'd reply could land on
377
+ // a group member that doesn't hold the pending correlation, timing out
378
+ // the requester even though the responder did the work).
379
+ this._roomContext.subscribe(TOPIC_RESULTS, {
380
+ loadBalance: false,
381
+ filters: [this.agentId],
382
+ });
383
+ // Broadcast topics must always fan out, even when the connection enables
384
+ // loadBalance for work distribution: state/events are broadcasts by
385
+ // nature; inbox and approval messages are claimed client-side.
386
+ const broadcastTopics = [TOPIC_STATE, TOPIC_EVENTS, TOPIC_INBOX, TOPIC_APPROVAL];
387
+ for (const topic of broadcastTopics) {
388
+ this._roomContext.subscribe(topic, { loadBalance: false });
389
+ }
390
+ // Simple 1:1 mappings
391
+ const simpleMap = [
392
+ { topic: TOPIC_TASKS, event: "task" },
393
+ { topic: TOPIC_STATE, event: "stateChange" },
394
+ { topic: TOPIC_EVENTS, event: "event" },
395
+ { topic: TOPIC_INBOX, event: "inbox" },
396
+ ];
397
+ for (const { topic, event } of simpleMap) {
398
+ this._on(topic, (data) => {
399
+ this._log(`received ${topic} in room ${this.name}`);
400
+ this.emit(event, data);
401
+ });
402
+ }
403
+ // Multiplexed: results topic carries task results AND tool responses,
404
+ // both filter-directed to this agent.
405
+ this._on(TOPIC_RESULTS, (data) => {
406
+ this._log(`received ${TOPIC_RESULTS} in room ${this.name}`);
407
+ if (data?.type === "tool_response") {
408
+ this.emit("toolResponse", data);
409
+ }
410
+ else {
411
+ this.emit("result", data);
412
+ }
413
+ });
414
+ // Multiplexed: approval topic carries requests + responses
415
+ this._on(TOPIC_APPROVAL, (data) => {
416
+ this._log(`received ${TOPIC_APPROVAL} in room ${this.name}`);
417
+ if (data?.type === "approval_response") {
418
+ this.emit("approvalResponse", data);
419
+ }
420
+ else {
421
+ this.emit("approvalRequest", data);
422
+ }
423
+ });
424
+ // Tools topic carries requests; tool_response is still accepted here for
425
+ // backward compatibility with responders on older SDK versions (their
426
+ // responses are only reliable when the requester is not load-balanced).
427
+ this._on(TOPIC_TOOLS, (data) => {
428
+ this._log(`received ${TOPIC_TOOLS} in room ${this.name}`);
429
+ if (data?.type === "tool_response") {
430
+ this.emit("toolResponse", data);
431
+ }
432
+ else {
433
+ this.emit("toolRequest", data);
434
+ }
435
+ });
436
+ }
437
+ }
438
+
439
+ /**
440
+ * Generate a unique ID.
441
+ * Uses crypto.randomUUID when available, falls back to a simple random string.
442
+ */
443
+ function generateId() {
444
+ if (typeof crypto !== "undefined" &&
445
+ typeof crypto.randomUUID === "function") {
446
+ return crypto.randomUUID();
447
+ }
448
+ return "xxxx-xxxx-xxxx-xxxx".replace(/x/g, () => Math.floor(Math.random() * 16).toString(16));
449
+ }
450
+ /**
451
+ * Create a debug logger that only logs when enabled.
452
+ */
453
+ function createLogger(prefix, enabled) {
454
+ if (!enabled) {
455
+ return (..._args) => { };
456
+ }
457
+ return (...args) => {
458
+ console.log(`[${prefix}]`, ...args);
459
+ };
460
+ }
461
+ /**
462
+ * Create a Unix millisecond timestamp.
463
+ */
464
+ function createTimestamp() {
465
+ return Date.now();
466
+ }
467
+ // ============ Wrapper registry ============
468
+ // One wrapper instance per (client, appName): two wrappers sharing an app on
469
+ // one connection would collide on topics, presence and the lobby.
470
+ // Warn (not throw): HMR and tests legitimately construct before disposing.
471
+ const wrapperRegistry = new WeakMap();
472
+ /** Register a wrapper against a client + appName; warns on collision. */
473
+ function registerWrapper(client, appName, wrapperName) {
474
+ let apps = wrapperRegistry.get(client);
475
+ if (!apps) {
476
+ apps = new Map();
477
+ wrapperRegistry.set(client, apps);
478
+ }
479
+ const existing = apps.get(appName);
480
+ if (existing) {
481
+ console.warn(`[${wrapperName}] Another wrapper (${existing}) is already attached to this client for app "${appName}". ` +
482
+ `Use one wrapper per (client, app) — detach the other instance first.`);
483
+ }
484
+ apps.set(appName, wrapperName);
485
+ }
486
+ /** Release a wrapper's (client, appName) registration on detach. */
487
+ function releaseWrapper(client, appName) {
488
+ wrapperRegistry.get(client)?.delete(appName);
489
+ }
490
+
491
+ /**
492
+ * NoLagAgents — high-level agent coordination SDK built on @nolag/js-sdk.
493
+ *
494
+ * Provides typed rooms for multi-agent patterns: Handoff, Blackboard,
495
+ * Inbox, Tools, Approval, and Observe.
496
+ *
497
+ * The wrapper NEVER manages the connection. The app owns one core NoLag
498
+ * client (shared by any number of wrappers on distinct apps) and the
499
+ * wrapper attaches to it at construction and releases it via `detach()`.
500
+ *
501
+ * @example
502
+ * ```typescript
503
+ * import { NoLag } from '@nolag/js-sdk';
504
+ * import { NoLagAgents } from '@nolag/agents';
505
+ *
506
+ * const client = NoLag(async () => (await (await fetch('/api/nolag-token')).json()).token);
507
+ * const agents = new NoLagAgents({
508
+ * client,
509
+ * appName: 'my-workflow',
510
+ * agentId: 'worker-1',
511
+ * presence: { name: 'worker-1', role: 'agent', capabilities: ['summarize'] },
512
+ * });
513
+ *
514
+ * await client.connect(); // the app owns the connection
515
+ * await agents.ready(); // wrapper setup done (identity, rooms, lobby)
516
+ *
517
+ * const room = agents.room('default-workflow');
518
+ * room.on('task', (task) => console.log('New task:', task));
519
+ *
520
+ * agents.detach(); // wrapper releases its handlers and topics
521
+ * client.disconnect(); // the app closes the socket
522
+ * ```
523
+ */
524
+ class NoLagAgents extends EventEmitter {
525
+ constructor(options) {
526
+ super();
527
+ this._rooms = new Map();
528
+ this._lobby = null;
529
+ // Lifecycle: one setup run per connection epoch; detach is terminal.
530
+ this._epoch = 0;
531
+ this._detached = false;
532
+ this._isReady = false;
533
+ this._lobbyRefreshTimer = null;
534
+ // Stored client handler refs. INVARIANT: every client.on() below has a
535
+ // matching client.off() in detach() — never bare off(event), never inline
536
+ // closures on the client.
537
+ this._onConnectRef = () => this._onConnect();
538
+ this._onDisconnectRef = (reason) => {
539
+ this._log("disconnected:", reason);
540
+ this.emit("disconnected", reason);
541
+ };
542
+ this._onReconnectRef = () => {
543
+ this._log("reconnecting...");
544
+ this.emit("reconnecting");
545
+ };
546
+ this._onErrorRef = (error) => {
547
+ this._log("error:", error?.message ?? error);
548
+ this.emit("error", error);
549
+ };
550
+ this._onPresenceJoinRef = (data) => this._handleRoomPresenceJoin(data);
551
+ this._onPresenceLeaveRef = (data) => this._handleRoomPresenceLeave(data);
552
+ this._onPresenceUpdateRef = (data) => this._handleRoomPresenceUpdate(data);
553
+ this._onLobbyJoinRef = (data) => this._handleLobbyJoin(data);
554
+ this._onLobbyLeaveRef = (data) => this._handleLobbyLeave(data);
555
+ this._onLobbyUpdateRef = (data) => this._handleLobbyUpdate(data);
556
+ if (!options?.client) {
557
+ throw new TypeError("NoLagAgents requires an injected NoLag client: new NoLagAgents({ client, ... })");
558
+ }
559
+ this._client = options.client;
560
+ this._options = {
561
+ appName: options.appName ?? DEFAULT_APP_NAME,
562
+ agentId: options.agentId ?? generateId(),
563
+ name: options.name,
564
+ role: options.role,
565
+ debug: options.debug ?? false,
566
+ rooms: options.rooms ?? [DEFAULT_ROOM],
567
+ lobby: options.lobby,
568
+ presence: options.presence ?? this._presenceFromIdentity(options),
569
+ };
570
+ this._log = createLogger("NoLagAgents", this._options.debug);
571
+ this._readyPromise = new Promise((resolve, reject) => {
572
+ this._readyResolve = resolve;
573
+ this._readyReject = reject;
574
+ });
575
+ // ready() rejection is only meaningful to callers that await it
576
+ this._readyPromise.catch(() => { });
577
+ registerWrapper(this._client, this._options.appName, "NoLagAgents");
578
+ // Construction = attach: wire everything now, with stored refs.
579
+ this._client.on("connect", this._onConnectRef);
580
+ this._client.on("disconnect", this._onDisconnectRef);
581
+ this._client.on("reconnect", this._onReconnectRef);
582
+ this._client.on("error", this._onErrorRef);
583
+ this._client.on("presence:join", this._onPresenceJoinRef);
584
+ this._client.on("presence:leave", this._onPresenceLeaveRef);
585
+ this._client.on("presence:update", this._onPresenceUpdateRef);
586
+ this._client.on("lobbyPresence:join", this._onLobbyJoinRef);
587
+ this._client.on("lobbyPresence:leave", this._onLobbyLeaveRef);
588
+ this._client.on("lobbyPresence:update", this._onLobbyUpdateRef);
589
+ // Attach-to-connected: if the client is already authenticated, run setup.
590
+ // The microtask lets the caller wire wrapper event handlers synchronously
591
+ // first; a racing real 'connect' event wins via the epoch guard.
592
+ queueMicrotask(() => {
593
+ if (this._epoch === 0 && !this._detached && this._client.connected) {
594
+ this._onConnect();
595
+ }
596
+ });
597
+ }
598
+ // ============ Public Properties ============
599
+ /** The agent's unique ID */
600
+ get agentId() {
601
+ return this._options.agentId;
602
+ }
603
+ /** Whether the underlying connection is established (connected ≠ ready) */
604
+ get connected() {
605
+ return !this._detached && this._client.connected;
606
+ }
607
+ /** The injected core client (owned by the app, not the wrapper) */
608
+ get client() {
609
+ return this._client;
610
+ }
611
+ /** Map of joined rooms */
612
+ get rooms() {
613
+ return this._rooms;
614
+ }
615
+ // ============ Lifecycle ============
616
+ /**
617
+ * Resolves once the wrapper's first setup completed (identity, configured
618
+ * rooms and — when configured — the lobby ready; equivalently, once
619
+ * 'connected' has fired). Rejects only if detach() is called before that.
620
+ * Client auth failures surface via the app's own `await client.connect()`.
621
+ */
622
+ ready() {
623
+ return this._readyPromise;
624
+ }
625
+ /**
626
+ * Detach from the client: remove every handler this wrapper added,
627
+ * unsubscribe its topics and lobby (when connected), clear state.
628
+ * Terminal and idempotent; never touches the socket. To use agents again,
629
+ * construct a new instance.
630
+ */
631
+ detach() {
632
+ if (this._detached)
633
+ return;
634
+ this._log("detaching...");
635
+ this._detached = true;
636
+ this._epoch++; // aborts any in-flight setup at its next checkpoint
637
+ if (this._lobbyRefreshTimer) {
638
+ clearTimeout(this._lobbyRefreshTimer);
639
+ this._lobbyRefreshTimer = null;
640
+ }
641
+ // Remove all client handlers by stored ref
642
+ this._client.off("connect", this._onConnectRef);
643
+ this._client.off("disconnect", this._onDisconnectRef);
644
+ this._client.off("reconnect", this._onReconnectRef);
645
+ this._client.off("error", this._onErrorRef);
646
+ this._client.off("presence:join", this._onPresenceJoinRef);
647
+ this._client.off("presence:leave", this._onPresenceLeaveRef);
648
+ this._client.off("presence:update", this._onPresenceUpdateRef);
649
+ this._client.off("lobbyPresence:join", this._onLobbyJoinRef);
650
+ this._client.off("lobbyPresence:leave", this._onLobbyLeaveRef);
651
+ this._client.off("lobbyPresence:update", this._onLobbyUpdateRef);
652
+ // Rooms: handler-specific off + connected-gated server unsubscribe
653
+ for (const name of [...this._rooms.keys()]) {
654
+ this._rooms.get(name)._cleanup();
655
+ this._rooms.delete(name);
656
+ }
657
+ // Lobby: server unsubscribe is best-effort and needs a live socket
658
+ if (this._lobby && this._client.connected) {
659
+ try {
660
+ this._lobby.unsubscribe();
661
+ }
662
+ catch {
663
+ /* best-effort */
664
+ }
665
+ }
666
+ this._lobby = null;
667
+ releaseWrapper(this._client, this._options.appName);
668
+ if (!this._isReady) {
669
+ this._readyReject(new Error("NoLagAgents detached before ready"));
670
+ }
671
+ }
672
+ // ============ Private: Epoch Setup ============
673
+ _onConnect() {
674
+ this._epoch++;
675
+ void this._runSetup(this._epoch);
676
+ }
677
+ /**
678
+ * One setup pass per connection epoch. Serves both initial setup (epoch 1)
679
+ * and reconnect restore (epoch > 1). Aborts silently whenever a newer
680
+ * epoch started or the wrapper detached — checked after every await.
681
+ */
682
+ async _runSetup(epoch) {
683
+ const stale = () => epoch !== this._epoch || this._detached;
684
+ this._log(this._isReady ? "restoring after reconnect..." : "setting up...");
685
+ this._log("agentId:", this._options.agentId, "→ actorId:", this._client.actorId);
686
+ if (!this._isReady) {
687
+ // First successful setup: auto-join configured rooms.
688
+ for (const roomName of this._options.rooms) {
689
+ this._joinRoomInternal(roomName);
690
+ }
691
+ }
692
+ else {
693
+ // Reconnect: the core auto-restores topic subscriptions, but not
694
+ // room-scoped presence — re-apply each room's local presence.
695
+ for (const room of this._rooms.values()) {
696
+ room._updateLocalPresence();
697
+ }
698
+ }
699
+ // Lobby is OPTIONAL: only when configured. Subscribe every epoch
700
+ // (idempotent server-side) and diff-hydrate from the returned snapshot —
701
+ // one path for setup and reconnect restore.
702
+ if (this._options.lobby) {
703
+ if (!this._lobby) {
704
+ this._lobby = this._client.setApp(this._options.appName).setLobby(this._options.lobby);
705
+ }
706
+ try {
707
+ const state = await this._lobby.subscribe();
708
+ if (stale())
709
+ return;
710
+ this._diffHydrateLobby(state);
711
+ this._log("lobby subscribed:", this._options.lobby);
712
+ }
713
+ catch (err) {
714
+ if (stale())
715
+ return;
716
+ this._log("lobby subscription failed:", err);
717
+ }
718
+ }
719
+ if (stale())
720
+ return;
721
+ // Ready keys on the first setup that COMPLETES, not on epoch 1: an
722
+ // epoch aborted by a racing reconnect must not strand ready().
723
+ if (!this._isReady) {
724
+ this._isReady = true;
725
+ this._readyResolve();
726
+ this.emit("connected");
727
+ }
728
+ else {
729
+ this.emit("reconnected");
730
+ }
731
+ // Deferred lobby refetch: catches agents who joined during the setup
732
+ // window (only when the lobby is configured).
733
+ if (this._options.lobby) {
734
+ this._scheduleLobbyRefresh(epoch);
735
+ }
736
+ }
737
+ _scheduleLobbyRefresh(epoch) {
738
+ if (this._lobbyRefreshTimer)
739
+ clearTimeout(this._lobbyRefreshTimer);
740
+ this._lobbyRefreshTimer = setTimeout(() => {
741
+ this._lobbyRefreshTimer = null;
742
+ if (epoch !== this._epoch || this._detached || !this._client.connected || !this._lobby) {
743
+ return;
744
+ }
745
+ this._lobby
746
+ .fetchPresence()
747
+ .then((state) => {
748
+ if (epoch !== this._epoch || this._detached)
749
+ return;
750
+ this._diffHydrateLobby(state);
751
+ })
752
+ .catch(() => {
753
+ /* best-effort */
754
+ });
755
+ }, LOBBY_REFRESH_DELAY_MS);
756
+ }
757
+ // ============ Room Management ============
758
+ /**
759
+ * Get or create an AgentRoom wrapper.
760
+ * If the room hasn't been joined yet, it will be joined automatically.
761
+ */
762
+ room(name) {
763
+ this._assertUsable();
764
+ const existing = this._rooms.get(name);
765
+ if (existing)
766
+ return existing;
767
+ return this._joinRoomInternal(name);
768
+ }
769
+ // ============ Lobby (cross-room presence observation) ============
770
+ /**
771
+ * Subscribe to a lobby for cross-room presence observation. Lobby presence
772
+ * events are forwarded into all AgentRooms. Prefer the `lobby` constructor
773
+ * option — this method is for on-demand subscription after ready.
774
+ *
775
+ * Returns the initial presence snapshot.
776
+ */
777
+ async subscribeLobby(lobbySlug) {
778
+ this._assertUsable();
779
+ this._log(`subscribing to lobby: ${lobbySlug}`);
780
+ this._options.lobby = lobbySlug;
781
+ if (!this._lobby) {
782
+ this._lobby = this._client.setApp(this._options.appName).setLobby(lobbySlug);
783
+ }
784
+ try {
785
+ const state = await this._lobby.subscribe();
786
+ if (!this._detached)
787
+ this._diffHydrateLobby(state);
788
+ return state || {};
789
+ }
790
+ catch (err) {
791
+ this._log("lobby subscription failed:", err);
792
+ return {};
793
+ }
794
+ }
795
+ // ============ Private: Guards ============
796
+ _assertUsable() {
797
+ if (this._detached) {
798
+ throw new Error("NoLagAgents has been detached — construct a new instance");
799
+ }
800
+ if (!this._isReady) {
801
+ throw new Error('NoLagAgents not ready — await ready() or the "connected" event');
802
+ }
803
+ }
804
+ // ============ Private: Room Setup ============
805
+ _joinRoomInternal(name) {
806
+ this._log(`joining room: ${name}`);
807
+ const roomContext = this._client.setApp(this._options.appName).setRoom(name);
808
+ const room = new AgentRoom(name, roomContext, createLogger(`AgentRoom:${name}`, this._options.debug), this._options.agentId, this._options.appName, () => this._client.connected, this._options.presence);
809
+ this._rooms.set(name, room);
810
+ return room;
811
+ }
812
+ // ============ Private: Scope Filtering ============
813
+ /**
814
+ * On a shared client, presence events from other apps' wrappers arrive on
815
+ * the same connection-level events. Wrappers stamp their presence with a
816
+ * `__scope` (their appName); a mismatched tag means another app's data.
817
+ * Untagged presence is accepted (older peers in this same app).
818
+ */
819
+ _foreignScope(data) {
820
+ const scope = data?.__scope;
821
+ return typeof scope === "string" && scope !== this._options.appName;
822
+ }
823
+ // ============ Private: Room Presence → Rooms ============
824
+ _handleRoomPresenceJoin(data) {
825
+ if (data.actorTokenId === this._client.actorId)
826
+ return;
827
+ const presence = (data.presence || {});
828
+ if (this._foreignScope(presence))
829
+ return;
830
+ const roomId = data.roomId;
831
+ for (const room of this._targetRooms(roomId)) {
832
+ room._handlePresenceJoin(data.actorTokenId, presence);
833
+ }
834
+ }
835
+ _handleRoomPresenceLeave(data) {
836
+ if (data.actorTokenId === this._client.actorId)
837
+ return;
838
+ const roomId = data.roomId;
839
+ for (const room of this._targetRooms(roomId)) {
840
+ room._handlePresenceLeave(data.actorTokenId);
841
+ }
842
+ }
843
+ _handleRoomPresenceUpdate(data) {
844
+ if (data.actorTokenId === this._client.actorId)
845
+ return;
846
+ const presence = (data.presence || {});
847
+ if (this._foreignScope(presence))
848
+ return;
849
+ const roomId = data.roomId;
850
+ for (const room of this._targetRooms(roomId)) {
851
+ room._handlePresenceUpdate(data.actorTokenId, presence);
852
+ }
853
+ }
854
+ /** Rooms a presence event targets: the named room, or all when unscoped. */
855
+ _targetRooms(roomId) {
856
+ if (roomId && this._rooms.has(roomId))
857
+ return [this._rooms.get(roomId)];
858
+ if (roomId)
859
+ return [];
860
+ return [...this._rooms.values()];
861
+ }
862
+ // ============ Private: Lobby → Rooms ============
863
+ _handleLobbyJoin(event) {
864
+ const { actorId, data } = event;
865
+ if (actorId === this._client.actorId)
866
+ return;
867
+ const presence = (data || {});
868
+ if (this._foreignScope(presence))
869
+ return;
870
+ this._log(`lobby presence:join — ${presence.name || actorId}`);
871
+ for (const room of this._rooms.values()) {
872
+ room._handlePresenceJoin(actorId, presence);
873
+ }
874
+ }
875
+ _handleLobbyLeave(event) {
876
+ const { actorId, data } = event;
877
+ if (actorId === this._client.actorId)
878
+ return;
879
+ const presence = (data || {});
880
+ if (this._foreignScope(presence))
881
+ return;
882
+ this._log(`lobby presence:leave — ${actorId}`);
883
+ for (const room of this._rooms.values()) {
884
+ room._handlePresenceLeave(actorId);
885
+ }
886
+ }
887
+ _handleLobbyUpdate(event) {
888
+ const { actorId, data } = event;
889
+ if (actorId === this._client.actorId)
890
+ return;
891
+ const presence = (data || {});
892
+ if (this._foreignScope(presence))
893
+ return;
894
+ for (const room of this._rooms.values()) {
895
+ room._handlePresenceUpdate(actorId, presence);
896
+ }
897
+ }
898
+ /**
899
+ * Reconcile the rooms' agent registries against a fresh lobby snapshot,
900
+ * routing each present actor in as a join. One path for initial hydration,
901
+ * reconnect restore, and the deferred refetch.
902
+ */
903
+ _diffHydrateLobby(state) {
904
+ for (const roomId of Object.keys(state)) {
905
+ const roomPresence = state[roomId];
906
+ for (const actorId of Object.keys(roomPresence)) {
907
+ if (actorId === this._client.actorId)
908
+ continue;
909
+ const raw = roomPresence[actorId];
910
+ // Server returns full actor records with presence nested under .presence
911
+ const presence = (raw?.presence ?? raw);
912
+ if (this._foreignScope(presence))
913
+ continue;
914
+ for (const room of this._rooms.values()) {
915
+ room._handlePresenceJoin(actorId, presence);
916
+ }
917
+ }
918
+ }
919
+ }
920
+ // ============ Private: Helpers ============
921
+ /** Derive presence identity from name/role options when no presence given. */
922
+ _presenceFromIdentity(options) {
923
+ if (!options.name && !options.role)
924
+ return undefined;
925
+ return {
926
+ name: options.name ?? (options.agentId ?? "agent"),
927
+ role: options.role ?? "agent",
928
+ };
929
+ }
930
+ }
931
+
932
+ /**
933
+ * IncompatibleProtocolError — thrown when an operation would deterministically
934
+ * fail because every relevant counterpart runs an older agents-protocol
935
+ * (pre-directed-replies). Failing fast beats burning the correlation timeout.
936
+ */
937
+ class IncompatibleProtocolError extends Error {
938
+ constructor(operation, agents) {
939
+ const list = agents.map((a) => `${a.name} (protocol ${a.protocol})`).join(", ");
940
+ super(`${operation} cannot succeed: every relevant agent advertises agents-protocol < 2 ` +
941
+ `[${list}]. Protocol >= 2 responders direct replies to the requester; older ones ` +
942
+ `broadcast and their replies never reach this SDK's filtered subscription. ` +
943
+ `Upgrade the responders to @nolag/agents >= 0.2.0 / nolag-agents >= 0.3.0. ` +
944
+ `NOTE: 0.2.x/0.3.0 responders DO have directed replies but do not yet advertise ` +
945
+ `protocol — if your responders run those versions, pass { allowLegacyResponders: true }.`);
946
+ this.name = "IncompatibleProtocolError";
947
+ }
948
+ }
949
+
950
+ /**
951
+ * CorrelationManager — maps correlationIds to pending promises with timeout.
952
+ * Used by Handoff and Tools patterns for request/response correlation.
953
+ */
954
+ class CorrelationManager {
955
+ constructor() {
956
+ this._pending = new Map();
957
+ }
958
+ /**
959
+ * Register a pending correlation. Returns a promise that resolves
960
+ * when `resolve()` is called with the matching correlationId.
961
+ */
962
+ register(correlationId, timeoutMs, context) {
963
+ return new Promise((resolve, reject) => {
964
+ let timer = null;
965
+ if (timeoutMs && timeoutMs > 0) {
966
+ timer = setTimeout(() => {
967
+ this._pending.delete(correlationId);
968
+ // Context turns an opaque correlation id into an actionable error —
969
+ // callers supply what they were waiting for and the likely causes.
970
+ const what = context ?? `Correlation ${correlationId}`;
971
+ reject(new Error(`${what} timed out after ${timeoutMs}ms`));
972
+ }, timeoutMs);
973
+ }
974
+ this._pending.set(correlationId, { resolve, reject, timer });
975
+ });
976
+ }
977
+ /**
978
+ * Resolve a pending correlation with a value.
979
+ * Returns true if the correlationId was found and resolved.
980
+ */
981
+ resolve(correlationId, value) {
982
+ const entry = this._pending.get(correlationId);
983
+ if (!entry)
984
+ return false;
985
+ if (entry.timer)
986
+ clearTimeout(entry.timer);
987
+ this._pending.delete(correlationId);
988
+ entry.resolve(value);
989
+ return true;
990
+ }
991
+ /**
992
+ * Reject a pending correlation with an error.
993
+ */
994
+ reject(correlationId, error) {
995
+ const entry = this._pending.get(correlationId);
996
+ if (!entry)
997
+ return false;
998
+ if (entry.timer)
999
+ clearTimeout(entry.timer);
1000
+ this._pending.delete(correlationId);
1001
+ entry.reject(error);
1002
+ return true;
1003
+ }
1004
+ /**
1005
+ * Check if a correlationId is pending.
1006
+ */
1007
+ has(correlationId) {
1008
+ return this._pending.has(correlationId);
1009
+ }
1010
+ /**
1011
+ * Cancel all pending correlations.
1012
+ */
1013
+ clear() {
1014
+ for (const [id, entry] of this._pending) {
1015
+ if (entry.timer)
1016
+ clearTimeout(entry.timer);
1017
+ entry.reject(new Error(`Correlation ${id} cancelled`));
1018
+ }
1019
+ this._pending.clear();
1020
+ }
1021
+ get size() {
1022
+ return this._pending.size;
1023
+ }
1024
+ }
1025
+
1026
+ function createTaskEnvelope(capability, payload, options) {
1027
+ return {
1028
+ type: "task",
1029
+ protocol: AGENTS_PROTOCOL_VERSION,
1030
+ taskId: generateId(),
1031
+ correlationId: generateId(),
1032
+ replyTo: options?.replyTo,
1033
+ capability,
1034
+ payload,
1035
+ tags: options?.tags,
1036
+ priority: options?.priority ?? "medium",
1037
+ metadata: options?.metadata,
1038
+ createdAt: createTimestamp(),
1039
+ createdBy: options?.createdBy,
1040
+ timeout: options?.timeout,
1041
+ };
1042
+ }
1043
+ function createResultEnvelope(taskId, correlationId, status, payload, error, completedBy, replyTo) {
1044
+ return {
1045
+ type: "result",
1046
+ protocol: AGENTS_PROTOCOL_VERSION,
1047
+ correlationId,
1048
+ taskId,
1049
+ status,
1050
+ payload,
1051
+ error,
1052
+ completedAt: createTimestamp(),
1053
+ completedBy,
1054
+ replyTo,
1055
+ };
1056
+ }
1057
+ function createStateEnvelope(key, value, version, updatedBy) {
1058
+ return {
1059
+ type: "state",
1060
+ protocol: AGENTS_PROTOCOL_VERSION,
1061
+ key,
1062
+ value,
1063
+ version,
1064
+ updatedBy,
1065
+ updatedAt: createTimestamp(),
1066
+ };
1067
+ }
1068
+ function createEventEnvelope(category, emittedBy, payload, severity = "info") {
1069
+ return {
1070
+ type: "event",
1071
+ protocol: AGENTS_PROTOCOL_VERSION,
1072
+ eventId: generateId(),
1073
+ severity,
1074
+ category,
1075
+ emittedBy,
1076
+ payload,
1077
+ timestamp: createTimestamp(),
1078
+ };
1079
+ }
1080
+ function createApprovalRequest(action, context, requestedBy, options) {
1081
+ return {
1082
+ type: "approval_request",
1083
+ protocol: AGENTS_PROTOCOL_VERSION,
1084
+ requestId: generateId(),
1085
+ correlationId: generateId(),
1086
+ action,
1087
+ context,
1088
+ urgency: options?.urgency ?? "medium",
1089
+ requestedBy,
1090
+ requestedAt: createTimestamp(),
1091
+ expiresAt: options?.expiresAt,
1092
+ };
1093
+ }
1094
+ function createApprovalResponse(requestId, correlationId, decision, respondedBy, reason) {
1095
+ return {
1096
+ type: "approval_response",
1097
+ protocol: AGENTS_PROTOCOL_VERSION,
1098
+ requestId,
1099
+ correlationId,
1100
+ decision,
1101
+ respondedBy,
1102
+ reason,
1103
+ respondedAt: createTimestamp(),
1104
+ };
1105
+ }
1106
+ function createToolRequest(toolName, args, requestedBy, options) {
1107
+ return {
1108
+ type: "tool_request",
1109
+ protocol: AGENTS_PROTOCOL_VERSION,
1110
+ requestId: generateId(),
1111
+ correlationId: generateId(),
1112
+ replyTo: options?.replyTo,
1113
+ toolName,
1114
+ arguments: args,
1115
+ requestedBy,
1116
+ requestedAt: createTimestamp(),
1117
+ };
1118
+ }
1119
+ function createToolResponse(requestId, correlationId, status, result, error, respondedBy, replyTo) {
1120
+ return {
1121
+ type: "tool_response",
1122
+ protocol: AGENTS_PROTOCOL_VERSION,
1123
+ requestId,
1124
+ correlationId,
1125
+ status,
1126
+ result,
1127
+ error,
1128
+ respondedBy,
1129
+ respondedAt: createTimestamp(),
1130
+ replyTo,
1131
+ };
1132
+ }
1133
+
1134
+ /**
1135
+ * Handoff pattern — dispatch tasks to agents and receive results.
1136
+ *
1137
+ * Orchestrators use `dispatch()` to send work. The SDK checks if any
1138
+ * connected agent has the requested capability (via presence-based
1139
+ * service discovery) before dispatching.
1140
+ *
1141
+ * Workers use `onTask()` with a capabilities filter — they only receive
1142
+ * tasks matching their registered capabilities.
1143
+ *
1144
+ * @example
1145
+ * ```typescript
1146
+ * // Orchestrator
1147
+ * const handoff = new Handoff(room);
1148
+ * const result = await handoff.dispatch('summarize', { text }, { waitForResult: true });
1149
+ *
1150
+ * // Worker
1151
+ * const handoff = new Handoff(room);
1152
+ * handoff.onTask(['summarize', 'translate'], async (task, respond) => {
1153
+ * const output = await processTask(task);
1154
+ * respond('success', { output });
1155
+ * });
1156
+ * ```
1157
+ */
1158
+ class Handoff {
1159
+ constructor(room) {
1160
+ this._correlations = new CorrelationManager();
1161
+ this._warnedMixed = false;
1162
+ this._room = room;
1163
+ // Wire result correlation
1164
+ this._room.on("result", (envelope) => {
1165
+ this._correlations.resolve(envelope.correlationId, envelope);
1166
+ });
1167
+ }
1168
+ /**
1169
+ * Dispatch a task to agents with the given capability.
1170
+ *
1171
+ * Uses presence-based service discovery to verify at least one agent
1172
+ * can handle the capability before dispatching. Throws if no capable
1173
+ * agent is connected (unless `allowNoWorkers` is set).
1174
+ */
1175
+ async dispatch(capability, payload, options) {
1176
+ // Service discovery: check if any agent can handle this capability.
1177
+ // Persistent Presence: findAgents includes offline persistent agents, which
1178
+ // the broker wakes on publish — so they satisfy the gate unless requireOnline.
1179
+ if (!options?.allowNoWorkers) {
1180
+ const capable = this._room.findAgents(capability);
1181
+ const usable = options?.requireOnline
1182
+ ? capable.filter((a) => a.status === undefined || a.status === "online")
1183
+ : capable;
1184
+ if (usable.length === 0) {
1185
+ throw new Error(`No ${options?.requireOnline ? "online " : ""}agent with capability "${capability}" is available. ` +
1186
+ `Available capabilities: [${this._room.getAvailableCapabilities().join(', ')}]. ` +
1187
+ `Connected agents: ${this._room.getConnectedAgents().length}. ` +
1188
+ `Use { allowNoWorkers: true } to dispatch anyway.`);
1189
+ }
1190
+ }
1191
+ const envelope = createTaskEnvelope(capability, payload, {
1192
+ ...options,
1193
+ createdBy: options?.createdBy ?? this._room.agentId,
1194
+ // Reply address: workers publish the result filter-directed to this
1195
+ // room's results subscription
1196
+ replyTo: options?.replyTo ?? this._room.agentId,
1197
+ });
1198
+ this._room.publishTask(envelope);
1199
+ if (options?.waitForResult) {
1200
+ // Fail fast when the outcome is deterministic: if capable workers are
1201
+ // visible and ALL advertise agents-protocol < 2, their results cannot
1202
+ // reach this dispatcher's filtered subscription. Mixed pools proceed
1203
+ // with a warning (presence is eventually consistent).
1204
+ const capable = this._room.findAgents(capability);
1205
+ if (!options?.allowLegacyResponders && capable.length > 0) {
1206
+ const modern = capable.filter((a) => a.protocol >= 2);
1207
+ if (modern.length === 0) {
1208
+ throw new IncompatibleProtocolError(`Task '${capability}' dispatch with waitForResult`, capable.map((a) => ({ name: a.name, protocol: a.protocol })));
1209
+ }
1210
+ if (modern.length < capable.length && !this._warnedMixed) {
1211
+ this._warnedMixed = true;
1212
+ console.warn(`[nolag-agents] Capability '${capability}' has workers on agents-protocol < 2: ` +
1213
+ capable.filter((a) => a.protocol < 2).map((a) => a.name).join(", ") +
1214
+ ". Their results may not be delivered — upgrade them.");
1215
+ }
1216
+ }
1217
+ return this._correlations.register(envelope.correlationId, options.timeout, `Task '${capability}' dispatch (${capable.length} capable worker${capable.length === 1 ? "" : "s"} visible). ` +
1218
+ `Likely causes: worker crashed mid-task, worker on agents-protocol < 2 ` +
1219
+ `(results not directed), or the room is not deliverable`);
1220
+ }
1221
+ }
1222
+ onTask(capabilitiesOrHandler, maybeHandler) {
1223
+ // Single-arg form: onTask(handler) receives all tasks
1224
+ const capabilities = typeof capabilitiesOrHandler === "function" ? '*' : capabilitiesOrHandler;
1225
+ const handler = typeof capabilitiesOrHandler === "function" ? capabilitiesOrHandler : maybeHandler;
1226
+ this._room.on("task", (task) => {
1227
+ // Filter by capability unless wildcard
1228
+ if (capabilities !== '*' && !capabilities.includes(task.capability)) {
1229
+ return;
1230
+ }
1231
+ const respond = (status, payload, error) => {
1232
+ const result = createResultEnvelope(task.taskId, task.correlationId, status, payload, error, this._room.agentId,
1233
+ // Direct the result to the dispatcher's filter sub-topic
1234
+ task.replyTo ?? task.createdBy);
1235
+ this._room.publishResult(result);
1236
+ };
1237
+ handler(task, respond);
1238
+ });
1239
+ }
1240
+ /**
1241
+ * Get agents capable of handling a specific task type.
1242
+ * Delegates to the room's presence-based service discovery.
1243
+ */
1244
+ getCapableAgents(capability) {
1245
+ return this._room.findAgents(capability);
1246
+ }
1247
+ /** Cancel all pending correlations */
1248
+ dispose() {
1249
+ this._correlations.clear();
1250
+ }
1251
+ }
1252
+
1253
+ /**
1254
+ * Inbox pattern — per-agent durable message queues.
1255
+ *
1256
+ * Agents send direct messages to other agents via their inbox.
1257
+ * Messages are persisted and replayed on reconnect (requires persistent sessions).
1258
+ */
1259
+ class Inbox {
1260
+ constructor(room, agentId) {
1261
+ this._room = room;
1262
+ this._agentId = agentId;
1263
+ }
1264
+ /**
1265
+ * Send a message to another agent's inbox.
1266
+ */
1267
+ send(to, payload) {
1268
+ const message = {
1269
+ messageId: generateId(),
1270
+ from: this._agentId,
1271
+ to,
1272
+ payload,
1273
+ createdAt: createTimestamp(),
1274
+ };
1275
+ this._room.publishInbox(message);
1276
+ }
1277
+ /**
1278
+ * Register a handler for incoming inbox messages.
1279
+ */
1280
+ onMessage(handler) {
1281
+ this._room.on("inbox", (envelope) => {
1282
+ const msg = envelope;
1283
+ if (msg.to === this._agentId) {
1284
+ handler(msg);
1285
+ }
1286
+ });
1287
+ }
1288
+ }
1289
+
1290
+ /**
1291
+ * Blackboard pattern — shared state across agents.
1292
+ *
1293
+ * Agents read and write key-value pairs visible to all room participants.
1294
+ * Uses retained messages so state is available on join.
1295
+ */
1296
+ class Blackboard {
1297
+ constructor(room, agentId) {
1298
+ this._state = new Map();
1299
+ this._room = room;
1300
+ this._agentId = agentId;
1301
+ this._room.on("stateChange", (envelope) => {
1302
+ this._state.set(envelope.key, envelope);
1303
+ });
1304
+ }
1305
+ /**
1306
+ * Set a shared state value.
1307
+ */
1308
+ set(key, value) {
1309
+ const existing = this._state.get(key);
1310
+ const version = existing ? existing.version + 1 : 1;
1311
+ const envelope = createStateEnvelope(key, value, version, this._agentId);
1312
+ this._state.set(key, envelope);
1313
+ this._room.publishState(envelope);
1314
+ }
1315
+ /**
1316
+ * Get a shared state value.
1317
+ */
1318
+ get(key) {
1319
+ return this._state.get(key)?.value;
1320
+ }
1321
+ /**
1322
+ * Get the full state envelope for a key.
1323
+ */
1324
+ getEnvelope(key) {
1325
+ return this._state.get(key);
1326
+ }
1327
+ /**
1328
+ * Get all state entries.
1329
+ */
1330
+ getAll() {
1331
+ return this._state;
1332
+ }
1333
+ /**
1334
+ * Register a handler for state changes on a specific key.
1335
+ */
1336
+ onChange(key, handler) {
1337
+ this._room.on("stateChange", (envelope) => {
1338
+ if (envelope.key === key) {
1339
+ handler(envelope);
1340
+ }
1341
+ });
1342
+ }
1343
+ }
1344
+
1345
+ /**
1346
+ * Observe pattern — emit and listen to observability events.
1347
+ *
1348
+ * Agents emit structured events; observers/dashboards subscribe to the stream.
1349
+ * Events have severity, category, and emittedBy for filtering.
1350
+ */
1351
+ class Observe {
1352
+ constructor(room, emittedBy) {
1353
+ this._room = room;
1354
+ this._emittedBy = emittedBy;
1355
+ }
1356
+ /**
1357
+ * Emit an observability event.
1358
+ */
1359
+ emit(category, payload, severity = "info") {
1360
+ const envelope = createEventEnvelope(category, this._emittedBy, payload, severity);
1361
+ this._room.publishEvent(envelope);
1362
+ }
1363
+ /**
1364
+ * Listen for events, optionally filtered by category or severity.
1365
+ */
1366
+ on(handler, filter) {
1367
+ this._room.on("event", (envelope) => {
1368
+ if (filter?.category && envelope.category !== filter.category)
1369
+ return;
1370
+ if (filter?.severity && envelope.severity !== filter.severity)
1371
+ return;
1372
+ handler(envelope);
1373
+ });
1374
+ }
1375
+ }
1376
+
1377
+ /**
1378
+ * Approve pattern — human-in-the-loop approval gates.
1379
+ *
1380
+ * Agents request approval before taking actions; humans (or other agents)
1381
+ * approve or reject via the approval topic.
1382
+ */
1383
+ class Approve {
1384
+ constructor(room, agentId) {
1385
+ this._correlations = new CorrelationManager();
1386
+ this._room = room;
1387
+ this._agentId = agentId;
1388
+ // Wire approval response correlation
1389
+ this._room.on("approvalResponse", (envelope) => {
1390
+ this._correlations.resolve(envelope.correlationId, envelope);
1391
+ });
1392
+ }
1393
+ /**
1394
+ * Request approval for an action. Returns the approval response.
1395
+ */
1396
+ async request(action, context, options) {
1397
+ const envelope = createApprovalRequest(action, context, this._agentId, {
1398
+ urgency: options?.urgency,
1399
+ expiresAt: options?.expiresAt,
1400
+ });
1401
+ this._room.publishApproval(envelope);
1402
+ return this._correlations.register(envelope.correlationId, options?.timeout);
1403
+ }
1404
+ /**
1405
+ * Register a handler for incoming approval requests.
1406
+ * The handler receives the request and a respond function.
1407
+ */
1408
+ onRequest(handler) {
1409
+ this._room.on("approvalRequest", (request) => {
1410
+ const respond = (decision, reason) => {
1411
+ const response = createApprovalResponse(request.requestId, request.correlationId, decision, this._agentId, reason);
1412
+ this._room.publishApproval(response);
1413
+ };
1414
+ handler(request, respond);
1415
+ });
1416
+ }
1417
+ /** Cancel all pending correlations */
1418
+ dispose() {
1419
+ this._correlations.clear();
1420
+ }
1421
+ }
1422
+
1423
+ /**
1424
+ * Tools pattern — typed RPC over pub/sub for tool invocations.
1425
+ *
1426
+ * Agents register tool handlers; callers invoke tools and receive
1427
+ * correlated responses.
1428
+ */
1429
+ class Tools {
1430
+ constructor(room, agentId) {
1431
+ this._correlations = new CorrelationManager();
1432
+ this._handlers = new Map();
1433
+ this._warnedMixed = false;
1434
+ this._room = room;
1435
+ this._agentId = agentId;
1436
+ // Wire response correlation
1437
+ this._room.on("toolResponse", (envelope) => {
1438
+ if (!envelope || typeof envelope.correlationId !== "string")
1439
+ return;
1440
+ this._correlations.resolve(envelope.correlationId, envelope);
1441
+ });
1442
+ // Wire request handling
1443
+ this._room.on("toolRequest", async (envelope) => {
1444
+ // The tools topic is an open room surface: anything published there
1445
+ // that is not a tool_response is classified as a request, including
1446
+ // foreign or malformed payloads. A request with no toolName cannot be
1447
+ // routed OR NACKed meaningfully — and it must never be able to crash
1448
+ // the host (this listener is async, so an uncaught throw here becomes
1449
+ // an unhandled rejection that terminates the process).
1450
+ if (!envelope || typeof envelope.toolName !== "string")
1451
+ return;
1452
+ const handler = this._handlers.get(envelope.toolName);
1453
+ // Direct the response back to the requester's filter sub-topic
1454
+ const replyTo = envelope.replyTo ?? envelope.requestedBy;
1455
+ if (!handler) {
1456
+ // Tool requests are load-balanced to EVERY group in the room, so
1457
+ // agents legitimately receive requests meant for other tool servers.
1458
+ // Stay silent unless this agent plausibly owns the tool:
1459
+ // - pure requesters (zero handlers) never answer
1460
+ // - servers answer only within their own namespace (the prefix
1461
+ // before the first '.', e.g. 'backend.*', 'chemistry.*') — a
1462
+ // 'backend.*' server NACKing 'chemistry.analyze' would race and
1463
+ // beat the real chemistry server's response
1464
+ if (!this._ownsNamespace(envelope.toolName))
1465
+ return;
1466
+ // A tool SERVER missing a handler in ITS OWN namespace NACKs instead
1467
+ // of silently ignoring — silence means the requester burns its full
1468
+ // timeout. (Requires homogeneous tool sets within a loadBalanceGroup
1469
+ // — see AGENTS-PROTOCOL.md.)
1470
+ const nack = createToolResponse(envelope.requestId, envelope.correlationId, "error", null, {
1471
+ code: "NO_HANDLER",
1472
+ message: `Agent '${this._agentId}' has no handler for tool '${envelope.toolName}'`,
1473
+ }, this._agentId, replyTo);
1474
+ this._room.publishTools(nack);
1475
+ return;
1476
+ }
1477
+ try {
1478
+ const result = await handler(envelope.arguments);
1479
+ const response = createToolResponse(envelope.requestId, envelope.correlationId, "success", result, undefined, this._agentId, replyTo);
1480
+ this._room.publishTools(response);
1481
+ }
1482
+ catch (err) {
1483
+ const response = createToolResponse(envelope.requestId, envelope.correlationId, "error", null, {
1484
+ code: "TOOL_ERROR",
1485
+ message: err instanceof Error ? err.message : String(err),
1486
+ }, this._agentId, replyTo);
1487
+ this._room.publishTools(response);
1488
+ }
1489
+ });
1490
+ }
1491
+ /**
1492
+ * Register a tool handler.
1493
+ */
1494
+ register(toolName, handler) {
1495
+ this._handlers.set(toolName, handler);
1496
+ }
1497
+ /** True when this agent hosts handlers in the tool's namespace (prefix
1498
+ * before the first '.'); unprefixed tools match any unprefixed handler. */
1499
+ _ownsNamespace(toolName) {
1500
+ // Belt and braces: a nameless tool belongs to nobody.
1501
+ if (typeof toolName !== "string")
1502
+ return false;
1503
+ if (this._handlers.size === 0)
1504
+ return false;
1505
+ const ns = toolName.includes(".") ? toolName.slice(0, toolName.indexOf(".")) : null;
1506
+ for (const name of this._handlers.keys()) {
1507
+ const handlerNs = name.includes(".") ? name.slice(0, name.indexOf(".")) : null;
1508
+ if (handlerNs === ns)
1509
+ return true;
1510
+ }
1511
+ return false;
1512
+ }
1513
+ /**
1514
+ * Invoke a remote tool and wait for the response.
1515
+ */
1516
+ async invoke(toolName, args, options) {
1517
+ // Fail fast when the outcome is deterministic: tool servers are visible
1518
+ // in presence; if some exist and ALL advertise protocol < 2, their
1519
+ // replies cannot reach this requester. Mixed pools proceed with a
1520
+ // warning (presence is eventually consistent — hard-failing on one
1521
+ // stale entry would flake).
1522
+ const servers = this._room
1523
+ .getConnectedAgents()
1524
+ .filter((a) => a.role === "tool-server");
1525
+ if (!options?.allowLegacyResponders && servers.length > 0) {
1526
+ const modern = servers.filter((a) => a.protocol >= 2);
1527
+ if (modern.length === 0) {
1528
+ throw new IncompatibleProtocolError(`Tool '${toolName}' invocation`, servers.map((a) => ({ name: a.name, protocol: a.protocol })));
1529
+ }
1530
+ if (modern.length < servers.length && !this._warnedMixed) {
1531
+ this._warnedMixed = true;
1532
+ console.warn(`[nolag-agents] Room '${this._room.name}' has tool servers on agents-protocol < 2: ` +
1533
+ servers.filter((a) => a.protocol < 2).map((a) => a.name).join(", ") +
1534
+ ". Their replies may not be delivered — upgrade them.");
1535
+ }
1536
+ }
1537
+ // replyTo is the room's agentId — the filter sub-topic this room's
1538
+ // results subscription listens on. (this._agentId may differ when a
1539
+ // caller attributes requests to a logical agent; delivery must use the
1540
+ // address that is actually subscribed.)
1541
+ const envelope = createToolRequest(toolName, args, this._agentId, {
1542
+ replyTo: this._room.agentId,
1543
+ });
1544
+ this._room.publishTools(envelope);
1545
+ const serverCount = servers.length;
1546
+ return this._correlations.register(envelope.correlationId, options?.timeout, `Tool '${toolName}' invocation in room '${this._room.name}' ` +
1547
+ `(${serverCount} tool-server${serverCount === 1 ? "" : "s"} visible). ` +
1548
+ `Likely causes: no agent has this tool registered (pre-0.3.0 responders ` +
1549
+ `don't NACK), the responder is offline, or the room is not deliverable ` +
1550
+ `(watch the room 'error' events)`);
1551
+ }
1552
+ /** Cancel all pending correlations */
1553
+ dispose() {
1554
+ this._correlations.clear();
1555
+ this._handlers.clear();
1556
+ }
1557
+ }
1558
+
1559
+ /** Standard tag prefixes for agent coordination */
1560
+ const TAG_PREFIX = {
1561
+ CAPABILITY: "capability",
1562
+ PRIORITY: "priority",
1563
+ ROLE: "role",
1564
+ SEVERITY: "severity",
1565
+ URGENCY: "urgency",
1566
+ TENANT: "tenant",
1567
+ };
1568
+ /** Boolean flags (used as standalone tags, no prefix) */
1569
+ const TAG_FLAGS = {
1570
+ REQUIRES_HUMAN: "requires_human",
1571
+ REQUIRES_AUDIT: "requires_audit",
1572
+ };
1573
+ /** Helper to create prefixed tags */
1574
+ function tag(prefix, value) {
1575
+ return `${prefix}:${value}`;
1576
+ }
1577
+
1578
+ export { AGENTS_PROTOCOL_VERSION, AgentRoom, Approve, Blackboard, CorrelationManager, EventEmitter, Handoff, Inbox, IncompatibleProtocolError, NoLagAgents, Observe, TAG_FLAGS, TAG_PREFIX, Tools, createApprovalRequest, createApprovalResponse, createEventEnvelope, createResultEnvelope, createStateEnvelope, createTaskEnvelope, createToolRequest, createToolResponse, tag };
1579
+ //# sourceMappingURL=react-native.js.map