risicare 0.4.2 → 0.5.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (72) hide show
  1. package/README.md +63 -0
  2. package/dist/frameworks/instructor.cjs +34 -18
  3. package/dist/frameworks/instructor.cjs.map +1 -1
  4. package/dist/frameworks/instructor.js +34 -18
  5. package/dist/frameworks/instructor.js.map +1 -1
  6. package/dist/frameworks/langchain.cjs +40 -24
  7. package/dist/frameworks/langchain.cjs.map +1 -1
  8. package/dist/frameworks/langchain.js +40 -24
  9. package/dist/frameworks/langchain.js.map +1 -1
  10. package/dist/frameworks/langgraph.cjs +40 -24
  11. package/dist/frameworks/langgraph.cjs.map +1 -1
  12. package/dist/frameworks/langgraph.js +40 -24
  13. package/dist/frameworks/langgraph.js.map +1 -1
  14. package/dist/frameworks/llamaindex.cjs +29 -13
  15. package/dist/frameworks/llamaindex.cjs.map +1 -1
  16. package/dist/frameworks/llamaindex.js +29 -13
  17. package/dist/frameworks/llamaindex.js.map +1 -1
  18. package/dist/index.cjs +1555 -761
  19. package/dist/index.cjs.map +1 -1
  20. package/dist/index.d.cts +237 -47
  21. package/dist/index.d.ts +237 -47
  22. package/dist/index.js +1704 -911
  23. package/dist/index.js.map +1 -1
  24. package/dist/providers/anthropic/index.cjs +40 -24
  25. package/dist/providers/anthropic/index.cjs.map +1 -1
  26. package/dist/providers/anthropic/index.js +40 -24
  27. package/dist/providers/anthropic/index.js.map +1 -1
  28. package/dist/providers/bedrock/index.cjs +40 -24
  29. package/dist/providers/bedrock/index.cjs.map +1 -1
  30. package/dist/providers/bedrock/index.js +40 -24
  31. package/dist/providers/bedrock/index.js.map +1 -1
  32. package/dist/providers/cerebras/index.cjs +40 -24
  33. package/dist/providers/cerebras/index.cjs.map +1 -1
  34. package/dist/providers/cerebras/index.js +40 -24
  35. package/dist/providers/cerebras/index.js.map +1 -1
  36. package/dist/providers/cohere/index.cjs +40 -24
  37. package/dist/providers/cohere/index.cjs.map +1 -1
  38. package/dist/providers/cohere/index.js +40 -24
  39. package/dist/providers/cohere/index.js.map +1 -1
  40. package/dist/providers/google/index.cjs +40 -24
  41. package/dist/providers/google/index.cjs.map +1 -1
  42. package/dist/providers/google/index.js +40 -24
  43. package/dist/providers/google/index.js.map +1 -1
  44. package/dist/providers/groq/index.cjs +40 -24
  45. package/dist/providers/groq/index.cjs.map +1 -1
  46. package/dist/providers/groq/index.js +40 -24
  47. package/dist/providers/groq/index.js.map +1 -1
  48. package/dist/providers/huggingface/index.cjs +40 -24
  49. package/dist/providers/huggingface/index.cjs.map +1 -1
  50. package/dist/providers/huggingface/index.js +40 -24
  51. package/dist/providers/huggingface/index.js.map +1 -1
  52. package/dist/providers/mistral/index.cjs +40 -24
  53. package/dist/providers/mistral/index.cjs.map +1 -1
  54. package/dist/providers/mistral/index.js +40 -24
  55. package/dist/providers/mistral/index.js.map +1 -1
  56. package/dist/providers/ollama/index.cjs +40 -24
  57. package/dist/providers/ollama/index.cjs.map +1 -1
  58. package/dist/providers/ollama/index.js +40 -24
  59. package/dist/providers/ollama/index.js.map +1 -1
  60. package/dist/providers/openai/index.cjs +40 -24
  61. package/dist/providers/openai/index.cjs.map +1 -1
  62. package/dist/providers/openai/index.js +40 -24
  63. package/dist/providers/openai/index.js.map +1 -1
  64. package/dist/providers/together/index.cjs +40 -24
  65. package/dist/providers/together/index.cjs.map +1 -1
  66. package/dist/providers/together/index.js +40 -24
  67. package/dist/providers/together/index.js.map +1 -1
  68. package/dist/providers/vercel-ai/index.cjs +34 -18
  69. package/dist/providers/vercel-ai/index.cjs.map +1 -1
  70. package/dist/providers/vercel-ai/index.js +34 -18
  71. package/dist/providers/vercel-ai/index.js.map +1 -1
  72. package/package.json +2 -2
package/dist/index.d.cts CHANGED
@@ -3,49 +3,6 @@ export { instrumentLangGraph } from './frameworks/langgraph.cjs';
3
3
  export { patchInstructor } from './frameworks/instructor.cjs';
4
4
  export { RisicareLlamaIndexHandler } from './frameworks/llamaindex.cjs';
5
5
 
6
- /**
7
- * SDK configuration with environment variable loading.
8
- *
9
- * Environment variables match the Python SDK exactly:
10
- * RISICARE_API_KEY, RISICARE_ENDPOINT, RISICARE_PROJECT_ID, etc.
11
- */
12
- interface RisicareConfig {
13
- /** API key for authentication (format: "rsk-{random}"). Each key is scoped to one project. */
14
- apiKey?: string;
15
- /** Gateway endpoint URL */
16
- endpoint?: string;
17
- /**
18
- * @deprecated Project is determined by your API key. This field is ignored
19
- * by the gateway and will be removed in v1.0. Use `serviceName` and
20
- * `environment` for within-project organization.
21
- */
22
- projectId?: string;
23
- /** Environment name (production, staging, development). Used for within-project organization. */
24
- environment?: string;
25
- /** Service name for within-project organization. */
26
- serviceName?: string;
27
- /** Service version */
28
- serviceVersion?: string;
29
- /** Whether tracing is enabled (default: true if apiKey provided) */
30
- enabled?: boolean;
31
- /** Whether to capture prompt/completion content (default: true) */
32
- traceContent?: boolean;
33
- /** Sample rate 0.0–1.0 (default: 1.0 = trace all) */
34
- sampleRate?: number;
35
- /** Batch size threshold before flush (default: 100) */
36
- batchSize?: number;
37
- /** Batch timeout in ms before flush (default: 1000) */
38
- batchTimeoutMs?: number;
39
- /** Maximum queue size (default: 10000) */
40
- maxQueueSize?: number;
41
- /** Enable debug logging (default: false) */
42
- debug?: boolean;
43
- /** Enable gzip compression for HTTP exports (default: false) */
44
- compress?: boolean;
45
- /** Custom metadata attached to all spans */
46
- metadata?: Record<string, unknown>;
47
- }
48
-
49
6
  /**
50
7
  * Core type definitions for the Risicare SDK.
51
8
  *
@@ -241,6 +198,144 @@ declare class Span {
241
198
  toPayload(): SpanPayload;
242
199
  }
243
200
 
201
+ /**
202
+ * Customer-supplied masking of span content, applied before anything leaves the process.
203
+ *
204
+ * The full rationale — why this is the ONLY layer rather than defence in depth,
205
+ * why the hook carries the key, what is deliberately not masked, and the
206
+ * fail-closed-per-field ruling — is written once, in the Python twin:
207
+ * `packages/risicare-sdk/src/risicare/masking.py`. This file mirrors it. Where
208
+ * the two languages diverge, the divergence is called out inline below; do not
209
+ * "align" them without reading both.
210
+ *
211
+ * ── Mirrored from Python ─────────────────────────────────────────────────────
212
+ * • signature `mask(key, value) => value` — the key is REQUIRED, because our
213
+ * span model has no input/output fields: the prompt and the model name are
214
+ * both plain entries of `span.attributes`, so a keyless hook cannot tell
215
+ * them apart and `() => '***'` would erase every dashboard label.
216
+ * • masked: every attribute value, `statusMessage`, every event-attribute
217
+ * value, every link-attribute value — plus `score.comment`, the one key
218
+ * that is NOT a span field (see {@link SCORE_COMMENT_KEY}).
219
+ * • NOT masked: traceId / spanId / parentSpanId, `span.name`, `event.name`,
220
+ * and the typed identity + llm columns (agentId, agentName, agentType,
221
+ * sessionId, toolName, llmModel, …). Masking an identifier breaks the
222
+ * customer's own joins — the F-39C lesson. The OTel-style attribute forms
223
+ * (`agent.name`, `session.user_id`) live in `attributes` and ARE masked.
224
+ * • no type narrowing: the hook sees numbers and booleans too. A card number
225
+ * is representable as a number, and deciding otherwise on the customer's
226
+ * behalf is the quiet narrowing this codebase keeps paying for.
227
+ * • fail closed per FIELD: a throwing hook yields `MASK_ERROR_MARKER` for
228
+ * that field and the span is exported intact. Never drop the span — the
229
+ * SDK is the last place the data exists, so a drop here is permanent loss,
230
+ * and it additionally orphans the span's children for zero extra safety.
231
+ * • idempotent: `_exportBatch` can re-queue a refused batch, and a user
232
+ * callback cannot be assumed idempotent, so a masked span is flagged.
233
+ *
234
+ * ── Where JS DIFFERS from Python, and it matters ─────────────────────────────
235
+ * 1. There is no `exceptions[]` on the JS Span — `toPayload()` emits none — so
236
+ * there are no `exceptions.{i}.*` keys here. A port that adds exceptions to
237
+ * the JS span must add them here in the same change.
238
+ * 2. ⚠ THE HOT-PATH COST IS STRICTLY WORSE THAN PYTHON'S. Python runs the mask
239
+ * on a background worker THREAD, so a slow mask costs only drain rate. Node
240
+ * has one thread: `_exportBatch` is `async`, but the mask itself is sync, so
241
+ * while it runs NOTHING else in the customer's process runs — not their
242
+ * request handlers, not their timers. In Python a slow mask degrades
243
+ * throughput; in JS it degrades the whole application. The budget warning
244
+ * below is not advisory decoration here.
245
+ * 3. `_masked` is a real private field on `Span` (we own that class), rather
246
+ * than Python's `setattr` — which Python needs only because its `Span`
247
+ * lives in the separate `risicare-core` package.
248
+ */
249
+
250
+ /**
251
+ * A customer mask callback.
252
+ *
253
+ * @param key Fully-qualified path of the value: an attribute key as-is
254
+ * (`"gen_ai.prompt.0.content"`), or a dotted path
255
+ * (`"statusMessage"`, `"events.0.attributes.foo"`,
256
+ * `"links.0.attributes.bar"`).
257
+ * @param value The current value — any type, not just string.
258
+ * @returns The replacement, or `value` unchanged.
259
+ */
260
+ type MaskFn = (key: string, value: unknown) => unknown;
261
+ /**
262
+ * Substituted for a value whose mask threw. Fixed, deliberately not
263
+ * valid-looking, and greppable in a dashboard.
264
+ */
265
+ declare const MASK_ERROR_MARKER = "<risicare:mask-error>";
266
+
267
+ /**
268
+ * SDK configuration with environment variable loading.
269
+ *
270
+ * Environment variables match the Python SDK exactly:
271
+ * RISICARE_API_KEY, RISICARE_ENDPOINT, RISICARE_PROJECT_ID, etc.
272
+ */
273
+
274
+ interface RisicareConfig {
275
+ /** API key for authentication (format: "rsk-{random}"). Each key is scoped to one project. */
276
+ apiKey?: string;
277
+ /** Gateway endpoint URL */
278
+ endpoint?: string;
279
+ /**
280
+ * @deprecated Project is determined by your API key. This field is ignored
281
+ * by the gateway and will be removed in v1.0. Use `serviceName` and
282
+ * `environment` for within-project organization.
283
+ */
284
+ projectId?: string;
285
+ /** Environment name (production, staging, development). Used for within-project organization. */
286
+ environment?: string;
287
+ /** Service name for within-project organization. */
288
+ serviceName?: string;
289
+ /** Service version */
290
+ serviceVersion?: string;
291
+ /** Whether tracing is enabled (default: true if apiKey provided) */
292
+ enabled?: boolean;
293
+ /**
294
+ * Whether prompt/completion content may leave the process.
295
+ *
296
+ * **Default `false` since 0.5.1** (was `true`). When false, every
297
+ * content-keyed attribute is replaced with `<risicare:content-omitted>` on
298
+ * the export path — including content you set by hand, which 0.5.0 and
299
+ * earlier did NOT gate.
300
+ */
301
+ traceContent?: boolean;
302
+ /** Sample rate 0.0–1.0 (default: 1.0 = trace all) */
303
+ sampleRate?: number;
304
+ /** Batch size threshold before flush (default: 100) */
305
+ batchSize?: number;
306
+ /** Batch timeout in ms before flush (default: 1000) */
307
+ batchTimeoutMs?: number;
308
+ /** Maximum queue size (default: 10000) */
309
+ maxQueueSize?: number;
310
+ /** Enable debug logging (default: false) */
311
+ debug?: boolean;
312
+ /** Enable gzip compression for HTTP exports (default: false) */
313
+ compress?: boolean;
314
+ /** Custom metadata attached to all spans */
315
+ metadata?: Record<string, unknown>;
316
+ /**
317
+ * Masking callback applied to every content-bearing field of every span
318
+ * BEFORE the batch leaves the process — `mask(key, value) => value`.
319
+ *
320
+ * This is the only layer at which you can keep data off Risicare's wire, so
321
+ * it applies to every exporter, including custom ones. `key` is the attribute
322
+ * key (`"gen_ai.prompt.0.content"`) or a dotted path (`"statusMessage"`,
323
+ * `"events.0.attributes.x"`). Identifiers and span/event names are NOT passed
324
+ * to it — masking those breaks trace structure and your own joins.
325
+ *
326
+ * ⚠ Must be CPU-only and fast: Node is single-threaded, so this runs on your
327
+ * event loop. No I/O, no network, no unbounded retries, no per-request state.
328
+ * If it throws, that one field becomes `"<risicare:mask-error>"` and the span
329
+ * is still exported. See `masking.ts`.
330
+ *
331
+ * ⚠ Has NO environment-variable form, deliberately: the shapes that would
332
+ * make a callable env-resolvable are arbitrary code execution driven by the
333
+ * process environment. Masking is configured in code, by the application that
334
+ * owns the data.
335
+ */
336
+ mask?: MaskFn;
337
+ }
338
+
244
339
  /**
245
340
  * Tracer — creates spans with automatic context nesting.
246
341
  *
@@ -275,14 +370,43 @@ interface TracerConfig {
275
370
  sampleRate?: number;
276
371
  /** Whether tracing is enabled */
277
372
  enabled?: boolean;
278
- /** Whether to capture prompt/completion content (default: true) */
373
+ /**
374
+ * Whether prompt/completion content may leave the process (default: false).
375
+ *
376
+ * ⚠ The Tracer only CARRIES this for the provider patches to read via
377
+ * `getTraceContent()`. It is NOT the enforcement point — the gate runs in the
378
+ * batch processor, which is the one place both content paths cross. See
379
+ * `masking.ts` `stripContent`.
380
+ */
279
381
  traceContent?: boolean;
382
+ /**
383
+ * Service name, emitted as the OTel `service.name` span attribute.
384
+ *
385
+ * ⚠ F-SDKJSSVCNAME-001. `serviceName` was accepted by `init()`, typed in
386
+ * `RisicareConfig`, documented, and recommended over the deprecated
387
+ * `projectId` — and reached the wire NOWHERE. Measured on the published
388
+ * 0.5.0: `serviceName: 'X'` at init, `X` absent from every request body,
389
+ * while a sibling control attribute in the same span arrived. Python has
390
+ * always emitted it (`tracer.py`, `service.name`); this makes JS match.
391
+ */
392
+ serviceName?: string;
393
+ /**
394
+ * Service version, emitted as `service.version`.
395
+ *
396
+ * ⚠ Was dropped by BOTH SDKs — same defect one field over, measured in the
397
+ * same run. Unlike `service.name` it is NOT suppressed under an agent: a
398
+ * version is a property of the deployed code, not of which agent owns the
399
+ * span.
400
+ */
401
+ serviceVersion?: string;
280
402
  }
281
403
  declare class Tracer {
282
404
  private _onSpanEnd;
283
405
  private _sampleRate;
284
406
  private _enabled;
285
407
  private _traceContent;
408
+ private _serviceName;
409
+ private _serviceVersion;
286
410
  constructor(config: TracerConfig);
287
411
  get enabled(): boolean;
288
412
  set enabled(value: boolean);
@@ -336,8 +460,16 @@ declare function init(config?: Partial<RisicareConfig>): void;
336
460
  declare function shutdown(): Promise<void>;
337
461
  /**
338
462
  * Flush all pending spans without shutting down.
463
+ *
464
+ * @returns `true` only if everything queued at entry was DELIVERED — `false`
465
+ * if the deadline expired with spans still queued, or if any span was
466
+ * discarded during the window (F-SDKCB-001 §6). An uninitialised SDK returns
467
+ * `true`: it was handed nothing, and it lost nothing.
468
+ *
469
+ * ⚠ Signature change in 0.5.0 — was `Promise<void>`. Existing callers that
470
+ * ignore the result keep working unchanged.
339
471
  */
340
- declare function flush(): Promise<void>;
472
+ declare function flush(): Promise<boolean>;
341
473
  /**
342
474
  * Enable tracing at runtime.
343
475
  */
@@ -360,15 +492,69 @@ declare function getTracer(): Tracer | undefined;
360
492
  declare function getTraceContent(): boolean;
361
493
  /**
362
494
  * Get SDK metrics: exported spans, dropped spans, failed exports, queue stats.
363
- * Returns zero-valued metrics if SDK is not initialized.
495
+ *
496
+ * `sdkState` — SDK-RELEASE-RULING.md §5 — says WHICH of three different facts
497
+ * the numbers are, because before it all three rendered as the same zeros:
498
+ *
499
+ * - `"uninitialised"` nothing was ever queued; the zeros are the truth
500
+ * - `"running"` live readings from a live processor
501
+ * - `"shutdown"` the RETAINED FINAL TALLY. Not live, and says so.
502
+ *
503
+ * The `"shutdown"` case is why this field exists. `shutdown()` clears the global
504
+ * client, so this used to answer `droppedSpans: 0` from a hardcoded literal in
505
+ * the very process that had just discarded spans — a guess presented
506
+ * byte-identical to an authoritative answer, which is the W1/W3 class this
507
+ * codebase already ruled against (`cost_source`, `settled`). The remedy there
508
+ * and here is the same: do not hide the value and do not null it, LABEL it.
509
+ * Every field of a retained tally is still true — the queue really is empty,
510
+ * the capacity really is the configured one, and the drop counts describe the
511
+ * whole life of the process, `shutdown_residue` included.
512
+ *
513
+ * ⚠ What it still CANNOT do: report loss to anything OUTSIDE the dying process.
514
+ * A counter in memory about to be freed has no reader, and a SIGKILL takes this
515
+ * and the WARNING together. The WARNING remains the primary signal.
364
516
  */
365
517
  declare function getMetrics(): {
518
+ sdkState: "running";
519
+ exportedSpans: number;
520
+ droppedSpans: number;
521
+ droppedSpansByReason: {
522
+ queue_full: number;
523
+ transport_refused: number;
524
+ shutdown_residue: number;
525
+ };
526
+ failedExports: number;
527
+ maskErrors: number;
528
+ queueSize: number;
529
+ queueCapacity: number;
530
+ queueUtilization: number;
531
+ } | {
532
+ droppedSpansByReason: {
533
+ queue_full: number;
534
+ transport_refused: number;
535
+ shutdown_residue: number;
536
+ };
537
+ sdkState: "shutdown";
366
538
  exportedSpans: number;
367
539
  droppedSpans: number;
368
540
  failedExports: number;
541
+ maskErrors: number;
369
542
  queueSize: number;
370
543
  queueCapacity: number;
371
544
  queueUtilization: number;
545
+ } | {
546
+ exportedSpans: number;
547
+ droppedSpans: number;
548
+ droppedSpansByReason: {
549
+ queue_full: number;
550
+ transport_refused: number;
551
+ shutdown_residue: number;
552
+ };
553
+ failedExports: number;
554
+ queueSize: number;
555
+ queueCapacity: number;
556
+ queueUtilization: number;
557
+ sdkState: "uninitialised";
372
558
  };
373
559
  /**
374
560
  * Report a caught exception to the error diagnosis pipeline.
@@ -390,6 +576,10 @@ declare function reportError(error: unknown, options?: {
390
576
  * Sends the score to the server in a fire-and-forget fashion.
391
577
  * This function never throws and is non-blocking.
392
578
  *
579
+ * If a `mask` is configured on `init()`, `options.comment` is passed to it under
580
+ * the key `score.comment` before the request is built. `traceId`, `spanId` and
581
+ * `name` are NOT masked — they are identifiers the platform joins and groups on.
582
+ *
393
583
  * @param traceId - The trace to score
394
584
  * @param name - Score name (e.g., "accuracy", "user_satisfaction")
395
585
  * @param value - Score value between 0.0 and 1.0 inclusive
@@ -1353,4 +1543,4 @@ type WebhookPayload = Uint8Array | ArrayBuffer | string;
1353
1543
  */
1354
1544
  declare function verifyWebhookSignature(payload: WebhookPayload, headers: HeaderLookup, secret: string, opts?: VerifyWebhookOptions): void;
1355
1545
 
1356
- export { type ActiveFix, type AgentContext, type AgentOptions, AgentRole, DEFAULT_TIMESTAMP_TOLERANCE_S, type FixRuntimeConfig, GuardRejectedError, type HeaderLookup, MessageType, type RisicareConfig, SemanticPhase, type SessionContext, type SessionOptions, Span, SpanKind, type SpanOptions, SpanStatus, type StartSpanOptions, type TraceContext, type TracedStreamOptions, Tracer, type VerifyWebhookOptions, type WebhookPayload, WebhookVerificationError, agent, disable, enable, extractTraceContext, flush, getCurrentAgent, getCurrentAgentId, getCurrentContext, getCurrentPhase, getCurrentSession, getCurrentSessionId, getCurrentSpan, getCurrentSpanId, getCurrentTraceId, getFixRuntime, getMetrics, getSpanById, getTraceContent, getTraceContext, getTracer, init, initFixRuntime, injectTraceContext, isEnabled, isProviderInstrumentationSuppressed, registerSpan, reportError, score, session, shutdown, shutdownFixRuntime, suppressProviderInstrumentation, traceAct, traceCoordinate, traceDecide, traceDelegate, traceMessage, traceObserve, traceThink, tracedStream, unregisterSpan, verifyWebhookSignature, withAgent, withPhase, withSession };
1546
+ export { type ActiveFix, type AgentContext, type AgentOptions, AgentRole, DEFAULT_TIMESTAMP_TOLERANCE_S, type FixRuntimeConfig, GuardRejectedError, type HeaderLookup, MASK_ERROR_MARKER, type MaskFn, MessageType, type RisicareConfig, SemanticPhase, type SessionContext, type SessionOptions, Span, SpanKind, type SpanOptions, SpanStatus, type StartSpanOptions, type TraceContext, type TracedStreamOptions, Tracer, type VerifyWebhookOptions, type WebhookPayload, WebhookVerificationError, agent, disable, enable, extractTraceContext, flush, getCurrentAgent, getCurrentAgentId, getCurrentContext, getCurrentPhase, getCurrentSession, getCurrentSessionId, getCurrentSpan, getCurrentSpanId, getCurrentTraceId, getFixRuntime, getMetrics, getSpanById, getTraceContent, getTraceContext, getTracer, init, initFixRuntime, injectTraceContext, isEnabled, isProviderInstrumentationSuppressed, registerSpan, reportError, score, session, shutdown, shutdownFixRuntime, suppressProviderInstrumentation, traceAct, traceCoordinate, traceDecide, traceDelegate, traceMessage, traceObserve, traceThink, tracedStream, unregisterSpan, verifyWebhookSignature, withAgent, withPhase, withSession };