risicare 0.4.2 → 0.5.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 (72) hide show
  1. package/README.md +30 -0
  2. package/dist/frameworks/instructor.cjs +26 -19
  3. package/dist/frameworks/instructor.cjs.map +1 -1
  4. package/dist/frameworks/instructor.js +26 -19
  5. package/dist/frameworks/instructor.js.map +1 -1
  6. package/dist/frameworks/langchain.cjs +32 -25
  7. package/dist/frameworks/langchain.cjs.map +1 -1
  8. package/dist/frameworks/langchain.js +32 -25
  9. package/dist/frameworks/langchain.js.map +1 -1
  10. package/dist/frameworks/langgraph.cjs +32 -25
  11. package/dist/frameworks/langgraph.cjs.map +1 -1
  12. package/dist/frameworks/langgraph.js +32 -25
  13. package/dist/frameworks/langgraph.js.map +1 -1
  14. package/dist/frameworks/llamaindex.cjs +21 -14
  15. package/dist/frameworks/llamaindex.cjs.map +1 -1
  16. package/dist/frameworks/llamaindex.js +21 -14
  17. package/dist/frameworks/llamaindex.js.map +1 -1
  18. package/dist/index.cjs +675 -239
  19. package/dist/index.cjs.map +1 -1
  20. package/dist/index.d.cts +200 -46
  21. package/dist/index.d.ts +200 -46
  22. package/dist/index.js +670 -235
  23. package/dist/index.js.map +1 -1
  24. package/dist/providers/anthropic/index.cjs +32 -25
  25. package/dist/providers/anthropic/index.cjs.map +1 -1
  26. package/dist/providers/anthropic/index.js +32 -25
  27. package/dist/providers/anthropic/index.js.map +1 -1
  28. package/dist/providers/bedrock/index.cjs +32 -25
  29. package/dist/providers/bedrock/index.cjs.map +1 -1
  30. package/dist/providers/bedrock/index.js +32 -25
  31. package/dist/providers/bedrock/index.js.map +1 -1
  32. package/dist/providers/cerebras/index.cjs +32 -25
  33. package/dist/providers/cerebras/index.cjs.map +1 -1
  34. package/dist/providers/cerebras/index.js +32 -25
  35. package/dist/providers/cerebras/index.js.map +1 -1
  36. package/dist/providers/cohere/index.cjs +32 -25
  37. package/dist/providers/cohere/index.cjs.map +1 -1
  38. package/dist/providers/cohere/index.js +32 -25
  39. package/dist/providers/cohere/index.js.map +1 -1
  40. package/dist/providers/google/index.cjs +32 -25
  41. package/dist/providers/google/index.cjs.map +1 -1
  42. package/dist/providers/google/index.js +32 -25
  43. package/dist/providers/google/index.js.map +1 -1
  44. package/dist/providers/groq/index.cjs +32 -25
  45. package/dist/providers/groq/index.cjs.map +1 -1
  46. package/dist/providers/groq/index.js +32 -25
  47. package/dist/providers/groq/index.js.map +1 -1
  48. package/dist/providers/huggingface/index.cjs +32 -25
  49. package/dist/providers/huggingface/index.cjs.map +1 -1
  50. package/dist/providers/huggingface/index.js +32 -25
  51. package/dist/providers/huggingface/index.js.map +1 -1
  52. package/dist/providers/mistral/index.cjs +32 -25
  53. package/dist/providers/mistral/index.cjs.map +1 -1
  54. package/dist/providers/mistral/index.js +32 -25
  55. package/dist/providers/mistral/index.js.map +1 -1
  56. package/dist/providers/ollama/index.cjs +32 -25
  57. package/dist/providers/ollama/index.cjs.map +1 -1
  58. package/dist/providers/ollama/index.js +32 -25
  59. package/dist/providers/ollama/index.js.map +1 -1
  60. package/dist/providers/openai/index.cjs +32 -25
  61. package/dist/providers/openai/index.cjs.map +1 -1
  62. package/dist/providers/openai/index.js +32 -25
  63. package/dist/providers/openai/index.js.map +1 -1
  64. package/dist/providers/together/index.cjs +32 -25
  65. package/dist/providers/together/index.cjs.map +1 -1
  66. package/dist/providers/together/index.js +32 -25
  67. package/dist/providers/together/index.js.map +1 -1
  68. package/dist/providers/vercel-ai/index.cjs +26 -19
  69. package/dist/providers/vercel-ai/index.cjs.map +1 -1
  70. package/dist/providers/vercel-ai/index.js +26 -19
  71. package/dist/providers/vercel-ai/index.js.map +1 -1
  72. package/package.json +1 -1
package/dist/index.cjs CHANGED
@@ -33,6 +33,7 @@ __export(src_exports, {
33
33
  AgentRole: () => AgentRole,
34
34
  DEFAULT_TIMESTAMP_TOLERANCE_S: () => DEFAULT_TIMESTAMP_TOLERANCE_S,
35
35
  GuardRejectedError: () => GuardRejectedError,
36
+ MASK_ERROR_MARKER: () => MASK_ERROR_MARKER,
36
37
  MessageType: () => MessageType,
37
38
  RisicareCallbackHandler: () => RisicareCallbackHandler,
38
39
  RisicareLlamaIndexHandler: () => RisicareLlamaIndexHandler,
@@ -90,6 +91,547 @@ __export(src_exports, {
90
91
  });
91
92
  module.exports = __toCommonJS(src_exports);
92
93
 
94
+ // src/client.ts
95
+ var import_node_crypto3 = require("crypto");
96
+
97
+ // src/globals.ts
98
+ var import_node_async_hooks = require("async_hooks");
99
+ var G = globalThis;
100
+ var PREFIX = "__risicare_";
101
+ function getClient() {
102
+ return G[PREFIX + "client"];
103
+ }
104
+ function setClient(client) {
105
+ G[PREFIX + "client"] = client;
106
+ }
107
+ function getTracer() {
108
+ return G[PREFIX + "tracer"];
109
+ }
110
+ function setTracer(tracer) {
111
+ G[PREFIX + "tracer"] = tracer;
112
+ }
113
+ function getContextStorage() {
114
+ if (!G[PREFIX + "ctx"]) {
115
+ G[PREFIX + "ctx"] = new import_node_async_hooks.AsyncLocalStorage();
116
+ }
117
+ return G[PREFIX + "ctx"];
118
+ }
119
+ function getRegistry() {
120
+ if (!G[PREFIX + "registry"]) {
121
+ G[PREFIX + "registry"] = /* @__PURE__ */ new Map();
122
+ }
123
+ return G[PREFIX + "registry"];
124
+ }
125
+ function getOpCount() {
126
+ return G[PREFIX + "opcount"] ?? 0;
127
+ }
128
+ function setOpCount(n) {
129
+ G[PREFIX + "opcount"] = n;
130
+ }
131
+ function getDebug() {
132
+ return G[PREFIX + "debug"] ?? false;
133
+ }
134
+ function setDebugFlag(enabled) {
135
+ G[PREFIX + "debug"] = enabled;
136
+ }
137
+
138
+ // src/utils/log.ts
139
+ function setDebug(enabled) {
140
+ setDebugFlag(enabled);
141
+ }
142
+ function debug(msg) {
143
+ if (getDebug()) {
144
+ process.stderr.write(`[risicare] ${msg}
145
+ `);
146
+ }
147
+ }
148
+ function warn(msg) {
149
+ process.stderr.write(`[risicare] WARNING: ${msg}
150
+ `);
151
+ }
152
+
153
+ // src/masking.ts
154
+ var MASK_ERROR_MARKER = "<risicare:mask-error>";
155
+ var MASK_BUDGET_MS_PER_SPAN = 1;
156
+ var MASK_WARN_WINDOW_MS = 3e5;
157
+ var SCORE_COMMENT_KEY = "score.comment";
158
+ function maskText(mask, key, value, onError) {
159
+ return maskString(mask, key, value, onError);
160
+ }
161
+ function maskOne(mask, key, value, onError) {
162
+ try {
163
+ return mask(key, value);
164
+ } catch (e) {
165
+ onError?.(key, e);
166
+ return MASK_ERROR_MARKER;
167
+ }
168
+ }
169
+ function maskString(mask, key, value, onError) {
170
+ const masked = maskOne(mask, key, value, onError);
171
+ if (typeof masked === "string") return masked;
172
+ try {
173
+ return String(masked);
174
+ } catch (e) {
175
+ onError?.(key, e);
176
+ return MASK_ERROR_MARKER;
177
+ }
178
+ }
179
+ function maskAttributes(mask, prefix, attrs, onError) {
180
+ for (const k of Object.keys(attrs)) {
181
+ attrs[k] = maskOne(mask, prefix + k, attrs[k], onError);
182
+ }
183
+ }
184
+ function isMasked(span) {
185
+ return span._risicareMasked === true;
186
+ }
187
+ function markMasked(span) {
188
+ try {
189
+ span._risicareMasked = true;
190
+ } catch {
191
+ debug("Could not mark span as masked; a re-queue may re-mask it");
192
+ }
193
+ }
194
+ function applyMask(span, mask, onError) {
195
+ if (isMasked(span)) return;
196
+ if (span.attributes && typeof span.attributes === "object") {
197
+ maskAttributes(mask, "", span.attributes, onError);
198
+ }
199
+ if (span.statusMessage !== void 0) {
200
+ span.statusMessage = maskString(mask, "statusMessage", span.statusMessage, onError);
201
+ }
202
+ if (Array.isArray(span.events)) {
203
+ span.events.forEach((event, i) => {
204
+ if (event?.attributes && typeof event.attributes === "object") {
205
+ maskAttributes(mask, `events.${i}.attributes.`, event.attributes, onError);
206
+ }
207
+ });
208
+ }
209
+ if (Array.isArray(span.links)) {
210
+ span.links.forEach((link, i) => {
211
+ if (link?.attributes && typeof link.attributes === "object") {
212
+ maskAttributes(mask, `links.${i}.attributes.`, link.attributes, onError);
213
+ }
214
+ });
215
+ }
216
+ markMasked(span);
217
+ }
218
+ function applyMaskBatch(spans, mask, onError) {
219
+ let errors = 0;
220
+ let firstKey;
221
+ let firstError;
222
+ const report = (key, error) => {
223
+ errors++;
224
+ if (firstKey === void 0) {
225
+ firstKey = key;
226
+ firstError = error;
227
+ }
228
+ onError?.(key, error);
229
+ };
230
+ const started = Date.now();
231
+ for (const span of spans) {
232
+ applyMask(span, mask, report);
233
+ }
234
+ const elapsedMs = Date.now() - started;
235
+ if (errors > 0 && firstKey !== void 0) {
236
+ debug(`mask threw on ${errors} field(s); first: key=${firstKey} ${String(firstError)}`);
237
+ }
238
+ return { errors, elapsedMs };
239
+ }
240
+ function warnMaskErrors(batchErrors, totalErrors) {
241
+ warn(
242
+ `the mask callback threw on ${batchErrors} field(s) in this batch (${totalErrors} since start). Those fields were replaced with "${MASK_ERROR_MARKER}" and the spans were exported intact \u2014 no span was dropped. Fix the callback; until then those fields carry no data.`
243
+ );
244
+ }
245
+ function warnMaskSlow(spanCount, elapsedMs) {
246
+ warn(
247
+ `masking ${spanCount} span(s) took ${elapsedMs} ms (budget ${MASK_BUDGET_MS_PER_SPAN * spanCount} ms, ${MASK_BUDGET_MS_PER_SPAN} ms/span). Node is single-threaded: this time is taken from your event loop, so it delays your application as well as the export drain, and a queue that cannot drain drops spans (reason=queue_full). Keep the callback CPU-only: no I/O, no network, no unbounded retries.`
248
+ );
249
+ }
250
+
251
+ // src/exporters/batch.ts
252
+ var SHUTDOWN_RESERVE_MS = 100;
253
+ var SHUTDOWN_BUDGET_MS = 5e3;
254
+ var REFUSAL_WARN_WINDOW_MS = 3e5;
255
+ var DEFAULT_BATCH_SIZE = 500;
256
+ var MAX_ATTRIBUTE_PAIRS_PER_BATCH = 24e3;
257
+ var MAX_BATCH_BYTES = 8 * 1024 * 1024;
258
+ var SPAN_ENVELOPE_BYTES = 512;
259
+ var CHILD_ENVELOPE_BYTES = 128;
260
+ var SCALAR_BYTES = 24;
261
+ var LITERAL_BYTES = 5;
262
+ var EST_MAX_DEPTH = 4;
263
+ var EST_OPAQUE_VALUE_BYTES = 4096;
264
+ var utf8ByteLength = typeof Buffer !== "undefined" && typeof Buffer.byteLength === "function" ? (s) => Buffer.byteLength(s, "utf8") : (s) => s.length * 3;
265
+ function estStringBytes(s) {
266
+ return 2 + utf8ByteLength(s);
267
+ }
268
+ function estValueBytes(v, depth = 0) {
269
+ if (typeof v === "string") return estStringBytes(v);
270
+ if (v === null || v === void 0 || typeof v === "boolean") return LITERAL_BYTES;
271
+ if (typeof v === "number" || typeof v === "bigint") return SCALAR_BYTES;
272
+ if (Array.isArray(v) && depth < EST_MAX_DEPTH) {
273
+ let total = 2 + Math.max(0, v.length - 1);
274
+ for (const item of v) total += estValueBytes(item, depth + 1);
275
+ return total;
276
+ }
277
+ if (typeof v === "object" && depth < EST_MAX_DEPTH && Object.getPrototypeOf(v) === Object.prototype) {
278
+ let total = 2;
279
+ for (const [k, val] of Object.entries(v)) {
280
+ total += estStringBytes(k) + 2 + estValueBytes(val, depth + 1);
281
+ }
282
+ return total;
283
+ }
284
+ return EST_OPAQUE_VALUE_BYTES;
285
+ }
286
+ function estMappingBytes(m) {
287
+ let total = 0;
288
+ for (const [k, v] of Object.entries(m)) total += estStringBytes(k) + 2 + estValueBytes(v);
289
+ return total;
290
+ }
291
+ function spanBytesEstimate(span) {
292
+ try {
293
+ const s = span;
294
+ let total = SPAN_ENVELOPE_BYTES;
295
+ for (const field of ["name", "statusMessage"]) {
296
+ if (typeof s[field] === "string") total += estStringBytes(s[field]);
297
+ }
298
+ const attrs = s.attributes;
299
+ if (attrs != null && typeof attrs === "object" && !Array.isArray(attrs)) {
300
+ total += estMappingBytes(attrs);
301
+ }
302
+ for (const key of ["events", "links"]) {
303
+ const coll = s[key];
304
+ if (!Array.isArray(coll)) continue;
305
+ for (const child of coll) {
306
+ total += CHILD_ENVELOPE_BYTES;
307
+ const ca = child?.attributes;
308
+ if (ca != null && typeof ca === "object" && !Array.isArray(ca)) {
309
+ total += estMappingBytes(ca);
310
+ }
311
+ }
312
+ }
313
+ return total;
314
+ } catch {
315
+ return SPAN_ENVELOPE_BYTES;
316
+ }
317
+ }
318
+ function spanAttrCount(span) {
319
+ const attrs = span.attributes;
320
+ if (attrs == null) return 0;
321
+ if (attrs instanceof Map) return attrs.size;
322
+ if (typeof attrs === "object") return Object.keys(attrs).length;
323
+ return 0;
324
+ }
325
+ var BatchSpanProcessor = class _BatchSpanProcessor {
326
+ _exporters;
327
+ _batchSize;
328
+ _batchTimeoutMs;
329
+ _maxQueueSize;
330
+ _debug;
331
+ _queue = [];
332
+ _timer = null;
333
+ _started = false;
334
+ _flushing = false;
335
+ _beforeExitHandler = null;
336
+ // Retry tracking for failed batches (Audit #5)
337
+ _retryCounts = /* @__PURE__ */ new Map();
338
+ static MAX_RETRIES = 3;
339
+ _lastRefusalWarnAt = Number.NEGATIVE_INFINITY;
340
+ // ── Masking (see `../masking.ts`) ──────────────────────────────────────────
341
+ _mask;
342
+ _lastMaskWarnAt = Number.NEGATIVE_INFINITY;
343
+ _lastSlowMaskWarnAt = Number.NEGATIVE_INFINITY;
344
+ // Metrics
345
+ /** DEPRECATED flat total. Retained as the exact SUM of
346
+ * `droppedSpansByReason` so existing readers keep working (RULING §5
347
+ * back-compat — the same deprecate-and-alias shape this codebase used for
348
+ * `complete`->`settled` and `spans_flushed_total`). Prefer the labelled
349
+ * record: one integer cannot tell an under-provisioned queue from a dead
350
+ * gateway from a redeploy. */
351
+ droppedSpans = 0;
352
+ droppedSpansByReason = {
353
+ queue_full: 0,
354
+ transport_refused: 0,
355
+ shutdown_residue: 0
356
+ };
357
+ exportedSpans = 0;
358
+ /** Export ATTEMPTS, not a span count. */
359
+ failedExports = 0;
360
+ /**
361
+ * Fields whose mask callback threw and were replaced with
362
+ * `MASK_ERROR_MARKER`. A FIELD count, not a span count — one span can
363
+ * contribute several. Non-zero means those fields carry a marker instead of
364
+ * data: a customer-code bug, not a transport one.
365
+ */
366
+ maskErrors = 0;
367
+ constructor(options) {
368
+ this._exporters = [...options.exporters];
369
+ const requestedBatchSize = options.batchSize ?? DEFAULT_BATCH_SIZE;
370
+ const clampedBatchSize = Math.max(1, Math.min(requestedBatchSize, 1e4));
371
+ if (clampedBatchSize !== requestedBatchSize) {
372
+ warn(
373
+ `batchSize=${requestedBatchSize} is outside the allowed range [1, 10000]; clamping to ${clampedBatchSize}`
374
+ );
375
+ }
376
+ this._batchSize = clampedBatchSize;
377
+ this._batchTimeoutMs = options.batchTimeoutMs ?? 1e3;
378
+ this._maxQueueSize = options.maxQueueSize ?? 1e4;
379
+ this._debug = options.debug ?? false;
380
+ this._mask = options.mask;
381
+ }
382
+ start() {
383
+ if (this._started) return;
384
+ this._started = true;
385
+ this._timer = setInterval(() => {
386
+ void this._exportBatch();
387
+ }, this._batchTimeoutMs);
388
+ this._timer.unref();
389
+ this._beforeExitHandler = () => {
390
+ void this.shutdown();
391
+ };
392
+ process.once("beforeExit", this._beforeExitHandler);
393
+ }
394
+ /** Record `count` discarded spans under `reason`.
395
+ *
396
+ * `droppedSpans` is maintained as the exact sum of the labelled counters
397
+ * (RULING §5 back-compat), so the locked pins — which read the flat
398
+ * integer — stay meaningful. */
399
+ _recordDropped(reason, count = 1) {
400
+ this.droppedSpans += count;
401
+ this.droppedSpansByReason[reason] += count;
402
+ }
403
+ /**
404
+ * Run the customer mask over a batch, in place. Never throws.
405
+ *
406
+ * Failure semantics are ruled in `../masking.ts`: a field whose mask throws
407
+ * becomes `MASK_ERROR_MARKER` and the span is kept. The counter is per FIELD;
408
+ * both warnings are rate-limited to one per window so a mask that throws on
409
+ * every span cannot flood the customer's logs — the same shape as the
410
+ * transport-refusal warning above.
411
+ */
412
+ _applyMask(batch) {
413
+ const mask = this._mask;
414
+ if (mask === void 0) return;
415
+ const { errors, elapsedMs } = applyMaskBatch(batch, mask);
416
+ const now = Date.now();
417
+ if (errors > 0) {
418
+ this.maskErrors += errors;
419
+ if (now - this._lastMaskWarnAt > MASK_WARN_WINDOW_MS) {
420
+ this._lastMaskWarnAt = now;
421
+ warnMaskErrors(errors, this.maskErrors);
422
+ }
423
+ }
424
+ if (elapsedMs > MASK_BUDGET_MS_PER_SPAN * batch.length && now - this._lastSlowMaskWarnAt > MASK_WARN_WINDOW_MS) {
425
+ this._lastSlowMaskWarnAt = now;
426
+ warnMaskSlow(batch.length, elapsedMs);
427
+ }
428
+ }
429
+ /**
430
+ * Drain what we hold, or name what we could not (F-SDKDRAIN-001).
431
+ *
432
+ * Per RULING §4 (option E, hard-bounded) the drain loops until ONE of: the
433
+ * queue is empty; the deadline expires; or a full round completes with no
434
+ * exporter returning SUCCESS.
435
+ *
436
+ * ⚠ The `_flushing` handling is load-bearing, and `SDKDRAIN_JS_004` exists
437
+ * to catch its absence. `_exportBatch()` returns immediately when an export
438
+ * is already in flight (`:171`), so a loop that merely calls it again makes
439
+ * NO progress and abandons the queue exactly as before — measured at 900 of
440
+ * 1,000. We await a tick instead, the shape `flush()` already models.
441
+ *
442
+ * Anything still queued when the loop stops is COUNTED as `shutdown_residue`
443
+ * and announced with a WARNING. The warning is the primary signal, not the
444
+ * counter: a counter incremented inside `shutdown()` is written to memory
445
+ * about to be freed and has no reader (RULING §2 / §8.2).
446
+ */
447
+ async shutdown(timeoutMs = SHUTDOWN_BUDGET_MS) {
448
+ if (!this._started) return;
449
+ this._started = false;
450
+ if (this._timer) {
451
+ clearInterval(this._timer);
452
+ this._timer = null;
453
+ }
454
+ if (this._beforeExitHandler) {
455
+ process.removeListener("beforeExit", this._beforeExitHandler);
456
+ this._beforeExitHandler = null;
457
+ }
458
+ const reserveMs = Math.min(SHUTDOWN_RESERVE_MS, timeoutMs / 2);
459
+ const drainDeadline = Date.now() + Math.max(0, timeoutMs - reserveMs);
460
+ while (this._queue.length > 0 || this._flushing) {
461
+ if (Date.now() >= drainDeadline) break;
462
+ const outcome = await this._exportBatch();
463
+ if (outcome === 3 /* Busy */) {
464
+ await new Promise((r) => setTimeout(r, 1));
465
+ continue;
466
+ }
467
+ if (outcome !== 1 /* Delivered */) {
468
+ break;
469
+ }
470
+ }
471
+ const residue = this._queue.length;
472
+ if (residue > 0) {
473
+ this._queue.length = 0;
474
+ this._recordDropped("shutdown_residue", residue);
475
+ warn(
476
+ `shutdown() gave up with ${residue} span(s) still queued (reason=shutdown_residue) \u2014 they were NOT delivered. The ${timeoutMs} ms shutdown budget expired or the transport stopped accepting. Raise the shutdown timeout, or your container's termination grace period, to lose less.`
477
+ );
478
+ }
479
+ for (const exporter of this._exporters) {
480
+ try {
481
+ await exporter.shutdown();
482
+ } catch (e) {
483
+ debug(`Error shutting down ${exporter.name}: ${e}`);
484
+ }
485
+ }
486
+ this._retryCounts.clear();
487
+ debug(
488
+ `BatchSpanProcessor shutdown. Exported: ${this.exportedSpans}, Dropped: ${this.droppedSpans}, Failed: ${this.failedExports}`
489
+ );
490
+ }
491
+ onSpanEnd(span) {
492
+ if (!this._started) return;
493
+ if (this._queue.length >= this._maxQueueSize) {
494
+ this._recordDropped("queue_full");
495
+ if (this.droppedSpans === 1 || this.droppedSpans % 1e3 === 0) {
496
+ warn(`Span queue full (${this._maxQueueSize}). ${this.droppedSpans} spans dropped so far.`);
497
+ }
498
+ return;
499
+ }
500
+ this._queue.push(span);
501
+ if (this._queue.length >= this._batchSize) {
502
+ void this._exportBatch();
503
+ }
504
+ }
505
+ /**
506
+ * Flush pending spans.
507
+ *
508
+ * @returns `true` only if everything queued at entry was DELIVERED.
509
+ *
510
+ * RULING §6. This used to answer a different question — "is the queue
511
+ * empty?" — and those two diverge in exactly one case: when spans left the
512
+ * queue WITHOUT reaching the transport. That case is the entire finding. A
513
+ * customer who calls `flush()` before exit and gets `true` has done
514
+ * everything right; silence lets them discover the problem, a false
515
+ * affirmative forecloses it.
516
+ *
517
+ * Returns `false` when (a) the deadline expires with spans still queued,
518
+ * (b) any span was discarded during the window — breaker refusal or retry
519
+ * exhaustion — or (c) it is called after `shutdown()` and the shutdown
520
+ * residue was non-zero.
521
+ *
522
+ * ⚠ (b) reads the flat total, so a concurrent `queue_full` drop of a span
523
+ * that arrived DURING the window also answers `false`. That is the
524
+ * conservative direction on purpose: a false negative costs a caller one
525
+ * more flush, a false positive is the defect being fixed.
526
+ */
527
+ async flush(timeoutMs = SHUTDOWN_BUDGET_MS) {
528
+ if (!this._started) {
529
+ return this._queue.length === 0 && this.droppedSpansByReason.shutdown_residue === 0;
530
+ }
531
+ const start = Date.now();
532
+ const discardedAtEntry = this.droppedSpans;
533
+ while (this._queue.length > 0 || this._flushing) {
534
+ if (!this._flushing && this._queue.length > 0) {
535
+ await this._exportBatch();
536
+ } else {
537
+ await new Promise((r) => setTimeout(r, 1));
538
+ }
539
+ if (Date.now() - start > timeoutMs) return false;
540
+ }
541
+ return this.droppedSpans === discardedAtEntry;
542
+ }
543
+ getMetrics() {
544
+ return {
545
+ exportedSpans: this.exportedSpans,
546
+ droppedSpans: this.droppedSpans,
547
+ droppedSpansByReason: { ...this.droppedSpansByReason },
548
+ failedExports: this.failedExports,
549
+ maskErrors: this.maskErrors,
550
+ queueSize: this._queue.length,
551
+ queueCapacity: this._maxQueueSize,
552
+ queueUtilization: this._queue.length / this._maxQueueSize
553
+ };
554
+ }
555
+ async _exportBatch() {
556
+ if (this._flushing) return 3 /* Busy */;
557
+ if (this._queue.length === 0) return 0 /* Empty */;
558
+ this._flushing = true;
559
+ try {
560
+ let take = 0;
561
+ let pairs = 0;
562
+ let nbytes = 0;
563
+ const limit = Math.min(this._batchSize, this._queue.length);
564
+ while (take < limit) {
565
+ const head = this._queue[take];
566
+ const spanPairs = spanAttrCount(head);
567
+ const spanBytes = spanBytesEstimate(head);
568
+ if (take > 0 && (pairs + spanPairs > MAX_ATTRIBUTE_PAIRS_PER_BATCH || nbytes + spanBytes > MAX_BATCH_BYTES)) {
569
+ break;
570
+ }
571
+ pairs += spanPairs;
572
+ nbytes += spanBytes;
573
+ take++;
574
+ }
575
+ const batch = this._queue.splice(0, take);
576
+ if (batch.length === 0) return 0 /* Empty */;
577
+ if (this._mask !== void 0) {
578
+ this._applyMask(batch);
579
+ }
580
+ debug(`Exporting batch of ${batch.length} spans`);
581
+ let batchExported = false;
582
+ for (const exporter of this._exporters) {
583
+ try {
584
+ const result = await exporter.export(batch);
585
+ if (result === "success" /* SUCCESS */) {
586
+ if (!batchExported) {
587
+ this.exportedSpans += batch.length;
588
+ batchExported = true;
589
+ for (const span of batch) {
590
+ this._retryCounts.delete(span.spanId);
591
+ }
592
+ }
593
+ } else {
594
+ this.failedExports++;
595
+ }
596
+ } catch (e) {
597
+ this.failedExports++;
598
+ debug(`Export to ${exporter.name} failed: ${e}`);
599
+ }
600
+ }
601
+ if (!batchExported) {
602
+ let dropped = 0;
603
+ const retryable = batch.filter((span) => {
604
+ const count = (this._retryCounts.get(span.spanId) ?? 0) + 1;
605
+ if (count > _BatchSpanProcessor.MAX_RETRIES) {
606
+ this._retryCounts.delete(span.spanId);
607
+ this._recordDropped("transport_refused");
608
+ dropped++;
609
+ return false;
610
+ }
611
+ this._retryCounts.set(span.spanId, count);
612
+ return true;
613
+ });
614
+ if (retryable.length > 0) {
615
+ this._queue.unshift(...retryable);
616
+ debug(`Re-queued ${retryable.length} spans for retry (${batch.length - retryable.length} dropped after max retries)`);
617
+ }
618
+ if (dropped > 0) {
619
+ const now = Date.now();
620
+ if (now - this._lastRefusalWarnAt > REFUSAL_WARN_WINDOW_MS) {
621
+ this._lastRefusalWarnAt = now;
622
+ warn(
623
+ `${dropped} span(s) DISCARDED (reason=transport_refused) after ${_BatchSpanProcessor.MAX_RETRIES} failed export attempts each \u2014 the endpoint is not accepting spans and the retry budget is spent. ${this.droppedSpansByReason.transport_refused} span(s) discarded this way so far in this process. This data is gone; check the apiKey and the endpoint.`
624
+ );
625
+ }
626
+ }
627
+ }
628
+ return batchExported ? 1 /* Delivered */ : 2 /* Failed */;
629
+ } finally {
630
+ this._flushing = false;
631
+ }
632
+ }
633
+ };
634
+
93
635
  // src/config.ts
94
636
  var DEFAULT_ENDPOINT = "https://app.risicare.ai";
95
637
  function resolveConfig(config) {
@@ -109,11 +651,11 @@ function resolveConfig(config) {
109
651
  const sampleRateRaw = config?.sampleRate ?? parseFloat(env.RISICARE_SAMPLE_RATE ?? "1.0");
110
652
  const debug2 = config?.debug ?? parseBool(env.RISICARE_DEBUG, false);
111
653
  const compress = config?.compress ?? parseBool(env.RISICARE_COMPRESS, false);
112
- const batchSizeRaw = config?.batchSize ?? parseNumericEnv(env.RISICARE_BATCH_SIZE, 100);
654
+ const batchSizeRaw = config?.batchSize ?? parseNumericEnv(env.RISICARE_BATCH_SIZE, DEFAULT_BATCH_SIZE);
113
655
  const batchTimeoutMsRaw = config?.batchTimeoutMs ?? parseNumericEnv(env.RISICARE_BATCH_TIMEOUT_MS, 1e3);
114
656
  const maxQueueSizeRaw = config?.maxQueueSize ?? parseNumericEnv(env.RISICARE_MAX_QUEUE_SIZE, 1e4);
115
657
  const sampleRate = validateSampleRate(sampleRateRaw);
116
- const batchSize = validatePositiveInt("batchSize", batchSizeRaw, 100, 1, 1e4);
658
+ const batchSize = validatePositiveInt("batchSize", batchSizeRaw, DEFAULT_BATCH_SIZE, 1, 1e4);
117
659
  const batchTimeoutMs = validatePositiveInt("batchTimeoutMs", batchTimeoutMsRaw, 1e3, 1, 6e5);
118
660
  const maxQueueSize = validatePositiveInt("maxQueueSize", maxQueueSizeRaw, 1e4, 1, 1e6);
119
661
  let enabled;
@@ -139,7 +681,9 @@ function resolveConfig(config) {
139
681
  maxQueueSize,
140
682
  debug: debug2,
141
683
  compress,
142
- metadata: config?.metadata ?? {}
684
+ metadata: config?.metadata ?? {},
685
+ // No env fallback — see the field's note on RisicareConfig.
686
+ mask: config?.mask
143
687
  };
144
688
  }
145
689
  function parseBool(value, defaultValue) {
@@ -550,47 +1094,6 @@ function shouldSample(traceId, sampleRate) {
550
1094
  return hash / 4294967295 < sampleRate;
551
1095
  }
552
1096
 
553
- // src/globals.ts
554
- var import_node_async_hooks = require("async_hooks");
555
- var G = globalThis;
556
- var PREFIX = "__risicare_";
557
- function getClient() {
558
- return G[PREFIX + "client"];
559
- }
560
- function setClient(client) {
561
- G[PREFIX + "client"] = client;
562
- }
563
- function getTracer() {
564
- return G[PREFIX + "tracer"];
565
- }
566
- function setTracer(tracer) {
567
- G[PREFIX + "tracer"] = tracer;
568
- }
569
- function getContextStorage() {
570
- if (!G[PREFIX + "ctx"]) {
571
- G[PREFIX + "ctx"] = new import_node_async_hooks.AsyncLocalStorage();
572
- }
573
- return G[PREFIX + "ctx"];
574
- }
575
- function getRegistry() {
576
- if (!G[PREFIX + "registry"]) {
577
- G[PREFIX + "registry"] = /* @__PURE__ */ new Map();
578
- }
579
- return G[PREFIX + "registry"];
580
- }
581
- function getOpCount() {
582
- return G[PREFIX + "opcount"] ?? 0;
583
- }
584
- function setOpCount(n) {
585
- G[PREFIX + "opcount"] = n;
586
- }
587
- function getDebug() {
588
- return G[PREFIX + "debug"] ?? false;
589
- }
590
- function setDebugFlag(enabled) {
591
- G[PREFIX + "debug"] = enabled;
592
- }
593
-
594
1097
  // src/context/storage.ts
595
1098
  function storage() {
596
1099
  return getContextStorage();
@@ -789,180 +1292,8 @@ var Tracer = class {
789
1292
  }
790
1293
  };
791
1294
 
792
- // src/utils/log.ts
793
- function setDebug(enabled) {
794
- setDebugFlag(enabled);
795
- }
796
- function debug(msg) {
797
- if (getDebug()) {
798
- process.stderr.write(`[risicare] ${msg}
799
- `);
800
- }
801
- }
802
- function warn(msg) {
803
- process.stderr.write(`[risicare] WARNING: ${msg}
804
- `);
805
- }
806
-
807
- // src/exporters/batch.ts
808
- var BatchSpanProcessor = class _BatchSpanProcessor {
809
- _exporters;
810
- _batchSize;
811
- _batchTimeoutMs;
812
- _maxQueueSize;
813
- _debug;
814
- _queue = [];
815
- _timer = null;
816
- _started = false;
817
- _flushing = false;
818
- _beforeExitHandler = null;
819
- // Retry tracking for failed batches (Audit #5)
820
- _retryCounts = /* @__PURE__ */ new Map();
821
- static MAX_RETRIES = 3;
822
- // Metrics
823
- droppedSpans = 0;
824
- exportedSpans = 0;
825
- failedExports = 0;
826
- constructor(options) {
827
- this._exporters = [...options.exporters];
828
- const requestedBatchSize = options.batchSize ?? 100;
829
- const clampedBatchSize = Math.max(1, Math.min(requestedBatchSize, 1e4));
830
- if (clampedBatchSize !== requestedBatchSize) {
831
- warn(
832
- `batchSize=${requestedBatchSize} is outside the allowed range [1, 10000]; clamping to ${clampedBatchSize}`
833
- );
834
- }
835
- this._batchSize = clampedBatchSize;
836
- this._batchTimeoutMs = options.batchTimeoutMs ?? 1e3;
837
- this._maxQueueSize = options.maxQueueSize ?? 1e4;
838
- this._debug = options.debug ?? false;
839
- }
840
- start() {
841
- if (this._started) return;
842
- this._started = true;
843
- this._timer = setInterval(() => {
844
- void this._exportBatch();
845
- }, this._batchTimeoutMs);
846
- this._timer.unref();
847
- this._beforeExitHandler = () => {
848
- void this.shutdown();
849
- };
850
- process.once("beforeExit", this._beforeExitHandler);
851
- }
852
- async shutdown(timeoutMs = 5e3) {
853
- if (!this._started) return;
854
- this._started = false;
855
- if (this._timer) {
856
- clearInterval(this._timer);
857
- this._timer = null;
858
- }
859
- if (this._beforeExitHandler) {
860
- process.removeListener("beforeExit", this._beforeExitHandler);
861
- this._beforeExitHandler = null;
862
- }
863
- const flushPromise = this._exportBatch();
864
- const timeoutPromise = new Promise((resolve) => setTimeout(resolve, timeoutMs));
865
- await Promise.race([flushPromise, timeoutPromise]);
866
- for (const exporter of this._exporters) {
867
- try {
868
- await exporter.shutdown();
869
- } catch (e) {
870
- debug(`Error shutting down ${exporter.name}: ${e}`);
871
- }
872
- }
873
- this._retryCounts.clear();
874
- debug(
875
- `BatchSpanProcessor shutdown. Exported: ${this.exportedSpans}, Dropped: ${this.droppedSpans}, Failed: ${this.failedExports}`
876
- );
877
- }
878
- onSpanEnd(span) {
879
- if (!this._started) return;
880
- if (this._queue.length >= this._maxQueueSize) {
881
- this.droppedSpans++;
882
- if (this.droppedSpans === 1 || this.droppedSpans % 1e3 === 0) {
883
- warn(`Span queue full (${this._maxQueueSize}). ${this.droppedSpans} spans dropped so far.`);
884
- }
885
- return;
886
- }
887
- this._queue.push(span);
888
- if (this._queue.length >= this._batchSize) {
889
- void this._exportBatch();
890
- }
891
- }
892
- async flush(timeoutMs = 5e3) {
893
- if (!this._started) return true;
894
- const start = Date.now();
895
- while (this._queue.length > 0 || this._flushing) {
896
- if (!this._flushing && this._queue.length > 0) {
897
- await this._exportBatch();
898
- } else {
899
- await new Promise((r) => setTimeout(r, 1));
900
- }
901
- if (Date.now() - start > timeoutMs) return false;
902
- }
903
- return true;
904
- }
905
- getMetrics() {
906
- return {
907
- exportedSpans: this.exportedSpans,
908
- droppedSpans: this.droppedSpans,
909
- failedExports: this.failedExports,
910
- queueSize: this._queue.length,
911
- queueCapacity: this._maxQueueSize,
912
- queueUtilization: this._queue.length / this._maxQueueSize
913
- };
914
- }
915
- async _exportBatch() {
916
- if (this._flushing || this._queue.length === 0) return;
917
- this._flushing = true;
918
- try {
919
- const batch = this._queue.splice(0, this._batchSize);
920
- if (batch.length === 0) return;
921
- debug(`Exporting batch of ${batch.length} spans`);
922
- let batchExported = false;
923
- for (const exporter of this._exporters) {
924
- try {
925
- const result = await exporter.export(batch);
926
- if (result === "success" /* SUCCESS */) {
927
- if (!batchExported) {
928
- this.exportedSpans += batch.length;
929
- batchExported = true;
930
- for (const span of batch) {
931
- this._retryCounts.delete(span.spanId);
932
- }
933
- }
934
- } else {
935
- this.failedExports++;
936
- }
937
- } catch (e) {
938
- this.failedExports++;
939
- debug(`Export to ${exporter.name} failed: ${e}`);
940
- }
941
- }
942
- if (!batchExported) {
943
- const retryable = batch.filter((span) => {
944
- const count = (this._retryCounts.get(span.spanId) ?? 0) + 1;
945
- if (count > _BatchSpanProcessor.MAX_RETRIES) {
946
- this._retryCounts.delete(span.spanId);
947
- this.droppedSpans++;
948
- return false;
949
- }
950
- this._retryCounts.set(span.spanId, count);
951
- return true;
952
- });
953
- if (retryable.length > 0) {
954
- this._queue.unshift(...retryable);
955
- debug(`Re-queued ${retryable.length} spans for retry (${batch.length - retryable.length} dropped after max retries)`);
956
- }
957
- }
958
- } finally {
959
- this._flushing = false;
960
- }
961
- }
962
- };
963
-
964
1295
  // src/version.ts
965
- var SDK_VERSION = "0.4.2";
1296
+ var SDK_VERSION = "0.5.0";
966
1297
 
967
1298
  // src/exporters/http.ts
968
1299
  var HttpExporter = class {
@@ -2386,10 +2717,20 @@ function shutdownFixRuntime() {
2386
2717
  }
2387
2718
 
2388
2719
  // src/client.ts
2720
+ var TERMINATING_SIGNALS = [
2721
+ ["SIGTERM", 15],
2722
+ ["SIGINT", 2]
2723
+ ];
2724
+ var BACKSTOP_MARGIN_MS = 500;
2725
+ var _finalMetrics;
2389
2726
  var RisicareClient = class {
2390
2727
  config;
2391
2728
  processor;
2392
2729
  tracer;
2730
+ /** RULING §5. The signal path does NOT clear the global client, so without
2731
+ * this flag `getMetrics()` would keep reporting `"running"` over a processor
2732
+ * that has already been torn down. */
2733
+ isShutdown = false;
2393
2734
  _shutdownPromise;
2394
2735
  _shutdownHandlers = [];
2395
2736
  constructor(config) {
@@ -2409,14 +2750,27 @@ var RisicareClient = class {
2409
2750
  compress: this.config.compress
2410
2751
  });
2411
2752
  } else {
2412
- exporter = new ConsoleExporter();
2753
+ exporter = void 0;
2754
+ if (this.config.enabled) {
2755
+ try {
2756
+ console.warn(
2757
+ `[risicare] tracing is enabled but NO API key is configured \u2014 spans are created and then DROPPED, not sent to ${this.config.endpoint}. Pass apiKey to init() (or set the RISICARE_API_KEY env var). Span data is NOT written to the console: it would be unredacted. Pass debug:true if you want console output for local development.`
2758
+ );
2759
+ } catch {
2760
+ }
2761
+ }
2413
2762
  }
2414
2763
  this.processor = new BatchSpanProcessor({
2415
- exporters: [exporter],
2764
+ exporters: exporter ? [exporter] : [],
2416
2765
  batchSize: this.config.batchSize,
2417
2766
  batchTimeoutMs: this.config.batchTimeoutMs,
2418
2767
  maxQueueSize: this.config.maxQueueSize,
2419
- debug: this.config.debug
2768
+ debug: this.config.debug,
2769
+ // The processor is the ONE choke point every exporter is behind. Masking
2770
+ // anywhere downstream (in the HTTP exporter, say) would leave a hole for
2771
+ // any other exporter; masking upstream would put customer code on the
2772
+ // span-end call path.
2773
+ mask: this.config.mask
2420
2774
  });
2421
2775
  this.tracer = new Tracer({
2422
2776
  onSpanEnd: (span) => this.processor.onSpanEnd(span),
@@ -2470,21 +2824,82 @@ var RisicareClient = class {
2470
2824
  }
2471
2825
  this._shutdownHandlers = [];
2472
2826
  await this.processor.shutdown();
2827
+ this.isShutdown = true;
2828
+ _finalMetrics = this.processor.getMetrics();
2473
2829
  }
2830
+ /**
2831
+ * Flush pending spans.
2832
+ *
2833
+ * @returns `true` only if everything queued at entry was DELIVERED.
2834
+ *
2835
+ * RULING §6: this used to discard the processor's boolean and return
2836
+ * `Promise<void>`, which resolves without throwing and reads to a caller
2837
+ * exactly like success. A discarded answer is not meaningfully better than a
2838
+ * false one — both leave the customer unable to tell *drained* from
2839
+ * *discarded*.
2840
+ */
2474
2841
  async flush() {
2475
- await this.processor.flush();
2842
+ return this.processor.flush();
2476
2843
  }
2844
+ /**
2845
+ * SDK-RELEASE-RULING.md §3 — who decides whether the process dies.
2846
+ *
2847
+ * The contract, and it is the same one the Python SDK now satisfies:
2848
+ *
2849
+ * the SDK's signal handler never CHANGES whether the signal
2850
+ * terminates the process.
2851
+ *
2852
+ * Registering ANY listener for SIGTERM/SIGINT displaces Node's default
2853
+ * terminate. Before this, the SDK registered one unconditionally, and on the
2854
+ * success path `clearTimeout` removed the 5 s `process.exit(1)` backstop —
2855
+ * so a JS app with a live event loop drained, cleared its own only exit, and
2856
+ * **ran forever**. The orchestrator waited out the whole grace period and
2857
+ * SIGKILLed, which exits **137** and reads as OOM-killed in every dashboard.
2858
+ * Measured >25 s alive on both 0.5.0 and a clean-rebuilt 0.4.2, so this is
2859
+ * PRE-EXISTING (`F-SDKJSEXIT-001`), not a regression of the data-loss fix.
2860
+ *
2861
+ * The rule splits on one question — did the signal already have an owner?
2862
+ *
2863
+ * * **No prior listener.** Node's default was termination and OUR
2864
+ * registration displaced it. We owe the process that death.
2865
+ * * **A prior listener exists.** The application took ownership before the
2866
+ * SDK loaded. We drain and RETURN; termination was never ours to decide,
2867
+ * and forcing it would cut off the app's own graceful shutdown.
2868
+ *
2869
+ * ⚠ `beforeExit` is deliberately NOT in that logic. It is not a signal and
2870
+ * carries no termination the SDK could displace — the loop has already
2871
+ * drained and the process is leaving on its own.
2872
+ */
2477
2873
  _registerShutdownHooks() {
2478
- const onShutdown = () => {
2479
- const timeout = setTimeout(() => process.exit(1), 5e3);
2480
- timeout.unref();
2874
+ const onBeforeExit = () => {
2481
2875
  this.shutdown().catch(() => {
2482
- }).finally(() => clearTimeout(timeout));
2876
+ });
2483
2877
  };
2484
- const signals = ["beforeExit", "SIGTERM", "SIGINT"];
2485
- for (const signal of signals) {
2486
- process.once(signal, onShutdown);
2487
- this._shutdownHandlers.push({ signal, handler: onShutdown });
2878
+ process.once("beforeExit", onBeforeExit);
2879
+ this._shutdownHandlers.push({ signal: "beforeExit", handler: onBeforeExit });
2880
+ for (const [signal, signum] of TERMINATING_SIGNALS) {
2881
+ const weDisplacedDefault = process.listenerCount(signal) === 0;
2882
+ const handler = () => {
2883
+ const backstop = setTimeout(
2884
+ () => process.exit(128 + signum),
2885
+ SHUTDOWN_BUDGET_MS + BACKSTOP_MARGIN_MS
2886
+ );
2887
+ backstop.unref();
2888
+ this.shutdown().catch(() => {
2889
+ }).finally(() => {
2890
+ clearTimeout(backstop);
2891
+ if (!weDisplacedDefault) return;
2892
+ try {
2893
+ process.kill(process.pid, signal);
2894
+ } catch {
2895
+ process.exit(128 + signum);
2896
+ }
2897
+ const failsafe = setTimeout(() => process.exit(128 + signum), 100);
2898
+ failsafe.unref();
2899
+ });
2900
+ };
2901
+ process.once(signal, handler);
2902
+ this._shutdownHandlers.push({ signal, handler });
2488
2903
  }
2489
2904
  }
2490
2905
  };
@@ -2521,6 +2936,7 @@ function init(config) {
2521
2936
  }
2522
2937
  return;
2523
2938
  }
2939
+ _finalMetrics = void 0;
2524
2940
  const client = new RisicareClient(config);
2525
2941
  setClient(client);
2526
2942
  setTracer(client.tracer);
@@ -2538,8 +2954,8 @@ async function shutdown() {
2538
2954
  }
2539
2955
  async function flush() {
2540
2956
  const client = getClient();
2541
- if (!client) return;
2542
- await client.flush();
2957
+ if (!client) return true;
2958
+ return client.flush();
2543
2959
  }
2544
2960
  function enable() {
2545
2961
  const client = getClient();
@@ -2562,13 +2978,29 @@ function getTraceContent() {
2562
2978
  }
2563
2979
  function getMetrics() {
2564
2980
  const client = getClient();
2565
- return client?.processor.getMetrics() ?? {
2981
+ if (client && !client.isShutdown) {
2982
+ return { ...client.processor.getMetrics(), sdkState: "running" };
2983
+ }
2984
+ if (_finalMetrics) {
2985
+ return {
2986
+ ..._finalMetrics,
2987
+ droppedSpansByReason: { ..._finalMetrics.droppedSpansByReason },
2988
+ sdkState: "shutdown"
2989
+ };
2990
+ }
2991
+ return {
2566
2992
  exportedSpans: 0,
2567
2993
  droppedSpans: 0,
2994
+ droppedSpansByReason: {
2995
+ queue_full: 0,
2996
+ transport_refused: 0,
2997
+ shutdown_residue: 0
2998
+ },
2568
2999
  failedExports: 0,
2569
3000
  queueSize: 0,
2570
3001
  queueCapacity: 0,
2571
- queueUtilization: 0
3002
+ queueUtilization: 0,
3003
+ sdkState: "uninitialised"
2572
3004
  };
2573
3005
  }
2574
3006
  var _ERROR_DEDUP_TTL_MS = 5 * 60 * 1e3;
@@ -2576,8 +3008,7 @@ var _ERROR_DEDUP_MAX = 1e3;
2576
3008
  var _recentErrors = /* @__PURE__ */ new Map();
2577
3009
  function _errorFingerprint(err) {
2578
3010
  const raw = `${err.constructor?.name ?? "Error"}:${String(err.message ?? "").slice(0, 200)}`;
2579
- const { createHash: createHash2 } = require("crypto");
2580
- return createHash2("sha256").update(raw).digest("hex").slice(0, 16);
3011
+ return (0, import_node_crypto3.createHash)("sha256").update(raw).digest("hex").slice(0, 16);
2581
3012
  }
2582
3013
  function _isDuplicateError(fingerprint) {
2583
3014
  const now = Date.now();
@@ -2635,13 +3066,17 @@ function score(traceId, name, value, options) {
2635
3066
  if (!client?.enabled || !client.config.apiKey) return;
2636
3067
  const endpoint = client.config.endpoint.replace(/\/$/, "");
2637
3068
  const url = `${endpoint}/api/v1/scores`;
3069
+ let comment = options?.comment;
3070
+ if (comment !== void 0 && client.config.mask) {
3071
+ comment = maskText(client.config.mask, SCORE_COMMENT_KEY, comment);
3072
+ }
2638
3073
  const body = JSON.stringify({
2639
3074
  trace_id: traceId,
2640
3075
  name,
2641
3076
  score: value,
2642
3077
  source: "sdk",
2643
3078
  ...options?.spanId && { span_id: options.spanId },
2644
- ...options?.comment && { comment: options.comment }
3079
+ ...comment && { comment }
2645
3080
  });
2646
3081
  fetch(url, {
2647
3082
  method: "POST",
@@ -3619,7 +4054,7 @@ var RisicareLlamaIndexHandler = class {
3619
4054
  };
3620
4055
 
3621
4056
  // src/webhooks.ts
3622
- var import_node_crypto3 = require("crypto");
4057
+ var import_node_crypto4 = require("crypto");
3623
4058
  var import_node_buffer = require("buffer");
3624
4059
  var DEFAULT_TIMESTAMP_TOLERANCE_S = 300;
3625
4060
  var SIGNATURE_HEADER = "X-Risicare-Signature";
@@ -3732,7 +4167,7 @@ function safeHexEqual(computed, expected) {
3732
4167
  if (a.length !== b.length) {
3733
4168
  return false;
3734
4169
  }
3735
- return (0, import_node_crypto3.timingSafeEqual)(a, b);
4170
+ return (0, import_node_crypto4.timingSafeEqual)(a, b);
3736
4171
  }
3737
4172
  function verifyWebhookSignature(payload, headers, secret, opts = {}) {
3738
4173
  const toleranceS = opts.toleranceS ?? DEFAULT_TIMESTAMP_TOLERANCE_S;
@@ -3773,7 +4208,7 @@ function verifyWebhookSignature(payload, headers, secret, opts = {}) {
3773
4208
  `Webhook timestamp outside tolerance: skew=${skew}s, max=${toleranceS}s`
3774
4209
  );
3775
4210
  }
3776
- const hmac = (0, import_node_crypto3.createHmac)("sha256", secret);
4211
+ const hmac = (0, import_node_crypto4.createHmac)("sha256", secret);
3777
4212
  hmac.update(`${tsInSig}.`);
3778
4213
  hmac.update(payloadBytes);
3779
4214
  const computed = hmac.digest("hex");
@@ -3786,6 +4221,7 @@ function verifyWebhookSignature(payload, headers, secret, opts = {}) {
3786
4221
  AgentRole,
3787
4222
  DEFAULT_TIMESTAMP_TOLERANCE_S,
3788
4223
  GuardRejectedError,
4224
+ MASK_ERROR_MARKER,
3789
4225
  MessageType,
3790
4226
  RisicareCallbackHandler,
3791
4227
  RisicareLlamaIndexHandler,