@cliptude/cli 0.1.21 → 0.1.32

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.
@@ -0,0 +1,378 @@
1
+ /* Cliptude MCP App bridge: JSON-RPC 2.0 over postMessage with the host (MCP Apps, SEP-1865).
2
+ * Spec: https://modelcontextprotocol.io/specification/draft/extensions/apps
3
+ * View -> Host requests: ui/initialize, ui/message, ui/update-model-context, ui/open-link, tools/call
4
+ * View -> Host notifications: ui/notifications/initialized, ui/notifications/size-changed
5
+ * Host -> View notifications: ui/notifications/tool-input, ui/notifications/tool-result,
6
+ * ui/notifications/tool-cancelled, ui/notifications/host-context-changed
7
+ * Host -> View requests: ui/resource-teardown, ping
8
+ * ChatGPT speaks this same bridge (Apps SDK "Build a ChatGPT UI"); when a host does not answer ui/initialize but
9
+ * offers window.openai (the Apps SDK's own API), the widget uses that instead: toolInput/toolOutput, callTool,
10
+ * sendFollowUpMessage, openExternal and the openai:set_globals event.
11
+ * Inlined into every widget by cliptude_mcp/apps.py, so the served HTML has no external script. */
12
+ var Cliptude = (function () {
13
+ "use strict";
14
+ var PROTOCOL_VERSION = "2026-01-26";
15
+ var nextId = 1;
16
+ var pending = {};
17
+ var handlers = { input: null, result: null, cancelled: null, context: null };
18
+ var state = { hostContext: {}, hostCapabilities: {}, toolInput: null, connected: false, openai: false };
19
+
20
+ function openaiApi() {
21
+ try { return window.openai && typeof window.openai === "object" ? window.openai : null; } catch (e) { return null; }
22
+ }
23
+
24
+ function post(message) {
25
+ if (window.parent && window.parent !== window) window.parent.postMessage(message, "*");
26
+ }
27
+
28
+ function request(method, params, timeoutMs) {
29
+ var id = nextId++;
30
+ return new Promise(function (resolve, reject) {
31
+ pending[id] = { resolve: resolve, reject: reject };
32
+ post({ jsonrpc: "2.0", id: id, method: method, params: params || {} });
33
+ setTimeout(function () {
34
+ if (pending[id]) {
35
+ delete pending[id];
36
+ reject(new Error(method + " timed out"));
37
+ }
38
+ }, timeoutMs || 60000);
39
+ });
40
+ }
41
+
42
+ function notify(method, params) {
43
+ post({ jsonrpc: "2.0", method: method, params: params || {} });
44
+ }
45
+
46
+ function respond(id, result) {
47
+ post({ jsonrpc: "2.0", id: id, result: result || {} });
48
+ }
49
+
50
+ function applyContext(ctx) {
51
+ if (!ctx) return;
52
+ var root = document.documentElement;
53
+ if (ctx.theme === "dark" || ctx.theme === "light") {
54
+ root.setAttribute("data-theme", ctx.theme);
55
+ root.style.colorScheme = ctx.theme;
56
+ }
57
+ var styles = ctx.styles || {};
58
+ var vars = styles.variables || {};
59
+ Object.keys(vars).forEach(function (key) {
60
+ if (vars[key] != null && key.indexOf("--") === 0) root.style.setProperty(key, vars[key]);
61
+ });
62
+ if (styles.css && styles.css.fonts && !document.getElementById("host-fonts")) {
63
+ var tag = document.createElement("style");
64
+ tag.id = "host-fonts";
65
+ tag.textContent = styles.css.fonts;
66
+ document.head.appendChild(tag);
67
+ }
68
+ var dims = ctx.containerDimensions || {};
69
+ if (dims.maxHeight) root.style.maxHeight = dims.maxHeight + "px";
70
+ if (handlers.context) handlers.context(state.hostContext);
71
+ }
72
+
73
+ function merge(target, source) {
74
+ Object.keys(source || {}).forEach(function (key) { target[key] = source[key]; });
75
+ return target;
76
+ }
77
+
78
+ window.addEventListener("message", function (event) {
79
+ if (event.source !== window.parent) return;
80
+ var msg = event.data;
81
+ if (!msg || msg.jsonrpc !== "2.0") return;
82
+ if (msg.method === undefined && msg.id !== undefined && msg.id !== null) {
83
+ var waiter = pending[msg.id];
84
+ if (!waiter) return;
85
+ delete pending[msg.id];
86
+ if (msg.error) waiter.reject(new Error(msg.error.message || "Host error"));
87
+ else waiter.resolve(msg.result || {});
88
+ return;
89
+ }
90
+ var params = msg.params || {};
91
+ if (msg.id !== undefined && msg.id !== null) {
92
+ // Requests from the host.
93
+ if (msg.method === "ui/resource-teardown" || msg.method === "ping") {
94
+ Media.stop();
95
+ respond(msg.id, {});
96
+ } else {
97
+ post({ jsonrpc: "2.0", id: msg.id, error: { code: -32601, message: "Method not found" } });
98
+ }
99
+ return;
100
+ }
101
+ switch (msg.method) {
102
+ case "ui/notifications/tool-input":
103
+ state.toolInput = params.arguments || {};
104
+ if (handlers.input) handlers.input(state.toolInput);
105
+ break;
106
+ case "ui/notifications/tool-result":
107
+ if (handlers.result) handlers.result(resultData(params), params);
108
+ break;
109
+ case "ui/notifications/tool-cancelled":
110
+ if (handlers.cancelled) handlers.cancelled(params.reason || "");
111
+ break;
112
+ case "ui/notifications/host-context-changed":
113
+ merge(state.hostContext, params);
114
+ applyContext(params);
115
+ break;
116
+ }
117
+ });
118
+
119
+ /** The tool's data: structuredContent, else the JSON in its first text block. */
120
+ function resultData(result) {
121
+ if (!result) return null;
122
+ if (result.structuredContent && typeof result.structuredContent === "object") return result.structuredContent;
123
+ var blocks = result.content || [];
124
+ for (var i = 0; i < blocks.length; i++) {
125
+ if (blocks[i] && blocks[i].type === "text") {
126
+ try { return JSON.parse(blocks[i].text); } catch (e) { return { error: blocks[i].text }; }
127
+ }
128
+ }
129
+ return null;
130
+ }
131
+
132
+ var lastSize = "";
133
+ function reportSize() {
134
+ var el = document.documentElement;
135
+ var width = Math.ceil(el.scrollWidth);
136
+ var height = Math.ceil(document.body ? document.body.scrollHeight : el.scrollHeight);
137
+ var key = width + "x" + height;
138
+ if (key === lastSize) return;
139
+ lastSize = key;
140
+ if (state.openai) {
141
+ // Apps SDK: notifyIntrinsicHeight (argument shape not documented; ChatGPT also sizes the frame itself).
142
+ try { if (window.openai.notifyIntrinsicHeight) window.openai.notifyIntrinsicHeight(height); } catch (e) {}
143
+ return;
144
+ }
145
+ notify("ui/notifications/size-changed", { width: width, height: height });
146
+ }
147
+
148
+ /** ChatGPT's window.openai: the tool's arguments and result are globals, updated by openai:set_globals. */
149
+ var lastOutput = null;
150
+ function connectOpenai() {
151
+ var api = openaiApi();
152
+ state.openai = true;
153
+ state.connected = true;
154
+ state.hostCapabilities = { serverTools: typeof api.callTool === "function" ? {} : undefined };
155
+ if (!state.hostCapabilities.serverTools) delete state.hostCapabilities.serverTools;
156
+ state.hostContext = { theme: api.theme, displayMode: api.displayMode,
157
+ containerDimensions: api.maxHeight ? { maxHeight: api.maxHeight } : {} };
158
+ applyContext(state.hostContext);
159
+ function deliver() {
160
+ var input = api.toolInput || null;
161
+ if (input && input !== state.toolInput) {
162
+ state.toolInput = input;
163
+ if (handlers.input) handlers.input(input);
164
+ }
165
+ var output = api.toolOutput;
166
+ if (output && output !== lastOutput) {
167
+ lastOutput = output;
168
+ if (handlers.result) handlers.result(output && output.structuredContent ? resultData(output) : output, {});
169
+ }
170
+ }
171
+ window.addEventListener("openai:set_globals", function (event) {
172
+ var globals = (event && event.detail && event.detail.globals) || {};
173
+ if (globals.theme) applyContext({ theme: globals.theme });
174
+ deliver();
175
+ });
176
+ deliver();
177
+ if (window.ResizeObserver) new ResizeObserver(reportSize).observe(document.body);
178
+ reportSize();
179
+ return true;
180
+ }
181
+
182
+ function connect(options) {
183
+ handlers.input = options.onInput || null;
184
+ handlers.result = options.onResult || null;
185
+ handlers.cancelled = options.onCancelled || null;
186
+ handlers.context = options.onContext || null;
187
+ if (!window.parent || window.parent === window) {
188
+ return Promise.resolve(openaiApi() ? connectOpenai() : false);
189
+ }
190
+ // A host with window.openai answers quickly or not at all; do not keep its user waiting a minute.
191
+ return request("ui/initialize", {
192
+ appInfo: { name: options.name, version: "1.0.0" },
193
+ appCapabilities: { availableDisplayModes: ["inline"] },
194
+ protocolVersion: PROTOCOL_VERSION
195
+ }, openaiApi() ? 4000 : 60000).catch(function (error) {
196
+ if (openaiApi()) return null;
197
+ throw error;
198
+ }).then(function (result) {
199
+ if (result === null) return connectOpenai();
200
+ state.hostContext = result.hostContext || {};
201
+ state.hostCapabilities = result.hostCapabilities || {};
202
+ state.connected = true;
203
+ applyContext(state.hostContext);
204
+ notify("ui/notifications/initialized", {});
205
+ if (window.ResizeObserver) new ResizeObserver(reportSize).observe(document.body);
206
+ reportSize();
207
+ return true;
208
+ });
209
+ }
210
+
211
+ /** Post a user message into the conversation (ui/message); falls back to model context. */
212
+ function sendMessage(text) {
213
+ if (state.openai) {
214
+ return Promise.resolve(window.openai.sendFollowUpMessage({ prompt: text }));
215
+ }
216
+ return request("ui/message", { role: "user", content: [{ type: "text", text: text }] }).then(function (res) {
217
+ if (res && res.isError) throw new Error("The host did not accept the message");
218
+ return res;
219
+ });
220
+ }
221
+
222
+ function updateModelContext(text, structured) {
223
+ if (state.openai) return Promise.reject(new Error("Not supported here"));
224
+ var params = { content: [{ type: "text", text: text }] };
225
+ if (structured) params.structuredContent = structured;
226
+ return request("ui/update-model-context", params);
227
+ }
228
+
229
+ function openLink(url) {
230
+ if (state.openai) return Promise.resolve(window.openai.openExternal({ href: url }));
231
+ return request("ui/open-link", { url: url });
232
+ }
233
+
234
+ /** Call a server tool from the widget. Only ever from a user's click (see review.html). */
235
+ function callTool(name, args) {
236
+ if (state.openai) {
237
+ return Promise.resolve(window.openai.callTool(name, args || {})).then(function (res) {
238
+ return res && (res.structuredContent || res.content) ? resultData(res) : res;
239
+ });
240
+ }
241
+ return request("tools/call", { name: name, arguments: args || {} }).then(resultData);
242
+ }
243
+
244
+ function canCallTools() {
245
+ return !!state.hostCapabilities.serverTools;
246
+ }
247
+
248
+ return {
249
+ connect: connect,
250
+ sendMessage: sendMessage,
251
+ updateModelContext: updateModelContext,
252
+ openLink: openLink,
253
+ callTool: callTool,
254
+ canCallTools: canCallTools,
255
+ reportSize: reportSize,
256
+ state: state
257
+ };
258
+ })();
259
+
260
+ /* One preview playing at a time across the widget (audio or video). */
261
+ var Media = (function () {
262
+ "use strict";
263
+ var current = null;
264
+ var onChange = null;
265
+ function stop() {
266
+ if (current) {
267
+ try { current.el.pause(); } catch (e) {}
268
+ var was = current;
269
+ current = null;
270
+ if (onChange) onChange(was.key, false);
271
+ }
272
+ }
273
+ function toggleAudio(key, url) {
274
+ if (current && current.key === key) { stop(); return false; }
275
+ stop();
276
+ var audio = new Audio(url);
277
+ audio.preload = "none";
278
+ current = { key: key, el: audio };
279
+ audio.addEventListener("ended", function () { if (current && current.el === audio) stop(); });
280
+ audio.addEventListener("error", function () {
281
+ if (current && current.el === audio) { stop(); UI.toast("That preview could not be played."); }
282
+ });
283
+ var played = audio.play();
284
+ if (played && played.catch) played.catch(function () {
285
+ if (current && current.el === audio) { stop(); UI.toast("That preview could not be played."); }
286
+ });
287
+ if (onChange) onChange(key, true);
288
+ return true;
289
+ }
290
+ function claimVideo(key, video) {
291
+ if (current && current.el !== video) stop();
292
+ current = { key: key, el: video };
293
+ if (onChange) onChange(key, true);
294
+ }
295
+ function release(video) {
296
+ if (current && current.el === video) { current = null; }
297
+ }
298
+ return {
299
+ stop: stop, toggleAudio: toggleAudio, claimVideo: claimVideo, release: release,
300
+ onChange: function (fn) { onChange = fn; },
301
+ playing: function () { return current ? current.key : null; }
302
+ };
303
+ })();
304
+
305
+ /* Small DOM helpers shared by the widgets. */
306
+ var UI = (function () {
307
+ "use strict";
308
+ function h(tag, attrs, children) {
309
+ var el = document.createElement(tag);
310
+ Object.keys(attrs || {}).forEach(function (key) {
311
+ var value = attrs[key];
312
+ if (value === null || value === undefined || value === false) return;
313
+ if (key === "class") el.className = value;
314
+ else if (key === "text") el.textContent = value;
315
+ else if (key.indexOf("on") === 0 && typeof value === "function") el.addEventListener(key.slice(2), value);
316
+ else if (key === "style" && typeof value === "object") Object.keys(value).forEach(function (k) { el.style[k] = value[k]; });
317
+ else el.setAttribute(key, value === true ? "" : value);
318
+ });
319
+ (children || []).forEach(function (child) {
320
+ if (child === null || child === undefined || child === false) return;
321
+ el.appendChild(typeof child === "string" ? document.createTextNode(child) : child);
322
+ });
323
+ return el;
324
+ }
325
+ function clear(el) { while (el.firstChild) el.removeChild(el.firstChild); return el; }
326
+ var toastTimer = null;
327
+ function toast(text) {
328
+ var el = document.getElementById("toast");
329
+ if (!el) return;
330
+ el.textContent = text;
331
+ el.classList.add("show");
332
+ clearTimeout(toastTimer);
333
+ toastTimer = setTimeout(function () { el.classList.remove("show"); }, 3200);
334
+ }
335
+ /** Send a choice to the chat. If the host refuses ui/message, keep it in model context and say so. */
336
+ function choose(text, structured) {
337
+ return Cliptude.sendMessage(text).then(function () {
338
+ toast("Sent to the chat.");
339
+ return true;
340
+ }).catch(function () {
341
+ return Cliptude.updateModelContext(text, structured).then(function () {
342
+ toast("Saved. Tell Claude to continue and it will use your choice.");
343
+ return true;
344
+ }).catch(function () {
345
+ toast("Copy this into the chat: " + text);
346
+ return false;
347
+ });
348
+ });
349
+ }
350
+ function status(el, text, kind) {
351
+ clear(el).appendChild(h("div", { class: "status " + (kind || ""), role: kind === "error" ? "alert" : "status" }, [text]));
352
+ }
353
+ function initials(name) {
354
+ var letters = String(name || "").replace(/[^\p{L}\p{N}\s]/gu, " ").split(/\s+/).filter(Boolean);
355
+ return (letters.slice(0, 2).map(function (p) { return p[0]; }).join("") || "?").toUpperCase();
356
+ }
357
+ function img(src, alt, fallbackText) {
358
+ var box = h("span", { class: "thumb" });
359
+ if (src) {
360
+ var image = h("img", { src: src, alt: alt || "", loading: "lazy", decoding: "async", referrerpolicy: "no-referrer" });
361
+ image.addEventListener("error", function () {
362
+ box.replaceChild(h("span", { class: "thumb-fallback", "aria-hidden": "true" }, [fallbackText || ""]), image);
363
+ }, { once: true });
364
+ box.appendChild(image);
365
+ } else {
366
+ box.appendChild(h("span", { class: "thumb-fallback", "aria-hidden": "true" }, [fallbackText || ""]));
367
+ }
368
+ return box;
369
+ }
370
+ function errorText(data) {
371
+ if (!data) return "Nothing came back from Cliptude.";
372
+ if (typeof data.error === "string" && data.error) {
373
+ return data.error.indexOf("<") >= 0 ? "Cliptude returned an error" + (data.status ? " (" + data.status + ")" : "") + "." : data.error;
374
+ }
375
+ return "";
376
+ }
377
+ return { h: h, clear: clear, toast: toast, choose: choose, status: status, initials: initials, img: img, errorText: errorText };
378
+ })();
@@ -0,0 +1,108 @@
1
+ <!DOCTYPE html>
2
+ <html lang="en">
3
+ <head>
4
+ <meta charset="utf-8">
5
+ <meta name="viewport" content="width=device-width, initial-scale=1">
6
+ <title>Choose a character</title>
7
+ <style>
8
+ /*@BASE_CSS@*/
9
+ .thumb img { object-fit: contain; background: #fff; }
10
+ .card .desc { color: var(--color-text-secondary); font-size: var(--font-text-xs-size); display: -webkit-box; -webkit-line-clamp: 3; -webkit-box-orient: vertical; overflow: hidden; }
11
+ </style>
12
+ </head>
13
+ <body>
14
+ <main class="app" aria-labelledby="title">
15
+ <div class="head">
16
+ <h1 id="title">Choose a Vector Explainer character</h1>
17
+ <span class="sub" id="count"></span>
18
+ </div>
19
+ <div class="toolbar">
20
+ <label class="sr-only" for="filter">Filter characters</label>
21
+ <input type="search" id="filter" placeholder="Filter characters" autocomplete="off">
22
+ </div>
23
+ <div id="content"><div class="status" role="status">Loading characters…</div></div>
24
+ <div class="selection" id="selection">
25
+ <span class="what" id="selected-text">Pick a character, or go without one.</span>
26
+ <span class="toolbar">
27
+ <button id="none" type="button">No character</button>
28
+ <button class="primary" id="use" type="button" disabled>Use this character</button>
29
+ </span>
30
+ </div>
31
+ </main>
32
+ <div id="toast" role="status" aria-live="polite"></div>
33
+ <script>
34
+ /*@BRIDGE_JS@*/
35
+ (function () {
36
+ "use strict";
37
+ var h = UI.h;
38
+ var data = { builtin: [], uploads: [] };
39
+ var selected = null;
40
+ var content = document.getElementById("content");
41
+
42
+ function matches(c, q) {
43
+ return !q || [c.name, c.descriptor, c.description, c.id].join(" ").toLowerCase().indexOf(q) >= 0;
44
+ }
45
+
46
+ function card(c) {
47
+ return h("button", {
48
+ type: "button", class: "card", role: "listitem", "aria-pressed": String(!!selected && selected.id === c.id),
49
+ "aria-label": c.name + (c.descriptor ? ", " + c.descriptor : ""),
50
+ onclick: function () { select(c); }
51
+ }, [
52
+ UI.img(c.preview_url, "", UI.initials(c.name)),
53
+ h("span", { class: "body" }, [
54
+ h("span", { class: "name" }, [c.name || "Character"]),
55
+ c.descriptor ? h("span", { class: "chips" }, [h("span", { class: "chip" }, [c.descriptor])]) : null,
56
+ c.description ? h("span", { class: "desc" }, [c.description]) : null
57
+ ])
58
+ ]);
59
+ }
60
+
61
+ function section(title, rows) {
62
+ if (!rows.length) return null;
63
+ var grid = h("div", { class: "grid", role: "list", "aria-label": title });
64
+ rows.forEach(function (c) { grid.appendChild(card(c)); });
65
+ return h("section", { class: "list" }, [h("h2", { class: "section-title" }, [title]), grid]);
66
+ }
67
+
68
+ function render() {
69
+ var q = document.getElementById("filter").value.trim().toLowerCase();
70
+ var mine = (data.uploads || []).filter(function (c) { return matches(c, q); });
71
+ var cast = (data.builtin || []).filter(function (c) { return matches(c, q); });
72
+ document.getElementById("count").textContent =
73
+ (data.builtin || []).length + " built-in" + ((data.uploads || []).length ? " · " + data.uploads.length + " yours" : "");
74
+ if (!mine.length && !cast.length) { UI.status(content, q ? "No character matches that filter." : "No characters yet."); return; }
75
+ UI.clear(content).appendChild(h("div", { class: "list" }, [section("Your characters", mine), section("Built-in cast", cast)]));
76
+ }
77
+
78
+ function select(c) {
79
+ selected = c;
80
+ render();
81
+ document.getElementById("use").disabled = false;
82
+ document.getElementById("selected-text").textContent = "“" + c.name + "” · " + c.id;
83
+ }
84
+
85
+ document.getElementById("filter").addEventListener("input", render);
86
+ document.getElementById("use").addEventListener("click", function () {
87
+ if (!selected) return;
88
+ UI.choose("Use the Vector Explainer character “" + selected.name + "” (vector_character_id " + selected.id + ").",
89
+ { vector_character_id: selected.id, vector_character_name: selected.name });
90
+ });
91
+ document.getElementById("none").addEventListener("click", function () {
92
+ UI.choose("Make the Vector Explainer video with no character (leave vector_character_id unset).", { vector_character_id: null });
93
+ });
94
+
95
+ Cliptude.connect({
96
+ name: "cliptude-character-picker",
97
+ onResult: function (result) {
98
+ var err = UI.errorText(result);
99
+ if (err) { UI.status(content, err, "error"); return; }
100
+ data = result || data;
101
+ render();
102
+ },
103
+ onCancelled: function () { UI.status(content, "Cancelled."); }
104
+ }).catch(function () { UI.status(content, "This view could not connect to the chat.", "error"); });
105
+ })();
106
+ </script>
107
+ </body>
108
+ </html>