@webmcp-agents/telemetry 0.0.0-stage → 0.6.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/dist/server.js ADDED
@@ -0,0 +1,1431 @@
1
+ import { a as failure, c as parseTraceparent, d as traceparentSampled, f as withMappedKeys, i as cleanAttributes, n as appAttributes, o as isSampled, r as around, s as keyValues, t as VERSION, u as registeredGlobalTrace } from "./util-5Bj-Z8Ym.js";
2
+ import { A as SCOPE_NAME, C as ATTR_USAGE_INPUT_TOKENS, D as EVENT_PARK, E as DEFAULT_AGENT_NAME, M as SPAN_CHAT, N as SPAN_EXECUTE_TOOL, O as EVENT_RESUME, P as SPAN_INVOKE_AGENT, S as ATTR_TOOL_WAITED_MS, T as ATTR_WEBMCP_AGENT_ID, _ as ATTR_TOOL_CALL_RESULT, a as ATTR_ERROR_TYPE, b as ATTR_TOOL_NAME, c as ATTR_PARENT_CALL_ID, d as ATTR_RUN_REASON, f as ATTR_RUN_STEPS, g as ATTR_TOOL_CALL_ID, h as ATTR_TOOL_CALL_ARGUMENTS, i as ATTR_CUSTOM, j as SCOPE_NAME_LEGACY, k as EVENT_YIELD, l as ATTR_REQUEST_MODEL, m as ATTR_STEP, n as ATTR_AGENT_ID, o as ATTR_OPERATION_NAME, p as ATTR_SESSION_ID, r as ATTR_CONVERSATION_ID, s as ATTR_PAGE, t as ATTR_ADAPTER, u as ATTR_RUN_ID, v as ATTR_TOOL_CONFIRM, w as ATTR_USAGE_OUTPUT_TOKENS, x as ATTR_TOOL_STATE, y as ATTR_TOOL_ERROR_CODE } from "./semconv-74esS-9v.js";
3
+ import { isCrossSite, validTraceparent } from "@webmcp-agents/chat/server";
4
+ import { createRedactor, getRedactor } from "@webmcp-agents/core/redact";
5
+ // src/server/config.ts
6
+ /** The three wire formats. */
7
+ const PROTOCOLS = [
8
+ "http/json",
9
+ "http/protobuf",
10
+ "grpc"
11
+ ];
12
+ const lower = (v) => (v ?? "").trim().toLowerCase();
13
+ /**
14
+ * `OTEL_SDK_DISABLED=true` (everything off, the relay drops) or `WEB_AGENTS_OTEL_ENABLED=false` (only this library).
15
+ * Returns which, or undefined when neither is set.
16
+ */
17
+ function killSwitch(env) {
18
+ if (lower(env.OTEL_SDK_DISABLED) === "true") return "OTEL_SDK_DISABLED";
19
+ if (lower(env.WEB_AGENTS_OTEL_ENABLED) === "false") return "WEB_AGENTS_OTEL_ENABLED";
20
+ }
21
+ /**
22
+ * `k=v,k2=v2` (OTel's list format: values percent-decoded, spaces trimmed). An entry with no `=` or an empty key is
23
+ * skipped and reported to `bad`; the others are kept.
24
+ */
25
+ function parseList(raw, bad = () => {}) {
26
+ const out = {};
27
+ for (const entry of (raw ?? "").split(",")) {
28
+ if (!entry.trim()) continue;
29
+ const at = entry.indexOf("=");
30
+ const key = at > 0 ? entry.slice(0, at).trim() : "";
31
+ if (!key) {
32
+ bad(entry.trim());
33
+ continue;
34
+ }
35
+ const value = entry.slice(at + 1).trim();
36
+ try {
37
+ out[decodeURIComponent(key)] = decodeURIComponent(value);
38
+ } catch {
39
+ bad(entry.trim());
40
+ }
41
+ }
42
+ return out;
43
+ }
44
+ /** The base URL with `/v1/traces` appended (OTel: relative to the base, one slash). */
45
+ const withTracesPath = (base) => `${base.replace(/\/+$/, "")}/v1/traces`;
46
+ const positive = (v) => {
47
+ const n = typeof v === "number" ? v : Number(v);
48
+ return v !== void 0 && v !== "" && Number.isFinite(n) && n > 0 ? n : void 0;
49
+ };
50
+ /**
51
+ * One OTLP target from its options, then the env: `endpoints.traces` (as given) › `endpoint` (+ `/v1/traces`) ›
52
+ * `OTEL_EXPORTER_OTLP_TRACES_ENDPOINT` (as given) › `OTEL_EXPORTER_OTLP_ENDPOINT` (+ `/v1/traces`). For `grpc` a base
53
+ * endpoint is used as given. An error string when it cannot be used: both endpoint forms, an unknown protocol, no URL.
54
+ */
55
+ function resolveOtlp(target, env, bad = () => {}) {
56
+ if (target.endpoint && target.endpoints) return { error: "an OTLP target has both `endpoint` and `endpoints`: give one (`endpoint` is a base URL, `endpoints.traces` an exact one)" };
57
+ const raw = target.protocol ?? (lower(env.OTEL_EXPORTER_OTLP_TRACES_PROTOCOL) || lower(env.OTEL_EXPORTER_OTLP_PROTOCOL) || "http/json");
58
+ if (!PROTOCOLS.includes(raw)) return { error: `unknown OTLP protocol "${raw}": use one of "http/json", "http/protobuf" or "grpc"` };
59
+ const protocol = raw;
60
+ const base = (url) => protocol === "grpc" ? url : withTracesPath(url);
61
+ const fromEnv = !target.endpoints?.traces && !target.endpoint;
62
+ const url = target.endpoints?.traces ?? (target.endpoint ? base(target.endpoint) : void 0) ?? (env.OTEL_EXPORTER_OTLP_TRACES_ENDPOINT?.trim() || void 0) ?? (env.OTEL_EXPORTER_OTLP_ENDPOINT?.trim() ? base(env.OTEL_EXPORTER_OTLP_ENDPOINT.trim()) : void 0);
63
+ if (!url) return { error: "an OTLP target has no URL: give it `endpoint` or set OTEL_EXPORTER_OTLP_ENDPOINT" };
64
+ try {
65
+ new URL(url);
66
+ } catch {
67
+ if (protocol !== "grpc") return { error: "an OTLP target's URL is not a valid URL" };
68
+ }
69
+ return {
70
+ url,
71
+ protocol,
72
+ headers: {
73
+ ...fromEnv && parseList(env.OTEL_EXPORTER_OTLP_HEADERS, bad),
74
+ ...fromEnv && parseList(env.OTEL_EXPORTER_OTLP_TRACES_HEADERS, bad),
75
+ ...target.headers
76
+ },
77
+ timeout: positive(target.timeout) ?? positive(env.OTEL_EXPORTER_OTLP_TRACES_TIMEOUT) ?? positive(env.OTEL_EXPORTER_OTLP_TIMEOUT) ?? 3e4
78
+ };
79
+ }
80
+ /**
81
+ * Where the env alone sends spans: the URL, or `"off"` (no endpoint variable, a kill switch, or a target that cannot
82
+ * be used). The design's table (§7.2) as a function.
83
+ *
84
+ * @example
85
+ * resolveTarget({}, { OTEL_EXPORTER_OTLP_ENDPOINT: "https://c.example" }) // "https://c.example/v1/traces"
86
+ */
87
+ function resolveTarget(target, env) {
88
+ if (killSwitch(env)) return "off";
89
+ const r = resolveOtlp(target, env);
90
+ return "error" in r ? "off" : r.url;
91
+ }
92
+ /**
93
+ * §7.2, first match wins: a kill switch › `tracerProvider` instance › `"global"` (required) › `exporters` /
94
+ * `spanProcessors` › a registered global provider (unless `"own"`) › an endpoint variable › off.
95
+ */
96
+ function resolveMode(config, env, globalRegistered) {
97
+ if (killSwitch(env)) return {
98
+ mode: "off",
99
+ off: "kill-switch"
100
+ };
101
+ const provider = config.tracerProvider;
102
+ if (provider && typeof provider === "object") return { mode: "provider" };
103
+ if (provider === "global") return globalRegistered ? { mode: "global" } : {
104
+ mode: "off",
105
+ off: "no-global-provider"
106
+ };
107
+ if (config.exporters?.length || config.spanProcessors?.length) return { mode: "private" };
108
+ if (provider !== "own" && globalRegistered) return { mode: "global" };
109
+ if (env.OTEL_EXPORTER_OTLP_TRACES_ENDPOINT?.trim() || env.OTEL_EXPORTER_OTLP_ENDPOINT?.trim()) return { mode: "private" };
110
+ return {
111
+ mode: "off",
112
+ off: "nothing-configured"
113
+ };
114
+ }
115
+ /**
116
+ * Sampling from `OTEL_TRACES_SAMPLER` / `OTEL_TRACES_SAMPLER_ARG`: `always_on`, `always_off`, `traceidratio`, and
117
+ * their `parentbased_*` forms read as the same (the browser's sampled flag is not trusted: the server decides).
118
+ * Undefined when unset; `bad` hears of an unknown sampler or a ratio that is not a number from 0 to 1.
119
+ */
120
+ function samplingFromEnv(env, bad = () => {}) {
121
+ const name = lower(env.OTEL_TRACES_SAMPLER).replace(/^parentbased_/, "");
122
+ if (!name) return void 0;
123
+ if (name === "always_on") return { type: "always" };
124
+ if (name === "always_off") return { type: "never" };
125
+ if (name === "traceidratio") {
126
+ const arg = env.OTEL_TRACES_SAMPLER_ARG?.trim();
127
+ const p = arg ? Number(arg) : 1;
128
+ if (!(p >= 0 && p <= 1)) {
129
+ bad(`OTEL_TRACES_SAMPLER_ARG "${arg}" is not a number from 0 to 1: every trace is sampled`);
130
+ return { type: "always" };
131
+ }
132
+ return {
133
+ type: "ratio",
134
+ probability: p
135
+ };
136
+ }
137
+ bad(`unknown OTEL_TRACES_SAMPLER "${env.OTEL_TRACES_SAMPLER}": use always_on, always_off or traceidratio. Every trace is sampled`);
138
+ }
139
+ /**
140
+ * The resource's attributes: `OTEL_RESOURCE_ATTRIBUTES`, then `OTEL_SERVICE_NAME`, then the options (`resourceAttributes`,
141
+ * then `serviceName`); `service.name` defaults to `"web-agents"`.
142
+ */
143
+ function resourceAttributes(options, env, bad = () => {}) {
144
+ const out = parseList(env.OTEL_RESOURCE_ATTRIBUTES, bad);
145
+ if (env.OTEL_SERVICE_NAME?.trim()) out["service.name"] = env.OTEL_SERVICE_NAME.trim();
146
+ Object.assign(out, options.resourceAttributes);
147
+ if (options.serviceName) out["service.name"] = options.serviceName;
148
+ out["service.name"] ||= "web-agents";
149
+ return out;
150
+ }
151
+ // src/server/log.ts
152
+ /**
153
+ * The layer's console output: each fault is logged once per observability instance (a hundred requests with the same
154
+ * bad exporter print one line), every thrown value through the redactor (a provider error can echo an API key).
155
+ */
156
+ const PREFIX = "[web-agents/telemetry]";
157
+ /** A fresh logger (one per `defineObservability()`). */
158
+ function createLog() {
159
+ const seen = /* @__PURE__ */ new Set();
160
+ const first = (key) => !seen.has(key) && !!seen.add(key);
161
+ return {
162
+ error(key, message, err) {
163
+ if (!first(key)) return;
164
+ let detail = "";
165
+ if (err !== void 0) try {
166
+ detail = `: ${getRedactor().error(err)}`;
167
+ } catch {
168
+ detail = "";
169
+ }
170
+ console.error(`${PREFIX} ${message}${detail}`);
171
+ },
172
+ info(key, message) {
173
+ if (first(key)) console.info(`${PREFIX} ${message}`);
174
+ }
175
+ };
176
+ }
177
+ // src/server/relay.ts
178
+ /**
179
+ * The relay (design §7.6): the app's own endpoint for the browser's spans, so no backend key reaches the page. The
180
+ * browser is not trusted: same-site requests only (a request without an `Origin` is refused by default), a size cap, OTLP JSON from this package's scope only, every value
181
+ * redacted again, the server's sampling (never the browser's flag). Spans then go through the same pipeline as the
182
+ * server's. It answers `202` with no body whatever happens upstream, and a refusal carries no detail.
183
+ */
184
+ /** The relay's default body cap: 256 KB. */
185
+ const RELAY_MAX_BYTES = 262144;
186
+ /** Spans accepted in one request; more is refused as malformed. */
187
+ const MAX_SPANS = 2048;
188
+ /** Attributes kept per span or event. */
189
+ const MAX_ATTRIBUTES = 128;
190
+ const empty = (status, headers = {}) => new Response(null, {
191
+ status,
192
+ headers: {
193
+ "cache-control": "no-store",
194
+ ...headers
195
+ }
196
+ });
197
+ /** The body as text, or null once it passes `limit` bytes (the rest is never read). */
198
+ async function readCapped(req, limit) {
199
+ const declared = Number(req.headers.get("content-length"));
200
+ if (Number.isFinite(declared) && declared > limit) return null;
201
+ if (!req.body) return "";
202
+ const reader = req.body.getReader();
203
+ const chunks = [];
204
+ let size = 0;
205
+ for (;;) {
206
+ const { done, value } = await reader.read();
207
+ if (done) break;
208
+ size += value.byteLength;
209
+ if (size > limit) {
210
+ await reader.cancel().catch(() => {});
211
+ return null;
212
+ }
213
+ chunks.push(value);
214
+ }
215
+ const bytes = new Uint8Array(size);
216
+ let at = 0;
217
+ for (const c of chunks) {
218
+ bytes.set(c, at);
219
+ at += c.byteLength;
220
+ }
221
+ return new TextDecoder().decode(bytes);
222
+ }
223
+ const isObject = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
224
+ /** An OTLP JSON `AnyValue` as an attribute value (scalars and arrays of scalars only), else undefined. */
225
+ function value(v, depth = 0) {
226
+ if (!isObject(v)) return void 0;
227
+ if (typeof v.stringValue === "string") return v.stringValue;
228
+ if (typeof v.boolValue === "boolean") return v.boolValue;
229
+ if (typeof v.doubleValue === "number") return v.doubleValue;
230
+ if (typeof v.intValue === "number" || typeof v.intValue === "string") {
231
+ const n = Number(v.intValue);
232
+ return Number.isSafeInteger(n) ? n : String(v.intValue);
233
+ }
234
+ if (depth === 0 && isObject(v.arrayValue) && Array.isArray(v.arrayValue.values)) return v.arrayValue.values.map((x) => value(x, 1));
235
+ }
236
+ /** OTLP JSON `KeyValue`s as attributes (at most {@link MAX_ATTRIBUTES}). */
237
+ const attributesOf = (list) => {
238
+ const out = {};
239
+ if (!Array.isArray(list)) return out;
240
+ for (const kv of list.slice(0, MAX_ATTRIBUTES)) if (isObject(kv) && typeof kv.key === "string" && kv.key) out[kv.key] = value(kv.value);
241
+ return out;
242
+ };
243
+ /** A unix-nanosecond string or number as `[s, ns]`, or undefined. */
244
+ const hrTime = (v) => {
245
+ const s = typeof v === "number" && Number.isFinite(v) ? String(Math.trunc(v)) : typeof v === "string" ? v.trim() : "";
246
+ if (!/^\d{1,21}$/.test(s)) return void 0;
247
+ const n = BigInt(s);
248
+ return [Number(n / 1000000000n), Number(n % 1000000000n)];
249
+ };
250
+ /** The browser's OTLP JSON as relay spans, redacted (`finalize`, `text`), or why it was refused. */
251
+ function decodeBrowserSpans(body, finalize, text) {
252
+ if (!isObject(body) || !Array.isArray(body.resourceSpans)) return "malformed";
253
+ const out = [];
254
+ for (const rs of body.resourceSpans) {
255
+ if (!isObject(rs) || !Array.isArray(rs.scopeSpans)) return "malformed";
256
+ for (const ss of rs.scopeSpans) {
257
+ if (!isObject(ss) || !Array.isArray(ss.spans)) return "malformed";
258
+ if (!isObject(ss.scope) || ss.scope.name !== "@webmcp-agents/telemetry") return "foreign-scope";
259
+ for (const s of ss.spans) {
260
+ if (out.length >= MAX_SPANS || !isObject(s)) return "malformed";
261
+ const traceId = typeof s.traceId === "string" ? s.traceId.toLowerCase() : "";
262
+ const spanId = typeof s.spanId === "string" ? s.spanId.toLowerCase() : "";
263
+ const parent = typeof s.parentSpanId === "string" && s.parentSpanId ? s.parentSpanId.toLowerCase() : void 0;
264
+ const start = hrTime(s.startTimeUnixNano);
265
+ const end = hrTime(s.endTimeUnixNano);
266
+ if (!/^[0-9a-f]{32}$/.test(traceId) || /^0+$/.test(traceId) || !/^[0-9a-f]{16}$/.test(spanId) || /^0+$/.test(spanId)) return "malformed";
267
+ if (parent && !/^[0-9a-f]{16}$/.test(parent) || typeof s.name !== "string" || !s.name || s.name.length > 512 || !start || !end) return "malformed";
268
+ const status = isObject(s.status) ? s.status : {};
269
+ const code = status.code === 1 || status.code === 2 ? status.code : 0;
270
+ out.push({
271
+ traceId,
272
+ spanId,
273
+ ...parent && { parentSpanId: parent },
274
+ name: text(s.name),
275
+ kind: typeof s.kind === "number" && s.kind >= 1 && s.kind <= 5 ? s.kind - 1 : 0,
276
+ startTime: start,
277
+ endTime: end,
278
+ attributes: finalize(attributesOf(s.attributes)),
279
+ events: (Array.isArray(s.events) ? s.events.slice(0, MAX_ATTRIBUTES) : []).flatMap((e) => {
280
+ const time = isObject(e) ? hrTime(e.timeUnixNano) : void 0;
281
+ return isObject(e) && typeof e.name === "string" && time ? [{
282
+ name: text(e.name),
283
+ time,
284
+ attributes: finalize(attributesOf(e.attributes))
285
+ }] : [];
286
+ }),
287
+ status: {
288
+ code,
289
+ ...typeof status.message === "string" && status.message && { message: text(status.message) }
290
+ }
291
+ });
292
+ }
293
+ }
294
+ }
295
+ return out;
296
+ }
297
+ const VERCEL_CONTEXT = Symbol.for("@vercel/request-context");
298
+ /** The host's `waitUntil`: on an argument after the request (a Worker's `ctx`), else Vercel's request context. */
299
+ function findWaitUntil(args) {
300
+ for (const arg of args) {
301
+ const fn = arg?.waitUntil;
302
+ if (typeof fn === "function") return fn.bind(arg);
303
+ }
304
+ try {
305
+ const fn = globalThis[VERCEL_CONTEXT]?.get?.()?.waitUntil;
306
+ return typeof fn === "function" ? fn : void 0;
307
+ } catch {
308
+ return;
309
+ }
310
+ }
311
+ /** The relay's `POST` handler (see the module comment for every rule). */
312
+ function createRelay(layer, options = {}) {
313
+ const maxBytes = options.maxBytes && options.maxBytes > 0 ? options.maxBytes : RELAY_MAX_BYTES;
314
+ return async (req, ...rest) => {
315
+ try {
316
+ if (req.method !== "POST") return empty(405, { allow: "POST" });
317
+ if (isCrossSite(req) || !options.allowMissingOrigin && !req.headers.get("origin")) return empty(403);
318
+ if (options.guard) {
319
+ let refused;
320
+ try {
321
+ refused = await options.guard(req);
322
+ } catch (err) {
323
+ layer.log.error("relay-guard", "the relay's guard threw: the request was refused", err);
324
+ return empty(500);
325
+ }
326
+ if (refused) return refused;
327
+ }
328
+ if (!/^application\/json\b/i.test(req.headers.get("content-type") ?? "")) return empty(415);
329
+ const raw = await readCapped(req, maxBytes);
330
+ if (raw === null) return empty(413);
331
+ let body;
332
+ try {
333
+ body = JSON.parse(raw);
334
+ } catch {
335
+ return empty(400);
336
+ }
337
+ const rt = await layer.runtime();
338
+ if (!rt) return empty(202);
339
+ const spans = decodeBrowserSpans(body, rt.finalize, layer.text);
340
+ if (!Array.isArray(spans)) return empty(400);
341
+ let extra = {};
342
+ try {
343
+ extra = cleanAttributes(options.attributes?.(req));
344
+ } catch (err) {
345
+ layer.log.error("relay-attributes", "the relay's attributes() threw: spans were forwarded without them", err);
346
+ }
347
+ try {
348
+ rt.relay(spans, extra, req);
349
+ findWaitUntil(rest)?.(layer.flush());
350
+ } catch (err) {
351
+ layer.log.error("relay-forward", "relayed spans could not be forwarded", err);
352
+ }
353
+ return empty(202);
354
+ } catch (err) {
355
+ layer.log.error("relay", "the relay failed on a request", err);
356
+ return empty(400);
357
+ }
358
+ };
359
+ }
360
+ // src/server/otlp-json.ts
361
+ /** `[s, ns]` as a decimal nanosecond string (exact: BigInt). */
362
+ const nanos = (t) => {
363
+ if (!t) return "0";
364
+ try {
365
+ return (BigInt(Math.trunc(t[0])) * 1000000000n + BigInt(Math.trunc(t[1]))).toString();
366
+ } catch {
367
+ return "0";
368
+ }
369
+ };
370
+ /** An OTLP JSON `ExportTraceServiceRequest` for these spans. */
371
+ function encodeSpans(spans) {
372
+ const byResource = /* @__PURE__ */ new Map();
373
+ for (const span of spans) {
374
+ let entry = byResource.get(span.resource);
375
+ if (!entry) {
376
+ entry = {
377
+ attributes: span.resource?.attributes ?? {},
378
+ scopes: /* @__PURE__ */ new Map()
379
+ };
380
+ byResource.set(span.resource, entry);
381
+ }
382
+ const scope = `${span.instrumentationScope?.name ?? ""}\u0000${span.instrumentationScope?.version ?? ""}`;
383
+ entry.scopes.set(scope, [...entry.scopes.get(scope) ?? [], span]);
384
+ }
385
+ return { resourceSpans: [...byResource.values()].map(({ attributes, scopes }) => ({
386
+ resource: { attributes: keyValues(attributes) },
387
+ scopeSpans: [...scopes.entries()].map(([key, list]) => {
388
+ const [name, version] = key.split("\0");
389
+ return {
390
+ scope: {
391
+ name,
392
+ ...version && { version }
393
+ },
394
+ spans: list.map((s) => {
395
+ const ctx = s.spanContext();
396
+ return {
397
+ traceId: ctx.traceId,
398
+ spanId: ctx.spanId,
399
+ ...s.parentSpanContext?.spanId && { parentSpanId: s.parentSpanContext.spanId },
400
+ name: s.name,
401
+ kind: (typeof s.kind === "number" ? s.kind : 0) + 1,
402
+ startTimeUnixNano: nanos(s.startTime),
403
+ endTimeUnixNano: nanos(s.endTime),
404
+ attributes: keyValues(s.attributes),
405
+ events: (s.events ?? []).map((e) => ({
406
+ name: e.name,
407
+ timeUnixNano: nanos(e.time),
408
+ attributes: keyValues(e.attributes)
409
+ })),
410
+ status: {
411
+ code: s.status?.code ?? 0,
412
+ ...s.status?.message && { message: s.status.message }
413
+ }
414
+ };
415
+ })
416
+ };
417
+ })
418
+ })) };
419
+ }
420
+ /**
421
+ * A `SpanExporter` posting OTLP JSON to `target.url`. Each export is aborted after `target.timeout` ms; a failed or
422
+ * refused export reports failure to the pipeline (which logs it once) and is never retried.
423
+ */
424
+ function httpJsonExporter(target) {
425
+ return {
426
+ export(spans, done) {
427
+ const ctrl = new AbortController();
428
+ const timer = setTimeout(() => ctrl.abort(), target.timeout);
429
+ timer.unref?.();
430
+ let body;
431
+ try {
432
+ body = JSON.stringify(encodeSpans(spans));
433
+ } catch (error) {
434
+ clearTimeout(timer);
435
+ done({
436
+ code: 1,
437
+ error
438
+ });
439
+ return;
440
+ }
441
+ fetch(target.url, {
442
+ method: "POST",
443
+ headers: {
444
+ "content-type": "application/json",
445
+ ...target.headers
446
+ },
447
+ body,
448
+ signal: ctrl.signal
449
+ }).then(async (res) => {
450
+ await res.text().catch(() => "");
451
+ done(res.ok ? { code: 0 } : {
452
+ code: 1,
453
+ error: /* @__PURE__ */ new Error(`the collector answered ${res.status}`)
454
+ });
455
+ }, (error) => done({
456
+ code: 1,
457
+ error: error instanceof Error ? error : new Error(String(error))
458
+ })).finally(() => clearTimeout(timer));
459
+ },
460
+ async shutdown() {},
461
+ async forceFlush() {}
462
+ };
463
+ }
464
+ // src/server/peers.ts
465
+ /**
466
+ * How each peer is loaded. Mutable for this package's tests only (a missing package is simulated by replacing a
467
+ * loader); nothing else may change it.
468
+ *
469
+ * @internal
470
+ */
471
+ const peerLoaders = {
472
+ "@opentelemetry/api": () => import("@opentelemetry/api"),
473
+ "@ai-sdk/otel": () => import("@ai-sdk/otel"),
474
+ "@opentelemetry/sdk-trace": () => import("@opentelemetry/sdk-trace"),
475
+ "@opentelemetry/exporter-trace-otlp-proto": () => import("@opentelemetry/exporter-trace-otlp-proto"),
476
+ "@opentelemetry/exporter-trace-otlp-grpc": () => import("@opentelemetry/exporter-trace-otlp-grpc")
477
+ };
478
+ /** A peer that is not installed: the message names the package and the command that installs it. */
479
+ var MissingPeerError = class extends Error {
480
+ peer;
481
+ name = "MissingPeerError";
482
+ constructor(peer) {
483
+ super(`${peer} is not installed: add it to your dependencies (pnpm add ${peer}).`);
484
+ this.peer = peer;
485
+ }
486
+ };
487
+ const NOT_FOUND = /cannot find (module|package)|could not resolve|failed to (load|resolve)|is it installed|does the file exist/i;
488
+ /** True when `err` says `peer` itself could not be found (an error the package threw while loading is something else). */
489
+ function isMissingModule(err, peer) {
490
+ const e = err;
491
+ const message = typeof e?.message === "string" ? e.message : String(err);
492
+ if (!message.includes(peer)) return false;
493
+ return e?.code === "ERR_MODULE_NOT_FOUND" || e?.code === "MODULE_NOT_FOUND" || NOT_FOUND.test(message);
494
+ }
495
+ /** Load `peer`; a missing one rejects with {@link MissingPeerError}, any other failure as it is. */
496
+ async function loadPeer(peer) {
497
+ try {
498
+ return await peerLoaders[peer]();
499
+ } catch (err) {
500
+ if (isMissingModule(err, peer)) throw new MissingPeerError(peer);
501
+ throw err;
502
+ }
503
+ }
504
+ // src/server/pipeline.ts
505
+ /** A finished span with its attributes, events, status and name replaced (everything else read from `span`). */
506
+ function copySpan(span, name, attributes, events, status) {
507
+ const s = span;
508
+ const ctx = span.spanContext();
509
+ return {
510
+ name,
511
+ kind: span.kind,
512
+ spanContext: () => ctx,
513
+ parentSpanContext: span.parentSpanContext,
514
+ startTime: span.startTime,
515
+ endTime: span.endTime,
516
+ status,
517
+ attributes,
518
+ events,
519
+ instrumentationScope: span.instrumentationScope,
520
+ resource: span.resource,
521
+ links: s.links ?? [],
522
+ duration: s.duration,
523
+ ended: true,
524
+ droppedAttributesCount: s.droppedAttributesCount ?? 0,
525
+ droppedEventsCount: s.droppedEventsCount ?? 0,
526
+ droppedLinksCount: s.droppedLinksCount ?? 0
527
+ };
528
+ }
529
+ /** The last processor of a provider this package builds. Also takes the relay's spans (`push`). */
530
+ var Pipeline = class {
531
+ o;
532
+ #queue = [];
533
+ #timer;
534
+ #inflight = /* @__PURE__ */ new Set();
535
+ #closed = false;
536
+ constructor(o) {
537
+ this.o = o;
538
+ }
539
+ onStart() {}
540
+ onEnd(span) {
541
+ this.push(span);
542
+ }
543
+ /** A finished span: prepared, then queued for the next batch. */
544
+ push(span) {
545
+ if (this.#closed) return;
546
+ let out;
547
+ try {
548
+ out = this.prepare(span);
549
+ } catch (err) {
550
+ this.o.log.error("prepare", "a span could not be prepared for export and was dropped", err);
551
+ return;
552
+ }
553
+ if (!out) return;
554
+ this.#queue.push(out);
555
+ if (this.#queue.length >= this.o.batchSize) this.send();
556
+ else if (!this.#timer) {
557
+ this.#timer = setTimeout(() => void this.send(), this.o.delayMs);
558
+ this.#timer.unref?.();
559
+ }
560
+ }
561
+ /** metadataMapping → redaction → spanFilter. Undefined when the filter drops it. */
562
+ prepare(span) {
563
+ const attributes = { ...span.attributes };
564
+ for (const [from, to] of Object.entries(this.o.mapping)) if (attributes[from] !== void 0) attributes[to] = attributes[from];
565
+ const base = this.o.redactor();
566
+ const r = base && withMappedKeys(base, this.o.mapping);
567
+ const clean = (a) => r ? cleanAttributes(r(a ?? {}, { kind: "attribute" })) : cleanAttributes(a);
568
+ const out = copySpan(span, r ? r.text(span.name) : span.name, clean(attributes), (span.events ?? []).map((e) => ({
569
+ name: e.name,
570
+ time: e.time,
571
+ ...e.attributes && { attributes: clean(e.attributes) }
572
+ })), span.status?.message && r ? {
573
+ ...span.status,
574
+ message: r.text(span.status.message)
575
+ } : span.status ?? { code: 0 });
576
+ if (this.o.filter) try {
577
+ if (this.o.filter(out) === false) return void 0;
578
+ } catch (err) {
579
+ this.o.log.error("filter", "spanFilter threw: the span was dropped", err);
580
+ return;
581
+ }
582
+ return out;
583
+ }
584
+ /** Export everything queued, in batches. Resolves when each exporter answered or timed out. */
585
+ send() {
586
+ clearTimeout(this.#timer);
587
+ this.#timer = void 0;
588
+ const sends = [];
589
+ while (this.#queue.length) {
590
+ const batch = this.#queue.splice(0, this.o.batchSize);
591
+ if (this.o.debug) for (const s of batch) this.print(s);
592
+ for (const exporter of this.o.exporters) {
593
+ const p = this.exportOne(exporter, batch);
594
+ this.#inflight.add(p);
595
+ p.finally(() => this.#inflight.delete(p));
596
+ sends.push(p);
597
+ }
598
+ }
599
+ return Promise.all(sends).then(() => {});
600
+ }
601
+ /** One exporter, one batch: resolves on its callback, a throw, or the timeout, whichever first. */
602
+ exportOne(exporter, batch) {
603
+ return new Promise((resolve) => {
604
+ let settled = false;
605
+ const end = (failure) => {
606
+ if (settled) return;
607
+ settled = true;
608
+ clearTimeout(timer);
609
+ if (failure !== void 0) this.o.log.error("export", "an exporter failed; that batch was dropped (the chat is unaffected)", failure);
610
+ resolve();
611
+ };
612
+ const timer = setTimeout(() => end(/* @__PURE__ */ new Error(`no answer within ${this.o.timeout} ms`)), this.o.timeout);
613
+ timer.unref?.();
614
+ try {
615
+ exporter.export(batch, (result) => end(result?.code === 0 ? void 0 : result?.error ?? /* @__PURE__ */ new Error("export failed")));
616
+ } catch (err) {
617
+ end(err);
618
+ }
619
+ });
620
+ }
621
+ print(s) {
622
+ const ctx = s.spanContext();
623
+ console.log(`[web-agents/telemetry] span ${s.name}`, {
624
+ traceId: ctx.traceId,
625
+ spanId: ctx.spanId,
626
+ parentSpanId: s.parentSpanContext?.spanId,
627
+ attributes: s.attributes
628
+ });
629
+ }
630
+ /** Send what is queued and wait for it and every export in flight (each capped by its timeout). Never rejects. */
631
+ async forceFlush() {
632
+ await this.send();
633
+ await Promise.all([...this.#inflight]);
634
+ await Promise.all(this.o.exporters.map((x) => this.capped(() => x.forceFlush?.())));
635
+ }
636
+ /** Flush, then shut the exporters down. Spans arriving after are dropped. */
637
+ async shutdown() {
638
+ await this.forceFlush();
639
+ this.#closed = true;
640
+ await Promise.all(this.o.exporters.map((x) => this.capped(() => x.shutdown?.())));
641
+ }
642
+ capped(fn) {
643
+ return new Promise((resolve) => {
644
+ const timer = setTimeout(resolve, this.o.timeout);
645
+ timer.unref?.();
646
+ try {
647
+ Promise.resolve(fn()).catch((err) => this.o.log.error("exporter-flush", "an exporter failed to flush or shut down", err)).finally(() => {
648
+ clearTimeout(timer);
649
+ resolve();
650
+ });
651
+ } catch (err) {
652
+ clearTimeout(timer);
653
+ this.o.log.error("exporter-flush", "an exporter failed to flush or shut down", err);
654
+ resolve();
655
+ }
656
+ });
657
+ }
658
+ };
659
+ // src/server/tracer.ts
660
+ /** The AI SDK's wrapper spans (`invoke_agent`, `agent_step`), dropped when the browser's run span is the parent. */
661
+ const wrapper = (options) => {
662
+ const op = options?.attributes?.["gen_ai.operation.name"];
663
+ return op === "invoke_agent" || op === "agent_step";
664
+ };
665
+ /** A span whose attributes, events and status pass through `scope` before they reach the real span. */
666
+ function redactingSpan(span, scope) {
667
+ const own = {
668
+ spanContext: () => span.spanContext(),
669
+ setAttribute(key, value) {
670
+ if (value !== void 0) span.setAttributes(scope.finalize(cleanAttributes({ [key]: value })));
671
+ return own;
672
+ },
673
+ setAttributes(attributes) {
674
+ span.setAttributes(scope.finalize(cleanAttributes(attributes)));
675
+ return own;
676
+ },
677
+ addEvent(name, attributesOrTime, time) {
678
+ if (attributesOrTime && typeof attributesOrTime === "object" && !Array.isArray(attributesOrTime) && !(attributesOrTime instanceof Date)) span.addEvent(name, scope.finalize(cleanAttributes(attributesOrTime)), time);
679
+ else span.addEvent(name, attributesOrTime, time);
680
+ return own;
681
+ },
682
+ addLink(link) {
683
+ span.addLink(link);
684
+ return own;
685
+ },
686
+ addLinks(links) {
687
+ span.addLinks(links);
688
+ return own;
689
+ },
690
+ setStatus(status) {
691
+ span.setStatus(status.message ? {
692
+ ...status,
693
+ message: scope.text(status.message)
694
+ } : status);
695
+ return own;
696
+ },
697
+ updateName(name) {
698
+ span.updateName(scope.text(name));
699
+ return own;
700
+ },
701
+ end: (endTime) => span.end(endTime),
702
+ isRecording: () => span.isRecording(),
703
+ recordException(exception, time) {
704
+ const e = exception;
705
+ const type = typeof e === "object" && e && typeof e.name === "string" ? e.name : "Error";
706
+ const message = scope.text(typeof exception === "string" ? exception : typeof e?.message === "string" ? e.message : "");
707
+ span.recordException({
708
+ name: type,
709
+ message
710
+ }, time);
711
+ }
712
+ };
713
+ return own;
714
+ }
715
+ /** A tracer over `base` for one request (see the module comment). */
716
+ function requestTracer(api, base, scope) {
717
+ const parentOf = (ctx) => {
718
+ const c = ctx ?? api.context.active();
719
+ return !api.trace.getSpanContext(c) && scope.remote ? api.trace.setSpanContext(c, scope.remote) : c;
720
+ };
721
+ const startSpan = (name, options = {}, ctx) => {
722
+ const parent = parentOf(ctx);
723
+ const parentSpan = api.trace.getSpanContext(parent);
724
+ if (scope.remote && parentSpan && wrapper(options)) return api.trace.wrapSpanContext(parentSpan);
725
+ const attributes = scope.finalize({
726
+ ...scope.ids,
727
+ ...cleanAttributes(options.attributes)
728
+ });
729
+ if (scope.filter) {
730
+ let keep = true;
731
+ try {
732
+ keep = scope.filter(name, attributes) !== false;
733
+ } catch {
734
+ keep = false;
735
+ }
736
+ if (!keep) return api.trace.wrapSpanContext(parentSpan ?? api.INVALID_SPAN_CONTEXT);
737
+ }
738
+ const span = base.startSpan(scope.text(name), {
739
+ ...options,
740
+ attributes
741
+ }, parent);
742
+ if (!parentSpan) scope.root?.(span.spanContext());
743
+ return redactingSpan(span, scope);
744
+ };
745
+ return {
746
+ startSpan,
747
+ startActiveSpan(name, ...args) {
748
+ const fn = args.pop();
749
+ const [options, ctx] = args;
750
+ const parent = parentOf(ctx);
751
+ const span = startSpan(name, options, parent);
752
+ return api.context.with(api.trace.setSpan(parent, span), fn, void 0, span);
753
+ }
754
+ };
755
+ }
756
+ // src/server/runtime.ts
757
+ /** A minimal OpenTelemetry `Resource` (the SDK's interface), so `@opentelemetry/resources` need not be installed. */
758
+ function ownResource(attributes) {
759
+ const raw = Object.entries(attributes);
760
+ const resource = {
761
+ attributes,
762
+ schemaUrl: void 0,
763
+ asyncAttributesPending: false,
764
+ waitForAsyncAttributes: async () => {},
765
+ getRawAttributes: () => raw,
766
+ merge: (other) => other ? ownResource({
767
+ ...attributes,
768
+ ...cleanAttributes(other.attributes)
769
+ }) : resource
770
+ };
771
+ return resource;
772
+ }
773
+ /** The provider to call `forceFlush` on: the delegate behind the API's proxy, when it is one. */
774
+ const flushable = (provider) => {
775
+ const p = provider;
776
+ return typeof p?.getDelegate === "function" ? p.getDelegate() : p;
777
+ };
778
+ /**
779
+ * The app's registered global provider, or undefined. The API always hands out a proxy, registered or not: the
780
+ * registry's `trace` entry exists only after `setGlobalTracerProvider`, and its delegate must not be the no-op provider
781
+ * (compared by identity with this copy of the API's, and by name for another copy's) (open question 9).
782
+ */
783
+ function globalProvider(api) {
784
+ const registered = registeredGlobalTrace();
785
+ if (!registered) return void 0;
786
+ const delegate = typeof registered.getDelegate === "function" ? registered.getDelegate() : registered;
787
+ const noop = api ? new api.ProxyTracerProvider().getDelegate() : void 0;
788
+ if (!delegate || delegate === noop || delegate.constructor?.name === "NoopTracerProvider") return void 0;
789
+ return registered;
790
+ }
791
+ /** Build the layer, or null when it is off (each reason logged once). Never rejects for a configuration problem. */
792
+ async function buildRuntime(config, env, log, redactor) {
793
+ let api;
794
+ try {
795
+ api = await loadPeer("@opentelemetry/api");
796
+ } catch (err) {
797
+ return off(log, err);
798
+ }
799
+ const { mode, off: why } = resolveMode(config, env, !!globalProvider(api));
800
+ if (mode === "off") {
801
+ if (why === "no-global-provider") log.error("no-global", "telemetry is off: tracerProvider: \"global\" was set, but no tracer provider is registered. Register one first (any OpenTelemetry SDK setup does), or remove the option. The chat is unaffected.");
802
+ else if (why === "nothing-configured" && env.NODE_ENV === "development") log.info("nothing", "telemetry is off: set OTEL_EXPORTER_OTLP_ENDPOINT, pass exporters, or register a tracer provider.");
803
+ return null;
804
+ }
805
+ let otel;
806
+ try {
807
+ otel = await loadPeer("@ai-sdk/otel");
808
+ } catch (err) {
809
+ return off(log, err);
810
+ }
811
+ const attributes = resourceAttributes(config, env, (entry) => log.error("resource", `OTEL_RESOURCE_ATTRIBUTES has an entry without "=" ("${entry.slice(0, 40)}"): it was skipped`));
812
+ const finalize = (a) => {
813
+ const out = { ...a };
814
+ for (const [from, to] of Object.entries(config.metadataMapping ?? {})) if (out[from] !== void 0) out[to] = out[from];
815
+ const r = redactor();
816
+ return cleanAttributes(r ? withMappedKeys(r, config.metadataMapping ?? {})(out, { kind: "attribute" }) : out);
817
+ };
818
+ const text = (s) => {
819
+ const r = redactor();
820
+ return r ? r.text(s) : s;
821
+ };
822
+ const newPipeline = (exporters, given) => new Pipeline({
823
+ exporters,
824
+ redactor,
825
+ mapping: config.metadataMapping ?? {},
826
+ filter: config.spanFilter,
827
+ batchSize: Math.max(1, config.batchSize ?? 512),
828
+ delayMs: 5e3,
829
+ timeout: Math.max(...given.map((x) => "export" in x ? 0 : timeoutOf(x, env)), 1e3),
830
+ debug: config.debug ?? env.WEB_AGENTS_OTEL_DEBUG?.trim().toLowerCase() === "true",
831
+ log
832
+ });
833
+ let provider;
834
+ let pipeline;
835
+ if (mode === "provider") provider = config.tracerProvider;
836
+ else if (mode === "global") provider = globalProvider(api);
837
+ else {
838
+ let sdk;
839
+ try {
840
+ sdk = await loadPeer("@opentelemetry/sdk-trace");
841
+ } catch (err) {
842
+ return off(log, err);
843
+ }
844
+ const given = config.exporters?.length ? config.exporters : config.spanProcessors?.length ? [] : [{}];
845
+ const exporters = (await Promise.all(given.map((x, i) => toExporter(x, i, env, log)))).filter((x) => !!x);
846
+ if (!exporters.length && !config.spanProcessors?.length) {
847
+ log.error("no-exporter", "telemetry is off: no exporter could be set up (see the errors above). The chat is unaffected.");
848
+ return null;
849
+ }
850
+ pipeline = newPipeline(exporters, given);
851
+ try {
852
+ provider = new sdk.TracerProvider({
853
+ resource: ownResource(attributes),
854
+ sampler: new sdk.AlwaysOnSampler(),
855
+ spanProcessors: [...config.spanProcessors ?? [], pipeline]
856
+ });
857
+ } catch (err) {
858
+ log.error("provider", "telemetry is off: the tracer provider could not be created", err);
859
+ return null;
860
+ }
861
+ }
862
+ let relayPipeline;
863
+ if (mode !== "private" && config.relayThrough !== "provider") {
864
+ const given = config.exporters?.length ? config.exporters : "error" in resolveOtlp({}, env) ? [] : [{}];
865
+ const exporters = (await Promise.all(given.map((x, i) => toExporter(x, i, env, log)))).filter((x) => !!x);
866
+ if (exporters.length) relayPipeline = newPipeline(exporters, given);
867
+ else if (given.length) log.info("relay-provider", "relayed browser spans go through the app's tracer provider: no OTLP exporter could be set up for them");
868
+ }
869
+ const style = config.conventions ?? "genai";
870
+ const sampling = config.sampling ?? samplingFromEnv(env, (message) => log.error("sampler", `${message}.`));
871
+ const genai = style !== "legacy" ? provider.getTracer(SCOPE_NAME, VERSION) : void 0;
872
+ const legacy = style !== "genai" ? provider.getTracer(SCOPE_NAME_LEGACY, VERSION) : void 0;
873
+ const filter = config.spanFilter;
874
+ const startFilter = mode !== "private" && filter ? (name, a) => filter({
875
+ name,
876
+ kind: 0,
877
+ attributes: a,
878
+ spanContext: () => api.INVALID_SPAN_CONTEXT,
879
+ startTime: [0, 0],
880
+ endTime: [0, 0],
881
+ status: { code: 0 },
882
+ events: [],
883
+ instrumentationScope: {
884
+ name: SCOPE_NAME,
885
+ version: VERSION
886
+ },
887
+ resource: { attributes }
888
+ }) : void 0;
889
+ let requests;
890
+ try {
891
+ requests = new (await (import("node:async_hooks"))).AsyncLocalStorage();
892
+ } catch {}
893
+ const replayer = mode === "private" || relayPipeline ? void 0 : createReplayer(api, provider.getTracer(SCOPE_NAME, VERSION), attributes, filter, log);
894
+ const registered = globalProvider(api);
895
+ const sameAsGlobal = mode === "global" || mode === "provider" && !!registered && (provider === registered || provider === registered.getDelegate?.());
896
+ const otelClasses = [otel.OpenTelemetry, otel.LegacyOpenTelemetry];
897
+ /** The page's run span as the parent, only when its `traceparent` says the page records it (the sampled flag). */
898
+ const remoteOf = (traceparent) => {
899
+ const ids = parseTraceparent(traceparent);
900
+ return ids && traceparentSampled(traceparent) ? {
901
+ traceId: ids[0],
902
+ spanId: ids[1],
903
+ traceFlags: api.TraceFlags.SAMPLED,
904
+ isRemote: true
905
+ } : void 0;
906
+ };
907
+ /** The tracer of the app's own spans: this package's scope (the relay accepts it), through the request's redaction. */
908
+ const customTracer = provider.getTracer(SCOPE_NAME, VERSION);
909
+ return {
910
+ requests,
911
+ finalize,
912
+ startCustom(name, attributes, explicit) {
913
+ const frame = requests?.getStore();
914
+ const state = explicit && frame?.state.request !== explicit ? { request: explicit } : frame?.state ?? (explicit && { request: explicit });
915
+ if (!state) return void 0;
916
+ const traceparent = state.request.headers.get("traceparent");
917
+ state.sampled ??= isSampled(sampling, parseTraceparent(traceparent)?.[0], { request: state.request });
918
+ if (!state.sampled) return void 0;
919
+ const active = api.trace.getSpanContext(api.context.active());
920
+ const parent = frame?.state === state && frame.parent || (active && api.trace.isSpanContextValid(active) ? active : void 0) || remoteOf(traceparent) || state.root;
921
+ const ctx = parent ? api.trace.setSpanContext(api.context.active(), parent) : api.ROOT_CONTEXT;
922
+ const tracer = requestTracer(api, customTracer, {
923
+ ids: state.ids ?? {},
924
+ finalize,
925
+ text,
926
+ filter: startFilter
927
+ });
928
+ const startTime = performance.timeOrigin + performance.now();
929
+ const span = tracer.startSpan(name, {
930
+ kind: api.SpanKind.INTERNAL,
931
+ startTime,
932
+ attributes: cleanAttributes({
933
+ ...appAttributes(attributes),
934
+ [ATTR_CUSTOM]: true
935
+ })
936
+ }, ctx);
937
+ return {
938
+ end(error, instant) {
939
+ if (error !== void 0) {
940
+ const { type, message } = failure(error);
941
+ span.setAttribute(ATTR_ERROR_TYPE, type);
942
+ span.setStatus({
943
+ code: api.SpanStatusCode.ERROR,
944
+ message
945
+ });
946
+ }
947
+ span.end(instant ? startTime : void 0);
948
+ },
949
+ run(fn) {
950
+ const inner = () => api.context.with(api.trace.setSpan(api.context.active(), span), fn);
951
+ return requests ? requests.run({
952
+ state,
953
+ parent: span.spanContext()
954
+ }, inner) : inner();
955
+ }
956
+ };
957
+ },
958
+ sampled(ctx, request) {
959
+ const sc = {
960
+ agent: ctx.agent?.id,
961
+ conversation: ctx.trace?.conversation,
962
+ request: request ?? requests?.getStore()?.state.request
963
+ };
964
+ return isSampled(sampling, parseTraceparent(ctx.traceparent)?.[0], sc);
965
+ },
966
+ integrations(ctx) {
967
+ const state = requests?.getStore()?.state;
968
+ const scope = {
969
+ ids: cleanAttributes({
970
+ [ATTR_CONVERSATION_ID]: ctx.trace?.conversation,
971
+ [ATTR_RUN_ID]: ctx.trace?.run,
972
+ [ATTR_STEP]: ctx.trace?.step,
973
+ [ATTR_PARENT_CALL_ID]: ctx.trace?.parent,
974
+ [ATTR_WEBMCP_AGENT_ID]: ctx.agent?.id,
975
+ [ATTR_SESSION_ID]: ctx.session
976
+ }),
977
+ remote: remoteOf(ctx.traceparent),
978
+ finalize,
979
+ text,
980
+ filter: startFilter,
981
+ root: (sc) => {
982
+ if (state && !state.root) state.root = sc;
983
+ }
984
+ };
985
+ if (state) state.ids = scope.ids;
986
+ return [...genai ? [new otel.OpenTelemetry({
987
+ tracer: requestTracer(api, genai, scope),
988
+ agentSpanName: "functionId"
989
+ })] : [], ...legacy ? [new otel.LegacyOpenTelemetry({ tracer: requestTracer(api, legacy, scope) })] : []];
990
+ },
991
+ duplicates(integration) {
992
+ if (!sameAsGlobal || typeof integration !== "object" || integration === null) return false;
993
+ if (otelClasses.some((c) => integration instanceof c)) return true;
994
+ const name = integration.constructor?.name;
995
+ return name === "OpenTelemetry" || name === "LegacyOpenTelemetry";
996
+ },
997
+ async withParent(traceparent, run) {
998
+ const remote = remoteOf(traceparent);
999
+ if (!remote) return run();
1000
+ return api.context.with(api.trace.setSpanContext(api.context.active(), remote), run);
1001
+ },
1002
+ async flush() {
1003
+ if (pipeline) await provider.forceFlush();
1004
+ else await Promise.all([relayPipeline?.forceFlush(), flushable(provider).forceFlush?.()]);
1005
+ },
1006
+ async shutdown() {
1007
+ if (pipeline) await provider.shutdown();
1008
+ else {
1009
+ replayer?.releaseAll();
1010
+ await Promise.all([relayPipeline?.shutdown(), flushable(provider).forceFlush?.()]);
1011
+ }
1012
+ },
1013
+ relay(spans, extra, request) {
1014
+ const decided = /* @__PURE__ */ new Map();
1015
+ const kept = spans.filter((s) => {
1016
+ let keep = decided.get(s.traceId);
1017
+ if (keep === void 0) {
1018
+ keep = isSampled(sampling, s.traceId, { request });
1019
+ decided.set(s.traceId, keep);
1020
+ }
1021
+ return keep;
1022
+ });
1023
+ if (!kept.length) return;
1024
+ const out = pipeline ?? relayPipeline;
1025
+ if (out) {
1026
+ const resource = ownResource({
1027
+ ...attributes,
1028
+ ...extra
1029
+ });
1030
+ for (const s of kept) {
1031
+ const span = asReadable(s, resource);
1032
+ for (const p of pipeline ? config.spanProcessors ?? [] : []) try {
1033
+ p.onEnd(span);
1034
+ } catch (err) {
1035
+ log.error("processor", "a span processor threw on a relayed span", err);
1036
+ }
1037
+ out.push(span);
1038
+ }
1039
+ return;
1040
+ }
1041
+ replayer.relay(kept, extra);
1042
+ }
1043
+ };
1044
+ }
1045
+ /** Off because a package is missing or failed to load: one line naming it. */
1046
+ function off(log, err) {
1047
+ if (err instanceof MissingPeerError) log.error(`peer:${err.peer}`, `telemetry is off: ${err.message} The chat is unaffected.`);
1048
+ else log.error("load", "telemetry is off: a telemetry package failed to load. The chat is unaffected", err);
1049
+ return null;
1050
+ }
1051
+ /** The export timeout of one target (for the pipeline's cap and `flush`). */
1052
+ function timeoutOf(target, env) {
1053
+ const r = resolveOtlp(target, env);
1054
+ return "error" in r ? 0 : r.timeout;
1055
+ }
1056
+ /** One `exporters` entry as a `SpanExporter`, or undefined (logged once) when it cannot be used. */
1057
+ async function toExporter(entry, index, env, log) {
1058
+ if (typeof entry.export === "function") return entry;
1059
+ const target = resolveOtlp(entry, env, (header) => log.error(`header:${header}`, `OTEL_EXPORTER_OTLP_HEADERS has an entry that is not "key=value": it was skipped`));
1060
+ if ("error" in target) {
1061
+ log.error(`target:${index}`, `${target.error}. That target is off; the others still export`);
1062
+ return;
1063
+ }
1064
+ if (target.protocol === "http/json") return httpJsonExporter(target);
1065
+ const peer = target.protocol === "grpc" ? "@opentelemetry/exporter-trace-otlp-grpc" : "@opentelemetry/exporter-trace-otlp-proto";
1066
+ try {
1067
+ return new (await (loadPeer(peer))).OTLPTraceExporter({
1068
+ url: target.url,
1069
+ headers: target.headers,
1070
+ timeoutMillis: target.timeout
1071
+ });
1072
+ } catch (err) {
1073
+ if (err instanceof MissingPeerError) log.error(`peer:${peer}`, `the "${target.protocol}" target is off: ${err.message} Or use protocol "http/json", which needs nothing`);
1074
+ else log.error(`exporter:${index}`, `the "${target.protocol}" target is off: its exporter could not be created`, err);
1075
+ return;
1076
+ }
1077
+ }
1078
+ /** A relayed span as a `ReadableSpan`, under the server's resource and this package's scope. */
1079
+ function asReadable(s, resource) {
1080
+ const ctx = {
1081
+ traceId: s.traceId,
1082
+ spanId: s.spanId,
1083
+ traceFlags: 1,
1084
+ isRemote: true
1085
+ };
1086
+ const duration = [s.endTime[0] - s.startTime[0], s.endTime[1] - s.startTime[1]];
1087
+ if (duration[1] < 0) {
1088
+ duration[0] -= 1;
1089
+ duration[1] += 1e9;
1090
+ }
1091
+ return {
1092
+ name: s.name,
1093
+ kind: s.kind,
1094
+ spanContext: () => ctx,
1095
+ ...s.parentSpanId && { parentSpanContext: {
1096
+ traceId: s.traceId,
1097
+ spanId: s.parentSpanId,
1098
+ traceFlags: 1,
1099
+ isRemote: true
1100
+ } },
1101
+ startTime: s.startTime,
1102
+ endTime: s.endTime,
1103
+ status: s.status,
1104
+ attributes: s.attributes,
1105
+ events: s.events,
1106
+ instrumentationScope: {
1107
+ name: SCOPE_NAME,
1108
+ version: VERSION
1109
+ },
1110
+ resource,
1111
+ links: [],
1112
+ duration,
1113
+ ended: true,
1114
+ droppedAttributesCount: 0,
1115
+ droppedEventsCount: 0,
1116
+ droppedLinksCount: 0
1117
+ };
1118
+ }
1119
+ /** Browser span ids remembered, and children held, at most (each). */
1120
+ const MAX_KNOWN = 2e3;
1121
+ /** How long a child waits for its parent's batch before it goes under the page's ids. */
1122
+ const HOLD_MS = 3e4;
1123
+ /**
1124
+ * Relayed spans through a provider this package does not own (design §7.6): the fallback when no OTLP target resolves
1125
+ * for the relay in global / provider mode, or `relayThrough: "provider"`. The provider makes its own span ids, so a
1126
+ * span can be created only once its parent's new id is known: parents first within a batch, and across batches a
1127
+ * child whose parent has not arrived (the page sends a run's spans together, but flushes early on its caps, on
1128
+ * `pagehide`, and an older page sends every 2 s) is held until it does. A child held longer than {@link HOLD_MS}, or pushed out by {@link MAX_KNOWN} newer ones, goes under
1129
+ * the browser's parent id in the same trace. `spanFilter` runs on each span here (the private pipeline runs it on
1130
+ * its own); a skipped span hands its parent on to its children.
1131
+ */
1132
+ function createReplayer(api, tracer, resource, filter, log) {
1133
+ /** Browser span id → the context its children go under (the new span's, or a skipped span's parent). */
1134
+ const seen = /* @__PURE__ */ new Map();
1135
+ /** Held children by span id, oldest first. */
1136
+ const held = /* @__PURE__ */ new Map();
1137
+ /** Parent's browser span id → the ids of the children held for it. */
1138
+ const waiting = /* @__PURE__ */ new Map();
1139
+ let timer;
1140
+ const fallback = (s) => ({
1141
+ traceId: s.traceId,
1142
+ spanId: s.parentSpanId ?? s.spanId,
1143
+ traceFlags: api.TraceFlags.SAMPLED,
1144
+ isRemote: true
1145
+ });
1146
+ const keep = (s, extra) => {
1147
+ if (!filter) return true;
1148
+ try {
1149
+ return filter(asReadable(s, ownResource({
1150
+ ...resource,
1151
+ ...extra
1152
+ }))) !== false;
1153
+ } catch (err) {
1154
+ log.error("filter", "spanFilter threw: the span was dropped", err);
1155
+ return false;
1156
+ }
1157
+ };
1158
+ const place = (s, extra, parent) => {
1159
+ let ctx = parent;
1160
+ if (keep(s, extra)) try {
1161
+ const span = tracer.startSpan(s.name, {
1162
+ kind: s.kind,
1163
+ startTime: s.startTime,
1164
+ attributes: {
1165
+ ...s.attributes,
1166
+ ...extra
1167
+ }
1168
+ }, api.trace.setSpanContext(api.ROOT_CONTEXT, parent));
1169
+ for (const e of s.events) span.addEvent(e.name, e.attributes, e.time);
1170
+ if (s.status.code) span.setStatus({
1171
+ code: s.status.code,
1172
+ message: s.status.message
1173
+ });
1174
+ ctx = span.spanContext();
1175
+ span.end(s.endTime);
1176
+ } catch {}
1177
+ seen.set(s.spanId, ctx);
1178
+ if (seen.size > MAX_KNOWN) seen.delete(seen.keys().next().value);
1179
+ const kids = waiting.get(s.spanId);
1180
+ waiting.delete(s.spanId);
1181
+ for (const id of kids ?? []) {
1182
+ const h = held.get(id);
1183
+ if (!h) continue;
1184
+ held.delete(id);
1185
+ place(h.span, h.extra, ctx);
1186
+ }
1187
+ };
1188
+ /** Stop waiting for `h`'s parent: it goes under the browser's parent id. */
1189
+ const release = (h) => {
1190
+ if (!held.delete(h.span.spanId)) return;
1191
+ const siblings = waiting.get(h.span.parentSpanId);
1192
+ siblings?.delete(h.span.spanId);
1193
+ if (siblings && !siblings.size) waiting.delete(h.span.parentSpanId);
1194
+ place(h.span, h.extra, fallback(h.span));
1195
+ };
1196
+ const expire = () => {
1197
+ const now = Date.now();
1198
+ for (const h of held.values()) {
1199
+ if (now - h.at < HOLD_MS) break;
1200
+ release(h);
1201
+ }
1202
+ clearTimeout(timer);
1203
+ timer = void 0;
1204
+ const oldest = held.values().next().value;
1205
+ if (!oldest) return;
1206
+ timer = setTimeout(expire, Math.max(0, oldest.at + HOLD_MS - now));
1207
+ timer.unref?.();
1208
+ };
1209
+ return {
1210
+ relay(spans, extra) {
1211
+ const batch = new Map(spans.map((s) => [s.spanId, s]));
1212
+ const visit = (s) => {
1213
+ if (!batch.delete(s.spanId)) return;
1214
+ const p = s.parentSpanId;
1215
+ const parentInBatch = p ? batch.get(p) : void 0;
1216
+ if (parentInBatch) visit(parentInBatch);
1217
+ const known = p ? seen.get(p) : fallback(s);
1218
+ if (known) {
1219
+ place(s, extra, known);
1220
+ return;
1221
+ }
1222
+ held.set(s.spanId, {
1223
+ span: s,
1224
+ extra,
1225
+ at: Date.now()
1226
+ });
1227
+ let kids = waiting.get(p);
1228
+ if (!kids) {
1229
+ kids = /* @__PURE__ */ new Set();
1230
+ waiting.set(p, kids);
1231
+ }
1232
+ kids.add(s.spanId);
1233
+ if (held.size > MAX_KNOWN) release(held.values().next().value);
1234
+ };
1235
+ for (const s of spans) visit(s);
1236
+ expire();
1237
+ },
1238
+ /** Everything still held goes now (shutdown). */
1239
+ releaseAll() {
1240
+ for (const h of held.values()) release(h);
1241
+ clearTimeout(timer);
1242
+ timer = void 0;
1243
+ }
1244
+ };
1245
+ }
1246
+ // src/server/observability.ts
1247
+ /**
1248
+ * `defineObservability()` and `otlp()`: the chat handler's observability layer (design §7.3, §7.4). Lazy: nothing is
1249
+ * loaded and nothing is sent until the first request, and every fault (a missing package, bad env, a failing
1250
+ * exporter) is logged once and turns only the affected part off. A chat request's outcome and timing never depend on it.
1251
+ */
1252
+ /** The chat's `ChatObservability.exportTimeoutMs` default (how long the handler waits for a flush). */
1253
+ const DEFAULT_FLUSH_CAP = 5e3;
1254
+ /** The globally registered AI SDK integrations (`registerTelemetry`): read, never written (decision 4). */
1255
+ const appIntegrations = () => {
1256
+ const list = globalThis.AI_SDK_TELEMETRY_INTEGRATIONS;
1257
+ return Array.isArray(list) ? list : [];
1258
+ };
1259
+ const quiet = /* @__PURE__ */ new WeakMap();
1260
+ /**
1261
+ * An app's integration that never records content: every event it hears says `recordInputs` / `recordOutputs`
1262
+ * false. A call's flags reach every integration of the call; this layer's redact what they record, an app's would
1263
+ * export raw prompts (R-EXP-5). Its spans and timings are unchanged.
1264
+ */
1265
+ function withoutContent(integration) {
1266
+ if (typeof integration !== "object" || integration === null) return integration;
1267
+ let out = quiet.get(integration);
1268
+ if (!out) {
1269
+ const strip = (arg) => typeof arg === "object" && arg !== null && ("recordInputs" in arg || "recordOutputs" in arg) ? {
1270
+ ...arg,
1271
+ recordInputs: false,
1272
+ recordOutputs: false
1273
+ } : arg;
1274
+ out = new Proxy(integration, { get(target, key, receiver) {
1275
+ const value = Reflect.get(target, key, receiver);
1276
+ return typeof value === "function" ? (...args) => value.apply(target, args.map(strip)) : value;
1277
+ } });
1278
+ quiet.set(integration, out);
1279
+ }
1280
+ return out;
1281
+ }
1282
+ /**
1283
+ * The observability layer for `createChatHandler({ observability })`: every model step as an OpenTelemetry span,
1284
+ * with the run's ids, joined to the browser's run through its `traceparent`. Where spans go, first match wins: a
1285
+ * `tracerProvider` passed in › `exporters` / `spanProcessors` › a tracer provider the app registered (Sentry,
1286
+ * `@vercel/otel`, the OpenTelemetry SDK) › `OTEL_EXPORTER_OTLP_ENDPOINT` › off. It never registers anything globally.
1287
+ * `relay()` is the endpoint for the browser's spans.
1288
+ *
1289
+ * Needs `@opentelemetry/api` and `@ai-sdk/otel` installed (and `@opentelemetry/sdk-trace` unless the app has its own
1290
+ * provider); without them it is off, with one line saying which to install.
1291
+ *
1292
+ * @experimental
1293
+ *
1294
+ * @example
1295
+ * // app/api/chat/route.ts: everything else is OTEL_* env
1296
+ * export const POST = createChatHandler({ agents, observability: defineObservability() });
1297
+ */
1298
+ function defineObservability(config = {}) {
1299
+ const env = config.env ?? (typeof process !== "undefined" ? process.env : {});
1300
+ const log = createLog();
1301
+ const own = config.redact === false ? false : typeof config.redact === "function" ? config.redact : config.redact && createRedactor(config.redact);
1302
+ const redactor = () => own ?? getRedactor();
1303
+ const text = (s) => {
1304
+ const r = redactor();
1305
+ return r ? r.text(s) : s;
1306
+ };
1307
+ let built;
1308
+ let ready;
1309
+ const runtime = () => ready ??= buildRuntime(config, env, log, redactor).then((rt) => {
1310
+ built = rt;
1311
+ return rt;
1312
+ }, (err) => {
1313
+ log.error("build", "telemetry is off: it could not be set up. The chat is unaffected", err);
1314
+ built = null;
1315
+ return null;
1316
+ });
1317
+ const timeouts = (config.exporters ?? []).filter((x) => typeof x.export !== "function");
1318
+ const exportTimeoutMs = Math.max(DEFAULT_FLUSH_CAP, ...timeouts.map((t) => timeoutOf(t, env)), killSwitch(env) ? 0 : timeoutOf({}, env));
1319
+ /** Never rejects; settles within `exportTimeoutMs` at the latest. */
1320
+ const settle = (work) => new Promise((resolve) => {
1321
+ const timer = setTimeout(resolve, exportTimeoutMs);
1322
+ timer.unref?.();
1323
+ runtime().then((rt) => rt ? work(rt) : void 0).catch((err) => log.error("flush", "a flush failed; spans may be lost (the chat is unaffected)", err)).finally(() => {
1324
+ clearTimeout(timer);
1325
+ resolve();
1326
+ });
1327
+ });
1328
+ /** The app's own span, or undefined (not recorded, or the layer is not built: it builds on the first chat request). */
1329
+ const custom = (name, attributes, options) => {
1330
+ if (typeof name !== "string" || !name) return void 0;
1331
+ try {
1332
+ if (built === void 0 && options?.request) runtime();
1333
+ return built?.startCustom(name, attributes, options?.request);
1334
+ } catch (err) {
1335
+ log.error("custom", "a custom span or event was skipped (the app is unaffected)", err);
1336
+ return;
1337
+ }
1338
+ };
1339
+ return {
1340
+ get enabled() {
1341
+ if (built !== void 0) return built !== null;
1342
+ return resolveMode(config, env, !!globalProvider(void 0)).mode !== "off";
1343
+ },
1344
+ exportTimeoutMs,
1345
+ telemetry(ctx) {
1346
+ const rt = built;
1347
+ if (!rt) return {};
1348
+ const sampled = rt.sampled(ctx);
1349
+ const frame = rt.requests?.getStore();
1350
+ if (frame) frame.state.sampled = sampled;
1351
+ let app = appIntegrations();
1352
+ if (sampled && config.appIntegrations !== "keep") {
1353
+ const all = app.length;
1354
+ app = app.filter((x) => !rt.duplicates(x));
1355
+ if (app.length < all) log.info("dedupe", "the app's own @ai-sdk/otel integration was left out of the chat's model calls: this layer records the same steps into the same tracer provider (pass appIntegrations: \"keep\" to keep both)");
1356
+ }
1357
+ return {
1358
+ integrations: [...app.map(withoutContent), ...sampled ? rt.integrations(ctx) : []],
1359
+ recordInputs: config.recordInputs ?? false,
1360
+ recordOutputs: config.recordOutputs ?? false
1361
+ };
1362
+ },
1363
+ async withContext(req, run) {
1364
+ const rt = await runtime();
1365
+ if (!rt) return run();
1366
+ const go = () => rt.withParent(validTraceparent(req.headers.get("traceparent")) ?? null, run);
1367
+ return rt.requests ? rt.requests.run({ state: { request: req } }, go) : go();
1368
+ },
1369
+ flush: () => settle((rt) => rt.flush()),
1370
+ shutdown: () => settle((rt) => rt.shutdown()),
1371
+ relay: (options) => createRelay({
1372
+ runtime,
1373
+ text,
1374
+ flush: () => settle((rt) => rt.flush()),
1375
+ log
1376
+ }, options),
1377
+ event(name, attributes, options) {
1378
+ try {
1379
+ custom(name, attributes, options)?.end(void 0, true);
1380
+ } catch (err) {
1381
+ log.error("custom", "a custom event was skipped (the app is unaffected)", err);
1382
+ }
1383
+ },
1384
+ span(name, fn, attributes, options) {
1385
+ const s = custom(name, attributes, options);
1386
+ if (!s) return fn();
1387
+ let called = false;
1388
+ const end = (error) => {
1389
+ try {
1390
+ s.end(error);
1391
+ } catch (err) {
1392
+ log.error("custom", "a custom span could not be ended; it may be lost (the app is unaffected)", err);
1393
+ }
1394
+ };
1395
+ return around(() => {
1396
+ try {
1397
+ return s.run(() => {
1398
+ called = true;
1399
+ return fn();
1400
+ });
1401
+ } catch (err) {
1402
+ if (called) throw err;
1403
+ log.error("custom", "a custom span could not be entered; its code ran without it (the app is unaffected)", err);
1404
+ return fn();
1405
+ }
1406
+ }, end);
1407
+ }
1408
+ };
1409
+ }
1410
+ /**
1411
+ * An OTLP target. Fields left out fall back to the `OTEL_EXPORTER_OTLP_*` variables when the layer is built, so
1412
+ * `otlp()` alone means "whatever the env says". `endpoint` and `endpoints` together is a type error (and, at run time,
1413
+ * that target is off with an error).
1414
+ *
1415
+ * @experimental
1416
+ *
1417
+ * @example
1418
+ * defineObservability({
1419
+ * exporters: [
1420
+ * otlp({ endpoint: "https://otel.example.com", protocol: "http/protobuf", headers: { "x-api-key": process.env.OTEL_KEY! } }),
1421
+ * otlp({ endpoints: { traces: "https://traces.example.com/api/ingest/?tenant=acme" } }),
1422
+ * ],
1423
+ * });
1424
+ */
1425
+ function otlp(target = {}) {
1426
+ return {
1427
+ ...target,
1428
+ ...target.headers && { headers: { ...target.headers } }
1429
+ };
1430
+ }
1431
+ export { ATTR_ADAPTER, ATTR_AGENT_ID, ATTR_CONVERSATION_ID, ATTR_CUSTOM, ATTR_ERROR_TYPE, ATTR_OPERATION_NAME, ATTR_PAGE, ATTR_PARENT_CALL_ID, ATTR_REQUEST_MODEL, ATTR_RUN_ID, ATTR_RUN_REASON, ATTR_RUN_STEPS, ATTR_SESSION_ID, ATTR_STEP, ATTR_TOOL_CALL_ARGUMENTS, ATTR_TOOL_CALL_ID, ATTR_TOOL_CALL_RESULT, ATTR_TOOL_CONFIRM, ATTR_TOOL_ERROR_CODE, ATTR_TOOL_NAME, ATTR_TOOL_STATE, ATTR_TOOL_WAITED_MS, ATTR_USAGE_INPUT_TOKENS, ATTR_USAGE_OUTPUT_TOKENS, ATTR_WEBMCP_AGENT_ID, DEFAULT_AGENT_NAME, EVENT_PARK, EVENT_RESUME, EVENT_YIELD, RELAY_MAX_BYTES, SCOPE_NAME, SCOPE_NAME_LEGACY, SPAN_CHAT, SPAN_EXECUTE_TOOL, SPAN_INVOKE_AGENT, defineObservability, otlp, resolveTarget };