@m4trix/core 0.5.0 → 0.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -5,7 +5,9 @@ import { property, state, customElement } from 'lit/decorators.js';
5
5
  import { createRef, ref } from 'lit/directives/ref.js';
6
6
  import { createTimeline } from 'animejs';
7
7
  import { ToolMessage, AIMessage, HumanMessage } from '@langchain/core/messages';
8
- import { Effect, pipe } from 'effect';
8
+ import { Brand, Schema, Effect, pipe, PubSub, Queue, Cause } from 'effect';
9
+ export { Schema as S } from 'effect';
10
+ import { randomUUID } from 'crypto';
9
11
 
10
12
  var __defProp = Object.defineProperty;
11
13
  var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
@@ -18,6 +20,24 @@ var __decorateClass = (decorators, target, key, kind) => {
18
20
  __defProp(target, key, result);
19
21
  return result;
20
22
  };
23
+ var __accessCheck = (obj, member, msg) => {
24
+ if (!member.has(obj))
25
+ throw TypeError("Cannot " + msg);
26
+ };
27
+ var __privateGet = (obj, member, getter) => {
28
+ __accessCheck(obj, member, "read from private field");
29
+ return getter ? getter.call(obj) : member.get(obj);
30
+ };
31
+ var __privateAdd = (obj, member, value) => {
32
+ if (member.has(obj))
33
+ throw TypeError("Cannot add the same private member more than once");
34
+ member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
35
+ };
36
+ var __privateSet = (obj, member, value, setter) => {
37
+ __accessCheck(obj, member, "write to private field");
38
+ setter ? setter.call(obj, value) : member.set(obj, value);
39
+ return value;
40
+ };
21
41
 
22
42
  // src/utility/Logger.ts
23
43
  var _Logger = class _Logger {
@@ -2613,44 +2633,760 @@ var TransformMessages = class _TransformMessages {
2613
2633
  * Format messages according to the specified format type
2614
2634
  */
2615
2635
  format(formatType) {
2616
- return pipe(
2617
- this.effect,
2618
- Effect.map((messages) => {
2619
- if (formatType === "json" /* JSON */) {
2620
- return JSON.stringify(messages, null, 2);
2621
- }
2622
- const formatter = typeOnFormatter[formatType];
2623
- return formatter(messages);
2624
- })
2636
+ const result = Effect.runSync(
2637
+ pipe(
2638
+ this.effect,
2639
+ Effect.map((messages) => {
2640
+ if (formatType === "json" /* JSON */) {
2641
+ return JSON.stringify(messages, null, 2);
2642
+ }
2643
+ const formatter = typeOnFormatter[formatType];
2644
+ return formatter(messages);
2645
+ })
2646
+ )
2625
2647
  );
2648
+ return result;
2626
2649
  }
2627
2650
  // Sink methods
2628
2651
  /**
2629
- * Convert to array - runs the effect and returns the result
2630
- */
2652
+ * Convert to array - runs the effect and returns the result
2653
+ return pipe(
2654
+ this.effect,
2655
+ Effect.map((messages) => {
2656
+ if (formatType === FormatType.JSON) {
2657
+ return JSON.stringify(messages, null, 2);
2658
+ }
2659
+
2660
+ const formatter = typeOnFormatter[formatType];
2661
+ return formatter(messages);
2662
+ })
2663
+ );
2664
+ }
2665
+
2666
+ // Sink methods
2667
+
2668
+ /**
2669
+ * Convert to array - runs the effect and returns the result
2670
+ */
2631
2671
  toArray() {
2632
- return this.effect;
2672
+ return Effect.runSync(this.effect);
2633
2673
  }
2634
2674
  /**
2635
2675
  * Convert to string - runs the effect and returns JSON string
2636
2676
  */
2637
2677
  toString() {
2638
- return pipe(
2639
- this.effect,
2640
- Effect.map((messages) => JSON.stringify(messages, null, 2))
2678
+ const result = Effect.runSync(
2679
+ pipe(
2680
+ this.effect,
2681
+ Effect.map((messages) => JSON.stringify(messages, null, 2))
2682
+ )
2641
2683
  );
2684
+ return result;
2642
2685
  }
2643
2686
  /**
2644
2687
  * Get the count of messages
2645
2688
  */
2646
2689
  count() {
2647
- return pipe(
2648
- this.effect,
2649
- Effect.map((messages) => messages.length)
2690
+ const result = Effect.runSync(
2691
+ pipe(
2692
+ this.effect,
2693
+ Effect.map((messages) => messages.length)
2694
+ )
2650
2695
  );
2696
+ return result;
2697
+ }
2698
+ };
2699
+ var KEBAB_CASE_REGEX = /^[a-z0-9]+(-[a-z0-9]+)*$/;
2700
+ var ChannelName = Brand.refined(
2701
+ (s) => typeof s === "string" && KEBAB_CASE_REGEX.test(s),
2702
+ (s) => Brand.error(`Expected kebab-case (e.g. my-channel-name), got: ${s}`)
2703
+ );
2704
+
2705
+ // src/matrix/agent-network/channel.ts
2706
+ var Sink = {
2707
+ kafka(config) {
2708
+ return { _tag: "SinkDef", type: "kafka", config };
2709
+ },
2710
+ httpStream() {
2711
+ return { _tag: "SinkDef", type: "http-stream", config: {} };
2712
+ }
2713
+ };
2714
+ function isHttpStreamSink(sink) {
2715
+ return sink.type === "http-stream";
2716
+ }
2717
+ var ConfiguredChannel = class {
2718
+ constructor(name) {
2719
+ this._tag = "ConfiguredChannel";
2720
+ this._events = [];
2721
+ this._sinks = [];
2722
+ this.name = name;
2723
+ }
2724
+ events(events) {
2725
+ this._events = [...events];
2726
+ return this;
2727
+ }
2728
+ sink(sink) {
2729
+ this._sinks = [...this._sinks, sink];
2730
+ return this;
2731
+ }
2732
+ sinks(sinks) {
2733
+ this._sinks = [...sinks];
2734
+ return this;
2735
+ }
2736
+ getEvents() {
2737
+ return this._events;
2738
+ }
2739
+ getSinks() {
2740
+ return this._sinks;
2741
+ }
2742
+ };
2743
+ var Channel = {
2744
+ of(name) {
2745
+ return {
2746
+ _tag: "ChannelDef",
2747
+ name
2748
+ };
2749
+ }
2750
+ };
2751
+ var DEFAULT_CAPACITY = 16;
2752
+ var createEventPlane = (network, capacity = DEFAULT_CAPACITY) => Effect.gen(function* () {
2753
+ const channels = network.getChannels();
2754
+ const pubsubs = /* @__PURE__ */ new Map();
2755
+ for (const channel of channels.values()) {
2756
+ const pubsub = yield* PubSub.bounded(capacity);
2757
+ pubsubs.set(channel.name, pubsub);
2758
+ }
2759
+ const getPubsub = (channel) => {
2760
+ const p = pubsubs.get(channel);
2761
+ if (!p)
2762
+ throw new Error(`Channel not found: ${channel}`);
2763
+ return p;
2764
+ };
2765
+ const publish = (channel, envelope) => PubSub.publish(getPubsub(channel), envelope);
2766
+ const publishToChannels = (targetChannels, envelope) => Effect.all(
2767
+ targetChannels.map((c) => publish(c.name, envelope)),
2768
+ { concurrency: "unbounded" }
2769
+ ).pipe(Effect.map((results) => results.every(Boolean)));
2770
+ const subscribe = (channel) => PubSub.subscribe(getPubsub(channel));
2771
+ const shutdown = Effect.all([...pubsubs.values()].map(PubSub.shutdown), {
2772
+ concurrency: "unbounded"
2773
+ }).pipe(Effect.asVoid);
2774
+ return {
2775
+ publish,
2776
+ publishToChannels,
2777
+ subscribe,
2778
+ shutdown
2779
+ };
2780
+ });
2781
+ var runSubscriber = (agent, publishesTo, dequeue, plane, emitQueue) => Effect.gen(function* () {
2782
+ const listensTo = agent.getListensTo?.() ?? [];
2783
+ const processOne = () => Effect.gen(function* () {
2784
+ const envelope = yield* Queue.take(dequeue);
2785
+ if (listensTo.length > 0 && !listensTo.includes(envelope.name)) {
2786
+ return;
2787
+ }
2788
+ yield* Effect.tryPromise({
2789
+ try: () => agent.invoke({
2790
+ triggerEvent: envelope,
2791
+ emit: (userEvent) => {
2792
+ const fullEnvelope = {
2793
+ name: userEvent.name,
2794
+ meta: envelope.meta,
2795
+ payload: userEvent.payload
2796
+ };
2797
+ if (emitQueue) {
2798
+ Effect.runPromise(
2799
+ Queue.offer(emitQueue, {
2800
+ channels: publishesTo,
2801
+ envelope: fullEnvelope
2802
+ })
2803
+ ).catch(() => {
2804
+ });
2805
+ } else {
2806
+ Effect.runFork(
2807
+ plane.publishToChannels(publishesTo, fullEnvelope)
2808
+ );
2809
+ }
2810
+ }
2811
+ }),
2812
+ catch: (e) => e
2813
+ });
2814
+ }).pipe(
2815
+ Effect.catchAllCause(
2816
+ (cause) => Cause.isInterrupted(cause) ? Effect.void : Effect.sync(() => {
2817
+ console.error(`Agent ${agent.getId()} failed:`, cause);
2818
+ }).pipe(Effect.asVoid)
2819
+ )
2820
+ );
2821
+ const loop = () => processOne().pipe(Effect.flatMap(() => loop()));
2822
+ return yield* Effect.fork(loop());
2823
+ });
2824
+ var run = (network, plane, options) => Effect.gen(function* () {
2825
+ const registrations = network.getAgentRegistrations();
2826
+ const emitQueue = options?.emitQueue;
2827
+ for (const reg of registrations.values()) {
2828
+ for (const channel of reg.subscribedTo) {
2829
+ const dequeue = yield* plane.subscribe(channel.name);
2830
+ yield* runSubscriber(
2831
+ reg.agent,
2832
+ reg.publishesTo,
2833
+ dequeue,
2834
+ plane,
2835
+ emitQueue
2836
+ );
2837
+ }
2838
+ }
2839
+ yield* Effect.never;
2840
+ });
2841
+ async function extractPayload(req) {
2842
+ const webRequest = req.request;
2843
+ if (webRequest?.method === "POST") {
2844
+ const ct = webRequest.headers?.get?.("content-type") ?? "";
2845
+ if (ct.includes("application/json")) {
2846
+ try {
2847
+ return await webRequest.json();
2848
+ } catch {
2849
+ return {};
2850
+ }
2851
+ }
2852
+ }
2853
+ const expressReq = req.req;
2854
+ if (expressReq?.body != null) {
2855
+ return expressReq.body;
2856
+ }
2857
+ return {};
2858
+ }
2859
+ function resolveChannels(network, select) {
2860
+ const channels = network.getChannels();
2861
+ if (select?.channels) {
2862
+ const ch = select.channels;
2863
+ const arr = Array.isArray(ch) ? ch : [ch];
2864
+ return arr.map((c) => ChannelName(c));
2865
+ }
2866
+ const httpStreamChannels = [...channels.values()].filter((ch) => ch.getSinks().some(isHttpStreamSink)).map((ch) => ch.name);
2867
+ if (httpStreamChannels.length > 0)
2868
+ return httpStreamChannels;
2869
+ const client = channels.get("client");
2870
+ if (client)
2871
+ return [client.name];
2872
+ const first = channels.values().next().value;
2873
+ return first ? [first.name] : [];
2874
+ }
2875
+ function streamFromDequeue(take, signal, eventFilter) {
2876
+ const shouldInclude = (e) => !eventFilter?.length || eventFilter.includes(e.name);
2877
+ return {
2878
+ async *[Symbol.asyncIterator]() {
2879
+ while (!signal?.aborted) {
2880
+ const takePromise = take();
2881
+ const abortPromise = signal ? new Promise((_, reject) => {
2882
+ signal.addEventListener(
2883
+ "abort",
2884
+ () => reject(new DOMException("Aborted", "AbortError")),
2885
+ { once: true }
2886
+ );
2887
+ }) : new Promise(() => {
2888
+ });
2889
+ let envelope;
2890
+ try {
2891
+ envelope = await Promise.race([takePromise, abortPromise]);
2892
+ } catch (e) {
2893
+ if (e instanceof DOMException && e.name === "AbortError")
2894
+ break;
2895
+ throw e;
2896
+ }
2897
+ if (shouldInclude(envelope))
2898
+ yield envelope;
2899
+ }
2900
+ }
2901
+ };
2902
+ }
2903
+ function expose(network, options) {
2904
+ const { auth, select, plane: providedPlane, onRequest, startEventName = "request" } = options;
2905
+ const channels = resolveChannels(network, select);
2906
+ const eventFilter = select?.events;
2907
+ const mainChannel = network.getMainChannel();
2908
+ if (channels.length === 0) {
2909
+ throw new Error("expose: no channels to subscribe to");
2910
+ }
2911
+ const createStream = async (req, consumer) => {
2912
+ const payload = await extractPayload(req);
2913
+ const signal = req.request?.signal;
2914
+ const program = Effect.gen(function* () {
2915
+ const plane = providedPlane ?? (yield* createEventPlane(network));
2916
+ if (!providedPlane) {
2917
+ const emitQueue = yield* Queue.unbounded();
2918
+ yield* Effect.fork(
2919
+ Effect.forever(
2920
+ Queue.take(emitQueue).pipe(
2921
+ Effect.flatMap(
2922
+ ({ channels: chs, envelope }) => plane.publishToChannels(chs, envelope)
2923
+ )
2924
+ )
2925
+ )
2926
+ );
2927
+ yield* Effect.fork(run(network, plane, { emitQueue }));
2928
+ yield* Effect.sleep("10 millis");
2929
+ }
2930
+ const targetChannel = mainChannel?.name ?? channels[0];
2931
+ const emitStartEvent = (p) => {
2932
+ const pld = p ?? payload;
2933
+ const envelope = {
2934
+ name: startEventName,
2935
+ meta: { runId: crypto.randomUUID() },
2936
+ payload: pld
2937
+ };
2938
+ Effect.runPromise(plane.publish(targetChannel, envelope)).catch(() => {
2939
+ });
2940
+ };
2941
+ const dequeue = yield* plane.subscribe(channels[0]);
2942
+ if (onRequest) {
2943
+ yield* Effect.tryPromise(
2944
+ () => Promise.resolve(onRequest({ emitStartEvent, req, payload }))
2945
+ );
2946
+ } else if (!providedPlane) {
2947
+ const envelope = {
2948
+ name: startEventName,
2949
+ meta: { runId: crypto.randomUUID() },
2950
+ payload
2951
+ };
2952
+ yield* plane.publish(targetChannel, envelope);
2953
+ yield* Effect.sleep("10 millis");
2954
+ }
2955
+ const take = () => Effect.runPromise(Queue.take(dequeue));
2956
+ const stream = streamFromDequeue(take, signal ?? void 0, eventFilter);
2957
+ if (consumer) {
2958
+ return yield* Effect.tryPromise(() => consumer(stream));
2959
+ }
2960
+ return stream;
2961
+ });
2962
+ return Effect.runPromise(program.pipe(Effect.scoped));
2963
+ };
2964
+ return {
2965
+ protocol: "sse",
2966
+ createStream: async (req, consumer) => {
2967
+ if (auth) {
2968
+ const result = await auth(req);
2969
+ if (!result.allowed) {
2970
+ throw new ExposeAuthError(
2971
+ result.message ?? "Unauthorized",
2972
+ result.status ?? 401
2973
+ );
2974
+ }
2975
+ }
2976
+ return consumer ? createStream(req, consumer) : createStream(req);
2977
+ }
2978
+ };
2979
+ }
2980
+ var ExposeAuthError = class extends Error {
2981
+ constructor(message, status = 401) {
2982
+ super(message);
2983
+ this.status = status;
2984
+ this.name = "ExposeAuthError";
2985
+ }
2986
+ };
2987
+
2988
+ // src/matrix/agent-network/agent-network.ts
2989
+ var AgentNetwork = class _AgentNetwork {
2990
+ constructor() {
2991
+ this.channels = /* @__PURE__ */ new Map();
2992
+ this.agentRegistrations = /* @__PURE__ */ new Map();
2993
+ this.spawnerRegistrations = [];
2994
+ }
2995
+ /* ─── Public Static Factory ─── */
2996
+ static setup(callback) {
2997
+ const network = new _AgentNetwork();
2998
+ const ctx = {
2999
+ mainChannel: (name) => {
3000
+ const channel = network.addChannel(name);
3001
+ network.setMainChannel(channel);
3002
+ return channel;
3003
+ },
3004
+ createChannel: (name) => network.addChannel(name),
3005
+ sink: Sink,
3006
+ registerAgent: (agent) => network.registerAgentInternal(agent),
3007
+ spawner: (factory) => network.createSpawnerInternal(factory)
3008
+ };
3009
+ callback(ctx);
3010
+ return network;
3011
+ }
3012
+ /* ─── Internal Builders ─── */
3013
+ addChannel(name) {
3014
+ const channelName = ChannelName(name);
3015
+ const channel = new ConfiguredChannel(channelName);
3016
+ this.channels.set(channelName, channel);
3017
+ return channel;
3018
+ }
3019
+ setMainChannel(channel) {
3020
+ this._mainChannel = channel;
3021
+ }
3022
+ registerAgentInternal(agent) {
3023
+ const registration = {
3024
+ agent,
3025
+ subscribedTo: [],
3026
+ publishesTo: []
3027
+ };
3028
+ this.agentRegistrations.set(agent.getId(), registration);
3029
+ const binding = {
3030
+ subscribe(channel) {
3031
+ registration.subscribedTo.push(channel);
3032
+ return binding;
3033
+ },
3034
+ publishTo(channel) {
3035
+ registration.publishesTo.push(channel);
3036
+ return binding;
3037
+ }
3038
+ };
3039
+ return binding;
3040
+ }
3041
+ createSpawnerInternal(factoryClass) {
3042
+ const reg = {
3043
+ factoryClass,
3044
+ registry: {}
3045
+ };
3046
+ this.spawnerRegistrations.push(reg);
3047
+ const builder = {
3048
+ listen(channel, event) {
3049
+ reg.listenChannel = channel;
3050
+ reg.listenEvent = event;
3051
+ return builder;
3052
+ },
3053
+ registry(registry) {
3054
+ reg.registry = registry;
3055
+ return builder;
3056
+ },
3057
+ defaultBinding(fn) {
3058
+ reg.defaultBindingFn = fn;
3059
+ return builder;
3060
+ },
3061
+ onSpawn(fn) {
3062
+ reg.onSpawnFn = fn;
3063
+ return builder;
3064
+ }
3065
+ };
3066
+ return builder;
3067
+ }
3068
+ /* ─── Accessors ─── */
3069
+ getChannels() {
3070
+ return this.channels;
3071
+ }
3072
+ getMainChannel() {
3073
+ return this._mainChannel;
3074
+ }
3075
+ getAgentRegistrations() {
3076
+ return this.agentRegistrations;
3077
+ }
3078
+ getSpawnerRegistrations() {
3079
+ return this.spawnerRegistrations;
3080
+ }
3081
+ /**
3082
+ * Expose the network as a streamable API (e.g. SSE). Returns an ExposedAPI
3083
+ * that adapters (NextEndpoint, ExpressEndpoint) consume to produce streamed
3084
+ * responses.
3085
+ *
3086
+ * @example
3087
+ * const api = network.expose({ protocol: "sse", auth, select });
3088
+ * export const GET = NextEndpoint.from(api).handler();
3089
+ */
3090
+ expose(options) {
3091
+ return expose(this, options);
3092
+ }
3093
+ /**
3094
+ * Starts the event plane: creates one PubSub per channel and runs subscriber
3095
+ * loops for each (agent, channel) pair. Agents subscribed to a channel are
3096
+ * invoked concurrently when events are published to that channel.
3097
+ *
3098
+ * Returns the EventPlane for publishing. Use `Effect.scoped` so the run is
3099
+ * interrupted when the scope ends.
3100
+ */
3101
+ run(capacity) {
3102
+ return this.runScoped(this, capacity);
3103
+ }
3104
+ runScoped(network, capacity) {
3105
+ return Effect.gen(function* () {
3106
+ const plane = yield* createEventPlane(network, capacity);
3107
+ yield* Effect.fork(run(network, plane));
3108
+ return plane;
3109
+ });
3110
+ }
3111
+ };
3112
+ var EventMetaSchema = Schema.Struct({
3113
+ runId: Schema.String,
3114
+ contextId: Schema.optional(Schema.String),
3115
+ correlationId: Schema.optional(Schema.String),
3116
+ causationId: Schema.optional(Schema.String),
3117
+ ts: Schema.optional(Schema.Number)
3118
+ });
3119
+ var AgentNetworkEvent = {
3120
+ of(name, payload) {
3121
+ const decodePayload = Schema.decodeUnknown(payload);
3122
+ const envelopeSchema = Schema.Struct({
3123
+ name: Schema.Literal(name),
3124
+ meta: EventMetaSchema,
3125
+ payload
3126
+ });
3127
+ const decodeEnvelope = Schema.decodeUnknown(envelopeSchema);
3128
+ const make = (payload2) => {
3129
+ const decoded = Effect.runSync(
3130
+ decodePayload(payload2)
3131
+ );
3132
+ return { name, payload: decoded };
3133
+ };
3134
+ const makeBound = (meta, payload2) => Effect.runSync(
3135
+ decodeEnvelope({ name, meta, payload: payload2 })
3136
+ );
3137
+ const makeEffect = (payload2) => decodePayload(payload2).pipe(
3138
+ Effect.map((p) => ({ name, payload: p }))
3139
+ );
3140
+ const makeBoundEffect = (meta, payload2) => decodeEnvelope({ name, meta, payload: payload2 });
3141
+ const is = Schema.is(envelopeSchema);
3142
+ return {
3143
+ _tag: "AgentNetworkEventDef",
3144
+ name,
3145
+ payload,
3146
+ decodePayload,
3147
+ decode: decodeEnvelope,
3148
+ make,
3149
+ makeBound,
3150
+ makeEffect,
3151
+ makeBoundEffect,
3152
+ is
3153
+ };
3154
+ }
3155
+ };
3156
+ var _params, _logic, _id, _listensTo;
3157
+ var Agent = class {
3158
+ constructor(logic, params, listensTo) {
3159
+ __privateAdd(this, _params, void 0);
3160
+ __privateAdd(this, _logic, void 0);
3161
+ __privateAdd(this, _id, void 0);
3162
+ __privateAdd(this, _listensTo, void 0);
3163
+ __privateSet(this, _logic, logic);
3164
+ __privateSet(this, _params, params);
3165
+ __privateSet(this, _id, `agent-${randomUUID()}`);
3166
+ __privateSet(this, _listensTo, listensTo ?? []);
3167
+ }
3168
+ getListensTo() {
3169
+ return __privateGet(this, _listensTo);
3170
+ }
3171
+ async invoke(options) {
3172
+ const { triggerEvent, emit } = options ?? {};
3173
+ const emitFn = emit ?? ((_event) => {
3174
+ });
3175
+ await __privateGet(this, _logic).call(this, {
3176
+ params: __privateGet(this, _params),
3177
+ triggerEvent: triggerEvent ?? void 0,
3178
+ emit: emitFn
3179
+ });
3180
+ }
3181
+ getId() {
3182
+ return __privateGet(this, _id);
3183
+ }
3184
+ };
3185
+ _params = new WeakMap();
3186
+ _logic = new WeakMap();
3187
+ _id = new WeakMap();
3188
+ _listensTo = new WeakMap();
3189
+
3190
+ // src/matrix/agent-factory.ts
3191
+ var AgentFactory = class _AgentFactory {
3192
+ constructor({
3193
+ logic,
3194
+ paramsSchema,
3195
+ listensTo = [],
3196
+ emits = []
3197
+ }) {
3198
+ this._logic = logic;
3199
+ this._paramsSchema = paramsSchema;
3200
+ this._listensTo = listensTo;
3201
+ this._emits = emits;
3202
+ }
3203
+ getConstructorState() {
3204
+ return {
3205
+ logic: this._logic,
3206
+ paramsSchema: this._paramsSchema,
3207
+ listensTo: this._listensTo,
3208
+ emits: this._emits
3209
+ };
3210
+ }
3211
+ /** Union of all event definitions this agent listens to */
3212
+ getListensTo() {
3213
+ return this._listensTo;
3214
+ }
3215
+ /** Union of all event definitions this agent can emit */
3216
+ getEmits() {
3217
+ return this._emits;
3218
+ }
3219
+ getLogic() {
3220
+ return this._logic;
3221
+ }
3222
+ static run() {
3223
+ return new _AgentFactory({});
3224
+ }
3225
+ params(params) {
3226
+ const { logic, ...rest } = this.getConstructorState();
3227
+ return new _AgentFactory({
3228
+ ...rest,
3229
+ logic,
3230
+ paramsSchema: params
3231
+ });
3232
+ }
3233
+ listensTo(events) {
3234
+ return new _AgentFactory({
3235
+ ...this.getConstructorState(),
3236
+ listensTo: [...this._listensTo, ...events]
3237
+ });
3238
+ }
3239
+ emits(events) {
3240
+ return new _AgentFactory({
3241
+ ...this.getConstructorState(),
3242
+ emits: [...this._emits, ...events]
3243
+ });
3244
+ }
3245
+ logic(fn) {
3246
+ return new _AgentFactory({
3247
+ ...this.getConstructorState(),
3248
+ logic: fn
3249
+ });
3250
+ }
3251
+ produce(params) {
3252
+ const listensTo = this._listensTo.map((e) => e.name);
3253
+ return new Agent(
3254
+ this._logic,
3255
+ params,
3256
+ listensTo
3257
+ );
3258
+ }
3259
+ };
3260
+
3261
+ // src/matrix/io/protocols/sse.ts
3262
+ function formatSSE(envelope) {
3263
+ const data = JSON.stringify(envelope);
3264
+ return `event: ${envelope.name}
3265
+ data: ${data}
3266
+
3267
+ `;
3268
+ }
3269
+ function toSSEStream(source, signal) {
3270
+ const encoder = new TextEncoder();
3271
+ return new ReadableStream({
3272
+ async start(controller) {
3273
+ const onAbort = () => controller.close();
3274
+ signal?.addEventListener("abort", onAbort, { once: true });
3275
+ try {
3276
+ for await (const envelope of source) {
3277
+ if (signal?.aborted)
3278
+ break;
3279
+ controller.enqueue(encoder.encode(formatSSE(envelope)));
3280
+ }
3281
+ } finally {
3282
+ signal?.removeEventListener("abort", onAbort);
3283
+ controller.close();
3284
+ }
3285
+ }
3286
+ });
3287
+ }
3288
+
3289
+ // src/matrix/io/adapters/next-endpoint.ts
3290
+ var NextEndpoint = {
3291
+ from(api) {
3292
+ if (api.protocol !== "sse") {
3293
+ throw new Error(`NextEndpoint: unsupported protocol "${api.protocol}"`);
3294
+ }
3295
+ return {
3296
+ handler() {
3297
+ return async (request) => {
3298
+ const req = { request };
3299
+ try {
3300
+ const encoder = new TextEncoder();
3301
+ const { readable, writable } = new TransformStream();
3302
+ let consumerStarted;
3303
+ const started = new Promise((resolve) => {
3304
+ consumerStarted = resolve;
3305
+ });
3306
+ const streamDone = api.createStream(req, async (stream) => {
3307
+ consumerStarted();
3308
+ const writer = writable.getWriter();
3309
+ try {
3310
+ for await (const envelope of stream) {
3311
+ if (request.signal?.aborted)
3312
+ break;
3313
+ await writer.write(encoder.encode(formatSSE(envelope)));
3314
+ }
3315
+ } finally {
3316
+ await writer.close();
3317
+ }
3318
+ });
3319
+ await Promise.race([started, streamDone]);
3320
+ streamDone.catch(() => {
3321
+ });
3322
+ return new Response(readable, {
3323
+ headers: {
3324
+ "Content-Type": "text/event-stream",
3325
+ "Cache-Control": "no-cache",
3326
+ Connection: "keep-alive"
3327
+ }
3328
+ });
3329
+ } catch (e) {
3330
+ if (e instanceof ExposeAuthError) {
3331
+ return new Response(e.message, { status: e.status });
3332
+ }
3333
+ throw e;
3334
+ }
3335
+ };
3336
+ }
3337
+ };
3338
+ }
3339
+ };
3340
+
3341
+ // src/matrix/io/adapters/express-endpoint.ts
3342
+ var ExpressEndpoint = {
3343
+ from(api) {
3344
+ if (api.protocol !== "sse") {
3345
+ throw new Error(
3346
+ `ExpressEndpoint: unsupported protocol "${api.protocol}"`
3347
+ );
3348
+ }
3349
+ return {
3350
+ handler() {
3351
+ return async (req, res) => {
3352
+ const controller = new AbortController();
3353
+ req.on("close", () => controller.abort());
3354
+ const exposeReq = {
3355
+ request: { signal: controller.signal },
3356
+ req,
3357
+ res
3358
+ };
3359
+ try {
3360
+ const encoder = new TextEncoder();
3361
+ await api.createStream(exposeReq, async (stream) => {
3362
+ res.setHeader("Content-Type", "text/event-stream");
3363
+ res.setHeader("Cache-Control", "no-cache");
3364
+ res.setHeader("Connection", "keep-alive");
3365
+ res.flushHeaders?.();
3366
+ try {
3367
+ for await (const envelope of stream) {
3368
+ if (controller.signal.aborted)
3369
+ break;
3370
+ res.write(encoder.encode(formatSSE(envelope)));
3371
+ res.flush?.();
3372
+ }
3373
+ } finally {
3374
+ res.end();
3375
+ }
3376
+ });
3377
+ } catch (e) {
3378
+ if (e instanceof ExposeAuthError) {
3379
+ res.status(e.status).send(e.message);
3380
+ return;
3381
+ }
3382
+ throw e;
3383
+ }
3384
+ };
3385
+ }
3386
+ };
2651
3387
  }
2652
3388
  };
2653
3389
 
2654
- export { AiCursor, BaseVoiceEndpointAdapter, Emitter, InputAudioController, Pump, SocketIoFactory, TransformMessages, VoiceEndpointAdapter, VoiceSocketAdapter, ensureFullWords, httpStreamResponse, useConversation, useSocketConversation };
3390
+ export { Agent, AgentFactory, AgentNetwork, AgentNetworkEvent, AiCursor, BaseVoiceEndpointAdapter, Channel, ChannelName, ConfiguredChannel, Emitter, EventMetaSchema, ExposeAuthError, ExpressEndpoint, InputAudioController, NextEndpoint, Pump, Sink, SocketIoFactory, TransformMessages, VoiceEndpointAdapter, VoiceSocketAdapter, ensureFullWords, formatSSE, httpStreamResponse, isHttpStreamSink, toSSEStream, useConversation, useSocketConversation };
2655
3391
  //# sourceMappingURL=out.js.map
2656
3392
  //# sourceMappingURL=index.js.map