@m4trix/core 0.14.0 → 0.15.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.
package/dist/index.cjs CHANGED
@@ -22,715 +22,6 @@ var __privateSet = (obj, member, value, setter) => {
22
22
  return value;
23
23
  };
24
24
 
25
- // src/stream/Pump.ts
26
- var Pump = class _Pump {
27
- constructor(src) {
28
- this.src = src;
29
- }
30
- /**
31
- * Wrap an existing AsyncIterable or Readable stream into a Pump
32
- *
33
- * @template U The type of data in the source stream
34
- * @param source The source stream to convert to a Pump (AsyncIterable, ReadableStream, or NodeJS.ReadableStream)
35
- * @returns A new Pump instance that wraps the source
36
- */
37
- static from(source) {
38
- async function* gen() {
39
- let seq = 0;
40
- function isAsyncIterable(obj) {
41
- return Symbol.asyncIterator in obj;
42
- }
43
- function isWebReadableStream(obj) {
44
- return "getReader" in obj && typeof obj.getReader === "function";
45
- }
46
- function isNodeReadableStream(obj) {
47
- return "pipe" in obj && "on" in obj && typeof obj.pipe === "function" && typeof obj.on === "function";
48
- }
49
- if (isAsyncIterable(source)) {
50
- const iterator = source[Symbol.asyncIterator]();
51
- try {
52
- while (true) {
53
- const result = await iterator.next();
54
- if (result.done)
55
- break;
56
- yield {
57
- sequence: seq++,
58
- data: result.value,
59
- done: false
60
- };
61
- }
62
- } finally {
63
- }
64
- } else if (isWebReadableStream(source)) {
65
- const reader = source.getReader();
66
- try {
67
- while (true) {
68
- const result = await reader.read();
69
- if (result.done)
70
- break;
71
- yield {
72
- sequence: seq++,
73
- data: result.value,
74
- done: false
75
- };
76
- }
77
- } finally {
78
- reader.releaseLock();
79
- }
80
- } else if (isNodeReadableStream(source)) {
81
- try {
82
- for await (const chunk of source) {
83
- yield {
84
- sequence: seq++,
85
- data: chunk,
86
- done: false
87
- };
88
- }
89
- } catch (error) {
90
- console.error("Error reading from Node.js stream:", error);
91
- throw error;
92
- }
93
- }
94
- yield { sequence: seq, data: void 0, done: true };
95
- }
96
- return new _Pump(gen());
97
- }
98
- /**
99
- * Sync or async map over the data portion of each chunk
100
- *
101
- * @template U The output type after transformation
102
- * @param fn The mapping function that transforms each chunk
103
- * @returns A new Pump instance with the transformed data
104
- */
105
- map(fn) {
106
- async function* gen() {
107
- for await (const { sequence, data, done } of this.src) {
108
- if (done) {
109
- const out2 = data !== void 0 ? await fn(data) : void 0;
110
- yield { sequence, data: out2, done };
111
- break;
112
- }
113
- const out = await fn(data);
114
- yield { sequence, data: out, done };
115
- }
116
- }
117
- return new _Pump(gen.call(this));
118
- }
119
- /**
120
- * Stateful map allows processing stream chunks with a persistent context object.
121
- *
122
- * The context is initialized when the first chunk arrives and can be updated with each chunk.
123
- * This is useful for maintaining state across the stream processing.
124
- *
125
- * If you plan to use sockets you should rather opt for asyncStatefulMap.
126
- *
127
- * The pipe closes only after all processing is complete, including any final operations in onClose.
128
- *
129
- * TODO: Un-tested
130
- *
131
- * @param handlers Object containing callback functions for stream processing
132
- * @param handlers.onFirstChunk Function called when the first chunk arrives, initializes the context
133
- * @param handlers.onChunk Function called for each subsequent chunk, updates the context
134
- * @param handlers.onClose Optional function called when the stream closes, allows final processing
135
- * @returns A new Pump instance with transformed data
136
- */
137
- statefulMap(handlers) {
138
- const { src } = this;
139
- const gen = async function* () {
140
- let context;
141
- let initialized = false;
142
- let lastChunk;
143
- let seq = 0;
144
- const queue = [];
145
- const yieldData = (data) => {
146
- queue.push(data);
147
- };
148
- for await (const { data, done } of src) {
149
- if (done) {
150
- if (context && handlers.onClose) {
151
- await handlers.onClose(lastChunk, context, yieldData);
152
- }
153
- while (queue.length > 0) {
154
- yield { sequence: seq++, data: queue.shift(), done: false };
155
- }
156
- yield {
157
- sequence: seq++,
158
- data: void 0,
159
- done: true
160
- };
161
- break;
162
- }
163
- if (!initialized) {
164
- context = await handlers.onFirstChunk(data, yieldData);
165
- initialized = true;
166
- } else if (context) {
167
- context = await handlers.onChunk(data, context, yieldData);
168
- }
169
- lastChunk = data;
170
- while (queue.length > 0) {
171
- yield { sequence: seq++, data: queue.shift(), done: false };
172
- }
173
- }
174
- };
175
- return new _Pump(gen());
176
- }
177
- /**
178
- * Async map means that each incoming chunk is causing an async operation that when it completes
179
- * should yield a new chunk.
180
- * The pipe closes only after you unlock the pipe by using the unlockCloseEvent callback.
181
- *
182
- * Stateful refers to the fact that you can create your own small context object that is passed in the subsequent callbacks.
183
- * This allows you to keep track of things like a socket connection.
184
- *
185
- * Why is this nice? Well if you use things like a socket the pipe might have received the close event,
186
- * before you got any or all of your socket responses. Sockets don't fit into the standard promise pattern,
187
- * which makes it harder to wait for them.
188
- *
189
- * TODO: Un-tested
190
- *
191
- * @param handlers Object containing callback functions for stream processing
192
- * @param handlers.onFirstChunk Function called when the first chunk arrives, initializes the context
193
- * @param handlers.onChunk Function called for each subsequent chunk, updates the context
194
- * @param handlers.onClose Optional function called when the stream closes, allows final processing
195
- * @returns A new Pump instance with transformed data
196
- */
197
- asyncStatefulMap(handlers) {
198
- const { src } = this;
199
- const gen = async function* () {
200
- let context;
201
- let initialized = false;
202
- let lastChunk;
203
- let seq = 0;
204
- let lockedCloseEvent = true;
205
- const queue = [];
206
- const yieldData = (data) => {
207
- queue.push(data);
208
- };
209
- const unlockCloseEvent = () => {
210
- lockedCloseEvent = false;
211
- };
212
- for await (const { data, done } of src) {
213
- if (done) {
214
- if (context && handlers.onClose) {
215
- await handlers.onClose(
216
- lastChunk,
217
- context,
218
- yieldData,
219
- unlockCloseEvent
220
- );
221
- }
222
- const timestamp = Date.now();
223
- while (lockedCloseEvent && Date.now() - timestamp < 1e4) {
224
- while (queue.length > 0) {
225
- yield { sequence: seq++, data: queue.shift(), done: false };
226
- }
227
- await new Promise((resolve) => setTimeout(resolve, 5));
228
- }
229
- while (queue.length > 0) {
230
- yield { sequence: seq++, data: queue.shift(), done: false };
231
- }
232
- yield {
233
- sequence: seq++,
234
- data: void 0,
235
- done: true
236
- };
237
- break;
238
- }
239
- if (!initialized) {
240
- context = await handlers.onFirstChunk(
241
- data,
242
- yieldData,
243
- unlockCloseEvent
244
- );
245
- initialized = true;
246
- } else if (context) {
247
- context = await handlers.onChunk(
248
- data,
249
- context,
250
- yieldData,
251
- unlockCloseEvent
252
- );
253
- }
254
- lastChunk = data;
255
- while (queue.length > 0) {
256
- yield { sequence: seq++, data: queue.shift(), done: false };
257
- }
258
- }
259
- };
260
- return new _Pump(gen());
261
- }
262
- /**
263
- * Filter items based on a predicate
264
- *
265
- * @param predicate A function that determines whether to keep each chunk
266
- * @returns A new Pump instance containing only chunks that passed the predicate
267
- */
268
- filter(predicate) {
269
- async function* gen() {
270
- for await (const { sequence, data, done } of this.src) {
271
- if (done) {
272
- yield { sequence, data, done: true };
273
- break;
274
- }
275
- const keep = await predicate(data);
276
- if (keep) {
277
- yield { sequence, data, done: false };
278
- }
279
- }
280
- }
281
- return new _Pump(gen.call(this));
282
- }
283
- /**
284
- * Bundles (accumulates) chunks together based on a condition rather than a fixed size.
285
- *
286
- * This is useful when you need to group chunks dynamically based on their content or other criteria.
287
- *
288
- * Example: Bundling text chunks with a maximum character limit
289
- *
290
- * Input chunks: ["Hello", " this", " is", " a few", " chunks", " of text"]
291
- * With max size of 10 characters:
292
- * - First bundle: ["Hello", " this"] (10 chars)
293
- * - Second bundle: [" is", " a few"] (8 chars)
294
- * - Third bundle: [" chunks", " of text"] (13 chars)
295
- *
296
- * @param closeBundleCondition - Function that determines when to close the current bundle
297
- * Returns true when the current bundle should be emitted
298
- * Parameters:
299
- * - chunk: The current chunk being processed
300
- * - accumulatedChunks: Array of chunks in the current bundle
301
- *
302
- * @returns A pump that emits arrays of bundled items
303
- */
304
- bundle(closeBundleCondition) {
305
- async function* gen() {
306
- let buffer = [];
307
- let lastSequence = 0;
308
- for await (const { sequence, data, done } of this.src) {
309
- lastSequence = sequence;
310
- if (done) {
311
- if (buffer.length > 0) {
312
- yield { sequence, data: [...buffer], done: false };
313
- }
314
- yield {
315
- sequence: lastSequence,
316
- data: void 0,
317
- done: true
318
- };
319
- break;
320
- }
321
- const shouldClose = await closeBundleCondition(data, buffer);
322
- buffer.push(data);
323
- if (shouldClose) {
324
- yield {
325
- sequence: lastSequence,
326
- data: [...buffer],
327
- done: false
328
- };
329
- buffer = [];
330
- }
331
- }
332
- }
333
- return new _Pump(gen.call(this));
334
- }
335
- /**
336
- * Tap into each chunk without altering it
337
- *
338
- * @param fn A function that receives each chunk but doesn't affect the stream
339
- * @returns The same pump instance with unmodified data
340
- */
341
- onChunk(fn) {
342
- async function* gen() {
343
- for await (const chunk of this.src) {
344
- if (chunk.data === void 0 && chunk.done) {
345
- yield chunk;
346
- }
347
- await fn(chunk.data);
348
- yield chunk;
349
- }
350
- }
351
- return new _Pump(gen.call(this));
352
- }
353
- /**
354
- * Collect all chunks in the stream and run a callback when the stream is done.
355
- * The callback receives an array of all chunks that passed through.
356
- *
357
- * This is useful for analytics, logging, or processing the complete stream history
358
- * after all chunks have been received.
359
- *
360
- * @param fn - Callback function that receives the array of all chunks when the stream is complete
361
- * @returns The same pump, for chaining
362
- */
363
- onClose(fn) {
364
- async function* gen() {
365
- const history = [];
366
- for await (const chunk of this.src) {
367
- if (chunk.data !== void 0) {
368
- history.push(chunk.data);
369
- }
370
- if (chunk.done) {
371
- await fn(history);
372
- }
373
- yield chunk;
374
- }
375
- }
376
- return new _Pump(gen.call(this));
377
- }
378
- /**
379
- * Batch `n` chunks into arrays before emitting
380
- *
381
- * @param n The number of chunks to batch together
382
- * @returns A new Pump instance that emits arrays of batched chunks
383
- */
384
- batch(n) {
385
- async function* gen() {
386
- let buffer = [];
387
- for await (const chunk of this.src) {
388
- if (chunk.done) {
389
- if (chunk.data === void 0) {
390
- yield {
391
- sequence: buffer[0].sequence,
392
- data: buffer.map((c) => c.data),
393
- done: false
394
- };
395
- yield {
396
- sequence: chunk.sequence,
397
- data: void 0,
398
- done: true
399
- };
400
- buffer = [];
401
- } else {
402
- buffer.push(chunk);
403
- yield {
404
- sequence: buffer[0].sequence,
405
- data: buffer.map((c) => c.data),
406
- done: true
407
- };
408
- }
409
- break;
410
- }
411
- buffer.push(chunk);
412
- if (buffer.length === n) {
413
- yield {
414
- sequence: buffer[0].sequence,
415
- data: buffer.map((c) => c.data),
416
- done: chunk.done
417
- };
418
- buffer = [];
419
- }
420
- }
421
- }
422
- return new _Pump(gen.call(this));
423
- }
424
- /**
425
- * If you want to prevent chunk starvation, you can buffer the chunks.
426
- * Chunks will not be bundled into arrays or object but kept as is,
427
- * but the pipeline will not progress at that segment until the buffer is filled up.
428
- * Once a buffer is filled up it will drain and never buffer again.
429
- *
430
- * @param n The number of chunks to buffer before processing continues
431
- * @returns A new Pump instance with buffering behavior
432
- */
433
- buffer(n) {
434
- async function* gen() {
435
- let buffer = [];
436
- let bufferFilled = false;
437
- for await (const chunk of this.src) {
438
- if (!bufferFilled) {
439
- if (!chunk.done) {
440
- buffer.push(chunk);
441
- }
442
- if (buffer.length >= n || chunk.done) {
443
- bufferFilled = true;
444
- for (const bufferedChunk of buffer) {
445
- yield bufferedChunk;
446
- }
447
- if (chunk.done) {
448
- yield {
449
- sequence: chunk.sequence,
450
- data: void 0,
451
- done: true
452
- };
453
- break;
454
- }
455
- buffer = [];
456
- }
457
- } else {
458
- yield chunk;
459
- }
460
- }
461
- for (const bufferedChunk of buffer) {
462
- yield bufferedChunk;
463
- }
464
- }
465
- return new _Pump(gen.call(this));
466
- }
467
- /**
468
- * Rechunk the stream: transform one chunk into zero, one, or many output chunks.
469
- * The handler function receives the current buffer of chunks, a push function to emit new chunks,
470
- * and a flag indicating if this is the last chunk in the stream.
471
- *
472
- * @param handler Function that transforms chunks and pushes new ones
473
- * @returns A new Pump instance with rechunked data
474
- */
475
- rechunk(handler) {
476
- async function* gen() {
477
- let buffer = [];
478
- let seq = 0;
479
- const pending = [];
480
- const push = (chunk) => {
481
- pending.push(chunk);
482
- };
483
- for await (const { data, done } of this.src) {
484
- if (!done) {
485
- if (data !== void 0) {
486
- buffer.push(data);
487
- }
488
- await handler({
489
- buffer,
490
- push,
491
- lastChunk: false,
492
- setBuffer: (b) => {
493
- buffer = b;
494
- }
495
- });
496
- } else {
497
- await handler({
498
- buffer,
499
- push,
500
- lastChunk: true,
501
- setBuffer: (b) => {
502
- buffer = b;
503
- }
504
- });
505
- }
506
- while (pending.length > 0) {
507
- const out = pending.shift();
508
- yield { sequence: seq++, data: out, done: false };
509
- }
510
- if (done) {
511
- break;
512
- }
513
- }
514
- yield { sequence: seq, data: void 0, done: true };
515
- }
516
- return new _Pump(gen.call(this));
517
- }
518
- slidingWindow(size, step, fn) {
519
- async function* gen() {
520
- const history = [];
521
- let offset = 0;
522
- let lastSeq = 0;
523
- function buildWindow(_offset, _size, _history) {
524
- const window = Array(_size).fill(void 0);
525
- let windowIndex = 0;
526
- for (let i = _offset; i > _offset - _size; i -= step) {
527
- if (i >= history.length) {
528
- windowIndex++;
529
- continue;
530
- }
531
- if (i < 0) {
532
- break;
533
- }
534
- window[windowIndex] = _history[i];
535
- windowIndex++;
536
- }
537
- return window;
538
- }
539
- for await (const { sequence, data, done } of this.src) {
540
- if (done) {
541
- for (let i = 0; i < size - 1; i++) {
542
- const window2 = buildWindow(offset + i, size, history);
543
- yield { sequence: lastSeq, data: window2, done: false };
544
- }
545
- if (data === void 0) {
546
- yield {
547
- sequence: lastSeq,
548
- data: void 0,
549
- done: true
550
- };
551
- } else {
552
- yield {
553
- sequence: lastSeq,
554
- data: [
555
- history[history.length - 2] ?? void 0,
556
- history[history.length - 3] ?? void 0,
557
- history[history.length - 1]
558
- ],
559
- done: true
560
- };
561
- }
562
- break;
563
- }
564
- lastSeq = sequence;
565
- history.push(data);
566
- const window = buildWindow(offset, size, history);
567
- yield { sequence, data: window, done: false };
568
- offset++;
569
- }
570
- }
571
- const base = new _Pump(gen.call(this));
572
- return fn ? base.map(fn) : base;
573
- }
574
- /**
575
- * Sequentially flatten inner stream sources emitted by the pipeline.
576
- * Works with any Source type (AsyncIterable or ReadableStream).
577
- * This method is only available when the current Pump contains Source elements.
578
- *
579
- * @template U The type of data in the inner streams
580
- * @template F The type of inner stream source (extends Source<U>)
581
- * @returns A Pump instance with flattened stream data
582
- */
583
- sequenceStreams() {
584
- async function* gen() {
585
- let seq = 0;
586
- for await (const { data: innerSource, done: outerDone } of this.src) {
587
- if (outerDone)
588
- break;
589
- const innerPump = _Pump.from(innerSource);
590
- for await (const { data, done } of innerPump.src) {
591
- if (done)
592
- break;
593
- yield { sequence: seq++, data, done: false };
594
- }
595
- }
596
- yield { sequence: seq, data: void 0, done: true };
597
- }
598
- return new _Pump(gen.call(this));
599
- }
600
- /**
601
- * Fork the stream: two independent Pump<T> consumers
602
- * Both resulting Pumps will receive the same data, allowing for divergent processing paths.
603
- *
604
- * @returns An array containing two independent Pump instances with the same source data
605
- */
606
- fork() {
607
- const buffers = [[], []];
608
- let done = false;
609
- const srcIter = this.src[Symbol.asyncIterator]();
610
- async function fill() {
611
- const { value, done: streamDone } = await srcIter.next();
612
- if (streamDone) {
613
- done = true;
614
- return;
615
- }
616
- buffers.forEach((q) => q.push(value));
617
- if (value.done)
618
- done = true;
619
- }
620
- function makeStream(buf) {
621
- return {
622
- [Symbol.asyncIterator]() {
623
- return {
624
- async next() {
625
- while (buf.length === 0 && !done) {
626
- await fill();
627
- }
628
- if (buf.length === 0)
629
- return {
630
- done: true,
631
- value: void 0
632
- };
633
- return { done: false, value: buf.shift() };
634
- }
635
- };
636
- }
637
- };
638
- }
639
- return [new _Pump(makeStream(buffers[0])), new _Pump(makeStream(buffers[1]))];
640
- }
641
- /**
642
- * Drain the pipeline, consuming all chunks.
643
- * Returns a Promise that resolves when all chunks have been consumed.
644
- *
645
- * @returns A Promise that resolves when all chunks have been consumed
646
- */
647
- drain() {
648
- return (async () => {
649
- for await (const { done } of this.src) {
650
- if (done)
651
- break;
652
- }
653
- })();
654
- }
655
- /**
656
- * Drain the pipeline to a StreamTransformer.
657
- * Applies transform() to each data chunk, then closes the transformer,
658
- * and returns its response (which can be of any type defined by the transformer).
659
- *
660
- * Example with httpStreamResponse:
661
- * ```
662
- * const { transform, response, close } = httpStreamResponse(options);
663
- * return Pump.from(messageStream).drainTo({ transform, close, response });
664
- * ```
665
- *
666
- * @template U The type of data expected by the transformer (extends T)
667
- * @template R The response type produced by the transformer
668
- * @param transformer The StreamTransformer to drain to
669
- * @returns The response from the transformer
670
- */
671
- drainTo(transformer) {
672
- (async () => {
673
- for await (const { data, done } of this.src) {
674
- if (done)
675
- break;
676
- transformer.transform(data);
677
- }
678
- transformer.close();
679
- })();
680
- return transformer.response;
681
- }
682
- };
683
-
684
- // src/stream/utility/pipe-transformers/response.ts
685
- function httpStreamResponse(options = {}) {
686
- const { init, encoder } = options;
687
- const encodeFn = encoder ?? ((d) => {
688
- if (d instanceof Uint8Array)
689
- return d;
690
- if (typeof d === "string")
691
- return d;
692
- return JSON.stringify(d);
693
- });
694
- const { readable, writable } = new TransformStream();
695
- const writer = writable.getWriter();
696
- const response = new Response(readable, init);
697
- const transform = (chunk) => {
698
- const encoded = encodeFn(chunk);
699
- const bytes = typeof encoded === "string" ? new TextEncoder().encode(encoded) : encoded;
700
- writer.write(bytes);
701
- return chunk;
702
- };
703
- const close = () => {
704
- writer.close();
705
- };
706
- return { transform, response, close };
707
- }
708
-
709
- // src/stream/utility/rechunker/ensure-full-words.ts
710
- async function ensureFullWords({
711
- buffer,
712
- push,
713
- lastChunk
714
- }) {
715
- const combined = buffer.join("");
716
- const lastBoundary = Math.max(
717
- combined.lastIndexOf(" "),
718
- combined.lastIndexOf("\n"),
719
- combined.lastIndexOf(" ")
720
- );
721
- if (lastBoundary !== -1 || lastChunk) {
722
- const emitPart = lastBoundary !== -1 ? combined.slice(0, lastBoundary + 1) : combined;
723
- const leftoverPart = lastBoundary !== -1 ? combined.slice(lastBoundary + 1) : "";
724
- if (emitPart.trim().length > 0) {
725
- push(emitPart);
726
- }
727
- buffer.length = 0;
728
- if (leftoverPart.length > 0) {
729
- buffer.push(leftoverPart);
730
- }
731
- }
732
- }
733
-
734
25
  // src/api/socket-handler/SocketIoFactory.ts
735
26
  var SocketIoFactory = class _SocketIoFactory {
736
27
  constructor(socket, prefix, hooks) {
@@ -788,16 +79,10 @@ var SocketIoFactory = class _SocketIoFactory {
788
79
  this.socket.on(prefix("voice:output_file"), onVoiceOutputFile);
789
80
  }
790
81
  if (onVoiceOutputTranscriptDelta) {
791
- this.socket.on(
792
- prefix("voice:output_transcript_delta"),
793
- onVoiceOutputTranscriptDelta
794
- );
82
+ this.socket.on(prefix("voice:output_transcript_delta"), onVoiceOutputTranscriptDelta);
795
83
  }
796
84
  if (onVoiceOutputTranscriptFull) {
797
- this.socket.on(
798
- prefix("voice:output_transcript_full"),
799
- onVoiceOutputTranscriptFull
800
- );
85
+ this.socket.on(prefix("voice:output_transcript_full"), onVoiceOutputTranscriptFull);
801
86
  }
802
87
  }
803
88
  setupChatEvents(_socket) {
@@ -1013,10 +298,7 @@ var runSubscriber = (agent, publishesTo, dequeue, plane, emitQueue, channelName)
1013
298
  if (listensTo.length > 0 && !listensTo.includes(envelope.name)) {
1014
299
  return;
1015
300
  }
1016
- const runEvents = plane.getRunEvents(
1017
- envelope.meta.runId,
1018
- envelope.meta.contextId
1019
- );
301
+ const runEvents = plane.getRunEvents(envelope.meta.runId, envelope.meta.contextId);
1020
302
  const contextEvents = plane.getContextEvents(envelope.meta.contextId);
1021
303
  yield* effect.Effect.withSpan("agent.listen", {
1022
304
  attributes: {
@@ -1051,9 +333,7 @@ var runSubscriber = (agent, publishesTo, dequeue, plane, emitQueue, channelName)
1051
333
  ).catch(() => {
1052
334
  });
1053
335
  } else {
1054
- effect.Effect.runFork(
1055
- plane.publishToChannels(publishesTo, fullEnvelope)
1056
- );
336
+ effect.Effect.runFork(plane.publishToChannels(publishesTo, fullEnvelope));
1057
337
  }
1058
338
  },
1059
339
  runEvents,
@@ -1079,14 +359,7 @@ var run = (network, plane, options) => effect.Effect.gen(function* () {
1079
359
  for (const reg of registrations.values()) {
1080
360
  for (const channel of reg.subscribedTo) {
1081
361
  const dequeue = yield* plane.subscribe(channel.name);
1082
- yield* runSubscriber(
1083
- reg.agent,
1084
- reg.publishesTo,
1085
- dequeue,
1086
- plane,
1087
- emitQueue,
1088
- channel.name
1089
- );
362
+ yield* runSubscriber(reg.agent, reg.publishesTo, dequeue, plane, emitQueue, channel.name);
1090
363
  }
1091
364
  }
1092
365
  yield* effect.Effect.never;
@@ -1154,14 +427,7 @@ function streamFromDequeue(take, signal, eventFilter) {
1154
427
  };
1155
428
  }
1156
429
  function expose(network, options) {
1157
- const {
1158
- auth,
1159
- select,
1160
- plane: providedPlane,
1161
- onRequest,
1162
- triggerEvents,
1163
- tracingLayer
1164
- } = options;
430
+ const { auth, select, plane: providedPlane, onRequest, triggerEvents, tracingLayer } = options;
1165
431
  const triggerEventDef = triggerEvents?.[0];
1166
432
  const triggerEventName = triggerEventDef?.name ?? "request";
1167
433
  const channels = resolveChannels(network, select);
@@ -1208,10 +474,8 @@ function expose(network, options) {
1208
474
  meta,
1209
475
  payload: opts.event.payload
1210
476
  };
1211
- effect.Effect.runPromise(plane.publish(targetChannel, envelope)).catch(
1212
- () => {
1213
- }
1214
- );
477
+ effect.Effect.runPromise(plane.publish(targetChannel, envelope)).catch(() => {
478
+ });
1215
479
  };
1216
480
  const dequeue = yield* plane.subscribe(channels[0]);
1217
481
  if (onRequest) {
@@ -1251,10 +515,7 @@ function expose(network, options) {
1251
515
  if (auth) {
1252
516
  const result = await auth(req);
1253
517
  if (!result.allowed) {
1254
- throw new ExposeAuthError(
1255
- result.message ?? "Unauthorized",
1256
- result.status ?? 401
1257
- );
518
+ throw new ExposeAuthError(result.message ?? "Unauthorized", result.status ?? 401);
1258
519
  }
1259
520
  }
1260
521
  return consumer ? createStream(req, consumer) : createStream(req);
@@ -1289,6 +550,7 @@ var AgentNetwork = class _AgentNetwork {
1289
550
  createChannel: (name) => network.addChannel(name),
1290
551
  sink: Sink,
1291
552
  registerAgent: (agent) => network.registerAgentInternal(agent),
553
+ registerAggregator: (aggregator) => network.registerAggregatorInternal(aggregator),
1292
554
  spawner: (factory) => network.createSpawnerInternal(factory)
1293
555
  };
1294
556
  callback(ctx);
@@ -1323,6 +585,9 @@ var AgentNetwork = class _AgentNetwork {
1323
585
  };
1324
586
  return binding;
1325
587
  }
588
+ registerAggregatorInternal(aggregator) {
589
+ return this.registerAgentInternal(aggregator);
590
+ }
1326
591
  createSpawnerInternal(factoryClass) {
1327
592
  const reg = {
1328
593
  factoryClass,
@@ -1427,7 +692,9 @@ var AgentNetworkEvent = {
1427
692
  const makeBound = (meta, payload2) => effect.Effect.runSync(
1428
693
  decodeEnvelope({ name, meta, payload: payload2 })
1429
694
  );
1430
- const makeEffect = (payload2) => decodePayload(payload2).pipe(effect.Effect.map((p) => ({ name, payload: p })));
695
+ const makeEffect = (payload2) => decodePayload(payload2).pipe(
696
+ effect.Effect.map((p) => ({ name, payload: p }))
697
+ );
1431
698
  const makeBoundEffect = (meta, payload2) => decodeEnvelope({ name, meta, payload: payload2 });
1432
699
  const is = effect.Schema.is(envelopeSchema);
1433
700
  return {
@@ -1444,20 +711,110 @@ var AgentNetworkEvent = {
1444
711
  };
1445
712
  }
1446
713
  };
1447
- var _params, _logic, _id, _listensTo;
714
+ var EventAggregator = class _EventAggregator {
715
+ constructor({
716
+ listensTo = [],
717
+ emits = [],
718
+ emitWhen
719
+ }) {
720
+ this._listensTo = listensTo;
721
+ this._emits = emits;
722
+ this._emitWhen = emitWhen;
723
+ }
724
+ static listensTo(events) {
725
+ return new _EventAggregator({ listensTo: [...events] });
726
+ }
727
+ emits(events) {
728
+ return new _EventAggregator({
729
+ listensTo: this._listensTo,
730
+ emits: [...this._emits, ...events],
731
+ emitWhen: this._emitWhen
732
+ });
733
+ }
734
+ emitWhen(fn) {
735
+ return new _EventAggregator({
736
+ listensTo: this._listensTo,
737
+ emits: this._emits,
738
+ emitWhen: fn
739
+ });
740
+ }
741
+ mapToEmit(fn) {
742
+ return new EventAggregatorInstance({
743
+ listensTo: this._listensTo.map((eventDef) => eventDef.name),
744
+ emitWhen: this._emitWhen ?? (() => true),
745
+ mapToEmit: fn
746
+ });
747
+ }
748
+ };
749
+ var _id, _listensTo, _emitWhen, _mapToEmit;
750
+ var EventAggregatorInstance = class {
751
+ constructor({
752
+ listensTo,
753
+ emitWhen,
754
+ mapToEmit
755
+ }) {
756
+ __privateAdd(this, _id, void 0);
757
+ __privateAdd(this, _listensTo, void 0);
758
+ __privateAdd(this, _emitWhen, void 0);
759
+ __privateAdd(this, _mapToEmit, void 0);
760
+ __privateSet(this, _id, `event-aggregator-${crypto$1.randomUUID()}`);
761
+ __privateSet(this, _listensTo, listensTo);
762
+ __privateSet(this, _emitWhen, emitWhen);
763
+ __privateSet(this, _mapToEmit, mapToEmit);
764
+ }
765
+ getId() {
766
+ return __privateGet(this, _id);
767
+ }
768
+ getListensTo() {
769
+ return __privateGet(this, _listensTo);
770
+ }
771
+ async invoke(options) {
772
+ const { triggerEvent, emit, runEvents, contextEvents } = options ?? {};
773
+ if (triggerEvent == null) {
774
+ return;
775
+ }
776
+ const emitFn = emit ?? ((_event) => {
777
+ });
778
+ const runEventsValue = runEvents ?? [];
779
+ const contextEventsValue = contextEvents ?? {
780
+ all: [],
781
+ byRun: () => [],
782
+ map: /* @__PURE__ */ new Map()
783
+ };
784
+ const shouldEmit = await __privateGet(this, _emitWhen).call(this, {
785
+ triggerEvent,
786
+ runEvents: runEventsValue,
787
+ contextEvents: contextEventsValue
788
+ });
789
+ if (!shouldEmit) {
790
+ return;
791
+ }
792
+ await __privateGet(this, _mapToEmit).call(this, {
793
+ triggerEvent,
794
+ emit: emitFn,
795
+ runEvents: runEventsValue,
796
+ contextEvents: contextEventsValue
797
+ });
798
+ }
799
+ };
800
+ _id = new WeakMap();
801
+ _listensTo = new WeakMap();
802
+ _emitWhen = new WeakMap();
803
+ _mapToEmit = new WeakMap();
804
+ var _params, _logic, _id2, _listensTo2;
1448
805
  var Agent = class {
1449
806
  constructor(logic, params, listensTo) {
1450
807
  __privateAdd(this, _params, void 0);
1451
808
  __privateAdd(this, _logic, void 0);
1452
- __privateAdd(this, _id, void 0);
1453
- __privateAdd(this, _listensTo, void 0);
809
+ __privateAdd(this, _id2, void 0);
810
+ __privateAdd(this, _listensTo2, void 0);
1454
811
  __privateSet(this, _logic, logic);
1455
812
  __privateSet(this, _params, params);
1456
- __privateSet(this, _id, `agent-${crypto$1.randomUUID()}`);
1457
- __privateSet(this, _listensTo, listensTo ?? []);
813
+ __privateSet(this, _id2, `agent-${crypto$1.randomUUID()}`);
814
+ __privateSet(this, _listensTo2, listensTo ?? []);
1458
815
  }
1459
816
  getListensTo() {
1460
- return __privateGet(this, _listensTo);
817
+ return __privateGet(this, _listensTo2);
1461
818
  }
1462
819
  async invoke(options) {
1463
820
  const { triggerEvent, emit, runEvents, contextEvents } = options ?? {};
@@ -1476,13 +833,13 @@ var Agent = class {
1476
833
  });
1477
834
  }
1478
835
  getId() {
1479
- return __privateGet(this, _id);
836
+ return __privateGet(this, _id2);
1480
837
  }
1481
838
  };
1482
839
  _params = new WeakMap();
1483
840
  _logic = new WeakMap();
1484
- _id = new WeakMap();
1485
- _listensTo = new WeakMap();
841
+ _id2 = new WeakMap();
842
+ _listensTo2 = new WeakMap();
1486
843
 
1487
844
  // src/matrix/agent-factory.ts
1488
845
  var AgentFactory = class _AgentFactory {
@@ -1667,9 +1024,7 @@ var Skill = class _Skill {
1667
1024
  const layersObj = runtime?.layers ?? {};
1668
1025
  const chunks = [];
1669
1026
  const emit = (chunk) => {
1670
- const decoded = effect.Effect.runSync(
1671
- decodeChunk(chunk)
1672
- );
1027
+ const decoded = effect.Effect.runSync(decodeChunk(chunk));
1673
1028
  chunks.push(decoded);
1674
1029
  };
1675
1030
  const done = await defineFn({
@@ -1677,9 +1032,7 @@ var Skill = class _Skill {
1677
1032
  emit,
1678
1033
  layers: layersObj
1679
1034
  });
1680
- const decodedDone = effect.Effect.runSync(
1681
- decodeDone(done)
1682
- );
1035
+ const decodedDone = effect.Effect.runSync(decodeDone(done));
1683
1036
  return { chunks, done: decodedDone };
1684
1037
  };
1685
1038
  return {
@@ -1690,9 +1043,7 @@ var Skill = class _Skill {
1690
1043
  const layersObj = runtime?.layers ?? {};
1691
1044
  const chunks = [];
1692
1045
  const emit = (chunk) => {
1693
- const decoded = effect.Effect.runSync(
1694
- decodeChunk(chunk)
1695
- );
1046
+ const decoded = effect.Effect.runSync(decodeChunk(chunk));
1696
1047
  chunks.push(decoded);
1697
1048
  };
1698
1049
  const done = await defineFn({
@@ -1700,9 +1051,7 @@ var Skill = class _Skill {
1700
1051
  emit,
1701
1052
  layers: layersObj
1702
1053
  });
1703
- const decodedDone = effect.Effect.runSync(
1704
- decodeDone(done)
1705
- );
1054
+ const decodedDone = effect.Effect.runSync(decodeDone(done));
1706
1055
  for (const c of chunks) {
1707
1056
  yield c;
1708
1057
  }
@@ -1807,9 +1156,7 @@ var NextEndpoint = {
1807
1156
  var ExpressEndpoint = {
1808
1157
  from(api, options) {
1809
1158
  if (api.protocol !== "sse") {
1810
- throw new Error(
1811
- `ExpressEndpoint: unsupported protocol "${api.protocol}"`
1812
- );
1159
+ throw new Error(`ExpressEndpoint: unsupported protocol "${api.protocol}"`);
1813
1160
  }
1814
1161
  const { requestToContextId, requestToRunId } = options;
1815
1162
  return {
@@ -1912,20 +1259,10 @@ function getDepth(parent) {
1912
1259
  return 1 + getDepth(p.parent);
1913
1260
  }
1914
1261
  var consoleTracer = effect.Tracer.make({
1915
- span: (name, parent, context, links, startTime, kind) => new ConsoleSpan(
1916
- name,
1917
- parent,
1918
- context,
1919
- links,
1920
- startTime,
1921
- kind,
1922
- getDepth(parent)
1923
- ),
1262
+ span: (name, parent, context, links, startTime, kind) => new ConsoleSpan(name, parent, context, links, startTime, kind, getDepth(parent)),
1924
1263
  context: (f) => f()
1925
1264
  });
1926
- var consoleTracerLayer = effect.Layer.setTracer(
1927
- consoleTracer
1928
- );
1265
+ var consoleTracerLayer = effect.Layer.setTracer(consoleTracer);
1929
1266
 
1930
1267
  Object.defineProperty(exports, 'S', {
1931
1268
  enumerable: true,
@@ -1940,20 +1277,19 @@ exports.ChannelName = ChannelName;
1940
1277
  exports.ConfiguredChannel = ConfiguredChannel;
1941
1278
  exports.DepedencyLayer = DepedencyLayer;
1942
1279
  exports.Done = Done;
1280
+ exports.EventAggregator = EventAggregator;
1281
+ exports.EventAggregatorInstance = EventAggregatorInstance;
1943
1282
  exports.EventMetaSchema = EventMetaSchema;
1944
1283
  exports.ExposeAuthError = ExposeAuthError;
1945
1284
  exports.ExpressEndpoint = ExpressEndpoint;
1946
1285
  exports.LayerName = LayerName;
1947
1286
  exports.NextEndpoint = NextEndpoint;
1948
- exports.Pump = Pump;
1949
1287
  exports.Sink = Sink;
1950
1288
  exports.Skill = Skill;
1951
1289
  exports.SocketIoFactory = SocketIoFactory;
1952
1290
  exports.consoleTracer = consoleTracer;
1953
1291
  exports.consoleTracerLayer = consoleTracerLayer;
1954
- exports.ensureFullWords = ensureFullWords;
1955
1292
  exports.formatSSE = formatSSE;
1956
- exports.httpStreamResponse = httpStreamResponse;
1957
1293
  exports.isHttpStreamSink = isHttpStreamSink;
1958
1294
  exports.toSSEStream = toSSEStream;
1959
1295
  //# sourceMappingURL=out.js.map