@avowa/runtime 0.13.0 → 0.13.2

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
@@ -1,132 +1,114 @@
1
1
  # @avowa/runtime
2
2
 
3
- The JavaScript/TypeScript half of the [Avowa Runtime SDK](https://github.com/Avowa-AI/avowa-runtime-sdk) — emits live AI-inference
4
- signals to Avowa as **observed** evidence. Node 18+, server-side only — the signing secret must never ship to a browser, and the ingest API does not accept browser origins.
3
+ The Node.js half of the [Avowa Runtime SDK](https://github.com/Avowa-AI/avowa-runtime-sdk). Keeps an
4
+ independent record of what your AI does in production: which model answered, where it ran, which tools
5
+ your agents called, and who approved them.
6
+
7
+ It reads **metadata only**. It never sends prompts, completions, tool arguments or tool output, never
8
+ changes a request or response, and never blocks a call. If Avowa is unreachable your app carries on.
9
+ `AVOWA_DISABLE=1` turns it off. Node 18.18+ or 20.6+, server-side only. Apache-2.0, no dependencies.
10
+
11
+ **Documentation: [avowa.ai/docs](https://avowa.ai/docs/)**
5
12
 
6
13
  ## Install
7
14
 
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*.)
15
+ In your project folder. Generate the setup token in the Avowa console under **Connections, Runtime
16
+ SDK**; it works once.
10
17
 
11
18
  ```bash
12
19
  npm install @avowa/runtime
13
- npx @avowa/runtime init <setup-token> # writes avowa.env with one value: AVOWA_TOKEN
20
+ npx @avowa/runtime init <setup-token>
14
21
  ```
15
22
 
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):
23
+ `init` writes `avowa.env` (one line, `AVOWA_TOKEN`), adds it to `.gitignore`, and offers to add the
24
+ preload to your `start` script, showing the change first (`init --dry-run` changes nothing):
18
25
 
19
26
  ```
20
27
  from: node server.js
21
28
  to: node --import @avowa/runtime/register server.js
22
29
  ```
23
30
 
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.
31
+ Start your app the way you always do and send one request that calls the model. Then
32
+ `npx @avowa/runtime status` shows what is covered and whether the server knows this key. It sends no
33
+ signal.
27
34
 
28
- **In production** set two environment variables and change nothing else:
35
+ **In production** set two variables and change nothing else:
29
36
 
30
37
  ```bash
31
- AVOWA_TOKEN=avw1_... # the value in avowa.env
32
- NODE_OPTIONS=--import @avowa/runtime/register # any start command, Docker, Kubernetes
38
+ AVOWA_TOKEN=<the value in avowa.env>
39
+ NODE_OPTIONS=--import @avowa/runtime/register
33
40
  ```
34
41
 
35
- `AVOWA_DISABLE=1` switches everything off. One dependency-free package, Apache-2.0.
36
-
37
- ### What the preload covers
42
+ ## What the preload covers
38
43
 
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
+ | Library | Coverage |
44
45
  |---|---|
45
46
  | `openai` (OpenAI, Azure OpenAI, any OpenAI-compatible host) | `chat.completions.create`, `responses.create`, streams included |
46
47
  | `@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+.
48
+ | Bedrock, Gemini, Vercel AI SDK, raw `fetch` | not yet: use `capture()` or `track()` |
55
49
 
56
- ## Use it in code instead
50
+ ES modules and CommonJS both work. The wrappers hand back the provider's own promise and stream objects,
51
+ so `.withResponse()`, `.tee()` and `instanceof` behave as without Avowa.
57
52
 
58
- Nothing below is needed when the preload is on. It is for the cases above, and for recording what
59
- your app enforces.
53
+ **Bundled server code.** A bundler (Next.js, esbuild, webpack) that compiles the provider SDK into its
54
+ own output carries a private copy the preload never meets. Keep the provider SDK external to the bundle
55
+ (Next.js: `serverExternalPackages`), or wrap the client once:
60
56
 
61
57
  ```js
62
- import createAvowa from '@avowa/runtime'
63
-
64
- const avowa = createAvowa() // reads AVOWA_TOKEN from the environment
65
-
66
- // record a call you already made
67
- avowa.capture({ model: 'claude-opus-4-8', train_on_data: false })
58
+ import OpenAI from 'openai'
59
+ import { createAvowa } from '@avowa/runtime'
68
60
 
69
- // or wrap one: times it, and records whether it was blocked
70
- const resp = await avowa.track({ model: 'claude-opus-4-8' }, () => client.messages.create(...))
61
+ const avowa = createAvowa() // reads AVOWA_TOKEN
62
+ const openai = avowa.instrumentOpenAI(new OpenAI())
63
+ // const anthropic = avowa.instrumentAnthropic(new Anthropic())
71
64
  ```
72
65
 
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()`.
66
+ ## Agents: runs, approvals, outcomes
77
67
 
78
- **Metadata only.** Model id, host, region, latency, counts and the flags you pass. Never prompts,
79
- completions, tool arguments or customer data.
80
-
81
- **Never in your way.** Capture is fire-and-forget and never rejects: if Avowa is unreachable your
82
- call still returns, uploads time out after 5 s, and at most 64 are in flight (past that they are
83
- dropped, with one warning). The wrappers hand back the provider's own promise and stream objects
84
- (`.withResponse()`, `.tee()` and `instanceof` all behave as without Avowa). HTTPS only, every
85
- request signed and single-use, and `AVOWA_DISABLE=1` turns it off entirely.
86
- `track()` re-throws whatever your function threw, after recording that it was blocked.
87
-
88
- Licence: Apache-2.0.
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:
68
+ The wrappers record each tool call the model proposed and each result your app handed back, by a hash
69
+ of the provider's call id, with the step depth and a run key. Three calls add what they cannot see:
96
70
 
97
71
  ```js
98
- import { approval, toolOutcome, agentContext } from '@avowa/runtime'
72
+ import { agentContext, approval, toolOutcome } from '@avowa/runtime'
99
73
 
100
- await agentContext({ name: 'triage', customer: account.id }, async () => {
74
+ await agentContext({ name: 'incident-agent', customer: account.id }, async () => {
101
75
  const resp = await client.messages.create({ ... })
102
76
  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'
77
+ if (b.type === 'tool_use') {
78
+ const ok = await askOnCall(b) // your approval step
79
+ approval(b.id, ok, 'on-call SRE', { approverType: 'human' }) // a role, never a name
80
+ // a rule instead: approval(b.id, true, null, { approverType: 'policy', policyRef: 'read-only-tools' })
81
+ toolOutcome(b.id, ok ? 'ok' : 'denied') // or 'error', 'timeout'
106
82
  }
107
83
  }
108
84
  })
109
85
  ```
110
86
 
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.
87
+ `approverType` is `'human'`, `'policy'`, `'system'` or `'unknown'` (the default); only `'human'` counts
88
+ as human approval. The customer id is sent only as a keyed hash. Findings name the run, step and a call
89
+ reference; `npx @avowa/runtime ref --find <ref> <logfile>` finds that call in your own logs.
90
+
91
+ Guide: [avowa.ai/docs/agents.html](https://avowa.ai/docs/agents.html).
116
92
 
117
- ## Wrap your client (observed, not asserted)
93
+ ## Recording what your app enforces
118
94
 
119
95
  ```js
120
- import OpenAI from 'openai'
121
- import { createAvowa } from '@avowa/runtime'
96
+ avowa.capture({ model: 'claude-opus-4-8', train_on_data: false })
122
97
 
123
- const avowa = createAvowa() // AVOWA_TOKEN from the env
124
- const openai = avowa.instrumentOpenAI(new OpenAI()) // chat.completions.create, responses.create — streams included
125
- // const anthropic = avowa.instrumentAnthropic(new Anthropic()) // messages.create — streams included
98
+ // or wrap a call: times it and records whether it was blocked
99
+ const resp = await avowa.track({ model: 'claude-opus-4-8' }, () => client.messages.create(...))
126
100
  ```
127
101
 
128
- The wrapper reads the requested and served model, the provider's finish/stop code, the tools
129
- offered and the tools the model invoked, and scans the prompt and output text locally; only counts
130
- leave. It sends those facts as they are — Avowa evaluates them on its side — and each signal names
131
- the fields the wrapper read, so they grade as observed rather than as your app's word. `capture()` and `track()` remain for anything else,
132
- graded as self-reported.
102
+ These are signed in transit and graded as your application's word, never as observed. `track()`
103
+ re-throws whatever your function threw. Uploads time out after 5 seconds and at most 64 are in flight;
104
+ past that they are dropped, with one warning.
105
+
106
+ ## More
107
+
108
+ - What leaves your process, field by field: [avowa.ai/docs/data.html](https://avowa.ai/docs/data.html)
109
+ - Security review: [avowa.ai/docs/security.html](https://avowa.ai/docs/security.html)
110
+ - Commands and environment variables: [avowa.ai/docs/reference.html](https://avowa.ai/docs/reference.html)
111
+ - Troubleshooting: [avowa.ai/docs/troubleshooting.html](https://avowa.ai/docs/troubleshooting.html)
112
+ - Changelog: [avowa.ai/docs/changelog.html](https://avowa.ai/docs/changelog.html)
113
+
114
+ Support: support@avowa.ai. Licence: Apache-2.0.
package/avowa-runtime.js CHANGED
@@ -3,7 +3,7 @@
3
3
  import { createHash, createHmac } from 'node:crypto';
4
4
  import { AsyncLocalStorage } from 'node:async_hooks';
5
5
  const env = typeof process !== 'undefined' && process.env || {};
6
- const VERSION = '0.13.0';
6
+ const VERSION = '0.13.2';
7
7
  const SCHEMA = 'avowa.signal/1';
8
8
  export const SDK_VERSION = VERSION;
9
9
  let _subtle = null;
@@ -236,7 +236,7 @@ function toolResults(history) {
236
236
  for (const m of history) {
237
237
  const role = g(m, 'role'),
238
238
  typ = g(m, 'type');
239
- if (role === 'assistant' || typ === 'function_call' || typ === 'custom_tool_call') {
239
+ if (role === 'assistant' || MODEL_ITEMS.has(typ)) {
240
240
  fresh = [];
241
241
  continue;
242
242
  }
@@ -297,6 +297,10 @@ function mcpFacts(params, resp) {
297
297
  return f;
298
298
  }
299
299
  function runKey(messages, secret) {
300
+ if (typeof messages === 'string') messages = [{
301
+ role: 'user',
302
+ content: messages
303
+ }];
300
304
  if (!Array.isArray(messages)) return null;
301
305
  for (const m of messages) {
302
306
  if (g(m, 'role') !== 'user') continue;
@@ -308,19 +312,52 @@ function runKey(messages, secret) {
308
312
  }
309
313
  return null;
310
314
  }
311
- function autonomyDepth(messages) {
312
- if (!Array.isArray(messages)) return null;
313
- let d = 0;
315
+ const MODEL_ITEMS = new Set(['function_call', 'custom_tool_call', 'mcp_call', 'computer_call', 'web_search_call', 'file_search_call', 'code_interpreter_call', 'local_shell_call', 'reasoning']);
316
+ const CALL_ITEMS = new Set(['function_call', 'custom_tool_call', 'mcp_call', 'computer_call', 'local_shell_call']);
317
+ const RESULT_ITEMS = new Set(['function_call_output', 'custom_tool_call_output', 'computer_call_output', 'local_shell_call_output', 'mcp_approval_response']);
318
+ function modelTurns(messages) {
319
+ const turns = [];
320
+ let cur = null;
314
321
  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++;
322
+ const role = g(m, 'role'),
323
+ typ = g(m, 'type');
324
+ if (!(MODEL_ITEMS.has(typ) || role === 'assistant')) {
325
+ cur = null;
326
+ turns.push([false, false]);
318
327
  continue;
319
328
  }
320
- const c = g(m, 'content');
321
- if (Array.isArray(c) && c.some(b => g(b, 'type') === 'tool_use')) d++;
329
+ let tools = CALL_ITEMS.has(typ);
330
+ if (role === 'assistant') {
331
+ if (Array.isArray(g(m, 'tool_calls')) && m.tool_calls.length) tools = true;
332
+ const c = g(m, 'content');
333
+ if (Array.isArray(c) && c.some(b => g(b, 'type') === 'tool_use')) tools = true;
334
+ }
335
+ if (role === 'assistant' && typ === undefined) {
336
+ cur = null;
337
+ turns.push([true, tools]);
338
+ continue;
339
+ }
340
+ if (!cur) {
341
+ cur = [true, false];
342
+ turns.push(cur);
343
+ }
344
+ cur[1] = cur[1] || tools;
345
+ }
346
+ return turns;
347
+ }
348
+ function autonomyDepth(messages) {
349
+ if (typeof messages === 'string') return 0;
350
+ if (!Array.isArray(messages)) return null;
351
+ try {
352
+ return modelTurns(messages).filter(([m, t]) => m && t).length;
353
+ } catch {
354
+ return null;
322
355
  }
323
- return d;
356
+ }
357
+ const CHAIN = new Map();
358
+ function chainPut(id, key, next) {
359
+ CHAIN.set(String(id), [key, next]);
360
+ while (CHAIN.size > 4096) CHAIN.delete(CHAIN.keys().next().value);
324
361
  }
325
362
  const AGENT = new AsyncLocalStorage();
326
363
  export function agentContext({
@@ -555,7 +592,7 @@ export function createAvowa({
555
592
  const j = await r.clone().json();
556
593
  if (j && j.sdk_fields && secret && remoteOn()) await acceptFields(j.sdk_fields, secret);
557
594
  if (j && typeof j.sdk_latest === 'string' && /^\d+\.\d+\.\d+$/.test(j.sdk_latest)) {
558
- warnOnce('latest', `@avowa/runtime ${j.sdk_latest} is available (this is ${VERSION}). Nothing is wrong — upgrade when convenient.`);
595
+ warnOnce('latest', `@avowa/runtime ${j.sdk_latest} is available (this is ${VERSION}). Nothing is wrong — upgrade when convenient: npm install @avowa/runtime@latest.`);
559
596
  }
560
597
  } catch {}
561
598
  }
@@ -636,8 +673,12 @@ export function createAvowa({
636
673
  audio: 0
637
674
  };
638
675
  let chars = 0;
676
+ try {
677
+ roles.assistant += modelTurns(msgs).filter(([mt]) => mt).length - msgs.filter(m => g(m, 'role') === 'assistant').length;
678
+ } catch {}
639
679
  for (const m of msgs) {
640
680
  if (!m) continue;
681
+ if (RESULT_ITEMS.has(m.type)) roles.tool++;
641
682
  if (m.role === 'system' || m.role === 'developer') system = true;else if (m.role in roles) roles[m.role]++;
642
683
  if (typeof m.content === 'string') chars += m.content.length;else if (Array.isArray(m.content)) {
643
684
  for (const b of m.content) {
@@ -819,7 +860,7 @@ export function createAvowa({
819
860
  if (n) invoked.push(String(n).slice(0, 64));
820
861
  }
821
862
  for (const it of resp.output || []) {
822
- if (it && it.type === 'function_call' && it.name) invoked.push(String(it.name).slice(0, 64));
863
+ if (it && (it.type === 'function_call' || it.type === 'custom_tool_call') && it.name) invoked.push(String(it.name).slice(0, 64));
823
864
  }
824
865
  }
825
866
  } catch {}
@@ -832,7 +873,7 @@ export function createAvowa({
832
873
  f.tool_calls = calls;
833
874
  seen.push('tool_calls');
834
875
  }
835
- const history = params && (Array.isArray(params.messages) ? params.messages : Array.isArray(params.input) ? params.input : null);
876
+ const history = params && (Array.isArray(params.messages) ? params.messages : Array.isArray(params.input) || typeof params.input === 'string' ? params.input : null);
836
877
  const results = toolResults(history);
837
878
  if (results.length) {
838
879
  f.tool_results = results;
@@ -842,18 +883,32 @@ export function createAvowa({
842
883
  Object.assign(f, mcp);
843
884
  seen.push(...Object.keys(mcp));
844
885
  if (offered.length) {
845
- const depth = autonomyDepth(history);
886
+ let depth = autonomyDepth(history);
887
+ let rk = runKey(history, secret);
888
+ if (params.previous_response_id) {
889
+ const parent = CHAIN.get(String(params.previous_response_id));
890
+ if (!parent) {
891
+ depth = null;
892
+ rk = null;
893
+ } else {
894
+ rk = parent[0];
895
+ depth = parent[1] === null || depth === null ? null : parent[1] + depth;
896
+ }
897
+ } else if (params.conversation) {
898
+ depth = null;
899
+ rk = null;
900
+ }
846
901
  if (depth !== null) {
847
902
  f.autonomy_depth = depth;
848
903
  seen.push('autonomy_depth');
849
904
  }
850
- const rk = runKey(history, secret);
851
905
  if (rk) {
852
906
  Object.assign(f, {
853
907
  agent_run_key: rk
854
908
  });
855
909
  seen.push('agent_run_key');
856
910
  }
911
+ if (resp.id && Array.isArray(resp.output)) chainPut(resp.id, rk, depth === null ? null : depth + (calls.length ? 1 : 0));
857
912
  }
858
913
  return [f, seen];
859
914
  }
@@ -871,6 +926,10 @@ export function createAvowa({
871
926
  stop = null,
872
927
  size = 0,
873
928
  ttft = null;
929
+ let completed = null,
930
+ usage = null;
931
+ const chatCalls = new Map(),
932
+ blocks = [];
874
933
  const started = Date.now();
875
934
  const text = [];
876
935
  const keep = t => {
@@ -887,12 +946,38 @@ export function createAvowa({
887
946
  if (t === 'message_delta' && c.delta && c.delta.stop_reason) stop = c.delta.stop_reason;
888
947
  if (t === 'content_block_delta' && c.delta && c.delta.text) keep(c.delta.text);
889
948
  if (t.endsWith('output_text.delta') && typeof c.delta === 'string') keep(c.delta);
890
- if (t === 'response.completed' && c.response && c.response.model) model = c.response.model;
949
+ if (t === 'response.completed' && c.response) {
950
+ completed = c.response;
951
+ if (c.response.model) model = c.response.model;
952
+ }
953
+ if (t === 'content_block_start' && c.content_block && c.content_block.type === 'tool_use') blocks.push({
954
+ type: 'tool_use',
955
+ id: c.content_block.id,
956
+ name: c.content_block.name
957
+ });
958
+ if (t === 'message_start' && c.message && c.message.usage) usage = {
959
+ ...(usage || {}),
960
+ input_tokens: c.message.usage.input_tokens
961
+ };
962
+ if (t === 'message_delta' && c.usage && c.usage.output_tokens != null) usage = {
963
+ ...(usage || {}),
964
+ output_tokens: c.usage.output_tokens
965
+ };
891
966
  if (!t && c.model) model = c.model;
967
+ if (!t && c.usage && c.usage.prompt_tokens != null) usage = {
968
+ prompt_tokens: c.usage.prompt_tokens,
969
+ completion_tokens: c.usage.completion_tokens
970
+ };
892
971
  const ch = c.choices && c.choices[0];
893
972
  if (ch) {
894
973
  if (ch.finish_reason) stop = ch.finish_reason;
895
974
  if (ch.delta && typeof ch.delta.content === 'string') keep(ch.delta.content);
975
+ for (const tc of ch.delta && ch.delta.tool_calls || []) {
976
+ const slot = chatCalls.get(tc.index || 0) || [null, null];
977
+ if (tc.id) slot[0] = tc.id;
978
+ if (tc.function && tc.function.name) slot[1] = tc.function.name;
979
+ chatCalls.set(tc.index || 0, slot);
980
+ }
896
981
  }
897
982
  } catch {}
898
983
  };
@@ -901,20 +986,30 @@ export function createAvowa({
901
986
  if (done) return;
902
987
  done = true;
903
988
  const all = text.join('');
904
- const summary = kind === 'anthropic' ? {
989
+ const calls = [...chatCalls.entries()].sort((a, b) => a[0] - b[0]).filter(([, [, n]]) => n).map(([, [id, name]]) => ({
990
+ id,
991
+ type: 'function',
992
+ function: {
993
+ name
994
+ }
995
+ }));
996
+ const summary = completed ? completed : kind === 'anthropic' ? {
905
997
  model,
906
998
  stop_reason: stop,
999
+ usage,
907
1000
  content: [{
908
1001
  type: 'text',
909
1002
  text: all
910
- }]
1003
+ }, ...blocks]
911
1004
  } : {
912
1005
  model,
913
1006
  output_text: all,
1007
+ usage,
914
1008
  choices: [{
915
1009
  finish_reason: stop,
916
1010
  message: {
917
- content: all
1011
+ content: all,
1012
+ tool_calls: calls.length ? calls : undefined
918
1013
  }
919
1014
  }]
920
1015
  };
@@ -990,7 +1085,8 @@ export function createAvowa({
990
1085
  facts.output_chars = out.length;
991
1086
  seen.push('output_chars');
992
1087
  }
993
- seen.push('model', 'endpoint', 'latency_ms');
1088
+ if (resp && typeof resp.model === 'string' && resp.model) seen.push('model');
1089
+ seen.push('endpoint', 'latency_ms');
994
1090
  if (err) seen.push('error');
995
1091
  if (opts.scan !== false) seen.push('pii_detected', 'injection_suspected', 'pii_families', 'injection_families');
996
1092
  const prompt = kind === 'anthropic' ? textOfMessages(params.messages) : textOfMessages(params.messages || (Array.isArray(params.input) ? params.input : [params.input]));
package/cli.js CHANGED
@@ -9,12 +9,14 @@
9
9
  * init --dry-run show what init would do; changes nothing, uses no token
10
10
  * status what is wired, what is covered, does the server know this key
11
11
  * doctor the server check only (sends no signal)
12
+ * ref <tool-call-id> the reference Avowa shows for a provider tool call id (toolu_..., call_...)
13
+ * ref --find <ref> <file>... find the tool call behind a reference in your own logs (local only)
12
14
  */
13
15
  import fs from 'node:fs'
14
16
  import path from 'node:path'
15
17
  import crypto from 'node:crypto'
16
18
  import readline from 'node:readline'
17
- import { checkedBase, makeToken, readToken, SDK_VERSION as VERSION } from './avowa-runtime.js'
19
+ import { checkedBase, makeToken, readToken, callRef, SDK_VERSION as VERSION } from './avowa-runtime.js'
18
20
  import { loadEnv } from './env.js'
19
21
 
20
22
  const REGISTER = '@avowa/runtime/register'
@@ -23,6 +25,8 @@ const USAGE = `usage: npx @avowa/runtime <command>
23
25
  init <setup-token> [--api https://api.avowa.ai] [--dry-run] [--yes]
24
26
  status
25
27
  doctor
28
+ ref <tool-call-id>... the reference Avowa shows for a provider tool call id
29
+ ref --find <ref> <file>... find that call in your own logs ("-" reads stdin); nothing is sent
26
30
 
27
31
  Generate the setup token in the Avowa console: Connections, Runtime SDK.
28
32
  In production set two variables and change nothing else:
@@ -198,7 +202,7 @@ async function reportSetup(key, secret, base, pkg, isWired) {
198
202
  if (!who.signature_ok) return 'server check : the secret did NOT verify. Run `npx @avowa/runtime status`.'
199
203
  if (!who.capture_allowed) return "server check : key accepted, but this workspace's plan does not allow capture yet"
200
204
  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.` }
205
+ } catch (e) { return `server check : could not reach ${base} (${e.name}). This is the address in your credential; AVOWA_BASE_URL overrides it. Run \`npx @avowa/runtime status\` for more.` }
202
206
  }
203
207
 
204
208
  // Asks the server who this key is. Sends no signal: a synthetic one would show on the trust
@@ -237,7 +241,7 @@ async function doctor() {
237
241
  ok = ok && Math.abs(s) < 300
238
242
  }
239
243
  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.'))
244
+ console.log('\nThis check sent no signal.' + (ok ? '' : ' Fix the lines marked above, then run again.'))
241
245
  return ok ? 0 : 1
242
246
  }
243
247
 
@@ -256,10 +260,36 @@ async function status() {
256
260
  return doctor()
257
261
  }
258
262
 
263
+ // Avowa names a tool call by a hash of the provider's id. This goes the other way, locally: id ->
264
+ // reference, or a reference -> the line in your logs holding its id. Prints file:line and the id only.
265
+ async function ref(args) {
266
+ if (!args.length) { console.error('usage: npx @avowa/runtime ref <tool-call-id>... | ref --find <ref> <file>...'); return 2 }
267
+ if (args[0] !== '--find') { for (const id of args) console.log(`${callRef(id)} ${id}`); return 0 }
268
+ if (args.length < 3) { console.error('usage: npx @avowa/runtime ref --find <ref> <file>... ("-" reads stdin)'); return 2 }
269
+ const want = args[1].trim().toLowerCase()
270
+ const tok = /[A-Za-z0-9][A-Za-z0-9_-]{5,127}/g
271
+ let found = 0
272
+ for (const p of args.slice(2)) {
273
+ let stream
274
+ try { stream = p === '-' ? process.stdin : fs.createReadStream(p, { encoding: 'utf8' }) } catch (e) { console.error(`${p}: ${e.message}`); continue }
275
+ const rl = readline.createInterface({ input: stream, crlfDelay: Infinity })
276
+ let n = 0
277
+ try {
278
+ for await (const line of rl) {
279
+ n++
280
+ for (const t of new Set(line.match(tok) || [])) if (callRef(t) === want) { console.log(`${p}:${n} ${t}`); found++ }
281
+ }
282
+ } catch (e) { console.error(`${p}: ${e.message}`) }
283
+ }
284
+ if (!found) console.error(`no tool call id in those files has reference ${want}`)
285
+ return found ? 0 : 1
286
+ }
287
+
259
288
  const [cmd, ...rest] = process.argv.slice(2)
260
289
  let code
261
290
  if (cmd === 'init') code = await init(rest)
262
291
  else if (cmd === 'status') code = await status()
263
292
  else if (cmd === 'doctor') code = await doctor()
293
+ else if (cmd === 'ref') code = await ref(rest)
264
294
  else { console.error(USAGE); code = cmd && !['-h', '--help', 'help'].includes(cmd) ? 2 : (cmd ? 0 : 2) }
265
295
  process.exitCode = code
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@avowa/runtime",
3
- "version": "0.13.0",
3
+ "version": "0.13.2",
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",