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