wecool-chat 0.7.1 → 0.9.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 (201) hide show
  1. package/CHANGELOG.md +50 -3
  2. package/README.ja.md +161 -13
  3. package/README.md +301 -33
  4. package/dist/CopyIndicator-D50ixqNB.js +407 -0
  5. package/dist/MarkdownBody-eopKrDot.js +19983 -0
  6. package/dist/abort-BjeyCmGn.js +6 -0
  7. package/dist/browser-D1aZQhQL.js +1358 -0
  8. package/dist/core/client.d.ts +46 -2
  9. package/dist/core/client.d.ts.map +1 -1
  10. package/dist/core/consume-stream.d.ts +5 -0
  11. package/dist/core/consume-stream.d.ts.map +1 -1
  12. package/dist/core/debug-logger.d.ts +26 -0
  13. package/dist/core/debug-logger.d.ts.map +1 -0
  14. package/dist/core/error-reporter.d.ts +59 -0
  15. package/dist/core/error-reporter.d.ts.map +1 -0
  16. package/dist/core/global-error-capture.d.ts +10 -0
  17. package/dist/core/global-error-capture.d.ts.map +1 -0
  18. package/dist/core/i18n/messages.d.ts +83 -0
  19. package/dist/core/i18n/messages.d.ts.map +1 -1
  20. package/dist/core/run-conversation.d.ts +12 -0
  21. package/dist/core/run-conversation.d.ts.map +1 -1
  22. package/dist/core/sanitize-user-message.d.ts +11 -0
  23. package/dist/core/sanitize-user-message.d.ts.map +1 -0
  24. package/dist/core/stream-state.d.ts.map +1 -1
  25. package/dist/core/tool-confirmation.d.ts +35 -0
  26. package/dist/core/tool-confirmation.d.ts.map +1 -0
  27. package/dist/core/tool-runner.d.ts +15 -1
  28. package/dist/core/tool-runner.d.ts.map +1 -1
  29. package/dist/core/types.d.ts +168 -4
  30. package/dist/core/types.d.ts.map +1 -1
  31. package/dist/core/widget-origin.d.ts +33 -0
  32. package/dist/core/widget-origin.d.ts.map +1 -0
  33. package/dist/define-DZ0itsfG.js +4 -0
  34. package/dist/index.css +3 -1
  35. package/dist/index.d.ts +5 -1
  36. package/dist/index.d.ts.map +1 -1
  37. package/dist/index.js +8421 -32540
  38. package/dist/loader.d.ts +12 -0
  39. package/dist/loader.d.ts.map +1 -0
  40. package/dist/messages-CveZLPSJ.js +175 -0
  41. package/dist/observe/__tests__/format.test.d.ts +2 -0
  42. package/dist/observe/__tests__/format.test.d.ts.map +1 -0
  43. package/dist/observe/__tests__/http.test.d.ts +2 -0
  44. package/dist/observe/__tests__/http.test.d.ts.map +1 -0
  45. package/dist/observe/__tests__/index.test.d.ts +2 -0
  46. package/dist/observe/__tests__/index.test.d.ts.map +1 -0
  47. package/dist/observe/__tests__/js-error.test.d.ts +2 -0
  48. package/dist/observe/__tests__/js-error.test.d.ts.map +1 -0
  49. package/dist/observe/__tests__/redact.test.d.ts +2 -0
  50. package/dist/observe/__tests__/redact.test.d.ts.map +1 -0
  51. package/dist/observe/__tests__/ring-buffer.test.d.ts +2 -0
  52. package/dist/observe/__tests__/ring-buffer.test.d.ts.map +1 -0
  53. package/dist/observe/format.d.ts +10 -0
  54. package/dist/observe/format.d.ts.map +1 -0
  55. package/dist/observe/index.d.ts +33 -0
  56. package/dist/observe/index.d.ts.map +1 -0
  57. package/dist/observe/observers/http.d.ts +24 -0
  58. package/dist/observe/observers/http.d.ts.map +1 -0
  59. package/dist/observe/observers/js-error.d.ts +22 -0
  60. package/dist/observe/observers/js-error.d.ts.map +1 -0
  61. package/dist/observe/redact.d.ts +27 -0
  62. package/dist/observe/redact.d.ts.map +1 -0
  63. package/dist/observe/ring-buffer.d.ts +20 -0
  64. package/dist/observe/ring-buffer.d.ts.map +1 -0
  65. package/dist/observe/types.d.ts +25 -0
  66. package/dist/observe/types.d.ts.map +1 -0
  67. package/dist/plugin/registry.d.ts.map +1 -1
  68. package/dist/plugin/types.d.ts +19 -1
  69. package/dist/plugin/types.d.ts.map +1 -1
  70. package/dist/plugin.d.ts +1 -1
  71. package/dist/plugin.js +2 -2
  72. package/dist/plugins/page-reader/__tests__/get-meta.test.d.ts +2 -0
  73. package/dist/plugins/page-reader/__tests__/get-meta.test.d.ts.map +1 -0
  74. package/dist/plugins/page-reader/__tests__/index.test.d.ts +2 -0
  75. package/dist/plugins/page-reader/__tests__/index.test.d.ts.map +1 -0
  76. package/dist/plugins/page-reader/__tests__/read-content.test.d.ts +2 -0
  77. package/dist/plugins/page-reader/__tests__/read-content.test.d.ts.map +1 -0
  78. package/dist/plugins/page-reader/__tests__/scroll.test.d.ts +2 -0
  79. package/dist/plugins/page-reader/__tests__/scroll.test.d.ts.map +1 -0
  80. package/dist/plugins/page-reader/index.d.ts +18 -0
  81. package/dist/plugins/page-reader/index.d.ts.map +1 -0
  82. package/dist/plugins/page-reader/tools/get-meta.d.ts +29 -0
  83. package/dist/plugins/page-reader/tools/get-meta.d.ts.map +1 -0
  84. package/dist/plugins/page-reader/tools/read-content.d.ts +34 -0
  85. package/dist/plugins/page-reader/tools/read-content.d.ts.map +1 -0
  86. package/dist/plugins/page-reader/tools/scroll.d.ts +29 -0
  87. package/dist/plugins/page-reader/tools/scroll.d.ts.map +1 -0
  88. package/dist/plugins/page-reader.d.ts +2 -0
  89. package/dist/plugins/page-reader.js +230 -0
  90. package/dist/plugins/qrcode/tool.d.ts +9 -6
  91. package/dist/plugins/qrcode/tool.d.ts.map +1 -1
  92. package/dist/plugins/qrcode.d.ts +1 -1
  93. package/dist/plugins/qrcode.js +121 -100
  94. package/dist/plugins/shared/abort.d.ts +7 -0
  95. package/dist/plugins/shared/abort.d.ts.map +1 -0
  96. package/dist/ui/builtin-tools/get-current-page-info.d.ts.map +1 -1
  97. package/dist/ui/builtin-tools/index.d.ts +1 -1
  98. package/dist/ui/builtin-tools/index.d.ts.map +1 -1
  99. package/dist/ui/builtin-tools/merge-builtin-tools.d.ts +9 -0
  100. package/dist/ui/builtin-tools/merge-builtin-tools.d.ts.map +1 -1
  101. package/dist/ui/commands/builtin-commands.d.ts +46 -0
  102. package/dist/ui/commands/builtin-commands.d.ts.map +1 -0
  103. package/dist/ui/components/ChatErrorBoundary.d.ts +30 -0
  104. package/dist/ui/components/ChatErrorBoundary.d.ts.map +1 -0
  105. package/dist/ui/components/ChatFooter.d.ts +18 -2
  106. package/dist/ui/components/ChatFooter.d.ts.map +1 -1
  107. package/dist/ui/components/ChatHeader.d.ts +14 -1
  108. package/dist/ui/components/ChatHeader.d.ts.map +1 -1
  109. package/dist/ui/components/ChatHeaderMenu.d.ts +7 -2
  110. package/dist/ui/components/ChatHeaderMenu.d.ts.map +1 -1
  111. package/dist/ui/components/ChatPanel.d.ts +35 -4
  112. package/dist/ui/components/ChatPanel.d.ts.map +1 -1
  113. package/dist/ui/components/ChatWidget.d.ts +1 -1
  114. package/dist/ui/components/ChatWidget.d.ts.map +1 -1
  115. package/dist/ui/components/CommandConfirmationCard.d.ts +22 -0
  116. package/dist/ui/components/CommandConfirmationCard.d.ts.map +1 -0
  117. package/dist/ui/components/CommandOverlays.d.ts +28 -0
  118. package/dist/ui/components/CommandOverlays.d.ts.map +1 -0
  119. package/dist/ui/components/CommandPalette.d.ts +25 -0
  120. package/dist/ui/components/CommandPalette.d.ts.map +1 -0
  121. package/dist/ui/components/ConversationSelect.d.ts +15 -0
  122. package/dist/ui/components/ConversationSelect.d.ts.map +1 -0
  123. package/dist/ui/components/CopyIndicator.d.ts +1 -1
  124. package/dist/ui/components/CopyIndicator.d.ts.map +1 -1
  125. package/dist/ui/components/FloatButton.d.ts +1 -1
  126. package/dist/ui/components/FloatButton.d.ts.map +1 -1
  127. package/dist/ui/components/HelpDialogContent.d.ts +7 -0
  128. package/dist/ui/components/HelpDialogContent.d.ts.map +1 -0
  129. package/dist/ui/components/MessageActionsPopover.d.ts +1 -1
  130. package/dist/ui/components/MessageActionsPopover.d.ts.map +1 -1
  131. package/dist/ui/components/MessageAttachments.d.ts +1 -1
  132. package/dist/ui/components/MessageAttachments.d.ts.map +1 -1
  133. package/dist/ui/components/MessageBubble.d.ts +1 -1
  134. package/dist/ui/components/MessageBubble.d.ts.map +1 -1
  135. package/dist/ui/components/MessageCopyButton.d.ts +1 -1
  136. package/dist/ui/components/MessageCopyButton.d.ts.map +1 -1
  137. package/dist/ui/components/MessageEditor.d.ts +1 -1
  138. package/dist/ui/components/MessageEditor.d.ts.map +1 -1
  139. package/dist/ui/components/MessageList.d.ts +6 -1
  140. package/dist/ui/components/MessageList.d.ts.map +1 -1
  141. package/dist/ui/components/MessagePopoverButton.d.ts +1 -1
  142. package/dist/ui/components/MessagePopoverButton.d.ts.map +1 -1
  143. package/dist/ui/components/MessageRow.d.ts +1 -1
  144. package/dist/ui/components/MessageRow.d.ts.map +1 -1
  145. package/dist/ui/components/MessageRowActions.d.ts +1 -1
  146. package/dist/ui/components/MessageRowActions.d.ts.map +1 -1
  147. package/dist/ui/components/ResizeHandles.d.ts +15 -0
  148. package/dist/ui/components/ResizeHandles.d.ts.map +1 -0
  149. package/dist/ui/components/ToolConfirmationCard.d.ts +22 -0
  150. package/dist/ui/components/ToolConfirmationCard.d.ts.map +1 -0
  151. package/dist/ui/components/ToolConfirmationRecord.d.ts +16 -0
  152. package/dist/ui/components/ToolConfirmationRecord.d.ts.map +1 -0
  153. package/dist/ui/components/ToolsDialogContent.d.ts +20 -0
  154. package/dist/ui/components/ToolsDialogContent.d.ts.map +1 -0
  155. package/dist/ui/components/WidgetDialog.d.ts +22 -0
  156. package/dist/ui/components/WidgetDialog.d.ts.map +1 -0
  157. package/dist/ui/components/markdown/CodeBlock.d.ts +1 -1
  158. package/dist/ui/components/markdown/CodeBlock.d.ts.map +1 -1
  159. package/dist/ui/components/markdown/MarkdownBody.d.ts +28 -0
  160. package/dist/ui/components/markdown/MarkdownBody.d.ts.map +1 -0
  161. package/dist/ui/components/markdown/MarkdownMessage.d.ts +13 -14
  162. package/dist/ui/components/markdown/MarkdownMessage.d.ts.map +1 -1
  163. package/dist/ui/components/markdown/trim-autolink-cjk.d.ts +21 -0
  164. package/dist/ui/components/markdown/trim-autolink-cjk.d.ts.map +1 -0
  165. package/dist/ui/hooks/conversationPersistence.d.ts +21 -0
  166. package/dist/ui/hooks/conversationPersistence.d.ts.map +1 -0
  167. package/dist/ui/hooks/resize-geometry.d.ts +42 -0
  168. package/dist/ui/hooks/resize-geometry.d.ts.map +1 -0
  169. package/dist/ui/hooks/use-command-execution.d.ts +38 -0
  170. package/dist/ui/hooks/use-command-execution.d.ts.map +1 -0
  171. package/dist/ui/hooks/use-command-palette.d.ts +45 -0
  172. package/dist/ui/hooks/use-command-palette.d.ts.map +1 -0
  173. package/dist/ui/hooks/use-fullscreen.d.ts +21 -0
  174. package/dist/ui/hooks/use-fullscreen.d.ts.map +1 -0
  175. package/dist/ui/hooks/use-global-error-capture.d.ts +16 -0
  176. package/dist/ui/hooks/use-global-error-capture.d.ts.map +1 -0
  177. package/dist/ui/hooks/use-locale-preference.d.ts +14 -0
  178. package/dist/ui/hooks/use-locale-preference.d.ts.map +1 -0
  179. package/dist/ui/hooks/use-menu-keyboard.d.ts +7 -1
  180. package/dist/ui/hooks/use-menu-keyboard.d.ts.map +1 -1
  181. package/dist/ui/hooks/use-send-message.d.ts +20 -0
  182. package/dist/ui/hooks/use-send-message.d.ts.map +1 -1
  183. package/dist/ui/hooks/use-tool-confirmation.d.ts +22 -0
  184. package/dist/ui/hooks/use-tool-confirmation.d.ts.map +1 -0
  185. package/dist/ui/hooks/use-tool-runner.d.ts +17 -2
  186. package/dist/ui/hooks/use-tool-runner.d.ts.map +1 -1
  187. package/dist/ui/hooks/use-visitor-id.d.ts +10 -0
  188. package/dist/ui/hooks/use-visitor-id.d.ts.map +1 -0
  189. package/dist/ui/hooks/useChatStream.d.ts +35 -0
  190. package/dist/ui/hooks/useChatStream.d.ts.map +1 -1
  191. package/dist/ui/hooks/useConversationList.d.ts +33 -0
  192. package/dist/ui/hooks/useConversationList.d.ts.map +1 -0
  193. package/dist/ui/hooks/useDraggablePanel.d.ts +2 -0
  194. package/dist/ui/hooks/useDraggablePanel.d.ts.map +1 -1
  195. package/dist/ui/hooks/useResizablePanel.d.ts +48 -0
  196. package/dist/ui/hooks/useResizablePanel.d.ts.map +1 -0
  197. package/dist/ui/types.d.ts +6 -0
  198. package/dist/ui/types.d.ts.map +1 -1
  199. package/package.json +43 -27
  200. package/dist/_commonjsHelpers-C6fGbg64.js +0 -6
  201. package/dist/browser-beO7dF90.js +0 -1538
package/README.md CHANGED
@@ -5,7 +5,7 @@
5
5
  [![npm version](https://img.shields.io/npm/v/wecool-chat.svg)](https://www.npmjs.com/package/wecool-chat)
6
6
  [![npm downloads](https://img.shields.io/npm/dm/wecool-chat.svg)](https://www.npmjs.com/package/wecool-chat)
7
7
  [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
8
- [![bundle size](https://img.shields.io/bundlephobia/minzip/wecool-chat.svg)](https://bundlephobia.com/package/wecool-chat)
8
+ [![initial bundle](https://img.shields.io/badge/initial%20bundle-110.2_KB_gzip-brightgreen)](https://www.npmjs.com/package/wecool-chat)
9
9
 
10
10
  > A drop-in LLM chat widget that lets users operate your UI in natural language — works with any framework.
11
11
 
@@ -110,6 +110,59 @@ Since the API key is visible to the client, **restrict the calling origin** in t
110
110
 
111
111
  ---
112
112
 
113
+ ## Drop-in `<script>` tag (no build step)
114
+
115
+ For plain HTML sites, you don't need npm or a bundler. Paste a single `<script>` tag and the
116
+ widget self-initializes. The fastest way to get this snippet is `npx wecool-cli init`, which
117
+ registers your account, issues a key, and copies the tag to your clipboard.
118
+
119
+ ```html
120
+ <script src="https://api.wecool.dev/v1/widget.js" data-api-key="wlt_your_publishable_key"></script>
121
+ ```
122
+
123
+ The hosted bundle (`widget.js`) inlines the library, its styles, and the official plugins into one
124
+ self-contained file, so the widget renders inside a Shadow DOM without touching your page's CSS.
125
+
126
+ ### Attributes
127
+
128
+ | Attribute | Values | Default |
129
+ | --------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------ |
130
+ | `data-api-key` | your publishable key (`wlt_...`) — **required** | — |
131
+ | `data-locale` | `ja` \| `en` | `ja` |
132
+ | `data-theme` | `auto` \| `light` \| `dark` | `auto` |
133
+ | `data-layout` | `floating-bottom-right` \| `floating-bottom-left` \| `floating-top-right` \| `floating-top-left` \| `sidebar-left` \| `sidebar-right` \| `header-banner` \| `footer-fixed` | `floating-bottom-right` |
134
+ | `data-endpoint` | API base URL override (self-hosting) | `https://api.wecool.dev` |
135
+ | `data-plugins` | comma-separated list of official plugins (`qrcode`, `page-reader`). Empty string (`data-plugins=""`) disables all. | `qrcode,page-reader` |
136
+
137
+ ```html
138
+ <script
139
+ src="https://api.wecool.dev/v1/widget.js"
140
+ data-api-key="wlt_your_publishable_key"
141
+ data-locale="en"
142
+ data-theme="dark"
143
+ data-layout="floating-bottom-right"
144
+ ></script>
145
+ ```
146
+
147
+ ### Server-provided tools and official plugins work out of the box
148
+
149
+ The drop-in bundle enables the server-provided tools plus the bundled official plugins — **QR code
150
+ generation** and **page-content reading** — by default, so a pasted tag delivers the most value with
151
+ zero configuration. Toggle plugins with `data-plugins` (e.g. `data-plugins="qrcode"` for QR only, or
152
+ `data-plugins=""` to disable both).
153
+
154
+ ### Limitations
155
+
156
+ - **Custom JavaScript tools require the npm integration.** The `<script>` tag cannot register your own
157
+ functions — for user-defined tools, install `wecool-chat` from npm and pass `tools` to
158
+ `initWecoolChat` / `<ChatWidget>` as shown above.
159
+ - **Content Security Policy.** If the embedding site's CSP forbids external scripts, add
160
+ `https://api.wecool.dev` to `script-src` (and `connect-src` for the API calls), or self-host the
161
+ bundle and point `data-endpoint` at your API.
162
+ - Loading `widget.js` twice on the same page is a no-op — the second tag is ignored.
163
+
164
+ ---
165
+
113
166
  ## Display Modes (Layout Patterns)
114
167
 
115
168
  wecool-chat supports nine official layout patterns. Choose one with the `layout` option on `ChatConfig`.
@@ -144,6 +197,22 @@ initWecoolChat({
144
197
 
145
198
  For `header-banner`, you can add `transparent: true` to overlay the banner on the page content with a translucent background.
146
199
 
200
+ ### Fullscreen mode (floating patterns)
201
+
202
+ In the floating patterns, users can expand the panel to cover the entire viewport: open the header "⋮" menu and toggle **Fullscreen**. Pressing <kbd>Esc</kbd> exits fullscreen first; pressing <kbd>Esc</kbd> again closes the panel. The panel always reopens at its normal size — fullscreen is a transient view state and is never persisted.
203
+
204
+ Fullscreen is implemented as a CSS overlay (`position: fixed; inset: 0`) rather than the browser Fullscreen API, so the host page stays behind the panel and no browser permission prompt is involved. The height tracks `100dvh`, so it follows the collapsing URL bar on iOS Safari.
205
+
206
+ **Host page note**: if you pass a custom `container` element that sits inside an ancestor with `transform`, `filter`, or `contain` styles, `position: fixed` resolves against that ancestor instead of the viewport and fullscreen cannot cover the whole screen. The default mount (no `container` specified) appends the widget directly under `<body>` and is not affected.
207
+
208
+ ### Resizing the panel (floating patterns)
209
+
210
+ In the floating patterns, users can resize the panel by dragging any of its edges or corners with a mouse or pen, just like a browser window. The size is clamped between 320×400px and the viewport (minus a small margin), and follows the viewport when the browser window shrinks. The chosen size lasts for the current page session only — reloading restores the default size.
211
+
212
+ - **Keyboard**: the bottom-right corner handle is focusable; use arrow keys (8px), <kbd>Shift</kbd>+arrows (32px), and <kbd>Home</kbd> to reset the size.
213
+ - **Touch devices**: resizing is intentionally not offered on touch-primary devices (thin edge handles cannot be grabbed precisely and would conflict with scroll/pinch gestures). Handles are hidden there, and finger touches on hybrid devices (touch laptops) are ignored — use fullscreen mode instead for a larger view.
214
+ - **Reset**: the header "⋮" menu item **Reset position and size** restores both the dragged position and the resized dimensions.
215
+
147
216
  ### React equivalent
148
217
 
149
218
  When you use `<ChatWidget />` directly, pass `floating` / `position` as before; the `layout` field is consumed by `initWecoolChat` and translates to those props for you. The dedicated `sidebar-*` / `header-banner` / `footer-fixed` patterns are only available through `initWecoolChat` because they need a wrapper element on the host DOM.
@@ -222,7 +291,7 @@ The core of wecool-chat is the "tool definition". The LLM reads the list of tool
222
291
 
223
292
  ### Basic shape
224
293
 
225
- The `Tool` type has 4 fields.
294
+ The `Tool` type has 4 required fields.
226
295
 
227
296
  ```ts
228
297
  type Tool = {
@@ -230,9 +299,38 @@ type Tool = {
230
299
  description: string; // What the LLM uses to decide when to call this tool
231
300
  parameters: ToolParameters; // JSON Schema for arguments
232
301
  handler: (args: Record<string, unknown>) => unknown | Promise<unknown>;
302
+ requiresConfirmation?: boolean; // Ask the user before running (see below)
303
+ confirmationMessage?: string; // Text shown in the confirmation card
304
+ displayName?: LocalizedText; // Visitor-facing name shown in /tools (UI only, never sent to the LLM)
305
+ exampleQueries?: LocalizedText[]; // Example prompts shown in /tools (UI only, never sent to the LLM)
233
306
  };
234
307
  ```
235
308
 
309
+ ### Display metadata for `/tools`
310
+
311
+ `displayName` and `exampleQueries` power the [`/tools`](#slash-commands) list, which helps visitors discover "what they can ask". They are **UI-only** metadata — they are never included in the request body sent to the LLM (the request is built from `name` / `description` / `parameters` only), so it is safe to write them in the site's display language.
312
+
313
+ Both accept a `LocalizedText`, which is either a plain string or a per-locale map. Values are resolved in the order **current locale → the other locale**; if neither `displayName` is defined, the English `description` is shown as a fallback.
314
+
315
+ ```ts
316
+ type LocalizedText = string | Partial<Record<"ja" | "en", string>>;
317
+
318
+ {
319
+ name: "set_theme",
320
+ description: "Change the color theme. ...", // English (protocol string, sent to the LLM)
321
+ parameters: { /* ... */ },
322
+ handler: handleSetTheme,
323
+ // UI-only, follows /lang; safe to localize
324
+ displayName: { ja: "テーマの切り替え", en: "Switch theme" },
325
+ exampleQueries: [
326
+ { ja: "ダークモードにして", en: "Switch to dark mode" },
327
+ { ja: "明るいテーマにして", en: "Use a light theme" },
328
+ ],
329
+ }
330
+ ```
331
+
332
+ Clicking an example inserts it into the input field (it is **not** auto-sent), leaving the visitor free to edit before sending. Built-in utility tools (e.g. page-info) are excluded from `/tools`. Plugin tools may declare the same two fields.
333
+
236
334
  ### How you write `description` determines accuracy
237
335
 
238
336
  The LLM reads the `description` to decide "when to use this tool". **Including examples of how the user might phrase it** improves accuracy.
@@ -303,6 +401,37 @@ const config = {
303
401
 
304
402
  > **Note**: Receiving an `AbortSignal` inside `handler` to cancel work is not supported in the current version. Keep heavy work lightweight on the handler side.
305
403
 
404
+ ### Confirmation before destructive actions (`requiresConfirmation`)
405
+
406
+ LLMs occasionally misread instructions — especially negations like _"don't submit it yet"_ — and may call a tool the user did not intend. For tools whose effect is destructive or hard to undo, declare `requiresConfirmation: true`. Before running the handler, the widget shows an inline confirmation card ("Run" / "Cancel") in the chat:
407
+
408
+ ```ts
409
+ {
410
+ name: "clear_form",
411
+ description: "Clears the contact form. ...",
412
+ parameters: { type: "object", properties: {} },
413
+ handler: handleClearForm,
414
+ requiresConfirmation: true,
415
+ confirmationMessage: "This will clear everything you entered in the form. Do you want to continue?",
416
+ }
417
+ ```
418
+
419
+ - **Approve** → the handler runs as usual and the LLM narrates the result.
420
+ - Either way, the card is replaced by an **immutable record line** (the confirmation message plus "Approved" / "Cancelled") so the decision stays visible in the thread and cannot be re-triggered.
421
+ - **Cancel** → the handler is never called. The LLM receives a structured "the user declined" result and responds naturally; the conversation continues.
422
+ - Waiting for confirmation has **no timeout** (`toolTimeout` applies only after approval), and the Stop button still aborts the whole turn.
423
+ - Tools without the flag behave exactly as before.
424
+
425
+ **Which tools should require confirmation?**
426
+
427
+ | Declare `requiresConfirmation: true` | Leave it off |
428
+ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ---------------------------------------------------------------------------------------------------------- |
429
+ | Deleting or clearing user input (forms, carts, drafts), overwriting saved data, submitting/sending to external systems (orders, emails, payments), anything hard to undo | Read-only queries, display changes (theme, sort, filter, navigation), anything the user can trivially undo |
430
+
431
+ Do not gate everything: a confirmation on every tool call turns the assistant into a click-through dialog and users stop reading the prompts. Reserve it for actions with real cost.
432
+
433
+ **Always set `confirmationMessage`.** Tool names like `clear_form` are developer vocabulary; without a message the widget falls back to a generic prompt plus the tool name. Write a complete sentence in the language of your site (it is a UI string, so match `locale` — unlike tool `description`s, which should stay in English). The string is sanitized (control characters stripped, max 2,000 chars).
434
+
306
435
  ### Built-in tools
307
436
 
308
437
  wecool-chat ships ready-to-use tools that are **registered automatically**. You don't need to import or add them to the `tools` array — `ChatWidget` injects them for you.
@@ -490,6 +619,84 @@ Cancellation only throws `AbortError` — every other failure is returned as `{
490
619
 
491
620
  **Bundle impact**: the `qrcode` library lives inside `dist/plugins/qrcode.js` and its associated chunks under `dist/` (~14 KB gzipped in total). The core widget bundle (`dist/index.js`) does **not** pull it in. The plugin code itself loads `qrcode` only when the tool is actually invoked.
492
621
 
622
+ #### `wecool-chat/plugins/page-reader`
623
+
624
+ Read page content, retrieve meta/OGP information, and scroll the host page — all driven by natural language. The LLM decides which tool to invoke.
625
+
626
+ ```tsx
627
+ import { initWecoolChat } from "wecool-chat";
628
+ import { createPageReaderPlugin } from "wecool-chat/plugins/page-reader";
629
+
630
+ initWecoolChat({
631
+ endpoint: "https://your-api.example.com/chat",
632
+ plugins: [createPageReaderPlugin()],
633
+ });
634
+ ```
635
+
636
+ | Option | Type | Default | Description |
637
+ | ------------------ | -------- | ------- | --------------------------------------------------- |
638
+ | `defaultMaxLength` | `number` | `5000` | Max characters for `read_page_content` |
639
+ | `scrollAmount` | `number` | `0.5` | Viewport ratio for `up_a_bit` / `down_a_bit` scroll |
640
+
641
+ **Registered tools:**
642
+
643
+ | Tool | Description |
644
+ | ------------------- | --------------------------------------------------------------------- |
645
+ | `read_page_content` | Extract visible text from the current page (or a CSS-selected region) |
646
+ | `get_meta_info` | Retrieve URL, title, description, OGP tags, and canonical URL |
647
+ | `scroll_page` | Scroll to top/bottom, up/down a bit, or to a specific CSS selector |
648
+
649
+ **Limitations:**
650
+
651
+ - Shadow DOM and cross-origin iframe content cannot be read
652
+ - `scroll_page` targets the host page viewport only (not scrollable child elements)
653
+ - `scrollY` in the result may be a mid-scroll value when `behavior: "smooth"` is active
654
+
655
+ **Bundle impact**: `dist/plugins/page-reader.js` is ~2.4 KB gzipped with zero external dependencies. The core widget bundle is not affected.
656
+
657
+ ---
658
+
659
+ ## Page observation (`observe`) — automatic support context
660
+
661
+ The widget can observe client-side failure signals on the host page (HTTP `4xx`/`5xx`
662
+ responses and JavaScript errors — uncaught exceptions, unhandled rejections, and
663
+ `console.error`) and automatically attach a short summary of "what is currently going
664
+ wrong on this page" to the message sent to the LLM. This lets the assistant answer a vague
665
+ "the checkout button doesn't work" with an accurate first reply instead of many rounds of
666
+ questions.
667
+
668
+ - **On by default.** Using the widget enables observation. No extra flag.
669
+ - The background summary is attached to the message **sent to the LLM only** — the visitor's
670
+ chat transcript shows just their raw message.
671
+ - Only the **fact** of a failure is recorded (method/URL/status, error name/message). **Form
672
+ input values are never recorded.** URLs and error text are **redacted** (tokens, API keys,
673
+ email addresses, and token-like strings are masked) before being sent.
674
+ - Observation data is **not sent to any wecool server** — it is passed to the LLM once, at
675
+ send time, together with the visitor's message. Note this means the observed signals **are
676
+ sent to your configured LLM provider** as part of the chat request.
677
+
678
+ ```tsx
679
+ // default: observation on
680
+ initWecoolChat({ endpoint, tools: [] });
681
+
682
+ // turn it off entirely
683
+ initWecoolChat({ endpoint, tools: [], observe: false });
684
+
685
+ // per-channel
686
+ initWecoolChat({ endpoint, tools: [], observe: { http: true, errors: false } });
687
+ ```
688
+
689
+ **Privacy / consent (your responsibility):** because observation is on by default and not
690
+ gated on visitor consent, in regions where consent is required (GDPR / ePrivacy) you must
691
+ wire your own consent basis (e.g. a cookie banner) and set `observe: false` until consent is
692
+ granted. Flipping `observe` to `false` at runtime stops observation and discards the buffered
693
+ signals.
694
+
695
+ **Fixed-at-startup constraints:** the same startup-time constraints as locale/plugins apply —
696
+ `observe` is resolved when the widget mounts. Changing it requires re-initializing the widget.
697
+
698
+ **Bundle impact**: observation adds ~1.8 KB gzipped to the core bundle.
699
+
493
700
  ---
494
701
 
495
702
  ## Framework Guides
@@ -508,9 +715,7 @@ onMounted(() => {
508
715
  dispose = initWecoolChat({
509
716
  endpoint: "https://api.wecool.dev",
510
717
  apiKey: import.meta.env.VITE_WECOOL_API_KEY,
511
- tools: [
512
- /* ... */
513
- ],
718
+ tools: [/* ... */],
514
719
  });
515
720
  });
516
721
 
@@ -578,9 +783,7 @@ onUnmounted(() => dispose?.());
578
783
  const dispose = initWecoolChat({
579
784
  endpoint: "https://api.wecool.dev",
580
785
  apiKey: "<your-api-key>",
581
- tools: [
582
- /* ... */
583
- ],
786
+ tools: [/* ... */],
584
787
  });
585
788
  // window.addEventListener("beforeunload", () => dispose());
586
789
  </script>
@@ -607,9 +810,7 @@ export function Chat() {
607
810
  dispose.current = initWecoolChat({
608
811
  endpoint: process.env.NEXT_PUBLIC_API_URL!,
609
812
  apiKey: process.env.NEXT_PUBLIC_WECOOL_API_KEY,
610
- tools: [
611
- /* ... */
612
- ],
813
+ tools: [/* ... */],
613
814
  });
614
815
  // Don't forget cleanup
615
816
  return () => dispose.current?.();
@@ -646,25 +847,27 @@ const ChatWidget = dynamic(() => import("wecool-chat").then((m) => m.ChatWidget)
646
847
 
647
848
  ## ChatConfig Options
648
849
 
649
- | Property | Type | Required | Default | Description |
650
- | -------------------- | ------------------------------- | -------- | ----------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
651
- | `endpoint` | `string` | ✓ | — | API endpoint URL (must be HTTPS; `http://localhost` and `http://127.0.0.1` are allowed for development) |
652
- | `apiKey` | `string` | | — | API key issued from the dashboard |
653
- | `tools` | `Tool[]` | ✓ | — | Array of tool definitions |
654
- | `locale` | `"ja" \| "en"` | | `"ja"` | UI language. Set `"en"` for English |
655
- | `placeholder` | `string` | | depends on `locale` | Input field placeholder |
656
- | `theme` | `"auto" \| "light" \| "dark"` | | `"light"` | Color theme. `"auto"` follows OS dark-mode |
657
- | `className` | `string` | | — | Class name applied to the root element |
658
- | `toolTimeout` | `number` | | `30000` | Tool execution timeout (ms) |
659
- | `disableShadowDom` | `boolean` | | `false` | Mount to normal DOM instead of Shadow DOM |
660
- | `layout` | `LayoutPattern` | | `floating-bottom-right` | One of the nine layout patterns. See [Display Modes](#display-modes-layout-patterns). |
661
- | `transparent` | `boolean` | | `false` | Only meaningful for `layout: "header-banner"`. Renders a translucent background that overlays the page content. |
662
- | `narrateToolResults` | `boolean` | | `false` | After every tool result, make an extra LLM call with `tool_choice: "none"` so the model emits a short narration text. See [section](#narrate-tool-results) below for trade-offs. |
663
- | `plugins` | `ChatPlugin[]` | | `[]` | Plugins to load. See the [Plugins](#plugins) section. |
664
- | `onToolExecute` | `(name, args) => void` | | — | Callback fired right before tool execution |
665
- | `onToolResult` | `(name, result) => void` | | — | Callback fired after tool execution finishes |
666
- | `onMessagesChange` | `(messages: Message[]) => void` | | — | Fires whenever the internal `messages` list changes. Use this to mirror the conversation into your own host UI (often paired with `layout: "input-only"`). |
667
- | `onError` | `(error: Error) => void` | | — | Callback fired on error |
850
+ | Property | Type | Required | Default | Description |
851
+ | --------------------- | ------------------------------- | -------- | ----------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
852
+ | `endpoint` | `string` | ✓ | — | API endpoint URL (must be HTTPS; `http://localhost` and `http://127.0.0.1` are allowed for development) |
853
+ | `apiKey` | `string` | | — | API key issued from the dashboard |
854
+ | `tools` | `Tool[]` | ✓ | — | Array of tool definitions |
855
+ | `locale` | `"ja" \| "en"` | | `"ja"` | UI language. Set `"en"` for English |
856
+ | `placeholder` | `string` | | depends on `locale` | Input field placeholder |
857
+ | `theme` | `"auto" \| "light" \| "dark"` | | `"light"` | Color theme. `"auto"` follows OS dark-mode |
858
+ | `className` | `string` | | — | Class name applied to the root element |
859
+ | `toolTimeout` | `number` | | `30000` | Tool execution timeout (ms) |
860
+ | `disableShadowDom` | `boolean` | | `false` | Mount to normal DOM instead of Shadow DOM |
861
+ | `layout` | `LayoutPattern` | | `floating-bottom-right` | One of the nine layout patterns. See [Display Modes](#display-modes-layout-patterns). |
862
+ | `transparent` | `boolean` | | `false` | Only meaningful for `layout: "header-banner"`. Renders a translucent background that overlays the page content. |
863
+ | `narrateToolResults` | `boolean` | | `false` | After every tool result, make an extra LLM call with `tool_choice: "none"` so the model emits a short narration text. See [section](#narrate-tool-results) below for trade-offs. |
864
+ | `persistConversation` | `"tab"` | | — | Keep the conversation across page navigations and reloads within the same tab (stored in `sessionStorage`, restored on mount). Closing the tab ends it; other tabs get their own conversation. |
865
+ | `errorReporting` | `boolean` | | `true` | Report widget-internal errors (warn+) to `POST /api/client-errors`. No message content / raw API key / host activity is sent. Set `false` to disable. See [Error collection](#error-collection). |
866
+ | `plugins` | `ChatPlugin[]` | | `[]` | Plugins to load. See the [Plugins](#plugins) section. |
867
+ | `onToolExecute` | `(name, args) => void` | | — | Callback fired right before tool execution |
868
+ | `onToolResult` | `(name, result) => void` | | — | Callback fired after tool execution finishes |
869
+ | `onMessagesChange` | `(messages: Message[]) => void` | | — | Fires whenever the internal `messages` list changes. Use this to mirror the conversation into your own host UI (often paired with `layout: "input-only"`). |
870
+ | `onError` | `(error: Error) => void` | | — | Callback fired on error |
668
871
 
669
872
  ### Narrate tool results
670
873
 
@@ -691,6 +894,49 @@ Trade-offs:
691
894
 
692
895
  ---
693
896
 
897
+ ## Error collection
898
+
899
+ wecool-chat reports **widget-internal errors** (warning level and above) to your own API's
900
+ error-collection endpoint so you can correlate a user's symptom with a single backend log line.
901
+ It is **enabled by default** and can be turned off with `errorReporting: false`.
902
+
903
+ ```ts
904
+ initWecoolChat({
905
+ endpoint: "https://api.wecool.dev",
906
+ apiKey: "...",
907
+ tools,
908
+ errorReporting: false, // opt out of error collection entirely
909
+ });
910
+ ```
911
+
912
+ ### What is (and isn't) collected
913
+
914
+ Reports are sent **only** to your configured `endpoint` (`POST /api/client-errors`), **only** when
915
+ an error actually occurs, and are **discarded on send failure** (no retry, no local storage — one
916
+ error, one send attempt).
917
+
918
+ Each request also carries an `X-Request-Id` header that wecool-chat generates per request; the same
919
+ ID is used by the API in its logs and response, so you can trace "this screen's error" to the exact
920
+ backend log entry.
921
+
922
+ Collected fields:
923
+
924
+ | Included | Not included (never sent) |
925
+ | ------------------------------------------------------------------------------------------ | --------------------------------------------------- |
926
+ | Error `message` / `name` / `stack` (truncated to 5KB), application `errorCode` | **Message content / chat history** (no PII) |
927
+ | `version`, `requestId`, `sessionId`, `fingerprint` | **Raw API key** (only a masked `abcd…wxyz` is sent) |
928
+ | `hostOrigin` (origin only), `userAgent`, `network` info, `messageCount`, `streamingActive` | **Host-site activity** (clicks, page navigation) |
929
+ | | **Page URL / path** (path segments can carry PII) |
930
+
931
+ **Errors originating from the host site itself** (scripts outside the widget bundle) are **not**
932
+ sent. Origin is determined from both the stack trace and the event source; when it can't be
933
+ determined, the report is dropped rather than sent.
934
+
935
+ `sessionId` is kept in `localStorage`. If storage is unavailable (e.g. private browsing), a fresh
936
+ ID is generated per report and sending still proceeds.
937
+
938
+ ---
939
+
694
940
  ## Customization
695
941
 
696
942
  ### Locale and labels
@@ -709,6 +955,30 @@ const config = {
709
955
 
710
956
  If `placeholder` is provided, it takes precedence over the locale's default placeholder.
711
957
 
958
+ **Runtime language switching (`/lang`).** Visitors can switch the widget language at runtime with the `/lang ja` / `/lang en` slash commands (see [Slash commands](#slash-commands)). The chosen language is persisted per-site in the browser (`localStorage` key `wecool-chat:locale`). On the next visit the saved choice takes precedence over `config.locale`, so the initial locale resolves in this order:
959
+
960
+ 1. Saved value in `localStorage` (visitor's previous `/lang` choice)
961
+ 2. `config.locale` (host default)
962
+ 3. `"ja"` (fallback)
963
+
964
+ If `localStorage` is unavailable (e.g. private mode), the switch still applies for the current session but is not persisted. All display strings, `aria-label`s, `placeholder`, and the root `lang` attribute follow the switch immediately.
965
+
966
+ > **Known limitation.** The locale passed to plugins is fixed at startup and does **not** follow a `/lang` switch (the public plugin API shape is intentionally kept stable). Likewise, confirmation strings you bake into a tool definition (`confirmationMessage`) do not re-resolve on switch. These only surface during tool confirmation, so the impact is limited.
967
+
968
+ ### Slash commands
969
+
970
+ Typing `/` at the **start** of the input field opens a command palette. Type to filter (`/cl` narrows to `/clear`), navigate with ↑/↓, confirm with Enter, close with Esc (your input is kept), and complete the highlighted command with Tab. A `/`-prefixed input that matches no command is sent as a normal message. The palette does not open for a `/` in the middle of text, while an IME is composing, or while a response is generating.
971
+
972
+ | Command | Effect |
973
+ | ----------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
974
+ | `/tools` | Show what visitors can ask, with a display name and example prompts per tool. Clicking an example inserts it into the input (it is **not** auto-sent). |
975
+ | `/clear` | Ask for confirmation, then clear the current conversation from view and start a new one. Past conversations remain accessible from the conversation selector (this is not a server-side delete). |
976
+ | `/new` | Start a new conversation immediately (no confirmation). |
977
+ | `/lang ja` / `/lang en` | Switch the widget display language and persist the choice (see above). |
978
+ | `/help` | Show the command list and how to use it. |
979
+
980
+ To make `/tools` useful, give each tool a visitor-facing display name and example prompts (see [Display metadata for `/tools`](#display-metadata-for-tools)).
981
+
712
982
  ### Colors / theme
713
983
 
714
984
  Switch the built-in color theme with `config.theme`:
@@ -788,9 +1058,7 @@ const history = [createUserMessage("switch to dark mode")];
788
1058
 
789
1059
  for await (const event of client.chat({
790
1060
  message: "switch to dark mode",
791
- tools: [
792
- /* ToolDefinition[] */
793
- ],
1061
+ tools: [/* ToolDefinition[] */],
794
1062
  history,
795
1063
  })) {
796
1064
  switch (event.type) {