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