sunpeak 0.16.27 → 0.16.28

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (87) hide show
  1. package/bin/commands/build.mjs +0 -1
  2. package/dist/chatgpt/globals.css +10 -9
  3. package/dist/chatgpt/index.cjs +55 -24
  4. package/dist/chatgpt/index.cjs.map +1 -1
  5. package/dist/chatgpt/index.js +31 -25
  6. package/dist/chatgpt/index.js.map +1 -1
  7. package/dist/chunk-9hOWP6kD.cjs +64 -0
  8. package/dist/chunk-D6g4UhsZ.js +35 -0
  9. package/dist/claude/index.cjs +4 -4
  10. package/dist/claude/index.js +3 -5
  11. package/dist/discovery-BxKCIgG5.cjs +332 -0
  12. package/dist/discovery-BxKCIgG5.cjs.map +1 -0
  13. package/dist/discovery-Du4LHrih.js +261 -0
  14. package/dist/discovery-Du4LHrih.js.map +1 -0
  15. package/dist/host/chatgpt/index.cjs +171 -65
  16. package/dist/host/chatgpt/index.cjs.map +1 -1
  17. package/dist/host/chatgpt/index.js +170 -70
  18. package/dist/host/chatgpt/index.js.map +1 -1
  19. package/dist/host/index.cjs +47 -19
  20. package/dist/host/index.cjs.map +1 -1
  21. package/dist/host/index.js +47 -24
  22. package/dist/host/index.js.map +1 -1
  23. package/dist/index.cjs +3103 -3725
  24. package/dist/index.cjs.map +1 -1
  25. package/dist/index.js +3026 -3746
  26. package/dist/index.js.map +1 -1
  27. package/dist/lib/discovery-cli.cjs +117 -131
  28. package/dist/lib/discovery-cli.cjs.map +1 -1
  29. package/dist/lib/discovery-cli.js +107 -111
  30. package/dist/lib/discovery-cli.js.map +1 -1
  31. package/dist/mcp/index.cjs +9818 -10283
  32. package/dist/mcp/index.cjs.map +1 -1
  33. package/dist/mcp/index.js +9799 -10282
  34. package/dist/mcp/index.js.map +1 -1
  35. package/dist/protocol-DJmRaBzO.js +11080 -0
  36. package/dist/{protocol-DkDHRwOW.cjs.map → protocol-DJmRaBzO.js.map} +1 -1
  37. package/dist/protocol-jbxhzcnS.cjs +11493 -0
  38. package/dist/protocol-jbxhzcnS.cjs.map +1 -0
  39. package/dist/simulator/index.cjs +79 -36
  40. package/dist/simulator/index.cjs.map +1 -1
  41. package/dist/simulator/index.js +43 -37
  42. package/dist/simulator/index.js.map +1 -1
  43. package/dist/simulator-BYIH-xqQ.cjs +3701 -0
  44. package/dist/{simulator-Gc6n_fT4.cjs.map → simulator-BYIH-xqQ.cjs.map} +1 -1
  45. package/dist/simulator-CmgNnWBO.js +3575 -0
  46. package/dist/simulator-CmgNnWBO.js.map +1 -0
  47. package/dist/simulator-url-BDGD4vZD.cjs +69 -0
  48. package/dist/simulator-url-BDGD4vZD.cjs.map +1 -0
  49. package/dist/simulator-url-Bkxj43yT.js +64 -0
  50. package/dist/simulator-url-Bkxj43yT.js.map +1 -0
  51. package/dist/style.css +10 -9
  52. package/dist/use-app-D2h-aiyr.cjs +940 -0
  53. package/dist/use-app-D2h-aiyr.cjs.map +1 -0
  54. package/dist/use-app-X7JbGskk.js +598 -0
  55. package/dist/use-app-X7JbGskk.js.map +1 -0
  56. package/package.json +8 -8
  57. package/template/node_modules/.bin/vite +2 -2
  58. package/template/node_modules/.bin/vitest +2 -2
  59. package/template/package.json +5 -5
  60. package/dist/claude/index.cjs.map +0 -1
  61. package/dist/claude/index.js.map +0 -1
  62. package/dist/discovery-BVqD-JsT.js +0 -224
  63. package/dist/discovery-BVqD-JsT.js.map +0 -1
  64. package/dist/discovery-D1gpaVz4.cjs +0 -223
  65. package/dist/discovery-D1gpaVz4.cjs.map +0 -1
  66. package/dist/index-BEWVLFfB.cjs +0 -28
  67. package/dist/index-BEWVLFfB.cjs.map +0 -1
  68. package/dist/index-C6XYFOmh.js +0 -29
  69. package/dist/index-C6XYFOmh.js.map +0 -1
  70. package/dist/index-D0FsXP3Y.cjs +0 -40
  71. package/dist/index-D0FsXP3Y.cjs.map +0 -1
  72. package/dist/index-Rg7SWjvl.js +0 -41
  73. package/dist/index-Rg7SWjvl.js.map +0 -1
  74. package/dist/protocol-DkDHRwOW.cjs +0 -12221
  75. package/dist/protocol-uge7qFev.js +0 -12223
  76. package/dist/protocol-uge7qFev.js.map +0 -1
  77. package/dist/simulator-B-CrMHVs.js +0 -3534
  78. package/dist/simulator-B-CrMHVs.js.map +0 -1
  79. package/dist/simulator-Gc6n_fT4.cjs +0 -3549
  80. package/dist/simulator-url-DcSYRl-P.cjs +0 -53
  81. package/dist/simulator-url-DcSYRl-P.cjs.map +0 -1
  82. package/dist/simulator-url-j_XV3EoP.js +0 -54
  83. package/dist/simulator-url-j_XV3EoP.js.map +0 -1
  84. package/dist/use-app-C9gpzIQO.js +0 -349
  85. package/dist/use-app-C9gpzIQO.js.map +0 -1
  86. package/dist/use-app-D09O2swh.cjs +0 -348
  87. package/dist/use-app-D09O2swh.cjs.map +0 -1
@@ -0,0 +1,3575 @@
1
+ import { $ as literal, C as ListPromptsResultSchema, D as ListResourcesResultSchema, E as ListResourcesRequestSchema, F as ReadResourceRequestSchema, H as ToolListChangedNotificationSchema, I as ReadResourceResultSchema, L as RequestIdSchema, N as PingRequestSchema, P as PromptListChangedNotificationSchema, Q as boolean, R as ResourceLinkSchema, S as ListPromptsRequestSchema, T as ListResourceTemplatesResultSchema, U as ToolSchema, X as _undefined, Z as array, _ as ImplementationSchema, a as CallToolResultSchema, at as unknown, b as JSONRPCMessageSchema, et as number, i as CallToolRequestSchema, it as union, j as LoggingMessageNotificationSchema, nt as record, p as EmbeddedResourceSchema, rt as string, s as ContentBlockSchema, t as Protocol, tt as object, w as ListResourceTemplatesRequestSchema, z as ResourceListChangedNotificationSchema } from "./protocol-DJmRaBzO.js";
2
+ import * as React from "react";
3
+ import { useCallback, useEffect, useMemo, useRef, useState } from "react";
4
+ import { jsx, jsxs } from "react/jsx-runtime";
5
+ //#region src/lib/default-style-variables.ts
6
+ var DEFAULT_STYLE_VARIABLES = {
7
+ "--color-background-primary": "light-dark(#ffffff, #1a1a1a)",
8
+ "--color-background-secondary": "light-dark(#f5f5f5, #2d2d2d)",
9
+ "--color-background-tertiary": "light-dark(#e5e5e5, #404040)",
10
+ "--color-background-inverse": "light-dark(#1a1a1a, #ffffff)",
11
+ "--color-background-ghost": "light-dark(rgba(255,255,255,0), rgba(26,26,26,0))",
12
+ "--color-background-info": "light-dark(#eff6ff, #1e3a5f)",
13
+ "--color-background-danger": "light-dark(#fef2f2, #7f1d1d)",
14
+ "--color-background-success": "light-dark(#f0fdf4, #14532d)",
15
+ "--color-background-warning": "light-dark(#fefce8, #713f12)",
16
+ "--color-background-disabled": "light-dark(rgba(255,255,255,0.5), rgba(26,26,26,0.5))",
17
+ "--color-text-primary": "light-dark(#1f2937, #f3f4f6)",
18
+ "--color-text-secondary": "light-dark(#6b7280, #9ca3af)",
19
+ "--color-text-tertiary": "light-dark(#9ca3af, #6b7280)",
20
+ "--color-text-inverse": "light-dark(#f3f4f6, #1f2937)",
21
+ "--color-text-ghost": "light-dark(rgba(107,114,128,0.5), rgba(156,163,175,0.5))",
22
+ "--color-text-info": "light-dark(#1d4ed8, #60a5fa)",
23
+ "--color-text-danger": "light-dark(#b91c1c, #f87171)",
24
+ "--color-text-success": "light-dark(#15803d, #4ade80)",
25
+ "--color-text-warning": "light-dark(#a16207, #fbbf24)",
26
+ "--color-text-disabled": "light-dark(rgba(31,41,55,0.5), rgba(243,244,246,0.5))",
27
+ "--color-border-primary": "light-dark(#e5e7eb, #404040)",
28
+ "--color-border-secondary": "light-dark(#d1d5db, #525252)",
29
+ "--color-border-tertiary": "light-dark(#f3f4f6, #374151)",
30
+ "--color-border-inverse": "light-dark(rgba(255,255,255,0.3), rgba(0,0,0,0.3))",
31
+ "--color-border-ghost": "light-dark(rgba(229,231,235,0), rgba(64,64,64,0))",
32
+ "--color-border-info": "light-dark(#93c5fd, #1e40af)",
33
+ "--color-border-danger": "light-dark(#fca5a5, #991b1b)",
34
+ "--color-border-success": "light-dark(#86efac, #166534)",
35
+ "--color-border-warning": "light-dark(#fde047, #854d0e)",
36
+ "--color-border-disabled": "light-dark(rgba(229,231,235,0.5), rgba(64,64,64,0.5))",
37
+ "--color-ring-primary": "light-dark(#3b82f6, #60a5fa)",
38
+ "--color-ring-secondary": "light-dark(#6b7280, #9ca3af)",
39
+ "--color-ring-inverse": "light-dark(#ffffff, #1f2937)",
40
+ "--color-ring-info": "light-dark(#2563eb, #3b82f6)",
41
+ "--color-ring-danger": "light-dark(#dc2626, #ef4444)",
42
+ "--color-ring-success": "light-dark(#16a34a, #22c55e)",
43
+ "--color-ring-warning": "light-dark(#ca8a04, #eab308)",
44
+ "--font-sans": "system-ui, -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif",
45
+ "--font-mono": "ui-monospace, 'SF Mono', Monaco, 'Cascadia Code', monospace",
46
+ "--font-weight-normal": "400",
47
+ "--font-weight-medium": "500",
48
+ "--font-weight-semibold": "600",
49
+ "--font-weight-bold": "700",
50
+ "--font-text-xs-size": "0.75rem",
51
+ "--font-text-sm-size": "0.875rem",
52
+ "--font-text-md-size": "1rem",
53
+ "--font-text-lg-size": "1.125rem",
54
+ "--font-heading-xs-size": "0.75rem",
55
+ "--font-heading-sm-size": "0.875rem",
56
+ "--font-heading-md-size": "1rem",
57
+ "--font-heading-lg-size": "1.25rem",
58
+ "--font-heading-xl-size": "1.5rem",
59
+ "--font-heading-2xl-size": "1.875rem",
60
+ "--font-heading-3xl-size": "2.25rem",
61
+ "--font-text-xs-line-height": "1.4",
62
+ "--font-text-sm-line-height": "1.4",
63
+ "--font-text-md-line-height": "1.5",
64
+ "--font-text-lg-line-height": "1.5",
65
+ "--font-heading-xs-line-height": "1.4",
66
+ "--font-heading-sm-line-height": "1.4",
67
+ "--font-heading-md-line-height": "1.4",
68
+ "--font-heading-lg-line-height": "1.3",
69
+ "--font-heading-xl-line-height": "1.25",
70
+ "--font-heading-2xl-line-height": "1.2",
71
+ "--font-heading-3xl-line-height": "1.1",
72
+ "--border-radius-xs": "2px",
73
+ "--border-radius-sm": "4px",
74
+ "--border-radius-md": "6px",
75
+ "--border-radius-lg": "8px",
76
+ "--border-radius-xl": "12px",
77
+ "--border-radius-full": "9999px",
78
+ "--border-width-regular": "1px",
79
+ "--shadow-hairline": "0 1px 2px 0 rgba(0, 0, 0, 0.05)",
80
+ "--shadow-sm": "0 1px 3px 0 rgba(0, 0, 0, 0.1), 0 1px 2px -1px rgba(0, 0, 0, 0.1)",
81
+ "--shadow-md": "0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -2px rgba(0, 0, 0, 0.1)",
82
+ "--shadow-lg": "0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -4px rgba(0, 0, 0, 0.1)"
83
+ };
84
+ //#endregion
85
+ //#region src/simulator/hosts.ts
86
+ var registry = /* @__PURE__ */ new Map();
87
+ /** Register a host shell. Idempotent — re-registering with the same id replaces. */
88
+ function registerHostShell(shell) {
89
+ registry.set(shell.id, shell);
90
+ }
91
+ /** Get a registered host shell by id. */
92
+ function getHostShell(id) {
93
+ return registry.get(id);
94
+ }
95
+ /** Get all registered host shells, in insertion order. */
96
+ function getRegisteredHosts() {
97
+ return Array.from(registry.values());
98
+ }
99
+ //#endregion
100
+ //#region src/simulator/simulator-types.ts
101
+ var SCREEN_WIDTHS = {
102
+ "mobile-s": 375,
103
+ "mobile-l": 425,
104
+ tablet: 768,
105
+ full: 1024
106
+ };
107
+ //#endregion
108
+ //#region src/chatgpt/chatgpt-conversation.tsx
109
+ function CloseIcon$1({ className }) {
110
+ return /* @__PURE__ */ jsx("svg", {
111
+ width: "1em",
112
+ height: "1em",
113
+ viewBox: "0 0 24 24",
114
+ fill: "currentColor",
115
+ className,
116
+ children: /* @__PURE__ */ jsx("path", {
117
+ fillRule: "evenodd",
118
+ clipRule: "evenodd",
119
+ d: "M5.83071 5.83077C6.33839 5.32309 7.16151 5.32309 7.66919 5.83077L12 10.1615L16.3307 5.83077C16.8384 5.32309 17.6615 5.32309 18.1692 5.83077C18.6769 6.33845 18.6769 7.16157 18.1692 7.66925L13.8384 12L18.1692 16.3308C18.6769 16.8385 18.6769 17.6616 18.1692 18.1693C17.6615 18.6769 16.8384 18.6769 16.3307 18.1693L12 13.8385L7.66919 18.1693C7.16151 18.6769 6.33839 18.6769 5.83071 18.1693C5.32303 17.6616 5.32303 16.8385 5.83071 16.3308L10.1615 12L5.83071 7.66925C5.32303 7.16157 5.32303 6.33845 5.83071 5.83077Z"
120
+ })
121
+ });
122
+ }
123
+ /**
124
+ * Conversation layout that renders children (iframe) at a stable tree position.
125
+ *
126
+ * All three display modes (inline, pip, fullscreen) share the same React tree
127
+ * shape so that the iframe never unmounts when switching modes, avoiding a
128
+ * white-flash reload.
129
+ *
130
+ * Visual differences are achieved purely with CSS:
131
+ * - **inline**: content in normal document flow
132
+ * - **pip**: content wrapper becomes `position: fixed` floating overlay
133
+ * - **fullscreen**: content wrapper becomes `position: fixed` covering the viewport;
134
+ * fullscreen chrome (header/footer) rendered as a separate fixed overlay
135
+ */
136
+ function Conversation({ children, screenWidth, displayMode, platform, onRequestDisplayMode, appName = "Sunpeak", appIcon, userMessage = "What have you got for me today?", headerAction, onContentWidthChange }) {
137
+ const isDesktop = platform === "desktop";
138
+ const containerWidth = screenWidth === "full" ? "100%" : `${SCREEN_WIDTHS[screenWidth]}px`;
139
+ const isFullscreen = displayMode === "fullscreen";
140
+ const isPip = displayMode === "pip";
141
+ const contentRef = useRef(null);
142
+ const onContentWidthChangeRef = useRef(onContentWidthChange);
143
+ useEffect(() => {
144
+ onContentWidthChangeRef.current = onContentWidthChange;
145
+ });
146
+ const setContentRef = useCallback((node) => {
147
+ contentRef.current = node;
148
+ }, []);
149
+ useEffect(() => {
150
+ const el = contentRef.current;
151
+ if (!el) return;
152
+ const observer = new ResizeObserver((entries) => {
153
+ for (const entry of entries) {
154
+ const width = Math.round(entry.contentBoxSize[0]?.inlineSize ?? entry.contentRect.width);
155
+ if (width > 0) onContentWidthChangeRef.current?.(width);
156
+ }
157
+ });
158
+ observer.observe(el);
159
+ return () => observer.disconnect();
160
+ }, []);
161
+ const handleClose = () => onRequestDisplayMode?.("inline");
162
+ return /* @__PURE__ */ jsxs("div", {
163
+ className: "flex flex-col w-full h-full flex-1 items-center relative",
164
+ style: {
165
+ transform: "translate(0)",
166
+ backgroundColor: "var(--sim-bg-conversation, var(--color-background-primary))",
167
+ color: "var(--color-text-primary)"
168
+ },
169
+ children: [
170
+ isFullscreen && /* @__PURE__ */ jsxs("div", {
171
+ className: "fixed start-0 end-0 top-0 bottom-0 z-[51] mx-auto flex flex-col pointer-events-none",
172
+ style: { maxWidth: containerWidth },
173
+ children: [
174
+ /* @__PURE__ */ jsxs("div", {
175
+ className: "z-10 grid h-[3.25rem] grid-cols-[1fr_auto_1fr] border-b px-2 pointer-events-auto",
176
+ style: {
177
+ borderColor: "var(--color-border-primary)",
178
+ backgroundColor: "var(--sim-bg-conversation, var(--color-background-primary))"
179
+ },
180
+ children: [
181
+ /* @__PURE__ */ jsx("div", {
182
+ className: "flex items-center justify-start gap-3",
183
+ children: /* @__PURE__ */ jsx("button", {
184
+ onClick: handleClose,
185
+ "aria-label": "Close",
186
+ className: "h-7 w-7 flex items-center justify-center rounded-md transition-colors hover:opacity-70",
187
+ type: "button",
188
+ children: /* @__PURE__ */ jsx(CloseIcon$1, {})
189
+ })
190
+ }),
191
+ isDesktop && /* @__PURE__ */ jsx("div", {
192
+ className: "flex items-center justify-center text-base",
193
+ children: appName
194
+ }),
195
+ isDesktop && /* @__PURE__ */ jsx("div", {})
196
+ ]
197
+ }),
198
+ /* @__PURE__ */ jsx("div", { className: "flex-1" }),
199
+ /* @__PURE__ */ jsxs("footer", {
200
+ className: "relative",
201
+ children: [/* @__PURE__ */ jsx("div", {
202
+ className: "absolute inset-x-0 bottom-0 h-full -z-10",
203
+ style: {
204
+ maskImage: "linear-gradient(to bottom, transparent 0%, black 50%)",
205
+ WebkitMaskImage: "linear-gradient(to bottom, transparent 0%, black 50%)",
206
+ backdropFilter: "blur(16px)",
207
+ WebkitBackdropFilter: "blur(16px)"
208
+ }
209
+ }), /* @__PURE__ */ jsx("div", {
210
+ className: "max-w-[40rem] min-[1440px]:max-w-[48rem] mx-auto px-4 pt-4 pb-4 pointer-events-auto",
211
+ children: /* @__PURE__ */ jsx("div", {
212
+ className: "relative",
213
+ children: /* @__PURE__ */ jsx("input", {
214
+ type: "text",
215
+ name: "userInput",
216
+ disabled: true,
217
+ placeholder: "Message sunpeak.ai",
218
+ className: "w-full rounded-3xl px-5 py-3 pr-12 shadow-sm",
219
+ style: {
220
+ backgroundColor: "var(--sim-bg-reply-input, var(--color-background-secondary))",
221
+ color: "var(--color-text-primary)",
222
+ border: "1px solid var(--color-border-tertiary)"
223
+ }
224
+ })
225
+ })
226
+ })]
227
+ })
228
+ ]
229
+ }),
230
+ !isFullscreen && /* @__PURE__ */ jsxs("header", {
231
+ className: "h-12 flex items-center gap-3 px-4 text-lg sticky top-0 z-40 w-full",
232
+ style: {
233
+ maxWidth: containerWidth,
234
+ backgroundColor: "var(--sim-bg-conversation, var(--color-background-primary))"
235
+ },
236
+ children: [/* @__PURE__ */ jsx("span", { children: "sunpeak.ai" }), headerAction]
237
+ }),
238
+ /* @__PURE__ */ jsx("div", {
239
+ className: "flex flex-col flex-1 w-full transition-all duration-200 overflow-hidden",
240
+ style: { maxWidth: containerWidth },
241
+ children: /* @__PURE__ */ jsxs("main", {
242
+ className: "flex-1 overflow-y-auto overflow-x-hidden flex flex-col",
243
+ children: [
244
+ !isFullscreen && /* @__PURE__ */ jsxs("article", {
245
+ className: "w-full focus:outline-none",
246
+ dir: "auto",
247
+ "data-turn": "user",
248
+ children: [/* @__PURE__ */ jsx("h5", {
249
+ className: "sr-only",
250
+ children: "You said:"
251
+ }), /* @__PURE__ */ jsx("div", {
252
+ className: "text-base my-auto mx-auto md:pt-8 px-4",
253
+ children: /* @__PURE__ */ jsx("div", {
254
+ className: "max-w-[40rem] min-[1440px]:max-w-[48rem] mx-auto flex-1 relative flex w-full min-w-0 flex-col",
255
+ children: /* @__PURE__ */ jsx("div", {
256
+ className: "flex max-w-full flex-col grow",
257
+ children: /* @__PURE__ */ jsx("div", {
258
+ "data-message-author-role": "user",
259
+ className: "min-h-8 relative flex w-full flex-col items-end gap-2 text-start break-words whitespace-normal",
260
+ children: /* @__PURE__ */ jsx("div", {
261
+ className: "flex w-full flex-col gap-1 empty:hidden items-end",
262
+ children: /* @__PURE__ */ jsx("div", {
263
+ className: "relative rounded-[18px] px-4 py-3 max-w-[70%]",
264
+ style: { backgroundColor: "var(--sim-bg-user-bubble, var(--color-background-tertiary))" },
265
+ children: /* @__PURE__ */ jsx("div", {
266
+ className: "whitespace-pre-wrap",
267
+ children: userMessage
268
+ })
269
+ })
270
+ })
271
+ })
272
+ })
273
+ })
274
+ })]
275
+ }),
276
+ /* @__PURE__ */ jsxs("article", {
277
+ className: "w-full focus:outline-none flex-1",
278
+ dir: "auto",
279
+ "data-turn": "assistant",
280
+ children: [/* @__PURE__ */ jsxs("h6", {
281
+ className: "sr-only",
282
+ children: [appName, " said:"]
283
+ }), /* @__PURE__ */ jsx("div", {
284
+ className: "text-base my-auto mx-auto pb-10 px-4",
285
+ children: /* @__PURE__ */ jsx("div", {
286
+ className: "max-w-[40rem] min-[1440px]:max-w-[48rem] mx-auto flex-1 relative flex w-full min-w-0 flex-col",
287
+ children: /* @__PURE__ */ jsxs("div", {
288
+ className: "flex max-w-full flex-col grow",
289
+ children: [!isFullscreen && /* @__PURE__ */ jsxs("div", {
290
+ className: "flex items-center gap-2 my-3",
291
+ children: [appIcon ? appIcon.startsWith("data:") || appIcon.startsWith("http") ? /* @__PURE__ */ jsx("img", {
292
+ src: appIcon,
293
+ alt: "",
294
+ className: "size-6 rounded-full object-cover"
295
+ }) : /* @__PURE__ */ jsx("div", {
296
+ className: "size-6 flex items-center justify-center text-base",
297
+ children: appIcon
298
+ }) : /* @__PURE__ */ jsx("div", {
299
+ className: "size-6 rounded-full flex items-center justify-center font-medium text-xs text-white",
300
+ style: { backgroundColor: "#10a37f" },
301
+ children: "AI"
302
+ }), /* @__PURE__ */ jsx("span", {
303
+ className: "font-semibold text-sm",
304
+ children: appName
305
+ })]
306
+ }), /* @__PURE__ */ jsx("div", {
307
+ "data-message-author-role": "assistant",
308
+ className: "min-h-8 relative flex w-full flex-col items-start gap-2 text-start break-words whitespace-normal",
309
+ children: /* @__PURE__ */ jsx("div", {
310
+ className: "flex w-full flex-col gap-1 empty:hidden",
311
+ children: /* @__PURE__ */ jsxs("div", {
312
+ ref: setContentRef,
313
+ className: isPip ? "no-scrollbar @w-xl/main:top-4 fixed start-4 end-4 top-12 z-50 mx-auto max-w-[40rem] lg:max-w-[48rem] sm:start-0 sm:end-0 sm:top-[3.25rem] sm:w-full overflow-visible" : isFullscreen ? "no-scrollbar fixed inset-x-0 top-[3.25rem] bottom-0 z-50 mx-auto" : "no-scrollbar relative mb-2 @w-sm/main:w-full mx-0 max-sm:-mx-[1rem] max-sm:w-[100cqw] max-sm:overflow-hidden overflow-visible",
314
+ style: {
315
+ ...isPip ? { maxHeight: "480px" } : {},
316
+ ...isFullscreen ? { maxWidth: containerWidth } : {}
317
+ },
318
+ children: [isPip && /* @__PURE__ */ jsx("button", {
319
+ onClick: handleClose,
320
+ className: "absolute -start-2 -top-1.5 z-10 rounded-full bg-[#3a3a3a] p-1.5 text-white shadow-[0px_0px_0px_1px_#fff3,0px_4px_12px_rgba(0,0,0,0.12)] hover:bg-[#6a6a6a]",
321
+ "aria-label": "Close picture-in-picture",
322
+ type: "button",
323
+ children: /* @__PURE__ */ jsx(CloseIcon$1, { className: "h-4 w-4" })
324
+ }, "pip-close"), /* @__PURE__ */ jsx("div", {
325
+ className: isPip ? "relative overflow-hidden h-full rounded-2xl sm:rounded-3xl shadow-[0px_0px_0px_1px_#fff3,0px_6px_20px_rgba(0,0,0,0.1)] md:-mx-4" : "relative overflow-hidden h-full",
326
+ children: /* @__PURE__ */ jsx("div", {
327
+ className: "h-full w-full max-w-full",
328
+ style: { ...isPip ? {
329
+ overflow: "auto",
330
+ backgroundColor: "var(--color-background-primary)"
331
+ } : isFullscreen ? {
332
+ overflow: "auto",
333
+ backgroundColor: "var(--color-background-primary)"
334
+ } : { backgroundColor: "transparent" } },
335
+ children
336
+ })
337
+ }, "content")]
338
+ })
339
+ })
340
+ })]
341
+ })
342
+ })
343
+ })]
344
+ }),
345
+ !isFullscreen && /* @__PURE__ */ jsxs("div", {
346
+ className: "sticky bottom-0 z-10 pointer-events-none",
347
+ children: [/* @__PURE__ */ jsx("div", {
348
+ className: "absolute inset-x-0 bottom-0 h-full -z-10",
349
+ style: {
350
+ maskImage: "linear-gradient(to bottom, transparent 0%, black 50%)",
351
+ WebkitMaskImage: "linear-gradient(to bottom, transparent 0%, black 50%)",
352
+ backdropFilter: "blur(16px)",
353
+ WebkitBackdropFilter: "blur(16px)"
354
+ }
355
+ }), /* @__PURE__ */ jsx("div", {
356
+ className: "max-w-[40rem] min-[1440px]:max-w-[48rem] mx-auto px-4 pt-4 pb-4 pointer-events-auto",
357
+ children: /* @__PURE__ */ jsx("div", {
358
+ className: "relative",
359
+ children: /* @__PURE__ */ jsx("input", {
360
+ type: "text",
361
+ name: "userInput",
362
+ disabled: true,
363
+ placeholder: "Message sunpeak.ai",
364
+ className: "w-full rounded-3xl px-5 py-3 pr-12 shadow-sm",
365
+ style: {
366
+ backgroundColor: "var(--sim-bg-reply-input, var(--color-background-secondary))",
367
+ color: "var(--color-text-primary)",
368
+ border: "1px solid var(--color-border-tertiary)"
369
+ }
370
+ })
371
+ })
372
+ })]
373
+ })
374
+ ]
375
+ })
376
+ })
377
+ ]
378
+ });
379
+ }
380
+ //#endregion
381
+ //#region src/chatgpt/chatgpt-host.ts
382
+ /**
383
+ * ChatGPT host version info — matches what ChatGPT reports via the MCP protocol.
384
+ * Verified against production ChatGPT on 2026-03-19.
385
+ */
386
+ var CHATGPT_HOST_INFO = {
387
+ name: "chatgpt",
388
+ version: "0.0.1"
389
+ };
390
+ var CHATGPT_HOST_CAPABILITIES = {
391
+ openLinks: {},
392
+ serverTools: {},
393
+ serverResources: {},
394
+ logging: {},
395
+ updateModelContext: {},
396
+ message: {},
397
+ sandbox: { permissions: { microphone: {} } }
398
+ };
399
+ /**
400
+ * Apply ChatGPT-style theming to the document.
401
+ * Sets data-theme attribute and color-scheme for light-dark() CSS support.
402
+ */
403
+ function applyChatGPTTheme(theme) {
404
+ document.documentElement.setAttribute("data-theme", theme);
405
+ document.documentElement.style.colorScheme = theme;
406
+ }
407
+ registerHostShell({
408
+ id: "chatgpt",
409
+ label: "ChatGPT",
410
+ Conversation,
411
+ applyTheme: applyChatGPTTheme,
412
+ hostInfo: CHATGPT_HOST_INFO,
413
+ hostCapabilities: CHATGPT_HOST_CAPABILITIES,
414
+ userAgent: "chatgpt",
415
+ styleVariables: { ...DEFAULT_STYLE_VARIABLES },
416
+ pageStyles: {
417
+ "--sim-bg-sidebar": "light-dark(#ffffff, #212121)",
418
+ "--sim-bg-conversation": "light-dark(#ffffff, #212121)",
419
+ "--sim-bg-user-bubble": "light-dark(rgba(233,233,233,0.5), rgba(50,50,50,0.85))",
420
+ "--sim-bg-reply-input": "light-dark(#ffffff, #212121)"
421
+ }
422
+ });
423
+ //#endregion
424
+ //#region src/claude/claude-conversation.tsx
425
+ function CloseIcon() {
426
+ return /* @__PURE__ */ jsx("svg", {
427
+ width: "16",
428
+ height: "16",
429
+ viewBox: "0 0 16 16",
430
+ fill: "none",
431
+ xmlns: "http://www.w3.org/2000/svg",
432
+ children: /* @__PURE__ */ jsx("path", {
433
+ d: "M12 4L4 12M4 4L12 12",
434
+ stroke: "currentColor",
435
+ strokeWidth: "1.5",
436
+ strokeLinecap: "round"
437
+ })
438
+ });
439
+ }
440
+ function BackIcon() {
441
+ return /* @__PURE__ */ jsx("svg", {
442
+ width: "16",
443
+ height: "16",
444
+ viewBox: "0 0 16 16",
445
+ fill: "none",
446
+ xmlns: "http://www.w3.org/2000/svg",
447
+ children: /* @__PURE__ */ jsx("path", {
448
+ d: "M10 3L5 8L10 13",
449
+ stroke: "currentColor",
450
+ strokeWidth: "1.5",
451
+ strokeLinecap: "round",
452
+ strokeLinejoin: "round"
453
+ })
454
+ });
455
+ }
456
+ /**
457
+ * Claude conversation shell — mimics Claude's chat UI chrome.
458
+ *
459
+ * All three display modes (inline, pip, fullscreen) share the same React tree
460
+ * shape so that the iframe never unmounts when switching modes.
461
+ */
462
+ function ClaudeConversation({ children, screenWidth, displayMode, platform, onRequestDisplayMode, appName = "Sunpeak", appIcon, userMessage = "What have you got for me today?", headerAction, onContentWidthChange }) {
463
+ const isDesktop = platform === "desktop";
464
+ const containerWidth = screenWidth === "full" ? "100%" : `${SCREEN_WIDTHS[screenWidth]}px`;
465
+ const isFullscreen = displayMode === "fullscreen";
466
+ const isPip = displayMode === "pip";
467
+ const contentRef = useRef(null);
468
+ const onContentWidthChangeRef = useRef(onContentWidthChange);
469
+ useEffect(() => {
470
+ onContentWidthChangeRef.current = onContentWidthChange;
471
+ });
472
+ const setContentRef = useCallback((node) => {
473
+ contentRef.current = node;
474
+ }, []);
475
+ useEffect(() => {
476
+ const el = contentRef.current;
477
+ if (!el) return;
478
+ const observer = new ResizeObserver((entries) => {
479
+ for (const entry of entries) {
480
+ const width = Math.round(entry.contentBoxSize[0]?.inlineSize ?? entry.contentRect.width);
481
+ if (width > 0) onContentWidthChangeRef.current?.(width);
482
+ }
483
+ });
484
+ observer.observe(el);
485
+ return () => observer.disconnect();
486
+ }, []);
487
+ const handleClose = () => onRequestDisplayMode?.("inline");
488
+ return /* @__PURE__ */ jsxs("div", {
489
+ className: "flex flex-col w-full h-full flex-1 items-center relative",
490
+ style: {
491
+ transform: "translate(0)",
492
+ backgroundColor: "var(--sim-bg-conversation, var(--color-background-primary))",
493
+ color: "var(--color-text-primary)"
494
+ },
495
+ children: [
496
+ isFullscreen && /* @__PURE__ */ jsxs("div", {
497
+ className: "fixed start-0 end-0 top-0 bottom-0 z-[51] mx-auto flex flex-col pointer-events-none",
498
+ style: { maxWidth: containerWidth },
499
+ children: [
500
+ /* @__PURE__ */ jsxs("div", {
501
+ className: "z-10 flex items-center h-12 border-b px-3 pointer-events-auto",
502
+ style: {
503
+ borderColor: "var(--color-border-primary)",
504
+ backgroundColor: "var(--sim-bg-conversation, var(--color-background-primary))"
505
+ },
506
+ children: [
507
+ /* @__PURE__ */ jsx("button", {
508
+ onClick: handleClose,
509
+ "aria-label": "Back",
510
+ className: "h-8 w-8 flex items-center justify-center rounded-lg transition-colors hover:opacity-70",
511
+ type: "button",
512
+ children: /* @__PURE__ */ jsx(BackIcon, {})
513
+ }),
514
+ /* @__PURE__ */ jsx("div", {
515
+ className: "flex-1 text-center text-sm font-medium",
516
+ children: appName
517
+ }),
518
+ isDesktop && /* @__PURE__ */ jsx("div", { className: "w-8" })
519
+ ]
520
+ }),
521
+ /* @__PURE__ */ jsx("div", { className: "flex-1" }),
522
+ /* @__PURE__ */ jsx("footer", {
523
+ className: "pointer-events-auto p-3",
524
+ style: { backgroundColor: "var(--sim-bg-conversation, var(--color-background-primary))" },
525
+ children: /* @__PURE__ */ jsx("div", {
526
+ className: "max-w-[48rem] mx-auto",
527
+ children: /* @__PURE__ */ jsx("input", {
528
+ type: "text",
529
+ name: "userInput",
530
+ disabled: true,
531
+ placeholder: "Reply to sunpeak...",
532
+ className: "w-full rounded-xl px-4 py-2.5 text-sm",
533
+ style: {
534
+ backgroundColor: "var(--sim-bg-reply-input, var(--color-background-secondary))",
535
+ border: "1px solid var(--color-border-primary)",
536
+ color: "var(--color-text-primary)"
537
+ }
538
+ })
539
+ })
540
+ })
541
+ ]
542
+ }),
543
+ !isFullscreen && /* @__PURE__ */ jsxs("header", {
544
+ className: "h-12 flex items-center gap-3 px-4 text-sm font-medium sticky top-0 z-40 w-full",
545
+ style: {
546
+ maxWidth: containerWidth,
547
+ backgroundColor: "var(--sim-bg-conversation, var(--color-background-primary))"
548
+ },
549
+ children: [/* @__PURE__ */ jsx("span", { children: "sunpeak.ai" }), headerAction]
550
+ }),
551
+ /* @__PURE__ */ jsxs("div", {
552
+ className: "flex flex-col flex-1 w-full transition-all duration-200 overflow-hidden",
553
+ style: { maxWidth: containerWidth },
554
+ children: [/* @__PURE__ */ jsxs("main", {
555
+ className: "flex-1 overflow-y-auto overflow-x-hidden",
556
+ children: [!isFullscreen && /* @__PURE__ */ jsx("article", {
557
+ className: "w-full",
558
+ dir: "auto",
559
+ "data-turn": "user",
560
+ children: /* @__PURE__ */ jsx("div", {
561
+ className: "px-4 py-4",
562
+ children: /* @__PURE__ */ jsx("div", {
563
+ className: "max-w-[48rem] mx-auto flex justify-end",
564
+ children: /* @__PURE__ */ jsx("div", {
565
+ className: "inline-block rounded-2xl px-4 py-2.5 text-sm max-w-[85%]",
566
+ style: { backgroundColor: "var(--sim-bg-user-bubble, var(--color-background-tertiary))" },
567
+ children: userMessage
568
+ })
569
+ })
570
+ })
571
+ }), /* @__PURE__ */ jsxs("article", {
572
+ className: "w-full",
573
+ dir: "auto",
574
+ "data-turn": "assistant",
575
+ children: [/* @__PURE__ */ jsxs("h6", {
576
+ className: "sr-only",
577
+ children: [appName, " said:"]
578
+ }), /* @__PURE__ */ jsx("div", {
579
+ className: "px-4 py-2",
580
+ children: /* @__PURE__ */ jsxs("div", {
581
+ className: "max-w-[48rem] mx-auto",
582
+ children: [!isFullscreen && /* @__PURE__ */ jsxs("div", {
583
+ className: "flex items-center gap-2 mb-3",
584
+ children: [appIcon ? appIcon.startsWith("data:") || appIcon.startsWith("http") ? /* @__PURE__ */ jsx("img", {
585
+ src: appIcon,
586
+ alt: "",
587
+ className: "size-6 rounded-full object-cover"
588
+ }) : /* @__PURE__ */ jsx("div", {
589
+ className: "size-6 flex items-center justify-center text-base",
590
+ children: appIcon
591
+ }) : /* @__PURE__ */ jsx("div", {
592
+ className: "size-6 rounded-full flex items-center justify-center text-xs font-medium text-white",
593
+ style: { backgroundColor: "#c55a30" },
594
+ children: "C"
595
+ }), /* @__PURE__ */ jsx("span", {
596
+ className: "text-sm font-medium",
597
+ children: appName
598
+ })]
599
+ }), /* @__PURE__ */ jsxs("div", {
600
+ ref: setContentRef,
601
+ className: isPip ? "fixed start-4 end-4 top-12 z-50 mx-auto max-w-[40rem] lg:max-w-[48rem] sm:start-0 sm:end-0 sm:top-[3rem] sm:w-full overflow-visible" : isFullscreen ? "fixed inset-x-0 top-[3rem] bottom-0 z-50 mx-auto" : "relative mb-2 w-full overflow-visible",
602
+ style: {
603
+ ...isPip ? { maxHeight: "480px" } : {},
604
+ ...isFullscreen ? { maxWidth: containerWidth } : {}
605
+ },
606
+ children: [isPip && /* @__PURE__ */ jsx("button", {
607
+ onClick: handleClose,
608
+ className: "absolute -start-2 -top-1.5 z-10 rounded-full p-1.5 text-white shadow-md",
609
+ style: { backgroundColor: "#4a4a4a" },
610
+ "aria-label": "Close picture-in-picture",
611
+ type: "button",
612
+ children: /* @__PURE__ */ jsx(CloseIcon, {})
613
+ }, "pip-close"), /* @__PURE__ */ jsx("div", {
614
+ className: isPip ? "relative overflow-hidden h-full rounded-2xl shadow-lg" : "relative overflow-hidden h-full",
615
+ children: /* @__PURE__ */ jsx("div", {
616
+ className: "h-full w-full max-w-full",
617
+ style: { ...isPip ? {
618
+ overflow: "auto",
619
+ backgroundColor: "var(--color-background-secondary)"
620
+ } : isFullscreen ? {
621
+ overflow: "auto",
622
+ backgroundColor: "var(--color-background-primary)"
623
+ } : { backgroundColor: "transparent" } },
624
+ children
625
+ })
626
+ }, "content")]
627
+ })]
628
+ })
629
+ })]
630
+ })]
631
+ }), !isFullscreen && /* @__PURE__ */ jsx("footer", {
632
+ style: { backgroundColor: "var(--sim-bg-conversation, var(--color-background-primary))" },
633
+ children: /* @__PURE__ */ jsx("div", {
634
+ className: "max-w-[48rem] mx-auto px-4 py-4",
635
+ children: /* @__PURE__ */ jsx("div", {
636
+ className: "relative",
637
+ children: /* @__PURE__ */ jsx("input", {
638
+ type: "text",
639
+ name: "userInput",
640
+ disabled: true,
641
+ placeholder: "Reply to sunpeak...",
642
+ className: "w-full rounded-xl px-4 py-2.5 text-sm",
643
+ style: {
644
+ backgroundColor: "var(--sim-bg-reply-input, var(--color-background-secondary))",
645
+ border: "1px solid var(--color-border-primary)"
646
+ }
647
+ })
648
+ })
649
+ })
650
+ })]
651
+ })
652
+ ]
653
+ });
654
+ }
655
+ //#endregion
656
+ //#region src/claude/claude-host.ts
657
+ var CLAUDE_HOST_INFO = {
658
+ name: "Claude",
659
+ version: "1.0.0"
660
+ };
661
+ var CLAUDE_HOST_CAPABILITIES = {
662
+ openLinks: {},
663
+ serverTools: {},
664
+ serverResources: {},
665
+ downloadFile: {},
666
+ logging: {},
667
+ updateModelContext: { text: {} },
668
+ message: { text: {} },
669
+ sandbox: {}
670
+ };
671
+ /**
672
+ * Apply Claude-style theming to the document.
673
+ * Sets data-theme attribute and color-scheme so CSS light-dark() resolves correctly.
674
+ */
675
+ function applyClaudeTheme(theme) {
676
+ document.documentElement.setAttribute("data-theme", theme);
677
+ document.documentElement.style.colorScheme = theme;
678
+ }
679
+ registerHostShell({
680
+ id: "claude",
681
+ label: "Claude",
682
+ Conversation: ClaudeConversation,
683
+ applyTheme: applyClaudeTheme,
684
+ hostInfo: CLAUDE_HOST_INFO,
685
+ hostCapabilities: CLAUDE_HOST_CAPABILITIES,
686
+ userAgent: "claude",
687
+ styleVariables: {
688
+ ...DEFAULT_STYLE_VARIABLES,
689
+ "--color-background-primary": "light-dark(#faf9f5, #262624)",
690
+ "--color-background-secondary": "light-dark(#ffffff, #3a3935)",
691
+ "--color-background-tertiary": "light-dark(#e8e4dc, #4a4843)",
692
+ "--color-background-inverse": "light-dark(#2b2a27, #f3f0e8)",
693
+ "--color-text-primary": "light-dark(#2d2b27, #e8e4dc)",
694
+ "--color-text-secondary": "light-dark(#6b6560, #9b9690)",
695
+ "--color-text-tertiary": "light-dark(#9b9690, #6b6560)",
696
+ "--color-text-inverse": "light-dark(#e8e4dc, #2d2b27)",
697
+ "--color-border-primary": "light-dark(#e0ddd5, #4a4843)",
698
+ "--color-border-secondary": "light-dark(#d5d1c8, #5a5753)",
699
+ "--color-border-tertiary": "light-dark(#f0ede5, #3a3935)"
700
+ },
701
+ pageStyles: {
702
+ "--sim-bg-sidebar": "light-dark(#f9f8f3, #252523)",
703
+ "--sim-bg-conversation": "light-dark(#faf9f5, #262624)",
704
+ "--sim-bg-user-bubble": "light-dark(#f1eee6, #141413)",
705
+ "--sim-bg-reply-input": "light-dark(#ffffff, #30302e)"
706
+ }
707
+ });
708
+ //#endregion
709
+ //#region ../../node_modules/.pnpm/@modelcontextprotocol+ext-apps@1.2.2_@modelcontextprotocol+sdk@1.27.1_zod@4.3.6__react-_e9bf7657371391a829fe8b4e289b253c/node_modules/@modelcontextprotocol/ext-apps/dist/src/app-bridge.js
710
+ var G = "2026-01-26", m = union([literal("light"), literal("dark")]).describe("Color theme preference for the host environment."), D = union([
711
+ literal("inline"),
712
+ literal("fullscreen"),
713
+ literal("pip")
714
+ ]).describe("Display mode for UI presentation."), VQ = record(union([
715
+ literal("--color-background-primary"),
716
+ literal("--color-background-secondary"),
717
+ literal("--color-background-tertiary"),
718
+ literal("--color-background-inverse"),
719
+ literal("--color-background-ghost"),
720
+ literal("--color-background-info"),
721
+ literal("--color-background-danger"),
722
+ literal("--color-background-success"),
723
+ literal("--color-background-warning"),
724
+ literal("--color-background-disabled"),
725
+ literal("--color-text-primary"),
726
+ literal("--color-text-secondary"),
727
+ literal("--color-text-tertiary"),
728
+ literal("--color-text-inverse"),
729
+ literal("--color-text-ghost"),
730
+ literal("--color-text-info"),
731
+ literal("--color-text-danger"),
732
+ literal("--color-text-success"),
733
+ literal("--color-text-warning"),
734
+ literal("--color-text-disabled"),
735
+ literal("--color-border-primary"),
736
+ literal("--color-border-secondary"),
737
+ literal("--color-border-tertiary"),
738
+ literal("--color-border-inverse"),
739
+ literal("--color-border-ghost"),
740
+ literal("--color-border-info"),
741
+ literal("--color-border-danger"),
742
+ literal("--color-border-success"),
743
+ literal("--color-border-warning"),
744
+ literal("--color-border-disabled"),
745
+ literal("--color-ring-primary"),
746
+ literal("--color-ring-secondary"),
747
+ literal("--color-ring-inverse"),
748
+ literal("--color-ring-info"),
749
+ literal("--color-ring-danger"),
750
+ literal("--color-ring-success"),
751
+ literal("--color-ring-warning"),
752
+ literal("--font-sans"),
753
+ literal("--font-mono"),
754
+ literal("--font-weight-normal"),
755
+ literal("--font-weight-medium"),
756
+ literal("--font-weight-semibold"),
757
+ literal("--font-weight-bold"),
758
+ literal("--font-text-xs-size"),
759
+ literal("--font-text-sm-size"),
760
+ literal("--font-text-md-size"),
761
+ literal("--font-text-lg-size"),
762
+ literal("--font-heading-xs-size"),
763
+ literal("--font-heading-sm-size"),
764
+ literal("--font-heading-md-size"),
765
+ literal("--font-heading-lg-size"),
766
+ literal("--font-heading-xl-size"),
767
+ literal("--font-heading-2xl-size"),
768
+ literal("--font-heading-3xl-size"),
769
+ literal("--font-text-xs-line-height"),
770
+ literal("--font-text-sm-line-height"),
771
+ literal("--font-text-md-line-height"),
772
+ literal("--font-text-lg-line-height"),
773
+ literal("--font-heading-xs-line-height"),
774
+ literal("--font-heading-sm-line-height"),
775
+ literal("--font-heading-md-line-height"),
776
+ literal("--font-heading-lg-line-height"),
777
+ literal("--font-heading-xl-line-height"),
778
+ literal("--font-heading-2xl-line-height"),
779
+ literal("--font-heading-3xl-line-height"),
780
+ literal("--border-radius-xs"),
781
+ literal("--border-radius-sm"),
782
+ literal("--border-radius-md"),
783
+ literal("--border-radius-lg"),
784
+ literal("--border-radius-xl"),
785
+ literal("--border-radius-full"),
786
+ literal("--border-width-regular"),
787
+ literal("--shadow-hairline"),
788
+ literal("--shadow-sm"),
789
+ literal("--shadow-md"),
790
+ literal("--shadow-lg")
791
+ ]).describe("CSS variable keys available to MCP apps for theming.").describe(`Style variables for theming MCP apps.
792
+
793
+ Individual style keys are optional - hosts may provide any subset of these values.
794
+ Values are strings containing CSS values (colors, sizes, font stacks, etc.).
795
+
796
+ Note: This type uses \`Record<K, string | undefined>\` rather than \`Partial<Record<K, string>>\`
797
+ for compatibility with Zod schema generation. Both are functionally equivalent for validation.`), union([string(), _undefined()]).describe(`Style variables for theming MCP apps.
798
+
799
+ Individual style keys are optional - hosts may provide any subset of these values.
800
+ Values are strings containing CSS values (colors, sizes, font stacks, etc.).
801
+
802
+ Note: This type uses \`Record<K, string | undefined>\` rather than \`Partial<Record<K, string>>\`
803
+ for compatibility with Zod schema generation. Both are functionally equivalent for validation.`)).describe(`Style variables for theming MCP apps.
804
+
805
+ Individual style keys are optional - hosts may provide any subset of these values.
806
+ Values are strings containing CSS values (colors, sizes, font stacks, etc.).
807
+
808
+ Note: This type uses \`Record<K, string | undefined>\` rather than \`Partial<Record<K, string>>\`
809
+ for compatibility with Zod schema generation. Both are functionally equivalent for validation.`), V = object({
810
+ method: literal("ui/open-link"),
811
+ params: object({ url: string().describe("URL to open in the host's browser") })
812
+ });
813
+ object({ isError: boolean().optional().describe("True if the host failed to open the URL (e.g., due to security policy).") }).passthrough();
814
+ object({ isError: boolean().optional().describe("True if the download failed (e.g., user cancelled or host denied).") }).passthrough();
815
+ object({ isError: boolean().optional().describe("True if the host rejected or failed to deliver the message.") }).passthrough();
816
+ var F = object({
817
+ method: literal("ui/notifications/sandbox-proxy-ready"),
818
+ params: object({})
819
+ }), j = object({
820
+ connectDomains: array(string()).optional().describe(`Origins for network requests (fetch/XHR/WebSocket).
821
+
822
+ - Maps to CSP \`connect-src\` directive
823
+ - Empty or omitted → no network connections (secure default)`),
824
+ resourceDomains: array(string()).optional().describe("Origins for static resources (images, scripts, stylesheets, fonts, media).\n\n- Maps to CSP `img-src`, `script-src`, `style-src`, `font-src`, `media-src` directives\n- Wildcard subdomains supported: `https://*.example.com`\n- Empty or omitted → no network resources (secure default)"),
825
+ frameDomains: array(string()).optional().describe("Origins for nested iframes.\n\n- Maps to CSP `frame-src` directive\n- Empty or omitted → no nested iframes allowed (`frame-src 'none'`)"),
826
+ baseUriDomains: array(string()).optional().describe("Allowed base URIs for the document.\n\n- Maps to CSP `base-uri` directive\n- Empty or omitted → only same origin allowed (`base-uri 'self'`)")
827
+ }), E = object({
828
+ camera: object({}).optional().describe("Request camera access.\n\nMaps to Permission Policy `camera` feature."),
829
+ microphone: object({}).optional().describe("Request microphone access.\n\nMaps to Permission Policy `microphone` feature."),
830
+ geolocation: object({}).optional().describe("Request geolocation access.\n\nMaps to Permission Policy `geolocation` feature."),
831
+ clipboardWrite: object({}).optional().describe("Request clipboard write access.\n\nMaps to Permission Policy `clipboard-write` feature.")
832
+ }), P = object({
833
+ method: literal("ui/notifications/size-changed"),
834
+ params: object({
835
+ width: number().optional().describe("New width in pixels."),
836
+ height: number().optional().describe("New height in pixels.")
837
+ })
838
+ });
839
+ object({
840
+ method: literal("ui/notifications/tool-input"),
841
+ params: object({ arguments: record(string(), unknown().describe("Complete tool call arguments as key-value pairs.")).optional().describe("Complete tool call arguments as key-value pairs.") })
842
+ });
843
+ object({
844
+ method: literal("ui/notifications/tool-input-partial"),
845
+ params: object({ arguments: record(string(), unknown().describe("Partial tool call arguments (incomplete, may change).")).optional().describe("Partial tool call arguments (incomplete, may change).") })
846
+ });
847
+ object({
848
+ method: literal("ui/notifications/tool-cancelled"),
849
+ params: object({ reason: string().optional().describe("Optional reason for the cancellation (e.g., \"user action\", \"timeout\").") })
850
+ });
851
+ var p = object({ fonts: string().optional() }), c = object({
852
+ variables: VQ.optional().describe("CSS variables for theming the app."),
853
+ css: p.optional().describe("CSS blocks that apps can inject.")
854
+ });
855
+ object({
856
+ method: literal("ui/resource-teardown"),
857
+ params: object({})
858
+ });
859
+ var R = record(string(), unknown()), O = object({
860
+ text: object({}).optional().describe("Host supports text content blocks."),
861
+ image: object({}).optional().describe("Host supports image content blocks."),
862
+ audio: object({}).optional().describe("Host supports audio content blocks."),
863
+ resource: object({}).optional().describe("Host supports resource content blocks."),
864
+ resourceLink: object({}).optional().describe("Host supports resource link content blocks."),
865
+ structuredContent: object({}).optional().describe("Host supports structured content.")
866
+ }), n = object({
867
+ experimental: object({}).optional().describe("Experimental features (structure TBD)."),
868
+ openLinks: object({}).optional().describe("Host supports opening external URLs."),
869
+ downloadFile: object({}).optional().describe("Host supports file downloads via ui/download-file."),
870
+ serverTools: object({ listChanged: boolean().optional().describe("Host supports tools/list_changed notifications.") }).optional().describe("Host can proxy tool calls to the MCP server."),
871
+ serverResources: object({ listChanged: boolean().optional().describe("Host supports resources/list_changed notifications.") }).optional().describe("Host can proxy resource reads to the MCP server."),
872
+ logging: object({}).optional().describe("Host accepts log messages."),
873
+ sandbox: object({
874
+ permissions: E.optional().describe("Permissions granted by the host (camera, microphone, geolocation)."),
875
+ csp: j.optional().describe("CSP domains approved by the host.")
876
+ }).optional().describe("Sandbox configuration applied by the host."),
877
+ updateModelContext: O.optional().describe("Host accepts context updates (ui/update-model-context) to be included in the model's context for future turns."),
878
+ message: O.optional().describe("Host supports receiving content messages (ui/message) from the view.")
879
+ }), i = object({
880
+ experimental: object({}).optional().describe("Experimental features (structure TBD)."),
881
+ tools: object({ listChanged: boolean().optional().describe("App supports tools/list_changed notifications.") }).optional().describe("App exposes MCP-style tools that the host can call."),
882
+ availableDisplayModes: array(D).optional().describe("Display modes the app supports.")
883
+ }), M = object({
884
+ method: literal("ui/notifications/initialized"),
885
+ params: object({}).optional()
886
+ });
887
+ object({
888
+ csp: j.optional().describe("Content Security Policy configuration for UI resources."),
889
+ permissions: E.optional().describe("Sandbox permissions requested by the UI resource."),
890
+ domain: string().optional().describe(`Dedicated origin for view sandbox.
891
+
892
+ Useful when views need stable, dedicated origins for OAuth callbacks, CORS policies, or API key allowlists.
893
+
894
+ **Host-dependent:** The format and validation rules for this field are determined by each host. Servers MUST consult host-specific documentation for the expected domain format. Common patterns include:
895
+ - Hash-based subdomains (e.g., \`{hash}.claudemcpcontent.com\`)
896
+ - URL-derived subdomains (e.g., \`www-example-com.oaiusercontent.com\`)
897
+
898
+ If omitted, host uses default sandbox origin (typically per-conversation).`),
899
+ prefersBorder: boolean().optional().describe(`Visual boundary preference - true if view prefers a visible border.
900
+
901
+ Boolean requesting whether a visible border and background is provided by the host. Specifying an explicit value for this is recommended because hosts' defaults may vary.
902
+
903
+ - \`true\`: request visible border + background
904
+ - \`false\`: request no visible border + background
905
+ - omitted: host decides border`)
906
+ });
907
+ var W = object({
908
+ method: literal("ui/request-display-mode"),
909
+ params: object({ mode: D.describe("The display mode being requested.") })
910
+ });
911
+ object({ mode: D.describe("The display mode that was actually set. May differ from requested if not supported.") }).passthrough();
912
+ var l = union([literal("model"), literal("app")]).describe("Tool visibility scope - who can access the tool.");
913
+ object({
914
+ resourceUri: string().optional(),
915
+ visibility: array(l).optional().describe(`Who can access this tool. Default: ["model", "app"]
916
+ - "model": Tool visible to and callable by the agent
917
+ - "app": Tool callable by the app from this server only`)
918
+ });
919
+ object({ mimeTypes: array(string()).optional().describe("Array of supported MIME types for UI resources.\nMust include `\"text/html;profile=mcp-app\"` for MCP Apps support.") });
920
+ var S = object({
921
+ method: literal("ui/download-file"),
922
+ params: object({ contents: array(union([EmbeddedResourceSchema, ResourceLinkSchema])).describe("Resource contents to download — embedded (inline data) or linked (host fetches). Uses standard MCP resource types.") })
923
+ }), C = object({
924
+ method: literal("ui/message"),
925
+ params: object({
926
+ role: literal("user").describe("Message role, currently only \"user\" is supported."),
927
+ content: array(ContentBlockSchema).describe("Message content blocks (text, image, etc.).")
928
+ })
929
+ });
930
+ object({
931
+ method: literal("ui/notifications/sandbox-resource-ready"),
932
+ params: object({
933
+ html: string().describe("HTML content to load into the inner iframe."),
934
+ sandbox: string().optional().describe("Optional override for the inner iframe's sandbox attribute."),
935
+ csp: j.optional().describe("CSP configuration from resource metadata."),
936
+ permissions: E.optional().describe("Sandbox permissions from resource metadata.")
937
+ })
938
+ });
939
+ object({
940
+ method: literal("ui/notifications/tool-result"),
941
+ params: CallToolResultSchema.describe("Standard MCP tool execution result.")
942
+ });
943
+ var q = object({
944
+ toolInfo: object({
945
+ id: RequestIdSchema.optional().describe("JSON-RPC id of the tools/call request."),
946
+ tool: ToolSchema.describe("Tool definition including name, inputSchema, etc.")
947
+ }).optional().describe("Metadata of the tool call that instantiated this App."),
948
+ theme: m.optional().describe("Current color theme preference."),
949
+ styles: c.optional().describe("Style configuration for theming the app."),
950
+ displayMode: D.optional().describe("How the UI is currently displayed."),
951
+ availableDisplayModes: array(D).optional().describe("Display modes the host supports."),
952
+ containerDimensions: union([object({ height: number().describe("Fixed container height in pixels.") }), object({ maxHeight: union([number(), _undefined()]).optional().describe("Maximum container height in pixels.") })]).and(union([object({ width: number().describe("Fixed container width in pixels.") }), object({ maxWidth: union([number(), _undefined()]).optional().describe("Maximum container width in pixels.") })])).optional().describe(`Container dimensions. Represents the dimensions of the iframe or other
953
+ container holding the app. Specify either width or maxWidth, and either height or maxHeight.`),
954
+ locale: string().optional().describe("User's language and region preference in BCP 47 format."),
955
+ timeZone: string().optional().describe("User's timezone in IANA format."),
956
+ userAgent: string().optional().describe("Host application identifier."),
957
+ platform: union([
958
+ literal("web"),
959
+ literal("desktop"),
960
+ literal("mobile")
961
+ ]).optional().describe("Platform type for responsive design decisions."),
962
+ deviceCapabilities: object({
963
+ touch: boolean().optional().describe("Whether the device supports touch input."),
964
+ hover: boolean().optional().describe("Whether the device supports hover interactions.")
965
+ }).optional().describe("Device input capabilities."),
966
+ safeAreaInsets: object({
967
+ top: number().describe("Top safe area inset in pixels."),
968
+ right: number().describe("Right safe area inset in pixels."),
969
+ bottom: number().describe("Bottom safe area inset in pixels."),
970
+ left: number().describe("Left safe area inset in pixels.")
971
+ }).optional().describe("Mobile safe area boundaries in pixels.")
972
+ }).passthrough();
973
+ object({
974
+ method: literal("ui/notifications/host-context-changed"),
975
+ params: q.describe("Partial context update containing only changed fields.")
976
+ });
977
+ var y = object({
978
+ method: literal("ui/update-model-context"),
979
+ params: object({
980
+ content: array(ContentBlockSchema).optional().describe("Context content blocks (text, image, etc.)."),
981
+ structuredContent: record(string(), unknown().describe("Structured content for machine-readable context data.")).optional().describe("Structured content for machine-readable context data.")
982
+ })
983
+ }), f = object({
984
+ method: literal("ui/initialize"),
985
+ params: object({
986
+ appInfo: ImplementationSchema.describe("App identification (name and version)."),
987
+ appCapabilities: i.describe("Features and capabilities this app provides."),
988
+ protocolVersion: string().describe("Protocol version this app supports.")
989
+ })
990
+ });
991
+ object({
992
+ protocolVersion: string().describe("Negotiated protocol version string (e.g., \"2025-11-21\")."),
993
+ hostInfo: ImplementationSchema.describe("Host application identification and version."),
994
+ hostCapabilities: n.describe("Features and capabilities provided by the host."),
995
+ hostContext: q.describe("Rich context about the host environment.")
996
+ }).passthrough();
997
+ var N = class {
998
+ eventTarget;
999
+ eventSource;
1000
+ messageListener;
1001
+ constructor(X = window.parent, Y) {
1002
+ this.eventTarget = X;
1003
+ this.eventSource = Y;
1004
+ this.messageListener = (Z) => {
1005
+ if (Y && Z.source !== this.eventSource) {
1006
+ console.debug("Ignoring message from unknown source", Z);
1007
+ return;
1008
+ }
1009
+ let $ = JSONRPCMessageSchema.safeParse(Z.data);
1010
+ if ($.success) console.debug("Parsed message", $.data), this.onmessage?.($.data);
1011
+ else if (Z.data?.jsonrpc !== "2.0") console.debug("Ignoring non-JSON-RPC message", $.error.message, Z);
1012
+ else console.error("Failed to parse message", $.error.message, Z), this.onerror?.(Error("Invalid JSON-RPC message received: " + $.error.message));
1013
+ };
1014
+ }
1015
+ async start() {
1016
+ window.addEventListener("message", this.messageListener);
1017
+ }
1018
+ async send(X, Y) {
1019
+ if (X.method !== "ui/notifications/tool-input-partial") console.debug("Sending message", X);
1020
+ this.eventTarget.postMessage(X, "*");
1021
+ }
1022
+ async close() {
1023
+ window.removeEventListener("message", this.messageListener), this.onclose?.();
1024
+ }
1025
+ onclose;
1026
+ onerror;
1027
+ onmessage;
1028
+ sessionId;
1029
+ setProtocolVersion;
1030
+ };
1031
+ var rQ = [G];
1032
+ var oQ = class extends Protocol {
1033
+ _client;
1034
+ _hostInfo;
1035
+ _capabilities;
1036
+ _appCapabilities;
1037
+ _hostContext = {};
1038
+ _appInfo;
1039
+ constructor(X, Y, Z, $) {
1040
+ super($);
1041
+ this._client = X;
1042
+ this._hostInfo = Y;
1043
+ this._capabilities = Z;
1044
+ this._hostContext = $?.hostContext || {}, this.setRequestHandler(f, (K) => this._oninitialize(K)), this.setRequestHandler(PingRequestSchema, (K, J) => {
1045
+ return this.onping?.(K.params, J), {};
1046
+ }), this.setRequestHandler(W, (K) => {
1047
+ return { mode: this._hostContext.displayMode ?? "inline" };
1048
+ });
1049
+ }
1050
+ getAppCapabilities() {
1051
+ return this._appCapabilities;
1052
+ }
1053
+ getAppVersion() {
1054
+ return this._appInfo;
1055
+ }
1056
+ onping;
1057
+ set onsizechange(X) {
1058
+ this.setNotificationHandler(P, (Y) => X(Y.params));
1059
+ }
1060
+ set onsandboxready(X) {
1061
+ this.setNotificationHandler(F, (Y) => X(Y.params));
1062
+ }
1063
+ set oninitialized(X) {
1064
+ this.setNotificationHandler(M, (Y) => X(Y.params));
1065
+ }
1066
+ set onmessage(X) {
1067
+ this.setRequestHandler(C, async (Y, Z) => {
1068
+ return X(Y.params, Z);
1069
+ });
1070
+ }
1071
+ set onopenlink(X) {
1072
+ this.setRequestHandler(V, async (Y, Z) => {
1073
+ return X(Y.params, Z);
1074
+ });
1075
+ }
1076
+ set ondownloadfile(X) {
1077
+ this.setRequestHandler(S, async (Y, Z) => {
1078
+ return X(Y.params, Z);
1079
+ });
1080
+ }
1081
+ set onrequestdisplaymode(X) {
1082
+ this.setRequestHandler(W, async (Y, Z) => {
1083
+ return X(Y.params, Z);
1084
+ });
1085
+ }
1086
+ set onloggingmessage(X) {
1087
+ this.setNotificationHandler(LoggingMessageNotificationSchema, async (Y) => {
1088
+ X(Y.params);
1089
+ });
1090
+ }
1091
+ set onupdatemodelcontext(X) {
1092
+ this.setRequestHandler(y, async (Y, Z) => {
1093
+ return X(Y.params, Z);
1094
+ });
1095
+ }
1096
+ set oncalltool(X) {
1097
+ this.setRequestHandler(CallToolRequestSchema, async (Y, Z) => {
1098
+ return X(Y.params, Z);
1099
+ });
1100
+ }
1101
+ sendToolListChanged(X = {}) {
1102
+ return this.notification({
1103
+ method: "notifications/tools/list_changed",
1104
+ params: X
1105
+ });
1106
+ }
1107
+ set onlistresources(X) {
1108
+ this.setRequestHandler(ListResourcesRequestSchema, async (Y, Z) => {
1109
+ return X(Y.params, Z);
1110
+ });
1111
+ }
1112
+ set onlistresourcetemplates(X) {
1113
+ this.setRequestHandler(ListResourceTemplatesRequestSchema, async (Y, Z) => {
1114
+ return X(Y.params, Z);
1115
+ });
1116
+ }
1117
+ set onreadresource(X) {
1118
+ this.setRequestHandler(ReadResourceRequestSchema, async (Y, Z) => {
1119
+ return X(Y.params, Z);
1120
+ });
1121
+ }
1122
+ sendResourceListChanged(X = {}) {
1123
+ return this.notification({
1124
+ method: "notifications/resources/list_changed",
1125
+ params: X
1126
+ });
1127
+ }
1128
+ set onlistprompts(X) {
1129
+ this.setRequestHandler(ListPromptsRequestSchema, async (Y, Z) => {
1130
+ return X(Y.params, Z);
1131
+ });
1132
+ }
1133
+ sendPromptListChanged(X = {}) {
1134
+ return this.notification({
1135
+ method: "notifications/prompts/list_changed",
1136
+ params: X
1137
+ });
1138
+ }
1139
+ assertCapabilityForMethod(X) {}
1140
+ assertRequestHandlerCapability(X) {}
1141
+ assertNotificationCapability(X) {}
1142
+ assertTaskCapability(X) {
1143
+ throw Error("Tasks are not supported in MCP Apps");
1144
+ }
1145
+ assertTaskHandlerCapability(X) {
1146
+ throw Error("Task handlers are not supported in MCP Apps");
1147
+ }
1148
+ getCapabilities() {
1149
+ return this._capabilities;
1150
+ }
1151
+ async _oninitialize(X) {
1152
+ let Y = X.params.protocolVersion;
1153
+ return this._appCapabilities = X.params.appCapabilities, this._appInfo = X.params.appInfo, {
1154
+ protocolVersion: rQ.includes(Y) ? Y : G,
1155
+ hostCapabilities: this.getCapabilities(),
1156
+ hostInfo: this._hostInfo,
1157
+ hostContext: this._hostContext
1158
+ };
1159
+ }
1160
+ setHostContext(X) {
1161
+ let Y = {}, Z = !1;
1162
+ for (let $ of Object.keys(X)) {
1163
+ let K = this._hostContext[$], J = X[$];
1164
+ if (aQ(K, J)) continue;
1165
+ Y[$] = J, Z = !0;
1166
+ }
1167
+ if (Z) this._hostContext = X, this.sendHostContextChange(Y);
1168
+ }
1169
+ sendHostContextChange(X) {
1170
+ return this.notification({
1171
+ method: "ui/notifications/host-context-changed",
1172
+ params: X
1173
+ });
1174
+ }
1175
+ sendToolInput(X) {
1176
+ return this.notification({
1177
+ method: "ui/notifications/tool-input",
1178
+ params: X
1179
+ });
1180
+ }
1181
+ sendToolInputPartial(X) {
1182
+ return this.notification({
1183
+ method: "ui/notifications/tool-input-partial",
1184
+ params: X
1185
+ });
1186
+ }
1187
+ sendToolResult(X) {
1188
+ return this.notification({
1189
+ method: "ui/notifications/tool-result",
1190
+ params: X
1191
+ });
1192
+ }
1193
+ sendToolCancelled(X) {
1194
+ return this.notification({
1195
+ method: "ui/notifications/tool-cancelled",
1196
+ params: X
1197
+ });
1198
+ }
1199
+ sendSandboxResourceReady(X) {
1200
+ return this.notification({
1201
+ method: "ui/notifications/sandbox-resource-ready",
1202
+ params: X
1203
+ });
1204
+ }
1205
+ teardownResource(X, Y) {
1206
+ return this.request({
1207
+ method: "ui/resource-teardown",
1208
+ params: X
1209
+ }, R, Y);
1210
+ }
1211
+ sendResourceTeardown = this.teardownResource;
1212
+ async connect(X) {
1213
+ if (this.transport) throw Error("AppBridge is already connected. Call close() before connecting again.");
1214
+ if (this._client) {
1215
+ let Y = this._client.getServerCapabilities();
1216
+ if (!Y) throw Error("Client server capabilities not available");
1217
+ if (Y.tools) {
1218
+ if (this.oncalltool = async (Z, $) => {
1219
+ return this._client.request({
1220
+ method: "tools/call",
1221
+ params: Z
1222
+ }, CallToolResultSchema, { signal: $.signal });
1223
+ }, Y.tools.listChanged) this._client.setNotificationHandler(ToolListChangedNotificationSchema, (Z) => this.sendToolListChanged(Z.params));
1224
+ }
1225
+ if (Y.resources) {
1226
+ if (this.onlistresources = async (Z, $) => {
1227
+ return this._client.request({
1228
+ method: "resources/list",
1229
+ params: Z
1230
+ }, ListResourcesResultSchema, { signal: $.signal });
1231
+ }, this.onlistresourcetemplates = async (Z, $) => {
1232
+ return this._client.request({
1233
+ method: "resources/templates/list",
1234
+ params: Z
1235
+ }, ListResourceTemplatesResultSchema, { signal: $.signal });
1236
+ }, this.onreadresource = async (Z, $) => {
1237
+ return this._client.request({
1238
+ method: "resources/read",
1239
+ params: Z
1240
+ }, ReadResourceResultSchema, { signal: $.signal });
1241
+ }, Y.resources.listChanged) this._client.setNotificationHandler(ResourceListChangedNotificationSchema, (Z) => this.sendResourceListChanged(Z.params));
1242
+ }
1243
+ if (Y.prompts) {
1244
+ if (this.onlistprompts = async (Z, $) => {
1245
+ return this._client.request({
1246
+ method: "prompts/list",
1247
+ params: Z
1248
+ }, ListPromptsResultSchema, { signal: $.signal });
1249
+ }, Y.prompts.listChanged) this._client.setNotificationHandler(PromptListChangedNotificationSchema, (Z) => this.sendPromptListChanged(Z.params));
1250
+ }
1251
+ }
1252
+ return super.connect(X);
1253
+ }
1254
+ };
1255
+ function aQ(X, Y) {
1256
+ return JSON.stringify(X) === JSON.stringify(Y);
1257
+ }
1258
+ //#endregion
1259
+ //#region src/simulator/mcp-app-host.ts
1260
+ var DEFAULT_HOST_INFO = {
1261
+ name: "SunpeakSimulator",
1262
+ version: "1.0.0"
1263
+ };
1264
+ var DEFAULT_HOST_CAPABILITIES = {
1265
+ openLinks: {},
1266
+ serverTools: {},
1267
+ serverResources: {},
1268
+ downloadFile: {},
1269
+ logging: {},
1270
+ updateModelContext: { text: {} },
1271
+ message: { text: {} },
1272
+ sandbox: {}
1273
+ };
1274
+ /**
1275
+ * MCP Apps host for the Sunpeak simulator.
1276
+ * Wraps AppBridge to provide a simpler API for the simulator.
1277
+ * Connects to an iframe via PostMessageTransport.
1278
+ */
1279
+ var McpAppHost = class {
1280
+ bridge;
1281
+ options;
1282
+ _initialized = false;
1283
+ _contentWindow = null;
1284
+ _fenceId = 0;
1285
+ _fenceCleanup = null;
1286
+ _prevDisplayMode;
1287
+ _pendingToolInput = null;
1288
+ _pendingToolResult = null;
1289
+ constructor(options = {}) {
1290
+ this.options = options;
1291
+ this._prevDisplayMode = options.hostContext?.displayMode;
1292
+ this.bridge = new oQ(null, options.hostInfo ?? DEFAULT_HOST_INFO, options.hostCapabilities ?? DEFAULT_HOST_CAPABILITIES, { hostContext: options.hostContext });
1293
+ this.bridge.oninitialized = () => {
1294
+ this._initialized = true;
1295
+ if (this._pendingToolInput) {
1296
+ this.bridge.sendToolInput(this._pendingToolInput);
1297
+ this._pendingToolInput = null;
1298
+ }
1299
+ if (this._pendingToolResult) {
1300
+ this.bridge.sendToolResult(this._pendingToolResult);
1301
+ this._pendingToolResult = null;
1302
+ }
1303
+ };
1304
+ this.bridge.onopenlink = async ({ url }) => {
1305
+ console.log("[MCP App] openLink:", url);
1306
+ if (this.options.onOpenLink) this.options.onOpenLink(url);
1307
+ else {
1308
+ try {
1309
+ const parsed = new URL(url);
1310
+ if (parsed.protocol !== "http:" && parsed.protocol !== "https:") {
1311
+ console.warn("[MCP App] openLink blocked non-http(s) URL:", url);
1312
+ return {};
1313
+ }
1314
+ } catch {
1315
+ console.warn("[MCP App] openLink blocked invalid URL:", url);
1316
+ return {};
1317
+ }
1318
+ window.open(url, "_blank");
1319
+ }
1320
+ return {};
1321
+ };
1322
+ this.bridge.onmessage = async ({ role, content }) => {
1323
+ if (this.options.onMessage) this.options.onMessage(role, content);
1324
+ else console.log("[MCP App] sendMessage:", {
1325
+ role,
1326
+ content
1327
+ });
1328
+ return {};
1329
+ };
1330
+ this.bridge.onrequestdisplaymode = async ({ mode }) => {
1331
+ this.options.onDisplayModeChange?.(mode);
1332
+ return { mode };
1333
+ };
1334
+ this.bridge.onupdatemodelcontext = async ({ content, structuredContent }) => {
1335
+ this.options.onUpdateModelContext?.(content ?? [], structuredContent);
1336
+ return {};
1337
+ };
1338
+ this.bridge.onsizechange = (params) => {
1339
+ this.options.onSizeChanged?.(params);
1340
+ };
1341
+ this.bridge.onloggingmessage = (params) => {
1342
+ if (this.options.onLog) this.options.onLog(params);
1343
+ else {
1344
+ const level = params.level ?? "info";
1345
+ const prefix = `[MCP App${params.logger ? ` ${params.logger}` : ""}]`;
1346
+ if (level === "error" || level === "critical" || level === "alert" || level === "emergency") console.error(prefix, params.data);
1347
+ else if (level === "warning") console.warn(prefix, params.data);
1348
+ else if (level === "debug") console.debug(prefix, params.data);
1349
+ else console.log(prefix, params.data);
1350
+ }
1351
+ };
1352
+ this.bridge.oncalltool = async (params) => {
1353
+ if (this.options.onCallTool) return this.options.onCallTool(params);
1354
+ console.log("[MCP App] callServerTool:", params.name, params.arguments);
1355
+ return { content: [{
1356
+ type: "text",
1357
+ text: `[Simulator] Tool "${params.name}" called (no handler configured)`
1358
+ }] };
1359
+ };
1360
+ this.bridge.ondownloadfile = async ({ contents }) => {
1361
+ if (this.options.onDownloadFile) this.options.onDownloadFile(contents);
1362
+ else console.log("[MCP App] downloadFile:", contents.length, "item(s)");
1363
+ return {};
1364
+ };
1365
+ this.bridge.onsandboxready = () => {
1366
+ this.options.onSandboxReady?.();
1367
+ };
1368
+ }
1369
+ /**
1370
+ * Connect to an iframe's contentWindow.
1371
+ */
1372
+ async connectToIframe(contentWindow) {
1373
+ this._contentWindow = contentWindow;
1374
+ const transport = new N(contentWindow, contentWindow);
1375
+ await this.bridge.connect(transport);
1376
+ }
1377
+ /**
1378
+ * Wait for the iframe to process all pending messages and commit its DOM.
1379
+ *
1380
+ * Uses a postMessage fence: since messages to the same target are delivered
1381
+ * in FIFO order, a fence message sent after setHostContext is guaranteed to
1382
+ * be processed after the host context change. The iframe's fence responder
1383
+ * waits for requestAnimationFrame before acking, ensuring the DOM has been
1384
+ * committed for the re-render triggered by the context change.
1385
+ *
1386
+ * Returns immediately if the iframe is not connected.
1387
+ */
1388
+ waitForPaint() {
1389
+ const win = this._contentWindow;
1390
+ if (!win) return Promise.resolve();
1391
+ this._fenceCleanup?.();
1392
+ const id = ++this._fenceId;
1393
+ return new Promise((resolve) => {
1394
+ const handler = (event) => {
1395
+ if (event.source !== win) return;
1396
+ if (event.data?.method === "sunpeak/fence-ack" && event.data.params?.fenceId === id) {
1397
+ cleanup();
1398
+ resolve();
1399
+ }
1400
+ };
1401
+ const cleanup = () => {
1402
+ window.removeEventListener("message", handler);
1403
+ if (this._fenceCleanup === cleanup) this._fenceCleanup = null;
1404
+ };
1405
+ this._fenceCleanup = cleanup;
1406
+ window.addEventListener("message", handler);
1407
+ try {
1408
+ win.postMessage({
1409
+ jsonrpc: "2.0",
1410
+ method: "sunpeak/fence",
1411
+ params: { fenceId: id }
1412
+ }, "*");
1413
+ } catch {
1414
+ cleanup();
1415
+ resolve();
1416
+ }
1417
+ });
1418
+ }
1419
+ /**
1420
+ * Update the host context and notify the connected app.
1421
+ * Automatically detects display mode changes and waits for the iframe
1422
+ * to commit its DOM before firing onDisplayModeReady.
1423
+ */
1424
+ setHostContext(context) {
1425
+ this.bridge.setHostContext(context);
1426
+ const currentMode = context.displayMode;
1427
+ if (currentMode && currentMode !== this._prevDisplayMode) {
1428
+ this._prevDisplayMode = currentMode;
1429
+ const mode = currentMode;
1430
+ this.waitForPaint().then(() => {
1431
+ this.options.onDisplayModeReady?.(mode);
1432
+ });
1433
+ }
1434
+ }
1435
+ /**
1436
+ * Send tool input to the app.
1437
+ * If the app hasn't initialized yet, the input is queued.
1438
+ */
1439
+ sendToolInput(args) {
1440
+ const params = { arguments: args };
1441
+ if (this._initialized) this.bridge.sendToolInput(params);
1442
+ else this._pendingToolInput = params;
1443
+ }
1444
+ /**
1445
+ * Send tool result to the app.
1446
+ * If the app hasn't initialized yet, the result is queued.
1447
+ */
1448
+ sendToolResult(result) {
1449
+ if (this._initialized) this.bridge.sendToolResult(result);
1450
+ else this._pendingToolResult = result;
1451
+ }
1452
+ /**
1453
+ * Send partial/streaming tool input to the app.
1454
+ * Useful for simulating streaming tool arguments.
1455
+ */
1456
+ sendToolInputPartial(args) {
1457
+ const params = { arguments: args };
1458
+ if (this._initialized) this.bridge.sendToolInputPartial(params);
1459
+ }
1460
+ /**
1461
+ * Send tool cancellation notification to the app.
1462
+ * Simulates user or host cancelling a tool execution.
1463
+ */
1464
+ sendToolCancelled(reason) {
1465
+ const params = reason ? { reason } : {};
1466
+ if (this._initialized) this.bridge.sendToolCancelled(params);
1467
+ }
1468
+ /**
1469
+ * Send HTML resource to the sandbox proxy for secure loading.
1470
+ * Used in the double-iframe architecture after the proxy signals readiness.
1471
+ */
1472
+ sendSandboxResourceReady(params) {
1473
+ this.bridge.sendSandboxResourceReady(params);
1474
+ }
1475
+ /**
1476
+ * Send a custom message to the connected iframe (for sandbox proxy commands).
1477
+ */
1478
+ sendRawMessage(data) {
1479
+ const win = this._contentWindow;
1480
+ if (!win) return;
1481
+ try {
1482
+ win.postMessage(data, "*");
1483
+ } catch {}
1484
+ }
1485
+ /**
1486
+ * Close the connection.
1487
+ */
1488
+ async close() {
1489
+ this._fenceCleanup?.();
1490
+ this._fenceCleanup = null;
1491
+ try {
1492
+ if (this._initialized) await this.bridge.teardownResource({});
1493
+ } catch {}
1494
+ await this.bridge.close();
1495
+ this._initialized = false;
1496
+ }
1497
+ /**
1498
+ * Debug: Inject state directly into the app's useAppState hook.
1499
+ * This bypasses the normal MCP Apps protocol and is intended for
1500
+ * simulator testing/debugging only.
1501
+ */
1502
+ injectState(state) {
1503
+ const win = this._contentWindow;
1504
+ if (!win) return;
1505
+ try {
1506
+ win.postMessage({
1507
+ jsonrpc: "2.0",
1508
+ method: "sunpeak/injectState",
1509
+ params: { state }
1510
+ }, "*");
1511
+ } catch {}
1512
+ }
1513
+ /**
1514
+ * Update mutable options (callbacks) after construction.
1515
+ * Allows the simulator to swap handlers (e.g. onCallTool) without
1516
+ * recreating the host and tearing down the iframe connection.
1517
+ */
1518
+ updateOptions(partial) {
1519
+ Object.assign(this.options, partial);
1520
+ }
1521
+ get initialized() {
1522
+ return this._initialized;
1523
+ }
1524
+ };
1525
+ //#endregion
1526
+ //#region src/simulator/mock-openai-runtime.ts
1527
+ /**
1528
+ * Mock OpenAI runtime for the simulator.
1529
+ *
1530
+ * ChatGPT-specific hooks (useUploadFile, useRequestModal, etc.) call
1531
+ * `window.openai` directly — they don't use the MCP protocol. When the
1532
+ * ChatGPT host is selected in the simulator, we inject this mock into
1533
+ * the iframe's window so those hooks work during local development.
1534
+ */
1535
+ /**
1536
+ * Inline script that sets up a mock `window.openai` for srcdoc iframes.
1537
+ * Embedded in the generated HTML *before* the app's script so that
1538
+ * `isChatGPT()` and hooks work from the very first render.
1539
+ */
1540
+ var MOCK_OPENAI_RUNTIME_SCRIPT = [
1541
+ "window.openai={",
1542
+ "uploadFile:function(f){console.log(\"[Simulator] uploadFile:\",f.name);",
1543
+ "return Promise.resolve({fileId:\"sim_file_\"+Date.now()})},",
1544
+ "getFileDownloadUrl:function(p){console.log(\"[Simulator] getFileDownloadUrl:\",p.fileId);",
1545
+ "return Promise.resolve({downloadUrl:\"https://simulator.local/files/\"+p.fileId})},",
1546
+ "requestModal:function(p){console.log(\"[Simulator] requestModal:\",JSON.stringify(p));",
1547
+ "return Promise.resolve()},",
1548
+ "requestCheckout:function(s){console.log(\"[Simulator] requestCheckout:\",JSON.stringify(s));",
1549
+ "return Promise.resolve({id:\"sim_order_\"+Date.now(),checkout_session_id:s.id||\"sim_session\",status:\"completed\"})},",
1550
+ "requestClose:function(){console.log(\"[Simulator] requestClose\")},",
1551
+ "requestDisplayMode:function(p){console.log(\"[Simulator] requestDisplayMode:\",p.mode);",
1552
+ "return Promise.resolve()},",
1553
+ "sendFollowUpMessage:function(p){console.log(\"[Simulator] sendFollowUpMessage:\",p.prompt)},",
1554
+ "openExternal:function(p){console.log(\"[Simulator] openExternal:\",p.href);window.open(p.href,\"_blank\")}",
1555
+ "};"
1556
+ ].join("");
1557
+ //#endregion
1558
+ //#region src/simulator/sandbox-proxy.ts
1559
+ /**
1560
+ * Sandbox proxy for the double-iframe architecture.
1561
+ *
1562
+ * Real hosts (ChatGPT, Claude) use a two-level iframe structure:
1563
+ * 1. Outer iframe (sandbox proxy) — acts as a message relay on a separate origin
1564
+ * 2. Inner iframe — loads the untrusted app HTML
1565
+ *
1566
+ * The proxy relays PostMessage between the host (parent) and the app (inner iframe),
1567
+ * providing origin isolation and security boundaries.
1568
+ *
1569
+ * The simulator replicates this architecture so apps are tested under the same
1570
+ * iframe nesting they'll encounter in production.
1571
+ *
1572
+ * Protocol:
1573
+ * 1. Host creates outer iframe with proxy HTML (srcdoc)
1574
+ * 2. Proxy sends `ui/notifications/sandbox-proxy-ready` to parent
1575
+ * 3. Host sends `ui/notifications/sandbox-resource-ready` with { html, sandbox, csp, permissions }
1576
+ * OR `sunpeak/sandbox-load-src` with { src } for dev mode
1577
+ * 4. Proxy creates inner iframe and loads the content
1578
+ * 5. All subsequent messages relay transparently between parent and inner iframe
1579
+ */
1580
+ /**
1581
+ * Generate the sandbox proxy HTML.
1582
+ *
1583
+ * This HTML is loaded into the outer iframe via srcdoc. It:
1584
+ * - Signals readiness via `ui/notifications/sandbox-proxy-ready`
1585
+ * - Listens for resource content or URL to load into the inner iframe
1586
+ * - Relays all PostMessage between parent and inner iframe
1587
+ * - Optionally injects platform runtime scripts (e.g., mock window.openai)
1588
+ *
1589
+ * @param platformScript - Optional JS to inject into the inner iframe before the app loads
1590
+ */
1591
+ function generateSandboxProxyHtml(platformScript) {
1592
+ const escapedPlatformScript = platformScript ? JSON.stringify(platformScript) : "null";
1593
+ const colorScheme = "dark";
1594
+ return `<!DOCTYPE html>
1595
+ <html style="color-scheme:${colorScheme}">
1596
+ <head>
1597
+ <meta name="color-scheme" content="${colorScheme}" />
1598
+ <style>
1599
+ html, body { margin: 0; padding: 0; width: 100%; height: 100%; overflow: hidden; }
1600
+ iframe { border: none; width: 100%; height: 100%; display: block; }
1601
+ </style>
1602
+ </head>
1603
+ <body>
1604
+ <script>
1605
+ (function() {
1606
+ var innerFrame = null;
1607
+ var innerWindow = null;
1608
+ var platformScript = ${escapedPlatformScript};
1609
+
1610
+ // Relay messages between parent (host) and inner iframe (app)
1611
+ window.addEventListener('message', function(event) {
1612
+ var data = event.data;
1613
+ if (!data || typeof data !== 'object') return;
1614
+
1615
+ if (event.source === window.parent) {
1616
+ // ── Messages from the host ──
1617
+
1618
+ // sandbox-resource-ready: load HTML into inner iframe (scriptSrc/prod mode)
1619
+ if (data.method === 'ui/notifications/sandbox-resource-ready' && data.params) {
1620
+ createInnerFrame(data.params);
1621
+ return;
1622
+ }
1623
+
1624
+ // sunpeak/sandbox-load-src: load URL into inner iframe (src/dev mode)
1625
+ if (data.method === 'sunpeak/sandbox-load-src' && data.params) {
1626
+ createInnerFrameWithSrc(data.params);
1627
+ return;
1628
+ }
1629
+
1630
+ // Handle paint fence. Forward to the inner iframe and wait for its ack.
1631
+ // If the inner iframe has a fence responder (same-origin, script injected),
1632
+ // the ack is deterministic. Otherwise fall back to a 150ms timeout.
1633
+ if (data.method === 'sunpeak/fence' && data.params) {
1634
+ var fenceId = data.params.fenceId;
1635
+ var acked = false;
1636
+ var onAck = function(e) {
1637
+ if (e.source !== innerWindow) return;
1638
+ if (e.data && e.data.method === 'sunpeak/fence-ack' &&
1639
+ e.data.params && e.data.params.fenceId === fenceId) {
1640
+ acked = true;
1641
+ window.removeEventListener('message', onAck);
1642
+ window.parent.postMessage(e.data, '*');
1643
+ }
1644
+ };
1645
+ window.addEventListener('message', onAck);
1646
+ if (innerWindow) {
1647
+ try { innerWindow.postMessage(data, '*'); } catch(e) {}
1648
+ }
1649
+ setTimeout(function() {
1650
+ if (!acked) {
1651
+ window.removeEventListener('message', onAck);
1652
+ window.parent.postMessage({
1653
+ jsonrpc: '2.0',
1654
+ method: 'sunpeak/fence-ack',
1655
+ params: { fenceId: fenceId }
1656
+ }, '*');
1657
+ }
1658
+ }, 150);
1659
+ return;
1660
+ }
1661
+
1662
+ // Forward all other messages to the inner iframe
1663
+ if (innerWindow) {
1664
+ try { innerWindow.postMessage(data, '*'); } catch(e) { /* detached */ }
1665
+ }
1666
+ } else if (innerWindow && event.source === innerWindow) {
1667
+ // ── Messages from the app → forward to host ──
1668
+ try { window.parent.postMessage(data, '*'); } catch(e) { /* detached */ }
1669
+ }
1670
+ });
1671
+
1672
+ function createInnerFrame(params) {
1673
+ if (innerFrame) innerFrame.remove();
1674
+
1675
+ innerFrame = document.createElement('iframe');
1676
+ innerFrame.sandbox = params.sandbox ||
1677
+ 'allow-scripts allow-same-origin allow-forms allow-popups allow-popups-to-escape-sandbox';
1678
+ if (params.allow) innerFrame.allow = params.allow;
1679
+ document.body.appendChild(innerFrame);
1680
+ innerWindow = innerFrame.contentWindow;
1681
+
1682
+ // Write HTML content into the inner iframe
1683
+ var doc = innerFrame.contentDocument;
1684
+ if (doc && params.html) {
1685
+ doc.open();
1686
+ doc.write(params.html);
1687
+ doc.close();
1688
+ }
1689
+ }
1690
+
1691
+ function createInnerFrameWithSrc(params) {
1692
+ if (innerFrame) innerFrame.remove();
1693
+
1694
+ innerFrame = document.createElement('iframe');
1695
+ innerFrame.sandbox =
1696
+ 'allow-scripts allow-same-origin allow-forms allow-popups allow-popups-to-escape-sandbox';
1697
+ if (params.allow) innerFrame.allow = params.allow;
1698
+ innerFrame.src = params.src;
1699
+ innerFrame.style.height = '100%';
1700
+
1701
+ // Set color-scheme on the inner iframe to match the host theme.
1702
+ // This ensures prefers-color-scheme resolves correctly inside.
1703
+ if (params.theme) {
1704
+ innerFrame.style.colorScheme = params.theme;
1705
+ }
1706
+
1707
+ // After load, inject helpers into the inner iframe
1708
+ innerFrame.addEventListener('load', function() {
1709
+ innerWindow = innerFrame.contentWindow;
1710
+
1711
+ // Inject platform runtime (e.g., mock window.openai for ChatGPT)
1712
+ if (platformScript && innerWindow) {
1713
+ try {
1714
+ var pScript = innerFrame.contentDocument.createElement('script');
1715
+ pScript.textContent = platformScript;
1716
+ innerFrame.contentDocument.head.appendChild(pScript);
1717
+ } catch(e) { /* cross-origin */ }
1718
+ }
1719
+
1720
+ // Inject paint fence responder
1721
+ try {
1722
+ var fenceScript = innerFrame.contentDocument.createElement('script');
1723
+ fenceScript.setAttribute('data-sunpeak-fence', '');
1724
+ fenceScript.textContent = PAINT_FENCE_SCRIPT;
1725
+ innerFrame.contentDocument.head.appendChild(fenceScript);
1726
+ } catch(e) { /* cross-origin */ }
1727
+
1728
+ // Inject background rule
1729
+ if (params.theme) {
1730
+ try {
1731
+ innerFrame.contentDocument.documentElement.style.colorScheme = params.theme;
1732
+ var bgStyle = innerFrame.contentDocument.createElement('style');
1733
+ bgStyle.setAttribute('data-sunpeak-bg', '');
1734
+ bgStyle.textContent = 'html { background-color: var(--color-background-primary, Canvas); }';
1735
+ innerFrame.contentDocument.head.appendChild(bgStyle);
1736
+ } catch(e) { /* cross-origin */ }
1737
+ }
1738
+
1739
+ // Inject style variables for immediate rendering
1740
+ if (params.styleVars) {
1741
+ try {
1742
+ var root = innerFrame.contentDocument.documentElement;
1743
+ for (var key in params.styleVars) {
1744
+ if (params.styleVars[key]) root.style.setProperty(key, params.styleVars[key]);
1745
+ }
1746
+ } catch(e) { /* cross-origin */ }
1747
+ }
1748
+
1749
+ // Signal that load is complete — fade in
1750
+ innerFrame.style.opacity = '1';
1751
+ innerFrame.style.transition = 'opacity 100ms';
1752
+ });
1753
+
1754
+ // Start hidden for smooth fade-in
1755
+ innerFrame.style.opacity = '0';
1756
+ document.body.appendChild(innerFrame);
1757
+ innerWindow = innerFrame.contentWindow;
1758
+ }
1759
+
1760
+ // Paint fence responder — same as in iframe-resource.ts
1761
+ var PAINT_FENCE_SCRIPT = 'window.addEventListener("message",function(e){' +
1762
+ 'if(e.data&&e.data.method==="sunpeak/fence"){' +
1763
+ 'var fid=e.data.params&&e.data.params.fenceId;' +
1764
+ 'requestAnimationFrame(function(){' +
1765
+ 'e.source.postMessage({jsonrpc:"2.0",method:"sunpeak/fence-ack",params:{fenceId:fid}},"*");' +
1766
+ '});}});';
1767
+
1768
+ // Signal to the host that the proxy is ready.
1769
+ // Use setTimeout to ensure the host's PostMessageTransport listener
1770
+ // is set up before we send the ready notification. The srcdoc is parsed
1771
+ // synchronously by the browser, which can race with React's ref callback.
1772
+ setTimeout(function() {
1773
+ window.parent.postMessage({
1774
+ jsonrpc: '2.0',
1775
+ method: 'ui/notifications/sandbox-proxy-ready',
1776
+ params: {}
1777
+ }, '*');
1778
+ }, 0);
1779
+ })();
1780
+ <\/script>
1781
+ </body>
1782
+ </html>`;
1783
+ }
1784
+ //#endregion
1785
+ //#region src/simulator/iframe-resource.tsx
1786
+ /**
1787
+ * Allowed origins for cross-origin script loading.
1788
+ * - Local development: localhost, 127.0.0.1, file://
1789
+ * - Production: sunpeak-prod-app-storage.s3.us-east-2.amazonaws.com (serves user scripts)
1790
+ */
1791
+ var ALLOWED_SCRIPT_ORIGINS = [
1792
+ "https://sunpeak-prod-app-storage.s3.us-east-2.amazonaws.com",
1793
+ "http://localhost",
1794
+ "https://localhost",
1795
+ "http://127.0.0.1",
1796
+ "https://127.0.0.1"
1797
+ ];
1798
+ /**
1799
+ * Escapes HTML special characters to prevent XSS via attribute injection.
1800
+ */
1801
+ function escapeHtml(str) {
1802
+ return str.replace(/[&<>"']/g, (c) => {
1803
+ return {
1804
+ "&": "&amp;",
1805
+ "<": "&lt;",
1806
+ ">": "&gt;",
1807
+ "\"": "&quot;",
1808
+ "'": "&#39;"
1809
+ }[c] ?? c;
1810
+ });
1811
+ }
1812
+ /**
1813
+ * Validates that a URL is from an allowed origin.
1814
+ * Allows same-origin URLs and URLs from whitelisted domains.
1815
+ */
1816
+ function isAllowedUrl(src) {
1817
+ if (!src) return false;
1818
+ if (src.startsWith("/") && !src.startsWith("//")) return true;
1819
+ if (!src.includes("://")) return false;
1820
+ try {
1821
+ const url = new URL(src);
1822
+ if (url.origin === window.location.origin) return true;
1823
+ if (url.hostname === "localhost" || url.hostname === "127.0.0.1") return true;
1824
+ return ALLOWED_SCRIPT_ORIGINS.some((allowed) => {
1825
+ try {
1826
+ return url.origin === new URL(allowed).origin;
1827
+ } catch {
1828
+ return false;
1829
+ }
1830
+ });
1831
+ } catch {
1832
+ return false;
1833
+ }
1834
+ }
1835
+ /**
1836
+ * Extract CSP configuration from a resource's _meta.ui.csp field.
1837
+ */
1838
+ function extractResourceCSP(resource) {
1839
+ return (resource._meta?.ui)?.csp;
1840
+ }
1841
+ /**
1842
+ * Validates a CSP source entry is a safe origin URL (scheme + host + optional port).
1843
+ * Rejects wildcards, CSP keywords, and whitespace that could inject extra directives.
1844
+ */
1845
+ function isValidCspSource(source) {
1846
+ if (!source || /[\s;,']/.test(source) || source === "*") return false;
1847
+ try {
1848
+ const url = new URL(source);
1849
+ return url.protocol === "http:" || url.protocol === "https:" || url.protocol === "ws:" || url.protocol === "wss:";
1850
+ } catch {
1851
+ return false;
1852
+ }
1853
+ }
1854
+ /**
1855
+ * Generates a Content Security Policy string.
1856
+ */
1857
+ function generateCSP(csp, scriptSrc) {
1858
+ let scriptOrigin = "";
1859
+ try {
1860
+ scriptOrigin = new URL(scriptSrc, window.location.origin).origin;
1861
+ } catch {}
1862
+ const frameSources = /* @__PURE__ */ new Set();
1863
+ if (csp?.frameDomains) for (const domain of csp.frameDomains) if (isValidCspSource(domain)) frameSources.add(domain);
1864
+ else console.warn("[IframeResource] Ignoring invalid CSP frame domain:", domain);
1865
+ const frameSrc = frameSources.size > 0 ? `frame-src ${Array.from(frameSources).join(" ")}` : "frame-src 'none'";
1866
+ const baseSources = new Set(["'self'"]);
1867
+ if (csp?.baseUriDomains) for (const domain of csp.baseUriDomains) if (isValidCspSource(domain)) baseSources.add(domain);
1868
+ else console.warn("[IframeResource] Ignoring invalid CSP base-uri domain:", domain);
1869
+ const directives = [
1870
+ "default-src 'none'",
1871
+ `script-src 'self' 'unsafe-inline' 'unsafe-eval' blob: ${scriptOrigin}`.trim(),
1872
+ `style-src 'self' 'unsafe-inline' ${scriptOrigin}`.trim(),
1873
+ frameSrc,
1874
+ "object-src 'none'",
1875
+ "form-action 'none'",
1876
+ `base-uri ${Array.from(baseSources).join(" ")}`
1877
+ ];
1878
+ const connectSources = new Set(["'self'"]);
1879
+ if (scriptOrigin) connectSources.add(scriptOrigin);
1880
+ if (csp?.connectDomains) for (const domain of csp.connectDomains) if (isValidCspSource(domain)) connectSources.add(domain);
1881
+ else console.warn("[IframeResource] Ignoring invalid CSP connect domain:", domain);
1882
+ directives.push(`connect-src ${Array.from(connectSources).join(" ")}`);
1883
+ const resourceSources = new Set([
1884
+ "'self'",
1885
+ "data:",
1886
+ "blob:"
1887
+ ]);
1888
+ if (scriptOrigin) resourceSources.add(scriptOrigin);
1889
+ if (csp?.resourceDomains) for (const domain of csp.resourceDomains) if (isValidCspSource(domain)) resourceSources.add(domain);
1890
+ else console.warn("[IframeResource] Ignoring invalid CSP resource domain:", domain);
1891
+ const resourceList = Array.from(resourceSources).join(" ");
1892
+ directives.push(`img-src ${resourceList}`);
1893
+ directives.push(`font-src ${resourceList}`);
1894
+ directives.push(`media-src ${resourceList}`);
1895
+ return directives.join("; ");
1896
+ }
1897
+ /**
1898
+ * Paint fence responder script body.
1899
+ * Embedded in the generated HTML for scriptSrc mode. The sandbox proxy
1900
+ * handles fence injection for src-mode iframes.
1901
+ */
1902
+ var PAINT_FENCE_SCRIPT = `window.addEventListener("message",function(e){
1903
+ if(e.data&&e.data.method==="sunpeak/fence"){
1904
+ var fid=e.data.params&&e.data.params.fenceId;
1905
+ requestAnimationFrame(function(){
1906
+ e.source.postMessage({jsonrpc:"2.0",method:"sunpeak/fence-ack",params:{fenceId:fid}},"*");
1907
+ });}});`;
1908
+ /**
1909
+ * Generates HTML wrapper for a script URL.
1910
+ * The MCP Apps SDK in the loaded script handles communication via PostMessageTransport.
1911
+ */
1912
+ function generateScriptHtml(scriptSrc, theme, cspPolicy, platformScript) {
1913
+ const safeScriptSrc = escapeHtml(scriptSrc);
1914
+ const safeCsp = escapeHtml(cspPolicy);
1915
+ const safeTheme = escapeHtml(theme);
1916
+ return `<!DOCTYPE html>
1917
+ <html lang="en" data-theme="${safeTheme}" style="color-scheme:${safeTheme};background:Canvas">
1918
+ <head>
1919
+ <meta charset="UTF-8" />
1920
+ <meta name="color-scheme" content="${safeTheme}" />
1921
+ <meta name="viewport" content="width=device-width, initial-scale=1.0" />
1922
+ <meta http-equiv="Content-Security-Policy" content="${safeCsp}" />
1923
+ <title>Resource</title>
1924
+ <style>
1925
+ html {
1926
+ /* Use the MCP App background variable once JS sets it, otherwise
1927
+ Canvas (the system color that auto-adapts to color-scheme). */
1928
+ background-color: var(--color-background-primary, Canvas);
1929
+ }
1930
+ body, #root {
1931
+ margin: 0;
1932
+ padding: 0;
1933
+ width: 100%;
1934
+ background: transparent;
1935
+ }
1936
+ </style>
1937
+ <script>${PAINT_FENCE_SCRIPT}<\/script>${platformScript ? `\n <script>${platformScript}<\/script>` : ""}
1938
+ </head>
1939
+ <body>
1940
+ <div id="root"></div>
1941
+ <script src="${safeScriptSrc}"><\/script>
1942
+ </body>
1943
+ </html>`;
1944
+ }
1945
+ /**
1946
+ * Build the iframe `allow` attribute from resource-declared permissions.
1947
+ * Maps McpUiResourcePermissions to Permission Policy directives and
1948
+ * combines them with simulator baseline permissions.
1949
+ */
1950
+ function buildIframeAllow(permissions) {
1951
+ const parts = ["local-network-access *"];
1952
+ for (const [key, directive] of [
1953
+ ["camera", "camera"],
1954
+ ["microphone", "microphone"],
1955
+ ["geolocation", "geolocation"],
1956
+ ["clipboardWrite", "clipboard-write"]
1957
+ ]) if (permissions?.[key]) parts.push(directive);
1958
+ return parts.join("; ");
1959
+ }
1960
+ /**
1961
+ * IframeResource renders MCP Apps in an iframe, communicating via the
1962
+ * MCP Apps protocol (PostMessageTransport + AppBridge).
1963
+ *
1964
+ * Supports two modes:
1965
+ * - `src`: Load an HTML page directly (dev mode with Vite HMR)
1966
+ * - `scriptSrc`: Generate HTML wrapper for a JS file (production builds)
1967
+ *
1968
+ * The loaded app uses the MCP Apps SDK's useApp() hook which automatically
1969
+ * connects via PostMessageTransport to window.parent. The parent side uses
1970
+ * McpAppHost (wrapping AppBridge) to communicate.
1971
+ */
1972
+ function IframeResource({ src, scriptSrc, hostContext, toolInput, toolInputPartial, toolResult, hostOptions, csp, permissions, prefersBorder, className, style, onDisplayModeReady, debugInjectState, injectOpenAIRuntime, sandboxUrl }) {
1973
+ const iframeRef = useRef(null);
1974
+ const hostRef = useRef(null);
1975
+ const resourceUrl = src ?? scriptSrc;
1976
+ const srcRef = useRef(src);
1977
+ srcRef.current = src;
1978
+ const scriptSrcRef = useRef(scriptSrc);
1979
+ scriptSrcRef.current = scriptSrc;
1980
+ const cspRef = useRef(csp);
1981
+ cspRef.current = csp;
1982
+ const hostContextRef = useRef(hostContext);
1983
+ hostContextRef.current = hostContext;
1984
+ const injectOpenAIRuntimeRef = useRef(injectOpenAIRuntime);
1985
+ injectOpenAIRuntimeRef.current = injectOpenAIRuntime;
1986
+ const permissionsRef = useRef(permissions);
1987
+ permissionsRef.current = permissions;
1988
+ const hasReceivedSizeRef = useRef(false);
1989
+ const displayModeRef = useRef(hostContext?.displayMode);
1990
+ displayModeRef.current = hostContext?.displayMode;
1991
+ const lastContentHeightRef = useRef(null);
1992
+ const host = useMemo(() => new McpAppHost({
1993
+ hostContext,
1994
+ ...hostOptions,
1995
+ onSizeChanged: (params) => {
1996
+ hostOptions?.onSizeChanged?.(params);
1997
+ if (params.height != null) lastContentHeightRef.current = params.height;
1998
+ if (displayModeRef.current === "fullscreen") return;
1999
+ const iframe = iframeRef.current;
2000
+ if (!iframe) return;
2001
+ const style = getComputedStyle(iframe);
2002
+ const isBorderBox = style.boxSizing === "border-box";
2003
+ const from = {};
2004
+ const to = {};
2005
+ if (params.width != null) {
2006
+ let w = params.width;
2007
+ if (isBorderBox) w += parseFloat(style.borderLeftWidth) + parseFloat(style.borderRightWidth);
2008
+ from.minWidth = `${iframe.offsetWidth}px`;
2009
+ iframe.style.minWidth = `min(${w}px, 100%)`;
2010
+ to.minWidth = `min(${w}px, 100%)`;
2011
+ }
2012
+ if (params.height != null) {
2013
+ hasReceivedSizeRef.current = true;
2014
+ let h = params.height;
2015
+ if (isBorderBox) h += parseFloat(style.borderTopWidth) + parseFloat(style.borderBottomWidth);
2016
+ from.height = `${iframe.offsetHeight}px`;
2017
+ iframe.style.height = `${h}px`;
2018
+ to.height = `${h}px`;
2019
+ }
2020
+ if (Object.keys(from).length > 0) iframe.animate([from, to], {
2021
+ duration: 300,
2022
+ easing: "ease-out"
2023
+ });
2024
+ },
2025
+ onDisplayModeReady: (mode) => onDisplayModeReady?.(mode),
2026
+ onSandboxReady: () => {
2027
+ const currentSrc = srcRef.current;
2028
+ const currentScriptSrc = scriptSrcRef.current;
2029
+ const currentHost = hostRef.current;
2030
+ if (!currentHost) return;
2031
+ if (currentScriptSrc) {
2032
+ const absoluteScriptSrc = currentScriptSrc.startsWith("/") ? `${window.location.origin}${currentScriptSrc}` : currentScriptSrc;
2033
+ const cspPolicy = generateCSP(cspRef.current, absoluteScriptSrc);
2034
+ const appHtml = generateScriptHtml(absoluteScriptSrc, hostContextRef.current?.theme ?? "dark", cspPolicy, injectOpenAIRuntimeRef.current ? MOCK_OPENAI_RUNTIME_SCRIPT : void 0);
2035
+ currentHost.sendSandboxResourceReady({
2036
+ html: appHtml,
2037
+ sandbox: "allow-scripts allow-same-origin allow-forms allow-popups allow-popups-to-escape-sandbox"
2038
+ });
2039
+ if (iframeRef.current) {
2040
+ iframeRef.current.style.opacity = "1";
2041
+ iframeRef.current.style.transition = "opacity 100ms";
2042
+ }
2043
+ } else if (currentSrc) {
2044
+ const absoluteSrc = currentSrc.startsWith("/") ? `${window.location.origin}${currentSrc}` : currentSrc;
2045
+ const allowAttr = buildIframeAllow(permissionsRef.current);
2046
+ currentHost.sendRawMessage({
2047
+ jsonrpc: "2.0",
2048
+ method: "sunpeak/sandbox-load-src",
2049
+ params: {
2050
+ src: absoluteSrc,
2051
+ allow: allowAttr,
2052
+ theme: hostContextRef.current?.theme,
2053
+ styleVars: hostContextRef.current?.styles?.variables
2054
+ }
2055
+ });
2056
+ }
2057
+ }
2058
+ }), []);
2059
+ hostRef.current = host;
2060
+ const setIframeRef = useCallback((node) => {
2061
+ iframeRef.current = node;
2062
+ if (node?.contentWindow) host.connectToIframe(node.contentWindow);
2063
+ }, [host]);
2064
+ const handleLoad = useCallback(() => {
2065
+ if (iframeRef.current) {
2066
+ iframeRef.current.style.opacity = "1";
2067
+ iframeRef.current.style.transition = "opacity 100ms";
2068
+ }
2069
+ }, []);
2070
+ useEffect(() => {
2071
+ if (hostOptions) host.updateOptions(hostOptions);
2072
+ }, [host, hostOptions]);
2073
+ useEffect(() => {
2074
+ if (hostContext) host.setHostContext(hostContext);
2075
+ if (iframeRef.current) {
2076
+ if (hostContext?.displayMode === "fullscreen") iframeRef.current.style.height = "100%";
2077
+ else if (lastContentHeightRef.current != null) iframeRef.current.style.height = `${lastContentHeightRef.current}px`;
2078
+ }
2079
+ }, [host, hostContext]);
2080
+ useEffect(() => {
2081
+ if (toolInput) host.sendToolInput(toolInput);
2082
+ }, [host, toolInput]);
2083
+ useEffect(() => {
2084
+ if (toolInputPartial) host.sendToolInputPartial(toolInputPartial);
2085
+ }, [host, toolInputPartial]);
2086
+ useEffect(() => {
2087
+ if (toolResult) host.sendToolResult(toolResult);
2088
+ }, [host, toolResult]);
2089
+ useEffect(() => {
2090
+ if (debugInjectState != null) host.injectState(debugInjectState);
2091
+ }, [host, debugInjectState]);
2092
+ useEffect(() => {
2093
+ return () => {
2094
+ hostRef.current?.close();
2095
+ };
2096
+ }, []);
2097
+ const isValidUrl = useMemo(() => resourceUrl && isAllowedUrl(resourceUrl), [resourceUrl]);
2098
+ const allowAttribute = useMemo(() => buildIframeAllow(permissions), [permissions]);
2099
+ const borderStyle = prefersBorder ? { border: "1px solid var(--color-border-primary, #e5e7eb)" } : { border: "none" };
2100
+ const sandboxSrc = useMemo(() => {
2101
+ if (!sandboxUrl) return void 0;
2102
+ const url = new URL("/proxy", sandboxUrl);
2103
+ if (injectOpenAIRuntime) url.searchParams.set("platform", "chatgpt");
2104
+ return url.toString();
2105
+ }, [sandboxUrl, injectOpenAIRuntime]);
2106
+ const proxyHtml = useMemo(() => {
2107
+ if (sandboxSrc) return void 0;
2108
+ return generateSandboxProxyHtml(injectOpenAIRuntime ? MOCK_OPENAI_RUNTIME_SCRIPT : void 0);
2109
+ }, [sandboxSrc, injectOpenAIRuntime]);
2110
+ const iframeStyle = {
2111
+ ...borderStyle,
2112
+ background: "transparent",
2113
+ colorScheme: hostContext?.theme === "light" ? "light dark" : "dark light",
2114
+ opacity: 0,
2115
+ width: "100%",
2116
+ ...hostContext?.displayMode === "fullscreen" ? { height: "100%" } : { minHeight: "200px" },
2117
+ ...style
2118
+ };
2119
+ const dims = hostContext?.containerDimensions;
2120
+ const isFullscreenMode = hostContext?.displayMode === "fullscreen";
2121
+ const wrapperStyle = {};
2122
+ if (dims && !isFullscreenMode) {
2123
+ const h = "height" in dims ? dims.height : void 0;
2124
+ const mh = "maxHeight" in dims ? dims.maxHeight : void 0;
2125
+ const w = "width" in dims ? dims.width : void 0;
2126
+ const mw = "maxWidth" in dims ? dims.maxWidth : void 0;
2127
+ if (h != null) {
2128
+ wrapperStyle.height = h;
2129
+ wrapperStyle.overflow = "hidden";
2130
+ }
2131
+ if (mh != null) {
2132
+ wrapperStyle.maxHeight = mh;
2133
+ wrapperStyle.overflow = "hidden";
2134
+ }
2135
+ if (w != null) wrapperStyle.width = w;
2136
+ if (mw != null) wrapperStyle.maxWidth = mw;
2137
+ }
2138
+ if (src && !isValidUrl) {
2139
+ console.error("[IframeResource] URL not allowed:", src);
2140
+ return /* @__PURE__ */ jsxs("div", {
2141
+ style: {
2142
+ color: "red",
2143
+ padding: 20
2144
+ },
2145
+ children: ["Error: URL not allowed: ", src]
2146
+ });
2147
+ }
2148
+ if (scriptSrc && !isValidUrl) {
2149
+ console.error("[IframeResource] Script source not allowed:", scriptSrc);
2150
+ return /* @__PURE__ */ jsx("div", {
2151
+ style: {
2152
+ color: "red",
2153
+ padding: 20
2154
+ },
2155
+ children: "Error: Script source not allowed."
2156
+ });
2157
+ }
2158
+ return /* @__PURE__ */ jsx("div", {
2159
+ className,
2160
+ style: wrapperStyle,
2161
+ children: /* @__PURE__ */ jsx("iframe", {
2162
+ ref: setIframeRef,
2163
+ onLoad: handleLoad,
2164
+ style: iframeStyle,
2165
+ title: "Resource Preview",
2166
+ sandbox: "allow-scripts allow-same-origin allow-forms allow-popups allow-popups-to-escape-sandbox",
2167
+ allow: allowAttribute,
2168
+ src: sandboxSrc ?? void 0,
2169
+ srcDoc: sandboxSrc ? void 0 : proxyHtml
2170
+ })
2171
+ });
2172
+ }
2173
+ //#endregion
2174
+ //#region src/simulator/use-simulator-state.ts
2175
+ var DEFAULT_THEME = "dark";
2176
+ var DEFAULT_DISPLAY_MODE = "inline";
2177
+ var DEFAULT_PLATFORM = "desktop";
2178
+ /**
2179
+ * Parse URL params for initial simulator values.
2180
+ * Supported params:
2181
+ * - simulation: simulation name (e.g., 'show-albums')
2182
+ * - theme: 'light' | 'dark'
2183
+ * - displayMode: 'inline' | 'pip' | 'fullscreen'
2184
+ * - locale: e.g., 'en-US'
2185
+ * - maxHeight: number (containerDimensions.maxHeight)
2186
+ * - maxWidth: number (containerDimensions.maxWidth)
2187
+ * - deviceType: 'mobile' | 'tablet' | 'desktop' → maps to platform
2188
+ * - hover: 'true' | 'false'
2189
+ * - touch: 'true' | 'false'
2190
+ * - safeAreaTop, safeAreaBottom, safeAreaLeft, safeAreaRight: number
2191
+ * - host: 'chatgpt' | 'claude'
2192
+ * - prodTools: 'true' | 'false'
2193
+ * - prodResources: 'true' | 'false'
2194
+ */
2195
+ function parseUrlParams() {
2196
+ if (typeof window === "undefined") return {};
2197
+ const params = new URLSearchParams(window.location.search);
2198
+ const simulation = params.get("simulation") ?? void 0;
2199
+ const theme = params.get("theme");
2200
+ const displayMode = params.get("displayMode");
2201
+ const locale = params.get("locale");
2202
+ const maxHeightParam = params.get("maxHeight");
2203
+ const containerMaxHeight = maxHeightParam ? Number(maxHeightParam) : void 0;
2204
+ const maxWidthParam = params.get("maxWidth");
2205
+ const containerMaxWidth = maxWidthParam ? Number(maxWidthParam) : void 0;
2206
+ const host = params.get("host") ?? void 0;
2207
+ const prodToolsParam = params.get("prodTools");
2208
+ const prodTools = prodToolsParam === "true" ? true : prodToolsParam === "false" ? false : void 0;
2209
+ const prodResourcesParam = params.get("prodResources");
2210
+ const prodResources = prodResourcesParam === "true" ? true : prodResourcesParam === "false" ? false : void 0;
2211
+ const deviceType = params.get("deviceType");
2212
+ let platform;
2213
+ if (deviceType === "mobile" || deviceType === "tablet") platform = "mobile";
2214
+ else if (deviceType === "desktop") platform = "desktop";
2215
+ const hoverParam = params.get("hover");
2216
+ const touchParam = params.get("touch");
2217
+ const deviceCapabilities = hoverParam || touchParam ? {
2218
+ hover: hoverParam === "false" ? false : true,
2219
+ touch: touchParam === "true" ? true : false
2220
+ } : void 0;
2221
+ const safeAreaTop = params.get("safeAreaTop");
2222
+ const safeAreaBottom = params.get("safeAreaBottom");
2223
+ const safeAreaLeft = params.get("safeAreaLeft");
2224
+ const safeAreaRight = params.get("safeAreaRight");
2225
+ const safeAreaInsets = safeAreaTop || safeAreaBottom || safeAreaLeft || safeAreaRight ? {
2226
+ top: safeAreaTop ? Number(safeAreaTop) : 0,
2227
+ bottom: safeAreaBottom ? Number(safeAreaBottom) : 0,
2228
+ left: safeAreaLeft ? Number(safeAreaLeft) : 0,
2229
+ right: safeAreaRight ? Number(safeAreaRight) : 0
2230
+ } : void 0;
2231
+ return {
2232
+ simulation,
2233
+ theme: theme ?? void 0,
2234
+ displayMode: displayMode ?? void 0,
2235
+ locale: locale ?? void 0,
2236
+ containerMaxHeight,
2237
+ containerMaxWidth,
2238
+ platform,
2239
+ deviceCapabilities,
2240
+ safeAreaInsets,
2241
+ host: host ?? void 0,
2242
+ prodTools,
2243
+ prodResources
2244
+ };
2245
+ }
2246
+ function useSimulatorState({ simulations, defaultHost = "chatgpt" }) {
2247
+ const simulationNames = Object.keys(simulations).filter((name) => simulations[name].resource).sort((a, b) => {
2248
+ const simA = simulations[a];
2249
+ const simB = simulations[b];
2250
+ const resourceLabelA = simA.resource.title || simA.resource.name;
2251
+ const resourceLabelB = simB.resource.title || simB.resource.name;
2252
+ const labelA = `${resourceLabelA}: ${simA.tool.title || simA.tool.name}`;
2253
+ const labelB = `${resourceLabelB}: ${simB.tool.title || simB.tool.name}`;
2254
+ return labelA.localeCompare(labelB);
2255
+ });
2256
+ const urlParams = useMemo(() => parseUrlParams(), []);
2257
+ const [screenWidth, setScreenWidth] = useState("full");
2258
+ const isMobileWidth = (width) => width === "mobile-s" || width === "mobile-l";
2259
+ const [activeHost, setActiveHost] = useState(urlParams.host ?? defaultHost);
2260
+ const [selectedSimulationName, setSelectedSimulationName] = useState(useMemo(() => {
2261
+ const defaultName = simulationNames[0] ?? "";
2262
+ if (!urlParams.simulation) return defaultName;
2263
+ return urlParams.simulation in simulations ? urlParams.simulation : defaultName;
2264
+ }, [
2265
+ urlParams.simulation,
2266
+ simulations,
2267
+ simulationNames
2268
+ ]));
2269
+ const selectedSim = simulations[selectedSimulationName];
2270
+ const [theme, setTheme] = useState(urlParams.theme ?? DEFAULT_THEME);
2271
+ const [displayMode, _setDisplayMode] = useState(urlParams.displayMode ?? DEFAULT_DISPLAY_MODE);
2272
+ const [locale, setLocale] = useState(urlParams.locale ?? "en-US");
2273
+ const [containerHeight, setContainerHeight] = useState(void 0);
2274
+ const [containerWidth, setContainerWidth] = useState(void 0);
2275
+ const [containerMaxHeight, setContainerMaxHeight] = useState(urlParams.containerMaxHeight);
2276
+ const [containerMaxWidth, setContainerMaxWidth] = useState(urlParams.containerMaxWidth);
2277
+ const [platform, setPlatform] = useState(urlParams.platform ?? DEFAULT_PLATFORM);
2278
+ const [hover, setHover] = useState(urlParams.deviceCapabilities?.hover ?? true);
2279
+ const [touch, setTouch] = useState(urlParams.deviceCapabilities?.touch ?? false);
2280
+ const [safeAreaInsets, setSafeAreaInsets] = useState(urlParams.safeAreaInsets ?? {
2281
+ top: 0,
2282
+ bottom: 0,
2283
+ left: 0,
2284
+ right: 0
2285
+ });
2286
+ const [timeZone, setTimeZone] = useState(() => Intl.DateTimeFormat().resolvedOptions().timeZone);
2287
+ const [measuredContentWidth, setMeasuredContentWidth] = useState(void 0);
2288
+ const handleContentWidthChange = useCallback((width) => {
2289
+ setMeasuredContentWidth(width);
2290
+ }, []);
2291
+ const setDisplayMode = (mode) => {
2292
+ if (isMobileWidth(screenWidth) && mode === "pip") _setDisplayMode("fullscreen");
2293
+ else _setDisplayMode(mode);
2294
+ };
2295
+ const handleDisplayModeReady = useCallback((_mode) => {}, []);
2296
+ const containerDimensions = useMemo(() => {
2297
+ if (containerHeight != null || containerWidth != null || containerMaxHeight != null || containerMaxWidth != null) return {
2298
+ ...containerHeight != null ? { height: containerHeight } : {},
2299
+ ...containerWidth != null ? { width: containerWidth } : {},
2300
+ ...containerMaxHeight != null ? { maxHeight: containerMaxHeight } : {},
2301
+ ...containerMaxWidth != null ? { maxWidth: containerMaxWidth } : {}
2302
+ };
2303
+ if (displayMode === "fullscreen") return {
2304
+ height: typeof window !== "undefined" ? window.innerHeight - 52 : 800,
2305
+ width: measuredContentWidth ?? (typeof window !== "undefined" ? window.innerWidth : 1280)
2306
+ };
2307
+ if (displayMode === "pip") return {
2308
+ height: 480,
2309
+ ...measuredContentWidth != null ? { maxWidth: measuredContentWidth } : {}
2310
+ };
2311
+ if (measuredContentWidth != null) return { maxWidth: measuredContentWidth };
2312
+ }, [
2313
+ containerHeight,
2314
+ containerWidth,
2315
+ containerMaxHeight,
2316
+ containerMaxWidth,
2317
+ measuredContentWidth,
2318
+ displayMode
2319
+ ]);
2320
+ const hostContext = useMemo(() => ({
2321
+ theme,
2322
+ displayMode,
2323
+ availableDisplayModes: [
2324
+ "inline",
2325
+ "pip",
2326
+ "fullscreen"
2327
+ ],
2328
+ locale,
2329
+ timeZone,
2330
+ platform,
2331
+ deviceCapabilities: {
2332
+ hover,
2333
+ touch
2334
+ },
2335
+ safeAreaInsets,
2336
+ ...containerDimensions ? { containerDimensions } : {}
2337
+ }), [
2338
+ theme,
2339
+ displayMode,
2340
+ locale,
2341
+ timeZone,
2342
+ platform,
2343
+ hover,
2344
+ touch,
2345
+ safeAreaInsets,
2346
+ containerDimensions
2347
+ ]);
2348
+ const [toolInput, setToolInput] = useState(() => selectedSim?.toolInput ?? {});
2349
+ const [toolResult, setToolResult] = useState(() => selectedSim?.toolResult);
2350
+ const [toolInputJson, setToolInputJson] = useState(() => JSON.stringify(toolInput, null, 2));
2351
+ const [toolResultJson, setToolResultJson] = useState(() => JSON.stringify(toolResult ?? null, null, 2));
2352
+ const [modelContextJson, setModelContextJson] = useState("null");
2353
+ const [modelContext, setModelContext] = useState(null);
2354
+ const [editingField, setEditingField] = useState(null);
2355
+ const [toolInputError, setToolInputError] = useState("");
2356
+ const [toolResultError, setToolResultError] = useState("");
2357
+ const [modelContextError, setModelContextError] = useState("");
2358
+ useEffect(() => {
2359
+ const newInput = selectedSim?.toolInput ?? {};
2360
+ const newResult = selectedSim?.toolResult ?? void 0;
2361
+ setToolInput(newInput);
2362
+ setToolResult(newResult);
2363
+ if (editingField !== "toolInput") {
2364
+ setToolInputJson(JSON.stringify(newInput, null, 2));
2365
+ setToolInputError("");
2366
+ }
2367
+ if (editingField !== "toolResult") {
2368
+ setToolResultJson(JSON.stringify(newResult ?? null, null, 2));
2369
+ setToolResultError("");
2370
+ }
2371
+ if (editingField !== "modelContext") {
2372
+ setModelContextJson("null");
2373
+ setModelContext(null);
2374
+ setModelContextError("");
2375
+ }
2376
+ }, [selectedSimulationName, selectedSim]);
2377
+ useEffect(() => {
2378
+ if (isMobileWidth(screenWidth) && displayMode === "pip") _setDisplayMode("fullscreen");
2379
+ }, [screenWidth, displayMode]);
2380
+ const handleDisplayModeChange = (mode) => {
2381
+ setDisplayMode(mode);
2382
+ };
2383
+ const handleUpdateModelContext = (content, structuredContent) => {
2384
+ setModelContextJson(JSON.stringify(structuredContent ?? content, null, 2));
2385
+ };
2386
+ const validateJSON = (json, setJson, setError) => {
2387
+ setJson(json);
2388
+ try {
2389
+ if (json.trim() !== "") JSON.parse(json);
2390
+ setError("");
2391
+ } catch (e) {
2392
+ setError(e instanceof Error ? e.message : "Invalid JSON");
2393
+ }
2394
+ };
2395
+ const commitJSON = (json, setError, updateFn) => {
2396
+ try {
2397
+ const parsed = json.trim() === "" ? null : JSON.parse(json);
2398
+ setError("");
2399
+ updateFn(parsed);
2400
+ } catch (e) {
2401
+ setError(e instanceof Error ? e.message : "Invalid JSON");
2402
+ } finally {
2403
+ setEditingField(null);
2404
+ }
2405
+ };
2406
+ const effectiveToolResult = useMemo(() => {
2407
+ if (!toolResult && !modelContext) return void 0;
2408
+ if (!modelContext) return toolResult;
2409
+ const baseResult = toolResult ?? { content: [] };
2410
+ const baseStructured = baseResult.structuredContent ?? {};
2411
+ return {
2412
+ ...baseResult,
2413
+ structuredContent: {
2414
+ ...baseStructured,
2415
+ ...modelContext
2416
+ }
2417
+ };
2418
+ }, [toolResult, modelContext]);
2419
+ const resourceUrl = selectedSim?.resourceUrl;
2420
+ const resourceScript = selectedSim?.resourceScript;
2421
+ const csp = selectedSim?.resource ? extractResourceCSP(selectedSim.resource) : void 0;
2422
+ const resourceMeta = (selectedSim?.resource?._meta)?.ui;
2423
+ return {
2424
+ simulationNames,
2425
+ selectedSimulationName,
2426
+ setSelectedSimulationName,
2427
+ selectedSim,
2428
+ activeHost,
2429
+ setActiveHost,
2430
+ screenWidth,
2431
+ setScreenWidth,
2432
+ theme,
2433
+ setTheme,
2434
+ displayMode,
2435
+ setDisplayMode,
2436
+ locale,
2437
+ setLocale,
2438
+ containerHeight,
2439
+ setContainerHeight,
2440
+ containerWidth,
2441
+ setContainerWidth,
2442
+ containerMaxHeight,
2443
+ setContainerMaxHeight,
2444
+ containerMaxWidth,
2445
+ setContainerMaxWidth,
2446
+ platform,
2447
+ setPlatform,
2448
+ hover,
2449
+ setHover,
2450
+ touch,
2451
+ setTouch,
2452
+ safeAreaInsets,
2453
+ setSafeAreaInsets,
2454
+ timeZone,
2455
+ setTimeZone,
2456
+ hostContext,
2457
+ handleDisplayModeReady,
2458
+ toolInput,
2459
+ setToolInput,
2460
+ toolResult,
2461
+ setToolResult,
2462
+ effectiveToolResult,
2463
+ modelContext,
2464
+ setModelContext,
2465
+ toolInputJson,
2466
+ setToolInputJson,
2467
+ toolInputError,
2468
+ setToolInputError,
2469
+ toolResultJson,
2470
+ setToolResultJson,
2471
+ toolResultError,
2472
+ setToolResultError,
2473
+ modelContextJson,
2474
+ setModelContextJson,
2475
+ modelContextError,
2476
+ setModelContextError,
2477
+ editingField,
2478
+ setEditingField,
2479
+ validateJSON,
2480
+ commitJSON,
2481
+ measuredContentWidth,
2482
+ handleContentWidthChange,
2483
+ handleDisplayModeChange,
2484
+ handleUpdateModelContext,
2485
+ resourceUrl,
2486
+ resourceScript,
2487
+ csp,
2488
+ permissions: resourceMeta?.permissions,
2489
+ prefersBorder: resourceMeta?.prefersBorder ?? false,
2490
+ urlProdTools: urlParams.prodTools,
2491
+ urlProdResources: urlParams.prodResources
2492
+ };
2493
+ }
2494
+ //#endregion
2495
+ //#region src/simulator/theme-provider.tsx
2496
+ var ThemeProviderContext = React.createContext(void 0);
2497
+ /** Default theme applier: sets data-theme attribute on document.documentElement */
2498
+ function defaultApplyTheme(theme) {
2499
+ if (typeof document !== "undefined") document.documentElement.setAttribute("data-theme", theme);
2500
+ }
2501
+ function ThemeProvider({ children, defaultTheme = "light", theme: controlledTheme, applyTheme, ...props }) {
2502
+ const [internalTheme] = React.useState(defaultTheme);
2503
+ const theme = controlledTheme ?? internalTheme;
2504
+ const applier = applyTheme ?? defaultApplyTheme;
2505
+ React.useLayoutEffect(() => {
2506
+ if (typeof window !== "undefined" && typeof document !== "undefined") try {
2507
+ applier(theme);
2508
+ } catch (error) {
2509
+ console.warn("Failed to apply document theme:", error);
2510
+ }
2511
+ }, [theme, applier]);
2512
+ const value = { theme };
2513
+ return /* @__PURE__ */ jsx(ThemeProviderContext.Provider, {
2514
+ ...props,
2515
+ value,
2516
+ children
2517
+ });
2518
+ }
2519
+ var useThemeContext = () => {
2520
+ const context = React.useContext(ThemeProviderContext);
2521
+ if (context === void 0) throw new Error("useThemeContext must be used within a ThemeProvider");
2522
+ return context;
2523
+ };
2524
+ //#endregion
2525
+ //#region src/simulator/simple-sidebar.tsx
2526
+ var DEFAULT_SIDEBAR_WIDTH = 224;
2527
+ function ChevronRightIcon() {
2528
+ return /* @__PURE__ */ jsx("svg", {
2529
+ width: "1em",
2530
+ height: "1em",
2531
+ viewBox: "0 0 24 24",
2532
+ fill: "currentColor",
2533
+ children: /* @__PURE__ */ jsx("path", {
2534
+ fillRule: "evenodd",
2535
+ d: "M8.293 4.293a1 1 0 0 1 1.414 0l7 7a1 1 0 0 1 0 1.414l-7 7a1 1 0 0 1-1.414-1.414L14.586 12 8.293 5.707a1 1 0 0 1 0-1.414Z",
2536
+ clipRule: "evenodd"
2537
+ })
2538
+ });
2539
+ }
2540
+ function SimpleSidebar({ children, controls, headerRight }) {
2541
+ const [isDrawerOpen, setIsDrawerOpen] = React.useState(false);
2542
+ const [sidebarWidth, setSidebarWidth] = React.useState(DEFAULT_SIDEBAR_WIDTH);
2543
+ const [isResizing, setIsResizing] = React.useState(false);
2544
+ const handleMouseDown = React.useCallback((e) => {
2545
+ e.preventDefault();
2546
+ setIsResizing(true);
2547
+ }, []);
2548
+ React.useEffect(() => {
2549
+ if (!isResizing) return;
2550
+ const handleMouseMove = (e) => {
2551
+ const maxWidth = Math.floor(window.innerWidth / 3);
2552
+ setSidebarWidth(Math.min(maxWidth, Math.max(DEFAULT_SIDEBAR_WIDTH, e.clientX)));
2553
+ };
2554
+ const handleMouseUp = () => {
2555
+ setIsResizing(false);
2556
+ };
2557
+ document.addEventListener("mousemove", handleMouseMove);
2558
+ document.addEventListener("mouseup", handleMouseUp);
2559
+ return () => {
2560
+ document.removeEventListener("mousemove", handleMouseMove);
2561
+ document.removeEventListener("mouseup", handleMouseUp);
2562
+ };
2563
+ }, [isResizing]);
2564
+ return /* @__PURE__ */ jsxs("div", {
2565
+ className: "sunpeak-simulator-root flex h-screen w-full overflow-hidden relative",
2566
+ children: [
2567
+ isResizing && /* @__PURE__ */ jsx("div", { className: "fixed inset-0 z-50 cursor-col-resize" }),
2568
+ isDrawerOpen && /* @__PURE__ */ jsx("div", {
2569
+ className: "md:hidden fixed inset-0 bg-black/50 z-40 pointer-events-auto",
2570
+ onClick: (e) => {
2571
+ if (e.target === e.currentTarget) setIsDrawerOpen(false);
2572
+ }
2573
+ }),
2574
+ /* @__PURE__ */ jsxs("aside", {
2575
+ className: `
2576
+ relative flex flex-col bg-sidebar
2577
+ md:z-auto
2578
+ max-md:fixed max-md:inset-y-0 max-md:left-0 max-md:z-[100]
2579
+ max-md:transition-transform max-md:duration-300 max-md:!w-2/3
2580
+ ${isDrawerOpen ? "max-md:translate-x-0" : "max-md:-translate-x-full"}
2581
+ `,
2582
+ style: {
2583
+ width: sidebarWidth,
2584
+ borderRight: "1px solid var(--color-border-primary)"
2585
+ },
2586
+ children: [/* @__PURE__ */ jsx("div", {
2587
+ className: "flex-1 overflow-y-auto min-h-0 px-3 pb-3 pt-0",
2588
+ children: /* @__PURE__ */ jsx("div", {
2589
+ className: "space-y-3",
2590
+ children: /* @__PURE__ */ jsxs("div", { children: [/* @__PURE__ */ jsxs("div", {
2591
+ className: "flex items-center justify-between sticky top-0 bg-sidebar z-10 py-2",
2592
+ children: [/* @__PURE__ */ jsx("h2", {
2593
+ className: "text-xs font-semibold",
2594
+ style: { color: "var(--color-text-primary)" },
2595
+ children: "Controls"
2596
+ }), /* @__PURE__ */ jsxs("div", {
2597
+ className: "flex items-center gap-2",
2598
+ children: [headerRight, /* @__PURE__ */ jsx("button", {
2599
+ onClick: () => setIsDrawerOpen(false),
2600
+ className: "md:hidden p-1 transition-colors",
2601
+ style: { color: "var(--color-text-secondary)" },
2602
+ type: "button",
2603
+ "aria-label": "Close sidebar",
2604
+ children: /* @__PURE__ */ jsx("svg", {
2605
+ width: "16",
2606
+ height: "16",
2607
+ viewBox: "0 0 16 16",
2608
+ fill: "none",
2609
+ xmlns: "http://www.w3.org/2000/svg",
2610
+ children: /* @__PURE__ */ jsx("path", {
2611
+ d: "M12 4L4 12M4 4L12 12",
2612
+ stroke: "currentColor",
2613
+ strokeWidth: "2",
2614
+ strokeLinecap: "round"
2615
+ })
2616
+ })
2617
+ })]
2618
+ })]
2619
+ }), controls] })
2620
+ })
2621
+ }), /* @__PURE__ */ jsx("div", {
2622
+ onMouseDown: handleMouseDown,
2623
+ className: "hidden md:block absolute top-0 right-0 w-1 h-full cursor-col-resize hover:bg-black/10 dark:hover:bg-white/10 active:bg-black/20 dark:active:bg-white/20 transition-colors"
2624
+ })]
2625
+ }),
2626
+ /* @__PURE__ */ jsxs("main", {
2627
+ className: "flex-1 overflow-auto relative",
2628
+ children: [/* @__PURE__ */ jsx("button", {
2629
+ onClick: () => setIsDrawerOpen(true),
2630
+ className: "md:hidden fixed top-18 left-0 z-30 bg-sidebar rounded-r-md p-2 shadow-lg hover:bg-black/5 dark:hover:bg-white/10 transition-colors",
2631
+ style: {
2632
+ borderRight: "1px solid var(--color-border-primary)",
2633
+ borderTop: "1px solid var(--color-border-primary)",
2634
+ borderBottom: "1px solid var(--color-border-primary)"
2635
+ },
2636
+ type: "button",
2637
+ "aria-label": "Open sidebar",
2638
+ children: /* @__PURE__ */ jsx(ChevronRightIcon, {})
2639
+ }), children]
2640
+ })
2641
+ ]
2642
+ });
2643
+ }
2644
+ var DOCS_BASE_URL = "https://sunpeak.ai/docs";
2645
+ function HelpIcon({ tooltip, docsPath }) {
2646
+ const [pos, setPos] = React.useState(null);
2647
+ const ref = React.useRef(null);
2648
+ const showTooltip = () => {
2649
+ const rect = ref.current?.getBoundingClientRect();
2650
+ if (rect) setPos({
2651
+ top: rect.top + rect.height / 2,
2652
+ left: rect.right + 6
2653
+ });
2654
+ };
2655
+ return /* @__PURE__ */ jsxs("a", {
2656
+ ref,
2657
+ href: `${DOCS_BASE_URL}/${docsPath}`,
2658
+ target: "_blank",
2659
+ rel: "noopener noreferrer",
2660
+ className: "inline-flex items-center justify-center no-underline flex-shrink-0 transition-colors",
2661
+ style: { color: "var(--color-text-tertiary, var(--color-text-secondary))" },
2662
+ onClick: (e) => e.stopPropagation(),
2663
+ onMouseEnter: showTooltip,
2664
+ onMouseLeave: () => setPos(null),
2665
+ children: [/* @__PURE__ */ jsxs("svg", {
2666
+ width: "12",
2667
+ height: "12",
2668
+ viewBox: "0 0 12 12",
2669
+ fill: "none",
2670
+ xmlns: "http://www.w3.org/2000/svg",
2671
+ children: [/* @__PURE__ */ jsx("circle", {
2672
+ cx: "6",
2673
+ cy: "6",
2674
+ r: "5.25",
2675
+ stroke: "currentColor",
2676
+ strokeWidth: "1"
2677
+ }), /* @__PURE__ */ jsx("text", {
2678
+ x: "6.25",
2679
+ y: "8.5",
2680
+ textAnchor: "middle",
2681
+ fill: "currentColor",
2682
+ fontSize: "7.5",
2683
+ fontWeight: "600",
2684
+ fontFamily: "system-ui, sans-serif",
2685
+ children: "?"
2686
+ })]
2687
+ }), pos && /* @__PURE__ */ jsx("span", {
2688
+ className: "pointer-events-none fixed whitespace-nowrap rounded px-2 py-1 text-[11px] font-normal leading-tight z-[200]",
2689
+ style: {
2690
+ top: pos.top,
2691
+ left: pos.left,
2692
+ transform: "translateY(-50%)",
2693
+ backgroundColor: "var(--color-text-primary)",
2694
+ color: "var(--color-background-primary)"
2695
+ },
2696
+ children: tooltip
2697
+ })]
2698
+ });
2699
+ }
2700
+ function SidebarControl({ label, children, tooltip, docsPath }) {
2701
+ return /* @__PURE__ */ jsxs("div", {
2702
+ className: "space-y-1",
2703
+ children: [/* @__PURE__ */ jsxs("span", {
2704
+ className: "text-[10px] font-medium leading-tight inline-flex items-center gap-1",
2705
+ style: { color: "var(--color-text-secondary)" },
2706
+ children: [label, tooltip && docsPath && /* @__PURE__ */ jsx(HelpIcon, {
2707
+ tooltip,
2708
+ docsPath
2709
+ })]
2710
+ }), children]
2711
+ });
2712
+ }
2713
+ function SidebarCollapsibleControl({ label, children, defaultCollapsed = true, tooltip, docsPath }) {
2714
+ const [isCollapsed, setIsCollapsed] = React.useState(defaultCollapsed);
2715
+ return /* @__PURE__ */ jsxs("div", {
2716
+ className: "space-y-1",
2717
+ children: [/* @__PURE__ */ jsxs("button", {
2718
+ onClick: () => setIsCollapsed(!isCollapsed),
2719
+ className: "w-full flex items-center justify-between text-[10px] font-medium leading-tight transition-colors py-1 cursor-pointer",
2720
+ style: { color: "var(--color-text-secondary)" },
2721
+ type: "button",
2722
+ children: [/* @__PURE__ */ jsxs("span", {
2723
+ className: "inline-flex items-center gap-1",
2724
+ children: [label, tooltip && docsPath && /* @__PURE__ */ jsx(HelpIcon, {
2725
+ tooltip,
2726
+ docsPath
2727
+ })]
2728
+ }), /* @__PURE__ */ jsx("span", {
2729
+ className: "text-[8px]",
2730
+ children: isCollapsed ? "▶" : "▼"
2731
+ })]
2732
+ }), !isCollapsed && children]
2733
+ });
2734
+ }
2735
+ var formElementStyle = {
2736
+ color: "var(--color-text-primary)",
2737
+ backgroundColor: "var(--color-background-primary)",
2738
+ cursor: "pointer"
2739
+ };
2740
+ function SidebarSelect({ value, onChange, options, placeholder }) {
2741
+ return /* @__PURE__ */ jsxs("select", {
2742
+ value,
2743
+ onChange: (e) => onChange(e.target.value),
2744
+ className: "w-full h-7 text-xs rounded-full px-2 outline-none appearance-none bg-no-repeat bg-[length:12px] bg-[right_6px_center]",
2745
+ style: {
2746
+ ...formElementStyle,
2747
+ backgroundImage: `url("data:image/svg+xml,%3csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 16 16' fill='%236b7280'%3e%3cpath d='M4.22 6.22a.75.75 0 0 1 1.06 0L8 8.94l2.72-2.72a.75.75 0 1 1 1.06 1.06l-3.25 3.25a.75.75 0 0 1-1.06 0L4.22 7.28a.75.75 0 0 1 0-1.06Z'/%3e%3c/svg%3e")`,
2748
+ paddingRight: "1.5rem"
2749
+ },
2750
+ children: [placeholder && /* @__PURE__ */ jsx("option", {
2751
+ value: "",
2752
+ disabled: true,
2753
+ children: placeholder
2754
+ }), options.map((option) => /* @__PURE__ */ jsx("option", {
2755
+ value: option.value,
2756
+ children: option.label
2757
+ }, option.value))]
2758
+ });
2759
+ }
2760
+ function SidebarInput({ value, onChange, applyOnBlur = false, placeholder, type = "text", disabled = false }) {
2761
+ const [draft, setDraft] = useState(value);
2762
+ const [isEditing, setIsEditing] = useState(false);
2763
+ const [prevValue, setPrevValue] = useState(value);
2764
+ if (!isEditing && value !== prevValue) {
2765
+ setPrevValue(value);
2766
+ setDraft(value);
2767
+ }
2768
+ if (applyOnBlur) return /* @__PURE__ */ jsx("input", {
2769
+ type,
2770
+ value: draft,
2771
+ onChange: (e) => setDraft(e.target.value),
2772
+ onFocus: () => setIsEditing(true),
2773
+ onBlur: () => {
2774
+ setIsEditing(false);
2775
+ onChange(draft);
2776
+ },
2777
+ placeholder,
2778
+ disabled,
2779
+ className: "w-full h-7 text-xs rounded-md px-2 outline-none disabled:opacity-50 disabled:cursor-not-allowed",
2780
+ style: {
2781
+ ...formElementStyle,
2782
+ cursor: disabled ? void 0 : "text"
2783
+ }
2784
+ });
2785
+ return /* @__PURE__ */ jsx("input", {
2786
+ type,
2787
+ value,
2788
+ onChange: (e) => onChange(e.target.value),
2789
+ placeholder,
2790
+ disabled,
2791
+ className: "w-full h-7 text-xs rounded-md px-2 outline-none disabled:opacity-50 disabled:cursor-not-allowed",
2792
+ style: {
2793
+ ...formElementStyle,
2794
+ cursor: disabled ? void 0 : "text"
2795
+ }
2796
+ });
2797
+ }
2798
+ function SidebarCheckbox({ checked, onChange, label, tooltip, docsPath }) {
2799
+ const id = React.useId();
2800
+ return /* @__PURE__ */ jsxs("div", {
2801
+ className: "flex items-center gap-1.5",
2802
+ children: [/* @__PURE__ */ jsx("input", {
2803
+ id,
2804
+ type: "checkbox",
2805
+ checked,
2806
+ onChange: (e) => onChange(e.target.checked),
2807
+ className: "outline-none cursor-pointer"
2808
+ }), /* @__PURE__ */ jsxs("label", {
2809
+ htmlFor: id,
2810
+ className: "text-[11px] select-none cursor-pointer leading-tight inline-flex items-center gap-1",
2811
+ style: { color: "var(--color-text-primary)" },
2812
+ children: [label, tooltip && docsPath && /* @__PURE__ */ jsx(HelpIcon, {
2813
+ tooltip,
2814
+ docsPath
2815
+ })]
2816
+ })]
2817
+ });
2818
+ }
2819
+ function SidebarTextarea({ value, onChange, onFocus, onBlur, placeholder, maxRows = 8, error }) {
2820
+ const contentRows = value?.split("\n").length ?? 1;
2821
+ return /* @__PURE__ */ jsxs("div", {
2822
+ className: "space-y-0.5",
2823
+ children: [/* @__PURE__ */ jsx("textarea", {
2824
+ value,
2825
+ onChange: (e) => onChange(e.target.value),
2826
+ onFocus,
2827
+ onBlur,
2828
+ placeholder,
2829
+ rows: Math.min(contentRows, maxRows),
2830
+ className: "w-full text-[10px] font-mono rounded-md px-2 py-1.5 outline-none resize-y",
2831
+ style: {
2832
+ ...formElementStyle,
2833
+ cursor: "text",
2834
+ whiteSpace: "pre",
2835
+ overflowX: "auto",
2836
+ overflowWrap: "normal",
2837
+ ...error ? { boxShadow: "inset 0 0 0 1px var(--color-text-danger, #dc2626)" } : {}
2838
+ },
2839
+ "aria-invalid": !!error
2840
+ }), error && /* @__PURE__ */ jsx("div", {
2841
+ className: "text-[9px]",
2842
+ style: { color: "var(--color-text-danger, #dc2626)" },
2843
+ children: error
2844
+ })]
2845
+ });
2846
+ }
2847
+ function SidebarToggle({ value, onChange, options }) {
2848
+ return /* @__PURE__ */ jsx("div", {
2849
+ className: "inline-flex w-full rounded-full p-[3px] gap-0.5",
2850
+ style: { backgroundColor: "var(--color-background-tertiary)" },
2851
+ role: "group",
2852
+ "aria-label": "Toggle options",
2853
+ children: options.map((option) => {
2854
+ const isSelected = value === option.value;
2855
+ return /* @__PURE__ */ jsx("button", {
2856
+ onClick: () => onChange(option.value),
2857
+ "aria-pressed": isSelected,
2858
+ className: "flex-1 text-[10px] font-medium h-[22px] px-2 rounded-full outline-none transition-all duration-150 cursor-pointer",
2859
+ style: {
2860
+ backgroundColor: isSelected ? "var(--color-background-primary)" : "transparent",
2861
+ color: isSelected ? "var(--color-text-primary)" : "var(--color-text-secondary)",
2862
+ boxShadow: isSelected ? "0 1px 2px 0 rgba(0,0,0,0.06)" : "none"
2863
+ },
2864
+ type: "button",
2865
+ children: option.label
2866
+ }, option.value);
2867
+ })
2868
+ });
2869
+ }
2870
+ //#endregion
2871
+ //#region src/types/simulation.ts
2872
+ /**
2873
+ * Resolve a `ServerToolMock` to a concrete `CallToolResult` given the call arguments.
2874
+ *
2875
+ * - Simple form (single result): returns it directly.
2876
+ * - Conditional form (array of `{ when, result }`): returns the first entry
2877
+ * whose `when` keys all shallow-equal the corresponding values in `args`.
2878
+ * Falls back to `undefined` if no condition matches.
2879
+ */
2880
+ function resolveServerToolResult(mock, args) {
2881
+ if (!Array.isArray(mock)) return mock;
2882
+ for (const entry of mock) if (Object.entries(entry.when).every(([key, value]) => args != null && args[key] === value)) return entry.result;
2883
+ }
2884
+ //#endregion
2885
+ //#region src/simulator/simulator.tsx
2886
+ function Simulator({ children, simulations = {}, appName = "Sunpeak", appIcon, defaultHost = "chatgpt", onCallTool, defaultProdTools = false, defaultProdResources = false, hideSimulatorModes = false, sandboxUrl }) {
2887
+ const state = useSimulatorState({
2888
+ simulations,
2889
+ defaultHost
2890
+ });
2891
+ const [prodTools, setProdTools] = React.useState(state.urlProdTools ?? defaultProdTools);
2892
+ const [prodResources, setProdResources] = React.useState(state.urlProdResources ?? defaultProdResources);
2893
+ const [isRunning, setIsRunning] = React.useState(false);
2894
+ const [hasRun, setHasRun] = React.useState(false);
2895
+ const [showCheck, setShowCheck] = React.useState(false);
2896
+ const checkTimerRef = React.useRef(void 0);
2897
+ React.useEffect(() => {
2898
+ if (prodTools) setHasRun(false);
2899
+ else {
2900
+ const simResult = state.selectedSim?.toolResult ?? void 0;
2901
+ state.setToolResult(simResult);
2902
+ }
2903
+ }, [prodTools, state.selectedSimulationName]);
2904
+ React.useEffect(() => () => clearTimeout(checkTimerRef.current), []);
2905
+ const toolOptions = React.useMemo(() => {
2906
+ if (!prodTools) return [];
2907
+ const seen = /* @__PURE__ */ new Map();
2908
+ for (const simName of state.simulationNames) {
2909
+ const toolName = simulations[simName].tool.name;
2910
+ if (!seen.has(toolName)) seen.set(toolName, simName);
2911
+ }
2912
+ return Array.from(seen.entries()).map(([toolName, simName]) => ({
2913
+ value: simName,
2914
+ label: simulations[simName].tool.title || toolName
2915
+ }));
2916
+ }, [
2917
+ prodTools,
2918
+ state.simulationNames,
2919
+ simulations
2920
+ ]);
2921
+ const handleRun = React.useCallback(async () => {
2922
+ if (!onCallTool || !state.selectedSim) return;
2923
+ const toolName = state.selectedSim.tool.name;
2924
+ setIsRunning(true);
2925
+ try {
2926
+ const result = await onCallTool({
2927
+ name: toolName,
2928
+ arguments: state.toolInput
2929
+ });
2930
+ state.setToolResult(result);
2931
+ state.setToolResultJson(JSON.stringify(result, null, 2));
2932
+ state.setToolResultError("");
2933
+ setHasRun(true);
2934
+ setShowCheck(true);
2935
+ clearTimeout(checkTimerRef.current);
2936
+ checkTimerRef.current = setTimeout(() => setShowCheck(false), 2e3);
2937
+ } catch (err) {
2938
+ const message = err instanceof Error ? err.message : String(err);
2939
+ state.setToolResult({
2940
+ content: [{
2941
+ type: "text",
2942
+ text: `Error: ${message}`
2943
+ }],
2944
+ isError: true
2945
+ });
2946
+ state.setToolResultJson(JSON.stringify({
2947
+ content: [{
2948
+ type: "text",
2949
+ text: `Error: ${message}`
2950
+ }],
2951
+ isError: true
2952
+ }, null, 2));
2953
+ } finally {
2954
+ setIsRunning(false);
2955
+ }
2956
+ }, [onCallTool, state]);
2957
+ const activeShell = getHostShell(state.activeHost);
2958
+ const registeredHosts = getRegisteredHosts();
2959
+ const ShellConversation = activeShell?.Conversation;
2960
+ const hostContext = React.useMemo(() => {
2961
+ const styleVars = activeShell?.styleVariables;
2962
+ const userAgent = activeShell?.userAgent;
2963
+ const ctx = { ...state.hostContext };
2964
+ if (styleVars) ctx.styles = { variables: styleVars };
2965
+ if (userAgent) ctx.userAgent = userAgent;
2966
+ return ctx;
2967
+ }, [state.hostContext, activeShell]);
2968
+ React.useEffect(() => {
2969
+ const vars = activeShell?.styleVariables;
2970
+ if (!vars) return;
2971
+ const root = document.documentElement;
2972
+ for (const [key, value] of Object.entries(vars)) if (value) root.style.setProperty(key, value);
2973
+ }, [activeShell]);
2974
+ const prevPageStyleKeysRef = React.useRef([]);
2975
+ React.useEffect(() => {
2976
+ const root = document.documentElement;
2977
+ for (const key of prevPageStyleKeysRef.current) root.style.removeProperty(key);
2978
+ const pageStyles = activeShell?.pageStyles;
2979
+ if (pageStyles) {
2980
+ const keys = [];
2981
+ for (const [key, value] of Object.entries(pageStyles)) {
2982
+ root.style.setProperty(key, value);
2983
+ keys.push(key);
2984
+ }
2985
+ prevPageStyleKeysRef.current = keys;
2986
+ } else prevPageStyleKeysRef.current = [];
2987
+ }, [activeShell]);
2988
+ const handleCallTool = React.useCallback((params) => {
2989
+ if (onCallTool) return onCallTool(params);
2990
+ const mock = state.selectedSim?.serverTools?.[params.name];
2991
+ if (mock) {
2992
+ const result = resolveServerToolResult(mock, params.arguments);
2993
+ if (result) return result;
2994
+ }
2995
+ return { content: [{
2996
+ type: "text",
2997
+ text: `[Simulator] Tool "${params.name}" called — no serverTools mock found in simulation "${state.selectedSimulationName}".`
2998
+ }] };
2999
+ }, [
3000
+ onCallTool,
3001
+ state.selectedSim,
3002
+ state.selectedSimulationName
3003
+ ]);
3004
+ const prodToolsUserMessage = prodTools && state.selectedSim ? `Call my ${state.selectedSim.tool.title || state.selectedSim.tool.name} tool` : void 0;
3005
+ const prodResourcesPath = React.useMemo(() => {
3006
+ if (!prodResources || !state.selectedSim?.resource) return void 0;
3007
+ const name = state.selectedSim.resource.name;
3008
+ return `/dist/${name}/${name}.html`;
3009
+ }, [prodResources, state.selectedSim?.resource]);
3010
+ const [prodResourcesReady, setProdResourcesReady] = React.useState(false);
3011
+ const [prodResourcesGeneration, setProdResourcesGeneration] = React.useState(0);
3012
+ const prodResourcesWasReady = React.useRef(false);
3013
+ React.useEffect(() => {
3014
+ if (!prodResourcesPath) {
3015
+ setProdResourcesReady(false);
3016
+ prodResourcesWasReady.current = false;
3017
+ return;
3018
+ }
3019
+ let cancelled = false;
3020
+ let timer;
3021
+ const check = async () => {
3022
+ let ok = false;
3023
+ try {
3024
+ ok = (await fetch(prodResourcesPath, { method: "HEAD" })).ok;
3025
+ } catch {}
3026
+ if (cancelled) return;
3027
+ if (ok) {
3028
+ if (!prodResourcesWasReady.current) setProdResourcesGeneration((g) => g + 1);
3029
+ prodResourcesWasReady.current = true;
3030
+ setProdResourcesReady(true);
3031
+ } else {
3032
+ prodResourcesWasReady.current = false;
3033
+ setProdResourcesReady(false);
3034
+ }
3035
+ timer = setTimeout(check, 1e3);
3036
+ };
3037
+ check();
3038
+ return () => {
3039
+ cancelled = true;
3040
+ clearTimeout(timer);
3041
+ };
3042
+ }, [prodResourcesPath]);
3043
+ const effectiveResourceUrl = (prodResourcesPath && prodResourcesReady ? prodResourcesPath : void 0) ?? state.resourceUrl;
3044
+ const prodResourcesLoading = !!prodResourcesPath && !prodResourcesReady;
3045
+ const showEmptyState = prodTools && !hasRun;
3046
+ let content;
3047
+ const iframeBg = "var(--sim-bg-conversation, var(--color-background-primary, transparent))";
3048
+ if (showEmptyState) content = /* @__PURE__ */ jsx("div", {
3049
+ className: "h-full w-full flex items-center justify-center",
3050
+ style: { background: iframeBg },
3051
+ children: /* @__PURE__ */ jsxs("span", {
3052
+ className: "text-sm",
3053
+ style: { color: "var(--color-text-secondary)" },
3054
+ children: [
3055
+ "Press ",
3056
+ /* @__PURE__ */ jsx("strong", { children: "Run" }),
3057
+ " to call the tool"
3058
+ ]
3059
+ })
3060
+ });
3061
+ else if (prodResourcesLoading) content = /* @__PURE__ */ jsx("div", {
3062
+ className: "h-full w-full flex items-center justify-center",
3063
+ style: { background: iframeBg },
3064
+ children: /* @__PURE__ */ jsx("span", {
3065
+ className: "text-sm",
3066
+ style: { color: "var(--color-text-secondary)" },
3067
+ children: "Building…"
3068
+ })
3069
+ });
3070
+ else if (effectiveResourceUrl) content = /* @__PURE__ */ jsx("div", {
3071
+ className: "h-full w-full",
3072
+ style: { background: iframeBg },
3073
+ children: /* @__PURE__ */ jsx(IframeResource, {
3074
+ src: effectiveResourceUrl,
3075
+ hostContext,
3076
+ toolInput: state.toolInput,
3077
+ toolResult: state.effectiveToolResult,
3078
+ hostOptions: {
3079
+ hostInfo: activeShell?.hostInfo,
3080
+ hostCapabilities: activeShell?.hostCapabilities,
3081
+ onDisplayModeChange: state.handleDisplayModeChange,
3082
+ onUpdateModelContext: state.handleUpdateModelContext,
3083
+ onCallTool: handleCallTool
3084
+ },
3085
+ permissions: state.permissions,
3086
+ prefersBorder: state.prefersBorder,
3087
+ onDisplayModeReady: state.handleDisplayModeReady,
3088
+ debugInjectState: state.modelContext,
3089
+ injectOpenAIRuntime: state.activeHost === "chatgpt",
3090
+ sandboxUrl,
3091
+ className: "h-full w-full"
3092
+ }, `${state.activeHost}-${state.selectedSimulationName}-${prodResources}-${prodResourcesGeneration}`)
3093
+ });
3094
+ else if (!prodResources && state.resourceScript) content = /* @__PURE__ */ jsx("div", {
3095
+ className: "h-full w-full",
3096
+ style: { background: iframeBg },
3097
+ children: /* @__PURE__ */ jsx(IframeResource, {
3098
+ scriptSrc: state.resourceScript,
3099
+ hostContext,
3100
+ toolInput: state.toolInput,
3101
+ toolResult: state.effectiveToolResult,
3102
+ csp: state.csp,
3103
+ hostOptions: {
3104
+ hostInfo: activeShell?.hostInfo,
3105
+ hostCapabilities: activeShell?.hostCapabilities,
3106
+ onDisplayModeChange: state.handleDisplayModeChange,
3107
+ onUpdateModelContext: state.handleUpdateModelContext,
3108
+ onCallTool: handleCallTool
3109
+ },
3110
+ permissions: state.permissions,
3111
+ prefersBorder: state.prefersBorder,
3112
+ onDisplayModeReady: state.handleDisplayModeReady,
3113
+ debugInjectState: state.modelContext,
3114
+ injectOpenAIRuntime: state.activeHost === "chatgpt",
3115
+ sandboxUrl,
3116
+ className: "h-full w-full"
3117
+ }, `${state.activeHost}-${state.selectedSimulationName}`)
3118
+ });
3119
+ else content = children;
3120
+ const applyTheme = activeShell?.applyTheme;
3121
+ return /* @__PURE__ */ jsx(ThemeProvider, {
3122
+ theme: state.theme,
3123
+ applyTheme,
3124
+ children: /* @__PURE__ */ jsx(SimpleSidebar, {
3125
+ controls: /* @__PURE__ */ jsxs("div", {
3126
+ className: "space-y-1",
3127
+ children: [
3128
+ !hideSimulatorModes && onCallTool && /* @__PURE__ */ jsx(SidebarCheckbox, {
3129
+ checked: prodTools,
3130
+ onChange: setProdTools,
3131
+ label: "Prod Tools",
3132
+ tooltip: "Use real tool handlers instead of simulations",
3133
+ docsPath: "api-reference/cli/dev#prod-tools-and-prod-resources-flags"
3134
+ }),
3135
+ !hideSimulatorModes && /* @__PURE__ */ jsx(SidebarCheckbox, {
3136
+ checked: prodResources,
3137
+ onChange: setProdResources,
3138
+ label: "Prod Resources",
3139
+ tooltip: "Load resources from dist/ builds instead of HMR",
3140
+ docsPath: "api-reference/cli/dev#prod-tools-and-prod-resources-flags"
3141
+ }),
3142
+ /* @__PURE__ */ jsxs("div", {
3143
+ className: "grid grid-cols-2 gap-2",
3144
+ children: [registeredHosts.length > 1 && /* @__PURE__ */ jsx(SidebarControl, {
3145
+ label: "Host",
3146
+ tooltip: "Host runtime to simulate",
3147
+ docsPath: "api-reference/functions/host-detection",
3148
+ children: /* @__PURE__ */ jsx(SidebarSelect, {
3149
+ value: state.activeHost,
3150
+ onChange: (value) => state.setActiveHost(value),
3151
+ options: registeredHosts.map((h) => ({
3152
+ value: h.id,
3153
+ label: h.label
3154
+ }))
3155
+ })
3156
+ }), /* @__PURE__ */ jsx(SidebarControl, {
3157
+ label: "Width",
3158
+ tooltip: "Chat width",
3159
+ docsPath: "api-reference/simulations/simulator",
3160
+ children: /* @__PURE__ */ jsx(SidebarSelect, {
3161
+ value: state.screenWidth,
3162
+ onChange: (value) => state.setScreenWidth(value),
3163
+ options: [
3164
+ {
3165
+ value: "mobile-s",
3166
+ label: "Mobile S (375px)"
3167
+ },
3168
+ {
3169
+ value: "mobile-l",
3170
+ label: "Mobile L (425px)"
3171
+ },
3172
+ {
3173
+ value: "tablet",
3174
+ label: "Tablet (768px)"
3175
+ },
3176
+ {
3177
+ value: "full",
3178
+ label: "100% (Full)"
3179
+ }
3180
+ ]
3181
+ })
3182
+ })]
3183
+ }),
3184
+ prodTools && toolOptions.length > 1 && /* @__PURE__ */ jsx(SidebarControl, {
3185
+ label: "Tool",
3186
+ tooltip: "Tool to call with prod handler",
3187
+ docsPath: "api-reference/cli/dev",
3188
+ children: /* @__PURE__ */ jsx(SidebarSelect, {
3189
+ value: state.selectedSimulationName,
3190
+ onChange: (value) => state.setSelectedSimulationName(value),
3191
+ options: toolOptions
3192
+ })
3193
+ }),
3194
+ !prodTools && state.simulationNames.length > 1 && /* @__PURE__ */ jsx(SidebarControl, {
3195
+ label: "Simulation",
3196
+ tooltip: "Test fixture to render",
3197
+ docsPath: "api-reference/simulations/simulation",
3198
+ children: /* @__PURE__ */ jsx(SidebarSelect, {
3199
+ value: state.selectedSimulationName,
3200
+ onChange: (value) => state.setSelectedSimulationName(value),
3201
+ options: state.simulationNames.map((name) => {
3202
+ const sim = simulations[name];
3203
+ const resourceTitle = sim.resource ? sim.resource.title || sim.resource.name : void 0;
3204
+ const toolTitle = sim.tool.title || sim.tool.name;
3205
+ return {
3206
+ value: name,
3207
+ label: resourceTitle ? `${resourceTitle}: ${toolTitle}` : toolTitle
3208
+ };
3209
+ })
3210
+ })
3211
+ }),
3212
+ /* @__PURE__ */ jsx(SidebarCollapsibleControl, {
3213
+ label: "Host Context",
3214
+ defaultCollapsed: false,
3215
+ tooltip: "Host-provided environment",
3216
+ docsPath: "api-reference/hooks/use-host-context",
3217
+ children: /* @__PURE__ */ jsxs("div", {
3218
+ className: "space-y-1",
3219
+ children: [
3220
+ /* @__PURE__ */ jsxs("div", {
3221
+ className: "grid grid-cols-[2fr_1fr] gap-2",
3222
+ children: [/* @__PURE__ */ jsx(SidebarControl, {
3223
+ label: "Theme",
3224
+ tooltip: "Host color theme",
3225
+ docsPath: "api-reference/hooks/use-theme",
3226
+ children: /* @__PURE__ */ jsx(SidebarToggle, {
3227
+ value: state.theme,
3228
+ onChange: (value) => state.setTheme(value),
3229
+ options: [{
3230
+ value: "light",
3231
+ label: "Light"
3232
+ }, {
3233
+ value: "dark",
3234
+ label: "Dark"
3235
+ }]
3236
+ })
3237
+ }), /* @__PURE__ */ jsx(SidebarControl, {
3238
+ label: "Locale",
3239
+ tooltip: "BCP 47 language tag",
3240
+ docsPath: "api-reference/hooks/use-locale",
3241
+ children: /* @__PURE__ */ jsx(SidebarInput, {
3242
+ applyOnBlur: true,
3243
+ value: state.locale,
3244
+ onChange: (value) => state.setLocale(value),
3245
+ placeholder: "en-US"
3246
+ })
3247
+ })]
3248
+ }),
3249
+ /* @__PURE__ */ jsx(SidebarControl, {
3250
+ label: "Display Mode",
3251
+ tooltip: "Host resource rendering paradigm",
3252
+ docsPath: "api-reference/hooks/use-display-mode",
3253
+ children: /* @__PURE__ */ jsx(SidebarToggle, {
3254
+ value: state.displayMode,
3255
+ onChange: (value) => state.setDisplayMode(value),
3256
+ options: [
3257
+ {
3258
+ value: "inline",
3259
+ label: "Inline"
3260
+ },
3261
+ {
3262
+ value: "pip",
3263
+ label: "PiP"
3264
+ },
3265
+ {
3266
+ value: "fullscreen",
3267
+ label: "Full"
3268
+ }
3269
+ ]
3270
+ })
3271
+ }),
3272
+ /* @__PURE__ */ jsxs("div", {
3273
+ className: "grid grid-cols-7 gap-2",
3274
+ children: [/* @__PURE__ */ jsx("div", {
3275
+ className: "col-span-3",
3276
+ children: /* @__PURE__ */ jsx(SidebarControl, {
3277
+ label: "Platform",
3278
+ tooltip: "End user device platform",
3279
+ docsPath: "api-reference/hooks/use-platform",
3280
+ children: /* @__PURE__ */ jsx(SidebarSelect, {
3281
+ value: state.platform,
3282
+ onChange: (value) => {
3283
+ const p = value;
3284
+ state.setPlatform(p);
3285
+ if (p === "mobile") {
3286
+ state.setHover(false);
3287
+ state.setTouch(true);
3288
+ } else if (p === "desktop") {
3289
+ state.setHover(true);
3290
+ state.setTouch(false);
3291
+ } else {
3292
+ state.setHover(true);
3293
+ state.setTouch(false);
3294
+ }
3295
+ },
3296
+ options: [
3297
+ {
3298
+ value: "mobile",
3299
+ label: "Mobile"
3300
+ },
3301
+ {
3302
+ value: "desktop",
3303
+ label: "Desktop"
3304
+ },
3305
+ {
3306
+ value: "web",
3307
+ label: "Web"
3308
+ }
3309
+ ]
3310
+ })
3311
+ })
3312
+ }), /* @__PURE__ */ jsx("div", {
3313
+ className: "col-span-4",
3314
+ children: /* @__PURE__ */ jsx(SidebarControl, {
3315
+ label: "Capabilities",
3316
+ tooltip: "End user device capabilities",
3317
+ docsPath: "api-reference/hooks/use-device-capabilities",
3318
+ children: /* @__PURE__ */ jsxs("div", {
3319
+ className: "flex gap-2",
3320
+ children: [/* @__PURE__ */ jsx(SidebarCheckbox, {
3321
+ checked: state.hover,
3322
+ onChange: state.setHover,
3323
+ label: "Hover"
3324
+ }), /* @__PURE__ */ jsx(SidebarCheckbox, {
3325
+ checked: state.touch,
3326
+ onChange: state.setTouch,
3327
+ label: "Touch"
3328
+ })]
3329
+ })
3330
+ })
3331
+ })]
3332
+ }),
3333
+ /* @__PURE__ */ jsx(SidebarControl, {
3334
+ label: "Time Zone",
3335
+ tooltip: "End user IANA time zone",
3336
+ docsPath: "api-reference/hooks/use-time-zone",
3337
+ children: /* @__PURE__ */ jsx(SidebarInput, {
3338
+ applyOnBlur: true,
3339
+ value: state.timeZone,
3340
+ onChange: (value) => state.setTimeZone(value),
3341
+ placeholder: "e.g. America/New_York"
3342
+ })
3343
+ }),
3344
+ /* @__PURE__ */ jsx(SidebarControl, {
3345
+ label: "Container Dimensions",
3346
+ tooltip: "Host-enforced size constraints (px)",
3347
+ docsPath: "api-reference/hooks/use-viewport",
3348
+ children: /* @__PURE__ */ jsxs("div", {
3349
+ className: "grid grid-cols-4 gap-1",
3350
+ children: [
3351
+ /* @__PURE__ */ jsx(SidebarControl, {
3352
+ label: "Height",
3353
+ children: /* @__PURE__ */ jsx(SidebarInput, {
3354
+ type: "number",
3355
+ applyOnBlur: true,
3356
+ placeholder: "-",
3357
+ value: state.containerHeight != null ? String(state.containerHeight) : "",
3358
+ onChange: (value) => state.setContainerHeight(value ? Number(value) : void 0)
3359
+ })
3360
+ }),
3361
+ /* @__PURE__ */ jsx(SidebarControl, {
3362
+ label: "Width",
3363
+ children: /* @__PURE__ */ jsx(SidebarInput, {
3364
+ type: "number",
3365
+ applyOnBlur: true,
3366
+ placeholder: "-",
3367
+ value: state.containerWidth != null ? String(state.containerWidth) : "",
3368
+ onChange: (value) => state.setContainerWidth(value ? Number(value) : void 0)
3369
+ })
3370
+ }),
3371
+ /* @__PURE__ */ jsx(SidebarControl, {
3372
+ label: "Max H",
3373
+ children: /* @__PURE__ */ jsx(SidebarInput, {
3374
+ type: "number",
3375
+ applyOnBlur: true,
3376
+ placeholder: "-",
3377
+ value: state.containerMaxHeight != null ? String(state.containerMaxHeight) : "",
3378
+ onChange: (value) => state.setContainerMaxHeight(value ? Number(value) : void 0)
3379
+ })
3380
+ }),
3381
+ /* @__PURE__ */ jsx(SidebarControl, {
3382
+ label: "Max W",
3383
+ children: /* @__PURE__ */ jsx(SidebarInput, {
3384
+ type: "number",
3385
+ applyOnBlur: true,
3386
+ placeholder: state.measuredContentWidth != null ? String(state.measuredContentWidth) : "-",
3387
+ value: state.containerMaxWidth != null ? String(state.containerMaxWidth) : "",
3388
+ onChange: (value) => state.setContainerMaxWidth(value ? Number(value) : void 0)
3389
+ })
3390
+ })
3391
+ ]
3392
+ })
3393
+ }),
3394
+ /* @__PURE__ */ jsx(SidebarControl, {
3395
+ label: "Safe Area Insets",
3396
+ tooltip: "Device safe area padding (px)",
3397
+ docsPath: "api-reference/hooks/use-safe-area",
3398
+ children: /* @__PURE__ */ jsxs("div", {
3399
+ className: "grid grid-cols-4 gap-1",
3400
+ children: [
3401
+ /* @__PURE__ */ jsxs("div", {
3402
+ className: "flex items-center gap-0.5",
3403
+ children: [/* @__PURE__ */ jsx("span", {
3404
+ className: "text-[10px]",
3405
+ style: { color: "var(--color-text-secondary)" },
3406
+ children: "↑"
3407
+ }), /* @__PURE__ */ jsx(SidebarInput, {
3408
+ type: "number",
3409
+ applyOnBlur: true,
3410
+ placeholder: "-",
3411
+ value: state.safeAreaInsets.top ? String(state.safeAreaInsets.top) : "",
3412
+ onChange: (value) => state.setSafeAreaInsets((prev) => ({
3413
+ ...prev,
3414
+ top: Number(value) || 0
3415
+ }))
3416
+ })]
3417
+ }),
3418
+ /* @__PURE__ */ jsxs("div", {
3419
+ className: "flex items-center gap-0.5",
3420
+ children: [/* @__PURE__ */ jsx("span", {
3421
+ className: "text-[10px]",
3422
+ style: { color: "var(--color-text-secondary)" },
3423
+ children: "↓"
3424
+ }), /* @__PURE__ */ jsx(SidebarInput, {
3425
+ type: "number",
3426
+ applyOnBlur: true,
3427
+ placeholder: "-",
3428
+ value: state.safeAreaInsets.bottom ? String(state.safeAreaInsets.bottom) : "",
3429
+ onChange: (value) => state.setSafeAreaInsets((prev) => ({
3430
+ ...prev,
3431
+ bottom: Number(value) || 0
3432
+ }))
3433
+ })]
3434
+ }),
3435
+ /* @__PURE__ */ jsxs("div", {
3436
+ className: "flex items-center gap-0.5",
3437
+ children: [/* @__PURE__ */ jsx("span", {
3438
+ className: "text-[10px]",
3439
+ style: { color: "var(--color-text-secondary)" },
3440
+ children: "←"
3441
+ }), /* @__PURE__ */ jsx(SidebarInput, {
3442
+ type: "number",
3443
+ applyOnBlur: true,
3444
+ placeholder: "-",
3445
+ value: state.safeAreaInsets.left ? String(state.safeAreaInsets.left) : "",
3446
+ onChange: (value) => state.setSafeAreaInsets((prev) => ({
3447
+ ...prev,
3448
+ left: Number(value) || 0
3449
+ }))
3450
+ })]
3451
+ }),
3452
+ /* @__PURE__ */ jsxs("div", {
3453
+ className: "flex items-center gap-0.5",
3454
+ children: [/* @__PURE__ */ jsx("span", {
3455
+ className: "text-[10px]",
3456
+ style: { color: "var(--color-text-secondary)" },
3457
+ children: "→"
3458
+ }), /* @__PURE__ */ jsx(SidebarInput, {
3459
+ type: "number",
3460
+ applyOnBlur: true,
3461
+ placeholder: "-",
3462
+ value: state.safeAreaInsets.right ? String(state.safeAreaInsets.right) : "",
3463
+ onChange: (value) => state.setSafeAreaInsets((prev) => ({
3464
+ ...prev,
3465
+ right: Number(value) || 0
3466
+ }))
3467
+ })]
3468
+ })
3469
+ ]
3470
+ })
3471
+ })
3472
+ ]
3473
+ })
3474
+ }),
3475
+ /* @__PURE__ */ jsx(SidebarCollapsibleControl, {
3476
+ label: "App Context",
3477
+ defaultCollapsed: true,
3478
+ tooltip: "App-provided context shared with the model",
3479
+ docsPath: "api-reference/hooks/use-app-state",
3480
+ children: /* @__PURE__ */ jsx(SidebarTextarea, {
3481
+ value: state.modelContextJson,
3482
+ onChange: (json) => state.validateJSON(json, state.setModelContextJson, state.setModelContextError),
3483
+ onFocus: () => state.setEditingField("modelContext"),
3484
+ onBlur: () => state.commitJSON(state.modelContextJson, state.setModelContextError, (parsed) => {
3485
+ state.setModelContext(parsed);
3486
+ }),
3487
+ error: state.modelContextError,
3488
+ maxRows: 8
3489
+ })
3490
+ }),
3491
+ /* @__PURE__ */ jsx(SidebarCollapsibleControl, {
3492
+ label: "Tool Input (JSON)",
3493
+ defaultCollapsed: !prodTools,
3494
+ tooltip: "Arguments passed to the tool",
3495
+ docsPath: "api-reference/hooks/use-tool-data",
3496
+ children: /* @__PURE__ */ jsx(SidebarTextarea, {
3497
+ value: state.toolInputJson,
3498
+ onChange: (json) => state.validateJSON(json, state.setToolInputJson, state.setToolInputError),
3499
+ onFocus: () => state.setEditingField("toolInput"),
3500
+ onBlur: () => state.commitJSON(state.toolInputJson, state.setToolInputError, (parsed) => state.setToolInput(parsed ?? {})),
3501
+ error: state.toolInputError,
3502
+ maxRows: 8
3503
+ })
3504
+ }, `tool-input-${prodTools}`),
3505
+ !prodTools && /* @__PURE__ */ jsx(SidebarCollapsibleControl, {
3506
+ label: "Tool Result (JSON)",
3507
+ defaultCollapsed: false,
3508
+ tooltip: "Structured content returned by the tool",
3509
+ docsPath: "api-reference/hooks/use-tool-data",
3510
+ children: /* @__PURE__ */ jsx(SidebarTextarea, {
3511
+ value: state.toolResultJson,
3512
+ onChange: (json) => state.validateJSON(json, state.setToolResultJson, state.setToolResultError),
3513
+ onFocus: () => state.setEditingField("toolResult"),
3514
+ onBlur: () => state.commitJSON(state.toolResultJson, state.setToolResultError, (parsed) => {
3515
+ if (parsed === null) state.setToolResult(void 0);
3516
+ else {
3517
+ const result = parsed;
3518
+ if ("content" in result || "structuredContent" in result) state.setToolResult(result);
3519
+ else state.setToolResult({
3520
+ content: [],
3521
+ structuredContent: result
3522
+ });
3523
+ }
3524
+ }),
3525
+ error: state.toolResultError,
3526
+ maxRows: 8
3527
+ })
3528
+ })
3529
+ ]
3530
+ }),
3531
+ children: ShellConversation ? /* @__PURE__ */ jsx(ShellConversation, {
3532
+ screenWidth: state.screenWidth,
3533
+ displayMode: state.displayMode,
3534
+ platform: state.platform,
3535
+ onRequestDisplayMode: state.handleDisplayModeChange,
3536
+ appName,
3537
+ appIcon,
3538
+ userMessage: prodToolsUserMessage ?? state.selectedSim?.userMessage,
3539
+ onContentWidthChange: state.handleContentWidthChange,
3540
+ headerAction: prodTools && onCallTool ? /* @__PURE__ */ jsxs("button", {
3541
+ type: "button",
3542
+ onClick: handleRun,
3543
+ disabled: isRunning,
3544
+ className: "rounded-full px-3 py-1 text-sm font-medium transition-opacity disabled:opacity-40 flex items-center gap-1.5 cursor-pointer",
3545
+ style: {
3546
+ backgroundColor: "var(--color-text-primary)",
3547
+ color: "var(--color-background-primary)"
3548
+ },
3549
+ children: [showCheck ? /* @__PURE__ */ jsx("svg", {
3550
+ width: "12",
3551
+ height: "12",
3552
+ viewBox: "0 0 12 12",
3553
+ fill: "none",
3554
+ stroke: "currentColor",
3555
+ strokeWidth: "2",
3556
+ strokeLinecap: "round",
3557
+ strokeLinejoin: "round",
3558
+ children: /* @__PURE__ */ jsx("path", { d: "M2 6L5 9L10 3" })
3559
+ }) : /* @__PURE__ */ jsx("svg", {
3560
+ width: "10",
3561
+ height: "12",
3562
+ viewBox: "0 0 10 12",
3563
+ fill: "currentColor",
3564
+ children: /* @__PURE__ */ jsx("path", { d: "M0 0L10 6L0 12V0Z" })
3565
+ }), "Run"]
3566
+ }) : void 0,
3567
+ children: content
3568
+ }) : content
3569
+ })
3570
+ });
3571
+ }
3572
+ //#endregion
3573
+ export { SCREEN_WIDTHS as _, SidebarControl as a, registerHostShell as b, SidebarTextarea as c, ThemeProvider as d, useThemeContext as f, McpAppHost as g, extractResourceCSP as h, SidebarCollapsibleControl as i, SidebarToggle as l, IframeResource as m, resolveServerToolResult as n, SidebarInput as o, useSimulatorState as p, SidebarCheckbox as r, SidebarSelect as s, Simulator as t, SimpleSidebar as u, getHostShell as v, DEFAULT_STYLE_VARIABLES as x, getRegisteredHosts as y };
3574
+
3575
+ //# sourceMappingURL=simulator-CmgNnWBO.js.map