risicare 0.7.0 → 0.9.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 (84) hide show
  1. package/README.md +346 -68
  2. package/dist/frameworks/instructor.cjs +790 -5
  3. package/dist/frameworks/instructor.cjs.map +1 -1
  4. package/dist/frameworks/instructor.js +780 -5
  5. package/dist/frameworks/instructor.js.map +1 -1
  6. package/dist/frameworks/langchain.cjs +790 -5
  7. package/dist/frameworks/langchain.cjs.map +1 -1
  8. package/dist/frameworks/langchain.d.cts +3 -2
  9. package/dist/frameworks/langchain.d.ts +3 -2
  10. package/dist/frameworks/langchain.js +780 -5
  11. package/dist/frameworks/langchain.js.map +1 -1
  12. package/dist/frameworks/langgraph.cjs +790 -5
  13. package/dist/frameworks/langgraph.cjs.map +1 -1
  14. package/dist/frameworks/langgraph.js +780 -5
  15. package/dist/frameworks/langgraph.js.map +1 -1
  16. package/dist/frameworks/llamaindex.cjs +801 -5
  17. package/dist/frameworks/llamaindex.cjs.map +1 -1
  18. package/dist/frameworks/llamaindex.d.cts +3 -2
  19. package/dist/frameworks/llamaindex.d.ts +3 -2
  20. package/dist/frameworks/llamaindex.js +791 -5
  21. package/dist/frameworks/llamaindex.js.map +1 -1
  22. package/dist/index.cjs +1219 -212
  23. package/dist/index.cjs.map +1 -1
  24. package/dist/index.d.cts +250 -44
  25. package/dist/index.d.ts +250 -44
  26. package/dist/index.js +1219 -212
  27. package/dist/index.js.map +1 -1
  28. package/dist/providers/anthropic/index.cjs +1601 -36
  29. package/dist/providers/anthropic/index.cjs.map +1 -1
  30. package/dist/providers/anthropic/index.d.cts +3 -1
  31. package/dist/providers/anthropic/index.d.ts +3 -1
  32. package/dist/providers/anthropic/index.js +1591 -36
  33. package/dist/providers/anthropic/index.js.map +1 -1
  34. package/dist/providers/bedrock/index.cjs +850 -32
  35. package/dist/providers/bedrock/index.cjs.map +1 -1
  36. package/dist/providers/bedrock/index.js +840 -32
  37. package/dist/providers/bedrock/index.js.map +1 -1
  38. package/dist/providers/cerebras/index.cjs +1534 -30
  39. package/dist/providers/cerebras/index.cjs.map +1 -1
  40. package/dist/providers/cerebras/index.js +1524 -30
  41. package/dist/providers/cerebras/index.js.map +1 -1
  42. package/dist/providers/cohere/index.cjs +1557 -102
  43. package/dist/providers/cohere/index.cjs.map +1 -1
  44. package/dist/providers/cohere/index.js +1547 -102
  45. package/dist/providers/cohere/index.js.map +1 -1
  46. package/dist/providers/google/index.cjs +1562 -60
  47. package/dist/providers/google/index.cjs.map +1 -1
  48. package/dist/providers/google/index.js +1552 -60
  49. package/dist/providers/google/index.js.map +1 -1
  50. package/dist/providers/groq/index.cjs +1534 -30
  51. package/dist/providers/groq/index.cjs.map +1 -1
  52. package/dist/providers/groq/index.js +1524 -30
  53. package/dist/providers/groq/index.js.map +1 -1
  54. package/dist/providers/huggingface/index.cjs +1622 -25
  55. package/dist/providers/huggingface/index.cjs.map +1 -1
  56. package/dist/providers/huggingface/index.d.cts +0 -9
  57. package/dist/providers/huggingface/index.d.ts +0 -9
  58. package/dist/providers/huggingface/index.js +1612 -25
  59. package/dist/providers/huggingface/index.js.map +1 -1
  60. package/dist/providers/mistral/index.cjs +1535 -54
  61. package/dist/providers/mistral/index.cjs.map +1 -1
  62. package/dist/providers/mistral/index.js +1525 -54
  63. package/dist/providers/mistral/index.js.map +1 -1
  64. package/dist/providers/ollama/index.cjs +1559 -93
  65. package/dist/providers/ollama/index.cjs.map +1 -1
  66. package/dist/providers/ollama/index.js +1549 -93
  67. package/dist/providers/ollama/index.js.map +1 -1
  68. package/dist/providers/openai/index.cjs +1598 -61
  69. package/dist/providers/openai/index.cjs.map +1 -1
  70. package/dist/providers/openai/index.d.cts +6 -1
  71. package/dist/providers/openai/index.d.ts +6 -1
  72. package/dist/providers/openai/index.js +1588 -61
  73. package/dist/providers/openai/index.js.map +1 -1
  74. package/dist/providers/together/index.cjs +1534 -30
  75. package/dist/providers/together/index.cjs.map +1 -1
  76. package/dist/providers/together/index.js +1524 -30
  77. package/dist/providers/together/index.js.map +1 -1
  78. package/dist/providers/vercel-ai/index.cjs +1288 -17
  79. package/dist/providers/vercel-ai/index.cjs.map +1 -1
  80. package/dist/providers/vercel-ai/index.d.cts +0 -6
  81. package/dist/providers/vercel-ai/index.d.ts +0 -6
  82. package/dist/providers/vercel-ai/index.js +1278 -17
  83. package/dist/providers/vercel-ai/index.js.map +1 -1
  84. package/package.json +1 -1
package/dist/index.d.cts CHANGED
@@ -139,8 +139,8 @@ interface SpanOptions {
139
139
  agentType?: string;
140
140
  semanticPhase?: string;
141
141
  }
142
- type SpanEndCallback = (span: Span) => void;
143
- declare class Span {
142
+ type SpanEndCallback = (span: Span$1) => void;
143
+ declare class Span$1 {
144
144
  readonly traceId: string;
145
145
  readonly spanId: string;
146
146
  readonly parentSpanId: string | undefined;
@@ -277,9 +277,16 @@ interface RisicareConfig {
277
277
  /** Ingest gateway URL. It receives spans only. */
278
278
  endpoint?: string;
279
279
  /**
280
- * Api URL. It serves active-fix reads and scores.
281
- * Falls back to `endpoint` when only that one is given, so a single-host
282
- * deployment keeps every URL shape on the one host.
280
+ * Api URL. It serves active-fix reads and scores. The order is:
281
+ * 1. this option;
282
+ * 2. the `endpoint` option, when it is given and it is not the default ingest host;
283
+ * 3. `RISICARE_API_ENDPOINT`;
284
+ * 4. `RISICARE_ENDPOINT`, when no `endpoint` option is given and it is not the
285
+ * default ingest host;
286
+ * 5. the default api host.
287
+ * The default ingest host (`https://ingest.risicare.ai`) never names an api
288
+ * host. `RISICARE_ENDPOINT` alone keeps every URL shape on that one host. Each
289
+ * value is trimmed of ASCII whitespace, and an empty value is not given.
283
290
  */
284
291
  apiEndpoint?: string;
285
292
  /**
@@ -294,7 +301,11 @@ interface RisicareConfig {
294
301
  serviceName?: string;
295
302
  /** Service version */
296
303
  serviceVersion?: string;
297
- /** Whether tracing is enabled (default: true if apiKey provided) */
304
+ /**
305
+ * Whether tracing is enabled (default: true if apiKey provided).
306
+ * With no API key tracing is always off, also with `enabled: true`,
307
+ * `RISICARE_TRACING=true` or `enable()`: the SDK sends nothing without a key.
308
+ */
298
309
  enabled?: boolean;
299
310
  /**
300
311
  * Whether prompt/completion content may leave the process.
@@ -307,7 +318,7 @@ interface RisicareConfig {
307
318
  traceContent?: boolean;
308
319
  /** Sample rate 0.0–1.0 (default: 1.0 = trace all) */
309
320
  sampleRate?: number;
310
- /** Batch size threshold before flush (default: 100) */
321
+ /** Batch size threshold before flush (default: 500) */
311
322
  batchSize?: number;
312
323
  /** Batch timeout in ms before flush (default: 1000) */
313
324
  batchTimeoutMs?: number;
@@ -321,8 +332,12 @@ interface RisicareConfig {
321
332
  * Whether FixRuntime starts (or `RISICARE_FIX_RUNTIME=true`).
322
333
  *
323
334
  * **Default `false` since 0.7.0** (it started whenever an `apiKey` was set).
324
- * When true, the SDK polls `/fixes/active` every 60 s and applies the active
325
- * fixes to LLM calls. When false, nothing polls and nothing is applied.
335
+ * During the beta, the Risicare service does not give fixes to customer
336
+ * projects, so FixRuntime has no effect for them. When true, the SDK polls
337
+ * `/fixes/active` every 60 s. The interceptor then enforces guard fixes on
338
+ * the paths that call it, and a failed guard throws `GuardRejectedError`.
339
+ * The provider path does not apply prompt, parameter or fallback fixes.
340
+ * When false, nothing polls and nothing is applied.
326
341
  */
327
342
  fixRuntime?: boolean;
328
343
  /** Custom metadata attached to all spans */
@@ -414,7 +429,7 @@ interface TracerConfig {
414
429
  */
415
430
  serviceVersion?: string;
416
431
  }
417
- declare class Tracer {
432
+ declare class Tracer$1 {
418
433
  private _onSpanEnd;
419
434
  private _sampleRate;
420
435
  private _enabled;
@@ -437,14 +452,14 @@ declare class Tracer {
437
452
  *
438
453
  * @returns The callback's return value
439
454
  */
440
- startSpan<T>(options: StartSpanOptions | string, fn: (span: Span) => T): T;
455
+ startSpan<T>(options: StartSpanOptions | string, fn: (span: Span$1) => T): T;
441
456
  /**
442
457
  * Create a span without auto-ending. Caller is responsible for calling span.end().
443
458
  *
444
459
  * Useful for long-running operations where you need manual control.
445
460
  * The span is still linked to context and enriched with session/agent/phase.
446
461
  */
447
- createSpan(options: StartSpanOptions | string): Span;
462
+ createSpan(options: StartSpanOptions | string): Span$1;
448
463
  }
449
464
 
450
465
  /**
@@ -470,20 +485,63 @@ declare class Tracer {
470
485
  declare function init(config?: Partial<RisicareConfig>): void;
471
486
  /**
472
487
  * Gracefully shut down the SDK. Flushes pending spans before resolving.
488
+ *
489
+ * @param timeoutMs - The shutdown budget in milliseconds (default 5000). It is a
490
+ * hard wall-clock bound. A value that is not a finite number (NaN, Infinity, a
491
+ * string, null) gives 5000. A negative value gives 0. The largest value is
492
+ * 2**31 - 1.
493
+ *
494
+ * At the deadline, `shutdown()` stops the export in flight. Spans still queued
495
+ * and spans in the stopped export are counted as `shutdown_residue`, with one
496
+ * WARNING: they were not confirmed as delivered. The server may have received
497
+ * the spans of the stopped export. Each exporter's own `shutdown()` gets only
498
+ * the time that is left of the budget.
499
+ *
500
+ * Limit: the stop does not end a TLS handshake that stalls. Such a handshake
501
+ * can keep the process alive about 10 s after `shutdown()` returns.
473
502
  */
474
- declare function shutdown(): Promise<void>;
503
+ declare function shutdown(timeoutMs?: number): Promise<void>;
475
504
  /**
476
505
  * Flush all pending spans without shutting down.
477
506
  *
478
- * @returns `true` only if everything queued at entry was DELIVERED — `false`
479
- * if the deadline expired with spans still queued, or if any span was
480
- * discarded during the window (F-SDKCB-001 §6). An uninitialised SDK returns
481
- * `true`: it was handed nothing, and it lost nothing.
507
+ * @param timeoutMs - The budget in milliseconds (default 5000). It is a hard
508
+ * wall-clock bound on the wait: at the deadline `flush()` resolves `false`.
509
+ * A value that is not a finite number (NaN, Infinity, a string, null) gives
510
+ * 5000. A negative value gives 0. The largest value is 2**31 - 1.
511
+ * @returns `true` only if everything queued at entry was DELIVERED and no span
512
+ * was lost since the previous `flush()` returned. A loss is reported by the next
513
+ * `flush()`, one time. It returns `false` in these cases:
514
+ * - the deadline expired with spans still queued or in flight;
515
+ * - a span was discarded since the previous flush returned (F-SDKCB-001 §6);
516
+ * - the backend rejected a span since the previous flush returned, or its ack
517
+ * did not account for a span;
518
+ * - a `shutdown()` left spans undelivered (`shutdown_residue`) since the previous
519
+ * flush returned. That loss is reported once, as every other loss.
520
+ * A `flush()` that comes while a `shutdown()` runs (the SDK's own drain at
521
+ * SIGTERM / SIGINT, or one that nobody awaited) waits for it inside its own
522
+ * deadline, and then answers from the final tally with the same rule. So does a
523
+ * `flush()` after `shutdown()`. Through 0.8.0 both answered from the empty queue.
524
+ * Not active means not true: `flush()` returns `false` before `init()`, with tracing
525
+ * off (`enabled: false`, `RISICARE_TRACING=false`), and with no API key. Through
526
+ * 0.8.0 it returned `true` in those cases: nothing was queued.
527
+ *
528
+ * `flush()` never stops a request that is already sent. At the deadline it stops
529
+ * waiting; the export in flight continues and ends by its own rules.
530
+ *
531
+ * Limit: that export can keep the process alive after `flush()` returns `false`,
532
+ * until its own timeouts end (measured on a silent server: 22 s). To end a
533
+ * process within a bound, call `await shutdown(timeoutMs)`. It stops the export
534
+ * in flight.
535
+ *
536
+ * Scores: `flush()` also waits, inside the same deadline, for each `score()`
537
+ * request that is not complete. It returns `false` when a score is not complete
538
+ * at the deadline, or when a score failed since the previous `flush()` returned.
539
+ * Each failed score makes one flush `false`, as each lost span does.
482
540
  *
483
541
  * ⚠ Signature change in 0.5.0 — was `Promise<void>`. Existing callers that
484
542
  * ignore the result keep working unchanged.
485
543
  */
486
- declare function flush(): Promise<boolean>;
544
+ declare function flush(timeoutMs?: number): Promise<boolean>;
487
545
  /**
488
546
  * Enable tracing at runtime.
489
547
  */
@@ -493,19 +551,24 @@ declare function enable(): void;
493
551
  */
494
552
  declare function disable(): void;
495
553
  /**
496
- * Check whether tracing is currently enabled.
554
+ * Check whether tracing is currently enabled. False before `init()`, with no API
555
+ * key (also with `RISICARE_TRACING=true`, `enabled: true` or `enable()`), with
556
+ * tracing off, and after `shutdown()` or the SDK's own drain at SIGTERM / SIGINT.
497
557
  */
498
558
  declare function isEnabled(): boolean;
499
559
  /**
500
560
  * Get the global tracer instance. Returns undefined if not initialized.
501
561
  */
502
- declare function getTracer(): Tracer | undefined;
562
+ declare function getTracer(): Tracer$1 | undefined;
503
563
  /**
504
564
  * Check whether content tracing (prompt/completion capture) is enabled.
505
565
  */
506
566
  declare function getTraceContent(): boolean;
507
567
  /**
508
- * Get SDK metrics: exported spans, dropped spans, failed exports, queue stats.
568
+ * Get SDK metrics: exported spans (accepted by the backend), `rejectedSpans`,
569
+ * dropped spans and their reasons (`unacknowledged` included), failed exports,
570
+ * queue stats, and `failedScores` (`score()` requests that failed since
571
+ * `init()`).
509
572
  *
510
573
  * `sdkState` — SDK-RELEASE-RULING.md §5 — says WHICH of three different facts
511
574
  * the numbers are, because before it all three rendered as the same zeros:
@@ -529,13 +592,16 @@ declare function getTraceContent(): boolean;
529
592
  * and the WARNING together. The WARNING remains the primary signal.
530
593
  */
531
594
  declare function getMetrics(): {
595
+ failedScores: number;
532
596
  sdkState: "running";
533
597
  exportedSpans: number;
598
+ rejectedSpans: number;
534
599
  droppedSpans: number;
535
600
  droppedSpansByReason: {
536
601
  queue_full: number;
537
602
  transport_refused: number;
538
603
  shutdown_residue: number;
604
+ unacknowledged: number;
539
605
  };
540
606
  failedExports: number;
541
607
  maskErrors: number;
@@ -543,13 +609,16 @@ declare function getMetrics(): {
543
609
  queueCapacity: number;
544
610
  queueUtilization: number;
545
611
  } | {
612
+ failedScores: number;
546
613
  droppedSpansByReason: {
547
614
  queue_full: number;
548
615
  transport_refused: number;
549
616
  shutdown_residue: number;
617
+ unacknowledged: number;
550
618
  };
551
619
  sdkState: "shutdown";
552
620
  exportedSpans: number;
621
+ rejectedSpans: number;
553
622
  droppedSpans: number;
554
623
  failedExports: number;
555
624
  maskErrors: number;
@@ -558,11 +627,14 @@ declare function getMetrics(): {
558
627
  queueUtilization: number;
559
628
  } | {
560
629
  exportedSpans: number;
630
+ rejectedSpans: number;
631
+ failedScores: number;
561
632
  droppedSpans: number;
562
633
  droppedSpansByReason: {
563
634
  queue_full: number;
564
635
  transport_refused: number;
565
636
  shutdown_residue: number;
637
+ unacknowledged: number;
566
638
  };
567
639
  failedExports: number;
568
640
  queueSize: number;
@@ -587,8 +659,24 @@ declare function reportError(error: unknown, options?: {
587
659
  /**
588
660
  * Record a custom evaluation score on a trace.
589
661
  *
590
- * Sends the score to the server in a fire-and-forget fashion.
591
- * This function never throws and is non-blocking.
662
+ * Sends the score in the background. The root `flush()` waits for it.
663
+ * This function never throws and does not block. At most 50 score requests
664
+ * are in flight at once. Up to 1,000 scores wait for a free slot, with no timer;
665
+ * the 2000 ms bound of a score starts when its request starts. A score that
666
+ * comes when 1,000 already wait fails at once and is counted. When a `flush()`
667
+ * or `shutdown()` bound ends, the scores that still wait fail and are not sent.
668
+ *
669
+ * Delivery: the request stops after 2000 ms and never follows a redirect. A
670
+ * status of 300 or more, an error or the timeout is a failure, and it adds 1
671
+ * to `failedScores` in `getMetrics()`. The first failure writes a WARNING with
672
+ * the score name and the status or the error code. Later failures in the next
673
+ * 10 s are counted, and the next WARNING gives their number. Root `flush()`
674
+ * waits for pending scores inside its deadline, and returns `false` when a
675
+ * score failed since the previous `flush()` returned. An out-of-range value, a
676
+ * value that is not a number, or an empty `traceId` or `name` writes one WARNING,
677
+ * and the SDK does not send the score. It counts as a failed score, so the next
678
+ * `flush()` is false (not when the SDK is not active: then nothing is counted).
679
+ * `true` and `false` count as 1 and 0.
592
680
  *
593
681
  * If a `mask` is configured on `init()`, `options.comment` is passed to it under
594
682
  * the key `score.comment` before the request is built. `traceId`, `spanId` and
@@ -693,6 +781,14 @@ declare function withSession<T>(options: SessionOptions, fn: () => T): T;
693
781
  * );
694
782
  */
695
783
 
784
+ /**
785
+ * Blocks inference from the resolver, so that the target function alone
786
+ * decides `TArgs` (F-020). The resolver may declare fewer parameters than the
787
+ * target, as the documented `(sessionId, userId) => ...` resolver does.
788
+ * Written without the built-in `NoInfer` (TypeScript 5.4+) because the
789
+ * package supports TypeScript 5.0.
790
+ */
791
+ type NoInferArgs<T> = [T][T extends unknown ? 0 : never];
696
792
  /**
697
793
  * Wrap a function with session context.
698
794
  *
@@ -707,14 +803,18 @@ declare function withSession<T>(options: SessionOptions, fn: () => T): T;
707
803
  * @param optionsOrResolver - Static session options, or a function that derives them from args
708
804
  * @param fn - The function to wrap. If omitted, returns a decorator factory.
709
805
  */
710
- declare function session<TArgs extends unknown[], TReturn>(optionsOrResolver: SessionOptions | ((...args: TArgs) => SessionOptions), fn: (...args: TArgs) => TReturn): (...args: TArgs) => TReturn;
806
+ declare function session<TArgs extends unknown[], TReturn>(optionsOrResolver: SessionOptions | ((...args: NoInferArgs<TArgs>) => SessionOptions), fn: (...args: TArgs) => TReturn): (...args: TArgs) => TReturn;
807
+ declare function session(options: SessionOptions): <TArgs extends unknown[], TR>(fn: (...args: TArgs) => TR) => (...args: TArgs) => TR;
808
+ declare function session<TArgs extends unknown[]>(resolver: (...args: TArgs) => SessionOptions): <TR>(fn: (...args: TArgs) => TR) => (...args: TArgs) => TR;
711
809
  declare function session<TArgs extends unknown[]>(optionsOrResolver: SessionOptions | ((...args: TArgs) => SessionOptions)): <TR>(fn: (...args: TArgs) => TR) => (...args: TArgs) => TR;
712
810
 
713
811
  /**
714
812
  * Phase decorators — decision phase tracking (Tier 4).
715
813
  *
716
814
  * Wraps functions to execute within a semantic phase context (THINK/DECIDE/ACT/OBSERVE).
717
- * Each creates a span named after the phase.
815
+ * Each creates a span. The named form uses the given name. The bare form uses
816
+ * `<phase>:<function name>` (for example `think:analyzeQuery`), as the Python
817
+ * SDK does; an anonymous function gives `phase:<phase>` (for example `phase:think`).
718
818
  *
719
819
  * @example
720
820
  * const analyze = traceThink(async (data: string) => {
@@ -832,16 +932,48 @@ interface AgentContext {
832
932
  }
833
933
  declare function getCurrentSession(): SessionContext | undefined;
834
934
  declare function getCurrentAgent(): AgentContext | undefined;
835
- declare function getCurrentSpan(): Span | undefined;
935
+ declare function getCurrentSpan(): Span$1 | undefined;
836
936
  declare function getCurrentPhase(): SemanticPhase | undefined;
837
937
  declare function getCurrentSessionId(): string | undefined;
838
938
  declare function getCurrentAgentId(): string | undefined;
839
939
  declare function getCurrentTraceId(): string | undefined;
840
940
  declare function getCurrentSpanId(): string | undefined;
941
+ /**
942
+ * A plain-object snapshot of the current context, as `getCurrentContext()`
943
+ * returns it. `session`, `agent` and `span` are `null` when not set.
944
+ *
945
+ * This is a type alias, not an interface, so that a value of this type is
946
+ * still assignable to `Record<string, unknown>` (the return type through 0.7.1).
947
+ * `getCurrentContext()` returns it joined with `Record<string, unknown>`, so
948
+ * code that writes or reads other keys still compiles.
949
+ */
950
+ type ContextSnapshot = {
951
+ session: {
952
+ sessionId: string;
953
+ userId?: string;
954
+ parentSessionId?: string;
955
+ turnNumber?: number;
956
+ metadata?: Record<string, unknown>;
957
+ } | null;
958
+ agent: {
959
+ agentId: string;
960
+ agentName?: string;
961
+ agentRole?: string;
962
+ agentType?: string;
963
+ parentAgentId?: string;
964
+ version?: number;
965
+ metadata?: Record<string, unknown>;
966
+ } | null;
967
+ span: {
968
+ spanId: string;
969
+ traceId: string;
970
+ } | null;
971
+ phase: SemanticPhase | null;
972
+ };
841
973
  /**
842
974
  * Get all current context as a plain object (for debugging/serialization).
843
975
  */
844
- declare function getCurrentContext(): Record<string, unknown>;
976
+ declare function getCurrentContext(): ContextSnapshot & Record<string, unknown>;
845
977
 
846
978
  /**
847
979
  * Serializable trace context + W3C Trace Context headers.
@@ -863,9 +995,15 @@ interface TraceContext {
863
995
  * Get the current trace context as a serializable object.
864
996
  *
865
997
  * When called inside a span context, returns the active span's IDs.
866
- * When called outside a span (e.g. inside session() but before agent()),
867
- * pre-allocates a trace ID and stores it in context so the next
868
- * startSpan() call inherits it — preventing trace ID mismatch.
998
+ * When called outside a span but inside a context scope (for example inside
999
+ * `withSession()`, `withAgent()` or `withPhase()`), pre-allocates a trace ID
1000
+ * and stores it in that scope. The ID stays in the scope. EVERY later root
1001
+ * span in that scope uses it: the next span, each span after it, and spans
1002
+ * that start at the same time (for example in `Promise.all`). So all root
1003
+ * spans of the scope are in one trace. Later calls return the same ID.
1004
+ *
1005
+ * Outside every context scope there is no place to store the ID: each call
1006
+ * returns a new trace ID, and the next span does not use it.
869
1007
  */
870
1008
  declare function getTraceContext(): TraceContext;
871
1009
  /**
@@ -874,8 +1012,12 @@ declare function getTraceContext(): TraceContext;
874
1012
  declare function injectTraceContext(headers: Record<string, string>): Record<string, string>;
875
1013
  /**
876
1014
  * Extract trace context from HTTP headers (W3C format).
1015
+ *
1016
+ * Accepts a plain string record or Node's `IncomingHttpHeaders`
1017
+ * (`req.headers`). For a header with several values (`string[]`) the first
1018
+ * value is used. An `undefined` value is ignored.
877
1019
  */
878
- declare function extractTraceContext(headers: Record<string, string>): Record<string, string | undefined>;
1020
+ declare function extractTraceContext(headers: Record<string, string | string[] | undefined>): Record<string, string | undefined>;
879
1021
 
880
1022
  /**
881
1023
  * Span registry — TTL-based span store for edge cases.
@@ -887,8 +1029,8 @@ declare function extractTraceContext(headers: Record<string, string>): Record<st
887
1029
  * - Long-running operations that outlive their original context
888
1030
  */
889
1031
 
890
- declare function registerSpan(span: Span, ttlMs?: number): void;
891
- declare function getSpanById(spanId: string): Span | undefined;
1032
+ declare function registerSpan(span: Span$1, ttlMs?: number): void;
1033
+ declare function getSpanById(spanId: string): Span$1 | undefined;
892
1034
  declare function unregisterSpan(spanId: string): void;
893
1035
 
894
1036
  /**
@@ -897,8 +1039,9 @@ declare function unregisterSpan(spanId: string): void;
897
1039
  * Creates a span that starts when iteration begins and ends when
898
1040
  * iteration completes (or errors). Chunks pass through UNCHANGED.
899
1041
  *
900
- * This is the user-level streaming utility. For provider-level streaming
901
- * enrichment (token counts, cost), see individual provider instrumentors.
1042
+ * This is the user-level streaming utility. The OpenAI, Anthropic, Groq,
1043
+ * Cerebras and Together patches do not read a stream; the Google, Cohere,
1044
+ * Mistral and Ollama patches do (see each provider's patch).
902
1045
  *
903
1046
  * Usage:
904
1047
  * const stream = await openai.chat.completions.create({ stream: true, ... });
@@ -1144,6 +1287,26 @@ declare class FixApplier {
1144
1287
  * - content_filter: Regex-based blocked patterns
1145
1288
  * - format_check: JSON.parse() validity
1146
1289
  * - input_validation / output_validation: min/max length
1290
+ *
1291
+ * `content_filter` searches the content for each entry of `blocked_patterns`
1292
+ * (case-insensitive, after `translatePythonPattern`). It fails CLOSED: when
1293
+ * `blocked_patterns` is not a list, or an entry is empty, is not a string,
1294
+ * is longer than 500 characters or cannot be used, the guard does not pass.
1295
+ * One WARNING names the fix id and the pattern index, once for each pair in
1296
+ * the process. The reason names the pattern index, never the pattern or the
1297
+ * content.
1298
+ *
1299
+ * Limits:
1300
+ * - The interceptor runs only on the OpenAI chat patch (input guards) and on
1301
+ * `interceptCall` / `interceptResponse`. It does not run when a framework
1302
+ * integration suppresses provider instrumentation.
1303
+ * - Each SDK uses its own regular-expression engine. These constructs can
1304
+ * give a different result in JavaScript and Python: `$` before a final
1305
+ * newline, Unicode case folding, `\d` and `\w` on non-ASCII text,
1306
+ * `\N{...}` and `\U........` (JavaScript fails closed), and a `]` first
1307
+ * in a class.
1308
+ * - A pattern has no time bound. A pattern with nested repeats can take a
1309
+ * very long time on a long input.
1147
1310
  */
1148
1311
  applyGuardFix(fix: ActiveFix, content: string, isInput?: boolean): {
1149
1312
  content: string;
@@ -1157,6 +1320,11 @@ declare class FixApplier {
1157
1320
  /**
1158
1321
  * Safely compile a regex pattern from untrusted input.
1159
1322
  * Returns null if invalid or too long.
1323
+ *
1324
+ * F-029: the fix patterns are written for Python `re`. Before it compiles
1325
+ * the pattern, this function translates the Python forms that have an exact
1326
+ * JavaScript equivalent (see `translatePythonPattern`). The `i` flag is
1327
+ * always on, as in the Python applier.
1160
1328
  */
1161
1329
  private _safeCompileRegex;
1162
1330
  /** Prepend content to the first message matching the target role. */
@@ -1191,9 +1359,18 @@ declare class FixLoader {
1191
1359
  private _consecutiveFailures;
1192
1360
  private _circuitOpenUntil;
1193
1361
  private _onLoadCallbacks;
1362
+ private _lastStatus;
1194
1363
  private static readonly CIRCUIT_BREAKER_THRESHOLD;
1195
1364
  private static readonly CIRCUIT_BREAKER_COOLDOWN_MS;
1196
1365
  constructor(config: FixRuntimeConfig, cache: FixCache);
1366
+ /** Error text for a log line: one line, the api endpoint as `safeUrl` gives it, no key. */
1367
+ private _scrub;
1368
+ /**
1369
+ * The WARNING for a failed first load: the request URL with no userinfo, no
1370
+ * query and no key, the HTTP status or the error class, and that tracing is
1371
+ * not affected. Never the error text: it can echo the URL with its query.
1372
+ */
1373
+ private _firstLoadWarning;
1197
1374
  /** Timestamp of last successful load. */
1198
1375
  get lastLoadTime(): number | null;
1199
1376
  /**
@@ -1226,9 +1403,16 @@ declare class FixLoader {
1226
1403
  /**
1227
1404
  * Fix Interceptors — Hook into LLM/tool calls to apply fixes.
1228
1405
  *
1229
- * Interceptors are registered with the runtime and called during agent
1230
- * execution to apply relevant fixes at three interception points:
1231
- * - preCall: Before the LLM/tool call (prompt/parameter/fallback fixes)
1406
+ * FixRuntime is off by default. During the beta, the Risicare service does not
1407
+ * give fixes to customer projects, so FixRuntime has no effect for them.
1408
+ *
1409
+ * The interceptor enforces guard fixes only on the paths that call it:
1410
+ * `interceptCall` and `interceptResponse` on `FixRuntime`, and the OpenAI chat
1411
+ * patch (input guards only). Three interception points:
1412
+ * - preCall: Before the LLM/tool call. Input guards always; prompt,
1413
+ * parameter and fallback fixes only when the context has an
1414
+ * `errorCode`. The provider path supplies none, so it does not
1415
+ * apply them.
1232
1416
  * - postCall: After the call (output guard validation)
1233
1417
  * - onError: When an error occurs (retry/fallback decisions)
1234
1418
  *
@@ -1244,10 +1428,10 @@ declare class FixLoader {
1244
1428
  * LLM with the attacker payload anyway. The `fail-CLOSED` was advisory only.
1245
1429
  *
1246
1430
  * Now the interceptor THROWS this error on both pre-call and post-call
1247
- * guard rejection. The provider patcher's surrounding span.startSpan
1248
- * already catches and records exceptions, so the customer sees a
1431
+ * guard rejection. The OpenAI patcher calls the interceptor BEFORE it starts
1432
+ * the LLM span and re-throws this error, so the customer sees a
1249
1433
  * `GuardRejectedError` propagated out of their `openai.chat.completions.create`
1250
- * call — the LLM is NEVER invoked.
1434
+ * call, and the LLM does not receive the call. No span records the rejection.
1251
1435
  *
1252
1436
  * Customers who want to handle rejection gracefully can:
1253
1437
  * try { await openai.chat.completions.create({ ... }); }
@@ -1310,12 +1494,19 @@ interface FixInterceptor {
1310
1494
  /**
1311
1495
  * Fix Runtime — Main orchestrator for the fix application system.
1312
1496
  *
1313
- * Manages:
1497
+ * FixRuntime is off by default (`init({ fixRuntime: true })` turns it on).
1498
+ * During the beta, the Risicare service does not give fixes to customer
1499
+ * projects, so FixRuntime has no effect for them. Manages:
1314
1500
  * - Loading active fixes from the API (via FixLoader)
1315
1501
  * - Caching fixes locally (via FixCache)
1316
- * - Applying fixes via interceptors (via DefaultFixInterceptor)
1502
+ * - Running fixes via interceptors on the paths that call them
1317
1503
  * - Tracking fix effectiveness
1318
1504
  *
1505
+ * The interceptor enforces guard fixes on the paths that call it. The
1506
+ * interceptor applies prompt, parameter and fallback fixes only when the call
1507
+ * has an `errorCode`. The provider path does not supply one, so it does not
1508
+ * apply them.
1509
+ *
1319
1510
  * Singleton management via globalThis (same pattern as the tracer).
1320
1511
  *
1321
1512
  * Port of Python SDK's runtime/runtime.py adapted for Node.js.
@@ -1557,4 +1748,19 @@ type WebhookPayload = Uint8Array | ArrayBuffer | string;
1557
1748
  */
1558
1749
  declare function verifyWebhookSignature(payload: WebhookPayload, headers: HeaderLookup, secret: string, opts?: VerifyWebhookOptions): void;
1559
1750
 
1560
- 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 };
1751
+ /**
1752
+ * Risicare SDK for JavaScript/TypeScript — Public API.
1753
+ *
1754
+ * Progressive integration tiers:
1755
+ * Tier 1: init() + patchOpenAI() (minimum setup)
1756
+ * Tier 2: agent() wrapper (agent identity)
1757
+ * Tier 3: session() / withSession() (user sessions)
1758
+ * Tier 4: traceThink/Decide/Act/Observe (decision phases)
1759
+ * Tier 5: traceMessage/Delegate/Coordinate (multi-agent)
1760
+ */
1761
+
1762
+ type Tracer = Tracer$1;
1763
+
1764
+ type Span = Span$1;
1765
+
1766
+ 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, type Span, SpanKind, type SpanOptions, SpanStatus, type StartSpanOptions, type TraceContext, type TracedStreamOptions, type 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 };