@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.
@@ -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))
@@ -21,56 +21,114 @@ var __privateSet = (obj, member, value, setter) => {
21
21
  setter ? setter.call(obj, value) : member.set(obj, value);
22
22
  return value;
23
23
  };
24
- var KEBAB_CASE_REGEX = /^[a-z0-9]+(-[a-z0-9]+)*$/;
25
- var ChannelName = effect.Brand.refined(
26
- (s) => typeof s === "string" && KEBAB_CASE_REGEX.test(s),
27
- (s) => effect.Brand.error(`Expected kebab-case (e.g. my-channel-name), got: ${s}`)
28
- );
29
-
30
- // src/matrix/agent-network/channel.ts
31
- var Sink = {
32
- kafka(config) {
33
- return { _tag: "SinkDef", type: "kafka", config };
34
- },
35
- httpStream() {
36
- return { _tag: "SinkDef", type: "http-stream", config: {} };
24
+ var _params, _logic, _id, _listensTo;
25
+ var Agent = class {
26
+ constructor(logic, params, listensTo) {
27
+ __privateAdd(this, _params, void 0);
28
+ __privateAdd(this, _logic, void 0);
29
+ __privateAdd(this, _id, void 0);
30
+ __privateAdd(this, _listensTo, void 0);
31
+ __privateSet(this, _logic, logic);
32
+ __privateSet(this, _params, params);
33
+ __privateSet(this, _id, `agent-${crypto$1.randomUUID()}`);
34
+ __privateSet(this, _listensTo, listensTo ?? []);
35
+ }
36
+ getListensTo() {
37
+ return __privateGet(this, _listensTo);
38
+ }
39
+ async invoke(options) {
40
+ const { triggerEvent, emit, runEvents, contextEvents } = options ?? {};
41
+ const emitFn = emit ?? ((_event) => {
42
+ });
43
+ await __privateGet(this, _logic).call(this, {
44
+ params: __privateGet(this, _params),
45
+ triggerEvent: triggerEvent ?? void 0,
46
+ emit: emitFn,
47
+ runEvents: runEvents ?? [],
48
+ contextEvents: contextEvents ?? {
49
+ all: [],
50
+ byRun: () => [],
51
+ map: /* @__PURE__ */ new Map()
52
+ }
53
+ });
54
+ }
55
+ getId() {
56
+ return __privateGet(this, _id);
37
57
  }
38
58
  };
39
- function isHttpStreamSink(sink) {
40
- return sink.type === "http-stream";
41
- }
42
- var ConfiguredChannel = class {
43
- constructor(name) {
44
- this._tag = "ConfiguredChannel";
45
- this._events = [];
46
- this._sinks = [];
47
- this.name = name;
59
+ _params = new WeakMap();
60
+ _logic = new WeakMap();
61
+ _id = new WeakMap();
62
+ _listensTo = new WeakMap();
63
+
64
+ // src/matrix/agent-factory.ts
65
+ var AgentFactory = class _AgentFactory {
66
+ constructor({
67
+ logic,
68
+ paramsSchema,
69
+ listensTo = [],
70
+ emits = []
71
+ }) {
72
+ this._logic = logic;
73
+ this._paramsSchema = paramsSchema;
74
+ this._listensTo = listensTo;
75
+ this._emits = emits;
48
76
  }
49
- events(events) {
50
- this._events = [...events];
51
- return this;
77
+ getConstructorState() {
78
+ return {
79
+ logic: this._logic,
80
+ paramsSchema: this._paramsSchema,
81
+ listensTo: this._listensTo,
82
+ emits: this._emits
83
+ };
52
84
  }
53
- sink(sink) {
54
- this._sinks = [...this._sinks, sink];
55
- return this;
85
+ /** Union of all event definitions this agent listens to */
86
+ getListensTo() {
87
+ return this._listensTo;
56
88
  }
57
- sinks(sinks) {
58
- this._sinks = [...sinks];
59
- return this;
89
+ /** Union of all event definitions this agent can emit */
90
+ getEmits() {
91
+ return this._emits;
60
92
  }
61
- getEvents() {
62
- return this._events;
93
+ getLogic() {
94
+ return this._logic;
63
95
  }
64
- getSinks() {
65
- return this._sinks;
96
+ static run() {
97
+ return new _AgentFactory({});
66
98
  }
67
- };
68
- var Channel = {
69
- of(name) {
70
- return {
71
- _tag: "ChannelDef",
72
- name
73
- };
99
+ params(params) {
100
+ const { logic, ...rest } = this.getConstructorState();
101
+ return new _AgentFactory({
102
+ ...rest,
103
+ logic,
104
+ paramsSchema: params
105
+ });
106
+ }
107
+ listensTo(events) {
108
+ return new _AgentFactory({
109
+ ...this.getConstructorState(),
110
+ listensTo: [...this._listensTo, ...events]
111
+ });
112
+ }
113
+ emits(events) {
114
+ return new _AgentFactory({
115
+ ...this.getConstructorState(),
116
+ emits: [...this._emits, ...events]
117
+ });
118
+ }
119
+ logic(fn) {
120
+ return new _AgentFactory({
121
+ ...this.getConstructorState(),
122
+ logic: fn
123
+ });
124
+ }
125
+ produce(params) {
126
+ const listensTo = this._listensTo.map((e) => e.name);
127
+ return new Agent(
128
+ this._logic,
129
+ params,
130
+ listensTo
131
+ );
74
132
  }
75
133
  };
76
134
 
@@ -226,10 +284,7 @@ var runSubscriber = (agent, publishesTo, dequeue, plane, emitQueue, channelName)
226
284
  if (listensTo.length > 0 && !listensTo.includes(envelope.name)) {
227
285
  return;
228
286
  }
229
- const runEvents = plane.getRunEvents(
230
- envelope.meta.runId,
231
- envelope.meta.contextId
232
- );
287
+ const runEvents = plane.getRunEvents(envelope.meta.runId, envelope.meta.contextId);
233
288
  const contextEvents = plane.getContextEvents(envelope.meta.contextId);
234
289
  yield* effect.Effect.withSpan("agent.listen", {
235
290
  attributes: {
@@ -264,9 +319,7 @@ var runSubscriber = (agent, publishesTo, dequeue, plane, emitQueue, channelName)
264
319
  ).catch(() => {
265
320
  });
266
321
  } else {
267
- effect.Effect.runFork(
268
- plane.publishToChannels(publishesTo, fullEnvelope)
269
- );
322
+ effect.Effect.runFork(plane.publishToChannels(publishesTo, fullEnvelope));
270
323
  }
271
324
  },
272
325
  runEvents,
@@ -292,18 +345,65 @@ var run = (network, plane, options) => effect.Effect.gen(function* () {
292
345
  for (const reg of registrations.values()) {
293
346
  for (const channel of reg.subscribedTo) {
294
347
  const dequeue = yield* plane.subscribe(channel.name);
295
- yield* runSubscriber(
296
- reg.agent,
297
- reg.publishesTo,
298
- dequeue,
299
- plane,
300
- emitQueue,
301
- channel.name
302
- );
348
+ yield* runSubscriber(reg.agent, reg.publishesTo, dequeue, plane, emitQueue, channel.name);
303
349
  }
304
350
  }
305
351
  yield* effect.Effect.never;
306
352
  });
353
+ var KEBAB_CASE_REGEX = /^[a-z0-9]+(-[a-z0-9]+)*$/;
354
+ var ChannelName = effect.Brand.refined(
355
+ (s) => typeof s === "string" && KEBAB_CASE_REGEX.test(s),
356
+ (s) => effect.Brand.error(`Expected kebab-case (e.g. my-channel-name), got: ${s}`)
357
+ );
358
+
359
+ // src/matrix/agent-network/channel.ts
360
+ var Sink = {
361
+ kafka(config) {
362
+ return { _tag: "SinkDef", type: "kafka", config };
363
+ },
364
+ httpStream() {
365
+ return { _tag: "SinkDef", type: "http-stream", config: {} };
366
+ }
367
+ };
368
+ function isHttpStreamSink(sink) {
369
+ return sink.type === "http-stream";
370
+ }
371
+ var ConfiguredChannel = class {
372
+ constructor(name) {
373
+ this._tag = "ConfiguredChannel";
374
+ this._events = [];
375
+ this._sinks = [];
376
+ this.name = name;
377
+ }
378
+ events(events) {
379
+ this._events = [...events];
380
+ return this;
381
+ }
382
+ sink(sink) {
383
+ this._sinks = [...this._sinks, sink];
384
+ return this;
385
+ }
386
+ sinks(sinks) {
387
+ this._sinks = [...sinks];
388
+ return this;
389
+ }
390
+ getEvents() {
391
+ return this._events;
392
+ }
393
+ getSinks() {
394
+ return this._sinks;
395
+ }
396
+ };
397
+ var Channel = {
398
+ of(name) {
399
+ return {
400
+ _tag: "ChannelDef",
401
+ name
402
+ };
403
+ }
404
+ };
405
+
406
+ // src/matrix/io/expose.ts
307
407
  async function extractPayload(req) {
308
408
  const webRequest = req.request;
309
409
  if (webRequest?.method === "POST") {
@@ -367,14 +467,7 @@ function streamFromDequeue(take, signal, eventFilter) {
367
467
  };
368
468
  }
369
469
  function expose(network, options) {
370
- const {
371
- auth,
372
- select,
373
- plane: providedPlane,
374
- onRequest,
375
- triggerEvents,
376
- tracingLayer
377
- } = options;
470
+ const { auth, select, plane: providedPlane, onRequest, triggerEvents, tracingLayer } = options;
378
471
  const triggerEventDef = triggerEvents?.[0];
379
472
  const triggerEventName = triggerEventDef?.name ?? "request";
380
473
  const channels = resolveChannels(network, select);
@@ -421,10 +514,8 @@ function expose(network, options) {
421
514
  meta,
422
515
  payload: opts.event.payload
423
516
  };
424
- effect.Effect.runPromise(plane.publish(targetChannel, envelope)).catch(
425
- () => {
426
- }
427
- );
517
+ effect.Effect.runPromise(plane.publish(targetChannel, envelope)).catch(() => {
518
+ });
428
519
  };
429
520
  const dequeue = yield* plane.subscribe(channels[0]);
430
521
  if (onRequest) {
@@ -464,10 +555,7 @@ function expose(network, options) {
464
555
  if (auth) {
465
556
  const result = await auth(req);
466
557
  if (!result.allowed) {
467
- throw new ExposeAuthError(
468
- result.message ?? "Unauthorized",
469
- result.status ?? 401
470
- );
558
+ throw new ExposeAuthError(result.message ?? "Unauthorized", result.status ?? 401);
471
559
  }
472
560
  }
473
561
  return consumer ? createStream(req, consumer) : createStream(req);
@@ -644,7 +732,9 @@ var AgentNetworkEvent = {
644
732
  const makeBound = (meta, payload2) => effect.Effect.runSync(
645
733
  decodeEnvelope({ name, meta, payload: payload2 })
646
734
  );
647
- const makeEffect = (payload2) => decodePayload(payload2).pipe(effect.Effect.map((p) => ({ name, payload: p })));
735
+ const makeEffect = (payload2) => decodePayload(payload2).pipe(
736
+ effect.Effect.map((p) => ({ name, payload: p }))
737
+ );
648
738
  const makeBoundEffect = (meta, payload2) => decodeEnvelope({ name, meta, payload: payload2 });
649
739
  const is = effect.Schema.is(envelopeSchema);
650
740
  return {
@@ -696,27 +786,27 @@ var EventAggregator = class _EventAggregator {
696
786
  });
697
787
  }
698
788
  };
699
- var _id, _listensTo, _emitWhen, _mapToEmit;
789
+ var _id2, _listensTo2, _emitWhen, _mapToEmit;
700
790
  var EventAggregatorInstance = class {
701
791
  constructor({
702
792
  listensTo,
703
793
  emitWhen,
704
794
  mapToEmit
705
795
  }) {
706
- __privateAdd(this, _id, void 0);
707
- __privateAdd(this, _listensTo, void 0);
796
+ __privateAdd(this, _id2, void 0);
797
+ __privateAdd(this, _listensTo2, void 0);
708
798
  __privateAdd(this, _emitWhen, void 0);
709
799
  __privateAdd(this, _mapToEmit, void 0);
710
- __privateSet(this, _id, `event-aggregator-${crypto$1.randomUUID()}`);
711
- __privateSet(this, _listensTo, listensTo);
800
+ __privateSet(this, _id2, `event-aggregator-${crypto$1.randomUUID()}`);
801
+ __privateSet(this, _listensTo2, listensTo);
712
802
  __privateSet(this, _emitWhen, emitWhen);
713
803
  __privateSet(this, _mapToEmit, mapToEmit);
714
804
  }
715
805
  getId() {
716
- return __privateGet(this, _id);
806
+ return __privateGet(this, _id2);
717
807
  }
718
808
  getListensTo() {
719
- return __privateGet(this, _listensTo);
809
+ return __privateGet(this, _listensTo2);
720
810
  }
721
811
  async invoke(options) {
722
812
  const { triggerEvent, emit, runEvents, contextEvents } = options ?? {};
@@ -747,118 +837,205 @@ var EventAggregatorInstance = class {
747
837
  });
748
838
  }
749
839
  };
750
- _id = new WeakMap();
751
- _listensTo = new WeakMap();
840
+ _id2 = new WeakMap();
841
+ _listensTo2 = new WeakMap();
752
842
  _emitWhen = new WeakMap();
753
843
  _mapToEmit = new WeakMap();
754
- var _params, _logic, _id2, _listensTo2;
755
- var Agent = class {
756
- constructor(logic, params, listensTo) {
757
- __privateAdd(this, _params, void 0);
758
- __privateAdd(this, _logic, void 0);
759
- __privateAdd(this, _id2, void 0);
760
- __privateAdd(this, _listensTo2, void 0);
761
- __privateSet(this, _logic, logic);
762
- __privateSet(this, _params, params);
763
- __privateSet(this, _id2, `agent-${crypto$1.randomUUID()}`);
764
- __privateSet(this, _listensTo2, listensTo ?? []);
765
- }
766
- getListensTo() {
767
- return __privateGet(this, _listensTo2);
768
- }
769
- async invoke(options) {
770
- const { triggerEvent, emit, runEvents, contextEvents } = options ?? {};
771
- const emitFn = emit ?? ((_event) => {
772
- });
773
- await __privateGet(this, _logic).call(this, {
774
- params: __privateGet(this, _params),
775
- triggerEvent: triggerEvent ?? void 0,
776
- emit: emitFn,
777
- runEvents: runEvents ?? [],
778
- contextEvents: contextEvents ?? {
779
- all: [],
780
- byRun: () => [],
781
- map: /* @__PURE__ */ new Map()
782
- }
783
- });
784
- }
785
- getId() {
786
- return __privateGet(this, _id2);
844
+ var randomHexString = (length) => {
845
+ const chars = "abcdef0123456789";
846
+ let result = "";
847
+ for (let i = 0; i < length; i++) {
848
+ result += chars.charAt(Math.floor(Math.random() * chars.length));
787
849
  }
850
+ return result;
788
851
  };
789
- _params = new WeakMap();
790
- _logic = new WeakMap();
791
- _id2 = new WeakMap();
792
- _listensTo2 = new WeakMap();
793
-
794
- // src/matrix/agent-factory.ts
795
- var AgentFactory = class _AgentFactory {
796
- constructor({
797
- logic,
798
- paramsSchema,
799
- listensTo = [],
800
- emits = []
801
- }) {
802
- this._logic = logic;
803
- this._paramsSchema = paramsSchema;
804
- this._listensTo = listensTo;
805
- this._emits = emits;
806
- }
807
- getConstructorState() {
808
- return {
809
- logic: this._logic,
810
- paramsSchema: this._paramsSchema,
811
- listensTo: this._listensTo,
812
- emits: this._emits
813
- };
814
- }
815
- /** Union of all event definitions this agent listens to */
816
- getListensTo() {
817
- return this._listensTo;
818
- }
819
- /** Union of all event definitions this agent can emit */
820
- getEmits() {
821
- return this._emits;
822
- }
823
- getLogic() {
824
- return this._logic;
852
+ var ConsoleSpan = class {
853
+ constructor(name, parent, context, links, startTime, kind, depth) {
854
+ this.name = name;
855
+ this.parent = parent;
856
+ this.context = context;
857
+ this.startTime = startTime;
858
+ this.kind = kind;
859
+ this.depth = depth;
860
+ this._tag = "Span";
861
+ this.sampled = true;
862
+ this.attributes = /* @__PURE__ */ new Map();
863
+ this.links = [];
864
+ this.traceId = parent._tag === "Some" ? parent.value.traceId : randomHexString(32);
865
+ this.spanId = randomHexString(16);
866
+ this.links = Array.from(links);
867
+ this.status = { _tag: "Started", startTime };
825
868
  }
826
- static run() {
827
- return new _AgentFactory({});
869
+ end(endTime, exit) {
870
+ if (this.status._tag === "Ended")
871
+ return;
872
+ const startTime = this.status.startTime;
873
+ const durationNs = endTime - startTime;
874
+ const durationMs = Number(durationNs) / 1e6;
875
+ const indent = " ".repeat(this.depth);
876
+ const attrs = Object.fromEntries(this.attributes);
877
+ const status = effect.Exit.isSuccess(exit) ? "ok" : "error";
878
+ console.log(
879
+ `${indent}[trace] ${this.name} ${durationMs.toFixed(2)}ms (${status})`,
880
+ Object.keys(attrs).length > 0 ? attrs : ""
881
+ );
882
+ this.status = { _tag: "Ended", startTime, endTime, exit };
828
883
  }
829
- params(params) {
830
- const { logic, ...rest } = this.getConstructorState();
831
- return new _AgentFactory({
832
- ...rest,
833
- logic,
834
- paramsSchema: params
835
- });
884
+ attribute(key, value) {
885
+ this.attributes.set(key, value);
836
886
  }
837
- listensTo(events) {
838
- return new _AgentFactory({
839
- ...this.getConstructorState(),
840
- listensTo: [...this._listensTo, ...events]
841
- });
887
+ event(_name, _startTime, _attributes) {
842
888
  }
843
- emits(events) {
844
- return new _AgentFactory({
845
- ...this.getConstructorState(),
846
- emits: [...this._emits, ...events]
847
- });
889
+ addLinks(links) {
890
+ this.links.push(...links);
848
891
  }
849
- logic(fn) {
850
- return new _AgentFactory({
851
- ...this.getConstructorState(),
852
- logic: fn
853
- });
892
+ };
893
+ function getDepth(parent) {
894
+ if (parent._tag === "None")
895
+ return 0;
896
+ const p = parent.value;
897
+ if (p._tag === "ExternalSpan")
898
+ return 0;
899
+ return 1 + getDepth(p.parent);
900
+ }
901
+ var consoleTracer = effect.Tracer.make({
902
+ span: (name, parent, context, links, startTime, kind) => new ConsoleSpan(name, parent, context, links, startTime, kind, getDepth(parent)),
903
+ context: (f) => f()
904
+ });
905
+ var consoleTracerLayer = effect.Layer.setTracer(consoleTracer);
906
+
907
+ // src/matrix/io/protocols/sse.ts
908
+ function formatSSE(envelope) {
909
+ const data = JSON.stringify(envelope);
910
+ return `event: ${envelope.name}
911
+ data: ${data}
912
+
913
+ `;
914
+ }
915
+ function toSSEStream(source, signal) {
916
+ const encoder = new TextEncoder();
917
+ return new ReadableStream({
918
+ async start(controller) {
919
+ const onAbort = () => controller.close();
920
+ signal?.addEventListener("abort", onAbort, { once: true });
921
+ try {
922
+ for await (const envelope of source) {
923
+ if (signal?.aborted)
924
+ break;
925
+ controller.enqueue(encoder.encode(formatSSE(envelope)));
926
+ }
927
+ } finally {
928
+ signal?.removeEventListener("abort", onAbort);
929
+ controller.close();
930
+ }
931
+ }
932
+ });
933
+ }
934
+
935
+ // src/matrix/io/adapters/next-endpoint.ts
936
+ var NextEndpoint = {
937
+ from(api, options) {
938
+ if (api.protocol !== "sse") {
939
+ throw new Error(`NextEndpoint: unsupported protocol "${api.protocol}"`);
940
+ }
941
+ const { requestToContextId, requestToRunId } = options;
942
+ return {
943
+ handler() {
944
+ return async (request) => {
945
+ const req = {
946
+ request,
947
+ contextId: requestToContextId(request),
948
+ runId: requestToRunId(request)
949
+ };
950
+ try {
951
+ const encoder = new TextEncoder();
952
+ const { readable, writable } = new TransformStream();
953
+ let consumerStarted;
954
+ const started = new Promise((resolve) => {
955
+ consumerStarted = resolve;
956
+ });
957
+ const streamDone = api.createStream(req, async (stream) => {
958
+ consumerStarted();
959
+ const writer = writable.getWriter();
960
+ try {
961
+ for await (const envelope of stream) {
962
+ if (request.signal?.aborted)
963
+ break;
964
+ await writer.write(encoder.encode(formatSSE(envelope)));
965
+ }
966
+ } finally {
967
+ await writer.close();
968
+ }
969
+ });
970
+ await Promise.race([started, streamDone]);
971
+ streamDone.catch(() => {
972
+ });
973
+ return new Response(readable, {
974
+ headers: {
975
+ "Content-Type": "text/event-stream",
976
+ "Cache-Control": "no-cache",
977
+ Connection: "keep-alive"
978
+ }
979
+ });
980
+ } catch (e) {
981
+ if (e instanceof ExposeAuthError) {
982
+ return new Response(e.message, { status: e.status });
983
+ }
984
+ throw e;
985
+ }
986
+ };
987
+ }
988
+ };
854
989
  }
855
- produce(params) {
856
- const listensTo = this._listensTo.map((e) => e.name);
857
- return new Agent(
858
- this._logic,
859
- params,
860
- listensTo
861
- );
990
+ };
991
+
992
+ // src/matrix/io/adapters/express-endpoint.ts
993
+ var ExpressEndpoint = {
994
+ from(api, options) {
995
+ if (api.protocol !== "sse") {
996
+ throw new Error(`ExpressEndpoint: unsupported protocol "${api.protocol}"`);
997
+ }
998
+ const { requestToContextId, requestToRunId } = options;
999
+ return {
1000
+ handler() {
1001
+ return async (req, res) => {
1002
+ const controller = new AbortController();
1003
+ req.on("close", () => controller.abort());
1004
+ const exposeReq = {
1005
+ request: { signal: controller.signal },
1006
+ req,
1007
+ res,
1008
+ contextId: requestToContextId(req),
1009
+ runId: requestToRunId(req)
1010
+ };
1011
+ try {
1012
+ const encoder = new TextEncoder();
1013
+ await api.createStream(exposeReq, async (stream) => {
1014
+ res.setHeader("Content-Type", "text/event-stream");
1015
+ res.setHeader("Cache-Control", "no-cache");
1016
+ res.setHeader("Connection", "keep-alive");
1017
+ res.flushHeaders?.();
1018
+ try {
1019
+ for await (const envelope of stream) {
1020
+ if (controller.signal.aborted)
1021
+ break;
1022
+ res.write(encoder.encode(formatSSE(envelope)));
1023
+ res.flush?.();
1024
+ }
1025
+ } finally {
1026
+ res.end();
1027
+ }
1028
+ });
1029
+ } catch (e) {
1030
+ if (e instanceof ExposeAuthError) {
1031
+ res.status(e.status).send(e.message);
1032
+ return;
1033
+ }
1034
+ throw e;
1035
+ }
1036
+ };
1037
+ }
1038
+ };
862
1039
  }
863
1040
  };
864
1041
  var CAMEL_CASE_REGEX = /^[a-z][a-zA-Z0-9]*$/;
@@ -974,9 +1151,7 @@ var Skill = class _Skill {
974
1151
  const layersObj = runtime?.layers ?? {};
975
1152
  const chunks = [];
976
1153
  const emit = (chunk) => {
977
- const decoded = effect.Effect.runSync(
978
- decodeChunk(chunk)
979
- );
1154
+ const decoded = effect.Effect.runSync(decodeChunk(chunk));
980
1155
  chunks.push(decoded);
981
1156
  };
982
1157
  const done = await defineFn({
@@ -984,9 +1159,7 @@ var Skill = class _Skill {
984
1159
  emit,
985
1160
  layers: layersObj
986
1161
  });
987
- const decodedDone = effect.Effect.runSync(
988
- decodeDone(done)
989
- );
1162
+ const decodedDone = effect.Effect.runSync(decodeDone(done));
990
1163
  return { chunks, done: decodedDone };
991
1164
  };
992
1165
  return {
@@ -997,9 +1170,7 @@ var Skill = class _Skill {
997
1170
  const layersObj = runtime?.layers ?? {};
998
1171
  const chunks = [];
999
1172
  const emit = (chunk) => {
1000
- const decoded = effect.Effect.runSync(
1001
- decodeChunk(chunk)
1002
- );
1173
+ const decoded = effect.Effect.runSync(decodeChunk(chunk));
1003
1174
  chunks.push(decoded);
1004
1175
  };
1005
1176
  const done = await defineFn({
@@ -1007,9 +1178,7 @@ var Skill = class _Skill {
1007
1178
  emit,
1008
1179
  layers: layersObj
1009
1180
  });
1010
- const decodedDone = effect.Effect.runSync(
1011
- decodeDone(done)
1012
- );
1181
+ const decodedDone = effect.Effect.runSync(decodeDone(done));
1013
1182
  for (const c of chunks) {
1014
1183
  yield c;
1015
1184
  }
@@ -1025,215 +1194,6 @@ var Skill = class _Skill {
1025
1194
  }
1026
1195
  };
1027
1196
 
1028
- // src/matrix/io/protocols/sse.ts
1029
- function formatSSE(envelope) {
1030
- const data = JSON.stringify(envelope);
1031
- return `event: ${envelope.name}
1032
- data: ${data}
1033
-
1034
- `;
1035
- }
1036
- function toSSEStream(source, signal) {
1037
- const encoder = new TextEncoder();
1038
- return new ReadableStream({
1039
- async start(controller) {
1040
- const onAbort = () => controller.close();
1041
- signal?.addEventListener("abort", onAbort, { once: true });
1042
- try {
1043
- for await (const envelope of source) {
1044
- if (signal?.aborted)
1045
- break;
1046
- controller.enqueue(encoder.encode(formatSSE(envelope)));
1047
- }
1048
- } finally {
1049
- signal?.removeEventListener("abort", onAbort);
1050
- controller.close();
1051
- }
1052
- }
1053
- });
1054
- }
1055
-
1056
- // src/matrix/io/adapters/next-endpoint.ts
1057
- var NextEndpoint = {
1058
- from(api, options) {
1059
- if (api.protocol !== "sse") {
1060
- throw new Error(`NextEndpoint: unsupported protocol "${api.protocol}"`);
1061
- }
1062
- const { requestToContextId, requestToRunId } = options;
1063
- return {
1064
- handler() {
1065
- return async (request) => {
1066
- const req = {
1067
- request,
1068
- contextId: requestToContextId(request),
1069
- runId: requestToRunId(request)
1070
- };
1071
- try {
1072
- const encoder = new TextEncoder();
1073
- const { readable, writable } = new TransformStream();
1074
- let consumerStarted;
1075
- const started = new Promise((resolve) => {
1076
- consumerStarted = resolve;
1077
- });
1078
- const streamDone = api.createStream(req, async (stream) => {
1079
- consumerStarted();
1080
- const writer = writable.getWriter();
1081
- try {
1082
- for await (const envelope of stream) {
1083
- if (request.signal?.aborted)
1084
- break;
1085
- await writer.write(encoder.encode(formatSSE(envelope)));
1086
- }
1087
- } finally {
1088
- await writer.close();
1089
- }
1090
- });
1091
- await Promise.race([started, streamDone]);
1092
- streamDone.catch(() => {
1093
- });
1094
- return new Response(readable, {
1095
- headers: {
1096
- "Content-Type": "text/event-stream",
1097
- "Cache-Control": "no-cache",
1098
- Connection: "keep-alive"
1099
- }
1100
- });
1101
- } catch (e) {
1102
- if (e instanceof ExposeAuthError) {
1103
- return new Response(e.message, { status: e.status });
1104
- }
1105
- throw e;
1106
- }
1107
- };
1108
- }
1109
- };
1110
- }
1111
- };
1112
-
1113
- // src/matrix/io/adapters/express-endpoint.ts
1114
- var ExpressEndpoint = {
1115
- from(api, options) {
1116
- if (api.protocol !== "sse") {
1117
- throw new Error(
1118
- `ExpressEndpoint: unsupported protocol "${api.protocol}"`
1119
- );
1120
- }
1121
- const { requestToContextId, requestToRunId } = options;
1122
- return {
1123
- handler() {
1124
- return async (req, res) => {
1125
- const controller = new AbortController();
1126
- req.on("close", () => controller.abort());
1127
- const exposeReq = {
1128
- request: { signal: controller.signal },
1129
- req,
1130
- res,
1131
- contextId: requestToContextId(req),
1132
- runId: requestToRunId(req)
1133
- };
1134
- try {
1135
- const encoder = new TextEncoder();
1136
- await api.createStream(exposeReq, async (stream) => {
1137
- res.setHeader("Content-Type", "text/event-stream");
1138
- res.setHeader("Cache-Control", "no-cache");
1139
- res.setHeader("Connection", "keep-alive");
1140
- res.flushHeaders?.();
1141
- try {
1142
- for await (const envelope of stream) {
1143
- if (controller.signal.aborted)
1144
- break;
1145
- res.write(encoder.encode(formatSSE(envelope)));
1146
- res.flush?.();
1147
- }
1148
- } finally {
1149
- res.end();
1150
- }
1151
- });
1152
- } catch (e) {
1153
- if (e instanceof ExposeAuthError) {
1154
- res.status(e.status).send(e.message);
1155
- return;
1156
- }
1157
- throw e;
1158
- }
1159
- };
1160
- }
1161
- };
1162
- }
1163
- };
1164
- var randomHexString = (length) => {
1165
- const chars = "abcdef0123456789";
1166
- let result = "";
1167
- for (let i = 0; i < length; i++) {
1168
- result += chars.charAt(Math.floor(Math.random() * chars.length));
1169
- }
1170
- return result;
1171
- };
1172
- var ConsoleSpan = class {
1173
- constructor(name, parent, context, links, startTime, kind, depth) {
1174
- this.name = name;
1175
- this.parent = parent;
1176
- this.context = context;
1177
- this.startTime = startTime;
1178
- this.kind = kind;
1179
- this.depth = depth;
1180
- this._tag = "Span";
1181
- this.sampled = true;
1182
- this.attributes = /* @__PURE__ */ new Map();
1183
- this.links = [];
1184
- this.traceId = parent._tag === "Some" ? parent.value.traceId : randomHexString(32);
1185
- this.spanId = randomHexString(16);
1186
- this.links = Array.from(links);
1187
- this.status = { _tag: "Started", startTime };
1188
- }
1189
- end(endTime, exit) {
1190
- if (this.status._tag === "Ended")
1191
- return;
1192
- const startTime = this.status.startTime;
1193
- const durationNs = endTime - startTime;
1194
- const durationMs = Number(durationNs) / 1e6;
1195
- const indent = " ".repeat(this.depth);
1196
- const attrs = Object.fromEntries(this.attributes);
1197
- const status = effect.Exit.isSuccess(exit) ? "ok" : "error";
1198
- console.log(
1199
- `${indent}[trace] ${this.name} ${durationMs.toFixed(2)}ms (${status})`,
1200
- Object.keys(attrs).length > 0 ? attrs : ""
1201
- );
1202
- this.status = { _tag: "Ended", startTime, endTime, exit };
1203
- }
1204
- attribute(key, value) {
1205
- this.attributes.set(key, value);
1206
- }
1207
- event(_name, _startTime, _attributes) {
1208
- }
1209
- addLinks(links) {
1210
- this.links.push(...links);
1211
- }
1212
- };
1213
- function getDepth(parent) {
1214
- if (parent._tag === "None")
1215
- return 0;
1216
- const p = parent.value;
1217
- if (p._tag === "ExternalSpan")
1218
- return 0;
1219
- return 1 + getDepth(p.parent);
1220
- }
1221
- var consoleTracer = effect.Tracer.make({
1222
- span: (name, parent, context, links, startTime, kind) => new ConsoleSpan(
1223
- name,
1224
- parent,
1225
- context,
1226
- links,
1227
- startTime,
1228
- kind,
1229
- getDepth(parent)
1230
- ),
1231
- context: (f) => f()
1232
- });
1233
- var consoleTracerLayer = effect.Layer.setTracer(
1234
- consoleTracer
1235
- );
1236
-
1237
1197
  Object.defineProperty(exports, 'S', {
1238
1198
  enumerable: true,
1239
1199
  get: function () { return effect.Schema; }