@mcp-b/embedded-agent 0.0.4 → 0.0.6

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.
package/README.md CHANGED
@@ -1,29 +1,330 @@
1
- # react-compiler-components-starter
1
+ # @mcp-b/embedded-agent
2
2
 
3
- A starter for creating a React component library with React Compiler.
3
+ React components for embedding an AI agent UI with MCP (Model Context Protocol) tool support and voice mode.
4
4
 
5
- ## Development
5
+ ## Architecture Overview
6
6
 
7
- - Install dependencies:
7
+ The package follows a **core/widgets** architecture:
8
+
9
+ - **Core** (`src/core/`): Data layer - providers and hooks, no UI
10
+ - **Widgets** (`src/widgets/`): UI layer - independent components that consume core
8
11
 
9
- ```bash
10
- npm install
12
+ ```
13
+ src/
14
+ ├── core/ # DATA LAYER
15
+ │ ├── providers/
16
+ │ │ ├── AgentProvider.tsx # Unified provider (START HERE)
17
+ │ │ └── index.ts
18
+ │ ├── hooks/
19
+ │ │ ├── useAgent.ts # Main facade hook (START HERE)
20
+ │ │ └── index.ts
21
+ │ └── index.ts
22
+
23
+ ├── widgets/ # UI LAYER
24
+ │ ├── pill/ # Compact floating UI
25
+ │ │ └── index.ts # Exports AgentPill, PillContainer, etc.
26
+ │ ├── modal/ # Full chat modal
27
+ │ │ └── index.ts # Exports AssistantModal, Thread, etc.
28
+ │ ├── shared/ # Shared components
29
+ │ │ └── index.ts # Exports ActionList, SummaryBlock, etc.
30
+ │ └── index.ts
31
+
32
+ ├── components/ # IMPLEMENTATION (internal)
33
+ │ ├── pill/ # Pill component implementations
34
+ │ │ ├── AgentPill.tsx # Main pill component
35
+ │ │ ├── PillContainer.tsx # Morphing container
36
+ │ │ ├── PillVoice.tsx # Voice mode UI
37
+ │ │ ├── ActionList.tsx # Action display
38
+ │ │ └── ...
39
+ │ └── ... # Other component implementations
40
+
41
+ ├── hooks/ # INDIVIDUAL HOOKS (internal)
42
+ │ ├── useActions.ts # Derives actions from tool calls
43
+ │ ├── useVoiceActions.ts # Voice mode action tracking
44
+ │ ├── useVoiceSummary.ts # Voice session summary
45
+ │ ├── useVoiceMode.ts # Voice mode state machine
46
+ │ └── ...
47
+
48
+ ├── providers/ # INDIVIDUAL PROVIDERS (internal)
49
+ │ ├── MCPToolsProvider.tsx # MCP tool registry
50
+ │ ├── VoiceModeProvider.tsx # Voice mode context
51
+ │ └── VoiceMCPBridge.tsx # Connects MCP tools to voice
52
+
53
+ ├── services/ # EXTERNAL SERVICES
54
+ │ └── realtime/ # OpenAI Realtime API via WebRTC
55
+ │ ├── openai-realtime-service.ts
56
+ │ ├── webrtc-manager.ts
57
+ │ └── ...
58
+
59
+ ├── lib/ # UTILITIES
60
+ │ ├── constants.ts # Magic numbers live here
61
+ │ ├── utils.ts # cn(), etc.
62
+ │ └── ...
63
+
64
+ └── index.ts # PUBLIC EXPORTS
11
65
  ```
12
66
 
13
- - Run the playground:
67
+ ## Quick Start
14
68
 
15
- ```bash
16
- npm run play
69
+ ### Recommended: AgentProvider + Widget
70
+
71
+ ```tsx
72
+ import { AgentPill, AgentProvider } from '@mcp-b/embedded-agent'
73
+
74
+ function App() {
75
+ return (
76
+ <AgentProvider apiBase="https://your-worker.workers.dev">
77
+ <AgentPill position="bottom-center" showVoiceButton />
78
+ </AgentProvider>
79
+ )
80
+ }
17
81
  ```
18
82
 
19
- - Run the unit tests:
83
+ ### Custom UI with useAgent
20
84
 
21
- ```bash
22
- npm run test
85
+ ```tsx
86
+ import { AgentProvider, useAgent } from '@mcp-b/embedded-agent'
87
+
88
+ function CustomUI() {
89
+ const agent = useAgent()
90
+
91
+ return (
92
+ <div>
93
+ {agent.isRunning && <p>Processing...</p>}
94
+ {agent.activeActions.map((action) => (
95
+ <div key={action.id}>{action.label}</div>
96
+ ))}
97
+ {agent.voice?.isActive && <button onClick={agent.voice.stop}>End Voice</button>}
98
+ </div>
99
+ )
100
+ }
101
+
102
+ function App() {
103
+ return (
104
+ <AgentProvider apiBase="https://...">
105
+ <CustomUI />
106
+ </AgentProvider>
107
+ )
108
+ }
109
+ ```
110
+
111
+ ## Core API
112
+
113
+ ### AgentProvider
114
+
115
+ **File:** `src/core/providers/AgentProvider.tsx`
116
+
117
+ Unified provider that sets up:
118
+
119
+ - MCP tool registry (`MCPToolsProvider`)
120
+ - Voice mode bridge (`VoiceMCPBridge`)
121
+ - Chat runtime (`AssistantRuntimeProvider` from @assistant-ui/react)
122
+
123
+ ```tsx
124
+ interface AgentProviderProps {
125
+ children: ReactNode
126
+ apiBase?: string // Backend URL
127
+ tokenEndpoint?: string // Voice token endpoint (defaults to {apiBase}/api/realtime/session)
128
+ autoConnectLocal?: boolean // Auto-connect to local MCP source (default: true)
129
+ onToolsChange?: (tools: ToolWithSource[]) => void
130
+ onVoiceError?: (error: string) => void
131
+ onVoiceConnect?: () => void
132
+ onVoiceDisconnect?: (duration: number) => void
133
+ }
134
+ ```
135
+
136
+ ### useAgent Hook
137
+
138
+ **File:** `src/core/hooks/useAgent.ts`
139
+
140
+ Main facade hook - combines all agent capabilities into one interface.
141
+
142
+ ```tsx
143
+ interface AgentState {
144
+ // Thread
145
+ messages: ReadonlyArray<ThreadMessage>
146
+ isRunning: boolean
147
+ hasMessages: boolean
148
+
149
+ // Actions (from tool calls)
150
+ actions: Action[] // All text mode actions
151
+ currentAction: Action | null // Currently running
152
+ recentActions: Action[] // Last 3 completed
153
+
154
+ // Voice mode actions
155
+ voiceActions: Action[] // Actions from voice mode
156
+ activeActions: Action[] // Voice or text depending on mode
157
+
158
+ // Summary
159
+ summary: string | null // Latest summary text
160
+ voiceSummary: VoiceSummary | null
161
+
162
+ // Voice controls (null if not configured)
163
+ voice: {
164
+ isActive: boolean
165
+ isConnecting: boolean
166
+ isError: boolean
167
+ isMuted: boolean
168
+ error?: string
169
+ audioLevel?: AudioLevelData
170
+ transcript?: TranscriptData
171
+ start: () => Promise<void>
172
+ stop: () => void
173
+ toggleMute: (muted?: boolean) => void
174
+ sendMessage: (text: string) => void
175
+ } | null
176
+
177
+ // MCP tools (null if not in context)
178
+ tools: {
179
+ list: ToolWithSource[]
180
+ call: (name: string, args: Record<string, unknown>) => Promise<CallToolResult>
181
+ } | null
182
+
183
+ // Derived
184
+ isVoiceActive: boolean
185
+ }
186
+ ```
187
+
188
+ ## Widgets
189
+
190
+ ### AgentPill
191
+
192
+ **File:** `src/components/pill/AgentPill.tsx`
193
+
194
+ Compact, morphing floating UI. Shows actions, voice mode, and composer.
195
+
196
+ ```tsx
197
+ interface AgentPillProps {
198
+ position?: 'bottom-center' | 'bottom-right'
199
+ onOpenHistory?: () => void
200
+ showVoiceButton?: boolean
201
+ autoCollapse?: boolean // Auto-collapse after 30s inactivity
202
+ className?: string
203
+ }
204
+ ```
205
+
206
+ ### AssistantModal
207
+
208
+ **File:** `src/components/assistant-modal.tsx`
209
+
210
+ Traditional chat modal with full message thread.
211
+
212
+ ```tsx
213
+ // No props - uses context from AgentProvider
214
+ <AssistantModal />
23
215
  ```
24
216
 
25
- - Build the library:
217
+ ## Key Implementation Details
218
+
219
+ ### Action Tracking
220
+
221
+ **Files:** `src/hooks/useActions.ts`, `src/hooks/useVoiceActions.ts`
222
+
223
+ Actions are derived from tool calls in assistant messages. The `useActions` hook:
224
+
225
+ 1. Subscribes to thread messages via `useThread`
226
+ 2. Extracts tool calls from assistant messages
227
+ 3. Maps tool calls to Action objects with status (running/success/error)
228
+
229
+ Voice actions work similarly but track tool calls from the realtime voice API.
230
+
231
+ ### Voice Mode
232
+
233
+ **Files:**
234
+
235
+ - `src/hooks/useVoiceMode.ts` - State machine for voice sessions
236
+ - `src/services/realtime/` - OpenAI Realtime API integration
237
+ - `src/providers/VoiceMCPBridge.tsx` - Connects MCP tools to voice mode
238
+
239
+ Voice mode uses WebRTC to connect to OpenAI's Realtime API. The VoiceMCPBridge:
240
+
241
+ 1. Watches MCP tools from MCPToolsProvider
242
+ 2. Converts them to RegisteredTool format
243
+ 3. Provides tool executor that calls through MCP
244
+
245
+ ### MCP Tools
246
+
247
+ **File:** `src/providers/MCPToolsProvider.tsx`
248
+
249
+ Manages MCP tool sources (local tab, remote servers). Key exports:
250
+
251
+ - `useMCPTools()` - Required context hook
252
+ - `useOptionalMCPTools()` - Returns null if not in provider
253
+
254
+ ### Constants
255
+
256
+ **File:** `src/lib/constants.ts`
257
+
258
+ All magic numbers are centralized here:
259
+
260
+ - `VOICE_ACTIONS_RETENTION_MS` (3000ms) - How long voice actions persist
261
+ - `VOICE_SUMMARY_RETENTION_MS` (30000ms) - How long voice summary persists
262
+ - `TOOL_CALL_DISPLAY_DURATION_MS` (2000ms) - Tool status display time
263
+ - etc.
264
+
265
+ ## Legacy API
266
+
267
+ The `EmbeddedAgent` component is preserved for backward compatibility but wraps the new architecture internally.
268
+
269
+ ```tsx
270
+ // Legacy (still works)
271
+ import { EmbeddedAgent } from '@mcp-b/embedded-agent'
272
+
273
+ <EmbeddedAgent
274
+ appId="your-app"
275
+ apiBase="https://..."
276
+ viewMode="pill"
277
+ />
278
+
279
+ // New (recommended)
280
+ import { AgentProvider, AgentPill } from '@mcp-b/embedded-agent'
281
+
282
+ <AgentProvider apiBase="https://...">
283
+ <AgentPill />
284
+ </AgentProvider>
285
+ ```
286
+
287
+ ## Development
26
288
 
27
289
  ```bash
28
- npm run build
290
+ # Build
291
+ pnpm build
292
+
293
+ # Type check
294
+ pnpm check:types
295
+
296
+ # Lint
297
+ pnpm check:lint
298
+
299
+ # Test
300
+ pnpm test
301
+
302
+ # Run playground
303
+ pnpm play
29
304
  ```
305
+
306
+ ## Exports Reference
307
+
308
+ ### From `@mcp-b/embedded-agent`
309
+
310
+ **Core:**
311
+
312
+ - `AgentProvider`, `AgentProviderProps`
313
+ - `useAgent`, `AgentState`, `AgentVoice`, `AgentTools`
314
+ - `useActions`, `useCurrentAction`, `useRecentActions`, `Action`
315
+ - `useVoiceActions`, `useVoiceSummary`, `VoiceSummary`
316
+ - `useMCPTools`, `useOptionalMCPTools`, `MCPToolsContextValue`
317
+
318
+ **Widgets:**
319
+
320
+ - `AgentPill`, `AgentPillProps`, `PillPosition`
321
+ - `AssistantModal`
322
+ - `ActionList`, `SummaryBlock`, `CurrentActivity`
323
+ - `PillContainer`, `PillComposer`, `PillVoice`
324
+ - `LiveWaveform`, `VoiceIndicator`, `ToolStatusBorder`
325
+
326
+ **Legacy:**
327
+
328
+ - `EmbeddedAgent`, `EmbeddedAgentProps`
329
+
330
+ See `src/index.ts` for the complete export list.
@@ -1,4 +1,4 @@
1
- var WebMCP=(function(e,t,n,r,i,a,o,s,c,l,u,d,f,p,m,h,g,_,v,y,b,x,S,C,w,T){var E=Object.create,D=Object.defineProperty,O=Object.getOwnPropertyDescriptor,k=Object.getOwnPropertyNames,A=Object.getPrototypeOf,j=Object.prototype.hasOwnProperty,M=(e,t,n,r)=>{if(t&&typeof t==`object`||typeof t==`function`)for(var i=k(t),a=0,o=i.length,s;a<o;a++)s=i[a],!j.call(e,s)&&s!==n&&D(e,s,{get:(e=>t[e]).bind(null,s),enumerable:!(r=O(t,s))||r.enumerable});return e},N=(e,t,n)=>(n=e==null?{}:E(A(e)),M(t||!e||!e.__esModule?D(n,`default`,{value:e,enumerable:!0}):n,e));s=N(s),l=N(l),m=N(m),h=N(h),g=N(g),b=N(b);function P(...e){return(0,d.twMerge)((0,u.clsx)(e))}typeof window<`u`&&window.__WEBMCP_DEBUG__;function F(e,t,n){typeof window<`u`&&window.__WEBMCP_DEBUG__===!0&&(n===void 0?console.log(`[${e}] ${t}`):console.log(`[${e}] ${t}`,n))}var I=class{audioContext=null;analyser=null;source=null;dataArray=null;animationId=null;async initialize(e){let t=e.getAudioTracks();F(`AudioAnalyzer`,`Initializing with stream`,{streamId:e.id,audioTracks:t.length,trackInfo:t.map(e=>({id:e.id,label:e.label,enabled:e.enabled,muted:e.muted,readyState:e.readyState}))}),this.audioContext=new AudioContext,F(`AudioAnalyzer`,`AudioContext created, initial state: ${this.audioContext.state}`);try{await this.audioContext.resume(),F(`AudioAnalyzer`,`AudioContext after resume: ${this.audioContext.state}`)}catch(e){console.warn(`[AudioAnalyzer] Failed to resume AudioContext:`,e)}this.analyser=this.audioContext.createAnalyser(),this.analyser.fftSize=256,this.analyser.smoothingTimeConstant=.8,this.source=this.audioContext.createMediaStreamSource(e),this.source.connect(this.analyser);let n=this.analyser.frequencyBinCount;this.dataArray=new Uint8Array(new ArrayBuffer(n)),F(`AudioAnalyzer`,`Setup complete`,{sampleRate:this.audioContext.sampleRate,frequencyBinCount:n,contextState:this.audioContext.state})}getAudioLevel(){if(!this.analyser||!this.dataArray)return 0;this.analyser.getByteFrequencyData(this.dataArray);let e=0;for(let t=0;t<this.dataArray.length;t++)e+=this.dataArray[t];let t=e/this.dataArray.length;return Math.min(1,t/128)}getFrequencyData(e=16){if(!this.analyser||!this.dataArray)return Array(e).fill(0);this.analyser.getByteFrequencyData(this.dataArray);let t=[],n=Math.floor(this.dataArray.length/e);for(let r=0;r<e;r++){let e=0;for(let t=0;t<n;t++)e+=this.dataArray[r*n+t];t.push(Math.min(1,e/n/255))}return t}startAnalysis(e){let t=()=>{e(this.getAudioLevel(),this.getFrequencyData()),this.animationId=requestAnimationFrame(t)};t()}stopAnalysis(){this.animationId!==null&&(cancelAnimationFrame(this.animationId),this.animationId=null)}destroy(){this.stopAnalysis(),this.source&&=(this.source.disconnect(),null),this.analyser&&=(this.analyser.disconnect(),null),this.audioContext&&=(this.audioContext.close(),null),this.dataArray=null}},L=class{listeners=new Map;on(e,t){this.listeners.has(e)||this.listeners.set(e,new Set);let n=this.listeners.get(e);n&&n.add(t)}off(e,t){this.listeners.get(e)?.delete(t)}emit(e,t){this.listeners.get(e)?.forEach(n=>{try{n(t)}catch(t){console.error(`Error in event listener for ${e}:`,t)}})}removeAllListeners(e){e?this.listeners.delete(e):this.listeners.clear()}listenerCount(e){return this.listeners.get(e)?.size||0}};function R(e){return e.type===`function_call`&&e.status===`completed`&&typeof e.name==`string`&&typeof e.call_id==`string`}var z=class{isProcessingResponse=!1;pendingFunctionCalls=new Set;responseRequestTimer=null;hasRequestedResponse=!1;constructor(e,t){this.toolManager=e,this.eventEmitter=t}async handleMessage(e,t){let n;try{n=JSON.parse(e)}catch(e){console.error(`Failed to parse realtime message:`,e);return}switch(n.type){case`response.created`:this.handleResponseCreated(n);break;case`response.done`:await this.handleResponseDone(n,t);break;case`response.function_call_arguments.done`:this.handleFunctionCallArguments();break;case`input_audio_buffer.speech_started`:case`input_audio_buffer.speech_stopped`:this.handleSpeechEvents(n);break;case`response.output_audio.delta`:case`response.output_audio.done`:this.handleAudioEvents(n);break;case`response.output_audio_transcript.delta`:case`response.output_audio_transcript.done`:case`response.output_text.delta`:case`response.output_text.done`:this.handleTranscriptEvents(n);break;case`conversation.item.input_audio_transcription.completed`:this.handleUserTranscript(n);break;case`error`:this.handleError(n);break;case`session.created`:case`session.updated`:this.handleSessionEvents(n);break;case`conversation.item.created`:case`input_audio_buffer.committed`:break}}handleResponseCreated(e){this.isProcessingResponse=!0,this.hasRequestedResponse=!1}async handleResponseDone(e,t){let n=this.extractResponseOutput(e.response);if(n.some(R)||(this.isProcessingResponse=!1,this.hasRequestedResponse=!1),n.length>0){let e=n.filter(R).map(e=>({name:e.name,call_id:e.call_id,arguments:e.arguments??``}));for(let n of e)this.pendingFunctionCalls.has(n.call_id)?console.warn(`[MessageHandler] Skipping duplicate function call: ${n.name} (${n.call_id})`):(this.pendingFunctionCalls.add(n.call_id),await this.executeFunctionCall(n,t));e.length>0&&this.pendingFunctionCalls.size===0&&this.requestResponseIfNeeded(t)}}extractResponseOutput(e){if(!e||typeof e!=`object`)return[];let t=e;return Array.isArray(t.output)?t.output.filter(e=>typeof e==`object`&&!!e&&typeof e.type==`string`):[]}handleFunctionCallArguments(){}handleSpeechEvents(e){let t=e.type===`input_audio_buffer.speech_started`?`speech_started`:`speech_stopped`;this.eventEmitter.emit(t,e)}handleAudioEvents(e){let t=e.type===`response.output_audio.delta`?`audio_started`:`audio_stopped`;console.log(`[MessageHandler] Assistant ${t}`,{type:e.type,hasAudio:!!e.delta}),this.eventEmitter.emit(t,e)}handleTranscriptEvents(e){let t={"response.output_audio_transcript.delta":`assistant_transcript`,"response.output_audio_transcript.done":`assistant_transcript_done`,"response.output_text.delta":`text`,"response.output_text.done":`text_done`}[e.type];t&&this.eventEmitter.emit(t,e)}handleUserTranscript(e){this.eventEmitter.emit(`user_transcript_done`,{text:e.transcript})}handleSessionEvents(e){}handleError(e){console.error(`Realtime API error:`,e),this.eventEmitter.emit(`error`,e),this.isProcessingResponse=!1,this.hasRequestedResponse=!1,this.responseRequestTimer&&=(clearTimeout(this.responseRequestTimer),null)}async executeFunctionCall(e,t){let{name:n,call_id:r}=e;try{this.eventEmitter.emit(`tool_call_started`,{name:n});let i=await this.toolManager.executeToolCall(e);if(t.readyState!==`open`){console.error(`[MessageHandler] Cannot send tool result for ${n}: DataChannel is ${t.readyState}`),this.eventEmitter.emit(`tool_call_completed`,{name:n,error:`DataChannel closed during tool execution`});return}let a={type:`conversation.item.create`,item:{type:`function_call_output`,call_id:r,output:JSON.stringify(i.success?i.data:{error:i.error,success:!1})}};t.send(JSON.stringify(a)),this.eventEmitter.emit(`tool_call_completed`,{name:n,error:i.success?void 0:i.error})}catch(e){console.error(`[MessageHandler] Tool execution failed for ${n}:`,e),this.sendToolError(r,String(e),t)}finally{this.pendingFunctionCalls.delete(r),this.pendingFunctionCalls.size===0&&(this.isProcessingResponse=!1,this.hasRequestedResponse=!1,this.requestResponseIfNeeded(t))}}sendToolError(e,t,n){if(n.readyState!==`open`){console.error(`[MessageHandler] Cannot send tool error: DataChannel is ${n.readyState}`);return}let r={type:`conversation.item.create`,item:{type:`function_call_output`,call_id:e,output:JSON.stringify({error:t,success:!1})}};n.send(JSON.stringify(r))}requestResponseIfNeeded(e){this.responseRequestTimer&&=(clearTimeout(this.responseRequestTimer),null),this.responseRequestTimer=setTimeout(()=>{!this.isProcessingResponse&&!this.hasRequestedResponse&&e.readyState===`open`&&this.pendingFunctionCalls.size===0&&(this.hasRequestedResponse=!0,this.isProcessingResponse=!0,e.send(JSON.stringify({type:`response.create`}))),this.responseRequestTimer=null},150)}reset(){this.isProcessingResponse=!1,this.hasRequestedResponse=!1,this.pendingFunctionCalls.clear(),this.responseRequestTimer&&=(clearTimeout(this.responseRequestTimer),null)}},B=class{tools=[];executor=null;lastSentToolSignature=``;setTools(e){this.tools=e}setExecutor(e){this.executor=e}resetSession(){console.log(`[ToolManager] resetSession called (lastSentToolSignature preserved)`)}getToolSignature(e){return e.map(e=>e.name).sort().join(`|`)}hasToolsChanged(){return this.getToolSignature(this.tools)!==this.lastSentToolSignature}markToolsSent(){this.lastSentToolSignature=this.getToolSignature(this.tools)}formatToolsForOpenAI(){let e=[{type:`function`,name:`list_available_tools`,description:`List all currently available tools that can be called. Use this when you need to know what tools are available or when the user asks about available capabilities.`,parameters:{type:`object`,properties:{},required:[]}}],t=this.tools.map(e=>({type:`function`,name:e.name,description:e.description||`Execute ${e.name} action`,parameters:this.validateToolSchema(e.inputSchema)}));return[...e,...t]}validateToolSchema(e){if(!e)return{type:`object`,properties:{},required:[]};let t={type:`object`,...e};return t.type===`object`&&(t.properties=t.properties||{},!t.required&&t.properties&&(t.required=Object.entries(t.properties).filter(([,e])=>{if(e&&typeof e==`object`){let t=e;return!t.optional&&!t.nullable&&t.type!==`null`}return!1}).map(([e])=>e))),t}async executeToolCall(e){let{name:t,arguments:n}=e;if(t===`list_available_tools`)return this.executeListTools();if(!this.executor)return{success:!1,error:`Tool executor not configured`};if(!this.tools.find(e=>e.name===t))return console.error(`[ToolManager] Tool not found: ${t}`),{success:!1,error:`Tool not found: ${t}`};let r;try{r=n?JSON.parse(n):{}}catch(e){return console.error(`[ToolManager] Failed to parse arguments:`,e),{success:!1,error:`Invalid arguments format`}}try{return{success:!0,data:await this.executor(t,r)}}catch(e){return console.error(`[ToolManager] Tool execution error for ${t}:`,e),{success:!1,error:String(e)}}}executeListTools(){let e=this.tools.map(e=>({name:e.name,description:e.description||`No description available`,parameters:e.inputSchema||{}}));return{success:!0,data:{tools:e,count:e.length,message:e.length>0?`Found ${e.length} available tools`:`No tools currently available`}}}getChangesSummary(){if(!this.hasToolsChanged())return null;let e=this.lastSentToolSignature.split(`|`).filter(Boolean),t=this.tools.map(e=>e.name),n=new Set(e),r=new Set(t);return{added:t.filter(e=>!n.has(e)),removed:e.filter(e=>!r.has(e)),total:this.tools.length}}};function V(e){return!e||typeof e!=`object`?!1:typeof e.client_secret?.value==`string`}var H=class{tokenEndpoint;constructor(e){this.tokenEndpoint=e}async createSession(e={}){let t=e.model||`gpt-4o-realtime-preview-2024-12-17`,n=e.voice||`verse`,r=e.apiUrl||`https://api.openai.com/v1/realtime`,i=await this.getEphemeralToken(t,n),a=new RTCPeerConnection,o=this.createAudioElement(),s=null;a.ontrack=e=>{s=e.streams[0],o.srcObject=s,F(`WebRTC`,`Remote audio stream received and connected to audio element`,{streamId:s.id,tracks:s.getTracks().length})};let c=await this.getUserMedia();F(`WebRTC`,`Local microphone stream acquired`,{streamId:c.id,tracks:c.getTracks().map(e=>({kind:e.kind,enabled:e.enabled,muted:e.muted,readyState:e.readyState}))}),c.getTracks().forEach(e=>{a.addTrack(e,c)});let l=a.createDataChannel(`oai-events`),u=await a.createOffer();if(await a.setLocalDescription(u),!u.sdp)throw Error(`Failed to create offer SDP`);let d=await this.connectToOpenAI(r,t,u.sdp,i);return await a.setRemoteDescription(d),{pc:a,dataChannel:l,audioElement:o,localStream:c,remoteStream:s,cleanup:()=>{c.getTracks().forEach(e=>{e.stop()}),o.remove(),l.close(),a.close()}}}async getEphemeralToken(e,t){let n=await fetch(this.tokenEndpoint,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({model:e,voice:t})});if(!n.ok){let e=await n.text();throw console.error(`Failed to get ephemeral token:`,e),Error(`Failed to get ephemeral token: ${n.statusText}`)}let r=await n.json();if(!V(r))throw Error(`Invalid token response format`);return r.client_secret.value}createAudioElement(){let e=document.createElement(`audio`);return e.autoplay=!0,e.style.display=`none`,document.body.appendChild(e),e}async getUserMedia(){try{return await navigator.mediaDevices.getUserMedia({audio:{echoCancellation:!0,noiseSuppression:!0,autoGainControl:!0}})}catch(e){throw Error(`Failed to access microphone: ${e}`)}}async connectToOpenAI(e,t,n,r){let i=await fetch(`${e}?model=${t}`,{method:`POST`,body:n,headers:{Authorization:`Bearer ${r}`,"Content-Type":`application/sdp`}});if(!i.ok)throw Error(`Failed to establish WebRTC connection: ${i.statusText}`);return{type:`answer`,sdp:await i.text()}}};let U=Object.freeze(Array(32).fill(0)),W=()=>[...U];var ee=class{session=null;webrtcManager;toolManager;messageHandler;eventEmitter;muted=!1;lastState=`disconnected`;localAnalyzer=null;remoteAnalyzer=null;visualizationInterval=null;sessionStartTime=null;onToolsChangedCallback=null;constructor(e){this.webrtcManager=new H(e),this.toolManager=new B,this.eventEmitter=new L,this.messageHandler=new z(this.toolManager,this.eventEmitter)}setTools(e){this.toolManager.setTools(e),this.isSessionActive()&&this.updateSessionTools()}setToolExecutor(e){this.toolManager.setExecutor(e)}onToolsChanged(e){this.onToolsChangedCallback=e}async startSession(e={}){try{this.session&&this.stopSession(),this.muted=!1,this.sessionStartTime=Date.now(),this.emitSessionState(`connecting`),this.session=await this.webrtcManager.createSession(e),this.setupDataChannel(this.session.dataChannel),this.setupPeerConnectionMonitoring(this.session.pc),this.session.localStream&&await this.initializeLocalAnalyzer(this.session.localStream),this.session.remoteStream&&this.initializeRemoteAnalyzer(this.session.remoteStream);let t=this.session.pc.ontrack,n=this.session;return this.session.pc.ontrack=e=>{t&&t.call(n.pc,e),this.session&&(this.session.remoteStream=e.streams[0]);let r=e.streams[0];if(!r){console.warn(`[OpenAIRealtimeService] Received ontrack event without stream`);return}this.initializeRemoteAnalyzer(r)},this.session}catch(e){throw this.handleSessionError(e),e}}stopSession(){let e=0;this.sessionStartTime&&(e=Math.floor((Date.now()-this.sessionStartTime)/1e3)),this.visualizationInterval&&=(clearInterval(this.visualizationInterval),null),this.localAnalyzer&&=(this.localAnalyzer.destroy(),null),this.remoteAnalyzer&&=(this.remoteAnalyzer.destroy(),null),this.session&&=(this.session.cleanup(),null),this.messageHandler.reset(),this.toolManager.resetSession(),this.muted=!1,this.emitSessionState(`disconnected`,{durationSeconds:e}),this.sessionStartTime=null}sendUserMessage(e){if(!this.isSessionActive())throw Error(`No active session`);let t={type:`conversation.item.create`,item:{type:`message`,role:`user`,content:[{type:`input_text`,text:e}]}};if(!this.session)throw Error(`Session is not active`);this.session.dataChannel.send(JSON.stringify(t)),this.session.dataChannel.send(JSON.stringify({type:`response.create`}))}isSessionActive(){return this.session!==null&&this.session.dataChannel.readyState===`open`}getLocalStream(){return this.session?.localStream||null}getRemoteStream(){return this.session?.remoteStream||null}toggleMute(e){this.session?.audioElement&&(this.session.audioElement.muted=e),this.muted=e,this.emitSessionState(this.lastState,{isMuted:this.muted})}on(e,t){this.eventEmitter.on(e,t)}off(e,t){this.eventEmitter.off(e,t)}getSessionStatus(){return{state:this.lastState,isActive:this.lastState===`connected`,isMuted:this.muted}}setupDataChannel(e){e.addEventListener(`open`,()=>{this.configureSession(e),this.muted=!1,this.emitSessionState(`connected`)}),e.addEventListener(`message`,t=>{(async()=>{try{await this.messageHandler.handleMessage(t.data,e)}catch(e){console.error(`Error handling message:`,e)}})()}),e.addEventListener(`error`,e=>{console.error(`DataChannel error:`,e),this.eventEmitter.emit(`error`,{type:`datachannel_error`,error:e})}),e.addEventListener(`close`,()=>{this.messageHandler.reset(),this.eventEmitter.emit(`session_closed`,{})})}setupPeerConnectionMonitoring(e){e.addEventListener(`connectionstatechange`,()=>{(e.connectionState===`failed`||e.connectionState===`disconnected`)&&(console.error(`Peer connection failed or disconnected`),this.messageHandler.reset(),this.eventEmitter.emit(`error`,{type:`connection_error`,message:`Connection ${e.connectionState}`}))}),e.addEventListener(`iceconnectionstatechange`,()=>{(e.iceConnectionState===`failed`||e.iceConnectionState===`disconnected`)&&console.error(`ICE connection failed or disconnected`)}),e.addEventListener(`signalingstatechange`,()=>{})}configureSession(e){this.toolManager.resetSession();let t=this.toolManager.formatToolsForOpenAI();this.toolManager.markToolsSent();let n={type:`session.update`,session:{modalities:[`text`,`audio`],instructions:this.getSessionInstructions(),voice:`verse`,tools:t,tool_choice:`auto`,turn_detection:{type:`server_vad`,threshold:.5,prefix_padding_ms:300,silence_duration_ms:500},input_audio_transcription:{model:`whisper-1`}}};e.send(JSON.stringify(n))}updateSessionTools(){if(!this.session){console.warn(`[OpenAIRealtimeService] Cannot update tools: no active session`);return}if(this.session.dataChannel.readyState!==`open`){console.warn(`[OpenAIRealtimeService] Cannot update tools: DataChannel is ${this.session.dataChannel.readyState}`);return}let e=this.toolManager.getChangesSummary();if(!e)return;let t=this.toolManager.formatToolsForOpenAI();console.log(`[OpenAIRealtimeService] Sending tool update to OpenAI:`,`${e.total} total tools,`,e.added.length>0?`+${e.added.length} added (${e.added.slice(0,3).join(`, `)}${e.added.length>3?`...`:``})`:``,e.removed.length>0?`-${e.removed.length} removed`:``),this.toolManager.markToolsSent();let n={type:`session.update`,session:{tools:t,tool_choice:`auto`}};this.session.dataChannel.send(JSON.stringify(n))}getSessionInstructions(){return`You are a helpful assistant with access to tools.
1
+ var WebMCP=(function(e,t,n,r,i,a,o,s,c,l,u,d,f,p,m,h,g,_,v,y,b,x,S,C,w,T){var E=Object.create,D=Object.defineProperty,O=Object.getOwnPropertyDescriptor,k=Object.getOwnPropertyNames,A=Object.getPrototypeOf,j=Object.prototype.hasOwnProperty,M=(e,t,n,r)=>{if(t&&typeof t==`object`||typeof t==`function`)for(var i=k(t),a=0,o=i.length,s;a<o;a++)s=i[a],!j.call(e,s)&&s!==n&&D(e,s,{get:(e=>t[e]).bind(null,s),enumerable:!(r=O(t,s))||r.enumerable});return e},N=(e,t,n)=>(n=e==null?{}:E(A(e)),M(t||!e||!e.__esModule?D(n,`default`,{value:e,enumerable:!0}):n,e));s=N(s),l=N(l),m=N(m),h=N(h),g=N(g),b=N(b);function P(...e){return(0,d.twMerge)((0,u.clsx)(e))}typeof window<`u`&&window.__WEBMCP_DEBUG__;function F(e,t,n){typeof window<`u`&&window.__WEBMCP_DEBUG__===!0&&(n===void 0?console.log(`[${e}] ${t}`):console.log(`[${e}] ${t}`,n))}var I=class{audioContext=null;analyser=null;source=null;dataArray=null;animationId=null;async initialize(e){let t=e.getAudioTracks();F(`AudioAnalyzer`,`Initializing with stream`,{streamId:e.id,audioTracks:t.length,trackInfo:t.map(e=>({id:e.id,label:e.label,enabled:e.enabled,muted:e.muted,readyState:e.readyState}))}),this.audioContext=new AudioContext,F(`AudioAnalyzer`,`AudioContext created, initial state: ${this.audioContext.state}`);try{await this.audioContext.resume(),F(`AudioAnalyzer`,`AudioContext after resume: ${this.audioContext.state}`)}catch(e){console.warn(`[AudioAnalyzer] Failed to resume AudioContext:`,e)}this.analyser=this.audioContext.createAnalyser(),this.analyser.fftSize=256,this.analyser.smoothingTimeConstant=.8,this.source=this.audioContext.createMediaStreamSource(e),this.source.connect(this.analyser);let n=this.analyser.frequencyBinCount;this.dataArray=new Uint8Array(new ArrayBuffer(n)),F(`AudioAnalyzer`,`Setup complete`,{sampleRate:this.audioContext.sampleRate,frequencyBinCount:n,contextState:this.audioContext.state})}getAudioLevel(){if(!this.analyser||!this.dataArray)return 0;this.analyser.getByteFrequencyData(this.dataArray);let e=0;for(let t=0;t<this.dataArray.length;t++)e+=this.dataArray[t];let t=e/this.dataArray.length;return Math.min(1,t/128)}getFrequencyData(e=16){if(!this.analyser||!this.dataArray)return Array(e).fill(0);this.analyser.getByteFrequencyData(this.dataArray);let t=[],n=Math.floor(this.dataArray.length/e);for(let r=0;r<e;r++){let e=0;for(let t=0;t<n;t++)e+=this.dataArray[r*n+t];t.push(Math.min(1,e/n/255))}return t}startAnalysis(e){let t=()=>{e(this.getAudioLevel(),this.getFrequencyData()),this.animationId=requestAnimationFrame(t)};t()}stopAnalysis(){this.animationId!==null&&(cancelAnimationFrame(this.animationId),this.animationId=null)}destroy(){this.stopAnalysis(),this.source&&=(this.source.disconnect(),null),this.analyser&&=(this.analyser.disconnect(),null),this.audioContext&&=(this.audioContext.close(),null),this.dataArray=null}},L=class{listeners=new Map;on(e,t){this.listeners.has(e)||this.listeners.set(e,new Set);let n=this.listeners.get(e);n&&n.add(t)}off(e,t){this.listeners.get(e)?.delete(t)}emit(e,t){this.listeners.get(e)?.forEach(n=>{try{n(t)}catch(t){console.error(`Error in event listener for ${e}:`,t)}})}removeAllListeners(e){e?this.listeners.delete(e):this.listeners.clear()}listenerCount(e){return this.listeners.get(e)?.size||0}};function R(e){return e.type===`function_call`&&e.status===`completed`&&typeof e.name==`string`&&typeof e.call_id==`string`}var z=class{isProcessingResponse=!1;pendingFunctionCalls=new Set;responseRequestTimer=null;hasRequestedResponse=!1;constructor(e,t){this.toolManager=e,this.eventEmitter=t}async handleMessage(e,t){let n;try{n=JSON.parse(e)}catch(e){console.error(`Failed to parse realtime message:`,e);return}switch(n.type){case`response.created`:this.handleResponseCreated(n);break;case`response.done`:await this.handleResponseDone(n,t);break;case`response.function_call_arguments.done`:this.handleFunctionCallArguments();break;case`input_audio_buffer.speech_started`:case`input_audio_buffer.speech_stopped`:this.handleSpeechEvents(n);break;case`response.output_audio.delta`:case`response.output_audio.done`:this.handleAudioEvents(n);break;case`response.output_audio_transcript.delta`:case`response.output_audio_transcript.done`:case`response.output_text.delta`:case`response.output_text.done`:this.handleTranscriptEvents(n);break;case`conversation.item.input_audio_transcription.completed`:this.handleUserTranscript(n);break;case`error`:this.handleError(n);break;case`session.created`:case`session.updated`:this.handleSessionEvents(n);break;case`conversation.item.created`:case`input_audio_buffer.committed`:break}}handleResponseCreated(e){this.isProcessingResponse=!0,this.hasRequestedResponse=!1}async handleResponseDone(e,t){let n=this.extractResponseOutput(e.response);if(n.some(R)||(this.isProcessingResponse=!1,this.hasRequestedResponse=!1),n.length>0){let e=n.filter(R).map(e=>({name:e.name,call_id:e.call_id,arguments:e.arguments??``}));for(let n of e)this.pendingFunctionCalls.has(n.call_id)?console.warn(`[MessageHandler] Skipping duplicate function call: ${n.name} (${n.call_id})`):(this.pendingFunctionCalls.add(n.call_id),await this.executeFunctionCall(n,t));e.length>0&&this.pendingFunctionCalls.size===0&&this.requestResponseIfNeeded(t)}}extractResponseOutput(e){if(!e||typeof e!=`object`)return[];let t=e;return Array.isArray(t.output)?t.output.filter(e=>typeof e==`object`&&!!e&&typeof e.type==`string`):[]}handleFunctionCallArguments(){}handleSpeechEvents(e){let t=e.type===`input_audio_buffer.speech_started`?`speech_started`:`speech_stopped`;this.eventEmitter.emit(t,e)}handleAudioEvents(e){let t=e.type===`response.output_audio.delta`?`audio_started`:`audio_stopped`;console.log(`[MessageHandler] Assistant ${t}`,{type:e.type,hasAudio:!!e.delta}),this.eventEmitter.emit(t,e)}handleTranscriptEvents(e){let t={"response.output_audio_transcript.delta":`assistant_transcript`,"response.output_audio_transcript.done":`assistant_transcript_done`,"response.output_text.delta":`text`,"response.output_text.done":`text_done`}[e.type];t&&this.eventEmitter.emit(t,e)}handleUserTranscript(e){this.eventEmitter.emit(`user_transcript_done`,{text:e.transcript})}handleSessionEvents(e){}handleError(e){console.error(`Realtime API error:`,e),this.eventEmitter.emit(`error`,e),this.isProcessingResponse=!1,this.hasRequestedResponse=!1,this.responseRequestTimer&&=(clearTimeout(this.responseRequestTimer),null)}async executeFunctionCall(e,t){let{name:n,call_id:r}=e;try{this.eventEmitter.emit(`tool_call_started`,{name:n});let i=await this.toolManager.executeToolCall(e);if(t.readyState!==`open`){console.error(`[MessageHandler] Cannot send tool result for ${n}: DataChannel is ${t.readyState}`),this.eventEmitter.emit(`tool_call_completed`,{name:n,error:`DataChannel closed during tool execution`});return}let a={type:`conversation.item.create`,item:{type:`function_call_output`,call_id:r,output:JSON.stringify(i.success?i.data:{error:i.error,success:!1})}};t.send(JSON.stringify(a)),this.eventEmitter.emit(`tool_call_completed`,{name:n,error:i.success?void 0:i.error})}catch(e){console.error(`[MessageHandler] Tool execution failed for ${n}:`,e),this.sendToolError(r,String(e),t)}finally{this.pendingFunctionCalls.delete(r),this.pendingFunctionCalls.size===0&&(this.isProcessingResponse=!1,this.hasRequestedResponse=!1,this.requestResponseIfNeeded(t))}}sendToolError(e,t,n){if(n.readyState!==`open`){console.error(`[MessageHandler] Cannot send tool error: DataChannel is ${n.readyState}`);return}let r={type:`conversation.item.create`,item:{type:`function_call_output`,call_id:e,output:JSON.stringify({error:t,success:!1})}};n.send(JSON.stringify(r))}requestResponseIfNeeded(e){this.responseRequestTimer&&=(clearTimeout(this.responseRequestTimer),null),this.responseRequestTimer=setTimeout(()=>{!this.isProcessingResponse&&!this.hasRequestedResponse&&e.readyState===`open`&&this.pendingFunctionCalls.size===0&&(this.hasRequestedResponse=!0,this.isProcessingResponse=!0,e.send(JSON.stringify({type:`response.create`}))),this.responseRequestTimer=null},150)}reset(){this.isProcessingResponse=!1,this.hasRequestedResponse=!1,this.pendingFunctionCalls.clear(),this.responseRequestTimer&&=(clearTimeout(this.responseRequestTimer),null)}},B=class{tools=[];executor=null;lastSentToolSignature=``;setTools(e){this.tools=e}setExecutor(e){this.executor=e}resetSession(){console.log(`[ToolManager] resetSession called (lastSentToolSignature preserved)`)}getToolSignature(e){return e.map(e=>e.name).sort().join(`|`)}hasToolsChanged(){return this.getToolSignature(this.tools)!==this.lastSentToolSignature}markToolsSent(){this.lastSentToolSignature=this.getToolSignature(this.tools)}formatToolsForOpenAI(){let e=[{type:`function`,name:`list_available_tools`,description:`List all currently available tools that can be called. Use this when you need to know what tools are available or when the user asks about available capabilities.`,parameters:{type:`object`,properties:{},required:[]}}],t=this.tools.map(e=>({type:`function`,name:e.name,description:e.description||`Execute ${e.name} action`,parameters:this.validateToolSchema(e.inputSchema)}));return[...e,...t]}validateToolSchema(e){if(!e)return{type:`object`,properties:{},required:[]};let t={type:`object`,...e};return t.type===`object`&&(t.properties=t.properties||{},!t.required&&t.properties&&(t.required=Object.entries(t.properties).filter(([,e])=>{if(e&&typeof e==`object`){let t=e;return!t.optional&&!t.nullable&&t.type!==`null`}return!1}).map(([e])=>e))),t}async executeToolCall(e){let{name:t,arguments:n}=e;if(t===`list_available_tools`)return this.executeListTools();if(!this.executor)return console.error(`[ToolManager] Tool executor not configured`),{success:!1,error:`Tool executor not configured`};let r;try{r=n?JSON.parse(n):{}}catch(e){return console.error(`[ToolManager] Failed to parse arguments:`,e),{success:!1,error:`Invalid arguments format`}}try{return{success:!0,data:await this.executor(t,r)}}catch(e){return console.error(`[ToolManager] Tool execution error for ${t}:`,e),{success:!1,error:String(e)}}}executeListTools(){let e=this.tools.map(e=>({name:e.name,description:e.description||`No description available`,parameters:e.inputSchema||{}}));return{success:!0,data:{tools:e,count:e.length,message:e.length>0?`Found ${e.length} available tools`:`No tools currently available`}}}getChangesSummary(){if(!this.hasToolsChanged())return null;let e=this.lastSentToolSignature.split(`|`).filter(Boolean),t=this.tools.map(e=>e.name),n=new Set(e),r=new Set(t);return{added:t.filter(e=>!n.has(e)),removed:e.filter(e=>!r.has(e)),total:this.tools.length}}};function V(e){return!e||typeof e!=`object`?!1:typeof e.client_secret?.value==`string`}var H=class{tokenEndpoint;constructor(e){this.tokenEndpoint=e}async createSession(e={}){let t=e.model||`gpt-4o-realtime-preview-2024-12-17`,n=e.voice||`verse`,r=e.apiUrl||`https://api.openai.com/v1/realtime`,i=await this.getEphemeralToken(t,n),a=new RTCPeerConnection,o=this.createAudioElement(),s=null;a.ontrack=e=>{s=e.streams[0],o.srcObject=s,F(`WebRTC`,`Remote audio stream received and connected to audio element`,{streamId:s.id,tracks:s.getTracks().length})};let c=await this.getUserMedia();F(`WebRTC`,`Local microphone stream acquired`,{streamId:c.id,tracks:c.getTracks().map(e=>({kind:e.kind,enabled:e.enabled,muted:e.muted,readyState:e.readyState}))}),c.getTracks().forEach(e=>{a.addTrack(e,c)});let l=a.createDataChannel(`oai-events`),u=await a.createOffer();if(await a.setLocalDescription(u),!u.sdp)throw Error(`Failed to create offer SDP`);let d=await this.connectToOpenAI(r,t,u.sdp,i);return await a.setRemoteDescription(d),{pc:a,dataChannel:l,audioElement:o,localStream:c,remoteStream:s,cleanup:()=>{c.getTracks().forEach(e=>{e.stop()}),o.remove(),l.close(),a.close()}}}async getEphemeralToken(e,t){let n=await fetch(this.tokenEndpoint,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({model:e,voice:t})});if(!n.ok){let e=await n.text();throw console.error(`Failed to get ephemeral token:`,e),Error(`Failed to get ephemeral token: ${n.statusText}`)}let r=await n.json();if(!V(r))throw Error(`Invalid token response format`);return r.client_secret.value}createAudioElement(){let e=document.createElement(`audio`);return e.autoplay=!0,e.style.display=`none`,document.body.appendChild(e),e}async getUserMedia(){try{return await navigator.mediaDevices.getUserMedia({audio:{echoCancellation:!0,noiseSuppression:!0,autoGainControl:!0}})}catch(e){throw Error(`Failed to access microphone: ${e}`)}}async connectToOpenAI(e,t,n,r){let i=await fetch(`${e}?model=${t}`,{method:`POST`,body:n,headers:{Authorization:`Bearer ${r}`,"Content-Type":`application/sdp`}});if(!i.ok)throw Error(`Failed to establish WebRTC connection: ${i.statusText}`);return{type:`answer`,sdp:await i.text()}}};let U=Object.freeze(Array(32).fill(0)),W=()=>[...U];var ee=class{session=null;webrtcManager;toolManager;messageHandler;eventEmitter;muted=!1;lastState=`disconnected`;localAnalyzer=null;remoteAnalyzer=null;visualizationInterval=null;sessionStartTime=null;onToolsChangedCallback=null;constructor(e){this.webrtcManager=new H(e),this.toolManager=new B,this.eventEmitter=new L,this.messageHandler=new z(this.toolManager,this.eventEmitter)}setTools(e){this.toolManager.setTools(e),this.isSessionActive()&&this.updateSessionTools()}setToolExecutor(e){this.toolManager.setExecutor(e)}onToolsChanged(e){this.onToolsChangedCallback=e}async startSession(e={}){try{this.session&&this.stopSession(),this.muted=!1,this.sessionStartTime=Date.now(),this.emitSessionState(`connecting`),this.session=await this.webrtcManager.createSession(e),this.setupDataChannel(this.session.dataChannel),this.setupPeerConnectionMonitoring(this.session.pc),this.session.localStream&&await this.initializeLocalAnalyzer(this.session.localStream),this.session.remoteStream&&this.initializeRemoteAnalyzer(this.session.remoteStream);let t=this.session.pc.ontrack,n=this.session;return this.session.pc.ontrack=e=>{t&&t.call(n.pc,e),this.session&&(this.session.remoteStream=e.streams[0]);let r=e.streams[0];if(!r){console.warn(`[OpenAIRealtimeService] Received ontrack event without stream`);return}this.initializeRemoteAnalyzer(r)},this.session}catch(e){throw this.handleSessionError(e),e}}stopSession(){let e=0;this.sessionStartTime&&(e=Math.floor((Date.now()-this.sessionStartTime)/1e3)),this.visualizationInterval&&=(clearInterval(this.visualizationInterval),null),this.localAnalyzer&&=(this.localAnalyzer.destroy(),null),this.remoteAnalyzer&&=(this.remoteAnalyzer.destroy(),null),this.session&&=(this.session.cleanup(),null),this.messageHandler.reset(),this.toolManager.resetSession(),this.muted=!1,this.emitSessionState(`disconnected`,{durationSeconds:e}),this.sessionStartTime=null}sendUserMessage(e){if(!this.isSessionActive())throw Error(`No active session`);let t={type:`conversation.item.create`,item:{type:`message`,role:`user`,content:[{type:`input_text`,text:e}]}};if(!this.session)throw Error(`Session is not active`);this.session.dataChannel.send(JSON.stringify(t)),this.session.dataChannel.send(JSON.stringify({type:`response.create`}))}isSessionActive(){return this.session!==null&&this.session.dataChannel.readyState===`open`}getLocalStream(){return this.session?.localStream||null}getRemoteStream(){return this.session?.remoteStream||null}toggleMute(e){this.session?.audioElement&&(this.session.audioElement.muted=e),this.muted=e,this.emitSessionState(this.lastState,{isMuted:this.muted})}on(e,t){this.eventEmitter.on(e,t)}off(e,t){this.eventEmitter.off(e,t)}getSessionStatus(){return{state:this.lastState,isActive:this.lastState===`connected`,isMuted:this.muted}}setupDataChannel(e){e.addEventListener(`open`,()=>{this.configureSession(e),this.muted=!1,this.emitSessionState(`connected`)}),e.addEventListener(`message`,t=>{(async()=>{try{await this.messageHandler.handleMessage(t.data,e)}catch(e){console.error(`Error handling message:`,e)}})()}),e.addEventListener(`error`,e=>{console.error(`DataChannel error:`,e),this.eventEmitter.emit(`error`,{type:`datachannel_error`,error:e})}),e.addEventListener(`close`,()=>{this.messageHandler.reset(),this.eventEmitter.emit(`session_closed`,{})})}setupPeerConnectionMonitoring(e){e.addEventListener(`connectionstatechange`,()=>{(e.connectionState===`failed`||e.connectionState===`disconnected`)&&(console.error(`Peer connection failed or disconnected`),this.messageHandler.reset(),this.eventEmitter.emit(`error`,{type:`connection_error`,message:`Connection ${e.connectionState}`}))}),e.addEventListener(`iceconnectionstatechange`,()=>{(e.iceConnectionState===`failed`||e.iceConnectionState===`disconnected`)&&console.error(`ICE connection failed or disconnected`)}),e.addEventListener(`signalingstatechange`,()=>{})}configureSession(e){this.toolManager.resetSession();let t=this.toolManager.formatToolsForOpenAI();this.toolManager.markToolsSent();let n={type:`session.update`,session:{modalities:[`text`,`audio`],instructions:this.getSessionInstructions(),voice:`verse`,tools:t,tool_choice:`auto`,turn_detection:{type:`server_vad`,threshold:.5,prefix_padding_ms:300,silence_duration_ms:500},input_audio_transcription:{model:`whisper-1`}}};e.send(JSON.stringify(n))}updateSessionTools(){if(!this.session){console.warn(`[OpenAIRealtimeService] Cannot update tools: no active session`);return}if(this.session.dataChannel.readyState!==`open`){console.warn(`[OpenAIRealtimeService] Cannot update tools: DataChannel is ${this.session.dataChannel.readyState}`);return}let e=this.toolManager.getChangesSummary();if(!e)return;let t=this.toolManager.formatToolsForOpenAI();console.log(`[OpenAIRealtimeService] Sending tool update to OpenAI:`,`${e.total} total tools,`,e.added.length>0?`+${e.added.length} added (${e.added.slice(0,3).join(`, `)}${e.added.length>3?`...`:``})`:``,e.removed.length>0?`-${e.removed.length} removed`:``),this.toolManager.markToolsSent();let n={type:`session.update`,session:{tools:t,tool_choice:`auto`}};this.session.dataChannel.send(JSON.stringify(n))}getSessionInstructions(){return`You are a helpful assistant with access to tools.
2
2
  Use the available tools to help users with their tasks.
3
3
  You can use the list_available_tools function to see what tools are currently available.
4
4
  Be concise and helpful in your responses.`}handleSessionError(e){console.error(`Session error:`,e),this.emitSessionState(`error`,{type:`session_error`,error:String(e)}),this.stopSession()}async initializeLocalAnalyzer(e){this.localAnalyzer&&this.localAnalyzer.destroy(),this.localAnalyzer=new I;try{let t=new MediaStream(e.getAudioTracks().map(e=>e.clone()));await this.localAnalyzer.initialize(t),this.startAudioVisualization()}catch(e){console.error(`[OpenAIRealtimeService] Failed to initialize local audio analyzer`,e),this.localAnalyzer&&=(this.localAnalyzer.destroy(),null)}}async initializeRemoteAnalyzer(e){this.remoteAnalyzer&&this.remoteAnalyzer.destroy(),this.remoteAnalyzer=new I;try{let t=new MediaStream(e.getAudioTracks().map(e=>e.clone()));await this.remoteAnalyzer.initialize(t),this.startAudioVisualization()}catch(e){console.error(`[OpenAIRealtimeService] Failed to initialize remote audio analyzer`,e),this.remoteAnalyzer&&=(this.remoteAnalyzer.destroy(),null)}}startAudioVisualization(){if(!this.localAnalyzer&&!this.remoteAnalyzer){F(`OpenAIRealtimeService`,`Audio visualization not started: no analyzers ready`);return}this.visualizationInterval&&clearInterval(this.visualizationInterval);let e=0;this.visualizationInterval=setInterval(()=>{let t=this.localAnalyzer?.getAudioLevel()??0,n=this.localAnalyzer?.getFrequencyData(32)??W(),r=this.remoteAnalyzer?.getAudioLevel()??0,i=this.remoteAnalyzer?.getFrequencyData(32)??W();e++,e%60==0&&F(`OpenAIRealtimeService`,`Audio levels`,{mic:t.toFixed(3),speaker:r.toFixed(3)}),this.eventEmitter.emit(`audio_level`,{micLevel:t,micFrequency:n,speakerLevel:r,speakerFrequency:i})},16)}emitSessionState(e,t={}){this.lastState=e;let n={state:e,isActive:e===`connected`,isMuted:this.muted,...t};switch(this.eventEmitter.emit(`session_state`,n),e){case`connecting`:this.eventEmitter.emit(`session_connecting`,n);break;case`connected`:this.eventEmitter.emit(`session_connected`,n);break;case`disconnected`:this.eventEmitter.emit(`session_closed`,n);break;case`error`:this.eventEmitter.emit(`error`,n);break;default:break}}};function te(e){if(!e||typeof e!=`object`)return!1;let t=e;return typeof t.state==`string`&&[`connecting`,`connected`,`disconnected`,`error`].includes(t.state)&&typeof t.isActive==`boolean`&&typeof t.isMuted==`boolean`}function ne(e){return!e||typeof e!=`object`?!1:typeof e.text==`string`}function re(e){if(!e||typeof e!=`object`)return!1;let t=e;return t.delta===void 0||typeof t.delta==`string`}function ie(e){return!e||typeof e!=`object`?!1:typeof e.name==`string`}function ae(e){return!e||typeof e!=`object`?!1:typeof e.name==`string`}function G(e){if(!e||typeof e!=`object`)return!1;let t=e;return typeof t.error==`string`||typeof t.message==`string`||typeof t.type==`string`}function oe(e){if(!e||typeof e!=`object`)return!1;let t=e;return typeof t.micLevel==`number`&&Array.isArray(t.micFrequency)&&typeof t.speakerLevel==`number`&&Array.isArray(t.speakerFrequency)}function K(e){let n=(0,t.c)(43),{tokenEndpoint:r,tools:i,toolExecutor:a,onConnect:o,onDisconnect:c,onError:l,onUserTranscript:u,onAssistantTranscript:d}=e,[f,p]=(0,s.useState)(!1),[m,h]=(0,s.useState)(!1),[g,_]=(0,s.useState)(!1),[v,y]=(0,s.useState)(!1),[b,x]=(0,s.useState)(`disconnected`),[S,C]=(0,s.useState)(),[w,T]=(0,s.useState)(),[E,D]=(0,s.useState)(),[O,k]=(0,s.useState)(),A=(0,s.useRef)(null),j=(0,s.useRef)(o),M=(0,s.useRef)(c),N=(0,s.useRef)(l),P=(0,s.useRef)(u),F=(0,s.useRef)(d),I,L;n[0]!==d||n[1]!==o||n[2]!==c||n[3]!==l||n[4]!==u?(I=()=>{j.current=o,M.current=c,N.current=l,P.current=u,F.current=d},L=[o,c,l,u,d],n[0]=d,n[1]=o,n[2]=c,n[3]=l,n[4]=u,n[5]=I,n[6]=L):(I=n[5],L=n[6]),(0,s.useEffect)(I,L);let R;n[7]===r?R=n[8]:(R=()=>(A.current||=new ee(r),A.current),n[7]=r,n[8]=R);let z=R,B,V;n[9]!==z||n[10]!==i?(B=()=>{i&&z().setTools(i)},V=[i,z],n[9]=z,n[10]=i,n[11]=B,n[12]=V):(B=n[11],V=n[12]),(0,s.useEffect)(B,V);let H,U;n[13]!==z||n[14]!==a?(H=()=>{a&&z().setToolExecutor(a)},U=[a,z],n[13]=z,n[14]=a,n[15]=H,n[16]=U):(H=n[15],U=n[16]),(0,s.useEffect)(H,U);let W,K;n[17]===z?(W=n[18],K=n[19]):(W=()=>{let e=z(),t=e=>{if(!te(e)){console.warn(`[useVoiceMode] Invalid session state event data:`,e);return}x(e.state),p(e.isActive),_(e.isMuted),h(e.state===`connecting`),y(e.state===`error`),e.state===`connected`?j.current?.():e.state===`disconnected`&&M.current?.(e.durationSeconds??0)},n=e=>{oe(e)&&C(e)},r=e=>{if(!ne(e)){console.warn(`[useVoiceMode] Invalid user transcript event data:`,e);return}T({type:`user`,text:e.text,isDone:!0}),P.current?.(e.text)},i=e=>{if(!re(e))return;let t=e.delta||e.transcript||``;T(e=>({type:`assistant`,text:e?.type===`assistant`?e.text+t:t,isDone:!1}))},a=e=>{if(!re(e))return;let t=e.transcript||``;T({type:`assistant`,text:t,isDone:!0}),F.current?.(t)},o=e=>{if(!ie(e)){console.warn(`[useVoiceMode] Invalid tool call started event data:`,e);return}D({status:`started`,toolName:e.name})},s=e=>{if(!ae(e)){console.warn(`[useVoiceMode] Invalid tool call completed event data:`,e);return}D({status:`completed`,toolName:e.name,error:e.error}),setTimeout(()=>{D(void 0)},e.error?3e3:1500)},c=e=>{if(!G(e)){k(`Unknown error`),y(!0),N.current?.(`Unknown error`);return}let t=e.error||e.message||`Unknown error`;k(t),y(!0),N.current?.(t)};return e.on(`session_state`,t),e.on(`audio_level`,n),e.on(`user_transcript_done`,r),e.on(`assistant_transcript`,i),e.on(`assistant_transcript_done`,a),e.on(`tool_call_started`,o),e.on(`tool_call_completed`,s),e.on(`error`,c),()=>{e.off(`session_state`,t),e.off(`audio_level`,n),e.off(`user_transcript_done`,r),e.off(`assistant_transcript`,i),e.off(`assistant_transcript_done`,a),e.off(`tool_call_started`,o),e.off(`tool_call_completed`,s),e.off(`error`,c)}},K=[z],n[17]=z,n[18]=W,n[19]=K),(0,s.useEffect)(W,K);let q;n[20]===z?q=n[21]:(q=async e=>{try{h(!0),y(!1),k(void 0),await z().startSession(e)}catch(e){let t=e;h(!1),y(!0);let n=t instanceof Error?t.message:`Failed to start session`;k(n),N.current?.(n)}},n[20]=z,n[21]=q);let J=q,Y;n[22]===z?Y=n[23]:(Y=()=>{z().stopSession(),C(void 0),T(void 0),D(void 0)},n[22]=z,n[23]=Y);let se=Y,ce;n[24]!==z||n[25]!==g?(ce=e=>{let t=z(),n=e===void 0?!g:e;t.toggleMute(n),_(n)},n[24]=z,n[25]=g,n[26]=ce):ce=n[26];let le=ce,ue;n[27]===z?ue=n[28]:(ue=e=>{let t=z();t.isSessionActive()&&t.sendUserMessage(e)},n[27]=z,n[28]=ue);let de=ue,fe;return n[29]!==S||n[30]!==b||n[31]!==O||n[32]!==f||n[33]!==m||n[34]!==v||n[35]!==g||n[36]!==de||n[37]!==J||n[38]!==se||n[39]!==le||n[40]!==E||n[41]!==w?(fe={isActive:f,isConnecting:m,isMuted:g,isError:v,connectionState:b,audioLevel:S,transcript:w,toolCall:E,error:O,startSession:J,stopSession:se,toggleMute:le,sendMessage:de},n[29]=S,n[30]=b,n[31]=O,n[32]=f,n[33]=m,n[34]=v,n[35]=g,n[36]=de,n[37]=J,n[38]=se,n[39]=le,n[40]=E,n[41]=w,n[42]=fe):fe=n[42],fe}let q=(0,s.createContext)(null);function J(){return!!(typeof window<`u`&&window.RTCPeerConnection&&navigator.mediaDevices?.getUserMedia)}function Y(e){let n=(0,t.c)(15),{children:r,tokenEndpoint:i,tools:a,toolExecutor:o,onConnect:s,onDisconnect:c,onError:l,onUserTranscript:u,onAssistantTranscript:d}=e,p;n[0]!==d||n[1]!==s||n[2]!==c||n[3]!==l||n[4]!==u||n[5]!==i||n[6]!==o||n[7]!==a?(p={tokenEndpoint:i,tools:a,toolExecutor:o,onConnect:s,onDisconnect:c,onError:l,onUserTranscript:u,onAssistantTranscript:d},n[0]=d,n[1]=s,n[2]=c,n[3]=l,n[4]=u,n[5]=i,n[6]=o,n[7]=a,n[8]=p):p=n[8];let m=K(p),h;n[9]===Symbol.for(`react.memo_cache_sentinel`)?(h=J(),n[9]=h):h=n[9];let g=h,_;n[10]===m?_=n[11]:(_={...m,isSupported:g},n[10]=m,n[11]=_);let v=_,y;return n[12]!==r||n[13]!==v?(y=(0,f.jsx)(q.Provider,{value:v,children:r}),n[12]=r,n[13]=v,n[14]=y):y=n[14],y}function se(){return(0,s.useContext)(q)}function ce(e){let n=(0,t.c)(8),r,i;n[0]===e?(r=n[1],i=n[2]):({className:r,...i}=e,n[0]=e,n[1]=r,n[2]=i);let a;n[3]===r?a=n[4]:(a=P(`relative flex size-8 shrink-0 overflow-hidden rounded-full`,r),n[3]=r,n[4]=a);let o;return n[5]!==i||n[6]!==a?(o=(0,f.jsx)(m.Root,{"data-slot":`avatar`,className:a,...i}),n[5]=i,n[6]=a,n[7]=o):o=n[7],o}function le(e){let n=(0,t.c)(8),r,i;n[0]===e?(r=n[1],i=n[2]):({className:r,...i}=e,n[0]=e,n[1]=r,n[2]=i);let a;n[3]===r?a=n[4]:(a=P(`aspect-square size-full`,r),n[3]=r,n[4]=a);let o;return n[5]!==i||n[6]!==a?(o=(0,f.jsx)(m.Image,{"data-slot":`avatar-image`,className:a,...i}),n[5]=i,n[6]=a,n[7]=o):o=n[7],o}function ue(e){let n=(0,t.c)(8),r,i;n[0]===e?(r=n[1],i=n[2]):({className:r,...i}=e,n[0]=e,n[1]=r,n[2]=i);let a;n[3]===r?a=n[4]:(a=P(`bg-muted flex size-full items-center justify-center rounded-full`,r),n[3]=r,n[4]=a);let o;return n[5]!==i||n[6]!==a?(o=(0,f.jsx)(m.Fallback,{"data-slot":`avatar-fallback`,className:a,...i}),n[5]=i,n[6]=a,n[7]=o):o=n[7],o}function de(e){let n=(0,t.c)(4),r;n[0]===e?r=n[1]:({...r}=e,n[0]=e,n[1]=r);let i;return n[2]===r?i=n[3]:(i=(0,f.jsx)(h.Root,{"data-slot":`dialog`,...r}),n[2]=r,n[3]=i),i}function fe(e){let n=(0,t.c)(4),r;n[0]===e?r=n[1]:({...r}=e,n[0]=e,n[1]=r);let i;return n[2]===r?i=n[3]:(i=(0,f.jsx)(h.Trigger,{"data-slot":`dialog-trigger`,...r}),n[2]=r,n[3]=i),i}function pe(e){let n=(0,t.c)(4),r;n[0]===e?r=n[1]:({...r}=e,n[0]=e,n[1]=r);let i;return n[2]===r?i=n[3]:(i=(0,f.jsx)(h.Portal,{"data-slot":`dialog-portal`,...r}),n[2]=r,n[3]=i),i}function me(e){let n=(0,t.c)(8),r,i;n[0]===e?(r=n[1],i=n[2]):({className:r,...i}=e,n[0]=e,n[1]=r,n[2]=i);let a;n[3]===r?a=n[4]:(a=P(`data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 fixed inset-0 z-50 bg-black/50`,r),n[3]=r,n[4]=a);let o;return n[5]!==i||n[6]!==a?(o=(0,f.jsx)(h.Overlay,{"data-slot":`dialog-overlay`,className:a,...i}),n[5]=i,n[6]=a,n[7]=o):o=n[7],o}function he(e){let n=(0,t.c)(15),r,i,a,s;n[0]===e?(r=n[1],i=n[2],a=n[3],s=n[4]):({className:i,children:r,showCloseButton:s,...a}=e,n[0]=e,n[1]=r,n[2]=i,n[3]=a,n[4]=s);let c=s===void 0?!0:s,l;n[5]===Symbol.for(`react.memo_cache_sentinel`)?(l=(0,f.jsx)(me,{}),n[5]=l):l=n[5];let u;n[6]===i?u=n[7]:(u=P(`bg-background data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 fixed top-[50%] left-[50%] z-50 grid w-full max-w-[calc(100%-2rem)] translate-x-[-50%] translate-y-[-50%] gap-4 rounded-lg border p-6 shadow-lg duration-200 sm:max-w-lg`,i),n[6]=i,n[7]=u);let d;n[8]===c?d=n[9]:(d=c&&(0,f.jsxs)(h.Close,{"data-slot":`dialog-close`,className:`ring-offset-background focus:ring-ring data-[state=open]:bg-accent data-[state=open]:text-muted-foreground absolute top-4 right-4 rounded-xs opacity-70 transition-opacity hover:opacity-100 focus:ring-2 focus:ring-offset-2 focus:outline-hidden disabled:pointer-events-none [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4`,children:[(0,f.jsx)(o.XIcon,{}),(0,f.jsx)(`span`,{className:`sr-only`,children:`Close`})]}),n[8]=c,n[9]=d);let p;return n[10]!==r||n[11]!==a||n[12]!==u||n[13]!==d?(p=(0,f.jsxs)(pe,{"data-slot":`dialog-portal`,children:[l,(0,f.jsxs)(h.Content,{"data-slot":`dialog-content`,className:u,...a,children:[r,d]})]}),n[10]=r,n[11]=a,n[12]=u,n[13]=d,n[14]=p):p=n[14],p}function ge(e){let n=(0,t.c)(8),r,i;n[0]===e?(r=n[1],i=n[2]):({className:r,...i}=e,n[0]=e,n[1]=r,n[2]=i);let a;n[3]===r?a=n[4]:(a=P(`flex flex-col gap-2 text-center sm:text-left`,r),n[3]=r,n[4]=a);let o;return n[5]!==i||n[6]!==a?(o=(0,f.jsx)(`div`,{"data-slot":`dialog-header`,className:a,...i}),n[5]=i,n[6]=a,n[7]=o):o=n[7],o}function _e(e){let n=(0,t.c)(8),r,i;n[0]===e?(r=n[1],i=n[2]):({className:r,...i}=e,n[0]=e,n[1]=r,n[2]=i);let a;n[3]===r?a=n[4]:(a=P(`text-lg leading-none font-semibold`,r),n[3]=r,n[4]=a);let o;return n[5]!==i||n[6]!==a?(o=(0,f.jsx)(h.Title,{"data-slot":`dialog-title`,className:a,...i}),n[5]=i,n[6]=a,n[7]=o):o=n[7],o}function ve(e){let n=(0,t.c)(8),r,i;n[0]===e?(r=n[1],i=n[2]):({className:r,...i}=e,n[0]=e,n[1]=r,n[2]=i);let a;n[3]===r?a=n[4]:(a=P(`text-muted-foreground text-sm`,r),n[3]=r,n[4]=a);let o;return n[5]!==i||n[6]!==a?(o=(0,f.jsx)(h.Description,{"data-slot":`dialog-description`,className:a,...i}),n[5]=i,n[6]=a,n[7]=o):o=n[7],o}function ye(e){let n=(0,t.c)(6),r,i;n[0]===e?(r=n[1],i=n[2]):({delayDuration:i,...r}=e,n[0]=e,n[1]=r,n[2]=i);let a=i===void 0?0:i,o;return n[3]!==a||n[4]!==r?(o=(0,f.jsx)(g.Provider,{"data-slot":`tooltip-provider`,delayDuration:a,...r}),n[3]=a,n[4]=r,n[5]=o):o=n[5],o}function be(e){let n=(0,t.c)(4),r;n[0]===e?r=n[1]:({...r}=e,n[0]=e,n[1]=r);let i;return n[2]===r?i=n[3]:(i=(0,f.jsx)(ye,{children:(0,f.jsx)(g.Root,{"data-slot":`tooltip`,...r})}),n[2]=r,n[3]=i),i}function xe(e){let n=(0,t.c)(4),r;n[0]===e?r=n[1]:({...r}=e,n[0]=e,n[1]=r);let i;return n[2]===r?i=n[3]:(i=(0,f.jsx)(g.Trigger,{"data-slot":`tooltip-trigger`,...r}),n[2]=r,n[3]=i),i}function Se(e){let n=(0,t.c)(13),r,i,a,o;n[0]===e?(r=n[1],i=n[2],a=n[3],o=n[4]):({className:i,sideOffset:o,children:r,...a}=e,n[0]=e,n[1]=r,n[2]=i,n[3]=a,n[4]=o);let s=o===void 0?0:o,c;n[5]===i?c=n[6]:(c=P(`bg-foreground text-background animate-in fade-in-0 zoom-in-95 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 z-50 w-fit origin-(--radix-tooltip-content-transform-origin) rounded-md px-3 py-1.5 text-xs text-balance`,i),n[5]=i,n[6]=c);let l;n[7]===Symbol.for(`react.memo_cache_sentinel`)?(l=(0,f.jsx)(g.Arrow,{className:`bg-foreground fill-foreground z-50 size-2.5 translate-y-[calc(-50%_-_2px)] rotate-45 rounded-[2px]`}),n[7]=l):l=n[7];let u;return n[8]!==r||n[9]!==a||n[10]!==s||n[11]!==c?(u=(0,f.jsx)(g.Portal,{children:(0,f.jsxs)(g.Content,{"data-slot":`tooltip-content`,sideOffset:s,className:c,...a,children:[r,l]})}),n[8]=r,n[9]=a,n[10]=s,n[11]=c,n[12]=u):u=n[12],u}let Ce=(0,v.cva)(`inline-flex items-center justify-center gap-2 whitespace-nowrap rounded-md text-sm font-medium transition-all disabled:pointer-events-none disabled:opacity-50 [&_svg]:pointer-events-none [&_svg:not([class*='size-'])]:size-4 shrink-0 [&_svg]:shrink-0 outline-none focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:ring-[3px] aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive`,{variants:{variant:{default:`bg-primary text-primary-foreground hover:bg-primary/90`,destructive:`bg-destructive text-white hover:bg-destructive/90 focus-visible:ring-destructive/20 dark:focus-visible:ring-destructive/40 dark:bg-destructive/60`,outline:`border bg-background shadow-xs hover:bg-accent hover:text-accent-foreground dark:bg-input/30 dark:border-input dark:hover:bg-input/50`,secondary:`bg-secondary text-secondary-foreground hover:bg-secondary/80`,ghost:`hover:bg-accent hover:text-accent-foreground dark:hover:bg-accent/50`,link:`text-primary underline-offset-4 hover:underline`},size:{default:`h-9 px-4 py-2 has-[>svg]:px-3`,sm:`h-8 rounded-md gap-1.5 px-3 has-[>svg]:px-2.5`,lg:`h-10 rounded-md px-6 has-[>svg]:px-4`,icon:`size-9`,"icon-sm":`size-8`,"icon-lg":`size-10`}},defaultVariants:{variant:`default`,size:`default`}});function X(e){let n=(0,t.c)(14),r,i,a,o,s;n[0]===e?(r=n[1],i=n[2],a=n[3],o=n[4],s=n[5]):({className:r,variant:s,size:a,asChild:o,...i}=e,n[0]=e,n[1]=r,n[2]=i,n[3]=a,n[4]=o,n[5]=s);let c=o!==void 0&&o?_.Slot:`button`,l;n[6]!==r||n[7]!==a||n[8]!==s?(l=P(Ce({variant:s,size:a,className:r})),n[6]=r,n[7]=a,n[8]=s,n[9]=l):l=n[9];let u;return n[10]!==c||n[11]!==i||n[12]!==l?(u=(0,f.jsx)(c,{"data-slot":`button`,className:l,...i}),n[10]=c,n[11]=i,n[12]=l,n[13]=u):u=n[13],u}let Z=(0,s.forwardRef)((e,n)=>{let r=(0,t.c)(24),i,a,o,s,c;r[0]===e?(i=r[1],a=r[2],o=r[3],s=r[4],c=r[5]):({children:i,tooltip:c,side:s,className:a,...o}=e,r[0]=e,r[1]=i,r[2]=a,r[3]=o,r[4]=s,r[5]=c);let l=s===void 0?`bottom`:s,u;r[6]===a?u=r[7]:(u=P(`aui-button-icon size-6 p-1`,a),r[6]=a,r[7]=u);let d;r[8]===i?d=r[9]:(d=(0,f.jsx)(_.Slottable,{children:i}),r[8]=i,r[9]=d);let p;r[10]===c?p=r[11]:(p=(0,f.jsx)(`span`,{className:`aui-sr-only sr-only`,children:c}),r[10]=c,r[11]=p);let m;r[12]!==n||r[13]!==o||r[14]!==u||r[15]!==d||r[16]!==p?(m=(0,f.jsx)(xe,{asChild:!0,children:(0,f.jsxs)(X,{variant:`ghost`,size:`icon`,...o,className:u,ref:n,children:[d,p]})}),r[12]=n,r[13]=o,r[14]=u,r[15]=d,r[16]=p,r[17]=m):m=r[17];let h;r[18]!==l||r[19]!==c?(h=(0,f.jsx)(Se,{side:l,children:c}),r[18]=l,r[19]=c,r[20]=h):h=r[20];let g;return r[21]!==m||r[22]!==h?(g=(0,f.jsxs)(be,{children:[m,h]}),r[21]=m,r[22]=h,r[23]=g):g=r[23],g});Z.displayName=`TooltipIconButton`;let we=e=>{let n=(0,t.c)(3),[r,i]=(0,s.useState)(void 0),a,o;return n[0]===e?(a=n[1],o=n[2]):(a=()=>{if(!e){i(void 0);return}let t=URL.createObjectURL(e);return i(t),()=>{URL.revokeObjectURL(t)}},o=[e],n[0]=e,n[1]=a,n[2]=o),(0,s.useEffect)(a,o),r},Te=()=>{let{file:e,src:t}=(0,n.useAssistantState)((0,p.useShallow)(Fe));return we(e)??t},Ee=e=>{let n=(0,t.c)(2),{src:r}=e,i;return n[0]===r?i=n[1]:(i=(0,f.jsx)(`img`,{src:r,alt:`Image Preview`,width:1,height:1,className:`aui-attachment-preview-image-loaded block h-auto max-h-[80vh] w-auto max-w-full object-contain`}),n[0]=r,n[1]=i),i},De=e=>{let n=(0,t.c)(8),{children:r}=e,i=Te();if(!i)return r;let a;n[0]===r?a=n[1]:(a=(0,f.jsx)(fe,{className:`aui-attachment-preview-trigger cursor-pointer transition-colors hover:bg-accent/50`,asChild:!0,children:r}),n[0]=r,n[1]=a);let o;n[2]===Symbol.for(`react.memo_cache_sentinel`)?(o=(0,f.jsx)(_e,{className:`aui-sr-only sr-only`,children:`Image Attachment Preview`}),n[2]=o):o=n[2];let s;n[3]===i?s=n[4]:(s=(0,f.jsxs)(he,{className:`aui-attachment-preview-dialog-content p-2 sm:max-w-3xl [&_svg]:text-background [&>button]:rounded-full [&>button]:bg-foreground/60 [&>button]:p-1 [&>button]:opacity-100 [&>button]:!ring-0 [&>button]:hover:[&_svg]:text-destructive`,children:[o,(0,f.jsx)(`div`,{className:`aui-attachment-preview relative mx-auto flex max-h-[80dvh] w-full items-center justify-center overflow-hidden bg-background`,children:(0,f.jsx)(Ee,{src:i})})]}),n[3]=i,n[4]=s);let c;return n[5]!==a||n[6]!==s?(c=(0,f.jsxs)(de,{children:[a,s]}),n[5]=a,n[6]=s,n[7]=c):c=n[7],c},Oe=()=>{let e=(0,t.c)(8),r=(0,n.useAssistantState)(Ie),i=Te(),a;e[0]===i?a=e[1]:(a=(0,f.jsx)(le,{src:i,alt:`Attachment preview`,className:`aui-attachment-tile-image object-cover`}),e[0]=i,e[1]=a);let s=r?200:0,c;e[2]===Symbol.for(`react.memo_cache_sentinel`)?(c=(0,f.jsx)(o.FileText,{className:`aui-attachment-tile-fallback-icon size-8 text-muted-foreground`}),e[2]=c):c=e[2];let l;e[3]===s?l=e[4]:(l=(0,f.jsx)(ue,{delayMs:s,children:c}),e[3]=s,e[4]=l);let u;return e[5]!==a||e[6]!==l?(u=(0,f.jsxs)(ce,{className:`aui-attachment-tile-avatar h-full w-full rounded-none`,children:[a,l]}),e[5]=a,e[6]=l,e[7]=u):u=e[7],u},ke=()=>{let e=(0,t.c)(17),r=(0,n.useAssistantApi)().attachment.source===`composer`,i=(0,n.useAssistantState)(Le),a=(0,n.useAssistantState)(Re),o=i&&`aui-attachment-root-composer only:[&>#attachment-tile]:size-24`,s;e[0]===o?s=e[1]:(s=P(`aui-attachment-root relative`,o),e[0]=o,e[1]=s);let c=r&&`aui-attachment-tile-composer border-foreground/20`,l;e[2]===c?l=e[3]:(l=P(`aui-attachment-tile size-14 cursor-pointer overflow-hidden rounded-[14px] border bg-muted transition-opacity hover:opacity-75`,c),e[2]=c,e[3]=l);let u=`${a} attachment`,d;e[4]===Symbol.for(`react.memo_cache_sentinel`)?(d=(0,f.jsx)(Oe,{}),e[4]=d):d=e[4];let p;e[5]!==l||e[6]!==u?(p=(0,f.jsx)(De,{children:(0,f.jsx)(xe,{asChild:!0,children:(0,f.jsx)(`div`,{className:l,role:`button`,id:`attachment-tile`,"aria-label":u,children:d})})}),e[5]=l,e[6]=u,e[7]=p):p=e[7];let m;e[8]===r?m=e[9]:(m=r&&(0,f.jsx)(Ae,{}),e[8]=r,e[9]=m);let h;e[10]!==s||e[11]!==p||e[12]!==m?(h=(0,f.jsxs)(n.AttachmentPrimitive.Root,{className:s,children:[p,m]}),e[10]=s,e[11]=p,e[12]=m,e[13]=h):h=e[13];let g;e[14]===Symbol.for(`react.memo_cache_sentinel`)?(g=(0,f.jsx)(Se,{side:`top`,children:(0,f.jsx)(n.AttachmentPrimitive.Name,{})}),e[14]=g):g=e[14];let _;return e[15]===h?_=e[16]:(_=(0,f.jsxs)(be,{children:[h,g]}),e[15]=h,e[16]=_),_},Ae=()=>{let e=(0,t.c)(1),r;return e[0]===Symbol.for(`react.memo_cache_sentinel`)?(r=(0,f.jsx)(n.AttachmentPrimitive.Remove,{asChild:!0,children:(0,f.jsx)(Z,{tooltip:`Remove file`,className:`aui-attachment-tile-remove absolute top-1.5 right-1.5 size-3.5 rounded-full bg-white text-muted-foreground opacity-100 shadow-sm hover:!bg-white [&_svg]:text-black hover:[&_svg]:text-destructive`,side:`top`,children:(0,f.jsx)(o.XIcon,{className:`aui-attachment-remove-icon size-3 dark:stroke-[2.5px]`})})}),e[0]=r):r=e[0],r},je=()=>{let e=(0,t.c)(1),r;return e[0]===Symbol.for(`react.memo_cache_sentinel`)?(r=(0,f.jsx)(`div`,{className:`aui-user-message-attachments-end col-span-full col-start-1 row-start-1 flex w-full flex-row justify-end gap-2`,children:(0,f.jsx)(n.MessagePrimitive.Attachments,{components:{Attachment:ke}})}),e[0]=r):r=e[0],r},Me=()=>{let e=(0,t.c)(1),r;return e[0]===Symbol.for(`react.memo_cache_sentinel`)?(r=(0,f.jsx)(`div`,{className:`aui-composer-attachments mb-2 flex w-full flex-row items-center gap-2 overflow-x-auto px-1.5 pt-0.5 pb-1 empty:hidden`,children:(0,f.jsx)(n.ComposerPrimitive.Attachments,{components:{Attachment:ke}})}),e[0]=r):r=e[0],r},Ne=()=>{let e=(0,t.c)(1),r;return e[0]===Symbol.for(`react.memo_cache_sentinel`)?(r=(0,f.jsx)(n.ComposerPrimitive.AddAttachment,{asChild:!0,children:(0,f.jsx)(Z,{tooltip:`Add Attachment`,side:`bottom`,variant:`ghost`,size:`icon`,className:`aui-composer-add-attachment size-[34px] rounded-full p-1 text-xs font-semibold hover:bg-muted-foreground/15 dark:border-muted-foreground/15 dark:hover:bg-muted-foreground/30`,"aria-label":`Add Attachment`,children:(0,f.jsx)(o.PlusIcon,{className:`aui-attachment-add-icon size-5 stroke-[1.5px]`})})}),e[0]=r):r=e[0],r};function Pe(e){return e.type===`image`}function Fe(e){let{attachment:t}=e;if(t.type!==`image`)return{};if(t.file)return{file:t.file};let n=t.content?.filter(Pe)[0]?.image;return n?{src:n}:{}}function Ie(e){let{attachment:t}=e;return t.type===`image`}function Le(e){let{attachment:t}=e;return t.type===`image`}function Re(e){let{attachment:t}=e,n=t.type;switch(n){case`image`:return`Image`;case`document`:return`Document`;case`file`:return`File`;default:{let e=n;throw Error(`Unknown attachment type: ${e}`)}}}let ze=(0,s.memo)(()=>{let e=(0,t.c)(1),n;return e[0]===Symbol.for(`react.memo_cache_sentinel`)?(n=(0,f.jsx)(y.MarkdownTextPrimitive,{remarkPlugins:[b.default],className:`aui-md`,components:He}),e[0]=n):n=e[0],n}),Be=e=>{let n=(0,t.c)(17),{language:r,code:i}=e,{isCopied:a,copyToClipboard:s}=Ve(),c;n[0]!==i||n[1]!==s||n[2]!==a?(c=()=>{!i||a||s(i)},n[0]=i,n[1]=s,n[2]=a,n[3]=c):c=n[3];let l=c,u;n[4]===r?u=n[5]:(u=(0,f.jsx)(`span`,{className:`aui-code-header-language lowercase [&>span]:text-xs`,children:r}),n[4]=r,n[5]=u);let d;n[6]===a?d=n[7]:(d=!a&&(0,f.jsx)(o.CopyIcon,{}),n[6]=a,n[7]=d);let p;n[8]===a?p=n[9]:(p=a&&(0,f.jsx)(o.CheckIcon,{}),n[8]=a,n[9]=p);let m;n[10]!==l||n[11]!==d||n[12]!==p?(m=(0,f.jsxs)(Z,{tooltip:`Copy`,onClick:l,children:[d,p]}),n[10]=l,n[11]=d,n[12]=p,n[13]=m):m=n[13];let h;return n[14]!==u||n[15]!==m?(h=(0,f.jsxs)(`div`,{className:`aui-code-header-root mt-2 flex items-center justify-between gap-2 rounded-t-lg bg-muted-foreground/15 px-2 py-1 text-sm font-semibold text-foreground dark:bg-muted-foreground/20`,children:[u,m]}),n[14]=u,n[15]=m,n[16]=h):h=n[16],h},Ve=e=>{let n=(0,t.c)(7),r;n[0]===e?r=n[1]:(r=e===void 0?{}:e,n[0]=e,n[1]=r);let{copiedDuration:i}=r,a=i===void 0?3e3:i,[o,c]=(0,s.useState)(!1),l;n[2]===a?l=n[3]:(l=e=>{e&&navigator.clipboard.writeText(e).then(()=>{c(!0),setTimeout(()=>c(!1),a)})},n[2]=a,n[3]=l);let u=l,d;return n[4]!==u||n[5]!==o?(d={isCopied:o,copyToClipboard:u},n[4]=u,n[5]=o,n[6]=d):d=n[6],d},He=(0,y.unstable_memoizeMarkdownComponents)({h1:({className:e,...t})=>(0,f.jsx)(`h1`,{className:P(`aui-md-h1 mb-4 scroll-m-20 text-[25px] font-extrabold tracking-tight last:mb-0`,e),...t}),h2:({className:e,...t})=>(0,f.jsx)(`h2`,{className:P(`aui-md-h2 mt-4 mb-2 scroll-m-20 text-[21px] font-semibold tracking-tight first:mt-0 last:mb-0`,e),...t}),h3:({className:e,...t})=>(0,f.jsx)(`h3`,{className:P(`aui-md-h3 mt-3 mb-2 scroll-m-20 text-[19px] font-semibold tracking-tight first:mt-0 last:mb-0`,e),...t}),h4:({className:e,...t})=>(0,f.jsx)(`h4`,{className:P(`aui-md-h4 mt-3 mb-2 scroll-m-20 text-[17px] font-semibold tracking-tight first:mt-0 last:mb-0`,e),...t}),h5:({className:e,...t})=>(0,f.jsx)(`h5`,{className:P(`aui-md-h5 my-2 text-[15px] font-semibold first:mt-0 last:mb-0`,e),...t}),h6:({className:e,...t})=>(0,f.jsx)(`h6`,{className:P(`aui-md-h6 my-2 text-[15px] font-semibold first:mt-0 last:mb-0`,e),...t}),p:({className:e,...t})=>(0,f.jsx)(`p`,{className:P(`aui-md-p mt-2 mb-2 text-[13px] leading-relaxed first:mt-0 last:mb-0`,e),...t}),a:({className:e,...t})=>(0,f.jsx)(`a`,{className:P(`aui-md-a text-[13px] font-medium text-primary underline underline-offset-4`,e),...t}),blockquote:({className:e,...t})=>(0,f.jsx)(`blockquote`,{className:P(`aui-md-blockquote text-[13px] border-l-2 pl-3 italic`,e),...t}),ul:({className:e,...t})=>(0,f.jsx)(`ul`,{className:P(`aui-md-ul text-[13px] my-2 ml-4 list-disc [&>li]:mt-1`,e),...t}),ol:({className:e,...t})=>(0,f.jsx)(`ol`,{className:P(`aui-md-ol text-[13px] my-2 ml-4 list-decimal [&>li]:mt-1`,e),...t}),hr:({className:e,...t})=>(0,f.jsx)(`hr`,{className:P(`aui-md-hr my-2 border-b`,e),...t}),table:({className:e,...t})=>(0,f.jsx)(`table`,{className:P(`aui-md-table text-[13px] my-2 w-full border-separate border-spacing-0 overflow-y-auto`,e),...t}),th:({className:e,...t})=>(0,f.jsx)(`th`,{className:P(`aui-md-th bg-muted px-2 py-1 text-left font-bold first:rounded-tl-lg last:rounded-tr-lg [&[align=center]]:text-center [&[align=right]]:text-right`,e),...t}),td:({className:e,...t})=>(0,f.jsx)(`td`,{className:P(`aui-md-td border-b border-l px-2 py-1 text-left last:border-r [&[align=center]]:text-center [&[align=right]]:text-right`,e),...t}),tr:({className:e,...t})=>(0,f.jsx)(`tr`,{className:P(`aui-md-tr m-0 border-b p-0 first:border-t [&:last-child>td:first-child]:rounded-bl-lg [&:last-child>td:last-child]:rounded-br-lg`,e),...t}),sup:({className:e,...t})=>(0,f.jsx)(`sup`,{className:P(`aui-md-sup [&>a]:text-xs [&>a]:no-underline`,e),...t}),pre:({className:e,...t})=>(0,f.jsx)(`pre`,{className:P(`aui-md-pre text-[13px] overflow-x-auto !rounded-t-none rounded-b-lg bg-black p-2 text-white`,e),...t}),code:function({className:e,...t}){return(0,f.jsx)(`code`,{className:P(!(0,y.useIsMarkdownCodeBlock)()&&`aui-md-inline-code text-[13px] rounded border bg-muted font-semibold`,e),...t})},CodeHeader:Be});function Ue(e,t=`http`){if(e.type===`tab`)return new C.TabClientTransport({targetOrigin:e.targetOrigin??window.location.origin,channelId:e.channelId??`mcp-default`});let n=new URL(e.url),r={Accept:`application/json, text/event-stream`,...e.customHeaders??{}};e.authToken&&(r.Authorization=`Bearer ${e.authToken}`);let i={requestInit:{headers:r}};return t===`sse`?new w.SSEClientTransport(n,i):new T.StreamableHTTPClientTransport(n,i)}let We=(0,s.createContext)(null);function Ge({children:e,autoConnectLocal:t=!0,onToolsChange:n}){let r=(0,s.useRef)(new Map),[,i]=(0,s.useState)({}),[a,o]=(0,s.useState)([]),c=(0,s.useCallback)(()=>{let e=[];r.current.forEach(t=>{t.tools.forEach(n=>{e.push({...n,_sourceId:t.id})})}),o(e)},[]),l=(0,s.useCallback)(e=>({id:e.id,config:e.config,state:e.state,error:e.error,tools:e.tools,resources:e.resources,resourceTemplates:e.resourceTemplates,prompts:e.prompts}),[]),u=(0,s.useCallback)(async(e,t)=>{r.current.has(e)&&await d(e);let n={id:e,config:t,state:`connecting`,error:null,tools:[],resources:[],resourceTemplates:[],prompts:[],client:null,transport:null};r.current.set(e,n),i({});try{let r=new x.Client({name:`MCP-Source-${e}`,version:`1.0.0`}),a=Ue(t);await r.connect(a),n.client=r,n.transport=a;let{tools:o}=await r.listTools();n.tools=o,n.state=`connected`,r.setNotificationHandler(S.ToolListChangedNotificationSchema,async()=>{try{n.tools=(await r.listTools()).tools,c(),i({})}catch(t){console.error(`[MCPToolsProvider:${e}] Failed to update tools:`,t)}}),c(),i({})}catch(t){let r=t instanceof Error?t:Error(String(t));console.error(`[MCPToolsProvider:${e}] Connection failed:`,r),n.state=`error`,n.error=r,i({})}},[c]),d=(0,s.useCallback)(async e=>{let t=r.current.get(e);if(t){if(t.client)try{await t.client.close()}catch(t){console.error(`[MCPToolsProvider:${e}] Error closing client:`,t)}if(t.transport)try{await t.transport.close()}catch(t){console.error(`[MCPToolsProvider:${e}] Error closing transport:`,t)}r.current.delete(e),c(),i({})}},[c]),p=(0,s.useCallback)(e=>{let t=r.current.get(e);return t?l(t):void 0},[l]),m=(0,s.useCallback)(e=>r.current.get(e)?.state===`connected`,[]),h=(0,s.useCallback)(async(e,t,n)=>{let i=r.current.get(e);if(!i?.client)throw Error(`Source '${e}' not connected`);return await i.client.callTool({name:t,arguments:n})},[]),g=(0,s.useCallback)(async(e,t)=>{let n=a.find(t=>t.name===e);if(!n)throw Error(`Tool '${e}' not found`);return h(n._sourceId,e,t)},[a,h]),_=(0,s.useMemo)(()=>{let e=new Map;return r.current.forEach(t=>{e.set(t.id,l(t))}),e},[a,l]);(0,s.useEffect)(()=>{if(t){let e=setTimeout(()=>{u(`local`,{type:`tab`})},100);return()=>clearTimeout(e)}},[t,u]),(0,s.useEffect)(()=>{n?.(a)},[a,n]),(0,s.useEffect)(()=>{let e=r;return()=>{e.current.forEach(e=>{e.client&&e.client.close().catch(console.error),e.transport&&e.transport.close().catch(console.error)}),e.current.clear()}},[]);let v=(0,s.useMemo)(()=>({tools:a,sources:_,addSource:u,removeSource:d,getSource:p,isConnected:m,callTool:g,callToolOnSource:h}),[a,_,u,d,p,m,g,h]);return(0,f.jsx)(We.Provider,{value:v,children:e})}function Ke(){let e=(0,s.useContext)(We);if(!e)throw Error(`useMCPTools must be used within an MCPToolsProvider`);return e}let qe=()=>{let{sources:e,addSource:t,removeSource:n}=Ke(),[r,i]=(0,s.useState)(!1),[a,c]=(0,s.useState)(``),[l,u]=(0,s.useState)(!1),[d,p]=(0,s.useState)(null),m=[];e.forEach((e,t)=>{e.config.type===`http`&&t!==`local`&&m.push({id:t,url:e.config.url})});let h=(0,s.useCallback)(async()=>{if(!a.trim()){p(`Please enter a URL`);return}try{new URL(a)}catch{p(`Please enter a valid URL`);return}u(!0),p(null);try{await t(m.length===0?`remote`:`remote-${Date.now()}`,{type:`http`,url:a}),c(``)}catch(e){p(e instanceof Error?e.message:`Failed to connect`)}finally{u(!1)}},[a,t,m.length]),g=(0,s.useCallback)(async e=>{await n(e)},[n]),_=(0,s.useCallback)(e=>{e.key===`Enter`&&!l&&h()},[h,l]),v=m.filter(t=>e.get(t.id)?.state===`connected`).length;return(0,f.jsxs)(de,{open:r,onOpenChange:i,children:[(0,f.jsx)(fe,{asChild:!0,children:(0,f.jsxs)(Z,{tooltip:`Connect MCP Server`,variant:`ghost`,size:`sm`,className:P(`gap-2 rounded-full text-muted-foreground hover:text-foreground`,v>0&&`text-green-600 dark:text-green-400`),children:[(0,f.jsx)(o.Plug,{className:`h-4 w-4`}),v>0&&(0,f.jsx)(`span`,{className:`text-xs`,children:v})]})}),(0,f.jsxs)(he,{className:`sm:max-w-md`,children:[(0,f.jsxs)(ge,{children:[(0,f.jsx)(_e,{children:`Remote MCP Servers`}),(0,f.jsx)(ve,{children:`Connect to remote MCP servers to access their tools, resources, and prompts.`})]}),(0,f.jsxs)(`div`,{className:`space-y-4`,children:[(0,f.jsxs)(`div`,{className:`space-y-2`,children:[(0,f.jsx)(`label`,{htmlFor:`mcp-url`,className:`text-sm font-medium`,children:`Server URL`}),(0,f.jsxs)(`div`,{className:`flex gap-2`,children:[(0,f.jsx)(`input`,{id:`mcp-url`,type:`url`,value:a,onChange:e=>c(e.target.value),onKeyDown:_,placeholder:`https://mcp.example.com/sse`,disabled:l,className:P(`flex h-9 w-full rounded-md border border-input bg-background px-3 py-1 text-sm shadow-sm transition-colors`,`placeholder:text-muted-foreground`,`focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring`,`disabled:cursor-not-allowed disabled:opacity-50`)}),(0,f.jsx)(X,{onClick:()=>void h(),disabled:l||!a.trim(),size:`sm`,className:`shrink-0`,children:l?(0,f.jsx)(o.Loader2,{className:`h-4 w-4 animate-spin`}):(0,f.jsx)(o.Plus,{className:`h-4 w-4`})})]}),d&&(0,f.jsx)(`p`,{className:`text-xs text-destructive`,children:d})]}),m.length>0&&(0,f.jsxs)(`div`,{className:`space-y-2`,children:[(0,f.jsx)(`label`,{className:`text-sm font-medium`,children:`Connected Servers`}),(0,f.jsx)(`div`,{className:`space-y-2`,children:m.map(t=>{let n=e.get(t.id),r=n?.state===`connected`,i=n?.state===`connecting`;return(0,f.jsxs)(`div`,{className:`flex items-center gap-2 rounded-md border border-border bg-muted/50 px-3 py-2`,children:[(0,f.jsx)(`div`,{className:P(`h-2 w-2 shrink-0 rounded-full`,r&&`bg-green-500`,i&&`bg-yellow-500 animate-pulse`,n?.state===`error`&&`bg-red-500`)}),(0,f.jsx)(`span`,{className:`flex-1 truncate text-xs text-muted-foreground`,children:t.url}),r&&n&&(0,f.jsxs)(`span`,{className:`text-xs text-muted-foreground`,children:[n.tools.length,` tools`]}),(0,f.jsx)(`button`,{type:`button`,onClick:()=>void g(t.id),className:`shrink-0 rounded p-1 text-muted-foreground hover:bg-destructive/10 hover:text-destructive`,"aria-label":`Disconnect server`,children:i?(0,f.jsx)(o.Loader2,{className:`h-3 w-3 animate-spin`}):(0,f.jsx)(o.X,{className:`h-3 w-3`})})]},t.id)})})]}),(0,f.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`Enter the URL of an MCP server that supports the Streamable HTTP transport (SSE).`})]})]})]})},Je=e=>{let n=(0,t.c)(15),{toolName:r,argsText:i,result:a}=e,[c,l]=(0,s.useState)(!0),u;n[0]===Symbol.for(`react.memo_cache_sentinel`)?(u=(0,f.jsx)(o.CheckIcon,{className:`aui-tool-fallback-icon size-3.5 text-emerald-500`}),n[0]=u):u=n[0];let d;n[1]===r?d=n[2]:(d=(0,f.jsx)(`p`,{className:`aui-tool-fallback-title flex-grow text-sm font-medium`,children:r}),n[1]=r,n[2]=d);let p;n[3]===c?p=n[4]:(p=(0,f.jsx)(X,{variant:`ghost`,size:`sm`,className:`h-6 w-6 p-0`,onClick:()=>l(!c),children:c?(0,f.jsx)(o.ChevronUpIcon,{className:`size-3.5`}):(0,f.jsx)(o.ChevronDownIcon,{className:`size-3.5`})}),n[3]=c,n[4]=p);let m;n[5]!==d||n[6]!==p?(m=(0,f.jsxs)(`div`,{className:`aui-tool-fallback-header flex items-center gap-2 px-3`,children:[u,d,p]}),n[5]=d,n[6]=p,n[7]=m):m=n[7];let h;n[8]!==i||n[9]!==c||n[10]!==a?(h=!c&&(0,f.jsxs)(`div`,{className:`aui-tool-fallback-content flex flex-col gap-2 border-t border-border/20 pt-2`,children:[(0,f.jsxs)(`div`,{className:`aui-tool-fallback-args-root px-3`,children:[(0,f.jsx)(`span`,{className:`text-[10px] font-medium uppercase tracking-wide text-muted-foreground/70`,children:`Input`}),(0,f.jsx)(`pre`,{className:`aui-tool-fallback-args-value mt-1 max-h-40 overflow-auto rounded-lg bg-muted/30 px-2 py-1.5 font-mono text-[11px] leading-relaxed text-foreground/80 whitespace-pre-wrap`,children:i})]}),a!==void 0&&(0,f.jsxs)(`div`,{className:`aui-tool-fallback-result-root border-t border-dashed border-border/20 px-3 pt-2`,children:[(0,f.jsx)(`span`,{className:`text-[10px] font-medium uppercase tracking-wide text-muted-foreground/70`,children:`Output`}),(0,f.jsx)(`pre`,{className:`aui-tool-fallback-result-content mt-1 max-h-60 overflow-auto rounded-lg bg-muted/30 px-2 py-1.5 font-mono text-[11px] leading-relaxed text-foreground/80 whitespace-pre-wrap`,children:typeof a==`string`?a:JSON.stringify(a,null,2)})]})]}),n[8]=i,n[9]=c,n[10]=a,n[11]=h):h=n[11];let g;return n[12]!==m||n[13]!==h?(g=(0,f.jsxs)(`div`,{className:`aui-tool-fallback-root mb-3 flex w-full flex-col gap-2 rounded-xl border border-border/20 bg-muted/5 py-2`,children:[m,h]}),n[12]=m,n[13]=h,n[14]=g):g=n[14],g},Ye=e=>{let n=(0,t.c)(54),r,i,a,o,c,l,u,d,p,m,h,g,_,v;n[0]===e?(r=n[1],i=n[2],a=n[3],o=n[4],c=n[5],l=n[6],u=n[7],d=n[8],p=n[9],m=n[10],h=n[11],g=n[12],_=n[13],v=n[14]):({active:c,processing:u,barWidth:d,barGap:p,barRadius:m,barColor:r,fadeEdges:h,fadeWidth:g,height:_,sensitivity:v,mode:l,manualAudioLevel:a,className:i,...o}=e,n[0]=e,n[1]=r,n[2]=i,n[3]=a,n[4]=o,n[5]=c,n[6]=l,n[7]=u,n[8]=d,n[9]=p,n[10]=m,n[11]=h,n[12]=g,n[13]=_,n[14]=v);let y=c===void 0?!1:c,b=u===void 0?!1:u,x=d===void 0?3:d,S=p===void 0?1:p,C=m===void 0?1.5:m,w=h===void 0?!0:h,T=g===void 0?24:g,E=_===void 0?64:_,D=v===void 0?1:v,O=l===void 0?`static`:l,k=(0,s.useRef)(null),A=(0,s.useRef)(null),j;n[15]===Symbol.for(`react.memo_cache_sentinel`)?(j=[],n[15]=j):j=n[15];let M=(0,s.useRef)(j);(0,s.useRef)(0);let N=(0,s.useRef)(0),F=(0,s.useRef)(null),I;n[16]===Symbol.for(`react.memo_cache_sentinel`)?(I=[],n[16]=I):I=n[16];let L=(0,s.useRef)(I),R=(0,s.useRef)(0),z;n[17]===Symbol.for(`react.memo_cache_sentinel`)?(z=[],n[17]=z):z=n[17];let B=(0,s.useRef)(z),V=(0,s.useRef)(!0),H=(0,s.useRef)(null),U=(0,s.useRef)(0),W=typeof E==`number`?`${E}px`:E,ee,te;n[18]===Symbol.for(`react.memo_cache_sentinel`)?(ee=()=>{let e=k.current,t=A.current;if(!e||!t)return;let n=new ResizeObserver(()=>{let n=t.getBoundingClientRect(),r=window.devicePixelRatio||1;e.width=n.width*r,e.height=n.height*r,e.style.width=`${n.width}px`,e.style.height=`${n.height}px`;let i=e.getContext(`2d`);i&&i.scale(r,r),H.current=null,U.current=n.width,V.current=!0});return n.observe(t),()=>n.disconnect()},te=[],n[18]=ee,n[19]=te):(ee=n[18],te=n[19]),(0,s.useEffect)(ee,te);let ne,re;n[20]!==y||n[21]!==S||n[22]!==x||n[23]!==O||n[24]!==b?(ne=()=>{if(b&&!y){let e=0;R.current=0;let t=()=>{e+=.03,R.current=Math.min(1,R.current+.02);let n=[],r=Math.floor((A.current?.getBoundingClientRect().width||200)/(x+S));if(O===`static`){let t=Math.floor(r/2);for(let i=0;i<r;i++){let r=(i-t)/t,a=1-Math.abs(r)*.4,o=Math.sin(e*1.5+r*3)*.25,s=Math.sin(e*.8-r*2)*.2,c=Math.cos(e*2+r)*.15,l=(.2+(o+s+c))*a,u=l;if(L.current.length>0&&R.current<1){let e=Math.min(i,L.current.length-1);u=(L.current[e]||0)*(1-R.current)+l*R.current}n.push(Math.max(.05,Math.min(1,u)))}}else for(let t=0;t<r;t++){let i=(t-r/2)/(r/2),a=1-Math.abs(i)*.4,o=Math.sin(e*1.5+t*.15)*.25,s=Math.sin(e*.8-t*.1)*.2,c=Math.cos(e*2+t*.05)*.15,l=(.2+(o+s+c))*a,u=l;if(L.current.length>0&&R.current<1){let e=Math.floor(t/r*L.current.length);u=(L.current[e]||0)*(1-R.current)+l*R.current}n.push(Math.max(.05,Math.min(1,u)))}O===`static`?B.current=n:M.current=n,V.current=!0,F.current=requestAnimationFrame(t)};return t(),()=>{F.current&&cancelAnimationFrame(F.current)}}if(!y&&!b&&(O===`static`?B.current.length>0:M.current.length>0)){let e=0,t=()=>{e+=.03,e<1?(O===`static`?B.current=B.current.map(t=>t*(1-e)):M.current=M.current.map(t=>t*(1-e)),V.current=!0,requestAnimationFrame(t)):O===`static`?B.current=[]:M.current=[]};t()}},re=[b,y,x,S,O],n[20]=y,n[21]=S,n[22]=x,n[23]=O,n[24]=b,n[25]=ne,n[26]=re):(ne=n[25],re=n[26]),(0,s.useEffect)(ne,re);let ie,ae;n[27]!==y||n[28]!==r||n[29]!==S||n[30]!==C||n[31]!==x||n[32]!==w||n[33]!==T||n[34]!==a||n[35]!==O||n[36]!==b||n[37]!==D?(ie=()=>{let e=k.current;if(!e)return;let t=e.getContext(`2d`);if(!t)return;let n,i=o=>{let s=e.getBoundingClientRect();if(y&&o-N.current>30&&(N.current=o,a!==void 0)){let e=Math.max(.05,Math.min(1,a*D));if(O===`static`){let t=Math.floor(s.width/(x+S)),n=Math.floor(t/2),r=[];for(let t=n-1;t>=0;t--){let i=e*(1-Math.abs(t-n/2)/(n/2)*.3);r.push(Math.max(.05,i))}for(let t=0;t<n;t++){let i=e*(1-Math.abs(t-n/2)/(n/2)*.3);r.push(Math.max(.05,i))}B.current=r,L.current=r}else M.current.push(e),L.current=[...M.current],M.current.length>60&&M.current.shift();V.current=!0}if(!V.current&&!y){n=requestAnimationFrame(i);return}V.current=y,t.clearRect(0,0,s.width,s.height);let c=r||(()=>getComputedStyle(e).color||`#000`)(),l=x+S,u=Math.floor(s.width/l),d=s.height/2;if(O===`static`){let e=b||y||B.current.length>0?B.current:[];for(let n=0;n<u&&n<e.length;n++){let r=e[n]||.1,i=n*l,a=Math.max(4,r*s.height*.8),o=d-a/2;t.fillStyle=c,t.globalAlpha=.4+r*.6,C>0?(t.beginPath(),t.roundRect(i,o,x,a,C),t.fill()):t.fillRect(i,o,x,a)}}else for(let e=0;e<u&&e<M.current.length;e++){let n=M.current.length-1-e,r=M.current[n]||.1,i=s.width-(e+1)*l,a=Math.max(4,r*s.height*.8),o=d-a/2;t.fillStyle=c,t.globalAlpha=.4+r*.6,C>0?(t.beginPath(),t.roundRect(i,o,x,a,C),t.fill()):t.fillRect(i,o,x,a)}if(w&&T>0&&s.width>0){if(!H.current||U.current!==s.width){let e=t.createLinearGradient(0,0,s.width,0),n=Math.min(.3,T/s.width);e.addColorStop(0,`rgba(255,255,255,1)`),e.addColorStop(n,`rgba(255,255,255,0)`),e.addColorStop(1-n,`rgba(255,255,255,0)`),e.addColorStop(1,`rgba(255,255,255,1)`),H.current=e,U.current=s.width}t.globalCompositeOperation=`destination-out`,t.fillStyle=H.current,t.fillRect(0,0,s.width,s.height),t.globalCompositeOperation=`source-over`}t.globalAlpha=1,n=requestAnimationFrame(i)};return n=requestAnimationFrame(i),()=>{n&&cancelAnimationFrame(n)}},ae=[y,b,D,x,S,C,r,w,T,O,a,60,30],n[27]=y,n[28]=r,n[29]=S,n[30]=C,n[31]=x,n[32]=w,n[33]=T,n[34]=a,n[35]=O,n[36]=b,n[37]=D,n[38]=ie,n[39]=ae):(ie=n[38],ae=n[39]),(0,s.useEffect)(ie,ae);let G;n[40]===i?G=n[41]:(G=P(`relative h-full w-full`,i),n[40]=i,n[41]=G);let oe;n[42]===W?oe=n[43]:(oe={height:W},n[42]=W,n[43]=oe);let K=y?`Live audio waveform`:b?`Processing audio`:`Audio waveform idle`,q;n[44]!==y||n[45]!==b?(q=!y&&!b&&(0,f.jsx)(`div`,{className:`border-muted-foreground/20 absolute top-1/2 right-0 left-0 -translate-y-1/2 border-t-2 border-dotted`}),n[44]=y,n[45]=b,n[46]=q):q=n[46];let J;n[47]===Symbol.for(`react.memo_cache_sentinel`)?(J=(0,f.jsx)(`canvas`,{className:`block h-full w-full`,ref:k}),n[47]=J):J=n[47];let Y;return n[48]!==o||n[49]!==G||n[50]!==oe||n[51]!==K||n[52]!==q?(Y=(0,f.jsxs)(`div`,{className:G,ref:A,style:oe,"aria-label":K,role:`img`,...o,children:[q,J]}),n[48]=o,n[49]=G,n[50]=oe,n[51]=K,n[52]=q,n[53]=Y):Y=n[53],Y};function Xe(e){let n=(0,t.c)(65),{isActive:r,isConnecting:i,isMuted:a,audioLevel:s,toolCall:c,onStart:l,onStop:u,onToggleMute:d,className:p}=e,m=s?.micLevel??0,h=s?.speakerLevel??0,g=c?.status===`started`?`calling`:c?.status===`completed`?c.error?`error`:`success`:`idle`,_;n[0]===g?_=n[1]:(_=()=>{switch(g){case`calling`:return`border-blue-500/60 shadow-[0_0_12px_rgba(59,130,246,0.3)]`;case`success`:return`border-green-500/60 shadow-[0_0_12px_rgba(34,197,94,0.3)]`;case`error`:return`border-red-500/60 shadow-[0_0_12px_rgba(239,68,68,0.3)]`;default:return`border-border`}},n[0]=g,n[1]=_);let v=_;if(!r&&!i){let e;n[2]===p?e=n[3]:(e=P(`flex items-center`,p),n[2]=p,n[3]=e);let t,r;n[4]===Symbol.for(`react.memo_cache_sentinel`)?(t=(0,f.jsx)(o.Phone,{className:`h-4 w-4`}),r=(0,f.jsx)(`span`,{className:`text-xs`,children:`Voice`}),n[4]=t,n[5]=r):(t=n[4],r=n[5]);let i;n[6]===l?i=n[7]:(i=(0,f.jsxs)(X,{variant:`outline`,size:`sm`,onClick:l,className:`gap-2 rounded-full`,"aria-label":`Start voice session`,children:[t,r]}),n[6]=l,n[7]=i);let a;return n[8]!==e||n[9]!==i?(a=(0,f.jsx)(`div`,{className:e,children:i}),n[8]=e,n[9]=i,n[10]=a):a=n[10],a}let y;n[11]!==p||n[12]!==v?(y=P(`flex items-center gap-3 rounded-full border bg-background/95 px-3 py-2 backdrop-blur-sm transition-all duration-300`,v(),p),n[11]=p,n[12]=v,n[13]=y):y=n[13];let b=a?`bg-muted text-muted-foreground`:`bg-primary/10 text-primary`,x;n[14]===b?x=n[15]:(x=P(`flex h-8 w-8 items-center justify-center rounded-full transition-colors`,b),n[14]=b,n[15]=x);let S;n[16]===a?S=n[17]:(S=a?(0,f.jsx)(o.MicOff,{className:`h-4 w-4`}):(0,f.jsx)(o.Mic,{className:`h-4 w-4`}),n[16]=a,n[17]=S);let C;n[18]!==x||n[19]!==S?(C=(0,f.jsx)(`div`,{className:x,children:S}),n[18]=x,n[19]=S,n[20]=C):C=n[20];let w=r&&!a,T;n[21]!==i||n[22]!==m||n[23]!==w?(T=(0,f.jsx)(`div`,{className:`h-6 w-16`,children:(0,f.jsx)(Ye,{active:w,processing:i,manualAudioLevel:m,barWidth:2,barGap:1,barRadius:2,barColor:`hsl(var(--primary))`,height:24,mode:`static`,sensitivity:2,fadeEdges:!1})}),n[21]=i,n[22]=m,n[23]=w,n[24]=T):T=n[24];let E;n[25]!==C||n[26]!==T?(E=(0,f.jsxs)(`div`,{className:`flex items-center gap-2`,children:[C,T]}),n[25]=C,n[26]=T,n[27]=E):E=n[27];let D;n[28]===Symbol.for(`react.memo_cache_sentinel`)?(D=(0,f.jsx)(`div`,{className:`h-6 w-px bg-border`}),n[28]=D):D=n[28];let O;n[29]!==r||n[30]!==i||n[31]!==h?(O=(0,f.jsx)(`div`,{className:`h-6 w-16`,children:(0,f.jsx)(Ye,{active:r,processing:i,manualAudioLevel:h,barWidth:2,barGap:1,barRadius:2,barColor:`hsl(var(--muted-foreground))`,height:24,mode:`static`,sensitivity:2,fadeEdges:!1})}),n[29]=r,n[30]=i,n[31]=h,n[32]=O):O=n[32];let k;n[33]===Symbol.for(`react.memo_cache_sentinel`)?(k=(0,f.jsx)(`div`,{className:P(`flex h-8 w-8 items-center justify-center rounded-full bg-muted text-muted-foreground`),children:(0,f.jsx)(o.Volume2,{className:`h-4 w-4`})}),n[33]=k):k=n[33];let A;n[34]===O?A=n[35]:(A=(0,f.jsxs)(`div`,{className:`flex items-center gap-2`,children:[O,k]}),n[34]=O,n[35]=A);let j;n[36]===Symbol.for(`react.memo_cache_sentinel`)?(j=(0,f.jsx)(`div`,{className:`h-6 w-px bg-border`}),n[36]=j):j=n[36];let M=!r,N=a&&`text-destructive hover:text-destructive`,F;n[37]===N?F=n[38]:(F=P(`h-8 w-8 rounded-full`,N),n[37]=N,n[38]=F);let I=a?`Unmute microphone`:`Mute microphone`,L;n[39]===a?L=n[40]:(L=a?(0,f.jsx)(o.MicOff,{className:`h-4 w-4`}):(0,f.jsx)(o.Mic,{className:`h-4 w-4`}),n[39]=a,n[40]=L);let R;n[41]!==d||n[42]!==M||n[43]!==F||n[44]!==I||n[45]!==L?(R=(0,f.jsx)(X,{variant:`ghost`,size:`icon`,onClick:d,disabled:M,className:F,"aria-label":I,children:L}),n[41]=d,n[42]=M,n[43]=F,n[44]=I,n[45]=L,n[46]=R):R=n[46];let z;n[47]===Symbol.for(`react.memo_cache_sentinel`)?(z=(0,f.jsx)(o.PhoneOff,{className:`h-4 w-4`}),n[47]=z):z=n[47];let B;n[48]===u?B=n[49]:(B=(0,f.jsx)(X,{variant:`ghost`,size:`icon`,onClick:u,className:`h-8 w-8 rounded-full text-destructive hover:bg-destructive/10 hover:text-destructive`,"aria-label":`End voice session`,children:z}),n[48]=u,n[49]=B);let V;n[50]!==R||n[51]!==B?(V=(0,f.jsxs)(`div`,{className:`flex items-center gap-1`,children:[R,B]}),n[50]=R,n[51]=B,n[52]=V):V=n[52];let H;n[53]!==c||n[54]!==g?(H=c&&g!==`idle`&&(0,f.jsxs)(`div`,{className:P(`ml-1 flex items-center gap-1 rounded-full px-2 py-0.5 text-xs`,g===`calling`&&`bg-blue-500/10 text-blue-600`,g===`success`&&`bg-green-500/10 text-green-600`,g===`error`&&`bg-red-500/10 text-red-600`),children:[(0,f.jsx)(`span`,{className:P(`h-1.5 w-1.5 rounded-full`,g===`calling`&&`animate-pulse bg-blue-500`,g===`success`&&`bg-green-500`,g===`error`&&`bg-red-500`)}),(0,f.jsx)(`span`,{className:`max-w-[80px] truncate`,children:c.toolName})]}),n[53]=c,n[54]=g,n[55]=H):H=n[55];let U;n[56]===i?U=n[57]:(U=i&&(0,f.jsxs)(`div`,{className:`ml-1 flex items-center gap-1 text-xs text-muted-foreground`,children:[(0,f.jsx)(`span`,{className:`h-1.5 w-1.5 animate-pulse rounded-full bg-amber-500`}),(0,f.jsx)(`span`,{children:`Connecting...`})]}),n[56]=i,n[57]=U);let W;return n[58]!==A||n[59]!==y||n[60]!==V||n[61]!==H||n[62]!==U||n[63]!==E?(W=(0,f.jsxs)(`div`,{className:y,children:[E,D,A,j,V,H,U]}),n[58]=A,n[59]=y,n[60]=V,n[61]=H,n[62]=U,n[63]=E,n[64]=W):W=n[64],W}let Ze=()=>(0,f.jsx)(c.LazyMotion,{features:c.domAnimation,children:(0,f.jsx)(c.MotionConfig,{reducedMotion:`user`,children:(0,f.jsx)(n.ThreadPrimitive.Root,{className:`aui-root aui-thread-root app-shell @container relative flex h-full flex-col bg-background/50`,style:{"--thread-max-width":`100%`},children:(0,f.jsxs)(n.ThreadPrimitive.Viewport,{className:`aui-thread-viewport relative flex flex-1 flex-col overflow-x-auto overflow-y-scroll px-4`,children:[(0,f.jsx)(n.ThreadPrimitive.If,{empty:!0,children:(0,f.jsx)(tt,{})}),(0,f.jsx)(n.ThreadPrimitive.Messages,{components:{UserMessage:ot,EditComposer:ct,AssistantMessage:it}}),(0,f.jsx)(n.ThreadPrimitive.If,{empty:!1,children:(0,f.jsx)(`div`,{className:`aui-thread-viewport-spacer min-h-8 grow`})}),(0,f.jsx)(Qe,{})]})})})}),Qe=()=>{let e=(0,t.c)(8),n=se(),r;e[0]===Symbol.for(`react.memo_cache_sentinel`)?(r=(0,f.jsx)(et,{}),e[0]=r):r=e[0];let i;e[1]===n?i=e[2]:(i=n?.isSupported&&(n.isActive||n.isConnecting)&&(0,f.jsx)(l.div,{initial:{opacity:0,y:20},animate:{opacity:1,y:0},exit:{opacity:0,y:-10},transition:{duration:.2},className:`flex justify-center`,children:(0,f.jsx)(Xe,{isActive:n.isActive,isConnecting:n.isConnecting,isMuted:n.isMuted,audioLevel:n.audioLevel,toolCall:n.toolCall,onStart:n.startSession,onStop:n.stopSession,onToggleMute:()=>n.toggleMute()})}),e[1]=n,e[2]=i);let a;e[3]===i?a=e[4]:(a=(0,f.jsx)(c.AnimatePresence,{children:i}),e[3]=i,e[4]=a);let o;e[5]===Symbol.for(`react.memo_cache_sentinel`)?(o=(0,f.jsx)($e,{}),e[5]=o):o=e[5];let s;return e[6]===a?s=e[7]:(s=(0,f.jsxs)(`div`,{className:`aui-composer-wrapper sticky bottom-0 mx-auto flex w-full max-w-[var(--thread-max-width)] flex-col gap-4 overflow-visible rounded-t-3xl pb-4 md:pb-6`,children:[r,a,o]}),e[6]=a,e[7]=s),s},$e=()=>{let e=(0,t.c)(13),r=se(),i,a,s;e[0]===Symbol.for(`react.memo_cache_sentinel`)?(i=P(`aui-composer-root group/composer flex w-full flex-col overflow-hidden rounded-2xl px-3 py-2`,`border border-border/40 shadow-sm backdrop-blur-md`,`bg-background/80`,`transition-all duration-200`,`focus-within:border-ring/50 focus-within:shadow-md`,`hover:border-border/60`),a=(0,f.jsx)(Me,{}),s=(0,f.jsx)(n.ComposerPrimitive.Input,{placeholder:`Send a message...`,className:`aui-composer-input mt-2 max-h-24 w-full resize-none bg-transparent px-0 py-2 text-sm leading-relaxed text-foreground placeholder:text-muted-foreground/70 focus-visible:outline-none focus-visible:ring-0`,rows:1,autoFocus:!0,"aria-label":`Message input`}),e[0]=i,e[1]=a,e[2]=s):(i=e[0],a=e[1],s=e[2]);let c,l;e[3]===Symbol.for(`react.memo_cache_sentinel`)?(c=(0,f.jsx)(Ne,{}),l=(0,f.jsx)(qe,{}),e[3]=c,e[4]=l):(c=e[3],l=e[4]);let u;e[5]===r?u=e[6]:(u=r?.isSupported&&(0,f.jsxs)(X,{variant:`ghost`,size:`sm`,onClick:()=>r.startSession(),className:`gap-2 rounded-full text-muted-foreground hover:text-foreground`,"aria-label":`Start voice session`,children:[(0,f.jsx)(o.Phone,{className:`h-4 w-4`}),(0,f.jsx)(`span`,{className:`text-xs`,children:`Voice`})]}),e[5]=r,e[6]=u);let d;e[7]===u?d=e[8]:(d=(0,f.jsxs)(`div`,{className:`flex items-center gap-2`,children:[c,l,u]}),e[7]=u,e[8]=d);let p;e[9]===Symbol.for(`react.memo_cache_sentinel`)?(p=(0,f.jsx)(n.ThreadPrimitive.If,{running:!1,children:(0,f.jsx)(n.ComposerPrimitive.Send,{asChild:!0,children:(0,f.jsx)(Z,{tooltip:`Send message`,side:`top`,type:`submit`,variant:`ghost`,size:`icon`,className:`aui-composer-send size-8 shrink-0 rounded-full border border-primary/60 bg-primary px-0 text-primary-foreground shadow-[0_12px_24px_-16px_rgba(37,99,235,0.55)] transition-shadow hover:shadow-[0_14px_24px_-14px_rgba(37,99,235,0.6)] focus-visible:ring-2 focus-visible:ring-primary/40`,"aria-label":`Send message`,children:(0,f.jsx)(o.ArrowUpIcon,{className:`aui-composer-send-icon size-4`})})})}),e[9]=p):p=e[9];let m;e[10]===Symbol.for(`react.memo_cache_sentinel`)?(m=(0,f.jsxs)(`div`,{className:`flex items-center gap-1.5`,children:[p,(0,f.jsx)(n.ThreadPrimitive.If,{running:!0,children:(0,f.jsx)(n.ComposerPrimitive.Cancel,{asChild:!0,children:(0,f.jsx)(Z,{tooltip:`Stop generating`,side:`top`,type:`button`,variant:`ghost`,size:`icon`,className:`aui-composer-cancel size-8 shrink-0 rounded-full border border-destructive/60 bg-destructive px-0 text-destructive-foreground shadow-[0_12px_24px_-18px_rgba(220,38,38,0.55)] transition-shadow hover:shadow-[0_14px_24px_-16px_rgba(220,38,38,0.6)] focus-visible:ring-2 focus-visible:ring-destructive/40`,"aria-label":`Stop generating`,children:(0,f.jsx)(o.Square,{className:`aui-composer-cancel-icon size-3.5`})})})})]}),e[10]=m):m=e[10];let h;return e[11]===d?h=e[12]:(h=(0,f.jsxs)(n.ComposerPrimitive.Root,{className:i,children:[a,s,(0,f.jsxs)(`div`,{className:`aui-composer-action-wrapper mt-2 flex items-center justify-between text-muted-foreground`,children:[d,m]})]}),e[11]=d,e[12]=h),h},et=()=>{let e=(0,t.c)(1),r;return e[0]===Symbol.for(`react.memo_cache_sentinel`)?(r=(0,f.jsx)(n.ThreadPrimitive.ScrollToBottom,{asChild:!0,children:(0,f.jsx)(Z,{tooltip:`Scroll to bottom`,variant:`outline`,className:`aui-thread-scroll-to-bottom absolute -top-12 z-10 self-center rounded-full p-4 disabled:invisible dark:bg-background dark:hover:bg-accent`,children:(0,f.jsx)(o.ArrowDownIcon,{})})}),e[0]=r):r=e[0],r},tt=()=>{let e=(0,t.c)(2),n;e[0]===Symbol.for(`react.memo_cache_sentinel`)?(n=(0,f.jsx)(l.div,{initial:{opacity:0,y:10},animate:{opacity:1,y:0},exit:{opacity:0,y:10},className:`aui-thread-welcome-message-motion-1 text-3xl font-bold tracking-tight`,children:`Hello there!`}),e[0]=n):n=e[0];let r;return e[1]===Symbol.for(`react.memo_cache_sentinel`)?(r=(0,f.jsxs)(`div`,{className:`aui-thread-welcome-root mx-auto my-auto flex w-full max-w-[var(--thread-max-width)] flex-grow flex-col`,children:[(0,f.jsx)(`div`,{className:`aui-thread-welcome-center flex w-full flex-grow flex-col items-center justify-center`,children:(0,f.jsxs)(`div`,{className:`aui-thread-welcome-message flex size-full flex-col justify-center px-8`,children:[n,(0,f.jsx)(l.div,{initial:{opacity:0,y:10},animate:{opacity:1,y:0},exit:{opacity:0,y:10},transition:{delay:.1},className:`aui-thread-welcome-message-motion-2 mt-2 text-lg text-muted-foreground`,children:`How can I help you today?`})]})}),(0,f.jsx)(nt,{})]}),e[1]=r):r=e[1],r},nt=()=>{let e=(0,t.c)(1),n;return e[0]===Symbol.for(`react.memo_cache_sentinel`)?(n=(0,f.jsx)(`div`,{className:`aui-thread-welcome-suggestions grid w-full gap-2 pb-4 @md:grid-cols-2`,children:[{title:`What's the weather`,label:`in San Francisco?`,action:`What's the weather in San Francisco?`},{title:`Explain React hooks`,label:`like useState and useEffect`,action:`Explain React hooks like useState and useEffect`},{title:`Write a SQL query`,label:`to find top customers`,action:`Write a SQL query to find top customers`},{title:`Create a meal plan`,label:`for healthy weight loss`,action:`Create a meal plan for healthy weight loss`}].map(ut)}),e[0]=n):n=e[0],n},rt=()=>{let e=(0,t.c)(1),r;return e[0]===Symbol.for(`react.memo_cache_sentinel`)?(r=(0,f.jsx)(n.MessagePrimitive.Error,{children:(0,f.jsx)(n.ErrorPrimitive.Root,{className:`aui-message-error-root mt-2 rounded-md border border-destructive bg-destructive/10 p-3 text-sm text-destructive dark:bg-destructive/5 dark:text-red-200`,children:(0,f.jsx)(n.ErrorPrimitive.Message,{className:`aui-message-error-message line-clamp-2`})})}),e[0]=r):r=e[0],r},it=()=>{let e=(0,t.c)(2),r;e[0]===Symbol.for(`react.memo_cache_sentinel`)?(r=(0,f.jsxs)(`div`,{className:`aui-assistant-message-content mx-2 leading-7 break-words text-foreground`,children:[(0,f.jsx)(n.MessagePrimitive.Parts,{components:{Text:ze,tools:{Fallback:Je}}}),(0,f.jsx)(rt,{})]}),e[0]=r):r=e[0];let i;return e[1]===Symbol.for(`react.memo_cache_sentinel`)?(i=(0,f.jsx)(n.MessagePrimitive.Root,{asChild:!0,children:(0,f.jsxs)(`div`,{className:`aui-assistant-message-root relative mx-auto w-full max-w-[var(--thread-max-width)] animate-in py-4 duration-200 fade-in slide-in-from-bottom-1 last:mb-24`,"data-role":`assistant`,children:[r,(0,f.jsxs)(`div`,{className:`aui-assistant-message-footer mt-2 ml-2 flex`,children:[(0,f.jsx)(lt,{}),(0,f.jsx)(at,{})]})]})}),e[1]=i):i=e[1],i},at=()=>{let e=(0,t.c)(3),r;e[0]===Symbol.for(`react.memo_cache_sentinel`)?(r=(0,f.jsx)(n.MessagePrimitive.If,{copied:!0,children:(0,f.jsx)(o.CheckIcon,{})}),e[0]=r):r=e[0];let i;e[1]===Symbol.for(`react.memo_cache_sentinel`)?(i=(0,f.jsx)(n.ActionBarPrimitive.Copy,{asChild:!0,children:(0,f.jsxs)(Z,{tooltip:`Copy`,children:[r,(0,f.jsx)(n.MessagePrimitive.If,{copied:!1,children:(0,f.jsx)(o.CopyIcon,{})})]})}),e[1]=i):i=e[1];let a;return e[2]===Symbol.for(`react.memo_cache_sentinel`)?(a=(0,f.jsxs)(n.ActionBarPrimitive.Root,{hideWhenRunning:!0,autohide:`not-last`,autohideFloat:`single-branch`,className:`aui-assistant-action-bar-root col-start-3 row-start-2 -ml-1 flex gap-1 text-muted-foreground data-floating:absolute data-floating:rounded-md data-floating:border data-floating:bg-background data-floating:p-1 data-floating:shadow-sm`,children:[i,(0,f.jsx)(n.ActionBarPrimitive.Reload,{asChild:!0,children:(0,f.jsx)(Z,{tooltip:`Refresh`,children:(0,f.jsx)(o.RefreshCwIcon,{})})})]}),e[2]=a):a=e[2],a},ot=()=>{let e=(0,t.c)(3),r;e[0]===Symbol.for(`react.memo_cache_sentinel`)?(r=(0,f.jsx)(je,{}),e[0]=r):r=e[0];let i;e[1]===Symbol.for(`react.memo_cache_sentinel`)?(i=(0,f.jsx)(`div`,{className:`aui-user-message-content rounded-2xl rounded-tr-sm bg-primary text-primary-foreground px-4 py-3 text-sm leading-relaxed shadow-sm`,children:(0,f.jsx)(n.MessagePrimitive.Parts,{})}),e[1]=i):i=e[1];let a;return e[2]===Symbol.for(`react.memo_cache_sentinel`)?(a=(0,f.jsx)(n.MessagePrimitive.Root,{asChild:!0,children:(0,f.jsxs)(`div`,{className:`aui-user-message-root mx-auto grid w-full max-w-[var(--thread-max-width)] animate-in auto-rows-auto grid-cols-[minmax(72px,1fr)_auto] gap-y-2 px-2 py-4 duration-200 fade-in slide-in-from-bottom-1 first:mt-3 last:mb-5 [&:where(>*)]:col-start-2`,"data-role":`user`,children:[r,(0,f.jsxs)(`div`,{className:`aui-user-message-content-wrapper relative col-start-2 min-w-0 max-w-[85%]`,children:[i,(0,f.jsx)(`div`,{className:`aui-user-action-bar-wrapper absolute top-1/2 left-0 -translate-x-full -translate-y-1/2 pr-2`,children:(0,f.jsx)(st,{})})]}),(0,f.jsx)(lt,{className:`aui-user-branch-picker col-span-full col-start-1 row-start-3 -mr-1 justify-end`})]})}),e[2]=a):a=e[2],a},st=()=>{let e=(0,t.c)(1),r;return e[0]===Symbol.for(`react.memo_cache_sentinel`)?(r=(0,f.jsx)(n.ActionBarPrimitive.Root,{hideWhenRunning:!0,autohide:`not-last`,className:`aui-user-action-bar-root flex flex-col items-end`,children:(0,f.jsx)(n.ActionBarPrimitive.Edit,{asChild:!0,children:(0,f.jsx)(Z,{tooltip:`Edit`,className:`aui-user-action-edit p-4`,children:(0,f.jsx)(o.PencilIcon,{})})})}),e[0]=r):r=e[0],r},ct=()=>{let e=(0,t.c)(3),r;e[0]===Symbol.for(`react.memo_cache_sentinel`)?(r=(0,f.jsx)(n.ComposerPrimitive.Input,{className:`aui-edit-composer-input flex min-h-[60px] w-full resize-none bg-transparent p-4 text-foreground outline-none`,autoFocus:!0}),e[0]=r):r=e[0];let i;e[1]===Symbol.for(`react.memo_cache_sentinel`)?(i=(0,f.jsx)(n.ComposerPrimitive.Cancel,{asChild:!0,children:(0,f.jsx)(X,{variant:`ghost`,size:`sm`,"aria-label":`Cancel edit`,children:`Cancel`})}),e[1]=i):i=e[1];let a;return e[2]===Symbol.for(`react.memo_cache_sentinel`)?(a=(0,f.jsx)(`div`,{className:`aui-edit-composer-wrapper mx-auto flex w-full max-w-[var(--thread-max-width)] flex-col gap-4 px-2 first:mt-4`,children:(0,f.jsxs)(n.ComposerPrimitive.Root,{className:`aui-edit-composer-root ml-auto flex w-full max-w-7/8 flex-col rounded-xl bg-muted`,children:[r,(0,f.jsxs)(`div`,{className:`aui-edit-composer-footer mx-3 mb-3 flex items-center justify-center gap-2 self-end`,children:[i,(0,f.jsx)(n.ComposerPrimitive.Send,{asChild:!0,children:(0,f.jsx)(X,{size:`sm`,"aria-label":`Update message`,children:`Update`})})]})]})}),e[2]=a):a=e[2],a},lt=e=>{let r=(0,t.c)(12),i,a;r[0]===e?(i=r[1],a=r[2]):({className:i,...a}=e,r[0]=e,r[1]=i,r[2]=a);let s;r[3]===i?s=r[4]:(s=P(`aui-branch-picker-root mr-2 -ml-2 inline-flex items-center text-xs text-muted-foreground`,i),r[3]=i,r[4]=s);let c;r[5]===Symbol.for(`react.memo_cache_sentinel`)?(c=(0,f.jsx)(n.BranchPickerPrimitive.Previous,{asChild:!0,children:(0,f.jsx)(Z,{tooltip:`Previous`,children:(0,f.jsx)(o.ChevronLeftIcon,{})})}),r[5]=c):c=r[5];let l;r[6]===Symbol.for(`react.memo_cache_sentinel`)?(l=(0,f.jsx)(n.BranchPickerPrimitive.Number,{}),r[6]=l):l=r[6];let u;r[7]===Symbol.for(`react.memo_cache_sentinel`)?(u=(0,f.jsxs)(`span`,{className:`aui-branch-picker-state font-medium`,children:[l,` / `,(0,f.jsx)(n.BranchPickerPrimitive.Count,{})]}),r[7]=u):u=r[7];let d;r[8]===Symbol.for(`react.memo_cache_sentinel`)?(d=(0,f.jsx)(n.BranchPickerPrimitive.Next,{asChild:!0,children:(0,f.jsx)(Z,{tooltip:`Next`,children:(0,f.jsx)(o.ChevronRightIcon,{})})}),r[8]=d):d=r[8];let p;return r[9]!==a||r[10]!==s?(p=(0,f.jsxs)(n.BranchPickerPrimitive.Root,{hideWhenSingleBranch:!0,className:s,...a,children:[c,u,d]}),r[9]=a,r[10]=s,r[11]=p):p=r[11],p};function ut(e,t){return(0,f.jsx)(l.div,{initial:{opacity:0,y:20},animate:{opacity:1,y:0},exit:{opacity:0,y:20},transition:{delay:.05*t},className:`aui-thread-welcome-suggestion-display [&:nth-child(n+3)]:hidden @md:[&:nth-child(n+3)]:block`,children:(0,f.jsx)(n.ThreadPrimitive.Suggestion,{prompt:e.action,send:!0,asChild:!0,children:(0,f.jsxs)(X,{variant:`outline`,className:`aui-thread-welcome-suggestion h-auto w-full flex-1 flex-wrap items-start justify-start gap-1 rounded-xl border-border/50 bg-background/50 px-4 py-3 text-left text-sm transition-colors hover:bg-accent/50 hover:border-accent @md:flex-col`,"aria-label":e.action,children:[(0,f.jsx)(`span`,{className:`aui-thread-welcome-suggestion-text-1 font-medium text-foreground`,children:e.title}),(0,f.jsx)(`span`,{className:`aui-thread-welcome-suggestion-text-2 text-muted-foreground text-xs`,children:e.label})]})})},`suggested-action-${e.title}-${t}`)}let dt=()=>{let e=(0,t.c)(2),r;e[0]===Symbol.for(`react.memo_cache_sentinel`)?(r=(0,f.jsx)(n.AssistantModalPrimitive.Anchor,{className:`aui-root aui-modal-anchor fixed right-6 bottom-6 size-14`,children:(0,f.jsx)(n.AssistantModalPrimitive.Trigger,{asChild:!0,children:(0,f.jsx)(ft,{})})}),e[0]=r):r=e[0];let i;return e[1]===Symbol.for(`react.memo_cache_sentinel`)?(i=(0,f.jsxs)(n.AssistantModalPrimitive.Root,{children:[r,(0,f.jsx)(n.AssistantModalPrimitive.Content,{sideOffset:16,className:`aui-root aui-modal-content z-50 h-[600px] w-[500px] overflow-clip overscroll-contain rounded-2xl border border-border/50 bg-popover/95 backdrop-blur-xl p-0 text-popover-foreground shadow-2xl outline-none data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:slide-out-to-bottom-1/2 data-[state=closed]:slide-out-to-right-1/2 data-[state=closed]:zoom-out-95 data-[state=open]:animate-in data-[state=open]:fade-in-0 data-[state=open]:slide-in-from-bottom-1/2 data-[state=open]:slide-in-from-right-1/2 data-[state=open]:zoom-in-95 [&>.aui-thread-root]:bg-inherit`,children:(0,f.jsx)(Ze,{})})]}),e[1]=i):i=e[1],i},ft=(0,s.forwardRef)((e,n)=>{let r=(0,t.c)(15),i,a;r[0]===e?(i=r[1],a=r[2]):({"data-state":a,...i}=e,r[0]=e,r[1]=i,r[2]=a);let s=a===`open`?`Close Assistant`:`Open Assistant`,c,l;r[3]===a?(c=r[4],l=r[5]):(c=(0,f.jsx)(`img`,{src:`/logo.png`,alt:`Assistant`,"data-state":a,className:`aui-modal-button-closed-icon absolute size-full object-contain drop-shadow-xl transition-all duration-300 ease-in-out hover:drop-shadow-2xl data-[state=closed]:scale-100 data-[state=closed]:rotate-0 data-[state=open]:scale-0 data-[state=open]:rotate-90`}),l=(0,f.jsx)(o.ChevronDownIcon,{"data-state":a,className:`aui-modal-button-open-icon absolute size-full rounded-full bg-primary p-3 text-primary-foreground shadow-xl transition-all duration-300 ease-in-out hover:shadow-2xl data-[state=closed]:scale-0 data-[state=closed]:-rotate-90 data-[state=open]:scale-100 data-[state=open]:rotate-0`}),r[3]=a,r[4]=c,r[5]=l);let u;r[6]===s?u=r[7]:(u=(0,f.jsx)(`span`,{className:`aui-sr-only sr-only`,children:s}),r[6]=s,r[7]=u);let d;return r[8]!==n||r[9]!==i||r[10]!==c||r[11]!==l||r[12]!==u||r[13]!==s?(d=(0,f.jsxs)(Z,{variant:`ghost`,tooltip:s,side:`left`,...i,className:`aui-modal-button size-full rounded-full transition-all hover:scale-105 hover:bg-transparent active:scale-95`,ref:n,children:[c,l,u]}),r[8]=n,r[9]=i,r[10]=c,r[11]=l,r[12]=u,r[13]=s,r[14]=d):d=r[14],d});ft.displayName=`AssistantModalButton`;let pt=({tool:e,callTool:t})=>((0,n.useAssistantTool)({toolName:e.name,description:e.description??``,parameters:e.inputSchema??{},execute:async n=>{try{return(await t(e.name,n)).content.map(e=>`text`in e&&typeof e.text==`string`?e.text:JSON.stringify(e)).join(`