vanilla-agent 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 +310 -0
- package/dist/index.cjs +14 -0
- package/dist/index.cjs.map +1 -0
- package/dist/index.d.cts +370 -0
- package/dist/index.d.ts +370 -0
- package/dist/index.global.js +1710 -0
- package/dist/index.global.js.map +1 -0
- package/dist/index.js +14 -0
- package/dist/index.js.map +1 -0
- package/dist/install.global.js +2 -0
- package/dist/install.global.js.map +1 -0
- package/dist/widget.css +752 -0
- package/package.json +61 -0
- package/src/client.ts +577 -0
- package/src/components/forms.ts +165 -0
- package/src/components/launcher.ts +184 -0
- package/src/components/message-bubble.ts +52 -0
- package/src/components/messages.ts +43 -0
- package/src/components/panel.ts +555 -0
- package/src/components/reasoning-bubble.ts +114 -0
- package/src/components/suggestions.ts +52 -0
- package/src/components/tool-bubble.ts +158 -0
- package/src/index.ts +37 -0
- package/src/install.ts +159 -0
- package/src/plugins/registry.ts +72 -0
- package/src/plugins/types.ts +90 -0
- package/src/postprocessors.ts +76 -0
- package/src/runtime/init.ts +116 -0
- package/src/session.ts +206 -0
- package/src/styles/tailwind.css +19 -0
- package/src/styles/widget.css +752 -0
- package/src/types.ts +194 -0
- package/src/ui.ts +1325 -0
- package/src/utils/constants.ts +11 -0
- package/src/utils/dom.ts +20 -0
- package/src/utils/formatting.ts +77 -0
- package/src/utils/icons.ts +92 -0
- package/src/utils/positioning.ts +12 -0
- package/src/utils/theme.ts +20 -0
- package/src/widget.css +1 -0
- package/widget.css +1 -0
package/README.md
ADDED
|
@@ -0,0 +1,310 @@
|
|
|
1
|
+
## Streaming Agent Widget
|
|
2
|
+
|
|
3
|
+
Installable vanilla JavaScript widget for embedding a streaming AI assistant on any website.
|
|
4
|
+
|
|
5
|
+
### Installation
|
|
6
|
+
|
|
7
|
+
```bash
|
|
8
|
+
npm install vanilla-agent
|
|
9
|
+
```
|
|
10
|
+
|
|
11
|
+
### Building locally
|
|
12
|
+
|
|
13
|
+
```bash
|
|
14
|
+
pnpm build
|
|
15
|
+
```
|
|
16
|
+
|
|
17
|
+
- `dist/index.js` (ESM), `dist/index.cjs` (CJS), and `dist/index.global.js` (IIFE) provide different module formats.
|
|
18
|
+
- `dist/widget.css` is the prefixed Tailwind bundle.
|
|
19
|
+
- `dist/install.global.js` is the automatic installer script for easy script tag installation.
|
|
20
|
+
|
|
21
|
+
### Using with modules
|
|
22
|
+
|
|
23
|
+
```ts
|
|
24
|
+
import 'vanilla-agent/widget.css';
|
|
25
|
+
import {
|
|
26
|
+
initChatWidget,
|
|
27
|
+
createChatExperience,
|
|
28
|
+
markdownPostprocessor,
|
|
29
|
+
directivePostprocessor
|
|
30
|
+
} from 'vanilla-agent';
|
|
31
|
+
|
|
32
|
+
const proxyUrl = '/api/chat/dispatch';
|
|
33
|
+
|
|
34
|
+
// Inline embed
|
|
35
|
+
const inlineHost = document.querySelector('#inline-widget')!;
|
|
36
|
+
createChatExperience(inlineHost, {
|
|
37
|
+
apiUrl: proxyUrl,
|
|
38
|
+
launcher: { enabled: false },
|
|
39
|
+
theme: { accent: '#2563eb', primary: '#111827' },
|
|
40
|
+
features: {
|
|
41
|
+
showReasoning: true, // Show thinking bubbles (default: true)
|
|
42
|
+
showToolCalls: true // Show tool usage bubbles (default: true)
|
|
43
|
+
},
|
|
44
|
+
suggestionChips: ['What can you do?', 'Show API docs'],
|
|
45
|
+
postprocessMessage: ({ text }) => markdownPostprocessor(text)
|
|
46
|
+
});
|
|
47
|
+
|
|
48
|
+
// Floating launcher with runtime updates
|
|
49
|
+
const controller = initChatWidget({
|
|
50
|
+
target: '#launcher-root',
|
|
51
|
+
config: {
|
|
52
|
+
apiUrl: proxyUrl,
|
|
53
|
+
launcher: {
|
|
54
|
+
enabled: true,
|
|
55
|
+
autoExpand: false,
|
|
56
|
+
title: 'AI Assistant',
|
|
57
|
+
subtitle: 'Here to help you get answers fast',
|
|
58
|
+
width: 'min(420px, 95vw)'
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
});
|
|
62
|
+
|
|
63
|
+
document.querySelector('#dark-mode')?.addEventListener('click', () => {
|
|
64
|
+
controller.update({ theme: { surface: '#0f172a', primary: '#f8fafc' } });
|
|
65
|
+
});
|
|
66
|
+
controller.update({
|
|
67
|
+
postprocessMessage: ({ text, streaming }) =>
|
|
68
|
+
streaming ? markdownPostprocessor(text) : directivePostprocessor(text)
|
|
69
|
+
});
|
|
70
|
+
```
|
|
71
|
+
|
|
72
|
+
> **Security note:** When you return HTML from `postprocessMessage`, make sure you sanitise it before injecting into the page. The provided postprocessors (`markdownPostprocessor`, `directivePostprocessor`) do not perform sanitisation.
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
### Programmatic control
|
|
76
|
+
|
|
77
|
+
`initChatWidget` (and `createChatExperience`) return a controller with `open()`, `close()`, and `toggle()` helpers so you can launch the widget from your own UI elements.
|
|
78
|
+
|
|
79
|
+
```ts
|
|
80
|
+
const chat = initChatWidget({
|
|
81
|
+
target: '#launcher-root',
|
|
82
|
+
config: { /* ... */ }
|
|
83
|
+
})
|
|
84
|
+
|
|
85
|
+
document.getElementById('open-chat')?.addEventListener('click', () => chat.open())
|
|
86
|
+
document.getElementById('toggle-chat')?.addEventListener('click', () => chat.toggle())
|
|
87
|
+
```
|
|
88
|
+
|
|
89
|
+
### Travrse adapter
|
|
90
|
+
|
|
91
|
+
This package ships with a Travrse adapter by default. The proxy handles all flow configuration, keeping the client lightweight and flexible.
|
|
92
|
+
|
|
93
|
+
**Flow configuration happens server-side** - you have three options:
|
|
94
|
+
|
|
95
|
+
1. **Use default flow** - The proxy includes a basic streaming chat flow out of the box
|
|
96
|
+
2. **Reference a Travrse flow ID** - Configure flows in your Travrse dashboard and reference them by ID
|
|
97
|
+
3. **Define custom flows** - Build flow configurations directly in the proxy
|
|
98
|
+
|
|
99
|
+
The client simply sends messages to the proxy, which constructs the full Travrse payload. This architecture allows you to:
|
|
100
|
+
- Change models/prompts without redeploying the widget
|
|
101
|
+
- A/B test different flows server-side
|
|
102
|
+
- Enforce security and cost controls centrally
|
|
103
|
+
- Support multiple flows for different use cases
|
|
104
|
+
|
|
105
|
+
### Directive postprocessor
|
|
106
|
+
|
|
107
|
+
`directivePostprocessor` looks for either `<Form type="init" />` tokens or
|
|
108
|
+
`<Directive>{"component":"form","type":"init"}</Directive>` blocks and swaps them for placeholders that the widget upgrades into interactive UI (forms, cards, etc.). See `examples/embedded-app/json.html` for a full working example that submits to the proxy’s `/form` endpoint and posts a follow-up message back into the chat.
|
|
109
|
+
|
|
110
|
+
### Script tag installation
|
|
111
|
+
|
|
112
|
+
The widget can be installed via a simple script tag, perfect for platforms where you can't compile custom code. There are two methods:
|
|
113
|
+
|
|
114
|
+
#### Method 1: Automatic installer (recommended)
|
|
115
|
+
|
|
116
|
+
The easiest way is to use the automatic installer script. It handles loading CSS and JavaScript, then initializes the widget automatically:
|
|
117
|
+
|
|
118
|
+
```html
|
|
119
|
+
<!-- Add this before the closing </body> tag -->
|
|
120
|
+
<script>
|
|
121
|
+
window.siteAgentConfig = {
|
|
122
|
+
target: 'body', // or '#my-container' for specific placement
|
|
123
|
+
config: {
|
|
124
|
+
apiUrl: 'https://your-proxy.com/api/chat/dispatch',
|
|
125
|
+
launcher: {
|
|
126
|
+
enabled: true,
|
|
127
|
+
title: 'AI Assistant',
|
|
128
|
+
subtitle: 'How can I help you?'
|
|
129
|
+
},
|
|
130
|
+
theme: {
|
|
131
|
+
accent: '#2563eb',
|
|
132
|
+
surface: '#ffffff'
|
|
133
|
+
}
|
|
134
|
+
}
|
|
135
|
+
};
|
|
136
|
+
</script>
|
|
137
|
+
<script src="https://cdn.jsdelivr.net/npm/vanilla-agent@latest/dist/install.global.js"></script>
|
|
138
|
+
```
|
|
139
|
+
|
|
140
|
+
**Installer options:**
|
|
141
|
+
|
|
142
|
+
- `version` - Package version to load (default: `"latest"`)
|
|
143
|
+
- `cdn` - CDN provider: `"jsdelivr"` or `"unpkg"` (default: `"jsdelivr"`)
|
|
144
|
+
- `cssUrl` - Custom CSS URL (overrides CDN)
|
|
145
|
+
- `jsUrl` - Custom JS URL (overrides CDN)
|
|
146
|
+
- `target` - CSS selector or element where widget mounts (default: `"body"`)
|
|
147
|
+
- `config` - Widget configuration object (see Configuration reference)
|
|
148
|
+
- `autoInit` - Automatically initialize after loading (default: `true`)
|
|
149
|
+
|
|
150
|
+
**Example with version pinning:**
|
|
151
|
+
|
|
152
|
+
```html
|
|
153
|
+
<script>
|
|
154
|
+
window.siteAgentConfig = {
|
|
155
|
+
version: '0.1.0', // Pin to specific version
|
|
156
|
+
config: {
|
|
157
|
+
apiUrl: '/api/chat/dispatch',
|
|
158
|
+
launcher: { enabled: true, title: 'Support Chat' }
|
|
159
|
+
}
|
|
160
|
+
};
|
|
161
|
+
</script>
|
|
162
|
+
<script src="https://cdn.jsdelivr.net/npm/vanilla-agent@0.1.0/dist/install.global.js"></script>
|
|
163
|
+
```
|
|
164
|
+
|
|
165
|
+
#### Method 2: Manual installation
|
|
166
|
+
|
|
167
|
+
For more control, manually load CSS and JavaScript:
|
|
168
|
+
|
|
169
|
+
```html
|
|
170
|
+
<!-- Load CSS -->
|
|
171
|
+
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/vanilla-agent@latest/dist/widget.css" />
|
|
172
|
+
|
|
173
|
+
<!-- Load JavaScript -->
|
|
174
|
+
<script src="https://cdn.jsdelivr.net/npm/vanilla-agent@latest/dist/index.global.js"></script>
|
|
175
|
+
|
|
176
|
+
<!-- Initialize widget -->
|
|
177
|
+
<script>
|
|
178
|
+
window.ChatWidget.initChatWidget({
|
|
179
|
+
target: '#vanilla-agent-anchor', // or 'body' for floating launcher
|
|
180
|
+
config: {
|
|
181
|
+
apiUrl: '/api/chat/dispatch',
|
|
182
|
+
launcher: {
|
|
183
|
+
enabled: true,
|
|
184
|
+
title: 'AI Assistant',
|
|
185
|
+
subtitle: 'Here to help'
|
|
186
|
+
},
|
|
187
|
+
theme: {
|
|
188
|
+
accent: '#111827',
|
|
189
|
+
surface: '#f5f5f5'
|
|
190
|
+
}
|
|
191
|
+
}
|
|
192
|
+
});
|
|
193
|
+
</script>
|
|
194
|
+
```
|
|
195
|
+
|
|
196
|
+
**CDN options:**
|
|
197
|
+
|
|
198
|
+
- **jsDelivr** (recommended): `https://cdn.jsdelivr.net/npm/vanilla-agent@VERSION/dist/`
|
|
199
|
+
- **unpkg**: `https://unpkg.com/vanilla-agent@VERSION/dist/`
|
|
200
|
+
|
|
201
|
+
Replace `VERSION` with `latest` for auto-updates, or a specific version like `0.1.0` for stability.
|
|
202
|
+
|
|
203
|
+
**Available files:**
|
|
204
|
+
|
|
205
|
+
- `widget.css` - Stylesheet (required)
|
|
206
|
+
- `index.global.js` - Widget JavaScript (IIFE format)
|
|
207
|
+
- `install.global.js` - Automatic installer script
|
|
208
|
+
|
|
209
|
+
The script build exposes a `window.ChatWidget` global with `initChatWidget()` and other exports.
|
|
210
|
+
|
|
211
|
+
### Configuration reference
|
|
212
|
+
|
|
213
|
+
| Option | Type | Description |
|
|
214
|
+
| --- | --- | --- |
|
|
215
|
+
| `apiUrl` | `string` | Proxy endpoint for your chat backend (defaults to Travrse's cloud API). |
|
|
216
|
+
| `flowId` | `string` | Optional Travrse flow ID. If provided, the client sends it to the proxy which can use it to select a specific flow. |
|
|
217
|
+
| `headers` | `Record<string, string>` | Extra headers forwarded to your proxy. |
|
|
218
|
+
| `copy` | `{ welcomeTitle?, welcomeSubtitle?, inputPlaceholder?, sendButtonLabel? }` | Customize user-facing text. |
|
|
219
|
+
| `theme` | `{ primary?, secondary?, surface?, muted?, accent?, radiusSm?, radiusMd?, radiusLg?, radiusFull? }` | Override CSS variables for the widget. Colors: `primary` (text/UI), `secondary` (unused), `surface` (backgrounds), `muted` (secondary text), `accent` (buttons/links). Border radius: `radiusSm` (0.75rem, inputs), `radiusMd` (1rem, cards), `radiusLg` (1.5rem, panels/bubbles), `radiusFull` (9999px, pills/buttons). |
|
|
220
|
+
| `features` | `ChatWidgetFeatureFlags` | Toggle UI features: `showReasoning?` (show thinking bubbles, default: `true`), `showToolCalls?` (show tool usage bubbles, default: `true`). |
|
|
221
|
+
| `launcher` | `{ enabled?, autoExpand?, title?, subtitle?, iconUrl?, position? }` | Controls the floating launcher button. |
|
|
222
|
+
| `initialMessages` | `ChatWidgetMessage[]` | Seed the conversation transcript. |
|
|
223
|
+
| `suggestionChips` | `string[]` | Render quick reply buttons above the composer. |
|
|
224
|
+
| `postprocessMessage` | `(ctx) => string` | Transform message text before it renders (return HTML). Combine with `markdownPostprocessor` for rich output. |
|
|
225
|
+
| `formEndpoint` | `string` | Endpoint used by built-in directives (defaults to `/form`). |
|
|
226
|
+
| `launcherWidth` | `string` | CSS width applied to the floating launcher panel (e.g. `320px`, `90vw`). Defaults to `min(360px, calc(100vw - 24px))`. |
|
|
227
|
+
| `debug` | `boolean` | Emits verbose logs to `console`. |
|
|
228
|
+
|
|
229
|
+
All options are safe to mutate via `initChatWidget(...).update(newConfig)`.
|
|
230
|
+
|
|
231
|
+
### Optional proxy server
|
|
232
|
+
|
|
233
|
+
The proxy server handles flow configuration and forwards requests to Travrse. You can configure it in three ways:
|
|
234
|
+
|
|
235
|
+
**Option 1: Use default flow (recommended for getting started)**
|
|
236
|
+
|
|
237
|
+
```ts
|
|
238
|
+
// api/chat.ts
|
|
239
|
+
import { createChatProxyApp } from 'vanilla-agent-proxy';
|
|
240
|
+
|
|
241
|
+
export default createChatProxyApp({
|
|
242
|
+
path: '/api/chat/dispatch',
|
|
243
|
+
allowedOrigins: ['https://www.example.com']
|
|
244
|
+
});
|
|
245
|
+
```
|
|
246
|
+
|
|
247
|
+
**Option 2: Reference a Travrse flow ID**
|
|
248
|
+
|
|
249
|
+
```ts
|
|
250
|
+
import { createChatProxyApp } from 'vanilla-agent-proxy';
|
|
251
|
+
|
|
252
|
+
export default createChatProxyApp({
|
|
253
|
+
path: '/api/chat/dispatch',
|
|
254
|
+
allowedOrigins: ['https://www.example.com'],
|
|
255
|
+
flowId: 'flow_abc123' // Flow created in Travrse dashboard or API
|
|
256
|
+
});
|
|
257
|
+
```
|
|
258
|
+
|
|
259
|
+
**Option 3: Define a custom flow**
|
|
260
|
+
|
|
261
|
+
```ts
|
|
262
|
+
import { createChatProxyApp } from 'vanilla-agent-proxy';
|
|
263
|
+
|
|
264
|
+
export default createChatProxyApp({
|
|
265
|
+
path: '/api/chat/dispatch',
|
|
266
|
+
allowedOrigins: ['https://www.example.com'],
|
|
267
|
+
flowConfig: {
|
|
268
|
+
name: "Custom Chat Flow",
|
|
269
|
+
description: "Specialized assistant flow",
|
|
270
|
+
steps: [
|
|
271
|
+
{
|
|
272
|
+
id: "custom_prompt",
|
|
273
|
+
name: "Custom Prompt",
|
|
274
|
+
type: "prompt",
|
|
275
|
+
enabled: true,
|
|
276
|
+
config: {
|
|
277
|
+
model: "meta/llama3.1-8b-instruct-free",
|
|
278
|
+
responseFormat: "markdown",
|
|
279
|
+
outputVariable: "prompt_result",
|
|
280
|
+
userPrompt: "{{user_message}}",
|
|
281
|
+
systemPrompt: "you are a helpful assistant, chatting with a user",
|
|
282
|
+
previousMessages: "{{messages}}"
|
|
283
|
+
}
|
|
284
|
+
}
|
|
285
|
+
]
|
|
286
|
+
}
|
|
287
|
+
});
|
|
288
|
+
```
|
|
289
|
+
|
|
290
|
+
**Hosting on Vercel:**
|
|
291
|
+
|
|
292
|
+
```ts
|
|
293
|
+
import { createVercelHandler } from 'vanilla-agent-proxy';
|
|
294
|
+
|
|
295
|
+
export default createVercelHandler({
|
|
296
|
+
allowedOrigins: ['https://www.example.com'],
|
|
297
|
+
flowId: 'flow_abc123' // Optional
|
|
298
|
+
});
|
|
299
|
+
```
|
|
300
|
+
|
|
301
|
+
**Environment setup:**
|
|
302
|
+
|
|
303
|
+
Add `TRAVRSE_API_KEY` to your environment. The proxy constructs the Travrse payload (including flow configuration) and streams the response back to the client.
|
|
304
|
+
|
|
305
|
+
### Development notes
|
|
306
|
+
|
|
307
|
+
- The widget streams results using SSE and mirrors the backend `flow_complete`/`step_chunk` events.
|
|
308
|
+
- Tailwind-esc classes are prefixed with `tvw-` and scoped to `#vanilla-agent-root`, so they won't collide with the host page.
|
|
309
|
+
- Run `pnpm dev` from the repository root to boot the example proxy (`examples/proxy`) and the vanilla demo (`examples/embedded-app`).
|
|
310
|
+
- The proxy prefers port `43111` but automatically selects the next free port if needed.
|
package/dist/index.cjs
ADDED
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
"use strict";var we=Object.defineProperty;var Ln=Object.getOwnPropertyDescriptor;var Wn=Object.getOwnPropertyNames;var kn=Object.prototype.hasOwnProperty;var Hn=(e,n)=>{for(var t in n)we(e,t,{get:n[t],enumerable:!0})},An=(e,n,t,a)=>{if(n&&typeof n=="object"||typeof n=="function")for(let o of Wn(n))!kn.call(e,o)&&o!==t&&we(e,o,{get:()=>n[o],enumerable:!(a=Ln(n,o))||a.enumerable});return e};var In=e=>An(we({},"__esModule",{value:!0}),e);var On={};Hn(On,{ChatWidgetClient:()=>oe,ChatWidgetSession:()=>ae,createChatExperience:()=>ue,default:()=>Pn,directivePostprocessor:()=>vn,escapeHtml:()=>ce,initChatWidget:()=>We,markdownPostprocessor:()=>he,pluginRegistry:()=>de});module.exports=In(On);var me=require("marked");me.marked.setOptions({breaks:!0});var he=e=>me.marked.parse(e),ce=e=>e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'"),Bn=e=>e.replace(/"/g,""").replace(/</g,"<").replace(/>/g,">"),hn=e=>`%%FORM_PLACEHOLDER_${e}%%`,Rn=(e,n)=>{let t=e;return t=t.replace(/<Directive>([\s\S]*?)<\/Directive>/gi,(a,o)=>{try{let l=JSON.parse(o.trim());if(l&&typeof l=="object"&&l.component==="form"&&l.type){let i=hn(n.length);return n.push({token:i,type:String(l.type)}),i}}catch{return a}return a}),t=t.replace(/<Form\s+type="([^"]+)"\s*\/>/gi,(a,o)=>{let l=hn(n.length);return n.push({token:l,type:o}),l}),t},vn=e=>{let n=[],t=Rn(e,n),a=he(t);return n.forEach(({token:o,type:l})=>{let i=new RegExp(o.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g"),b=`<div class="tvw-form-directive" data-tv-form="${Bn(l)}"></div>`;a=a.replace(i,b)}),a};var Nn="https://api.travrse.ai/v1/dispatch",oe=class{constructor(n={}){this.config=n;var t;this.apiUrl=(t=n.apiUrl)!=null?t:Nn,this.headers={"Content-Type":"application/json",...n.headers},this.debug=!!n.debug}async dispatch(n,t){let a=new AbortController;n.signal&&n.signal.addEventListener("abort",()=>a.abort()),t({type:"status",status:"connecting"});let o={messages:n.messages.slice().sort((i,C)=>{let b=new Date(i.createdAt).getTime(),T=new Date(C.createdAt).getTime();return b-T}).map(i=>({role:i.role,content:i.content,createdAt:i.createdAt})),...this.config.flowId&&{flowId:this.config.flowId}};this.debug&&console.debug("[ChatWidgetClient] dispatch body",o);let l=await fetch(this.apiUrl,{method:"POST",headers:this.headers,body:JSON.stringify(o),signal:a.signal});if(!l.ok||!l.body){let i=new Error(`Chat backend request failed: ${l.status} ${l.statusText}`);throw t({type:"error",error:i}),i}t({type:"status",status:"connected"});try{await this.streamResponse(l.body,t)}finally{t({type:"status",status:"idle"})}}async streamResponse(n,t){var B,H,U,y,R,wt,Mt,ht,D,Bt,lt,Et,st,pt,E,Y,Dt,q,xt,se,Ht,At,re,Rt,It,Ct,Nt,zt,$t,Pt,rt,mt,St,vt,Jt,Zt,ft,Qt,Ft,Ot,j,Lt,Ut,jt,_t,Vt,Xt,Yt,Kt;let a=n.getReader(),o=new TextDecoder,l="",i=Date.now(),C=0,b=()=>i+C++,T=g=>{let A=g.reasoning?{...g.reasoning,chunks:[...g.reasoning.chunks]}:void 0,N=g.toolCall?{...g.toolCall,chunks:g.toolCall.chunks?[...g.toolCall.chunks]:void 0}:void 0,V=g.tools?g.tools.map(s=>({...s,chunks:s.chunks?[...s.chunks]:void 0})):void 0;return{...g,reasoning:A,toolCall:N,tools:V}},v=g=>{t({type:"message",message:T(g)})},W=null,w=new Map,z=new Map,x={lastId:null,byStep:new Map},$={lastId:null,byCall:new Map},ut=g=>{if(g==null)return null;try{return String(g)}catch{return null}},P=g=>{var A,N,V,s,h;return ut((h=(s=(V=(N=(A=g.stepId)!=null?A:g.step_id)!=null?N:g.step)!=null?V:g.parentId)!=null?s:g.flowStepId)!=null?h:g.flow_step_id)},_=g=>{var A,N,V,s,h,S,c;return ut((c=(S=(h=(s=(V=(N=(A=g.callId)!=null?A:g.call_id)!=null?N:g.requestId)!=null?V:g.request_id)!=null?s:g.toolCallId)!=null?h:g.tool_call_id)!=null?S:g.stepId)!=null?c:g.step_id)},ot=()=>W||(W={id:`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"assistant",sequence:b()},v(W),W),it=(g,A)=>{x.lastId=A,g&&x.byStep.set(g,A)},M=(g,A)=>{var h;let N=(h=g.reasoningId)!=null?h:g.id,V=P(g);if(N){let S=String(N);return it(V,S),S}if(V){let S=x.byStep.get(V);if(S)return x.lastId=S,S}if(x.lastId&&!A)return x.lastId;if(!A)return null;let s=`reason-${b()}`;return it(V,s),s},f=g=>{let A=w.get(g);if(A)return A;let N={id:`reason-${g}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"reasoning",sequence:b(),reasoning:{id:g,status:"streaming",chunks:[]}};return w.set(g,N),v(N),N},O=(g,A)=>{$.lastId=A,g&&$.byCall.set(g,A)},G=(g,A)=>{var h;let N=(h=g.toolId)!=null?h:g.id,V=_(g);if(N){let S=String(N);return O(V,S),S}if(V){let S=$.byCall.get(V);if(S)return $.lastId=S,S}if($.lastId&&!A)return $.lastId;if(!A)return null;let s=`tool-${b()}`;return O(V,s),s},tt=g=>{let A=z.get(g);if(A)return A;let N={id:`tool-${g}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"tool",sequence:b(),toolCall:{id:g,status:"pending"}};return z.set(g,N),v(N),N},J=g=>{if(typeof g=="number"&&Number.isFinite(g))return g;if(typeof g=="string"){let A=Number(g);if(!Number.isNaN(A)&&Number.isFinite(A))return A;let N=Date.parse(g);if(!Number.isNaN(N))return N}return Date.now()};for(;;){let{done:g,value:A}=await a.read();if(g)break;l+=o.decode(A,{stream:!0});let N=l.split(`
|
|
2
|
+
|
|
3
|
+
`);l=(B=N.pop())!=null?B:"";for(let V of N){let s=V.split(`
|
|
4
|
+
`),h="message",S="";for(let m of s)m.startsWith("event:")?h=m.replace("event:","").trim():m.startsWith("data:")&&(S+=m.replace("data:","").trim());if(!S)continue;let c;try{c=JSON.parse(S)}catch(m){t({type:"error",error:m instanceof Error?m:new Error("Failed to parse chat stream payload")});continue}let r=h!=="message"?h:(H=c.type)!=null?H:"message";if(r==="reason_start"){let m=(U=M(c,!0))!=null?U:`reason-${b()}`,d=f(m);d.reasoning=(y=d.reasoning)!=null?y:{id:m,status:"streaming",chunks:[]},d.reasoning.startedAt=(wt=d.reasoning.startedAt)!=null?wt:J((R=c.startedAt)!=null?R:c.timestamp),d.reasoning.completedAt=void 0,d.reasoning.durationMs=void 0,d.streaming=!0,d.reasoning.status="streaming",v(d)}else if(r==="reason_chunk"){let m=(ht=(Mt=M(c,!1))!=null?Mt:M(c,!0))!=null?ht:`reason-${b()}`,d=f(m);d.reasoning=(D=d.reasoning)!=null?D:{id:m,status:"streaming",chunks:[]},d.reasoning.startedAt=(lt=d.reasoning.startedAt)!=null?lt:J((Bt=c.startedAt)!=null?Bt:c.timestamp);let p=(pt=(st=(Et=c.reasoningText)!=null?Et:c.text)!=null?st:c.delta)!=null?pt:"";if(p&&c.hidden!==!0&&d.reasoning.chunks.push(String(p)),d.reasoning.status=c.done?"complete":"streaming",c.done){d.reasoning.completedAt=J((E=c.completedAt)!=null?E:c.timestamp);let L=(Y=d.reasoning.startedAt)!=null?Y:Date.now();d.reasoning.durationMs=Math.max(0,((Dt=d.reasoning.completedAt)!=null?Dt:Date.now())-L)}d.streaming=d.reasoning.status!=="complete",v(d)}else if(r==="reason_complete"){let m=(xt=(q=M(c,!1))!=null?q:M(c,!0))!=null?xt:`reason-${b()}`,d=w.get(m);if(d!=null&&d.reasoning){d.reasoning.status="complete",d.reasoning.completedAt=J((se=c.completedAt)!=null?se:c.timestamp);let L=(Ht=d.reasoning.startedAt)!=null?Ht:Date.now();d.reasoning.durationMs=Math.max(0,((At=d.reasoning.completedAt)!=null?At:Date.now())-L),d.streaming=!1,v(d)}let p=P(c);p&&x.byStep.delete(p)}else if(r==="tool_start"){let m=(re=G(c,!0))!=null?re:`tool-${b()}`,d=tt(m),p=(Rt=d.toolCall)!=null?Rt:{id:m,status:"pending"};p.name=(It=c.toolName)!=null?It:p.name,p.status="running",c.args!==void 0&&(p.args=c.args),p.startedAt=(Nt=p.startedAt)!=null?Nt:J((Ct=c.startedAt)!=null?Ct:c.timestamp),p.completedAt=void 0,p.durationMs=void 0,d.toolCall=p,d.streaming=!0,v(d)}else if(r==="tool_chunk"){let m=($t=(zt=G(c,!1))!=null?zt:G(c,!0))!=null?$t:`tool-${b()}`,d=tt(m),p=(Pt=d.toolCall)!=null?Pt:{id:m,status:"running"};p.startedAt=(mt=p.startedAt)!=null?mt:J((rt=c.startedAt)!=null?rt:c.timestamp);let L=(Jt=(vt=(St=c.text)!=null?St:c.delta)!=null?vt:c.message)!=null?Jt:"";L&&(p.chunks=(Zt=p.chunks)!=null?Zt:[],p.chunks.push(String(L))),p.status="running",d.toolCall=p,d.streaming=!0,v(d)}else if(r==="tool_complete"){let m=(Qt=(ft=G(c,!1))!=null?ft:G(c,!0))!=null?Qt:`tool-${b()}`,d=tt(m),p=(Ft=d.toolCall)!=null?Ft:{id:m,status:"running"};if(p.status="complete",c.result!==void 0&&(p.result=c.result),typeof c.duration=="number"&&(p.duration=c.duration),p.completedAt=J((Ot=c.completedAt)!=null?Ot:c.timestamp),typeof c.duration=="number")p.durationMs=c.duration;else{let et=(j=p.startedAt)!=null?j:Date.now();p.durationMs=Math.max(0,((Lt=p.completedAt)!=null?Lt:Date.now())-et)}d.toolCall=p,d.streaming=!1,v(d);let L=_(c);L&&$.byCall.delete(L)}else if(r==="step_chunk"){let m=ot(),d=(_t=(jt=(Ut=c.text)!=null?Ut:c.delta)!=null?jt:c.content)!=null?_t:"";if(d&&(m.content+=d,v(m)),c.isComplete){let p=(Xt=(Vt=c.result)==null?void 0:Vt.response)!=null?Xt:m.content;p&&(m.content=p,m.streaming=!1,v(m))}}else if(r==="step_complete"){let m=(Yt=c.result)==null?void 0:Yt.response,d=ot();m?(d.content=m,d.streaming=!1,v(d)):(d.streaming=!1,v(d))}else if(r==="flow_complete"){let m=(Kt=c.result)==null?void 0:Kt.response;if(m){let d=ot();m!==d.content&&(d.content=m,v(d)),d.streaming=!1,v(d)}else{let d=W;if(d){let p=d;p.streaming=!1,v(p)}}t({type:"status",status:"idle"})}else r==="error"&&c.error&&t({type:"error",error:c.error instanceof Error?c.error:new Error(String(c.error))})}}}};var ae=class{constructor(n={},t){this.config=n;this.callbacks=t;this.status="idle";this.streaming=!1;this.abortController=null;this.sequenceCounter=Date.now();this.handleEvent=n=>{var t,a;n.type==="message"?this.upsertMessage(n.message):n.type==="status"?(this.setStatus(n.status),n.status==="connecting"?this.setStreaming(!0):(n.status==="idle"||n.status==="error")&&(this.setStreaming(!1),this.abortController=null)):n.type==="error"&&(this.setStatus("error"),this.setStreaming(!1),this.abortController=null,(a=(t=this.callbacks).onError)==null||a.call(t,n.error))};var a;this.messages=[...(a=n.initialMessages)!=null?a:[]].map(o=>{var l;return{...o,sequence:(l=o.sequence)!=null?l:this.nextSequence()}}),this.messages=this.sortMessages(this.messages),this.client=new oe(n),this.messages.length&&this.callbacks.onMessagesChanged([...this.messages]),this.callbacks.onStatusChanged(this.status)}updateConfig(n){this.config={...this.config,...n},this.client=new oe(this.config)}getMessages(){return[...this.messages]}getStatus(){return this.status}isStreaming(){return this.streaming}async sendMessage(n){var i,C,b,T,v;let t=n.trim();if(!t)return;(i=this.abortController)==null||i.abort();let a={id:`user-${Date.now()}`,role:"user",content:t,createdAt:new Date().toISOString(),sequence:this.nextSequence()};this.appendMessage(a),this.setStreaming(!0);let o=new AbortController;this.abortController=o;let l=[...this.messages];try{await this.client.dispatch({messages:l,signal:o.signal},this.handleEvent)}catch(W){let w={id:`assistant-${Date.now()}`,role:"assistant",createdAt:new Date().toISOString(),content:"It looks like the proxy isn't returning a real response yet. Here's a sample message so you can continue testing locally.",sequence:this.nextSequence()};this.appendMessage(w),this.setStatus("idle"),this.setStreaming(!1),this.abortController=null,W instanceof Error?(b=(C=this.callbacks).onError)==null||b.call(C,W):(v=(T=this.callbacks).onError)==null||v.call(T,new Error(String(W)))}}cancel(){var n;(n=this.abortController)==null||n.abort(),this.abortController=null,this.setStreaming(!1),this.setStatus("idle")}setStatus(n){this.status!==n&&(this.status=n,this.callbacks.onStatusChanged(n))}setStreaming(n){this.streaming!==n&&(this.streaming=n,this.callbacks.onStreamingChanged(n))}appendMessage(n){let t=this.ensureSequence(n);this.messages=this.sortMessages([...this.messages,t]),this.callbacks.onMessagesChanged([...this.messages])}upsertMessage(n){let t=this.ensureSequence(n),a=this.messages.findIndex(o=>o.id===t.id);if(a===-1){this.appendMessage(t);return}this.messages=this.messages.map((o,l)=>l===a?{...o,...t}:o),this.messages=this.sortMessages(this.messages),this.callbacks.onMessagesChanged([...this.messages])}ensureSequence(n){return n.sequence!==void 0?{...n}:{...n,sequence:this.nextSequence()}}nextSequence(){return this.sequenceCounter++}sortMessages(n){return[...n].sort((t,a)=>{var b,T;let o=new Date(t.createdAt).getTime(),l=new Date(a.createdAt).getTime();if(!Number.isNaN(o)&&!Number.isNaN(l)&&o!==l)return o-l;let i=(b=t.sequence)!=null?b:0,C=(T=a.sequence)!=null?T:0;return i!==C?i-C:t.id.localeCompare(a.id)})}};var ve=(e,n)=>{var a;let t=(a=n==null?void 0:n.theme)!=null?a:{};Object.entries(t).forEach(([o,l])=>{if(l==null||l==="")return;let i=o.replace(/[A-Z]/g,C=>`-${C.toLowerCase()}`);e.style.setProperty(`--cw-${i}`,String(l))})};var fn=require("lucide"),Tt=(e,n=24,t="currentColor",a=2)=>{try{let o=e.split("-").map(i=>i.charAt(0).toUpperCase()+i.slice(1)).join(""),l=fn.icons[o];return l?Fn(l,n,t,a):(console.warn(`Lucide icon "${e}" not found (tried "${o}"). Available icons: https://lucide.dev/icons`),null)}catch(o){return console.warn(`Failed to render Lucide icon "${e}":`,o),null}};function Fn(e,n,t,a){if(!e||!Array.isArray(e))return null;let o=document.createElementNS("http://www.w3.org/2000/svg","svg");return o.setAttribute("width",String(n)),o.setAttribute("height",String(n)),o.setAttribute("viewBox","0 0 24 24"),o.setAttribute("fill","none"),o.setAttribute("stroke",t),o.setAttribute("stroke-width",String(a)),o.setAttribute("stroke-linecap","round"),o.setAttribute("stroke-linejoin","round"),o.setAttribute("aria-hidden","true"),e.forEach(l=>{if(Array.isArray(l)&&l.length>=2){let i=l[0],C=l[1];if(C){let b=document.createElementNS("http://www.w3.org/2000/svg",i);Object.entries(C).forEach(([T,v])=>{T!=="stroke"&&b.setAttribute(T,String(v))}),o.appendChild(b)}}}),o}var u=(e,n)=>{let t=document.createElement(e);return n&&(t.className=n),t};var ct={idle:"Online",connecting:"Connecting\u2026",connected:"Streaming\u2026",error:"Offline"};var Gt={"bottom-right":"tvw-bottom-6 tvw-right-6","bottom-left":"tvw-bottom-6 tvw-left-6","top-right":"tvw-top-6 tvw-right-6","top-left":"tvw-top-6 tvw-left-6"};var fe=(e,n)=>{let t=u("button");t.type="button",t.innerHTML=`
|
|
5
|
+
<span class="tvw-inline-flex tvw-items-center tvw-justify-center tvw-rounded-full tvw-bg-cw-primary tvw-text-white" data-role="launcher-icon">\u{1F4AC}</span>
|
|
6
|
+
<img data-role="launcher-image" class="tvw-rounded-full tvw-object-cover" alt="" style="display:none" />
|
|
7
|
+
<span class="tvw-flex tvw-flex-col tvw-items-start tvw-text-left">
|
|
8
|
+
<span class="tvw-text-sm tvw-font-semibold tvw-text-cw-primary" data-role="launcher-title"></span>
|
|
9
|
+
<span class="tvw-text-xs tvw-text-cw-muted" data-role="launcher-subtitle"></span>
|
|
10
|
+
</span>
|
|
11
|
+
<span class="tvw-ml-2 tvw-grid tvw-place-items-center tvw-rounded-full tvw-bg-cw-primary tvw-text-cw-call-to-action" data-role="launcher-call-to-action-icon">\u2197</span>
|
|
12
|
+
`,t.addEventListener("click",n);let a=l=>{var $,ut,P,_,ot,it,M,f,O,G;let i=($=l.launcher)!=null?$:{},C=t.querySelector("[data-role='launcher-title']");C&&(C.textContent=(ut=i.title)!=null?ut:"Chat Assistant");let b=t.querySelector("[data-role='launcher-subtitle']");b&&(b.textContent=(P=i.subtitle)!=null?P:"Get answers fast");let T=t.querySelector(".tvw-flex-col");T&&(i.textHidden?T.style.display="none":T.style.display="");let v=t.querySelector("[data-role='launcher-icon']");if(v)if(i.agentIconHidden)v.style.display="none";else{let tt=(_=i.agentIconSize)!=null?_:"40px";if(v.style.height=tt,v.style.width=tt,v.innerHTML="",i.agentIconName){let J=parseFloat(tt)||24,B=Tt(i.agentIconName,J*.6,"#ffffff",2);B?(v.appendChild(B),v.style.display=""):(v.textContent=(ot=i.agentIconText)!=null?ot:"\u{1F4AC}",v.style.display="")}else i.iconUrl?v.style.display="none":(v.textContent=(it=i.agentIconText)!=null?it:"\u{1F4AC}",v.style.display="")}let W=t.querySelector("[data-role='launcher-image']");if(W){let tt=(M=i.agentIconSize)!=null?M:"40px";W.style.height=tt,W.style.width=tt,i.iconUrl&&!i.agentIconName&&!i.agentIconHidden?(W.src=i.iconUrl,W.style.display="block"):W.style.display="none"}let w=t.querySelector("[data-role='launcher-call-to-action-icon']");if(w){let tt=(f=i.callToActionIconSize)!=null?f:"32px";w.style.height=tt,w.style.width=tt,i.callToActionIconBackgroundColor?(w.style.backgroundColor=i.callToActionIconBackgroundColor,w.classList.remove("tvw-bg-cw-primary")):(w.style.backgroundColor="",w.classList.add("tvw-bg-cw-primary"));let J=0;if(i.callToActionIconPadding?(w.style.boxSizing="border-box",w.style.padding=i.callToActionIconPadding,J=(parseFloat(i.callToActionIconPadding)||0)*2):(w.style.boxSizing="",w.style.padding=""),i.callToActionIconHidden)w.style.display="none";else if(w.style.display="",w.innerHTML="",i.callToActionIconName){let B=parseFloat(tt)||24,H=Math.max(B-J,8),U=Tt(i.callToActionIconName,H,"currentColor",2);U?w.appendChild(U):w.textContent=(O=i.callToActionIconText)!=null?O:"\u2197"}else w.textContent=(G=i.callToActionIconText)!=null?G:"\u2197"}let z=i.position&&Gt[i.position]?Gt[i.position]:Gt["bottom-right"],x="tvw-fixed tvw-flex tvw-items-center tvw-gap-3 tvw-rounded-launcher tvw-bg-cw-surface tvw-py-2.5 tvw-pl-3 tvw-pr-3 tvw-shadow-lg tvw-border tvw-border-gray-200 tvw-transition hover:tvw-translate-y-[-2px] tvw-cursor-pointer";t.className=`${x} ${z}`},o=()=>{t.removeEventListener("click",n),t.remove()};return e&&a(e),{element:t,update:a,destroy:o}};var yn=e=>{var b,T,v,W,w;if(!((T=(b=e==null?void 0:e.launcher)==null?void 0:b.enabled)!=null?T:!0)){let z=u("div","tvw-relative tvw-w-full tvw-h-full"),x=u("div","tvw-relative tvw-w-full tvw-h-full tvw-min-h-[360px]");return z.appendChild(x),{wrapper:z,panel:x}}let t=(v=e==null?void 0:e.launcher)!=null?v:{},a=t.position&&Gt[t.position]?Gt[t.position]:Gt["bottom-right"],o=u("div",`tvw-fixed ${a} tvw-z-50 tvw-transition`),l=u("div","tvw-relative tvw-min-h-[320px]"),i=(w=(W=e==null?void 0:e.launcher)==null?void 0:W.width)!=null?w:e==null?void 0:e.launcherWidth,C=i!=null?i:"min(360px, calc(100vw - 24px))";return l.style.width=C,l.style.maxWidth=C,o.appendChild(l),{wrapper:o,panel:l}},bn=(e,n=!0)=>{var Rt,It,Ct,Nt,zt,$t,Pt,rt,mt,St,vt,Jt,Zt,ft,Qt,Ft,Ot,j,Lt,Ut,jt,_t,Vt,Xt,Yt,Kt,g,A,N,V,s,h,S,c,r,m,d,p,L,et,Z,F,Q;let t=u("div","tvw-flex tvw-h-full tvw-w-full tvw-flex-col tvw-bg-cw-surface tvw-text-cw-primary tvw-rounded-2xl tvw-overflow-hidden tvw-shadow-2xl tvw-border tvw-border-cw-border"),a=u("div","tvw-flex tvw-items-center tvw-gap-3 tvw-bg-cw-surface tvw-px-6 tvw-py-5 tvw-border-b-cw-divider"),o=(Rt=e==null?void 0:e.launcher)!=null?Rt:{},l=(It=o.headerIconSize)!=null?It:"48px",i=(Ct=o.closeButtonSize)!=null?Ct:"32px",C=(Nt=o.closeButtonPlacement)!=null?Nt:"inline",b=(zt=o.headerIconHidden)!=null?zt:!1,T=o.headerIconName,v=u("div","tvw-flex tvw-items-center tvw-justify-center tvw-rounded-xl tvw-bg-cw-primary tvw-text-white tvw-text-xl");if(v.style.height=l,v.style.width=l,!b)if(T){let I=parseFloat(l)||24,K=Tt(T,I*.6,"#ffffff",2);K?v.replaceChildren(K):v.textContent=(Pt=($t=e==null?void 0:e.launcher)==null?void 0:$t.agentIconText)!=null?Pt:"\u{1F4AC}"}else if((rt=e==null?void 0:e.launcher)!=null&&rt.iconUrl){let I=u("img");I.src=e.launcher.iconUrl,I.alt="",I.className="tvw-rounded-xl tvw-object-cover",I.style.height=l,I.style.width=l,v.replaceChildren(I)}else v.textContent=(St=(mt=e==null?void 0:e.launcher)==null?void 0:mt.agentIconText)!=null?St:"\u{1F4AC}";let W=u("div","tvw-flex tvw-flex-col"),w=u("span","tvw-text-base tvw-font-semibold");w.textContent=(Jt=(vt=e==null?void 0:e.launcher)==null?void 0:vt.title)!=null?Jt:"Chat Assistant";let z=u("span","tvw-text-xs tvw-text-cw-muted");z.textContent=(ft=(Zt=e==null?void 0:e.launcher)==null?void 0:Zt.subtitle)!=null?ft:"Here to help you get answers fast",W.append(w,z),b?a.append(W):a.append(v,W);let x=u("button",C==="top-right"?"tvw-absolute tvw-top-4 tvw-right-4 tvw-z-50 tvw-inline-flex tvw-items-center tvw-justify-center tvw-rounded-full tvw-text-cw-muted hover:tvw-bg-gray-100 tvw-cursor-pointer tvw-border-none":"tvw-ml-auto tvw-inline-flex tvw-items-center tvw-justify-center tvw-rounded-full tvw-text-cw-muted hover:tvw-bg-gray-100 tvw-cursor-pointer tvw-border-none");if(x.style.height=i,x.style.width=i,x.type="button",x.setAttribute("aria-label","Close chat"),x.textContent="\xD7",x.style.display=n?"":"none",o.closeButtonColor?(x.style.color=o.closeButtonColor,x.classList.remove("tvw-text-cw-muted")):(x.style.color="",x.classList.add("tvw-text-cw-muted")),o.closeButtonBackgroundColor?(x.style.backgroundColor=o.closeButtonBackgroundColor,x.classList.remove("hover:tvw-bg-gray-100")):(x.style.backgroundColor="",x.classList.add("hover:tvw-bg-gray-100")),o.closeButtonBorderWidth||o.closeButtonBorderColor){let I=o.closeButtonBorderWidth||"0px",K=o.closeButtonBorderColor||"transparent";x.style.border=`${I} solid ${K}`,x.classList.remove("tvw-border-none")}else x.style.border="",x.classList.add("tvw-border-none");o.closeButtonBorderRadius?(x.style.borderRadius=o.closeButtonBorderRadius,x.classList.remove("tvw-rounded-full")):(x.style.borderRadius="",x.classList.add("tvw-rounded-full")),C==="top-right"?(t.style.position="relative",t.appendChild(x)):a.appendChild(x);let $=u("div","tvw-flex tvw-flex-1 tvw-min-h-0 tvw-flex-col tvw-gap-6 tvw-overflow-y-auto tvw-bg-cw-container tvw-px-6 tvw-py-6"),ut=u("div","tvw-rounded-2xl tvw-bg-cw-surface tvw-p-6 tvw-shadow-sm"),P=u("h2","tvw-text-lg tvw-font-semibold tvw-text-cw-primary");P.textContent=(Ft=(Qt=e==null?void 0:e.copy)==null?void 0:Qt.welcomeTitle)!=null?Ft:"Hello \u{1F44B}";let _=u("p","tvw-mt-2 tvw-text-sm tvw-text-cw-muted");_.textContent=(j=(Ot=e==null?void 0:e.copy)==null?void 0:Ot.welcomeSubtitle)!=null?j:"Ask anything about your account or products.",ut.append(P,_);let ot=u("div","tvw-flex tvw-flex-col tvw-gap-3");$.append(ut,ot);let it=u("div","tvw-border-t-cw-divider tvw-bg-cw-surface tvw-px-6 tvw-py-4"),M=u("div","tvw-mb-3 tvw-flex tvw-flex-wrap tvw-gap-2"),f=((Lt=e==null?void 0:e.voiceRecognition)==null?void 0:Lt.enabled)===!0,O=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),J=u("form",`tvw-flex tvw-items-end ${f&&O?"tvw-gap-1":"tvw-gap-3"} tvw-rounded-2xl tvw-border tvw-border-gray-200 tvw-bg-cw-input-background tvw-px-4 tvw-py-3`);J.style.outline="none";let B=u("textarea");B.placeholder=(jt=(Ut=e==null?void 0:e.copy)==null?void 0:Ut.inputPlaceholder)!=null?jt:"Type your message\u2026",B.className="tvw-min-h-[48px] tvw-flex-1 tvw-resize-none tvw-border-none tvw-bg-transparent tvw-text-sm tvw-text-cw-primary focus:tvw-outline-none focus:tvw-border-none",B.rows=1;let H=(Vt=(_t=e==null?void 0:e.theme)==null?void 0:_t.inputFontFamily)!=null?Vt:"sans-serif",U=(Yt=(Xt=e==null?void 0:e.theme)==null?void 0:Xt.inputFontWeight)!=null?Yt:"400",y=I=>{switch(I){case"serif":return'Georgia, "Times New Roman", Times, serif';case"mono":return'"Courier New", Courier, "Lucida Console", Monaco, monospace';case"sans-serif":default:return'-apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif'}};B.style.fontFamily=y(H),B.style.fontWeight=U,B.style.border="none",B.style.outline="none",B.style.borderWidth="0",B.style.borderStyle="none",B.style.borderColor="transparent",B.addEventListener("focus",()=>{B.style.border="none",B.style.outline="none",B.style.borderWidth="0",B.style.borderStyle="none",B.style.borderColor="transparent",B.style.boxShadow="none"}),B.addEventListener("blur",()=>{B.style.border="none",B.style.outline="none"});let R=(Kt=e==null?void 0:e.sendButton)!=null?Kt:{},wt=(g=R.useIcon)!=null?g:!1,Mt=(A=R.iconText)!=null?A:"\u2191",ht=R.iconName,D=(N=R.tooltipText)!=null?N:"Send message",Bt=(V=R.showTooltip)!=null?V:!1,lt=(s=R.size)!=null?s:"40px",Et=R.backgroundColor,st=R.textColor,pt=u("div","tvw-send-button-wrapper"),E=u("button",wt?"tvw-rounded-button tvw-flex tvw-items-center tvw-justify-center disabled:tvw-opacity-50 tvw-cursor-pointer":"tvw-rounded-button tvw-bg-cw-accent tvw-px-4 tvw-py-2 tvw-text-sm tvw-font-semibold disabled:tvw-opacity-50 tvw-cursor-pointer");if(E.type="submit",wt){if(E.style.width=lt,E.style.height=lt,E.style.minWidth=lt,E.style.minHeight=lt,E.style.fontSize="18px",E.style.lineHeight="1",E.innerHTML="",ht){let I=parseFloat(lt)||24,K=st&&typeof st=="string"&&st.trim()?st.trim():"currentColor",yt=Tt(ht,I,K,2);yt?(E.appendChild(yt),E.style.color=K):(E.textContent=Mt,st?E.style.color=st:E.classList.add("tvw-text-white"))}else E.textContent=Mt,st?E.style.color=st:E.classList.add("tvw-text-white");Et?E.style.backgroundColor=Et:E.classList.add("tvw-bg-cw-primary")}else E.textContent=(S=(h=e==null?void 0:e.copy)==null?void 0:h.sendButtonLabel)!=null?S:"Send",st?E.style.color=st:E.classList.add("tvw-text-white");if(R.borderWidth&&(E.style.borderWidth=R.borderWidth,E.style.borderStyle="solid"),R.borderColor&&(E.style.borderColor=R.borderColor),R.paddingX?(E.style.paddingLeft=R.paddingX,E.style.paddingRight=R.paddingX):(E.style.paddingLeft="",E.style.paddingRight=""),R.paddingY?(E.style.paddingTop=R.paddingY,E.style.paddingBottom=R.paddingY):(E.style.paddingTop="",E.style.paddingBottom=""),Bt&&D){let I=u("div","tvw-send-button-tooltip");I.textContent=D,pt.appendChild(I)}pt.appendChild(E);let Y=(c=e==null?void 0:e.voiceRecognition)!=null?c:{},Dt=Y.enabled===!0,q=null,xt=null,se=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined");if(Dt&&se){xt=u("div","tvw-send-button-wrapper"),q=u("button","tvw-rounded-button tvw-flex tvw-items-center tvw-justify-center disabled:tvw-opacity-50 tvw-cursor-pointer"),q.type="button",q.setAttribute("aria-label","Start voice recognition");let I=(r=Y.iconName)!=null?r:"mic",K=(m=Y.iconSize)!=null?m:lt,yt=parseFloat(K)||24,te=(d=Y.backgroundColor)!=null?d:Et,bt=(p=Y.iconColor)!=null?p:st;q.style.width=K,q.style.height=K,q.style.minWidth=K,q.style.minHeight=K,q.style.fontSize="18px",q.style.lineHeight="1";let Wt=bt||"currentColor",dt=Tt(I,yt,Wt,1.5);dt?(q.appendChild(dt),q.style.color=Wt):(q.textContent="\u{1F3A4}",q.style.color=Wt),te?q.style.backgroundColor=te:q.classList.add("tvw-bg-cw-primary"),bt?q.style.color=bt:!bt&&!st&&q.classList.add("tvw-text-white"),Y.borderWidth&&(q.style.borderWidth=Y.borderWidth,q.style.borderStyle="solid"),Y.borderColor&&(q.style.borderColor=Y.borderColor),Y.paddingX&&(q.style.paddingLeft=Y.paddingX,q.style.paddingRight=Y.paddingX),Y.paddingY&&(q.style.paddingTop=Y.paddingY,q.style.paddingBottom=Y.paddingY),xt.appendChild(q);let kt=(L=Y.tooltipText)!=null?L:"Start voice recognition";if(((et=Y.showTooltip)!=null?et:!1)&&kt){let ee=u("div","tvw-send-button-tooltip");ee.textContent=kt,xt.appendChild(ee)}}J.addEventListener("click",I=>{I.target!==E&&I.target!==pt&&I.target!==q&&I.target!==xt&&B.focus()}),J.append(B),xt&&J.append(xt),J.append(pt);let Ht=u("div","tvw-mt-2 tvw-text-right tvw-text-xs tvw-text-cw-muted"),At=(Z=e==null?void 0:e.statusIndicator)!=null?Z:{},re=(F=At.visible)!=null?F:!0;return Ht.style.display=re?"":"none",Ht.textContent=(Q=At.idleText)!=null?Q:"Online",it.append(M,J,Ht),t.append(a,$,it),{container:t,body:$,messagesWrapper:ot,suggestions:M,textarea:B,sendButton:E,sendButtonWrapper:pt,micButton:q,micButtonWrapper:xt,composerForm:J,statusText:Ht,introTitle:P,introSubtitle:_,closeButton:x,iconHolder:v}};var ye=(e,n)=>{let t=["tvw-max-w-[85%]","tvw-rounded-2xl","tvw-text-sm","tvw-leading-relaxed","tvw-shadow-sm"];e.role==="user"?t.push("tvw-ml-auto","tvw-bg-cw-accent","tvw-text-white","tvw-px-5","tvw-py-3"):t.push("tvw-bg-cw-surface","tvw-border","tvw-border-cw-message-border","tvw-text-cw-primary","tvw-px-5","tvw-py-3");let a=u("div",t.join(" "));return a.innerHTML=n({text:e.content,message:e,streaming:!!e.streaming}),a};var be=e=>{if(e===null)return"null";if(e===void 0)return"";if(typeof e=="string")return e;if(typeof e=="number"||typeof e=="boolean")return String(e);try{return JSON.stringify(e,null,2)}catch{return String(e)}},qn=e=>{var i,C;let n=(i=e.completedAt)!=null?i:Date.now(),t=(C=e.startedAt)!=null?C:n,o=(e.durationMs!==void 0?e.durationMs:Math.max(0,n-t))/1e3;return o<.1?"Thought for <0.1 seconds":`Thought for ${o>=10?Math.round(o).toString():o.toFixed(1).replace(/\.0$/,"")} seconds`},xn=e=>e.status==="complete"?qn(e):e.status==="pending"?"Waiting":"",Dn=e=>{var o,l,i;let t=(typeof e.duration=="number"?e.duration:typeof e.durationMs=="number"?e.durationMs:Math.max(0,((o=e.completedAt)!=null?o:Date.now())-((i=(l=e.startedAt)!=null?l:e.completedAt)!=null?i:Date.now())))/1e3;return t<.1?"Used tool for <0.1 seconds":`Used tool for ${t>=10?Math.round(t).toString():t.toFixed(1).replace(/\.0$/,"")} seconds`};var Cn=e=>e.status==="complete"?Dn(e):"Using tool...";var xe=new Set,Ce=e=>{let n=e.reasoning,t=u("div",["tvw-max-w-[85%]","tvw-rounded-2xl","tvw-bg-cw-surface","tvw-border","tvw-border-cw-message-border","tvw-text-cw-primary","tvw-shadow-sm","tvw-overflow-hidden","tvw-px-0","tvw-py-0"].join(" "));if(!n)return t;let a=xe.has(e.id),o=u("button","tvw-flex tvw-w-full tvw-items-center tvw-justify-between tvw-gap-3 tvw-bg-transparent tvw-px-4 tvw-py-3 tvw-text-left tvw-cursor-pointer tvw-border-none");o.type="button",o.setAttribute("aria-expanded",a?"true":"false");let l=u("div","tvw-flex tvw-flex-col tvw-text-left"),i=u("span","tvw-text-xs tvw-font-semibold tvw-text-cw-primary");i.textContent="Thinking...",l.appendChild(i);let C=u("span","tvw-text-xs tvw-text-cw-primary");C.textContent=xn(n),l.appendChild(C),n.status==="complete"?i.style.display="none":i.style.display="";let b=u("span","tvw-text-xs tvw-text-cw-primary");b.textContent=a?"Hide":"Show",o.append(l,b);let T=u("div","tvw-border-t tvw-border-gray-200 tvw-bg-gray-50 tvw-px-4 tvw-py-3");T.style.display=a?"":"none";let v=n.chunks.join(""),W=u("div","tvw-whitespace-pre-wrap tvw-text-xs tvw-leading-snug tvw-text-cw-muted");W.textContent=v||(n.status==="complete"?"No additional context was shared.":"Waiting for details\u2026"),T.appendChild(W);let w=()=>{o.setAttribute("aria-expanded",a?"true":"false"),b.textContent=a?"Hide":"Show",T.style.display=a?"":"none"},z=()=>{a=!a,a?xe.add(e.id):xe.delete(e.id),w()};return o.addEventListener("pointerdown",x=>{x.preventDefault(),z()}),o.addEventListener("keydown",x=>{(x.key==="Enter"||x.key===" ")&&(x.preventDefault(),z())}),w(),t.append(o,T),t};var Se=new Set,Te=e=>{let n=e.toolCall,t=u("div",["tvw-max-w-[85%]","tvw-rounded-2xl","tvw-bg-cw-surface","tvw-border","tvw-border-cw-message-border","tvw-text-cw-primary","tvw-shadow-sm","tvw-overflow-hidden","tvw-px-0","tvw-py-0"].join(" "));if(!n)return t;let a=Se.has(e.id),o=u("button","tvw-flex tvw-w-full tvw-items-center tvw-justify-between tvw-gap-3 tvw-bg-transparent tvw-px-4 tvw-py-3 tvw-text-left tvw-cursor-pointer tvw-border-none");o.type="button",o.setAttribute("aria-expanded",a?"true":"false");let l=u("div","tvw-flex tvw-flex-col tvw-text-left"),i=u("span","tvw-text-xs tvw-text-cw-primary");if(i.textContent=Cn(n),l.appendChild(i),n.name){let w=u("span","tvw-text-[11px] tvw-text-cw-muted");w.textContent=n.name,l.appendChild(w)}let C=u("span","tvw-text-xs tvw-text-cw-primary");C.textContent=a?"Hide":"Show";let b=u("div","tvw-flex tvw-items-center tvw-gap-2");b.append(C),o.append(l,b);let T=u("div","tvw-border-t tvw-border-gray-200 tvw-bg-gray-50 tvw-space-y-3 tvw-px-4 tvw-py-3");if(T.style.display=a?"":"none",n.args!==void 0){let w=u("div","tvw-space-y-1"),z=u("div","tvw-font-xxs tvw-font-medium tvw-text-cw-muted");z.textContent="Arguments";let x=u("pre","tvw-max-h-48 tvw-overflow-auto tvw-whitespace-pre-wrap tvw-rounded-lg tvw-border tvw-border-gray-100 tvw-bg-white tvw-px-3 tvw-py-2 tvw-font-xxs tvw-text-cw-primary");x.textContent=be(n.args),w.append(z,x),T.appendChild(w)}if(n.chunks&&n.chunks.length){let w=u("div","tvw-space-y-1"),z=u("div","tvw-font-xxs tvw-font-medium tvw-text-cw-muted");z.textContent="Activity";let x=u("pre","tvw-max-h-48 tvw-overflow-auto tvw-whitespace-pre-wrap tvw-rounded-lg tvw-border tvw-border-gray-100 tvw-bg-white tvw-px-3 tvw-py-2 tvw-font-xxs tvw-text-cw-primary");x.textContent=n.chunks.join(`
|
|
13
|
+
`),w.append(z,x),T.appendChild(w)}if(n.status==="complete"&&n.result!==void 0){let w=u("div","tvw-space-y-1"),z=u("div","tvw-font-xxs tvw-text-sm tvw-text-cw-muted");z.textContent="Result";let x=u("pre","tvw-max-h-48 tvw-overflow-auto tvw-whitespace-pre-wrap tvw-rounded-lg tvw-border tvw-border-gray-100 tvw-bg-white tvw-px-3 tvw-py-2 tvw-font-xxs tvw-text-cw-primary");x.textContent=be(n.result),w.append(z,x),T.appendChild(w)}if(n.status==="complete"&&typeof n.duration=="number"){let w=u("div","tvw-font-xxs tvw-text-cw-muted");w.textContent=`Duration: ${n.duration}ms`,T.appendChild(w)}let v=()=>{o.setAttribute("aria-expanded",a?"true":"false"),C.textContent=a?"Hide":"Show",T.style.display=a?"":"none"},W=()=>{a=!a,a?Se.add(e.id):Se.delete(e.id),v()};return o.addEventListener("pointerdown",w=>{w.preventDefault(),W()}),o.addEventListener("keydown",w=>{(w.key==="Enter"||w.key===" ")&&(w.preventDefault(),W())}),v(),t.append(o,T),t};var Sn=e=>{let n=[];return{buttons:n,render:(a,o,l,i)=>{if(e.innerHTML="",n.length=0,!a||!a.length||(i!=null?i:o?o.getMessages():[]).some(W=>W.role==="user"))return;let T=document.createDocumentFragment(),v=o?o.isStreaming():!1;a.forEach(W=>{let w=u("button","tvw-rounded-button tvw-bg-cw-surface tvw-px-3 tvw-py-1.5 tvw-text-xs tvw-font-medium tvw-text-cw-muted hover:tvw-opacity-90 tvw-cursor-pointer tvw-border tvw-border-gray-200");w.type="button",w.textContent=W,w.disabled=v,w.addEventListener("click",()=>{!o||o.isStreaming()||(l.value="",o.sendMessage(W))}),T.appendChild(w),n.push(w)}),e.appendChild(T)}}};var Tn={init:{title:"Schedule a Demo",description:"Share the basics and we'll follow up with a confirmation.",fields:[{name:"name",label:"Full name",placeholder:"Jane Doe",required:!0},{name:"email",label:"Work email",placeholder:"jane@example.com",type:"email",required:!0},{name:"notes",label:"What would you like to cover?",type:"textarea"}],submitLabel:"Submit details"},followup:{title:"Additional Information",description:"Provide any extra details to tailor the next steps.",fields:[{name:"company",label:"Company",placeholder:"Acme Inc."},{name:"context",label:"Context",type:"textarea",placeholder:"Share more about your use case"}],submitLabel:"Send"}},Me=(e,n,t,a)=>{let o=e.querySelectorAll("[data-tv-form]");o.length&&o.forEach(l=>{var x,$,ut;if(l.dataset.enhanced==="true")return;let i=(x=l.dataset.tvForm)!=null?x:"init";l.dataset.enhanced="true";let C=($=Tn[i])!=null?$:Tn.init;l.classList.add("tvw-form-card","tvw-space-y-4");let b=u("div","tvw-space-y-1"),T=u("h3","tvw-text-base tvw-font-semibold tvw-text-cw-primary");if(T.textContent=C.title,b.appendChild(T),C.description){let P=u("p","tvw-text-sm tvw-text-cw-muted");P.textContent=C.description,b.appendChild(P)}let v=document.createElement("form");v.className="tvw-form-grid tvw-space-y-3",C.fields.forEach(P=>{var f,O;let _=u("label","tvw-form-field tvw-flex tvw-flex-col tvw-gap-1");_.htmlFor=`${n.id}-${i}-${P.name}`;let ot=u("span","tvw-text-xs tvw-font-medium tvw-text-cw-muted");ot.textContent=P.label,_.appendChild(ot);let it=(f=P.type)!=null?f:"text",M;it==="textarea"?(M=document.createElement("textarea"),M.rows=3):(M=document.createElement("input"),M.type=it),M.className="tvw-rounded-xl tvw-border tvw-border-gray-200 tvw-bg-white tvw-px-3 tvw-py-2 tvw-text-sm tvw-text-cw-primary focus:tvw-outline-none focus:tvw-border-cw-primary",M.id=`${n.id}-${i}-${P.name}`,M.name=P.name,M.placeholder=(O=P.placeholder)!=null?O:"",P.required&&(M.required=!0),_.appendChild(M),v.appendChild(_)});let W=u("div","tvw-flex tvw-items-center tvw-justify-between tvw-gap-2"),w=u("div","tvw-text-xs tvw-text-cw-muted tvw-min-h-[1.5rem]"),z=u("button","tvw-inline-flex tvw-items-center tvw-rounded-full tvw-bg-cw-primary tvw-px-4 tvw-py-2 tvw-text-sm tvw-font-semibold tvw-text-white disabled:tvw-opacity-60 tvw-cursor-pointer");z.type="submit",z.textContent=(ut=C.submitLabel)!=null?ut:"Submit",W.appendChild(w),W.appendChild(z),v.appendChild(W),l.replaceChildren(b,v),v.addEventListener("submit",async P=>{var M,f;P.preventDefault();let _=(M=t.formEndpoint)!=null?M:"/form",ot=new FormData(v),it={};ot.forEach((O,G)=>{it[G]=O}),it.type=i,z.disabled=!0,w.textContent="Submitting\u2026";try{let O=await fetch(_,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(it)});if(!O.ok)throw new Error(`Form submission failed (${O.status})`);let G=await O.json();w.textContent=(f=G.message)!=null?f:"Thanks! We'll be in touch soon.",G.success&&G.nextPrompt&&await a.sendMessage(String(G.nextPrompt))}catch(O){w.textContent=O instanceof Error?O.message:"Something went wrong. Please try again."}finally{z.disabled=!1}})})};var Ee=class{constructor(){this.plugins=new Map}register(n){var t;this.plugins.has(n.id)&&console.warn(`Plugin "${n.id}" is already registered. Overwriting.`),this.plugins.set(n.id,n),(t=n.onRegister)==null||t.call(n)}unregister(n){var a;let t=this.plugins.get(n);t&&((a=t.onUnregister)==null||a.call(t),this.plugins.delete(n))}getAll(){return Array.from(this.plugins.values()).sort((n,t)=>{var a,o;return((a=t.priority)!=null?a:0)-((o=n.priority)!=null?o:0)})}getForInstance(n){let t=this.getAll();if(!n||n.length===0)return t;let a=new Set(n.map(l=>l.id));return[...t.filter(l=>!a.has(l.id)),...n].sort((l,i)=>{var C,b;return((C=i.priority)!=null?C:0)-((b=l.priority)!=null?b:0)})}clear(){this.plugins.forEach(n=>{var t;return(t=n.onUnregister)==null?void 0:t.call(n)}),this.plugins.clear()}},de=new Ee;var Mn=e=>e!=null&&e.postprocessMessage?n=>e.postprocessMessage({text:n.text,message:n.message,streaming:n.streaming}):({text:n})=>ce(n),ue=(e,n)=>{var _t,Vt,Xt,Yt,Kt,g,A,N,V;(!e.id||e.id!=="vanilla-agent-root")&&(e.id="vanilla-agent-root");let t={...n};ve(e,t);let a=de.getForInstance(t.plugins),o=(Vt=(_t=t.launcher)==null?void 0:_t.enabled)!=null?Vt:!0,l=(Yt=(Xt=t.launcher)==null?void 0:Xt.autoExpand)!=null?Yt:!1,i=l,C=o,b=o?l:!0,T=Mn(t),v=(g=(Kt=t.features)==null?void 0:Kt.showReasoning)!=null?g:!0,W=(N=(A=t.features)==null?void 0:A.showToolCalls)!=null?N:!0,w=(V=t.statusIndicator)!=null?V:{},z=s=>{var h,S,c,r;return s==="idle"?(h=w.idleText)!=null?h:ct.idle:s==="connecting"?(S=w.connectingText)!=null?S:ct.connecting:s==="connected"?(c=w.connectedText)!=null?c:ct.connected:s==="error"?(r=w.errorText)!=null?r:ct.error:ct[s]},{wrapper:x,panel:$}=yn(t),ut=bn(t,o),{container:P,body:_,messagesWrapper:ot,suggestions:it,textarea:M,sendButton:f,sendButtonWrapper:O,composerForm:G,statusText:tt,introTitle:J,introSubtitle:B,closeButton:H,iconHolder:U}=ut,y=ut.micButton,R=ut.micButtonWrapper;$.appendChild(P),e.appendChild(x);let wt=[],Mt=Sn(it),ht=null,D,Bt=!1,lt=!0,Et=0,st=0,pt=null,E=!1,Y=0,Dt=!1,q=125,xt=2e3,se=5,Ht=50,At=(s=!1)=>{if(!lt)return;let h=Date.now();E&&h<Y&&!s||(E&&h>=Y&&(E=!1),!(!s&&!Bt)&&(h-st<q||(st=h,pt&&cancelAnimationFrame(pt),pt=requestAnimationFrame(()=>{E||!lt||(Dt=!0,_.scrollTop=_.scrollHeight,Et=_.scrollTop,requestAnimationFrame(()=>{Dt=!1}),pt=null)}))))},re=()=>{let s=document.createElement("div");s.className="tvw-flex tvw-items-center tvw-space-x-1 tvw-h-5";let h=document.createElement("div");h.className="tvw-bg-cw-primary tvw-animate-typing tvw-rounded-full tvw-h-1.5 tvw-w-1.5",h.style.animationDelay="0ms";let S=document.createElement("div");S.className="tvw-bg-cw-primary tvw-animate-typing tvw-rounded-full tvw-h-1.5 tvw-w-1.5",S.style.animationDelay="250ms";let c=document.createElement("div");c.className="tvw-bg-cw-primary tvw-animate-typing tvw-rounded-full tvw-h-1.5 tvw-w-1.5",c.style.animationDelay="500ms";let r=document.createElement("span");return r.className="tvw-sr-only",r.textContent="Loading",s.appendChild(h),s.appendChild(S),s.appendChild(c),s.appendChild(r),s},Rt=(s,h,S)=>{s.innerHTML="";let c=document.createDocumentFragment();if(h.forEach(r=>{let m=null,d=a.find(L=>!!(r.variant==="reasoning"&&L.renderReasoning||r.variant==="tool"&&L.renderToolCall||!r.variant&&L.renderMessage));if(d)if(r.variant==="reasoning"&&r.reasoning&&d.renderReasoning){if(!v)return;m=d.renderReasoning({message:r,defaultRenderer:()=>Ce(r),config:t})}else if(r.variant==="tool"&&r.toolCall&&d.renderToolCall){if(!W)return;m=d.renderToolCall({message:r,defaultRenderer:()=>Te(r),config:t})}else d.renderMessage&&(m=d.renderMessage({message:r,defaultRenderer:()=>{let L=ye(r,S);return r.role!=="user"&&Me(L,r,t,D),L},config:t}));if(!m)if(r.variant==="reasoning"&&r.reasoning){if(!v)return;m=Ce(r)}else if(r.variant==="tool"&&r.toolCall){if(!W)return;m=Te(r)}else m=ye(r,S),r.role!=="user"&&Me(m,r,t,D);let p=document.createElement("div");p.className="tvw-flex",r.role==="user"&&p.classList.add("tvw-justify-end"),p.appendChild(m),c.appendChild(p)}),Bt&&h.some(r=>r.role==="user")){let r=re(),m=document.createElement("div");m.className="tvw-flex tvw-justify-end",m.appendChild(r),c.appendChild(m)}s.appendChild(c),s.scrollTop=s.scrollHeight},It=()=>{o&&(b?(x.classList.remove("tvw-pointer-events-none","tvw-opacity-0"),$.classList.remove("tvw-scale-95","tvw-opacity-0"),$.classList.add("tvw-scale-100","tvw-opacity-100"),j&&(j.element.style.display="none")):(x.classList.add("tvw-pointer-events-none","tvw-opacity-0"),$.classList.remove("tvw-scale-100","tvw-opacity-100"),$.classList.add("tvw-scale-95","tvw-opacity-0"),j&&(j.element.style.display="")))},Ct=s=>{o&&b!==s&&(b=s,It(),b&&(Lt(),At(!0)))},Nt=s=>{M.disabled=s,f.disabled=s,y&&(y.disabled=s),Mt.buttons.forEach(h=>{h.disabled=s})},zt=()=>{var c,r,m,d,p,L,et,Z,F,Q,I,K;J.textContent=(r=(c=t.copy)==null?void 0:c.welcomeTitle)!=null?r:"Hello \u{1F44B}",B.textContent=(d=(m=t.copy)==null?void 0:m.welcomeSubtitle)!=null?d:"Ask anything about your account or products.",M.placeholder=(L=(p=t.copy)==null?void 0:p.inputPlaceholder)!=null?L:"Type your message\u2026",f.textContent=(Z=(et=t.copy)==null?void 0:et.sendButtonLabel)!=null?Z:"Send";let s=(Q=(F=t.theme)==null?void 0:F.inputFontFamily)!=null?Q:"sans-serif",h=(K=(I=t.theme)==null?void 0:I.inputFontWeight)!=null?K:"400",S=yt=>{switch(yt){case"serif":return'Georgia, "Times New Roman", Times, serif';case"mono":return'"Courier New", Courier, "Lucida Console", Monaco, monospace';case"sans-serif":default:return'-apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif'}};M.style.fontFamily=S(s),M.style.fontWeight=h};D=new ae(t,{onMessagesChanged(s){Rt(ot,s,T),D&&(s.some(S=>S.role==="user")?Mt.render([],D,M,s):Mt.render(t.suggestionChips,D,M,s)),At(!Bt)},onStatusChanged(s){var c;let h=(c=t.statusIndicator)!=null?c:{},S=r=>{var m,d,p,L;return r==="idle"?(m=h.idleText)!=null?m:ct.idle:r==="connecting"?(d=h.connectingText)!=null?d:ct.connecting:r==="connected"?(p=h.connectedText)!=null?p:ct.connected:r==="error"?(L=h.errorText)!=null?L:ct.error:ct[r]};tt.textContent=S(s)},onStreamingChanged(s){Bt=s,Nt(s),D&&Rt(ot,D.getMessages(),T),s||At(!0)}});let $t=s=>{s.preventDefault();let h=M.value.trim();h&&(M.value="",D.sendMessage(h))},Pt=s=>{s.key==="Enter"&&!s.shiftKey&&(s.preventDefault(),f.click())},rt=null,mt=!1,St=null,vt=null,Jt=()=>typeof window=="undefined"?null:window.webkitSpeechRecognition||window.SpeechRecognition||null,Zt=()=>{var r,m,d,p;if(mt||D.isStreaming())return;let s=Jt();if(!s)return;rt=new s;let S=(m=((r=t.voiceRecognition)!=null?r:{}).pauseDuration)!=null?m:2e3;rt.continuous=!0,rt.interimResults=!0,rt.lang="en-US";let c=M.value;rt.onresult=L=>{let et="",Z="";for(let Q=0;Q<L.results.length;Q++){let I=L.results[Q],K=I[0].transcript;I.isFinal?et+=K+" ":Z=K}let F=c+et+Z;M.value=F,St&&clearTimeout(St),(et||Z)&&(St=window.setTimeout(()=>{let Q=M.value.trim();Q&&rt&&mt&&(ft(),M.value="",D.sendMessage(Q))},S))},rt.onerror=L=>{L.error!=="no-speech"&&ft()},rt.onend=()=>{if(mt){let L=M.value.trim();L&&L!==c.trim()&&(M.value="",D.sendMessage(L)),ft()}};try{if(rt.start(),mt=!0,y){vt={backgroundColor:y.style.backgroundColor,color:y.style.color,borderColor:y.style.borderColor};let L=(d=t.voiceRecognition)!=null?d:{},et=(p=L.recordingBackgroundColor)!=null?p:"#ef4444",Z=L.recordingIconColor,F=L.recordingBorderColor;if(y.classList.add("tvw-voice-recording"),y.style.backgroundColor=et,Z){y.style.color=Z;let Q=y.querySelector("svg");Q&&Q.setAttribute("stroke",Z)}F&&(y.style.borderColor=F),y.setAttribute("aria-label","Stop voice recognition")}}catch{ft()}},ft=()=>{if(mt){if(mt=!1,St&&(clearTimeout(St),St=null),rt){try{rt.stop()}catch{}rt=null}if(y){if(y.classList.remove("tvw-voice-recording"),vt){y.style.backgroundColor=vt.backgroundColor,y.style.color=vt.color,y.style.borderColor=vt.borderColor;let s=y.querySelector("svg");s&&s.setAttribute("stroke",vt.color||"currentColor"),vt=null}y.setAttribute("aria-label","Start voice recognition")}}},Qt=(s,h)=>{var yt,te,bt,Wt,dt,kt,qt;if(!(typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined")))return null;let c=u("div","tvw-send-button-wrapper"),r=u("button","tvw-rounded-button tvw-flex tvw-items-center tvw-justify-center disabled:tvw-opacity-50 tvw-cursor-pointer");r.type="button",r.setAttribute("aria-label","Start voice recognition");let m=(yt=s==null?void 0:s.iconName)!=null?yt:"mic",d=(te=h==null?void 0:h.size)!=null?te:"40px",p=(bt=s==null?void 0:s.iconSize)!=null?bt:d,L=parseFloat(p)||24,et=(Wt=s==null?void 0:s.backgroundColor)!=null?Wt:h==null?void 0:h.backgroundColor,Z=(dt=s==null?void 0:s.iconColor)!=null?dt:h==null?void 0:h.textColor;r.style.width=p,r.style.height=p,r.style.minWidth=p,r.style.minHeight=p,r.style.fontSize="18px",r.style.lineHeight="1";let F=Z||"currentColor",Q=Tt(m,L,F,1.5);Q?(r.appendChild(Q),r.style.color=F):(r.textContent="\u{1F3A4}",r.style.color=F),et?r.style.backgroundColor=et:r.classList.add("tvw-bg-cw-primary"),Z?r.style.color=Z:!Z&&!(h!=null&&h.textColor)&&r.classList.add("tvw-text-white"),s!=null&&s.borderWidth&&(r.style.borderWidth=s.borderWidth,r.style.borderStyle="solid"),s!=null&&s.borderColor&&(r.style.borderColor=s.borderColor),s!=null&&s.paddingX&&(r.style.paddingLeft=s.paddingX,r.style.paddingRight=s.paddingX),s!=null&&s.paddingY&&(r.style.paddingTop=s.paddingY,r.style.paddingBottom=s.paddingY),c.appendChild(r);let I=(kt=s==null?void 0:s.tooltipText)!=null?kt:"Start voice recognition";if(((qt=s==null?void 0:s.showTooltip)!=null?qt:!1)&&I){let ee=u("div","tvw-send-button-tooltip");ee.textContent=I,c.appendChild(ee)}return{micButton:r,micButtonWrapper:c}},Ft=()=>{if(mt){let s=M.value.trim();ft(),s&&(M.value="",D.sendMessage(s))}else Zt()};y&&(y.addEventListener("click",Ft),wt.push(()=>{ft(),y&&y.removeEventListener("click",Ft)}));let Ot=()=>{Ct(!b)},j=o?fe(t,Ot):null;j&&e.appendChild(j.element),It(),Mt.render(t.suggestionChips,D,M),zt(),Nt(D.isStreaming()),At(!0);let Lt=()=>{var d,p;if(!o){$.style.height="",$.style.width="";return}let s=(p=(d=t==null?void 0:t.launcher)==null?void 0:d.width)!=null?p:t==null?void 0:t.launcherWidth,h=s!=null?s:"min(360px, calc(100vw - 24px))";$.style.width=h,$.style.maxWidth=h;let S=window.innerHeight,r=Math.max(200,S-64),m=Math.min(640,r);$.style.height=`${m}px`};Lt(),window.addEventListener("resize",Lt),wt.push(()=>window.removeEventListener("resize",Lt)),Et=_.scrollTop;let Ut=()=>{let s=_.scrollTop,h=_.scrollHeight,S=_.clientHeight,c=h-s-S,r=Math.abs(s-Et);if(Et=s,!Dt&&!(r<=se)){if(!lt&&c<Ht){E=!1,lt=!0;return}lt&&c>Ht&&(E=!0,Y=Date.now()+xt,lt=!1)}};_.addEventListener("scroll",Ut,{passive:!0}),wt.push(()=>_.removeEventListener("scroll",Ut)),wt.push(()=>{pt&&cancelAnimationFrame(pt)});let jt=()=>{H&&(ht&&(H.removeEventListener("click",ht),ht=null),o?(H.style.display="",ht=()=>{b=!1,It()},H.addEventListener("click",ht)):H.style.display="none")};return jt(),G.addEventListener("submit",$t),M.addEventListener("keydown",Pt),wt.push(()=>{G.removeEventListener("submit",$t),M.removeEventListener("keydown",Pt)}),wt.push(()=>{D.cancel()}),j&&wt.push(()=>{j==null||j.destroy()}),{update(s){var ke,He,Ae,Ie,Be,Re,Ne,Fe,qe,De,ze,$e,Pe,Oe,Ue,je,_e,Ve,Xe,Ye,Ke,Ge,Je,Ze,Qe,tn,en,nn,on,sn,rn,an,ln,dn,cn,un,pn,gn;t={...t,...s},ve(e,t);let h=de.getForInstance(t.plugins);a.length=0,a.push(...h),o=(He=(ke=t.launcher)==null?void 0:ke.enabled)!=null?He:!0,l=(Ie=(Ae=t.launcher)==null?void 0:Ae.autoExpand)!=null?Ie:!1,v=(Re=(Be=t.features)==null?void 0:Be.showReasoning)!=null?Re:!0,W=(Fe=(Ne=t.features)==null?void 0:Ne.showToolCalls)!=null?Fe:!0,((qe=t.launcher)==null?void 0:qe.enabled)===!1&&j&&(j.destroy(),j=null),((De=t.launcher)==null?void 0:De.enabled)!==!1&&!j&&(j=fe(t,Ot),e.appendChild(j.element)),j&&j.update(t),o!==C?o?Ct(l):(b=!0,It()):l!==i&&Ct(l),i=l,C=o,Lt(),jt();let r=(ze=t.launcher)!=null?ze:{},m=($e=r.headerIconHidden)!=null?$e:!1,d=r.headerIconName,p=(Pe=r.headerIconSize)!=null?Pe:"48px";if(U){let k=P.querySelector(".tvw-border-b-cw-divider"),nt=k==null?void 0:k.querySelector(".tvw-flex-col");if(m)U.style.display="none",k&&nt&&!k.contains(nt)&&k.insertBefore(nt,k.firstChild);else{if(U.style.display="",U.style.height=p,U.style.width=p,k&&nt&&(k.contains(U)?U.nextSibling!==nt&&(U.remove(),k.insertBefore(U,nt)):k.insertBefore(U,nt)),d){let gt=parseFloat(p)||24,X=Tt(d,gt*.6,"#ffffff",2);X?U.replaceChildren(X):U.textContent=(Oe=r.agentIconText)!=null?Oe:"\u{1F4AC}"}else if(r.iconUrl){let gt=U.querySelector("img");if(gt)gt.src=r.iconUrl,gt.style.height=p,gt.style.width=p;else{let X=document.createElement("img");X.src=r.iconUrl,X.alt="",X.className="tvw-rounded-xl tvw-object-cover",X.style.height=p,X.style.width=p,U.replaceChildren(X)}}else{let gt=U.querySelector("svg"),X=U.querySelector("img");(gt||X)&&U.replaceChildren(),U.textContent=(Ue=r.agentIconText)!=null?Ue:"\u{1F4AC}"}let at=U.querySelector("img");at&&(at.style.height=p,at.style.width=p)}}if(H){let k=(je=r.closeButtonSize)!=null?je:"32px",nt=(_e=r.closeButtonPlacement)!=null?_e:"inline";H.style.height=k,H.style.width=k;let at=nt==="top-right",gt=H.classList.contains("tvw-absolute");if(at!==gt)if(H.remove(),at)H.className="tvw-absolute tvw-top-4 tvw-right-4 tvw-z-50 tvw-inline-flex tvw-items-center tvw-justify-center tvw-rounded-full tvw-text-cw-muted hover:tvw-bg-gray-100 tvw-cursor-pointer tvw-border-none",P.style.position="relative",P.appendChild(H);else{H.className="tvw-ml-auto tvw-inline-flex tvw-items-center tvw-justify-center tvw-rounded-full tvw-text-cw-muted hover:tvw-bg-gray-100 tvw-cursor-pointer tvw-border-none";let X=P.querySelector(".tvw-border-b-cw-divider");X&&X.appendChild(H)}if(r.closeButtonColor?(H.style.color=r.closeButtonColor,H.classList.remove("tvw-text-cw-muted")):(H.style.color="",H.classList.add("tvw-text-cw-muted")),r.closeButtonBackgroundColor?(H.style.backgroundColor=r.closeButtonBackgroundColor,H.classList.remove("hover:tvw-bg-gray-100")):(H.style.backgroundColor="",H.classList.add("hover:tvw-bg-gray-100")),r.closeButtonBorderWidth||r.closeButtonBorderColor){let X=r.closeButtonBorderWidth||"0px",ie=r.closeButtonBorderColor||"transparent";H.style.border=`${X} solid ${ie}`,H.classList.remove("tvw-border-none")}else H.style.border="",H.classList.add("tvw-border-none");r.closeButtonBorderRadius?(H.style.borderRadius=r.closeButtonBorderRadius,H.classList.remove("tvw-rounded-full")):(H.style.borderRadius="",H.classList.add("tvw-rounded-full"))}T=Mn(t),D.updateConfig(t),Rt(ot,D.getMessages(),T),Mt.render(t.suggestionChips,D,M),zt(),Nt(D.isStreaming());let L=((Ve=t.voiceRecognition)==null?void 0:Ve.enabled)===!0,et=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),Z=L&&et;if(G.classList.remove("tvw-gap-1","tvw-gap-3"),G.classList.add(Z?"tvw-gap-1":"tvw-gap-3"),L&&et)if(!y||!R){let k=Qt(t.voiceRecognition,t.sendButton);k&&(y=k.micButton,R=k.micButtonWrapper,G.insertBefore(R,O),y.addEventListener("click",Ft),y.disabled=D.isStreaming())}else{let k=(Xe=t.voiceRecognition)!=null?Xe:{},nt=(Ye=t.sendButton)!=null?Ye:{},at=(Ke=k.iconName)!=null?Ke:"mic",gt=(Ge=nt.size)!=null?Ge:"40px",X=(Je=k.iconSize)!=null?Je:gt,ie=parseFloat(X)||24;y.style.width=X,y.style.height=X,y.style.minWidth=X,y.style.minHeight=X;let ne=(Qe=(Ze=k.iconColor)!=null?Ze:nt.textColor)!=null?Qe:"currentColor";y.innerHTML="";let wn=Tt(at,ie,ne,2);wn?y.appendChild(wn):y.textContent="\u{1F3A4}";let mn=(tn=k.backgroundColor)!=null?tn:nt.backgroundColor;mn?(y.style.backgroundColor=mn,y.classList.remove("tvw-bg-cw-primary")):(y.style.backgroundColor="",y.classList.add("tvw-bg-cw-primary")),ne?(y.style.color=ne,y.classList.remove("tvw-text-white")):!ne&&!nt.textColor&&(y.style.color="",y.classList.add("tvw-text-white")),k.borderWidth?(y.style.borderWidth=k.borderWidth,y.style.borderStyle="solid"):(y.style.borderWidth="",y.style.borderStyle=""),k.borderColor?y.style.borderColor=k.borderColor:y.style.borderColor="",k.paddingX?(y.style.paddingLeft=k.paddingX,y.style.paddingRight=k.paddingX):(y.style.paddingLeft="",y.style.paddingRight=""),k.paddingY?(y.style.paddingTop=k.paddingY,y.style.paddingBottom=k.paddingY):(y.style.paddingTop="",y.style.paddingBottom="");let le=R==null?void 0:R.querySelector(".tvw-send-button-tooltip"),pe=(en=k.tooltipText)!=null?en:"Start voice recognition";if(((nn=k.showTooltip)!=null?nn:!1)&&pe)if(le)le.textContent=pe,le.style.display="";else{let ge=document.createElement("div");ge.className="tvw-send-button-tooltip",ge.textContent=pe,R==null||R.insertBefore(ge,y)}else le&&(le.style.display="none");R.style.display="",y.disabled=D.isStreaming()}else y&&R&&(R.style.display="none",mt&&ft());let F=(on=t.sendButton)!=null?on:{},Q=(sn=F.useIcon)!=null?sn:!1,I=(rn=F.iconText)!=null?rn:"\u2191",K=F.iconName,yt=(an=F.tooltipText)!=null?an:"Send message",te=(ln=F.showTooltip)!=null?ln:!1,bt=(dn=F.size)!=null?dn:"40px",Wt=F.backgroundColor,dt=F.textColor;if(Q){if(f.style.width=bt,f.style.height=bt,f.style.minWidth=bt,f.style.minHeight=bt,f.style.fontSize="18px",f.style.lineHeight="1",f.innerHTML="",K){let k=parseFloat(bt)||24,nt=dt&&typeof dt=="string"&&dt.trim()?dt.trim():"currentColor",at=Tt(K,k,nt,2);at?(f.appendChild(at),f.style.color=nt):(f.textContent=I,dt?f.style.color=dt:f.classList.add("tvw-text-white"))}else f.textContent=I,dt?f.style.color=dt:f.classList.add("tvw-text-white");f.className="tvw-rounded-button tvw-flex tvw-items-center tvw-justify-center disabled:tvw-opacity-50 tvw-cursor-pointer",Wt?(f.style.backgroundColor=Wt,f.classList.remove("tvw-bg-cw-primary")):f.classList.add("tvw-bg-cw-primary")}else f.textContent=(un=(cn=t.copy)==null?void 0:cn.sendButtonLabel)!=null?un:"Send",f.style.width="",f.style.height="",f.style.minWidth="",f.style.minHeight="",f.style.fontSize="",f.style.lineHeight="",f.className="tvw-rounded-button tvw-bg-cw-accent tvw-px-4 tvw-py-2 tvw-text-sm tvw-font-semibold tvw-text-white disabled:tvw-opacity-50 tvw-cursor-pointer",Wt?(f.style.backgroundColor=Wt,f.classList.remove("tvw-bg-cw-accent")):f.classList.add("tvw-bg-cw-accent"),dt?f.style.color=dt:f.classList.add("tvw-text-white");F.borderWidth?(f.style.borderWidth=F.borderWidth,f.style.borderStyle="solid"):(f.style.borderWidth="",f.style.borderStyle=""),F.borderColor?f.style.borderColor=F.borderColor:f.style.borderColor="",F.paddingX?(f.style.paddingLeft=F.paddingX,f.style.paddingRight=F.paddingX):(f.style.paddingLeft="",f.style.paddingRight=""),F.paddingY?(f.style.paddingTop=F.paddingY,f.style.paddingBottom=F.paddingY):(f.style.paddingTop="",f.style.paddingBottom="");let kt=O==null?void 0:O.querySelector(".tvw-send-button-tooltip");if(te&&yt)if(kt)kt.textContent=yt,kt.style.display="";else{let k=document.createElement("div");k.className="tvw-send-button-tooltip",k.textContent=yt,O==null||O.insertBefore(k,f)}else kt&&(kt.style.display="none");let qt=(pn=t.statusIndicator)!=null?pn:{},ee=(gn=qt.visible)!=null?gn:!0;if(tt.style.display=ee?"":"none",D){let k=D.getStatus(),nt=at=>{var gt,X,ie,ne;return at==="idle"?(gt=qt.idleText)!=null?gt:ct.idle:at==="connecting"?(X=qt.connectingText)!=null?X:ct.connecting:at==="connected"?(ie=qt.connectedText)!=null?ie:ct.connected:at==="error"?(ne=qt.errorText)!=null?ne:ct.error:ct[at]};tt.textContent=nt(k)}},open(){o&&Ct(!0)},close(){o&&Ct(!1)},toggle(){o&&Ct(!b)},destroy(){wt.forEach(s=>s()),x.remove(),j==null||j.destroy(),ht&&H.removeEventListener("click",ht)}}};var Le={},zn=e=>{if(typeof window=="undefined"||typeof document=="undefined")throw new Error("Chat widget can only be mounted in a browser environment");if(typeof e=="string"){let n=document.querySelector(e);if(!n)throw new Error(`Chat widget target "${e}" was not found`);return n}return e},$n=()=>{try{if(typeof Le!="undefined"&&Le.url)return new URL("../widget.css",Le.url).href}catch{}return null},En=e=>{let n=$n();if(e instanceof ShadowRoot){if(n){let t=document.createElement("link");t.rel="stylesheet",t.href=n,t.setAttribute("data-vanilla-agent","true"),e.insertBefore(t,e.firstChild)}}else if(!document.head.querySelector("link[data-vanilla-agent]")&&n){let a=document.createElement("link");a.rel="stylesheet",a.href=n,a.setAttribute("data-vanilla-agent","true"),document.head.appendChild(a)}},We=e=>{var C;let n=zn(e.target),t=document.createElement("div");t.className="vanilla-agent-host",n.appendChild(t);let a=e.useShadowDom!==!1,o,l;if(a){let b=t.attachShadow({mode:"open"});l=b,o=document.createElement("div"),o.id="vanilla-agent-root",b.appendChild(o),En(b)}else l=t,o=document.createElement("div"),o.id="vanilla-agent-root",t.appendChild(o),En(t);let i=ue(o,e.config);return(C=e.onReady)==null||C.call(e),{host:t,update(b){i.update(b)},open(){i.open()},close(){i.close()},toggle(){i.toggle()},destroy(){i.destroy(),t.remove()}}};var Pn=We;0&&(module.exports={ChatWidgetClient,ChatWidgetSession,createChatExperience,directivePostprocessor,escapeHtml,initChatWidget,markdownPostprocessor,pluginRegistry});
|
|
14
|
+
//# sourceMappingURL=index.cjs.map
|