@avowa/runtime 0.0.0-stage → 0.11.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,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright 2026 Avowa, Inc.
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
package/NOTICE ADDED
@@ -0,0 +1,4 @@
1
+ Avowa Runtime SDK
2
+ Copyright 2026 Avowa, Inc.
3
+
4
+ This product includes software developed at Avowa, Inc. (https://avowa.ai).
package/README.md CHANGED
@@ -1,3 +1,56 @@
1
- # Temporary Holding Version
1
+ # @avowa/runtime
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ The JavaScript/TypeScript half of the [Avowa Runtime SDK](https://github.com/Avowa-AI/avowa-runtime-sdk) — emits live AI-inference
4
+ signals to Avowa as **observed** evidence. Node 18+, server-side only — the signing secret must never ship to a browser, and the ingest API does not accept browser origins.
5
+
6
+ ```bash
7
+ npm install @avowa/runtime
8
+ ```
9
+
10
+ One dependency-free file, Apache-2.0. (It is also in your Avowa SDK download, if you would rather vendor it.)
11
+
12
+ ```js
13
+ import createAvowa from '@avowa/runtime'
14
+
15
+ const avowa = createAvowa({
16
+ ingestKey: process.env.AVOWA_RUNTIME_KEY,
17
+ ingestSecret: process.env.AVOWA_RUNTIME_SECRET, // signs each signal (tamper-evident)
18
+ baseUrl: process.env.AVOWA_BASE_URL,
19
+ region: 'us-east-1',
20
+ })
21
+
22
+ // record a call you already made
23
+ avowa.capture({ model: 'claude-opus-4-8', train_on_data: false })
24
+
25
+ // or wrap one — times it, and records whether it was blocked
26
+ const resp = await avowa.track({ model: 'claude-opus-4-8' }, () => client.messages.create(...))
27
+ ```
28
+
29
+ **Metadata only.** Model id, host, region, latency, counts and the flags you pass. Never prompts,
30
+ completions, tool arguments or customer data.
31
+
32
+ **Never in your way.** Capture is fire-and-forget and never rejects: if Avowa is unreachable your
33
+ call still returns, uploads time out after 5 s, and at most 64 are in flight (past that they are
34
+ dropped, with one warning). The wrappers hand back the provider's own promise and stream objects
35
+ (`.withResponse()`, `.tee()` and `instanceof` all behave as without Avowa). HTTPS only, every
36
+ request signed and single-use, and `AVOWA_DISABLE=1` turns it off entirely.
37
+ `track()` re-throws whatever your function threw, after recording that it was blocked.
38
+
39
+ Licence: Apache-2.0.
40
+
41
+ ## Wrap your client (observed, not asserted)
42
+
43
+ ```js
44
+ import OpenAI from 'openai'
45
+ import { createAvowa } from '@avowa/runtime'
46
+
47
+ const avowa = createAvowa() // AVOWA_RUNTIME_KEY / _SECRET / AVOWA_BASE_URL from the env
48
+ const openai = avowa.instrumentOpenAI(new OpenAI()) // chat.completions.create, responses.create — streams included
49
+ // const anthropic = avowa.instrumentAnthropic(new Anthropic()) // messages.create — streams included
50
+ ```
51
+
52
+ The wrapper reads the requested and served model, the provider's finish/stop code, the tools
53
+ offered and the tools the model invoked, and scans the prompt and output text locally; only counts
54
+ leave. It sends those facts as they are — Avowa evaluates them on its side — and each signal names
55
+ the fields the wrapper read, so they grade as observed rather than as your app's word. `capture()` and `track()` remain for anything else,
56
+ graded as self-reported.
@@ -0,0 +1,767 @@
1
+ // SPDX-License-Identifier: Apache-2.0
2
+ // Copyright 2026 Avowa, Inc.
3
+ const env = typeof process !== 'undefined' && process.env || {};
4
+ const VERSION = '0.11.0';
5
+ let _subtle = null;
6
+ async function subtle() {
7
+ if (_subtle) return _subtle;
8
+ if (globalThis.crypto && globalThis.crypto.subtle) return _subtle = globalThis.crypto.subtle;
9
+ const m = await import('node:crypto');
10
+ return _subtle = m.webcrypto.subtle;
11
+ }
12
+ async function hmacHex(secret, msg) {
13
+ const enc = new TextEncoder();
14
+ const st = await subtle();
15
+ const k = await st.importKey('raw', enc.encode(secret), {
16
+ name: 'HMAC',
17
+ hash: 'SHA-256'
18
+ }, false, ['sign']);
19
+ const sig = await st.sign('HMAC', k, enc.encode(msg));
20
+ return [...new Uint8Array(sig)].map(b => b.toString(16).padStart(2, '0')).join('');
21
+ }
22
+ const RF_DENY = new Set(['content', 'contents', 'text', 'texts', 'message', 'messages', 'input', 'inputs', 'output', 'outputs', 'output_text', 'prompt', 'prompts', 'system', 'instructions', 'arguments', 'args', 'delta', 'parts', 'part', 'body', 'data', 'completion', 'completions', 'document', 'documents', 'query', 'queries', 'value', 'values', 'raw', 'html', 'markdown', 'transcript', 'summary', 'reasoning_content', 'thinking']);
23
+ const RF_NAME = /^[a-z][a-z0-9_]{1,40}$/;
24
+ const RF_SEG = /^(?:[A-Za-z_][A-Za-z0-9_]{0,40}|\d{1,2})$/;
25
+ const RF_PROVIDERS = ['*', 'openai', 'anthropic', 'bedrock', 'gemini'];
26
+ const REMOTE = {
27
+ v: null,
28
+ fields: []
29
+ };
30
+ const remoteOn = () => !['off', '0', 'false', 'no'].includes(String(env.AVOWA_REMOTE_FIELDS || 'on').trim().toLowerCase());
31
+ export function rfOk(f) {
32
+ if (!f || typeof f !== 'object') return false;
33
+ const {
34
+ name,
35
+ provider,
36
+ path
37
+ } = f;
38
+ if (!(typeof name === 'string' && RF_NAME.test(name) && RF_PROVIDERS.includes(provider) && ['request', 'response', 'error'].includes(f.from) && typeof path === 'string')) return false;
39
+ const segs = path.split('.');
40
+ return segs.length >= 1 && segs.length <= 6 && segs.every(x => RF_SEG.test(x) && !x.startsWith('_') && !RF_DENY.has(x.toLowerCase()));
41
+ }
42
+ function rfValue(v) {
43
+ if (typeof v === 'boolean') return v;
44
+ if (typeof v === 'number') return Number.isFinite(v) ? v : null;
45
+ return typeof v === 'string' && v && /^[A-Za-z0-9_.:-]{1,40}$/.test(v.slice(0, 40)) ? v.slice(0, 40) : null;
46
+ }
47
+ function rfGet(obj, path) {
48
+ for (const k of path.split('.')) {
49
+ if (obj == null) return null;
50
+ try {
51
+ obj = Array.isArray(obj) && /^\d+$/.test(k) ? obj[Number(k)] : obj[k];
52
+ } catch {
53
+ return null;
54
+ }
55
+ }
56
+ return obj;
57
+ }
58
+ async function acceptFields(block, secret) {
59
+ try {
60
+ if (!block || typeof block.doc !== 'string' || typeof block.mac !== 'string' || !secret) return;
61
+ if ((await hmacHex(secret, 'avowa-fields.' + block.doc)) !== block.mac) {
62
+ warnOnce('rf-mac', 'ignored a metadata-field list that did not verify under this connection\'s secret.');
63
+ return;
64
+ }
65
+ const d = JSON.parse(block.doc);
66
+ REMOTE.v = String(d.v || '').slice(0, 32) || null;
67
+ REMOTE.fields = (Array.isArray(d.fields) ? d.fields : []).slice(0, 20).filter(rfOk);
68
+ } catch (e) {
69
+ internalError('remote_fields', e);
70
+ }
71
+ }
72
+ export const _resetRemoteFields = () => {
73
+ REMOTE.v = null;
74
+ REMOTE.fields = [];
75
+ };
76
+ export const remoteFields = () => remoteOn() ? REMOTE.fields.map(f => ({
77
+ ...f
78
+ })) : [];
79
+ function remoteFacts(kind, resp, params, errObj) {
80
+ const out = {};
81
+ if (!REMOTE.fields.length || !remoteOn()) return out;
82
+ const src = {
83
+ request: params,
84
+ response: resp,
85
+ error: errObj
86
+ };
87
+ for (const f of REMOTE.fields) {
88
+ if ((f.provider === '*' || f.provider === kind) && src[f.from] != null) {
89
+ const v = rfValue(rfGet(src[f.from], f.path));
90
+ if (v != null) out['rf_' + f.name] = v;
91
+ }
92
+ }
93
+ return out;
94
+ }
95
+ const _warned = new Set();
96
+ function warnOnce(kind, msg) {
97
+ if (_warned.has(kind)) return;
98
+ _warned.add(kind);
99
+ try {
100
+ console.error(`[avowa] ${msg}`);
101
+ } catch {}
102
+ }
103
+ export const INTERNAL_ERRORS = {};
104
+ function internalError(where, e) {
105
+ const key = `${where}:${e && e.name || 'Error'}`;
106
+ INTERNAL_ERRORS[key] = (INTERNAL_ERRORS[key] || 0) + 1;
107
+ if (['1', 'true', 'yes', 'on'].includes(String(typeof process !== 'undefined' && process.env && process.env.AVOWA_STRICT || '').trim().toLowerCase())) throw e;
108
+ warnOnce('internal:' + key, `internal error in ${where} (${key.split(':')[1]}) — this signal was skipped; your app is unaffected`);
109
+ }
110
+ const CARD_RX = /\b(?:\d[ -]*?){13,16}\b/;
111
+ function luhnOk(digits) {
112
+ let total = 0,
113
+ alt = false;
114
+ for (let i = digits.length - 1; i >= 0; i--) {
115
+ let d = digits.charCodeAt(i) - 48;
116
+ if (alt) {
117
+ d *= 2;
118
+ if (d > 9) d -= 9;
119
+ }
120
+ total += d;
121
+ alt = !alt;
122
+ }
123
+ return total % 10 === 0;
124
+ }
125
+ function looksLikeCard(text) {
126
+ const rx = new RegExp(CARD_RX.source, 'g');
127
+ let m;
128
+ while ((m = rx.exec(text)) !== null) {
129
+ const digits = m[0].replace(/[^0-9]/g, '');
130
+ if (digits.length >= 13 && digits.length <= 16 && luhnOk(digits)) return true;
131
+ }
132
+ return false;
133
+ }
134
+ const PII_PATTERNS = [/(?<![\w.+-])[\w.+-]{1,64}@[\w-]{1,63}\.[\w.]{2,63}/, /\b\d{3}-\d{2}-\d{4}\b/, CARD_RX, /\bAKIA[0-9A-Z]{16}\b/, /-----BEGIN (?:RSA |EC |OPENSSH )?PRIVATE KEY-----/, /\beyJ[A-Za-z0-9_-]{10,4096}\.[A-Za-z0-9_-]{10,4096}\./, /\b(?:sk|rk)-[A-Za-z0-9]{20,200}\b/];
135
+ export const SCAN_LIMIT = 32 * 1024;
136
+ const cap = (t, keep) => typeof t === 'string' && t.length > SCAN_LIMIT ? keep === 'tail' ? t.slice(-SCAN_LIMIT) : t.slice(0, SCAN_LIMIT) : t;
137
+ const TRUE = new Set(['1', 'true', 'yes', 'on']);
138
+ const isOn = v => TRUE.has(String(v || '').trim().toLowerCase());
139
+ function privateHost(h) {
140
+ h = String(h || '').replace(/^\[|\]$/g, '').toLowerCase();
141
+ if (!h) return false;
142
+ if (h === 'localhost' || h.endsWith('.localhost') || !h.includes('.') && !h.includes(':')) return true;
143
+ if (/^127\./.test(h) || h === '::1' || /^10\./.test(h) || /^192\.168\./.test(h) || /^169\.254\./.test(h)) return true;
144
+ const m = h.match(/^172\.(\d+)\./);
145
+ return !!(m && +m[1] >= 16 && +m[1] <= 31);
146
+ }
147
+ export function checkedBase(url) {
148
+ if (!url) return [null, 'AVOWA_BASE_URL is not set'];
149
+ let u;
150
+ try {
151
+ u = new URL(String(url).includes('://') ? String(url) : `https://${url}`);
152
+ } catch {
153
+ return [null, 'AVOWA_BASE_URL is not a valid URL'];
154
+ }
155
+ const base = String(url).replace(/\/+$/, '');
156
+ if (u.protocol === 'https:') return [base, null];
157
+ if (u.protocol === 'http:' && (privateHost(u.hostname) || isOn(env.AVOWA_ALLOW_HTTP))) return [base, null];
158
+ return [null, `AVOWA_BASE_URL uses ${u.protocol}// to ${u.hostname} — signals carry your ingest key, so only https:// is accepted (plain http only to localhost or a private network)`];
159
+ }
160
+ const INJECTION_PATTERNS = [/ignore\s+(?:all\s+)?(?:previous|prior|above)\s+instructions?/i, /disregard\s+(?:all\s+)?(?:previous|prior|your)\s+(?:instructions?|rules?)/i, /(?:reveal|print|repeat|show)\s+(?:me\s+)?(?:your\s+)?system\s+prompt/i, /you\s+are\s+now\s+(?:a|an|in)\b/i, /\bdeveloper\s+mode\b|\bDAN\s+mode\b/i, /<\/?(?:system|instructions?)>/i, /pretend\s+(?:that\s+)?you\s+(?:are|have)\b/i];
161
+ const countMatches = (text, pats) => typeof text === 'string' && text ? pats.reduce((n, rx) => n + ((rx === CARD_RX ? looksLikeCard(text) : rx.test(text)) ? 1 : 0), 0) : 0;
162
+ const PII_GATES = [(t, d) => t.includes('@'), (t, d) => d && t.includes('-'), (t, d) => d, t => t.includes('AKIA'), t => t.includes('-----BEGIN'), t => t.includes('eyJ'), t => t.includes('sk-') || t.includes('rk-')];
163
+ const PII_NAMES = ['email', 'us_ssn', 'payment_card', 'aws_access_key', 'private_key', 'jwt', 'provider_secret_key'];
164
+ const INJECTION_NAMES = ['ignore_instructions', 'disregard_rules', 'reveal_system_prompt', 'role_override', 'developer_mode', 'delimiter_injection', 'pretend'];
165
+ export function piiFamilies(text) {
166
+ if (typeof text !== 'string' || !text) return [];
167
+ const d = /\d/.test(text);
168
+ return PII_PATTERNS.flatMap((rx, i) => PII_GATES[i](text, d) && (rx === CARD_RX ? looksLikeCard(text) : rx.test(text)) ? [PII_NAMES[i]] : []);
169
+ }
170
+ export function injectionFamilies(text) {
171
+ if (typeof text !== 'string' || !text) return [];
172
+ return INJECTION_PATTERNS.flatMap((rx, i) => rx.test(text) ? [INJECTION_NAMES[i]] : []);
173
+ }
174
+ export const scanPii = text => piiFamilies(text).length;
175
+ export const scanInjection = text => injectionFamilies(text).length;
176
+ export const _ungated = {
177
+ pii: t => countMatches(t, PII_PATTERNS),
178
+ injection: t => countMatches(t, INJECTION_PATTERNS)
179
+ };
180
+ export function hostOf(url) {
181
+ if (!url) return null;
182
+ try {
183
+ return new URL(String(url).includes('://') ? url : `https://${url}`).hostname || null;
184
+ } catch {
185
+ return null;
186
+ }
187
+ }
188
+ export function createAvowa({
189
+ ingestKey,
190
+ ingestSecret,
191
+ baseUrl,
192
+ region
193
+ } = {}) {
194
+ if (isOn(env.AVOWA_DISABLE)) {
195
+ const noop = async () => undefined;
196
+ return {
197
+ capture: noop,
198
+ track: (meta, fn) => fn(),
199
+ instrumentOpenAI: c => c,
200
+ instrumentAnthropic: c => c,
201
+ disabled: true
202
+ };
203
+ }
204
+ const key = ingestKey || env.AVOWA_RUNTIME_KEY;
205
+ const secret = ingestSecret || env.AVOWA_RUNTIME_SECRET;
206
+ const [base, baseProblem] = checkedBase(baseUrl || env.AVOWA_BASE_URL);
207
+ if (!key) warnOnce('nokey', 'no credentials — set AVOWA_RUNTIME_KEY / AVOWA_RUNTIME_SECRET (from your avowa.env) or pass ingestKey. No signals will be sent.');else if (baseProblem) warnOnce('nobase', `${baseProblem} — no signals will be sent. Your app is unaffected.`);
208
+ const MAX_INFLIGHT = 64;
209
+ const TIMEOUT_MS = 5000;
210
+ let inflight = 0;
211
+ async function capture(evt = {}) {
212
+ try {
213
+ return await _capture(evt);
214
+ } catch (e) {
215
+ internalError('capture', e);
216
+ return null;
217
+ }
218
+ }
219
+ async function _capture(evt = {}) {
220
+ if (!key || !base) return;
221
+ const payload = {
222
+ model: evt.model || null,
223
+ region: evt.region || region || null,
224
+ latency_ms: evt.latency_ms ?? null
225
+ };
226
+ if (evt.train_on_data !== undefined && evt.train_on_data !== null) payload.train_on_data = !!evt.train_on_data;
227
+ if (evt.guardrail_blocked !== undefined && evt.guardrail_blocked !== null) {
228
+ payload.guardrail_blocked = !!evt.guardrail_blocked;
229
+ }
230
+ for (const k of ['guardrail', 'decision_logged', 'human_reviewed', 'rationale_present', 'ai_disclosed', 'uncertainty_flagged', 'fairness_checked', 'blocked_category', 'pii_redacted', 'grounded', 'refused', 'injection_blocked', 'output_validated', 'system_prompt_protected', 'rate_limited', 'tool_authorized', 'action_authorized', 'model_pinned', 'eval_score', 'agent_run', 'tool_called', 'autonomy_depth', 'action_class', 'approval_required', 'approved_by_human', 'action_blocked', 'action_logged', 'agent_run_key', 'tools_offered', 'tools_invoked', 'injection_suspected', 'pii_detected', 'error', 'fallback_model', 'retries', 'token_ceiling', 'provider_throttled', 'requested_model', 'stop_reason', 'structured_output', 'refusal_part', 'input_tokens', 'output_tokens', 'cache_read_tokens', 'cache_write_tokens', 'system_prompt_present', 'tool_choice', 'messages_user', 'messages_assistant', 'messages_tool', 'input_images', 'input_files', 'input_audio', 'streaming', 'response_format_type', 'prompt_chars', 'output_chars', 'client_max_retries', 'client_timeout_s', 'pii_families', 'injection_families', 'temperature', 'top_p', 'seed', 'choices_n', 'stop_sequences', 'parallel_tool_calls', 'store_requested', 'logprobs', 'service_tier_requested', 'metadata_present', 'end_user_id_present', 'reasoning_effort', 'thinking_enabled', 'system_fingerprint', 'service_tier', 'provider_filtered', 'provider_filter_categories', 'ttft_ms', 'http_status', 'provider_error_code', 'retry_after_s', 'provider_lib', 'node_version', 'app_region', 'app_region_source']) {
231
+ if (evt[k] !== undefined && evt[k] !== null) payload[k] = evt[k];
232
+ }
233
+ if (evt.endpoint) payload.endpoint = hostOf(evt.endpoint);
234
+ const scanP = evt.scanPrompt !== undefined && evt.scanPrompt !== null ? cap(evt.scanPrompt, 'tail') : null;
235
+ const scanO = evt.scanOutput !== undefined && evt.scanOutput !== null ? cap(evt.scanOutput, 'head') : null;
236
+ if (scanP !== null || scanO !== null) {
237
+ await new Promise(r => typeof setImmediate === 'function' ? setImmediate(r) : setTimeout(r, 0));
238
+ if (scanP !== null) {
239
+ const fam = injectionFamilies(scanP);
240
+ payload.injection_suspected = fam.length;
241
+ payload.injection_families = fam;
242
+ }
243
+ if (scanO !== null) {
244
+ const fam = piiFamilies(scanO);
245
+ payload.pii_detected = fam.length;
246
+ payload.pii_families = fam;
247
+ }
248
+ }
249
+ for (const k of Object.keys(evt)) if (/^rf_[a-z][a-z0-9_]{1,40}$/.test(k) && evt[k] != null) payload[k] = evt[k];
250
+ if (Array.isArray(evt._sdk_observed) && evt._sdk_observed.length) payload._sdk_observed = [...new Set(evt._sdk_observed)];
251
+ const kinds = Object.keys(INTERNAL_ERRORS);
252
+ if (kinds.length) {
253
+ payload.sdk_errors = kinds.reduce((n, k) => n + INTERNAL_ERRORS[k], 0);
254
+ payload.sdk_error_kinds = kinds.sort().slice(0, 10);
255
+ }
256
+ const body = JSON.stringify(payload);
257
+ const headers = {
258
+ 'Content-Type': 'application/json',
259
+ 'X-Ingest-Key': key,
260
+ 'X-Avowa-Client': `avowa-runtime-js/${VERSION}`
261
+ };
262
+ if (secret) {
263
+ const ts = String(Math.floor(Date.now() / 1000));
264
+ const nonce = [...(globalThis.crypto && globalThis.crypto.getRandomValues ? globalThis.crypto.getRandomValues(new Uint8Array(12)) : (await import('node:crypto')).randomBytes(12))].map(b => b.toString(16).padStart(2, '0')).join('');
265
+ headers['X-Avowa-Timestamp'] = ts;
266
+ headers['X-Avowa-Nonce'] = nonce;
267
+ headers['X-Avowa-Signature'] = await hmacHex(secret, `${ts}.${nonce}.${body}`);
268
+ if (remoteOn()) headers['X-Avowa-Fields'] = REMOTE.v || 'none';
269
+ }
270
+ if (inflight >= MAX_INFLIGHT) {
271
+ warnOnce('inflight', `${MAX_INFLIGHT} signals already in flight — Avowa is slow or unreachable, so signals are being dropped. Your app is unaffected.`);
272
+ return null;
273
+ }
274
+ inflight++;
275
+ const ctl = new AbortController();
276
+ const timer = setTimeout(() => ctl.abort(), TIMEOUT_MS);
277
+ if (timer && typeof timer.unref === 'function') timer.unref();
278
+ try {
279
+ const r = await fetch(base + '/ingest/runtime', {
280
+ method: 'POST',
281
+ headers,
282
+ body,
283
+ signal: ctl.signal
284
+ });
285
+ if (r.ok) {
286
+ try {
287
+ const j = await r.clone().json();
288
+ if (j && j.sdk_fields && secret && remoteOn()) await acceptFields(j.sdk_fields, secret);
289
+ if (j && typeof j.sdk_latest === 'string' && /^\d+\.\d+\.\d+$/.test(j.sdk_latest)) {
290
+ warnOnce('latest', `@avowa/runtime ${j.sdk_latest} is available (this is ${VERSION}). Nothing is wrong — upgrade when convenient (your Avowa Connections page has the download).`);
291
+ }
292
+ } catch {}
293
+ }
294
+ if (!r.ok) {
295
+ const hint = {
296
+ 401: 'the key or secret is wrong, or this host\'s clock is off (signatures expire after 5 minutes)',
297
+ 402: 'the workspace is on the Declare plan — live capture needs Prove',
298
+ 403: 'blocked before reaching Avowa (a proxy or WAF?)',
299
+ 404: `${base} is not an Avowa API — check AVOWA_BASE_URL`,
300
+ 429: 'rate limited — the SDK does not retry; reduce volume or sample'
301
+ }[r.status];
302
+ warnOnce(`http${r.status}`, `signal rejected: HTTP ${r.status}${hint ? ' — ' + hint : ''}`);
303
+ }
304
+ return r;
305
+ } catch (e) {
306
+ warnOnce('net', `could not reach ${base} (${e && e.name ? e.name : 'error'}) — check the URL, DNS and egress from this host`);
307
+ return null;
308
+ } finally {
309
+ clearTimeout(timer);
310
+ inflight--;
311
+ }
312
+ }
313
+ async function track(meta, fn) {
314
+ const start = Date.now();
315
+ let err = null;
316
+ try {
317
+ return await fn();
318
+ } catch (e) {
319
+ err = errName(e);
320
+ throw e;
321
+ } finally {
322
+ Promise.resolve().then(() => capture({
323
+ ...meta,
324
+ error: err,
325
+ latency_ms: Date.now() - start
326
+ })).catch(() => {});
327
+ }
328
+ }
329
+ const textOfMessages = msgs => {
330
+ const out = [];
331
+ for (const m of msgs || []) {
332
+ if (typeof m === 'string') out.push(m);else if (m && typeof m.content === 'string') out.push(m.content);else if (m && Array.isArray(m.content)) for (const b of m.content) if (b && typeof b.text === 'string') out.push(b.text);
333
+ }
334
+ return out.join('\n');
335
+ };
336
+ const toolNames = tools => (tools || []).map(t => t && (t.name || t.function && t.function.name) || null).filter(Boolean).slice(0, 60);
337
+ const errName = e => e && (e.status === 429 || e.statusCode === 429) ? 'RateLimitError' : e && e.name || 'Error';
338
+ const KIND = {
339
+ image: 'image',
340
+ image_url: 'image',
341
+ input_image: 'image',
342
+ document: 'file',
343
+ file: 'file',
344
+ input_file: 'file',
345
+ input_audio: 'audio',
346
+ audio: 'audio'
347
+ };
348
+ function requestFacts(params) {
349
+ const p = params || {},
350
+ f = {};
351
+ for (const k of ['max_tokens', 'max_completion_tokens', 'max_output_tokens']) {
352
+ if (Number.isInteger(p[k]) && p[k] > 0) {
353
+ f.token_ceiling = p[k];
354
+ break;
355
+ }
356
+ }
357
+ const msgs = Array.isArray(p.messages) ? p.messages : Array.isArray(p.input) ? p.input : null;
358
+ let system = !!(p.system || p.instructions);
359
+ if (msgs) {
360
+ const roles = {
361
+ user: 0,
362
+ assistant: 0,
363
+ tool: 0
364
+ },
365
+ kinds = {
366
+ image: 0,
367
+ file: 0,
368
+ audio: 0
369
+ };
370
+ let chars = 0;
371
+ for (const m of msgs) {
372
+ if (!m) continue;
373
+ if (m.role === 'system' || m.role === 'developer') system = true;else if (m.role in roles) roles[m.role]++;
374
+ if (typeof m.content === 'string') chars += m.content.length;else if (Array.isArray(m.content)) {
375
+ for (const b of m.content) {
376
+ const k = b && KIND[b.type];
377
+ if (k) kinds[k]++;else if (b && b.type === 'tool_result') roles.tool++;
378
+ if (b && typeof b.text === 'string') chars += b.text.length;
379
+ }
380
+ }
381
+ }
382
+ Object.assign(f, {
383
+ messages_user: roles.user,
384
+ messages_assistant: roles.assistant,
385
+ messages_tool: roles.tool,
386
+ input_images: kinds.image,
387
+ input_files: kinds.file,
388
+ input_audio: kinds.audio,
389
+ prompt_chars: chars
390
+ });
391
+ }
392
+ if (msgs || system) f.system_prompt_present = system;
393
+ if (p.tool_choice != null) f.tool_choice = String(typeof p.tool_choice === 'string' ? p.tool_choice : p.tool_choice.type || 'specific').slice(0, 20);
394
+ if (p.stream != null) f.streaming = !!p.stream;
395
+ const rf = p.response_format || p.output_format;
396
+ if (rf != null) f.response_format_type = String(rf && rf.type || 'schema').slice(0, 30);
397
+ return [f, Object.keys(f)];
398
+ }
399
+ const USAGE = {
400
+ input_tokens: ['input_tokens', 'prompt_tokens'],
401
+ output_tokens: ['output_tokens', 'completion_tokens'],
402
+ cache_read_tokens: ['cache_read_input_tokens'],
403
+ cache_write_tokens: ['cache_creation_input_tokens']
404
+ };
405
+ function usageFacts(resp) {
406
+ const u = resp && resp.usage,
407
+ f = {};
408
+ if (!u) return f;
409
+ for (const [fact, names] of Object.entries(USAGE)) {
410
+ for (const n of names) if (Number.isInteger(u[n])) {
411
+ f[fact] = u[n];
412
+ break;
413
+ }
414
+ }
415
+ if (f.cache_read_tokens == null) {
416
+ for (const d of ['prompt_tokens_details', 'input_tokens_details']) {
417
+ if (u[d] && Number.isInteger(u[d].cached_tokens)) {
418
+ f.cache_read_tokens = u[d].cached_tokens;
419
+ break;
420
+ }
421
+ }
422
+ }
423
+ return f;
424
+ }
425
+ function clientFacts(client) {
426
+ const f = {};
427
+ if (client && Number.isInteger(client.maxRetries)) f.client_max_retries = client.maxRetries;
428
+ if (client && typeof client.timeout === 'number') f.client_timeout_s = client.timeout / 1000;
429
+ return f;
430
+ }
431
+ const CODE = /^[A-Za-z0-9_.:-]{1,60}$/;
432
+ const label = (v, n = 30) => typeof v === 'string' && v && CODE.test(v.slice(0, n)) ? v.slice(0, n) : null;
433
+ const num = v => typeof v === 'number' && Number.isFinite(v) ? v : null;
434
+ function paramFacts(params) {
435
+ const p = params || {},
436
+ f = {};
437
+ for (const [fact, key] of [['temperature', 'temperature'], ['top_p', 'top_p'], ['seed', 'seed'], ['choices_n', 'n']]) {
438
+ const v = num(p[key]);
439
+ if (v != null) f[fact] = v;
440
+ }
441
+ let stops = p.stop_sequences != null ? p.stop_sequences : p.stop;
442
+ if (typeof stops === 'string') stops = [stops];
443
+ if (Array.isArray(stops)) f.stop_sequences = stops.length;
444
+ for (const [fact, key] of [['parallel_tool_calls', 'parallel_tool_calls'], ['store_requested', 'store'], ['logprobs', 'logprobs']]) {
445
+ if (typeof p[key] === 'boolean') f[fact] = p[key];
446
+ }
447
+ const tier = label(p.service_tier, 20);
448
+ if (tier) f.service_tier_requested = tier;
449
+ if (p.metadata != null) f.metadata_present = !!p.metadata && Object.keys(p.metadata).length > 0;
450
+ if (p.user || p.safety_identifier || p.metadata && p.metadata.user_id) f.end_user_id_present = true;else if ('user' in p || 'safety_identifier' in p || p.metadata != null) f.end_user_id_present = false;
451
+ const effort = label(p.reasoning_effort || p.reasoning && p.reasoning.effort, 20);
452
+ if (effort) f.reasoning_effort = effort;
453
+ if (typeof p.thinking === 'boolean') f.thinking_enabled = p.thinking;else if (p.thinking != null) f.thinking_enabled = p.thinking.type != null && p.thinking.type !== 'disabled';
454
+ return f;
455
+ }
456
+ const filtered = r => {
457
+ const inner = r && r.content_filter_results ? r.content_filter_results : r;
458
+ return inner && typeof inner === 'object' ? Object.entries(inner).filter(([k, v]) => v && v.filtered === true && CODE.test(k)).map(([k]) => k) : [];
459
+ };
460
+ function responseMetaFacts(resp) {
461
+ const f = {};
462
+ if (!resp) return f;
463
+ const fp = label(resp.system_fingerprint, 60);
464
+ if (fp) f.system_fingerprint = fp;
465
+ const tier = label(resp.service_tier || resp.usage && resp.usage.service_tier, 20);
466
+ if (tier) f.service_tier = tier;
467
+ let present = false,
468
+ cats = [];
469
+ if (resp.prompt_filter_results != null) {
470
+ present = true;
471
+ for (const r of [].concat(resp.prompt_filter_results)) cats.push(...filtered(r));
472
+ }
473
+ for (const c of Array.isArray(resp.choices) ? resp.choices.slice(0, 4) : []) {
474
+ if (c && c.content_filter_results != null) {
475
+ present = true;
476
+ cats.push(...filtered(c));
477
+ }
478
+ }
479
+ if (present) {
480
+ f.provider_filtered = cats.length > 0;
481
+ if (cats.length) f.provider_filter_categories = [...new Set(cats)].sort().slice(0, 10);
482
+ }
483
+ return f;
484
+ }
485
+ function errorFacts(e) {
486
+ const f = {};
487
+ if (!e || typeof e !== 'object') return f;
488
+ const st = num(e.status) != null ? e.status : num(e.statusCode);
489
+ if (st != null && st >= 100 && st <= 599) f.http_status = st;
490
+ const body = e.error;
491
+ const code = [body && body.error && body.error.type, body && body.type !== 'error' ? body.type : null, e.code, e.type].map(c => label(typeof c === 'string' ? c : null, 60)).find(Boolean);
492
+ if (code) f.provider_error_code = code;
493
+ try {
494
+ const h = e.headers;
495
+ const ra = h && (typeof h.get === 'function' ? h.get('retry-after') : h['retry-after']);
496
+ if (ra != null && Number.isFinite(Number(ra))) f.retry_after_s = Number(ra);
497
+ } catch {}
498
+ return f;
499
+ }
500
+ const REGION_VARS = ['AWS_REGION', 'AWS_DEFAULT_REGION', 'GOOGLE_CLOUD_REGION', 'FUNCTION_REGION', 'CLOUD_RUN_REGION', 'REGION_NAME', 'AZURE_REGION', 'FLY_REGION', 'VERCEL_REGION', 'RAILWAY_REPLICA_REGION', 'RENDER_REGION'];
501
+ function envFacts() {
502
+ const f = {};
503
+ if (typeof process !== 'undefined' && process.versions && process.versions.node) f.node_version = process.versions.node;
504
+ for (const v of REGION_VARS) {
505
+ const val = env[v];
506
+ if (val && /^[A-Za-z0-9 _-]{2,30}$/.test(val)) {
507
+ f.app_region = val;
508
+ f.app_region_source = v;
509
+ break;
510
+ }
511
+ }
512
+ return f;
513
+ }
514
+ function responseFacts(resp, params, kind) {
515
+ const f = {},
516
+ seen = [];
517
+ if (!resp) return [f, seen];
518
+ const asked = params && params.model;
519
+ if (asked) {
520
+ f.requested_model = String(asked).slice(0, 120);
521
+ seen.push('requested_model');
522
+ }
523
+ let stop = resp.stop_reason;
524
+ if (stop == null && resp.choices && resp.choices[0]) stop = resp.choices[0].finish_reason;
525
+ if (stop == null && resp.status != null && Array.isArray(resp.output)) {
526
+ stop = resp.incomplete_details && resp.incomplete_details.reason || resp.status;
527
+ const types = new Set(resp.output.flatMap(it => (Array.isArray(it && it.content) ? it.content : []).map(c => c && c.type)));
528
+ if (types.has('refusal')) {
529
+ f.refusal_part = true;
530
+ seen.push('refusal_part');
531
+ }
532
+ }
533
+ if (stop != null) {
534
+ f.stop_reason = String(stop).slice(0, 40);
535
+ seen.push('stop_reason');
536
+ }
537
+ const offered = toolNames(params && params.tools);
538
+ if (offered.length) {
539
+ f.tools_offered = offered;
540
+ seen.push('tools_offered');
541
+ }
542
+ const invoked = [];
543
+ try {
544
+ if (kind === 'anthropic') {
545
+ for (const b of resp.content || []) {
546
+ if (b && b.type === 'tool_use' && b.name) invoked.push(String(b.name).slice(0, 64));
547
+ }
548
+ } else {
549
+ for (const tc of resp.choices && resp.choices[0] && resp.choices[0].message && resp.choices[0].message.tool_calls || []) {
550
+ const n = tc.function && tc.function.name || tc.name;
551
+ if (n) invoked.push(String(n).slice(0, 64));
552
+ }
553
+ for (const it of resp.output || []) {
554
+ if (it && it.type === 'function_call' && it.name) invoked.push(String(it.name).slice(0, 64));
555
+ }
556
+ }
557
+ } catch {}
558
+ if (offered.length || invoked.length) {
559
+ f.tools_invoked = invoked;
560
+ seen.push('tools_invoked');
561
+ }
562
+ return [f, seen];
563
+ }
564
+ function outputText(resp, kind) {
565
+ try {
566
+ if (kind === 'anthropic') return (resp.content || []).map(b => b && b.text || '').join('\n');
567
+ if (typeof resp.output_text === 'string') return resp.output_text;
568
+ return (resp.choices || []).map(c => c.message && c.message.content || '').join('\n');
569
+ } catch {
570
+ return '';
571
+ }
572
+ }
573
+ function streamWatch(onEnd, kind) {
574
+ let model = null,
575
+ stop = null,
576
+ size = 0,
577
+ ttft = null;
578
+ const started = Date.now();
579
+ const text = [];
580
+ const keep = t => {
581
+ if (size < SCAN_LIMIT) {
582
+ text.push(t);
583
+ size += t.length;
584
+ }
585
+ };
586
+ const see = c => {
587
+ if (ttft === null) ttft = Date.now() - started;
588
+ try {
589
+ const t = c.type || '';
590
+ if (t === 'message_start' && c.message && c.message.model) model = c.message.model;
591
+ if (t === 'message_delta' && c.delta && c.delta.stop_reason) stop = c.delta.stop_reason;
592
+ if (t === 'content_block_delta' && c.delta && c.delta.text) keep(c.delta.text);
593
+ if (t.endsWith('output_text.delta') && typeof c.delta === 'string') keep(c.delta);
594
+ if (t === 'response.completed' && c.response && c.response.model) model = c.response.model;
595
+ if (!t && c.model) model = c.model;
596
+ const ch = c.choices && c.choices[0];
597
+ if (ch) {
598
+ if (ch.finish_reason) stop = ch.finish_reason;
599
+ if (ch.delta && typeof ch.delta.content === 'string') keep(ch.delta.content);
600
+ }
601
+ } catch {}
602
+ };
603
+ let done = false;
604
+ const finish = err => {
605
+ if (done) return;
606
+ done = true;
607
+ const all = text.join('');
608
+ const summary = kind === 'anthropic' ? {
609
+ model,
610
+ stop_reason: stop,
611
+ content: [{
612
+ type: 'text',
613
+ text: all
614
+ }]
615
+ } : {
616
+ model,
617
+ output_text: all,
618
+ choices: [{
619
+ finish_reason: stop,
620
+ message: {
621
+ content: all
622
+ }
623
+ }]
624
+ };
625
+ try {
626
+ onEnd(summary, err, ttft);
627
+ } catch (e) {
628
+ internalError('stream.finish', e);
629
+ }
630
+ };
631
+ return {
632
+ see,
633
+ finish
634
+ };
635
+ }
636
+ function observeStream(stream, onEnd, kind) {
637
+ const w = streamWatch(onEnd, kind);
638
+ const watched = makeIt => async function* () {
639
+ try {
640
+ for await (const c of {
641
+ [Symbol.asyncIterator]: makeIt
642
+ }) {
643
+ w.see(c);
644
+ yield c;
645
+ }
646
+ } catch (e) {
647
+ w.finish(e);
648
+ throw e;
649
+ } finally {
650
+ w.finish(null);
651
+ }
652
+ }();
653
+ try {
654
+ if (typeof stream.iterator === 'function') {
655
+ const orig = stream.iterator.bind(stream);
656
+ stream.iterator = () => watched(orig);
657
+ } else if (typeof stream[Symbol.asyncIterator] === 'function') {
658
+ const orig = stream[Symbol.asyncIterator].bind(stream);
659
+ stream[Symbol.asyncIterator] = () => watched(orig);
660
+ }
661
+ } catch {}
662
+ return stream;
663
+ }
664
+ function wrapMethod(holder, name, kind, host, opts) {
665
+ if (typeof holder[name] !== 'function' || holder[name]._avowa_wrapped) return;
666
+ const original = holder[name].bind(holder);
667
+ const wrapped = function (params = {}, ...rest) {
668
+ const start = Date.now();
669
+ const emit = (resp, err, ttft) => {
670
+ try {
671
+ const more = {
672
+ ...envFacts(),
673
+ ...paramFacts(params),
674
+ ...responseMetaFacts(resp),
675
+ provider_lib: kind === 'anthropic' ? '@anthropic-ai/sdk' : 'openai'
676
+ };
677
+ Object.assign(more, remoteFacts(kind, resp, params, err && typeof err === 'object' ? err : null));
678
+ if (err && typeof err === 'object') {
679
+ Object.assign(more, errorFacts(err));
680
+ err = errName(err);
681
+ }
682
+ if (ttft != null) more.ttft_ms = ttft;
683
+ const [facts, seen] = responseFacts(resp, params, kind);
684
+ for (const [k, v] of Object.entries(more)) if (!(k in facts)) facts[k] = v;
685
+ seen.push(...Object.keys(more));
686
+ const [req, reqSeen] = requestFacts(params);
687
+ Object.assign(facts, req);
688
+ seen.push(...reqSeen);
689
+ const usage = usageFacts(resp);
690
+ Object.assign(facts, usage, opts.clientFacts || {});
691
+ seen.push(...Object.keys(usage), ...Object.keys(opts.clientFacts || {}));
692
+ const out = resp ? outputText(resp, kind) : '';
693
+ if (resp) {
694
+ facts.output_chars = out.length;
695
+ seen.push('output_chars');
696
+ }
697
+ seen.push('model', 'endpoint', 'latency_ms');
698
+ if (err) seen.push('error');
699
+ if (opts.scan !== false) seen.push('pii_detected', 'injection_suspected', 'pii_families', 'injection_families');
700
+ const prompt = kind === 'anthropic' ? textOfMessages(params.messages) : textOfMessages(params.messages || (Array.isArray(params.input) ? params.input : [params.input]));
701
+ capture({
702
+ ...(opts.asserts || {}),
703
+ ...facts,
704
+ model: resp && resp.model || params.model,
705
+ region: opts.region,
706
+ endpoint: host,
707
+ latency_ms: Date.now() - start,
708
+ error: err,
709
+ scanPrompt: opts.scan !== false ? prompt : undefined,
710
+ scanOutput: opts.scan !== false && out ? out : undefined,
711
+ _sdk_observed: seen
712
+ });
713
+ } catch (e) {
714
+ internalError('emit', e);
715
+ }
716
+ };
717
+ let p;
718
+ try {
719
+ p = original(params, ...rest);
720
+ } catch (e) {
721
+ emit(null, e);
722
+ throw e;
723
+ }
724
+ try {
725
+ if (p && typeof p.then === 'function') {
726
+ p.then(resp => {
727
+ if (params && params.stream && resp && (typeof resp.iterator === 'function' || typeof resp[Symbol.asyncIterator] === 'function')) observeStream(resp, emit, kind);else emit(resp, null);
728
+ }, e => emit(null, e));
729
+ } else {
730
+ emit(p, null);
731
+ }
732
+ } catch (e) {
733
+ internalError('wrap', e);
734
+ }
735
+ return p;
736
+ };
737
+ wrapped._avowa_wrapped = true;
738
+ holder[name] = wrapped;
739
+ }
740
+ function instrumentOpenAI(client, opts = {}) {
741
+ const host = hostOf(client && client.baseURL) || 'api.openai.com';
742
+ opts = {
743
+ ...opts,
744
+ clientFacts: clientFacts(client)
745
+ };
746
+ const chat = client && client.chat && client.chat.completions;
747
+ if (chat) wrapMethod(chat, 'create', 'openai', host, opts);
748
+ if (client && client.responses) wrapMethod(client.responses, 'create', 'openai', host, opts);
749
+ return client;
750
+ }
751
+ function instrumentAnthropic(client, opts = {}) {
752
+ const host = hostOf(client && client.baseURL) || 'api.anthropic.com';
753
+ opts = {
754
+ ...opts,
755
+ clientFacts: clientFacts(client)
756
+ };
757
+ if (client && client.messages) wrapMethod(client.messages, 'create', 'anthropic', host, opts);
758
+ return client;
759
+ }
760
+ return {
761
+ capture,
762
+ track,
763
+ instrumentOpenAI,
764
+ instrumentAnthropic
765
+ };
766
+ }
767
+ export default createAvowa;
package/package.json CHANGED
@@ -1,6 +1,42 @@
1
1
  {
2
2
  "name": "@avowa/runtime",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.11.0",
4
+ "description": "Avowa Runtime SDK — emit live AI-inference signals as observed evidence. Metadata only; never prompts or completions.",
5
+ "type": "module",
6
+ "main": "avowa-runtime.js",
7
+ "exports": {
8
+ ".": "./avowa-runtime.js"
9
+ },
10
+ "files": [
11
+ "avowa-runtime.js",
12
+ "README.md",
13
+ "LICENSE",
14
+ "NOTICE"
15
+ ],
16
+ "keywords": [
17
+ "avowa",
18
+ "ai-trust",
19
+ "evidence",
20
+ "compliance",
21
+ "observability",
22
+ "llm"
23
+ ],
24
+ "license": "Apache-2.0",
25
+ "author": "Avowa, Inc.",
26
+ "homepage": "https://avowa.ai",
27
+ "repository": {
28
+ "type": "git",
29
+ "url": "git+https://github.com/Avowa-AI/avowa-runtime-sdk.git"
30
+ },
31
+ "engines": {
32
+ "node": ">=18"
33
+ },
34
+ "dependencies": {},
35
+ "publishConfig": {
36
+ "access": "public",
37
+ "provenance": true
38
+ },
39
+ "bugs": {
40
+ "url": "https://github.com/Avowa-AI/avowa-runtime-sdk/issues"
41
+ }
42
+ }