@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.
@@ -0,0 +1,225 @@
1
+ import { c as parseTraceparent, o as isSampled, r as around } from "./util-5Bj-Z8Ym.js";
2
+ import { onAgentRun } from "@webmcp-agents/chat";
3
+ import { onAgentEvent } from "@webmcp-agents/core";
4
+ // src/browser/custom.ts
5
+ /** The running observers' hooks (`observeAgents()` adds one, its stop removes it). */
6
+ const hooks = /* @__PURE__ */ new Set();
7
+ let warned = false;
8
+ /** Telemetry never breaks the app: a failure here is swallowed, and logged once. */
9
+ const fail = (err) => {
10
+ if (!warned) {
11
+ warned = true;
12
+ console.error(`[web-agents/telemetry] a custom event or span was skipped: ${err?.message ?? err}`);
13
+ }
14
+ };
15
+ /** Hand the op to every observer; the span's end functions, joined. */
16
+ function forward(span, name, attributes, options) {
17
+ if (!hooks.size || typeof name !== "string" || !name) return void 0;
18
+ const run = typeof options?.run === "object" ? options.run?.run : options?.run;
19
+ const ends = [];
20
+ for (const hook of hooks) try {
21
+ const end = hook(span, name, attributes, run);
22
+ if (end) ends.push(end);
23
+ } catch (err) {
24
+ fail(err);
25
+ }
26
+ return ends.length ? (error) => {
27
+ for (const end of ends) try {
28
+ end(error);
29
+ } catch (err) {
30
+ fail(err);
31
+ }
32
+ } : void 0;
33
+ }
34
+ /**
35
+ * Add an event (a point in time with attributes) to the running agent run's `invoke_agent` span: what the app saw
36
+ * happen during the run (a coupon applied, a result shown). It is mapped, redacted and filtered with the run's span,
37
+ * and sent with it. A no-op, cheap, when `observeAgents()` is not running, when no recorded run is running (no
38
+ * consent, not sampled, or between runs: consent and sampling are decided per run, so outside one there is no
39
+ * decision to follow and the event is dropped), or when `options.run` names a run that is not recorded.
40
+ *
41
+ * @experimental
42
+ *
43
+ * @example
44
+ * import { recordAgentEvent } from "@webmcp-agents/telemetry";
45
+ * recordAgentEvent("cart.coupon_applied", { "cart.coupon": code, "cart.total": total });
46
+ */
47
+ function recordAgentEvent(name, attributes, options) {
48
+ try {
49
+ forward(false, name, attributes, options);
50
+ } catch (err) {
51
+ fail(err);
52
+ }
53
+ }
54
+ /**
55
+ * Run `fn` inside a span of the running agent run: a child of the tool call that is running when exactly one is, else
56
+ * of the run's `invoke_agent` span. Timed around `fn` (sync, or until its promise settles); a throw or rejection sets
57
+ * the span's status to error (`error.type` is the error's name) and is rethrown unchanged. Returns what `fn` returns.
58
+ * The span goes through the same pipeline as the package's own: `metadataMapping`, redaction, `spanFilter`, then the
59
+ * relay or the page's provider; it carries `webmcp.custom: true` and the run's ids. With no recorded run (see
60
+ * `recordAgentEvent`), `fn` just runs. Telemetry never breaks `fn`: a failure in it is swallowed and logged once.
61
+ *
62
+ * @experimental
63
+ *
64
+ * @example
65
+ * import { withAgentSpan } from "@webmcp-agents/telemetry";
66
+ * const results = await withAgentSpan("search.query", () => api.search(query), { "search.kind": "flights" });
67
+ */
68
+ function withAgentSpan(name, fn, attributes, options) {
69
+ let end;
70
+ try {
71
+ end = forward(true, name, attributes, options);
72
+ } catch (err) {
73
+ fail(err);
74
+ }
75
+ return end ? around(fn, end) : fn();
76
+ }
77
+ // src/browser/observe.ts
78
+ /**
79
+ * `observeAgents()`: subscribe to the page's agent runs and hand them to the span builder (`./engine`), which is a
80
+ * chunk of its own loaded when the first consented run starts. What a page downloads up front is this subscription
81
+ * and a queue; a page where no run happens, or where consent is never given, downloads nothing more.
82
+ */
83
+ /** Custom events and spans held at most while the engine chunk loads; past it they are dropped. */
84
+ const MAX_QUEUED_CUSTOM = 256;
85
+ const noop = Object.assign(() => {}, { flush: async () => {} });
86
+ /**
87
+ * Send the page's agent runs to an OpenTelemetry backend: each run, tool call and on-device model step becomes a span
88
+ * in the same trace as the server's model steps. By default spans are posted to the app's relay at `/api/telemetry`
89
+ * (`observability.relay()`), so no backend key reaches the page; a page that already runs OpenTelemetry gets them in
90
+ * its own provider. Content (tool inputs, results) is left out unless `recordInputs` / `recordOutputs`, and
91
+ * everything is redacted. Returns the function that stops observing (buffered spans are sent first), with `flush()`.
92
+ *
93
+ * @experimental
94
+ *
95
+ * @example
96
+ * import { observeAgents } from "@webmcp-agents/telemetry";
97
+ * const stop = observeAgents({ enabled: () => consent.analytics });
98
+ */
99
+ function observeAgents(options = {}) {
100
+ if (typeof document === "undefined" || options.exporters?.length === 0 && !options.tracerProvider) return noop;
101
+ const { enabled = () => true } = options;
102
+ let engine;
103
+ let loading;
104
+ /** What arrived while the engine loads (run events, resumes, the app's custom ops), in order. */
105
+ const queue = [];
106
+ /** Custom ops waiting in `queue`: bounded, so an app that records in a loop while the chunk loads holds little. */
107
+ let customs = 0;
108
+ /** `start`: a root run's start with consent, which is what loads the engine. */
109
+ const take = (op, start, custom) => {
110
+ if (engine !== void 0) {
111
+ if (engine) op(engine);
112
+ return;
113
+ }
114
+ if (!loading && !start) return;
115
+ if (custom && ++customs > MAX_QUEUED_CUSTOM) return;
116
+ queue.push(op);
117
+ loading ??= import("./engine-BLhKZ5vF.js").then((m) => engine = m.createEngine(options) ?? null, () => engine = null).then(() => {
118
+ for (const q of queue.splice(0)) if (engine) q(engine);
119
+ });
120
+ };
121
+ /** Open recorded runs: run id → its top-level run's id. In start order. */
122
+ const runs = /* @__PURE__ */ new Map();
123
+ /** Open tool calls of recorded runs: call id → run id. */
124
+ const calls = /* @__PURE__ */ new Map();
125
+ const stopRuns = onAgentRun((e) => {
126
+ let consent;
127
+ let kept;
128
+ const { run, parent } = e.ref;
129
+ if (e.type === "run-start") {
130
+ if (!parent) {
131
+ try {
132
+ consent = enabled() === true;
133
+ } catch {
134
+ consent = false;
135
+ }
136
+ kept = consent && isSampled(options.sampling, parseTraceparent(e.ref.traceparent)?.[0], {
137
+ agent: e.agent,
138
+ conversation: e.ref.conversation
139
+ });
140
+ if (kept && engine !== null) {
141
+ e.ref.sampled = true;
142
+ runs.set(run, run);
143
+ }
144
+ } else {
145
+ const root = runs.get(calls.get(parent));
146
+ if (root) runs.set(run, root);
147
+ }
148
+ } else if (e.type === "run-finish") {
149
+ runs.delete(run);
150
+ for (const [c, r] of calls) if (r === run) calls.delete(c);
151
+ } else if (e.type === "tool-start" && runs.has(run)) calls.set(e.call, run);
152
+ else if (e.type === "tool-finish") calls.delete(e.call);
153
+ take((x) => x.event(e, consent, kept), consent);
154
+ });
155
+ const stopVisuals = onAgentEvent((e) => {
156
+ if (e.type === "resume") take((x) => x.resume());
157
+ });
158
+ let seq = 0;
159
+ const hook = (span, name, attributes, target) => {
160
+ let run = target;
161
+ if (run === void 0) {
162
+ let top;
163
+ for (const [r, root] of runs) if (r === root) top = r;
164
+ for (const [r, root] of runs) if (root === top) run = r;
165
+ }
166
+ if (!run || !runs.has(run) || engine === null) return void 0;
167
+ const at = performance.now();
168
+ const op = {
169
+ run,
170
+ name,
171
+ attributes: attributes && { ...attributes },
172
+ at
173
+ };
174
+ if (!span) {
175
+ take((x) => x.custom({
176
+ type: "event",
177
+ ...op
178
+ }), false, true);
179
+ return;
180
+ }
181
+ let call;
182
+ let open = 0;
183
+ for (const [c, r] of calls) if (r === run) {
184
+ call = c;
185
+ open++;
186
+ }
187
+ const id = ++seq;
188
+ take((x) => x.custom({
189
+ type: "start",
190
+ id,
191
+ ...op,
192
+ call: open === 1 ? call : void 0
193
+ }), false, true);
194
+ return (error) => {
195
+ const at = performance.now();
196
+ take((x) => x.custom({
197
+ type: "end",
198
+ id,
199
+ at,
200
+ error
201
+ }));
202
+ };
203
+ };
204
+ hooks.add(hook);
205
+ const flushNow = () => (loading ?? Promise.resolve()).then(() => engine?.flush()).catch(() => {});
206
+ const flush = () => void flushNow();
207
+ const onHide = () => {
208
+ if (document.visibilityState === "hidden") flush();
209
+ };
210
+ addEventListener("pagehide", flush);
211
+ document.addEventListener("visibilitychange", onHide);
212
+ let stopped = false;
213
+ const stop = () => {
214
+ if (stopped) return;
215
+ stopped = true;
216
+ stopRuns();
217
+ stopVisuals();
218
+ hooks.delete(hook);
219
+ removeEventListener("pagehide", flush);
220
+ document.removeEventListener("visibilitychange", onHide);
221
+ flush();
222
+ };
223
+ return Object.assign(stop, { flush: flushNow });
224
+ }
225
+ export { recordAgentEvent as n, withAgentSpan as r, observeAgents as t };
@@ -0,0 +1,19 @@
1
+ import { n as ObserveAgentsOptions } from "./types-8Tdrt7C_.js";
2
+ /**
3
+ * Props of `<ObserveAgents>`: the options of `observeAgents()`.
4
+ *
5
+ * @experimental
6
+ */
7
+ export type ObserveAgentsProps = ObserveAgentsOptions;
8
+ /**
9
+ * Observe the page's agent runs while mounted (`observeAgents()`), and stop (sending what is buffered) on unmount.
10
+ * Renders nothing. The options are read once, when it mounts, except `enabled`, which is read at every run's start
11
+ * from the latest props (an inline function is fine).
12
+ *
13
+ * @experimental
14
+ *
15
+ * @example
16
+ * import { ObserveAgents } from "@webmcp-agents/telemetry/react";
17
+ * <ObserveAgents enabled={() => consent.analytics} />
18
+ */
19
+ export declare function ObserveAgents(props: ObserveAgentsProps): null;
package/dist/react.js ADDED
@@ -0,0 +1,29 @@
1
+ import { t as observeAgents } from "./observe-BTuF-PfR.js";
2
+ import { useEffect, useRef } from "react";
3
+ // src/react.tsx
4
+ /**
5
+ * @webmcp-agents/telemetry/react: `observeAgents()` as one element.
6
+ *
7
+ * <WebAgentsProvider><ObserveAgents enabled={() => consent.analytics} /><App /></WebAgentsProvider>
8
+ */
9
+ /**
10
+ * Observe the page's agent runs while mounted (`observeAgents()`), and stop (sending what is buffered) on unmount.
11
+ * Renders nothing. The options are read once, when it mounts, except `enabled`, which is read at every run's start
12
+ * from the latest props (an inline function is fine).
13
+ *
14
+ * @experimental
15
+ *
16
+ * @example
17
+ * import { ObserveAgents } from "@webmcp-agents/telemetry/react";
18
+ * <ObserveAgents enabled={() => consent.analytics} />
19
+ */
20
+ function ObserveAgents(props) {
21
+ const latest = useRef(props);
22
+ latest.current = props;
23
+ useEffect(() => observeAgents({
24
+ ...latest.current,
25
+ enabled: () => latest.current.enabled ? latest.current.enabled() : true
26
+ }), []);
27
+ return null;
28
+ }
29
+ export { ObserveAgents };
@@ -0,0 +1,222 @@
1
+ // src/semconv.ts
2
+ /**
3
+ * Every span name, attribute key and event name this package writes, in one place (design decision 8). The GenAI ones
4
+ * follow the OpenTelemetry GenAI semantic conventions as they stood in November 2026 (status: Development, so they may
5
+ * still be renamed upstream); the `webmcp.*` ones are this library's own.
6
+ *
7
+ * Use them in a `spanFilter`, a `metadataMapping` or a test instead of retyping the strings.
8
+ *
9
+ * @experimental The GenAI conventions are not stable yet: names may change in a minor release when they do.
10
+ *
11
+ * @example
12
+ * import { ATTR_CONVERSATION_ID } from "@webmcp-agents/telemetry/server";
13
+ * defineObservability({ metadataMapping: { [ATTR_CONVERSATION_ID]: "session.id" } });
14
+ */
15
+ /**
16
+ * The instrumentation scope of every span this package creates in the browser, and the only one the relay accepts.
17
+ *
18
+ * @experimental
19
+ */
20
+ const SCOPE_NAME = "@webmcp-agents/telemetry";
21
+ /**
22
+ * The scope of the server's model spans in the `ai.*` style (`conventions: "legacy"` or `"both"`).
23
+ *
24
+ * @experimental
25
+ */
26
+ const SCOPE_NAME_LEGACY = "@webmcp-agents/telemetry/legacy";
27
+ /**
28
+ * One agent run: `invoke_agent <agent id>` (`invoke_agent web-agent` for a run without an agent).
29
+ *
30
+ * @experimental
31
+ */
32
+ const SPAN_INVOKE_AGENT = "invoke_agent";
33
+ /**
34
+ * One tool call on the page: `execute_tool <tool name>`.
35
+ *
36
+ * @experimental
37
+ */
38
+ const SPAN_EXECUTE_TOOL = "execute_tool";
39
+ /**
40
+ * One model step: `chat <model>` (the server's, from the AI SDK; the browser's for an on-device run).
41
+ *
42
+ * @experimental
43
+ */
44
+ const SPAN_CHAT = "chat";
45
+ /**
46
+ * The subject of a run span when the run has no agent.
47
+ *
48
+ * @experimental
49
+ */
50
+ const DEFAULT_AGENT_NAME = "web-agent";
51
+ /**
52
+ * `invoke_agent`, `execute_tool` or `chat`.
53
+ *
54
+ * @experimental
55
+ */
56
+ const ATTR_OPERATION_NAME = "gen_ai.operation.name";
57
+ /**
58
+ * The agent's id (`defineWebAgent({ id })`).
59
+ *
60
+ * @experimental
61
+ */
62
+ const ATTR_AGENT_ID = "gen_ai.agent.id";
63
+ /**
64
+ * The tool's name.
65
+ *
66
+ * @experimental
67
+ */
68
+ const ATTR_TOOL_NAME = "gen_ai.tool.name";
69
+ /**
70
+ * The tool call's id, as the model gave it.
71
+ *
72
+ * @experimental
73
+ */
74
+ const ATTR_TOOL_CALL_ID = "gen_ai.tool.call.id";
75
+ /**
76
+ * The tool's input as JSON. Only with `recordInputs`, always redacted.
77
+ *
78
+ * @experimental
79
+ */
80
+ const ATTR_TOOL_CALL_ARGUMENTS = "gen_ai.tool.call.arguments";
81
+ /**
82
+ * The tool's result as JSON. Only with `recordOutputs`, always redacted.
83
+ *
84
+ * @experimental
85
+ */
86
+ const ATTR_TOOL_CALL_RESULT = "gen_ai.tool.call.result";
87
+ /**
88
+ * The model a step asked for.
89
+ *
90
+ * @experimental
91
+ */
92
+ const ATTR_REQUEST_MODEL = "gen_ai.request.model";
93
+ /**
94
+ * Prompt tokens of a step.
95
+ *
96
+ * @experimental
97
+ */
98
+ const ATTR_USAGE_INPUT_TOKENS = "gen_ai.usage.input_tokens";
99
+ /**
100
+ * Generated tokens of a step.
101
+ *
102
+ * @experimental
103
+ */
104
+ const ATTR_USAGE_OUTPUT_TOKENS = "gen_ai.usage.output_tokens";
105
+ /**
106
+ * The error code of a failed run or call (OpenTelemetry's general `error.type`).
107
+ *
108
+ * @experimental
109
+ */
110
+ const ATTR_ERROR_TYPE = "error.type";
111
+ /**
112
+ * The conversation: the same for every turn of one chat.
113
+ *
114
+ * @experimental
115
+ */
116
+ const ATTR_CONVERSATION_ID = "webmcp.conversation.id";
117
+ /**
118
+ * The run: one user turn, one `agent.invoke`, or one sub-agent run.
119
+ *
120
+ * @experimental
121
+ */
122
+ const ATTR_RUN_ID = "webmcp.run.id";
123
+ /**
124
+ * The model step within the run, from 1.
125
+ *
126
+ * @experimental
127
+ */
128
+ const ATTR_STEP = "webmcp.step";
129
+ /**
130
+ * For a sub-agent's run: the id of the `delegate_to_<id>` call that started it.
131
+ *
132
+ * @experimental
133
+ */
134
+ const ATTR_PARENT_CALL_ID = "webmcp.parent.call.id";
135
+ /**
136
+ * The agent's id, on the server's spans.
137
+ *
138
+ * @experimental
139
+ */
140
+ const ATTR_WEBMCP_AGENT_ID = "webmcp.agent.id";
141
+ /**
142
+ * The chat session's id, on the server's spans (`createChatHandler({ session })`).
143
+ *
144
+ * @experimental
145
+ */
146
+ const ATTR_SESSION_ID = "webmcp.session.id";
147
+ /**
148
+ * The adapter that ran the model: `cloud`, `local`…
149
+ *
150
+ * @experimental
151
+ */
152
+ const ATTR_ADAPTER = "webmcp.adapter";
153
+ /**
154
+ * How the run ended: `stop`, `max-steps`, `aborted` or `error`.
155
+ *
156
+ * @experimental
157
+ */
158
+ const ATTR_RUN_REASON = "webmcp.run.reason";
159
+ /**
160
+ * Model steps the run took.
161
+ *
162
+ * @experimental
163
+ */
164
+ const ATTR_RUN_STEPS = "webmcp.run.steps";
165
+ /**
166
+ * The page the run started on, redacted (origin and path; query values withheld).
167
+ *
168
+ * @experimental
169
+ */
170
+ const ATTR_PAGE = "webmcp.page";
171
+ /**
172
+ * How the call ended: `done`, `error` or `cancelled`.
173
+ *
174
+ * @experimental
175
+ */
176
+ const ATTR_TOOL_STATE = "webmcp.tool.state";
177
+ /**
178
+ * The error code of a failed or cancelled call (`not_found`, `cancelled`, `needs_user`…).
179
+ *
180
+ * @experimental
181
+ */
182
+ const ATTR_TOOL_ERROR_CODE = "webmcp.tool.error.code";
183
+ /**
184
+ * Of the call's time, the milliseconds spent waiting for the person.
185
+ *
186
+ * @experimental
187
+ */
188
+ const ATTR_TOOL_WAITED_MS = "webmcp.tool.waited_ms";
189
+ /**
190
+ * For a call that waited for the person: `accepted`, `cancelled` or `timeout`.
191
+ *
192
+ * @experimental
193
+ */
194
+ const ATTR_TOOL_CONFIRM = "webmcp.tool.confirm";
195
+ /**
196
+ * The call started waiting for the person. Attribute `prompt`: what they were asked (redacted).
197
+ *
198
+ * @experimental
199
+ */
200
+ const EVENT_PARK = "webmcp.park";
201
+ /**
202
+ * The person interacted and the cursor got out of the way. Attribute `reason`.
203
+ *
204
+ * @experimental
205
+ */
206
+ const EVENT_YIELD = "webmcp.yield";
207
+ /**
208
+ * The cursor came back after a yield.
209
+ *
210
+ * @experimental
211
+ */
212
+ const EVENT_RESUME = "webmcp.resume";
213
+ /**
214
+ * `true` on every span the app created through this package (`withAgentSpan` in the browser, `observability.span` /
215
+ * `observability.event` on the server), so a `spanFilter` or a backend query can tell them from the library's own.
216
+ * Their names are the app's, as given; their attribute keys are free except `webmcp.*`, which this library reserves
217
+ * (an app's `webmcp.*` keys are dropped).
218
+ *
219
+ * @experimental
220
+ */
221
+ const ATTR_CUSTOM = "webmcp.custom";
222
+ export { SCOPE_NAME as A, ATTR_USAGE_INPUT_TOKENS as C, EVENT_PARK as D, DEFAULT_AGENT_NAME as E, SPAN_CHAT as M, SPAN_EXECUTE_TOOL as N, EVENT_RESUME as O, SPAN_INVOKE_AGENT as P, ATTR_TOOL_WAITED_MS as S, ATTR_WEBMCP_AGENT_ID as T, ATTR_TOOL_CALL_RESULT as _, ATTR_ERROR_TYPE as a, ATTR_TOOL_NAME as b, ATTR_PARENT_CALL_ID as c, ATTR_RUN_REASON as d, ATTR_RUN_STEPS as f, ATTR_TOOL_CALL_ID as g, ATTR_TOOL_CALL_ARGUMENTS as h, ATTR_CUSTOM as i, SCOPE_NAME_LEGACY as j, EVENT_YIELD as k, ATTR_REQUEST_MODEL as l, ATTR_STEP as m, ATTR_AGENT_ID as n, ATTR_OPERATION_NAME as o, ATTR_SESSION_ID as p, ATTR_CONVERSATION_ID as r, ATTR_PAGE as s, ATTR_ADAPTER as t, ATTR_RUN_ID as u, ATTR_TOOL_CONFIRM as v, ATTR_USAGE_OUTPUT_TOKENS as w, ATTR_TOOL_STATE as x, ATTR_TOOL_ERROR_CODE as y };