@kohaku-ui/otel 0.1.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/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (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
105
+
106
+ (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.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
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
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
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.
package/README.md ADDED
@@ -0,0 +1,18 @@
1
+ # @kohaku-ui/otel
2
+
3
+ Opt-in OpenTelemetry layer for kohaku: turns compose observer callbacks into spans. Ships no exporter or SDK wiring.
4
+
5
+ Part of [kohaku](https://github.com/yosuque/kohaku), a reference implementation of the
6
+ [Kohaku Protocol](https://github.com/yosuque/kohaku/blob/main/spec/SPEC.md): UI treated as data
7
+ (a declarative UI Spec), with generation separated from rendering.
8
+
9
+ ```bash
10
+ npm install @kohaku-ui/otel
11
+ ```
12
+
13
+ The packages in this scope share a single version and are designed to be installed together.
14
+
15
+ - Documentation: https://github.com/yosuque/kohaku#readme
16
+ - Source: https://github.com/yosuque/kohaku/tree/main/packages/otel
17
+
18
+ Licensed under the Apache License, Version 2.0.
@@ -0,0 +1,2 @@
1
+ export { createOtelComposeObserver, DEFAULT_OTEL_ATTRIBUTE_NAMES, type OtelAttributeNames, type OtelComposeObserverOptions, } from "./observer.js";
2
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,yBAAyB,EACzB,4BAA4B,EAC5B,KAAK,kBAAkB,EACvB,KAAK,0BAA0B,GAChC,MAAM,eAAe,CAAC"}
package/dist/index.js ADDED
@@ -0,0 +1,2 @@
1
+ export { createOtelComposeObserver, DEFAULT_OTEL_ATTRIBUTE_NAMES, } from "./observer.js";
2
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,yBAAyB,EACzB,4BAA4B,GAG7B,MAAM,eAAe,CAAC"}
@@ -0,0 +1,75 @@
1
+ import type { ComposeObserver } from "@kohaku-ui/composer";
2
+ import { type Tracer } from "@opentelemetry/api";
3
+ /**
4
+ * Attribute key names emitted by createOtelComposeObserver's spans. The 5 `gen_ai.*` keys follow
5
+ * OpenTelemetry's Generative AI semantic conventions
6
+ * (https://opentelemetry.io/docs/specs/semconv/gen-ai/), which are still in "Development" status as of
7
+ * this writing -- **the key spellings here are not a stability guarantee**, only this package's current
8
+ * best-effort mapping. Every name is therefore independently overridable via
9
+ * `createOtelComposeObserver({ attributes })`, so a future semconv rename (or a product's own convention)
10
+ * does not require waiting on a kohaku release. The `kohaku.*` keys are this package's own, unaffiliated
11
+ * with any external convention, and equally overridable for the same reason (an operator's collector /
12
+ * dashboards may already expect different names).
13
+ */
14
+ export interface OtelAttributeNames {
15
+ operationName: string;
16
+ providerName: string;
17
+ requestModel: string;
18
+ usageInputTokens: string;
19
+ usageOutputTokens: string;
20
+ tier: string;
21
+ cache: string;
22
+ intentHash: string;
23
+ correlationId: string;
24
+ durationMs: string;
25
+ }
26
+ /** createOtelComposeObserver's default attribute key names (see OtelAttributeNames' doc comment). */
27
+ export declare const DEFAULT_OTEL_ATTRIBUTE_NAMES: OtelAttributeNames;
28
+ export interface OtelComposeObserverOptions {
29
+ /**
30
+ * The @opentelemetry/api Tracer to record spans on. Defaults to
31
+ * `trace.getTracer("@kohaku-ui/otel")` -- a no-op tracer when no SDK/TracerProvider is registered
32
+ * globally, which is exactly the safe default for KOHAKU_OTEL unset/off: every call below still runs,
33
+ * simply recording into a tracer that discards everything.
34
+ */
35
+ tracer?: Tracer;
36
+ /** Overrides for one or more attribute key names (see OtelAttributeNames). Unspecified keys keep their default (DEFAULT_OTEL_ATTRIBUTE_NAMES). */
37
+ attributes?: Partial<OtelAttributeNames>;
38
+ /**
39
+ * `gen_ai.provider.name`'s value (e.g. "anthropic", "openai", "ollama"). ComposeTrace carries only a
40
+ * model id (LlmPort.modelId), never a provider name, so this package cannot derive it on its own --
41
+ * pass the provider kohaku's LlmPort is actually configured with, or a function of the model id for a
42
+ * host mixing providers. Omitted (default): the attribute is simply not set on any span.
43
+ */
44
+ providerName?: string | ((model: string) => string | undefined);
45
+ }
46
+ /**
47
+ * Creates a ComposeObserver that records each compose as an OpenTelemetry span (thin layer: no exporter /
48
+ * SDK setup here -- that is left to the host process, see docs/user-guide.md's "Trace context / OTel"
49
+ * section). Combine with a product's own observer via @kohaku-ui/composer's `composeObservers`.
50
+ *
51
+ * - `onComposed`: one span named "kohaku.compose" per delivered Spec, ending OK (or ERROR when
52
+ * trace.fallback is set -- a delivered-but-degraded Spec), with the gen_ai.* / kohaku.* attributes above.
53
+ * Its `startTime` is backdated by `trace.durationMs` so the span's length approximates the actual compose
54
+ * time instead of always reading ~0 (see composedAttributes' `durationMs` attribute for the exact figure).
55
+ * - `onError`: one ERROR-status span (the exception recorded via span.recordException when it is an Error)
56
+ * for a genuine generation failure -- phase "hard" or "cache" only. Phases "fallback" (a
57
+ * degraded-but-delivered Spec) and "cancelled" (a caller abort, not a real failure -- see
58
+ * ComposeErrorContext's doc comment) create **no span here**: both outcomes still reach `onComposed` with
59
+ * their own single ERROR/OK span (a fallback compose always calls onComposed too, with `trace.fallback`
60
+ * set), so recording a second span in onError for either would double-count it -- e.g. one degraded
61
+ * delivery would otherwise produce two ERROR spans and roughly double the apparent fallback rate as soon
62
+ * as `KOHAKU_OTEL=1`. This mirrors the hosts' own lineage-recording skip for "cancelled" (a client
63
+ * disconnect must not inflate fallback-rate analytics either).
64
+ * - `onBudgetCheckError`: **not a failure** (generation continues normally) -- recorded as its own span
65
+ * ("kohaku.budget_check", not "kohaku.compose" -- see BUDGET_CHECK_SPAN_NAME's doc comment) with a
66
+ * span event, never an ERROR status.
67
+ *
68
+ * Every hook is a plain function: any exception it throws (or a rejected Promise it returns) is swallowed
69
+ * by @kohaku-ui/composer's own observer fire-and-forget wrapping (fireObserverHook, used by both a bare
70
+ * ComposeObserver and composeObservers' per-observer isolation) -- this package relies on that existing
71
+ * fail-open contract rather than duplicating try/catch here, so a broken/misconfigured Tracer (e.g. no
72
+ * TracerProvider registered, or one that throws) never fails a compose.
73
+ */
74
+ export declare function createOtelComposeObserver(options?: OtelComposeObserverOptions): ComposeObserver;
75
+ //# sourceMappingURL=observer.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"observer.d.ts","sourceRoot":"","sources":["../src/observer.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAuB,eAAe,EAA8B,MAAM,qBAAqB,CAAC;AAC5G,OAAO,EAUL,KAAK,MAAM,EACZ,MAAM,oBAAoB,CAAC;AAE5B;;;;;;;;;;GAUG;AACH,MAAM,WAAW,kBAAkB;IACjC,aAAa,EAAE,MAAM,CAAC;IACtB,YAAY,EAAE,MAAM,CAAC;IACrB,YAAY,EAAE,MAAM,CAAC;IACrB,gBAAgB,EAAE,MAAM,CAAC;IACzB,iBAAiB,EAAE,MAAM,CAAC;IAC1B,IAAI,EAAE,MAAM,CAAC;IACb,KAAK,EAAE,MAAM,CAAC;IACd,UAAU,EAAE,MAAM,CAAC;IACnB,aAAa,EAAE,MAAM,CAAC;IACtB,UAAU,EAAE,MAAM,CAAC;CACpB;AAED,qGAAqG;AACrG,eAAO,MAAM,4BAA4B,EAAE,kBAW1C,CAAC;AAsBF,MAAM,WAAW,0BAA0B;IACzC;;;;;OAKG;IACH,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,kJAAkJ;IAClJ,UAAU,CAAC,EAAE,OAAO,CAAC,kBAAkB,CAAC,CAAC;IACzC;;;;;OAKG;IACH,YAAY,CAAC,EAAE,MAAM,GAAG,CAAC,CAAC,KAAK,EAAE,MAAM,KAAK,MAAM,GAAG,SAAS,CAAC,CAAC;CACjE;AAgFD;;;;;;;;;;;;;;;;;;;;;;;;;;;GA2BG;AACH,wBAAgB,yBAAyB,CAAC,OAAO,GAAE,0BAA+B,GAAG,eAAe,CAuCnG"}
@@ -0,0 +1,170 @@
1
+ import { createTraceState, isSpanContextValid, context as otelContext, trace as otelTrace, SpanStatusCode, } from "@opentelemetry/api";
2
+ /** createOtelComposeObserver's default attribute key names (see OtelAttributeNames' doc comment). */
3
+ export const DEFAULT_OTEL_ATTRIBUTE_NAMES = {
4
+ operationName: "gen_ai.operation.name",
5
+ providerName: "gen_ai.provider.name",
6
+ requestModel: "gen_ai.request.model",
7
+ usageInputTokens: "gen_ai.usage.input_tokens",
8
+ usageOutputTokens: "gen_ai.usage.output_tokens",
9
+ tier: "kohaku.tier",
10
+ cache: "kohaku.cache",
11
+ intentHash: "kohaku.intent_hash",
12
+ correlationId: "kohaku.correlation_id",
13
+ durationMs: "kohaku.duration_ms",
14
+ };
15
+ /** The span name onComposed / onError record under (a real compose attempt). */
16
+ const SPAN_NAME = "kohaku.compose";
17
+ /**
18
+ * The span name onBudgetCheckError records under. Deliberately distinct from SPAN_NAME: a budget-check
19
+ * failure is not a compose (generation continues normally around it -- see BudgetCheckErrorContext's doc
20
+ * comment), so folding it into "kohaku.compose" would pollute the compose span count with an unrelated event
21
+ * that carries no trace context (BudgetCheckErrorContext has no traceContext field to parent it under).
22
+ */
23
+ const BUDGET_CHECK_SPAN_NAME = "kohaku.budget_check";
24
+ /**
25
+ * `gen_ai.operation.name`'s value for a kohaku compose span. Fixed ("chat"): kohaku's L1/L2 generation is a
26
+ * structured-output (schema-constrained) chat completion, the closest of GenAI semconv's enumerated
27
+ * operation names. Set only when ComposeTrace.model is present -- an L0 fixed Spec or a cache hit never
28
+ * calls an LLM at all, so no span for one ever asserts a gen_ai.* attribute for an operation it did not
29
+ * perform.
30
+ */
31
+ const GEN_AI_OPERATION_NAME = "chat";
32
+ /**
33
+ * Reconstructs a parent `Context` from a `ComposeTrace`/`ComposeErrorContext`'s `traceContext` (the
34
+ * caller's own W3C trace, propagated via `ComposeOptions.traceContext` -- see TraceContext's doc comment
35
+ * in @kohaku-ui/composer), so the span created here becomes a **child** of the caller's trace instead of
36
+ * always starting a fresh root trace. Fail-open: a missing or malformed traceContext (defense in depth --
37
+ * host-rest/host-mcp-apps already validate before ever setting this field) simply falls back to the
38
+ * ambient active Context (today's un-parented behavior), never throws.
39
+ */
40
+ function parentContextFrom(traceContext) {
41
+ const active = otelContext.active();
42
+ if (traceContext == null)
43
+ return active;
44
+ const parts = traceContext.traceparent.split("-");
45
+ if (parts.length !== 4)
46
+ return active;
47
+ const [, traceId, spanId, flagsHex] = parts;
48
+ const flags = Number.parseInt(flagsHex ?? "", 16);
49
+ const spanContext = {
50
+ traceId: traceId ?? "",
51
+ spanId: spanId ?? "",
52
+ traceFlags: Number.isNaN(flags) ? 0 : flags,
53
+ isRemote: true,
54
+ ...(traceContext.tracestate != null ? { traceState: createTraceState(traceContext.tracestate) } : {}),
55
+ };
56
+ if (!isSpanContextValid(spanContext))
57
+ return active;
58
+ return otelTrace.setSpanContext(active, spanContext);
59
+ }
60
+ function providerNameFor(model, providerName) {
61
+ if (model == null || providerName == null)
62
+ return undefined;
63
+ return typeof providerName === "function" ? providerName(model) : providerName;
64
+ }
65
+ /** Builds the onComposed span's attributes from a ComposeTrace (see OtelAttributeNames' doc comment). */
66
+ function composedAttributes(trace, names, providerName) {
67
+ const attrs = {
68
+ [names.tier]: trace.tier,
69
+ [names.cache]: trace.cache,
70
+ [names.intentHash]: trace.intent.hash,
71
+ [names.durationMs]: trace.durationMs,
72
+ };
73
+ if (trace.correlationId != null)
74
+ attrs[names.correlationId] = trace.correlationId;
75
+ if (trace.model != null) {
76
+ attrs[names.operationName] = GEN_AI_OPERATION_NAME;
77
+ attrs[names.requestModel] = trace.model;
78
+ const provider = providerNameFor(trace.model, providerName);
79
+ if (provider != null)
80
+ attrs[names.providerName] = provider;
81
+ }
82
+ if (trace.usage != null) {
83
+ attrs[names.usageInputTokens] = trace.usage.inputTokens;
84
+ attrs[names.usageOutputTokens] = trace.usage.outputTokens;
85
+ }
86
+ return attrs;
87
+ }
88
+ /** Builds the onError span's attributes from a ComposeErrorContext (only the fields it actually has). */
89
+ function errorAttributes(ctx, names) {
90
+ const attrs = {};
91
+ if (ctx.intent != null)
92
+ attrs[names.intentHash] = ctx.intent.hash;
93
+ if (ctx.tier != null)
94
+ attrs[names.tier] = ctx.tier;
95
+ if (ctx.correlationId != null)
96
+ attrs[names.correlationId] = ctx.correlationId;
97
+ return attrs;
98
+ }
99
+ function endWithComposedStatus(span, trace) {
100
+ span.setStatus(trace.fallback != null
101
+ ? { code: SpanStatusCode.ERROR, message: trace.fallback.reason }
102
+ : { code: SpanStatusCode.OK });
103
+ span.end();
104
+ }
105
+ /**
106
+ * Creates a ComposeObserver that records each compose as an OpenTelemetry span (thin layer: no exporter /
107
+ * SDK setup here -- that is left to the host process, see docs/user-guide.md's "Trace context / OTel"
108
+ * section). Combine with a product's own observer via @kohaku-ui/composer's `composeObservers`.
109
+ *
110
+ * - `onComposed`: one span named "kohaku.compose" per delivered Spec, ending OK (or ERROR when
111
+ * trace.fallback is set -- a delivered-but-degraded Spec), with the gen_ai.* / kohaku.* attributes above.
112
+ * Its `startTime` is backdated by `trace.durationMs` so the span's length approximates the actual compose
113
+ * time instead of always reading ~0 (see composedAttributes' `durationMs` attribute for the exact figure).
114
+ * - `onError`: one ERROR-status span (the exception recorded via span.recordException when it is an Error)
115
+ * for a genuine generation failure -- phase "hard" or "cache" only. Phases "fallback" (a
116
+ * degraded-but-delivered Spec) and "cancelled" (a caller abort, not a real failure -- see
117
+ * ComposeErrorContext's doc comment) create **no span here**: both outcomes still reach `onComposed` with
118
+ * their own single ERROR/OK span (a fallback compose always calls onComposed too, with `trace.fallback`
119
+ * set), so recording a second span in onError for either would double-count it -- e.g. one degraded
120
+ * delivery would otherwise produce two ERROR spans and roughly double the apparent fallback rate as soon
121
+ * as `KOHAKU_OTEL=1`. This mirrors the hosts' own lineage-recording skip for "cancelled" (a client
122
+ * disconnect must not inflate fallback-rate analytics either).
123
+ * - `onBudgetCheckError`: **not a failure** (generation continues normally) -- recorded as its own span
124
+ * ("kohaku.budget_check", not "kohaku.compose" -- see BUDGET_CHECK_SPAN_NAME's doc comment) with a
125
+ * span event, never an ERROR status.
126
+ *
127
+ * Every hook is a plain function: any exception it throws (or a rejected Promise it returns) is swallowed
128
+ * by @kohaku-ui/composer's own observer fire-and-forget wrapping (fireObserverHook, used by both a bare
129
+ * ComposeObserver and composeObservers' per-observer isolation) -- this package relies on that existing
130
+ * fail-open contract rather than duplicating try/catch here, so a broken/misconfigured Tracer (e.g. no
131
+ * TracerProvider registered, or one that throws) never fails a compose.
132
+ */
133
+ export function createOtelComposeObserver(options = {}) {
134
+ const tracer = options.tracer ?? otelTrace.getTracer("@kohaku-ui/otel");
135
+ const names = { ...DEFAULT_OTEL_ATTRIBUTE_NAMES, ...options.attributes };
136
+ return {
137
+ onComposed(trace) {
138
+ // startTime is an approximation (Date.now() minus the already-elapsed durationMs), not the compose's
139
+ // true wall-clock start -- close enough to keep the span's length representative in a trace waterfall
140
+ // rather than always reading ~0, without threading a real start timestamp through ComposeTrace.
141
+ const span = tracer.startSpan(SPAN_NAME, { startTime: Date.now() - trace.durationMs }, parentContextFrom(trace.traceContext));
142
+ span.setAttributes(composedAttributes(trace, names, options.providerName));
143
+ endWithComposedStatus(span, trace);
144
+ },
145
+ onError(ctx, error) {
146
+ // "fallback" and "cancelled" are both already represented by onComposed's own span (see this
147
+ // function's doc comment) -- recording a span here too would double-count them.
148
+ if (ctx.phase === "fallback" || ctx.phase === "cancelled")
149
+ return;
150
+ const span = tracer.startSpan(SPAN_NAME, {}, parentContextFrom(ctx.traceContext));
151
+ span.setAttributes(errorAttributes(ctx, names));
152
+ if (error instanceof Error)
153
+ span.recordException(error);
154
+ const message = error instanceof Error ? error.message : (ctx.reason ?? ctx.phase);
155
+ span.setStatus({ code: SpanStatusCode.ERROR, message });
156
+ span.end();
157
+ },
158
+ onBudgetCheckError(ctx) {
159
+ // This is not a failure notification (generation continues) -- see BudgetCheckErrorContext's doc
160
+ // comment -- so it becomes a span event, never an ERROR status. BudgetCheckErrorContext carries no
161
+ // traceContext (unlike ComposeTrace/ComposeErrorContext -- out of this package's scope to add), so
162
+ // this always starts from the ambient active Context.
163
+ const span = tracer.startSpan(BUDGET_CHECK_SPAN_NAME, {}, otelContext.active());
164
+ span.setAttributes({ [names.tier]: ctx.tier, [names.intentHash]: ctx.intent.hash });
165
+ span.addEvent("kohaku.budget_check_error");
166
+ span.end();
167
+ },
168
+ };
169
+ }
170
+ //# sourceMappingURL=observer.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"observer.js","sourceRoot":"","sources":["../src/observer.ts"],"names":[],"mappings":"AACA,OAAO,EAGL,gBAAgB,EAChB,kBAAkB,EAClB,OAAO,IAAI,WAAW,EACtB,KAAK,IAAI,SAAS,EAGlB,cAAc,GAEf,MAAM,oBAAoB,CAAC;AA0B5B,qGAAqG;AACrG,MAAM,CAAC,MAAM,4BAA4B,GAAuB;IAC9D,aAAa,EAAE,uBAAuB;IACtC,YAAY,EAAE,sBAAsB;IACpC,YAAY,EAAE,sBAAsB;IACpC,gBAAgB,EAAE,2BAA2B;IAC7C,iBAAiB,EAAE,4BAA4B;IAC/C,IAAI,EAAE,aAAa;IACnB,KAAK,EAAE,cAAc;IACrB,UAAU,EAAE,oBAAoB;IAChC,aAAa,EAAE,uBAAuB;IACtC,UAAU,EAAE,oBAAoB;CACjC,CAAC;AAEF,gFAAgF;AAChF,MAAM,SAAS,GAAG,gBAAgB,CAAC;AAEnC;;;;;GAKG;AACH,MAAM,sBAAsB,GAAG,qBAAqB,CAAC;AAErD;;;;;;GAMG;AACH,MAAM,qBAAqB,GAAG,MAAM,CAAC;AAqBrC;;;;;;;GAOG;AACH,SAAS,iBAAiB,CAAC,YAAsC;IAC/D,MAAM,MAAM,GAAG,WAAW,CAAC,MAAM,EAAE,CAAC;IACpC,IAAI,YAAY,IAAI,IAAI;QAAE,OAAO,MAAM,CAAC;IACxC,MAAM,KAAK,GAAG,YAAY,CAAC,WAAW,CAAC,KAAK,C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J,CAAC"}
package/package.json ADDED
@@ -0,0 +1,56 @@
1
+ {
2
+ "name": "@kohaku-ui/otel",
3
+ "version": "0.1.0",
4
+ "description": "Opt-in OpenTelemetry layer for kohaku: turns compose observer callbacks into spans. Ships no exporter or SDK wiring.",
5
+ "type": "module",
6
+ "exports": {
7
+ ".": {
8
+ "types": "./dist/index.d.ts",
9
+ "default": "./dist/index.js"
10
+ },
11
+ "./package.json": "./package.json"
12
+ },
13
+ "dependencies": {
14
+ "@kohaku-ui/composer": "^0.1.0"
15
+ },
16
+ "peerDependencies": {
17
+ "@opentelemetry/api": "^1.9.1",
18
+ "zod": "^4.6.2"
19
+ },
20
+ "devDependencies": {
21
+ "@opentelemetry/api": "^1.9.1",
22
+ "@types/node": "^25.9.6",
23
+ "typescript": "7.0.2",
24
+ "vitest": "^4.1.11",
25
+ "zod": "^4.6.2",
26
+ "@kohaku-ui/spec-core": "^0.1.0"
27
+ },
28
+ "license": "Apache-2.0",
29
+ "homepage": "https://github.com/yosuque/kohaku/tree/main/packages/otel#readme",
30
+ "bugs": {
31
+ "url": "https://github.com/yosuque/kohaku/issues"
32
+ },
33
+ "repository": {
34
+ "type": "git",
35
+ "url": "git+https://github.com/yosuque/kohaku.git",
36
+ "directory": "packages/otel"
37
+ },
38
+ "engines": {
39
+ "node": ">=22"
40
+ },
41
+ "sideEffects": false,
42
+ "files": [
43
+ "dist",
44
+ "LICENSE",
45
+ "README.md"
46
+ ],
47
+ "publishConfig": {
48
+ "access": "public"
49
+ },
50
+ "scripts": {
51
+ "typecheck": "tsc --noEmit",
52
+ "build": "rm -rf dist && tsc -p tsconfig.build.json"
53
+ },
54
+ "main": "./dist/index.js",
55
+ "types": "./dist/index.d.ts"
56
+ }