@gnldev/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 +201 -0
- package/README.md +100 -0
- package/dist/index.d.ts +57 -0
- package/dist/index.js +126 -0
- package/dist/index.js.map +1 -0
- package/dist/live.d.ts +60 -0
- package/dist/live.js +197 -0
- package/dist/live.js.map +1 -0
- package/dist/metrics.d.ts +100 -0
- package/dist/metrics.js +145 -0
- package/dist/metrics.js.map +1 -0
- package/dist/otlp.d.ts +112 -0
- package/dist/otlp.js +218 -0
- package/dist/otlp.js.map +1 -0
- package/dist/presets.d.ts +50 -0
- package/dist/presets.js +96 -0
- package/dist/presets.js.map +1 -0
- package/dist/spans.d.ts +29 -0
- package/dist/spans.js +77 -0
- package/dist/spans.js.map +1 -0
- package/package.json +84 -0
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 2026 Karaca Yılmaz (https://gnl.dev)
|
|
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,100 @@
|
|
|
1
|
+
# @gnldev/otel
|
|
2
|
+
|
|
3
|
+
Converts the journal into a real **OpenTelemetry trace** and sends it to a SpanExporter (or an OTLP endpoint). Deterministic span ids → **idempotent**; since it's produced post-hoc from the journal, it stays complete even after a crash and consistent across replays = **crash-proof, idempotent observability** — exporting the same run twice produces the same trace rather than a duplicate (live-instrumenting frameworks cannot offer this).
|
|
4
|
+
|
|
5
|
+
> Install: `pnpm add @gnldev/otel` — or use it from a [repo clone](https://github.com/Karaca7/gnldev): `pnpm install && pnpm -r build`.
|
|
6
|
+
|
|
7
|
+
```bash
|
|
8
|
+
npm i @gnldev/otel # peer: @gnldev/durable, (optional) @opentelemetry/exporter-trace-otlp-http
|
|
9
|
+
```
|
|
10
|
+
|
|
11
|
+
```ts
|
|
12
|
+
import { exportRun } from '@gnldev/otel';
|
|
13
|
+
|
|
14
|
+
// Send a run to an OTLP collector (Jaeger/Tempo/Honeycomb…).
|
|
15
|
+
const { traceId, spans } = await exportRun(journal, 'order-123', {
|
|
16
|
+
endpoint: 'http://localhost:4318/v1/traces',
|
|
17
|
+
serviceName: 'support-desk',
|
|
18
|
+
});
|
|
19
|
+
|
|
20
|
+
// Test: pass a ready-made InMemorySpanExporter → getFinishedSpans().
|
|
21
|
+
```
|
|
22
|
+
|
|
23
|
+
## API
|
|
24
|
+
- `exportRun(journal, runId, opts?) → { traceId, spans, exporter }`
|
|
25
|
+
- `opts`: `exporter?` (ready-made SpanExporter) · `endpoint?` (OTLP-HTTP, set up lazily) · `serviceName?` · `pricing?` · `modelId?` · `redact?`
|
|
26
|
+
|
|
27
|
+
### `redact` — the one free-text value a span carries
|
|
28
|
+
|
|
29
|
+
Spans from this package hold model ids, finish reasons, token counts and tool statuses; prompts, responses and tool results are never read. The single exception is a **failed run's error message**, which travels as `gnl.error` and as the root span's status message.
|
|
30
|
+
|
|
31
|
+
That message is not always your own text — a provider refusing a request commonly echoes the offending input back inside it. And a processor chain does not cover this path: `piiRedactor` hooks `processInput`/`processOutput`/`processToolResult`, while a run's verdict is written by `recordRunOutcome` in `@gnldev/durable`, which no processor sees. So with the redactor installed, the address still reaches your collector — which for a hosted backend is a third party.
|
|
32
|
+
|
|
33
|
+
It stays raw by default, because the message is the main debugging value a trace carries and this package cannot know whether `endpoint` is your own collector. One line turns it on, sharing `piiRedactor`'s defaults:
|
|
34
|
+
|
|
35
|
+
```ts
|
|
36
|
+
import { exportRun } from '@gnldev/otel';
|
|
37
|
+
import { piiTextRedactor } from '@gnldev/processors';
|
|
38
|
+
|
|
39
|
+
await exportRun(journal, 'order-123', {
|
|
40
|
+
endpoint: 'http://localhost:4318/v1/traces',
|
|
41
|
+
redact: piiTextRedactor(),
|
|
42
|
+
});
|
|
43
|
+
```
|
|
44
|
+
|
|
45
|
+
A redactor that throws or returns a non-string **drops** the message rather than falling back to the raw text — the run is still exported as failed, only the reason is withheld.
|
|
46
|
+
|
|
47
|
+
## How it works
|
|
48
|
+
Each model/tool journal entry maps to a span; trace/span ids are derived from runId+seq (deterministic) → exporting the same run again produces the same trace. Cost/token span attributes are added via `getRunCost`.
|
|
49
|
+
|
|
50
|
+
## Zero-dependency OTLP/HTTP JSON exporter (`exportRunToOtlp` / `toOtlpJson`)
|
|
51
|
+
|
|
52
|
+
The `exportRun` above uses `@opentelemetry/sdk-trace-base` (a dependency of this package, installed for you). Alongside it there is also a smaller alternative that **doesn't need any OTel SDK** — it manually converts `packages/durable`'s `toTraceSpans` output into an OTLP/HTTP JSON body and POSTs it with plain `fetch` (~8KB footprint: just `node:crypto` + the global `fetch`).
|
|
53
|
+
|
|
54
|
+
```ts
|
|
55
|
+
import { exportRunToOtlp, toOtlpJson } from '@gnldev/otel';
|
|
56
|
+
import { toTraceSpans } from '@gnldev/durable';
|
|
57
|
+
|
|
58
|
+
// Send a run directly to an OTLP/HTTP collector.
|
|
59
|
+
const { traceId, spans, ok, status } = await exportRunToOtlp(journal, 'order-123', {
|
|
60
|
+
endpoint: process.env.OTLP_ENDPOINT!, // e.g. 'http://localhost:4318/v1/traces'
|
|
61
|
+
headers: process.env.OTLP_HEADERS ? JSON.parse(process.env.OTLP_HEADERS) : undefined,
|
|
62
|
+
serviceName: 'support-desk',
|
|
63
|
+
});
|
|
64
|
+
|
|
65
|
+
// Network-free testing / custom delivery: a PURE function.
|
|
66
|
+
const spans2 = await toTraceSpans(journal, 'order-123');
|
|
67
|
+
const payload = toOtlpJson(spans2, { runId: 'order-123', serviceName: 'support-desk' });
|
|
68
|
+
```
|
|
69
|
+
|
|
70
|
+
### API
|
|
71
|
+
- `toOtlpJson(spans: TraceSpan[], opts) → OtlpPayload` — PURE, no network. `opts`: `runId` (required) · `serviceName?` · `resourceAttributes?` · `now?` (fallback timestamp for entries without a `ts`, for test determinism).
|
|
72
|
+
- `exportRunToOtlp(journal, runId, opts) → { traceId, spans, ok, status }` — `toTraceSpans` + `toOtlpJson` + `fetch(POST)`. `opts`: `endpoint` (required) · `headers?` · `serviceName?` · `resourceAttributes?` · `now?`.
|
|
73
|
+
- `otlpTraceId(runId)` / `otlpSpanId(runId, seq | 'root')` — deterministic id generators (idempotent export).
|
|
74
|
+
|
|
75
|
+
### Connecting to your own endpoint (Langfuse / Datadog / Jaeger / Honeycomb …)
|
|
76
|
+
|
|
77
|
+
This package **never sends to a server of ours** — the `endpoint` is always supplied by the caller, opt-in. How this relates to the "no telemetry" principle: gnl sends data nowhere by default; the OTLP exporter only runs when `endpoint` is explicitly given, and that data always goes to the CALLER's own chosen collector/backend.
|
|
78
|
+
|
|
79
|
+
```bash
|
|
80
|
+
# Local OTel Collector / Jaeger (OTLP/HTTP ingest, usually port 4318)
|
|
81
|
+
OTLP_ENDPOINT=http://localhost:4318/v1/traces
|
|
82
|
+
|
|
83
|
+
# Langfuse (OTLP ingest endpoint; project public/secret key in the Basic Auth header)
|
|
84
|
+
OTLP_ENDPOINT=https://cloud.langfuse.com/api/public/otel/v1/traces
|
|
85
|
+
OTLP_HEADERS='{"authorization":"Basic <base64(public_key:secret_key)>"}'
|
|
86
|
+
|
|
87
|
+
# Datadog Agent (if the OTLP receiver is enabled, usually 4318)
|
|
88
|
+
OTLP_ENDPOINT=http://localhost:4318/v1/traces
|
|
89
|
+
OTLP_HEADERS='{"dd-api-key":"<DATADOG_API_KEY>"}'
|
|
90
|
+
|
|
91
|
+
# Honeycomb
|
|
92
|
+
OTLP_ENDPOINT=https://api.honeycomb.io/v1/traces
|
|
93
|
+
OTLP_HEADERS='{"x-honeycomb-team":"<HONEYCOMB_API_KEY>"}'
|
|
94
|
+
```
|
|
95
|
+
|
|
96
|
+
Spans carry `gen_ai.*` semantic convention fields (`gen_ai.usage.input_tokens`, `gen_ai.usage.output_tokens`, `gen_ai.request.model`) — most LLM-observability backends recognize these automatically.
|
|
97
|
+
|
|
98
|
+
## License
|
|
99
|
+
|
|
100
|
+
Apache-2.0 — see [LICENSE](./LICENSE).
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
import { type SpanExporter } from '@opentelemetry/sdk-trace-base';
|
|
2
|
+
import type { JournalReader, ModelPricing } from '@gnldev/durable';
|
|
3
|
+
export interface ExportRunOptions {
|
|
4
|
+
/** A ready-made OTEL SpanExporter (InMemorySpanExporter for tests). If not given, falls back to the endpoint or the default. */
|
|
5
|
+
exporter?: SpanExporter;
|
|
6
|
+
/** OTLP-HTTP endpoint (e.g. 'http://localhost:4318/v1/traces'). If exporter is not given, one is built from this (lazily). */
|
|
7
|
+
endpoint?: string;
|
|
8
|
+
/** Price table for cost attributes (passed to getRunCost). */
|
|
9
|
+
pricing?: Record<string, ModelPricing>;
|
|
10
|
+
/** Default when the journal has no model id. */
|
|
11
|
+
modelId?: string;
|
|
12
|
+
/** service.name attribute. */
|
|
13
|
+
serviceName?: string;
|
|
14
|
+
/**
|
|
15
|
+
* Applied to every free-text attribute this exporter emits. Today that is exactly one value — a
|
|
16
|
+
* failed run's `outcome.error`, which reaches both the `gnl.error` attribute and the root span's
|
|
17
|
+
* status message. Everything else emitted here is a model id, a finish reason, a token count or a
|
|
18
|
+
* tool status; `mapEntry` never reads prompt, response or tool-result text.
|
|
19
|
+
*
|
|
20
|
+
* It exists because a processor chain does NOT cover this path. `piiRedactor` runs in
|
|
21
|
+
* `processInput`/`processOutput`/`processToolResult`, while the run's verdict is written from a
|
|
22
|
+
* different place entirely (`recordRunOutcome` in @gnldev/durable), which no processor sees.
|
|
23
|
+
* Measured with the redactor installed: a provider that echoes the offending input back in its
|
|
24
|
+
* refusal — `Invalid request: message contained disallowed content: "<address>"` — still put that
|
|
25
|
+
* address into the span raw, and from there into whatever collector `endpoint` names, which is
|
|
26
|
+
* commonly a third party's.
|
|
27
|
+
*
|
|
28
|
+
* Off by default rather than redacting unconditionally: the message is the main debugging value a
|
|
29
|
+
* trace carries, and this package cannot know whether the endpoint is the host's own collector.
|
|
30
|
+
* One line to turn on, sharing `piiRedactor`'s defaults:
|
|
31
|
+
*
|
|
32
|
+
* import { piiTextRedactor } from '@gnldev/processors';
|
|
33
|
+
* await exportRun(journal, runId, { endpoint, redact: piiTextRedactor() });
|
|
34
|
+
*
|
|
35
|
+
* A redactor that throws or returns a non-string DROPS the message rather than falling back to the
|
|
36
|
+
* raw text — the raw text is the exact value it was installed to keep out.
|
|
37
|
+
*/
|
|
38
|
+
redact?: (text: string) => string;
|
|
39
|
+
}
|
|
40
|
+
export interface ExportRunResult {
|
|
41
|
+
traceId: string;
|
|
42
|
+
spans: number;
|
|
43
|
+
/** The exporter used (if InMemorySpanExporter, tests can call getFinishedSpans()). */
|
|
44
|
+
exporter: SpanExporter;
|
|
45
|
+
}
|
|
46
|
+
/**
|
|
47
|
+
* Exports a run from the journal as an OTEL trace: 1 root span `agent.run` + one child span per
|
|
48
|
+
* model/tool entry. trace_id/span_id are deterministic (hash of runId/seq) → exporting the same run
|
|
49
|
+
* twice yields the SAME trace (idempotent). Duration is derived from each entry's `ts` (created_at).
|
|
50
|
+
*/
|
|
51
|
+
export declare function exportRun(reader: JournalReader, runId: string, opts?: ExportRunOptions): Promise<ExportRunResult>;
|
|
52
|
+
export { traceIdFor, spanIdFor, mapEntry } from './spans.js';
|
|
53
|
+
export { toOtlpJson, exportRunToOtlp, otlpTraceId, otlpSpanId } from './otlp.js';
|
|
54
|
+
export { toOtlpMetricsJson, nextEpoch } from './metrics.js';
|
|
55
|
+
export type { ToOtlpMetricsOptions, MetricsEpoch, OtlpMetricsPayload, OtlpMetric } from './metrics.js';
|
|
56
|
+
export type { OtlpPayload, OtlpSpan, OtlpKeyValue, OtlpAttributeValue, ToOtlpJsonOptions, ExportRunToOtlpOptions, ExportRunToOtlpResult, OtlpRetryOptions, } from './otlp.js';
|
|
57
|
+
export { otlpPresets, langfuse, apiKeyOtlp, braintrust, honeycomb, datadogAgent, collector } from './presets.js';
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,126 @@
|
|
|
1
|
+
// @gnldev/otel — converts the journal into a real OpenTelemetry trace and sends it to a SpanExporter (or an
|
|
2
|
+
// OTLP endpoint). Deterministic ids → idempotent; post-hoc from the journal → complete even after a crash,
|
|
3
|
+
// consistent across replays = exactly-once / crash-proof observability (frameworks that live-instrument cannot offer this).
|
|
4
|
+
import { BasicTracerProvider, SimpleSpanProcessor, InMemorySpanExporter, } from '@opentelemetry/sdk-trace-base';
|
|
5
|
+
import { trace, context, SpanKind, SpanStatusCode } from '@opentelemetry/api';
|
|
6
|
+
import { getRunCost } from '@gnldev/durable';
|
|
7
|
+
import { traceIdFor, spanIdFor, QueueIdGenerator, mapEntry } from './spans.js';
|
|
8
|
+
async function otlpExporter(endpoint) {
|
|
9
|
+
const mod = '@opentelemetry/exporter-trace-otlp-http'; // string variable → doesn't break the optional peer build
|
|
10
|
+
const { OTLPTraceExporter } = (await import(mod));
|
|
11
|
+
return new OTLPTraceExporter({ url: endpoint });
|
|
12
|
+
}
|
|
13
|
+
/**
|
|
14
|
+
* Exports a run from the journal as an OTEL trace: 1 root span `agent.run` + one child span per
|
|
15
|
+
* model/tool entry. trace_id/span_id are deterministic (hash of runId/seq) → exporting the same run
|
|
16
|
+
* twice yields the SAME trace (idempotent). Duration is derived from each entry's `ts` (created_at).
|
|
17
|
+
*/
|
|
18
|
+
export async function exportRun(reader, runId, opts = {}) {
|
|
19
|
+
const entries = await reader.readRun(runId);
|
|
20
|
+
// The run's recorded outcome. Without it, a run that DIED — a 401 on the first call, a cost ceiling —
|
|
21
|
+
// produced no error-bearing entry and was therefore exported as OK with $0 of cost: the single most
|
|
22
|
+
// misleading signal this exporter could send. `get` is optional on a bare JournalReader, so this
|
|
23
|
+
// degrades to the old derivation rather than throwing.
|
|
24
|
+
const outcome = typeof reader.get === 'function'
|
|
25
|
+
? await reader
|
|
26
|
+
.get(`${runId}:outcome`).catch(() => undefined)
|
|
27
|
+
: undefined;
|
|
28
|
+
const runFailed = outcome?.status === 'failed';
|
|
29
|
+
const runCanceled = outcome?.status === 'canceled';
|
|
30
|
+
// The one free-text value that leaves this exporter — see `redact` on the options for why the
|
|
31
|
+
// processor chain never touched it. Computed once so the status message and the attribute cannot
|
|
32
|
+
// disagree about what was masked.
|
|
33
|
+
const errorText = (() => {
|
|
34
|
+
const raw = outcome?.error;
|
|
35
|
+
if (!raw || !opts.redact)
|
|
36
|
+
return raw;
|
|
37
|
+
try {
|
|
38
|
+
const out = opts.redact(raw);
|
|
39
|
+
return typeof out === 'string' ? out : undefined;
|
|
40
|
+
}
|
|
41
|
+
catch {
|
|
42
|
+
return undefined; // fail CLOSED: a broken redactor must not resurrect the raw text
|
|
43
|
+
}
|
|
44
|
+
})();
|
|
45
|
+
const exporter = opts.exporter ?? (opts.endpoint ? await otlpExporter(opts.endpoint) : new InMemorySpanExporter());
|
|
46
|
+
// Deterministic id queues: root traceId + (for the root + each entry) spanId.
|
|
47
|
+
const traceId = traceIdFor(runId);
|
|
48
|
+
const spanIds = ['root', ...entries.map((_, i) => i)].map((s) => spanIdFor(runId, s));
|
|
49
|
+
const idGenerator = new QueueIdGenerator(runId, [traceId], spanIds);
|
|
50
|
+
// OpenTelemetry JS 2.x removed `provider.addSpanProcessor()`: a processor can no longer be
|
|
51
|
+
// attached after construction, it is declared with the provider. Passed via `spanProcessors`.
|
|
52
|
+
const provider = new BasicTracerProvider({ idGenerator, spanProcessors: [new SimpleSpanProcessor(exporter)] });
|
|
53
|
+
const tracer = provider.getTracer('@gnldev/otel');
|
|
54
|
+
const cost = await getRunCost(reader, runId, { pricing: opts.pricing, modelId: opts.modelId });
|
|
55
|
+
// Timing: span start = entry.ts, end = next entry.ts (last = end of run). Falls back to now if ts is missing.
|
|
56
|
+
const now = Date.now();
|
|
57
|
+
const firstTs = entries.find((e) => e.ts != null)?.ts ?? now;
|
|
58
|
+
const lastTs = [...entries].reverse().find((e) => e.ts != null)?.ts ?? firstTs;
|
|
59
|
+
const root = tracer.startSpan('agent.run', {
|
|
60
|
+
kind: SpanKind.INTERNAL,
|
|
61
|
+
startTime: firstTs,
|
|
62
|
+
attributes: {
|
|
63
|
+
'gnl.run_id': runId,
|
|
64
|
+
'gen_ai.usage.input_tokens': cost.inputTokens,
|
|
65
|
+
'gen_ai.usage.output_tokens': cost.outputTokens,
|
|
66
|
+
'gen_ai.usage.total_tokens': cost.totalTokens,
|
|
67
|
+
'gnl.cost_usd': cost.costUsd,
|
|
68
|
+
'gnl.model_calls': cost.modelCalls,
|
|
69
|
+
'gnl.tool_calls': cost.toolCalls,
|
|
70
|
+
...(opts.serviceName ? { 'service.name': opts.serviceName } : {}),
|
|
71
|
+
},
|
|
72
|
+
});
|
|
73
|
+
const parentCtx = trace.setSpan(context.active(), root);
|
|
74
|
+
let anyError = false;
|
|
75
|
+
let anySuspended = false;
|
|
76
|
+
for (let i = 0; i < entries.length; i++) {
|
|
77
|
+
const e = entries[i];
|
|
78
|
+
const m = mapEntry(e);
|
|
79
|
+
const start = e.ts ?? firstTs;
|
|
80
|
+
const end = entries[i + 1]?.ts ?? lastTs;
|
|
81
|
+
const span = tracer.startSpan(m.name, { kind: e.kind === 'model' ? SpanKind.CLIENT : SpanKind.INTERNAL, startTime: start, attributes: m.attributes }, parentCtx);
|
|
82
|
+
if (m.isError) {
|
|
83
|
+
span.setStatus({ code: SpanStatusCode.ERROR });
|
|
84
|
+
anyError = true;
|
|
85
|
+
}
|
|
86
|
+
if (m.isSuspended)
|
|
87
|
+
anySuspended = true;
|
|
88
|
+
span.end(end > start ? end : start);
|
|
89
|
+
}
|
|
90
|
+
// A cancel is an OPERATOR ACTION, not a system fault, so it decides the run's ending outright — the
|
|
91
|
+
// outcome record is the authority on HOW a run ended, and an errored entry earlier in a run someone
|
|
92
|
+
// then chose to stop does not make the stopping a failure. The child span that errored keeps its own
|
|
93
|
+
// ERROR status, so nothing is hidden; it simply stops being the root's verdict.
|
|
94
|
+
const failed = !runCanceled && (anyError || runFailed);
|
|
95
|
+
const stillRunning = !failed && !runCanceled && outcome?.status === 'running';
|
|
96
|
+
// A run whose write-ahead has no terminal yet is UNSET, not OK: OTel's OK means "ended fine", and
|
|
97
|
+
// this run has not ended — exporting mid-flight (or after a crash) must not report a success.
|
|
98
|
+
// A canceled run is UNSET for the mirror-image reason: it ended, but not WELL enough for OK and not
|
|
99
|
+
// BADLY enough for ERROR. OTel's semantic conventions reserve ERROR for unexpected endings, and
|
|
100
|
+
// paging an on-call because an operator cancelled a run is exactly the false alarm that trains
|
|
101
|
+
// people to ignore the signal. `gnl.status` carries the fact for anyone filtering on it.
|
|
102
|
+
root.setStatus(failed
|
|
103
|
+
? { code: SpanStatusCode.ERROR, ...(errorText ? { message: errorText } : {}) }
|
|
104
|
+
: stillRunning || runCanceled ? { code: SpanStatusCode.UNSET } : { code: SpanStatusCode.OK });
|
|
105
|
+
// Same precedence as deriveRunStatus in @gnldev/durable: canceled is terminal and wins over even
|
|
106
|
+
// suspended (a canceled run's pending approval can never be applied), then suspended is a live state.
|
|
107
|
+
root.setAttribute('gnl.status', runCanceled ? 'canceled' : anySuspended ? 'suspended' : failed ? 'failed' : stillRunning ? 'running' : 'completed');
|
|
108
|
+
if (runFailed && errorText)
|
|
109
|
+
root.setAttribute('gnl.error', errorText);
|
|
110
|
+
root.end(lastTs > firstTs ? lastTs : firstTs);
|
|
111
|
+
// Guarantee the export via forceFlush; DO NOT call shutdown (the caller owns the exporter; on InMemory,
|
|
112
|
+
// shutdown would reset the finished spans). SimpleSpanProcessor already exports synchronously on span.end.
|
|
113
|
+
await provider.forceFlush();
|
|
114
|
+
return { traceId, spans: entries.length + 1, exporter };
|
|
115
|
+
}
|
|
116
|
+
export { traceIdFor, spanIdFor, mapEntry } from './spans.js';
|
|
117
|
+
// Zero-dependency OTLP/HTTP JSON exporter (no OTel SDK, fetch only). Added alongside
|
|
118
|
+
// exportRun; does not change the existing API.
|
|
119
|
+
export { toOtlpJson, exportRunToOtlp, otlpTraceId, otlpSpanId } from './otlp.js';
|
|
120
|
+
// Counters → OTLP metrics. Also reachable as `@gnldev/otel/metrics`, which is the leaner route:
|
|
121
|
+
// this entry point statically imports the OTel trace SDK, and the metrics path needs none of it.
|
|
122
|
+
export { toOtlpMetricsJson, nextEpoch } from './metrics.js';
|
|
123
|
+
// Named observability presets (Langfuse/Braintrust/Honeycomb/Datadog/Collector) + a generic
|
|
124
|
+
// API-key-authenticated OTLP/HTTP preset for any other provider.
|
|
125
|
+
export { otlpPresets, langfuse, apiKeyOtlp, braintrust, honeycomb, datadogAgent, collector } from './presets.js';
|
|
126
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,4GAA4G;AAC5G,2GAA2G;AAC3G,4HAA4H;AAC5H,OAAO,EACL,mBAAmB,EACnB,mBAAmB,EACnB,oBAAoB,GAErB,MAAM,+BAA+B,CAAC;AACvC,OAAO,EAAE,KAAK,EAAE,OAAO,EAAE,QAAQ,EAAE,cAAc,EAAE,MAAM,oBAAoB,CAAC;AAC9E,OAAO,EAAE,UAAU,EAAE,MAAM,iBAAiB,CAAC;AAE7C,OAAO,EAAE,UAAU,EAAE,SAAS,EAAE,gBAAgB,EAAE,QAAQ,EAAE,MAAM,YAAY,CAAC;AA+C/E,KAAK,UAAU,YAAY,CAAC,QAAgB;IAC1C,MAAM,GAAG,GAAG,yCAAyC,CAAC,CAAC,0DAA0D;IACjH,MAAM,EAAE,iBAAiB,EAAE,GAAG,CAAC,MAAM,MAAM,CAAC,GAAG,CAAC,CAAQ,CAAC;IACzD,OAAO,IAAI,iBAAiB,CAAC,EAAE,GAAG,EAAE,QAAQ,EAAE,CAAC,CAAC;AAClD,CAAC;A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,CAAC,CAAC,UAAU,CAAC,CAAC,CAAC,YAAY,CAAC,CAAC,CAAC,WAAW,CAAC,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,QAAQ,CAAC,CAAC,CAAC,YAAY,CAAC,CAAC,CAAC,SAAS,CAAC,CAAC,CAAC,WAAW,CAAC,CAAC;IACpJ,IAAI,SAAS,IAAI,SAAS;QAAE,IAAI,CAAC,YAAY,CAAC,WAAW,EAAE,SAAS,CAAC,CAAC;IACtE,IAAI,CAAC,GAAG,CAAC,MAAM,GAAG,OAAO,CAAC,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,OAAO,CAAC,CAAC;IAE9C,wGAAwG;IACxG,2GAA2G;IAC3G,MAAM,QAAQ,CAAC,UAAU,EAAE,CAAC;IAE5B,OAAO,EAAE,OAAO,EAAE,KAAK,EAAE,OAAO,CAAC,MAAM,GAAG,CAAC,EAAE,QAAQ,EAAE,CAAC;AAC1D,CAAC;AAED,OAAO,EAAE,UAAU,EAAE,SAAS,EAAE,QAAQ,EAAE,MAAM,YAAY,CAAC;AAE7D,qFAAqF;AACrF,+CAA+C;AAC/C,OAAO,EAAE,UAAU,EAAE,eAAe,EAAE,WAAW,EAAE,UAAU,EAAE,MAAM,WAAW,CAAC;AACjF,gGAAgG;AAChG,iGAAiG;AACjG,OAAO,EAAE,iBAAiB,EAAE,SAAS,EAAE,MAAM,cAAc,CAAC;AAa5D,4FAA4F;AAC5F,iEAAiE;AACjE,OAAO,EAAE,WAAW,EAAE,QAAQ,EAAE,UAAU,EAAE,UAAU,EAAE,SAAS,EAAE,YAAY,EAAE,SAAS,EAAE,MAAM,cAAc,CAAC","sourcesContent":["// @gnldev/otel — converts the journal into a real OpenTelemetry trace and sends it to a SpanExporter (or an\n// OTLP endpoint). Deterministic ids → idempotent; post-hoc from the journal → complete even after a crash,\n// consistent across replays = exactly-once / crash-proof observability (frameworks that live-instrument cannot offer this).\nimport {\n BasicTracerProvider,\n SimpleSpanProcessor,\n InMemorySpanExporter,\n type SpanExporter,\n} from '@opentelemetry/sdk-trace-base';\nimport { trace, context, SpanKind, SpanStatusCode } from '@opentelemetry/api';\nimport { getRunCost } from '@gnldev/durable';\nimport type { JournalReader, ModelPricing } from '@gnldev/durable';\nimport { traceIdFor, spanIdFor, QueueIdGenerator, mapEntry } from './spans.js';\n\nexport interface ExportRunOptions {\n /** A ready-made OTEL SpanExporter (InMemorySpanExporter for tests). If not given, falls back to the endpoint or the default. */\n exporter?: SpanExporter;\n /** OTLP-HTTP endpoint (e.g. 'http://localhost:4318/v1/traces'). If exporter is not given, one is built from this (lazily). */\n endpoint?: string;\n /** Price table for cost attributes (passed to getRunCost). */\n pricing?: Record<string, ModelPricing>;\n /** Default when the journal has no model id. */\n modelId?: string;\n /** service.name attribute. */\n serviceName?: string;\n /**\n * Applied to every free-text attribute this exporter emits. Today that is exactly one value — a\n * failed run's `outcome.error`, which reaches both the `gnl.error` attribute and the root span's\n * status message. Everything else emitted here is a model id, a finish reason, a token count or a\n * tool status; `mapEntry` never reads prompt, response or tool-result text.\n *\n * It exists because a processor chain does NOT cover this path. `piiRedactor` runs in\n * `processInput`/`processOutput`/`processToolResult`, while the run's verdict is written from a\n * different place entirely (`recordRunOutcome` in @gnldev/durable), which no processor sees.\n * Measured with the redactor installed: a provider that echoes the offending input back in its\n * refusal — `Invalid request: message contained disallowed content: \"<address>\"` — still put that\n * address into the span raw, and from there into whatever collector `endpoint` names, which is\n * commonly a third party's.\n *\n * Off by default rather than redacting unconditionally: the message is the main debugging value a\n * trace carries, and this package cannot know whether the endpoint is the host's own collector.\n * One line to turn on, sharing `piiRedactor`'s defaults:\n *\n * import { piiTextRedactor } from '@gnldev/processors';\n * await exportRun(journal, runId, { endpoint, redact: piiTextRedactor() });\n *\n * A redactor that throws or returns a non-string DROPS the message rather than falling back to the\n * raw text — the raw text is the exact value it was installed to keep out.\n */\n redact?: (text: string) => string;\n}\n\nexport interface ExportRunResult {\n traceId: string;\n spans: number;\n /** The exporter used (if InMemorySpanExporter, tests can call getFinishedSpans()). */\n exporter: SpanExporter;\n}\n\nasync function otlpExporter(endpoint: string): Promise<SpanExporter> {\n const mod = '@opentelemetry/exporter-trace-otlp-http'; // string variable → doesn't break the optional peer build\n const { OTLPTraceExporter } = (await import(mod)) as any;\n return new OTLPTraceExporter({ url: endpoint });\n}\n\n/**\n * Exports a run from the journal as an OTEL trace: 1 root span `agent.run` + one child span per\n * model/tool entry. trace_id/span_id are deterministic (hash of runId/seq) → exporting the same run\n * twice yields the SAME trace (idempotent). Duration is derived from each entry's `ts` (created_at).\n */\nexport async function exportRun(\n reader: JournalReader,\n runId: string,\n opts: ExportRunOptions = {},\n): Promise<ExportRunResult> {\n const entries = await reader.readRun(runId);\n // The run's recorded outcome. Without it, a run that DIED — a 401 on the first call, a cost ceiling —\n // produced no error-bearing entry and was therefore exported as OK with $0 of cost: the single most\n // misleading signal this exporter could send. `get` is optional on a bare JournalReader, so this\n // degrades to the old derivation rather than throwing.\n const outcome = typeof (reader as { get?: unknown }).get === 'function'\n ? await (reader as unknown as { get<T>(k: string): Promise<T | undefined> })\n .get<{ status?: string; error?: string }>(`${runId}:outcome`).catch(() => undefined)\n : undefined;\n const runFailed = outcome?.status === 'failed';\n const runCanceled = outcome?.status === 'canceled';\n // The one free-text value that leaves this exporter — see `redact` on the options for why the\n // processor chain never touched it. Computed once so the status message and the attribute cannot\n // disagree about what was masked.\n const errorText = ((): string | undefined => {\n const raw = outcome?.error;\n if (!raw || !opts.redact) return raw;\n try {\n const out = opts.redact(raw);\n return typeof out === 'string' ? out : undefined;\n } catch {\n return undefined; // fail CLOSED: a broken redactor must not resurrect the raw text\n }\n })();\n const exporter = opts.exporter ?? (opts.endpoint ? await otlpExporter(opts.endpoint) : new InMemorySpanExporter());\n\n // Deterministic id queues: root traceId + (for the root + each entry) spanId.\n const traceId = traceIdFor(runId);\n const spanIds = ['root' as const, ...entries.map((_, i) => i)].map((s) => spanIdFor(runId, s));\n const idGenerator = new QueueIdGenerator(runId, [traceId], spanIds);\n\n // OpenTelemetry JS 2.x removed `provider.addSpanProcessor()`: a processor can no longer be\n // attached after construction, it is declared with the provider. Passed via `spanProcessors`.\n const provider = new BasicTracerProvider({ idGenerator, spanProcessors: [new SimpleSpanProcessor(exporter)] });\n const tracer = provider.getTracer('@gnldev/otel');\n\n const cost = await getRunCost(reader, runId, { pricing: opts.pricing, modelId: opts.modelId });\n\n // Timing: span start = entry.ts, end = next entry.ts (last = end of run). Falls back to now if ts is missing.\n const now = Date.now();\n const firstTs = entries.find((e) => e.ts != null)?.ts ?? now;\n const lastTs = [...entries].reverse().find((e) => e.ts != null)?.ts ?? firstTs;\n\n const root = tracer.startSpan('agent.run', {\n kind: SpanKind.INTERNAL,\n startTime: firstTs,\n attributes: {\n 'gnl.run_id': runId,\n 'gen_ai.usage.input_tokens': cost.inputTokens,\n 'gen_ai.usage.output_tokens': cost.outputTokens,\n 'gen_ai.usage.total_tokens': cost.totalTokens,\n 'gnl.cost_usd': cost.costUsd,\n 'gnl.model_calls': cost.modelCalls,\n 'gnl.tool_calls': cost.toolCalls,\n ...(opts.serviceName ? { 'service.name': opts.serviceName } : {}),\n },\n });\n const parentCtx = trace.setSpan(context.active(), root);\n\n let anyError = false;\n let anySuspended = false;\n for (let i = 0; i < entries.length; i++) {\n const e = entries[i]!;\n const m = mapEntry(e);\n const start = e.ts ?? firstTs;\n const end = entries[i + 1]?.ts ?? lastTs;\n const span = tracer.startSpan(\n m.name,\n { kind: e.kind === 'model' ? SpanKind.CLIENT : SpanKind.INTERNAL, startTime: start, attributes: m.attributes },\n parentCtx,\n );\n if (m.isError) {\n span.setStatus({ code: SpanStatusCode.ERROR });\n anyError = true;\n }\n if (m.isSuspended) anySuspended = true;\n span.end(end > start ? end : start);\n }\n\n // A cancel is an OPERATOR ACTION, not a system fault, so it decides the run's ending outright — the\n // outcome record is the authority on HOW a run ended, and an errored entry earlier in a run someone\n // then chose to stop does not make the stopping a failure. The child span that errored keeps its own\n // ERROR status, so nothing is hidden; it simply stops being the root's verdict.\n const failed = !runCanceled && (anyError || runFailed);\n const stillRunning = !failed && !runCanceled && outcome?.status === 'running';\n // A run whose write-ahead has no terminal yet is UNSET, not OK: OTel's OK means \"ended fine\", and\n // this run has not ended — exporting mid-flight (or after a crash) must not report a success.\n // A canceled run is UNSET for the mirror-image reason: it ended, but not WELL enough for OK and not\n // BADLY enough for ERROR. OTel's semantic conventions reserve ERROR for unexpected endings, and\n // paging an on-call because an operator cancelled a run is exactly the false alarm that trains\n // people to ignore the signal. `gnl.status` carries the fact for anyone filtering on it.\n root.setStatus(failed\n ? { code: SpanStatusCode.ERROR, ...(errorText ? { message: errorText } : {}) }\n : stillRunning || runCanceled ? { code: SpanStatusCode.UNSET } : { code: SpanStatusCode.OK });\n // Same precedence as deriveRunStatus in @gnldev/durable: canceled is terminal and wins over even\n // suspended (a canceled run's pending approval can never be applied), then suspended is a live state.\n root.setAttribute('gnl.status', runCanceled ? 'canceled' : anySuspended ? 'suspended' : failed ? 'failed' : stillRunning ? 'running' : 'completed');\n if (runFailed && errorText) root.setAttribute('gnl.error', errorText);\n root.end(lastTs > firstTs ? lastTs : firstTs);\n\n // Guarantee the export via forceFlush; DO NOT call shutdown (the caller owns the exporter; on InMemory,\n // shutdown would reset the finished spans). SimpleSpanProcessor already exports synchronously on span.end.\n await provider.forceFlush();\n\n return { traceId, spans: entries.length + 1, exporter };\n}\n\nexport { traceIdFor, spanIdFor, mapEntry } from './spans.js';\n\n// Zero-dependency OTLP/HTTP JSON exporter (no OTel SDK, fetch only). Added alongside\n// exportRun; does not change the existing API.\nexport { toOtlpJson, exportRunToOtlp, otlpTraceId, otlpSpanId } from './otlp.js';\n// Counters → OTLP metrics. Also reachable as `@gnldev/otel/metrics`, which is the leaner route:\n// this entry point statically imports the OTel trace SDK, and the metrics path needs none of it.\nexport { toOtlpMetricsJson, nextEpoch } from './metrics.js';\nexport type { ToOtlpMetricsOptions, MetricsEpoch, OtlpMetricsPayload, OtlpMetric } from './metrics.js';\nexport type {\n OtlpPayload,\n OtlpSpan,\n OtlpKeyValue,\n OtlpAttributeValue,\n ToOtlpJsonOptions,\n ExportRunToOtlpOptions,\n ExportRunToOtlpResult,\n OtlpRetryOptions,\n} from './otlp.js';\n\n// Named observability presets (Langfuse/Braintrust/Honeycomb/Datadog/Collector) + a generic\n// API-key-authenticated OTLP/HTTP preset for any other provider.\nexport { otlpPresets, langfuse, apiKeyOtlp, braintrust, honeycomb, datadogAgent, collector } from './presets.js';\n"]}
|
package/dist/live.d.ts
ADDED
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
import { type SpanExporter } from '@opentelemetry/sdk-trace-base';
|
|
2
|
+
import type { ModelPricing } from '@gnldev/durable';
|
|
3
|
+
export interface LiveCost {
|
|
4
|
+
inputTokens: number;
|
|
5
|
+
outputTokens: number;
|
|
6
|
+
cachedTokens: number;
|
|
7
|
+
totalTokens: number;
|
|
8
|
+
modelCalls: number;
|
|
9
|
+
toolCalls: number;
|
|
10
|
+
costUsd: number;
|
|
11
|
+
}
|
|
12
|
+
export interface LiveObservabilityOptions {
|
|
13
|
+
/** A ready-made OTEL SpanExporter (InMemorySpanExporter for tests). If not given, falls back to the endpoint or InMemory. */
|
|
14
|
+
exporter?: SpanExporter;
|
|
15
|
+
/** OTLP-HTTP endpoint (e.g. 'http://localhost:4318/v1/traces'). If exporter is not given, one is built from this (lazily). */
|
|
16
|
+
endpoint?: string;
|
|
17
|
+
/** Price table for cost calculation (default DEFAULT_PRICING). */
|
|
18
|
+
pricing?: Record<string, ModelPricing>;
|
|
19
|
+
/** service.name span attribute. */
|
|
20
|
+
serviceName?: string;
|
|
21
|
+
/** Sampling rate 0..1 (default 1 = all). instrument() kicks in with this probability. */
|
|
22
|
+
sampleRate?: number;
|
|
23
|
+
/** Called with the current running total cost after every model call (live budget alarm). */
|
|
24
|
+
onCost?: (cost: LiveCost) => void;
|
|
25
|
+
/**
|
|
26
|
+
* FINDING (roots leak guard): the `roots` Map holds one root span per new runId; normally this is
|
|
27
|
+
* cleared by `flush(runId)` (or plain `flush()` if never closed). If the caller forgets to do this
|
|
28
|
+
* (e.g. a long-lived multi-run server), the Map grows unbounded. This is the last-resort guardrail
|
|
29
|
+
* for that case: once the Map exceeds this size, the OLDEST (insertion-order) root is forcibly ended
|
|
30
|
+
* and removed. If not given, the guardrail is OFF (default behavior unchanged) — only opted-in callers
|
|
31
|
+
* get it. Kept simple: no TTL, just a size limit.
|
|
32
|
+
*/
|
|
33
|
+
maxPendingRuns?: number;
|
|
34
|
+
}
|
|
35
|
+
export interface LiveInstrumentArgs {
|
|
36
|
+
runId: string;
|
|
37
|
+
model: unknown;
|
|
38
|
+
tools?: Record<string, any>;
|
|
39
|
+
[k: string]: unknown;
|
|
40
|
+
}
|
|
41
|
+
export interface LiveObservability {
|
|
42
|
+
/** Wraps runDurable/streamDurable args to inject live tracing (model + tool). Returns the same type. */
|
|
43
|
+
instrument<T extends LiveInstrumentArgs>(args: T): T;
|
|
44
|
+
/** Total cost/tokens accumulated so far (live). */
|
|
45
|
+
cost(): LiveCost;
|
|
46
|
+
/**
|
|
47
|
+
* If `runId` is given, closes ONLY that run's root span + removes it from the `roots` Map (does not
|
|
48
|
+
* touch other concurrent runs) — this is the cleanup point that must be called as each run finishes
|
|
49
|
+
* in a multi-run scenario. If `runId` is omitted (old behavior, UNCHANGED), closes ALL open root spans
|
|
50
|
+
* + clears the Map entirely. In both cases forces a flush to the exporter.
|
|
51
|
+
*/
|
|
52
|
+
flush(runId?: string): Promise<void>;
|
|
53
|
+
/** Shut down the provider (exporter shutdown). */
|
|
54
|
+
shutdown(): Promise<void>;
|
|
55
|
+
/** The exporter used (if InMemorySpanExporter, tests can call getFinishedSpans()). */
|
|
56
|
+
exporter: SpanExporter;
|
|
57
|
+
/** Number of runs currently held in the `roots` Map (not yet closed via `flush(runId)`) — for leak monitoring. */
|
|
58
|
+
pendingRuns(): number;
|
|
59
|
+
}
|
|
60
|
+
export declare function liveObservability(opts?: LiveObservabilityOptions): LiveObservability;
|