@avowa/runtime 0.11.0 → 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.
package/README.md CHANGED
@@ -3,29 +3,78 @@
3
3
  The JavaScript/TypeScript half of the [Avowa Runtime SDK](https://github.com/Avowa-AI/avowa-runtime-sdk) — emits live AI-inference
4
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
5
 
6
+ ## Install
7
+
8
+ **Two lines, in your project folder.** Your code stays as it is. (The setup token comes from
9
+ Connections → Runtime SDK → *Generate setup token*.)
10
+
6
11
  ```bash
7
12
  npm install @avowa/runtime
13
+ npx @avowa/runtime init <setup-token> # writes avowa.env with one value: AVOWA_TOKEN
14
+ ```
15
+
16
+ `init` also offers to add the preload to your `start` script, and shows the change before it makes
17
+ it (`init --dry-run` changes nothing at all):
18
+
8
19
  ```
20
+ from: node server.js
21
+ to: node --import @avowa/runtime/register server.js
22
+ ```
23
+
24
+ Then start your app the way you always do and send one real request that calls the model.
25
+ `npx @avowa/runtime status` shows what is covered and asks the server whether it knows this key. It
26
+ sends no signal.
27
+
28
+ **In production** set two environment variables and change nothing else:
9
29
 
10
- One dependency-free file, Apache-2.0. (It is also in your Avowa SDK download, if you would rather vendor it.)
30
+ ```bash
31
+ AVOWA_TOKEN=avw1_... # the value in avowa.env
32
+ NODE_OPTIONS=--import @avowa/runtime/register # any start command, Docker, Kubernetes
33
+ ```
34
+
35
+ `AVOWA_DISABLE=1` switches everything off. One dependency-free package, Apache-2.0.
36
+
37
+ ### What the preload covers
38
+
39
+ `@avowa/runtime/register` patches the provider SDKs' own classes as your app loads, so every client
40
+ is covered whoever builds it: your code, a framework, or a dependency. ES modules and CommonJS both
41
+ work.
42
+
43
+ | Library | Covered |
44
+ |---|---|
45
+ | `openai` (OpenAI, Azure OpenAI, any OpenAI-compatible host) | `chat.completions.create`, `responses.create`, streams included |
46
+ | `@anthropic-ai/sdk` | `messages.create`, streams included |
47
+ | anything else (Bedrock, Gemini, Vercel AI SDK, raw `fetch`) | not yet: use `capture()` / `track()` below |
48
+
49
+ Two limits to know about:
50
+
51
+ - **Bundled server code.** A bundler (Next.js, esbuild, webpack) that compiles the provider SDK into
52
+ its own output file carries a private copy the preload never meets. Keep the provider SDK external
53
+ to the bundle (Next.js: `serverExternalPackages`), or wrap the client once as shown below.
54
+ - **Node version.** `--import` needs Node 18.18+ or 20.6+.
55
+
56
+ ## Use it in code instead
57
+
58
+ Nothing below is needed when the preload is on. It is for the cases above, and for recording what
59
+ your app enforces.
11
60
 
12
61
  ```js
13
62
  import createAvowa from '@avowa/runtime'
14
63
 
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
- })
64
+ const avowa = createAvowa() // reads AVOWA_TOKEN from the environment
21
65
 
22
66
  // record a call you already made
23
67
  avowa.capture({ model: 'claude-opus-4-8', train_on_data: false })
24
68
 
25
- // or wrap one — times it, and records whether it was blocked
69
+ // or wrap one: times it, and records whether it was blocked
26
70
  const resp = await avowa.track({ model: 'claude-opus-4-8' }, () => client.messages.create(...))
27
71
  ```
28
72
 
73
+ `createAvowa({ ingestKey, ingestSecret, baseUrl, region })` takes the values explicitly if you would
74
+ rather not use the token, and the three separate variables (`AVOWA_RUNTIME_KEY`,
75
+ `AVOWA_RUNTIME_SECRET`, `AVOWA_BASE_URL`) still work. To read `avowa.env` without the preload:
76
+ `import { loadEnv } from '@avowa/runtime/env'; loadEnv()`.
77
+
29
78
  **Metadata only.** Model id, host, region, latency, counts and the flags you pass. Never prompts,
30
79
  completions, tool arguments or customer data.
31
80
 
@@ -44,7 +93,7 @@ Licence: Apache-2.0.
44
93
  import OpenAI from 'openai'
45
94
  import { createAvowa } from '@avowa/runtime'
46
95
 
47
- const avowa = createAvowa() // AVOWA_RUNTIME_KEY / _SECRET / AVOWA_BASE_URL from the env
96
+ const avowa = createAvowa() // AVOWA_TOKEN from the env
48
97
  const openai = avowa.instrumentOpenAI(new OpenAI()) // chat.completions.create, responses.create — streams included
49
98
  // const anthropic = avowa.instrumentAnthropic(new Anthropic()) // messages.create — streams included
50
99
  ```
package/avowa-runtime.js CHANGED
@@ -1,7 +1,9 @@
1
1
  // SPDX-License-Identifier: Apache-2.0
2
2
  // Copyright 2026 Avowa, Inc.
3
3
  const env = typeof process !== 'undefined' && process.env || {};
4
- const VERSION = '0.11.0';
4
+ const VERSION = '0.12.0';
5
+ const SCHEMA = 'avowa.signal/1';
6
+ export const SDK_VERSION = VERSION;
5
7
  let _subtle = null;
6
8
  async function subtle() {
7
9
  if (_subtle) return _subtle;
@@ -185,6 +187,21 @@ export function hostOf(url) {
185
187
  return null;
186
188
  }
187
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
+ }
188
205
  export function createAvowa({
189
206
  ingestKey,
190
207
  ingestSecret,
@@ -198,13 +215,16 @@ export function createAvowa({
198
215
  track: (meta, fn) => fn(),
199
216
  instrumentOpenAI: c => c,
200
217
  instrumentAnthropic: c => c,
218
+ _wrapResource: () => undefined,
201
219
  disabled: true
202
220
  };
203
221
  }
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.`);
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.`);
208
228
  const MAX_INFLIGHT = 64;
209
229
  const TIMEOUT_MS = 5000;
210
230
  let inflight = 0;
@@ -253,7 +273,45 @@ export function createAvowa({
253
273
  payload.sdk_errors = kinds.reduce((n, k) => n + INTERNAL_ERRORS[k], 0);
254
274
  payload.sdk_error_kinds = kinds.sort().slice(0, 10);
255
275
  }
256
- const body = JSON.stringify(payload);
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
+ });
257
315
  const headers = {
258
316
  'Content-Type': 'application/json',
259
317
  'X-Ingest-Key': key,
@@ -261,14 +319,12 @@ export function createAvowa({
261
319
  };
262
320
  if (secret) {
263
321
  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
322
  headers['X-Avowa-Timestamp'] = ts;
266
- headers['X-Avowa-Nonce'] = nonce;
267
- headers['X-Avowa-Signature'] = await hmacHex(secret, `${ts}.${nonce}.${body}`);
323
+ headers['X-Avowa-Signature'] = await hmacHex(secret, `${ts}.${body}`);
268
324
  if (remoteOn()) headers['X-Avowa-Fields'] = REMOTE.v || 'none';
269
325
  }
270
326
  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.`);
327
+ warnOnce('inflight', `${MAX_INFLIGHT} uploads already in flight — Avowa is slow or unreachable, so signals are being dropped. Your app is unaffected.`);
272
328
  return null;
273
329
  }
274
330
  inflight++;
@@ -276,7 +332,7 @@ export function createAvowa({
276
332
  const timer = setTimeout(() => ctl.abort(), TIMEOUT_MS);
277
333
  if (timer && typeof timer.unref === 'function') timer.unref();
278
334
  try {
279
- const r = await fetch(base + '/ingest/runtime', {
335
+ const r = await fetch(base + '/ingest/v1', {
280
336
  method: 'POST',
281
337
  headers,
282
338
  body,
@@ -287,7 +343,7 @@ export function createAvowa({
287
343
  const j = await r.clone().json();
288
344
  if (j && j.sdk_fields && secret && remoteOn()) await acceptFields(j.sdk_fields, secret);
289
345
  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).`);
346
+ warnOnce('latest', `@avowa/runtime ${j.sdk_latest} is available (this is ${VERSION}). Nothing is wrong — upgrade when convenient.`);
291
347
  }
292
348
  } catch {}
293
349
  }
@@ -661,9 +717,9 @@ export function createAvowa({
661
717
  } catch {}
662
718
  return stream;
663
719
  }
664
- function wrapMethod(holder, name, kind, host, opts) {
720
+ function wrapMethod(holder, name, kind, host, opts, given) {
665
721
  if (typeof holder[name] !== 'function' || holder[name]._avowa_wrapped) return;
666
- const original = holder[name].bind(holder);
722
+ const original = given || holder[name].bind(holder);
667
723
  const wrapped = function (params = {}, ...rest) {
668
724
  const start = Date.now();
669
725
  const emit = (resp, err, ttft) => {
@@ -757,11 +813,22 @@ export function createAvowa({
757
813
  if (client && client.messages) wrapMethod(client.messages, 'create', 'anthropic', host, opts);
758
814
  return client;
759
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
+ }
760
826
  return {
761
827
  capture,
762
828
  track,
763
829
  instrumentOpenAI,
764
- instrumentAnthropic
830
+ instrumentAnthropic,
831
+ _wrapResource
765
832
  };
766
833
  }
767
834
  export default createAvowa;
package/cli.js ADDED
@@ -0,0 +1,255 @@
1
+ #!/usr/bin/env node
2
+ // SPDX-License-Identifier: Apache-2.0
3
+ // Copyright 2026 Avowa, Inc.
4
+ /**
5
+ * `npx @avowa/runtime <command>` - set up and check the Runtime SDK. A setup tool, not a launcher:
6
+ * after `init` your app starts the way it always has.
7
+ *
8
+ * init <setup-token> connect this project: writes avowa.env (one line: AVOWA_TOKEN)
9
+ * init --dry-run show what init would do; changes nothing, uses no token
10
+ * status what is wired, what is covered, does the server know this key
11
+ * doctor the server check only (sends no signal)
12
+ */
13
+ import fs from 'node:fs'
14
+ import path from 'node:path'
15
+ import crypto from 'node:crypto'
16
+ import readline from 'node:readline'
17
+ import { checkedBase, makeToken, readToken, SDK_VERSION as VERSION } from './avowa-runtime.js'
18
+ import { loadEnv } from './env.js'
19
+
20
+ const REGISTER = '@avowa/runtime/register'
21
+ const USAGE = `usage: npx @avowa/runtime <command>
22
+
23
+ init <setup-token> [--api https://api.avowa.ai] [--dry-run] [--yes]
24
+ status
25
+ doctor
26
+
27
+ Generate the setup token in the Avowa console: Connections, Runtime SDK.
28
+ In production set two variables and change nothing else:
29
+ AVOWA_TOKEN=<the value in avowa.env>
30
+ NODE_OPTIONS=--import ${REGISTER}
31
+ AVOWA_DISABLE=1 switches everything off.`
32
+
33
+ // How each library is covered: "auto" needs nothing; the rest say what they need.
34
+ const LIBS = [
35
+ ['openai', 'covered automatically (OpenAI, Azure OpenAI, OpenAI-compatible hosts)'],
36
+ ['@anthropic-ai/sdk', 'covered automatically'],
37
+ ['@aws-sdk/client-bedrock-runtime', 'no wrapper yet: record calls with avowa.capture(...)'],
38
+ ['@google/genai', 'no wrapper yet: record calls with avowa.capture(...)'],
39
+ ['@google/generative-ai', 'no wrapper yet: record calls with avowa.capture(...)'],
40
+ ['ai', 'Vercel AI SDK calls providers over its own HTTP client: record calls with avowa.track(...)'],
41
+ ]
42
+ const BUNDLED = ['next', 'nuxt', '@remix-run/dev', '@sveltejs/kit']
43
+
44
+ const readPkg = () => { try { return JSON.parse(fs.readFileSync('package.json', 'utf8')) } catch { return null } }
45
+ const deps = (pkg) => ({ ...(pkg && pkg.dependencies), ...(pkg && pkg.devDependencies) })
46
+
47
+ function coverage(pkg) {
48
+ const d = deps(pkg)
49
+ const out = LIBS.filter(([n]) => n in d).map(([n, note]) => ` ${n.padEnd(18)}: ${note}`)
50
+ if (!out.length) out.push(' no AI provider library in package.json. Calls made over fetch need avowa.capture(...).')
51
+ const b = BUNDLED.filter((n) => n in d)
52
+ if (b.length) out.push(` ${b.join(', ')} bundles server code, so the preload may not see the provider SDK.\n` +
53
+ ' Keep it external to the bundle (Next.js: serverExternalPackages), or wrap the\n' +
54
+ ' client once with avowa.instrumentOpenAI(client).')
55
+ return out
56
+ }
57
+
58
+ function nodeOk() {
59
+ const [maj, min] = process.versions.node.split('.').map(Number)
60
+ return maj > 20 || (maj === 20 && min >= 6) || (maj === 18 && min >= 18) || maj === 19
61
+ }
62
+
63
+ function gitignore(dry) {
64
+ if (!fs.existsSync('.gitignore') && !fs.existsSync('.git')) return null
65
+ let lines = []
66
+ try { lines = fs.readFileSync('.gitignore', 'utf8').split(/\r?\n/) } catch { /* no file yet */ }
67
+ if (lines.some((l) => ['avowa.env', '/avowa.env', '*.env'].includes(l.trim()))) return '.gitignore : already ignores avowa.env'
68
+ if (dry) return '.gitignore : would add avowa.env'
69
+ try {
70
+ const sep = lines.length && lines[lines.length - 1] !== '' ? '\n' : ''
71
+ fs.appendFileSync('.gitignore', sep + 'avowa.env\n')
72
+ } catch { return '.gitignore : could not be updated. Add the line avowa.env yourself; the file holds a secret.' }
73
+ return '.gitignore : added avowa.env (the file holds a secret)'
74
+ }
75
+
76
+ // The scripts that start the app with plain `node`, and what each would become.
77
+ function startScripts(pkg) {
78
+ const out = []
79
+ for (const name of ['start', 'dev', 'serve']) {
80
+ const cmd = pkg && pkg.scripts && pkg.scripts[name]
81
+ if (typeof cmd !== 'string' || cmd.includes(REGISTER)) continue
82
+ const m = cmd.match(/^(\s*(?:[A-Z_]+=\S+\s+)*node\s)(.*)$/)
83
+ if (m) out.push({ name, from: cmd, to: `${m[1]}--import ${REGISTER} ${m[2]}` })
84
+ }
85
+ return out
86
+ }
87
+ const wired = (pkg) => (process.env.NODE_OPTIONS || '').includes(REGISTER) ||
88
+ Object.values((pkg && pkg.scripts) || {}).some((c) => typeof c === 'string' && c.includes(REGISTER))
89
+
90
+ function ask(question) {
91
+ if (!process.stdin.isTTY) return Promise.resolve(false)
92
+ const rl = readline.createInterface({ input: process.stdin, output: process.stdout })
93
+ return new Promise((ok) => rl.question(question + ' [y/N] ', (a) => { rl.close(); ok(/^y(es)?$/i.test(a.trim())) }))
94
+ }
95
+
96
+ async function redeem(token, api) {
97
+ const [base, problem] = checkedBase(api)
98
+ if (problem) return [null, problem.replace('AVOWA_BASE_URL', '--api') + '.']
99
+ let r
100
+ try {
101
+ r = await fetch(base + '/public/sdk/setup', { method: 'POST', body: JSON.stringify({ token }),
102
+ headers: { 'Content-Type': 'application/json', 'User-Agent': 'avowa-runtime-js (+https://avowa.ai)' },
103
+ signal: AbortSignal.timeout(15000) })
104
+ } catch (e) { return [null, `Could not reach ${base} (${e.name}). Pass --api with your Avowa API URL.`] }
105
+ if (r.status === 404) return [null, 'That setup token is invalid, expired (24h) or already used. Generate a new one in the console.']
106
+ if (!r.ok) return [null, `${base} answered HTTP ${r.status}.`]
107
+ const creds = await r.json()
108
+ if (creds.connector_id !== 'runtime_sdk') return [null, 'That token belongs to a Collector connection, not the Runtime SDK.']
109
+ const [b, p] = checkedBase(creds.base_url || base)
110
+ if (p) return [null, `The server returned an unsafe API URL (${p}); nothing was written.`]
111
+ return [{ ...creds, base_url: b }, null]
112
+ }
113
+
114
+ async function init(args) {
115
+ const dry = args.includes('--dry-run')
116
+ const yes = args.includes('--yes')
117
+ let api = (process.env.AVOWA_BASE_URL || 'https://api.avowa.ai').replace(/\/+$/, '')
118
+ const i = args.indexOf('--api')
119
+ if (i >= 0) {
120
+ if (!args[i + 1]) { console.error('--api needs a URL'); return 2 }
121
+ api = args[i + 1].replace(/\/+$/, ''); args = [...args.slice(0, i), ...args.slice(i + 2)]
122
+ }
123
+ const words = args.filter((a) => !a.startsWith('-'))
124
+ const file = path.join(process.cwd(), 'avowa.env')
125
+ const pkg = readPkg()
126
+ const scripts = startScripts(pkg)
127
+ const dep = pkg && !('@avowa/runtime' in deps(pkg)) ? 'dependency : run `npm install @avowa/runtime` so your build installs it too' : null
128
+ const node = nodeOk() ? null : `node : ${process.versions.node} has no --import flag (needs 18.18+ or 20.6+). Wrap the client with avowa.instrumentOpenAI(client) instead.`
129
+
130
+ if (dry) {
131
+ console.log('npx @avowa/runtime init --dry-run: nothing is changed and no setup token is used.\n')
132
+ console.log(`credentials : would write ${file} (mode 0600, one line: AVOWA_TOKEN)`)
133
+ for (const l of [gitignore(true), dep, node]) if (l) console.log(l)
134
+ for (const s of scripts) console.log(`package.json : would offer to change "${s.name}"\n from: ${s.from}\n to: ${s.to}`)
135
+ console.log('coverage from package.json:'); console.log(coverage(pkg).join('\n'))
136
+ return 0
137
+ }
138
+ if (!words.length) { console.error(USAGE); return 2 }
139
+ const [, unsafe] = checkedBase(api)
140
+ if (unsafe) { console.error(unsafe.replace('AVOWA_BASE_URL', '--api') + '.'); return 2 }
141
+ const [creds, problem] = await redeem(words[0], api)
142
+ if (problem) { console.error(problem); return 1 }
143
+ const token = makeToken(creds.ingest_token, creds.ingest_secret || '', creds.base_url)
144
+ fs.writeFileSync(file,
145
+ '# Avowa Runtime SDK: the credential for this connection. Keep private, server-side only.\n' +
146
+ '# Written by `npx @avowa/runtime init`. Read from the directory you start your app in.\n' +
147
+ '# In production, put this one value in your secret store as AVOWA_TOKEN instead.\n' +
148
+ `AVOWA_TOKEN=${token}\n`, { mode: 0o600 })
149
+ try { fs.chmodSync(file, 0o600) } catch { /* Windows */ }
150
+ console.log(`connected : ${creds.label || 'Avowa Runtime SDK'} (${creds.environment || 'prod'})`)
151
+ console.log(`credentials : ${file} (mode 0600, one line: AVOWA_TOKEN)`)
152
+ for (const l of [gitignore(false), dep, node]) if (l) console.log(l)
153
+
154
+ let changed = false
155
+ for (const s of scripts) {
156
+ console.log(`package.json : "${s.name}" can load Avowa before your app:\n from: ${s.from}\n to: ${s.to}`)
157
+ if (yes || await ask(' Make this change?')) {
158
+ const raw = fs.readFileSync('package.json', 'utf8')
159
+ const next = raw.replace(JSON.stringify(s.from), JSON.stringify(s.to))
160
+ if (next !== raw) { fs.writeFileSync('package.json', next); changed = true; console.log(' changed') }
161
+ } else console.log(' left as it is')
162
+ }
163
+ console.log('coverage from package.json:'); console.log(coverage(pkg).join('\n'))
164
+ console.log(await reportSetup(creds.ingest_token, creds.ingest_secret || '', creds.base_url, readPkg(), wired(readPkg())))
165
+ console.log('\nDone.' + (changed ? ' Start your app the way you always do' : ` Start your app with NODE_OPTIONS="--import ${REGISTER}" set`) +
166
+ ', then send one real request that calls the model.\n' +
167
+ ' check : npx @avowa/runtime status\n' +
168
+ ` production : set AVOWA_TOKEN (the value in avowa.env) and NODE_OPTIONS=--import ${REGISTER}. Nothing else changes.\n` +
169
+ ' off switch : AVOWA_DISABLE=1')
170
+ return 0
171
+ }
172
+
173
+ // Tell the server how the install stands, so the console's checklist can tick: the key and secret
174
+ // verify, which covered libraries package.json names, whether the preload is wired. The same
175
+ // signed whoami the doctor makes, with one extra header. No signal is sent.
176
+ async function reportSetup(key, secret, base, pkg, isWired) {
177
+ const d = deps(pkg)
178
+ const covered = ['openai', '@anthropic-ai/sdk'].filter((n) => n in d)
179
+ const ts = String(Math.floor(Date.now() / 1000))
180
+ const headers = { 'X-Ingest-Key': key, 'X-Avowa-Timestamp': ts,
181
+ 'X-Avowa-Signature': crypto.createHmac('sha256', secret || '').update(ts + '.').digest('hex'),
182
+ 'X-Avowa-Setup': `wired=${isWired ? 1 : 0}; covered=${covered.join(',')}`,
183
+ 'User-Agent': `avowa-runtime-js/${VERSION} (+https://avowa.ai)` }
184
+ try {
185
+ const r = await fetch(base + '/ingest/whoami', { headers, signal: AbortSignal.timeout(8000) })
186
+ if (!r.ok) return `server check : could not confirm (HTTP ${r.status}). Run \`npx @avowa/runtime status\` to see why.`
187
+ const who = await r.json()
188
+ if (!who.signature_ok) return 'server check : the secret did NOT verify. Run `npx @avowa/runtime status`.'
189
+ if (!who.capture_allowed) return "server check : key accepted, but this workspace's plan does not allow capture yet"
190
+ return 'server check : key and signature accepted (your console card now shows this step done)'
191
+ } catch (e) { return `server check : could not confirm (${e.name}). Run \`npx @avowa/runtime status\` to see why.` }
192
+ }
193
+
194
+ // Asks the server who this key is. Sends no signal: a synthetic one would show on the trust
195
+ // profile as inference that never happened.
196
+ async function doctor() {
197
+ const found = loadEnv()
198
+ const tok = process.env.AVOWA_TOKEN ? readToken(process.env.AVOWA_TOKEN) : null
199
+ const key = process.env.AVOWA_RUNTIME_KEY || (tok && tok[0])
200
+ const secret = process.env.AVOWA_RUNTIME_SECRET || (tok && tok[1])
201
+ const [base, problem] = checkedBase(process.env.AVOWA_BASE_URL || (tok && tok[2]) || undefined)
202
+ console.log(`env file : ${found || 'not found'}`)
203
+ if (process.env.AVOWA_TOKEN && !tok) { console.log('token : AVOWA_TOKEN is not a valid Avowa token (one starts with avw1_)'); return 1 }
204
+ if (problem) { console.log('api : ' + problem); return 1 }
205
+ console.log('api : ' + base)
206
+ if (!key) { console.log('credential : MISSING. Run `npx @avowa/runtime init <setup-token>` or set AVOWA_TOKEN'); return 1 }
207
+ const ts = String(Math.floor(Date.now() / 1000))
208
+ const headers = { 'X-Ingest-Key': key, 'X-Avowa-Timestamp': ts, 'User-Agent': `avowa-runtime-js/${VERSION} (+https://avowa.ai)` }
209
+ if (secret) headers['X-Avowa-Signature'] = crypto.createHmac('sha256', secret).update(ts + '.').digest('hex')
210
+ let who
211
+ try {
212
+ const r = await fetch(base + '/ingest/whoami', { headers, signal: AbortSignal.timeout(8000) })
213
+ if (r.status === 401) { console.log(`credential : REJECTED by ${base}. Not a key this server knows (rotated or revoked?)`); return 1 }
214
+ if (!r.ok) { console.log(`api : ${base} answered HTTP ${r.status}`); return 1 }
215
+ who = await r.json()
216
+ } catch (e) { console.log(`api : NOT reachable from this host (${e.name})`); return 1 }
217
+ let ok = true
218
+ console.log(`connection : ${who.label || who.connection_id} · ${who.environment}`)
219
+ if (who.capture_allowed) console.log('plan : capture allowed')
220
+ else { console.log('plan : capture NOT allowed. The workspace is on Declare; signals will get 402'); ok = false }
221
+ if (!secret) { console.log('secret : not set. Signals would be sent unsigned and refused'); ok = false }
222
+ else if (who.signature_ok) console.log('secret : signs correctly')
223
+ else { console.log('secret : does NOT verify. Every signal would get 401'); ok = false }
224
+ if (typeof who.clock_skew_s === 'number') {
225
+ const s = who.clock_skew_s
226
+ console.log(`clock : ${s >= 0 ? '+' : ''}${Math.round(s)}s vs server${Math.abs(s) < 120 ? '' : '. Over 5 minutes is rejected; fix NTP'}`)
227
+ ok = ok && Math.abs(s) < 300
228
+ }
229
+ console.log(`last event : ${who.last_event_at || 'never'} (${who.events_total || 0} total)`)
230
+ console.log('\nNo signal was sent.' + (ok ? '' : ' Fix the lines marked above, then run again.'))
231
+ return ok ? 0 : 1
232
+ }
233
+
234
+ async function status() {
235
+ const pkg = readPkg()
236
+ console.log(`node : ${process.versions.node}${nodeOk() ? '' : ' (no --import flag: needs 18.18+ or 20.6+)'}`)
237
+ console.log(`preload : ${wired(pkg) ? 'wired (' + REGISTER + ')' : 'NOT wired. Set NODE_OPTIONS="--import ' + REGISTER + '" or run init'}`)
238
+ console.log('coverage from package.json:'); console.log(coverage(pkg).join('\n'))
239
+ loadEnv()
240
+ const tok = process.env.AVOWA_TOKEN ? readToken(process.env.AVOWA_TOKEN) : null
241
+ const key = process.env.AVOWA_RUNTIME_KEY || (tok && tok[0])
242
+ const secret = process.env.AVOWA_RUNTIME_SECRET || (tok && tok[1])
243
+ const [base] = checkedBase(process.env.AVOWA_BASE_URL || (tok && tok[2]) || undefined)
244
+ if (key && secret && base) await reportSetup(key, secret, base, pkg, wired(pkg)) // refreshes the console checklist
245
+ console.log('server check:')
246
+ return doctor()
247
+ }
248
+
249
+ const [cmd, ...rest] = process.argv.slice(2)
250
+ let code
251
+ if (cmd === 'init') code = await init(rest)
252
+ else if (cmd === 'status') code = await status()
253
+ else if (cmd === 'doctor') code = await doctor()
254
+ else { console.error(USAGE); code = cmd && !['-h', '--help', 'help'].includes(cmd) ? 2 : (cmd ? 0 : 2) }
255
+ process.exitCode = code
package/env.js ADDED
@@ -0,0 +1,42 @@
1
+ // SPDX-License-Identifier: Apache-2.0
2
+ // Copyright 2026 Avowa, Inc.
3
+ import fs from 'node:fs';
4
+ import path from 'node:path';
5
+ const on = v => ['1', 'true', 'yes', 'on'].includes(String(v || '').trim().toLowerCase());
6
+ export function loadEnv(file) {
7
+ if (on(process.env.AVOWA_NO_ENV_FILE)) return null;
8
+ const candidates = [];
9
+ const explicit = file || process.env.AVOWA_ENV_FILE;
10
+ if (explicit) candidates.push(explicit);else {
11
+ let d = process.cwd();
12
+ for (let i = 0; i < 3; i++) {
13
+ candidates.push(path.join(d, 'avowa.env'), path.join(d, '.env'));
14
+ const parent = path.dirname(d);
15
+ if (parent === d) break;
16
+ d = parent;
17
+ }
18
+ }
19
+ for (const cand of candidates) {
20
+ let text;
21
+ try {
22
+ text = fs.readFileSync(cand, 'utf8');
23
+ } catch {
24
+ continue;
25
+ }
26
+ let found = false;
27
+ for (let line of text.split(/\r?\n/)) {
28
+ line = line.trim();
29
+ if (!line || line.startsWith('#')) continue;
30
+ if (line.startsWith('export ')) line = line.slice(7).trimStart();
31
+ const i = line.indexOf('=');
32
+ if (i < 1) continue;
33
+ const key = line.slice(0, i).trim();
34
+ if (!key.startsWith('AVOWA_')) continue;
35
+ const val = line.slice(i + 1).trim().replace(/^["']|["']$/g, '');
36
+ found = true;
37
+ if (process.env[key] === undefined) process.env[key] = val;
38
+ }
39
+ if (found) return cand;
40
+ }
41
+ return null;
42
+ }
package/package.json CHANGED
@@ -1,14 +1,19 @@
1
1
  {
2
2
  "name": "@avowa/runtime",
3
- "version": "0.11.0",
4
- "description": "Avowa Runtime SDK — emit live AI-inference signals as observed evidence. Metadata only; never prompts or completions.",
3
+ "version": "0.12.0",
4
+ "description": "Avowa Runtime SDK \u2014 emit live AI-inference signals as observed evidence. Metadata only; never prompts or completions.",
5
5
  "type": "module",
6
6
  "main": "avowa-runtime.js",
7
7
  "exports": {
8
- ".": "./avowa-runtime.js"
8
+ ".": "./avowa-runtime.js",
9
+ "./register": "./register.js",
10
+ "./env": "./env.js"
9
11
  },
10
12
  "files": [
11
13
  "avowa-runtime.js",
14
+ "register.js",
15
+ "env.js",
16
+ "cli.js",
12
17
  "README.md",
13
18
  "LICENSE",
14
19
  "NOTICE"
@@ -38,5 +43,8 @@
38
43
  },
39
44
  "bugs": {
40
45
  "url": "https://github.com/Avowa-AI/avowa-runtime-sdk/issues"
46
+ },
47
+ "bin": {
48
+ "avowa": "cli.js"
41
49
  }
42
50
  }
package/register.js ADDED
@@ -0,0 +1,130 @@
1
+ // SPDX-License-Identifier: Apache-2.0
2
+ // Copyright 2026 Avowa, Inc.
3
+ import fs from 'node:fs';
4
+ import path from 'node:path';
5
+ import { createRequire } from 'node:module';
6
+ import { pathToFileURL } from 'node:url';
7
+ import { createAvowa } from './avowa-runtime.js';
8
+ import { loadEnv } from './env.js';
9
+ const on = v => ['1', 'true', 'yes', 'on'].includes(String(v || '').trim().toLowerCase());
10
+ const debug = msg => {
11
+ if (on(process.env.AVOWA_DEBUG)) console.error('[avowa:debug] ' + msg);
12
+ };
13
+ const TARGETS = {
14
+ 'openai': {
15
+ kind: 'openai',
16
+ root: 'OpenAI',
17
+ methods: [['Chat', 'Completions', 'create'], ['Responses', 'create']]
18
+ },
19
+ '@anthropic-ai/sdk': {
20
+ kind: 'anthropic',
21
+ root: 'Anthropic',
22
+ methods: [['Messages', 'create']]
23
+ }
24
+ };
25
+ export const instrumented = [];
26
+ let avowa = null;
27
+ function patchModule(name, mod, flavour) {
28
+ const t = TARGETS[name];
29
+ if (!t || !mod || !avowa) return;
30
+ const root = mod[t.root] || mod.default && (mod.default[t.root] || mod.default);
31
+ if (typeof root !== 'function') return;
32
+ for (const p of t.methods) {
33
+ const method = p[p.length - 1];
34
+ let cls = root;
35
+ for (const seg of p.slice(0, -1)) cls = cls && cls[seg];
36
+ const proto = cls && cls.prototype;
37
+ if (!proto || typeof proto[method] !== 'function' || proto[method]._avowa_class_patch) continue;
38
+ const original = proto[method];
39
+ const shim = function (...args) {
40
+ try {
41
+ const own = Object.prototype.hasOwnProperty.call(this, method) ? this[method] : null;
42
+ if (own && own._avowa_wrapped) return original.apply(this, args);
43
+ avowa._wrapResource(this, method, t.kind, original);
44
+ const wrapped = Object.prototype.hasOwnProperty.call(this, method) ? this[method] : null;
45
+ if (wrapped && wrapped._avowa_wrapped) return wrapped.apply(this, args);
46
+ } catch {}
47
+ return original.apply(this, args);
48
+ };
49
+ shim._avowa_class_patch = true;
50
+ try {
51
+ proto[method] = shim;
52
+ const label = `${name} ${p.join('.')} (${flavour})`;
53
+ instrumented.push(label);
54
+ debug('patched ' + label);
55
+ } catch {}
56
+ }
57
+ }
58
+ function esmEntry(cjsEntry, name) {
59
+ let dir = path.dirname(cjsEntry);
60
+ for (let i = 0; i < 6; i++) {
61
+ const pj = path.join(dir, 'package.json');
62
+ if (fs.existsSync(pj)) {
63
+ let pkg;
64
+ try {
65
+ pkg = JSON.parse(fs.readFileSync(pj, 'utf8'));
66
+ } catch {
67
+ return null;
68
+ }
69
+ if (pkg.name !== name) {
70
+ dir = path.dirname(dir);
71
+ continue;
72
+ }
73
+ const pick = e => {
74
+ if (typeof e === 'string') return e;
75
+ if (!e || typeof e !== 'object') return null;
76
+ return pick(e.import) || pick(e.default);
77
+ };
78
+ const dot = pkg.exports && (pkg.exports['.'] !== undefined ? pkg.exports['.'] : pkg.exports);
79
+ const rel = pick(dot) || pkg.module;
80
+ return rel ? path.join(dir, rel) : null;
81
+ }
82
+ dir = path.dirname(dir);
83
+ }
84
+ return null;
85
+ }
86
+ async function install() {
87
+ if (on(process.env.AVOWA_DISABLE)) {
88
+ debug('AVOWA_DISABLE is set: nothing is patched');
89
+ return;
90
+ }
91
+ const found = loadEnv();
92
+ avowa = createAvowa({
93
+ region: process.env.AVOWA_REGION
94
+ });
95
+ debug(`@avowa/runtime/register active · env file ${found || 'none'}`);
96
+ const nodeModule = createRequire(import.meta.url)('node:module');
97
+ const load = nodeModule._load;
98
+ nodeModule._load = function (request) {
99
+ const exp = load.apply(this, arguments);
100
+ if (Object.prototype.hasOwnProperty.call(TARGETS, request)) {
101
+ try {
102
+ patchModule(request, exp, 'require');
103
+ } catch {}
104
+ }
105
+ return exp;
106
+ };
107
+ const roots = [];
108
+ if (process.argv[1]) roots.push(path.dirname(path.resolve(process.argv[1])));
109
+ roots.push(process.cwd());
110
+ for (const name of Object.keys(TARGETS)) {
111
+ for (const root of roots) {
112
+ let cjs;
113
+ try {
114
+ cjs = createRequire(path.join(root, 'noop.js')).resolve(name);
115
+ } catch {
116
+ continue;
117
+ }
118
+ const esm = esmEntry(cjs, name);
119
+ if (esm && esm !== cjs && fs.existsSync(esm)) {
120
+ try {
121
+ patchModule(name, await import(pathToFileURL(esm).href), 'import');
122
+ } catch {}
123
+ }
124
+ break;
125
+ }
126
+ }
127
+ }
128
+ try {
129
+ await install();
130
+ } catch {}