@runtypelabs/persona 3.29.1 → 3.31.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (68) hide show
  1. package/README.md +15 -2547
  2. package/dist/animations/glyph-cycle.d.cts +1 -1
  3. package/dist/animations/glyph-cycle.d.ts +1 -1
  4. package/dist/animations/{types-B_Qazlm4.d.cts → types-quh7NmYD.d.cts} +9 -0
  5. package/dist/animations/{types-B_Qazlm4.d.ts → types-quh7NmYD.d.ts} +9 -0
  6. package/dist/animations/wipe.d.cts +1 -1
  7. package/dist/animations/wipe.d.ts +1 -1
  8. package/dist/codegen.cjs +6 -6
  9. package/dist/codegen.js +4 -4
  10. package/dist/index.cjs +50 -50
  11. package/dist/index.cjs.map +1 -1
  12. package/dist/index.d.cts +164 -7
  13. package/dist/index.d.ts +164 -7
  14. package/dist/index.global.js +60 -60
  15. package/dist/index.global.js.map +1 -1
  16. package/dist/index.js +49 -49
  17. package/dist/index.js.map +1 -1
  18. package/dist/launcher.global.js +2 -2
  19. package/dist/launcher.global.js.map +1 -1
  20. package/dist/plugin-kit.cjs +1 -0
  21. package/dist/plugin-kit.d.cts +98 -0
  22. package/dist/plugin-kit.d.ts +98 -0
  23. package/dist/plugin-kit.js +1 -0
  24. package/dist/smart-dom-reader.d.cts +157 -4
  25. package/dist/smart-dom-reader.d.ts +157 -4
  26. package/dist/theme-editor.cjs +40 -40
  27. package/dist/theme-editor.d.cts +161 -6
  28. package/dist/theme-editor.d.ts +161 -6
  29. package/dist/theme-editor.js +40 -40
  30. package/dist/theme-reference.cjs +1 -1
  31. package/dist/theme-reference.d.cts +2 -0
  32. package/dist/theme-reference.d.ts +2 -0
  33. package/dist/theme-reference.js +1 -1
  34. package/dist/widget.css +19 -0
  35. package/package.json +8 -2
  36. package/src/client.ts +6 -0
  37. package/src/components/approval-bubble.test.ts +320 -0
  38. package/src/components/approval-bubble.ts +190 -20
  39. package/src/components/launcher.ts +6 -3
  40. package/src/components/panel.ts +7 -1
  41. package/src/components/tool-bubble.test.ts +39 -0
  42. package/src/components/tool-bubble.ts +4 -0
  43. package/src/defaults.ts +14 -0
  44. package/src/generated/runtype-openapi-contract.ts +4 -0
  45. package/src/index-core.ts +1 -0
  46. package/src/plugin-kit.test.ts +230 -0
  47. package/src/plugin-kit.ts +294 -0
  48. package/src/plugins/types.ts +49 -2
  49. package/src/session.test.ts +161 -0
  50. package/src/session.ts +41 -3
  51. package/src/styles/widget.css +19 -0
  52. package/src/theme-editor/preview-utils.test.ts +10 -0
  53. package/src/theme-editor/preview-utils.ts +29 -1
  54. package/src/theme-editor/sections.test.ts +17 -0
  55. package/src/theme-editor/sections.ts +31 -0
  56. package/src/theme-reference.ts +2 -2
  57. package/src/types/theme.ts +2 -0
  58. package/src/types.ts +109 -2
  59. package/src/ui.approval-plugin.test.ts +204 -0
  60. package/src/ui.scroll.test.ts +383 -0
  61. package/src/ui.ts +539 -56
  62. package/src/utils/auto-follow.test.ts +91 -0
  63. package/src/utils/auto-follow.ts +68 -0
  64. package/src/utils/theme.test.ts +6 -2
  65. package/src/utils/theme.ts +0 -8
  66. package/src/utils/tokens.ts +6 -1
  67. package/src/webmcp-bridge.test.ts +66 -0
  68. package/src/webmcp-bridge.ts +49 -0
package/README.md CHANGED
@@ -38,8 +38,7 @@ createAgentExperience(inlineHost, {
38
38
  apiUrl: proxyUrl,
39
39
  launcher: { enabled: false },
40
40
  theme: {
41
- ...DEFAULT_WIDGET_CONFIG.theme,
42
- accent: '#2563eb'
41
+ semantic: { colors: { accent: '#2563eb' } }
43
42
  },
44
43
  suggestionChips: ['What can you do?', 'Show API docs'],
45
44
  postprocessMessage: ({ text }) => markdownPostprocessor(text)
@@ -62,7 +61,9 @@ const controller = initAgentWidget({
62
61
 
63
62
  // Runtime theme update
64
63
  document.querySelector('#dark-mode')?.addEventListener('click', () => {
65
- controller.update({ theme: { surface: '#0f172a', primary: '#f8fafc' } });
64
+ controller.update({
65
+ theme: { semantic: { colors: { surface: '#0f172a', primary: '#f8fafc' } } }
66
+ });
66
67
  });
67
68
 
68
69
  // Docked panel that wraps a concrete workspace container
@@ -90,7 +91,7 @@ const docked = initAgentWidget({
90
91
  | Option | Type | Description |
91
92
  | --- | --- | --- |
92
93
  | `target` | `string \| HTMLElement` | CSS selector or element where widget mounts. |
93
- | `config` | `AgentWidgetConfig` | Widget configuration object (see [Configuration reference](#configuration-reference) below). |
94
+ | `config` | `AgentWidgetConfig` | Widget configuration object (see the [Configuration Reference](./docs/CONFIGURATION-REFERENCE.md)). |
94
95
  | `useShadowDom` | `boolean` | Use Shadow DOM for style isolation (default: `true`). |
95
96
  | `onChatReady` | `() => void` | Callback fired when the widget is initialized and its API is callable. |
96
97
  | `onReady` | `() => void` | **Deprecated** alias of `onChatReady`; still works, removed in the next major. |
@@ -106,2551 +107,18 @@ With **`dock.reveal: 'resize'`** (default), a **closed** dock uses a **`0px`** c
106
107
 
107
108
  > **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.
108
109
 
110
+ ### Documentation
109
111
 
110
- ### Programmatic control
111
-
112
- `initAgentWidget` (and `createAgentExperience`) return a controller with methods to programmatically control the widget.
113
-
114
- #### Basic controls
115
-
116
- ```ts
117
- const chat = initAgentWidget({
118
- target: '#launcher-root',
119
- config: { /* ... */ }
120
- })
121
-
122
- document.getElementById('open-chat')?.addEventListener('click', () => chat.open())
123
- document.getElementById('toggle-chat')?.addEventListener('click', () => chat.toggle())
124
- document.getElementById('close-chat')?.addEventListener('click', () => chat.close())
125
- ```
126
-
127
- #### Message hooks
128
-
129
- You can programmatically set messages, submit messages, and control voice recognition:
130
-
131
- ```ts
132
- const chat = initAgentWidget({
133
- target: '#launcher-root',
134
- config: { /* ... */ }
135
- })
136
-
137
- // Set a message in the input field (doesn't submit)
138
- chat.setMessage("Hello, I need help")
139
-
140
- // Submit a message (uses textarea value if no argument provided)
141
- chat.submitMessage()
142
- // Or submit a specific message
143
- chat.submitMessage("What are your hours?")
144
-
145
- // Start voice recognition
146
- chat.startVoiceRecognition()
147
-
148
- // Stop voice recognition
149
- chat.stopVoiceRecognition()
150
- ```
151
-
152
- All hook methods return `boolean` indicating success (`true`) or failure (`false`). They will automatically open the widget if it's currently closed (when launcher is enabled).
153
-
154
- #### Clear chat
155
-
156
- ```ts
157
- const chat = initAgentWidget({
158
- target: '#launcher-root',
159
- config: { /* ... */ }
160
- })
161
-
162
- // Clear all messages programmatically
163
- chat.clearChat()
164
- ```
165
-
166
- #### Message Injection
167
-
168
- Inject messages programmatically from external sources like tool call responses, system events, or third-party integrations. This is useful when local tools need to push results back into the conversation.
169
-
170
- ```ts
171
- const chat = initAgentWidget({
172
- target: '#launcher-root',
173
- config: { /* ... */ }
174
- })
175
-
176
- // Simple message injection
177
- chat.injectAssistantMessage({
178
- content: 'Here are your search results...'
179
- });
180
-
181
- // User message injection
182
- chat.injectUserMessage({
183
- content: 'Add to cart'
184
- });
185
-
186
- // System context injection
187
- chat.injectSystemMessage({
188
- content: '[Context updated]',
189
- llmContent: 'User is viewing product page for iPhone 15 Pro'
190
- });
191
- ```
192
-
193
- **Dual-Content Messages (llmContent)**
194
-
195
- Use `llmContent` to show different content to the user versus what gets sent to the LLM. This is useful for:
196
- - **Token efficiency**: Show rich content to users while sending concise summaries to the LLM
197
- - **Sensitive data redaction**: Display PII to users while hiding it from the LLM
198
- - **Context injection**: Provide detailed LLM context with minimal UI footprint
199
-
200
- ```ts
201
- // Example: Tool callback that injects search results
202
- async function handleProductSearch(query: string) {
203
- const results = await searchProducts(query);
204
-
205
- // User sees full product details with images and prices
206
- // LLM receives a concise summary to save tokens
207
- chat.injectAssistantMessage({
208
- content: `**Found ${results.length} products:**
209
- ${results.map(p => `- ${p.name} - $${p.price} (SKU: ${p.sku})`).join('\n')}`,
210
-
211
- llmContent: `[Search results: ${results.length} products found, price range $${results.minPrice}-$${results.maxPrice}]`
212
- });
213
- }
214
-
215
- // Example: Redacting sensitive information
216
- chat.injectAssistantMessage({
217
- // User sees their order confirmation with details
218
- content: `Your order #12345 has been placed!
219
- - Card ending in 4242
220
- - Shipping to: 123 Main St, Anytown, USA`,
221
-
222
- // LLM only knows an order was placed (no PII)
223
- llmContent: '[Order confirmation displayed to user]'
224
- });
225
- ```
226
-
227
- **Content Priority**
228
-
229
- When messages are sent to the API, content is resolved in this priority order:
230
- 1. `contentParts` - Multi-modal content (images, files)
231
- 2. `llmContent` - Explicit LLM-specific content
232
- 3. `content` - Display content as fallback
233
-
234
- **Streaming Updates**
235
-
236
- For long-running operations, use the same message ID to update content:
237
-
238
- ```ts
239
- const messageId = 'search-123';
240
-
241
- // Show loading state
242
- chat.injectAssistantMessage({
243
- id: messageId,
244
- content: 'Searching...',
245
- streaming: true
246
- });
247
-
248
- // Update with results
249
- chat.injectAssistantMessage({
250
- id: messageId,
251
- content: 'Found 5 results...',
252
- llmContent: '[5 search results]',
253
- streaming: false
254
- });
255
- ```
256
-
257
- **Component Directives (`injectComponentDirective`)**
258
-
259
- When you've registered a custom component via `componentRegistry.register(...)`, inject an assistant message that renders that component using the same path Persona uses for streamed JSON directives:
260
-
261
- ```ts
262
- import { componentRegistry } from '@runtypelabs/persona';
263
- import { DynamicForm } from './components';
264
-
265
- componentRegistry.register('DynamicForm', DynamicForm);
266
-
267
- chat.injectComponentDirective({
268
- component: 'DynamicForm',
269
- props: {
270
- title: 'Book a demo',
271
- fields: [
272
- { label: 'Name', type: 'text', required: true },
273
- { label: 'Email', type: 'email', required: true }
274
- ],
275
- submit_text: 'Request meeting'
276
- },
277
- text: 'Share your details to book a demo.',
278
- llmContent: '[Showed booking form]' // optional, redacted version for the LLM
279
- });
280
- ```
281
-
282
- The helper sets `content` to `text`, `rawContent` to the canonical directive JSON, and forwards `llmContent`. Useful for previews, replays, debug buttons, and local tools that should render a component instead of plain text.
283
-
284
- If you already have a serialized directive, you can pass it through `rawContent` directly on any inject method:
285
-
286
- ```ts
287
- chat.injectAssistantMessage({
288
- content: 'Booking form',
289
- rawContent: JSON.stringify({
290
- text: 'Booking form',
291
- component: 'DynamicForm',
292
- props: { /* ... */ }
293
- }),
294
- llmContent: '[Showed booking form]'
295
- });
296
- ```
297
-
298
- See [docs/MESSAGE-INJECTION.md](./docs/MESSAGE-INJECTION.md#component-directive-injection) for the full reference.
299
-
300
- #### Event Stream Control
301
-
302
- When the `showEventStreamToggle` feature flag is enabled, you can programmatically control the event stream inspector panel:
303
-
304
- ```ts
305
- const chat = initAgentWidget({
306
- target: '#launcher-root',
307
- config: {
308
- apiUrl: '/api/chat/dispatch',
309
- features: { showEventStreamToggle: true }
310
- }
311
- })
312
-
313
- // Open the event stream panel
314
- chat.showEventStream()
315
-
316
- // Close the event stream panel
317
- chat.hideEventStream()
318
-
319
- // Check if the event stream panel is currently visible
320
- chat.isEventStreamVisible() // returns boolean
321
- ```
322
-
323
- These methods are no-ops if `showEventStreamToggle` is not enabled.
324
-
325
- #### Input focus control
326
-
327
- Focus the chat input programmatically:
328
-
329
- ```ts
330
- const chat = initAgentWidget({
331
- target: '#chat-root',
332
- config: { apiUrl: '/api/chat/dispatch' }
333
- })
334
-
335
- // Focus the input (returns true if successful, false if panel is closed or unavailable)
336
- chat.focusInput()
337
- ```
338
-
339
- In launcher mode, `focusInput()` returns `false` when the panel is closed and does not auto-open it. Use `chat.open()` first if you want to open and focus in one flow.
340
-
341
- #### Accessing from window
342
-
343
- To access the controller globally (e.g., from browser console or external scripts), use the `windowKey` option:
344
-
345
- ```ts
346
- const chat = initAgentWidget({
347
- target: '#launcher-root',
348
- windowKey: 'chatController', // Stores controller on window.chatController
349
- config: { /* ... */ }
350
- })
351
-
352
- // Now accessible globally
353
- window.chatController.setMessage("Hello from console!")
354
- window.chatController.submitMessage("Test message")
355
- window.chatController.startVoiceRecognition()
356
- ```
357
-
358
- When using the automatic installer script (`install.global.js`), see [Programmatic access with the installer](#programmatic-access-with-the-installer) for additional approaches including the `onChatReady` callback and `persona:chat-ready` event.
359
-
360
- #### Message Types
361
-
362
- The widget uses `AgentWidgetMessage` objects to represent messages in the conversation. You can access these through `postprocessMessage` callbacks or by inspecting the session's message array.
363
-
364
- ```typescript
365
- type AgentWidgetMessage = {
366
- id: string; // Unique message identifier
367
- role: "user" | "assistant" | "system";
368
- content: string; // Message text content
369
- createdAt: string; // ISO timestamp
370
- streaming?: boolean; // Whether message is still streaming
371
- variant?: "assistant" | "reasoning" | "tool";
372
- sequence?: number; // Message ordering
373
- reasoning?: AgentWidgetReasoning;
374
- toolCall?: AgentWidgetToolCall;
375
- tools?: AgentWidgetToolCall[];
376
- viaVoice?: boolean; // Indicates if user message was sent via voice input
377
- };
378
- ```
379
-
380
- **`viaVoice` field**: Set to `true` when a user message is sent through voice recognition. This allows you to implement voice-specific behaviors, such as automatically reactivating voice recognition after assistant responses. You can check this field in your `postprocessMessage` callback:
381
-
382
- ```ts
383
- postprocessMessage: ({ message, text, streaming }) => {
384
- if (message.role === 'user' && message.viaVoice) {
385
- console.log('User sent message via voice');
386
- }
387
- return text;
388
- }
389
- ```
390
-
391
- Alternatively, manually assign the controller:
392
-
393
- ```ts
394
- const chat = initAgentWidget({ /* ... */ })
395
- window.chatController = chat
396
- ```
397
-
398
- ### Enriched DOM context
399
-
400
- Use `collectEnrichedPageContext` and `formatEnrichedContext` to summarize the visible page for tools or metadata (selectors, roles, text, and optional structured card summaries). By default the collector runs in **structured** mode: it gathers candidates, scores them with built-in `ParseRule` definitions in `defaultParseRules` (product/result-style cards), suppresses redundant descendants, then applies `maxElements`. Pass `options: { mode: "simple" }` for the legacy path (traverse with an early cap only, no rules or `formattedSummary`).
401
-
402
- ```ts
403
- import {
404
- collectEnrichedPageContext,
405
- formatEnrichedContext,
406
- defaultParseRules
407
- } from '@runtypelabs/persona';
408
-
409
- const elements = collectEnrichedPageContext({
410
- options: {
411
- mode: 'structured',
412
- maxElements: 80,
413
- excludeSelector: '.persona-host',
414
- maxTextLength: 200,
415
- visibleOnly: true
416
- },
417
- rules: defaultParseRules
418
- });
419
-
420
- const pageContext = formatEnrichedContext(elements);
421
- // Structured mode: "Structured summaries:" blocks for matched cards, then grouped interactivity sections.
422
- ```
423
-
424
- - Omit both `options` and `rules` → structured defaults (`defaultParseRules`, sensible limits).
425
- - `options: { mode: 'structured' }` → explicit structured behavior (same as default).
426
- - `rules: [...]` → custom rules with default options.
427
- - `options: { mode: 'simple' }` → no relation-based scoring or rule-owned formatting. If you also pass `rules`, they are ignored and a console warning is emitted.
428
-
429
- Pass `formatEnrichedContext(elements, { mode: 'simple' })` to ignore any `formattedSummary` fields on elements (for example when re-formatting data collected earlier).
430
-
431
- **Where things live:** `defaultParseRules` and the rule/config types are part of the public package API — import them from `@runtypelabs/persona` (same entry as `collectEnrichedPageContext`). Exported names you will use most often:
432
-
433
- | Export | Role |
434
- | --- | --- |
435
- | `defaultParseRules` | Built-in `ParseRule[]` (commerce-style cards + generic result rows). |
436
- | `ParseRule` | Type for a custom rule: `id`, `scoreElement`, optional `shouldSuppressDescendant`, optional `formatSummary`. |
437
- | `RuleScoringContext` | Argument to rule hooks (`doc`, `maxTextLength`). |
438
- | `ParseOptionsConfig` | `mode`, `maxElements`, `maxCandidates`, `excludeSelector`, `maxTextLength`, `visibleOnly`, `root`. |
439
- | `DomContextOptions` | What you pass to `collectEnrichedPageContext` (`options`, `rules`, plus legacy top-level limits). |
440
- | `FormatEnrichedContextOptions` | Second argument to `formatEnrichedContext` (`mode`). |
441
- | `EnrichedPageElement` | One collected node; optional `formattedSummary` in structured mode. |
442
-
443
- Use **Go to definition** (or open `node_modules/@runtypelabs/persona/dist/index.d.ts` after install) for the authoritative field list and JSDoc. Implementation source in this repo: `packages/widget/src/utils/dom-context.ts`.
444
-
445
- Custom rule sketch:
446
-
447
- ```ts
448
- import type { ParseRule } from '@runtypelabs/persona';
449
-
450
- const myRules: ParseRule[] = [
451
- {
452
- id: 'kpi-tile',
453
- scoreElement: (el, enriched, ctx) =>
454
- el.classList.contains('kpi-tile') ? 2000 : 0,
455
- formatSummary: (el, enriched, ctx) =>
456
- el.classList.contains('kpi-tile')
457
- ? `${enriched.text.trim()}\nselector: ${enriched.selector}`
458
- : null
459
- }
460
- ];
461
- ```
462
-
463
- #### Optional: smart-dom-reader provider
464
-
465
- The default reader above is a zero-dependency `TreeWalker` and **does not pierce shadow
466
- DOM**. For pages built from web components, an optional provider backed by a
467
- vendored copy of [`@mcp-b/smart-dom-reader`](https://github.com/WebMCP-org/npm-packages/tree/main/packages/smart-dom-reader)
468
- ships as a **separate entry point**, `@runtypelabs/persona/smart-dom-reader`. It is **not**
469
- imported by the main bundle, so consumers who never import this subpath pay nothing — no
470
- extra install, no bundle weight, no IIFE/CDN impact.
471
-
472
- It adds, over the default reader: **Shadow-DOM piercing**, form grouping, and page
473
- landmarks/state — while still emitting Persona's `EnrichedPageElement[]` shape so it
474
- formats and flows through the same pipeline.
475
-
476
- ```ts
477
- import initAgentWidget from '@runtypelabs/persona';
478
- import { createSmartDomReaderContextProvider } from '@runtypelabs/persona/smart-dom-reader';
479
-
480
- initAgentWidget({
481
- // ...config
482
- contextProviders: [
483
- createSmartDomReaderContextProvider({
484
- // 'interactive' (default) | 'full' — full adds semantic content AND is required
485
- // for shadow-DOM piercing (shadow descendants surface only in full mode).
486
- mode: 'full',
487
- contextKey: 'pageContext', // key under payload.context (default)
488
- // root: document.querySelector('main') // optional: scope to a subtree, skip chrome
489
- })
490
- ]
491
- });
492
- ```
493
-
494
- `contextProviders` are honored on the **agent** send path (`buildAgentPayload` merges each
495
- provider's result into `payload.context` on every request). If you drive the legacy
496
- flow/`buildPayload` path, call `collectSmartDomContext()` yourself and inject the result.
497
-
498
- You can also use the pieces directly:
499
-
500
- ```ts
501
- import {
502
- collectSmartDomContext, // → EnrichedPageElement[] (parity with collectEnrichedPageContext)
503
- smartDomResultToEnriched // pure mapper: SmartDOMResult → EnrichedPageElement[]
504
- } from '@runtypelabs/persona/smart-dom-reader';
505
- import { formatEnrichedContext } from '@runtypelabs/persona';
506
-
507
- const pageContext = formatEnrichedContext(collectSmartDomContext({ mode: 'full' }));
508
- ```
509
-
510
- Both `collectSmartDomContext()` and `createSmartDomReaderContextProvider()` accept a
511
- `root` element to scope extraction to a subtree (parity with `collectEnrichedPageContext`'s
512
- `root`) — useful to read only your main content region and skip nav/sidebars. Shadow DOM
513
- inside the subtree is still pierced.
514
-
515
- > **Actionability caveat.** Persona's click loop (`utils/actions.ts`) drives
516
- > `document.querySelector`, which cannot pierce shadow roots or evaluate XPath. The adapter
517
- > therefore prefers plain-CSS selectors; elements reachable only via shadow-piercing or
518
- > XPath selectors are surfaced to the model as **context only** and are **not clickable**
519
- > through the current `message_and_click` handler.
520
-
521
- > **Why vendored, not a dependency.** Every published version of `@mcp-b/smart-dom-reader`
522
- > (2.3.1–3.0.0) is mis-published — its `package.json` points to `dist/index.js` /
523
- > `dist/index.d.ts` while the build only ships `.mjs` / `.d.mts`, so it cannot be imported
524
- > by name in Node or any bundler. The library (MIT, zero-dep) is therefore vendored under
525
- > `packages/widget/src/vendor/smart-dom-reader/`; see that directory's `README.md` for
526
- > provenance and update steps. Once upstream republishes correctly this can revert to a
527
- > normal optional peer dependency.
528
-
529
- ### WebMCP page tools
530
-
531
- When `webmcp: { enabled: true }` is set, the widget consumes tools the page
532
- registers on `document.modelContext` (the [WebMCP](https://github.com/webmachinelearning/webmcp)
533
- producer surface), snapshots them into each request as `clientTools[]`, runs the
534
- agent's calls on the page, and gates each behind a confirm bubble (override with
535
- `autoApprove` / `onConfirm`).
536
-
537
- ```ts
538
- initAgentWidget({
539
- // ...config
540
- webmcp: {
541
- enabled: true,
542
- autoApprove: (info) => READ_ONLY_TOOLS.has(info.toolName),
543
- },
544
- });
545
- ```
546
-
547
- **Using WebMCP against a non-Runtype backend (e.g. the Vercel AI SDK)?** The
548
- widget's WebMCP loop expects Runtype's proxy wire protocol (a `step_await` pause
549
- → `/resume` round-trip). See
550
- [`docs/webmcp-without-runtype.md`](../../docs/webmcp-without-runtype.md) for the
551
- exact contract and two integration paths, with a runnable Next.js example at
552
- [`examples/ai-sdk-webmcp/`](../../examples/ai-sdk-webmcp/).
553
-
554
- ### DOM Events
555
-
556
- The widget dispatches custom DOM events that you can listen to for integration with your application:
557
-
558
- #### `persona:clear-chat`
559
-
560
- Dispatched when the user clicks the "Clear chat" button or when `chat.clearChat()` is called programmatically.
561
-
562
- ```ts
563
- window.addEventListener("persona:clear-chat", (event) => {
564
- console.log("Chat cleared at:", event.detail.timestamp);
565
- // Clear your localStorage, reset state, etc.
566
- });
567
- ```
568
-
569
- **Event detail:**
570
- - `timestamp`: ISO timestamp string of when the chat was cleared
571
-
572
- **Use cases:**
573
- - Clear localStorage chat history
574
- - Reset application state
575
- - Track analytics events
576
- - Sync with backend
577
-
578
- **Note:** The widget automatically clears the `"persona-chat-history"` localStorage key by default when chat is cleared. If you set `clearChatHistoryStorageKey` in the config, it will also clear that additional key. You can still listen to this event for additional custom behavior.
579
-
580
- #### `persona:showEventStream` / `persona:hideEventStream`
581
-
582
- Dispatched to programmatically open or close the event stream panel. Requires `showEventStreamToggle: true` in the widget config.
583
-
584
- ```ts
585
- // Open the event stream panel on all widget instances
586
- window.dispatchEvent(new CustomEvent('persona:showEventStream'))
587
-
588
- // Close the event stream panel on all widget instances
589
- window.dispatchEvent(new CustomEvent('persona:hideEventStream'))
590
- ```
591
-
592
- **Instance scoping:** When multiple widget instances exist on the same page, use the `instanceId` detail to target a specific one. For `createAgentExperience`, the `instanceId` is the original `id` of the mount element. For `initAgentWidget`, it's the `id` of the target element.
593
-
594
- ```ts
595
- // Target only the widget mounted on #inline-widget
596
- window.dispatchEvent(new CustomEvent('persona:showEventStream', {
597
- detail: { instanceId: 'inline-widget' }
598
- }))
599
-
600
- // Events with a non-matching instanceId are ignored
601
- window.dispatchEvent(new CustomEvent('persona:showEventStream', {
602
- detail: { instanceId: 'wrong-id' }
603
- }))
604
- // ^ No effect — no widget has this instanceId
605
- ```
606
-
607
- #### `persona:focusInput`
608
-
609
- Dispatched to programmatically focus the chat input on a widget instance.
610
-
611
- ```ts
612
- // Focus input on all widget instances
613
- window.dispatchEvent(new CustomEvent('persona:focusInput'))
614
-
615
- // Focus input on a specific instance
616
- window.dispatchEvent(new CustomEvent('persona:focusInput', {
617
- detail: { instanceId: 'inline-widget' }
618
- }))
619
- ```
620
-
621
- **Instance scoping:** Same as `persona:showEventStream` — use `detail.instanceId` to target a specific widget. Without `instanceId`, all instances receive the event.
622
-
623
- #### `persona:chat-ready`
624
-
625
- Dispatched on `window` by the automatic installer script (`install.global.js`) when the widget is initialized and its controller API is callable. The `event.detail` contains the `AgentWidgetInitHandle` (the same object returned by `initAgentWidget()`). In a deferred install (the default floating-launcher case) this fires after the user first opens the panel; in an eager install it fires on page load.
626
-
627
- ```ts
628
- window.addEventListener('persona:chat-ready', (e) => {
629
- const handle = e.detail;
630
- handle.on('message:sent', (msg) => console.log(msg));
631
- handle.open();
632
- });
633
- ```
634
-
635
- The installer also dispatches sibling lifecycle events for diagnostics and analytics:
636
-
637
- | Event | `detail` | Fires |
638
- | --- | --- | --- |
639
- | `persona:script-load` | `{ version }` | the installer script executed (before any loading) |
640
- | `persona:launcher-shown` | `{ deferred, element? }` | the floating launcher painted on the page (page-load time) |
641
- | `persona:chat-ready` | the widget handle | the widget is initialized and its API is callable |
642
- | `persona:error` | `{ phase, error }` | a load step (`css` / `bundle` / `init`) failed |
643
-
644
- > **Note:** These events are only dispatched by the automatic installer script. Direct calls to `initAgentWidget()` return the handle synchronously and do not fire them.
645
- >
646
- > `persona:ready` is still dispatched as a **deprecated** alias of `persona:chat-ready` and will be removed in the next major.
647
-
648
- ### Controller Events
649
-
650
- The widget controller exposes an event system for reacting to chat events. Use `controller.on(eventName, callback)` to subscribe and `controller.off(eventName, callback)` to unsubscribe.
651
-
652
- #### Available Events
653
-
654
- | Event | Payload | Description |
655
- |-------|---------|-------------|
656
- | `user:message` | `AgentWidgetMessage` | Emitted when a new user message is detected. Includes `viaVoice: true` if sent via voice. |
657
- | `assistant:message` | `AgentWidgetMessage` | Emitted when an assistant message starts streaming |
658
- | `assistant:complete` | `AgentWidgetMessage` | Emitted when an assistant message finishes streaming |
659
- | `voice:state` | `AgentWidgetVoiceStateEvent` | Emitted when voice recognition state changes |
660
- | `action:detected` | `AgentWidgetActionEventPayload` | Emitted when an action is parsed from an assistant message |
661
- | `widget:opened` | `AgentWidgetStateEvent` | Emitted when the widget panel opens |
662
- | `widget:closed` | `AgentWidgetStateEvent` | Emitted when the widget panel closes |
663
- | `widget:state` | `AgentWidgetStateSnapshot` | Emitted on any widget state change |
664
- | `message:feedback` | `AgentWidgetMessageFeedback` | Emitted when user provides feedback (upvote/downvote) |
665
- | `message:copy` | `AgentWidgetMessage` | Emitted when user copies a message |
666
- | `eventStream:opened` | `{ timestamp: number }` | Emitted when the event stream panel opens |
667
- | `eventStream:closed` | `{ timestamp: number }` | Emitted when the event stream panel closes |
668
-
669
- #### Event Payload Types
670
-
671
- ```typescript
672
- // Voice state event
673
- type AgentWidgetVoiceStateEvent = {
674
- active: boolean;
675
- source: "user" | "auto" | "restore" | "system";
676
- timestamp: number;
677
- };
678
-
679
- // Widget state event (for opened/closed)
680
- type AgentWidgetStateEvent = {
681
- open: boolean;
682
- source: "user" | "auto" | "api" | "system";
683
- timestamp: number;
684
- };
685
-
686
- // Widget state snapshot
687
- type AgentWidgetStateSnapshot = {
688
- open: boolean;
689
- launcherEnabled: boolean;
690
- voiceActive: boolean;
691
- streaming: boolean;
692
- };
693
-
694
- // Action event payload
695
- type AgentWidgetActionEventPayload = {
696
- action: AgentWidgetParsedAction;
697
- message: AgentWidgetMessage;
698
- };
699
-
700
- // Message feedback
701
- type AgentWidgetMessageFeedback = {
702
- type: "upvote" | "downvote";
703
- messageId: string;
704
- message: AgentWidgetMessage;
705
- };
706
- ```
707
-
708
- #### Example: Listening to Events
709
-
710
- ```ts
711
- const chat = initAgentWidget({
712
- target: 'body',
713
- config: { apiUrl: '/api/chat/dispatch' }
714
- });
715
-
716
- // Listen for new user messages
717
- chat.on('user:message', (message) => {
718
- console.log('User sent:', message.content);
719
- if (message.viaVoice) {
720
- console.log('Message was sent via voice recognition');
721
- }
722
- });
723
-
724
- // Listen for completed assistant responses
725
- chat.on('assistant:complete', (message) => {
726
- console.log('Assistant replied:', message.content);
727
- });
728
-
729
- // Listen for voice state changes
730
- chat.on('voice:state', (event) => {
731
- console.log('Voice active:', event.active, 'Source:', event.source);
732
- });
733
-
734
- // Listen for widget open/close
735
- chat.on('widget:opened', (event) => {
736
- console.log('Widget opened by:', event.source);
737
- });
738
-
739
- chat.on('widget:closed', (event) => {
740
- console.log('Widget closed by:', event.source);
741
- });
742
-
743
- // Listen for parsed actions from assistant messages
744
- chat.on('action:detected', ({ action, message }) => {
745
- console.log('Action detected:', action.type, action.payload);
746
- });
747
- ```
748
-
749
- #### Example: Voice Mode Persistence
750
-
751
- The `user:message` event is useful for implementing custom voice mode persistence across page navigations:
752
-
753
- ```ts
754
- const chat = initAgentWidget({
755
- target: 'body',
756
- config: {
757
- apiUrl: '/api/chat/dispatch',
758
- voiceRecognition: { enabled: true }
759
- }
760
- });
761
-
762
- // Track if the user is in "voice mode"
763
- chat.on('user:message', (message) => {
764
- localStorage.setItem('voice-mode', message.viaVoice ? 'true' : 'false');
765
- });
766
-
767
- // On page load, restore voice mode if the user was using voice
768
- if (localStorage.getItem('voice-mode') === 'true') {
769
- chat.startVoiceRecognition();
770
- }
771
- ```
772
-
773
- Note: The built-in `persistState` option handles this automatically when configured:
774
-
775
- ```ts
776
- initAgentWidget({
777
- target: 'body',
778
- config: {
779
- persistState: true, // Automatically persists open state and voice mode
780
- voiceRecognition: { enabled: true, autoResume: 'assistant' }
781
- }
782
- });
783
- ```
784
-
785
- ### State Loaded Hook
786
-
787
- The `onStateLoaded` hook is called after state is loaded from the storage adapter, but before the widget initializes. Use this to transform or inject messages based on external state (e.g., navigation flags, checkout returns).
788
-
789
- Returning `{ state, open: true }` also tells the widget to open the panel after initialization — useful when injecting a post-navigation message that the user should immediately see.
790
-
791
- ```ts
792
- // Plain state transform
793
- initAgentWidget({
794
- target: 'body',
795
- config: {
796
- storageAdapter: createLocalStorageAdapter('my-chat'),
797
- onStateLoaded: (state) => {
798
- const navMessage = consumeNavigationFlag();
799
- if (navMessage) {
800
- return {
801
- ...state,
802
- messages: [...(state.messages || []), {
803
- id: `nav-${Date.now()}`,
804
- role: 'assistant',
805
- content: navMessage,
806
- createdAt: new Date().toISOString()
807
- }]
808
- };
809
- }
810
- return state;
811
- }
812
- }
813
- });
814
-
815
- // Return { state, open: true } to also open the panel
816
- initAgentWidget({
817
- target: 'body',
818
- config: {
819
- storageAdapter: createLocalStorageAdapter('my-chat'),
820
- onStateLoaded: (state) => {
821
- const navMessage = consumeNavigationFlag();
822
- if (navMessage) {
823
- return {
824
- state: {
825
- ...state,
826
- messages: [...(state.messages || []), {
827
- id: `nav-${Date.now()}`,
828
- role: 'assistant',
829
- content: navMessage,
830
- createdAt: new Date().toISOString()
831
- }]
832
- },
833
- open: true
834
- };
835
- }
836
- return state;
837
- }
838
- }
839
- });
840
- ```
841
-
842
- **Use cases:**
843
- - Inject messages after page navigation (e.g., "Here are our products!") and open the panel
844
- - Add confirmation messages after checkout/payment returns
845
- - Transform or filter loaded messages
846
- - Inject system messages based on external state
847
-
848
- The hook receives the loaded state and must return the (potentially modified) state synchronously.
849
-
850
- ### Message Actions (Copy, Upvote, Downvote)
851
-
852
- The widget includes built-in action buttons for assistant messages that allow users to copy message content and provide feedback through upvote/downvote buttons.
853
-
854
- #### Configuration
855
-
856
- ```ts
857
- const controller = initAgentWidget({
858
- target: '#app',
859
- config: {
860
- apiUrl: '/api/chat/dispatch',
861
-
862
- // Message actions configuration
863
- messageActions: {
864
- enabled: true, // Enable/disable all action buttons (default: true)
865
- showCopy: true, // Show copy button (default: true)
866
- showUpvote: true, // Show upvote button (default: false - requires backend)
867
- showDownvote: true, // Show downvote button (default: false - requires backend)
868
- visibility: 'hover', // 'hover' or 'always' (default: 'hover')
869
- align: 'right', // 'left', 'center', or 'right' (default: 'right')
870
- layout: 'pill-inside', // 'pill-inside' (compact floating) or 'row-inside' (full-width bar)
871
-
872
- // Optional callbacks (called in addition to events)
873
- onCopy: (message) => {
874
- console.log('Copied:', message.id);
875
- },
876
- onFeedback: (feedback) => {
877
- console.log('Feedback:', feedback.type, feedback.messageId);
878
- // Send to your analytics/backend
879
- fetch('/api/feedback', {
880
- method: 'POST',
881
- headers: { 'Content-Type': 'application/json' },
882
- body: JSON.stringify(feedback)
883
- });
884
- }
885
- }
886
- }
887
- });
888
- ```
889
-
890
- #### Feedback Events
891
-
892
- Listen to feedback events via the controller:
893
-
894
- ```ts
895
- // Copy event - fired when user copies a message
896
- controller.on('message:copy', (message) => {
897
- console.log('Message copied:', message.id, message.content);
898
- });
899
-
900
- // Feedback event - fired when user upvotes or downvotes
901
- controller.on('message:feedback', (feedback) => {
902
- console.log('Feedback received:', {
903
- type: feedback.type, // 'upvote' or 'downvote'
904
- messageId: feedback.messageId,
905
- message: feedback.message // Full message object
906
- });
907
- });
908
- ```
909
-
910
- #### Feedback Types
911
-
912
- ```typescript
913
- type AgentWidgetMessageFeedback = {
914
- type: 'upvote' | 'downvote';
915
- messageId: string;
916
- message: AgentWidgetMessage;
917
- };
918
-
919
- type AgentWidgetMessageActionsConfig = {
920
- enabled?: boolean;
921
- showCopy?: boolean;
922
- showUpvote?: boolean;
923
- showDownvote?: boolean;
924
- visibility?: 'always' | 'hover';
925
- onFeedback?: (feedback: AgentWidgetMessageFeedback) => void;
926
- onCopy?: (message: AgentWidgetMessage) => void;
927
- };
928
- ```
929
-
930
- #### Visual Behavior
931
-
932
- - **Hover mode** (`visibility: 'hover'`): Action buttons appear when hovering over assistant messages
933
- - **Always mode** (`visibility: 'always'`): Action buttons are always visible
934
- - **Copy button**: Shows a checkmark briefly after successful copy
935
- - **Vote buttons**: Toggle active state and are mutually exclusive (upvoting clears downvote and vice versa)
936
-
937
- ### Loading & Idle Indicators
938
-
939
- The widget displays visual indicators during different states of the conversation:
940
-
941
- - **Loading indicator**: Shown while waiting for a response (standalone) or when an assistant message is streaming but has no content yet (inline)
942
- - **Idle indicator**: Shown when the widget is idle (not streaming) and has at least one message - useful for showing the assistant is "waiting" for user input
943
-
944
- #### Configuration
945
-
946
- ```ts
947
- const controller = initAgentWidget({
948
- target: '#app',
949
- config: {
950
- apiUrl: '/api/chat/dispatch',
951
-
952
- loadingIndicator: {
953
- // Show/hide bubble styling around standalone indicator (default: true)
954
- showBubble: false,
955
-
956
- // Custom loading indicator renderer
957
- render: ({ location, config, defaultRenderer }) => {
958
- // location: 'standalone' (separate bubble) or 'inline' (inside message)
959
- if (location === 'standalone') {
960
- const el = document.createElement('div');
961
- el.innerHTML = '<svg class="spinner">...</svg>';
962
- el.setAttribute('data-preserve-animation', 'true');
963
- return el;
964
- }
965
- // Use default 3-dot bouncing indicator for inline
966
- return defaultRenderer();
967
- },
968
-
969
- // Custom idle state indicator (shown after response completes)
970
- renderIdle: ({ lastMessage, messageCount, config }) => {
971
- // Only show after assistant messages
972
- if (lastMessage?.role !== 'assistant') return null;
973
-
974
- const el = document.createElement('div');
975
- el.textContent = 'What would you like to do next?';
976
- el.setAttribute('data-preserve-animation', 'true');
977
- return el;
978
- }
979
- }
980
- }
981
- });
982
- ```
983
-
984
- #### Indicator Locations
985
-
986
- | Location | When Shown | Description |
987
- |----------|------------|-------------|
988
- | `standalone` | Waiting for stream to start | Separate bubble shown after user sends a message |
989
- | `inline` | Streaming with empty content | Inside the assistant message bubble |
990
- | `idle` | Not streaming, has messages | After assistant finishes responding |
991
-
992
- #### Animation Preservation
993
-
994
- When using custom animated indicators, add the `data-preserve-animation="true"` attribute to prevent the DOM morpher from interrupting CSS animations during updates:
995
-
996
- ```ts
997
- render: () => {
998
- const el = document.createElement('div');
999
- el.setAttribute('data-preserve-animation', 'true');
1000
- el.innerHTML = `
1001
- <style>
1002
- @keyframes spin { to { transform: rotate(360deg); } }
1003
- .spinner { animation: spin 1s linear infinite; }
1004
- </style>
1005
- <div class="spinner">⟳</div>
1006
- `;
1007
- return el;
1008
- }
1009
- ```
1010
-
1011
- #### Hiding Indicators
1012
-
1013
- Return `null` from any render function to hide that indicator:
1014
-
1015
- ```ts
1016
- loadingIndicator: {
1017
- // Hide loading indicator entirely
1018
- render: () => null,
1019
-
1020
- // Hide idle indicator (default behavior)
1021
- renderIdle: () => null
1022
- }
1023
- ```
1024
-
1025
- #### Using Plugins
1026
-
1027
- You can also customize indicators via plugins, which take priority over config:
1028
-
1029
- ```ts
1030
- const customIndicatorPlugin = {
1031
- id: 'custom-indicators',
1032
-
1033
- renderLoadingIndicator: ({ location, defaultRenderer }) => {
1034
- if (location === 'standalone') {
1035
- return createCustomSpinner();
1036
- }
1037
- return defaultRenderer();
1038
- },
1039
-
1040
- renderIdleIndicator: ({ lastMessage, messageCount }) => {
1041
- if (messageCount === 0) return null;
1042
- if (lastMessage?.role !== 'assistant') return null;
1043
- return createIdleAnimation();
1044
- }
1045
- };
1046
-
1047
- initAgentWidget({
1048
- target: '#app',
1049
- config: {
1050
- plugins: [customIndicatorPlugin]
1051
- }
1052
- });
1053
- ```
1054
-
1055
- #### Type Definitions
1056
-
1057
- ```typescript
1058
- // Loading indicator context
1059
- type LoadingIndicatorRenderContext = {
1060
- config: AgentWidgetConfig;
1061
- streaming: boolean;
1062
- location: 'inline' | 'standalone';
1063
- defaultRenderer: () => HTMLElement;
1064
- };
1065
-
1066
- // Idle indicator context
1067
- type IdleIndicatorRenderContext = {
1068
- config: AgentWidgetConfig;
1069
- lastMessage: AgentWidgetMessage | undefined;
1070
- messageCount: number;
1071
- };
1072
-
1073
- // Configuration
1074
- type AgentWidgetLoadingIndicatorConfig = {
1075
- showBubble?: boolean;
1076
- render?: (context: LoadingIndicatorRenderContext) => HTMLElement | null;
1077
- renderIdle?: (context: IdleIndicatorRenderContext) => HTMLElement | null;
1078
- };
1079
- ```
1080
-
1081
- #### Priority Chain
1082
-
1083
- Indicators are resolved in this order:
1084
- 1. **Plugin hook** (`renderLoadingIndicator` / `renderIdleIndicator`)
1085
- 2. **Config function** (`loadingIndicator.render` / `loadingIndicator.renderIdle`)
1086
- 3. **Default** (3-dot bouncing animation for loading, `null` for idle)
1087
-
1088
- ### Ask User Question
1089
-
1090
- The `ask_user_question` feature turns a LOCAL agent tool into an interactive prompt with tappable option pills. When the agent calls the `ask_user_question` tool, the server pauses execution and emits a `step_await` event; the widget renders an answer-pill sheet over the composer; the user picks / types / dismisses; the widget POSTs the answer to `/v1/dispatch/resume` and the paused execution continues with a structured `tool_result`.
1091
-
1092
- This is the recommended pattern for human-in-the-loop clarifying questions. The agent-side setup (declare `ask_user_question` as a `runtimeTools` LOCAL tool and instruct the model to call it) lives in your `RuntypeFlowConfig` in the proxy — pair it with a `POST` handler that forwards to the upstream `/resume` endpoint (see `@runtypelabs/persona-proxy` and your deployment’s `resume` route).
1093
-
1094
- #### Configuration
1095
-
1096
- ```ts
1097
- features: {
1098
- askUserQuestion: {
1099
- enabled: true, // default: true. When false, the tool falls through to the normal tool-bubble path.
1100
- dismissible: true, // default: true. Shows a × close button on the sheet.
1101
- slideInMs: 180, // slide-in animation duration.
1102
- freeTextLabel: 'Other…',
1103
- freeTextPlaceholder: 'Type your answer…',
1104
- submitLabel: 'Send',
1105
- styles: {
1106
- sheetBackground: '#ffffff',
1107
- sheetBorder: '#e5e7eb',
1108
- sheetShadow: '0 12px 28px -10px rgba(0,0,0,0.15)',
1109
- pillBackground: 'transparent',
1110
- pillBackgroundSelected: '#0f0f0f',
1111
- pillTextColor: '#1f2937',
1112
- pillTextColorSelected: '#fafafa',
1113
- pillBorderRadius: '999px',
1114
- customInputBackground: '#ffffff'
1115
- }
1116
- }
1117
- }
1118
- ```
1119
-
1120
- The composer-overlay sheet is the only question UI — no transcript stub is rendered. After the user picks, the picked answer appears as a normal user bubble so the transcript reads naturally.
1121
-
1122
- #### DOM events
1123
-
1124
- The widget dispatches two events on the mount element so the host page can react without touching the plugin API:
1125
-
1126
- | Event | Detail |
1127
- |---|---|
1128
- | `persona:askUserQuestion:answered` | `{ toolUseId, answer, values, isFreeText, source }` where `source` is `'pick' \| 'multi' \| 'free-text'` |
1129
- | `persona:askUserQuestion:dismissed` | `{ toolUseId }` |
1130
-
1131
- ```ts
1132
- mount.addEventListener('persona:askUserQuestion:answered', (event) => {
1133
- const { answer, source } = event.detail;
1134
- console.log('User picked', answer, 'via', source);
1135
- });
1136
- ```
1137
-
1138
- #### Custom UI via the `renderAskUserQuestion` plugin hook
1139
-
1140
- For full control over the question UI — a modal, a sidebar form, a command palette, whatever — register a plugin with `renderAskUserQuestion`. Returning a non-null `HTMLElement` renders inline in the transcript and suppresses the built-in overlay sheet. Returning `null` falls through to the default sheet.
1141
-
1142
- ```ts
1143
- import type { AgentWidgetPlugin } from '@runtypelabs/persona';
1144
-
1145
- const customAskPlugin: AgentWidgetPlugin = {
1146
- id: 'custom-ask',
1147
- renderAskUserQuestion: ({ payload, complete, resolve, dismiss }) => {
1148
- const prompt = payload?.questions?.[0];
1149
- if (!prompt) return null; // streaming — wait for more data, or show a skeleton
1150
-
1151
- const root = document.createElement('div');
1152
- root.className = 'my-question-card';
1153
-
1154
- const q = document.createElement('p');
1155
- q.textContent = prompt.question ?? '';
1156
- root.appendChild(q);
1157
-
1158
- (prompt.options ?? []).forEach((option) => {
1159
- const btn = document.createElement('button');
1160
- btn.textContent = option.label;
1161
- btn.addEventListener('click', () => resolve(option.label));
1162
- root.appendChild(btn);
1163
- });
1164
-
1165
- if (prompt.allowFreeText !== false) {
1166
- const input = document.createElement('input');
1167
- input.placeholder = 'Other…';
1168
- input.addEventListener('keydown', (e) => {
1169
- if (e.key === 'Enter' && input.value.trim()) resolve(input.value.trim());
1170
- });
1171
- root.appendChild(input);
1172
- }
1173
-
1174
- const close = document.createElement('button');
1175
- close.textContent = '×';
1176
- close.addEventListener('click', () => dismiss());
1177
- root.appendChild(close);
1178
-
1179
- return root;
1180
- }
1181
- };
1182
-
1183
- initAgentWidget({
1184
- target: '#app',
1185
- config: {
1186
- plugins: [customAskPlugin]
1187
- }
1188
- });
1189
- ```
1190
-
1191
- #### Type Definitions
1192
-
1193
- ```ts
1194
- type AskUserQuestionOption = {
1195
- label: string;
1196
- description?: string;
1197
- };
1198
-
1199
- type AskUserQuestionPrompt = {
1200
- question: string;
1201
- header?: string; // short chip label, ≤12 chars
1202
- options: AskUserQuestionOption[];
1203
- multiSelect?: boolean; // allow multiple picks with a Submit button
1204
- allowFreeText?: boolean; // show an "Other…" free-text pill
1205
- };
1206
-
1207
- type AskUserQuestionPayload = {
1208
- questions: AskUserQuestionPrompt[];
1209
- };
1210
-
1211
- // Plugin hook signature
1212
- renderAskUserQuestion?: (context: {
1213
- message: AgentWidgetMessage;
1214
- payload: Partial<AskUserQuestionPayload> | null; // may be partial mid-stream
1215
- complete: boolean; // true once tool-call args fully stream
1216
- resolve: (answer: string) => void; // posts /resume with structured toolOutput
1217
- dismiss: () => void; // sends "(dismissed)" sentinel
1218
- config: AgentWidgetConfig;
1219
- }) => HTMLElement | null;
1220
- ```
1221
-
1222
- For plugins that want to re-parse a tool message outside the hook context, the widget also exports a `parseAskUserQuestionPayload(message)` helper that returns `{ payload, complete }` using the same partial-JSON logic the built-in sheet uses.
1223
-
1224
- #### Priority chain
1225
-
1226
- 1. **Plugin hook** (`renderAskUserQuestion` returning a non-null element) — fully owns the UI; built-in overlay is suppressed.
1227
- 2. **Built-in overlay sheet** — when the feature is enabled and no plugin handles it.
1228
- 3. **Generic tool bubble** — when `features.askUserQuestion.enabled` is `false`, the tool call renders through the normal `renderToolCall` path.
1229
-
1230
- ### Dropdown Menu
1231
-
1232
- A reusable dropdown menu utility for building custom menus in plugins, custom components, or host-page UI that matches the widget's theme.
1233
-
1234
- #### Basic usage
1235
-
1236
- ```ts
1237
- import { createDropdownMenu } from '@runtypelabs/persona';
1238
-
1239
- const button = document.querySelector('#my-button')!;
1240
- const wrapper = document.createElement('div');
1241
- wrapper.style.position = 'relative';
1242
- button.parentElement!.insertBefore(wrapper, button);
1243
- wrapper.appendChild(button);
1244
-
1245
- const dropdown = createDropdownMenu({
1246
- items: [
1247
- { id: 'edit', label: 'Edit', icon: 'pencil' },
1248
- { id: 'duplicate', label: 'Duplicate', icon: 'copy' },
1249
- { id: 'delete', label: 'Delete', icon: 'trash-2', destructive: true, dividerBefore: true },
1250
- ],
1251
- onSelect: (id) => console.log('Selected:', id),
1252
- anchor: wrapper,
1253
- position: 'bottom-left', // or 'bottom-right'
1254
- });
1255
-
1256
- wrapper.appendChild(dropdown.element);
1257
- button.addEventListener('click', () => dropdown.toggle());
1258
- ```
1259
-
1260
- #### Escaping overflow containers
1261
-
1262
- When the anchor is inside a container with `overflow: hidden`, use the `portal` option to render the menu at a higher DOM level while keeping CSS variable inheritance:
1263
-
1264
- ```ts
1265
- const dropdown = createDropdownMenu({
1266
- items: [...],
1267
- onSelect: (id) => { /* handle */ },
1268
- anchor: myButton,
1269
- position: 'bottom-right',
1270
- portal: document.querySelector('[data-persona-root]')!,
1271
- });
1272
- // No need to append — portal mode appends automatically
1273
- ```
1274
-
1275
- #### Header dropdown menus
1276
-
1277
- Trailing header actions support built-in dropdown menus via the `menuItems` property:
1278
-
1279
- ```ts
1280
- createAgentExperience(mount, {
1281
- layout: {
1282
- header: {
1283
- layout: 'minimal',
1284
- trailingActions: [
1285
- {
1286
- id: 'options',
1287
- icon: 'chevron-down',
1288
- ariaLabel: 'Options',
1289
- menuItems: [
1290
- { id: 'settings', label: 'Settings', icon: 'settings' },
1291
- { id: 'help', label: 'Help', icon: 'help-circle' },
1292
- { id: 'logout', label: 'Log out', icon: 'log-out', destructive: true, dividerBefore: true },
1293
- ]
1294
- }
1295
- ],
1296
- onAction: (actionId) => {
1297
- // Receives the menu item id when selected
1298
- console.log('Action:', actionId);
1299
- }
1300
- }
1301
- }
1302
- });
1303
- ```
1304
-
1305
- #### Theming
1306
-
1307
- Dropdown menus are styled via CSS custom properties with semantic fallbacks:
1308
-
1309
- | Variable | Description | Fallback |
1310
- |----------|-------------|----------|
1311
- | `--persona-dropdown-bg` | Menu background | `--persona-surface` |
1312
- | `--persona-dropdown-border` | Menu border | `--persona-border` |
1313
- | `--persona-dropdown-radius` | Border radius | `0.625rem` |
1314
- | `--persona-dropdown-shadow` | Box shadow | `0 4px 16px rgba(0,0,0,0.12)` |
1315
- | `--persona-dropdown-item-color` | Item text color | `--persona-text` |
1316
- | `--persona-dropdown-item-hover-bg` | Item hover background | `--persona-container` |
1317
- | `--persona-dropdown-destructive-color` | Destructive item color | `#ef4444` |
1318
-
1319
- Artifact toolbar copy menu tokens (`copyMenuBackground`, `copyMenuBorder`, etc.) also set the dropdown variables as defaults, so dropdown theming works with the existing artifact token config.
1320
-
1321
- #### Type definitions
1322
-
1323
- ```ts
1324
- interface DropdownMenuItem {
1325
- id: string;
1326
- label: string;
1327
- icon?: string; // Lucide icon name
1328
- destructive?: boolean;
1329
- dividerBefore?: boolean;
1330
- }
1331
-
1332
- interface CreateDropdownOptions {
1333
- items: DropdownMenuItem[];
1334
- onSelect: (id: string) => void;
1335
- anchor: HTMLElement;
1336
- position?: 'bottom-left' | 'bottom-right';
1337
- portal?: HTMLElement;
1338
- }
1339
-
1340
- interface DropdownMenuHandle {
1341
- element: HTMLElement;
1342
- show: () => void;
1343
- hide: () => void;
1344
- toggle: () => void;
1345
- destroy: () => void;
1346
- }
1347
- ```
1348
-
1349
- ### Button Utilities
1350
-
1351
- Composable button factories for building custom toolbars, actions, and toggle controls that match the widget's theme.
1352
-
1353
- #### Icon button
1354
-
1355
- ```ts
1356
- import { createIconButton } from '@runtypelabs/persona';
1357
-
1358
- const refreshBtn = createIconButton({
1359
- icon: 'refresh-cw',
1360
- label: 'Refresh',
1361
- onClick: () => handleRefresh(),
1362
- });
1363
- toolbar.appendChild(refreshBtn);
1364
- ```
1365
-
1366
- #### Label button
1367
-
1368
- ```ts
1369
- import { createLabelButton } from '@runtypelabs/persona';
1370
-
1371
- const copyBtn = createLabelButton({
1372
- icon: 'copy',
1373
- label: 'Copy',
1374
- variant: 'default', // 'default' | 'primary' | 'destructive' | 'ghost'
1375
- onClick: () => copyToClipboard(),
1376
- });
1377
- ```
1378
-
1379
- #### Toggle group
1380
-
1381
- ```ts
1382
- import { createToggleGroup } from '@runtypelabs/persona';
1383
-
1384
- const toggle = createToggleGroup({
1385
- items: [
1386
- { id: 'preview', icon: 'eye', label: 'Preview' },
1387
- { id: 'source', icon: 'code-2', label: 'Source' },
1388
- ],
1389
- selectedId: 'preview',
1390
- onSelect: (id) => setViewMode(id),
1391
- });
1392
- toolbar.appendChild(toggle.element);
1393
-
1394
- // Programmatic update (does not fire onSelect)
1395
- toggle.setSelected('source');
1396
- ```
1397
-
1398
- #### Theming
1399
-
1400
- All button utilities are styled via CSS custom properties:
1401
-
1402
- | Variable | Component | Description | Fallback |
1403
- |----------|-----------|-------------|----------|
1404
- | `--persona-icon-btn-bg` | Icon button | Background | `--persona-surface` |
1405
- | `--persona-icon-btn-border` | Icon button | Border | `--persona-border` |
1406
- | `--persona-icon-btn-color` | Icon button | Icon color | `--persona-text` |
1407
- | `--persona-icon-btn-hover-bg` | Icon button | Hover background | `--persona-container` |
1408
- | `--persona-icon-btn-hover-color` | Icon button | Hover color | `inherit` |
1409
- | `--persona-icon-btn-active-bg` | Icon button | Pressed/active bg | `--persona-container` |
1410
- | `--persona-icon-btn-active-border` | Icon button | Pressed/active border | `--persona-border` |
1411
- | `--persona-icon-btn-padding` | Icon button | Padding | `0.25rem` |
1412
- | `--persona-icon-btn-radius` | Icon button | Border radius | `--persona-radius-md` |
1413
- | `--persona-label-btn-bg` | Label button | Background | `--persona-surface` |
1414
- | `--persona-label-btn-border` | Label button | Border | `--persona-border` |
1415
- | `--persona-label-btn-color` | Label button | Text color | `--persona-text` |
1416
- | `--persona-label-btn-hover-bg` | Label button | Hover background | `--persona-container` |
1417
- | `--persona-label-btn-font-size` | Label button | Font size | `0.75rem` |
1418
- | `--persona-toggle-group-gap` | Toggle group | Gap between items | `0` |
1419
- | `--persona-toggle-group-radius` | Toggle group | First/last radius | `--persona-icon-btn-radius` |
1420
-
1421
- These can also be set via the widget config's theme token system:
1422
-
1423
- ```ts
1424
- createAgentExperience(mount, {
1425
- darkTheme: {
1426
- components: {
1427
- iconButton: {
1428
- background: 'transparent',
1429
- border: 'none',
1430
- hoverBackground: '#2B2B2B',
1431
- hoverColor: '#E5E5E5',
1432
- },
1433
- toggleGroup: {
1434
- gap: '0',
1435
- borderRadius: '8px',
1436
- },
1437
- }
1438
- }
1439
- });
1440
- ```
1441
-
1442
- ### Runtype adapter
1443
-
1444
- This package ships with a Runtype adapter by default. The proxy handles all flow configuration, keeping the client lightweight and flexible.
1445
-
1446
- **Flow configuration happens server-side** - you have three options:
1447
-
1448
- 1. **Use default flow** - The proxy includes a basic streaming chat flow out of the box
1449
- 2. **Reference a Runtype flow ID** - Configure flows in your Runtype dashboard and reference them by ID
1450
- 3. **Define custom flows** - Build flow configurations directly in the proxy
1451
-
1452
- The client simply sends messages to the proxy, which constructs the full Runtype payload. This architecture allows you to:
1453
- - Change models/prompts without redeploying the widget
1454
- - A/B test different flows server-side
1455
- - Enforce security and cost controls centrally
1456
- - Support multiple flows for different use cases
1457
-
1458
- ### Dynamic Forms (Recommended)
1459
-
1460
- For rendering AI-generated forms, use the **component middleware** approach with the `DynamicForm` component. This allows the AI to create contextually appropriate forms with any fields:
1461
-
1462
- ```typescript
1463
- import { componentRegistry, initAgentWidget } from "@runtypelabs/persona";
1464
- import { DynamicForm } from "./components"; // Your DynamicForm component
1465
-
1466
- // Register the component
1467
- componentRegistry.register("DynamicForm", DynamicForm);
1468
-
1469
- initAgentWidget({
1470
- target: "#app",
1471
- config: {
1472
- apiUrl: "/api/chat/dispatch-directive",
1473
- parserType: "json",
1474
- enableComponentStreaming: true,
1475
- formEndpoint: "/form",
1476
- // Optional: customize form appearance
1477
- formStyles: {
1478
- borderRadius: "16px",
1479
- borderWidth: "1px",
1480
- borderColor: "#e5e7eb",
1481
- padding: "1.5rem",
1482
- titleFontSize: "1.25rem",
1483
- buttonBorderRadius: "9999px"
1484
- }
1485
- }
1486
- });
1487
- ```
1488
-
1489
- The AI responds with JSON like:
1490
-
1491
- ```json
1492
- {
1493
- "text": "Please fill out this form:",
1494
- "component": "DynamicForm",
1495
- "props": {
1496
- "title": "Contact Us",
1497
- "fields": [
1498
- { "label": "Name", "type": "text", "required": true },
1499
- { "label": "Email", "type": "email", "required": true }
1500
- ],
1501
- "submit_text": "Submit"
1502
- }
1503
- }
1504
- ```
1505
-
1506
- **Demos and reference:**
1507
-
1508
- - [`examples/embedded-app/dynamic-form.html`](../../examples/embedded-app/dynamic-form.html) — primary demo with three layout variants (Compact / Spacious / Branded) showing how `formStyles` scales between visual languages.
1509
- - [`examples/embedded-app/dynamic-form-fields.html`](../../examples/embedded-app/dynamic-form-fields.html) — every field type, layout width, helper-text, required marking, and sensitive-masking pattern in one page.
1510
- - [`docs/DYNAMIC-FORMS.md`](./docs/DYNAMIC-FORMS.md) — full reference: field schema, `formStyles` tokens, layout patterns, recipes, and how to extend the example component (new field types, sections, conditional fields).
1511
-
1512
- The shipped `DynamicForm` is an **example** in [`examples/embedded-app/src/components.ts`](../../examples/embedded-app/src/components.ts) — copy it into your app and customize. It supports text/email/tel/url/number/date/time/textarea, half-width pairs, auto-grow textareas, required-asterisk marking, inline validation, a success recap card with sensitive-field masking, and edit-after-submit. See [DYNAMIC-FORMS.md](./docs/DYNAMIC-FORMS.md) for the full surface area.
1513
-
1514
- ### Directive postprocessor (Deprecated)
1515
-
1516
- > **⚠️ Deprecated:** The `directivePostprocessor` approach is deprecated in favor of the component middleware with `DynamicForm`. The old approach only supports predefined form templates ("init" and "followup"), while the new approach allows AI-generated forms with any fields.
1517
-
1518
- `directivePostprocessor` looks for either `<Form type="init" />` tokens or
1519
- `<Directive>{"component":"form","type":"init"}</Directive>` blocks and swaps them for placeholders that the widget upgrades into interactive UI. This approach is limited to the predefined form templates in `formDefinitions`.
1520
-
1521
- ### Script tag installation
1522
-
1523
- The widget can be installed via a simple script tag, perfect for platforms where you can't compile custom code. There are two methods:
1524
-
1525
- #### Method 1: Automatic installer (recommended)
1526
-
1527
- The easiest way is to use the automatic installer script. It handles loading CSS and JavaScript, then initializes the widget automatically:
1528
-
1529
- ```html
1530
- <!-- Add this before the closing </body> tag -->
1531
- <script>
1532
- window.siteAgentConfig = {
1533
- target: 'body', // or '#my-container' for specific placement
1534
- config: {
1535
- apiUrl: 'https://your-proxy.com/api/chat/dispatch',
1536
- launcher: {
1537
- enabled: true,
1538
- title: 'AI Assistant',
1539
- subtitle: 'How can I help you?'
1540
- },
1541
- theme: {
1542
- accent: '#2563eb',
1543
- surface: '#ffffff'
1544
- },
1545
- // Optional: configure stream parser for JSON/XML responses
1546
- // streamParser: () => window.AgentWidget.createJsonStreamParser()
1547
- }
1548
- };
1549
- </script>
1550
- <script src="https://cdn.jsdelivr.net/npm/@runtypelabs/persona@latest/dist/install.global.js"></script>
1551
- ```
1552
-
1553
- **Installer options:**
1554
-
1555
- - `version` - Package version to load (default: `"latest"`)
1556
- - `cdn` - CDN provider: `"jsdelivr"` or `"unpkg"` (default: `"jsdelivr"`)
1557
- - `cssUrl` - Custom CSS URL (overrides CDN)
1558
- - `jsUrl` - Custom JS URL (overrides CDN)
1559
- - `target` - CSS selector or element where widget mounts (default: `"body"`)
1560
- - `config` - Widget configuration object (see Configuration reference)
1561
- - `autoInit` - Automatically initialize after loading (default: `true`)
1562
- - `clientToken` - Client token for authentication (alternative to proxy `apiUrl`)
1563
- - `flowId` - Flow ID for client token authentication
1564
- - `apiUrl` - API URL for the chat endpoint (can also be set inside `config`)
1565
- - `previewQueryParam` - Query parameter key that gates widget loading; widget only loads when the parameter is present and truthy
1566
- - `useShadowDom` - Use Shadow DOM for style isolation (default: `false`)
1567
- - `windowKey` - If provided, stores the widget handle on `window[windowKey]` for programmatic access
1568
- - `onScriptLoad` - Fired as soon as the installer script executes, before it loads or gates anything (diagnostics / timing); signature: `({ version }) => void`
1569
- - `onLauncherShown` - Fired when the floating launcher is painted on the page (page-load time — for "widget appeared" analytics); signature: `({ deferred, element? }) => void`
1570
- - `onChatReady` - Fired when the widget is initialized and its controller API is callable (after first open in a deferred install); signature: `(handle) => void`
1571
- - `onError` - Fired when a load step fails (`css` / `bundle` / `init`), so ad-blocked / timed-out installs don't fail silently; signature: `({ phase, error }) => void`
1572
- - `onReady` - **Deprecated** alias of `onChatReady`; still works, removed in the next major; signature: `(handle) => void`
1573
-
1574
- **Example with version pinning:**
1575
-
1576
- ```html
1577
- <script>
1578
- window.siteAgentConfig = {
1579
- version: '0.1.0', // Pin to specific version
1580
- config: {
1581
- apiUrl: '/api/chat/dispatch',
1582
- launcher: { enabled: true, title: 'Support Chat' }
1583
- }
1584
- };
1585
- </script>
1586
- <script src="https://cdn.jsdelivr.net/npm/@runtypelabs/persona@0.1.0/dist/install.global.js"></script>
1587
- ```
1588
-
1589
- #### Programmatic access with the installer
1590
-
1591
- The installer is fully asynchronous (it waits for framework hydration, then loads CSS and JS). To interact with the widget after it initializes, use one of these approaches:
1592
-
1593
- **`onChatReady` callback** — best when config and access logic live in the same script:
1594
-
1595
- ```html
1596
- <script>
1597
- window.siteAgentConfig = {
1598
- clientToken: 'YOUR_TOKEN',
1599
- windowKey: 'myChat',
1600
- onChatReady(handle) {
1601
- handle.on('message:sent', (e) => console.log('sent:', e));
1602
- handle.on('message:received', (e) => console.log('received:', e));
1603
- }
1604
- };
1605
- </script>
1606
- <script src="https://cdn.jsdelivr.net/npm/@runtypelabs/persona@latest/dist/install.global.js"></script>
1607
- ```
1608
-
1609
- **`persona:chat-ready` event** — best for decoupled integration (e.g. tag managers, separate scripts):
1610
-
1611
- ```html
1612
- <script>
1613
- window.addEventListener('persona:chat-ready', (e) => {
1614
- const handle = e.detail;
1615
- handle.on('message:sent', (e) => console.log('sent:', e));
1616
- });
1617
- </script>
1618
-
1619
- <!-- Can be in a different script, tag manager snippet, etc. -->
1620
- <script>
1621
- window.siteAgentConfig = { clientToken: 'YOUR_TOKEN' };
1622
- </script>
1623
- <script src="https://cdn.jsdelivr.net/npm/@runtypelabs/persona@latest/dist/install.global.js"></script>
1624
- ```
1625
-
1626
- **`windowKey`** — stores the handle on `window[windowKey]` for persistent global access. Combine with `onChatReady` or `persona:chat-ready` to know when it's available:
1627
-
1628
- ```html
1629
- <script>
1630
- window.siteAgentConfig = {
1631
- clientToken: 'YOUR_TOKEN',
1632
- windowKey: 'myChat'
1633
- };
1634
- </script>
1635
- <script src="https://cdn.jsdelivr.net/npm/@runtypelabs/persona@latest/dist/install.global.js"></script>
1636
-
1637
- <script>
1638
- window.addEventListener('persona:chat-ready', () => {
1639
- // window.myChat is now available and persists until destroy()
1640
- window.myChat.open();
1641
- });
1642
- </script>
1643
- ```
1644
-
1645
- #### Method 2: Manual installation
1646
-
1647
- For more control, manually load CSS and JavaScript:
1648
-
1649
- ```html
1650
- <!-- Load CSS -->
1651
- <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@runtypelabs/persona@latest/dist/widget.css" />
1652
-
1653
- <!-- Load JavaScript -->
1654
- <script src="https://cdn.jsdelivr.net/npm/@runtypelabs/persona@latest/dist/index.global.js"></script>
1655
-
1656
- <!-- Initialize widget -->
1657
- <script>
1658
- const chatController = window.AgentWidget.initAgentWidget({
1659
- target: '#persona-anchor', // or 'body' for floating launcher
1660
- windowKey: 'chatWidget', // Optional: stores controller on window.chatWidget
1661
- config: {
1662
- apiUrl: '/api/chat/dispatch',
1663
- launcher: {
1664
- enabled: true,
1665
- title: 'AI Assistant',
1666
- subtitle: 'Here to help'
1667
- },
1668
- theme: {
1669
- accent: '#111827',
1670
- surface: '#f5f5f5'
1671
- },
1672
- // Optional: configure stream parser for JSON/XML responses
1673
- streamParser: window.AgentWidget.createJsonStreamParser // or createXmlParser, createPlainTextParser
1674
- }
1675
- });
1676
-
1677
- // Controller is now available as window.chatWidget (if windowKey was used)
1678
- // or use the returned chatController variable
1679
- </script>
1680
- ```
1681
-
1682
- **CDN options:**
1683
-
1684
- - **jsDelivr** (recommended): `https://cdn.jsdelivr.net/npm/@runtypelabs/persona@VERSION/dist/`
1685
- - **unpkg**: `https://unpkg.com/@runtypelabs/persona@VERSION/dist/`
1686
-
1687
- Replace `VERSION` with `latest` for auto-updates, or a specific version like `0.1.0` for stability.
1688
-
1689
- **Available files:**
1690
-
1691
- - `widget.css` - Stylesheet (required)
1692
- - `index.global.js` - Widget JavaScript (IIFE format)
1693
- - `install.global.js` - Automatic installer script
1694
-
1695
- The script build exposes a `window.AgentWidget` global with `initAgentWidget()` and other exports, including parser functions:
1696
-
1697
- - `window.AgentWidget.initAgentWidget()` - Initialize the widget
1698
- - `window.AgentWidget.createPlainTextParser()` - Plain text parser (default)
1699
- - `window.AgentWidget.createJsonStreamParser()` - JSON parser using schema-stream
1700
- - `window.AgentWidget.createXmlParser()` - XML parser
1701
- - `window.AgentWidget.markdownPostprocessor()` - Markdown postprocessor
1702
- - `window.AgentWidget.directivePostprocessor()` - Directive postprocessor *(deprecated)*
1703
- - `window.AgentWidget.componentRegistry` - Component registry for custom components
1704
-
1705
- ### React Framework Integration
1706
-
1707
- The widget is fully compatible with React frameworks. Use the ESM imports to integrate it as a client component.
1708
-
1709
- #### Framework Compatibility
1710
-
1711
- | Framework | Compatible | Implementation Notes |
1712
- |-----------|------------|---------------------|
1713
- | **Vite** | ✅ Yes | No special requirements - works out of the box |
1714
- | **Create React App** | ✅ Yes | No special requirements - works out of the box |
1715
- | **Next.js** | ✅ Yes | Requires `'use client'` directive (App Router) |
1716
- | **Remix** | ✅ Yes | Use dynamic import or `useEffect` guard for SSR |
1717
- | **Gatsby** | ✅ Yes | Use in `wrapRootElement` or check `typeof window !== 'undefined'` |
1718
- | **Astro** | ✅ Yes | Use `client:load` or `client:only="react"` directive |
1719
-
1720
- #### Quick Start with Vite or Create React App
1721
-
1722
- For client-side-only React frameworks (Vite, CRA), create a component:
1723
-
1724
- ```typescript
1725
- // src/components/ChatWidget.tsx
1726
- import { useEffect } from 'react';
1727
- import '@runtypelabs/persona/widget.css';
1728
- import { initAgentWidget, markdownPostprocessor } from '@runtypelabs/persona';
1729
- import type { AgentWidgetInitHandle } from '@runtypelabs/persona';
1730
-
1731
- export function ChatWidget() {
1732
- useEffect(() => {
1733
- let handle: AgentWidgetInitHandle | null = null;
1734
-
1735
- handle = initAgentWidget({
1736
- target: 'body',
1737
- config: {
1738
- apiUrl: "/api/chat/dispatch",
1739
- theme: {
1740
- primary: "#111827",
1741
- accent: "#1d4ed8",
1742
- },
1743
- launcher: {
1744
- enabled: true,
1745
- title: "Chat Assistant",
1746
- subtitle: "Here to help you get answers fast"
1747
- },
1748
- postprocessMessage: ({ text }) => markdownPostprocessor(text)
1749
- }
1750
- });
1751
-
1752
- // Cleanup on unmount
1753
- return () => {
1754
- if (handle) {
1755
- handle.destroy();
1756
- }
1757
- };
1758
- }, []);
1759
-
1760
- return null; // Widget injects itself into the DOM
1761
- }
1762
- ```
1763
-
1764
- Then use it in your app:
1765
-
1766
- ```typescript
1767
- // src/App.tsx
1768
- import { ChatWidget } from './components/ChatWidget';
1769
-
1770
- function App() {
1771
- return (
1772
- <div>
1773
- {/* Your app content */}
1774
- <ChatWidget />
1775
- </div>
1776
- );
1777
- }
1778
-
1779
- export default App;
1780
- ```
1781
-
1782
- #### Next.js Integration
1783
-
1784
- For Next.js App Router, add the `'use client'` directive:
1785
-
1786
- ```typescript
1787
- // components/ChatWidget.tsx
1788
- 'use client';
1789
-
1790
- import { useEffect } from 'react';
1791
- import '@runtypelabs/persona/widget.css';
1792
- import { initAgentWidget, markdownPostprocessor } from '@runtypelabs/persona';
1793
- import type { AgentWidgetInitHandle } from '@runtypelabs/persona';
1794
-
1795
- export function ChatWidget() {
1796
- useEffect(() => {
1797
- let handle: AgentWidgetInitHandle | null = null;
1798
-
1799
- handle = initAgentWidget({
1800
- target: 'body',
1801
- config: {
1802
- apiUrl: "/api/chat/dispatch",
1803
- launcher: {
1804
- enabled: true,
1805
- title: "Chat Assistant",
1806
- },
1807
- postprocessMessage: ({ text }) => markdownPostprocessor(text)
1808
- }
1809
- });
1810
-
1811
- return () => {
1812
- if (handle) {
1813
- handle.destroy();
1814
- }
1815
- };
1816
- }, []);
1817
-
1818
- return null;
1819
- }
1820
- ```
1821
-
1822
- Use it in your layout or page:
1823
-
1824
- ```typescript
1825
- // app/layout.tsx
1826
- import { ChatWidget } from '@/components/ChatWidget';
1827
-
1828
- export default function RootLayout({ children }) {
1829
- return (
1830
- <html lang="en">
1831
- <body>
1832
- {children}
1833
- <ChatWidget />
1834
- </body>
1835
- </html>
1836
- );
1837
- }
1838
- ```
1839
-
1840
- **Alternative: Dynamic Import (SSR-Safe)**
1841
-
1842
- If you encounter SSR issues, use Next.js dynamic imports:
1843
-
1844
- ```typescript
1845
- // app/layout.tsx
1846
- import dynamic from 'next/dynamic';
1847
-
1848
- const ChatWidget = dynamic(
1849
- () => import('@/components/ChatWidget').then(mod => mod.ChatWidget),
1850
- { ssr: false }
1851
- );
1852
-
1853
- export default function RootLayout({ children }) {
1854
- return (
1855
- <html lang="en">
1856
- <body>
1857
- {children}
1858
- <ChatWidget />
1859
- </body>
1860
- </html>
1861
- );
1862
- }
1863
- ```
1864
-
1865
- #### Remix Integration
1866
-
1867
- For Remix, guard the widget initialization with a client-side check:
1868
-
1869
- ```typescript
1870
- // app/components/ChatWidget.tsx
1871
- import { useEffect, useState } from 'react';
1872
-
1873
- export function ChatWidget() {
1874
- const [mounted, setMounted] = useState(false);
1875
-
1876
- useEffect(() => {
1877
- setMounted(true);
1878
-
1879
- // Dynamic import to avoid SSR issues
1880
- import('@runtypelabs/persona/widget.css');
1881
- import('@runtypelabs/persona').then(({ initAgentWidget, markdownPostprocessor }) => {
1882
- const handle = initAgentWidget({
1883
- target: 'body',
1884
- config: {
1885
- apiUrl: "/api/chat/dispatch",
1886
- launcher: { enabled: true },
1887
- postprocessMessage: ({ text }) => markdownPostprocessor(text)
1888
- }
1889
- });
1890
-
1891
- return () => handle?.destroy();
1892
- });
1893
- }, []);
1894
-
1895
- if (!mounted) return null;
1896
- return null;
1897
- }
1898
- ```
1899
-
1900
- #### Gatsby Integration
1901
-
1902
- Use Gatsby's `wrapRootElement` API:
1903
-
1904
- ```typescript
1905
- // gatsby-browser.js
1906
- import { ChatWidget } from './src/components/ChatWidget';
1907
-
1908
- export const wrapRootElement = ({ element }) => (
1909
- <>
1910
- {element}
1911
- <ChatWidget />
1912
- </>
1913
- );
1914
- ```
1915
-
1916
- #### Astro Integration
1917
-
1918
- Use Astro's client directives with React islands:
1919
-
1920
- ```astro
1921
- ---
1922
- // src/components/ChatWidget.astro
1923
- import { ChatWidget } from './ChatWidget.tsx';
1924
- ---
1925
-
1926
- <ChatWidget client:load />
1927
- ```
1928
-
1929
- #### Using the Theme Configurator
1930
-
1931
- For easy configuration generation, use the [Theme Configurator](https://github.com/becomevocal/chaty/tree/main/examples/embedded-app) which includes a "React (Client Component)" export option. It generates a complete React component with your custom theme, launcher settings, and all configuration options.
1932
-
1933
- #### Installation
1934
-
1935
- ```bash
1936
- npm install @runtypelabs/persona
1937
- # or
1938
- pnpm add @runtypelabs/persona
1939
- # or
1940
- yarn add @runtypelabs/persona
1941
- ```
1942
-
1943
- #### Key Considerations
1944
-
1945
- 1. **CSS Import**: The CSS import (`import '@runtypelabs/persona/widget.css'`) works natively with all modern React build tools
1946
- 2. **Client-Side Only**: The widget manipulates the DOM, so it must run client-side only
1947
- 3. **Cleanup**: Always call `handle.destroy()` in the cleanup function to prevent memory leaks
1948
- 4. **API Routes**: Ensure your `apiUrl` points to a valid backend endpoint
1949
- 5. **TypeScript Support**: Full TypeScript definitions are included for all exports
1950
-
1951
- ### Using default configuration
1952
-
1953
- The package exports a complete default configuration that you can use as a base:
1954
-
1955
- ```ts
1956
- import { DEFAULT_WIDGET_CONFIG, mergeWithDefaults } from '@runtypelabs/persona';
1957
-
1958
- // Option 1: Use defaults with selective overrides
1959
- const controller = initAgentWidget({
1960
- target: '#app',
1961
- config: {
1962
- ...DEFAULT_WIDGET_CONFIG,
1963
- apiUrl: '/api/chat/dispatch',
1964
- theme: {
1965
- ...DEFAULT_WIDGET_CONFIG.theme,
1966
- accent: '#custom-color' // Override only what you need
1967
- }
1968
- }
1969
- });
1970
-
1971
- // Option 2: Use the merge helper
1972
- const controller = initAgentWidget({
1973
- target: '#app',
1974
- config: mergeWithDefaults({
1975
- apiUrl: '/api/chat/dispatch',
1976
- theme: { accent: '#custom-color' }
1977
- })
1978
- });
1979
- ```
1980
-
1981
- This ensures all configuration values are set to sensible defaults while allowing you to customize only what you need.
1982
-
1983
- ### Configuration reference
1984
-
1985
- All options are safe to mutate via `initAgentWidget(...).update(newConfig)`.
1986
-
1987
- For detailed theme styling properties, see [THEME-CONFIG.md](./THEME-CONFIG.md).
1988
-
1989
- #### Core
1990
-
1991
- | Option | Type | Description |
1992
- | --- | --- | --- |
1993
- | `apiUrl` | `string` | Proxy endpoint for your chat backend. Defaults to Runtype's cloud API. |
1994
- | `flowId` | `string` | Runtype flow ID. The client sends it to the proxy to select a specific flow. |
1995
- | `debug` | `boolean` | Emits verbose logs to `console`. Default: `false`. |
1996
- | `headers` | `Record<string, string>` | Static headers forwarded with each request. |
1997
- | `getHeaders` | `() => Record<string, string> \| Promise<...>` | Dynamic headers function called before each request. Use for auth tokens that may change. |
1998
- | `customFetch` | `(url, init, payload) => Promise<Response>` | Replace the default `fetch` entirely. Receives URL, RequestInit, and the payload. |
1999
- | `parseSSEEvent` | `(eventData) => { text?, done?, error? } \| null` | Transform non-standard SSE events into the expected format. Return `null` to ignore an event. |
2000
-
2001
- #### Client Token Mode
2002
-
2003
- When `clientToken` is set, the widget uses `/v1/client/*` endpoints directly from the browser instead of `/v1/dispatch`.
2004
-
2005
- | Option | Type | Description |
2006
- | --- | --- | --- |
2007
- | `clientToken` | `string` | Client token for direct browser-to-API communication (e.g. `ct_live_flow01k7_...`). Mutually exclusive with `headers` auth. |
2008
- | `onSessionInit` | `(session: ClientSession) => void` | Called when the session is initialized. Receives session ID, expiry, flow info. |
2009
- | `onSessionExpired` | `() => void` | Called when the session expires or errors. Prompt the user to refresh. |
2010
- | `getStoredSessionId` | `() => string \| null` | Return a previously stored session ID for session resumption. |
2011
- | `setStoredSessionId` | `(sessionId: string) => void` | Persist the session ID so conversations can be resumed later. |
2012
-
2013
- ```typescript
2014
- config: {
2015
- clientToken: 'ct_live_flow01k7_a8b9c0d1e2f3g4h5i6j7k8l9',
2016
- onSessionInit: (session) => console.log('Session:', session.sessionId),
2017
- onSessionExpired: () => alert('Session expired — please refresh.'),
2018
- getStoredSessionId: () => localStorage.getItem('session_id'),
2019
- setStoredSessionId: (id) => localStorage.setItem('session_id', id)
2020
- }
2021
- ```
2022
-
2023
- #### Agent Mode
2024
-
2025
- Use agent loop execution instead of flow dispatch. Mutually exclusive with `flowId`.
2026
-
2027
- | Option | Type | Description |
2028
- | --- | --- | --- |
2029
- | `agent` | `AgentConfig` | Agent configuration (see sub-table below). Enables agent loop execution. |
2030
- | `agentOptions` | `AgentRequestOptions` | Options for agent execution requests. Default: `{ streamResponse: true, recordMode: 'virtual' }`. |
2031
- | `iterationDisplay` | `'separate' \| 'merged'` | How multi-iteration output is shown. `'separate'`: new bubble per iteration. `'merged'`: single bubble. Default: `'separate'`. |
2032
-
2033
- **`AgentConfig`**
2034
-
2035
- | Property | Type | Description |
2036
- | --- | --- | --- |
2037
- | `name` | `string` | Agent display name. |
2038
- | `model` | `string` | Model identifier (e.g. `'openai:gpt-4o-mini'`). |
2039
- | `systemPrompt` | `string` | System prompt for the agent. |
2040
- | `temperature` | `number?` | Temperature for model responses. |
2041
- | `loopConfig` | `AgentLoopConfig?` | Loop behavior configuration (see below). |
2042
-
2043
- **`AgentLoopConfig`**
2044
-
2045
- | Property | Type | Description |
2046
- | --- | --- | --- |
2047
- | `maxTurns` | `number` | Maximum number of agent turns (1-100). The loop continues while the model calls tools. |
2048
- | `maxCost` | `number?` | Maximum cost budget in USD. Agent stops when exceeded. |
2049
- | `enableReflection` | `boolean?` | Enable periodic reflection during execution. |
2050
- | `reflectionInterval` | `number?` | Number of iterations between reflections (1-50). |
2051
-
2052
- **`AgentToolsConfig`**
2053
-
2054
- | Property | Type | Description |
2055
- | --- | --- | --- |
2056
- | `toolIds` | `string[]?` | Tool IDs to enable (e.g., `"builtin:exa"`, `"builtin:dalle"`). |
2057
- | `toolConfigs` | `Record<string, Record<string, unknown>>?` | Per-tool configuration overrides keyed by tool ID. |
2058
- | `runtimeTools` | `Array<Record<string, unknown>>?` | Inline tool definitions for runtime-defined tools. |
2059
- | `mcpServers` | `Array<Record<string, unknown>>?` | Custom MCP server connections. |
2060
- | `maxToolCalls` | `number?` | Maximum number of tool invocations per execution. |
2061
- | `approval` | `{ require: string[] \| boolean; timeout?: number }?` | Tool approval configuration for human-in-the-loop workflows. |
2062
-
2063
- **`AgentRequestOptions`**
2064
-
2065
- | Property | Type | Description |
2066
- | --- | --- | --- |
2067
- | `streamResponse` | `boolean?` | Stream the response (should be `true` for widget usage). |
2068
- | `recordMode` | `'virtual' \| 'existing' \| 'create'?` | Record persistence mode. |
2069
- | `storeResults` | `boolean?` | Store results server-side. |
2070
- | `debugMode` | `boolean?` | Enable debug mode for additional event data. |
2071
-
2072
- ```typescript
2073
- config: {
2074
- agent: {
2075
- name: 'Research Assistant',
2076
- model: 'qwen/qwen3-8b',
2077
- systemPrompt: 'You are a research assistant with access to web search.',
2078
- tools: { toolIds: ['builtin:exa'] },
2079
- loopConfig: { maxTurns: 5 }
2080
- },
2081
- agentOptions: { streamResponse: true, recordMode: 'virtual' },
2082
- iterationDisplay: 'merged'
2083
- }
2084
- ```
2085
-
2086
- #### UI & Theme
2087
-
2088
- | Option | Type | Description |
2089
- | --- | --- | --- |
2090
- | `theme` | `DeepPartial<PersonaTheme>` | Semantic tokens (`palette`, `semantic`, `components`). See [THEME-CONFIG.md](./THEME-CONFIG.md). Flat v1-style objects are still accepted at runtime (with a console warning) and migrated internally. |
2091
- | `darkTheme` | `DeepPartial<PersonaTheme>` | Dark-mode token overrides, merged over `theme` when the active scheme is dark. |
2092
- | `colorScheme` | `'light' \| 'dark' \| 'auto'` | Color scheme mode. `'auto'` detects from `<html class="dark">` or `prefers-color-scheme`. Default: `'light'`. |
2093
- | `copy` | `{ welcomeTitle?, welcomeSubtitle?, inputPlaceholder?, sendButtonLabel? }` | Customize user-facing text strings. |
2094
- | `autoFocusInput` | `boolean` | Focus the chat input after the panel opens. Skips when voice is active. Default: `false`. |
2095
- | `launcherWidth` | `string` | CSS width for the floating launcher panel (e.g. `'320px'`). Default: `'min(440px, calc(100vw - 24px))'`. |
2096
-
2097
- #### Launcher
2098
-
2099
- Controls the floating launcher button and panel.
2100
-
2101
- | Option | Type | Description |
2102
- | --- | --- | --- |
2103
- | `launcher` | `AgentWidgetLauncherConfig` | Launcher button configuration (see key properties below). See [THEME-CONFIG.md](./THEME-CONFIG.md) for the full list of icon, button, and style properties. |
2104
-
2105
- **Key `launcher` properties**
2106
-
2107
- | Property | Type | Description |
2108
- | --- | --- | --- |
2109
- | `enabled` | `boolean?` | Show the launcher button. |
2110
- | `autoExpand` | `boolean?` | Auto-open the chat panel on load. |
2111
- | `title` | `string?` | Launcher header title text. |
2112
- | `subtitle` | `string?` | Launcher header subtitle text. |
2113
- | `iconUrl` | `string?` | URL for the launcher icon image. |
2114
- | `position` | `'bottom-right' \| 'bottom-left' \| 'top-right' \| 'top-left'?` | Screen corner position. |
2115
- | `mountMode` | `'floating' \| 'docked'?` | Mount as the existing floating launcher or wrap the target with a docked side panel. Default: `'floating'`. |
2116
- | `dock` | `{ side?, width?, animate?, reveal? }?` | Dock layout. Defaults: right / `420px` / `animate: true` / `reveal: 'resize'`. `reveal: 'emerge'` = content column animates like resize but the panel stays fixed `dock.width` (clip-in). `reveal: 'overlay'` = transform overlay; `reveal: 'push'` = sliding track. `animate: false` snaps without transition. |
2117
- | `width` | `string?` | Width of the launcher button. |
2118
- | `fullHeight` | `boolean?` | Fill the full height of the container. Default: `false`. |
2119
- | `sidebarMode` | `boolean?` | Flush sidebar layout with no border-radius or margins. Default: `false`. |
2120
- | `sidebarWidth` | `string?` | Width when `sidebarMode` is true. Default: `'420px'`. |
2121
- | `heightOffset` | `number?` | Pixels to subtract from panel height (for fixed headers, etc.). Default: `0`. |
2122
- | `clearChat` | `AgentWidgetClearChatConfig?` | Clear chat button configuration (enabled, placement, icon, styling). |
2123
- | `border` | `string?` | Border style for the launcher button. Default: `'1px solid #e5e7eb'`. |
2124
- | `shadow` | `string?` | Box shadow for the launcher button. |
2125
- | `collapsedMaxWidth` | `string?` | CSS `max-width` for the floating launcher pill when the panel is closed (title/subtitle truncate with ellipsis; full text in `title` tooltip). Does not affect the open panel (`width`). |
2126
-
2127
- In docked mode, `position`, `fullHeight`, and `sidebarMode` are ignored because the widget fills the dock slot created around the target container.
2128
-
2129
- #### Layout
2130
-
2131
- | Option | Type | Description |
2132
- | --- | --- | --- |
2133
- | `layout` | `AgentWidgetLayoutConfig` | Layout configuration (see sub-properties below). |
2134
-
2135
- **`AgentWidgetLayoutConfig`**
2136
-
2137
- | Property | Type | Description |
2138
- | --- | --- | --- |
2139
- | `showHeader` | `boolean?` | Show/hide the header section entirely. Default: `true`. |
2140
- | `showFooter` | `boolean?` | Show/hide the footer/composer section entirely. Default: `true`. |
2141
- | `header` | `AgentWidgetHeaderLayoutConfig?` | Header customization (see below). |
2142
- | `messages` | `AgentWidgetMessageLayoutConfig?` | Message display customization (see below). |
2143
- | `slots` | `Record<WidgetLayoutSlot, SlotRenderer>?` | Content injection into named slots. |
2144
-
2145
- **`header`** — `AgentWidgetHeaderLayoutConfig`
2146
-
2147
- | Property | Type | Description |
2148
- | --- | --- | --- |
2149
- | `layout` | `'default' \| 'minimal'?` | Header preset. |
2150
- | `showIcon` | `boolean?` | Show/hide the header icon. |
2151
- | `showTitle` | `boolean?` | Show/hide the title. |
2152
- | `showSubtitle` | `boolean?` | Show/hide the subtitle. |
2153
- | `showCloseButton` | `boolean?` | Show/hide the close button. |
2154
- | `showClearChat` | `boolean?` | Show/hide the clear chat button. |
2155
- | `render` | `(ctx: HeaderRenderContext) => HTMLElement?` | Custom renderer that replaces the entire header. |
2156
-
2157
- **`messages`** — `AgentWidgetMessageLayoutConfig`
2158
-
2159
- | Property | Type | Description |
2160
- | --- | --- | --- |
2161
- | `layout` | `'bubble' \| 'flat' \| 'minimal'?` | Message style preset. Default: `'bubble'`. |
2162
- | `avatar` | `{ show?, position?, userAvatar?, assistantAvatar? }?` | Avatar configuration. |
2163
- | `timestamp` | `{ show?, position?, format? }?` | Timestamp configuration. |
2164
- | `groupConsecutive` | `boolean?` | Group consecutive messages from the same role. |
2165
- | `renderUserMessage` | `(ctx: MessageRenderContext) => HTMLElement?` | Custom user message renderer. |
2166
- | `renderAssistantMessage` | `(ctx: MessageRenderContext) => HTMLElement?` | Custom assistant message renderer. |
2167
-
2168
- **Available `slots`**: `header-left`, `header-center`, `header-right`, `body-top`, `messages`, `body-bottom`, `footer-top`, `composer`, `footer-bottom`.
2169
-
2170
- #### Message Display
2171
-
2172
- | Option | Type | Description |
2173
- | --- | --- | --- |
2174
- | `postprocessMessage` | `(ctx: { text, message, streaming, raw? }) => string` | Transform message text before rendering (return HTML). |
2175
- | `markdown` | `AgentWidgetMarkdownConfig` | Markdown rendering configuration (see sub-table). |
2176
- | `messageActions` | `AgentWidgetMessageActionsConfig` | Action buttons on assistant messages (see sub-table). |
2177
- | `loadingIndicator` | `AgentWidgetLoadingIndicatorConfig` | Customize the loading indicator (see sub-table). |
2178
-
2179
- **`markdown`** — `AgentWidgetMarkdownConfig`
2180
-
2181
- | Property | Type | Description |
2182
- | --- | --- | --- |
2183
- | `options` | `AgentWidgetMarkdownOptions?` | Marked parser options: `gfm` (default: `true`), `breaks` (default: `true`), `pedantic`, `headerIds`, `headerPrefix`, `mangle`, `silent`. |
2184
- | `renderer` | `AgentWidgetMarkdownRendererOverrides?` | Custom renderers for elements: `heading`, `code`, `blockquote`, `table`, `link`, `image`, `list`, `listitem`, `paragraph`, `codespan`, `strong`, `em`, `hr`, `br`, `del`, `checkbox`, `html`, `text`. Return `false` to use default. |
2185
- | `disableDefaultStyles` | `boolean?` | Skip all default markdown CSS styles. Default: `false`. |
2186
-
2187
- **`messageActions`** — `AgentWidgetMessageActionsConfig`
2188
-
2189
- | Property | Type | Description |
2190
- | --- | --- | --- |
2191
- | `enabled` | `boolean?` | Enable/disable message actions. Default: `true`. |
2192
- | `showCopy` | `boolean?` | Show copy button. Default: `true`. |
2193
- | `showUpvote` | `boolean?` | Show upvote button. Auto-submitted with `clientToken`. Default: `false`. |
2194
- | `showDownvote` | `boolean?` | Show downvote button. Auto-submitted with `clientToken`. Default: `false`. |
2195
- | `visibility` | `'always' \| 'hover'?` | Button visibility mode. Default: `'hover'`. |
2196
- | `align` | `'left' \| 'center' \| 'right'?` | Horizontal alignment. Default: `'right'`. |
2197
- | `layout` | `'pill-inside' \| 'row-inside'?` | Button layout style. Default: `'pill-inside'`. |
2198
- | `onFeedback` | `(feedback: AgentWidgetMessageFeedback) => void?` | Callback on upvote/downvote. Called in addition to automatic submission with `clientToken`. |
2199
- | `onCopy` | `(message: AgentWidgetMessage) => void?` | Callback on copy. Called in addition to automatic tracking with `clientToken`. |
2200
-
2201
- **`loadingIndicator`** — `AgentWidgetLoadingIndicatorConfig`
2202
-
2203
- | Property | Type | Description |
2204
- | --- | --- | --- |
2205
- | `showBubble` | `boolean?` | Show bubble background around standalone indicator. Default: `true`. |
2206
- | `render` | `(ctx: LoadingIndicatorRenderContext) => HTMLElement \| null?` | Custom render function. Return `null` to hide. Add `data-preserve-animation="true"` for custom animations. |
2207
- | `renderIdle` | `(ctx: IdleIndicatorRenderContext) => HTMLElement \| null?` | Custom idle state renderer (shown when not streaming). Return `null` to hide. |
2208
-
2209
- #### Streaming & Parsing
2210
-
2211
- | Option | Type | Description |
2212
- | --- | --- | --- |
2213
- | `parserType` | `'plain' \| 'json' \| 'regex-json' \| 'xml'` | Built-in parser selector. `'plain'` (default), `'json'` (partial-json), `'regex-json'` (regex-based), `'xml'`. |
2214
- | `streamParser` | `() => AgentWidgetStreamParser` | Custom stream parser factory. Takes precedence over `parserType`. See [Stream Parser Configuration](#stream-parser-configuration). |
2215
- | `enableComponentStreaming` | `boolean` | Update component props incrementally as they stream in. Default: `true`. |
2216
-
2217
- #### Components
2218
-
2219
- | Option | Type | Description |
2220
- | --- | --- | --- |
2221
- | `components` | `Record<string, AgentWidgetComponentRenderer>` | Registry of custom components rendered from JSON directives (`{"component": "Name", "props": {...}}`). Each renderer receives `(props, context)` and returns an `HTMLElement`. Event listeners attached via `addEventListener` (and any other imperative state on the returned element) are preserved across transcript updates — the widget injects the live element directly into the morphed wrapper so listeners survive subsequent re-renders. The renderer is re-invoked when the directive's props change; for state you want to persist across prop changes, hold it in a closure outside the render. |
2222
-
2223
- ```typescript
2224
- config: {
2225
- components: {
2226
- ProductCard: (props, { message, config, updateProps }) => {
2227
- const card = document.createElement('div');
2228
- card.innerHTML = `<h3>${props.title}</h3><p>$${props.price}</p>`;
2229
- return card;
2230
- }
2231
- }
2232
- }
2233
- ```
2234
-
2235
- #### Voice Recognition
2236
-
2237
- | Option | Type | Description |
2238
- | --- | --- | --- |
2239
- | `voiceRecognition` | `AgentWidgetVoiceRecognitionConfig` | Voice input configuration (see sub-table). |
2240
-
2241
- **`voiceRecognition`** — `AgentWidgetVoiceRecognitionConfig`
2242
-
2243
- | Property | Type | Description |
2244
- | --- | --- | --- |
2245
- | `enabled` | `boolean?` | Enable voice recognition. |
2246
- | `pauseDuration` | `number?` | Silence duration (ms) before auto-stop. |
2247
- | `processingText` | `string?` | Placeholder text while processing voice. Default: `'Processing voice...'`. |
2248
- | `processingErrorText` | `string?` | Error text on voice failure. Default: `'Voice processing failed. Please try again.'`. |
2249
- | `autoResume` | `boolean \| 'assistant'?` | Auto-resume listening after playback. `'assistant'` resumes after assistant finishes. |
2250
- | `provider` | `{ type, browser?, runtype?, custom? }?` | Voice provider configuration (see below). |
2251
- | `iconName`, `iconSize`, `iconColor`, `backgroundColor`, `borderColor`, `borderWidth`, `paddingX`, `paddingY`, `tooltipText`, `showTooltip`, `recordingIconColor`, `recordingBackgroundColor`, `recordingBorderColor`, `showRecordingIndicator` | various | Styling options for the voice button. See [THEME-CONFIG.md](./THEME-CONFIG.md). |
2252
-
2253
- **`provider.browser`**
2254
-
2255
- | Property | Type | Description |
2256
- | --- | --- | --- |
2257
- | `language` | `string?` | Recognition language (e.g. `'en-US'`). |
2258
- | `continuous` | `boolean?` | Continuous listening mode. |
2259
-
2260
- **`provider.runtype`**
2261
-
2262
- | Property | Type | Description |
2263
- | --- | --- | --- |
2264
- | `agentId` | `string` | Runtype agent ID for server-side voice. |
2265
- | `clientToken` | `string` | Client token for authentication. |
2266
- | `host` | `string?` | API host override. |
2267
- | `voiceId` | `string?` | Voice ID for TTS. |
2268
- | `pauseDuration` | `number?` | Silence duration (ms) before auto-stop. Default: `2000`. |
2269
- | `silenceThreshold` | `number?` | RMS volume threshold for silence detection. Default: `0.01`. |
2270
-
2271
- ```typescript
2272
- // Browser voice recognition
2273
- config: {
2274
- voiceRecognition: {
2275
- enabled: true,
2276
- provider: { type: 'browser', browser: { language: 'en-US' } }
2277
- }
2278
- }
2279
-
2280
- // Runtype server-side voice
2281
- config: {
2282
- voiceRecognition: {
2283
- enabled: true,
2284
- provider: {
2285
- type: 'runtype',
2286
- runtype: { agentId: 'agent_01abc', clientToken: 'ct_live_...' }
2287
- }
2288
- }
2289
- }
2290
- ```
2291
-
2292
- #### Text-to-Speech
2293
-
2294
- | Option | Type | Description |
2295
- | --- | --- | --- |
2296
- | `textToSpeech` | `TextToSpeechConfig` | TTS configuration (see sub-table). |
2297
-
2298
- **`textToSpeech`** — `TextToSpeechConfig`
2299
-
2300
- | Property | Type | Description |
2301
- | --- | --- | --- |
2302
- | `enabled` | `boolean` | Enable text-to-speech for assistant messages. |
2303
- | `provider` | `'browser' \| 'runtype'?` | `'browser'` uses Web Speech API (default). `'runtype'` delegates to server. |
2304
- | `browserFallback` | `boolean?` | When provider is `'runtype'`, fall back to browser TTS for text-typed responses. Default: `false`. |
2305
- | `voice` | `string?` | Browser TTS voice name (e.g. `'Google US English'`). |
2306
- | `pickVoice` | `(voices: SpeechSynthesisVoice[]) => SpeechSynthesisVoice?` | Custom voice picker when `voice` is not set. |
2307
- | `rate` | `number?` | Speech rate (0.1–10). Default: `1`. |
2308
- | `pitch` | `number?` | Speech pitch (0–2). Default: `1`. |
2309
-
2310
- ```typescript
2311
- config: {
2312
- textToSpeech: {
2313
- enabled: true,
2314
- provider: 'browser',
2315
- voice: 'Google US English',
2316
- rate: 1.2,
2317
- pitch: 1.0
2318
- }
2319
- }
2320
- ```
2321
-
2322
- #### Tool Calls & Approvals
2323
-
2324
- | Option | Type | Description |
2325
- | --- | --- | --- |
2326
- | `toolCall` | `AgentWidgetToolCallConfig` | Styling for tool call bubbles: `backgroundColor`, `borderColor`, `borderWidth`, `borderRadius`, `headerBackgroundColor`, `headerTextColor`, `contentBackgroundColor`, `contentTextColor`, `codeBlockBackgroundColor`, `codeBlockBorderColor`, `codeBlockTextColor`, `toggleTextColor`, `labelTextColor`, and padding options. |
2327
- | `approval` | `AgentWidgetApprovalConfig \| false` | Tool approval bubble configuration. Set to `false` to disable built-in approval handling. |
2328
-
2329
- **`approval`** — `AgentWidgetApprovalConfig`
2330
-
2331
- | Property | Type | Description |
2332
- | --- | --- | --- |
2333
- | `title` | `string?` | Title text above the description. |
2334
- | `approveLabel` | `string?` | Label for the approve button. |
2335
- | `denyLabel` | `string?` | Label for the deny button. |
2336
- | `backgroundColor`, `borderColor`, `titleColor`, `descriptionColor` | `string?` | Bubble styling. |
2337
- | `approveButtonColor`, `approveButtonTextColor` | `string?` | Approve button styling. |
2338
- | `denyButtonColor`, `denyButtonTextColor` | `string?` | Deny button styling. |
2339
- | `parameterBackgroundColor`, `parameterTextColor` | `string?` | Parameters block styling. |
2340
- | `onDecision` | `(data, decision) => Promise<Response \| ReadableStream \| void>?` | Custom approval handler. Return `void` for SDK auto-resolve. |
2341
-
2342
- #### Suggestion Chips
2343
-
2344
- | Option | Type | Description |
2345
- | --- | --- | --- |
2346
- | `suggestionChips` | `string[]` | Render quick reply buttons above the composer. |
2347
- | `suggestionChipsConfig` | `AgentWidgetSuggestionChipsConfig` | Chip styling: `fontFamily` (`'sans-serif' \| 'serif' \| 'mono'`), `fontWeight`, `paddingX`, `paddingY`. |
2348
-
2349
- #### Input & Composer
2350
-
2351
- | Option | Type | Description |
2352
- | --- | --- | --- |
2353
- | `sendButton` | `AgentWidgetSendButtonConfig` | Send button customization: `borderWidth`, `borderColor`, `paddingX`, `paddingY`, `iconText`, `iconName`, `useIcon`, `tooltipText`, `showTooltip`, `backgroundColor`, `textColor`, `size`. |
2354
- | `attachments` | `AgentWidgetAttachmentsConfig` | File attachment configuration (see sub-table). |
2355
- | `formEndpoint` | `string` | Endpoint used by built-in directives. Default: `'/form'`. |
2356
-
2357
- **`attachments`** — `AgentWidgetAttachmentsConfig`
2358
-
2359
- | Property | Type | Description |
2360
- | --- | --- | --- |
2361
- | `enabled` | `boolean?` | Enable file attachments. Default: `false`. |
2362
- | `allowedTypes` | `string[]?` | Allowed MIME types. Default: `['image/png', 'image/jpeg', 'image/gif', 'image/webp']`. |
2363
- | `maxFileSize` | `number?` | Maximum file size in bytes. Default: `10485760` (10 MB). |
2364
- | `maxFiles` | `number?` | Maximum files per message. Default: `4`. |
2365
- | `buttonIconName` | `string?` | Lucide icon name. Default: `'image-plus'`. |
2366
- | `buttonTooltipText` | `string?` | Tooltip text. Default: `'Attach image'`. |
2367
- | `onFileRejected` | `(file, reason: 'type' \| 'size' \| 'count') => void?` | Callback when a file is rejected. |
2368
-
2369
- #### Status Indicator
2370
-
2371
- | Option | Type | Description |
2372
- | --- | --- | --- |
2373
- | `statusIndicator` | `AgentWidgetStatusIndicatorConfig` | Connection status display: `visible`, `idleText`, `connectingText`, `connectedText`, `errorText`. |
2374
-
2375
- #### Features
2376
-
2377
- | Option | Type | Description |
2378
- | --- | --- | --- |
2379
- | `features` | `AgentWidgetFeatureFlags` | Feature flag toggles (see sub-table). |
2380
-
2381
- **`features`** — `AgentWidgetFeatureFlags`
2382
-
2383
- | Property | Type | Description |
2384
- | --- | --- | --- |
2385
- | `showReasoning` | `boolean?` | Show thinking/reasoning bubbles. Default: `true`. |
2386
- | `showToolCalls` | `boolean?` | Show tool usage bubbles. Default: `true`. |
2387
- | `showEventStreamToggle` | `boolean?` | Show the event stream inspector toggle in the header. Default: `false`. |
2388
- | `composerHistory` | `boolean?` | `Up`/`Down` arrows in the composer navigate previously sent user messages for re-entry/editing (shell / Slack style). Entered only when the caret is at the start of the input, so multi-line cursor movement is preserved. Default: `true`. |
2389
- | `eventStream` | `EventStreamConfig?` | Event stream inspector configuration: `badgeColors`, `timestampFormat`, `showSequenceNumbers`, `maxEvents`, `descriptionFields`, `classNames`. |
2390
- | `artifacts` | `AgentWidgetArtifactsFeature?` | Artifact sidebar: `enabled`, `allowedTypes`, optional `layout` (see below). |
2391
-
2392
- **`features.artifacts`** — `AgentWidgetArtifactsFeature`
2393
-
2394
- | Property | Type | Description |
2395
- | --- | --- | --- |
2396
- | `enabled` | `boolean?` | When `true`, shows the artifact pane and handles `artifact_*` SSE events. |
2397
- | `allowedTypes` | `('markdown' \| 'component')[]?` | If set, other artifact kinds are ignored client-side. |
2398
- | `layout` | `AgentWidgetArtifactsLayoutConfig?` | Split/drawer sizing and launcher widen behavior. |
2399
-
2400
- **`features.artifacts.layout`** — `AgentWidgetArtifactsLayoutConfig`
2401
-
2402
- | Property | Type | Description |
2403
- | --- | --- | --- |
2404
- | `splitGap` | `string?` | CSS gap between chat column and artifact pane. Default: `0.5rem`. |
2405
- | `paneWidth` | `string?` | Artifact column width in split mode. Default: `40%`. |
2406
- | `paneMaxWidth` | `string?` | Max width of artifact column. Default: `28rem`. |
2407
- | `paneMinWidth` | `string?` | Optional min width of artifact column. |
2408
- | `narrowHostMaxWidth` | `number?` | If the **panel** is at most this many px wide, artifacts use an in-panel drawer instead of split. Default: `520`. |
2409
- | `expandLauncherPanelWhenOpen` | `boolean?` | When not `false`, the floating panel grows while artifacts are visible (not user-dismissed). Default: widens for launcher mode. |
2410
- | `expandedPanelWidth` | `string?` | CSS width when expanded. Default: `min(720px, calc(100vw - 24px))`. |
2411
- | `resizable` | `boolean?` | When `true`, draggable handle between chat and artifact in desktop split mode. Default: `false`. |
2412
- | `resizableMinWidth` | `string?` | Min artifact width while resizing; `px` only (e.g. `"200px"`). Default: `200px`. |
2413
- | `resizableMaxWidth` | `string?` | Optional max artifact width cap (`px` only); layout still limits by panel width. |
2414
- | `paneAppearance` | `'panel' \| 'seamless'?` | `panel` (default) — bordered sidebar with left border, gap, and shadow. `seamless` — flush with chat: no border or shadow, container background, zero gap (with `resizable`, the drag handle overlays the seam). |
2415
- | `paneBorderRadius` | `string?` | Border radius on the artifact pane. Works with any `paneAppearance`. |
2416
- | `paneShadow` | `string?` | CSS `box-shadow` on the artifact pane. Set `"none"` to suppress the default shadow. |
2417
- | `paneBorder` | `string?` | Full CSS `border` shorthand on the artifact pane (e.g. `"1px solid #cccccc"`). Overrides default/`rounded` borders. If set, `paneBorderLeft` is ignored. |
2418
- | `paneBorderLeft` | `string?` | `border-left` shorthand only — typical for the split edge next to chat (works with or without `resizable`). Example: `"1px solid #cccccc"`. |
2419
- | `unifiedSplitChrome` | `boolean?` | Desktop split only: square the main chat card’s **top-right / bottom-right** radii and round the artifact pane’s **top-right / bottom-right** to match the panel (`--persona-radius-lg`) so both columns read as one shell. |
2420
- | `unifiedSplitOuterRadius` | `string?` | Outer-right radius on the artifact side when `unifiedSplitChrome` is true. If omitted, uses `--persona-radius-lg`, or `paneBorderRadius` when `paneAppearance: 'rounded'`. |
2421
-
2422
- #### State & Storage
2423
-
2424
- | Option | Type | Description |
2425
- | --- | --- | --- |
2426
- | `initialMessages` | `AgentWidgetMessage[]` | Seed the conversation transcript with initial messages. |
2427
- | `persistState` | `boolean \| AgentWidgetPersistStateConfig` | Persist widget state across page navigations. `true` uses defaults (sessionStorage). |
2428
- | `storageAdapter` | `AgentWidgetStorageAdapter` | Custom storage adapter with `load()`, `save(state)`, and `clear()` methods. |
2429
- | `onStateLoaded` | `(state: AgentWidgetStoredState) => AgentWidgetStoredState \| { state: AgentWidgetStoredState; open?: boolean }` | Transform state after loading from storage but before widget initialization. Return `{ state, open: true }` to also open the panel. |
2430
- | `clearChatHistoryStorageKey` | `string` | Additional localStorage key to clear on chat reset. The widget clears `"persona-chat-history"` by default. |
2431
-
2432
- **`persistState`** — `AgentWidgetPersistStateConfig`
2433
-
2434
- | Property | Type | Description |
2435
- | --- | --- | --- |
2436
- | `storage` | `'local' \| 'session'?` | Storage type. Default: `'session'`. |
2437
- | `keyPrefix` | `string?` | Prefix for storage keys. Default: `'persona-'`. |
2438
- | `persist.openState` | `boolean?` | Persist widget open/closed state. Default: `true`. |
2439
- | `persist.voiceState` | `boolean?` | Persist voice recognition state. Default: `true`. |
2440
- | `persist.focusInput` | `boolean?` | Focus input when restoring open state. Default: `true`. |
2441
- | `clearOnChatClear` | `boolean?` | Clear persisted state when chat is cleared. Default: `true`. |
2442
-
2443
- #### Extensibility
2444
-
2445
- | Option | Type | Description |
2446
- | --- | --- | --- |
2447
- | `plugins` | `AgentWidgetPlugin[]` | Plugin array for extending widget functionality. |
2448
- | `contextProviders` | `AgentWidgetContextProvider[]` | Functions that inject additional context into each request payload. |
2449
- | `requestMiddleware` | `AgentWidgetRequestMiddleware` | Transform the request payload before it is sent. |
2450
- | `actionParsers` | `AgentWidgetActionParser[]` | Parse structured directives from assistant messages. |
2451
- | `actionHandlers` | `AgentWidgetActionHandler[]` | Handle parsed actions (navigation, UI updates, etc.). |
2452
-
2453
- ### Stream Parser Configuration
2454
-
2455
- The widget can parse structured responses (JSON, XML, etc.) that stream in chunk by chunk, extracting the `text` field for display. By default, it uses a plain text parser. You can easily select a built-in parser using `parserType`, or provide a custom parser via `streamParser`.
2456
-
2457
- **Key benefits of the unified stream parser:**
2458
- - **Format detection**: Automatically detects if content matches your parser's format
2459
- - **Extensible**: Handle JSON, XML, or any custom structured format
2460
- - **Incremental parsing**: Extract text as it streams in, not just when complete
2461
-
2462
- **Quick start with `parserType` (recommended):**
2463
-
2464
- The easiest way to use a built-in parser is with the `parserType` option:
2465
-
2466
- ```javascript
2467
- import { initAgentWidget } from '@runtypelabs/persona';
2468
-
2469
- const controller = initAgentWidget({
2470
- target: '#chat-root',
2471
- config: {
2472
- apiUrl: '/api/chat/dispatch',
2473
- parserType: 'json' // Options: 'plain', 'json', 'regex-json', 'xml'
2474
- }
2475
- });
2476
- ```
2477
-
2478
- **Using built-in parsers with `streamParser` (ESM/Modules):**
2479
-
2480
- ```javascript
2481
- import { initAgentWidget, createPlainTextParser, createJsonStreamParser, createXmlParser } from '@runtypelabs/persona';
2482
-
2483
- const controller = initAgentWidget({
2484
- target: '#chat-root',
2485
- config: {
2486
- apiUrl: '/api/chat/dispatch',
2487
- streamParser: createJsonStreamParser // Use JSON parser
2488
- // Or: createXmlParser for XML, createPlainTextParser for plain text (default)
2489
- }
2490
- });
2491
- ```
2492
-
2493
- **Using built-in parsers with CDN Script Tags:**
2494
-
2495
- ```html
2496
- <script src="https://cdn.jsdelivr.net/npm/@runtypelabs/persona@latest/dist/index.global.js"></script>
2497
- <script>
2498
- window.AgentWidget.initAgentWidget({
2499
- target: '#chat-root',
2500
- config: {
2501
- apiUrl: '/api/chat/dispatch',
2502
- streamParser: window.AgentWidget.createJsonStreamParser // JSON parser
2503
- // Or: window.AgentWidget.createXmlParser for XML
2504
- // Or: window.AgentWidget.createPlainTextParser for plain text (default)
2505
- }
2506
- });
2507
- </script>
2508
- ```
2509
-
2510
- **Using with automatic installer script:**
2511
-
2512
- ```html
2513
- <script>
2514
- window.siteAgentConfig = {
2515
- target: 'body',
2516
- config: {
2517
- apiUrl: '/api/chat/dispatch',
2518
- parserType: 'json' // Simple way to select parser - no function imports needed!
2519
- }
2520
- };
2521
- </script>
2522
- <script src="https://cdn.jsdelivr.net/npm/@runtypelabs/persona@latest/dist/install.global.js"></script>
2523
- ```
2524
-
2525
- **Alternative: Using `streamParser` with installer script:**
2526
-
2527
- If you need a custom parser, you can still use `streamParser`:
2528
-
2529
- ```html
2530
- <script>
2531
- window.siteAgentConfig = {
2532
- target: 'body',
2533
- config: {
2534
- apiUrl: '/api/chat/dispatch',
2535
- // Note: streamParser must be set after the script loads, or use a function
2536
- streamParser: function() {
2537
- return window.AgentWidget.createJsonStreamParser();
2538
- }
2539
- }
2540
- };
2541
- </script>
2542
- <script src="https://cdn.jsdelivr.net/npm/@runtypelabs/persona@latest/dist/install.global.js"></script>
2543
- ```
2544
-
2545
- Alternatively, you can set it after the script loads:
2546
-
2547
- ```html
2548
- <script>
2549
- window.siteAgentConfig = {
2550
- target: 'body',
2551
- config: {
2552
- apiUrl: '/api/chat/dispatch'
2553
- }
2554
- };
2555
- </script>
2556
- <script src="https://cdn.jsdelivr.net/npm/@runtypelabs/persona@latest/dist/install.global.js"></script>
2557
- <script>
2558
- // Set parser after AgentWidget is loaded
2559
- if (window.siteAgentConfig && window.AgentWidget) {
2560
- window.siteAgentConfig.config.streamParser = window.AgentWidget.createJsonStreamParser;
2561
- }
2562
- </script>
2563
- ```
2564
-
2565
- **Custom JSON parser example:**
2566
-
2567
- ```javascript
2568
- const jsonParser = () => {
2569
- let extractedText = null;
2570
-
2571
- return {
2572
- // Extract text field from JSON as it streams in
2573
- // Return null if not JSON or text not available yet
2574
- processChunk(accumulatedContent) {
2575
- const trimmed = accumulatedContent.trim();
2576
- // Return null if not JSON format
2577
- if (!trimmed.startsWith('{') && !trimmed.startsWith('[')) {
2578
- return null;
2579
- }
2580
-
2581
- const match = accumulatedContent.match(/"text"\s*:\s*"([^"]*(?:\\.[^"]*)*)"/);
2582
- if (match) {
2583
- extractedText = match[1].replace(/\\"/g, '"').replace(/\\n/g, '\n');
2584
- return extractedText;
2585
- }
2586
- return null;
2587
- },
2588
-
2589
- getExtractedText() {
2590
- return extractedText;
2591
- }
2592
- };
2593
- };
2594
-
2595
- initAgentWidget({
2596
- target: '#chat-root',
2597
- config: {
2598
- apiUrl: '/api/chat/dispatch',
2599
- streamParser: jsonParser,
2600
- postprocessMessage: ({ text, raw }) => {
2601
- // raw contains the structured payload (JSON, XML, etc.)
2602
- return markdownPostprocessor(text);
2603
- }
2604
- }
2605
- });
2606
- ```
2607
-
2608
- **Custom XML parser example:**
2609
-
2610
- ```javascript
2611
- const xmlParser = () => {
2612
- let extractedText = null;
2613
-
2614
- return {
2615
- processChunk(accumulatedContent) {
2616
- // Return null if not XML format
2617
- if (!accumulatedContent.trim().startsWith('<')) {
2618
- return null;
2619
- }
2620
-
2621
- // Extract text from <text>...</text> tags
2622
- const match = accumulatedContent.match(/<text[^>]*>([\s\S]*?)<\/text>/);
2623
- if (match) {
2624
- extractedText = match[1];
2625
- return extractedText;
2626
- }
2627
- return null;
2628
- },
2629
-
2630
- getExtractedText() {
2631
- return extractedText;
2632
- }
2633
- };
2634
- };
2635
- ```
2636
-
2637
- **Parser interface:**
2638
-
2639
- ```typescript
2640
- interface AgentWidgetStreamParser {
2641
- // Process a chunk and return extracted text (if available)
2642
- // Return null if the content doesn't match this parser's format or text is not yet available
2643
- processChunk(accumulatedContent: string): Promise<string | null> | string | null;
2644
-
2645
- // Get the currently extracted text (may be partial)
2646
- getExtractedText(): string | null;
2647
-
2648
- // Optional cleanup when parsing is complete
2649
- close?(): Promise<void> | void;
2650
- }
2651
- ```
112
+ The full reference lives in [`docs/`](./docs/) and the theming guide:
2652
113
 
2653
- The parser's `processChunk` method is called for each chunk. If the content matches your parser's format, return the extracted text and the raw payload. Built-in parsers already do this, so action handlers and middleware can read the original structured content without re-implementing a parser. Return `null` if the chunk isn't ready yet—the widget will keep waiting or fall back to plain text.
114
+ - [Programmatic Control & Events](./docs/PROGRAMMATIC-CONTROL.md) controller API, message hooks and injection, enriched DOM context, WebMCP page tools, DOM and controller events, state loading
115
+ - [UI Features & Components](./docs/UI-COMPONENTS.md) — message actions and feedback, loading indicators, ask-user-question, dropdown menus, button utilities, dynamic forms
116
+ - [Script Tag Installation & Framework Integration](./docs/INSTALLATION-FRAMEWORKS.md) — automatic installer, manual script tag setup, React, Next.js, Remix, Gatsby, and Astro guides
117
+ - [Configuration Reference](./docs/CONFIGURATION-REFERENCE.md) — every config option: core, client token mode, agent mode, UI & theme, launcher, layout, voice, tool calls, suggestion chips, state & storage
118
+ - [Stream Parser Configuration](./docs/STREAM-PARSERS.md) — JSON, XML, and plain-text stream parsers and custom parser factories
119
+ - [THEME-CONFIG.md](./THEME-CONFIG.md) — the complete theme and design-token reference
120
+ - [Message Injection](./docs/MESSAGE-INJECTION.md) — full injection and component-directive reference
121
+ - [Dynamic Forms](./docs/DYNAMIC-FORMS.md) — field schema, form styles, and recipes
2654
122
 
2655
123
  ### Optional proxy server
2656
124