chatgsd 0.0.1 → 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +206 -3
- package/dist/index.cjs +329 -0
- package/dist/index.cjs.map +1 -0
- package/dist/index.d.cts +64 -0
- package/dist/index.d.ts +64 -0
- package/dist/index.js +302 -0
- package/dist/index.js.map +1 -0
- package/dist/styles.css +236 -0
- package/package.json +45 -6
- package/index.js +0 -1
- package/tsconfig.json +0 -113
package/README.md
CHANGED
|
@@ -1,4 +1,207 @@
|
|
|
1
|
-
#
|
|
1
|
+
# ChatGSD
|
|
2
2
|
|
|
3
|
-
|
|
4
|
-
|
|
3
|
+
A conversational UI component where AI orchestrates the interface. The AI decides when to show calendars, collect payments, submit forms — chat becomes the control layer.
|
|
4
|
+
|
|
5
|
+
## Install
|
|
6
|
+
|
|
7
|
+
```bash
|
|
8
|
+
npm install chatgsd
|
|
9
|
+
```
|
|
10
|
+
|
|
11
|
+
## Quick Start
|
|
12
|
+
|
|
13
|
+
```tsx
|
|
14
|
+
import { ChatGSD } from "chatgsd";
|
|
15
|
+
import "chatgsd/styles.css";
|
|
16
|
+
|
|
17
|
+
function App() {
|
|
18
|
+
return (
|
|
19
|
+
<ChatGSD
|
|
20
|
+
endpoint="/api/chat"
|
|
21
|
+
brandName="assistant"
|
|
22
|
+
initialMessage="Hey! How can I help you today?"
|
|
23
|
+
/>
|
|
24
|
+
);
|
|
25
|
+
}
|
|
26
|
+
```
|
|
27
|
+
|
|
28
|
+
## How It Works
|
|
29
|
+
|
|
30
|
+
Your backend streams responses to the chat. When the AI wants to trigger an action, it includes a tool call at the end of its response:
|
|
31
|
+
|
|
32
|
+
```
|
|
33
|
+
Great, let me show you the available times.
|
|
34
|
+
|
|
35
|
+
[TOOL:show_slots]
|
|
36
|
+
```
|
|
37
|
+
|
|
38
|
+
The component parses this, executes the corresponding tool handler, and renders the result inline in the chat.
|
|
39
|
+
|
|
40
|
+
## Tools
|
|
41
|
+
|
|
42
|
+
Tools are handlers that run when the AI invokes them. They can render UI, call APIs, update parent state — anything.
|
|
43
|
+
|
|
44
|
+
```tsx
|
|
45
|
+
import { ChatGSD, Tool } from "chatgsd";
|
|
46
|
+
|
|
47
|
+
const tools: Record<string, Tool> = {
|
|
48
|
+
show_slots: {
|
|
49
|
+
handler: async (args, messages) => {
|
|
50
|
+
// Fetch data, update state, etc.
|
|
51
|
+
return { success: true };
|
|
52
|
+
},
|
|
53
|
+
renderSuccess: () => (
|
|
54
|
+
<div className="slots">
|
|
55
|
+
{slots.map(slot => (
|
|
56
|
+
<button key={slot.id} onClick={() => selectSlot(slot)}>
|
|
57
|
+
{slot.time}
|
|
58
|
+
</button>
|
|
59
|
+
))}
|
|
60
|
+
</div>
|
|
61
|
+
),
|
|
62
|
+
},
|
|
63
|
+
|
|
64
|
+
submit_inquiry: {
|
|
65
|
+
terminal: true, // Ends the conversation
|
|
66
|
+
handler: async (args, messages) => {
|
|
67
|
+
await fetch("/api/submit", {
|
|
68
|
+
method: "POST",
|
|
69
|
+
body: JSON.stringify({ messages }),
|
|
70
|
+
});
|
|
71
|
+
return { success: true, message: "Submitted!" };
|
|
72
|
+
},
|
|
73
|
+
},
|
|
74
|
+
};
|
|
75
|
+
|
|
76
|
+
<ChatGSD endpoint="/api/chat" tools={tools} />
|
|
77
|
+
```
|
|
78
|
+
|
|
79
|
+
### Tool Format
|
|
80
|
+
|
|
81
|
+
The AI can invoke tools in two ways:
|
|
82
|
+
|
|
83
|
+
```
|
|
84
|
+
[TOOL:name]
|
|
85
|
+
[TOOL:name({"key": "value"})]
|
|
86
|
+
```
|
|
87
|
+
|
|
88
|
+
Arguments are parsed as JSON and passed to the handler.
|
|
89
|
+
|
|
90
|
+
### Tool Configuration
|
|
91
|
+
|
|
92
|
+
| Property | Type | Description |
|
|
93
|
+
|----------|------|-------------|
|
|
94
|
+
| `handler` | `(args, messages) => Promise<ToolResult>` | Called when tool is invoked |
|
|
95
|
+
| `terminal` | `boolean` | If true, ends the conversation |
|
|
96
|
+
| `renderCalling` | `() => ReactNode` | Custom UI while tool is running |
|
|
97
|
+
| `renderSuccess` | `(result) => ReactNode` | Custom UI on success |
|
|
98
|
+
| `renderError` | `(result) => ReactNode` | Custom UI on error |
|
|
99
|
+
|
|
100
|
+
### ToolResult
|
|
101
|
+
|
|
102
|
+
```ts
|
|
103
|
+
interface ToolResult {
|
|
104
|
+
success: boolean;
|
|
105
|
+
message?: string;
|
|
106
|
+
}
|
|
107
|
+
```
|
|
108
|
+
|
|
109
|
+
## Props
|
|
110
|
+
|
|
111
|
+
| Prop | Type | Default | Description |
|
|
112
|
+
|------|------|---------|-------------|
|
|
113
|
+
| `endpoint` | `string` | `"/api/chat"` | Chat API endpoint |
|
|
114
|
+
| `tools` | `Record<string, Tool>` | `{}` | Tool definitions |
|
|
115
|
+
| `context` | `Record<string, unknown>` | `{}` | Context sent with each request |
|
|
116
|
+
| `headers` | `Record<string, string>` | `{}` | Custom headers for API requests |
|
|
117
|
+
| `brandName` | `string` | `"assistant"` | Name shown in chat |
|
|
118
|
+
| `initialMessage` | `string` | `"How can I help?"` | First message displayed |
|
|
119
|
+
| `className` | `string` | `""` | Additional CSS class |
|
|
120
|
+
| `onMessagesChange` | `(messages) => void` | - | Called when messages update |
|
|
121
|
+
| `onComplete` | `(messages) => void` | - | Called when conversation ends |
|
|
122
|
+
|
|
123
|
+
## Backend API
|
|
124
|
+
|
|
125
|
+
The component expects a streaming endpoint that accepts:
|
|
126
|
+
|
|
127
|
+
```ts
|
|
128
|
+
// Request
|
|
129
|
+
{
|
|
130
|
+
messages: Array<{ role: "system" | "user", content: string }>,
|
|
131
|
+
context: Record<string, unknown>
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
// Response: streaming text, optionally ending with [TOOL:name]
|
|
135
|
+
```
|
|
136
|
+
|
|
137
|
+
### Example (Node.js)
|
|
138
|
+
|
|
139
|
+
```ts
|
|
140
|
+
app.post("/api/chat", async (req, res) => {
|
|
141
|
+
const { messages, context } = req.body;
|
|
142
|
+
|
|
143
|
+
const stream = await openai.chat.completions.create({
|
|
144
|
+
model: "gpt-4",
|
|
145
|
+
stream: true,
|
|
146
|
+
messages: [
|
|
147
|
+
{
|
|
148
|
+
role: "system",
|
|
149
|
+
content: `You are a helpful assistant. You have these tools available:
|
|
150
|
+
- [TOOL:show_slots] - Show available meeting times
|
|
151
|
+
- [TOOL:submit_inquiry] - Submit the inquiry (use when you have enough info)
|
|
152
|
+
|
|
153
|
+
When you want to use a tool, end your message with the tool call.`
|
|
154
|
+
},
|
|
155
|
+
...messages.map(m => ({ role: m.role, content: m.content }))
|
|
156
|
+
],
|
|
157
|
+
});
|
|
158
|
+
|
|
159
|
+
res.setHeader("Content-Type", "text/plain");
|
|
160
|
+
|
|
161
|
+
for await (const chunk of stream) {
|
|
162
|
+
const text = chunk.choices[0]?.delta?.content || "";
|
|
163
|
+
res.write(text);
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
res.end();
|
|
167
|
+
});
|
|
168
|
+
```
|
|
169
|
+
|
|
170
|
+
## Styling
|
|
171
|
+
|
|
172
|
+
Import the default styles:
|
|
173
|
+
|
|
174
|
+
```tsx
|
|
175
|
+
import "chatgsd/styles.css";
|
|
176
|
+
```
|
|
177
|
+
|
|
178
|
+
Customize with CSS variables:
|
|
179
|
+
|
|
180
|
+
```css
|
|
181
|
+
:root {
|
|
182
|
+
--chatgsd-bg: #0a0a0a;
|
|
183
|
+
--chatgsd-border: #333;
|
|
184
|
+
--chatgsd-green: #27ca40;
|
|
185
|
+
--chatgsd-yellow: #ffbd2e;
|
|
186
|
+
--chatgsd-red: #ff5f56;
|
|
187
|
+
--chatgsd-text: #e0e0e0;
|
|
188
|
+
--chatgsd-muted: #666;
|
|
189
|
+
--chatgsd-font: ui-monospace, monospace;
|
|
190
|
+
}
|
|
191
|
+
```
|
|
192
|
+
|
|
193
|
+
Or write your own styles targeting `.chatgsd-*` classes.
|
|
194
|
+
|
|
195
|
+
## Example
|
|
196
|
+
|
|
197
|
+
Run the example app:
|
|
198
|
+
|
|
199
|
+
```bash
|
|
200
|
+
cd example
|
|
201
|
+
npm install
|
|
202
|
+
npm run dev
|
|
203
|
+
```
|
|
204
|
+
|
|
205
|
+
## License
|
|
206
|
+
|
|
207
|
+
MIT
|
package/dist/index.cjs
ADDED
|
@@ -0,0 +1,329 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __defProp = Object.defineProperty;
|
|
3
|
+
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
4
|
+
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
5
|
+
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
6
|
+
var __export = (target, all) => {
|
|
7
|
+
for (var name in all)
|
|
8
|
+
__defProp(target, name, { get: all[name], enumerable: true });
|
|
9
|
+
};
|
|
10
|
+
var __copyProps = (to, from, except, desc) => {
|
|
11
|
+
if (from && typeof from === "object" || typeof from === "function") {
|
|
12
|
+
for (let key of __getOwnPropNames(from))
|
|
13
|
+
if (!__hasOwnProp.call(to, key) && key !== except)
|
|
14
|
+
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
|
15
|
+
}
|
|
16
|
+
return to;
|
|
17
|
+
};
|
|
18
|
+
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
|
19
|
+
|
|
20
|
+
// src/index.ts
|
|
21
|
+
var index_exports = {};
|
|
22
|
+
__export(index_exports, {
|
|
23
|
+
ChatGSD: () => ChatGSD
|
|
24
|
+
});
|
|
25
|
+
module.exports = __toCommonJS(index_exports);
|
|
26
|
+
|
|
27
|
+
// src/ChatGSD.tsx
|
|
28
|
+
var import_react = require("react");
|
|
29
|
+
var import_jsx_runtime = require("react/jsx-runtime");
|
|
30
|
+
function generateId() {
|
|
31
|
+
return Math.random().toString(36).substring(2, 11);
|
|
32
|
+
}
|
|
33
|
+
function parseToolCall(content) {
|
|
34
|
+
const match = content.match(/\[TOOL:(\w+)(?:\((\{.*\})\))?\]$/);
|
|
35
|
+
if (!match) return null;
|
|
36
|
+
const name = match[1];
|
|
37
|
+
let args = {};
|
|
38
|
+
if (match[2]) {
|
|
39
|
+
try {
|
|
40
|
+
args = JSON.parse(match[2]);
|
|
41
|
+
} catch {
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
return { name, args };
|
|
45
|
+
}
|
|
46
|
+
function ChatGSD({
|
|
47
|
+
initialMessage = "How can I help you today?",
|
|
48
|
+
onMessagesChange,
|
|
49
|
+
tools = {},
|
|
50
|
+
endpoint = "/api/chat",
|
|
51
|
+
headers = {},
|
|
52
|
+
context = {},
|
|
53
|
+
brandName = "assistant",
|
|
54
|
+
className = "",
|
|
55
|
+
onComplete
|
|
56
|
+
}) {
|
|
57
|
+
const [messages, setMessages] = (0, import_react.useState)([
|
|
58
|
+
{
|
|
59
|
+
id: generateId(),
|
|
60
|
+
role: "system",
|
|
61
|
+
content: initialMessage,
|
|
62
|
+
timestamp: /* @__PURE__ */ new Date()
|
|
63
|
+
}
|
|
64
|
+
]);
|
|
65
|
+
const [input, setInput] = (0, import_react.useState)("");
|
|
66
|
+
const [cursorVisible, setCursorVisible] = (0, import_react.useState)(true);
|
|
67
|
+
const [isLoading, setIsLoading] = (0, import_react.useState)(false);
|
|
68
|
+
const [conversationEnded, setConversationEnded] = (0, import_react.useState)(false);
|
|
69
|
+
const [activeTool, setActiveTool] = (0, import_react.useState)(null);
|
|
70
|
+
const messagesEndRef = (0, import_react.useRef)(null);
|
|
71
|
+
const inputRef = (0, import_react.useRef)(null);
|
|
72
|
+
const toolTimeoutRef = (0, import_react.useRef)(null);
|
|
73
|
+
(0, import_react.useEffect)(() => {
|
|
74
|
+
const interval = setInterval(() => setCursorVisible((v) => !v), 530);
|
|
75
|
+
return () => clearInterval(interval);
|
|
76
|
+
}, []);
|
|
77
|
+
(0, import_react.useEffect)(() => {
|
|
78
|
+
messagesEndRef.current?.scrollIntoView({
|
|
79
|
+
behavior: "smooth",
|
|
80
|
+
block: "nearest"
|
|
81
|
+
});
|
|
82
|
+
});
|
|
83
|
+
(0, import_react.useEffect)(() => {
|
|
84
|
+
inputRef.current?.focus();
|
|
85
|
+
}, []);
|
|
86
|
+
(0, import_react.useEffect)(() => {
|
|
87
|
+
return () => {
|
|
88
|
+
if (toolTimeoutRef.current) {
|
|
89
|
+
clearTimeout(toolTimeoutRef.current);
|
|
90
|
+
}
|
|
91
|
+
};
|
|
92
|
+
}, []);
|
|
93
|
+
const executeTool = (0, import_react.useCallback)(
|
|
94
|
+
async (toolName, args, currentMessages) => {
|
|
95
|
+
const tool = tools[toolName];
|
|
96
|
+
if (!tool) {
|
|
97
|
+
console.warn(`Unknown tool: ${toolName}`);
|
|
98
|
+
return;
|
|
99
|
+
}
|
|
100
|
+
setActiveTool({ name: toolName, status: "calling" });
|
|
101
|
+
await new Promise((resolve) => {
|
|
102
|
+
toolTimeoutRef.current = setTimeout(resolve, 800);
|
|
103
|
+
});
|
|
104
|
+
try {
|
|
105
|
+
const result = await tool.handler(args, currentMessages);
|
|
106
|
+
setActiveTool({ name: toolName, status: result.success ? "success" : "error", result });
|
|
107
|
+
if (tool.terminal) {
|
|
108
|
+
setConversationEnded(true);
|
|
109
|
+
onComplete?.(currentMessages);
|
|
110
|
+
}
|
|
111
|
+
} catch (err) {
|
|
112
|
+
const message = err instanceof Error ? err.message : "Tool execution failed";
|
|
113
|
+
setActiveTool({ name: toolName, status: "error", result: { success: false, message } });
|
|
114
|
+
}
|
|
115
|
+
},
|
|
116
|
+
[tools, onComplete]
|
|
117
|
+
);
|
|
118
|
+
const fetchAIResponse = (0, import_react.useCallback)(
|
|
119
|
+
async (updatedMessages) => {
|
|
120
|
+
setIsLoading(true);
|
|
121
|
+
const aiMessage = {
|
|
122
|
+
id: generateId(),
|
|
123
|
+
role: "system",
|
|
124
|
+
content: "",
|
|
125
|
+
timestamp: /* @__PURE__ */ new Date()
|
|
126
|
+
};
|
|
127
|
+
setMessages((prev) => [...prev, aiMessage]);
|
|
128
|
+
try {
|
|
129
|
+
const res = await fetch(endpoint, {
|
|
130
|
+
method: "POST",
|
|
131
|
+
headers: {
|
|
132
|
+
"Content-Type": "application/json",
|
|
133
|
+
...headers
|
|
134
|
+
},
|
|
135
|
+
body: JSON.stringify({
|
|
136
|
+
messages: updatedMessages.map((m) => ({
|
|
137
|
+
role: m.role,
|
|
138
|
+
content: m.content
|
|
139
|
+
})),
|
|
140
|
+
context
|
|
141
|
+
})
|
|
142
|
+
});
|
|
143
|
+
if (res.ok && res.body) {
|
|
144
|
+
const reader = res.body.getReader();
|
|
145
|
+
const decoder = new TextDecoder();
|
|
146
|
+
let fullContent = "";
|
|
147
|
+
while (true) {
|
|
148
|
+
const { done, value } = await reader.read();
|
|
149
|
+
if (done) break;
|
|
150
|
+
const chunk = decoder.decode(value, { stream: true });
|
|
151
|
+
fullContent += chunk;
|
|
152
|
+
const displayContent = fullContent.replace(/\n?\[TOOL:\w+(?:\(\{.*\}\))?\]$/, "");
|
|
153
|
+
setMessages((prev) => {
|
|
154
|
+
const updated = [...prev];
|
|
155
|
+
const last = updated[updated.length - 1];
|
|
156
|
+
if (last.role === "system") {
|
|
157
|
+
last.content = displayContent;
|
|
158
|
+
}
|
|
159
|
+
return updated;
|
|
160
|
+
});
|
|
161
|
+
}
|
|
162
|
+
const toolCall = parseToolCall(fullContent);
|
|
163
|
+
if (toolCall) {
|
|
164
|
+
const finalMessages = [...updatedMessages, {
|
|
165
|
+
id: generateId(),
|
|
166
|
+
role: "system",
|
|
167
|
+
content: fullContent.replace(/\n?\[TOOL:\w+(?:\(\{.*\}\))?\]$/, ""),
|
|
168
|
+
timestamp: /* @__PURE__ */ new Date()
|
|
169
|
+
}];
|
|
170
|
+
await executeTool(toolCall.name, toolCall.args, finalMessages);
|
|
171
|
+
}
|
|
172
|
+
}
|
|
173
|
+
} catch {
|
|
174
|
+
} finally {
|
|
175
|
+
setIsLoading(false);
|
|
176
|
+
}
|
|
177
|
+
},
|
|
178
|
+
[endpoint, headers, context, executeTool]
|
|
179
|
+
);
|
|
180
|
+
const handleSend = (0, import_react.useCallback)(async () => {
|
|
181
|
+
if (!input.trim() || isLoading || conversationEnded) return;
|
|
182
|
+
const newMessage = {
|
|
183
|
+
id: generateId(),
|
|
184
|
+
role: "user",
|
|
185
|
+
content: input.trim(),
|
|
186
|
+
timestamp: /* @__PURE__ */ new Date()
|
|
187
|
+
};
|
|
188
|
+
const updated = [...messages, newMessage];
|
|
189
|
+
setMessages(updated);
|
|
190
|
+
onMessagesChange?.(updated);
|
|
191
|
+
setInput("");
|
|
192
|
+
await fetchAIResponse(updated);
|
|
193
|
+
}, [input, isLoading, conversationEnded, messages, onMessagesChange, fetchAIResponse]);
|
|
194
|
+
const handleKeyDown = (0, import_react.useCallback)(
|
|
195
|
+
async (e) => {
|
|
196
|
+
if (e.key === "Enter" && !e.shiftKey) {
|
|
197
|
+
e.preventDefault();
|
|
198
|
+
await handleSend();
|
|
199
|
+
}
|
|
200
|
+
},
|
|
201
|
+
[handleSend]
|
|
202
|
+
);
|
|
203
|
+
const downloadTranscript = (0, import_react.useCallback)(() => {
|
|
204
|
+
const transcript = messages.map((m) => `${m.role === "system" ? `[${brandName}]` : "[you]"} ${m.content}`).join("\n\n");
|
|
205
|
+
const blob = new Blob([transcript], { type: "text/plain" });
|
|
206
|
+
const url = URL.createObjectURL(blob);
|
|
207
|
+
const a = document.createElement("a");
|
|
208
|
+
a.href = url;
|
|
209
|
+
a.download = `chat-${(/* @__PURE__ */ new Date()).toISOString().split("T")[0]}.txt`;
|
|
210
|
+
a.click();
|
|
211
|
+
URL.revokeObjectURL(url);
|
|
212
|
+
}, [messages, brandName]);
|
|
213
|
+
const renderToolStatus = () => {
|
|
214
|
+
if (!activeTool) return null;
|
|
215
|
+
const tool = tools[activeTool.name];
|
|
216
|
+
const { name, status, result } = activeTool;
|
|
217
|
+
if (status === "calling") {
|
|
218
|
+
if (tool?.renderCalling) {
|
|
219
|
+
return tool.renderCalling();
|
|
220
|
+
}
|
|
221
|
+
return /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", { className: "chatgsd-status-calling", children: [
|
|
222
|
+
/* @__PURE__ */ (0, import_jsx_runtime.jsx)("span", { className: "chatgsd-message-prefix", children: "[tool]" }),
|
|
223
|
+
/* @__PURE__ */ (0, import_jsx_runtime.jsxs)("span", { className: "chatgsd-status-spinner", children: [
|
|
224
|
+
/* @__PURE__ */ (0, import_jsx_runtime.jsx)("span", { className: "chatgsd-spinner", children: "\u25D0" }),
|
|
225
|
+
/* @__PURE__ */ (0, import_jsx_runtime.jsxs)("span", { children: [
|
|
226
|
+
name,
|
|
227
|
+
"()"
|
|
228
|
+
] })
|
|
229
|
+
] })
|
|
230
|
+
] });
|
|
231
|
+
}
|
|
232
|
+
if (status === "success") {
|
|
233
|
+
if (tool?.renderSuccess && result) {
|
|
234
|
+
return tool.renderSuccess(result);
|
|
235
|
+
}
|
|
236
|
+
return /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", { className: "chatgsd-status-success", children: [
|
|
237
|
+
/* @__PURE__ */ (0, import_jsx_runtime.jsx)("span", { className: "chatgsd-message-prefix", children: "[tool]" }),
|
|
238
|
+
/* @__PURE__ */ (0, import_jsx_runtime.jsxs)("span", { children: [
|
|
239
|
+
"\u2713 ",
|
|
240
|
+
name,
|
|
241
|
+
"() \u2014 ",
|
|
242
|
+
result?.message || "success"
|
|
243
|
+
] })
|
|
244
|
+
] });
|
|
245
|
+
}
|
|
246
|
+
if (status === "error") {
|
|
247
|
+
if (tool?.renderError && result) {
|
|
248
|
+
return tool.renderError(result);
|
|
249
|
+
}
|
|
250
|
+
return /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", { className: "chatgsd-status-error", children: [
|
|
251
|
+
/* @__PURE__ */ (0, import_jsx_runtime.jsx)("span", { className: "chatgsd-message-prefix", children: "[tool]" }),
|
|
252
|
+
/* @__PURE__ */ (0, import_jsx_runtime.jsxs)("span", { children: [
|
|
253
|
+
"\u2717 ",
|
|
254
|
+
name,
|
|
255
|
+
"() \u2014 ",
|
|
256
|
+
result?.message || "failed"
|
|
257
|
+
] })
|
|
258
|
+
] });
|
|
259
|
+
}
|
|
260
|
+
return null;
|
|
261
|
+
};
|
|
262
|
+
return /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", { className: `chatgsd ${className}`.trim(), children: [
|
|
263
|
+
/* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", { className: "chatgsd-messages", children: [
|
|
264
|
+
messages.map((msg) => /* @__PURE__ */ (0, import_jsx_runtime.jsx)("div", { className: "chatgsd-message", children: msg.role === "system" ? /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", { className: "chatgsd-message-system", children: [
|
|
265
|
+
/* @__PURE__ */ (0, import_jsx_runtime.jsxs)("span", { className: "chatgsd-message-prefix", children: [
|
|
266
|
+
"[",
|
|
267
|
+
brandName,
|
|
268
|
+
"]"
|
|
269
|
+
] }),
|
|
270
|
+
" ",
|
|
271
|
+
msg.content
|
|
272
|
+
] }) : /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", { className: "chatgsd-message-user", children: [
|
|
273
|
+
/* @__PURE__ */ (0, import_jsx_runtime.jsx)("span", { className: "chatgsd-message-prompt", children: ">" }),
|
|
274
|
+
" ",
|
|
275
|
+
msg.content
|
|
276
|
+
] }) }, msg.id)),
|
|
277
|
+
activeTool && activeTool.status !== "idle" && /* @__PURE__ */ (0, import_jsx_runtime.jsx)("div", { className: "chatgsd-tool-status", children: renderToolStatus() }),
|
|
278
|
+
/* @__PURE__ */ (0, import_jsx_runtime.jsx)("div", { ref: messagesEndRef })
|
|
279
|
+
] }),
|
|
280
|
+
/* @__PURE__ */ (0, import_jsx_runtime.jsx)("div", { className: "chatgsd-input-area", children: conversationEnded ? /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", { className: "chatgsd-session-complete", children: [
|
|
281
|
+
/* @__PURE__ */ (0, import_jsx_runtime.jsx)("span", { className: "chatgsd-session-label", children: "session complete" }),
|
|
282
|
+
/* @__PURE__ */ (0, import_jsx_runtime.jsxs)(
|
|
283
|
+
"button",
|
|
284
|
+
{
|
|
285
|
+
type: "button",
|
|
286
|
+
onClick: downloadTranscript,
|
|
287
|
+
className: "chatgsd-download-btn",
|
|
288
|
+
children: [
|
|
289
|
+
/* @__PURE__ */ (0, import_jsx_runtime.jsx)("span", { children: "\u2193" }),
|
|
290
|
+
" download transcript"
|
|
291
|
+
]
|
|
292
|
+
}
|
|
293
|
+
)
|
|
294
|
+
] }) : /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(import_jsx_runtime.Fragment, { children: [
|
|
295
|
+
/* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", { className: "chatgsd-input-line", children: [
|
|
296
|
+
/* @__PURE__ */ (0, import_jsx_runtime.jsx)("span", { className: "chatgsd-message-prompt", children: ">" }),
|
|
297
|
+
/* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", { className: "chatgsd-input-display", children: [
|
|
298
|
+
/* @__PURE__ */ (0, import_jsx_runtime.jsx)("span", { className: "chatgsd-input-text", children: input }),
|
|
299
|
+
/* @__PURE__ */ (0, import_jsx_runtime.jsx)(
|
|
300
|
+
"span",
|
|
301
|
+
{
|
|
302
|
+
className: `chatgsd-cursor ${cursorVisible ? "chatgsd-cursor-visible" : "chatgsd-cursor-hidden"}`,
|
|
303
|
+
children: "\u2588"
|
|
304
|
+
}
|
|
305
|
+
),
|
|
306
|
+
/* @__PURE__ */ (0, import_jsx_runtime.jsx)(
|
|
307
|
+
"textarea",
|
|
308
|
+
{
|
|
309
|
+
ref: inputRef,
|
|
310
|
+
value: input,
|
|
311
|
+
onChange: (e) => setInput(e.target.value),
|
|
312
|
+
onKeyDown: handleKeyDown,
|
|
313
|
+
rows: 1,
|
|
314
|
+
className: "chatgsd-sr-only",
|
|
315
|
+
disabled: conversationEnded,
|
|
316
|
+
"aria-label": "Chat input"
|
|
317
|
+
}
|
|
318
|
+
)
|
|
319
|
+
] })
|
|
320
|
+
] }),
|
|
321
|
+
/* @__PURE__ */ (0, import_jsx_runtime.jsx)("div", { className: "chatgsd-input-hint", children: "press enter to send \xB7 shift+enter for new line" })
|
|
322
|
+
] }) })
|
|
323
|
+
] });
|
|
324
|
+
}
|
|
325
|
+
// Annotate the CommonJS export names for ESM import in node:
|
|
326
|
+
0 && (module.exports = {
|
|
327
|
+
ChatGSD
|
|
328
|
+
});
|
|
329
|
+
//# sourceMappingURL=index.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/index.ts","../src/ChatGSD.tsx"],"sourcesContent":["// Components\nexport { ChatGSD } from \"./ChatGSD\";\nexport type { ChatGSDProps } from \"./ChatGSD\";\n\n// Types\nexport type {\n ChatMessage,\n ToolStatus,\n ToolCall,\n ToolResult,\n ToolHandler,\n Tool,\n ChatContext,\n ChatApiRequest,\n} from \"./types\";\n","import { useState, useRef, useEffect, useCallback } from \"react\";\nimport type { KeyboardEvent, ReactNode } from \"react\";\nimport type { ChatMessage, ToolStatus, Tool, ToolResult, ChatContext } from \"./types\";\n\nfunction generateId(): string {\n return Math.random().toString(36).substring(2, 11);\n}\n\n// Parse tool calls from content: [TOOL:name] or [TOOL:name({\"arg\": \"value\"})]\nfunction parseToolCall(content: string): { name: string; args: Record<string, unknown> } | null {\n const match = content.match(/\\[TOOL:(\\w+)(?:\\((\\{.*\\})\\))?\\]$/);\n if (!match) return null;\n \n const name = match[1];\n let args: Record<string, unknown> = {};\n \n if (match[2]) {\n try {\n args = JSON.parse(match[2]);\n } catch {\n // Invalid JSON, use empty args\n }\n }\n \n return { name, args };\n}\n\nexport interface ChatGSDProps {\n /** Initial system message to display */\n initialMessage?: string;\n /** Callback when messages change */\n onMessagesChange?: (messages: ChatMessage[]) => void;\n /** Tool definitions - key is tool name, value is tool config */\n tools?: Record<string, Tool>;\n /** Custom chat API endpoint */\n endpoint?: string;\n /** Custom headers to include in API requests */\n headers?: Record<string, string>;\n /** Additional context to send with each request */\n context?: ChatContext;\n /** Brand name to display in chat */\n brandName?: string;\n /** Custom class name */\n className?: string;\n /** Called when conversation ends (terminal tool completes) */\n onComplete?: (messages: ChatMessage[]) => void;\n}\n\ninterface ActiveTool {\n name: string;\n status: ToolStatus;\n result?: ToolResult;\n}\n\nexport function ChatGSD({\n initialMessage = \"How can I help you today?\",\n onMessagesChange,\n tools = {},\n endpoint = \"/api/chat\",\n headers = {},\n context = {},\n brandName = \"assistant\",\n className = \"\",\n onComplete,\n}: ChatGSDProps) {\n const [messages, setMessages] = useState<ChatMessage[]>([\n {\n id: generateId(),\n role: \"system\",\n content: initialMessage,\n timestamp: new Date(),\n },\n ]);\n const [input, setInput] = useState(\"\");\n const [cursorVisible, setCursorVisible] = useState(true);\n const [isLoading, setIsLoading] = useState(false);\n const [conversationEnded, setConversationEnded] = useState(false);\n const [activeTool, setActiveTool] = useState<ActiveTool | null>(null);\n const messagesEndRef = useRef<HTMLDivElement>(null);\n const inputRef = useRef<HTMLTextAreaElement>(null);\n const toolTimeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null);\n\n // Cursor blink effect\n useEffect(() => {\n const interval = setInterval(() => setCursorVisible((v) => !v), 530);\n return () => clearInterval(interval);\n }, []);\n\n // Auto-scroll to bottom\n useEffect(() => {\n messagesEndRef.current?.scrollIntoView({\n behavior: \"smooth\",\n block: \"nearest\",\n });\n });\n\n // Focus input on mount\n useEffect(() => {\n inputRef.current?.focus();\n }, []);\n\n // Cleanup timeout on unmount\n useEffect(() => {\n return () => {\n if (toolTimeoutRef.current) {\n clearTimeout(toolTimeoutRef.current);\n }\n };\n }, []);\n\n const executeTool = useCallback(\n async (toolName: string, args: Record<string, unknown>, currentMessages: ChatMessage[]) => {\n const tool = tools[toolName];\n if (!tool) {\n console.warn(`Unknown tool: ${toolName}`);\n return;\n }\n\n setActiveTool({ name: toolName, status: \"calling\" });\n\n // Small delay for visual feedback\n await new Promise((resolve) => {\n toolTimeoutRef.current = setTimeout(resolve, 800);\n });\n\n try {\n const result = await tool.handler(args, currentMessages);\n setActiveTool({ name: toolName, status: result.success ? \"success\" : \"error\", result });\n\n if (tool.terminal) {\n setConversationEnded(true);\n onComplete?.(currentMessages);\n }\n } catch (err) {\n const message = err instanceof Error ? err.message : \"Tool execution failed\";\n setActiveTool({ name: toolName, status: \"error\", result: { success: false, message } });\n }\n },\n [tools, onComplete]\n );\n\n const fetchAIResponse = useCallback(\n async (updatedMessages: ChatMessage[]) => {\n setIsLoading(true);\n\n const aiMessage: ChatMessage = {\n id: generateId(),\n role: \"system\",\n content: \"\",\n timestamp: new Date(),\n };\n setMessages((prev) => [...prev, aiMessage]);\n\n try {\n const res = await fetch(endpoint, {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n ...headers,\n },\n body: JSON.stringify({\n messages: updatedMessages.map((m) => ({\n role: m.role,\n content: m.content,\n })),\n context,\n }),\n });\n\n if (res.ok && res.body) {\n const reader = res.body.getReader();\n const decoder = new TextDecoder();\n let fullContent = \"\";\n\n while (true) {\n const { done, value } = await reader.read();\n if (done) break;\n\n const chunk = decoder.decode(value, { stream: true });\n fullContent += chunk;\n\n // Strip any tool call from display\n const displayContent = fullContent.replace(/\\n?\\[TOOL:\\w+(?:\\(\\{.*\\}\\))?\\]$/, \"\");\n setMessages((prev) => {\n const updated = [...prev];\n const last = updated[updated.length - 1];\n if (last.role === \"system\") {\n last.content = displayContent;\n }\n return updated;\n });\n }\n\n // Check for tool call\n const toolCall = parseToolCall(fullContent);\n if (toolCall) {\n const finalMessages = [...updatedMessages, { \n id: generateId(), \n role: \"system\" as const, \n content: fullContent.replace(/\\n?\\[TOOL:\\w+(?:\\(\\{.*\\}\\))?\\]$/, \"\"),\n timestamp: new Date()\n }];\n await executeTool(toolCall.name, toolCall.args, finalMessages);\n }\n }\n } catch {\n // Silently fail - the chat still works without AI responses\n } finally {\n setIsLoading(false);\n }\n },\n [endpoint, headers, context, executeTool]\n );\n\n const handleSend = useCallback(async () => {\n if (!input.trim() || isLoading || conversationEnded) return;\n\n const newMessage: ChatMessage = {\n id: generateId(),\n role: \"user\",\n content: input.trim(),\n timestamp: new Date(),\n };\n const updated = [...messages, newMessage];\n setMessages(updated);\n onMessagesChange?.(updated);\n setInput(\"\");\n\n await fetchAIResponse(updated);\n }, [input, isLoading, conversationEnded, messages, onMessagesChange, fetchAIResponse]);\n\n const handleKeyDown = useCallback(\n async (e: KeyboardEvent<HTMLTextAreaElement>) => {\n if (e.key === \"Enter\" && !e.shiftKey) {\n e.preventDefault();\n await handleSend();\n }\n },\n [handleSend]\n );\n\n const downloadTranscript = useCallback(() => {\n const transcript = messages\n .map((m) => `${m.role === \"system\" ? `[${brandName}]` : \"[you]\"} ${m.content}`)\n .join(\"\\n\\n\");\n const blob = new Blob([transcript], { type: \"text/plain\" });\n const url = URL.createObjectURL(blob);\n const a = document.createElement(\"a\");\n a.href = url;\n a.download = `chat-${new Date().toISOString().split(\"T\")[0]}.txt`;\n a.click();\n URL.revokeObjectURL(url);\n }, [messages, brandName]);\n\n // Render tool status\n const renderToolStatus = (): ReactNode => {\n if (!activeTool) return null;\n\n const tool = tools[activeTool.name];\n const { name, status, result } = activeTool;\n\n if (status === \"calling\") {\n if (tool?.renderCalling) {\n return tool.renderCalling();\n }\n return (\n <div className=\"chatgsd-status-calling\">\n <span className=\"chatgsd-message-prefix\">[tool]</span>\n <span className=\"chatgsd-status-spinner\">\n <span className=\"chatgsd-spinner\">◐</span>\n <span>{name}()</span>\n </span>\n </div>\n );\n }\n\n if (status === \"success\") {\n if (tool?.renderSuccess && result) {\n return tool.renderSuccess(result);\n }\n return (\n <div className=\"chatgsd-status-success\">\n <span className=\"chatgsd-message-prefix\">[tool]</span>\n <span>✓ {name}() — {result?.message || \"success\"}</span>\n </div>\n );\n }\n\n if (status === \"error\") {\n if (tool?.renderError && result) {\n return tool.renderError(result);\n }\n return (\n <div className=\"chatgsd-status-error\">\n <span className=\"chatgsd-message-prefix\">[tool]</span>\n <span>✗ {name}() — {result?.message || \"failed\"}</span>\n </div>\n );\n }\n\n return null;\n };\n\n return (\n <div className={`chatgsd ${className}`.trim()}>\n {/* Messages area */}\n <div className=\"chatgsd-messages\">\n {messages.map((msg) => (\n <div key={msg.id} className=\"chatgsd-message\">\n {msg.role === \"system\" ? (\n <div className=\"chatgsd-message-system\">\n <span className=\"chatgsd-message-prefix\">[{brandName}]</span>{\" \"}\n {msg.content}\n </div>\n ) : (\n <div className=\"chatgsd-message-user\">\n <span className=\"chatgsd-message-prompt\">></span>{\" \"}\n {msg.content}\n </div>\n )}\n </div>\n ))}\n\n {activeTool && activeTool.status !== \"idle\" && (\n <div className=\"chatgsd-tool-status\">\n {renderToolStatus()}\n </div>\n )}\n\n <div ref={messagesEndRef} />\n </div>\n\n {/* Input area */}\n <div className=\"chatgsd-input-area\">\n {conversationEnded ? (\n <div className=\"chatgsd-session-complete\">\n <span className=\"chatgsd-session-label\">session complete</span>\n <button\n type=\"button\"\n onClick={downloadTranscript}\n className=\"chatgsd-download-btn\"\n >\n <span>↓</span> download transcript\n </button>\n </div>\n ) : (\n <>\n <div className=\"chatgsd-input-line\">\n <span className=\"chatgsd-message-prompt\">></span>\n <div className=\"chatgsd-input-display\">\n <span className=\"chatgsd-input-text\">{input}</span>\n <span\n className={`chatgsd-cursor ${cursorVisible ? \"chatgsd-cursor-visible\" : \"chatgsd-cursor-hidden\"}`}\n >\n █\n </span>\n <textarea\n ref={inputRef}\n value={input}\n onChange={(e) => setInput(e.target.value)}\n onKeyDown={handleKeyDown}\n rows={1}\n className=\"chatgsd-sr-only\"\n disabled={conversationEnded}\n aria-label=\"Chat input\"\n />\n </div>\n </div>\n <div className=\"chatgsd-input-hint\">\n press enter to send · shift+enter for new line\n </div>\n </>\n )}\n </div>\n </div>\n );\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACAA,mBAAyD;AA2Q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cACN,WAAU;AAAA,cACV,UAAU;AAAA,cACV,cAAW;AAAA;AAAA,UACb;AAAA,WACF;AAAA,SACF;AAAA,MACA,4CAAC,SAAI,WAAU,sBAAqB,+DAEpC;AAAA,OACF,GAEJ;AAAA,KACF;AAEJ;","names":[]}
|
package/dist/index.d.cts
ADDED
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
import * as react_jsx_runtime from 'react/jsx-runtime';
|
|
2
|
+
|
|
3
|
+
type ChatMessage = {
|
|
4
|
+
id: string;
|
|
5
|
+
role: "system" | "user";
|
|
6
|
+
content: string;
|
|
7
|
+
timestamp: Date;
|
|
8
|
+
};
|
|
9
|
+
type ToolStatus = "idle" | "calling" | "success" | "error";
|
|
10
|
+
interface ToolCall {
|
|
11
|
+
name: string;
|
|
12
|
+
args?: Record<string, unknown>;
|
|
13
|
+
}
|
|
14
|
+
interface ToolResult {
|
|
15
|
+
success: boolean;
|
|
16
|
+
message?: string;
|
|
17
|
+
}
|
|
18
|
+
type ToolHandler = (args: Record<string, unknown>, messages: ChatMessage[]) => Promise<ToolResult>;
|
|
19
|
+
interface Tool {
|
|
20
|
+
/** Handler function called when the tool is invoked */
|
|
21
|
+
handler: ToolHandler;
|
|
22
|
+
/** Whether this tool ends the conversation (default: false) */
|
|
23
|
+
terminal?: boolean;
|
|
24
|
+
/** Custom render for the "calling" state */
|
|
25
|
+
renderCalling?: () => React.ReactNode;
|
|
26
|
+
/** Custom render for the "success" state */
|
|
27
|
+
renderSuccess?: (result: ToolResult) => React.ReactNode;
|
|
28
|
+
/** Custom render for the "error" state */
|
|
29
|
+
renderError?: (result: ToolResult) => React.ReactNode;
|
|
30
|
+
}
|
|
31
|
+
interface ChatContext {
|
|
32
|
+
[key: string]: unknown;
|
|
33
|
+
}
|
|
34
|
+
interface ChatApiRequest {
|
|
35
|
+
messages: Array<{
|
|
36
|
+
role: string;
|
|
37
|
+
content: string;
|
|
38
|
+
}>;
|
|
39
|
+
context: ChatContext;
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
interface ChatGSDProps {
|
|
43
|
+
/** Initial system message to display */
|
|
44
|
+
initialMessage?: string;
|
|
45
|
+
/** Callback when messages change */
|
|
46
|
+
onMessagesChange?: (messages: ChatMessage[]) => void;
|
|
47
|
+
/** Tool definitions - key is tool name, value is tool config */
|
|
48
|
+
tools?: Record<string, Tool>;
|
|
49
|
+
/** Custom chat API endpoint */
|
|
50
|
+
endpoint?: string;
|
|
51
|
+
/** Custom headers to include in API requests */
|
|
52
|
+
headers?: Record<string, string>;
|
|
53
|
+
/** Additional context to send with each request */
|
|
54
|
+
context?: ChatContext;
|
|
55
|
+
/** Brand name to display in chat */
|
|
56
|
+
brandName?: string;
|
|
57
|
+
/** Custom class name */
|
|
58
|
+
className?: string;
|
|
59
|
+
/** Called when conversation ends (terminal tool completes) */
|
|
60
|
+
onComplete?: (messages: ChatMessage[]) => void;
|
|
61
|
+
}
|
|
62
|
+
declare function ChatGSD({ initialMessage, onMessagesChange, tools, endpoint, headers, context, brandName, className, onComplete, }: ChatGSDProps): react_jsx_runtime.JSX.Element;
|
|
63
|
+
|
|
64
|
+
export { type ChatApiRequest, type ChatContext, ChatGSD, type ChatGSDProps, type ChatMessage, type Tool, type ToolCall, type ToolHandler, type ToolResult, type ToolStatus };
|