risicare 0.6.0 → 0.8.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 (85) hide show
  1. package/LICENSE +26 -0
  2. package/README.md +308 -61
  3. package/dist/frameworks/instructor.cjs +790 -5
  4. package/dist/frameworks/instructor.cjs.map +1 -1
  5. package/dist/frameworks/instructor.js +780 -5
  6. package/dist/frameworks/instructor.js.map +1 -1
  7. package/dist/frameworks/langchain.cjs +790 -5
  8. package/dist/frameworks/langchain.cjs.map +1 -1
  9. package/dist/frameworks/langchain.d.cts +3 -2
  10. package/dist/frameworks/langchain.d.ts +3 -2
  11. package/dist/frameworks/langchain.js +780 -5
  12. package/dist/frameworks/langchain.js.map +1 -1
  13. package/dist/frameworks/langgraph.cjs +790 -5
  14. package/dist/frameworks/langgraph.cjs.map +1 -1
  15. package/dist/frameworks/langgraph.js +780 -5
  16. package/dist/frameworks/langgraph.js.map +1 -1
  17. package/dist/frameworks/llamaindex.cjs +801 -5
  18. package/dist/frameworks/llamaindex.cjs.map +1 -1
  19. package/dist/frameworks/llamaindex.d.cts +3 -2
  20. package/dist/frameworks/llamaindex.d.ts +3 -2
  21. package/dist/frameworks/llamaindex.js +791 -5
  22. package/dist/frameworks/llamaindex.js.map +1 -1
  23. package/dist/index.cjs +1259 -175
  24. package/dist/index.cjs.map +1 -1
  25. package/dist/index.d.cts +245 -39
  26. package/dist/index.d.ts +245 -39
  27. package/dist/index.js +1259 -175
  28. package/dist/index.js.map +1 -1
  29. package/dist/providers/anthropic/index.cjs +1601 -36
  30. package/dist/providers/anthropic/index.cjs.map +1 -1
  31. package/dist/providers/anthropic/index.d.cts +3 -1
  32. package/dist/providers/anthropic/index.d.ts +3 -1
  33. package/dist/providers/anthropic/index.js +1591 -36
  34. package/dist/providers/anthropic/index.js.map +1 -1
  35. package/dist/providers/bedrock/index.cjs +850 -32
  36. package/dist/providers/bedrock/index.cjs.map +1 -1
  37. package/dist/providers/bedrock/index.js +840 -32
  38. package/dist/providers/bedrock/index.js.map +1 -1
  39. package/dist/providers/cerebras/index.cjs +1534 -30
  40. package/dist/providers/cerebras/index.cjs.map +1 -1
  41. package/dist/providers/cerebras/index.js +1524 -30
  42. package/dist/providers/cerebras/index.js.map +1 -1
  43. package/dist/providers/cohere/index.cjs +1557 -102
  44. package/dist/providers/cohere/index.cjs.map +1 -1
  45. package/dist/providers/cohere/index.js +1547 -102
  46. package/dist/providers/cohere/index.js.map +1 -1
  47. package/dist/providers/google/index.cjs +1562 -60
  48. package/dist/providers/google/index.cjs.map +1 -1
  49. package/dist/providers/google/index.js +1552 -60
  50. package/dist/providers/google/index.js.map +1 -1
  51. package/dist/providers/groq/index.cjs +1534 -30
  52. package/dist/providers/groq/index.cjs.map +1 -1
  53. package/dist/providers/groq/index.js +1524 -30
  54. package/dist/providers/groq/index.js.map +1 -1
  55. package/dist/providers/huggingface/index.cjs +1622 -25
  56. package/dist/providers/huggingface/index.cjs.map +1 -1
  57. package/dist/providers/huggingface/index.d.cts +0 -9
  58. package/dist/providers/huggingface/index.d.ts +0 -9
  59. package/dist/providers/huggingface/index.js +1612 -25
  60. package/dist/providers/huggingface/index.js.map +1 -1
  61. package/dist/providers/mistral/index.cjs +1535 -54
  62. package/dist/providers/mistral/index.cjs.map +1 -1
  63. package/dist/providers/mistral/index.js +1525 -54
  64. package/dist/providers/mistral/index.js.map +1 -1
  65. package/dist/providers/ollama/index.cjs +1559 -93
  66. package/dist/providers/ollama/index.cjs.map +1 -1
  67. package/dist/providers/ollama/index.js +1549 -93
  68. package/dist/providers/ollama/index.js.map +1 -1
  69. package/dist/providers/openai/index.cjs +1598 -61
  70. package/dist/providers/openai/index.cjs.map +1 -1
  71. package/dist/providers/openai/index.d.cts +6 -1
  72. package/dist/providers/openai/index.d.ts +6 -1
  73. package/dist/providers/openai/index.js +1588 -61
  74. package/dist/providers/openai/index.js.map +1 -1
  75. package/dist/providers/together/index.cjs +1534 -30
  76. package/dist/providers/together/index.cjs.map +1 -1
  77. package/dist/providers/together/index.js +1524 -30
  78. package/dist/providers/together/index.js.map +1 -1
  79. package/dist/providers/vercel-ai/index.cjs +1288 -17
  80. package/dist/providers/vercel-ai/index.cjs.map +1 -1
  81. package/dist/providers/vercel-ai/index.d.cts +0 -6
  82. package/dist/providers/vercel-ai/index.d.ts +0 -6
  83. package/dist/providers/vercel-ai/index.js +1278 -17
  84. package/dist/providers/vercel-ai/index.js.map +1 -1
  85. package/package.json +5 -12
package/dist/index.d.ts 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;
@@ -274,8 +274,21 @@ declare const MASK_ERROR_MARKER = "<risicare:mask-error>";
274
274
  interface RisicareConfig {
275
275
  /** API key for authentication (format: "rsk-{random}"). Each key is scoped to one project. */
276
276
  apiKey?: string;
277
- /** Gateway endpoint URL */
277
+ /** Ingest gateway URL. It receives spans only. */
278
278
  endpoint?: string;
279
+ /**
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.
290
+ */
291
+ apiEndpoint?: string;
279
292
  /**
280
293
  * @deprecated Project is determined by your API key. This field is ignored
281
294
  * by the gateway and will be removed in v1.0. Use `serviceName` and
@@ -301,7 +314,7 @@ interface RisicareConfig {
301
314
  traceContent?: boolean;
302
315
  /** Sample rate 0.0–1.0 (default: 1.0 = trace all) */
303
316
  sampleRate?: number;
304
- /** Batch size threshold before flush (default: 100) */
317
+ /** Batch size threshold before flush (default: 500) */
305
318
  batchSize?: number;
306
319
  /** Batch timeout in ms before flush (default: 1000) */
307
320
  batchTimeoutMs?: number;
@@ -311,6 +324,18 @@ interface RisicareConfig {
311
324
  debug?: boolean;
312
325
  /** Enable gzip compression for HTTP exports (default: false) */
313
326
  compress?: boolean;
327
+ /**
328
+ * Whether FixRuntime starts (or `RISICARE_FIX_RUNTIME=true`).
329
+ *
330
+ * **Default `false` since 0.7.0** (it started whenever an `apiKey` was set).
331
+ * During the beta, the Risicare service does not give fixes to customer
332
+ * projects, so FixRuntime has no effect for them. When true, the SDK polls
333
+ * `/fixes/active` every 60 s. The interceptor then enforces guard fixes on
334
+ * the paths that call it, and a failed guard throws `GuardRejectedError`.
335
+ * The provider path does not apply prompt, parameter or fallback fixes.
336
+ * When false, nothing polls and nothing is applied.
337
+ */
338
+ fixRuntime?: boolean;
314
339
  /** Custom metadata attached to all spans */
315
340
  metadata?: Record<string, unknown>;
316
341
  /**
@@ -400,7 +425,7 @@ interface TracerConfig {
400
425
  */
401
426
  serviceVersion?: string;
402
427
  }
403
- declare class Tracer {
428
+ declare class Tracer$1 {
404
429
  private _onSpanEnd;
405
430
  private _sampleRate;
406
431
  private _enabled;
@@ -423,14 +448,14 @@ declare class Tracer {
423
448
  *
424
449
  * @returns The callback's return value
425
450
  */
426
- startSpan<T>(options: StartSpanOptions | string, fn: (span: Span) => T): T;
451
+ startSpan<T>(options: StartSpanOptions | string, fn: (span: Span$1) => T): T;
427
452
  /**
428
453
  * Create a span without auto-ending. Caller is responsible for calling span.end().
429
454
  *
430
455
  * Useful for long-running operations where you need manual control.
431
456
  * The span is still linked to context and enriched with session/agent/phase.
432
457
  */
433
- createSpan(options: StartSpanOptions | string): Span;
458
+ createSpan(options: StartSpanOptions | string): Span$1;
434
459
  }
435
460
 
436
461
  /**
@@ -456,20 +481,57 @@ declare class Tracer {
456
481
  declare function init(config?: Partial<RisicareConfig>): void;
457
482
  /**
458
483
  * Gracefully shut down the SDK. Flushes pending spans before resolving.
484
+ *
485
+ * @param timeoutMs - The shutdown budget in milliseconds (default 5000). It is a
486
+ * hard wall-clock bound. A value that is not a finite number (NaN, Infinity, a
487
+ * string, null) gives 5000. A negative value gives 0. The largest value is
488
+ * 2**31 - 1.
489
+ *
490
+ * At the deadline, `shutdown()` stops the export in flight. Spans still queued
491
+ * and spans in the stopped export are counted as `shutdown_residue`, with one
492
+ * WARNING: they were not confirmed as delivered. The server may have received
493
+ * the spans of the stopped export. Each exporter's own `shutdown()` gets only
494
+ * the time that is left of the budget.
495
+ *
496
+ * Limit: the stop does not end a TLS handshake that stalls. Such a handshake
497
+ * can keep the process alive about 10 s after `shutdown()` returns.
459
498
  */
460
- declare function shutdown(): Promise<void>;
499
+ declare function shutdown(timeoutMs?: number): Promise<void>;
461
500
  /**
462
501
  * Flush all pending spans without shutting down.
463
502
  *
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.
503
+ * @param timeoutMs - The budget in milliseconds (default 5000). It is a hard
504
+ * wall-clock bound on the wait: at the deadline `flush()` resolves `false`.
505
+ * A value that is not a finite number (NaN, Infinity, a string, null) gives
506
+ * 5000. A negative value gives 0. The largest value is 2**31 - 1.
507
+ * @returns `true` only if everything queued at entry was DELIVERED and no span
508
+ * was lost since the previous `flush()` returned. A loss is reported by the next
509
+ * `flush()`, one time. It returns `false` in these cases:
510
+ * - the deadline expired with spans still queued or in flight;
511
+ * - a span was discarded since the previous flush returned (F-SDKCB-001 §6);
512
+ * - the backend rejected a span since the previous flush returned, or its ack
513
+ * did not account for a span;
514
+ * - it is called after a `shutdown()` that left spans undelivered
515
+ * (`shutdown_residue`).
516
+ * An uninitialised SDK returns `true`: it was handed nothing, and it lost nothing.
517
+ *
518
+ * `flush()` never stops a request that is already sent. At the deadline it stops
519
+ * waiting; the export in flight continues and ends by its own rules.
520
+ *
521
+ * Limit: that export can keep the process alive after `flush()` returns `false`,
522
+ * until its own timeouts end (measured on a silent server: 22 s). To end a
523
+ * process within a bound, call `await shutdown(timeoutMs)`. It stops the export
524
+ * in flight.
525
+ *
526
+ * Scores: `flush()` also waits, inside the same deadline, for each `score()`
527
+ * request that is not complete. It returns `false` when a score is not complete
528
+ * at the deadline, or when a score failed since the previous `flush()` returned.
529
+ * Each failed score makes one flush `false`, as each lost span does.
468
530
  *
469
531
  * ⚠ Signature change in 0.5.0 — was `Promise<void>`. Existing callers that
470
532
  * ignore the result keep working unchanged.
471
533
  */
472
- declare function flush(): Promise<boolean>;
534
+ declare function flush(timeoutMs?: number): Promise<boolean>;
473
535
  /**
474
536
  * Enable tracing at runtime.
475
537
  */
@@ -485,13 +547,16 @@ declare function isEnabled(): boolean;
485
547
  /**
486
548
  * Get the global tracer instance. Returns undefined if not initialized.
487
549
  */
488
- declare function getTracer(): Tracer | undefined;
550
+ declare function getTracer(): Tracer$1 | undefined;
489
551
  /**
490
552
  * Check whether content tracing (prompt/completion capture) is enabled.
491
553
  */
492
554
  declare function getTraceContent(): boolean;
493
555
  /**
494
- * Get SDK metrics: exported spans, dropped spans, failed exports, queue stats.
556
+ * Get SDK metrics: exported spans (accepted by the backend), `rejectedSpans`,
557
+ * dropped spans and their reasons (`unacknowledged` included), failed exports,
558
+ * queue stats, and `failedScores` (`score()` requests that failed since
559
+ * `init()`).
495
560
  *
496
561
  * `sdkState` — SDK-RELEASE-RULING.md §5 — says WHICH of three different facts
497
562
  * the numbers are, because before it all three rendered as the same zeros:
@@ -515,13 +580,16 @@ declare function getTraceContent(): boolean;
515
580
  * and the WARNING together. The WARNING remains the primary signal.
516
581
  */
517
582
  declare function getMetrics(): {
583
+ failedScores: number;
518
584
  sdkState: "running";
519
585
  exportedSpans: number;
586
+ rejectedSpans: number;
520
587
  droppedSpans: number;
521
588
  droppedSpansByReason: {
522
589
  queue_full: number;
523
590
  transport_refused: number;
524
591
  shutdown_residue: number;
592
+ unacknowledged: number;
525
593
  };
526
594
  failedExports: number;
527
595
  maskErrors: number;
@@ -529,13 +597,16 @@ declare function getMetrics(): {
529
597
  queueCapacity: number;
530
598
  queueUtilization: number;
531
599
  } | {
600
+ failedScores: number;
532
601
  droppedSpansByReason: {
533
602
  queue_full: number;
534
603
  transport_refused: number;
535
604
  shutdown_residue: number;
605
+ unacknowledged: number;
536
606
  };
537
607
  sdkState: "shutdown";
538
608
  exportedSpans: number;
609
+ rejectedSpans: number;
539
610
  droppedSpans: number;
540
611
  failedExports: number;
541
612
  maskErrors: number;
@@ -544,11 +615,14 @@ declare function getMetrics(): {
544
615
  queueUtilization: number;
545
616
  } | {
546
617
  exportedSpans: number;
618
+ rejectedSpans: number;
619
+ failedScores: number;
547
620
  droppedSpans: number;
548
621
  droppedSpansByReason: {
549
622
  queue_full: number;
550
623
  transport_refused: number;
551
624
  shutdown_residue: number;
625
+ unacknowledged: number;
552
626
  };
553
627
  failedExports: number;
554
628
  queueSize: number;
@@ -573,8 +647,22 @@ declare function reportError(error: unknown, options?: {
573
647
  /**
574
648
  * Record a custom evaluation score on a trace.
575
649
  *
576
- * Sends the score to the server in a fire-and-forget fashion.
577
- * This function never throws and is non-blocking.
650
+ * Sends the score in the background. The root `flush()` waits for it.
651
+ * This function never throws and does not block. At most 50 score requests
652
+ * are in flight at once. Up to 1,000 scores wait for a free slot, with no timer;
653
+ * the 2000 ms bound of a score starts when its request starts. A score that
654
+ * comes when 1,000 already wait fails at once and is counted. When a `flush()`
655
+ * or `shutdown()` bound ends, the scores that still wait fail and are not sent.
656
+ *
657
+ * Delivery: the request stops after 2000 ms and never follows a redirect. A
658
+ * status of 300 or more, an error or the timeout is a failure, and it adds 1
659
+ * to `failedScores` in `getMetrics()`. The first failure writes a WARNING with
660
+ * the score name and the status or the error code. Later failures in the next
661
+ * 10 s are counted, and the next WARNING gives their number. Root `flush()`
662
+ * waits for pending scores inside its deadline, and returns `false` when a
663
+ * score failed since the previous `flush()` returned. An out-of-range value, or an empty `traceId`
664
+ * or `name`, writes one WARNING, and the SDK does not send the score. `true`
665
+ * and `false` count as 1 and 0.
578
666
  *
579
667
  * If a `mask` is configured on `init()`, `options.comment` is passed to it under
580
668
  * the key `score.comment` before the request is built. `traceId`, `spanId` and
@@ -679,6 +767,14 @@ declare function withSession<T>(options: SessionOptions, fn: () => T): T;
679
767
  * );
680
768
  */
681
769
 
770
+ /**
771
+ * Blocks inference from the resolver, so that the target function alone
772
+ * decides `TArgs` (F-020). The resolver may declare fewer parameters than the
773
+ * target, as the documented `(sessionId, userId) => ...` resolver does.
774
+ * Written without the built-in `NoInfer` (TypeScript 5.4+) because the
775
+ * package supports TypeScript 5.0.
776
+ */
777
+ type NoInferArgs<T> = [T][T extends unknown ? 0 : never];
682
778
  /**
683
779
  * Wrap a function with session context.
684
780
  *
@@ -693,14 +789,18 @@ declare function withSession<T>(options: SessionOptions, fn: () => T): T;
693
789
  * @param optionsOrResolver - Static session options, or a function that derives them from args
694
790
  * @param fn - The function to wrap. If omitted, returns a decorator factory.
695
791
  */
696
- declare function session<TArgs extends unknown[], TReturn>(optionsOrResolver: SessionOptions | ((...args: TArgs) => SessionOptions), fn: (...args: TArgs) => TReturn): (...args: TArgs) => TReturn;
792
+ declare function session<TArgs extends unknown[], TReturn>(optionsOrResolver: SessionOptions | ((...args: NoInferArgs<TArgs>) => SessionOptions), fn: (...args: TArgs) => TReturn): (...args: TArgs) => TReturn;
793
+ declare function session(options: SessionOptions): <TArgs extends unknown[], TR>(fn: (...args: TArgs) => TR) => (...args: TArgs) => TR;
794
+ declare function session<TArgs extends unknown[]>(resolver: (...args: TArgs) => SessionOptions): <TR>(fn: (...args: TArgs) => TR) => (...args: TArgs) => TR;
697
795
  declare function session<TArgs extends unknown[]>(optionsOrResolver: SessionOptions | ((...args: TArgs) => SessionOptions)): <TR>(fn: (...args: TArgs) => TR) => (...args: TArgs) => TR;
698
796
 
699
797
  /**
700
798
  * Phase decorators — decision phase tracking (Tier 4).
701
799
  *
702
800
  * Wraps functions to execute within a semantic phase context (THINK/DECIDE/ACT/OBSERVE).
703
- * Each creates a span named after the phase.
801
+ * Each creates a span. The named form uses the given name. The bare form uses
802
+ * `<phase>:<function name>` (for example `think:analyzeQuery`), as the Python
803
+ * SDK does; an anonymous function gives `phase:<phase>` (for example `phase:think`).
704
804
  *
705
805
  * @example
706
806
  * const analyze = traceThink(async (data: string) => {
@@ -818,16 +918,48 @@ interface AgentContext {
818
918
  }
819
919
  declare function getCurrentSession(): SessionContext | undefined;
820
920
  declare function getCurrentAgent(): AgentContext | undefined;
821
- declare function getCurrentSpan(): Span | undefined;
921
+ declare function getCurrentSpan(): Span$1 | undefined;
822
922
  declare function getCurrentPhase(): SemanticPhase | undefined;
823
923
  declare function getCurrentSessionId(): string | undefined;
824
924
  declare function getCurrentAgentId(): string | undefined;
825
925
  declare function getCurrentTraceId(): string | undefined;
826
926
  declare function getCurrentSpanId(): string | undefined;
927
+ /**
928
+ * A plain-object snapshot of the current context, as `getCurrentContext()`
929
+ * returns it. `session`, `agent` and `span` are `null` when not set.
930
+ *
931
+ * This is a type alias, not an interface, so that a value of this type is
932
+ * still assignable to `Record<string, unknown>` (the return type through 0.7.1).
933
+ * `getCurrentContext()` returns it joined with `Record<string, unknown>`, so
934
+ * code that writes or reads other keys still compiles.
935
+ */
936
+ type ContextSnapshot = {
937
+ session: {
938
+ sessionId: string;
939
+ userId?: string;
940
+ parentSessionId?: string;
941
+ turnNumber?: number;
942
+ metadata?: Record<string, unknown>;
943
+ } | null;
944
+ agent: {
945
+ agentId: string;
946
+ agentName?: string;
947
+ agentRole?: string;
948
+ agentType?: string;
949
+ parentAgentId?: string;
950
+ version?: number;
951
+ metadata?: Record<string, unknown>;
952
+ } | null;
953
+ span: {
954
+ spanId: string;
955
+ traceId: string;
956
+ } | null;
957
+ phase: SemanticPhase | null;
958
+ };
827
959
  /**
828
960
  * Get all current context as a plain object (for debugging/serialization).
829
961
  */
830
- declare function getCurrentContext(): Record<string, unknown>;
962
+ declare function getCurrentContext(): ContextSnapshot & Record<string, unknown>;
831
963
 
832
964
  /**
833
965
  * Serializable trace context + W3C Trace Context headers.
@@ -849,9 +981,15 @@ interface TraceContext {
849
981
  * Get the current trace context as a serializable object.
850
982
  *
851
983
  * When called inside a span context, returns the active span's IDs.
852
- * When called outside a span (e.g. inside session() but before agent()),
853
- * pre-allocates a trace ID and stores it in context so the next
854
- * startSpan() call inherits it — preventing trace ID mismatch.
984
+ * When called outside a span but inside a context scope (for example inside
985
+ * `withSession()`, `withAgent()` or `withPhase()`), pre-allocates a trace ID
986
+ * and stores it in that scope. The ID stays in the scope. EVERY later root
987
+ * span in that scope uses it: the next span, each span after it, and spans
988
+ * that start at the same time (for example in `Promise.all`). So all root
989
+ * spans of the scope are in one trace. Later calls return the same ID.
990
+ *
991
+ * Outside every context scope there is no place to store the ID: each call
992
+ * returns a new trace ID, and the next span does not use it.
855
993
  */
856
994
  declare function getTraceContext(): TraceContext;
857
995
  /**
@@ -860,8 +998,12 @@ declare function getTraceContext(): TraceContext;
860
998
  declare function injectTraceContext(headers: Record<string, string>): Record<string, string>;
861
999
  /**
862
1000
  * Extract trace context from HTTP headers (W3C format).
1001
+ *
1002
+ * Accepts a plain string record or Node's `IncomingHttpHeaders`
1003
+ * (`req.headers`). For a header with several values (`string[]`) the first
1004
+ * value is used. An `undefined` value is ignored.
863
1005
  */
864
- declare function extractTraceContext(headers: Record<string, string>): Record<string, string | undefined>;
1006
+ declare function extractTraceContext(headers: Record<string, string | string[] | undefined>): Record<string, string | undefined>;
865
1007
 
866
1008
  /**
867
1009
  * Span registry — TTL-based span store for edge cases.
@@ -873,8 +1015,8 @@ declare function extractTraceContext(headers: Record<string, string>): Record<st
873
1015
  * - Long-running operations that outlive their original context
874
1016
  */
875
1017
 
876
- declare function registerSpan(span: Span, ttlMs?: number): void;
877
- declare function getSpanById(spanId: string): Span | undefined;
1018
+ declare function registerSpan(span: Span$1, ttlMs?: number): void;
1019
+ declare function getSpanById(spanId: string): Span$1 | undefined;
878
1020
  declare function unregisterSpan(spanId: string): void;
879
1021
 
880
1022
  /**
@@ -883,8 +1025,9 @@ declare function unregisterSpan(spanId: string): void;
883
1025
  * Creates a span that starts when iteration begins and ends when
884
1026
  * iteration completes (or errors). Chunks pass through UNCHANGED.
885
1027
  *
886
- * This is the user-level streaming utility. For provider-level streaming
887
- * enrichment (token counts, cost), see individual provider instrumentors.
1028
+ * This is the user-level streaming utility. The OpenAI, Anthropic, Groq,
1029
+ * Cerebras and Together patches do not read a stream; the Google, Cohere,
1030
+ * Mistral and Ollama patches do (see each provider's patch).
888
1031
  *
889
1032
  * Usage:
890
1033
  * const stream = await openai.chat.completions.create({ stream: true, ... });
@@ -951,7 +1094,7 @@ declare function isProviderInstrumentationSuppressed(): boolean;
951
1094
  * Port of Python SDK's runtime/config.py adapted for Node.js patterns.
952
1095
  */
953
1096
  interface FixRuntimeConfig {
954
- /** API endpoint URL (e.g., "https://app.risicare.ai") */
1097
+ /** Api URL, serving /v1/fixes/active (e.g., "https://api.risicare.ai") */
955
1098
  apiEndpoint: string;
956
1099
  /** API key for authentication (format: "rsk-{random}") */
957
1100
  apiKey: string;
@@ -1130,6 +1273,26 @@ declare class FixApplier {
1130
1273
  * - content_filter: Regex-based blocked patterns
1131
1274
  * - format_check: JSON.parse() validity
1132
1275
  * - input_validation / output_validation: min/max length
1276
+ *
1277
+ * `content_filter` searches the content for each entry of `blocked_patterns`
1278
+ * (case-insensitive, after `translatePythonPattern`). It fails CLOSED: when
1279
+ * `blocked_patterns` is not a list, or an entry is empty, is not a string,
1280
+ * is longer than 500 characters or cannot be used, the guard does not pass.
1281
+ * One WARNING names the fix id and the pattern index, once for each pair in
1282
+ * the process. The reason names the pattern index, never the pattern or the
1283
+ * content.
1284
+ *
1285
+ * Limits:
1286
+ * - The interceptor runs only on the OpenAI chat patch (input guards) and on
1287
+ * `interceptCall` / `interceptResponse`. It does not run when a framework
1288
+ * integration suppresses provider instrumentation.
1289
+ * - Each SDK uses its own regular-expression engine. These constructs can
1290
+ * give a different result in JavaScript and Python: `$` before a final
1291
+ * newline, Unicode case folding, `\d` and `\w` on non-ASCII text,
1292
+ * `\N{...}` and `\U........` (JavaScript fails closed), and a `]` first
1293
+ * in a class.
1294
+ * - A pattern has no time bound. A pattern with nested repeats can take a
1295
+ * very long time on a long input.
1133
1296
  */
1134
1297
  applyGuardFix(fix: ActiveFix, content: string, isInput?: boolean): {
1135
1298
  content: string;
@@ -1143,6 +1306,11 @@ declare class FixApplier {
1143
1306
  /**
1144
1307
  * Safely compile a regex pattern from untrusted input.
1145
1308
  * Returns null if invalid or too long.
1309
+ *
1310
+ * F-029: the fix patterns are written for Python `re`. Before it compiles
1311
+ * the pattern, this function translates the Python forms that have an exact
1312
+ * JavaScript equivalent (see `translatePythonPattern`). The `i` flag is
1313
+ * always on, as in the Python applier.
1146
1314
  */
1147
1315
  private _safeCompileRegex;
1148
1316
  /** Prepend content to the first message matching the target role. */
@@ -1177,9 +1345,18 @@ declare class FixLoader {
1177
1345
  private _consecutiveFailures;
1178
1346
  private _circuitOpenUntil;
1179
1347
  private _onLoadCallbacks;
1348
+ private _lastStatus;
1180
1349
  private static readonly CIRCUIT_BREAKER_THRESHOLD;
1181
1350
  private static readonly CIRCUIT_BREAKER_COOLDOWN_MS;
1182
1351
  constructor(config: FixRuntimeConfig, cache: FixCache);
1352
+ /** Error text for a log line: one line, the api endpoint as `safeUrl` gives it, no key. */
1353
+ private _scrub;
1354
+ /**
1355
+ * The WARNING for a failed first load: the request URL with no userinfo, no
1356
+ * query and no key, the HTTP status or the error class, and that tracing is
1357
+ * not affected. Never the error text: it can echo the URL with its query.
1358
+ */
1359
+ private _firstLoadWarning;
1183
1360
  /** Timestamp of last successful load. */
1184
1361
  get lastLoadTime(): number | null;
1185
1362
  /**
@@ -1212,9 +1389,16 @@ declare class FixLoader {
1212
1389
  /**
1213
1390
  * Fix Interceptors — Hook into LLM/tool calls to apply fixes.
1214
1391
  *
1215
- * Interceptors are registered with the runtime and called during agent
1216
- * execution to apply relevant fixes at three interception points:
1217
- * - preCall: Before the LLM/tool call (prompt/parameter/fallback fixes)
1392
+ * FixRuntime is off by default. During the beta, the Risicare service does not
1393
+ * give fixes to customer projects, so FixRuntime has no effect for them.
1394
+ *
1395
+ * The interceptor enforces guard fixes only on the paths that call it:
1396
+ * `interceptCall` and `interceptResponse` on `FixRuntime`, and the OpenAI chat
1397
+ * patch (input guards only). Three interception points:
1398
+ * - preCall: Before the LLM/tool call. Input guards always; prompt,
1399
+ * parameter and fallback fixes only when the context has an
1400
+ * `errorCode`. The provider path supplies none, so it does not
1401
+ * apply them.
1218
1402
  * - postCall: After the call (output guard validation)
1219
1403
  * - onError: When an error occurs (retry/fallback decisions)
1220
1404
  *
@@ -1230,10 +1414,10 @@ declare class FixLoader {
1230
1414
  * LLM with the attacker payload anyway. The `fail-CLOSED` was advisory only.
1231
1415
  *
1232
1416
  * Now the interceptor THROWS this error on both pre-call and post-call
1233
- * guard rejection. The provider patcher's surrounding span.startSpan
1234
- * already catches and records exceptions, so the customer sees a
1417
+ * guard rejection. The OpenAI patcher calls the interceptor BEFORE it starts
1418
+ * the LLM span and re-throws this error, so the customer sees a
1235
1419
  * `GuardRejectedError` propagated out of their `openai.chat.completions.create`
1236
- * call — the LLM is NEVER invoked.
1420
+ * call, and the LLM does not receive the call. No span records the rejection.
1237
1421
  *
1238
1422
  * Customers who want to handle rejection gracefully can:
1239
1423
  * try { await openai.chat.completions.create({ ... }); }
@@ -1296,12 +1480,19 @@ interface FixInterceptor {
1296
1480
  /**
1297
1481
  * Fix Runtime — Main orchestrator for the fix application system.
1298
1482
  *
1299
- * Manages:
1483
+ * FixRuntime is off by default (`init({ fixRuntime: true })` turns it on).
1484
+ * During the beta, the Risicare service does not give fixes to customer
1485
+ * projects, so FixRuntime has no effect for them. Manages:
1300
1486
  * - Loading active fixes from the API (via FixLoader)
1301
1487
  * - Caching fixes locally (via FixCache)
1302
- * - Applying fixes via interceptors (via DefaultFixInterceptor)
1488
+ * - Running fixes via interceptors on the paths that call them
1303
1489
  * - Tracking fix effectiveness
1304
1490
  *
1491
+ * The interceptor enforces guard fixes on the paths that call it. The
1492
+ * interceptor applies prompt, parameter and fallback fixes only when the call
1493
+ * has an `errorCode`. The provider path does not supply one, so it does not
1494
+ * apply them.
1495
+ *
1305
1496
  * Singleton management via globalThis (same pattern as the tracer).
1306
1497
  *
1307
1498
  * Port of Python SDK's runtime/runtime.py adapted for Node.js.
@@ -1543,4 +1734,19 @@ type WebhookPayload = Uint8Array | ArrayBuffer | string;
1543
1734
  */
1544
1735
  declare function verifyWebhookSignature(payload: WebhookPayload, headers: HeaderLookup, secret: string, opts?: VerifyWebhookOptions): void;
1545
1736
 
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 };
1737
+ /**
1738
+ * Risicare SDK for JavaScript/TypeScript — Public API.
1739
+ *
1740
+ * Progressive integration tiers:
1741
+ * Tier 1: init() + patchOpenAI() (minimum setup)
1742
+ * Tier 2: agent() wrapper (agent identity)
1743
+ * Tier 3: session() / withSession() (user sessions)
1744
+ * Tier 4: traceThink/Decide/Act/Observe (decision phases)
1745
+ * Tier 5: traceMessage/Delegate/Coordinate (multi-agent)
1746
+ */
1747
+
1748
+ type Tracer = Tracer$1;
1749
+
1750
+ type Span = Span$1;
1751
+
1752
+ 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 };