@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,6 +1,6 @@
1
+ import { randomUUID } from 'crypto';
1
2
  import { Brand, Schema, Tracer, Layer, Effect, Exit, PubSub, Queue, Cause } from 'effect';
2
3
  export { Schema as S } from 'effect';
3
- import { randomUUID } from 'crypto';
4
4
 
5
5
  var __accessCheck = (obj, member, msg) => {
6
6
  if (!member.has(obj))
@@ -20,56 +20,114 @@ var __privateSet = (obj, member, value, setter) => {
20
20
  setter ? setter.call(obj, value) : member.set(obj, value);
21
21
  return value;
22
22
  };
23
- var KEBAB_CASE_REGEX = /^[a-z0-9]+(-[a-z0-9]+)*$/;
24
- var ChannelName = Brand.refined(
25
- (s) => typeof s === "string" && KEBAB_CASE_REGEX.test(s),
26
- (s) => Brand.error(`Expected kebab-case (e.g. my-channel-name), got: ${s}`)
27
- );
28
-
29
- // src/matrix/agent-network/channel.ts
30
- var Sink = {
31
- kafka(config) {
32
- return { _tag: "SinkDef", type: "kafka", config };
33
- },
34
- httpStream() {
35
- return { _tag: "SinkDef", type: "http-stream", config: {} };
23
+ var _params, _logic, _id, _listensTo;
24
+ var Agent = class {
25
+ constructor(logic, params, listensTo) {
26
+ __privateAdd(this, _params, void 0);
27
+ __privateAdd(this, _logic, void 0);
28
+ __privateAdd(this, _id, void 0);
29
+ __privateAdd(this, _listensTo, void 0);
30
+ __privateSet(this, _logic, logic);
31
+ __privateSet(this, _params, params);
32
+ __privateSet(this, _id, `agent-${randomUUID()}`);
33
+ __privateSet(this, _listensTo, listensTo ?? []);
34
+ }
35
+ getListensTo() {
36
+ return __privateGet(this, _listensTo);
37
+ }
38
+ async invoke(options) {
39
+ const { triggerEvent, emit, runEvents, contextEvents } = options ?? {};
40
+ const emitFn = emit ?? ((_event) => {
41
+ });
42
+ await __privateGet(this, _logic).call(this, {
43
+ params: __privateGet(this, _params),
44
+ triggerEvent: triggerEvent ?? void 0,
45
+ emit: emitFn,
46
+ runEvents: runEvents ?? [],
47
+ contextEvents: contextEvents ?? {
48
+ all: [],
49
+ byRun: () => [],
50
+ map: /* @__PURE__ */ new Map()
51
+ }
52
+ });
53
+ }
54
+ getId() {
55
+ return __privateGet(this, _id);
36
56
  }
37
57
  };
38
- function isHttpStreamSink(sink) {
39
- return sink.type === "http-stream";
40
- }
41
- var ConfiguredChannel = class {
42
- constructor(name) {
43
- this._tag = "ConfiguredChannel";
44
- this._events = [];
45
- this._sinks = [];
46
- this.name = name;
58
+ _params = new WeakMap();
59
+ _logic = new WeakMap();
60
+ _id = new WeakMap();
61
+ _listensTo = new WeakMap();
62
+
63
+ // src/matrix/agent-factory.ts
64
+ var AgentFactory = class _AgentFactory {
65
+ constructor({
66
+ logic,
67
+ paramsSchema,
68
+ listensTo = [],
69
+ emits = []
70
+ }) {
71
+ this._logic = logic;
72
+ this._paramsSchema = paramsSchema;
73
+ this._listensTo = listensTo;
74
+ this._emits = emits;
47
75
  }
48
- events(events) {
49
- this._events = [...events];
50
- return this;
76
+ getConstructorState() {
77
+ return {
78
+ logic: this._logic,
79
+ paramsSchema: this._paramsSchema,
80
+ listensTo: this._listensTo,
81
+ emits: this._emits
82
+ };
51
83
  }
52
- sink(sink) {
53
- this._sinks = [...this._sinks, sink];
54
- return this;
84
+ /** Union of all event definitions this agent listens to */
85
+ getListensTo() {
86
+ return this._listensTo;
55
87
  }
56
- sinks(sinks) {
57
- this._sinks = [...sinks];
58
- return this;
88
+ /** Union of all event definitions this agent can emit */
89
+ getEmits() {
90
+ return this._emits;
59
91
  }
60
- getEvents() {
61
- return this._events;
92
+ getLogic() {
93
+ return this._logic;
62
94
  }
63
- getSinks() {
64
- return this._sinks;
95
+ static run() {
96
+ return new _AgentFactory({});
65
97
  }
66
- };
67
- var Channel = {
68
- of(name) {
69
- return {
70
- _tag: "ChannelDef",
71
- name
72
- };
98
+ params(params) {
99
+ const { logic, ...rest } = this.getConstructorState();
100
+ return new _AgentFactory({
101
+ ...rest,
102
+ logic,
103
+ paramsSchema: params
104
+ });
105
+ }
106
+ listensTo(events) {
107
+ return new _AgentFactory({
108
+ ...this.getConstructorState(),
109
+ listensTo: [...this._listensTo, ...events]
110
+ });
111
+ }
112
+ emits(events) {
113
+ return new _AgentFactory({
114
+ ...this.getConstructorState(),
115
+ emits: [...this._emits, ...events]
116
+ });
117
+ }
118
+ logic(fn) {
119
+ return new _AgentFactory({
120
+ ...this.getConstructorState(),
121
+ logic: fn
122
+ });
123
+ }
124
+ produce(params) {
125
+ const listensTo = this._listensTo.map((e) => e.name);
126
+ return new Agent(
127
+ this._logic,
128
+ params,
129
+ listensTo
130
+ );
73
131
  }
74
132
  };
75
133
 
@@ -291,6 +349,60 @@ var run = (network, plane, options) => Effect.gen(function* () {
291
349
  }
292
350
  yield* Effect.never;
293
351
  });
352
+ var KEBAB_CASE_REGEX = /^[a-z0-9]+(-[a-z0-9]+)*$/;
353
+ var ChannelName = Brand.refined(
354
+ (s) => typeof s === "string" && KEBAB_CASE_REGEX.test(s),
355
+ (s) => Brand.error(`Expected kebab-case (e.g. my-channel-name), got: ${s}`)
356
+ );
357
+
358
+ // src/matrix/agent-network/channel.ts
359
+ var Sink = {
360
+ kafka(config) {
361
+ return { _tag: "SinkDef", type: "kafka", config };
362
+ },
363
+ httpStream() {
364
+ return { _tag: "SinkDef", type: "http-stream", config: {} };
365
+ }
366
+ };
367
+ function isHttpStreamSink(sink) {
368
+ return sink.type === "http-stream";
369
+ }
370
+ var ConfiguredChannel = class {
371
+ constructor(name) {
372
+ this._tag = "ConfiguredChannel";
373
+ this._events = [];
374
+ this._sinks = [];
375
+ this.name = name;
376
+ }
377
+ events(events) {
378
+ this._events = [...events];
379
+ return this;
380
+ }
381
+ sink(sink) {
382
+ this._sinks = [...this._sinks, sink];
383
+ return this;
384
+ }
385
+ sinks(sinks) {
386
+ this._sinks = [...sinks];
387
+ return this;
388
+ }
389
+ getEvents() {
390
+ return this._events;
391
+ }
392
+ getSinks() {
393
+ return this._sinks;
394
+ }
395
+ };
396
+ var Channel = {
397
+ of(name) {
398
+ return {
399
+ _tag: "ChannelDef",
400
+ name
401
+ };
402
+ }
403
+ };
404
+
405
+ // src/matrix/io/expose.ts
294
406
  async function extractPayload(req) {
295
407
  const webRequest = req.request;
296
408
  if (webRequest?.method === "POST") {
@@ -468,12 +580,10 @@ var AgentNetwork = class _AgentNetwork {
468
580
  /* ─── Public Static Factory ─── */
469
581
  static setup(callback) {
470
582
  const network = new _AgentNetwork();
583
+ const mainChannel = network.addChannel("main");
584
+ network.setMainChannel(mainChannel);
471
585
  const ctx = {
472
- mainChannel: (name) => {
473
- const channel = network.addChannel(name);
474
- network.setMainChannel(channel);
475
- return channel;
476
- },
586
+ mainChannel,
477
587
  createChannel: (name) => network.addChannel(name),
478
588
  sink: Sink,
479
589
  registerAgent: (agent) => network.registerAgentInternal(agent),
@@ -486,6 +596,10 @@ var AgentNetwork = class _AgentNetwork {
486
596
  /* ─── Internal Builders ─── */
487
597
  addChannel(name) {
488
598
  const channelName = ChannelName(name);
599
+ const existing = this.channels.get(channelName);
600
+ if (existing) {
601
+ return existing;
602
+ }
489
603
  const channel = new ConfiguredChannel(channelName);
490
604
  this.channels.set(channelName, channel);
491
605
  return channel;
@@ -673,27 +787,27 @@ var EventAggregator = class _EventAggregator {
673
787
  });
674
788
  }
675
789
  };
676
- var _id, _listensTo, _emitWhen, _mapToEmit;
790
+ var _id2, _listensTo2, _emitWhen, _mapToEmit;
677
791
  var EventAggregatorInstance = class {
678
792
  constructor({
679
793
  listensTo,
680
794
  emitWhen,
681
795
  mapToEmit
682
796
  }) {
683
- __privateAdd(this, _id, void 0);
684
- __privateAdd(this, _listensTo, void 0);
797
+ __privateAdd(this, _id2, void 0);
798
+ __privateAdd(this, _listensTo2, void 0);
685
799
  __privateAdd(this, _emitWhen, void 0);
686
800
  __privateAdd(this, _mapToEmit, void 0);
687
- __privateSet(this, _id, `event-aggregator-${randomUUID()}`);
688
- __privateSet(this, _listensTo, listensTo);
801
+ __privateSet(this, _id2, `event-aggregator-${randomUUID()}`);
802
+ __privateSet(this, _listensTo2, listensTo);
689
803
  __privateSet(this, _emitWhen, emitWhen);
690
804
  __privateSet(this, _mapToEmit, mapToEmit);
691
805
  }
692
806
  getId() {
693
- return __privateGet(this, _id);
807
+ return __privateGet(this, _id2);
694
808
  }
695
809
  getListensTo() {
696
- return __privateGet(this, _listensTo);
810
+ return __privateGet(this, _listensTo2);
697
811
  }
698
812
  async invoke(options) {
699
813
  const { triggerEvent, emit, runEvents, contextEvents } = options ?? {};
@@ -724,118 +838,205 @@ var EventAggregatorInstance = class {
724
838
  });
725
839
  }
726
840
  };
727
- _id = new WeakMap();
728
- _listensTo = new WeakMap();
841
+ _id2 = new WeakMap();
842
+ _listensTo2 = new WeakMap();
729
843
  _emitWhen = new WeakMap();
730
844
  _mapToEmit = new WeakMap();
731
- var _params, _logic, _id2, _listensTo2;
732
- var Agent = class {
733
- constructor(logic, params, listensTo) {
734
- __privateAdd(this, _params, void 0);
735
- __privateAdd(this, _logic, void 0);
736
- __privateAdd(this, _id2, void 0);
737
- __privateAdd(this, _listensTo2, void 0);
738
- __privateSet(this, _logic, logic);
739
- __privateSet(this, _params, params);
740
- __privateSet(this, _id2, `agent-${randomUUID()}`);
741
- __privateSet(this, _listensTo2, listensTo ?? []);
742
- }
743
- getListensTo() {
744
- return __privateGet(this, _listensTo2);
745
- }
746
- async invoke(options) {
747
- const { triggerEvent, emit, runEvents, contextEvents } = options ?? {};
748
- const emitFn = emit ?? ((_event) => {
749
- });
750
- await __privateGet(this, _logic).call(this, {
751
- params: __privateGet(this, _params),
752
- triggerEvent: triggerEvent ?? void 0,
753
- emit: emitFn,
754
- runEvents: runEvents ?? [],
755
- contextEvents: contextEvents ?? {
756
- all: [],
757
- byRun: () => [],
758
- map: /* @__PURE__ */ new Map()
759
- }
760
- });
761
- }
762
- getId() {
763
- return __privateGet(this, _id2);
845
+ var randomHexString = (length) => {
846
+ const chars = "abcdef0123456789";
847
+ let result = "";
848
+ for (let i = 0; i < length; i++) {
849
+ result += chars.charAt(Math.floor(Math.random() * chars.length));
764
850
  }
851
+ return result;
765
852
  };
766
- _params = new WeakMap();
767
- _logic = new WeakMap();
768
- _id2 = new WeakMap();
769
- _listensTo2 = new WeakMap();
770
-
771
- // src/matrix/agent-factory.ts
772
- var AgentFactory = class _AgentFactory {
773
- constructor({
774
- logic,
775
- paramsSchema,
776
- listensTo = [],
777
- emits = []
778
- }) {
779
- this._logic = logic;
780
- this._paramsSchema = paramsSchema;
781
- this._listensTo = listensTo;
782
- this._emits = emits;
783
- }
784
- getConstructorState() {
785
- return {
786
- logic: this._logic,
787
- paramsSchema: this._paramsSchema,
788
- listensTo: this._listensTo,
789
- emits: this._emits
790
- };
791
- }
792
- /** Union of all event definitions this agent listens to */
793
- getListensTo() {
794
- return this._listensTo;
795
- }
796
- /** Union of all event definitions this agent can emit */
797
- getEmits() {
798
- return this._emits;
799
- }
800
- getLogic() {
801
- return this._logic;
853
+ var ConsoleSpan = class {
854
+ constructor(name, parent, context, links, startTime, kind, depth) {
855
+ this.name = name;
856
+ this.parent = parent;
857
+ this.context = context;
858
+ this.startTime = startTime;
859
+ this.kind = kind;
860
+ this.depth = depth;
861
+ this._tag = "Span";
862
+ this.sampled = true;
863
+ this.attributes = /* @__PURE__ */ new Map();
864
+ this.links = [];
865
+ this.traceId = parent._tag === "Some" ? parent.value.traceId : randomHexString(32);
866
+ this.spanId = randomHexString(16);
867
+ this.links = Array.from(links);
868
+ this.status = { _tag: "Started", startTime };
802
869
  }
803
- static run() {
804
- return new _AgentFactory({});
870
+ end(endTime, exit) {
871
+ if (this.status._tag === "Ended")
872
+ return;
873
+ const startTime = this.status.startTime;
874
+ const durationNs = endTime - startTime;
875
+ const durationMs = Number(durationNs) / 1e6;
876
+ const indent = " ".repeat(this.depth);
877
+ const attrs = Object.fromEntries(this.attributes);
878
+ const status = Exit.isSuccess(exit) ? "ok" : "error";
879
+ console.log(
880
+ `${indent}[trace] ${this.name} ${durationMs.toFixed(2)}ms (${status})`,
881
+ Object.keys(attrs).length > 0 ? attrs : ""
882
+ );
883
+ this.status = { _tag: "Ended", startTime, endTime, exit };
805
884
  }
806
- params(params) {
807
- const { logic, ...rest } = this.getConstructorState();
808
- return new _AgentFactory({
809
- ...rest,
810
- logic,
811
- paramsSchema: params
812
- });
885
+ attribute(key, value) {
886
+ this.attributes.set(key, value);
813
887
  }
814
- listensTo(events) {
815
- return new _AgentFactory({
816
- ...this.getConstructorState(),
817
- listensTo: [...this._listensTo, ...events]
818
- });
888
+ event(_name, _startTime, _attributes) {
819
889
  }
820
- emits(events) {
821
- return new _AgentFactory({
822
- ...this.getConstructorState(),
823
- emits: [...this._emits, ...events]
824
- });
890
+ addLinks(links) {
891
+ this.links.push(...links);
825
892
  }
826
- logic(fn) {
827
- return new _AgentFactory({
828
- ...this.getConstructorState(),
829
- logic: fn
830
- });
893
+ };
894
+ function getDepth(parent) {
895
+ if (parent._tag === "None")
896
+ return 0;
897
+ const p = parent.value;
898
+ if (p._tag === "ExternalSpan")
899
+ return 0;
900
+ return 1 + getDepth(p.parent);
901
+ }
902
+ var consoleTracer = Tracer.make({
903
+ span: (name, parent, context, links, startTime, kind) => new ConsoleSpan(name, parent, context, links, startTime, kind, getDepth(parent)),
904
+ context: (f) => f()
905
+ });
906
+ var consoleTracerLayer = Layer.setTracer(consoleTracer);
907
+
908
+ // src/matrix/io/protocols/sse.ts
909
+ function formatSSE(envelope) {
910
+ const data = JSON.stringify(envelope);
911
+ return `event: ${envelope.name}
912
+ data: ${data}
913
+
914
+ `;
915
+ }
916
+ function toSSEStream(source, signal) {
917
+ const encoder = new TextEncoder();
918
+ return new ReadableStream({
919
+ async start(controller) {
920
+ const onAbort = () => controller.close();
921
+ signal?.addEventListener("abort", onAbort, { once: true });
922
+ try {
923
+ for await (const envelope of source) {
924
+ if (signal?.aborted)
925
+ break;
926
+ controller.enqueue(encoder.encode(formatSSE(envelope)));
927
+ }
928
+ } finally {
929
+ signal?.removeEventListener("abort", onAbort);
930
+ controller.close();
931
+ }
932
+ }
933
+ });
934
+ }
935
+
936
+ // src/matrix/io/adapters/next-endpoint.ts
937
+ var NextEndpoint = {
938
+ from(api, options) {
939
+ if (api.protocol !== "sse") {
940
+ throw new Error(`NextEndpoint: unsupported protocol "${api.protocol}"`);
941
+ }
942
+ const { requestToContextId, requestToRunId } = options;
943
+ return {
944
+ handler() {
945
+ return async (request) => {
946
+ const req = {
947
+ request,
948
+ contextId: requestToContextId(request),
949
+ runId: requestToRunId(request)
950
+ };
951
+ try {
952
+ const encoder = new TextEncoder();
953
+ const { readable, writable } = new TransformStream();
954
+ let consumerStarted;
955
+ const started = new Promise((resolve) => {
956
+ consumerStarted = resolve;
957
+ });
958
+ const streamDone = api.createStream(req, async (stream) => {
959
+ consumerStarted();
960
+ const writer = writable.getWriter();
961
+ try {
962
+ for await (const envelope of stream) {
963
+ if (request.signal?.aborted)
964
+ break;
965
+ await writer.write(encoder.encode(formatSSE(envelope)));
966
+ }
967
+ } finally {
968
+ await writer.close();
969
+ }
970
+ });
971
+ await Promise.race([started, streamDone]);
972
+ streamDone.catch(() => {
973
+ });
974
+ return new Response(readable, {
975
+ headers: {
976
+ "Content-Type": "text/event-stream",
977
+ "Cache-Control": "no-cache",
978
+ Connection: "keep-alive"
979
+ }
980
+ });
981
+ } catch (e) {
982
+ if (e instanceof ExposeAuthError) {
983
+ return new Response(e.message, { status: e.status });
984
+ }
985
+ throw e;
986
+ }
987
+ };
988
+ }
989
+ };
831
990
  }
832
- produce(params) {
833
- const listensTo = this._listensTo.map((e) => e.name);
834
- return new Agent(
835
- this._logic,
836
- params,
837
- listensTo
838
- );
991
+ };
992
+
993
+ // src/matrix/io/adapters/express-endpoint.ts
994
+ var ExpressEndpoint = {
995
+ from(api, options) {
996
+ if (api.protocol !== "sse") {
997
+ throw new Error(`ExpressEndpoint: unsupported protocol "${api.protocol}"`);
998
+ }
999
+ const { requestToContextId, requestToRunId } = options;
1000
+ return {
1001
+ handler() {
1002
+ return async (req, res) => {
1003
+ const controller = new AbortController();
1004
+ req.on("close", () => controller.abort());
1005
+ const exposeReq = {
1006
+ request: { signal: controller.signal },
1007
+ req,
1008
+ res,
1009
+ contextId: requestToContextId(req),
1010
+ runId: requestToRunId(req)
1011
+ };
1012
+ try {
1013
+ const encoder = new TextEncoder();
1014
+ await api.createStream(exposeReq, async (stream) => {
1015
+ res.setHeader("Content-Type", "text/event-stream");
1016
+ res.setHeader("Cache-Control", "no-cache");
1017
+ res.setHeader("Connection", "keep-alive");
1018
+ res.flushHeaders?.();
1019
+ try {
1020
+ for await (const envelope of stream) {
1021
+ if (controller.signal.aborted)
1022
+ break;
1023
+ res.write(encoder.encode(formatSSE(envelope)));
1024
+ res.flush?.();
1025
+ }
1026
+ } finally {
1027
+ res.end();
1028
+ }
1029
+ });
1030
+ } catch (e) {
1031
+ if (e instanceof ExposeAuthError) {
1032
+ res.status(e.status).send(e.message);
1033
+ return;
1034
+ }
1035
+ throw e;
1036
+ }
1037
+ };
1038
+ }
1039
+ };
839
1040
  }
840
1041
  };
841
1042
  var CAMEL_CASE_REGEX = /^[a-z][a-zA-Z0-9]*$/;
@@ -994,203 +1195,6 @@ var Skill = class _Skill {
994
1195
  }
995
1196
  };
996
1197
 
997
- // src/matrix/io/protocols/sse.ts
998
- function formatSSE(envelope) {
999
- const data = JSON.stringify(envelope);
1000
- return `event: ${envelope.name}
1001
- data: ${data}
1002
-
1003
- `;
1004
- }
1005
- function toSSEStream(source, signal) {
1006
- const encoder = new TextEncoder();
1007
- return new ReadableStream({
1008
- async start(controller) {
1009
- const onAbort = () => controller.close();
1010
- signal?.addEventListener("abort", onAbort, { once: true });
1011
- try {
1012
- for await (const envelope of source) {
1013
- if (signal?.aborted)
1014
- break;
1015
- controller.enqueue(encoder.encode(formatSSE(envelope)));
1016
- }
1017
- } finally {
1018
- signal?.removeEventListener("abort", onAbort);
1019
- controller.close();
1020
- }
1021
- }
1022
- });
1023
- }
1024
-
1025
- // src/matrix/io/adapters/next-endpoint.ts
1026
- var NextEndpoint = {
1027
- from(api, options) {
1028
- if (api.protocol !== "sse") {
1029
- throw new Error(`NextEndpoint: unsupported protocol "${api.protocol}"`);
1030
- }
1031
- const { requestToContextId, requestToRunId } = options;
1032
- return {
1033
- handler() {
1034
- return async (request) => {
1035
- const req = {
1036
- request,
1037
- contextId: requestToContextId(request),
1038
- runId: requestToRunId(request)
1039
- };
1040
- try {
1041
- const encoder = new TextEncoder();
1042
- const { readable, writable } = new TransformStream();
1043
- let consumerStarted;
1044
- const started = new Promise((resolve) => {
1045
- consumerStarted = resolve;
1046
- });
1047
- const streamDone = api.createStream(req, async (stream) => {
1048
- consumerStarted();
1049
- const writer = writable.getWriter();
1050
- try {
1051
- for await (const envelope of stream) {
1052
- if (request.signal?.aborted)
1053
- break;
1054
- await writer.write(encoder.encode(formatSSE(envelope)));
1055
- }
1056
- } finally {
1057
- await writer.close();
1058
- }
1059
- });
1060
- await Promise.race([started, streamDone]);
1061
- streamDone.catch(() => {
1062
- });
1063
- return new Response(readable, {
1064
- headers: {
1065
- "Content-Type": "text/event-stream",
1066
- "Cache-Control": "no-cache",
1067
- Connection: "keep-alive"
1068
- }
1069
- });
1070
- } catch (e) {
1071
- if (e instanceof ExposeAuthError) {
1072
- return new Response(e.message, { status: e.status });
1073
- }
1074
- throw e;
1075
- }
1076
- };
1077
- }
1078
- };
1079
- }
1080
- };
1081
-
1082
- // src/matrix/io/adapters/express-endpoint.ts
1083
- var ExpressEndpoint = {
1084
- from(api, options) {
1085
- if (api.protocol !== "sse") {
1086
- throw new Error(`ExpressEndpoint: unsupported protocol "${api.protocol}"`);
1087
- }
1088
- const { requestToContextId, requestToRunId } = options;
1089
- return {
1090
- handler() {
1091
- return async (req, res) => {
1092
- const controller = new AbortController();
1093
- req.on("close", () => controller.abort());
1094
- const exposeReq = {
1095
- request: { signal: controller.signal },
1096
- req,
1097
- res,
1098
- contextId: requestToContextId(req),
1099
- runId: requestToRunId(req)
1100
- };
1101
- try {
1102
- const encoder = new TextEncoder();
1103
- await api.createStream(exposeReq, async (stream) => {
1104
- res.setHeader("Content-Type", "text/event-stream");
1105
- res.setHeader("Cache-Control", "no-cache");
1106
- res.setHeader("Connection", "keep-alive");
1107
- res.flushHeaders?.();
1108
- try {
1109
- for await (const envelope of stream) {
1110
- if (controller.signal.aborted)
1111
- break;
1112
- res.write(encoder.encode(formatSSE(envelope)));
1113
- res.flush?.();
1114
- }
1115
- } finally {
1116
- res.end();
1117
- }
1118
- });
1119
- } catch (e) {
1120
- if (e instanceof ExposeAuthError) {
1121
- res.status(e.status).send(e.message);
1122
- return;
1123
- }
1124
- throw e;
1125
- }
1126
- };
1127
- }
1128
- };
1129
- }
1130
- };
1131
- var randomHexString = (length) => {
1132
- const chars = "abcdef0123456789";
1133
- let result = "";
1134
- for (let i = 0; i < length; i++) {
1135
- result += chars.charAt(Math.floor(Math.random() * chars.length));
1136
- }
1137
- return result;
1138
- };
1139
- var ConsoleSpan = class {
1140
- constructor(name, parent, context, links, startTime, kind, depth) {
1141
- this.name = name;
1142
- this.parent = parent;
1143
- this.context = context;
1144
- this.startTime = startTime;
1145
- this.kind = kind;
1146
- this.depth = depth;
1147
- this._tag = "Span";
1148
- this.sampled = true;
1149
- this.attributes = /* @__PURE__ */ new Map();
1150
- this.links = [];
1151
- this.traceId = parent._tag === "Some" ? parent.value.traceId : randomHexString(32);
1152
- this.spanId = randomHexString(16);
1153
- this.links = Array.from(links);
1154
- this.status = { _tag: "Started", startTime };
1155
- }
1156
- end(endTime, exit) {
1157
- if (this.status._tag === "Ended")
1158
- return;
1159
- const startTime = this.status.startTime;
1160
- const durationNs = endTime - startTime;
1161
- const durationMs = Number(durationNs) / 1e6;
1162
- const indent = " ".repeat(this.depth);
1163
- const attrs = Object.fromEntries(this.attributes);
1164
- const status = Exit.isSuccess(exit) ? "ok" : "error";
1165
- console.log(
1166
- `${indent}[trace] ${this.name} ${durationMs.toFixed(2)}ms (${status})`,
1167
- Object.keys(attrs).length > 0 ? attrs : ""
1168
- );
1169
- this.status = { _tag: "Ended", startTime, endTime, exit };
1170
- }
1171
- attribute(key, value) {
1172
- this.attributes.set(key, value);
1173
- }
1174
- event(_name, _startTime, _attributes) {
1175
- }
1176
- addLinks(links) {
1177
- this.links.push(...links);
1178
- }
1179
- };
1180
- function getDepth(parent) {
1181
- if (parent._tag === "None")
1182
- return 0;
1183
- const p = parent.value;
1184
- if (p._tag === "ExternalSpan")
1185
- return 0;
1186
- return 1 + getDepth(p.parent);
1187
- }
1188
- var consoleTracer = Tracer.make({
1189
- span: (name, parent, context, links, startTime, kind) => new ConsoleSpan(name, parent, context, links, startTime, kind, getDepth(parent)),
1190
- context: (f) => f()
1191
- });
1192
- var consoleTracerLayer = Layer.setTracer(consoleTracer);
1193
-
1194
1198
  export { Agent, AgentFactory, AgentNetwork, AgentNetworkEvent, Channel, ChannelName, ConfiguredChannel, DepedencyLayer, Done, EventAggregator, EventAggregatorInstance, EventMetaSchema, ExposeAuthError, ExpressEndpoint, LayerName, NextEndpoint, Sink, Skill, consoleTracer, consoleTracerLayer, formatSSE, isHttpStreamSink, toSSEStream };
1195
1199
  //# sourceMappingURL=out.js.map
1196
1200
  //# sourceMappingURL=index.js.map