chatbotlite 0.3.1 → 0.5.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.
@@ -5,8 +5,60 @@ var jsxRuntime = require('react/jsx-runtime');
5
5
 
6
6
  // src/react/ChatWidget.tsx
7
7
 
8
+ // src/core/tools.ts
9
+ var MARKER_RE = /\[SKILL:(\w+)((?:\s+\w+=(?:"[^"]*"|[\w./@*+,:-]+))*)\s*\]/g;
10
+ var ARG_RE = /(\w+)=("([^"]*)"|([\w./@*+,:-]+))/g;
11
+ function coerce(value) {
12
+ if (value === "true") return true;
13
+ if (value === "false") return false;
14
+ if (/^-?\d+(?:\.\d+)?$/.test(value)) return Number(value);
15
+ return value;
16
+ }
17
+ function parseToolMarkers(text) {
18
+ const markers = [];
19
+ let m;
20
+ MARKER_RE.lastIndex = 0;
21
+ while ((m = MARKER_RE.exec(text)) !== null) {
22
+ const name = m[1];
23
+ const argsRaw = m[2] ?? "";
24
+ const args = {};
25
+ let a;
26
+ ARG_RE.lastIndex = 0;
27
+ while ((a = ARG_RE.exec(argsRaw)) !== null) {
28
+ const key = a[1];
29
+ const value = a[3] ?? a[4] ?? "";
30
+ args[key] = coerce(value);
31
+ }
32
+ markers.push({ name, args, raw: m[0] });
33
+ }
34
+ return markers;
35
+ }
36
+ function stripToolMarkers(text) {
37
+ return text.replace(MARKER_RE, "").replace(/\s+\n/g, "\n").trim();
38
+ }
39
+ function buildToolsPromptAddendum(enabledTools) {
40
+ if (enabledTools.length === 0) return "";
41
+ const examples = {
42
+ uploadForReview: '[SKILL:uploadForReview purpose="T4 slip" accept="image/*,application/pdf" maxMb=10] \u2014 collect a document for human review (bytes go to webhook, you never see content)',
43
+ scheduleCallback: '[SKILL:scheduleCallback durationMin=15 timezone="America/Vancouver"] \u2014 let the user pick a callback time slot',
44
+ requestPayment: '[SKILL:requestPayment amount=4250 currency="cad" reason="initial deposit"] \u2014 collect payment via inline card'
45
+ };
46
+ const lines = enabledTools.filter((t) => examples[t]).map((t) => `- ${examples[t]}`);
47
+ if (lines.length === 0) return "";
48
+ return [
49
+ "",
50
+ "## Available tools",
51
+ "When you need one of these workflows, emit the marker INLINE in your reply.",
52
+ "Write a short message first, THEN the marker. The marker will be replaced by an interactive card.",
53
+ "Pause the conversation after emitting \u2014 wait for the tool result before continuing.",
54
+ "",
55
+ ...lines
56
+ ].join("\n");
57
+ }
58
+
8
59
  // src/core/prompts.ts
9
- function buildSystemPrompt(knowledge) {
60
+ function buildSystemPrompt(knowledge, enabledTools = []) {
61
+ const toolsAddendum = buildToolsPromptAddendum(enabledTools);
10
62
  return [
11
63
  "You are an AI assistant on a business website. Use ONLY the knowledge below to answer.",
12
64
  "",
@@ -19,33 +71,23 @@ function buildSystemPrompt(knowledge) {
19
71
  "- For anything not covered in the knowledge above, say the owner will follow up \u2014 do NOT guess.",
20
72
  '- If the caller is clearly a vendor/sales pitch, say: "This does not look like a customer service request, so we will not continue this thread."',
21
73
  `- If wrong number or asked to stop, say: "Sorry about that. We won't text again."`,
22
- "- Match the caller's language automatically."
23
- ].join("\n");
74
+ "- Match the caller's language automatically.",
75
+ toolsAddendum
76
+ ].filter(Boolean).join("\n");
24
77
  }
25
78
 
26
79
  // src/core/guards.ts
27
80
  var FORBIDDEN_PHRASES = [
28
- "help is coming",
29
- "someone is on the way",
30
- "technician is on the way",
31
- "provider is on the way",
32
- "dispatching someone",
33
81
  "i've booked",
82
+ // fake booking
34
83
  "i have booked",
35
- "reservation confirmed",
36
84
  "your appointment is confirmed",
37
- "i've scheduled",
38
- "i have scheduled",
39
- "we've dispatched",
40
- "we have dispatched",
41
- "i can confirm",
42
- "i guarantee",
43
- "guaranteed delivery",
44
- "guaranteed arrival",
45
- "will arrive at",
46
- "arriving at",
47
- "i'll send",
48
- "i will send"
85
+ // fake confirmation
86
+ "reservation confirmed",
87
+ "someone is on the way",
88
+ // false dispatch
89
+ "i guarantee"
90
+ // legal liability
49
91
  ];
50
92
  function checkForbiddenPhrases(reply) {
51
93
  const lower = reply.toLowerCase();
@@ -70,6 +112,33 @@ function stripForbidden(reply) {
70
112
  return trimmed;
71
113
  }
72
114
 
115
+ // src/core/judges.ts
116
+ async function runJudge(config, apiKey, endpointUrl, content, fetcher) {
117
+ const res = await fetcher(`${endpointUrl}/chat/completions`, {
118
+ method: "POST",
119
+ headers: {
120
+ Authorization: `Bearer ${apiKey}`,
121
+ "Content-Type": "application/json"
122
+ },
123
+ body: JSON.stringify({
124
+ model: config.model,
125
+ messages: [
126
+ { role: "system", content: config.prompt },
127
+ { role: "user", content }
128
+ ],
129
+ temperature: 0,
130
+ max_tokens: 10
131
+ })
132
+ });
133
+ if (!res.ok) {
134
+ return { decision: "PASS", raw: `judge HTTP ${res.status} \u2014 fail-open` };
135
+ }
136
+ const data = await res.json();
137
+ const raw = (data.choices?.[0]?.message?.content ?? "").trim().toUpperCase();
138
+ const decision = raw.startsWith("BLOCK") ? "BLOCK" : "PASS";
139
+ return { decision, raw };
140
+ }
141
+
73
142
  // src/client/types.ts
74
143
  var PROVIDER_NAMES = /* @__PURE__ */ new Set([
75
144
  "openai",
@@ -90,22 +159,34 @@ function isKnownProvider(name) {
90
159
 
91
160
  // src/client/providers.ts
92
161
  var PROVIDER_ENDPOINTS = {
93
- openai: { baseUrl: "https://api.openai.com/v1", defaultModel: "gpt-4o-mini" },
162
+ openai: { baseUrl: "https://api.openai.com/v1", defaultModel: "gpt-4o-mini", visionModel: "gpt-4o" },
94
163
  deepseek: { baseUrl: "https://api.deepseek.com/v1", defaultModel: "deepseek-chat" },
95
- groq: { baseUrl: "https://api.groq.com/openai/v1", defaultModel: "llama-3.3-70b-versatile" },
96
- gemini: { baseUrl: "https://generativelanguage.googleapis.com/v1beta/openai", defaultModel: "gemini-2.5-flash" },
97
- anthropic: { baseUrl: "https://api.anthropic.com/v1", defaultModel: "claude-haiku-4-5" },
164
+ groq: { baseUrl: "https://api.groq.com/openai/v1", defaultModel: "llama-3.3-70b-versatile", visionModel: "llama-3.2-90b-vision-preview" },
165
+ gemini: { baseUrl: "https://generativelanguage.googleapis.com/v1beta/openai", defaultModel: "gemini-2.5-flash", visionModel: "gemini-2.5-flash" },
166
+ anthropic: { baseUrl: "https://api.anthropic.com/v1", defaultModel: "claude-haiku-4-5", visionModel: "claude-haiku-4-5" },
98
167
  cerebras: { baseUrl: "https://api.cerebras.ai/v1", defaultModel: "qwen-3-235b-a22b-instruct-2507" },
99
168
  sambanova: { baseUrl: "https://api.sambanova.ai/v1", defaultModel: "Meta-Llama-3.3-70B-Instruct" },
100
169
  fireworks: { baseUrl: "https://api.fireworks.ai/inference/v1", defaultModel: "accounts/fireworks/models/llama-v3p3-70b-instruct" },
101
170
  mistral: { baseUrl: "https://api.mistral.ai/v1", defaultModel: "mistral-small-latest" },
102
- openrouter: { baseUrl: "https://openrouter.ai/api/v1", defaultModel: "deepseek/deepseek-chat" },
103
- moonshot: { baseUrl: "https://api.moonshot.ai/v1", defaultModel: "moonshot-v1-32k" }
171
+ openrouter: { baseUrl: "https://openrouter.ai/api/v1", defaultModel: "deepseek/deepseek-chat", visionModel: "openai/gpt-4o" },
172
+ moonshot: { baseUrl: "https://api.moonshot.ai/v1", defaultModel: "moonshot-v1-32k", visionModel: "moonshot-v1-32k-vision-preview" }
104
173
  };
105
174
  function isRetryableError(err) {
106
175
  const msg = err instanceof Error ? err.message : String(err);
107
176
  return /\b(429|rate.?limit|quota|exceed|5\d\d|timeout|ECONNRESET|fetch failed)\b/i.test(msg);
108
177
  }
178
+ async function fileToDataUrl(file) {
179
+ const buf = new Uint8Array(await file.arrayBuffer());
180
+ const base64 = bufferToBase64(buf);
181
+ const mime = file.type || "application/octet-stream";
182
+ return `data:${mime};base64,${base64}`;
183
+ }
184
+ function bufferToBase64(buf) {
185
+ let bin = "";
186
+ for (let i = 0; i < buf.length; i++) bin += String.fromCharCode(buf[i]);
187
+ if (typeof btoa === "function") return btoa(bin);
188
+ return globalThis.Buffer.from(bin, "binary").toString("base64");
189
+ }
109
190
 
110
191
  // src/client/chatbot.ts
111
192
  var ChatBot = class {
@@ -114,18 +195,258 @@ var ChatBot = class {
114
195
  fetcher;
115
196
  timeoutMs;
116
197
  cachedSystemPrompt;
198
+ guards;
199
+ knowledge;
117
200
  constructor(init) {
118
201
  if (!init.knowledge || typeof init.knowledge !== "string" || init.knowledge.trim().length === 0) {
119
202
  throw new Error("chatbotlite: knowledge is required (a non-empty markdown string).");
120
203
  }
204
+ this.knowledge = init.knowledge;
121
205
  this.keys = init.providers.keys ?? {};
122
206
  this.steps = resolveChain(init.providers);
123
207
  this.fetcher = init.options?.fetch ?? globalThis.fetch.bind(globalThis);
124
208
  this.timeoutMs = init.options?.timeoutMs ?? 3e4;
125
209
  this.cachedSystemPrompt = buildSystemPrompt(init.knowledge);
210
+ this.guards = init.guards ?? {};
211
+ }
212
+ /** Build system prompt for given opts — uses cached if no enabledTools, else rebuilds. */
213
+ resolveSystemPrompt(opts) {
214
+ if (opts.systemPrompt) return opts.systemPrompt;
215
+ if (opts.enabledTools && opts.enabledTools.length > 0) {
216
+ return buildSystemPrompt(this.knowledge, opts.enabledTools);
217
+ }
218
+ return this.cachedSystemPrompt;
219
+ }
220
+ /** Run an LLM judge against content. Fail-open on errors. */
221
+ async judge(config, content) {
222
+ const endpoint = PROVIDER_ENDPOINTS[config.provider];
223
+ const key = this.keys[config.provider];
224
+ if (!key) {
225
+ return { decision: "PASS", raw: `judge provider ${config.provider} has no key \u2014 fail-open` };
226
+ }
227
+ const model = config.model ?? endpoint.defaultModel;
228
+ return runJudge(
229
+ { provider: config.provider, model, prompt: config.prompt },
230
+ key,
231
+ endpoint.baseUrl,
232
+ content,
233
+ this.fetcher
234
+ );
235
+ }
236
+ /**
237
+ * Stream a reply as SSE events. Returns a ReadableStream that yields tokens
238
+ * progressively. Designed to plug into Next.js/Hono/Express route handlers:
239
+ *
240
+ * ```ts
241
+ * export async function POST(req: Request) {
242
+ * const { message, transcript } = await req.json();
243
+ * const stream = await bot.replyStream(message, { history: transcript });
244
+ * return new Response(stream, {
245
+ * headers: { "Content-Type": "text/event-stream" }
246
+ * });
247
+ * }
248
+ * ```
249
+ *
250
+ * Events emitted (one per `data:` line, SSE format):
251
+ * event: token data: "<text fragment>"
252
+ * event: done data: {"reply":"...","usedProvider":"...","usedModel":"...","attempts":[...]}
253
+ * event: error data: {"message":"...","attempts":[...]}
254
+ */
255
+ async replyStream(message, opts = {}) {
256
+ const systemPrompt = this.resolveSystemPrompt(opts);
257
+ const messages = [
258
+ { role: "system", content: systemPrompt },
259
+ ...opts.history ?? [],
260
+ { role: "user", content: message }
261
+ ];
262
+ const steps = this.steps;
263
+ const fetcher = this.fetcher;
264
+ const keys = this.keys;
265
+ const timeoutMs = this.timeoutMs;
266
+ const encoder = new TextEncoder();
267
+ const sse = (event, data) => encoder.encode(`event: ${event}
268
+ data: ${data}
269
+
270
+ `);
271
+ return new ReadableStream({
272
+ async start(controller) {
273
+ const attempts = [];
274
+ let lastError;
275
+ let assembled = "";
276
+ for (const step of steps) {
277
+ const t0 = Date.now();
278
+ const endpoint = PROVIDER_ENDPOINTS[step.provider];
279
+ const key = keys[step.provider];
280
+ if (!key) {
281
+ attempts.push({ provider: step.provider, model: step.model, status: "error", error: "missing key", latencyMs: 0 });
282
+ continue;
283
+ }
284
+ const abortCtrl = new AbortController();
285
+ const timer = setTimeout(() => abortCtrl.abort(), timeoutMs);
286
+ try {
287
+ const res = await fetcher(`${endpoint.baseUrl}/chat/completions`, {
288
+ method: "POST",
289
+ headers: { Authorization: `Bearer ${key}`, "Content-Type": "application/json" },
290
+ body: JSON.stringify({ model: step.model, messages, temperature: 0.3, max_tokens: 300, stream: true }),
291
+ signal: abortCtrl.signal
292
+ });
293
+ if (!res.ok) {
294
+ const body = await res.text();
295
+ throw new Error(`${res.status}: ${body.slice(0, 200)}`);
296
+ }
297
+ const reader = res.body.getReader();
298
+ const decoder = new TextDecoder();
299
+ let sseBuffer = "";
300
+ while (true) {
301
+ const { done, value } = await reader.read();
302
+ if (done) break;
303
+ sseBuffer += decoder.decode(value, { stream: true });
304
+ const lines = sseBuffer.split("\n");
305
+ sseBuffer = lines.pop() ?? "";
306
+ for (const line of lines) {
307
+ const trimmed = line.trim();
308
+ if (!trimmed.startsWith("data:")) continue;
309
+ const payload = trimmed.slice(5).trim();
310
+ if (payload === "[DONE]") continue;
311
+ try {
312
+ const obj = JSON.parse(payload);
313
+ const delta = obj.choices?.[0]?.delta?.content ?? obj.choices?.[0]?.delta?.reasoning_content ?? "";
314
+ if (delta) {
315
+ assembled += delta;
316
+ controller.enqueue(sse("token", JSON.stringify(delta)));
317
+ }
318
+ } catch {
319
+ }
320
+ }
321
+ }
322
+ attempts.push({ provider: step.provider, model: step.model, status: "ok", latencyMs: Date.now() - t0 });
323
+ const guard = checkForbiddenPhrases(assembled);
324
+ const finalReply = guard.ok ? assembled : stripForbidden(assembled);
325
+ controller.enqueue(sse("done", JSON.stringify({
326
+ reply: finalReply,
327
+ usedProvider: step.provider,
328
+ usedModel: step.model,
329
+ guardWarnings: guard.violations,
330
+ attempts
331
+ })));
332
+ controller.close();
333
+ return;
334
+ } catch (err) {
335
+ lastError = err;
336
+ const errMsg = err instanceof Error ? err.message : String(err);
337
+ attempts.push({ provider: step.provider, model: step.model, status: "error", error: errMsg, latencyMs: Date.now() - t0 });
338
+ assembled = "";
339
+ if (!isRetryableError(err)) {
340
+ controller.enqueue(sse("error", JSON.stringify({ message: `${step.label} failed (non-retryable): ${errMsg}`, attempts })));
341
+ controller.close();
342
+ return;
343
+ }
344
+ } finally {
345
+ clearTimeout(timer);
346
+ }
347
+ }
348
+ const summary = attempts.map((a) => `${a.provider}/${a.model}:${a.error ?? "ok"}`).join(" \u2192 ");
349
+ controller.enqueue(sse("error", JSON.stringify({
350
+ message: `all chain steps failed. Trace: ${summary}. Last error: ${lastError instanceof Error ? lastError.message : String(lastError)}`,
351
+ attempts
352
+ })));
353
+ controller.close();
354
+ }
355
+ });
356
+ }
357
+ /**
358
+ * Reply to a message with optional image attachments. Routes through vision-capable
359
+ * providers only — chain steps without `visionModel` are skipped (logged in attempts).
360
+ *
361
+ * Images are inlined as data: URLs. Keep total payload modest (<10MB).
362
+ */
363
+ async replyWithMedia(message, opts = {}) {
364
+ const images = opts.images ?? [];
365
+ if (images.length === 0) {
366
+ return this.reply(message, opts);
367
+ }
368
+ const dataUrls = await Promise.all(images.map(fileToDataUrl));
369
+ const systemPrompt = this.resolveSystemPrompt(opts);
370
+ const userContent = [];
371
+ if (message) userContent.push({ type: "text", text: message });
372
+ for (const url of dataUrls) userContent.push({ type: "image_url", image_url: { url } });
373
+ const messages = [
374
+ { role: "system", content: systemPrompt },
375
+ ...opts.history ?? [],
376
+ { role: "user", content: userContent }
377
+ ];
378
+ const attempts = [];
379
+ let lastError;
380
+ for (const step of this.steps) {
381
+ const endpoint = PROVIDER_ENDPOINTS[step.provider];
382
+ if (!endpoint.visionModel) {
383
+ attempts.push({ provider: step.provider, model: step.model, status: "error", error: "no vision support", latencyMs: 0 });
384
+ continue;
385
+ }
386
+ const t0 = Date.now();
387
+ const visionStep = { provider: step.provider, model: endpoint.visionModel, label: `${step.provider}/${endpoint.visionModel}` };
388
+ try {
389
+ const key = this.keys[step.provider];
390
+ if (!key) throw new Error(`Missing API key for provider: ${step.provider}`);
391
+ const controller = new AbortController();
392
+ const timer = setTimeout(() => controller.abort(), this.timeoutMs);
393
+ try {
394
+ const res = await this.fetcher(`${endpoint.baseUrl}/chat/completions`, {
395
+ method: "POST",
396
+ headers: { Authorization: `Bearer ${key}`, "Content-Type": "application/json" },
397
+ body: JSON.stringify({ model: visionStep.model, messages, temperature: 0.3, max_tokens: 400 }),
398
+ signal: controller.signal
399
+ });
400
+ if (!res.ok) {
401
+ const body = await res.text();
402
+ throw new Error(`${res.status}: ${body.slice(0, 200)}`);
403
+ }
404
+ const data = await res.json();
405
+ const reply = (data.choices?.[0]?.message?.content ?? "").trim();
406
+ if (!reply) throw new Error("empty vision reply");
407
+ attempts.push({ provider: visionStep.provider, model: visionStep.model, status: "ok", latencyMs: Date.now() - t0 });
408
+ const guard = checkForbiddenPhrases(reply);
409
+ const finalReply = guard.ok ? reply : stripForbidden(reply);
410
+ return {
411
+ reply: finalReply,
412
+ usedProvider: visionStep.provider,
413
+ usedModel: visionStep.model,
414
+ ...data.usage ? { usage: data.usage } : {},
415
+ guardWarnings: guard.violations,
416
+ attempts
417
+ };
418
+ } finally {
419
+ clearTimeout(timer);
420
+ }
421
+ } catch (err) {
422
+ lastError = err;
423
+ const errMsg = err instanceof Error ? err.message : String(err);
424
+ attempts.push({ provider: visionStep.provider, model: visionStep.model, status: "error", error: errMsg, latencyMs: Date.now() - t0 });
425
+ if (!isRetryableError(err)) {
426
+ throw new Error(`chatbotlite: ${visionStep.label} vision failed (non-retryable). ${errMsg}`);
427
+ }
428
+ }
429
+ }
430
+ const summary = attempts.map((a) => `${a.provider}/${a.model}:${a.error ?? "ok"}`).join(" \u2192 ");
431
+ throw new Error(`chatbotlite: no vision-capable provider succeeded. Trace: ${summary}. Last error: ${lastError instanceof Error ? lastError.message : String(lastError)}`);
126
432
  }
127
433
  async reply(message, opts = {}) {
128
- const systemPrompt = opts.systemPrompt ?? this.cachedSystemPrompt;
434
+ let inputVerdict;
435
+ if (this.guards.inputJudge) {
436
+ inputVerdict = await this.judge(this.guards.inputJudge, message);
437
+ if (inputVerdict.decision === "BLOCK") {
438
+ return {
439
+ reply: "I can't process that request. Please ask in a different way.",
440
+ usedProvider: this.steps[0].provider,
441
+ usedModel: this.steps[0].model,
442
+ guardWarnings: [],
443
+ judges: { input: inputVerdict },
444
+ attempts: [],
445
+ blockedByInputJudge: true
446
+ };
447
+ }
448
+ }
449
+ const systemPrompt = this.resolveSystemPrompt(opts);
129
450
  const messages = [
130
451
  { role: "system", content: systemPrompt },
131
452
  ...opts.history ?? [],
@@ -139,13 +460,21 @@ var ChatBot = class {
139
460
  const result = await this.callProvider(step, messages);
140
461
  attempts.push({ provider: step.provider, model: step.model, status: "ok", latencyMs: Date.now() - t0 });
141
462
  const guard = checkForbiddenPhrases(result.reply);
142
- const finalReply = guard.ok ? result.reply : stripForbidden(result.reply);
463
+ let finalReply = guard.ok ? result.reply : stripForbidden(result.reply);
464
+ let outputVerdict;
465
+ if (this.guards.outputJudge) {
466
+ outputVerdict = await this.judge(this.guards.outputJudge, finalReply);
467
+ if (outputVerdict.decision === "BLOCK") {
468
+ finalReply = "Let me check with the owner and get back to you on that.";
469
+ }
470
+ }
143
471
  return {
144
472
  reply: finalReply,
145
473
  usedProvider: step.provider,
146
474
  usedModel: step.model,
147
475
  ...result.usage ? { usage: result.usage } : {},
148
476
  guardWarnings: guard.violations,
477
+ ...inputVerdict || outputVerdict ? { judges: { ...inputVerdict ? { input: inputVerdict } : {}, ...outputVerdict ? { output: outputVerdict } : {} } } : {},
149
478
  attempts
150
479
  };
151
480
  } catch (err) {
@@ -230,6 +559,458 @@ function normalizeChainEntry(entry, keys) {
230
559
  }
231
560
  return { provider, model, label: `${provider}/${model}` };
232
561
  }
562
+ var CLOUD_ICON = "M7 16a4 4 0 01-.88-7.903A5 5 0 1115.9 6L16 6a5 5 0 011 9.9M15 13l-3-3m0 0l-3 3m3-3v12";
563
+ function UploadForReview(props) {
564
+ const {
565
+ purpose = "Files",
566
+ accept = "*",
567
+ maxMb = 10,
568
+ primary,
569
+ onPrimary,
570
+ border,
571
+ surface,
572
+ surfaceMuted,
573
+ textBody,
574
+ textMuted,
575
+ onSubmit,
576
+ onCancel,
577
+ submitting = false,
578
+ submitted = false
579
+ } = props;
580
+ const inputRef = react.useRef(null);
581
+ const [files, setFiles] = react.useState([]);
582
+ const [drag, setDrag] = react.useState(false);
583
+ function add(picked) {
584
+ const arr = Array.from(picked).filter((f) => f.size <= maxMb * 1024 * 1024);
585
+ setFiles((p) => [...p, ...arr]);
586
+ }
587
+ function remove(i) {
588
+ setFiles((p) => p.filter((_, j) => j !== i));
589
+ }
590
+ if (submitted) {
591
+ return /* @__PURE__ */ jsxRuntime.jsxs("div", { style: {
592
+ padding: "12px 16px",
593
+ borderRadius: 14,
594
+ background: surface,
595
+ border: `1px solid ${border}`,
596
+ boxShadow: "0 1px 2px rgba(15,23,42,0.04)",
597
+ color: textBody,
598
+ fontSize: 13
599
+ }, children: [
600
+ "\u2713 ",
601
+ files.length || 1,
602
+ " file",
603
+ files.length === 1 ? "" : "s",
604
+ " submitted for review."
605
+ ] });
606
+ }
607
+ return /* @__PURE__ */ jsxRuntime.jsxs("div", { style: {
608
+ padding: 16,
609
+ borderRadius: 14,
610
+ background: surface,
611
+ border: `1px solid ${border}`,
612
+ boxShadow: "0 2px 8px -2px rgba(15,23,42,0.08)"
613
+ }, children: [
614
+ /* @__PURE__ */ jsxRuntime.jsxs("p", { style: { margin: 0, marginBottom: 12, fontSize: 13, fontWeight: 600, color: textBody }, children: [
615
+ "Upload your ",
616
+ purpose
617
+ ] }),
618
+ /* @__PURE__ */ jsxRuntime.jsxs(
619
+ "div",
620
+ {
621
+ onClick: () => inputRef.current?.click(),
622
+ onDragOver: (e) => {
623
+ e.preventDefault();
624
+ setDrag(true);
625
+ },
626
+ onDragLeave: () => setDrag(false),
627
+ onDrop: (e) => {
628
+ e.preventDefault();
629
+ setDrag(false);
630
+ if (e.dataTransfer.files) add(e.dataTransfer.files);
631
+ },
632
+ style: {
633
+ border: `1.5px dashed ${drag ? primary : border}`,
634
+ borderRadius: 12,
635
+ padding: "20px 12px",
636
+ textAlign: "center",
637
+ cursor: "pointer",
638
+ background: drag ? `${primary}0a` : surfaceMuted,
639
+ transition: "border-color 120ms ease, background 120ms ease"
640
+ },
641
+ children: [
642
+ /* @__PURE__ */ jsxRuntime.jsx("svg", { width: "28", height: "28", viewBox: "0 0 24 24", fill: "none", stroke: primary, strokeWidth: "1.5", style: { display: "block", margin: "0 auto 6px" }, children: /* @__PURE__ */ jsxRuntime.jsx("path", { d: CLOUD_ICON, strokeLinecap: "round", strokeLinejoin: "round" }) }),
643
+ /* @__PURE__ */ jsxRuntime.jsxs("p", { style: { margin: 0, fontSize: 13, fontWeight: 500, color: textBody }, children: [
644
+ "Drop file",
645
+ maxMb > 0 ? "s" : "",
646
+ " here or click to browse"
647
+ ] }),
648
+ /* @__PURE__ */ jsxRuntime.jsxs("p", { style: { margin: "4px 0 0", fontSize: 11, color: textMuted }, children: [
649
+ accept === "*" ? "Any file" : accept,
650
+ " \xB7 max ",
651
+ maxMb,
652
+ "MB"
653
+ ] }),
654
+ /* @__PURE__ */ jsxRuntime.jsx(
655
+ "input",
656
+ {
657
+ ref: inputRef,
658
+ type: "file",
659
+ multiple: true,
660
+ accept,
661
+ style: { display: "none" },
662
+ onChange: (e) => {
663
+ if (e.target.files) add(e.target.files);
664
+ e.target.value = "";
665
+ }
666
+ }
667
+ )
668
+ ]
669
+ }
670
+ ),
671
+ files.length > 0 && /* @__PURE__ */ jsxRuntime.jsx("div", { style: { display: "flex", flexWrap: "wrap", gap: 6, marginTop: 10 }, children: files.map((f, i) => /* @__PURE__ */ jsxRuntime.jsxs(
672
+ "span",
673
+ {
674
+ style: {
675
+ display: "inline-flex",
676
+ alignItems: "center",
677
+ gap: 6,
678
+ padding: "4px 8px 4px 10px",
679
+ borderRadius: 8,
680
+ background: surfaceMuted,
681
+ border: `1px solid ${border}`,
682
+ fontSize: 12,
683
+ color: textBody,
684
+ maxWidth: 220
685
+ },
686
+ children: [
687
+ /* @__PURE__ */ jsxRuntime.jsxs("span", { style: { overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }, children: [
688
+ "\u{1F4C4} ",
689
+ f.name
690
+ ] }),
691
+ /* @__PURE__ */ jsxRuntime.jsx(
692
+ "button",
693
+ {
694
+ onClick: () => remove(i),
695
+ "aria-label": `Remove ${f.name}`,
696
+ style: { background: "transparent", border: "none", cursor: "pointer", color: textMuted, fontSize: 14, lineHeight: 1, padding: 0 },
697
+ children: "\xD7"
698
+ }
699
+ )
700
+ ]
701
+ },
702
+ `${f.name}-${i}`
703
+ )) }),
704
+ /* @__PURE__ */ jsxRuntime.jsxs("div", { style: { display: "flex", gap: 8, marginTop: 12 }, children: [
705
+ onCancel && /* @__PURE__ */ jsxRuntime.jsx(
706
+ "button",
707
+ {
708
+ onClick: onCancel,
709
+ disabled: submitting,
710
+ style: {
711
+ padding: "8px 14px",
712
+ borderRadius: 10,
713
+ background: "transparent",
714
+ color: textMuted,
715
+ border: `1px solid ${border}`,
716
+ fontSize: 13,
717
+ cursor: submitting ? "default" : "pointer"
718
+ },
719
+ children: "Cancel"
720
+ }
721
+ ),
722
+ /* @__PURE__ */ jsxRuntime.jsx(
723
+ "button",
724
+ {
725
+ onClick: () => void onSubmit(files),
726
+ disabled: submitting || files.length === 0,
727
+ style: {
728
+ flex: 1,
729
+ padding: "9px 16px",
730
+ borderRadius: 10,
731
+ background: primary,
732
+ color: onPrimary,
733
+ border: "none",
734
+ fontSize: 13,
735
+ fontWeight: 600,
736
+ cursor: submitting || files.length === 0 ? "default" : "pointer",
737
+ opacity: submitting || files.length === 0 ? 0.4 : 1
738
+ },
739
+ children: submitting ? "Submitting\u2026" : "Submit"
740
+ }
741
+ )
742
+ ] })
743
+ ] });
744
+ }
745
+ function ScheduleCallback(props) {
746
+ const {
747
+ durationMin = 15,
748
+ timezone = "UTC",
749
+ primary,
750
+ onPrimary,
751
+ border,
752
+ surface,
753
+ surfaceMuted,
754
+ textBody,
755
+ textMuted,
756
+ getAvailableSlots,
757
+ onConfirm,
758
+ submitting = false,
759
+ submitted = false,
760
+ submittedSlot
761
+ } = props;
762
+ const [slots, setSlots] = react.useState([]);
763
+ const [loading, setLoading] = react.useState(true);
764
+ const [selected, setSelected] = react.useState(null);
765
+ react.useEffect(() => {
766
+ let cancelled = false;
767
+ setLoading(true);
768
+ getAvailableSlots({ durationMin, timezone }).then((s) => {
769
+ if (cancelled) return;
770
+ setSlots(s);
771
+ setLoading(false);
772
+ }).catch(() => {
773
+ if (!cancelled) setLoading(false);
774
+ });
775
+ return () => {
776
+ cancelled = true;
777
+ };
778
+ }, [durationMin, timezone, getAvailableSlots]);
779
+ if (submitted && submittedSlot) {
780
+ return /* @__PURE__ */ jsxRuntime.jsxs("div", { style: {
781
+ padding: "12px 16px",
782
+ borderRadius: 14,
783
+ background: surface,
784
+ border: `1px solid ${border}`,
785
+ fontSize: 13,
786
+ color: textBody
787
+ }, children: [
788
+ "\u2713 Booked for ",
789
+ formatSlot(submittedSlot)
790
+ ] });
791
+ }
792
+ return /* @__PURE__ */ jsxRuntime.jsxs("div", { style: {
793
+ padding: 16,
794
+ borderRadius: 14,
795
+ background: surface,
796
+ border: `1px solid ${border}`,
797
+ boxShadow: "0 2px 8px -2px rgba(15,23,42,0.08)"
798
+ }, children: [
799
+ /* @__PURE__ */ jsxRuntime.jsxs("p", { style: { margin: 0, marginBottom: 12, fontSize: 13, fontWeight: 600, color: textBody }, children: [
800
+ "Pick a ",
801
+ durationMin,
802
+ "-minute slot"
803
+ ] }),
804
+ loading ? /* @__PURE__ */ jsxRuntime.jsx("p", { style: { fontSize: 12, color: textMuted }, children: "Loading availability\u2026" }) : slots.length === 0 ? /* @__PURE__ */ jsxRuntime.jsx("p", { style: { fontSize: 12, color: textMuted }, children: "No slots available \u2014 the owner will follow up." }) : /* @__PURE__ */ jsxRuntime.jsx("div", { style: { display: "grid", gridTemplateColumns: "1fr 1fr", gap: 6 }, children: slots.map((slot) => {
805
+ const isSel = selected === slot;
806
+ return /* @__PURE__ */ jsxRuntime.jsx(
807
+ "button",
808
+ {
809
+ onClick: () => setSelected(slot),
810
+ style: {
811
+ padding: "8px 10px",
812
+ borderRadius: 10,
813
+ fontSize: 12,
814
+ fontWeight: isSel ? 600 : 500,
815
+ cursor: "pointer",
816
+ background: isSel ? `${primary}0d` : surfaceMuted,
817
+ color: textBody,
818
+ border: `1px solid ${isSel ? primary : border}`,
819
+ transition: "border-color 120ms ease, background 120ms ease"
820
+ },
821
+ children: formatSlot(slot)
822
+ },
823
+ slot
824
+ );
825
+ }) }),
826
+ /* @__PURE__ */ jsxRuntime.jsx(
827
+ "button",
828
+ {
829
+ onClick: () => {
830
+ if (selected) void onConfirm(selected);
831
+ },
832
+ disabled: !selected || submitting,
833
+ style: {
834
+ width: "100%",
835
+ marginTop: 12,
836
+ padding: "9px 16px",
837
+ borderRadius: 10,
838
+ background: primary,
839
+ color: onPrimary,
840
+ border: "none",
841
+ fontSize: 13,
842
+ fontWeight: 600,
843
+ cursor: selected && !submitting ? "pointer" : "default",
844
+ opacity: selected && !submitting ? 1 : 0.4
845
+ },
846
+ children: submitting ? "Booking\u2026" : "Confirm"
847
+ }
848
+ )
849
+ ] });
850
+ }
851
+ function formatSlot(iso) {
852
+ try {
853
+ const d = new Date(iso);
854
+ return d.toLocaleString(void 0, {
855
+ weekday: "short",
856
+ month: "short",
857
+ day: "numeric",
858
+ hour: "numeric",
859
+ minute: "2-digit"
860
+ });
861
+ } catch {
862
+ return iso;
863
+ }
864
+ }
865
+ function formatAmount(amountMinor, currency = "USD") {
866
+ try {
867
+ return new Intl.NumberFormat(void 0, {
868
+ style: "currency",
869
+ currency: currency.toUpperCase(),
870
+ minimumFractionDigits: 2
871
+ }).format(amountMinor / 100);
872
+ } catch {
873
+ return `${currency.toUpperCase()} ${(amountMinor / 100).toFixed(2)}`;
874
+ }
875
+ }
876
+ function RequestPayment(props) {
877
+ const {
878
+ amount,
879
+ currency = "USD",
880
+ reason,
881
+ primary,
882
+ border,
883
+ surface,
884
+ textBody,
885
+ textMuted,
886
+ showInterac = true,
887
+ stripeLink,
888
+ onPick,
889
+ submitting = false,
890
+ submitted = false,
891
+ submittedMethod
892
+ } = props;
893
+ const formatted = formatAmount(amount, currency);
894
+ if (submitted) {
895
+ return /* @__PURE__ */ jsxRuntime.jsxs("div", { style: {
896
+ padding: "12px 16px",
897
+ borderRadius: 14,
898
+ background: surface,
899
+ border: `1px solid ${border}`,
900
+ fontSize: 13,
901
+ color: textBody
902
+ }, children: [
903
+ "\u2713 ",
904
+ submittedMethod === "interac" ? "Interac request sent \u2014 instructions to follow" : "Payment opened",
905
+ " \xB7 ",
906
+ formatted
907
+ ] });
908
+ }
909
+ return /* @__PURE__ */ jsxRuntime.jsxs("div", { style: {
910
+ padding: 16,
911
+ borderRadius: 14,
912
+ background: surface,
913
+ border: `1px solid ${border}`,
914
+ boxShadow: "0 2px 8px -2px rgba(15,23,42,0.08)"
915
+ }, children: [
916
+ /* @__PURE__ */ jsxRuntime.jsxs("div", { style: { marginBottom: 12 }, children: [
917
+ /* @__PURE__ */ jsxRuntime.jsx("p", { style: { margin: 0, fontSize: 13, fontWeight: 600, color: textBody }, children: reason || "Payment required" }),
918
+ /* @__PURE__ */ jsxRuntime.jsx("p", { style: { margin: "2px 0 0", fontSize: 20, fontWeight: 700, color: textBody, letterSpacing: "-0.01em" }, children: formatted })
919
+ ] }),
920
+ /* @__PURE__ */ jsxRuntime.jsxs("div", { style: { display: "flex", flexDirection: "column", gap: 8 }, children: [
921
+ showInterac && /* @__PURE__ */ jsxRuntime.jsxs(
922
+ "button",
923
+ {
924
+ onClick: () => void onPick("interac"),
925
+ disabled: submitting,
926
+ style: {
927
+ display: "flex",
928
+ alignItems: "center",
929
+ gap: 12,
930
+ padding: 12,
931
+ borderRadius: 12,
932
+ background: surface,
933
+ border: `1px solid ${border}`,
934
+ cursor: submitting ? "default" : "pointer",
935
+ opacity: submitting ? 0.5 : 1,
936
+ textAlign: "left",
937
+ transition: "border-color 120ms ease"
938
+ },
939
+ onMouseEnter: (e) => {
940
+ e.currentTarget.style.borderColor = primary;
941
+ },
942
+ onMouseLeave: (e) => {
943
+ e.currentTarget.style.borderColor = border;
944
+ },
945
+ children: [
946
+ /* @__PURE__ */ jsxRuntime.jsx("div", { style: {
947
+ width: 40,
948
+ height: 40,
949
+ borderRadius: 10,
950
+ background: "#FFBE2E1f",
951
+ display: "flex",
952
+ alignItems: "center",
953
+ justifyContent: "center",
954
+ fontSize: 18,
955
+ fontWeight: 700,
956
+ color: "#B8860B",
957
+ flexShrink: 0
958
+ }, children: "$" }),
959
+ /* @__PURE__ */ jsxRuntime.jsxs("div", { style: { flex: 1, minWidth: 0 }, children: [
960
+ /* @__PURE__ */ jsxRuntime.jsx("p", { style: { margin: 0, fontSize: 13, fontWeight: 600, color: textBody }, children: "Interac e-Transfer" }),
961
+ /* @__PURE__ */ jsxRuntime.jsx("p", { style: { margin: "2px 0 0", fontSize: 11, color: textMuted }, children: "Instant, no fees" })
962
+ ] })
963
+ ]
964
+ }
965
+ ),
966
+ /* @__PURE__ */ jsxRuntime.jsxs(
967
+ "button",
968
+ {
969
+ onClick: () => {
970
+ if (stripeLink) window.open(stripeLink, "_blank", "noopener");
971
+ void onPick("stripe");
972
+ },
973
+ disabled: submitting,
974
+ style: {
975
+ display: "flex",
976
+ alignItems: "center",
977
+ gap: 12,
978
+ padding: 12,
979
+ borderRadius: 12,
980
+ background: surface,
981
+ border: `1px solid ${border}`,
982
+ cursor: submitting ? "default" : "pointer",
983
+ opacity: submitting ? 0.5 : 1,
984
+ textAlign: "left",
985
+ transition: "border-color 120ms ease"
986
+ },
987
+ onMouseEnter: (e) => {
988
+ e.currentTarget.style.borderColor = primary;
989
+ },
990
+ onMouseLeave: (e) => {
991
+ e.currentTarget.style.borderColor = border;
992
+ },
993
+ children: [
994
+ /* @__PURE__ */ jsxRuntime.jsx("div", { style: {
995
+ width: 40,
996
+ height: 40,
997
+ borderRadius: 10,
998
+ background: "#635BFF1a",
999
+ display: "flex",
1000
+ alignItems: "center",
1001
+ justifyContent: "center",
1002
+ flexShrink: 0
1003
+ }, children: /* @__PURE__ */ jsxRuntime.jsx("span", { style: { color: "#635BFF", fontSize: 14, fontWeight: 700 }, children: "\u{1F4B3}" }) }),
1004
+ /* @__PURE__ */ jsxRuntime.jsxs("div", { style: { flex: 1, minWidth: 0 }, children: [
1005
+ /* @__PURE__ */ jsxRuntime.jsx("p", { style: { margin: 0, fontSize: 13, fontWeight: 600, color: textBody }, children: "Pay by card" }),
1006
+ /* @__PURE__ */ jsxRuntime.jsx("p", { style: { margin: "2px 0 0", fontSize: 11, color: textMuted }, children: "Visa \xB7 Mastercard \xB7 Amex" })
1007
+ ] })
1008
+ ]
1009
+ }
1010
+ )
1011
+ ] })
1012
+ ] });
1013
+ }
233
1014
  var BOLT = "\u26A1";
234
1015
  var DEFAULT_PRIMARY = "#0f172a";
235
1016
  var DEFAULT_ON_PRIMARY = "#ffffff";
@@ -246,7 +1027,9 @@ var KEYFRAMES = `
246
1027
  @keyframes chatbotlite-slide { 0% { opacity: 0; transform: translateY(16px) scale(0.98); } 100% { opacity: 1; transform: translateY(0) scale(1); } }
247
1028
  @keyframes chatbotlite-fade-in { from { opacity: 0; transform: translateY(4px); } to { opacity: 1; transform: translateY(0); } }
248
1029
  @keyframes chatbotlite-dot { 0%, 60%, 100% { transform: translateY(0); opacity: 0.4; } 30% { transform: translateY(-4px); opacity: 1; } }
249
- .chatbotlite-launcher { transition: transform 180ms cubic-bezier(0.4, 0, 0.2, 1), box-shadow 180ms cubic-bezier(0.4, 0, 0.2, 1); }
1030
+ @keyframes chatbotlite-cursor { 0%, 50% { opacity: 1; } 51%, 100% { opacity: 0; } }
1031
+ @keyframes chatbotlite-pulse { 0%, 100% { box-shadow: 0 12px 28px -8px rgba(15,23,42,0.32), 0 4px 8px -2px rgba(15,23,42,0.12); } 50% { box-shadow: 0 14px 32px -8px rgba(15,23,42,0.36), 0 6px 12px -2px rgba(15,23,42,0.16); } }
1032
+ .chatbotlite-launcher { transition: transform 180ms cubic-bezier(0.4, 0, 0.2, 1), box-shadow 180ms cubic-bezier(0.4, 0, 0.2, 1); animation: chatbotlite-pop 320ms cubic-bezier(0.34, 1.56, 0.64, 1), chatbotlite-pulse 3.6s ease-in-out 1.2s 2; }
250
1033
  .chatbotlite-launcher:hover { transform: translateY(-2px) scale(1.04); }
251
1034
  .chatbotlite-launcher:active { transform: translateY(0) scale(0.98); }
252
1035
  .chatbotlite-close { transition: background 120ms ease; }
@@ -257,6 +1040,9 @@ var KEYFRAMES = `
257
1040
  .chatbotlite-input:focus { box-shadow: 0 0 0 3px rgba(15,23,42,0.06); }
258
1041
  .chatbotlite-msg { animation: chatbotlite-fade-in 220ms cubic-bezier(0.4, 0, 0.2, 1); }
259
1042
  .chatbotlite-dot { display: inline-block; width: 6px; height: 6px; border-radius: 50%; background: ${TEXT_FAINT}; margin-right: 4px; animation: chatbotlite-dot 1.2s ease-in-out infinite; }
1043
+ .chatbotlite-cursor { display: inline-block; width: 2px; height: 1em; background: currentColor; vertical-align: text-bottom; margin-left: 1px; animation: chatbotlite-cursor 1s steps(1) infinite; }
1044
+ .chatbotlite-attach-btn:hover:not(:disabled), .chatbotlite-voice-btn:hover:not(:disabled) { background: ${BORDER}; }
1045
+ .chatbotlite-attach-btn:active:not(:disabled), .chatbotlite-voice-btn:active:not(:disabled) { transform: scale(0.96); }
260
1046
  .chatbotlite-dot:nth-child(2) { animation-delay: 0.15s; }
261
1047
  .chatbotlite-dot:nth-child(3) { animation-delay: 0.3s; margin-right: 0; }
262
1048
  .chatbotlite-brand:hover { color: ${TEXT_MUTED} !important; }
@@ -283,14 +1069,105 @@ function ChatWidget(props) {
283
1069
  const resolvedGreeting = greeting ?? "Hi! How can we help?";
284
1070
  const primary = themeOverrides?.primary ?? DEFAULT_PRIMARY;
285
1071
  const onPrimary = themeOverrides?.onPrimary ?? DEFAULT_ON_PRIMARY;
1072
+ const attachCfg = props.attach;
1073
+ const attachEnabled = attachCfg?.enabled === true;
1074
+ const acceptAttr = attachCfg?.accept?.join(",");
1075
+ const maxSizeMb = attachCfg?.maxSizeMb ?? 10;
1076
+ const maxFiles = attachCfg?.maxFiles ?? 5;
1077
+ const voiceCfg = props.voice;
1078
+ const voiceEnabled = voiceCfg?.enabled === true;
1079
+ const voiceLang = voiceCfg?.lang ?? "en-US";
1080
+ const speechSupported = typeof window !== "undefined" && (Boolean(window.SpeechRecognition) || Boolean(window.webkitSpeechRecognition));
286
1081
  const [open, setOpen] = react.useState(false);
287
1082
  const [messages, setMessages] = react.useState([
288
1083
  { id: "g0", role: "assistant", content: resolvedGreeting, ts: Date.now() }
289
1084
  ]);
290
1085
  const [input, setInput] = react.useState("");
291
1086
  const [sending, setSending] = react.useState(false);
1087
+ const [files, setFiles] = react.useState([]);
292
1088
  const scrollRef = react.useRef(null);
293
1089
  const inputRef = react.useRef(null);
1090
+ const fileInputRef = react.useRef(null);
1091
+ const [pendingTools, setPendingTools] = react.useState([]);
1092
+ const tools = props.tools ?? {};
1093
+ const [voiceListening, setVoiceListening] = react.useState(false);
1094
+ const recognitionRef = react.useRef(null);
1095
+ async function continueAfterTool(toolName, result) {
1096
+ const ctxMsg = `[Tool ${toolName} result: ${JSON.stringify(result)}]`;
1097
+ setSending(true);
1098
+ const assistantId = `a${Date.now()}`;
1099
+ setMessages((prev) => [...prev, { id: assistantId, role: "assistant", content: "", ts: Date.now() }]);
1100
+ const appendToken = (tok) => {
1101
+ setMessages(
1102
+ (prev) => prev.map((m) => m.id === assistantId ? { ...m, content: m.content + tok } : m)
1103
+ );
1104
+ };
1105
+ try {
1106
+ const history = messages.filter((m) => m.role !== "system").map((m) => ({ role: m.role, content: m.content }));
1107
+ const reply = isEndpointMode ? await fetchReplyFromEndpoint(ctxMsg, history, [], appendToken) : (await bot.reply(ctxMsg, { history })).reply;
1108
+ const markers = parseToolMarkers(reply);
1109
+ const cleanReply = stripToolMarkers(reply);
1110
+ setMessages(
1111
+ (prev) => prev.map((m) => m.id === assistantId ? { ...m, content: cleanReply } : m)
1112
+ );
1113
+ if (markers.length > 0) {
1114
+ setPendingTools((prev) => [
1115
+ ...prev,
1116
+ ...markers.map((marker) => ({ messageId: assistantId, marker, status: "pending" }))
1117
+ ]);
1118
+ }
1119
+ } catch (err) {
1120
+ const errMsg = err instanceof Error ? err.message : String(err);
1121
+ setMessages(
1122
+ (prev) => prev.map(
1123
+ (m) => m.id === assistantId ? { ...m, content: `Sorry \u2014 something went wrong. (${errMsg})` } : m
1124
+ )
1125
+ );
1126
+ } finally {
1127
+ setSending(false);
1128
+ }
1129
+ }
1130
+ async function handleToolSubmit(toolName, idx, result) {
1131
+ setPendingTools(
1132
+ (prev) => prev.map((p, i) => i === idx ? { ...p, status: "submitted", result } : p)
1133
+ );
1134
+ await continueAfterTool(toolName, result);
1135
+ }
1136
+ function toggleVoice() {
1137
+ if (!speechSupported) return;
1138
+ if (voiceListening) {
1139
+ recognitionRef.current?.stop();
1140
+ return;
1141
+ }
1142
+ const Ctor = window.SpeechRecognition ?? window.webkitSpeechRecognition;
1143
+ if (!Ctor) return;
1144
+ const rec = new Ctor();
1145
+ rec.lang = voiceLang;
1146
+ rec.continuous = false;
1147
+ rec.interimResults = true;
1148
+ rec.onresult = (e) => {
1149
+ let transcript = "";
1150
+ for (let i = e.resultIndex; i < e.results.length; i++) {
1151
+ transcript += e.results[i][0].transcript;
1152
+ }
1153
+ setInput(transcript);
1154
+ };
1155
+ rec.onend = () => setVoiceListening(false);
1156
+ rec.onerror = () => setVoiceListening(false);
1157
+ recognitionRef.current = rec;
1158
+ setVoiceListening(true);
1159
+ rec.start();
1160
+ }
1161
+ function addFiles(picked) {
1162
+ const arr = Array.from(picked).filter((f) => f.size <= maxSizeMb * 1024 * 1024);
1163
+ setFiles((prev) => {
1164
+ const combined = [...prev, ...arr];
1165
+ return combined.slice(0, maxFiles);
1166
+ });
1167
+ }
1168
+ function removeFile(idx) {
1169
+ setFiles((prev) => prev.filter((_, i) => i !== idx));
1170
+ }
294
1171
  react.useEffect(() => {
295
1172
  ensureStyles();
296
1173
  }, []);
@@ -311,13 +1188,71 @@ function ChatWidget(props) {
311
1188
  }
312
1189
  return void 0;
313
1190
  }, [open]);
314
- async function fetchReplyFromEndpoint(text, history) {
315
- const res = await fetch(props.endpoint, {
316
- method: "POST",
317
- headers: { "Content-Type": "application/json" },
318
- body: JSON.stringify({ message: text, transcript: history })
319
- });
1191
+ async function fetchReplyFromEndpoint(text, history, attachedFiles, onToken) {
1192
+ const enabledTools = Object.keys(tools);
1193
+ let body;
1194
+ const headers = { Accept: "text/event-stream, application/json" };
1195
+ if (attachedFiles.length > 0) {
1196
+ const form = new FormData();
1197
+ form.append("message", text);
1198
+ form.append("transcript", JSON.stringify(history));
1199
+ form.append("enabledTools", JSON.stringify(enabledTools));
1200
+ for (const f of attachedFiles) form.append("attachments", f, f.name);
1201
+ body = form;
1202
+ } else {
1203
+ headers["Content-Type"] = "application/json";
1204
+ body = JSON.stringify({ message: text, transcript: history, enabledTools });
1205
+ }
1206
+ const res = await fetch(props.endpoint, { method: "POST", headers, body });
320
1207
  if (!res.ok) throw new Error(`Endpoint ${res.status}: ${await res.text().catch(() => "")}`);
1208
+ const contentType = res.headers.get("Content-Type") ?? "";
1209
+ if (contentType.includes("text/event-stream") && res.body) {
1210
+ const reader = res.body.getReader();
1211
+ const decoder = new TextDecoder();
1212
+ let buffer = "";
1213
+ let assembled = "";
1214
+ let lastError = null;
1215
+ while (true) {
1216
+ const { done, value } = await reader.read();
1217
+ if (done) break;
1218
+ buffer += decoder.decode(value, { stream: true });
1219
+ const events = buffer.split("\n\n");
1220
+ buffer = events.pop() ?? "";
1221
+ for (const evt of events) {
1222
+ const lines = evt.split("\n");
1223
+ let evtName = "message";
1224
+ let data2 = "";
1225
+ for (const line of lines) {
1226
+ if (line.startsWith("event:")) evtName = line.slice(6).trim();
1227
+ else if (line.startsWith("data:")) data2 = line.slice(5).trim();
1228
+ }
1229
+ if (!data2) continue;
1230
+ if (evtName === "token") {
1231
+ try {
1232
+ const tok = JSON.parse(data2);
1233
+ assembled += tok;
1234
+ onToken(tok);
1235
+ } catch {
1236
+ }
1237
+ } else if (evtName === "done") {
1238
+ try {
1239
+ const obj = JSON.parse(data2);
1240
+ if (obj.reply) return obj.reply;
1241
+ } catch {
1242
+ }
1243
+ } else if (evtName === "error") {
1244
+ try {
1245
+ const obj = JSON.parse(data2);
1246
+ lastError = obj.message ?? "stream error";
1247
+ } catch {
1248
+ lastError = "stream error";
1249
+ }
1250
+ }
1251
+ }
1252
+ }
1253
+ if (lastError) throw new Error(lastError);
1254
+ return assembled;
1255
+ }
321
1256
  const data = await res.json();
322
1257
  if (data.error) throw new Error(data.error);
323
1258
  if (!data.reply) throw new Error("Endpoint returned no reply.");
@@ -325,18 +1260,42 @@ function ChatWidget(props) {
325
1260
  }
326
1261
  async function send() {
327
1262
  const text = input.trim();
328
- if (!text || sending) return;
1263
+ const attached = files;
1264
+ if (!text && attached.length === 0 || sending) return;
329
1265
  setInput("");
330
- const userMsg = { id: `u${Date.now()}`, role: "user", content: text, ts: Date.now() };
1266
+ setFiles([]);
1267
+ const userContent = attached.length > 0 ? `${text}${text ? "\n" : ""}\u{1F4CE} ${attached.map((f) => f.name).join(", ")}` : text;
1268
+ const userMsg = { id: `u${Date.now()}`, role: "user", content: userContent, ts: Date.now() };
331
1269
  setMessages((prev) => [...prev, userMsg]);
332
1270
  setSending(true);
1271
+ const assistantId = `a${Date.now()}`;
1272
+ setMessages((prev) => [...prev, { id: assistantId, role: "assistant", content: "", ts: Date.now() }]);
1273
+ const appendToken = (tok) => {
1274
+ setMessages(
1275
+ (prev) => prev.map((m) => m.id === assistantId ? { ...m, content: m.content + tok } : m)
1276
+ );
1277
+ };
333
1278
  try {
334
1279
  const history = messages.filter((m) => m.role !== "system").map((m) => ({ role: m.role, content: m.content }));
335
- const reply = isEndpointMode ? await fetchReplyFromEndpoint(text, history) : (await bot.reply(text, { history })).reply;
336
- setMessages((prev) => [...prev, { id: `a${Date.now()}`, role: "assistant", content: reply, ts: Date.now() }]);
1280
+ const reply = isEndpointMode ? await fetchReplyFromEndpoint(text, history, attached, appendToken) : (await bot.reply(text, { history })).reply;
1281
+ const markers = parseToolMarkers(reply);
1282
+ const cleanReply = stripToolMarkers(reply);
1283
+ setMessages(
1284
+ (prev) => prev.map((m) => m.id === assistantId ? { ...m, content: cleanReply } : m)
1285
+ );
1286
+ if (markers.length > 0) {
1287
+ setPendingTools((prev) => [
1288
+ ...prev,
1289
+ ...markers.map((marker) => ({ messageId: assistantId, marker, status: "pending" }))
1290
+ ]);
1291
+ }
337
1292
  } catch (err) {
338
1293
  const errMsg = err instanceof Error ? err.message : String(err);
339
- setMessages((prev) => [...prev, { id: `e${Date.now()}`, role: "assistant", content: `Sorry \u2014 something went wrong. (${errMsg})`, ts: Date.now() }]);
1294
+ setMessages(
1295
+ (prev) => prev.map(
1296
+ (m) => m.id === assistantId ? { ...m, content: `Sorry \u2014 something went wrong. (${errMsg})` } : m
1297
+ )
1298
+ );
340
1299
  } finally {
341
1300
  setSending(false);
342
1301
  }
@@ -450,29 +1409,122 @@ function ChatWidget(props) {
450
1409
  background: SURFACE_MUTED
451
1410
  },
452
1411
  children: [
453
- messages.map((m) => /* @__PURE__ */ jsxRuntime.jsx(
454
- "div",
455
- {
456
- className: "chatbotlite-msg",
457
- style: {
458
- alignSelf: m.role === "user" ? "flex-end" : "flex-start",
459
- maxWidth: "82%",
460
- padding: "9px 13px",
461
- borderRadius: m.role === "user" ? "18px 18px 4px 18px" : "18px 18px 18px 4px",
462
- background: m.role === "user" ? primary : SURFACE,
463
- color: m.role === "user" ? onPrimary : TEXT_BODY,
464
- border: m.role === "user" ? "none" : `1px solid ${BORDER}`,
465
- fontSize: 14,
466
- lineHeight: 1.5,
467
- letterSpacing: "-0.005em",
468
- whiteSpace: "pre-wrap",
469
- wordBreak: "break-word",
470
- boxShadow: m.role === "user" ? "0 1px 2px rgba(15,23,42,0.12)" : "0 1px 2px rgba(15,23,42,0.04)"
471
- },
472
- children: m.content
473
- },
474
- m.id
475
- )),
1412
+ messages.map((m) => /* @__PURE__ */ jsxRuntime.jsxs("div", { style: { display: "flex", flexDirection: "column", gap: 6, alignItems: m.role === "user" ? "flex-end" : "stretch" }, children: [
1413
+ m.content && /* @__PURE__ */ jsxRuntime.jsxs(
1414
+ "div",
1415
+ {
1416
+ className: "chatbotlite-msg",
1417
+ style: {
1418
+ alignSelf: m.role === "user" ? "flex-end" : "flex-start",
1419
+ maxWidth: "82%",
1420
+ padding: "9px 13px",
1421
+ borderRadius: m.role === "user" ? "18px 18px 4px 18px" : "18px 18px 18px 4px",
1422
+ background: m.role === "user" ? primary : SURFACE,
1423
+ color: m.role === "user" ? onPrimary : TEXT_BODY,
1424
+ border: m.role === "user" ? "none" : `1px solid ${BORDER}`,
1425
+ fontSize: 14,
1426
+ lineHeight: 1.5,
1427
+ letterSpacing: "-0.005em",
1428
+ whiteSpace: "pre-wrap",
1429
+ wordBreak: "break-word",
1430
+ boxShadow: m.role === "user" ? "0 1px 2px rgba(15,23,42,0.12)" : "0 1px 2px rgba(15,23,42,0.04)"
1431
+ },
1432
+ children: [
1433
+ m.content,
1434
+ sending && m.role === "assistant" && m === messages[messages.length - 1] && /* @__PURE__ */ jsxRuntime.jsx("span", { className: "chatbotlite-cursor", "aria-hidden": "true" })
1435
+ ]
1436
+ }
1437
+ ),
1438
+ pendingTools.map((pt, originalIdx) => ({ pt, originalIdx })).filter(({ pt }) => pt.messageId === m.id).map(({ pt, originalIdx }) => {
1439
+ const toolCommonStyle = { className: "chatbotlite-msg", style: { alignSelf: "stretch" } };
1440
+ const palette = {
1441
+ primary,
1442
+ onPrimary,
1443
+ border: BORDER,
1444
+ surface: SURFACE,
1445
+ surfaceMuted: SURFACE_MUTED,
1446
+ textBody: TEXT_BODY,
1447
+ textMuted: TEXT_MUTED
1448
+ };
1449
+ if (pt.marker.name === "uploadForReview" && tools.uploadForReview) {
1450
+ return /* @__PURE__ */ jsxRuntime.jsx("div", { ...toolCommonStyle, children: /* @__PURE__ */ jsxRuntime.jsx(
1451
+ UploadForReview,
1452
+ {
1453
+ ...palette,
1454
+ purpose: String(pt.marker.args.purpose ?? "files"),
1455
+ accept: String(pt.marker.args.accept ?? "*"),
1456
+ maxMb: Number(pt.marker.args.maxMb ?? 10),
1457
+ submitting: pt.status === "submitting",
1458
+ submitted: pt.status === "submitted",
1459
+ onSubmit: async (files2) => {
1460
+ setPendingTools(
1461
+ (prev) => prev.map((p, i) => i === originalIdx ? { ...p, status: "submitting" } : p)
1462
+ );
1463
+ try {
1464
+ const result = await tools.uploadForReview.handler({
1465
+ files: files2,
1466
+ purpose: String(pt.marker.args.purpose ?? "files")
1467
+ });
1468
+ await handleToolSubmit("uploadForReview", originalIdx, result);
1469
+ } catch (err) {
1470
+ setPendingTools(
1471
+ (prev) => prev.map((p, i) => i === originalIdx ? { ...p, status: "pending" } : p)
1472
+ );
1473
+ throw err;
1474
+ }
1475
+ }
1476
+ }
1477
+ ) }, `tool-${originalIdx}`);
1478
+ }
1479
+ if (pt.marker.name === "scheduleCallback" && tools.scheduleCallback) {
1480
+ return /* @__PURE__ */ jsxRuntime.jsx("div", { ...toolCommonStyle, children: /* @__PURE__ */ jsxRuntime.jsx(
1481
+ ScheduleCallback,
1482
+ {
1483
+ ...palette,
1484
+ durationMin: Number(pt.marker.args.durationMin ?? 15),
1485
+ timezone: String(pt.marker.args.timezone ?? "UTC"),
1486
+ submitting: pt.status === "submitting",
1487
+ submitted: pt.status === "submitted",
1488
+ ...pt.result?.confirmedAt ? { submittedSlot: String(pt.result.confirmedAt) } : {},
1489
+ getAvailableSlots: tools.scheduleCallback.getAvailableSlots,
1490
+ onConfirm: async (slot) => {
1491
+ setPendingTools(
1492
+ (prev) => prev.map((p, i) => i === originalIdx ? { ...p, status: "submitting" } : p)
1493
+ );
1494
+ const result = await tools.scheduleCallback.onConfirm({ slot });
1495
+ await handleToolSubmit("scheduleCallback", originalIdx, result);
1496
+ }
1497
+ }
1498
+ ) }, `tool-${originalIdx}`);
1499
+ }
1500
+ if (pt.marker.name === "requestPayment" && tools.requestPayment) {
1501
+ return /* @__PURE__ */ jsxRuntime.jsx("div", { ...toolCommonStyle, children: /* @__PURE__ */ jsxRuntime.jsx(
1502
+ RequestPayment,
1503
+ {
1504
+ ...palette,
1505
+ amount: Number(pt.marker.args.amount ?? 0),
1506
+ currency: String(pt.marker.args.currency ?? "USD"),
1507
+ ...pt.marker.args.reason ? { reason: String(pt.marker.args.reason) } : {},
1508
+ showInterac: tools.requestPayment.showInterac ?? true,
1509
+ ...tools.requestPayment.stripeLink ? { stripeLink: tools.requestPayment.stripeLink } : {},
1510
+ submitting: pt.status === "submitting",
1511
+ submitted: pt.status === "submitted",
1512
+ ...pt.result?.method ? { submittedMethod: pt.result.method } : {},
1513
+ onPick: async (method) => {
1514
+ setPendingTools(
1515
+ (prev) => prev.map((p, i) => i === originalIdx ? { ...p, status: "submitting" } : p)
1516
+ );
1517
+ const amount = Number(pt.marker.args.amount ?? 0);
1518
+ const currency = String(pt.marker.args.currency ?? "USD");
1519
+ const result = await tools.requestPayment.onPick({ method, amount, currency });
1520
+ await handleToolSubmit("requestPayment", originalIdx, { ...result, method });
1521
+ }
1522
+ }
1523
+ ) }, `tool-${originalIdx}`);
1524
+ }
1525
+ return null;
1526
+ })
1527
+ ] }, m.id)),
476
1528
  sending && /* @__PURE__ */ jsxRuntime.jsxs(
477
1529
  "div",
478
1530
  {
@@ -497,66 +1549,169 @@ function ChatWidget(props) {
497
1549
  ),
498
1550
  /* @__PURE__ */ jsxRuntime.jsxs("div", { style: {
499
1551
  display: "flex",
1552
+ flexDirection: "column",
500
1553
  padding: 12,
501
1554
  gap: 8,
502
1555
  background: SURFACE,
503
1556
  borderTop: `1px solid ${BORDER}`
504
1557
  }, children: [
505
- /* @__PURE__ */ jsxRuntime.jsx(
506
- "input",
1558
+ files.length > 0 && /* @__PURE__ */ jsxRuntime.jsx("div", { style: { display: "flex", flexWrap: "wrap", gap: 6 }, children: files.map((f, i) => /* @__PURE__ */ jsxRuntime.jsxs(
1559
+ "span",
507
1560
  {
508
- ref: inputRef,
509
- className: "chatbotlite-input",
510
- type: "text",
511
- value: input,
512
- onChange: (e) => setInput(e.target.value),
513
- onKeyDown: (e) => {
514
- if (e.key === "Enter" && !e.shiftKey) {
515
- e.preventDefault();
516
- void send();
517
- }
518
- },
519
- placeholder: "Type a message\u2026",
520
- disabled: sending,
521
1561
  style: {
522
- flex: 1,
523
- padding: "10px 14px",
524
- borderRadius: 12,
525
- border: `1px solid ${BORDER}`,
1562
+ display: "inline-flex",
1563
+ alignItems: "center",
1564
+ gap: 6,
1565
+ padding: "4px 8px 4px 10px",
1566
+ borderRadius: 8,
526
1567
  background: SURFACE_MUTED,
527
- fontSize: 14,
528
- fontFamily: FONT_STACK,
1568
+ border: `1px solid ${BORDER}`,
1569
+ fontSize: 12,
529
1570
  color: TEXT_BODY,
530
- outline: "none",
531
- transition: "box-shadow 120ms ease, border-color 120ms ease"
532
- }
533
- }
534
- ),
535
- /* @__PURE__ */ jsxRuntime.jsx(
536
- "button",
537
- {
538
- className: "chatbotlite-send",
539
- onClick: () => void send(),
540
- disabled: sending || !input.trim(),
541
- "aria-label": "Send message",
542
- style: {
543
- padding: "0 16px",
544
- height: 40,
545
- minWidth: 64,
546
- borderRadius: 12,
547
- background: primary,
548
- color: onPrimary,
549
- border: "none",
550
- fontSize: 14,
551
- fontWeight: 600,
552
- fontFamily: FONT_STACK,
553
- cursor: sending || !input.trim() ? "default" : "pointer",
554
- opacity: sending || !input.trim() ? 0.4 : 1,
555
- boxShadow: "0 2px 6px -1px rgba(15,23,42,0.18)"
1571
+ maxWidth: 200
556
1572
  },
557
- children: "Send"
558
- }
559
- )
1573
+ children: [
1574
+ /* @__PURE__ */ jsxRuntime.jsxs("span", { style: { overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }, children: [
1575
+ "\u{1F4CE} ",
1576
+ f.name
1577
+ ] }),
1578
+ /* @__PURE__ */ jsxRuntime.jsx(
1579
+ "button",
1580
+ {
1581
+ onClick: () => removeFile(i),
1582
+ "aria-label": `Remove ${f.name}`,
1583
+ style: {
1584
+ background: "transparent",
1585
+ border: "none",
1586
+ cursor: "pointer",
1587
+ color: TEXT_MUTED,
1588
+ fontSize: 14,
1589
+ lineHeight: 1,
1590
+ padding: 0
1591
+ },
1592
+ children: "\xD7"
1593
+ }
1594
+ )
1595
+ ]
1596
+ },
1597
+ `${f.name}-${i}`
1598
+ )) }),
1599
+ /* @__PURE__ */ jsxRuntime.jsxs("div", { style: { display: "flex", gap: 8 }, children: [
1600
+ attachEnabled && /* @__PURE__ */ jsxRuntime.jsxs(jsxRuntime.Fragment, { children: [
1601
+ /* @__PURE__ */ jsxRuntime.jsx(
1602
+ "input",
1603
+ {
1604
+ ref: fileInputRef,
1605
+ type: "file",
1606
+ multiple: true,
1607
+ accept: acceptAttr,
1608
+ style: { display: "none" },
1609
+ onChange: (e) => {
1610
+ if (e.target.files) addFiles(e.target.files);
1611
+ e.target.value = "";
1612
+ }
1613
+ }
1614
+ ),
1615
+ /* @__PURE__ */ jsxRuntime.jsx(
1616
+ "button",
1617
+ {
1618
+ className: "chatbotlite-attach-btn",
1619
+ onClick: () => fileInputRef.current?.click(),
1620
+ disabled: sending || files.length >= maxFiles,
1621
+ "aria-label": "Attach file",
1622
+ style: {
1623
+ width: 40,
1624
+ height: 40,
1625
+ borderRadius: 10,
1626
+ background: SURFACE_MUTED,
1627
+ border: `1px solid ${BORDER}`,
1628
+ cursor: sending || files.length >= maxFiles ? "default" : "pointer",
1629
+ opacity: sending || files.length >= maxFiles ? 0.4 : 1,
1630
+ fontSize: 16,
1631
+ transition: "background 120ms ease, transform 80ms ease"
1632
+ },
1633
+ children: "\u{1F4CE}"
1634
+ }
1635
+ )
1636
+ ] }),
1637
+ voiceEnabled && speechSupported && /* @__PURE__ */ jsxRuntime.jsx(
1638
+ "button",
1639
+ {
1640
+ className: "chatbotlite-voice-btn",
1641
+ onClick: toggleVoice,
1642
+ disabled: sending,
1643
+ "aria-label": voiceListening ? "Stop recording" : "Start voice input",
1644
+ style: {
1645
+ width: 40,
1646
+ height: 40,
1647
+ borderRadius: 10,
1648
+ background: voiceListening ? primary : SURFACE_MUTED,
1649
+ color: voiceListening ? onPrimary : TEXT_BODY,
1650
+ border: `1px solid ${voiceListening ? primary : BORDER}`,
1651
+ cursor: sending ? "default" : "pointer",
1652
+ opacity: sending ? 0.4 : 1,
1653
+ fontSize: 16,
1654
+ transition: "background 120ms ease, color 120ms ease, border-color 120ms ease, transform 80ms ease"
1655
+ },
1656
+ children: "\u{1F399}\uFE0F"
1657
+ }
1658
+ ),
1659
+ /* @__PURE__ */ jsxRuntime.jsx(
1660
+ "input",
1661
+ {
1662
+ ref: inputRef,
1663
+ className: "chatbotlite-input",
1664
+ type: "text",
1665
+ value: input,
1666
+ onChange: (e) => setInput(e.target.value),
1667
+ onKeyDown: (e) => {
1668
+ if (e.key === "Enter" && !e.shiftKey) {
1669
+ e.preventDefault();
1670
+ void send();
1671
+ }
1672
+ },
1673
+ placeholder: "Type a message\u2026",
1674
+ disabled: sending,
1675
+ style: {
1676
+ flex: 1,
1677
+ padding: "10px 14px",
1678
+ borderRadius: 12,
1679
+ border: `1px solid ${BORDER}`,
1680
+ background: SURFACE_MUTED,
1681
+ fontSize: 14,
1682
+ fontFamily: FONT_STACK,
1683
+ color: TEXT_BODY,
1684
+ outline: "none",
1685
+ transition: "box-shadow 120ms ease, border-color 120ms ease"
1686
+ }
1687
+ }
1688
+ ),
1689
+ /* @__PURE__ */ jsxRuntime.jsx(
1690
+ "button",
1691
+ {
1692
+ className: "chatbotlite-send",
1693
+ onClick: () => void send(),
1694
+ disabled: sending || !input.trim() && files.length === 0,
1695
+ "aria-label": "Send message",
1696
+ style: {
1697
+ padding: "0 16px",
1698
+ height: 40,
1699
+ minWidth: 64,
1700
+ borderRadius: 12,
1701
+ background: primary,
1702
+ color: onPrimary,
1703
+ border: "none",
1704
+ fontSize: 14,
1705
+ fontWeight: 600,
1706
+ fontFamily: FONT_STACK,
1707
+ cursor: sending || !input.trim() && files.length === 0 ? "default" : "pointer",
1708
+ opacity: sending || !input.trim() && files.length === 0 ? 0.4 : 1,
1709
+ boxShadow: "0 2px 6px -1px rgba(15,23,42,0.18)"
1710
+ },
1711
+ children: "Send"
1712
+ }
1713
+ )
1714
+ ] })
560
1715
  ] }),
561
1716
  showBranding && /* @__PURE__ */ jsxRuntime.jsxs(
562
1717
  "a",