agents 0.31.0 → 0.32.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.
Files changed (105) hide show
  1. package/dist/{agent-routing-wS1TimZ_.d.ts → agent-routing-vVMA7m8Y.d.ts} +6 -6
  2. package/dist/agent-routing.d.ts +1 -1
  3. package/dist/agent-tool-types.d.ts +1 -1
  4. package/dist/{agent-tools-Bamxxb6Y.d.ts → agent-tools-gGXXkf1z.d.ts} +2 -2
  5. package/dist/agent-tools.d.ts +1 -1
  6. package/dist/agent-tools.js +0 -1
  7. package/dist/agent-tools.js.map +1 -1
  8. package/dist/browser/ai.js +1 -1
  9. package/dist/browser/tools/ai-sdk.d.ts +66 -1
  10. package/dist/browser/tools/ai-sdk.js +2 -2
  11. package/dist/browser/tools/pi.js +2 -2
  12. package/dist/browser/tools/tanstack-ai.d.ts +2 -2
  13. package/dist/browser/tools/tanstack-ai.js +2 -2
  14. package/dist/browser/tools/tanstack-ai.js.map +1 -1
  15. package/dist/{browser-tool-lGnvEBLJ.js → browser-tool-DRan7Lk6.js} +2 -2
  16. package/dist/{browser-tool-lGnvEBLJ.js.map → browser-tool-DRan7Lk6.js.map} +1 -1
  17. package/dist/catalog-BpOejOsE.js +239 -0
  18. package/dist/catalog-BpOejOsE.js.map +1 -0
  19. package/dist/catalog-BpiVV1OF.d.ts +173 -0
  20. package/dist/chat/index.d.ts +2 -2
  21. package/dist/chat-sdk/index.d.ts +1 -1
  22. package/dist/chat-sdk/index.js +1 -1
  23. package/dist/{client-wn4-yqGz.d.ts → client-eSfgYvd3.d.ts} +2 -2
  24. package/dist/client.d.ts +1 -1
  25. package/dist/{cloudflare-Dzvc7V2N.js → cloudflare-CUUm_9q9.js} +26 -4
  26. package/dist/cloudflare-CUUm_9q9.js.map +1 -0
  27. package/dist/{do-oauth-client-provider-DfsUcpc3.d.ts → do-oauth-client-provider-DtNqv7oj.d.ts} +26 -2
  28. package/dist/{index-YSKgfgg9.d.ts → emitter-BJZtCVjQ.d.ts} +6 -140
  29. package/dist/emitter-DPOVcCln.js +15 -0
  30. package/dist/emitter-DPOVcCln.js.map +1 -0
  31. package/dist/experimental/channels/web/index.js +1 -1
  32. package/dist/harness/container/index.js +0 -1
  33. package/dist/harness/container/index.js.map +1 -1
  34. package/dist/harness/container/runtime/index.js +2 -2
  35. package/dist/harness/opencode/index.js +0 -1
  36. package/dist/harness/opencode/index.js.map +1 -1
  37. package/dist/harness/pi/index.d.ts +11 -4
  38. package/dist/harness/pi/index.js +43 -141
  39. package/dist/harness/pi/index.js.map +1 -1
  40. package/dist/index.d.ts +2 -3
  41. package/dist/index.js +2 -2
  42. package/dist/markdown-BZ-VLtA1.js +86 -0
  43. package/dist/markdown-BZ-VLtA1.js.map +1 -0
  44. package/dist/mcp/client/do-oauth-client-provider.d.ts +4 -2
  45. package/dist/mcp/client/do-oauth-client-provider.js +15 -1
  46. package/dist/mcp/client/do-oauth-client-provider.js.map +1 -1
  47. package/dist/mcp/client/index.d.ts +1 -1
  48. package/dist/mcp/index.d.ts +1 -1
  49. package/dist/mcp/index.js +1 -1
  50. package/dist/models/pi-ai/index.js +129 -2
  51. package/dist/models/pi-ai/index.js.map +1 -1
  52. package/dist/observability/ai/index.js +1 -2
  53. package/dist/observability/ai/index.js.map +1 -1
  54. package/dist/observability/index.d.ts +170 -9
  55. package/dist/observability/index.js +386 -11
  56. package/dist/observability/index.js.map +1 -1
  57. package/dist/react.d.ts +2 -2
  58. package/dist/resource-B59OV2a2.js +325 -0
  59. package/dist/resource-B59OV2a2.js.map +1 -0
  60. package/dist/routing/index.d.ts +1 -1
  61. package/dist/script-CFDLTk5b.d.ts +91 -0
  62. package/dist/script-workspace-BpdAYq1R.d.ts +41 -0
  63. package/dist/serializable.d.ts +1 -1
  64. package/dist/skill-DRBcIBjC.d.ts +221 -0
  65. package/dist/skills/index.d.ts +275 -36
  66. package/dist/skills/index.js +265 -1534
  67. package/dist/skills/index.js.map +1 -1
  68. package/dist/skills/runner.d.ts +37 -0
  69. package/dist/skills/runner.js +912 -0
  70. package/dist/skills/runner.js.map +1 -0
  71. package/dist/skills/tools/ai-sdk.d.ts +36 -0
  72. package/dist/skills/tools/ai-sdk.js +94 -0
  73. package/dist/skills/tools/ai-sdk.js.map +1 -0
  74. package/dist/source-9RQzlEhM.d.ts +112 -0
  75. package/dist/{src-BGolXG_H.js → src-DoGNJ4Ud.js} +4 -5
  76. package/dist/src-DoGNJ4Ud.js.map +1 -0
  77. package/dist/sub-routing.d.ts +1 -1
  78. package/dist/tool-CxKsvxjm.js.map +1 -1
  79. package/dist/tool-DkT_DJBm.js.map +1 -1
  80. package/dist/{tool-helpers-BodWi4gd.js → tool-helpers-BI7ifO2S.js} +1 -2
  81. package/dist/{tool-helpers-BodWi4gd.js.map → tool-helpers-BI7ifO2S.js.map} +1 -1
  82. package/dist/vite.d.ts +2 -2
  83. package/dist/vite.js +10 -258
  84. package/dist/vite.js.map +1 -1
  85. package/dist/voice/index.d.ts +1 -1
  86. package/dist/websockets/index.js +1 -1
  87. package/dist/{websockets-CyoeosdO.js → websockets-C6SJtWCJ.js} +1 -2
  88. package/dist/{websockets-CyoeosdO.js.map → websockets-C6SJtWCJ.js.map} +1 -1
  89. package/dist/workflow-types.d.ts +1 -1
  90. package/dist/workflows.d.ts +1 -1
  91. package/dist/workflows.js +0 -1
  92. package/dist/workflows.js.map +1 -1
  93. package/docs/harnesses/pi.md +9 -3
  94. package/docs/mcp-client.md +23 -1
  95. package/docs/mcp-servers.md +2 -2
  96. package/docs/observability.md +5 -3
  97. package/package.json +24 -15
  98. package/dist/ai-sdk-hW3vntnk.d.ts +0 -72
  99. package/dist/cloudflare-Dzvc7V2N.js.map +0 -1
  100. package/dist/index-iv9FTXX9.d.ts +0 -311
  101. package/dist/skills/compile.d.ts +0 -40
  102. package/dist/skills/compile.js +0 -65
  103. package/dist/skills/compile.js.map +0 -1
  104. package/dist/src-BGolXG_H.js.map +0 -1
  105. package/skills-module.d.ts +0 -22
@@ -1,16 +1,177 @@
1
1
  import {
2
- a as subscribe,
3
- i as genericObservability,
4
- n as Observability,
5
- o as channels,
6
- r as ObservabilityEvent,
7
- t as ChannelEventMap
8
- } from "../index-YSKgfgg9.js";
2
+ n as ObservabilityEvent,
3
+ r as genericObservability,
4
+ t as Observability
5
+ } from "../emitter-BJZtCVjQ.js";
6
+ import { Channel } from "node:diagnostics_channel";
7
+
8
+ //#region src/observability/diagnostics.d.ts
9
+ /** Diagnostics channels for Agent and Lifecycle telemetry. */
10
+ declare const channels: {
11
+ readonly state: Channel<any, any>;
12
+ readonly rpc: Channel<any, any>;
13
+ readonly message: Channel<any, any>;
14
+ readonly chat: Channel<any, any>;
15
+ readonly transcript: Channel<any, any>;
16
+ readonly fiber: Channel<any, any>;
17
+ readonly task: Channel<any, any>;
18
+ readonly stream: Channel<any, any>;
19
+ readonly agentTool: Channel<any, any>;
20
+ readonly schedule: Channel<any, any>;
21
+ readonly lifecycle: Channel<any, any>;
22
+ readonly workflow: Channel<any, any>;
23
+ readonly mcp: Channel<any, any>;
24
+ readonly email: Channel<any, any>;
25
+ readonly channel: Channel<any, any>;
26
+ };
27
+ //#endregion
28
+ //#region src/observability/otel/index.d.ts
29
+ /**
30
+ * Connects the OpenTelemetry API (`@opentelemetry/api`) to Workers tracing.
31
+ * Call once at module scope:
32
+ *
33
+ * ```ts
34
+ * import { experimental_registerOpenTelemetry } from "agents/observability";
35
+ *
36
+ * experimental_registerOpenTelemetry();
37
+ * ```
38
+ *
39
+ * Afterwards, libraries instrumented with the OpenTelemetry API (the MCP SDK,
40
+ * AI SDK telemetry, your own `trace.getTracer(...)` spans) record native
41
+ * Workers spans. They nest with the Agents SDK's spans and the automatic
42
+ * fetch, KV, D1 and Durable Object spans, and export through
43
+ * `observability.traces.destinations`. Enable `observability.traces` in your
44
+ * Wrangler configuration for anything to be recorded.
45
+ *
46
+ * Safe to call more than once. When OpenTelemetry is already fully registered,
47
+ * by your own SDK setup or natively by the Workers runtime, this leaves it in
48
+ * place and does nothing. Throws when only part of an OpenTelemetry setup is
49
+ * registered.
50
+ *
51
+ * @experimental Undocumented and subject to change: a temporary bridge until
52
+ * Workers supports the OpenTelemetry API natively. See
53
+ * `design/rfc-opentelemetry-bridge.md` for what it records and refuses.
54
+ */
55
+ declare function experimental_registerOpenTelemetry(): void;
56
+ //#endregion
57
+ //#region src/observability/index.d.ts
58
+ /**
59
+ * Maps each channel key to the observability events it carries.
60
+ */
61
+ type ChannelEventMap = {
62
+ state: Extract<
63
+ ObservabilityEvent,
64
+ {
65
+ type: `state:${string}`;
66
+ }
67
+ >;
68
+ rpc: Extract<
69
+ ObservabilityEvent,
70
+ {
71
+ type: "rpc" | `rpc:${string}`;
72
+ }
73
+ >;
74
+ message: Extract<
75
+ ObservabilityEvent,
76
+ {
77
+ type:
78
+ | `message:${string}`
79
+ | `tool:${string}`
80
+ | `submission:${string}`
81
+ | `action:${string}`;
82
+ }
83
+ >;
84
+ chat: Exclude<
85
+ Extract<
86
+ ObservabilityEvent,
87
+ {
88
+ type: `chat:${string}`;
89
+ }
90
+ >,
91
+ {
92
+ type: `chat:transcript:${string}`;
93
+ }
94
+ >;
95
+ transcript: Extract<
96
+ ObservabilityEvent,
97
+ {
98
+ type: `transcript:${string}` | `chat:transcript:${string}`;
99
+ }
100
+ >;
101
+ fiber: Extract<
102
+ ObservabilityEvent,
103
+ {
104
+ type: `fiber:${string}`;
105
+ }
106
+ >;
107
+ agentTool: Extract<
108
+ ObservabilityEvent,
109
+ {
110
+ type: `agent_tool:${string}`;
111
+ }
112
+ >;
113
+ schedule: Extract<
114
+ ObservabilityEvent,
115
+ {
116
+ type: `schedule:${string}` | `queue:${string}`;
117
+ }
118
+ >;
119
+ lifecycle: Extract<
120
+ ObservabilityEvent,
121
+ {
122
+ type: "connect" | "disconnect" | "destroy";
123
+ }
124
+ >;
125
+ workflow: Extract<
126
+ ObservabilityEvent,
127
+ {
128
+ type: `workflow:${string}`;
129
+ }
130
+ >;
131
+ mcp: Extract<
132
+ ObservabilityEvent,
133
+ {
134
+ type: `mcp:${string}`;
135
+ }
136
+ >;
137
+ email: Extract<
138
+ ObservabilityEvent,
139
+ {
140
+ type: `email:${string}`;
141
+ }
142
+ >;
143
+ channel: Extract<
144
+ ObservabilityEvent,
145
+ {
146
+ type: `channel:${string}` | `notice:${string}`;
147
+ }
148
+ >;
149
+ };
150
+ /**
151
+ * Subscribe to a typed observability channel.
152
+ *
153
+ * ```ts
154
+ * import { subscribe } from "agents/observability";
155
+ *
156
+ * const unsub = subscribe("rpc", (event) => {
157
+ * console.log(event.payload.method); // fully typed
158
+ * });
159
+ * ```
160
+ *
161
+ * @returns A function that unsubscribes the callback.
162
+ */
163
+ declare function subscribe<K extends keyof ChannelEventMap>(
164
+ channelKey: K,
165
+ callback: (event: ChannelEventMap[K]) => void
166
+ ): () => void;
167
+ //#endregion
9
168
  export {
10
169
  ChannelEventMap,
11
- Observability,
12
- ObservabilityEvent,
170
+ type Observability,
171
+ type ObservabilityEvent,
13
172
  channels,
173
+ experimental_registerOpenTelemetry,
14
174
  genericObservability,
15
175
  subscribe
16
176
  };
177
+ //# sourceMappingURL=index.d.ts.map
@@ -1,5 +1,389 @@
1
- import { n as publishDiagnosticsEvent, t as channels } from "../diagnostics-BzvaX2UT.js";
1
+ import { i as _classPrivateFieldInitSpec, n as _classPrivateFieldSet2, t as _classPrivateFieldGet2 } from "../classPrivateFieldGet2-DZBYAB34.js";
2
+ import { t as nativeTracing } from "../cloudflare-CUUm_9q9.js";
3
+ import { t as channels } from "../diagnostics-BzvaX2UT.js";
4
+ import { t as genericObservability } from "../emitter-DPOVcCln.js";
5
+ import { AsyncLocalStorage } from "node:async_hooks";
2
6
  import { subscribe as subscribe$1, unsubscribe } from "node:diagnostics_channel";
7
+ import { INVALID_SPAN_CONTEXT, ROOT_CONTEXT, SpanStatusCode, context, createContextKey, diag, isSpanContextValid, trace } from "@opentelemetry/api";
8
+ //#region src/observability/otel/bridge.ts
9
+ /**
10
+ * The OpenTelemetry API on Workers native tracing.
11
+ *
12
+ * Every recording OTel span is a native span. Native tracing has no manual
13
+ * parent wiring: a span's parent is whatever native span is active (in the
14
+ * async context) when it opens, and a span can only be active inside the
15
+ * callback that opened it. The bridge works within that:
16
+ *
17
+ * - Every span opens with `tracing.startActiveSpan`, so it is native-active for
18
+ * at least a moment. Inside that moment the bridge captures an async-context
19
+ * snapshot: a way back into "this span is the active native parent".
20
+ * - `startActiveSpan` runs the caller's function inside the native callback.
21
+ * - `startSpan` returns from the native callback at once (the span stays open
22
+ * and inactive, as OTel requires). When the span later becomes active through
23
+ * `context.with(trace.setSpan(ctx, span), fn)` — the pattern the MCP SDK and
24
+ * other instrumentation use — `fn` runs inside the snapshot, so platform
25
+ * spans (fetch, KV, D1, Durable Objects) and child spans nest under it.
26
+ * - A span is only opened where its native parent is the span the caller asked
27
+ * for. Anything native tracing cannot represent faithfully (remote parents,
28
+ * new roots, explicit start times, parents from another request) returns a
29
+ * non-recording span instead of a span under a substitute parent.
30
+ */
31
+ const reported = /* @__PURE__ */ new Set();
32
+ /**
33
+ * Marks a context taken where no native span was visible. Durable Object
34
+ * constructors and `blockConcurrencyWhile` callbacks report no active span,
35
+ * yet native spans opened there still parent to the request; at module scope
36
+ * they record nothing. Either way the runtime, not the bridge, picks.
37
+ */
38
+ const AMBIENT = createContextKey("agents: ambient native span");
39
+ /**
40
+ * Reports a dropped or refused feature once per isolate through OTel's `diag`
41
+ * logger. Messages name the feature only, never span names or values.
42
+ */
43
+ function unsupported(feature) {
44
+ if (reported.has(feature)) return;
45
+ reported.add(feature);
46
+ diag.warn(`agents/observability: ${feature} cannot be represented by Workers tracing.`);
47
+ }
48
+ /** Telemetry must never replace the application's result or error. */
49
+ function safely(write, feature) {
50
+ try {
51
+ write();
52
+ } catch {
53
+ unsupported(`${feature} (the runtime rejected the value)`);
54
+ }
55
+ }
56
+ var _spans = /* @__PURE__ */ new WeakMap();
57
+ var _tracer = /* @__PURE__ */ new WeakMap();
58
+ var _snapshot = /* @__PURE__ */ new WeakMap();
59
+ var Bridge = class {
60
+ constructor(native, snapshot) {
61
+ this.native = native;
62
+ _classPrivateFieldInitSpec(this, _spans, /* @__PURE__ */ new WeakMap());
63
+ _classPrivateFieldInitSpec(this, _tracer, void 0);
64
+ _classPrivateFieldInitSpec(this, _snapshot, void 0);
65
+ _classPrivateFieldSet2(_snapshot, this, snapshot);
66
+ this.contextManager = new WorkersContextManager(this).enable();
67
+ _classPrivateFieldSet2(_tracer, this, new WorkersTracer(this));
68
+ const tracer = _classPrivateFieldGet2(_tracer, this);
69
+ this.tracerProvider = { getTracer: () => tracer };
70
+ }
71
+ /** The OTel span for a native span the bridge did not open (root, agent spans). */
72
+ wrap(native) {
73
+ let span = _classPrivateFieldGet2(_spans, this).get(native);
74
+ if (span === void 0) {
75
+ span = new WorkersSpan(this, native, void 0);
76
+ _classPrivateFieldGet2(_spans, this).set(native, span);
77
+ }
78
+ return span;
79
+ }
80
+ /**
81
+ * Opens a native span where `placement` says, seeds its attributes, and
82
+ * calls `body` while it is the active native span.
83
+ */
84
+ open(name, attributes, placement, body) {
85
+ const start = () => this.native.startActiveSpan(name, (native) => {
86
+ const span = new WorkersSpan(this, native, _classPrivateFieldGet2(_snapshot, this).call(this));
87
+ _classPrivateFieldGet2(_spans, this).set(native, span);
88
+ if (attributes !== void 0) span.setAttributes(attributes);
89
+ return body(span);
90
+ });
91
+ return placement.in === void 0 ? start() : placement.in(start);
92
+ }
93
+ /**
94
+ * Decides whether a span can open natively under the requested parent, and
95
+ * from which async context.
96
+ */
97
+ place(options, parentContext) {
98
+ const parent = options.root ? void 0 : trace.getSpan(parentContext);
99
+ const current = this.native.getActiveSpan();
100
+ const refuse = (feature) => {
101
+ unsupported(feature);
102
+ const ids = parent?.spanContext();
103
+ return { refused: ids !== void 0 && isSpanContextValid(ids) ? ids : INVALID_SPAN_CONTEXT };
104
+ };
105
+ if (current === void 0) return parent === void 0 && !options.root && options.startTime === void 0 && parentContext.getValue(AMBIENT) === true ? { in: void 0 } : refuse("Spans outside a request");
106
+ if (parent === void 0) return refuse("Root spans and spans without a parent");
107
+ if (!(parent instanceof WorkersSpan) || parent.bridge !== this) return refuse("Spans under remote or foreign parents");
108
+ if (options.startTime !== void 0) return refuse("Explicit span start timestamps");
109
+ if (options.links !== void 0 && options.links.length > 0) unsupported("Span links (dropped)");
110
+ if (parent.native === current) return { in: void 0 };
111
+ const reentry = parent.reentry(current);
112
+ return reentry === void 0 ? refuse("Spans under a parent from another request or scope") : { in: reentry };
113
+ }
114
+ /** Runs `fn` with `context` as the OTel context and `native` as its native span. */
115
+ run(context, native, fn) {
116
+ return this.contextManager.run({
117
+ context,
118
+ native
119
+ }, fn);
120
+ }
121
+ };
122
+ var _traceId = /* @__PURE__ */ new WeakMap();
123
+ var WorkersSpan = class {
124
+ constructor(bridge, native, snapshot) {
125
+ this.bridge = bridge;
126
+ this.native = native;
127
+ this.snapshot = snapshot;
128
+ _classPrivateFieldInitSpec(this, _traceId, void 0);
129
+ _classPrivateFieldSet2(_traceId, this, snapshot === void 0 ? void 0 : traceIdOf(native));
130
+ }
131
+ /**
132
+ * The snapshot to re-enter so this span is the active native parent again,
133
+ * or `undefined` when that would cross into another request.
134
+ */
135
+ reentry(current) {
136
+ if (this.snapshot === void 0) return;
137
+ const currentTraceId = traceIdOf(current);
138
+ if (_classPrivateFieldGet2(_traceId, this) !== void 0 && currentTraceId !== void 0 && _classPrivateFieldGet2(_traceId, this) !== currentTraceId) return;
139
+ return this.snapshot;
140
+ }
141
+ spanContext() {
142
+ let ids;
143
+ safely(() => {
144
+ ids = this.native.spanContext?.();
145
+ }, "Span context");
146
+ if (ids === void 0) return INVALID_SPAN_CONTEXT;
147
+ const { traceId, spanId, traceFlags } = ids;
148
+ return {
149
+ traceId,
150
+ spanId,
151
+ traceFlags
152
+ };
153
+ }
154
+ isRecording() {
155
+ return this.native.isTraced;
156
+ }
157
+ setAttribute(key, value) {
158
+ if (key === "" || value === void 0 || !this.native.isTraced) return this;
159
+ if (typeof value === "string" || typeof value === "number" || typeof value === "boolean") safely(() => this.native.setAttribute(key, value), "Attribute");
160
+ else unsupported("Array and non-scalar attribute values (dropped)");
161
+ return this;
162
+ }
163
+ setAttributes(attributes) {
164
+ for (const [key, value] of Object.entries(attributes)) this.setAttribute(key, value);
165
+ return this;
166
+ }
167
+ setStatus(status) {
168
+ if (status.code !== SpanStatusCode.OK && status.code !== SpanStatusCode.ERROR) return this;
169
+ const setStatus = this.native.setStatus;
170
+ if (setStatus === void 0) {
171
+ unsupported("Span status on this runtime version");
172
+ return this;
173
+ }
174
+ safely(() => setStatus.call(this.native, status.code === SpanStatusCode.ERROR ? status.message === void 0 ? { code: "error" } : {
175
+ code: "error",
176
+ message: status.message
177
+ } : { code: "ok" }), "Span status");
178
+ return this;
179
+ }
180
+ updateName(name) {
181
+ const updateName = this.native.updateName;
182
+ if (updateName === void 0) {
183
+ unsupported("Span renames on this runtime version");
184
+ return this;
185
+ }
186
+ safely(() => updateName.call(this.native, name), "Span rename");
187
+ return this;
188
+ }
189
+ recordException(exception, time) {
190
+ if (time !== void 0) unsupported("Explicit exception timestamps (recorded at runtime time)");
191
+ safely(() => this.native.recordException(exception), "Exception");
192
+ }
193
+ end(endTime) {
194
+ if (endTime !== void 0) unsupported("Explicit end timestamps (ended at runtime time)");
195
+ safely(() => this.native.end(), "Span end");
196
+ }
197
+ addEvent(_name, _attributesOrStartTime, _startTime) {
198
+ unsupported("Span events other than exceptions (dropped)");
199
+ return this;
200
+ }
201
+ addLink(_link) {
202
+ unsupported("Span links (dropped)");
203
+ return this;
204
+ }
205
+ addLinks(links) {
206
+ if (links.length > 0) unsupported("Span links (dropped)");
207
+ return this;
208
+ }
209
+ };
210
+ function traceIdOf(native) {
211
+ try {
212
+ const traceId = native.spanContext?.().traceId;
213
+ return traceId === void 0 || /^0+$/.test(traceId) ? void 0 : traceId;
214
+ } catch {
215
+ return;
216
+ }
217
+ }
218
+ var WorkersTracer = class {
219
+ constructor(bridge) {
220
+ this.bridge = bridge;
221
+ }
222
+ startSpan(name, options = {}, parentContext = this.bridge.contextManager.active()) {
223
+ const placement = this.bridge.place(options, parentContext);
224
+ if ("refused" in placement) return trace.wrapSpanContext(placement.refused);
225
+ return this.bridge.open(name, options.attributes, placement, (span) => span);
226
+ }
227
+ startActiveSpan(name, optionsOrFn, contextOrFn, maybeFn) {
228
+ const options = typeof optionsOrFn === "function" ? {} : optionsOrFn;
229
+ const parentContext = typeof contextOrFn === "object" ? contextOrFn : this.bridge.contextManager.active();
230
+ const fn = typeof optionsOrFn === "function" ? optionsOrFn : typeof contextOrFn === "function" ? contextOrFn : maybeFn;
231
+ if (fn === void 0) throw new TypeError("startActiveSpan requires a callback");
232
+ const placement = this.bridge.place(options, parentContext);
233
+ if ("refused" in placement) {
234
+ const span = trace.wrapSpanContext(placement.refused);
235
+ return this.bridge.contextManager.with(trace.setSpan(parentContext, span), () => fn(span));
236
+ }
237
+ return this.bridge.open(name, options.attributes, placement, (span) => this.bridge.run(trace.setSpan(parentContext, span), span.native, () => fn(span)));
238
+ }
239
+ };
240
+ var _storage = /* @__PURE__ */ new WeakMap();
241
+ var WorkersContextManager = class {
242
+ constructor(bridge) {
243
+ this.bridge = bridge;
244
+ _classPrivateFieldInitSpec(this, _storage, void 0);
245
+ }
246
+ active() {
247
+ const storage = _classPrivateFieldGet2(_storage, this);
248
+ if (storage === void 0) return ROOT_CONTEXT;
249
+ const scope = storage.getStore();
250
+ const native = this.bridge.native.getActiveSpan();
251
+ if (scope !== void 0 && scope.native === native) return scope.context;
252
+ if (native === void 0) return scope?.context ?? ROOT_CONTEXT.setValue(AMBIENT, true);
253
+ return trace.setSpan(scope?.context ?? ROOT_CONTEXT, this.bridge.wrap(native));
254
+ }
255
+ with(context, fn, thisArg, ...args) {
256
+ const call = () => fn.apply(thisArg, args);
257
+ if (_classPrivateFieldGet2(_storage, this) === void 0) return call();
258
+ const current = this.bridge.native.getActiveSpan();
259
+ const span = trace.getSpan(context);
260
+ if (span instanceof WorkersSpan && span.bridge === this.bridge && current !== void 0 && span.native !== current) {
261
+ const reentry = span.reentry(current);
262
+ if (reentry !== void 0) return reentry(() => this.run({
263
+ context,
264
+ native: span.native
265
+ }, call));
266
+ unsupported("Activating a span from another request or scope");
267
+ }
268
+ return this.run({
269
+ context,
270
+ native: current
271
+ }, call);
272
+ }
273
+ /** INTERNAL: runs `fn` in `scope` without native activation. */
274
+ run(scope, fn) {
275
+ const storage = _classPrivateFieldGet2(_storage, this);
276
+ return storage === void 0 ? fn() : storage.run(scope, fn);
277
+ }
278
+ bind(context, target) {
279
+ if (typeof target !== "function") {
280
+ unsupported("context.bind on non-functions (left unchanged)");
281
+ return target;
282
+ }
283
+ const manager = this;
284
+ const callable = target;
285
+ return function(...args) {
286
+ return manager.with(context, () => callable.apply(this, args));
287
+ };
288
+ }
289
+ enable() {
290
+ _classPrivateFieldGet2(_storage, this) ?? _classPrivateFieldSet2(_storage, this, new AsyncLocalStorage());
291
+ return this;
292
+ }
293
+ /** Workers has no `AsyncLocalStorage.disable()`; drop access to old scopes instead. */
294
+ disable() {
295
+ _classPrivateFieldSet2(_storage, this, void 0);
296
+ return this;
297
+ }
298
+ };
299
+ /** Creates (but does not register) the OTel components for native tracing. */
300
+ function createOpenTelemetryBridge(runtime) {
301
+ return new Bridge(runtime.tracing, runtime.snapshot ?? (() => AsyncLocalStorage.snapshot()));
302
+ }
303
+ //#endregion
304
+ //#region src/observability/otel/register.ts
305
+ /** Where `@opentelemetry/api` 1.x keeps its global registrations. */
306
+ const OTEL_GLOBAL = Symbol.for("opentelemetry.js.api.1");
307
+ function otelGlobal() {
308
+ return globalThis[OTEL_GLOBAL];
309
+ }
310
+ /** The provider behind the global proxy, when the proxy exposes it. */
311
+ function delegateOf(provider) {
312
+ const proxy = provider;
313
+ return typeof proxy?.getDelegate === "function" ? proxy.getDelegate() : provider;
314
+ }
315
+ /**
316
+ * Registers `bridge` as the global OTel context manager and tracer provider.
317
+ *
318
+ * - Idempotent while the bridge is registered.
319
+ * - Steps aside (`"deferred"`) when both globals are already registered by
320
+ * someone else: an OTel SDK the application set up, or the Workers runtime
321
+ * once it registers the OTel API natively. The existing setup keeps working.
322
+ * - Throws when only one of the two is registered, or the registry belongs to
323
+ * an incompatible `@opentelemetry/api` copy: either would leave OTel spans
324
+ * silently detached from native tracing.
325
+ */
326
+ function registerBridge(bridge) {
327
+ const registry = otelGlobal();
328
+ const contextOwner = registry?.context;
329
+ const traceOwner = registry?.trace;
330
+ const ownsContext = contextOwner === bridge.contextManager;
331
+ const ownsTrace = traceOwner !== void 0 && delegateOf(traceOwner) === bridge.tracerProvider;
332
+ if (ownsContext && ownsTrace) return "already-registered";
333
+ if (contextOwner !== void 0 && traceOwner !== void 0 && !ownsContext && !ownsTrace) {
334
+ diag.info("agents/observability: OpenTelemetry is already registered; experimental_registerOpenTelemetry() left it in place.");
335
+ return "deferred";
336
+ }
337
+ if (contextOwner !== void 0 || traceOwner !== void 0) throw new Error(`experimental_registerOpenTelemetry(): an OpenTelemetry ${contextOwner === void 0 ? "tracer provider" : "context manager"} is already registered without its ${contextOwner === void 0 ? "context manager" : "tracer provider"}. Remove the partial OpenTelemetry setup, or register both before calling experimental_registerOpenTelemetry().`);
338
+ if (!context.setGlobalContextManager(bridge.contextManager)) throw incompatible(registry?.version);
339
+ bridge.contextManager.enable();
340
+ if (!trace.setGlobalTracerProvider(bridge.tracerProvider)) {
341
+ context.disable();
342
+ throw incompatible(registry?.version);
343
+ }
344
+ return "registered";
345
+ }
346
+ function incompatible(version) {
347
+ return /* @__PURE__ */ new Error(`experimental_registerOpenTelemetry(): the global OpenTelemetry API rejected the registration${version === void 0 ? "" : ` (globals were created by @opentelemetry/api ${version})`}. Install a single version of @opentelemetry/api.`);
348
+ }
349
+ //#endregion
350
+ //#region src/observability/otel/index.ts
351
+ let bridge;
352
+ /**
353
+ * Connects the OpenTelemetry API (`@opentelemetry/api`) to Workers tracing.
354
+ * Call once at module scope:
355
+ *
356
+ * ```ts
357
+ * import { experimental_registerOpenTelemetry } from "agents/observability";
358
+ *
359
+ * experimental_registerOpenTelemetry();
360
+ * ```
361
+ *
362
+ * Afterwards, libraries instrumented with the OpenTelemetry API (the MCP SDK,
363
+ * AI SDK telemetry, your own `trace.getTracer(...)` spans) record native
364
+ * Workers spans. They nest with the Agents SDK's spans and the automatic
365
+ * fetch, KV, D1 and Durable Object spans, and export through
366
+ * `observability.traces.destinations`. Enable `observability.traces` in your
367
+ * Wrangler configuration for anything to be recorded.
368
+ *
369
+ * Safe to call more than once. When OpenTelemetry is already fully registered,
370
+ * by your own SDK setup or natively by the Workers runtime, this leaves it in
371
+ * place and does nothing. Throws when only part of an OpenTelemetry setup is
372
+ * registered.
373
+ *
374
+ * @experimental Undocumented and subject to change: a temporary bridge until
375
+ * Workers supports the OpenTelemetry API natively. See
376
+ * `design/rfc-opentelemetry-bridge.md` for what it records and refuses.
377
+ */
378
+ function experimental_registerOpenTelemetry() {
379
+ if (nativeTracing === void 0) {
380
+ diag.warn("agents/observability: this runtime has no native tracing; experimental_registerOpenTelemetry() did nothing.");
381
+ return;
382
+ }
383
+ bridge ??= createOpenTelemetryBridge({ tracing: nativeTracing });
384
+ registerBridge(bridge);
385
+ }
386
+ //#endregion
3
387
  //#region src/observability/index.ts
4
388
  /**
5
389
  * Channel keys whose diagnostics channel name differs from `agents:${key}`.
@@ -8,15 +392,6 @@ import { subscribe as subscribe$1, unsubscribe } from "node:diagnostics_channel"
8
392
  */
9
393
  const CHANNEL_DIAGNOSTIC_NAME_OVERRIDES = { agentTool: "agents:agent_tool" };
10
394
  /**
11
- * The default observability implementation.
12
- *
13
- * Publishes events to diagnostics_channel. Events are silent unless
14
- * a subscriber is registered or a Tail Worker is attached.
15
- */
16
- const genericObservability = { emit(event) {
17
- publishDiagnosticsEvent(event);
18
- } };
19
- /**
20
395
  * Subscribe to a typed observability channel.
21
396
  *
22
397
  * ```ts
@@ -36,6 +411,6 @@ function subscribe(channelKey, callback) {
36
411
  return () => unsubscribe(name, handler);
37
412
  }
38
413
  //#endregion
39
- export { channels, genericObservability, subscribe };
414
+ export { channels, experimental_registerOpenTelemetry, genericObservability, subscribe };
40
415
 
41
416
  //# sourceMappingURL=index.js.map