@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.
@@ -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
 
@@ -292,6 +350,60 @@ var run = (network, plane, options) => effect.Effect.gen(function* () {
292
350
  }
293
351
  yield* effect.Effect.never;
294
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
295
407
  async function extractPayload(req) {
296
408
  const webRequest = req.request;
297
409
  if (webRequest?.method === "POST") {
@@ -469,12 +581,10 @@ var AgentNetwork = class _AgentNetwork {
469
581
  /* ─── Public Static Factory ─── */
470
582
  static setup(callback) {
471
583
  const network = new _AgentNetwork();
584
+ const mainChannel = network.addChannel("main");
585
+ network.setMainChannel(mainChannel);
472
586
  const ctx = {
473
- mainChannel: (name) => {
474
- const channel = network.addChannel(name);
475
- network.setMainChannel(channel);
476
- return channel;
477
- },
587
+ mainChannel,
478
588
  createChannel: (name) => network.addChannel(name),
479
589
  sink: Sink,
480
590
  registerAgent: (agent) => network.registerAgentInternal(agent),
@@ -487,6 +597,10 @@ var AgentNetwork = class _AgentNetwork {
487
597
  /* ─── Internal Builders ─── */
488
598
  addChannel(name) {
489
599
  const channelName = ChannelName(name);
600
+ const existing = this.channels.get(channelName);
601
+ if (existing) {
602
+ return existing;
603
+ }
490
604
  const channel = new ConfiguredChannel(channelName);
491
605
  this.channels.set(channelName, channel);
492
606
  return channel;
@@ -674,27 +788,27 @@ var EventAggregator = class _EventAggregator {
674
788
  });
675
789
  }
676
790
  };
677
- var _id, _listensTo, _emitWhen, _mapToEmit;
791
+ var _id2, _listensTo2, _emitWhen, _mapToEmit;
678
792
  var EventAggregatorInstance = class {
679
793
  constructor({
680
794
  listensTo,
681
795
  emitWhen,
682
796
  mapToEmit
683
797
  }) {
684
- __privateAdd(this, _id, void 0);
685
- __privateAdd(this, _listensTo, void 0);
798
+ __privateAdd(this, _id2, void 0);
799
+ __privateAdd(this, _listensTo2, void 0);
686
800
  __privateAdd(this, _emitWhen, void 0);
687
801
  __privateAdd(this, _mapToEmit, void 0);
688
- __privateSet(this, _id, `event-aggregator-${crypto$1.randomUUID()}`);
689
- __privateSet(this, _listensTo, listensTo);
802
+ __privateSet(this, _id2, `event-aggregator-${crypto$1.randomUUID()}`);
803
+ __privateSet(this, _listensTo2, listensTo);
690
804
  __privateSet(this, _emitWhen, emitWhen);
691
805
  __privateSet(this, _mapToEmit, mapToEmit);
692
806
  }
693
807
  getId() {
694
- return __privateGet(this, _id);
808
+ return __privateGet(this, _id2);
695
809
  }
696
810
  getListensTo() {
697
- return __privateGet(this, _listensTo);
811
+ return __privateGet(this, _listensTo2);
698
812
  }
699
813
  async invoke(options) {
700
814
  const { triggerEvent, emit, runEvents, contextEvents } = options ?? {};
@@ -725,118 +839,205 @@ var EventAggregatorInstance = class {
725
839
  });
726
840
  }
727
841
  };
728
- _id = new WeakMap();
729
- _listensTo = new WeakMap();
842
+ _id2 = new WeakMap();
843
+ _listensTo2 = new WeakMap();
730
844
  _emitWhen = new WeakMap();
731
845
  _mapToEmit = new WeakMap();
732
- var _params, _logic, _id2, _listensTo2;
733
- var Agent = class {
734
- constructor(logic, params, listensTo) {
735
- __privateAdd(this, _params, void 0);
736
- __privateAdd(this, _logic, void 0);
737
- __privateAdd(this, _id2, void 0);
738
- __privateAdd(this, _listensTo2, void 0);
739
- __privateSet(this, _logic, logic);
740
- __privateSet(this, _params, params);
741
- __privateSet(this, _id2, `agent-${crypto$1.randomUUID()}`);
742
- __privateSet(this, _listensTo2, listensTo ?? []);
743
- }
744
- getListensTo() {
745
- return __privateGet(this, _listensTo2);
746
- }
747
- async invoke(options) {
748
- const { triggerEvent, emit, runEvents, contextEvents } = options ?? {};
749
- const emitFn = emit ?? ((_event) => {
750
- });
751
- await __privateGet(this, _logic).call(this, {
752
- params: __privateGet(this, _params),
753
- triggerEvent: triggerEvent ?? void 0,
754
- emit: emitFn,
755
- runEvents: runEvents ?? [],
756
- contextEvents: contextEvents ?? {
757
- all: [],
758
- byRun: () => [],
759
- map: /* @__PURE__ */ new Map()
760
- }
761
- });
762
- }
763
- getId() {
764
- return __privateGet(this, _id2);
846
+ var randomHexString = (length) => {
847
+ const chars = "abcdef0123456789";
848
+ let result = "";
849
+ for (let i = 0; i < length; i++) {
850
+ result += chars.charAt(Math.floor(Math.random() * chars.length));
765
851
  }
852
+ return result;
766
853
  };
767
- _params = new WeakMap();
768
- _logic = new WeakMap();
769
- _id2 = new WeakMap();
770
- _listensTo2 = new WeakMap();
771
-
772
- // src/matrix/agent-factory.ts
773
- var AgentFactory = class _AgentFactory {
774
- constructor({
775
- logic,
776
- paramsSchema,
777
- listensTo = [],
778
- emits = []
779
- }) {
780
- this._logic = logic;
781
- this._paramsSchema = paramsSchema;
782
- this._listensTo = listensTo;
783
- this._emits = emits;
784
- }
785
- getConstructorState() {
786
- return {
787
- logic: this._logic,
788
- paramsSchema: this._paramsSchema,
789
- listensTo: this._listensTo,
790
- emits: this._emits
791
- };
792
- }
793
- /** Union of all event definitions this agent listens to */
794
- getListensTo() {
795
- return this._listensTo;
796
- }
797
- /** Union of all event definitions this agent can emit */
798
- getEmits() {
799
- return this._emits;
800
- }
801
- getLogic() {
802
- return this._logic;
854
+ var ConsoleSpan = class {
855
+ constructor(name, parent, context, links, startTime, kind, depth) {
856
+ this.name = name;
857
+ this.parent = parent;
858
+ this.context = context;
859
+ this.startTime = startTime;
860
+ this.kind = kind;
861
+ this.depth = depth;
862
+ this._tag = "Span";
863
+ this.sampled = true;
864
+ this.attributes = /* @__PURE__ */ new Map();
865
+ this.links = [];
866
+ this.traceId = parent._tag === "Some" ? parent.value.traceId : randomHexString(32);
867
+ this.spanId = randomHexString(16);
868
+ this.links = Array.from(links);
869
+ this.status = { _tag: "Started", startTime };
803
870
  }
804
- static run() {
805
- return new _AgentFactory({});
871
+ end(endTime, exit) {
872
+ if (this.status._tag === "Ended")
873
+ return;
874
+ const startTime = this.status.startTime;
875
+ const durationNs = endTime - startTime;
876
+ const durationMs = Number(durationNs) / 1e6;
877
+ const indent = " ".repeat(this.depth);
878
+ const attrs = Object.fromEntries(this.attributes);
879
+ const status = effect.Exit.isSuccess(exit) ? "ok" : "error";
880
+ console.log(
881
+ `${indent}[trace] ${this.name} ${durationMs.toFixed(2)}ms (${status})`,
882
+ Object.keys(attrs).length > 0 ? attrs : ""
883
+ );
884
+ this.status = { _tag: "Ended", startTime, endTime, exit };
806
885
  }
807
- params(params) {
808
- const { logic, ...rest } = this.getConstructorState();
809
- return new _AgentFactory({
810
- ...rest,
811
- logic,
812
- paramsSchema: params
813
- });
886
+ attribute(key, value) {
887
+ this.attributes.set(key, value);
814
888
  }
815
- listensTo(events) {
816
- return new _AgentFactory({
817
- ...this.getConstructorState(),
818
- listensTo: [...this._listensTo, ...events]
819
- });
889
+ event(_name, _startTime, _attributes) {
820
890
  }
821
- emits(events) {
822
- return new _AgentFactory({
823
- ...this.getConstructorState(),
824
- emits: [...this._emits, ...events]
825
- });
891
+ addLinks(links) {
892
+ this.links.push(...links);
826
893
  }
827
- logic(fn) {
828
- return new _AgentFactory({
829
- ...this.getConstructorState(),
830
- logic: fn
831
- });
894
+ };
895
+ function getDepth(parent) {
896
+ if (parent._tag === "None")
897
+ return 0;
898
+ const p = parent.value;
899
+ if (p._tag === "ExternalSpan")
900
+ return 0;
901
+ return 1 + getDepth(p.parent);
902
+ }
903
+ var consoleTracer = effect.Tracer.make({
904
+ span: (name, parent, context, links, startTime, kind) => new ConsoleSpan(name, parent, context, links, startTime, kind, getDepth(parent)),
905
+ context: (f) => f()
906
+ });
907
+ var consoleTracerLayer = effect.Layer.setTracer(consoleTracer);
908
+
909
+ // src/matrix/io/protocols/sse.ts
910
+ function formatSSE(envelope) {
911
+ const data = JSON.stringify(envelope);
912
+ return `event: ${envelope.name}
913
+ data: ${data}
914
+
915
+ `;
916
+ }
917
+ function toSSEStream(source, signal) {
918
+ const encoder = new TextEncoder();
919
+ return new ReadableStream({
920
+ async start(controller) {
921
+ const onAbort = () => controller.close();
922
+ signal?.addEventListener("abort", onAbort, { once: true });
923
+ try {
924
+ for await (const envelope of source) {
925
+ if (signal?.aborted)
926
+ break;
927
+ controller.enqueue(encoder.encode(formatSSE(envelope)));
928
+ }
929
+ } finally {
930
+ signal?.removeEventListener("abort", onAbort);
931
+ controller.close();
932
+ }
933
+ }
934
+ });
935
+ }
936
+
937
+ // src/matrix/io/adapters/next-endpoint.ts
938
+ var NextEndpoint = {
939
+ from(api, options) {
940
+ if (api.protocol !== "sse") {
941
+ throw new Error(`NextEndpoint: unsupported protocol "${api.protocol}"`);
942
+ }
943
+ const { requestToContextId, requestToRunId } = options;
944
+ return {
945
+ handler() {
946
+ return async (request) => {
947
+ const req = {
948
+ request,
949
+ contextId: requestToContextId(request),
950
+ runId: requestToRunId(request)
951
+ };
952
+ try {
953
+ const encoder = new TextEncoder();
954
+ const { readable, writable } = new TransformStream();
955
+ let consumerStarted;
956
+ const started = new Promise((resolve) => {
957
+ consumerStarted = resolve;
958
+ });
959
+ const streamDone = api.createStream(req, async (stream) => {
960
+ consumerStarted();
961
+ const writer = writable.getWriter();
962
+ try {
963
+ for await (const envelope of stream) {
964
+ if (request.signal?.aborted)
965
+ break;
966
+ await writer.write(encoder.encode(formatSSE(envelope)));
967
+ }
968
+ } finally {
969
+ await writer.close();
970
+ }
971
+ });
972
+ await Promise.race([started, streamDone]);
973
+ streamDone.catch(() => {
974
+ });
975
+ return new Response(readable, {
976
+ headers: {
977
+ "Content-Type": "text/event-stream",
978
+ "Cache-Control": "no-cache",
979
+ Connection: "keep-alive"
980
+ }
981
+ });
982
+ } catch (e) {
983
+ if (e instanceof ExposeAuthError) {
984
+ return new Response(e.message, { status: e.status });
985
+ }
986
+ throw e;
987
+ }
988
+ };
989
+ }
990
+ };
832
991
  }
833
- produce(params) {
834
- const listensTo = this._listensTo.map((e) => e.name);
835
- return new Agent(
836
- this._logic,
837
- params,
838
- listensTo
839
- );
992
+ };
993
+
994
+ // src/matrix/io/adapters/express-endpoint.ts
995
+ var ExpressEndpoint = {
996
+ from(api, options) {
997
+ if (api.protocol !== "sse") {
998
+ throw new Error(`ExpressEndpoint: unsupported protocol "${api.protocol}"`);
999
+ }
1000
+ const { requestToContextId, requestToRunId } = options;
1001
+ return {
1002
+ handler() {
1003
+ return async (req, res) => {
1004
+ const controller = new AbortController();
1005
+ req.on("close", () => controller.abort());
1006
+ const exposeReq = {
1007
+ request: { signal: controller.signal },
1008
+ req,
1009
+ res,
1010
+ contextId: requestToContextId(req),
1011
+ runId: requestToRunId(req)
1012
+ };
1013
+ try {
1014
+ const encoder = new TextEncoder();
1015
+ await api.createStream(exposeReq, async (stream) => {
1016
+ res.setHeader("Content-Type", "text/event-stream");
1017
+ res.setHeader("Cache-Control", "no-cache");
1018
+ res.setHeader("Connection", "keep-alive");
1019
+ res.flushHeaders?.();
1020
+ try {
1021
+ for await (const envelope of stream) {
1022
+ if (controller.signal.aborted)
1023
+ break;
1024
+ res.write(encoder.encode(formatSSE(envelope)));
1025
+ res.flush?.();
1026
+ }
1027
+ } finally {
1028
+ res.end();
1029
+ }
1030
+ });
1031
+ } catch (e) {
1032
+ if (e instanceof ExposeAuthError) {
1033
+ res.status(e.status).send(e.message);
1034
+ return;
1035
+ }
1036
+ throw e;
1037
+ }
1038
+ };
1039
+ }
1040
+ };
840
1041
  }
841
1042
  };
842
1043
  var CAMEL_CASE_REGEX = /^[a-z][a-zA-Z0-9]*$/;
@@ -995,203 +1196,6 @@ var Skill = class _Skill {
995
1196
  }
996
1197
  };
997
1198
 
998
- // src/matrix/io/protocols/sse.ts
999
- function formatSSE(envelope) {
1000
- const data = JSON.stringify(envelope);
1001
- return `event: ${envelope.name}
1002
- data: ${data}
1003
-
1004
- `;
1005
- }
1006
- function toSSEStream(source, signal) {
1007
- const encoder = new TextEncoder();
1008
- return new ReadableStream({
1009
- async start(controller) {
1010
- const onAbort = () => controller.close();
1011
- signal?.addEventListener("abort", onAbort, { once: true });
1012
- try {
1013
- for await (const envelope of source) {
1014
- if (signal?.aborted)
1015
- break;
1016
- controller.enqueue(encoder.encode(formatSSE(envelope)));
1017
- }
1018
- } finally {
1019
- signal?.removeEventListener("abort", onAbort);
1020
- controller.close();
1021
- }
1022
- }
1023
- });
1024
- }
1025
-
1026
- // src/matrix/io/adapters/next-endpoint.ts
1027
- var NextEndpoint = {
1028
- from(api, options) {
1029
- if (api.protocol !== "sse") {
1030
- throw new Error(`NextEndpoint: unsupported protocol "${api.protocol}"`);
1031
- }
1032
- const { requestToContextId, requestToRunId } = options;
1033
- return {
1034
- handler() {
1035
- return async (request) => {
1036
- const req = {
1037
- request,
1038
- contextId: requestToContextId(request),
1039
- runId: requestToRunId(request)
1040
- };
1041
- try {
1042
- const encoder = new TextEncoder();
1043
- const { readable, writable } = new TransformStream();
1044
- let consumerStarted;
1045
- const started = new Promise((resolve) => {
1046
- consumerStarted = resolve;
1047
- });
1048
- const streamDone = api.createStream(req, async (stream) => {
1049
- consumerStarted();
1050
- const writer = writable.getWriter();
1051
- try {
1052
- for await (const envelope of stream) {
1053
- if (request.signal?.aborted)
1054
- break;
1055
- await writer.write(encoder.encode(formatSSE(envelope)));
1056
- }
1057
- } finally {
1058
- await writer.close();
1059
- }
1060
- });
1061
- await Promise.race([started, streamDone]);
1062
- streamDone.catch(() => {
1063
- });
1064
- return new Response(readable, {
1065
- headers: {
1066
- "Content-Type": "text/event-stream",
1067
- "Cache-Control": "no-cache",
1068
- Connection: "keep-alive"
1069
- }
1070
- });
1071
- } catch (e) {
1072
- if (e instanceof ExposeAuthError) {
1073
- return new Response(e.message, { status: e.status });
1074
- }
1075
- throw e;
1076
- }
1077
- };
1078
- }
1079
- };
1080
- }
1081
- };
1082
-
1083
- // src/matrix/io/adapters/express-endpoint.ts
1084
- var ExpressEndpoint = {
1085
- from(api, options) {
1086
- if (api.protocol !== "sse") {
1087
- throw new Error(`ExpressEndpoint: unsupported protocol "${api.protocol}"`);
1088
- }
1089
- const { requestToContextId, requestToRunId } = options;
1090
- return {
1091
- handler() {
1092
- return async (req, res) => {
1093
- const controller = new AbortController();
1094
- req.on("close", () => controller.abort());
1095
- const exposeReq = {
1096
- request: { signal: controller.signal },
1097
- req,
1098
- res,
1099
- contextId: requestToContextId(req),
1100
- runId: requestToRunId(req)
1101
- };
1102
- try {
1103
- const encoder = new TextEncoder();
1104
- await api.createStream(exposeReq, async (stream) => {
1105
- res.setHeader("Content-Type", "text/event-stream");
1106
- res.setHeader("Cache-Control", "no-cache");
1107
- res.setHeader("Connection", "keep-alive");
1108
- res.flushHeaders?.();
1109
- try {
1110
- for await (const envelope of stream) {
1111
- if (controller.signal.aborted)
1112
- break;
1113
- res.write(encoder.encode(formatSSE(envelope)));
1114
- res.flush?.();
1115
- }
1116
- } finally {
1117
- res.end();
1118
- }
1119
- });
1120
- } catch (e) {
1121
- if (e instanceof ExposeAuthError) {
1122
- res.status(e.status).send(e.message);
1123
- return;
1124
- }
1125
- throw e;
1126
- }
1127
- };
1128
- }
1129
- };
1130
- }
1131
- };
1132
- var randomHexString = (length) => {
1133
- const chars = "abcdef0123456789";
1134
- let result = "";
1135
- for (let i = 0; i < length; i++) {
1136
- result += chars.charAt(Math.floor(Math.random() * chars.length));
1137
- }
1138
- return result;
1139
- };
1140
- var ConsoleSpan = class {
1141
- constructor(name, parent, context, links, startTime, kind, depth) {
1142
- this.name = name;
1143
- this.parent = parent;
1144
- this.context = context;
1145
- this.startTime = startTime;
1146
- this.kind = kind;
1147
- this.depth = depth;
1148
- this._tag = "Span";
1149
- this.sampled = true;
1150
- this.attributes = /* @__PURE__ */ new Map();
1151
- this.links = [];
1152
- this.traceId = parent._tag === "Some" ? parent.value.traceId : randomHexString(32);
1153
- this.spanId = randomHexString(16);
1154
- this.links = Array.from(links);
1155
- this.status = { _tag: "Started", startTime };
1156
- }
1157
- end(endTime, exit) {
1158
- if (this.status._tag === "Ended")
1159
- return;
1160
- const startTime = this.status.startTime;
1161
- const durationNs = endTime - startTime;
1162
- const durationMs = Number(durationNs) / 1e6;
1163
- const indent = " ".repeat(this.depth);
1164
- const attrs = Object.fromEntries(this.attributes);
1165
- const status = effect.Exit.isSuccess(exit) ? "ok" : "error";
1166
- console.log(
1167
- `${indent}[trace] ${this.name} ${durationMs.toFixed(2)}ms (${status})`,
1168
- Object.keys(attrs).length > 0 ? attrs : ""
1169
- );
1170
- this.status = { _tag: "Ended", startTime, endTime, exit };
1171
- }
1172
- attribute(key, value) {
1173
- this.attributes.set(key, value);
1174
- }
1175
- event(_name, _startTime, _attributes) {
1176
- }
1177
- addLinks(links) {
1178
- this.links.push(...links);
1179
- }
1180
- };
1181
- function getDepth(parent) {
1182
- if (parent._tag === "None")
1183
- return 0;
1184
- const p = parent.value;
1185
- if (p._tag === "ExternalSpan")
1186
- return 0;
1187
- return 1 + getDepth(p.parent);
1188
- }
1189
- var consoleTracer = effect.Tracer.make({
1190
- span: (name, parent, context, links, startTime, kind) => new ConsoleSpan(name, parent, context, links, startTime, kind, getDepth(parent)),
1191
- context: (f) => f()
1192
- });
1193
- var consoleTracerLayer = effect.Layer.setTracer(consoleTracer);
1194
-
1195
1199
  Object.defineProperty(exports, 'S', {
1196
1200
  enumerable: true,
1197
1201
  get: function () { return effect.Schema; }