risicare 0.9.1 → 0.10.0

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