@pickaxeproject/react 6.24.1 → 6.24.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("../../../common/canChat.js"),n=require("../../../hooks/pickaxe/useEndUserModel.js"),i=require("../common/EndUserModelPicker.js"),r=require("../../../common/actionApproval.js"),o=require("react"),a=require("../../../hooks/pickaxe/usePickaxeContext.js"),l=require("../../../hooks/pickaxe/useResponseContext.js"),d=require("../../../hooks/studio/useStyleInput.js"),c=require("../../../hooks/studio/useStyleFontSize.js"),u=require("../../../hooks/pickaxe/useConversation.js"),p=require("../../../hooks/pickaxe/useDimensionContext.js"),m=require("../Addons/Auth/hooks/useAuthContext.js"),f=require("../Addons/Document/hooks/useDocument.js"),g=require("../Addons/Scroll/hooks/useScroll.js"),v=require("../Addons/Artifact/hooks/useArtifactContext.js"),h=require("../../../hooks/core/useHover.js"),b=require("../../../hooks/core/useMediaQuery.js"),x=require("../../../common/documents.js"),y=require("eventsource-parser"),I=require("../../Icons/attach-vertical.svg.js"),j=require("../../Icons/arrow-right.svg.js"),S=require("../../Icons/microphone.svg.js"),N=require("../../Icons/message-clock.svg.js"),O=require("../../Icons/stop.svg.js"),w=require("../../Icons/trash.svg.js"),k=require("../../Icons/pencil.svg.js"),_=require("../Addons/Document/List.js"),E=require("../../Core/Textarea.js"),T=require("../../Core/ErrorAlert.js"),C=require("../../Core/Menu/index.js"),U=require("../../Core/Menu/Button.js"),A=require("../../Core/Menu/List.js"),D=require("../../../common/error.js"),P=require("../../../common/api/pickaxe.js"),L=require("../../../common/validation.js"),q=require("../../../common/cn.js"),M=require("../../../common/utils.js"),R=require("../../../common/pickaxeConfig.js"),F=require("../../../common/agentPrefill.js"),V=require("../../../common/deploymentWebhooks.js"),$=require("../../../hooks/studio/useStudio.js"),B=require("../../../hooks/pickaxe/useSpeechToText.js"),X=require("../common/PickaxeCommon.js");const K=(e,t)=>{const s=e.find((e=>e.id===t));return s?e.filter((e=>e.id!==t)).map((e=>e.predecessorSubmissionId===t?Object.assign(Object.assign({},e),{predecessorSubmissionId:s.predecessorSubmissionId}):e)):e},G=e=>"string"==typeof e&&e.trim().length>0,H=()=>"undefined"!=typeof crypto&&"randomUUID"in crypto?crypto.randomUUID():`submission-${Date.now()}-${Math.random().toString(36).slice(2)}`,Y=e=>e.map((e=>Object.assign({},e))),W=e=>e instanceof Error&&("AbortError"===e.name||"BodyStreamBuffer was aborted"===e.message),z=(e,t)=>{if(e&&"object"==typeof e)return e[t]},J=(e,t)=>{const s=z(e,t);return G(s)?s:null},Q=e=>{const t=Number(e);return Number.isFinite(t)?t:void 0},Z=({studioUser:e,deploymentId:t,portalId:s})=>{var n,i;const r=Array.isArray(z(e,"uses"))?z(e,"uses"):[],o=(({deploymentId:e,portalId:t})=>G(e)?{type:"deployment",id:e}:G(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}},ee=o.forwardRef((({resubmitPrompt:z,onFocus:ee,onBlur:te,onInputHeightChange:se,initSmitheryAuthData:ne},ie)=>{var re,oe,ae,le,de,ce,ue,pe,me,fe,ge,ve,he,be,xe,ye,Ie,je;const{origin:Se,pickaxeId:Ne,sessionId:Oe,sender:we,senderType:ke,portalId:_e,deploymentId:Ee,deploymentType:Te,pickaxe:Ce,styles:Ue,colors:Ae,translations:De,locale:Pe,forceMobile:Le,isNewChat:qe,isRtl:Me,isEmbed:Re,isShowFeedbackMessage:Fe,accessGroup:Ve,setIsNewChat:$e,setIsShowIceBreaker:Be,setValidationStatus:Xe,setValidationUpgradeGroups:Ke,setValidationUpgradeUrl:Ge,setAccessGroup:He,onUpgrade:Ye,onGenerateComplete:We}=a.usePickaxeContext(),{value:ze,enabled:Je}=n.useEndUserModel(),{token:Qe,isLoggedOut:Ze,isSent:et,isPricingAuth:tt}=m.useAuthContext(),{messages:st,isGenerating:nt,setMessages:it,setStatus:rt,setLimitData:ot,setError:at,setActionApprovalToken:lt}=l.useResponseContext(),{documents:dt,isUploading:ct,documentError:ut,onFileUpload:pt,setDocuments:mt,setDocumentError:ft}=f.useDocument(),{studio:gt}=$.useStudio(),[vt]=b.useMediaQuery("(max-width: 480px)"),{scrollStartSession:ht,scrollEndSession:bt,scrollToBottom:xt}=g.useScroll({auto:!0,smooth:!(Le||vt)}),{artifacts:yt,currentPopupType:It,setArtifacts:jt,setCurrentArtifact:St}=v.useArtifactContext(),{height:Nt}=p.useDimensionContext(),Ot=u.useConversation(),[wt,kt]=o.useState((()=>F.readAgentPrefill([Ee,Ne]).chatInput)),[_t,Et]=o.useState(!1),[Tt,Ct]=o.useState(!1),[Ut,At]=o.useState(!1),[Dt,Pt]=o.useState(!1),[Lt,qt]=o.useState([]),[Mt,Rt]=o.useState(!1),[Ft,Vt]=o.useState(null),[$t,Bt]=o.useState(null),[Xt,Kt]=o.useState(null),[Gt,Ht]=o.useState(null),[Yt,Wt]=o.useState(!1),[zt,Jt]=o.useState(!1),[Qt,Zt]=o.useState(0),es=o.useRef(null),ts=o.useRef(""),ss=o.useRef(null),ns=o.useRef(null),is=o.useRef(null),rs=o.useRef([]),os=o.useRef(null),as=o.useRef(null),ls=o.useRef(null),ds=o.useRef(null),cs=o.useRef(new Set),us=o.useRef(null),ps=Math.max(.4*Nt,100),{speechTranscript:ms,isSpeechListening:fs,isSpeechProcessing:gs,isSpeechSupported:vs,onStartListening:hs,onStopListening:bs}=B.useSpeechToText(),xs=h.useHover(),{isHover:ys}=xs,Is=e.__rest(xs,["isHover"]),js=h.useHover(),{isHover:Ss}=js,Ns=e.__rest(js,["isHover"]),Os=h.useHover(),{isHover:ws}=Os,ks=e.__rest(Os,["isHover"]),_s=c.useStyleFontSize(),Es=d.useStyleInput(),Ts="undefined"!=typeof window?window.location.hostname:"",Cs="undefined"!=typeof window?window.location.href:"",Us="undefined"!=typeof window&&window.self!==window.top,As=Ts.includes("pickaxe.co")&&!Cs.includes("https://studio.pickaxe.co/_embed")&&!Us,Ds=null!==(oe=null===(re=null==Ce?void 0:Ce.documentuploadtype)||void 0===re?void 0:re.startsWith("enduserupload"))&&void 0!==oe&&oe,Ps=vs&&(null==Ce?void 0:Ce.enablevoicetotext),Ls=fs&&!wt.trim(),qs=G(Ee),Ms="chat-input"===Te&&qe&&!et,Rs="chat-input"===Te&&tt&&Ze&&et,Fs=o.useCallback((e=>{const t=L.getValidationFailure(e);return!!t&&(at(""),ot(null),Xe(t.status),He(t.accessGroup),Ke(t.upgradeGroups),Ge(t.upgradeUrl),!0)}),[at,lt,ot,Xe,Ke,Ge,He]),Vs=null!==(ae=null==Ce?void 0:Ce.placeholdertext)&&void 0!==ae?ae:Me?"بماذا تريد أن تتحدث؟":(null==De?void 0:De["what-do-you-want-to-talk-about"])||"What do you want to talk about?",$s=_t||Tt,Bs=o.useCallback((()=>e.__awaiter(void 0,void 0,void 0,(function*(){Wt(!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==Ce?void 0:Ce.studioid},Qe?{studioSessionToken:Qe}:we?{sender:we}:{sender:M.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}})),As&&{credentials:"include"})),t=yield e.json();(null==t?void 0:t.studioUser)&&(Kt(t.studioUser),Ht(t.url))}catch(e){console.error("Failed to fetch studio user:",e)}finally{Wt(!0)}}))),[As,null==Ce?void 0:Ce.studioid,we,Qe]);o.useEffect((()=>{Bs()}),[Bs]);const Xs=Number(null!==(le=null==Ve?void 0:Ve.limit)&&void 0!==le?le:0),Ks="string"==typeof(null==Ve?void 0:Ve.limitInterval)?Ve.limitInterval:null,Gs=!!(null==gt?void 0:gt.data.usage)&>.data.usage.isCredits,Hs=o.useMemo((()=>{var e,t,s,n,i;return null!==(i=null!==(n=null!==(s=null!==(t=null!==(e=null!=_e?_e:J(Xt,"portalId"))&&void 0!==e?e:J(Xt,"portalid"))&&void 0!==t?t:J(Ve,"portalId"))&&void 0!==s?s:J(Ve,"portalid"))&&void 0!==n?n:J(Ce,"portalId"))&&void 0!==i?i:J(Ce,"portalid")}),[Ve,_e,Ce,Xt]),Ys=o.useMemo((()=>Z({studioUser:Xt,deploymentId:Ee,portalId:Hs})),[Ee,Hs,Xt]);o.useEffect((()=>{qs&&qe&&Oe&&cs.current.add(Oe)}),[qe,Oe,qs]);const Ws=o.useCallback((()=>{var e,t,s;return{studioId:null==Ce?void 0:Ce.studioid,userEmail:J(Xt,"email"),userId:null!==(e=J(Xt,"userId"))&&void 0!==e?e:J(Xt,"userid"),sessionId:Oe,deploymentId:Ee,deploymentType:Te,portalId:Hs,accessGroupId:null!==(t=null==Ve?void 0:Ve.accessGroupId)&&void 0!==t?t:null,pickaxeId:Ne,sender:we,senderType:ke,origin:Se,metadata:null!==(s=R.getPickaxeConfigMetadata(Ee))&&void 0!==s?s:null}}),[null==Ve?void 0:Ve.accessGroupId,Ee,Te,Se,null==Ce?void 0:Ce.studioid,Ne,Hs,we,ke,Oe,Xt]),zs=o.useCallback((()=>!!(qs&&Yt&&Oe)&&(!!cs.current.has(Oe)&&(V.fireDeploymentSessionInitializedWebhook(Ws()),cs.current.delete(Oe),!0))),[Ws,Yt,Oe,qs]);o.useEffect((()=>{if(!Yt||!Oe)return;zs();const e=us.current;(null==e?void 0:e.sessionId)===Oe&&(V.fireDeploymentFirstMessageSubmittedWebhook(Object.assign(Object.assign(Object.assign({},e),Ws()),{message:e.message,documentIds:e.documentIds,uploadedModelImages:e.uploadedModelImages,hasUploadedDocuments:e.hasUploadedDocuments,isHidden:e.isHidden})),us.current=null)}),[zs,Ws,Yt,Oe]);const Js={currentUses:Q(null==Xt?void 0:Xt.currentUses),extraUses:Q(null==Xt?void 0:Xt.extraUses)},Qs=Ys.scope?{currentUses:null!==(ce=Q(null===(de=Ys.record)||void 0===de?void 0:de.currentUses))&&void 0!==ce?ce:0,extraUses:null!==(pe=Q(null===(ue=Ys.record)||void 0===ue?void 0:ue.extraUses))&&void 0!==pe?pe:0}:{currentUses:0,extraUses:0},Zs=J(Xt,"type"),en="guest"===Zs||!Zs&&Ze?Qs:Js;o.useEffect((()=>{let t=!0;return e.__awaiter(void 0,void 0,void 0,(function*(){var e;if(Gs&&(null===(e=null==gt?void 0:gt.data)||void 0===e?void 0:e.workspaceId))try{const e=yield P.pickaxeApi2.get(`/cost_per_run?workspaceId=${gt.data.workspaceId}`,{withCredentials:!1});t&&Zt(1e4*(Number(e.data.costPerRun)||0))}catch(e){console.error("Failed to fetch average cost per run:",e),t&&Zt(0)}else t&&Zt(0)})),()=>{t=!1}}),[Gs,null===(me=null==gt?void 0:gt.data)||void 0===me?void 0:me.workspaceId]);const tn=(({accessGroupType:e,currentUses:t,extraUses:s,limit:n,limitInterval:i})=>{const r=Number(null!=t?t:0),o=Number(null!=s?s:0);return"public"===e&&"one_time"===i?n===X.STUDIO_INFINITY_VALUE?X.STUDIO_INFINITY_VALUE:Math.max(0,n-r):n===X.STUDIO_INFINITY_VALUE||o===X.STUDIO_INFINITY_VALUE?X.STUDIO_INFINITY_VALUE:"one_time"===i?Math.max(0,o):Math.max(0,n-r)+o})({accessGroupType:null==Ve?void 0:Ve.type,currentUses:en.currentUses,extraUses:en.extraUses,limit:Xs,limitInterval:Ks}),sn=tn===X.STUDIO_INFINITY_VALUE?X.STUDIO_INFINITY_VALUE:Math.max(0,Math.ceil(tn)),nn=(({accessGroupType:e,extraUses:t,limit:s,limitInterval:n})=>{const i=Number(null!=t?t:0);return"public"===e&&"one_time"===n?s===X.STUDIO_INFINITY_VALUE?X.STUDIO_INFINITY_VALUE:Math.max(0,s):s===X.STUDIO_INFINITY_VALUE||i===X.STUDIO_INFINITY_VALUE?X.STUDIO_INFINITY_VALUE:"one_time"===n?Math.max(0,i):Math.max(0,s)+Math.max(0,i)})({accessGroupType:null==Ve?void 0:Ve.type,extraUses:en.extraUses,limit:Xs,limitInterval:Ks}),rn=nn===X.STUDIO_INFINITY_VALUE?X.STUDIO_INFINITY_VALUE:Math.ceil(.05*nn),on=Gs?Math.ceil(5*Qt):5,an=rn===X.STUDIO_INFINITY_VALUE?X.STUDIO_INFINITY_VALUE:Math.max(rn,on),ln=o.useMemo((()=>!!Xt&&(!zt&&(sn!==X.STUDIO_INFINITY_VALUE&&(!(nn<=0||sn>=nn)&&sn<=an)))),[zt,an,sn,Xt,nn]),dn=Boolean(null==Ve?void 0:Ve.hideUpgradeOptions),cn=Boolean(!dn&&((null===(fe=null==Ve?void 0:Ve.upgrade)||void 0===fe?void 0:fe.isBuyMoreUses)||(null===(ge=null==Ve?void 0:Ve.upgrade)||void 0===ge?void 0:ge.isLinkToCustomURL)||(null===(ve=null==Ve?void 0:Ve.upgrade)||void 0===ve?void 0:ve.isUpgradeToAnotherGroup)&&(null===(he=Ve.upgrade.accessGroupIds)||void 0===he?void 0:he.length))),un=!dn&&(null===(be=null==Ve?void 0:Ve.upgrade)||void 0===be?void 0:be.isLinkToCustomURL)&&"string"==typeof Ve.upgrade.limitLink&&Ve.upgrade.limitLink.trim().length>0?Ve.upgrade.limitLink.trim():null,pn=un&&"string"==typeof(null===(xe=null==Ve?void 0:Ve.upgrade)||void 0===xe?void 0:xe.limitCTA)&&Ve.upgrade.limitCTA.trim().length>0?Ve.upgrade.limitCTA:(null==De?void 0:De["pricing.upgrade"])||(null==De?void 0:De.upgrade)||"Upgrade",mn=o.useMemo((()=>{var e,t,s;return!!qe&&(!!Ce&&(!Ot.isLoading&&(!((null!==(t=null===(e=Ot.data)||void 0===e?void 0:e.messages.length)&&void 0!==t?t:0)>1)&&(!!(null===(s=Ce.icebreakers)||void 0===s?void 0:s.length)&&(!Fe&&!Ms)))))}),[Ce,qe,Fe,Ms,Ot.data,Ot.isLoading]),fn=o.useMemo((()=>{if(ct||Ut)return!1;const e=Ds&&dt.length>0&&dt.every((e=>"finished"===e.status));return!(!wt.trim()&&!e)&&dt.every((e=>"finished"===e.status||e.isInsertedAsRaw))}),[Ds,ct,Ut,wt,dt]);o.useImperativeHandle(ie,(()=>({onSubmit:xn}))),o.useEffect((()=>{Be(mn)}),[mn]),o.useEffect((()=>{var e;if(z){const t=Array.from(st),s=null===(e=t[t.length-2].parts.find((e=>"text"===e.type)))||void 0===e?void 0:e.content;xn(s,!0)}}),[z]),o.useEffect((()=>{if(!ls.current||!se)return;const e=new ResizeObserver((e=>{for(const t of e)se(t.contentRect.height)}));return e.observe(ls.current),()=>{e.disconnect()}}),[se]),o.useEffect((()=>{if(!fs)return;const e=ts.current?`${ts.current} `:"";kt(`${e}${ms}`)}),[ms,fs]),o.useEffect((()=>{if(!os.current)return;(()=>{if(!os.current)return;let e=os.current.scrollHeight>52;wt.includes("\n")||dt.length?e=!0:wt.trim()||(e=!1),Et(e)})()}),[wt,dt]),o.useEffect((()=>{const e=os.current,t=as.current;if(!e||!t||Je||_t||wt.includes("\n"))return void Ct(!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=wt||Vs,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;Ct(r>l)}),[wt,_t,Vs,Je]);const gn=t=>e.__awaiter(void 0,void 0,void 0,(function*(){if(!(t=null!=t?t:ns.current))return!1;const e=Y(rs.current);try{return(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})},As&&{credentials:"include"}))).ok}catch(e){return console.warn("Failed to cancel submission",e),!1}})),vn=e=>{is.current=e,ds.current&&(ds.current.abort(),ds.current=null),ss.current&&(ss.current.cancel().catch((()=>{})),ss.current=null)},hn=t=>e.__awaiter(void 0,void 0,void 0,(function*(){const e=Date.now()+3e4;for(;Date.now()<e;){try{const e=yield fetch(`${process.env.NEXT_PUBLIC_PICKAXE_API2_URL}/response/status/${t}`,Object.assign({headers:Object.assign({"Cache-Control":"no-cache"},(!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}))},As&&{credentials:"include"}));if(e.ok){if((yield e.json()).terminal)return!0}}catch(e){console.warn("Failed to read submission status",e)}yield new Promise((e=>setTimeout(e,250)))}return!1})),bn=()=>{const e=ns.current;e&&!Ut&&!ct&&wt.trim()&&(qt((t=>{var s,n;return[...t,{id:H(),message:wt,predecessorSubmissionId:null!==(n=null===(s=t[t.length-1])||void 0===s?void 0:s.id)&&void 0!==n?n:e}]})),kt(""))},xn=(t,n=!1,i=!1,o,a=!1)=>e.__awaiter(void 0,void 0,void 0,(function*(){var e,l,d,c,u;if(!s.canChat(Ce))return;let p=null;try{if(nt&&!i||ct)return;const s=dt.filter((e=>"finished"===e.status&&!e.isInsertedAsRaw)),m=s.map((e=>e.documentId)).filter(Boolean),f=s.filter((e=>"image"===e.type)).map((e=>{const t=e.name.split(".").pop()||"";return{documentId:e.documentId,extension:t}})),g=null!=t?t:wt,v=null!==(l=null===(e=null==Ce?void 0:Ce.documentuploadtype)||void 0===e?void 0:e.startsWith("enduserupload"))&&void 0!==l&&l&&m.length>0;if(!g&&!v)return;at(""),ft(""),ot(null),kt(""),$e(!1),Pt(!1),rt("fetching"),ht(),xt();const h=n?st.slice(0,st.length-1):st,b=(e=>e.reduce(((e,t)=>Math.max(e,t.id)),0)+1)(h),x=b+(n?0:1),I={id:x,role:"assistant",parts:[],documentIds:[]},j=[...h,...n?[]:[{id:b,role:"user",parts:[{type:"text",content:g,isVisible:!0}],documentIds:v?m:[]}],I];it(j),xt(),v&&mt([]);const S=R.getPickaxeConfigMetadata(Ee),N=null!=o?o:H();p=N,ns.current=N,is.current=null,rs.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(Object.assign(Object.assign({supportsActionConfirmation:!0,selectedModel:ze||void 0,origin:Se,pickaxeId:Ne,sessionId:Oe,submissionId:N},a&&{interactionType:"steer"}),{senderType:ke,value:g}),v&&{documentIds:m}),we&&{sender:we}),Qe&&{studioSessionToken:Qe}),!Qe&&!we&&{sender:M.initializeEmbedUserId()}),Hs&&{portalId:Hs}),Ee&&{deploymentId:Ee}),S&&{metadata:S}),v&&f.length>0?{uploadedModelImages:f}:{})),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()})},As&&{credentials:"include"})),w=yield O.json();if(!w.success){if(w.limitData){const e=new Error(w.error||w.message||(null==De?void 0:De["failed-to-start-generation"])||"Failed to start generation");throw e.limitData=w.limitData,e}if(Fs(w))return;throw new Error(w.error||w.message||(null==De?void 0:De["failed-to-start-generation"])||"Failed to start generation")}lt(null!==(d=w.actionApprovalToken)&&void 0!==d?d:null);const k=null!==(c=w.submissionId)&&void 0!==c?c:N;p=k,ns.current=k;const _=()=>is.current===k;if(_())return;qs&&qe&&Oe&&cs.current.add(Oe);const E=Object.assign(Object.assign({},Ws()),{message:g,documentIds:v?m:[],uploadedModelImages:v?f:[],hasUploadedDocuments:v,isHidden:n,metadata:null!=S?S:null});Yt?(zs(),V.fireDeploymentFirstMessageSubmittedWebhook(E)):us.current=E,rt("streaming"),ds.current=new AbortController;const T=[];let C=[...null!=yt?yt:[]],U=0,A=!1,D="";for(;!A;)try{const e=yield fetch(`${process.env.NEXT_PUBLIC_PICKAXE_API2_URL}/response/stream/${k}?index=${U}`,{signal:null===(u=ds.current)||void 0===u?void 0:u.signal,headers:{"Cache-Control":"no-cache",Connection:"keep-alive"}});if(!e.body)throw new Error("No response body");const t=e.body.getReader();ss.current=t;const s=new TextDecoder,n=y.createParser({onEvent:e=>{var t,s;if(_())A=!0;else if(e.event&&"ping"!==e.event&&U++,"stop"!==e.event){if("error"===e.event){const t=JSON.parse(e.data);if(t.limitData)return ot(t.limitData),at(""),void(A=!0);const s=t.error||t.message||(null==De?void 0:De["something-went-wrong"])||"Something went wrong.";return Fs(t)||at(s),void(A=!0)}if("delta"===e.event){const n=JSON.parse(e.data);if("finish"===n.type)return void Pt(!0);if("data-error"===n.type&&ne){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 A=!0,ne({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 A=!0,ne({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 A=!0,ne({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 A=!0,ne({provider:"composio",toolkitSlug:t.toolkitSlug,serverId:t.serverId,name:t.name}),new Error("STOP_STREAM")}}else if("text-start"===n.type)D="",T.push({type:"text",content:"",isVisible:null===(t=n.isVisible)||void 0===t||t});else if("text-delta"===n.type)D+=n.delta,r.updateStreamTextPart(T,"text",D);else if("text-end"===n.type)D="";else if("reasoning-start"===n.type)D="",T.push({type:"reasoning",content:"",isVisible:null===(s=n.isVisible)||void 0===s||s});else if("reasoning-delta"===n.type)D+=n.delta,r.updateStreamTextPart(T,"reasoning",D);else if("reasoning-end"===n.type)D="";else if(n.type.startsWith("data-")){const e=n;"data-action-approval"===e.type?r.upsertActionApprovalPart(T,e.data):T.push({type:e.type,content:JSON.stringify(e.data),isVisible:!0})}rs.current=Y(T);const i=Y(T);it((e=>{const t=e.findIndex((e=>e.id===x)),s=Object.assign(Object.assign({},I),{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);C=C.filter((e=>!(e.id===t.id&&e.version===t.version))),C.push(Object.assign(Object.assign({},t),{content:"",status:"streaming"})),jt([...C]),It.startsWith("inline")||St({id:t.id,version:t.version})}else if("artifact_updated"===e.event){const t=JSON.parse(e.data);C=C.filter((e=>!(e.id===t.id&&e.version===t.version))),C.push(Object.assign(Object.assign({},t),{content:"",status:"updating"})),jt(C),It.startsWith("inline")||St({id:t.id,version:t.version})}else if("artifact_rewrite"===e.event){const t=JSON.parse(e.data);C=C.filter((e=>!(e.id===t.id&&e.version===t.version))),C.push(Object.assign(Object.assign({},t),{content:"",status:"streaming"})),jt(C),It.startsWith("inline")||St({id:t.id,version:t.version})}else if("artifact_content"===e.event){const t=JSON.parse(e.data),s=t.token.replace(/\u200B/g,"");C=C.map((e=>e.id===t.id&&e.version===t.version?Object.assign(Object.assign({},e),{content:e.content+s,status:"streaming"}):e)),jt(C)}else if("artifact_finished"===e.event){const t=JSON.parse(e.data);jt(C.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 ot(t.limitData),at(""),void(A=!0);const s=t.error||t.message||(null==De?void 0:De["something-went-wrong-try-again"])||"Something went wrong, please try again.";if(Fs(t))return void(A=!0);at(s)}else"stop"===e.event&&(A=!0)}else A=!0}});for(;;){if(_()){A=!0,t.cancel().catch((()=>{}));break}const{value:e,done:i}=yield t.read();if(_()){A=!0,t.cancel().catch((()=>{}));break}if(i)break;n.feed(s.decode(e))}A||_()||(yield new Promise((e=>setTimeout(e,1e3))))}catch(e){if("STOP_STREAM"===e.message||W(e)||_())return void(A=!0);console.warn("Stream connection lost, retrying...",e),yield new Promise((e=>setTimeout(e,1e3)))}null==We||We(Oe)}catch(e){if(W(e))return;if(e.limitData)ot(e.limitData),at("");else{let t=D.default(e)||"";t&&!t.includes("Unexpected token 'A',")||(t=(null==De?void 0:De["high-traffic-try-again-later"])||"Oops! We're experiencing high traffic at the moment. Please try again later."),Fs(t)||at(t)}}finally{const e=!p||ns.current===p;xt(),e&&(rt("idle"),bt(),ss.current=null),p&&e&&(ns.current=null,rs.current=[]),yield Bs()}}));return o.useEffect((()=>{if(nt||Ut||Mt||0===Lt.length)return;const t=Lt[0];Rt(!0),Vt(t.id),e.__awaiter(void 0,void 0,void 0,(function*(){try{if(!(yield hn(t.predecessorSubmissionId)))return void at((null==De?void 0:De["queued-message-waiting"])||"A queued message is waiting for the previous response to finish.");qt((e=>e.filter((e=>e.id!==t.id)))),yield xn(t.message,!1,!0,t.id)}finally{Rt(!1),Vt(null)}}))}),[nt,Mt,Ut,Lt]),Rs?null:t.jsx("div",Object.assign({className:q.default("flex w-full flex-shrink-0 flex-col items-center",!Ms&&"px-4 pb-8"),dir:Me?"rtl":"ltr"},{children:t.jsxs("div",Object.assign({className:"flex w-full max-w-[800px] flex-col"},{children:[Lt.length>0&&t.jsx("div",Object.assign({className:"mx-3 -mb-3 overflow-hidden border pb-3",style:{borderColor:Ae.text+"18",backgroundColor:null!==(ye=Es.backgroundColor)&&void 0!==ye?ye:Ae.text+"08",color:Ae.text,borderTopLeftRadius:Math.max(Ue.cornerRadius-4,12),borderTopRightRadius:Math.max(Ue.cornerRadius-4,12)}},{children:Lt.map(((s,n)=>{var i;return t.jsxs("div",Object.assign({className:"flex min-h-10 items-center gap-2 px-3 py-2",style:n<Lt.length-1?{borderBottom:`1px solid ${Ae.text}12`}:void 0},{children:[t.jsx(N.default,{className:"h-4 w-4 shrink-0 opacity-50","aria-hidden":"true"}),t.jsx("span",Object.assign({className:"min-w-0 flex-1 truncate text-sm",title:s.message},{children:s.message})),$t===s.id||Ft===s.id?t.jsxs("span",Object.assign({className:"flex shrink-0 items-center gap-1.5 px-2 py-1 text-xs opacity-60","aria-live":"polite"},{children:[t.jsx("span",{className:"h-3 w-3 animate-spin rounded-full border border-current border-r-transparent","aria-hidden":"true"}),$t===s.id?(null==De?void 0:De.steering)||"Steering...":(null==De?void 0:De.starting)||"Starting..."]})):t.jsxs(t.Fragment,{children:[t.jsxs("button",Object.assign({type:"button",className:"shrink-0 rounded-md px-2 py-1 text-xs font-medium opacity-70 transition-opacity hover:opacity-100 disabled:cursor-default disabled:opacity-40",disabled:Ut||!nt,onClick:()=>{(t=>{e.__awaiter(void 0,void 0,void 0,(function*(){const e=ns.current;if(!e||Ut)return;const s=Lt.findIndex((e=>e.id===t.id));if(-1===s)return;At(!0),Bt(t.id),at(""),vn(e);let n=!1;try{if(!(yield gn(e)))throw new Error((null==De?void 0:De["failed-to-interrupt-current-response"])||"Failed to interrupt the current response.");if(!(yield hn(e)))throw new Error((null==De?void 0:De["current-response-still-stopping"])||"The current response is still stopping. Please send your message again in a moment.");rt("idle"),qt((e=>e.filter((e=>e.id!==t.id)))),n=!0,At(!1),Bt(null),yield xn(t.message,!1,!0,t.id,!0)}catch(e){rt("idle"),n&&qt((e=>{if(e.some((e=>e.id===t.id)))return e;const n=[...e];return n.splice(s,0,t),n})),at(D.default(e))}finally{At(!1),Bt(null)}}))})(s)},"aria-label":`${(null==De?void 0:De["steer-with"])||"Steer with"}: ${s.message}`},{children:[t.jsx("span",Object.assign({"aria-hidden":"true"},{children:"↳ "})),(null==De?void 0:De.steer)||"Steer"]})),t.jsx("button",Object.assign({type:"button",className:"flex h-7 w-7 shrink-0 items-center justify-center rounded-md opacity-50 transition-opacity hover:opacity-100 disabled:cursor-default disabled:opacity-30",disabled:Ut,onClick:()=>{return e=s.id,void qt((t=>K(t,e)));var e},"aria-label":`${(null==De?void 0:De["remove-queued-message"])||"Remove queued message"}: ${s.message}`},{children:t.jsx(w.default,{className:"h-4 w-4","aria-hidden":"true"})})),t.jsxs(C.default,Object.assign({id:`queued-message-menu-${s.id}`,className:"shrink-0"},{children:[t.jsx(U.default,Object.assign({className:"flex h-7 w-7 items-center justify-center rounded-md opacity-50 transition-opacity hover:opacity-100",isDisabled:Ut,role:"button",tabIndex:Ut?-1:0,"aria-haspopup":"menu","aria-label":(null==De?void 0:De["more-options"])||"More options",onKeyDown:e=>{"Enter"!==e.key&&" "!==e.key||(e.preventDefault(),e.currentTarget.click())}},{children:t.jsxs("svg",Object.assign({viewBox:"0 0 24 24",className:"h-4 w-4",fill:"currentColor","aria-hidden":"true"},{children:[t.jsx("circle",{cx:"5",cy:"12",r:"1.6"}),t.jsx("circle",{cx:"12",cy:"12",r:"1.6"}),t.jsx("circle",{cx:"19",cy:"12",r:"1.6"})]}))})),t.jsx(A.default,Object.assign({role:"menu",align:Me?"bottom-start":"bottom-end",positionStrategy:Re?"absolute":"fixed",width:"auto",className:"p-1 text-sm shadow-xl",style:{backgroundColor:null!==(i=Es.backgroundColor)&&void 0!==i?i:Ae.primary,color:Ae.text,borderRadius:"12px"},border:`1px solid ${Ae.text}20`},{children:t.jsxs("button",Object.assign({type:"button",role:"menuitem",className:"flex min-w-36 items-center gap-2 rounded-lg px-3 py-2 text-left transition-colors hover:bg-black/5 dark:hover:bg-white/10",onClick:()=>(e=>{qt((t=>K(t,e.id))),kt(e.message),requestAnimationFrame((()=>{const t=os.current;t&&(t.focus(),t.setSelectionRange(e.message.length,e.message.length))}))})(s)},{children:[t.jsx(k.default,{className:"h-4 w-4 shrink-0"}),(null==De?void 0:De["edit-message"])||"Edit message"]}))}))]}))]})]}),s.id)}))})),t.jsxs("div",Object.assign({ref:ls,className:q.default("relative z-10 flex flex-col w-full justify-end gap-y-3 py-[3px]","block"===Ue.formFieldStyle&&"shadow"),style:Object.assign(Object.assign({},Es),{maxHeight:`${ps}px`,overflowY:"auto"})},{children:[ln&&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:Es.backgroundColor?`${Es.backgroundColor}E6`:void 0,borderColor:Ae.text+"20",color:Ae.text,borderTopRightRadius:Ue.cornerRadius+"px",borderTopLeftRadius:Ue.cornerRadius+"px"}},{children:[t.jsx("div",Object.assign({className:"flex items-center gap-2 text-sm font-medium"},{children:t.jsxs("span",{children:[sn.toLocaleString()," ",Gs?(null==De?void 0:De.credits)||"Credits":(null==De?void 0:De.uses)||"Uses"," ",(null==De?void 0:De.remaining)||"remaining"]})})),t.jsxs("div",Object.assign({className:"flex items-center gap-3"},{children:[cn&&t.jsx("button",Object.assign({className:"rounded-md px-3 py-1.5 text-xs font-semibold transition-opacity hover:opacity-90",style:{backgroundColor:Ae.accent,color:Ae.accentText},onClick:e=>{if(e.preventDefault(),e.stopPropagation(),un)return void window.open(un,"_blank","noopener,noreferrer");if(Ye)return void Ye();const t=M.buildUpgradeUrl({baseUrl:Gt,accessGroupId:null==Ve?void 0:Ve.accessGroupId});t&&M.openAuthenticatedPricingUrl({deploymentId:Ee,pricingUrl:t,studioId:null==Ce?void 0:Ce.studioid,studioSessionToken:Qe})}},{children:pn})),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:()=>Jt(!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"})}))}))]}))]})),!nt&&dt.length>0&&t.jsx(_.default,{className:"p-4 pb-0",isDisabled:nt}),t.jsxs("div",Object.assign({className:"relative flex w-full flex-col"},{children:[Ls&&t.jsxs("div",Object.assign({className:q.default(Je?"top-6":"top-1/2","pointer-events-none absolute z-10 flex -translate-y-1/2 select-none items-center gap-x-2",Me?"right-4":"left-4")},{children:[t.jsx("span",{className:"h-2 w-2 animate-pulse rounded-full bg-c-secondary",style:{backgroundColor:null!==(Ie=Ae.accent)&&void 0!==Ie?Ie:"#ff0000"}}),t.jsx("span",Object.assign({className:"text-sm text-c-secondary font-semilight",style:{color:Ae.text+"90"}},{children:(null==De?void 0:De.listening)||"Listening..."}))]})),t.jsx(E.default,Object.assign({ref:os,className:q.default(_s.i1,"py-3.5 max-h-60 px-4 w-full border-transparent bg-transparent",!wt.trim()&&!wt.includes("\n")&&"overflow-hidden text-ellipsis whitespace-nowrap placeholder:whitespace-normal placeholder:overflow-visible",Me?"text-right":"text-left",!Je&&$s&&"mb-12"),value:wt,placeholder:Ls?"":Vs,onChange:e=>{kt(e)},onKeyDown:e=>{Le||vt||"Enter"===e.key&&(e.shiftKey||(e.preventDefault(),ct||Ut||(nt?bn():xn())))},onPaste:t=>e.__awaiter(void 0,void 0,void 0,(function*(){const e=Array.from(t.clipboardData.files||[]);if(e.length>0){if(!Ds)return;t.preventDefault(),$e(!1),yield pt(e)}}))},ee&&{onFocus:ee},te&&{onBlur:te},{dir:Me?"rtl":"ltr"})),t.jsxs("div",Object.assign({ref:as,className:Je?"relative flex w-full items-center gap-2 px-3 pb-2 [&>button]:shrink-0 [&>button]:mr-0":q.default("flex items-center gap-2 absolute z-2 transition-all duration-200 ease-in-out",$s?"bottom-3 right-2":"right-0 top-1/2 -translate-y-1/2"),style:Object.assign(Object.assign({},!$s&&Es.backgroundColor&&{backgroundColor:Es.backgroundColor}),{borderTopRightRadius:Ue.cornerRadius+"px",borderBottomRightRadius:Ue.cornerRadius+"px"})},{children:[!nt&&!fs&&Ds&&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:Ss?Ae.accent+"10":void 0,color:Ss?Ae.accent:Ae.accent+"80"},disabled:ct||nt,"aria-label":null!==(je=null==De?void 0:De["attach-files"])&&void 0!==je?je:"Attach files",onClick:()=>{var e;return null===(e=es.current)||void 0===e?void 0:e.click()}},Ns,{children:[t.jsx("input",{id:"file-upload",ref:es,type:"file",accept:[...x.allowedFileMimeTypes,...x.allowedImageMimeTypes,...x.additionalAllowedFileExtensions].join(", "),multiple:!0,hidden:!0,className:"hidden",onChange:t=>e.__awaiter(void 0,void 0,void 0,(function*(){$e(!1),yield pt(Array.from(t.target.files||[])),t.target.value=""}))}),t.jsx(I.default,{className:"h-6 w-6 shrink-0"})]})),t.jsx(i.default,{compact:!0}),nt&&!Dt?t.jsxs(t.Fragment,{children:[t.jsx("button",Object.assign({"aria-label":(null==De?void 0:De["stop-response"])||"Stop response",className:"flex h-8 w-8 items-center justify-center rounded-full outline-none transition-colors duration-200 ease-in-out",onClick:()=>{const e=ns.current;e&&(vn(e),gn(e)),rt("idle")},style:{backgroundColor:Ae.accent+"10",color:Ae.accent}},{children:t.jsx(O.default,{className:"h-4 w-4 shrink-0"})})),t.jsx("button",Object.assign({"aria-label":(null==De?void 0:De["queue-message"])||"Queue message",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",disabled:Ut||ct||!wt.trim(),onClick:bn,style:{backgroundColor:wt.trim()?Ae.accent:Ae.accent+"10",color:wt.trim()?Ae.accentText:Ae.accent+"80"}},{children:t.jsx(j.default,{className:q.default("h-6 w-6 shrink-0",Me&&"scale-x-[-1] transform")})}))]}):fs?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:bs,style:{backgroundColor:Ae.accent,color:Ae.accentText}},{children:t.jsx(O.default,{className:"h-4 w-4 shrink-0"})})):t.jsxs(t.Fragment,{children:[Ps&&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:fs?Ae.accent:ws?Ae.accent+"10":void 0,color:fs?Ae.accentText:ws?Ae.accent:Ae.accent+"80"},disabled:ct||nt||gs,onClick:()=>{fs?bs():(ts.current=wt,hs(Pe||"en-US"))}},ks,{children:t.jsx(S.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:ys||fn?Ae.accent:Ae.accent+"10",color:ys||fn?Ae.accentText:Ae.accent+"80"},disabled:!fn,onClick:()=>xn()},Is,{children:t.jsx(j.default,{className:q.default("h-6 w-6 shrink-0",Me&&"scale-x-[-1] transform")})}))]})]}))]}))]})),ut&&t.jsx(T.default,{error:ut,className:"mt-3"})]}))}))}));ee.displayName="Input",exports.default=ee;
|
|
1
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e=require("../../../_virtual/_tslib.js"),t=require("react/jsx-runtime"),s=require("../../../common/canChat.js"),n=require("../../../hooks/pickaxe/useEndUserModel.js"),i=require("../common/EndUserModelPicker.js"),r=require("../../../common/actionApproval.js"),o=require("react"),a=require("../../../hooks/pickaxe/usePickaxeContext.js"),l=require("../../../hooks/pickaxe/useResponseContext.js"),d=require("../../../hooks/studio/useStyleInput.js"),c=require("../../../hooks/studio/useStyleFontSize.js"),u=require("../../../hooks/pickaxe/useConversation.js"),p=require("../../../hooks/pickaxe/useDimensionContext.js"),m=require("../Addons/Auth/hooks/useAuthContext.js"),f=require("../Addons/Document/hooks/useDocument.js"),g=require("../Addons/Scroll/hooks/useScroll.js"),v=require("../Addons/Artifact/hooks/useArtifactContext.js"),h=require("../../../hooks/core/useHover.js"),b=require("../../../hooks/core/useMediaQuery.js"),x=require("../../../common/documents.js"),y=require("eventsource-parser"),I=require("../../Icons/attach-vertical.svg.js"),j=require("../../Icons/arrow-right.svg.js"),S=require("../../Icons/microphone.svg.js"),N=require("../../Icons/message-clock.svg.js"),O=require("../../Icons/stop.svg.js"),w=require("../../Icons/trash.svg.js"),k=require("../../Icons/pencil.svg.js"),_=require("../Addons/Document/List.js"),E=require("../../Core/Textarea.js"),T=require("../../Core/ErrorAlert.js"),C=require("../../Core/Menu/index.js"),U=require("../../Core/Menu/Button.js"),A=require("../../Core/Menu/List.js"),D=require("../../../common/error.js"),P=require("../../../common/api/pickaxe.js"),L=require("../../../common/validation.js"),q=require("../../../common/cn.js"),M=require("../../../common/utils.js"),R=require("../../../common/pickaxeConfig.js"),F=require("../../../common/agentPrefill.js"),V=require("../../../common/deploymentWebhooks.js"),$=require("../../../hooks/studio/useStudio.js"),B=require("../../../hooks/pickaxe/useSpeechToText.js"),X=require("../common/PickaxeCommon.js");const K=(e,t)=>{const s=e.find((e=>e.id===t));return s?e.filter((e=>e.id!==t)).map((e=>e.predecessorSubmissionId===t?Object.assign(Object.assign({},e),{predecessorSubmissionId:s.predecessorSubmissionId}):e)):e},G=e=>"string"==typeof e&&e.trim().length>0,H=()=>"undefined"!=typeof crypto&&"randomUUID"in crypto?crypto.randomUUID():`submission-${Date.now()}-${Math.random().toString(36).slice(2)}`,Y=e=>e.map((e=>Object.assign({},e))),W=e=>e instanceof Error&&("AbortError"===e.name||"BodyStreamBuffer was aborted"===e.message),z=(e,t)=>{if(e&&"object"==typeof e)return e[t]},J=(e,t)=>{const s=z(e,t);return G(s)?s:null},Q=e=>{const t=Number(e);return Number.isFinite(t)?t:void 0},Z=({studioUser:e,deploymentId:t,portalId:s})=>{var n,i;const r=Array.isArray(z(e,"uses"))?z(e,"uses"):[],o=(({deploymentId:e,portalId:t})=>G(e)?{type:"deployment",id:e}:G(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}},ee=o.forwardRef((({resubmitPrompt:z,onFocus:ee,onBlur:te,onInputHeightChange:se,initSmitheryAuthData:ne},ie)=>{var re,oe,ae,le,de,ce,ue,pe,me,fe,ge,ve,he,be,xe,ye,Ie,je;const{origin:Se,pickaxeId:Ne,sessionId:Oe,sender:we,senderType:ke,portalId:_e,deploymentId:Ee,deploymentType:Te,pickaxe:Ce,styles:Ue,colors:Ae,translations:De,locale:Pe,forceMobile:Le,isNewChat:qe,isRtl:Me,isEmbed:Re,isShowFeedbackMessage:Fe,accessGroup:Ve,setIsNewChat:$e,setIsShowIceBreaker:Be,setValidationStatus:Xe,setValidationUpgradeGroups:Ke,setValidationUpgradeUrl:Ge,setAccessGroup:He,onUpgrade:Ye,onGenerateComplete:We}=a.usePickaxeContext(),{value:ze,enabled:Je}=n.useEndUserModel(),{token:Qe,isLoggedOut:Ze,isSent:et,isPricingAuth:tt}=m.useAuthContext(),{messages:st,isGenerating:nt,setMessages:it,setStatus:rt,setLimitData:ot,setError:at,setActionApprovalToken:lt}=l.useResponseContext(),{documents:dt,isUploading:ct,documentError:ut,onFileUpload:pt,setDocuments:mt,setDocumentError:ft}=f.useDocument(),{studio:gt}=$.useStudio(),[vt]=b.useMediaQuery("(max-width: 480px)"),{scrollStartSession:ht,scrollEndSession:bt,scrollToBottom:xt}=g.useScroll({auto:!0,smooth:!(Le||vt)}),{artifacts:yt,currentPopupType:It,setArtifacts:jt,setCurrentArtifact:St}=v.useArtifactContext(),{height:Nt}=p.useDimensionContext(),Ot=u.useConversation(),[wt,kt]=o.useState((()=>F.readAgentPrefill([Ee,Ne]).chatInput)),[_t,Et]=o.useState(!1),[Tt,Ct]=o.useState(!1),[Ut,At]=o.useState(!1),[Dt,Pt]=o.useState(!1),[Lt,qt]=o.useState([]),[Mt,Rt]=o.useState(!1),[Ft,Vt]=o.useState(null),[$t,Bt]=o.useState(null),[Xt,Kt]=o.useState(null),[Gt,Ht]=o.useState(null),[Yt,Wt]=o.useState(!1),[zt,Jt]=o.useState(!1),[Qt,Zt]=o.useState(0),es=o.useRef(null),ts=o.useRef(""),ss=o.useRef(null),ns=o.useRef(null),is=o.useRef(null),rs=o.useRef([]),os=o.useRef(null),as=o.useRef(null),ls=o.useRef(null),ds=o.useRef(null),cs=o.useRef(new Set),us=o.useRef(null),ps=Math.max(.4*Nt,100),{speechTranscript:ms,isSpeechListening:fs,isSpeechProcessing:gs,isSpeechSupported:vs,onStartListening:hs,onStopListening:bs}=B.useSpeechToText(),xs=h.useHover(),{isHover:ys}=xs,Is=e.__rest(xs,["isHover"]),js=h.useHover(),{isHover:Ss}=js,Ns=e.__rest(js,["isHover"]),Os=h.useHover(),{isHover:ws}=Os,ks=e.__rest(Os,["isHover"]),_s=c.useStyleFontSize(),Es=d.useStyleInput(),Ts="undefined"!=typeof window?window.location.hostname:"",Cs="undefined"!=typeof window?window.location.href:"",Us="undefined"!=typeof window&&window.self!==window.top,As=Ts.includes("pickaxe.co")&&!Cs.includes("https://studio.pickaxe.co/_embed")&&!Us,Ds=null!==(oe=null===(re=null==Ce?void 0:Ce.documentuploadtype)||void 0===re?void 0:re.startsWith("enduserupload"))&&void 0!==oe&&oe,Ps=vs&&(null==Ce?void 0:Ce.enablevoicetotext),Ls=fs&&!wt.trim(),qs=G(Ee),Ms="chat-input"===Te&&qe&&!et,Rs="chat-input"===Te&&tt&&Ze&&et,Fs=o.useCallback((e=>{const t=L.getValidationFailure(e);return!!t&&(at(""),ot(null),Xe(t.status),He(t.accessGroup),Ke(t.upgradeGroups),Ge(t.upgradeUrl),!0)}),[at,lt,ot,Xe,Ke,Ge,He]),Vs=null!==(ae=null==Ce?void 0:Ce.placeholdertext)&&void 0!==ae?ae:Me?"بماذا تريد أن تتحدث؟":(null==De?void 0:De["what-do-you-want-to-talk-about"])||"What do you want to talk about?",$s=_t||Tt,Bs=o.useCallback((()=>e.__awaiter(void 0,void 0,void 0,(function*(){Wt(!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==Ce?void 0:Ce.studioid},Qe?{studioSessionToken:Qe}:we?{sender:we}:{sender:M.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}})),As&&{credentials:"include"})),t=yield e.json();(null==t?void 0:t.studioUser)&&(Kt(t.studioUser),Ht(t.url))}catch(e){console.error("Failed to fetch studio user:",e)}finally{Wt(!0)}}))),[As,null==Ce?void 0:Ce.studioid,we,Qe]);o.useEffect((()=>{Bs()}),[Bs]);const Xs=Number(null!==(le=null==Ve?void 0:Ve.limit)&&void 0!==le?le:0),Ks="string"==typeof(null==Ve?void 0:Ve.limitInterval)?Ve.limitInterval:null,Gs=!!(null==gt?void 0:gt.data.usage)&>.data.usage.isCredits,Hs=o.useMemo((()=>{var e,t,s,n,i;return null!==(i=null!==(n=null!==(s=null!==(t=null!==(e=null!=_e?_e:J(Xt,"portalId"))&&void 0!==e?e:J(Xt,"portalid"))&&void 0!==t?t:J(Ve,"portalId"))&&void 0!==s?s:J(Ve,"portalid"))&&void 0!==n?n:J(Ce,"portalId"))&&void 0!==i?i:J(Ce,"portalid")}),[Ve,_e,Ce,Xt]),Ys=o.useMemo((()=>Z({studioUser:Xt,deploymentId:Ee,portalId:Hs})),[Ee,Hs,Xt]);o.useEffect((()=>{qs&&qe&&Oe&&cs.current.add(Oe)}),[qe,Oe,qs]);const Ws=o.useCallback((()=>{var e,t,s;return{studioId:null==Ce?void 0:Ce.studioid,userEmail:J(Xt,"email"),userId:null!==(e=J(Xt,"userId"))&&void 0!==e?e:J(Xt,"userid"),sessionId:Oe,deploymentId:Ee,deploymentType:Te,portalId:Hs,accessGroupId:null!==(t=null==Ve?void 0:Ve.accessGroupId)&&void 0!==t?t:null,pickaxeId:Ne,sender:we,senderType:ke,origin:Se,metadata:null!==(s=R.getPickaxeConfigMetadata(Ee))&&void 0!==s?s:null}}),[null==Ve?void 0:Ve.accessGroupId,Ee,Te,Se,null==Ce?void 0:Ce.studioid,Ne,Hs,we,ke,Oe,Xt]),zs=o.useCallback((()=>!!(qs&&Yt&&Oe)&&(!!cs.current.has(Oe)&&(V.fireDeploymentSessionInitializedWebhook(Ws()),cs.current.delete(Oe),!0))),[Ws,Yt,Oe,qs]);o.useEffect((()=>{if(!Yt||!Oe)return;zs();const e=us.current;(null==e?void 0:e.sessionId)===Oe&&(V.fireDeploymentFirstMessageSubmittedWebhook(Object.assign(Object.assign(Object.assign({},e),Ws()),{message:e.message,documentIds:e.documentIds,uploadedModelImages:e.uploadedModelImages,hasUploadedDocuments:e.hasUploadedDocuments,isHidden:e.isHidden})),us.current=null)}),[zs,Ws,Yt,Oe]);const Js={currentUses:Q(null==Xt?void 0:Xt.currentUses),extraUses:Q(null==Xt?void 0:Xt.extraUses)},Qs=Ys.scope?{currentUses:null!==(ce=Q(null===(de=Ys.record)||void 0===de?void 0:de.currentUses))&&void 0!==ce?ce:0,extraUses:null!==(pe=Q(null===(ue=Ys.record)||void 0===ue?void 0:ue.extraUses))&&void 0!==pe?pe:0}:{currentUses:0,extraUses:0},Zs=J(Xt,"type"),en="guest"===Zs||!Zs&&Ze?Qs:Js;o.useEffect((()=>{let t=!0;return e.__awaiter(void 0,void 0,void 0,(function*(){var e;if(Gs&&(null===(e=null==gt?void 0:gt.data)||void 0===e?void 0:e.workspaceId))try{const e=yield P.pickaxeApi2.get(`/cost_per_run?workspaceId=${gt.data.workspaceId}`,{withCredentials:!1});t&&Zt(1e4*(Number(e.data.costPerRun)||0))}catch(e){console.error("Failed to fetch average cost per run:",e),t&&Zt(0)}else t&&Zt(0)})),()=>{t=!1}}),[Gs,null===(me=null==gt?void 0:gt.data)||void 0===me?void 0:me.workspaceId]);const tn=(({accessGroupType:e,currentUses:t,extraUses:s,limit:n,limitInterval:i})=>{const r=Number(null!=t?t:0),o=Number(null!=s?s:0);return"public"===e&&"one_time"===i?n===X.STUDIO_INFINITY_VALUE?X.STUDIO_INFINITY_VALUE:Math.max(0,n-r):n===X.STUDIO_INFINITY_VALUE||o===X.STUDIO_INFINITY_VALUE?X.STUDIO_INFINITY_VALUE:"one_time"===i?Math.max(0,o):Math.max(0,n-r)+o})({accessGroupType:null==Ve?void 0:Ve.type,currentUses:en.currentUses,extraUses:en.extraUses,limit:Xs,limitInterval:Ks}),sn=tn===X.STUDIO_INFINITY_VALUE?X.STUDIO_INFINITY_VALUE:Math.max(0,Math.ceil(tn)),nn=(({accessGroupType:e,extraUses:t,limit:s,limitInterval:n})=>{const i=Number(null!=t?t:0);return"public"===e&&"one_time"===n?s===X.STUDIO_INFINITY_VALUE?X.STUDIO_INFINITY_VALUE:Math.max(0,s):s===X.STUDIO_INFINITY_VALUE||i===X.STUDIO_INFINITY_VALUE?X.STUDIO_INFINITY_VALUE:"one_time"===n?Math.max(0,i):Math.max(0,s)+Math.max(0,i)})({accessGroupType:null==Ve?void 0:Ve.type,extraUses:en.extraUses,limit:Xs,limitInterval:Ks}),rn=nn===X.STUDIO_INFINITY_VALUE?X.STUDIO_INFINITY_VALUE:Math.ceil(.05*nn),on=Gs?Math.ceil(5*Qt):5,an=rn===X.STUDIO_INFINITY_VALUE?X.STUDIO_INFINITY_VALUE:Math.max(rn,on),ln=o.useMemo((()=>!!Xt&&(!zt&&(sn!==X.STUDIO_INFINITY_VALUE&&(!(nn<=0||sn>=nn)&&sn<=an)))),[zt,an,sn,Xt,nn]),dn=Boolean(null==Ve?void 0:Ve.hideUpgradeOptions),cn=Boolean(!dn&&((null===(fe=null==Ve?void 0:Ve.upgrade)||void 0===fe?void 0:fe.isBuyMoreUses)||(null===(ge=null==Ve?void 0:Ve.upgrade)||void 0===ge?void 0:ge.isLinkToCustomURL)||(null===(ve=null==Ve?void 0:Ve.upgrade)||void 0===ve?void 0:ve.isUpgradeToAnotherGroup)&&(null===(he=Ve.upgrade.accessGroupIds)||void 0===he?void 0:he.length))),un=!dn&&(null===(be=null==Ve?void 0:Ve.upgrade)||void 0===be?void 0:be.isLinkToCustomURL)&&"string"==typeof Ve.upgrade.limitLink&&Ve.upgrade.limitLink.trim().length>0?Ve.upgrade.limitLink.trim():null,pn=un&&"string"==typeof(null===(xe=null==Ve?void 0:Ve.upgrade)||void 0===xe?void 0:xe.limitCTA)&&Ve.upgrade.limitCTA.trim().length>0?Ve.upgrade.limitCTA:(null==De?void 0:De["pricing.upgrade"])||(null==De?void 0:De.upgrade)||"Upgrade",mn=o.useMemo((()=>{var e,t,s;return!!qe&&(!!Ce&&(!Ot.isLoading&&(!((null!==(t=null===(e=Ot.data)||void 0===e?void 0:e.messages.length)&&void 0!==t?t:0)>1)&&(!!(null===(s=Ce.icebreakers)||void 0===s?void 0:s.length)&&(!Fe&&!Ms)))))}),[Ce,qe,Fe,Ms,Ot.data,Ot.isLoading]),fn=o.useMemo((()=>{if(ct||Ut)return!1;const e=Ds&&dt.length>0&&dt.every((e=>"finished"===e.status));return!(!wt.trim()&&!e)&&dt.every((e=>"finished"===e.status||e.isInsertedAsRaw))}),[Ds,ct,Ut,wt,dt]);o.useImperativeHandle(ie,(()=>({onSubmit:xn}))),o.useEffect((()=>{Be(mn)}),[mn]),o.useEffect((()=>{var e;if(z){const t=Array.from(st),s=null===(e=t[t.length-2].parts.find((e=>"text"===e.type)))||void 0===e?void 0:e.content;xn(s,!0)}}),[z]),o.useEffect((()=>{if(!ls.current||!se)return;const e=new ResizeObserver((e=>{for(const t of e)se(t.contentRect.height)}));return e.observe(ls.current),()=>{e.disconnect()}}),[se]),o.useEffect((()=>{if(!fs)return;const e=ts.current?`${ts.current} `:"";kt(`${e}${ms}`)}),[ms,fs]),o.useEffect((()=>{if(!os.current)return;(()=>{if(!os.current)return;let e=os.current.scrollHeight>52;wt.includes("\n")||dt.length?e=!0:wt.trim()||(e=!1),Et(e)})()}),[wt,dt]),o.useEffect((()=>{const e=os.current,t=as.current;if(!e||!t||Je||_t||wt.includes("\n"))return void Ct(!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=wt||Vs,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;Ct(r>l)}),[wt,_t,Vs,Je]);const gn=t=>e.__awaiter(void 0,void 0,void 0,(function*(){if(!(t=null!=t?t:ns.current))return!1;const e=Y(rs.current);try{return(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})},As&&{credentials:"include"}))).ok}catch(e){return console.warn("Failed to cancel submission",e),!1}})),vn=e=>{is.current=e,ds.current&&(ds.current.abort(),ds.current=null),ss.current&&(ss.current.cancel().catch((()=>{})),ss.current=null)},hn=t=>e.__awaiter(void 0,void 0,void 0,(function*(){const e=Date.now()+3e4;for(;Date.now()<e;){try{const e=yield fetch(`${process.env.NEXT_PUBLIC_PICKAXE_API2_URL}/response/status/${t}`,Object.assign({headers:Object.assign({"Cache-Control":"no-cache"},(!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}))},As&&{credentials:"include"}));if(e.ok){if((yield e.json()).terminal)return!0}}catch(e){console.warn("Failed to read submission status",e)}yield new Promise((e=>setTimeout(e,250)))}return!1})),bn=()=>{const e=ns.current;e&&!Ut&&!ct&&wt.trim()&&(qt((t=>{var s,n;return[...t,{id:H(),message:wt,predecessorSubmissionId:null!==(n=null===(s=t[t.length-1])||void 0===s?void 0:s.id)&&void 0!==n?n:e}]})),kt(""))},xn=(t,n=!1,i=!1,o,a=!1)=>e.__awaiter(void 0,void 0,void 0,(function*(){var e,l,d,c,u;if(!s.canChat(Ce))return;let p=null;try{if(nt&&!i||ct||fs||gs)return;const s=dt.filter((e=>"finished"===e.status&&!e.isInsertedAsRaw)),m=s.map((e=>e.documentId)).filter(Boolean),f=s.filter((e=>"image"===e.type)).map((e=>{const t=e.name.split(".").pop()||"";return{documentId:e.documentId,extension:t}})),g=null!=t?t:wt,v=null!==(l=null===(e=null==Ce?void 0:Ce.documentuploadtype)||void 0===e?void 0:e.startsWith("enduserupload"))&&void 0!==l&&l&&m.length>0;if(!g&&!v)return;at(""),ft(""),ot(null),kt(""),$e(!1),Pt(!1),rt("fetching"),ht(),xt();const h=n?st.slice(0,st.length-1):st,b=(e=>e.reduce(((e,t)=>Math.max(e,t.id)),0)+1)(h),x=b+(n?0:1),I={id:x,role:"assistant",parts:[],documentIds:[]},j=[...h,...n?[]:[{id:b,role:"user",parts:[{type:"text",content:g,isVisible:!0}],documentIds:v?m:[]}],I];it(j),xt(),v&&mt([]);const S=R.getPickaxeConfigMetadata(Ee),N=null!=o?o:H();p=N,ns.current=N,is.current=null,rs.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(Object.assign(Object.assign({supportsActionConfirmation:!0,selectedModel:ze||void 0,origin:Se,pickaxeId:Ne,sessionId:Oe,submissionId:N},a&&{interactionType:"steer"}),{senderType:ke,value:g}),v&&{documentIds:m}),we&&{sender:we}),Qe&&{studioSessionToken:Qe}),!Qe&&!we&&{sender:M.initializeEmbedUserId()}),Hs&&{portalId:Hs}),Ee&&{deploymentId:Ee}),S&&{metadata:S}),v&&f.length>0?{uploadedModelImages:f}:{})),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()})},As&&{credentials:"include"})),w=yield O.json();if(!w.success){if(w.limitData){const e=new Error(w.error||w.message||(null==De?void 0:De["failed-to-start-generation"])||"Failed to start generation");throw e.limitData=w.limitData,e}if(Fs(w))return;throw new Error(w.error||w.message||(null==De?void 0:De["failed-to-start-generation"])||"Failed to start generation")}lt(null!==(d=w.actionApprovalToken)&&void 0!==d?d:null);const k=null!==(c=w.submissionId)&&void 0!==c?c:N;p=k,ns.current=k;const _=()=>is.current===k;if(_())return;qs&&qe&&Oe&&cs.current.add(Oe);const E=Object.assign(Object.assign({},Ws()),{message:g,documentIds:v?m:[],uploadedModelImages:v?f:[],hasUploadedDocuments:v,isHidden:n,metadata:null!=S?S:null});Yt?(zs(),V.fireDeploymentFirstMessageSubmittedWebhook(E)):us.current=E,rt("streaming"),ds.current=new AbortController;const T=[];let C=[...null!=yt?yt:[]],U=0,A=!1,D="";for(;!A;)try{const e=yield fetch(`${process.env.NEXT_PUBLIC_PICKAXE_API2_URL}/response/stream/${k}?index=${U}`,{signal:null===(u=ds.current)||void 0===u?void 0:u.signal,headers:{"Cache-Control":"no-cache",Connection:"keep-alive"}});if(!e.body)throw new Error("No response body");const t=e.body.getReader();ss.current=t;const s=new TextDecoder,n=y.createParser({onEvent:e=>{var t,s;if(_())A=!0;else if(e.event&&"ping"!==e.event&&U++,"stop"!==e.event){if("error"===e.event){const t=JSON.parse(e.data);if(t.limitData)return ot(t.limitData),at(""),void(A=!0);const s=t.error||t.message||(null==De?void 0:De["something-went-wrong"])||"Something went wrong.";return Fs(t)||at(s),void(A=!0)}if("delta"===e.event){const n=JSON.parse(e.data);if("finish"===n.type)return void Pt(!0);if("data-error"===n.type&&ne){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 A=!0,ne({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 A=!0,ne({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 A=!0,ne({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 A=!0,ne({provider:"composio",toolkitSlug:t.toolkitSlug,serverId:t.serverId,name:t.name}),new Error("STOP_STREAM")}}else if("text-start"===n.type)D="",T.push({type:"text",content:"",isVisible:null===(t=n.isVisible)||void 0===t||t});else if("text-delta"===n.type)D+=n.delta,r.updateStreamTextPart(T,"text",D);else if("text-end"===n.type)D="";else if("reasoning-start"===n.type)D="",T.push({type:"reasoning",content:"",isVisible:null===(s=n.isVisible)||void 0===s||s});else if("reasoning-delta"===n.type)D+=n.delta,r.updateStreamTextPart(T,"reasoning",D);else if("reasoning-end"===n.type)D="";else if(n.type.startsWith("data-")){const e=n;"data-action-approval"===e.type?r.upsertActionApprovalPart(T,e.data):T.push({type:e.type,content:JSON.stringify(e.data),isVisible:!0})}rs.current=Y(T);const i=Y(T);it((e=>{const t=e.findIndex((e=>e.id===x)),s=Object.assign(Object.assign({},I),{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);C=C.filter((e=>!(e.id===t.id&&e.version===t.version))),C.push(Object.assign(Object.assign({},t),{content:"",status:"streaming"})),jt([...C]),It.startsWith("inline")||St({id:t.id,version:t.version})}else if("artifact_updated"===e.event){const t=JSON.parse(e.data);C=C.filter((e=>!(e.id===t.id&&e.version===t.version))),C.push(Object.assign(Object.assign({},t),{content:"",status:"updating"})),jt(C),It.startsWith("inline")||St({id:t.id,version:t.version})}else if("artifact_rewrite"===e.event){const t=JSON.parse(e.data);C=C.filter((e=>!(e.id===t.id&&e.version===t.version))),C.push(Object.assign(Object.assign({},t),{content:"",status:"streaming"})),jt(C),It.startsWith("inline")||St({id:t.id,version:t.version})}else if("artifact_content"===e.event){const t=JSON.parse(e.data),s=t.token.replace(/\u200B/g,"");C=C.map((e=>e.id===t.id&&e.version===t.version?Object.assign(Object.assign({},e),{content:e.content+s,status:"streaming"}):e)),jt(C)}else if("artifact_finished"===e.event){const t=JSON.parse(e.data);jt(C.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 ot(t.limitData),at(""),void(A=!0);const s=t.error||t.message||(null==De?void 0:De["something-went-wrong-try-again"])||"Something went wrong, please try again.";if(Fs(t))return void(A=!0);at(s)}else"stop"===e.event&&(A=!0)}else A=!0}});for(;;){if(_()){A=!0,t.cancel().catch((()=>{}));break}const{value:e,done:i}=yield t.read();if(_()){A=!0,t.cancel().catch((()=>{}));break}if(i)break;n.feed(s.decode(e))}A||_()||(yield new Promise((e=>setTimeout(e,1e3))))}catch(e){if("STOP_STREAM"===e.message||W(e)||_())return void(A=!0);console.warn("Stream connection lost, retrying...",e),yield new Promise((e=>setTimeout(e,1e3)))}null==We||We(Oe)}catch(e){if(W(e))return;if(e.limitData)ot(e.limitData),at("");else{let t=D.default(e)||"";t&&!t.includes("Unexpected token 'A',")||(t=(null==De?void 0:De["high-traffic-try-again-later"])||"Oops! We're experiencing high traffic at the moment. Please try again later."),Fs(t)||at(t)}}finally{const e=!p||ns.current===p;xt(),e&&(rt("idle"),bt(),ss.current=null),p&&e&&(ns.current=null,rs.current=[]),yield Bs()}}));return o.useEffect((()=>{if(nt||Ut||Mt||0===Lt.length)return;const t=Lt[0];Rt(!0),Vt(t.id),e.__awaiter(void 0,void 0,void 0,(function*(){try{if(!(yield hn(t.predecessorSubmissionId)))return void at((null==De?void 0:De["queued-message-waiting"])||"A queued message is waiting for the previous response to finish.");qt((e=>e.filter((e=>e.id!==t.id)))),yield xn(t.message,!1,!0,t.id)}finally{Rt(!1),Vt(null)}}))}),[nt,Mt,Ut,Lt]),Rs?null:t.jsx("div",Object.assign({className:q.default("flex w-full flex-shrink-0 flex-col items-center",!Ms&&"px-4 pb-8"),dir:Me?"rtl":"ltr"},{children:t.jsxs("div",Object.assign({className:"flex w-full max-w-[800px] flex-col"},{children:[Lt.length>0&&t.jsx("div",Object.assign({className:"mx-3 -mb-3 overflow-hidden border pb-3",style:{borderColor:Ae.text+"18",backgroundColor:null!==(ye=Es.backgroundColor)&&void 0!==ye?ye:Ae.text+"08",color:Ae.text,borderTopLeftRadius:Math.max(Ue.cornerRadius-4,12),borderTopRightRadius:Math.max(Ue.cornerRadius-4,12)}},{children:Lt.map(((s,n)=>{var i;return t.jsxs("div",Object.assign({className:"flex min-h-10 items-center gap-2 px-3 py-2",style:n<Lt.length-1?{borderBottom:`1px solid ${Ae.text}12`}:void 0},{children:[t.jsx(N.default,{className:"h-4 w-4 shrink-0 opacity-50","aria-hidden":"true"}),t.jsx("span",Object.assign({className:"min-w-0 flex-1 truncate text-sm",title:s.message},{children:s.message})),$t===s.id||Ft===s.id?t.jsxs("span",Object.assign({className:"flex shrink-0 items-center gap-1.5 px-2 py-1 text-xs opacity-60","aria-live":"polite"},{children:[t.jsx("span",{className:"h-3 w-3 animate-spin rounded-full border border-current border-r-transparent","aria-hidden":"true"}),$t===s.id?(null==De?void 0:De.steering)||"Steering...":(null==De?void 0:De.starting)||"Starting..."]})):t.jsxs(t.Fragment,{children:[t.jsxs("button",Object.assign({type:"button",className:"shrink-0 rounded-md px-2 py-1 text-xs font-medium opacity-70 transition-opacity hover:opacity-100 disabled:cursor-default disabled:opacity-40",disabled:Ut||!nt,onClick:()=>{(t=>{e.__awaiter(void 0,void 0,void 0,(function*(){const e=ns.current;if(!e||Ut)return;const s=Lt.findIndex((e=>e.id===t.id));if(-1===s)return;At(!0),Bt(t.id),at(""),vn(e);let n=!1;try{if(!(yield gn(e)))throw new Error((null==De?void 0:De["failed-to-interrupt-current-response"])||"Failed to interrupt the current response.");if(!(yield hn(e)))throw new Error((null==De?void 0:De["current-response-still-stopping"])||"The current response is still stopping. Please send your message again in a moment.");rt("idle"),qt((e=>e.filter((e=>e.id!==t.id)))),n=!0,At(!1),Bt(null),yield xn(t.message,!1,!0,t.id,!0)}catch(e){rt("idle"),n&&qt((e=>{if(e.some((e=>e.id===t.id)))return e;const n=[...e];return n.splice(s,0,t),n})),at(D.default(e))}finally{At(!1),Bt(null)}}))})(s)},"aria-label":`${(null==De?void 0:De["steer-with"])||"Steer with"}: ${s.message}`},{children:[t.jsx("span",Object.assign({"aria-hidden":"true"},{children:"↳ "})),(null==De?void 0:De.steer)||"Steer"]})),t.jsx("button",Object.assign({type:"button",className:"flex h-7 w-7 shrink-0 items-center justify-center rounded-md opacity-50 transition-opacity hover:opacity-100 disabled:cursor-default disabled:opacity-30",disabled:Ut,onClick:()=>{return e=s.id,void qt((t=>K(t,e)));var e},"aria-label":`${(null==De?void 0:De["remove-queued-message"])||"Remove queued message"}: ${s.message}`},{children:t.jsx(w.default,{className:"h-4 w-4","aria-hidden":"true"})})),t.jsxs(C.default,Object.assign({id:`queued-message-menu-${s.id}`,className:"shrink-0"},{children:[t.jsx(U.default,Object.assign({className:"flex h-7 w-7 items-center justify-center rounded-md opacity-50 transition-opacity hover:opacity-100",isDisabled:Ut,role:"button",tabIndex:Ut?-1:0,"aria-haspopup":"menu","aria-label":(null==De?void 0:De["more-options"])||"More options",onKeyDown:e=>{"Enter"!==e.key&&" "!==e.key||(e.preventDefault(),e.currentTarget.click())}},{children:t.jsxs("svg",Object.assign({viewBox:"0 0 24 24",className:"h-4 w-4",fill:"currentColor","aria-hidden":"true"},{children:[t.jsx("circle",{cx:"5",cy:"12",r:"1.6"}),t.jsx("circle",{cx:"12",cy:"12",r:"1.6"}),t.jsx("circle",{cx:"19",cy:"12",r:"1.6"})]}))})),t.jsx(A.default,Object.assign({role:"menu",align:Me?"bottom-start":"bottom-end",positionStrategy:Re?"absolute":"fixed",width:"auto",className:"p-1 text-sm shadow-xl",style:{backgroundColor:null!==(i=Es.backgroundColor)&&void 0!==i?i:Ae.primary,color:Ae.text,borderRadius:"12px"},border:`1px solid ${Ae.text}20`},{children:t.jsxs("button",Object.assign({type:"button",role:"menuitem",className:"flex min-w-36 items-center gap-2 rounded-lg px-3 py-2 text-left transition-colors hover:bg-black/5 dark:hover:bg-white/10",onClick:()=>(e=>{qt((t=>K(t,e.id))),kt(e.message),requestAnimationFrame((()=>{const t=os.current;t&&(t.focus(),t.setSelectionRange(e.message.length,e.message.length))}))})(s)},{children:[t.jsx(k.default,{className:"h-4 w-4 shrink-0"}),(null==De?void 0:De["edit-message"])||"Edit message"]}))}))]}))]})]}),s.id)}))})),t.jsxs("div",Object.assign({ref:ls,className:q.default("relative z-10 flex flex-col w-full justify-end gap-y-3 py-[3px]","block"===Ue.formFieldStyle&&"shadow"),style:Object.assign(Object.assign({},Es),{maxHeight:`${ps}px`,overflowY:"auto"})},{children:[ln&&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:Es.backgroundColor?`${Es.backgroundColor}E6`:void 0,borderColor:Ae.text+"20",color:Ae.text,borderTopRightRadius:Ue.cornerRadius+"px",borderTopLeftRadius:Ue.cornerRadius+"px"}},{children:[t.jsx("div",Object.assign({className:"flex items-center gap-2 text-sm font-medium"},{children:t.jsxs("span",{children:[sn.toLocaleString()," ",Gs?(null==De?void 0:De.credits)||"Credits":(null==De?void 0:De.uses)||"Uses"," ",(null==De?void 0:De.remaining)||"remaining"]})})),t.jsxs("div",Object.assign({className:"flex items-center gap-3"},{children:[cn&&t.jsx("button",Object.assign({className:"rounded-md px-3 py-1.5 text-xs font-semibold transition-opacity hover:opacity-90",style:{backgroundColor:Ae.accent,color:Ae.accentText},onClick:e=>{if(e.preventDefault(),e.stopPropagation(),un)return void window.open(un,"_blank","noopener,noreferrer");if(Ye)return void Ye();const t=M.buildUpgradeUrl({baseUrl:Gt,accessGroupId:null==Ve?void 0:Ve.accessGroupId});t&&M.openAuthenticatedPricingUrl({deploymentId:Ee,pricingUrl:t,studioId:null==Ce?void 0:Ce.studioid,studioSessionToken:Qe})}},{children:pn})),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:()=>Jt(!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"})}))}))]}))]})),!nt&&dt.length>0&&t.jsx(_.default,{className:"p-4 pb-0",isDisabled:nt}),t.jsxs("div",Object.assign({className:"relative flex w-full flex-col"},{children:[Ls&&t.jsxs("div",Object.assign({className:q.default(Je?"top-6":"top-1/2","pointer-events-none absolute z-10 flex -translate-y-1/2 select-none items-center gap-x-2",Me?"right-4":"left-4")},{children:[t.jsx("span",{className:"h-2 w-2 animate-pulse rounded-full bg-c-secondary",style:{backgroundColor:null!==(Ie=Ae.accent)&&void 0!==Ie?Ie:"#ff0000"}}),t.jsx("span",Object.assign({className:"text-sm text-c-secondary font-semilight",style:{color:Ae.text+"90"}},{children:(null==De?void 0:De.listening)||"Listening..."}))]})),t.jsx(E.default,Object.assign({ref:os,className:q.default(_s.i1,"py-3.5 max-h-60 px-4 w-full border-transparent bg-transparent",!wt.trim()&&!wt.includes("\n")&&"overflow-hidden text-ellipsis whitespace-nowrap placeholder:whitespace-normal placeholder:overflow-visible",Me?"text-right":"text-left",!Je&&$s&&"mb-12"),value:wt,placeholder:Ls?"":Vs,onChange:e=>{kt(e)},onKeyDown:e=>{Le||vt||"Enter"===e.key&&(e.shiftKey||(e.preventDefault(),ct||Ut||(nt?bn():xn())))},onPaste:t=>e.__awaiter(void 0,void 0,void 0,(function*(){const e=Array.from(t.clipboardData.files||[]);if(e.length>0){if(!Ds)return;t.preventDefault(),$e(!1),yield pt(e)}}))},ee&&{onFocus:ee},te&&{onBlur:te},{dir:Me?"rtl":"ltr"})),t.jsxs("div",Object.assign({ref:as,className:Je?"relative flex w-full items-center gap-2 px-3 pb-2 [&>button]:shrink-0 [&>button]:mr-0":q.default("flex items-center gap-2 absolute z-2 transition-all duration-200 ease-in-out",$s?"bottom-3 right-2":"right-0 top-1/2 -translate-y-1/2"),style:Object.assign(Object.assign({},!$s&&Es.backgroundColor&&{backgroundColor:Es.backgroundColor}),{borderTopRightRadius:Ue.cornerRadius+"px",borderBottomRightRadius:Ue.cornerRadius+"px"})},{children:[!nt&&!fs&&Ds&&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:Ss?Ae.accent+"10":void 0,color:Ss?Ae.accent:Ae.accent+"80"},disabled:ct||nt,"aria-label":null!==(je=null==De?void 0:De["attach-files"])&&void 0!==je?je:"Attach files",onClick:()=>{var e;return null===(e=es.current)||void 0===e?void 0:e.click()}},Ns,{children:[t.jsx("input",{id:"file-upload",ref:es,type:"file",accept:[...x.allowedFileMimeTypes,...x.allowedImageMimeTypes,...x.additionalAllowedFileExtensions].join(", "),multiple:!0,hidden:!0,className:"hidden",onChange:t=>e.__awaiter(void 0,void 0,void 0,(function*(){$e(!1),yield pt(Array.from(t.target.files||[])),t.target.value=""}))}),t.jsx(I.default,{className:"h-6 w-6 shrink-0"})]})),t.jsx(i.default,{compact:!0}),nt&&!Dt?t.jsxs(t.Fragment,{children:[t.jsx("button",Object.assign({"aria-label":(null==De?void 0:De["stop-response"])||"Stop response",className:"flex h-8 w-8 items-center justify-center rounded-full outline-none transition-colors duration-200 ease-in-out",onClick:()=>{const e=ns.current;e&&(vn(e),gn(e)),rt("idle")},style:{backgroundColor:Ae.accent+"10",color:Ae.accent}},{children:t.jsx(O.default,{className:"h-4 w-4 shrink-0"})})),t.jsx("button",Object.assign({"aria-label":(null==De?void 0:De["queue-message"])||"Queue message",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",disabled:Ut||ct||!wt.trim(),onClick:bn,style:{backgroundColor:wt.trim()?Ae.accent:Ae.accent+"10",color:wt.trim()?Ae.accentText:Ae.accent+"80"}},{children:t.jsx(j.default,{className:q.default("h-6 w-6 shrink-0",Me&&"scale-x-[-1] transform")})}))]}):fs||gs?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:()=>{bs()},disabled:gs,style:{backgroundColor:Ae.accent,color:Ae.accentText}},{children:t.jsx(O.default,{className:"h-4 w-4 shrink-0"})})):t.jsxs(t.Fragment,{children:[Ps&&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:fs?Ae.accent:ws?Ae.accent+"10":void 0,color:fs?Ae.accentText:ws?Ae.accent:Ae.accent+"80"},disabled:ct||nt||gs,onClick:()=>{fs?bs():(ts.current=wt,hs(Pe||"en-US"))}},ks,{children:t.jsx(S.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:ys||fn?Ae.accent:Ae.accent+"10",color:ys||fn?Ae.accentText:Ae.accent+"80"},disabled:!fn,onClick:()=>xn()},Is,{children:t.jsx(j.default,{className:q.default("h-6 w-6 shrink-0",Me&&"scale-x-[-1] transform")})}))]})]}))]}))]})),ut&&t.jsx(T.default,{error:ut,className:"mt-3"})]}))}))}));ee.displayName="Input",exports.default=ee;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e=require("../../_virtual/_tslib.js"),s=require("../../common/utils.js");exports.useSubmitDocument=()=>({document:({contextId:s,pickaxeId:o,file:i,workspaceId:
|
|
1
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e=require("../../_virtual/_tslib.js"),s=require("../../common/utils.js");exports.useSubmitDocument=()=>({document:({contextId:s,pickaxeId:o,file:i,workspaceId:t,sessionId:n,studioUserId:r,studioSessionToken:d,isKnowledge:c,isUserDocument:a,isBlocking:l})=>e.__awaiter(void 0,void 0,void 0,(function*(){var u,_;if(!process.env.NEXT_PUBLIC_DOCUMENT_API2_URL)throw new Error("NEXT_PUBLIC_DOCUMENT_API2_URL is not defined");const p=i.name.split(".").pop(),g="md"===p?"md":i.type,I={sessionid:s,formid:o,mimetype:g,extension:p,responseid:n,workspaceid:t},m=new URLSearchParams(Object.entries(I).filter((e=>void 0!==e[1]&&null!==e[1]&&""!==e[1]))),O=`${process.env.NEXT_PUBLIC_DOCUMENT_API2_URL}/get_document_upload_url?${m.toString()}`,U=yield fetch(O),f=yield U.json();if(!f.success)throw new Error(null!==(u=f.error)&&void 0!==u?u:"Failed to get presigned URL, try again or contact support.");const w=new FormData;Object.entries(Object.assign(Object.assign({},f.fields),{file:i})).forEach((([e,s])=>{w.append(e,s)}));const b=()=>e.__awaiter(void 0,void 0,void 0,(function*(){const e=new URLSearchParams(Object.assign({sessionid:s,documentid:f.documentId},n&&{responseid:n}));try{yield fetch(`${process.env.NEXT_PUBLIC_DOCUMENT_API2_URL}/decrement_document_count?${e.toString()}`)}catch(e){}}));let j;try{j=yield fetch(f.url,{method:"POST",body:w})}catch(e){throw yield b(),e}if(!j.ok)throw yield b(),new Error(j.statusText);const v=`${f.url}${f.fields.key}`;"development"===process.env.NODE_ENV&&console.log("[S3URL]",v);const y=yield fetch(`${process.env.NEXT_PUBLIC_DOCUMENT_API2_URL}/process_document`,{method:"POST",body:JSON.stringify(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({formId:o,documentId:f.documentId,fileName:i.name,fileSize:i.size},t&&{workspaceId:t}),n&&{responseId:n}),r&&{studioUserId:r}),d&&{studioSessionToken:d}),c&&{isKnowledge:c}),a&&{isUserDocument:a}),l&&{isBlocking:l})),headers:{"Content-Type":"application/json"}}),T=yield y.json();if(!T.success)throw new Error(null!==(_=T.error)&&void 0!==_?_:"Failed processing document, try again or contact support.");return Object.assign(Object.assign({},T),{folder:f.folder})})),website:({pickaxeId:o,website:i,workspaceId:t,sessionId:n,studioUserId:r,studioSessionToken:d,isKnowledge:c,isUserDocument:a,isBlocking:l})=>e.__awaiter(void 0,void 0,void 0,(function*(){var e;if(!process.env.NEXT_PUBLIC_DOCUMENT_API2_URL)throw new Error("NEXT_PUBLIC_DOCUMENT_API2_URL is not defined");const u=s.generateId(20),_=yield fetch(`${process.env.NEXT_PUBLIC_DOCUMENT_API2_URL}/process_document`,{method:"POST",body:JSON.stringify(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({formId:o,documentId:u,website:i},t&&{workspaceId:t}),n&&{responseId:n}),r&&{studioUserId:r}),d&&{studioSessionToken:d}),c&&{isKnowledge:c}),a&&{isUserDocument:a}),l&&{isBlocking:l})),headers:{"Content-Type":"application/json"}}),p=yield _.json();if(!p.success)throw new Error(null!==(e=p.error)&&void 0!==e?e:"Failed processing website, try again or contact support.");return p}))});
|
|
@@ -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{canChat as i}from"../../../common/canChat.js";import{useEndUserModel as r}from"../../../hooks/pickaxe/useEndUserModel.js";import a from"../common/EndUserModelPicker.js";import{updateStreamTextPart as l,upsertActionApprovalPart as d}from"../../../common/actionApproval.js";import{forwardRef as c,useState as u,useRef as p,useCallback as m,useEffect as g,useMemo as f,useImperativeHandle as v}from"react";import{usePickaxeContext as h}from"../../../hooks/pickaxe/usePickaxeContext.js";import{useResponseContext as b}from"../../../hooks/pickaxe/useResponseContext.js";import{useStyleInput as y}from"../../../hooks/studio/useStyleInput.js";import{useStyleFontSize as x}from"../../../hooks/studio/useStyleFontSize.js";import{useConversation as j}from"../../../hooks/pickaxe/useConversation.js";import{useDimensionContext as I}from"../../../hooks/pickaxe/useDimensionContext.js";import{useAuthContext as w}from"../Addons/Auth/hooks/useAuthContext.js";import{useDocument as k}from"../Addons/Document/hooks/useDocument.js";import{useScroll as O}from"../Addons/Scroll/hooks/useScroll.js";import{useArtifactContext as N}from"../Addons/Artifact/hooks/useArtifactContext.js";import{useHover as S}from"../../../hooks/core/useHover.js";import{useMediaQuery as C}from"../../../hooks/core/useMediaQuery.js";import{allowedFileMimeTypes as E,allowedImageMimeTypes as _,additionalAllowedFileExtensions as T}from"../../../common/documents.js";import{createParser as U}from"eventsource-parser";import A from"../../Icons/attach-vertical.svg.js";import P from"../../Icons/arrow-right.svg.js";import D from"../../Icons/microphone.svg.js";import L from"../../Icons/message-clock.svg.js";import M from"../../Icons/stop.svg.js";import R from"../../Icons/trash.svg.js";import $ from"../../Icons/pencil.svg.js";import B from"../Addons/Document/List.js";import X from"../../Core/Textarea.js";import K from"../../Core/ErrorAlert.js";import F from"../../Core/Menu/index.js";import G from"../../Core/Menu/Button.js";import V from"../../Core/Menu/List.js";import H from"../../../common/error.js";import{pickaxeApi2 as W}from"../../../common/api/pickaxe.js";import{getValidationFailure as q}from"../../../common/validation.js";import J from"../../../common/cn.js";import{buildUpgradeUrl as z,openAuthenticatedPricingUrl as Q,initializeEmbedUserId as Y}from"../../../common/utils.js";import{getPickaxeConfigMetadata as Z}from"../../../common/pickaxeConfig.js";import{readAgentPrefill as ee}from"../../../common/agentPrefill.js";import{fireDeploymentSessionInitializedWebhook as te,fireDeploymentFirstMessageSubmittedWebhook as ne}from"../../../common/deploymentWebhooks.js";import{useStudio as oe}from"../../../hooks/studio/useStudio.js";import{useSpeechToText as se}from"../../../hooks/pickaxe/useSpeechToText.js";import{STUDIO_INFINITY_VALUE as ie}from"../common/PickaxeCommon.js";const re=(e,t)=>{const n=e.find((e=>e.id===t));return n?e.filter((e=>e.id!==t)).map((e=>e.predecessorSubmissionId===t?Object.assign(Object.assign({},e),{predecessorSubmissionId:n.predecessorSubmissionId}):e)):e},ae=e=>"string"==typeof e&&e.trim().length>0,le=()=>"undefined"!=typeof crypto&&"randomUUID"in crypto?crypto.randomUUID():`submission-${Date.now()}-${Math.random().toString(36).slice(2)}`,de=e=>e.map((e=>Object.assign({},e))),ce=e=>e instanceof Error&&("AbortError"===e.name||"BodyStreamBuffer was aborted"===e.message),ue=(e,t)=>{if(e&&"object"==typeof e)return e[t]},pe=(e,t)=>{const n=ue(e,t);return ae(n)?n:null},me=e=>{const t=Number(e);return Number.isFinite(t)?t:void 0},ge=({studioUser:e,deploymentId:t,portalId:n})=>{var o,s;const i=Array.isArray(ue(e,"uses"))?ue(e,"uses"):[],r=(({deploymentId:e,portalId:t})=>ae(e)?{type:"deployment",id:e}:ae(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}},fe=c((({resubmitPrompt:c,onFocus:ue,onBlur:fe,onInputHeightChange:ve,initSmitheryAuthData:he},be)=>{var ye,xe,je,Ie,we,ke,Oe,Ne,Se,Ce,Ee,_e,Te,Ue,Ae,Pe,De,Le;const{origin:Me,pickaxeId:Re,sessionId:$e,sender:Be,senderType:Xe,portalId:Ke,deploymentId:Fe,deploymentType:Ge,pickaxe:Ve,styles:He,colors:We,translations:qe,locale:Je,forceMobile:ze,isNewChat:Qe,isRtl:Ye,isEmbed:Ze,isShowFeedbackMessage:et,accessGroup:tt,setIsNewChat:nt,setIsShowIceBreaker:ot,setValidationStatus:st,setValidationUpgradeGroups:it,setValidationUpgradeUrl:rt,setAccessGroup:at,onUpgrade:lt,onGenerateComplete:dt}=h(),{value:ct,enabled:ut}=r(),{token:pt,isLoggedOut:mt,isSent:gt,isPricingAuth:ft}=w(),{messages:vt,isGenerating:ht,setMessages:bt,setStatus:yt,setLimitData:xt,setError:jt,setActionApprovalToken:It}=b(),{documents:wt,isUploading:kt,documentError:Ot,onFileUpload:Nt,setDocuments:St,setDocumentError:Ct}=k(),{studio:Et}=oe(),[_t]=C("(max-width: 480px)"),{scrollStartSession:Tt,scrollEndSession:Ut,scrollToBottom:At}=O({auto:!0,smooth:!(ze||_t)}),{artifacts:Pt,currentPopupType:Dt,setArtifacts:Lt,setCurrentArtifact:Mt}=N(),{height:Rt}=I(),$t=j(),[Bt,Xt]=u((()=>ee([Fe,Re]).chatInput)),[Kt,Ft]=u(!1),[Gt,Vt]=u(!1),[Ht,Wt]=u(!1),[qt,Jt]=u(!1),[zt,Qt]=u([]),[Yt,Zt]=u(!1),[en,tn]=u(null),[nn,on]=u(null),[sn,rn]=u(null),[an,ln]=u(null),[dn,cn]=u(!1),[un,pn]=u(!1),[mn,gn]=u(0),fn=p(null),vn=p(""),hn=p(null),bn=p(null),yn=p(null),xn=p([]),jn=p(null),In=p(null),wn=p(null),kn=p(null),On=p(new Set),Nn=p(null),Sn=Math.max(.4*Rt,100),{speechTranscript:Cn,isSpeechListening:En,isSpeechProcessing:_n,isSpeechSupported:Tn,onStartListening:Un,onStopListening:An}=se(),Pn=S(),{isHover:Dn}=Pn,Ln=e(Pn,["isHover"]),Mn=S(),{isHover:Rn}=Mn,$n=e(Mn,["isHover"]),Bn=S(),{isHover:Xn}=Bn,Kn=e(Bn,["isHover"]),Fn=x(),Gn=y(),Vn="undefined"!=typeof window?window.location.hostname:"",Hn="undefined"!=typeof window?window.location.href:"",Wn="undefined"!=typeof window&&window.self!==window.top,qn=Vn.includes("pickaxe.co")&&!Hn.includes("https://studio.pickaxe.co/_embed")&&!Wn,Jn=null!==(xe=null===(ye=null==Ve?void 0:Ve.documentuploadtype)||void 0===ye?void 0:ye.startsWith("enduserupload"))&&void 0!==xe&&xe,zn=Tn&&(null==Ve?void 0:Ve.enablevoicetotext),Qn=En&&!Bt.trim(),Yn=ae(Fe),Zn="chat-input"===Ge&&Qe&&!gt,eo="chat-input"===Ge&&ft&&mt&>,to=m((e=>{const t=q(e);return!!t&&(jt(""),xt(null),st(t.status),at(t.accessGroup),it(t.upgradeGroups),rt(t.upgradeUrl),!0)}),[jt,It,xt,st,it,rt,at]),no=null!==(je=null==Ve?void 0:Ve.placeholdertext)&&void 0!==je?je:Ye?"بماذا تريد أن تتحدث؟":(null==qe?void 0:qe["what-do-you-want-to-talk-about"])||"What do you want to talk about?",oo=Kt||Gt,so=m((()=>t(void 0,void 0,void 0,(function*(){cn(!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==Ve?void 0:Ve.studioid},pt?{studioSessionToken:pt}:Be?{sender:Be}:{sender:Y()}))},(!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}})),qn&&{credentials:"include"})),t=yield e.json();(null==t?void 0:t.studioUser)&&(rn(t.studioUser),ln(t.url))}catch(e){console.error("Failed to fetch studio user:",e)}finally{cn(!0)}}))),[qn,null==Ve?void 0:Ve.studioid,Be,pt]);g((()=>{so()}),[so]);const io=Number(null!==(Ie=null==tt?void 0:tt.limit)&&void 0!==Ie?Ie:0),ro="string"==typeof(null==tt?void 0:tt.limitInterval)?tt.limitInterval:null,ao=!!(null==Et?void 0:Et.data.usage)&&Et.data.usage.isCredits,lo=f((()=>{var e,t,n,o,s;return null!==(s=null!==(o=null!==(n=null!==(t=null!==(e=null!=Ke?Ke:pe(sn,"portalId"))&&void 0!==e?e:pe(sn,"portalid"))&&void 0!==t?t:pe(tt,"portalId"))&&void 0!==n?n:pe(tt,"portalid"))&&void 0!==o?o:pe(Ve,"portalId"))&&void 0!==s?s:pe(Ve,"portalid")}),[tt,Ke,Ve,sn]),co=f((()=>ge({studioUser:sn,deploymentId:Fe,portalId:lo})),[Fe,lo,sn]);g((()=>{Yn&&Qe&&$e&&On.current.add($e)}),[Qe,$e,Yn]);const uo=m((()=>{var e,t,n;return{studioId:null==Ve?void 0:Ve.studioid,userEmail:pe(sn,"email"),userId:null!==(e=pe(sn,"userId"))&&void 0!==e?e:pe(sn,"userid"),sessionId:$e,deploymentId:Fe,deploymentType:Ge,portalId:lo,accessGroupId:null!==(t=null==tt?void 0:tt.accessGroupId)&&void 0!==t?t:null,pickaxeId:Re,sender:Be,senderType:Xe,origin:Me,metadata:null!==(n=Z(Fe))&&void 0!==n?n:null}}),[null==tt?void 0:tt.accessGroupId,Fe,Ge,Me,null==Ve?void 0:Ve.studioid,Re,lo,Be,Xe,$e,sn]),po=m((()=>!!(Yn&&dn&&$e)&&(!!On.current.has($e)&&(te(uo()),On.current.delete($e),!0))),[uo,dn,$e,Yn]);g((()=>{if(!dn||!$e)return;po();const e=Nn.current;(null==e?void 0:e.sessionId)===$e&&(ne(Object.assign(Object.assign(Object.assign({},e),uo()),{message:e.message,documentIds:e.documentIds,uploadedModelImages:e.uploadedModelImages,hasUploadedDocuments:e.hasUploadedDocuments,isHidden:e.isHidden})),Nn.current=null)}),[po,uo,dn,$e]);const mo={currentUses:me(null==sn?void 0:sn.currentUses),extraUses:me(null==sn?void 0:sn.extraUses)},go=co.scope?{currentUses:null!==(ke=me(null===(we=co.record)||void 0===we?void 0:we.currentUses))&&void 0!==ke?ke:0,extraUses:null!==(Ne=me(null===(Oe=co.record)||void 0===Oe?void 0:Oe.extraUses))&&void 0!==Ne?Ne:0}:{currentUses:0,extraUses:0},fo=pe(sn,"type"),vo="guest"===fo||!fo&&mt?go:mo;g((()=>{let e=!0;return t(void 0,void 0,void 0,(function*(){var t;if(ao&&(null===(t=null==Et?void 0:Et.data)||void 0===t?void 0:t.workspaceId))try{const t=yield W.get(`/cost_per_run?workspaceId=${Et.data.workspaceId}`,{withCredentials:!1});e&&gn(1e4*(Number(t.data.costPerRun)||0))}catch(t){console.error("Failed to fetch average cost per run:",t),e&&gn(0)}else e&&gn(0)})),()=>{e=!1}}),[ao,null===(Se=null==Et?void 0:Et.data)||void 0===Se?void 0:Se.workspaceId]);const ho=(({accessGroupType:e,currentUses:t,extraUses:n,limit:o,limitInterval:s})=>{const i=Number(null!=t?t:0),r=Number(null!=n?n:0);return"public"===e&&"one_time"===s?o===ie?ie:Math.max(0,o-i):o===ie||r===ie?ie:"one_time"===s?Math.max(0,r):Math.max(0,o-i)+r})({accessGroupType:null==tt?void 0:tt.type,currentUses:vo.currentUses,extraUses:vo.extraUses,limit:io,limitInterval:ro}),bo=ho===ie?ie:Math.max(0,Math.ceil(ho)),yo=(({accessGroupType:e,extraUses:t,limit:n,limitInterval:o})=>{const s=Number(null!=t?t:0);return"public"===e&&"one_time"===o?n===ie?ie:Math.max(0,n):n===ie||s===ie?ie:"one_time"===o?Math.max(0,s):Math.max(0,n)+Math.max(0,s)})({accessGroupType:null==tt?void 0:tt.type,extraUses:vo.extraUses,limit:io,limitInterval:ro}),xo=yo===ie?ie:Math.ceil(.05*yo),jo=ao?Math.ceil(5*mn):5,Io=xo===ie?ie:Math.max(xo,jo),wo=f((()=>!!sn&&(!un&&(bo!==ie&&(!(yo<=0||bo>=yo)&&bo<=Io)))),[un,Io,bo,sn,yo]),ko=Boolean(null==tt?void 0:tt.hideUpgradeOptions),Oo=Boolean(!ko&&((null===(Ce=null==tt?void 0:tt.upgrade)||void 0===Ce?void 0:Ce.isBuyMoreUses)||(null===(Ee=null==tt?void 0:tt.upgrade)||void 0===Ee?void 0:Ee.isLinkToCustomURL)||(null===(_e=null==tt?void 0:tt.upgrade)||void 0===_e?void 0:_e.isUpgradeToAnotherGroup)&&(null===(Te=tt.upgrade.accessGroupIds)||void 0===Te?void 0:Te.length))),No=!ko&&(null===(Ue=null==tt?void 0:tt.upgrade)||void 0===Ue?void 0:Ue.isLinkToCustomURL)&&"string"==typeof tt.upgrade.limitLink&&tt.upgrade.limitLink.trim().length>0?tt.upgrade.limitLink.trim():null,So=No&&"string"==typeof(null===(Ae=null==tt?void 0:tt.upgrade)||void 0===Ae?void 0:Ae.limitCTA)&&tt.upgrade.limitCTA.trim().length>0?tt.upgrade.limitCTA:(null==qe?void 0:qe["pricing.upgrade"])||(null==qe?void 0:qe.upgrade)||"Upgrade",Co=f((()=>{var e,t,n;return!!Qe&&(!!Ve&&(!$t.isLoading&&(!((null!==(t=null===(e=$t.data)||void 0===e?void 0:e.messages.length)&&void 0!==t?t:0)>1)&&(!!(null===(n=Ve.icebreakers)||void 0===n?void 0:n.length)&&(!et&&!Zn)))))}),[Ve,Qe,et,Zn,$t.data,$t.isLoading]),Eo=f((()=>{if(kt||Ht)return!1;const e=Jn&&wt.length>0&&wt.every((e=>"finished"===e.status));return!(!Bt.trim()&&!e)&&wt.every((e=>"finished"===e.status||e.isInsertedAsRaw))}),[Jn,kt,Ht,Bt,wt]);v(be,(()=>({onSubmit:Po}))),g((()=>{ot(Co)}),[Co]),g((()=>{var e;if(c){const t=Array.from(vt),n=null===(e=t[t.length-2].parts.find((e=>"text"===e.type)))||void 0===e?void 0:e.content;Po(n,!0)}}),[c]),g((()=>{if(!wn.current||!ve)return;const e=new ResizeObserver((e=>{for(const t of e)ve(t.contentRect.height)}));return e.observe(wn.current),()=>{e.disconnect()}}),[ve]),g((()=>{if(!En)return;const e=vn.current?`${vn.current} `:"";Xt(`${e}${Cn}`)}),[Cn,En]),g((()=>{if(!jn.current)return;(()=>{if(!jn.current)return;let e=jn.current.scrollHeight>52;Bt.includes("\n")||wt.length?e=!0:Bt.trim()||(e=!1),Ft(e)})()}),[Bt,wt]),g((()=>{const e=jn.current,t=In.current;if(!e||!t||ut||Kt||Bt.includes("\n"))return void Vt(!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=Bt||no,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;Vt(i>l)}),[Bt,Kt,no,ut]);const _o=e=>t(void 0,void 0,void 0,(function*(){if(!(e=null!=e?e:bn.current))return!1;const t=de(xn.current);try{return(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})},qn&&{credentials:"include"}))).ok}catch(e){return console.warn("Failed to cancel submission",e),!1}})),To=e=>{yn.current=e,kn.current&&(kn.current.abort(),kn.current=null),hn.current&&(hn.current.cancel().catch((()=>{})),hn.current=null)},Uo=e=>t(void 0,void 0,void 0,(function*(){const t=Date.now()+3e4;for(;Date.now()<t;){try{const t=yield fetch(`${process.env.NEXT_PUBLIC_PICKAXE_API2_URL}/response/status/${e}`,Object.assign({headers:Object.assign({"Cache-Control":"no-cache"},(!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}))},qn&&{credentials:"include"}));if(t.ok){if((yield t.json()).terminal)return!0}}catch(e){console.warn("Failed to read submission status",e)}yield new Promise((e=>setTimeout(e,250)))}return!1})),Ao=()=>{const e=bn.current;e&&!Ht&&!kt&&Bt.trim()&&(Qt((t=>{var n,o;return[...t,{id:le(),message:Bt,predecessorSubmissionId:null!==(o=null===(n=t[t.length-1])||void 0===n?void 0:n.id)&&void 0!==o?o:e}]})),Xt(""))},Po=(e,n=!1,o=!1,s,r=!1)=>t(void 0,void 0,void 0,(function*(){var t,a,c,u,p;if(!i(Ve))return;let m=null;try{if(ht&&!o||kt)return;const i=wt.filter((e=>"finished"===e.status&&!e.isInsertedAsRaw)),g=i.map((e=>e.documentId)).filter(Boolean),f=i.filter((e=>"image"===e.type)).map((e=>{const t=e.name.split(".").pop()||"";return{documentId:e.documentId,extension:t}})),v=null!=e?e:Bt,h=null!==(a=null===(t=null==Ve?void 0:Ve.documentuploadtype)||void 0===t?void 0:t.startsWith("enduserupload"))&&void 0!==a&&a&&g.length>0;if(!v&&!h)return;jt(""),Ct(""),xt(null),Xt(""),nt(!1),Jt(!1),yt("fetching"),Tt(),At();const b=n?vt.slice(0,vt.length-1):vt,y=(e=>e.reduce(((e,t)=>Math.max(e,t.id)),0)+1)(b),x=y+(n?0:1),j={id:x,role:"assistant",parts:[],documentIds:[]},I=[...b,...n?[]:[{id:y,role:"user",parts:[{type:"text",content:v,isVisible:!0}],documentIds:h?g:[]}],j];bt(I),At(),h&&St([]);const w=Z(Fe),k=null!=s?s:le();m=k,bn.current=k,yn.current=null,xn.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(Object.assign(Object.assign({supportsActionConfirmation:!0,selectedModel:ct||void 0,origin:Me,pickaxeId:Re,sessionId:$e,submissionId:k},r&&{interactionType:"steer"}),{senderType:Xe,value:v}),h&&{documentIds:g}),Be&&{sender:Be}),pt&&{studioSessionToken:pt}),!pt&&!Be&&{sender:Y()}),lo&&{portalId:lo}),Fe&&{deploymentId:Fe}),w&&{metadata:w}),h&&f.length>0?{uploadedModelImages:f}:{})),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()})},qn&&{credentials:"include"})),N=yield O.json();if(!N.success){if(N.limitData){const e=new Error(N.error||N.message||(null==qe?void 0:qe["failed-to-start-generation"])||"Failed to start generation");throw e.limitData=N.limitData,e}if(to(N))return;throw new Error(N.error||N.message||(null==qe?void 0:qe["failed-to-start-generation"])||"Failed to start generation")}It(null!==(c=N.actionApprovalToken)&&void 0!==c?c:null);const S=null!==(u=N.submissionId)&&void 0!==u?u:k;m=S,bn.current=S;const C=()=>yn.current===S;if(C())return;Yn&&Qe&&$e&&On.current.add($e);const E=Object.assign(Object.assign({},uo()),{message:v,documentIds:h?g:[],uploadedModelImages:h?f:[],hasUploadedDocuments:h,isHidden:n,metadata:null!=w?w:null});dn?(po(),ne(E)):Nn.current=E,yt("streaming"),kn.current=new AbortController;const _=[];let T=[...null!=Pt?Pt:[]],A=0,P=!1,D="";for(;!P;)try{const e=yield fetch(`${process.env.NEXT_PUBLIC_PICKAXE_API2_URL}/response/stream/${S}?index=${A}`,{signal:null===(p=kn.current)||void 0===p?void 0:p.signal,headers:{"Cache-Control":"no-cache",Connection:"keep-alive"}});if(!e.body)throw new Error("No response body");const t=e.body.getReader();hn.current=t;const n=new TextDecoder,o=U({onEvent:e=>{var t,n;if(C())P=!0;else if(e.event&&"ping"!==e.event&&A++,"stop"!==e.event){if("error"===e.event){const t=JSON.parse(e.data);if(t.limitData)return xt(t.limitData),jt(""),void(P=!0);const n=t.error||t.message||(null==qe?void 0:qe["something-went-wrong"])||"Something went wrong.";return to(t)||jt(n),void(P=!0)}if("delta"===e.event){const o=JSON.parse(e.data);if("finish"===o.type)return void Jt(!0);if("data-error"===o.type&&he){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 P=!0,he({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 P=!0,he({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 P=!0,he({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 P=!0,he({provider:"composio",toolkitSlug:t.toolkitSlug,serverId:t.serverId,name:t.name}),new Error("STOP_STREAM")}}else if("text-start"===o.type)D="",_.push({type:"text",content:"",isVisible:null===(t=o.isVisible)||void 0===t||t});else if("text-delta"===o.type)D+=o.delta,l(_,"text",D);else if("text-end"===o.type)D="";else if("reasoning-start"===o.type)D="",_.push({type:"reasoning",content:"",isVisible:null===(n=o.isVisible)||void 0===n||n});else if("reasoning-delta"===o.type)D+=o.delta,l(_,"reasoning",D);else if("reasoning-end"===o.type)D="";else if(o.type.startsWith("data-")){const e=o;"data-action-approval"===e.type?d(_,e.data):_.push({type:e.type,content:JSON.stringify(e.data),isVisible:!0})}xn.current=de(_);const s=de(_);bt((e=>{const t=e.findIndex((e=>e.id===x)),n=Object.assign(Object.assign({},j),{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);T=T.filter((e=>!(e.id===t.id&&e.version===t.version))),T.push(Object.assign(Object.assign({},t),{content:"",status:"streaming"})),Lt([...T]),Dt.startsWith("inline")||Mt({id:t.id,version:t.version})}else if("artifact_updated"===e.event){const t=JSON.parse(e.data);T=T.filter((e=>!(e.id===t.id&&e.version===t.version))),T.push(Object.assign(Object.assign({},t),{content:"",status:"updating"})),Lt(T),Dt.startsWith("inline")||Mt({id:t.id,version:t.version})}else if("artifact_rewrite"===e.event){const t=JSON.parse(e.data);T=T.filter((e=>!(e.id===t.id&&e.version===t.version))),T.push(Object.assign(Object.assign({},t),{content:"",status:"streaming"})),Lt(T),Dt.startsWith("inline")||Mt({id:t.id,version:t.version})}else if("artifact_content"===e.event){const t=JSON.parse(e.data),n=t.token.replace(/\u200B/g,"");T=T.map((e=>e.id===t.id&&e.version===t.version?Object.assign(Object.assign({},e),{content:e.content+n,status:"streaming"}):e)),Lt(T)}else if("artifact_finished"===e.event){const t=JSON.parse(e.data);Lt(T.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 xt(t.limitData),jt(""),void(P=!0);const n=t.error||t.message||(null==qe?void 0:qe["something-went-wrong-try-again"])||"Something went wrong, please try again.";if(to(t))return void(P=!0);jt(n)}else"stop"===e.event&&(P=!0)}else P=!0}});for(;;){if(C()){P=!0,t.cancel().catch((()=>{}));break}const{value:e,done:s}=yield t.read();if(C()){P=!0,t.cancel().catch((()=>{}));break}if(s)break;o.feed(n.decode(e))}P||C()||(yield new Promise((e=>setTimeout(e,1e3))))}catch(e){if("STOP_STREAM"===e.message||ce(e)||C())return void(P=!0);console.warn("Stream connection lost, retrying...",e),yield new Promise((e=>setTimeout(e,1e3)))}null==dt||dt($e)}catch(e){if(ce(e))return;if(e.limitData)xt(e.limitData),jt("");else{let t=H(e)||"";t&&!t.includes("Unexpected token 'A',")||(t=(null==qe?void 0:qe["high-traffic-try-again-later"])||"Oops! We're experiencing high traffic at the moment. Please try again later."),to(t)||jt(t)}}finally{const e=!m||bn.current===m;At(),e&&(yt("idle"),Ut(),hn.current=null),m&&e&&(bn.current=null,xn.current=[]),yield so()}}));return g((()=>{if(ht||Ht||Yt||0===zt.length)return;const e=zt[0];Zt(!0),tn(e.id),t(void 0,void 0,void 0,(function*(){try{if(!(yield Uo(e.predecessorSubmissionId)))return void jt((null==qe?void 0:qe["queued-message-waiting"])||"A queued message is waiting for the previous response to finish.");Qt((t=>t.filter((t=>t.id!==e.id)))),yield Po(e.message,!1,!0,e.id)}finally{Zt(!1),tn(null)}}))}),[ht,Yt,Ht,zt]),eo?null:n("div",Object.assign({className:J("flex w-full flex-shrink-0 flex-col items-center",!Zn&&"px-4 pb-8"),dir:Ye?"rtl":"ltr"},{children:o("div",Object.assign({className:"flex w-full max-w-[800px] flex-col"},{children:[zt.length>0&&n("div",Object.assign({className:"mx-3 -mb-3 overflow-hidden border pb-3",style:{borderColor:We.text+"18",backgroundColor:null!==(Pe=Gn.backgroundColor)&&void 0!==Pe?Pe:We.text+"08",color:We.text,borderTopLeftRadius:Math.max(He.cornerRadius-4,12),borderTopRightRadius:Math.max(He.cornerRadius-4,12)}},{children:zt.map(((e,i)=>{var r;return o("div",Object.assign({className:"flex min-h-10 items-center gap-2 px-3 py-2",style:i<zt.length-1?{borderBottom:`1px solid ${We.text}12`}:void 0},{children:[n(L,{className:"h-4 w-4 shrink-0 opacity-50","aria-hidden":"true"}),n("span",Object.assign({className:"min-w-0 flex-1 truncate text-sm",title:e.message},{children:e.message})),nn===e.id||en===e.id?o("span",Object.assign({className:"flex shrink-0 items-center gap-1.5 px-2 py-1 text-xs opacity-60","aria-live":"polite"},{children:[n("span",{className:"h-3 w-3 animate-spin rounded-full border border-current border-r-transparent","aria-hidden":"true"}),nn===e.id?(null==qe?void 0:qe.steering)||"Steering...":(null==qe?void 0:qe.starting)||"Starting..."]})):o(s,{children:[o("button",Object.assign({type:"button",className:"shrink-0 rounded-md px-2 py-1 text-xs font-medium opacity-70 transition-opacity hover:opacity-100 disabled:cursor-default disabled:opacity-40",disabled:Ht||!ht,onClick:()=>{(e=>{t(void 0,void 0,void 0,(function*(){const t=bn.current;if(!t||Ht)return;const n=zt.findIndex((t=>t.id===e.id));if(-1===n)return;Wt(!0),on(e.id),jt(""),To(t);let o=!1;try{if(!(yield _o(t)))throw new Error((null==qe?void 0:qe["failed-to-interrupt-current-response"])||"Failed to interrupt the current response.");if(!(yield Uo(t)))throw new Error((null==qe?void 0:qe["current-response-still-stopping"])||"The current response is still stopping. Please send your message again in a moment.");yt("idle"),Qt((t=>t.filter((t=>t.id!==e.id)))),o=!0,Wt(!1),on(null),yield Po(e.message,!1,!0,e.id,!0)}catch(t){yt("idle"),o&&Qt((t=>{if(t.some((t=>t.id===e.id)))return t;const o=[...t];return o.splice(n,0,e),o})),jt(H(t))}finally{Wt(!1),on(null)}}))})(e)},"aria-label":`${(null==qe?void 0:qe["steer-with"])||"Steer with"}: ${e.message}`},{children:[n("span",Object.assign({"aria-hidden":"true"},{children:"↳ "})),(null==qe?void 0:qe.steer)||"Steer"]})),n("button",Object.assign({type:"button",className:"flex h-7 w-7 shrink-0 items-center justify-center rounded-md opacity-50 transition-opacity hover:opacity-100 disabled:cursor-default disabled:opacity-30",disabled:Ht,onClick:()=>{return t=e.id,void Qt((e=>re(e,t)));var t},"aria-label":`${(null==qe?void 0:qe["remove-queued-message"])||"Remove queued message"}: ${e.message}`},{children:n(R,{className:"h-4 w-4","aria-hidden":"true"})})),o(F,Object.assign({id:`queued-message-menu-${e.id}`,className:"shrink-0"},{children:[n(G,Object.assign({className:"flex h-7 w-7 items-center justify-center rounded-md opacity-50 transition-opacity hover:opacity-100",isDisabled:Ht,role:"button",tabIndex:Ht?-1:0,"aria-haspopup":"menu","aria-label":(null==qe?void 0:qe["more-options"])||"More options",onKeyDown:e=>{"Enter"!==e.key&&" "!==e.key||(e.preventDefault(),e.currentTarget.click())}},{children:o("svg",Object.assign({viewBox:"0 0 24 24",className:"h-4 w-4",fill:"currentColor","aria-hidden":"true"},{children:[n("circle",{cx:"5",cy:"12",r:"1.6"}),n("circle",{cx:"12",cy:"12",r:"1.6"}),n("circle",{cx:"19",cy:"12",r:"1.6"})]}))})),n(V,Object.assign({role:"menu",align:Ye?"bottom-start":"bottom-end",positionStrategy:Ze?"absolute":"fixed",width:"auto",className:"p-1 text-sm shadow-xl",style:{backgroundColor:null!==(r=Gn.backgroundColor)&&void 0!==r?r:We.primary,color:We.text,borderRadius:"12px"},border:`1px solid ${We.text}20`},{children:o("button",Object.assign({type:"button",role:"menuitem",className:"flex min-w-36 items-center gap-2 rounded-lg px-3 py-2 text-left transition-colors hover:bg-black/5 dark:hover:bg-white/10",onClick:()=>(e=>{Qt((t=>re(t,e.id))),Xt(e.message),requestAnimationFrame((()=>{const t=jn.current;t&&(t.focus(),t.setSelectionRange(e.message.length,e.message.length))}))})(e)},{children:[n($,{className:"h-4 w-4 shrink-0"}),(null==qe?void 0:qe["edit-message"])||"Edit message"]}))}))]}))]})]}),e.id)}))})),o("div",Object.assign({ref:wn,className:J("relative z-10 flex flex-col w-full justify-end gap-y-3 py-[3px]","block"===He.formFieldStyle&&"shadow"),style:Object.assign(Object.assign({},Gn),{maxHeight:`${Sn}px`,overflowY:"auto"})},{children:[wo&&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:Gn.backgroundColor?`${Gn.backgroundColor}E6`:void 0,borderColor:We.text+"20",color:We.text,borderTopRightRadius:He.cornerRadius+"px",borderTopLeftRadius:He.cornerRadius+"px"}},{children:[n("div",Object.assign({className:"flex items-center gap-2 text-sm font-medium"},{children:o("span",{children:[bo.toLocaleString()," ",ao?(null==qe?void 0:qe.credits)||"Credits":(null==qe?void 0:qe.uses)||"Uses"," ",(null==qe?void 0:qe.remaining)||"remaining"]})})),o("div",Object.assign({className:"flex items-center gap-3"},{children:[Oo&&n("button",Object.assign({className:"rounded-md px-3 py-1.5 text-xs font-semibold transition-opacity hover:opacity-90",style:{backgroundColor:We.accent,color:We.accentText},onClick:e=>{if(e.preventDefault(),e.stopPropagation(),No)return void window.open(No,"_blank","noopener,noreferrer");if(lt)return void lt();const t=z({baseUrl:an,accessGroupId:null==tt?void 0:tt.accessGroupId});t&&Q({deploymentId:Fe,pricingUrl:t,studioId:null==Ve?void 0:Ve.studioid,studioSessionToken:pt})}},{children:So})),n("button",Object.assign({className:"flex h-6 w-6 items-center justify-center rounded-full opacity-60 transition-opacity hover:opacity-100",onClick:()=>pn(!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"})}))}))]}))]})),!ht&&wt.length>0&&n(B,{className:"p-4 pb-0",isDisabled:ht}),o("div",Object.assign({className:"relative flex w-full flex-col"},{children:[Qn&&o("div",Object.assign({className:J(ut?"top-6":"top-1/2","pointer-events-none absolute z-10 flex -translate-y-1/2 select-none items-center gap-x-2",Ye?"right-4":"left-4")},{children:[n("span",{className:"h-2 w-2 animate-pulse rounded-full bg-c-secondary",style:{backgroundColor:null!==(De=We.accent)&&void 0!==De?De:"#ff0000"}}),n("span",Object.assign({className:"text-sm text-c-secondary font-semilight",style:{color:We.text+"90"}},{children:(null==qe?void 0:qe.listening)||"Listening..."}))]})),n(X,Object.assign({ref:jn,className:J(Fn.i1,"py-3.5 max-h-60 px-4 w-full border-transparent bg-transparent",!Bt.trim()&&!Bt.includes("\n")&&"overflow-hidden text-ellipsis whitespace-nowrap placeholder:whitespace-normal placeholder:overflow-visible",Ye?"text-right":"text-left",!ut&&oo&&"mb-12"),value:Bt,placeholder:Qn?"":no,onChange:e=>{Xt(e)},onKeyDown:e=>{ze||_t||"Enter"===e.key&&(e.shiftKey||(e.preventDefault(),kt||Ht||(ht?Ao():Po())))},onPaste:e=>t(void 0,void 0,void 0,(function*(){const t=Array.from(e.clipboardData.files||[]);if(t.length>0){if(!Jn)return;e.preventDefault(),nt(!1),yield Nt(t)}}))},ue&&{onFocus:ue},fe&&{onBlur:fe},{dir:Ye?"rtl":"ltr"})),o("div",Object.assign({ref:In,className:ut?"relative flex w-full items-center gap-2 px-3 pb-2 [&>button]:shrink-0 [&>button]:mr-0":J("flex items-center gap-2 absolute z-2 transition-all duration-200 ease-in-out",oo?"bottom-3 right-2":"right-0 top-1/2 -translate-y-1/2"),style:Object.assign(Object.assign({},!oo&&Gn.backgroundColor&&{backgroundColor:Gn.backgroundColor}),{borderTopRightRadius:He.cornerRadius+"px",borderBottomRightRadius:He.cornerRadius+"px"})},{children:[!ht&&!En&&Jn&&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:Rn?We.accent+"10":void 0,color:Rn?We.accent:We.accent+"80"},disabled:kt||ht,"aria-label":null!==(Le=null==qe?void 0:qe["attach-files"])&&void 0!==Le?Le:"Attach files",onClick:()=>{var e;return null===(e=fn.current)||void 0===e?void 0:e.click()}},$n,{children:[n("input",{id:"file-upload",ref:fn,type:"file",accept:[...E,..._,...T].join(", "),multiple:!0,hidden:!0,className:"hidden",onChange:e=>t(void 0,void 0,void 0,(function*(){nt(!1),yield Nt(Array.from(e.target.files||[])),e.target.value=""}))}),n(A,{className:"h-6 w-6 shrink-0"})]})),n(a,{compact:!0}),ht&&!qt?o(s,{children:[n("button",Object.assign({"aria-label":(null==qe?void 0:qe["stop-response"])||"Stop response",className:"flex h-8 w-8 items-center justify-center rounded-full outline-none transition-colors duration-200 ease-in-out",onClick:()=>{const e=bn.current;e&&(To(e),_o(e)),yt("idle")},style:{backgroundColor:We.accent+"10",color:We.accent}},{children:n(M,{className:"h-4 w-4 shrink-0"})})),n("button",Object.assign({"aria-label":(null==qe?void 0:qe["queue-message"])||"Queue message",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",disabled:Ht||kt||!Bt.trim(),onClick:Ao,style:{backgroundColor:Bt.trim()?We.accent:We.accent+"10",color:Bt.trim()?We.accentText:We.accent+"80"}},{children:n(P,{className:J("h-6 w-6 shrink-0",Ye&&"scale-x-[-1] transform")})}))]}):En?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:An,style:{backgroundColor:We.accent,color:We.accentText}},{children:n(M,{className:"h-4 w-4 shrink-0"})})):o(s,{children:[zn&&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:En?We.accent:Xn?We.accent+"10":void 0,color:En?We.accentText:Xn?We.accent:We.accent+"80"},disabled:kt||ht||_n,onClick:()=>{En?An():(vn.current=Bt,Un(Je||"en-US"))}},Kn,{children:n(D,{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:Dn||Eo?We.accent:We.accent+"10",color:Dn||Eo?We.accentText:We.accent+"80"},disabled:!Eo,onClick:()=>Po()},Ln,{children:n(P,{className:J("h-6 w-6 shrink-0",Ye&&"scale-x-[-1] transform")})}))]})]}))]}))]})),Ot&&n(K,{error:Ot,className:"mt-3"})]}))}))}));fe.displayName="Input";export{fe 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{canChat as i}from"../../../common/canChat.js";import{useEndUserModel as r}from"../../../hooks/pickaxe/useEndUserModel.js";import a from"../common/EndUserModelPicker.js";import{updateStreamTextPart as l,upsertActionApprovalPart as d}from"../../../common/actionApproval.js";import{forwardRef as c,useState as u,useRef as p,useCallback as m,useEffect as g,useMemo as f,useImperativeHandle as v}from"react";import{usePickaxeContext as h}from"../../../hooks/pickaxe/usePickaxeContext.js";import{useResponseContext as b}from"../../../hooks/pickaxe/useResponseContext.js";import{useStyleInput as y}from"../../../hooks/studio/useStyleInput.js";import{useStyleFontSize as x}from"../../../hooks/studio/useStyleFontSize.js";import{useConversation as j}from"../../../hooks/pickaxe/useConversation.js";import{useDimensionContext as I}from"../../../hooks/pickaxe/useDimensionContext.js";import{useAuthContext as w}from"../Addons/Auth/hooks/useAuthContext.js";import{useDocument as k}from"../Addons/Document/hooks/useDocument.js";import{useScroll as O}from"../Addons/Scroll/hooks/useScroll.js";import{useArtifactContext as N}from"../Addons/Artifact/hooks/useArtifactContext.js";import{useHover as S}from"../../../hooks/core/useHover.js";import{useMediaQuery as C}from"../../../hooks/core/useMediaQuery.js";import{allowedFileMimeTypes as E,allowedImageMimeTypes as _,additionalAllowedFileExtensions as T}from"../../../common/documents.js";import{createParser as U}from"eventsource-parser";import A from"../../Icons/attach-vertical.svg.js";import P from"../../Icons/arrow-right.svg.js";import D from"../../Icons/microphone.svg.js";import L from"../../Icons/message-clock.svg.js";import M from"../../Icons/stop.svg.js";import R from"../../Icons/trash.svg.js";import $ from"../../Icons/pencil.svg.js";import B from"../Addons/Document/List.js";import X from"../../Core/Textarea.js";import K from"../../Core/ErrorAlert.js";import F from"../../Core/Menu/index.js";import G from"../../Core/Menu/Button.js";import V from"../../Core/Menu/List.js";import H from"../../../common/error.js";import{pickaxeApi2 as W}from"../../../common/api/pickaxe.js";import{getValidationFailure as q}from"../../../common/validation.js";import J from"../../../common/cn.js";import{buildUpgradeUrl as z,openAuthenticatedPricingUrl as Q,initializeEmbedUserId as Y}from"../../../common/utils.js";import{getPickaxeConfigMetadata as Z}from"../../../common/pickaxeConfig.js";import{readAgentPrefill as ee}from"../../../common/agentPrefill.js";import{fireDeploymentSessionInitializedWebhook as te,fireDeploymentFirstMessageSubmittedWebhook as ne}from"../../../common/deploymentWebhooks.js";import{useStudio as oe}from"../../../hooks/studio/useStudio.js";import{useSpeechToText as se}from"../../../hooks/pickaxe/useSpeechToText.js";import{STUDIO_INFINITY_VALUE as ie}from"../common/PickaxeCommon.js";const re=(e,t)=>{const n=e.find((e=>e.id===t));return n?e.filter((e=>e.id!==t)).map((e=>e.predecessorSubmissionId===t?Object.assign(Object.assign({},e),{predecessorSubmissionId:n.predecessorSubmissionId}):e)):e},ae=e=>"string"==typeof e&&e.trim().length>0,le=()=>"undefined"!=typeof crypto&&"randomUUID"in crypto?crypto.randomUUID():`submission-${Date.now()}-${Math.random().toString(36).slice(2)}`,de=e=>e.map((e=>Object.assign({},e))),ce=e=>e instanceof Error&&("AbortError"===e.name||"BodyStreamBuffer was aborted"===e.message),ue=(e,t)=>{if(e&&"object"==typeof e)return e[t]},pe=(e,t)=>{const n=ue(e,t);return ae(n)?n:null},me=e=>{const t=Number(e);return Number.isFinite(t)?t:void 0},ge=({studioUser:e,deploymentId:t,portalId:n})=>{var o,s;const i=Array.isArray(ue(e,"uses"))?ue(e,"uses"):[],r=(({deploymentId:e,portalId:t})=>ae(e)?{type:"deployment",id:e}:ae(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}},fe=c((({resubmitPrompt:c,onFocus:ue,onBlur:fe,onInputHeightChange:ve,initSmitheryAuthData:he},be)=>{var ye,xe,je,Ie,we,ke,Oe,Ne,Se,Ce,Ee,_e,Te,Ue,Ae,Pe,De,Le;const{origin:Me,pickaxeId:Re,sessionId:$e,sender:Be,senderType:Xe,portalId:Ke,deploymentId:Fe,deploymentType:Ge,pickaxe:Ve,styles:He,colors:We,translations:qe,locale:Je,forceMobile:ze,isNewChat:Qe,isRtl:Ye,isEmbed:Ze,isShowFeedbackMessage:et,accessGroup:tt,setIsNewChat:nt,setIsShowIceBreaker:ot,setValidationStatus:st,setValidationUpgradeGroups:it,setValidationUpgradeUrl:rt,setAccessGroup:at,onUpgrade:lt,onGenerateComplete:dt}=h(),{value:ct,enabled:ut}=r(),{token:pt,isLoggedOut:mt,isSent:gt,isPricingAuth:ft}=w(),{messages:vt,isGenerating:ht,setMessages:bt,setStatus:yt,setLimitData:xt,setError:jt,setActionApprovalToken:It}=b(),{documents:wt,isUploading:kt,documentError:Ot,onFileUpload:Nt,setDocuments:St,setDocumentError:Ct}=k(),{studio:Et}=oe(),[_t]=C("(max-width: 480px)"),{scrollStartSession:Tt,scrollEndSession:Ut,scrollToBottom:At}=O({auto:!0,smooth:!(ze||_t)}),{artifacts:Pt,currentPopupType:Dt,setArtifacts:Lt,setCurrentArtifact:Mt}=N(),{height:Rt}=I(),$t=j(),[Bt,Xt]=u((()=>ee([Fe,Re]).chatInput)),[Kt,Ft]=u(!1),[Gt,Vt]=u(!1),[Ht,Wt]=u(!1),[qt,Jt]=u(!1),[zt,Qt]=u([]),[Yt,Zt]=u(!1),[en,tn]=u(null),[nn,on]=u(null),[sn,rn]=u(null),[an,ln]=u(null),[dn,cn]=u(!1),[un,pn]=u(!1),[mn,gn]=u(0),fn=p(null),vn=p(""),hn=p(null),bn=p(null),yn=p(null),xn=p([]),jn=p(null),In=p(null),wn=p(null),kn=p(null),On=p(new Set),Nn=p(null),Sn=Math.max(.4*Rt,100),{speechTranscript:Cn,isSpeechListening:En,isSpeechProcessing:_n,isSpeechSupported:Tn,onStartListening:Un,onStopListening:An}=se(),Pn=S(),{isHover:Dn}=Pn,Ln=e(Pn,["isHover"]),Mn=S(),{isHover:Rn}=Mn,$n=e(Mn,["isHover"]),Bn=S(),{isHover:Xn}=Bn,Kn=e(Bn,["isHover"]),Fn=x(),Gn=y(),Vn="undefined"!=typeof window?window.location.hostname:"",Hn="undefined"!=typeof window?window.location.href:"",Wn="undefined"!=typeof window&&window.self!==window.top,qn=Vn.includes("pickaxe.co")&&!Hn.includes("https://studio.pickaxe.co/_embed")&&!Wn,Jn=null!==(xe=null===(ye=null==Ve?void 0:Ve.documentuploadtype)||void 0===ye?void 0:ye.startsWith("enduserupload"))&&void 0!==xe&&xe,zn=Tn&&(null==Ve?void 0:Ve.enablevoicetotext),Qn=En&&!Bt.trim(),Yn=ae(Fe),Zn="chat-input"===Ge&&Qe&&!gt,eo="chat-input"===Ge&&ft&&mt&>,to=m((e=>{const t=q(e);return!!t&&(jt(""),xt(null),st(t.status),at(t.accessGroup),it(t.upgradeGroups),rt(t.upgradeUrl),!0)}),[jt,It,xt,st,it,rt,at]),no=null!==(je=null==Ve?void 0:Ve.placeholdertext)&&void 0!==je?je:Ye?"بماذا تريد أن تتحدث؟":(null==qe?void 0:qe["what-do-you-want-to-talk-about"])||"What do you want to talk about?",oo=Kt||Gt,so=m((()=>t(void 0,void 0,void 0,(function*(){cn(!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==Ve?void 0:Ve.studioid},pt?{studioSessionToken:pt}:Be?{sender:Be}:{sender:Y()}))},(!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}})),qn&&{credentials:"include"})),t=yield e.json();(null==t?void 0:t.studioUser)&&(rn(t.studioUser),ln(t.url))}catch(e){console.error("Failed to fetch studio user:",e)}finally{cn(!0)}}))),[qn,null==Ve?void 0:Ve.studioid,Be,pt]);g((()=>{so()}),[so]);const io=Number(null!==(Ie=null==tt?void 0:tt.limit)&&void 0!==Ie?Ie:0),ro="string"==typeof(null==tt?void 0:tt.limitInterval)?tt.limitInterval:null,ao=!!(null==Et?void 0:Et.data.usage)&&Et.data.usage.isCredits,lo=f((()=>{var e,t,n,o,s;return null!==(s=null!==(o=null!==(n=null!==(t=null!==(e=null!=Ke?Ke:pe(sn,"portalId"))&&void 0!==e?e:pe(sn,"portalid"))&&void 0!==t?t:pe(tt,"portalId"))&&void 0!==n?n:pe(tt,"portalid"))&&void 0!==o?o:pe(Ve,"portalId"))&&void 0!==s?s:pe(Ve,"portalid")}),[tt,Ke,Ve,sn]),co=f((()=>ge({studioUser:sn,deploymentId:Fe,portalId:lo})),[Fe,lo,sn]);g((()=>{Yn&&Qe&&$e&&On.current.add($e)}),[Qe,$e,Yn]);const uo=m((()=>{var e,t,n;return{studioId:null==Ve?void 0:Ve.studioid,userEmail:pe(sn,"email"),userId:null!==(e=pe(sn,"userId"))&&void 0!==e?e:pe(sn,"userid"),sessionId:$e,deploymentId:Fe,deploymentType:Ge,portalId:lo,accessGroupId:null!==(t=null==tt?void 0:tt.accessGroupId)&&void 0!==t?t:null,pickaxeId:Re,sender:Be,senderType:Xe,origin:Me,metadata:null!==(n=Z(Fe))&&void 0!==n?n:null}}),[null==tt?void 0:tt.accessGroupId,Fe,Ge,Me,null==Ve?void 0:Ve.studioid,Re,lo,Be,Xe,$e,sn]),po=m((()=>!!(Yn&&dn&&$e)&&(!!On.current.has($e)&&(te(uo()),On.current.delete($e),!0))),[uo,dn,$e,Yn]);g((()=>{if(!dn||!$e)return;po();const e=Nn.current;(null==e?void 0:e.sessionId)===$e&&(ne(Object.assign(Object.assign(Object.assign({},e),uo()),{message:e.message,documentIds:e.documentIds,uploadedModelImages:e.uploadedModelImages,hasUploadedDocuments:e.hasUploadedDocuments,isHidden:e.isHidden})),Nn.current=null)}),[po,uo,dn,$e]);const mo={currentUses:me(null==sn?void 0:sn.currentUses),extraUses:me(null==sn?void 0:sn.extraUses)},go=co.scope?{currentUses:null!==(ke=me(null===(we=co.record)||void 0===we?void 0:we.currentUses))&&void 0!==ke?ke:0,extraUses:null!==(Ne=me(null===(Oe=co.record)||void 0===Oe?void 0:Oe.extraUses))&&void 0!==Ne?Ne:0}:{currentUses:0,extraUses:0},fo=pe(sn,"type"),vo="guest"===fo||!fo&&mt?go:mo;g((()=>{let e=!0;return t(void 0,void 0,void 0,(function*(){var t;if(ao&&(null===(t=null==Et?void 0:Et.data)||void 0===t?void 0:t.workspaceId))try{const t=yield W.get(`/cost_per_run?workspaceId=${Et.data.workspaceId}`,{withCredentials:!1});e&&gn(1e4*(Number(t.data.costPerRun)||0))}catch(t){console.error("Failed to fetch average cost per run:",t),e&&gn(0)}else e&&gn(0)})),()=>{e=!1}}),[ao,null===(Se=null==Et?void 0:Et.data)||void 0===Se?void 0:Se.workspaceId]);const ho=(({accessGroupType:e,currentUses:t,extraUses:n,limit:o,limitInterval:s})=>{const i=Number(null!=t?t:0),r=Number(null!=n?n:0);return"public"===e&&"one_time"===s?o===ie?ie:Math.max(0,o-i):o===ie||r===ie?ie:"one_time"===s?Math.max(0,r):Math.max(0,o-i)+r})({accessGroupType:null==tt?void 0:tt.type,currentUses:vo.currentUses,extraUses:vo.extraUses,limit:io,limitInterval:ro}),bo=ho===ie?ie:Math.max(0,Math.ceil(ho)),yo=(({accessGroupType:e,extraUses:t,limit:n,limitInterval:o})=>{const s=Number(null!=t?t:0);return"public"===e&&"one_time"===o?n===ie?ie:Math.max(0,n):n===ie||s===ie?ie:"one_time"===o?Math.max(0,s):Math.max(0,n)+Math.max(0,s)})({accessGroupType:null==tt?void 0:tt.type,extraUses:vo.extraUses,limit:io,limitInterval:ro}),xo=yo===ie?ie:Math.ceil(.05*yo),jo=ao?Math.ceil(5*mn):5,Io=xo===ie?ie:Math.max(xo,jo),wo=f((()=>!!sn&&(!un&&(bo!==ie&&(!(yo<=0||bo>=yo)&&bo<=Io)))),[un,Io,bo,sn,yo]),ko=Boolean(null==tt?void 0:tt.hideUpgradeOptions),Oo=Boolean(!ko&&((null===(Ce=null==tt?void 0:tt.upgrade)||void 0===Ce?void 0:Ce.isBuyMoreUses)||(null===(Ee=null==tt?void 0:tt.upgrade)||void 0===Ee?void 0:Ee.isLinkToCustomURL)||(null===(_e=null==tt?void 0:tt.upgrade)||void 0===_e?void 0:_e.isUpgradeToAnotherGroup)&&(null===(Te=tt.upgrade.accessGroupIds)||void 0===Te?void 0:Te.length))),No=!ko&&(null===(Ue=null==tt?void 0:tt.upgrade)||void 0===Ue?void 0:Ue.isLinkToCustomURL)&&"string"==typeof tt.upgrade.limitLink&&tt.upgrade.limitLink.trim().length>0?tt.upgrade.limitLink.trim():null,So=No&&"string"==typeof(null===(Ae=null==tt?void 0:tt.upgrade)||void 0===Ae?void 0:Ae.limitCTA)&&tt.upgrade.limitCTA.trim().length>0?tt.upgrade.limitCTA:(null==qe?void 0:qe["pricing.upgrade"])||(null==qe?void 0:qe.upgrade)||"Upgrade",Co=f((()=>{var e,t,n;return!!Qe&&(!!Ve&&(!$t.isLoading&&(!((null!==(t=null===(e=$t.data)||void 0===e?void 0:e.messages.length)&&void 0!==t?t:0)>1)&&(!!(null===(n=Ve.icebreakers)||void 0===n?void 0:n.length)&&(!et&&!Zn)))))}),[Ve,Qe,et,Zn,$t.data,$t.isLoading]),Eo=f((()=>{if(kt||Ht)return!1;const e=Jn&&wt.length>0&&wt.every((e=>"finished"===e.status));return!(!Bt.trim()&&!e)&&wt.every((e=>"finished"===e.status||e.isInsertedAsRaw))}),[Jn,kt,Ht,Bt,wt]);v(be,(()=>({onSubmit:Po}))),g((()=>{ot(Co)}),[Co]),g((()=>{var e;if(c){const t=Array.from(vt),n=null===(e=t[t.length-2].parts.find((e=>"text"===e.type)))||void 0===e?void 0:e.content;Po(n,!0)}}),[c]),g((()=>{if(!wn.current||!ve)return;const e=new ResizeObserver((e=>{for(const t of e)ve(t.contentRect.height)}));return e.observe(wn.current),()=>{e.disconnect()}}),[ve]),g((()=>{if(!En)return;const e=vn.current?`${vn.current} `:"";Xt(`${e}${Cn}`)}),[Cn,En]),g((()=>{if(!jn.current)return;(()=>{if(!jn.current)return;let e=jn.current.scrollHeight>52;Bt.includes("\n")||wt.length?e=!0:Bt.trim()||(e=!1),Ft(e)})()}),[Bt,wt]),g((()=>{const e=jn.current,t=In.current;if(!e||!t||ut||Kt||Bt.includes("\n"))return void Vt(!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=Bt||no,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;Vt(i>l)}),[Bt,Kt,no,ut]);const _o=e=>t(void 0,void 0,void 0,(function*(){if(!(e=null!=e?e:bn.current))return!1;const t=de(xn.current);try{return(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})},qn&&{credentials:"include"}))).ok}catch(e){return console.warn("Failed to cancel submission",e),!1}})),To=e=>{yn.current=e,kn.current&&(kn.current.abort(),kn.current=null),hn.current&&(hn.current.cancel().catch((()=>{})),hn.current=null)},Uo=e=>t(void 0,void 0,void 0,(function*(){const t=Date.now()+3e4;for(;Date.now()<t;){try{const t=yield fetch(`${process.env.NEXT_PUBLIC_PICKAXE_API2_URL}/response/status/${e}`,Object.assign({headers:Object.assign({"Cache-Control":"no-cache"},(!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}))},qn&&{credentials:"include"}));if(t.ok){if((yield t.json()).terminal)return!0}}catch(e){console.warn("Failed to read submission status",e)}yield new Promise((e=>setTimeout(e,250)))}return!1})),Ao=()=>{const e=bn.current;e&&!Ht&&!kt&&Bt.trim()&&(Qt((t=>{var n,o;return[...t,{id:le(),message:Bt,predecessorSubmissionId:null!==(o=null===(n=t[t.length-1])||void 0===n?void 0:n.id)&&void 0!==o?o:e}]})),Xt(""))},Po=(e,n=!1,o=!1,s,r=!1)=>t(void 0,void 0,void 0,(function*(){var t,a,c,u,p;if(!i(Ve))return;let m=null;try{if(ht&&!o||kt||En||_n)return;const i=wt.filter((e=>"finished"===e.status&&!e.isInsertedAsRaw)),g=i.map((e=>e.documentId)).filter(Boolean),f=i.filter((e=>"image"===e.type)).map((e=>{const t=e.name.split(".").pop()||"";return{documentId:e.documentId,extension:t}})),v=null!=e?e:Bt,h=null!==(a=null===(t=null==Ve?void 0:Ve.documentuploadtype)||void 0===t?void 0:t.startsWith("enduserupload"))&&void 0!==a&&a&&g.length>0;if(!v&&!h)return;jt(""),Ct(""),xt(null),Xt(""),nt(!1),Jt(!1),yt("fetching"),Tt(),At();const b=n?vt.slice(0,vt.length-1):vt,y=(e=>e.reduce(((e,t)=>Math.max(e,t.id)),0)+1)(b),x=y+(n?0:1),j={id:x,role:"assistant",parts:[],documentIds:[]},I=[...b,...n?[]:[{id:y,role:"user",parts:[{type:"text",content:v,isVisible:!0}],documentIds:h?g:[]}],j];bt(I),At(),h&&St([]);const w=Z(Fe),k=null!=s?s:le();m=k,bn.current=k,yn.current=null,xn.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(Object.assign(Object.assign({supportsActionConfirmation:!0,selectedModel:ct||void 0,origin:Me,pickaxeId:Re,sessionId:$e,submissionId:k},r&&{interactionType:"steer"}),{senderType:Xe,value:v}),h&&{documentIds:g}),Be&&{sender:Be}),pt&&{studioSessionToken:pt}),!pt&&!Be&&{sender:Y()}),lo&&{portalId:lo}),Fe&&{deploymentId:Fe}),w&&{metadata:w}),h&&f.length>0?{uploadedModelImages:f}:{})),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()})},qn&&{credentials:"include"})),N=yield O.json();if(!N.success){if(N.limitData){const e=new Error(N.error||N.message||(null==qe?void 0:qe["failed-to-start-generation"])||"Failed to start generation");throw e.limitData=N.limitData,e}if(to(N))return;throw new Error(N.error||N.message||(null==qe?void 0:qe["failed-to-start-generation"])||"Failed to start generation")}It(null!==(c=N.actionApprovalToken)&&void 0!==c?c:null);const S=null!==(u=N.submissionId)&&void 0!==u?u:k;m=S,bn.current=S;const C=()=>yn.current===S;if(C())return;Yn&&Qe&&$e&&On.current.add($e);const E=Object.assign(Object.assign({},uo()),{message:v,documentIds:h?g:[],uploadedModelImages:h?f:[],hasUploadedDocuments:h,isHidden:n,metadata:null!=w?w:null});dn?(po(),ne(E)):Nn.current=E,yt("streaming"),kn.current=new AbortController;const _=[];let T=[...null!=Pt?Pt:[]],A=0,P=!1,D="";for(;!P;)try{const e=yield fetch(`${process.env.NEXT_PUBLIC_PICKAXE_API2_URL}/response/stream/${S}?index=${A}`,{signal:null===(p=kn.current)||void 0===p?void 0:p.signal,headers:{"Cache-Control":"no-cache",Connection:"keep-alive"}});if(!e.body)throw new Error("No response body");const t=e.body.getReader();hn.current=t;const n=new TextDecoder,o=U({onEvent:e=>{var t,n;if(C())P=!0;else if(e.event&&"ping"!==e.event&&A++,"stop"!==e.event){if("error"===e.event){const t=JSON.parse(e.data);if(t.limitData)return xt(t.limitData),jt(""),void(P=!0);const n=t.error||t.message||(null==qe?void 0:qe["something-went-wrong"])||"Something went wrong.";return to(t)||jt(n),void(P=!0)}if("delta"===e.event){const o=JSON.parse(e.data);if("finish"===o.type)return void Jt(!0);if("data-error"===o.type&&he){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 P=!0,he({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 P=!0,he({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 P=!0,he({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 P=!0,he({provider:"composio",toolkitSlug:t.toolkitSlug,serverId:t.serverId,name:t.name}),new Error("STOP_STREAM")}}else if("text-start"===o.type)D="",_.push({type:"text",content:"",isVisible:null===(t=o.isVisible)||void 0===t||t});else if("text-delta"===o.type)D+=o.delta,l(_,"text",D);else if("text-end"===o.type)D="";else if("reasoning-start"===o.type)D="",_.push({type:"reasoning",content:"",isVisible:null===(n=o.isVisible)||void 0===n||n});else if("reasoning-delta"===o.type)D+=o.delta,l(_,"reasoning",D);else if("reasoning-end"===o.type)D="";else if(o.type.startsWith("data-")){const e=o;"data-action-approval"===e.type?d(_,e.data):_.push({type:e.type,content:JSON.stringify(e.data),isVisible:!0})}xn.current=de(_);const s=de(_);bt((e=>{const t=e.findIndex((e=>e.id===x)),n=Object.assign(Object.assign({},j),{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);T=T.filter((e=>!(e.id===t.id&&e.version===t.version))),T.push(Object.assign(Object.assign({},t),{content:"",status:"streaming"})),Lt([...T]),Dt.startsWith("inline")||Mt({id:t.id,version:t.version})}else if("artifact_updated"===e.event){const t=JSON.parse(e.data);T=T.filter((e=>!(e.id===t.id&&e.version===t.version))),T.push(Object.assign(Object.assign({},t),{content:"",status:"updating"})),Lt(T),Dt.startsWith("inline")||Mt({id:t.id,version:t.version})}else if("artifact_rewrite"===e.event){const t=JSON.parse(e.data);T=T.filter((e=>!(e.id===t.id&&e.version===t.version))),T.push(Object.assign(Object.assign({},t),{content:"",status:"streaming"})),Lt(T),Dt.startsWith("inline")||Mt({id:t.id,version:t.version})}else if("artifact_content"===e.event){const t=JSON.parse(e.data),n=t.token.replace(/\u200B/g,"");T=T.map((e=>e.id===t.id&&e.version===t.version?Object.assign(Object.assign({},e),{content:e.content+n,status:"streaming"}):e)),Lt(T)}else if("artifact_finished"===e.event){const t=JSON.parse(e.data);Lt(T.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 xt(t.limitData),jt(""),void(P=!0);const n=t.error||t.message||(null==qe?void 0:qe["something-went-wrong-try-again"])||"Something went wrong, please try again.";if(to(t))return void(P=!0);jt(n)}else"stop"===e.event&&(P=!0)}else P=!0}});for(;;){if(C()){P=!0,t.cancel().catch((()=>{}));break}const{value:e,done:s}=yield t.read();if(C()){P=!0,t.cancel().catch((()=>{}));break}if(s)break;o.feed(n.decode(e))}P||C()||(yield new Promise((e=>setTimeout(e,1e3))))}catch(e){if("STOP_STREAM"===e.message||ce(e)||C())return void(P=!0);console.warn("Stream connection lost, retrying...",e),yield new Promise((e=>setTimeout(e,1e3)))}null==dt||dt($e)}catch(e){if(ce(e))return;if(e.limitData)xt(e.limitData),jt("");else{let t=H(e)||"";t&&!t.includes("Unexpected token 'A',")||(t=(null==qe?void 0:qe["high-traffic-try-again-later"])||"Oops! We're experiencing high traffic at the moment. Please try again later."),to(t)||jt(t)}}finally{const e=!m||bn.current===m;At(),e&&(yt("idle"),Ut(),hn.current=null),m&&e&&(bn.current=null,xn.current=[]),yield so()}}));return g((()=>{if(ht||Ht||Yt||0===zt.length)return;const e=zt[0];Zt(!0),tn(e.id),t(void 0,void 0,void 0,(function*(){try{if(!(yield Uo(e.predecessorSubmissionId)))return void jt((null==qe?void 0:qe["queued-message-waiting"])||"A queued message is waiting for the previous response to finish.");Qt((t=>t.filter((t=>t.id!==e.id)))),yield Po(e.message,!1,!0,e.id)}finally{Zt(!1),tn(null)}}))}),[ht,Yt,Ht,zt]),eo?null:n("div",Object.assign({className:J("flex w-full flex-shrink-0 flex-col items-center",!Zn&&"px-4 pb-8"),dir:Ye?"rtl":"ltr"},{children:o("div",Object.assign({className:"flex w-full max-w-[800px] flex-col"},{children:[zt.length>0&&n("div",Object.assign({className:"mx-3 -mb-3 overflow-hidden border pb-3",style:{borderColor:We.text+"18",backgroundColor:null!==(Pe=Gn.backgroundColor)&&void 0!==Pe?Pe:We.text+"08",color:We.text,borderTopLeftRadius:Math.max(He.cornerRadius-4,12),borderTopRightRadius:Math.max(He.cornerRadius-4,12)}},{children:zt.map(((e,i)=>{var r;return o("div",Object.assign({className:"flex min-h-10 items-center gap-2 px-3 py-2",style:i<zt.length-1?{borderBottom:`1px solid ${We.text}12`}:void 0},{children:[n(L,{className:"h-4 w-4 shrink-0 opacity-50","aria-hidden":"true"}),n("span",Object.assign({className:"min-w-0 flex-1 truncate text-sm",title:e.message},{children:e.message})),nn===e.id||en===e.id?o("span",Object.assign({className:"flex shrink-0 items-center gap-1.5 px-2 py-1 text-xs opacity-60","aria-live":"polite"},{children:[n("span",{className:"h-3 w-3 animate-spin rounded-full border border-current border-r-transparent","aria-hidden":"true"}),nn===e.id?(null==qe?void 0:qe.steering)||"Steering...":(null==qe?void 0:qe.starting)||"Starting..."]})):o(s,{children:[o("button",Object.assign({type:"button",className:"shrink-0 rounded-md px-2 py-1 text-xs font-medium opacity-70 transition-opacity hover:opacity-100 disabled:cursor-default disabled:opacity-40",disabled:Ht||!ht,onClick:()=>{(e=>{t(void 0,void 0,void 0,(function*(){const t=bn.current;if(!t||Ht)return;const n=zt.findIndex((t=>t.id===e.id));if(-1===n)return;Wt(!0),on(e.id),jt(""),To(t);let o=!1;try{if(!(yield _o(t)))throw new Error((null==qe?void 0:qe["failed-to-interrupt-current-response"])||"Failed to interrupt the current response.");if(!(yield Uo(t)))throw new Error((null==qe?void 0:qe["current-response-still-stopping"])||"The current response is still stopping. Please send your message again in a moment.");yt("idle"),Qt((t=>t.filter((t=>t.id!==e.id)))),o=!0,Wt(!1),on(null),yield Po(e.message,!1,!0,e.id,!0)}catch(t){yt("idle"),o&&Qt((t=>{if(t.some((t=>t.id===e.id)))return t;const o=[...t];return o.splice(n,0,e),o})),jt(H(t))}finally{Wt(!1),on(null)}}))})(e)},"aria-label":`${(null==qe?void 0:qe["steer-with"])||"Steer with"}: ${e.message}`},{children:[n("span",Object.assign({"aria-hidden":"true"},{children:"↳ "})),(null==qe?void 0:qe.steer)||"Steer"]})),n("button",Object.assign({type:"button",className:"flex h-7 w-7 shrink-0 items-center justify-center rounded-md opacity-50 transition-opacity hover:opacity-100 disabled:cursor-default disabled:opacity-30",disabled:Ht,onClick:()=>{return t=e.id,void Qt((e=>re(e,t)));var t},"aria-label":`${(null==qe?void 0:qe["remove-queued-message"])||"Remove queued message"}: ${e.message}`},{children:n(R,{className:"h-4 w-4","aria-hidden":"true"})})),o(F,Object.assign({id:`queued-message-menu-${e.id}`,className:"shrink-0"},{children:[n(G,Object.assign({className:"flex h-7 w-7 items-center justify-center rounded-md opacity-50 transition-opacity hover:opacity-100",isDisabled:Ht,role:"button",tabIndex:Ht?-1:0,"aria-haspopup":"menu","aria-label":(null==qe?void 0:qe["more-options"])||"More options",onKeyDown:e=>{"Enter"!==e.key&&" "!==e.key||(e.preventDefault(),e.currentTarget.click())}},{children:o("svg",Object.assign({viewBox:"0 0 24 24",className:"h-4 w-4",fill:"currentColor","aria-hidden":"true"},{children:[n("circle",{cx:"5",cy:"12",r:"1.6"}),n("circle",{cx:"12",cy:"12",r:"1.6"}),n("circle",{cx:"19",cy:"12",r:"1.6"})]}))})),n(V,Object.assign({role:"menu",align:Ye?"bottom-start":"bottom-end",positionStrategy:Ze?"absolute":"fixed",width:"auto",className:"p-1 text-sm shadow-xl",style:{backgroundColor:null!==(r=Gn.backgroundColor)&&void 0!==r?r:We.primary,color:We.text,borderRadius:"12px"},border:`1px solid ${We.text}20`},{children:o("button",Object.assign({type:"button",role:"menuitem",className:"flex min-w-36 items-center gap-2 rounded-lg px-3 py-2 text-left transition-colors hover:bg-black/5 dark:hover:bg-white/10",onClick:()=>(e=>{Qt((t=>re(t,e.id))),Xt(e.message),requestAnimationFrame((()=>{const t=jn.current;t&&(t.focus(),t.setSelectionRange(e.message.length,e.message.length))}))})(e)},{children:[n($,{className:"h-4 w-4 shrink-0"}),(null==qe?void 0:qe["edit-message"])||"Edit message"]}))}))]}))]})]}),e.id)}))})),o("div",Object.assign({ref:wn,className:J("relative z-10 flex flex-col w-full justify-end gap-y-3 py-[3px]","block"===He.formFieldStyle&&"shadow"),style:Object.assign(Object.assign({},Gn),{maxHeight:`${Sn}px`,overflowY:"auto"})},{children:[wo&&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:Gn.backgroundColor?`${Gn.backgroundColor}E6`:void 0,borderColor:We.text+"20",color:We.text,borderTopRightRadius:He.cornerRadius+"px",borderTopLeftRadius:He.cornerRadius+"px"}},{children:[n("div",Object.assign({className:"flex items-center gap-2 text-sm font-medium"},{children:o("span",{children:[bo.toLocaleString()," ",ao?(null==qe?void 0:qe.credits)||"Credits":(null==qe?void 0:qe.uses)||"Uses"," ",(null==qe?void 0:qe.remaining)||"remaining"]})})),o("div",Object.assign({className:"flex items-center gap-3"},{children:[Oo&&n("button",Object.assign({className:"rounded-md px-3 py-1.5 text-xs font-semibold transition-opacity hover:opacity-90",style:{backgroundColor:We.accent,color:We.accentText},onClick:e=>{if(e.preventDefault(),e.stopPropagation(),No)return void window.open(No,"_blank","noopener,noreferrer");if(lt)return void lt();const t=z({baseUrl:an,accessGroupId:null==tt?void 0:tt.accessGroupId});t&&Q({deploymentId:Fe,pricingUrl:t,studioId:null==Ve?void 0:Ve.studioid,studioSessionToken:pt})}},{children:So})),n("button",Object.assign({className:"flex h-6 w-6 items-center justify-center rounded-full opacity-60 transition-opacity hover:opacity-100",onClick:()=>pn(!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"})}))}))]}))]})),!ht&&wt.length>0&&n(B,{className:"p-4 pb-0",isDisabled:ht}),o("div",Object.assign({className:"relative flex w-full flex-col"},{children:[Qn&&o("div",Object.assign({className:J(ut?"top-6":"top-1/2","pointer-events-none absolute z-10 flex -translate-y-1/2 select-none items-center gap-x-2",Ye?"right-4":"left-4")},{children:[n("span",{className:"h-2 w-2 animate-pulse rounded-full bg-c-secondary",style:{backgroundColor:null!==(De=We.accent)&&void 0!==De?De:"#ff0000"}}),n("span",Object.assign({className:"text-sm text-c-secondary font-semilight",style:{color:We.text+"90"}},{children:(null==qe?void 0:qe.listening)||"Listening..."}))]})),n(X,Object.assign({ref:jn,className:J(Fn.i1,"py-3.5 max-h-60 px-4 w-full border-transparent bg-transparent",!Bt.trim()&&!Bt.includes("\n")&&"overflow-hidden text-ellipsis whitespace-nowrap placeholder:whitespace-normal placeholder:overflow-visible",Ye?"text-right":"text-left",!ut&&oo&&"mb-12"),value:Bt,placeholder:Qn?"":no,onChange:e=>{Xt(e)},onKeyDown:e=>{ze||_t||"Enter"===e.key&&(e.shiftKey||(e.preventDefault(),kt||Ht||(ht?Ao():Po())))},onPaste:e=>t(void 0,void 0,void 0,(function*(){const t=Array.from(e.clipboardData.files||[]);if(t.length>0){if(!Jn)return;e.preventDefault(),nt(!1),yield Nt(t)}}))},ue&&{onFocus:ue},fe&&{onBlur:fe},{dir:Ye?"rtl":"ltr"})),o("div",Object.assign({ref:In,className:ut?"relative flex w-full items-center gap-2 px-3 pb-2 [&>button]:shrink-0 [&>button]:mr-0":J("flex items-center gap-2 absolute z-2 transition-all duration-200 ease-in-out",oo?"bottom-3 right-2":"right-0 top-1/2 -translate-y-1/2"),style:Object.assign(Object.assign({},!oo&&Gn.backgroundColor&&{backgroundColor:Gn.backgroundColor}),{borderTopRightRadius:He.cornerRadius+"px",borderBottomRightRadius:He.cornerRadius+"px"})},{children:[!ht&&!En&&Jn&&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:Rn?We.accent+"10":void 0,color:Rn?We.accent:We.accent+"80"},disabled:kt||ht,"aria-label":null!==(Le=null==qe?void 0:qe["attach-files"])&&void 0!==Le?Le:"Attach files",onClick:()=>{var e;return null===(e=fn.current)||void 0===e?void 0:e.click()}},$n,{children:[n("input",{id:"file-upload",ref:fn,type:"file",accept:[...E,..._,...T].join(", "),multiple:!0,hidden:!0,className:"hidden",onChange:e=>t(void 0,void 0,void 0,(function*(){nt(!1),yield Nt(Array.from(e.target.files||[])),e.target.value=""}))}),n(A,{className:"h-6 w-6 shrink-0"})]})),n(a,{compact:!0}),ht&&!qt?o(s,{children:[n("button",Object.assign({"aria-label":(null==qe?void 0:qe["stop-response"])||"Stop response",className:"flex h-8 w-8 items-center justify-center rounded-full outline-none transition-colors duration-200 ease-in-out",onClick:()=>{const e=bn.current;e&&(To(e),_o(e)),yt("idle")},style:{backgroundColor:We.accent+"10",color:We.accent}},{children:n(M,{className:"h-4 w-4 shrink-0"})})),n("button",Object.assign({"aria-label":(null==qe?void 0:qe["queue-message"])||"Queue message",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",disabled:Ht||kt||!Bt.trim(),onClick:Ao,style:{backgroundColor:Bt.trim()?We.accent:We.accent+"10",color:Bt.trim()?We.accentText:We.accent+"80"}},{children:n(P,{className:J("h-6 w-6 shrink-0",Ye&&"scale-x-[-1] transform")})}))]}):En||_n?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:()=>{An()},disabled:_n,style:{backgroundColor:We.accent,color:We.accentText}},{children:n(M,{className:"h-4 w-4 shrink-0"})})):o(s,{children:[zn&&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:En?We.accent:Xn?We.accent+"10":void 0,color:En?We.accentText:Xn?We.accent:We.accent+"80"},disabled:kt||ht||_n,onClick:()=>{En?An():(vn.current=Bt,Un(Je||"en-US"))}},Kn,{children:n(D,{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:Dn||Eo?We.accent:We.accent+"10",color:Dn||Eo?We.accentText:We.accent+"80"},disabled:!Eo,onClick:()=>Po()},Ln,{children:n(P,{className:J("h-6 w-6 shrink-0",Ye&&"scale-x-[-1] transform")})}))]})]}))]}))]})),Ot&&n(K,{error:Ot,className:"mt-3"})]}))}))}));fe.displayName="Input";export{fe as default};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{__awaiter as e}from"../../_virtual/_tslib.js";import{generateId as s}from"../../common/utils.js";const o=()=>({document:({contextId:s,pickaxeId:o,file:i,workspaceId:n,sessionId:t,studioUserId:r,studioSessionToken:
|
|
1
|
+
import{__awaiter as e}from"../../_virtual/_tslib.js";import{generateId as s}from"../../common/utils.js";const o=()=>({document:({contextId:s,pickaxeId:o,file:i,workspaceId:n,sessionId:t,studioUserId:r,studioSessionToken:c,isKnowledge:d,isUserDocument:a,isBlocking:l})=>e(void 0,void 0,void 0,(function*(){var p,u;if(!process.env.NEXT_PUBLIC_DOCUMENT_API2_URL)throw new Error("NEXT_PUBLIC_DOCUMENT_API2_URL is not defined");const _=i.name.split(".").pop(),g="md"===_?"md":i.type,m={sessionid:s,formid:o,mimetype:g,extension:_,responseid:t,workspaceid:n},I=new URLSearchParams(Object.entries(m).filter((e=>void 0!==e[1]&&null!==e[1]&&""!==e[1]))),U=`${process.env.NEXT_PUBLIC_DOCUMENT_API2_URL}/get_document_upload_url?${I.toString()}`,O=yield fetch(U),f=yield O.json();if(!f.success)throw new Error(null!==(p=f.error)&&void 0!==p?p:"Failed to get presigned URL, try again or contact support.");const b=new FormData;Object.entries(Object.assign(Object.assign({},f.fields),{file:i})).forEach((([e,s])=>{b.append(e,s)}));const w=()=>e(void 0,void 0,void 0,(function*(){const e=new URLSearchParams(Object.assign({sessionid:s,documentid:f.documentId},t&&{responseid:t}));try{yield fetch(`${process.env.NEXT_PUBLIC_DOCUMENT_API2_URL}/decrement_document_count?${e.toString()}`)}catch(e){}}));let j;try{j=yield fetch(f.url,{method:"POST",body:b})}catch(e){throw yield w(),e}if(!j.ok)throw yield w(),new Error(j.statusText);const T=`${f.url}${f.fields.key}`;"development"===process.env.NODE_ENV&&console.log("[S3URL]",T);const y=yield fetch(`${process.env.NEXT_PUBLIC_DOCUMENT_API2_URL}/process_document`,{method:"POST",body:JSON.stringify(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({formId:o,documentId:f.documentId,fileName:i.name,fileSize:i.size},n&&{workspaceId:n}),t&&{responseId:t}),r&&{studioUserId:r}),c&&{studioSessionToken:c}),d&&{isKnowledge:d}),a&&{isUserDocument:a}),l&&{isBlocking:l})),headers:{"Content-Type":"application/json"}}),E=yield y.json();if(!E.success)throw new Error(null!==(u=E.error)&&void 0!==u?u:"Failed processing document, try again or contact support.");return Object.assign(Object.assign({},E),{folder:f.folder})})),website:({pickaxeId:o,website:i,workspaceId:n,sessionId:t,studioUserId:r,studioSessionToken:c,isKnowledge:d,isUserDocument:a,isBlocking:l})=>e(void 0,void 0,void 0,(function*(){var e;if(!process.env.NEXT_PUBLIC_DOCUMENT_API2_URL)throw new Error("NEXT_PUBLIC_DOCUMENT_API2_URL is not defined");const p=s(20),u=yield fetch(`${process.env.NEXT_PUBLIC_DOCUMENT_API2_URL}/process_document`,{method:"POST",body:JSON.stringify(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({formId:o,documentId:p,website:i},n&&{workspaceId:n}),t&&{responseId:t}),r&&{studioUserId:r}),c&&{studioSessionToken:c}),d&&{isKnowledge:d}),a&&{isUserDocument:a}),l&&{isBlocking:l})),headers:{"Content-Type":"application/json"}}),_=yield u.json();if(!_.success)throw new Error(null!==(e=_.error)&&void 0!==e?e:"Failed processing website, try again or contact support.");return _}))});export{o as useSubmitDocument};
|