@sentrial/sdk 0.2.0 → 0.3.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.
package/dist/index.d.cts CHANGED
@@ -1,6 +1,80 @@
1
+ /**
2
+ * PII Redaction Module
3
+ *
4
+ * Automatically detects and redacts personally identifiable information (PII)
5
+ * from SDK payloads before they are sent to the Sentrial API.
6
+ */
7
+ /** How redacted values are replaced */
8
+ type PiiMode = 'label' | 'hash' | 'remove';
9
+ /** Fields that can be redacted in SDK payloads */
10
+ type PiiField = 'userInput' | 'assistantOutput' | 'toolInput' | 'toolOutput' | 'metadata' | 'reasoning' | 'failureReason';
11
+ /** A custom regex pattern with a human-readable label */
12
+ interface PiiCustomPattern {
13
+ pattern: RegExp;
14
+ label: string;
15
+ }
16
+ /** Toggle individual builtin pattern categories */
17
+ interface PiiBuiltinPatterns {
18
+ emails?: boolean;
19
+ phones?: boolean;
20
+ ssns?: boolean;
21
+ creditCards?: boolean;
22
+ ipAddresses?: boolean;
23
+ }
24
+ /** Full PII redaction configuration */
25
+ interface PiiConfig {
26
+ /** Enable PII redaction (default: false) */
27
+ enabled: boolean;
28
+ /** Which payload fields to redact (default: DEFAULT_FIELDS) */
29
+ fields?: PiiField[];
30
+ /** Replacement mode (default: 'label') */
31
+ mode?: PiiMode;
32
+ /** Enable enhanced detection heuristics (reserved for future use) */
33
+ enhancedDetection?: boolean;
34
+ /** Toggle builtin patterns (default: all enabled) */
35
+ builtinPatterns?: PiiBuiltinPatterns;
36
+ /** Additional custom patterns to apply */
37
+ customPatterns?: PiiCustomPattern[];
38
+ }
39
+ /**
40
+ * Hash a value using SHA-256 and return the first 6 hex characters.
41
+ * Used in 'hash' mode to produce a short, deterministic pseudonym.
42
+ */
43
+ declare function hashValue(value: string): string;
44
+ /**
45
+ * Produce the replacement string for a matched PII value.
46
+ *
47
+ * - 'label' mode: [LABEL]
48
+ * - 'hash' mode: [PII:abcdef]
49
+ * - 'remove' mode: '' (empty string)
50
+ */
51
+ declare function replaceMatch(match: string, label: string, mode: PiiMode): string;
52
+ /**
53
+ * Run all enabled builtin and custom patterns against a single string,
54
+ * replacing every match according to the specified mode.
55
+ */
56
+ declare function redactString(value: string, mode: PiiMode, builtinPatterns: Required<PiiBuiltinPatterns>, customPatterns: PiiCustomPattern[]): string;
57
+ /**
58
+ * Recursively redact PII from a value. Handles strings, arrays, plain objects,
59
+ * and passes through primitives (numbers, booleans, null, undefined) unchanged.
60
+ */
61
+ declare function redactValue(value: unknown, mode: PiiMode, builtinPatterns: Required<PiiBuiltinPatterns>, customPatterns: PiiCustomPattern[]): unknown;
62
+ /**
63
+ * Main entry point: redact configured fields in a payload object.
64
+ *
65
+ * Only fields listed in the PiiConfig (or DEFAULT_FIELDS) are redacted.
66
+ * Other fields are returned unchanged.
67
+ *
68
+ * @param payload - The data payload (e.g., session params, tool call params)
69
+ * @param config - PII configuration from the client
70
+ * @returns A new payload object with PII redacted from the configured fields
71
+ */
72
+ declare function redactPayload(payload: Record<string, unknown>, config: PiiConfig): Record<string, unknown>;
73
+
1
74
  /**
2
75
  * Type definitions for the Sentrial TypeScript SDK
3
76
  */
77
+
4
78
  /**
5
79
  * Event types that can be tracked in a session
6
80
  */
@@ -27,6 +101,12 @@ interface SentrialClientConfig {
27
101
  * Set to false during development to see full errors.
28
102
  */
29
103
  failSilently?: boolean;
104
+ /**
105
+ * PII redaction configuration.
106
+ * - Pass a PiiConfig object for full control.
107
+ * - Pass `true` to fetch the org's PII config from the server automatically.
108
+ */
109
+ pii?: PiiConfig | boolean;
30
110
  }
31
111
  /**
32
112
  * Parameters for creating a new session
@@ -40,6 +120,8 @@ interface CreateSessionParams {
40
120
  userId: string;
41
121
  /** Optional parent session ID for multi-agent hierarchies */
42
122
  parentSessionId?: string;
123
+ /** Optional conversation ID to group related sessions into a thread */
124
+ convoId?: string;
43
125
  /** Optional metadata */
44
126
  metadata?: Record<string, unknown>;
45
127
  }
@@ -79,6 +161,7 @@ interface Session {
79
161
  id: string;
80
162
  agentId?: string;
81
163
  parentSessionId?: string;
164
+ convoId?: string;
82
165
  name: string;
83
166
  agentName: string;
84
167
  userId: string;
@@ -368,8 +451,18 @@ declare class SentrialClient {
368
451
  private readonly apiUrl;
369
452
  private readonly apiKey?;
370
453
  private readonly failSilently;
454
+ private piiConfig?;
455
+ private piiConfigNeedsHydration;
456
+ private piiHydrationPromise?;
371
457
  private currentState;
372
458
  constructor(config?: SentrialClientConfig);
459
+ /**
460
+ * Fetch the organization's PII config from the server.
461
+ *
462
+ * Called lazily on the first request when `pii: true` was passed to the constructor.
463
+ * Uses a single shared promise so concurrent requests don't trigger duplicate fetches.
464
+ */
465
+ private hydratePiiConfig;
373
466
  /**
374
467
  * Make an HTTP request with retry logic and exponential backoff.
375
468
  *
@@ -678,11 +771,11 @@ declare class ValidationError extends SentrialError {
678
771
  *
679
772
  * @example Simple Usage
680
773
  * ```ts
681
- * import { configure, wrapAISDK } from '@sentrial/sdk';
774
+ * import { configureVercel, wrapAISDK } from '@sentrial/sdk';
682
775
  * import * as ai from 'ai';
683
776
  * import { openai } from '@ai-sdk/openai';
684
777
  *
685
- * configure({
778
+ * configureVercel({
686
779
  * apiKey: process.env.SENTRIAL_API_KEY,
687
780
  * defaultAgent: 'my-ai-agent',
688
781
  * });
@@ -696,29 +789,15 @@ declare class ValidationError extends SentrialError {
696
789
  * });
697
790
  * ```
698
791
  *
699
- * @example With Tools
792
+ * @example Multi-Turn Conversations
700
793
  * ```ts
701
- * import { configure, wrapAISDK } from '@sentrial/sdk';
702
- * import * as ai from 'ai';
703
- * import { openai } from '@ai-sdk/openai';
704
- * import { z } from 'zod';
705
- *
706
- * configure({ apiKey: process.env.SENTRIAL_API_KEY, defaultAgent: 'tool-agent' });
707
- *
708
- * const { generateText } = wrapAISDK(ai);
794
+ * const { generateText } = wrapAISDK(ai, { convoId: 'convo_123' });
709
795
  *
796
+ * // All calls are linked to the same conversation thread
710
797
  * const { text } = await generateText({
711
- * model: openai('gpt-4'),
712
- * prompt: "What's the weather in San Francisco?",
713
- * tools: {
714
- * getWeather: {
715
- * description: 'Get weather for a location',
716
- * parameters: z.object({ location: z.string() }),
717
- * execute: async ({ location }) => ({ temperature: 72, conditions: 'sunny' }),
718
- * },
719
- * },
798
+ * model: openai('gpt-4o'),
799
+ * messages: conversationHistory,
720
800
  * });
721
- * // Tool calls are automatically traced as child spans!
722
801
  * ```
723
802
  *
724
803
  * @packageDocumentation
@@ -740,23 +819,38 @@ type GenerateTextParams = {
740
819
  prompt?: string;
741
820
  messages?: Array<{
742
821
  role: string;
743
- content: string;
822
+ content: string | unknown;
744
823
  }>;
745
824
  system?: string;
746
825
  tools?: Record<string, {
747
826
  execute?: Function;
748
827
  } & Record<string, unknown>>;
749
828
  maxTokens?: number;
829
+ maxSteps?: number;
750
830
  temperature?: number;
751
831
  [key: string]: unknown;
752
832
  };
833
+ type UsageInfo = {
834
+ promptTokens?: number;
835
+ completionTokens?: number;
836
+ totalTokens?: number;
837
+ };
838
+ type StepResult = {
839
+ text?: string;
840
+ toolCalls?: Array<{
841
+ toolName: string;
842
+ args: unknown;
843
+ }>;
844
+ toolResults?: Array<{
845
+ toolName: string;
846
+ result: unknown;
847
+ }>;
848
+ usage?: UsageInfo;
849
+ finishReason?: string;
850
+ };
753
851
  type GenerateTextResult = {
754
852
  text: string;
755
- usage?: {
756
- promptTokens?: number;
757
- completionTokens?: number;
758
- totalTokens?: number;
759
- };
853
+ usage?: UsageInfo;
760
854
  finishReason?: string;
761
855
  toolCalls?: Array<{
762
856
  toolName: string;
@@ -768,16 +862,19 @@ type GenerateTextResult = {
768
862
  }>;
769
863
  response?: {
770
864
  modelId?: string;
865
+ id?: string;
771
866
  };
867
+ steps?: StepResult[];
868
+ reasoning?: unknown;
869
+ reasoningText?: string;
870
+ sources?: unknown[];
772
871
  [key: string]: unknown;
773
872
  };
774
873
  type StreamTextResult = {
775
874
  textStream: AsyncIterable<string>;
776
- usage?: Promise<{
777
- promptTokens?: number;
778
- completionTokens?: number;
779
- totalTokens?: number;
780
- }>;
875
+ fullStream?: AsyncIterable<unknown>;
876
+ text?: string | Promise<string>;
877
+ usage?: Promise<UsageInfo>;
781
878
  finishReason?: Promise<string>;
782
879
  toolCalls?: Promise<Array<{
783
880
  toolName: string;
@@ -787,19 +884,30 @@ type StreamTextResult = {
787
884
  toolName: string;
788
885
  result: unknown;
789
886
  }>>;
887
+ steps?: Promise<StepResult[]>;
888
+ response?: Promise<{
889
+ modelId?: string;
890
+ id?: string;
891
+ }>;
790
892
  [key: string]: unknown;
791
893
  };
894
+ /** Per-instance config passed through closures (not global) */
895
+ type WrapperConfig = {
896
+ defaultAgent?: string;
897
+ userId?: string;
898
+ convoId?: string;
899
+ };
792
900
  /**
793
901
  * Configure the Sentrial SDK for Vercel AI SDK integration.
794
902
  *
795
903
  * @example
796
904
  * ```ts
797
- * import { configure } from '@sentrial/sdk';
905
+ * import { configureVercel } from '@sentrial/sdk';
798
906
  *
799
- * configure({
907
+ * configureVercel({
800
908
  * apiKey: process.env.SENTRIAL_API_KEY,
801
909
  * defaultAgent: 'my-chatbot',
802
- * userId: 'user_123', // Optional default user ID
910
+ * userId: 'user_123',
803
911
  * });
804
912
  * ```
805
913
  */
@@ -808,48 +916,43 @@ declare function configureVercel(config: {
808
916
  apiUrl?: string;
809
917
  defaultAgent?: string;
810
918
  userId?: string;
919
+ convoId?: string;
811
920
  failSilently?: boolean;
812
921
  }): void;
813
- /**
814
- * Wrap generateText function
815
- */
816
- declare function wrapGenerateText(originalFn: Function, client: SentrialClient): (params: GenerateTextParams) => Promise<GenerateTextResult>;
817
- /**
818
- * Wrap streamText function
819
- */
820
- declare function wrapStreamText(originalFn: Function, client: SentrialClient): (params: GenerateTextParams) => StreamTextResult;
821
- /**
822
- * Wrap generateObject function (similar to generateText)
823
- */
824
- declare function wrapGenerateObject(originalFn: Function, client: SentrialClient): (params: GenerateTextParams) => Promise<unknown>;
825
- /**
826
- * Wrap streamObject function
827
- */
828
- declare function wrapStreamObject(originalFn: Function, client: SentrialClient): (params: GenerateTextParams) => unknown;
922
+ declare function wrapGenerateText(originalFn: Function, client: SentrialClient, config: WrapperConfig): (params: GenerateTextParams) => Promise<GenerateTextResult>;
923
+ declare function wrapStreamText(originalFn: Function, client: SentrialClient, config: WrapperConfig): (params: GenerateTextParams) => StreamTextResult;
924
+ declare function wrapGenerateObject(originalFn: Function, client: SentrialClient, config: WrapperConfig): (params: GenerateTextParams) => Promise<unknown>;
925
+ declare function wrapStreamObject(originalFn: Function, client: SentrialClient, config: WrapperConfig): (params: GenerateTextParams) => unknown;
829
926
  /**
830
927
  * Wrap the Vercel AI SDK to automatically trace all AI calls.
831
928
  *
832
929
  * @param ai - The imported `ai` module from the Vercel AI SDK
930
+ * @param options - Optional configuration (client, defaultAgent, userId, convoId)
833
931
  * @returns Wrapped versions of the AI SDK functions
834
932
  *
835
- * @example
933
+ * @example Using with configureVercel
836
934
  * ```ts
837
- * import { configure, wrapAISDK } from '@sentrial/sdk';
838
- * import * as ai from 'ai';
839
- * import { openai } from '@ai-sdk/openai';
840
- *
841
- * configure({ apiKey: process.env.SENTRIAL_API_KEY, defaultAgent: 'my-agent' });
935
+ * configureVercel({ apiKey: process.env.SENTRIAL_API_KEY, defaultAgent: 'my-agent' });
936
+ * const { generateText, streamText } = wrapAISDK(ai);
937
+ * ```
842
938
  *
843
- * const { generateText, streamText, generateObject, streamObject } = wrapAISDK(ai);
939
+ * @example Multi-turn conversations
940
+ * ```ts
941
+ * const { generateText } = wrapAISDK(ai, { convoId: 'convo_123' });
942
+ * ```
844
943
  *
845
- * // All calls are now automatically traced!
846
- * const { text } = await generateText({
847
- * model: openai('gpt-4'),
848
- * prompt: 'Hello!',
849
- * });
944
+ * @example Using with existing SentrialClient
945
+ * ```ts
946
+ * const client = new SentrialClient({ apiKey: process.env.SENTRIAL_API_KEY });
947
+ * const { generateText } = wrapAISDK(ai, { client, defaultAgent: 'my-agent' });
850
948
  * ```
851
949
  */
852
- declare function wrapAISDK(ai: AIModule): {
950
+ declare function wrapAISDK(ai: AIModule, options?: {
951
+ client?: SentrialClient;
952
+ defaultAgent?: string;
953
+ userId?: string;
954
+ convoId?: string;
955
+ }): {
853
956
  generateText: ReturnType<typeof wrapGenerateText>;
854
957
  streamText: ReturnType<typeof wrapStreamText>;
855
958
  generateObject: ReturnType<typeof wrapGenerateObject>;
@@ -1577,4 +1680,4 @@ declare class Experiment {
1577
1680
  getResults(): Promise<ExperimentResults | null>;
1578
1681
  }
1579
1682
 
1580
- export { ApiError, type ApiResponse, type BeginParams, type CompleteSessionParams, type CostParams, type CreateSessionParams, type Event, EventType, Experiment, type ExperimentContext, type ExperimentResults, type ExperimentRunResult, ExperimentRunTracker, type ExperimentTestCase, type ExperimentVariant, type FinishParams, type GenerateTextParams, type GenerateTextResult, Interaction, NetworkError, SentrialClient, type SentrialClientConfig, SentrialError, type Session, SessionContext, type SessionStatus, type StreamTextResult, Tool, type TrackDecisionParams, type TrackErrorParams, TrackSession, type TrackToolCallParams, ValidationError, begin, calculateAnthropicCost, calculateGoogleCost, calculateOpenAICost, clearExperimentContext, clearSessionContext, configure, configureVercel, getCurrentInteraction, getCurrentSessionId, getExperimentContext, getExperimentId, getSessionContext, getSystemPrompt, getVariantName, isExperimentMode, sentrial, setClient, setDefaultClient, setExperimentContext, setSessionContext, withSession, withTool, wrapAISDK, wrapAnthropic, wrapGoogle, wrapLLM, wrapOpenAI };
1683
+ export { ApiError, type ApiResponse, type BeginParams, type CompleteSessionParams, type CostParams, type CreateSessionParams, type Event, EventType, Experiment, type ExperimentContext, type ExperimentResults, type ExperimentRunResult, ExperimentRunTracker, type ExperimentTestCase, type ExperimentVariant, type FinishParams, type GenerateTextParams, type GenerateTextResult, Interaction, NetworkError, type PiiBuiltinPatterns, type PiiConfig, type PiiCustomPattern, type PiiField, type PiiMode, SentrialClient, type SentrialClientConfig, SentrialError, type Session, SessionContext, type SessionStatus, type StreamTextResult, Tool, type TrackDecisionParams, type TrackErrorParams, TrackSession, type TrackToolCallParams, ValidationError, begin, calculateAnthropicCost, calculateGoogleCost, calculateOpenAICost, clearExperimentContext, clearSessionContext, configure, configureVercel, getCurrentInteraction, getCurrentSessionId, getExperimentContext, getExperimentId, getSessionContext, getSystemPrompt, getVariantName, hashValue, isExperimentMode, redactPayload, redactString, redactValue, replaceMatch, sentrial, setClient, setDefaultClient, setExperimentContext, setSessionContext, withSession, withTool, wrapAISDK, wrapAnthropic, wrapGoogle, wrapLLM, wrapOpenAI };