### Clone and Install Sunpeak AI Project Source: https://github.com/sunpeak-ai/sunpeak/blob/main/DEVELOPMENT.md This snippet outlines the initial steps to get the Sunpeak AI project running locally. It requires Node.js (version 20+) and pnpm (version 10+). The process involves cloning the repository, installing dependencies, and starting the development server. ```bash git clone https://github.com/Sunpeak-AI/sunpeak.git cd sunpeak && pnpm install pnpm dev ``` -------------------------------- ### Start Development Server Source: https://github.com/sunpeak-ai/sunpeak/blob/main/template/README.md Starts the development server for the sunpeak-app, allowing for live preview and iteration during UI development. ```bash pnpm dev ``` -------------------------------- ### Create and Run New Sunpeak Project Source: https://context7.com/sunpeak-ai/sunpeak/llms.txt Scaffolds a new Sunpeak project using the CLI, installs dependencies, and starts the development server. Supports interactive mode or direct project name specification. ```bash pnpm dlx sunpeak new my-app cd my-app pnpm install && pnpm dev ``` ```bash # Interactive mode - prompts for project name pnpm dlx sunpeak new # Specify project name directly pnpm dlx sunpeak new travel-app # Creates directory structure: # my-app/ # ├── src/ # │ ├── components/ # Pre-built UI components # │ ├── simulations/ # Test data for simulator # │ ├── styles/ # Global styles # ├── dev/ # Local development entry # ├── mcp/ # MCP server configuration # ├── package.json # Dependencies with sunpeak ``` -------------------------------- ### Start MCP Server for ChatGPT Testing Source: https://github.com/sunpeak-ai/sunpeak/blob/main/template/README.md Initiates the MCP (Meta Conversations Protocol) server, which is required for testing the app directly within ChatGPT. This command must be run after building the app. ```bash pnpm mcp ``` -------------------------------- ### Example Sunpeak UI Component using React Source: https://github.com/sunpeak-ai/sunpeak/blob/main/README.md Demonstrates a basic UI component using React and Sunpeak's `Card` component. This example shows how to import and use pre-built UI components for creating interactive elements within a ChatGPT App. It includes setting up image, header, metadata, and button configurations. ```tsx import "./styles/globals.css"; import { Card } from "./components/card"; export default function App() { return ( {} }} button2={{ children: "Learn More", onClick: () => {} }} > Scenic lake perfect for kayaking, paddleboarding, and trails. ); } ``` -------------------------------- ### Create and Validate a New Sunpeak App Locally Source: https://github.com/sunpeak-ai/sunpeak/blob/main/DEVELOPMENT.md This sequence of commands demonstrates how to create a new application using the Sunpeak CLI within a temporary directory and then run validation checks on it. This is part of the deployment testing process. ```bash rm -rf ../tmp && mkdir ../tmp && cd ../tmp pnpm dlx sunpeak new my-app && cd my-app pnpm validate ``` -------------------------------- ### Build Production App Source: https://github.com/sunpeak-ai/sunpeak/blob/main/template/README.md Compiles the sunpeak-app into optimized production-ready builds located in the 'dist/' directory. This includes the necessary JavaScript for the ChatGPT iframe component. ```bash pnpm build ``` -------------------------------- ### Run All Checks and Tests Source: https://github.com/sunpeak-ai/sunpeak/blob/main/template/README.md Executes a comprehensive suite of checks including linting, typechecking, unit tests, and build verification to ensure code quality and correctness. ```bash pnpm validate ``` -------------------------------- ### Create Tunnel for ChatGPT Testing Source: https://github.com/sunpeak-ai/sunpeak/blob/main/template/README.md Sets up an ngrok tunnel to expose the local MCP server to the internet, enabling connection from ChatGPT for UI testing in developer mode. ```bash ngrok http 6766 ``` -------------------------------- ### MCP Server Setup (TypeScript) Source: https://context7.com/sunpeak-ai/sunpeak/llms.txt Sets up an MCP (Message Communication Protocol) server using `runMCPServer` from 'sunpeak/mcp'. This server can handle SSE streams and POST messages for communication. It requires configuration such as name, version, distribution path, tool details, dummy data, and port. The provider defaults to ChatGPT. ```typescript import { runMCPServer, MCPProvider } from 'sunpeak/mcp'; import path from 'path'; runMCPServer({ name: 'my-travel-app', version: '0.1.0', distPath: path.resolve(__dirname, '../dist/chatgpt/index.js'), toolName: 'show-travel-app', toolDescription: 'Display travel recommendations', dummyData: { places: [ { name: 'Lady Bird Lake', rating: 4.5 }, { name: 'Zilker Park', rating: 4.8 } ] }, port: 6766, provider: MCPProvider.ChatGPT // Optional, defaults to ChatGPT }); // Server endpoints: // SSE stream: GET http://localhost:6766/mcp // Message post: POST http://localhost:6766/mcp/messages?sessionId=... ``` -------------------------------- ### Provider System Utilities (TypeScript) Source: https://context7.com/sunpeak-ai/sunpeak/llms.txt Provides several utility functions for interacting with the AI provider system: `getProvider` to get the current provider instance, `isProviderAvailable` to check if any provider is active, `getGlobal` and `subscribeToGlobal` for accessing and subscribing to global widget states, `getAPI` to retrieve API methods, and `resetProviderCache` for cache management, particularly useful in testing scenarios. ```typescript import { getProvider, isProviderAvailable, getGlobal, subscribeToGlobal, getAPI, resetProviderCache } from 'sunpeak'; // Check if any provider is available if (isProviderAvailable()) { const provider = getProvider(); // Returns OpenAI provider or null console.log('Provider ID:', provider?.id); } // Get global values directly const theme = getGlobal('theme'); const displayMode = getGlobal('displayMode'); // Subscribe to changes const unsubscribe = subscribeToGlobal('theme', () => { console.log('Theme changed to:', getGlobal('theme')); }); // Get API methods const api = getAPI(); if (api?.callTool) { await api.callTool('my-tool', { param: 'value' }); } // Reset cache (useful for testing) resetProviderCache(); ``` -------------------------------- ### Get Current Theme with useTheme Hook Source: https://context7.com/sunpeak-ai/sunpeak/llms.txt The `useTheme` hook from Sunpeak provides the current theme setting ('light' or 'dark') for the widget, allowing components to adapt their styling accordingly. ```tsx import { useTheme } from 'sunpeak'; function ThemedComponent() { const theme = useTheme(); // Returns 'light' | 'dark' | null return (

Current theme: {theme}

); } ``` -------------------------------- ### Get User Agent Information with useUserAgent Hook (React) Source: https://context7.com/sunpeak-ai/sunpeak/llms.txt The `useUserAgent` hook provides detailed information about the user's device and browser capabilities, including device type ('mobile', 'tablet', 'desktop', 'unknown'), hover support, and touch support. This data can be used to tailor the user experience based on the device. ```tsx import { useUserAgent } from 'sunpeak'; function DeviceAwareComponent() { const userAgent = useUserAgent(); const deviceType = userAgent?.device.type; // 'mobile' | 'tablet' | 'desktop' | 'unknown' const canHover = userAgent?.capabilities.hover; const hasTouch = userAgent?.capabilities.touch; return (

Device: {deviceType}

Hover: {canHover ? 'Yes' : 'No'}

Touch: {hasTouch ? 'Yes' : 'No'}

{canHover &&
Hover me
} {hasTouch && }
); } ``` -------------------------------- ### Get Locale Information with useLocale Hook (React) Source: https://context7.com/sunpeak-ai/sunpeak/llms.txt The `useLocale` hook retrieves the current locale string of the user, typically in a format like 'en-US'. This hook is essential for internationalization (i18n) and localization (l10n), allowing you to format dates, numbers, and text according to the user's language and region. ```tsx import { useLocale } from 'sunpeak'; function LocalizedComponent() { const locale = useLocale(); // Returns string like 'en-US' const formatDate = (date: Date) => { return new Intl.DateTimeFormat(locale || 'en-US').format(date); }; return (

Locale: {locale}

Today: {formatDate(new Date())}

); } ``` -------------------------------- ### Create a New Sunpeak Project using pnpm Source: https://github.com/sunpeak-ai/sunpeak/blob/main/README.md Initiates a new Sunpeak project using the pnpm package manager. This command sets up the project structure and initial configuration for developing ChatGPT Apps. Requires Node.js (20+) and pnpm (10+). ```bash pnpm dlx sunpeak new ``` -------------------------------- ### Mock OpenAI Initialization (TypeScript) Source: https://context7.com/sunpeak-ai/sunpeak/llms.txt Initializes a mock OpenAI environment using `initMockOpenAI` from 'sunpeak'. This is useful for testing and simulation purposes. It allows setting custom defaults for theme, display mode, tool output, and widget state. The mock object returned also provides methods to manually change these settings. ```typescript import { initMockOpenAI } from 'sunpeak'; // Initialize with custom defaults const mock = initMockOpenAI({ theme: 'dark', displayMode: 'inline', toolOutput: { results: ['Item 1', 'Item 2'] }, widgetState: { currentPage: 1 } }); // Manually set values mock.setTheme('light'); mock.setDisplayMode('fullscreen'); mock.setToolOutput({ newData: true }); // Available in tests and simulator window.openai === mock; // true ``` -------------------------------- ### Type Definitions for Sunpeak AI (TypeScript) Source: https://context7.com/sunpeak-ai/sunpeak/llms.txt Provides a comprehensive set of TypeScript type definitions for various aspects of the Sunpeak AI framework. This includes types for Theme, DisplayMode, ViewMode, DeviceType, UserAgent, SafeArea, WidgetGlobals, WidgetAPI, and WidgetProvider, enhancing type safety and developer experience. ```typescript import type { Theme, DisplayMode, ViewMode, DeviceType, UserAgent, SafeArea, SafeAreaInsets, View, UnknownObject, Simulation, WidgetGlobals, WidgetAPI, WidgetProvider } from 'sunpeak'; // Theme type const theme: Theme = 'dark'; // 'light' | 'dark' // Display mode const mode: DisplayMode = 'fullscreen'; // 'pip' | 'inline' | 'fullscreen' // View mode const viewMode: ViewMode = 'modal'; // 'modal' | 'default' // Device type const device: DeviceType = 'mobile'; // 'mobile' | 'tablet' | 'desktop' | 'unknown' // User agent const userAgent: UserAgent = { device: { type: 'desktop' }, capabilities: { hover: true, touch: false } }; // Safe area const safeArea: SafeArea = { insets: { top: 20, bottom: 20, left: 0, right: 0 } }; // Widget globals const globals: WidgetGlobals = { theme: 'dark', userAgent, locale: 'en-US', maxHeight: 600, displayMode: 'inline', safeArea, view: null, toolInput: {}, toolOutput: null, toolResponseMetadata: null, widgetState: null, setWidgetState: async (state) => {} }; ``` -------------------------------- ### Integrate ChatGPT Simulator Component Source: https://context7.com/sunpeak-ai/sunpeak/llms.txt Renders the ChatGPT Simulator component from Sunpeak, which allows for local testing of ChatGPT apps with predefined simulations. It requires React and ReactDOM. ```tsx import { ChatGPTSimulator, type Simulation } from 'sunpeak'; import { StrictMode } from 'react'; import { createRoot } from 'react-dom/client'; import MyApp from './MyApp'; // Define simulations with test data const simulations: Simulation[] = [ { value: 'travel', label: 'Travel App', component: MyApp, appName: 'Travel Guide', appIcon: 'https://example.com/icon.png', userMessage: 'Show me places to visit in Austin', toolOutput: { places: [ { name: 'Lady Bird Lake', rating: 4.5 }, { name: 'Zilker Park', rating: 4.8 } ] }, widgetState: { selectedPlace: null } } ]; createRoot(document.getElementById('root')!).render( ); // Provides sidebar controls for: // - Theme (light/dark) // - Display mode (inline/pip/fullscreen) // - Screen width (mobile/tablet/full) // - Simulation selection ``` -------------------------------- ### Card Component Usage (TypeScript/React) Source: https://context7.com/sunpeak-ai/sunpeak/llms.txt Demonstrates the usage of a `Card` component, likely imported from './components/card'. The component accepts various props to configure its appearance and behavior, including image source, alt text, header, metadata, button configurations, variant, and image dimensions. It's used here to display a list of places. ```tsx import { Card } from './components/card'; function PlacesList() { return (
console.log('Visit clicked') }} button2={{ children: 'Learn More', onClick: () => console.log('Learn more clicked') }} variant="elevated" imageMaxWidth={400} imageMaxHeight={400} > Scenic lake perfect for kayaking, paddleboarding, and trails.
); } ``` -------------------------------- ### Interact with Widget API using useWidgetAPI Hook (React) Source: https://context7.com/sunpeak-ai/sunpeak/llms.txt The `useWidgetAPI` hook provides access to the widget's API, enabling interactions like calling backend tools, sending messages, opening links, and requesting different display modes (fullscreen, modal). Ensure the API object and its methods are checked for existence before calling. ```tsx import { useWidgetAPI } from 'sunpeak'; function InteractiveComponent() { const api = useWidgetAPI(); const callBackendTool = async () => { if (api?.callTool) { const result = await api.callTool('search-places', { query: 'restaurants', location: 'Austin, TX' }); console.log('Tool result:', result); } }; const sendMessage = async () => { if (api?.sendFollowUpMessage) { await api.sendFollowUpMessage({ prompt: 'Show me more details about this place' }); } }; const openLink = () => { if (api?.openExternal) { api.openExternal({ href: 'https://example.com' }); } }; const requestFullscreen = async () => { if (api?.requestDisplayMode) { await api.requestDisplayMode({ mode: 'fullscreen' }); } }; const openModal = async () => { if (api?.requestModal) { await api.requestModal({ mode: 'modal', params: { itemId: '123' } }); } }; return (
); } ``` -------------------------------- ### Handle Safe Area Insets with useSafeArea Hook (React) Source: https://context7.com/sunpeak-ai/sunpeak/llms.txt The `useSafeArea` hook provides information about the device's safe area insets (e.g., for notches or status bars). It returns an object containing `top`, `bottom`, `left`, and `right` inset values in pixels. This hook is crucial for ensuring UI elements are not obscured by device hardware. ```tsx import { useSafeArea } from 'sunpeak'; function SafeAreaComponent() { const safeArea = useSafeArea(); return (

Content with safe area insets

Top: {safeArea?.insets.top}px

Bottom: {safeArea?.insets.bottom}px

); } ``` -------------------------------- ### Access Tool Input with useToolInput Hook Source: https://context7.com/sunpeak-ai/sunpeak/llms.txt The `useToolInput` hook from Sunpeak allows components to access typed input data provided to a tool, enabling dynamic behavior based on received parameters. ```tsx import { useToolInput } from 'sunpeak'; interface SearchInput { query: string; location?: string; radius?: number; } function SearchComponent() { const toolInput = useToolInput(); if (!toolInput) { return
No search parameters provided
; } return (

Searching for: {toolInput.query}

{toolInput.location &&

Near: {toolInput.location}

} {toolInput.radius &&

Within {toolInput.radius} miles

}
); } ``` -------------------------------- ### Control Layout with useDisplayMode Hook Source: https://context7.com/sunpeak-ai/sunpeak/llms.txt The `useDisplayMode` hook from Sunpeak returns the current display mode of the widget ('pip', 'inline', or 'fullscreen'), enabling responsive component behavior. ```tsx import { useDisplayMode } from 'sunpeak'; function ResponsiveComponent() { const displayMode = useDisplayMode(); // 'pip' | 'inline' | 'fullscreen' | null if (displayMode === 'pip') { return ; } if (displayMode === 'fullscreen') { return ; } return ; } ``` -------------------------------- ### Access Global Widget State with useWidgetGlobal Hook Source: https://context7.com/sunpeak-ai/sunpeak/llms.txt The `useWidgetGlobal` hook from Sunpeak allows components to access various global states of the ChatGPT widget, such as theme, display mode, locale, and device information. ```tsx import { useWidgetGlobal } from 'sunpeak'; function MyComponent() { const theme = useWidgetGlobal('theme'); const displayMode = useWidgetGlobal('displayMode'); const locale = useWidgetGlobal('locale'); const maxHeight = useWidgetGlobal('maxHeight'); const userAgent = useWidgetGlobal('userAgent'); const safeArea = useWidgetGlobal('safeArea'); const view = useWidgetGlobal('view'); const toolInput = useWidgetGlobal('toolInput'); const toolOutput = useWidgetGlobal('toolOutput'); return (

Current theme: {theme}

Display mode: {displayMode}

Device type: {userAgent?.device.type}

Safe area top: {safeArea?.insets.top}px

{toolOutput &&
{JSON.stringify(toolOutput, null, 2)}
}
); } ``` -------------------------------- ### Manage Widget State with useWidgetState Hook (React) Source: https://context7.com/sunpeak-ai/sunpeak/llms.txt The `useWidgetState` hook allows you to manage the state of a widget within your application. It takes an initial state object and returns the current state along with a function to update it. This is useful for handling user interactions and maintaining component-specific data. ```tsx import { useWidgetState } from 'sunpeak'; interface AppState { selectedItem: string | null; favorites: string[]; } function StatefulComponent() { const [state, setState] = useWidgetState({ selectedItem: null, favorites: [] }); const addFavorite = (item: string) => { setState(prev => ({ ...prev, favorites: [...prev.favorites, item] })); }; const selectItem = (item: string) => { setState(prev => ({ ...prev, selectedItem: item })); }; return (

Selected: {state?.selectedItem}

Favorites: {state?.favorites.join(', ')}

); } ``` -------------------------------- ### Use Tool Response Metadata Hook (TypeScript/React) Source: https://context7.com/sunpeak-ai/sunpeak/llms.txt The `useToolResponseMetadata` hook allows components to access metadata associated with a tool's response. It takes a generic type argument to define the shape of the expected metadata. If no metadata is available, it returns null. This hook is useful for displaying information like response time, source, or confidence scores. ```tsx import { useToolResponseMetadata } from 'sunpeak'; function MetadataComponent() { const metadata = useToolResponseMetadata<{ responseTime: number; source: string; confidence: number; }>(); if (!metadata) { return
No metadata available
; } return (

Response time: {metadata.responseTime}ms

Source: {metadata.source}

Confidence: {(metadata.confidence * 100).toFixed(1)}%

); } ``` -------------------------------- ### Utility Function - cn (TypeScript) Source: https://context7.com/sunpeak-ai/sunpeak/llms.txt The `cn` utility function, imported from 'sunpeak', is designed for merging class names efficiently. It combines the functionality of `clsx` and `tailwind-merge`, ensuring that Tailwind CSS classes are properly resolved and conflicts are avoided. It accepts multiple string arguments and conditional class names. ```typescript import { cn } from 'sunpeak'; function Component({ className, isActive }: { className?: string; isActive: boolean }) { return (
Content
); } // Combines clsx and tailwind-merge for optimal class merging ``` -------------------------------- ### Determine View Mode with useView Hook (React) Source: https://context7.com/sunpeak-ai/sunpeak/llms.txt The `useView` hook allows you to determine the current view mode of the widget, which can be 'modal' or 'default'. It also provides `params` if the mode is 'modal'. This is useful for conditionally rendering UI based on how the widget is being displayed. ```tsx import { useView } from 'sunpeak'; function ViewModeComponent() { const view = useView(); // { mode: 'modal' | 'default', params?: object } if (view?.mode === 'modal') { return (

Modal View

{JSON.stringify(view.params, null, 2)}
); } return
Default View
; } ``` -------------------------------- ### Determine Maximum Widget Height with useMaxHeight Hook (React) Source: https://context7.com/sunpeak-ai/sunpeak/llms.txt The `useMaxHeight` hook returns the maximum available height for the widget. This is particularly useful for creating scrollable containers or components that need to adapt to the available screen real estate. The returned value is a number representing pixels. ```tsx import { useMaxHeight } from 'sunpeak'; function ScrollableContent() { const maxHeight = useMaxHeight(); // Maximum height available to widget return (

Container max height: {maxHeight}px

Long scrollable content...
); } ``` -------------------------------- ### Detect Mobile Devices with useIsMobile Hook (React) Source: https://context7.com/sunpeak-ai/sunpeak/llms.txt The `useIsMobile` hook determines if the current user is on a mobile device based on the user agent. It returns a boolean value, `true` if the device type is 'mobile', and `false` otherwise. This is useful for implementing responsive design patterns. ```tsx import { useIsMobile } from 'sunpeak'; function ResponsiveLayout() { const isMobile = useIsMobile(); // Based on userAgent.device.type return (
{isMobile ? : }
); } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.