llm_meta_widget 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
checksums.yaml ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA256:
3
+ metadata.gz: 2f20be01e9b1ac0bfc27351f7c1583478eaf3f1c9c5a9ef0739f95e71f965b03
4
+ data.tar.gz: cb74a7a835799fb21b18ef51637f03320da067b37b955532705aae48ceb46df8
5
+ SHA512:
6
+ metadata.gz: 21a3107c99ecb9d7f27aee4378f9f9e816bcdaf140421cddc32967d4df6703d577972c5087cb0efe17eeb2ad5a924f162b406c30dd50f2fcc07a1935f98ff3c7
7
+ data.tar.gz: 0fec2f2cf2ad99af3cf4c932f7c35028ddd0017e331a559d9d90b339a4ad8d3dc920a492fdb2dcdf21a050f7f7dd5a3722968598ff2dbc1c15906604bd613499
data/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for describing the origin of the Work and
141
+ reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright 2026 DBCLS
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
data/README.md ADDED
@@ -0,0 +1,173 @@
1
+ # llm_meta_widget
2
+
3
+ Embeddable browser chat widget for the [llm_meta](https://github.com/pubannotation) ecosystem.
4
+
5
+ Client-orchestrated: the widget fetches host-side action schemas + host-published `.well-known/mcp.json` manifests at boot, dispatches tool_calls locally (page-embedded actions) or directly to MCP endpoints (host-wide well-known), and consumes the meta-server's SSE `single_llm_calls` API. Ships one Rails helper + one view partial + a served orchestrator JS module.
6
+
7
+ **No** Devise, DB migrations, ChatManager, or PromptNavigator. Adds only `rails >= 8.0` as a runtime dep — so hosts that haven't bumped to 8.1 can adopt it without a Rails upgrade.
8
+
9
+ ## Installation (local, path-based)
10
+
11
+ Add to the host app's Gemfile:
12
+
13
+ ```ruby
14
+ gem "llm_meta_widget", path: "../llm_meta/llm_meta_widget"
15
+ ```
16
+
17
+ Then `bundle install`. The engine auto-includes the widget helper into ActionView, so nothing else to wire up.
18
+
19
+ ## Usage
20
+
21
+ On any view where you want the widget:
22
+
23
+ ```erb
24
+ <%= llm_meta_widget(base_url: "https://your-meta-server.example",
25
+ model: "qwen3-6-35b-fast") %>
26
+ ```
27
+
28
+ That's the minimum. The widget renders a floating chat panel; visitors get a message-list, an input box, and (by default) a model dropdown + tool picker below the input.
29
+
30
+ To make the LLM able to do more than converse, declare tools using any of the **three tool classes** below.
31
+
32
+ ## Three tool classes
33
+
34
+ The widget classifies every tool_call the LLM emits by name and dispatches to one of three execution paths. Each class has a different declaration, different visibility to the LLM, and different execution semantics.
35
+
36
+ ### Class 3 — Page-embedded actions (`window.aiActions`)
37
+
38
+ Declared inline on the same view as the widget. Runs as JavaScript in the browser — no HTTP hop, no server involvement. Best for actions that mutate the page's own state ("click this button", "add to selection", "scroll to X").
39
+
40
+ **Declaration** — three script blocks on the view:
41
+
42
+ ```html
43
+ <!-- (a) Tool schemas the LLM sees. JSON Schema (draft-2020-12 subset). -->
44
+ <script type="application/json" id="ai-actions">
45
+ [
46
+ { "name": "add_dictionaries",
47
+ "description": "Add the named dictionaries to the current selection.",
48
+ "input_schema": {
49
+ "type": "object",
50
+ "properties": { "names": { "type": "array", "items": { "type": "string" } } },
51
+ "required": ["names"]
52
+ } }
53
+ ]
54
+ </script>
55
+
56
+ <!-- (b) State readers folded into the LLM's system prompt EVERY turn, -->
57
+ <!-- so the LLM can answer from page state without a tool_call. -->
58
+ <script>
59
+ window.aiState = {
60
+ text: function() { return $("#text").val() || ""; },
61
+ selected_dictionaries: function() { return getSelected(); }
62
+ };
63
+ </script>
64
+
65
+ <!-- (c) Action implementations invoked when the LLM emits a matching tool_call. -->
66
+ <script>
67
+ window.aiActions = {
68
+ add_dictionaries: function(args) { /* mutate the page here */ }
69
+ };
70
+ </script>
71
+ ```
72
+
73
+ **What the LLM sees.** The `ai-actions` JSON is passed to the meta-server as `local_tools` for every turn. Alongside it, every reader in `window.aiState` is invoked (each turn) and the results are JSON-serialized into a `Current page state:` block appended to the system prompt — the LLM can answer from state directly instead of tool-calling for lookups.
74
+
75
+ **When the tool_call fires.** Fire-and-forget, dispatched **AFTER** the LLM's response text finishes streaming. The action's return value is NOT fed back to the LLM this turn — the model already produced its user-facing answer and moved on. This is a deliberate design choice (see `project_page_embedded_actions` memory): writes are separated from the conversation loop so the LLM can commit to an action without waiting for a round-trip. Use Class 1/2 instead when you need the LLM to actually see the tool's result.
76
+
77
+ **Args**: parsed JS object matching the `input_schema`. Return value ignored. Async allowed (widget doesn't await, but browser will still execute the promise). Exceptions logged and surfaced as an `❌ <name>` chip in the message footer.
78
+
79
+ **LLM tried a name that isn't declared** → widget appends a `system: Not available on this page: <name>` message and continues.
80
+
81
+ ### Class 2 — Host-wide MCP (`.well-known/mcp.json`)
82
+
83
+ Declared once per host origin via a well-known manifest. Widget fetches the manifest at boot, exposes the listed tools to the LLM, and (on tool_call) POSTs directly to each tool's endpoint over MCP JSON-RPC. **Meta-server is not involved** for Class 2 tool execution.
84
+
85
+ **Declaration.** Publish at `https://your-host.example/.well-known/mcp.json`:
86
+
87
+ ```json
88
+ {
89
+ "servers": [{
90
+ "name": "myhost",
91
+ "url": "/mcp",
92
+ "tools": [
93
+ { "name": "annotate", "description": "…", "input_schema": {…} }
94
+ ]
95
+ }]
96
+ }
97
+ ```
98
+
99
+ - `url` is resolved against the host's origin (`/mcp` → `https://your-host.example/mcp`). Absolute URLs are also allowed but must be same-origin for the browser to reach them (otherwise CORS blocks the widget).
100
+ - The `tools[]` array in the manifest IS the tool list — the widget does not additionally call MCP `tools/list` on discovery. Keep the manifest in sync with the endpoint.
101
+
102
+ **Auto-discovery.** By default the widget fetches `<same-origin>/.well-known/mcp.json` at boot. To override, pass `well_known_urls:` to the helper: an explicit array (e.g. `["https://other.example/.well-known/mcp.json"]`) or `[]` to disable entirely.
103
+
104
+ **What the LLM sees.** Every tool listed in every discovered manifest is exposed as a callable. Names must be unique across manifests (if a name collides with a Class 1 or Class 3 tool, Class 3 wins, then Class 2, then Class 1).
105
+
106
+ **When the tool_call fires.** Synchronously during the turn — widget POSTs `{ jsonrpc, method: "tools/call", params: { name, arguments } }` to the tool's URL, awaits the JSON-RPC response, and feeds the result back to the LLM as tool output for the next round. Standard MCP loop.
107
+
108
+ **Error path.** HTTP 4xx/5xx, network failure, or an MCP JSON-RPC error → widget marks that dispatch as errored; visitor sees a red chip in the message footer; the LLM's next round sees the error as the tool's return value (so it can explain what went wrong instead of pretending it worked).
109
+
110
+ ### Class 1 — Hub-registered MCP (via the meta-server)
111
+
112
+ Declared out-of-band on the meta-server (via the hub's admin UI or `/user/:id/mcp_servers` API). The widget doesn't own these — they're a shared pool visible across all consumers of the hub. Suited for third-party MCP servers (PubDictionaries, TogoMCP, Brave Search, …) that a single visitor might want to pick and choose from.
113
+
114
+ **Declaration.** No widget-side change. Register the server on the hub → flip `public: true` (visible to signed-in users) and optionally `public_to_anonymous: true` (visible to widget visitors without a login). See the meta-server's `Api::McpServersController`.
115
+
116
+ **What the LLM sees.** Only tools from servers the visitor has **enabled via the tool picker** (see "Level-1 pickers" below). Nothing is auto-selected — the visitor opts in per session.
117
+
118
+ **When the tool_call fires.** Synchronously during the turn — widget POSTs to the hub's `/api/llm_api_keys/:uuid/models/:name/chat_streams` endpoint with `tool_ids: [...]`; the hub proxies to each MCP server and streams results back through SSE.
119
+
120
+ **Error path.** Hub-side errors (rate limit, timeout, MCP server unavailable, upstream failure) arrive as SSE `event: error` frames with typed codes (`mcp_unavailable`, `timeout`, `rate_limit`, …); the widget surfaces them in the message bubble with a per-code prefix.
121
+
122
+ ## Level-1 pickers
123
+
124
+ By default the widget renders two pickers below the input textarea:
125
+
126
+ - **Model dropdown** — populated from the hub's `GET /api/llms` (anon path returns Ollama-only, since the widget's LLM calls use `api_key_uuid: "ollama-local"`).
127
+ - **Tool picker** — populated from the hub's `GET /api/mcp_servers` (anon path returns `public_to_anonymous: true` servers). Two-level UX: server bulk-toggle + individual tool checkboxes on expand.
128
+
129
+ Both pickers require **CORS**: the meta-server must include the host's origin in its `config/initializers/cors.rb` allowlist (`/api/*` resource). Without CORS, the fetch is silently blocked and pickers stay empty.
130
+
131
+ To adjust picker behavior at the helper call site:
132
+
133
+ ```erb
134
+ <%= llm_meta_widget(
135
+ base_url: "https://your-meta-server.example",
136
+ model: "qwen3-6-35b-fast", # initial selection
137
+ enable_model_picker: true, # false → hide picker, use fixed `model:`
138
+ enable_tool_picker: true, # false → hide picker, no Class-1 tools
139
+ models: nil, # nil = all anon models; ["qwen3-6-35b-fast", …] = allowlist
140
+ hub_tools: nil # nil = all anon-public MCPs; ["togomcp", …] = allowlist by server name
141
+ ) %>
142
+ ```
143
+
144
+ To lock the widget to the fixed `model:` prop and disable Class-1 tools entirely (level-0 mode — Class 2 & 3 still work):
145
+
146
+ ```erb
147
+ <%= llm_meta_widget(base_url: "…", model: "…",
148
+ enable_model_picker: false,
149
+ enable_tool_picker: false) %>
150
+ ```
151
+
152
+ ## All helper options
153
+
154
+ | Option | Default | Purpose |
155
+ |---|---|---|
156
+ | `base_url:` | required | Meta-server URL |
157
+ | `model:` | required | Initial model (also the fallback when picker is disabled) |
158
+ | `api_key_uuid:` | `"ollama-local"` | Hub API-key uuid to invoke |
159
+ | `orchestrator_path:` | `"/llm_meta_widget_assets/orchestrator.js"` | Served by the gem's engine; rarely overridden |
160
+ | `actions_schema_id:` | `"ai-actions"` | DOM id of the Class-3 schema block |
161
+ | `state_global:` | `"aiState"` | Global window object holding Class-3 state readers |
162
+ | `actions_global:` | `"aiActions"` | Global window object holding Class-3 implementations |
163
+ | `remote_tools_schema_id:` | `"remote-mcp-tools"` | Optional DOM id for pre-configured Class-1 tools (bypasses picker) |
164
+ | `well_known_urls:` | `nil` | `nil` = auto-discover same-origin; explicit array = fetch those; `[]` = disable |
165
+ | `max_rounds:` | `3` | Cap on tool-call rounds per LLM turn |
166
+ | `enable_model_picker:` | `true` | Show model dropdown (Level-1) |
167
+ | `enable_tool_picker:` | `true` | Show tool picker (Level-1) |
168
+ | `models:` | `nil` | Model-name allowlist; `nil` = all anon-available |
169
+ | `hub_tools:` | `nil` | MCP-server-name allowlist; `nil` = all anon-public |
170
+
171
+ ## License
172
+
173
+ Apache-2.0.
data/Rakefile ADDED
@@ -0,0 +1,11 @@
1
+ # `rake build` / `rake release`, used by .github/workflows/gem_release.yml.
2
+ # The widget has no Ruby test suite of its own: its logic is the browser
3
+ # orchestrator, tested with `node --test` (see `rake test_js`).
4
+ require "bundler/gem_tasks"
5
+
6
+ desc "Run the orchestrator's JavaScript tests"
7
+ task :test_js do
8
+ sh "node --test app/assets/javascripts/llm_meta_widget/orchestrator.test.mjs"
9
+ end
10
+
11
+ task default: :test_js