@cmnd-ai/chatbot-react 1.9.2 → 1.13.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (34) hide show
  1. package/Readme.md +113 -9
  2. package/dist/ChatProvider/index.d.ts +2 -2
  3. package/dist/ChatProvider/index.js +13 -13
  4. package/dist/ChatProvider/processStream/index.js +40 -15
  5. package/dist/CmndChatBot/index.d.ts +2 -1
  6. package/dist/CmndChatBot/index.js +2 -2
  7. package/dist/components/Chatbubble.d.ts +2 -2
  8. package/dist/components/Chatbubble.js +11 -11
  9. package/dist/components/Conversation.d.ts +3 -3
  10. package/dist/components/Conversation.js +2 -2
  11. package/dist/components/ConversationCard.js +1 -1
  12. package/dist/components/ConversationsPanel/index.d.ts +2 -2
  13. package/dist/components/ConversationsPanel/index.js +25 -23
  14. package/dist/components/LoadingBubble.js +1 -1
  15. package/dist/constants/endpoints.d.ts +3 -3
  16. package/dist/constants/endpoints.js +2 -2
  17. package/dist/hooks/use-cmnd-chat.d.ts +130 -0
  18. package/dist/hooks/use-cmnd-chat.js +396 -0
  19. package/dist/index.d.ts +4 -1
  20. package/dist/index.js +4 -0
  21. package/dist/services/deleteChatbotConversationMemory/index.d.ts +2 -2
  22. package/dist/services/deleteChatbotConversationMemory/index.js +2 -2
  23. package/dist/services/getChatBotConversationsList/index.d.ts +1 -1
  24. package/dist/services/getEmbedChatBotById.d.ts +1 -1
  25. package/dist/services/patchChatbotConversationMemory/index.d.ts +2 -2
  26. package/dist/services/patchChatbotConversationMemory/index.js +2 -2
  27. package/dist/type.d.ts +134 -41
  28. package/dist/type.js +12 -0
  29. package/dist/utils/cleanMarkdown.d.ts +8 -0
  30. package/dist/utils/cleanMarkdown.js +31 -0
  31. package/dist/utils/saveConversationIdToLocalStorage/index.d.ts +2 -2
  32. package/dist/utils/saveConversationIdToLocalStorage/index.js +8 -7
  33. package/package.json +4 -3
  34. package/readme.dev.md +49 -0
package/dist/type.d.ts CHANGED
@@ -1,46 +1,58 @@
1
1
  import { CSSProperties } from "react";
2
2
  import { ConversationProps } from "./components/Conversation.js";
3
+ /**
4
+ * Context interface for the CMND Chat system.
5
+ * This is used primarily by the internal provider but can be accessed via useCMNDChatContext.
6
+ */
3
7
  export interface CmndChatContext {
8
+ /** Internal props passed to the conversation view. */
4
9
  props: Partial<ConversationProps>;
5
- /**
6
- * Create a new conversation (resets state, starts a new chat thread)
7
- */
10
+ /** Create a new conversation (resets state, starts a new chat thread). */
8
11
  createNewConversation: () => void;
9
- /**
10
- * Toggle the sidebar open/collapsed state
11
- */
12
+ /** Toggle the sidebar open/collapsed state. */
12
13
  toggleSidebar: () => void;
13
- /**
14
- * Open the sidebar (set collapsed to false)
15
- */
14
+ /** Open the sidebar (set collapsed to false). */
16
15
  openSidePanel: () => void;
17
- /**
18
- * Close the sidebar (set collapsed to true)
19
- */
16
+ /** Close the sidebar (set collapsed to true). */
20
17
  closeSidePanel: () => void;
21
- /**
22
- * Set the message text in the input box
23
- */
18
+ /** Set the message text in the input box. */
24
19
  setMessageText: (text: string) => void;
25
- /**
26
- * Send the current message, or set and send if text is provided
27
- */
20
+ /** Send the current message, or set and send if text is provided. */
28
21
  sendMessage: (text?: string) => void;
29
22
  }
23
+ /**
24
+ * Props for a custom input field component.
25
+ */
30
26
  export interface InputFieldProps {
27
+ /** The current input text. */
31
28
  input: string;
29
+ /** Setter for the input text. */
32
30
  setInput: (input: string) => void;
31
+ /** Whether the send button should be enabled. */
33
32
  canSendMessage: boolean;
33
+ /** Callback to trigger the send action. */
34
34
  handleSendClick: () => void;
35
- inputRef?: React.RefObject<HTMLInputElement> | React.RefObject<HTMLTextAreaElement> | React.RefObject<HTMLTextAreaElement>;
35
+ /** Ref for the input element. */
36
+ inputRef?: React.RefObject<HTMLInputElement> | React.RefObject<HTMLTextAreaElement>;
36
37
  }
38
+ /**
39
+ * Props for a custom send button component.
40
+ */
37
41
  export interface SendButtonProps {
42
+ /** Callback to trigger the send action. */
38
43
  handleSendClick: () => void;
44
+ /** Whether the button should be enabled. */
39
45
  canSendMessage: boolean;
40
46
  }
47
+ /**
48
+ * Utility type for wrapping API responses that might contain an error.
49
+ */
41
50
  export type ErrorOrData<T> = {
42
51
  error: unknown;
43
52
  } | T;
53
+ /**
54
+ * Represents a conversation object from the server.
55
+ */
44
56
  export interface Conversation {
45
57
  conversationId: number;
46
58
  conversationTitle: string;
@@ -50,36 +62,54 @@ export interface Conversation {
50
62
  costLimit: number;
51
63
  systemPrompt: string;
52
64
  enabledTools: any[];
53
- /** Date string format */
65
+ /** Date string format (UTC). */
54
66
  createdAt: string;
55
- /** Date string format */
67
+ /** Date string format (UTC). */
56
68
  updatedAt: string;
57
69
  }
70
+ /**
71
+ * Data object received via streaming or finalized responses.
72
+ */
58
73
  export interface ConversationDataObject {
74
+ /** Indicates if the AI has finished generating the response text. */
59
75
  completionFinished: boolean;
76
+ /** Indicates if this is the final message containing usage metadata. */
60
77
  finalResponseWithUsageData: boolean;
78
+ /** The message text (full or chunk). */
61
79
  message?: string;
62
- conversationId?: string;
63
- chatbotConversationId?: number;
80
+ /** The conversation reference ID. */
81
+ chatbotConversationRef?: string;
82
+ /** Alias for chatbotConversationRef used in some stream responses. */
83
+ conversationRef?: string;
84
+ /** Total tokens used in the conversation so far. */
64
85
  totalTokens?: number;
86
+ /** Total cost of the conversation so far. */
65
87
  totalCost?: number;
88
+ /** Updated list of all messages in the conversation. */
66
89
  messages?: Message[];
90
+ /** Indicates if an error occurred during streaming. */
91
+ hasError?: boolean;
92
+ /** Path associated with the error if available. */
93
+ errorPath?: string[] | string;
94
+ /** Indicates if a function call is currently being streamed. */
95
+ streamingFunctionCall?: boolean;
96
+ /** Name of the function being called. */
97
+ functionName?: string;
98
+ /** Result of a function execution. */
99
+ functionResult?: any;
67
100
  }
68
- interface ToolArgument {
69
- type: string;
70
- description: string;
71
- default?: any;
72
- }
73
- interface ToolArguments {
74
- type: string;
75
- default?: any;
76
- properties: Record<string, ToolArgument>;
77
- required?: string[];
78
- }
101
+ /**
102
+ * Defines the type of tool function.
103
+ */
79
104
  export declare enum FunctionType {
105
+ /** Tool that renders a React component in the chat. */
80
106
  UI = "ui",
107
+ /** Tool that runs on the backend. */
81
108
  BACKEND = "backend"
82
109
  }
110
+ /**
111
+ * Metadata for a tool.
112
+ */
83
113
  export type ToolData = {
84
114
  name: string;
85
115
  description: string;
@@ -88,62 +118,105 @@ export type ToolData = {
88
118
  subsubcategory?: string;
89
119
  functionType: FunctionType;
90
120
  dangerous: boolean;
91
- arguments: ToolArguments;
92
- };
93
- export type UIFunctionArguments<AIProvidedParams> = {
94
- functionArgs: AIProvidedParams;
95
- previousRunResults?: string;
96
- captureResults: (result: string) => void;
121
+ arguments: any;
97
122
  };
123
+ /**
124
+ * Represents a tool that can be used within the chatbot.
125
+ */
98
126
  export interface CMNDChatbotUITool {
127
+ /** Unique name of the tool. */
99
128
  name: string;
129
+ /** Description of what the tool does. */
100
130
  description: string;
131
+ /** Category for organizational purposes. */
101
132
  category: string;
133
+ /** Subcategory for finer organization. */
102
134
  subcategory?: string;
135
+ /** Indicates if the tool should be treated as dangerous (e.g., requires confirmation). */
103
136
  dangerous?: boolean;
137
+ /** Command aliases that might trigger this tool. */
104
138
  associatedCommands?: string[];
139
+ /** Prerequisites required before this tool can run. */
105
140
  prerequisites?: string[];
141
+ /** JSON Schema for the tool's arguments. */
106
142
  argumentSchema: any;
143
+ /** Whether the tool can be re-run after finishing. */
107
144
  rerun?: boolean;
145
+ /** Whether the tool can be re-run with different parameters. */
108
146
  rerunWithDifferentParameters?: boolean;
147
+ /** Whether the tool requires further user input. */
109
148
  capturesUserInput?: boolean;
149
+ /** Explicitly set to 'ui' for UI-based tools. */
110
150
  functionType?: "ui";
151
+ /** The function implementation to run when the tool is called. */
111
152
  runCmd: (args: {
112
153
  functionArgs?: Record<string, any>;
113
154
  captureResults?: (result: any) => Promise<any>;
114
155
  previousRunResults?: any;
115
156
  }, ref?: React.RefObject<HTMLElement>) => void;
116
157
  }
158
+ /**
159
+ * Roles for different message types.
160
+ */
117
161
  export declare enum MessageRole {
162
+ /** A tool call or result. */
118
163
  FUNCTION = "function",
164
+ /** A message from the user. */
119
165
  USER = "user",
166
+ /** A message from the AI assistant. */
120
167
  ASSISTANT = "assistant",
168
+ /** A system instruction. */
121
169
  SYSTEM = "system"
122
170
  }
123
171
  type MessageRoleExceptFunctions = Exclude<MessageRole, MessageRole.FUNCTION>;
172
+ /**
173
+ * Base message structure.
174
+ */
124
175
  interface GenericMessage {
125
176
  id: string;
177
+ /** Whether the message should be hidden or ignored in some contexts. */
126
178
  unuseful: boolean;
179
+ /** Whether the message is visible to the end user. */
127
180
  hiddenFromUser: boolean;
181
+ /** The text content of the message. */
128
182
  message?: string;
183
+ /** The role of the sender. */
129
184
  role: MessageRoleExceptFunctions;
130
185
  }
186
+ /**
187
+ * Details of a tool call or its execution result.
188
+ */
131
189
  export interface ToolDetails {
190
+ /** Arguments passed by the AI. */
132
191
  args: any;
192
+ /** Name of the tool called. */
133
193
  name: string;
194
+ /** Whether the tool run has been confirmed. */
134
195
  confirmed?: boolean;
196
+ /** Timestamp of when the tool was run. */
135
197
  runAt?: string;
198
+ /** The result/output of the tool execution. */
136
199
  output?: string;
137
200
  }
201
+ /**
202
+ * A message representing a tool call.
203
+ */
138
204
  interface ToolMessage {
139
205
  id: string;
140
206
  unuseful: boolean;
141
207
  hiddenFromUser: boolean;
142
208
  message?: string;
143
209
  role: MessageRole.FUNCTION;
210
+ /** Details about the tool call. */
144
211
  tool: ToolDetails;
145
212
  }
213
+ /**
214
+ * Union type for all possible message types in a conversation.
215
+ */
146
216
  export type Message = GenericMessage | ToolMessage;
217
+ /**
218
+ * CSS properties for customizing various parts of the chatbot UI.
219
+ */
147
220
  export interface CustomStyles {
148
221
  chatAvatarStyle?: CSSProperties;
149
222
  inputStyle?: CSSProperties;
@@ -164,9 +237,15 @@ export interface CustomStyles {
164
237
  dateStyle?: CSSProperties;
165
238
  deleteButtonStyle?: CSSProperties;
166
239
  }
240
+ /**
241
+ * KV store for conversation memory/context.
242
+ */
167
243
  export interface CMNDChatMemory {
168
244
  [key: string]: any;
169
245
  }
246
+ /**
247
+ * Simple message structure used in the ChatbotConversation summary.
248
+ */
170
249
  export interface ChatbotConversationMessage {
171
250
  id?: string;
172
251
  role: "user" | "assistant";
@@ -174,16 +253,30 @@ export interface ChatbotConversationMessage {
174
253
  unuseful: boolean;
175
254
  hiddenFromUser: boolean;
176
255
  }
256
+ /**
257
+ * Full conversation metadata and history.
258
+ */
177
259
  export interface ChatbotConversation {
178
- chatbotConversationId: number;
260
+ /** Unique reference for the conversation. */
261
+ chatbotConversationRef: string;
262
+ /** Snapshot of message history. */
179
263
  messages: ChatbotConversationMessage[];
264
+ /** ID of the parent chatbot. */
180
265
  chatbotId: number;
266
+ /** Human-readable title for the conversation. */
181
267
  chatbotConversationTitle: string;
268
+ /** Creation timestamp. */
182
269
  createdAt: string;
270
+ /** Last update timestamp. */
183
271
  updatedAt: string;
272
+ /** Cumulative cost of this thread. */
184
273
  totalCostSoFar: number;
274
+ /** Cumulative token count for this thread. */
185
275
  totalTokensSoFar: number;
186
276
  }
277
+ /**
278
+ * Response structure when listing conversations.
279
+ */
187
280
  export interface ChatbotConversationsResponse {
188
281
  chatbotConversations: ChatbotConversation[];
189
282
  }
package/dist/type.js CHANGED
@@ -1,12 +1,24 @@
1
+ /**
2
+ * Defines the type of tool function.
3
+ */
1
4
  export var FunctionType;
2
5
  (function (FunctionType) {
6
+ /** Tool that renders a React component in the chat. */
3
7
  FunctionType["UI"] = "ui";
8
+ /** Tool that runs on the backend. */
4
9
  FunctionType["BACKEND"] = "backend";
5
10
  })(FunctionType = FunctionType || (FunctionType = {}));
11
+ /**
12
+ * Roles for different message types.
13
+ */
6
14
  export var MessageRole;
7
15
  (function (MessageRole) {
16
+ /** A tool call or result. */
8
17
  MessageRole["FUNCTION"] = "function";
18
+ /** A message from the user. */
9
19
  MessageRole["USER"] = "user";
20
+ /** A message from the AI assistant. */
10
21
  MessageRole["ASSISTANT"] = "assistant";
22
+ /** A system instruction. */
11
23
  MessageRole["SYSTEM"] = "system";
12
24
  })(MessageRole = MessageRole || (MessageRole = {}));
@@ -0,0 +1,8 @@
1
+ /**
2
+ * Cleans markdown characters from a string to return plaintext.
3
+ * This is a simple regex-based cleaner that handles common markdown patterns.
4
+ *
5
+ * @param markdown The markdown string to clean.
6
+ * @returns The cleaned plaintext string.
7
+ */
8
+ export declare const cleanMarkdown: (markdown: string) => string;
@@ -0,0 +1,31 @@
1
+ /**
2
+ * Cleans markdown characters from a string to return plaintext.
3
+ * This is a simple regex-based cleaner that handles common markdown patterns.
4
+ *
5
+ * @param markdown The markdown string to clean.
6
+ * @returns The cleaned plaintext string.
7
+ */
8
+ export const cleanMarkdown = (markdown) => {
9
+ if (!markdown)
10
+ return "";
11
+ return (markdown
12
+ // Handle bold/italic
13
+ .replace(/(\*\*|__)(.*?)\1/g, "$2")
14
+ .replace(/(\*|_)(.*?)\1/g, "$2")
15
+ // Handle links: [text](url) -> text
16
+ .replace(/\[(.*?)\]\(.*?\)/g, "$1")
17
+ // Handle code blocks
18
+ .replace(/```[\s\S]*?```/g, (match) => {
19
+ return match.replace(/```(\w+)?\n?|```/g, "").trim();
20
+ })
21
+ // Handle inline code
22
+ .replace(/`(.*?)`/g, "$1")
23
+ // Handle headers: # Header -> Header
24
+ .replace(/^#+\s+/gm, "")
25
+ // Handle blockquotes: > quote -> quote
26
+ .replace(/^>\s+/gm, "")
27
+ // Handle horizontal rules
28
+ .replace(/^-{3,}|^\*{3,}|^\_{3,}/gm, "")
29
+ // Handle images: ![alt](url) -> alt
30
+ .replace(/!\[(.*?)\]\(.*?\)/g, "$1"));
31
+ };
@@ -1,5 +1,5 @@
1
- declare const saveConversationIdToLocalStorage: ({ chatbotConversationId, chatbotId, organizationId, chatHistoryStorageKey }: {
2
- chatbotConversationId: number;
1
+ declare const saveConversationIdToLocalStorage: ({ chatbotConversationRef, chatbotId, organizationId, chatHistoryStorageKey, }: {
2
+ chatbotConversationRef: string;
3
3
  chatbotId: number;
4
4
  organizationId: number;
5
5
  chatHistoryStorageKey?: string | undefined;
@@ -1,14 +1,15 @@
1
1
  import getConversationLocalStorageKey from "../getConversationLocalStorageKey/index.js";
2
- const saveConversationIdToLocalStorage = async ({ chatbotConversationId, chatbotId, organizationId, chatHistoryStorageKey }) => {
2
+ const saveConversationIdToLocalStorage = async ({ chatbotConversationRef, chatbotId, organizationId, chatHistoryStorageKey, }) => {
3
3
  try {
4
- const key = chatHistoryStorageKey || getConversationLocalStorageKey({
5
- organizationId,
6
- chatbotId: Number(chatbotId),
7
- });
4
+ const key = chatHistoryStorageKey ||
5
+ getConversationLocalStorageKey({
6
+ organizationId,
7
+ chatbotId: Number(chatbotId),
8
+ });
8
9
  //get the conversation ids from local storage
9
10
  const conversations = JSON.parse(localStorage.getItem(key) || "[]") ?? [];
10
- if (!conversations.includes(chatbotConversationId)) {
11
- conversations.push(chatbotConversationId);
11
+ if (!conversations.includes(chatbotConversationRef)) {
12
+ conversations.push(chatbotConversationRef);
12
13
  localStorage.setItem(key, JSON.stringify(conversations));
13
14
  }
14
15
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@cmnd-ai/chatbot-react",
3
- "version": "1.9.2",
3
+ "version": "1.13.0",
4
4
  "main": "dist/index.js",
5
5
  "description": "",
6
6
  "type": "module",
@@ -31,11 +31,12 @@
31
31
  "access": "public"
32
32
  },
33
33
  "dependencies": {
34
- "axios": "^1.7.5",
34
+ "axios": "^1.13.1",
35
35
  "react-error-boundary": "^4.0.13",
36
36
  "react-icons": "^5.3.0",
37
37
  "react-markdown": "^8.0.6",
38
38
  "react-syntax-highlighter": "^15.5.0",
39
- "remark-gfm": "^3.0.1"
39
+ "remark-gfm": "^3.0.1",
40
+ "uuid": "^13.0.0"
40
41
  }
41
42
  }
package/readme.dev.md CHANGED
@@ -28,3 +28,52 @@
28
28
  ```
29
29
 
30
30
  This will allow you to test your local changes in another project without publishing to npm.
31
+
32
+ ## Core Hook Implementation (`useCMNDChat`)
33
+
34
+ The `useCMNDChat` hook is designed to be the logic engine of the chatbot. Key implementation details:
35
+
36
+ - **State Management**: Uses native React `useState` for messages, input, and loading states.
37
+ - **Real-time Streaming**: Utilizes `postUserConversation` with a stream reader to process response chunks.
38
+ - **Tool Orchestration**:
39
+ - **Backend Tools**: Automatically confirms tool call by setting `confirmed: true`. This triggers the server to execute the tool and return the actual data.
40
+ - **UI Tools**: Fires the `onToolCall` callback. The developer must execute the tool logic and call `submitToolResult(output)`.
41
+ - **Message Cleaning**: When `cleanResponse: true` is enabled, assistant messages are passed through a `cleanMarkdown` utility to return plaintext.
42
+ - **Persistence**: Automatically saves and loads conversation IDs from `localStorage` based on the `organizationId` and `chatbotId`.
43
+
44
+ ### Tool Call Flow
45
+
46
+ 1. AI generates a `function_call`.
47
+ 2. Hook receives the call and adds a message with `role: "function"` to the state (internally).
48
+ 3. **Internal Behavior:**
49
+ - **Backend Tools**: The hook automatically calls `confirmBackendTool()`. This sends a confirmed message back to the server.
50
+ - **UI Tools**: The hook notifies the developer via `onToolCall`.
51
+ 4. **Execution:**
52
+ - **Backend Tools**: The server receives the confirmation, executes the tool, and returns the real data in the next stream update.
53
+ - **UI Tools**: The developer manually calls `submitToolResult(data)` with the result of the frontend execution.
54
+ 5. The conversation resumes with the tool results included in the history.
55
+
56
+ ### Backend Tool Data Flow
57
+
58
+ ```
59
+ User: "Show my playlists"
60
+
61
+ AI calls: get_playlists() (role: function)
62
+
63
+ Hook auto-confirms: internal confirmBackendTool() (sets confirmed: true)
64
+
65
+ Server executes and returns: { playlists: [...] } (Actual data)
66
+
67
+ AI receives data and responds: "Here are your playlists: ..."
68
+ ```
69
+
70
+ **Note**: `FUNCTION` role messages are filtered out from the `messages` array returned by the hook to keep the UI clean. Only `USER` and `ASSISTANT` messages are exposed.
71
+
72
+ ## Building and Releasing
73
+
74
+ 1. **Build the package:**
75
+ ```sh
76
+ npm run build
77
+ ```
78
+ 2. **Release:**
79
+ This project uses `semantic-release` for automated versioning and npm publishing. Ensure your commit messages follow the [Conventional Commits](https://www.conventionalcommits.org/) specification.