@nimblebrain/synapse 0.11.0 → 0.12.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.
@@ -0,0 +1,463 @@
1
+ import { applyThemeVariables } from './chunk-VXTMI266.js';
2
+
3
+ // src/host/theme.ts
4
+ function applyHostTheme(theme) {
5
+ if (typeof document !== "undefined") {
6
+ document.documentElement.setAttribute("data-theme", theme.mode);
7
+ }
8
+ applyThemeVariables(theme.mode, theme.tokens);
9
+ }
10
+ function preferredMode(win) {
11
+ try {
12
+ if (win?.matchMedia?.("(prefers-color-scheme: dark)").matches) return "dark";
13
+ } catch {
14
+ }
15
+ return "light";
16
+ }
17
+ function coerceMode(value, fallback) {
18
+ return value === "light" || value === "dark" ? value : fallback;
19
+ }
20
+
21
+ // src/host/types.ts
22
+ var HostUnsupportedError = class extends Error {
23
+ constructor(feature, host) {
24
+ super(`"${feature}" is not supported by the "${host}" host`);
25
+ this.name = "HostUnsupportedError";
26
+ }
27
+ };
28
+ var SYNAPSE_DATA_ELEMENT_ID = "synapse-ui-data";
29
+ var MCPUI_READY = "ui-lifecycle-iframe-ready";
30
+ var MCPUI_RENDER_DATA = "ui-lifecycle-iframe-render-data";
31
+ var MCPUI_SIZE_CHANGE = "ui-size-change";
32
+ var MCPUI_LINK = "link";
33
+ var MCPUI_PROMPT = "prompt";
34
+ var OPENAI_SET_GLOBALS = "openai:set_globals";
35
+ var MCPAPP_PROTOCOL_VERSION = "2026-01-26";
36
+ var MCPAPP_INITIALIZE = "ui/initialize";
37
+ var MCPAPP_INITIALIZED = "ui/notifications/initialized";
38
+ var MCPAPP_TOOL_RESULT = "ui/notifications/tool-result";
39
+ var MCPAPP_HOST_CONTEXT_CHANGED = "ui/notifications/host-context-changed";
40
+ var MCPAPP_SIZE_CHANGED = "ui/notifications/size-changed";
41
+ var MCPAPP_OPEN_LINK = "ui/open-link";
42
+ var MCPAPP_MESSAGE = "ui/message";
43
+ var MCPAPP_TEARDOWN = "ui/resource-teardown";
44
+ var MCP_TOOLS_CALL = "tools/call";
45
+
46
+ // src/host/adapters/chatgpt.ts
47
+ function createChatGPTAdapter(win, _options) {
48
+ const openai = () => win.openai;
49
+ let currentData = openai()?.toolOutput ?? null;
50
+ let currentTheme = {
51
+ mode: coerceMode(openai()?.theme, "light"),
52
+ tokens: {}
53
+ };
54
+ const dataCbs = /* @__PURE__ */ new Set();
55
+ const themeCbs = /* @__PURE__ */ new Set();
56
+ let destroyed = false;
57
+ const onSetGlobals = (event) => {
58
+ if (destroyed) return;
59
+ const globals = event.detail?.globals;
60
+ if (!globals) return;
61
+ if ("toolOutput" in globals && globals.toolOutput != null) {
62
+ currentData = globals.toolOutput;
63
+ for (const cb of dataCbs) cb(currentData);
64
+ }
65
+ if ("theme" in globals && globals.theme != null) {
66
+ const mode = coerceMode(globals.theme, currentTheme.mode);
67
+ if (mode !== currentTheme.mode) {
68
+ currentTheme = { mode, tokens: {} };
69
+ for (const cb of themeCbs) cb(currentTheme);
70
+ }
71
+ }
72
+ };
73
+ return {
74
+ host: "chatgpt",
75
+ getData: () => currentData,
76
+ onData(cb) {
77
+ dataCbs.add(cb);
78
+ return () => dataCbs.delete(cb);
79
+ },
80
+ getTheme: () => currentTheme,
81
+ onTheme(cb) {
82
+ themeCbs.add(cb);
83
+ return () => themeCbs.delete(cb);
84
+ },
85
+ async callTool(name, args) {
86
+ const call = openai()?.callTool;
87
+ if (!call) throw new HostUnsupportedError("callTool", "chatgpt");
88
+ return await call(name, args ?? {});
89
+ },
90
+ sendPrompt(text) {
91
+ const o = openai();
92
+ const send = o?.sendFollowUpMessage ?? o?.sendFollowupMessage;
93
+ send?.({ prompt: text });
94
+ },
95
+ openLink(url) {
96
+ const open = openai()?.openExternal;
97
+ if (open) open({ href: url });
98
+ else win.open(url, "_blank", "noopener,noreferrer");
99
+ },
100
+ resize() {
101
+ },
102
+ capabilities() {
103
+ const o = openai();
104
+ return {
105
+ pull: typeof o?.callTool === "function",
106
+ sendPrompt: typeof o?.sendFollowUpMessage === "function" || typeof o?.sendFollowupMessage === "function",
107
+ openLink: true
108
+ };
109
+ },
110
+ start() {
111
+ win.addEventListener(OPENAI_SET_GLOBALS, onSetGlobals, { passive: true });
112
+ currentData = openai()?.toolOutput ?? currentData;
113
+ },
114
+ destroy() {
115
+ if (destroyed) return;
116
+ destroyed = true;
117
+ win.removeEventListener(OPENAI_SET_GLOBALS, onSetGlobals);
118
+ dataCbs.clear();
119
+ themeCbs.clear();
120
+ }
121
+ };
122
+ }
123
+
124
+ // src/host/data.ts
125
+ function readInlineData(doc, elementId) {
126
+ if (!doc) return null;
127
+ const el = doc.getElementById(elementId);
128
+ const text = el?.textContent;
129
+ if (!text) return null;
130
+ try {
131
+ const parsed = JSON.parse(text);
132
+ return parsed ?? null;
133
+ } catch {
134
+ return null;
135
+ }
136
+ }
137
+ function unwrapRenderData(payload) {
138
+ if (payload == null || typeof payload !== "object") return null;
139
+ const rec = payload;
140
+ const nested = rec.renderData;
141
+ const source = nested != null && typeof nested === "object" ? nested : rec;
142
+ if (source.toolOutput != null) return source.toolOutput;
143
+ if (source.structuredContent != null) return source.structuredContent;
144
+ return source;
145
+ }
146
+
147
+ // src/host/adapters/inline.ts
148
+ function createInlineAdapter(win, options) {
149
+ const dataElementId = options.dataElementId ?? SYNAPSE_DATA_ELEMENT_ID;
150
+ let currentData = null;
151
+ let currentTheme = { mode: preferredMode(win), tokens: {} };
152
+ const themeCbs = /* @__PURE__ */ new Set();
153
+ let destroyed = false;
154
+ let media = null;
155
+ const onSchemeChange = (event) => {
156
+ if (destroyed) return;
157
+ const mode = coerceMode(event.matches ? "dark" : "light", currentTheme.mode);
158
+ if (mode === currentTheme.mode) return;
159
+ currentTheme = { mode, tokens: {} };
160
+ for (const cb of themeCbs) cb(currentTheme);
161
+ };
162
+ return {
163
+ host: "generic",
164
+ getData: () => currentData,
165
+ onData() {
166
+ return () => {
167
+ };
168
+ },
169
+ getTheme: () => currentTheme,
170
+ onTheme(cb) {
171
+ themeCbs.add(cb);
172
+ return () => themeCbs.delete(cb);
173
+ },
174
+ async callTool(_name) {
175
+ throw new HostUnsupportedError("callTool", "generic");
176
+ },
177
+ sendPrompt() {
178
+ },
179
+ openLink(url) {
180
+ win.open(url, "_blank", "noopener,noreferrer");
181
+ },
182
+ resize() {
183
+ },
184
+ capabilities() {
185
+ return { pull: false, sendPrompt: false, openLink: true };
186
+ },
187
+ start() {
188
+ currentData = readInlineData(win.document, dataElementId);
189
+ try {
190
+ media = win.matchMedia?.("(prefers-color-scheme: dark)") ?? null;
191
+ media?.addEventListener?.("change", onSchemeChange);
192
+ } catch {
193
+ media = null;
194
+ }
195
+ },
196
+ destroy() {
197
+ if (destroyed) return;
198
+ destroyed = true;
199
+ media?.removeEventListener?.("change", onSchemeChange);
200
+ media = null;
201
+ themeCbs.clear();
202
+ }
203
+ };
204
+ }
205
+
206
+ // src/host/adapters/mcpapps.ts
207
+ var REQUEST_TIMEOUT_MS = 3e4;
208
+ function createMcpAppsAdapter(win, options) {
209
+ const dataElementId = options.dataElementId ?? SYNAPSE_DATA_ELEMENT_ID;
210
+ const autoResize = options.autoResize !== false;
211
+ let currentData = null;
212
+ let currentTheme = { mode: preferredMode(win), tokens: {} };
213
+ const dataCbs = /* @__PURE__ */ new Set();
214
+ const themeCbs = /* @__PURE__ */ new Set();
215
+ let destroyed = false;
216
+ let standardConfirmed = false;
217
+ let nextId = 1;
218
+ const pending = /* @__PURE__ */ new Map();
219
+ let lastReportedHeight = -1;
220
+ let resizeObserver = null;
221
+ let onWindowResize = null;
222
+ const parent = () => win.parent ?? win;
223
+ function post(message) {
224
+ parent().postMessage(message, "*");
225
+ }
226
+ function postLegacy(message) {
227
+ if (standardConfirmed) return;
228
+ post(message);
229
+ }
230
+ function notify(method, params) {
231
+ post({ jsonrpc: "2.0", method, params: params ?? {} });
232
+ }
233
+ function request(method, params) {
234
+ const id = nextId++;
235
+ return new Promise((resolve, reject) => {
236
+ const timer = setTimeout(() => {
237
+ pending.delete(id);
238
+ reject(new Error(`"${method}" timed out`));
239
+ }, REQUEST_TIMEOUT_MS);
240
+ pending.set(id, { resolve, reject, timer });
241
+ post({ jsonrpc: "2.0", id, method, params: params ?? {} });
242
+ });
243
+ }
244
+ function emitData(next) {
245
+ if (next == null) return;
246
+ currentData = next;
247
+ for (const cb of dataCbs) cb(next);
248
+ }
249
+ function applyHostContext(ctx) {
250
+ if (!ctx || typeof ctx !== "object") return;
251
+ let { mode, tokens } = currentTheme;
252
+ let changed = false;
253
+ if (ctx.theme != null) {
254
+ const next = coerceMode(ctx.theme, mode);
255
+ if (next !== mode) {
256
+ mode = next;
257
+ changed = true;
258
+ }
259
+ }
260
+ const styles = ctx.styles;
261
+ if (styles?.variables && typeof styles.variables === "object") {
262
+ tokens = { ...tokens, ...styles.variables };
263
+ changed = true;
264
+ }
265
+ if (changed) {
266
+ currentTheme = { mode, tokens };
267
+ for (const cb of themeCbs) cb(currentTheme);
268
+ }
269
+ }
270
+ function reportSize(height) {
271
+ if (destroyed) return;
272
+ const h = typeof height === "number" ? height : Math.ceil(win.document.body.scrollHeight);
273
+ if (h === lastReportedHeight) return;
274
+ lastReportedHeight = h;
275
+ notify(MCPAPP_SIZE_CHANGED, { height: h });
276
+ postLegacy({ type: MCPUI_SIZE_CHANGE, payload: { height: h } });
277
+ }
278
+ function handleResponse(d) {
279
+ const id = Number(d.id);
280
+ const p = pending.get(id);
281
+ if (!p) return;
282
+ pending.delete(id);
283
+ clearTimeout(p.timer);
284
+ if (d.error != null) {
285
+ const err = d.error;
286
+ p.reject(new Error(err.message ?? "request failed"));
287
+ } else {
288
+ p.resolve(d.result);
289
+ }
290
+ }
291
+ function handleNotification(method, params) {
292
+ if (method === MCPAPP_TOOL_RESULT) {
293
+ const structured = params.structuredContent;
294
+ emitData(structured != null ? structured : unwrapRenderData(params));
295
+ } else if (method === MCPAPP_HOST_CONTEXT_CHANGED) {
296
+ applyHostContext(params);
297
+ }
298
+ }
299
+ function handleRequest(d) {
300
+ if (d.method === MCPAPP_TEARDOWN) {
301
+ post({ jsonrpc: "2.0", id: d.id, result: {} });
302
+ }
303
+ }
304
+ function handleLegacy(d) {
305
+ if (d.type === MCPUI_RENDER_DATA || d.type === "renderData") {
306
+ const { theme, ...rest } = d.payload ?? {};
307
+ if (theme != null) applyHostContext({ theme });
308
+ if (Object.keys(rest).length > 0) emitData(unwrapRenderData(rest));
309
+ }
310
+ }
311
+ const onMessage = (event) => {
312
+ if (destroyed) return;
313
+ if (event.source && event.source !== parent()) return;
314
+ const d = event.data;
315
+ if (!d || typeof d !== "object") return;
316
+ if (d.jsonrpc !== "2.0") {
317
+ handleLegacy(d);
318
+ return;
319
+ }
320
+ if (d.id != null && ("result" in d || "error" in d)) {
321
+ handleResponse(d);
322
+ } else if (typeof d.method === "string") {
323
+ if (d.id != null) handleRequest(d);
324
+ else handleNotification(d.method, d.params ?? {});
325
+ }
326
+ };
327
+ function setupResize() {
328
+ onWindowResize = () => reportSize();
329
+ win.addEventListener("resize", onWindowResize);
330
+ if (typeof win.ResizeObserver !== "undefined") {
331
+ resizeObserver = new win.ResizeObserver(() => reportSize());
332
+ resizeObserver.observe(win.document.body);
333
+ }
334
+ }
335
+ return {
336
+ host: "claude",
337
+ getData: () => currentData,
338
+ onData(cb) {
339
+ dataCbs.add(cb);
340
+ return () => dataCbs.delete(cb);
341
+ },
342
+ getTheme: () => currentTheme,
343
+ onTheme(cb) {
344
+ themeCbs.add(cb);
345
+ return () => themeCbs.delete(cb);
346
+ },
347
+ async callTool(name, args) {
348
+ return await request(MCP_TOOLS_CALL, { name, arguments: args ?? {} });
349
+ },
350
+ sendPrompt(text) {
351
+ void request(MCPAPP_MESSAGE, { role: "user", content: [{ type: "text", text }] }).catch(
352
+ () => {
353
+ }
354
+ );
355
+ postLegacy({ type: MCPUI_PROMPT, payload: { prompt: text } });
356
+ },
357
+ openLink(url) {
358
+ void request(MCPAPP_OPEN_LINK, { url }).catch(() => {
359
+ });
360
+ postLegacy({ type: MCPUI_LINK, payload: { url } });
361
+ },
362
+ resize(height) {
363
+ reportSize(height);
364
+ },
365
+ capabilities() {
366
+ return { pull: true, sendPrompt: true, openLink: true };
367
+ },
368
+ start() {
369
+ win.addEventListener("message", onMessage);
370
+ currentData = readInlineData(win.document, dataElementId);
371
+ if (autoResize) setupResize();
372
+ post({ type: MCPUI_READY });
373
+ request(MCPAPP_INITIALIZE, {
374
+ appInfo: { name: options.name ?? "synapse-ui", version: options.version ?? "0.0.0" },
375
+ appCapabilities: { availableDisplayModes: ["inline"] },
376
+ protocolVersion: MCPAPP_PROTOCOL_VERSION
377
+ }).then((result) => {
378
+ if (destroyed) return;
379
+ standardConfirmed = true;
380
+ applyHostContext(result?.hostContext);
381
+ notify(MCPAPP_INITIALIZED, {});
382
+ lastReportedHeight = -1;
383
+ reportSize();
384
+ }).catch(() => {
385
+ });
386
+ reportSize();
387
+ },
388
+ destroy() {
389
+ if (destroyed) return;
390
+ destroyed = true;
391
+ win.removeEventListener("message", onMessage);
392
+ if (onWindowResize) win.removeEventListener("resize", onWindowResize);
393
+ onWindowResize = null;
394
+ resizeObserver?.disconnect();
395
+ resizeObserver = null;
396
+ for (const p of pending.values()) {
397
+ clearTimeout(p.timer);
398
+ p.reject(new Error("adapter destroyed"));
399
+ }
400
+ pending.clear();
401
+ dataCbs.clear();
402
+ themeCbs.clear();
403
+ }
404
+ };
405
+ }
406
+
407
+ // src/host/detect.ts
408
+ function detectHostKind(win) {
409
+ if (win.openai != null) return "chatgpt";
410
+ try {
411
+ if (win.parent != null && win.parent !== win) return "claude";
412
+ } catch {
413
+ return "claude";
414
+ }
415
+ return "generic";
416
+ }
417
+ function adapterForKind(kind, win, options) {
418
+ switch (kind) {
419
+ case "chatgpt":
420
+ return createChatGPTAdapter(win);
421
+ case "claude":
422
+ case "nimblebrain":
423
+ return createMcpAppsAdapter(win, options);
424
+ default:
425
+ return createInlineAdapter(win, options);
426
+ }
427
+ }
428
+ function selectAdapter(win, options) {
429
+ const kind = options.host ?? detectHostKind(win);
430
+ return adapterForKind(kind, win, options);
431
+ }
432
+
433
+ // src/host/connect.ts
434
+ function connectUI(options = {}) {
435
+ const win = options.window ?? globalThis;
436
+ const adapter = selectAdapter(win, options);
437
+ applyHostTheme(adapter.getTheme());
438
+ const unsubTheme = adapter.onTheme(applyHostTheme);
439
+ adapter.start();
440
+ let destroyed = false;
441
+ return {
442
+ data: () => adapter.getData(),
443
+ onData: (cb) => adapter.onData(cb),
444
+ theme: () => adapter.getTheme(),
445
+ onTheme: (cb) => adapter.onTheme(cb),
446
+ callTool: (name, args) => adapter.callTool(name, args),
447
+ sendPrompt: (text) => adapter.sendPrompt(text),
448
+ openLink: (url) => adapter.openLink(url),
449
+ resize: (height) => adapter.resize(height),
450
+ capabilities: () => adapter.capabilities(),
451
+ host: () => adapter.host,
452
+ destroy() {
453
+ if (destroyed) return;
454
+ destroyed = true;
455
+ unsubTheme();
456
+ adapter.destroy();
457
+ }
458
+ };
459
+ }
460
+
461
+ export { HostUnsupportedError, SYNAPSE_DATA_ELEMENT_ID, adapterForKind, applyHostTheme, coerceMode, connectUI, createChatGPTAdapter, createInlineAdapter, createMcpAppsAdapter, detectHostKind, preferredMode, selectAdapter };
462
+ //# sourceMappingURL=chunk-JVKQNMAP.js.map
463
+ //# sourceMappingURL=chunk-JVKQNMAP.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/host/theme.ts","../src/host/types.ts","../src/host/adapters/chatgpt.ts","../src/host/data.ts","../src/host/adapters/inline.ts","../src/host/adapters/mcpapps.ts","../src/host/detect.ts","../src/host/connect.ts"],"names":[],"mappings":";;;AAkBO,SAAS,eAAe,KAAA,EAA6B;AAC1D,EAAA,IAAI,OAAO,aAAa,WAAA,EAAa;AACnC,IAAA,QAAA,CAAS,eAAA,CAAgB,YAAA,CAAa,YAAA,EAAc,KAAA,CAAM,IAAI,CAAA;AAAA,EAChE;AACA,EAAA,mBAAA,CAAoB,KAAA,CAAM,IAAA,EAAM,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AAA,CAAQ,OAAA,CAAQ,cAAc,CAAA;AAEjD,EAAA,OAAA,CAAQ,KAAA,EAAM;AAEd,EAAA,IAAI,SAAA,GAAY,KAAA;AAEhB,EAAA,OAAO;AAAA,IACL,IAAA,EAAM,MAAS,OAAA,CAAQ,OAAA,EAAW;AAAA,IAClC,MAAA,EAAQ,CAAI,EAAA,KAA0B,OAAA,CAAQ,OAAU,EAAE,CAAA;AAAA,IAC1D,KAAA,EAAO,MAAM,OAAA,CAAQ,QAAA,EAAS;AAAA,IAC9B,OAAA,EAAS,CAAC,EAAA,KAAO,OAAA,CAAQ,QAAQ,EAAE,CAAA;AAAA,IACnC,UAAU,CAAI,IAAA,EAAc,SAAmC,OAAA,CAAQ,QAAA,CAAY,MAAM,IAAI,CAAA;AAAA,IAC7F,UAAA,EAAY,CAAC,IAAA,KAAiB,OAAA,CAAQ,WAAW,IAAI,CAAA;AAAA,IACrD,QAAA,EAAU,CAAC,GAAA,KAAgB,OAAA,CAAQ,SAAS,GAAG,CAAA;AAAA,IAC/C,MAAA,EAAQ,CAAC,MAAA,KAAoB,OAAA,CAAQ,OAAO,MAAM,CAAA;AAAA,IAClD,YAAA,EAAc,MAAM,OAAA,CAAQ,YAAA,EAAa;AAAA,IACzC,IAAA,EAAM,MAAM,OAAA,CAAQ,IAAA;AAAA,IACpB,OAAA,GAAU;AACR,MAAA,IAAI,SAAA,EAAW;AACf,MAAA,SAAA,GAAY,IAAA;AACZ,MAAA,UAAA,EAAW;AACX,MAAA,OAAA,CAAQ,OAAA,EAAQ;AAAA,IAClB;AAAA,GACF;AACF","file":"chunk-JVKQNMAP.js","sourcesContent":["import { applyThemeVariables } from \"../theme-defaults.js\";\nimport type { SynapseUITheme } from \"./types.js\";\n\n/**\n * Apply a resolved theme to the DOM for the cross-host client.\n *\n * Two conventions coexist across Synapse components, so the client drives both:\n *\n * - `document.documentElement[data-theme=\"light\"|\"dark\"]` — how self-contained\n * HTML components (Bassethound's report) gate their `--var` palettes, and the\n * lever a host's light/dark signal actually flips.\n * - CSS custom properties via {@link applyThemeVariables} — how the\n * `@nimblebrain/synapse/ui` token components consume theme, backed by the\n * SDK's neutral defaults so every referenced var resolves in both modes.\n *\n * Setting both means an app can use either convention (or a host that supplies\n * only a mode string, like the OpenAI Apps SDK, still themes correctly). SSR-safe.\n */\nexport function applyHostTheme(theme: SynapseUITheme): void {\n if (typeof document !== \"undefined\") {\n document.documentElement.setAttribute(\"data-theme\", theme.mode);\n }\n applyThemeVariables(theme.mode, theme.tokens);\n}\n\n/** Read the OS-level color scheme as a sane default for hosts that don't push a\n * theme until later (mcp-ui) or ever (standalone). */\nexport function preferredMode(win: Window | undefined): \"light\" | \"dark\" {\n try {\n if (win?.matchMedia?.(\"(prefers-color-scheme: dark)\").matches) return \"dark\";\n } catch {\n // matchMedia unavailable (older test envs) — fall through to light.\n }\n return \"light\";\n}\n\n/** Coerce an arbitrary host-supplied theme signal to a mode. Accepts the string\n * form (`\"dark\"`) both hosts use; anything else falls back. */\nexport function coerceMode(value: unknown, fallback: \"light\" | \"dark\"): \"light\" | \"dark\" {\n return value === \"light\" || value === \"dark\" ? value : fallback;\n}\n","/**\n * Cross-host UI client — types and wire constants.\n *\n * The cross-host client (`connectUI`) renders one Synapse-authored component in\n * hosts that each speak a different bridge: ChatGPT (OpenAI Apps SDK), Claude\n * (mcp-ui), and plain/standalone. Apps code against `synapse.*` and never touch\n * a host protocol. This is a **push-first** surface: the tool output that spawned\n * the widget is delivered at render (`data()` / `onData()`); `callTool()` is the\n * pull escape hatch, advertised per host via `capabilities()`.\n *\n * This layer intentionally has ZERO dependency on `@modelcontextprotocol/*` — the\n * ChatGPT / mcp-ui / inline bridges are pure `window.openai` + `postMessage`, so\n * the IIFE that apps inline stays tiny (no Zod, no ext-apps schemas).\n */\n\n/**\n * The host the client resolved to, as reported by `synapse.host()`. An escape\n * hatch — apps should rarely branch on it; `capabilities()` is the supported way\n * to feature-detect. `\"nimblebrain\"` is reserved for the runtime adapter (P3).\n */\nexport type HostKind = \"chatgpt\" | \"claude\" | \"nimblebrain\" | \"generic\";\n\n/** Resolved theme. `mode` always resolves to light or dark. `tokens` are CSS\n * custom properties the host publishes — the MCP Apps adapter reads them from\n * `hostContext.styles.variables`; where a host sends none they stay empty and the\n * SDK's neutral defaults back them. */\nexport interface SynapseUITheme {\n mode: \"light\" | \"dark\";\n tokens: Record<string, string>;\n}\n\n/** What the active host actually supports. `data()`/`onData()`/`theme()`/\n * `resize()` work everywhere; these three vary. */\nexport interface HostCapabilities {\n /** `callTool()` can reach the server (widget→server fetch). */\n pull: boolean;\n /** `sendPrompt()` reaches the agent conversation. */\n sendPrompt: boolean;\n /** `openLink()` opens an external URL through the host. */\n openLink: boolean;\n}\n\n/** Thrown by `callTool()` when the active host offers no widget→server call. */\nexport class HostUnsupportedError extends Error {\n constructor(feature: string, host: HostKind) {\n super(`\"${feature}\" is not supported by the \"${host}\" host`);\n this.name = \"HostUnsupportedError\";\n }\n}\n\nexport interface ConnectUIOptions {\n /** App name — informational; forwarded to hosts that accept an appInfo. */\n name?: string;\n /** App semver — informational. */\n version?: string;\n /**\n * Force a host adapter instead of auto-detecting. Used by preview harnesses,\n * SSR, and tests; production apps omit it and let the SDK feature-detect.\n * `\"claude\"` → MCP Apps standard adapter, `\"chatgpt\"` → OpenAI Apps adapter,\n * `\"generic\"` → inline adapter.\n */\n host?: HostKind;\n /**\n * `id` of the `<script type=\"application/json\">` element carrying pushed data\n * baked into the HTML (the mcp-ui / SSR path). Defaults to\n * {@link SYNAPSE_DATA_ELEMENT_ID}.\n */\n dataElementId?: string;\n /**\n * Auto-report content height to the host on layout changes (mcp-ui only).\n * Defaults to `true`. Set `false` to size manually via `resize()`.\n */\n autoResize?: boolean;\n /** Window to bind to. Defaults to the global `window`. Injectable for tests. */\n window?: Window & typeof globalThis;\n}\n\n/**\n * The public cross-host client. Bound to `synapse` by convention.\n *\n * ```ts\n * const synapse = connectUI();\n * synapse.onData(render); // future pushes/updates\n * render(synapse.data()); // current value (may be null → empty state)\n * ```\n */\nexport interface SynapseUIClient {\n /** The current pushed data, or `null` before anything has been delivered. */\n data<T = unknown>(): T | null;\n /** Subscribe to data updates (NOT replayed — read `data()` for the current\n * value). Returns an unsubscribe. */\n onData<T = unknown>(cb: (data: T) => void): () => void;\n\n /** The current resolved theme. */\n theme(): SynapseUITheme;\n /** Subscribe to theme changes. The client already applies the theme to the DOM\n * (`data-theme` attribute + CSS variables) before this fires. */\n onTheme(cb: (theme: SynapseUITheme) => void): () => void;\n\n /** Widget→server tool call. Rejects with {@link HostUnsupportedError} where the\n * host advertises no pull (`capabilities().pull === false`). */\n callTool<O = unknown>(name: string, args?: Record<string, unknown>): Promise<O>;\n /** Send a follow-up message to the agent conversation. No-op where unsupported. */\n sendPrompt(text: string): void;\n /** Open an external URL through the host (falls back to `window.open`). */\n openLink(url: string): void;\n /** Report content height to the host. Omit `height` to measure `document.body`. */\n resize(height?: number): void;\n\n /** What the active host supports. */\n capabilities(): HostCapabilities;\n /** The resolved host — an escape hatch; prefer `capabilities()`. */\n host(): HostKind;\n /** Tear down listeners/observers. */\n destroy(): void;\n}\n\n/**\n * Internal adapter contract. One per host bridge; the client is a thin façade\n * over the selected adapter.\n */\nexport interface HostAdapter {\n readonly host: HostKind;\n getData<T = unknown>(): T | null;\n onData<T = unknown>(cb: (data: T) => void): () => void;\n getTheme(): SynapseUITheme;\n onTheme(cb: (theme: SynapseUITheme) => void): () => void;\n callTool<O = unknown>(name: string, args?: Record<string, unknown>): Promise<O>;\n sendPrompt(text: string): void;\n openLink(url: string): void;\n resize(height?: number): void;\n capabilities(): HostCapabilities;\n /** Begin listening / send the ready handshake / read baked-in data. Called once\n * by `connectUI` synchronously so `getData()` is populated on return. */\n start(): void;\n destroy(): void;\n}\n\n// ---------------------------------------------------------------------------\n// Wire constants — the bridge message shapes each host speaks. Centralized so a\n// host protocol tweak is a one-line change, not a grep-and-pray.\n// ---------------------------------------------------------------------------\n\n/** Default `id` of the baked-in data `<script type=\"application/json\">`. */\nexport const SYNAPSE_DATA_ELEMENT_ID = \"synapse-ui-data\";\n\n/** mcp-ui iframe-lifecycle messages (child → host, host → child). */\nexport const MCPUI_READY = \"ui-lifecycle-iframe-ready\";\nexport const MCPUI_RENDER_DATA = \"ui-lifecycle-iframe-render-data\";\nexport const MCPUI_SIZE_CHANGE = \"ui-size-change\";\n/** mcp-ui action messages (child → host). */\nexport const MCPUI_LINK = \"link\";\nexport const MCPUI_PROMPT = \"prompt\";\n\n/** OpenAI Apps SDK globals-broadcast event (host → child). */\nexport const OPENAI_SET_GLOBALS = \"openai:set_globals\";\n\n// ---------------------------------------------------------------------------\n// MCP Apps standard (SEP-1865) — the convergence bridge, primary for Claude\n// Desktop and the NimbleBrain runtime. The View iframe is an MCP client and the\n// host an MCP server; they exchange raw JSON-RPC 2.0 objects over `postMessage`\n// (no wrapper envelope). Method names are canonical to the ext-apps spec.\n// ---------------------------------------------------------------------------\n\n/** Protocol version exchanged in the `ui/initialize` handshake. */\nexport const MCPAPP_PROTOCOL_VERSION = \"2026-01-26\";\n/** View → host handshake request; the result carries the host context. */\nexport const MCPAPP_INITIALIZE = \"ui/initialize\";\n/** View → host notification sent once after the init result — the host holds all\n * pushes until it arrives. */\nexport const MCPAPP_INITIALIZED = \"ui/notifications/initialized\";\n/** Host → view notification carrying the tool output. `params` IS the\n * `CallToolResult` (data at `params.structuredContent`) — no `result` wrapper. */\nexport const MCPAPP_TOOL_RESULT = \"ui/notifications/tool-result\";\n/** Host → view notification carrying a partial host context (theme, styles, …). */\nexport const MCPAPP_HOST_CONTEXT_CHANGED = \"ui/notifications/host-context-changed\";\n/** View → host notification reporting intrinsic size (`{ width?, height? }`). A\n * host may keep the frame hidden until it receives one, so it is sent promptly. */\nexport const MCPAPP_SIZE_CHANGED = \"ui/notifications/size-changed\";\n/** View → host request: open an external URL (`{ url }`). */\nexport const MCPAPP_OPEN_LINK = \"ui/open-link\";\n/** View → host request: send a follow-up to the conversation\n * (`{ role: \"user\", content: ContentBlock[] }`). */\nexport const MCPAPP_MESSAGE = \"ui/message\";\n/** Host → view request: graceful teardown; the view replies `{}`. */\nexport const MCPAPP_TEARDOWN = \"ui/resource-teardown\";\n/** Standard MCP method the View may call over the same channel (pull). */\nexport const MCP_TOOLS_CALL = \"tools/call\";\n","import { coerceMode } from \"../theme.js\";\nimport {\n type ConnectUIOptions,\n type HostAdapter,\n type HostCapabilities,\n HostUnsupportedError,\n OPENAI_SET_GLOBALS,\n type SynapseUITheme,\n} from \"../types.js\";\n\n/**\n * The subset of the OpenAI Apps SDK `window.openai` surface this adapter uses.\n * All members are optional — the SDK version a host ships may not carry every\n * one, so each call is guarded and degraded.\n */\ninterface OpenAiHost {\n toolOutput?: unknown;\n theme?: unknown;\n callTool?: (name: string, args?: Record<string, unknown>) => Promise<unknown>;\n sendFollowUpMessage?: (arg: { prompt: string }) => void;\n /** Older casing seen in the wild — tried as a fallback. */\n sendFollowupMessage?: (arg: { prompt: string }) => void;\n openExternal?: (arg: { href: string }) => void;\n}\n\ninterface SetGlobalsDetail {\n globals?: { toolOutput?: unknown; theme?: unknown };\n}\n\n/**\n * ChatGPT (OpenAI Apps SDK) adapter.\n *\n * Data arrives on `window.openai.toolOutput` (available synchronously before the\n * widget script runs) and updates via the `openai:set_globals` event. Theme is a\n * mode string on the same surface. The host auto-sizes the iframe, so `resize()`\n * is a no-op. `callTool` is available when the host exposes `window.openai.callTool`.\n */\nexport function createChatGPTAdapter(\n win: Window & typeof globalThis,\n _options: ConnectUIOptions,\n): HostAdapter {\n const openai = () => (win as unknown as { openai?: OpenAiHost }).openai;\n\n let currentData: unknown = openai()?.toolOutput ?? null;\n let currentTheme: SynapseUITheme = {\n mode: coerceMode(openai()?.theme, \"light\"),\n tokens: {},\n };\n\n const dataCbs = new Set<(d: unknown) => void>();\n const themeCbs = new Set<(t: SynapseUITheme) => void>();\n let destroyed = false;\n\n const onSetGlobals = (event: Event) => {\n if (destroyed) return;\n const globals = (event as CustomEvent<SetGlobalsDetail>).detail?.globals;\n if (!globals) return;\n if (\"toolOutput\" in globals && globals.toolOutput != null) {\n currentData = globals.toolOutput;\n for (const cb of dataCbs) cb(currentData);\n }\n if (\"theme\" in globals && globals.theme != null) {\n const mode = coerceMode(globals.theme, currentTheme.mode);\n if (mode !== currentTheme.mode) {\n currentTheme = { mode, tokens: {} };\n for (const cb of themeCbs) cb(currentTheme);\n }\n }\n };\n\n return {\n host: \"chatgpt\",\n getData: <T>() => currentData as T | null,\n onData(cb) {\n dataCbs.add(cb as (d: unknown) => void);\n return () => dataCbs.delete(cb as (d: unknown) => void);\n },\n getTheme: () => currentTheme,\n onTheme(cb) {\n themeCbs.add(cb);\n return () => themeCbs.delete(cb);\n },\n async callTool<O>(name: string, args?: Record<string, unknown>): Promise<O> {\n const call = openai()?.callTool;\n if (!call) throw new HostUnsupportedError(\"callTool\", \"chatgpt\");\n return (await call(name, args ?? {})) as O;\n },\n sendPrompt(text: string) {\n const o = openai();\n const send = o?.sendFollowUpMessage ?? o?.sendFollowupMessage;\n send?.({ prompt: text });\n },\n openLink(url: string) {\n const open = openai()?.openExternal;\n if (open) open({ href: url });\n else win.open(url, \"_blank\", \"noopener,noreferrer\");\n },\n resize() {\n // ChatGPT auto-sizes the widget iframe — nothing to report.\n },\n capabilities(): HostCapabilities {\n const o = openai();\n return {\n pull: typeof o?.callTool === \"function\",\n sendPrompt:\n typeof o?.sendFollowUpMessage === \"function\" ||\n typeof o?.sendFollowupMessage === \"function\",\n openLink: true,\n };\n },\n start() {\n win.addEventListener(OPENAI_SET_GLOBALS, onSetGlobals as EventListener, { passive: true });\n // Re-read in case the host mutated globals between construction and start.\n currentData = openai()?.toolOutput ?? currentData;\n },\n destroy() {\n if (destroyed) return;\n destroyed = true;\n win.removeEventListener(OPENAI_SET_GLOBALS, onSetGlobals as EventListener);\n dataCbs.clear();\n themeCbs.clear();\n },\n };\n}\n","/**\n * Read data baked into the HTML as `<script type=\"application/json\" id=…>`.\n *\n * This is how the mcp-ui embedded-resource path and SSR/standalone deliver the\n * pushed tool output with no round-trip: the server helper escapes the payload\n * and substitutes it into the element (see the Python `SynapseUI.render_html`).\n * A data-free template leaves the marker comment in place, which fails\n * `JSON.parse` and reads back as `null` — exactly the \"no data yet\" state.\n */\nexport function readInlineData<T = unknown>(\n doc: Document | undefined,\n elementId: string,\n): T | null {\n if (!doc) return null;\n const el = doc.getElementById(elementId);\n const text = el?.textContent;\n if (!text) return null;\n try {\n const parsed = JSON.parse(text);\n return (parsed ?? null) as T | null;\n } catch {\n // Unreplaced marker or malformed blob — treat as no data.\n return null;\n }\n}\n\n/**\n * Pull the app payload out of an arbitrary render-data envelope. Hosts wrap the\n * tool output differently (`renderData`, `toolOutput`, `structuredContent`, or\n * the bare object), so unwrap the known envelope keys, else pass the object\n * through. Kept framework-generic — no app-specific keys.\n */\nexport function unwrapRenderData<T = unknown>(payload: unknown): T | null {\n if (payload == null || typeof payload !== \"object\") return null;\n const rec = payload as Record<string, unknown>;\n const nested = rec.renderData;\n const source =\n nested != null && typeof nested === \"object\" ? (nested as Record<string, unknown>) : rec;\n if (source.toolOutput != null) return source.toolOutput as T;\n if (source.structuredContent != null) return source.structuredContent as T;\n // No bare `data` envelope key — too ambiguous with an app's own `data` field.\n return source as T;\n}\n","import { readInlineData } from \"../data.js\";\nimport { coerceMode, preferredMode } from \"../theme.js\";\nimport {\n type ConnectUIOptions,\n type HostAdapter,\n type HostCapabilities,\n HostUnsupportedError,\n SYNAPSE_DATA_ELEMENT_ID,\n type SynapseUITheme,\n} from \"../types.js\";\n\n/**\n * Inline / standalone fallback adapter.\n *\n * No live host bridge — used for SSR, previews, and a plain browser render. Data\n * comes only from the baked-in `<script type=\"application/json\">` blob; there is\n * nothing to push, so `onData` never fires after `start()`. Theme follows the OS\n * color scheme and tracks `prefers-color-scheme` changes. `openLink` opens a new\n * tab; `sendPrompt`/`callTool` have no destination.\n */\nexport function createInlineAdapter(\n win: Window & typeof globalThis,\n options: ConnectUIOptions,\n): HostAdapter {\n const dataElementId = options.dataElementId ?? SYNAPSE_DATA_ELEMENT_ID;\n\n let currentData: unknown = null;\n let currentTheme: SynapseUITheme = { mode: preferredMode(win), tokens: {} };\n\n const themeCbs = new Set<(t: SynapseUITheme) => void>();\n let destroyed = false;\n let media: MediaQueryList | null = null;\n\n const onSchemeChange = (event: MediaQueryListEvent) => {\n if (destroyed) return;\n const mode = coerceMode(event.matches ? \"dark\" : \"light\", currentTheme.mode);\n if (mode === currentTheme.mode) return;\n currentTheme = { mode, tokens: {} };\n for (const cb of themeCbs) cb(currentTheme);\n };\n\n return {\n host: \"generic\",\n getData: <T>() => currentData as T | null,\n onData() {\n // Static render — no updates after the initial baked-in read.\n return () => {};\n },\n getTheme: () => currentTheme,\n onTheme(cb) {\n themeCbs.add(cb);\n return () => themeCbs.delete(cb);\n },\n async callTool<O>(_name: string): Promise<O> {\n throw new HostUnsupportedError(\"callTool\", \"generic\");\n },\n sendPrompt() {\n // No agent to reach in a standalone render.\n },\n openLink(url: string) {\n win.open(url, \"_blank\", \"noopener,noreferrer\");\n },\n resize() {\n // No host to size for.\n },\n capabilities(): HostCapabilities {\n return { pull: false, sendPrompt: false, openLink: true };\n },\n start() {\n currentData = readInlineData(win.document, dataElementId);\n try {\n media = win.matchMedia?.(\"(prefers-color-scheme: dark)\") ?? null;\n media?.addEventListener?.(\"change\", onSchemeChange);\n } catch {\n media = null;\n }\n },\n destroy() {\n if (destroyed) return;\n destroyed = true;\n media?.removeEventListener?.(\"change\", onSchemeChange);\n media = null;\n themeCbs.clear();\n },\n };\n}\n","import { readInlineData, unwrapRenderData } from \"../data.js\";\nimport { coerceMode, preferredMode } from \"../theme.js\";\nimport {\n type ConnectUIOptions,\n type HostAdapter,\n type HostCapabilities,\n MCP_TOOLS_CALL,\n MCPAPP_HOST_CONTEXT_CHANGED,\n MCPAPP_INITIALIZE,\n MCPAPP_INITIALIZED,\n MCPAPP_MESSAGE,\n MCPAPP_OPEN_LINK,\n MCPAPP_PROTOCOL_VERSION,\n MCPAPP_SIZE_CHANGED,\n MCPAPP_TEARDOWN,\n MCPAPP_TOOL_RESULT,\n MCPUI_LINK,\n MCPUI_PROMPT,\n MCPUI_READY,\n MCPUI_RENDER_DATA,\n MCPUI_SIZE_CHANGE,\n SYNAPSE_DATA_ELEMENT_ID,\n type SynapseUITheme,\n} from \"../types.js\";\n\n/** How long a widget→host request (`callTool`, `openLink`, `sendPrompt`) waits\n * for its response before rejecting, so a silent host never hangs a promise. */\nconst REQUEST_TIMEOUT_MS = 30_000;\n\ninterface PendingRequest {\n resolve: (value: unknown) => void;\n reject: (reason: unknown) => void;\n timer: ReturnType<typeof setTimeout>;\n}\n\n/**\n * MCP Apps standard (SEP-1865) adapter — the convergence bridge for Claude\n * Desktop and other MCP Apps hosts.\n *\n * The View iframe is an MCP client speaking JSON-RPC 2.0 to `window.parent`:\n *\n * 1. posts `ui/initialize` and awaits the host context (theme, style variables);\n * 2. posts `ui/notifications/initialized`, then a `size-changed` — a host keeps\n * the frame hidden until it has both the handshake and a size;\n * 3. receives data via `ui/notifications/tool-result` (`params` IS the\n * `CallToolResult`, so data is at `params.structuredContent`) and theme via\n * `ui/notifications/host-context-changed`.\n *\n * Actions go up as requests: `ui/open-link`, `ui/message` (follow-up), and\n * `tools/call` (pull). The legacy mcp-ui `ui-lifecycle-*` messages are sent and\n * accepted alongside so a pre-standard host still renders — a standard host drops\n * the non-JSON-RPC frames, and a legacy host ignores the JSON-RPC ones.\n */\nexport function createMcpAppsAdapter(\n win: Window & typeof globalThis,\n options: ConnectUIOptions,\n): HostAdapter {\n const dataElementId = options.dataElementId ?? SYNAPSE_DATA_ELEMENT_ID;\n const autoResize = options.autoResize !== false;\n\n let currentData: unknown = null;\n let currentTheme: SynapseUITheme = { mode: preferredMode(win), tokens: {} };\n\n const dataCbs = new Set<(d: unknown) => void>();\n const themeCbs = new Set<(t: SynapseUITheme) => void>();\n let destroyed = false;\n // Set once `ui/initialize` resolves — proof we're on an MCP Apps standard host,\n // which lets us stop mirroring actions to the legacy shim.\n let standardConfirmed = false;\n let nextId = 1;\n const pending = new Map<number, PendingRequest>();\n let lastReportedHeight = -1;\n let resizeObserver: ResizeObserver | null = null;\n let onWindowResize: (() => void) | null = null;\n\n const parent = () => win.parent ?? win;\n\n function post(message: Record<string, unknown>): void {\n parent().postMessage(message, \"*\");\n }\n\n // The legacy mcp-ui frames (render-data in, size/link/prompt out) are a\n // transitional shim for the one host that still speaks it — the NimbleBrain\n // runtime, which shares this adapter via the `nimblebrain` kind until the P3\n // `nimblebrain` adapter lands and this shim is removed. Once the handshake\n // confirms a standard host we stop mirroring, so a host that understood both\n // dialects never acts on an action twice.\n function postLegacy(message: Record<string, unknown>): void {\n if (standardConfirmed) return;\n post(message);\n }\n\n function notify(method: string, params?: Record<string, unknown>): void {\n post({ jsonrpc: \"2.0\", method, params: params ?? {} });\n }\n\n function request<T = unknown>(method: string, params?: Record<string, unknown>): Promise<T> {\n const id = nextId++;\n return new Promise<T>((resolve, reject) => {\n const timer = setTimeout(() => {\n pending.delete(id);\n reject(new Error(`\"${method}\" timed out`));\n }, REQUEST_TIMEOUT_MS);\n pending.set(id, { resolve: resolve as (v: unknown) => void, reject, timer });\n post({ jsonrpc: \"2.0\", id, method, params: params ?? {} });\n });\n }\n\n function emitData(next: unknown): void {\n if (next == null) return;\n currentData = next;\n for (const cb of dataCbs) cb(next);\n }\n\n /** Merge a full or partial host context into the resolved theme (mode + tokens). */\n function applyHostContext(ctx: Record<string, unknown> | null | undefined): void {\n if (!ctx || typeof ctx !== \"object\") return;\n let { mode, tokens } = currentTheme;\n let changed = false;\n if (ctx.theme != null) {\n const next = coerceMode(ctx.theme, mode);\n if (next !== mode) {\n mode = next;\n changed = true;\n }\n }\n const styles = ctx.styles as { variables?: Record<string, string> } | undefined;\n if (styles?.variables && typeof styles.variables === \"object\") {\n tokens = { ...tokens, ...styles.variables };\n changed = true;\n }\n if (changed) {\n currentTheme = { mode, tokens };\n for (const cb of themeCbs) cb(currentTheme);\n }\n }\n\n function reportSize(height?: number): void {\n if (destroyed) return;\n const h = typeof height === \"number\" ? height : Math.ceil(win.document.body.scrollHeight);\n if (h === lastReportedHeight) return;\n lastReportedHeight = h;\n notify(MCPAPP_SIZE_CHANGED, { height: h });\n postLegacy({ type: MCPUI_SIZE_CHANGE, payload: { height: h } });\n }\n\n function handleResponse(d: Record<string, unknown>): void {\n // Normalize the echoed id: JSON-RPC requires a same-type echo, but a lax host\n // that returned \"1\" for 1 would otherwise miss the numeric-keyed pending map.\n const id = Number(d.id);\n const p = pending.get(id);\n if (!p) return;\n pending.delete(id);\n clearTimeout(p.timer);\n if (d.error != null) {\n const err = d.error as { message?: string };\n p.reject(new Error(err.message ?? \"request failed\"));\n } else {\n p.resolve(d.result);\n }\n }\n\n function handleNotification(method: string, params: Record<string, unknown>): void {\n if (method === MCPAPP_TOOL_RESULT) {\n // `params` is the CallToolResult: the render data lives at structuredContent.\n const structured = params.structuredContent;\n emitData(structured != null ? structured : unwrapRenderData(params));\n } else if (method === MCPAPP_HOST_CONTEXT_CHANGED) {\n applyHostContext(params);\n }\n }\n\n function handleRequest(d: Record<string, unknown>): void {\n // The one host→view request we honor: acknowledge teardown so the host can\n // dispose the frame cleanly.\n if (d.method === MCPAPP_TEARDOWN) {\n post({ jsonrpc: \"2.0\", id: d.id, result: {} });\n }\n }\n\n /** Legacy mcp-ui render-data (non-JSON-RPC) — a pre-standard host's data path. */\n function handleLegacy(d: Record<string, unknown>): void {\n if (d.type === MCPUI_RENDER_DATA || d.type === \"renderData\") {\n const { theme, ...rest } = (d.payload ?? {}) as Record<string, unknown>;\n if (theme != null) applyHostContext({ theme });\n if (Object.keys(rest).length > 0) emitData(unwrapRenderData(rest));\n }\n }\n\n const onMessage = (event: MessageEvent) => {\n if (destroyed) return;\n // Accept only frames from the host window when the browser sets a source.\n if (event.source && event.source !== parent()) return;\n const d = event.data as Record<string, unknown> | null | undefined;\n if (!d || typeof d !== \"object\") return;\n if (d.jsonrpc !== \"2.0\") {\n handleLegacy(d);\n return;\n }\n if (d.id != null && (\"result\" in d || \"error\" in d)) {\n handleResponse(d);\n } else if (typeof d.method === \"string\") {\n if (d.id != null) handleRequest(d);\n else handleNotification(d.method, (d.params ?? {}) as Record<string, unknown>);\n }\n };\n\n function setupResize(): void {\n onWindowResize = () => reportSize();\n win.addEventListener(\"resize\", onWindowResize);\n if (typeof win.ResizeObserver !== \"undefined\") {\n resizeObserver = new win.ResizeObserver(() => reportSize());\n resizeObserver.observe(win.document.body);\n }\n }\n\n return {\n host: \"claude\",\n getData: <T>() => currentData as T | null,\n onData(cb) {\n dataCbs.add(cb as (d: unknown) => void);\n return () => dataCbs.delete(cb as (d: unknown) => void);\n },\n getTheme: () => currentTheme,\n onTheme(cb) {\n themeCbs.add(cb);\n return () => themeCbs.delete(cb);\n },\n async callTool<O>(name: string, args?: Record<string, unknown>): Promise<O> {\n return (await request(MCP_TOOLS_CALL, { name, arguments: args ?? {} })) as O;\n },\n sendPrompt(text: string) {\n // Standard follow-up (ack ignored); legacy mirror for a pre-standard host.\n void request(MCPAPP_MESSAGE, { role: \"user\", content: [{ type: \"text\", text }] }).catch(\n () => {},\n );\n postLegacy({ type: MCPUI_PROMPT, payload: { prompt: text } });\n },\n openLink(url: string) {\n void request(MCPAPP_OPEN_LINK, { url }).catch(() => {});\n postLegacy({ type: MCPUI_LINK, payload: { url } });\n },\n resize(height?: number) {\n reportSize(height);\n },\n capabilities(): HostCapabilities {\n // The MCP Apps standard host answers `tools/call` over this bridge, so pull\n // is advertised. A legacy-only host that shares this adapter (nimblebrain,\n // pre-P3) does not, so there callTool rejects only after REQUEST_TIMEOUT_MS\n // rather than failing fast.\n return { pull: true, sendPrompt: true, openLink: true };\n },\n start() {\n win.addEventListener(\"message\", onMessage as EventListener);\n\n // Baked-in data → available on first paint, before the handshake resolves.\n currentData = readInlineData(win.document, dataElementId);\n\n if (autoResize) setupResize();\n\n // Legacy mcp-ui ready (a standard host drops this non-JSON-RPC frame).\n post({ type: MCPUI_READY });\n\n // MCP Apps standard handshake. A legacy-only host never answers, so the\n // legacy render-data path (handleLegacy) still feeds the widget.\n request<{ hostContext?: Record<string, unknown> }>(MCPAPP_INITIALIZE, {\n appInfo: { name: options.name ?? \"synapse-ui\", version: options.version ?? \"0.0.0\" },\n appCapabilities: { availableDisplayModes: [\"inline\"] },\n protocolVersion: MCPAPP_PROTOCOL_VERSION,\n })\n .then((result) => {\n if (destroyed) return;\n standardConfirmed = true;\n applyHostContext(result?.hostContext);\n notify(MCPAPP_INITIALIZED, {});\n // A host keeps the frame hidden until it gets a size after init — force one.\n lastReportedHeight = -1;\n reportSize();\n })\n .catch(() => {\n // Not an MCP Apps host (or it was slow) — the legacy path covers data.\n });\n\n reportSize();\n },\n destroy() {\n if (destroyed) return;\n destroyed = true;\n win.removeEventListener(\"message\", onMessage as EventListener);\n if (onWindowResize) win.removeEventListener(\"resize\", onWindowResize);\n onWindowResize = null;\n resizeObserver?.disconnect();\n resizeObserver = null;\n for (const p of pending.values()) {\n clearTimeout(p.timer);\n p.reject(new Error(\"adapter destroyed\"));\n }\n pending.clear();\n dataCbs.clear();\n themeCbs.clear();\n },\n };\n}\n","import { createChatGPTAdapter } from \"./adapters/chatgpt.js\";\nimport { createInlineAdapter } from \"./adapters/inline.js\";\nimport { createMcpAppsAdapter } from \"./adapters/mcpapps.js\";\nimport type { ConnectUIOptions, HostAdapter, HostKind } from \"./types.js\";\n\n/**\n * Minimal window shape the detector inspects. Kept structural so detection is\n * unit-testable with a plain object — no full `Window` fake required.\n */\ninterface DetectableWindow {\n openai?: unknown;\n parent?: unknown;\n self?: unknown;\n}\n\n/**\n * Feature-detect the host from the browsing context.\n *\n * - `window.openai` present → **chatgpt** (OpenAI Apps SDK).\n * - otherwise, a nested browsing context (`parent !== self`, or a cross-origin\n * access that throws) → **claude** (MCP Apps standard postMessage host).\n * - top-level document → **generic** (inline / standalone).\n *\n * Returns the host *kind*; `chooseAdapter` maps it to a concrete adapter and\n * honors an explicit `options.host` override for previews/SSR/tests.\n */\nexport function detectHostKind(win: DetectableWindow): HostKind {\n if (win.openai != null) return \"chatgpt\";\n try {\n if (win.parent != null && win.parent !== win) return \"claude\";\n } catch {\n // Cross-origin parent access throws → we are framed by another origin.\n return \"claude\";\n }\n return \"generic\";\n}\n\n/** Build the adapter for an explicit host kind (`options.host` or a detected one). */\nexport function adapterForKind(\n kind: HostKind,\n win: Window & typeof globalThis,\n options: ConnectUIOptions,\n): HostAdapter {\n switch (kind) {\n case \"chatgpt\":\n return createChatGPTAdapter(win, options);\n case \"claude\":\n case \"nimblebrain\":\n // Both speak the MCP Apps standard (SEP-1865). `nimblebrain` shares it for\n // now; a dedicated adapter over the `synapse/*` extension lands in P3.\n return createMcpAppsAdapter(win, options);\n default:\n return createInlineAdapter(win, options);\n }\n}\n\n/** Select and construct the host adapter, honoring `options.host` when set. */\nexport function selectAdapter(\n win: Window & typeof globalThis,\n options: ConnectUIOptions,\n): HostAdapter {\n const kind = options.host ?? detectHostKind(win as unknown as DetectableWindow);\n return adapterForKind(kind, win, options);\n}\n","import { selectAdapter } from \"./detect.js\";\nimport { applyHostTheme } from \"./theme.js\";\nimport type { ConnectUIOptions, SynapseUIClient } from \"./types.js\";\n\n/**\n * Connect a Synapse-authored component to whatever host it renders in — ChatGPT\n * (OpenAI Apps SDK), Claude (MCP Apps standard), or a plain/standalone page — behind one\n * push-first API. Feature-detects the host, selects an adapter, and applies the\n * host theme to the DOM before returning.\n *\n * Synchronous: `data()` is populated from baked-in data (where present) on\n * return, and pushed updates arrive via `onData`. Bind the result to `synapse`:\n *\n * ```ts\n * const synapse = connectUI({ name: \"my-widget\", version: \"1.0.0\" });\n * synapse.onData(render); // future pushes/updates\n * render(synapse.data()); // current value (null → empty state)\n * ```\n */\nexport function connectUI(options: ConnectUIOptions = {}): SynapseUIClient {\n const win = options.window ?? (globalThis as unknown as Window & typeof globalThis);\n const adapter = selectAdapter(win, options);\n\n // The client owns theme application: adapters resolve mode/tokens; this puts\n // them on the DOM (data-theme + CSS vars) so apps never wire theme by hand.\n applyHostTheme(adapter.getTheme());\n const unsubTheme = adapter.onTheme(applyHostTheme);\n\n adapter.start();\n\n let destroyed = false;\n\n return {\n data: <T>() => adapter.getData<T>(),\n onData: <T>(cb: (data: T) => void) => adapter.onData<T>(cb),\n theme: () => adapter.getTheme(),\n onTheme: (cb) => adapter.onTheme(cb),\n callTool: <O>(name: string, args?: Record<string, unknown>) => adapter.callTool<O>(name, args),\n sendPrompt: (text: string) => adapter.sendPrompt(text),\n openLink: (url: string) => adapter.openLink(url),\n resize: (height?: number) => adapter.resize(height),\n capabilities: () => adapter.capabilities(),\n host: () => adapter.host,\n destroy() {\n if (destroyed) return;\n destroyed = true;\n unsubTheme();\n adapter.destroy();\n },\n };\n}\n"]}
@@ -0,0 +1,75 @@
1
+ 'use strict';
2
+
3
+ // src/theme-defaults.ts
4
+ var LIGHT = {
5
+ // ── Surfaces ──
6
+ "--color-background-primary": "#ffffff",
7
+ "--color-background-secondary": "#fafafa",
8
+ "--color-background-tertiary": "#f3f4f6",
9
+ // ── Text ──
10
+ "--color-text-primary": "#111827",
11
+ "--color-text-secondary": "#6b7280",
12
+ "--color-text-tertiary": "#9ca3af",
13
+ "--color-text-accent": "#2563eb",
14
+ "--nb-color-accent-foreground": "#ffffff",
15
+ // ── Border / ring ──
16
+ "--color-border-primary": "#e5e7eb",
17
+ "--color-border-secondary": "#d1d5db",
18
+ "--color-ring-primary": "#2563eb",
19
+ // ── Status / brand semantics ──
20
+ "--nb-color-danger": "#dc2626",
21
+ "--nb-color-success": "#059669",
22
+ "--nb-color-warning": "#f59e0b",
23
+ "--nb-color-warm": "#d4620a",
24
+ "--nb-color-warm-light": "#fef5ee",
25
+ "--nb-color-processing": "#7c3aed",
26
+ "--nb-color-processing-light": "#f3eeff",
27
+ "--nb-color-info-light": "#eef4ff"
28
+ };
29
+ var DARK = {
30
+ // ── Surfaces (base → lifted) ──
31
+ "--color-background-primary": "#18181b",
32
+ "--color-background-secondary": "#27272a",
33
+ "--color-background-tertiary": "#2f2f34",
34
+ // ── Text ──
35
+ "--color-text-primary": "#fafafa",
36
+ "--color-text-secondary": "#a1a1aa",
37
+ "--color-text-tertiary": "#71717a",
38
+ "--color-text-accent": "#818cf8",
39
+ "--nb-color-accent-foreground": "#ffffff",
40
+ // ── Border / ring (lighter than surfaces so they remain visible) ──
41
+ "--color-border-primary": "#3f3f46",
42
+ "--color-border-secondary": "#52525b",
43
+ "--color-ring-primary": "#818cf8",
44
+ // ── Status / brand semantics (brightened for contrast on dark) ──
45
+ "--nb-color-danger": "#f87171",
46
+ "--nb-color-success": "#34d399",
47
+ "--nb-color-warning": "#fbbf24",
48
+ "--nb-color-warm": "#fb923c",
49
+ "--nb-color-warm-light": "#3a2a1e",
50
+ "--nb-color-processing": "#a78bfa",
51
+ "--nb-color-processing-light": "#2a2440",
52
+ "--nb-color-info-light": "#1e2a44"
53
+ };
54
+ var DEFAULT_THEME_VARS = {
55
+ light: LIGHT,
56
+ dark: DARK
57
+ };
58
+ function applyThemeVariables(mode, hostVars) {
59
+ if (typeof document === "undefined") return;
60
+ const root = document.documentElement.style;
61
+ for (const [k, v] of Object.entries(DEFAULT_THEME_VARS[mode])) {
62
+ root.setProperty(k, v);
63
+ }
64
+ if (hostVars && typeof hostVars === "object") {
65
+ for (const [k, v] of Object.entries(hostVars)) {
66
+ if (typeof k === "string" && typeof v === "string") {
67
+ root.setProperty(k, v);
68
+ }
69
+ }
70
+ }
71
+ }
72
+
73
+ exports.applyThemeVariables = applyThemeVariables;
74
+ //# sourceMappingURL=chunk-KTXASIFJ.cjs.map
75
+ //# sourceMappingURL=chunk-KTXASIFJ.cjs.map