risicare 0.9.0 → 0.9.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.
Files changed (93) hide show
  1. package/CHANGELOG.md +1236 -0
  2. package/README.md +18 -0
  3. package/dist/frameworks/instructor.cjs +163 -6
  4. package/dist/frameworks/instructor.cjs.map +1 -1
  5. package/dist/frameworks/instructor.js +163 -6
  6. package/dist/frameworks/instructor.js.map +1 -1
  7. package/dist/frameworks/langchain.cjs +163 -6
  8. package/dist/frameworks/langchain.cjs.map +1 -1
  9. package/dist/frameworks/langchain.js +163 -6
  10. package/dist/frameworks/langchain.js.map +1 -1
  11. package/dist/frameworks/langgraph.cjs +163 -6
  12. package/dist/frameworks/langgraph.cjs.map +1 -1
  13. package/dist/frameworks/langgraph.js +163 -6
  14. package/dist/frameworks/langgraph.js.map +1 -1
  15. package/dist/frameworks/llamaindex.cjs +163 -6
  16. package/dist/frameworks/llamaindex.cjs.map +1 -1
  17. package/dist/frameworks/llamaindex.js +163 -6
  18. package/dist/frameworks/llamaindex.js.map +1 -1
  19. package/dist/index.cjs +274 -18
  20. package/dist/index.cjs.map +1 -1
  21. package/dist/index.d.cts +7 -1
  22. package/dist/index.d.ts +7 -1
  23. package/dist/index.js +274 -18
  24. package/dist/index.js.map +1 -1
  25. package/dist/providers/anthropic/index.cjs +168 -7
  26. package/dist/providers/anthropic/index.cjs.map +1 -1
  27. package/dist/providers/anthropic/index.d.cts +3 -0
  28. package/dist/providers/anthropic/index.d.ts +3 -0
  29. package/dist/providers/anthropic/index.js +168 -7
  30. package/dist/providers/anthropic/index.js.map +1 -1
  31. package/dist/providers/bedrock/index.cjs +168 -7
  32. package/dist/providers/bedrock/index.cjs.map +1 -1
  33. package/dist/providers/bedrock/index.d.cts +3 -0
  34. package/dist/providers/bedrock/index.d.ts +3 -0
  35. package/dist/providers/bedrock/index.js +168 -7
  36. package/dist/providers/bedrock/index.js.map +1 -1
  37. package/dist/providers/cerebras/index.cjs +168 -7
  38. package/dist/providers/cerebras/index.cjs.map +1 -1
  39. package/dist/providers/cerebras/index.d.cts +3 -0
  40. package/dist/providers/cerebras/index.d.ts +3 -0
  41. package/dist/providers/cerebras/index.js +168 -7
  42. package/dist/providers/cerebras/index.js.map +1 -1
  43. package/dist/providers/cohere/index.cjs +168 -7
  44. package/dist/providers/cohere/index.cjs.map +1 -1
  45. package/dist/providers/cohere/index.d.cts +3 -0
  46. package/dist/providers/cohere/index.d.ts +3 -0
  47. package/dist/providers/cohere/index.js +168 -7
  48. package/dist/providers/cohere/index.js.map +1 -1
  49. package/dist/providers/google/index.cjs +168 -7
  50. package/dist/providers/google/index.cjs.map +1 -1
  51. package/dist/providers/google/index.d.cts +3 -0
  52. package/dist/providers/google/index.d.ts +3 -0
  53. package/dist/providers/google/index.js +168 -7
  54. package/dist/providers/google/index.js.map +1 -1
  55. package/dist/providers/groq/index.cjs +168 -7
  56. package/dist/providers/groq/index.cjs.map +1 -1
  57. package/dist/providers/groq/index.d.cts +3 -0
  58. package/dist/providers/groq/index.d.ts +3 -0
  59. package/dist/providers/groq/index.js +168 -7
  60. package/dist/providers/groq/index.js.map +1 -1
  61. package/dist/providers/huggingface/index.cjs +166 -6
  62. package/dist/providers/huggingface/index.cjs.map +1 -1
  63. package/dist/providers/huggingface/index.js +166 -6
  64. package/dist/providers/huggingface/index.js.map +1 -1
  65. package/dist/providers/mistral/index.cjs +168 -7
  66. package/dist/providers/mistral/index.cjs.map +1 -1
  67. package/dist/providers/mistral/index.d.cts +3 -0
  68. package/dist/providers/mistral/index.d.ts +3 -0
  69. package/dist/providers/mistral/index.js +168 -7
  70. package/dist/providers/mistral/index.js.map +1 -1
  71. package/dist/providers/ollama/index.cjs +168 -7
  72. package/dist/providers/ollama/index.cjs.map +1 -1
  73. package/dist/providers/ollama/index.d.cts +3 -0
  74. package/dist/providers/ollama/index.d.ts +3 -0
  75. package/dist/providers/ollama/index.js +168 -7
  76. package/dist/providers/ollama/index.js.map +1 -1
  77. package/dist/providers/openai/index.cjs +168 -7
  78. package/dist/providers/openai/index.cjs.map +1 -1
  79. package/dist/providers/openai/index.d.cts +3 -0
  80. package/dist/providers/openai/index.d.ts +3 -0
  81. package/dist/providers/openai/index.js +168 -7
  82. package/dist/providers/openai/index.js.map +1 -1
  83. package/dist/providers/together/index.cjs +168 -7
  84. package/dist/providers/together/index.cjs.map +1 -1
  85. package/dist/providers/together/index.d.cts +3 -0
  86. package/dist/providers/together/index.d.ts +3 -0
  87. package/dist/providers/together/index.js +168 -7
  88. package/dist/providers/together/index.js.map +1 -1
  89. package/dist/providers/vercel-ai/index.cjs +163 -6
  90. package/dist/providers/vercel-ai/index.cjs.map +1 -1
  91. package/dist/providers/vercel-ai/index.js +163 -6
  92. package/dist/providers/vercel-ai/index.js.map +1 -1
  93. package/package.json +3 -2
package/CHANGELOG.md ADDED
@@ -0,0 +1,1236 @@
1
+ # Changelog — `risicare` (JS/TS SDK)
2
+
3
+ All notable changes to the JavaScript/TypeScript SDK are documented here.
4
+ Format loosely follows [Keep a Changelog](https://keepachangelog.com/).
5
+ Pre-1.0 (0.x): the MINOR number is the breaking signal. A change that can
6
+ break an existing caller ships as a MINOR bump. Other fixes and additions ship
7
+ as PATCH bumps.
8
+
9
+ ## [0.9.2] — 2026-10-17
10
+
11
+ ### Changed — the npm tarball now carries CHANGELOG.md (issue #95)
12
+
13
+ The npm tarball now carries CHANGELOG.md (#95). Before, it held only `dist/`,
14
+ `README.md`, `LICENSE` and `package.json`. This takes effect at the next
15
+ release.
16
+
17
+ ### Fixed
18
+
19
+ - **The `transport_refused` WARNING gives the number of HTTP requests that the SDK really sent**
20
+ ([#57](https://github.com/Conscience-AI-Labs/risicare-sdk/issues/57)). The WARNING said
21
+ "after 4 failed export rounds each (up to 12 HTTP requests: 3 in each round)". With a 401 or 403
22
+ the SDK sends one request in a round, so the sink received 4. The HTTP exporter now records how
23
+ many requests each `export()` call sent, and the batch processor adds them for the failed
24
+ rounds of each discarded span. The WARNING now says "after 4 failed export rounds each
25
+ (4 HTTP requests sent)". When the spans in one WARNING had different totals, it gives a range
26
+ ("7 to 9 HTTP requests sent"). A round with an open circuit breaker sends 0 requests. A custom
27
+ exporter that has no `takeAttempts(spans)` method keeps the "up to" text, from its
28
+ `attemptsPerExport`. `takeAttempts` is a new optional member of the `SpanExporter` interface.
29
+
30
+ - **A second patch of the same client gives no second span** ([#67](https://github.com/Conscience-AI-Labs/risicare-sdk/issues/67)).
31
+ `patchOpenAI(patchOpenAI(client))` wrapped the client in a new Proxy each time, so one call
32
+ made two LLM spans with the same name. Each `patch*` function now keeps a `WeakSet` of the
33
+ proxies it returned. When you give it one of them, it returns that proxy unchanged. This applies to
34
+ `patchOpenAI`, `patchAnthropic`, `patchBedrock`, `patchCerebras`, `patchCohere`,
35
+ `patchGoogleAI`, `patchGroq`, `patchHuggingFace`, `patchMistral`, `patchOllama` and
36
+ `patchTogether`. A different client still gets its own proxy. `patchVercelAI()` takes no client
37
+ and is not changed.
38
+
39
+ ## [0.9.1] — 2026-10-15
40
+
41
+ ### Changed — a monthly-quota discard is not an error: the SDK pauses and asks again later (metering step S-1)
42
+
43
+ **What changes for you.** When your organisation has used its monthly event quota (for example the
44
+ Free plan), the ingest gateway answers `200` with `reason: "monthly_quota_exceeded"`, the header
45
+ `X-Risicare-Quota: exceeded`, `resetsAt` and `retryAfterSeconds` (300), and discards the batch. Before
46
+ 0.9.1, the SDK counted every such batch as `rejectedSpans`, wrote one WARNING for each batch, and sent
47
+ the next batch at once. Now, for this reason only:
48
+
49
+ - The batch is not retried and is not an error. It does not count toward the circuit breaker, and
50
+ `failedExports` does not change.
51
+ - The exporter pauses for `retryAfterSeconds` (300 s if the answer has none). It never waits until
52
+ `resetsAt`. A value outside 1 s to 3600 s, or one that is not a usable number, is cut to that range
53
+ or becomes 300 s. During the pause the SDK sends no request. Spans that end wait in the existing
54
+ bounded queue. The most recent spans are kept: when the queue is full in the pause, the oldest are
55
+ dropped. After the pause it sends one batch as a probe. When the backend accepts, the queue
56
+ drains. A paid plan or a new event pack is therefore accepted again within minutes, and nothing
57
+ new is lost unless the queue overflows. A probe that is discarded again is dropped and the pause
58
+ starts again. `flush()` returns `false` at once in the pause when spans are queued, and does not
59
+ wait for its timeout. A process that exits in the pause loses the queued spans as
60
+ `shutdown_residue`, and the WARNING names the quota. The pause applies only when every exporter
61
+ that delivers is paused (the SDK has one HTTP exporter, so this matters for a custom exporter
62
+ only). The pause uses a monotonic
63
+ clock (`performance.now()`), so a change of the system clock does not lengthen it.
64
+ - The SDK writes one WARNING when the pause starts (with `resetsAt` and the retry interval), and at
65
+ most one more each hour for the life of the process. It carries the number of spans dropped for
66
+ the quota since the last WARNING. The "Span queue full" WARNING is not written for these drops. A pause ends after 3 accepted batches in a
67
+ row, not 1: the gateway can let one batch through while the quota is still used up. It then
68
+ writes one INFO, also at most once an hour.
69
+ - The spans that the quota dropped are counted as `quota_exceeded`:
70
+ `getMetrics().droppedSpansByReason.quota_exceeded`, and the same number as
71
+ `getMetrics().droppedQuota`. A span is counted only when a discarded batch is dropped or the queue
72
+ overflows in the pause. They are not in `rejectedSpans`. A drop is a loss, so one `flush()`
73
+ returns `false`, as for every other loss. **Alerts:** the deprecated flat `droppedSpans` includes
74
+ these spans, so an alert on `droppedSpans > 0` fires at the quota. An alert on `rejectedSpans` does
75
+ not fire for a quota discard any more (before 0.9.1 it did).
76
+ - `X-Risicare-Quota: exceeded` alone counts as a discard only when the body does not show stored
77
+ spans (`accepted > 0`).
78
+
79
+ Every other rejection reason, and every other answer, behave as in 0.9.0.
80
+
81
+ **What to do.** Nothing. To see how many spans the quota cost you, read `getMetrics().droppedQuota`.
82
+
83
+ **Compatibility.** An old gateway never sends this reason, so it changes nothing there. An old SDK
84
+ (before 0.9.1) keeps its old behaviour against a new gateway: it sends every batch and it is
85
+ discarded at low cost.
86
+
87
+ ## [0.9.0] — 2026-10-07
88
+
89
+ > Several entries below change a return value or a behaviour that an existing caller can see. Each one says what
90
+ > changes for you and what to do. Issues [#86](https://github.com/Conscience-AI-Labs/risicare-sdk/issues/86)
91
+ > (`flush()` tells the truth) and [#87](https://github.com/Conscience-AI-Labs/risicare-sdk/issues/87)
92
+ > (no key, no network; the state agrees).
93
+
94
+ ### `flush()` after `shutdown()`, and `flush()` during a drain, now tell the truth
95
+
96
+ **What changes for you.** Two cases returned `true` with spans not delivered. They now return the real outcome.
97
+
98
+ - A `flush()` that ran after the SDK's own drain started (your SIGTERM or SIGINT listener, registered after
99
+ `init()`) returned `true` in 0 ms, with the batch still in flight. It now waits for that drain, inside its own
100
+ deadline, and returns what the drain delivered. The same holds for a `flush()` that you call while a
101
+ `shutdown()` that you did not await still runs.
102
+ - A `flush()` after `shutdown()` returned `true` after a `transport_refused` drop or a rejection. It now returns
103
+ `false`, one time, when a span was lost since the previous `flush()` returned. A shutdown that left spans
104
+ (`shutdown_residue`) is reported one time too, like every other loss: the next `flush()` is `true` again. Before,
105
+ it stayed `false` for good.
106
+ - A span that ended while the SDK's drain, or a `shutdown()` of yours, was running (for example in your SIGTERM
107
+ listener, after the SDK's own listener had started the drain) was dropped with no count, and `flush()` returned
108
+ `true`. It now joins the drain and is delivered before the drain ends. A span that ends after the drain has stopped
109
+ taking spans (nothing was left to export, a round failed, or its time ended) is counted as `shutdown_residue`, with
110
+ one WARNING for the first such span, and one `flush()` returns `false`. After `shutdown()`, `getMetrics()` shows that count too.
111
+
112
+ **What to do.** Nothing, when you check the result of `flush()`. If your code ignored a `true` that was wrong,
113
+ you now see the `false`. Read `getMetrics()` (`droppedSpansByReason`, `rejectedSpans`, `failedScores`): a `false`
114
+ at the deadline with none of them raised means that the spans are still in flight. *Can break an existing caller.*
115
+
116
+ ### Your SIGTERM or SIGINT listener runs once, in both orders of registration
117
+
118
+ **What changes for you.** When your listener was registered after `init()`, the SDK raised the signal again after
119
+ its drain. Your listener ran a second time, and, if it was still running 100 ms later, the SDK ended the process
120
+ with exit code 143, so your listener could not finish. Now, when your application has a listener for the signal at
121
+ the moment the signal arrives, the SDK does not raise the signal again and does not end the process. Your listener
122
+ runs once and decides the exit, as it did when you registered it before `init()`. When you have no listener at that
123
+ moment, nothing changes: after its drain the SDK raises the signal again, so that the default action ends the
124
+ process. A listener that you add during the drain runs on that second signal, as before.
125
+
126
+ The order of registration still changes which spans your listener makes are delivered. Node calls the SDK's
127
+ listener first when you register yours after `init()`. A span that such a listener ends can miss the SDK's drain
128
+ (when the drain has stopped taking spans: nothing was left to export, a round failed, or its time ended). It is then
129
+ counted as `shutdown_residue`, and one `flush()` returns `false`. In both orders, `flush()` reports the real outcome.
130
+
131
+ **What to do.** Nothing. If you relied on the exit code 143 after your own listener, call `process.exit(143)`
132
+ yourself. If your listener must make spans that are delivered, register it before `init()`, or end the spans before
133
+ the signal. *Can break an existing caller.*
134
+
135
+ ### `score()` that refuses its input counts as a failed score
136
+
137
+ **What changes for you.** A score with a value outside 0 to 1 (or not a number), or with an empty trace id or name,
138
+ already wrote a WARNING and was not sent. It now also adds 1 to `failedScores`, so the next `flush()` returns
139
+ `false`, one time. When the SDK is not active (before `init()`, after `shutdown()` or the SDK's own drain, tracing
140
+ off, no key), nothing is counted.
141
+
142
+ **What to do.** Pass a value from 0 to 1. If a `flush()` that returned `true` before now returns `false`, look for
143
+ the `score:` WARNING in your log.
144
+
145
+ ### No API key: nothing is sent, tracing is off, `flush()` is `false`
146
+
147
+ **What changes for you.** With no API key (or an empty one), `RISICARE_TRACING=true`, `enabled: true` and
148
+ `enable()` no longer turn tracing on. Before, `isEnabled()` was `true`, the SDK created spans, queued them and
149
+ dropped them after four export rounds as `transport_refused`, and `flush()` returned `false` once and then `true`.
150
+ No request was sent in that case, but the WARNING told you to "check the endpoint". Now `isEnabled()` is `false`,
151
+ no span is created, `flush()` returns `false`, and nothing is counted as exported or dropped. The SDK writes one
152
+ WARNING at `init()`: there is no API key, nothing is sent to Risicare, `flush()` returns `false`, and how to set
153
+ the key. There is no WARNING when you turned tracing off on purpose (`enabled: false`, `RISICARE_TRACING=false`).
154
+ The old "tracing is enabled but NO API key is configured" notice and the later "DISCARDED" WARNING are gone.
155
+
156
+ **What to do.** Set `RISICARE_API_KEY` or pass `apiKey` to `init()`. If your tests or your CI ran with no key and
157
+ `RISICARE_TRACING=true`, and your code treated `flush()` as `true`, they now see `false`. *Can break an existing
158
+ caller.*
159
+
160
+ ### `debug: true` with no API key prints no span
161
+
162
+ **What changes for you.** With no key and tracing forced on (`RISICARE_TRACING=true` or `enabled: true`),
163
+ `debug: true` printed each span as JSON to stderr, and the SDK counted the printed spans as exported, so `flush()`
164
+ returned `true` with nothing delivered. (With no key and tracing not forced, tracing was already off, and `debug: true`
165
+ printed no span.) Now no span exists without a key, so nothing is printed and nothing is counted. `debug: true`
166
+ still writes the SDK's own debug lines.
167
+
168
+ **What to do.** For local output, use an API key and a loopback test server, or read `getMetrics()`. *Can break an
169
+ existing caller.*
170
+
171
+ ### An empty or whitespace API key: no key, and `RISICARE_API_KEY` is the fallback
172
+
173
+ **What changes for you.** The SDK now trims the API key, from the `apiKey` option and from `RISICARE_API_KEY`. A key
174
+ that is only whitespace is no key: before, it counted as a key, so the SDK built an exporter and sent
175
+ `Authorization: Bearer` with no token (to the default hosts, when you set no endpoint). Now it is the no-key state
176
+ above. An `apiKey` option that is empty, or only whitespace, counts as "not given", and the SDK uses
177
+ `RISICARE_API_KEY`, as the Python SDK does. Before, an empty `apiKey` option won over the variable and gave no key.
178
+ A key with spaces or a newline around it is sent trimmed.
179
+
180
+ **What to do.** Nothing, unless you pass `apiKey: ''` to turn tracing off: use `enabled: false` for that. *Can break
181
+ an existing caller.*
182
+
183
+ ### `flush()` returns `false` when the SDK is not active
184
+
185
+ **What changes for you.** `flush()` returned `true` before `init()`, and with tracing off at `init()` (`enabled: false`,
186
+ `RISICARE_TRACING=false`), because nothing was queued. It now returns `false`: the SDK has no evidence of delivery.
187
+ `disable()` after spans were accepted does not change the answer for those spans.
188
+
189
+ **What to do.** If your code stops on a `false` from `flush()` while tracing is off on purpose (a test run, a local
190
+ run), check `isEnabled()` first. *Can break an existing caller.*
191
+
192
+ ### `isEnabled()` is `false` after the SDK's own drain at SIGTERM or SIGINT
193
+
194
+ **What changes for you.** After the SDK's drain ended, `isEnabled()` was still `true` over a processor that was shut
195
+ down (`getMetrics().sdkState` already said `shutdown`). It is now `false`, as after your own `shutdown()`.
196
+
197
+ **What to do.** Nothing.
198
+
199
+ ### Documentation
200
+
201
+ - A new `init()` (after `shutdown()`) starts a new count. A loss that nobody reported with `flush()` before is not
202
+ carried over. Report it with `flush()` or `getMetrics()` before you call `init()` again.
203
+ - `failedExports` is not a loss counter. It counts the export calls that failed as a whole, and a later round can
204
+ still deliver those spans. The loss counters are `droppedSpansByReason`, `rejectedSpans` and `failedScores`.
205
+
206
+ ## [0.8.0] — 2026-10-04
207
+
208
+ > Several entries below can break an existing caller; each one says so. Version 0.7.1 was not published, so its
209
+ > entry below ships in this release.
210
+
211
+ ### Fixed
212
+
213
+ - **`flush()` no longer waits for a stalled response body.** The request
214
+ timer now covers the read of the ack body. Before, a server that sent the
215
+ headers and then stopped held `flush()` for about 5 minutes and the process
216
+ for about 10 minutes.
217
+ - **A refused connection no longer keeps the process alive** for about 5 s
218
+ after `flush()`. Each request timer is cleared when its request ends.
219
+ - **`shutdown(timeoutMs)` keeps its budget.** At the deadline it stops the
220
+ export that is in progress, so the process can exit. The stopped export
221
+ changes no counter, and its spans are counted as `shutdown_residue`. Before,
222
+ one export round against a server that did not answer took 15 s with a 5 s
223
+ budget, and an export that the batch timer started kept the process alive
224
+ for up to 15 s after `shutdown()` returned.
225
+ - **`flush()` after `shutdown()` returns `false`** when that shutdown left
226
+ spans that were not delivered. Before, it returned `true`. *Can break an
227
+ existing caller.*
228
+ - A `timeoutMs` that is not a finite number gives the default, 5000 ms. A
229
+ negative value gives 0. The largest value is 2**31 - 1.
230
+ - A reason text from the server is printed as one line. Control characters
231
+ become spaces.
232
+ - The console exporter (`debug: true`) does not count as a delivery when
233
+ another exporter is present. Before, its success hid a failed export.
234
+ - The 429, `transport_refused` and `shutdown_residue` WARNINGs say what the
235
+ SDK does. The `transport_refused` WARNING gives the number of export rounds
236
+ and the number of HTTP requests. The `shutdown_residue` WARNING says that
237
+ the spans were not confirmed as delivered.
238
+ - **A span that cannot be serialized (a BigInt, a circular value) is not
239
+ sent, and it does not make its batch fail.** It is dropped at once as
240
+ `unacknowledged`, with one WARNING for the batch that gives the error
241
+ class. Before, the batch failed four export rounds with no request, and the
242
+ WARNING named the endpoint and the API key as the cause.
243
+ - An exporter or a `mask` function that throws a value that cannot become a
244
+ string does not make `flush()` throw. Before, that batch was in no counter.
245
+ - **`shutdown(timeoutMs)` gives the `shutdown()` of each exporter only the
246
+ time that is left of the budget.** Before, an exporter whose `shutdown()`
247
+ did not end held the process.
248
+ - Two batch processors that share one HTTP exporter do not read the ack of
249
+ each other.
250
+ - **A guard pattern in the Python dialect now works** (only with
251
+ `fixRuntime: true`): a leading `(?i)`, `(?s)` or `(?m)` group, `\A`, `\Z`,
252
+ `(?P<name>` and `(?P=name)`. Before, a `(?i)` pattern was ignored and the
253
+ guard passed. A backslash and a letter that JavaScript and Python read
254
+ differently, and a group name used two times, now reject the call. *Can
255
+ break an existing caller.*
256
+ - A blocked pattern that is not usable (not a list of strings, empty, longer
257
+ than 500 characters, or it does not compile) now rejects the call. One
258
+ WARNING for each fix and pattern gives the fix id and the pattern index.
259
+ *Can break an existing caller.*
260
+ - The rejection reason gives the pattern index (`blocked pattern matched
261
+ (pattern N)`), not the pattern. A literal pattern is the blocked text.
262
+ - The input guards check the text parts of list content.
263
+ - **`score()` reports a failed request.** An HTTP status of 300 or more, an
264
+ error or a timeout adds 1 to `failedScores`. The first failure logs one
265
+ WARNING with the score name and the status or the error code. Later failures
266
+ in the next 10 s are counted, and the next WARNING gives their number and
267
+ the last reason. Before, the SDK did not read the status.
268
+ - **A `score()` request stops after 2000 ms.** Before, a server that did not
269
+ answer kept the process alive for about 300 s.
270
+ - **`score()` does not follow a redirect.** Before, a 307 sent the score a
271
+ second time to the redirect target.
272
+ - The WARNING for a score value that is not a number gives the type of the
273
+ value, not the value.
274
+ - An empty `endpoint`, `apiEndpoint`, `RISICARE_ENDPOINT` or
275
+ `RISICARE_API_ENDPOINT`, or one with ASCII whitespace only, is the same as
276
+ no value. Before, the SDK used the empty text as the endpoint.
277
+ - **`Span` and `Tracer` are types only.** The type declarations exported them
278
+ as values, but the package has no such values. A program that uses them as
279
+ values now fails to compile; before, it compiled and failed when it loaded
280
+ (`import { Span }` gave a SyntaxError). Use `import type { Span, Tracer }`.
281
+ *Can break an existing caller.*
282
+ - `getCurrentContext()` returns the documented type and still permits other
283
+ keys. `extractTraceContext()` accepts Node `req.headers` and uses the first
284
+ value of a list.
285
+ - `session()` accepts a resolver with fewer parameters than the function. The
286
+ curried form accepts typed parameters. The 0.7.1 forms still compile.
287
+ - `getTraceContext()` keeps its trace id in each context scope, not only in a
288
+ session or agent scope. Each later root span in that scope uses the id.
289
+ - An empty `environment` gives `development`, as in the Python SDK.
290
+ - **The API key hint is a WARNING at the default log level.** Before, it was
291
+ a debug line that ran before the debug setting was applied, so it did not
292
+ print. The WARNING contains no part of the key.
293
+ - Error text that the SDK cuts before export (`error.message` at 2,000,
294
+ `error.stack` at 4,000, the error status summary at 500) is cut by code
295
+ points. A cut does not divide an emoji, so a strict JSON parser does not
296
+ refuse the batch.
297
+ - README: `patchGoogleAI` (not `patchGoogle`), the `OpenAI` import,
298
+ `withSession` in the Sessions sample, and the wrapper calls in Core API.
299
+ - **The Vercel AI wrappers read `inputTokens` and `outputTokens`.** On `ai`
300
+ 5.x and later the result has these names, and the span had 0 tokens and a
301
+ cost of 0. The old names `promptTokens` and `completionTokens` still work.
302
+ A token count that is absent or not a number stays unset, and the span gets
303
+ no cost unless both counts are known.
304
+ - **`error.code` is now the same as in the Python SDK** on the shared fixture
305
+ of 147 error inputs. JavaScript applies the risicare-core keyword rules
306
+ first. It changes the text to lower case as Python does, and it matches `.`
307
+ and word boundaries as Python does. Some errors get a different, more
308
+ specific code: for example "worker process crashed" was
309
+ `TOOL.EXECUTION.CRASHED` and is `ORCHESTRATION.LIFECYCLE.CRASHED`.
310
+ Dashboards and alerts that use the old JavaScript codes can change. An
311
+ error that no rule matches is still `TOOL.EXECUTION.CRASHED`, in both SDKs.
312
+ *Can break an existing caller.*
313
+ - A thrown value that is not an `Error` is classified by its own `message`
314
+ text.
315
+ - **A 401 or 403 answer is sent once in each export call.** The SDK does not
316
+ send the request again in that call. Before, one span against an endpoint
317
+ that answers 401 gave 12 requests; now it gives 4 (one for each export
318
+ round).
319
+ - **The SDK removes its API key from every text that it writes.** This covers
320
+ a redirect target, a `Content-Type`, a `Retry-After` value, the reasons of
321
+ a rejection and every error text, in the HTTP exporter, the batch
322
+ processor, the fix loader and `score()`. The key is removed in any case of
323
+ letters, and also when it is percent-encoded. Before, a server that
324
+ answered with a redirect whose `Location` held the key, or with a
325
+ `Content-Type` that held it, put the key in the output.
326
+ - An endpoint is written without its user name, password and query (scheme,
327
+ host, port and path only). A secret that you put in the path of a URL is
328
+ written as you gave it.
329
+ - The export WARNING names the API key as a cause only for a 401 or a 403.
330
+ For another status it says that the server did not take the batch; for no
331
+ answer it says that the endpoint cannot be reached.
332
+ - `util.inspect()` of the config, the HTTP exporter and the fix loader does
333
+ not show the API key.
334
+ - An endpoint URL with credentials gives a WARNING that says so (`fetch` does
335
+ not support it). Before, the WARNING named the API key and the endpoint as
336
+ the cause.
337
+ - **At most 50 score requests are in flight at one time**; the others wait
338
+ for a free slot. Before, a burst of scores could fail with a connection
339
+ error when the server accepted connections slowly.
340
+ Up to 1,000 scores wait for a free slot, and a score that waits has no
341
+ timer: the bound of its request starts when the request starts. A score
342
+ that arrives when 1,000 already wait fails at once and is counted (`not
343
+ sent: 1000 scores wait for a free slot`). When the bound of `flush()`, of
344
+ shutdown or of exit ends, the scores that still wait fail (`not sent before
345
+ the deadline`), and the SDK does not send them.
346
+ - **A provider response that the SDK did not expect does not make your call
347
+ reject.** The SDK reads each response in a guard: a failure costs only
348
+ facts of the span. This applies to the OpenAI, Anthropic, Google and Vercel
349
+ AI responses and to the Ollama, Cohere, Mistral and Google streams. Before,
350
+ a null result, a null chunk or an object that throws on property access
351
+ made the call reject.
352
+ - When the SDK cannot read a provider response, the span gets the attribute
353
+ `risicare.observer_error` (the class name of the error), and its status
354
+ stays ok. With `debug: true`, one line gives the provider, the place and
355
+ the class, at most one time for each. It does not contain the error
356
+ message. Before, that line could hold prompt text and an API key of the
357
+ provider.
358
+ - **A traced OpenAI, Anthropic, Groq, Together or Cerebras call returns the
359
+ promise object of the provider's SDK** (`APIPromise`). `withResponse()` and
360
+ `asResponse()` work. Before, the patch returned a plain `Promise`, and
361
+ those methods did not exist.
362
+ - **`messages.stream()` works on a patched Anthropic client.** Before, it
363
+ failed with "withResponse is not a function".
364
+ - **`patchHuggingFace` works with `InferenceClient` 4.x.** Before, each
365
+ `chatCompletion` call on a patched client threw a `TypeError`.
366
+ - **A traced Cohere, Mistral, Ollama or Google stream is the stream object of
367
+ the provider's SDK.** `controller`, `getReader()`, `tee()`, `cancel()`,
368
+ `abort()`, `next()` and `withRawResponse()` work. Before, the patch
369
+ returned a new object that had only the async iterator.
370
+ - **The span of a streamed call ends when the stream ends, stops, aborts or
371
+ fails**, and it has the chunk count and the token counts. Before, the span
372
+ of an OpenAI, Anthropic, Groq, Together or Cerebras stream ended when the
373
+ stream object arrived, before one chunk was read. `shutdown()` ends the
374
+ span of a stream that nobody read.
375
+ - Vercel AI `streamText` and Hugging Face `chatCompletionStream` are traced.
376
+ - The span of a Cohere V2 `chatStream` call has the token counts.
377
+ - The Ollama span has `llm.stream: true` only for a call that streams.
378
+ - **A stream span ends when the caller stops reading and drops the stream
379
+ while a `next()` waits.** The span ends with `stream.end_reason = garbage`
380
+ when the waiting chunk arrives. Before, such a span stayed open until
381
+ `shutdown()` and was lost when the process ended without it (measured:
382
+ 2,000 streams with a read timeout, 2,000 spans open, 0 exported).
383
+ - **A fault in the SDK's own observation of a call does not reach the
384
+ caller.** The call goes on, and its span gets `risicare.observer_error`.
385
+ - Hugging Face: a getter of a subclass can read its private field, and a
386
+ client that is frozen before the patch reads as frozen.
387
+ - The README section "Streaming" describes the stream span as it is: when
388
+ it ends, each `stream.end_reason`, the token source of each provider, and
389
+ the limits.
390
+ - Google: a caller that awaits only `result.response` and does not read the
391
+ stream gets one span. It ends as `done` when the response settles, with
392
+ its tokens. Before, that span ended as `garbage` after some milliseconds,
393
+ with no tokens.
394
+ - Hugging Face: a getter that returns the client gives the patched client,
395
+ so calls through it are traced.
396
+ - **A failed first load of the fixes (`fixRuntime: true`) logs one WARNING**
397
+ with the request URL (no userinfo, no query, no key), the HTTP status or
398
+ the error class, and the fact that tracing is not affected. Before, it
399
+ logged nothing.
400
+ - The WARNING for a FixRuntime that cannot be built names the api host
401
+ (`apiEndpoint`). No known fault reaches that line; a failed first load
402
+ gives the WARNING above.
403
+
404
+ ### Changed
405
+
406
+ - **`flush()` returns `false` at its deadline**, and when a span was dropped,
407
+ rejected or not acknowledged since the previous `flush()` returned. A loss
408
+ makes the next `flush()` return `false` one time, also when it occurred
409
+ while no flush ran. `flush()` only waits: it does not stop a request that is
410
+ already sent, and an export that is in progress continues after the
411
+ deadline. To end a process in a fixed time, call
412
+ `await shutdown(timeoutMs)`. *Can break an existing caller.*
413
+ - **`exportedSpans` rises by the `accepted` count of the ack**, limited to
414
+ the number of spans in the batch. A rejection is believed before an
415
+ acceptance: when an ack names more spans than the batch holds, the rejected
416
+ spans are counted first. Before, a partial rejection counted the full batch.
417
+ *Can break an existing caller.*
418
+ - **An ack of 0 accepted and 0 rejected for a batch that has spans is a
419
+ failure**, with one WARNING. Before, it counted the batch as exported. *Can
420
+ break an existing caller.*
421
+ - **An ack that rejects every span is counted in `rejectedSpans`.** The batch
422
+ is not sent again, and the circuit breaker does not count it. Before, the
423
+ batch was sent 12 times and then dropped as `transport_refused`. *Can break
424
+ an existing caller.*
425
+ - **`RISICARE_TRACING` has one set of values, the same as in the Python SDK.**
426
+ The value is trimmed and case is ignored. `true`, `1`, `yes` and `on` turn
427
+ tracing on. `false`, `0`, `no` and `off` turn it off. An empty value is the
428
+ same as no value. Any other value turns tracing off and logs one WARNING.
429
+ Before, `on`, a value with spaces and an empty value turned tracing off with
430
+ no message. *Can break an existing caller.*
431
+ - The WARNING for a rejection gives at most 3 different reasons from the ack.
432
+ - The JSDoc and the README say what FixRuntime does. The JSDoc no longer says
433
+ that a span records a guard rejection: no span records it.
434
+ - **The SDK chooses the host for scores and fix reads in a new order**:
435
+ (1) the `apiEndpoint` option; (2) the `endpoint` option, unless it is
436
+ the default ingest host; (3) `RISICARE_API_ENDPOINT`; (4) `RISICARE_ENDPOINT`,
437
+ if you gave no `endpoint` option and it is not the default ingest host;
438
+ (5) `https://api.risicare.ai`. Before, `RISICARE_API_ENDPOINT` came before
439
+ the `endpoint` option, and `endpoint: 'https://ingest.risicare.ai'` sent
440
+ scores to the ingest host, which has no scores route. The default ingest
441
+ host never names an api host, so your key does not go to a host that you
442
+ did not name. *Can break an existing caller.*
443
+ - **`flush()` waits for score requests that are not complete**, inside its
444
+ timeout. It returns `false` when a score failed since the previous `flush()`
445
+ returned. Each failed score makes one `flush()` return `false`. *Can break
446
+ an existing caller.*
447
+ - A score value out of the range 0 to 1, or a `traceId` or `name` that is
448
+ empty or has whitespace only, logs a WARNING. Before, it was a debug line.
449
+ `true` and `false` are accepted as 1 and 0, as in the Python SDK.
450
+ - **An `agent()` with no name uses the function name**, as in the Python SDK.
451
+ A bound function uses the name of the original function. Before, each
452
+ such agent had the name `agent`. The stored agent names and ids change.
453
+ *Can break an existing caller.*
454
+ - **A phase span with no name is `<phase>:<function>`** (for example
455
+ `think:analyzeQuery`), as in the Python SDK. Before, it was `phase:think`.
456
+ The stored span names change. *Can break an existing caller.*
457
+ - With no API key, the SDK logs one WARNING: "Risicare found no API key.
458
+ Tracing is off and the SDK sends no span."
459
+ - **A token count that the provider did not give is not sent.** Before, the
460
+ SDK sent 0, with a total and a cost computed from it. A real 0 is kept: the
461
+ Ollama patch dropped a real 0 before. The cost is computed only when both
462
+ counts are known. *This can change what a dashboard shows.*
463
+ - **The object that a traced provider call returns is a `Proxy` of the
464
+ provider's own object.** `await`, `instanceof` and the methods work as on
465
+ the provider's object. *Can break an existing caller.* What a caller can
466
+ see:
467
+ - `util.types.isPromise(p)` is false for the promise of a traced call
468
+ (OpenAI, Groq, Together, Cerebras, Anthropic, Cohere: each call; Google,
469
+ Mistral, Ollama: stream calls).
470
+ - `Promise.resolve(p) === p` is false for a Google, Mistral or Ollama
471
+ stream call. Before, it was true.
472
+ - A traced call takes more microtask ticks to resolve: 1 more for OpenAI,
473
+ Groq, Together, Cerebras, Anthropic and Cohere (`await` on an OpenAI
474
+ call: 4 ticks, 3 without the SDK), and 3 more for a stream call of
475
+ Google, Mistral or Ollama (4 ticks, 1 without the SDK). The extra tick
476
+ keeps your own frame in the stack of a timeout or abort error.
477
+ - `util.inspect()` shows a `Proxy`.
478
+ - The span of a stream has the new attribute `stream.end_reason` (`done`,
479
+ `return`, `abort`, `error`, `handoff`, `garbage` or `shutdown`), and its
480
+ duration includes the time to read the stream. A stream that was aborted
481
+ has the status error and the attributes `risicare.cancelled` and
482
+ `risicare.cancel_type`. An abort that does not stop the stream (Cohere's
483
+ controller) is not an abort: the span follows what the stream does, also
484
+ when the stream is dropped or is still open at `shutdown()`. For Cohere,
485
+ only the request option `abortSignal` makes an abort.
486
+ - The shared state of the provider spans has `version: 1`. A second copy of
487
+ the SDK in the process that finds a state of another version does not use
488
+ it: its calls go on, not observed.
489
+ - **`gen_ai.tool.definitions` is a content key** (shared content-key corpus,
490
+ version 2). When content capture is off, the SDK replaces the value of this
491
+ attribute by the omission marker, as it does for prompts and completions.
492
+ The SDK does not set this attribute itself in this release.
493
+
494
+ ### Added
495
+
496
+ - **A `timeoutMs` argument on the root `flush()` and `shutdown()`.** The
497
+ default is 5000 ms. The two functions were in 0.7.0 with no argument.
498
+ - **`getMetrics().rejectedSpans`**: the number of spans that the backend
499
+ acknowledged and rejected.
500
+ - **The drop reason `unacknowledged`** in `droppedSpansByReason`: spans that
501
+ were sent, or that could not be serialized, and that the ack did not
502
+ account for.
503
+ - **`getMetrics().failedScores`**: the number of score requests that failed.
504
+ - **With `traceContent: true`, `patchOpenAI` and `patchAnthropic` capture the
505
+ prompt and completion text.** Before, no JavaScript provider captured text,
506
+ although the option existed. The keys and limits are those of the Python
507
+ SDK (the limits count code points). A streamed call gives the prompt only.
508
+ Other providers capture no text. The text of an error from a provider is
509
+ sent also when `traceContent` is off.
510
+ - README sections "Two hosts" and "Imports".
511
+ - **A WARNING at the first failed export of an outage**, at most one in
512
+ 300 s. It names the HTTP status, or the error code when there was no
513
+ answer. For 401 and 403 it tells you to check the API key. Before, the
514
+ JavaScript SDK wrote no line when an export failed.
515
+ - A change of the kind of failure in one outage (for example a 401, then no
516
+ answer) writes one more WARNING.
517
+ - **An aborted call (`AbortError`) gets the attributes `risicare.cancelled`
518
+ and `risicare.cancel_type`.** Its status stays error, as in 0.7.0.
519
+
520
+ ## [0.7.1] — 2026-09-29
521
+
522
+ ### Fixed
523
+
524
+ - **The API key format hint in `init()` now recognizes the new checksummed
525
+ key formats, `rski_` (Ingest) and `rsks_` (Secret), alongside the existing
526
+ `rsk-` legacy format.** Before this release, `init({ apiKey: 'rski_...' })`
527
+ printed a spurious `debug` warning ("API key should start with \"rsk-\"").
528
+ This is a hint only — it never blocked init() or disabled the client — but
529
+ the warning was wrong and confusing to anyone trying the new format early.
530
+ Old `rsk-` keys keep working unchanged; no other behavior changes.
531
+
532
+ This release ships ahead of the api minting any `rski_`/`rsks_` key, per the
533
+ key-model design's own ordering.
534
+
535
+ ## [0.7.0] — 2026-09-26
536
+
537
+ ### ⚠ Licence change — proprietary, not MIT, from this release
538
+
539
+ This package used the MIT licence up to and including 0.6.0. This release,
540
+ 0.7.0, and every later release use a proprietary licence instead. See the
541
+ `LICENSE` file.
542
+
543
+ The proprietary licence is a commercial EULA. It forbids you to change the
544
+ SDK, to make derivative works from it, to reverse-engineer it, and to give
545
+ it to another party. You need an active, paid subscription to use it.
546
+
547
+ Published versions keep their old licence. Version 0.6.0, and every version
548
+ before it, stays under MIT. Registry rules do not let anyone change a
549
+ published version's licence.
550
+
551
+ ### Behaviour changes — read before you upgrade
552
+
553
+ - **FixRuntime is now off by default.** To keep it, set
554
+ `init({ fixRuntime: true })`.
555
+ - **The default endpoints changed.** Set `endpoint` and `apiEndpoint`
556
+ explicitly if you self-route.
557
+ - **A redirect, or a 2xx with no Risicare ack, is now a failure.**
558
+ - **The content gate strips more keys when `traceContent` is off.**
559
+
560
+ > ⚠ **THE DEFAULT HOST CHANGES, AND THE `/api` PREFIX IS GONE.** Shipped
561
+ > because the old default did not work: `https://app.risicare.ai` is the
562
+ > production DASHBOARD, and measured 2026-09-19 it resolves but does not
563
+ > accept connections. The change removes a false promise, not a function.
564
+
565
+ > **Both hosts are live.** `ingest.risicare.ai` serves the ingest gateway
566
+ > and `api.risicare.ai` serves the api. Older SDKs that still send spans to
567
+ > `app.risicare.ai` keep working for now through a temporary route. That
568
+ > route will be removed, so move to the new defaults.
569
+
570
+ ### Two hosts
571
+
572
+ | Shape | Was | Now | Serves |
573
+ |---|---|---|---|
574
+ | A | `{endpoint}/v1/spans` | unchanged path, new default host | the ingest gateway |
575
+ | B | `{apiEndpoint}/api/v1/fixes/active` | `{apiEndpoint}/v1/fixes/active` | the api |
576
+ | C | `{endpoint}/api/v1/scores` | `{apiEndpoint}/v1/scores` | the api |
577
+
578
+ The `/api` prefix was a Caddy artifact and the split has no Caddy. Shape C also
579
+ read the span endpoint and composed an api path; it now reads `apiEndpoint`.
580
+ `score()` is fire-and-forget, so that was a silent 404 in waiting.
581
+
582
+ ### `apiEndpoint` / `RISICARE_API_ENDPOINT`, with a one-variable fallback
583
+
584
+ Setting only `RISICARE_ENDPOINT` still points both shapes at that one host.
585
+ Order: explicit `apiEndpoint`, `RISICARE_API_ENDPOINT`, explicit `endpoint`,
586
+ `RISICARE_ENDPOINT`, default.
587
+
588
+ ### ⚠ Who this breaks
589
+
590
+ A Caddy-fronted single-host deployment that relied on the proxy stripping
591
+ `/api`. Pin `risicare@0.6.0`, or drop the strip from the proxy.
592
+
593
+ ### Fixed
594
+
595
+ - `tests/endpoint-hosts.test.ts` pins all three shapes, and the JS SDK had no
596
+ default-host test at all before this release because `tests/setup.ts` pins
597
+ `RISICARE_ENDPOINT` before any test runs.
598
+ - `tests/setup.ts` refuses `ingest.risicare.ai` as well, so the production-leak
599
+ guard covers the new host.
600
+ - `package-lock.json` declared `0.4.0` against a published `0.6.0`. Corrected.
601
+
602
+ ### ⚠ FixRuntime is opt-in
603
+
604
+ Through 0.6.0, `init()` started FixRuntime whenever an `apiKey` was set and
605
+ tracing was enabled (`client.ts`, `enabled: true`). FixRuntime polls
606
+ `/fixes/active` every 60 seconds and applies prompt, parameter, tool, retry,
607
+ fallback, guard and routing fixes, at 100 % traffic by default. So the server
608
+ could change a customer's agent, and the customer did not ask for it.
609
+
610
+ Now FixRuntime starts only on an explicit opt-in:
611
+
612
+ - `init({ ..., fixRuntime: true })`, or
613
+ - the environment variable `RISICARE_FIX_RUNTIME=true` (also `1`, `yes`).
614
+
615
+ The option has priority over the environment variable. The default is off.
616
+ When it is off, nothing polls `/fixes/active`, no fix is applied, and the SDK
617
+ writes one debug line that says so (with `debug: true`).
618
+
619
+ **Who this changes:** a customer who relied on automatic fix application. Add
620
+ `fixRuntime: true` to keep it.
621
+
622
+ Tests: `tests/fixruntime-opt-in.test.ts` observes the wire with a local HTTP
623
+ server. Off by default, on by the option, on by the environment variable.
624
+
625
+ ### The content gate now covers the OTel GenAI, OpenInference and CrewAI keys
626
+
627
+ With `traceContent: false`, 0.6.0 passed `input.value`, `output.value`,
628
+ `gen_ai.input.messages`, `gen_ai.output.messages`,
629
+ `gen_ai.system_instructions`, a bare `gen_ai.prompt` and `gen_ai.completion`.
630
+ The old rule stripped only a last segment `content`, a suffix `_content`,
631
+ and two exact keys.
632
+
633
+ `isContentKey` now implements canonical content-key spec v1: 15 spec keys
634
+ and 9 keys from the OTel GenAI, OpenInference and OpenLLMetry conventions,
635
+ added on a fail-closed decision — a doubtful key is treated as content. All
636
+ 58 keys this SDK's own providers and frameworks set already carry no
637
+ content, so this closes a gap for third-party OTel data on the same span, not
638
+ the SDK's own instrumentation. A shared, versioned fixture
639
+ (`tests/fixtures/content-keys-v1.json`) is byte-identical to the Python
640
+ SDK's copy and matches what the ingest gateway enforces.
641
+
642
+ A gated field is replaced with `<risicare:content-omitted>`, not deleted, so
643
+ "no content was sent" stays distinguishable from "capture is off". `mask` is
644
+ unaffected.
645
+
646
+ Tests: `tests/content-keys-v1.test.ts` pins the corpus, the precedence
647
+ rules, and an end-to-end check through the real batch processor, with
648
+ `traceContent: true` as a control.
649
+
650
+ ### An export never follows a redirect, and a 2xx without a Risicare ack is a failure
651
+
652
+ Through 0.6.0, the default `https://app.risicare.ai` answered `POST
653
+ /v1/spans` with a 307 redirect to the dashboard login page. `fetch` follows
654
+ a redirect by default, so the SDK sent the request again, received an HTML
655
+ 200 login page, and `checkAck` treated an unparseable body as SUCCESS. Every
656
+ span was lost, and the SDK reported success.
657
+
658
+ Now the exporter sends `fetch(..., { redirect: 'manual' })`. A 3xx response
659
+ (or a browser-like `opaqueredirect`), or a 2xx whose body is not `{accepted,
660
+ rejected}`, is a FAILURE: it is not retried within the same export, it
661
+ counts toward the circuit breaker, and it gives one rate-limited warning
662
+ that names the endpoint and the status. A partial rejection stays SUCCESS
663
+ with a warning. The OTLP exporter also stops following redirects; its
664
+ success rule is still the OTLP spec.
665
+
666
+ **Who this changes:** anyone whose endpoint is misconfigured, or sits behind
667
+ a proxy that answers with a redirect or a non-conforming 2xx — exports that
668
+ silently looked like "success" now fail loudly instead.
669
+
670
+ Tests: `tests/exporters/http-misroute.test.ts`, against real Node `fetch`
671
+ behaviour, covers 3xx statuses, `opaqueredirect`, the breaker, and the
672
+ malformed-ack cases.
673
+
674
+ ## [0.6.0] — published to npm 2026-08-27
675
+
676
+ > ⚠ **This is the first release in which this SDK was ever RUN by the campaign
677
+ > that maintains it.** Sixty-six sessions read it; none executed it. Both fixes
678
+ > below were confirmed by driving the published `0.5.2` against a real gateway
679
+ > and reading what landed in ClickHouse.
680
+
681
+ ### ⚠ `withSession()` now emits the session-end marker
682
+
683
+ `withSession()` and `session()` are exported side by side from `index.ts` under
684
+ one "Tier 3: Sessions" heading, as alternatives. Only the decorator emitted the
685
+ `session.end` lifecycle marker the read model uses to decide whether a session
686
+ is still active, so a session scoped with `withSession` read **active forever**.
687
+ Which behaviour a customer got depended only on which spelling they picked.
688
+
689
+ Measured on the published `0.5.2`: **0 of 3 `withSession` sessions ended; 6 of 6
690
+ decorator sessions did.** After: 3 of 3 and 3 of 3, emitted exactly once each.
691
+
692
+ `withSessionEndMarker` is now called by `withSession` itself, so both public
693
+ session APIs share ONE definition and `decorators/session.ts` no longer wraps
694
+ separately (which would have emitted the marker twice).
695
+
696
+ ### ⚠ `reportError()` now attaches the canonical taxonomy code
697
+
698
+ The JS SDK has a full 154-code taxonomy (`runtime/taxonomy.generated.ts`) wired
699
+ into both throw handlers of `Tracer.startSpan` via `tracer.ts::attachErrorCode`.
700
+ `reportError()` — the API the docs name for feeding the diagnosis pipeline —
701
+ did not call it. Measured on the published `0.5.2`: **4 uncaught spans carried
702
+ `TOOL.EXECUTION.CRASHED`; the `reportError` span carried none.** After: 1 of 1
703
+ carries a code, with the uncaught path unchanged as a control.
704
+
705
+ Same shape and same remedy as the Python twin: reuse the one definition rather
706
+ than re-classifying at the call site.
707
+
708
+ ### 📖 README: the Decision Phases example ran NOTHING
709
+
710
+ `traceThink` / `traceDecide` / `traceAct` are **wrapper factories** —
711
+ `phaseWrapper` returns `(...args) => {...}` and never invokes. The README's own
712
+ "Decision Phases" example wrote `const analysis = await traceThink('analyze',
713
+ async () => {...});` without the trailing call, so `analysis` held a *function*,
714
+ the callback never ran, no span was emitted and nothing threw.
715
+
716
+ Executed verbatim against a real gateway, the shipped example produced **zero
717
+ side effects** — no LLM call, no downstream function, no span. `README.md` is in
718
+ `package.json`'s `files` array, so it is the package's npm landing page. The
719
+ example is corrected and the wrapper-factory semantics are now stated inline.
720
+
721
+ ### `score()` now identifies the SDK (F-SDKVER-001, partial)
722
+
723
+ `score()` reaches the FastAPI server under `/v1/`, which is audited into
724
+ `audit_logs.user_agent`; it sent no identity. It now sends `User-Agent` and
725
+ `X-Risicare-SDK-Version`. The ingest exporter also now sends
726
+ `X-Risicare-SDK-Version`, which Python has always sent — closing that
727
+ asymmetry. ⚠ The gateway still discards both, so ingest attribution needs a
728
+ gateway change.
729
+
730
+ ## [0.5.2] — published to npm 2026-08-22
731
+
732
+ > **0.5.1 was built and never published.** Its tarball never left a build
733
+ > machine, so the registry goes `0.5.0` → `0.5.2` directly. Everything 0.5.1
734
+ > documented ships here, unchanged, below the new entries. The number was
735
+ > retired rather than reused because a `risicare-0.5.1.tgz` already existed on
736
+ > disk with different bytes, and one version naming two artifacts is exactly
737
+ > the ambiguity a registry can never let you take back.
738
+
739
+ ### ⚠ BEHAVIOUR: a capacity refusal no longer opens the circuit breaker
740
+
741
+ **If the ingest endpoint sheds load (HTTP 429 or 503), this release stops the
742
+ SDK from going silent for a minute afterwards.**
743
+
744
+ Measured on the PUBLISHED `risicare@0.5.0` (clean `npm install` from the registry), driven at a recording stub —
745
+ `fix-workstream/perf/a3/sdk_python_refusal_probe.py` for the Python twin, whose
746
+ export path this one mirrors line for line:
747
+
748
+ | arm | requests | cycles the breaker swallowed | inter-attempt gaps |
749
+ |---|---|---|---|
750
+ | plain `200` (control) | 2 | 0 / 2 | 0.001 s |
751
+ | `503` | 15 | **2 / 7** | 0.101, 0.201 |
752
+ | `503` + `Retry-After: 2` | 15 | **2 / 7** | 0.102, 0.201 |
753
+ | `429` + `Retry-After: 2` | 15 | **2 / 7** | 0.102, 0.202 |
754
+ | genuine `500` (control) | 15 | 2 / 7 | 0.102, 0.201 |
755
+
756
+ Three facts in that table. `Retry-After` changed nothing — the gaps are the
757
+ SDK's own backoff either way. 429, 503 and 500 were byte-identical. And after
758
+ five consecutive failing exports the breaker opened for **60 seconds**, during
759
+ which the SDK sent nothing at all: under sustained overload five refusals
760
+ arrive in well under a second, so everything the application emitted in that
761
+ minute was discarded client-side.
762
+
763
+ A `503 QUEUE_NEAR_CAPACITY` is a **healthy** gateway saying "later" — its
764
+ backlog drains and admission resumes on its own. Treating it as a dead sink
765
+ converted a transient server-side shed into total client-side loss.
766
+
767
+ The published JS bundle was measured independently and agrees: it contains **zero**
768
+ occurrences of `accepted`, its only `"429"` is tool-error classification rather than
769
+ HTTP, and its export path is `if (response.status < 300) return SUCCESS`.
770
+
771
+ **Now:** a refusal backs off on the server's terms (`Retry-After`, capped at
772
+ 10 s) or 1 s/2 s/4 s when the server names none, and does **not** count toward
773
+ the breaker. Re-measured post-fix on the same instrument: the 503 arms make 21
774
+ requests with **0 / 7** cycles swallowed and honour `Retry-After: 2` exactly
775
+ (gaps 2.001 s). **A genuine 500 still opens the breaker — 15 requests, 2 / 7
776
+ swallowed, unchanged** — because a fix that made every failure retryable
777
+ forever would turn our outage into your retry loop.
778
+
779
+ This does not make anything retry forever: `max_retries` still bounds the
780
+ attempts, the export budget still bounds the wall clock, and the batch is
781
+ still dropped when both are spent. What changed is that the *next* batch is
782
+ no longer thrown away too.
783
+
784
+ ### ⚠ BEHAVIOUR: sampling no longer FABRICATES traces
785
+
786
+ **If you set `sampleRate` below 1.0, this release changes what you receive —
787
+ and the old behaviour was not a subsample, it was invention.**
788
+
789
+ When a trace was dropped, no span was created, so nothing recorded that a
790
+ decision had been made. Every nested call then saw no parent, took the *root*
791
+ branch, and re-rolled its own sampling decision. The half that passed was
792
+ delivered as a root: **a trace that never existed**, structurally identical on
793
+ the wire to a real one.
794
+
795
+ Measured from a tarball install at `sampleRate=0.5`, N=400 root traces each
796
+ wrapping one nested call, in **both** module systems, with `sampleRate=1.0` as
797
+ the control in every arm:
798
+
799
+ | path | before | after |
800
+ |---|---|---|
801
+ | ESM `startSpan` | 303 delivered, **104 fabricated (34.3%)** | 204, **0** |
802
+ | ESM `createSpan` in a root | 296, **111 (37.5%)** | 208, **0** |
803
+ | CJS `startSpan` | 310, **94 (30.3%)** | 204, **0** |
804
+ | CJS `createSpan` in a root | 294, **105 (35.7%)** | 194, **0** |
805
+
806
+ All four controls at `sampleRate=1.0` fabricated 0 of 400, before and after.
807
+
808
+ **What this means for your numbers.** Delivered traces were `N·r·(2−r)`, not
809
+ `N·r`. So "divide by 1/r" — the correction everyone assumes is available —
810
+ **overstated by 50% at r=0.5 and 90% at r=0.1**, and no downstream analysis
811
+ could undo it, because a fabricated trace carries nothing that marks it. After
812
+ this release delivered traces are `N·r` and every trace arrives whole.
813
+
814
+ **Expect fewer traces after upgrading.** That is the fix, not a regression.
815
+
816
+ The drop decision is now carried in the `AsyncLocalStorage` context and scoped
817
+ to the callback that set it, so — unlike the Python twin, which needed an
818
+ explicit guard — it cannot latch when a callback throws. That was measured, not
819
+ assumed: 145 (ESM) / 159 (CJS) traces delivered against 150 expected after 20
820
+ dropped-and-throwing roots.
821
+
822
+ `createSpan()` consults the decision but deliberately does not record one: it
823
+ hands the span's lifetime to you and owns no callback scope to unwind in.
824
+ Documented bound: a `createSpan` root that is itself dropped does not suppress
825
+ a re-roll by a following `createSpan`.
826
+
827
+ ### ⚠ BEHAVIOUR: every errored span now carries `error.code`
828
+
829
+ Errored spans gain an `error.code` attribute drawn from the canonical 154-code
830
+ taxonomy — **whether or not a fix was applied**. Non-errored spans do not.
831
+
832
+ The SDK previously classified errors with a private six-code vocabulary — the
833
+ same six the Python SDK carried, byte-for-byte — of which exactly **one code
834
+ existed** in that taxonomy:
835
+
836
+ | SDK emitted | canonical |
837
+ |---|---|
838
+ | `TOOL.EXECUTION.TIMEOUT` | ✅ valid |
839
+ | `TOOL.EXECUTION.RATE_LIMIT` | ❌ it is `RATE_LIMITED` |
840
+ | `OUTPUT.FORMAT.JSON_INVALID` | ❌ it is `INVALID_JSON` |
841
+ | `TOOL.EXECUTION.CONNECTION_ERROR` | ❌ no such code |
842
+ | `TOOL.EXECUTION.AUTH_ERROR` | ❌ no such code |
843
+ | `TOOL.EXECUTION.FAILURE` | ❌ no such code |
844
+
845
+ This SDK cannot import the taxonomy — `risicare-core` is a Python package and
846
+ is not on npm — so the rule table and the canonical code set are now
847
+ **generated** from the Python source of truth into
848
+ `src/runtime/taxonomy.generated.ts`, and a rail fails when the two drift.
849
+ Verified end-to-end: Python, ESM and CJS agree code-for-code on the same four
850
+ errors. Every code is checked against the canonical set before it is returned.
851
+
852
+ ### Changed — a `sampleRate` below 1.0 now warns that the rate is not transmitted
853
+
854
+ The rate is applied in your process and never sent to the platform: no ingest
855
+ field, no column, no query and no W3C `traceparent` flag carries it. So trace
856
+ counts, error rates and cost figures describe the sampled subset only and
857
+ cannot be scaled back to totals.
858
+
859
+ ### ⚠ BREAKING DEFAULT: prompt and completion content is no longer captured
860
+
861
+ **`traceContent` now defaults to `false`.** If you upgrade from 0.5.0 and change
862
+ nothing, prompt and completion text stops leaving your process. Every other
863
+ attribute — model, token counts, latency, cost, roles, errors, your own
864
+ attributes — is unchanged.
865
+
866
+ **To keep the old behaviour, opt in explicitly:**
867
+
868
+ ```ts
869
+ init({ apiKey: 'rsk-...', traceContent: true });
870
+ // or: RISICARE_TRACE_CONTENT=true
871
+ ```
872
+
873
+ **Why this ships in a PATCH, and why the default moved at all** — identical
874
+ reasoning to the Python SDK; see `packages/risicare-sdk/CHANGELOG.md` 0.2.1. In
875
+ short: `traceContent: false` was already the documented way to turn capture off
876
+ and it did not turn capture off, so the fix and the default change are one
877
+ change; and content captured by this SDK is archived in cleartext with no expiry
878
+ beyond the reach of the product's own erasure cascade.
879
+
880
+ ### Fixed — `traceContent` did not gate content you set yourself
881
+
882
+ `traceContent` was carried by the `Tracer` behind a getter and consulted **only**
883
+ by the provider patches. Measured against the published 0.5.0 from a tarball
884
+ install, in **both** CJS and ESM: `getTraceContent()` returned `false` while a
885
+ hand-set `gen_ai.prompt.0.content` reached the wire byte-for-byte.
886
+
887
+ The gate now runs in the batch processor — the one place both content paths
888
+ cross — as the same key-shape filter Python uses, with the same exact-match
889
+ additions (`gen_ai.system_prompt`, `gen_ai.prompt.message`) and the same
890
+ deliberate exclusions (`content_type`, `content_blocks`, `parts`, `role`,
891
+ `system_prompt_length`). A gated field is replaced with
892
+ `<risicare:content-omitted>`, not deleted.
893
+
894
+ `statusMessage` and exception text are not stripped, and `mask` is unchanged.
895
+
896
+ ### Fixed — `HTTP 200` was treated as delivery (F-SDKACKBLIND-001)
897
+
898
+ Identical defect and identical fix to Python. Measured with a sink returning
899
+ `200 {"accepted":0,"rejected":1}`:
900
+
901
+ | | published 0.5.0 | 0.5.1 |
902
+ |---|---|---|
903
+ | `exportedSpans` | **1** | 0 |
904
+ | `failedExports` | **0** | 2 |
905
+ | `droppedSpans` | **0** | 1 |
906
+
907
+ i.e. 0.5.0 reported a span as delivered that the backend never stored. Partial
908
+ rejections warn rather than fail, and any body we cannot parse is still a
909
+ success — fail-safe.
910
+
911
+ ### Added — `serviceName` and `serviceVersion` reach the wire (F-SDKJSSVCNAME-001)
912
+
913
+ `serviceName` was typed, documented, and recommended over the deprecated
914
+ `projectId` — and reached the wire **nowhere**. Measured on the published 0.5.0:
915
+ `serviceName` set at init, absent from every request body, while a control
916
+ attribute in the same span arrived. Both are now emitted as the `service.name`
917
+ and `service.version` span attributes, matching Python. `service.name` is
918
+ suppressed when an agent identity is present (the agent takes priority);
919
+ `service.version` never is.
920
+
921
+ ### Fixed — the package did not typecheck
922
+
923
+ `tsc --noEmit` had been failing on this package (TS6133, a dead private field).
924
+ It survived because the repo's gate runs this package's vitest and never its
925
+ typecheck, and `prepublishOnly` runs `build && test` — also no typecheck.
926
+
927
+ ### Note — the export budget is a Python-only fix
928
+
929
+ The Python SDK's per-call export budget has no JS counterpart because JS did not
930
+ need one: `fetch` is bounded by an `AbortController`, which is a wall clock and
931
+ is **not** charged per resolved address. Measured on the same dual-stack
932
+ blackhole: 5.00 s for one address and 5.00 s for two. Python's httpx timeout is
933
+ per-phase-per-address and was 15.31 s / 30.33 s. The asymmetry is deliberate.
934
+
935
+ ## [0.5.0] — published 2026-08-15 (npm)
936
+
937
+ **Upgrade if you care whether your spans arrive.** `shutdown()` was abandoning
938
+ most of its queue on every clean redeploy, silently, and `flush()` was throwing
939
+ away its own answer. Both are closed. The MINOR bump is bookkeeping (one return
940
+ type widened, below); the reason to take it is the data loss.
941
+
942
+ ### ⚠ Known limitation — spans are lost during a backend outage, and for ~60 s after it
943
+
944
+ **This is NOT fixed in 0.5.0.** Documented because a customer who knows they lose
945
+ spans during an outage is far better off than one who does not. The JS breaker is
946
+ **identical to the Python one** — same threshold, same cooldown — so the Python
947
+ CHANGELOG's measured numbers apply here too.
948
+
949
+ `src/exporters/http.ts:45-46` opens a circuit breaker after **5 consecutive
950
+ failed export calls** (`_circuitBreakerThreshold = 5`) and holds it open for
951
+ **60 s** (`_circuitBreakerCooldownMs = 60_000`). While open, export returns
952
+ failure immediately **without touching the network**, so the
953
+ `BatchSpanProcessor.MAX_RETRIES = 3` re-queues resolve against a local boolean in
954
+ microseconds and the queued spans are discarded as `transport_refused`. Recovery
955
+ is not immediate either: measured on the Python twin, a restored-to-health sink
956
+ still had **55.7 s** of cooldown to run and received **0 HTTP requests** in that
957
+ window.
958
+
959
+ Measured survival of a 1,000-span cohort emitted during an outage — 4 s: all
960
+ delivered; 5 s: half; 6 s and beyond: none.
961
+
962
+ ⚠ **The threshold is in FAILED CALLS, not seconds** — where the 5th consecutive
963
+ failure lands in wall-clock time depends on your span rate and on how fast the
964
+ endpoint fails. The seconds above are one measured application shape.
965
+
966
+ Probes (Python twin, same constants): `fix-workstream/perf/sdk_breaker_recovery_probe.py`
967
+ and `fix-workstream/perf/sdk_blip_survival_probe.py`. Tracked as **F-SDKBLIP-001** /
968
+ **F-SDKCBRECOVER-001**.
969
+
970
+ ### Fixed
971
+ - **F-SDKJSCONSOLE-001 — the SDK printed every span, unredacted, to your stderr
972
+ when no API key was set.** If tracing was enabled and `apiKey` was falsy — a
973
+ missing, mistyped or not-injected `RISICARE_API_KEY`, which is what a failed
974
+ secret mount looks like — the client fell back to `ConsoleExporter`, which
975
+ writes `JSON.stringify(span.toPayload())` to `process.stderr`. That is the
976
+ **whole payload**: every attribute, event and exception, including prompts and
977
+ completions. **No debug flag was required and no warning was emitted.** The SDK
978
+ performs no redaction of its own — both tiers run server-side, one hop later —
979
+ so nothing sanitised it. Present in every published 0.x including `0.4.2`, in
980
+ both CJS and ESM.
981
+
982
+ It now matches the Python SDK: a one-time `console.warn` naming the
983
+ misconfiguration, and the spans are dropped rather than printed. **The explicit
984
+ `debug: true` opt-in is unchanged** — if you want console output for local
985
+ development, ask for it and you still get it.
986
+ - **F-SDKJSREPORTERROR-001 — `reportError()` reported nothing under ESM.** It is
987
+ a **silent** no-op: `_errorFingerprint()` called `require('node:crypto')`
988
+ inside the function, esbuild rewrote that to `__require("crypto")` in the ESM
989
+ bundle, the shim **throws** at call time, and `reportError`'s catch-all
990
+ ("Never crash the host application") swallowed it. So the call returned
991
+ normally and sent nothing. Measured on clean tarball installs of the
992
+ **published 0.4.2**, same call and same sink in both arms: **0 error spans
993
+ delivered under `import`, 1 under `require`.** ESM is the default for modern
994
+ Node apps, so this was most customers. Now a static `import { createHash } from
995
+ 'node:crypto'` — which adds no new environmental constraint, because the main
996
+ entry already imports `node:crypto` statically via `webhooks.ts`. Post-fix:
997
+ **1 and 1.** Re-run `fix-workstream/perf/sdkjs/reporterror_module_system_probe.sh`;
998
+ its CJS arm is the non-vacuity control and gates the exit code.
999
+ - **F-SDKDRAIN-001 — `shutdown()` abandoned most of the queue, on every clean
1000
+ redeploy.** It called `_exportBatch()` exactly once — at most `batchSize`
1001
+ (then default 100) out of a queue up to `maxQueueSize` (default 10,000) — measured
1002
+ **9,800 of 10,000 spans lost in ~1 ms of a 5,000 ms budget, with a healthy
1003
+ transport.** Worse, if an export was already in flight the `_flushing` guard
1004
+ made that single call a **no-op**, so the drain exported *nothing at all*
1005
+ (measured 900 of 1,000 lost). `shutdown()` now drains in a loop — yielding
1006
+ when an export is in flight rather than no-op'ing — until the queue is empty,
1007
+ its deadline expires, or the transport stops accepting. Anything it cannot
1008
+ deliver is counted as `shutdown_residue` **and announced with a WARNING**.
1009
+ - **…and the drain now finishes at real-world latency, not just on loopback.**
1010
+ Draining is strictly serial — one export per round-trip — so what it can save
1011
+ is `(budget / RTT) x batchSize`. Over a real network the loop above was still
1012
+ losing most of the queue. Measured on a container SIGTERM with a full
1013
+ 10,000-span queue: **1,900 delivered at 100 ms round-trip before, 10,000
1014
+ after**; **800 at 250 ms before, 10,000 after**. Two changes were needed and
1015
+ **neither works alone** — at 100 ms the budget change by itself still loses
1016
+ 51 %, the batch change by itself still loses 60 % at the tail:
1017
+ - `batchSize` now defaults to **500** (was 100) — see *Changed*.
1018
+ - Every teardown path spends the same **5,000 ms** budget, and the signal
1019
+ handler's force-exit backstop is now **derived** from it instead of being a
1020
+ second independent `5000`. Those two literals used to race: a drain allowed
1021
+ 5,000 ms could be killed by a `process.exit(1)` firing at 5,000 ms, with the
1022
+ wrong exit code, before the residue WARNING could print.
1023
+ - **🛑 A SIGTERM'd process no longer runs forever (`F-SDKJSEXIT-001`).**
1024
+ Registering a `SIGTERM` listener displaces Node's default terminate, and on
1025
+ the success path the SDK cleared its own only remaining exit — so a service
1026
+ with a live event loop drained, then **kept running until the orchestrator
1027
+ gave up and SIGKILLed it**, exiting 137 (which reads as OOM-killed in most
1028
+ dashboards). Measured from the installed tarball: **before, SIGTERM did
1029
+ nothing and the process survived the full 30 s; after, it dies in 71 ms with
1030
+ the conventional 143.** The SDK now terminates **only when it displaced the
1031
+ default** — if your app registered its own `SIGTERM`/`SIGINT` listener first,
1032
+ the SDK drains and yields to you.
1033
+ - **`getMetrics()` after `shutdown()` no longer reports zeros.** `shutdown()`
1034
+ clears the global client, so the natural `await shutdown(); getMetrics()`
1035
+ returned a hardcoded row of zeros — `droppedSpans: 0`, byte-identical to an
1036
+ authoritative "nothing was lost", in the exact process that had just discarded
1037
+ spans. It now returns the **retained final tally**, labelled `sdkState`.
1038
+ - **`flush()` no longer reports success over data it lost.** It resolved `true`
1039
+ unconditionally after `shutdown()`, and the public `flush()` discarded the
1040
+ processor's boolean entirely. It now resolves `true` only if everything queued
1041
+ at entry was **delivered**.
1042
+ - **Span discards are now announced, not just counted.** `droppedSpans` has
1043
+ always ticked on retry exhaustion, but only a `debug()` line described it —
1044
+ suppressed at the default log level. Retry exhaustion now emits a **WARNING**
1045
+ naming the count and the reason.
1046
+
1047
+ ### Changed
1048
+ - **`flush()` returns `Promise<boolean>` (was `Promise<void>`).** This is the
1049
+ signature change that makes the release MINOR. It is **additive at runtime**:
1050
+ callers that `await flush()` and ignore the result are unaffected. TypeScript
1051
+ users who had annotated a wrapper as `Promise<void>` may need to widen it.
1052
+ - **`batchSize` now defaults to 500 (was 100).** Derived, not picked: the drain
1053
+ must clear the SDK's own maximum queue (`maxQueueSize`, 10,000) inside the
1054
+ budget at the round-trip the SDK is deployed at, which needs
1055
+ `batchSize >= 10,000 x RTT / 4,900` — 204 at 100 ms, 510 at 250 ms. It is also
1056
+ the SDK's steady-state export ceiling (`batchSize / RTT` spans per second), so
1057
+ the same constant governs both. `RISICARE_BATCH_SIZE` still overrides it.
1058
+ - `batchSize` is a **ceiling, not a fixed size** — a batch takes
1059
+ `min(queued, batchSize)`. A shallow queue is unaffected; only a deep one
1060
+ sends larger requests, which is exactly the case the raise exists for.
1061
+ - **A batch is now bounded on two further axes**, so the raise cannot push a
1062
+ workload past a gateway limit it was comfortably inside before. On either
1063
+ one you simply get smaller batches — the same ones you get today — rather
1064
+ than a rejected request. Nothing is dropped or truncated:
1065
+ - **Total attribute count ≤ 24,000 per request.** Binds above ~48
1066
+ attributes per span at `batchSize: 500`.
1067
+ - **Estimated serialized size ≤ 8 MiB per request** — 80 % of the gateway's
1068
+ 10 MiB body limit. Binds above ~21 KB per span at `batchSize: 500`;
1069
+ measured, a 500-span batch crosses the body limit at **20,971 B/span**,
1070
+ and without this bound the *whole* request came back `413`, was retried
1071
+ 12 times, and every span in it was then discarded as `transport_refused`.
1072
+ For scale: the heaviest span we measure from a real instrumented call is
1073
+ 13.5 KB, so this is headroom you are unlikely to touch — and if you do,
1074
+ you get two requests instead of one refusal.
1075
+ ⚠ The size is **estimated**, not serialized — serializing to measure would
1076
+ double the export cost. Strings are charged their real UTF-8 byte length,
1077
+ so a CJK or emoji payload is counted at its true wire weight rather than
1078
+ its `.length`. The one blind spot is heavy JSON escaping inside a string
1079
+ attribute, which the 20 % margin covers to roughly 25 % escape density;
1080
+ past that the gateway refuses exactly as it does today.
1081
+ - Set `batchSize: 100` in `init()` to keep the old behaviour.
1082
+
1083
+ ### Added
1084
+ - **`init({ mask })` — redact span content before it leaves your process.**
1085
+ Until now the SDK had no way to transform what it sends. `traceContent: false`
1086
+ is all-or-nothing (capture everything or capture nothing, never redact a
1087
+ substring), and a custom exporter receives a *parallel copy* — it cannot
1088
+ change what the built-in HTTP exporter sends. Risicare is SaaS-only, so for
1089
+ anyone who must keep PII out of a vendor's storage this hook is not defence in
1090
+ depth; it is the only layer.
1091
+
1092
+ ```ts
1093
+ const EMAIL = /[\w.+-]+@[\w-]+\.[\w.]+/g;
1094
+
1095
+ init({
1096
+ apiKey: 'rsk-...',
1097
+ mask: (key, value) =>
1098
+ typeof value === 'string' ? value.replace(EMAIL, '[email]') : value,
1099
+ });
1100
+ ```
1101
+
1102
+ `mask(key, value) => value` is called for every content-bearing field of every
1103
+ span — each `attributes` entry (by its own key, e.g.
1104
+ `"gen_ai.prompt.0.content"`), `"statusMessage"`,
1105
+ `"events.{i}.attributes.{k}"` and `"links.{i}.attributes.{k}"` — before the
1106
+ batch reaches ANY exporter, custom ones included.
1107
+
1108
+ **The key is passed because our span model needs it.** We have no separate
1109
+ `input`/`output` fields: your prompt and the model name are both plain entries
1110
+ of `attributes`. Without the key a mask could not tell them apart, and the
1111
+ obvious `() => '***'` would erase every model name in your account.
1112
+
1113
+ **What is never passed to it** — `traceId`/`spanId`, `span.name`,
1114
+ `event.name`, a link's `traceId`/`spanId`, and the typed identity/LLM columns
1115
+ (`agentName`, `sessionId`, `toolName`, `llmModel`, …). Masking a name destroys
1116
+ your grouping; masking an identifier destroys your joins. The OTel-style
1117
+ attribute forms (`agent.name`, `session.user_id`) live in `attributes` and ARE
1118
+ passed, so you can still redact those if you want to.
1119
+
1120
+ **If your mask throws, that one field becomes `"<risicare:mask-error>"` and
1121
+ the span is still exported** — never dropped. A dropped span orphans its
1122
+ children and buys no extra safety over a marker. You get a rate-limited
1123
+ WARNING plus `getMetrics().maskErrors`.
1124
+
1125
+ ⚠ **Keep it CPU-only and fast — this matters more in Node than in Python.**
1126
+ Node is single-threaded, so unlike the Python SDK (which masks on a background
1127
+ worker thread) this runs on your event loop: while it runs, nothing else in
1128
+ your process does. No I/O, no network, no unbounded retries. Exceed
1129
+ ~1 ms/span and you get a warning; the mask is never silently disabled, because
1130
+ a security control that turns itself off under load fails open.
1131
+
1132
+ ⚠ **It cannot reach spans that never enter this SDK.** If you send OTLP
1133
+ directly to the gateway, no SDK hook runs — mask in your OTel pipeline.
1134
+
1135
+ **It also covers `score(traceId, name, value, { comment })`, which is not a
1136
+ span** (key: `"score.comment"`). `score()` `fetch`es straight to
1137
+ `/api/v1/scores`, so it never passes through the span processor — its
1138
+ free-text `comment` would otherwise have been the one piece of customer
1139
+ content the hook could not see. `traceId`, `spanId` and `name` are NOT masked:
1140
+ `name` is the metric name we group your scores by, so masking it destroys your
1141
+ own aggregation, exactly as with `span.name`. A throwing mask marks the
1142
+ comment and the score is still sent.
1143
+
1144
+ ⚠ **One asymmetry, on this surface only:** the mask runs before the request is
1145
+ built, on the caller's stack. That is the same thread as everything else in
1146
+ Node, so the note above about the event loop applies here too — but `score()`
1147
+ is an explicit, low-frequency call, and the alternative would mean the raw
1148
+ comment had already been serialized.
1149
+ - **`MASK_ERROR_MARKER`** and the `MaskFn` type, exported from the package root.
1150
+ - **`getMetrics().maskErrors`** — fields whose mask threw (a field count, not a
1151
+ span count). Non-zero means those fields carry a marker instead of data.
1152
+ - **`getMetrics().droppedSpansByReason`** —
1153
+ `{ queue_full, transport_refused, shutdown_residue }`. One number could not
1154
+ distinguish an under-provisioned queue from a dead gateway from a redeploy,
1155
+ and those need three different responses.
1156
+ - **`getMetrics().sdkState`** — `"uninitialised"`, `"running"` or `"shutdown"`.
1157
+ Three different facts used to render as the same zeros: *nothing was lost*,
1158
+ *I have live numbers*, and *I have been torn down*. After `shutdown()` the
1159
+ numbers are the **retained final tally** — every field still true, including
1160
+ the `shutdown_residue` you most need — and `sdkState` says they are final
1161
+ rather than live.
1162
+
1163
+ ```ts
1164
+ await shutdown();
1165
+ const m = getMetrics(); // sdkState === 'shutdown'
1166
+ if (m.droppedSpans) console.error('risicare lost spans:', m.droppedSpansByReason);
1167
+ ```
1168
+
1169
+ ### Deprecated
1170
+ - `droppedSpans` (flat number) is retained and is exactly the **sum** of
1171
+ `droppedSpansByReason`. Nothing is removed.
1172
+
1173
+ ### Upgrade notes
1174
+ - **`shutdown()` may now take longer — up to 5 s instead of resolving in ~1 ms.
1175
+ That is the point**: it is spending the budget in order to deliver your spans,
1176
+ and the numbers above are what the extra seconds buy. It stays hard-bounded —
1177
+ it exits early on an empty queue or a refusing transport — and it fits inside
1178
+ `docker stop`'s 10 s default and Kubernetes' 30 s
1179
+ `terminationGracePeriodSeconds`.
1180
+ - ⚠ **Your process now exits on SIGTERM/SIGINT where it previously did not** (if
1181
+ you registered no signal listener of your own). If you were relying on the
1182
+ process surviving SIGTERM, register your own `process.on('SIGTERM')` **before**
1183
+ `init()` — the SDK yields to a listener that predates it, and drains either
1184
+ way.
1185
+ - ⚠ Neither the retained tally nor the WARNING survives a **SIGKILL** — both
1186
+ live in the memory of the process being killed. They cover graceful
1187
+ termination; nothing in the SDK can report loss from a process that is not
1188
+ given the chance to.
1189
+ - ⚠ **Not fixed, and stated rather than hidden:** past ~250 ms round-trip a full
1190
+ queue still exceeds the budget. The loss is bounded, counted and warned — it
1191
+ is not eliminated. A serial drain cannot beat `queue x RTT / batchSize`.
1192
+
1193
+ ## [0.4.2] — 2026-06-20
1194
+
1195
+ First publish since **0.4.0** (npm, 2026-05-23). Folds in the never-published
1196
+ `0.4.1` bump (PR #155 hardening + `GuardRejectedError` export) plus the run-end
1197
+ signal. **Backward-compatible** — no export removed; all 16 subpath exports
1198
+ (`.`, `./openai`, `./langchain`, …) intact; decorator signatures unchanged;
1199
+ package `exports` map identical to 0.4.0.
1200
+
1201
+ ### Added
1202
+ - **F-B-012 — SDK run-end signal (parity with Python 0.1.14).** `agent()`,
1203
+ `session()`, `traceThink/Decide/Act/Observe`, and the multi-agent decorators
1204
+ now emit a lifecycle-end marker on completion
1205
+ (`risicare.lifecycle.event=end`, `…entity=session|agent|trace`,
1206
+ `…status=ok|error`). Normal completion ⇒ `ok`; a thrown error ⇒ `error` (the
1207
+ error is **re-thrown unchanged**). New `src/lifecycle.ts`. Purely additive —
1208
+ no required wire field; an old backend simply ignores the marker.
1209
+ - **`GuardRejectedError`** is now a public export from the package root
1210
+ (`import { GuardRejectedError } from 'risicare'`). (Originally the `0.4.1`
1211
+ intent.)
1212
+
1213
+ ### Fixed
1214
+ - **PR #155 — JS SDK hardening (16 audit findings closed).** Input/robustness
1215
+ hardening across the SDK. (Originally the `0.4.1` intent; released here.)
1216
+
1217
+ ### Upgrade notes (behavior changes — none breaking)
1218
+ - **One extra marker per `session()`** and three `risicare.lifecycle.*`
1219
+ attributes added to `agent()`/trace entity spans on completion. Slightly more
1220
+ span volume; no schema change required, no API change.
1221
+ - Wire `SDK_VERSION` (User-Agent `risicare-js/0.4.2`, `X-Risicare-SDK-Version`
1222
+ header) bumped in lock-step with `package.json` (`src/version.ts`).
1223
+
1224
+ ### Internal / not customer-visible
1225
+ - F-B-012 also ships a worker + gateway half (already deployed in production)
1226
+ that derives `sessions.is_active` from the marker; the SDK change here is the
1227
+ producer of that signal.
1228
+
1229
+ ---
1230
+
1231
+ ## [0.4.1] — unpublished (folded into 0.4.2)
1232
+ Internal bump for **PR #155** (JS SDK hardening, 16 findings) + public
1233
+ `GuardRejectedError` export. Never published to npm; released as part of 0.4.2.
1234
+
1235
+ ## [0.4.0] — last release on npm prior to 0.4.2 (2026-05-23)
1236
+ Baseline for the 0.4.2 delta above. Shipped the F-34 webhook verifier.