@m4trix/core 0.15.1 → 0.16.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
@@ -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))
@@ -93,56 +93,114 @@ var SocketIoFactory = class _SocketIoFactory {
93
93
  return this.prefix ? `${this.prefix}:${event}` : event;
94
94
  }
95
95
  };
96
- var KEBAB_CASE_REGEX = /^[a-z0-9]+(-[a-z0-9]+)*$/;
97
- var ChannelName = effect.Brand.refined(
98
- (s) => typeof s === "string" && KEBAB_CASE_REGEX.test(s),
99
- (s) => effect.Brand.error(`Expected kebab-case (e.g. my-channel-name), got: ${s}`)
100
- );
101
-
102
- // src/matrix/agent-network/channel.ts
103
- var Sink = {
104
- kafka(config) {
105
- return { _tag: "SinkDef", type: "kafka", config };
106
- },
107
- httpStream() {
108
- 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);
109
129
  }
110
130
  };
111
- function isHttpStreamSink(sink) {
112
- return sink.type === "http-stream";
113
- }
114
- var ConfiguredChannel = class {
115
- constructor(name) {
116
- this._tag = "ConfiguredChannel";
117
- this._events = [];
118
- this._sinks = [];
119
- 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;
120
148
  }
121
- events(events) {
122
- this._events = [...events];
123
- return this;
149
+ getConstructorState() {
150
+ return {
151
+ logic: this._logic,
152
+ paramsSchema: this._paramsSchema,
153
+ listensTo: this._listensTo,
154
+ emits: this._emits
155
+ };
124
156
  }
125
- sink(sink) {
126
- this._sinks = [...this._sinks, sink];
127
- return this;
157
+ /** Union of all event definitions this agent listens to */
158
+ getListensTo() {
159
+ return this._listensTo;
128
160
  }
129
- sinks(sinks) {
130
- this._sinks = [...sinks];
131
- return this;
161
+ /** Union of all event definitions this agent can emit */
162
+ getEmits() {
163
+ return this._emits;
132
164
  }
133
- getEvents() {
134
- return this._events;
165
+ getLogic() {
166
+ return this._logic;
135
167
  }
136
- getSinks() {
137
- return this._sinks;
168
+ static run() {
169
+ return new _AgentFactory({});
138
170
  }
139
- };
140
- var Channel = {
141
- of(name) {
142
- return {
143
- _tag: "ChannelDef",
144
- name
145
- };
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
+ );
146
204
  }
147
205
  };
148
206
 
@@ -364,6 +422,60 @@ var run = (network, plane, options) => effect.Effect.gen(function* () {
364
422
  }
365
423
  yield* effect.Effect.never;
366
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
367
479
  async function extractPayload(req) {
368
480
  const webRequest = req.request;
369
481
  if (webRequest?.method === "POST") {
@@ -541,12 +653,10 @@ var AgentNetwork = class _AgentNetwork {
541
653
  /* ─── Public Static Factory ─── */
542
654
  static setup(callback) {
543
655
  const network = new _AgentNetwork();
656
+ const mainChannel = network.addChannel("main");
657
+ network.setMainChannel(mainChannel);
544
658
  const ctx = {
545
- mainChannel: (name) => {
546
- const channel = network.addChannel(name);
547
- network.setMainChannel(channel);
548
- return channel;
549
- },
659
+ mainChannel,
550
660
  createChannel: (name) => network.addChannel(name),
551
661
  sink: Sink,
552
662
  registerAgent: (agent) => network.registerAgentInternal(agent),
@@ -559,6 +669,10 @@ var AgentNetwork = class _AgentNetwork {
559
669
  /* ─── Internal Builders ─── */
560
670
  addChannel(name) {
561
671
  const channelName = ChannelName(name);
672
+ const existing = this.channels.get(channelName);
673
+ if (existing) {
674
+ return existing;
675
+ }
562
676
  const channel = new ConfiguredChannel(channelName);
563
677
  this.channels.set(channelName, channel);
564
678
  return channel;
@@ -746,27 +860,27 @@ var EventAggregator = class _EventAggregator {
746
860
  });
747
861
  }
748
862
  };
749
- var _id, _listensTo, _emitWhen, _mapToEmit;
863
+ var _id2, _listensTo2, _emitWhen, _mapToEmit;
750
864
  var EventAggregatorInstance = class {
751
865
  constructor({
752
866
  listensTo,
753
867
  emitWhen,
754
868
  mapToEmit
755
869
  }) {
756
- __privateAdd(this, _id, void 0);
757
- __privateAdd(this, _listensTo, void 0);
870
+ __privateAdd(this, _id2, void 0);
871
+ __privateAdd(this, _listensTo2, void 0);
758
872
  __privateAdd(this, _emitWhen, void 0);
759
873
  __privateAdd(this, _mapToEmit, void 0);
760
- __privateSet(this, _id, `event-aggregator-${crypto$1.randomUUID()}`);
761
- __privateSet(this, _listensTo, listensTo);
874
+ __privateSet(this, _id2, `event-aggregator-${crypto$1.randomUUID()}`);
875
+ __privateSet(this, _listensTo2, listensTo);
762
876
  __privateSet(this, _emitWhen, emitWhen);
763
877
  __privateSet(this, _mapToEmit, mapToEmit);
764
878
  }
765
879
  getId() {
766
- return __privateGet(this, _id);
880
+ return __privateGet(this, _id2);
767
881
  }
768
882
  getListensTo() {
769
- return __privateGet(this, _listensTo);
883
+ return __privateGet(this, _listensTo2);
770
884
  }
771
885
  async invoke(options) {
772
886
  const { triggerEvent, emit, runEvents, contextEvents } = options ?? {};
@@ -797,118 +911,205 @@ var EventAggregatorInstance = class {
797
911
  });
798
912
  }
799
913
  };
800
- _id = new WeakMap();
801
- _listensTo = new WeakMap();
914
+ _id2 = new WeakMap();
915
+ _listensTo2 = new WeakMap();
802
916
  _emitWhen = new WeakMap();
803
917
  _mapToEmit = new WeakMap();
804
- var _params, _logic, _id2, _listensTo2;
805
- var Agent = class {
806
- constructor(logic, params, listensTo) {
807
- __privateAdd(this, _params, void 0);
808
- __privateAdd(this, _logic, void 0);
809
- __privateAdd(this, _id2, void 0);
810
- __privateAdd(this, _listensTo2, void 0);
811
- __privateSet(this, _logic, logic);
812
- __privateSet(this, _params, params);
813
- __privateSet(this, _id2, `agent-${crypto$1.randomUUID()}`);
814
- __privateSet(this, _listensTo2, listensTo ?? []);
815
- }
816
- getListensTo() {
817
- return __privateGet(this, _listensTo2);
818
- }
819
- async invoke(options) {
820
- const { triggerEvent, emit, runEvents, contextEvents } = options ?? {};
821
- const emitFn = emit ?? ((_event) => {
822
- });
823
- await __privateGet(this, _logic).call(this, {
824
- params: __privateGet(this, _params),
825
- triggerEvent: triggerEvent ?? void 0,
826
- emit: emitFn,
827
- runEvents: runEvents ?? [],
828
- contextEvents: contextEvents ?? {
829
- all: [],
830
- byRun: () => [],
831
- map: /* @__PURE__ */ new Map()
832
- }
833
- });
834
- }
835
- getId() {
836
- return __privateGet(this, _id2);
918
+ var randomHexString = (length) => {
919
+ const chars = "abcdef0123456789";
920
+ let result = "";
921
+ for (let i = 0; i < length; i++) {
922
+ result += chars.charAt(Math.floor(Math.random() * chars.length));
837
923
  }
924
+ return result;
838
925
  };
839
- _params = new WeakMap();
840
- _logic = new WeakMap();
841
- _id2 = new WeakMap();
842
- _listensTo2 = new WeakMap();
843
-
844
- // src/matrix/agent-factory.ts
845
- var AgentFactory = class _AgentFactory {
846
- constructor({
847
- logic,
848
- paramsSchema,
849
- listensTo = [],
850
- emits = []
851
- }) {
852
- this._logic = logic;
853
- this._paramsSchema = paramsSchema;
854
- this._listensTo = listensTo;
855
- this._emits = emits;
856
- }
857
- getConstructorState() {
858
- return {
859
- logic: this._logic,
860
- paramsSchema: this._paramsSchema,
861
- listensTo: this._listensTo,
862
- emits: this._emits
863
- };
864
- }
865
- /** Union of all event definitions this agent listens to */
866
- getListensTo() {
867
- return this._listensTo;
868
- }
869
- /** Union of all event definitions this agent can emit */
870
- getEmits() {
871
- return this._emits;
872
- }
873
- getLogic() {
874
- return this._logic;
926
+ var ConsoleSpan = class {
927
+ constructor(name, parent, context, links, startTime, kind, depth) {
928
+ this.name = name;
929
+ this.parent = parent;
930
+ this.context = context;
931
+ this.startTime = startTime;
932
+ this.kind = kind;
933
+ this.depth = depth;
934
+ this._tag = "Span";
935
+ this.sampled = true;
936
+ this.attributes = /* @__PURE__ */ new Map();
937
+ this.links = [];
938
+ this.traceId = parent._tag === "Some" ? parent.value.traceId : randomHexString(32);
939
+ this.spanId = randomHexString(16);
940
+ this.links = Array.from(links);
941
+ this.status = { _tag: "Started", startTime };
875
942
  }
876
- static run() {
877
- return new _AgentFactory({});
943
+ end(endTime, exit) {
944
+ if (this.status._tag === "Ended")
945
+ return;
946
+ const startTime = this.status.startTime;
947
+ const durationNs = endTime - startTime;
948
+ const durationMs = Number(durationNs) / 1e6;
949
+ const indent = " ".repeat(this.depth);
950
+ const attrs = Object.fromEntries(this.attributes);
951
+ const status = effect.Exit.isSuccess(exit) ? "ok" : "error";
952
+ console.log(
953
+ `${indent}[trace] ${this.name} ${durationMs.toFixed(2)}ms (${status})`,
954
+ Object.keys(attrs).length > 0 ? attrs : ""
955
+ );
956
+ this.status = { _tag: "Ended", startTime, endTime, exit };
878
957
  }
879
- params(params) {
880
- const { logic, ...rest } = this.getConstructorState();
881
- return new _AgentFactory({
882
- ...rest,
883
- logic,
884
- paramsSchema: params
885
- });
958
+ attribute(key, value) {
959
+ this.attributes.set(key, value);
886
960
  }
887
- listensTo(events) {
888
- return new _AgentFactory({
889
- ...this.getConstructorState(),
890
- listensTo: [...this._listensTo, ...events]
891
- });
961
+ event(_name, _startTime, _attributes) {
892
962
  }
893
- emits(events) {
894
- return new _AgentFactory({
895
- ...this.getConstructorState(),
896
- emits: [...this._emits, ...events]
897
- });
963
+ addLinks(links) {
964
+ this.links.push(...links);
898
965
  }
899
- logic(fn) {
900
- return new _AgentFactory({
901
- ...this.getConstructorState(),
902
- logic: fn
903
- });
966
+ };
967
+ function getDepth(parent) {
968
+ if (parent._tag === "None")
969
+ return 0;
970
+ const p = parent.value;
971
+ if (p._tag === "ExternalSpan")
972
+ return 0;
973
+ return 1 + getDepth(p.parent);
974
+ }
975
+ var consoleTracer = effect.Tracer.make({
976
+ span: (name, parent, context, links, startTime, kind) => new ConsoleSpan(name, parent, context, links, startTime, kind, getDepth(parent)),
977
+ context: (f) => f()
978
+ });
979
+ var consoleTracerLayer = effect.Layer.setTracer(consoleTracer);
980
+
981
+ // src/matrix/io/protocols/sse.ts
982
+ function formatSSE(envelope) {
983
+ const data = JSON.stringify(envelope);
984
+ return `event: ${envelope.name}
985
+ data: ${data}
986
+
987
+ `;
988
+ }
989
+ function toSSEStream(source, signal) {
990
+ const encoder = new TextEncoder();
991
+ return new ReadableStream({
992
+ async start(controller) {
993
+ const onAbort = () => controller.close();
994
+ signal?.addEventListener("abort", onAbort, { once: true });
995
+ try {
996
+ for await (const envelope of source) {
997
+ if (signal?.aborted)
998
+ break;
999
+ controller.enqueue(encoder.encode(formatSSE(envelope)));
1000
+ }
1001
+ } finally {
1002
+ signal?.removeEventListener("abort", onAbort);
1003
+ controller.close();
1004
+ }
1005
+ }
1006
+ });
1007
+ }
1008
+
1009
+ // src/matrix/io/adapters/next-endpoint.ts
1010
+ var NextEndpoint = {
1011
+ from(api, options) {
1012
+ if (api.protocol !== "sse") {
1013
+ throw new Error(`NextEndpoint: unsupported protocol "${api.protocol}"`);
1014
+ }
1015
+ const { requestToContextId, requestToRunId } = options;
1016
+ return {
1017
+ handler() {
1018
+ return async (request) => {
1019
+ const req = {
1020
+ request,
1021
+ contextId: requestToContextId(request),
1022
+ runId: requestToRunId(request)
1023
+ };
1024
+ try {
1025
+ const encoder = new TextEncoder();
1026
+ const { readable, writable } = new TransformStream();
1027
+ let consumerStarted;
1028
+ const started = new Promise((resolve) => {
1029
+ consumerStarted = resolve;
1030
+ });
1031
+ const streamDone = api.createStream(req, async (stream) => {
1032
+ consumerStarted();
1033
+ const writer = writable.getWriter();
1034
+ try {
1035
+ for await (const envelope of stream) {
1036
+ if (request.signal?.aborted)
1037
+ break;
1038
+ await writer.write(encoder.encode(formatSSE(envelope)));
1039
+ }
1040
+ } finally {
1041
+ await writer.close();
1042
+ }
1043
+ });
1044
+ await Promise.race([started, streamDone]);
1045
+ streamDone.catch(() => {
1046
+ });
1047
+ return new Response(readable, {
1048
+ headers: {
1049
+ "Content-Type": "text/event-stream",
1050
+ "Cache-Control": "no-cache",
1051
+ Connection: "keep-alive"
1052
+ }
1053
+ });
1054
+ } catch (e) {
1055
+ if (e instanceof ExposeAuthError) {
1056
+ return new Response(e.message, { status: e.status });
1057
+ }
1058
+ throw e;
1059
+ }
1060
+ };
1061
+ }
1062
+ };
904
1063
  }
905
- produce(params) {
906
- const listensTo = this._listensTo.map((e) => e.name);
907
- return new Agent(
908
- this._logic,
909
- params,
910
- listensTo
911
- );
1064
+ };
1065
+
1066
+ // src/matrix/io/adapters/express-endpoint.ts
1067
+ var ExpressEndpoint = {
1068
+ from(api, options) {
1069
+ if (api.protocol !== "sse") {
1070
+ throw new Error(`ExpressEndpoint: unsupported protocol "${api.protocol}"`);
1071
+ }
1072
+ const { requestToContextId, requestToRunId } = options;
1073
+ return {
1074
+ handler() {
1075
+ return async (req, res) => {
1076
+ const controller = new AbortController();
1077
+ req.on("close", () => controller.abort());
1078
+ const exposeReq = {
1079
+ request: { signal: controller.signal },
1080
+ req,
1081
+ res,
1082
+ contextId: requestToContextId(req),
1083
+ runId: requestToRunId(req)
1084
+ };
1085
+ try {
1086
+ const encoder = new TextEncoder();
1087
+ await api.createStream(exposeReq, async (stream) => {
1088
+ res.setHeader("Content-Type", "text/event-stream");
1089
+ res.setHeader("Cache-Control", "no-cache");
1090
+ res.setHeader("Connection", "keep-alive");
1091
+ res.flushHeaders?.();
1092
+ try {
1093
+ for await (const envelope of stream) {
1094
+ if (controller.signal.aborted)
1095
+ break;
1096
+ res.write(encoder.encode(formatSSE(envelope)));
1097
+ res.flush?.();
1098
+ }
1099
+ } finally {
1100
+ res.end();
1101
+ }
1102
+ });
1103
+ } catch (e) {
1104
+ if (e instanceof ExposeAuthError) {
1105
+ res.status(e.status).send(e.message);
1106
+ return;
1107
+ }
1108
+ throw e;
1109
+ }
1110
+ };
1111
+ }
1112
+ };
912
1113
  }
913
1114
  };
914
1115
  var CAMEL_CASE_REGEX = /^[a-z][a-zA-Z0-9]*$/;
@@ -1067,203 +1268,6 @@ var Skill = class _Skill {
1067
1268
  }
1068
1269
  };
1069
1270
 
1070
- // src/matrix/io/protocols/sse.ts
1071
- function formatSSE(envelope) {
1072
- const data = JSON.stringify(envelope);
1073
- return `event: ${envelope.name}
1074
- data: ${data}
1075
-
1076
- `;
1077
- }
1078
- function toSSEStream(source, signal) {
1079
- const encoder = new TextEncoder();
1080
- return new ReadableStream({
1081
- async start(controller) {
1082
- const onAbort = () => controller.close();
1083
- signal?.addEventListener("abort", onAbort, { once: true });
1084
- try {
1085
- for await (const envelope of source) {
1086
- if (signal?.aborted)
1087
- break;
1088
- controller.enqueue(encoder.encode(formatSSE(envelope)));
1089
- }
1090
- } finally {
1091
- signal?.removeEventListener("abort", onAbort);
1092
- controller.close();
1093
- }
1094
- }
1095
- });
1096
- }
1097
-
1098
- // src/matrix/io/adapters/next-endpoint.ts
1099
- var NextEndpoint = {
1100
- from(api, options) {
1101
- if (api.protocol !== "sse") {
1102
- throw new Error(`NextEndpoint: unsupported protocol "${api.protocol}"`);
1103
- }
1104
- const { requestToContextId, requestToRunId } = options;
1105
- return {
1106
- handler() {
1107
- return async (request) => {
1108
- const req = {
1109
- request,
1110
- contextId: requestToContextId(request),
1111
- runId: requestToRunId(request)
1112
- };
1113
- try {
1114
- const encoder = new TextEncoder();
1115
- const { readable, writable } = new TransformStream();
1116
- let consumerStarted;
1117
- const started = new Promise((resolve) => {
1118
- consumerStarted = resolve;
1119
- });
1120
- const streamDone = api.createStream(req, async (stream) => {
1121
- consumerStarted();
1122
- const writer = writable.getWriter();
1123
- try {
1124
- for await (const envelope of stream) {
1125
- if (request.signal?.aborted)
1126
- break;
1127
- await writer.write(encoder.encode(formatSSE(envelope)));
1128
- }
1129
- } finally {
1130
- await writer.close();
1131
- }
1132
- });
1133
- await Promise.race([started, streamDone]);
1134
- streamDone.catch(() => {
1135
- });
1136
- return new Response(readable, {
1137
- headers: {
1138
- "Content-Type": "text/event-stream",
1139
- "Cache-Control": "no-cache",
1140
- Connection: "keep-alive"
1141
- }
1142
- });
1143
- } catch (e) {
1144
- if (e instanceof ExposeAuthError) {
1145
- return new Response(e.message, { status: e.status });
1146
- }
1147
- throw e;
1148
- }
1149
- };
1150
- }
1151
- };
1152
- }
1153
- };
1154
-
1155
- // src/matrix/io/adapters/express-endpoint.ts
1156
- var ExpressEndpoint = {
1157
- from(api, options) {
1158
- if (api.protocol !== "sse") {
1159
- throw new Error(`ExpressEndpoint: unsupported protocol "${api.protocol}"`);
1160
- }
1161
- const { requestToContextId, requestToRunId } = options;
1162
- return {
1163
- handler() {
1164
- return async (req, res) => {
1165
- const controller = new AbortController();
1166
- req.on("close", () => controller.abort());
1167
- const exposeReq = {
1168
- request: { signal: controller.signal },
1169
- req,
1170
- res,
1171
- contextId: requestToContextId(req),
1172
- runId: requestToRunId(req)
1173
- };
1174
- try {
1175
- const encoder = new TextEncoder();
1176
- await api.createStream(exposeReq, async (stream) => {
1177
- res.setHeader("Content-Type", "text/event-stream");
1178
- res.setHeader("Cache-Control", "no-cache");
1179
- res.setHeader("Connection", "keep-alive");
1180
- res.flushHeaders?.();
1181
- try {
1182
- for await (const envelope of stream) {
1183
- if (controller.signal.aborted)
1184
- break;
1185
- res.write(encoder.encode(formatSSE(envelope)));
1186
- res.flush?.();
1187
- }
1188
- } finally {
1189
- res.end();
1190
- }
1191
- });
1192
- } catch (e) {
1193
- if (e instanceof ExposeAuthError) {
1194
- res.status(e.status).send(e.message);
1195
- return;
1196
- }
1197
- throw e;
1198
- }
1199
- };
1200
- }
1201
- };
1202
- }
1203
- };
1204
- var randomHexString = (length) => {
1205
- const chars = "abcdef0123456789";
1206
- let result = "";
1207
- for (let i = 0; i < length; i++) {
1208
- result += chars.charAt(Math.floor(Math.random() * chars.length));
1209
- }
1210
- return result;
1211
- };
1212
- var ConsoleSpan = class {
1213
- constructor(name, parent, context, links, startTime, kind, depth) {
1214
- this.name = name;
1215
- this.parent = parent;
1216
- this.context = context;
1217
- this.startTime = startTime;
1218
- this.kind = kind;
1219
- this.depth = depth;
1220
- this._tag = "Span";
1221
- this.sampled = true;
1222
- this.attributes = /* @__PURE__ */ new Map();
1223
- this.links = [];
1224
- this.traceId = parent._tag === "Some" ? parent.value.traceId : randomHexString(32);
1225
- this.spanId = randomHexString(16);
1226
- this.links = Array.from(links);
1227
- this.status = { _tag: "Started", startTime };
1228
- }
1229
- end(endTime, exit) {
1230
- if (this.status._tag === "Ended")
1231
- return;
1232
- const startTime = this.status.startTime;
1233
- const durationNs = endTime - startTime;
1234
- const durationMs = Number(durationNs) / 1e6;
1235
- const indent = " ".repeat(this.depth);
1236
- const attrs = Object.fromEntries(this.attributes);
1237
- const status = effect.Exit.isSuccess(exit) ? "ok" : "error";
1238
- console.log(
1239
- `${indent}[trace] ${this.name} ${durationMs.toFixed(2)}ms (${status})`,
1240
- Object.keys(attrs).length > 0 ? attrs : ""
1241
- );
1242
- this.status = { _tag: "Ended", startTime, endTime, exit };
1243
- }
1244
- attribute(key, value) {
1245
- this.attributes.set(key, value);
1246
- }
1247
- event(_name, _startTime, _attributes) {
1248
- }
1249
- addLinks(links) {
1250
- this.links.push(...links);
1251
- }
1252
- };
1253
- function getDepth(parent) {
1254
- if (parent._tag === "None")
1255
- return 0;
1256
- const p = parent.value;
1257
- if (p._tag === "ExternalSpan")
1258
- return 0;
1259
- return 1 + getDepth(p.parent);
1260
- }
1261
- var consoleTracer = effect.Tracer.make({
1262
- span: (name, parent, context, links, startTime, kind) => new ConsoleSpan(name, parent, context, links, startTime, kind, getDepth(parent)),
1263
- context: (f) => f()
1264
- });
1265
- var consoleTracerLayer = effect.Layer.setTracer(consoleTracer);
1266
-
1267
1271
  Object.defineProperty(exports, 'S', {
1268
1272
  enumerable: true,
1269
1273
  get: function () { return effect.Schema; }