@hastekit/hastekit-converse 0.0.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,593 @@
1
+ import { ReactNode, ReactElement } from 'react';
2
+ import { AxiosInstance } from 'axios';
3
+
4
+ interface Agent {
5
+ id: string;
6
+ agent_id: string;
7
+ name: string;
8
+ version: number;
9
+ }
10
+ declare enum Role {
11
+ User = "user",
12
+ Developer = "developer",
13
+ System = "system",
14
+ Assistant = "assistant"
15
+ }
16
+ declare enum MessageType {
17
+ Message = "message",
18
+ FunctionCall = "function_call",
19
+ FunctionCallOutput = "function_call_output",
20
+ Reasoning = "reasoning",
21
+ ImageGenerationCall = "image_generation_call",
22
+ FunctionCallApprovalResponse = "function_call_approval_response"
23
+ }
24
+ declare enum ContentType {
25
+ InputText = "input_text",
26
+ OutputText = "output_text",
27
+ SummaryText = "summary_text",
28
+ InputImage = "input_image"
29
+ }
30
+ declare enum ChunkType {
31
+ ChunkTypeRunCreated = "run.created",
32
+ ChunkTypeRunInProgress = "run.in_progress",
33
+ ChunkTypeRunPaused = "run.paused",
34
+ ChunkTypeRunCompleted = "run.completed",
35
+ ChunkTypeResponseCreated = "response.created",
36
+ ChunkTypeResponseInProgress = "response.in_progress",
37
+ ChunkTypeResponseCompleted = "response.completed",
38
+ ChunkTypeOutputItemAdded = "response.output_item.added",
39
+ ChunkTypeOutputItemDone = "response.output_item.done",
40
+ ChunkTypeContentPartAdded = "response.content_part.added",
41
+ ChunkTypeContentPartDone = "response.content_part.done",
42
+ ChunkTypeOutputTextDelta = "response.output_text.delta",
43
+ ChunkTypeOutputTextDone = "response.output_text.done",
44
+ ChunkTypeFunctionCallArgumentsDelta = "response.function_call_arguments.delta",
45
+ ChunkTypeFunctionCallArgumentsDone = "response.function_call_arguments.done",
46
+ ChunkTypeReasoningSummaryPartAdded = "response.reasoning_summary_part.added",
47
+ ChunkTypeReasoningSummaryPartDone = "response.reasoning_summary_part.done",
48
+ ChunkTypeReasoningSummaryTextDelta = "response.reasoning_summary_text.delta",
49
+ ChunkTypeReasoningSummaryTextDone = "response.reasoning_summary_text.done",
50
+ ChunkTypeImageGenerationCallInProgress = "response.image_generation_call.in_progress",
51
+ ChunkTypeImageGenerationCallGenerating = "response.image_generation_call.generating",
52
+ ChunkTypeImageGenerationCallPartialImage = "response.image_generation_call.partial_image",
53
+ ChunkTypeFunctionCallOutput = "function_call_output"
54
+ }
55
+ /**
56
+ * Represents a conversation container
57
+ */
58
+ interface Conversation {
59
+ namespace_id: string;
60
+ conversation_id: string;
61
+ name: string;
62
+ created_at: string;
63
+ last_updated: string;
64
+ }
65
+ /**
66
+ * Represents a thread within a conversation
67
+ */
68
+ interface Thread {
69
+ conversation_id: string;
70
+ origin_message_id: string;
71
+ thread_id: string;
72
+ meta: Record<string, any>;
73
+ created_at: string;
74
+ last_updated: string;
75
+ }
76
+ /**
77
+ * Represents a message within a conversation thread
78
+ */
79
+ interface ConversationMessage {
80
+ conversation_id: string;
81
+ thread_id: string;
82
+ message_id: string;
83
+ messages: MessageUnion[];
84
+ meta: Record<string, any>;
85
+ isStreaming?: boolean;
86
+ }
87
+ type MessageUnion = EasyMessage | InputMessage | OutputMessage | FunctionCallMessage | FunctionCallApprovalResponseMessage | FunctionCallOutputMessage | ReasoningMessage | ImageGenerationCallMessage;
88
+ interface EasyMessage {
89
+ type: MessageType.Message;
90
+ id: string;
91
+ role?: Role;
92
+ content: EasyInputContentUnion;
93
+ }
94
+ interface InputMessage {
95
+ type: MessageType.Message;
96
+ id?: string;
97
+ role?: Role;
98
+ content?: InputContentUnion[];
99
+ }
100
+ interface OutputMessage {
101
+ id: string;
102
+ type?: MessageType.Message;
103
+ role?: Role;
104
+ content?: OutputContentUnion[];
105
+ }
106
+ interface FunctionCallMessage {
107
+ type: MessageType.FunctionCall;
108
+ id: string;
109
+ call_id?: string;
110
+ name: string;
111
+ arguments: string;
112
+ }
113
+ interface FunctionCallApprovalResponseMessage {
114
+ type: MessageType.FunctionCallApprovalResponse;
115
+ id: string;
116
+ approved_call_ids: string[];
117
+ rejected_call_ids: string[];
118
+ }
119
+ interface FunctionCallOutputMessage {
120
+ type: MessageType.FunctionCallOutput;
121
+ id: string;
122
+ call_id: string;
123
+ output: FunctionCallOutputContentUnion;
124
+ }
125
+ interface ReasoningMessage {
126
+ type: MessageType.Reasoning;
127
+ id: string;
128
+ summary?: SummaryTextContent[];
129
+ encrypted_content?: string;
130
+ }
131
+ interface ImageGenerationCallMessage {
132
+ type: MessageType.ImageGenerationCall;
133
+ id: string;
134
+ status: string;
135
+ background: string;
136
+ output_format: string;
137
+ quality: string;
138
+ size: string;
139
+ result: string;
140
+ }
141
+ type EasyInputContentUnion = string | InputContentUnion;
142
+ type InputContentUnion = InputTextContent | OutputTextContent | InputImageContent;
143
+ type FunctionCallOutputContentUnion = string | InputContentUnion;
144
+ type OutputContentUnion = OutputTextContent | FunctionCallMessage | SummaryTextContent;
145
+ interface InputTextContent {
146
+ type: ContentType.InputText;
147
+ text: string;
148
+ }
149
+ interface OutputTextContent {
150
+ type: ContentType.OutputText;
151
+ text: string;
152
+ }
153
+ interface SummaryTextContent {
154
+ type: ContentType.SummaryText;
155
+ text: string;
156
+ }
157
+ interface InputImageContent {
158
+ type: ContentType.InputImage;
159
+ image_url: string;
160
+ detail: string;
161
+ }
162
+ /**
163
+ * Configuration for the converse API endpoint
164
+ */
165
+ interface ConverseConfig {
166
+ namespace: string;
167
+ agentId: string;
168
+ baseUrl?: string;
169
+ context?: Record<string, unknown>;
170
+ headers?: Record<string, string>;
171
+ }
172
+ interface ResponseChunk {
173
+ type: ChunkType;
174
+ sequence_number: number;
175
+ run_state?: ChunkRunData;
176
+ response?: ChunkResponseData;
177
+ output_index?: number;
178
+ item?: ChunkOutputItemData;
179
+ item_id?: string;
180
+ content_index?: number;
181
+ part?: OutputContentUnion;
182
+ delta?: string;
183
+ text?: string;
184
+ arguments?: string;
185
+ summary_index?: number;
186
+ output: string;
187
+ partial_image_index?: number;
188
+ partial_image_b64?: string;
189
+ background?: string;
190
+ output_format?: string;
191
+ quality?: string;
192
+ size?: string;
193
+ status?: string;
194
+ }
195
+ interface ChunkRunData {
196
+ id: string;
197
+ object: "run";
198
+ status: "created" | "in_progress" | "paused" | "resumed" | "completed" | "aborted";
199
+ pending_tool_calls: FunctionCallMessage[];
200
+ usage: ChunkResponseUsage;
201
+ traceid: string;
202
+ }
203
+ interface ChunkResponseData {
204
+ id: string;
205
+ object: string;
206
+ created_at: number;
207
+ status: string;
208
+ background: boolean;
209
+ error: unknown;
210
+ incomplete_details: unknown;
211
+ output: OutputMessageUnion[];
212
+ usage: ChunkResponseUsage;
213
+ }
214
+ interface ChunkOutputItemData {
215
+ type: string;
216
+ id: string;
217
+ status: string;
218
+ content: OutputContentUnion[];
219
+ role: Role;
220
+ call_id?: string;
221
+ name?: string;
222
+ arguments?: string;
223
+ encrypted_content?: string;
224
+ summary?: OutputContentUnion[];
225
+ background?: string;
226
+ output_format?: string;
227
+ quality?: string;
228
+ result?: string;
229
+ size?: string;
230
+ }
231
+ type OutputMessageUnion = (OutputMessage & {
232
+ id: string;
233
+ }) | (FunctionCallMessage & {
234
+ id: string;
235
+ }) | (ReasoningMessage & {
236
+ id: string;
237
+ }) | (ImageGenerationCallMessage & {
238
+ id: string;
239
+ });
240
+ interface ChunkResponseUsage {
241
+ input_tokens: number;
242
+ input_tokens_details: {
243
+ cached_tokens: number;
244
+ };
245
+ output_tokens: number;
246
+ output_tokens_details: {
247
+ reasoning_tokens: number;
248
+ };
249
+ total_tokens: number;
250
+ }
251
+ interface Usage {
252
+ input_tokens: number;
253
+ output_tokens: number;
254
+ total_tokens: number;
255
+ input_tokens_details: {
256
+ cached_tokens: number;
257
+ };
258
+ output_tokens_details: {
259
+ reasoning_tokens: number;
260
+ };
261
+ }
262
+ declare function isEasyMessage(msg: MessageUnion): msg is EasyMessage;
263
+ declare function isInputMessage(msg: MessageUnion): msg is InputMessage;
264
+ declare function isFunctionCallMessage(msg: MessageUnion): msg is FunctionCallMessage;
265
+ declare function isFunctionCallOutputMessage(msg: MessageUnion): msg is FunctionCallOutputMessage;
266
+ declare function isReasoningMessage(msg: MessageUnion): msg is ReasoningMessage;
267
+ declare function isImageGenerationCallMessage(msg: MessageUnion): msg is ImageGenerationCallMessage;
268
+
269
+ /**
270
+ * Function type for providing custom headers.
271
+ * Called before each request to get headers (useful for dynamic auth tokens).
272
+ *
273
+ * @example
274
+ * ```ts
275
+ * const getHeaders: GetHeadersFn = () => ({
276
+ * 'Authorization': `Bearer ${getToken()}`,
277
+ * 'X-Custom-Header': 'value',
278
+ * });
279
+ * ```
280
+ */
281
+ type GetHeadersFn = () => Record<string, string> | Promise<Record<string, string>>;
282
+ /**
283
+ * Options for the useConversation hook
284
+ */
285
+ interface UseConversationOptions {
286
+ /** The namespace for conversations */
287
+ namespace: string;
288
+ /** Auto-load conversations on mount (default: true) */
289
+ autoLoad?: boolean;
290
+ }
291
+ /**
292
+ * Return type for the useConversation hook
293
+ */
294
+ interface UseConversationReturn {
295
+ /** List of all conversations */
296
+ conversations: Conversation[];
297
+ /** Whether conversations are being loaded */
298
+ conversationsLoading: boolean;
299
+ /** List of threads in the current conversation */
300
+ threads: Thread[];
301
+ /** Whether threads are being loaded */
302
+ threadsLoading: boolean;
303
+ /** Currently selected thread */
304
+ currentThread: Thread | null;
305
+ /** List of messages in the current thread */
306
+ messages: ConversationMessage[];
307
+ /** Message currently being streamed */
308
+ streamingMessage: ConversationMessage | null;
309
+ /** Whether messages are being loaded */
310
+ messagesLoading: boolean;
311
+ /** Whether a response is currently streaming */
312
+ isStreaming: boolean;
313
+ /** Whether waiting for a response */
314
+ isThinking: boolean;
315
+ /** ID of the currently selected conversation */
316
+ currentConversationId: string | null;
317
+ /** ID of the currently selected thread */
318
+ currentThreadId: string | null;
319
+ /** Load all conversations */
320
+ loadConversations: () => Promise<void>;
321
+ /** Select a conversation by ID */
322
+ selectConversation: (conversationId: string) => void;
323
+ /** Load threads for a conversation */
324
+ loadThreads: (conversationId: string) => Promise<void>;
325
+ /** Select a thread by ID */
326
+ selectThread: (threadId: string) => void;
327
+ /** Send a message and stream the response */
328
+ sendMessage: (userMessages: MessageUnion[], config: ConverseConfig) => Promise<void>;
329
+ /** Start a new chat (clears current state) */
330
+ startNewChat: () => void;
331
+ /** All messages including the currently streaming one */
332
+ allMessages: ConversationMessage[];
333
+ }
334
+ /**
335
+ * A comprehensive hook for managing conversations, threads, messages, and streaming
336
+ * with Uno Agent Server.
337
+ *
338
+ * @example
339
+ * ```tsx
340
+ * import { useConversation } from '@praveen001/uno-converse';
341
+ *
342
+ * function ChatComponent() {
343
+ * const {
344
+ * allMessages,
345
+ * isStreaming,
346
+ * sendMessage,
347
+ * startNewChat,
348
+ * } = useConversation({
349
+ * namespace: 'my-app',
350
+ * });
351
+ *
352
+ * const handleSend = async (text: string) => {
353
+ * await sendMessage(
354
+ * [{ type: 'message', id: '1', content: text }],
355
+ * {
356
+ * namespace: 'my-app',
357
+ * agentName: 'my-agent',
358
+ * }
359
+ * );
360
+ * };
361
+ *
362
+ * return (
363
+ * <div>
364
+ * {allMessages.map(msg => (
365
+ * <MessageComponent key={msg.message_id} message={msg} />
366
+ * ))}
367
+ * {isStreaming && <LoadingIndicator />}
368
+ * </div>
369
+ * );
370
+ * }
371
+ * ```
372
+ */
373
+ declare function useConversation(options: UseConversationOptions): UseConversationReturn;
374
+
375
+ /**
376
+ * Options for the useAgent hook
377
+ */
378
+ interface UseAgentOptions {
379
+ /** The name of the agent */
380
+ name: string;
381
+ }
382
+ /**
383
+ * Return type for the useAgent hook
384
+ */
385
+ interface UseAgentReturn {
386
+ agent: Agent | null;
387
+ /** Whether the agent is being loaded */
388
+ agentLoading: boolean;
389
+ }
390
+ declare function useAgent(options: UseAgentOptions): UseAgentReturn;
391
+
392
+ /**
393
+ * Options for the useProject hook
394
+ */
395
+ interface UseProjectOptions {
396
+ /** Base URL of the Uno Agent Server (e.g., 'https://api.example.com/api/agent-server') */
397
+ baseUrl: string;
398
+ /** Project Name used to fetch the project ID */
399
+ projectName: string;
400
+ /** Optional function to get custom headers for requests (e.g., for authentication) */
401
+ getHeaders?: GetHeadersFn;
402
+ /** Auto-load conversations on mount (default: true) */
403
+ autoLoad?: boolean;
404
+ }
405
+ /**
406
+ * Return type for the useProject hook
407
+ */
408
+ interface UseProjectReturn {
409
+ /** The fetched project ID */
410
+ projectId: string;
411
+ /** Whether the project ID is being fetched */
412
+ projectLoading: boolean;
413
+ /** Axios instance configured with baseUrl and custom headers */
414
+ axiosInstance: AxiosInstance;
415
+ /** Function to build query params with project_id automatically added */
416
+ buildParams: (params?: Record<string, string>) => Record<string, string>;
417
+ /** Function to get request headers (combines default + custom headers) */
418
+ getRequestHeaders: () => Promise<Record<string, string>>;
419
+ /** Base URL used for the axios instance */
420
+ baseUrl: string;
421
+ }
422
+
423
+ /**
424
+ * Context value for ProjectProvider
425
+ */
426
+ interface ProjectContextValue extends UseProjectReturn {
427
+ }
428
+ /**
429
+ * Props for ProjectProvider component
430
+ */
431
+ interface ProjectProviderProps {
432
+ /** Base URL of the Uno Agent Server (e.g., 'https://api.example.com/api/agent-server') */
433
+ baseUrl: string;
434
+ /** Project Name used to fetch the project ID */
435
+ projectName: string;
436
+ /** Optional function to get custom headers for requests (e.g., for authentication) */
437
+ getHeaders?: UseProjectOptions['getHeaders'];
438
+ /** Auto-load project on mount (default: true) */
439
+ autoLoad?: boolean;
440
+ /** Child components */
441
+ children: ReactNode;
442
+ }
443
+ /**
444
+ * ProjectProvider component that manages project state using React Context.
445
+ *
446
+ * This provider wraps the useProject hook and makes the project state available
447
+ * to all child components through context.
448
+ *
449
+ * @example
450
+ * ```tsx
451
+ * import { ProjectProvider, useProjectContext } from '@praveen001/uno-converse';
452
+ *
453
+ * function App() {
454
+ * return (
455
+ * <ProjectProvider
456
+ * baseUrl="https://api.example.com/api/agent-server"
457
+ * projectName="my-project"
458
+ * getHeaders={() => ({
459
+ * 'Authorization': `Bearer ${getToken()}`,
460
+ * })}
461
+ * >
462
+ * <YourApp />
463
+ * </ProjectProvider>
464
+ * );
465
+ * }
466
+ *
467
+ * function YourApp() {
468
+ * const { projectId, projectLoading } = useProjectContext();
469
+ *
470
+ * if (projectLoading) {
471
+ * return <div>Loading project...</div>;
472
+ * }
473
+ *
474
+ * return <div>Project ID: {projectId}</div>;
475
+ * }
476
+ * ```
477
+ */
478
+ declare const ProjectProvider: ({ baseUrl, projectName, getHeaders, autoLoad, children, }: ProjectProviderProps) => ReactElement;
479
+ /**
480
+ * Hook to access the project context.
481
+ *
482
+ * Must be used within a ProjectProvider component.
483
+ *
484
+ * @throws {Error} If used outside of ProjectProvider
485
+ *
486
+ * @example
487
+ * ```tsx
488
+ * function MyComponent() {
489
+ * const { projectId, projectLoading } = useProjectContext();
490
+ *
491
+ * return (
492
+ * <div>
493
+ * {projectLoading ? 'Loading...' : `Project ID: ${projectId}`}
494
+ * </div>
495
+ * );
496
+ * }
497
+ * ```
498
+ */
499
+ declare const useProjectContext: () => ProjectContextValue;
500
+
501
+ /**
502
+ * Callback invoked when the conversation state changes
503
+ */
504
+ type OnChangeCallback = (conversation: ConversationMessage) => void;
505
+ /**
506
+ * Processes streaming chunks from the LLM response.
507
+ * Builds up messages incrementally as chunks arrive.
508
+ *
509
+ * @example
510
+ * ```ts
511
+ * const processor = new ChunkProcessor(
512
+ * 'conv-123',
513
+ * 'thread-456',
514
+ * (conversation) => {
515
+ * // Update UI with new conversation state
516
+ * setConversation(conversation);
517
+ * }
518
+ * );
519
+ *
520
+ * // Process incoming chunks
521
+ * processor.processChunk(jsonData);
522
+ *
523
+ * // Get final conversation when done
524
+ * const finalConversation = processor.getConversation();
525
+ * ```
526
+ */
527
+ declare class ChunkProcessor {
528
+ private messages;
529
+ private currentOutputItem;
530
+ private _onChange;
531
+ private conversation;
532
+ constructor(conversationId: string, threadId: string, onChange: OnChangeCallback);
533
+ /**
534
+ * Get all processed messages
535
+ */
536
+ getMessages(): MessageUnion[];
537
+ /**
538
+ * Get the current conversation state
539
+ */
540
+ getConversation(): ConversationMessage;
541
+ private emitChange;
542
+ /**
543
+ * Process a raw JSON chunk from the SSE stream
544
+ */
545
+ processChunk(data: string): void;
546
+ private handleChunk;
547
+ private handleOutputItemAdded;
548
+ private handleContentPartAdded;
549
+ private handleOutputTextDelta;
550
+ private handleReasoningSummaryPartAdded;
551
+ private handleReasoningSummaryTextDelta;
552
+ private handleFunctionCallArgumentsDelta;
553
+ private handleFunctionCallOutput;
554
+ private handleImageGenerationCallPartialImage;
555
+ }
556
+
557
+ /**
558
+ * Options for the SSE stream callbacks
559
+ */
560
+ interface SSEStreamOptions {
561
+ /** Called for each data chunk received */
562
+ onChunk: (data: string) => void;
563
+ /** Called when an error occurs */
564
+ onError?: (error: Error) => void;
565
+ /** Called when the stream completes */
566
+ onComplete?: () => void;
567
+ }
568
+ /**
569
+ * Streams Server-Sent Events (SSE) from a URL.
570
+ * Parses SSE frames and calls onChunk for each data payload.
571
+ *
572
+ * @param url - The URL to stream from
573
+ * @param requestOptions - Fetch request options
574
+ * @param callbacks - SSE event callbacks
575
+ * @param abortSignal - Optional signal to abort the stream
576
+ *
577
+ * @example
578
+ * ```ts
579
+ * await streamSSE(
580
+ * 'https://api.example.com/stream',
581
+ * { method: 'POST', body: JSON.stringify({ message: 'Hello' }) },
582
+ * {
583
+ * onChunk: (data) => console.log('Received:', data),
584
+ * onComplete: () => console.log('Done'),
585
+ * onError: (err) => console.error('Error:', err),
586
+ * }
587
+ * );
588
+ * ```
589
+ */
590
+ declare function streamSSE(url: string, requestOptions: RequestInit, callbacks: SSEStreamOptions, abortSignal?: AbortSignal): Promise<void>;
591
+
592
+ export { ChunkProcessor, ChunkType, ContentType, MessageType, ProjectProvider, Role, isEasyMessage, isFunctionCallMessage, isFunctionCallOutputMessage, isImageGenerationCallMessage, isInputMessage, isReasoningMessage, streamSSE, useAgent, useConversation, useProjectContext };
593
+ export type { ChunkOutputItemData, ChunkResponseData, ChunkResponseUsage, ChunkRunData, Conversation, ConversationMessage, ConverseConfig, EasyInputContentUnion, EasyMessage, FunctionCallApprovalResponseMessage, FunctionCallMessage, FunctionCallOutputContentUnion, FunctionCallOutputMessage, GetHeadersFn, ImageGenerationCallMessage, InputContentUnion, InputImageContent, InputMessage, InputTextContent, MessageUnion, OnChangeCallback, OutputContentUnion, OutputMessage, OutputMessageUnion, OutputTextContent, ProjectContextValue, ProjectProviderProps, ReasoningMessage, ResponseChunk, SSEStreamOptions, SummaryTextContent, Thread, Usage, UseAgentOptions, UseAgentReturn, UseConversationOptions, UseConversationReturn };