@thaliq/sdk 1.0.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,49 @@
1
+ /**
2
+ * @thaliq/sdk - Error Types
3
+ * @module types/errors
4
+ */
5
+ /**
6
+ * SDK error codes used in `ThaliqError.code`.
7
+ * Use these to programmatically distinguish error types.
8
+ */
9
+ export type ErrorCode = 'AUTH_ERROR' | 'RATE_LIMIT' | 'VALIDATION_ERROR' | 'SERVICE_ERROR' | 'STREAM_ERROR' | 'TIMEOUT_ERROR' | 'CONNECTION_ERROR' | 'UNKNOWN_ERROR';
10
+ /** Base error class for all SDK errors */
11
+ export declare class ThaliqError extends Error {
12
+ readonly code: ErrorCode;
13
+ readonly status?: number;
14
+ constructor(message: string, code: ErrorCode, status?: number);
15
+ }
16
+ /** Authentication or authorization error (401/403) */
17
+ export declare class AuthError extends ThaliqError {
18
+ constructor(message: string, status?: number);
19
+ }
20
+ /** Rate limit exceeded (429) */
21
+ export declare class RateLimitError extends ThaliqError {
22
+ readonly retryAfter: number;
23
+ constructor(message: string, retryAfter?: number);
24
+ }
25
+ /** Request validation error (400) */
26
+ export declare class ValidationError extends ThaliqError {
27
+ constructor(message: string);
28
+ }
29
+ /** Service unavailable (503) */
30
+ export declare class ServiceError extends ThaliqError {
31
+ constructor(message: string);
32
+ }
33
+ /** Error during SSE streaming */
34
+ export declare class StreamError extends ThaliqError {
35
+ constructor(message: string);
36
+ }
37
+ /** Request timeout */
38
+ export declare class TimeoutError extends ThaliqError {
39
+ constructor(message?: string);
40
+ }
41
+ /** Network/connection error */
42
+ export declare class ConnectionError extends ThaliqError {
43
+ constructor(message?: string);
44
+ }
45
+ /**
46
+ * Maps an HTTP status code to the appropriate ThaliqError subclass.
47
+ * Used internally by the HTTP client; also useful for custom providers.
48
+ */
49
+ export declare function mapHttpError(status: number, message: string, headers?: Headers): ThaliqError;
@@ -0,0 +1,70 @@
1
+ import { PendingAction } from './actions';
2
+ import { Insight, ResponseMetadata } from './responses';
3
+ /** Metadata event — sent first, carries the conversation ID */
4
+ export interface MetaEvent {
5
+ type: 'meta';
6
+ conversationId: string;
7
+ }
8
+ /** Status update — shows progress text (e.g. "Thinking...") */
9
+ export interface StatusEvent {
10
+ type: 'status';
11
+ text: string;
12
+ }
13
+ /** Content delta — incremental text chunk */
14
+ export interface ContentDeltaEvent {
15
+ type: 'content.delta';
16
+ delta: string;
17
+ }
18
+ /** Tool execution started */
19
+ export interface ToolStartEvent {
20
+ type: 'tool.start';
21
+ tool: string;
22
+ }
23
+ /** Tool execution ended */
24
+ export interface ToolEndEvent {
25
+ type: 'tool.end';
26
+ tool: string;
27
+ success: boolean;
28
+ }
29
+ /** Action required — HITL event, stream pauses until user responds */
30
+ export interface ActionEvent {
31
+ type: 'action';
32
+ action: PendingAction;
33
+ }
34
+ /** Stream completed — final event with full response data */
35
+ export interface ResponseCompletedEvent {
36
+ type: 'response.completed';
37
+ message: string;
38
+ conversationId: string;
39
+ insights: Insight[];
40
+ metadata: ResponseMetadata;
41
+ }
42
+ /** Error during streaming */
43
+ export interface ErrorEvent {
44
+ type: 'error';
45
+ message: string;
46
+ }
47
+ /** Keepalive ping — sent periodically to keep connection open */
48
+ export interface KeepaliveEvent {
49
+ type: 'keepalive';
50
+ ts: number;
51
+ }
52
+ /**
53
+ * Discriminated union of all possible stream events.
54
+ * Use `event.type` in a switch statement for type narrowing.
55
+ *
56
+ * @example
57
+ * ```typescript
58
+ * for await (const event of stream) {
59
+ * switch (event.type) {
60
+ * case 'content.delta':
61
+ * process.stdout.write(event.delta);
62
+ * break;
63
+ * case 'tool.start':
64
+ * console.log(`Running: ${event.tool}`);
65
+ * break;
66
+ * }
67
+ * }
68
+ * ```
69
+ */
70
+ export type StreamEvent = MetaEvent | StatusEvent | ContentDeltaEvent | ToolStartEvent | ToolEndEvent | ActionEvent | ResponseCompletedEvent | ErrorEvent | KeepaliveEvent;
@@ -0,0 +1,21 @@
1
+ /**
2
+ * @thaliq/sdk - Identity Types
3
+ * @module types/identity
4
+ */
5
+ /** User identity for authenticated B2B scenarios */
6
+ export interface UserIdentity {
7
+ /** Unique user ID in the tenant's system */
8
+ userId: string;
9
+ /** User email (optional, for display/tracking) */
10
+ email?: string;
11
+ /** User display name (optional) */
12
+ name?: string;
13
+ /** JWT or bearer token (passthrough for MCP servers) */
14
+ token?: string;
15
+ /** Per-MCP-server tokens: { "server-id": "token" } */
16
+ mcpTokens?: Record<string, string>;
17
+ /** Participant ID for conversation tracking */
18
+ participantId?: string;
19
+ /** Arbitrary metadata attached to requests */
20
+ metadata?: Record<string, unknown>;
21
+ }
@@ -0,0 +1,13 @@
1
+ /**
2
+ * @thaliq/sdk - Type Exports
3
+ */
4
+ export type { ThaliqConfig, ResolvedConfig, Logger, LogLevel, } from './config';
5
+ export type { UserIdentity, } from './identity';
6
+ export type { ActionType, RejectBehavior, FieldType, ActionOption, ActionField, PendingAction, ActionResponse, } from './actions';
7
+ export type { InsightSeverity, InsightType, Insight, ResponseMetadata, ChatResponse, } from './responses';
8
+ export type { StreamEvent, MetaEvent, StatusEvent, ContentDeltaEvent, ToolStartEvent, ToolEndEvent, ActionEvent, ResponseCompletedEvent, ErrorEvent, KeepaliveEvent, } from './events';
9
+ export type { AgentType, ChatOptions, StreamOptions, AgentStream, } from './agent';
10
+ export type { ConversationRef, } from './conversations';
11
+ export type { ErrorCode, } from './errors';
12
+ export { ThaliqError, AuthError, RateLimitError, ValidationError, ServiceError, StreamError, TimeoutError, ConnectionError, mapHttpError, } from './errors';
13
+ export type { Provider, ProviderRequest, ResolvedHeaders, } from './provider';
@@ -0,0 +1,52 @@
1
+ import { ActionResponse } from './actions';
2
+ import { AgentType } from './agent';
3
+ import { StreamEvent } from './events';
4
+ import { ChatResponse } from './responses';
5
+ /** Resolved headers ready to be sent with the request */
6
+ export interface ResolvedHeaders {
7
+ /** API Key header */
8
+ 'x-api-key': string;
9
+ /** Integration type */
10
+ 'x-integration-type': string;
11
+ /** User ID (optional) */
12
+ 'x-user-id'?: string;
13
+ /** Participant ID (optional) */
14
+ 'x-participant-id'?: string;
15
+ /** Authorization bearer token (optional) */
16
+ authorization?: string;
17
+ /** MCP tokens JSON (optional) */
18
+ 'x-mcp-tokens'?: string;
19
+ /** Any additional custom headers */
20
+ [key: string]: string | undefined;
21
+ }
22
+ /** Request object passed to the provider */
23
+ export interface ProviderRequest {
24
+ /** User message */
25
+ message: string;
26
+ /** Conversation ID (optional) */
27
+ conversationId?: string;
28
+ /** Agent type */
29
+ agentType?: AgentType;
30
+ /** Response to a pending action */
31
+ actionResponse?: ActionResponse;
32
+ /** Resolved headers */
33
+ headers: ResolvedHeaders;
34
+ /** AbortSignal */
35
+ signal?: AbortSignal;
36
+ /** Request timeout in ms */
37
+ timeout: number;
38
+ }
39
+ /**
40
+ * Provider interface — the core abstraction for backend communication.
41
+ *
42
+ * Implement this interface to connect the SDK to any AI backend.
43
+ * The SDK ships with `ThaliqNativeProvider` as the default.
44
+ */
45
+ export interface Provider {
46
+ /** Unique name of the provider */
47
+ readonly name: string;
48
+ /** Send a message and return the complete response */
49
+ chat(request: ProviderRequest): Promise<ChatResponse>;
50
+ /** Send a message and return a stream of events */
51
+ stream(request: ProviderRequest): AsyncIterable<StreamEvent>;
52
+ }
@@ -0,0 +1,48 @@
1
+ import { PendingAction } from './actions';
2
+ /** Insight severity levels, from informational to critical. */
3
+ export type InsightSeverity = 'low' | 'medium' | 'high' | 'critical';
4
+ /** Categories of insights the agent can extract from a conversation. */
5
+ export type InsightType = 'warning' | 'opportunity' | 'info' | 'achievement';
6
+ /** An insight extracted from the agent's response */
7
+ export interface Insight {
8
+ /** Type of insight */
9
+ type: InsightType;
10
+ /** Severity level */
11
+ severity: InsightSeverity;
12
+ /** Short title */
13
+ title: string;
14
+ /** Detailed description */
15
+ description: string;
16
+ /** Optional category */
17
+ category?: string;
18
+ /** Optional amount (for financial insights) */
19
+ amount?: string;
20
+ }
21
+ /** Metadata about the response */
22
+ export interface ResponseMetadata {
23
+ /** Conversation ID */
24
+ conversationId: string;
25
+ /** Model used for generation */
26
+ model: string;
27
+ /** Number of input/prompt tokens */
28
+ promptTokens: number;
29
+ /** Number of output/completion tokens */
30
+ completionTokens: number;
31
+ /** Total processing time in ms */
32
+ processingTimeMs: number;
33
+ /** ISO timestamp of generation */
34
+ generatedAt: string;
35
+ }
36
+ /** Complete chat response (non-streaming or accumulated) */
37
+ export interface ChatResponse {
38
+ /** The agent's text response */
39
+ message: string;
40
+ /** Conversation ID */
41
+ conversationId: string;
42
+ /** Extracted insights */
43
+ insights: Insight[];
44
+ /** Response metadata */
45
+ metadata: ResponseMetadata;
46
+ /** Pending action if HITL is required */
47
+ action?: PendingAction;
48
+ }
@@ -0,0 +1,29 @@
1
+ import { ActionResponse } from '../types/actions';
2
+ export declare class ActionResponseBuilder {
3
+ /**
4
+ * Accept a consent or confirm action.
5
+ *
6
+ * @param instructionId - The instruction ID from `pendingAction.instructionId`
7
+ */
8
+ static accept(instructionId: string): ActionResponse;
9
+ /**
10
+ * Reject a consent or confirm action.
11
+ *
12
+ * @param instructionId - The instruction ID from `pendingAction.instructionId`
13
+ */
14
+ static reject(instructionId: string): ActionResponse;
15
+ /**
16
+ * Select an option from a select action.
17
+ *
18
+ * @param instructionId - The instruction ID from `pendingAction.instructionId`
19
+ * @param value - The selected option value
20
+ */
21
+ static select(instructionId: string, value: string): ActionResponse;
22
+ /**
23
+ * Submit form values for a form action.
24
+ *
25
+ * @param instructionId - The instruction ID from `pendingAction.instructionId`
26
+ * @param values - Key-value map of form field names to values
27
+ */
28
+ static submitForm(instructionId: string, values: Record<string, string>): ActionResponse;
29
+ }
@@ -0,0 +1,30 @@
1
+ /**
2
+ * Typed EventEmitter — zero-dependency, type-safe event system.
3
+ *
4
+ * @example
5
+ * ```typescript
6
+ * const emitter = new TypedEventEmitter<SDKEventMap>();
7
+ * emitter.on('error', (err) => console.error(err));
8
+ * emitter.once('identify', (userId) => console.log('Identified:', userId));
9
+ * ```
10
+ */
11
+ /** Callback function type */
12
+ type Callback = (...args: any[]) => void;
13
+ export declare class TypedEventEmitter<T extends {
14
+ [K in keyof T]: Callback;
15
+ }> {
16
+ private readonly _listeners;
17
+ /** Register a listener for an event */
18
+ on<K extends keyof T>(event: K, listener: T[K]): this;
19
+ /** Register a one-time listener */
20
+ once<K extends keyof T>(event: K, listener: T[K]): this;
21
+ /** Remove a listener */
22
+ off<K extends keyof T>(event: K, listener: T[K]): this;
23
+ /** Emit an event to all registered listeners */
24
+ emit<K extends keyof T>(event: K, ...args: Parameters<T[K]>): void;
25
+ /** Remove all listeners for an event, or all listeners if no event specified */
26
+ removeAllListeners(event?: keyof T): this;
27
+ /** Get the count of listeners for a specific event */
28
+ listenerCount(event: keyof T): number;
29
+ }
30
+ export {};
@@ -0,0 +1,2 @@
1
+ import { Logger, LogLevel } from '../types/config';
2
+ export declare function createDefaultLogger(minLevel: LogLevel): Logger;
@@ -0,0 +1,32 @@
1
+ import { ResolvedRetryConfig, Logger } from '../types/config';
2
+ import { ThaliqError } from '../types/errors';
3
+ /**
4
+ * Check if an error is retryable.
5
+ * Returns `true` for server errors (5xx), timeouts, and connection errors.
6
+ * Returns `false` for auth errors (401/403), validation (400), and rate limits (429).
7
+ */
8
+ export declare function isRetryableError(error: unknown): boolean;
9
+ /**
10
+ * Calculate the retry delay with exponential backoff and jitter.
11
+ * Formula: `min(baseDelay * 2^attempt, maxDelay) + random(0..50%)`.
12
+ */
13
+ export declare function calculateBackoff(attempt: number, baseDelay: number, maxDelay: number): number;
14
+ /** Options for the retry wrapper */
15
+ export interface RetryOptions {
16
+ config: ResolvedRetryConfig;
17
+ logger: Logger;
18
+ /** Called before each retry attempt */
19
+ onRetry?: (attempt: number, error: ThaliqError, delayMs: number) => void;
20
+ /** AbortSignal to cancel retries */
21
+ signal?: AbortSignal;
22
+ }
23
+ /**
24
+ * Execute an async function with automatic retry on retryable errors.
25
+ * Uses exponential backoff with jitter between attempts.
26
+ *
27
+ * @param fn - The async function to execute (and potentially retry)
28
+ * @param options - Retry configuration, logger, and optional callbacks
29
+ * @returns The result of `fn()` on success
30
+ * @throws The last error after all retries are exhausted
31
+ */
32
+ export declare function withRetry<T>(fn: () => Promise<T>, options: RetryOptions): Promise<T>;
@@ -0,0 +1,5 @@
1
+ /**
2
+ * Generate a UUID v4 using crypto.randomUUID when available,
3
+ * falling back to a manual implementation.
4
+ */
5
+ export declare function uuid(): string;