@pickaxeproject/react 6.8.6 → 6.8.8
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cjs/common/utils.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e=require("tldts");const t="PXE-uid",r=(e,t=!1)=>{let r="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890";t&&(r=r.replace(/[0-9]/g,""));let o="";for(let t=0;t<e;t++)o+=r.charAt(Math.floor(Math.random()*r.length));return o},o=e=>{try{const t=document.cookie.split("; ");for(const r of t){const[t,o]=r.split("=");if(t===e)return o}return null}catch(e){return console.error("[pxe] failed to get cookie",e),null}};exports.COOKIE_USER_ID=t,exports.buildUpgradeUrl=({baseUrl:e,redirectUrl:t,accessGroupId:r,currentUrl:o})=>{if(!e)return null;const n=null!=o?o:"undefined"!=typeof window?window.location.href:null;if(!n)return null;try{const o=new URL(e,n);
|
|
1
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e=require("tldts");const t="PXE-uid",r=(e,t=!1)=>{let r="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890";t&&(r=r.replace(/[0-9]/g,""));let o="";for(let t=0;t<e;t++)o+=r.charAt(Math.floor(Math.random()*r.length));return o},o=e=>{try{const t=document.cookie.split("; ");for(const r of t){const[t,o]=r.split("=");if(t===e)return o}return null}catch(e){return console.error("[pxe] failed to get cookie",e),null}};exports.COOKIE_USER_ID=t,exports.buildUpgradeUrl=({baseUrl:e,redirectUrl:t,accessGroupId:r,currentUrl:o})=>{if(!e)return null;const n=null!=o?o:"undefined"!=typeof window?window.location.href:null;if(!n)return null;try{const o=new URL(e,n);if(r){const e=((e,t)=>{const r=e.pathname.split("/"),o=r.findIndex((e=>"ag-pricing"===e));return-1!==o&&!r[o+1]&&(r.splice(o+1,0,encodeURIComponent(t)),e.pathname=r.join("/"),!0)})(o,r);e||o.searchParams.set("agid",r)}return t&&o.searchParams.set("redirectUrl",t),o.toString()}catch(e){return console.error("[pxe] failed to build upgrade url",e),null}},exports.deleteAuthToken=e=>{try{if("undefined"==typeof window)return;localStorage.removeItem(e)}catch(e){console.error("[pxe] failed to delete auth token",e)}},exports.deleteCookie=e=>{document.cookie=e+"=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;"},exports.extractUrlsFromText=e=>{const t=e.match(/(https?:\/\/[^\s]+)/g)||[];return Array.from(new Set(t))},exports.formatBytes=(e,t=2)=>{if(!+e)return"0 Bytes";const r=t<0?0:t,o=Math.floor(Math.log(e)/Math.log(1024));return`${parseFloat((e/Math.pow(1024,o)).toFixed(r))} ${["Bytes","KB","MB","PB","EB"][o]}`},exports.generateId=(e,t="",r="")=>{let o="";for(let t=0;t<e;t++){o+="ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"[Math.floor(36*Math.random())]}return t+o+r},exports.getAuthToken=e=>{try{if("undefined"==typeof window)return null;let t=null;return t=new URLSearchParams(window.location.search).get("pxtoken"),t||(t=localStorage.getItem(`PXE-token-${e}`)),t||(t=o(`PXE-token-${e}`)),t||(t=o(`__Secure-PS-${e}.session-token`)),t?decodeURIComponent(t):null}catch(e){return null}},exports.getCookie=o,exports.initializeEmbedUserId=()=>{try{const n=o(t);if(!n){const o=r(28),n=new Date;n.setFullYear(n.getFullYear()+1);let l=window.location.hostname;const s=e.parse(l).domain;if(s)l=`.${s}`;else{const e=l.split(":")[0],t=e.split(".");l=e,t.length>=2&&(l=`.${t.slice(-2).join(".")}`)}return document.cookie=`${t}=${o};Path=/; Domain=${l}; Expires=${n.toUTCString()}`,o}return n}catch(e){return console.error("[pxe-embed] failed to initialized embed user id",e),r(28)}},exports.isInIframe=()=>{if("undefined"==typeof window)return!1;try{return window.self!==window.top}catch(e){return!0}},exports.mergeRefs=function(...e){return t=>{for(const r of e)r&&("function"==typeof r?r(t):r.current=t)}},exports.randomStr=r,exports.safeJSONParse=e=>{try{return JSON.parse(e)}catch(e){return null}},exports.setAuthToken=(e,t)=>{try{if("undefined"==typeof window)return;localStorage.setItem(e,t)}catch(e){console.error("[pxe] failed to set auth token",e)}};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e=require("../../../_virtual/_tslib.js"),t=require("react/jsx-runtime"),s=require("react"),n=require("../../../hooks/pickaxe/usePickaxeContext.js"),i=require("../../../hooks/pickaxe/useResponseContext.js"),r=require("../../../hooks/studio/useStyleInput.js"),o=require("../../../hooks/studio/useStyleFontSize.js"),a=require("../../../hooks/pickaxe/useConversation.js"),l=require("../../../hooks/pickaxe/useDimensionContext.js"),c=require("../Addons/Auth/hooks/useAuthContext.js"),d=require("../Addons/Document/hooks/useDocument.js"),u=require("../Addons/Scroll/hooks/useScroll.js"),p=require("../Addons/Artifact/hooks/useArtifactContext.js"),m=require("../../../hooks/core/useHover.js"),f=require("../../../hooks/core/useMediaQuery.js"),g=require("../../../common/documents.js"),h=require("eventsource-parser"),v=require("../../Icons/attach-vertical.svg.js"),b=require("../../Icons/arrow-right.svg.js"),y=require("../../Icons/microphone.svg.js"),I=require("../../Icons/stop.svg.js"),x=require("../Addons/Document/List.js"),j=require("../../Core/Textarea.js"),S=require("../../Core/ErrorAlert.js"),w=require("../../../common/error.js"),O=require("../../../common/api/pickaxe.js"),N=require("../../../common/validation.js"),_=require("../../../common/cn.js"),k=require("../../../common/utils.js"),E=require("../../../common/pickaxeConfig.js"),C=require("../../../common/deploymentWebhooks.js"),U=require("../../../hooks/studio/useStudio.js"),T=require("../../../hooks/pickaxe/useSpeech.js"),A=require("../common/PickaxeCommon.js");const D=e=>"string"==typeof e&&e.trim().length>0,P=e=>e.map((e=>Object.assign({},e))),L=e=>e instanceof Error&&("AbortError"===e.name||"BodyStreamBuffer was aborted"===e.message),R=(e,t)=>{if(e&&"object"==typeof e)return e[t]},M=(e,t)=>{const s=R(e,t);return D(s)?s:null},q=e=>{const t=Number(e);return Number.isFinite(t)?t:void 0},F=({studioUser:e,deploymentId:t,portalId:s})=>{var n,i;const r=Array.isArray(R(e,"uses"))?R(e,"uses"):[],o=(({deploymentId:e,portalId:t})=>D(e)?{type:"deployment",id:e}:D(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}},V=s.forwardRef((({resubmitPrompt:R,onFocus:V,onBlur:$,onInputHeightChange:B,initSmitheryAuthData:X},H)=>{var K,W,Y,z,G,J,Q,Z,ee,te,se,ne;const{origin:ie,pickaxeId:re,sessionId:oe,sender:ae,senderType:le,portalId:ce,deploymentId:de,deploymentType:ue,pickaxe:pe,styles:me,colors:fe,translations:ge,locale:he,forceMobile:ve,isNewChat:be,isRtl:ye,isShowFeedbackMessage:Ie,accessGroup:xe,setIsNewChat:je,setIsShowIceBreaker:Se,setValidationStatus:we,setValidationUpgradeGroups:Oe,setValidationUpgradeUrl:Ne,setAccessGroup:_e,onGenerateComplete:ke}=n.usePickaxeContext(),{token:Ee,isLoggedOut:Ce,isSent:Ue,isPricingAuth:Te}=c.useAuthContext(),{messages:Ae,isGenerating:De,setMessages:Pe,setStatus:Le,setLimitData:Re,setError:Me}=i.useResponseContext(),{documents:qe,isUploading:Fe,documentError:Ve,onFileUpload:$e,setDocuments:Be,setDocumentError:Xe}=d.useDocument(),{studio:He}=U.useStudio(),{scrollStartSession:Ke,scrollEndSession:We,scrollToBottom:Ye}=u.useScroll({auto:!0}),{artifacts:ze,currentPopupType:Ge,setArtifacts:Je,setCurrentArtifact:Qe}=p.useArtifactContext(),{height:Ze}=l.useDimensionContext(),et=a.useConversation(),[tt,st]=s.useState(""),[nt,it]=s.useState(!1),[rt,ot]=s.useState(!1),[at,lt]=s.useState(null),[ct,dt]=s.useState(null),[ut,pt]=s.useState(!1),[mt,ft]=s.useState(!1),[gt,ht]=s.useState(0),vt=s.useRef(null),bt=s.useRef(""),yt=s.useRef(null),It=s.useRef(null),xt=s.useRef(null),jt=s.useRef([]),St=s.useRef(null),wt=s.useRef(null),Ot=s.useRef(null),Nt=s.useRef(null),_t=s.useRef(new Set),kt=s.useRef(null),Et=Math.max(.4*Ze,100),{speechTranscript:Ct,isSpeechListening:Ut,isSpeechProcessing:Tt,isSpeechSupported:At,onStartListening:Dt,onStopListening:Pt}=T.useSpeech(),[Lt]=f.useMediaQuery("(max-width: 480px)"),Rt=m.useHover(),{isHover:Mt}=Rt,qt=e.__rest(Rt,["isHover"]),Ft=m.useHover(),{isHover:Vt}=Ft,$t=e.__rest(Ft,["isHover"]),Bt=m.useHover(),{isHover:Xt}=Bt,Ht=e.__rest(Bt,["isHover"]),Kt=o.useStyleFontSize(),Wt=r.useStyleInput(),Yt="undefined"!=typeof window?window.location.hostname:"",zt="undefined"!=typeof window?window.location.href:"",Gt="undefined"!=typeof window&&window.self!==window.top,Jt=Yt.includes("pickaxe.co")&&!zt.includes("https://studio.pickaxe.co/_embed")&&!Gt,Qt=null!==(W=null===(K=null==pe?void 0:pe.documentuploadtype)||void 0===K?void 0:K.startsWith("enduserupload"))&&void 0!==W&&W,Zt=At&&(null==pe?void 0:pe.enablevoicetotext),es=D(de),ts="chat-input"===ue&&be&&!Ue,ss="chat-input"===ue&&Te&&Ce&&Ue,ns=s.useCallback((e=>{const t=N.getValidationFailure(e);return!!t&&(Me(""),Re(null),we(t.status),_e(t.accessGroup),Oe(t.upgradeGroups),Ne(t.upgradeUrl),!0)}),[Me,Re,we,Oe,Ne,_e]),is=null!==(Y=null==pe?void 0:pe.placeholdertext)&&void 0!==Y?Y:ye?"بماذا تريد أن تتحدث؟":(null==ge?void 0:ge["what-do-you-want-to-talk-about"])||"What do you want to talk about?",rs=nt||rt,os=s.useCallback((()=>e.__awaiter(void 0,void 0,void 0,(function*(){pt(!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==pe?void 0:pe.studioid},Ee?{studioSessionToken:Ee}:ae?{sender:ae}:{sender:k.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}})),Jt&&{credentials:"include"})),t=yield e.json();(null==t?void 0:t.studioUser)&&(lt(t.studioUser),dt(t.url))}catch(e){console.error("Failed to fetch studio user:",e)}finally{pt(!0)}}))),[Jt,null==pe?void 0:pe.studioid,ae,Ee]);s.useEffect((()=>{os()}),[os]);const as=Number(null!==(z=null==xe?void 0:xe.limit)&&void 0!==z?z:0),ls="string"==typeof(null==xe?void 0:xe.limitInterval)?xe.limitInterval:null,cs=!!(null==He?void 0:He.data.usage)&&He.data.usage.isCredits,ds=s.useMemo((()=>F({studioUser:at,deploymentId:de,portalId:ce})),[de,ce,at]);s.useEffect((()=>{es&&be&&oe&&_t.current.add(oe)}),[be,oe,es]);const us=s.useCallback((()=>{var e,t,s;return{studioId:null==pe?void 0:pe.studioid,userEmail:M(at,"email"),userId:null!==(e=M(at,"userId"))&&void 0!==e?e:M(at,"userid"),sessionId:oe,deploymentId:de,deploymentType:ue,portalId:ce,accessGroupId:null!==(t=null==xe?void 0:xe.accessGroupId)&&void 0!==t?t:null,pickaxeId:re,sender:ae,senderType:le,origin:ie,metadata:null!==(s=E.getPickaxeConfigMetadata(de))&&void 0!==s?s:null}}),[null==xe?void 0:xe.accessGroupId,de,ue,ie,null==pe?void 0:pe.studioid,re,ce,ae,le,oe,at]),ps=s.useCallback((()=>!!(es&&ut&&oe)&&(!!_t.current.has(oe)&&(C.fireDeploymentSessionInitializedWebhook(us()),_t.current.delete(oe),!0))),[us,ut,oe,es]);s.useEffect((()=>{if(!ut||!oe)return;ps();const e=kt.current;(null==e?void 0:e.sessionId)===oe&&(C.fireDeploymentFirstMessageSubmittedWebhook(Object.assign(Object.assign(Object.assign({},e),us()),{message:e.message,documentIds:e.documentIds,uploadedModelImages:e.uploadedModelImages,hasUploadedDocuments:e.hasUploadedDocuments,isHidden:e.isHidden})),kt.current=null)}),[ps,us,ut,oe]);const ms={currentUses:q(null==at?void 0:at.currentUses),extraUses:q(null==at?void 0:at.extraUses)},fs=ds.scope?{currentUses:null!==(J=q(null===(G=ds.record)||void 0===G?void 0:G.currentUses))&&void 0!==J?J:0,extraUses:null!==(Z=q(null===(Q=ds.record)||void 0===Q?void 0:Q.extraUses))&&void 0!==Z?Z:0}:{currentUses:0,extraUses:0},gs=M(at,"type"),hs="guest"===gs||!gs&&Ce?fs:ms;s.useEffect((()=>{let t=!0;return e.__awaiter(void 0,void 0,void 0,(function*(){var e;if(cs&&(null===(e=null==He?void 0:He.data)||void 0===e?void 0:e.workspaceId))try{const e=yield O.pickaxeApi2.get(`/cost_per_run?workspaceId=${He.data.workspaceId}`,{withCredentials:!1});t&&ht(1e4*(Number(e.data.costPerRun)||0))}catch(e){console.error("Failed to fetch average cost per run:",e),t&&ht(0)}else t&&ht(0)})),()=>{t=!1}}),[cs,null===(ee=null==He?void 0:He.data)||void 0===ee?void 0:ee.workspaceId]);const vs=(({currentUses:e,extraUses:t,limit:s,limitInterval:n})=>{const i=Number(null!=e?e:0),r=Number(null!=t?t:0);return s===A.STUDIO_INFINITY_VALUE||r===A.STUDIO_INFINITY_VALUE?A.STUDIO_INFINITY_VALUE:"one_time"===n?Math.max(0,r-i):(console.log("Calculating remaining balance with limit:",s,"currentUses:",i,"extraUses:",r),Math.max(0,s-i)+r)})({currentUses:hs.currentUses,extraUses:hs.extraUses,limit:as,limitInterval:ls}),bs=vs===A.STUDIO_INFINITY_VALUE?A.STUDIO_INFINITY_VALUE:Math.max(0,Math.ceil(vs)),ys=(({extraUses:e,limit:t,limitInterval:s})=>{const n=Number(null!=e?e:0);return t===A.STUDIO_INFINITY_VALUE||n===A.STUDIO_INFINITY_VALUE?A.STUDIO_INFINITY_VALUE:"one_time"===s?Math.max(0,n):Math.max(0,t)+Math.max(0,n)})({extraUses:hs.extraUses,limit:as,limitInterval:ls}),Is=ys===A.STUDIO_INFINITY_VALUE?A.STUDIO_INFINITY_VALUE:Math.ceil(.05*ys),xs=cs?Math.ceil(5*gt):5,js=Is===A.STUDIO_INFINITY_VALUE?A.STUDIO_INFINITY_VALUE:Math.max(Is,xs),Ss=s.useMemo((()=>!!at&&(!mt&&(bs!==A.STUDIO_INFINITY_VALUE&&bs<=js))),[mt,js,bs,at]),ws=(null===(te=null==xe?void 0:xe.upgrade)||void 0===te?void 0:te.isLinkToCustomURL)&&"string"==typeof xe.upgrade.limitLink&&xe.upgrade.limitLink.trim().length>0?xe.upgrade.limitLink.trim():null,Os=ws&&"string"==typeof(null===(se=null==xe?void 0:xe.upgrade)||void 0===se?void 0:se.limitCTA)&&xe.upgrade.limitCTA.trim().length>0?xe.upgrade.limitCTA:(null==ge?void 0:ge["pricing.upgrade"])||(null==ge?void 0:ge.upgrade)||"Upgrade",Ns=s.useMemo((()=>{var e,t,s;return!!be&&(!!pe&&(!et.isLoading&&(!((null!==(t=null===(e=et.data)||void 0===e?void 0:e.messages.length)&&void 0!==t?t:0)>1)&&(!!(null===(s=pe.icebreakers)||void 0===s?void 0:s.length)&&(!Ie&&!ts)))))}),[pe,be,Ie,ts,et.data,et.isLoading]),_s=s.useMemo((()=>{if(De||Fe)return!1;const e=Qt&&qe.length>0&&qe.every((e=>"finished"===e.status));return!(!tt.trim()&&!e)&&qe.every((e=>"finished"===e.status||e.isInsertedAsRaw))}),[Qt,De,Fe,tt,qe]);s.useImperativeHandle(H,(()=>({onSubmit:ks}))),s.useEffect((()=>{Se(Ns)}),[Ns]),s.useEffect((()=>{var e;if(R){const t=Array.from(Ae),s=null===(e=t[t.length-2].parts.find((e=>"text"===e.type)))||void 0===e?void 0:e.content;ks(s,!0)}}),[R]),s.useEffect((()=>{if(!Ot.current||!B)return;const e=new ResizeObserver((e=>{for(const t of e)B(t.contentRect.height)}));return e.observe(Ot.current),()=>{e.disconnect()}}),[B]),s.useEffect((()=>{if(!Ut)return;const e=bt.current?`${bt.current} `:"";st(`${e}${Ct}`)}),[Ct,Ut]),s.useEffect((()=>{if(!St.current)return;(()=>{if(!St.current)return;let e=St.current.scrollHeight>52;tt.includes("\n")||qe.length?e=!0:tt.trim()||(e=!1),it(e)})()}),[tt,qe]),s.useEffect((()=>{const e=St.current,t=wt.current;if(!e||!t||nt||tt.includes("\n"))return void ot(!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=tt||is,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;ot(r>l)}),[tt,nt,is]);const ks=(t,s=!1)=>e.__awaiter(void 0,void 0,void 0,(function*(){var e,n,i,r;let o=null;try{if(De||Fe)return;const a=qe.filter((e=>"finished"===e.status&&!e.isInsertedAsRaw)),l=a.map((e=>e.documentId)).filter(Boolean),c=a.filter((e=>"image"===e.type)).map((e=>{const t=e.name.split(".").pop()||"";return{documentId:e.documentId,extension:t}})),d=null!=t?t:tt,u=null!==(n=null===(e=null==pe?void 0:pe.documentuploadtype)||void 0===e?void 0:e.startsWith("enduserupload"))&&void 0!==n&&n&&l.length>0;if(!d&&!u)return;Me(""),Xe(""),Re(null),st(""),je(!1),Le("fetching"),Ke(),Ye();const p=[...s?Array.from(Ae.slice(0,Ae.length-1)):Array.from(Ae),...s?[]:[{id:Ae.length+1,role:"user",parts:[{type:"text",content:d,isVisible:!0}],documentIds:u?l:[]}],{id:Ae.length+(s?0:2),role:"assistant",parts:[],documentIds:[]}];Pe(p),Ye(),u&&Be([]);const m=E.getPickaxeConfigMetadata(de),f="undefined"!=typeof crypto&&"randomUUID"in crypto?crypto.randomUUID():`submission-${Date.now()}-${Math.random().toString(36).slice(2)}`;o=f,It.current=f,xt.current=null,jt.current=[];const g=yield fetch(`${process.env.NEXT_PUBLIC_PICKAXE_API2_URL}/response/submit`,Object.assign({method:"POST",body:JSON.stringify(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({origin:ie,pickaxeId:re,sessionId:oe,submissionId:f,senderType:le,value:d},u&&{documentIds:l}),ae&&{sender:ae}),Ee&&{studioSessionToken:Ee}),!Ee&&!ae&&{sender:k.initializeEmbedUserId()}),ce&&{portalId:ce}),de&&{deploymentId:de}),m&&{metadata:m}),u&&c.length>0?{uploadedModelImages:c}:{})),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()})},Jt&&{credentials:"include"})),v=yield g.json();if(!v.success){if(v.limitData){const e=new Error(v.error||v.message||(null==ge?void 0:ge["failed-to-start-generation"])||"Failed to start generation");throw e.limitData=v.limitData,e}if(ns(v))return;throw new Error(v.error||v.message||(null==ge?void 0:ge["failed-to-start-generation"])||"Failed to start generation")}const b=null!==(i=v.submissionId)&&void 0!==i?i:f;o=b,It.current=b;const y=()=>xt.current===b;if(y())return;es&&be&&oe&&_t.current.add(oe);const I=Object.assign(Object.assign({},us()),{message:d,documentIds:u?l:[],uploadedModelImages:u?c:[],hasUploadedDocuments:u,isHidden:s,metadata:null!=m?m:null});ut?(ps(),C.fireDeploymentFirstMessageSubmittedWebhook(I)):kt.current=I,Le("streaming"),Nt.current=new AbortController;const x=p.length-1,j=[];let S=[...null!=ze?ze:[]],w=0,O=!1,N="";for(;!O;)try{const e=yield fetch(`${process.env.NEXT_PUBLIC_PICKAXE_API2_URL}/response/stream/${b}?index=${w}`,{signal:null===(r=Nt.current)||void 0===r?void 0:r.signal,headers:{"Cache-Control":"no-cache",Connection:"keep-alive"}});if(!e.body)throw new Error("No response body");const t=e.body.getReader();yt.current=t;const s=new TextDecoder,n=h.createParser({onEvent:e=>{var t,s;if(y())O=!0;else if(e.event&&"ping"!==e.event&&w++,"stop"!==e.event){if("error"===e.event){const t=JSON.parse(e.data);if(t.limitData)return Re(t.limitData),Me(""),void(O=!0);const s=t.error||t.message||(null==ge?void 0:ge["something-went-wrong"])||"Something went wrong.";return ns(t)||Me(s),void(O=!0)}if("delta"===e.event){const n=JSON.parse(e.data);if("data-error"===n.type&&X){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 O=!0,X({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 O=!0,X({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 O=!0,X({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 O=!0,X({provider:"composio",toolkitSlug:t.toolkitSlug,serverId:t.serverId,name:t.name}),new Error("STOP_STREAM")}}else if("text-start"===n.type)N="",j.push({type:"text",content:"",isVisible:null===(t=n.isVisible)||void 0===t||t});else if("text-delta"===n.type)N+=n.delta,j[j.length-1].content=N;else if("text-end"===n.type)N="";else if("reasoning-start"===n.type)N="",j.push({type:"reasoning",content:"",isVisible:null===(s=n.isVisible)||void 0===s||s});else if("reasoning-delta"===n.type)N+=n.delta,j[j.length-1].content=N;else if("reasoning-end"===n.type)N="";else if(n.type.startsWith("data-")){const e=n;j.push({type:e.type,content:JSON.stringify(e.data),isVisible:!0})}jt.current=P(j),Pe([...p.slice(0,x),Object.assign(Object.assign({},p[p.length-1]),{id:Ae.length+1,role:"assistant",parts:j})])}else if("artifact_created"===e.event){const t=JSON.parse(e.data);S=S.filter((e=>!(e.id===t.id&&e.version===t.version))),S.push(Object.assign(Object.assign({},t),{content:"",status:"streaming"})),Je([...S]),Ge.startsWith("inline")||Qe({id:t.id,version:t.version})}else if("artifact_updated"===e.event){const t=JSON.parse(e.data);S=S.filter((e=>!(e.id===t.id&&e.version===t.version))),S.push(Object.assign(Object.assign({},t),{content:"",status:"updating"})),Je(S),Ge.startsWith("inline")||Qe({id:t.id,version:t.version})}else if("artifact_rewrite"===e.event){const t=JSON.parse(e.data);S=S.filter((e=>!(e.id===t.id&&e.version===t.version))),S.push(Object.assign(Object.assign({},t),{content:"",status:"streaming"})),Je(S),Ge.startsWith("inline")||Qe({id:t.id,version:t.version})}else if("artifact_content"===e.event){const t=JSON.parse(e.data),s=t.token.replace(/\u200B/g,"");S=S.map((e=>e.id===t.id&&e.version===t.version?Object.assign(Object.assign({},e),{content:e.content+s,status:"streaming"}):e)),Je(S)}else if("artifact_finished"===e.event){const t=JSON.parse(e.data);Je(S.map((e=>e.id===t.id?Object.assign(Object.assign({},e),{status:"finished"}):e)))}else if("error"===e.event){const t=JSON.parse(e.data);if(t.limitData)return Re(t.limitData),Me(""),void(O=!0);const s=t.error||t.message||(null==ge?void 0:ge["something-went-wrong-try-again"])||"Something went wrong, please try again.";if(ns(t))return void(O=!0);Me(s)}else"stop"===e.event&&(O=!0)}else O=!0}});for(;;){if(y()){O=!0,t.cancel().catch((()=>{}));break}const{value:e,done:i}=yield t.read();if(y()){O=!0,t.cancel().catch((()=>{}));break}if(i)break;n.feed(s.decode(e))}O||y()||(yield new Promise((e=>setTimeout(e,1e3))))}catch(e){if("STOP_STREAM"===e.message||L(e)||y())return void(O=!0);console.warn("Stream connection lost, retrying...",e),yield new Promise((e=>setTimeout(e,1e3)))}null==ke||ke(oe)}catch(e){if(L(e))return;if(e.limitData)Re(e.limitData),Me("");else{let t=w.default(e)||"";t&&!t.includes("Unexpected token 'A',")||(t=(null==ge?void 0:ge["high-traffic-try-again-later"])||"Oops! We're experiencing high traffic at the moment. Please try again later."),ns(t)||Me(t)}}finally{const e=!o||It.current===o;Ye(),e&&(Le("idle"),We(),yt.current=null),o&&e&&(It.current=null,jt.current=[]),yield os()}}));return ss?null:t.jsx("div",Object.assign({className:_.default("flex w-full flex-shrink-0 flex-col items-center",!ts&&"px-4 pb-8"),dir:ye?"rtl":"ltr"},{children:t.jsxs("div",Object.assign({className:"flex w-full max-w-[800px] flex-col"},{children:[t.jsxs("div",Object.assign({ref:Ot,className:_.default("relative flex flex-col w-full justify-end gap-y-3 py-[3px]","block"===me.formFieldStyle&&"shadow"),style:Object.assign(Object.assign({},Wt),{maxHeight:`${Et}px`,overflowY:"auto"})},{children:[Ss&&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:Wt.backgroundColor?`${Wt.backgroundColor}E6`:void 0,borderColor:fe.text+"20",color:fe.text,borderTopRightRadius:me.cornerRadius+"px",borderTopLeftRadius:me.cornerRadius+"px"}},{children:[t.jsx("div",Object.assign({className:"flex items-center gap-2 text-sm font-medium"},{children:t.jsxs("span",{children:[bs.toLocaleString()," ",cs?(null==ge?void 0:ge.credits)||"Credits":(null==ge?void 0:ge.uses)||"Uses"," ",(null==ge?void 0:ge.remaining)||"remaining"]})})),t.jsxs("div",Object.assign({className:"flex items-center gap-3"},{children:[t.jsx("button",Object.assign({className:"rounded-md px-3 py-1.5 text-xs font-semibold transition-opacity hover:opacity-90",style:{backgroundColor:fe.accent,color:fe.accentText},onClick:e=>{if(e.preventDefault(),e.stopPropagation(),ws)return void window.open(ws,"_blank","noopener,noreferrer");const t=k.buildUpgradeUrl({baseUrl:ct,accessGroupId:null==xe?void 0:xe.accessGroupId});t&&(k.isInIframe()?window.open(t):location.href=t)}},{children:Os})),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:()=>ft(!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"})}))}))]}))]})),!De&&qe.length>0&&t.jsx(x.default,{className:"p-4 pb-0",isDisabled:De}),t.jsxs("div",Object.assign({className:"relative flex w-full flex-col"},{children:[Ut&&t.jsxs("div",Object.assign({className:"absolute left-4 top-1/2 flex -translate-y-1/2 select-none items-center gap-x-2"},{children:[t.jsx("span",{className:"h-2 w-2 animate-pulse rounded-full bg-c-secondary",style:{backgroundColor:null!==(ne=fe.accent)&&void 0!==ne?ne:"#ff0000"}}),t.jsx("span",Object.assign({className:"text-sm text-c-secondary font-semilight",style:{color:fe.text+"90"}},{children:(null==ge?void 0:ge.listening)||"Listening..."}))]})),t.jsx(j.default,Object.assign({ref:St,className:_.default(Kt.i1,"py-3.5 max-h-60 px-4 w-full border-transparent bg-transparent",!tt.trim()&&!tt.includes("\n")&&"overflow-hidden text-ellipsis whitespace-nowrap placeholder:whitespace-normal placeholder:overflow-visible",ye?"text-right":"text-left",rs&&"mb-12",Ut&&"text-transparent"),value:tt,placeholder:is,onChange:e=>{st(e)},onKeyDown:e=>{ve||Lt||"Enter"===e.key&&(e.shiftKey||(e.preventDefault(),Fe||De||ks()))},onPaste:t=>e.__awaiter(void 0,void 0,void 0,(function*(){const e=Array.from(t.clipboardData.files||[]);if(e.length>0){if(!Qt)return;t.preventDefault(),je(!1),yield $e(e)}}))},V&&{onFocus:V},$&&{onBlur:$},{dir:ye?"rtl":"ltr"})),t.jsx("div",Object.assign({ref:wt,className:_.default("flex items-center gap-2 absolute right-0 z-2 transition-all duration-200 ease-in-out",rs?"bottom-0 mb-2.5":"top-1/2 -translate-y-1/2"),style:Object.assign(Object.assign({},!rs&&Wt.backgroundColor&&{backgroundColor:Wt.backgroundColor}),{borderTopRightRadius:me.cornerRadius+"px",borderBottomRightRadius:me.cornerRadius+"px"})},{children:De?t.jsx("button",Object.assign({className:"flex h-8 w-8 items-center mr-2 justify-center rounded-full outline-none transition-colors duration-200 ease-in-out",onClick:()=>{const t=It.current;t&&(xt.current=t,(t=>{e.__awaiter(void 0,void 0,void 0,(function*(){if(!(t=null!=t?t:It.current))return;const e=P(jt.current);try{yield fetch(`${process.env.NEXT_PUBLIC_PICKAXE_API2_URL}/response/cancel/${t}`,Object.assign({method:"POST",headers:Object.assign(Object.assign({"Content-Type":"application/json"},(!process.env.NODE_ENV||"development"===process.env.NODE_ENV)&&Object.assign({},process.env.NEXT_PUBLIC_PICKAXE_SESSION_TOKEN&&{"x-pickaxe-session-token":process.env.NEXT_PUBLIC_PICKAXE_SESSION_TOKEN})),{"x-request-sent-at":(new Date).toISOString()}),body:JSON.stringify({outputMessageParts:e})},Jt&&{credentials:"include"}))}catch(e){console.warn("Failed to cancel submission",e)}}))})(t)),Nt.current&&(Nt.current.abort(),Nt.current=null),yt.current&&(yt.current.cancel().catch((()=>{})),yt.current=null),Le("idle")},style:{backgroundColor:fe.accent,color:fe.accentText}},{children:t.jsx(I.default,{className:"h-4 w-4 shrink-0"})})):Ut?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:Pt,style:{backgroundColor:fe.accent,color:fe.accentText}},{children:t.jsx(I.default,{className:"h-4 w-4 shrink-0"})})):t.jsxs(t.Fragment,{children:[Qt&&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:Vt?fe.accent+"10":void 0,color:Vt?fe.accent:fe.accent+"80"},disabled:Fe||De,onClick:()=>{var e;return null===(e=vt.current)||void 0===e?void 0:e.click()}},$t,{children:[t.jsx("input",{id:"file-upload",ref:vt,type:"file",accept:[...g.allowedFileMimeTypes,...g.allowedImageMimeTypes,...g.additionalAllowedFileExtensions].join(", "),multiple:!0,hidden:!0,className:"hidden",onChange:t=>e.__awaiter(void 0,void 0,void 0,(function*(){je(!1),yield $e(Array.from(t.target.files||[])),t.target.value=""}))}),t.jsx(v.default,{className:"h-6 w-6 shrink-0"})]})),Zt&&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:Ut?fe.accent:Xt?fe.accent+"10":void 0,color:Ut?fe.accentText:Xt?fe.accent:fe.accent+"80"},disabled:Fe||De||Tt,onClick:()=>{Ut?Pt():(bt.current=tt,Dt(he||"en-US"))}},Ht,{children:t.jsx(y.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:Mt||_s?fe.accent:fe.accent+"10",color:Mt||_s?fe.accentText:fe.accent+"80"},disabled:!_s,onClick:()=>ks()},qt,{children:t.jsx(b.default,{className:_.default("h-6 w-6 shrink-0",ye&&"scale-x-[-1] transform")})}))]})}))]}))]})),Ve&&t.jsx(S.default,{error:Ve,className:"mt-3"})]}))}))}));V.displayName="Input",exports.default=V;
|
|
1
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e=require("../../../_virtual/_tslib.js"),t=require("react/jsx-runtime"),s=require("react"),n=require("../../../hooks/pickaxe/usePickaxeContext.js"),i=require("../../../hooks/pickaxe/useResponseContext.js"),r=require("../../../hooks/studio/useStyleInput.js"),o=require("../../../hooks/studio/useStyleFontSize.js"),a=require("../../../hooks/pickaxe/useConversation.js"),l=require("../../../hooks/pickaxe/useDimensionContext.js"),c=require("../Addons/Auth/hooks/useAuthContext.js"),d=require("../Addons/Document/hooks/useDocument.js"),u=require("../Addons/Scroll/hooks/useScroll.js"),p=require("../Addons/Artifact/hooks/useArtifactContext.js"),m=require("../../../hooks/core/useHover.js"),f=require("../../../hooks/core/useMediaQuery.js"),g=require("../../../common/documents.js"),h=require("eventsource-parser"),v=require("../../Icons/attach-vertical.svg.js"),b=require("../../Icons/arrow-right.svg.js"),y=require("../../Icons/microphone.svg.js"),I=require("../../Icons/stop.svg.js"),x=require("../Addons/Document/List.js"),j=require("../../Core/Textarea.js"),S=require("../../Core/ErrorAlert.js"),w=require("../../../common/error.js"),O=require("../../../common/api/pickaxe.js"),N=require("../../../common/validation.js"),_=require("../../../common/cn.js"),k=require("../../../common/utils.js"),E=require("../../../common/pickaxeConfig.js"),U=require("../../../common/deploymentWebhooks.js"),C=require("../../../hooks/studio/useStudio.js"),T=require("../../../hooks/pickaxe/useSpeech.js"),A=require("../common/PickaxeCommon.js");const D=e=>"string"==typeof e&&e.trim().length>0,P=e=>e.map((e=>Object.assign({},e))),L=e=>e instanceof Error&&("AbortError"===e.name||"BodyStreamBuffer was aborted"===e.message),R=(e,t)=>{if(e&&"object"==typeof e)return e[t]},M=(e,t)=>{const s=R(e,t);return D(s)?s:null},q=e=>{const t=Number(e);return Number.isFinite(t)?t:void 0},F=({studioUser:e,deploymentId:t,portalId:s})=>{var n,i;const r=Array.isArray(R(e,"uses"))?R(e,"uses"):[],o=(({deploymentId:e,portalId:t})=>D(e)?{type:"deployment",id:e}:D(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}},V=s.forwardRef((({resubmitPrompt:R,onFocus:V,onBlur:$,onInputHeightChange:B,initSmitheryAuthData:X},H)=>{var K,W,Y,z,G,J,Q,Z,ee,te,se,ne;const{origin:ie,pickaxeId:re,sessionId:oe,sender:ae,senderType:le,portalId:ce,deploymentId:de,deploymentType:ue,pickaxe:pe,styles:me,colors:fe,translations:ge,locale:he,forceMobile:ve,isNewChat:be,isRtl:ye,isShowFeedbackMessage:Ie,accessGroup:xe,setIsNewChat:je,setIsShowIceBreaker:Se,setValidationStatus:we,setValidationUpgradeGroups:Oe,setValidationUpgradeUrl:Ne,setAccessGroup:_e,onGenerateComplete:ke}=n.usePickaxeContext(),{token:Ee,isLoggedOut:Ue,isSent:Ce,isPricingAuth:Te}=c.useAuthContext(),{messages:Ae,isGenerating:De,setMessages:Pe,setStatus:Le,setLimitData:Re,setError:Me}=i.useResponseContext(),{documents:qe,isUploading:Fe,documentError:Ve,onFileUpload:$e,setDocuments:Be,setDocumentError:Xe}=d.useDocument(),{studio:He}=C.useStudio(),{scrollStartSession:Ke,scrollEndSession:We,scrollToBottom:Ye}=u.useScroll({auto:!0}),{artifacts:ze,currentPopupType:Ge,setArtifacts:Je,setCurrentArtifact:Qe}=p.useArtifactContext(),{height:Ze}=l.useDimensionContext(),et=a.useConversation(),[tt,st]=s.useState(""),[nt,it]=s.useState(!1),[rt,ot]=s.useState(!1),[at,lt]=s.useState(null),[ct,dt]=s.useState(null),[ut,pt]=s.useState(!1),[mt,ft]=s.useState(!1),[gt,ht]=s.useState(0),vt=s.useRef(null),bt=s.useRef(""),yt=s.useRef(null),It=s.useRef(null),xt=s.useRef(null),jt=s.useRef([]),St=s.useRef(null),wt=s.useRef(null),Ot=s.useRef(null),Nt=s.useRef(null),_t=s.useRef(new Set),kt=s.useRef(null),Et=Math.max(.4*Ze,100),{speechTranscript:Ut,isSpeechListening:Ct,isSpeechProcessing:Tt,isSpeechSupported:At,onStartListening:Dt,onStopListening:Pt}=T.useSpeech(),[Lt]=f.useMediaQuery("(max-width: 480px)"),Rt=m.useHover(),{isHover:Mt}=Rt,qt=e.__rest(Rt,["isHover"]),Ft=m.useHover(),{isHover:Vt}=Ft,$t=e.__rest(Ft,["isHover"]),Bt=m.useHover(),{isHover:Xt}=Bt,Ht=e.__rest(Bt,["isHover"]),Kt=o.useStyleFontSize(),Wt=r.useStyleInput(),Yt="undefined"!=typeof window?window.location.hostname:"",zt="undefined"!=typeof window?window.location.href:"",Gt="undefined"!=typeof window&&window.self!==window.top,Jt=Yt.includes("pickaxe.co")&&!zt.includes("https://studio.pickaxe.co/_embed")&&!Gt,Qt=null!==(W=null===(K=null==pe?void 0:pe.documentuploadtype)||void 0===K?void 0:K.startsWith("enduserupload"))&&void 0!==W&&W,Zt=At&&(null==pe?void 0:pe.enablevoicetotext),es=D(de),ts="chat-input"===ue&&be&&!Ce,ss="chat-input"===ue&&Te&&Ue&&Ce,ns=s.useCallback((e=>{const t=N.getValidationFailure(e);return!!t&&(Me(""),Re(null),we(t.status),_e(t.accessGroup),Oe(t.upgradeGroups),Ne(t.upgradeUrl),!0)}),[Me,Re,we,Oe,Ne,_e]),is=null!==(Y=null==pe?void 0:pe.placeholdertext)&&void 0!==Y?Y:ye?"بماذا تريد أن تتحدث؟":(null==ge?void 0:ge["what-do-you-want-to-talk-about"])||"What do you want to talk about?",rs=nt||rt,os=s.useCallback((()=>e.__awaiter(void 0,void 0,void 0,(function*(){pt(!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==pe?void 0:pe.studioid},Ee?{studioSessionToken:Ee}:ae?{sender:ae}:{sender:k.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}})),Jt&&{credentials:"include"})),t=yield e.json();(null==t?void 0:t.studioUser)&&(lt(t.studioUser),dt(t.url))}catch(e){console.error("Failed to fetch studio user:",e)}finally{pt(!0)}}))),[Jt,null==pe?void 0:pe.studioid,ae,Ee]);s.useEffect((()=>{os()}),[os]);const as=Number(null!==(z=null==xe?void 0:xe.limit)&&void 0!==z?z:0),ls="string"==typeof(null==xe?void 0:xe.limitInterval)?xe.limitInterval:null,cs=!!(null==He?void 0:He.data.usage)&&He.data.usage.isCredits,ds=s.useMemo((()=>F({studioUser:at,deploymentId:de,portalId:ce})),[de,ce,at]);s.useEffect((()=>{es&&be&&oe&&_t.current.add(oe)}),[be,oe,es]);const us=s.useCallback((()=>{var e,t,s;return{studioId:null==pe?void 0:pe.studioid,userEmail:M(at,"email"),userId:null!==(e=M(at,"userId"))&&void 0!==e?e:M(at,"userid"),sessionId:oe,deploymentId:de,deploymentType:ue,portalId:ce,accessGroupId:null!==(t=null==xe?void 0:xe.accessGroupId)&&void 0!==t?t:null,pickaxeId:re,sender:ae,senderType:le,origin:ie,metadata:null!==(s=E.getPickaxeConfigMetadata(de))&&void 0!==s?s:null}}),[null==xe?void 0:xe.accessGroupId,de,ue,ie,null==pe?void 0:pe.studioid,re,ce,ae,le,oe,at]),ps=s.useCallback((()=>!!(es&&ut&&oe)&&(!!_t.current.has(oe)&&(U.fireDeploymentSessionInitializedWebhook(us()),_t.current.delete(oe),!0))),[us,ut,oe,es]);s.useEffect((()=>{if(!ut||!oe)return;ps();const e=kt.current;(null==e?void 0:e.sessionId)===oe&&(U.fireDeploymentFirstMessageSubmittedWebhook(Object.assign(Object.assign(Object.assign({},e),us()),{message:e.message,documentIds:e.documentIds,uploadedModelImages:e.uploadedModelImages,hasUploadedDocuments:e.hasUploadedDocuments,isHidden:e.isHidden})),kt.current=null)}),[ps,us,ut,oe]);const ms={currentUses:q(null==at?void 0:at.currentUses),extraUses:q(null==at?void 0:at.extraUses)},fs=ds.scope?{currentUses:null!==(J=q(null===(G=ds.record)||void 0===G?void 0:G.currentUses))&&void 0!==J?J:0,extraUses:null!==(Z=q(null===(Q=ds.record)||void 0===Q?void 0:Q.extraUses))&&void 0!==Z?Z:0}:{currentUses:0,extraUses:0},gs=M(at,"type"),hs="guest"===gs||!gs&&Ue?fs:ms;s.useEffect((()=>{let t=!0;return e.__awaiter(void 0,void 0,void 0,(function*(){var e;if(cs&&(null===(e=null==He?void 0:He.data)||void 0===e?void 0:e.workspaceId))try{const e=yield O.pickaxeApi2.get(`/cost_per_run?workspaceId=${He.data.workspaceId}`,{withCredentials:!1});t&&ht(1e4*(Number(e.data.costPerRun)||0))}catch(e){console.error("Failed to fetch average cost per run:",e),t&&ht(0)}else t&&ht(0)})),()=>{t=!1}}),[cs,null===(ee=null==He?void 0:He.data)||void 0===ee?void 0:ee.workspaceId]);const vs=(({currentUses:e,extraUses:t,limit:s,limitInterval:n})=>{const i=Number(null!=e?e:0),r=Number(null!=t?t:0);return s===A.STUDIO_INFINITY_VALUE||r===A.STUDIO_INFINITY_VALUE?A.STUDIO_INFINITY_VALUE:"one_time"===n?Math.max(0,r-i):(console.log("Calculating remaining balance with limit:",s,"currentUses:",i,"extraUses:",r),Math.max(0,s-i)+r)})({currentUses:hs.currentUses,extraUses:hs.extraUses,limit:as,limitInterval:ls}),bs=vs===A.STUDIO_INFINITY_VALUE?A.STUDIO_INFINITY_VALUE:Math.max(0,Math.ceil(vs)),ys=(({extraUses:e,limit:t,limitInterval:s})=>{const n=Number(null!=e?e:0);return t===A.STUDIO_INFINITY_VALUE||n===A.STUDIO_INFINITY_VALUE?A.STUDIO_INFINITY_VALUE:"one_time"===s?Math.max(0,n):Math.max(0,t)+Math.max(0,n)})({extraUses:hs.extraUses,limit:as,limitInterval:ls}),Is=ys===A.STUDIO_INFINITY_VALUE?A.STUDIO_INFINITY_VALUE:Math.ceil(.05*ys),xs=cs?Math.ceil(5*gt):5,js=Is===A.STUDIO_INFINITY_VALUE?A.STUDIO_INFINITY_VALUE:Math.max(Is,xs),Ss=s.useMemo((()=>!!at&&(!mt&&(bs!==A.STUDIO_INFINITY_VALUE&&bs<=js))),[mt,js,bs,at]),ws=(null===(te=null==xe?void 0:xe.upgrade)||void 0===te?void 0:te.isLinkToCustomURL)&&"string"==typeof xe.upgrade.limitLink&&xe.upgrade.limitLink.trim().length>0?xe.upgrade.limitLink.trim():null,Os=ws&&"string"==typeof(null===(se=null==xe?void 0:xe.upgrade)||void 0===se?void 0:se.limitCTA)&&xe.upgrade.limitCTA.trim().length>0?xe.upgrade.limitCTA:(null==ge?void 0:ge["pricing.upgrade"])||(null==ge?void 0:ge.upgrade)||"Upgrade",Ns=s.useMemo((()=>{var e,t,s;return!!be&&(!!pe&&(!et.isLoading&&(!((null!==(t=null===(e=et.data)||void 0===e?void 0:e.messages.length)&&void 0!==t?t:0)>1)&&(!!(null===(s=pe.icebreakers)||void 0===s?void 0:s.length)&&(!Ie&&!ts)))))}),[pe,be,Ie,ts,et.data,et.isLoading]),_s=s.useMemo((()=>{if(De||Fe)return!1;const e=Qt&&qe.length>0&&qe.every((e=>"finished"===e.status));return!(!tt.trim()&&!e)&&qe.every((e=>"finished"===e.status||e.isInsertedAsRaw))}),[Qt,De,Fe,tt,qe]);s.useImperativeHandle(H,(()=>({onSubmit:ks}))),s.useEffect((()=>{Se(Ns)}),[Ns]),s.useEffect((()=>{var e;if(R){const t=Array.from(Ae),s=null===(e=t[t.length-2].parts.find((e=>"text"===e.type)))||void 0===e?void 0:e.content;ks(s,!0)}}),[R]),s.useEffect((()=>{if(!Ot.current||!B)return;const e=new ResizeObserver((e=>{for(const t of e)B(t.contentRect.height)}));return e.observe(Ot.current),()=>{e.disconnect()}}),[B]),s.useEffect((()=>{if(!Ct)return;const e=bt.current?`${bt.current} `:"";st(`${e}${Ut}`)}),[Ut,Ct]),s.useEffect((()=>{if(!St.current)return;(()=>{if(!St.current)return;let e=St.current.scrollHeight>52;tt.includes("\n")||qe.length?e=!0:tt.trim()||(e=!1),it(e)})()}),[tt,qe]),s.useEffect((()=>{const e=St.current,t=wt.current;if(!e||!t||nt||tt.includes("\n"))return void ot(!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=tt||is,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;ot(r>l)}),[tt,nt,is]);const ks=(t,s=!1)=>e.__awaiter(void 0,void 0,void 0,(function*(){var e,n,i,r;let o=null;try{if(De||Fe)return;const a=qe.filter((e=>"finished"===e.status&&!e.isInsertedAsRaw)),l=a.map((e=>e.documentId)).filter(Boolean),c=a.filter((e=>"image"===e.type)).map((e=>{const t=e.name.split(".").pop()||"";return{documentId:e.documentId,extension:t}})),d=null!=t?t:tt,u=null!==(n=null===(e=null==pe?void 0:pe.documentuploadtype)||void 0===e?void 0:e.startsWith("enduserupload"))&&void 0!==n&&n&&l.length>0;if(!d&&!u)return;Me(""),Xe(""),Re(null),st(""),je(!1),Le("fetching"),Ke(),Ye();const p=[...s?Array.from(Ae.slice(0,Ae.length-1)):Array.from(Ae),...s?[]:[{id:Ae.length+1,role:"user",parts:[{type:"text",content:d,isVisible:!0}],documentIds:u?l:[]}],{id:Ae.length+(s?0:2),role:"assistant",parts:[],documentIds:[]}];Pe(p),Ye(),u&&Be([]);const m=E.getPickaxeConfigMetadata(de),f="undefined"!=typeof crypto&&"randomUUID"in crypto?crypto.randomUUID():`submission-${Date.now()}-${Math.random().toString(36).slice(2)}`;o=f,It.current=f,xt.current=null,jt.current=[];const g=yield fetch(`${process.env.NEXT_PUBLIC_PICKAXE_API2_URL}/response/submit`,Object.assign({method:"POST",body:JSON.stringify(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({origin:ie,pickaxeId:re,sessionId:oe,submissionId:f,senderType:le,value:d},u&&{documentIds:l}),ae&&{sender:ae}),Ee&&{studioSessionToken:Ee}),!Ee&&!ae&&{sender:k.initializeEmbedUserId()}),ce&&{portalId:ce}),de&&{deploymentId:de}),m&&{metadata:m}),u&&c.length>0?{uploadedModelImages:c}:{})),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()})},Jt&&{credentials:"include"})),v=yield g.json();if(!v.success){if(v.limitData){const e=new Error(v.error||v.message||(null==ge?void 0:ge["failed-to-start-generation"])||"Failed to start generation");throw e.limitData=v.limitData,e}if(ns(v))return;throw new Error(v.error||v.message||(null==ge?void 0:ge["failed-to-start-generation"])||"Failed to start generation")}const b=null!==(i=v.submissionId)&&void 0!==i?i:f;o=b,It.current=b;const y=()=>xt.current===b;if(y())return;es&&be&&oe&&_t.current.add(oe);const I=Object.assign(Object.assign({},us()),{message:d,documentIds:u?l:[],uploadedModelImages:u?c:[],hasUploadedDocuments:u,isHidden:s,metadata:null!=m?m:null});ut?(ps(),U.fireDeploymentFirstMessageSubmittedWebhook(I)):kt.current=I,Le("streaming"),Nt.current=new AbortController;const x=p.length-1,j=[];let S=[...null!=ze?ze:[]],w=0,O=!1,N="";for(;!O;)try{const e=yield fetch(`${process.env.NEXT_PUBLIC_PICKAXE_API2_URL}/response/stream/${b}?index=${w}`,{signal:null===(r=Nt.current)||void 0===r?void 0:r.signal,headers:{"Cache-Control":"no-cache",Connection:"keep-alive"}});if(!e.body)throw new Error("No response body");const t=e.body.getReader();yt.current=t;const s=new TextDecoder,n=h.createParser({onEvent:e=>{var t,s;if(y())O=!0;else if(e.event&&"ping"!==e.event&&w++,"stop"!==e.event){if("error"===e.event){const t=JSON.parse(e.data);if(t.limitData)return Re(t.limitData),Me(""),void(O=!0);const s=t.error||t.message||(null==ge?void 0:ge["something-went-wrong"])||"Something went wrong.";return ns(t)||Me(s),void(O=!0)}if("delta"===e.event){const n=JSON.parse(e.data);if("data-error"===n.type&&X){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 O=!0,X({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 O=!0,X({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 O=!0,X({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 O=!0,X({provider:"composio",toolkitSlug:t.toolkitSlug,serverId:t.serverId,name:t.name}),new Error("STOP_STREAM")}}else if("text-start"===n.type)N="",j.push({type:"text",content:"",isVisible:null===(t=n.isVisible)||void 0===t||t});else if("text-delta"===n.type)N+=n.delta,j[j.length-1].content=N;else if("text-end"===n.type)N="";else if("reasoning-start"===n.type)N="",j.push({type:"reasoning",content:"",isVisible:null===(s=n.isVisible)||void 0===s||s});else if("reasoning-delta"===n.type)N+=n.delta,j[j.length-1].content=N;else if("reasoning-end"===n.type)N="";else if(n.type.startsWith("data-")){const e=n;j.push({type:e.type,content:JSON.stringify(e.data),isVisible:!0})}jt.current=P(j),Pe([...p.slice(0,x),Object.assign(Object.assign({},p[p.length-1]),{id:Ae.length+1,role:"assistant",parts:j})])}else if("artifact_created"===e.event){const t=JSON.parse(e.data);S=S.filter((e=>!(e.id===t.id&&e.version===t.version))),S.push(Object.assign(Object.assign({},t),{content:"",status:"streaming"})),Je([...S]),Ge.startsWith("inline")||Qe({id:t.id,version:t.version})}else if("artifact_updated"===e.event){const t=JSON.parse(e.data);S=S.filter((e=>!(e.id===t.id&&e.version===t.version))),S.push(Object.assign(Object.assign({},t),{content:"",status:"updating"})),Je(S),Ge.startsWith("inline")||Qe({id:t.id,version:t.version})}else if("artifact_rewrite"===e.event){const t=JSON.parse(e.data);S=S.filter((e=>!(e.id===t.id&&e.version===t.version))),S.push(Object.assign(Object.assign({},t),{content:"",status:"streaming"})),Je(S),Ge.startsWith("inline")||Qe({id:t.id,version:t.version})}else if("artifact_content"===e.event){const t=JSON.parse(e.data),s=t.token.replace(/\u200B/g,"");S=S.map((e=>e.id===t.id&&e.version===t.version?Object.assign(Object.assign({},e),{content:e.content+s,status:"streaming"}):e)),Je(S)}else if("artifact_finished"===e.event){const t=JSON.parse(e.data);Je(S.map((e=>e.id===t.id?Object.assign(Object.assign({},e),{status:"finished"}):e)))}else if("error"===e.event){const t=JSON.parse(e.data);if(t.limitData)return Re(t.limitData),Me(""),void(O=!0);const s=t.error||t.message||(null==ge?void 0:ge["something-went-wrong-try-again"])||"Something went wrong, please try again.";if(ns(t))return void(O=!0);Me(s)}else"stop"===e.event&&(O=!0)}else O=!0}});for(;;){if(y()){O=!0,t.cancel().catch((()=>{}));break}const{value:e,done:i}=yield t.read();if(y()){O=!0,t.cancel().catch((()=>{}));break}if(i)break;n.feed(s.decode(e))}O||y()||(yield new Promise((e=>setTimeout(e,1e3))))}catch(e){if("STOP_STREAM"===e.message||L(e)||y())return void(O=!0);console.warn("Stream connection lost, retrying...",e),yield new Promise((e=>setTimeout(e,1e3)))}null==ke||ke(oe)}catch(e){if(L(e))return;if(e.limitData)Re(e.limitData),Me("");else{let t=w.default(e)||"";t&&!t.includes("Unexpected token 'A',")||(t=(null==ge?void 0:ge["high-traffic-try-again-later"])||"Oops! We're experiencing high traffic at the moment. Please try again later."),ns(t)||Me(t)}}finally{const e=!o||It.current===o;Ye(),e&&(Le("idle"),We(),yt.current=null),o&&e&&(It.current=null,jt.current=[]),yield os()}}));return ss?null:t.jsx("div",Object.assign({className:_.default("flex w-full flex-shrink-0 flex-col items-center",!ts&&"px-4 pb-8"),dir:ye?"rtl":"ltr"},{children:t.jsxs("div",Object.assign({className:"flex w-full max-w-[800px] flex-col"},{children:[t.jsxs("div",Object.assign({ref:Ot,className:_.default("relative flex flex-col w-full justify-end gap-y-3 py-[3px]","block"===me.formFieldStyle&&"shadow"),style:Object.assign(Object.assign({},Wt),{maxHeight:`${Et}px`,overflowY:"auto"})},{children:[Ss&&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:Wt.backgroundColor?`${Wt.backgroundColor}E6`:void 0,borderColor:fe.text+"20",color:fe.text,borderTopRightRadius:me.cornerRadius+"px",borderTopLeftRadius:me.cornerRadius+"px"}},{children:[t.jsx("div",Object.assign({className:"flex items-center gap-2 text-sm font-medium"},{children:t.jsxs("span",{children:[bs.toLocaleString()," ",cs?(null==ge?void 0:ge.credits)||"Credits":(null==ge?void 0:ge.uses)||"Uses"," ",(null==ge?void 0:ge.remaining)||"remaining"]})})),t.jsxs("div",Object.assign({className:"flex items-center gap-3"},{children:[t.jsx("button",Object.assign({className:"rounded-md px-3 py-1.5 text-xs font-semibold transition-opacity hover:opacity-90",style:{backgroundColor:fe.accent,color:fe.accentText},onClick:e=>{if(e.preventDefault(),e.stopPropagation(),ws)return void window.open(ws,"_blank","noopener,noreferrer");const t=k.buildUpgradeUrl({baseUrl:ct,accessGroupId:null==xe?void 0:xe.accessGroupId,redirectUrl:document.URL});t&&(k.isInIframe()?window.open(t):location.href=t)}},{children:Os})),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:()=>ft(!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"})}))}))]}))]})),!De&&qe.length>0&&t.jsx(x.default,{className:"p-4 pb-0",isDisabled:De}),t.jsxs("div",Object.assign({className:"relative flex w-full flex-col"},{children:[Ct&&t.jsxs("div",Object.assign({className:"absolute left-4 top-1/2 flex -translate-y-1/2 select-none items-center gap-x-2"},{children:[t.jsx("span",{className:"h-2 w-2 animate-pulse rounded-full bg-c-secondary",style:{backgroundColor:null!==(ne=fe.accent)&&void 0!==ne?ne:"#ff0000"}}),t.jsx("span",Object.assign({className:"text-sm text-c-secondary font-semilight",style:{color:fe.text+"90"}},{children:(null==ge?void 0:ge.listening)||"Listening..."}))]})),t.jsx(j.default,Object.assign({ref:St,className:_.default(Kt.i1,"py-3.5 max-h-60 px-4 w-full border-transparent bg-transparent",!tt.trim()&&!tt.includes("\n")&&"overflow-hidden text-ellipsis whitespace-nowrap placeholder:whitespace-normal placeholder:overflow-visible",ye?"text-right":"text-left",rs&&"mb-12",Ct&&"text-transparent"),value:tt,placeholder:is,onChange:e=>{st(e)},onKeyDown:e=>{ve||Lt||"Enter"===e.key&&(e.shiftKey||(e.preventDefault(),Fe||De||ks()))},onPaste:t=>e.__awaiter(void 0,void 0,void 0,(function*(){const e=Array.from(t.clipboardData.files||[]);if(e.length>0){if(!Qt)return;t.preventDefault(),je(!1),yield $e(e)}}))},V&&{onFocus:V},$&&{onBlur:$},{dir:ye?"rtl":"ltr"})),t.jsx("div",Object.assign({ref:wt,className:_.default("flex items-center gap-2 absolute right-0 z-2 transition-all duration-200 ease-in-out",rs?"bottom-0 mb-2.5":"top-1/2 -translate-y-1/2"),style:Object.assign(Object.assign({},!rs&&Wt.backgroundColor&&{backgroundColor:Wt.backgroundColor}),{borderTopRightRadius:me.cornerRadius+"px",borderBottomRightRadius:me.cornerRadius+"px"})},{children:De?t.jsx("button",Object.assign({className:"flex h-8 w-8 items-center mr-2 justify-center rounded-full outline-none transition-colors duration-200 ease-in-out",onClick:()=>{const t=It.current;t&&(xt.current=t,(t=>{e.__awaiter(void 0,void 0,void 0,(function*(){if(!(t=null!=t?t:It.current))return;const e=P(jt.current);try{yield fetch(`${process.env.NEXT_PUBLIC_PICKAXE_API2_URL}/response/cancel/${t}`,Object.assign({method:"POST",headers:Object.assign(Object.assign({"Content-Type":"application/json"},(!process.env.NODE_ENV||"development"===process.env.NODE_ENV)&&Object.assign({},process.env.NEXT_PUBLIC_PICKAXE_SESSION_TOKEN&&{"x-pickaxe-session-token":process.env.NEXT_PUBLIC_PICKAXE_SESSION_TOKEN})),{"x-request-sent-at":(new Date).toISOString()}),body:JSON.stringify({outputMessageParts:e})},Jt&&{credentials:"include"}))}catch(e){console.warn("Failed to cancel submission",e)}}))})(t)),Nt.current&&(Nt.current.abort(),Nt.current=null),yt.current&&(yt.current.cancel().catch((()=>{})),yt.current=null),Le("idle")},style:{backgroundColor:fe.accent,color:fe.accentText}},{children:t.jsx(I.default,{className:"h-4 w-4 shrink-0"})})):Ct?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:Pt,style:{backgroundColor:fe.accent,color:fe.accentText}},{children:t.jsx(I.default,{className:"h-4 w-4 shrink-0"})})):t.jsxs(t.Fragment,{children:[Qt&&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:Vt?fe.accent+"10":void 0,color:Vt?fe.accent:fe.accent+"80"},disabled:Fe||De,onClick:()=>{var e;return null===(e=vt.current)||void 0===e?void 0:e.click()}},$t,{children:[t.jsx("input",{id:"file-upload",ref:vt,type:"file",accept:[...g.allowedFileMimeTypes,...g.allowedImageMimeTypes,...g.additionalAllowedFileExtensions].join(", "),multiple:!0,hidden:!0,className:"hidden",onChange:t=>e.__awaiter(void 0,void 0,void 0,(function*(){je(!1),yield $e(Array.from(t.target.files||[])),t.target.value=""}))}),t.jsx(v.default,{className:"h-6 w-6 shrink-0"})]})),Zt&&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:Ct?fe.accent:Xt?fe.accent+"10":void 0,color:Ct?fe.accentText:Xt?fe.accent:fe.accent+"80"},disabled:Fe||De||Tt,onClick:()=>{Ct?Pt():(bt.current=tt,Dt(he||"en-US"))}},Ht,{children:t.jsx(y.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:Mt||_s?fe.accent:fe.accent+"10",color:Mt||_s?fe.accentText:fe.accent+"80"},disabled:!_s,onClick:()=>ks()},qt,{children:t.jsx(b.default,{className:_.default("h-6 w-6 shrink-0",ye&&"scale-x-[-1] transform")})}))]})}))]}))]})),Ve&&t.jsx(S.default,{error:Ve,className:"mt-3"})]}))}))}));V.displayName="Input",exports.default=V;
|
package/dist/esm/common/utils.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{parse as e}from"tldts";const t="PXE-uid",r=(e,t="",r="")=>{let
|
|
1
|
+
import{parse as e}from"tldts";const t="PXE-uid",r=(e,t="",r="")=>{let n="";for(let t=0;t<e;t++){n+="ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"[Math.floor(36*Math.random())]}return t+n+r},n=(e,t=!1)=>{let r="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890";t&&(r=r.replace(/[0-9]/g,""));let n="";for(let t=0;t<e;t++)n+=r.charAt(Math.floor(Math.random()*r.length));return n},o=e=>{const t=e.match(/(https?:\/\/[^\s]+)/g)||[];return Array.from(new Set(t))},l=({baseUrl:e,redirectUrl:t,accessGroupId:r,currentUrl:n})=>{if(!e)return null;const o=null!=n?n:"undefined"!=typeof window?window.location.href:null;if(!o)return null;try{const n=new URL(e,o);if(r){const e=((e,t)=>{const r=e.pathname.split("/"),n=r.findIndex((e=>"ag-pricing"===e));return-1!==n&&!r[n+1]&&(r.splice(n+1,0,encodeURIComponent(t)),e.pathname=r.join("/"),!0)})(n,r);e||n.searchParams.set("agid",r)}return t&&n.searchParams.set("redirectUrl",t),n.toString()}catch(e){return console.error("[pxe] failed to build upgrade url",e),null}},c=(e,t=2)=>{if(!+e)return"0 Bytes";const r=t<0?0:t,n=Math.floor(Math.log(e)/Math.log(1024));return`${parseFloat((e/Math.pow(1024,n)).toFixed(r))} ${["Bytes","KB","MB","PB","EB"][n]}`},i=e=>{try{const t=document.cookie.split("; ");for(const r of t){const[t,n]=r.split("=");if(t===e)return n}return null}catch(e){return console.error("[pxe] failed to get cookie",e),null}},a=e=>{document.cookie=e+"=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;"},u=()=>{try{const r=i(t);if(!r){const r=n(28),o=new Date;o.setFullYear(o.getFullYear()+1);let l=window.location.hostname;const c=e(l).domain;if(c)l=`.${c}`;else{const e=l.split(":")[0],t=e.split(".");l=e,t.length>=2&&(l=`.${t.slice(-2).join(".")}`)}return document.cookie=`${t}=${r};Path=/; Domain=${l}; Expires=${o.toUTCString()}`,r}return r}catch(e){return console.error("[pxe-embed] failed to initialized embed user id",e),n(28)}},s=e=>{try{if("undefined"==typeof window)return null;let t=null;return t=new URLSearchParams(window.location.search).get("pxtoken"),t||(t=localStorage.getItem(`PXE-token-${e}`)),t||(t=i(`PXE-token-${e}`)),t||(t=i(`__Secure-PS-${e}.session-token`)),t?decodeURIComponent(t):null}catch(e){return null}},d=(e,t)=>{try{if("undefined"==typeof window)return;localStorage.setItem(e,t)}catch(e){console.error("[pxe] failed to set auth token",e)}},f=e=>{try{if("undefined"==typeof window)return;localStorage.removeItem(e)}catch(e){console.error("[pxe] failed to delete auth token",e)}};function p(...e){return t=>{for(const r of e)r&&("function"==typeof r?r(t):r.current=t)}}const h=()=>{if("undefined"==typeof window)return!1;try{return window.self!==window.top}catch(e){return!0}},m=e=>{try{return JSON.parse(e)}catch(e){return null}};export{t as COOKIE_USER_ID,l as buildUpgradeUrl,f as deleteAuthToken,a as deleteCookie,o as extractUrlsFromText,c as formatBytes,r as generateId,s as getAuthToken,i as getCookie,u as initializeEmbedUserId,h as isInIframe,p as mergeRefs,n as randomStr,m as safeJSONParse,d as setAuthToken};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{__rest as e,__awaiter as t}from"../../../_virtual/_tslib.js";import{jsx as n,jsxs as s,Fragment as o}from"react/jsx-runtime";import{forwardRef as i,useState as r,useRef as a,useCallback as l,useEffect as c,useMemo as d,useImperativeHandle as u}from"react";import{usePickaxeContext as m}from"../../../hooks/pickaxe/usePickaxeContext.js";import{useResponseContext as p}from"../../../hooks/pickaxe/useResponseContext.js";import{useStyleInput as f}from"../../../hooks/studio/useStyleInput.js";import{useStyleFontSize as g}from"../../../hooks/studio/useStyleFontSize.js";import{useConversation as h}from"../../../hooks/pickaxe/useConversation.js";import{useDimensionContext as v}from"../../../hooks/pickaxe/useDimensionContext.js";import{useAuthContext as b}from"../Addons/Auth/hooks/useAuthContext.js";import{useDocument as y}from"../Addons/Document/hooks/useDocument.js";import{useScroll as x}from"../Addons/Scroll/hooks/useScroll.js";import{useArtifactContext as I}from"../Addons/Artifact/hooks/useArtifactContext.js";import{useHover as j}from"../../../hooks/core/useHover.js";import{useMediaQuery as w}from"../../../hooks/core/useMediaQuery.js";import{allowedFileMimeTypes as O,allowedImageMimeTypes as k,additionalAllowedFileExtensions as S}from"../../../common/documents.js";import{createParser as N}from"eventsource-parser";import C from"../../Icons/attach-vertical.svg.js";import E from"../../Icons/arrow-right.svg.js";import _ from"../../Icons/microphone.svg.js";import T from"../../Icons/stop.svg.js";import U from"../Addons/Document/List.js";import A from"../../Core/Textarea.js";import P from"../../Core/ErrorAlert.js";import D from"../../../common/error.js";import{pickaxeApi2 as L}from"../../../common/api/pickaxe.js";import{getValidationFailure as R}from"../../../common/validation.js";import M from"../../../common/cn.js";import{buildUpgradeUrl as $,isInIframe as B,initializeEmbedUserId as X}from"../../../common/utils.js";import{getPickaxeConfigMetadata as K}from"../../../common/pickaxeConfig.js";import{fireDeploymentSessionInitializedWebhook as V,fireDeploymentFirstMessageSubmittedWebhook as F}from"../../../common/deploymentWebhooks.js";import{useStudio as H}from"../../../hooks/studio/useStudio.js";import{useSpeech as W}from"../../../hooks/pickaxe/useSpeech.js";import{STUDIO_INFINITY_VALUE as G}from"../common/PickaxeCommon.js";const J=e=>"string"==typeof e&&e.trim().length>0,z=e=>e.map((e=>Object.assign({},e))),q=e=>e instanceof Error&&("AbortError"===e.name||"BodyStreamBuffer was aborted"===e.message),Q=(e,t)=>{if(e&&"object"==typeof e)return e[t]},Y=(e,t)=>{const n=Q(e,t);return J(n)?n:null},Z=e=>{const t=Number(e);return Number.isFinite(t)?t:void 0},ee=({studioUser:e,deploymentId:t,portalId:n})=>{var s,o;const i=Array.isArray(Q(e,"uses"))?Q(e,"uses"):[],r=(({deploymentId:e,portalId:t})=>J(e)?{type:"deployment",id:e}:J(t)?{type:"portal",id:t}:null)({deploymentId:t,portalId:n});if(!r)return{scope:r,record:null};const a=null!==(o=null!==(s=i.find((e=>e.id===r.id&&e.type===r.type)))&&void 0!==s?s:i.find((e=>e.id===r.id)))&&void 0!==o?o:null;return{scope:r,record:a}},te=i((({resubmitPrompt:i,onFocus:Q,onBlur:te,onInputHeightChange:ne,initSmitheryAuthData:se},oe)=>{var ie,re,ae,le,ce,de,ue,me,pe,fe,ge,he;const{origin:ve,pickaxeId:be,sessionId:ye,sender:xe,senderType:Ie,portalId:je,deploymentId:we,deploymentType:Oe,pickaxe:ke,styles:Se,colors:Ne,translations:Ce,locale:Ee,forceMobile:_e,isNewChat:Te,isRtl:Ue,isShowFeedbackMessage:Ae,accessGroup:Pe,setIsNewChat:De,setIsShowIceBreaker:Le,setValidationStatus:Re,setValidationUpgradeGroups:Me,setValidationUpgradeUrl:$e,setAccessGroup:Be,onGenerateComplete:Xe}=m(),{token:Ke,isLoggedOut:Ve,isSent:Fe,isPricingAuth:He}=b(),{messages:We,isGenerating:Ge,setMessages:Je,setStatus:ze,setLimitData:qe,setError:Qe}=p(),{documents:Ye,isUploading:Ze,documentError:et,onFileUpload:tt,setDocuments:nt,setDocumentError:st}=y(),{studio:ot}=H(),{scrollStartSession:it,scrollEndSession:rt,scrollToBottom:at}=x({auto:!0}),{artifacts:lt,currentPopupType:ct,setArtifacts:dt,setCurrentArtifact:ut}=I(),{height:mt}=v(),pt=h(),[ft,gt]=r(""),[ht,vt]=r(!1),[bt,yt]=r(!1),[xt,It]=r(null),[jt,wt]=r(null),[Ot,kt]=r(!1),[St,Nt]=r(!1),[Ct,Et]=r(0),_t=a(null),Tt=a(""),Ut=a(null),At=a(null),Pt=a(null),Dt=a([]),Lt=a(null),Rt=a(null),Mt=a(null),$t=a(null),Bt=a(new Set),Xt=a(null),Kt=Math.max(.4*mt,100),{speechTranscript:Vt,isSpeechListening:Ft,isSpeechProcessing:Ht,isSpeechSupported:Wt,onStartListening:Gt,onStopListening:Jt}=W(),[zt]=w("(max-width: 480px)"),qt=j(),{isHover:Qt}=qt,Yt=e(qt,["isHover"]),Zt=j(),{isHover:en}=Zt,tn=e(Zt,["isHover"]),nn=j(),{isHover:sn}=nn,on=e(nn,["isHover"]),rn=g(),an=f(),ln="undefined"!=typeof window?window.location.hostname:"",cn="undefined"!=typeof window?window.location.href:"",dn="undefined"!=typeof window&&window.self!==window.top,un=ln.includes("pickaxe.co")&&!cn.includes("https://studio.pickaxe.co/_embed")&&!dn,mn=null!==(re=null===(ie=null==ke?void 0:ke.documentuploadtype)||void 0===ie?void 0:ie.startsWith("enduserupload"))&&void 0!==re&&re,pn=Wt&&(null==ke?void 0:ke.enablevoicetotext),fn=J(we),gn="chat-input"===Oe&&Te&&!Fe,hn="chat-input"===Oe&&He&&Ve&&Fe,vn=l((e=>{const t=R(e);return!!t&&(Qe(""),qe(null),Re(t.status),Be(t.accessGroup),Me(t.upgradeGroups),$e(t.upgradeUrl),!0)}),[Qe,qe,Re,Me,$e,Be]),bn=null!==(ae=null==ke?void 0:ke.placeholdertext)&&void 0!==ae?ae:Ue?"بماذا تريد أن تتحدث؟":(null==Ce?void 0:Ce["what-do-you-want-to-talk-about"])||"What do you want to talk about?",yn=ht||bt,xn=l((()=>t(void 0,void 0,void 0,(function*(){kt(!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==ke?void 0:ke.studioid},Ke?{studioSessionToken:Ke}:xe?{sender:xe}:{sender:X()}))},(!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}})),un&&{credentials:"include"})),t=yield e.json();(null==t?void 0:t.studioUser)&&(It(t.studioUser),wt(t.url))}catch(e){console.error("Failed to fetch studio user:",e)}finally{kt(!0)}}))),[un,null==ke?void 0:ke.studioid,xe,Ke]);c((()=>{xn()}),[xn]);const In=Number(null!==(le=null==Pe?void 0:Pe.limit)&&void 0!==le?le:0),jn="string"==typeof(null==Pe?void 0:Pe.limitInterval)?Pe.limitInterval:null,wn=!!(null==ot?void 0:ot.data.usage)&&ot.data.usage.isCredits,On=d((()=>ee({studioUser:xt,deploymentId:we,portalId:je})),[we,je,xt]);c((()=>{fn&&Te&&ye&&Bt.current.add(ye)}),[Te,ye,fn]);const kn=l((()=>{var e,t,n;return{studioId:null==ke?void 0:ke.studioid,userEmail:Y(xt,"email"),userId:null!==(e=Y(xt,"userId"))&&void 0!==e?e:Y(xt,"userid"),sessionId:ye,deploymentId:we,deploymentType:Oe,portalId:je,accessGroupId:null!==(t=null==Pe?void 0:Pe.accessGroupId)&&void 0!==t?t:null,pickaxeId:be,sender:xe,senderType:Ie,origin:ve,metadata:null!==(n=K(we))&&void 0!==n?n:null}}),[null==Pe?void 0:Pe.accessGroupId,we,Oe,ve,null==ke?void 0:ke.studioid,be,je,xe,Ie,ye,xt]),Sn=l((()=>!!(fn&&Ot&&ye)&&(!!Bt.current.has(ye)&&(V(kn()),Bt.current.delete(ye),!0))),[kn,Ot,ye,fn]);c((()=>{if(!Ot||!ye)return;Sn();const e=Xt.current;(null==e?void 0:e.sessionId)===ye&&(F(Object.assign(Object.assign(Object.assign({},e),kn()),{message:e.message,documentIds:e.documentIds,uploadedModelImages:e.uploadedModelImages,hasUploadedDocuments:e.hasUploadedDocuments,isHidden:e.isHidden})),Xt.current=null)}),[Sn,kn,Ot,ye]);const Nn={currentUses:Z(null==xt?void 0:xt.currentUses),extraUses:Z(null==xt?void 0:xt.extraUses)},Cn=On.scope?{currentUses:null!==(de=Z(null===(ce=On.record)||void 0===ce?void 0:ce.currentUses))&&void 0!==de?de:0,extraUses:null!==(me=Z(null===(ue=On.record)||void 0===ue?void 0:ue.extraUses))&&void 0!==me?me:0}:{currentUses:0,extraUses:0},En=Y(xt,"type"),_n="guest"===En||!En&&Ve?Cn:Nn;c((()=>{let e=!0;return t(void 0,void 0,void 0,(function*(){var t;if(wn&&(null===(t=null==ot?void 0:ot.data)||void 0===t?void 0:t.workspaceId))try{const t=yield L.get(`/cost_per_run?workspaceId=${ot.data.workspaceId}`,{withCredentials:!1});e&&Et(1e4*(Number(t.data.costPerRun)||0))}catch(t){console.error("Failed to fetch average cost per run:",t),e&&Et(0)}else e&&Et(0)})),()=>{e=!1}}),[wn,null===(pe=null==ot?void 0:ot.data)||void 0===pe?void 0:pe.workspaceId]);const Tn=(({currentUses:e,extraUses:t,limit:n,limitInterval:s})=>{const o=Number(null!=e?e:0),i=Number(null!=t?t:0);return n===G||i===G?G:"one_time"===s?Math.max(0,i-o):(console.log("Calculating remaining balance with limit:",n,"currentUses:",o,"extraUses:",i),Math.max(0,n-o)+i)})({currentUses:_n.currentUses,extraUses:_n.extraUses,limit:In,limitInterval:jn}),Un=Tn===G?G:Math.max(0,Math.ceil(Tn)),An=(({extraUses:e,limit:t,limitInterval:n})=>{const s=Number(null!=e?e:0);return t===G||s===G?G:"one_time"===n?Math.max(0,s):Math.max(0,t)+Math.max(0,s)})({extraUses:_n.extraUses,limit:In,limitInterval:jn}),Pn=An===G?G:Math.ceil(.05*An),Dn=wn?Math.ceil(5*Ct):5,Ln=Pn===G?G:Math.max(Pn,Dn),Rn=d((()=>!!xt&&(!St&&(Un!==G&&Un<=Ln))),[St,Ln,Un,xt]),Mn=(null===(fe=null==Pe?void 0:Pe.upgrade)||void 0===fe?void 0:fe.isLinkToCustomURL)&&"string"==typeof Pe.upgrade.limitLink&&Pe.upgrade.limitLink.trim().length>0?Pe.upgrade.limitLink.trim():null,$n=Mn&&"string"==typeof(null===(ge=null==Pe?void 0:Pe.upgrade)||void 0===ge?void 0:ge.limitCTA)&&Pe.upgrade.limitCTA.trim().length>0?Pe.upgrade.limitCTA:(null==Ce?void 0:Ce["pricing.upgrade"])||(null==Ce?void 0:Ce.upgrade)||"Upgrade",Bn=d((()=>{var e,t,n;return!!Te&&(!!ke&&(!pt.isLoading&&(!((null!==(t=null===(e=pt.data)||void 0===e?void 0:e.messages.length)&&void 0!==t?t:0)>1)&&(!!(null===(n=ke.icebreakers)||void 0===n?void 0:n.length)&&(!Ae&&!gn)))))}),[ke,Te,Ae,gn,pt.data,pt.isLoading]),Xn=d((()=>{if(Ge||Ze)return!1;const e=mn&&Ye.length>0&&Ye.every((e=>"finished"===e.status));return!(!ft.trim()&&!e)&&Ye.every((e=>"finished"===e.status||e.isInsertedAsRaw))}),[mn,Ge,Ze,ft,Ye]);u(oe,(()=>({onSubmit:Kn}))),c((()=>{Le(Bn)}),[Bn]),c((()=>{var e;if(i){const t=Array.from(We),n=null===(e=t[t.length-2].parts.find((e=>"text"===e.type)))||void 0===e?void 0:e.content;Kn(n,!0)}}),[i]),c((()=>{if(!Mt.current||!ne)return;const e=new ResizeObserver((e=>{for(const t of e)ne(t.contentRect.height)}));return e.observe(Mt.current),()=>{e.disconnect()}}),[ne]),c((()=>{if(!Ft)return;const e=Tt.current?`${Tt.current} `:"";gt(`${e}${Vt}`)}),[Vt,Ft]),c((()=>{if(!Lt.current)return;(()=>{if(!Lt.current)return;let e=Lt.current.scrollHeight>52;ft.includes("\n")||Ye.length?e=!0:ft.trim()||(e=!1),vt(e)})()}),[ft,Ye]),c((()=>{const e=Lt.current,t=Rt.current;if(!e||!t||ht||ft.includes("\n"))return void yt(!1);const n=window.getComputedStyle(e),s=`${n.fontStyle} ${n.fontVariant} ${n.fontWeight} ${n.fontSize} / ${n.lineHeight} ${n.fontFamily}`,o=document.createElement("span");Object.assign(o.style,{font:s,letterSpacing:n.letterSpacing,position:"absolute",visibility:"hidden",whiteSpace:"nowrap",top:"0",left:"0"}),o.textContent=ft||bn,document.body.appendChild(o);const i=o.offsetWidth;o.remove();const r=parseFloat(n.paddingLeft)||0,a=parseFloat(n.paddingRight)||0,l=e.clientWidth-r-a-t.offsetWidth;yt(i>l)}),[ft,ht,bn]);const Kn=(e,n=!1)=>t(void 0,void 0,void 0,(function*(){var t,s,o,i;let r=null;try{if(Ge||Ze)return;const a=Ye.filter((e=>"finished"===e.status&&!e.isInsertedAsRaw)),l=a.map((e=>e.documentId)).filter(Boolean),c=a.filter((e=>"image"===e.type)).map((e=>{const t=e.name.split(".").pop()||"";return{documentId:e.documentId,extension:t}})),d=null!=e?e:ft,u=null!==(s=null===(t=null==ke?void 0:ke.documentuploadtype)||void 0===t?void 0:t.startsWith("enduserupload"))&&void 0!==s&&s&&l.length>0;if(!d&&!u)return;Qe(""),st(""),qe(null),gt(""),De(!1),ze("fetching"),it(),at();const m=[...n?Array.from(We.slice(0,We.length-1)):Array.from(We),...n?[]:[{id:We.length+1,role:"user",parts:[{type:"text",content:d,isVisible:!0}],documentIds:u?l:[]}],{id:We.length+(n?0:2),role:"assistant",parts:[],documentIds:[]}];Je(m),at(),u&&nt([]);const p=K(we),f="undefined"!=typeof crypto&&"randomUUID"in crypto?crypto.randomUUID():`submission-${Date.now()}-${Math.random().toString(36).slice(2)}`;r=f,At.current=f,Pt.current=null,Dt.current=[];const g=yield fetch(`${process.env.NEXT_PUBLIC_PICKAXE_API2_URL}/response/submit`,Object.assign({method:"POST",body:JSON.stringify(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({origin:ve,pickaxeId:be,sessionId:ye,submissionId:f,senderType:Ie,value:d},u&&{documentIds:l}),xe&&{sender:xe}),Ke&&{studioSessionToken:Ke}),!Ke&&!xe&&{sender:X()}),je&&{portalId:je}),we&&{deploymentId:we}),p&&{metadata:p}),u&&c.length>0?{uploadedModelImages:c}:{})),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()})},un&&{credentials:"include"})),h=yield g.json();if(!h.success){if(h.limitData){const e=new Error(h.error||h.message||(null==Ce?void 0:Ce["failed-to-start-generation"])||"Failed to start generation");throw e.limitData=h.limitData,e}if(vn(h))return;throw new Error(h.error||h.message||(null==Ce?void 0:Ce["failed-to-start-generation"])||"Failed to start generation")}const v=null!==(o=h.submissionId)&&void 0!==o?o:f;r=v,At.current=v;const b=()=>Pt.current===v;if(b())return;fn&&Te&&ye&&Bt.current.add(ye);const y=Object.assign(Object.assign({},kn()),{message:d,documentIds:u?l:[],uploadedModelImages:u?c:[],hasUploadedDocuments:u,isHidden:n,metadata:null!=p?p:null});Ot?(Sn(),F(y)):Xt.current=y,ze("streaming"),$t.current=new AbortController;const x=m.length-1,I=[];let j=[...null!=lt?lt:[]],w=0,O=!1,k="";for(;!O;)try{const e=yield fetch(`${process.env.NEXT_PUBLIC_PICKAXE_API2_URL}/response/stream/${v}?index=${w}`,{signal:null===(i=$t.current)||void 0===i?void 0:i.signal,headers:{"Cache-Control":"no-cache",Connection:"keep-alive"}});if(!e.body)throw new Error("No response body");const t=e.body.getReader();Ut.current=t;const n=new TextDecoder,s=N({onEvent:e=>{var t,n;if(b())O=!0;else if(e.event&&"ping"!==e.event&&w++,"stop"!==e.event){if("error"===e.event){const t=JSON.parse(e.data);if(t.limitData)return qe(t.limitData),Qe(""),void(O=!0);const n=t.error||t.message||(null==Ce?void 0:Ce["something-went-wrong"])||"Something went wrong.";return vn(t)||Qe(n),void(O=!0)}if("delta"===e.event){const s=JSON.parse(e.data);if("data-error"===s.type&&se){const e=s.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*['"]([^'"]+)['"]/),s=e.match(/['"]name['"]\s*:\s*['"]([^'"]+)['"]/);if(t&&t[1]&&n&&n[1]&&s&&s[1])throw O=!0,se({provider:"smithery",smitheryId:t[1],serverId:n[1],name:s[1]}),new Error("STOP_STREAM")}else if(n){const t=e.match(/['"]toolkitSlug['"]\s*:\s*['"]([^'"]+)['"]/),n=e.match(/['"]serverId['"]\s*:\s*['"]([^'"]+)['"]/),s=e.match(/['"]name['"]\s*:\s*['"]([^'"]+)['"]/);if(t&&t[1]&&n&&n[1]&&s&&s[1])throw O=!0,se({provider:"composio",toolkitSlug:t[1],serverId:n[1],name:s[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 O=!0,se({provider:"smithery",smitheryId:t.qualifiedName,serverId:t.serverId,name:t.name}),new Error("STOP_STREAM");if("unauthorized_composio"===t.type&&t.toolkitSlug&&t.serverId&&t.name)throw O=!0,se({provider:"composio",toolkitSlug:t.toolkitSlug,serverId:t.serverId,name:t.name}),new Error("STOP_STREAM")}}else if("text-start"===s.type)k="",I.push({type:"text",content:"",isVisible:null===(t=s.isVisible)||void 0===t||t});else if("text-delta"===s.type)k+=s.delta,I[I.length-1].content=k;else if("text-end"===s.type)k="";else if("reasoning-start"===s.type)k="",I.push({type:"reasoning",content:"",isVisible:null===(n=s.isVisible)||void 0===n||n});else if("reasoning-delta"===s.type)k+=s.delta,I[I.length-1].content=k;else if("reasoning-end"===s.type)k="";else if(s.type.startsWith("data-")){const e=s;I.push({type:e.type,content:JSON.stringify(e.data),isVisible:!0})}Dt.current=z(I),Je([...m.slice(0,x),Object.assign(Object.assign({},m[m.length-1]),{id:We.length+1,role:"assistant",parts:I})])}else if("artifact_created"===e.event){const t=JSON.parse(e.data);j=j.filter((e=>!(e.id===t.id&&e.version===t.version))),j.push(Object.assign(Object.assign({},t),{content:"",status:"streaming"})),dt([...j]),ct.startsWith("inline")||ut({id:t.id,version:t.version})}else if("artifact_updated"===e.event){const t=JSON.parse(e.data);j=j.filter((e=>!(e.id===t.id&&e.version===t.version))),j.push(Object.assign(Object.assign({},t),{content:"",status:"updating"})),dt(j),ct.startsWith("inline")||ut({id:t.id,version:t.version})}else if("artifact_rewrite"===e.event){const t=JSON.parse(e.data);j=j.filter((e=>!(e.id===t.id&&e.version===t.version))),j.push(Object.assign(Object.assign({},t),{content:"",status:"streaming"})),dt(j),ct.startsWith("inline")||ut({id:t.id,version:t.version})}else if("artifact_content"===e.event){const t=JSON.parse(e.data),n=t.token.replace(/\u200B/g,"");j=j.map((e=>e.id===t.id&&e.version===t.version?Object.assign(Object.assign({},e),{content:e.content+n,status:"streaming"}):e)),dt(j)}else if("artifact_finished"===e.event){const t=JSON.parse(e.data);dt(j.map((e=>e.id===t.id?Object.assign(Object.assign({},e),{status:"finished"}):e)))}else if("error"===e.event){const t=JSON.parse(e.data);if(t.limitData)return qe(t.limitData),Qe(""),void(O=!0);const n=t.error||t.message||(null==Ce?void 0:Ce["something-went-wrong-try-again"])||"Something went wrong, please try again.";if(vn(t))return void(O=!0);Qe(n)}else"stop"===e.event&&(O=!0)}else O=!0}});for(;;){if(b()){O=!0,t.cancel().catch((()=>{}));break}const{value:e,done:o}=yield t.read();if(b()){O=!0,t.cancel().catch((()=>{}));break}if(o)break;s.feed(n.decode(e))}O||b()||(yield new Promise((e=>setTimeout(e,1e3))))}catch(e){if("STOP_STREAM"===e.message||q(e)||b())return void(O=!0);console.warn("Stream connection lost, retrying...",e),yield new Promise((e=>setTimeout(e,1e3)))}null==Xe||Xe(ye)}catch(e){if(q(e))return;if(e.limitData)qe(e.limitData),Qe("");else{let t=D(e)||"";t&&!t.includes("Unexpected token 'A',")||(t=(null==Ce?void 0:Ce["high-traffic-try-again-later"])||"Oops! We're experiencing high traffic at the moment. Please try again later."),vn(t)||Qe(t)}}finally{const e=!r||At.current===r;at(),e&&(ze("idle"),rt(),Ut.current=null),r&&e&&(At.current=null,Dt.current=[]),yield xn()}}));return hn?null:n("div",Object.assign({className:M("flex w-full flex-shrink-0 flex-col items-center",!gn&&"px-4 pb-8"),dir:Ue?"rtl":"ltr"},{children:s("div",Object.assign({className:"flex w-full max-w-[800px] flex-col"},{children:[s("div",Object.assign({ref:Mt,className:M("relative flex flex-col w-full justify-end gap-y-3 py-[3px]","block"===Se.formFieldStyle&&"shadow"),style:Object.assign(Object.assign({},an),{maxHeight:`${Kt}px`,overflowY:"auto"})},{children:[Rn&&s("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:an.backgroundColor?`${an.backgroundColor}E6`:void 0,borderColor:Ne.text+"20",color:Ne.text,borderTopRightRadius:Se.cornerRadius+"px",borderTopLeftRadius:Se.cornerRadius+"px"}},{children:[n("div",Object.assign({className:"flex items-center gap-2 text-sm font-medium"},{children:s("span",{children:[Un.toLocaleString()," ",wn?(null==Ce?void 0:Ce.credits)||"Credits":(null==Ce?void 0:Ce.uses)||"Uses"," ",(null==Ce?void 0:Ce.remaining)||"remaining"]})})),s("div",Object.assign({className:"flex items-center gap-3"},{children:[n("button",Object.assign({className:"rounded-md px-3 py-1.5 text-xs font-semibold transition-opacity hover:opacity-90",style:{backgroundColor:Ne.accent,color:Ne.accentText},onClick:e=>{if(e.preventDefault(),e.stopPropagation(),Mn)return void window.open(Mn,"_blank","noopener,noreferrer");const t=$({baseUrl:jt,accessGroupId:null==Pe?void 0:Pe.accessGroupId});t&&(B()?window.open(t):location.href=t)}},{children:$n})),n("button",Object.assign({className:"flex h-6 w-6 items-center justify-center rounded-full opacity-60 transition-opacity hover:opacity-100",onClick:()=>Nt(!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"})}))}))]}))]})),!Ge&&Ye.length>0&&n(U,{className:"p-4 pb-0",isDisabled:Ge}),s("div",Object.assign({className:"relative flex w-full flex-col"},{children:[Ft&&s("div",Object.assign({className:"absolute left-4 top-1/2 flex -translate-y-1/2 select-none items-center gap-x-2"},{children:[n("span",{className:"h-2 w-2 animate-pulse rounded-full bg-c-secondary",style:{backgroundColor:null!==(he=Ne.accent)&&void 0!==he?he:"#ff0000"}}),n("span",Object.assign({className:"text-sm text-c-secondary font-semilight",style:{color:Ne.text+"90"}},{children:(null==Ce?void 0:Ce.listening)||"Listening..."}))]})),n(A,Object.assign({ref:Lt,className:M(rn.i1,"py-3.5 max-h-60 px-4 w-full border-transparent bg-transparent",!ft.trim()&&!ft.includes("\n")&&"overflow-hidden text-ellipsis whitespace-nowrap placeholder:whitespace-normal placeholder:overflow-visible",Ue?"text-right":"text-left",yn&&"mb-12",Ft&&"text-transparent"),value:ft,placeholder:bn,onChange:e=>{gt(e)},onKeyDown:e=>{_e||zt||"Enter"===e.key&&(e.shiftKey||(e.preventDefault(),Ze||Ge||Kn()))},onPaste:e=>t(void 0,void 0,void 0,(function*(){const t=Array.from(e.clipboardData.files||[]);if(t.length>0){if(!mn)return;e.preventDefault(),De(!1),yield tt(t)}}))},Q&&{onFocus:Q},te&&{onBlur:te},{dir:Ue?"rtl":"ltr"})),n("div",Object.assign({ref:Rt,className:M("flex items-center gap-2 absolute right-0 z-2 transition-all duration-200 ease-in-out",yn?"bottom-0 mb-2.5":"top-1/2 -translate-y-1/2"),style:Object.assign(Object.assign({},!yn&&an.backgroundColor&&{backgroundColor:an.backgroundColor}),{borderTopRightRadius:Se.cornerRadius+"px",borderBottomRightRadius:Se.cornerRadius+"px"})},{children:Ge?n("button",Object.assign({className:"flex h-8 w-8 items-center mr-2 justify-center rounded-full outline-none transition-colors duration-200 ease-in-out",onClick:()=>{const e=At.current;e&&(Pt.current=e,(e=>{t(void 0,void 0,void 0,(function*(){if(!(e=null!=e?e:At.current))return;const t=z(Dt.current);try{yield fetch(`${process.env.NEXT_PUBLIC_PICKAXE_API2_URL}/response/cancel/${e}`,Object.assign({method:"POST",headers:Object.assign(Object.assign({"Content-Type":"application/json"},(!process.env.NODE_ENV||"development"===process.env.NODE_ENV)&&Object.assign({},process.env.NEXT_PUBLIC_PICKAXE_SESSION_TOKEN&&{"x-pickaxe-session-token":process.env.NEXT_PUBLIC_PICKAXE_SESSION_TOKEN})),{"x-request-sent-at":(new Date).toISOString()}),body:JSON.stringify({outputMessageParts:t})},un&&{credentials:"include"}))}catch(e){console.warn("Failed to cancel submission",e)}}))})(e)),$t.current&&($t.current.abort(),$t.current=null),Ut.current&&(Ut.current.cancel().catch((()=>{})),Ut.current=null),ze("idle")},style:{backgroundColor:Ne.accent,color:Ne.accentText}},{children:n(T,{className:"h-4 w-4 shrink-0"})})):Ft?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:Jt,style:{backgroundColor:Ne.accent,color:Ne.accentText}},{children:n(T,{className:"h-4 w-4 shrink-0"})})):s(o,{children:[mn&&s("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:en?Ne.accent+"10":void 0,color:en?Ne.accent:Ne.accent+"80"},disabled:Ze||Ge,onClick:()=>{var e;return null===(e=_t.current)||void 0===e?void 0:e.click()}},tn,{children:[n("input",{id:"file-upload",ref:_t,type:"file",accept:[...O,...k,...S].join(", "),multiple:!0,hidden:!0,className:"hidden",onChange:e=>t(void 0,void 0,void 0,(function*(){De(!1),yield tt(Array.from(e.target.files||[])),e.target.value=""}))}),n(C,{className:"h-6 w-6 shrink-0"})]})),pn&&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:Ft?Ne.accent:sn?Ne.accent+"10":void 0,color:Ft?Ne.accentText:sn?Ne.accent:Ne.accent+"80"},disabled:Ze||Ge||Ht,onClick:()=>{Ft?Jt():(Tt.current=ft,Gt(Ee||"en-US"))}},on,{children:n(_,{className:"h-5 w-5 shrink-0"})})),n("button",Object.assign({className:"flex h-8 w-8 items-center mr-2 justify-center rounded-full outline-none transition-colors duration-200 ease-in-out disabled:cursor-default",style:{backgroundColor:Qt||Xn?Ne.accent:Ne.accent+"10",color:Qt||Xn?Ne.accentText:Ne.accent+"80"},disabled:!Xn,onClick:()=>Kn()},Yt,{children:n(E,{className:M("h-6 w-6 shrink-0",Ue&&"scale-x-[-1] transform")})}))]})}))]}))]})),et&&n(P,{error:et,className:"mt-3"})]}))}))}));te.displayName="Input";export{te as default};
|
|
1
|
+
import{__rest as e,__awaiter as t}from"../../../_virtual/_tslib.js";import{jsx as n,jsxs as s,Fragment as o}from"react/jsx-runtime";import{forwardRef as i,useState as r,useRef as a,useCallback as l,useEffect as c,useMemo as d,useImperativeHandle as u}from"react";import{usePickaxeContext as m}from"../../../hooks/pickaxe/usePickaxeContext.js";import{useResponseContext as p}from"../../../hooks/pickaxe/useResponseContext.js";import{useStyleInput as f}from"../../../hooks/studio/useStyleInput.js";import{useStyleFontSize as g}from"../../../hooks/studio/useStyleFontSize.js";import{useConversation as h}from"../../../hooks/pickaxe/useConversation.js";import{useDimensionContext as v}from"../../../hooks/pickaxe/useDimensionContext.js";import{useAuthContext as b}from"../Addons/Auth/hooks/useAuthContext.js";import{useDocument as y}from"../Addons/Document/hooks/useDocument.js";import{useScroll as x}from"../Addons/Scroll/hooks/useScroll.js";import{useArtifactContext as I}from"../Addons/Artifact/hooks/useArtifactContext.js";import{useHover as j}from"../../../hooks/core/useHover.js";import{useMediaQuery as w}from"../../../hooks/core/useMediaQuery.js";import{allowedFileMimeTypes as O,allowedImageMimeTypes as k,additionalAllowedFileExtensions as S}from"../../../common/documents.js";import{createParser as N}from"eventsource-parser";import C from"../../Icons/attach-vertical.svg.js";import E from"../../Icons/arrow-right.svg.js";import _ from"../../Icons/microphone.svg.js";import U from"../../Icons/stop.svg.js";import T from"../Addons/Document/List.js";import A from"../../Core/Textarea.js";import P from"../../Core/ErrorAlert.js";import D from"../../../common/error.js";import{pickaxeApi2 as L}from"../../../common/api/pickaxe.js";import{getValidationFailure as R}from"../../../common/validation.js";import M from"../../../common/cn.js";import{buildUpgradeUrl as $,isInIframe as B,initializeEmbedUserId as X}from"../../../common/utils.js";import{getPickaxeConfigMetadata as K}from"../../../common/pickaxeConfig.js";import{fireDeploymentSessionInitializedWebhook as V,fireDeploymentFirstMessageSubmittedWebhook as F}from"../../../common/deploymentWebhooks.js";import{useStudio as H}from"../../../hooks/studio/useStudio.js";import{useSpeech as W}from"../../../hooks/pickaxe/useSpeech.js";import{STUDIO_INFINITY_VALUE as G}from"../common/PickaxeCommon.js";const J=e=>"string"==typeof e&&e.trim().length>0,z=e=>e.map((e=>Object.assign({},e))),q=e=>e instanceof Error&&("AbortError"===e.name||"BodyStreamBuffer was aborted"===e.message),Q=(e,t)=>{if(e&&"object"==typeof e)return e[t]},Y=(e,t)=>{const n=Q(e,t);return J(n)?n:null},Z=e=>{const t=Number(e);return Number.isFinite(t)?t:void 0},ee=({studioUser:e,deploymentId:t,portalId:n})=>{var s,o;const i=Array.isArray(Q(e,"uses"))?Q(e,"uses"):[],r=(({deploymentId:e,portalId:t})=>J(e)?{type:"deployment",id:e}:J(t)?{type:"portal",id:t}:null)({deploymentId:t,portalId:n});if(!r)return{scope:r,record:null};const a=null!==(o=null!==(s=i.find((e=>e.id===r.id&&e.type===r.type)))&&void 0!==s?s:i.find((e=>e.id===r.id)))&&void 0!==o?o:null;return{scope:r,record:a}},te=i((({resubmitPrompt:i,onFocus:Q,onBlur:te,onInputHeightChange:ne,initSmitheryAuthData:se},oe)=>{var ie,re,ae,le,ce,de,ue,me,pe,fe,ge,he;const{origin:ve,pickaxeId:be,sessionId:ye,sender:xe,senderType:Ie,portalId:je,deploymentId:we,deploymentType:Oe,pickaxe:ke,styles:Se,colors:Ne,translations:Ce,locale:Ee,forceMobile:_e,isNewChat:Ue,isRtl:Te,isShowFeedbackMessage:Ae,accessGroup:Pe,setIsNewChat:De,setIsShowIceBreaker:Le,setValidationStatus:Re,setValidationUpgradeGroups:Me,setValidationUpgradeUrl:$e,setAccessGroup:Be,onGenerateComplete:Xe}=m(),{token:Ke,isLoggedOut:Ve,isSent:Fe,isPricingAuth:He}=b(),{messages:We,isGenerating:Ge,setMessages:Je,setStatus:ze,setLimitData:qe,setError:Qe}=p(),{documents:Ye,isUploading:Ze,documentError:et,onFileUpload:tt,setDocuments:nt,setDocumentError:st}=y(),{studio:ot}=H(),{scrollStartSession:it,scrollEndSession:rt,scrollToBottom:at}=x({auto:!0}),{artifacts:lt,currentPopupType:ct,setArtifacts:dt,setCurrentArtifact:ut}=I(),{height:mt}=v(),pt=h(),[ft,gt]=r(""),[ht,vt]=r(!1),[bt,yt]=r(!1),[xt,It]=r(null),[jt,wt]=r(null),[Ot,kt]=r(!1),[St,Nt]=r(!1),[Ct,Et]=r(0),_t=a(null),Ut=a(""),Tt=a(null),At=a(null),Pt=a(null),Dt=a([]),Lt=a(null),Rt=a(null),Mt=a(null),$t=a(null),Bt=a(new Set),Xt=a(null),Kt=Math.max(.4*mt,100),{speechTranscript:Vt,isSpeechListening:Ft,isSpeechProcessing:Ht,isSpeechSupported:Wt,onStartListening:Gt,onStopListening:Jt}=W(),[zt]=w("(max-width: 480px)"),qt=j(),{isHover:Qt}=qt,Yt=e(qt,["isHover"]),Zt=j(),{isHover:en}=Zt,tn=e(Zt,["isHover"]),nn=j(),{isHover:sn}=nn,on=e(nn,["isHover"]),rn=g(),an=f(),ln="undefined"!=typeof window?window.location.hostname:"",cn="undefined"!=typeof window?window.location.href:"",dn="undefined"!=typeof window&&window.self!==window.top,un=ln.includes("pickaxe.co")&&!cn.includes("https://studio.pickaxe.co/_embed")&&!dn,mn=null!==(re=null===(ie=null==ke?void 0:ke.documentuploadtype)||void 0===ie?void 0:ie.startsWith("enduserupload"))&&void 0!==re&&re,pn=Wt&&(null==ke?void 0:ke.enablevoicetotext),fn=J(we),gn="chat-input"===Oe&&Ue&&!Fe,hn="chat-input"===Oe&&He&&Ve&&Fe,vn=l((e=>{const t=R(e);return!!t&&(Qe(""),qe(null),Re(t.status),Be(t.accessGroup),Me(t.upgradeGroups),$e(t.upgradeUrl),!0)}),[Qe,qe,Re,Me,$e,Be]),bn=null!==(ae=null==ke?void 0:ke.placeholdertext)&&void 0!==ae?ae:Te?"بماذا تريد أن تتحدث؟":(null==Ce?void 0:Ce["what-do-you-want-to-talk-about"])||"What do you want to talk about?",yn=ht||bt,xn=l((()=>t(void 0,void 0,void 0,(function*(){kt(!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==ke?void 0:ke.studioid},Ke?{studioSessionToken:Ke}:xe?{sender:xe}:{sender:X()}))},(!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}})),un&&{credentials:"include"})),t=yield e.json();(null==t?void 0:t.studioUser)&&(It(t.studioUser),wt(t.url))}catch(e){console.error("Failed to fetch studio user:",e)}finally{kt(!0)}}))),[un,null==ke?void 0:ke.studioid,xe,Ke]);c((()=>{xn()}),[xn]);const In=Number(null!==(le=null==Pe?void 0:Pe.limit)&&void 0!==le?le:0),jn="string"==typeof(null==Pe?void 0:Pe.limitInterval)?Pe.limitInterval:null,wn=!!(null==ot?void 0:ot.data.usage)&&ot.data.usage.isCredits,On=d((()=>ee({studioUser:xt,deploymentId:we,portalId:je})),[we,je,xt]);c((()=>{fn&&Ue&&ye&&Bt.current.add(ye)}),[Ue,ye,fn]);const kn=l((()=>{var e,t,n;return{studioId:null==ke?void 0:ke.studioid,userEmail:Y(xt,"email"),userId:null!==(e=Y(xt,"userId"))&&void 0!==e?e:Y(xt,"userid"),sessionId:ye,deploymentId:we,deploymentType:Oe,portalId:je,accessGroupId:null!==(t=null==Pe?void 0:Pe.accessGroupId)&&void 0!==t?t:null,pickaxeId:be,sender:xe,senderType:Ie,origin:ve,metadata:null!==(n=K(we))&&void 0!==n?n:null}}),[null==Pe?void 0:Pe.accessGroupId,we,Oe,ve,null==ke?void 0:ke.studioid,be,je,xe,Ie,ye,xt]),Sn=l((()=>!!(fn&&Ot&&ye)&&(!!Bt.current.has(ye)&&(V(kn()),Bt.current.delete(ye),!0))),[kn,Ot,ye,fn]);c((()=>{if(!Ot||!ye)return;Sn();const e=Xt.current;(null==e?void 0:e.sessionId)===ye&&(F(Object.assign(Object.assign(Object.assign({},e),kn()),{message:e.message,documentIds:e.documentIds,uploadedModelImages:e.uploadedModelImages,hasUploadedDocuments:e.hasUploadedDocuments,isHidden:e.isHidden})),Xt.current=null)}),[Sn,kn,Ot,ye]);const Nn={currentUses:Z(null==xt?void 0:xt.currentUses),extraUses:Z(null==xt?void 0:xt.extraUses)},Cn=On.scope?{currentUses:null!==(de=Z(null===(ce=On.record)||void 0===ce?void 0:ce.currentUses))&&void 0!==de?de:0,extraUses:null!==(me=Z(null===(ue=On.record)||void 0===ue?void 0:ue.extraUses))&&void 0!==me?me:0}:{currentUses:0,extraUses:0},En=Y(xt,"type"),_n="guest"===En||!En&&Ve?Cn:Nn;c((()=>{let e=!0;return t(void 0,void 0,void 0,(function*(){var t;if(wn&&(null===(t=null==ot?void 0:ot.data)||void 0===t?void 0:t.workspaceId))try{const t=yield L.get(`/cost_per_run?workspaceId=${ot.data.workspaceId}`,{withCredentials:!1});e&&Et(1e4*(Number(t.data.costPerRun)||0))}catch(t){console.error("Failed to fetch average cost per run:",t),e&&Et(0)}else e&&Et(0)})),()=>{e=!1}}),[wn,null===(pe=null==ot?void 0:ot.data)||void 0===pe?void 0:pe.workspaceId]);const Un=(({currentUses:e,extraUses:t,limit:n,limitInterval:s})=>{const o=Number(null!=e?e:0),i=Number(null!=t?t:0);return n===G||i===G?G:"one_time"===s?Math.max(0,i-o):(console.log("Calculating remaining balance with limit:",n,"currentUses:",o,"extraUses:",i),Math.max(0,n-o)+i)})({currentUses:_n.currentUses,extraUses:_n.extraUses,limit:In,limitInterval:jn}),Tn=Un===G?G:Math.max(0,Math.ceil(Un)),An=(({extraUses:e,limit:t,limitInterval:n})=>{const s=Number(null!=e?e:0);return t===G||s===G?G:"one_time"===n?Math.max(0,s):Math.max(0,t)+Math.max(0,s)})({extraUses:_n.extraUses,limit:In,limitInterval:jn}),Pn=An===G?G:Math.ceil(.05*An),Dn=wn?Math.ceil(5*Ct):5,Ln=Pn===G?G:Math.max(Pn,Dn),Rn=d((()=>!!xt&&(!St&&(Tn!==G&&Tn<=Ln))),[St,Ln,Tn,xt]),Mn=(null===(fe=null==Pe?void 0:Pe.upgrade)||void 0===fe?void 0:fe.isLinkToCustomURL)&&"string"==typeof Pe.upgrade.limitLink&&Pe.upgrade.limitLink.trim().length>0?Pe.upgrade.limitLink.trim():null,$n=Mn&&"string"==typeof(null===(ge=null==Pe?void 0:Pe.upgrade)||void 0===ge?void 0:ge.limitCTA)&&Pe.upgrade.limitCTA.trim().length>0?Pe.upgrade.limitCTA:(null==Ce?void 0:Ce["pricing.upgrade"])||(null==Ce?void 0:Ce.upgrade)||"Upgrade",Bn=d((()=>{var e,t,n;return!!Ue&&(!!ke&&(!pt.isLoading&&(!((null!==(t=null===(e=pt.data)||void 0===e?void 0:e.messages.length)&&void 0!==t?t:0)>1)&&(!!(null===(n=ke.icebreakers)||void 0===n?void 0:n.length)&&(!Ae&&!gn)))))}),[ke,Ue,Ae,gn,pt.data,pt.isLoading]),Xn=d((()=>{if(Ge||Ze)return!1;const e=mn&&Ye.length>0&&Ye.every((e=>"finished"===e.status));return!(!ft.trim()&&!e)&&Ye.every((e=>"finished"===e.status||e.isInsertedAsRaw))}),[mn,Ge,Ze,ft,Ye]);u(oe,(()=>({onSubmit:Kn}))),c((()=>{Le(Bn)}),[Bn]),c((()=>{var e;if(i){const t=Array.from(We),n=null===(e=t[t.length-2].parts.find((e=>"text"===e.type)))||void 0===e?void 0:e.content;Kn(n,!0)}}),[i]),c((()=>{if(!Mt.current||!ne)return;const e=new ResizeObserver((e=>{for(const t of e)ne(t.contentRect.height)}));return e.observe(Mt.current),()=>{e.disconnect()}}),[ne]),c((()=>{if(!Ft)return;const e=Ut.current?`${Ut.current} `:"";gt(`${e}${Vt}`)}),[Vt,Ft]),c((()=>{if(!Lt.current)return;(()=>{if(!Lt.current)return;let e=Lt.current.scrollHeight>52;ft.includes("\n")||Ye.length?e=!0:ft.trim()||(e=!1),vt(e)})()}),[ft,Ye]),c((()=>{const e=Lt.current,t=Rt.current;if(!e||!t||ht||ft.includes("\n"))return void yt(!1);const n=window.getComputedStyle(e),s=`${n.fontStyle} ${n.fontVariant} ${n.fontWeight} ${n.fontSize} / ${n.lineHeight} ${n.fontFamily}`,o=document.createElement("span");Object.assign(o.style,{font:s,letterSpacing:n.letterSpacing,position:"absolute",visibility:"hidden",whiteSpace:"nowrap",top:"0",left:"0"}),o.textContent=ft||bn,document.body.appendChild(o);const i=o.offsetWidth;o.remove();const r=parseFloat(n.paddingLeft)||0,a=parseFloat(n.paddingRight)||0,l=e.clientWidth-r-a-t.offsetWidth;yt(i>l)}),[ft,ht,bn]);const Kn=(e,n=!1)=>t(void 0,void 0,void 0,(function*(){var t,s,o,i;let r=null;try{if(Ge||Ze)return;const a=Ye.filter((e=>"finished"===e.status&&!e.isInsertedAsRaw)),l=a.map((e=>e.documentId)).filter(Boolean),c=a.filter((e=>"image"===e.type)).map((e=>{const t=e.name.split(".").pop()||"";return{documentId:e.documentId,extension:t}})),d=null!=e?e:ft,u=null!==(s=null===(t=null==ke?void 0:ke.documentuploadtype)||void 0===t?void 0:t.startsWith("enduserupload"))&&void 0!==s&&s&&l.length>0;if(!d&&!u)return;Qe(""),st(""),qe(null),gt(""),De(!1),ze("fetching"),it(),at();const m=[...n?Array.from(We.slice(0,We.length-1)):Array.from(We),...n?[]:[{id:We.length+1,role:"user",parts:[{type:"text",content:d,isVisible:!0}],documentIds:u?l:[]}],{id:We.length+(n?0:2),role:"assistant",parts:[],documentIds:[]}];Je(m),at(),u&&nt([]);const p=K(we),f="undefined"!=typeof crypto&&"randomUUID"in crypto?crypto.randomUUID():`submission-${Date.now()}-${Math.random().toString(36).slice(2)}`;r=f,At.current=f,Pt.current=null,Dt.current=[];const g=yield fetch(`${process.env.NEXT_PUBLIC_PICKAXE_API2_URL}/response/submit`,Object.assign({method:"POST",body:JSON.stringify(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({origin:ve,pickaxeId:be,sessionId:ye,submissionId:f,senderType:Ie,value:d},u&&{documentIds:l}),xe&&{sender:xe}),Ke&&{studioSessionToken:Ke}),!Ke&&!xe&&{sender:X()}),je&&{portalId:je}),we&&{deploymentId:we}),p&&{metadata:p}),u&&c.length>0?{uploadedModelImages:c}:{})),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()})},un&&{credentials:"include"})),h=yield g.json();if(!h.success){if(h.limitData){const e=new Error(h.error||h.message||(null==Ce?void 0:Ce["failed-to-start-generation"])||"Failed to start generation");throw e.limitData=h.limitData,e}if(vn(h))return;throw new Error(h.error||h.message||(null==Ce?void 0:Ce["failed-to-start-generation"])||"Failed to start generation")}const v=null!==(o=h.submissionId)&&void 0!==o?o:f;r=v,At.current=v;const b=()=>Pt.current===v;if(b())return;fn&&Ue&&ye&&Bt.current.add(ye);const y=Object.assign(Object.assign({},kn()),{message:d,documentIds:u?l:[],uploadedModelImages:u?c:[],hasUploadedDocuments:u,isHidden:n,metadata:null!=p?p:null});Ot?(Sn(),F(y)):Xt.current=y,ze("streaming"),$t.current=new AbortController;const x=m.length-1,I=[];let j=[...null!=lt?lt:[]],w=0,O=!1,k="";for(;!O;)try{const e=yield fetch(`${process.env.NEXT_PUBLIC_PICKAXE_API2_URL}/response/stream/${v}?index=${w}`,{signal:null===(i=$t.current)||void 0===i?void 0:i.signal,headers:{"Cache-Control":"no-cache",Connection:"keep-alive"}});if(!e.body)throw new Error("No response body");const t=e.body.getReader();Tt.current=t;const n=new TextDecoder,s=N({onEvent:e=>{var t,n;if(b())O=!0;else if(e.event&&"ping"!==e.event&&w++,"stop"!==e.event){if("error"===e.event){const t=JSON.parse(e.data);if(t.limitData)return qe(t.limitData),Qe(""),void(O=!0);const n=t.error||t.message||(null==Ce?void 0:Ce["something-went-wrong"])||"Something went wrong.";return vn(t)||Qe(n),void(O=!0)}if("delta"===e.event){const s=JSON.parse(e.data);if("data-error"===s.type&&se){const e=s.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*['"]([^'"]+)['"]/),s=e.match(/['"]name['"]\s*:\s*['"]([^'"]+)['"]/);if(t&&t[1]&&n&&n[1]&&s&&s[1])throw O=!0,se({provider:"smithery",smitheryId:t[1],serverId:n[1],name:s[1]}),new Error("STOP_STREAM")}else if(n){const t=e.match(/['"]toolkitSlug['"]\s*:\s*['"]([^'"]+)['"]/),n=e.match(/['"]serverId['"]\s*:\s*['"]([^'"]+)['"]/),s=e.match(/['"]name['"]\s*:\s*['"]([^'"]+)['"]/);if(t&&t[1]&&n&&n[1]&&s&&s[1])throw O=!0,se({provider:"composio",toolkitSlug:t[1],serverId:n[1],name:s[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 O=!0,se({provider:"smithery",smitheryId:t.qualifiedName,serverId:t.serverId,name:t.name}),new Error("STOP_STREAM");if("unauthorized_composio"===t.type&&t.toolkitSlug&&t.serverId&&t.name)throw O=!0,se({provider:"composio",toolkitSlug:t.toolkitSlug,serverId:t.serverId,name:t.name}),new Error("STOP_STREAM")}}else if("text-start"===s.type)k="",I.push({type:"text",content:"",isVisible:null===(t=s.isVisible)||void 0===t||t});else if("text-delta"===s.type)k+=s.delta,I[I.length-1].content=k;else if("text-end"===s.type)k="";else if("reasoning-start"===s.type)k="",I.push({type:"reasoning",content:"",isVisible:null===(n=s.isVisible)||void 0===n||n});else if("reasoning-delta"===s.type)k+=s.delta,I[I.length-1].content=k;else if("reasoning-end"===s.type)k="";else if(s.type.startsWith("data-")){const e=s;I.push({type:e.type,content:JSON.stringify(e.data),isVisible:!0})}Dt.current=z(I),Je([...m.slice(0,x),Object.assign(Object.assign({},m[m.length-1]),{id:We.length+1,role:"assistant",parts:I})])}else if("artifact_created"===e.event){const t=JSON.parse(e.data);j=j.filter((e=>!(e.id===t.id&&e.version===t.version))),j.push(Object.assign(Object.assign({},t),{content:"",status:"streaming"})),dt([...j]),ct.startsWith("inline")||ut({id:t.id,version:t.version})}else if("artifact_updated"===e.event){const t=JSON.parse(e.data);j=j.filter((e=>!(e.id===t.id&&e.version===t.version))),j.push(Object.assign(Object.assign({},t),{content:"",status:"updating"})),dt(j),ct.startsWith("inline")||ut({id:t.id,version:t.version})}else if("artifact_rewrite"===e.event){const t=JSON.parse(e.data);j=j.filter((e=>!(e.id===t.id&&e.version===t.version))),j.push(Object.assign(Object.assign({},t),{content:"",status:"streaming"})),dt(j),ct.startsWith("inline")||ut({id:t.id,version:t.version})}else if("artifact_content"===e.event){const t=JSON.parse(e.data),n=t.token.replace(/\u200B/g,"");j=j.map((e=>e.id===t.id&&e.version===t.version?Object.assign(Object.assign({},e),{content:e.content+n,status:"streaming"}):e)),dt(j)}else if("artifact_finished"===e.event){const t=JSON.parse(e.data);dt(j.map((e=>e.id===t.id?Object.assign(Object.assign({},e),{status:"finished"}):e)))}else if("error"===e.event){const t=JSON.parse(e.data);if(t.limitData)return qe(t.limitData),Qe(""),void(O=!0);const n=t.error||t.message||(null==Ce?void 0:Ce["something-went-wrong-try-again"])||"Something went wrong, please try again.";if(vn(t))return void(O=!0);Qe(n)}else"stop"===e.event&&(O=!0)}else O=!0}});for(;;){if(b()){O=!0,t.cancel().catch((()=>{}));break}const{value:e,done:o}=yield t.read();if(b()){O=!0,t.cancel().catch((()=>{}));break}if(o)break;s.feed(n.decode(e))}O||b()||(yield new Promise((e=>setTimeout(e,1e3))))}catch(e){if("STOP_STREAM"===e.message||q(e)||b())return void(O=!0);console.warn("Stream connection lost, retrying...",e),yield new Promise((e=>setTimeout(e,1e3)))}null==Xe||Xe(ye)}catch(e){if(q(e))return;if(e.limitData)qe(e.limitData),Qe("");else{let t=D(e)||"";t&&!t.includes("Unexpected token 'A',")||(t=(null==Ce?void 0:Ce["high-traffic-try-again-later"])||"Oops! We're experiencing high traffic at the moment. Please try again later."),vn(t)||Qe(t)}}finally{const e=!r||At.current===r;at(),e&&(ze("idle"),rt(),Tt.current=null),r&&e&&(At.current=null,Dt.current=[]),yield xn()}}));return hn?null:n("div",Object.assign({className:M("flex w-full flex-shrink-0 flex-col items-center",!gn&&"px-4 pb-8"),dir:Te?"rtl":"ltr"},{children:s("div",Object.assign({className:"flex w-full max-w-[800px] flex-col"},{children:[s("div",Object.assign({ref:Mt,className:M("relative flex flex-col w-full justify-end gap-y-3 py-[3px]","block"===Se.formFieldStyle&&"shadow"),style:Object.assign(Object.assign({},an),{maxHeight:`${Kt}px`,overflowY:"auto"})},{children:[Rn&&s("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:an.backgroundColor?`${an.backgroundColor}E6`:void 0,borderColor:Ne.text+"20",color:Ne.text,borderTopRightRadius:Se.cornerRadius+"px",borderTopLeftRadius:Se.cornerRadius+"px"}},{children:[n("div",Object.assign({className:"flex items-center gap-2 text-sm font-medium"},{children:s("span",{children:[Tn.toLocaleString()," ",wn?(null==Ce?void 0:Ce.credits)||"Credits":(null==Ce?void 0:Ce.uses)||"Uses"," ",(null==Ce?void 0:Ce.remaining)||"remaining"]})})),s("div",Object.assign({className:"flex items-center gap-3"},{children:[n("button",Object.assign({className:"rounded-md px-3 py-1.5 text-xs font-semibold transition-opacity hover:opacity-90",style:{backgroundColor:Ne.accent,color:Ne.accentText},onClick:e=>{if(e.preventDefault(),e.stopPropagation(),Mn)return void window.open(Mn,"_blank","noopener,noreferrer");const t=$({baseUrl:jt,accessGroupId:null==Pe?void 0:Pe.accessGroupId,redirectUrl:document.URL});t&&(B()?window.open(t):location.href=t)}},{children:$n})),n("button",Object.assign({className:"flex h-6 w-6 items-center justify-center rounded-full opacity-60 transition-opacity hover:opacity-100",onClick:()=>Nt(!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"})}))}))]}))]})),!Ge&&Ye.length>0&&n(T,{className:"p-4 pb-0",isDisabled:Ge}),s("div",Object.assign({className:"relative flex w-full flex-col"},{children:[Ft&&s("div",Object.assign({className:"absolute left-4 top-1/2 flex -translate-y-1/2 select-none items-center gap-x-2"},{children:[n("span",{className:"h-2 w-2 animate-pulse rounded-full bg-c-secondary",style:{backgroundColor:null!==(he=Ne.accent)&&void 0!==he?he:"#ff0000"}}),n("span",Object.assign({className:"text-sm text-c-secondary font-semilight",style:{color:Ne.text+"90"}},{children:(null==Ce?void 0:Ce.listening)||"Listening..."}))]})),n(A,Object.assign({ref:Lt,className:M(rn.i1,"py-3.5 max-h-60 px-4 w-full border-transparent bg-transparent",!ft.trim()&&!ft.includes("\n")&&"overflow-hidden text-ellipsis whitespace-nowrap placeholder:whitespace-normal placeholder:overflow-visible",Te?"text-right":"text-left",yn&&"mb-12",Ft&&"text-transparent"),value:ft,placeholder:bn,onChange:e=>{gt(e)},onKeyDown:e=>{_e||zt||"Enter"===e.key&&(e.shiftKey||(e.preventDefault(),Ze||Ge||Kn()))},onPaste:e=>t(void 0,void 0,void 0,(function*(){const t=Array.from(e.clipboardData.files||[]);if(t.length>0){if(!mn)return;e.preventDefault(),De(!1),yield tt(t)}}))},Q&&{onFocus:Q},te&&{onBlur:te},{dir:Te?"rtl":"ltr"})),n("div",Object.assign({ref:Rt,className:M("flex items-center gap-2 absolute right-0 z-2 transition-all duration-200 ease-in-out",yn?"bottom-0 mb-2.5":"top-1/2 -translate-y-1/2"),style:Object.assign(Object.assign({},!yn&&an.backgroundColor&&{backgroundColor:an.backgroundColor}),{borderTopRightRadius:Se.cornerRadius+"px",borderBottomRightRadius:Se.cornerRadius+"px"})},{children:Ge?n("button",Object.assign({className:"flex h-8 w-8 items-center mr-2 justify-center rounded-full outline-none transition-colors duration-200 ease-in-out",onClick:()=>{const e=At.current;e&&(Pt.current=e,(e=>{t(void 0,void 0,void 0,(function*(){if(!(e=null!=e?e:At.current))return;const t=z(Dt.current);try{yield fetch(`${process.env.NEXT_PUBLIC_PICKAXE_API2_URL}/response/cancel/${e}`,Object.assign({method:"POST",headers:Object.assign(Object.assign({"Content-Type":"application/json"},(!process.env.NODE_ENV||"development"===process.env.NODE_ENV)&&Object.assign({},process.env.NEXT_PUBLIC_PICKAXE_SESSION_TOKEN&&{"x-pickaxe-session-token":process.env.NEXT_PUBLIC_PICKAXE_SESSION_TOKEN})),{"x-request-sent-at":(new Date).toISOString()}),body:JSON.stringify({outputMessageParts:t})},un&&{credentials:"include"}))}catch(e){console.warn("Failed to cancel submission",e)}}))})(e)),$t.current&&($t.current.abort(),$t.current=null),Tt.current&&(Tt.current.cancel().catch((()=>{})),Tt.current=null),ze("idle")},style:{backgroundColor:Ne.accent,color:Ne.accentText}},{children:n(U,{className:"h-4 w-4 shrink-0"})})):Ft?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:Jt,style:{backgroundColor:Ne.accent,color:Ne.accentText}},{children:n(U,{className:"h-4 w-4 shrink-0"})})):s(o,{children:[mn&&s("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:en?Ne.accent+"10":void 0,color:en?Ne.accent:Ne.accent+"80"},disabled:Ze||Ge,onClick:()=>{var e;return null===(e=_t.current)||void 0===e?void 0:e.click()}},tn,{children:[n("input",{id:"file-upload",ref:_t,type:"file",accept:[...O,...k,...S].join(", "),multiple:!0,hidden:!0,className:"hidden",onChange:e=>t(void 0,void 0,void 0,(function*(){De(!1),yield tt(Array.from(e.target.files||[])),e.target.value=""}))}),n(C,{className:"h-6 w-6 shrink-0"})]})),pn&&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:Ft?Ne.accent:sn?Ne.accent+"10":void 0,color:Ft?Ne.accentText:sn?Ne.accent:Ne.accent+"80"},disabled:Ze||Ge||Ht,onClick:()=>{Ft?Jt():(Ut.current=ft,Gt(Ee||"en-US"))}},on,{children:n(_,{className:"h-5 w-5 shrink-0"})})),n("button",Object.assign({className:"flex h-8 w-8 items-center mr-2 justify-center rounded-full outline-none transition-colors duration-200 ease-in-out disabled:cursor-default",style:{backgroundColor:Qt||Xn?Ne.accent:Ne.accent+"10",color:Qt||Xn?Ne.accentText:Ne.accent+"80"},disabled:!Xn,onClick:()=>Kn()},Yt,{children:n(E,{className:M("h-6 w-6 shrink-0",Te&&"scale-x-[-1] transform")})}))]})}))]}))]})),et&&n(P,{error:et,className:"mt-3"})]}))}))}));te.displayName="Input";export{te as default};
|