@avowa/runtime 0.12.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
@@ -87,6 +87,33 @@ request signed and single-use, and `AVOWA_DISABLE=1` turns it off entirely.
87
87
 
88
88
  Licence: Apache-2.0.
89
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
+
90
117
  ## Wrap your client (observed, not asserted)
91
118
 
92
119
  ```js
package/avowa-runtime.js CHANGED
@@ -1,7 +1,9 @@
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.12.0';
6
+ const VERSION = '0.13.0';
5
7
  const SCHEMA = 'avowa.signal/1';
6
8
  export const SDK_VERSION = VERSION;
7
9
  let _subtle = null;
@@ -202,6 +204,160 @@ export function readToken(token) {
202
204
  return null;
203
205
  }
204
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
+ }
205
361
  export function createAvowa({
206
362
  ingestKey,
207
363
  ingestSecret,
@@ -216,6 +372,8 @@ export function createAvowa({
216
372
  instrumentOpenAI: c => c,
217
373
  instrumentAnthropic: c => c,
218
374
  _wrapResource: () => undefined,
375
+ approval: noop,
376
+ toolOutcome: noop,
219
377
  disabled: true
220
378
  };
221
379
  }
@@ -247,9 +405,14 @@ export function createAvowa({
247
405
  if (evt.guardrail_blocked !== undefined && evt.guardrail_blocked !== null) {
248
406
  payload.guardrail_blocked = !!evt.guardrail_blocked;
249
407
  }
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']) {
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']) {
251
409
  if (evt[k] !== undefined && evt[k] !== null) payload[k] = evt[k];
252
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;
253
416
  if (evt.endpoint) payload.endpoint = hostOf(evt.endpoint);
254
417
  const scanP = evt.scanPrompt !== undefined && evt.scanPrompt !== null ? cap(evt.scanPrompt, 'tail') : null;
255
418
  const scanO = evt.scanOutput !== undefined && evt.scanOutput !== null ? cap(evt.scanOutput, 'head') : null;
@@ -297,11 +460,58 @@ export function createAvowa({
297
460
  const batch = pending.splice(0, BATCH_MAX);
298
461
  if (pending.length) pendingTimer = setTimeout(flushPending, BATCH_WAIT_MS);
299
462
  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)));
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);
301
497
  }
302
- async function sendEnvelope(events) {
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 = []) {
303
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('');
304
- const body = JSON.stringify({
514
+ const envelope = {
305
515
  schema: SCHEMA,
306
516
  source: {
307
517
  kind: 'runtime',
@@ -311,7 +521,9 @@ export function createAvowa({
311
521
  sent_at: new Date().toISOString().replace(/\.\d{3}Z$/, 'Z'),
312
522
  nonce,
313
523
  events
314
- });
524
+ };
525
+ if (annotations.length) envelope.annotations = annotations;
526
+ const body = JSON.stringify(envelope);
315
527
  const headers = {
316
528
  'Content-Type': 'application/json',
317
529
  'X-Ingest-Key': key,
@@ -615,6 +827,34 @@ export function createAvowa({
615
827
  f.tools_invoked = invoked;
616
828
  seen.push('tools_invoked');
617
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
+ }
618
858
  return [f, seen];
619
859
  }
620
860
  function outputText(resp, kind) {
@@ -823,12 +1063,16 @@ export function createAvowa({
823
1063
  region
824
1064
  }, original.bind(resource));
825
1065
  }
826
- return {
1066
+ const api = {
827
1067
  capture,
828
1068
  track,
829
1069
  instrumentOpenAI,
830
1070
  instrumentAnthropic,
831
- _wrapResource
1071
+ _wrapResource,
1072
+ approval,
1073
+ toolOutcome
832
1074
  };
1075
+ if (!DEFAULT && key) DEFAULT = api;
1076
+ return api;
833
1077
  }
834
1078
  export default createAvowa;
package/cli.js CHANGED
@@ -96,12 +96,22 @@ function ask(question) {
96
96
  async function redeem(token, api) {
97
97
  const [base, problem] = checkedBase(api)
98
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.
99
102
  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.`] }
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
+ }
105
115
  if (r.status === 404) return [null, 'That setup token is invalid, expired (24h) or already used. Generate a new one in the console.']
106
116
  if (!r.ok) return [null, `${base} answered HTTP ${r.status}.`]
107
117
  const creds = await r.json()
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@avowa/runtime",
3
- "version": "0.12.0",
3
+ "version": "0.13.0",
4
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",