@briefcase-ai/auto 0.0.0 → 5.0.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 (42) hide show
  1. package/README.md +103 -0
  2. package/dist/activate.d.ts +35 -0
  3. package/dist/activate.js +108 -0
  4. package/dist/auto.d.ts +92 -0
  5. package/dist/auto.js +350 -0
  6. package/dist/context.d.ts +49 -0
  7. package/dist/context.js +82 -0
  8. package/dist/detect.d.ts +26 -0
  9. package/dist/detect.js +127 -0
  10. package/dist/esbuild.d.ts +40 -0
  11. package/dist/esbuild.js +55 -0
  12. package/dist/exporters.d.ts +196 -0
  13. package/dist/exporters.js +405 -0
  14. package/dist/index.d.ts +16 -0
  15. package/dist/index.js +14 -0
  16. package/dist/instrument/anthropic.d.ts +40 -0
  17. package/dist/instrument/anthropic.js +178 -0
  18. package/dist/instrument/bedrock.d.ts +53 -0
  19. package/dist/instrument/bedrock.js +256 -0
  20. package/dist/instrument/core.d.ts +257 -0
  21. package/dist/instrument/core.js +772 -0
  22. package/dist/instrument/google-genai.d.ts +71 -0
  23. package/dist/instrument/google-genai.js +289 -0
  24. package/dist/instrument/openai.d.ts +68 -0
  25. package/dist/instrument/openai.js +293 -0
  26. package/dist/instrument/stainless.d.ts +41 -0
  27. package/dist/instrument/stainless.js +151 -0
  28. package/dist/loader.d.ts +79 -0
  29. package/dist/loader.js +202 -0
  30. package/dist/observe.d.ts +60 -0
  31. package/dist/observe.js +246 -0
  32. package/dist/pipeline.d.ts +48 -0
  33. package/dist/pipeline.js +155 -0
  34. package/dist/record.d.ts +54 -0
  35. package/dist/record.js +55 -0
  36. package/dist/register.d.ts +9 -0
  37. package/dist/register.js +12 -0
  38. package/dist/state.d.ts +25 -0
  39. package/dist/state.js +29 -0
  40. package/dist/util.d.ts +51 -0
  41. package/dist/util.js +198 -0
  42. package/package.json +84 -1
@@ -0,0 +1,40 @@
1
+ /**
2
+ * Instrumentation for the `@anthropic-ai/sdk` Node SDK.
3
+ *
4
+ * Verified against @anthropic-ai/sdk 1.12.0 (npm), by reading the installed
5
+ * package's `.mjs` / `.js` sources and `.d.ts` types, and by the offline
6
+ * tests in `test/anthropic.test.ts`.
7
+ *
8
+ * Patch targets (prototype methods, patched in both the CommonJS and the ESM
9
+ * copy of the package), all recorded as `decision_type: "llm.anthropic.messages"`:
10
+ *
11
+ * - `@anthropic-ai/sdk/resources/messages/messages` `Messages.prototype.create`
12
+ * - `@anthropic-ai/sdk/resources/beta/messages/messages` `Messages.prototype.create`
13
+ *
14
+ * Layout facts relied on, as found in 1.12.0:
15
+ *
16
+ * - `messages.parse()` calls `this.create()`; `messages.stream()` builds a
17
+ * `MessageStream` whose request is `messages.create({ ...params, stream: true })`
18
+ * with header `x-stainless-helper-method: stream`. Both are covered by the
19
+ * `create` patch; the `MessageStream` object (`.on()`, `.finalMessage()`,
20
+ * `.controller.abort()`) is not touched.
21
+ * - `create()` returns an `APIPromise`; `stream: true` parses to a `Stream`
22
+ * of raw events (see `stainless.ts`).
23
+ * - Usage: `Message.usage` (`input_tokens`, `output_tokens`,
24
+ * `cache_read_input_tokens`, `cache_creation_input_tokens`). In a stream,
25
+ * `message_start.message.usage` carries the input side and each
26
+ * `message_delta.usage` the cumulative `output_tokens`; `message_delta.delta.stop_reason`
27
+ * the stop reason; `content_block_delta.delta` (`type: "text_delta"`) the text.
28
+ * `input_tokens` excludes cached tokens, so `total_tokens` is
29
+ * `input_tokens + output_tokens` with the cache counters reported next to it.
30
+ * - The request id is the `request-id` response header (`_request_id` on
31
+ * parsed bodies).
32
+ */
33
+ import { type Instrumentor, type PatchTarget, type SdkFile } from "./core.js";
34
+ export declare const PROVIDER = "anthropic";
35
+ export declare const PACKAGE = "@anthropic-ai/sdk";
36
+ export declare const VERIFIED_VERSION = "1.12.0";
37
+ export declare const DECISION_TYPE = "llm.anthropic.messages";
38
+ export declare const SPECIFIERS: ("@anthropic-ai/sdk/resources/messages/messages" | "@anthropic-ai/sdk/resources/beta/messages/messages")[];
39
+ export declare const FILES: SdkFile[];
40
+ export declare function targets(inst: Instrumentor, modules: Record<string, Record<string, unknown> | undefined>): PatchTarget[];
@@ -0,0 +1,178 @@
1
+ /**
2
+ * Instrumentation for the `@anthropic-ai/sdk` Node SDK.
3
+ *
4
+ * Verified against @anthropic-ai/sdk 1.12.0 (npm), by reading the installed
5
+ * package's `.mjs` / `.js` sources and `.d.ts` types, and by the offline
6
+ * tests in `test/anthropic.test.ts`.
7
+ *
8
+ * Patch targets (prototype methods, patched in both the CommonJS and the ESM
9
+ * copy of the package), all recorded as `decision_type: "llm.anthropic.messages"`:
10
+ *
11
+ * - `@anthropic-ai/sdk/resources/messages/messages` `Messages.prototype.create`
12
+ * - `@anthropic-ai/sdk/resources/beta/messages/messages` `Messages.prototype.create`
13
+ *
14
+ * Layout facts relied on, as found in 1.12.0:
15
+ *
16
+ * - `messages.parse()` calls `this.create()`; `messages.stream()` builds a
17
+ * `MessageStream` whose request is `messages.create({ ...params, stream: true })`
18
+ * with header `x-stainless-helper-method: stream`. Both are covered by the
19
+ * `create` patch; the `MessageStream` object (`.on()`, `.finalMessage()`,
20
+ * `.controller.abort()`) is not touched.
21
+ * - `create()` returns an `APIPromise`; `stream: true` parses to a `Stream`
22
+ * of raw events (see `stainless.ts`).
23
+ * - Usage: `Message.usage` (`input_tokens`, `output_tokens`,
24
+ * `cache_read_input_tokens`, `cache_creation_input_tokens`). In a stream,
25
+ * `message_start.message.usage` carries the input side and each
26
+ * `message_delta.usage` the cumulative `output_tokens`; `message_delta.delta.stop_reason`
27
+ * the stop reason; `content_block_delta.delta` (`type: "text_delta"`) the text.
28
+ * `input_tokens` excludes cached tokens, so `total_tokens` is
29
+ * `input_tokens + output_tokens` with the cache counters reported next to it.
30
+ * - The request id is the `request-id` response header (`_request_id` on
31
+ * parsed bodies).
32
+ */
33
+ import { tokenUsage } from "../record.js";
34
+ import { TextAccumulator, read, scalarParams } from "../util.js";
35
+ import { StreamState, stainlessFiles, } from "./core.js";
36
+ import { wrapStainlessMethod } from "./stainless.js";
37
+ export const PROVIDER = "anthropic";
38
+ export const PACKAGE = "@anthropic-ai/sdk";
39
+ export const VERIFIED_VERSION = "1.12.0";
40
+ export const DECISION_TYPE = "llm.anthropic.messages";
41
+ const PARAMS = ["max_tokens", "service_tier", "speed", "inference_geo", "temperature", "top_p", "top_k"];
42
+ const INPUT_KEYS = ["system", "messages", "tools"];
43
+ function usage(value) {
44
+ return tokenUsage(read(value, "input_tokens"), read(value, "output_tokens"), undefined, {
45
+ cache_read_input_tokens: read(value, "cache_read_input_tokens"),
46
+ cache_creation_input_tokens: read(value, "cache_creation_input_tokens"),
47
+ });
48
+ }
49
+ function contentBlocks(blocks) {
50
+ const texts = [];
51
+ const toolCalls = [];
52
+ for (const block of Array.isArray(blocks) ? blocks : []) {
53
+ const kind = read(block, "type");
54
+ if (kind === "text")
55
+ texts.push(String(read(block, "text") ?? ""));
56
+ else if (kind === "tool_use")
57
+ toolCalls.push({ id: read(block, "id"), name: read(block, "name"), input: read(block, "input") });
58
+ }
59
+ const content = { content: texts.join("") };
60
+ if (toolCalls.length)
61
+ content["tool_calls"] = toolCalls;
62
+ return content;
63
+ }
64
+ function messageInfo(message, wantContent) {
65
+ const info = {
66
+ model: read(message, "model"),
67
+ response_id: read(message, "id"),
68
+ request_id: read(message, "_request_id"),
69
+ finish_reason: read(message, "stop_reason"),
70
+ usage: usage(read(message, "usage")),
71
+ };
72
+ if (wantContent)
73
+ info.content = contentBlocks(read(message, "content"));
74
+ return info;
75
+ }
76
+ class MessageStreamState extends StreamState {
77
+ inst;
78
+ text;
79
+ data;
80
+ counters = {};
81
+ constructor(call, inst, requestId) {
82
+ super(call);
83
+ this.inst = inst;
84
+ this.text = new TextAccumulator(inst.options.maxContentChars);
85
+ this.data = { request_id: requestId };
86
+ }
87
+ readUsage(value) {
88
+ for (const key of ["input_tokens", "output_tokens", "cache_read_input_tokens", "cache_creation_input_tokens"]) {
89
+ const n = read(value, key);
90
+ if (typeof n === "number" && Number.isFinite(n))
91
+ this.counters[key] = n;
92
+ }
93
+ }
94
+ observe(event) {
95
+ const kind = read(event, "type");
96
+ if (kind === "message_start") {
97
+ const message = read(event, "message");
98
+ this.data.model = read(message, "model");
99
+ this.data.response_id = read(message, "id");
100
+ this.readUsage(read(message, "usage"));
101
+ }
102
+ else if (kind === "message_delta") {
103
+ this.readUsage(read(event, "usage"));
104
+ const stop = read(event, "delta", "stop_reason");
105
+ if (stop)
106
+ this.data.finish_reason = stop;
107
+ }
108
+ else if (kind === "content_block_delta" && this.inst.capturesContent) {
109
+ if (read(event, "delta", "type") === "text_delta")
110
+ this.text.add(read(event, "delta", "text"));
111
+ }
112
+ }
113
+ info() {
114
+ const info = { ...this.data, usage: usage(this.counters) };
115
+ if (this.inst.capturesContent)
116
+ info.content = { content: this.text.text };
117
+ return info;
118
+ }
119
+ }
120
+ function helperMethod(options) {
121
+ const headers = read(options, "headers");
122
+ if (!headers || typeof headers !== "object")
123
+ return null;
124
+ const get = headers.get;
125
+ if (typeof get === "function") {
126
+ const value = get.call(headers, "x-stainless-helper-method");
127
+ return typeof value === "string" ? value : null;
128
+ }
129
+ for (const [key, value] of Object.entries(headers)) {
130
+ if (key.toLowerCase() === "x-stainless-helper-method" && typeof value === "string")
131
+ return value;
132
+ }
133
+ return null;
134
+ }
135
+ const SURFACES = [
136
+ { specifier: "@anthropic-ai/sdk/resources/messages/messages", functionBase: "anthropic.messages" },
137
+ { specifier: "@anthropic-ai/sdk/resources/beta/messages/messages", functionBase: "anthropic.beta.messages" },
138
+ ];
139
+ export const SPECIFIERS = SURFACES.map((s) => s.specifier);
140
+ export const FILES = stainlessFiles(PACKAGE, SPECIFIERS);
141
+ export function targets(inst, modules) {
142
+ return SURFACES.map((surface) => {
143
+ const begin = (args) => {
144
+ const body = args[0];
145
+ if (!body || typeof body !== "object")
146
+ return null;
147
+ const params = scalarParams(body, PARAMS);
148
+ const effort = read(body, "output_config", "effort");
149
+ if (typeof effort === "string")
150
+ params["effort"] = effort;
151
+ const helper = helperMethod(args[1]);
152
+ return inst.begin(DECISION_TYPE, `${surface.functionBase}.${helper === "stream" ? "stream" : "create"}`, {
153
+ model: read(body, "model"),
154
+ params,
155
+ inputs: () => {
156
+ const out = {};
157
+ for (const key of INPUT_KEYS)
158
+ if (read(body, key) !== undefined)
159
+ out[key] = read(body, key);
160
+ return out;
161
+ },
162
+ stream: read(body, "stream") === true,
163
+ });
164
+ };
165
+ const hooks = {
166
+ requestIdHeader: "request-id",
167
+ info: (parsed) => messageInfo(parsed, inst.capturesContent),
168
+ streamState: (call, requestId) => new MessageStreamState(call, inst, requestId),
169
+ };
170
+ return {
171
+ kind: "method",
172
+ owner: read(modules[surface.specifier]?.["Messages"], "prototype"),
173
+ key: "create",
174
+ label: `${surface.specifier}#Messages.create`,
175
+ wrap: wrapStainlessMethod(inst, begin, hooks),
176
+ };
177
+ });
178
+ }
@@ -0,0 +1,53 @@
1
+ /**
2
+ * Instrumentation for Amazon Bedrock Runtime through the AWS SDK for
3
+ * JavaScript v3 (`@aws-sdk/client-bedrock-runtime`).
4
+ *
5
+ * Verified against @aws-sdk/client-bedrock-runtime 3.1175.0 (with
6
+ * @smithy/core 3.41.0), by reading `dist-cjs/index.js`,
7
+ * `@smithy/core/dist-cjs/submodules/client/index.js` and
8
+ * `dist-types/models/models_0.d.ts`, and by the offline tests in
9
+ * `test/bedrock.test.ts`.
10
+ *
11
+ * Seam: the client middleware stack (`client.middlewareStack.add`), the
12
+ * documented AWS SDK v3 extension point. The package has no `exports` map
13
+ * and resolves to its CommonJS build for both `import` and `require`, so
14
+ * there is one copy. `BedrockRuntimeClient.prototype` gets an own `send`
15
+ * (the method is inherited from `@smithy/core`'s `Client`) that adds an
16
+ * `initialize`-step middleware named `briefcaseAutoMiddleware` to the
17
+ * client's stack once, then calls the inherited `send`. `BedrockRuntime`
18
+ * (the aggregated client) extends `BedrockRuntimeClient` and is covered.
19
+ * `undo()` removes the own `send`; clients that already carry the
20
+ * middleware keep it, switched to pass-through.
21
+ *
22
+ * | command | decision_type |
23
+ * |----------------------------------------|----------------------------|
24
+ * | `ConverseCommand` | `llm.bedrock.converse` |
25
+ * | `ConverseStreamCommand` | `llm.bedrock.converse` |
26
+ * | `InvokeModelCommand` | `llm.bedrock.invoke_model` |
27
+ * | `InvokeModelWithResponseStreamCommand` | `llm.bedrock.invoke_model` |
28
+ *
29
+ * Fields read (3.1175.0 types): Converse `usage` (`inputTokens`,
30
+ * `outputTokens`, `totalTokens`, `cacheReadInputTokens`,
31
+ * `cacheWriteInputTokens`), `stopReason`, `output.message.content[].text`;
32
+ * ConverseStream `output.stream` events `messageStop.stopReason`,
33
+ * `metadata.usage`, `contentBlockDelta.delta.text` (the stream object is
34
+ * instrumented in place); InvokeModel token counts from the
35
+ * `x-amzn-bedrock-input-token-count` / `x-amzn-bedrock-output-token-count`
36
+ * response headers (the body is never read); the request id from
37
+ * `$metadata.requestId`. InvokeModelWithResponseStream: the final chunk's
38
+ * `amazon-bedrock-invocationMetrics` (provider JSON, parsed defensively,
39
+ * not described by the SDK types; mirrors the Python module).
40
+ */
41
+ import { type Instrumentor, type PatchTarget, type SdkFile } from "./core.js";
42
+ export declare const PROVIDER = "bedrock";
43
+ export declare const PACKAGE = "@aws-sdk/client-bedrock-runtime";
44
+ export declare const VERIFIED_VERSION = "3.1175.0";
45
+ export declare const SPECIFIERS: string[];
46
+ /**
47
+ * `dist-cjs/index.js` is what Node loads (`main`; there is no `exports`
48
+ * map). `dist-es/BedrockRuntimeClient.js` is the ES build bundlers pick
49
+ * through the `module` field.
50
+ */
51
+ export declare const FILES: SdkFile[];
52
+ export declare const MIDDLEWARE_NAME = "briefcaseAutoMiddleware";
53
+ export declare function targets(inst: Instrumentor, modules: Record<string, Record<string, unknown> | undefined>): PatchTarget[];
@@ -0,0 +1,256 @@
1
+ /**
2
+ * Instrumentation for Amazon Bedrock Runtime through the AWS SDK for
3
+ * JavaScript v3 (`@aws-sdk/client-bedrock-runtime`).
4
+ *
5
+ * Verified against @aws-sdk/client-bedrock-runtime 3.1175.0 (with
6
+ * @smithy/core 3.41.0), by reading `dist-cjs/index.js`,
7
+ * `@smithy/core/dist-cjs/submodules/client/index.js` and
8
+ * `dist-types/models/models_0.d.ts`, and by the offline tests in
9
+ * `test/bedrock.test.ts`.
10
+ *
11
+ * Seam: the client middleware stack (`client.middlewareStack.add`), the
12
+ * documented AWS SDK v3 extension point. The package has no `exports` map
13
+ * and resolves to its CommonJS build for both `import` and `require`, so
14
+ * there is one copy. `BedrockRuntimeClient.prototype` gets an own `send`
15
+ * (the method is inherited from `@smithy/core`'s `Client`) that adds an
16
+ * `initialize`-step middleware named `briefcaseAutoMiddleware` to the
17
+ * client's stack once, then calls the inherited `send`. `BedrockRuntime`
18
+ * (the aggregated client) extends `BedrockRuntimeClient` and is covered.
19
+ * `undo()` removes the own `send`; clients that already carry the
20
+ * middleware keep it, switched to pass-through.
21
+ *
22
+ * | command | decision_type |
23
+ * |----------------------------------------|----------------------------|
24
+ * | `ConverseCommand` | `llm.bedrock.converse` |
25
+ * | `ConverseStreamCommand` | `llm.bedrock.converse` |
26
+ * | `InvokeModelCommand` | `llm.bedrock.invoke_model` |
27
+ * | `InvokeModelWithResponseStreamCommand` | `llm.bedrock.invoke_model` |
28
+ *
29
+ * Fields read (3.1175.0 types): Converse `usage` (`inputTokens`,
30
+ * `outputTokens`, `totalTokens`, `cacheReadInputTokens`,
31
+ * `cacheWriteInputTokens`), `stopReason`, `output.message.content[].text`;
32
+ * ConverseStream `output.stream` events `messageStop.stopReason`,
33
+ * `metadata.usage`, `contentBlockDelta.delta.text` (the stream object is
34
+ * instrumented in place); InvokeModel token counts from the
35
+ * `x-amzn-bedrock-input-token-count` / `x-amzn-bedrock-output-token-count`
36
+ * response headers (the body is never read); the request id from
37
+ * `$metadata.requestId`. InvokeModelWithResponseStream: the final chunk's
38
+ * `amazon-bedrock-invocationMetrics` (provider JSON, parsed defensively,
39
+ * not described by the SDK types; mirrors the Python module).
40
+ */
41
+ import { tokenUsage } from "../record.js";
42
+ import { TextAccumulator, debug, read, safe, scalarParams } from "../util.js";
43
+ import { StreamState, callStore, finishWhenCollected, instrumentAsyncIterable, } from "./core.js";
44
+ export const PROVIDER = "bedrock";
45
+ export const PACKAGE = "@aws-sdk/client-bedrock-runtime";
46
+ export const VERIFIED_VERSION = "3.1175.0";
47
+ export const SPECIFIERS = ["@aws-sdk/client-bedrock-runtime"];
48
+ /**
49
+ * `dist-cjs/index.js` is what Node loads (`main`; there is no `exports`
50
+ * map). `dist-es/BedrockRuntimeClient.js` is the ES build bundlers pick
51
+ * through the `module` field.
52
+ */
53
+ export const FILES = [
54
+ { specifier: SPECIFIERS[0], rel: "dist-cjs/index.js", format: "cjs", group: "main" },
55
+ { specifier: SPECIFIERS[0], rel: "dist-es/BedrockRuntimeClient.js", format: "esm", group: "es" },
56
+ ];
57
+ export const MIDDLEWARE_NAME = "briefcaseAutoMiddleware";
58
+ const OPERATIONS = {
59
+ ConverseCommand: { name: "Converse", decisionType: "llm.bedrock.converse", functionName: "bedrock-runtime.converse", stream: false },
60
+ ConverseStreamCommand: {
61
+ name: "ConverseStream",
62
+ decisionType: "llm.bedrock.converse",
63
+ functionName: "bedrock-runtime.converse_stream",
64
+ stream: true,
65
+ },
66
+ InvokeModelCommand: {
67
+ name: "InvokeModel",
68
+ decisionType: "llm.bedrock.invoke_model",
69
+ functionName: "bedrock-runtime.invoke_model",
70
+ stream: false,
71
+ },
72
+ InvokeModelWithResponseStreamCommand: {
73
+ name: "InvokeModelWithResponseStream",
74
+ decisionType: "llm.bedrock.invoke_model",
75
+ functionName: "bedrock-runtime.invoke_model_with_response_stream",
76
+ stream: true,
77
+ },
78
+ };
79
+ const INFERENCE_PARAMS = ["maxTokens", "temperature", "topP"];
80
+ function usage(value) {
81
+ return tokenUsage(read(value, "inputTokens"), read(value, "outputTokens"), read(value, "totalTokens"), {
82
+ cache_read_input_tokens: read(value, "cacheReadInputTokens"),
83
+ cache_write_input_tokens: read(value, "cacheWriteInputTokens"),
84
+ });
85
+ }
86
+ function headerInt(headers, name) {
87
+ const raw = read(headers, name);
88
+ const n = typeof raw === "string" ? Number(raw) : NaN;
89
+ return Number.isFinite(n) ? n : undefined;
90
+ }
91
+ function converseInfo(output, wantContent) {
92
+ const info = {
93
+ request_id: read(output, "$metadata", "requestId"),
94
+ finish_reason: read(output, "stopReason"),
95
+ usage: usage(read(output, "usage")),
96
+ };
97
+ if (wantContent) {
98
+ const blocks = read(output, "output", "message", "content");
99
+ const texts = (Array.isArray(blocks) ? blocks : []).map((b) => read(b, "text")).filter((t) => typeof t === "string");
100
+ info.content = { content: texts.join("") };
101
+ }
102
+ return info;
103
+ }
104
+ class ConverseStreamState extends StreamState {
105
+ inst;
106
+ acc;
107
+ data;
108
+ constructor(call, inst, requestId) {
109
+ super(call);
110
+ this.inst = inst;
111
+ this.acc = new TextAccumulator(inst.options.maxContentChars);
112
+ this.data = { request_id: requestId };
113
+ }
114
+ observe(event) {
115
+ if (!event || typeof event !== "object")
116
+ return;
117
+ if ("messageStop" in event)
118
+ this.data.finish_reason = read(event, "messageStop", "stopReason");
119
+ else if ("metadata" in event) {
120
+ const u = usage(read(event, "metadata", "usage"));
121
+ if (u)
122
+ this.data.usage = u;
123
+ }
124
+ else if ("contentBlockDelta" in event && this.inst.capturesContent) {
125
+ this.acc.add(read(event, "contentBlockDelta", "delta", "text"));
126
+ }
127
+ }
128
+ info() {
129
+ const info = { ...this.data };
130
+ if (this.inst.capturesContent)
131
+ info.content = { content: this.acc.text };
132
+ return info;
133
+ }
134
+ }
135
+ class InvokeStreamState extends StreamState {
136
+ data;
137
+ constructor(call, requestId) {
138
+ super(call);
139
+ this.data = { request_id: requestId };
140
+ }
141
+ observe(event) {
142
+ const bytes = read(event, "chunk", "bytes");
143
+ if (!(bytes instanceof Uint8Array))
144
+ return;
145
+ const text = Buffer.from(bytes.buffer, bytes.byteOffset, bytes.byteLength).toString("utf8");
146
+ if (!text.includes("invocationMetrics"))
147
+ return;
148
+ const metrics = read(JSON.parse(text), "amazon-bedrock-invocationMetrics");
149
+ const u = tokenUsage(read(metrics, "inputTokenCount"), read(metrics, "outputTokenCount"));
150
+ if (u)
151
+ this.data.usage = u;
152
+ }
153
+ info() {
154
+ return { ...this.data };
155
+ }
156
+ }
157
+ function beginCall(inst, op, input) {
158
+ return inst.begin(op.decisionType, op.functionName, {
159
+ model: read(input, "modelId"),
160
+ params: scalarParams(read(input, "inferenceConfig") ?? {}, INFERENCE_PARAMS),
161
+ inputs: () => {
162
+ if (op.name.startsWith("Converse")) {
163
+ const out = {};
164
+ for (const key of ["system", "messages"])
165
+ if (read(input, key) !== undefined)
166
+ out[key] = read(input, key);
167
+ return out;
168
+ }
169
+ let body = read(input, "body");
170
+ if (body instanceof Uint8Array)
171
+ body = Buffer.from(body).toString("utf8");
172
+ return { body };
173
+ },
174
+ stream: op.stream,
175
+ });
176
+ }
177
+ function endCall(inst, call, op, result) {
178
+ const output = read(result, "output");
179
+ const requestId = read(output, "$metadata", "requestId");
180
+ if (op.name === "Converse")
181
+ return call.finish(converseInfo(output, inst.capturesContent));
182
+ if (op.name === "InvokeModel") {
183
+ const headers = read(result, "response", "headers");
184
+ return call.finish({
185
+ request_id: requestId,
186
+ usage: tokenUsage(headerInt(headers, "x-amzn-bedrock-input-token-count"), headerInt(headers, "x-amzn-bedrock-output-token-count")),
187
+ });
188
+ }
189
+ const key = op.name === "ConverseStream" ? "stream" : "body";
190
+ const events = read(output, key);
191
+ const state = op.name === "ConverseStream" ? new ConverseStreamState(call, inst, requestId) : new InvokeStreamState(call, requestId);
192
+ call.fallback = { request_id: requestId };
193
+ const ok = instrumentAsyncIterable(events, {
194
+ onItem: (event) => state.onItem(event),
195
+ onEnd: (kind, error) => state.onEnd(kind, error),
196
+ });
197
+ if (!ok)
198
+ call.finish({ request_id: requestId }, { stream: { chunk_count: 0, stream_completed: false } });
199
+ else
200
+ finishWhenCollected(events, call);
201
+ }
202
+ function middleware(inst) {
203
+ return (next, context) => async (args) => {
204
+ const op = OPERATIONS[context?.commandName ?? ""];
205
+ if (!op || !inst.active)
206
+ return next(args);
207
+ const call = safe(() => beginCall(inst, op, args?.input), "begin") ?? null;
208
+ if (!call)
209
+ return next(args);
210
+ let result;
211
+ try {
212
+ result = await callStore.run(call, () => next(args));
213
+ }
214
+ catch (error) {
215
+ call.finish({}, { error });
216
+ throw error;
217
+ }
218
+ try {
219
+ endCall(inst, call, op, result);
220
+ }
221
+ catch (error) {
222
+ debug(`bedrock record could not be completed: ${String(error)}`);
223
+ call.finish({});
224
+ }
225
+ return result;
226
+ };
227
+ }
228
+ export function targets(inst, modules) {
229
+ const Client = modules["@aws-sdk/client-bedrock-runtime"]?.["BedrockRuntimeClient"];
230
+ const seen = new WeakSet();
231
+ const mw = middleware(inst);
232
+ return [
233
+ {
234
+ kind: "method",
235
+ owner: read(Client, "prototype"),
236
+ key: "send",
237
+ inherited: true,
238
+ label: "@aws-sdk/client-bedrock-runtime#BedrockRuntimeClient.send",
239
+ wrap: (original) => function (...args) {
240
+ if (inst.active && this && typeof this === "object" && !seen.has(this)) {
241
+ seen.add(this);
242
+ safe(() => {
243
+ const stack = read(this, "middlewareStack");
244
+ if (typeof stack?.add !== "function") {
245
+ debug("BedrockRuntimeClient has no middlewareStack.add; call not recorded");
246
+ return;
247
+ }
248
+ stack.add(mw, { step: "initialize", name: MIDDLEWARE_NAME, priority: "high", override: true });
249
+ delete this["handlers"]; // drop a cached handler chain built without us
250
+ }, "add middleware");
251
+ }
252
+ return original.apply(this, args);
253
+ },
254
+ },
255
+ ];
256
+ }