1"use strict";(self.webpackChunk_N_E=self.webpackChunk_N_E||[]).push([[91777],{879:(e,t,n)=>{n.d(t,{CE:()=>i,MS:()=>s,ZX:()=>o,eL:()=>a,km:()=>l,uj:()=>r});let i="Protected conversation",o="That would be too easy",s="Unlock with your passkey to view",a=3e5,r={filter:"blur(4px)",userSelect:"none"};function l(e){return e?e.isPasskeyProtected?i:e.name:""}},26628:(e,t,n)=>{n.d(t,{Hf:()=>o,r3:()=>i});let i="(min-width: 48em)",o="(min-width: 64em)"},35912:(e,t,n)=>{n.d(t,{$A:()=>s,i$:()=>o});let i=new Set(["flac","m4a","mp3","ogg","wav","webm"]);function o(e){return"Kokoro-82m"===e?"kokoro":String(e).toLowerCase().replace(/[^a-z0-9.-]+/g,"-")}function s(e){let t=function(e){if(!e||"object"!=typeof e)return[];let t=e.samples;return Array.isArray(t)?t:[]}(e),n={};for(let e of t){if(!e||"object"!=typeof e)continue;let t="string"==typeof e.voice?e.voice.trim():"",o=function(e){let t=e.trim().replace(/^\/+/,""),n=function(e){let t=e;try{for(let e=0;e<4;e+=1){let e=decodeURIComponent(t);if(e===t)return t;t=e}}catch(e){}return null}(t);return t&&n&&a(t)&&a(n)&&function(e){let t=e.split("/").pop()||"",n=t.lastIndexOf("."),o=n>0?t.slice(n+1).toLowerCase():"";return!!(o&&i.has(o))}(t)?"/".concat(t):null}("string"==typeof e.relativePath?e.relativePath:"");t&&o&&(n[t]=o)}return n}function a(e){let t=e.split("/");return!e.includes("\\")&&!e.includes("?")&&!e.includes("#")&&e.startsWith("examples/voices/")&&!t.some(e=>""===e||"."===e||".."===e)}},40966:(e,t,n)=>{n.d(t,{F:()=>p});var i=n(15484),o=n(59086),s=n(44693);let a=e=>"number"==typeof e&&Number.isFinite(e)?e<1e10?1e3*e:e:null,r=e=>!!(e&&"object"==typeof e&&!Array.isArray(e)),l=(e,t)=>({message:e,index:t}),u=(e,t)=>{let n=a(e.message.timestamp),i=a(t.message.timestamp);return null!==n&&null!==i&&n!==i?n-i:null!==n&&null===i?-1:null===n&&null!==i?1:e.index-t.index},c=(e,t)=>!t&&"assistant"===e.role&&!1===e.isActiveBranch,d=e=>e.id?String(e.id):null,p=function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if(!Array.isArray(e)||0===e.length)return[];let n=!0===t.includeInactiveAssistantBranches,p=!0===t.includeContextOnlyMessages,h=[],m=new Set;for(let t of e){if(!r(t)||!p&&!(0,o.yM)(t)||c(t,n))continue;let e=d(t);if(e){if(m.has(e))continue;m.add(e)}let l=a(t.timestamp),u=(0,s.w)(t.webSearchResults),g=2===t.schemaVersion&&Array.isArray(t.parts)?t.parts:null,v=g?(0,i.ie)(g):null,f=null!==g,y=null!==l&&l!==t.timestamp||void 0!==u||f;h.push(y?{...t,...null!==l&&l!==t.timestamp?{timestamp:l}:{},...u?{webSearchResults:u}:{},...f?{parts:null!=v?v:[]}:{}}:t)}let g=h.map(l);return g.sort(u),g.map(e=>e.message)}},44693:(e,t,n)=>{n.d(t,{K:()=>s,w:()=>i});let i=e=>{if(Array.isArray(e)&&0!==e.length)return e.map((e,t)=>({...e,sourceIndex:t+1}))},o=RegExp("(?<![\\p{L}\\p{N}_!])\\[(\\d+)\\](?![\\p{L}\\p{N}_]|\\(|:)","gu"),s=(e,t)=>{if(!e||!Array.isArray(t)||0===t.length||!e.includes("["))return e;let n=!1;return e.split(/(\n)/).map(e=>"\n"===e?e:/^\s*```/.test(e)?(n=!n,e):n?e:((e,t)=>{let n="",i=0;for(;i<e.length;){let o=e.indexOf("`",i);if(-1===o){n+=t(e.slice(i));break}n+=t(e.slice(i,o));let s=1;for(;"`"===e[o+s];)s+=1;let a="`".repeat(s),r=e.indexOf(a,o+s);if(-1===r){n+=t(e.slice(o));break}n+=e.slice(o,r+s),i=r+s}return n})(e,e=>e.replace(o,(e,n)=>{let i=Number.parseInt(n,10);if(!Number.isFinite(i)||i<1)return e;let o=t[i-1];return(null==o?void 0:o.url)?"[\\[".concat(i,"\\]](").concat(o.url,")"):e}))).join("")}},47051:(e,t,n)=>{n.d(t,{H8:()=>a,Sb:()=>o,T8:()=>l,TV:()=>s,o$:()=>c,tM:()=>u});var i=n(72457);let o=n(26628).r3,s="data-boot-desktop",a="data-boot-navbar-collapsed",r="/auth/",l=300,u=80,c=e=>e.startsWith(r),d=e=>JSON.stringify(e);"\n(function() {\n try {\n var root = document.documentElement;\n try {\n var legacyTokenStorage = window.localStorage;\n var legacyTokenKeys = [];\n for (var legacyTokenIndex = 0; legacyTokenIndex < legacyTokenStorage.length; legacyTokenIndex += 1) {\n var legacyTokenKey = legacyTokenStorage.key(legacyTokenIndex);\n if (legacyTokenKey && legacyTokenKey.indexOf(".concat(d("signin_token_history:v1:"),") === 0) {\n legacyTokenKeys.push(legacyTokenKey);\n }\n }\n for (var legacyKeyIndex = 0; legacyKeyIndex < legacyTokenKeys.length; legacyKeyIndex += 1) {\n legacyTokenStorage.removeItem(legacyTokenKeys[legacyKeyIndex]);\n }\n } catch (legacyTokenCleanupError) {}\n var matchesDesktop = window.matchMedia(").concat(d(o),").matches;\n root.setAttribute(").concat(d(s),', matchesDesktop ? "true" : "false");
1\n var navbarCollapsed = false;\n var navbarHidden = window.location.pathname.indexOf(').concat(d(r),") === 0;\n var fontMultiplier = 1;\n {\n try {\n var persistedUiSnapshot = window.localStorage && window.localStorage.getItem(").concat(d("app:ui:v1"),");\n if (persistedUiSnapshot) {\n var parsed = JSON.parse(persistedUiSnapshot);\n navbarCollapsed = !navbarHidden && parsed && parsed.navbarCollapsed === true;\n var fontScales = ").concat(JSON.stringify(i.J),';\n var savedMultiplier = parsed && fontScales[parsed.fontSizePreference];\n if (typeof savedMultiplier === "number") fontMultiplier = savedMultiplier;\n }\n } catch (snapshotError) {}\n }\n var scale = Number(((matchesDesktop ? ').concat(i.A," : 1) * fontMultiplier).toFixed(3));\n root.style.setProperty('--mantine-scale', String(scale));\n root.setAttribute(").concat(d(a),', navbarCollapsed ? "true" : "false");\n } catch (error) {}\n})();')},65579:(e,t,n)=>{n.d(t,{Fi:()=>u,n$:()=>c,y8:()=>i});let i=[{value:"off",label:"Off"},{value:"chime",label:"Soft chime"},{value:"bell",label:"Gentle bell"},{value:"ping",label:"Subtle ping"}],o=(e,t,n)=>Math.min(n,Math.max(t,e)),s={chime:{masterGain:.14,tones:[{freq:880,start:0,duration:.28,gain:.32},{freq:1320,start:.08,duration:.32,gain:.26}]},bell:{masterGain:.12,tones:[{freq:659.25,start:0,duration:.5,gain:.28,type:"triangle"},{freq:1318.5,start:0,duration:.4,gain:.14,detune:3},{freq:1976,start:.03,duration:.32,gain:.08}]},ping:{masterGain:.14,tones:[{freq:1046.5,start:0,duration:.2,gain:.36}]}},a=null,r=0,l=()=>{let e=window.AudioContext||window.webkitAudioContext;return e?(a||(a=new e),a):null},u=async()=>{let e=l();if(!e)return!1;if("suspended"===e.state)try{await e.resume()}catch(e){return!1}return"running"===e.state},c=async(e,t)=>{if("off"===e)return!1;let n=s[e];if(!n)return!1;let i=(e=>"number"!=typeof e||Number.isNaN(e)?1:o(e,0,2))(t);if(i<=0)return!1;let a=o(i*((()=>{if("undefined"==typeof document)return!1;let e="visible"!==document.visibilityState,t="function"==typeof document.hasFocus&&!document.hasFocus();return e||t})()?1.6:1),0,3);if(a<=0)return!1;let u=Date.now();if(u-r<(e=>e.tones.length?Math.max(300,Math.round(1e3*e.tones.reduce((e,t)=>{let n=t.start+t.duration;return n>e?n:e},0))+120):300)(n))return!1;r=u;let c=l();if(!c)return!1;if("suspended"===c.state)try{await c.resume()}catch(e){return!1}if("running"!==c.state)return!1;let d=c.currentTime,p=c.createGain();p.gain.value=o(n.masterGain*a,0,1);let h=c.createDynamicsCompressor();return h.threshold.value=-18,h.knee.value=16,h.ratio.value=6,h.attack.value=.005,h.release.value=.12,p.connect(h),h.connect(c.destination),n.tones.forEach(e=>{((e,t,n,i)=>{var o;let s=e.createOscillator(),a=e.createGain();s.type=null!=(o=i.type)?o:"sine",s.frequency.setValueAtTime(i.freq,n+i.start),i.detune&&s.detune.setValueAtTime(i.detune,n+i.start);let r=n+i.start,l=r+i.duration,u=Math.min(.02,i.duration/3);a.gain.setValueAtTime(1e-4,r),a.gain.exponentialRampToValueAtTime(Math.max(1e-4,i.gain),r+u),a.gain.exponentialRampToValueAtTime(1e-4,l),s.connect(a),a.connect(t),s.start(r),s.stop(l+.05)})(c,p,d,e)}),!0}},72457:(e,t,n)=>{n.d(t,{A:()=>i,J:()=>o});let i=.94,o={"extra-small":.85,small:.9,normal:1,big:1.1,"extra-big":1.2}},90430:(e,t,n)=>{n.d(t,{E:()=>i});let i=e=>{if("number"!=typeof e||!Number.isFinite(e)||e<=0)return"";let t=new Date(e<1e10?1e3*e:e);return Number.isNaN(t.getTime())?"":t.toLocaleString()}},92890:(e,t,n)=>{n.r(t),n.d(t,{Conversation:()=>e3});var i=n(95155),o=n(31184),s=n(3553),a=n(6584),r=n(61915),l=n(46460),u=n(12658),c=n(57142),d=n(52181),p=n(7498),h=n(29452),m=n(46536),g=n(47965),v=n(54998),f=n(44633),y=n(32698),x=n(26550),b=n(18398),w=n(37206),k=n(12115),T=n(73321),S=n(7138),E=n(26628),_=n(63088),I=n(94870),A=n(15243),C=n(53986),j=n(5297),R=n(84392),O=n(5652),F=n(879),D=n(7167),N=n(48622),M=n(73825),P=n(11337),B=n(52240),L=n(95),z=n(41695),U=n(5700),G=n(20240),V=n(39525),K=n(26457),W=n(72081),H=n(91184),q=n(48303),X=n(66292),Q=n(72329),J=n(72426),Y=n(33
1643),$=n(33381),Z=n(38715),ee=n(62770),et=n(81978),en=n(61733),ei=n(41166);class eo{append(e){if("string"!=typeof e.delta||!Number.isFinite(e.start_ms)||!Number.isFinite(e.end_ms)||e.event_id&&this.seen.has(e.event_id))return null;e.event_id&&this.seen.add(e.event_id);let t="session.input_transcript.delta"===e.type?"user":"assistant",n=[...this.rows].reverse().find(n=>n.role===t&&n.fragments.some(t=>e.start_ms<=t.end_ms+1500&&e.end_ms>=t.start_ms-1500));return n||(n={id:"live-caption-".concat(this.rows.length),role:t,fragments:[],content:""},this.rows.push(n)),n.fragments.push({delta:e.delta,start_ms:e.start_ms,end_ms:e.end_ms}),n.fragments.sort((e,t)=>e.start_ms-t.start_ms),n.content=n.fragments.map(e=>e.delta).join(""),n}constructor(){this.rows=[],this.seen=new Set}}var es=n(80271),ea=n(16096);let er=e=>"number"!=typeof e||!Number.isFinite(e)||e<0?null:Math.floor(e);function el(e,t){let n=er(e),i=null!=n?n:0,o=er(null==t?void 0:t.audio_tokens),s=er(null==t?void 0:t.text_tokens);if(null===o&&null===s)return{audio:0,text:0,unattributed:i};if(null!==n&&(null!=o?o:0)+(null!=s?s:0)>n)return{audio:0,text:0,unattributed:n};let a=null!=o?o:Math.max(0,i-(null!=s?s:0)),r=null!=s?s:Math.max(0,i-a);return{audio:a,text:r,unattributed:Math.max(0,i-a-r)}}function eu(e){let t=el(null==e?void 0:e.input_tokens,null==e?void 0:e.input_token_details),n=el(null==e?void 0:e.output_tokens,null==e?void 0:e.output_token_details);return{audioInputTokens:t.audio,audioOutputTokens:n.audio,textInputTokens:t.text,textOutputTokens:n.text,unattributedInputTokens:t.unattributed,unattributedOutputTokens:n.unattributed}}let ec=new Set(["input_audio_buffer.speech_started","input_audio_buffer.speech_stopped","response.audio.started","output_audio_buffer.started","response.audio.done","response.output_audio.delta","response.output_audio.done","response.done","session.usage.updated","session.closed","response.event"]),ed=e=>"gpt-4o-realtime-preview"===e?"gpt-4o-realtime-preview-2025-06-03":e,ep=e=>"pcm16"===e?{type:"audio/pcm",rate:24e3}:e,eh=e=>{var t;return e&&"object"==typeof e&&"server_vad"===e.type?{...e,create_response:!1,interrupt_response:null==(t=e.interrupt_response)||t}:e},em="gpt-realtime-2";class eg extends ea.EventEmitter{async connect(){var e,t,n,i,o;try{let i,o,s;this.disconnectInFlight&&await this.disconnectInFlight,this.hasSentFinalBilling=!1,this.isDisconnecting=!1,this.forwardEventForwardingDisabled=!1,this.forwardEventSyntheticIdCounter=0,this.forwardEventRetryableFailureCount=0,this.forwardEventPendingRetryDelayMs=null,this.forwardEventQueue=[],this.forwardEventInFlightEvents=[],this.meteringFailureDisconnectScheduled=!1,this.terminalBillingDisconnectScheduled=!1,this.billedAudioInputSeconds=0,this.billedAudioOutputSeconds=0,this.billedAudioInputTokens=0,this.billedAudioOutputTokens=0,this.billedTextInputTokens=0,this.billedTextOutputTokens=0,this.fetchModelRates(),this.liveStarted=!1,this.liveClosed=!1,this.liveBackendUsageIds.clear(),this.livePendingTools.clear(),this.liveCompletedToolCalls.clear(),this.liveInstructions=this.config.instructions,this.liveDelegatedCost=0;let a=async e=>{var t,n,o,s;let a=await fetch("/api/realtime/session",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({model:this.config.model||em,voice:this.config.voice||((0,ei.Ap)(this.config.model)?"marin":"verse"),instructions:this.config.instructions,speed:this.config.speed,...e?{sdp:e}:{}})});if(!a.ok){let e=await a.json().catch(()=>({}));if(429===a.status)throw Error("Rate limit exceeded. Please try again later.");if(401===a.status)throw Error("Authentication required. Please sign in.");let t=Error(e.error||"Failed to get session token: ".concat(a.statusText));throw"string"==typeof e.code&&(t.code=e.code),t}let r=await a.json();if(i=null!=(o=null==(t=r.client_secret)?void 0:t.value)?o:r.value,this.sessionId=null!=(s=r.id)?s:null==(n=r.session)?void 0:n.id,this.realtimeApi="ga"===r.realtime_api?"ga":"legacy",!(0,ei.Ap)(this.config.model)&&!i||!this.sessionId)throw Error("Realtime session response was missing connection credentials");return r};if((0,ei.Ap)(this.config.model)||await a(),await this.cancelConnectIfRequested())return;this.pc=new RTCPeerConnection({iceServers:[{urls:"stun:stun.l.google.com:19302"}]}),this.pc.onconnectionstatechange=()=>{var e,t,n,i,o;console.log("Connection state:",null==(e=this.pc)?void 0:e.connectionState),((null==(t=this.pc)?void 0:t.connectionState)==="failed"||(null==(n=this.pc)?void 0:n.connectionState)==="disconnected")&&(this.handleDisconnect(),null==(i=(o=this.config).onError)||i.call(o,Error("Connection lost")))},this.pc.oniceconnectionstatechange=()=>{var e,t,n,i;console.log("ICE connection state:",null==(e=this.pc)?void 0:e.iceConnectionState),(null==(t=this.pc)?void 0:t.iceConnectionState)==="failed"&&(this.handleDisconnect(),null==(n=(i=this.config).onError)||n.call(i,Error("ICE connection failed")))},this.audioElement=document.createElement("audio"),this.audioElement.autoplay=!0,this.audioElement.style.display="none",document.body.appendChild(this.audioElement),this.pc.ontrack=e=>{this.audioElement&&(e.streams[0]||(0,ei.Ap)(this.config.model))&&(this.audioElement.srcObject=e.streams[0]||new MediaStream([e.track]))};try{if(this.localStream=await navigator.mediaDevices.getUserMedia({audio:{echoCancellation:!0,noiseSuppression:!0,autoGainControl:!0}}),await this.cancelConnectIfRequested())return;
1this.localStream.getTracks().forEach(e=>{this.pc&&this.localStream&&this.pc.addTrack(e,this.localStream)})}catch(e){throw console.error("Microphone access denied:",e),Error("Microphone access is required for voice conversations")}this.dc=this.pc.createDataChannel("oai-events"),this.setupDataChannel();let r=await this.pc.createOffer();if(await this.pc.setLocalDescription(r),await this.cancelConnectIfRequested())return;if((0,ei.Ap)(this.config.model)){if("complete"!==this.pc.iceGatheringState&&await new Promise((e,t)=>{let n=this.pc,i=()=>{"complete"===n.iceGatheringState&&(clearTimeout(o),n.removeEventListener("icegatheringstatechange",i),e())},o=setTimeout(()=>{n.removeEventListener("icegatheringstatechange",i),t(Error("Timed out gathering voice connection candidates"))},1e4);n.addEventListener("icegatheringstatechange",i),i()}),await this.cancelConnectIfRequested()||!this.pc)return;let e=await a(null==(n=this.pc.localDescription)?void 0:n.sdp);this.totalAudioInputSeconds=15,this.totalAudioOutputSeconds=0,this.totalTextInputTokens=0,this.totalTextOutputTokens=0,this.totalAudioInputTokens=0,this.totalAudioOutputTokens=0,s=new Promise((e,t)=>{this.liveReadyResolve=e,this.liveReadyReject=t}),o={type:"answer",sdp:e.sdp}}else{let e=ed(this.config.model||em),t="ga"===this.realtimeApi?"https://api.openai.com/v1/realtime/calls":"https://api.openai.com/v1/realtime?model=".concat(e),n=await fetch(t,{method:"POST",body:r.sdp,headers:{Authorization:"Bearer ".concat(i),"Content-Type":"application/sdp"}});if(!n.ok)throw Error("Failed to connect to Realtime API: ".concat(n.statusText));o={type:"answer",sdp:await n.text()}}if(await this.cancelConnectIfRequested()||!this.pc)return void console.log("[CONNECT] Connection cancelled before applying remote description.");let l=this.pc;if(await l.setRemoteDescription(o),await this.cancelConnectIfRequested())return void console.log("[CONNECT] Connection completed after cancellation; cleaning up.");if(s&&!this.liveStarted){let e;try{await Promise.race([s,new Promise((t,n)=>{e=setTimeout(()=>n(Error("GPT-Live did not start")),2e4)})])}finally{clearTimeout(e),this.liveReadyResolve=null,this.liveReadyReject=null}if(await this.cancelConnectIfRequested())return}this.isConnected=!0,this.startTime=Date.now(),this.lastBillingTime=Date.now(),this.startBillingInterval(),this.setupUnloadHandlers(),null==(e=(t=this.config).onConnectionChange)||e.call(t,!0),this.emit("connected")}catch(e){if(this.sessionId||this.pc||this.dc||this.localStream)try{await this.handleDisconnect()}catch(e){console.error("[CONNECT] Failed to finalize session after setup failure:",e)}throw console.error("Connection error:",e),null==(i=(o=this.config).onError)||i.call(o,e),this.emit("error",e),e}}setupDataChannel(){this.dc&&(this.dc.onopen=()=>{if((0,ei.Ap)(this.config.model))return;console.log("Data channel opened"),this.emit("datachannel:open");let e="string"==typeof this.config.instructions?this.config.instructions:"You are a helpful assistant. Always provide a spoken response to the user, even when using tools like the scratchpad. After using any tool, continue the conversation naturally with voice.";console.log("\uD83D\uDDE3ï¸ [REALTIME] Sending session instructions:",e);let t=es.j;if("ga"===this.realtimeApi)return void this.sendEvent({type:"session.update",session:{type:"realtime",model:ed(this.config.model||em),output_modalities:["audio"],instructions:e,audio:{input:{format:{type:"audio/pcm",rate:24e3},transcription:{model:"gpt-4o-mini-transcribe"},turn_detection:{type:"server_vad",threshold:.5,prefix_padding_ms:450,silence_duration_ms:650,create_response:!1,interrupt_response:!0}},output:{format:{type:"audio/pcm",rate:24e3},voice:this.config.voice||"verse",speed:this.config.speed}},tools:t}});this.sendEvent({type:"session.update",session:{modalities:["text","audio"],instructions:e,voice:this.config.voice||"verse",input_audio_format:"pcm16",output_audio_format:"pcm16",input_audio_transcription:{model:"whisper-1"},speed:this.config.speed,turn_detection:{type:"server_vad",threshold:.5,prefix_padding_ms:450,silence_duration_ms:650}
1,tools:[{type:"function",name:"scratchpad",description:"Use this to organize your thoughts, make plans, take notes, or analyze information. The user can see this scratchpad in a side panel. IMPORTANT: After using this tool, you MUST also provide a spoken acknowledgment to the user confirming what you added and continuing the conversation.",parameters:{type:"object",properties:{content:{type:"string",description:"The content to write to the scratchpad. Use clear, organized text."},type:{type:"string",enum:["thought","note","plan","analysis"],description:"The type of entry: thought (for thinking out loud), note (for important information), plan (for organizing steps), analysis (for breaking down complex topics)"}},required:["content","type"]}},{type:"function",name:"end_conversation",description:"Call this when the user explicitly asks to end, stop, or hang up the voice conversation.",parameters:{type:"object",properties:{reason:{type:"string",description:"Optional short reason for ending the conversation."}},required:[]}},{type:"function",name:"web_search",description:"Search the web for fresh information when the user asks for current events, recent facts, or sources.",parameters:{type:"object",properties:{query:{type:"string",description:"The search query to run on the web."},depth:{type:"string",enum:["standard","deep"],description:"Search depth. Use deep only when standard likely misses key context."},provider:{type:"string",enum:["linkup","tavily","exa","kagi","perplexity","valyu","brave"],description:"Optional provider override. Defaults to linkup."}},required:["query"]}}]}})},this.dc.onmessage=e=>{try{var t,n,i,o,s,a,r,l,u,c,d,p,h,m,g,v,f,y,x,b,w,k,T,S,E,_,I;let A=JSON.parse(e.data);if((0,ei.Ap)(this.config.model))return void this.handleLiveEvent(A);console.log("Received event:",A.type,A),"response.done"===A.type&&(null==(t=A.response)?void 0:t.usage)&&(console.log("\uD83C\uDFAF [OPENAI TOKENS] Complete usage from response.done:",{event_type:A.type,response_id:null==(n=A.response)?void 0:n.id,full_usage_object:A.response.usage,breakdown:{total_tokens:A.response.usage.total_tokens,input_tokens:A.response.usage.input_tokens,output_tokens:A.response.usage.output_tokens,input_token_details:A.response.usage.input_token_details,output_token_details:A.response.usage.output_token_details}}),((null==(i=A.response.usage.input_token_details)?void 0:i.audio_tokens)||(null==(o=A.response.usage.output_token_details)?void 0:o.audio_tokens))&&console.log("\uD83D\uDD0A [AUDIO TOKENS DETECTED]:",{input_audio_tokens:(null==(s=A.response.usage.input_token_details)?void 0:s.audio_tokens)||0,output_audio_tokens:(null==(a=A.response.usage.output_token_details)?void 0:a.audio_tokens)||0,text_input_tokens:(null==(r=A.response.usage.input_token_details)?void 0:r.text_tokens)||0,text_output_tokens:(null==(l=A.response.usage.output_token_details)?void 0:l.text_tokens)||0,cached_tokens:(null==(u=A.response.usage.input_token_details)?void 0:u.cached_tokens)||0})),A.usage&&"response.done"!==A.type&&console.log("\uD83D\uDCCA [USAGE DATA] Event usage:",{event_type:A.type,usage_data:A.usage});let C=this.normalizeInboundUiEvent(A);switch(C&&(null==(c=(d=this.config).onMessage)||c.call(d,C),this.emit(C.type,C)),this.forwardEventToServer(A),"response.done"===A.type&&A.response&&console.log("Response done details:",A.response),A.type){case"conversation.item.input_audio_transcription.completed":console.log("\uD83D\uDCDD [USER TRANSCRIPT] Received transcription:",A.transcript);break;case"conversation.item.input_audio_transcription.failed":console.warn("â [TRANSCRIPT FAILED]:",A);break;case"error":console.error("Realtime API error:",A.error),this.config.onError&&this.config.onError(Error((null==(p=A.error)?void 0:p.message)||"Unknown error"));break;case"session.created":this.emit("session:created",A);break;case"session.updated":console.log("Session updated:",A);break;case"conversation.item.created":case"conversation.item.added":this.handleConversationItemEvent(A);break;case"input_audio_buffer.committed":this.isProcessingResponse?console.log("Skipping - already processing a response"):(console.log("Audio buffer committed, waiting for conversation item:",A.item_id),this.pendingResponseItemId=A.item_id);break;case"response.created":console.log("[RESPONSE CREATED] ID: ".concat(null==(h=A.response)?void 0:h.id,", Already processing: ").concat(this.isProcessingResponse)),(null==(m=A.response)?void 0:m.id)&&(this.activeResponseIds.has(A.response.id)?console.warn("[DUPLICATE RESPONSE] Response ".concat(A.response.id," already being processed!")):this.activeResponseIds.add(A.response.id)),this.audioOutputStartTime||(this.audioOutputStartTime=Date.now(),console.log("[AUDIO PRESTART] Started timing for response ".concat(null==(g=A.response)?void 0:g.id))),this.emit
1("response:created",A);break;case"response.output_item.added":console.log("Output item added:",A.item),this.emit("response:output_item:added",A);break;case"response.content_part.added":console.log("Content part added:",A.part),this.emit("response:content_part:added",A);break;case"response.audio_transcript.delta":case"response.output_audio_transcript.delta":this.emit("response:audio_transcript:delta",A);break;case"response.output_audio_transcript.done":this.emit("response:audio_transcript:done",A);break;case"response.audio.delta":case"response.output_audio.delta":this.audioOutputStartTime||(this.audioOutputStartTime=Date.now(),this.emit("response:audio:started",A)),this.emit("response:audio:delta",A);break;case"response.audio.started":console.log("[AUDIO STARTED] Response ID: ".concat(A.response_id)),this.audioOutputStartTime=Date.now(),this.emit("response:audio:started",A);break;case"output_audio_buffer.started":console.log("[OUTPUT AUDIO STARTED] Response ID: ".concat(A.response_id)),this.audioOutputStartTime||(this.audioOutputStartTime=Date.now()),this.emit("output_audio:started",A);break;case"response.audio.done":case"response.output_audio.done":if(console.log("[AUDIO DONE] Response ID: ".concat(A.response_id,", Duration: ").concat(A.duration_ms,"ms")),this.pruneForwardedGaOutputAudioStartKey(A),this.pruneUiGaOutputAudioStartKey(A),A.duration_ms){let e=A.duration_ms/1e3;this.totalAudioOutputSeconds+=e,console.log("[AUDIO DONE] Added ".concat(e,"s from event duration_ms. Total: ").concat(this.totalAudioOutputSeconds,"s"))}else if(this.audioOutputStartTime){let e=(Date.now()-this.audioOutputStartTime)/1e3;this.totalAudioOutputSeconds+=e,console.log("[AUDIO DONE] Added ".concat(e,"s from calculated duration. Total: ").concat(this.totalAudioOutputSeconds,"s"))}else console.warn("[AUDIO DONE] No duration_ms in event and no audioOutputStartTime set!");this.audioOutputStartTime=null,this.emit("response:audio:done",A);break;case"input_audio_buffer.speech_started":this.audioInputStartTime=Date.now(),this.emit("input_audio:speech_started",A);break;case"input_audio_buffer.speech_stopped":if(this.audioInputStartTime){let e=(Date.now()-this.audioInputStartTime)/1e3;this.totalAudioInputSeconds+=e,this.audioInputStartTime=null}this.emit("input_audio:speech_stopped",A);break;case"response.text.delta":this.emit("response:text:delta",A);break;case"response.done":if(this.pruneForwardedGaOutputAudioStartKey(A),this.pruneUiGaOutputAudioStartKey(A),console.log("[RESPONSE DONE] ID: ".concat(null==(v=A.response)?void 0:v.id,", status: ").concat(null==(f=A.response)?void 0:f.status)),(null==(y=A.response)?void 0:y.output)&&A.response.output.forEach((e,t)=>{e.content&&e.content.forEach((e,n)=>{("text"===e.type||"output_text"===e.type)&&e.text?console.log("\uD83D\uDCAC [RESPONSE TEXT] Output[".concat(t,"].Content[").concat(n,"]:"),e.text):("audio"===e.type||"output_audio"===e.type)&&e.transcript&&console.log("\uD83C\uDFA4 [RESPONSE TRANSCRIPT] Output[".concat(t,"].Content[").concat(n,"]:"),e.transcript)})}),this.emit("response:done",A),null==(x=A.response)?void 0:x.usage){let e=A.response.usage,t=eu(e);if(console.log("\uD83D\uDCB0 [TOKEN COST CALCULATION]",{response_id:null==(T=A.response)?void 0:T.id,session_id:this.sessionId,model:this.config.model,raw_usage:e,token_breakdown:{total_tokens:e.total_tokens,input_tokens:e.input_tokens,output_tokens:e.output_tokens,audio_input_tokens:t.audioInputTokens,audio_output_tokens:t.audioOutputTokens,text_input_tokens:t.textInputTokens,text_output_tokens:t.textOutputTokens,cached_input_tokens:(null==(S=e.input_token_details)?void 0:S.cached_tokens)||0},running_totals_before:{total_text_input:this.totalTextInputTokens,total_text_output:this.totalTextOutputTokens}}),t.textInputTokens>0&&(this.totalTextInputTokens+=t.textInputTokens,console.log("\uD83D\uDCC8 [TOTAL UPDATED] Text input tokens: ".concat(this.totalTextInputTokens," (+").concat(t.textInputTokens,")"))),t.textOutputTokens>0&&(this.totalTextOutputTokens+=t.textOutputTokens,console.log("\uD83D\uDCC8 [TOTAL UPDATED] Text output tokens: ".concat(this.totalTextOutputTokens," (+").concat(t.textOutputTokens,")"))),t.audio
1InputTokens>0||t.audioOutputTokens>0){let e=t.audioInputTokens,n=t.audioOutputTokens;if(e>0&&(this.totalAudioInputTokens+=e,console.log("\uD83C\uDFAF [AUDIO INPUT TOKENS] Added ".concat(e," tokens, total: ").concat(this.totalAudioInputTokens))),n>0&&(this.totalAudioOutputTokens+=n,console.log("\uD83C\uDFAF [AUDIO OUTPUT TOKENS] Added ".concat(n," tokens, total: ").concat(this.totalAudioOutputTokens))),console.log("\uD83C\uDFB5 [AUDIO TOKEN ANALYSIS]",{audio_input_tokens:e,audio_output_tokens:n,session_totals:{totalAudioInputTokens:this.totalAudioInputTokens,totalAudioOutputTokens:this.totalAudioOutputTokens},conversion_rate:"6400 tokens per second",estimated_durations:{input_seconds:e>0?(e/6400).toFixed(3):"0",output_seconds:n>0?(n/6400).toFixed(3):"0"},openai_pricing_per_1m_tokens:{mini_audio_input:"$10.00",mini_audio_output:"$20.00",gpt4o_audio_input:"$40.00",gpt4o_audio_output:"$80.00"},cost_calculation_this_response:{audio_input_cost_if_mini:(e/1e6*10).toFixed(6),audio_output_cost_if_mini:(n/1e6*20).toFixed(6),audio_input_cost_if_gpt4o:(e/1e6*40).toFixed(6),audio_output_cost_if_gpt4o:(n/1e6*80).toFixed(6)}}),n>0&&0===this.totalAudioOutputSeconds){let e=n/6400;console.log("â±ï¸ [AUDIO DURATION OVERRIDE] Using token-based calculation: ".concat(e.toFixed(3),"s from ").concat(n," audio tokens")),this.totalAudioOutputSeconds=e}if(e>0){let t=e/6400;console.log("â±ï¸ [AUDIO INPUT DURATION] From tokens: ".concat(t.toFixed(3),"s from ").concat(e," audio tokens"))}}else console.log("â¹ï¸ [NO AUDIO TOKENS] This response contained no audio tokens");console.log("\uD83D\uDCCA [SESSION TOTALS AFTER UPDATE]",{total_text_input_tokens:this.totalTextInputTokens,total_text_output_tokens:this.totalTextOutputTokens,total_audio_input_tokens:this.totalAudioInputTokens,total_audio_output_tokens:this.totalAudioOutputTokens,total_audio_input_seconds_time_based:this.totalAudioInputSeconds.toFixed(3),total_audio_output_seconds_time_based:this.totalAudioOutputSeconds.toFixed(3)})}(null==(b=A.response)?void 0:b.id)&&this.activeResponseIds.delete(A.response.id),this.isProcessingResponse=!1,(null==(w=A.response)?void 0:w.status)==="failed"?(console.error("Response failed:",A.response),console.error("Failure details:",A.response.status_details),(null==(E=A.response.status_details)?void 0:E.error)&&(null==(_=(I=this.config).onError)||_.call(I,Error(A.response.status_details.error.message||"Response generation failed")))):(null==(k=A.response)?void 0:k.status)==="completed"&&console.log("Response completed successfully")}}catch(e){console.error("Error parsing message:",e)}},this.dc.onclose=()=>{console.log("Data channel closed"),this.handleDisconnect()},this.dc.onerror=e=>{var t,n;console.error("Data channel error:",e),null==(t=(n=this.config).onError)||t.call(n,Error("Data channel error"))})}handleLiveEvent(e){var t,n,i,o,s,a,r,l,u,c,d,p,h,m,g,v;if("session.started"===e.type&&(this.liveStarted=!0,null==(i=this.liveReadyResolve)||i.call(this),this.startLiveActivityMeter()),("session.usage.updated"===e.type||"session.closed"===e.type)&&"number"==typeof(null==(o=e.usage)?void 0:o.seconds)&&Number.isFinite(e.usage.seconds)&&(this.totalAudioInputSeconds=Math.max(this.totalAudioInputSeconds,e.usage.seconds),this.forwardEventToServer(e)),"response.event"===e.type){let t=e.event;if(["response.completed","response.failed","response.incomplete"].includes(null==t?void 0:t.type)&&(null==(s=t.response)?void 0:s.usage)){let n=t.response.id;this.liveBackendUsageIds.has(n)||(this.liveBackendUsageIds.add(n),this.totalTextInputTokens+=t.response.usage.input_tokens||0,this.totalTextOutputTokens+=t.response.usage.output_tokens||0,(null==(r=this.modelRates)?void 0:r.backend)&&(this.liveDelegatedCost+=function(e,t){var n,i,o,s,a,r,l,u;let c=e.input_tokens,d=e.output_tokens,p=null!=(i=null==(n=e.input_tokens_details)?void 0:n.cached_tokens)?i:0;if(![c,d,p].every(e=>Number.isSafeInteger(e)&&e>=0&&e<=1e7)||p>c)throw Error("Invalid delegated token usage");let h=c>(null!=(o=t.highContextThresholdTokens)?o:2e5),m=h&&null!=(s=t.inputRateAbove200k)?s:t.inputRate,g=h&&null!=(a=t.outputRateAbove200k)?a:t.outputRate,v=h?null!=(l=null!=(r=t.cacheReadInputRateAbove200k)?r:t.cacheReadInputRate)?l:m:null!=(u=t.cacheReadInputRate)?u:m;return((c-p)*m+p*v+d*g)/1e3}(t.response.usage,this.modelRates.backend)),this.forwardEventToServer({type:e.type,event_id:e.event_id,event:{type:t.type,response:{id:n,model:t.response.model,usage:t.response.usage}}}))}let n=e.delegation_id||"default";if((null==t?void 0:t.type)==="response.output_item.done"&&(null==(a=t.item)?void 0:a.type)==="function_call"){let i=this.livePendingTools.get(n)||new Map;t.item.call_id&&i.set(t.item.call_id,{...t,delegation_id:e.delegation_id,live:!0}),this.livePendingTools.set(n,i)}if((null==t?void 0:t.type)==="response.completed"){let e=this.livePendingTools.get(n);for(let[t,i]of(this.livePendingTools.delete(n),e||[]))this.liveCompletedToolCalls.has(t)||(this.liveCompletedToolCalls.add(t),null==(l=(u=this.config).onMessage)||l.call(u,i))}else((null==t?void 0:t.type)==="response.failed"||(null==t?void 0:t.type)==="response.incomplete")&&(this.livePendingTools.delete(n),null==(c=(d=this.config).onError)||c.call(d,Error("GPT-Live backend could not complete the request")))}if("error"===e.type){let t=Error((null==(p=e.error)?void 0:p.message)||"GPT-Live error");this.liveStarted||null==(h=this.liveReadyReject)||h.call(this,t),null==(m
1=(g=this.config).onError)||m.call(g,t)}"session.closed"===e.type&&(this.liveClosed=!0,null==(v=this.liveCloseResolve)||v.call(this),this.isDisconnecting||this.handleDisconnect()),"response.event"!==e.type&&(null==(t=(n=this.config).onMessage)||t.call(n,e))}startLiveActivityMeter(){try{let e=new AudioContext;this.liveAudioContext=e,e.resume();let t=new Map,n=n=>{if(!n)return!1;let i=t.get(n);i||((i=e.createAnalyser()).fftSize=256,e.createMediaStreamSource(n).connect(i),t.set(n,i));let o=new Uint8Array(i.fftSize);return i.getByteTimeDomainData(o),o.some(e=>Math.abs(e-128)>4)};this.liveActivityTimer=setInterval(()=>{var e,t,i;null==(t=(i=this.config).onMessage)||t.call(i,{type:"live.activity",listening:n(this.localStream),speaking:!!(this.audioElement&&!this.audioElement.paused&&this.audioElement.volume>0)&&n(null==(e=this.audioElement)?void 0:e.srcObject)})},200)}catch(e){}}sendEvent(e){if(!this.dc||"open"!==this.dc.readyState)return void console.error("Data channel not ready");try{if((0,ei.Ap)(this.config.model)){var t,n;if(!this.liveStarted)return;if("session.update"===e.type){let n=null==(t=e.session)?void 0:t.instructions;"string"==typeof n&&n!==this.liveInstructions&&(this.liveInstructions=n,this.disconnect().then(()=>{var e,t;null==(e=(t=this.config).onError)||e.call(t,Error("Instructions changed. Start voice again to apply the new instructions."))}).catch(e=>{var t,n;null==(t=(n=this.config).onError)||t.call(n,e instanceof Error?e:Error("Could not close the previous voice session."))}));return}if("response.cancel"===e.type)return;if("conversation.item.create"===e.type){if((null==(n=e.item)?void 0:n.type)!=="function_call_output")return;this.dc.send(JSON.stringify({...e,type:"response.item.create",event_id:e.event_id||crypto.randomUUID()}));return}if("response.create"!==e.type&&"session.close"!==e.type)return;this.dc.send(JSON.stringify({type:e.type,event_id:e.event_id||crypto.randomUUID()}));return}let i=((e,t)=>{if("ga"!==t)return e;if("session.update"===e.type){var n=e;let t={...n.session||{}};t.type=t.type||"realtime";let i={...t.audio||{}},o={...i.input||{}},s={...i.output||{}};return void 0!==t.turn_detection&&(o.turn_detection=eh(t.turn_detection),delete t.turn_detection),void 0!==o.turn_detection&&(o.turn_detection=eh(o.turn_detection)),void 0!==t.input_audio_transcription&&(o.transcription=t.input_audio_transcription,delete t.input_audio_transcription),void 0!==t.input_audio_format&&(o.format=ep(t.input_audio_format),delete t.input_audio_format),void 0!==t.speed&&(s.speed=t.speed,delete t.speed),void 0!==t.voice&&(s.voice=t.voice,delete t.voice),void 0!==t.output_audio_format&&(s.format=ep(t.output_audio_format),delete t.output_audio_format),Array.isArray(t.modalities)&&(t.output_modalities||(t.output_modalities=t.modalities.includes("audio")?["audio"]:["text"]),delete t.modalities),Array.isArray(t.output_modalities)&&t.output_modalities.length>1&&(t.output_modalities=t.output_modalities.includes("audio")?["audio"]:["text"]),Object.keys(o).length>0&&(i.input=o),Object.keys(s).length>0&&(i.output=s),Object.keys(i).length>0&&(t.audio=i),{...n,session:t}}if("response.create"!==e.type)return e;let i={...e.response||{}};return Array.isArray(i.modalities)&&(i.output_modalities||(i.output_modalities=i.modalities.includes("audio")?["audio"]:["text"]),delete i.modalities),Array.isArray(i.output_modalities)&&i.output_modalities.length>1&&(i.output_modalities=i.output_modalities.includes("audio")?["audio"]:["text"]),i.output_modalities||(i.output_modalities=["audio"]),{...e,response:i}})(e,this.realtimeApi);this.dc.send(JSON.stringify(i)),"response.create"===e.type?console.log("[EVENT SENT] response.create - triggering AI response"):console.log("Sent event:",e.type)}catch(e){console.error("Error sending event:",e)}}handleConversationItemEvent(e){var t,n;if(console.log("Conversation item event:",e.type,e.item),this.emit("conversation:item:created",e),this.emit("conversation:item:added",e),(null==(t=e.item)?void 0:t.role)!=="user"||(null==(n=e.item)?void 0:n.id)!==this.pendingResponseItemId||this.isProcessingResponse)return;let i=Date.now();if(i-this.lastResponseCreateTime<500){console.log("[DEBOUNCE] Skipping response creation - too soon after last response"),this.pendingResponseItemId=null;return}console.log("Creating response for user item ".concat(e.item.id)),this.isProcessingResponse=!0,this.lastResponseCreateTime=i,this.pendingResponseItemId=null,this.sendEvent({type:"response.create",response:"ga"===this.realtimeApi?{output_modalities:["audio"]}:{modalities:["text","audio"]}})}normalizeInboundUiEvent(e){if("conversation.item.added"===e.type)return{...e,type:"conversation.item.created",realtime_event_type:e.type};if("response.audio.delta"!==e.type&&"response.output_audio.delta"!==e.type)return e;let t=e.response_id||e.item_id||"unknown";if(this.uiGaOutputAudioStartKeys.has(t))return null;for(this.uiGaOutputAudioStartKeys.add(t);this.uiGaOutputAudioStartKeys.size>eg.UI_GA_AUDIO_START_MAX_KEYS;){let e=this.uiGaOutputAudioStartKeys.values().next().value;if(!e)break;this.uiGaOutputAudioStartKeys.delete(e)}let{delta:n,...i}=e;return{...i,type:"response.audio.started",realtime_event_type:e.type}}sendText(e){this.sendEvent({type:"conversation.item.create",item:{type:"message",role:"user",content:[{type:"input_text",text:e}]}}),this.sendEvent({type:"response.create",..."ga"===this.realtimeApi?{response:{output_modalities:["audio"]}}:{}})}disconnect(){return this.handleDisconnect()}async cancelConnectIfRequested(){if(!this.isDisconnecting)return!1;let e=this.disconnectInFlight;return e&&await e,(this.sessionId||this.pc||this.dc||this.localStream)&&await this.handleDisconnect(),!0}handleDisconnect(){if(this.disconnectInFlight)return this.disconnectInFlight;let e=this.performDisconnect().finally(()=>{this.disconnectInFlight===e&&(this.disconnectInFlight=null)});return this.disconnectInFlight=e,e}async performDisconnect(){var e,t,n,i,o,s,a,r,l;if(this.isDisconnecting=!0,!this.isConnected&&!this.pc&&!this.dc&&!this.localStream&&!this.sessionId){null==(i=(o=this.config).onConnectionChange)||i.call(o,!1);return}let u=this.isConnected;if(this.isConnected=!1,this.stopBillingInterval(),(0,ei.Ap)(this.config.model)&&this.liveStarted&&!this.liveClosed&&(null==(e=this.dc)?void 0:e.readyState)==="open"){let e;
1null==(s=this.localStream)||s.getTracks().forEach(e=>{e.enabled=!1}),null==(a=this.audioElement)||a.pause();let t=new Promise(e=>{this.liveCloseResolve=e});this.sendEvent({type:"session.close"}),await Promise.race([t,new Promise(t=>{e=setTimeout(t,15e3)})]),clearTimeout(e),this.liveCloseResolve=null,this.liveClosed||null==(r=(l=this.config).onError)||r.call(l,Error("Voice disconnected before final usage was confirmed"))}this.stopProviderTransport(),(u||this.sessionId)&&(await this.flushForwardEventQueueForDisconnect(),await this.sendFinalBilling()),null==(t=(n=this.config).onConnectionChange)||t.call(n,!1),this.cleanup(),this.sessionId=null,this.emit("disconnected")}isActive(){return this.isConnected}getSessionId(){return this.sessionId}static isRetryableForwardEventStatus(e){return 408===e||425===e||429===e||e>=500}static isTerminalBillingRejection(e,t){return 429===e?"api_account_monthly_usd_limit"===t:"number"==typeof e&&e>=400&&e<500&&408!==e&&409!==e&&425!==e}terminateForBillingRejection(e,t,n){if(this.terminalBillingDisconnectScheduled)return;this.terminalBillingDisconnectScheduled=!0,this.forwardEventForwardingDisabled=!0,this.forwardEventFlushTimer&&(clearTimeout(this.forwardEventFlushTimer),this.forwardEventFlushTimer=null),this.forwardEventRetryableFailureCount=0,this.forwardEventPendingRetryDelayMs=null,this.stopBillingInterval();let i=Error(402===e?"Insufficient balance. Please add credits to continue.":n||"Account monthly spend limit exceeded.");t&&(i.code=t),console.warn("[BILLING] Terminal billing rejection (".concat(e).concat(t?"/".concat(t):"","); stopping the provider session.")),this.stopProviderTransport(),this.handleDisconnect().catch(e=>{console.error("[BILLING] Failed to finalize after terminal billing rejection",e)});try{var o,s;null==(o=(s=this.config).onError)||o.call(s,i)}catch(e){console.error("[BILLING] Realtime error callback failed after terminal billing rejection",e)}}createSyntheticForwardEventId(){return this.forwardEventSyntheticIdCounter+=1,"client-synth-".concat(this.forwardEventSyntheticIdCounter)}disableForwardEventForwarding(e){if(this.forwardEventForwardingDisabled)return;this.forwardEventForwardingDisabled=!0,this.forwardEventFlushTimer&&(clearTimeout(this.forwardEventFlushTimer),this.forwardEventFlushTimer=null);let t=this.forwardEventQueue.length+this.forwardEventInFlightEvents.length;this.forwardEventRetryableFailureCount=0,this.forwardEventPendingRetryDelayMs=null,console.warn("[EVENT FORWARD] Durable metering became unavailable (".concat(e,"). Preserving ").concat(t," queued event(s) for final beacon and stopping the provider session.")),this.stopProviderTransport(),this.meteringFailureDisconnectScheduled||(this.meteringFailureDisconnectScheduled=!0,setTimeout(()=>{this.handleDisconnect().catch(e=>{console.error("[EVENT FORWARD] Failed to finalize after metering failure",e)})},0))}stopProviderTransport(){var e,t;let n=Date.now();null!==this.audioInputStartTime&&(this.totalAudioInputSeconds+=Math.max(0,n-this.audioInputStartTime)/1e3,this.audioInputStartTime=null),null!==this.audioOutputStartTime&&(this.totalAudioOutputSeconds+=Math.max(0,n-this.audioOutputStartTime)/1e3,this.audioOutputStartTime=null),null==(e=this.localStream)||e.getTracks().forEach(e=>e.stop()),null==(t=this.audioElement)||t.pause(),this.dc&&(this.dc.onopen=null,this.dc.onmessage=null,this.dc.onclose=null,this.dc.onerror=null,("open"===this.dc.readyState||"connecting"===this.dc.readyState)&&this.dc.close()),this.pc&&(this.pc.ontrack=null,this.pc.onicecandidate=null,this.pc.onconnectionstatechange=null,this.pc.oniceconnectionstatechange=null,"closed"!==this.pc.connectionState&&this.pc.close())}getForwardEventBufferedCount(){return this.forwardEventQueue.length+this.forwardEventInFlightEvents.length}ensureForwardEventQueueWithinLimit(){let e=this.getForwardEventBufferedCount();return e<=eg.FORWARD_EVENT_MAX_QUEUED_EVENTS||(this.disableForwardEventForwarding("buffer overflow (".concat(e," > ").concat(eg.FORWARD_EVENT_MAX_QUEUED_EVENTS,")")),!1)}getNextForwardEventRetryDelayMs(){let e=Math.max(0,this.forwardEventRetryableFailureCount-1);return Math.min(eg.FORWARD_EVENT_RETRY_BASE_MS*2**e,eg.FORWARD_EVENT_RETRY_MAX_MS)}requeueInFlightForwardEvents(){0!==this.forwardEventInFlightEvents.length&&(this.forwardEventQueue.unshift(...this.forwardEventInFlightEvents),this.forwardEventInFlightEvents=[],this.ensureForwardEventQueueWithinLim
1it())}normalizeForwardEvent(e){let t="string"==typeof e.event_id&&e.event_id.trim().length>0?e.event_id:null;return{...e,event_id:null!=t?t:this.createSyntheticForwardEventId(),client_ts:Date.now(),model:this.config.model||em}}scheduleForwardEventFlush(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:eg.FORWARD_EVENT_BATCH_WINDOW_MS;if(this.forwardEventFlushTimer)return;let t=Math.max(0,Math.floor(e));this.forwardEventFlushTimer=setTimeout(()=>{this.forwardEventFlushTimer=null,this.flushForwardEventQueue()},t)}advanceBilledUsageFromForwardBilling(e,t){if(!e||!0!==e.success||!0===e.pending||!0===e.duplicate||!e.usage||"object"!=typeof e.usage)return;let n=e.usage,i=this.getCurrentUsage(),o=null!=t?t:i,s=e=>{let t=n[e];return"number"==typeof t&&Number.isFinite(t)&&t>=0?t:null},a=e=>{let t=o[e];return Number.isFinite(t)&&t>=0?Math.min(i[e],t):i[e]},r=(e,t,n)=>{if(null===n)return;let i=this[e];this[e]=Math.max(i,Math.min(a(t),i+n))},l=s("audioInputTokens"),u=s("audioOutputTokens"),c=s("audioInputSeconds"),d=s("audioOutputSeconds");r("billedAudioInputTokens","audioInputTokens",l),r("billedAudioOutputTokens","audioOutputTokens",u),r("billedTextInputTokens","textInputTokens",s("textInputTokens")),r("billedTextOutputTokens","textOutputTokens",s("textOutputTokens")),r("billedAudioInputSeconds","audioInputSeconds",c),r("billedAudioOutputSeconds","audioOutputSeconds",d),"token-based"===e.billingMethod&&(!Object.prototype.hasOwnProperty.call(n,"audioInputSeconds")&&null!==l&&l>0&&(this.billedAudioInputSeconds=Math.max(this.billedAudioInputSeconds,a("audioInputSeconds"))),!Object.prototype.hasOwnProperty.call(n,"audioOutputSeconds")&&null!==u&&u>0&&(this.billedAudioOutputSeconds=Math.max(this.billedAudioOutputSeconds,a("audioOutputSeconds"))))}recoverBilledUsageFromAmbiguousDuplicate(e,t){let n={audioInputTokens:0,audioOutputTokens:0,textInputTokens:0,textOutputTokens:0},i=!1;for(let t of e){var o;if(!t||"object"!=typeof t||!this.ambiguouslyDeliveredForwardEvents.has(t)||"response.done"!==t.type||!(null==(o=t.response)?void 0:o.usage))continue;let e=eu(t.response.usage);n.audioInputTokens+=e.audioInputTokens,n.audioOutputTokens+=e.audioOutputTokens,n.textInputTokens+=e.textInputTokens,n.textOutputTokens+=e.textOutputTokens,i=!0}i&&this.advanceBilledUsageFromForwardBilling({success:!0,billingMethod:n.audioInputTokens>0||n.audioOutputTokens>0?"token-based":"text-token-based",usage:n},t)}markForwardEventsAsAmbiguouslyDelivered(e){for(let t of e)t&&"object"==typeof t&&this.ambiguouslyDeliveredForwardEvents.add(t)}async sendForwardEvents(e,t){try{let n=await fetch("/api/realtime/forward-event",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)});if(409===n.status&&n.headers.has("retry-after"))return console.warn("[EVENT FORWARD] Usage accepted; billing reconciliation is pending"),{ok:!0,retryable:!1,status:n.status};if(!n.ok){let t=eg.isRetryableForwardEventStatus(n.status);return t&&this.markForwardEventsAsAmbiguouslyDelivered(e.events),console.warn("[EVENT FORWARD] Failed to forward ".concat(e.events.length," event(s): status=").concat(n.status," (").concat(t?"retryable":"non-retryable",")")),{ok:!1,retryable:t,status:n.status}}try{let i=await n.json(),o=null==i?void 0:i.billing;for(let i of(202===n.status&&(null==o?void 0:o.pending)===!0&&eg.isTerminalBillingRejection(o.status,o.code)&&this.terminateForBillingRejection(o.status,"string"==typeof o.code?o.code:void 0,"string"==typeof o.error?o.error:void 0),(null==o?void 0:o.success)===!0&&!0===o.duplicate?this.recoverBilledUsageFromAmbiguousDuplicate(e.events,t):this.advanceBilledUsageFromForwardBilling(o,t),e.events))i&&"object"==typeof i&&this.ambiguouslyDeliveredForwardEvents.delete(i);o&&!0!==o.duplicate&&"number"==typeof o.cost&&Number.isFinite(o.cost)&&o.cost>0&&(this.accumulatedCost+=o.cost,this.emit("billing:update",{cost:o.cost,totalCost:this.accumulatedCost,balance:o.newBalance,billingMethod:o.billingMethod,tokenBasedAccuracy:o.tokenBasedAccuracy,usage:o.usage}))}catch(e){}return{ok:!0,retryable:!1,status:n.status}}catch(t){return this.markForwardEventsAsAmbiguouslyDelivered(e.events),console.error("[EVENT FORWARD] Error forwarding ".concat(e.events.length," event(s):"),t),{ok:!1,retryable:!0}}}flushForwardEventQueueWithBeacon(){let e=[...this.forwardEventInFlightEvents,...this.forwardEventQueue];if(!this.sessionId||0===e.length||"undefined"==typeof navigator||"function"!=typeof navigator.sendBeacon)return;this.forwardEventFlushTimer&&(clearTimeout(this.forwardEventFlushTimer),this.forwardEventFlushTimer=null),this.forwardEventInFlightEvents=[],this.forwardEventQueue=[];let t=0;for(;t<e.length;){let n=e.slice(t,t+eg.FORWARD_EVENT_SERVER_MAX_BATCH_SIZE),i=new Blob([JSON.stringify({sessionId:this.sessionId,events:n}
1)],{type:"application/json"});if(!navigator.sendBeacon("/api/realtime/forward-event",i)){console.warn("[EVENT FORWARD] Failed to flush events via beacon"),this.forwardEventQueue.unshift(...e.slice(t)),this.ensureForwardEventQueueWithinLimit();break}t+=n.length}}async flushForwardEventQueueForDisconnect(){let e=this.flushForwardEventQueue().then(e=>e).catch(e=>(console.warn("[EVENT FORWARD] Flush failed during disconnect; falling back to beacon.",e),"retry-pending")),t=null,n=await Promise.race([e,new Promise(e=>{t=setTimeout(()=>e("timed-out"),eg.FORWARD_EVENT_DISCONNECT_WAIT_TIMEOUT_MS)})]);t&&clearTimeout(t),("drained"!==n||this.getForwardEventBufferedCount()>0)&&(console.warn("[EVENT FORWARD] Disconnect flush ended as ".concat(n,"; using beacon fallback.")),(0,ei.Ap)(this.config.model)&&this.liveStarted&&!this.liveClosed&&this.sendEvent({type:"session.close"}),this.flushForwardEventQueueWithBeacon())}async flushForwardEventQueue(){if(this.forwardEventFlushInFlight&&await this.forwardEventFlushInFlight,this.forwardEventForwardingDisabled)return"disabled";if(!this.sessionId||0===this.forwardEventQueue.length)return"drained";this.forwardEventFlushTimer&&(clearTimeout(this.forwardEventFlushTimer),this.forwardEventFlushTimer=null);let e=this.forwardEventQueue.splice(0,this.forwardEventQueue.length);return this.forwardEventInFlightEvents=e.slice(),this.forwardEventFlushInFlight=(async()=>{for(;this.forwardEventInFlightEvents.length>0;){let t=this.forwardEventInFlightEvents.slice(0,eg.FORWARD_EVENT_SERVER_MAX_BATCH_SIZE),n={sessionId:this.sessionId,events:t},i=this.forwardEventUsageCeilings.get(t[t.length-1]),o=await this.sendForwardEvents(n,i);if(!o.ok){var e;if(o.retryable){if(this.forwardEventRetryableFailureCount+=1,this.forwardEventRetryableFailureCount>eg.FORWARD_EVENT_MAX_RETRYABLE_FAILURES)return this.disableForwardEventForwarding("retryable failures exceeded (".concat(this.forwardEventRetryableFailureCount,")")),"disabled";return this.forwardEventPendingRetryDelayMs=this.getNextForwardEventRetryDelayMs(),this.requeueInFlightForwardEvents(),"retry-pending"}return this.disableForwardEventForwarding("status ".concat(null!=(e=o.status)?e:"unknown")),"disabled"}this.forwardEventInFlightEvents.splice(0,t.length),this.forwardEventRetryableFailureCount=0,this.forwardEventPendingRetryDelayMs=null}return"drained"})().finally(()=>{let e=this.forwardEventPendingRetryDelayMs;this.forwardEventPendingRetryDelayMs=null,this.requeueInFlightForwardEvents(),this.forwardEventFlushInFlight=null,!this.forwardEventForwardingDisabled&&this.forwardEventQueue.length>0&&this.sessionId&&this.scheduleForwardEventFlush(null!=e?e:eg.FORWARD_EVENT_BATCH_WINDOW_MS)}),await this.forwardEventFlushInFlight,this.forwardEventForwardingDisabled?"disabled":this.forwardEventQueue.length>0?"retry-pending":"drained"}async forwardEventToServer(e){let t=this.sessionId;if(this.forwardEventForwardingDisabled||!eg.USAGE_EVENTS.has(e.type)||!t||(await Promise.resolve(),this.forwardEventForwardingDisabled||this.sessionId!==t))return;let n=this.prepareForwardEvent(e);if(!n)return;let i=this.normalizeForwardEvent(n);if(this.forwardEventUsageCeilings.set(i,this.getCurrentUsage()),this.forwardEventQueue.push(i),this.ensureForwardEventQueueWithinLimit()){if("response.done"===e.type||this.forwardEventQueue.length>=eg.FORWARD_EVENT_MAX_BATCH_SIZE)return void await this.flushForwardEventQueue();this.scheduleForwardEventFlush()}}prepareForwardEvent(e){if("response.done"===e.type){var t,n,i;return{type:e.type,event_id:e.event_id,response:{id:null==(t=e.response)?void 0:t.id,status:null==(n=e.response)?void 0:n.status,usage:null==(i=e.response)?void 0:i.usage}}}if("response.output_audio.delta"!==e.type)return e;let o=e.response_id||e.item_id||e.event_id||"unknown";if(this.forwardedGaOutputAudioStartKeys.has(o))return null;for(this.forwardedGaOutputAudioStartKeys.add(o);this.forwardedGaOutputAudioStartKeys.size>eg.FORWARDED_GA_AUDIO_START_MAX_KEYS;){let e=this.forwardedGaOutputAudioStartKeys.values().next().value;if(!e)break;this.forwardedGaOutputAudioStartKeys.delete(e)}let{delta:s,...a}=e;return a}pruneForwardedGaOutputAudioStartKey(e){var t;let n=e.response_id||(null==(t=e.response)?void 0:t.id)||e.item_id;n&&this.forwardedGaOutputAudioStartKeys.delete(n)}pruneUiGaOutputAudioStartKey(e){var t;let n=e.response_id||(null==(t=e.response)?void 0:t.id)||e.item_id;n&&this.uiGaOutputAudioStartKeys.delete(n)}muteInput(e){this.localStream&&this.localStream.getAudioTracks().forEac
1h(t=>{t.enabled=!e})}setOutputVolume(e){this.audioElement&&(this.audioElement.volume=Math.max(0,Math.min(1,e)))}startBillingInterval(){this.billingInterval=setInterval(()=>{this.checkAndSendBilling()},1e4)}stopBillingInterval(){this.billingInterval&&(clearInterval(this.billingInterval),this.billingInterval=null)}async checkAndSendBilling(){if(this.isDisconnecting)return void console.log("[BILLING CHECK] Skipping - disconnect in progress");let e=this.getCurrentUsage(),t={audioInputSeconds:e.audioInputSeconds-this.billedAudioInputSeconds,audioOutputSeconds:e.audioOutputSeconds-this.billedAudioOutputSeconds,audioInputTokens:e.audioInputTokens-this.billedAudioInputTokens,audioOutputTokens:e.audioOutputTokens-this.billedAudioOutputTokens,textInputTokens:e.textInputTokens-this.billedTextInputTokens,textOutputTokens:e.textOutputTokens-this.billedTextOutputTokens},n=this.estimateCost(t);console.log("[BILLING CHECK]",{deltaAudioInputSeconds:t.audioInputSeconds.toFixed(2),deltaAudioOutputSeconds:t.audioOutputSeconds.toFixed(2),deltaTextInputTokens:t.textInputTokens,deltaTextOutputTokens:t.textOutputTokens,estimatedDeltaCost:n.toFixed(6),threshold:.05}),n>=.05&&(console.log("[BILLING] Sending interval billing request..."),await this.sendBilling(t)&&(this.billedAudioInputSeconds=e.audioInputSeconds,this.billedAudioOutputSeconds=e.audioOutputSeconds,this.billedAudioInputTokens=e.audioInputTokens,this.billedAudioOutputTokens=e.audioOutputTokens,this.billedTextInputTokens=e.textInputTokens,this.billedTextOutputTokens=e.textOutputTokens,this.lastBillingTime=Date.now(),this.lastIntervalBillingTime=Date.now()))}async sendFinalBilling(){if(this.hasSentFinalBilling)return void console.log("[FINAL BILLING] Already sent, skipping");console.log("[FINAL BILLING] Waiting 500ms for events to be processed server-side..."),await new Promise(e=>setTimeout(e,500));let e=this.getCurrentUsage(),t={audioInputSeconds:e.audioInputSeconds-this.billedAudioInputSeconds,audioOutputSeconds:e.audioOutputSeconds-this.billedAudioOutputSeconds,audioInputTokens:e.audioInputTokens-this.billedAudioInputTokens,audioOutputTokens:e.audioOutputTokens-this.billedAudioOutputTokens,textInputTokens:e.textInputTokens-this.billedTextInputTokens,textOutputTokens:e.textOutputTokens-this.billedTextOutputTokens},n=this.estimateCost(t);console.log("[FINAL BILLING] Delta usage:",JSON.stringify(t,null,2)),console.log("[FINAL BILLING] Summary:",{deltaAudioInputSeconds:t.audioInputSeconds.toFixed(2),deltaAudioOutputSeconds:t.audioOutputSeconds.toFixed(2),deltaTextInputTokens:t.textInputTokens,deltaTextOutputTokens:t.textOutputTokens,estimatedDeltaCost:n.toFixed(6),totalUsage:{audioInputSeconds:e.audioInputSeconds.toFixed(2),audioOutputSeconds:e.audioOutputSeconds.toFixed(2)},billedUsage:{audioInputSeconds:this.billedAudioInputSeconds.toFixed(2),audioOutputSeconds:this.billedAudioOutputSeconds.toFixed(2)},threshold:.001}),console.log("[FINAL BILLING] Sending final billing request..."),await this.sendBilling({...t,triggerFinalBilling:!0},{maxPendingUsageRetries:8})?this.hasSentFinalBilling=!0:console.error("[FINAL BILLING] Failed to send final billing")}getCurrentUsage(){let e=this.totalAudioInputSeconds,t=this.totalAudioOutputSeconds;return this.audioInputStartTime&&(e+=(Date.now()-this.audioInputStartTime)/1e3),this.audioOutputStartTime&&(t+=(Date.now()-this.audioOutputStartTime)/1e3),{audioInputSeconds:e,audioOutputSeconds:t,audioInputTokens:this.totalAudioInputTokens,audioOutputTokens:this.totalAudioOutputTokens,textInputTokens:this.totalTextInputTokens,textOutputTokens:this.totalTextOutputTokens}}estimateCost(e){if((0,ei.Ap)(this.config.model)){var t,n;return e.audioInputSeconds*(null!=(n=null==(t=this.modelRates)?void 0:t.sessionDurationRate)?n:.05/60)}if(this.modelRates){let t=e.audioInputTokens||0,n=e.audioOutputTokens||0;return(t>0||n>0)&&void 0!==this.modelRates.audioInputTokenRate&&void 0!==this.modelRates.audioOutputTokenRate?t/1e3*this.modelRates.audioInputTokenRate+n/1e3*this.modelRates.audioOutputTokenRate:e.audioInputSeconds*this.modelRates.audioInputRate+e.audioOutputSeconds*this.modelRates.audioOutputRate}let i=(this.config.model||em).includes("mini");return e.audioInputSeconds*(i?.001:.004)+e.audioOutputSeconds*(i?.002:.008)}async sendBilling(e){var t,n;let i=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if(!this.sessionId)return console.log("[BILLING] No session ID, skipping billing"),!1;let o="".concat(this.sessionId,"-").concat(Date.now(),"-").concat(Math.random().toString(36).substr(2,9));console.log("[BILLING] Sending usage data with requestId:",o,"usage:",JSON.stringify(e,null,2));let s=null!=(t=i.maxPendingUsageRetries)?t:2;for(let t=0;t<=s;t++)try{let i={requestId:o,sessionId:this.sessionId,model:this.config.model||em,...e};console.log("[BILLING] Full request body:",JSON.stringify(i,null,2));let a=await fetch("/api/realtime/track-usage",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(i)});if(a.ok){let e=await a.json();if(e.duplicate)return console.log("[BILLING DUPLICATE]",e),!0;return console.log("\uD83D\uDCB3 [BILLING SUCCESS] ".concat((null==(n=e.billingMethod)?void 0:n.toUpperCase())||"UNKNOWN"," billing completed:"),{...e,billingAccuracy:e.tokenBasedAccuracy?"TOKEN-BASED (forwarded)":"ESTIMATED (time-based)"}
1),this.accumulatedCost+=e.cost,this.emit("billing:update",{cost:e.cost,totalCost:this.accumulatedCost,balance:e.newBalance,billingMethod:e.billingMethod,tokenBasedAccuracy:e.tokenBasedAccuracy,usage:e.usage}),!0}{let e=await a.text();if(console.error("[BILLING ERROR] Status: ".concat(a.status,", Error:"),e),409===a.status&&t<s){let e=this.getBillingRetryDelayMs(a.headers.get("Retry-After"));console.warn("[BILLING RETRY] Usage not ready, retrying in ".concat(e,"ms (").concat(t+1,"/").concat(s,")")),await new Promise(t=>setTimeout(t,e));continue}try{let t=JSON.parse(e);eg.isTerminalBillingRejection(a.status,null==t?void 0:t.code)&&this.terminateForBillingRejection(a.status,"string"==typeof(null==t?void 0:t.code)?t.code:void 0,"string"==typeof(null==t?void 0:t.error)?t.error:void 0)}catch(e){console.error("[BILLING ERROR] Could not parse error response")}break}}catch(e){if(console.error("Failed to send billing:",e),t<s){await new Promise(e=>setTimeout(e,1e3));continue}break}return!1}getBillingRetryDelayMs(e){if(e){let t=Number(e);if(Number.isFinite(t)&&t>=0)return Math.min(Math.max(1e3*t,250),5e3)}return 1e3}getTotalCost(){return this.accumulatedCost}getUsageStats(){let e=this.getCurrentUsage();return{sessionDuration:this.startTime?(Date.now()-this.startTime)/1e3:0,audioInputSeconds:e.audioInputSeconds,audioOutputSeconds:e.audioOutputSeconds,audioInputTokens:this.totalAudioInputTokens,audioOutputTokens:this.totalAudioOutputTokens,textInputTokens:e.textInputTokens,textOutputTokens:e.textOutputTokens,estimatedCost:this.estimateCost(e)+this.liveDelegatedCost,totalCost:this.accumulatedCost}}setupUnloadHandlers(){this.unloadHandler&&(window.removeEventListener("beforeunload",this.unloadHandler),window.removeEventListener("unload",this.unloadHandler)),this.unloadHandler=e=>{this.sendBeaconBilling()},window.addEventListener("beforeunload",this.unloadHandler),window.addEventListener("unload",this.unloadHandler)}sendBeaconBilling(){if(!this.sessionId||this.hasSentFinalBilling)return;this.flushForwardEventQueueWithBeacon();let e=this.getCurrentUsage(),t={audioInputSeconds:e.audioInputSeconds-this.billedAudioInputSeconds,audioOutputSeconds:e.audioOutputSeconds-this.billedAudioOutputSeconds,audioInputTokens:e.audioInputTokens-this.billedAudioInputTokens,audioOutputTokens:e.audioOutputTokens-this.billedAudioOutputTokens,textInputTokens:e.textInputTokens-this.billedTextInputTokens,textOutputTokens:e.textOutputTokens-this.billedTextOutputTokens},n=this.estimateCost(t);this.hasSentFinalBilling=!0;let i=new Blob([JSON.stringify({requestId:"".concat(this.sessionId,"-").concat(Date.now(),"-beacon"),sessionId:this.sessionId,model:this.config.model||em,triggerFinalBilling:!0,...t})],{type:"application/json"}),o=navigator.sendBeacon("/api/realtime/track-usage",i);console.log("[BEACON BILLING] Final billing ".concat(o?"sent":"failed",":"),{estimatedCost:n.toFixed(6),deltaUsage:t})}async fetchModelRates(){try{let e=await fetch("/api/realtime/get-rates");if(!e.ok)return void console.warn("[RATES] Failed to fetch model rates, using fallback rates");let t=await e.json(),n=this.config.model||em;t.rates&&t.rates[n]?(this.modelRates=t.rates[n],console.log("[RATES] Fetched rates for ".concat(n,":"),this.modelRates)):console.warn("[RATES] No rates found for model ".concat(n,", using fallback rates"))}catch(e){console.error("[RATES] Error fetching model rates:",e)}}cleanup(){var e,t;this.liveActivityTimer&&clearInterval(this.liveActivityTimer),this.liveActivityTimer=null,null==(e=this.liveAudioContext)||e.close(),this.liveAudioContext=null,null==(t=this.liveReadyResolve)||t.call(this),this.liveReadyResolve=null,this.liveReadyReject=null,this.forwardEventFlushTimer&&(clearTimeout(this.forwardEventFlushTimer),this.forwardEventFlushTimer=null),this.forwardEventFlushInFlight=null,this.forwardEventForwardingDisabled=!1,this.forwardEventSyntheticIdCounter=0,this.forwardEventRetryableFailureCount=0,this.forwardEventPendingRetryDelayMs=null,this.forwardEventInFlightEvents=[],this.forwardEventQueue=[],this.unloadHandler&&(window.removeEventListener("beforeunload",this.unloadHandler),window.removeEventListener("unload",this.unloadHandler),this.unloadHandler=null),this.localStream&&(this.localStream.getTracks().forEac
1h(e=>{e.stop()}),this.localStream=null),this.audioElement&&(this.audioElement.pause(),this.audioElement.srcObject=null,this.audioElement.parentNode&&this.audioElement.remove(),this.audioElement=null),this.dc&&(this.dc.onopen=null,this.dc.onmessage=null,this.dc.onclose=null,this.dc.onerror=null,"open"===this.dc.readyState&&this.dc.close(),this.dc=null),this.pc&&(this.pc.ontrack=null,this.pc.onicecandidate=null,this.pc.oniceconnectionstatechange=null,this.pc.onconnectionstatechange=null,this.pc.getTransceivers().forEach(e=>{e.stop&&e.stop()}),"closed"!==this.pc.connectionState&&this.pc.close(),this.pc=null),this.activeResponseIds.clear(),this.forwardedGaOutputAudioStartKeys.clear(),this.uiGaOutputAudioStartKeys.clear(),this.pendingResponseItemId=null,this.lastUserItemId=null,this.isProcessingResponse=!1,this.audioInputStartTime=null,this.audioOutputStartTime=null}constructor(e={}){super(),this.pc=null,this.dc=null,this.audioElement=null,this.localStream=null,this.realtimeApi="legacy",this.liveStarted=!1,this.liveClosed=!1,this.liveReadyReject=null,this.livePendingTools=new Map,this.liveCompletedToolCalls=new Set,this.liveReadyResolve=null,this.liveCloseResolve=null,this.liveBackendUsageIds=new Set,this.liveDelegatedCost=0,this.liveActivityTimer=null,this.liveAudioContext=null,this.isConnected=!1,this.sessionId=null,this.isProcessingResponse=!1,this.pendingResponseItemId=null,this.lastUserItemId=null,this.activeResponseIds=new Set,this.forwardedGaOutputAudioStartKeys=new Set,this.uiGaOutputAudioStartKeys=new Set,this.lastResponseCreateTime=0,this.hasSentFinalBilling=!1,this.isDisconnecting=!1,this.startTime=null,this.audioInputStartTime=null,this.audioOutputStartTime=null,this.totalAudioInputSeconds=0,this.totalAudioOutputSeconds=0,this.totalTextInputTokens=0,this.totalTextOutputTokens=0,this.lastBillingTime=null,this.billingInterval=null,this.accumulatedCost=0,this.billedAudioInputSeconds=0,this.billedAudioOutputSeconds=0,this.billedAudioInputTokens=0,this.billedAudioOutputTokens=0,this.billedTextInputTokens=0,this.billedTextOutputTokens=0,this.lastIntervalBillingTime=0,this.totalAudioInputTokens=0,this.totalAudioOutputTokens=0,this.modelRates=null,this.unloadHandler=null,this.forwardEventQueue=[],this.forwardEventInFlightEvents=[],this.forwardEventFlushTimer=null,this.forwardEventFlushInFlight=null,this.forwardEventSyntheticIdCounter=0,this.forwardEventForwardingDisabled=!1,this.forwardEventRetryableFailureCount=0,this.forwardEventPendingRetryDelayMs=null,this.forwardEventUsageCeilings=new WeakMap,this.ambiguouslyDeliveredForwardEvents=new WeakSet,this.disconnectInFlight=null,this.meteringFailureDisconnectScheduled=!1,this.terminalBillingDisconnectScheduled=!1,this.config=e,(0,ei.Ap)(e.model)&&this.on("billing:update",e=>{var t,n;return null==(t=(n=this.config).onMessage)?void 0:t.call(n,{...e,type:"billing:update"})})}}eg.FORWARD_EVENT_BATCH_WINDOW_MS=500,eg.FORWARD_EVENT_MAX_BATCH_SIZE=8,eg.FORWARD_EVENT_SERVER_MAX_BATCH_SIZE=64,eg.FORWARD_EVENT_MAX_QUEUED_EVENTS=256,eg.FORWARD_EVENT_MAX_RETRYABLE_FAILURES=8,eg.FORWARD_EVENT_RETRY_BASE_MS=500,eg.FORWARD_EVENT_RETRY_MAX_MS=8e3,eg.FORWARD_EVENT_DISCONNECT_WAIT_TIMEOUT_MS=3e3,eg.FORWARDED_GA_AUDIO_START_MAX_KEYS=256,eg.UI_GA_AUDIO_START_MAX_KEYS=256,eg.USAGE_EVENTS=ec;var ev=n(35912),ef=n(46943),ey=n(3372),ex=n(11890),eb=n(74334),ew=n(85286),ek=n(5772);let eT=[{value:"alloy",label:"Alloy"},{value:"ash",label:"Ash"},{value:"ballad",label:"Ballad"},{value:"coral",label:"Coral"},{value:"echo",label:"Echo"},{value:"sage",label:"Sage"},{value:"shimmer",label:"Shimmer"},{value:"verse",label:"Verse"}],eS=[{value:"gpt-live-1",label:"GPT-Live 1"},{value:"gpt-realtime-2",label:"GPT Realtime 2"},{value:"gpt-4o-realtime-preview",label:"GPT-4o Realtime"},{value:"gpt-4o-mini-realtime-preview-2024-12-17",label:"GPT-4o Mini Realtime"},{value:"gpt-realtime-mini-2025-12-15",label:"GPT Realtime Mini"}],eE=[{value:.85,label:"Slow"},{value:1,label:"Normal"},{value:1.15,label:"Fast"}],e_=[{value:520,label:"Quick"},{value:650,label:"Balanced"},{value:820,label:"Patient"}],eI=e=>Number.isFinite(e)?Math.max(400,Math.min(1200,Math.round(e))):650,eA="en-US",eC={background:"light-dark(var(--mantine-color-white), rgba(13, 18, 26, 0.74))",border:"1px solid light-dark(var(--mantine-color-gray-3), rgba(148, 163,
1184, 0.24))",boxShadow:"inset 0 1px 0 light-dark(rgba(255, 255, 255, 0.9), rgba(255, 255, 255, 0.045)), 0 18px 44px light-dark(rgba(15, 23, 42, 0.16), rgba(0, 0, 0, 0.22))",backdropFilter:"blur(18px) saturate(145%)",WebkitBackdropFilter:"blur(18px) saturate(145%)"},ej="The user can stop the conversation at any time by tapping the voice ring with the diamond in the middle.",eR=e=>{let t=(e||"").trim();if(!t)return ej;if(t.toLowerCase().includes("diamond in the middle"))return t.slice(0,2e3);let n="".concat("\n\n").concat(ej),i=Math.max(0,2e3-n.length),o=t.slice(0,i).trimEnd();return o?"".concat(o).concat(n):ej.slice(0,2e3)};function eO(){return en.r?(0,i.jsx)(eF,{}):(0,i.jsx)(et.RealtimeVoiceUnavailable,{})}let eF=(0,b.PA)(()=>{var e,t;let{conversation:n,ui:s,scratchpad:u,systemPromptPresets:c,userData:h}=(0,g.useStores)(),m=(0,T.useRouter)(),[v,f]=(0,k.useState)(!1),[y,x]=(0,k.useState)("verse"),b=(0,k.useRef)(new eo),w=(0,k.useRef)(new Map),S=(0,ei.Ap)(n.voiceModel),E=S?ei.df.map(e=>({value:e,label:e[0].toUpperCase()+e.slice(1)})):eT,I=E.some(e=>e.value===y)?y:S?"marin":"verse",[A,C]=(0,k.useState)(!1),[j,R]=(0,k.useState)(!1),[O,F]=(0,k.useState)(!1),[D,N]=(0,k.useState)(null),[M,P]=(0,k.useState)(!1),[B,L]=(0,k.useState)(!1),[z,U]=(0,k.useState)("prompt"),G=(0,k.useRef)(0),V=(0,k.useRef)(null),K=(0,k.useRef)(new Map),et=(0,k.useRef)(new Map),en=(0,k.useRef)(null),es=(0,k.useRef)(!1),ea=(0,k.useRef)(!1),er=(0,k.useRef)(null),el=(0,k.useRef)(0),[eu,ec]=(0,k.useState)(0),[ed,ep]=(0,k.useState)(!1),[eh,em]=(0,k.useState)(!1),[ej,eO]=(0,k.useState)(!1),[eF,eD]=(0,k.useState)(!1),[eN,eM]=(0,k.useState)(!1),[eP,eB]=(0,k.useState)(!1),[eL,ez]=(0,k.useState)({}),[eU,eG]=(0,k.useState)(null),[eV,eK]=(0,k.useState)(()=>{let e=ew.safeLocalStorage.getItem(ew.LocalStorageKeys.voice_speakingSpeed);return(e=>Number.isFinite(e)?Math.max(.75,Math.min(1.25,Number(e.toFixed(2)))):1)(e?Number(e):NaN)}),[eW,eH]=(0,k.useState)(()=>{let e=ew.safeLocalStorage.getItem(ew.LocalStorageKeys.voice_turnDetectionSilenceMs);return eI(e?Number(e):NaN)}),eq=(0,k.useRef)(null),eX=(0,k.useRef)(!1),eQ=(0,k.useRef)(0),eJ=(0,k.useRef)(null),eY=(0,k.useCallback)(()=>{eJ.current&&(clearTimeout(eJ.current),eJ.current=null)},[]),e$=(0,k.useCallback)(()=>{eY(),eJ.current=setTimeout(()=>{R(!1),eJ.current=null},450)},[eY]),eZ=O?1:j?.65:.3,e0=O?"Speaking":j?"Listening":"Idle",e1=(null==(e=E.find(e=>e.value===I))?void 0:e.label)||"Verse",e5=e=>(e||"").replace(/\r\n/g,"\n").trim(),e2=e5(n.instructions||""),e4=(0,k.useMemo)(()=>{var e,t;let n=c.lastUsedPresetId;if(n){let e=c.presets.find(e=>{var t;return(null==(t=e.id)?void 0:t.toString())===n});if(e&&e5(e.instructions)===e2)return(null==(t=e.id)?void 0:t.toString())||null}let i=c.presets.find(e=>e5(e.instructions)===e2);return(null==i||null==(e=i.id)?void 0:e.toString())||null},[e2,c.lastUsedPresetId,c.presets]),e8=0===e2.length,e6=(0,k.useMemo)(()=>{if(e8)return"No instructions";let e=c.presets.find(e=>{var t;return(null==(t=e.id)?void 0:t.toString())===e4});return(null==e?void 0:e.name)||"Custom"},[e8,e4,c.presets]),e3=n.voiceModel||ei.Hr,e9=(null==(t=eS.find(e=>e.value===e3))?void 0:t.label)||"GPT-Live 1",e7=(0,k.useMemo)(()=>{let e=eE.find(e=>.001>Math.abs(e.value-eV));return e?"".concat(e.label," (").concat(eV.toFixed(2),"x)"):"".concat(eV.toFixed(2),"x")},[eV]),te=(0,k.useMemo)(()=>{let e=e_.reduce((e,t)=>{if(!e)return t;let n=Math.abs(e.value-eW);return Math.abs(t.value-eW)<n?t:e},null);return e?"".concat(e.label," (").concat(eW,"ms)"):"".concat(eW,"ms")},[eW]),tt=(0,k.useCallback)(e=>8+24*eZ*((Math.sin(2*Math.PI*e/24+eu)+1)/2),[eZ,eu]);(0,k.useEffect)(()=>()=>{!function(e){e.current&&(clearTimeout(e.current),e.current=null)}(eJ)},[]),(0,k.useEffect)(()=>{if(n.mode===_.Dp.voice){if(!ea.current){let e=e5(ef.U);e5(n.instructions||"")===e&&n.set("instructions",""),ea.current=!0}return}ea.current=!1},[n.mode,n.instructions,n,c]);let tn=(0,k.useMemo)(()=>{let e=ew.safeLocalStorage.getItem(ew.LocalStorageKeys.voice_lastLanguage);return e&&e.trim()?e.trim():eA},[]);(0,k.useEffect)(()=>{if(ew.safeLocalStorage.getItem(ew.LocalStorageKeys.voice_lastLanguage)!==tn){ew.safeLocalStorage.setItem(ew.LocalStorageKeys.voice_lastLanguage,tn);try{var e;null==h||null==(e=h.markDataChanged)||e.call(h,{allowManualSync:!0})}catch(e){}}},[tn,h]),(0,k.useEffect)(()=>{let e=String(eV);if(ew.safeLocalStorage.getItem(ew.LocalStorageKeys.voice_speakingSpeed)!==e){ew.safeLocalStorage.setItem(ew.LocalStorageKeys.voice_speakingSpeed,e);try{var t;null==h||null==(t=h.markDataChanged)||t.call(h,{allowManualSync:!0})}catch(e){}}},[h,eV]);let ti=(0,k.useMemo)(()=>{let e="string"==typeof n.instructions?n.instructions:"";return e5(e).length>0?eR(e):eR((e=>{let t=e||eA;return"Respond in ".concat(t," unless the user asks to switch language.")})(tn))},[n.instructions,tn]),to=(0,k.useCallback)(e=>{eH(eI(e))},[]),{isConnected:ts,isConnecting:ta,error:tr,connect:tl,disconnect:tu,muteInput:tc,events:td,getUsageStats:tp,sendEvent:th}=function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},[t,n]=(0,k.useState)(!1),[i,o]=(0,k.useState)(!1),[s,a]=(0,k.useState)(null),[r,l]=(0,k.useState)([]),u=(0,k.useRef)(e),c=(0,k.useRef)(null),d=(0,k.useCallback)(e=>{var t;(null==(t=c.current)?void 0:t.isActive())&&o(!1),l(t=>[...t,e])},[]),p=(0,k.useCallback)(e=>{a(e),o(!1)},[]),h=(0,k.useCallback)(e=>{n(e),o(!1)},[]);(0,k.useEffect)(()=>{u.current={...e}},[e]);let m=(0,k.useCallback)(async()=>{var e;if((null==(e=c.current)?void 0:e.isActive())||i)return;c.current&&(await c.current.disconnect(),c.current=null),o(!0),a(null);let t=null;try{let{autoConnect:e,...n}=u.current;c.current=t=new eg({...n,onMessage:d,onError:p,onConnectionChange:h}),await t.connect()}catch(e){t&&c.current===t&&(c.current=null),a(e),o(!1)}},[d,p,h,i]),g=(0,k.useCallback)(async()=>{c.current&&(await c.current.disconnect(),c.current=null)},[]),v=(0,k.useCallback)(e=>{var t;null==(t=c.current)||t.sendText(e)},[]),f=(0,k.useCallback)(e=>{var t;null==(t=c.current)||t.sendEvent(e)},[]),y=(0,k.useCallback)(e=>{var t;null==(t=c.current)||t.muteInput(e)},[]),x=(0,k.useCallback)(e=>{var t;null==(t=c.current)||t.setOutputVolume(e)},[]),b=(0,k.useCallback)(()=>{l([])},[]),w=(0,k.useCallback)(()=>{var e;return(null==(e=c.current)?void 0:e.getUsageStats())||null},[]),T=(0,k.useCallback)(()=>{var e;return(null==(e=c.current)?void 0:e.getTotalCost())||0},[]),S=!!e.autoConnect;return(0,k.useEffect)(()=>{!S||t||i||s||m()},[S,t,i,s,m]),(0,k.useEffect)(()=>()=>{var e;null==(e=c.current)||e.disconnect()},[]),{isConnected:t,isConnecting:i,error:s,connect:m,disconnect:g,sendText:v,sendEvent:f,muteInput:y,setOutputVolume:
1x,events:r,clearEvents:b,getUsageStats:w,getTotalCost:T}}(k.useMemo(()=>({model:n.voiceModel||ei.Hr,voice:I,instructions:ti,speed:eV}),[n.voiceModel,I,ti,eV])),tm=(0,k.useCallback)(async e=>{let t=e&&"object"==typeof e?e:{},n="string"==typeof t.query?t.query.trim():"",i="deep"===t.depth?"deep":"standard",o="string"==typeof t.provider&&t.provider.trim().length>0?t.provider.trim():"linkup";if(!n)return{ok:!1,error:"Missing required query string for web_search."};try{var s,a;let e=await fetch("/api/web",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({query:n,depth:i,provider:o,outputType:"searchResults"})}),t=await e.json().catch(()=>null);if(!e.ok){let n="string"==typeof(null==t?void 0:t.error)?t.error:"Web search failed with status ".concat(e.status);return{ok:!1,error:n}}let r=Array.isArray(null==t?void 0:t.data)?t.data:[],l=r.slice(0,5).map(e=>({title:(null==e?void 0:e.title)||(null==e?void 0:e.name)||null,url:(null==e?void 0:e.url)||null,snippet:(null==e?void 0:e.snippet)||(null==e?void 0:e.content)||(null==e?void 0:e.text)||null}));return{ok:!0,query:n,provider:(null==t||null==(s=t.metadata)?void 0:s.provider)||o,depth:(null==t||null==(a=t.metadata)?void 0:a.depth)||i,resultCount:r.length,results:l}}catch(e){return{ok:!1,error:e instanceof Error?e.message:"Unknown web search error"}}},[]);(0,k.useEffect)(()=>{let e=String(eW);if(ew.safeLocalStorage.getItem(ew.LocalStorageKeys.voice_turnDetectionSilenceMs)!==e){ew.safeLocalStorage.setItem(ew.LocalStorageKeys.voice_turnDetectionSilenceMs,e);try{var t;null==h||null==(t=h.markDataChanged)||t.call(h,{allowManualSync:!0})}catch(e){}}},[eW,h]),(0,k.useEffect)(()=>{ts&&th&&!S&&th({type:"session.update",session:{turn_detection:{type:"server_vad",threshold:.5,prefix_padding_ms:450,silence_duration_ms:eW},speed:eV}})},[eW,ts,th,eV,S]),(0,k.useEffect)(()=>{ts&&th&&th({type:"session.update",session:{instructions:ti}})},[ts,th,ti,S]),(0,k.useEffect)(()=>{if(!ts)return void ec(0);let e=O?.35:j?.24:.14,t=setInterval(()=>{ec(t=>t+e)},70);return()=>clearInterval(t)},[ts,j,O]),(0,k.useEffect)(()=>{if(!eh&&!A&&!ej&&!eF&&!eN)return;let e=e=>{let t=e.target;if(!t)return;let n=en.current;n&&n.contains(t)||(em(!1),C(!1),eO(!1),eD(!1),eM(!1))};return document.addEventListener("mousedown",e),document.addEventListener("touchstart",e,{passive:!0}),()=>{document.removeEventListener("mousedown",e),document.removeEventListener("touchstart",e)}},[eh,A,ej,eF,eN]),(0,k.useEffect)(()=>{let e=!1;return fetch("/examples/voices/gpt-4o-mini-tts/manifest.json",{cache:"no-store"}).then(e=>{if(!e.ok)throw Error("manifest unavailable");return e.json()}).then(t=>{e||ez((0,ev.$A)(t))}).catch(()=>{e||ez({})}),()=>{e=!0,function(e){let t=e.current;t&&(t.pause(),t.currentTime=0,t.onended=null,t.onerror=null,e.current=null)}(er),eG(null)}},[]),(0,k.useEffect)(()=>{td.length<G.current&&(G.current=0);let e=td.slice(G.current);0!==e.length&&(G.current=td.length,e.forEach(e=>{var t,i,o,a,r,l;switch(e.type){case"session.started":b.current=new eo,w.current.clear();break;case"live.activity":R(!!e.listening),F(!!e.speaking);break;case"session.input_transcript.delta":case"session.output_transcript.delta":{let t=b.current.append(e);if(!t)break;let i=t.content,o=w.current.get(t.id),s=o?o.then(async e=>(await n.updateVoiceMessage(e,i),e)):n.addVoiceMessage({role:t.role,content:i,timestamp:new Date});w.current.set(t.id,s),s.catch(e=>console.error("Failed to save Live captions",e));break}case"conversation.item.created":let c=e.item,d="";if(null==c||null==(t=c.content)?void 0:t[0]){let e=c.content[0];d=e.transcript||e.text||""}else(null==c||null==(i=c.formatted)?void 0:i.transcript)?d=c.formatted.transcript:(null==c||null==(o=c.formatted)?void 0:o.text)&&(d=c.formatted.text);(null==c?void 0:c.role)==="user"&&!d&&(null==c?void 0:c.id)?n.addVoiceMessage({role:"user",content:"...",timestamp:new Date}).then(e=>{if(e){K.current.set(c.id,e);let t=et.current.get(c.id);t&&(et.current.delete(c.id),n.updateVoiceMessage(e,t).catch(e=>{console.error("[IntegratedVoiceControls] Failed to apply buffered voice transcript:",e)}))}}):d&&(null==c?void 0:c.role)&&n.addVoiceMessage({role:c.role,content:d,timestamp:new Date});break;case"conversation.item.input_audio_transcription.completed":if(e.transcript&&e.item_id){let t=K.current.get(e.item_id);t?n.updateVoiceMessage(t,e.transcript).catch(e=>{console.error("[IntegratedVoiceControls] Failed to update voice message:",e)}):et.current.set(e.item_id,e.transcript)}break;case"input_audio_buffer.speech_started":eY(),R(!0),eq.current&&Date.now()-eq.current<=1500&&(eQ.current=0,to(eW+120)),O&&th&&(el.current=Date.now()+600,F(!1),eX.current=!1,th({type:"response.cancel"}));break;case"input_audio_buffer.speech_stopped":e$();break;case"response.audio.started":case"output_audio_buffer.started":case"response.output_audio.delta":if(eY(),R(!1),"response.output_audio.delta"===e.type&&eX.current||(eq.current=Date.now()),eX.current=!0,Date.now()<el.current&&th){th({type:"response.cancel"}),eX.current=!1;break}F(!0);break;case"response.audio.done":case"response.output_audio.done":F(!1),eX.current=!1,eQ.
1current+=1,eQ.current>=4&&(eQ.current=0,to(eW-60));break;case"response.output_item.added":if(e.item){let t=e.item;"function_call"===t.type&&"scratchpad"===t.name&&console.log("\uD83D\uDDD2ï¸ [SCRATCHPAD] Function call detected (waiting for arguments to complete):",{itemType:t.type,itemName:t.name,itemId:t.id,currentScratchpadState:s.scratchpadOpened}),"function_call"===t.type&&"end_conversation"===t.name&&console.log("[VOICE] end_conversation tool call detected, waiting for completed arguments."),"function_call"===t.type&&"web_search"===t.name&&console.log("[VOICE] web_search tool call detected, waiting for completed arguments.")}break;case"response.output_item.done":if(e.item&&"function_call"===e.item.type&&"end_conversation"===e.item.name){let t;try{let n="string"==typeof e.item.arguments?JSON.parse(e.item.arguments):e.item.arguments;n&&"string"==typeof n.reason&&(t=n.reason)}catch(e){}th&&e.item.call_id&&(th({type:"conversation.item.create",item:{type:"function_call_output",call_id:e.item.call_id,output:JSON.stringify({ok:!0,stopped:!0,reason:t||null})}}),th({type:"response.cancel"})),P(!1),em(!1),C(!1),eO(!1),eD(!1),eM(!1),eB(!1),R(!1),F(!1),eX.current=!1,eY(),n.set("isVoiceActive",!1),K.current.clear(),et.current.clear(),tu();break}if(e.item&&"function_call"===e.item.type&&"scratchpad"===e.item.name){console.log("\uD83D\uDDD2ï¸ [SCRATCHPAD] Function call completed with full arguments:",{itemType:e.item.type,itemName:e.item.name,arguments:e.item.arguments,currentScratchpadState:s.scratchpadOpened});try{let t="string"==typeof e.item.arguments?JSON.parse(e.item.arguments):e.item.arguments;console.log("\uD83D\uDDD2ï¸ [SCRATCHPAD] Parsed arguments:",t),console.log("\uD83D\uDDD2ï¸ [SCRATCHPAD] Adding entry with:",{content:t.content,type:t.type||"note",conversationSlug:null==(a=n.properties)?void 0:a.slug}),u.addEntry(t.content,t.type||"note",null==(r=n.properties)?void 0:r.slug),console.log("\uD83D\uDDD2ï¸ [SCRATCHPAD] Entry added successfully"),e.live&&e.item.call_id&&(th({type:"conversation.item.create",item:{type:"function_call_output",call_id:e.item.call_id,output:'{"ok":true}'}}),th({type:"response.create"}))}catch(t){console.error("\uD83D\uDDD2ï¸ [SCRATCHPAD] ERROR parsing arguments:",t),e.live&&e.item.call_id&&(th({type:"conversation.item.create",item:{type:"function_call_output",call_id:e.item.call_id,output:'{"ok":false,"error":"Unable to add note"}'}}),th({type:"response.create"}))}}e.item&&"function_call"===e.item.type&&"web_search"===e.item.name&&(async()=>{let t={};try{t="string"==typeof e.item.arguments?JSON.parse(e.item.arguments):e.item.arguments}catch(e){t={}}let n=await tm(t);th&&e.item.call_id&&(th({type:"conversation.item.create",item:{type:"function_call_output",call_id:e.item.call_id,output:JSON.stringify(n)}}),th({type:"response.create"}))})();break;case"response.done":(null==(l=e.response)?void 0:l.output)&&e.response.output.forEach(e=>{if("function_call"===e.type){"scratchpad"===e.name&&console.log("\uD83D\uDDD2ï¸ [SCRATCHPAD] Function call found in response.done (should already be handled)");return}e.content&&e.content.forEach(e=>{let t="";("text"===e.type||"output_text"===e.type)&&e.text?t=e.text:("audio"===e.type||"output_audio"===e.type)&&e.transcript&&(t=e.transcript),t&&n.addVoiceMessage({role:"assistant",content:t,timestamp:new Date})})});break;case"billing:update":e.totalCost&&n.set("voiceTotalCost",e.totalCost)}}))},[td,n,s,u,th,tu,eW,O,to,tm,eY,e$]),(0,k.useEffect)(()=>{if(tr){if(tr.message.toLowerCase().includes("microphone access is required")){U("denied"),L(!0);return}ts||(P(!1),R(!1),F(!1),n.set("isVoiceActive",!1))}},[tr,ts,n]),(0,k.useEffect)(()=>(ts?V.current=setInterval(()=>{let e=tp();e&&(N(e),n.set("voiceUsageStats",e))},1e3):V.current&&(clearInterval(V.current),V.current=null),()=>{V.current&&clearInterval(V.current)}),[ts,tp,n]);let tg=(0,k.useCallback)(async()=>{em(!1),C(!1),eO(!1),eD(!1),eM(!1),eB(!1),P(!0);try{let e=async()=>{var e;if("undefined"==typeof navigator||!(null==(e=navigator.mediaDevices)?void 0:e.getUserMedia))return U("unsupported"),L(!0),!1;try{let e=navigator.permissions;
1if(null==e?void 0:e.query){let t=await e.query({name:"microphone"});if("denied"===t.state)return U("denied"),L(!0),!1}}catch(e){}return!0};if(!await e())return void n.set("isVoiceActive",!1);n.set("isVoiceActive",!0),n.set("voiceModel",n.voiceModel||ei.Hr),0===n.voiceMessages.length&&(n.set("voiceTotalCost",0),N(null)),await tl()}catch(e){console.error("Failed to start voice conversation:",e),e instanceof Error&&e.message.toLowerCase().includes("microphone access is required")?(U("denied"),L(!0)):q.$e.show({title:"Failed to Start",message:"Could not start voice conversation. Please try again.",color:"red"}),n.set("isVoiceActive",!1)}finally{P(!1)}},[n,tl]),tv=(0,k.useCallback)(async()=>{try{P(!1),C(!1),eO(!1),eD(!1),eM(!1),eB(!1),R(!1),F(!1),eY(),n.set("isVoiceActive",!1),K.current.clear(),et.current.clear(),await tu()}catch(e){console.error("Failed to end voice conversation:",e),eY(),K.current.clear(),et.current.clear(),n.set("isVoiceActive",!1)}},[tu,n,eY]),tf=(0,k.useCallback)(async()=>{var e;await tv(),n.set("mode",_.Dp.chat);let t=null==(e=n.properties)?void 0:e.slug;t?m.push("/conversation/".concat(t)):m.push("/conversation/new")},[tv,n,m]);(0,k.useEffect)(()=>{let e=()=>{(n.isVoiceActive||ts||ta||M)&&(P(!1),n.set("isVoiceActive",!1),tu())};return window.addEventListener("beforeunload",e),window.addEventListener("pagehide",e),()=>{window.removeEventListener("beforeunload",e),window.removeEventListener("pagehide",e)}},[n,tu,ts,ta,M]),(0,k.useEffect)(()=>()=>{P(!1),n.set("isVoiceActive",!1),tu()},[n,tu]);let ty=(0,k.useCallback)(()=>{let e=!v;f(e),tc(e)},[v,tc]),tx=(0,k.useCallback)(async e=>{if(!e||e===y||es.current)return void C(!1);es.current=!0,C(!1);try{if(x(e),!(n.isVoiceActive||ts))return;await tu(),n.set("isVoiceActive",!0),await tl()}catch(e){console.error("Failed to switch voice during active session:",e),n.set("isVoiceActive",!1)}finally{es.current=!1}},[y,tu,n,tl,ts]),tb=(0,k.useCallback)(async e=>{if(!e||e===e3)return void em(!1);if(n.set("voiceModel",e),em(!1),n.isVoiceActive||ts)try{await tu(),n.set("isVoiceActive",!0),await tl()}catch(e){console.error("Failed to switch voice model during active session:",e),n.set("isVoiceActive",!1)}},[e3,n,ts,tu,tl]),tw=(0,k.useCallback)(e=>{let t=eL[e],n=er.current;if(!t)return;if(n&&eU===e){n.pause(),n.currentTime=0,er.current=null,eG(null);return}n&&(n.pause(),n.currentTime=0,er.current=null,eG(null));let i=new Audio(t);er.current=i,eG(e),i.onended=()=>{eG(t=>t===e?null:t),er.current===i&&(er.current=null)},i.onerror=()=>{eG(t=>t===e?null:t),er.current===i&&(er.current=null)},i.play().catch(()=>{eG(t=>t===e?null:t),er.current===i&&(er.current=null)})},[eL,eU]),tk=O?"rgba(255, 184, 107, 0.48)":j?"rgba(80, 182, 255, 0.45)":"rgba(17, 233, 187, 0.45)",tT=ts?(Math.sin(.7*eu)+1)/2:0,tS="0 0 ".concat(10+18*tT,"px rgba(47, 201, 255, ").concat(.16+.28*tT,")"),tE=()=>(0,i.jsxs)(l.Box,{style:{position:"relative",width:220,height:220,display:"flex",alignItems:"center",justifyContent:"center",borderRadius:"50%",boxShadow:ts?tS:"none",transition:"box-shadow 140ms ease",background:O?"radial-gradient(circle, rgba(255, 190, 120, 0.14) 0%, rgba(151, 99, 34, 0.05) 58%, transparent 74%)":j?"radial-gradient(circle, rgba(80, 182, 255, 0.12) 0%, rgba(34, 124, 191, 0.05) 58%, transparent 74%)":"radial-gradient(circle, rgba(17, 233, 187, 0.1) 0%, rgba(1, 90, 158, 0.03) 58%, transparent 74%)"},"aria-label":"Voice status: ".concat(e0),children:[Array.from({length:24}).map((e,t)=>{let n=15*t,o=tt(t),s=O||j&&t%2==0,a={position:"absolute",top:"50%",left:"50%",width:4,height:o,borderRadius:999,transform:"translate(-50%, -50%) rotate(".concat(n,"deg) translateY(-").concat(96,"px)"),transformOrigin:"center center",background:s?O?"linear-gradient(180deg, #ffd08a 0%, #ff9f43 100%)":"linear-gradient(180deg, #6fd3ff 0%, #32a4f7 100%)":"linear-gradient(180deg, rgba(17, 233, 187, 0.65) 0%, rgba(1, 90, 158, 0.5) 100%)",opacity:O?1:j?.85:.55,boxShadow:s?"0 0 10px ".concat(tk):"none",transition:"opacity 120ms ease"};return(0,i.jsx)(l.Box,{style:a},"halo-bar-".concat(t))}),(0,i.jsx)(l.Box,{style:{width:74,height:74,borderRadius:"50%",display:"flex",alignItems:"center",justifyContent:"center",background:O?"linear-gradient(145deg, rgba(121, 79, 20, 0.3), rgba(255, 193, 110, 0.15))":j?"linear-gradient(145deg, rgba(24, 87, 132, 0.28), rgba(111, 211, 255, 0.12))":"linear-gradient(145deg, rgba(1, 90, 158, 0.2), rgba(17, 233, 187, 0.1))",border:O?"1px solid rgba(255, 199, 117, 0.48)":j?"1px solid rgba(111, 211, 255, 0.45)":"1px solid rgba(17, 233, 187, 0.28)"},children:(0,i.jsx)(ek.default,{src:"/logo.png",alt:"NanoGPT",width:46,height:46,style:{objectFit:"contain"}})})]}),t_=(0,i.jsx)(W.a,{opened:B,onClose:()=>L(!1),title:"Microphone access needed",centered:!0,children:(0,i.jsxs)(o.Stack,{gap:"sm",children:[(0,i.jsx)(r.Text,{size:"sm",children:"unsupported"===z?"Your browser does not support microphone input for realtime voice.":"To start voice mode, allow microphone access when your browser asks."}),(0,i.jsx)(r.Text,{size:"sm",c:"dimmed",children:"denied"===z?"Microphone permission appears blocked. Enable it in your browser/site settings, then try Begin again.":"If you previously blocked it, you can re-enable it in browser/site settings."}),(0,i.jsx)(a.Group,{justify:"flex-end",children:(0,i.jsx)(d.Button,{variant:"light",onClick:()=>L(!1),children:"Got it"})})]})}),tI=!ts&&(M||ta||n.isVoiceActive),tA=ts||tI?null:(e=>e?"INSUFFICIENT_REALTIME_CREDITS"===(e=>{let t=null==e?void 0:e.code;return"string"==typeof t?t:null})(e)?"Realtime voice needs at least $1.00 in credits to start, even with an active subscription; realtime usage is billed separately.":e.message:null)(tr),tC=112*!!tA,tj=e=>"calc(100% + ".concat(e+tC,"px)");return ts?(0,i.jsxs)(i.Fragment,{children:[t_,(0,i.jsxs)(o.Stack,{gap:0,mb:0,children:[(0,i.jsxs)(l.Box,{style:{position:"relative",width:"100%",minHeight:s.isDesktop?s.contentWindowMah:"65vh",display:"flex",alignItems:"center",justifyContent:"center",zIndex:20},children:[(0,i.jsxs)(l.Box,{ref:en,style:{position:"relative",width:220,height:220},children:[(0,i.jsx)(l.Box,{onClick:tv,role:"button","aria-label":"Tap to end voice conversation",style:{cursor:"pointer",WebkitTapHighlightColor:"transparent",WebkitUserSelect:"none",userSelect:"none"},children:tE()}),(0,i.jsx)(r.Text,{size:"sm",c:"dimmed",style:{position:"absolute",top:"calc(100% + 14px)",left:"50%",transform:"translateX(-50%)",whiteSpace:"nowrap"},children:"Tap again to stop conversation"}),(0,i.jsxs)(a.Group,{gap:4,wrap:"nowrap",justify:"center",style:{position:"absolute",top:"calc(100% + 112px)",left:"50%",transform:"translateX(-50%)",cursor:"pointer"},onClick:e=>{e.stopPropagation(),C(!1),eO(!1),eD(!1),eM(!1),em(e=>!e)},"aria-label":"Select voice model",children:[(0,i.jsx)(r.Text,{size:"sm",c:"dimmed",style:{whiteSpace:"nowrap"},children:e9}),eh?(0,i.jsx)(X.A,{size:14}):(0,i.jsx)(Q.A,{size:14})]}),(0,i.jsxs)(a.Group,{gap:4,wrap:"nowrap",justify:"center",style:{position:"absolute",top:"calc(100% + 136px)",left:"50%",transform:"translateX(-50%)",cursor:"pointer"},onClick:e=>{e.stopPropagation(),em(!1),eD(!1),eM(!1),C(e=>!e)},"aria-label":"Select voice",children:[(0,i.jsx)(r.Text,{size:"sm",c:"dimmed",style:{whiteSpace:"nowrap"},children:e1}),A?(0,i.jsx)(X.A,{size:14}):(0,i.jsx)(Q.A,{size:14})]}),(0,i.jsxs)(a.Group,{gap:4,wrap:"nowrap",justify:"center",style:{position:"absolute",top:"calc(100% + 160px)",left:"50%",transform:"translateX(-50%)",cursor:"pointer"},onClick:e=>{e.stopPropagation();let t=!eP;eB(t),t||(eO(!1),eD(!1),eM(!1))},"aria-label":"Toggle more voice settings",children:[(0,i.jsx)(r.Text,{size:"sm",c:"dimmed",style:{whiteSpace:"nowrap"},children:"More settings"}),eP?(0,i.jsx)(X.A,{size:14}):(0,i.jsx)(Q.A,{size:14})]}),!S&&eP&&(0,i.jsxs)(a.Group,{gap:4,wrap:"nowrap",justify:"center",style:{position:"absolute",top:"calc(100% + 184px)",left:"50%",transform:"translateX(-50%)",cursor:"pointer"},onClick:e=>{e.stopPropagation(),C(!1),em(!1),eO(!1),eD(!1),eM(e=>!e)},"aria-label":"Adjust response delay",children:[(0,i.jsx)(r.Text,{size:"sm",c:"dimmed",style:{whiteSpace:"nowrap"},children:te}),eN?(0,i.jsx)(X.A,{size:14}):(0,i.jsx)(Q.A,{size:14})]}),!S&&eP&&(0,i.jsxs)(a.Group,{gap:4,wrap:"nowrap",justify:"center",style:{position:"absolute",top:"calc(100% + 208px)",left:"50%",transform:"translateX(-50%)",cursor:"pointer"},onClick:e=>{e.stopPropagation(),C(!1),em(!1),eM(!1),eO(!1),eD(e=>!e)},"aria-label":"Adjust speaking speed",children:[(0,i.jsx)(r.Text,{size:"sm",c:"dimmed",style:{whiteSpace:"nowrap"},children:e7}),eF?(0,i.jsx)(X.A,{size:14}):(0,i.jsx)(Q.A,{size:14})]}),eP&&(0,i.jsxs)(a.Group,{gap:4,wrap:"nowrap",justify:"center",style:{position:"absolute",top:"calc(100% + 232px)",left:"50%",transform:"translateX(-50%)",cursor:"pointer"},onClick:e=>{e.stopPropagation(),C(!1),em(!1),eM(!1),eD(!1),eO(e=>!e)},"aria-label":"Select instructions preset",children:[(0,i.jsx)(r.Text,{size:"sm",c:"dimmed",style:{whiteSpace:"nowrap"},children:e6}),ej?(0,i.jsx)(X.A,{size:14}):(0,i.jsx)(Q.A,{size:14})]}),(0,i.jsx)(a.Group,{justify:"center",style:{position:"absolute",top:"calc(100% + 64px)",left:"50%",transform:"translateX(-50%)"}
1,children:(0,i.jsx)(p.ActionIcon,{size:"lg",radius:"xl",variant:"transparent",onClick:ty,"aria-label":v?"Unmute microphone":"Mute microphone",style:{padding:6,color:"var(--mantine-color-dimmed)"},children:v?(0,i.jsx)(Z.A,{size:20}):(0,i.jsx)(ee.A,{size:20})})}),eh&&(0,i.jsx)(H.Card,{withBorder:!0,p:6,style:{...eC,position:"absolute",top:"calc(100% + 140px)",left:"50%",transform:"translateX(-50%)",width:220,maxWidth:"min(220px, 86vw)"},onClick:e=>e.stopPropagation(),children:(0,i.jsx)(o.Stack,{gap:2,children:eS.map(e=>(0,i.jsxs)(l.Box,{role:"button",tabIndex:0,style:{display:"flex",alignItems:"center",justifyContent:"space-between",borderRadius:8,padding:"6px 8px",background:e3===e.value?"rgba(255, 255, 255, 0.08)":"transparent",cursor:"pointer"},onClick:()=>{tb(e.value)},onKeyDown:t=>{("Enter"===t.key||" "===t.key)&&(t.preventDefault(),tb(e.value))},children:[(0,i.jsx)(r.Text,{size:"sm",c:"dimmed",children:e.label}),e3===e.value?(0,i.jsx)(J.A,{size:14,color:"var(--mantine-color-gray-4)"}):null]},e.value))})}),A&&(0,i.jsx)(H.Card,{withBorder:!0,p:6,style:{...eC,position:"absolute",top:"calc(100% + 164px)",left:"50%",transform:"translateX(-50%)",width:220,maxWidth:"min(220px, 86vw)"},onClick:e=>e.stopPropagation(),children:(0,i.jsx)(o.Stack,{gap:2,children:E.map(e=>(0,i.jsxs)(l.Box,{role:"button",tabIndex:0,style:{display:"flex",alignItems:"center",justifyContent:"space-between",borderRadius:8,padding:"6px 8px",background:I===e.value?"rgba(255, 255, 255, 0.08)":"transparent",cursor:"pointer"},onClick:()=>{tx(e.value),C(!1)},onKeyDown:t=>{("Enter"===t.key||" "===t.key)&&(t.preventDefault(),tx(e.value),C(!1))},children:[(0,i.jsxs)(a.Group,{gap:8,wrap:"nowrap",children:[(0,i.jsx)(r.Text,{size:"sm",c:"dimmed",children:e.label}),eL[e.value]&&(0,i.jsx)(p.ActionIcon,{variant:"transparent",size:"sm",color:"gray",onClick:t=>{t.stopPropagation(),tw(e.value)},"aria-label":eU===e.value?"Stop ".concat(e.label," preview"):"Play ".concat(e.label," preview"),children:eU===e.value?(0,i.jsx)(Y.A,{size:13}):(0,i.jsx)($.A,{size:13})})]}),I===e.value&&(0,i.jsx)(J.A,{size:14,color:"var(--mantine-color-gray-4)"})]},e.value))})}),ej&&(0,i.jsx)(H.Card,{withBorder:!0,p:6,style:{...eC,position:"absolute",top:"calc(100% + 256px)",left:"50%",transform:"translateX(-50%)",width:260,maxWidth:"min(260px, 90vw)"},onClick:e=>e.stopPropagation(),children:(0,i.jsxs)(o.Stack,{gap:2,children:[(0,i.jsx)(r.Text,{size:"xs",c:"dimmed",px:8,py:4,children:"Instructions"}),c.presets.map(e=>{var t,o;return(0,i.jsxs)(l.Box,{role:"button",tabIndex:0,style:{display:"flex",alignItems:"center",justifyContent:"space-between",borderRadius:8,padding:"6px 8px",background:e4===(null==(t=e.id)?void 0:t.toString())?"rgba(255, 255, 255, 0.08)":"transparent",cursor:"pointer"},onClick:()=>{var t;n.set("instructions",e.instructions),c.setLastUsedSelection(e.instructions,(null==(t=e.id)?void 0:t.toString())||""),eO(!1)},children:[(0,i.jsx)(r.Text,{size:"sm",c:"dimmed",children:e.name}),e4===(null==(o=e.id)?void 0:o.toString())?(0,i.jsx)(J.A,{size:14,color:"var(--mantine-color-gray-4)"}):null]},e.id)}),(0,i.jsx)(l.Box,{style:{borderTop:"1px solid rgba(255,255,255,0.1)",margin:"6px 0"}}),(0,i.jsxs)(l.Box,{role:"button",tabIndex:0,style:{display:"flex",alignItems:"center",justifyContent:"space-between",borderRadius:8,padding:"6px 8px",background:e8?"rgba(255, 255, 255, 0.08)":"transparent",cursor:"pointer"},onClick:()=>{n.set("instructions",""),c.clearLastUsedSelection(),eO(!1)},children:[(0,i.jsx)(r.Text,{size:"sm",c:"dimmed",children:"No instructions"}),e8?(0,i.jsx)(J.A,{size:14,color:"var(--mantine-color-gray-4)"}):null]}),(0,i.jsx)(l.Box,{style:{borderTop:"1px solid rgba(255,255,255,0.1)",margin:"6px 0"}}),(0,i.jsx)(l.Box,{role:"button",tabIndex:0,style:{borderRadius:8,padding:"6px 8px",cursor:"pointer"},onClick:()=>{s.setShowSystemPromptModal(!0),eO(!1)},children:(0,i.jsx)(r.Text,{size:"sm",c:"dimmed",children:"Manage instructionsâ¦"})})]})}),!S&&eF&&(0,i.jsx)(H.Card,{withBorder:!0,p:6,style:{...eC,position:"absolute",top:"calc(100% + 232px)",left:"50%",transform:"translateX(-50%)",width:220,maxWidth:"min(220px, 86vw)"},onClick:e=>e.stopPropagation(),children:(0,i.jsx)(o.Stack,{gap:2,children:eE.map(e=>(0,i.jsxs)(l.Box,{role:"button",tabIndex:0,style:{display:"flex",alignItems:"center",justifyContent:"space-between",borderRadius:8,padding:"6px 8px",background:.001>Math.abs(e.value-eV)?"rgba(255, 255, 255, 0.08)":"transparent",curs
1or:"pointer"},onClick:()=>{eK(e.value),eD(!1)},onKeyDown:t=>{("Enter"===t.key||" "===t.key)&&(t.preventDefault(),eK(e.value),eD(!1))},children:[(0,i.jsxs)(r.Text,{size:"sm",c:"dimmed",children:[e.label," (",e.value.toFixed(2),"x)"]}),.001>Math.abs(e.value-eV)?(0,i.jsx)(J.A,{size:14,color:"var(--mantine-color-gray-4)"}):null]},e.value))})}),!S&&eN&&(0,i.jsx)(H.Card,{withBorder:!0,p:6,style:{...eC,position:"absolute",top:"calc(100% + 208px)",left:"50%",transform:"translateX(-50%)",width:220,maxWidth:"min(220px, 86vw)"},onClick:e=>e.stopPropagation(),children:(0,i.jsx)(o.Stack,{gap:2,children:e_.map(e=>(0,i.jsxs)(l.Box,{role:"button",tabIndex:0,style:{display:"flex",alignItems:"center",justifyContent:"space-between",borderRadius:8,padding:"6px 8px",background:8>Math.abs(e.value-eW)?"rgba(255, 255, 255, 0.08)":"transparent",cursor:"pointer"},onClick:()=>{eQ.current=0,to(e.value),eM(!1)},onKeyDown:t=>{("Enter"===t.key||" "===t.key)&&(t.preventDefault(),eQ.current=0,to(e.value),eM(!1))},children:[(0,i.jsxs)(r.Text,{size:"sm",c:"dimmed",children:[e.label," (",e.value,"ms)"]}),8>Math.abs(e.value-eW)?(0,i.jsx)(J.A,{size:14,color:"var(--mantine-color-gray-4)"}):null]},e.value))})})]}),ts&&D&&(0,i.jsx)(l.Box,{style:{position:"fixed",bottom:"calc(env(safe-area-inset-bottom, 0px) + ".concat(s.isDesktop?8:4,"px)"),left:"50%",transform:"translateX(-50%)",width:"min(520px, calc(100% - 16px))",zIndex:40},children:(0,i.jsxs)(o.Stack,{gap:"xs",children:[(0,i.jsx)(a.Group,{justify:"flex-end",align:"center",wrap:"nowrap",children:(0,i.jsxs)(a.Group,{gap:4,wrap:"nowrap",children:[(0,i.jsx)(d.Button,{size:"compact-xs",variant:"subtle",color:"gray",onClick:tf,children:"Open chat"}),(0,i.jsx)(p.ActionIcon,{variant:"subtle",size:"sm",onClick:()=>ep(e=>!e),"aria-label":ed?"Hide advanced voice stats":"Show advanced voice stats",children:ed?(0,i.jsx)(X.A,{size:16}):(0,i.jsx)(Q.A,{size:16})})]})}),ed&&(0,i.jsxs)(a.Group,{justify:"space-between",gap:"xs",wrap:"wrap",children:[(0,i.jsxs)("div",{children:[(0,i.jsx)(r.Text,{size:"xs",c:"dimmed",children:"Audio Input"}),(0,i.jsxs)(r.Text,{size:"xs",fw:500,children:[D.audioInputTokens||0," tokens"]})]}),(0,i.jsxs)("div",{children:[(0,i.jsx)(r.Text,{size:"xs",c:"dimmed",children:"Audio Output"}),(0,i.jsxs)(r.Text,{size:"xs",fw:500,children:[D.audioOutputTokens||0," tokens"]})]}),(0,i.jsxs)("div",{children:[(0,i.jsx)(r.Text,{size:"xs",c:"dimmed",children:"Text Tokens"}),(0,i.jsx)(r.Text,{size:"xs",fw:500,children:(D.textInputTokens||0)+(D.textOutputTokens||0)}),(0,i.jsxs)(r.Text,{size:"xs",c:"dimmed",children:[D.textInputTokens||0,"â ",D.textOutputTokens||0,"â"]})]})]})]})})]}),tr&&(0,i.jsx)(r.Text,{size:"xs",c:"red",ta:"center",children:tr.message})]})]}):(0,i.jsxs)(i.Fragment,{children:[t_,(0,i.jsx)(l.Box,{style:{position:"relative",width:"100%",minHeight:s.isDesktop?s.contentWindowMah:"65vh",display:"flex",alignItems:"center",justifyContent:"center",zIndex:20},children:(0,i.jsx)(o.Stack,{gap:0,align:"center",justify:"center",style:{cursor:s.online?"pointer":"default",WebkitTapHighlightColor:"transparent",WebkitUserSelect:"none",userSelect:"none"},onClick:s.online?tI?tv:tg:void 0,role:"button","aria-label":tI?"Tap to cancel voice connection":"Tap to begin voice conversation",children:(0,i.jsxs)(l.Box,{ref:en,style:{position:"relative",width:220,height:220},children:[tE(),(0,i.jsx)(r.Text,{size:"sm",c:"dimmed",style:{position:"absolute",top:"calc(100% + 14px)",left:"50%",transform:"translateX(-50%)",whiteSpace:"nowrap"},children:tI?"Connecting voice chat...":"Tap to begin voice chat"}),tA&&(0,i.jsx)(r.Text,{size:"xs",c:"red",ta:"center",style:{position:"absolute",top:"calc(100% + 42px)",left:"50%",transform:"translateX(-50%)",width:"min(360px, 88vw)",lineHeight:1.35},children:tA}),!tI&&(0,i.jsxs)(a.Group,{gap:4,wrap:"nowrap",justify:"center",style:{position:"absolute",top:tj(94),left:"50%",transform:"translateX(-50%)",cursor:"pointer"},onClick:e=>{e.stopPropagation(),C(!1),eO(!1),em(e=>!e)},"aria-label":"Select voice model",children:[(0,i.jsx)(r.Text,{size:"sm",c:"dimmed",style:{whiteSpace:"nowrap"},children:e9}),eh?(0,i.jsx)(X.A,{size:14}):(0,i.jsx)(Q.A,{size:14})]}),!tI&&(0,i.jsxs)(a.Group,{gap:4,wrap:"nowrap",justify:"center",style:{position:"absolute",top:tj(120),left
1:"50%",transform:"translateX(-50%)",cursor:"pointer"},onClick:e=>{e.stopPropagation(),em(!1),eO(!1),eD(!1),C(e=>!e)},"aria-label":"Select voice",children:[(0,i.jsx)(r.Text,{size:"sm",c:"dimmed",style:{whiteSpace:"nowrap"},children:e1}),A?(0,i.jsx)(X.A,{size:14}):(0,i.jsx)(Q.A,{size:14})]}),!tI&&(0,i.jsxs)(a.Group,{gap:4,wrap:"nowrap",justify:"center",style:{position:"absolute",top:tj(146),left:"50%",transform:"translateX(-50%)",cursor:"pointer"},onClick:e=>{e.stopPropagation();let t=!eP;eB(t),t||(eO(!1),eD(!1),eM(!1))},"aria-label":"Toggle more voice settings",children:[(0,i.jsx)(r.Text,{size:"sm",c:"dimmed",style:{whiteSpace:"nowrap"},children:"More settings"}),eP?(0,i.jsx)(X.A,{size:14}):(0,i.jsx)(Q.A,{size:14})]}),!tI&&eP&&(0,i.jsxs)(a.Group,{gap:4,wrap:"nowrap",justify:"center",style:{position:"absolute",top:tj(172),left:"50%",transform:"translateX(-50%)",cursor:"pointer"},onClick:e=>{e.stopPropagation(),em(!1),C(!1),eD(!1),eO(e=>!e)},"aria-label":"Select instructions preset",children:[(0,i.jsx)(r.Text,{size:"sm",c:"dimmed",style:{whiteSpace:"nowrap"},children:e6}),ej?(0,i.jsx)(X.A,{size:14}):(0,i.jsx)(Q.A,{size:14})]}),!S&&!tI&&eP&&(0,i.jsxs)(a.Group,{gap:4,wrap:"nowrap",justify:"center",style:{position:"absolute",top:tj(198),left:"50%",transform:"translateX(-50%)",cursor:"pointer"},onClick:e=>{e.stopPropagation(),em(!1),C(!1),eO(!1),eD(e=>!e),eM(!1)},"aria-label":"Adjust speaking speed",children:[(0,i.jsx)(r.Text,{size:"sm",c:"dimmed",style:{whiteSpace:"nowrap"},children:e7}),eF?(0,i.jsx)(X.A,{size:14}):(0,i.jsx)(Q.A,{size:14})]}),!S&&!tI&&eP&&(0,i.jsxs)(a.Group,{gap:4,wrap:"nowrap",justify:"center",style:{position:"absolute",top:tj(224),left:"50%",transform:"translateX(-50%)",cursor:"pointer"},onClick:e=>{e.stopPropagation(),em(!1),C(!1),eO(!1),eD(!1),eM(e=>!e)},"aria-label":"Adjust response delay",children:[(0,i.jsx)(r.Text,{size:"sm",c:"dimmed",style:{whiteSpace:"nowrap"},children:te}),eN?(0,i.jsx)(X.A,{size:14}):(0,i.jsx)(Q.A,{size:14})]}),eh&&!tI&&(0,i.jsx)(H.Card,{withBorder:!0,p:6,style:{...eC,position:"absolute",top:tj(122),left:"50%",transform:"translateX(-50%)",width:220,maxWidth:"min(220px, 86vw)"},onClick:e=>e.stopPropagation(),children:(0,i.jsx)(o.Stack,{gap:2,children:eS.map(e=>(0,i.jsxs)(l.Box,{role:"button",tabIndex:0,style:{display:"flex",alignItems:"center",justifyContent:"space-between",borderRadius:8,padding:"6px 8px",background:e3===e.value?"rgba(255, 255, 255, 0.08)":"transparent",cursor:"pointer"},onClick:()=>{n.set("voiceModel",e.value),em(!1)},onKeyDown:t=>{("Enter"===t.key||" "===t.key)&&(t.preventDefault(),n.set("voiceModel",e.value),em(!1))},children:[(0,i.jsx)(r.Text,{size:"sm",c:"dimmed",children:e.label}),e3===e.value?(0,i.jsx)(J.A,{size:14,color:"var(--mantine-color-gray-4)"}):null]},e.value))})}),A&&!tI&&(0,i.jsx)(H.Card,{withBorder:!0,p:6,style:{...eC,position:"absolute",top:tj(148),left:"50%",transform:"translateX(-50%)",width:220,maxWidth:"min(220px, 86vw)"},onClick:e=>e.stopPropagation(),children:(0,i.jsx)(o.Stack,{gap:2,children:E.map(e=>(0,i.jsxs)(l.Box,{role:"button",tabIndex:0,style:{display:"flex",alignItems:"center",justifyContent:"space-between",borderRadius:8,padding:"6px 8px",background:I===e.value?"rgba(255, 255, 255, 0.08)":"transparent",cursor:"pointer"},onClick:()=>{tx(e.value),C(!1)},onKeyDown:t=>{("Enter"===t.key||" "===t.key)&&(t.preventDefault(),tx(e.value),C(!1))},children:[(0,i.jsxs)(a.Group,{gap:8,wrap:"nowrap",children:[(0,i.jsx)(r.Text,{size:"sm",c:"dimmed",children:e.label}),eL[e.value]&&(0,i.jsx)(p.ActionIcon,{variant:"transparent",size:"sm",color:"gray",onClick:t=>{t.stopPropagation(),tw(e.value)},"aria-label":eU===e.value?"Stop ".concat(e.label," preview"):"Play ".concat(e.label," preview"),children:eU===e.value?(0,i.jsx)(Y.A,{size:13}):(0,i.jsx)($.A,{size:13})})]}),I===e.value&&(0,i.jsx)(J.A,{size:14,color:"var(--mantine-color-gray-4)"})]},e.value))})}),ej&&!tI&&(0,i.jsx)(H.Card,{withBorder:!0,p:6,style:{...eC,position:"absolute",top:tj(200),left:"50%",transform:"translateX(-50%)",width:260,maxWidth:"min(260px, 90vw)"},onClick:e=>e.stopPropagation(),children:(0,i.jsxs)(o.Stack,{gap:2,children:[(0,i.jsx)(r.Text,{size:"xs",c:"dimmed",px:8,py:4,children:"Instructions"}),c.presets.map(e=>{var t,o;return(0,i.jsxs)(l.Box,{role:"button",tabIndex:0,style:{display:"flex",alignItems:"center",justifyContent:"space-between",borderRadius:8,padding:"6px 8px",background:e4===(null==(t=e.id)?void 0:t.toString())?"rgba(255, 255, 255, 0.08)":"transparent",curs
1or:"pointer"},onClick:()=>{var t;n.set("instructions",e.instructions);let i=(0,ex.b4)(e.model||"");if(i&&ey.Z$[i])try{n.setTextModel(i,!1)}catch(e){}let o=(0,eb.Sw)(e.advancedSettings);o&&(0,eb.dz)(n,o),c.setLastUsedSelection(e.instructions,(null==(t=e.id)?void 0:t.toString())||""),eO(!1)},children:[(0,i.jsx)(r.Text,{size:"sm",c:"dimmed",children:e.name}),e4===(null==(o=e.id)?void 0:o.toString())?(0,i.jsx)(J.A,{size:14,color:"var(--mantine-color-gray-4)"}):null]},e.id)}),(0,i.jsx)(l.Box,{style:{borderTop:"1px solid rgba(255,255,255,0.1)",margin:"6px 0"}}),(0,i.jsxs)(l.Box,{role:"button",tabIndex:0,style:{display:"flex",alignItems:"center",justifyContent:"space-between",borderRadius:8,padding:"6px 8px",background:e8?"rgba(255, 255, 255, 0.08)":"transparent",cursor:"pointer"},onClick:()=>{n.set("instructions",""),c.clearLastUsedSelection(),eO(!1)},children:[(0,i.jsx)(r.Text,{size:"sm",c:"dimmed",children:"No instructions"}),e8?(0,i.jsx)(J.A,{size:14,color:"var(--mantine-color-gray-4)"}):null]}),(0,i.jsx)(l.Box,{style:{borderTop:"1px solid rgba(255,255,255,0.1)",margin:"6px 0"}}),(0,i.jsx)(l.Box,{role:"button",tabIndex:0,style:{borderRadius:8,padding:"6px 8px",cursor:"pointer"},onClick:()=>{s.setShowSystemPromptModal(!0),eO(!1)},children:(0,i.jsx)(r.Text,{size:"sm",c:"dimmed",children:"Manage instructionsâ¦"})})]})}),!S&&eF&&!tI&&(0,i.jsx)(H.Card,{withBorder:!0,p:6,style:{...eC,position:"absolute",top:tj(226),left:"50%",transform:"translateX(-50%)",width:220,maxWidth:"min(220px, 86vw)"},onClick:e=>e.stopPropagation(),children:(0,i.jsx)(o.Stack,{gap:2,children:eE.map(e=>(0,i.jsxs)(l.Box,{role:"button",tabIndex:0,style:{display:"flex",alignItems:"center",justifyContent:"space-between",borderRadius:8,padding:"6px 8px",background:.001>Math.abs(e.value-eV)?"rgba(255, 255, 255, 0.08)":"transparent",cursor:"pointer"},onClick:()=>{eK(e.value),eD(!1)},onKeyDown:t=>{("Enter"===t.key||" "===t.key)&&(t.preventDefault(),eK(e.value),eD(!1))},children:[(0,i.jsxs)(r.Text,{size:"sm",c:"dimmed",children:[e.label," (",e.value.toFixed(2),"x)"]}),.001>Math.abs(e.value-eV)?(0,i.jsx)(J.A,{size:14,color:"var(--mantine-color-gray-4)"}):null]},e.value))})}),!S&&eN&&!tI&&(0,i.jsx)(H.Card,{withBorder:!0,p:6,style:{...eC,position:"absolute",top:tj(252),left:"50%",transform:"translateX(-50%)",width:220,maxWidth:"min(220px, 86vw)"},onClick:e=>e.stopPropagation(),children:(0,i.jsx)(o.Stack,{gap:2,children:e_.map(e=>(0,i.jsxs)(l.Box,{role:"button",tabIndex:0,style:{display:"flex",alignItems:"center",justifyContent:"space-between",borderRadius:8,padding:"6px 8px",background:8>Math.abs(e.value-eW)?"rgba(255, 255, 255, 0.08)":"transparent",cursor:"pointer"},onClick:()=>{eQ.current=0,to(e.value),eM(!1)},onKeyDown:t=>{("Enter"===t.key||" "===t.key)&&(t.preventDefault(),eQ.current=0,to(e.value),eM(!1))},children:[(0,i.jsxs)(r.Text,{size:"sm",c:"dimmed",children:[e.label," (",e.value,"ms)"]}),8>Math.abs(e.value-eW)?(0,i.jsx)(J.A,{size:14,color:"var(--mantine-color-gray-4)"}):null]},e.value))})})]})})})]})});var eD=n(76794),eN=n(69742),eM=n(35382),eP=n(44043),eB=n(61637),eL=n(76270),ez=n(35452),eU=n(278),eG=n(89869),eV=n(52927),eK=n(51008);let eW=(0,w.default)(()=>Promise.all([n.e(91954),n.e(53965),n.e(31637),n.e(63181),n.e(73491),n.e(67585),n.e(10493)]).then(n.bind(n,67585)).then(e=>e.SystemPromptModal),{loadableGenerated:{webpack:()=>[67585]},ssr:!1,loading:()=>null}),eH=(0,w.default)(()=>Promise.all([n.e(96394),n.e(77326),n.e(89368),n.e(45879)]).then(n.bind(n,89368)).then(e=>e.ImageModal),{loadableGenerated:{webpack:()=>[89368]},ssr:!1,loading:()=>null}),eq=(0,w.default)(()=>n.e(75410).then(n.bind(n,75410)).then(e=>e.EmptyResponseModal),{loadableGenerated:{webpack:()=>[75410]},ssr:!1,loading:()=>null}),eX=(0,w.default)(()=>Promise.all([n.e(69641),n.e(6079),n.e(43009),n.e(6697),n.e(64910),n.e(32874)]).then(n.bind(n,64910)).then(e=>e.SplitScreenCodeViewer),{loadableGenerated:{webpack:()=>[64910]},ssr:!1,loading:()=>null}),eQ=(0,w.default)(()=>Promise.all([n.e(43011),n.e(55577)]).then(n.bind(n,55577)).then(e=>e.Scratchpad),{loadableGenerated:{webpack:()=>[55577]},ssr:!1,loading:()=>null}),eJ=()=>Promise.all([n.e(31593),n.e(91954),n.e(84214),n.e(85041),n.e(48056),n.e(17099),n.e(76710),n.e(84466),n.e(9866),n.e(12401),n.e(91659),n.e(16072),n.e(93763),n.e(79544),n.e(31703)]).then(n.bind(n,79544)).then(e=>
1e.WelcomeScrollContent),eY=(0,w.default)(eJ,{ssr:!1,loading:()=>(0,i.jsx)(eZ,{announce:!0})}),e$=e=>{let t=window,n=!1,i=()=>{n||e()};if("function"==typeof t.requestIdleCallback){let e=t.requestIdleCallback(i,{timeout:2e3});return()=>{var i;n=!0,null==(i=t.cancelIdleCallback)||i.call(t,e)}}let o=window.setTimeout(i,200);return()=>{n=!0,window.clearTimeout(o)}};function eZ(e){let{announce:t=!1}=e;return(0,i.jsxs)(o.Stack,{"data-testid":"welcome-scroll-content-skeleton",role:t?"status":void 0,"aria-label":t?"Loading more to explore":void 0,"aria-hidden":!t||void 0,gap:"md",mt:"md",w:"100%",children:[(0,i.jsx)(s.Skeleton,{height:88,radius:"md"}),(0,i.jsxs)(a.Group,{grow:!0,align:"stretch",children:[(0,i.jsx)(s.Skeleton,{height:72,radius:"md"}),(0,i.jsx)(s.Skeleton,{height:72,radius:"md"})]})]})}let e0=e=>e?e.replace(/\s+/g," ").trim():"",e1=null,e5=()=>"function"!=typeof window.matchMedia?null:(null!=e1||(e1=window.matchMedia(E.r3)),e1),e2=e=>{let t=e5();return t?"function"==typeof t.addEventListener?(t.addEventListener("change",e),()=>t.removeEventListener("change",e)):(t.addListener(e),()=>t.removeListener(e)):()=>{}},e4=()=>{var e,t;return null!=(t=null==(e=e5())?void 0:e.matches)&&t},e8=()=>!1,e6=(0,b.PA)(e=>{var t,n,s,b,w,E,W,H;let q,{slug:X,voiceOnly:Q=!1}=e,{ui:J,conversation:Y}=(0,g.useStores)(),$=(0,T.useRouter)(),Z=(0,T.useSearchParams)(),[ee,et]=(0,k.useState)(!1),[en,ei]=(0,k.useState)(!1),[eo,es]=(0,k.useState)(!1),[ea,er]=(0,k.useState)(!1),[el,eu]=(0,k.useState)(!1),[ec,ed]=(0,k.useState)(!1),ep=(0,k.useRef)(null),[eh,em]=(0,k.useState)(!1),[eg,ev]=(0,k.useState)(!1),[ef,ey]=(0,k.useState)(!1),ex=(0,k.useSyncExternalStore)(e2,e4,e8);(0,eV.N)(Y.isStreaming&&!ex);let eb="new"===X,ew=!!X&&"new"!==X,ek=Y.lastInitializedSlug===X&&Y.initializingSlug!==X,eT=ew&&Y.missingConversationSlug===X&&Y.initializingSlug!==X&&Y.lastInitializedSlug===X,eS=ew&&Y.conversationLoadErrorSlug===X&&Y.initializingSlug!==X,eE=ew&&!eT&&!eS&&(Y.initializingSlug===X||!ek&&((null==(t=Y.properties)?void 0:t.slug)!==X||!0!==Y.initialized)),e_=Number.parseInt(((null==Z?void 0:Z.get("projectId"))||"").trim(),10),eI=Number.isFinite(e_)&&e_>0?e_:null,eA=(0,y.kk)(async()=>{let e=eI;if(!e){var t;let n=Number(null==(t=Y.properties)?void 0:t.id);if(Number.isFinite(n)&&n>0){let t=await x.projectConversationsTable.where("conversationId").equals(n).first();"number"==typeof(null==t?void 0:t.projectId)&&Number.isFinite(t.projectId)&&t.projectId>0&&(e=t.projectId)}}if(!e)return null;let n=await x.projectsTable.get(e),[i,o]=await Promise.all([x.projectLibraryTable.where("projectId").equals(e).count(),x.projectLibraryTable.where("projectId").equals(e).limit(12).toArray()]),s=o.flatMap(e=>"number"==typeof e.libraryId&&Number.isFinite(e.libraryId)?[e.libraryId]:[]),a=new Map((s.length>0?await x.libraryTable.where("id").anyOf(s).toArray():[]).flatMap(e=>"number"==typeof(null==e?void 0:e.id)&&Number.isFinite(e.id)?[[e.id,e]]:[])),r=s.map(e=>{let t=a.get(e);return("string"==typeof(null==t?void 0:t.name)?t.name.trim():"")||"File #".concat(String(e))});return n?{projectId:e,projectName:(n.name||"").trim()||"Project ".concat(e),projectRouteKey:(n.projectKey||"").trim()||String(e),fileCount:i,fileNames:r}:null},[eI,null==(n=Y.properties)?void 0:n.id]),eC=(0,k.useCallback)(()=>{(null==eA?void 0:eA.projectRouteKey)&&$.push("/workspace/project/".concat(encodeURIComponent(eA.projectRouteKey)))},[null==eA?void 0:eA.projectRouteKey,$]),ej=(0,k.useMemo)(()=>{var e;let t=null!=(e=null==eA?void 0:eA.fileCount)?e:0;return"".concat(t," file").concat(1===t?"":"s"," available")},[null==eA?void 0:eA.fileCount]),eR=void 0===eA&&null!==eI&&!eh,eF=(0,k.useMemo)(()=>!eA||Y.mode!==_.Dp.chat||(0,v.dZ)(String(Y.model.text||"")),[eA,Y.mode,Y.model.text]),e1=(0,k.useCallback)(()=>{X&&Y.initialize({slug:X}).catch(e=>{(0,eK.F)(e)})},[Y,X]);(0,k.useEffect)(()=>{em(!1),ev(!1),ey(!1)},[null==eA?void 0:eA.projectId]);let e5=J.codeViewerOpened&&J.activeCode,e6=J.scratchpadOpened,e3=Array.isArray(Y.messages)&&Y.messages.length>0,e9=(null==(s=Y.state)?void 0:s.isPending)===!0,e7=Y.submitPreview,te=(0,eL.a)(Y),tt=(null==(b=Y.state)?void 0:b.isPreparingSubmit)===!0&&!e9&&!e7,tn=Y.isNewConversation&&!e9&&!e3&&!e7,ti=!Q&&(!!e7||e9||!Y.isNewConversation&&e3),to=J.isDesktop?J.codeViewerFullscreen:e5,ts=J.isDesktop?J.scratchpadFullscreen:e6,ta=Y.isActiveConversationPasskeyLocked;(0,eG.z)(Y.messages,{notificationsEnabled:J.browserNotificationsEnabled&&!ta,hapticFeedbackEnabled:J.hapticFeedbackEnabled,completionSound:J.responseCompletionSound,completionSoundVolume:J.responseCompletionSoundVolume,conversationSlug:null==(w=Y.properties)?void 0:w.slug,isStreaming:Y.isStreaming,isPending:Y.state.isPending});let tr=e0(Y.name),tl=(0,k.useMemo)(()=>(e=>{if(!Array.isArray(e)||0===e.length)return"";let t=t=>{for(let n of e){if(t&&n.role!==t)continue;let e=e0(n.prompt);if(e)return e}return""},n=t("user")||t();return n?n.split(" ").slice(0,10).join(" "):""})(Y.messages),[Y.messages]),tu=e0(null==(E=Y.properties)?void 0:E.latestMessage),tc=(null==(W=Y.properties)?void 0:W.isPasskeyProtected)?F.CE:tr||(Y.isIncognito?"Incognito chat":tl||tu||"New conversation"),td="".concat((0,f.g)(tc,80)," | NanoGPT"),tp=function(){let e=arguments.length>0&&void 0!==arguments[0]&&arguments[0];e&&es(!0),ee||et(!0)};(0,k.useEffect)(()=>{document.title=td},[td]),(0,k.useEffect)(()=>{J.systemPromptModalVisible&&er(!0),J.imageModalOpened&&eu(!0),Y.emptyResponseError&&ed(!0)},[Y.emptyResponseError,J.imageModalOpened,J.systemPromptModalVisible]),(0,k.useEffect)(()=>
1{if(!eo||!ee)return;let e=0,t=!1,n=()=>{var i;if(t)return;let o=null==(i=ep.current)?void 0:i.querySelector('a[href], button:not([disabled]), [tabindex]:not([tabindex="-1"])');if(o){o.focus(),es(!1);return}e=window.requestAnimationFrame(n)};return e=window.requestAnimationFrame(n),()=>{t=!0,window.cancelAnimationFrame(e)}},[eo,ee]),(0,k.useEffect)(()=>{if(Q){Y.mode!==_.Dp.voice&&Y.set("mode",_.Dp.voice);return}Y.mode===_.Dp.voice&&Y.set("mode",_.Dp.chat)},[Q,Y.mode,Y]),(0,k.useEffect)(()=>{if(eb&&Y.isNewConversation&&!Q&&!ee)return e$(()=>{eJ().catch(()=>{})})},[Y.isNewConversation,eb,ee,Q]),(0,k.useEffect)(()=>{let e;if(!eb||!Y.isNewConversation||Q){eo&&es(!1),ee&&et(!1);return}if(ee)return;let t=()=>{et(!0)},n=e=>{let n=e.target;n&&("INPUT"===n.tagName||"TEXTAREA"===n.tagName||"SELECT"===n.tagName||n.isContentEditable)||("ArrowDown"===e.key||"PageDown"===e.key||"End"===e.key||" "===e.key)&&t()};if(window.scrollY>0||document.documentElement.scrollTop>0||document.body.scrollTop>0)return void t();let i=window.requestAnimationFrame(()=>{document.documentElement.scrollHeight<=window.innerHeight+1&&document.body.scrollHeight<=window.innerHeight+1&&(e=e$(t))});return window.addEventListener("scroll",t,{passive:!0,once:!0}),window.addEventListener("wheel",t,{passive:!0,once:!0}),window.addEventListener("touchmove",t,{passive:!0,once:!0}),window.addEventListener("keydown",n),document.addEventListener("scroll",t,{passive:!0,capture:!0,once:!0}),()=>{window.cancelAnimationFrame(i),null==e||e(),window.removeEventListener("scroll",t),window.removeEventListener("wheel",t),window.removeEventListener("touchmove",t),window.removeEventListener("keydown",n),document.removeEventListener("scroll",t,!0)}},[Y.isNewConversation,eb,eo,ee,Q]);let th=J.isDesktop||ex?{marginLeft:"auto",marginRight:"auto",width:J.inputWidth,maxWidth:"100%"}:{width:"100%",maxWidth:"100%"},tm="dark"===J.resolvedColorScheme,tg=tm?"var(--mantine-color-teal-1)":"var(--mantine-color-teal-9)",tv=tm?"var(--mantine-color-gray-4)":"var(--mantine-color-teal-8)",tf=te?U.iJ:[U.iJ,U.pZ,U.Ax].join(" "),ty=(0,i.jsxs)(o.Stack,{className:tf,"data-conversation-composer-status":!0,"data-conversation-composer-mobile-first":!te||void 0,"data-conversation-composer-status-reserve":!te||void 0,align:"center",gap:"xs",children:[Y.isIncognito&&(0,i.jsx)(r.Text,{size:"xs",c:"dimmed",ta:"center",maw:520,children:"Incognito chats and temporary images are not saved to history, browser storage, or NanoGPT memory. Request content is still sent to the selected model provider."}),(0,i.jsx)(B.A,{}),(0,i.jsx)(L.A,{dismissed:en,onDismiss:()=>ei(!0)}),(0,i.jsx)(P.T,{})]}),tx=(0,i.jsxs)(K.o,{children:[(0,i.jsxs)(o.Stack,{align:"center",gap:0,maw:800,children:[(0,i.jsx)(ez.mG,{}),(0,i.jsx)(ez.o6,{isProjectMode:!!(eA&&Y.mode===_.Dp.chat)}),Q&&(0,i.jsx)(eO,{})]}),!Q&&(0,i.jsxs)(l.Box,{"data-conversation-input-alignment":!0,style:th,children:[(0,i.jsxs)(o.Stack,{gap:5,justify:"center",w:"100%",children:[eR||eA&&!eh?(0,i.jsx)(l.Box,{className:"".concat(A.hJ," ").concat(eR?A.g$:""),"data-conversation-banner-slot":"project","aria-hidden":eR?"true":void 0,children:eA&&!eh?(0,i.jsx)(u.Paper,{withBorder:!0,radius:"md",p:"xs",style:{background:tm?"var(--mantine-color-dark-8)":"var(--mantine-color-teal-0)",borderColor:tm?"rgba(16, 185, 129, 0.25)":"rgba(13, 148, 136, 0.4)"},children:(0,i.jsxs)(o.Stack,{gap:4,children:[(0,i.jsxs)(a.Group,{justify:"space-between",align:"center",wrap:"wrap",gap:"xs",children:[(0,i.jsxs)(a.Group,{gap:4,wrap:"wrap",align:"center",children:[(0,i.jsxs)(r.Text,{size:"sm",style:{color:tm?"var(--mantine-color-teal-2)":"var(--mantine-color-teal-8)"},children:["Working in project â",eA.projectName,"â \xb7"]}),(0,i.jsx)(c.UnstyledButton,{onClick:()=>ev(e=>!e),onMouseEnter:()=>ey(!0),onMouseLeave:()=>ey(!1),style:{lineHeight:1},children:(0,i.jsx)(r.Text,{size:"sm",style:{color:tm?"var(--mantine-color-teal-2)":"var(--mantine-color-teal-9)"},fw:600,td:eg||ef?"underline":"none",children:ej})})]}),(0,i.jsxs)(a.Group,{gap:4,align:"center",wrap:"nowrap",children:[(0,i.jsx)(d.Button,{size:"compact-xs",variant:"subtle",color:"teal",onClick:eC,children:"Manage project"}),(0,i.jsx)(p.ActionIcon,{size:"sm",variant:"subtle",color:"teal",onClick:()=>em(!0),"aria-label":"Dismiss project banner",children:(0,i.jsx)(S.A,{size:14})})]})]}),eF?null:(0,i.jsx)(r.Text,{size:"xs",c:"orange",children:"This model cannot use project tools. Pick a tool-calling model before sending messages in this project."}),(0,i.jsx)(h.S,{in:eg,children:(0,i.jsx)(o.Stack,{gap:2,mt:4,pt:6,style:{borderTop:"1px solid ".concat(tm?"rgba(16, 185, 129, 0.2)":"rgba(13, 148, 136, 0.3)")},children:0===(eA.fileNames||[]).length?(0,i.jsx)(r.Text,{size:"xs",style:{color:tv},children:"No project files linked yet."}):(0,i.jsxs)(i.Fragment,{children:[(eA.fileNames||[]).slice(0,12).map(e=>(0,i.jsxs)(r.Text,{size:"xs",style:{color:tg},children:["⢠",e]},e)),(eA.fileCount||0)>12?(0,i.jsxs)(r.Text,{size:"xs",style:{color:tv},children:["Showing 12 of ",eA.fileCount," files here. Use project search tools to find the rest."]}):null,(eA.fileNames||[]).length>12?(0,i.jsxs)(r.Text,{size:"xs",style:{color:tv},children:["+",(eA.fileNames||[]).length-12," more"]}):null]})})})]})}):null}):null,(0,i.jsx)(G.X,{}),(0,i.jsx)(V.s,{showControls:!1}),(0,i.jsx)(I.T,{}),(0,i.jsx)(eN.K,{canShow:null===eA}),(0,i.jsxs)(l.Box,{className:U.z6,"data-conversation-composer-boundary":!0,children:[(0,i.jsx)(a.Group,{gap:5,wrap:"nowrap",w:"100%",align:"center",children:(0,i.jsx)(z.s,{})}),ty]})]}),te&&(0,i.jsx)(N.w,{})]})]}),tb=Q?tx:(0,i.jsxs)(o.Stack,{className:M.yr,gap:0,children:[(0,i.jsxs)(o.Stack,{className:M.os,gap:0,children:[(0,i.jsx)(D.m,{}),tx]}),!ee||eo?(0,i.jsx)(a.Group,{justify:"center",children:(0,i.jsx)(d.Button,{variant:"subtle",size:"compact-sm",onFocus:()=>tp(!0),onClick:()=>
1tp(!0),children:eo?"Loading more sections":"Continue exploring"})}):null,ee?null:(0,i.jsx)(eZ,{}),(0,i.jsx)(l.Box,{ref:ep,children:ee?(0,i.jsx)(eY,{}):null})]}),tw=(0,i.jsx)(C.Y,{slug:X}),tk=eS?(0,i.jsxs)(o.Stack,{align:"center",justify:"center",mih:"50dvh",gap:"xs",px:"md",children:[(0,i.jsx)(r.Text,{fw:600,children:"Conversation storage unavailable"}),(0,i.jsx)(r.Text,{size:"sm",c:"dimmed",ta:"center",maw:460,children:"NanoGPT could not read this conversation from browser storage. Check the storage recovery notice, then retry or reload. Do not clear site data before preserving any local conversations you need."}),(0,i.jsx)(d.Button,{variant:"light",size:"compact-sm",onClick:e1,children:"Retry"})]}):eT?(0,i.jsxs)(o.Stack,{align:"center",justify:"center",mih:"50dvh",gap:"xs",px:"md",children:[(0,i.jsx)(r.Text,{fw:600,children:"Conversation not found"}),(0,i.jsx)(r.Text,{size:"sm",c:"dimmed",ta:"center",maw:420,children:"It may have been deleted or not synced to this device yet."}),(0,i.jsx)(d.Button,{variant:"light",size:"compact-sm",onClick:e1,children:"Retry"})]}):eE?(0,i.jsx)(R.h,{statusLabel:"Loading conversation messages",insetBottomHandledByParent:!0}):(0,i.jsxs)(i.Fragment,{children:[tt&&(0,i.jsx)(eP.j,{}),!Q&&(0,i.jsx)(eM.$,{}),(Y.isNewConversation&&!ti&&!e7||Q)&&(0,i.jsx)(eD.y,{}),ti&&(0,i.jsx)(eB.MessageList,{}),tn?tb:tx,(0,i.jsx)(eU.a,{onDismiss:()=>Y.dismissVideoPromptTooLongNotice()}),ea&&(0,i.jsx)(eW,{}),el&&(0,i.jsx)(eH,{}),ec&&(0,i.jsx)(eq,{})]}),tT=ta?(0,i.jsxs)(j.f,{children:[tw,(0,i.jsx)(O.u,{conversationUuid:null==(H=Y.properties)?void 0:H.uuid,beginUnlock:Y.beginPasskeyUnlock,markUnlocked:Y.markPasskeyConversationUnlocked,endUnlock:Y.endPasskeyUnlock,isDesktop:J.isDesktop,resolvedColorScheme:J.resolvedColorScheme,sidebarOpen:J.sidebarOpen,setSidebarOpen:J.setSidebarOpen})]}):(0,i.jsxs)(j.f,{children:[tw,tk]}),tS=!ta&&J.activeCode?(0,i.jsx)(eX,{code:J.activeCode.code,language:J.activeCode.language,title:J.activeCode.title,opened:J.codeViewerOpened,onClose:()=>{J.setCodeViewerOpened(!1),J.setActiveCode(void 0),J.setCodeViewerFullscreen(!1)},onCodeChange:e=>{J.activeCode&&J.setActiveCode({...J.activeCode,code:e})}}):null,tE=!ta&&e6?(0,i.jsx)(eQ,{opened:J.scratchpadOpened,onClose:J.closeScratchpad}):null,t_=tT,tI=(0,i.jsx)(l.Box,{}),tA=100,tC=100,tj=100;return e5&&to&&tS?(t_=tS,tI=tT,tA=100):e6&&ts&&tE?(t_=tE,tI=tT,tA=100):e5&&!to&&tS?(tI=tS,tA=J.codeViewerHorizontalSplit,q=e=>J.setCodeViewerHorizontalSplit(e),tC=20,tj=80):e6&&!ts&&tE&&(tI=tE,tA=J.scratchpadHorizontalSplit,q=e=>J.setScratchpadHorizontalSplit(e),tC=20,tj=80),(0,i.jsx)(m.W2,{left:t_,right:tI,split:tA,onSplitChange:q,minSplit:tC,maxSplit:tj,disabled:100===tC})}),e3=e=>(0,i.jsx)(k.Suspense,{fallback:null,children:(0,i.jsx)(e6,{...e})})},93171:(e,t,n)=>{n.d(t,{Fx:()=>A,zR:()=>C,LF:()=>I});var i=n(95155),o=n(46460),s=n(12658),a=n(6584),r=n(61915),l=n(52645),u=n(7498),c=n(52181),d=n(48303),p=n(22476),h=n(34362),m=n(23070),g=n(7138),v=n(47965),f=n(6829),y=n(73321),x=n(12115),b=n(93986),w=n(40966),k=n(96420);let T=e=>String(e).padStart(2,"0"),S=function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:new Date,n=(0,w.F)(e);return 0!==n.length&&((0,k.o)(n,"incognito-chat-".concat(t.getFullYear(),"-").concat(T(t.getMonth()+1),"-").concat(T(t.getDate())),"Incognito chat"),!0)};var E=n(51008),_=n(63781);let I=()=>{var e;let{conversation:t,ui:n}=(0,v.useStores)(),i=(0,b.S)(),o=(0,y.useRouter)(),s=(0,y.usePathname)(),[a,r]=x.useState(!1),l=x.useCallback(()=>{var e,n,i,o;return(t.prompt||"").trim().length>0||((null==(e=t.attachments)?void 0:e.length)||0)>0||((null==(n=t.scrapedUrls)?void 0:n.length)||0)>0||((null==(i=t.scrapedContent)?void 0:i.length)||0)>0||((null==(o=t.messages)?void 0:o.length)||0)>0},[t]),u=x.useCallback(e=>{let t=(0,_.Sn)(s),n=e?(0,_.Rk)(e,t?"chat":"classic"):t?"/chat":"/conversation/new";s!==n&&o.push(n)},[s,o]),c=x.useCallback(()=>{(0,_.T9)(s)&&t.initialize({slug:"new"}).catch(e=>{(0,E.F)(e)})},[t,s]),p=t.state.isPending||t.state.isPreparingSubmit||t.isStreaming,h=((null==(e=t.messages)?void 0:e.length)||0)>
10,m=h&&!p&&!a,g=h&&!p&&!a,f=x.useCallback(async()=>{if(!t.isIncognito)(!l()||await i({title:"Start an incognito chat?",message:"This opens a new chat. Your current chat remains in history.",confirmLabel:"Start incognito chat"}))&&t.confirmNavigationAway()&&(t.setIncognitoEnabled(!0),u(null),c())},[i,t,u,l,c]),w=x.useCallback(async()=>{if(!t.confirmNavigationAway())return;let e=t.consumeIncognitoReturnSlug()||n.previousConversationSlug;t.setIncognitoEnabled(!1),u(e),e||c()},[t,u,c,n.previousConversationSlug]),k=x.useCallback(async()=>{if(t.isIncognito&&m&&!a){r(!0);try{let e=await t.convertIncognitoToPersistent();e&&u(e)}catch(e){console.error("[IncognitoControls] Unexpected error saving incognito chat",e)}finally{r(!1)}}},[m,t,a,u]),T=x.useCallback(()=>{if(t.isIncognito&&g)try{S(t.messages)||d.$e.show({title:"Nothing to export",message:"Send a message before exporting this chat.",color:"yellow"})}catch(e){console.error("[IncognitoControls] Failed to export incognito chat",e),d.$e.show({title:"Export failed",message:"Could not download this chat. Please try again.",color:"red"})}},[g,t]);return{conversation:t,canExport:g,canSave:m,handleEnable:f,handleDisable:w,handleExportMarkdown:T,handleSave:k,isSaving:a}},A=(0,f.PA)(()=>{let{conversation:e,canExport:t,canSave:n,handleDisable:d,handleExportMarkdown:v,handleSave:f,isSaving:y}=I();return e.isIncognito?(0,i.jsx)(o.Box,{style:{position:"absolute",top:0,left:0,right:0,zIndex:30,pointerEvents:"auto"},children:(0,i.jsx)(s.Paper,{radius:0,shadow:"sm",style:{backgroundColor:"var(--mantine-color-dark-7)",color:"var(--mantine-color-white)",pointerEvents:"auto"},children:(0,i.jsxs)(a.Group,{justify:"space-between",px:"md",py:"md",wrap:"nowrap",children:[(0,i.jsxs)(a.Group,{gap:8,wrap:"nowrap",children:[(0,i.jsx)(p.A,{size:18}),(0,i.jsx)(r.Text,{size:"md",fw:600,children:"Incognito chat"})]}),(0,i.jsxs)(a.Group,{gap:8,wrap:"nowrap",children:[(0,i.jsx)(l.Tooltip,{label:"Export Markdown without saving this chat to history",withArrow:!0,children:(0,i.jsx)(u.ActionIcon,{variant:"light",color:"blue",size:"md","aria-label":"Export Markdown",onClick:v,disabled:!t,children:(0,i.jsx)(h.A,{size:18})})}),(0,i.jsx)(l.Tooltip,{label:"Save this chat to your history",withArrow:!0,disabled:y,children:(0,i.jsx)(c.Button,{variant:"light",color:"green",size:"xs",leftSection:(0,i.jsx)(m.A,{size:16}),onClick:f,disabled:!n,loading:y,children:"Save"})}),(0,i.jsx)(l.Tooltip,{label:"Exit incognito",withArrow:!0,children:(0,i.jsx)(u.ActionIcon,{variant:"subtle",color:"gray",size:"md","aria-label":"Exit incognito",onClick:d,children:(0,i.jsx)(g.A,{size:18})})})]})]})})}):null}),C=(0,f.PA)(e=>{let{compact:t=!1,compactSize:n="sm"}=e,{conversation:o,handleEnable:s}=I();if(o.isIncognito||!o.isNewConversation)return null;let a="undefined"!=typeof navigator&&/Mac|iPod|iPhone|iPad/.test(navigator.platform),r="Use incognito ".concat(a?"â§âI":"â§CtrlI"),c=t?n:"xl";return(0,i.jsx)(l.Tooltip,{label:r,withArrow:!0,position:"bottom",children:(0,i.jsx)(u.ActionIcon,{variant:"subtle",size:c,radius:"xl",c:"dimmed","aria-label":r,onClick:s,children:(0,i.jsx)(p.A,{size:"md"===c?"1.25rem":"sm"===c?"1.125rem":24})})})})}
1,95362:(e,t,n)=>{n.d(t,{Y:()=>i});let i={withinPortal:!1,position:"bottom",middlewares:{flip:!1,shift:!1},keepMounted:!1}},96420:(e,t,n)=>{n.d(t,{_:()=>l,o:()=>u});var i=n(86672),o=n(98064),s=n(44693),a=n(90430);let r=(e,t)=>{let n=t.webSearchResults;Array.isArray(n)&&0!==n.length&&(e.push("### Sources\n\n"),n.forEach((n,i)=>{if(!(null==n?void 0:n.url))return;let o="number"==typeof n.sourceIndex&&Number.isFinite(n.sourceIndex)?n.sourceIndex:i+1,s=((e,t)=>{var n,i;let o=null==(n=e.webSearchResults)?void 0:n[t];return(null==o||null==(i=o.title)?void 0:i.trim())||(null==o?void 0:o.url)||"Source ".concat(t+1)})(t,i).replace(/\\/g,"\\\\").replace(/\[/g,"\\[").replace(/\]/g,"\\]");e.push("".concat(o,". [").concat(s,"](").concat(n.url,")\n"))}),e.push("\n"))},l=(e,t)=>{let n=["# Nano-GPT.com\n\n"];for(let u of(t&&n.push("## Conversation: ".concat(t,"\n\n")),e)){var l;let e="user"===u.role?(0,o.Bk)(u.prompt||""):(0,s.K)(u.prompt||"",u.webSearchResults);if(n.push("## ".concat((0,i.Z)(u.role||"Unknown"),"\n"),"##### ".concat((0,a.E)(u.timestamp),"\n\n"),"".concat(e,"\n\n")),null==(l=u.images)?void 0:l.length)for(let[e,t]of u.images.entries())t.b64_json?n.push(".concat(t.b64_json,")\n\n")):t.url&&n.push(".concat(t.url,")\n\n"));u.completion&&n.push("*Tokens: Input ".concat(u.completion.inputTokens,", Output ").concat(u.completion.outputTokens,"*\n\n")),r(n,u),n.push("---\n\n")}return n.join("")},u=(e,t,n)=>{let i=new Blob([l(e,n)],{type:"text/markdown"}),o=URL.createObjectURL(i),s=document.createElement("a");s.href=o,s.download=t+".md",document.body.appendChild(s),s.click(),document.body.removeChild(s),URL.revokeObjectURL(o)}}}]);
Line numbers count LF bytes from the start of the resource, as the search results do. Vendor segments are library code the classifier recognised; they are stored but not indexed. Bytes are shown as Latin1 characters, one per byte.