@tenova/swt3-ai 0.3.2 → 0.3.4

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 (54) hide show
  1. package/README.md +21 -0
  2. package/package.json +1 -1
  3. package/dist/adapters/anthropic.d.ts +0 -32
  4. package/dist/adapters/anthropic.d.ts.map +0 -1
  5. package/dist/adapters/anthropic.js +0 -291
  6. package/dist/adapters/anthropic.js.map +0 -1
  7. package/dist/adapters/bedrock.d.ts +0 -33
  8. package/dist/adapters/bedrock.d.ts.map +0 -1
  9. package/dist/adapters/bedrock.js +0 -259
  10. package/dist/adapters/bedrock.js.map +0 -1
  11. package/dist/adapters/openai.d.ts +0 -19
  12. package/dist/adapters/openai.d.ts.map +0 -1
  13. package/dist/adapters/openai.js +0 -284
  14. package/dist/adapters/openai.js.map +0 -1
  15. package/dist/adapters/vercel-ai.d.ts +0 -64
  16. package/dist/adapters/vercel-ai.d.ts.map +0 -1
  17. package/dist/adapters/vercel-ai.js +0 -68
  18. package/dist/adapters/vercel-ai.js.map +0 -1
  19. package/dist/buffer.d.ts +0 -42
  20. package/dist/buffer.d.ts.map +0 -1
  21. package/dist/buffer.js +0 -161
  22. package/dist/buffer.js.map +0 -1
  23. package/dist/clearing.d.ts +0 -20
  24. package/dist/clearing.d.ts.map +0 -1
  25. package/dist/clearing.js +0 -268
  26. package/dist/clearing.js.map +0 -1
  27. package/dist/demo.d.ts +0 -11
  28. package/dist/demo.d.ts.map +0 -1
  29. package/dist/demo.js +0 -237
  30. package/dist/demo.js.map +0 -1
  31. package/dist/fingerprint.d.ts +0 -29
  32. package/dist/fingerprint.d.ts.map +0 -1
  33. package/dist/fingerprint.js +0 -57
  34. package/dist/fingerprint.js.map +0 -1
  35. package/dist/handoff.d.ts +0 -17
  36. package/dist/handoff.d.ts.map +0 -1
  37. package/dist/handoff.js +0 -82
  38. package/dist/handoff.js.map +0 -1
  39. package/dist/index.d.ts +0 -22
  40. package/dist/index.d.ts.map +0 -1
  41. package/dist/index.js +0 -20
  42. package/dist/index.js.map +0 -1
  43. package/dist/signing.d.ts +0 -20
  44. package/dist/signing.d.ts.map +0 -1
  45. package/dist/signing.js +0 -28
  46. package/dist/signing.js.map +0 -1
  47. package/dist/types.d.ts +0 -96
  48. package/dist/types.d.ts.map +0 -1
  49. package/dist/types.js +0 -17
  50. package/dist/types.js.map +0 -1
  51. package/dist/witness.d.ts +0 -114
  52. package/dist/witness.d.ts.map +0 -1
  53. package/dist/witness.js +0 -291
  54. package/dist/witness.js.map +0 -1
package/README.md CHANGED
@@ -194,6 +194,27 @@ Each inference produces anchors for these checks. Every check maps to a regulati
194
194
  | AI-ACC.1 | Resource access was within scope | "Was the access authorized?" | EU AI Act Art. 14 |
195
195
  | AI-ID.1 | Agent identity was attested | "Is the agent identified?" | EU AI Act Art. 13 |
196
196
 
197
+ ### EU AI Act Article Mapping
198
+
199
+ All 12 SWT3 AI witnessing procedures map to specific EU AI Act obligations:
200
+
201
+ | Procedure | EU AI Act Article | Obligation | Demo | Production |
202
+ |-----------|-------------------|------------|------|------------|
203
+ | AI-INF.1 | Art. 12(1) | Automatic Logging of Use Periods | ✓ | ✓ |
204
+ | AI-INF.2 | Art. 15(3) | Performance Consistency Monitoring | — | ✓ |
205
+ | AI-INF.3 | Art. 12(1) | Volume & Usage Logging | — | ✓ |
206
+ | AI-MDL.1 | Art. 9(4a) | Model Risk Identification | ✓ | ✓ |
207
+ | AI-MDL.2 | Art. 12(2b) | Version & Lineage Tracking | — | ✓ |
208
+ | AI-MDL.3 | Art. 72(1) | Post-Market Drift Monitoring | — | ✓ |
209
+ | AI-MDL.4 | Art. 15(4) | Feedback Loop Isolation | — | ✓ |
210
+ | AI-GRD.1 | Art. 9(2a) | Risk Mitigation Measures | ✓ | ✓ |
211
+ | AI-GRD.2 | Art. 9(4b) | Content Safety Filtering | — | ✓ |
212
+ | AI-GRD.3 | Art. 10(2f) | PII & Data Protection | — | ✓ |
213
+ | AI-EXPL.1 | Art. 13(1) | Transparency & Explainability | — | ✓ |
214
+ | AI-EXPL.2 | Art. 13(3b) | Confidence Calibration | — | ✓ |
215
+
216
+ The demo demonstrates 3 procedures using simulated data. All 12 are available in production with real inference data. [See live conformity →](https://sovereign.tenova.io/audit/axm_audit_demo_eu_ai_act_public)
217
+
197
218
  ## How Verdicts Work
198
219
 
199
220
  Every anchor carries three numbers:
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tenova/swt3-ai",
3
- "version": "0.3.2",
3
+ "version": "0.3.4",
4
4
  "description": "SWT3 AI Witness SDK: cryptographic attestation for AI inference",
5
5
  "main": "dist/index.js",
6
6
  "types": "dist/index.d.ts",
@@ -1,32 +0,0 @@
1
- /**
2
- * SWT3 AI Witness SDK — Anthropic Adapter (ES6 Proxy).
3
- *
4
- * Wraps the Anthropic client so that `client.messages.create()` is
5
- * intercepted for witnessing. Two levels deep (simpler than OpenAI).
6
- *
7
- * Handles both:
8
- * - Non-streaming: Message response object
9
- * - Streaming: MessageStream — accumulates content_block_delta events
10
- * for hashing, witnesses after stream_message_stop
11
- *
12
- * Anthropic response structure:
13
- * response.content → ContentBlock[] (text, tool_use, etc.)
14
- * response.model → string
15
- * response.stop_reason → "end_turn" | "max_tokens" | "stop_sequence" | "tool_use"
16
- * response.usage → { input_tokens, output_tokens }
17
- *
18
- * Anthropic streaming:
19
- * The SDK returns a MessageStream with:
20
- * - Symbol.asyncIterator → yields MessageStreamEvent objects
21
- * - .on("message", cb) → fires when complete message is assembled
22
- * - .finalMessage() → Promise<Message> (the assembled message)
23
- *
24
- * Events: message_start, content_block_start, content_block_delta,
25
- * content_block_stop, message_delta, message_stop
26
- */
27
- import type { Witness } from "../witness.js";
28
- /**
29
- * Wrap an Anthropic client with an ES6 Proxy for transparent witnessing.
30
- */
31
- export declare function wrapAnthropic(client: unknown, witness: Witness): unknown;
32
- //# sourceMappingURL=anthropic.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"anthropic.d.ts","sourceRoot":"","sources":["../../src/adapters/anthropic.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;GAyBG;AAIH,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,eAAe,CAAC;AAE7C;;GAEG;AACH,wBAAgB,aAAa,CAAC,MAAM,EAAE,OAAO,EAAE,OAAO,EAAE,OAAO,GAAG,OAAO,CAYxE"}
@@ -1,291 +0,0 @@
1
- /**
2
- * SWT3 AI Witness SDK — Anthropic Adapter (ES6 Proxy).
3
- *
4
- * Wraps the Anthropic client so that `client.messages.create()` is
5
- * intercepted for witnessing. Two levels deep (simpler than OpenAI).
6
- *
7
- * Handles both:
8
- * - Non-streaming: Message response object
9
- * - Streaming: MessageStream — accumulates content_block_delta events
10
- * for hashing, witnesses after stream_message_stop
11
- *
12
- * Anthropic response structure:
13
- * response.content → ContentBlock[] (text, tool_use, etc.)
14
- * response.model → string
15
- * response.stop_reason → "end_turn" | "max_tokens" | "stop_sequence" | "tool_use"
16
- * response.usage → { input_tokens, output_tokens }
17
- *
18
- * Anthropic streaming:
19
- * The SDK returns a MessageStream with:
20
- * - Symbol.asyncIterator → yields MessageStreamEvent objects
21
- * - .on("message", cb) → fires when complete message is assembled
22
- * - .finalMessage() → Promise<Message> (the assembled message)
23
- *
24
- * Events: message_start, content_block_start, content_block_delta,
25
- * content_block_stop, message_delta, message_stop
26
- */
27
- import { sha256Truncated } from "../fingerprint.js";
28
- /**
29
- * Wrap an Anthropic client with an ES6 Proxy for transparent witnessing.
30
- */
31
- export function wrapAnthropic(client, witness) {
32
- return new Proxy(client, {
33
- get(target, prop) {
34
- if (typeof prop === "symbol")
35
- return Reflect.get(target, prop);
36
- const real = Reflect.get(target, prop);
37
- if (prop === "messages") {
38
- return createMessagesProxy(real, witness);
39
- }
40
- return real;
41
- },
42
- });
43
- }
44
- function createMessagesProxy(messages, witness) {
45
- return new Proxy(messages, {
46
- get(target, prop) {
47
- if (typeof prop === "symbol")
48
- return Reflect.get(target, prop);
49
- const real = Reflect.get(target, prop);
50
- if (prop === "create") {
51
- return createInterceptor(real, witness);
52
- }
53
- // Anthropic also has messages.stream() — intercept that too
54
- if (prop === "stream") {
55
- return createStreamInterceptor(real, witness);
56
- }
57
- return real;
58
- },
59
- });
60
- }
61
- // ── Non-streaming / auto-detect interceptor ─────────────────────────
62
- function createInterceptor(realMethod, witness) {
63
- return function interceptedCreate(...args) {
64
- const kwargs = (args[0] ?? {});
65
- const messages = kwargs.messages;
66
- const system = kwargs.system;
67
- const model = kwargs.model ?? "unknown";
68
- const isStreaming = kwargs.stream === true;
69
- const promptText = extractPromptText(messages, system);
70
- const promptHash = sha256Truncated(promptText);
71
- // Hash system prompt separately (instruction drift detection)
72
- const systemPromptText = extractSystemOnly(system);
73
- const systemPromptHash = systemPromptText ? sha256Truncated(systemPromptText) : undefined;
74
- const start = performance.now();
75
- const result = realMethod.call(this, ...args);
76
- if (isStreaming) {
77
- // Streaming via create({ stream: true }) — returns a Stream
78
- return handleStreaming(result, witness, model, promptHash, start, systemPromptHash);
79
- }
80
- // Non-streaming — result is Promise<Message>
81
- return result.then((response) => {
82
- const elapsedMs = Math.round(performance.now() - start);
83
- const record = extractRecord(response, model, promptHash, elapsedMs, systemPromptHash);
84
- witness.record(record);
85
- return response;
86
- });
87
- };
88
- }
89
- // ── Explicit .stream() interceptor ──────────────────────────────────
90
- function createStreamInterceptor(realMethod, witness) {
91
- return function interceptedStream(...args) {
92
- const kwargs = (args[0] ?? {});
93
- const messages = kwargs.messages;
94
- const system = kwargs.system;
95
- const model = kwargs.model ?? "unknown";
96
- const promptText = extractPromptText(messages, system);
97
- const promptHash = sha256Truncated(promptText);
98
- const systemPromptText = extractSystemOnly(system);
99
- const systemPromptHash = systemPromptText ? sha256Truncated(systemPromptText) : undefined;
100
- const start = performance.now();
101
- const result = realMethod.call(this, ...args);
102
- return handleStreaming(result, witness, model, promptHash, start, systemPromptHash);
103
- };
104
- }
105
- // ── Streaming Handler ───────────────────────────────────────────────
106
- async function* streamAccumulator(stream, witness, model, promptHash, startTime, systemPromptHash) {
107
- const textParts = [];
108
- let actualModel = model;
109
- let stopReason = "";
110
- let inputTokens;
111
- let outputTokens;
112
- for await (const event of stream) {
113
- // Yield to developer immediately
114
- yield event;
115
- const e = event;
116
- const type = e.type;
117
- if (type === "message_start") {
118
- const msg = e.message;
119
- if (msg?.model)
120
- actualModel = msg.model;
121
- const usage = msg?.usage;
122
- if (usage?.input_tokens)
123
- inputTokens = usage.input_tokens;
124
- }
125
- if (type === "content_block_delta") {
126
- const delta = e.delta;
127
- if (delta?.type === "text_delta" && delta?.text) {
128
- textParts.push(delta.text);
129
- }
130
- }
131
- if (type === "message_delta") {
132
- const delta = e.delta;
133
- if (delta?.stop_reason)
134
- stopReason = delta.stop_reason;
135
- const usage = e.usage;
136
- if (usage?.output_tokens)
137
- outputTokens = usage.output_tokens;
138
- }
139
- }
140
- // Stream complete — witness
141
- const elapsedMs = Math.round(performance.now() - startTime);
142
- const responseText = textParts.join("");
143
- const hasRefusal = !["end_turn", "max_tokens", "stop_sequence", "tool_use"].includes(stopReason);
144
- const record = {
145
- modelId: actualModel,
146
- modelHash: sha256Truncated(actualModel),
147
- promptHash,
148
- responseHash: sha256Truncated(responseText),
149
- latencyMs: elapsedMs,
150
- inputTokens,
151
- outputTokens,
152
- guardrailsActive: 0,
153
- guardrailsRequired: 0,
154
- guardrailPassed: true,
155
- hasRefusal,
156
- provider: "anthropic",
157
- systemPromptHash,
158
- guardrailNames: [],
159
- };
160
- witness.record(record);
161
- }
162
- function handleStreaming(streamResult, witness, model, promptHash, startTime, systemPromptHash) {
163
- // Anthropic's stream() returns a MessageStream directly (not a Promise)
164
- // But create({ stream: true }) may return a Promise<Stream>
165
- if (streamResult && typeof streamResult.then === "function") {
166
- return streamResult.then((stream) => wrapAnthropicStream(stream, witness, model, promptHash, startTime, systemPromptHash));
167
- }
168
- return wrapAnthropicStream(streamResult, witness, model, promptHash, startTime, systemPromptHash);
169
- }
170
- function wrapAnthropicStream(stream, witness, model, promptHash, startTime, systemPromptHash) {
171
- const s = stream;
172
- const gen = streamAccumulator(s, witness, model, promptHash, startTime, systemPromptHash);
173
- return new Proxy(s, {
174
- get(target, prop) {
175
- if (prop === Symbol.asyncIterator) {
176
- return () => gen;
177
- }
178
- const value = Reflect.get(target, prop);
179
- if (typeof value === "function") {
180
- // Wrap finalMessage() to also witness the complete response
181
- if (prop === "finalMessage") {
182
- return async function wrappedFinalMessage() {
183
- const msg = await value.call(target);
184
- // The stream accumulator will have already witnessed via iteration,
185
- // but if someone calls finalMessage() WITHOUT iterating, we need
186
- // to witness from the assembled message.
187
- return msg;
188
- };
189
- }
190
- return value.bind(target);
191
- }
192
- return value;
193
- },
194
- });
195
- }
196
- // ── Factor Extraction ──────────────────────────────────────────────
197
- function extractSystemOnly(system) {
198
- if (typeof system === "string" && system)
199
- return system;
200
- if (Array.isArray(system)) {
201
- const parts = [];
202
- for (const block of system) {
203
- if (typeof block === "object" && block !== null) {
204
- const b = block;
205
- if (b.type === "text" && typeof b.text === "string") {
206
- parts.push(b.text);
207
- }
208
- }
209
- }
210
- return parts.length > 0 ? parts.join("\n") : undefined;
211
- }
212
- return undefined;
213
- }
214
- function extractPromptText(messages, system = "") {
215
- const parts = [];
216
- // System prompt
217
- if (typeof system === "string" && system) {
218
- parts.push(system);
219
- }
220
- else if (Array.isArray(system)) {
221
- for (const block of system) {
222
- if (typeof block === "object" && block !== null) {
223
- const b = block;
224
- if (b.type === "text" && typeof b.text === "string") {
225
- parts.push(b.text);
226
- }
227
- }
228
- }
229
- }
230
- // Messages
231
- if (Array.isArray(messages)) {
232
- for (const msg of messages) {
233
- if (typeof msg === "object" && msg !== null) {
234
- const m = msg;
235
- const content = m.content;
236
- if (typeof content === "string") {
237
- parts.push(content);
238
- }
239
- else if (Array.isArray(content)) {
240
- for (const block of content) {
241
- if (typeof block === "object" && block !== null) {
242
- const b = block;
243
- if (b.type === "text" && typeof b.text === "string") {
244
- parts.push(b.text);
245
- }
246
- }
247
- }
248
- }
249
- }
250
- }
251
- }
252
- return parts.join("\n");
253
- }
254
- function extractRecord(response, model, promptHash, elapsedMs, systemPromptHash) {
255
- const r = response;
256
- // Extract text from content blocks
257
- let responseText = "";
258
- const contentBlocks = r.content;
259
- if (Array.isArray(contentBlocks)) {
260
- const texts = [];
261
- for (const block of contentBlocks) {
262
- if (block.type === "text" && typeof block.text === "string") {
263
- texts.push(block.text);
264
- }
265
- }
266
- responseText = texts.join("\n");
267
- }
268
- const stopReason = r.stop_reason ?? "";
269
- const hasRefusal = !["end_turn", "max_tokens", "stop_sequence", "tool_use"].includes(stopReason);
270
- const usage = r.usage;
271
- const inputTokens = usage?.input_tokens;
272
- const outputTokens = usage?.output_tokens;
273
- const actualModel = r.model ?? model;
274
- return {
275
- modelId: actualModel,
276
- modelHash: sha256Truncated(actualModel),
277
- promptHash,
278
- responseHash: sha256Truncated(responseText),
279
- latencyMs: elapsedMs,
280
- inputTokens,
281
- outputTokens,
282
- guardrailsActive: 0,
283
- guardrailsRequired: 0,
284
- guardrailPassed: true,
285
- hasRefusal,
286
- provider: "anthropic",
287
- systemPromptHash,
288
- guardrailNames: [],
289
- };
290
- }
291
- //# sourceMappingURL=anthropic.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"anthropic.js","sourceRoot":"","sources":["../../src/adapters/anthropic.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;GAyBG;AAEH,OAAO,EAAE,eAAe,EAAE,MAAM,mBAAmB,CAAC;AAIpD;;GAEG;AACH,MAAM,UAAU,aAAa,CAAC,MAAe,EAAE,OAAgB;IAC7D,OAAO,IAAI,KAAK,CAAC,MAAgB,EAAE;QACjC,GAAG,CAAC,MAAc,EAAE,IAAqB;YACvC,IAAI,OAAO,IAAI,KAAK,QAAQ;gBAAE,OAAO,OAAO,CAAC,GAAG,CAAC,MAAM,EAAE,IAAI,CAAC,CAAC;YAC/D,MAAM,IAAI,G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CAAC,CAAC,QAAQ,CAAC,UAAU,CAAC,CAAC;IAEjG,MAAM,KAAK,GAAG,CAAC,CAAC,KAA4C,CAAC;IAC7D,MAAM,WAAW,GAAG,KAAK,EAAE,YAAkC,CAAC;IAC9D,MAAM,YAAY,GAAG,KAAK,EAAE,aAAmC,CAAC;IAEhE,MAAM,WAAW,GAAI,CAAC,CAAC,KAAgB,IAAI,KAAK,CAAC;IAEjD,OAAO;QACL,OAAO,EAAE,WAAW;QACpB,SAAS,EAAE,eAAe,CAAC,WAAW,CAAC;QACvC,UAAU;QACV,YAAY,EAAE,eAAe,CAAC,YAAY,CAAC;QAC3C,SAAS,EAAE,SAAS;QACpB,WAAW;QACX,YAAY;QACZ,gBAAgB,EAAE,CAAC;QACnB,kBAAkB,EAAE,CAAC;QACrB,eAAe,EAAE,IAAI;QACrB,UAAU;QACV,QAAQ,EAAE,WAAW;QACrB,gBAAgB;QAChB,cAAc,EAAE,EAAE;KACnB,CAAC;AACJ,CAAC"}
@@ -1,33 +0,0 @@
1
- /**
2
- * SWT3 AI Witness SDK — AWS Bedrock Adapter (ES6 Proxy).
3
- *
4
- * Wraps the @aws-sdk/client-bedrock-runtime client so that
5
- * `client.send(new ConverseCommand(...))` and
6
- * `client.send(new InvokeModelCommand(...))` are intercepted.
7
- *
8
- * AWS Bedrock uses the Command pattern:
9
- * const response = await client.send(new ConverseCommand({ modelId, messages }));
10
- *
11
- * The adapter intercepts `send()` and checks if the command is a
12
- * ConverseCommand or InvokeModelCommand to extract factors.
13
- *
14
- * Copyright (c) 2026 Tenable Nova LLC. Apache 2.0. Patent pending.
15
- */
16
- import type { Witness } from "../witness.js";
17
- /**
18
- * Wrap a BedrockRuntimeClient with transparent witnessing.
19
- *
20
- * Usage:
21
- * import { BedrockRuntimeClient, ConverseCommand } from "@aws-sdk/client-bedrock-runtime";
22
- * import { Witness } from "@tenova/swt3-ai";
23
- *
24
- * const witness = new Witness({ endpoint, apiKey, tenantId });
25
- * const client = witness.wrap(new BedrockRuntimeClient({ region: "us-east-1" }));
26
- *
27
- * const response = await client.send(new ConverseCommand({
28
- * modelId: "anthropic.claude-3-5-sonnet-20241022-v2:0",
29
- * messages: [{ role: "user", content: [{ text: "Hello" }] }],
30
- * }));
31
- */
32
- export declare function wrapBedrock(client: unknown, witness: Witness): unknown;
33
- //# sourceMappingURL=bedrock.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"bedrock.d.ts","sourceRoot":"","sources":["../../src/adapters/bedrock.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG;AAIH,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,eAAe,CAAC;AAE7C;;;;;;;;;;;;;;GAcG;AACH,wBAAgB,WAAW,CAAC,MAAM,EAAE,OAAO,EAAE,OAAO,EAAE,OAAO,GAAG,OAAO,CAatE"}
@@ -1,259 +0,0 @@
1
- /**
2
- * SWT3 AI Witness SDK — AWS Bedrock Adapter (ES6 Proxy).
3
- *
4
- * Wraps the @aws-sdk/client-bedrock-runtime client so that
5
- * `client.send(new ConverseCommand(...))` and
6
- * `client.send(new InvokeModelCommand(...))` are intercepted.
7
- *
8
- * AWS Bedrock uses the Command pattern:
9
- * const response = await client.send(new ConverseCommand({ modelId, messages }));
10
- *
11
- * The adapter intercepts `send()` and checks if the command is a
12
- * ConverseCommand or InvokeModelCommand to extract factors.
13
- *
14
- * Copyright (c) 2026 Tenable Nova LLC. Apache 2.0. Patent pending.
15
- */
16
- import { sha256Truncated } from "../fingerprint.js";
17
- /**
18
- * Wrap a BedrockRuntimeClient with transparent witnessing.
19
- *
20
- * Usage:
21
- * import { BedrockRuntimeClient, ConverseCommand } from "@aws-sdk/client-bedrock-runtime";
22
- * import { Witness } from "@tenova/swt3-ai";
23
- *
24
- * const witness = new Witness({ endpoint, apiKey, tenantId });
25
- * const client = witness.wrap(new BedrockRuntimeClient({ region: "us-east-1" }));
26
- *
27
- * const response = await client.send(new ConverseCommand({
28
- * modelId: "anthropic.claude-3-5-sonnet-20241022-v2:0",
29
- * messages: [{ role: "user", content: [{ text: "Hello" }] }],
30
- * }));
31
- */
32
- export function wrapBedrock(client, witness) {
33
- return new Proxy(client, {
34
- get(target, prop) {
35
- if (typeof prop === "symbol")
36
- return Reflect.get(target, prop);
37
- const real = Reflect.get(target, prop);
38
- if (prop === "send" && typeof real === "function") {
39
- return createSendInterceptor(real, witness, target);
40
- }
41
- return real;
42
- },
43
- });
44
- }
45
- function createSendInterceptor(realSend, witness, thisArg) {
46
- return async function interceptedSend(...args) {
47
- const command = args[0];
48
- if (!command)
49
- return realSend.call(thisArg, ...args);
50
- // Detect command type by constructor name
51
- const commandName = command.constructor?.name ?? "";
52
- if (commandName === "ConverseCommand") {
53
- return handleConverse(realSend, thisArg, command, witness, args);
54
- }
55
- if (commandName === "InvokeModelCommand") {
56
- return handleInvokeModel(realSend, thisArg, command, witness, args);
57
- }
58
- // Not a command we intercept — pass through
59
- return realSend.call(thisArg, ...args);
60
- };
61
- }
62
- // ── Converse Command Handler ──────────────────────────────────────
63
- async function handleConverse(realSend, thisArg, command, witness, args) {
64
- const input = command.input ?? command;
65
- const modelId = input.modelId ?? "unknown";
66
- const messages = input.messages ?? [];
67
- const promptText = extractConversePrompt(messages);
68
- const promptHash = sha256Truncated(promptText);
69
- const start = performance.now();
70
- const response = await realSend.call(thisArg, ...args);
71
- const elapsedMs = Math.round(performance.now() - start);
72
- const resp = response;
73
- const record = extractConverseRecord(resp, modelId, promptHash, elapsedMs);
74
- witness.record(record);
75
- return response;
76
- }
77
- // ── InvokeModel Command Handler ──────────────────────────────────
78
- async function handleInvokeModel(realSend, thisArg, command, witness, args) {
79
- const input = command.input ?? command;
80
- const modelId = input.modelId ?? "unknown";
81
- // Parse the body to get prompt
82
- let body = {};
83
- const rawBody = input.body;
84
- if (typeof rawBody === "string") {
85
- try {
86
- body = JSON.parse(rawBody);
87
- }
88
- catch { /* empty */ }
89
- }
90
- else if (rawBody instanceof Uint8Array) {
91
- try {
92
- body = JSON.parse(new TextDecoder().decode(rawBody));
93
- }
94
- catch { /* empty */ }
95
- }
96
- const promptText = extractInvokePrompt(body, modelId);
97
- const promptHash = sha256Truncated(promptText);
98
- const start = performance.now();
99
- const response = await realSend.call(thisArg, ...args);
100
- const elapsedMs = Math.round(performance.now() - start);
101
- const resp = response;
102
- const record = extractInvokeRecord(resp, modelId, promptHash, elapsedMs);
103
- witness.record(record);
104
- return response;
105
- }
106
- // ── Prompt Extraction ─────────────────────────────────────────────
107
- function extractConversePrompt(messages) {
108
- const parts = [];
109
- for (const msg of messages) {
110
- const m = msg;
111
- const content = m.content;
112
- if (Array.isArray(content)) {
113
- for (const block of content) {
114
- const b = block;
115
- if (b.text)
116
- parts.push(b.text);
117
- }
118
- }
119
- else if (typeof content === "string") {
120
- parts.push(content);
121
- }
122
- }
123
- return parts.join("\n");
124
- }
125
- function extractInvokePrompt(body, modelId) {
126
- // Anthropic on Bedrock
127
- const messages = body.messages;
128
- if (messages?.length) {
129
- const parts = [];
130
- for (const msg of messages) {
131
- const m = msg;
132
- const content = m.content;
133
- if (typeof content === "string") {
134
- parts.push(content);
135
- }
136
- else if (Array.isArray(content)) {
137
- for (const block of content) {
138
- const b = block;
139
- if (b.type === "text" && b.text)
140
- parts.push(b.text);
141
- }
142
- }
143
- }
144
- if (parts.length)
145
- return parts.join("\n");
146
- }
147
- // Amazon Titan
148
- if (body.inputText)
149
- return body.inputText;
150
- // Meta Llama
151
- if (body.prompt)
152
- return body.prompt;
153
- return JSON.stringify(body);
154
- }
155
- // ── Record Extraction ─────────────────────────────────────────────
156
- function extractConverseRecord(response, modelId, promptHash, elapsedMs) {
157
- let responseText = "";
158
- let hasRefusal = false;
159
- const output = response.output;
160
- const message = output?.message;
161
- const content = message?.content;
162
- if (content) {
163
- for (const block of content) {
164
- if (block.text)
165
- responseText += block.text;
166
- }
167
- }
168
- const stopReason = response.stopReason;
169
- if (stopReason === "content_filtered")
170
- hasRefusal = true;
171
- const usage = response.usage;
172
- const inputTokens = usage?.inputTokens;
173
- const outputTokens = usage?.outputTokens;
174
- return {
175
- modelId: modelId,
176
- modelHash: sha256Truncated(modelId),
177
- promptHash: promptHash,
178
- responseHash: sha256Truncated(responseText || ""),
179
- latencyMs: elapsedMs,
180
- inputTokens: inputTokens ?? undefined,
181
- outputTokens: outputTokens ?? undefined,
182
- hasRefusal: hasRefusal,
183
- provider: "bedrock",
184
- systemFingerprint: undefined,
185
- guardrailsActive: 0,
186
- guardrailsRequired: 0,
187
- guardrailPassed: true,
188
- guardrailNames: [],
189
- };
190
- }
191
- function extractInvokeRecord(response, modelId, promptHash, elapsedMs) {
192
- let responseText = "";
193
- let hasRefusal = false;
194
- let inputTokens = null;
195
- let outputTokens = null;
196
- try {
197
- let body = {};
198
- const rawBody = response.body;
199
- if (rawBody instanceof Uint8Array) {
200
- body = JSON.parse(new TextDecoder().decode(rawBody));
201
- }
202
- else if (typeof rawBody === "string") {
203
- body = JSON.parse(rawBody);
204
- }
205
- // Anthropic on Bedrock
206
- if (body.content) {
207
- const content = body.content;
208
- if (Array.isArray(content)) {
209
- for (const block of content) {
210
- if (block.type === "text" && block.text)
211
- responseText += block.text;
212
- }
213
- }
214
- else if (typeof content === "string") {
215
- responseText = content;
216
- }
217
- }
218
- // Amazon Titan
219
- else if (body.results) {
220
- const results = body.results;
221
- if (results[0]?.outputText)
222
- responseText = results[0].outputText;
223
- }
224
- // Meta Llama
225
- else if (body.generation) {
226
- responseText = body.generation;
227
- }
228
- // Usage
229
- const usage = body.usage;
230
- if (usage) {
231
- inputTokens = (usage.input_tokens ?? usage.inputTokens ?? null);
232
- outputTokens = (usage.output_tokens ?? usage.outputTokens ?? null);
233
- }
234
- // Refusal
235
- const stopReason = (body.stop_reason ?? body.stopReason ?? "");
236
- if (stopReason.toLowerCase().includes("content_filter"))
237
- hasRefusal = true;
238
- }
239
- catch {
240
- // Parse failure — still witness with what we have
241
- }
242
- return {
243
- modelId: modelId,
244
- modelHash: sha256Truncated(modelId),
245
- promptHash: promptHash,
246
- responseHash: sha256Truncated(responseText || ""),
247
- latencyMs: elapsedMs,
248
- inputTokens: inputTokens ?? undefined,
249
- outputTokens: outputTokens ?? undefined,
250
- hasRefusal: hasRefusal,
251
- provider: "bedrock",
252
- systemFingerprint: undefined,
253
- guardrailsActive: 0,
254
- guardrailsRequired: 0,
255
- guardrailPassed: true,
256
- guardrailNames: [],
257
- };
258
- }
259
- //# sourceMappingURL=bedrock.js.map