@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/README.md CHANGED
@@ -1,3 +1,39 @@
1
- # Temporary Holding Version
1
+ # @webmcp-agents/telemetry
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Send what your agents do to any OpenTelemetry backend. The chat handler exports every model step; the page exports each
4
+ run and tool call through your own relay endpoint, so no backend key reaches the browser; both land in one trace per
5
+ turn. Where spans go is the standard `OTEL_*` environment, or any OpenTelemetry exporter, processor or tracer provider
6
+ you pass as is: no vendor code here, and an app's own OpenTelemetry setup is used, never replaced. Content stays out
7
+ until you ask for it, and everything is redacted. **Experimental in 0.5.0.**
8
+
9
+ ```sh
10
+ pnpm add @webmcp-agents/telemetry @opentelemetry/api @opentelemetry/sdk-trace @ai-sdk/otel
11
+ ```
12
+
13
+ ```ts
14
+ // app/api/chat/route.ts: the server, one line; OTEL_EXPORTER_OTLP_ENDPOINT / _HEADERS say where
15
+ import { defineObservability } from "@webmcp-agents/telemetry/server";
16
+ export const observability = defineObservability();
17
+ export const POST = createChatHandler({ agents, observability });
18
+
19
+ // app/api/telemetry/route.ts: the relay for the browser's spans (same origin only; add your per-IP limit)
20
+ export const POST = observability.relay({ guard: perIp });
21
+ ```
22
+
23
+ ```tsx
24
+ // the page: each run and tool call, sent to /api/telemetry once the person agreed
25
+ import { ObserveAgents } from "@webmcp-agents/telemetry/react";
26
+ <ObserveAgents enabled={() => consent.analytics} />;
27
+ ```
28
+
29
+ | Entry | Contents |
30
+ |---|---|
31
+ | `@webmcp-agents/telemetry/server` | `defineObservability`, `otlp`, `observability.relay()`, `resolveTarget`, the span names |
32
+ | `@webmcp-agents/telemetry` | `observeAgents`, `consoleExporter`, the span names (about 0.7 KB up front; the span builder loads at the first consented run) |
33
+ | `@webmcp-agents/telemetry/react` | `<ObserveAgents>` |
34
+
35
+ The OpenTelemetry packages are optional peers, loaded on the first request: without them the layer is off and says
36
+ which to install. A missing package, bad env, a failing exporter or an unreachable backend is logged once and never
37
+ changes a chat request.
38
+
39
+ Docs: [webmcp-agents.dev/docs/reference/telemetry](https://webmcp-agents.dev/docs/reference/telemetry).
@@ -0,0 +1,76 @@
1
+ import { ROOT_CONTEXT, SpanKind, SpanStatusCode, trace } from "@opentelemetry/api";
2
+ // src/browser/bridge.ts
3
+ /**
4
+ * The bridge to a tracer provider the page already runs (the OpenTelemetry Web SDK, Sentry, Datadog RUM), or one
5
+ * passed in. Its own chunk: `@opentelemetry/api` is loaded only on pages that have a provider.
6
+ *
7
+ * A provider makes its own span ids, so a span here is created when it ends (with its recorded start time), its parent
8
+ * first. A run span is created under its `traceparent`'s span context, so it lands in the same trace as the server's
9
+ * step spans (which hang under that id).
10
+ */
11
+ /**
12
+ * A sink that turns span records into spans of `provider` (`"global"`: the page's registered one), under the
13
+ * instrumentation scope `scope` (passed in, so this chunk shares no module with the main one).
14
+ */
15
+ function createBridge(provider, scope, version) {
16
+ const source = provider === "global" ? trace.getTracerProvider() : provider;
17
+ const tracer = source.getTracer(scope, version);
18
+ const started = /* @__PURE__ */ new Map();
19
+ const live = /* @__PURE__ */ new Map();
20
+ const ensure = (id) => {
21
+ const known = live.get(id);
22
+ if (known) return known;
23
+ const r = started.get(id);
24
+ if (!r) return void 0;
25
+ const parent = r.parentSpanId && ensure(r.parentSpanId)?.ctx || trace.setSpanContext(ROOT_CONTEXT, {
26
+ traceId: r.traceId,
27
+ spanId: r.parentSpanId ?? r.spanId,
28
+ traceFlags: 1,
29
+ isRemote: true
30
+ });
31
+ const span = tracer.startSpan(r.name, {
32
+ startTime: r.startTime,
33
+ kind: SpanKind.INTERNAL
34
+ }, parent);
35
+ const made = {
36
+ span,
37
+ ctx: trace.setSpan(parent, span)
38
+ };
39
+ live.set(id, made);
40
+ return made;
41
+ };
42
+ const flushable = () => {
43
+ const p = source;
44
+ return typeof p.getDelegate === "function" ? p.getDelegate() : p;
45
+ };
46
+ return {
47
+ start(r) {
48
+ started.set(r.spanId, r);
49
+ },
50
+ end(r) {
51
+ if (!started.has(r.spanId)) started.set(r.spanId, r);
52
+ const made = ensure(r.spanId);
53
+ started.delete(r.spanId);
54
+ live.delete(r.spanId);
55
+ if (!made) return;
56
+ const { span } = made;
57
+ span.updateName(r.name);
58
+ span.setAttributes(r.attributes);
59
+ for (const e of r.events) span.addEvent(e.name, e.attributes, e.time);
60
+ if (r.status.code !== "unset") span.setStatus({
61
+ code: r.status.code === "error" ? SpanStatusCode.ERROR : SpanStatusCode.OK,
62
+ message: r.status.message
63
+ });
64
+ span.end(r.endTime);
65
+ },
66
+ drop(id) {
67
+ live.get(id)?.span.end();
68
+ live.delete(id);
69
+ started.delete(id);
70
+ },
71
+ async flush() {
72
+ await flushable().forceFlush?.().catch(() => {});
73
+ }
74
+ };
75
+ }
76
+ export { createBridge };
@@ -0,0 +1,420 @@
1
+ import { A as SCOPE_NAME, C as ATTR_USAGE_INPUT_TOKENS, D as EVENT_PARK, M as SPAN_CHAT, N as SPAN_EXECUTE_TOOL, O as EVENT_RESUME, P as SPAN_INVOKE_AGENT, S as ATTR_TOOL_WAITED_MS, _ 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, k as EVENT_YIELD, l as ATTR_REQUEST_MODEL, m as ATTR_STEP, n as ATTR_AGENT_ID, o as ATTR_OPERATION_NAME, 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";
2
+ import { a as failure, c as parseTraceparent, f as withMappedKeys, i as cleanAttributes, l as randomHex, n as appAttributes, o as isSampled, s as keyValues, t as VERSION, u as registeredGlobalTrace } from "./util-5Bj-Z8Ym.js";
3
+ import { createRedactor, getRedactor } from "@webmcp-agents/core/redact";
4
+ // src/browser/exporters.ts
5
+ /**
6
+ * The browser's built-in exporters: a POST of OTLP JSON to the app's relay (the default) or to a collector, and the
7
+ * console. No dependency: `fetch` and `JSON` only.
8
+ */
9
+ /** The relay's default path: `observability.relay()` mounted at `/api/telemetry`. */
10
+ const DEFAULT_RELAY = "/api/telemetry";
11
+ /** Milliseconds since the epoch as OTLP's nanosecond string. */
12
+ const ns = (ms) => String(Math.round(ms * 1e6));
13
+ /** An OTLP JSON `ExportTraceServiceRequest` for these spans, under one resource and this package's scope. */
14
+ const otlpBody = (resource, spans) => ({ resourceSpans: [{
15
+ resource: { attributes: keyValues(resource) },
16
+ scopeSpans: [{
17
+ scope: {
18
+ name: SCOPE_NAME,
19
+ version: VERSION
20
+ },
21
+ spans: spans.map((s) => ({
22
+ traceId: s.traceId,
23
+ spanId: s.spanId,
24
+ ...s.parentSpanId && { parentSpanId: s.parentSpanId },
25
+ name: s.name,
26
+ kind: 1,
27
+ startTimeUnixNano: ns(s.startTime),
28
+ endTimeUnixNano: ns(s.endTime),
29
+ attributes: keyValues(s.attributes),
30
+ events: s.events.map((e) => ({
31
+ name: e.name,
32
+ timeUnixNano: ns(e.time),
33
+ attributes: keyValues(e.attributes)
34
+ })),
35
+ status: {
36
+ code: s.status.code === "error" ? 2 : s.status.code === "ok" ? 1 : 0,
37
+ ...s.status.message && { message: s.status.message }
38
+ }
39
+ }))
40
+ }]
41
+ }] });
42
+ /**
43
+ * POSTs each batch as OTLP JSON. `keepalive` lets a batch sent while the page unloads arrive. A `404` / `405` means
44
+ * there is no relay at that URL: nothing more is sent. Failures are swallowed: telemetry never breaks the page.
45
+ */
46
+ function postExporter(url, resource, headers = {}) {
47
+ let gone = false;
48
+ return { export(spans) {
49
+ if (gone || !spans.length) return;
50
+ const body = JSON.stringify(otlpBody(resource, spans));
51
+ return fetch(url, {
52
+ method: "POST",
53
+ headers: {
54
+ "content-type": "application/json",
55
+ ...headers
56
+ },
57
+ body,
58
+ keepalive: new TextEncoder().encode(body).byteLength < 6e4,
59
+ credentials: "same-origin"
60
+ }).then((res) => {
61
+ if (res.status === 404 || res.status === 405) gone = true;
62
+ }, () => {});
63
+ } };
64
+ }
65
+ /** One error per problem, so a bad option logs once however many runs it affects. */
66
+ const said = /* @__PURE__ */ new Set();
67
+ const warnOnce = (message) => {
68
+ if (said.has(message)) return;
69
+ said.add(message);
70
+ console.error(`[web-agents/telemetry] ${message}`);
71
+ };
72
+ // src/browser/engine.ts
73
+ /** The adapter whose steps reach a server that makes the `chat` spans itself. */
74
+ const CLOUD_ADAPTER = "cloud";
75
+ const noop = () => {};
76
+ /** Spans of one run held at most; past it, what is held goes early (a body this size stays well under the relay's cap). */
77
+ const RUN_MAX_SPANS = 128;
78
+ /** How long a run's spans are held at most, ms: a run that goes on longer still exports. */
79
+ const RUN_MAX_HOLD_MS = 3e5;
80
+ /** Top-level runs remembered as sent, so a span that ends after its run (a call still open) is not held again. */
81
+ const MAX_DONE = 100;
82
+ /** `spans` with each one after its parent, when the parent is among them. */
83
+ const parentFirst = (spans) => {
84
+ const left = new Map(spans.map((s) => [s.spanId, s]));
85
+ const out = [];
86
+ const visit = (s) => {
87
+ if (!left.delete(s.spanId)) return;
88
+ const parent = s.parentSpanId ? left.get(s.parentSpanId) : void 0;
89
+ if (parent) visit(parent);
90
+ out.push(s);
91
+ };
92
+ for (const s of spans) visit(s);
93
+ return out;
94
+ };
95
+ /**
96
+ * Send batches to exporters. A run's spans are held until its top-level run ends, then sent as one batch, parents
97
+ * first; early, in the same order, once {@link RUN_MAX_SPANS} wait or after {@link RUN_MAX_HOLD_MS}, and on `flush`
98
+ * (the page hidden). Any other span goes at most every `batchMs`, sooner once `batchSize` wait.
99
+ */
100
+ function batchSink(exporters, batchMs, batchSize) {
101
+ const queue = [];
102
+ const inflight = /* @__PURE__ */ new Set();
103
+ const held = /* @__PURE__ */ new Map();
104
+ const done = /* @__PURE__ */ new Set();
105
+ let timer;
106
+ /** The run's held spans, parents first, as a batch of their own (and what is queued with them). */
107
+ const release = (root) => {
108
+ const group = held.get(root);
109
+ if (!group) return;
110
+ held.delete(root);
111
+ clearTimeout(group.timer);
112
+ send([parentFirst(group.spans)]);
113
+ };
114
+ /** The top-level run ended: send what it held, and never hold for it again. */
115
+ const finished = (root) => {
116
+ done.add(root);
117
+ if (done.size > MAX_DONE) done.delete(done.values().next().value);
118
+ release(root);
119
+ };
120
+ const send = (runs = []) => {
121
+ clearTimeout(timer);
122
+ timer = void 0;
123
+ const batches = runs.filter((b) => b.length);
124
+ while (queue.length) batches.push(queue.splice(0, batchSize));
125
+ const sent = exporters.then((xs) => Promise.all(xs.flatMap((x) => batches.map(async (batch) => {
126
+ await x.export(batch);
127
+ })))).catch(noop);
128
+ inflight.add(sent);
129
+ sent.then(() => inflight.delete(sent));
130
+ return sent;
131
+ };
132
+ return {
133
+ end(span, root) {
134
+ if (!root || done.has(root)) {
135
+ queue.push(span);
136
+ if (queue.length >= batchSize) send();
137
+ else timer ??= setTimeout(() => send(), batchMs);
138
+ return;
139
+ }
140
+ let group = held.get(root);
141
+ if (!group) {
142
+ group = {
143
+ spans: [],
144
+ timer: setTimeout(() => release(root), RUN_MAX_HOLD_MS)
145
+ };
146
+ held.set(root, group);
147
+ }
148
+ group.spans.push(span);
149
+ if (span.spanId === root) finished(root);
150
+ else if (group.spans.length >= RUN_MAX_SPANS) release(root);
151
+ },
152
+ drop(spanId, root) {
153
+ if (spanId === root) finished(root);
154
+ },
155
+ async flush() {
156
+ const runs = [...held.keys()].map((root) => {
157
+ const group = held.get(root);
158
+ held.delete(root);
159
+ clearTimeout(group.timer);
160
+ return parentFirst(group.spans);
161
+ });
162
+ await Promise.all([...inflight, send(runs)]);
163
+ await exporters.then((xs) => Promise.all(xs.map((x) => x.flush?.()))).catch(noop);
164
+ }
165
+ };
166
+ }
167
+ /** The bridge chunk, loaded on first use. Every operation waits on the same promise, so they run in order. */
168
+ function bridgeSink(provider) {
169
+ const ready = import("./bridge-n3EZZQrm.js").then((m) => m.createBridge(provider, SCOPE_NAME, VERSION), (err) => warnOnce(`browser spans are off: @opentelemetry/api could not be loaded (${getRedactor().error(err)})`));
170
+ const on = (op) => (arg) => void ready.then((s) => s && op(s, arg)).catch(noop);
171
+ return {
172
+ start: on((s, span) => s.start?.(span)),
173
+ end: on((s, span) => s.end(span)),
174
+ drop: on((s, id) => s.drop?.(id)),
175
+ flush: () => ready.then((s) => s?.flush()).catch(noop)
176
+ };
177
+ }
178
+ /** §7.2's order in the browser: a provider passed in, `exporters`, the page's global provider, the relay. */
179
+ function chooseSink(options) {
180
+ const { tracerProvider: provider, exporters, batchMs = 2e3 } = options;
181
+ const batchSize = Math.max(1, options.batchSize ?? 64);
182
+ if (provider && typeof provider === "object") return bridgeSink(provider);
183
+ const global = registeredGlobalTrace();
184
+ if (provider === "global" && !global) {
185
+ warnOnce("tracerProvider: \"global\" was set but the page registered no tracer provider: browser spans are off");
186
+ return;
187
+ }
188
+ if (provider === "global" || provider !== "own" && !exporters && global) return bridgeSink("global");
189
+ const resource = {
190
+ "service.name": options.serviceName ?? location.host,
191
+ "telemetry.sdk.language": "webjs"
192
+ };
193
+ if (!exporters) return batchSink(Promise.resolve([postExporter(DEFAULT_RELAY, resource)]), batchMs, batchSize);
194
+ if (!exporters.length) return void 0;
195
+ return batchSink(import("./targets-vd2wpXrO.js").then((m) => exporters.flatMap((x) => m.toExporter(x, resource, postExporter, warnOnce) ?? []), () => []), batchMs, batchSize);
196
+ }
197
+ /** JSON of a tool input or output for a span attribute; what cannot be serialized is left out. */
198
+ const json = (value) => {
199
+ try {
200
+ return value === void 0 ? void 0 : JSON.stringify(value);
201
+ } catch {
202
+ return;
203
+ }
204
+ };
205
+ /** Custom spans open at most; past it the oldest is forgotten (a `withAgentSpan` whose promise never settles). */
206
+ const MAX_CUSTOM_OPEN = 256;
207
+ /** The engine for these options, or undefined when there is nowhere to send (logged once when that is a mistake). */
208
+ function createEngine(options) {
209
+ const sink = chooseSink(options);
210
+ if (!sink) return void 0;
211
+ const { recordInputs, recordOutputs, sampling, spanFilter, metadataMapping = {}, redact } = options;
212
+ const own = redact === false ? false : typeof redact === "function" ? redact : redact && createRedactor(redact);
213
+ const runs = /* @__PURE__ */ new Map();
214
+ const calls = /* @__PURE__ */ new Map();
215
+ const epoch = (at) => performance.timeOrigin + at;
216
+ /** `fn()`, or `fallback` when it throws: an app's callback never breaks a run. */
217
+ const safe = (fn, fallback) => {
218
+ try {
219
+ return fn();
220
+ } catch {
221
+ return fallback;
222
+ }
223
+ };
224
+ const begin = (name, traceId, parentSpanId, at, attributes, spanId = randomHex(8), root) => {
225
+ const rec = {
226
+ name,
227
+ traceId,
228
+ spanId,
229
+ parentSpanId,
230
+ startTime: epoch(at),
231
+ endTime: 0,
232
+ attributes,
233
+ events: [],
234
+ status: { code: "unset" }
235
+ };
236
+ sink.start?.(rec);
237
+ return {
238
+ rec,
239
+ root: root ?? spanId
240
+ };
241
+ };
242
+ const finish = ({ rec, root }, endTime) => {
243
+ const attributes = { ...rec.attributes };
244
+ for (const [from, to] of Object.entries(metadataMapping)) if (attributes[from] !== void 0) attributes[to] = attributes[from];
245
+ const base = own ?? getRedactor();
246
+ const r = base && withMappedKeys(base, metadataMapping);
247
+ const clean = (a) => cleanAttributes(r ? r(a, { kind: "attribute" }) : a);
248
+ const text = (t) => r ? r.text(t) : t;
249
+ const out = {
250
+ ...rec,
251
+ name: text(rec.name),
252
+ endTime: Math.max(endTime, rec.startTime),
253
+ attributes: clean(attributes),
254
+ events: rec.events.map((e) => ({
255
+ ...e,
256
+ name: text(e.name),
257
+ attributes: clean(e.attributes ?? {})
258
+ })),
259
+ status: rec.status.message ? {
260
+ ...rec.status,
261
+ message: text(rec.status.message)
262
+ } : rec.status
263
+ };
264
+ if (safe(() => spanFilter?.(out) !== false, false)) sink.end(out, root);
265
+ else sink.drop?.(rec.spanId, root);
266
+ };
267
+ const handle = (e, consent, kept) => {
268
+ const run = runs.get(e.ref.run);
269
+ const step = "step" in e ? e.step : void 0;
270
+ const call = "call" in e ? calls.get(e.call) : void 0;
271
+ const ids = {
272
+ [ATTR_CONVERSATION_ID]: e.ref.conversation,
273
+ [ATTR_RUN_ID]: e.ref.run
274
+ };
275
+ const child = (name, operation, at, attributes) => begin(name, run.span.rec.traceId, run.span.rec.spanId, at, {
276
+ [ATTR_OPERATION_NAME]: operation,
277
+ [ATTR_STEP]: step,
278
+ ...ids,
279
+ ...attributes
280
+ }, void 0, run.span.root);
281
+ if (e.type === "run-start") {
282
+ const parent = e.ref.parent ? calls.get(e.ref.parent) : void 0;
283
+ const ref = parseTraceparent(e.ref.traceparent);
284
+ const traceId = parent?.rec.traceId || ref?.[0] || randomHex(16);
285
+ if (e.ref.parent ? !parent : !(consent && (kept ?? isSampled(sampling, traceId, {
286
+ agent: e.agent,
287
+ conversation: e.ref.conversation
288
+ })))) return;
289
+ e.ref.sampled = true;
290
+ const span = begin(`${SPAN_INVOKE_AGENT} ${e.agent ?? "web-agent"}`, traceId, parent ? parent.rec.spanId : void 0, e.at, {
291
+ [ATTR_OPERATION_NAME]: SPAN_INVOKE_AGENT,
292
+ [ATTR_AGENT_ID]: e.agent,
293
+ ...ids,
294
+ [ATTR_PARENT_CALL_ID]: e.ref.parent,
295
+ [ATTR_ADAPTER]: e.adapter,
296
+ [ATTR_PAGE]: location.href
297
+ }, ref?.[1], parent?.root);
298
+ runs.set(e.ref.run, {
299
+ span,
300
+ adapter: e.adapter,
301
+ steps: /* @__PURE__ */ new Map()
302
+ });
303
+ } else if (!run) return;
304
+ else if (e.type === "step-start") {
305
+ if (run.adapter !== CLOUD_ADAPTER) run.steps.set(e.step, child(SPAN_CHAT, SPAN_CHAT, e.at, {}));
306
+ } else if (e.type === "step-finish") {
307
+ const open = run.steps.get(e.step);
308
+ if (!open) return;
309
+ run.steps.delete(e.step);
310
+ if (e.model) open.rec.name += ` ${e.model}`;
311
+ Object.assign(open.rec.attributes, {
312
+ [ATTR_REQUEST_MODEL]: e.model,
313
+ [ATTR_USAGE_INPUT_TOKENS]: e.usage?.inputTokens,
314
+ [ATTR_USAGE_OUTPUT_TOKENS]: e.usage?.outputTokens
315
+ });
316
+ finish(open, open.rec.startTime + e.ms);
317
+ } else if (e.type === "tool-start") calls.set(e.call, child(`${SPAN_EXECUTE_TOOL} ${e.tool}`, SPAN_EXECUTE_TOOL, e.at, {
318
+ [ATTR_TOOL_NAME]: e.tool,
319
+ [ATTR_TOOL_CALL_ID]: e.call,
320
+ [ATTR_TOOL_CALL_ARGUMENTS]: recordInputs ? json(e.input) : void 0
321
+ }));
322
+ else if (!call && e.type !== "run-finish") return;
323
+ else if (e.type === "tool-park") {
324
+ call.parked = true;
325
+ call.rec.events.push({
326
+ name: EVENT_PARK,
327
+ time: epoch(e.at),
328
+ attributes: { prompt: e.prompt }
329
+ });
330
+ } else if (e.type === "tool-yield") {
331
+ call.yielded = true;
332
+ call.rec.events.push({
333
+ name: EVENT_YIELD,
334
+ time: epoch(e.at),
335
+ attributes: { reason: e.reason }
336
+ });
337
+ } else if (e.type === "tool-finish") {
338
+ calls.delete(e.call);
339
+ const failed = e.state === "error";
340
+ Object.assign(call.rec.attributes, {
341
+ [ATTR_TOOL_STATE]: e.state,
342
+ [ATTR_TOOL_WAITED_MS]: Math.round(e.waitedMs),
343
+ [ATTR_TOOL_ERROR_CODE]: e.code,
344
+ [ATTR_TOOL_CONFIRM]: call.parked ? e.state === "done" ? "accepted" : e.code === "needs_user" ? "timeout" : "cancelled" : void 0,
345
+ [ATTR_TOOL_CALL_RESULT]: recordOutputs ? json(e.output) : void 0,
346
+ [ATTR_ERROR_TYPE]: failed ? e.code ?? "failed" : void 0
347
+ });
348
+ if (failed) call.rec.status = { code: "error" };
349
+ finish(call, call.rec.startTime + e.ms);
350
+ } else if (e.type === "run-finish") {
351
+ runs.delete(e.ref.run);
352
+ const end = run.span.rec.startTime + e.ms;
353
+ for (const open of run.steps.values()) finish(open, end);
354
+ const failed = e.reason === "error";
355
+ Object.assign(run.span.rec.attributes, {
356
+ [ATTR_RUN_REASON]: e.reason,
357
+ [ATTR_RUN_STEPS]: e.steps,
358
+ [ATTR_ERROR_TYPE]: failed ? e.code ?? "error" : void 0
359
+ });
360
+ if (failed) run.span.rec.status = {
361
+ code: "error",
362
+ message: e.error
363
+ };
364
+ finish(run.span, end);
365
+ }
366
+ };
367
+ const customs = /* @__PURE__ */ new Map();
368
+ const custom = (op) => {
369
+ if (op.type === "end") {
370
+ const open = customs.get(op.id);
371
+ if (!open) return;
372
+ customs.delete(op.id);
373
+ if (op.error !== void 0) {
374
+ const { type, message } = failure(op.error);
375
+ open.rec.attributes[ATTR_ERROR_TYPE] = type;
376
+ open.rec.status = {
377
+ code: "error",
378
+ message
379
+ };
380
+ }
381
+ finish(open, epoch(op.at));
382
+ return;
383
+ }
384
+ const run = runs.get(op.run);
385
+ if (!run) return;
386
+ if (op.type === "event") {
387
+ run.span.rec.events.push({
388
+ name: op.name,
389
+ time: epoch(op.at),
390
+ attributes: appAttributes(op.attributes)
391
+ });
392
+ return;
393
+ }
394
+ const parent = op.call && calls.get(op.call) || run.span;
395
+ const ids = run.span.rec.attributes;
396
+ customs.set(op.id, begin(op.name, parent.rec.traceId, parent.rec.spanId, op.at, {
397
+ ...appAttributes(op.attributes),
398
+ [ATTR_CUSTOM]: true,
399
+ [ATTR_CONVERSATION_ID]: ids[ATTR_CONVERSATION_ID],
400
+ [ATTR_RUN_ID]: ids[ATTR_RUN_ID],
401
+ [ATTR_TOOL_CALL_ID]: parent === run.span ? void 0 : op.call
402
+ }, void 0, run.span.root));
403
+ if (customs.size > MAX_CUSTOM_OPEN) customs.delete(customs.keys().next().value);
404
+ };
405
+ return {
406
+ event: (e, consent, kept) => safe(() => handle(e, consent, kept), void 0),
407
+ custom: (op) => safe(() => custom(op), void 0),
408
+ resume() {
409
+ for (const call of calls.values()) if (call.yielded) {
410
+ call.yielded = false;
411
+ call.rec.events.push({
412
+ name: EVENT_RESUME,
413
+ time: Date.now()
414
+ });
415
+ }
416
+ },
417
+ flush: () => sink.flush()
418
+ };
419
+ }
420
+ export { createEngine };
@@ -0,0 +1,90 @@
1
+ /**
2
+ * @webmcp-agents/telemetry: the browser side. Observe the page's agent runs and send them, as OpenTelemetry spans, to
3
+ * the app's relay (`/api/telemetry`) or to the page's own OpenTelemetry provider.
4
+ *
5
+ * import { observeAgents } from "@webmcp-agents/telemetry";
6
+ * observeAgents({ enabled: () => consent.analytics });
7
+ *
8
+ * The server side (`defineObservability`, the relay) is `@webmcp-agents/telemetry/server`; React's one line is
9
+ * `<ObserveAgents />` from `@webmcp-agents/telemetry/react`. Everything here is experimental in 0.5.0.
10
+ */
11
+ import { n as ObserveAgentsOptions, r as SpanRecord, t as BrowserSpanExporter } from "./types-8Tdrt7C_.js";
12
+ import { a as ReadableSpanLike, c as SpanExporter, d as TracerProviderOption, i as OtlpTarget, l as SpanProcessor, n as Attributes, o as Sampling, r as CustomAttributes, s as SamplingContext, t as AttributeValue, u as TracerProvider } from "./types-Bqk6T-HL.js";
13
+ 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-BXKrNtuf.js";
14
+ import { RunRef } from "@webmcp-agents/chat";
15
+ /**
16
+ * An exporter that prints each finished span to the console instead of sending it: for development, and to see what
17
+ * would leave the page. Spans are already redacted when they reach it. No request is made.
18
+ *
19
+ * @experimental
20
+ *
21
+ * @example
22
+ * import { consoleExporter, observeAgents } from "@webmcp-agents/telemetry";
23
+ * observeAgents({ exporters: [consoleExporter()] });
24
+ */
25
+ export declare function consoleExporter(): BrowserSpanExporter;
26
+ /**
27
+ * Options for `recordAgentEvent()` / `withAgentSpan()`.
28
+ *
29
+ * @experimental
30
+ */
31
+ interface AgentSpanOptions {
32
+ /**
33
+ * The run to attach to: a run id or a `RunRef` (from `onAgentRun`). Default: the run that is running now, the most
34
+ * recently started top-level run, or its sub-agent's run while one is running.
35
+ */
36
+ run?: string | Pick<RunRef, "run">;
37
+ }
38
+ /**
39
+ * Add an event (a point in time with attributes) to the running agent run's `invoke_agent` span: what the app saw
40
+ * happen during the run (a coupon applied, a result shown). It is mapped, redacted and filtered with the run's span,
41
+ * and sent with it. A no-op, cheap, when `observeAgents()` is not running, when no recorded run is running (no
42
+ * consent, not sampled, or between runs: consent and sampling are decided per run, so outside one there is no
43
+ * decision to follow and the event is dropped), or when `options.run` names a run that is not recorded.
44
+ *
45
+ * @experimental
46
+ *
47
+ * @example
48
+ * import { recordAgentEvent } from "@webmcp-agents/telemetry";
49
+ * recordAgentEvent("cart.coupon_applied", { "cart.coupon": code, "cart.total": total });
50
+ */
51
+ export declare function recordAgentEvent(name: string, attributes?: CustomAttributes, options?: AgentSpanOptions): void;
52
+ /**
53
+ * Run `fn` inside a span of the running agent run: a child of the tool call that is running when exactly one is, else
54
+ * of the run's `invoke_agent` span. Timed around `fn` (sync, or until its promise settles); a throw or rejection sets
55
+ * the span's status to error (`error.type` is the error's name) and is rethrown unchanged. Returns what `fn` returns.
56
+ * The span goes through the same pipeline as the package's own: `metadataMapping`, redaction, `spanFilter`, then the
57
+ * relay or the page's provider; it carries `webmcp.custom: true` and the run's ids. With no recorded run (see
58
+ * `recordAgentEvent`), `fn` just runs. Telemetry never breaks `fn`: a failure in it is swallowed and logged once.
59
+ *
60
+ * @experimental
61
+ *
62
+ * @example
63
+ * import { withAgentSpan } from "@webmcp-agents/telemetry";
64
+ * const results = await withAgentSpan("search.query", () => api.search(query), { "search.kind": "flights" });
65
+ */
66
+ export declare function withAgentSpan<T>(name: string, fn: () => T, attributes?: CustomAttributes, options?: AgentSpanOptions): T;
67
+ /**
68
+ * What `observeAgents()` returns: call it to stop observing (buffered spans are sent first); `flush()` sends what is
69
+ * buffered now and resolves once the exporters took it (never rejects).
70
+ *
71
+ * @experimental
72
+ */
73
+ type StopObserving = (() => void) & {
74
+ flush(): Promise<void>;
75
+ };
76
+ /**
77
+ * Send the page's agent runs to an OpenTelemetry backend: each run, tool call and on-device model step becomes a span
78
+ * in the same trace as the server's model steps. By default spans are posted to the app's relay at `/api/telemetry`
79
+ * (`observability.relay()`), so no backend key reaches the page; a page that already runs OpenTelemetry gets them in
80
+ * its own provider. Content (tool inputs, results) is left out unless `recordInputs` / `recordOutputs`, and
81
+ * everything is redacted. Returns the function that stops observing (buffered spans are sent first), with `flush()`.
82
+ *
83
+ * @experimental
84
+ *
85
+ * @example
86
+ * import { observeAgents } from "@webmcp-agents/telemetry";
87
+ * const stop = observeAgents({ enabled: () => consent.analytics });
88
+ */
89
+ export declare function observeAgents(options?: ObserveAgentsOptions): StopObserving;
90
+ 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, type AgentSpanOptions, type AttributeValue, type Attributes, type BrowserSpanExporter, type CustomAttributes, DEFAULT_AGENT_NAME, EVENT_PARK, EVENT_RESUME, EVENT_YIELD, type ObserveAgentsOptions, type OtlpTarget, type ReadableSpanLike, SCOPE_NAME, SCOPE_NAME_LEGACY, SPAN_CHAT, SPAN_EXECUTE_TOOL, SPAN_INVOKE_AGENT, type Sampling, type SamplingContext, type SpanExporter, type SpanProcessor, type SpanRecord, type StopObserving, type TracerProvider, type TracerProviderOption };
package/dist/index.js ADDED
@@ -0,0 +1,19 @@
1
+ import { n as recordAgentEvent, r as withAgentSpan, t as observeAgents } from "./observe-BTuF-PfR.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
+ // src/browser/console.ts
4
+ /**
5
+ * An exporter that prints each finished span to the console instead of sending it: for development, and to see what
6
+ * would leave the page. Spans are already redacted when they reach it. No request is made.
7
+ *
8
+ * @experimental
9
+ *
10
+ * @example
11
+ * import { consoleExporter, observeAgents } from "@webmcp-agents/telemetry";
12
+ * observeAgents({ exporters: [consoleExporter()] });
13
+ */
14
+ function consoleExporter() {
15
+ return { export(spans) {
16
+ for (const span of spans) console.log(`[web-agents/telemetry] ${span.name}`, span);
17
+ } };
18
+ }
19
+ 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, SCOPE_NAME, SCOPE_NAME_LEGACY, SPAN_CHAT, SPAN_EXECUTE_TOOL, SPAN_INVOKE_AGENT, consoleExporter, observeAgents, recordAgentEvent, withAgentSpan };