@pickaxeproject/react 6.13.1 → 6.13.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e=require("../../../_virtual/_tslib.js"),t=require("react/jsx-runtime"),s=require("react"),n=require("../../../hooks/pickaxe/usePickaxeContext.js"),i=require("../../../hooks/pickaxe/useResponseContext.js"),o=require("../../../hooks/studio/useStyleInput.js"),r=require("../../../hooks/studio/useStyleFontSize.js"),a=require("../../../hooks/pickaxe/useConversation.js"),l=require("../../../hooks/pickaxe/useDimensionContext.js"),d=require("../Addons/Auth/hooks/useAuthContext.js"),c=require("../Addons/Document/hooks/useDocument.js"),u=require("../Addons/Scroll/hooks/useScroll.js"),p=require("../Addons/Artifact/hooks/useArtifactContext.js"),m=require("../../../hooks/core/useHover.js"),f=require("../../../hooks/core/useMediaQuery.js"),g=require("../../../common/documents.js"),v=require("eventsource-parser"),h=require("../../Icons/attach-vertical.svg.js"),b=require("../../Icons/arrow-right.svg.js"),I=require("../../Icons/microphone.svg.js"),y=require("../../Icons/stop.svg.js"),x=require("../Addons/Document/List.js"),j=require("../../Core/Textarea.js"),S=require("../../Core/ErrorAlert.js"),O=require("../../../common/error.js"),w=require("../../../common/chatMessages.js"),N=require("../../../common/api/pickaxe.js"),_=require("../../../common/validation.js"),k=require("../../../common/cn.js"),E=require("../../../common/utils.js"),T=require("../../../common/pickaxeConfig.js"),U=require("../../../common/deploymentWebhooks.js"),C=require("../../../hooks/studio/useStudio.js"),A=require("../../../hooks/pickaxe/useSpeechToText.js"),D=require("../common/PickaxeCommon.js");const P=e=>"string"==typeof e&&e.trim().length>0,L=e=>e.map((e=>Object.assign({},e))),M=e=>e instanceof Error&&("AbortError"===e.name||"BodyStreamBuffer was aborted"===e.message),R=(e,t)=>{if(e&&"object"==typeof e)return e[t]},q=(e,t)=>{const s=R(e,t);return P(s)?s:null},F=e=>{const t=Number(e);return Number.isFinite(t)?t:void 0},V=({studioUser:e,deploymentId:t,portalId:s})=>{var n,i;const o=Array.isArray(R(e,"uses"))?R(e,"uses"):[],r=(({deploymentId:e,portalId:t})=>P(e)?{type:"deployment",id:e}:P(t)?{type:"portal",id:t}:null)({deploymentId:t,portalId:s});if(!r)return{scope:r,record:null};const a=null!==(i=null!==(n=o.find((e=>e.id===r.id&&e.type===r.type)))&&void 0!==n?n:o.find((e=>e.id===r.id)))&&void 0!==i?i:null;return{scope:r,record:a}},B=s.forwardRef((({resubmitPrompt:R,onFocus:B,onBlur:$,onInputHeightChange:X,initSmitheryAuthData:H},K)=>{var W,Y,z,G,J,Q,Z,ee,te,se,ne,ie;const{origin:oe,pickaxeId:re,sessionId:ae,sender:le,senderType:de,portalId:ce,deploymentId:ue,deploymentType:pe,pickaxe:me,styles:fe,colors:ge,translations:ve,locale:he,forceMobile:be,isNewChat:Ie,isRtl:ye,isShowFeedbackMessage:xe,accessGroup:je,setIsNewChat:Se,setIsShowIceBreaker:Oe,setValidationStatus:we,setValidationUpgradeGroups:Ne,setValidationUpgradeUrl:_e,setAccessGroup:ke,onGenerateComplete:Ee}=n.usePickaxeContext(),{token:Te,isLoggedOut:Ue,isSent:Ce,isPricingAuth:Ae}=d.useAuthContext(),{messages:De,isGenerating:Pe,setMessages:Le,setStatus:Me,setLimitData:Re,setError:qe}=i.useResponseContext(),{documents:Fe,isUploading:Ve,documentError:Be,onFileUpload:$e,setDocuments:Xe,setDocumentError:He}=c.useDocument(),{studio:Ke}=C.useStudio(),[We]=f.useMediaQuery("(max-width: 480px)"),{scrollStartSession:Ye,scrollEndSession:ze,scrollToBottom:Ge}=u.useScroll({auto:!0,smooth:!(be||We)}),{artifacts:Je,currentPopupType:Qe,setArtifacts:Ze,setCurrentArtifact:et}=p.useArtifactContext(),{height:tt}=l.useDimensionContext(),st=a.useConversation(),[nt,it]=s.useState(""),[ot,rt]=s.useState(!1),[at,lt]=s.useState(!1),[dt,ct]=s.useState(null),[ut,pt]=s.useState(null),[mt,ft]=s.useState(!1),[gt,vt]=s.useState(!1),[ht,bt]=s.useState(0),It=s.useRef(null),yt=s.useRef(""),xt=s.useRef(null),jt=s.useRef(null),St=s.useRef(null),Ot=s.useRef([]),wt=s.useRef(null),Nt=s.useRef(null),_t=s.useRef(null),kt=s.useRef(null),Et=s.useRef(new Set),Tt=s.useRef(null),Ut=Math.max(.4*tt,100),{speechTranscript:Ct,isSpeechListening:At,isSpeechProcessing:Dt,isSpeechSupported:Pt,onStartListening:Lt,onStopListening:Mt}=A.useSpeechToText(),Rt=m.useHover(),{isHover:qt}=Rt,Ft=e.__rest(Rt,["isHover"]),Vt=m.useHover(),{isHover:Bt}=Vt,$t=e.__rest(Vt,["isHover"]),Xt=m.useHover(),{isHover:Ht}=Xt,Kt=e.__rest(Xt,["isHover"]),Wt=r.useStyleFontSize(),Yt=o.useStyleInput(),zt="undefined"!=typeof window?window.location.hostname:"",Gt="undefined"!=typeof window?window.location.href:"",Jt="undefined"!=typeof window&&window.self!==window.top,Qt=zt.includes("pickaxe.co")&&!Gt.includes("https://studio.pickaxe.co/_embed")&&!Jt,Zt=null!==(Y=null===(W=null==me?void 0:me.documentuploadtype)||void 0===W?void 0:W.startsWith("enduserupload"))&&void 0!==Y&&Y,es=Pt&&(null==me?void 0:me.enablevoicetotext),ts=P(ue),ss="chat-input"===pe&&Ie&&!Ce,ns="chat-input"===pe&&Ae&&Ue&&Ce,is=s.useCallback((e=>{const t=_.getValidationFailure(e);return!!t&&(qe(""),Re(null),we(t.status),ke(t.accessGroup),Ne(t.upgradeGroups),_e(t.upgradeUrl),!0)}),[qe,Re,we,Ne,_e,ke]),os=null!==(z=null==me?void 0:me.placeholdertext)&&void 0!==z?z:ye?"بماذا تريد أن تتحدث؟":(null==ve?void 0:ve["what-do-you-want-to-talk-about"])||"What do you want to talk about?",rs=ot||at,as=s.useCallback((()=>e.__awaiter(void 0,void 0,void 0,(function*(){ft(!1);try{const e=yield fetch(`${process.env.NEXT_PUBLIC_PICKAXE_API2_URL}/user`,Object.assign(Object.assign({method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(Object.assign({studioId:null==me?void 0:me.studioid},Te?{studioSessionToken:Te}:le?{sender:le}:{sender:E.initializeEmbedUserId()}))},(!process.env.NODE_ENV||"development"===process.env.NODE_ENV)&&Object.assign({},process.env.NEXT_PUBLIC_PICKAXE_SESSION_TOKEN&&{headers:{"Content-Type":"application/json","x-pickaxe-session-token":process.env.NEXT_PUBLIC_PICKAXE_SESSION_TOKEN}})),Qt&&{credentials:"include"})),t=yield e.json();(null==t?void 0:t.studioUser)&&(ct(t.studioUser),pt(t.url))}catch(e){console.error("Failed to fetch studio user:",e)}finally{ft(!0)}}))),[Qt,null==me?void 0:me.studioid,le,Te]);s.useEffect((()=>{as()}),[as]);const ls=Number(null!==(G=null==je?void 0:je.limit)&&void 0!==G?G:0),ds="string"==typeof(null==je?void 0:je.limitInterval)?je.limitInterval:null,cs=!!(null==Ke?void 0:Ke.data.usage)&&Ke.data.usage.isCredits,us=s.useMemo((()=>{var e,t,s,n,i;return null!==(i=null!==(n=null!==(s=null!==(t=null!==(e=null!=ce?ce:q(dt,"portalId"))&&void 0!==e?e:q(dt,"portalid"))&&void 0!==t?t:q(je,"portalId"))&&void 0!==s?s:q(je,"portalid"))&&void 0!==n?n:q(me,"portalId"))&&void 0!==i?i:q(me,"portalid")}),[je,ce,me,dt]),ps=s.useMemo((()=>V({studioUser:dt,deploymentId:ue,portalId:us})),[ue,us,dt]);s.useEffect((()=>{ts&&Ie&&ae&&Et.current.add(ae)}),[Ie,ae,ts]);const ms=s.useCallback((()=>{var e,t,s;return{studioId:null==me?void 0:me.studioid,userEmail:q(dt,"email"),userId:null!==(e=q(dt,"userId"))&&void 0!==e?e:q(dt,"userid"),sessionId:ae,deploymentId:ue,deploymentType:pe,portalId:us,accessGroupId:null!==(t=null==je?void 0:je.accessGroupId)&&void 0!==t?t:null,pickaxeId:re,sender:le,senderType:de,origin:oe,metadata:null!==(s=T.getPickaxeConfigMetadata(ue))&&void 0!==s?s:null}}),[null==je?void 0:je.accessGroupId,ue,pe,oe,null==me?void 0:me.studioid,re,us,le,de,ae,dt]),fs=s.useCallback((()=>!!(ts&&mt&&ae)&&(!!Et.current.has(ae)&&(U.fireDeploymentSessionInitializedWebhook(ms()),Et.current.delete(ae),!0))),[ms,mt,ae,ts]);s.useEffect((()=>{if(!mt||!ae)return;fs();const e=Tt.current;(null==e?void 0:e.sessionId)===ae&&(U.fireDeploymentFirstMessageSubmittedWebhook(Object.assign(Object.assign(Object.assign({},e),ms()),{message:e.message,documentIds:e.documentIds,uploadedModelImages:e.uploadedModelImages,hasUploadedDocuments:e.hasUploadedDocuments,isHidden:e.isHidden})),Tt.current=null)}),[fs,ms,mt,ae]);const gs={currentUses:F(null==dt?void 0:dt.currentUses),extraUses:F(null==dt?void 0:dt.extraUses)},vs=ps.scope?{currentUses:null!==(Q=F(null===(J=ps.record)||void 0===J?void 0:J.currentUses))&&void 0!==Q?Q:0,extraUses:null!==(ee=F(null===(Z=ps.record)||void 0===Z?void 0:Z.extraUses))&&void 0!==ee?ee:0}:{currentUses:0,extraUses:0},hs=q(dt,"type"),bs="guest"===hs||!hs&&Ue?vs:gs;s.useEffect((()=>{let t=!0;return e.__awaiter(void 0,void 0,void 0,(function*(){var e;if(cs&&(null===(e=null==Ke?void 0:Ke.data)||void 0===e?void 0:e.workspaceId))try{const e=yield N.pickaxeApi2.get(`/cost_per_run?workspaceId=${Ke.data.workspaceId}`,{withCredentials:!1});t&&bt(1e4*(Number(e.data.costPerRun)||0))}catch(e){console.error("Failed to fetch average cost per run:",e),t&&bt(0)}else t&&bt(0)})),()=>{t=!1}}),[cs,null===(te=null==Ke?void 0:Ke.data)||void 0===te?void 0:te.workspaceId]);const Is=(({currentUses:e,extraUses:t,limit:s,limitInterval:n})=>{const i=Number(null!=e?e:0),o=Number(null!=t?t:0);return s===D.STUDIO_INFINITY_VALUE||o===D.STUDIO_INFINITY_VALUE?D.STUDIO_INFINITY_VALUE:"one_time"===n?Math.max(0,o-i):Math.max(0,s-i)+o})({currentUses:bs.currentUses,extraUses:bs.extraUses,limit:ls,limitInterval:ds}),ys=Is===D.STUDIO_INFINITY_VALUE?D.STUDIO_INFINITY_VALUE:Math.max(0,Math.ceil(Is)),xs=(({extraUses:e,limit:t,limitInterval:s})=>{const n=Number(null!=e?e:0);return t===D.STUDIO_INFINITY_VALUE||n===D.STUDIO_INFINITY_VALUE?D.STUDIO_INFINITY_VALUE:"one_time"===s?Math.max(0,n):Math.max(0,t)+Math.max(0,n)})({extraUses:bs.extraUses,limit:ls,limitInterval:ds}),js=xs===D.STUDIO_INFINITY_VALUE?D.STUDIO_INFINITY_VALUE:Math.ceil(.05*xs),Ss=cs?Math.ceil(5*ht):5,Os=js===D.STUDIO_INFINITY_VALUE?D.STUDIO_INFINITY_VALUE:Math.max(js,Ss),ws=s.useMemo((()=>!!dt&&(!gt&&(ys!==D.STUDIO_INFINITY_VALUE&&(!(ys<=0)&&ys<=Os)))),[gt,Os,ys,dt]),Ns=Boolean(null==je?void 0:je.hideUpgradeOptions),_s=!Ns&&(null===(se=null==je?void 0:je.upgrade)||void 0===se?void 0:se.isLinkToCustomURL)&&"string"==typeof je.upgrade.limitLink&&je.upgrade.limitLink.trim().length>0?je.upgrade.limitLink.trim():null,ks=_s&&"string"==typeof(null===(ne=null==je?void 0:je.upgrade)||void 0===ne?void 0:ne.limitCTA)&&je.upgrade.limitCTA.trim().length>0?je.upgrade.limitCTA:(null==ve?void 0:ve["pricing.upgrade"])||(null==ve?void 0:ve.upgrade)||"Upgrade",Es=s.useMemo((()=>{var e,t,s;return!!Ie&&(!!me&&(!st.isLoading&&(!((null!==(t=null===(e=st.data)||void 0===e?void 0:e.messages.length)&&void 0!==t?t:0)>1)&&(!!(null===(s=me.icebreakers)||void 0===s?void 0:s.length)&&(!xe&&!ss)))))}),[me,Ie,xe,ss,st.data,st.isLoading]),Ts=s.useMemo((()=>{if(Pe||Ve)return!1;const e=Zt&&Fe.length>0&&Fe.every((e=>"finished"===e.status));return!(!nt.trim()&&!e)&&Fe.every((e=>"finished"===e.status||e.isInsertedAsRaw))}),[Zt,Pe,Ve,nt,Fe]);s.useImperativeHandle(K,(()=>({onSubmit:Us}))),s.useEffect((()=>{Oe(Es)}),[Es]),s.useEffect((()=>{var e;if(R){const t=Array.from(De),s=null===(e=t[t.length-2].parts.find((e=>"text"===e.type)))||void 0===e?void 0:e.content;Us(s,!0)}}),[R]),s.useEffect((()=>{if(!_t.current||!X)return;const e=new ResizeObserver((e=>{for(const t of e)X(t.contentRect.height)}));return e.observe(_t.current),()=>{e.disconnect()}}),[X]),s.useEffect((()=>{if(!At)return;const e=yt.current?`${yt.current} `:"";it(`${e}${Ct}`)}),[Ct,At]),s.useEffect((()=>{if(!wt.current)return;(()=>{if(!wt.current)return;let e=wt.current.scrollHeight>52;nt.includes("\n")||Fe.length?e=!0:nt.trim()||(e=!1),rt(e)})()}),[nt,Fe]),s.useEffect((()=>{const e=wt.current,t=Nt.current;if(!e||!t||ot||nt.includes("\n"))return void lt(!1);const s=window.getComputedStyle(e),n=`${s.fontStyle} ${s.fontVariant} ${s.fontWeight} ${s.fontSize} / ${s.lineHeight} ${s.fontFamily}`,i=document.createElement("span");Object.assign(i.style,{font:n,letterSpacing:s.letterSpacing,position:"absolute",visibility:"hidden",whiteSpace:"nowrap",top:"0",left:"0"}),i.textContent=nt||os,document.body.appendChild(i);const o=i.offsetWidth;i.remove();const r=parseFloat(s.paddingLeft)||0,a=parseFloat(s.paddingRight)||0,l=e.clientWidth-r-a-t.offsetWidth;lt(o>l)}),[nt,ot,os]);const Us=(t,s=!1)=>e.__awaiter(void 0,void 0,void 0,(function*(){var e,n,i,o,r,a;let l=null;try{if(Pe||Ve)return;const d=Fe.filter((e=>"finished"===e.status&&!e.isInsertedAsRaw)),c=d.map((e=>e.documentId)).filter(Boolean),u=d.filter((e=>"image"===e.type)).map((e=>{const t=e.name.split(".").pop()||"";return{documentId:e.documentId,extension:t}})),p=null!=t?t:nt,m=null!==(n=null===(e=null==me?void 0:me.documentuploadtype)||void 0===e?void 0:e.startsWith("enduserupload"))&&void 0!==n&&n&&c.length>0;if(!p&&!m)return;qe(""),He(""),Re(null),it(""),Se(!1),Me("fetching"),Ye(),Ge();const f=null!==(o=null===(i=st.data)||void 0===i?void 0:i.messages)&&void 0!==o?o:[],g=w.getUnpersistedMemoryMessages(De,f),h=s?g.slice(0,g.length-1):g,b=(e=>e.reduce(((e,t)=>Math.max(e,t.id)),0)+1)(h),I=b+(s?0:1),y={id:I,role:"assistant",parts:[],documentIds:[]},x=[...h,...s?[]:[{id:b,role:"user",parts:[{type:"text",content:p,isVisible:!0}],documentIds:m?c:[]}],y];Le(x),Ge(),m&&Xe([]);const j=T.getPickaxeConfigMetadata(ue),S="undefined"!=typeof crypto&&"randomUUID"in crypto?crypto.randomUUID():`submission-${Date.now()}-${Math.random().toString(36).slice(2)}`;l=S,jt.current=S,St.current=null,Ot.current=[];const O=yield fetch(`${process.env.NEXT_PUBLIC_PICKAXE_API2_URL}/response/submit`,Object.assign({method:"POST",body:JSON.stringify(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({origin:oe,pickaxeId:re,sessionId:ae,submissionId:S,senderType:de,value:p},m&&{documentIds:c}),le&&{sender:le}),Te&&{studioSessionToken:Te}),!Te&&!le&&{sender:E.initializeEmbedUserId()}),us&&{portalId:us}),ue&&{deploymentId:ue}),j&&{metadata:j}),m&&u.length>0?{uploadedModelImages:u}:{})),headers:Object.assign(Object.assign({},(!process.env.NODE_ENV||"development"===process.env.NODE_ENV)&&Object.assign({},process.env.NEXT_PUBLIC_PICKAXE_SESSION_TOKEN&&{"x-pickaxe-session-token":process.env.NEXT_PUBLIC_PICKAXE_SESSION_TOKEN})),{"x-request-sent-at":(new Date).toISOString()})},Qt&&{credentials:"include"})),N=yield O.json();if(!N.success){if(N.limitData){const e=new Error(N.error||N.message||(null==ve?void 0:ve["failed-to-start-generation"])||"Failed to start generation");throw e.limitData=N.limitData,e}if(is(N))return;throw new Error(N.error||N.message||(null==ve?void 0:ve["failed-to-start-generation"])||"Failed to start generation")}const _=null!==(r=N.submissionId)&&void 0!==r?r:S;l=_,jt.current=_;const k=()=>St.current===_;if(k())return;ts&&Ie&&ae&&Et.current.add(ae);const C=Object.assign(Object.assign({},ms()),{message:p,documentIds:m?c:[],uploadedModelImages:m?u:[],hasUploadedDocuments:m,isHidden:s,metadata:null!=j?j:null});mt?(fs(),U.fireDeploymentFirstMessageSubmittedWebhook(C)):Tt.current=C,Me("streaming"),kt.current=new AbortController;const A=[];let D=[...null!=Je?Je:[]],P=0,R=!1,q="";for(;!R;)try{const e=yield fetch(`${process.env.NEXT_PUBLIC_PICKAXE_API2_URL}/response/stream/${_}?index=${P}`,{signal:null===(a=kt.current)||void 0===a?void 0:a.signal,headers:{"Cache-Control":"no-cache",Connection:"keep-alive"}});if(!e.body)throw new Error("No response body");const t=e.body.getReader();xt.current=t;const s=new TextDecoder,n=v.createParser({onEvent:e=>{var t,s;if(k())R=!0;else if(e.event&&"ping"!==e.event&&P++,"stop"!==e.event){if("error"===e.event){const t=JSON.parse(e.data);if(t.limitData)return Re(t.limitData),qe(""),void(R=!0);const s=t.error||t.message||(null==ve?void 0:ve["something-went-wrong"])||"Something went wrong.";return is(t)||qe(s),void(R=!0)}if("delta"===e.event){const n=JSON.parse(e.data);if("data-error"===n.type&&H){const e=n.data.error;if("string"==typeof e){const t=/['"]type['"]\s*:\s*['"]unauthorized_smithery['"]/.test(e),s=/['"]type['"]\s*:\s*['"]unauthorized_composio['"]/.test(e);if(t){const t=e.match(/['"]qualifiedName['"]\s*:\s*['"]([^'"]+)['"]/),s=e.match(/['"]serverId['"]\s*:\s*['"]([^'"]+)['"]/),n=e.match(/['"]name['"]\s*:\s*['"]([^'"]+)['"]/);if(t&&t[1]&&s&&s[1]&&n&&n[1])throw R=!0,H({provider:"smithery",smitheryId:t[1],serverId:s[1],name:n[1]}),new Error("STOP_STREAM")}else if(s){const t=e.match(/['"]toolkitSlug['"]\s*:\s*['"]([^'"]+)['"]/),s=e.match(/['"]serverId['"]\s*:\s*['"]([^'"]+)['"]/),n=e.match(/['"]name['"]\s*:\s*['"]([^'"]+)['"]/);if(t&&t[1]&&s&&s[1]&&n&&n[1])throw R=!0,H({provider:"composio",toolkitSlug:t[1],serverId:s[1],name:n[1]}),new Error("STOP_STREAM")}}else if("object"==typeof e&&null!==e){const t=e;if("unauthorized_smithery"===t.type&&t.qualifiedName&&t.serverId&&t.name)throw R=!0,H({provider:"smithery",smitheryId:t.qualifiedName,serverId:t.serverId,name:t.name}),new Error("STOP_STREAM");if("unauthorized_composio"===t.type&&t.toolkitSlug&&t.serverId&&t.name)throw R=!0,H({provider:"composio",toolkitSlug:t.toolkitSlug,serverId:t.serverId,name:t.name}),new Error("STOP_STREAM")}}else if("text-start"===n.type)q="",A.push({type:"text",content:"",isVisible:null===(t=n.isVisible)||void 0===t||t});else if("text-delta"===n.type)q+=n.delta,A[A.length-1].content=q;else if("text-end"===n.type)q="";else if("reasoning-start"===n.type)q="",A.push({type:"reasoning",content:"",isVisible:null===(s=n.isVisible)||void 0===s||s});else if("reasoning-delta"===n.type)q+=n.delta,A[A.length-1].content=q;else if("reasoning-end"===n.type)q="";else if(n.type.startsWith("data-")){const e=n;A.push({type:e.type,content:JSON.stringify(e.data),isVisible:!0})}Ot.current=L(A);const i=L(A);Le((e=>{const t=e.findIndex((e=>e.id===I)),s=Object.assign(Object.assign({},y),{parts:i});return-1===t?[...e,s]:e.map(((e,n)=>n===t?s:e))}))}else if("artifact_created"===e.event){const t=JSON.parse(e.data);D=D.filter((e=>!(e.id===t.id&&e.version===t.version))),D.push(Object.assign(Object.assign({},t),{content:"",status:"streaming"})),Ze([...D]),Qe.startsWith("inline")||et({id:t.id,version:t.version})}else if("artifact_updated"===e.event){const t=JSON.parse(e.data);D=D.filter((e=>!(e.id===t.id&&e.version===t.version))),D.push(Object.assign(Object.assign({},t),{content:"",status:"updating"})),Ze(D),Qe.startsWith("inline")||et({id:t.id,version:t.version})}else if("artifact_rewrite"===e.event){const t=JSON.parse(e.data);D=D.filter((e=>!(e.id===t.id&&e.version===t.version))),D.push(Object.assign(Object.assign({},t),{content:"",status:"streaming"})),Ze(D),Qe.startsWith("inline")||et({id:t.id,version:t.version})}else if("artifact_content"===e.event){const t=JSON.parse(e.data),s=t.token.replace(/\u200B/g,"");D=D.map((e=>e.id===t.id&&e.version===t.version?Object.assign(Object.assign({},e),{content:e.content+s,status:"streaming"}):e)),Ze(D)}else if("artifact_finished"===e.event){const t=JSON.parse(e.data);Ze(D.map((e=>e.id===t.id?Object.assign(Object.assign({},e),{status:"finished"}):e)))}else if("error"===e.event){const t=JSON.parse(e.data);if(t.limitData)return Re(t.limitData),qe(""),void(R=!0);const s=t.error||t.message||(null==ve?void 0:ve["something-went-wrong-try-again"])||"Something went wrong, please try again.";if(is(t))return void(R=!0);qe(s)}else"stop"===e.event&&(R=!0)}else R=!0}});for(;;){if(k()){R=!0,t.cancel().catch((()=>{}));break}const{value:e,done:i}=yield t.read();if(k()){R=!0,t.cancel().catch((()=>{}));break}if(i)break;n.feed(s.decode(e))}R||k()||(yield new Promise((e=>setTimeout(e,1e3))))}catch(e){if("STOP_STREAM"===e.message||M(e)||k())return void(R=!0);console.warn("Stream connection lost, retrying...",e),yield new Promise((e=>setTimeout(e,1e3)))}null==Ee||Ee(ae)}catch(e){if(M(e))return;if(e.limitData)Re(e.limitData),qe("");else{let t=O.default(e)||"";t&&!t.includes("Unexpected token 'A',")||(t=(null==ve?void 0:ve["high-traffic-try-again-later"])||"Oops! We're experiencing high traffic at the moment. Please try again later."),is(t)||qe(t)}}finally{const e=!l||jt.current===l;Ge(),e&&(Me("idle"),ze(),xt.current=null),l&&e&&(jt.current=null,Ot.current=[]),yield as()}}));return ns?null:t.jsx("div",Object.assign({className:k.default("flex w-full flex-shrink-0 flex-col items-center",!ss&&"px-4 pb-8"),dir:ye?"rtl":"ltr"},{children:t.jsxs("div",Object.assign({className:"flex w-full max-w-[800px] flex-col"},{children:[t.jsxs("div",Object.assign({ref:_t,className:k.default("relative flex flex-col w-full justify-end gap-y-3 py-[3px]","block"===fe.formFieldStyle&&"shadow"),style:Object.assign(Object.assign({},Yt),{maxHeight:`${Ut}px`,overflowY:"auto"})},{children:[ws&&t.jsxs("div",Object.assign({className:"sticky top-0 z-10 flex w-full items-center justify-between border-b px-4 py-2.5 shadow-sm backdrop-blur-md",style:{backgroundColor:Yt.backgroundColor?`${Yt.backgroundColor}E6`:void 0,borderColor:ge.text+"20",color:ge.text,borderTopRightRadius:fe.cornerRadius+"px",borderTopLeftRadius:fe.cornerRadius+"px"}},{children:[t.jsx("div",Object.assign({className:"flex items-center gap-2 text-sm font-medium"},{children:t.jsxs("span",{children:[ys.toLocaleString()," ",cs?(null==ve?void 0:ve.credits)||"Credits":(null==ve?void 0:ve.uses)||"Uses"," ",(null==ve?void 0:ve.remaining)||"remaining"]})})),t.jsxs("div",Object.assign({className:"flex items-center gap-3"},{children:[!Ns&&t.jsx("button",Object.assign({className:"rounded-md px-3 py-1.5 text-xs font-semibold transition-opacity hover:opacity-90",style:{backgroundColor:ge.accent,color:ge.accentText},onClick:e=>{if(e.preventDefault(),e.stopPropagation(),_s)return void window.open(_s,"_blank","noopener,noreferrer");const t=E.buildUpgradeUrl({baseUrl:ut,accessGroupId:null==je?void 0:je.accessGroupId,redirectUrl:document.URL});t&&(E.isInIframe()?window.open(t):location.href=t)}},{children:ks})),t.jsx("button",Object.assign({className:"flex h-6 w-6 items-center justify-center rounded-full opacity-60 transition-opacity hover:opacity-100",onClick:()=>vt(!0)},{children:t.jsx("svg",Object.assign({xmlns:"http://www.w3.org/2000/svg",fill:"none",viewBox:"0 0 24 24",strokeWidth:2,stroke:"currentColor",className:"h-4 w-4"},{children:t.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M6 18L18 6M6 6l12 12"})}))}))]}))]})),!Pe&&Fe.length>0&&t.jsx(x.default,{className:"p-4 pb-0",isDisabled:Pe}),t.jsxs("div",Object.assign({className:"relative flex w-full flex-col"},{children:[At&&t.jsxs("div",Object.assign({className:"absolute left-4 top-1/2 flex -translate-y-1/2 select-none items-center gap-x-2"},{children:[t.jsx("span",{className:"h-2 w-2 animate-pulse rounded-full bg-c-secondary",style:{backgroundColor:null!==(ie=ge.accent)&&void 0!==ie?ie:"#ff0000"}}),t.jsx("span",Object.assign({className:"text-sm text-c-secondary font-semilight",style:{color:ge.text+"90"}},{children:(null==ve?void 0:ve.listening)||"Listening..."}))]})),t.jsx(j.default,Object.assign({ref:wt,className:k.default(Wt.i1,"py-3.5 max-h-60 px-4 w-full border-transparent bg-transparent",!nt.trim()&&!nt.includes("\n")&&"overflow-hidden text-ellipsis whitespace-nowrap placeholder:whitespace-normal placeholder:overflow-visible",ye?"text-right":"text-left",rs&&"mb-12",At&&"text-transparent"),value:nt,placeholder:os,onChange:e=>{it(e)},onKeyDown:e=>{be||We||"Enter"===e.key&&(e.shiftKey||(e.preventDefault(),Ve||Pe||Us()))},onPaste:t=>e.__awaiter(void 0,void 0,void 0,(function*(){const e=Array.from(t.clipboardData.files||[]);if(e.length>0){if(!Zt)return;t.preventDefault(),Se(!1),yield $e(e)}}))},B&&{onFocus:B},$&&{onBlur:$},{dir:ye?"rtl":"ltr"})),t.jsx("div",Object.assign({ref:Nt,className:k.default("flex items-center gap-2 absolute right-0 z-2 transition-all duration-200 ease-in-out",rs?"bottom-0 mb-2.5":"top-1/2 -translate-y-1/2"),style:Object.assign(Object.assign({},!rs&&Yt.backgroundColor&&{backgroundColor:Yt.backgroundColor}),{borderTopRightRadius:fe.cornerRadius+"px",borderBottomRightRadius:fe.cornerRadius+"px"})},{children:Pe?t.jsx("button",Object.assign({className:"flex h-8 w-8 items-center mr-2 justify-center rounded-full outline-none transition-colors duration-200 ease-in-out",onClick:()=>{const t=jt.current;t&&(St.current=t,(t=>{e.__awaiter(void 0,void 0,void 0,(function*(){if(!(t=null!=t?t:jt.current))return;const e=L(Ot.current);try{yield fetch(`${process.env.NEXT_PUBLIC_PICKAXE_API2_URL}/response/cancel/${t}`,Object.assign({method:"POST",headers:Object.assign(Object.assign({"Content-Type":"application/json"},(!process.env.NODE_ENV||"development"===process.env.NODE_ENV)&&Object.assign({},process.env.NEXT_PUBLIC_PICKAXE_SESSION_TOKEN&&{"x-pickaxe-session-token":process.env.NEXT_PUBLIC_PICKAXE_SESSION_TOKEN})),{"x-request-sent-at":(new Date).toISOString()}),body:JSON.stringify({outputMessageParts:e})},Qt&&{credentials:"include"}))}catch(e){console.warn("Failed to cancel submission",e)}}))})(t)),kt.current&&(kt.current.abort(),kt.current=null),xt.current&&(xt.current.cancel().catch((()=>{})),xt.current=null),Me("idle")},style:{backgroundColor:ge.accent,color:ge.accentText}},{children:t.jsx(y.default,{className:"h-4 w-4 shrink-0"})})):At?t.jsx("button",Object.assign({className:"flex h-8 w-8 items-center mr-2 justify-center rounded-full outline-none transition-colors duration-200 ease-in-out",onClick:Mt,style:{backgroundColor:ge.accent,color:ge.accentText}},{children:t.jsx(y.default,{className:"h-4 w-4 shrink-0"})})):t.jsxs(t.Fragment,{children:[Zt&&t.jsxs("button",Object.assign({className:"flex h-8 w-8 items-center justify-center rounded-full outline-none transition-colors duration-200 ease-in-out disabled:cursor-default",style:{backgroundColor:Bt?ge.accent+"10":void 0,color:Bt?ge.accent:ge.accent+"80"},disabled:Ve||Pe,onClick:()=>{var e;return null===(e=It.current)||void 0===e?void 0:e.click()}},$t,{children:[t.jsx("input",{id:"file-upload",ref:It,type:"file",accept:[...g.allowedFileMimeTypes,...g.allowedImageMimeTypes,...g.additionalAllowedFileExtensions].join(", "),multiple:!0,hidden:!0,className:"hidden",onChange:t=>e.__awaiter(void 0,void 0,void 0,(function*(){Se(!1),yield $e(Array.from(t.target.files||[])),t.target.value=""}))}),t.jsx(h.default,{className:"h-6 w-6 shrink-0"})]})),es&&t.jsx("button",Object.assign({className:"disabled:cursor-default flex h-8 w-8 items-center justify-center rounded-full outline-none transition-colors duration-200 ease-in-out",style:{backgroundColor:At?ge.accent:Ht?ge.accent+"10":void 0,color:At?ge.accentText:Ht?ge.accent:ge.accent+"80"},disabled:Ve||Pe||Dt,onClick:()=>{At?Mt():(yt.current=nt,Lt(he||"en-US"))}},Kt,{children:t.jsx(I.default,{className:"h-5 w-5 shrink-0"})})),t.jsx("button",Object.assign({className:"flex h-8 w-8 items-center mr-2 justify-center rounded-full outline-none transition-colors duration-200 ease-in-out disabled:cursor-default",style:{backgroundColor:qt||Ts?ge.accent:ge.accent+"10",color:qt||Ts?ge.accentText:ge.accent+"80"},disabled:!Ts,onClick:()=>Us()},Ft,{children:t.jsx(b.default,{className:k.default("h-6 w-6 shrink-0",ye&&"scale-x-[-1] transform")})}))]})}))]}))]})),Be&&t.jsx(S.default,{error:Be,className:"mt-3"})]}))}))}));B.displayName="Input",exports.default=B;
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e=require("../../../_virtual/_tslib.js"),t=require("react/jsx-runtime"),s=require("react"),n=require("../../../hooks/pickaxe/usePickaxeContext.js"),i=require("../../../hooks/pickaxe/useResponseContext.js"),r=require("../../../hooks/studio/useStyleInput.js"),o=require("../../../hooks/studio/useStyleFontSize.js"),a=require("../../../hooks/pickaxe/useConversation.js"),l=require("../../../hooks/pickaxe/useDimensionContext.js"),d=require("../Addons/Auth/hooks/useAuthContext.js"),c=require("../Addons/Document/hooks/useDocument.js"),u=require("../Addons/Scroll/hooks/useScroll.js"),p=require("../Addons/Artifact/hooks/useArtifactContext.js"),m=require("../../../hooks/core/useHover.js"),f=require("../../../hooks/core/useMediaQuery.js"),g=require("../../../common/documents.js"),v=require("eventsource-parser"),h=require("../../Icons/attach-vertical.svg.js"),I=require("../../Icons/arrow-right.svg.js"),b=require("../../Icons/microphone.svg.js"),y=require("../../Icons/stop.svg.js"),x=require("../Addons/Document/List.js"),j=require("../../Core/Textarea.js"),S=require("../../Core/ErrorAlert.js"),O=require("../../../common/error.js"),w=require("../../../common/chatMessages.js"),N=require("../../../common/api/pickaxe.js"),_=require("../../../common/validation.js"),k=require("../../../common/cn.js"),E=require("../../../common/utils.js"),T=require("../../../common/pickaxeConfig.js"),U=require("../../../common/deploymentWebhooks.js"),C=require("../../../hooks/studio/useStudio.js"),A=require("../../../hooks/pickaxe/useSpeechToText.js"),D=require("../common/PickaxeCommon.js");const P=e=>"string"==typeof e&&e.trim().length>0,L=e=>e.map((e=>Object.assign({},e))),M=e=>e instanceof Error&&("AbortError"===e.name||"BodyStreamBuffer was aborted"===e.message),R=(e,t)=>{if(e&&"object"==typeof e)return e[t]},q=(e,t)=>{const s=R(e,t);return P(s)?s:null},F=e=>{const t=Number(e);return Number.isFinite(t)?t:void 0},V=({studioUser:e,deploymentId:t,portalId:s})=>{var n,i;const r=Array.isArray(R(e,"uses"))?R(e,"uses"):[],o=(({deploymentId:e,portalId:t})=>P(e)?{type:"deployment",id:e}:P(t)?{type:"portal",id:t}:null)({deploymentId:t,portalId:s});if(!o)return{scope:o,record:null};const a=null!==(i=null!==(n=r.find((e=>e.id===o.id&&e.type===o.type)))&&void 0!==n?n:r.find((e=>e.id===o.id)))&&void 0!==i?i:null;return{scope:o,record:a}},B=s.forwardRef((({resubmitPrompt:R,onFocus:B,onBlur:$,onInputHeightChange:X,initSmitheryAuthData:H},K)=>{var W,Y,z,G,J,Q,Z,ee,te,se,ne,ie;const{origin:re,pickaxeId:oe,sessionId:ae,sender:le,senderType:de,portalId:ce,deploymentId:ue,deploymentType:pe,pickaxe:me,styles:fe,colors:ge,translations:ve,locale:he,forceMobile:Ie,isNewChat:be,isRtl:ye,isShowFeedbackMessage:xe,accessGroup:je,setIsNewChat:Se,setIsShowIceBreaker:Oe,setValidationStatus:we,setValidationUpgradeGroups:Ne,setValidationUpgradeUrl:_e,setAccessGroup:ke,onGenerateComplete:Ee}=n.usePickaxeContext(),{token:Te,isLoggedOut:Ue,isSent:Ce,isPricingAuth:Ae}=d.useAuthContext(),{messages:De,isGenerating:Pe,setMessages:Le,setStatus:Me,setLimitData:Re,setError:qe}=i.useResponseContext(),{documents:Fe,isUploading:Ve,documentError:Be,onFileUpload:$e,setDocuments:Xe,setDocumentError:He}=c.useDocument(),{studio:Ke}=C.useStudio(),[We]=f.useMediaQuery("(max-width: 480px)"),{scrollStartSession:Ye,scrollEndSession:ze,scrollToBottom:Ge}=u.useScroll({auto:!0,smooth:!(Ie||We)}),{artifacts:Je,currentPopupType:Qe,setArtifacts:Ze,setCurrentArtifact:et}=p.useArtifactContext(),{height:tt}=l.useDimensionContext(),st=a.useConversation(),[nt,it]=s.useState(""),[rt,ot]=s.useState(!1),[at,lt]=s.useState(!1),[dt,ct]=s.useState(null),[ut,pt]=s.useState(null),[mt,ft]=s.useState(!1),[gt,vt]=s.useState(!1),[ht,It]=s.useState(0),bt=s.useRef(null),yt=s.useRef(""),xt=s.useRef(null),jt=s.useRef(null),St=s.useRef(null),Ot=s.useRef([]),wt=s.useRef(null),Nt=s.useRef(null),_t=s.useRef(null),kt=s.useRef(null),Et=s.useRef(new Set),Tt=s.useRef(null),Ut=Math.max(.4*tt,100),{speechTranscript:Ct,isSpeechListening:At,isSpeechProcessing:Dt,isSpeechSupported:Pt,onStartListening:Lt,onStopListening:Mt}=A.useSpeechToText(),Rt=m.useHover(),{isHover:qt}=Rt,Ft=e.__rest(Rt,["isHover"]),Vt=m.useHover(),{isHover:Bt}=Vt,$t=e.__rest(Vt,["isHover"]),Xt=m.useHover(),{isHover:Ht}=Xt,Kt=e.__rest(Xt,["isHover"]),Wt=o.useStyleFontSize(),Yt=r.useStyleInput(),zt="undefined"!=typeof window?window.location.hostname:"",Gt="undefined"!=typeof window?window.location.href:"",Jt="undefined"!=typeof window&&window.self!==window.top,Qt=zt.includes("pickaxe.co")&&!Gt.includes("https://studio.pickaxe.co/_embed")&&!Jt,Zt=null!==(Y=null===(W=null==me?void 0:me.documentuploadtype)||void 0===W?void 0:W.startsWith("enduserupload"))&&void 0!==Y&&Y,es=Pt&&(null==me?void 0:me.enablevoicetotext),ts=P(ue),ss="chat-input"===pe&&be&&!Ce,ns="chat-input"===pe&&Ae&&Ue&&Ce,is=s.useCallback((e=>{const t=_.getValidationFailure(e);return!!t&&(qe(""),Re(null),we(t.status),ke(t.accessGroup),Ne(t.upgradeGroups),_e(t.upgradeUrl),!0)}),[qe,Re,we,Ne,_e,ke]),rs=null!==(z=null==me?void 0:me.placeholdertext)&&void 0!==z?z:ye?"بماذا تريد أن تتحدث؟":(null==ve?void 0:ve["what-do-you-want-to-talk-about"])||"What do you want to talk about?",os=rt||at,as=s.useCallback((()=>e.__awaiter(void 0,void 0,void 0,(function*(){ft(!1);try{const e=yield fetch(`${process.env.NEXT_PUBLIC_PICKAXE_API2_URL}/user`,Object.assign(Object.assign({method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(Object.assign({studioId:null==me?void 0:me.studioid},Te?{studioSessionToken:Te}:le?{sender:le}:{sender:E.initializeEmbedUserId()}))},(!process.env.NODE_ENV||"development"===process.env.NODE_ENV)&&Object.assign({},process.env.NEXT_PUBLIC_PICKAXE_SESSION_TOKEN&&{headers:{"Content-Type":"application/json","x-pickaxe-session-token":process.env.NEXT_PUBLIC_PICKAXE_SESSION_TOKEN}})),Qt&&{credentials:"include"})),t=yield e.json();(null==t?void 0:t.studioUser)&&(ct(t.studioUser),pt(t.url))}catch(e){console.error("Failed to fetch studio user:",e)}finally{ft(!0)}}))),[Qt,null==me?void 0:me.studioid,le,Te]);s.useEffect((()=>{as()}),[as]);const ls=Number(null!==(G=null==je?void 0:je.limit)&&void 0!==G?G:0),ds="string"==typeof(null==je?void 0:je.limitInterval)?je.limitInterval:null,cs=!!(null==Ke?void 0:Ke.data.usage)&&Ke.data.usage.isCredits,us=s.useMemo((()=>{var e,t,s,n,i;return null!==(i=null!==(n=null!==(s=null!==(t=null!==(e=null!=ce?ce:q(dt,"portalId"))&&void 0!==e?e:q(dt,"portalid"))&&void 0!==t?t:q(je,"portalId"))&&void 0!==s?s:q(je,"portalid"))&&void 0!==n?n:q(me,"portalId"))&&void 0!==i?i:q(me,"portalid")}),[je,ce,me,dt]),ps=s.useMemo((()=>V({studioUser:dt,deploymentId:ue,portalId:us})),[ue,us,dt]);s.useEffect((()=>{ts&&be&&ae&&Et.current.add(ae)}),[be,ae,ts]);const ms=s.useCallback((()=>{var e,t,s;return{studioId:null==me?void 0:me.studioid,userEmail:q(dt,"email"),userId:null!==(e=q(dt,"userId"))&&void 0!==e?e:q(dt,"userid"),sessionId:ae,deploymentId:ue,deploymentType:pe,portalId:us,accessGroupId:null!==(t=null==je?void 0:je.accessGroupId)&&void 0!==t?t:null,pickaxeId:oe,sender:le,senderType:de,origin:re,metadata:null!==(s=T.getPickaxeConfigMetadata(ue))&&void 0!==s?s:null}}),[null==je?void 0:je.accessGroupId,ue,pe,re,null==me?void 0:me.studioid,oe,us,le,de,ae,dt]),fs=s.useCallback((()=>!!(ts&&mt&&ae)&&(!!Et.current.has(ae)&&(U.fireDeploymentSessionInitializedWebhook(ms()),Et.current.delete(ae),!0))),[ms,mt,ae,ts]);s.useEffect((()=>{if(!mt||!ae)return;fs();const e=Tt.current;(null==e?void 0:e.sessionId)===ae&&(U.fireDeploymentFirstMessageSubmittedWebhook(Object.assign(Object.assign(Object.assign({},e),ms()),{message:e.message,documentIds:e.documentIds,uploadedModelImages:e.uploadedModelImages,hasUploadedDocuments:e.hasUploadedDocuments,isHidden:e.isHidden})),Tt.current=null)}),[fs,ms,mt,ae]);const gs={currentUses:F(null==dt?void 0:dt.currentUses),extraUses:F(null==dt?void 0:dt.extraUses)},vs=ps.scope?{currentUses:null!==(Q=F(null===(J=ps.record)||void 0===J?void 0:J.currentUses))&&void 0!==Q?Q:0,extraUses:null!==(ee=F(null===(Z=ps.record)||void 0===Z?void 0:Z.extraUses))&&void 0!==ee?ee:0}:{currentUses:0,extraUses:0},hs=q(dt,"type"),Is="guest"===hs||!hs&&Ue?vs:gs;s.useEffect((()=>{let t=!0;return e.__awaiter(void 0,void 0,void 0,(function*(){var e;if(cs&&(null===(e=null==Ke?void 0:Ke.data)||void 0===e?void 0:e.workspaceId))try{const e=yield N.pickaxeApi2.get(`/cost_per_run?workspaceId=${Ke.data.workspaceId}`,{withCredentials:!1});t&&It(1e4*(Number(e.data.costPerRun)||0))}catch(e){console.error("Failed to fetch average cost per run:",e),t&&It(0)}else t&&It(0)})),()=>{t=!1}}),[cs,null===(te=null==Ke?void 0:Ke.data)||void 0===te?void 0:te.workspaceId]);const bs=(({currentUses:e,extraUses:t,limit:s,limitInterval:n})=>{const i=Number(null!=e?e:0),r=Number(null!=t?t:0);return s===D.STUDIO_INFINITY_VALUE||r===D.STUDIO_INFINITY_VALUE?D.STUDIO_INFINITY_VALUE:"one_time"===n?Math.max(0,r-i):Math.max(0,s-i)+r})({currentUses:Is.currentUses,extraUses:Is.extraUses,limit:ls,limitInterval:ds}),ys=bs===D.STUDIO_INFINITY_VALUE?D.STUDIO_INFINITY_VALUE:Math.max(0,Math.ceil(bs)),xs=(({extraUses:e,limit:t,limitInterval:s})=>{const n=Number(null!=e?e:0);return t===D.STUDIO_INFINITY_VALUE||n===D.STUDIO_INFINITY_VALUE?D.STUDIO_INFINITY_VALUE:"one_time"===s?Math.max(0,n):Math.max(0,t)+Math.max(0,n)})({extraUses:Is.extraUses,limit:ls,limitInterval:ds}),js=xs===D.STUDIO_INFINITY_VALUE?D.STUDIO_INFINITY_VALUE:Math.ceil(.05*xs),Ss=cs?Math.ceil(5*ht):5,Os=js===D.STUDIO_INFINITY_VALUE?D.STUDIO_INFINITY_VALUE:Math.max(js,Ss),ws=s.useMemo((()=>!!dt&&(!gt&&(ys!==D.STUDIO_INFINITY_VALUE&&(!(ys<=0)&&ys<=Os)))),[gt,Os,ys,dt]),Ns=Boolean(null==je?void 0:je.hideUpgradeOptions),_s=!Ns&&(null===(se=null==je?void 0:je.upgrade)||void 0===se?void 0:se.isLinkToCustomURL)&&"string"==typeof je.upgrade.limitLink&&je.upgrade.limitLink.trim().length>0?je.upgrade.limitLink.trim():null,ks=_s&&"string"==typeof(null===(ne=null==je?void 0:je.upgrade)||void 0===ne?void 0:ne.limitCTA)&&je.upgrade.limitCTA.trim().length>0?je.upgrade.limitCTA:(null==ve?void 0:ve["pricing.upgrade"])||(null==ve?void 0:ve.upgrade)||"Upgrade",Es=s.useMemo((()=>{var e,t,s;return!!be&&(!!me&&(!st.isLoading&&(!((null!==(t=null===(e=st.data)||void 0===e?void 0:e.messages.length)&&void 0!==t?t:0)>1)&&(!!(null===(s=me.icebreakers)||void 0===s?void 0:s.length)&&(!xe&&!ss)))))}),[me,be,xe,ss,st.data,st.isLoading]),Ts=s.useMemo((()=>{if(Pe||Ve)return!1;const e=Zt&&Fe.length>0&&Fe.every((e=>"finished"===e.status));return!(!nt.trim()&&!e)&&Fe.every((e=>"finished"===e.status||e.isInsertedAsRaw))}),[Zt,Pe,Ve,nt,Fe]);s.useImperativeHandle(K,(()=>({onSubmit:Us}))),s.useEffect((()=>{Oe(Es)}),[Es]),s.useEffect((()=>{var e;if(R){const t=Array.from(De),s=null===(e=t[t.length-2].parts.find((e=>"text"===e.type)))||void 0===e?void 0:e.content;Us(s,!0)}}),[R]),s.useEffect((()=>{if(!_t.current||!X)return;const e=new ResizeObserver((e=>{for(const t of e)X(t.contentRect.height)}));return e.observe(_t.current),()=>{e.disconnect()}}),[X]),s.useEffect((()=>{if(!At)return;const e=yt.current?`${yt.current} `:"";it(`${e}${Ct}`)}),[Ct,At]),s.useEffect((()=>{if(!wt.current)return;(()=>{if(!wt.current)return;let e=wt.current.scrollHeight>52;nt.includes("\n")||Fe.length?e=!0:nt.trim()||(e=!1),ot(e)})()}),[nt,Fe]),s.useEffect((()=>{const e=wt.current,t=Nt.current;if(!e||!t||rt||nt.includes("\n"))return void lt(!1);const s=window.getComputedStyle(e),n=`${s.fontStyle} ${s.fontVariant} ${s.fontWeight} ${s.fontSize} / ${s.lineHeight} ${s.fontFamily}`,i=document.createElement("span");Object.assign(i.style,{font:n,letterSpacing:s.letterSpacing,position:"absolute",visibility:"hidden",whiteSpace:"nowrap",top:"0",left:"0"}),i.textContent=nt||rs,document.body.appendChild(i);const r=i.offsetWidth;i.remove();const o=parseFloat(s.paddingLeft)||0,a=parseFloat(s.paddingRight)||0,l=e.clientWidth-o-a-t.offsetWidth;lt(r>l)}),[nt,rt,rs]);const Us=(t,s=!1)=>e.__awaiter(void 0,void 0,void 0,(function*(){var e,n,i,r,o,a;let l=null;try{if(Pe||Ve)return;const d=Fe.filter((e=>"finished"===e.status&&!e.isInsertedAsRaw)),c=d.map((e=>e.documentId)).filter(Boolean),u=d.filter((e=>"image"===e.type)).map((e=>{const t=e.name.split(".").pop()||"";return{documentId:e.documentId,extension:t}})),p=null!=t?t:nt,m=null!==(n=null===(e=null==me?void 0:me.documentuploadtype)||void 0===e?void 0:e.startsWith("enduserupload"))&&void 0!==n&&n&&c.length>0;if(!p&&!m)return;qe(""),He(""),Re(null),it(""),Se(!1),Me("fetching"),Ye(),Ge();const f=null!==(r=null===(i=st.data)||void 0===i?void 0:i.messages)&&void 0!==r?r:[],g=w.getUnpersistedMemoryMessages(De,f),h=s?g.slice(0,g.length-1):g,I=(e=>e.reduce(((e,t)=>Math.max(e,t.id)),0)+1)(h),b=I+(s?0:1),y={id:b,role:"assistant",parts:[],documentIds:[]},x=[...h,...s?[]:[{id:I,role:"user",parts:[{type:"text",content:p,isVisible:!0}],documentIds:m?c:[]}],y];Le(x),Ge(),m&&Xe([]);const j=T.getPickaxeConfigMetadata(ue),S="undefined"!=typeof crypto&&"randomUUID"in crypto?crypto.randomUUID():`submission-${Date.now()}-${Math.random().toString(36).slice(2)}`;l=S,jt.current=S,St.current=null,Ot.current=[];const O=yield fetch(`${process.env.NEXT_PUBLIC_PICKAXE_API2_URL}/response/submit`,Object.assign({method:"POST",body:JSON.stringify(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({origin:re,pickaxeId:oe,sessionId:ae,submissionId:S,senderType:de,value:p},m&&{documentIds:c}),le&&{sender:le}),Te&&{studioSessionToken:Te}),!Te&&!le&&{sender:E.initializeEmbedUserId()}),us&&{portalId:us}),ue&&{deploymentId:ue}),j&&{metadata:j}),m&&u.length>0?{uploadedModelImages:u}:{})),headers:Object.assign(Object.assign({},(!process.env.NODE_ENV||"development"===process.env.NODE_ENV)&&Object.assign({},process.env.NEXT_PUBLIC_PICKAXE_SESSION_TOKEN&&{"x-pickaxe-session-token":process.env.NEXT_PUBLIC_PICKAXE_SESSION_TOKEN})),{"x-request-sent-at":(new Date).toISOString()})},Qt&&{credentials:"include"})),N=yield O.json();if(!N.success){if(N.limitData){const e=new Error(N.error||N.message||(null==ve?void 0:ve["failed-to-start-generation"])||"Failed to start generation");throw e.limitData=N.limitData,e}if(is(N))return;throw new Error(N.error||N.message||(null==ve?void 0:ve["failed-to-start-generation"])||"Failed to start generation")}const _=null!==(o=N.submissionId)&&void 0!==o?o:S;l=_,jt.current=_;const k=()=>St.current===_;if(k())return;ts&&be&&ae&&Et.current.add(ae);const C=Object.assign(Object.assign({},ms()),{message:p,documentIds:m?c:[],uploadedModelImages:m?u:[],hasUploadedDocuments:m,isHidden:s,metadata:null!=j?j:null});mt?(fs(),U.fireDeploymentFirstMessageSubmittedWebhook(C)):Tt.current=C,Me("streaming"),kt.current=new AbortController;const A=[];let D=[...null!=Je?Je:[]],P=0,R=!1,q="";for(;!R;)try{const e=yield fetch(`${process.env.NEXT_PUBLIC_PICKAXE_API2_URL}/response/stream/${_}?index=${P}`,{signal:null===(a=kt.current)||void 0===a?void 0:a.signal,headers:{"Cache-Control":"no-cache",Connection:"keep-alive"}});if(!e.body)throw new Error("No response body");const t=e.body.getReader();xt.current=t;const s=new TextDecoder,n=v.createParser({onEvent:e=>{var t,s;if(k())R=!0;else if(e.event&&"ping"!==e.event&&P++,"stop"!==e.event){if("error"===e.event){const t=JSON.parse(e.data);if(t.limitData)return Re(t.limitData),qe(""),void(R=!0);const s=t.error||t.message||(null==ve?void 0:ve["something-went-wrong"])||"Something went wrong.";return is(t)||qe(s),void(R=!0)}if("delta"===e.event){const n=JSON.parse(e.data);if("data-error"===n.type&&H){const e=n.data.error;if("string"==typeof e){const t=/['"]type['"]\s*:\s*['"]unauthorized_smithery['"]/.test(e),s=/['"]type['"]\s*:\s*['"]unauthorized_composio['"]/.test(e);if(t){const t=e.match(/['"]qualifiedName['"]\s*:\s*['"]([^'"]+)['"]/),s=e.match(/['"]serverId['"]\s*:\s*['"]([^'"]+)['"]/),n=e.match(/['"]name['"]\s*:\s*['"]([^'"]+)['"]/);if(t&&t[1]&&s&&s[1]&&n&&n[1])throw R=!0,H({provider:"smithery",smitheryId:t[1],serverId:s[1],name:n[1]}),new Error("STOP_STREAM")}else if(s){const t=e.match(/['"]toolkitSlug['"]\s*:\s*['"]([^'"]+)['"]/),s=e.match(/['"]serverId['"]\s*:\s*['"]([^'"]+)['"]/),n=e.match(/['"]name['"]\s*:\s*['"]([^'"]+)['"]/);if(t&&t[1]&&s&&s[1]&&n&&n[1])throw R=!0,H({provider:"composio",toolkitSlug:t[1],serverId:s[1],name:n[1]}),new Error("STOP_STREAM")}}else if("object"==typeof e&&null!==e){const t=e;if("unauthorized_smithery"===t.type&&t.qualifiedName&&t.serverId&&t.name)throw R=!0,H({provider:"smithery",smitheryId:t.qualifiedName,serverId:t.serverId,name:t.name}),new Error("STOP_STREAM");if("unauthorized_composio"===t.type&&t.toolkitSlug&&t.serverId&&t.name)throw R=!0,H({provider:"composio",toolkitSlug:t.toolkitSlug,serverId:t.serverId,name:t.name}),new Error("STOP_STREAM")}}else if("text-start"===n.type)q="",A.push({type:"text",content:"",isVisible:null===(t=n.isVisible)||void 0===t||t});else if("text-delta"===n.type)q+=n.delta,A[A.length-1].content=q;else if("text-end"===n.type)q="";else if("reasoning-start"===n.type)q="",A.push({type:"reasoning",content:"",isVisible:null===(s=n.isVisible)||void 0===s||s});else if("reasoning-delta"===n.type)q+=n.delta,A[A.length-1].content=q;else if("reasoning-end"===n.type)q="";else if(n.type.startsWith("data-")){const e=n;A.push({type:e.type,content:JSON.stringify(e.data),isVisible:!0})}Ot.current=L(A);const i=L(A);Le((e=>{const t=e.findIndex((e=>e.id===b)),s=Object.assign(Object.assign({},y),{parts:i});return-1===t?[...e,s]:e.map(((e,n)=>n===t?s:e))}))}else if("artifact_created"===e.event){const t=JSON.parse(e.data);D=D.filter((e=>!(e.id===t.id&&e.version===t.version))),D.push(Object.assign(Object.assign({},t),{content:"",status:"streaming"})),Ze([...D]),Qe.startsWith("inline")||et({id:t.id,version:t.version})}else if("artifact_updated"===e.event){const t=JSON.parse(e.data);D=D.filter((e=>!(e.id===t.id&&e.version===t.version))),D.push(Object.assign(Object.assign({},t),{content:"",status:"updating"})),Ze(D),Qe.startsWith("inline")||et({id:t.id,version:t.version})}else if("artifact_rewrite"===e.event){const t=JSON.parse(e.data);D=D.filter((e=>!(e.id===t.id&&e.version===t.version))),D.push(Object.assign(Object.assign({},t),{content:"",status:"streaming"})),Ze(D),Qe.startsWith("inline")||et({id:t.id,version:t.version})}else if("artifact_content"===e.event){const t=JSON.parse(e.data),s=t.token.replace(/\u200B/g,"");D=D.map((e=>e.id===t.id&&e.version===t.version?Object.assign(Object.assign({},e),{content:e.content+s,status:"streaming"}):e)),Ze(D)}else if("artifact_finished"===e.event){const t=JSON.parse(e.data);Ze(D.map((e=>e.id===t.id?Object.assign(Object.assign({},e),{status:"finished"}):e)))}else if("error"===e.event){const t=JSON.parse(e.data);if(t.limitData)return Re(t.limitData),qe(""),void(R=!0);const s=t.error||t.message||(null==ve?void 0:ve["something-went-wrong-try-again"])||"Something went wrong, please try again.";if(is(t))return void(R=!0);qe(s)}else"stop"===e.event&&(R=!0)}else R=!0}});for(;;){if(k()){R=!0,t.cancel().catch((()=>{}));break}const{value:e,done:i}=yield t.read();if(k()){R=!0,t.cancel().catch((()=>{}));break}if(i)break;n.feed(s.decode(e))}R||k()||(yield new Promise((e=>setTimeout(e,1e3))))}catch(e){if("STOP_STREAM"===e.message||M(e)||k())return void(R=!0);console.warn("Stream connection lost, retrying...",e),yield new Promise((e=>setTimeout(e,1e3)))}null==Ee||Ee(ae)}catch(e){if(M(e))return;if(e.limitData)Re(e.limitData),qe("");else{let t=O.default(e)||"";t&&!t.includes("Unexpected token 'A',")||(t=(null==ve?void 0:ve["high-traffic-try-again-later"])||"Oops! We're experiencing high traffic at the moment. Please try again later."),is(t)||qe(t)}}finally{const e=!l||jt.current===l;Ge(),e&&(Me("idle"),ze(),xt.current=null),l&&e&&(jt.current=null,Ot.current=[]),yield as()}}));return ns?null:t.jsx("div",Object.assign({className:k.default("flex w-full flex-shrink-0 flex-col items-center",!ss&&"px-4 pb-8"),dir:ye?"rtl":"ltr"},{children:t.jsxs("div",Object.assign({className:"flex w-full max-w-[800px] flex-col"},{children:[t.jsxs("div",Object.assign({ref:_t,className:k.default("relative flex flex-col w-full justify-end gap-y-3 py-[3px]","block"===fe.formFieldStyle&&"shadow"),style:Object.assign(Object.assign({},Yt),{maxHeight:`${Ut}px`,overflowY:"auto"})},{children:[ws&&t.jsxs("div",Object.assign({className:"sticky top-0 z-10 flex w-full items-center justify-between border-b px-4 py-2.5 shadow-sm backdrop-blur-md",style:{backgroundColor:Yt.backgroundColor?`${Yt.backgroundColor}E6`:void 0,borderColor:ge.text+"20",color:ge.text,borderTopRightRadius:fe.cornerRadius+"px",borderTopLeftRadius:fe.cornerRadius+"px"}},{children:[t.jsx("div",Object.assign({className:"flex items-center gap-2 text-sm font-medium"},{children:t.jsxs("span",{children:[ys.toLocaleString()," ",cs?(null==ve?void 0:ve.credits)||"Credits":(null==ve?void 0:ve.uses)||"Uses"," ",(null==ve?void 0:ve.remaining)||"remaining"]})})),t.jsxs("div",Object.assign({className:"flex items-center gap-3"},{children:[!Ns&&t.jsx("button",Object.assign({className:"rounded-md px-3 py-1.5 text-xs font-semibold transition-opacity hover:opacity-90",style:{backgroundColor:ge.accent,color:ge.accentText},onClick:e=>{if(e.preventDefault(),e.stopPropagation(),_s)return void window.open(_s,"_blank","noopener,noreferrer");const t=E.buildUpgradeUrl({baseUrl:ut,accessGroupId:null==je?void 0:je.accessGroupId,redirectUrl:document.URL});t&&(E.isInIframe()?window.open(t):location.href=t)}},{children:ks})),t.jsx("button",Object.assign({className:"flex h-6 w-6 items-center justify-center rounded-full opacity-60 transition-opacity hover:opacity-100",onClick:()=>vt(!0)},{children:t.jsx("svg",Object.assign({xmlns:"http://www.w3.org/2000/svg",fill:"none",viewBox:"0 0 24 24",strokeWidth:2,stroke:"currentColor",className:"h-4 w-4"},{children:t.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M6 18L18 6M6 6l12 12"})}))}))]}))]})),!Pe&&Fe.length>0&&t.jsx(x.default,{className:"p-4 pb-0",isDisabled:Pe}),t.jsxs("div",Object.assign({className:"relative flex w-full flex-col"},{children:[At&&t.jsxs("div",Object.assign({className:"absolute left-4 top-1/2 flex -translate-y-1/2 select-none items-center gap-x-2"},{children:[t.jsx("span",{className:"h-2 w-2 animate-pulse rounded-full bg-c-secondary",style:{backgroundColor:null!==(ie=ge.accent)&&void 0!==ie?ie:"#ff0000"}}),t.jsx("span",Object.assign({className:"text-sm text-c-secondary font-semilight",style:{color:ge.text+"90"}},{children:(null==ve?void 0:ve.listening)||"Listening..."}))]})),t.jsx(j.default,Object.assign({ref:wt,className:k.default(Wt.i1,"py-3.5 max-h-60 px-4 w-full border-transparent bg-transparent",!nt.trim()&&!nt.includes("\n")&&"overflow-hidden text-ellipsis whitespace-nowrap placeholder:whitespace-normal placeholder:overflow-visible",ye?"text-right":"text-left",os&&"mb-12",At&&"text-transparent"),value:nt,placeholder:rs,onChange:e=>{it(e)},onKeyDown:e=>{Ie||We||"Enter"===e.key&&(e.shiftKey||(e.preventDefault(),Ve||Pe||Us()))},onPaste:t=>e.__awaiter(void 0,void 0,void 0,(function*(){const e=Array.from(t.clipboardData.files||[]);if(e.length>0){if(!Zt)return;t.preventDefault(),Se(!1),yield $e(e)}}))},B&&{onFocus:B},$&&{onBlur:$},{dir:ye?"rtl":"ltr"})),t.jsx("div",Object.assign({ref:Nt,className:k.default("flex items-center gap-2 absolute z-2 transition-all duration-200 ease-in-out",os?"bottom-3 right-2":"right-0 top-1/2 -translate-y-1/2"),style:Object.assign(Object.assign({},!os&&Yt.backgroundColor&&{backgroundColor:Yt.backgroundColor}),{borderTopRightRadius:fe.cornerRadius+"px",borderBottomRightRadius:fe.cornerRadius+"px"})},{children:Pe?t.jsx("button",Object.assign({className:"flex h-8 w-8 items-center mr-2 justify-center rounded-full outline-none transition-colors duration-200 ease-in-out",onClick:()=>{const t=jt.current;t&&(St.current=t,(t=>{e.__awaiter(void 0,void 0,void 0,(function*(){if(!(t=null!=t?t:jt.current))return;const e=L(Ot.current);try{yield fetch(`${process.env.NEXT_PUBLIC_PICKAXE_API2_URL}/response/cancel/${t}`,Object.assign({method:"POST",headers:Object.assign(Object.assign({"Content-Type":"application/json"},(!process.env.NODE_ENV||"development"===process.env.NODE_ENV)&&Object.assign({},process.env.NEXT_PUBLIC_PICKAXE_SESSION_TOKEN&&{"x-pickaxe-session-token":process.env.NEXT_PUBLIC_PICKAXE_SESSION_TOKEN})),{"x-request-sent-at":(new Date).toISOString()}),body:JSON.stringify({outputMessageParts:e})},Qt&&{credentials:"include"}))}catch(e){console.warn("Failed to cancel submission",e)}}))})(t)),kt.current&&(kt.current.abort(),kt.current=null),xt.current&&(xt.current.cancel().catch((()=>{})),xt.current=null),Me("idle")},style:{backgroundColor:ge.accent,color:ge.accentText}},{children:t.jsx(y.default,{className:"h-4 w-4 shrink-0"})})):At?t.jsx("button",Object.assign({className:"flex h-8 w-8 items-center mr-2 justify-center rounded-full outline-none transition-colors duration-200 ease-in-out",onClick:Mt,style:{backgroundColor:ge.accent,color:ge.accentText}},{children:t.jsx(y.default,{className:"h-4 w-4 shrink-0"})})):t.jsxs(t.Fragment,{children:[Zt&&t.jsxs("button",Object.assign({className:"flex h-8 w-8 items-center justify-center rounded-full outline-none transition-colors duration-200 ease-in-out disabled:cursor-default",style:{backgroundColor:Bt?ge.accent+"10":void 0,color:Bt?ge.accent:ge.accent+"80"},disabled:Ve||Pe,onClick:()=>{var e;return null===(e=bt.current)||void 0===e?void 0:e.click()}},$t,{children:[t.jsx("input",{id:"file-upload",ref:bt,type:"file",accept:[...g.allowedFileMimeTypes,...g.allowedImageMimeTypes,...g.additionalAllowedFileExtensions].join(", "),multiple:!0,hidden:!0,className:"hidden",onChange:t=>e.__awaiter(void 0,void 0,void 0,(function*(){Se(!1),yield $e(Array.from(t.target.files||[])),t.target.value=""}))}),t.jsx(h.default,{className:"h-6 w-6 shrink-0"})]})),es&&t.jsx("button",Object.assign({className:"disabled:cursor-default flex h-8 w-8 items-center justify-center rounded-full outline-none transition-colors duration-200 ease-in-out",style:{backgroundColor:At?ge.accent:Ht?ge.accent+"10":void 0,color:At?ge.accentText:Ht?ge.accent:ge.accent+"80"},disabled:Ve||Pe||Dt,onClick:()=>{At?Mt():(yt.current=nt,Lt(he||"en-US"))}},Kt,{children:t.jsx(b.default,{className:"h-5 w-5 shrink-0"})})),t.jsx("button",Object.assign({className:"flex h-8 w-8 items-center mr-2 justify-center rounded-full outline-none transition-colors duration-200 ease-in-out disabled:cursor-default",style:{backgroundColor:qt||Ts?ge.accent:ge.accent+"10",color:qt||Ts?ge.accentText:ge.accent+"80"},disabled:!Ts,onClick:()=>Us()},Ft,{children:t.jsx(I.default,{className:k.default("h-6 w-6 shrink-0",ye&&"scale-x-[-1] transform")})}))]})}))]}))]})),Be&&t.jsx(S.default,{error:Be,className:"mt-3"})]}))}))}));B.displayName="Input",exports.default=B;
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e=require("../../_virtual/_tslib.js");require("../../node_modules/.pnpm/regenerator-runtime@0.14.1/node_modules/regenerator-runtime/runtime.js");var t=require("react-speech-recognition"),r=require("react"),i=require("../../common/api/pickaxe.js");function n(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}function o(e){if(e&&e.__esModule)return e;var t=Object.create(null);return e&&Object.keys(e).forEach((function(r){if("default"!==r){var i=Object.getOwnPropertyDescriptor(e,r);Object.defineProperty(t,r,i.get?i:{enumerable:!0,get:function(){return e[r]}})}})),t.default=e,Object.freeze(t)}var s=n(t);exports.useSpeechToText=()=>{const{transcript:n,listening:a,resetTranscript:c}=t.useSpeechRecognition(),[u,l]=r.useState(!1),[p,d]=r.useState(!1);return{speechTranscript:n,isSpeechSupported:!0,isSpeechProcessing:u,isSpeechListening:a,onStartListening:t=>e.__awaiter(void 0,void 0,void 0,(function*(){try{l(!0),yield navigator.mediaDevices.getUserMedia({audio:!0});const e=(yield i.pickaxeApi2.post("/speech")).data;if(!p){const{createSpeechServicesPonyfill:t}=yield Promise.resolve().then((function(){return o(require("web-speech-cognitive-services"))})),{SpeechRecognition:r}=t({credentials:{region:"eastus",authorizationToken:e.token}});s.default.applyPolyfill(r),d(!0)}c();const r={ar:"ar-SA",ca:"ca-ES",cs:"cs-CZ",da:"da-DK",de:"de-DE",en:"en-US",es:"es-ES",fi:"fi-FI",fr:"fr-FR",hi:"hi-IN",it:"it-IT",iw:"he-IL",ja:"ja-JP",ko:"ko-KR",nb:"nb-NO",nl:"nl-NL",pl:"pl-PL",pt:"pt-PT","pt-BR":"pt-BR",ro:"ro-RO",ru:"ru-RU",sv:"sv-SE",th:"th-TH",tr:"tr-TR",vi:"vi-VN",zh:"zh-CN",zu:"zu-ZA"};yield s.default.startListening({continuous:!0,interimResults:!0,language:r[t]||"en-US"})}catch(e){console.error(e)}finally{l(!1)}})),onStopListening:()=>e.__awaiter(void 0,void 0,void 0,(function*(){try{l(!0),yield s.default.abortListening()}catch(e){console.error(e)}finally{l(!1)}}))}};
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e=require("../../_virtual/_tslib.js"),t=require("react"),r=require("../../common/api/pickaxe.js");const o=()=>{if("undefined"!=typeof window)return window.AudioContext||window.webkitAudioContext},n=e=>{var t,r;e.processor&&(e.processor.onaudioprocess=null,e.processor.disconnect()),null===(t=e.source)||void 0===t||t.disconnect(),null===(r=e.silentGain)||void 0===r||r.disconnect(),e.processor=void 0,e.source=void 0,e.silentGain=void 0;for(const t of e.stream.getTracks())t.stop();"closed"!==e.audioContext.state&&e.audioContext.close()};exports.useSpeechToText=()=>{var s;const[c,i]=t.useState(""),[a,u]=t.useState(!1),[l,d]=t.useState(!1),m=t.useRef(!0),p=t.useRef(0),f=t.useRef(null),w=t.useRef(new Map),v=e=>{n(e),e.socket.readyState!==WebSocket.OPEN&&e.socket.readyState!==WebSocket.CONNECTING||e.socket.close(),f.current===e&&(f.current=null)};t.useEffect((()=>(m.current=!0,()=>{m.current=!1,p.current+=1;const e=f.current;e&&(e.socket.readyState===WebSocket.OPEN&&e.socket.send(JSON.stringify({type:"Terminate"})),v(e))})),[]);return{speechTranscript:c,isSpeechSupported:"undefined"!=typeof window&&Boolean(o())&&Boolean(null===(s=navigator.mediaDevices)||void 0===s?void 0:s.getUserMedia)&&"WebSocket"in window,isSpeechProcessing:l,isSpeechListening:a,onStartListening:t=>e.__awaiter(void 0,void 0,void 0,(function*(){var e;const t=++p.current,s=o();if(!s||!(null===(e=navigator.mediaDevices)||void 0===e?void 0:e.getUserMedia))return;const c=f.current;let a,l;c&&v(c);try{d(!0),u(!1),i(""),w.current.clear(),a=yield navigator.mediaDevices.getUserMedia({audio:{autoGainControl:!0,channelCount:1,echoCancellation:!0,noiseSuppression:!0}}),l=new s;const{data:e}=yield r.pickaxeApi2.post("/speech/assemblyai");if(!e.success||!e.token)throw new Error(e.error||"AssemblyAI streaming token was not returned");if(!m.current||t!==p.current)return;const o=new URL("wss://streaming.assemblyai.com/v3/ws");o.searchParams.set("sample_rate",String(16e3)),o.searchParams.set("speech_model","whisper-rt"),o.searchParams.set("language_detection","true"),o.searchParams.set("format_turns","true"),o.searchParams.set("token",e.token);const c={socket:new WebSocket(o),stream:a,audioContext:l,started:!1};a=void 0,l=void 0,f.current=c,yield new Promise(((e,r)=>{const o=window.setTimeout((()=>{r(new Error("AssemblyAI streaming session timed out"))}),1e4),s=e=>{c.started||(window.clearTimeout(o),r(e))};c.socket.binaryType="arraybuffer",c.socket.onmessage=r=>{try{const n=JSON.parse(String(r.data));if("Begin"!==n.type||c.started){if("Turn"===n.type)(e=>{var t;const r=(e=>{var t,r,o;const n=null===(t=e.utterance)||void 0===t?void 0:t.trim();return n&&!/^(?:\[[^\]]+\]\s*)+$/.test(n)?n:null!==(o=null===(r=e.transcript)||void 0===r?void 0:r.trim())&&void 0!==o?o:""})(e),o=null!==(t=e.turn_order)&&void 0!==t?t:0;r?w.current.set(o,r):w.current.delete(o);const n=Array.from(w.current.entries()).sort((([e],[t])=>e-t)).map((([,e])=>e)).join(" ").trim();m.current&&i(n)})(n);else if("Termination"===n.type)c.socket.close();else if("Error"===n.type)throw new Error(n.error||"AssemblyAI streaming failed")}else{c.started=!0,window.clearTimeout(o);const r=c.audioContext.createMediaStreamSource(c.stream),n=c.audioContext.createScriptProcessor(4096,1,1),s=c.audioContext.createGain();s.gain.value=0,n.onaudioprocess=({inputBuffer:e})=>{if(c.socket.readyState!==WebSocket.OPEN)return;const t=((e,t)=>{const r=t/16e3,o=Math.max(1,Math.round(e.length/r)),n=new Int16Array(o);let s=0;for(let t=0;t<o;t+=1){const o=Math.min(e.length,Math.round((t+1)*r));let c=0,i=0;for(;s<o;s+=1)c+=e[s],i+=1;const a=Math.max(-1,Math.min(1,i?c/i:0));n[t]=a<0?32768*a:32767*a}return n})(e.getChannelData(0),e.sampleRate);c.socket.send(t.buffer)},r.connect(n),n.connect(s),s.connect(c.audioContext.destination),c.source=r,c.processor=n,c.silentGain=s,c.audioContext.resume(),m.current&&t===p.current&&u(!0),e()}}catch(e){console.error("Could not process AssemblyAI message",e),s(e instanceof Error?e:new Error(String(e))),c.socket.close()}},c.socket.onerror=()=>{const e=new Error("Could not connect to AssemblyAI streaming");s(e),c.started&&console.error(e),c.socket.close()},c.socket.onclose=()=>{s(new Error("AssemblyAI streaming closed before it started")),(e=>{n(e),f.current===e&&(f.current=null,m.current&&u(!1))})(c)}})),m.current&&t===p.current||v(c)}catch(e){const t=f.current;t&&v(t),console.error("Could not start AssemblyAI speech recognition",e)}finally{if(a)for(const e of a.getTracks())e.stop();"closed"!==(null==l?void 0:l.state)&&(null==l||l.close()),m.current&&t===p.current&&d(!1)}})),onStopListening:()=>e.__awaiter(void 0,void 0,void 0,(function*(){const e=++p.current,t=f.current;if(t)try{d(!0),n(t),yield new Promise((e=>{const r=window.setTimeout(e,2e3),o=t.socket.onclose;t.socket.onclose=n=>{window.clearTimeout(r),null==o||o.call(t.socket,n),e()},t.socket.readyState===WebSocket.OPEN?t.socket.send(JSON.stringify({type:"Terminate"})):e()}))}catch(e){console.error("Could not stop AssemblyAI speech recognition",e)}finally{v(t),m.current&&e===p.current&&(u(!1),d(!1))}else u(!1)}))}};
@@ -1,9 +1,8 @@
1
- import "regenerator-runtime/runtime";
2
1
  export declare const useSpeechToText: () => {
3
2
  speechTranscript: string;
4
3
  isSpeechSupported: boolean;
5
4
  isSpeechProcessing: boolean;
6
5
  isSpeechListening: boolean;
7
- onStartListening: (locale: string) => Promise<void>;
6
+ onStartListening: (_locale: string) => Promise<void>;
8
7
  onStopListening: () => Promise<void>;
9
8
  };
@@ -1 +1 @@
1
- import{__rest as e,__awaiter as t}from"../../../_virtual/_tslib.js";import{jsx as n,jsxs as o,Fragment as s}from"react/jsx-runtime";import{forwardRef as i,useState as r,useRef as a,useCallback as l,useEffect as d,useMemo as c,useImperativeHandle as u}from"react";import{usePickaxeContext as m}from"../../../hooks/pickaxe/usePickaxeContext.js";import{useResponseContext as p}from"../../../hooks/pickaxe/useResponseContext.js";import{useStyleInput as f}from"../../../hooks/studio/useStyleInput.js";import{useStyleFontSize as g}from"../../../hooks/studio/useStyleFontSize.js";import{useConversation as v}from"../../../hooks/pickaxe/useConversation.js";import{useDimensionContext as h}from"../../../hooks/pickaxe/useDimensionContext.js";import{useAuthContext as b}from"../Addons/Auth/hooks/useAuthContext.js";import{useDocument as y}from"../Addons/Document/hooks/useDocument.js";import{useScroll as x}from"../Addons/Scroll/hooks/useScroll.js";import{useArtifactContext as I}from"../Addons/Artifact/hooks/useArtifactContext.js";import{useHover as j}from"../../../hooks/core/useHover.js";import{useMediaQuery as w}from"../../../hooks/core/useMediaQuery.js";import{allowedFileMimeTypes as O,allowedImageMimeTypes as k,additionalAllowedFileExtensions as S}from"../../../common/documents.js";import{createParser as N}from"eventsource-parser";import C from"../../Icons/attach-vertical.svg.js";import E from"../../Icons/arrow-right.svg.js";import _ from"../../Icons/microphone.svg.js";import T from"../../Icons/stop.svg.js";import U from"../Addons/Document/List.js";import A from"../../Core/Textarea.js";import P from"../../Core/ErrorAlert.js";import D from"../../../common/error.js";import{getUnpersistedMemoryMessages as L}from"../../../common/chatMessages.js";import{pickaxeApi2 as R}from"../../../common/api/pickaxe.js";import{getValidationFailure as M}from"../../../common/validation.js";import B from"../../../common/cn.js";import{buildUpgradeUrl as $,isInIframe as X,initializeEmbedUserId as K}from"../../../common/utils.js";import{getPickaxeConfigMetadata as V}from"../../../common/pickaxeConfig.js";import{fireDeploymentSessionInitializedWebhook as F,fireDeploymentFirstMessageSubmittedWebhook as H}from"../../../common/deploymentWebhooks.js";import{useStudio as W}from"../../../hooks/studio/useStudio.js";import{useSpeechToText as G}from"../../../hooks/pickaxe/useSpeechToText.js";import{STUDIO_INFINITY_VALUE as J}from"../common/PickaxeCommon.js";const z=e=>"string"==typeof e&&e.trim().length>0,q=e=>e.map((e=>Object.assign({},e))),Q=e=>e instanceof Error&&("AbortError"===e.name||"BodyStreamBuffer was aborted"===e.message),Y=(e,t)=>{if(e&&"object"==typeof e)return e[t]},Z=(e,t)=>{const n=Y(e,t);return z(n)?n:null},ee=e=>{const t=Number(e);return Number.isFinite(t)?t:void 0},te=({studioUser:e,deploymentId:t,portalId:n})=>{var o,s;const i=Array.isArray(Y(e,"uses"))?Y(e,"uses"):[],r=(({deploymentId:e,portalId:t})=>z(e)?{type:"deployment",id:e}:z(t)?{type:"portal",id:t}:null)({deploymentId:t,portalId:n});if(!r)return{scope:r,record:null};const a=null!==(s=null!==(o=i.find((e=>e.id===r.id&&e.type===r.type)))&&void 0!==o?o:i.find((e=>e.id===r.id)))&&void 0!==s?s:null;return{scope:r,record:a}},ne=i((({resubmitPrompt:i,onFocus:Y,onBlur:ne,onInputHeightChange:oe,initSmitheryAuthData:se},ie)=>{var re,ae,le,de,ce,ue,me,pe,fe,ge,ve,he;const{origin:be,pickaxeId:ye,sessionId:xe,sender:Ie,senderType:je,portalId:we,deploymentId:Oe,deploymentType:ke,pickaxe:Se,styles:Ne,colors:Ce,translations:Ee,locale:_e,forceMobile:Te,isNewChat:Ue,isRtl:Ae,isShowFeedbackMessage:Pe,accessGroup:De,setIsNewChat:Le,setIsShowIceBreaker:Re,setValidationStatus:Me,setValidationUpgradeGroups:Be,setValidationUpgradeUrl:$e,setAccessGroup:Xe,onGenerateComplete:Ke}=m(),{token:Ve,isLoggedOut:Fe,isSent:He,isPricingAuth:We}=b(),{messages:Ge,isGenerating:Je,setMessages:ze,setStatus:qe,setLimitData:Qe,setError:Ye}=p(),{documents:Ze,isUploading:et,documentError:tt,onFileUpload:nt,setDocuments:ot,setDocumentError:st}=y(),{studio:it}=W(),[rt]=w("(max-width: 480px)"),{scrollStartSession:at,scrollEndSession:lt,scrollToBottom:dt}=x({auto:!0,smooth:!(Te||rt)}),{artifacts:ct,currentPopupType:ut,setArtifacts:mt,setCurrentArtifact:pt}=I(),{height:ft}=h(),gt=v(),[vt,ht]=r(""),[bt,yt]=r(!1),[xt,It]=r(!1),[jt,wt]=r(null),[Ot,kt]=r(null),[St,Nt]=r(!1),[Ct,Et]=r(!1),[_t,Tt]=r(0),Ut=a(null),At=a(""),Pt=a(null),Dt=a(null),Lt=a(null),Rt=a([]),Mt=a(null),Bt=a(null),$t=a(null),Xt=a(null),Kt=a(new Set),Vt=a(null),Ft=Math.max(.4*ft,100),{speechTranscript:Ht,isSpeechListening:Wt,isSpeechProcessing:Gt,isSpeechSupported:Jt,onStartListening:zt,onStopListening:qt}=G(),Qt=j(),{isHover:Yt}=Qt,Zt=e(Qt,["isHover"]),en=j(),{isHover:tn}=en,nn=e(en,["isHover"]),on=j(),{isHover:sn}=on,rn=e(on,["isHover"]),an=g(),ln=f(),dn="undefined"!=typeof window?window.location.hostname:"",cn="undefined"!=typeof window?window.location.href:"",un="undefined"!=typeof window&&window.self!==window.top,mn=dn.includes("pickaxe.co")&&!cn.includes("https://studio.pickaxe.co/_embed")&&!un,pn=null!==(ae=null===(re=null==Se?void 0:Se.documentuploadtype)||void 0===re?void 0:re.startsWith("enduserupload"))&&void 0!==ae&&ae,fn=Jt&&(null==Se?void 0:Se.enablevoicetotext),gn=z(Oe),vn="chat-input"===ke&&Ue&&!He,hn="chat-input"===ke&&We&&Fe&&He,bn=l((e=>{const t=M(e);return!!t&&(Ye(""),Qe(null),Me(t.status),Xe(t.accessGroup),Be(t.upgradeGroups),$e(t.upgradeUrl),!0)}),[Ye,Qe,Me,Be,$e,Xe]),yn=null!==(le=null==Se?void 0:Se.placeholdertext)&&void 0!==le?le:Ae?"بماذا تريد أن تتحدث؟":(null==Ee?void 0:Ee["what-do-you-want-to-talk-about"])||"What do you want to talk about?",xn=bt||xt,In=l((()=>t(void 0,void 0,void 0,(function*(){Nt(!1);try{const e=yield fetch(`${process.env.NEXT_PUBLIC_PICKAXE_API2_URL}/user`,Object.assign(Object.assign({method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(Object.assign({studioId:null==Se?void 0:Se.studioid},Ve?{studioSessionToken:Ve}:Ie?{sender:Ie}:{sender:K()}))},(!process.env.NODE_ENV||"development"===process.env.NODE_ENV)&&Object.assign({},process.env.NEXT_PUBLIC_PICKAXE_SESSION_TOKEN&&{headers:{"Content-Type":"application/json","x-pickaxe-session-token":process.env.NEXT_PUBLIC_PICKAXE_SESSION_TOKEN}})),mn&&{credentials:"include"})),t=yield e.json();(null==t?void 0:t.studioUser)&&(wt(t.studioUser),kt(t.url))}catch(e){console.error("Failed to fetch studio user:",e)}finally{Nt(!0)}}))),[mn,null==Se?void 0:Se.studioid,Ie,Ve]);d((()=>{In()}),[In]);const jn=Number(null!==(de=null==De?void 0:De.limit)&&void 0!==de?de:0),wn="string"==typeof(null==De?void 0:De.limitInterval)?De.limitInterval:null,On=!!(null==it?void 0:it.data.usage)&&it.data.usage.isCredits,kn=c((()=>{var e,t,n,o,s;return null!==(s=null!==(o=null!==(n=null!==(t=null!==(e=null!=we?we:Z(jt,"portalId"))&&void 0!==e?e:Z(jt,"portalid"))&&void 0!==t?t:Z(De,"portalId"))&&void 0!==n?n:Z(De,"portalid"))&&void 0!==o?o:Z(Se,"portalId"))&&void 0!==s?s:Z(Se,"portalid")}),[De,we,Se,jt]),Sn=c((()=>te({studioUser:jt,deploymentId:Oe,portalId:kn})),[Oe,kn,jt]);d((()=>{gn&&Ue&&xe&&Kt.current.add(xe)}),[Ue,xe,gn]);const Nn=l((()=>{var e,t,n;return{studioId:null==Se?void 0:Se.studioid,userEmail:Z(jt,"email"),userId:null!==(e=Z(jt,"userId"))&&void 0!==e?e:Z(jt,"userid"),sessionId:xe,deploymentId:Oe,deploymentType:ke,portalId:kn,accessGroupId:null!==(t=null==De?void 0:De.accessGroupId)&&void 0!==t?t:null,pickaxeId:ye,sender:Ie,senderType:je,origin:be,metadata:null!==(n=V(Oe))&&void 0!==n?n:null}}),[null==De?void 0:De.accessGroupId,Oe,ke,be,null==Se?void 0:Se.studioid,ye,kn,Ie,je,xe,jt]),Cn=l((()=>!!(gn&&St&&xe)&&(!!Kt.current.has(xe)&&(F(Nn()),Kt.current.delete(xe),!0))),[Nn,St,xe,gn]);d((()=>{if(!St||!xe)return;Cn();const e=Vt.current;(null==e?void 0:e.sessionId)===xe&&(H(Object.assign(Object.assign(Object.assign({},e),Nn()),{message:e.message,documentIds:e.documentIds,uploadedModelImages:e.uploadedModelImages,hasUploadedDocuments:e.hasUploadedDocuments,isHidden:e.isHidden})),Vt.current=null)}),[Cn,Nn,St,xe]);const En={currentUses:ee(null==jt?void 0:jt.currentUses),extraUses:ee(null==jt?void 0:jt.extraUses)},_n=Sn.scope?{currentUses:null!==(ue=ee(null===(ce=Sn.record)||void 0===ce?void 0:ce.currentUses))&&void 0!==ue?ue:0,extraUses:null!==(pe=ee(null===(me=Sn.record)||void 0===me?void 0:me.extraUses))&&void 0!==pe?pe:0}:{currentUses:0,extraUses:0},Tn=Z(jt,"type"),Un="guest"===Tn||!Tn&&Fe?_n:En;d((()=>{let e=!0;return t(void 0,void 0,void 0,(function*(){var t;if(On&&(null===(t=null==it?void 0:it.data)||void 0===t?void 0:t.workspaceId))try{const t=yield R.get(`/cost_per_run?workspaceId=${it.data.workspaceId}`,{withCredentials:!1});e&&Tt(1e4*(Number(t.data.costPerRun)||0))}catch(t){console.error("Failed to fetch average cost per run:",t),e&&Tt(0)}else e&&Tt(0)})),()=>{e=!1}}),[On,null===(fe=null==it?void 0:it.data)||void 0===fe?void 0:fe.workspaceId]);const An=(({currentUses:e,extraUses:t,limit:n,limitInterval:o})=>{const s=Number(null!=e?e:0),i=Number(null!=t?t:0);return n===J||i===J?J:"one_time"===o?Math.max(0,i-s):Math.max(0,n-s)+i})({currentUses:Un.currentUses,extraUses:Un.extraUses,limit:jn,limitInterval:wn}),Pn=An===J?J:Math.max(0,Math.ceil(An)),Dn=(({extraUses:e,limit:t,limitInterval:n})=>{const o=Number(null!=e?e:0);return t===J||o===J?J:"one_time"===n?Math.max(0,o):Math.max(0,t)+Math.max(0,o)})({extraUses:Un.extraUses,limit:jn,limitInterval:wn}),Ln=Dn===J?J:Math.ceil(.05*Dn),Rn=On?Math.ceil(5*_t):5,Mn=Ln===J?J:Math.max(Ln,Rn),Bn=c((()=>!!jt&&(!Ct&&(Pn!==J&&(!(Pn<=0)&&Pn<=Mn)))),[Ct,Mn,Pn,jt]),$n=Boolean(null==De?void 0:De.hideUpgradeOptions),Xn=!$n&&(null===(ge=null==De?void 0:De.upgrade)||void 0===ge?void 0:ge.isLinkToCustomURL)&&"string"==typeof De.upgrade.limitLink&&De.upgrade.limitLink.trim().length>0?De.upgrade.limitLink.trim():null,Kn=Xn&&"string"==typeof(null===(ve=null==De?void 0:De.upgrade)||void 0===ve?void 0:ve.limitCTA)&&De.upgrade.limitCTA.trim().length>0?De.upgrade.limitCTA:(null==Ee?void 0:Ee["pricing.upgrade"])||(null==Ee?void 0:Ee.upgrade)||"Upgrade",Vn=c((()=>{var e,t,n;return!!Ue&&(!!Se&&(!gt.isLoading&&(!((null!==(t=null===(e=gt.data)||void 0===e?void 0:e.messages.length)&&void 0!==t?t:0)>1)&&(!!(null===(n=Se.icebreakers)||void 0===n?void 0:n.length)&&(!Pe&&!vn)))))}),[Se,Ue,Pe,vn,gt.data,gt.isLoading]),Fn=c((()=>{if(Je||et)return!1;const e=pn&&Ze.length>0&&Ze.every((e=>"finished"===e.status));return!(!vt.trim()&&!e)&&Ze.every((e=>"finished"===e.status||e.isInsertedAsRaw))}),[pn,Je,et,vt,Ze]);u(ie,(()=>({onSubmit:Hn}))),d((()=>{Re(Vn)}),[Vn]),d((()=>{var e;if(i){const t=Array.from(Ge),n=null===(e=t[t.length-2].parts.find((e=>"text"===e.type)))||void 0===e?void 0:e.content;Hn(n,!0)}}),[i]),d((()=>{if(!$t.current||!oe)return;const e=new ResizeObserver((e=>{for(const t of e)oe(t.contentRect.height)}));return e.observe($t.current),()=>{e.disconnect()}}),[oe]),d((()=>{if(!Wt)return;const e=At.current?`${At.current} `:"";ht(`${e}${Ht}`)}),[Ht,Wt]),d((()=>{if(!Mt.current)return;(()=>{if(!Mt.current)return;let e=Mt.current.scrollHeight>52;vt.includes("\n")||Ze.length?e=!0:vt.trim()||(e=!1),yt(e)})()}),[vt,Ze]),d((()=>{const e=Mt.current,t=Bt.current;if(!e||!t||bt||vt.includes("\n"))return void It(!1);const n=window.getComputedStyle(e),o=`${n.fontStyle} ${n.fontVariant} ${n.fontWeight} ${n.fontSize} / ${n.lineHeight} ${n.fontFamily}`,s=document.createElement("span");Object.assign(s.style,{font:o,letterSpacing:n.letterSpacing,position:"absolute",visibility:"hidden",whiteSpace:"nowrap",top:"0",left:"0"}),s.textContent=vt||yn,document.body.appendChild(s);const i=s.offsetWidth;s.remove();const r=parseFloat(n.paddingLeft)||0,a=parseFloat(n.paddingRight)||0,l=e.clientWidth-r-a-t.offsetWidth;It(i>l)}),[vt,bt,yn]);const Hn=(e,n=!1)=>t(void 0,void 0,void 0,(function*(){var t,o,s,i,r,a;let l=null;try{if(Je||et)return;const d=Ze.filter((e=>"finished"===e.status&&!e.isInsertedAsRaw)),c=d.map((e=>e.documentId)).filter(Boolean),u=d.filter((e=>"image"===e.type)).map((e=>{const t=e.name.split(".").pop()||"";return{documentId:e.documentId,extension:t}})),m=null!=e?e:vt,p=null!==(o=null===(t=null==Se?void 0:Se.documentuploadtype)||void 0===t?void 0:t.startsWith("enduserupload"))&&void 0!==o&&o&&c.length>0;if(!m&&!p)return;Ye(""),st(""),Qe(null),ht(""),Le(!1),qe("fetching"),at(),dt();const f=null!==(i=null===(s=gt.data)||void 0===s?void 0:s.messages)&&void 0!==i?i:[],g=L(Ge,f),v=n?g.slice(0,g.length-1):g,h=(e=>e.reduce(((e,t)=>Math.max(e,t.id)),0)+1)(v),b=h+(n?0:1),y={id:b,role:"assistant",parts:[],documentIds:[]},x=[...v,...n?[]:[{id:h,role:"user",parts:[{type:"text",content:m,isVisible:!0}],documentIds:p?c:[]}],y];ze(x),dt(),p&&ot([]);const I=V(Oe),j="undefined"!=typeof crypto&&"randomUUID"in crypto?crypto.randomUUID():`submission-${Date.now()}-${Math.random().toString(36).slice(2)}`;l=j,Dt.current=j,Lt.current=null,Rt.current=[];const w=yield fetch(`${process.env.NEXT_PUBLIC_PICKAXE_API2_URL}/response/submit`,Object.assign({method:"POST",body:JSON.stringify(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({origin:be,pickaxeId:ye,sessionId:xe,submissionId:j,senderType:je,value:m},p&&{documentIds:c}),Ie&&{sender:Ie}),Ve&&{studioSessionToken:Ve}),!Ve&&!Ie&&{sender:K()}),kn&&{portalId:kn}),Oe&&{deploymentId:Oe}),I&&{metadata:I}),p&&u.length>0?{uploadedModelImages:u}:{})),headers:Object.assign(Object.assign({},(!process.env.NODE_ENV||"development"===process.env.NODE_ENV)&&Object.assign({},process.env.NEXT_PUBLIC_PICKAXE_SESSION_TOKEN&&{"x-pickaxe-session-token":process.env.NEXT_PUBLIC_PICKAXE_SESSION_TOKEN})),{"x-request-sent-at":(new Date).toISOString()})},mn&&{credentials:"include"})),O=yield w.json();if(!O.success){if(O.limitData){const e=new Error(O.error||O.message||(null==Ee?void 0:Ee["failed-to-start-generation"])||"Failed to start generation");throw e.limitData=O.limitData,e}if(bn(O))return;throw new Error(O.error||O.message||(null==Ee?void 0:Ee["failed-to-start-generation"])||"Failed to start generation")}const k=null!==(r=O.submissionId)&&void 0!==r?r:j;l=k,Dt.current=k;const S=()=>Lt.current===k;if(S())return;gn&&Ue&&xe&&Kt.current.add(xe);const C=Object.assign(Object.assign({},Nn()),{message:m,documentIds:p?c:[],uploadedModelImages:p?u:[],hasUploadedDocuments:p,isHidden:n,metadata:null!=I?I:null});St?(Cn(),H(C)):Vt.current=C,qe("streaming"),Xt.current=new AbortController;const E=[];let _=[...null!=ct?ct:[]],T=0,U=!1,A="";for(;!U;)try{const e=yield fetch(`${process.env.NEXT_PUBLIC_PICKAXE_API2_URL}/response/stream/${k}?index=${T}`,{signal:null===(a=Xt.current)||void 0===a?void 0:a.signal,headers:{"Cache-Control":"no-cache",Connection:"keep-alive"}});if(!e.body)throw new Error("No response body");const t=e.body.getReader();Pt.current=t;const n=new TextDecoder,o=N({onEvent:e=>{var t,n;if(S())U=!0;else if(e.event&&"ping"!==e.event&&T++,"stop"!==e.event){if("error"===e.event){const t=JSON.parse(e.data);if(t.limitData)return Qe(t.limitData),Ye(""),void(U=!0);const n=t.error||t.message||(null==Ee?void 0:Ee["something-went-wrong"])||"Something went wrong.";return bn(t)||Ye(n),void(U=!0)}if("delta"===e.event){const o=JSON.parse(e.data);if("data-error"===o.type&&se){const e=o.data.error;if("string"==typeof e){const t=/['"]type['"]\s*:\s*['"]unauthorized_smithery['"]/.test(e),n=/['"]type['"]\s*:\s*['"]unauthorized_composio['"]/.test(e);if(t){const t=e.match(/['"]qualifiedName['"]\s*:\s*['"]([^'"]+)['"]/),n=e.match(/['"]serverId['"]\s*:\s*['"]([^'"]+)['"]/),o=e.match(/['"]name['"]\s*:\s*['"]([^'"]+)['"]/);if(t&&t[1]&&n&&n[1]&&o&&o[1])throw U=!0,se({provider:"smithery",smitheryId:t[1],serverId:n[1],name:o[1]}),new Error("STOP_STREAM")}else if(n){const t=e.match(/['"]toolkitSlug['"]\s*:\s*['"]([^'"]+)['"]/),n=e.match(/['"]serverId['"]\s*:\s*['"]([^'"]+)['"]/),o=e.match(/['"]name['"]\s*:\s*['"]([^'"]+)['"]/);if(t&&t[1]&&n&&n[1]&&o&&o[1])throw U=!0,se({provider:"composio",toolkitSlug:t[1],serverId:n[1],name:o[1]}),new Error("STOP_STREAM")}}else if("object"==typeof e&&null!==e){const t=e;if("unauthorized_smithery"===t.type&&t.qualifiedName&&t.serverId&&t.name)throw U=!0,se({provider:"smithery",smitheryId:t.qualifiedName,serverId:t.serverId,name:t.name}),new Error("STOP_STREAM");if("unauthorized_composio"===t.type&&t.toolkitSlug&&t.serverId&&t.name)throw U=!0,se({provider:"composio",toolkitSlug:t.toolkitSlug,serverId:t.serverId,name:t.name}),new Error("STOP_STREAM")}}else if("text-start"===o.type)A="",E.push({type:"text",content:"",isVisible:null===(t=o.isVisible)||void 0===t||t});else if("text-delta"===o.type)A+=o.delta,E[E.length-1].content=A;else if("text-end"===o.type)A="";else if("reasoning-start"===o.type)A="",E.push({type:"reasoning",content:"",isVisible:null===(n=o.isVisible)||void 0===n||n});else if("reasoning-delta"===o.type)A+=o.delta,E[E.length-1].content=A;else if("reasoning-end"===o.type)A="";else if(o.type.startsWith("data-")){const e=o;E.push({type:e.type,content:JSON.stringify(e.data),isVisible:!0})}Rt.current=q(E);const s=q(E);ze((e=>{const t=e.findIndex((e=>e.id===b)),n=Object.assign(Object.assign({},y),{parts:s});return-1===t?[...e,n]:e.map(((e,o)=>o===t?n:e))}))}else if("artifact_created"===e.event){const t=JSON.parse(e.data);_=_.filter((e=>!(e.id===t.id&&e.version===t.version))),_.push(Object.assign(Object.assign({},t),{content:"",status:"streaming"})),mt([..._]),ut.startsWith("inline")||pt({id:t.id,version:t.version})}else if("artifact_updated"===e.event){const t=JSON.parse(e.data);_=_.filter((e=>!(e.id===t.id&&e.version===t.version))),_.push(Object.assign(Object.assign({},t),{content:"",status:"updating"})),mt(_),ut.startsWith("inline")||pt({id:t.id,version:t.version})}else if("artifact_rewrite"===e.event){const t=JSON.parse(e.data);_=_.filter((e=>!(e.id===t.id&&e.version===t.version))),_.push(Object.assign(Object.assign({},t),{content:"",status:"streaming"})),mt(_),ut.startsWith("inline")||pt({id:t.id,version:t.version})}else if("artifact_content"===e.event){const t=JSON.parse(e.data),n=t.token.replace(/\u200B/g,"");_=_.map((e=>e.id===t.id&&e.version===t.version?Object.assign(Object.assign({},e),{content:e.content+n,status:"streaming"}):e)),mt(_)}else if("artifact_finished"===e.event){const t=JSON.parse(e.data);mt(_.map((e=>e.id===t.id?Object.assign(Object.assign({},e),{status:"finished"}):e)))}else if("error"===e.event){const t=JSON.parse(e.data);if(t.limitData)return Qe(t.limitData),Ye(""),void(U=!0);const n=t.error||t.message||(null==Ee?void 0:Ee["something-went-wrong-try-again"])||"Something went wrong, please try again.";if(bn(t))return void(U=!0);Ye(n)}else"stop"===e.event&&(U=!0)}else U=!0}});for(;;){if(S()){U=!0,t.cancel().catch((()=>{}));break}const{value:e,done:s}=yield t.read();if(S()){U=!0,t.cancel().catch((()=>{}));break}if(s)break;o.feed(n.decode(e))}U||S()||(yield new Promise((e=>setTimeout(e,1e3))))}catch(e){if("STOP_STREAM"===e.message||Q(e)||S())return void(U=!0);console.warn("Stream connection lost, retrying...",e),yield new Promise((e=>setTimeout(e,1e3)))}null==Ke||Ke(xe)}catch(e){if(Q(e))return;if(e.limitData)Qe(e.limitData),Ye("");else{let t=D(e)||"";t&&!t.includes("Unexpected token 'A',")||(t=(null==Ee?void 0:Ee["high-traffic-try-again-later"])||"Oops! We're experiencing high traffic at the moment. Please try again later."),bn(t)||Ye(t)}}finally{const e=!l||Dt.current===l;dt(),e&&(qe("idle"),lt(),Pt.current=null),l&&e&&(Dt.current=null,Rt.current=[]),yield In()}}));return hn?null:n("div",Object.assign({className:B("flex w-full flex-shrink-0 flex-col items-center",!vn&&"px-4 pb-8"),dir:Ae?"rtl":"ltr"},{children:o("div",Object.assign({className:"flex w-full max-w-[800px] flex-col"},{children:[o("div",Object.assign({ref:$t,className:B("relative flex flex-col w-full justify-end gap-y-3 py-[3px]","block"===Ne.formFieldStyle&&"shadow"),style:Object.assign(Object.assign({},ln),{maxHeight:`${Ft}px`,overflowY:"auto"})},{children:[Bn&&o("div",Object.assign({className:"sticky top-0 z-10 flex w-full items-center justify-between border-b px-4 py-2.5 shadow-sm backdrop-blur-md",style:{backgroundColor:ln.backgroundColor?`${ln.backgroundColor}E6`:void 0,borderColor:Ce.text+"20",color:Ce.text,borderTopRightRadius:Ne.cornerRadius+"px",borderTopLeftRadius:Ne.cornerRadius+"px"}},{children:[n("div",Object.assign({className:"flex items-center gap-2 text-sm font-medium"},{children:o("span",{children:[Pn.toLocaleString()," ",On?(null==Ee?void 0:Ee.credits)||"Credits":(null==Ee?void 0:Ee.uses)||"Uses"," ",(null==Ee?void 0:Ee.remaining)||"remaining"]})})),o("div",Object.assign({className:"flex items-center gap-3"},{children:[!$n&&n("button",Object.assign({className:"rounded-md px-3 py-1.5 text-xs font-semibold transition-opacity hover:opacity-90",style:{backgroundColor:Ce.accent,color:Ce.accentText},onClick:e=>{if(e.preventDefault(),e.stopPropagation(),Xn)return void window.open(Xn,"_blank","noopener,noreferrer");const t=$({baseUrl:Ot,accessGroupId:null==De?void 0:De.accessGroupId,redirectUrl:document.URL});t&&(X()?window.open(t):location.href=t)}},{children:Kn})),n("button",Object.assign({className:"flex h-6 w-6 items-center justify-center rounded-full opacity-60 transition-opacity hover:opacity-100",onClick:()=>Et(!0)},{children:n("svg",Object.assign({xmlns:"http://www.w3.org/2000/svg",fill:"none",viewBox:"0 0 24 24",strokeWidth:2,stroke:"currentColor",className:"h-4 w-4"},{children:n("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M6 18L18 6M6 6l12 12"})}))}))]}))]})),!Je&&Ze.length>0&&n(U,{className:"p-4 pb-0",isDisabled:Je}),o("div",Object.assign({className:"relative flex w-full flex-col"},{children:[Wt&&o("div",Object.assign({className:"absolute left-4 top-1/2 flex -translate-y-1/2 select-none items-center gap-x-2"},{children:[n("span",{className:"h-2 w-2 animate-pulse rounded-full bg-c-secondary",style:{backgroundColor:null!==(he=Ce.accent)&&void 0!==he?he:"#ff0000"}}),n("span",Object.assign({className:"text-sm text-c-secondary font-semilight",style:{color:Ce.text+"90"}},{children:(null==Ee?void 0:Ee.listening)||"Listening..."}))]})),n(A,Object.assign({ref:Mt,className:B(an.i1,"py-3.5 max-h-60 px-4 w-full border-transparent bg-transparent",!vt.trim()&&!vt.includes("\n")&&"overflow-hidden text-ellipsis whitespace-nowrap placeholder:whitespace-normal placeholder:overflow-visible",Ae?"text-right":"text-left",xn&&"mb-12",Wt&&"text-transparent"),value:vt,placeholder:yn,onChange:e=>{ht(e)},onKeyDown:e=>{Te||rt||"Enter"===e.key&&(e.shiftKey||(e.preventDefault(),et||Je||Hn()))},onPaste:e=>t(void 0,void 0,void 0,(function*(){const t=Array.from(e.clipboardData.files||[]);if(t.length>0){if(!pn)return;e.preventDefault(),Le(!1),yield nt(t)}}))},Y&&{onFocus:Y},ne&&{onBlur:ne},{dir:Ae?"rtl":"ltr"})),n("div",Object.assign({ref:Bt,className:B("flex items-center gap-2 absolute right-0 z-2 transition-all duration-200 ease-in-out",xn?"bottom-0 mb-2.5":"top-1/2 -translate-y-1/2"),style:Object.assign(Object.assign({},!xn&&ln.backgroundColor&&{backgroundColor:ln.backgroundColor}),{borderTopRightRadius:Ne.cornerRadius+"px",borderBottomRightRadius:Ne.cornerRadius+"px"})},{children:Je?n("button",Object.assign({className:"flex h-8 w-8 items-center mr-2 justify-center rounded-full outline-none transition-colors duration-200 ease-in-out",onClick:()=>{const e=Dt.current;e&&(Lt.current=e,(e=>{t(void 0,void 0,void 0,(function*(){if(!(e=null!=e?e:Dt.current))return;const t=q(Rt.current);try{yield fetch(`${process.env.NEXT_PUBLIC_PICKAXE_API2_URL}/response/cancel/${e}`,Object.assign({method:"POST",headers:Object.assign(Object.assign({"Content-Type":"application/json"},(!process.env.NODE_ENV||"development"===process.env.NODE_ENV)&&Object.assign({},process.env.NEXT_PUBLIC_PICKAXE_SESSION_TOKEN&&{"x-pickaxe-session-token":process.env.NEXT_PUBLIC_PICKAXE_SESSION_TOKEN})),{"x-request-sent-at":(new Date).toISOString()}),body:JSON.stringify({outputMessageParts:t})},mn&&{credentials:"include"}))}catch(e){console.warn("Failed to cancel submission",e)}}))})(e)),Xt.current&&(Xt.current.abort(),Xt.current=null),Pt.current&&(Pt.current.cancel().catch((()=>{})),Pt.current=null),qe("idle")},style:{backgroundColor:Ce.accent,color:Ce.accentText}},{children:n(T,{className:"h-4 w-4 shrink-0"})})):Wt?n("button",Object.assign({className:"flex h-8 w-8 items-center mr-2 justify-center rounded-full outline-none transition-colors duration-200 ease-in-out",onClick:qt,style:{backgroundColor:Ce.accent,color:Ce.accentText}},{children:n(T,{className:"h-4 w-4 shrink-0"})})):o(s,{children:[pn&&o("button",Object.assign({className:"flex h-8 w-8 items-center justify-center rounded-full outline-none transition-colors duration-200 ease-in-out disabled:cursor-default",style:{backgroundColor:tn?Ce.accent+"10":void 0,color:tn?Ce.accent:Ce.accent+"80"},disabled:et||Je,onClick:()=>{var e;return null===(e=Ut.current)||void 0===e?void 0:e.click()}},nn,{children:[n("input",{id:"file-upload",ref:Ut,type:"file",accept:[...O,...k,...S].join(", "),multiple:!0,hidden:!0,className:"hidden",onChange:e=>t(void 0,void 0,void 0,(function*(){Le(!1),yield nt(Array.from(e.target.files||[])),e.target.value=""}))}),n(C,{className:"h-6 w-6 shrink-0"})]})),fn&&n("button",Object.assign({className:"disabled:cursor-default flex h-8 w-8 items-center justify-center rounded-full outline-none transition-colors duration-200 ease-in-out",style:{backgroundColor:Wt?Ce.accent:sn?Ce.accent+"10":void 0,color:Wt?Ce.accentText:sn?Ce.accent:Ce.accent+"80"},disabled:et||Je||Gt,onClick:()=>{Wt?qt():(At.current=vt,zt(_e||"en-US"))}},rn,{children:n(_,{className:"h-5 w-5 shrink-0"})})),n("button",Object.assign({className:"flex h-8 w-8 items-center mr-2 justify-center rounded-full outline-none transition-colors duration-200 ease-in-out disabled:cursor-default",style:{backgroundColor:Yt||Fn?Ce.accent:Ce.accent+"10",color:Yt||Fn?Ce.accentText:Ce.accent+"80"},disabled:!Fn,onClick:()=>Hn()},Zt,{children:n(E,{className:B("h-6 w-6 shrink-0",Ae&&"scale-x-[-1] transform")})}))]})}))]}))]})),tt&&n(P,{error:tt,className:"mt-3"})]}))}))}));ne.displayName="Input";export{ne as default};
1
+ import{__rest as e,__awaiter as t}from"../../../_virtual/_tslib.js";import{jsx as n,jsxs as o,Fragment as s}from"react/jsx-runtime";import{forwardRef as i,useState as r,useRef as a,useCallback as l,useEffect as d,useMemo as c,useImperativeHandle as u}from"react";import{usePickaxeContext as m}from"../../../hooks/pickaxe/usePickaxeContext.js";import{useResponseContext as p}from"../../../hooks/pickaxe/useResponseContext.js";import{useStyleInput as f}from"../../../hooks/studio/useStyleInput.js";import{useStyleFontSize as g}from"../../../hooks/studio/useStyleFontSize.js";import{useConversation as v}from"../../../hooks/pickaxe/useConversation.js";import{useDimensionContext as h}from"../../../hooks/pickaxe/useDimensionContext.js";import{useAuthContext as b}from"../Addons/Auth/hooks/useAuthContext.js";import{useDocument as y}from"../Addons/Document/hooks/useDocument.js";import{useScroll as x}from"../Addons/Scroll/hooks/useScroll.js";import{useArtifactContext as I}from"../Addons/Artifact/hooks/useArtifactContext.js";import{useHover as j}from"../../../hooks/core/useHover.js";import{useMediaQuery as w}from"../../../hooks/core/useMediaQuery.js";import{allowedFileMimeTypes as O,allowedImageMimeTypes as k,additionalAllowedFileExtensions as S}from"../../../common/documents.js";import{createParser as N}from"eventsource-parser";import C from"../../Icons/attach-vertical.svg.js";import E from"../../Icons/arrow-right.svg.js";import _ from"../../Icons/microphone.svg.js";import T from"../../Icons/stop.svg.js";import U from"../Addons/Document/List.js";import A from"../../Core/Textarea.js";import P from"../../Core/ErrorAlert.js";import D from"../../../common/error.js";import{getUnpersistedMemoryMessages as L}from"../../../common/chatMessages.js";import{pickaxeApi2 as R}from"../../../common/api/pickaxe.js";import{getValidationFailure as M}from"../../../common/validation.js";import B from"../../../common/cn.js";import{buildUpgradeUrl as $,isInIframe as X,initializeEmbedUserId as K}from"../../../common/utils.js";import{getPickaxeConfigMetadata as V}from"../../../common/pickaxeConfig.js";import{fireDeploymentSessionInitializedWebhook as F,fireDeploymentFirstMessageSubmittedWebhook as H}from"../../../common/deploymentWebhooks.js";import{useStudio as W}from"../../../hooks/studio/useStudio.js";import{useSpeechToText as G}from"../../../hooks/pickaxe/useSpeechToText.js";import{STUDIO_INFINITY_VALUE as J}from"../common/PickaxeCommon.js";const z=e=>"string"==typeof e&&e.trim().length>0,q=e=>e.map((e=>Object.assign({},e))),Q=e=>e instanceof Error&&("AbortError"===e.name||"BodyStreamBuffer was aborted"===e.message),Y=(e,t)=>{if(e&&"object"==typeof e)return e[t]},Z=(e,t)=>{const n=Y(e,t);return z(n)?n:null},ee=e=>{const t=Number(e);return Number.isFinite(t)?t:void 0},te=({studioUser:e,deploymentId:t,portalId:n})=>{var o,s;const i=Array.isArray(Y(e,"uses"))?Y(e,"uses"):[],r=(({deploymentId:e,portalId:t})=>z(e)?{type:"deployment",id:e}:z(t)?{type:"portal",id:t}:null)({deploymentId:t,portalId:n});if(!r)return{scope:r,record:null};const a=null!==(s=null!==(o=i.find((e=>e.id===r.id&&e.type===r.type)))&&void 0!==o?o:i.find((e=>e.id===r.id)))&&void 0!==s?s:null;return{scope:r,record:a}},ne=i((({resubmitPrompt:i,onFocus:Y,onBlur:ne,onInputHeightChange:oe,initSmitheryAuthData:se},ie)=>{var re,ae,le,de,ce,ue,me,pe,fe,ge,ve,he;const{origin:be,pickaxeId:ye,sessionId:xe,sender:Ie,senderType:je,portalId:we,deploymentId:Oe,deploymentType:ke,pickaxe:Se,styles:Ne,colors:Ce,translations:Ee,locale:_e,forceMobile:Te,isNewChat:Ue,isRtl:Ae,isShowFeedbackMessage:Pe,accessGroup:De,setIsNewChat:Le,setIsShowIceBreaker:Re,setValidationStatus:Me,setValidationUpgradeGroups:Be,setValidationUpgradeUrl:$e,setAccessGroup:Xe,onGenerateComplete:Ke}=m(),{token:Ve,isLoggedOut:Fe,isSent:He,isPricingAuth:We}=b(),{messages:Ge,isGenerating:Je,setMessages:ze,setStatus:qe,setLimitData:Qe,setError:Ye}=p(),{documents:Ze,isUploading:et,documentError:tt,onFileUpload:nt,setDocuments:ot,setDocumentError:st}=y(),{studio:it}=W(),[rt]=w("(max-width: 480px)"),{scrollStartSession:at,scrollEndSession:lt,scrollToBottom:dt}=x({auto:!0,smooth:!(Te||rt)}),{artifacts:ct,currentPopupType:ut,setArtifacts:mt,setCurrentArtifact:pt}=I(),{height:ft}=h(),gt=v(),[vt,ht]=r(""),[bt,yt]=r(!1),[xt,It]=r(!1),[jt,wt]=r(null),[Ot,kt]=r(null),[St,Nt]=r(!1),[Ct,Et]=r(!1),[_t,Tt]=r(0),Ut=a(null),At=a(""),Pt=a(null),Dt=a(null),Lt=a(null),Rt=a([]),Mt=a(null),Bt=a(null),$t=a(null),Xt=a(null),Kt=a(new Set),Vt=a(null),Ft=Math.max(.4*ft,100),{speechTranscript:Ht,isSpeechListening:Wt,isSpeechProcessing:Gt,isSpeechSupported:Jt,onStartListening:zt,onStopListening:qt}=G(),Qt=j(),{isHover:Yt}=Qt,Zt=e(Qt,["isHover"]),en=j(),{isHover:tn}=en,nn=e(en,["isHover"]),on=j(),{isHover:sn}=on,rn=e(on,["isHover"]),an=g(),ln=f(),dn="undefined"!=typeof window?window.location.hostname:"",cn="undefined"!=typeof window?window.location.href:"",un="undefined"!=typeof window&&window.self!==window.top,mn=dn.includes("pickaxe.co")&&!cn.includes("https://studio.pickaxe.co/_embed")&&!un,pn=null!==(ae=null===(re=null==Se?void 0:Se.documentuploadtype)||void 0===re?void 0:re.startsWith("enduserupload"))&&void 0!==ae&&ae,fn=Jt&&(null==Se?void 0:Se.enablevoicetotext),gn=z(Oe),vn="chat-input"===ke&&Ue&&!He,hn="chat-input"===ke&&We&&Fe&&He,bn=l((e=>{const t=M(e);return!!t&&(Ye(""),Qe(null),Me(t.status),Xe(t.accessGroup),Be(t.upgradeGroups),$e(t.upgradeUrl),!0)}),[Ye,Qe,Me,Be,$e,Xe]),yn=null!==(le=null==Se?void 0:Se.placeholdertext)&&void 0!==le?le:Ae?"بماذا تريد أن تتحدث؟":(null==Ee?void 0:Ee["what-do-you-want-to-talk-about"])||"What do you want to talk about?",xn=bt||xt,In=l((()=>t(void 0,void 0,void 0,(function*(){Nt(!1);try{const e=yield fetch(`${process.env.NEXT_PUBLIC_PICKAXE_API2_URL}/user`,Object.assign(Object.assign({method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(Object.assign({studioId:null==Se?void 0:Se.studioid},Ve?{studioSessionToken:Ve}:Ie?{sender:Ie}:{sender:K()}))},(!process.env.NODE_ENV||"development"===process.env.NODE_ENV)&&Object.assign({},process.env.NEXT_PUBLIC_PICKAXE_SESSION_TOKEN&&{headers:{"Content-Type":"application/json","x-pickaxe-session-token":process.env.NEXT_PUBLIC_PICKAXE_SESSION_TOKEN}})),mn&&{credentials:"include"})),t=yield e.json();(null==t?void 0:t.studioUser)&&(wt(t.studioUser),kt(t.url))}catch(e){console.error("Failed to fetch studio user:",e)}finally{Nt(!0)}}))),[mn,null==Se?void 0:Se.studioid,Ie,Ve]);d((()=>{In()}),[In]);const jn=Number(null!==(de=null==De?void 0:De.limit)&&void 0!==de?de:0),wn="string"==typeof(null==De?void 0:De.limitInterval)?De.limitInterval:null,On=!!(null==it?void 0:it.data.usage)&&it.data.usage.isCredits,kn=c((()=>{var e,t,n,o,s;return null!==(s=null!==(o=null!==(n=null!==(t=null!==(e=null!=we?we:Z(jt,"portalId"))&&void 0!==e?e:Z(jt,"portalid"))&&void 0!==t?t:Z(De,"portalId"))&&void 0!==n?n:Z(De,"portalid"))&&void 0!==o?o:Z(Se,"portalId"))&&void 0!==s?s:Z(Se,"portalid")}),[De,we,Se,jt]),Sn=c((()=>te({studioUser:jt,deploymentId:Oe,portalId:kn})),[Oe,kn,jt]);d((()=>{gn&&Ue&&xe&&Kt.current.add(xe)}),[Ue,xe,gn]);const Nn=l((()=>{var e,t,n;return{studioId:null==Se?void 0:Se.studioid,userEmail:Z(jt,"email"),userId:null!==(e=Z(jt,"userId"))&&void 0!==e?e:Z(jt,"userid"),sessionId:xe,deploymentId:Oe,deploymentType:ke,portalId:kn,accessGroupId:null!==(t=null==De?void 0:De.accessGroupId)&&void 0!==t?t:null,pickaxeId:ye,sender:Ie,senderType:je,origin:be,metadata:null!==(n=V(Oe))&&void 0!==n?n:null}}),[null==De?void 0:De.accessGroupId,Oe,ke,be,null==Se?void 0:Se.studioid,ye,kn,Ie,je,xe,jt]),Cn=l((()=>!!(gn&&St&&xe)&&(!!Kt.current.has(xe)&&(F(Nn()),Kt.current.delete(xe),!0))),[Nn,St,xe,gn]);d((()=>{if(!St||!xe)return;Cn();const e=Vt.current;(null==e?void 0:e.sessionId)===xe&&(H(Object.assign(Object.assign(Object.assign({},e),Nn()),{message:e.message,documentIds:e.documentIds,uploadedModelImages:e.uploadedModelImages,hasUploadedDocuments:e.hasUploadedDocuments,isHidden:e.isHidden})),Vt.current=null)}),[Cn,Nn,St,xe]);const En={currentUses:ee(null==jt?void 0:jt.currentUses),extraUses:ee(null==jt?void 0:jt.extraUses)},_n=Sn.scope?{currentUses:null!==(ue=ee(null===(ce=Sn.record)||void 0===ce?void 0:ce.currentUses))&&void 0!==ue?ue:0,extraUses:null!==(pe=ee(null===(me=Sn.record)||void 0===me?void 0:me.extraUses))&&void 0!==pe?pe:0}:{currentUses:0,extraUses:0},Tn=Z(jt,"type"),Un="guest"===Tn||!Tn&&Fe?_n:En;d((()=>{let e=!0;return t(void 0,void 0,void 0,(function*(){var t;if(On&&(null===(t=null==it?void 0:it.data)||void 0===t?void 0:t.workspaceId))try{const t=yield R.get(`/cost_per_run?workspaceId=${it.data.workspaceId}`,{withCredentials:!1});e&&Tt(1e4*(Number(t.data.costPerRun)||0))}catch(t){console.error("Failed to fetch average cost per run:",t),e&&Tt(0)}else e&&Tt(0)})),()=>{e=!1}}),[On,null===(fe=null==it?void 0:it.data)||void 0===fe?void 0:fe.workspaceId]);const An=(({currentUses:e,extraUses:t,limit:n,limitInterval:o})=>{const s=Number(null!=e?e:0),i=Number(null!=t?t:0);return n===J||i===J?J:"one_time"===o?Math.max(0,i-s):Math.max(0,n-s)+i})({currentUses:Un.currentUses,extraUses:Un.extraUses,limit:jn,limitInterval:wn}),Pn=An===J?J:Math.max(0,Math.ceil(An)),Dn=(({extraUses:e,limit:t,limitInterval:n})=>{const o=Number(null!=e?e:0);return t===J||o===J?J:"one_time"===n?Math.max(0,o):Math.max(0,t)+Math.max(0,o)})({extraUses:Un.extraUses,limit:jn,limitInterval:wn}),Ln=Dn===J?J:Math.ceil(.05*Dn),Rn=On?Math.ceil(5*_t):5,Mn=Ln===J?J:Math.max(Ln,Rn),Bn=c((()=>!!jt&&(!Ct&&(Pn!==J&&(!(Pn<=0)&&Pn<=Mn)))),[Ct,Mn,Pn,jt]),$n=Boolean(null==De?void 0:De.hideUpgradeOptions),Xn=!$n&&(null===(ge=null==De?void 0:De.upgrade)||void 0===ge?void 0:ge.isLinkToCustomURL)&&"string"==typeof De.upgrade.limitLink&&De.upgrade.limitLink.trim().length>0?De.upgrade.limitLink.trim():null,Kn=Xn&&"string"==typeof(null===(ve=null==De?void 0:De.upgrade)||void 0===ve?void 0:ve.limitCTA)&&De.upgrade.limitCTA.trim().length>0?De.upgrade.limitCTA:(null==Ee?void 0:Ee["pricing.upgrade"])||(null==Ee?void 0:Ee.upgrade)||"Upgrade",Vn=c((()=>{var e,t,n;return!!Ue&&(!!Se&&(!gt.isLoading&&(!((null!==(t=null===(e=gt.data)||void 0===e?void 0:e.messages.length)&&void 0!==t?t:0)>1)&&(!!(null===(n=Se.icebreakers)||void 0===n?void 0:n.length)&&(!Pe&&!vn)))))}),[Se,Ue,Pe,vn,gt.data,gt.isLoading]),Fn=c((()=>{if(Je||et)return!1;const e=pn&&Ze.length>0&&Ze.every((e=>"finished"===e.status));return!(!vt.trim()&&!e)&&Ze.every((e=>"finished"===e.status||e.isInsertedAsRaw))}),[pn,Je,et,vt,Ze]);u(ie,(()=>({onSubmit:Hn}))),d((()=>{Re(Vn)}),[Vn]),d((()=>{var e;if(i){const t=Array.from(Ge),n=null===(e=t[t.length-2].parts.find((e=>"text"===e.type)))||void 0===e?void 0:e.content;Hn(n,!0)}}),[i]),d((()=>{if(!$t.current||!oe)return;const e=new ResizeObserver((e=>{for(const t of e)oe(t.contentRect.height)}));return e.observe($t.current),()=>{e.disconnect()}}),[oe]),d((()=>{if(!Wt)return;const e=At.current?`${At.current} `:"";ht(`${e}${Ht}`)}),[Ht,Wt]),d((()=>{if(!Mt.current)return;(()=>{if(!Mt.current)return;let e=Mt.current.scrollHeight>52;vt.includes("\n")||Ze.length?e=!0:vt.trim()||(e=!1),yt(e)})()}),[vt,Ze]),d((()=>{const e=Mt.current,t=Bt.current;if(!e||!t||bt||vt.includes("\n"))return void It(!1);const n=window.getComputedStyle(e),o=`${n.fontStyle} ${n.fontVariant} ${n.fontWeight} ${n.fontSize} / ${n.lineHeight} ${n.fontFamily}`,s=document.createElement("span");Object.assign(s.style,{font:o,letterSpacing:n.letterSpacing,position:"absolute",visibility:"hidden",whiteSpace:"nowrap",top:"0",left:"0"}),s.textContent=vt||yn,document.body.appendChild(s);const i=s.offsetWidth;s.remove();const r=parseFloat(n.paddingLeft)||0,a=parseFloat(n.paddingRight)||0,l=e.clientWidth-r-a-t.offsetWidth;It(i>l)}),[vt,bt,yn]);const Hn=(e,n=!1)=>t(void 0,void 0,void 0,(function*(){var t,o,s,i,r,a;let l=null;try{if(Je||et)return;const d=Ze.filter((e=>"finished"===e.status&&!e.isInsertedAsRaw)),c=d.map((e=>e.documentId)).filter(Boolean),u=d.filter((e=>"image"===e.type)).map((e=>{const t=e.name.split(".").pop()||"";return{documentId:e.documentId,extension:t}})),m=null!=e?e:vt,p=null!==(o=null===(t=null==Se?void 0:Se.documentuploadtype)||void 0===t?void 0:t.startsWith("enduserupload"))&&void 0!==o&&o&&c.length>0;if(!m&&!p)return;Ye(""),st(""),Qe(null),ht(""),Le(!1),qe("fetching"),at(),dt();const f=null!==(i=null===(s=gt.data)||void 0===s?void 0:s.messages)&&void 0!==i?i:[],g=L(Ge,f),v=n?g.slice(0,g.length-1):g,h=(e=>e.reduce(((e,t)=>Math.max(e,t.id)),0)+1)(v),b=h+(n?0:1),y={id:b,role:"assistant",parts:[],documentIds:[]},x=[...v,...n?[]:[{id:h,role:"user",parts:[{type:"text",content:m,isVisible:!0}],documentIds:p?c:[]}],y];ze(x),dt(),p&&ot([]);const I=V(Oe),j="undefined"!=typeof crypto&&"randomUUID"in crypto?crypto.randomUUID():`submission-${Date.now()}-${Math.random().toString(36).slice(2)}`;l=j,Dt.current=j,Lt.current=null,Rt.current=[];const w=yield fetch(`${process.env.NEXT_PUBLIC_PICKAXE_API2_URL}/response/submit`,Object.assign({method:"POST",body:JSON.stringify(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({origin:be,pickaxeId:ye,sessionId:xe,submissionId:j,senderType:je,value:m},p&&{documentIds:c}),Ie&&{sender:Ie}),Ve&&{studioSessionToken:Ve}),!Ve&&!Ie&&{sender:K()}),kn&&{portalId:kn}),Oe&&{deploymentId:Oe}),I&&{metadata:I}),p&&u.length>0?{uploadedModelImages:u}:{})),headers:Object.assign(Object.assign({},(!process.env.NODE_ENV||"development"===process.env.NODE_ENV)&&Object.assign({},process.env.NEXT_PUBLIC_PICKAXE_SESSION_TOKEN&&{"x-pickaxe-session-token":process.env.NEXT_PUBLIC_PICKAXE_SESSION_TOKEN})),{"x-request-sent-at":(new Date).toISOString()})},mn&&{credentials:"include"})),O=yield w.json();if(!O.success){if(O.limitData){const e=new Error(O.error||O.message||(null==Ee?void 0:Ee["failed-to-start-generation"])||"Failed to start generation");throw e.limitData=O.limitData,e}if(bn(O))return;throw new Error(O.error||O.message||(null==Ee?void 0:Ee["failed-to-start-generation"])||"Failed to start generation")}const k=null!==(r=O.submissionId)&&void 0!==r?r:j;l=k,Dt.current=k;const S=()=>Lt.current===k;if(S())return;gn&&Ue&&xe&&Kt.current.add(xe);const C=Object.assign(Object.assign({},Nn()),{message:m,documentIds:p?c:[],uploadedModelImages:p?u:[],hasUploadedDocuments:p,isHidden:n,metadata:null!=I?I:null});St?(Cn(),H(C)):Vt.current=C,qe("streaming"),Xt.current=new AbortController;const E=[];let _=[...null!=ct?ct:[]],T=0,U=!1,A="";for(;!U;)try{const e=yield fetch(`${process.env.NEXT_PUBLIC_PICKAXE_API2_URL}/response/stream/${k}?index=${T}`,{signal:null===(a=Xt.current)||void 0===a?void 0:a.signal,headers:{"Cache-Control":"no-cache",Connection:"keep-alive"}});if(!e.body)throw new Error("No response body");const t=e.body.getReader();Pt.current=t;const n=new TextDecoder,o=N({onEvent:e=>{var t,n;if(S())U=!0;else if(e.event&&"ping"!==e.event&&T++,"stop"!==e.event){if("error"===e.event){const t=JSON.parse(e.data);if(t.limitData)return Qe(t.limitData),Ye(""),void(U=!0);const n=t.error||t.message||(null==Ee?void 0:Ee["something-went-wrong"])||"Something went wrong.";return bn(t)||Ye(n),void(U=!0)}if("delta"===e.event){const o=JSON.parse(e.data);if("data-error"===o.type&&se){const e=o.data.error;if("string"==typeof e){const t=/['"]type['"]\s*:\s*['"]unauthorized_smithery['"]/.test(e),n=/['"]type['"]\s*:\s*['"]unauthorized_composio['"]/.test(e);if(t){const t=e.match(/['"]qualifiedName['"]\s*:\s*['"]([^'"]+)['"]/),n=e.match(/['"]serverId['"]\s*:\s*['"]([^'"]+)['"]/),o=e.match(/['"]name['"]\s*:\s*['"]([^'"]+)['"]/);if(t&&t[1]&&n&&n[1]&&o&&o[1])throw U=!0,se({provider:"smithery",smitheryId:t[1],serverId:n[1],name:o[1]}),new Error("STOP_STREAM")}else if(n){const t=e.match(/['"]toolkitSlug['"]\s*:\s*['"]([^'"]+)['"]/),n=e.match(/['"]serverId['"]\s*:\s*['"]([^'"]+)['"]/),o=e.match(/['"]name['"]\s*:\s*['"]([^'"]+)['"]/);if(t&&t[1]&&n&&n[1]&&o&&o[1])throw U=!0,se({provider:"composio",toolkitSlug:t[1],serverId:n[1],name:o[1]}),new Error("STOP_STREAM")}}else if("object"==typeof e&&null!==e){const t=e;if("unauthorized_smithery"===t.type&&t.qualifiedName&&t.serverId&&t.name)throw U=!0,se({provider:"smithery",smitheryId:t.qualifiedName,serverId:t.serverId,name:t.name}),new Error("STOP_STREAM");if("unauthorized_composio"===t.type&&t.toolkitSlug&&t.serverId&&t.name)throw U=!0,se({provider:"composio",toolkitSlug:t.toolkitSlug,serverId:t.serverId,name:t.name}),new Error("STOP_STREAM")}}else if("text-start"===o.type)A="",E.push({type:"text",content:"",isVisible:null===(t=o.isVisible)||void 0===t||t});else if("text-delta"===o.type)A+=o.delta,E[E.length-1].content=A;else if("text-end"===o.type)A="";else if("reasoning-start"===o.type)A="",E.push({type:"reasoning",content:"",isVisible:null===(n=o.isVisible)||void 0===n||n});else if("reasoning-delta"===o.type)A+=o.delta,E[E.length-1].content=A;else if("reasoning-end"===o.type)A="";else if(o.type.startsWith("data-")){const e=o;E.push({type:e.type,content:JSON.stringify(e.data),isVisible:!0})}Rt.current=q(E);const s=q(E);ze((e=>{const t=e.findIndex((e=>e.id===b)),n=Object.assign(Object.assign({},y),{parts:s});return-1===t?[...e,n]:e.map(((e,o)=>o===t?n:e))}))}else if("artifact_created"===e.event){const t=JSON.parse(e.data);_=_.filter((e=>!(e.id===t.id&&e.version===t.version))),_.push(Object.assign(Object.assign({},t),{content:"",status:"streaming"})),mt([..._]),ut.startsWith("inline")||pt({id:t.id,version:t.version})}else if("artifact_updated"===e.event){const t=JSON.parse(e.data);_=_.filter((e=>!(e.id===t.id&&e.version===t.version))),_.push(Object.assign(Object.assign({},t),{content:"",status:"updating"})),mt(_),ut.startsWith("inline")||pt({id:t.id,version:t.version})}else if("artifact_rewrite"===e.event){const t=JSON.parse(e.data);_=_.filter((e=>!(e.id===t.id&&e.version===t.version))),_.push(Object.assign(Object.assign({},t),{content:"",status:"streaming"})),mt(_),ut.startsWith("inline")||pt({id:t.id,version:t.version})}else if("artifact_content"===e.event){const t=JSON.parse(e.data),n=t.token.replace(/\u200B/g,"");_=_.map((e=>e.id===t.id&&e.version===t.version?Object.assign(Object.assign({},e),{content:e.content+n,status:"streaming"}):e)),mt(_)}else if("artifact_finished"===e.event){const t=JSON.parse(e.data);mt(_.map((e=>e.id===t.id?Object.assign(Object.assign({},e),{status:"finished"}):e)))}else if("error"===e.event){const t=JSON.parse(e.data);if(t.limitData)return Qe(t.limitData),Ye(""),void(U=!0);const n=t.error||t.message||(null==Ee?void 0:Ee["something-went-wrong-try-again"])||"Something went wrong, please try again.";if(bn(t))return void(U=!0);Ye(n)}else"stop"===e.event&&(U=!0)}else U=!0}});for(;;){if(S()){U=!0,t.cancel().catch((()=>{}));break}const{value:e,done:s}=yield t.read();if(S()){U=!0,t.cancel().catch((()=>{}));break}if(s)break;o.feed(n.decode(e))}U||S()||(yield new Promise((e=>setTimeout(e,1e3))))}catch(e){if("STOP_STREAM"===e.message||Q(e)||S())return void(U=!0);console.warn("Stream connection lost, retrying...",e),yield new Promise((e=>setTimeout(e,1e3)))}null==Ke||Ke(xe)}catch(e){if(Q(e))return;if(e.limitData)Qe(e.limitData),Ye("");else{let t=D(e)||"";t&&!t.includes("Unexpected token 'A',")||(t=(null==Ee?void 0:Ee["high-traffic-try-again-later"])||"Oops! We're experiencing high traffic at the moment. Please try again later."),bn(t)||Ye(t)}}finally{const e=!l||Dt.current===l;dt(),e&&(qe("idle"),lt(),Pt.current=null),l&&e&&(Dt.current=null,Rt.current=[]),yield In()}}));return hn?null:n("div",Object.assign({className:B("flex w-full flex-shrink-0 flex-col items-center",!vn&&"px-4 pb-8"),dir:Ae?"rtl":"ltr"},{children:o("div",Object.assign({className:"flex w-full max-w-[800px] flex-col"},{children:[o("div",Object.assign({ref:$t,className:B("relative flex flex-col w-full justify-end gap-y-3 py-[3px]","block"===Ne.formFieldStyle&&"shadow"),style:Object.assign(Object.assign({},ln),{maxHeight:`${Ft}px`,overflowY:"auto"})},{children:[Bn&&o("div",Object.assign({className:"sticky top-0 z-10 flex w-full items-center justify-between border-b px-4 py-2.5 shadow-sm backdrop-blur-md",style:{backgroundColor:ln.backgroundColor?`${ln.backgroundColor}E6`:void 0,borderColor:Ce.text+"20",color:Ce.text,borderTopRightRadius:Ne.cornerRadius+"px",borderTopLeftRadius:Ne.cornerRadius+"px"}},{children:[n("div",Object.assign({className:"flex items-center gap-2 text-sm font-medium"},{children:o("span",{children:[Pn.toLocaleString()," ",On?(null==Ee?void 0:Ee.credits)||"Credits":(null==Ee?void 0:Ee.uses)||"Uses"," ",(null==Ee?void 0:Ee.remaining)||"remaining"]})})),o("div",Object.assign({className:"flex items-center gap-3"},{children:[!$n&&n("button",Object.assign({className:"rounded-md px-3 py-1.5 text-xs font-semibold transition-opacity hover:opacity-90",style:{backgroundColor:Ce.accent,color:Ce.accentText},onClick:e=>{if(e.preventDefault(),e.stopPropagation(),Xn)return void window.open(Xn,"_blank","noopener,noreferrer");const t=$({baseUrl:Ot,accessGroupId:null==De?void 0:De.accessGroupId,redirectUrl:document.URL});t&&(X()?window.open(t):location.href=t)}},{children:Kn})),n("button",Object.assign({className:"flex h-6 w-6 items-center justify-center rounded-full opacity-60 transition-opacity hover:opacity-100",onClick:()=>Et(!0)},{children:n("svg",Object.assign({xmlns:"http://www.w3.org/2000/svg",fill:"none",viewBox:"0 0 24 24",strokeWidth:2,stroke:"currentColor",className:"h-4 w-4"},{children:n("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M6 18L18 6M6 6l12 12"})}))}))]}))]})),!Je&&Ze.length>0&&n(U,{className:"p-4 pb-0",isDisabled:Je}),o("div",Object.assign({className:"relative flex w-full flex-col"},{children:[Wt&&o("div",Object.assign({className:"absolute left-4 top-1/2 flex -translate-y-1/2 select-none items-center gap-x-2"},{children:[n("span",{className:"h-2 w-2 animate-pulse rounded-full bg-c-secondary",style:{backgroundColor:null!==(he=Ce.accent)&&void 0!==he?he:"#ff0000"}}),n("span",Object.assign({className:"text-sm text-c-secondary font-semilight",style:{color:Ce.text+"90"}},{children:(null==Ee?void 0:Ee.listening)||"Listening..."}))]})),n(A,Object.assign({ref:Mt,className:B(an.i1,"py-3.5 max-h-60 px-4 w-full border-transparent bg-transparent",!vt.trim()&&!vt.includes("\n")&&"overflow-hidden text-ellipsis whitespace-nowrap placeholder:whitespace-normal placeholder:overflow-visible",Ae?"text-right":"text-left",xn&&"mb-12",Wt&&"text-transparent"),value:vt,placeholder:yn,onChange:e=>{ht(e)},onKeyDown:e=>{Te||rt||"Enter"===e.key&&(e.shiftKey||(e.preventDefault(),et||Je||Hn()))},onPaste:e=>t(void 0,void 0,void 0,(function*(){const t=Array.from(e.clipboardData.files||[]);if(t.length>0){if(!pn)return;e.preventDefault(),Le(!1),yield nt(t)}}))},Y&&{onFocus:Y},ne&&{onBlur:ne},{dir:Ae?"rtl":"ltr"})),n("div",Object.assign({ref:Bt,className:B("flex items-center gap-2 absolute z-2 transition-all duration-200 ease-in-out",xn?"bottom-3 right-2":"right-0 top-1/2 -translate-y-1/2"),style:Object.assign(Object.assign({},!xn&&ln.backgroundColor&&{backgroundColor:ln.backgroundColor}),{borderTopRightRadius:Ne.cornerRadius+"px",borderBottomRightRadius:Ne.cornerRadius+"px"})},{children:Je?n("button",Object.assign({className:"flex h-8 w-8 items-center mr-2 justify-center rounded-full outline-none transition-colors duration-200 ease-in-out",onClick:()=>{const e=Dt.current;e&&(Lt.current=e,(e=>{t(void 0,void 0,void 0,(function*(){if(!(e=null!=e?e:Dt.current))return;const t=q(Rt.current);try{yield fetch(`${process.env.NEXT_PUBLIC_PICKAXE_API2_URL}/response/cancel/${e}`,Object.assign({method:"POST",headers:Object.assign(Object.assign({"Content-Type":"application/json"},(!process.env.NODE_ENV||"development"===process.env.NODE_ENV)&&Object.assign({},process.env.NEXT_PUBLIC_PICKAXE_SESSION_TOKEN&&{"x-pickaxe-session-token":process.env.NEXT_PUBLIC_PICKAXE_SESSION_TOKEN})),{"x-request-sent-at":(new Date).toISOString()}),body:JSON.stringify({outputMessageParts:t})},mn&&{credentials:"include"}))}catch(e){console.warn("Failed to cancel submission",e)}}))})(e)),Xt.current&&(Xt.current.abort(),Xt.current=null),Pt.current&&(Pt.current.cancel().catch((()=>{})),Pt.current=null),qe("idle")},style:{backgroundColor:Ce.accent,color:Ce.accentText}},{children:n(T,{className:"h-4 w-4 shrink-0"})})):Wt?n("button",Object.assign({className:"flex h-8 w-8 items-center mr-2 justify-center rounded-full outline-none transition-colors duration-200 ease-in-out",onClick:qt,style:{backgroundColor:Ce.accent,color:Ce.accentText}},{children:n(T,{className:"h-4 w-4 shrink-0"})})):o(s,{children:[pn&&o("button",Object.assign({className:"flex h-8 w-8 items-center justify-center rounded-full outline-none transition-colors duration-200 ease-in-out disabled:cursor-default",style:{backgroundColor:tn?Ce.accent+"10":void 0,color:tn?Ce.accent:Ce.accent+"80"},disabled:et||Je,onClick:()=>{var e;return null===(e=Ut.current)||void 0===e?void 0:e.click()}},nn,{children:[n("input",{id:"file-upload",ref:Ut,type:"file",accept:[...O,...k,...S].join(", "),multiple:!0,hidden:!0,className:"hidden",onChange:e=>t(void 0,void 0,void 0,(function*(){Le(!1),yield nt(Array.from(e.target.files||[])),e.target.value=""}))}),n(C,{className:"h-6 w-6 shrink-0"})]})),fn&&n("button",Object.assign({className:"disabled:cursor-default flex h-8 w-8 items-center justify-center rounded-full outline-none transition-colors duration-200 ease-in-out",style:{backgroundColor:Wt?Ce.accent:sn?Ce.accent+"10":void 0,color:Wt?Ce.accentText:sn?Ce.accent:Ce.accent+"80"},disabled:et||Je||Gt,onClick:()=>{Wt?qt():(At.current=vt,zt(_e||"en-US"))}},rn,{children:n(_,{className:"h-5 w-5 shrink-0"})})),n("button",Object.assign({className:"flex h-8 w-8 items-center mr-2 justify-center rounded-full outline-none transition-colors duration-200 ease-in-out disabled:cursor-default",style:{backgroundColor:Yt||Fn?Ce.accent:Ce.accent+"10",color:Yt||Fn?Ce.accentText:Ce.accent+"80"},disabled:!Fn,onClick:()=>Hn()},Zt,{children:n(E,{className:B("h-6 w-6 shrink-0",Ae&&"scale-x-[-1] transform")})}))]})}))]}))]})),tt&&n(P,{error:tt,className:"mt-3"})]}))}))}));ne.displayName="Input";export{ne as default};
@@ -1 +1 @@
1
- import{__awaiter as e}from"../../_virtual/_tslib.js";import"../../node_modules/.pnpm/regenerator-runtime@0.14.1/node_modules/regenerator-runtime/runtime.js";import i,{useSpeechRecognition as t}from"react-speech-recognition";import{useState as o}from"react";import{pickaxeApi2 as r}from"../../common/api/pickaxe.js";const n=()=>{const{transcript:n,listening:s,resetTranscript:c}=t(),[a,p]=o(!1),[l,d]=o(!1);return{speechTranscript:n,isSpeechSupported:!0,isSpeechProcessing:a,isSpeechListening:s,onStartListening:t=>e(void 0,void 0,void 0,(function*(){try{p(!0),yield navigator.mediaDevices.getUserMedia({audio:!0});const e=(yield r.post("/speech")).data;if(!l){const{createSpeechServicesPonyfill:t}=yield import("web-speech-cognitive-services"),{SpeechRecognition:o}=t({credentials:{region:"eastus",authorizationToken:e.token}});i.applyPolyfill(o),d(!0)}c();const o={ar:"ar-SA",ca:"ca-ES",cs:"cs-CZ",da:"da-DK",de:"de-DE",en:"en-US",es:"es-ES",fi:"fi-FI",fr:"fr-FR",hi:"hi-IN",it:"it-IT",iw:"he-IL",ja:"ja-JP",ko:"ko-KR",nb:"nb-NO",nl:"nl-NL",pl:"pl-PL",pt:"pt-PT","pt-BR":"pt-BR",ro:"ro-RO",ru:"ru-RU",sv:"sv-SE",th:"th-TH",tr:"tr-TR",vi:"vi-VN",zh:"zh-CN",zu:"zu-ZA"};yield i.startListening({continuous:!0,interimResults:!0,language:o[t]||"en-US"})}catch(e){console.error(e)}finally{p(!1)}})),onStopListening:()=>e(void 0,void 0,void 0,(function*(){try{p(!0),yield i.abortListening()}catch(e){console.error(e)}finally{p(!1)}}))}};export{n as useSpeechToText};
1
+ import{__awaiter as e}from"../../_virtual/_tslib.js";import{useState as t,useRef as r,useEffect as o}from"react";import{pickaxeApi2 as n}from"../../common/api/pickaxe.js";const s=()=>{if("undefined"!=typeof window)return window.AudioContext||window.webkitAudioContext},c=e=>{var t,r;e.processor&&(e.processor.onaudioprocess=null,e.processor.disconnect()),null===(t=e.source)||void 0===t||t.disconnect(),null===(r=e.silentGain)||void 0===r||r.disconnect(),e.processor=void 0,e.source=void 0,e.silentGain=void 0;for(const t of e.stream.getTracks())t.stop();"closed"!==e.audioContext.state&&e.audioContext.close()},i=()=>{var i;const[a,u]=t(""),[l,d]=t(!1),[m,p]=t(!1),f=r(!0),w=r(0),y=r(null),v=r(new Map),k=e=>{c(e),e.socket.readyState!==WebSocket.OPEN&&e.socket.readyState!==WebSocket.CONNECTING||e.socket.close(),y.current===e&&(y.current=null)};o((()=>(f.current=!0,()=>{f.current=!1,w.current+=1;const e=y.current;e&&(e.socket.readyState===WebSocket.OPEN&&e.socket.send(JSON.stringify({type:"Terminate"})),k(e))})),[]);return{speechTranscript:a,isSpeechSupported:"undefined"!=typeof window&&Boolean(s())&&Boolean(null===(i=navigator.mediaDevices)||void 0===i?void 0:i.getUserMedia)&&"WebSocket"in window,isSpeechProcessing:m,isSpeechListening:l,onStartListening:t=>e(void 0,void 0,void 0,(function*(){var e;const t=++w.current,r=s();if(!r||!(null===(e=navigator.mediaDevices)||void 0===e?void 0:e.getUserMedia))return;const o=y.current;let i,a;o&&k(o);try{p(!0),d(!1),u(""),v.current.clear(),i=yield navigator.mediaDevices.getUserMedia({audio:{autoGainControl:!0,channelCount:1,echoCancellation:!0,noiseSuppression:!0}}),a=new r;const{data:e}=yield n.post("/speech/assemblyai");if(!e.success||!e.token)throw new Error(e.error||"AssemblyAI streaming token was not returned");if(!f.current||t!==w.current)return;const o=new URL("wss://streaming.assemblyai.com/v3/ws");o.searchParams.set("sample_rate",String(16e3)),o.searchParams.set("speech_model","whisper-rt"),o.searchParams.set("language_detection","true"),o.searchParams.set("format_turns","true"),o.searchParams.set("token",e.token);const s={socket:new WebSocket(o),stream:i,audioContext:a,started:!1};i=void 0,a=void 0,y.current=s,yield new Promise(((e,r)=>{const o=window.setTimeout((()=>{r(new Error("AssemblyAI streaming session timed out"))}),1e4),n=e=>{s.started||(window.clearTimeout(o),r(e))};s.socket.binaryType="arraybuffer",s.socket.onmessage=r=>{try{const n=JSON.parse(String(r.data));if("Begin"!==n.type||s.started){if("Turn"===n.type)(e=>{var t;const r=(e=>{var t,r,o;const n=null===(t=e.utterance)||void 0===t?void 0:t.trim();return n&&!/^(?:\[[^\]]+\]\s*)+$/.test(n)?n:null!==(o=null===(r=e.transcript)||void 0===r?void 0:r.trim())&&void 0!==o?o:""})(e),o=null!==(t=e.turn_order)&&void 0!==t?t:0;r?v.current.set(o,r):v.current.delete(o);const n=Array.from(v.current.entries()).sort((([e],[t])=>e-t)).map((([,e])=>e)).join(" ").trim();f.current&&u(n)})(n);else if("Termination"===n.type)s.socket.close();else if("Error"===n.type)throw new Error(n.error||"AssemblyAI streaming failed")}else{s.started=!0,window.clearTimeout(o);const r=s.audioContext.createMediaStreamSource(s.stream),n=s.audioContext.createScriptProcessor(4096,1,1),c=s.audioContext.createGain();c.gain.value=0,n.onaudioprocess=({inputBuffer:e})=>{if(s.socket.readyState!==WebSocket.OPEN)return;const t=((e,t)=>{const r=t/16e3,o=Math.max(1,Math.round(e.length/r)),n=new Int16Array(o);let s=0;for(let t=0;t<o;t+=1){const o=Math.min(e.length,Math.round((t+1)*r));let c=0,i=0;for(;s<o;s+=1)c+=e[s],i+=1;const a=Math.max(-1,Math.min(1,i?c/i:0));n[t]=a<0?32768*a:32767*a}return n})(e.getChannelData(0),e.sampleRate);s.socket.send(t.buffer)},r.connect(n),n.connect(c),c.connect(s.audioContext.destination),s.source=r,s.processor=n,s.silentGain=c,s.audioContext.resume(),f.current&&t===w.current&&d(!0),e()}}catch(e){console.error("Could not process AssemblyAI message",e),n(e instanceof Error?e:new Error(String(e))),s.socket.close()}},s.socket.onerror=()=>{const e=new Error("Could not connect to AssemblyAI streaming");n(e),s.started&&console.error(e),s.socket.close()},s.socket.onclose=()=>{n(new Error("AssemblyAI streaming closed before it started")),(e=>{c(e),y.current===e&&(y.current=null,f.current&&d(!1))})(s)}})),f.current&&t===w.current||k(s)}catch(e){const t=y.current;t&&k(t),console.error("Could not start AssemblyAI speech recognition",e)}finally{if(i)for(const e of i.getTracks())e.stop();"closed"!==(null==a?void 0:a.state)&&(null==a||a.close()),f.current&&t===w.current&&p(!1)}})),onStopListening:()=>e(void 0,void 0,void 0,(function*(){const e=++w.current,t=y.current;if(t)try{p(!0),c(t),yield new Promise((e=>{const r=window.setTimeout(e,2e3),o=t.socket.onclose;t.socket.onclose=n=>{window.clearTimeout(r),null==o||o.call(t.socket,n),e()},t.socket.readyState===WebSocket.OPEN?t.socket.send(JSON.stringify({type:"Terminate"})):e()}))}catch(e){console.error("Could not stop AssemblyAI speech recognition",e)}finally{k(t),f.current&&e===w.current&&(d(!1),p(!1))}else d(!1)}))}};export{i as useSpeechToText};
@@ -1,9 +1,8 @@
1
- import "regenerator-runtime/runtime";
2
1
  export declare const useSpeechToText: () => {
3
2
  speechTranscript: string;
4
3
  isSpeechSupported: boolean;
5
4
  isSpeechProcessing: boolean;
6
5
  isSpeechListening: boolean;
7
- onStartListening: (locale: string) => Promise<void>;
6
+ onStartListening: (_locale: string) => Promise<void>;
8
7
  onStopListening: () => Promise<void>;
9
8
  };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@pickaxeproject/react",
3
- "version": "6.13.1",
3
+ "version": "6.13.3",
4
4
  "description": "Client utility library for Pickaxe",
5
5
  "repository": {
6
6
  "type": "git",
@@ -39,8 +39,6 @@
39
39
  "jose": "^6.1.3",
40
40
  "lucide-react": "^0.563.0",
41
41
  "pkce-challenge": "3.0.0",
42
- "react-speech-recognition": "^4.0.1",
43
- "regenerator-runtime": "^0.14.1",
44
42
  "remove-markdown": "^0.6.3",
45
43
  "tldts": "^7.0.23"
46
44
  },
@@ -82,7 +80,6 @@
82
80
  "@types/node": "^18.11.18",
83
81
  "@types/react": "^18.0.26",
84
82
  "@types/react-dom": "^18.0.10",
85
- "@types/react-speech-recognition": "^3.9.6",
86
83
  "@types/react-syntax-highlighter": "^15.5.13",
87
84
  "@types/uuid": "^10.0.0",
88
85
  "@types/webfontloader": "^1.6.38",
@@ -151,7 +148,6 @@
151
148
  "vite-plugin-node-polyfills": "^0.24.0",
152
149
  "vite-plugin-svgr": "^4.3.0",
153
150
  "vite-tsconfig-paths": "^5.1.4",
154
- "web-speech-cognitive-services": "^8.1.4",
155
151
  "webfontloader": "^1.6.28",
156
152
  "webpack": "^5.75.0",
157
153
  "webpack-cli": "^5.0.1"
@@ -191,7 +187,6 @@
191
187
  "tailwind-scrollbar": "^3.1.0",
192
188
  "unist-util-visit": "^5.0.0",
193
189
  "uuid": "^11.1.0",
194
- "web-speech-cognitive-services": "^8.1.4",
195
190
  "webfontloader": "^1.6.28"
196
191
  },
197
192
  "engines": {
@@ -1 +0,0 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:!0});exports.__module={exports:{}};
@@ -1 +0,0 @@
1
- "use strict";var t=require("../../../../../_virtual/runtime.js");t.__module.exports,function(t){var r=function(t){var r,e=Object.prototype,n=e.hasOwnProperty,o=Object.defineProperty||function(t,r,e){t[r]=e.value},i="function"==typeof Symbol?Symbol:{},a=i.iterator||"@@iterator",c=i.asyncIterator||"@@asyncIterator",u=i.toStringTag||"@@toStringTag";function l(t,r,e){return Object.defineProperty(t,r,{value:e,enumerable:!0,configurable:!0,writable:!0}),t[r]}try{l({},"")}catch(t){l=function(t,r,e){return t[r]=e}}function h(t,r,e,n){var i=r&&r.prototype instanceof d?r:d,a=Object.create(i.prototype),c=new T(n||[]);return o(a,"_invoke",{value:O(t,e,c)}),a}function f(t,r,e){try{return{type:"normal",arg:t.call(r,e)}}catch(t){return{type:"throw",arg:t}}}t.wrap=h;var s="suspendedStart",p="suspendedYield",y="executing",v="completed",g={};function d(){}function m(){}function w(){}var b={};l(b,a,(function(){return this}));var L=Object.getPrototypeOf,x=L&&L(L(P([])));x&&x!==e&&n.call(x,a)&&(b=x);var E=w.prototype=d.prototype=Object.create(b);function _(t){["next","throw","return"].forEach((function(r){l(t,r,(function(t){return this._invoke(r,t)}))}))}function j(t,r){function e(o,i,a,c){var u=f(t[o],t,i);if("throw"!==u.type){var l=u.arg,h=l.value;return h&&"object"==typeof h&&n.call(h,"__await")?r.resolve(h.__await).then((function(t){e("next",t,a,c)}),(function(t){e("throw",t,a,c)})):r.resolve(h).then((function(t){l.value=t,a(l)}),(function(t){return e("throw",t,a,c)}))}c(u.arg)}var i;o(this,"_invoke",{value:function(t,n){function o(){return new r((function(r,o){e(t,n,r,o)}))}return i=i?i.then(o,o):o()}})}function O(t,e,n){var o=s;return function(i,a){if(o===y)throw new Error("Generator is already running");if(o===v){if("throw"===i)throw a;return{value:r,done:!0}}for(n.method=i,n.arg=a;;){var c=n.delegate;if(c){var u=k(c,n);if(u){if(u===g)continue;return u}}if("next"===n.method)n.sent=n._sent=n.arg;else if("throw"===n.method){if(o===s)throw o=v,n.arg;n.dispatchException(n.arg)}else"return"===n.method&&n.abrupt("return",n.arg);o=y;var l=f(t,e,n);if("normal"===l.type){if(o=n.done?v:p,l.arg===g)continue;return{value:l.arg,done:n.done}}"throw"===l.type&&(o=v,n.method="throw",n.arg=l.arg)}}}function k(t,e){var n=e.method,o=t.iterator[n];if(o===r)return e.delegate=null,"throw"===n&&t.iterator.return&&(e.method="return",e.arg=r,k(t,e),"throw"===e.method)||"return"!==n&&(e.method="throw",e.arg=new TypeError("The iterator does not provide a '"+n+"' method")),g;var i=f(o,t.iterator,e.arg);if("throw"===i.type)return e.method="throw",e.arg=i.arg,e.delegate=null,g;var a=i.arg;return a?a.done?(e[t.resultName]=a.value,e.next=t.nextLoc,"return"!==e.method&&(e.method="next",e.arg=r),e.delegate=null,g):a:(e.method="throw",e.arg=new TypeError("iterator result is not an object"),e.delegate=null,g)}function G(t){var r={tryLoc:t[0]};1 in t&&(r.catchLoc=t[1]),2 in t&&(r.finallyLoc=t[2],r.afterLoc=t[3]),this.tryEntries.push(r)}function N(t){var r=t.completion||{};r.type="normal",delete r.arg,t.completion=r}function T(t){this.tryEntries=[{tryLoc:"root"}],t.forEach(G,this),this.reset(!0)}function P(t){if(null!=t){var e=t[a];if(e)return e.call(t);if("function"==typeof t.next)return t;if(!isNaN(t.length)){var o=-1,i=function e(){for(;++o<t.length;)if(n.call(t,o))return e.value=t[o],e.done=!1,e;return e.value=r,e.done=!0,e};return i.next=i}}throw new TypeError(typeof t+" is not iterable")}return m.prototype=w,o(E,"constructor",{value:w,configurable:!0}),o(w,"constructor",{value:m,configurable:!0}),m.displayName=l(w,u,"GeneratorFunction"),t.isGeneratorFunction=function(t){var r="function"==typeof t&&t.constructor;return!!r&&(r===m||"GeneratorFunction"===(r.displayName||r.name))},t.mark=function(t){return Object.setPrototypeOf?Object.setPrototypeOf(t,w):(t.__proto__=w,l(t,u,"GeneratorFunction")),t.prototype=Object.create(E),t},t.awrap=function(t){return{__await:t}},_(j.prototype),l(j.prototype,c,(function(){return this})),t.AsyncIterator=j,t.async=function(r,e,n,o,i){void 0===i&&(i=Promise);var a=new j(h(r,e,n,o),i);return t.isGeneratorFunction(e)?a:a.next().then((function(t){return t.done?t.value:a.next()}))},_(E),l(E,u,"Generator"),l(E,a,(function(){return this})),l(E,"toString",(function(){return"[object Generator]"})),t.keys=function(t){var r=Object(t),e=[];for(var n in r)e.push(n);return e.reverse(),function t(){for(;e.length;){var n=e.pop();if(n in r)return t.value=n,t.done=!1,t}return t.done=!0,t}},t.values=P,T.prototype={constructor:T,reset:function(t){if(this.prev=0,this.next=0,this.sent=this._sent=r,this.done=!1,this.delegate=null,this.method="next",this.arg=r,this.tryEntries.forEach(N),!t)for(var e in this)"t"===e.charAt(0)&&n.call(this,e)&&!isNaN(+e.slice(1))&&(this[e]=r)},stop:function(){this.done=!0;var t=this.tryEntries[0].completion;if("throw"===t.type)throw t.arg;return this.rval},dispatchException:function(t){if(this.done)throw t;var e=this;function o(n,o){return c.type="throw",c.arg=t,e.next=n,o&&(e.method="next",e.arg=r),!!o}for(var i=this.tryEntries.length-1;i>=0;--i){var a=this.tryEntries[i],c=a.completion;if("root"===a.tryLoc)return o("end");if(a.tryLoc<=this.prev){var u=n.call(a,"catchLoc"),l=n.call(a,"finallyLoc");if(u&&l){if(this.prev<a.catchLoc)return o(a.catchLoc,!0);if(this.prev<a.finallyLoc)return o(a.finallyLoc)}else if(u){if(this.prev<a.catchLoc)return o(a.catchLoc,!0)}else{if(!l)throw new Error("try statement without catch or finally");if(this.prev<a.finallyLoc)return o(a.finallyLoc)}}}},abrupt:function(t,r){for(var e=this.tryEntries.length-1;e>=0;--e){var o=this.tryEntries[e];if(o.tryLoc<=this.prev&&n.call(o,"finallyLoc")&&this.prev<o.finallyLoc){var i=o;break}}i&&("break"===t||"continue"===t)&&i.tryLoc<=r&&r<=i.finallyLoc&&(i=null);var a=i?i.completion:{};return a.type=t,a.arg=r,i?(this.method="next",this.next=i.finallyLoc,g):this.complete(a)},complete:function(t,r){if("throw"===t.type)throw t.arg;return"break"===t.type||"continue"===t.type?this.next=t.arg:"return"===t.type?(this.rval=this.arg=t.arg,this.method="return",this.next="end"):"normal"===t.type&&r&&(this.next=r),g},finish:function(t){for(var r=this.tryEntries.length-1;r>=0;--r){var e=this.tryEntries[r];if(e.finallyLoc===t)return this.complete(e.completion,e.afterLoc),N(e),g}},catch:function(t){for(var r=this.tryEntries.length-1;r>=0;--r){var e=this.tryEntries[r];if(e.tryLoc===t){var n=e.completion;if("throw"===n.type){var o=n.arg;N(e)}return o}}throw new Error("illegal catch attempt")},delegateYield:function(t,e,n){return this.delegate={iterator:P(t),resultName:e,nextLoc:n},"next"===this.method&&(this.arg=r),g}},t}(t.exports);try{regeneratorRuntime=r}catch(t){"object"==typeof globalThis?globalThis.regeneratorRuntime=r:Function("r","regeneratorRuntime = r")(r)}}(t.__module),t.__module.exports;
@@ -1 +0,0 @@
1
- var e={exports:{}};export{e as __module};
@@ -1 +0,0 @@
1
- import{__module as t}from"../../../../../_virtual/runtime.js";t.exports,function(t){var r=function(t){var r,e=Object.prototype,n=e.hasOwnProperty,o=Object.defineProperty||function(t,r,e){t[r]=e.value},i="function"==typeof Symbol?Symbol:{},a=i.iterator||"@@iterator",c=i.asyncIterator||"@@asyncIterator",u=i.toStringTag||"@@toStringTag";function h(t,r,e){return Object.defineProperty(t,r,{value:e,enumerable:!0,configurable:!0,writable:!0}),t[r]}try{h({},"")}catch(t){h=function(t,r,e){return t[r]=e}}function l(t,r,e,n){var i=r&&r.prototype instanceof d?r:d,a=Object.create(i.prototype),c=new T(n||[]);return o(a,"_invoke",{value:O(t,e,c)}),a}function f(t,r,e){try{return{type:"normal",arg:t.call(r,e)}}catch(t){return{type:"throw",arg:t}}}t.wrap=l;var s="suspendedStart",p="suspendedYield",y="executing",v="completed",g={};function d(){}function m(){}function w(){}var b={};h(b,a,(function(){return this}));var L=Object.getPrototypeOf,x=L&&L(L(P([])));x&&x!==e&&n.call(x,a)&&(b=x);var E=w.prototype=d.prototype=Object.create(b);function _(t){["next","throw","return"].forEach((function(r){h(t,r,(function(t){return this._invoke(r,t)}))}))}function j(t,r){function e(o,i,a,c){var u=f(t[o],t,i);if("throw"!==u.type){var h=u.arg,l=h.value;return l&&"object"==typeof l&&n.call(l,"__await")?r.resolve(l.__await).then((function(t){e("next",t,a,c)}),(function(t){e("throw",t,a,c)})):r.resolve(l).then((function(t){h.value=t,a(h)}),(function(t){return e("throw",t,a,c)}))}c(u.arg)}var i;o(this,"_invoke",{value:function(t,n){function o(){return new r((function(r,o){e(t,n,r,o)}))}return i=i?i.then(o,o):o()}})}function O(t,e,n){var o=s;return function(i,a){if(o===y)throw new Error("Generator is already running");if(o===v){if("throw"===i)throw a;return{value:r,done:!0}}for(n.method=i,n.arg=a;;){var c=n.delegate;if(c){var u=k(c,n);if(u){if(u===g)continue;return u}}if("next"===n.method)n.sent=n._sent=n.arg;else if("throw"===n.method){if(o===s)throw o=v,n.arg;n.dispatchException(n.arg)}else"return"===n.method&&n.abrupt("return",n.arg);o=y;var h=f(t,e,n);if("normal"===h.type){if(o=n.done?v:p,h.arg===g)continue;return{value:h.arg,done:n.done}}"throw"===h.type&&(o=v,n.method="throw",n.arg=h.arg)}}}function k(t,e){var n=e.method,o=t.iterator[n];if(o===r)return e.delegate=null,"throw"===n&&t.iterator.return&&(e.method="return",e.arg=r,k(t,e),"throw"===e.method)||"return"!==n&&(e.method="throw",e.arg=new TypeError("The iterator does not provide a '"+n+"' method")),g;var i=f(o,t.iterator,e.arg);if("throw"===i.type)return e.method="throw",e.arg=i.arg,e.delegate=null,g;var a=i.arg;return a?a.done?(e[t.resultName]=a.value,e.next=t.nextLoc,"return"!==e.method&&(e.method="next",e.arg=r),e.delegate=null,g):a:(e.method="throw",e.arg=new TypeError("iterator result is not an object"),e.delegate=null,g)}function G(t){var r={tryLoc:t[0]};1 in t&&(r.catchLoc=t[1]),2 in t&&(r.finallyLoc=t[2],r.afterLoc=t[3]),this.tryEntries.push(r)}function N(t){var r=t.completion||{};r.type="normal",delete r.arg,t.completion=r}function T(t){this.tryEntries=[{tryLoc:"root"}],t.forEach(G,this),this.reset(!0)}function P(t){if(null!=t){var e=t[a];if(e)return e.call(t);if("function"==typeof t.next)return t;if(!isNaN(t.length)){var o=-1,i=function e(){for(;++o<t.length;)if(n.call(t,o))return e.value=t[o],e.done=!1,e;return e.value=r,e.done=!0,e};return i.next=i}}throw new TypeError(typeof t+" is not iterable")}return m.prototype=w,o(E,"constructor",{value:w,configurable:!0}),o(w,"constructor",{value:m,configurable:!0}),m.displayName=h(w,u,"GeneratorFunction"),t.isGeneratorFunction=function(t){var r="function"==typeof t&&t.constructor;return!!r&&(r===m||"GeneratorFunction"===(r.displayName||r.name))},t.mark=function(t){return Object.setPrototypeOf?Object.setPrototypeOf(t,w):(t.__proto__=w,h(t,u,"GeneratorFunction")),t.prototype=Object.create(E),t},t.awrap=function(t){return{__await:t}},_(j.prototype),h(j.prototype,c,(function(){return this})),t.AsyncIterator=j,t.async=function(r,e,n,o,i){void 0===i&&(i=Promise);var a=new j(l(r,e,n,o),i);return t.isGeneratorFunction(e)?a:a.next().then((function(t){return t.done?t.value:a.next()}))},_(E),h(E,u,"Generator"),h(E,a,(function(){return this})),h(E,"toString",(function(){return"[object Generator]"})),t.keys=function(t){var r=Object(t),e=[];for(var n in r)e.push(n);return e.reverse(),function t(){for(;e.length;){var n=e.pop();if(n in r)return t.value=n,t.done=!1,t}return t.done=!0,t}},t.values=P,T.prototype={constructor:T,reset:function(t){if(this.prev=0,this.next=0,this.sent=this._sent=r,this.done=!1,this.delegate=null,this.method="next",this.arg=r,this.tryEntries.forEach(N),!t)for(var e in this)"t"===e.charAt(0)&&n.call(this,e)&&!isNaN(+e.slice(1))&&(this[e]=r)},stop:function(){this.done=!0;var t=this.tryEntries[0].completion;if("throw"===t.type)throw t.arg;return this.rval},dispatchException:function(t){if(this.done)throw t;var e=this;function o(n,o){return c.type="throw",c.arg=t,e.next=n,o&&(e.method="next",e.arg=r),!!o}for(var i=this.tryEntries.length-1;i>=0;--i){var a=this.tryEntries[i],c=a.completion;if("root"===a.tryLoc)return o("end");if(a.tryLoc<=this.prev){var u=n.call(a,"catchLoc"),h=n.call(a,"finallyLoc");if(u&&h){if(this.prev<a.catchLoc)return o(a.catchLoc,!0);if(this.prev<a.finallyLoc)return o(a.finallyLoc)}else if(u){if(this.prev<a.catchLoc)return o(a.catchLoc,!0)}else{if(!h)throw new Error("try statement without catch or finally");if(this.prev<a.finallyLoc)return o(a.finallyLoc)}}}},abrupt:function(t,r){for(var e=this.tryEntries.length-1;e>=0;--e){var o=this.tryEntries[e];if(o.tryLoc<=this.prev&&n.call(o,"finallyLoc")&&this.prev<o.finallyLoc){var i=o;break}}i&&("break"===t||"continue"===t)&&i.tryLoc<=r&&r<=i.finallyLoc&&(i=null);var a=i?i.completion:{};return a.type=t,a.arg=r,i?(this.method="next",this.next=i.finallyLoc,g):this.complete(a)},complete:function(t,r){if("throw"===t.type)throw t.arg;return"break"===t.type||"continue"===t.type?this.next=t.arg:"return"===t.type?(this.rval=this.arg=t.arg,this.method="return",this.next="end"):"normal"===t.type&&r&&(this.next=r),g},finish:function(t){for(var r=this.tryEntries.length-1;r>=0;--r){var e=this.tryEntries[r];if(e.finallyLoc===t)return this.complete(e.completion,e.afterLoc),N(e),g}},catch:function(t){for(var r=this.tryEntries.length-1;r>=0;--r){var e=this.tryEntries[r];if(e.tryLoc===t){var n=e.completion;if("throw"===n.type){var o=n.arg;N(e)}return o}}throw new Error("illegal catch attempt")},delegateYield:function(t,e,n){return this.delegate={iterator:P(t),resultName:e,nextLoc:n},"next"===this.method&&(this.arg=r),g}},t}(t.exports);try{regeneratorRuntime=r}catch(t){"object"==typeof globalThis?globalThis.regeneratorRuntime=r:Function("r","regeneratorRuntime = r")(r)}}(t),t.exports;