llm_meta_widget 0.6.1 → 0.7.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.
@@ -1,1473 +1,46 @@
1
- <%# Chat-panel widget for the client-orchestrated flow. Render via the %>
2
- <%# llm_meta_widget helper — see llm_meta_widget_helper.rb for options. %>
1
+ <%# Renders the widget as a custom element. Everything that used to live here — %>
2
+ <%# 360 lines of CSS, 21 lines of markup and 1,450 lines of script — moved into %>
3
+ <%# app/assets/javascripts/llm_meta_widget/element.js and is bundled into one %>
4
+ <%# ES module, so a non-Rails host can use the same widget with two lines of %>
5
+ <%# HTML. See docs/custom-element-distribution.md. %>
3
6
  <%# %>
4
- <%# Required locals: base_url, model. %>
5
- <%# Optional locals (helper defaults): %>
6
- <%# api_key_uuid, orchestrator_path, actions_schema_id, state_global, %>
7
- <%# actions_global, remote_tools_schema_id, well_known_urls, max_rounds. %>
7
+ <%# Render via the llm_meta_widget helper, which maps its keyword options onto %>
8
+ <%# the attributes below — see app/helpers/llm_meta_widget/widget_helper.rb. %>
8
9
  <%# %>
9
- <%# The host page must ALSO provide: %>
10
- <%# (a) a JSON schema block with id = actions_schema_id, listing the %>
11
- <%# local action set (name/description/input_schema each). %>
10
+ <%# The host page must still provide, because these belong to the host and not %>
11
+ <%# to the element: %>
12
+ <%# (a) a JSON schema block with id = actions_schema_id, listing the local %>
13
+ <%# action set (name/description/input_schema each). %>
12
14
  <%# (b) window.aiState — reader functions called each turn. %>
13
- <%# (c) window.aiActions — action implementations invoked after the LLM %>
14
- <%# turn completes. %>
15
+ <%# (c) window.aiActions — action implementations invoked after the LLM turn. %>
15
16
  <%# %>
16
17
  <%# NOTE on ERB comments: DO NOT consolidate these lines into one <%_# ... %_> %>
17
18
  <%# block. Rails-ERB comment blocks terminate at the FIRST closing `%_>`, so %>
18
19
  <%# any nested <%_= ... %_> inside cuts them short and the trailing lines leak %>
19
- <%# into rendered HTML — including any literal `<script>` text, which then %>
20
- <%# swallows the widget div. One line per comment keeps them self-terminating. %>
21
-
22
- <%# Bubble/thinking/role-label styles come from the shared conversation.css %>
23
- <%# — the canonical "chat conversation" surface owned by this gem. See %>
24
- <%# comment in /llm_meta_widget_assets/conversation.css. The widget's %>
25
- <%# outer div opts in via class="llm-meta-conversation" (below). %>
26
- <link rel="stylesheet" href="/llm_meta_widget_assets/conversation.css">
27
-
28
- <style>
29
- /* Widget-specific chrome — floating container, header, scroll region,
30
- * input area. Everything BUBBLE / THINKING / ROLE-related lives in the
31
- * shared conversation.css above. */
32
- #llm-meta-widget-chat {
33
- /* Positioned via JS on open (see setOpen()) so top/left are set in
34
- * pixels — required for CSS `resize: both` to grow correctly
35
- * (bottom/right anchoring blocks the resize handle from being
36
- * dragged outward from viewport corner). */
37
- position: fixed;
38
- width: 40em; height: 55vh;
39
- min-width: 24em; min-height: 16em;
40
- max-width: calc(100vw - 2em); max-height: calc(100vh - 2em);
41
- background: #ffffff;
42
- border: 1px solid #e5e7eb;
43
- border-radius: 8px;
44
- box-shadow: 0 4px 16px rgba(0, 0, 0, 0.12);
45
- padding: 10px;
46
- z-index: 9999;
47
- font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;
48
- font-size: 14px;
49
- color: #1f2937;
50
- display: flex; flex-direction: column;
51
- /* Native drag-to-resize handle appears at bottom-right when
52
- * overflow != visible. overflow:hidden clips at widget edge; the
53
- * inner .lmw-messages has its own scroll so no content is lost. */
54
- resize: both;
55
- overflow: hidden;
56
- }
57
- #llm-meta-widget-chat.lmw-collapsed { display: none; }
58
-
59
- /* Collapsed-state toggle — a small floating chat-bubble button in the
60
- * bottom-right corner. Always in the DOM; visible only when the chat
61
- * panel is collapsed. Click to open the chat panel; the panel's × button
62
- * collapses back to this. State persists across page loads via
63
- * localStorage (see the JS below). */
64
- #llm-meta-widget-toggle {
65
- position: fixed; bottom: 1em; right: 1em;
66
- width: 52px; height: 52px;
67
- border-radius: 26px;
68
- background-color: #3b82f6;
69
- color: white;
70
- border: none;
71
- box-shadow: 0 4px 12px rgba(0, 0, 0, 0.18);
72
- cursor: pointer;
73
- z-index: 9999;
74
- display: flex; align-items: center; justify-content: center;
75
- transition: background-color 0.15s, transform 0.1s;
76
- }
77
- #llm-meta-widget-toggle:hover { background-color: #2563eb; }
78
- #llm-meta-widget-toggle:active { transform: scale(0.96); }
79
- #llm-meta-widget-toggle.lmw-hidden { display: none; }
80
- #llm-meta-widget-toggle svg { display: block; }
81
-
82
- /* Header hide/close: a subtle "−" button that collapses to the toggle
83
- * bubble. Sits between the "clear" button and title. */
84
- #llm-meta-widget-chat .lmw-hide {
85
- background: none; border: none;
86
- color: #6b7280;
87
- font: inherit; font-size: 18px; line-height: 1;
88
- cursor: pointer;
89
- padding: 0 8px;
90
- transition: color 0.15s;
91
- }
92
- #llm-meta-widget-chat .lmw-hide:hover { color: #1f2937; }
93
- #llm-meta-widget-chat .lmw-header {
94
- display: flex; justify-content: space-between; align-items: center;
95
- gap: 8px;
96
- padding-bottom: 8px; margin-bottom: 8px;
97
- border-bottom: 2px solid #e5e7eb;
98
- }
99
- #llm-meta-widget-chat .lmw-header-right { display: flex; align-items: center; gap: 4px; flex-shrink: 0; }
100
-
101
- /* Level-1 pickers row — matches chat.aibranch.org's input-container
102
- * convention (attach / model / tools / settings in a horizontal row
103
- * below the textarea). We only render model + tools for now. Uses
104
- * relative positioning so the tools <details> panel can drop down
105
- * as a floating overlay instead of pushing the input area around. */
106
- #llm-meta-widget-chat .lmw-input-controls {
107
- display: flex;
108
- align-items: center;
109
- gap: 6px;
110
- margin-top: 6px;
111
- position: relative;
112
- min-height: 26px;
113
- }
114
- #llm-meta-widget-chat .lmw-title { font-weight: 600; color: #1f2937; }
115
-
116
- /* Level-1 model picker — compact <select> next to the title.
117
- * Populated by JS on widget open from GET /api/llms (anon path
118
- * returns Ollama-only). Hidden entirely if enable_model_picker
119
- * is false at the helper call site. */
120
- #llm-meta-widget-chat .lmw-model-picker {
121
- font: inherit; font-size: 12px;
122
- padding: 3px 6px;
123
- border: 1px solid #d1d5db;
124
- border-radius: 4px;
125
- background: #f9fafb;
126
- color: #374151;
127
- cursor: pointer;
128
- max-width: 12em;
129
- text-overflow: ellipsis;
130
- }
131
- #llm-meta-widget-chat .lmw-model-picker:focus {
132
- outline: none;
133
- border-color: #3b82f6;
134
- box-shadow: 0 0 0 2px rgba(59, 130, 246, 0.15);
135
- }
136
-
137
- /* Level-1 tools picker — inline chip in the input-controls row (same
138
- * convention as chat.aibranch.org). The tools list drops down as a
139
- * floating overlay above the input, so opening the panel doesn't
140
- * push the textarea around. Populated by JS on widget open from
141
- * GET /api/mcp_servers (anon path returns public_to_anonymous MCP
142
- * servers with their tools inline). One checkbox per SERVER —
143
- * toggling enables/disables ALL of its tools. */
144
- #llm-meta-widget-chat .lmw-tools-picker {
145
- position: relative; /* anchor for the absolutely-positioned list */
146
- }
147
- #llm-meta-widget-chat .lmw-tools-picker > summary {
148
- list-style: none;
149
- cursor: pointer;
150
- padding: 3px 8px;
151
- font-size: 12px;
152
- color: #374151;
153
- background: #f9fafb;
154
- border: 1px solid #d1d5db;
155
- border-radius: 4px;
156
- display: inline-flex; align-items: center; gap: 6px;
157
- }
158
- #llm-meta-widget-chat .lmw-tools-picker > summary:hover { background: #f3f4f6; }
159
- #llm-meta-widget-chat .lmw-tools-picker > summary::-webkit-details-marker { display: none; }
160
- #llm-meta-widget-chat .lmw-tools-picker[open] > summary {
161
- background: #eff6ff;
162
- border-color: #93c5fd;
163
- }
164
- #llm-meta-widget-chat .lmw-tools-count {
165
- display: inline-block;
166
- background: #0ea5e9;
167
- color: #fff;
168
- font-size: 10px;
169
- padding: 0 5px;
170
- border-radius: 8px;
171
- min-width: 14px;
172
- text-align: center;
173
- }
174
- #llm-meta-widget-chat .lmw-tools-count.lmw-tools-count-zero {
175
- background: #d1d5db;
176
- color: #6b7280;
177
- }
178
- /* Floating dropdown panel — sits above the input area when open so
179
- * expanding never shifts the textarea. Bottom-anchored so it opens
180
- * UPWARD (natural direction since we're at the panel's bottom). */
181
- #llm-meta-widget-chat .lmw-tools-list {
182
- position: absolute;
183
- bottom: calc(100% + 4px);
184
- left: 0;
185
- min-width: 220px;
186
- max-height: 12em;
187
- overflow-y: auto;
188
- background: #ffffff;
189
- border: 1px solid #d1d5db;
190
- border-radius: 6px;
191
- box-shadow: 0 4px 12px rgba(0, 0, 0, 0.10);
192
- padding: 4px 0;
193
- z-index: 10;
194
- }
195
- #llm-meta-widget-chat .lmw-tools-item {
196
- display: flex; align-items: center; gap: 6px;
197
- padding: 4px 10px;
198
- font-size: 12px;
199
- color: #374151;
200
- cursor: pointer;
201
- }
202
- #llm-meta-widget-chat .lmw-tools-item:hover { background: #eff6ff; }
203
- #llm-meta-widget-chat .lmw-tools-item input[type="checkbox"] { margin: 0; }
204
- #llm-meta-widget-chat .lmw-tools-empty {
205
- padding: 6px 10px;
206
- font-size: 12px;
207
- color: #94a3b8;
208
- font-style: italic;
209
- }
210
- /* Two-level tool selection — mirrors chat.aibranch.org's tool_selector.
211
- * Server row (bulk checkbox + name + count + caret) is clickable to
212
- * expand its children. Individual tool rows are indented one level. */
213
- #llm-meta-widget-chat .lmw-tools-server + .lmw-tools-server {
214
- border-top: 1px solid #f1f5f9;
215
- }
216
- #llm-meta-widget-chat .lmw-tools-server-row {
217
- display: flex; align-items: center; gap: 6px;
218
- padding: 4px 10px;
219
- font-size: 12px;
220
- font-weight: 500;
221
- color: #1f2937;
222
- cursor: pointer;
223
- }
224
- #llm-meta-widget-chat .lmw-tools-server-row:hover { background: #eff6ff; }
225
- #llm-meta-widget-chat .lmw-tools-server-name { flex: 1; }
226
- #llm-meta-widget-chat .lmw-tools-server-caret {
227
- color: #94a3b8;
228
- font-size: 10px;
229
- line-height: 1;
230
- flex-shrink: 0;
231
- }
232
- #llm-meta-widget-chat .lmw-tools-item-child {
233
- padding-left: 26px; /* align tool checkboxes past the server bulk checkbox */
234
- font-size: 12px;
235
- color: #4b5563;
236
- }
237
- #llm-meta-widget-chat .lmw-clear {
238
- background: #ef4444; color: white; border: none;
239
- padding: 4px 10px; border-radius: 6px; cursor: pointer;
240
- font: inherit; font-size: 12px;
241
- transition: background-color 0.15s;
242
- }
243
- #llm-meta-widget-chat .lmw-clear:hover { background: #dc2626; }
244
-
245
- #llm-meta-widget-chat .lmw-messages {
246
- flex: 1; overflow-y: auto;
247
- padding: 10px;
248
- background-color: #f9fafb;
249
- border-radius: 8px;
250
- margin-bottom: 8px;
251
- min-height: 6em;
252
- /* No max-height — messages grows with the widget (which the user
253
- * can drag to any size). A hard cap here would leave an ugly gap
254
- * between the messages area and the input on tall widget sizes. */
255
- }
256
- #llm-meta-widget-chat .lmw-messages::-webkit-scrollbar { width: 8px; }
257
- #llm-meta-widget-chat .lmw-messages::-webkit-scrollbar-track { background: #f1f1f1; border-radius: 4px; }
258
- #llm-meta-widget-chat .lmw-messages::-webkit-scrollbar-thumb { background: #cbd5e1; border-radius: 4px; }
259
- #llm-meta-widget-chat .lmw-messages::-webkit-scrollbar-thumb:hover { background: #94a3b8; }
260
-
261
- /* Input area — mirrors llm_meta_chat's .chat-input-container +
262
- * .chat-input + .send-button so it reads as the same UI. Multi-line
263
- * textarea with an absolutely-positioned paper-plane send button
264
- * (SVG inlined so no external icon-font dep). */
265
- #llm-meta-widget-chat .lmw-input-container {
266
- background-color: white;
267
- border: 2px solid #e5e7eb;
268
- border-radius: 8px;
269
- padding: 8px;
270
- }
271
- #llm-meta-widget-chat .message-content details > summary {
272
- cursor: pointer;
273
- font-weight: 600;
274
- }
275
- #llm-meta-widget-chat .lmw-sent-text {
276
- margin-top: 6px;
277
- font-size: 12px;
278
- opacity: 0.8;
279
- white-space: pre-wrap;
280
- }
281
-
282
- /* Opening state: greeting + the offers themselves. Shown until the first
283
- * real turn, and again after Clear. */
284
- #llm-meta-widget-chat .lmw-welcome { padding: 4px 2px 2px; }
285
- #llm-meta-widget-chat .lmw-welcome-hello {
286
- margin: 0 0 12px;
287
- font-size: 14px;
288
- line-height: 1.5;
289
- color: #374151;
290
- }
291
- #llm-meta-widget-chat .lmw-welcome-card {
292
- background-color: #f9fafb;
293
- border: 1px solid #e5e7eb;
294
- border-radius: 8px;
295
- padding: 10px 12px;
296
- margin-bottom: 8px;
297
- }
298
- #llm-meta-widget-chat .lmw-welcome-start {
299
- background-color: #eff6ff;
300
- color: #1d4ed8;
301
- border: 1px solid #bfdbfe;
302
- border-radius: 999px;
303
- padding: 4px 12px;
304
- font-size: 13px;
305
- font-family: inherit;
306
- cursor: pointer;
307
- }
308
- #llm-meta-widget-chat .lmw-welcome-start:hover { background-color: #dbeafe; }
309
- #llm-meta-widget-chat .lmw-welcome-why {
310
- margin: 8px 0 0;
311
- font-size: 13px;
312
- line-height: 1.45;
313
- color: #4b5563;
314
- }
315
- #llm-meta-widget-chat .lmw-welcome-slots {
316
- margin: 8px 0 0;
317
- padding-left: 16px;
318
- font-size: 12px;
319
- color: #6b7280;
320
- }
321
- #llm-meta-widget-chat .lmw-welcome-slots li { margin-bottom: 2px; }
322
- #llm-meta-widget-chat .lmw-welcome-slots li.filled { color: #047857; }
323
-
324
- /* Server-offered prompt templates. The row is display:none in markup and
325
- * gets its display back only when a prompt actually exists, so the inline
326
- * style and this rule have to agree on "flex". */
327
- #llm-meta-widget-chat .lmw-prompts {
328
- display: flex;
329
- flex-wrap: wrap;
330
- gap: 6px;
331
- margin-bottom: 8px;
332
- }
333
- #llm-meta-widget-chat .lmw-prompt {
334
- background-color: #eff6ff;
335
- color: #1d4ed8;
336
- border: 1px solid #bfdbfe;
337
- border-radius: 999px;
338
- padding: 4px 12px;
339
- font-size: 12px;
340
- font-family: inherit;
341
- cursor: pointer;
342
- transition: background-color 0.2s, border-color 0.2s;
343
- }
344
- #llm-meta-widget-chat .lmw-prompt:hover:not(:disabled) {
345
- background-color: #dbeafe;
346
- border-color: #93c5fd;
347
- }
348
- #llm-meta-widget-chat .lmw-prompt:disabled { opacity: 0.5; cursor: default; }
349
- #llm-meta-widget-chat .lmw-form { display: flex; flex-direction: column; gap: 8px; }
350
- #llm-meta-widget-chat .lmw-input-wrapper { position: relative; flex: 1; }
351
- #llm-meta-widget-chat .lmw-input {
352
- width: 100%;
353
- padding: 10px 48px 10px 10px;
354
- border: 1px solid #d1d5db;
355
- border-radius: 6px;
356
- font-size: 14px;
357
- font-family: inherit;
358
- resize: vertical;
359
- min-height: 44px;
360
- box-sizing: border-box;
361
- transition: border-color 0.2s, box-shadow 0.2s;
362
- }
363
- #llm-meta-widget-chat .lmw-input:focus {
364
- outline: none;
365
- border-color: #3b82f6;
366
- box-shadow: 0 0 0 3px rgba(59, 130, 246, 0.1);
367
- }
368
- #llm-meta-widget-chat .lmw-send {
369
- position: absolute;
370
- bottom: 6px;
371
- right: 6px;
372
- background-color: #3b82f6;
373
- color: white;
374
- border: none;
375
- width: 32px;
376
- height: 32px;
377
- padding: 0;
378
- border-radius: 6px;
379
- cursor: pointer;
380
- display: flex;
381
- align-items: center;
382
- justify-content: center;
383
- transition: background-color 0.15s, opacity 0.15s;
384
- }
385
- #llm-meta-widget-chat .lmw-send:hover { background-color: #2563eb; }
386
- #llm-meta-widget-chat .lmw-send:disabled { opacity: 0.5; cursor: not-allowed; }
387
- #llm-meta-widget-chat .lmw-send svg { display: block; }
388
- </style>
389
-
390
- <%# Floating toggle — visible when the chat panel is collapsed. See CSS above. %>
391
- <button type="button" id="llm-meta-widget-toggle" title="Open AI assistant" aria-label="Open AI assistant">
392
- <svg xmlns="http://www.w3.org/2000/svg" width="22" height="22" fill="currentColor" viewBox="0 0 16 16" aria-hidden="true">
393
- <path d="M2 4a2 2 0 0 1 2-2h8a2 2 0 0 1 2 2v6a2 2 0 0 1-2 2h-3l-3.5 3.5V12H4a2 2 0 0 1-2-2V4Zm3 2a1 1 0 1 0 0 2 1 1 0 0 0 0-2Zm3 0a1 1 0 1 0 0 2 1 1 0 0 0 0-2Zm3 0a1 1 0 1 0 0 2 1 1 0 0 0 0-2Z"/>
394
- </svg>
395
- </button>
396
-
397
- <div id="llm-meta-widget-chat" class="llm-meta-conversation">
398
- <div class="lmw-header">
399
- <span class="lmw-title">AI assistant</span>
400
- <div class="lmw-header-right">
401
- <button type="button" class="lmw-clear" title="Clear conversation">clear</button>
402
- <button type="button" class="lmw-hide" title="Hide">−</button>
403
- </div>
404
- </div>
405
- <div class="lmw-messages"></div>
406
- <div class="lmw-input-container">
407
- <%# Server-offered prompt templates (MCP prompts/list). Hidden until a
408
- host MCP server actually offers one, so a tools-only server leaves
409
- the widget exactly as it was. %>
410
- <div class="lmw-prompts" style="display:none"></div>
411
- <form class="lmw-form">
412
- <div class="lmw-input-wrapper">
413
- <textarea class="lmw-input" placeholder="Enter your message..." rows="2" autocomplete="off"></textarea>
414
- <button type="submit" class="lmw-send" title="Send message">
415
- <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" viewBox="0 0 16 16" aria-hidden="true">
416
- <path d="M15.964.686a.5.5 0 0 0-.65-.65L.293 6.011a.513.513 0 0 0 .002.947l4.708 1.878 8.94-6.94-6.94 8.94 1.879 4.708c.163.407.756.416.951.016l6.13-13.884Z"/>
417
- </svg>
418
- </button>
419
- </div>
420
- <%# Level-1 pickers — model + tools sit inline BELOW the textarea, %>
421
- <%# same layout convention as chat.aibranch.org's input area. Each %>
422
- <%# picker is hidden by CSS if its enable_* flag is false at the %>
423
- <%# helper call site (level-0 minimalist mode). %>
424
- <% if enable_model_picker || enable_tool_picker %>
425
- <div class="lmw-input-controls">
426
- <% if enable_model_picker %>
427
- <%# Populated by JS on widget open from GET /api/llms (anon → Ollama-only). %>
428
- <select class="lmw-model-picker" title="Select model" aria-label="Select model" style="display:none">
429
- </select>
430
- <% end %>
431
- <% if enable_tool_picker %>
432
- <%# Populated by JS on widget open from GET /api/mcp_servers. Each %>
433
- <%# checkbox toggles ALL tools on that server. Selections are %>
434
- <%# session-scoped (not persisted across widget reloads). %>
435
- <details class="lmw-tools-picker">
436
- <summary>
437
- 🔧 Tools
438
- <span class="lmw-tools-count lmw-tools-count-zero">0</span>
439
- </summary>
440
- <div class="lmw-tools-list">
441
- <div class="lmw-tools-empty">Loading…</div>
442
- </div>
443
- </details>
444
- <% end %>
445
- </div>
446
- <% end %>
447
- </form>
448
- </div>
449
- </div>
450
-
451
- <script type="module">
452
- import { runChatLoop, fetchMcpManifest, listMcpPrompts, getMcpPrompt,
453
- listMcpResources, readMcpResource, promptMessagesToText,
454
- loadHostResource, resourceLinesForTurn, resolvePromptArguments,
455
- promptButtonProps, promptArgumentSummary, fetchOllamaModels,
456
- createConversationStore, conversationKeyFor } from "<%= orchestrator_path %>";
457
- import { marked } from "/llm_meta_widget_assets/marked.esm.js";
458
-
459
- // Standard prose settings — GFM (tables, autolinks, strikethrough),
460
- // break single newlines into <br> so streamed LLM output that uses
461
- // bare newlines still reads naturally.
462
- marked.setOptions({ gfm: true, breaks: true });
463
-
464
- // Two endpoints, two jobs: one answers the chat, the other registers the
465
- // MCP tools on offer. They are usually the same llm_meta_server, but need
466
- // not be — an adopter can run their own Ollama and still borrow a hub's
467
- // tools, or use no hub at all.
468
- var LLM_BASE = <%= llm_url.to_json.html_safe %>;
469
- var TOOL_HUB_BASE = <%= tool_hub_url.to_json.html_safe %>;
470
- var API_KEY_UUID = <%= api_key_uuid.to_json.html_safe %>;
471
- var MODEL = <%= model.to_json.html_safe %>;
472
- var ACTIONS_SCHEMA_ID = <%= actions_schema_id.to_json.html_safe %>;
473
- var GREETING = <%= greeting.to_json.html_safe %>;
474
- var STATE_GLOBAL = <%= state_global.to_json.html_safe %>;
475
- var ACTIONS_GLOBAL = <%= actions_global.to_json.html_safe %>;
476
- var REMOTE_TOOLS_SCHEMA_ID = <%= remote_tools_schema_id.to_json.html_safe %>;
477
- var MAX_ROUNDS = <%= max_rounds.to_json.html_safe %>;
478
- var WELL_KNOWN_URLS = <%= raw(well_known_urls.nil? ? "null" : well_known_urls.to_json) %>;
479
- var LLM_PROVIDER = <%= llm_provider.to_json.html_safe %>;
480
- var ENABLE_MODEL_PICKER = <%= enable_model_picker.to_json.html_safe %>;
481
- // Class 1 tools are registered on a hub, so the picker needs one — which
482
- // is independent of who answers the chat. Page actions and the host's own
483
- // .well-known MCP work regardless.
484
- var ENABLE_TOOL_PICKER = <%= enable_tool_picker.to_json.html_safe %> && <%= tool_hub_url.to_json.html_safe %> !== null;
485
- var MODEL_ALLOWLIST = <%= raw(models.nil? ? "null" : models.to_json) %>;
486
- var HUB_TOOLS_ALLOWLIST = <%= raw(hub_tools.nil? ? "null" : hub_tools.to_json) %>;
487
-
488
- var root = document.getElementById("llm-meta-widget-chat");
489
- var toggleBtn = document.getElementById("llm-meta-widget-toggle");
490
- var historyEl = root.querySelector(".lmw-messages");
491
- var formEl = root.querySelector(".lmw-form");
492
- var inputEl = root.querySelector(".lmw-input");
493
- var clearBtn = root.querySelector(".lmw-clear");
494
- var hideBtn = root.querySelector(".lmw-hide");
495
- var modelPicker = root.querySelector(".lmw-model-picker"); // null when disabled
496
- var toolsPicker = root.querySelector(".lmw-tools-picker"); // null when disabled
497
- var toolsListEl = root.querySelector(".lmw-tools-list"); // null when disabled
498
- var toolsCountEl = root.querySelector(".lmw-tools-count"); // null when disabled
499
-
500
- // Persistence keys — open/close state + resized geometry (width/height).
501
- // Position is re-computed each open so the widget lands at bottom-right
502
- // of the CURRENT viewport (not wherever the user resized it last time).
503
- // Size is preserved because that's a user preference; position is a
504
- // spawn convention.
505
- var STORAGE_KEY_OPEN = "llm_meta_widget:open";
506
- var STORAGE_KEY_SIZE = "llm_meta_widget:size"; // stored as "WxH" in px
507
-
508
- // Floors matching the CSS min-width/min-height (24em / 16em). A panel
509
- // measured mid-layout reports a few pixels; saving that produced a sliver
510
- // anchored off the bottom of the window, and — worse — it was stored, so
511
- // every later visit reopened at the sliver size. Sizes below the floor are
512
- // neither saved nor honoured, which also heals a value already stored.
513
- var MIN_SAVED_WIDTH = 320;
514
- var MIN_SAVED_HEIGHT = 240;
515
-
516
- function plausibleSize(w, h) {
517
- return w >= MIN_SAVED_WIDTH && h >= MIN_SAVED_HEIGHT &&
518
- w <= window.innerWidth * 2 && h <= window.innerHeight * 2;
519
- }
520
-
521
- function applyStoredSize() {
522
- try {
523
- var raw = localStorage.getItem(STORAGE_KEY_SIZE);
524
- if (!raw) return;
525
- var parts = raw.split("x");
526
- var w = parseInt(parts[0], 10), h = parseInt(parts[1], 10);
527
- if (!plausibleSize(w, h)) {
528
- localStorage.removeItem(STORAGE_KEY_SIZE); // heal a bad value
529
- return;
530
- }
531
- root.style.width = w + "px";
532
- root.style.height = h + "px";
533
- } catch (e) { /* noop */ }
534
- }
535
- function saveCurrentSize() {
536
- try {
537
- var rect = root.getBoundingClientRect();
538
- var w = Math.round(rect.width), h = Math.round(rect.height);
539
- if (!plausibleSize(w, h)) return; // layout noise, not a choice
540
- localStorage.setItem(STORAGE_KEY_SIZE, w + "x" + h);
541
- } catch (e) { /* noop */ }
542
- }
543
-
544
- // Anchor the widget at bottom-right of the viewport, given whatever
545
- // size it currently has. Uses top/left in pixels (required for CSS
546
- // `resize: both` — a bottom/right-pinned element can't be dragged out
547
- // past the viewport edge to grow).
548
- function positionAtBottomRight(attempt) {
549
- var margin = 16; // ~1em from the viewport edges
550
- var rect = root.getBoundingClientRect();
551
- var top = Math.max(margin, window.innerHeight - rect.height - margin);
552
- var left = Math.max(margin, window.innerWidth - rect.width - margin);
553
- root.style.top = top + "px";
554
- root.style.left = left + "px";
555
-
556
- // Measured before layout settled: the panel reports a sliver and gets
557
- // anchored to the very bottom of the window. Re-measure next frame.
558
- var tries = attempt || 0;
559
- if (rect.height < MIN_SAVED_HEIGHT && tries < 3 && typeof requestAnimationFrame === "function") {
560
- requestAnimationFrame(function() { positionAtBottomRight(tries + 1); });
561
- }
562
- }
563
-
564
- function setOpen(open) {
565
- if (open) {
566
- applyStoredSize(); // restore user's preferred size (if any)
567
- root.classList.remove("lmw-collapsed");
568
- toggleBtn.classList.add("lmw-hidden");
569
- // Position AFTER unhiding so getBoundingClientRect returns real size.
570
- positionAtBottomRight();
571
- try { inputEl.focus(); } catch (e) { /* noop */ }
572
- // Fire-and-forget the hub-picker fetch on first open; subsequent
573
- // opens are no-ops (pickerLoaded flag). We deliberately don't
574
- // await — the widget is immediately usable with the initial MODEL
575
- // and no hub tools; pickers populate a moment later.
576
- ensurePickerLoaded().catch(function(e) { console.warn("[widget] picker load failed:", e); });
577
- } else {
578
- saveCurrentSize(); // capture whatever the user resized to
579
- root.classList.add("lmw-collapsed");
580
- toggleBtn.classList.remove("lmw-hidden");
581
- }
582
- try { localStorage.setItem(STORAGE_KEY_OPEN, open ? "1" : "0"); } catch (e) { /* noop */ }
583
- }
584
- var initialOpen = false;
585
- try { initialOpen = localStorage.getItem(STORAGE_KEY_OPEN) === "1"; } catch (e) { /* noop */ }
586
- setOpen(initialOpen);
587
- window.addEventListener("resize", function() {
588
- if (!root.classList.contains("lmw-collapsed")) positionAtBottomRight();
589
- });
590
-
591
- toggleBtn.addEventListener("click", function() { setOpen(true); });
592
- hideBtn.addEventListener("click", function() { setOpen(false); });
593
-
594
- // Persist size on every resize interaction. ResizeObserver fires
595
- // continuously during a drag; save + reposition on each tick so the
596
- // widget stays anchored to bottom-right as the user grows it.
597
- if (typeof ResizeObserver === "function") {
598
- var sawFirstResizeTick = false;
599
- var ro = new ResizeObserver(function() {
600
- if (root.classList.contains("lmw-collapsed")) return;
601
- positionAtBottomRight();
602
- // ResizeObserver always delivers an initial observation, and that
603
- // one reports whatever the layout happened to be mid-boot. Only
604
- // later ticks can be a user dragging the corner.
605
- if (!sawFirstResizeTick) { sawFirstResizeTick = true; return; }
606
- saveCurrentSize();
607
- });
608
- ro.observe(root);
609
- }
610
-
611
- // [{role, content, tools}] — grows across turns. `tools` is for the
612
- // transcript only; the model is sent role and content.
613
- var conversation = [];
614
-
615
- // A page action that navigates used to take the conversation with it. The
616
- // transcript lives in sessionStorage — per tab, gone when the tab closes —
617
- // keyed by path, so submitting a form and landing back on the same page
618
- // with a new query string keeps the thread.
619
- var conversationStore = createConversationStore({
620
- storage: window.sessionStorage,
621
- key: conversationKeyFor(window.location)
622
- });
623
-
624
- function persistConversation() {
625
- conversationStore.save({
626
- turns: conversation,
627
- open: !root.classList.contains("lmw-collapsed"),
628
- model: MODEL
629
- });
630
- }
631
- var actionsSchemaEl = document.getElementById(ACTIONS_SCHEMA_ID);
632
- var localTools = actionsSchemaEl ? JSON.parse(actionsSchemaEl.textContent) : [];
633
- var remoteToolsEl = document.getElementById(REMOTE_TOOLS_SCHEMA_ID);
634
- // remoteTools is a mutable live list: starts from the schema-provided
635
- // baseline (if any), then the level-1 picker adds/removes entries as
636
- // the visitor toggles server checkboxes. Passed to runChatLoop on
637
- // every submit so the current selection is respected turn-by-turn.
638
- var remoteTools = remoteToolsEl ? JSON.parse(remoteToolsEl.textContent) : [];
639
-
640
- // Level-1 picker caches. hubMcpServers[] is the list of anon-visible
641
- // servers fetched from GET /api/mcp_servers; each server has an
642
- // embedded `tools` array. selectedToolIds is the set of *individual*
643
- // tool ids currently ON — same granularity as chat.aibranch.org's
644
- // tool_selector: each tool can be toggled individually, and each
645
- // server has a bulk-toggle checkbox that reflects/drives its children's
646
- // state (all-on / indeterminate / all-off).
647
- var hubMcpServers = [];
648
- var selectedToolIds = new Set();
649
-
650
- function anyAllowedByAllowlist(name, allowlist) {
651
- return allowlist === null || allowlist.indexOf(name) >= 0;
652
- }
653
-
654
- function refreshRemoteToolsFromPicker() {
655
- // Flatten every SELECTED tool (across all servers) into remoteTools,
656
- // adapted to runChatLoop's expected { id, name, description, input_schema }.
657
- var flat = [];
658
- hubMcpServers.forEach(function(s) {
659
- (s.tools || []).forEach(function(t) {
660
- if (!selectedToolIds.has(t.id)) return;
661
- flat.push({
662
- id: t.id,
663
- name: t.name,
664
- description: t.description,
665
- input_schema: t.input_schema
666
- });
667
- });
668
- });
669
- remoteTools = flat;
670
- if (toolsCountEl) {
671
- toolsCountEl.textContent = flat.length;
672
- toolsCountEl.classList.toggle("lmw-tools-count-zero", flat.length === 0);
673
- }
674
- }
675
-
676
- // Reflect the mix of child-tool states onto a server's bulk checkbox
677
- // (checked / indeterminate / unchecked). Called after any child
678
- // checkbox change, and after applying a bulk toggle.
679
- function refreshServerBulkCheckbox(server, bulkCheckbox) {
680
- var tools = server.tools || [];
681
- var n = tools.length;
682
- if (n === 0) { bulkCheckbox.checked = false; bulkCheckbox.indeterminate = false; return; }
683
- var onCount = 0;
684
- tools.forEach(function(t) { if (selectedToolIds.has(t.id)) onCount++; });
685
- bulkCheckbox.checked = (onCount === n);
686
- bulkCheckbox.indeterminate = (onCount > 0 && onCount < n);
687
- }
688
-
689
- async function loadHubResourcesForPickers() {
690
- // Called once on first widget open (idempotent — pickerLoaded flag
691
- // below). Fetches models + MCP servers from the hub's anon endpoints
692
- // and populates each picker. Non-fatal if either fetch fails (widget
693
- // still works with the initial `model:` + no hub tools).
694
- var tasks = [];
695
-
696
- if (ENABLE_MODEL_PICKER && modelPicker && LLM_PROVIDER === "ollama") {
697
- // No hub to ask: Ollama lists its own models.
698
- tasks.push(fetchOllamaModels({ baseUrl: LLM_BASE }).then(function(names) {
699
- var flat = names
700
- .filter(function(n) { return anyAllowedByAllowlist(n, MODEL_ALLOWLIST); })
701
- .map(function(n) { return { value: n, label: n }; });
702
- if (!flat.some(function(m) { return m.value === MODEL; })) {
703
- flat.unshift({ value: MODEL, label: MODEL });
704
- }
705
- modelPicker.innerHTML = "";
706
- flat.forEach(function(m) {
707
- var opt = document.createElement("option");
708
- opt.value = m.value;
709
- opt.textContent = m.label;
710
- if (m.value === MODEL) opt.selected = true;
711
- modelPicker.appendChild(opt);
712
- });
713
- if (flat.length > 1) modelPicker.style.display = "";
714
- }));
715
- } else if (ENABLE_MODEL_PICKER && modelPicker) {
716
- tasks.push(fetch(LLM_BASE + "/api/llms", { headers: { "Accept": "application/json" } })
717
- .then(function(r) { return r.ok ? r.json() : { llms: [] }; })
718
- .then(function(payload) {
719
- // /api/llms is heterogeneous per family:
720
- // - OpenAI/Anthropic/Google: `models: [{ name, display_name, ... }]`
721
- // - Ollama: `available_models: [{ value, label, ... }]`
722
- // Anon widget uses api_key_uuid = "ollama-local" so only Ollama models
723
- // are invocable; filter to that family and use its subshape.
724
- var flat = [];
725
- (payload.llms || []).forEach(function(llm) {
726
- if (llm.family !== "ollama") return;
727
- (llm.available_models || []).forEach(function(m) {
728
- if (anyAllowedByAllowlist(m.value, MODEL_ALLOWLIST)) {
729
- flat.push({ value: m.value, label: m.label });
730
- }
731
- });
732
- });
733
- // Ensure the host-configured MODEL is in the list even if the
734
- // server doesn't return it — visitor should always see the
735
- // current selection, and we don't want to silently switch.
736
- if (!flat.some(function(m) { return m.value === MODEL; })) {
737
- flat.unshift({ value: MODEL, label: MODEL });
738
- }
739
- modelPicker.innerHTML = "";
740
- flat.forEach(function(m) {
741
- var opt = document.createElement("option");
742
- opt.value = m.value;
743
- opt.textContent = m.label;
744
- if (m.value === MODEL) opt.selected = true;
745
- modelPicker.appendChild(opt);
746
- });
747
- if (flat.length > 1) modelPicker.style.display = "";
748
- })
749
- .catch(function(e) { console.warn("[widget] model list fetch failed:", e); }));
750
- }
751
-
752
- if (ENABLE_TOOL_PICKER && toolsListEl) {
753
- tasks.push(fetch(TOOL_HUB_BASE + "/api/mcp_servers", { headers: { "Accept": "application/json" } })
754
- .then(function(r) { return r.ok ? r.json() : { mcp_servers: [] }; })
755
- .then(function(payload) {
756
- hubMcpServers = (payload.mcp_servers || []).filter(function(s) {
757
- return anyAllowedByAllowlist(s.name, HUB_TOOLS_ALLOWLIST);
758
- });
759
- toolsListEl.innerHTML = "";
760
- if (hubMcpServers.length === 0) {
761
- var empty = document.createElement("div");
762
- empty.className = "lmw-tools-empty";
763
- empty.textContent = "No hub-registered tools available.";
764
- toolsListEl.appendChild(empty);
765
- return;
766
- }
767
- hubMcpServers.forEach(function(s) {
768
- var serverBlock = document.createElement("div");
769
- serverBlock.className = "lmw-tools-server";
770
-
771
- // Server header row: bulk checkbox + name + tool count + expand caret.
772
- // Bulk checkbox toggles ALL of the server's tools at once and reflects
773
- // the mix of child states (indeterminate when partial).
774
- var headerRow = document.createElement("div");
775
- headerRow.className = "lmw-tools-server-row";
776
-
777
- var bulkCb = document.createElement("input");
778
- bulkCb.type = "checkbox";
779
- bulkCb.className = "lmw-tools-server-bulk";
780
- bulkCb.title = "Enable all tools on this server";
781
- bulkCb.addEventListener("click", function(e) {
782
- // Prevent header-row click from toggling expand.
783
- e.stopPropagation();
784
- });
785
- bulkCb.addEventListener("change", function() {
786
- var shouldOn = bulkCb.checked;
787
- (s.tools || []).forEach(function(t) {
788
- if (shouldOn) selectedToolIds.add(t.id);
789
- else selectedToolIds.delete(t.id);
790
- });
791
- bulkCb.indeterminate = false;
792
- // Sync every visible individual checkbox for this server.
793
- childList.querySelectorAll('input[type="checkbox"]').forEach(function(cb) {
794
- cb.checked = shouldOn;
795
- });
796
- refreshRemoteToolsFromPicker();
797
- });
798
-
799
- var nameSpan = document.createElement("span");
800
- nameSpan.className = "lmw-tools-server-name";
801
- var toolCount = (s.tools || []).length;
802
- nameSpan.textContent = s.name + " (" + toolCount + " tool" + (toolCount === 1 ? "" : "s") + ")";
803
-
804
- var caret = document.createElement("span");
805
- caret.className = "lmw-tools-server-caret";
806
- caret.textContent = "▸";
807
-
808
- headerRow.appendChild(bulkCb);
809
- headerRow.appendChild(nameSpan);
810
- headerRow.appendChild(caret);
811
-
812
- // Individual-tool rows — one checkbox per tool, indented.
813
- // Hidden by default; header click expands. This mirrors
814
- // chat.aibranch.org's lazy-expand server UX.
815
- var childList = document.createElement("div");
816
- childList.className = "lmw-tools-server-children";
817
- childList.style.display = "none";
818
-
819
- (s.tools || []).forEach(function(t) {
820
- var toolLabel = document.createElement("label");
821
- toolLabel.className = "lmw-tools-item lmw-tools-item-child";
822
- toolLabel.title = t.description || t.name;
823
- var cb = document.createElement("input");
824
- cb.type = "checkbox";
825
- cb.value = t.id;
826
- cb.checked = selectedToolIds.has(t.id);
827
- cb.addEventListener("change", function() {
828
- if (cb.checked) selectedToolIds.add(t.id);
829
- else selectedToolIds.delete(t.id);
830
- refreshServerBulkCheckbox(s, bulkCb);
831
- refreshRemoteToolsFromPicker();
832
- });
833
- var span = document.createElement("span");
834
- span.textContent = t.name;
835
- toolLabel.appendChild(cb);
836
- toolLabel.appendChild(span);
837
- childList.appendChild(toolLabel);
838
- });
839
-
840
- headerRow.addEventListener("click", function() {
841
- var isOpen = childList.style.display !== "none";
842
- childList.style.display = isOpen ? "none" : "block";
843
- caret.textContent = isOpen ? "▸" : "▾";
844
- });
845
-
846
- serverBlock.appendChild(headerRow);
847
- serverBlock.appendChild(childList);
848
- toolsListEl.appendChild(serverBlock);
849
-
850
- // Initial bulk-checkbox state (all unchecked at first render).
851
- refreshServerBulkCheckbox(s, bulkCb);
852
- });
853
- refreshRemoteToolsFromPicker();
854
- })
855
- .catch(function(e) { console.warn("[widget] MCP server list fetch failed:", e); }));
856
- }
857
-
858
- await Promise.all(tasks);
859
- }
860
-
861
- if (modelPicker) {
862
- modelPicker.addEventListener("change", function() { MODEL = modelPicker.value; });
863
- }
864
-
865
- // Close the tools dropdown on any click outside its area. Native
866
- // <details> only closes on summary re-click; visitors expect a
867
- // dropdown/popover to dismiss on outside click, matching native
868
- // select/menu behavior. `.contains(target)` includes the summary
869
- // AND the drop-down list (both are descendants of the <details>).
870
- if (toolsPicker) {
871
- document.addEventListener("click", function(e) {
872
- if (!toolsPicker.open) return;
873
- if (toolsPicker.contains(e.target)) return;
874
- toolsPicker.open = false;
875
- });
876
- }
877
-
878
- var pickerLoaded = false;
879
- async function ensurePickerLoaded() {
880
- if (pickerLoaded) return;
881
- pickerLoaded = true; // set first so parallel opens don't double-fetch
882
- try { await loadHubResourcesForPickers(); }
883
- catch (e) { pickerLoaded = false; throw e; }
884
- }
885
-
886
- // Fetch well-known MCP manifests at boot. Auto-discovers same origin
887
- // if WELL_KNOWN_URLS is null; empty array disables entirely.
888
- var hostWideTools = [];
889
- var hostWidePrompts = [];
890
- var resourceContext = null; // payload of the host's reference resource
891
- var resourcePlan = null; // the pre-flight decision, kept so Clear can re-arm the gate
892
-
893
- // Beyond ~2k tokens a reference resource starts crowding out the
894
- // conversation on a 32k-context local model — production PubDictionaries
895
- // is 218 dictionaries / ~35KB / ~10k tokens.
896
- var RESOURCE_BUDGET_BYTES = 8000;
897
-
898
-
899
- // Before anything asynchronous: if this page was navigated away from and
900
- // back, the visitor should see their conversation immediately.
901
- restoreConversation();
902
-
903
- var wellKnownReady = (async function() {
904
- var urls = WELL_KNOWN_URLS === null
905
- ? [ window.location.origin + "/.well-known/mcp.json" ]
906
- : WELL_KNOWN_URLS;
907
- for (var i = 0; i < urls.length; i++) {
908
- var tools = await fetchMcpManifest(urls[i]);
909
- hostWideTools = hostWideTools.concat(tools);
910
- }
911
-
912
- // The manifest publishes TOOLS only, so the endpoints are learned from
913
- // them. A server offering only prompts or resources is invisible here —
914
- // worth knowing when deciding what a static manifest should carry.
915
- var endpoints = [];
916
- hostWideTools.forEach(function(t) {
917
- if (t.endpoint && endpoints.indexOf(t.endpoint) === -1) endpoints.push(t.endpoint);
918
- });
919
-
920
- for (var j = 0; j < endpoints.length; j++) {
921
- var endpoint = endpoints[j];
922
- var prompts = await listMcpPrompts({ endpoint: endpoint });
923
- hostWidePrompts = hostWidePrompts.concat(prompts);
924
-
925
- if (resourcePlan === null) {
926
- // Listing, size gate and read all live in the orchestrator, where
927
- // they are tested together — a gate nothing consults is exactly
928
- // the bug this shape prevents.
929
- var loaded = await loadHostResource({
930
- endpoint: endpoint,
931
- budgetBytes: RESOURCE_BUDGET_BYTES,
932
- list: listMcpResources,
933
- read: readMcpResource,
934
- onSkip: function(plan) {
935
- console.info("[llm_meta_widget] not attaching " + plan.uri +
936
- " (" + plan.reason + ", sizeBytes=" + plan.sizeBytes + ")");
937
- }
938
- });
939
- // A volatile resource comes back with no context — it is read
940
- // per turn instead — so the plan, not the payload, is what says
941
- // whether this endpoint offered anything worth attaching.
942
- if (loaded && loaded.plan && loaded.plan.fetch) {
943
- resourceContext = loaded.context;
944
- resourcePlan = loaded.plan;
945
- }
946
- }
947
- }
948
- renderPromptButtons();
949
- renderWelcome();
950
- })();
951
-
952
- // ---- server-offered prompt templates --------------------------------
953
- //
954
- // One button per prompt the host's MCP server offers. Clicking it fills
955
- // the prompt's arguments from page state, asks the server to materialise
956
- // the message (prompts/get), then drops the text into the textarea and
957
- // submits — so it travels the exact path a typed message does.
958
-
959
- var promptsEl = root.querySelector(".lmw-prompts");
960
-
961
- function renderPromptButtons() {
962
- if (!promptsEl) return;
963
- promptsEl.textContent = "";
964
- if (!hostWidePrompts.length) { promptsEl.style.display = "none"; return; }
965
-
966
- hostWidePrompts.forEach(function(prompt) {
967
- var props = promptButtonProps(prompt);
968
- var button = document.createElement("button");
969
- button.type = "button";
970
- button.className = "lmw-prompt";
971
- button.textContent = props.label;
972
- button.title = props.title;
973
- button.addEventListener("click", function() { runPromptTemplate(prompt, button); });
974
- promptsEl.appendChild(button);
975
- });
976
- promptsEl.style.display = "";
977
- }
978
-
979
- // Put a saved transcript back on screen: the same bubbles, the same
980
- // markdown, and the same record of which tools ran. Called once at boot,
981
- // before the welcome block, which is only for a genuinely fresh start.
982
- function restoreConversation() {
983
- var saved = conversationStore.load();
984
- if (!saved || !saved.turns.length) return false;
985
-
986
- conversation = saved.turns;
987
- saved.turns.forEach(function(turn) {
988
- var body = appendTurn(turn.role, turn.role === "assistant" ? "" : turn.content);
989
- if (turn.role === "assistant") renderMarkdownInto(body, turn.content || "");
990
- if (!turn.tools || !turn.tools.length) return;
991
- var row = document.createElement("div");
992
- row.className = "lmw-tool-chips";
993
- turn.tools.forEach(function(tool) {
994
- var chip = document.createElement("span");
995
- chip.className = "lmw-tool-chip" + (tool.error ? " error" : "");
996
- chip.textContent = (tool.error ? "❌ " : "🔧 ") + tool.name;
997
- row.appendChild(chip);
998
- });
999
- if (body.parentNode) body.parentNode.appendChild(row);
1000
- });
1001
- historyEl.scrollTop = historyEl.scrollHeight;
1002
- return true;
1003
- }
1004
-
1005
- // A blank panel tells a first-time visitor nothing. Open with a greeting
1006
- // and the offers themselves — each template showing what it will take from
1007
- // the page and what it will ask for — so the assistant is the page's way
1008
- // in rather than a box you must already know how to talk to.
1009
- function renderWelcome() {
1010
- // A restored transcript is not a fresh start; the greeting would push
1011
- // the conversation the visitor is mid-way through off the screen.
1012
- if (!historyEl || historyEl.querySelector(".message")) return;
1013
- historyEl.textContent = "";
1014
-
1015
- var box = document.createElement("div");
1016
- box.className = "lmw-welcome";
1017
-
1018
- var hello = document.createElement("p");
1019
- hello.className = "lmw-welcome-hello";
1020
- hello.textContent = GREETING ||
1021
- "Hi — I can work this page for you. Tell me what you need in your own words" +
1022
- (hostWidePrompts.length ? ", or start with one of these:" : ".");
1023
- box.appendChild(hello);
1024
-
1025
- var state = window[STATE_GLOBAL] || {};
1026
- hostWidePrompts.forEach(function(prompt) {
1027
- var props = promptButtonProps(prompt);
1028
- var card = document.createElement("div");
1029
- card.className = "lmw-welcome-card";
1030
-
1031
- var start = document.createElement("button");
1032
- start.type = "button";
1033
- start.className = "lmw-welcome-start";
1034
- start.textContent = props.label;
1035
- start.addEventListener("click", function() { runPromptTemplate(prompt, start); });
1036
- card.appendChild(start);
1037
-
1038
- if (prompt.description) {
1039
- var why = document.createElement("p");
1040
- why.className = "lmw-welcome-why";
1041
- why.textContent = prompt.description;
1042
- card.appendChild(why);
1043
- }
1044
-
1045
- // Name the placeholders, filled or not, so the offer is concrete:
1046
- // a newcomer can see the text box is empty before clicking.
1047
- var summary = promptArgumentSummary(prompt, state);
1048
- if (summary.length) {
1049
- var slots = document.createElement("ul");
1050
- slots.className = "lmw-welcome-slots";
1051
- summary.forEach(function(slot) {
1052
- var li = document.createElement("li");
1053
- li.className = slot.filled ? "filled" : "empty";
1054
- li.textContent = slot.filled
1055
- ? slot.name + ": " + (slot.value.length > 60 ? slot.value.slice(0, 60) + "…" : slot.value)
1056
- : slot.name + ": not set yet — I'll ask, or work it out";
1057
- slots.appendChild(li);
1058
- });
1059
- card.appendChild(slots);
1060
- }
1061
- box.appendChild(card);
1062
- });
1063
-
1064
- historyEl.appendChild(box);
1065
- }
1066
-
1067
- async function runPromptTemplate(prompt, button) {
1068
- var resolved = resolvePromptArguments(prompt, window[STATE_GLOBAL] || {});
1069
- var args = resolved.args;
1070
- var missing = resolved.missing;
1071
-
1072
- // Say which page field is empty rather than letting the server answer
1073
- // -32602 for something the user can actually fix on screen.
1074
- if (missing.length) {
1075
- appendTurn("error", "Cannot run \"" + (prompt.title || prompt.name) + "\" yet — nothing to use for: " +
1076
- missing.join(", ") + ". Fill that in on the page first.");
1077
- return;
1078
- }
1079
-
1080
- button.disabled = true;
1081
- try {
1082
- var result = await getMcpPrompt({ endpoint: prompt.endpoint, name: prompt.name, args: args });
1083
- var text = promptMessagesToText(result);
1084
- if (!text) { appendTurn("error", "The server returned an empty prompt."); return; }
1085
- inputEl.value = text;
1086
- pendingTurnLabel = promptButtonProps(prompt).label;
1087
- if (typeof formEl.requestSubmit === "function") formEl.requestSubmit();
1088
- else formEl.dispatchEvent(new Event("submit", { cancelable: true }));
1089
- } catch (e) {
1090
- appendTurn("error", "Prompt failed: " + (e && e.message ? e.message : e));
1091
- } finally {
1092
- button.disabled = false;
1093
- }
1094
- }
1095
-
1096
- // Set just before a template submits, so its turn is labelled by what the
1097
- // user actually did — "Annotate text" — instead of showing a paragraph of
1098
- // server-written instructions as though they had typed it. The instructions
1099
- // stay one click away rather than hidden: what was sent is what is shown.
1100
- var pendingTurnLabel = null;
1101
-
1102
- function appendTurn(role, text, turnLabel) {
1103
- // Class names mirror llm_meta_chat's chats/_message.html.erb —
1104
- // `.message.<role>`, `.message-role`, `.message-content` — so the
1105
- // shared conversation.css styles apply directly (see the <link>
1106
- // above). The .lmw-* prefix is reserved for widget-CHROME classes
1107
- // (header, clear button, scroll region, input area) that aren't
1108
- // part of the shared conversation surface.
1109
- var welcome = historyEl.querySelector(".lmw-welcome");
1110
- if (welcome) welcome.remove();
1111
-
1112
- var div = document.createElement("div");
1113
- div.className = "message " + role;
1114
- var label = document.createElement("div");
1115
- label.className = "message-role";
1116
- label.textContent = roleLabel(role);
1117
- var body = document.createElement("div");
1118
- body.className = "message-content";
1119
- // User / system / error turns render as plain text (safe from any
1120
- // injection via user input or server-supplied strings). Assistant
1121
- // content is rendered as markdown but only after the assistant's
1122
- // text is streamed in via renderMarkdownInto — this appendTurn
1123
- // creates the empty container.
1124
- if (turnLabel) {
1125
- var details = document.createElement("details");
1126
- var summary = document.createElement("summary");
1127
- summary.textContent = turnLabel;
1128
- var full = document.createElement("div");
1129
- full.className = "lmw-sent-text";
1130
- full.textContent = text;
1131
- details.appendChild(summary);
1132
- details.appendChild(full);
1133
- body.appendChild(details);
1134
- } else {
1135
- body.textContent = text;
1136
- }
1137
- div.appendChild(label);
1138
- div.appendChild(document.createTextNode(" "));
1139
- div.appendChild(body);
1140
- historyEl.appendChild(div);
1141
- historyEl.scrollTop = historyEl.scrollHeight;
1142
- body.roleLabel = label; // so a turn in flight can show it is working
1143
- return body;
1144
- }
1145
-
1146
- // Render a raw-markdown buffer into an element's innerHTML. marked's
1147
- // default HTML output escapes user content, so passing arbitrary
1148
- // LLM output is safe against XSS. Called per-delta so streaming
1149
- // assistant text formats live (headings/lists/code blocks/etc.).
1150
- function renderMarkdownInto(el, mdText) {
1151
- try { el.innerHTML = marked.parse(mdText); }
1152
- catch (e) { el.textContent = mdText; } // fall back to raw on parse error
1153
- }
1154
-
1155
- // Role labels mirror llm_meta_chat's chats/_message.html.erb:
1156
- // user → "👤 You"
1157
- // assistant → "🤖 <model>"
1158
- // so the widget reads as the same UI as the full chat host.
1159
- function roleLabel(role) {
1160
- if (role === "user") return "👤 You";
1161
- if (role === "assistant") return "🤖 " + MODEL;
1162
- if (role === "system") return "• system";
1163
- if (role === "error") return "⚠ error";
1164
- return role;
1165
- }
1166
-
1167
- // While a turn is in flight the assistant's label becomes a turning gear.
1168
- // Same markup and class names as llm_meta_chat's message_stream_controller,
1169
- // so the shared conversation.css drives both. Without it there is no sign
1170
- // whether the assistant is still working or has quietly stopped — and on a
1171
- // local model a tool round can take a long time before the first token.
1172
- function markWorking(label) {
1173
- if (!label || label.classList.contains("is-working")) return;
1174
- label.innerHTML = '<span class="role-spinner" aria-hidden="true">\u2699\uFE0F</span> Working…';
1175
- label.classList.add("is-working");
1176
- }
1177
-
1178
- function markDone(label) {
1179
- if (!label || !label.classList.contains("is-working")) return;
1180
- label.classList.remove("is-working");
1181
- label.textContent = roleLabel("assistant");
1182
- }
1183
-
1184
- // Tool chips, written as the tools run rather than assembled at the end.
1185
- // The end-of-turn footer was invisible for as long as the turn lasted —
1186
- // minutes on a thinking model — so a visitor watched tools execute with
1187
- // no idea which ones.
1188
- var liveChips = null; // the container inside the current bubble
1189
- var pendingChips = []; // chips awaiting their outcome, oldest first
1190
-
1191
- function chipRow() {
1192
- if (liveChips && liveChips.parentNode) return liveChips;
1193
- if (!activeAssistantBody || !activeAssistantBody.parentNode) return null;
1194
- liveChips = document.createElement("div");
1195
- liveChips.className = "lmw-tool-chips";
1196
- // Inside the bubble but OUTSIDE .message-content: every text delta
1197
- // re-renders that element's markdown from scratch, which silently
1198
- // erased any chip already written into it.
1199
- activeAssistantBody.parentNode.appendChild(liveChips);
1200
- return liveChips;
1201
- }
1202
-
1203
- function announceToolCall(toolCall) {
1204
- var row = chipRow();
1205
- if (!row) return;
1206
- var chip = document.createElement("span");
1207
- chip.className = "lmw-tool-chip running";
1208
- chip.textContent = "⏳ " + toolCall.name;
1209
- chip.dataset.tool = toolCall.name;
1210
- row.appendChild(chip);
1211
- pendingChips.push(chip);
1212
- historyEl.scrollTop = historyEl.scrollHeight;
1213
- }
1214
-
1215
- function resolveToolCall(outcome) {
1216
- // Match by name, oldest first: ids are not always echoed back, and a
1217
- // repeated name resolves in call order.
1218
- var idx = pendingChips.findIndex(function(c) { return c.dataset.tool === outcome.toolCall.name; });
1219
- var chip = idx === -1 ? null : pendingChips.splice(idx, 1)[0];
1220
- if (!chip) return;
1221
- chip.className = "lmw-tool-chip" + (outcome.error ? " error" : "");
1222
- chip.textContent = (outcome.error ? "❌ " : "🔧 ") + outcome.toolCall.name;
1223
- if (outcome.error) chip.title = outcome.error.message || String(outcome.error);
1224
- }
1225
-
1226
- var currentThinkingBlock = null;
1227
- var currentThinkingBody = null;
1228
- // The assistant bubble of the turn in flight. Reasoning belongs ABOVE that
1229
- // bubble's content, the way llm_meta_chat places it — appending it to the
1230
- // transcript instead left it below the answer it was reasoning towards.
1231
- var activeAssistantBody = null;
1232
-
1233
- function ensureThinkingBlock() {
1234
- if (currentThinkingBody) return currentThinkingBody;
1235
- // Class names match llm_meta_chat's .message-thinking pattern so
1236
- // the shared conversation.css applies directly.
1237
- var details = document.createElement("details");
1238
- details.className = "message-thinking";
1239
- details.open = true;
1240
- details.classList.add("thinking-active");
1241
- var summary = document.createElement("summary");
1242
- summary.textContent = "🤔 thinking…";
1243
- var dots = document.createElement("span");
1244
- dots.className = "thinking-dots";
1245
- for (var i = 0; i < 3; i++) {
1246
- var dot = document.createElement("span");
1247
- dot.textContent = ".";
1248
- dots.appendChild(dot);
1249
- }
1250
- summary.appendChild(dots);
1251
- var body = document.createElement("div");
1252
- body.className = "message-thinking-content";
1253
- details.appendChild(summary);
1254
- details.appendChild(body);
1255
- if (activeAssistantBody && activeAssistantBody.parentNode) {
1256
- activeAssistantBody.parentNode.insertBefore(details, activeAssistantBody);
1257
- } else {
1258
- historyEl.appendChild(details);
1259
- }
1260
- historyEl.scrollTop = historyEl.scrollHeight;
1261
- currentThinkingBlock = details;
1262
- currentThinkingBody = body;
1263
- return body;
1264
- }
1265
-
1266
- function collapseThinkingBlock() {
1267
- if (currentThinkingBlock) {
1268
- currentThinkingBlock.classList.remove("thinking-active");
1269
- currentThinkingBlock.open = false;
1270
- var summary = currentThinkingBlock.querySelector("summary");
1271
- if (summary) summary.textContent = "🤔 thinking (finished)";
1272
- }
1273
- currentThinkingBlock = null;
1274
- currentThinkingBody = null;
1275
- }
1276
-
1277
- function currentPageState() {
1278
- var reader = window[STATE_GLOBAL] || {};
1279
- var out = {};
1280
- Object.keys(reader).forEach(function(k) {
1281
- try { out[k] = reader[k](); } catch (e) { out[k] = "<error: " + e.message + ">"; }
1282
- });
1283
- return out;
1284
- }
1285
-
1286
- function currentSystemPrompt(resourceLines) {
1287
- return [
1288
- "You are integrated into a web page as an AI assistant. You have tools available to change page state or fetch information.",
1289
- "",
1290
- "RULES for tool use:",
1291
- "1. If the user's question can be answered from the Current page state below, answer directly with a plain-text response — do NOT invoke a tool.",
1292
- "2. If the user requests a state change, or needs information not in the page state, invoke the matching tool via a function call. Do not describe your intent in text without actually invoking (a textual promise like \"I will add X\" is a failure).",
1293
- "3. After a tool returns a result, use it: either take the next step the task needs, or — if the task is done — answer in plain text. Do not stop silently after a tool call.",
1294
- "4. NEVER repeat a call you have already made with the same or similar arguments — its result is already in the conversation history.",
1295
- "",
1296
- "Current page state:",
1297
- JSON.stringify(currentPageState(), null, 2)
1298
- ].concat(resourceLines || []).join("\n");
1299
- }
1300
-
1301
- // Runs once per send, before the system prompt is built: a volatile
1302
- // resource is re-read here, a stable one re-uses the copy taken at boot.
1303
- // Either way it is attached to every turn — the server's hint governs
1304
- // re-FETCHING; how often to include it is this client's call.
1305
- async function resourceLinesForThisTurn() {
1306
- var turn = await resourceLinesForTurn({
1307
- plan: resourcePlan,
1308
- cached: resourceContext,
1309
- endpoint: resourcePlan && resourcePlan.endpoint,
1310
- read: readMcpResource,
1311
- budgetBytes: RESOURCE_BUDGET_BYTES
1312
- });
1313
- resourceContext = turn.cached;
1314
- return turn.lines;
1315
- }
1316
-
1317
- // Per-turn AbortController — lets the Clear button (or a new submit)
1318
- // terminate an in-flight runChatLoop.
1319
- var currentAbort = null;
1320
-
1321
- clearBtn.addEventListener("click", function() {
1322
- if (currentAbort) { try { currentAbort.abort(); } catch (e) { /* noop */ } }
1323
- conversation = [];
1324
- conversationStore.clear();
1325
- historyEl.innerHTML = "";
1326
- renderWelcome();
1327
- });
1328
-
1329
- // Enter submits, Shift+Enter inserts a newline — matches llm_meta_chat's
1330
- // input UX so users can type multi-line prompts without accidentally
1331
- // firing the form.
1332
- inputEl.addEventListener("keydown", function(e) {
1333
- if (e.key === "Enter" && !e.shiftKey && !e.isComposing) {
1334
- e.preventDefault();
1335
- if (typeof formEl.requestSubmit === "function") formEl.requestSubmit();
1336
- else formEl.dispatchEvent(new Event("submit", { cancelable: true }));
1337
- }
1338
- });
1339
-
1340
- formEl.addEventListener("submit", async function(event) {
1341
- event.preventDefault();
1342
- var userText = inputEl.value.trim();
1343
- if (!userText) return;
1344
- inputEl.value = "";
1345
- appendTurn("user", userText, pendingTurnLabel);
1346
- pendingTurnLabel = null;
1347
-
1348
- if (currentAbort) { try { currentAbort.abort(); } catch (e) { /* noop */ } }
1349
- currentAbort = new AbortController();
1350
-
1351
- var assistantBody = appendTurn("assistant", "");
1352
- activeAssistantBody = assistantBody;
1353
- liveChips = null;
1354
- pendingChips = [];
1355
- markWorking(assistantBody.roleLabel);
1356
- var assistantMarkdown = ""; // accumulate raw markdown, re-render on each delta
1357
-
1358
- try {
1359
- // Discovery has to finish before the system prompt is built: the
1360
- // resource catalog is attached to the first turn only, so building
1361
- // messages first would silently ship that turn without it AND mark
1362
- // it as sent.
1363
- await wellKnownReady;
1364
-
1365
- var resourceLines = await resourceLinesForThisTurn();
1366
- var messages = [{ role: "system", content: currentSystemPrompt(resourceLines) }]
1367
- .concat(conversation.map(function(t) { return { role: t.role, content: t.content }; }))
1368
- .concat([{ role: "user", content: userText }]);
1369
-
1370
- var result = await runChatLoop({
1371
- baseUrl: LLM_BASE,
1372
- toolHubUrl: TOOL_HUB_BASE,
1373
- apiKeyUuid: API_KEY_UUID,
1374
- modelName: MODEL,
1375
- messages: messages,
1376
- localTools: localTools,
1377
- remoteTools: remoteTools,
1378
- hostWideTools: hostWideTools,
1379
- aiActions: window[ACTIONS_GLOBAL] || {},
1380
- maxRounds: MAX_ROUNDS,
1381
- provider: LLM_PROVIDER === "ollama" ? "ollama" : "hub",
1382
- signal: currentAbort.signal,
1383
- onToolCall: function(toolCall) { announceToolCall(toolCall); },
1384
- onToolDispatched: function(outcome) { resolveToolCall(outcome); },
1385
- onPhase: function(name) {
1386
- // 'thinking' covers the long silence before the first
1387
- // token; 'responding' means text is on its way.
1388
- if (name === "responding") markDone(assistantBody.roleLabel);
1389
- else markWorking(assistantBody.roleLabel);
1390
- },
1391
- onRoundStart: function(roundIdx) {
1392
- // A new round means more work: tool results are going back
1393
- // to the model, which is the longest wait of all.
1394
- markWorking(assistantBody.roleLabel);
1395
- // Loop mechanics are debugging info, not user-facing signal.
1396
- // Reuse the same assistant bubble across rounds — text just
1397
- // keeps streaming into it (accumulating markdown). Weaker
1398
- // models sometimes emit tool_calls in >1 round instead of
1399
- // synthesizing right away; keeping one bubble makes the
1400
- // resulting conversation read as ONE reply rather than a
1401
- // debug trace with round separators.
1402
- collapseThinkingBlock();
1403
- },
1404
- onThinkingDelta: function(delta) {
1405
- var body = ensureThinkingBlock();
1406
- body.appendChild(document.createTextNode(delta));
1407
- body.scrollTop = body.scrollHeight;
1408
- historyEl.scrollTop = historyEl.scrollHeight;
1409
- },
1410
- onTextDelta: function(delta) {
1411
- markDone(assistantBody.roleLabel);
1412
- collapseThinkingBlock();
1413
- assistantMarkdown += delta;
1414
- renderMarkdownInto(assistantBody, assistantMarkdown);
1415
- historyEl.scrollTop = historyEl.scrollHeight;
1416
- }
1417
- });
1418
- conversation.push({ role: "user", content: userText });
1419
- conversation.push({
1420
- role: "assistant",
1421
- content: result.content,
1422
- // Kept so a restored transcript still shows what ran — losing
1423
- // that record is what made a navigating action unbearable.
1424
- tools: result.dispatched.map(function(d) {
1425
- return d.error ? { name: d.toolCall.name, error: true } : { name: d.toolCall.name };
1426
- })
1427
- });
1428
- persistConversation();
1429
-
1430
- // Anything still pending never reported an outcome (a class that
1431
- // does not round-trip, or a dispatch that vanished). Reconcile
1432
- // from the loop's own record so no chip is left spinning.
1433
- result.dispatched.forEach(function(d) { resolveToolCall(d); });
1434
- pendingChips.forEach(function(chip) {
1435
- chip.className = "lmw-tool-chip";
1436
- chip.textContent = "🔧 " + chip.dataset.tool;
1437
- });
1438
- pendingChips = [];
1439
-
1440
- // Skipped = LLM tried a tool that doesn't exist. Real signal.
1441
- if (result.skipped.length > 0) {
1442
- appendTurn("system", "Not available on this page: " +
1443
- result.skipped.map(function(t) { return t.name; }).join(", "));
1444
- }
1445
- // Loop termination reasons:
1446
- // "duplicate_tool_calls" — LLM re-called an already-invoked
1447
- // tool; the earlier round's dispatch already produced the
1448
- // answer/effect, so we silently absorb this (no user warning).
1449
- // otherwise (e.g. max_rounds) — the loop hit a real hard cap
1450
- // that likely truncated the response; user should know.
1451
- if (result.stopped_reason && result.stopped_reason !== "duplicate_tool_calls") {
1452
- appendTurn("system",
1453
- "The assistant reached its tool-use limit before finishing. " +
1454
- "The reply above may be incomplete — try asking again or rephrasing.");
1455
- }
1456
- } catch (err) {
1457
- if (err.name === "AbortError" || /aborted/i.test(err.message || "")) {
1458
- appendTurn("system", "⏹ stopped");
1459
- } else {
1460
- appendTurn("error", err.message);
1461
- }
1462
- } finally {
1463
- // Whatever happened — answered, aborted, threw, or returned
1464
- // nothing at all — the turn is over and the label must stop
1465
- // claiming otherwise. A spinner left running is a worse lie than
1466
- // no spinner: it says "still working" about a turn that ended.
1467
- markDone(assistantBody.roleLabel);
1468
- collapseThinkingBlock();
1469
- activeAssistantBody = null;
1470
- currentAbort = null;
1471
- }
1472
- });
1473
- </script>
20
+ <%# into rendered HTML. One line per comment keeps them self-terminating. %>
21
+ <script type="module" src="<%= element_path %>"></script>
22
+ <llm-meta-widget
23
+ llm-url="<%= llm_url %>"
24
+ model="<%= model %>"
25
+ <%= tag_attr("tool-hub-url", tool_hub_url) %>
26
+ <%= tag_attr("llm-provider", llm_provider) %>
27
+ <%= tag_attr("api-key-uuid", api_key_uuid) %>
28
+ <%= tag_attr("greeting", greeting) %>
29
+ <%= tag_attr("max-rounds", max_rounds) %>
30
+ <%= tag_attr("actions-schema-id", actions_schema_id) %>
31
+ <%= tag_attr("state-global", state_global) %>
32
+ <%= tag_attr("actions-global", actions_global) %>
33
+ <%= tag_attr("remote-tools-schema-id", remote_tools_schema_id) %>
34
+ <%# Pickers default to true in the element, so only emit the disabling value. %>
35
+ <%= enable_model_picker ? "" : 'enable-model-picker="false"'.html_safe %>
36
+ <%= enable_tool_picker ? "" : 'enable-tool-picker="false"'.html_safe %>
37
+ <%# Allowlists: nil omits the attribute, which the element reads as "no %>
38
+ <%# allowlist". An empty array would mean the same thing, so it omits too. %>
39
+ <%= tag_attr("models", Array(models).join(",").presence) %>
40
+ <%= tag_attr("hub-tools", Array(hub_tools).join(",").presence) %>
41
+ <%# well-known-urls is tri-state and this is the mapping that preserves it: %>
42
+ <%# nil -> attribute omitted -> auto-discover same-origin %>
43
+ <%# [] -> well-known-urls="" -> discovery off %>
44
+ <%# [a,b] -> "a,b" -> fetch those %>
45
+ <%= well_known_attr(well_known_urls) %>
46
+ ></llm-meta-widget>