PageSourceSearch

https://whop.com/_web/assets/gha-36830342614-1/ai-chat-state-DzJDKTRV.js

js whop.com collected 2026-10-01 08:52:01 UTC 35,643 bytes, 4 lines download raw bytes

1
2!function(){try{var e="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:{},n=(new e.Error).stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="f75363b4-3735-50de-8c9e-c8affd0f6a61")}catch(e){}}();
3import{o as e}from"./rolldown-runtime-CMxvf4Kt.js";import{Ca as t,wa as n}from"./frosted-ui-C-IlupeO.js";import{t as r}from"./useRouter-CXQWTBlB.js";import{m as i}from"./useQuery-BjchxOEi.js";import{t as a}from"./env-hqZPCsXO.js";import{r as o}from"./exports-BhwNzoD3.js";import{n as s,t as c}from"./safe-internal-path-BHALxEa_.js";import{t as l}from"./get-session-C7BEKgXR.js";import{t as u}from"./fetcher-B4iehi-C.js";import{$ as d,et as f}from"./operations-Bdh8uwto.js";import{f as ee}from"./types-D8zNp4wx.js";import{t as te}from"./Observable-CC4J3rk8.js";import{a as p,c as ne,i as m,l as h,n as g,o as _,r as v,s as y,t as b,u as x}from"./query-keys-ONcwhtsh.js";import{di as re,mu as ie,si as ae}from"./index-BK_sTHql.js";import{n as oe}from"./product-surface-tracker-C2l78nC8.js";import{a as se,n as ce,r as le,t as ue}from"./create-optimistic-user-message-DpT-lgEK.js";import{r as S}from"./use-right-sidebar-CKqIzgts.js";import{n as de}from"./dist-jQ0htEWX.js";import{i as fe}from"./use-dev-mode-B1yRjOap.js";import{t as pe}from"./use-play-sound-CEHYQ-ds.js";var C=e(n(),1),w=re()(e=>{let t=new Map;return{generatingIds:new Set,activeProviderIds:new Set,setGenerating:(t,n)=>e(e=>{if(e.generatingIds.has(t)===n)return e;let r=new Set(e.generatingIds);return n?r.add(t):r.delete(t),{generatingIds:r}}),registerActiveProvider:n=>(t.set(n,(t.get(n)??0)+1),e({activeProviderIds:new Set(t.keys())}),()=>{let r=(t.get(n)??1)-1;r>0?t.set(n,r):t.delete(n),e({activeProviderIds:new Set(t.keys())})})}});function T(e){return w(t=>t.generatingIds.has(e))}var E=new Set;function me(e){return E.add(e),()=>E.delete(e)}function D(e){if(E.has(e))return!0;let t=S.getState();return t.isOpen&&t.activePanel===`ai-chat`&&t.aiChatView==="default"&&t.selectedChatId===e}var O=`app_acX6tWhzECntTn`;async function k(e){let t=await u(d)({input:{appId:O,codeChallenge:e}});if(!t.generateInternalOauthCode?.code)throw Error(`Failed to generate AI auth code`);return t.generateInternalOauthCode.code}var A=new Set([`AI chat disconnected while recording Intercom handoff offer`,`Timed out recording Intercom handoff offer`,`Intercom handoff offer tracking temporarily failed`]),he=class{chatId;ws=null;reconnectTimer=null;reconnectAttempt=0;sendBuffer=[];authenticated=!1;pkceAttempt=0;pkceTimer=null;connectionActive=!1;intercomHandoffPreparations=new Map;intercomHandoffButtonUnavailableReports=new Map;intercomHandoffOfferRenderReports=new Map;serverCapabilities=null;serverCapabilitiesWaiters=new Map;url;staticToken;constructor(e,t){this.chatId=e,this.url=new URL(`/agent/v1/ai_chats/${e}/ws`,a),this.staticToken=t??null}send(e){e.type===`authenticate`||this.authenticated&&this.ws?.readyState===WebSocket.OPEN?this.ws?.send(JSON.stringify(e)):this.sendBuffer.push({message:e,expiresAt:Date.now()+1e4})}async prepareIntercomHandoff(e){let t=await this.waitForServerCapabilities();if(t===null)throw Error(`Unable to confirm Intercom handoff support`);if(!t.has(`prepare_intercom_handoff`))return;let n=crypto.randomUUID();return new Promise((t,r)=>{let i=setTimeout(()=>{this.intercomHandoffPreparations.delete(n),this.sendBuffer=this.sendBuffer.filter(({message:e})=>e.type!==`prepare_intercom_handoff`||e.requestId!==n),r(Error(`Timed out preparing Intercom handoff`))},5e3);this.intercomHandoffPreparations.set(n,{resolve:t,reject:r,timeout:i}),this.send({type:`prepare_intercom_handoff`,escalationId:e,requestId:n})})}async recordIntercomHandoffButtonUnavailable(e){let t=Date.now()+1e4;for(;Date.now()<t;){let t=await this.waitForServerCapabilities();if(t===null){if(!this.connectionActive)throw Error(`AI chat closed before recording unavailable handoff button`);continue}if(!t.has(`record_intercom_handoff_button_unavailable`))return;try{await this.sendIntercomHandoffButtonUnavailableReport(e);return}catch(e){if(!this.connectionActive||!(e instanceof Error)||e.message!==`AI chat disconnected while recording unavailable Intercom handoff button`)throw e}}throw Error(`Unable to confirm unavailable Intercom handoff button was recorded`)}async recordIntercomHandoffOfferRendered(e,t){let n=250;for(;!t.aborted;){let r=await this.waitForServerCapabilities();if(t.throwIfAborted(),r===null){if(!this.connectionActive)throw Error(`AI chat closed before recording Intercom handoff offer`);await new Promise(e=>setTimeout(e,n)),t.throwIfAborted(),n=Math.min(n*2,2e3);continue}let i=r.has(`record_intercom_handoff_offer_rendered`)?`rendered`:r.has(`record_intercom_handoff_offer_presented`)?`presented`:null;if(!i){await new Promise(e=>setTimeout(e,n)),t.throwIfAborted(),n=Math.min(n*2,2e3);continue}try{await this.sendIntercomHandoffOfferRenderReport(e,i);return}catch(e){if(t.throwIfAborted(),!this.connectionActive||!(e instanceof Error)||!A.has(e.message))throw e;await new Promise(e=>setTimeout(e,n)),t.throwIfAborted(),n=Math.min(n*2,2e3)}}t.throwIfAborted()}connect(e={}){let{onStatus:t,onMessage:n}=e,r={value:!0};this.connectionActive=!0;let i=!0,a=()=>
3{if(this.reconnectTimer||!r.value||!i)return;let e=Math.min(100*2**this.reconnectAttempt,1e4);this.reconnectAttempt++,this.reconnectTimer=setTimeout(()=>{this.reconnectTimer=null,o()},e)},o=()=>{r.value&&(this.ws&&this.ws.readyState<=WebSocket.OPEN||(this.staticToken?this.url.searchParams.set(`token`,this.staticToken):this.url.searchParams.delete(`token`),this.ws=new WebSocket(this.url),this.ws.onopen=()=>{this.reconnectAttempt=0,this.pkceAttempt=0},this.ws.onclose=()=>{this.authenticated=!1,this.rejectIntercomHandoffPreparations(),this.rejectIntercomHandoffButtonUnavailableReports(),this.rejectIntercomHandoffOfferRenderReports(),this.resolveUnavailableServerCapabilities(),this.pkceTimer&&=(clearTimeout(this.pkceTimer),null),t?.(!1),a()},this.ws.onerror=()=>this.ws?.close(),this.ws.onmessage=async e=>{try{let r=JSON.parse(e.data);if(r.type===`authenticated`){if(r.result.canRead)this.authenticated=!0,this.pkceAttempt=0,this.pkceTimer&&=(clearTimeout(this.pkceTimer),null),t?.(!0),this.flushSendBuffer();else if(this.staticToken){i=!1,this.ws?.close();return}else if(r.result.codeChallenge){let{codeChallenge:e}=r.result,t=this.pkceAttempt===0?0:Math.min(50*2**this.pkceAttempt,3e4);this.pkceAttempt++,this.pkceTimer&&clearTimeout(this.pkceTimer),this.pkceTimer=setTimeout(async()=>{this.pkceTimer=null;try{let t=await k(e);this.send({type:`authenticate`,data:{type:`code`,aiChatId:this.chatId,code:t,codeChallenge:e}})}catch(e){console.error(`PKCE auth failed`,e),this.ws?.close()}},t);return}}if(r.type===`intercom_handoff_prepared`){this.resolveIntercomHandoffPreparation(r.requestId);return}if(r.type===`intercom_handoff_button_unavailable_reported`){this.resolveIntercomHandoffButtonUnavailableReport(r.requestId);return}if(r.type===`intercom_handoff_offer_rendered_recorded`||r.type===`intercom_handoff_offer_presented_recorded`){this.resolveIntercomHandoffOfferRenderReport(r.requestId);return}if(r.type===`initial`&&this.resolveServerCapabilities(r.capabilities??[]),r.type===`error`&&r.requestId){this.resolveIntercomHandoffPreparation(r.requestId,Error(r.message)),this.resolveIntercomHandoffButtonUnavailableReport(r.requestId,Error(r.message)),this.resolveIntercomHandoffOfferRenderReport(r.requestId,Error(r.message));return}n?.(r)}catch{n?.(e.data)}}))};return o(),()=>{r.value=!1,this.reconnectTimer&&=(clearTimeout(this.reconnectTimer),null),this.pkceTimer&&=(clearTimeout(this.pkceTimer),null),this.reconnectAttempt=0,this.pkceAttempt=0,this.authenticated=!1,this.connectionActive=!1,this.rejectIntercomHandoffPreparations(),this.rejectIntercomHandoffButtonUnavailableReports(),this.rejectIntercomHandoffOfferRenderReports(),this.resolveUnavailableServerCapabilities(),this.ws&&=(this.ws.onclose=null,this.ws.close(),null)}}rejectIntercomHandoffPreparations(){let e=new Set(this.intercomHandoffPreparations.keys());for(let e of this.intercomHandoffPreparations.values())clearTimeout(e.timeout),e.reject(Error(`AI chat disconnected while preparing Intercom handoff`));this.intercomHandoffPreparations.clear(),this.sendBuffer=this.sendBuffer.filter(({message:t})=>t.type!==`prepare_intercom_handoff`||!e.has(t.requestId))}rejectIntercomHandoffButtonUnavailableReports(){let e=new Set(this.intercomHandoffButtonUnavailableReports.keys());for(let e of this.intercomHandoffButtonUnavailableReports.values())clearTimeout(e.timeout),e.reject(Error(`AI chat disconnected while recording unavailable Intercom handoff button`));this.intercomHandoffButtonUnavailableReports.clear(),this.sendBuffer=this.sendBuffer.filter(({message:t})=>t.type!==`record_intercom_handoff_button_unavailable`||!e.has(t.requestId))}sendIntercomHandoffButtonUnavailableReport(e){let t=crypto.randomUUID();return new Promise((n,r)=>{let i=setTimeout(()=>{this.intercomHandoffButtonUnavailableReports.delete(t),this.sendBuffer=this.sendBuffer.filter(({message:e})=>e.type!==`record_intercom_handoff_button_unavailable`||e.requestId!==t),r(Error(`Timed out recording unavailable Intercom handoff button`))},5e3);this.intercomHandoffButtonUnavailableReports.set(t,{resolve:n,reject:r,timeout:i}),this.send({type:`record_intercom_handoff_button_unavailable`,escalationId:e,requestId:t})})}rejectIntercomHandoffOfferRenderReports(){let e=new Set(this.intercomHandoffOfferRenderReports.keys());for(let e of this.intercomHandoffOfferRenderReports.values())clearTimeout(e.timeout),e.reject(Error(`AI chat disconnected while recording Intercom handoff offer`));this.intercomHandoffOfferRenderReports.clear(),this.sendBuffer=this.sendBuffer.filter(({message:t})=>t.type!==`record_intercom_handoff_offer_rendered`&&t.type!==`record_intercom_handoff_offer_presented`||!e.has(t.requestId))}sendIntercomHandoffOfferRenderReport(e,t){let n=crypto.randomUUID();return new Promise((r,i)=>{let a=setTimeout(()=>{this.intercomHandoffOfferRenderReports.delete(n),this.sendBuffer=this.sendBuffer.filter(({message:e})=>e.type!==`record_intercom_handoff_offer_rendered`&&e.type!==`record_intercom_handoff_offer_presented`||e.requestId!==n),i(Error(`Timed out recording Intercom handoff offer`))},5e3);this.intercomHandoffOfferRenderReports.set(n,{resolve:r,reject:i,timeout:a}),t===`rendered`?this.send({type:`record_intercom_handoff_offer_rendered`,escalationId:e,requestId:n}):this.send({type:`record_intercom_handoff_offer_presented`,escalationId:e,requestId:n})})}waitForServerCapabilities(){if(this.serverCapabilities)return Promise.resolve(this.serverCapabilities);let e=crypto.randomUUID();return new Promise(t=>{let n=setTimeout(()=>{this.serverCapabilitiesWaiters.delete(e),t(null)},2e3);this.serverCapabilitiesWaiters.set(e,{resolve:t,timeout:n})})}resolveServerCapabilities(e){this.serverCapabilities=new Set(e);for(let e of this.serverCapabilitiesWaiters.values())clearTimeout(e.timeout),e.resolve(this.serverCapabilities);this.serverCapabilitiesWaiters.clear()}resolveUnavailableServerCapabilities(){this.serverCapabilities=null;for(let e of this.serverCapabilitiesWaiters.values())clearTimeout(e.timeout),e.resolve(null);this.serverCapabilitiesWaiters.clear()}resolveIntercomHandoffPreparation(e,t){let n=this.intercomHandoffPreparations.get(e);n&&(clearTimeout(n.timeout),this.intercomHandoffPreparations.delete(e),t?n.reject(t):n.resolve())}resolveIntercomHandoffButtonUnavailableReport(e,t){let n=this.intercomHandoffButtonUnavailableReports.get(e);n&&(clearTimeout(n.timeout),this.intercomHandoffButtonUnavailableReports.delete(e),t?n.reject(t):n.resolve())}resolveIntercomHandoffOfferRenderReport(e,t){let n=this.intercomHandoffOfferRenderReports.get(e);n&&(clearTimeout(n.timeout),this.intercomHandoffOfferRenderReports.delete(e),t?n.reject(t):n.resolve())}flushSendBuffer(){let e=Date.now(),t=this.sendBuffer.filter(t=>t.expiresAt>e);if(this.sendBuffer=t,this.ws?.readyState===WebSocket.OPEN){for(let e of t)this.ws.send(JSON.stringify(e.message));this.sendBuffer=[]}}};function j(e){return Object.fromEntries((e??[]).map(e=>
3[e.aiChatId,e.unreadCount]))}function ge(e,t=[]){let n=new Map(t.map(e=>[e.aiChatId,e.agentIdentifier]));return Object.entries(e).map(([e,t])=>({aiChatId:e,agentIdentifier:n.get(e)??ee.General,unreadCount:t}))}function _e(e,t){e.setQueryData([`coreFetchAiChatNotificationBadges`],{aiChatNotificationBadges:t})}function M(e,t,n){e.setQueriesData({queryKey:[`coreFetchAiChatNotificationBadges`]},e=>e&&{...e,aiChatNotificationBadges:ge({...j(e.aiChatNotificationBadges),[t]:n},e.aiChatNotificationBadges)})}var N=new Set;function ve(e,t){M(e,t,0),!N.has(t)&&(N.add(t),u(f)({input:{id:t}}).catch(()=>{}).finally(()=>{N.delete(t)}))}var P=class{value;subscribers;unsubscribeListeners;isEqual=(e,t)=>e===t;get numSubscribers(){return this.subscribers.size}constructor(e){this.value=e,this.subscribers=new Set,this.unsubscribeListeners=new Set}setValue(e){if(!this.isEqual(this.value,e)){this.value=e;for(let t of this.subscribers)t(e)}}getValue(){return this.value}subscribe(e){return this.subscribers.add(e),()=>{if(this.subscribers.delete(e),this.subscribers.size===0){for(let e of this.unsubscribeListeners)e();this.unsubscribeListeners.clear()}}}_onUnsubscribe(e){return this.unsubscribeListeners.add(e),()=>{this.unsubscribeListeners.delete(e)}}setComparer(e){return this.isEqual=e,this}get $(){return new te(e=>(e.next(this.value),this.subscribe(t=>e.next(t))))}};function F(e,t){let n=(0,C.useCallback)(t=>e.subscribe(t),[e]),r=(0,C.useCallback)(()=>e.getValue(),[e]);return(0,C.useSyncExternalStore)(n,r,t??r)}var I=[50,100];function L(e){return`toolCallId`in e&&`state`in e&&e.state===`output-available`}function R(e){return`toolCallId`in e&&`state`in e&&e.state===`input-available`}var ye=class extends P{initialMessage;messages=new Map;chatId;token;messageCallbacks;capabilities=new Set;skillDocumentRequests=new Map;constructor(e,t,n,r){super([]),this.initialMessage=r,this.chatId=e,this.token=t,this.messageCallbacks=n,r&&(this.getMessage(r).optimisticId=r.id,this.setValue([r.id]))}get canReadSkillInstructions(){return this.capabilities.has(`read_skill_instructions`)}getSkillDocument(e,t){if(!this.canReadSkillInstructions)return Promise.reject(Error(`Skill instructions are not supported.`));let n=JSON.stringify([e,t]),r=this.skillDocumentRequests.get(n);if(r)return r;let i=Ne(this.chatId,this.token,e,t);return this.skillDocumentRequests.set(n,i),i.catch(()=>{this.skillDocumentRequests.get(n)===i&&this.skillDocumentRequests.delete(n)}),i}getMessage(e){let t=typeof e==`string`?e:e.id,n=this.messages.get(t);if(n)return n;let r=new we(this.chatId,this.token,e,this.messageCallbacks);return this.messages.set(t,r),r.isIntId||this.aliasOnceLoaded(t,r),r}isMessageGenerating(e){if(e==null)return!1;let t=this.messages.get(e.toString())?.getValue();return t?.status===`success`?t.message.role===`assistant`?t.message.metadata?.status===`generating`:!0:!1}createOptimisticMessage(e){let t=this.getValue().at(-1),n=t?this.messages.get(t):void 0;if(n?.optimisticId&&n.id===n.optimisticId)return!1;let r=ue(e);return this.getMessage(r).optimisticId=r.id,this.appendMessageToHead(r),!0}prependMessages(e){if(e.length===0)return;for(let t of e)this.getMessage(t).acceptWebsocketMessage({type:`ui_message`,message:t});let t=this.getValue(),n=new Set(t),r=e.map(e=>e.id).filter(e=>!n.has(e));r.length!==0&&this.setValue([...r,...t])}aliasOnceLoaded(e,t){let n=t.getValue();if(n.status===`success`){this.handleMessageLoaded(e,n.message,t);return}let r=t.subscribe(n=>{n.status===`success`&&(r(),this.handleMessageLoaded(e,n.message,t))})}handleMessageLoaded(e,t,n){let r=this.messages.get(t.id);r?this.messages.set(e,r):this.messages.set(t.id,n)}acceptWebsocketMessage(e){switch(e.type){case`ai_chat`:break;case`error`:break;case`insufficient_credits`:this.messageCallbacks.onInsufficientCredits(this.dropLatestOptimisticMessage());break;case`chunk`:this.getMessage(e.messageId).acceptWebsocketMessage(e);break;case`initial`:this.capabilities=new Set(e.capabilities??[]),this.messages.clear();for(let t of e.messages)this.getMessage(t).acceptWebsocketMessage({type:`ui_message`,message:t});this.setValue(e.messages.map(e=>e.id));break;case`stream_end`:this.getMessage(e.messageId).acceptWebsocketMessage(e);break;case`ui_message`:this.acceptUiMessage(e.message);break;case`ui_messages`:for(let t of e.messages)this.acceptUiMessage(t);break}}acceptUiMessage(e){this.replaceOptimisticMessage(e)||(this.getMessage(e).acceptWebsocketMessage({type:`ui_message`,message:e}),this.appendMessageToHead(e))}replaceOptimisticMessage(e){let t=this.findOptimisticMessageId(e);if(!t)return!1;let n=this.messages.get(t);if(!n)return!1;if(n.id=e.id,n.acceptWebsocketMessage({type:`ui_message`,message:e}),t!==e.id){this.messages.delete(t),this.messages.set(e.id,n);let r=this.getValue(),i=r.indexOf(t);if(i!==-1){let t=[...r];t[i]=e.id,this.setValue(t)}}return!0}dropLatestOptimisticMessage(){let e=this.getValue();for(let t=e.length-1;t>=0;--t){let n=e[t];if(!n)continue;let r=this.messages.get(n);if(!r?.optimisticId||r.id!==r.optimisticId)continue;let i=r.getValue(),a=i.status===`success`?i.message.parts.find(e=>e.type===`text`):void 0;return this.messages.delete(n),this.setValue(e.filter(e=>e!==n)),a?.type===`text`?a.text:null}return null}findOptimisticMessageId(e){let t=this.getValue();for(let n=t.length-1;n>=0;--n){let r=t[n],i=this.messages.get(r);if(!i?.optimisticId||i.id!==i.optimisticId)continue;let a=i.getValue();if(a.status===`success`&&a.message.role===e.role&&a.message.metadata?.parentId===e.metadata?.parentId)return r}}appendMessageToHead(e){if(!e.metadata)return;let t=this.getValue();t.at(-1)===e.metadata.parentId&&this.setValue([...t,e.id])}},z=class extends P{messageStore;stopWatchingMessageStore;stopWatchingLastMessage;lastMessageId;constructor(e){super(H(e)),this.messageStore=e}get isLive(){return this.stopWatchingMessageStore!==void 0}subscribe(e){return this.isLive||(this.stopWatchingMessageStore=this.messageStore.subscribe(()=>{this.refresh()}),this._onUnsubscribe(()=>{this.stopWatchingMessageStore?.(),this.stopWatchingMessageStore=void 0,this.stopWatchingLastMessage?.(),this.stopWatchingLastMessage=void 0,this.lastMessageId=void 0}),this.refresh()),super.subscribe(e)}refresh(){let e=this.messageStore.getValue().at(-1);this.lastMessageId!==e&&(this.stopWatchingLastMessage?.(),this.stopWatchingLastMessage=void 0,this.lastMessageId=e,e&&(this.stopWatchingLastMessage=this.messageStore.getMe
3ssage(e).subscribe(()=>{this.setValue(H(this.messageStore))}))),this.setValue(H(this.messageStore))}},B=new WeakMap;function V(e){let t=B.get(e);if(t)return t;let n=new z(e);return B.set(e,n),n}function H(e){return e.isMessageGenerating(e.getValue().at(-1))}function be(e){let[t,n]=(0,C.useState)(()=>e.getValue().length>0);return(0,C.useEffect)(()=>{let t=()=>n(e.getValue().length>0),r=e.subscribe(t);return t(),r},[e]),t}function xe(e){let t=e.getValue().at(-1);if(!t)return null;let n=Number.parseInt(t,10);return Number.isNaN(n)?null:n}function Se(e){for(let t=e.getValue().length-1;t>=0;--t){let n=e.getValue()[t];if(!n)continue;let r=e.getMessage(n).getValue();if(!(r.status!==`success`||r.message.role!==`assistant`))return r.message.metadata?.status===`cancelled`}return!1}function Ce(e){let[t,n]=(0,C.useState)(()=>Se(e));return(0,C.useEffect)(()=>{let t=()=>{n(t=>{let n=Se(e);return t===n?t:n})},r=new Map,i=()=>{for(let n of e.getValue())r.has(n)||r.set(n,e.getMessage(n).subscribe(t));t()},a=e.subscribe(i);return i(),()=>{a();for(let e of r.values())e()}},[e]),t}var we=class extends P{chatId;id;optimisticId;streamController;queuedChunks=[];isStreaming=!1;token;streamGeneration=0;messageCallbacks;firedCompletions=new Set;firedInputAvailable=new Set;constructor(e,t,n,r){let i=typeof n==`string`?n:n.id,a=typeof n==`string`?{status:`loading`,promise:Me(e,t,n)}:{status:`success`,message:n};super(a),this.chatId=e,this.token=t,this.id=i,this.messageCallbacks=r,this.load()}detectToolCompletions(e){let t=this.getValue(),n=t.status===`success`?t.message.parts:[];for(let t of e)L(t)&&(this.firedCompletions.has(t.toolCallId)||n.some(e=>L(e)&&e.toolCallId===t.toolCallId)||(this.firedCompletions.add(t.toolCallId),this.messageCallbacks.onToolCompleted(t)))}detectMessageCompletion(e){if(e.role!==`assistant`||e.metadata?.status===`generating`)return;let t=this.getValue();t.status===`success`&&t.message.metadata?.status===`generating`&&this.messageCallbacks.onMessageCompleted()}detectToolInputAvailable(e){let t=this.getValue(),n=t.status===`success`?t.message.parts:[];for(let t of e)R(t)&&(this.firedInputAvailable.has(t.toolCallId)||n.some(e=>R(e)&&e.toolCallId===t.toolCallId)||(this.firedInputAvailable.add(t.toolCallId),this.messageCallbacks.onToolInputAvailable(t)))}acceptWebsocketMessage(e){e.type===`chunk`?(this.setupStream(),this.streamController?this.streamController.enqueue(e.chunk):this.queuedChunks.push(e.chunk)):e.type===`stream_end`?(this.streamController?.close(),this.streamController=void 0,this.queuedChunks=[]):(this.detectToolCompletions(e.message.parts),this.detectToolInputAvailable(e.message.parts),this.detectMessageCompletion(e.message),this.setValue({status:`success`,message:e.message}))}get isIntId(){return/^\d+$/.test(this.id)}setupStream(){let e=this.getValue();if(e.status!==`success`||this.streamController||this.isStreaming)return;this.isStreaming=!0;let t=++this.streamGeneration,n=this.queuedChunks;this.queuedChunks=[];let r=new ReadableStream({start:e=>{this.streamController=e;for(let t of n)e.enqueue(t)}}),i=!1,a=de({stream:r,message:e.message,onError:e=>{i||(i=!0,o(e,{tags:{component:`ai_chat_stream`},extra:{chatId:this.chatId,messageId:this.id}}))}});(async()=>{for await(let e of a){if(this.streamGeneration!==t)return;this.detectToolCompletions(e.parts),this.detectToolInputAvailable(e.parts),this.setValue({message:e,status:`success`})}this.streamController=void 0,this.isStreaming=!1,this.queuedChunks.length>0&&this.setupStream()})()}async load(){let e=this.getValue();if(e.status===`success`)return e.message;e.status!==`loading`&&(e={status:`loading`,promise:Me(this.chatId,this.token,this.id)},this.setValue(e));try{let t=await e.promise;return this.id=t.id,this.setValue({status:`success`,message:t}),this.queuedChunks.length>0&&this.setupStream(),t}catch(e){let t=e instanceof Error?e.message:`An unknown error happened when downloading the AiChatMessage`;return this.setValue({status:`error`,errorMessage:t,retry:()=>this.load()}),null}}};function Te(e){return F(e)}var Ee=new P({status:`loading`,promise:new Promise(()=>{})});
3function De(e,t){return F(t?e.getMessage(t):Ee)}function Oe(e){return F(V(e),()=>H(e))}var ke=new P(!1);function Ae(e){return F(e?V(e):ke,()=>e?H(e):!1)}async function je(e,t,n){let r=a.replace(/^ws/,`http`),i=new URL(`/agent/v1/ai_chats/${e}/messages`,r);n&&i.searchParams.set(`before`,n);let o=await U(i,t);if(o.response.ok)return Le(await o.response.json());throw o.retriedWithPkce?Error(`Failed to fetch messages after PKCE: ${o.response.status} - ${o.responseText}`):Error(`Failed to fetch messages: ${o.response.status} - ${o.responseText}`)}async function Me(e,t,n){let r=a.replace(/^ws/,`http`),i=await U(new URL(`/agent/v1/ai_chats/${e}/messages/${n}`,r),t);if(i.response.ok)return i.response.json();throw i.retriedWithPkce?Error(`Failed to fetch message after PKCE: ${i.response.status} - ${i.responseText}`):i.response.status===404?Error(`Message not found: ${i.responseText}`):Error(`Failed to fetch message: ${i.response.status} - ${i.responseText}`)}async function Ne(e,t,n,r){let i=a.replace(/^ws/,`http`),o=new URL(`/agent/v1/ai_chats/${encodeURIComponent(e)}/messages/${encodeURIComponent(n)}/tool_calls/${encodeURIComponent(r)}/skill_instructions`,i);for(let e=0;;e+=1){let n=await U(o,t);if(n.response.ok)return Ie(await n.response.json());let r=I.at(e);if(n.response.status===404&&r!==void 0){await Pe(r);continue}throw n.retriedWithPkce?Error(`Failed to fetch skill after PKCE: ${n.response.status} - ${n.responseText}`):n.response.status===404?Error(`Skill instructions are not available.`):Error(`Failed to fetch skill: ${n.response.status} - ${n.responseText}`)}}async function U(e,t,n=`GET`){let r={};t&&(r.Authorization=`Bearer ${t}`);let i=await fetch(e,{method:n,headers:r,credentials:`include`});if(i.ok)return{response:i,responseText:``,retriedWithPkce:!1};let a=await i.text().catch(()=>`An unknown error has occurred`);if(i.status!==401&&i.status!==403||t)return{response:i,responseText:a,retriedWithPkce:!1};let o=Fe(a);if(!o)return{response:i,responseText:a,retriedWithPkce:!1};let s=l().userId,c=await k(o);if(l().userId!==s)throw Error(`Your account changed while authenticating. Try again.`);let u=new URL(e);u.searchParams.set(`code`,c),u.searchParams.set(`code_challenge`,o);let d=await fetch(u,{method:n,credentials:`include`});return d.ok?{response:d,responseText:``,retriedWithPkce:!0}:{response:d,responseText:await d.text().catch(()=>`Auth retry failed`),retriedWithPkce:!0}}function Pe(e){return new Promise(t=>setTimeout(t,e))}function Fe(e){try{let t=JSON.parse(e);if(!t||typeof t!=`object`||!(`error`in t))return;let n=t.error;return!n||typeof n!=`object`||!(`codeChallenge`in n)?void 0:typeof n.codeChallenge==`string`?n.codeChallenge:void 0}catch{return}}function Ie(e){if(!e||typeof e!=`object`||!(`data`in e))throw Error(`Invalid skill response.`);let t=e.data;if(!t||typeof t!=`object`||!(`name`in t)||typeof t.name!=`string`||!(`content`in t)||typeof t.content!=`string`)throw Error(`Invalid skill response.`);return{name:t.name,content:t.content}}function Le(e){let t=e;return{data:t.data??[],pageInfo:{startCursor:t.page_info?.start_cursor??null,endCursor:t.page_info?.end_cursor??null,hasNextPage:t.page_info?.has_next_page??!1,hasPreviousPage:t.page_info?.has_previous_page??!1}}}var W=[`coreFetchCompanyVisibleProducts`,`coreFetchCompanyAccessPassesWithPlans`,`coreFetchCompanyAccessPassesWithPlans.infinite`,`fetchCompanyAccessPasses`,`coreFetchCompanyAccessPassesForStorePage`,`coreFetchCompanyAccessPass`,`coreFetchAccessPass`,`coreFetchCompanyAccessPassesV2`,`coreFetchEditCompanyProductPage`,`coreFetchCompanyProductPage`,`coreFetchCompanyProductPageProduct`],G=[`coreFetchCompanyAccessPassesWithPlans`,`coreFetchCompanyAccessPassesWithPlans.infinite`,`coreFetchCompanyPlans`,`coreFetchCompanyPlan`],K=[`forums`,`coreFetchCompanyExperienceList`,`coreFetchCompanyExperienceListWithAccessPasses`,`coreFetchExperienceSettings`,`coreFetchCompanyPrimaryExperience`],q=[`CoreFetchCourses`,`CoreFetchChapters`,`CoreFetchLesson`,`CoreFetchLessonAnalytics`],J=[`coreFetchCompanyOnboardingSteps`],Re=[`coreFetchBasicCompanyDetails`,`coreFetchCompanySocialLinks`,`account`],Y=[`coreFetchAdminSidebarData`],ze=[`coreFetchOwnedCompaniesWithBalances`],X=[p,x,ne],Z=[_,...X],Q=[v,...Z],$=[g],Be=[m,h,y],Ve=[b],He={createAccount:[...Re,...ze,...J,`economic-intelligence`],updateAccount:[...Re],updateEconomicIntelligence:[`economic-intelligence`],createProduct:[...W,...J],updateProduct:[...W],deleteProduct:[...W],createPlan:[...G,...J],updatePlan:[...G],deletePlan:[...G],createExperience:[...K,...Y,...J],updateExperience:[...K],deleteExperience:[...K,...Y],duplicateE
3xperience:[...K,...W,...Y],attachExperience:[...W,...K,...Y,...J],detachExperience:[...W,...K,...Y],createCourse:[...q,...J],updateCourse:[...q],deleteCourse:[...q],createCourseChapter:[...q],updateCourseChapter:[...q],deleteCourseChapter:[...q],createCourseLesson:[...q],updateCourseLesson:[...q],deleteCourseLesson:[...q],createAdCampaign:[...X],updateAdCampaign:[...X],deleteAdCampaign:[...X],duplicateAdCampaign:[...Q],pauseAdCampaign:[...X],unpauseAdCampaign:[...X],retryAdCampaignPayment:[...X],createAdGroup:[...Z],updateAdGroup:[...Z],deleteAdGroup:[...Z],duplicateAdGroup:[...Q],pauseAdGroup:[...Z],unpauseAdGroup:[...Z],createAd:[...Q],updateAd:[...Q],deleteAd:[...Q],duplicateAd:[...Q],pauseAd:[...Q],unpauseAd:[...Q],createAudience:[...$],updateAudience:[...$],deleteAudience:[...$],addAudiencePeople:[...$],createSocialAccount:[...Be],connectSocialAccount:[...Be],deleteSocialAccount:[...Be],updateAccountPreferences:[...Ve]};function Ue(e,t,n,r){t===`createAccount`&&(e.invalidateQueries({queryKey:[`fetchMembersV2`]}),r?.invalidate());let i=He[t],a=i?[...new Set(i)]:[];a.includes(`coreFetchAdminSidebarData`)&&r?.invalidate();for(let t of a)e.invalidateQueries({queryKey:[t]})}var We=new Set(`api.billing.bounties.claim.core.dashboard.discover.experiences.finance.home.townhall.hub.joined.live.login.messages.network.new.notifications.popular.r.form-company.register-llc.signup.verify-identity.unfurl.whopx`.split(`.`));function Ge(e){let t=s(e);if(!t)return null;let n=new URL(t,c),r=n.hash.slice(1),i=n.pathname.match(/^\/(?:joined\/)?([^/]+)\/product\/([^/]+?)\/?$/);return i&&!We.has(i[1])&&(n.pathname=`/${i[1]}/products/${i[2]}/`),{to:n.pathname,search:Object.fromEntries(n.searchParams),...r?{hash:r}:{}}}var Ke=re(ae({answersByChatId:{}},e=>({setAnswer:(t,n,r)=>e(e=>({answersByChatId:{...e.answersByChatId,[t]:{...e.answersByChatId[t],[n]:r}}}))})));function qe(e){return Ke(t=>t.answersByChatId[e]??{})}var Je=t(),Ye=(0,C.createContext)(null);function Xe({answerable:e,cancellable:t,chatId:n,children:r,keepAlive:i,onAiChatUpdate:a,onInitialMessagesLoaded:o,readonly:s,showTimestamps:c,token:l}){let u=nt(n,{answerable:e,cancellable:t,keepAlive:i,onAiChatUpdate:a,onInitialMessagesLoaded:o,readonly:s,showTimestamps:c,token:l});return(0,Je.jsx)(Ye.Provider,{value:u,children:r})}function Ze(){let e=(0,C.use)(Ye);if(!e)throw Error(`Cannot useAiChat when <AiChatContextProvider /> is not mounted`);return e}function Qe(){return(0,C.use)(Ye)}function $e(e){return`ai-chat:${e}:dismissed-handoff-invitation`}function et(e){try{return window.sessionStorage.getItem($e(e))}catch{return null}}function tt(e,t){try{window.sessionStorage.setItem($e(e),t)}catch{return}}function nt(e,t){let[n,a]=(0,C.useState)(!1),[o,s]=(0,C.useState)(null),[c,l]=(0,C.useState)(()=>et(e)),[u,d]=(0,C.useState)([]),[f,ee]=(0,C.useState)({}),te=qe(e),[p,ne]=(0,C.useState)({}),[m,h]=(0,C.useState)({startCursor:null,endCursor:null,hasNextPage:!1,hasPreviousPage:!1}),[g,_]=(0,C.useState)(!1),v=i(),y=r(),b=(0,C.useRef)(!1),x=oe(),re=(0,C.useEffectEvent)(e=>{if(!t.readonly&&x?.app_id){let t={appId:x.app_id,experienceId:x.experience_id};if((e.type===`tool-edit`||e.type===`tool-write`)&&fe({...t,on:`development`}),e.type===`tool-bash`){let n=e.input?.command,r=e.output?.exitCode;typeof n==`string`&&/\bsave\s+["']/.test(n)&&r===0&&fe({...t,on:null})}}}),{play:ae}=pe({url:`/_static/sounds/completed.mp3`,volume:.25}),ue=(0,C.useEffectEvent)(()=>{t.readonly||(D(e)&&ve(v,e),ae())}),de=(0,C.useEffectEvent)(e=>{if(!t.readonly&&e.type===`tool-navigate`){let t=e.input?.path;if(t){let n=Ge(t),r=ie(new URLSearchParams(window.location.search).get(`funnel_id`));n&&y.navigate({...n,search:{...n.search,...r&&{funnel_id:r.id}}}),A.send({type:`complete_tool`,toolCallId:e.toolCallId,data:{success:!!n,path:t}})}}}),[T,E]=(0,C.useState)(null),O=(0,C.useCallback)(()=>E(null),[]),k=(0,C.useEffectEvent)(e=>{t.readonly||E({textContent:e,at:Date.now()})}),A=(0,C.useMemo)(()=>new he(e,t.token),[e,t.token]),j=(0,C.useMemo)(()=>new ye(e,t.token,{onToolCompleted:re,onToolInputAvailable:de,onMessageCompleted:ue,onInsufficientCredits:k},v.getQueryData([`ai-chat-initial-message`,e])),[e,t.token,v]);it(e,j),(0,C.useEffect)(()=>
3{if(!t.keepAlive)return w.getState().registerActiveProvider(e)},[e,t.keepAlive]);let ge=(0,C.useEffectEvent)(e=>t.onAiChatUpdate?.(e)),_e=(0,C.useEffectEvent)(()=>t.onInitialMessagesLoaded?.());(0,C.useEffect)(()=>{a(!1);let t=new AbortController,n=A.connect({onMessage:n=>{j.acceptWebsocketMessage(n),n.type===`initial`&&(v.removeQueries({queryKey:[`ai-chat-initial-message`,e],exact:!0}),s(n.handoffInvitationEscalationId??null),h(n.pageInfo),d(n.todos??[]),_e(),se(v,e,{signal:t.signal})),n.type===`handoff_invitation_changed`&&s(n.escalationId),n.type===`todo_list`&&d(n.todos),n.type===`tool_live_state`&&ee(e=>({...e,[n.toolCallId]:n.state})),n.type===`ai_chat`&&(ge(n.chat),n.chat.title&&le(v,{id:n.chat.id,title:n.chat.title}),`cronSchedule`in n.chat&&(n.cronCreated&&S.getState().markAgentCreated(n.chat.id),ce(v,n.chat))),n.type===`invalidate_queries`&&Ue(v,n.operation,n.pathParams,y)},onStatus:a});return()=>{t.abort(),n()}},[A,j,e,v]),(0,C.useEffect)(()=>{if(t.readonly)return;let n=null,r=me(e),i=!1,a=()=>{let t=D(e)&&document.visibilityState===`visible`;t&&!i?(A.send({type:`focus`}),n??=setInterval(()=>A.send({type:`focus`}),3e3)):!t&&i&&(A.send({type:`blur`}),n&&=(clearInterval(n),null)),i=t};a();let o=S.subscribe(a);return document.addEventListener(`visibilitychange`,a),()=>{r(),o(),document.removeEventListener(`visibilitychange`,a),n&&clearInterval(n),i&&A.send({type:`blur`})}},[A,e,t.readonly]);let M=(0,C.useCallback)(e=>t.readonly||!j.createOptimisticMessage(e)?!1:(A.send({type:`create_message`,...e}),!0),[j,A,t.readonly]),N=(0,C.useCallback)(()=>b.current||!m.hasNextPage||!m.endCursor?Promise.resolve():(b.current=!0,_(!0),je(e,t.token,m.endCursor).then(e=>{j.prependMessages(e.data),h(e.pageInfo)}).finally(()=>{b.current=!1,_(!1)})),[e,j,t.token,m.endCursor,m.hasNextPage]),P=(0,C.useCallback)(e=>{t.readonly&&!t.cancellable||A.send({type:`cancel`,messageId:e})},[A,t.readonly,t.cancellable]),F=(0,C.useCallback)(e=>{t.readonly||(A.send({type:`approve_tool`,...e}),document.querySelector(`[data-ai-chat-composer]`)?.focus())},[A,t.readonly]),I=(0,C.useCallback)(n=>{if(t.readonly&&!t.answerable)return;let r=n.data?.answer;typeof r==`string`&&Ke.getState().setAnswer(e,n.toolCallId,r),A.send({type:`complete_tool`,...n}),document.querySelector(`[data-ai-chat-composer]`)?.focus()},[e,A,t.readonly,t.answerable]),L=(0,C.useCallback)(e=>{t.readonly&&!t.token||(e.targetMessageId&&e.sentiment&&ne(t=>({...t,[e.targetMessageId]:e.sentiment})),A.send({type:`submit_feedback`,...e}),window.parent!==window&&window.parent.postMessage({__scope:`whop-ai-chat`,event:`feedbackSubmitted`},`*`))},[A,t.readonly,t.token]),R=(0,C.useCallback)(e=>t.readonly?Promise.reject(Error(`Cannot prepare a handoff from a read-only chat`)):A.prepareIntercomHandoff(e.escalationId),[A,t.readonly]),z=(0,C.useCallback)(e=>t.readonly?Promise.resolve():A.recordIntercomHandoffButtonUnavailable(e.escalationId),[A,t.readonly]),B=(0,C.useCallback)(e=>t.readonly?Promise.resolve():A.recordIntercomHandoffOfferRendered(e.escalationId,e.signal),[A,t.readonly]),V=(0,C.useCallback)(()=>{o&&(l(o),tt(e,o))},[e,o]),H=o===c?null:o;return(0,C.useMemo)(()=>({chatId:e,messageStore:j,connected:n,insufficientCredits:T,clearInsufficientCredits:O,sendMessage:M,completeTool:I,approveTool:F,submitFeedback:L,prepareIntercomHandoff:R,recordIntercomHandoffButtonUnavailable:z,recordIntercomHandoffOfferRendered:B,visibleHandoffInvitationEscalationId:H,dismissHandoffInvitation:V,feedbackByMessageId:p,loadMore:N,hasMore:m.hasNextPage,isLoadingMore:g,showTimestamps:t.showTimestamps??!1,cancel:P,optimisticAskQuestionAnswers:te,todos:u,toolLiveState:f}),[j,n,T,O,M,I,N,P,F,L,R,z,B,H,V,p,e,m.hasNextPage,g,t.showTimestamps,te,u,f])}var rt=3e4;function it(e,t){let n=be(t),r=Oe(t),i=w(e=>e.setGenerating);(0,C.useEffect)(()=>{if(n||r){i(e,r);return}let t=setTimeout(()=>i(e,!1),rt);return()=>clearTimeout(t)},[e,n,r,i])}export{w as _,be as a,Ce as c,ve as d,j as f,D as g,k as h,xe as i,Oe as l,M as m,Ze as n,De as o,_e as p,Qe as r,Te as s,Xe as t,Ae as u,T as v};
4//# debugId=f75363b4-3735-50de-8c9e-c8affd0f6a61

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.