@avowa/runtime 0.0.0-stage → 0.12.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.
@@ -0,0 +1,834 @@
1
+ // SPDX-License-Identifier: Apache-2.0
2
+ // Copyright 2026 Avowa, Inc.
3
+ const env = typeof process !== 'undefined' && process.env || {};
4
+ const VERSION = '0.12.0';
5
+ const SCHEMA = 'avowa.signal/1';
6
+ export const SDK_VERSION = VERSION;
7
+ let _subtle = null;
8
+ async function subtle() {
9
+ if (_subtle) return _subtle;
10
+ if (globalThis.crypto && globalThis.crypto.subtle) return _subtle = globalThis.crypto.subtle;
11
+ const m = await import('node:crypto');
12
+ return _subtle = m.webcrypto.subtle;
13
+ }
14
+ async function hmacHex(secret, msg) {
15
+ const enc = new TextEncoder();
16
+ const st = await subtle();
17
+ const k = await st.importKey('raw', enc.encode(secret), {
18
+ name: 'HMAC',
19
+ hash: 'SHA-256'
20
+ }, false, ['sign']);
21
+ const sig = await st.sign('HMAC', k, enc.encode(msg));
22
+ return [...new Uint8Array(sig)].map(b => b.toString(16).padStart(2, '0')).join('');
23
+ }
24
+ 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']);
25
+ const RF_NAME = /^[a-z][a-z0-9_]{1,40}$/;
26
+ const RF_SEG = /^(?:[A-Za-z_][A-Za-z0-9_]{0,40}|\d{1,2})$/;
27
+ const RF_PROVIDERS = ['*', 'openai', 'anthropic', 'bedrock', 'gemini'];
28
+ const REMOTE = {
29
+ v: null,
30
+ fields: []
31
+ };
32
+ const remoteOn = () => !['off', '0', 'false', 'no'].includes(String(env.AVOWA_REMOTE_FIELDS || 'on').trim().toLowerCase());
33
+ export function rfOk(f) {
34
+ if (!f || typeof f !== 'object') return false;
35
+ const {
36
+ name,
37
+ provider,
38
+ path
39
+ } = f;
40
+ if (!(typeof name === 'string' && RF_NAME.test(name) && RF_PROVIDERS.includes(provider) && ['request', 'response', 'error'].includes(f.from) && typeof path === 'string')) return false;
41
+ const segs = path.split('.');
42
+ return segs.length >= 1 && segs.length <= 6 && segs.every(x => RF_SEG.test(x) && !x.startsWith('_') && !RF_DENY.has(x.toLowerCase()));
43
+ }
44
+ function rfValue(v) {
45
+ if (typeof v === 'boolean') return v;
46
+ if (typeof v === 'number') return Number.isFinite(v) ? v : null;
47
+ return typeof v === 'string' && v && /^[A-Za-z0-9_.:-]{1,40}$/.test(v.slice(0, 40)) ? v.slice(0, 40) : null;
48
+ }
49
+ function rfGet(obj, path) {
50
+ for (const k of path.split('.')) {
51
+ if (obj == null) return null;
52
+ try {
53
+ obj = Array.isArray(obj) && /^\d+$/.test(k) ? obj[Number(k)] : obj[k];
54
+ } catch {
55
+ return null;
56
+ }
57
+ }
58
+ return obj;
59
+ }
60
+ async function acceptFields(block, secret) {
61
+ try {
62
+ if (!block || typeof block.doc !== 'string' || typeof block.mac !== 'string' || !secret) return;
63
+ if ((await hmacHex(secret, 'avowa-fields.' + block.doc)) !== block.mac) {
64
+ warnOnce('rf-mac', 'ignored a metadata-field list that did not verify under this connection\'s secret.');
65
+ return;
66
+ }
67
+ const d = JSON.parse(block.doc);
68
+ REMOTE.v = String(d.v || '').slice(0, 32) || null;
69
+ REMOTE.fields = (Array.isArray(d.fields) ? d.fields : []).slice(0, 20).filter(rfOk);
70
+ } catch (e) {
71
+ internalError('remote_fields', e);
72
+ }
73
+ }
74
+ export const _resetRemoteFields = () => {
75
+ REMOTE.v = null;
76
+ REMOTE.fields = [];
77
+ };
78
+ export const remoteFields = () => remoteOn() ? REMOTE.fields.map(f => ({
79
+ ...f
80
+ })) : [];
81
+ function remoteFacts(kind, resp, params, errObj) {
82
+ const out = {};
83
+ if (!REMOTE.fields.length || !remoteOn()) return out;
84
+ const src = {
85
+ request: params,
86
+ response: resp,
87
+ error: errObj
88
+ };
89
+ for (const f of REMOTE.fields) {
90
+ if ((f.provider === '*' || f.provider === kind) && src[f.from] != null) {
91
+ const v = rfValue(rfGet(src[f.from], f.path));
92
+ if (v != null) out['rf_' + f.name] = v;
93
+ }
94
+ }
95
+ return out;
96
+ }
97
+ const _warned = new Set();
98
+ function warnOnce(kind, msg) {
99
+ if (_warned.has(kind)) return;
100
+ _warned.add(kind);
101
+ try {
102
+ console.error(`[avowa] ${msg}`);
103
+ } catch {}
104
+ }
105
+ export const INTERNAL_ERRORS = {};
106
+ function internalError(where, e) {
107
+ const key = `${where}:${e && e.name || 'Error'}`;
108
+ INTERNAL_ERRORS[key] = (INTERNAL_ERRORS[key] || 0) + 1;
109
+ if (['1', 'true', 'yes', 'on'].includes(String(typeof process !== 'undefined' && process.env && process.env.AVOWA_STRICT || '').trim().toLowerCase())) throw e;
110
+ warnOnce('internal:' + key, `internal error in ${where} (${key.split(':')[1]}) — this signal was skipped; your app is unaffected`);
111
+ }
112
+ const CARD_RX = /\b(?:\d[ -]*?){13,16}\b/;
113
+ function luhnOk(digits) {
114
+ let total = 0,
115
+ alt = false;
116
+ for (let i = digits.length - 1; i >= 0; i--) {
117
+ let d = digits.charCodeAt(i) - 48;
118
+ if (alt) {
119
+ d *= 2;
120
+ if (d > 9) d -= 9;
121
+ }
122
+ total += d;
123
+ alt = !alt;
124
+ }
125
+ return total % 10 === 0;
126
+ }
127
+ function looksLikeCard(text) {
128
+ const rx = new RegExp(CARD_RX.source, 'g');
129
+ let m;
130
+ while ((m = rx.exec(text)) !== null) {
131
+ const digits = m[0].replace(/[^0-9]/g, '');
132
+ if (digits.length >= 13 && digits.length <= 16 && luhnOk(digits)) return true;
133
+ }
134
+ return false;
135
+ }
136
+ 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/];
137
+ export const SCAN_LIMIT = 32 * 1024;
138
+ const cap = (t, keep) => typeof t === 'string' && t.length > SCAN_LIMIT ? keep === 'tail' ? t.slice(-SCAN_LIMIT) : t.slice(0, SCAN_LIMIT) : t;
139
+ const TRUE = new Set(['1', 'true', 'yes', 'on']);
140
+ const isOn = v => TRUE.has(String(v || '').trim().toLowerCase());
141
+ function privateHost(h) {
142
+ h = String(h || '').replace(/^\[|\]$/g, '').toLowerCase();
143
+ if (!h) return false;
144
+ if (h === 'localhost' || h.endsWith('.localhost') || !h.includes('.') && !h.includes(':')) return true;
145
+ if (/^127\./.test(h) || h === '::1' || /^10\./.test(h) || /^192\.168\./.test(h) || /^169\.254\./.test(h)) return true;
146
+ const m = h.match(/^172\.(\d+)\./);
147
+ return !!(m && +m[1] >= 16 && +m[1] <= 31);
148
+ }
149
+ export function checkedBase(url) {
150
+ if (!url) return [null, 'AVOWA_BASE_URL is not set'];
151
+ let u;
152
+ try {
153
+ u = new URL(String(url).includes('://') ? String(url) : `https://${url}`);
154
+ } catch {
155
+ return [null, 'AVOWA_BASE_URL is not a valid URL'];
156
+ }
157
+ const base = String(url).replace(/\/+$/, '');
158
+ if (u.protocol === 'https:') return [base, null];
159
+ if (u.protocol === 'http:' && (privateHost(u.hostname) || isOn(env.AVOWA_ALLOW_HTTP))) return [base, null];
160
+ 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)`];
161
+ }
162
+ 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];
163
+ 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;
164
+ 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-')];
165
+ const PII_NAMES = ['email', 'us_ssn', 'payment_card', 'aws_access_key', 'private_key', 'jwt', 'provider_secret_key'];
166
+ const INJECTION_NAMES = ['ignore_instructions', 'disregard_rules', 'reveal_system_prompt', 'role_override', 'developer_mode', 'delimiter_injection', 'pretend'];
167
+ export function piiFamilies(text) {
168
+ if (typeof text !== 'string' || !text) return [];
169
+ const d = /\d/.test(text);
170
+ return PII_PATTERNS.flatMap((rx, i) => PII_GATES[i](text, d) && (rx === CARD_RX ? looksLikeCard(text) : rx.test(text)) ? [PII_NAMES[i]] : []);
171
+ }
172
+ export function injectionFamilies(text) {
173
+ if (typeof text !== 'string' || !text) return [];
174
+ return INJECTION_PATTERNS.flatMap((rx, i) => rx.test(text) ? [INJECTION_NAMES[i]] : []);
175
+ }
176
+ export const scanPii = text => piiFamilies(text).length;
177
+ export const scanInjection = text => injectionFamilies(text).length;
178
+ export const _ungated = {
179
+ pii: t => countMatches(t, PII_PATTERNS),
180
+ injection: t => countMatches(t, INJECTION_PATTERNS)
181
+ };
182
+ export function hostOf(url) {
183
+ if (!url) return null;
184
+ try {
185
+ return new URL(String(url).includes('://') ? url : `https://${url}`).hostname || null;
186
+ } catch {
187
+ return null;
188
+ }
189
+ }
190
+ const TOKEN_PREFIX = 'avw1_';
191
+ export function makeToken(key, secret, baseUrl) {
192
+ const raw = [key || '', secret || '', String(baseUrl || '').replace(/\/+$/, '')].join('\n');
193
+ return TOKEN_PREFIX + btoa(raw).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '');
194
+ }
195
+ export function readToken(token) {
196
+ token = String(token || '').trim();
197
+ if (!token.startsWith(TOKEN_PREFIX)) return null;
198
+ try {
199
+ const parts = atob(token.slice(TOKEN_PREFIX.length).replace(/-/g, '+').replace(/_/g, '/')).split('\n');
200
+ return parts.length === 3 && parts[0] ? parts : null;
201
+ } catch {
202
+ return null;
203
+ }
204
+ }
205
+ export function createAvowa({
206
+ ingestKey,
207
+ ingestSecret,
208
+ baseUrl,
209
+ region
210
+ } = {}) {
211
+ if (isOn(env.AVOWA_DISABLE)) {
212
+ const noop = async () => undefined;
213
+ return {
214
+ capture: noop,
215
+ track: (meta, fn) => fn(),
216
+ instrumentOpenAI: c => c,
217
+ instrumentAnthropic: c => c,
218
+ _wrapResource: () => undefined,
219
+ disabled: true
220
+ };
221
+ }
222
+ const tok = env.AVOWA_TOKEN ? readToken(env.AVOWA_TOKEN) : null;
223
+ if (env.AVOWA_TOKEN && !tok) warnOnce('token', 'AVOWA_TOKEN is set but is not a valid Avowa token (one starts with avw1_), so no signals will be sent. Copy it again from avowa.env or the console.');
224
+ const key = ingestKey || env.AVOWA_RUNTIME_KEY || tok && tok[0] || undefined;
225
+ const secret = ingestSecret || env.AVOWA_RUNTIME_SECRET || tok && tok[1] || undefined;
226
+ const [base, baseProblem] = checkedBase(baseUrl || env.AVOWA_BASE_URL || tok && tok[2] || undefined);
227
+ if (!key) warnOnce('nokey', 'no credentials. Set AVOWA_TOKEN (from `npx @avowa/runtime init`) or pass ingestKey. No signals will be sent.');else if (baseProblem) warnOnce('nobase', `${baseProblem} — no signals will be sent. Your app is unaffected.`);
228
+ const MAX_INFLIGHT = 64;
229
+ const TIMEOUT_MS = 5000;
230
+ let inflight = 0;
231
+ async function capture(evt = {}) {
232
+ try {
233
+ return await _capture(evt);
234
+ } catch (e) {
235
+ internalError('capture', e);
236
+ return null;
237
+ }
238
+ }
239
+ async function _capture(evt = {}) {
240
+ if (!key || !base) return;
241
+ const payload = {
242
+ model: evt.model || null,
243
+ region: evt.region || region || null,
244
+ latency_ms: evt.latency_ms ?? null
245
+ };
246
+ if (evt.train_on_data !== undefined && evt.train_on_data !== null) payload.train_on_data = !!evt.train_on_data;
247
+ if (evt.guardrail_blocked !== undefined && evt.guardrail_blocked !== null) {
248
+ payload.guardrail_blocked = !!evt.guardrail_blocked;
249
+ }
250
+ 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']) {
251
+ if (evt[k] !== undefined && evt[k] !== null) payload[k] = evt[k];
252
+ }
253
+ if (evt.endpoint) payload.endpoint = hostOf(evt.endpoint);
254
+ const scanP = evt.scanPrompt !== undefined && evt.scanPrompt !== null ? cap(evt.scanPrompt, 'tail') : null;
255
+ const scanO = evt.scanOutput !== undefined && evt.scanOutput !== null ? cap(evt.scanOutput, 'head') : null;
256
+ if (scanP !== null || scanO !== null) {
257
+ await new Promise(r => typeof setImmediate === 'function' ? setImmediate(r) : setTimeout(r, 0));
258
+ if (scanP !== null) {
259
+ const fam = injectionFamilies(scanP);
260
+ payload.injection_suspected = fam.length;
261
+ payload.injection_families = fam;
262
+ }
263
+ if (scanO !== null) {
264
+ const fam = piiFamilies(scanO);
265
+ payload.pii_detected = fam.length;
266
+ payload.pii_families = fam;
267
+ }
268
+ }
269
+ 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];
270
+ if (Array.isArray(evt._sdk_observed) && evt._sdk_observed.length) payload._sdk_observed = [...new Set(evt._sdk_observed)];
271
+ const kinds = Object.keys(INTERNAL_ERRORS);
272
+ if (kinds.length) {
273
+ payload.sdk_errors = kinds.reduce((n, k) => n + INTERNAL_ERRORS[k], 0);
274
+ payload.sdk_error_kinds = kinds.sort().slice(0, 10);
275
+ }
276
+ return enqueue(payload);
277
+ }
278
+ const BATCH_MAX = 100;
279
+ const BATCH_WAIT_MS = 20;
280
+ let pending = [];
281
+ let pendingTimer = null;
282
+ function enqueue(payload) {
283
+ return new Promise((resolve, reject) => {
284
+ pending.push({
285
+ payload,
286
+ resolve,
287
+ reject
288
+ });
289
+ if (pending.length >= BATCH_MAX) flushPending();else if (!pendingTimer) pendingTimer = setTimeout(flushPending, BATCH_WAIT_MS);
290
+ });
291
+ }
292
+ function flushPending() {
293
+ if (pendingTimer) {
294
+ clearTimeout(pendingTimer);
295
+ pendingTimer = null;
296
+ }
297
+ const batch = pending.splice(0, BATCH_MAX);
298
+ if (pending.length) pendingTimer = setTimeout(flushPending, BATCH_WAIT_MS);
299
+ if (!batch.length) return;
300
+ sendEnvelope(batch.map(b => b.payload)).then(r => batch.forEach(b => b.resolve(r)), e => batch.forEach(b => b.reject(e)));
301
+ }
302
+ async function sendEnvelope(events) {
303
+ 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('');
304
+ const body = JSON.stringify({
305
+ schema: SCHEMA,
306
+ source: {
307
+ kind: 'runtime',
308
+ client: 'avowa-runtime-js',
309
+ version: VERSION
310
+ },
311
+ sent_at: new Date().toISOString().replace(/\.\d{3}Z$/, 'Z'),
312
+ nonce,
313
+ events
314
+ });
315
+ const headers = {
316
+ 'Content-Type': 'application/json',
317
+ 'X-Ingest-Key': key,
318
+ 'X-Avowa-Client': `avowa-runtime-js/${VERSION}`
319
+ };
320
+ if (secret) {
321
+ const ts = String(Math.floor(Date.now() / 1000));
322
+ headers['X-Avowa-Timestamp'] = ts;
323
+ headers['X-Avowa-Signature'] = await hmacHex(secret, `${ts}.${body}`);
324
+ if (remoteOn()) headers['X-Avowa-Fields'] = REMOTE.v || 'none';
325
+ }
326
+ if (inflight >= MAX_INFLIGHT) {
327
+ warnOnce('inflight', `${MAX_INFLIGHT} uploads already in flight — Avowa is slow or unreachable, so signals are being dropped. Your app is unaffected.`);
328
+ return null;
329
+ }
330
+ inflight++;
331
+ const ctl = new AbortController();
332
+ const timer = setTimeout(() => ctl.abort(), TIMEOUT_MS);
333
+ if (timer && typeof timer.unref === 'function') timer.unref();
334
+ try {
335
+ const r = await fetch(base + '/ingest/v1', {
336
+ method: 'POST',
337
+ headers,
338
+ body,
339
+ signal: ctl.signal
340
+ });
341
+ if (r.ok) {
342
+ try {
343
+ const j = await r.clone().json();
344
+ if (j && j.sdk_fields && secret && remoteOn()) await acceptFields(j.sdk_fields, secret);
345
+ if (j && typeof j.sdk_latest === 'string' && /^\d+\.\d+\.\d+$/.test(j.sdk_latest)) {
346
+ warnOnce('latest', `@avowa/runtime ${j.sdk_latest} is available (this is ${VERSION}). Nothing is wrong — upgrade when convenient.`);
347
+ }
348
+ } catch {}
349
+ }
350
+ if (!r.ok) {
351
+ const hint = {
352
+ 401: 'the key or secret is wrong, or this host\'s clock is off (signatures expire after 5 minutes)',
353
+ 402: 'the workspace is on the Declare plan — live capture needs Prove',
354
+ 403: 'blocked before reaching Avowa (a proxy or WAF?)',
355
+ 404: `${base} is not an Avowa API — check AVOWA_BASE_URL`,
356
+ 429: 'rate limited — the SDK does not retry; reduce volume or sample'
357
+ }[r.status];
358
+ warnOnce(`http${r.status}`, `signal rejected: HTTP ${r.status}${hint ? ' — ' + hint : ''}`);
359
+ }
360
+ return r;
361
+ } catch (e) {
362
+ warnOnce('net', `could not reach ${base} (${e && e.name ? e.name : 'error'}) — check the URL, DNS and egress from this host`);
363
+ return null;
364
+ } finally {
365
+ clearTimeout(timer);
366
+ inflight--;
367
+ }
368
+ }
369
+ async function track(meta, fn) {
370
+ const start = Date.now();
371
+ let err = null;
372
+ try {
373
+ return await fn();
374
+ } catch (e) {
375
+ err = errName(e);
376
+ throw e;
377
+ } finally {
378
+ Promise.resolve().then(() => capture({
379
+ ...meta,
380
+ error: err,
381
+ latency_ms: Date.now() - start
382
+ })).catch(() => {});
383
+ }
384
+ }
385
+ const textOfMessages = msgs => {
386
+ const out = [];
387
+ for (const m of msgs || []) {
388
+ 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);
389
+ }
390
+ return out.join('\n');
391
+ };
392
+ const toolNames = tools => (tools || []).map(t => t && (t.name || t.function && t.function.name) || null).filter(Boolean).slice(0, 60);
393
+ const errName = e => e && (e.status === 429 || e.statusCode === 429) ? 'RateLimitError' : e && e.name || 'Error';
394
+ const KIND = {
395
+ image: 'image',
396
+ image_url: 'image',
397
+ input_image: 'image',
398
+ document: 'file',
399
+ file: 'file',
400
+ input_file: 'file',
401
+ input_audio: 'audio',
402
+ audio: 'audio'
403
+ };
404
+ function requestFacts(params) {
405
+ const p = params || {},
406
+ f = {};
407
+ for (const k of ['max_tokens', 'max_completion_tokens', 'max_output_tokens']) {
408
+ if (Number.isInteger(p[k]) && p[k] > 0) {
409
+ f.token_ceiling = p[k];
410
+ break;
411
+ }
412
+ }
413
+ const msgs = Array.isArray(p.messages) ? p.messages : Array.isArray(p.input) ? p.input : null;
414
+ let system = !!(p.system || p.instructions);
415
+ if (msgs) {
416
+ const roles = {
417
+ user: 0,
418
+ assistant: 0,
419
+ tool: 0
420
+ },
421
+ kinds = {
422
+ image: 0,
423
+ file: 0,
424
+ audio: 0
425
+ };
426
+ let chars = 0;
427
+ for (const m of msgs) {
428
+ if (!m) continue;
429
+ if (m.role === 'system' || m.role === 'developer') system = true;else if (m.role in roles) roles[m.role]++;
430
+ if (typeof m.content === 'string') chars += m.content.length;else if (Array.isArray(m.content)) {
431
+ for (const b of m.content) {
432
+ const k = b && KIND[b.type];
433
+ if (k) kinds[k]++;else if (b && b.type === 'tool_result') roles.tool++;
434
+ if (b && typeof b.text === 'string') chars += b.text.length;
435
+ }
436
+ }
437
+ }
438
+ Object.assign(f, {
439
+ messages_user: roles.user,
440
+ messages_assistant: roles.assistant,
441
+ messages_tool: roles.tool,
442
+ input_images: kinds.image,
443
+ input_files: kinds.file,
444
+ input_audio: kinds.audio,
445
+ prompt_chars: chars
446
+ });
447
+ }
448
+ if (msgs || system) f.system_prompt_present = system;
449
+ 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);
450
+ if (p.stream != null) f.streaming = !!p.stream;
451
+ const rf = p.response_format || p.output_format;
452
+ if (rf != null) f.response_format_type = String(rf && rf.type || 'schema').slice(0, 30);
453
+ return [f, Object.keys(f)];
454
+ }
455
+ const USAGE = {
456
+ input_tokens: ['input_tokens', 'prompt_tokens'],
457
+ output_tokens: ['output_tokens', 'completion_tokens'],
458
+ cache_read_tokens: ['cache_read_input_tokens'],
459
+ cache_write_tokens: ['cache_creation_input_tokens']
460
+ };
461
+ function usageFacts(resp) {
462
+ const u = resp && resp.usage,
463
+ f = {};
464
+ if (!u) return f;
465
+ for (const [fact, names] of Object.entries(USAGE)) {
466
+ for (const n of names) if (Number.isInteger(u[n])) {
467
+ f[fact] = u[n];
468
+ break;
469
+ }
470
+ }
471
+ if (f.cache_read_tokens == null) {
472
+ for (const d of ['prompt_tokens_details', 'input_tokens_details']) {
473
+ if (u[d] && Number.isInteger(u[d].cached_tokens)) {
474
+ f.cache_read_tokens = u[d].cached_tokens;
475
+ break;
476
+ }
477
+ }
478
+ }
479
+ return f;
480
+ }
481
+ function clientFacts(client) {
482
+ const f = {};
483
+ if (client && Number.isInteger(client.maxRetries)) f.client_max_retries = client.maxRetries;
484
+ if (client && typeof client.timeout === 'number') f.client_timeout_s = client.timeout / 1000;
485
+ return f;
486
+ }
487
+ const CODE = /^[A-Za-z0-9_.:-]{1,60}$/;
488
+ const label = (v, n = 30) => typeof v === 'string' && v && CODE.test(v.slice(0, n)) ? v.slice(0, n) : null;
489
+ const num = v => typeof v === 'number' && Number.isFinite(v) ? v : null;
490
+ function paramFacts(params) {
491
+ const p = params || {},
492
+ f = {};
493
+ for (const [fact, key] of [['temperature', 'temperature'], ['top_p', 'top_p'], ['seed', 'seed'], ['choices_n', 'n']]) {
494
+ const v = num(p[key]);
495
+ if (v != null) f[fact] = v;
496
+ }
497
+ let stops = p.stop_sequences != null ? p.stop_sequences : p.stop;
498
+ if (typeof stops === 'string') stops = [stops];
499
+ if (Array.isArray(stops)) f.stop_sequences = stops.length;
500
+ for (const [fact, key] of [['parallel_tool_calls', 'parallel_tool_calls'], ['store_requested', 'store'], ['logprobs', 'logprobs']]) {
501
+ if (typeof p[key] === 'boolean') f[fact] = p[key];
502
+ }
503
+ const tier = label(p.service_tier, 20);
504
+ if (tier) f.service_tier_requested = tier;
505
+ if (p.metadata != null) f.metadata_present = !!p.metadata && Object.keys(p.metadata).length > 0;
506
+ 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;
507
+ const effort = label(p.reasoning_effort || p.reasoning && p.reasoning.effort, 20);
508
+ if (effort) f.reasoning_effort = effort;
509
+ 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';
510
+ return f;
511
+ }
512
+ const filtered = r => {
513
+ const inner = r && r.content_filter_results ? r.content_filter_results : r;
514
+ return inner && typeof inner === 'object' ? Object.entries(inner).filter(([k, v]) => v && v.filtered === true && CODE.test(k)).map(([k]) => k) : [];
515
+ };
516
+ function responseMetaFacts(resp) {
517
+ const f = {};
518
+ if (!resp) return f;
519
+ const fp = label(resp.system_fingerprint, 60);
520
+ if (fp) f.system_fingerprint = fp;
521
+ const tier = label(resp.service_tier || resp.usage && resp.usage.service_tier, 20);
522
+ if (tier) f.service_tier = tier;
523
+ let present = false,
524
+ cats = [];
525
+ if (resp.prompt_filter_results != null) {
526
+ present = true;
527
+ for (const r of [].concat(resp.prompt_filter_results)) cats.push(...filtered(r));
528
+ }
529
+ for (const c of Array.isArray(resp.choices) ? resp.choices.slice(0, 4) : []) {
530
+ if (c && c.content_filter_results != null) {
531
+ present = true;
532
+ cats.push(...filtered(c));
533
+ }
534
+ }
535
+ if (present) {
536
+ f.provider_filtered = cats.length > 0;
537
+ if (cats.length) f.provider_filter_categories = [...new Set(cats)].sort().slice(0, 10);
538
+ }
539
+ return f;
540
+ }
541
+ function errorFacts(e) {
542
+ const f = {};
543
+ if (!e || typeof e !== 'object') return f;
544
+ const st = num(e.status) != null ? e.status : num(e.statusCode);
545
+ if (st != null && st >= 100 && st <= 599) f.http_status = st;
546
+ const body = e.error;
547
+ 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);
548
+ if (code) f.provider_error_code = code;
549
+ try {
550
+ const h = e.headers;
551
+ const ra = h && (typeof h.get === 'function' ? h.get('retry-after') : h['retry-after']);
552
+ if (ra != null && Number.isFinite(Number(ra))) f.retry_after_s = Number(ra);
553
+ } catch {}
554
+ return f;
555
+ }
556
+ 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'];
557
+ function envFacts() {
558
+ const f = {};
559
+ if (typeof process !== 'undefined' && process.versions && process.versions.node) f.node_version = process.versions.node;
560
+ for (const v of REGION_VARS) {
561
+ const val = env[v];
562
+ if (val && /^[A-Za-z0-9 _-]{2,30}$/.test(val)) {
563
+ f.app_region = val;
564
+ f.app_region_source = v;
565
+ break;
566
+ }
567
+ }
568
+ return f;
569
+ }
570
+ function responseFacts(resp, params, kind) {
571
+ const f = {},
572
+ seen = [];
573
+ if (!resp) return [f, seen];
574
+ const asked = params && params.model;
575
+ if (asked) {
576
+ f.requested_model = String(asked).slice(0, 120);
577
+ seen.push('requested_model');
578
+ }
579
+ let stop = resp.stop_reason;
580
+ if (stop == null && resp.choices && resp.choices[0]) stop = resp.choices[0].finish_reason;
581
+ if (stop == null && resp.status != null && Array.isArray(resp.output)) {
582
+ stop = resp.incomplete_details && resp.incomplete_details.reason || resp.status;
583
+ const types = new Set(resp.output.flatMap(it => (Array.isArray(it && it.content) ? it.content : []).map(c => c && c.type)));
584
+ if (types.has('refusal')) {
585
+ f.refusal_part = true;
586
+ seen.push('refusal_part');
587
+ }
588
+ }
589
+ if (stop != null) {
590
+ f.stop_reason = String(stop).slice(0, 40);
591
+ seen.push('stop_reason');
592
+ }
593
+ const offered = toolNames(params && params.tools);
594
+ if (offered.length) {
595
+ f.tools_offered = offered;
596
+ seen.push('tools_offered');
597
+ }
598
+ const invoked = [];
599
+ try {
600
+ if (kind === 'anthropic') {
601
+ for (const b of resp.content || []) {
602
+ if (b && b.type === 'tool_use' && b.name) invoked.push(String(b.name).slice(0, 64));
603
+ }
604
+ } else {
605
+ for (const tc of resp.choices && resp.choices[0] && resp.choices[0].message && resp.choices[0].message.tool_calls || []) {
606
+ const n = tc.function && tc.function.name || tc.name;
607
+ if (n) invoked.push(String(n).slice(0, 64));
608
+ }
609
+ for (const it of resp.output || []) {
610
+ if (it && it.type === 'function_call' && it.name) invoked.push(String(it.name).slice(0, 64));
611
+ }
612
+ }
613
+ } catch {}
614
+ if (offered.length || invoked.length) {
615
+ f.tools_invoked = invoked;
616
+ seen.push('tools_invoked');
617
+ }
618
+ return [f, seen];
619
+ }
620
+ function outputText(resp, kind) {
621
+ try {
622
+ if (kind === 'anthropic') return (resp.content || []).map(b => b && b.text || '').join('\n');
623
+ if (typeof resp.output_text === 'string') return resp.output_text;
624
+ return (resp.choices || []).map(c => c.message && c.message.content || '').join('\n');
625
+ } catch {
626
+ return '';
627
+ }
628
+ }
629
+ function streamWatch(onEnd, kind) {
630
+ let model = null,
631
+ stop = null,
632
+ size = 0,
633
+ ttft = null;
634
+ const started = Date.now();
635
+ const text = [];
636
+ const keep = t => {
637
+ if (size < SCAN_LIMIT) {
638
+ text.push(t);
639
+ size += t.length;
640
+ }
641
+ };
642
+ const see = c => {
643
+ if (ttft === null) ttft = Date.now() - started;
644
+ try {
645
+ const t = c.type || '';
646
+ if (t === 'message_start' && c.message && c.message.model) model = c.message.model;
647
+ if (t === 'message_delta' && c.delta && c.delta.stop_reason) stop = c.delta.stop_reason;
648
+ if (t === 'content_block_delta' && c.delta && c.delta.text) keep(c.delta.text);
649
+ if (t.endsWith('output_text.delta') && typeof c.delta === 'string') keep(c.delta);
650
+ if (t === 'response.completed' && c.response && c.response.model) model = c.response.model;
651
+ if (!t && c.model) model = c.model;
652
+ const ch = c.choices && c.choices[0];
653
+ if (ch) {
654
+ if (ch.finish_reason) stop = ch.finish_reason;
655
+ if (ch.delta && typeof ch.delta.content === 'string') keep(ch.delta.content);
656
+ }
657
+ } catch {}
658
+ };
659
+ let done = false;
660
+ const finish = err => {
661
+ if (done) return;
662
+ done = true;
663
+ const all = text.join('');
664
+ const summary = kind === 'anthropic' ? {
665
+ model,
666
+ stop_reason: stop,
667
+ content: [{
668
+ type: 'text',
669
+ text: all
670
+ }]
671
+ } : {
672
+ model,
673
+ output_text: all,
674
+ choices: [{
675
+ finish_reason: stop,
676
+ message: {
677
+ content: all
678
+ }
679
+ }]
680
+ };
681
+ try {
682
+ onEnd(summary, err, ttft);
683
+ } catch (e) {
684
+ internalError('stream.finish', e);
685
+ }
686
+ };
687
+ return {
688
+ see,
689
+ finish
690
+ };
691
+ }
692
+ function observeStream(stream, onEnd, kind) {
693
+ const w = streamWatch(onEnd, kind);
694
+ const watched = makeIt => async function* () {
695
+ try {
696
+ for await (const c of {
697
+ [Symbol.asyncIterator]: makeIt
698
+ }) {
699
+ w.see(c);
700
+ yield c;
701
+ }
702
+ } catch (e) {
703
+ w.finish(e);
704
+ throw e;
705
+ } finally {
706
+ w.finish(null);
707
+ }
708
+ }();
709
+ try {
710
+ if (typeof stream.iterator === 'function') {
711
+ const orig = stream.iterator.bind(stream);
712
+ stream.iterator = () => watched(orig);
713
+ } else if (typeof stream[Symbol.asyncIterator] === 'function') {
714
+ const orig = stream[Symbol.asyncIterator].bind(stream);
715
+ stream[Symbol.asyncIterator] = () => watched(orig);
716
+ }
717
+ } catch {}
718
+ return stream;
719
+ }
720
+ function wrapMethod(holder, name, kind, host, opts, given) {
721
+ if (typeof holder[name] !== 'function' || holder[name]._avowa_wrapped) return;
722
+ const original = given || holder[name].bind(holder);
723
+ const wrapped = function (params = {}, ...rest) {
724
+ const start = Date.now();
725
+ const emit = (resp, err, ttft) => {
726
+ try {
727
+ const more = {
728
+ ...envFacts(),
729
+ ...paramFacts(params),
730
+ ...responseMetaFacts(resp),
731
+ provider_lib: kind === 'anthropic' ? '@anthropic-ai/sdk' : 'openai'
732
+ };
733
+ Object.assign(more, remoteFacts(kind, resp, params, err && typeof err === 'object' ? err : null));
734
+ if (err && typeof err === 'object') {
735
+ Object.assign(more, errorFacts(err));
736
+ err = errName(err);
737
+ }
738
+ if (ttft != null) more.ttft_ms = ttft;
739
+ const [facts, seen] = responseFacts(resp, params, kind);
740
+ for (const [k, v] of Object.entries(more)) if (!(k in facts)) facts[k] = v;
741
+ seen.push(...Object.keys(more));
742
+ const [req, reqSeen] = requestFacts(params);
743
+ Object.assign(facts, req);
744
+ seen.push(...reqSeen);
745
+ const usage = usageFacts(resp);
746
+ Object.assign(facts, usage, opts.clientFacts || {});
747
+ seen.push(...Object.keys(usage), ...Object.keys(opts.clientFacts || {}));
748
+ const out = resp ? outputText(resp, kind) : '';
749
+ if (resp) {
750
+ facts.output_chars = out.length;
751
+ seen.push('output_chars');
752
+ }
753
+ seen.push('model', 'endpoint', 'latency_ms');
754
+ if (err) seen.push('error');
755
+ if (opts.scan !== false) seen.push('pii_detected', 'injection_suspected', 'pii_families', 'injection_families');
756
+ const prompt = kind === 'anthropic' ? textOfMessages(params.messages) : textOfMessages(params.messages || (Array.isArray(params.input) ? params.input : [params.input]));
757
+ capture({
758
+ ...(opts.asserts || {}),
759
+ ...facts,
760
+ model: resp && resp.model || params.model,
761
+ region: opts.region,
762
+ endpoint: host,
763
+ latency_ms: Date.now() - start,
764
+ error: err,
765
+ scanPrompt: opts.scan !== false ? prompt : undefined,
766
+ scanOutput: opts.scan !== false && out ? out : undefined,
767
+ _sdk_observed: seen
768
+ });
769
+ } catch (e) {
770
+ internalError('emit', e);
771
+ }
772
+ };
773
+ let p;
774
+ try {
775
+ p = original(params, ...rest);
776
+ } catch (e) {
777
+ emit(null, e);
778
+ throw e;
779
+ }
780
+ try {
781
+ if (p && typeof p.then === 'function') {
782
+ p.then(resp => {
783
+ if (params && params.stream && resp && (typeof resp.iterator === 'function' || typeof resp[Symbol.asyncIterator] === 'function')) observeStream(resp, emit, kind);else emit(resp, null);
784
+ }, e => emit(null, e));
785
+ } else {
786
+ emit(p, null);
787
+ }
788
+ } catch (e) {
789
+ internalError('wrap', e);
790
+ }
791
+ return p;
792
+ };
793
+ wrapped._avowa_wrapped = true;
794
+ holder[name] = wrapped;
795
+ }
796
+ function instrumentOpenAI(client, opts = {}) {
797
+ const host = hostOf(client && client.baseURL) || 'api.openai.com';
798
+ opts = {
799
+ ...opts,
800
+ clientFacts: clientFacts(client)
801
+ };
802
+ const chat = client && client.chat && client.chat.completions;
803
+ if (chat) wrapMethod(chat, 'create', 'openai', host, opts);
804
+ if (client && client.responses) wrapMethod(client.responses, 'create', 'openai', host, opts);
805
+ return client;
806
+ }
807
+ function instrumentAnthropic(client, opts = {}) {
808
+ const host = hostOf(client && client.baseURL) || 'api.anthropic.com';
809
+ opts = {
810
+ ...opts,
811
+ clientFacts: clientFacts(client)
812
+ };
813
+ if (client && client.messages) wrapMethod(client.messages, 'create', 'anthropic', host, opts);
814
+ return client;
815
+ }
816
+ function _wrapResource(resource, name, kind, original) {
817
+ const client = resource && resource._client;
818
+ const host = hostOf(client && client.baseURL) || (kind === 'anthropic' ? 'api.anthropic.com' : 'api.openai.com');
819
+ const scan = !['0', 'false', 'no', 'off'].includes(String(env.AVOWA_SCAN || '').trim().toLowerCase());
820
+ wrapMethod(resource, name, kind, host, {
821
+ clientFacts: clientFacts(client),
822
+ scan,
823
+ region
824
+ }, original.bind(resource));
825
+ }
826
+ return {
827
+ capture,
828
+ track,
829
+ instrumentOpenAI,
830
+ instrumentAnthropic,
831
+ _wrapResource
832
+ };
833
+ }
834
+ export default createAvowa;