@m4trix/core 0.15.0 → 0.15.2

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
@@ -1,6 +1,6 @@
1
+ import { randomUUID } from 'crypto';
1
2
  import { Brand, Schema, Tracer, Layer, Effect, Exit, PubSub, Queue, Cause } from 'effect';
2
3
  export { Schema as S } from 'effect';
3
- import { randomUUID } from 'crypto';
4
4
 
5
5
  var __accessCheck = (obj, member, msg) => {
6
6
  if (!member.has(obj))
@@ -78,16 +78,10 @@ var SocketIoFactory = class _SocketIoFactory {
78
78
  this.socket.on(prefix("voice:output_file"), onVoiceOutputFile);
79
79
  }
80
80
  if (onVoiceOutputTranscriptDelta) {
81
- this.socket.on(
82
- prefix("voice:output_transcript_delta"),
83
- onVoiceOutputTranscriptDelta
84
- );
81
+ this.socket.on(prefix("voice:output_transcript_delta"), onVoiceOutputTranscriptDelta);
85
82
  }
86
83
  if (onVoiceOutputTranscriptFull) {
87
- this.socket.on(
88
- prefix("voice:output_transcript_full"),
89
- onVoiceOutputTranscriptFull
90
- );
84
+ this.socket.on(prefix("voice:output_transcript_full"), onVoiceOutputTranscriptFull);
91
85
  }
92
86
  }
93
87
  setupChatEvents(_socket) {
@@ -98,56 +92,114 @@ var SocketIoFactory = class _SocketIoFactory {
98
92
  return this.prefix ? `${this.prefix}:${event}` : event;
99
93
  }
100
94
  };
101
- var KEBAB_CASE_REGEX = /^[a-z0-9]+(-[a-z0-9]+)*$/;
102
- var ChannelName = Brand.refined(
103
- (s) => typeof s === "string" && KEBAB_CASE_REGEX.test(s),
104
- (s) => Brand.error(`Expected kebab-case (e.g. my-channel-name), got: ${s}`)
105
- );
106
-
107
- // src/matrix/agent-network/channel.ts
108
- var Sink = {
109
- kafka(config) {
110
- return { _tag: "SinkDef", type: "kafka", config };
111
- },
112
- httpStream() {
113
- return { _tag: "SinkDef", type: "http-stream", config: {} };
95
+ var _params, _logic, _id, _listensTo;
96
+ var Agent = class {
97
+ constructor(logic, params, listensTo) {
98
+ __privateAdd(this, _params, void 0);
99
+ __privateAdd(this, _logic, void 0);
100
+ __privateAdd(this, _id, void 0);
101
+ __privateAdd(this, _listensTo, void 0);
102
+ __privateSet(this, _logic, logic);
103
+ __privateSet(this, _params, params);
104
+ __privateSet(this, _id, `agent-${randomUUID()}`);
105
+ __privateSet(this, _listensTo, listensTo ?? []);
106
+ }
107
+ getListensTo() {
108
+ return __privateGet(this, _listensTo);
109
+ }
110
+ async invoke(options) {
111
+ const { triggerEvent, emit, runEvents, contextEvents } = options ?? {};
112
+ const emitFn = emit ?? ((_event) => {
113
+ });
114
+ await __privateGet(this, _logic).call(this, {
115
+ params: __privateGet(this, _params),
116
+ triggerEvent: triggerEvent ?? void 0,
117
+ emit: emitFn,
118
+ runEvents: runEvents ?? [],
119
+ contextEvents: contextEvents ?? {
120
+ all: [],
121
+ byRun: () => [],
122
+ map: /* @__PURE__ */ new Map()
123
+ }
124
+ });
125
+ }
126
+ getId() {
127
+ return __privateGet(this, _id);
114
128
  }
115
129
  };
116
- function isHttpStreamSink(sink) {
117
- return sink.type === "http-stream";
118
- }
119
- var ConfiguredChannel = class {
120
- constructor(name) {
121
- this._tag = "ConfiguredChannel";
122
- this._events = [];
123
- this._sinks = [];
124
- this.name = name;
130
+ _params = new WeakMap();
131
+ _logic = new WeakMap();
132
+ _id = new WeakMap();
133
+ _listensTo = new WeakMap();
134
+
135
+ // src/matrix/agent-factory.ts
136
+ var AgentFactory = class _AgentFactory {
137
+ constructor({
138
+ logic,
139
+ paramsSchema,
140
+ listensTo = [],
141
+ emits = []
142
+ }) {
143
+ this._logic = logic;
144
+ this._paramsSchema = paramsSchema;
145
+ this._listensTo = listensTo;
146
+ this._emits = emits;
125
147
  }
126
- events(events) {
127
- this._events = [...events];
128
- return this;
148
+ getConstructorState() {
149
+ return {
150
+ logic: this._logic,
151
+ paramsSchema: this._paramsSchema,
152
+ listensTo: this._listensTo,
153
+ emits: this._emits
154
+ };
129
155
  }
130
- sink(sink) {
131
- this._sinks = [...this._sinks, sink];
132
- return this;
156
+ /** Union of all event definitions this agent listens to */
157
+ getListensTo() {
158
+ return this._listensTo;
133
159
  }
134
- sinks(sinks) {
135
- this._sinks = [...sinks];
136
- return this;
160
+ /** Union of all event definitions this agent can emit */
161
+ getEmits() {
162
+ return this._emits;
137
163
  }
138
- getEvents() {
139
- return this._events;
164
+ getLogic() {
165
+ return this._logic;
140
166
  }
141
- getSinks() {
142
- return this._sinks;
167
+ static run() {
168
+ return new _AgentFactory({});
143
169
  }
144
- };
145
- var Channel = {
146
- of(name) {
147
- return {
148
- _tag: "ChannelDef",
149
- name
150
- };
170
+ params(params) {
171
+ const { logic, ...rest } = this.getConstructorState();
172
+ return new _AgentFactory({
173
+ ...rest,
174
+ logic,
175
+ paramsSchema: params
176
+ });
177
+ }
178
+ listensTo(events) {
179
+ return new _AgentFactory({
180
+ ...this.getConstructorState(),
181
+ listensTo: [...this._listensTo, ...events]
182
+ });
183
+ }
184
+ emits(events) {
185
+ return new _AgentFactory({
186
+ ...this.getConstructorState(),
187
+ emits: [...this._emits, ...events]
188
+ });
189
+ }
190
+ logic(fn) {
191
+ return new _AgentFactory({
192
+ ...this.getConstructorState(),
193
+ logic: fn
194
+ });
195
+ }
196
+ produce(params) {
197
+ const listensTo = this._listensTo.map((e) => e.name);
198
+ return new Agent(
199
+ this._logic,
200
+ params,
201
+ listensTo
202
+ );
151
203
  }
152
204
  };
153
205
 
@@ -303,10 +355,7 @@ var runSubscriber = (agent, publishesTo, dequeue, plane, emitQueue, channelName)
303
355
  if (listensTo.length > 0 && !listensTo.includes(envelope.name)) {
304
356
  return;
305
357
  }
306
- const runEvents = plane.getRunEvents(
307
- envelope.meta.runId,
308
- envelope.meta.contextId
309
- );
358
+ const runEvents = plane.getRunEvents(envelope.meta.runId, envelope.meta.contextId);
310
359
  const contextEvents = plane.getContextEvents(envelope.meta.contextId);
311
360
  yield* Effect.withSpan("agent.listen", {
312
361
  attributes: {
@@ -341,9 +390,7 @@ var runSubscriber = (agent, publishesTo, dequeue, plane, emitQueue, channelName)
341
390
  ).catch(() => {
342
391
  });
343
392
  } else {
344
- Effect.runFork(
345
- plane.publishToChannels(publishesTo, fullEnvelope)
346
- );
393
+ Effect.runFork(plane.publishToChannels(publishesTo, fullEnvelope));
347
394
  }
348
395
  },
349
396
  runEvents,
@@ -369,18 +416,65 @@ var run = (network, plane, options) => Effect.gen(function* () {
369
416
  for (const reg of registrations.values()) {
370
417
  for (const channel of reg.subscribedTo) {
371
418
  const dequeue = yield* plane.subscribe(channel.name);
372
- yield* runSubscriber(
373
- reg.agent,
374
- reg.publishesTo,
375
- dequeue,
376
- plane,
377
- emitQueue,
378
- channel.name
379
- );
419
+ yield* runSubscriber(reg.agent, reg.publishesTo, dequeue, plane, emitQueue, channel.name);
380
420
  }
381
421
  }
382
422
  yield* Effect.never;
383
423
  });
424
+ var KEBAB_CASE_REGEX = /^[a-z0-9]+(-[a-z0-9]+)*$/;
425
+ var ChannelName = Brand.refined(
426
+ (s) => typeof s === "string" && KEBAB_CASE_REGEX.test(s),
427
+ (s) => Brand.error(`Expected kebab-case (e.g. my-channel-name), got: ${s}`)
428
+ );
429
+
430
+ // src/matrix/agent-network/channel.ts
431
+ var Sink = {
432
+ kafka(config) {
433
+ return { _tag: "SinkDef", type: "kafka", config };
434
+ },
435
+ httpStream() {
436
+ return { _tag: "SinkDef", type: "http-stream", config: {} };
437
+ }
438
+ };
439
+ function isHttpStreamSink(sink) {
440
+ return sink.type === "http-stream";
441
+ }
442
+ var ConfiguredChannel = class {
443
+ constructor(name) {
444
+ this._tag = "ConfiguredChannel";
445
+ this._events = [];
446
+ this._sinks = [];
447
+ this.name = name;
448
+ }
449
+ events(events) {
450
+ this._events = [...events];
451
+ return this;
452
+ }
453
+ sink(sink) {
454
+ this._sinks = [...this._sinks, sink];
455
+ return this;
456
+ }
457
+ sinks(sinks) {
458
+ this._sinks = [...sinks];
459
+ return this;
460
+ }
461
+ getEvents() {
462
+ return this._events;
463
+ }
464
+ getSinks() {
465
+ return this._sinks;
466
+ }
467
+ };
468
+ var Channel = {
469
+ of(name) {
470
+ return {
471
+ _tag: "ChannelDef",
472
+ name
473
+ };
474
+ }
475
+ };
476
+
477
+ // src/matrix/io/expose.ts
384
478
  async function extractPayload(req) {
385
479
  const webRequest = req.request;
386
480
  if (webRequest?.method === "POST") {
@@ -444,14 +538,7 @@ function streamFromDequeue(take, signal, eventFilter) {
444
538
  };
445
539
  }
446
540
  function expose(network, options) {
447
- const {
448
- auth,
449
- select,
450
- plane: providedPlane,
451
- onRequest,
452
- triggerEvents,
453
- tracingLayer
454
- } = options;
541
+ const { auth, select, plane: providedPlane, onRequest, triggerEvents, tracingLayer } = options;
455
542
  const triggerEventDef = triggerEvents?.[0];
456
543
  const triggerEventName = triggerEventDef?.name ?? "request";
457
544
  const channels = resolveChannels(network, select);
@@ -498,10 +585,8 @@ function expose(network, options) {
498
585
  meta,
499
586
  payload: opts.event.payload
500
587
  };
501
- Effect.runPromise(plane.publish(targetChannel, envelope)).catch(
502
- () => {
503
- }
504
- );
588
+ Effect.runPromise(plane.publish(targetChannel, envelope)).catch(() => {
589
+ });
505
590
  };
506
591
  const dequeue = yield* plane.subscribe(channels[0]);
507
592
  if (onRequest) {
@@ -541,10 +626,7 @@ function expose(network, options) {
541
626
  if (auth) {
542
627
  const result = await auth(req);
543
628
  if (!result.allowed) {
544
- throw new ExposeAuthError(
545
- result.message ?? "Unauthorized",
546
- result.status ?? 401
547
- );
629
+ throw new ExposeAuthError(result.message ?? "Unauthorized", result.status ?? 401);
548
630
  }
549
631
  }
550
632
  return consumer ? createStream(req, consumer) : createStream(req);
@@ -721,7 +803,9 @@ var AgentNetworkEvent = {
721
803
  const makeBound = (meta, payload2) => Effect.runSync(
722
804
  decodeEnvelope({ name, meta, payload: payload2 })
723
805
  );
724
- const makeEffect = (payload2) => decodePayload(payload2).pipe(Effect.map((p) => ({ name, payload: p })));
806
+ const makeEffect = (payload2) => decodePayload(payload2).pipe(
807
+ Effect.map((p) => ({ name, payload: p }))
808
+ );
725
809
  const makeBoundEffect = (meta, payload2) => decodeEnvelope({ name, meta, payload: payload2 });
726
810
  const is = Schema.is(envelopeSchema);
727
811
  return {
@@ -773,27 +857,27 @@ var EventAggregator = class _EventAggregator {
773
857
  });
774
858
  }
775
859
  };
776
- var _id, _listensTo, _emitWhen, _mapToEmit;
860
+ var _id2, _listensTo2, _emitWhen, _mapToEmit;
777
861
  var EventAggregatorInstance = class {
778
862
  constructor({
779
863
  listensTo,
780
864
  emitWhen,
781
865
  mapToEmit
782
866
  }) {
783
- __privateAdd(this, _id, void 0);
784
- __privateAdd(this, _listensTo, void 0);
867
+ __privateAdd(this, _id2, void 0);
868
+ __privateAdd(this, _listensTo2, void 0);
785
869
  __privateAdd(this, _emitWhen, void 0);
786
870
  __privateAdd(this, _mapToEmit, void 0);
787
- __privateSet(this, _id, `event-aggregator-${randomUUID()}`);
788
- __privateSet(this, _listensTo, listensTo);
871
+ __privateSet(this, _id2, `event-aggregator-${randomUUID()}`);
872
+ __privateSet(this, _listensTo2, listensTo);
789
873
  __privateSet(this, _emitWhen, emitWhen);
790
874
  __privateSet(this, _mapToEmit, mapToEmit);
791
875
  }
792
876
  getId() {
793
- return __privateGet(this, _id);
877
+ return __privateGet(this, _id2);
794
878
  }
795
879
  getListensTo() {
796
- return __privateGet(this, _listensTo);
880
+ return __privateGet(this, _listensTo2);
797
881
  }
798
882
  async invoke(options) {
799
883
  const { triggerEvent, emit, runEvents, contextEvents } = options ?? {};
@@ -824,118 +908,205 @@ var EventAggregatorInstance = class {
824
908
  });
825
909
  }
826
910
  };
827
- _id = new WeakMap();
828
- _listensTo = new WeakMap();
911
+ _id2 = new WeakMap();
912
+ _listensTo2 = new WeakMap();
829
913
  _emitWhen = new WeakMap();
830
914
  _mapToEmit = new WeakMap();
831
- var _params, _logic, _id2, _listensTo2;
832
- var Agent = class {
833
- constructor(logic, params, listensTo) {
834
- __privateAdd(this, _params, void 0);
835
- __privateAdd(this, _logic, void 0);
836
- __privateAdd(this, _id2, void 0);
837
- __privateAdd(this, _listensTo2, void 0);
838
- __privateSet(this, _logic, logic);
839
- __privateSet(this, _params, params);
840
- __privateSet(this, _id2, `agent-${randomUUID()}`);
841
- __privateSet(this, _listensTo2, listensTo ?? []);
842
- }
843
- getListensTo() {
844
- return __privateGet(this, _listensTo2);
845
- }
846
- async invoke(options) {
847
- const { triggerEvent, emit, runEvents, contextEvents } = options ?? {};
848
- const emitFn = emit ?? ((_event) => {
849
- });
850
- await __privateGet(this, _logic).call(this, {
851
- params: __privateGet(this, _params),
852
- triggerEvent: triggerEvent ?? void 0,
853
- emit: emitFn,
854
- runEvents: runEvents ?? [],
855
- contextEvents: contextEvents ?? {
856
- all: [],
857
- byRun: () => [],
858
- map: /* @__PURE__ */ new Map()
859
- }
860
- });
861
- }
862
- getId() {
863
- return __privateGet(this, _id2);
915
+ var randomHexString = (length) => {
916
+ const chars = "abcdef0123456789";
917
+ let result = "";
918
+ for (let i = 0; i < length; i++) {
919
+ result += chars.charAt(Math.floor(Math.random() * chars.length));
864
920
  }
921
+ return result;
865
922
  };
866
- _params = new WeakMap();
867
- _logic = new WeakMap();
868
- _id2 = new WeakMap();
869
- _listensTo2 = new WeakMap();
870
-
871
- // src/matrix/agent-factory.ts
872
- var AgentFactory = class _AgentFactory {
873
- constructor({
874
- logic,
875
- paramsSchema,
876
- listensTo = [],
877
- emits = []
878
- }) {
879
- this._logic = logic;
880
- this._paramsSchema = paramsSchema;
881
- this._listensTo = listensTo;
882
- this._emits = emits;
883
- }
884
- getConstructorState() {
885
- return {
886
- logic: this._logic,
887
- paramsSchema: this._paramsSchema,
888
- listensTo: this._listensTo,
889
- emits: this._emits
890
- };
891
- }
892
- /** Union of all event definitions this agent listens to */
893
- getListensTo() {
894
- return this._listensTo;
895
- }
896
- /** Union of all event definitions this agent can emit */
897
- getEmits() {
898
- return this._emits;
899
- }
900
- getLogic() {
901
- return this._logic;
923
+ var ConsoleSpan = class {
924
+ constructor(name, parent, context, links, startTime, kind, depth) {
925
+ this.name = name;
926
+ this.parent = parent;
927
+ this.context = context;
928
+ this.startTime = startTime;
929
+ this.kind = kind;
930
+ this.depth = depth;
931
+ this._tag = "Span";
932
+ this.sampled = true;
933
+ this.attributes = /* @__PURE__ */ new Map();
934
+ this.links = [];
935
+ this.traceId = parent._tag === "Some" ? parent.value.traceId : randomHexString(32);
936
+ this.spanId = randomHexString(16);
937
+ this.links = Array.from(links);
938
+ this.status = { _tag: "Started", startTime };
902
939
  }
903
- static run() {
904
- return new _AgentFactory({});
940
+ end(endTime, exit) {
941
+ if (this.status._tag === "Ended")
942
+ return;
943
+ const startTime = this.status.startTime;
944
+ const durationNs = endTime - startTime;
945
+ const durationMs = Number(durationNs) / 1e6;
946
+ const indent = " ".repeat(this.depth);
947
+ const attrs = Object.fromEntries(this.attributes);
948
+ const status = Exit.isSuccess(exit) ? "ok" : "error";
949
+ console.log(
950
+ `${indent}[trace] ${this.name} ${durationMs.toFixed(2)}ms (${status})`,
951
+ Object.keys(attrs).length > 0 ? attrs : ""
952
+ );
953
+ this.status = { _tag: "Ended", startTime, endTime, exit };
905
954
  }
906
- params(params) {
907
- const { logic, ...rest } = this.getConstructorState();
908
- return new _AgentFactory({
909
- ...rest,
910
- logic,
911
- paramsSchema: params
912
- });
955
+ attribute(key, value) {
956
+ this.attributes.set(key, value);
913
957
  }
914
- listensTo(events) {
915
- return new _AgentFactory({
916
- ...this.getConstructorState(),
917
- listensTo: [...this._listensTo, ...events]
918
- });
958
+ event(_name, _startTime, _attributes) {
919
959
  }
920
- emits(events) {
921
- return new _AgentFactory({
922
- ...this.getConstructorState(),
923
- emits: [...this._emits, ...events]
924
- });
960
+ addLinks(links) {
961
+ this.links.push(...links);
925
962
  }
926
- logic(fn) {
927
- return new _AgentFactory({
928
- ...this.getConstructorState(),
929
- logic: fn
930
- });
963
+ };
964
+ function getDepth(parent) {
965
+ if (parent._tag === "None")
966
+ return 0;
967
+ const p = parent.value;
968
+ if (p._tag === "ExternalSpan")
969
+ return 0;
970
+ return 1 + getDepth(p.parent);
971
+ }
972
+ var consoleTracer = Tracer.make({
973
+ span: (name, parent, context, links, startTime, kind) => new ConsoleSpan(name, parent, context, links, startTime, kind, getDepth(parent)),
974
+ context: (f) => f()
975
+ });
976
+ var consoleTracerLayer = Layer.setTracer(consoleTracer);
977
+
978
+ // src/matrix/io/protocols/sse.ts
979
+ function formatSSE(envelope) {
980
+ const data = JSON.stringify(envelope);
981
+ return `event: ${envelope.name}
982
+ data: ${data}
983
+
984
+ `;
985
+ }
986
+ function toSSEStream(source, signal) {
987
+ const encoder = new TextEncoder();
988
+ return new ReadableStream({
989
+ async start(controller) {
990
+ const onAbort = () => controller.close();
991
+ signal?.addEventListener("abort", onAbort, { once: true });
992
+ try {
993
+ for await (const envelope of source) {
994
+ if (signal?.aborted)
995
+ break;
996
+ controller.enqueue(encoder.encode(formatSSE(envelope)));
997
+ }
998
+ } finally {
999
+ signal?.removeEventListener("abort", onAbort);
1000
+ controller.close();
1001
+ }
1002
+ }
1003
+ });
1004
+ }
1005
+
1006
+ // src/matrix/io/adapters/next-endpoint.ts
1007
+ var NextEndpoint = {
1008
+ from(api, options) {
1009
+ if (api.protocol !== "sse") {
1010
+ throw new Error(`NextEndpoint: unsupported protocol "${api.protocol}"`);
1011
+ }
1012
+ const { requestToContextId, requestToRunId } = options;
1013
+ return {
1014
+ handler() {
1015
+ return async (request) => {
1016
+ const req = {
1017
+ request,
1018
+ contextId: requestToContextId(request),
1019
+ runId: requestToRunId(request)
1020
+ };
1021
+ try {
1022
+ const encoder = new TextEncoder();
1023
+ const { readable, writable } = new TransformStream();
1024
+ let consumerStarted;
1025
+ const started = new Promise((resolve) => {
1026
+ consumerStarted = resolve;
1027
+ });
1028
+ const streamDone = api.createStream(req, async (stream) => {
1029
+ consumerStarted();
1030
+ const writer = writable.getWriter();
1031
+ try {
1032
+ for await (const envelope of stream) {
1033
+ if (request.signal?.aborted)
1034
+ break;
1035
+ await writer.write(encoder.encode(formatSSE(envelope)));
1036
+ }
1037
+ } finally {
1038
+ await writer.close();
1039
+ }
1040
+ });
1041
+ await Promise.race([started, streamDone]);
1042
+ streamDone.catch(() => {
1043
+ });
1044
+ return new Response(readable, {
1045
+ headers: {
1046
+ "Content-Type": "text/event-stream",
1047
+ "Cache-Control": "no-cache",
1048
+ Connection: "keep-alive"
1049
+ }
1050
+ });
1051
+ } catch (e) {
1052
+ if (e instanceof ExposeAuthError) {
1053
+ return new Response(e.message, { status: e.status });
1054
+ }
1055
+ throw e;
1056
+ }
1057
+ };
1058
+ }
1059
+ };
931
1060
  }
932
- produce(params) {
933
- const listensTo = this._listensTo.map((e) => e.name);
934
- return new Agent(
935
- this._logic,
936
- params,
937
- listensTo
938
- );
1061
+ };
1062
+
1063
+ // src/matrix/io/adapters/express-endpoint.ts
1064
+ var ExpressEndpoint = {
1065
+ from(api, options) {
1066
+ if (api.protocol !== "sse") {
1067
+ throw new Error(`ExpressEndpoint: unsupported protocol "${api.protocol}"`);
1068
+ }
1069
+ const { requestToContextId, requestToRunId } = options;
1070
+ return {
1071
+ handler() {
1072
+ return async (req, res) => {
1073
+ const controller = new AbortController();
1074
+ req.on("close", () => controller.abort());
1075
+ const exposeReq = {
1076
+ request: { signal: controller.signal },
1077
+ req,
1078
+ res,
1079
+ contextId: requestToContextId(req),
1080
+ runId: requestToRunId(req)
1081
+ };
1082
+ try {
1083
+ const encoder = new TextEncoder();
1084
+ await api.createStream(exposeReq, async (stream) => {
1085
+ res.setHeader("Content-Type", "text/event-stream");
1086
+ res.setHeader("Cache-Control", "no-cache");
1087
+ res.setHeader("Connection", "keep-alive");
1088
+ res.flushHeaders?.();
1089
+ try {
1090
+ for await (const envelope of stream) {
1091
+ if (controller.signal.aborted)
1092
+ break;
1093
+ res.write(encoder.encode(formatSSE(envelope)));
1094
+ res.flush?.();
1095
+ }
1096
+ } finally {
1097
+ res.end();
1098
+ }
1099
+ });
1100
+ } catch (e) {
1101
+ if (e instanceof ExposeAuthError) {
1102
+ res.status(e.status).send(e.message);
1103
+ return;
1104
+ }
1105
+ throw e;
1106
+ }
1107
+ };
1108
+ }
1109
+ };
939
1110
  }
940
1111
  };
941
1112
  var CAMEL_CASE_REGEX = /^[a-z][a-zA-Z0-9]*$/;
@@ -1051,9 +1222,7 @@ var Skill = class _Skill {
1051
1222
  const layersObj = runtime?.layers ?? {};
1052
1223
  const chunks = [];
1053
1224
  const emit = (chunk) => {
1054
- const decoded = Effect.runSync(
1055
- decodeChunk(chunk)
1056
- );
1225
+ const decoded = Effect.runSync(decodeChunk(chunk));
1057
1226
  chunks.push(decoded);
1058
1227
  };
1059
1228
  const done = await defineFn({
@@ -1061,9 +1230,7 @@ var Skill = class _Skill {
1061
1230
  emit,
1062
1231
  layers: layersObj
1063
1232
  });
1064
- const decodedDone = Effect.runSync(
1065
- decodeDone(done)
1066
- );
1233
+ const decodedDone = Effect.runSync(decodeDone(done));
1067
1234
  return { chunks, done: decodedDone };
1068
1235
  };
1069
1236
  return {
@@ -1074,9 +1241,7 @@ var Skill = class _Skill {
1074
1241
  const layersObj = runtime?.layers ?? {};
1075
1242
  const chunks = [];
1076
1243
  const emit = (chunk) => {
1077
- const decoded = Effect.runSync(
1078
- decodeChunk(chunk)
1079
- );
1244
+ const decoded = Effect.runSync(decodeChunk(chunk));
1080
1245
  chunks.push(decoded);
1081
1246
  };
1082
1247
  const done = await defineFn({
@@ -1084,9 +1249,7 @@ var Skill = class _Skill {
1084
1249
  emit,
1085
1250
  layers: layersObj
1086
1251
  });
1087
- const decodedDone = Effect.runSync(
1088
- decodeDone(done)
1089
- );
1252
+ const decodedDone = Effect.runSync(decodeDone(done));
1090
1253
  for (const c of chunks) {
1091
1254
  yield c;
1092
1255
  }
@@ -1102,215 +1265,6 @@ var Skill = class _Skill {
1102
1265
  }
1103
1266
  };
1104
1267
 
1105
- // src/matrix/io/protocols/sse.ts
1106
- function formatSSE(envelope) {
1107
- const data = JSON.stringify(envelope);
1108
- return `event: ${envelope.name}
1109
- data: ${data}
1110
-
1111
- `;
1112
- }
1113
- function toSSEStream(source, signal) {
1114
- const encoder = new TextEncoder();
1115
- return new ReadableStream({
1116
- async start(controller) {
1117
- const onAbort = () => controller.close();
1118
- signal?.addEventListener("abort", onAbort, { once: true });
1119
- try {
1120
- for await (const envelope of source) {
1121
- if (signal?.aborted)
1122
- break;
1123
- controller.enqueue(encoder.encode(formatSSE(envelope)));
1124
- }
1125
- } finally {
1126
- signal?.removeEventListener("abort", onAbort);
1127
- controller.close();
1128
- }
1129
- }
1130
- });
1131
- }
1132
-
1133
- // src/matrix/io/adapters/next-endpoint.ts
1134
- var NextEndpoint = {
1135
- from(api, options) {
1136
- if (api.protocol !== "sse") {
1137
- throw new Error(`NextEndpoint: unsupported protocol "${api.protocol}"`);
1138
- }
1139
- const { requestToContextId, requestToRunId } = options;
1140
- return {
1141
- handler() {
1142
- return async (request) => {
1143
- const req = {
1144
- request,
1145
- contextId: requestToContextId(request),
1146
- runId: requestToRunId(request)
1147
- };
1148
- try {
1149
- const encoder = new TextEncoder();
1150
- const { readable, writable } = new TransformStream();
1151
- let consumerStarted;
1152
- const started = new Promise((resolve) => {
1153
- consumerStarted = resolve;
1154
- });
1155
- const streamDone = api.createStream(req, async (stream) => {
1156
- consumerStarted();
1157
- const writer = writable.getWriter();
1158
- try {
1159
- for await (const envelope of stream) {
1160
- if (request.signal?.aborted)
1161
- break;
1162
- await writer.write(encoder.encode(formatSSE(envelope)));
1163
- }
1164
- } finally {
1165
- await writer.close();
1166
- }
1167
- });
1168
- await Promise.race([started, streamDone]);
1169
- streamDone.catch(() => {
1170
- });
1171
- return new Response(readable, {
1172
- headers: {
1173
- "Content-Type": "text/event-stream",
1174
- "Cache-Control": "no-cache",
1175
- Connection: "keep-alive"
1176
- }
1177
- });
1178
- } catch (e) {
1179
- if (e instanceof ExposeAuthError) {
1180
- return new Response(e.message, { status: e.status });
1181
- }
1182
- throw e;
1183
- }
1184
- };
1185
- }
1186
- };
1187
- }
1188
- };
1189
-
1190
- // src/matrix/io/adapters/express-endpoint.ts
1191
- var ExpressEndpoint = {
1192
- from(api, options) {
1193
- if (api.protocol !== "sse") {
1194
- throw new Error(
1195
- `ExpressEndpoint: unsupported protocol "${api.protocol}"`
1196
- );
1197
- }
1198
- const { requestToContextId, requestToRunId } = options;
1199
- return {
1200
- handler() {
1201
- return async (req, res) => {
1202
- const controller = new AbortController();
1203
- req.on("close", () => controller.abort());
1204
- const exposeReq = {
1205
- request: { signal: controller.signal },
1206
- req,
1207
- res,
1208
- contextId: requestToContextId(req),
1209
- runId: requestToRunId(req)
1210
- };
1211
- try {
1212
- const encoder = new TextEncoder();
1213
- await api.createStream(exposeReq, async (stream) => {
1214
- res.setHeader("Content-Type", "text/event-stream");
1215
- res.setHeader("Cache-Control", "no-cache");
1216
- res.setHeader("Connection", "keep-alive");
1217
- res.flushHeaders?.();
1218
- try {
1219
- for await (const envelope of stream) {
1220
- if (controller.signal.aborted)
1221
- break;
1222
- res.write(encoder.encode(formatSSE(envelope)));
1223
- res.flush?.();
1224
- }
1225
- } finally {
1226
- res.end();
1227
- }
1228
- });
1229
- } catch (e) {
1230
- if (e instanceof ExposeAuthError) {
1231
- res.status(e.status).send(e.message);
1232
- return;
1233
- }
1234
- throw e;
1235
- }
1236
- };
1237
- }
1238
- };
1239
- }
1240
- };
1241
- var randomHexString = (length) => {
1242
- const chars = "abcdef0123456789";
1243
- let result = "";
1244
- for (let i = 0; i < length; i++) {
1245
- result += chars.charAt(Math.floor(Math.random() * chars.length));
1246
- }
1247
- return result;
1248
- };
1249
- var ConsoleSpan = class {
1250
- constructor(name, parent, context, links, startTime, kind, depth) {
1251
- this.name = name;
1252
- this.parent = parent;
1253
- this.context = context;
1254
- this.startTime = startTime;
1255
- this.kind = kind;
1256
- this.depth = depth;
1257
- this._tag = "Span";
1258
- this.sampled = true;
1259
- this.attributes = /* @__PURE__ */ new Map();
1260
- this.links = [];
1261
- this.traceId = parent._tag === "Some" ? parent.value.traceId : randomHexString(32);
1262
- this.spanId = randomHexString(16);
1263
- this.links = Array.from(links);
1264
- this.status = { _tag: "Started", startTime };
1265
- }
1266
- end(endTime, exit) {
1267
- if (this.status._tag === "Ended")
1268
- return;
1269
- const startTime = this.status.startTime;
1270
- const durationNs = endTime - startTime;
1271
- const durationMs = Number(durationNs) / 1e6;
1272
- const indent = " ".repeat(this.depth);
1273
- const attrs = Object.fromEntries(this.attributes);
1274
- const status = Exit.isSuccess(exit) ? "ok" : "error";
1275
- console.log(
1276
- `${indent}[trace] ${this.name} ${durationMs.toFixed(2)}ms (${status})`,
1277
- Object.keys(attrs).length > 0 ? attrs : ""
1278
- );
1279
- this.status = { _tag: "Ended", startTime, endTime, exit };
1280
- }
1281
- attribute(key, value) {
1282
- this.attributes.set(key, value);
1283
- }
1284
- event(_name, _startTime, _attributes) {
1285
- }
1286
- addLinks(links) {
1287
- this.links.push(...links);
1288
- }
1289
- };
1290
- function getDepth(parent) {
1291
- if (parent._tag === "None")
1292
- return 0;
1293
- const p = parent.value;
1294
- if (p._tag === "ExternalSpan")
1295
- return 0;
1296
- return 1 + getDepth(p.parent);
1297
- }
1298
- var consoleTracer = Tracer.make({
1299
- span: (name, parent, context, links, startTime, kind) => new ConsoleSpan(
1300
- name,
1301
- parent,
1302
- context,
1303
- links,
1304
- startTime,
1305
- kind,
1306
- getDepth(parent)
1307
- ),
1308
- context: (f) => f()
1309
- });
1310
- var consoleTracerLayer = Layer.setTracer(
1311
- consoleTracer
1312
- );
1313
-
1314
1268
  export { Agent, AgentFactory, AgentNetwork, AgentNetworkEvent, Channel, ChannelName, ConfiguredChannel, DepedencyLayer, Done, EventAggregator, EventAggregatorInstance, EventMetaSchema, ExposeAuthError, ExpressEndpoint, LayerName, NextEndpoint, Sink, Skill, SocketIoFactory, consoleTracer, consoleTracerLayer, formatSSE, isHttpStreamSink, toSSEStream };
1315
1269
  //# sourceMappingURL=out.js.map
1316
1270
  //# sourceMappingURL=index.js.map