@sentrial/sdk 0.1.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.
@@ -0,0 +1,642 @@
1
+ /**
2
+ * Type definitions for the Sentrial TypeScript SDK
3
+ */
4
+ /**
5
+ * Event types that can be tracked in a session
6
+ */
7
+ declare enum EventType {
8
+ TOOL_CALL = "tool_call",
9
+ LLM_DECISION = "llm_decision",
10
+ STATE_CHANGE = "state_change",
11
+ ERROR = "error"
12
+ }
13
+ /**
14
+ * Session status values
15
+ */
16
+ type SessionStatus = 'running' | 'completed' | 'failed' | 'cancelled';
17
+ /**
18
+ * Configuration options for SentrialClient
19
+ */
20
+ interface SentrialClientConfig {
21
+ /** API key for authentication (defaults to SENTRIAL_API_KEY env var) */
22
+ apiKey?: string;
23
+ /** URL of the Sentrial API server (defaults to SENTRIAL_API_URL env var or production) */
24
+ apiUrl?: string;
25
+ /**
26
+ * If true (default), SDK errors are logged but won't crash your app.
27
+ * Set to false during development to see full errors.
28
+ */
29
+ failSilently?: boolean;
30
+ }
31
+ /**
32
+ * Parameters for creating a new session
33
+ */
34
+ interface CreateSessionParams {
35
+ /** Name of the session */
36
+ name: string;
37
+ /** Identifier for the agent type (used for grouping) */
38
+ agentName: string;
39
+ /** External user ID (for grouping sessions by end-user) */
40
+ userId: string;
41
+ /** Optional metadata */
42
+ metadata?: Record<string, unknown>;
43
+ }
44
+ /**
45
+ * Parameters for completing a session
46
+ */
47
+ interface CompleteSessionParams {
48
+ /** Session ID */
49
+ sessionId: string;
50
+ /** Whether the session successfully completed its goal (default: true) */
51
+ success?: boolean;
52
+ /** If success=false, why did it fail? */
53
+ failureReason?: string;
54
+ /** Total estimated cost in USD for this session */
55
+ estimatedCost?: number;
56
+ /** Custom metrics (e.g., { customer_satisfaction: 4.5, steps_taken: 3 }) */
57
+ customMetrics?: Record<string, number>;
58
+ /** Duration in milliseconds (auto-calculated if not provided) */
59
+ durationMs?: number;
60
+ /** Number of prompt/input tokens used */
61
+ promptTokens?: number;
62
+ /** Number of completion/output tokens used */
63
+ completionTokens?: number;
64
+ /** Total tokens used (prompt + completion) */
65
+ totalTokens?: number;
66
+ /** The user's original query/input for this session */
67
+ userInput?: string;
68
+ /** The final assistant response for this session */
69
+ assistantOutput?: string;
70
+ }
71
+ /**
72
+ * Session data returned from the API
73
+ */
74
+ interface Session {
75
+ id: string;
76
+ agentId?: string;
77
+ name: string;
78
+ agentName: string;
79
+ userId: string;
80
+ status: SessionStatus;
81
+ totalEvents: number;
82
+ userInput?: string;
83
+ assistantOutput?: string;
84
+ success?: boolean;
85
+ failureReason?: string;
86
+ estimatedCost?: number;
87
+ customMetrics?: Record<string, unknown>;
88
+ score?: number;
89
+ metricScores?: Record<string, unknown>;
90
+ metricReasonings?: Record<string, string>;
91
+ promptTokens?: number;
92
+ completionTokens?: number;
93
+ totalTokens?: number;
94
+ durationMs?: number;
95
+ metadata?: Record<string, unknown>;
96
+ createdAt: Date;
97
+ updatedAt: Date;
98
+ completedAt?: Date;
99
+ }
100
+ /**
101
+ * Parameters for tracking a tool call event
102
+ */
103
+ interface TrackToolCallParams {
104
+ /** Session ID */
105
+ sessionId: string;
106
+ /** Name of the tool */
107
+ toolName: string;
108
+ /** Tool input data */
109
+ toolInput: Record<string, unknown>;
110
+ /** Tool output data */
111
+ toolOutput: Record<string, unknown>;
112
+ /** Optional reasoning for why this tool was called */
113
+ reasoning?: string;
114
+ /** Estimated cost in USD for this tool call */
115
+ estimatedCost?: number;
116
+ /** Error details if the tool failed */
117
+ toolError?: Record<string, unknown>;
118
+ /** Number of tokens used by this tool call (for LLM-based tools) */
119
+ tokenCount?: number;
120
+ /** OpenTelemetry trace ID for distributed tracing */
121
+ traceId?: string;
122
+ /** OpenTelemetry span ID for distributed tracing */
123
+ spanId?: string;
124
+ /** Additional metadata */
125
+ metadata?: Record<string, unknown>;
126
+ }
127
+ /**
128
+ * Parameters for tracking an LLM decision event
129
+ */
130
+ interface TrackDecisionParams {
131
+ /** Session ID */
132
+ sessionId: string;
133
+ /** Decision reasoning */
134
+ reasoning: string;
135
+ /** Alternative options considered */
136
+ alternatives?: string[];
137
+ /** Confidence score (0.0 to 1.0) */
138
+ confidence?: number;
139
+ /** Estimated cost in USD for this decision */
140
+ estimatedCost?: number;
141
+ /** Number of tokens used */
142
+ tokenCount?: number;
143
+ /** OpenTelemetry trace ID for distributed tracing */
144
+ traceId?: string;
145
+ /** OpenTelemetry span ID for distributed tracing */
146
+ spanId?: string;
147
+ /** Additional metadata */
148
+ metadata?: Record<string, unknown>;
149
+ }
150
+ /**
151
+ * Parameters for tracking an error event
152
+ */
153
+ interface TrackErrorParams {
154
+ /** Session ID */
155
+ sessionId: string;
156
+ /** Error message */
157
+ errorMessage: string;
158
+ /** Type of error (e.g., "ValueError", "APIError") */
159
+ errorType?: string;
160
+ /** Name of the tool that caused the error (if applicable) */
161
+ toolName?: string;
162
+ /** Stack trace for debugging */
163
+ stackTrace?: string;
164
+ /** OpenTelemetry trace ID for distributed tracing */
165
+ traceId?: string;
166
+ /** OpenTelemetry span ID for distributed tracing */
167
+ spanId?: string;
168
+ /** Additional metadata */
169
+ metadata?: Record<string, unknown>;
170
+ }
171
+ /**
172
+ * Event data returned from the API
173
+ */
174
+ interface Event {
175
+ id: string;
176
+ sessionId: string;
177
+ eventType: EventType;
178
+ timestamp: Date;
179
+ sequenceNumber: number;
180
+ toolName?: string;
181
+ toolInput?: Record<string, unknown>;
182
+ toolOutput?: Record<string, unknown>;
183
+ toolError?: Record<string, unknown>;
184
+ reasoning?: string;
185
+ alternativesConsidered?: string[];
186
+ confidence?: number;
187
+ stateBefore?: Record<string, unknown>;
188
+ stateAfter?: Record<string, unknown>;
189
+ stateDiff?: Record<string, unknown>;
190
+ estimatedCost?: number;
191
+ tokenCount?: number;
192
+ metadata?: Record<string, unknown>;
193
+ traceId?: string;
194
+ spanId?: string;
195
+ }
196
+ /**
197
+ * Parameters for beginning an interaction
198
+ */
199
+ interface BeginParams {
200
+ /** External user ID for grouping sessions */
201
+ userId: string;
202
+ /** Event type/name (e.g., "chat_message", "search_query") */
203
+ event: string;
204
+ /** Optional input data for the interaction */
205
+ input?: string;
206
+ /** Optional custom event ID (auto-generated UUID if not provided) */
207
+ eventId?: string;
208
+ /** Optional conversation ID to group related interactions */
209
+ convoId?: string;
210
+ /** Optional additional metadata */
211
+ metadata?: Record<string, unknown>;
212
+ }
213
+ /**
214
+ * Parameters for finishing an interaction
215
+ */
216
+ interface FinishParams {
217
+ /** Output/response from the interaction */
218
+ output?: string;
219
+ /** Whether the interaction succeeded (default: true) */
220
+ success?: boolean;
221
+ /** Reason for failure if success=false */
222
+ failureReason?: string;
223
+ /** Total estimated cost in USD */
224
+ estimatedCost?: number;
225
+ /** Custom metrics */
226
+ customMetrics?: Record<string, number>;
227
+ /** Number of prompt/input tokens used */
228
+ promptTokens?: number;
229
+ /** Number of completion/output tokens used */
230
+ completionTokens?: number;
231
+ /** Total tokens used */
232
+ totalTokens?: number;
233
+ }
234
+ /**
235
+ * Parameters for cost calculation
236
+ */
237
+ interface CostParams {
238
+ /** Model name (e.g., "gpt-4", "claude-3-sonnet") */
239
+ model: string;
240
+ /** Number of input tokens */
241
+ inputTokens: number;
242
+ /** Number of output tokens */
243
+ outputTokens: number;
244
+ }
245
+ /**
246
+ * Standard API response wrapper
247
+ */
248
+ interface ApiResponse<T> {
249
+ data?: T;
250
+ error?: {
251
+ code: string;
252
+ message: string;
253
+ details?: Record<string, unknown>;
254
+ };
255
+ }
256
+
257
+ /**
258
+ * Cost calculation utilities for various LLM providers
259
+ */
260
+
261
+ /**
262
+ * Calculate cost for OpenAI API calls
263
+ *
264
+ * @param params - Cost calculation parameters
265
+ * @returns Estimated cost in USD
266
+ *
267
+ * @example
268
+ * ```ts
269
+ * const cost = calculateOpenAICost({
270
+ * model: 'gpt-4o',
271
+ * inputTokens: 1000,
272
+ * outputTokens: 500,
273
+ * });
274
+ * console.log(`Cost: $${cost.toFixed(4)}`);
275
+ * ```
276
+ */
277
+ declare function calculateOpenAICost(params: CostParams): number;
278
+ /**
279
+ * Calculate cost for Anthropic API calls
280
+ *
281
+ * @param params - Cost calculation parameters
282
+ * @returns Estimated cost in USD
283
+ *
284
+ * @example
285
+ * ```ts
286
+ * const cost = calculateAnthropicCost({
287
+ * model: 'claude-3-5-sonnet',
288
+ * inputTokens: 1000,
289
+ * outputTokens: 500,
290
+ * });
291
+ * console.log(`Cost: $${cost.toFixed(4)}`);
292
+ * ```
293
+ */
294
+ declare function calculateAnthropicCost(params: CostParams): number;
295
+ /**
296
+ * Calculate cost for Google/Gemini API calls
297
+ *
298
+ * @param params - Cost calculation parameters
299
+ * @returns Estimated cost in USD
300
+ *
301
+ * @example
302
+ * ```ts
303
+ * const cost = calculateGoogleCost({
304
+ * model: 'gemini-2.0-flash',
305
+ * inputTokens: 1000,
306
+ * outputTokens: 500,
307
+ * });
308
+ * console.log(`Cost: $${cost.toFixed(4)}`);
309
+ * ```
310
+ */
311
+ declare function calculateGoogleCost(params: CostParams): number;
312
+
313
+ /**
314
+ * Sentrial Client - Main SDK interface
315
+ *
316
+ * Captures agent sessions, tool calls, and metrics. This data powers:
317
+ * - Signal detection (auto-detect patterns/anomalies)
318
+ * - Root cause analysis (understand WHY agents fail)
319
+ * - Code fixer (AI-suggested fixes with GitHub PRs)
320
+ */
321
+
322
+ /**
323
+ * Sentrial Client for agent observability.
324
+ *
325
+ * Captures the data needed for automated root cause analysis and fix suggestions.
326
+ *
327
+ * @example
328
+ * ```ts
329
+ * const client = new SentrialClient({
330
+ * apiKey: 'sentrial_live_xxx',
331
+ * apiUrl: 'https://api.sentrial.com',
332
+ * });
333
+ *
334
+ * // Create a session for an agent run
335
+ * const sessionId = await client.createSession({
336
+ * name: 'Support Request #123',
337
+ * agentName: 'support-agent',
338
+ * userId: 'user_123',
339
+ * });
340
+ *
341
+ * // Track events
342
+ * await client.trackToolCall({
343
+ * sessionId,
344
+ * toolName: 'search_kb',
345
+ * toolInput: { query: 'password reset' },
346
+ * toolOutput: { articles: ['KB-001'] },
347
+ * });
348
+ *
349
+ * // Complete session with metrics
350
+ * await client.completeSession({
351
+ * sessionId,
352
+ * success: true,
353
+ * customMetrics: { customer_satisfaction: 90 },
354
+ * });
355
+ * ```
356
+ *
357
+ * @remarks
358
+ * By default, the SDK fails silently (failSilently=true) to ensure
359
+ * monitoring never crashes your application. Set failSilently=false
360
+ * during development to see errors.
361
+ */
362
+ declare class SentrialClient {
363
+ private readonly apiUrl;
364
+ private readonly apiKey?;
365
+ private readonly failSilently;
366
+ private currentState;
367
+ constructor(config?: SentrialClientConfig);
368
+ /**
369
+ * Make an HTTP request with graceful error handling
370
+ */
371
+ private safeRequest;
372
+ /**
373
+ * Create a new session
374
+ *
375
+ * @param params - Session creation parameters
376
+ * @returns Session ID, or null if the request failed and failSilently is true
377
+ */
378
+ createSession(params: CreateSessionParams): Promise<string | null>;
379
+ /**
380
+ * Track a tool call event
381
+ *
382
+ * @param params - Tool call parameters
383
+ * @returns Event data
384
+ */
385
+ trackToolCall(params: TrackToolCallParams): Promise<Event | null>;
386
+ /**
387
+ * Track an LLM decision event
388
+ *
389
+ * @param params - Decision parameters
390
+ * @returns Event data
391
+ */
392
+ trackDecision(params: TrackDecisionParams): Promise<Event | null>;
393
+ /**
394
+ * Track an error event
395
+ *
396
+ * @param params - Error parameters
397
+ * @returns Event data
398
+ */
399
+ trackError(params: TrackErrorParams): Promise<Event | null>;
400
+ /**
401
+ * Update the current state
402
+ *
403
+ * @param key - State key
404
+ * @param value - State value
405
+ */
406
+ updateState(key: string, value: unknown): void;
407
+ /**
408
+ * Complete a session with performance metrics
409
+ *
410
+ * This is the recommended way to close sessions for performance monitoring.
411
+ *
412
+ * @param params - Session completion parameters
413
+ * @returns Updated session data
414
+ *
415
+ * @example
416
+ * ```ts
417
+ * await client.completeSession({
418
+ * sessionId,
419
+ * success: true,
420
+ * estimatedCost: 0.023,
421
+ * promptTokens: 1500,
422
+ * completionTokens: 500,
423
+ * totalTokens: 2000,
424
+ * userInput: "What's the weather in San Francisco?",
425
+ * assistantOutput: "The weather in San Francisco is 65°F and sunny.",
426
+ * customMetrics: {
427
+ * customer_satisfaction: 4.5,
428
+ * order_value: 129.99,
429
+ * },
430
+ * });
431
+ * ```
432
+ */
433
+ completeSession(params: CompleteSessionParams): Promise<Session | null>;
434
+ /**
435
+ * Begin tracking an interaction (simplified API)
436
+ *
437
+ * @param params - Interaction parameters
438
+ * @returns Interaction object with finish() method
439
+ *
440
+ * @example
441
+ * ```ts
442
+ * const interaction = await client.begin({
443
+ * userId: 'user_123',
444
+ * event: 'chat_message',
445
+ * input: message,
446
+ * convoId: 'convo_456',
447
+ * });
448
+ *
449
+ * // ... do your agent work ...
450
+ *
451
+ * await interaction.finish({ output: responseText });
452
+ * ```
453
+ */
454
+ begin(params: BeginParams): Promise<Interaction>;
455
+ static calculateOpenAICost: typeof calculateOpenAICost;
456
+ static calculateAnthropicCost: typeof calculateAnthropicCost;
457
+ static calculateGoogleCost: typeof calculateGoogleCost;
458
+ }
459
+ interface InteractionConfig {
460
+ client: SentrialClient;
461
+ sessionId: string | null;
462
+ eventId: string;
463
+ userId: string;
464
+ event: string;
465
+ }
466
+ /**
467
+ * Represents an in-progress interaction that can be finished.
468
+ *
469
+ * Created by SentrialClient.begin() - provides a clean begin/finish API pattern.
470
+ *
471
+ * @remarks
472
+ * If session creation failed (sessionId is null), all tracking methods
473
+ * become no-ops to ensure your application continues running.
474
+ */
475
+ declare class Interaction {
476
+ private readonly client;
477
+ private readonly sessionId;
478
+ /** Event ID for this interaction */
479
+ readonly eventId: string;
480
+ /** User ID for this interaction */
481
+ readonly userId: string;
482
+ /** Event name for this interaction */
483
+ readonly event: string;
484
+ private finished;
485
+ private success;
486
+ private failureReason?;
487
+ private output?;
488
+ private readonly degraded;
489
+ constructor(config: InteractionConfig);
490
+ /**
491
+ * Set the output for this interaction
492
+ *
493
+ * This will be used when finish() is called.
494
+ * Useful when you want to set the output but call finish() later.
495
+ *
496
+ * @param output - The output/response text
497
+ */
498
+ setOutput(output: string): void;
499
+ /**
500
+ * Finish the interaction and record metrics
501
+ *
502
+ * @param params - Finish parameters
503
+ * @returns Updated session data, or null if degraded/already finished
504
+ *
505
+ * @example
506
+ * ```ts
507
+ * await interaction.finish({
508
+ * output: "Here's the answer to your question...",
509
+ * success: true,
510
+ * customMetrics: { satisfaction: 4.5 },
511
+ * });
512
+ * ```
513
+ */
514
+ finish(params?: FinishParams): Promise<Session | null>;
515
+ /**
516
+ * Track a tool call within this interaction
517
+ */
518
+ trackToolCall(params: Omit<TrackToolCallParams, 'sessionId'>): Promise<Event | null>;
519
+ /**
520
+ * Track an LLM decision within this interaction
521
+ */
522
+ trackDecision(params: Omit<TrackDecisionParams, 'sessionId'>): Promise<Event | null>;
523
+ /**
524
+ * Track an error within this interaction
525
+ */
526
+ trackError(params: Omit<TrackErrorParams, 'sessionId'>): Promise<Event | null>;
527
+ /**
528
+ * Get the session ID (null if session creation failed)
529
+ */
530
+ getSessionId(): string | null;
531
+ /**
532
+ * Check if the interaction is in a degraded state (session creation failed)
533
+ */
534
+ isDegraded(): boolean;
535
+ }
536
+ /**
537
+ * Configure the default Sentrial client
538
+ *
539
+ * @param config - Client configuration
540
+ *
541
+ * @example
542
+ * ```ts
543
+ * import { sentrial } from '@sentrial/sdk';
544
+ *
545
+ * sentrial.configure({
546
+ * apiKey: 'sentrial_live_xxx',
547
+ * apiUrl: 'https://api.sentrial.com',
548
+ * });
549
+ * ```
550
+ */
551
+ declare function configure(config: SentrialClientConfig): void;
552
+ /**
553
+ * Begin tracking an interaction (module-level convenience function)
554
+ *
555
+ * This is a shorthand for new SentrialClient().begin(...).
556
+ * Configure the client first with sentrial.configure() or set SENTRIAL_API_KEY env var.
557
+ *
558
+ * @param params - Interaction parameters
559
+ * @returns Interaction object with finish() method
560
+ *
561
+ * @example
562
+ * ```ts
563
+ * import { sentrial } from '@sentrial/sdk';
564
+ *
565
+ * sentrial.configure({ apiKey: 'sentrial_live_xxx' });
566
+ *
567
+ * const interaction = await sentrial.begin({
568
+ * userId: 'user_123',
569
+ * event: 'chat_message',
570
+ * input: message,
571
+ * });
572
+ *
573
+ * // ... do your agent work ...
574
+ *
575
+ * await interaction.finish({ output: responseText });
576
+ * ```
577
+ */
578
+ declare function begin(params: BeginParams): Promise<Interaction>;
579
+ /**
580
+ * Simple API namespace for module-level usage
581
+ */
582
+ declare const sentrial: {
583
+ configure: typeof configure;
584
+ begin: typeof begin;
585
+ };
586
+
587
+ /**
588
+ * Error classes for the Sentrial SDK
589
+ */
590
+ /**
591
+ * Base error class for all Sentrial SDK errors
592
+ */
593
+ declare class SentrialError extends Error {
594
+ /** HTTP status code (if applicable) */
595
+ readonly status?: number;
596
+ /** Error code from the API */
597
+ readonly code?: string;
598
+ /** Additional error details */
599
+ readonly details?: Record<string, unknown>;
600
+ constructor(message: string, options?: {
601
+ status?: number;
602
+ code?: string;
603
+ details?: Record<string, unknown>;
604
+ cause?: Error;
605
+ });
606
+ /**
607
+ * Check if the error is a rate limit error
608
+ */
609
+ isRateLimitError(): boolean;
610
+ /**
611
+ * Check if the error is an authentication error
612
+ */
613
+ isAuthError(): boolean;
614
+ /**
615
+ * Check if the error is a network/connection error
616
+ */
617
+ isNetworkError(): boolean;
618
+ /**
619
+ * Convert to a plain object for logging
620
+ */
621
+ toJSON(): Record<string, unknown>;
622
+ }
623
+ /**
624
+ * Error thrown when the API returns an error response
625
+ */
626
+ declare class ApiError extends SentrialError {
627
+ constructor(message: string, status: number, code?: string, details?: Record<string, unknown>);
628
+ }
629
+ /**
630
+ * Error thrown when there's a network/connection issue
631
+ */
632
+ declare class NetworkError extends SentrialError {
633
+ constructor(message: string, cause?: Error);
634
+ }
635
+ /**
636
+ * Error thrown when validation fails
637
+ */
638
+ declare class ValidationError extends SentrialError {
639
+ constructor(message: string, details?: Record<string, unknown>);
640
+ }
641
+
642
+ export { ApiError, type ApiResponse, type BeginParams, type CompleteSessionParams, type CostParams, type CreateSessionParams, type Event, EventType, type FinishParams, Interaction, NetworkError, SentrialClient, type SentrialClientConfig, SentrialError, type Session, type SessionStatus, type TrackDecisionParams, type TrackErrorParams, type TrackToolCallParams, ValidationError, begin, calculateAnthropicCost, calculateGoogleCost, calculateOpenAICost, configure, sentrial };