@kortyx/telemetry 0.1.0 → 0.3.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/CHANGELOG.md CHANGED
@@ -1,5 +1,44 @@
1
1
  # Changelog
2
2
 
3
+ ## [0.3.0](https://github.com/kortyx-io/kortyx/compare/telemetry-v0.2.0...telemetry-v0.3.0) (2026-09-09)
4
+
5
+
6
+ ### Features
7
+
8
+ * add resumable child workflows and Studio inspection ([#157](https://github.com/kortyx-io/kortyx/issues/157)) ([542ba29](https://github.com/kortyx-io/kortyx/commit/542ba29b3b57217e6e5d98c1b409bbec5ce3261f))
9
+
10
+
11
+ ### Dependencies
12
+
13
+ * The following workspace dependencies were updated
14
+ * dependencies
15
+ * @kortyx/hooks bumped to 0.19.0
16
+ * @kortyx/telemetry-contracts bumped to 0.3.0
17
+
18
+ ## [0.2.0](https://github.com/kortyx-io/kortyx/compare/telemetry-v0.1.0...telemetry-v0.2.0) (2026-08-02)
19
+
20
+
21
+ ### Features
22
+
23
+ * **studio:** harden self-hosted preview ([c5438f8](https://github.com/kortyx-io/kortyx/commit/c5438f89499f98df7bf6d10cff9e1e37812a1496))
24
+ * **studio:** release self-hosted observability preview ([4e9d3fd](https://github.com/kortyx-io/kortyx/commit/4e9d3fdbc7233f9b1de94ca1afe6dbae9cc9157f))
25
+ * **studio:** release self-hosted observability preview ([#139](https://github.com/kortyx-io/kortyx/issues/139)) ([4e9d3fd](https://github.com/kortyx-io/kortyx/commit/4e9d3fdbc7233f9b1de94ca1afe6dbae9cc9157f))
26
+ * **telemetry:** add persisted studio read models ([cebb06b](https://github.com/kortyx-io/kortyx/commit/cebb06bb74ccd4422e263f0ff4efa0fee5a16240))
27
+
28
+
29
+ ### Bug Fixes
30
+
31
+ * harden interrupt lifecycle semantics ([958d149](https://github.com/kortyx-io/kortyx/commit/958d149596d54215821ef5a7f8562a06a7459149))
32
+ * **studio:** reconcile incomplete run lifecycles ([2a3d9f4](https://github.com/kortyx-io/kortyx/commit/2a3d9f4cc927cccfd6efc6256a848b704a0d203f))
33
+
34
+
35
+ ### Dependencies
36
+
37
+ * The following workspace dependencies were updated
38
+ * dependencies
39
+ * @kortyx/hooks bumped to 0.18.0
40
+ * @kortyx/telemetry-contracts bumped to 0.2.0
41
+
3
42
  ## 0.1.0
4
43
 
5
44
  - Initial Studio telemetry HTTP adapter.
package/LICENSE CHANGED
@@ -1,10 +1,18 @@
1
+ Copyright 2026 Kortyx contributors
2
+
3
+ Portions of this software are licensed as follows:
4
+
5
+ - All content that resides under the `apps/studio/` directory of this repository is licensed under the license defined in `apps/studio/LICENSE.md`.
6
+ - All content that resides under a `plugins/*/` directory of this repository is licensed under the license defined in that plugin's `LICENSE.md`.
7
+ - All third party components incorporated into the Kortyx software are licensed under the original license provided by the owner of the applicable component.
8
+ - Content outside of the above mentioned directories or restrictions is available under the Apache License, Version 2.0, as defined below.
9
+
1
10
  Apache License
2
11
  Version 2.0, January 2004
3
12
  http://www.apache.org/licenses/
4
13
 
5
- TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
-
7
- 1. Definitions.
14
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
15
+ 1. Definitions.
8
16
 
9
17
  "License" shall mean the terms and conditions for use, reproduction,
10
18
  and distribution as defined by Sections 1 through 9 of this document.
@@ -63,14 +71,14 @@
63
71
  on behalf of whom a Contribution has been received by Licensor and
64
72
  subsequently incorporated within the Work.
65
73
 
66
- 2. Grant of Copyright License. Subject to the terms and conditions of
74
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
75
  this License, each Contributor hereby grants to You a perpetual,
68
76
  worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
77
  copyright license to reproduce, prepare Derivative Works of,
70
78
  publicly display, publicly perform, sublicense, and distribute the
71
79
  Work and such Derivative Works in Source or Object form.
72
80
 
73
- 3. Grant of Patent License. Subject to the terms and conditions of
81
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
82
  this License, each Contributor hereby grants to You a perpetual,
75
83
  worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
84
  (except as stated in this section) patent license to make, have made,
@@ -86,39 +94,39 @@
86
94
  granted to You under this License for that Work shall terminate
87
95
  as of the date such litigation is filed.
88
96
 
89
- 4. Redistribution. You may reproduce and distribute copies of the
97
+ 4. Redistribution. You may reproduce and distribute copies of the
90
98
  Work or Derivative Works thereof in any medium, with or without
91
99
  modifications, and in Source or Object form, provided that You
92
100
  meet the following conditions:
93
101
 
94
102
  (a) You must give any other recipients of the Work or
95
- Derivative Works a copy of this License; and
103
+ Derivative Works a copy of this License; and
96
104
 
97
105
  (b) You must cause any modified files to carry prominent notices
98
- stating that You changed the files; and
106
+ stating that You changed the files; and
99
107
 
100
108
  (c) You must retain, in the Source form of any Derivative Works
101
- that You distribute, all copyright, patent, trademark, and
102
- attribution notices from the Source form of the Work,
103
- excluding those notices that do not pertain to any part of
104
- the Derivative Works; and
109
+ that You distribute, all copyright, patent, trademark, and
110
+ attribution notices from the Source form of the Work,
111
+ excluding those notices that do not pertain to any part of
112
+ the Derivative Works; and
105
113
 
106
114
  (d) If the Work includes a "NOTICE" text file as part of its
107
- distribution, then any Derivative Works that You distribute must
108
- include a readable copy of the attribution notices contained
109
- within such NOTICE file, excluding those notices that do not
110
- pertain to any part of the Derivative Works, in at least one
111
- of the following places: within a NOTICE text file distributed
112
- as part of the Derivative Works; within the Source form or
113
- documentation, if provided along with the Derivative Works; or,
114
- within a display generated by the Derivative Works, if and
115
- wherever such third-party notices normally appear. The contents
116
- of the NOTICE file are for informational purposes only and
117
- do not modify the License. You may add Your own attribution
118
- notices within Derivative Works that You distribute, alongside
119
- or as an addendum to the NOTICE text from the Work, provided
120
- that such additional attribution notices cannot be construed
121
- as modifying the License.
115
+ distribution, then any Derivative Works that You distribute must
116
+ include a readable copy of the attribution notices contained
117
+ within such NOTICE file, excluding those notices that do not
118
+ pertain to any part of the Derivative Works, in at least one
119
+ of the following places: within a NOTICE text file distributed
120
+ as part of the Derivative Works; within the Source form or
121
+ documentation, if provided along with the Derivative Works; or,
122
+ within a display generated by the Derivative Works, if and
123
+ wherever such third-party notices normally appear. The contents
124
+ of the NOTICE file are for informational purposes only and
125
+ do not modify the License. You may add Your own attribution
126
+ notices within Derivative Works that You distribute, alongside
127
+ or as an addendum to the NOTICE text from the Work, provided
128
+ that such additional attribution notices cannot be construed
129
+ as modifying the License.
122
130
 
123
131
  You may add Your own copyright statement to Your modifications and
124
132
  may provide additional or different license terms and conditions
@@ -127,7 +135,7 @@
127
135
  reproduction, and distribution of the Work otherwise complies with
128
136
  the conditions stated in this License.
129
137
 
130
- 5. Submission of Contributions. Unless You explicitly state otherwise,
138
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
139
  any Contribution intentionally submitted for inclusion in the Work
132
140
  by You to the Licensor shall be under the terms and conditions of
133
141
  this License, without any additional terms or conditions.
@@ -135,12 +143,12 @@
135
143
  the terms of any separate license agreement you may have executed
136
144
  with Licensor regarding such Contributions.
137
145
 
138
- 6. Trademarks. This License does not grant permission to use the trade
146
+ 6. Trademarks. This License does not grant permission to use the trade
139
147
  names, trademarks, service marks, or product names of the Licensor,
140
148
  except as required for reasonable and customary use in describing the
141
149
  origin of the Work and reproducing the content of the NOTICE file.
142
150
 
143
- 7. Disclaimer of Warranty. Unless required by applicable law or
151
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
152
  agreed to in writing, Licensor provides the Work (and each
145
153
  Contributor provides its Contributions) on an "AS IS" BASIS,
146
154
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
@@ -150,7 +158,7 @@
150
158
  appropriateness of using or redistributing the Work and assume any
151
159
  risks associated with Your exercise of permissions under this License.
152
160
 
153
- 8. Limitation of Liability. In no event and under no legal theory,
161
+ 8. Limitation of Liability. In no event and under no legal theory,
154
162
  whether in tort (including negligence), contract, or otherwise,
155
163
  unless required by applicable law (such as deliberate and grossly
156
164
  negligent acts) or agreed to in writing, shall any Contributor be
@@ -162,7 +170,7 @@
162
170
  other commercial damages or losses), even if such Contributor
163
171
  has been advised of the possibility of such damages.
164
172
 
165
- 9. Accepting Warranty or Additional Liability. While redistributing
173
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
174
  the Work or Derivative Works thereof, You may choose to offer,
167
175
  and charge a fee for, acceptance of support, warranty, indemnity,
168
176
  or other liability obligations and/or rights consistent with this
@@ -173,9 +181,9 @@
173
181
  incurred by, or claims asserted against, such Contributor by reason
174
182
  of your accepting any such warranty or additional liability.
175
183
 
176
- END OF TERMS AND CONDITIONS
184
+ END OF TERMS AND CONDITIONS
177
185
 
178
- APPENDIX: How to apply the Apache License to your work.
186
+ APPENDIX: How to apply the Apache License to your work.
179
187
 
180
188
  To apply the Apache License to your work, attach the following
181
189
  boilerplate notice, with the fields enclosed by brackets "[]"
@@ -186,16 +194,16 @@
186
194
  same "printed page" as the copyright notice for easier
187
195
  identification within third-party archives.
188
196
 
189
- Copyright [yyyy] [name of copyright owner]
197
+ Copyright [yyyy] [name of copyright owner]
190
198
 
191
- Licensed under the Apache License, Version 2.0 (the "License");
192
- you may not use this file except in compliance with the License.
193
- You may obtain a copy of the License at
199
+ Licensed under the Apache License, Version 2.0 (the "License");
200
+ you may not use this file except in compliance with the License.
201
+ You may obtain a copy of the License at
194
202
 
195
203
  http://www.apache.org/licenses/LICENSE-2.0
196
204
 
197
- Unless required by applicable law or agreed to in writing, software
198
- distributed under the License is distributed on an "AS IS" BASIS,
199
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
- See the License for the specific language governing permissions and
201
- limitations under the License.
205
+ Unless required by applicable law or agreed to in writing, software
206
+ distributed under the License is distributed on an "AS IS" BASIS,
207
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
208
+ See the License for the specific language governing permissions and
209
+ limitations under the License.
package/README.md CHANGED
@@ -9,10 +9,13 @@ import { createAgent } from "kortyx";
9
9
  import { createKortyxTelemetryAdapter } from "@kortyx/telemetry";
10
10
 
11
11
  const telemetry = createKortyxTelemetryAdapter({
12
- endpoint: process.env.KORTYX_TELEMETRY_ENDPOINT!,
12
+ endpoint: process.env.KORTYX_TELEMETRY_API_URL!,
13
13
  apiKey: process.env.KORTYX_TELEMETRY_API_KEY!,
14
- environment: "production",
15
- service: { name: "support-agent" },
14
+ environment:
15
+ process.env.KORTYX_TELEMETRY_ENVIRONMENT ?? "development",
16
+ service: {
17
+ name: process.env.KORTYX_TELEMETRY_SERVICE_NAME ?? "support-agent",
18
+ },
16
19
  });
17
20
 
18
21
  const agent = createAgent({
@@ -53,5 +56,13 @@ workflow execution.
53
56
  included with `interrupt.created`. The SDK does not use an unreliable local TTL
54
57
  timer.
55
58
 
59
+ Interrupt events always retain non-sensitive structure: `kind`,
60
+ `interactionMode`, `optionCount`, `schemaId`, and `schemaVersion`.
61
+ `interactionMode` distinguishes `static-options`, `dynamic-picker`, and
62
+ `freeform` requests, so a client-resolved picker is not mistaken for a choice
63
+ with zero options. Questions and static option labels follow output-content
64
+ capture; a submitted human response follows input-content capture. Option
65
+ values and resume capability tokens are never included in interrupt telemetry.
66
+
56
67
  `run.cancelled` is reserved until Kortyx exposes a real SDK cancellation
57
68
  operation. A client disconnect is not a cancellation.
package/dist/index.js CHANGED
@@ -50,42 +50,53 @@ var createDelivery = (args) => {
50
50
  if (typeof timer === "object" && "unref" in timer) timer.unref?.();
51
51
  };
52
52
  const flush = async () => {
53
- if (inFlight) return inFlight;
54
- if (timer) {
55
- clearTimeout(timer);
56
- timer = void 0;
57
- }
58
- if (queue.length === 0) return;
59
- const events = queue.splice(0);
60
- inFlight = (async () => {
61
- let retry;
62
- try {
63
- await args.send(events);
64
- retryAttempt = 0;
65
- } catch (error) {
66
- const status = error instanceof TelemetryHttpError ? error.status : void 0;
67
- if (status !== void 0 && status !== 429 && status < 500) {
68
- permanentFailures += events.length;
69
- return;
70
- }
71
- const overflow = Math.max(
72
- 0,
73
- queue.length + events.length - args.maxQueueSize
74
- );
75
- if (overflow) {
76
- dropped += overflow;
77
- events.splice(0, overflow);
53
+ while (true) {
54
+ if (inFlight) {
55
+ const result2 = await inFlight;
56
+ if (result2.retryDelay !== null) return;
57
+ continue;
58
+ }
59
+ if (timer) {
60
+ clearTimeout(timer);
61
+ timer = void 0;
62
+ }
63
+ if (queue.length === 0) return;
64
+ const events = queue.splice(0);
65
+ const current = (async () => {
66
+ try {
67
+ await args.send(events);
68
+ retryAttempt = 0;
69
+ return { retryDelay: null };
70
+ } catch (error) {
71
+ const status = error instanceof TelemetryHttpError ? error.status : void 0;
72
+ if (status !== void 0 && status !== 429 && status < 500) {
73
+ permanentFailures += events.length;
74
+ return { retryDelay: null };
75
+ }
76
+ const overflow = Math.max(
77
+ 0,
78
+ queue.length + events.length - args.maxQueueSize
79
+ );
80
+ if (overflow) {
81
+ dropped += overflow;
82
+ events.splice(0, overflow);
83
+ }
84
+ queue.unshift(...events);
85
+ retryAttempt += 1;
86
+ const backoff = Math.min(3e4, 250 * 2 ** (retryAttempt - 1));
87
+ return {
88
+ retryDelay: Math.floor(backoff * (0.5 + Math.random() * 0.5))
89
+ };
78
90
  }
79
- queue.unshift(...events);
80
- retryAttempt += 1;
81
- const backoff = Math.min(3e4, 250 * 2 ** (retryAttempt - 1));
82
- retry = Math.floor(backoff * (0.5 + Math.random() * 0.5));
83
- } finally {
84
- inFlight = void 0;
85
- if (retry !== void 0) schedule(retry);
91
+ })();
92
+ inFlight = current;
93
+ const result = await current;
94
+ if (inFlight === current) inFlight = void 0;
95
+ if (result.retryDelay !== null) {
96
+ schedule(result.retryDelay);
97
+ return;
86
98
  }
87
- })();
88
- return inFlight;
99
+ }
89
100
  };
90
101
  return {
91
102
  enqueue: (event) => {
@@ -117,13 +128,20 @@ var correlationFrom = (attributes, active) => {
117
128
  const runId = stringValue(source.runId) ?? active?.correlation.runId;
118
129
  const workflowId = stringValue(source.workflowId) ?? active?.correlation.workflowId;
119
130
  if (!runId || !workflowId) return void 0;
131
+ const sameWorkflow = workflowId === active?.correlation.workflowId;
120
132
  const sessionId = stringValue(source.sessionId) ?? active?.correlation.sessionId;
121
- const workflowRevisionId = stringValue(source.workflowRevisionId) ?? active?.correlation.workflowRevisionId;
122
- const topologyHash = stringValue(source.topologyHash) ?? active?.correlation.topologyHash;
123
- const nodeId = stringValue(source.nodeId) ?? active?.correlation.nodeId;
133
+ const workflowRevisionId = stringValue(source.workflowRevisionId) ?? (sameWorkflow ? active?.correlation.workflowRevisionId : void 0);
134
+ const topologyHash = stringValue(source.topologyHash) ?? (sameWorkflow ? active?.correlation.topologyHash : void 0);
135
+ const nodeId = stringValue(source.nodeId) ?? (sameWorkflow ? active?.correlation.nodeId : void 0);
124
136
  return {
125
137
  runId,
126
138
  workflowId,
139
+ ...Object.fromEntries(
140
+ ["invocationId", "parentInvocationId", "branchId"].flatMap((key) => {
141
+ const value = stringValue(source[key]) ?? active?.correlation[key];
142
+ return value ? [[key, value]] : [];
143
+ })
144
+ ),
127
145
  ...sessionId ? { sessionId } : {},
128
146
  ...workflowRevisionId ? { workflowRevisionId } : {},
129
147
  ...topologyHash ? { topologyHash } : {},
@@ -150,7 +168,12 @@ var createEventMapper = (args) => {
150
168
  }
151
169
  } : {},
152
170
  type: input.type,
153
- payload: input.payload
171
+ payload: {
172
+ ...input.payload,
173
+ ...input.correlation.invocationId ? { invocationId: input.correlation.invocationId } : {},
174
+ ...input.correlation.parentInvocationId ? { parentInvocationId: input.correlation.parentInvocationId } : {},
175
+ ...input.correlation.branchId ? { branchId: input.correlation.branchId } : {}
176
+ }
154
177
  });
155
178
  const spanContext = (telemetry, attributes) => {
156
179
  const tags = [...args.tags ?? [], ...telemetry?.tags ?? []];
@@ -275,6 +298,7 @@ var createTraceAdapter = (args) => {
275
298
  ...endArgs?.attributes ?? {}
276
299
  };
277
300
  const telemetry = endArgs?.telemetry ?? startArgs.telemetry;
301
+ const durationMs = Date.now() - startedAt;
278
302
  args.enqueue(
279
303
  args.eventMapper.createEvent({
280
304
  type: "span.ended",
@@ -284,7 +308,7 @@ var createTraceAdapter = (args) => {
284
308
  payload: {
285
309
  name: startArgs.name,
286
310
  attributes: endAttributes,
287
- durationMs: Date.now() - startedAt,
311
+ durationMs,
288
312
  telemetry: args.eventMapper.telemetryPayload(telemetry),
289
313
  ...args.eventMapper.shouldCapture(
290
314
  endArgs?.telemetry?.captureContent ?? startArgs.telemetry?.captureContent ?? args.captureContent,
@@ -295,6 +319,13 @@ var createTraceAdapter = (args) => {
295
319
  })
296
320
  );
297
321
  if (startArgs.name !== "runReasonEngine") return;
322
+ const ttftMs = nonnegativeNumber(endAttributes.ttftMs);
323
+ const streamDurationMs = nonnegativeNumber(
324
+ endAttributes.streamDurationMs
325
+ );
326
+ const timeToLastTokenMs = nonnegativeNumber(
327
+ endAttributes.timeToLastTokenMs
328
+ );
298
329
  args.enqueue(
299
330
  args.eventMapper.createEvent({
300
331
  type: "generation.completed",
@@ -304,6 +335,15 @@ var createTraceAdapter = (args) => {
304
335
  payload: {
305
336
  provider: args.eventMapper.stringValue(attributes.providerId) ?? "unknown",
306
337
  model: args.eventMapper.stringValue(attributes.modelId) ?? "unknown",
338
+ durationMs,
339
+ ...ttftMs !== void 0 ? { ttftMs } : {},
340
+ ...streamDurationMs !== void 0 ? { streamDurationMs } : {},
341
+ ...timeToLastTokenMs !== void 0 ? {
342
+ postStreamDurationMs: Math.max(
343
+ 0,
344
+ durationMs - timeToLastTokenMs
345
+ )
346
+ } : {},
307
347
  ...endArgs?.usage ? { usage: endArgs.usage } : {},
308
348
  ...endArgs?.finishReason ? { finishReason: endArgs.finishReason } : {},
309
349
  ...endArgs?.warnings ? { warnings: endArgs.warnings } : {},
@@ -379,6 +419,7 @@ var createTraceAdapter = (args) => {
379
419
  }
380
420
  };
381
421
  };
422
+ var nonnegativeNumber = (value) => typeof value === "number" && Number.isFinite(value) && value >= 0 ? value : void 0;
382
423
 
383
424
  // src/adapter.ts
384
425
  var DEFAULT_FLUSH_INTERVAL_MS = 250;
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/index.ts","../src/adapter.ts","../src/delivery.ts","../src/event-mapper.ts","../src/topology.ts","../src/trace.ts"],"sourcesContent":["export { createKortyxTelemetryAdapter } from \"./adapter\";\nexport type {\n CreateKortyxTelemetryAdapterOptions,\n KortyxTelemetryAdapter,\n} from \"./types\";\n","import { randomUUID } from \"node:crypto\";\nimport type {\n EnsureWorkflowTopologyResponse,\n KortyxTelemetryEvent,\n} from \"@kortyx/hooks\";\nimport { createDelivery, TelemetryHttpError } from \"./delivery\";\nimport { createEventMapper } from \"./event-mapper\";\nimport { createTopologyResolver } from \"./topology\";\nimport { createTraceAdapter } from \"./trace\";\nimport type {\n CreateKortyxTelemetryAdapterOptions,\n KortyxTelemetryAdapter,\n} from \"./types\";\n\nexport type {\n CreateKortyxTelemetryAdapterOptions,\n KortyxTelemetryAdapter,\n} from \"./types\";\n\nconst DEFAULT_FLUSH_INTERVAL_MS = 250;\nconst DEFAULT_MAX_QUEUE_SIZE = 1_000;\n\nconst createId = (): string => {\n try {\n return randomUUID();\n } catch {\n return `${Date.now()}-${Math.random().toString(36).slice(2)}`;\n }\n};\n\nconst endpointFor = (endpoint: string, path: string): string =>\n `${endpoint.replace(/\\/$/, \"\")}${path}`;\n\n/**\n * Creates the optional Kortyx Studio HTTP adapter. Execution paths only enqueue\n * telemetry; delivery remains best-effort and cannot fail a workflow.\n */\nexport function createKortyxTelemetryAdapter(\n options: CreateKortyxTelemetryAdapterOptions,\n): KortyxTelemetryAdapter {\n const fetchImpl = options.fetch ?? globalThis.fetch;\n if (!fetchImpl) {\n throw new Error(\n \"createKortyxTelemetryAdapter requires a fetch implementation.\",\n );\n }\n\n const send = async (path: string, body: unknown): Promise<Response> => {\n const response = await fetchImpl(endpointFor(options.endpoint, path), {\n method: \"POST\",\n headers: {\n authorization: `Bearer ${options.apiKey}`,\n \"content-type\": \"application/json\",\n },\n body: JSON.stringify(body),\n });\n if (!response.ok) throw new TelemetryHttpError(response.status);\n return response;\n };\n\n const delivery = createDelivery({\n maxQueueSize: options.maxQueueSize ?? DEFAULT_MAX_QUEUE_SIZE,\n flushIntervalMs: options.flushIntervalMs ?? DEFAULT_FLUSH_INTERVAL_MS,\n send: async (events) => {\n await send(\"/v1/telemetry/events:batch\", { events });\n },\n });\n const eventMapper = createEventMapper({\n environment: options.environment,\n service: options.service,\n ...(options.metadata ? { metadata: options.metadata } : {}),\n ...(options.tags ? { tags: options.tags } : {}),\n createId,\n });\n const topology = createTopologyResolver({\n ensure: async (snapshot) => {\n const response = await send(\n \"/v1/telemetry/workflow-revisions:ensure\",\n snapshot,\n );\n return (await response.json()) as EnsureWorkflowTopologyResponse;\n },\n });\n const trace = createTraceAdapter({\n ...(options.captureContent\n ? { captureContent: options.captureContent }\n : {}),\n createId,\n enqueue: delivery.enqueue,\n eventMapper,\n });\n const emit = async (events: KortyxTelemetryEvent[]): Promise<void> => {\n for (const event of events) delivery.enqueue(event);\n };\n\n return {\n trace,\n reporter: {\n ensureWorkflowTopology: topology.ensureWorkflowTopology,\n emit,\n getWorkflowRevisionId: topology.getWorkflowRevisionId,\n },\n environment: options.environment,\n service: options.service,\n ...(options.captureContent\n ? { captureContent: options.captureContent }\n : {}),\n ...(options.metadata ? { metadata: options.metadata } : {}),\n ...(options.tags ? { tags: options.tags } : {}),\n flush: delivery.flush,\n getDroppedEventCount: delivery.getDroppedEventCount,\n getPermanentDeliveryFailureCount: delivery.getPermanentDeliveryFailureCount,\n };\n}\n","import type { KortyxTelemetryEvent } from \"@kortyx/hooks\";\n\nexport class TelemetryHttpError extends Error {\n constructor(readonly status: number) {\n super(`Kortyx telemetry request failed (${status}).`);\n }\n}\n\nexport const createDelivery = (args: {\n maxQueueSize: number;\n flushIntervalMs: number;\n send: (events: KortyxTelemetryEvent[]) => Promise<void>;\n}) => {\n const queue: KortyxTelemetryEvent[] = [];\n let dropped = 0;\n let permanentFailures = 0;\n let retryAttempt = 0;\n let timer: ReturnType<typeof setTimeout> | undefined;\n let inFlight: Promise<void> | undefined;\n const schedule = (delay = args.flushIntervalMs) => {\n if (timer || inFlight || queue.length === 0) return;\n timer = setTimeout(() => {\n timer = undefined;\n void flush();\n }, delay);\n if (typeof timer === \"object\" && \"unref\" in timer) timer.unref?.();\n };\n const flush = async (): Promise<void> => {\n if (inFlight) return inFlight;\n if (timer) {\n clearTimeout(timer);\n timer = undefined;\n }\n if (queue.length === 0) return;\n const events = queue.splice(0);\n inFlight = (async () => {\n let retry: number | undefined;\n try {\n await args.send(events);\n retryAttempt = 0;\n } catch (error) {\n const status =\n error instanceof TelemetryHttpError ? error.status : undefined;\n if (status !== undefined && status !== 429 && status < 500) {\n permanentFailures += events.length;\n return;\n }\n const overflow = Math.max(\n 0,\n queue.length + events.length - args.maxQueueSize,\n );\n if (overflow) {\n dropped += overflow;\n events.splice(0, overflow);\n }\n queue.unshift(...events);\n retryAttempt += 1;\n const backoff = Math.min(30_000, 250 * 2 ** (retryAttempt - 1));\n retry = Math.floor(backoff * (0.5 + Math.random() * 0.5));\n } finally {\n inFlight = undefined;\n if (retry !== undefined) schedule(retry);\n }\n })();\n return inFlight;\n };\n return {\n enqueue: (event: KortyxTelemetryEvent) => {\n if (queue.length >= args.maxQueueSize) {\n queue.shift();\n dropped += 1;\n }\n queue.push(event);\n schedule();\n },\n flush,\n getDroppedEventCount: () => dropped,\n getPermanentDeliveryFailureCount: () => permanentFailures,\n };\n};\n","import type {\n KortyxTelemetryConfig,\n KortyxTelemetryEvent,\n KortyxTelemetryEventType,\n ReasonTraceAttributes,\n ReasonTraceSpanStartArgs,\n} from \"@kortyx/hooks\";\nimport type { ActiveSpan, SpanContext } from \"./types\";\n\nconst stringValue = (value: unknown): string | undefined =>\n typeof value === \"string\" && value.length > 0 ? value : undefined;\n\nconst shouldCapture = (\n value: KortyxTelemetryConfig[\"captureContent\"] | undefined,\n side: \"input\" | \"output\",\n): boolean => {\n if (value === true) return true;\n return Boolean(value && typeof value === \"object\" && value[side]);\n};\n\nconst asErrorPayload = (error: unknown): Record<string, unknown> => ({\n message: error instanceof Error ? error.message : String(error),\n ...(error instanceof Error && error.name ? { name: error.name } : {}),\n});\n\nconst correlationFrom = (\n attributes: ReasonTraceAttributes | undefined,\n active: ActiveSpan | undefined,\n): KortyxTelemetryEvent[\"correlation\"] | undefined => {\n const source = attributes ?? {};\n const runId = stringValue(source.runId) ?? active?.correlation.runId;\n const workflowId =\n stringValue(source.workflowId) ?? active?.correlation.workflowId;\n if (!runId || !workflowId) return undefined;\n\n const sessionId =\n stringValue(source.sessionId) ?? active?.correlation.sessionId;\n const workflowRevisionId =\n stringValue(source.workflowRevisionId) ??\n active?.correlation.workflowRevisionId;\n const topologyHash =\n stringValue(source.topologyHash) ?? active?.correlation.topologyHash;\n const nodeId = stringValue(source.nodeId) ?? active?.correlation.nodeId;\n return {\n runId,\n workflowId,\n ...(sessionId ? { sessionId } : {}),\n ...(workflowRevisionId ? { workflowRevisionId } : {}),\n ...(topologyHash ? { topologyHash } : {}),\n ...(nodeId ? { nodeId } : {}),\n };\n};\n\nexport const createEventMapper = (args: {\n environment: string;\n service: KortyxTelemetryEvent[\"service\"];\n metadata?: Record<string, unknown> | undefined;\n tags?: string[] | undefined;\n createId: () => string;\n}) => {\n const createEvent = (input: {\n type: KortyxTelemetryEventType;\n correlation: KortyxTelemetryEvent[\"correlation\"];\n span?: SpanContext | undefined;\n parentSpanId?: string | undefined;\n payload: Record<string, unknown>;\n context?: KortyxTelemetryEvent[\"context\"] | undefined;\n }): KortyxTelemetryEvent => ({\n schemaVersion: 1,\n eventId: args.createId(),\n occurredAt: new Date().toISOString(),\n environment: args.environment,\n service: args.service,\n correlation: {\n ...input.correlation,\n ...(input.span\n ? { traceId: input.span.traceId, spanId: input.span.spanId }\n : {}),\n ...(input.parentSpanId ? { parentSpanId: input.parentSpanId } : {}),\n },\n ...(input.context || args.metadata || args.tags\n ? {\n context: {\n ...(args.tags ? { tags: args.tags } : {}),\n ...(args.metadata ? { metadata: args.metadata } : {}),\n ...(input.context ?? {}),\n },\n }\n : {}),\n type: input.type,\n payload: input.payload,\n });\n\n const spanContext = (\n telemetry: ReasonTraceSpanStartArgs[\"telemetry\"] | undefined,\n attributes: ReasonTraceAttributes,\n ): KortyxTelemetryEvent[\"context\"] | undefined => {\n const tags = [...(args.tags ?? []), ...(telemetry?.tags ?? [])];\n const metadata = {\n ...(args.metadata ?? {}),\n ...(telemetry?.metadata ?? {}),\n };\n const userId = stringValue(attributes.userId);\n const tenantId = stringValue(attributes.tenantId);\n return userId || tenantId || tags.length || Object.keys(metadata).length\n ? {\n ...(userId ? { userId } : {}),\n ...(tenantId ? { tenantId } : {}),\n ...(tags.length ? { tags } : {}),\n ...(Object.keys(metadata).length ? { metadata } : {}),\n }\n : undefined;\n };\n\n const telemetryPayload = (\n telemetry: ReasonTraceSpanStartArgs[\"telemetry\"] | undefined,\n ): Record<string, unknown> => ({\n ...(telemetry?.operation ? { operation: telemetry.operation } : {}),\n ...(telemetry?.tags?.length ? { tags: telemetry.tags } : {}),\n ...(telemetry?.metadata ? { metadata: telemetry.metadata } : {}),\n ...(telemetry?.prompt\n ? {\n prompt: {\n ...(telemetry.prompt.name ? { name: telemetry.prompt.name } : {}),\n ...(telemetry.prompt.version !== undefined\n ? { version: telemetry.prompt.version }\n : {}),\n ...(telemetry.prompt.type ? { type: telemetry.prompt.type } : {}),\n ...(telemetry.prompt.source\n ? { source: telemetry.prompt.source }\n : {}),\n },\n }\n : {}),\n });\n\n return {\n asErrorPayload,\n correlationFrom,\n createEvent,\n shouldCapture,\n spanContext,\n stringValue,\n telemetryPayload,\n };\n};\n","import type {\n EnsureWorkflowTopologyRequest,\n EnsureWorkflowTopologyResponse,\n} from \"@kortyx/hooks\";\n\ntype TopologyKey = {\n environment: string;\n workflowId: string;\n topologyHash: string;\n};\n\nconst keyFor = ({ environment, workflowId, topologyHash }: TopologyKey) =>\n `${environment}:${workflowId}:${topologyHash}`;\n\n/** Caches successful topology ensures and coalesces concurrent requests. */\nexport const createTopologyResolver = (args: {\n ensure: (\n snapshot: EnsureWorkflowTopologyRequest,\n ) => Promise<EnsureWorkflowTopologyResponse>;\n}) => {\n const revisions = new Map<string, string>();\n const pending = new Map<string, Promise<EnsureWorkflowTopologyResponse>>();\n\n const ensureWorkflowTopology = (\n snapshot: EnsureWorkflowTopologyRequest,\n ): Promise<EnsureWorkflowTopologyResponse> => {\n const key = keyFor({\n environment: snapshot.environment,\n workflowId: snapshot.workflow.id,\n topologyHash: snapshot.workflow.topologyHash,\n });\n const revision = revisions.get(key);\n if (revision) {\n return Promise.resolve({ workflowRevisionId: revision, created: false });\n }\n\n const existing = pending.get(key);\n if (existing) return existing;\n\n const request = args\n .ensure(snapshot)\n .then((result) => {\n if (!result.workflowRevisionId) {\n throw new Error(\n \"Telemetry API returned an invalid workflow revision.\",\n );\n }\n revisions.set(key, result.workflowRevisionId);\n return result;\n })\n .finally(() => {\n pending.delete(key);\n });\n pending.set(key, request);\n return request;\n };\n\n return {\n ensureWorkflowTopology,\n getWorkflowRevisionId: (args: TopologyKey) => revisions.get(keyFor(args)),\n };\n};\n","import { AsyncLocalStorage } from \"node:async_hooks\";\nimport type {\n KortyxTelemetryConfig,\n KortyxTelemetryEvent,\n ReasonTraceAdapter,\n ReasonTraceSpan,\n ReasonTraceSpanEndArgs,\n ReasonTraceSpanStartArgs,\n} from \"@kortyx/hooks\";\nimport type { createEventMapper } from \"./event-mapper\";\nimport type { ActiveSpan, SpanContext } from \"./types\";\n\n/** Maps generic SDK trace calls to Kortyx Studio's span and generation facts. */\nexport const createTraceAdapter = (args: {\n captureContent?: KortyxTelemetryConfig[\"captureContent\"] | undefined;\n createId: () => string;\n enqueue: (event: KortyxTelemetryEvent) => void;\n eventMapper: ReturnType<typeof createEventMapper>;\n}): ReasonTraceAdapter => {\n const activeSpans = new AsyncLocalStorage<ActiveSpan>();\n\n const createSpan = (\n startArgs: ReasonTraceSpanStartArgs,\n ): { span: ReasonTraceSpan; active?: ActiveSpan | undefined } => {\n const parent = activeSpans.getStore();\n const span: SpanContext = {\n traceId: parent?.traceId ?? args.createId(),\n spanId: args.createId(),\n };\n const attributes = { ...(startArgs.attributes ?? {}) };\n const currentAttributes = { ...attributes };\n const correlation = args.eventMapper.correlationFrom(attributes, parent);\n const startedAt = Date.now();\n\n if (correlation) {\n args.enqueue(\n args.eventMapper.createEvent({\n type: \"span.started\",\n correlation,\n span,\n ...(parent ? { parentSpanId: parent.spanId } : {}),\n payload: {\n name: startArgs.name,\n attributes: currentAttributes,\n telemetry: args.eventMapper.telemetryPayload(startArgs.telemetry),\n ...(args.eventMapper.shouldCapture(\n startArgs.telemetry?.captureContent ?? args.captureContent,\n \"input\",\n )\n ? { input: startArgs.telemetry?.input }\n : {}),\n },\n context: args.eventMapper.spanContext(\n startArgs.telemetry,\n currentAttributes,\n ),\n }),\n );\n }\n\n let ended = false;\n const end = (endArgs?: ReasonTraceSpanEndArgs): void => {\n if (ended) return;\n ended = true;\n if (!correlation) return;\n\n const endAttributes = {\n ...currentAttributes,\n ...(endArgs?.attributes ?? {}),\n };\n const telemetry = endArgs?.telemetry ?? startArgs.telemetry;\n args.enqueue(\n args.eventMapper.createEvent({\n type: \"span.ended\",\n correlation,\n span,\n ...(parent ? { parentSpanId: parent.spanId } : {}),\n payload: {\n name: startArgs.name,\n attributes: endAttributes,\n durationMs: Date.now() - startedAt,\n telemetry: args.eventMapper.telemetryPayload(telemetry),\n ...(args.eventMapper.shouldCapture(\n endArgs?.telemetry?.captureContent ??\n startArgs.telemetry?.captureContent ??\n args.captureContent,\n \"output\",\n )\n ? { output: endArgs?.telemetry?.output }\n : {}),\n },\n context: args.eventMapper.spanContext(telemetry, endAttributes),\n }),\n );\n\n if (startArgs.name !== \"runReasonEngine\") return;\n args.enqueue(\n args.eventMapper.createEvent({\n type: \"generation.completed\",\n correlation,\n span,\n ...(parent ? { parentSpanId: parent.spanId } : {}),\n payload: {\n provider:\n args.eventMapper.stringValue(attributes.providerId) ?? \"unknown\",\n model:\n args.eventMapper.stringValue(attributes.modelId) ?? \"unknown\",\n ...(endArgs?.usage ? { usage: endArgs.usage } : {}),\n ...(endArgs?.finishReason\n ? { finishReason: endArgs.finishReason }\n : {}),\n ...(endArgs?.warnings ? { warnings: endArgs.warnings } : {}),\n ...(endArgs?.providerMetadata\n ? { providerMetadata: endArgs.providerMetadata }\n : {}),\n },\n context: args.eventMapper.spanContext(telemetry, currentAttributes),\n }),\n );\n };\n\n const traceSpan: ReasonTraceSpan = {\n setAttributes: (nextAttributes) => {\n Object.assign(currentAttributes, nextAttributes);\n },\n addEvent: (name, eventAttributes = {}) => {\n if (!correlation) return;\n const type =\n name === \"useReason.tool-call.start\"\n ? \"tool.started\"\n : name === \"useReason.tool-call.complete\"\n ? \"tool.completed\"\n : name === \"useReason.tool-call.error\"\n ? \"tool.failed\"\n : undefined;\n if (!type) return;\n args.enqueue(\n args.eventMapper.createEvent({\n type,\n correlation,\n span,\n ...(parent ? { parentSpanId: parent.spanId } : {}),\n payload: eventAttributes,\n }),\n );\n },\n end,\n fail: (error, endArgs) => {\n if (ended) return;\n if (correlation) {\n args.enqueue(\n args.eventMapper.createEvent({\n type: \"span.failed\",\n correlation,\n span,\n ...(parent ? { parentSpanId: parent.spanId } : {}),\n payload: {\n name: startArgs.name,\n error: args.eventMapper.asErrorPayload(error),\n durationMs: Date.now() - startedAt,\n },\n }),\n );\n }\n end(endArgs);\n },\n };\n\n return {\n span: traceSpan,\n ...(correlation ? { active: { ...span, correlation } } : {}),\n };\n };\n\n return {\n startSpan: (startArgs) => createSpan(startArgs).span,\n withSpan: async (startArgs, fn) => {\n const created = createSpan(startArgs);\n const run = async (): Promise<Awaited<ReturnType<typeof fn>>> => {\n try {\n const result = await fn(created.span);\n created.span.end?.();\n return result;\n } catch (error) {\n created.span.fail?.(error);\n throw error;\n }\n };\n return created.active ? activeSpans.run(created.active, run) : run();\n },\n getActiveContext: () => {\n const active = activeSpans.getStore();\n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,MAAM,QAAQ,KAAK,IAAI,CAAC;AAAA,IAC7C;AAAA,EACF,CAAC;AACD,QAAM,WAAW,uBAAuB;AAAA,IACtC,QAAQ,OAAO,aAAa;AAC1B,YAAM,WAAW,MAAM;AAAA,QACrB;AAAA,QACA;AAAA,MACF;AACA,aAAQ,MAAM,SAAS,KAAK;AAAA,IAC9B;AAAA,EACF,CAAC;AACD,QAAM,QAAQ,mBAAmB;AAAA,IAC/B,GAAI,QAAQ,iBACR,EAAE,gBAAgB,QAAQ,eAAe,IACzC,CAAC;AAAA,IACL;AAAA,IACA,SAAS,SAAS;AAAA,IAClB;AAAA,EACF,CAAC;AACD,QAAM,OAAO,OAAO,WAAkD;AACpE,eAAW,SAAS,OAAQ,UAAS,QAAQ,KAAK;AAAA,EACpD;AAEA,SAAO;AAAA,IACL;AAAA,IACA,UAAU;AAAA,MACR,wBAAwB,SAAS;AAAA,MACjC;AAAA,MACA,uBAAuB,SAAS;AAAA,IAClC;AAAA,IACA,aAAa,QAAQ;AAAA,IACrB,SAAS,QAAQ;AAAA,IACjB,GAAI,QAAQ,iBACR,EAAE,gBAAgB,QAAQ,eAAe,IACzC,CAAC;AAAA,IACL,GAAI,QAAQ,WAAW,EAAE,UAAU,QAAQ,SAAS,IAAI,CAAC;AAAA,IACzD,GAAI,QAAQ,OAAO,EAAE,MAAM,QAAQ,KAAK,IAAI,CAAC;AAAA,IAC7C,OAAO,SAAS;AAAA,IAChB,sBAAsB,SAAS;AAAA,IAC/B,kCAAkC,SAAS;AAAA,EAC7C;AACF;","names":["args"]}
1
+ {"version":3,"sources":["../src/index.ts","../src/adapter.ts","../src/delivery.ts","../src/event-mapper.ts","../src/topology.ts","../src/trace.ts"],"sourcesContent":["export { createKortyxTelemetryAdapter } from \"./adapter\";\nexport type {\n CreateKortyxTelemetryAdapterOptions,\n KortyxTelemetryAdapter,\n} from \"./types\";\n","import { randomUUID } from \"node:crypto\";\nimport type {\n EnsureWorkflowTopologyResponse,\n KortyxTelemetryEvent,\n} from \"@kortyx/hooks\";\nimport { createDelivery, TelemetryHttpError } from \"./delivery\";\nimport { createEventMapper } from \"./event-mapper\";\nimport { createTopologyResolver } from \"./topology\";\nimport { createTraceAdapter } from \"./trace\";\nimport type {\n CreateKortyxTelemetryAdapterOptions,\n KortyxTelemetryAdapter,\n} from \"./types\";\n\nexport type {\n CreateKortyxTelemetryAdapterOptions,\n KortyxTelemetryAdapter,\n} from \"./types\";\n\nconst DEFAULT_FLUSH_INTERVAL_MS = 250;\nconst DEFAULT_MAX_QUEUE_SIZE = 1_000;\n\nconst createId = (): string => {\n try {\n return randomUUID();\n } catch {\n return `${Date.now()}-${Math.random().toString(36).slice(2)}`;\n }\n};\n\nconst endpointFor = (endpoint: string, path: string): string =>\n `${endpoint.replace(/\\/$/, \"\")}${path}`;\n\n/**\n * Creates the optional Kortyx Studio HTTP adapter. Execution paths only enqueue\n * telemetry; delivery remains best-effort and cannot fail a workflow.\n */\nexport function createKortyxTelemetryAdapter(\n options: CreateKortyxTelemetryAdapterOptions,\n): KortyxTelemetryAdapter {\n const fetchImpl = options.fetch ?? globalThis.fetch;\n if (!fetchImpl) {\n throw new Error(\n \"createKortyxTelemetryAdapter requires a fetch implementation.\",\n );\n }\n\n const send = async (path: string, body: unknown): Promise<Response> => {\n const response = await fetchImpl(endpointFor(options.endpoint, path), {\n method: \"POST\",\n headers: {\n authorization: `Bearer ${options.apiKey}`,\n \"content-type\": \"application/json\",\n },\n body: JSON.stringify(body),\n });\n if (!response.ok) throw new TelemetryHttpError(response.status);\n return response;\n };\n\n const delivery = createDelivery({\n maxQueueSize: options.maxQueueSize ?? DEFAULT_MAX_QUEUE_SIZE,\n flushIntervalMs: options.flushIntervalMs ?? DEFAULT_FLUSH_INTERVAL_MS,\n send: async (events) => {\n await send(\"/v1/telemetry/events:batch\", { events });\n },\n });\n const eventMapper = createEventMapper({\n environment: options.environment,\n service: options.service,\n ...(options.metadata ? { metadata: options.metadata } : {}),\n ...(options.tags ? { tags: options.tags } : {}),\n createId,\n });\n const topology = createTopologyResolver({\n ensure: async (snapshot) => {\n const response = await send(\n \"/v1/telemetry/workflow-revisions:ensure\",\n snapshot,\n );\n return (await response.json()) as EnsureWorkflowTopologyResponse;\n },\n });\n const trace = createTraceAdapter({\n ...(options.captureContent\n ? { captureContent: options.captureContent }\n : {}),\n createId,\n enqueue: delivery.enqueue,\n eventMapper,\n });\n const emit = async (events: KortyxTelemetryEvent[]): Promise<void> => {\n for (const event of events) delivery.enqueue(event);\n };\n\n return {\n trace,\n reporter: {\n ensureWorkflowTopology: topology.ensureWorkflowTopology,\n emit,\n getWorkflowRevisionId: topology.getWorkflowRevisionId,\n },\n environment: options.environment,\n service: options.service,\n ...(options.captureContent\n ? { captureContent: options.captureContent }\n : {}),\n ...(options.metadata ? { metadata: options.metadata } : {}),\n ...(options.tags ? { tags: options.tags } : {}),\n flush: delivery.flush,\n getDroppedEventCount: delivery.getDroppedEventCount,\n getPermanentDeliveryFailureCount: delivery.getPermanentDeliveryFailureCount,\n };\n}\n","import type { KortyxTelemetryEvent } from \"@kortyx/hooks\";\n\nexport class TelemetryHttpError extends Error {\n constructor(readonly status: number) {\n super(`Kortyx telemetry request failed (${status}).`);\n }\n}\n\nexport const createDelivery = (args: {\n maxQueueSize: number;\n flushIntervalMs: number;\n send: (events: KortyxTelemetryEvent[]) => Promise<void>;\n}) => {\n const queue: KortyxTelemetryEvent[] = [];\n let dropped = 0;\n let permanentFailures = 0;\n let retryAttempt = 0;\n let timer: ReturnType<typeof setTimeout> | undefined;\n let inFlight: Promise<{ retryDelay: number | null }> | undefined;\n const schedule = (delay = args.flushIntervalMs) => {\n if (timer || inFlight || queue.length === 0) return;\n timer = setTimeout(() => {\n timer = undefined;\n void flush();\n }, delay);\n if (typeof timer === \"object\" && \"unref\" in timer) timer.unref?.();\n };\n const flush = async (): Promise<void> => {\n while (true) {\n if (inFlight) {\n const result = await inFlight;\n if (result.retryDelay !== null) return;\n continue;\n }\n if (timer) {\n clearTimeout(timer);\n timer = undefined;\n }\n if (queue.length === 0) return;\n const events = queue.splice(0);\n const current = (async (): Promise<{ retryDelay: number | null }> => {\n try {\n await args.send(events);\n retryAttempt = 0;\n return { retryDelay: null };\n } catch (error) {\n const status =\n error instanceof TelemetryHttpError ? error.status : undefined;\n if (status !== undefined && status !== 429 && status < 500) {\n permanentFailures += events.length;\n return { retryDelay: null };\n }\n const overflow = Math.max(\n 0,\n queue.length + events.length - args.maxQueueSize,\n );\n if (overflow) {\n dropped += overflow;\n events.splice(0, overflow);\n }\n queue.unshift(...events);\n retryAttempt += 1;\n const backoff = Math.min(30_000, 250 * 2 ** (retryAttempt - 1));\n return {\n retryDelay: Math.floor(backoff * (0.5 + Math.random() * 0.5)),\n };\n }\n })();\n inFlight = current;\n const result = await current;\n if (inFlight === current) inFlight = undefined;\n if (result.retryDelay !== null) {\n schedule(result.retryDelay);\n return;\n }\n }\n };\n return {\n enqueue: (event: KortyxTelemetryEvent) => {\n if (queue.length >= args.maxQueueSize) {\n queue.shift();\n dropped += 1;\n }\n queue.push(event);\n schedule();\n },\n flush,\n getDroppedEventCount: () => dropped,\n getPermanentDeliveryFailureCount: () => permanentFailures,\n };\n};\n","import type {\n KortyxTelemetryConfig,\n KortyxTelemetryEvent,\n KortyxTelemetryEventType,\n ReasonTraceAttributes,\n ReasonTraceSpanStartArgs,\n} from \"@kortyx/hooks\";\nimport type { ActiveSpan, SpanContext } from \"./types\";\n\nconst stringValue = (value: unknown): string | undefined =>\n typeof value === \"string\" && value.length > 0 ? value : undefined;\n\nconst shouldCapture = (\n value: KortyxTelemetryConfig[\"captureContent\"] | undefined,\n side: \"input\" | \"output\",\n): boolean => {\n if (value === true) return true;\n return Boolean(value && typeof value === \"object\" && value[side]);\n};\n\nconst asErrorPayload = (error: unknown): Record<string, unknown> => ({\n message: error instanceof Error ? error.message : String(error),\n ...(error instanceof Error && error.name ? { name: error.name } : {}),\n});\n\nconst correlationFrom = (\n attributes: ReasonTraceAttributes | undefined,\n active: ActiveSpan | undefined,\n): KortyxTelemetryEvent[\"correlation\"] | undefined => {\n const source = attributes ?? {};\n const runId = stringValue(source.runId) ?? active?.correlation.runId;\n const workflowId =\n stringValue(source.workflowId) ?? active?.correlation.workflowId;\n if (!runId || !workflowId) return undefined;\n\n const sameWorkflow = workflowId === active?.correlation.workflowId;\n const sessionId =\n stringValue(source.sessionId) ?? active?.correlation.sessionId;\n const workflowRevisionId =\n stringValue(source.workflowRevisionId) ??\n (sameWorkflow ? active?.correlation.workflowRevisionId : undefined);\n const topologyHash =\n stringValue(source.topologyHash) ??\n (sameWorkflow ? active?.correlation.topologyHash : undefined);\n const nodeId =\n stringValue(source.nodeId) ??\n (sameWorkflow ? active?.correlation.nodeId : undefined);\n return {\n runId,\n workflowId,\n ...Object.fromEntries(\n [\"invocationId\", \"parentInvocationId\", \"branchId\"].flatMap((key) => {\n const value =\n stringValue(source[key]) ??\n active?.correlation[key as \"invocationId\"];\n return value ? [[key, value]] : [];\n }),\n ),\n ...(sessionId ? { sessionId } : {}),\n ...(workflowRevisionId ? { workflowRevisionId } : {}),\n ...(topologyHash ? { topologyHash } : {}),\n ...(nodeId ? { nodeId } : {}),\n };\n};\n\nexport const createEventMapper = (args: {\n environment: string;\n service: KortyxTelemetryEvent[\"service\"];\n metadata?: Record<string, unknown> | undefined;\n tags?: string[] | undefined;\n createId: () => string;\n}) => {\n const createEvent = (input: {\n type: KortyxTelemetryEventType;\n correlation: KortyxTelemetryEvent[\"correlation\"];\n span?: SpanContext | undefined;\n parentSpanId?: string | undefined;\n payload: Record<string, unknown>;\n context?: KortyxTelemetryEvent[\"context\"] | undefined;\n }): KortyxTelemetryEvent => ({\n schemaVersion: 1,\n eventId: args.createId(),\n occurredAt: new Date().toISOString(),\n environment: args.environment,\n service: args.service,\n correlation: {\n ...input.correlation,\n ...(input.span\n ? { traceId: input.span.traceId, spanId: input.span.spanId }\n : {}),\n ...(input.parentSpanId ? { parentSpanId: input.parentSpanId } : {}),\n },\n ...(input.context || args.metadata || args.tags\n ? {\n context: {\n ...(args.tags ? { tags: args.tags } : {}),\n ...(args.metadata ? { metadata: args.metadata } : {}),\n ...(input.context ?? {}),\n },\n }\n : {}),\n type: input.type,\n payload: {\n ...input.payload,\n ...(input.correlation.invocationId\n ? { invocationId: input.correlation.invocationId }\n : {}),\n ...(input.correlation.parentInvocationId\n ? { parentInvocationId: input.correlation.parentInvocationId }\n : {}),\n ...(input.correlation.branchId\n ? { branchId: input.correlation.branchId }\n : {}),\n },\n });\n\n const spanContext = (\n telemetry: ReasonTraceSpanStartArgs[\"telemetry\"] | undefined,\n attributes: ReasonTraceAttributes,\n ): KortyxTelemetryEvent[\"context\"] | undefined => {\n const tags = [...(args.tags ?? []), ...(telemetry?.tags ?? [])];\n const metadata = {\n ...(args.metadata ?? {}),\n ...(telemetry?.metadata ?? {}),\n };\n const userId = stringValue(attributes.userId);\n const tenantId = stringValue(attributes.tenantId);\n return userId || tenantId || tags.length || Object.keys(metadata).length\n ? {\n ...(userId ? { userId } : {}),\n ...(tenantId ? { tenantId } : {}),\n ...(tags.length ? { tags } : {}),\n ...(Object.keys(metadata).length ? { metadata } : {}),\n }\n : undefined;\n };\n\n const telemetryPayload = (\n telemetry: ReasonTraceSpanStartArgs[\"telemetry\"] | undefined,\n ): Record<string, unknown> => ({\n ...(telemetry?.operation ? { operation: telemetry.operation } : {}),\n ...(telemetry?.tags?.length ? { tags: telemetry.tags } : {}),\n ...(telemetry?.metadata ? { metadata: telemetry.metadata } : {}),\n ...(telemetry?.prompt\n ? {\n prompt: {\n ...(telemetry.prompt.name ? { name: telemetry.prompt.name } : {}),\n ...(telemetry.prompt.version !== undefined\n ? { version: telemetry.prompt.version }\n : {}),\n ...(telemetry.prompt.type ? { type: telemetry.prompt.type } : {}),\n ...(telemetry.prompt.source\n ? { source: telemetry.prompt.source }\n : {}),\n },\n }\n : {}),\n });\n\n return {\n asErrorPayload,\n correlationFrom,\n createEvent,\n shouldCapture,\n spanContext,\n stringValue,\n telemetryPayload,\n };\n};\n","import type {\n EnsureWorkflowTopologyRequest,\n EnsureWorkflowTopologyResponse,\n} from \"@kortyx/hooks\";\n\ntype TopologyKey = {\n environment: string;\n workflowId: string;\n topologyHash: string;\n};\n\nconst keyFor = ({ environment, workflowId, topologyHash }: TopologyKey) =>\n `${environment}:${workflowId}:${topologyHash}`;\n\n/** Caches successful topology ensures and coalesces concurrent requests. */\nexport const createTopologyResolver = (args: {\n ensure: (\n snapshot: EnsureWorkflowTopologyRequest,\n ) => Promise<EnsureWorkflowTopologyResponse>;\n}) => {\n const revisions = new Map<string, string>();\n const pending = new Map<string, Promise<EnsureWorkflowTopologyResponse>>();\n\n const ensureWorkflowTopology = (\n snapshot: EnsureWorkflowTopologyRequest,\n ): Promise<EnsureWorkflowTopologyResponse> => {\n const key = keyFor({\n environment: snapshot.environment,\n workflowId: snapshot.workflow.id,\n topologyHash: snapshot.workflow.topologyHash,\n });\n const revision = revisions.get(key);\n if (revision) {\n return Promise.resolve({ workflowRevisionId: revision, created: false });\n }\n\n const existing = pending.get(key);\n if (existing) return existing;\n\n const request = args\n .ensure(snapshot)\n .then((result) => {\n if (!result.workflowRevisionId) {\n throw new Error(\n \"Telemetry API returned an invalid workflow revision.\",\n );\n }\n revisions.set(key, result.workflowRevisionId);\n return result;\n })\n .finally(() => {\n pending.delete(key);\n });\n pending.set(key, request);\n return request;\n };\n\n return {\n ensureWorkflowTopology,\n getWorkflowRevisionId: (args: TopologyKey) => revisions.get(keyFor(args)),\n };\n};\n","import { AsyncLocalStorage } from \"node:async_hooks\";\nimport type {\n KortyxTelemetryConfig,\n KortyxTelemetryEvent,\n ReasonTraceAdapter,\n ReasonTraceSpan,\n ReasonTraceSpanEndArgs,\n ReasonTraceSpanStartArgs,\n} from \"@kortyx/hooks\";\nimport type { createEventMapper } from \"./event-mapper\";\nimport type { ActiveSpan, SpanContext } from \"./types\";\n\n/** Maps generic SDK trace calls to Kortyx Studio's span and generation facts. */\nexport const createTraceAdapter = (args: {\n captureContent?: KortyxTelemetryConfig[\"captureContent\"] | undefined;\n createId: () => string;\n enqueue: (event: KortyxTelemetryEvent) => void;\n eventMapper: ReturnType<typeof createEventMapper>;\n}): ReasonTraceAdapter => {\n const activeSpans = new AsyncLocalStorage<ActiveSpan>();\n\n const createSpan = (\n startArgs: ReasonTraceSpanStartArgs,\n ): { span: ReasonTraceSpan; active?: ActiveSpan | undefined } => {\n const parent = activeSpans.getStore();\n const span: SpanContext = {\n traceId: parent?.traceId ?? args.createId(),\n spanId: args.createId(),\n };\n const attributes = { ...(startArgs.attributes ?? {}) };\n const currentAttributes = { ...attributes };\n const correlation = args.eventMapper.correlationFrom(attributes, parent);\n const startedAt = Date.now();\n\n if (correlation) {\n args.enqueue(\n args.eventMapper.createEvent({\n type: \"span.started\",\n correlation,\n span,\n ...(parent ? { parentSpanId: parent.spanId } : {}),\n payload: {\n name: startArgs.name,\n attributes: currentAttributes,\n telemetry: args.eventMapper.telemetryPayload(startArgs.telemetry),\n ...(args.eventMapper.shouldCapture(\n startArgs.telemetry?.captureContent ?? args.captureContent,\n \"input\",\n )\n ? { input: startArgs.telemetry?.input }\n : {}),\n },\n context: args.eventMapper.spanContext(\n startArgs.telemetry,\n currentAttributes,\n ),\n }),\n );\n }\n\n let ended = false;\n const end = (endArgs?: ReasonTraceSpanEndArgs): void => {\n if (ended) return;\n ended = true;\n if (!correlation) return;\n\n const endAttributes = {\n ...currentAttributes,\n ...(endArgs?.attributes ?? {}),\n };\n const telemetry = endArgs?.telemetry ?? startArgs.telemetry;\n const durationMs = Date.now() - startedAt;\n args.enqueue(\n args.eventMapper.createEvent({\n type: \"span.ended\",\n correlation,\n span,\n ...(parent ? { parentSpanId: parent.spanId } : {}),\n payload: {\n name: startArgs.name,\n attributes: endAttributes,\n durationMs,\n telemetry: args.eventMapper.telemetryPayload(telemetry),\n ...(args.eventMapper.shouldCapture(\n endArgs?.telemetry?.captureContent ??\n startArgs.telemetry?.captureContent ??\n args.captureContent,\n \"output\",\n )\n ? { output: endArgs?.telemetry?.output }\n : {}),\n },\n context: args.eventMapper.spanContext(telemetry, endAttributes),\n }),\n );\n\n if (startArgs.name !== \"runReasonEngine\") return;\n const ttftMs = nonnegativeNumber(endAttributes.ttftMs);\n const streamDurationMs = nonnegativeNumber(\n endAttributes.streamDurationMs,\n );\n const timeToLastTokenMs = nonnegativeNumber(\n endAttributes.timeToLastTokenMs,\n );\n args.enqueue(\n args.eventMapper.createEvent({\n type: \"generation.completed\",\n correlation,\n span,\n ...(parent ? { parentSpanId: parent.spanId } : {}),\n payload: {\n provider:\n args.eventMapper.stringValue(attributes.providerId) ?? \"unknown\",\n model:\n args.eventMapper.stringValue(attributes.modelId) ?? \"unknown\",\n durationMs,\n ...(ttftMs !== undefined ? { ttftMs } : {}),\n ...(streamDurationMs !== undefined ? { streamDurationMs } : {}),\n ...(timeToLastTokenMs !== undefined\n ? {\n postStreamDurationMs: Math.max(\n 0,\n durationMs - timeToLastTokenMs,\n ),\n }\n : {}),\n ...(endArgs?.usage ? { usage: endArgs.usage } : {}),\n ...(endArgs?.finishReason\n ? { finishReason: endArgs.finishReason }\n : {}),\n ...(endArgs?.warnings ? { warnings: endArgs.warnings } : {}),\n ...(endArgs?.providerMetadata\n ? { providerMetadata: endArgs.providerMetadata }\n : {}),\n },\n context: args.eventMapper.spanContext(telemetry, currentAttributes),\n }),\n );\n };\n\n const traceSpan: ReasonTraceSpan = {\n setAttributes: (nextAttributes) => {\n Object.assign(currentAttributes, nextAttributes);\n },\n addEvent: (name, eventAttributes = {}) => {\n if (!correlation) return;\n const type =\n name === \"useReason.tool-call.start\"\n ? \"tool.started\"\n : name === \"useReason.tool-call.complete\"\n ? \"tool.completed\"\n : name === \"useReason.tool-call.error\"\n ? \"tool.failed\"\n : undefined;\n if (!type) return;\n args.enqueue(\n args.eventMapper.createEvent({\n type,\n correlation,\n span,\n ...(parent ? { parentSpanId: parent.spanId } : {}),\n payload: eventAttributes,\n }),\n );\n },\n end,\n fail: (error, endArgs) => {\n if (ended) return;\n if (correlation) {\n args.enqueue(\n args.eventMapper.createEvent({\n type: \"span.failed\",\n correlation,\n span,\n ...(parent ? { parentSpanId: parent.spanId } : {}),\n payload: {\n name: startArgs.name,\n error: args.eventMapper.asErrorPayload(error),\n durationMs: Date.now() - startedAt,\n },\n }),\n );\n }\n end(endArgs);\n },\n };\n\n return {\n span: traceSpan,\n ...(correlation ? { active: { ...span, correlation } } : {}),\n };\n };\n\n return {\n startSpan: (startArgs) => createSpan(startArgs).span,\n withSpan: async (startArgs, fn) => {\n const created = createSpan(startArgs);\n const run = async (): Promise<Awaited<ReturnType<typeof fn>>> => {\n try {\n const result = await fn(created.span);\n created.span.end?.();\n return result;\n } catch (error) {\n created.span.fail?.(error);\n throw error;\n }\n };\n return created.active ? activeSpans.run(created.active, run) : run();\n },\n getActiveContext: () => {\n const active = activeSpans.getStore();\n return active\n ? { traceId: active.traceId, spanId: active.spanId }\n : undefined;\n },\n };\n};\n\nconst nonnegativeNumber = (value: unknown): number | undefined =>\n typeof value === \"number\" && Number.isFinite(value) && value >= 0\n ? value\n : undefined;\n"],"mappings":";;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACAA,yBAA2B;;;ACEpB,IAAM,qBAAN,cAAiC,MAAM;AAAA,EAC5C,YAAqB,QAAgB;AACnC,UAAM,oCAAoC,MAAM,IAAI;AADjC;AAAA,EAErB;AAAA,EAFqB;AAGvB;AAEO,IAAM,iBAAiB,CAAC,SAIzB;AACJ,QAAM,QAAgC,CAAC;AACvC,MAAI,UAAU;AACd,MAAI,oBAAoB;AACxB,MAAI,eAAe;AACnB,MAAI;AACJ,MAAI;AACJ,QAAM,WAAW,CAAC,QAAQ,KAAK,oBAAoB;AACjD,QAAI,SAAS,YAAY,MAAM,WAAW,EAAG;AAC7C,YAAQ,WAAW,MAAM;AACvB,cAAQ;AACR,WAAK,MAAM;AAAA,IACb,GAAG,KAAK;AACR,QAAI,OAAO,UAAU,YAAY,W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AAA,IACA,UAAU;AAAA,MACR,wBAAwB,SAAS;AAAA,MACjC;AAAA,MACA,uBAAuB,SAAS;AAAA,IAClC;AAAA,IACA,aAAa,QAAQ;AAAA,IACrB,SAAS,QAAQ;AAAA,IACjB,GAAI,QAAQ,iBACR,EAAE,gBAAgB,QAAQ,eAAe,IACzC,CAAC;AAAA,IACL,GAAI,QAAQ,WAAW,EAAE,UAAU,QAAQ,SAAS,IAAI,CAAC;AAAA,IACzD,GAAI,QAAQ,OAAO,EAAE,MAAM,QAAQ,KAAK,IAAI,CAAC;AAAA,IAC7C,OAAO,SAAS;AAAA,IAChB,sBAAsB,SAAS;AAAA,IAC/B,kCAAkC,SAAS;AAAA,EAC7C;AACF;","names":["result","args"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@kortyx/telemetry",
3
- "version": "0.1.0",
3
+ "version": "0.3.0",
4
4
  "private": false,
5
5
  "description": "Kortyx Studio telemetry HTTP adapter.",
6
6
  "license": "Apache-2.0",
@@ -18,8 +18,8 @@
18
18
  "CHANGELOG.md"
19
19
  ],
20
20
  "dependencies": {
21
- "@kortyx/hooks": "0.17.1",
22
- "@kortyx/telemetry-contracts": "0.1.0"
21
+ "@kortyx/hooks": "0.19.0",
22
+ "@kortyx/telemetry-contracts": "0.3.0"
23
23
  },
24
24
  "devDependencies": {
25
25
  "tsup": "^8.5.1",