@telemetry-dev/bedrock 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 telemetry.dev
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,157 @@
1
+ # @telemetry-dev/bedrock
2
+
3
+ First-class AWS Bedrock instrumentation for the telemetry.dev TypeScript SDK.
4
+
5
+ This package instruments AWS SDK for JavaScript v3 clients for:
6
+
7
+ - `@aws-sdk/client-bedrock-runtime`
8
+ - `Converse`
9
+ - `ConverseStream`
10
+ - `InvokeModel`
11
+ - `InvokeModelWithResponseStream`
12
+ - `ApplyGuardrail`
13
+ - `@aws-sdk/client-bedrock-agent-runtime`
14
+ - `InvokeAgent`
15
+ - `InvokeInlineAgent`
16
+ - `Retrieve`
17
+ - `RetrieveAndGenerate`
18
+ - `RetrieveAndGenerateStream`
19
+ - `InvokeFlow`
20
+
21
+ Telemetry is emitted through the public `@telemetry-dev/sdk` span API. No AWS request payloads are mutated.
22
+
23
+ ## Install
24
+
25
+ ```sh
26
+ pnpm add @telemetry-dev/sdk @telemetry-dev/bedrock @aws-sdk/client-bedrock-runtime
27
+ # Agent Runtime support is optional:
28
+ pnpm add @aws-sdk/client-bedrock-agent-runtime
29
+ ```
30
+
31
+ ## Quickstart
32
+
33
+ ```ts
34
+ import { BedrockRuntimeClient, ConverseCommand } from "@aws-sdk/client-bedrock-runtime";
35
+ import { init, shutdown } from "@telemetry-dev/sdk";
36
+ import { wrapBedrock } from "@telemetry-dev/bedrock";
37
+
38
+ init({
39
+ apiKey: process.env.TELEMETRY_DEV_API_KEY,
40
+ serviceName: "bedrock-app",
41
+ environment: "production",
42
+ });
43
+
44
+ const bedrock = wrapBedrock(new BedrockRuntimeClient({ region: "us-east-1" }));
45
+
46
+ await bedrock.send(
47
+ new ConverseCommand({
48
+ modelId: "anthropic.claude-3-5-haiku-20241022-v1:0",
49
+ messages: [{ role: "user", content: [{ text: "Hello" }] }],
50
+ }),
51
+ );
52
+
53
+ await shutdown();
54
+ ```
55
+
56
+ `wrapBedrock` is per-client and idempotent. It accepts any structural client with a `send(command, options?)` method, so it works with `BedrockRuntimeClient`, `BedrockRuntime`, and tests/fakes using real command objects.
57
+
58
+ ## Global runtime instrumentation
59
+
60
+ ```ts
61
+ import { instrumentBedrock, uninstrumentBedrock } from "@telemetry-dev/bedrock";
62
+
63
+ instrumentBedrock();
64
+ // BedrockRuntimeClient instances created before or after this point are instrumented.
65
+ uninstrumentBedrock();
66
+ ```
67
+
68
+ Global instrumentation shadows `BedrockRuntimeClient.prototype.send`. It does not patch the shared Smithy base client, so other AWS SDK clients are untouched.
69
+
70
+ ## Agent Runtime entrypoint
71
+
72
+ Agent Runtime support lives in a subpath so `@aws-sdk/client-bedrock-agent-runtime` can stay optional for runtime-only users.
73
+
74
+ ```ts
75
+ import {
76
+ BedrockAgentRuntimeClient,
77
+ InvokeAgentCommand,
78
+ } from "@aws-sdk/client-bedrock-agent-runtime";
79
+ import { wrapBedrockAgents, instrumentBedrockAgents } from "@telemetry-dev/bedrock/agents";
80
+
81
+ const agent = wrapBedrockAgents(new BedrockAgentRuntimeClient({}), {
82
+ captureAgentTrace: true,
83
+ });
84
+
85
+ await agent.send(
86
+ new InvokeAgentCommand({
87
+ agentId: process.env.BEDROCK_AGENT_ID!,
88
+ agentAliasId: process.env.BEDROCK_AGENT_ALIAS_ID!,
89
+ sessionId: crypto.randomUUID(),
90
+ inputText: "Hello",
91
+ enableTrace: true,
92
+ }),
93
+ );
94
+
95
+ instrumentBedrockAgents({ captureAgentTrace: false });
96
+ ```
97
+
98
+ ## Options
99
+
100
+ | Option | Default | Applies to | Notes |
101
+ | ------------------- | ------- | --------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------- |
102
+ | `captureAgentTrace` | `false` | Agent Runtime streams | Aggregates trace usage and counts by default. When enabled, also attaches raw trace events as `td.metadata.agent_trace` after SDK masking/truncation. |
103
+
104
+ ## Signal coverage
105
+
106
+ All instrumented AWS responses/errors include `gen_ai.response.id` from the AWS request id, plus `aws.http.status_code`, `aws.request.attempts` when retries occurred, and `aws.request.total_retry_delay_ms` when the SDK exposes them.
107
+
108
+ | Operation | Span type | Span name | Captured fields |
109
+ | ----------------------------------- | --------------------------- | ----------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
110
+ | `Converse` | `generation` | `chat {modelId}` | normalized input/output messages, system instructions, sampling params, usage/cache usage, finish reason, request id, retry attempts, prompt-router response model, server latency, guardrail metadata |
111
+ | `ConverseStream` | `generation` | `chat {modelId}` | pull-through stream output, time-to-first-chunk, usage/latency from `metadata`, partial output on early break/error |
112
+ | `InvokeModel` | `generation` or `embedding` | `chat {modelId}` / `embeddings {modelId}` | native JSON request/response bodies, provider-native sampling, provider-native usage, embedding output type |
113
+ | `InvokeModelWithResponseStream` | `generation` or `embedding` | `chat {modelId}` / `embeddings {modelId}` | provider-native chunk text where known, optional final `amazon-bedrock-invocationMetrics` usage |
114
+ | `ApplyGuardrail` | `span` | `apply_guardrail {guardrailIdentifier}` | guardrail input/output, action, action reason, request id |
115
+ | `InvokeAgent` / `InvokeInlineAgent` | `agent` | `invoke_agent {agentId}` / `invoke_agent {agentName}` | user input, streamed answer, session/memory ids, alias id, trace usage aggregation, trace event count, return-control output |
116
+ | `Retrieve` | `span` | `retrieve {knowledgeBaseId}` | query, retrieval results, guardrail action, result count metadata |
117
+ | `RetrieveAndGenerate` / stream | `generation` | `retrieve_and_generate {modelArn basename}` | input text, generated text, citations count, session id, guardrail action |
118
+ | `InvokeFlow` | `agent` | `invoke_flow {flowIdentifier}` | inputs, flow output events, completion reason |
119
+
120
+ ## Message normalization
121
+
122
+ Converse messages follow the OpenTelemetry GenAI non-normative LLM-call examples:
123
+
124
+ - text blocks become `{ type: "text", content }`
125
+ - `toolUse` becomes `{ type: "tool_call", id, name, arguments }`
126
+ - `toolResult` becomes `{ type: "tool_call_response", id, response }`
127
+ - reasoning text becomes `{ type: "reasoning", content }`
128
+ - image/document/video/audio bytes become blob parts without byte content
129
+ - S3/URI sources become `{ type: "uri", uri, modality }`
130
+
131
+ InvokeModel captures provider-native JSON bodies verbatim. Non-JSON bodies are not captured.
132
+
133
+ ## Semantics and guarantees
134
+
135
+ - Provider is emitted as `amazon-bedrock`. This intentionally differs from the OpenTelemetry registry value `aws.bedrock` so telemetry.dev pricing keys match Bedrock model IDs exactly. The raw caller `modelId`, `modelArn`, or `foundationModel` is emitted as the model.
136
+ - Instrumentation is fail-open. Normalization, span updates, and span endings are guarded so telemetry failures do not break caller code.
137
+ - Requests are never modified. This is especially important for AWS SigV4 signing and for application-level request object reuse.
138
+ - Streams are pull-through. The wrapper does not pre-buffer chunks and therefore preserves backpressure.
139
+ - Streams end spans exactly once. Exhaustion records full output and finish reason; early `break`, `return()`, `close()`, abort, or stream errors record partial output.
140
+ - `AbortSignal` passed to `send(command, { abortSignal })` is forwarded untouched. Pre-response aborts end the span with the thrown abort error. Mid-stream aborts end the span with partial output and the stream error.
141
+ - Callback-style `send(command, callback)` and `send(command, options, callback)` calls are instrumented; callbacks receive the original data/error while the span is ended before callback invocation.
142
+
143
+ ## Coverage gaps
144
+
145
+ The following calls pass through unless a supported operation above is used:
146
+
147
+ - `CountTokens`
148
+ - `InvokeGuardrailChecks`
149
+ - `InvokeModelWithBidirectionalStream`
150
+ - `StartAsyncInvoke`, `GetAsyncInvoke`, `ListAsyncInvokes`
151
+ - Agent Runtime session CRUD
152
+ - `Rerank`
153
+ - `GenerateQuery`
154
+ - `OptimizePrompt`
155
+ - `AgenticRetrieveStream`
156
+
157
+ Provider-native `InvokeModel` usage is best-effort. Anthropic Claude, Amazon Titan/Nova, Meta Llama, and Titan embeddings expose known token fields. Cohere and Mistral text models do not consistently include usage in the JSON body; spans still capture request/response bodies and finish reasons where present.
@@ -0,0 +1,11 @@
1
+ import { t as BedrockInstrumentationOptions } from "./internal-_ZoDhB3-.mjs";
2
+
3
+ //#region src/agents.d.ts
4
+ interface WrappableBedrockAgentClient {
5
+ send: (...args: never[]) => unknown;
6
+ }
7
+ declare function wrapBedrockAgents<T extends WrappableBedrockAgentClient>(client: T, options?: BedrockInstrumentationOptions): T;
8
+ declare function instrumentBedrockAgents(options?: BedrockInstrumentationOptions): void;
9
+ declare function uninstrumentBedrockAgents(): void;
10
+ //#endregion
11
+ export { type BedrockInstrumentationOptions, WrappableBedrockAgentClient, instrumentBedrockAgents, uninstrumentBedrockAgents, wrapBedrockAgents };
@@ -0,0 +1,52 @@
1
+ import { r as createInstrumentedSend, t as AGENT_HANDLERS } from "./internal-handlers-BloMjBP8.mjs";
2
+ import { BedrockAgentRuntimeClient } from "@aws-sdk/client-bedrock-agent-runtime";
3
+ //#region src/agents.ts
4
+ const WRAPPED = /* @__PURE__ */ new WeakSet();
5
+ let ORIGINAL;
6
+ function wrapBedrockAgents(client, options = {}) {
7
+ if (WRAPPED.has(client)) return client;
8
+ const original = client.send;
9
+ Object.defineProperty(client, "send", {
10
+ value: createInstrumentedSend(original, options, AGENT_HANDLERS),
11
+ configurable: true,
12
+ writable: true
13
+ });
14
+ WRAPPED.add(client);
15
+ return client;
16
+ }
17
+ function instrumentBedrockAgents(options = {}) {
18
+ if (ORIGINAL) return;
19
+ const proto = BedrockAgentRuntimeClient.prototype;
20
+ const hadOwn = Object.prototype.hasOwnProperty.call(proto, "send");
21
+ const original = proto.send;
22
+ const instrumentedSend = createInstrumentedSend(original, options, AGENT_HANDLERS);
23
+ const wrapper = function telemetryDevBedrockAgentSend(...args) {
24
+ if (WRAPPED.has(this)) return original.apply(this, args);
25
+ return instrumentedSend.apply(this, args);
26
+ };
27
+ ORIGINAL = {
28
+ proto,
29
+ hadOwn,
30
+ value: original,
31
+ wrapper
32
+ };
33
+ Object.defineProperty(proto, "send", {
34
+ configurable: true,
35
+ writable: true,
36
+ value: wrapper
37
+ });
38
+ }
39
+ function uninstrumentBedrockAgents() {
40
+ const original = ORIGINAL;
41
+ if (!original) return;
42
+ if (Object.getOwnPropertyDescriptor(original.proto, "send")?.value !== original.wrapper) return;
43
+ ORIGINAL = void 0;
44
+ if (original.hadOwn) Object.defineProperty(original.proto, "send", {
45
+ configurable: true,
46
+ writable: true,
47
+ value: original.value
48
+ });
49
+ else Reflect.deleteProperty(original.proto, "send");
50
+ }
51
+ //#endregion
52
+ export { instrumentBedrockAgents, uninstrumentBedrockAgents, wrapBedrockAgents };
@@ -0,0 +1,11 @@
1
+ import { t as BedrockInstrumentationOptions } from "./internal-_ZoDhB3-.mjs";
2
+
3
+ //#region src/index.d.ts
4
+ interface WrappableBedrockClient {
5
+ send: (...args: never[]) => unknown;
6
+ }
7
+ declare function wrapBedrock<T extends WrappableBedrockClient>(client: T, options?: BedrockInstrumentationOptions): T;
8
+ declare function instrumentBedrock(options?: BedrockInstrumentationOptions): void;
9
+ declare function uninstrumentBedrock(): void;
10
+ //#endregion
11
+ export { type BedrockInstrumentationOptions, WrappableBedrockClient, instrumentBedrock, uninstrumentBedrock, wrapBedrock };
package/dist/index.mjs ADDED
@@ -0,0 +1,52 @@
1
+ import { n as RUNTIME_HANDLERS, r as createInstrumentedSend } from "./internal-handlers-BloMjBP8.mjs";
2
+ import { BedrockRuntimeClient } from "@aws-sdk/client-bedrock-runtime";
3
+ //#region src/index.ts
4
+ const WRAPPED = /* @__PURE__ */ new WeakSet();
5
+ let ORIGINAL;
6
+ function wrapBedrock(client, options = {}) {
7
+ if (WRAPPED.has(client)) return client;
8
+ const original = client.send;
9
+ Object.defineProperty(client, "send", {
10
+ value: createInstrumentedSend(original, options, RUNTIME_HANDLERS),
11
+ configurable: true,
12
+ writable: true
13
+ });
14
+ WRAPPED.add(client);
15
+ return client;
16
+ }
17
+ function instrumentBedrock(options = {}) {
18
+ if (ORIGINAL) return;
19
+ const proto = BedrockRuntimeClient.prototype;
20
+ const hadOwn = Object.prototype.hasOwnProperty.call(proto, "send");
21
+ const original = proto.send;
22
+ const instrumentedSend = createInstrumentedSend(original, options, RUNTIME_HANDLERS);
23
+ const wrapper = function telemetryDevBedrockSend(...args) {
24
+ if (WRAPPED.has(this)) return original.apply(this, args);
25
+ return instrumentedSend.apply(this, args);
26
+ };
27
+ ORIGINAL = {
28
+ proto,
29
+ hadOwn,
30
+ value: original,
31
+ wrapper
32
+ };
33
+ Object.defineProperty(proto, "send", {
34
+ configurable: true,
35
+ writable: true,
36
+ value: wrapper
37
+ });
38
+ }
39
+ function uninstrumentBedrock() {
40
+ const original = ORIGINAL;
41
+ if (!original) return;
42
+ if (Object.getOwnPropertyDescriptor(original.proto, "send")?.value !== original.wrapper) return;
43
+ ORIGINAL = void 0;
44
+ if (original.hadOwn) Object.defineProperty(original.proto, "send", {
45
+ configurable: true,
46
+ writable: true,
47
+ value: original.value
48
+ });
49
+ else Reflect.deleteProperty(original.proto, "send");
50
+ }
51
+ //#endregion
52
+ export { instrumentBedrock, uninstrumentBedrock, wrapBedrock };
@@ -0,0 +1,6 @@
1
+ //#region src/internal.d.ts
2
+ interface BedrockInstrumentationOptions {
3
+ captureAgentTrace?: boolean;
4
+ }
5
+ //#endregion
6
+ export { BedrockInstrumentationOptions as t };