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