@avowa/runtime 0.11.0 → 0.13.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
+
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:
29
+
30
+ ```bash
31
+ AVOWA_TOKEN=avw1_... # the value in avowa.env
32
+ NODE_OPTIONS=--import @avowa/runtime/register # any start command, Docker, Kubernetes
8
33
  ```
9
34
 
10
- One dependency-free file, Apache-2.0. (It is also in your Avowa SDK download, if you would rather vendor it.)
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
 
@@ -38,13 +87,40 @@ request signed and single-use, and `AVOWA_DISABLE=1` turns it off entirely.
38
87
 
39
88
  Licence: Apache-2.0.
40
89
 
90
+ ## Agents: approvals, outcomes and who ran it (0.13)
91
+
92
+ The wrappers read each tool call the model proposed and each result your app handed back, by a hash
93
+ of the provider's call id (the id never leaves your process), plus the run key and step depth, the
94
+ same as the Python SDK. A human approval or a tool's outcome happens after the call, so record it on
95
+ its own:
96
+
97
+ ```js
98
+ import { approval, toolOutcome, agentContext } from '@avowa/runtime'
99
+
100
+ await agentContext({ name: 'triage', customer: account.id }, async () => {
101
+ const resp = await client.messages.create({ ... })
102
+ for (const b of resp.content) {
103
+ if (b.type === 'tool_use' && needsSignOff(b)) {
104
+ approval(b.id, await askAHuman(b), 'finance_ops', { approverType: 'human' }) // a role label, never a name
105
+ toolOutcome(b.id, 'ok') // or 'error', 'denied', 'timeout'
106
+ }
107
+ }
108
+ })
109
+ ```
110
+
111
+ `approverType` is `'human'`, `'policy'` (with `policyRef`), `'system'` or `'unknown'` (the default); only
112
+ `'human'` counts as human approval, and Avowa does not claim the decision came before the tool ran.
113
+ Call references are 20 hex characters of a hash of the provider's id: a correlation label, not
114
+ anonymisation. The customer id is sent only as a keyed hash; set `AVOWA_REF_KEY` (read only in your
115
+ process, never sent) and nobody else can test a guess. Rotating it starts a new correlation period.
116
+
41
117
  ## Wrap your client (observed, not asserted)
42
118
 
43
119
  ```js
44
120
  import OpenAI from 'openai'
45
121
  import { createAvowa } from '@avowa/runtime'
46
122
 
47
- const avowa = createAvowa() // AVOWA_RUNTIME_KEY / _SECRET / AVOWA_BASE_URL from the env
123
+ const avowa = createAvowa() // AVOWA_TOKEN from the env
48
124
  const openai = avowa.instrumentOpenAI(new OpenAI()) // chat.completions.create, responses.create — streams included
49
125
  // const anthropic = avowa.instrumentAnthropic(new Anthropic()) // messages.create — streams included
50
126
  ```
package/avowa-runtime.js CHANGED
@@ -1,7 +1,11 @@
1
1
  // SPDX-License-Identifier: Apache-2.0
2
2
  // Copyright 2026 Avowa, Inc.
3
+ import { createHash, createHmac } from 'node:crypto';
4
+ import { AsyncLocalStorage } from 'node:async_hooks';
3
5
  const env = typeof process !== 'undefined' && process.env || {};
4
- const VERSION = '0.11.0';
6
+ const VERSION = '0.13.0';
7
+ const SCHEMA = 'avowa.signal/1';
8
+ export const SDK_VERSION = VERSION;
5
9
  let _subtle = null;
6
10
  async function subtle() {
7
11
  if (_subtle) return _subtle;
@@ -185,6 +189,175 @@ export function hostOf(url) {
185
189
  return null;
186
190
  }
187
191
  }
192
+ const TOKEN_PREFIX = 'avw1_';
193
+ export function makeToken(key, secret, baseUrl) {
194
+ const raw = [key || '', secret || '', String(baseUrl || '').replace(/\/+$/, '')].join('\n');
195
+ return TOKEN_PREFIX + btoa(raw).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '');
196
+ }
197
+ export function readToken(token) {
198
+ token = String(token || '').trim();
199
+ if (!token.startsWith(TOKEN_PREFIX)) return null;
200
+ try {
201
+ const parts = atob(token.slice(TOKEN_PREFIX.length).replace(/-/g, '+').replace(/_/g, '/')).split('\n');
202
+ return parts.length === 3 && parts[0] ? parts : null;
203
+ } catch {
204
+ return null;
205
+ }
206
+ }
207
+ export const TOOL_OUTCOMES = ['ok', 'error', 'denied', 'timeout'];
208
+ export const APPROVER_TYPES = ['human', 'policy', 'system', 'unknown'];
209
+ const CALL_REF_LEN = 20;
210
+ const TOOL_CAP = 60;
211
+ const LABEL_RX = /^[A-Za-z0-9 _.:/-]{1,64}$/;
212
+ export function callRef(id) {
213
+ if (id === undefined || id === null || id === '') return null;
214
+ return createHash('sha256').update('avowa-call:' + String(id)).digest('hex').slice(0, CALL_REF_LEN);
215
+ }
216
+ const g = (o, k) => o === null || o === undefined ? undefined : o[k];
217
+ function toolCalls(resp) {
218
+ const out = [];
219
+ const add = (id, name) => {
220
+ const r = callRef(id);
221
+ if (r && name) out.push(r + ':' + String(name).slice(0, 64));
222
+ };
223
+ try {
224
+ for (const b of g(resp, 'content') || []) if (g(b, 'type') === 'tool_use') add(g(b, 'id'), g(b, 'name'));
225
+ const msg = g(g(g(resp, 'choices'), 0), 'message');
226
+ for (const tc of g(msg, 'tool_calls') || []) add(g(tc, 'id'), g(g(tc, 'function'), 'name') || g(tc, 'name'));
227
+ for (const it of Array.isArray(g(resp, 'output')) ? resp.output : []) {
228
+ if (['function_call', 'custom_tool_call'].includes(g(it, 'type'))) add(g(it, 'call_id') || g(it, 'id'), g(it, 'name'));
229
+ }
230
+ } catch {}
231
+ return out.slice(0, TOOL_CAP);
232
+ }
233
+ function toolResults(history) {
234
+ if (!Array.isArray(history)) return [];
235
+ let fresh = [];
236
+ for (const m of history) {
237
+ const role = g(m, 'role'),
238
+ typ = g(m, 'type');
239
+ if (role === 'assistant' || typ === 'function_call' || typ === 'custom_tool_call') {
240
+ fresh = [];
241
+ continue;
242
+ }
243
+ if (role === 'tool') {
244
+ const r = callRef(g(m, 'tool_call_id'));
245
+ if (r) fresh.push(r + ':returned');
246
+ continue;
247
+ }
248
+ if (typ === 'function_call_output' || typ === 'custom_tool_call_output') {
249
+ const r = callRef(g(m, 'call_id'));
250
+ if (r) fresh.push(r + ':returned');
251
+ continue;
252
+ }
253
+ const c = g(m, 'content');
254
+ if (Array.isArray(c)) {
255
+ for (const b of c) {
256
+ if (g(b, 'type') === 'tool_result') {
257
+ const r = callRef(g(b, 'tool_use_id'));
258
+ if (r) fresh.push(r + (g(b, 'is_error') === true ? ':error' : ':returned'));
259
+ }
260
+ }
261
+ }
262
+ }
263
+ return fresh.slice(0, TOOL_CAP);
264
+ }
265
+ function mcpFacts(params, resp) {
266
+ const f = {},
267
+ labels = [],
268
+ hosts = [],
269
+ ran = [],
270
+ hostOfLabel = {};
271
+ const note = (lb, h) => {
272
+ if (lb) labels.push(String(lb).slice(0, 64));
273
+ if (h) {
274
+ hosts.push(h);
275
+ if (lb) hostOfLabel[String(lb).slice(0, 64)] = h;
276
+ }
277
+ };
278
+ try {
279
+ for (const s of g(params, 'mcp_servers') || []) note(g(s, 'name'), hostOf(g(s, 'url')));
280
+ for (const t of g(params, 'tools') || []) {
281
+ if (g(t, 'type') === 'mcp') note(g(t, 'server_label'), hostOf(g(t, 'server_url')));
282
+ }
283
+ for (const b of g(resp, 'content') || []) {
284
+ if (g(b, 'type') === 'mcp_tool_use' && g(b, 'name')) ran.push(String(g(b, 'server_name') || '?').slice(0, 64) + '/' + String(b.name).slice(0, 64));
285
+ }
286
+ for (const it of Array.isArray(g(resp, 'output')) ? resp.output : []) {
287
+ if (g(it, 'type') === 'mcp_call' && g(it, 'name')) ran.push(String(g(it, 'server_label') || '?').slice(0, 64) + '/' + String(it.name).slice(0, 64));
288
+ }
289
+ } catch {}
290
+ const uniq = a => [...new Set(a)].sort().slice(0, TOOL_CAP);
291
+ if (labels.length) f.mcp_servers_offered = uniq(labels);
292
+ if (hosts.length) f.mcp_hosts = uniq(hosts);
293
+ if (labels.length || ran.length) {
294
+ f.mcp_tools_invoked = uniq(ran);
295
+ f.mcp_hosts_invoked = uniq(ran.map(r => hostOfLabel[r.split('/')[0]]).filter(Boolean));
296
+ }
297
+ return f;
298
+ }
299
+ function runKey(messages, secret) {
300
+ if (!Array.isArray(messages)) return null;
301
+ for (const m of messages) {
302
+ if (g(m, 'role') !== 'user') continue;
303
+ let c = g(m, 'content');
304
+ if (Array.isArray(c)) c = c.map(b => b && typeof b === 'object' ? String(b.text || b.content || '') : '').join('');
305
+ c = String(c || '').trim();
306
+ if (!c) continue;
307
+ return (secret ? createHmac('sha256', String(secret)).update(c) : createHash('sha256').update(c)).digest('hex').slice(0, 12);
308
+ }
309
+ return null;
310
+ }
311
+ function autonomyDepth(messages) {
312
+ if (!Array.isArray(messages)) return null;
313
+ let d = 0;
314
+ for (const m of messages) {
315
+ if (g(m, 'role') !== 'assistant') continue;
316
+ if (Array.isArray(g(m, 'tool_calls')) && m.tool_calls.length) {
317
+ d++;
318
+ continue;
319
+ }
320
+ const c = g(m, 'content');
321
+ if (Array.isArray(c) && c.some(b => g(b, 'type') === 'tool_use')) d++;
322
+ }
323
+ return d;
324
+ }
325
+ const AGENT = new AsyncLocalStorage();
326
+ export function agentContext({
327
+ name,
328
+ customer
329
+ } = {}, fn) {
330
+ let nm = name === undefined || name === null ? null : String(name).slice(0, 64);
331
+ if (nm !== null && !LABEL_RX.test(nm)) {
332
+ warnOnce('agentname', 'agentContext name must be letters, digits and _ . : / - (64 at most); the name was not recorded.');
333
+ nm = null;
334
+ }
335
+ return AGENT.run({
336
+ name: nm,
337
+ customer: customer === undefined || customer === null ? null : String(customer)
338
+ }, fn);
339
+ }
340
+ function customerRef(secret, customer) {
341
+ if (customer === undefined || customer === null || customer === '') return null;
342
+ const key = env.AVOWA_REF_KEY || secret;
343
+ if (!key) return null;
344
+ return createHmac('sha256', String(key)).update('avowa-customer:' + String(customer)).digest('hex').slice(0, 12);
345
+ }
346
+ let DEFAULT = null;
347
+ export function approval(callId, approved, approverRole, opts = {}) {
348
+ if (!DEFAULT) {
349
+ warnOnce('noruntime', 'approval() was called but no Avowa runtime is running; nothing was recorded.');
350
+ return Promise.resolve(null);
351
+ }
352
+ return DEFAULT.approval(callId, approved, approverRole, opts);
353
+ }
354
+ export function toolOutcome(callId, outcome) {
355
+ if (!DEFAULT) {
356
+ warnOnce('noruntime', 'toolOutcome() was called but no Avowa runtime is running; nothing was recorded.');
357
+ return Promise.resolve(null);
358
+ }
359
+ return DEFAULT.toolOutcome(callId, outcome);
360
+ }
188
361
  export function createAvowa({
189
362
  ingestKey,
190
363
  ingestSecret,
@@ -198,13 +371,18 @@ export function createAvowa({
198
371
  track: (meta, fn) => fn(),
199
372
  instrumentOpenAI: c => c,
200
373
  instrumentAnthropic: c => c,
374
+ _wrapResource: () => undefined,
375
+ approval: noop,
376
+ toolOutcome: noop,
201
377
  disabled: true
202
378
  };
203
379
  }
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.`);
380
+ const tok = env.AVOWA_TOKEN ? readToken(env.AVOWA_TOKEN) : null;
381
+ 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.');
382
+ const key = ingestKey || env.AVOWA_RUNTIME_KEY || tok && tok[0] || undefined;
383
+ const secret = ingestSecret || env.AVOWA_RUNTIME_SECRET || tok && tok[1] || undefined;
384
+ const [base, baseProblem] = checkedBase(baseUrl || env.AVOWA_BASE_URL || tok && tok[2] || undefined);
385
+ 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
386
  const MAX_INFLIGHT = 64;
209
387
  const TIMEOUT_MS = 5000;
210
388
  let inflight = 0;
@@ -227,9 +405,14 @@ export function createAvowa({
227
405
  if (evt.guardrail_blocked !== undefined && evt.guardrail_blocked !== null) {
228
406
  payload.guardrail_blocked = !!evt.guardrail_blocked;
229
407
  }
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']) {
408
+ 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', 'tool_calls', 'tool_results', 'mcp_servers_offered', 'mcp_tools_invoked', 'mcp_hosts', 'mcp_hosts_invoked']) {
231
409
  if (evt[k] !== undefined && evt[k] !== null) payload[k] = evt[k];
232
410
  }
411
+ const ctx = AGENT.getStore() || {};
412
+ const name = evt.agent_name !== undefined && evt.agent_name !== null ? String(evt.agent_name).slice(0, 64) : ctx.name;
413
+ if (name) payload.agent_name = name;
414
+ const cref = customerRef(secret, evt.customer !== undefined && evt.customer !== null ? evt.customer : ctx.customer);
415
+ if (cref) payload.customer_ref = cref;
233
416
  if (evt.endpoint) payload.endpoint = hostOf(evt.endpoint);
234
417
  const scanP = evt.scanPrompt !== undefined && evt.scanPrompt !== null ? cap(evt.scanPrompt, 'tail') : null;
235
418
  const scanO = evt.scanOutput !== undefined && evt.scanOutput !== null ? cap(evt.scanOutput, 'head') : null;
@@ -253,7 +436,94 @@ export function createAvowa({
253
436
  payload.sdk_errors = kinds.reduce((n, k) => n + INTERNAL_ERRORS[k], 0);
254
437
  payload.sdk_error_kinds = kinds.sort().slice(0, 10);
255
438
  }
256
- const body = JSON.stringify(payload);
439
+ return enqueue(payload);
440
+ }
441
+ const BATCH_MAX = 100;
442
+ const BATCH_WAIT_MS = 20;
443
+ let pending = [];
444
+ let pendingTimer = null;
445
+ function enqueue(payload) {
446
+ return new Promise((resolve, reject) => {
447
+ pending.push({
448
+ payload,
449
+ resolve,
450
+ reject
451
+ });
452
+ if (pending.length >= BATCH_MAX) flushPending();else if (!pendingTimer) pendingTimer = setTimeout(flushPending, BATCH_WAIT_MS);
453
+ });
454
+ }
455
+ function flushPending() {
456
+ if (pendingTimer) {
457
+ clearTimeout(pendingTimer);
458
+ pendingTimer = null;
459
+ }
460
+ const batch = pending.splice(0, BATCH_MAX);
461
+ if (pending.length) pendingTimer = setTimeout(flushPending, BATCH_WAIT_MS);
462
+ if (!batch.length) return;
463
+ sendEnvelope(batch.filter(b => !b.payload._annotation).map(b => b.payload), batch.filter(b => b.payload._annotation).map(b => b.payload._annotation)).then(r => batch.forEach(b => b.resolve(r)), e => batch.forEach(b => b.reject(e)));
464
+ }
465
+ function annotate(ann) {
466
+ if (!key || !base) return Promise.resolve(null);
467
+ return enqueue({
468
+ _annotation: ann
469
+ }).catch(e => {
470
+ internalError('annotate', e);
471
+ return null;
472
+ });
473
+ }
474
+ const nowIso = () => new Date().toISOString().replace(/\.\d{3}Z$/, 'Z');
475
+ function approval(callId, approved, approverRole, {
476
+ approverType = 'unknown',
477
+ policyRef
478
+ } = {}) {
479
+ const ref = callRef(callId);
480
+ if (!ref) return Promise.resolve(null);
481
+ if (!APPROVER_TYPES.includes(approverType)) {
482
+ warnOnce('approvertype', `approval() approverType must be one of ${APPROVER_TYPES.join(', ')}; recorded as unknown.`);
483
+ approverType = 'unknown';
484
+ }
485
+ const ann = {
486
+ type: 'approval',
487
+ tool_call_ref: ref,
488
+ approved: !!approved,
489
+ approver_type: approverType,
490
+ at: nowIso()
491
+ };
492
+ const role = approverRole === undefined || approverRole === null ? null : String(approverRole).slice(0, 40);
493
+ if (role && LABEL_RX.test(role)) ann.approver_role = role;
494
+ const pol = policyRef === undefined || policyRef === null ? null : String(policyRef).slice(0, 64);
495
+ if (pol && LABEL_RX.test(pol)) ann.policy_ref = pol;
496
+ return annotate(ann);
497
+ }
498
+ function toolOutcome(callId, outcome) {
499
+ const ref = callRef(callId);
500
+ if (!ref) return Promise.resolve(null);
501
+ if (!TOOL_OUTCOMES.includes(outcome)) {
502
+ warnOnce('outcome', `toolOutcome() takes one of ${TOOL_OUTCOMES.join(', ')}; that outcome was not recorded.`);
503
+ return Promise.resolve(null);
504
+ }
505
+ return annotate({
506
+ type: 'outcome',
507
+ tool_call_ref: ref,
508
+ outcome,
509
+ at: nowIso()
510
+ });
511
+ }
512
+ async function sendEnvelope(events, annotations = []) {
513
+ 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('');
514
+ const envelope = {
515
+ schema: SCHEMA,
516
+ source: {
517
+ kind: 'runtime',
518
+ client: 'avowa-runtime-js',
519
+ version: VERSION
520
+ },
521
+ sent_at: new Date().toISOString().replace(/\.\d{3}Z$/, 'Z'),
522
+ nonce,
523
+ events
524
+ };
525
+ if (annotations.length) envelope.annotations = annotations;
526
+ const body = JSON.stringify(envelope);
257
527
  const headers = {
258
528
  'Content-Type': 'application/json',
259
529
  'X-Ingest-Key': key,
@@ -261,14 +531,12 @@ export function createAvowa({
261
531
  };
262
532
  if (secret) {
263
533
  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
534
  headers['X-Avowa-Timestamp'] = ts;
266
- headers['X-Avowa-Nonce'] = nonce;
267
- headers['X-Avowa-Signature'] = await hmacHex(secret, `${ts}.${nonce}.${body}`);
535
+ headers['X-Avowa-Signature'] = await hmacHex(secret, `${ts}.${body}`);
268
536
  if (remoteOn()) headers['X-Avowa-Fields'] = REMOTE.v || 'none';
269
537
  }
270
538
  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.`);
539
+ warnOnce('inflight', `${MAX_INFLIGHT} uploads already in flight — Avowa is slow or unreachable, so signals are being dropped. Your app is unaffected.`);
272
540
  return null;
273
541
  }
274
542
  inflight++;
@@ -276,7 +544,7 @@ export function createAvowa({
276
544
  const timer = setTimeout(() => ctl.abort(), TIMEOUT_MS);
277
545
  if (timer && typeof timer.unref === 'function') timer.unref();
278
546
  try {
279
- const r = await fetch(base + '/ingest/runtime', {
547
+ const r = await fetch(base + '/ingest/v1', {
280
548
  method: 'POST',
281
549
  headers,
282
550
  body,
@@ -287,7 +555,7 @@ export function createAvowa({
287
555
  const j = await r.clone().json();
288
556
  if (j && j.sdk_fields && secret && remoteOn()) await acceptFields(j.sdk_fields, secret);
289
557
  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).`);
558
+ warnOnce('latest', `@avowa/runtime ${j.sdk_latest} is available (this is ${VERSION}). Nothing is wrong — upgrade when convenient.`);
291
559
  }
292
560
  } catch {}
293
561
  }
@@ -559,6 +827,34 @@ export function createAvowa({
559
827
  f.tools_invoked = invoked;
560
828
  seen.push('tools_invoked');
561
829
  }
830
+ const calls = toolCalls(resp);
831
+ if (calls.length) {
832
+ f.tool_calls = calls;
833
+ seen.push('tool_calls');
834
+ }
835
+ const history = params && (Array.isArray(params.messages) ? params.messages : Array.isArray(params.input) ? params.input : null);
836
+ const results = toolResults(history);
837
+ if (results.length) {
838
+ f.tool_results = results;
839
+ seen.push('tool_results');
840
+ }
841
+ const mcp = mcpFacts(params, resp);
842
+ Object.assign(f, mcp);
843
+ seen.push(...Object.keys(mcp));
844
+ if (offered.length) {
845
+ const depth = autonomyDepth(history);
846
+ if (depth !== null) {
847
+ f.autonomy_depth = depth;
848
+ seen.push('autonomy_depth');
849
+ }
850
+ const rk = runKey(history, secret);
851
+ if (rk) {
852
+ Object.assign(f, {
853
+ agent_run_key: rk
854
+ });
855
+ seen.push('agent_run_key');
856
+ }
857
+ }
562
858
  return [f, seen];
563
859
  }
564
860
  function outputText(resp, kind) {
@@ -661,9 +957,9 @@ export function createAvowa({
661
957
  } catch {}
662
958
  return stream;
663
959
  }
664
- function wrapMethod(holder, name, kind, host, opts) {
960
+ function wrapMethod(holder, name, kind, host, opts, given) {
665
961
  if (typeof holder[name] !== 'function' || holder[name]._avowa_wrapped) return;
666
- const original = holder[name].bind(holder);
962
+ const original = given || holder[name].bind(holder);
667
963
  const wrapped = function (params = {}, ...rest) {
668
964
  const start = Date.now();
669
965
  const emit = (resp, err, ttft) => {
@@ -757,11 +1053,26 @@ export function createAvowa({
757
1053
  if (client && client.messages) wrapMethod(client.messages, 'create', 'anthropic', host, opts);
758
1054
  return client;
759
1055
  }
760
- return {
1056
+ function _wrapResource(resource, name, kind, original) {
1057
+ const client = resource && resource._client;
1058
+ const host = hostOf(client && client.baseURL) || (kind === 'anthropic' ? 'api.anthropic.com' : 'api.openai.com');
1059
+ const scan = !['0', 'false', 'no', 'off'].includes(String(env.AVOWA_SCAN || '').trim().toLowerCase());
1060
+ wrapMethod(resource, name, kind, host, {
1061
+ clientFacts: clientFacts(client),
1062
+ scan,
1063
+ region
1064
+ }, original.bind(resource));
1065
+ }
1066
+ const api = {
761
1067
  capture,
762
1068
  track,
763
1069
  instrumentOpenAI,
764
- instrumentAnthropic
1070
+ instrumentAnthropic,
1071
+ _wrapResource,
1072
+ approval,
1073
+ toolOutcome
765
1074
  };
1075
+ if (!DEFAULT && key) DEFAULT = api;
1076
+ return api;
766
1077
  }
767
1078
  export default createAvowa;
package/cli.js ADDED
@@ -0,0 +1,265 @@
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
+ // One retry: in a container that has just started, the very first connection can fail once
100
+ // (seen 2026-11-17 in a fresh node:22-slim) and succeed a second later. The token is spent only
101
+ // by a request the server answers, so retrying a request that never arrived is safe.
102
+ let r
103
+ for (let attempt = 1; ; attempt++) {
104
+ try {
105
+ r = await fetch(base + '/public/sdk/setup', { method: 'POST', body: JSON.stringify({ token }),
106
+ headers: { 'Content-Type': 'application/json', 'User-Agent': 'avowa-runtime-js (+https://avowa.ai)' },
107
+ signal: AbortSignal.timeout(15000) })
108
+ break
109
+ } catch (e) {
110
+ if (attempt < 2) { await new Promise((ok) => setTimeout(ok, 1500)); continue }
111
+ const why = (e.cause && (e.cause.code || e.cause.message)) || e.name
112
+ return [null, `Could not reach ${base} (${why}). Check the address and that this machine can reach it, or pass --api with your Avowa API URL. The setup token was not used.`]
113
+ }
114
+ }
115
+ if (r.status === 404) return [null, 'That setup token is invalid, expired (24h) or already used. Generate a new one in the console.']
116
+ if (!r.ok) return [null, `${base} answered HTTP ${r.status}.`]
117
+ const creds = await r.json()
118
+ if (creds.connector_id !== 'runtime_sdk') return [null, 'That token belongs to a Collector connection, not the Runtime SDK.']
119
+ const [b, p] = checkedBase(creds.base_url || base)
120
+ if (p) return [null, `The server returned an unsafe API URL (${p}); nothing was written.`]
121
+ return [{ ...creds, base_url: b }, null]
122
+ }
123
+
124
+ async function init(args) {
125
+ const dry = args.includes('--dry-run')
126
+ const yes = args.includes('--yes')
127
+ let api = (process.env.AVOWA_BASE_URL || 'https://api.avowa.ai').replace(/\/+$/, '')
128
+ const i = args.indexOf('--api')
129
+ if (i >= 0) {
130
+ if (!args[i + 1]) { console.error('--api needs a URL'); return 2 }
131
+ api = args[i + 1].replace(/\/+$/, ''); args = [...args.slice(0, i), ...args.slice(i + 2)]
132
+ }
133
+ const words = args.filter((a) => !a.startsWith('-'))
134
+ const file = path.join(process.cwd(), 'avowa.env')
135
+ const pkg = readPkg()
136
+ const scripts = startScripts(pkg)
137
+ const dep = pkg && !('@avowa/runtime' in deps(pkg)) ? 'dependency : run `npm install @avowa/runtime` so your build installs it too' : null
138
+ 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.`
139
+
140
+ if (dry) {
141
+ console.log('npx @avowa/runtime init --dry-run: nothing is changed and no setup token is used.\n')
142
+ console.log(`credentials : would write ${file} (mode 0600, one line: AVOWA_TOKEN)`)
143
+ for (const l of [gitignore(true), dep, node]) if (l) console.log(l)
144
+ for (const s of scripts) console.log(`package.json : would offer to change "${s.name}"\n from: ${s.from}\n to: ${s.to}`)
145
+ console.log('coverage from package.json:'); console.log(coverage(pkg).join('\n'))
146
+ return 0
147
+ }
148
+ if (!words.length) { console.error(USAGE); return 2 }
149
+ const [, unsafe] = checkedBase(api)
150
+ if (unsafe) { console.error(unsafe.replace('AVOWA_BASE_URL', '--api') + '.'); return 2 }
151
+ const [creds, problem] = await redeem(words[0], api)
152
+ if (problem) { console.error(problem); return 1 }
153
+ const token = makeToken(creds.ingest_token, creds.ingest_secret || '', creds.base_url)
154
+ fs.writeFileSync(file,
155
+ '# Avowa Runtime SDK: the credential for this connection. Keep private, server-side only.\n' +
156
+ '# Written by `npx @avowa/runtime init`. Read from the directory you start your app in.\n' +
157
+ '# In production, put this one value in your secret store as AVOWA_TOKEN instead.\n' +
158
+ `AVOWA_TOKEN=${token}\n`, { mode: 0o600 })
159
+ try { fs.chmodSync(file, 0o600) } catch { /* Windows */ }
160
+ console.log(`connected : ${creds.label || 'Avowa Runtime SDK'} (${creds.environment || 'prod'})`)
161
+ console.log(`credentials : ${file} (mode 0600, one line: AVOWA_TOKEN)`)
162
+ for (const l of [gitignore(false), dep, node]) if (l) console.log(l)
163
+
164
+ let changed = false
165
+ for (const s of scripts) {
166
+ console.log(`package.json : "${s.name}" can load Avowa before your app:\n from: ${s.from}\n to: ${s.to}`)
167
+ if (yes || await ask(' Make this change?')) {
168
+ const raw = fs.readFileSync('package.json', 'utf8')
169
+ const next = raw.replace(JSON.stringify(s.from), JSON.stringify(s.to))
170
+ if (next !== raw) { fs.writeFileSync('package.json', next); changed = true; console.log(' changed') }
171
+ } else console.log(' left as it is')
172
+ }
173
+ console.log('coverage from package.json:'); console.log(coverage(pkg).join('\n'))
174
+ console.log(await reportSetup(creds.ingest_token, creds.ingest_secret || '', creds.base_url, readPkg(), wired(readPkg())))
175
+ console.log('\nDone.' + (changed ? ' Start your app the way you always do' : ` Start your app with NODE_OPTIONS="--import ${REGISTER}" set`) +
176
+ ', then send one real request that calls the model.\n' +
177
+ ' check : npx @avowa/runtime status\n' +
178
+ ` production : set AVOWA_TOKEN (the value in avowa.env) and NODE_OPTIONS=--import ${REGISTER}. Nothing else changes.\n` +
179
+ ' off switch : AVOWA_DISABLE=1')
180
+ return 0
181
+ }
182
+
183
+ // Tell the server how the install stands, so the console's checklist can tick: the key and secret
184
+ // verify, which covered libraries package.json names, whether the preload is wired. The same
185
+ // signed whoami the doctor makes, with one extra header. No signal is sent.
186
+ async function reportSetup(key, secret, base, pkg, isWired) {
187
+ const d = deps(pkg)
188
+ const covered = ['openai', '@anthropic-ai/sdk'].filter((n) => n in d)
189
+ const ts = String(Math.floor(Date.now() / 1000))
190
+ const headers = { 'X-Ingest-Key': key, 'X-Avowa-Timestamp': ts,
191
+ 'X-Avowa-Signature': crypto.createHmac('sha256', secret || '').update(ts + '.').digest('hex'),
192
+ 'X-Avowa-Setup': `wired=${isWired ? 1 : 0}; covered=${covered.join(',')}`,
193
+ 'User-Agent': `avowa-runtime-js/${VERSION} (+https://avowa.ai)` }
194
+ try {
195
+ const r = await fetch(base + '/ingest/whoami', { headers, signal: AbortSignal.timeout(8000) })
196
+ if (!r.ok) return `server check : could not confirm (HTTP ${r.status}). Run \`npx @avowa/runtime status\` to see why.`
197
+ const who = await r.json()
198
+ if (!who.signature_ok) return 'server check : the secret did NOT verify. Run `npx @avowa/runtime status`.'
199
+ if (!who.capture_allowed) return "server check : key accepted, but this workspace's plan does not allow capture yet"
200
+ return 'server check : key and signature accepted (your console card now shows this step done)'
201
+ } catch (e) { return `server check : could not confirm (${e.name}). Run \`npx @avowa/runtime status\` to see why.` }
202
+ }
203
+
204
+ // Asks the server who this key is. Sends no signal: a synthetic one would show on the trust
205
+ // profile as inference that never happened.
206
+ async function doctor() {
207
+ const found = loadEnv()
208
+ const tok = process.env.AVOWA_TOKEN ? readToken(process.env.AVOWA_TOKEN) : null
209
+ const key = process.env.AVOWA_RUNTIME_KEY || (tok && tok[0])
210
+ const secret = process.env.AVOWA_RUNTIME_SECRET || (tok && tok[1])
211
+ const [base, problem] = checkedBase(process.env.AVOWA_BASE_URL || (tok && tok[2]) || undefined)
212
+ console.log(`env file : ${found || 'not found'}`)
213
+ if (process.env.AVOWA_TOKEN && !tok) { console.log('token : AVOWA_TOKEN is not a valid Avowa token (one starts with avw1_)'); return 1 }
214
+ if (problem) { console.log('api : ' + problem); return 1 }
215
+ console.log('api : ' + base)
216
+ if (!key) { console.log('credential : MISSING. Run `npx @avowa/runtime init <setup-token>` or set AVOWA_TOKEN'); return 1 }
217
+ const ts = String(Math.floor(Date.now() / 1000))
218
+ const headers = { 'X-Ingest-Key': key, 'X-Avowa-Timestamp': ts, 'User-Agent': `avowa-runtime-js/${VERSION} (+https://avowa.ai)` }
219
+ if (secret) headers['X-Avowa-Signature'] = crypto.createHmac('sha256', secret).update(ts + '.').digest('hex')
220
+ let who
221
+ try {
222
+ const r = await fetch(base + '/ingest/whoami', { headers, signal: AbortSignal.timeout(8000) })
223
+ if (r.status === 401) { console.log(`credential : REJECTED by ${base}. Not a key this server knows (rotated or revoked?)`); return 1 }
224
+ if (!r.ok) { console.log(`api : ${base} answered HTTP ${r.status}`); return 1 }
225
+ who = await r.json()
226
+ } catch (e) { console.log(`api : NOT reachable from this host (${e.name})`); return 1 }
227
+ let ok = true
228
+ console.log(`connection : ${who.label || who.connection_id} · ${who.environment}`)
229
+ if (who.capture_allowed) console.log('plan : capture allowed')
230
+ else { console.log('plan : capture NOT allowed. The workspace is on Declare; signals will get 402'); ok = false }
231
+ if (!secret) { console.log('secret : not set. Signals would be sent unsigned and refused'); ok = false }
232
+ else if (who.signature_ok) console.log('secret : signs correctly')
233
+ else { console.log('secret : does NOT verify. Every signal would get 401'); ok = false }
234
+ if (typeof who.clock_skew_s === 'number') {
235
+ const s = who.clock_skew_s
236
+ console.log(`clock : ${s >= 0 ? '+' : ''}${Math.round(s)}s vs server${Math.abs(s) < 120 ? '' : '. Over 5 minutes is rejected; fix NTP'}`)
237
+ ok = ok && Math.abs(s) < 300
238
+ }
239
+ console.log(`last event : ${who.last_event_at || 'never'} (${who.events_total || 0} total)`)
240
+ console.log('\nNo signal was sent.' + (ok ? '' : ' Fix the lines marked above, then run again.'))
241
+ return ok ? 0 : 1
242
+ }
243
+
244
+ async function status() {
245
+ const pkg = readPkg()
246
+ console.log(`node : ${process.versions.node}${nodeOk() ? '' : ' (no --import flag: needs 18.18+ or 20.6+)'}`)
247
+ console.log(`preload : ${wired(pkg) ? 'wired (' + REGISTER + ')' : 'NOT wired. Set NODE_OPTIONS="--import ' + REGISTER + '" or run init'}`)
248
+ console.log('coverage from package.json:'); console.log(coverage(pkg).join('\n'))
249
+ loadEnv()
250
+ const tok = process.env.AVOWA_TOKEN ? readToken(process.env.AVOWA_TOKEN) : null
251
+ const key = process.env.AVOWA_RUNTIME_KEY || (tok && tok[0])
252
+ const secret = process.env.AVOWA_RUNTIME_SECRET || (tok && tok[1])
253
+ const [base] = checkedBase(process.env.AVOWA_BASE_URL || (tok && tok[2]) || undefined)
254
+ if (key && secret && base) await reportSetup(key, secret, base, pkg, wired(pkg)) // refreshes the console checklist
255
+ console.log('server check:')
256
+ return doctor()
257
+ }
258
+
259
+ const [cmd, ...rest] = process.argv.slice(2)
260
+ let code
261
+ if (cmd === 'init') code = await init(rest)
262
+ else if (cmd === 'status') code = await status()
263
+ else if (cmd === 'doctor') code = await doctor()
264
+ else { console.error(USAGE); code = cmd && !['-h', '--help', 'help'].includes(cmd) ? 2 : (cmd ? 0 : 2) }
265
+ 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.13.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 {}