@cadraos/sdk 0.1.3 → 0.1.5

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.
@@ -1,256 +1,28 @@
1
1
  import * as react_jsx_runtime from 'react/jsx-runtime';
2
- import * as React from 'react';
2
+ import { Components } from 'react-markdown';
3
+ import * as React$1 from 'react';
3
4
 
4
- /**
5
- * ChatAdapter interface for customizable API integration
6
- *
7
- * Implement this interface to:
8
- * - Connect to different backends
9
- * - Use direct DB access (in ai-saas-v2)
10
- * - Mock for testing
11
- *
12
- * @module @cadraos/sdk/chat
13
- */
14
- /**
15
- * Input for starting an agent execution
16
- */
17
- interface StartExecutionInput {
18
- /** UUID of the agent to execute */
19
- agentId: string;
20
- /** Optional session ID for continuing a conversation */
21
- sessionId?: string;
22
- /** User message content */
23
- content: string;
24
- /** UUIDs of attached files */
25
- attachmentUuids?: string[];
26
- }
27
- /**
28
- * Input for sending a message in an existing session
29
- */
30
- interface SendMessageInput {
31
- /** Session ID */
32
- sessionId: string;
33
- /** Message content */
34
- content: string;
35
- /** UUIDs of attached files */
36
- attachmentUuids?: string[];
37
- }
38
- /**
39
- * Input for getting an upload URL
40
- */
41
- interface UploadUrlInput {
42
- /** Session ID */
43
- sessionId: string;
44
- /** Filename */
45
- filename: string;
46
- /** MIME type */
47
- mimeType: string;
48
- /** File size in bytes */
49
- size: number;
50
- }
51
- /**
52
- * Result from starting an execution
53
- */
54
- interface ExecutionResult {
55
- /** UUID of the created execution */
56
- executionId: string;
57
- /** UUID of the session (new or existing) */
58
- sessionId: string;
59
- }
60
- /**
61
- * Result from getting an upload URL
62
- */
63
- interface UploadUrlResult {
64
- /** Pre-signed upload URL */
65
- uploadUrl: string;
66
- /** UUID for the attachment */
67
- attachmentUuid: string;
68
- }
69
- /**
70
- * Execution status and result
71
- */
72
- interface Execution {
73
- /** Execution UUID */
74
- uuid: string;
75
- /** Current status */
76
- status: "pending" | "running" | "completed" | "failed" | "cancelled";
77
- /** Final result (when completed) */
78
- result?: string;
79
- /** Error message (when failed) */
80
- error?: string;
81
- }
82
- /**
83
- * Artifact generated during execution
84
- */
85
- interface Artifact {
86
- /** Artifact UUID */
87
- uuid: string;
88
- /** Artifact type */
89
- type: "image" | "document" | "code" | "audio";
90
- /** Filename */
91
- filename: string;
92
- /** MIME type */
93
- mimeType: string;
94
- /** Download URL */
95
- url: string;
96
- }
97
- /**
98
- * Attachment metadata for history messages
99
- */
100
- interface HistoryAttachment {
101
- /** Attachment UUID */
102
- uuid: string;
103
- /** Original filename */
104
- filename: string;
105
- /** MIME type */
106
- mimeType: string;
107
- /** File size in bytes */
108
- size: number;
109
- /** Category classification */
110
- category: "document" | "image" | "audio";
111
- /** Preview URL (for images) */
112
- previewUrl?: string;
113
- /** Thumbnail URL */
114
- thumbnailUrl?: string;
115
- }
116
- /**
117
- * Tool call data for history messages
118
- */
119
- interface HistoryToolCall {
120
- /** Tool call ID */
121
- id: string;
122
- /** Tool name */
123
- name: string;
124
- /** Tool arguments */
125
- args?: Record<string, unknown>;
126
- /** Tool result */
127
- result?: unknown;
128
- /** Execution status */
129
- status: "pending" | "running" | "completed" | "failed";
130
- /** Execution duration in ms */
131
- durationMs?: number;
132
- }
133
- /**
134
- * A message in the session history
135
- */
136
- interface HistoryMessage {
137
- /** Message UUID */
138
- uuid: string;
139
- /** Message role */
140
- role: "user" | "assistant";
141
- /** Message content */
5
+ interface MarkdownContentProps {
6
+ /** Markdown content to render */
142
7
  content: string;
143
- /** Message timestamp */
144
- timestamp: string;
145
- /** File attachments (for user messages) */
146
- attachments?: HistoryAttachment[];
147
- /** Tool calls (for assistant messages) */
148
- toolCalls?: HistoryToolCall[];
149
- }
150
- /**
151
- * Session with chat history
152
- */
153
- interface SessionHistory {
154
- /** Session UUID */
155
- sessionId: string;
156
- /** Agent UUID */
157
- agentId: string;
158
- /** Messages in chronological order */
159
- messages: HistoryMessage[];
160
- /** When the session was created */
161
- createdAt: string;
162
- /** When the session was last updated */
163
- updatedAt: string;
8
+ /** Additional CSS classes */
9
+ className?: string;
10
+ /** Custom React-Markdown component overrides (merged with defaults, user wins) */
11
+ components?: Partial<Components>;
12
+ /** Custom URL transform for React-Markdown (e.g., to preserve custom protocols like artifact:) */
13
+ urlTransform?: (url: string) => string;
14
+ /** Transform content string before rendering (e.g., strip certain patterns) */
15
+ contentTransform?: (content: string) => string;
164
16
  }
165
17
  /**
166
- * ChatAdapter interface for API integration
167
- *
168
- * This interface decouples the UI from the API implementation,
169
- * allowing:
170
- * - Built-in HTTP adapter for external API consumers
171
- * - Custom adapter for ai-saas-v2 (direct tRPC/DB access)
172
- * - Testing with mock adapters
18
+ * Renders markdown content with chat-appropriate styling
173
19
  *
174
20
  * @example
175
- * ```typescript
176
- * // Using default HTTP adapter
177
- * const adapter = createDefaultAdapter({
178
- * baseUrl: 'https://api.example.com/api/v1/external',
179
- * apiKey: 'your-api-key',
180
- * orgId: 123,
181
- * });
182
- *
183
- * // Using custom tRPC adapter
184
- * const adapter: ChatAdapter = {
185
- * startExecution: (input) => api.agents.execute.mutate(input),
186
- * // ... other methods
187
- * };
21
+ * ```tsx
22
+ * <MarkdownContent content="# Hello\n\nThis is **bold** text." />
188
23
  * ```
189
24
  */
190
- interface ChatAdapter {
191
- /**
192
- * Start a new agent execution
193
- * @param input - Execution input
194
- * @returns Execution and session IDs
195
- */
196
- startExecution(input: StartExecutionInput): Promise<ExecutionResult>;
197
- /**
198
- * Send a message in an existing session
199
- * @param input - Message input
200
- * @returns Execution and session IDs
201
- */
202
- sendMessage(input: SendMessageInput): Promise<ExecutionResult>;
203
- /**
204
- * Cancel a running execution
205
- * @param uuid - Execution UUID
206
- */
207
- cancelExecution(uuid: string): Promise<void>;
208
- /**
209
- * Get execution status and result
210
- * @param uuid - Execution UUID
211
- * @returns Execution details
212
- */
213
- getExecution(uuid: string): Promise<Execution>;
214
- /**
215
- * Get a pre-signed URL for uploading a file
216
- * @param input - Upload URL input
217
- * @returns Upload URL and attachment UUID
218
- */
219
- getUploadUrl(input: UploadUrlInput): Promise<UploadUrlResult>;
220
- /**
221
- * Confirm that a file upload has completed
222
- * @param uuid - Attachment UUID
223
- */
224
- confirmUpload(uuid: string): Promise<void>;
225
- /**
226
- * Get a download URL for an attachment
227
- * @param uuid - Attachment UUID
228
- * @returns Signed download URL
229
- */
230
- getDownloadUrl(uuid: string): Promise<string>;
231
- /**
232
- * Get artifacts generated in a session
233
- * @param sessionId - Session UUID
234
- * @returns List of artifacts
235
- */
236
- getSessionArtifacts?(sessionId: string): Promise<Artifact[]>;
237
- /**
238
- * Load chat history for an existing session
239
- *
240
- * This method is optional. If not implemented, session loading will not be available.
241
- * The returned data is designed to be cacheable with React Query, SWR, or Next.js caching.
242
- *
243
- * @param sessionId - Session UUID
244
- * @returns Session with message history
245
- */
246
- getSessionHistory?(sessionId: string): Promise<SessionHistory>;
247
- /**
248
- * Get the SSE stream URL for an execution
249
- * @param executionId - Execution UUID
250
- * @returns Full URL for SSE connection
251
- */
252
- getStreamUrl(executionId: string): string;
253
- }
25
+ declare function MarkdownContent({ content, className, components: customComponents, urlTransform, contentTransform, }: MarkdownContentProps): react_jsx_runtime.JSX.Element;
254
26
 
255
27
  /**
256
28
  * Type definitions for @cadraos/sdk/chat
@@ -332,168 +104,2569 @@ interface ThinkingBlock {
332
104
  /**
333
105
  * Chat error information
334
106
  */
335
- interface ChatError {
336
- /** Error code for programmatic handling */
337
- code: string;
338
- /** Human-readable error message */
339
- message: string;
340
- /** Additional error details */
341
- details?: Record<string, unknown>;
342
- /** Whether the error is retryable */
343
- retryable?: boolean;
344
- }
107
+ interface ChatError {
108
+ /** Error code for programmatic handling */
109
+ code: string;
110
+ /** Human-readable error message */
111
+ message: string;
112
+ /** Additional error details */
113
+ details?: Record<string, unknown>;
114
+ /** Whether the error is retryable */
115
+ retryable?: boolean;
116
+ }
117
+ /**
118
+ * Data for agent clarification requests (ask_user tool)
119
+ */
120
+ interface ClarificationData {
121
+ /** The question being asked */
122
+ question: string;
123
+ /** Optional reason for asking */
124
+ reason?: string;
125
+ /** Suggested response options */
126
+ suggestedOptions?: string[];
127
+ }
128
+ /**
129
+ * Todo item for agent task lists
130
+ */
131
+ interface TodoItem {
132
+ /** Task description (imperative form) */
133
+ content: string;
134
+ /** Current status */
135
+ status: "pending" | "in_progress" | "completed";
136
+ /** Present continuous form for active display */
137
+ activeForm: string;
138
+ }
139
+ /**
140
+ * SSE stream event from agent execution
141
+ */
142
+ interface ExecutionStreamEvent {
143
+ /** Event type */
144
+ type: string;
145
+ /** Unique event ID for deduplication */
146
+ id: string;
147
+ /** ISO timestamp */
148
+ timestamp: string;
149
+ /** Event data payload */
150
+ data: {
151
+ type?: string;
152
+ log?: {
153
+ stepIndex: number;
154
+ logType: string;
155
+ message: string;
156
+ metadata: Record<string, unknown>;
157
+ timestamp: string;
158
+ durationMs?: number;
159
+ };
160
+ executionId?: string;
161
+ toolName?: string;
162
+ args?: unknown;
163
+ iteration?: number;
164
+ tokenUsage?: {
165
+ prompt: number;
166
+ completion: number;
167
+ total: number;
168
+ };
169
+ cost?: number;
170
+ error?: string;
171
+ question?: string;
172
+ reason?: string;
173
+ suggestedOptions?: string[];
174
+ redisAvailable?: boolean;
175
+ [key: string]: unknown;
176
+ };
177
+ }
178
+ /**
179
+ * Theme mode options
180
+ */
181
+ type ThemeMode = "light" | "dark" | "system";
182
+ /**
183
+ * Attachment file for upload
184
+ */
185
+ interface AttachmentFile {
186
+ /** File UUID after upload */
187
+ uuid: string;
188
+ /** Original file object */
189
+ file: File;
190
+ /** Upload status */
191
+ status: "pending" | "uploading" | "ready" | "failed";
192
+ /** Preview URL for local display */
193
+ previewUrl?: string;
194
+ /** Progress percentage (0-100) */
195
+ progress?: number;
196
+ }
197
+
198
+ interface ChatMessageProps {
199
+ /** Message data */
200
+ message: ChatMessage$1;
201
+ /** Whether to enable markdown rendering */
202
+ enableMarkdown?: boolean;
203
+ /** Whether to show tool calls */
204
+ showToolCalls?: boolean;
205
+ /** Additional CSS classes */
206
+ className?: string;
207
+ /** Custom markdown component overrides */
208
+ markdownComponents?: Parameters<typeof MarkdownContent>[0]["components"];
209
+ /** Custom URL transform for markdown */
210
+ markdownUrlTransform?: (url: string) => string;
211
+ /** Custom content transform for markdown */
212
+ markdownContentTransform?: (content: string) => string;
213
+ /** Optional callback when an image in a tool call result is clicked */
214
+ onImageClick?: (image: {
215
+ url: string;
216
+ alt?: string;
217
+ filename?: string;
218
+ }) => void;
219
+ }
220
+ /**
221
+ * Renders a single chat message with appropriate styling
222
+ *
223
+ * @example
224
+ * ```tsx
225
+ * <ChatMessage
226
+ * message={{
227
+ * id: "1",
228
+ * role: "assistant",
229
+ * content: "Hello! How can I help?",
230
+ * timestamp: new Date(),
231
+ * }}
232
+ * enableMarkdown
233
+ * showToolCalls
234
+ * />
235
+ * ```
236
+ */
237
+ declare function ChatMessage({ message, enableMarkdown, showToolCalls, className, markdownComponents, markdownUrlTransform, markdownContentTransform, onImageClick, }: ChatMessageProps): react_jsx_runtime.JSX.Element;
238
+
239
+ interface MessageListProps {
240
+ /** Array of messages to display */
241
+ messages: ChatMessage$1[];
242
+ /** Welcome message shown when chat is empty */
243
+ welcomeMessage?: string;
244
+ /**
245
+ * Custom welcome UI rendered when chat is empty (no messages).
246
+ * When provided, replaces the default centered text welcome message.
247
+ * Takes precedence over `welcomeMessage` string prop.
248
+ *
249
+ * Can be a ReactNode or a render function receiving `{ sendMessage }`
250
+ * to allow interactive elements (e.g., suggestion chips) to send messages.
251
+ */
252
+ renderWelcome?: React.ReactNode | ((props: {
253
+ sendMessage: (text: string) => void;
254
+ }) => React.ReactNode);
255
+ /** Whether a new message is loading */
256
+ isLoading?: boolean;
257
+ /** Whether the assistant is currently streaming a response */
258
+ isStreaming?: boolean;
259
+ /** Whether session history is being loaded */
260
+ isLoadingHistory?: boolean;
261
+ /** Whether to enable markdown rendering */
262
+ enableMarkdown?: boolean;
263
+ /** Whether to show tool calls */
264
+ showToolCalls?: boolean;
265
+ /** Additional CSS classes */
266
+ className?: string;
267
+ /** Custom markdown component overrides */
268
+ markdownComponents?: ChatMessageProps["markdownComponents"];
269
+ /** Custom URL transform for markdown */
270
+ markdownUrlTransform?: (url: string) => string;
271
+ /** Custom content transform for markdown */
272
+ markdownContentTransform?: (content: string) => string;
273
+ /** Optional callback when an image in a tool call result is clicked */
274
+ onImageClick?: (image: {
275
+ url: string;
276
+ alt?: string;
277
+ filename?: string;
278
+ }) => void;
279
+ /**
280
+ * Send message function passed from parent (AgentChat).
281
+ * Used to forward to renderWelcome render function for suggestion chips.
282
+ * @internal
283
+ */
284
+ sendMessage?: (text: string) => void;
285
+ }
286
+ /**
287
+ * Renders a scrollable list of chat messages with auto-scroll
288
+ *
289
+ * @example
290
+ * ```tsx
291
+ * <MessageList
292
+ * messages={messages}
293
+ * welcomeMessage="Hello! How can I help you today?"
294
+ * isLoading={isLoading}
295
+ * isStreaming={isStreaming}
296
+ * enableMarkdown
297
+ * showToolCalls
298
+ * />
299
+ * ```
300
+ */
301
+ declare function MessageList({ messages, welcomeMessage, renderWelcome, isLoading, isStreaming, isLoadingHistory, enableMarkdown, showToolCalls, className, markdownComponents, markdownUrlTransform, markdownContentTransform, onImageClick, sendMessage, }: MessageListProps): react_jsx_runtime.JSX.Element;
302
+
303
+ /**
304
+ * Common types shared across all resources
305
+ */
306
+ /**
307
+ * JSON Schema type for tool input/output schemas
308
+ */
309
+ type JSONSchema = {
310
+ type: string;
311
+ properties?: Record<string, JSONSchema>;
312
+ required?: string[];
313
+ items?: JSONSchema;
314
+ description?: string;
315
+ [key: string]: unknown;
316
+ };
317
+ /**
318
+ * Pagination options for list operations
319
+ */
320
+ interface ListOptions {
321
+ /** Maximum number of items to return (default: 20) */
322
+ limit?: number;
323
+ /** Number of items to skip (pagination offset) */
324
+ offset?: number;
325
+ /** Field to sort by (e.g., 'createdAt') */
326
+ sort?: string;
327
+ /** Sort order */
328
+ order?: 'asc' | 'desc';
329
+ }
330
+ /**
331
+ * Pagination metadata in list responses
332
+ */
333
+ interface PaginationInfo {
334
+ /** Total number of items */
335
+ total: number;
336
+ /** Number of items returned */
337
+ limit: number;
338
+ /** Number of items skipped */
339
+ offset: number;
340
+ /** Whether there are more items */
341
+ hasMore: boolean;
342
+ }
343
+ /**
344
+ * Paginated list response
345
+ */
346
+ interface PaginatedResponse<T> {
347
+ data: T[];
348
+ pagination: PaginationInfo;
349
+ }
350
+ /**
351
+ * Execute operation options
352
+ */
353
+ interface ExecuteOptions {
354
+ /** Maximum number of agent iterations */
355
+ maxIterations?: number;
356
+ /** Maximum tokens for the response */
357
+ maxTokens?: number;
358
+ /** Execution timeout in milliseconds */
359
+ timeout?: number;
360
+ /** Idempotency key for retry safety */
361
+ idempotencyKey?: string;
362
+ }
363
+ /**
364
+ * Execute input for agent/skill operations
365
+ */
366
+ interface ExecuteInput {
367
+ /** The task or prompt to execute */
368
+ task: string;
369
+ /** Additional context for the execution */
370
+ context?: Record<string, unknown>;
371
+ /** Attachment UUIDs to include with the message (for images, documents, etc.) */
372
+ attachmentIds?: string[];
373
+ /** Team UUID for team-based execution (routes to team's lead orchestrator) */
374
+ teamUuid?: string;
375
+ /** Execution options */
376
+ options?: ExecuteOptions;
377
+ }
378
+ /**
379
+ * Execution status
380
+ */
381
+ type ExecutionStatus = 'queued' | 'running' | 'completed' | 'failed' | 'cancelled' | 'paused' | 'waiting_user_input';
382
+ /**
383
+ * Token usage information
384
+ */
385
+ interface TokenUsage {
386
+ /** Input tokens consumed */
387
+ input: number;
388
+ /** Output tokens generated */
389
+ output: number;
390
+ /** Total tokens */
391
+ total: number;
392
+ }
393
+
394
+ /**
395
+ * Agent types
396
+ */
397
+
398
+ /**
399
+ * Agent type
400
+ */
401
+ type AgentType = 'simple' | 'workflow' | 'orchestrator';
402
+ /**
403
+ * Agent status
404
+ */
405
+ type AgentStatus = 'active' | 'inactive' | 'draft';
406
+ /**
407
+ * Agent configuration
408
+ */
409
+ interface AgentConfig {
410
+ /** LLM model to use */
411
+ model?: string;
412
+ /** Temperature for generation */
413
+ temperature?: number;
414
+ /** Maximum iterations for agent loop */
415
+ maxIterations?: number;
416
+ /** System prompt for the agent */
417
+ systemPrompt?: string;
418
+ }
419
+ /**
420
+ * Agent resource
421
+ */
422
+ interface Agent {
423
+ /** Unique identifier */
424
+ uuid: string;
425
+ /** Agent name */
426
+ name: string;
427
+ /** Agent description */
428
+ description: string | null;
429
+ /** Agent type */
430
+ type: AgentType;
431
+ /** Agent status */
432
+ status: AgentStatus;
433
+ /** Creation timestamp */
434
+ createdAt: string;
435
+ /** Last update timestamp */
436
+ updatedAt: string;
437
+ /** Agent configuration (included in get, not list) */
438
+ config?: AgentConfig;
439
+ }
440
+ /**
441
+ * Agent list options
442
+ */
443
+ interface AgentListOptions extends ListOptions {
444
+ /** Filter by status */
445
+ status?: AgentStatus;
446
+ /** Filter by type */
447
+ type?: AgentType;
448
+ }
449
+ /**
450
+ * Log types that can be generated during execution
451
+ * Matches the LogType from cadra-api's log-collector service
452
+ */
453
+ type LogType = 'info' | 'llm_request' | 'llm_response' | 'tool_call' | 'tool_result' | 'error' | 'system' | 'think' | 'rag' | 'skill' | 'delegation' | 'plan' | 'message';
454
+ /**
455
+ * Execution log entry
456
+ */
457
+ interface ExecutionLog {
458
+ /** Unique identifier */
459
+ uuid: string;
460
+ /** Log type */
461
+ type: LogType;
462
+ /** Log title/summary */
463
+ title: string;
464
+ /** Log content/details */
465
+ content?: string;
466
+ /** Additional metadata */
467
+ metadata?: Record<string, unknown>;
468
+ /** Timestamp */
469
+ timestamp: string;
470
+ /** Duration in milliseconds (if applicable) */
471
+ durationMs?: number;
472
+ }
473
+ /**
474
+ * Agent execution result
475
+ */
476
+ interface AgentExecution {
477
+ /** Execution ID */
478
+ uuid: string;
479
+ /** Agent ID */
480
+ agentUuid: string;
481
+ /** Session ID for conversation continuity */
482
+ sessionId?: string;
483
+ /** Execution status */
484
+ status: ExecutionStatus;
485
+ /** Input provided */
486
+ input: {
487
+ task: string;
488
+ context?: Record<string, unknown>;
489
+ };
490
+ /** Output result */
491
+ output?: string;
492
+ /** Error message if failed */
493
+ error?: string;
494
+ /** Execution logs */
495
+ logs: ExecutionLog[];
496
+ /** Token usage */
497
+ tokenUsage?: TokenUsage;
498
+ /** Cost in USD */
499
+ cost?: number;
500
+ /** Number of iterations */
501
+ iterations?: number;
502
+ /** When execution was queued */
503
+ queuedAt: string;
504
+ /** When execution started */
505
+ startedAt?: string;
506
+ /** When execution completed */
507
+ completedAt?: string;
508
+ /** Total duration in milliseconds */
509
+ durationMs?: number;
510
+ }
511
+ /**
512
+ * Agent update input
513
+ */
514
+ interface AgentUpdateInput {
515
+ /** New name */
516
+ name?: string;
517
+ /** New description */
518
+ description?: string;
519
+ /** New status */
520
+ status?: AgentStatus;
521
+ }
522
+ /**
523
+ * Agent config update input
524
+ */
525
+ interface AgentConfigUpdateInput {
526
+ /** LLM model */
527
+ model?: string;
528
+ /** Temperature */
529
+ temperature?: number;
530
+ /** Max iterations */
531
+ maxIterations?: number;
532
+ /** System prompt */
533
+ systemPrompt?: string;
534
+ }
535
+ /**
536
+ * Execute response (async)
537
+ */
538
+ interface ExecuteResponse {
539
+ /** Execution ID */
540
+ executionId: string;
541
+ /** Session ID for conversation continuity */
542
+ sessionId?: string;
543
+ /** Initial status */
544
+ status: ExecutionStatus;
545
+ }
546
+
547
+ /**
548
+ * Streaming types
549
+ */
550
+
551
+ /**
552
+ * Tool call event
553
+ */
554
+ interface ToolCallEvent {
555
+ /** Tool call ID */
556
+ toolCallId: string;
557
+ /** Tool name */
558
+ toolName: string;
559
+ /** Tool inputs */
560
+ inputs: Record<string, unknown>;
561
+ /** Step/iteration index */
562
+ stepIndex: number;
563
+ }
564
+ /**
565
+ * Tool result event
566
+ */
567
+ interface ToolResultEvent {
568
+ /** Tool call ID */
569
+ toolCallId: string;
570
+ /** Tool name */
571
+ toolName: string;
572
+ /** Tool result */
573
+ result: unknown;
574
+ /** Duration in milliseconds */
575
+ durationMs: number;
576
+ }
577
+ /**
578
+ * Plan event
579
+ */
580
+ interface PlanEvent {
581
+ /** Planned tasks */
582
+ tasks: Array<{
583
+ title: string;
584
+ status: 'pending' | 'in_progress' | 'completed' | 'failed';
585
+ }>;
586
+ }
587
+ /**
588
+ * Complete event
589
+ */
590
+ interface CompleteEvent {
591
+ /** Final execution result */
592
+ execution: AgentExecution;
593
+ }
594
+ /**
595
+ * Error event
596
+ */
597
+ interface ErrorEvent {
598
+ /** Error message */
599
+ error: string;
600
+ /** Error code */
601
+ errorCode?: string;
602
+ }
603
+ /**
604
+ * Connection change event
605
+ */
606
+ interface ConnectionChangeEvent {
607
+ /** Whether connected */
608
+ connected: boolean;
609
+ /** Whether using fallback polling */
610
+ usingFallback?: boolean;
611
+ }
612
+ /**
613
+ * Paused event (ask_user waiting for user input)
614
+ */
615
+ interface PausedEvent {
616
+ /** The question to ask the user */
617
+ question: string;
618
+ /** Optional predefined choices */
619
+ options?: string[];
620
+ /** Reason for pausing */
621
+ reason: 'waiting_user_input';
622
+ }
623
+ /**
624
+ * Delegation started event (handoff_to_agent initiated)
625
+ */
626
+ interface DelegationStartedEvent {
627
+ /** Event type */
628
+ type: 'delegation_started';
629
+ /** Unique handoff ID */
630
+ handoffId: string;
631
+ /** Target agent UUID */
632
+ targetAgentUuid: string;
633
+ /** Target agent name */
634
+ targetAgentName?: string;
635
+ /** Preview of the delegated task */
636
+ taskPreview: string;
637
+ /** Event timestamp */
638
+ timestamp: string;
639
+ }
640
+ /**
641
+ * Delegation completed event (handoff_to_agent finished)
642
+ */
643
+ interface DelegationCompletedEvent {
644
+ /** Event type */
645
+ type: 'delegation_completed';
646
+ /** Unique handoff ID */
647
+ handoffId: string;
648
+ /** Completion status */
649
+ status: 'completed' | 'failed';
650
+ /** Preview of the result (if completed) */
651
+ resultPreview?: string;
652
+ /** Error message (if failed) */
653
+ error?: string;
654
+ /** Duration in milliseconds */
655
+ durationMs: number;
656
+ /** Event timestamp */
657
+ timestamp: string;
658
+ }
659
+ /**
660
+ * Text delta event - token-by-token streaming text
661
+ */
662
+ interface TextDeltaEvent {
663
+ /** Text delta chunk */
664
+ delta: string;
665
+ /** Execution ID */
666
+ executionId: string;
667
+ /** Event timestamp */
668
+ timestamp: string;
669
+ }
670
+ /**
671
+ * Started event - execution has begun
672
+ */
673
+ interface StartedEvent {
674
+ /** Execution ID */
675
+ executionId: string;
676
+ /** Agent UUID */
677
+ agentUuid: string;
678
+ /** Initial status */
679
+ status: 'initializing';
680
+ /** Current step description */
681
+ currentStep?: string;
682
+ }
683
+ /**
684
+ * Progress event - execution status update
685
+ */
686
+ interface ProgressEvent {
687
+ /** Current status */
688
+ status: 'initializing' | 'thinking' | 'acting' | 'observing' | 'planning' | 'paused';
689
+ /** Current iteration number */
690
+ iteration: number;
691
+ /** Description of current step */
692
+ currentStep?: string;
693
+ /** Current token usage */
694
+ tokenUsage?: {
695
+ prompt: number;
696
+ completion: number;
697
+ total: number;
698
+ };
699
+ /** Current cost */
700
+ cost?: number;
701
+ /** Number of tool calls made */
702
+ toolCalls?: number;
703
+ }
704
+ /**
705
+ * Task status for task list updates
706
+ */
707
+ type TaskStatus = 'pending' | 'in_progress' | 'completed';
708
+ /**
709
+ * Task item in task list
710
+ */
711
+ interface TaskItem {
712
+ /** Unique task ID */
713
+ id: string;
714
+ /** Task content/description */
715
+ content: string;
716
+ /** Active form text shown during in_progress */
717
+ activeForm?: string | null;
718
+ /** Task status */
719
+ status: TaskStatus;
720
+ }
721
+ /**
722
+ * Task list update event - agent creating/updating task list
723
+ */
724
+ interface TaskListUpdateEvent {
725
+ /** Execution ID */
726
+ executionId: string;
727
+ /** Current task list */
728
+ tasks: TaskItem[];
729
+ /** Timestamp */
730
+ timestamp: string;
731
+ }
732
+ /**
733
+ * Stream controller interface
734
+ */
735
+ interface StreamController {
736
+ /** Listen for log events */
737
+ on(event: 'log', callback: (log: ExecutionLog) => void): void;
738
+ /** Listen for tool call events */
739
+ on(event: 'toolCall', callback: (data: ToolCallEvent) => void): void;
740
+ /** Listen for tool result events */
741
+ on(event: 'toolResult', callback: (data: ToolResultEvent) => void): void;
742
+ /** Listen for plan updates */
743
+ on(event: 'plan', callback: (data: PlanEvent) => void): void;
744
+ /** Listen for paused events (ask_user waiting for input) */
745
+ on(event: 'paused', callback: (data: PausedEvent) => void): void;
746
+ /** Listen for execution started (immediate feedback) */
747
+ on(event: 'started', callback: (data: StartedEvent) => void): void;
748
+ /** Listen for progress updates (status changes during execution) */
749
+ on(event: 'progress', callback: (data: ProgressEvent) => void): void;
750
+ /** Listen for task list updates */
751
+ on(event: 'taskListUpdate', callback: (data: TaskListUpdateEvent) => void): void;
752
+ /** Listen for delegation started events */
753
+ on(event: 'delegationStarted', callback: (data: DelegationStartedEvent) => void): void;
754
+ /** Listen for delegation completed events */
755
+ on(event: 'delegationCompleted', callback: (data: DelegationCompletedEvent) => void): void;
756
+ /** Listen for text delta events (token-by-token streaming) */
757
+ on(event: 'textDelta', callback: (data: TextDeltaEvent) => void): void;
758
+ /** Listen for completion */
759
+ on(event: 'complete', callback: (data: CompleteEvent) => void): void;
760
+ /** Listen for errors */
761
+ on(event: 'error', callback: (error: ErrorEvent) => void): void;
762
+ /** Listen for connection state changes */
763
+ on(event: 'connectionChange', callback: (data: ConnectionChangeEvent) => void): void;
764
+ /** Cancel the stream */
765
+ cancel(): void;
766
+ /** Wait for completion, returns final execution result */
767
+ wait(): Promise<AgentExecution>;
768
+ }
769
+
770
+ /**
771
+ * Stream Controller
772
+ *
773
+ * Manages execution streaming with automatic reconnection and fallback to polling.
774
+ * Implements the StreamController interface for type-safe event handling.
775
+ */
776
+
777
+ /**
778
+ * Execution Stream Controller
779
+ *
780
+ * Manages the lifecycle of an execution stream, including:
781
+ * - SSE connection management
782
+ * - Automatic reconnection with exponential backoff
783
+ * - Fallback to polling on connection failure
784
+ * - Event deduplication
785
+ */
786
+ interface ExecutionStreamController extends StreamController {
787
+ /** Connect to the stream */
788
+ connect(): Promise<void>;
789
+ /** Get the execution ID */
790
+ readonly executionId: string;
791
+ /** Get the session ID (if available) */
792
+ readonly sessionId: string | undefined;
793
+ }
794
+
795
+ /**
796
+ * ChatAdapter interface for customizable API integration
797
+ *
798
+ * Implement this interface to:
799
+ * - Connect to different backends
800
+ * - Use direct DB access (in ai-saas-v2)
801
+ * - Mock for testing
802
+ *
803
+ * @module @cadraos/sdk/chat
804
+ */
805
+
806
+ /**
807
+ * Input for starting an agent execution
808
+ */
809
+ interface StartExecutionInput {
810
+ /** UUID of the agent to execute. Optional when teamId is provided. */
811
+ agentId?: string;
812
+ /** Optional team UUID for team-based execution (routes to team's lead orchestrator) */
813
+ teamId?: string;
814
+ /** Optional session ID for continuing a conversation */
815
+ sessionId?: string;
816
+ /** User message content */
817
+ content: string;
818
+ /** UUIDs of attached files */
819
+ attachmentUuids?: string[];
820
+ }
821
+ /**
822
+ * Input for sending a message in an existing session
823
+ */
824
+ interface SendMessageInput$1 {
825
+ /** Session ID */
826
+ sessionId: string;
827
+ /** Message content */
828
+ content: string;
829
+ /** UUIDs of attached files */
830
+ attachmentUuids?: string[];
831
+ }
832
+ /**
833
+ * Input for getting an upload URL
834
+ */
835
+ interface UploadUrlInput {
836
+ /** Session ID */
837
+ sessionId: string;
838
+ /** Filename */
839
+ filename: string;
840
+ /** MIME type */
841
+ mimeType: string;
842
+ /** File size in bytes */
843
+ size: number;
844
+ }
845
+ /**
846
+ * Input for listing sessions
847
+ */
848
+ interface ListSessionsInput {
849
+ /** Filter by agent UUID */
850
+ agentId?: string;
851
+ /** Maximum number of sessions to return */
852
+ limit?: number;
853
+ /** Pagination offset */
854
+ offset?: number;
855
+ }
856
+ /**
857
+ * Result from starting an execution
858
+ */
859
+ interface ExecutionResult {
860
+ /** UUID of the created execution */
861
+ executionId: string;
862
+ /** UUID of the session (new or existing) */
863
+ sessionId: string;
864
+ }
865
+ /**
866
+ * Result from getting an upload URL
867
+ */
868
+ interface UploadUrlResult {
869
+ /** Pre-signed upload URL */
870
+ uploadUrl: string;
871
+ /** UUID for the attachment */
872
+ attachmentUuid: string;
873
+ }
874
+ /**
875
+ * Execution status and result
876
+ */
877
+ interface Execution {
878
+ /** Execution UUID */
879
+ uuid: string;
880
+ /** Current status */
881
+ status: "pending" | "running" | "completed" | "failed" | "cancelled";
882
+ /** Final result (when completed) */
883
+ result?: string;
884
+ /** Error message (when failed) */
885
+ error?: string;
886
+ }
887
+ /**
888
+ * Artifact generated during execution
889
+ */
890
+ interface Artifact$1 {
891
+ /** Artifact UUID */
892
+ uuid: string;
893
+ /** Artifact type */
894
+ type: "image" | "document" | "code" | "audio";
895
+ /** Filename */
896
+ filename: string;
897
+ /** MIME type */
898
+ mimeType: string;
899
+ /** Download URL */
900
+ url: string;
901
+ /** When the artifact was created (ISO string) */
902
+ createdAt?: string;
903
+ }
904
+ /**
905
+ * Session summary for list display
906
+ */
907
+ interface SessionListItem {
908
+ /** Session UUID */
909
+ id: string;
910
+ /** Agent UUID */
911
+ agentId: string;
912
+ /** When the session was created */
913
+ createdAt: string;
914
+ /** When the last message was sent */
915
+ lastMessageAt: string;
916
+ /** Total message count */
917
+ messageCount: number;
918
+ /** Preview of the last user message */
919
+ lastUserMessage?: string | null;
920
+ }
921
+ /**
922
+ * Paginated session list result
923
+ */
924
+ interface SessionList {
925
+ /** Sessions in the current page */
926
+ sessions: SessionListItem[];
927
+ /** Total number of sessions */
928
+ total: number;
929
+ /** Whether there are more sessions beyond this page */
930
+ hasMore: boolean;
931
+ }
932
+ /**
933
+ * Attachment metadata for history messages
934
+ */
935
+ interface HistoryAttachment {
936
+ /** Attachment UUID */
937
+ uuid: string;
938
+ /** Original filename */
939
+ filename: string;
940
+ /** MIME type */
941
+ mimeType: string;
942
+ /** File size in bytes */
943
+ size: number;
944
+ /** Category classification */
945
+ category: "document" | "image" | "audio";
946
+ /** Preview URL (for images) */
947
+ previewUrl?: string;
948
+ /** Thumbnail URL */
949
+ thumbnailUrl?: string;
950
+ }
951
+ /**
952
+ * Tool call data for history messages
953
+ */
954
+ interface HistoryToolCall {
955
+ /** Tool call ID */
956
+ id: string;
957
+ /** Tool name */
958
+ name: string;
959
+ /** Tool arguments */
960
+ args?: Record<string, unknown>;
961
+ /** Tool result */
962
+ result?: unknown;
963
+ /** Execution status */
964
+ status: "pending" | "running" | "completed" | "failed";
965
+ /** Execution duration in ms */
966
+ durationMs?: number;
967
+ }
968
+ /**
969
+ * A message in the session history
970
+ */
971
+ interface HistoryMessage {
972
+ /** Message UUID */
973
+ uuid: string;
974
+ /** Message role */
975
+ role: "user" | "assistant";
976
+ /** Message content */
977
+ content: string;
978
+ /** Message timestamp */
979
+ timestamp: string;
980
+ /** File attachments (for user messages) */
981
+ attachments?: HistoryAttachment[];
982
+ /** Tool calls (for assistant messages) */
983
+ toolCalls?: HistoryToolCall[];
984
+ }
985
+ /**
986
+ * Session with chat history
987
+ */
988
+ interface SessionHistory$1 {
989
+ /** Session UUID */
990
+ sessionId: string;
991
+ /** Agent UUID */
992
+ agentId: string;
993
+ /** Messages in chronological order */
994
+ messages: HistoryMessage[];
995
+ /** When the session was created */
996
+ createdAt: string;
997
+ /** When the session was last updated */
998
+ updatedAt: string;
999
+ }
1000
+ /**
1001
+ * ChatAdapter interface for API integration
1002
+ *
1003
+ * This interface decouples the UI from the API implementation,
1004
+ * allowing:
1005
+ * - Built-in HTTP adapter for external API consumers
1006
+ * - Custom adapter for ai-saas-v2 (direct tRPC/DB access)
1007
+ * - Testing with mock adapters
1008
+ *
1009
+ * @example
1010
+ * ```typescript
1011
+ * // Using default HTTP adapter
1012
+ * const adapter = createDefaultAdapter({
1013
+ * baseUrl: 'https://api.example.com/api/v1/external',
1014
+ * apiKey: 'your-api-key',
1015
+ * orgId: 123,
1016
+ * });
1017
+ *
1018
+ * // Using custom tRPC adapter
1019
+ * const adapter: ChatAdapter = {
1020
+ * startExecution: (input) => api.agents.execute.mutate(input),
1021
+ * // ... other methods
1022
+ * };
1023
+ * ```
1024
+ */
1025
+ interface ChatAdapter {
1026
+ /**
1027
+ * Start a new agent execution
1028
+ * @param input - Execution input
1029
+ * @returns Execution and session IDs
1030
+ */
1031
+ startExecution(input: StartExecutionInput): Promise<ExecutionResult>;
1032
+ /**
1033
+ * Send a message in an existing session
1034
+ * @param input - Message input
1035
+ * @returns Execution and session IDs
1036
+ */
1037
+ sendMessage(input: SendMessageInput$1): Promise<ExecutionResult>;
1038
+ /**
1039
+ * Cancel a running execution
1040
+ * @param uuid - Execution UUID
1041
+ */
1042
+ cancelExecution(uuid: string): Promise<void>;
1043
+ /**
1044
+ * Get execution status and result
1045
+ * @param uuid - Execution UUID
1046
+ * @returns Execution details
1047
+ */
1048
+ getExecution(uuid: string): Promise<Execution>;
1049
+ /**
1050
+ * Get a pre-signed URL for uploading a file
1051
+ * @param input - Upload URL input
1052
+ * @returns Upload URL and attachment UUID
1053
+ */
1054
+ getUploadUrl(input: UploadUrlInput): Promise<UploadUrlResult>;
1055
+ /**
1056
+ * Confirm that a file upload has completed
1057
+ * @param uuid - Attachment UUID
1058
+ */
1059
+ confirmUpload(uuid: string): Promise<void>;
1060
+ /**
1061
+ * Get a download URL for an attachment
1062
+ * @param uuid - Attachment UUID
1063
+ * @returns Signed download URL
1064
+ */
1065
+ getDownloadUrl(uuid: string): Promise<string>;
1066
+ /**
1067
+ * Get artifacts generated in a session
1068
+ * @param sessionId - Session UUID
1069
+ * @returns List of artifacts
1070
+ */
1071
+ getSessionArtifacts?(sessionId: string): Promise<Artifact$1[]>;
1072
+ /**
1073
+ * Load chat history for an existing session
1074
+ *
1075
+ * This method is optional. If not implemented, session loading will not be available.
1076
+ * The returned data is designed to be cacheable with React Query, SWR, or Next.js caching.
1077
+ *
1078
+ * @param sessionId - Session UUID
1079
+ * @returns Session with message history
1080
+ */
1081
+ getSessionHistory?(sessionId: string): Promise<SessionHistory$1>;
1082
+ /**
1083
+ * List sessions for the current user/agent
1084
+ *
1085
+ * @param input - List options (agent filter, pagination)
1086
+ * @returns Paginated session list
1087
+ */
1088
+ listSessions?(input: ListSessionsInput): Promise<SessionList>;
1089
+ /**
1090
+ * Create an ExecutionStreamController for an execution.
1091
+ *
1092
+ * When implemented, useAgentChat will use this instead of the legacy
1093
+ * EventSource-based useExecutionStream hook. The stream controller
1094
+ * provides automatic reconnection, polling fallback, and event deduplication.
1095
+ *
1096
+ * @param executionId - Execution UUID to stream
1097
+ * @param sessionId - Optional session ID for context
1098
+ * @returns ExecutionStreamController instance (call .connect() to start)
1099
+ */
1100
+ createStream?(executionId: string, sessionId?: string): ExecutionStreamController;
1101
+ /**
1102
+ * Get the SSE stream URL for an execution.
1103
+ *
1104
+ * @deprecated Prefer implementing `createStream` which provides
1105
+ * fetch-based SSE with auth headers. This is kept for backward
1106
+ * compatibility with EventSource-based streaming.
1107
+ *
1108
+ * @param executionId - Execution UUID
1109
+ * @returns Full URL for SSE connection
1110
+ */
1111
+ getStreamUrl?(executionId: string): string;
1112
+ }
1113
+
1114
+ interface AgentChatProps {
1115
+ /**
1116
+ * The UUID of the agent to chat with.
1117
+ * Optional when teamId is provided (team execution routes to team's lead orchestrator).
1118
+ */
1119
+ agentId?: string;
1120
+ /** Optional team UUID for team-based execution (routes to team's lead orchestrator) */
1121
+ teamId?: string;
1122
+ /**
1123
+ * Session ID to resume an existing conversation
1124
+ * When provided, the component will load the session's chat history
1125
+ */
1126
+ sessionId?: string;
1127
+ /** Custom adapter (optional - uses context if not provided) */
1128
+ adapter?: ChatAdapter;
1129
+ /** Callback fired when a new message is added */
1130
+ onMessage?: (message: ChatMessage$1) => void;
1131
+ /** Callback fired when an error occurs */
1132
+ onError?: (error: ChatError) => void;
1133
+ /**
1134
+ * Callback fired when a new session is created
1135
+ * Called with the sessionId when starting a new chat (no existing sessionId)
1136
+ * Useful for updating external state like session lists
1137
+ */
1138
+ onSessionCreated?: (sessionId: string) => void;
1139
+ /** @deprecated Use onSessionCreated instead */
1140
+ onSessionStart?: (sessionId: string) => void;
1141
+ /** Callback fired when a tool is called */
1142
+ onToolCall?: (toolName: string, args: unknown) => void;
1143
+ /** Callback fired when a tool result is received */
1144
+ onToolResult?: (toolName: string, result: unknown, durationMs?: number) => void;
1145
+ /** Callback fired when clarification is needed */
1146
+ onClarification?: (data: ClarificationData) => void;
1147
+ /** Initial messages to populate the chat */
1148
+ initialMessages?: ChatMessage$1[];
1149
+ /** Placeholder text for the input */
1150
+ placeholder?: string;
1151
+ /** Welcome message shown when chat is empty */
1152
+ welcomeMessage?: string;
1153
+ /**
1154
+ * Custom welcome UI rendered when chat is empty (no messages).
1155
+ * When provided, replaces the default centered text welcome message.
1156
+ * Takes precedence over `welcomeMessage` string prop.
1157
+ *
1158
+ * Can be a ReactNode or a render function receiving `{ sendMessage }`
1159
+ * to allow interactive elements (e.g., suggestion chips) to send messages.
1160
+ */
1161
+ renderWelcome?: React.ReactNode | ((props: {
1162
+ sendMessage: (text: string) => void;
1163
+ }) => React.ReactNode);
1164
+ /** Maximum height of the chat container */
1165
+ maxHeight?: string | number;
1166
+ /** Additional CSS class for the container */
1167
+ className?: string;
1168
+ /** Theme mode */
1169
+ theme?: ThemeMode;
1170
+ /** Enable file attachments (future feature) */
1171
+ enableAttachments?: boolean;
1172
+ /** Enable markdown rendering */
1173
+ enableMarkdown?: boolean;
1174
+ /** Show tool call visualization */
1175
+ showToolCalls?: boolean;
1176
+ /** Custom markdown component overrides (e.g., for artifact rendering) */
1177
+ markdownComponents?: MessageListProps["markdownComponents"];
1178
+ /** Custom URL transform for markdown (e.g., to preserve artifact: protocol) */
1179
+ markdownUrlTransform?: (url: string) => string;
1180
+ /** Custom content transform for markdown */
1181
+ markdownContentTransform?: (content: string) => string;
1182
+ /** Optional callback when an image in a tool call result is clicked */
1183
+ onImageClick?: (image: {
1184
+ url: string;
1185
+ alt?: string;
1186
+ filename?: string;
1187
+ }) => void;
1188
+ }
1189
+ /**
1190
+ * Complete chat interface for interacting with AI agents
1191
+ *
1192
+ * @example
1193
+ * ```tsx
1194
+ * // With ChatConfigProvider (recommended for API key users)
1195
+ * <ChatConfigProvider config={{ baseUrl: '...', apiKey: '...' }}>
1196
+ * <AgentChat
1197
+ * agentId="agent-uuid"
1198
+ * onMessage={(msg) => console.log('New message:', msg)}
1199
+ * />
1200
+ * </ChatConfigProvider>
1201
+ *
1202
+ * // With custom adapter
1203
+ * <AgentChat
1204
+ * agentId="agent-uuid"
1205
+ * adapter={myCustomAdapter}
1206
+ * />
1207
+ * ```
1208
+ */
1209
+ declare function AgentChat({ agentId, teamId, sessionId, adapter, onMessage, onError, onSessionCreated, onSessionStart, onToolCall, onToolResult, onClarification, initialMessages, placeholder, welcomeMessage, renderWelcome, maxHeight, className, theme, enableAttachments, enableMarkdown, showToolCalls, markdownComponents, markdownUrlTransform, markdownContentTransform, onImageClick, }: AgentChatProps): react_jsx_runtime.JSX.Element;
1210
+
1211
+ /**
1212
+ * Retry utility with exponential backoff
1213
+ */
1214
+ /**
1215
+ * Retry configuration
1216
+ */
1217
+ interface RetryConfig {
1218
+ /** Maximum number of retry attempts (default: 3) */
1219
+ maxRetries: number;
1220
+ /** Base delay in milliseconds (default: 1000) */
1221
+ baseDelayMs: number;
1222
+ /** Maximum delay in milliseconds (default: 30000) */
1223
+ maxDelayMs: number;
1224
+ /** Jitter factor (0-1, default: 0.1) */
1225
+ jitterFactor: number;
1226
+ }
1227
+
1228
+ /**
1229
+ * HTTP Client
1230
+ *
1231
+ * Handles all HTTP requests with authentication, retry logic, and error handling.
1232
+ */
1233
+
1234
+ /**
1235
+ * HTTP Client configuration
1236
+ */
1237
+ interface HttpClientConfig {
1238
+ /** Base URL for API requests */
1239
+ baseUrl: string;
1240
+ /** API key for authentication */
1241
+ apiKey?: string;
1242
+ /** OAuth token for authentication */
1243
+ token?: string;
1244
+ /** Token provider callback (called before each request) */
1245
+ tokenProvider?: () => Promise<string>;
1246
+ /** Organization ID */
1247
+ orgId: number;
1248
+ /** Request timeout in milliseconds (default: 30000) */
1249
+ timeout: number;
1250
+ /** Retry configuration */
1251
+ retry: RetryConfig;
1252
+ /** Custom headers */
1253
+ headers?: Record<string, string>;
1254
+ }
1255
+ /**
1256
+ * Request options
1257
+ */
1258
+ interface RequestOptions {
1259
+ /** HTTP method */
1260
+ method: 'GET' | 'POST' | 'PATCH' | 'DELETE' | 'PUT';
1261
+ /** Request path (appended to base URL) */
1262
+ path: string;
1263
+ /** Request body */
1264
+ body?: unknown;
1265
+ /** Query parameters */
1266
+ query?: Record<string, string | number | boolean | undefined>;
1267
+ /** Additional headers */
1268
+ headers?: Record<string, string>;
1269
+ /** Skip retry (for non-idempotent operations) */
1270
+ skipRetry?: boolean;
1271
+ /** Idempotency key */
1272
+ idempotencyKey?: string;
1273
+ }
1274
+ /**
1275
+ * HTTP Client class
1276
+ */
1277
+ declare class HttpClient {
1278
+ private config;
1279
+ private tokenRefreshAttempts;
1280
+ private readonly maxTokenRefreshAttempts;
1281
+ constructor(config: HttpClientConfig);
1282
+ /**
1283
+ * Get authorization header value
1284
+ */
1285
+ private getAuthHeader;
1286
+ /**
1287
+ * Build full URL with query parameters
1288
+ */
1289
+ private buildUrl;
1290
+ /**
1291
+ * Make an HTTP request
1292
+ */
1293
+ request<T>(options: RequestOptions): Promise<T>;
1294
+ /**
1295
+ * GET request
1296
+ */
1297
+ get<T>(path: string, query?: Record<string, string | number | boolean | undefined>): Promise<T>;
1298
+ /**
1299
+ * POST request
1300
+ */
1301
+ post<T>(path: string, body?: unknown, options?: {
1302
+ idempotencyKey?: string;
1303
+ skipRetry?: boolean;
1304
+ }): Promise<T>;
1305
+ /**
1306
+ * PATCH request
1307
+ */
1308
+ patch<T>(path: string, body?: unknown, options?: {
1309
+ idempotencyKey?: string;
1310
+ }): Promise<T>;
1311
+ /**
1312
+ * DELETE request
1313
+ */
1314
+ delete<T>(path: string): Promise<T>;
1315
+ /**
1316
+ * Update configuration
1317
+ */
1318
+ updateConfig(config: Partial<HttpClientConfig>): void;
1319
+ }
1320
+
1321
+ /**
1322
+ * Skill types
1323
+ */
1324
+
1325
+ /**
1326
+ * Skill tool reference
1327
+ */
1328
+ interface SkillTool {
1329
+ /** Tool UUID */
1330
+ uuid: string;
1331
+ /** Tool name */
1332
+ name: string;
1333
+ /** Tool description */
1334
+ description: string;
1335
+ }
1336
+ /**
1337
+ * Skill variable definition
1338
+ */
1339
+ interface SkillVariable {
1340
+ /** Variable name */
1341
+ name: string;
1342
+ /** Variable type */
1343
+ type: 'string' | 'number' | 'boolean' | 'object';
1344
+ /** Variable description */
1345
+ description: string;
1346
+ /** Whether the variable is required */
1347
+ required: boolean;
1348
+ /** Default value */
1349
+ default?: unknown;
1350
+ }
1351
+ /**
1352
+ * Skill resource (list view)
1353
+ */
1354
+ interface Skill {
1355
+ /** Unique identifier */
1356
+ uuid: string;
1357
+ /** Skill name */
1358
+ name: string;
1359
+ /** Skill description */
1360
+ description: string | null;
1361
+ /** Category */
1362
+ category: string | null;
1363
+ /** Tags */
1364
+ tags: string[];
1365
+ /** Version string */
1366
+ version: string;
1367
+ /** Whether skill is public */
1368
+ isPublic: boolean;
1369
+ /** Creation timestamp */
1370
+ createdAt: string;
1371
+ /** Last update timestamp */
1372
+ updatedAt: string;
1373
+ }
1374
+ /**
1375
+ * Skill details (get view, includes prompt template)
1376
+ */
1377
+ interface SkillDetails extends Skill {
1378
+ /** Prompt template */
1379
+ promptTemplate: string;
1380
+ /** Associated tools */
1381
+ tools: SkillTool[];
1382
+ /** Variable definitions */
1383
+ variables: SkillVariable[];
1384
+ }
1385
+ /**
1386
+ * Skill list options
1387
+ */
1388
+ interface SkillListOptions extends ListOptions {
1389
+ /** Filter by category */
1390
+ category?: string;
1391
+ /** Filter by tags (any match) */
1392
+ tags?: string[];
1393
+ }
1394
+ /**
1395
+ * Skill execute input
1396
+ */
1397
+ interface SkillExecuteInput {
1398
+ /** Variable values for the prompt template */
1399
+ variables?: Record<string, unknown>;
1400
+ /** Additional context */
1401
+ context?: Record<string, unknown>;
1402
+ }
1403
+ /**
1404
+ * Skill execution result
1405
+ */
1406
+ interface SkillExecution {
1407
+ /** Execution ID */
1408
+ uuid: string;
1409
+ /** Skill ID */
1410
+ skillUuid: string;
1411
+ /** Execution status */
1412
+ status: 'success' | 'error';
1413
+ /** Input variables */
1414
+ input: Record<string, unknown>;
1415
+ /** Generated prompt output */
1416
+ output?: string;
1417
+ /** Error message */
1418
+ error?: string;
1419
+ /** Execution timestamp */
1420
+ executedAt: string;
1421
+ /** Duration in milliseconds */
1422
+ durationMs: number;
1423
+ }
1424
+ /**
1425
+ * Skill update input
1426
+ */
1427
+ interface SkillUpdateInput {
1428
+ /** New name */
1429
+ name?: string;
1430
+ /** New description */
1431
+ description?: string;
1432
+ /** New category */
1433
+ category?: string;
1434
+ /** New tags */
1435
+ tags?: string[];
1436
+ }
1437
+
1438
+ /**
1439
+ * Tool types
1440
+ */
1441
+
1442
+ /**
1443
+ * Tool resource
1444
+ */
1445
+ interface Tool {
1446
+ /** Unique identifier */
1447
+ uuid: string;
1448
+ /** Tool name */
1449
+ name: string;
1450
+ /** Tool description */
1451
+ description: string;
1452
+ /** Category */
1453
+ category: string | null;
1454
+ /** Input JSON schema */
1455
+ inputSchema: JSONSchema;
1456
+ /** Output JSON schema */
1457
+ outputSchema?: JSONSchema;
1458
+ /** Whether tool is enabled */
1459
+ isEnabled: boolean;
1460
+ /** Creation timestamp */
1461
+ createdAt: string;
1462
+ /** Last update timestamp */
1463
+ updatedAt: string;
1464
+ }
1465
+ /**
1466
+ * Tool list options
1467
+ */
1468
+ interface ToolListOptions extends ListOptions {
1469
+ /** Filter by category */
1470
+ category?: string;
1471
+ /** Filter by enabled status */
1472
+ isEnabled?: boolean;
1473
+ }
1474
+ /**
1475
+ * Tool execution result
1476
+ */
1477
+ interface ToolExecution {
1478
+ /** Execution ID */
1479
+ uuid: string;
1480
+ /** Tool ID */
1481
+ toolUuid: string;
1482
+ /** Execution status */
1483
+ status: 'success' | 'error';
1484
+ /** Input provided */
1485
+ input: Record<string, unknown>;
1486
+ /** Output result */
1487
+ output?: unknown;
1488
+ /** Error message */
1489
+ error?: string;
1490
+ /** Duration in milliseconds */
1491
+ durationMs: number;
1492
+ /** Execution timestamp */
1493
+ executedAt: string;
1494
+ }
1495
+ /**
1496
+ * Tool input validation result
1497
+ */
1498
+ interface ToolValidationResult {
1499
+ /** Whether the input is valid */
1500
+ valid: boolean;
1501
+ /** Validation errors (if invalid) */
1502
+ errors?: Array<{
1503
+ field: string;
1504
+ message: string;
1505
+ }>;
1506
+ }
1507
+ /**
1508
+ * Tool update input
1509
+ */
1510
+ interface ToolUpdateInput {
1511
+ /** New name */
1512
+ name?: string;
1513
+ /** New description */
1514
+ description?: string;
1515
+ /** New category */
1516
+ category?: string;
1517
+ }
1518
+ /**
1519
+ * Tool config update input
1520
+ */
1521
+ interface ToolConfigUpdateInput {
1522
+ /** Tool-specific configuration */
1523
+ config?: Record<string, unknown>;
1524
+ /** Enable/disable tool */
1525
+ isEnabled?: boolean;
1526
+ }
1527
+
1528
+ /**
1529
+ * Artifact types
1530
+ */
1531
+
1532
+ /**
1533
+ * Artifact type
1534
+ */
1535
+ type ArtifactType = 'file' | 'data' | 'log';
1536
+ /**
1537
+ * Artifact resource
1538
+ */
1539
+ interface Artifact {
1540
+ /** Unique identifier */
1541
+ uuid: string;
1542
+ /** Associated execution ID */
1543
+ executionUuid: string;
1544
+ /** Artifact name */
1545
+ name: string;
1546
+ /** Artifact type */
1547
+ type: ArtifactType;
1548
+ /** MIME type */
1549
+ mimeType: string;
1550
+ /** Size in bytes */
1551
+ size: number;
1552
+ /** Creation timestamp */
1553
+ createdAt: string;
1554
+ /** Additional metadata */
1555
+ metadata?: Record<string, unknown>;
1556
+ }
1557
+ /**
1558
+ * Artifact list options
1559
+ */
1560
+ interface ArtifactListOptions extends ListOptions {
1561
+ /** Filter by type */
1562
+ type?: ArtifactType;
1563
+ }
1564
+ /**
1565
+ * Artifact download options
1566
+ */
1567
+ interface ArtifactDownloadOptions {
1568
+ /** Response format (only for getSignedUrl) */
1569
+ format?: 'buffer' | 'stream' | 'url';
1570
+ /** Expiration time in seconds for signed URL (default: 3600) */
1571
+ expiresIn?: number;
1572
+ }
1573
+ /**
1574
+ * Signed URL response
1575
+ */
1576
+ interface SignedUrlResponse {
1577
+ /** The signed URL */
1578
+ url: string;
1579
+ /** When the URL expires */
1580
+ expiresAt: string;
1581
+ }
1582
+ /**
1583
+ * Artifact upload input
1584
+ */
1585
+ interface ArtifactUploadInput {
1586
+ /** File name */
1587
+ name: string;
1588
+ /** File content (Buffer in Node.js, Blob in browser) */
1589
+ content: Buffer | Blob | ReadableStream<Uint8Array>;
1590
+ /** MIME type */
1591
+ mimeType?: string;
1592
+ /** Artifact type */
1593
+ type?: ArtifactType;
1594
+ /** Additional metadata */
1595
+ metadata?: Record<string, unknown>;
1596
+ }
1597
+
1598
+ /**
1599
+ * Session types
1600
+ */
1601
+
1602
+ /**
1603
+ * Session resource
1604
+ */
1605
+ interface Session {
1606
+ /** Session ID */
1607
+ id: string;
1608
+ /** Associated agent ID */
1609
+ agentUuid: string;
1610
+ /** Creation timestamp */
1611
+ createdAt: string;
1612
+ /** Last message timestamp */
1613
+ lastMessageAt: string;
1614
+ /** Number of messages in session */
1615
+ messageCount: number;
1616
+ /** Last user message (for session list preview) */
1617
+ lastUserMessage?: string | null;
1618
+ }
1619
+ /**
1620
+ * Session message
1621
+ */
1622
+ interface SessionMessage {
1623
+ /** Message ID */
1624
+ id: string;
1625
+ /** Message role */
1626
+ role: 'user' | 'assistant' | 'system';
1627
+ /** Message content */
1628
+ content: string;
1629
+ /** Associated execution ID (for assistant messages) */
1630
+ executionUuid?: string;
1631
+ /** Message timestamp */
1632
+ timestamp: string;
1633
+ }
1634
+ /**
1635
+ * Session history with messages
1636
+ */
1637
+ interface SessionHistory {
1638
+ /** Session info */
1639
+ session: Session;
1640
+ /** Messages in chronological order */
1641
+ messages: SessionMessage[];
1642
+ }
1643
+ /**
1644
+ * Session list options
1645
+ */
1646
+ interface SessionListOptions extends ListOptions {
1647
+ /** Filter by agent */
1648
+ agentUuid?: string;
1649
+ }
1650
+ /**
1651
+ * Session create input
1652
+ */
1653
+ interface SessionCreateInput {
1654
+ /** Agent to associate with the session */
1655
+ agentUuid: string;
1656
+ /** Initial system message (optional) */
1657
+ systemMessage?: string;
1658
+ }
1659
+ /**
1660
+ * Send message input
1661
+ */
1662
+ interface SendMessageInput {
1663
+ /** Message content */
1664
+ message: string;
1665
+ /** Additional context */
1666
+ context?: Record<string, unknown>;
1667
+ /** Attachment UUIDs to include with the message (for images, documents, etc.) */
1668
+ attachmentIds?: string[];
1669
+ }
1670
+ /**
1671
+ * Session artifact type
1672
+ */
1673
+ type SessionArtifactType = 'file' | 'image' | 'code' | 'data' | 'log' | 'report';
1674
+ /**
1675
+ * Session artifact variant type
1676
+ */
1677
+ type SessionArtifactVariantType = 'original' | 'thumbnail';
1678
+ /**
1679
+ * Session artifact resource
1680
+ * Represents an artifact generated during a session execution
1681
+ */
1682
+ interface SessionArtifact {
1683
+ /** Unique identifier */
1684
+ uuid: string;
1685
+ /** Associated execution ID */
1686
+ executionId: string;
1687
+ /** Artifact type */
1688
+ type: SessionArtifactType;
1689
+ /** Variant type (original or thumbnail) */
1690
+ variantType: SessionArtifactVariantType;
1691
+ /** Original filename */
1692
+ filename: string;
1693
+ /** MIME type */
1694
+ mimeType: string;
1695
+ /** Size in bytes */
1696
+ size: number;
1697
+ /** Pre-signed URL for accessing the artifact */
1698
+ url: string;
1699
+ /** Thumbnail URL (for images) */
1700
+ thumbnailUrl?: string;
1701
+ /** Image dimensions (for images) */
1702
+ dimensions?: {
1703
+ width: number;
1704
+ height: number;
1705
+ };
1706
+ /** Description */
1707
+ description?: string | null;
1708
+ /** Additional metadata */
1709
+ metadata?: Record<string, unknown> | null;
1710
+ /** Creation timestamp */
1711
+ createdAt: string;
1712
+ }
1713
+ /**
1714
+ * Session artifact list options
1715
+ */
1716
+ interface SessionArtifactListOptions extends ListOptions {
1717
+ /** Filter by artifact type */
1718
+ type?: SessionArtifactType;
1719
+ /** Include thumbnail variants (default: false) */
1720
+ includeVariants?: boolean;
1721
+ }
1722
+
1723
+ /**
1724
+ * Base Resource API
1725
+ *
1726
+ * Abstract base class for all resource APIs.
1727
+ * Provides common HTTP methods and path handling.
1728
+ */
1729
+
1730
+ /**
1731
+ * Base Resource API class
1732
+ */
1733
+ declare abstract class BaseResourceAPI {
1734
+ protected readonly http: HttpClient;
1735
+ protected readonly basePath: string;
1736
+ constructor(http: HttpClient, basePath: string);
1737
+ /**
1738
+ * Build query parameters from list options
1739
+ */
1740
+ protected buildListQuery(options?: ListOptions): Record<string, string | number | boolean | undefined>;
1741
+ /**
1742
+ * HTTP GET request helper
1743
+ */
1744
+ protected httpGet<T>(path: string, query?: Record<string, string | number | boolean | undefined>): Promise<T>;
1745
+ /**
1746
+ * HTTP POST request helper
1747
+ */
1748
+ protected httpPost<T>(path: string, body?: unknown, options?: {
1749
+ idempotencyKey?: string;
1750
+ skipRetry?: boolean;
1751
+ }): Promise<T>;
1752
+ /**
1753
+ * HTTP PATCH request helper
1754
+ */
1755
+ protected httpPatch<T>(path: string, body?: unknown, options?: {
1756
+ idempotencyKey?: string;
1757
+ }): Promise<T>;
1758
+ /**
1759
+ * HTTP DELETE request helper
1760
+ */
1761
+ protected httpDelete<T>(path: string): Promise<T>;
1762
+ /**
1763
+ * List resources with pagination
1764
+ */
1765
+ protected listResources<T>(path: string, options?: ListOptions): Promise<PaginatedResponse<T>>;
1766
+ }
1767
+
1768
+ /**
1769
+ * Agents Resource API
1770
+ *
1771
+ * Provides all agent-related operations:
1772
+ * - List: list(), get()
1773
+ * - Execute: execute(), executeSync(), stream()
1774
+ * - Receive: getExecution()
1775
+ * - Edit: update(), updateConfig(), cancelExecution()
1776
+ */
1777
+
1778
+ /**
1779
+ * Agents API class
1780
+ */
1781
+ declare class AgentsAPI extends BaseResourceAPI {
1782
+ private readonly getStreamConfig;
1783
+ constructor(http: HttpClient, getStreamConfig: () => StreamConfig);
1784
+ /**
1785
+ * List all agents in the organization
1786
+ *
1787
+ * @param options - List options (pagination, filtering)
1788
+ * @returns Paginated list of agents
1789
+ *
1790
+ * @example
1791
+ * ```typescript
1792
+ * const { data: agents, pagination } = await client.agents.list({ limit: 10 });
1793
+ * ```
1794
+ */
1795
+ list(options?: AgentListOptions): Promise<PaginatedResponse<Agent>>;
1796
+ /**
1797
+ * Get a single agent by UUID
1798
+ *
1799
+ * @param uuid - Agent UUID
1800
+ * @returns Agent with configuration
1801
+ *
1802
+ * @example
1803
+ * ```typescript
1804
+ * const agent = await client.agents.get('agent-uuid');
1805
+ * console.log(agent.config);
1806
+ * ```
1807
+ */
1808
+ get(uuid: string): Promise<Agent>;
1809
+ /**
1810
+ * Start an agent execution (async)
1811
+ *
1812
+ * Returns immediately with execution ID. Use getExecution() to poll
1813
+ * for results, or use stream() for real-time updates.
1814
+ *
1815
+ * @param uuid - Agent UUID
1816
+ * @param input - Execution input (task, context, options)
1817
+ * @returns Execution ID and initial status
1818
+ *
1819
+ * @example
1820
+ * ```typescript
1821
+ * const { executionId, status } = await client.agents.execute('agent-uuid', {
1822
+ * task: 'Summarize the latest news about AI',
1823
+ * });
1824
+ * ```
1825
+ */
1826
+ execute(uuid: string, input: ExecuteInput): Promise<ExecuteResponse>;
1827
+ /**
1828
+ * Execute an agent and wait for completion (sync)
1829
+ *
1830
+ * Polls the execution status until completion or failure.
1831
+ *
1832
+ * @param uuid - Agent UUID
1833
+ * @param input - Execution input
1834
+ * @param pollInterval - Polling interval in ms (default: 1000)
1835
+ * @returns Final execution result
1836
+ *
1837
+ * @example
1838
+ * ```typescript
1839
+ * const execution = await client.agents.executeSync('agent-uuid', {
1840
+ * task: 'Write a haiku about coding',
1841
+ * });
1842
+ * console.log(execution.output);
1843
+ * ```
1844
+ */
1845
+ executeSync(uuid: string, input: ExecuteInput, pollInterval?: number): Promise<AgentExecution>;
1846
+ /**
1847
+ * Stream an agent execution
1848
+ *
1849
+ * Returns a StreamController for real-time event handling.
1850
+ *
1851
+ * @param uuid - Agent UUID
1852
+ * @param input - Execution input
1853
+ * @returns Stream controller for event handling
1854
+ *
1855
+ * @example
1856
+ * ```typescript
1857
+ * const stream = await client.agents.stream('agent-uuid', {
1858
+ * task: 'Research climate change',
1859
+ * });
1860
+ *
1861
+ * stream.on('log', (log) => console.log(log.title));
1862
+ * stream.on('toolCall', ({ toolName }) => console.log(`Calling ${toolName}`));
1863
+ * stream.on('complete', ({ execution }) => console.log(execution.output));
1864
+ *
1865
+ * const result = await stream.wait();
1866
+ * ```
1867
+ */
1868
+ stream(uuid: string, input: ExecuteInput): Promise<ExecutionStreamController>;
1869
+ /**
1870
+ * Connect to an existing execution's stream
1871
+ *
1872
+ * Use this when the execution was started externally (e.g., via tRPC for team executions)
1873
+ * and you need to connect to its SSE stream for real-time updates.
1874
+ *
1875
+ * @param executionId - Execution UUID (already running)
1876
+ * @param sessionId - Optional session ID for conversation continuity
1877
+ * @returns Stream controller for the execution
1878
+ *
1879
+ * @example
1880
+ * ```typescript
1881
+ * // Execution started via tRPC
1882
+ * const executionId = await trpc.executions.start.mutate({ teamUuid, task });
1883
+ *
1884
+ * // Connect to SSE stream for real-time updates
1885
+ * const stream = client.agents.streamExecution(executionId);
1886
+ *
1887
+ * stream.on('log', (log) => console.log(log.title));
1888
+ * stream.on('delegationStarted', (data) => console.log('Subagent:', data.targetAgentName));
1889
+ * stream.on('complete', ({ execution }) => console.log(execution.output));
1890
+ *
1891
+ * await stream.connect();
1892
+ * const result = await stream.wait();
1893
+ * ```
1894
+ */
1895
+ streamExecution(executionId: string, sessionId?: string): ExecutionStreamController;
1896
+ /**
1897
+ * Get execution result by ID
1898
+ *
1899
+ * @param executionId - Execution UUID
1900
+ * @returns Execution details including status, output, logs
1901
+ *
1902
+ * @example
1903
+ * ```typescript
1904
+ * const execution = await client.agents.getExecution('exec-uuid');
1905
+ * if (execution.status === 'completed') {
1906
+ * console.log(execution.output);
1907
+ * }
1908
+ * ```
1909
+ */
1910
+ getExecution(executionId: string): Promise<AgentExecution>;
1911
+ /**
1912
+ * Update agent details
1913
+ *
1914
+ * @param uuid - Agent UUID
1915
+ * @param data - Fields to update
1916
+ * @returns Updated agent
1917
+ *
1918
+ * @example
1919
+ * ```typescript
1920
+ * const agent = await client.agents.update('agent-uuid', {
1921
+ * name: 'My Updated Agent',
1922
+ * description: 'New description',
1923
+ * });
1924
+ * ```
1925
+ */
1926
+ update(uuid: string, data: AgentUpdateInput): Promise<Agent>;
1927
+ /**
1928
+ * Update agent configuration
1929
+ *
1930
+ * @param uuid - Agent UUID
1931
+ * @param config - Configuration fields to update
1932
+ * @returns Updated agent
1933
+ *
1934
+ * @example
1935
+ * ```typescript
1936
+ * const agent = await client.agents.updateConfig('agent-uuid', {
1937
+ * temperature: 0.7,
1938
+ * maxIterations: 5,
1939
+ * });
1940
+ * ```
1941
+ */
1942
+ updateConfig(uuid: string, config: AgentConfigUpdateInput): Promise<Agent>;
1943
+ /**
1944
+ * Cancel a running execution
1945
+ *
1946
+ * @param executionId - Execution UUID
1947
+ * @returns Updated execution with cancelled status
1948
+ *
1949
+ * @example
1950
+ * ```typescript
1951
+ * const execution = await client.agents.cancelExecution('exec-uuid');
1952
+ * console.log(execution.status); // 'cancelled'
1953
+ * ```
1954
+ */
1955
+ cancelExecution(executionId: string): Promise<AgentExecution>;
1956
+ /**
1957
+ * Poll execution until completion
1958
+ */
1959
+ private pollExecution;
1960
+ }
1961
+ /**
1962
+ * Stream configuration passed from client
1963
+ */
1964
+ interface StreamConfig {
1965
+ baseUrl: string;
1966
+ apiKey?: string;
1967
+ token?: string;
1968
+ tokenProvider?: () => Promise<string>;
1969
+ orgId: number;
1970
+ }
1971
+
1972
+ /**
1973
+ * Skills Resource API
1974
+ *
1975
+ * Provides all skill-related operations:
1976
+ * - List: list(), get(), getTools()
1977
+ * - Execute: execute()
1978
+ * - Receive: getExecution()
1979
+ * - Edit: update(), updatePrompt()
1980
+ */
1981
+
1982
+ /**
1983
+ * Skills API class
1984
+ */
1985
+ declare class SkillsAPI extends BaseResourceAPI {
1986
+ constructor(http: HttpClient);
1987
+ /**
1988
+ * List all skills in the organization
1989
+ *
1990
+ * @param options - List options (pagination, filtering by category/tags)
1991
+ * @returns Paginated list of skills
1992
+ *
1993
+ * @example
1994
+ * ```typescript
1995
+ * const { data: skills } = await client.skills.list({
1996
+ * category: 'writing',
1997
+ * tags: ['seo', 'blog'],
1998
+ * });
1999
+ * ```
2000
+ */
2001
+ list(options?: SkillListOptions): Promise<PaginatedResponse<Skill>>;
2002
+ /**
2003
+ * Get a single skill by UUID with full details
2004
+ *
2005
+ * @param uuid - Skill UUID
2006
+ * @returns Skill with prompt template and tools
2007
+ *
2008
+ * @example
2009
+ * ```typescript
2010
+ * const skill = await client.skills.get('skill-uuid');
2011
+ * console.log(skill.promptTemplate);
2012
+ * ```
2013
+ */
2014
+ get(uuid: string): Promise<SkillDetails>;
2015
+ /**
2016
+ * Get tools associated with a skill
2017
+ *
2018
+ * @param uuid - Skill UUID
2019
+ * @returns Array of tools used by the skill
2020
+ *
2021
+ * @example
2022
+ * ```typescript
2023
+ * const tools = await client.skills.getTools('skill-uuid');
2024
+ * tools.forEach(tool => console.log(tool.name));
2025
+ * ```
2026
+ */
2027
+ getTools(uuid: string): Promise<SkillTool[]>;
2028
+ /**
2029
+ * Execute a skill with variables
2030
+ *
2031
+ * @param uuid - Skill UUID
2032
+ * @param input - Variables and context for execution
2033
+ * @returns Skill execution result
2034
+ *
2035
+ * @example
2036
+ * ```typescript
2037
+ * const result = await client.skills.execute('skill-uuid', {
2038
+ * variables: {
2039
+ * topic: 'AI in healthcare',
2040
+ * tone: 'professional',
2041
+ * },
2042
+ * });
2043
+ * console.log(result.output);
2044
+ * ```
2045
+ */
2046
+ execute(uuid: string, input: SkillExecuteInput): Promise<SkillExecution>;
2047
+ /**
2048
+ * Get skill execution result by ID
2049
+ *
2050
+ * @param executionId - Execution UUID
2051
+ * @returns Skill execution details
2052
+ *
2053
+ * @example
2054
+ * ```typescript
2055
+ * const execution = await client.skills.getExecution('exec-uuid');
2056
+ * ```
2057
+ */
2058
+ getExecution(executionId: string): Promise<SkillExecution>;
2059
+ /**
2060
+ * Update skill details
2061
+ *
2062
+ * @param uuid - Skill UUID
2063
+ * @param data - Fields to update
2064
+ * @returns Updated skill
2065
+ *
2066
+ * @example
2067
+ * ```typescript
2068
+ * const skill = await client.skills.update('skill-uuid', {
2069
+ * name: 'Updated Skill Name',
2070
+ * tags: ['new-tag'],
2071
+ * });
2072
+ * ```
2073
+ */
2074
+ update(uuid: string, data: SkillUpdateInput): Promise<Skill>;
2075
+ /**
2076
+ * Update skill prompt template
2077
+ *
2078
+ * @param uuid - Skill UUID
2079
+ * @param prompt - New prompt template
2080
+ * @returns Updated skill with new version
2081
+ *
2082
+ * @example
2083
+ * ```typescript
2084
+ * const skill = await client.skills.updatePrompt('skill-uuid',
2085
+ * 'Write a {{tone}} article about {{topic}}...'
2086
+ * );
2087
+ * console.log(skill.version); // Version incremented
2088
+ * ```
2089
+ */
2090
+ updatePrompt(uuid: string, prompt: string): Promise<SkillDetails>;
2091
+ }
2092
+
2093
+ /**
2094
+ * Tools Resource API
2095
+ *
2096
+ * Provides all tool-related operations:
2097
+ * - List: list(), get()
2098
+ * - Execute: execute(), validateInput()
2099
+ * - Receive: getExecution()
2100
+ * - Edit: update(), updateConfig()
2101
+ */
2102
+
2103
+ /**
2104
+ * Tools API class
2105
+ */
2106
+ declare class ToolsAPI extends BaseResourceAPI {
2107
+ constructor(http: HttpClient);
2108
+ /**
2109
+ * List all tools in the organization
2110
+ *
2111
+ * @param options - List options (pagination, filtering)
2112
+ * @returns Paginated list of tools
2113
+ *
2114
+ * @example
2115
+ * ```typescript
2116
+ * const { data: tools } = await client.tools.list({
2117
+ * category: 'data',
2118
+ * isEnabled: true,
2119
+ * });
2120
+ * ```
2121
+ */
2122
+ list(options?: ToolListOptions): Promise<PaginatedResponse<Tool>>;
2123
+ /**
2124
+ * Get a single tool by UUID with schema
2125
+ *
2126
+ * @param uuid - Tool UUID
2127
+ * @returns Tool with input/output schemas
2128
+ *
2129
+ * @example
2130
+ * ```typescript
2131
+ * const tool = await client.tools.get('tool-uuid');
2132
+ * console.log(tool.inputSchema);
2133
+ * ```
2134
+ */
2135
+ get(uuid: string): Promise<Tool>;
2136
+ /**
2137
+ * Execute a tool directly
2138
+ *
2139
+ * @param uuid - Tool UUID
2140
+ * @param input - Tool input (validated against inputSchema)
2141
+ * @returns Tool execution result
2142
+ *
2143
+ * @example
2144
+ * ```typescript
2145
+ * const result = await client.tools.execute('tool-uuid', {
2146
+ * query: 'weather in London',
2147
+ * limit: 5,
2148
+ * });
2149
+ * console.log(result.output);
2150
+ * ```
2151
+ */
2152
+ execute(uuid: string, input: Record<string, unknown>): Promise<ToolExecution>;
2153
+ /**
2154
+ * Validate input against tool schema
2155
+ *
2156
+ * @param uuid - Tool UUID
2157
+ * @param input - Input to validate
2158
+ * @returns Validation result with errors if invalid
2159
+ *
2160
+ * @example
2161
+ * ```typescript
2162
+ * const validation = await client.tools.validateInput('tool-uuid', {
2163
+ * query: 'test',
2164
+ * });
2165
+ * if (!validation.valid) {
2166
+ * console.log(validation.errors);
2167
+ * }
2168
+ * ```
2169
+ */
2170
+ validateInput(uuid: string, input: Record<string, unknown>): Promise<ToolValidationResult>;
2171
+ /**
2172
+ * Get tool execution result by ID
2173
+ *
2174
+ * @param executionId - Execution UUID
2175
+ * @returns Tool execution details
2176
+ *
2177
+ * @example
2178
+ * ```typescript
2179
+ * const execution = await client.tools.getExecution('exec-uuid');
2180
+ * ```
2181
+ */
2182
+ getExecution(executionId: string): Promise<ToolExecution>;
2183
+ /**
2184
+ * Update tool details
2185
+ *
2186
+ * @param uuid - Tool UUID
2187
+ * @param data - Fields to update
2188
+ * @returns Updated tool
2189
+ *
2190
+ * @example
2191
+ * ```typescript
2192
+ * const tool = await client.tools.update('tool-uuid', {
2193
+ * name: 'Updated Tool Name',
2194
+ * description: 'New description',
2195
+ * });
2196
+ * ```
2197
+ */
2198
+ update(uuid: string, data: ToolUpdateInput): Promise<Tool>;
2199
+ /**
2200
+ * Update tool configuration
2201
+ *
2202
+ * @param uuid - Tool UUID
2203
+ * @param config - Configuration to update
2204
+ * @returns Updated tool
2205
+ *
2206
+ * @example
2207
+ * ```typescript
2208
+ * const tool = await client.tools.updateConfig('tool-uuid', {
2209
+ * isEnabled: false,
2210
+ * config: { apiKey: 'new-key' },
2211
+ * });
2212
+ * ```
2213
+ */
2214
+ updateConfig(uuid: string, config: ToolConfigUpdateInput): Promise<Tool>;
2215
+ }
2216
+
2217
+ /**
2218
+ * Artifacts Resource API
2219
+ *
2220
+ * Provides all artifact-related operations:
2221
+ * - List: list(), get()
2222
+ * - Receive: download(), downloadStream(), getSignedUrl()
2223
+ * - Edit: upload(), delete()
2224
+ */
2225
+
2226
+ /**
2227
+ * Artifacts API class
2228
+ */
2229
+ declare class ArtifactsAPI extends BaseResourceAPI {
2230
+ constructor(http: HttpClient);
2231
+ /**
2232
+ * List artifacts for an execution
2233
+ *
2234
+ * @param executionId - Execution UUID
2235
+ * @param options - List options (pagination, filtering by type)
2236
+ * @returns Paginated list of artifacts
2237
+ *
2238
+ * @example
2239
+ * ```typescript
2240
+ * const { data: artifacts } = await client.artifacts.list('exec-uuid', {
2241
+ * type: 'file',
2242
+ * });
2243
+ * ```
2244
+ */
2245
+ list(executionId: string, options?: ArtifactListOptions): Promise<PaginatedResponse<Artifact>>;
2246
+ /**
2247
+ * Get artifact metadata by UUID
2248
+ *
2249
+ * @param uuid - Artifact UUID
2250
+ * @returns Artifact metadata
2251
+ *
2252
+ * @example
2253
+ * ```typescript
2254
+ * const artifact = await client.artifacts.get('artifact-uuid');
2255
+ * console.log(artifact.name, artifact.size);
2256
+ * ```
2257
+ */
2258
+ get(uuid: string): Promise<Artifact>;
2259
+ /**
2260
+ * Download artifact content
2261
+ *
2262
+ * In Node.js returns Buffer, in browser returns Blob.
2263
+ *
2264
+ * @param uuid - Artifact UUID
2265
+ * @returns Artifact content as Buffer (Node.js) or Blob (browser)
2266
+ *
2267
+ * @example
2268
+ * ```typescript
2269
+ * const content = await client.artifacts.download('artifact-uuid');
2270
+ * // Node.js: Buffer
2271
+ * // Browser: Blob
2272
+ * ```
2273
+ */
2274
+ download(uuid: string): Promise<Buffer | Blob>;
2275
+ /**
2276
+ * Download artifact as a stream
2277
+ *
2278
+ * In Node.js returns Readable stream, in browser returns ReadableStream.
2279
+ *
2280
+ * @param uuid - Artifact UUID
2281
+ * @returns Readable stream
2282
+ *
2283
+ * @example
2284
+ * ```typescript
2285
+ * const stream = await client.artifacts.downloadStream('artifact-uuid');
2286
+ * // Pipe to file or process incrementally
2287
+ * ```
2288
+ */
2289
+ downloadStream(uuid: string): Promise<ReadableStream<Uint8Array>>;
2290
+ /**
2291
+ * Get a signed URL for direct download
2292
+ *
2293
+ * @param uuid - Artifact UUID
2294
+ * @param options - Options including expiration time
2295
+ * @returns Signed URL and expiration time
2296
+ *
2297
+ * @example
2298
+ * ```typescript
2299
+ * const { url, expiresAt } = await client.artifacts.getSignedUrl('artifact-uuid', {
2300
+ * expiresIn: 3600, // 1 hour
2301
+ * });
2302
+ * // Use URL for direct download
2303
+ * ```
2304
+ */
2305
+ getSignedUrl(uuid: string, options?: ArtifactDownloadOptions): Promise<SignedUrlResponse>;
2306
+ /**
2307
+ * Upload a new artifact for an execution
2308
+ *
2309
+ * @param executionId - Execution UUID
2310
+ * @param input - Upload input (name, content, mime type)
2311
+ * @returns Created artifact metadata
2312
+ *
2313
+ * @example
2314
+ * ```typescript
2315
+ * const artifact = await client.artifacts.upload('exec-uuid', {
2316
+ * name: 'report.pdf',
2317
+ * content: fileBuffer,
2318
+ * mimeType: 'application/pdf',
2319
+ * });
2320
+ * ```
2321
+ */
2322
+ upload(executionId: string, input: ArtifactUploadInput): Promise<Artifact>;
2323
+ /**
2324
+ * Delete an artifact
2325
+ *
2326
+ * @param uuid - Artifact UUID
2327
+ *
2328
+ * @example
2329
+ * ```typescript
2330
+ * await client.artifacts.delete('artifact-uuid');
2331
+ * ```
2332
+ */
2333
+ delete(uuid: string): Promise<void>;
2334
+ }
2335
+
2336
+ /**
2337
+ * Sessions Resource API
2338
+ *
2339
+ * Provides all session-related operations:
2340
+ * - List: list(), get()
2341
+ * - Execute: sendMessage(), stream()
2342
+ * - Receive: getHistory(), listArtifacts()
2343
+ * - Edit: create(), delete()
2344
+ */
2345
+
2346
+ /**
2347
+ * Sessions API class
2348
+ */
2349
+ declare class SessionsAPI extends BaseResourceAPI {
2350
+ private readonly getStreamConfig;
2351
+ constructor(http: HttpClient, getStreamConfig: () => StreamConfig);
2352
+ /**
2353
+ * List all sessions in the organization
2354
+ *
2355
+ * @param options - List options (pagination, filtering by agent)
2356
+ * @returns Paginated list of sessions
2357
+ *
2358
+ * @example
2359
+ * ```typescript
2360
+ * const { data: sessions } = await client.sessions.list({
2361
+ * agentUuid: 'agent-uuid',
2362
+ * });
2363
+ * ```
2364
+ */
2365
+ list(options?: SessionListOptions): Promise<PaginatedResponse<Session>>;
2366
+ /**
2367
+ * Get session details by ID
2368
+ *
2369
+ * @param sessionId - Session ID
2370
+ * @returns Session details
2371
+ *
2372
+ * @example
2373
+ * ```typescript
2374
+ * const session = await client.sessions.get('session-id');
2375
+ * console.log(session.messageCount);
2376
+ * ```
2377
+ */
2378
+ get(sessionId: string): Promise<Session>;
2379
+ /**
2380
+ * Send a message to a session
2381
+ *
2382
+ * Triggers an agent execution in the context of the session.
2383
+ * Returns immediately with execution ID. Use getHistory() to get
2384
+ * the response, or use stream() for real-time updates.
2385
+ *
2386
+ * @param sessionId - Session ID
2387
+ * @param input - Message content and optional context
2388
+ * @returns Execution ID and status
2389
+ *
2390
+ * @example
2391
+ * ```typescript
2392
+ * const { executionId } = await client.sessions.sendMessage('session-id', {
2393
+ * message: 'What is the capital of France?',
2394
+ * });
2395
+ * ```
2396
+ */
2397
+ sendMessage(sessionId: string, input: SendMessageInput): Promise<ExecuteResponse>;
2398
+ /**
2399
+ * Send a message and wait for response (sync)
2400
+ *
2401
+ * @param sessionId - Session ID
2402
+ * @param input - Message content and optional context
2403
+ * @param pollInterval - Polling interval in ms (default: 1000)
2404
+ * @returns Final execution result
2405
+ *
2406
+ * @example
2407
+ * ```typescript
2408
+ * const execution = await client.sessions.sendMessageSync('session-id', {
2409
+ * message: 'What is the capital of France?',
2410
+ * });
2411
+ * console.log(execution.output);
2412
+ * ```
2413
+ */
2414
+ sendMessageSync(sessionId: string, input: SendMessageInput, pollInterval?: number): Promise<AgentExecution>;
2415
+ /**
2416
+ * Stream a message response
2417
+ *
2418
+ * Returns a StreamController for real-time event handling.
2419
+ *
2420
+ * @param sessionId - Session ID
2421
+ * @param input - Message content and optional context
2422
+ * @returns Stream controller
2423
+ *
2424
+ * @example
2425
+ * ```typescript
2426
+ * const stream = await client.sessions.stream('session-id', {
2427
+ * message: 'Tell me more about that',
2428
+ * });
2429
+ *
2430
+ * stream.on('log', (log) => console.log(log.title));
2431
+ * stream.on('complete', ({ execution }) => console.log(execution.output));
2432
+ *
2433
+ * const result = await stream.wait();
2434
+ * ```
2435
+ */
2436
+ stream(sessionId: string, input: SendMessageInput): Promise<ExecutionStreamController>;
2437
+ /**
2438
+ * Get session conversation history
2439
+ *
2440
+ * @param sessionId - Session ID
2441
+ * @returns Session with all messages
2442
+ *
2443
+ * @example
2444
+ * ```typescript
2445
+ * const history = await client.sessions.getHistory('session-id');
2446
+ * history.messages.forEach(msg => {
2447
+ * console.log(`${msg.role}: ${msg.content}`);
2448
+ * });
2449
+ * ```
2450
+ */
2451
+ getHistory(sessionId: string): Promise<SessionHistory>;
2452
+ /**
2453
+ * List artifacts for a session
2454
+ *
2455
+ * Returns all artifacts generated across all executions in the session.
2456
+ * Useful for retrieving images, files, and other outputs created during
2457
+ * agent interactions.
2458
+ *
2459
+ * @param sessionId - Session ID
2460
+ * @param options - List options (filtering by type, pagination)
2461
+ * @returns Paginated list of session artifacts
2462
+ *
2463
+ * @example
2464
+ * ```typescript
2465
+ * // Get all images from a session
2466
+ * const { data: artifacts } = await client.sessions.listArtifacts('session-id', {
2467
+ * type: 'image',
2468
+ * });
2469
+ *
2470
+ * artifacts.forEach(artifact => {
2471
+ * console.log(artifact.filename, artifact.url);
2472
+ * });
2473
+ * ```
2474
+ */
2475
+ listArtifacts(sessionId: string, options?: SessionArtifactListOptions): Promise<PaginatedResponse<SessionArtifact>>;
2476
+ /**
2477
+ * Get execution result
2478
+ */
2479
+ private getExecution;
2480
+ /**
2481
+ * Create a new session for an agent
2482
+ *
2483
+ * @param agentUuid - Agent UUID to associate with session
2484
+ * @param options - Optional system message
2485
+ * @returns Created session
2486
+ *
2487
+ * @example
2488
+ * ```typescript
2489
+ * const session = await client.sessions.create({
2490
+ * agentUuid: 'agent-uuid',
2491
+ * systemMessage: 'You are a helpful assistant.',
2492
+ * });
2493
+ * console.log(session.id);
2494
+ * ```
2495
+ */
2496
+ create(input: SessionCreateInput): Promise<Session>;
2497
+ /**
2498
+ * Delete a session and all its messages
2499
+ *
2500
+ * @param sessionId - Session ID
2501
+ *
2502
+ * @example
2503
+ * ```typescript
2504
+ * await client.sessions.delete('session-id');
2505
+ * ```
2506
+ */
2507
+ delete(sessionId: string): Promise<void>;
2508
+ /**
2509
+ * Poll execution until completion
2510
+ */
2511
+ private pollExecution;
2512
+ }
2513
+
2514
+ /**
2515
+ * AI SaaS Client
2516
+ *
2517
+ * Main entry point for the SDK. Provides access to all resource APIs.
2518
+ *
2519
+ * @example
2520
+ * ```typescript
2521
+ * import { AISaaSClient } from '@cadraos/sdk';
2522
+ *
2523
+ * const client = new AISaaSClient({
2524
+ * apiKey: process.env.AISAAS_API_KEY,
2525
+ * orgId: Number(process.env.AISAAS_ORG_ID),
2526
+ * });
2527
+ *
2528
+ * // List agents
2529
+ * const { data: agents } = await client.agents.list();
2530
+ *
2531
+ * // Execute an agent
2532
+ * const execution = await client.agents.executeSync(agents[0].uuid, {
2533
+ * task: 'Summarize the latest news',
2534
+ * });
2535
+ *
2536
+ * // Stream an agent execution
2537
+ * const stream = await client.agents.stream(agents[0].uuid, {
2538
+ * task: 'Research climate change',
2539
+ * });
2540
+ *
2541
+ * stream.on('log', (log) => console.log(log.title));
2542
+ * stream.on('complete', ({ execution }) => console.log(execution.output));
2543
+ *
2544
+ * const result = await stream.wait();
2545
+ * ```
2546
+ */
2547
+
345
2548
  /**
346
- * Data for agent clarification requests (ask_user tool)
2549
+ * Client options for API key authentication
347
2550
  */
348
- interface ClarificationData {
349
- /** The question being asked */
350
- question: string;
351
- /** Optional reason for asking */
352
- reason?: string;
353
- /** Suggested response options */
354
- suggestedOptions?: string[];
2551
+ interface AISaaSClientOptionsApiKey {
2552
+ /** API key for authentication */
2553
+ apiKey: string;
2554
+ /** Organization ID */
2555
+ orgId: number;
2556
+ /** Base URL for API (default: https://api.aisaas.com/v1) */
2557
+ baseUrl?: string;
2558
+ /** Request timeout in milliseconds (default: 30000) */
2559
+ timeout?: number;
2560
+ /** Maximum retry attempts (default: 3) */
2561
+ maxRetries?: number;
2562
+ /** Custom headers to include in all requests */
2563
+ headers?: Record<string, string>;
355
2564
  }
356
2565
  /**
357
- * Todo item for agent task lists
2566
+ * Client options for OAuth token authentication
358
2567
  */
359
- interface TodoItem {
360
- /** Task description (imperative form) */
361
- content: string;
362
- /** Current status */
363
- status: "pending" | "in_progress" | "completed";
364
- /** Present continuous form for active display */
365
- activeForm: string;
2568
+ interface AISaaSClientOptionsToken {
2569
+ /** OAuth token for authentication */
2570
+ token: string;
2571
+ /** Organization ID */
2572
+ orgId: number;
2573
+ /** Base URL for API (default: https://api.aisaas.com/v1) */
2574
+ baseUrl?: string;
2575
+ /** Request timeout in milliseconds (default: 30000) */
2576
+ timeout?: number;
2577
+ /** Maximum retry attempts (default: 3) */
2578
+ maxRetries?: number;
2579
+ /** Custom headers to include in all requests */
2580
+ headers?: Record<string, string>;
366
2581
  }
367
2582
  /**
368
- * SSE stream event from agent execution
2583
+ * Client options for token provider authentication
369
2584
  */
370
- interface ExecutionStreamEvent {
371
- /** Event type */
372
- type: string;
373
- /** Unique event ID for deduplication */
374
- id: string;
375
- /** ISO timestamp */
376
- timestamp: string;
377
- /** Event data payload */
378
- data: {
379
- type?: string;
380
- log?: {
381
- stepIndex: number;
382
- logType: string;
383
- message: string;
384
- metadata: Record<string, unknown>;
385
- timestamp: string;
386
- durationMs?: number;
387
- };
388
- executionId?: string;
389
- toolName?: string;
390
- args?: unknown;
391
- iteration?: number;
392
- tokenUsage?: {
393
- prompt: number;
394
- completion: number;
395
- total: number;
396
- };
397
- cost?: number;
398
- error?: string;
399
- question?: string;
400
- reason?: string;
401
- suggestedOptions?: string[];
402
- redisAvailable?: boolean;
403
- [key: string]: unknown;
404
- };
2585
+ interface AISaaSClientOptionsTokenProvider {
2586
+ /** Token provider callback (called before each request) */
2587
+ tokenProvider: () => Promise<string>;
2588
+ /** Organization ID */
2589
+ orgId: number;
2590
+ /** Base URL for API (default: https://api.aisaas.com/v1) */
2591
+ baseUrl?: string;
2592
+ /** Request timeout in milliseconds (default: 30000) */
2593
+ timeout?: number;
2594
+ /** Maximum retry attempts (default: 3) */
2595
+ maxRetries?: number;
2596
+ /** Custom headers to include in all requests */
2597
+ headers?: Record<string, string>;
405
2598
  }
406
2599
  /**
407
- * Theme mode options
2600
+ * All client options
408
2601
  */
409
- type ThemeMode = "light" | "dark" | "system";
2602
+ type AISaaSClientOptions = AISaaSClientOptionsApiKey | AISaaSClientOptionsToken | AISaaSClientOptionsTokenProvider;
410
2603
  /**
411
- * Attachment file for upload
2604
+ * AI SaaS Client
2605
+ *
2606
+ * Main class for interacting with the AI SaaS API.
2607
+ * Provides access to all resource APIs (agents, skills, tools, artifacts, sessions).
412
2608
  */
413
- interface AttachmentFile {
414
- /** File UUID after upload */
415
- uuid: string;
416
- /** Original file object */
417
- file: File;
418
- /** Upload status */
419
- status: "pending" | "uploading" | "ready" | "failed";
420
- /** Preview URL for local display */
421
- previewUrl?: string;
422
- /** Progress percentage (0-100) */
423
- progress?: number;
424
- }
425
-
426
- interface AgentChatProps {
427
- /** The UUID of the agent to chat with */
428
- agentId: string;
2609
+ declare class AISaaSClient {
2610
+ private readonly httpClient;
2611
+ private readonly config;
429
2612
  /**
430
- * Session ID to resume an existing conversation
431
- * When provided, the component will load the session's chat history
2613
+ * Agent operations (list, execute, stream, update)
432
2614
  */
433
- sessionId?: string;
434
- /** Custom adapter (optional - uses context if not provided) */
435
- adapter?: ChatAdapter;
436
- /** Callback fired when a new message is added */
437
- onMessage?: (message: ChatMessage$1) => void;
438
- /** Callback fired when an error occurs */
439
- onError?: (error: ChatError) => void;
2615
+ readonly agents: AgentsAPI;
440
2616
  /**
441
- * Callback fired when a new session is created
442
- * Called with the sessionId when starting a new chat (no existing sessionId)
443
- * Useful for updating external state like session lists
2617
+ * Skill operations (list, get, execute, update)
444
2618
  */
445
- onSessionCreated?: (sessionId: string) => void;
446
- /** @deprecated Use onSessionCreated instead */
447
- onSessionStart?: (sessionId: string) => void;
448
- /** Callback fired when a tool is called */
449
- onToolCall?: (toolName: string, args: unknown) => void;
450
- /** Callback fired when clarification is needed */
451
- onClarification?: (data: ClarificationData) => void;
452
- /** Initial messages to populate the chat */
453
- initialMessages?: ChatMessage$1[];
454
- /** Placeholder text for the input */
455
- placeholder?: string;
456
- /** Welcome message shown when chat is empty */
457
- welcomeMessage?: string;
458
- /** Maximum height of the chat container */
459
- maxHeight?: string | number;
460
- /** Additional CSS class for the container */
461
- className?: string;
462
- /** Theme mode */
463
- theme?: ThemeMode;
464
- /** Enable file attachments (future feature) */
465
- enableAttachments?: boolean;
466
- /** Enable markdown rendering */
467
- enableMarkdown?: boolean;
468
- /** Show tool call visualization */
469
- showToolCalls?: boolean;
2619
+ readonly skills: SkillsAPI;
2620
+ /**
2621
+ * Tool operations (list, get, execute, validate, update)
2622
+ */
2623
+ readonly tools: ToolsAPI;
2624
+ /**
2625
+ * Artifact operations (list, get, download, upload, delete)
2626
+ */
2627
+ readonly artifacts: ArtifactsAPI;
2628
+ /**
2629
+ * Session operations (list, get, create, message, delete)
2630
+ */
2631
+ readonly sessions: SessionsAPI;
2632
+ /**
2633
+ * Create a new AI SaaS client
2634
+ *
2635
+ * @param options - Client configuration options
2636
+ *
2637
+ * @example
2638
+ * ```typescript
2639
+ * // API key authentication
2640
+ * const client = new AISaaSClient({
2641
+ * apiKey: 'sk_...',
2642
+ * orgId: 123,
2643
+ * });
2644
+ *
2645
+ * // OAuth token authentication
2646
+ * const client = new AISaaSClient({
2647
+ * token: 'eyJ...',
2648
+ * orgId: 123,
2649
+ * });
2650
+ *
2651
+ * // Token provider (for automatic refresh)
2652
+ * const client = new AISaaSClient({
2653
+ * tokenProvider: async () => myAuth.getAccessToken(),
2654
+ * orgId: 123,
2655
+ * });
2656
+ * ```
2657
+ */
2658
+ constructor(options: AISaaSClientOptions);
2659
+ /**
2660
+ * Validate client options
2661
+ */
2662
+ private validateOptions;
470
2663
  }
471
- /**
472
- * Complete chat interface for interacting with AI agents
473
- *
474
- * @example
475
- * ```tsx
476
- * // With ChatConfigProvider (recommended for API key users)
477
- * <ChatConfigProvider config={{ baseUrl: '...', apiKey: '...' }}>
478
- * <AgentChat
479
- * agentId="agent-uuid"
480
- * onMessage={(msg) => console.log('New message:', msg)}
481
- * />
482
- * </ChatConfigProvider>
483
- *
484
- * // With custom adapter
485
- * <AgentChat
486
- * agentId="agent-uuid"
487
- * adapter={myCustomAdapter}
488
- * />
489
- * ```
490
- */
491
- declare function AgentChat({ agentId, sessionId, adapter, onMessage, onError, onSessionCreated, onSessionStart, onToolCall, onClarification, initialMessages, placeholder, welcomeMessage, maxHeight, className, theme, enableAttachments, enableMarkdown, showToolCalls, }: AgentChatProps): react_jsx_runtime.JSX.Element;
492
2664
 
493
2665
  /**
494
- * Default HTTP adapter for ChatAdapter
2666
+ * Default adapter for ChatAdapter — thin wrapper around AISaaSClient
495
2667
  *
496
- * Uses the AI SaaS External API for all operations.
2668
+ * Uses the AISaaSClient for all operations, providing proper auth,
2669
+ * retries, and streaming support out of the box.
497
2670
  *
498
2671
  * @module @cadraos/sdk/chat
499
2672
  */
@@ -502,37 +2675,49 @@ declare function AgentChat({ agentId, sessionId, adapter, onMessage, onError, on
502
2675
  * Configuration for the default HTTP adapter
503
2676
  */
504
2677
  interface DefaultAdapterConfig {
2678
+ /**
2679
+ * Pre-constructed AISaaSClient (takes priority over individual options)
2680
+ */
2681
+ client?: AISaaSClient;
505
2682
  /**
506
2683
  * Base URL for the API
507
- * @example "https://api.example.com/api/v1/external"
2684
+ * @example "https://api.example.com/v1"
508
2685
  */
509
- baseUrl: string;
2686
+ baseUrl?: string;
510
2687
  /**
511
2688
  * API key for authentication
512
2689
  */
513
2690
  apiKey?: string;
514
2691
  /**
515
- * Organization ID for multi-tenant access
2692
+ * OAuth token for authentication
516
2693
  */
517
- orgId?: number;
2694
+ token?: string;
518
2695
  /**
519
- * Custom fetch function (for testing or custom HTTP clients)
2696
+ * Token provider callback for dynamic auth
520
2697
  */
521
- fetch?: typeof fetch;
2698
+ tokenProvider?: () => Promise<string>;
2699
+ /**
2700
+ * Organization ID for multi-tenant access
2701
+ */
2702
+ orgId?: number;
522
2703
  }
523
2704
  /**
524
- * Create a default HTTP adapter for the Chat component
2705
+ * Create a default adapter that wraps AISaaSClient
525
2706
  *
526
2707
  * @param config - Adapter configuration
527
- * @returns ChatAdapter implementation
2708
+ * @returns ChatAdapter implementation backed by AISaaSClient
528
2709
  *
529
2710
  * @example
530
2711
  * ```typescript
2712
+ * // With individual options
531
2713
  * const adapter = createDefaultAdapter({
532
- * baseUrl: 'https://api.example.com/api/v1/external',
2714
+ * baseUrl: 'https://api.example.com/v1',
533
2715
  * apiKey: 'your-api-key',
534
2716
  * orgId: 123,
535
2717
  * });
2718
+ *
2719
+ * // With pre-constructed client
2720
+ * const adapter = createDefaultAdapter({ client: myClient });
536
2721
  * ```
537
2722
  */
538
2723
  declare function createDefaultAdapter(config: DefaultAdapterConfig): ChatAdapter;
@@ -549,7 +2734,7 @@ interface ChatConfigProviderProps {
549
2734
  /**
550
2735
  * Child components
551
2736
  */
552
- children: React.ReactNode;
2737
+ children: React$1.ReactNode;
553
2738
  }
554
2739
  /**
555
2740
  * Provider component that configures the default adapter for all child AgentChat components
@@ -587,8 +2772,13 @@ declare function useChatConfig(): ChatConfigContextValue;
587
2772
  declare function useChatConfigOptional(): ChatConfigContextValue | null;
588
2773
 
589
2774
  interface UseAgentChatOptions {
590
- /** UUID of the agent to chat with */
591
- agentId: string;
2775
+ /**
2776
+ * UUID of the agent to chat with.
2777
+ * Optional when teamId is provided (team execution routes to team's lead orchestrator).
2778
+ */
2779
+ agentId?: string;
2780
+ /** Optional team UUID for team-based execution (routes to team's lead orchestrator) */
2781
+ teamId?: string;
592
2782
  /**
593
2783
  * Session ID to resume an existing conversation
594
2784
  * If provided, the hook will attempt to load the session history on mount
@@ -612,6 +2802,8 @@ interface UseAgentChatOptions {
612
2802
  onSessionStart?: (sessionId: string) => void;
613
2803
  /** Callback fired when a tool is called */
614
2804
  onToolCall?: (toolName: string, args: unknown) => void;
2805
+ /** Callback fired when a tool result is received */
2806
+ onToolResult?: (toolName: string, result: unknown, durationMs?: number) => void;
615
2807
  /** Callback fired when clarification is needed */
616
2808
  onClarification?: (data: ClarificationData) => void;
617
2809
  }
@@ -649,6 +2841,27 @@ interface UseAgentChatResult {
649
2841
  */
650
2842
  loadSession: (sessionId: string) => Promise<void>;
651
2843
  }
2844
+ /**
2845
+ * Main hook for managing chat state and interactions
2846
+ *
2847
+ * @example
2848
+ * ```typescript
2849
+ * const {
2850
+ * messages,
2851
+ * isLoading,
2852
+ * isStreaming,
2853
+ * sendMessage,
2854
+ * error,
2855
+ * } = useAgentChat({
2856
+ * agentId: 'agent-uuid',
2857
+ * adapter: myAdapter,
2858
+ * onMessage: (msg) => console.log('New message:', msg),
2859
+ * });
2860
+ *
2861
+ * // Send a message
2862
+ * await sendMessage('Hello, agent!');
2863
+ * ```
2864
+ */
652
2865
  declare function useAgentChat(options: UseAgentChatOptions): UseAgentChatResult;
653
2866
 
654
2867
  interface UseExecutionStreamOptions {
@@ -700,6 +2913,11 @@ interface UseExecutionStreamResult {
700
2913
  /**
701
2914
  * Hook for streaming agent execution events via SSE
702
2915
  *
2916
+ * @deprecated Prefer using `adapter.createStream()` which provides
2917
+ * fetch-based SSE with auth headers, automatic reconnection, and
2918
+ * polling fallback. This hook is kept for backward compatibility
2919
+ * with adapters that only implement `getStreamUrl`.
2920
+ *
703
2921
  * @example
704
2922
  * ```typescript
705
2923
  * const { isConnected, disconnect } = useExecutionStream({
@@ -714,7 +2932,7 @@ declare function useExecutionStream(options: UseExecutionStreamOptions): UseExec
714
2932
 
715
2933
  interface ChatContainerProps {
716
2934
  /** Child components (MessageList, ChatInput, etc.) */
717
- children: React.ReactNode;
2935
+ children: React$1.ReactNode;
718
2936
  /** Maximum height of the container */
719
2937
  maxHeight?: string | number;
720
2938
  /** Additional CSS classes */
@@ -767,86 +2985,6 @@ interface ChatInputProps {
767
2985
  */
768
2986
  declare function ChatInput({ onSend, onStop, placeholder, disabled, isLoading, enableAttachments, className, }: ChatInputProps): react_jsx_runtime.JSX.Element;
769
2987
 
770
- interface MessageListProps {
771
- /** Array of messages to display */
772
- messages: ChatMessage$1[];
773
- /** Welcome message shown when chat is empty */
774
- welcomeMessage?: string;
775
- /** Whether a new message is loading */
776
- isLoading?: boolean;
777
- /** Whether the assistant is currently streaming a response */
778
- isStreaming?: boolean;
779
- /** Whether session history is being loaded */
780
- isLoadingHistory?: boolean;
781
- /** Whether to enable markdown rendering */
782
- enableMarkdown?: boolean;
783
- /** Whether to show tool calls */
784
- showToolCalls?: boolean;
785
- /** Additional CSS classes */
786
- className?: string;
787
- }
788
- /**
789
- * Renders a scrollable list of chat messages with auto-scroll
790
- *
791
- * @example
792
- * ```tsx
793
- * <MessageList
794
- * messages={messages}
795
- * welcomeMessage="Hello! How can I help you today?"
796
- * isLoading={isLoading}
797
- * isStreaming={isStreaming}
798
- * enableMarkdown
799
- * showToolCalls
800
- * />
801
- * ```
802
- */
803
- declare function MessageList({ messages, welcomeMessage, isLoading, isStreaming, isLoadingHistory, enableMarkdown, showToolCalls, className, }: MessageListProps): react_jsx_runtime.JSX.Element;
804
-
805
- interface ChatMessageProps {
806
- /** Message data */
807
- message: ChatMessage$1;
808
- /** Whether to enable markdown rendering */
809
- enableMarkdown?: boolean;
810
- /** Whether to show tool calls */
811
- showToolCalls?: boolean;
812
- /** Additional CSS classes */
813
- className?: string;
814
- }
815
- /**
816
- * Renders a single chat message with appropriate styling
817
- *
818
- * @example
819
- * ```tsx
820
- * <ChatMessage
821
- * message={{
822
- * id: "1",
823
- * role: "assistant",
824
- * content: "Hello! How can I help?",
825
- * timestamp: new Date(),
826
- * }}
827
- * enableMarkdown
828
- * showToolCalls
829
- * />
830
- * ```
831
- */
832
- declare function ChatMessage({ message, enableMarkdown, showToolCalls, className, }: ChatMessageProps): react_jsx_runtime.JSX.Element;
833
-
834
- interface MarkdownContentProps {
835
- /** Markdown content to render */
836
- content: string;
837
- /** Additional CSS classes */
838
- className?: string;
839
- }
840
- /**
841
- * Renders markdown content with chat-appropriate styling
842
- *
843
- * @example
844
- * ```tsx
845
- * <MarkdownContent content="# Hello\n\nThis is **bold** text." />
846
- * ```
847
- */
848
- declare function MarkdownContent({ content, className }: MarkdownContentProps): react_jsx_runtime.JSX.Element;
849
-
850
2988
  interface ToolCallEntryProps {
851
2989
  /** Tool call data */
852
2990
  toolCall: ToolCall;
@@ -854,6 +2992,12 @@ interface ToolCallEntryProps {
854
2992
  className?: string;
855
2993
  /** Whether to show the full JSON in expanded view */
856
2994
  showFullJson?: boolean;
2995
+ /** Optional callback when an image is clicked. If provided, overrides default browser-open behavior. */
2996
+ onImageClick?: (image: {
2997
+ url: string;
2998
+ alt?: string;
2999
+ filename?: string;
3000
+ }) => void;
857
3001
  }
858
3002
  /**
859
3003
  * Displays a single tool call with status and expandable details
@@ -872,7 +3016,7 @@ interface ToolCallEntryProps {
872
3016
  * />
873
3017
  * ```
874
3018
  */
875
- declare function ToolCallEntry({ toolCall, className, showFullJson, }: ToolCallEntryProps): react_jsx_runtime.JSX.Element;
3019
+ declare function ToolCallEntry({ toolCall, className, showFullJson, onImageClick, }: ToolCallEntryProps): react_jsx_runtime.JSX.Element;
876
3020
 
877
3021
  interface AskUserPromptProps {
878
3022
  /** The question to display to the user */
@@ -971,4 +3115,4 @@ declare function HelpCircleIcon({ className, ...props }: IconProps): react_jsx_r
971
3115
  declare function DatabaseIcon({ className, ...props }: IconProps): react_jsx_runtime.JSX.Element;
972
3116
  declare function ClockIcon({ className, ...props }: IconProps): react_jsx_runtime.JSX.Element;
973
3117
 
974
- export { AgentChat, type AgentChatProps, AlertCircleIcon, type Artifact, AskUserPrompt, type AskUserPromptProps, type AttachmentData, type AttachmentFile, BotIcon, type ChatAdapter, ChatConfigProvider, type ChatConfigProviderProps, ChatContainer, type ChatContainerProps, type ChatError, ChatInput, type ChatInputProps, ChatMessage, type ChatMessageProps, type ChatMessage$1 as ChatMessageType, CheckCircleIcon, CheckIcon, ChevronDownIcon, ChevronLeftIcon, ChevronRightIcon, CircleIcon, type ClarificationData, ClockIcon, CodeIcon, CopyIcon, DatabaseIcon, type DefaultAdapterConfig, DownloadIcon, type Execution, type ExecutionResult, type ExecutionStreamEvent, ExternalLinkIcon, FileIcon, FileTextIcon, HelpCircleIcon, type HistoryMessage, type IconProps, ImageIcon, ImagesIcon, ListTodoIcon, LoadingSpinner, MarkdownContent, type MarkdownContentProps, Maximize2Icon, MessageCircleIcon, MessageList, type MessageListProps, Minimize2Icon, PaperclipIcon, SendIcon, type SendMessageInput, type SessionHistory, SparklesIcon, type StartExecutionInput, StopCircleIcon, type ThemeMode, type ThinkingBlock, type TodoItem, TodoList, type TodoListProps, type ToolCall, ToolCallEntry, type ToolCallEntryProps, type UploadUrlInput, type UploadUrlResult, type UseAgentChatOptions, type UseAgentChatResult, type UseExecutionStreamOptions, type UseExecutionStreamResult, UserIcon, XIcon, ZoomInIcon, ZoomOutIcon, createDefaultAdapter, useAgentChat, useChatConfig, useChatConfigOptional, useExecutionStream };
3118
+ export { AgentChat, type AgentChatProps, AlertCircleIcon, type Artifact$1 as Artifact, AskUserPrompt, type AskUserPromptProps, type AttachmentData, type AttachmentFile, BotIcon, type ChatAdapter, ChatConfigProvider, type ChatConfigProviderProps, ChatContainer, type ChatContainerProps, type ChatError, ChatInput, type ChatInputProps, ChatMessage, type ChatMessageProps, type ChatMessage$1 as ChatMessageType, CheckCircleIcon, CheckIcon, ChevronDownIcon, ChevronLeftIcon, ChevronRightIcon, CircleIcon, type ClarificationData, ClockIcon, CodeIcon, CopyIcon, DatabaseIcon, type DefaultAdapterConfig, DownloadIcon, type Execution, type ExecutionResult, type ExecutionStreamEvent, ExternalLinkIcon, FileIcon, FileTextIcon, HelpCircleIcon, type HistoryMessage, type IconProps, ImageIcon, ImagesIcon, type ListSessionsInput, ListTodoIcon, LoadingSpinner, MarkdownContent, type MarkdownContentProps, Maximize2Icon, MessageCircleIcon, MessageList, type MessageListProps, Minimize2Icon, PaperclipIcon, SendIcon, type SendMessageInput$1 as SendMessageInput, type SessionHistory$1 as SessionHistory, type SessionList, type SessionListItem, SparklesIcon, type StartExecutionInput, StopCircleIcon, type ThemeMode, type ThinkingBlock, type TodoItem, TodoList, type TodoListProps, type ToolCall, ToolCallEntry, type ToolCallEntryProps, type UploadUrlInput, type UploadUrlResult, type UseAgentChatOptions, type UseAgentChatResult, type UseExecutionStreamOptions, type UseExecutionStreamResult, UserIcon, XIcon, ZoomInIcon, ZoomOutIcon, createDefaultAdapter, useAgentChat, useChatConfig, useChatConfigOptional, useExecutionStream };