@pickaxeproject/react 6.7.1 → 6.8.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1 +1 @@
1
- "use strict";function e(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}Object.defineProperty(exports,"__esModule",{value:!0});var t=e(require("axios"));const r=process.env.NEXT_PUBLIC_API_URL;if(!r)throw new Error("[px/react] NEXT_PUBLIC_API_URL is not defined");const o=process.env.NEXT_PUBLIC_API2_URL;if(!o)throw new Error("[px/react] NEXT_PUBLIC_API2_URL is not defined");t.default.create({baseURL:r});const s=t.default.create({baseURL:o});exports.api2=s;
1
+ "use strict";function e(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}Object.defineProperty(exports,"__esModule",{value:!0});var t=e(require("axios"));const r=process.env.NEXT_PUBLIC_API_URL;if(!r)throw new Error("[px/react] NEXT_PUBLIC_API_URL is not defined");const o=process.env.NEXT_PUBLIC_API2_URL;if(!o)throw new Error("[px/react] NEXT_PUBLIC_API2_URL is not defined");const s=t.default.create({baseURL:r}),n=t.default.create({baseURL:o});exports.api=s,exports.api2=n;
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e=require("react/jsx-runtime"),s=require("react"),t=require("../../../../hooks/pickaxe/usePickaxeContext.js"),a=require("../../../../hooks/studio/useStyleFontSize.js"),i=require("../../../../hooks/pickaxe/useResponseContext.js"),n=require("../../Addons/Artifact/hooks/useArtifact.js"),r=require("../../common/PickaxeMarkdown/index.js"),o=require("../../common/PickaxeIcon.js"),l=require("./Document.js"),c=require("../../common/PickaxeMessageActions.js"),d=require("../../common/PickaxeMessageParts/index.js"),u=require("../../../../common/cn.js"),x=require("../../../../common/isoMap.js"),m=require("franc-min"),f=require("../../common/SmitheryConnectView.js");function h(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}var p=h(require("remove-markdown"));exports.default=({index:h,message:j,smitheryData:g,resubmitPrompt:b,isLastMessage:w=!1})=>{var y,v;const{pickaxeId:k,pickaxe:O,styles:N,colors:q,misc:S,responsiveBy:C,disableHtml:I,disableJs:A,disableCss:P,isNewChat:R,isRtl:M}=t.usePickaxeContext(),{isGenerating:F}=i.useResponseContext(),{onLoadArtifact:H}=n.useArtifact(),[L,T]=s.useState(!1),[E,J]=s.useState([]),V=a.useStyleFontSize(),z=null!==(y=null==O?void 0:O.chaticon)&&void 0!==y?y:`https://cdn.mail.studio/chaticons/${k}.png`,B=w&&F,D=null==O?void 0:O.enablereadout;s.useEffect((()=>{if(!D||"assistant"!==j.role)return;const e=()=>{const e=window.speechSynthesis.getVoices();e.length>0&&J(e)};return e(),window.speechSynthesis.onvoiceschanged=e,()=>{window.speechSynthesis.onvoiceschanged=null}}),[D,j.role]),s.useEffect((()=>()=>{L&&window.speechSynthesis.cancel()}),[L]);const G=()=>{if(L)return window.speechSynthesis.cancel(),void T(!1);const e=j.parts.filter((e=>"text"===e.type)).map((e=>e.content)).join(" ");if(!e)return;const s=p.default(e,{stripListLeaders:!0,listUnicodeChar:"",gfm:!0,useImgAltText:!1}),t=m.franc(s),a=x.convertToIso1(t);window.speechSynthesis.cancel();const i=new SpeechSynthesisUtterance(s),n=E.find((e=>e.lang.startsWith(a)&&e.name.includes("Google")))||E.find((e=>e.lang.startsWith(a)));n?(i.voice=n,i.lang=n.lang):i.lang=a||"en",i.onstart=()=>T(!0),i.onend=()=>T(!1),i.onerror=()=>T(!1),window.speechSynthesis.speak(i)},U=!j.parts.some((e=>["text","reasoning","data-action-tool-caption"].includes(e.type)));return"assistant"===j.role?e.jsx("div",Object.assign({className:u.default("flex w-full",M?"justify-end":"justify-start")},{children:e.jsx("div",Object.assign({className:u.default("flex flex-col w-full",0===h&&R&&"viewport"===C&&"min-[767px]:max-w-[80%]",0===h&&R&&"container"===C&&"@[767px]/pickaxe-root:max-w-[80%]")},{children:e.jsxs("div",Object.assign({className:u.default("flex gap-x-3",M&&"flex-row-reverse")},{children:[S.isChatImage&&"NONE"!==z&&e.jsx(o.default,{src:z,alt:"Assistant",width:24,height:24,className:"my-3 h-6 w-6",textColor:q.text}),e.jsxs("div",Object.assign({className:u.default("flex flex-col flex-grow",M?"items-end":"items-start")},{children:[e.jsxs("div",Object.assign({className:u.default(V.b2,"chat-message pt-3 w-full",M?"text-right":"text-left")},{children:[e.jsx(r.PickaxeMarkdown,Object.assign({theme:N.theme,colors:q},M&&{rtl:!0},I&&{disableHtml:!0},A&&{disableJs:!0},P&&{disableCss:!0},{disableReasoning:null!==(v=null==O?void 0:O.enablereasoningdisplay)&&void 0!==v&&v,onArtifactClick:H},{children:e.jsx(d.default,{parts:j.parts})})),w&&g&&b&&e.jsx("div",Object.assign({className:"mt-4 px-1"},{children:e.jsx(f.default,{serverId:g.serverId,smitheryId:g.smitheryId,name:g.smitheryId,resubmitPrompt:()=>b()})}))]})),e.jsx("div",Object.assign({className:u.default("flex flex-col gap-6 my-4",U&&"mt-2")},{children:B?e.jsx("div",Object.assign({className:"flex items-center gap-x-2 rounded"},{children:Array.from({length:3}).map(((s,t)=>e.jsx("div",{className:u.default("h-1.5 w-1.5 animate-dot rounded-full",1===t&&"animate-dot-down"),style:{backgroundColor:q.secondaryText}},t)))})):e.jsx(c.default,Object.assign({content:j.parts.filter((e=>e.isVisible&&"text"===e.type)).map((e=>e.content)).join("\n"),index:h},"intromessage"===j.area&&{isHideFeedback:!0},{onReadOut:G,isReadOut:D||!1,isReading:L}))}))]}))]}))}))})):"user"===j.role?e.jsx("div",Object.assign({className:u.default("flex w-full",M?"justify-start":"justify-end")},{children:e.jsx("div",Object.assign({className:u.default("flex gap-x-3 max-w-[80%]",M?"pr-9":"pl-9","viewport"===C?M?"min-[767px]:pr-0":"min-[767px]:pl-0":M?"@[767px]/pickaxe-root:pr-0":"@[767px]/pickaxe-root:pl-0")},{children:e.jsxs("div",Object.assign({className:u.default(V.b2,"overflow-x-auto overflow-y-hidden px-4 py-3 scrollbar-thin scrollbar-track-white scrollbar-thumb-[#4A4A4B] flex flex-col gap-y-3",M?"text-right":"text-left"),style:{backgroundColor:q.secondary+"80",color:q.secondaryText,borderRadius:N.cornerRadius}},{children:[j.documentIds&&j.documentIds.length>0&&e.jsx("div",Object.assign({className:u.default("flex flex-col gap-y-2",M?"items-start":"items-end")},{children:j.documentIds.map((t=>e.jsx(s.Fragment,{children:e.jsx(l.default,{documentId:t})},t)))})),e.jsx(r.PickaxeMarkdown,Object.assign({theme:N.theme,colors:q},M&&{rtl:!0},I&&{disableHtml:!0},A&&{disableJs:!0},P&&{disableCss:!0},{children:e.jsx(d.default,{parts:j.parts})}))]}))}))})):e.jsx("div",{})};
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e=require("react/jsx-runtime"),s=require("react"),t=require("../../../../hooks/pickaxe/usePickaxeContext.js"),i=require("../../../../hooks/studio/useStyleFontSize.js"),a=require("../../../../hooks/pickaxe/useResponseContext.js"),n=require("../../Addons/Artifact/hooks/useArtifact.js"),r=require("../../common/PickaxeMarkdown/index.js"),o=require("../../common/PickaxeIcon.js"),l=require("./Document.js"),c=require("../../common/PickaxeMessageActions.js"),d=require("../../common/PickaxeMessageParts/index.js"),u=require("../../../../common/cn.js"),m=require("../../../../common/isoMap.js"),x=require("franc-min"),f=require("../../common/ComposioConnectView.js"),p=require("../../common/SmitheryConnectView.js");function h(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}var j=h(require("remove-markdown"));exports.default=({index:h,message:g,smitheryData:b,resubmitPrompt:v,isLastMessage:w=!1})=>{var y,k;const{pickaxeId:O,pickaxe:N,styles:S,colors:q,misc:C,responsiveBy:I,disableHtml:P,disableJs:A,disableCss:R,isNewChat:M,isRtl:F}=t.usePickaxeContext(),{isGenerating:H}=a.useResponseContext(),{onLoadArtifact:L}=n.useArtifact(),[T,V]=s.useState(!1),[E,J]=s.useState([]),z=i.useStyleFontSize(),B=null!==(y=null==N?void 0:N.chaticon)&&void 0!==y?y:`https://cdn.mail.studio/chaticons/${O}.png`,D=w&&H,G=null==N?void 0:N.enablereadout;s.useEffect((()=>{if(!G||"assistant"!==g.role)return;const e=()=>{const e=window.speechSynthesis.getVoices();e.length>0&&J(e)};return e(),window.speechSynthesis.onvoiceschanged=e,()=>{window.speechSynthesis.onvoiceschanged=null}}),[G,g.role]),s.useEffect((()=>()=>{T&&window.speechSynthesis.cancel()}),[T]);const U=()=>{if(T)return window.speechSynthesis.cancel(),void V(!1);const e=g.parts.filter((e=>"text"===e.type)).map((e=>e.content)).join(" ");if(!e)return;const s=j.default(e,{stripListLeaders:!0,listUnicodeChar:"",gfm:!0,useImgAltText:!1}),t=x.franc(s),i=m.convertToIso1(t);window.speechSynthesis.cancel();const a=new SpeechSynthesisUtterance(s),n=E.find((e=>e.lang.startsWith(i)&&e.name.includes("Google")))||E.find((e=>e.lang.startsWith(i)));n?(a.voice=n,a.lang=n.lang):a.lang=i||"en",a.onstart=()=>V(!0),a.onend=()=>V(!1),a.onerror=()=>V(!1),window.speechSynthesis.speak(a)},W=!g.parts.some((e=>["text","reasoning","data-action-tool-caption"].includes(e.type)));return"assistant"===g.role?e.jsx("div",Object.assign({className:u.default("flex w-full",F?"justify-end":"justify-start")},{children:e.jsx("div",Object.assign({className:u.default("flex flex-col w-full",0===h&&M&&"viewport"===I&&"min-[767px]:max-w-[80%]",0===h&&M&&"container"===I&&"@[767px]/pickaxe-root:max-w-[80%]")},{children:e.jsxs("div",Object.assign({className:u.default("flex gap-x-3",F&&"flex-row-reverse")},{children:[C.isChatImage&&"NONE"!==B&&e.jsx(o.default,{src:B,alt:"Assistant",width:24,height:24,className:"my-3 h-6 w-6",textColor:q.text}),e.jsxs("div",Object.assign({className:u.default("flex flex-col flex-grow",F?"items-end":"items-start")},{children:[e.jsxs("div",Object.assign({className:u.default(z.b2,"chat-message pt-3 w-full",F?"text-right":"text-left")},{children:[e.jsx(r.PickaxeMarkdown,Object.assign({theme:S.theme,colors:q},F&&{rtl:!0},P&&{disableHtml:!0},A&&{disableJs:!0},R&&{disableCss:!0},{disableReasoning:null!==(k=null==N?void 0:N.enablereasoningdisplay)&&void 0!==k&&k,onArtifactClick:L},{children:e.jsx(d.default,{parts:g.parts})})),w&&b&&v&&("composio"===b.provider?e.jsx("div",Object.assign({className:"mt-4 px-1"},{children:e.jsx(f.default,{serverId:b.serverId,toolkitSlug:b.toolkitSlug||"",name:b.name,resubmitPrompt:()=>v()})})):e.jsx("div",Object.assign({className:"mt-4 px-1"},{children:e.jsx(p.default,{serverId:b.serverId,smitheryId:b.smitheryId||"",name:b.name||b.smitheryId,resubmitPrompt:()=>v()})})))]})),e.jsx("div",Object.assign({className:u.default("flex flex-col gap-6 my-4",W&&"mt-2")},{children:D?e.jsx("div",Object.assign({className:"flex items-center gap-x-2 rounded"},{children:Array.from({length:3}).map(((s,t)=>e.jsx("div",{className:u.default("h-1.5 w-1.5 animate-dot rounded-full",1===t&&"animate-dot-down"),style:{backgroundColor:q.secondaryText}},t)))})):e.jsx(c.default,Object.assign({content:g.parts.filter((e=>e.isVisible&&"text"===e.type)).map((e=>e.content)).join("\n"),index:h},"intromessage"===g.area&&{isHideFeedback:!0},{onReadOut:U,isReadOut:G||!1,isReading:T}))}))]}))]}))}))})):"user"===g.role?e.jsx("div",Object.assign({className:u.default("flex w-full",F?"justify-start":"justify-end")},{children:e.jsx("div",Object.assign({className:u.default("flex gap-x-3 max-w-[80%]",F?"pr-9":"pl-9","viewport"===I?F?"min-[767px]:pr-0":"min-[767px]:pl-0":F?"@[767px]/pickaxe-root:pr-0":"@[767px]/pickaxe-root:pl-0")},{children:e.jsxs("div",Object.assign({className:u.default(z.b2,"overflow-x-auto overflow-y-hidden px-4 py-3 scrollbar-thin scrollbar-track-white scrollbar-thumb-[#4A4A4B] flex flex-col gap-y-3",F?"text-right":"text-left"),style:{backgroundColor:q.secondary+"80",color:q.secondaryText,borderRadius:S.cornerRadius}},{children:[g.documentIds&&g.documentIds.length>0&&e.jsx("div",Object.assign({className:u.default("flex flex-col gap-y-2",F?"items-start":"items-end")},{children:g.documentIds.map((t=>e.jsx(s.Fragment,{children:e.jsx(l.default,{documentId:t})},t)))})),e.jsx(r.PickaxeMarkdown,Object.assign({theme:S.theme,colors:q},F&&{rtl:!0},P&&{disableHtml:!0},A&&{disableJs:!0},R&&{disableCss:!0},{children:e.jsx(d.default,{parts:g.parts})}))]}))}))})):e.jsx("div",{})};
@@ -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"),O=require("../../Core/ErrorAlert.js"),w=require("../../../common/error.js"),N=require("../../../common/api/pickaxe.js"),S=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]},q=(e,t)=>{const s=R(e,t);return D(s)?s:null},M=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,G,J,z,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:Oe,setValidationStatus:we,setValidationUpgradeGroups:Ne,setValidationUpgradeUrl:Se,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:qe}=i.useResponseContext(),{documents:Me,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:Ge,currentPopupType:Je,setArtifacts:ze,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([]),Ot=s.useRef(null),wt=s.useRef(null),Nt=s.useRef(null),St=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:qt}=Rt,Mt=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:"",Gt="undefined"!=typeof window?window.location.href:"",Jt="undefined"!=typeof window&&window.self!==window.top,zt=Yt.includes("pickaxe.co")&&!Gt.includes("https://studio.pickaxe.co/_embed")&&!Jt,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=S.getValidationFailure(e);return!!t&&(qe(""),Re(null),we(t.status),_e(t.accessGroup),Ne(t.upgradeGroups),Se(t.upgradeUrl),!0)}),[qe,Re,we,Ne,Se,_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}})),zt&&{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)}}))),[zt,null==pe?void 0:pe.studioid,ae,Ee]);s.useEffect((()=>{os()}),[os]);const as=Number(null!==(G=null==xe?void 0:xe.limit)&&void 0!==G?G: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:q(at,"email"),userId:null!==(e=q(at,"userId"))&&void 0!==e?e:q(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:M(null==at?void 0:at.currentUses),extraUses:M(null==at?void 0:at.extraUses)},fs=ds.scope?{currentUses:null!==(z=M(null===(J=ds.record)||void 0===J?void 0:J.currentUses))&&void 0!==z?z:0,extraUses:null!==(Z=M(null===(Q=ds.record)||void 0===Q?void 0:Q.extraUses))&&void 0!==Z?Z:0}:{currentUses:0,extraUses:0},gs=q(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 N.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),Os=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,Ns=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",Ss=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&&Me.length>0&&Me.every((e=>"finished"===e.status));return!(!tt.trim()&&!e)&&Me.every((e=>"finished"===e.status||e.isInsertedAsRaw))}),[Qt,De,Fe,tt,Me]);s.useImperativeHandle(H,(()=>({onSubmit:ks}))),s.useEffect((()=>{Oe(Ss)}),[Ss]),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(!Nt.current||!B)return;const e=new ResizeObserver((e=>{for(const t of e)B(t.contentRect.height)}));return e.observe(Nt.current),()=>{e.disconnect()}}),[B]),s.useEffect((()=>{if(!Ut)return;const e=bt.current?`${bt.current} `:"";st(`${e}${Ct}`)}),[Ct,Ut]),s.useEffect((()=>{if(!Ot.current)return;(()=>{if(!Ot.current)return;let e=Ot.current.scrollHeight>52;tt.includes("\n")||Me.length?e=!0:tt.trim()||(e=!1),it(e)})()}),[tt,Me]),s.useEffect((()=>{const e=Ot.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=Me.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;qe(""),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_API_URL}/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()})},zt&&{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"),St.current=new AbortController;const x=p.length-1,j=[];let O=[...null!=Ge?Ge:[]],w=0,N=!1,S="";for(;!N;)try{const e=yield fetch(`${process.env.NEXT_PUBLIC_PICKAXE_API_URL}/stream/${b}?index=${w}`,{signal:null===(r=St.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())N=!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),qe(""),void(N=!0);const s=t.error||t.message||(null==ge?void 0:ge["something-went-wrong"])||"Something went wrong.";return ns(t)||qe(s),void(N=!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){if(/['"]type['"]\s*:\s*['"]unauthorized_smithery['"]/.test(e)){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 N=!0,X({smitheryId: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 N=!0,X({smitheryId:t.qualifiedName,serverId:t.serverId,name:t.name}),new Error("STOP_STREAM")}}else if("text-start"===n.type)S="",j.push({type:"text",content:"",isVisible:null===(t=n.isVisible)||void 0===t||t});else if("text-delta"===n.type)S+=n.delta,j[j.length-1].content=S;else if("text-end"===n.type)S="";else if("reasoning-start"===n.type)S="",j.push({type:"reasoning",content:"",isVisible:null===(s=n.isVisible)||void 0===s||s});else if("reasoning-delta"===n.type)S+=n.delta,j[j.length-1].content=S;else if("reasoning-end"===n.type)S="";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);O=O.filter((e=>!(e.id===t.id&&e.version===t.version))),O.push(Object.assign(Object.assign({},t),{content:"",status:"streaming"})),ze([...O]),Je.startsWith("inline")||Qe({id:t.id,version:t.version})}else if("artifact_updated"===e.event){const t=JSON.parse(e.data);O=O.filter((e=>!(e.id===t.id&&e.version===t.version))),O.push(Object.assign(Object.assign({},t),{content:"",status:"updating"})),ze(O),Je.startsWith("inline")||Qe({id:t.id,version:t.version})}else if("artifact_rewrite"===e.event){const t=JSON.parse(e.data);O=O.filter((e=>!(e.id===t.id&&e.version===t.version))),O.push(Object.assign(Object.assign({},t),{content:"",status:"streaming"})),ze(O),Je.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,"");O=O.map((e=>e.id===t.id&&e.version===t.version?Object.assign(Object.assign({},e),{content:e.content+s,status:"streaming"}):e)),ze(O)}else if("artifact_finished"===e.event){const t=JSON.parse(e.data);ze(O.map((e=>e.id===t.id?Object.assign(Object.assign({},e),{status:"finished"}):e)))}else if("error"===e.event){const t=JSON.parse(e.data);if(t.limitData)return Re(t.limitData),qe(""),void(N=!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(N=!0);qe(s)}else"stop"===e.event&&(N=!0)}else N=!0}});for(;;){if(y()){N=!0,t.cancel().catch((()=>{}));break}const{value:e,done:i}=yield t.read();if(y()){N=!0,t.cancel().catch((()=>{}));break}if(i)break;n.feed(s.decode(e))}N||y()||(yield new Promise((e=>setTimeout(e,1e3))))}catch(e){if("STOP_STREAM"===e.message||L(e)||y())return void(N=!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),qe("");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)||qe(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:Nt,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:[Os&&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:Ns})),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&&Me.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:Ot,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_API_URL}/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})},zt&&{credentials:"include"}))}catch(e){console.warn("Failed to cancel submission",e)}}))})(t)),St.current&&(St.current.abort(),St.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:qt||_s?fe.accent:fe.accent+"10",color:qt||_s?fe.accentText:fe.accent+"80"},disabled:!_s,onClick:()=>ks()},Mt,{children:t.jsx(b.default,{className:_.default("h-6 w-6 shrink-0",ye&&"scale-x-[-1] transform")})}))]})}))]}))]})),Ve&&t.jsx(O.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"),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_API_URL}/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_API_URL}/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_API_URL}/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;
@@ -0,0 +1 @@
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e=require("../../../_virtual/_tslib.js"),t=require("react/jsx-runtime"),o=require("react"),s=require("../../../common/error.js"),i=require("../../Core/Button.js"),n=require("../../Core/ErrorAlert.js"),r=require("../../../common/api/api.js"),c=require("../../../common/utils.js"),a=require("../Addons/Auth/hooks/useAuthContext.js"),l=require("../../../hooks/pickaxe/usePickaxeContext.js");exports.default=({serverId:u,toolkitSlug:d,name:m,resubmitPrompt:x})=>{const{pickaxe:p,sender:j,translations:b,colors:f}=l.usePickaxeContext(),{token:g}=a.useAuthContext(),h=o.useRef(null),[v,k]=o.useState(!0),[C,O]=o.useState(!1),[y,q]=o.useState(null),w=()=>{if(j)return j;if(h.current)return h.current;const e=c.initializeEmbedUserId();return h.current=e,e},_=()=>{const e={serverId:u,studioId:null==p?void 0:p.studioid};return g?Object.assign(Object.assign({},e),{studioSessionToken:g}):Object.assign(Object.assign({},e),{userId:w()})};return v?t.jsxs("div",Object.assign({className:"w-full bg-white border border-c-sep rounded-lg shadow-sm p-4 flex flex-col gap-4"},{children:[t.jsxs("div",Object.assign({className:"flex flex-col gap-1"},{children:[t.jsx("h3",Object.assign({className:"font-semibold text-black/80 text-lg"},{children:(null==b?void 0:b["authentication-required"])||"Authentication Required"})),t.jsxs("p",Object.assign({className:"text-black/60 text-sm"},{children:[(null==b?void 0:b["composio-auth-description-prefix"])||"The tool you are trying to use requires authentication with"," ",t.jsx("span",Object.assign({className:"font-semibold text-black/80"},{children:m||d})),"."]}))]})),y&&t.jsx(n.default,{error:y}),t.jsxs("div",Object.assign({className:"flex justify-end gap-2"},{children:[t.jsx(i.default,Object.assign({variant:"secondary",onClick:()=>k(!1),className:"text-sm px-3 h-9"},{children:(null==b?void 0:b.dismiss)||"Dismiss"})),t.jsx(i.default,Object.assign({variant:"primary",loadingText:(null==b?void 0:b.connecting)||"Connecting...",isLoading:C,style:{borderColor:f.accent,backgroundColor:f.accent,color:f.accentText},onClick:()=>e.__awaiter(void 0,void 0,void 0,(function*(){if(C)return;const t=_();if("LOGGED OUT"!==t.userId)try{q(null),O(!0);const o=yield r.api.post("/mcp/composio/connect",t),{connectLinkUrl:s,connected:i}=o.data;if(s&&window.open(s,"_blank","noopener,noreferrer"),!i){const t=yield e.__awaiter(void 0,void 0,void 0,(function*(){for(let e=0;e<180;e+=1){const e=yield r.api.post("/mcp/composio/status",_()),{connected:t}=e.data;if(t)return!0;yield new Promise((e=>setTimeout(e,1e3)))}return!1}));if(!t)throw new Error((null==b?void 0:b["composio-auth-timeout"])||"Composio authentication timed out.")}k(!1),x()}catch(e){q(s.default(e))}finally{O(!1)}else q((null==b?void 0:b["must-be-logged-in-to-connect-composio"])||"You must be logged in to connect Composio MCPs.")})),className:"text-sm px-3 h-9 hover:opacity-90"},{children:(null==b?void 0:b.connect)||"Connect"}))]}))]})):null};
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e=require("../../../../../../_virtual/_tslib.js"),t=require("react/jsx-runtime"),o=require("react"),s=require("../../../../../../hooks/pickaxe/usePickaxeContext.js"),i=require("../../../../Addons/Auth/hooks/useAuthContext.js"),r=require("../../../../../../hooks/pickaxe/useSubmitDocument.js"),l=require("../../hooks/usePickaxeMarkdownContext.js"),n=require("../../../../../Icons/download.svg.js"),a=require("../../../../../Icons/copy.svg.js"),c=require("../../../../../Icons/copied.svg.js"),d=require("../../../../../Icons/file.svg.js"),u=require("../../../../../Icons/upload-cloud.svg.js"),p=require("copy-to-clipboard"),m=require("../../../../../../common/error.js");function f(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}var x=f(p);const h=/(?:https?:\/\/|www\.)[^\s<>"']+/gi,v=new Set(["jpeg","jpg","gif","bmp","webp","svg","tiff","avif","png","jfif","pjpeg","pjp"]),w=new Set(["mp3","wav","ogg","flac","aac","wma","alac","m4a","aiff","ape","au","mid","midi","opus"]),b=new Set(["mp4","webm","mov","avi","mkv","m4v"]),g=new Set(["csv","tsv","txt","json","xml","md","log","yaml","yml"]),j=new Set(["doc","docx","xls","xlsx","ppt","pptx"]),k=new Set(["pdf","html","htm",...g,...j]),y=e=>v.has(e)?"image":w.has(e)?"audio":b.has(e)?"video":"pdf"===e?"pdf":"html"===e||"htm"===e?"html":g.has(e)?"text":j.has(e)?"office":"file",N=e=>{const t=(e=>{let t=e.trim();for(;/[),.;!?]$/.test(t);)t=t.slice(0,-1);return t})(e);return t.startsWith("http://")?`https://${t.slice(7)}`:t.startsWith("www.")?`https://${t}`:t},C=e=>{try{return new URL(N(e)).pathname.includes("/action_generated_files/")}catch(e){return!1}},S=e=>{try{return new URL(N(e)).pathname.includes("/documentinterrogation/")}catch(e){return!1}},O=e=>{const t=N(e);if(C(t))return!1;if(S(t))return!0;if((e=>{const t=N(e);return/(?:youtube\.com\/watch\?v=|youtu\.be\/)([\w-]+)/i.test(t)||/loom\.com\/(?:share|embed)\/([\w-]+)/i.test(t)||/vimeo\.com\/(?:video\/)?(\d+)/i.test(t)||/streamable\.com\/([\w-]+)/i.test(t)})(t))return!0;const o=(e=>{var t,o,s,i;try{const r=new URL(N(e));return"https:"!==r.protocol&&"http:"!==r.protocol?null:null!==(i=null===(s=null===(o=null===(t=r.pathname.split("/").filter(Boolean).pop())||void 0===t?void 0:t.match(/\.([a-z0-9]{1,10})$/i))||void 0===o?void 0:o[1])||void 0===s?void 0:s.toLowerCase())&&void 0!==i?i:null}catch(e){return null}})(t);return!!o&&k.has(o)},I=(e,t)=>{const o=N(e);return O(o)||(null==t?void 0:t.has(o))};exports.default=({fileInfo:p,displayName:f})=>{const{theme:h,colors:v,disableHtml:w,disableJs:b}=l.usePickaxeMarkdownContext(),{contextId:g,pickaxeId:j,pickaxe:k,translations:y}=s.usePickaxeContext(),{isLoggedIn:N,token:C}=i.useAuthContext(),S=r.useSubmitDocument(),[O,I]=o.useState(!1),[F,q]=o.useState(!1),[U,P]=o.useState(!1),R=(e,t)=>{var o;return null!==(o=null==y?void 0:y[e])&&void 0!==o?o:t},_="dark"===h?"#30363D":"#D0D7DE",D="dark"===h?"#0D1117":"#F6F8FA",$="dark"===h?"#161B22":"#FFFFFF",L=(null==f?void 0:f.trim())||p.fileName,T=L!==p.fileName,A={display:"inline-flex",width:32,height:32,alignItems:"center",justifyContent:"center",borderRadius:4,color:v.accentText,backgroundColor:v.accent,opacity:.88,flexShrink:0},B=(e,o,s)=>t.jsx("div",Object.assign({className:"flex w-full p-4"},{children:t.jsxs("div",Object.assign({className:"relative w-full overflow-hidden rounded-md shadow-sm",style:{aspectRatio:"8.5 / 11",backgroundColor:$,border:`1px solid ${_}`}},{children:[t.jsx("iframe",Object.assign({src:e,title:o},s,{className:"h-full w-full",scrolling:"no",tabIndex:-1,style:{border:"none",pointerEvents:"none"}})),t.jsx("div",{className:"pointer-events-none absolute inset-x-0 bottom-0 h-10",style:{background:"dark"===h?"linear-gradient(to top, rgba(22,27,34,0.95), rgba(22,27,34,0))":"linear-gradient(to top, rgba(255,255,255,0.95), rgba(255,255,255,0))"}})]}))}));return t.jsxs("div",Object.assign({className:"my-2 w-full overflow-hidden rounded-lg",style:{border:`1px solid ${_}`,backgroundColor:D,color:v.secondaryText}},{children:[t.jsxs("div",Object.assign({className:"flex items-center justify-between gap-3 border-b px-3 py-2",style:{borderColor:_}},{children:[t.jsx("a",Object.assign({href:p.url,target:"_blank",rel:"noopener noreferrer",className:"min-w-0 flex-1 truncate text-sm font-semibold hover:underline",style:{color:v.secondaryText},title:T?`${L} (${p.fileName})`:L},{children:L})),t.jsxs("div",Object.assign({className:"flex shrink-0 items-center gap-1.5"},{children:[t.jsx("button",Object.assign({type:"button",onClick:()=>{const e=document.createElement("a");e.href=p.url,e.download=p.fileName,e.target="_blank",e.rel="noopener noreferrer",e.click()},title:R("download","Download"),"aria-label":R("download","Download"),style:A},{children:t.jsx(n.default,{className:"h-[18px] w-[18px]"})})),t.jsx("button",Object.assign({type:"button",onClick:()=>{e.__awaiter(void 0,void 0,void 0,(function*(){try{I(!0),x.default(p.url),yield new Promise((e=>setTimeout(e,1500)))}finally{I(!1)}}))},title:O?R("copied","Copied"):R("copy-link","Copy link"),"aria-label":O?R("copied","Copied"):R("copy-link","Copy link"),style:Object.assign(Object.assign({},A),{opacity:O?1:A.opacity})},{children:O?t.jsx(c.default,{className:"h-[18px] w-[18px]"}):t.jsx(a.default,{className:"h-[18px] w-[18px]"})})),N&&C&&t.jsx("button",Object.assign({type:"button",disabled:F||U,onClick:()=>{e.__awaiter(void 0,void 0,void 0,(function*(){if(C&&!F){q(!0),P(!1);try{const e=yield fetch(p.url);if(!e.ok)throw new Error("Failed to download generated file.");const t=yield e.blob(),o=new File([t],p.fileName,{type:t.type||"application/octet-stream"});yield S.document(Object.assign(Object.assign({contextId:g,pickaxeId:j,file:o},(null==k?void 0:k.workspaceid)&&{workspaceId:k.workspaceid}),{studioSessionToken:C,isUserDocument:!0})),P(!0),yield new Promise((e=>setTimeout(e,1500)))}catch(e){alert(m.default(e))}finally{q(!1),P(!1)}}}))},title:F?R("saving","Saving..."):U?R("saved","Saved"):R("save-to-knowledge-base","Save to Knowledge Base"),"aria-label":F?R("saving","Saving..."):U?R("saved","Saved"):R("save-to-knowledge-base","Save to Knowledge Base"),style:Object.assign(Object.assign({},A),{opacity:F||U?.55:A.opacity,cursor:F||U?"not-allowed":"pointer"})},{children:t.jsx(u.default,{className:"h-[18px] w-[18px]"})}))]}))]})),t.jsx("div",{children:(()=>{if("image"===p.kind)return t.jsx("img",{src:p.url,alt:p.fileName,className:"block max-h-[420px] w-full object-contain"});if("audio"===p.kind)return t.jsx("div",Object.assign({className:"flex min-h-[72px] items-center p-4"},{children:t.jsx("audio",{className:"w-full",controls:!0,src:p.url})}));if("video"===p.kind)return t.jsx("video",{className:"block max-h-[420px] w-full bg-black",controls:!0,preload:"metadata",src:p.url});if("pdf"===p.kind||"text"===p.kind){const e="pdf"===p.kind?`${p.url}#page=1&toolbar=0&navpanes=0&scrollbar=0&view=FitH`:p.url;return B(e,p.fileName)}if("html"===p.kind&&!w){const e=["allow-same-origin","allow-forms","allow-popups","allow-downloads","allow-modals",b?"":"allow-scripts"].filter(Boolean).join(" ");return B(p.url,p.fileName,{sandbox:e})}return"office"===p.kind?B(`https://view.officeapps.live.com/op/embed.aspx?src=${encodeURIComponent(p.url)}`,p.fileName):t.jsxs("div",Object.assign({className:"flex min-h-[120px] items-center justify-center gap-3 p-6 text-sm"},{children:[t.jsx(d.default,{className:"h-8 w-8 shrink-0"}),t.jsx("span",Object.assign({className:"break-all"},{children:p.extension.toUpperCase()}))]}))})()})]}))},exports.getFilePreviewInfo=e=>{var t,o;try{const s=N(e),i=new URL(s);if("https:"!==i.protocol&&"http:"!==i.protocol)return null;const r=i.pathname.split("/").filter(Boolean).pop();if(!r)return null;const l=decodeURIComponent(r),n=null===(o=null===(t=l.match(/\.([a-z0-9]{1,10})$/i))||void 0===t?void 0:t[1])||void 0===o?void 0:o.toLowerCase();return n?{url:s,fileName:l,extension:n,kind:y(n)}:null}catch(e){return null}},exports.isDocumentSourceUrl=S,exports.isGeneratedFileUrl=C,exports.isSourceLikeRichPreviewUrl=O,exports.normalizeMarkdownUrl=N,exports.shouldRenderFilePreview=(e,t)=>!!e&&(!t||!t.current.has(e.url)&&(t.current.add(e.url),!0)),exports.shouldSuppressRichPreviewForUrl=I,exports.shouldSuppressRichPreviewInText=(e,t)=>{for(const o of e.matchAll(h))if(I(o[0],t))return!0;return!1};
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e=require("../../../../../../_virtual/_tslib.js"),t=require("react/jsx-runtime"),o=require("react"),s=require("../../../../../../hooks/pickaxe/usePickaxeContext.js"),r=require("../../../../Addons/Auth/hooks/useAuthContext.js"),i=require("../../../../../../hooks/pickaxe/useSubmitDocument.js"),l=require("../../hooks/usePickaxeMarkdownContext.js"),n=require("../../../../../Icons/download.svg.js"),a=require("../../../../../Icons/copy.svg.js"),c=require("../../../../../Icons/copied.svg.js"),d=require("../../../../../Icons/file.svg.js"),u=require("../../../../../Icons/upload-cloud.svg.js"),p=require("copy-to-clipboard"),m=require("../../../../../../common/error.js");function f(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}var x=f(p);const h=/(?:https?:\/\/|www\.)[^\s<>"']+/gi,v=new Set(["jpeg","jpg","gif","bmp","webp","svg","tiff","avif","png","jfif","pjpeg","pjp"]),w=new Set(["mp3","wav","ogg","flac","aac","wma","alac","m4a","aiff","ape","au","mid","midi","opus"]),b=new Set(["mp4","webm","mov","avi","mkv","m4v"]),g=new Set(["csv","tsv","txt","json","xml","md","log","yaml","yml"]),j=new Set(["doc","docx","xls","xlsx","ppt","pptx"]),k=new Set(["pdf","html","htm",...g,...j]),y=e=>v.has(e)?"image":w.has(e)?"audio":b.has(e)?"video":"pdf"===e?"pdf":"html"===e||"htm"===e?"html":g.has(e)?"text":j.has(e)?"office":"file",N=e=>{const t=(e=>{let t=e.trim();for(;/[),.;!?]$/.test(t);)t=t.slice(0,-1);return t})(e);return t.startsWith("http://")?`https://${t.slice(7)}`:t.startsWith("www.")?`https://${t}`:t},C=e=>{try{return new URL(N(e)).pathname.includes("/action_generated_files/")}catch(e){return!1}},S=e=>{try{return new URL(N(e)).pathname.includes("/documentinterrogation/")}catch(e){return!1}},O=e=>{const t=N(e);return/(?:youtube\.com\/watch\?v=|youtu\.be\/)([\w-]+)/i.test(t)},I=e=>{const t=N(e);if(C(t))return!1;if(S(t))return!0;if(O(t))return!1;if((e=>{const t=N(e);return/loom\.com\/(?:share|embed)\/([\w-]+)/i.test(t)||/vimeo\.com\/(?:video\/)?(\d+)/i.test(t)||/streamable\.com\/([\w-]+)/i.test(t)})(t))return!0;const o=(e=>{var t,o,s,r;try{const i=new URL(N(e));return"https:"!==i.protocol&&"http:"!==i.protocol?null:null!==(r=null===(s=null===(o=null===(t=i.pathname.split("/").filter(Boolean).pop())||void 0===t?void 0:t.match(/\.([a-z0-9]{1,10})$/i))||void 0===o?void 0:o[1])||void 0===s?void 0:s.toLowerCase())&&void 0!==r?r:null}catch(e){return null}})(t);return!!o&&k.has(o)},F=(e,t)=>{const o=N(e);return!O(o)&&(I(o)||(null==t?void 0:t.has(o)))};exports.default=({fileInfo:p,displayName:f})=>{const{theme:h,colors:v,disableHtml:w,disableJs:b}=l.usePickaxeMarkdownContext(),{contextId:g,pickaxeId:j,pickaxe:k,translations:y}=s.usePickaxeContext(),{isLoggedIn:N,token:C}=r.useAuthContext(),S=i.useSubmitDocument(),[O,I]=o.useState(!1),[F,q]=o.useState(!1),[U,P]=o.useState(!1),R=(e,t)=>{var o;return null!==(o=null==y?void 0:y[e])&&void 0!==o?o:t},_="dark"===h?"#30363D":"#D0D7DE",D="dark"===h?"#0D1117":"#F6F8FA",$="dark"===h?"#161B22":"#FFFFFF",L=(null==f?void 0:f.trim())||p.fileName,T=L!==p.fileName,A={display:"inline-flex",width:32,height:32,alignItems:"center",justifyContent:"center",borderRadius:4,color:v.accentText,backgroundColor:v.accent,opacity:.88,flexShrink:0},B=(e,o,s)=>t.jsx("div",Object.assign({className:"flex w-full p-4"},{children:t.jsxs("div",Object.assign({className:"relative w-full overflow-hidden rounded-md shadow-sm",style:{aspectRatio:"8.5 / 11",backgroundColor:$,border:`1px solid ${_}`}},{children:[t.jsx("iframe",Object.assign({src:e,title:o},s,{className:"h-full w-full",scrolling:"no",tabIndex:-1,style:{border:"none",pointerEvents:"none"}})),t.jsx("div",{className:"pointer-events-none absolute inset-x-0 bottom-0 h-10",style:{background:"dark"===h?"linear-gradient(to top, rgba(22,27,34,0.95), rgba(22,27,34,0))":"linear-gradient(to top, rgba(255,255,255,0.95), rgba(255,255,255,0))"}})]}))}));return t.jsxs("div",Object.assign({className:"my-2 w-full overflow-hidden rounded-lg",style:{border:`1px solid ${_}`,backgroundColor:D,color:v.secondaryText}},{children:[t.jsxs("div",Object.assign({className:"flex items-center justify-between gap-3 border-b px-3 py-2",style:{borderColor:_}},{children:[t.jsx("a",Object.assign({href:p.url,target:"_blank",rel:"noopener noreferrer",className:"min-w-0 flex-1 truncate text-sm font-semibold hover:underline",style:{color:v.secondaryText},title:T?`${L} (${p.fileName})`:L},{children:L})),t.jsxs("div",Object.assign({className:"flex shrink-0 items-center gap-1.5"},{children:[t.jsx("button",Object.assign({type:"button",onClick:()=>{const e=document.createElement("a");e.href=p.url,e.download=p.fileName,e.target="_blank",e.rel="noopener noreferrer",e.click()},title:R("download","Download"),"aria-label":R("download","Download"),style:A},{children:t.jsx(n.default,{className:"h-[18px] w-[18px]"})})),t.jsx("button",Object.assign({type:"button",onClick:()=>{e.__awaiter(void 0,void 0,void 0,(function*(){try{I(!0),x.default(p.url),yield new Promise((e=>setTimeout(e,1500)))}finally{I(!1)}}))},title:O?R("copied","Copied"):R("copy-link","Copy link"),"aria-label":O?R("copied","Copied"):R("copy-link","Copy link"),style:Object.assign(Object.assign({},A),{opacity:O?1:A.opacity})},{children:O?t.jsx(c.default,{className:"h-[18px] w-[18px]"}):t.jsx(a.default,{className:"h-[18px] w-[18px]"})})),N&&C&&t.jsx("button",Object.assign({type:"button",disabled:F||U,onClick:()=>{e.__awaiter(void 0,void 0,void 0,(function*(){if(C&&!F){q(!0),P(!1);try{const e=yield fetch(p.url);if(!e.ok)throw new Error("Failed to download generated file.");const t=yield e.blob(),o=new File([t],p.fileName,{type:t.type||"application/octet-stream"});yield S.document(Object.assign(Object.assign({contextId:g,pickaxeId:j,file:o},(null==k?void 0:k.workspaceid)&&{workspaceId:k.workspaceid}),{studioSessionToken:C,isUserDocument:!0})),P(!0),yield new Promise((e=>setTimeout(e,1500)))}catch(e){alert(m.default(e))}finally{q(!1),P(!1)}}}))},title:F?R("saving","Saving..."):U?R("saved","Saved"):R("save-to-knowledge-base","Save to Knowledge Base"),"aria-label":F?R("saving","Saving..."):U?R("saved","Saved"):R("save-to-knowledge-base","Save to Knowledge Base"),style:Object.assign(Object.assign({},A),{opacity:F||U?.55:A.opacity,cursor:F||U?"not-allowed":"pointer"})},{children:t.jsx(u.default,{className:"h-[18px] w-[18px]"})}))]}))]})),t.jsx("div",{children:(()=>{if("image"===p.kind)return t.jsx("img",{src:p.url,alt:p.fileName,className:"block max-h-[420px] w-full object-contain"});if("audio"===p.kind)return t.jsx("div",Object.assign({className:"flex min-h-[72px] items-center p-4"},{children:t.jsx("audio",{className:"w-full",controls:!0,src:p.url})}));if("video"===p.kind)return t.jsx("video",{className:"block max-h-[420px] w-full bg-black",controls:!0,preload:"metadata",src:p.url});if("pdf"===p.kind||"text"===p.kind){const e="pdf"===p.kind?`${p.url}#page=1&toolbar=0&navpanes=0&scrollbar=0&view=FitH`:p.url;return B(e,p.fileName)}if("html"===p.kind&&!w){const e=["allow-same-origin","allow-forms","allow-popups","allow-downloads","allow-modals",b?"":"allow-scripts"].filter(Boolean).join(" ");return B(p.url,p.fileName,{sandbox:e})}return"office"===p.kind?B(`https://view.officeapps.live.com/op/embed.aspx?src=${encodeURIComponent(p.url)}`,p.fileName):t.jsxs("div",Object.assign({className:"flex min-h-[120px] items-center justify-center gap-3 p-6 text-sm"},{children:[t.jsx(d.default,{className:"h-8 w-8 shrink-0"}),t.jsx("span",Object.assign({className:"break-all"},{children:p.extension.toUpperCase()}))]}))})()})]}))},exports.getFilePreviewInfo=e=>{var t,o;try{const s=N(e),r=new URL(s);if("https:"!==r.protocol&&"http:"!==r.protocol)return null;const i=r.pathname.split("/").filter(Boolean).pop();if(!i)return null;const l=decodeURIComponent(i),n=null===(o=null===(t=l.match(/\.([a-z0-9]{1,10})$/i))||void 0===t?void 0:t[1])||void 0===o?void 0:o.toLowerCase();return n?{url:s,fileName:l,extension:n,kind:y(n)}:null}catch(e){return null}},exports.isDocumentSourceUrl=S,exports.isGeneratedFileUrl=C,exports.isSourceLikeRichPreviewUrl=I,exports.normalizeMarkdownUrl=N,exports.shouldRenderFilePreview=(e,t)=>!!e&&(!t||!t.current.has(e.url)&&(t.current.add(e.url),!0)),exports.shouldSuppressRichPreviewForUrl=F,exports.shouldSuppressRichPreviewInText=(e,t)=>{for(const o of e.matchAll(h))if(F(o[0],t))return!0;return!1};
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e=require("../../../_virtual/_tslib.js"),t=require("react/jsx-runtime"),i=require("react"),s=require("../../../common/error.js"),r=require("../../../node_modules/.pnpm/@modelcontextprotocol_sdk@1.20.2/node_modules/@modelcontextprotocol/sdk/dist/esm/client/index.js"),n=require("../../../node_modules/.pnpm/@modelcontextprotocol_sdk@1.20.2/node_modules/@modelcontextprotocol/sdk/dist/esm/client/streamableHttp.js"),o=require("../../Core/Button.js"),a=require("../../Core/ErrorAlert.js"),l=require("./SmitheryAuthProvider.js"),c=require("uuid"),d=require("../../../common/api/api.js"),u=require("../../../common/api/pickaxe.js"),m=require("../../../hooks/pickaxe/usePickaxeContext.js"),p=require("../../../common/fernet.js");exports.default=({serverId:v,smitheryId:h,name:x,resubmitPrompt:f})=>{const{sender:g,translations:j}=m.usePickaxeContext(),[_,b]=i.useState(!0),[k,y]=i.useState(!1),[O,N]=i.useState(null),I=i.useRef(null),S=i.useMemo((()=>c.v4()),[]);i.useEffect((()=>{let t=null;return k&&(t=setInterval((()=>e.__awaiter(void 0,void 0,void 0,(function*(){const e=yield d.api2.post("/oauth/handshake/check",{sessionId:S}),{success:i,code:s}=e.data;if("failed"===s)return N((null==j?void 0:j["auth-failed"])||"Auth failed"),y(!1),void(t&&clearInterval(t));if(s&&i){t&&clearInterval(t);try{if(!I.current)throw new Error("Transport not available for finalization.");yield I.current.finishAuth(s)}catch(e){return console.error(e),N((null==j?void 0:j["failed-to-finalize-authentication"])||"Failed to finalize authentication."),void y(!1)}const e=localStorage.getItem("mcp_tokens"),i=localStorage.getItem("mcp_client");e&&i&&q(JSON.parse(e),JSON.parse(i))}}))),1e3)),()=>{t&&clearInterval(t)}}),[k]);const q=(t,i)=>e.__awaiter(void 0,void 0,void 0,(function*(){try{yield u.pickaxeApi2.post("/mcp/user/save",{tokens:yield p.encryptFernet(JSON.stringify(t)),clientId:i.client_id,serverId:v,userId:g},Object.assign(Object.assign({},(!process.env.NODE_ENV||"development"===process.env.NODE_ENV)&&Object.assign({},process.env.NEXT_PUBLIC_PICKAXE_SESSION_TOKEN&&{headers:{"x-pickaxe-session-token":process.env.NEXT_PUBLIC_PICKAXE_SESSION_TOKEN}})),u.isPickaxeDomain&&{credentials:"include"})),localStorage.removeItem("mcp_tokens"),localStorage.removeItem("mcp_client"),b(!1),f()}catch(e){N(s.default(e))}}));return _?t.jsxs("div",Object.assign({className:"w-full bg-white border border-c-sep rounded-lg shadow-sm p-4 flex flex-col gap-4"},{children:[t.jsxs("div",Object.assign({className:"flex flex-col gap-1"},{children:[t.jsx("h3",Object.assign({className:"font-semibold text-black/80 text-lg"},{children:(null==j?void 0:j["authentication-required"])||"Authentication Required"})),t.jsxs("p",Object.assign({className:"text-black/60 text-sm"},{children:[(null==j?void 0:j["smithery-auth-description-prefix"])||"The tool you are trying to use requires authentication with"," ",t.jsx("span",Object.assign({className:"font-semibold text-black/80"},{children:x||h})),"."]}))]})),O&&t.jsx(a.default,{error:O}),t.jsxs("div",Object.assign({className:"flex justify-end gap-2"},{children:[t.jsx(o.default,Object.assign({variant:"secondary",onClick:()=>b(!1),className:"text-sm px-3 h-9"},{children:(null==j?void 0:j.dismiss)||"Dismiss"})),t.jsx(o.default,Object.assign({variant:"primary",loadingText:(null==j?void 0:j.connecting)||"Connecting...",isLoading:k,onClick:()=>e.__awaiter(void 0,void 0,void 0,(function*(){if(!k)if("LOGGED OUT"!==g)try{N(null),y(!0);const e=new l.SmitheryAuthProvider(S),t=new n.StreamableHTTPClientTransport(new URL(`https://server.smithery.ai/${h}/mcp`),{authProvider:e});I.current=t;const i=new r.Client({name:"Pickaxe",version:"1.0.0"});yield i.connect(t)}catch(e){console.log(s.default(e))}else N((null==j?void 0:j["must-be-logged-in-to-connect-smithery"])||"You must be logged in to connect Smithery MCPs.")})),className:"text-sm px-3 h-9"},{children:(null==j?void 0:j.connect)||"Connect"}))]}))]})):null};
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e=require("../../../_virtual/_tslib.js"),t=require("react/jsx-runtime"),i=require("react"),o=require("../../../common/error.js"),s=require("../../../node_modules/.pnpm/@modelcontextprotocol_sdk@1.20.2/node_modules/@modelcontextprotocol/sdk/dist/esm/client/index.js"),r=require("../../../node_modules/.pnpm/@modelcontextprotocol_sdk@1.20.2/node_modules/@modelcontextprotocol/sdk/dist/esm/client/streamableHttp.js"),n=require("../../Core/Button.js"),a=require("../../Core/ErrorAlert.js"),l=require("./SmitheryAuthProvider.js"),c=require("uuid"),d=require("../../../common/api/api.js"),u=require("../../../common/api/pickaxe.js"),m=require("../../../hooks/pickaxe/usePickaxeContext.js"),p=require("../../../common/fernet.js");exports.default=({serverId:v,smitheryId:h,name:x,resubmitPrompt:f})=>{const{sender:g,translations:j,colors:_}=m.usePickaxeContext(),[b,k]=i.useState(!0),[y,O]=i.useState(!1),[N,I]=i.useState(null),S=i.useRef(null),q=i.useMemo((()=>c.v4()),[]);i.useEffect((()=>{let t=null;return y&&(t=setInterval((()=>e.__awaiter(void 0,void 0,void 0,(function*(){const e=yield d.api2.post("/oauth/handshake/check",{sessionId:q}),{success:i,code:o}=e.data;if("failed"===o)return I((null==j?void 0:j["auth-failed"])||"Auth failed"),O(!1),void(t&&clearInterval(t));if(o&&i){t&&clearInterval(t);try{if(!S.current)throw new Error("Transport not available for finalization.");yield S.current.finishAuth(o)}catch(e){return console.error(e),I((null==j?void 0:j["failed-to-finalize-authentication"])||"Failed to finalize authentication."),void O(!1)}const e=localStorage.getItem("mcp_tokens"),i=localStorage.getItem("mcp_client");e&&i&&C(JSON.parse(e),JSON.parse(i))}}))),1e3)),()=>{t&&clearInterval(t)}}),[y]);const C=(t,i)=>e.__awaiter(void 0,void 0,void 0,(function*(){try{yield u.pickaxeApi2.post("/mcp/user/save",{tokens:yield p.encryptFernet(JSON.stringify(t)),clientId:i.client_id,serverId:v,userId:g},Object.assign(Object.assign({},(!process.env.NODE_ENV||"development"===process.env.NODE_ENV)&&Object.assign({},process.env.NEXT_PUBLIC_PICKAXE_SESSION_TOKEN&&{headers:{"x-pickaxe-session-token":process.env.NEXT_PUBLIC_PICKAXE_SESSION_TOKEN}})),u.isPickaxeDomain&&{credentials:"include"})),localStorage.removeItem("mcp_tokens"),localStorage.removeItem("mcp_client"),k(!1),f()}catch(e){I(o.default(e))}}));return b?t.jsxs("div",Object.assign({className:"w-full bg-white border border-c-sep rounded-lg shadow-sm p-4 flex flex-col gap-4"},{children:[t.jsxs("div",Object.assign({className:"flex flex-col gap-1"},{children:[t.jsx("h3",Object.assign({className:"font-semibold text-black/80 text-lg"},{children:(null==j?void 0:j["authentication-required"])||"Authentication Required"})),t.jsxs("p",Object.assign({className:"text-black/60 text-sm"},{children:[(null==j?void 0:j["smithery-auth-description-prefix"])||"The tool you are trying to use requires authentication with"," ",t.jsx("span",Object.assign({className:"font-semibold text-black/80"},{children:x||h})),"."]}))]})),N&&t.jsx(a.default,{error:N}),t.jsxs("div",Object.assign({className:"flex justify-end gap-2"},{children:[t.jsx(n.default,Object.assign({variant:"secondary",onClick:()=>k(!1),className:"text-sm px-3 h-9"},{children:(null==j?void 0:j.dismiss)||"Dismiss"})),t.jsx(n.default,Object.assign({variant:"primary",loadingText:(null==j?void 0:j.connecting)||"Connecting...",isLoading:y,style:{borderColor:_.accent,backgroundColor:_.accent,color:_.accentText},onClick:()=>e.__awaiter(void 0,void 0,void 0,(function*(){if(!y)if("LOGGED OUT"!==g)try{I(null),O(!0);const e=new l.SmitheryAuthProvider(q),t=new r.StreamableHTTPClientTransport(new URL(`https://server.smithery.ai/${h}/mcp`),{authProvider:e});S.current=t;const i=new s.Client({name:"Pickaxe",version:"1.0.0"});yield i.connect(t)}catch(e){console.log(o.default(e))}else I((null==j?void 0:j["must-be-logged-in-to-connect-smithery"])||"You must be logged in to connect Smithery MCPs.")})),className:"text-sm px-3 h-9 hover:opacity-90"},{children:(null==j?void 0:j.connect)||"Connect"}))]}))]})):null};
@@ -1,7 +1,9 @@
1
1
  import type { PickaxeHistoryMessage } from "../../../../types/history";
2
2
  interface SmitheryAuthData {
3
+ provider?: "smithery" | "composio";
3
4
  serverId: string;
4
- smitheryId: string;
5
+ smitheryId?: string;
6
+ toolkitSlug?: string;
5
7
  name: string;
6
8
  }
7
9
  interface MessageProps {
@@ -0,0 +1,9 @@
1
+ /// <reference types="react" />
2
+ interface ComposioConnectViewProps {
3
+ serverId: string;
4
+ toolkitSlug: string;
5
+ name?: string;
6
+ resubmitPrompt: () => void;
7
+ }
8
+ declare const ComposioConnectView: ({ serverId, toolkitSlug, name, resubmitPrompt, }: ComposioConnectViewProps) => JSX.Element | null;
9
+ export default ComposioConnectView;
@@ -1 +1 @@
1
- import e from"axios";const r=process.env.NEXT_PUBLIC_API_URL;if(!r)throw new Error("[px/react] NEXT_PUBLIC_API_URL is not defined");const o=process.env.NEXT_PUBLIC_API2_URL;if(!o)throw new Error("[px/react] NEXT_PUBLIC_API2_URL is not defined");e.create({baseURL:r});const t=e.create({baseURL:o});export{t as api2};
1
+ import e from"axios";const r=process.env.NEXT_PUBLIC_API_URL;if(!r)throw new Error("[px/react] NEXT_PUBLIC_API_URL is not defined");const o=process.env.NEXT_PUBLIC_API2_URL;if(!o)throw new Error("[px/react] NEXT_PUBLIC_API2_URL is not defined");const t=e.create({baseURL:r}),s=e.create({baseURL:o});export{t as api,s as api2};
@@ -1 +1 @@
1
- import{jsx as e,jsxs as s}from"react/jsx-runtime";import{useState as t,useEffect as i,Fragment as o}from"react";import{usePickaxeContext as a}from"../../../../hooks/pickaxe/usePickaxeContext.js";import{useStyleFontSize as n}from"../../../../hooks/studio/useStyleFontSize.js";import{useResponseContext as r}from"../../../../hooks/pickaxe/useResponseContext.js";import{useArtifact as c}from"../../Addons/Artifact/hooks/useArtifact.js";import{PickaxeMarkdown as l}from"../../common/PickaxeMarkdown/index.js";import m from"../../common/PickaxeIcon.js";import d from"./Document.js";import p from"../../common/PickaxeMessageActions.js";import h from"../../common/PickaxeMessageParts/index.js";import x from"../../../../common/cn.js";import{convertToIso1 as f}from"../../../../common/isoMap.js";import{franc as g}from"franc-min";import u from"../../common/SmitheryConnectView.js";import b from"remove-markdown";const w=({index:w,message:y,smitheryData:j,resubmitPrompt:v,isLastMessage:k=!1})=>{var O,N;const{pickaxeId:C,pickaxe:I,styles:S,colors:A,misc:P,responsiveBy:R,disableHtml:M,disableJs:H,disableCss:L,isNewChat:J,isRtl:T}=a(),{isGenerating:V}=r(),{onLoadArtifact:B}=c(),[D,F]=t(!1),[G,U]=t([]),W=n(),z=null!==(O=null==I?void 0:I.chaticon)&&void 0!==O?O:`https://cdn.mail.studio/chaticons/${C}.png`,E=k&&V,$=null==I?void 0:I.enablereadout;i((()=>{if(!$||"assistant"!==y.role)return;const e=()=>{const e=window.speechSynthesis.getVoices();e.length>0&&U(e)};return e(),window.speechSynthesis.onvoiceschanged=e,()=>{window.speechSynthesis.onvoiceschanged=null}}),[$,y.role]),i((()=>()=>{D&&window.speechSynthesis.cancel()}),[D]);const q=()=>{if(D)return window.speechSynthesis.cancel(),void F(!1);const e=y.parts.filter((e=>"text"===e.type)).map((e=>e.content)).join(" ");if(!e)return;const s=b(e,{stripListLeaders:!0,listUnicodeChar:"",gfm:!0,useImgAltText:!1}),t=g(s),i=f(t);window.speechSynthesis.cancel();const o=new SpeechSynthesisUtterance(s),a=G.find((e=>e.lang.startsWith(i)&&e.name.includes("Google")))||G.find((e=>e.lang.startsWith(i)));a?(o.voice=a,o.lang=a.lang):o.lang=i||"en",o.onstart=()=>F(!0),o.onend=()=>F(!1),o.onerror=()=>F(!1),window.speechSynthesis.speak(o)},K=!y.parts.some((e=>["text","reasoning","data-action-tool-caption"].includes(e.type)));return"assistant"===y.role?e("div",Object.assign({className:x("flex w-full",T?"justify-end":"justify-start")},{children:e("div",Object.assign({className:x("flex flex-col w-full",0===w&&J&&"viewport"===R&&"min-[767px]:max-w-[80%]",0===w&&J&&"container"===R&&"@[767px]/pickaxe-root:max-w-[80%]")},{children:s("div",Object.assign({className:x("flex gap-x-3",T&&"flex-row-reverse")},{children:[P.isChatImage&&"NONE"!==z&&e(m,{src:z,alt:"Assistant",width:24,height:24,className:"my-3 h-6 w-6",textColor:A.text}),s("div",Object.assign({className:x("flex flex-col flex-grow",T?"items-end":"items-start")},{children:[s("div",Object.assign({className:x(W.b2,"chat-message pt-3 w-full",T?"text-right":"text-left")},{children:[e(l,Object.assign({theme:S.theme,colors:A},T&&{rtl:!0},M&&{disableHtml:!0},H&&{disableJs:!0},L&&{disableCss:!0},{disableReasoning:null!==(N=null==I?void 0:I.enablereasoningdisplay)&&void 0!==N&&N,onArtifactClick:B},{children:e(h,{parts:y.parts})})),k&&j&&v&&e("div",Object.assign({className:"mt-4 px-1"},{children:e(u,{serverId:j.serverId,smitheryId:j.smitheryId,name:j.smitheryId,resubmitPrompt:()=>v()})}))]})),e("div",Object.assign({className:x("flex flex-col gap-6 my-4",K&&"mt-2")},{children:E?e("div",Object.assign({className:"flex items-center gap-x-2 rounded"},{children:Array.from({length:3}).map(((s,t)=>e("div",{className:x("h-1.5 w-1.5 animate-dot rounded-full",1===t&&"animate-dot-down"),style:{backgroundColor:A.secondaryText}},t)))})):e(p,Object.assign({content:y.parts.filter((e=>e.isVisible&&"text"===e.type)).map((e=>e.content)).join("\n"),index:w},"intromessage"===y.area&&{isHideFeedback:!0},{onReadOut:q,isReadOut:$||!1,isReading:D}))}))]}))]}))}))})):"user"===y.role?e("div",Object.assign({className:x("flex w-full",T?"justify-start":"justify-end")},{children:e("div",Object.assign({className:x("flex gap-x-3 max-w-[80%]",T?"pr-9":"pl-9","viewport"===R?T?"min-[767px]:pr-0":"min-[767px]:pl-0":T?"@[767px]/pickaxe-root:pr-0":"@[767px]/pickaxe-root:pl-0")},{children:s("div",Object.assign({className:x(W.b2,"overflow-x-auto overflow-y-hidden px-4 py-3 scrollbar-thin scrollbar-track-white scrollbar-thumb-[#4A4A4B] flex flex-col gap-y-3",T?"text-right":"text-left"),style:{backgroundColor:A.secondary+"80",color:A.secondaryText,borderRadius:S.cornerRadius}},{children:[y.documentIds&&y.documentIds.length>0&&e("div",Object.assign({className:x("flex flex-col gap-y-2",T?"items-start":"items-end")},{children:y.documentIds.map((s=>e(o,{children:e(d,{documentId:s})},s)))})),e(l,Object.assign({theme:S.theme,colors:A},T&&{rtl:!0},M&&{disableHtml:!0},H&&{disableJs:!0},L&&{disableCss:!0},{children:e(h,{parts:y.parts})}))]}))}))})):e("div",{})};export{w as default};
1
+ import{jsx as e,jsxs as s}from"react/jsx-runtime";import{useState as t,useEffect as i,Fragment as o}from"react";import{usePickaxeContext as n}from"../../../../hooks/pickaxe/usePickaxeContext.js";import{useStyleFontSize as a}from"../../../../hooks/studio/useStyleFontSize.js";import{useResponseContext as r}from"../../../../hooks/pickaxe/useResponseContext.js";import{useArtifact as c}from"../../Addons/Artifact/hooks/useArtifact.js";import{PickaxeMarkdown as l}from"../../common/PickaxeMarkdown/index.js";import m from"../../common/PickaxeIcon.js";import d from"./Document.js";import p from"../../common/PickaxeMessageActions.js";import h from"../../common/PickaxeMessageParts/index.js";import x from"../../../../common/cn.js";import{convertToIso1 as f}from"../../../../common/isoMap.js";import{franc as g}from"franc-min";import u from"../../common/ComposioConnectView.js";import b from"../../common/SmitheryConnectView.js";import w from"remove-markdown";const v=({index:v,message:j,smitheryData:y,resubmitPrompt:k,isLastMessage:O=!1})=>{var N,C;const{pickaxeId:I,pickaxe:S,styles:A,colors:P,misc:R,responsiveBy:M,disableHtml:H,disableJs:L,disableCss:V,isNewChat:J,isRtl:T}=n(),{isGenerating:B}=r(),{onLoadArtifact:D}=c(),[F,G]=t(!1),[U,W]=t([]),z=a(),E=null!==(N=null==S?void 0:S.chaticon)&&void 0!==N?N:`https://cdn.mail.studio/chaticons/${I}.png`,$=O&&B,q=null==S?void 0:S.enablereadout;i((()=>{if(!q||"assistant"!==j.role)return;const e=()=>{const e=window.speechSynthesis.getVoices();e.length>0&&W(e)};return e(),window.speechSynthesis.onvoiceschanged=e,()=>{window.speechSynthesis.onvoiceschanged=null}}),[q,j.role]),i((()=>()=>{F&&window.speechSynthesis.cancel()}),[F]);const K=()=>{if(F)return window.speechSynthesis.cancel(),void G(!1);const e=j.parts.filter((e=>"text"===e.type)).map((e=>e.content)).join(" ");if(!e)return;const s=w(e,{stripListLeaders:!0,listUnicodeChar:"",gfm:!0,useImgAltText:!1}),t=g(s),i=f(t);window.speechSynthesis.cancel();const o=new SpeechSynthesisUtterance(s),n=U.find((e=>e.lang.startsWith(i)&&e.name.includes("Google")))||U.find((e=>e.lang.startsWith(i)));n?(o.voice=n,o.lang=n.lang):o.lang=i||"en",o.onstart=()=>G(!0),o.onend=()=>G(!1),o.onerror=()=>G(!1),window.speechSynthesis.speak(o)},Q=!j.parts.some((e=>["text","reasoning","data-action-tool-caption"].includes(e.type)));return"assistant"===j.role?e("div",Object.assign({className:x("flex w-full",T?"justify-end":"justify-start")},{children:e("div",Object.assign({className:x("flex flex-col w-full",0===v&&J&&"viewport"===M&&"min-[767px]:max-w-[80%]",0===v&&J&&"container"===M&&"@[767px]/pickaxe-root:max-w-[80%]")},{children:s("div",Object.assign({className:x("flex gap-x-3",T&&"flex-row-reverse")},{children:[R.isChatImage&&"NONE"!==E&&e(m,{src:E,alt:"Assistant",width:24,height:24,className:"my-3 h-6 w-6",textColor:P.text}),s("div",Object.assign({className:x("flex flex-col flex-grow",T?"items-end":"items-start")},{children:[s("div",Object.assign({className:x(z.b2,"chat-message pt-3 w-full",T?"text-right":"text-left")},{children:[e(l,Object.assign({theme:A.theme,colors:P},T&&{rtl:!0},H&&{disableHtml:!0},L&&{disableJs:!0},V&&{disableCss:!0},{disableReasoning:null!==(C=null==S?void 0:S.enablereasoningdisplay)&&void 0!==C&&C,onArtifactClick:D},{children:e(h,{parts:j.parts})})),O&&y&&k&&("composio"===y.provider?e("div",Object.assign({className:"mt-4 px-1"},{children:e(u,{serverId:y.serverId,toolkitSlug:y.toolkitSlug||"",name:y.name,resubmitPrompt:()=>k()})})):e("div",Object.assign({className:"mt-4 px-1"},{children:e(b,{serverId:y.serverId,smitheryId:y.smitheryId||"",name:y.name||y.smitheryId,resubmitPrompt:()=>k()})})))]})),e("div",Object.assign({className:x("flex flex-col gap-6 my-4",Q&&"mt-2")},{children:$?e("div",Object.assign({className:"flex items-center gap-x-2 rounded"},{children:Array.from({length:3}).map(((s,t)=>e("div",{className:x("h-1.5 w-1.5 animate-dot rounded-full",1===t&&"animate-dot-down"),style:{backgroundColor:P.secondaryText}},t)))})):e(p,Object.assign({content:j.parts.filter((e=>e.isVisible&&"text"===e.type)).map((e=>e.content)).join("\n"),index:v},"intromessage"===j.area&&{isHideFeedback:!0},{onReadOut:K,isReadOut:q||!1,isReading:F}))}))]}))]}))}))})):"user"===j.role?e("div",Object.assign({className:x("flex w-full",T?"justify-start":"justify-end")},{children:e("div",Object.assign({className:x("flex gap-x-3 max-w-[80%]",T?"pr-9":"pl-9","viewport"===M?T?"min-[767px]:pr-0":"min-[767px]:pl-0":T?"@[767px]/pickaxe-root:pr-0":"@[767px]/pickaxe-root:pl-0")},{children:s("div",Object.assign({className:x(z.b2,"overflow-x-auto overflow-y-hidden px-4 py-3 scrollbar-thin scrollbar-track-white scrollbar-thumb-[#4A4A4B] flex flex-col gap-y-3",T?"text-right":"text-left"),style:{backgroundColor:P.secondary+"80",color:P.secondaryText,borderRadius:A.cornerRadius}},{children:[j.documentIds&&j.documentIds.length>0&&e("div",Object.assign({className:x("flex flex-col gap-y-2",T?"items-start":"items-end")},{children:j.documentIds.map((s=>e(o,{children:e(d,{documentId:s})},s)))})),e(l,Object.assign({theme:A.theme,colors:P},T&&{rtl:!0},H&&{disableHtml:!0},L&&{disableJs:!0},V&&{disableCss:!0},{children:e(h,{parts:j.parts})}))]}))}))})):e("div",{})};export{v as default};
@@ -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 j}from"../Addons/Artifact/hooks/useArtifactContext.js";import{useHover as I}from"../../../hooks/core/useHover.js";import{useMediaQuery as w}from"../../../hooks/core/useMediaQuery.js";import{allowedFileMimeTypes as O,allowedImageMimeTypes as k,additionalAllowedFileExtensions as N}from"../../../common/documents.js";import{createParser as S}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:je,portalId:Ie,deploymentId:we,deploymentType:Oe,pickaxe:ke,styles:Ne,colors:Se,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}=j(),{height:mt}=v(),pt=h(),[ft,gt]=r(""),[ht,vt]=r(!1),[bt,yt]=r(!1),[xt,jt]=r(null),[It,wt]=r(null),[Ot,kt]=r(!1),[Nt,St]=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=I(),{isHover:Qt}=qt,Yt=e(qt,["isHover"]),Zt=I(),{isHover:en}=Zt,tn=e(Zt,["isHover"]),nn=I(),{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)&&(jt(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 jn=Number(null!==(le=null==Pe?void 0:Pe.limit)&&void 0!==le?le:0),In="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:Ie})),[we,Ie,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:Ie,accessGroupId:null!==(t=null==Pe?void 0:Pe.accessGroupId)&&void 0!==t?t:null,pickaxeId:be,sender:xe,senderType:je,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,Ie,xe,je,ye,xt]),Nn=l((()=>!!(fn&&Ot&&ye)&&(!!Bt.current.has(ye)&&(V(kn()),Bt.current.delete(ye),!0))),[kn,Ot,ye,fn]);c((()=>{if(!Ot||!ye)return;Nn();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)}),[Nn,kn,Ot,ye]);const Sn={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:Sn;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:jn,limitInterval:In}),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:jn,limitInterval:In}),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&&(!Nt&&(Tn!==G&&Tn<=Ln))),[Nt,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_API_URL}/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:je,value:d},u&&{documentIds:l}),xe&&{sender:xe}),Ke&&{studioSessionToken:Ke}),!Ke&&!xe&&{sender:X()}),Ie&&{portalId:Ie}),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?(Nn(),F(y)):Xt.current=y,ze("streaming"),$t.current=new AbortController;const x=m.length-1,j=[];let I=[...null!=lt?lt:[]],w=0,O=!1,k="";for(;!O;)try{const e=yield fetch(`${process.env.NEXT_PUBLIC_PICKAXE_API_URL}/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=S({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){if(/['"]type['"]\s*:\s*['"]unauthorized_smithery['"]/.test(e)){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({smitheryId: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({smitheryId:t.qualifiedName,serverId:t.serverId,name:t.name}),new Error("STOP_STREAM")}}else if("text-start"===s.type)k="",j.push({type:"text",content:"",isVisible:null===(t=s.isVisible)||void 0===t||t});else if("text-delta"===s.type)k+=s.delta,j[j.length-1].content=k;else if("text-end"===s.type)k="";else if("reasoning-start"===s.type)k="",j.push({type:"reasoning",content:"",isVisible:null===(n=s.isVisible)||void 0===n||n});else if("reasoning-delta"===s.type)k+=s.delta,j[j.length-1].content=k;else if("reasoning-end"===s.type)k="";else if(s.type.startsWith("data-")){const e=s;j.push({type:e.type,content:JSON.stringify(e.data),isVisible:!0})}Dt.current=z(j),Je([...m.slice(0,x),Object.assign(Object.assign({},m[m.length-1]),{id:We.length+1,role:"assistant",parts:j})])}else if("artifact_created"===e.event){const t=JSON.parse(e.data);I=I.filter((e=>!(e.id===t.id&&e.version===t.version))),I.push(Object.assign(Object.assign({},t),{content:"",status:"streaming"})),dt([...I]),ct.startsWith("inline")||ut({id:t.id,version:t.version})}else if("artifact_updated"===e.event){const t=JSON.parse(e.data);I=I.filter((e=>!(e.id===t.id&&e.version===t.version))),I.push(Object.assign(Object.assign({},t),{content:"",status:"updating"})),dt(I),ct.startsWith("inline")||ut({id:t.id,version:t.version})}else if("artifact_rewrite"===e.event){const t=JSON.parse(e.data);I=I.filter((e=>!(e.id===t.id&&e.version===t.version))),I.push(Object.assign(Object.assign({},t),{content:"",status:"streaming"})),dt(I),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,"");I=I.map((e=>e.id===t.id&&e.version===t.version?Object.assign(Object.assign({},e),{content:e.content+n,status:"streaming"}):e)),dt(I)}else if("artifact_finished"===e.event){const t=JSON.parse(e.data);dt(I.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"===Ne.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:Se.text+"20",color:Se.text,borderTopRightRadius:Ne.cornerRadius+"px",borderTopLeftRadius:Ne.cornerRadius+"px"}},{children:[n("div",Object.assign({className:"flex items-center gap-2 text-sm font-medium"},{children: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:Se.accent,color:Se.accentText},onClick:e=>{if(e.preventDefault(),e.stopPropagation(),Mn)return void window.open(Mn,"_blank","noopener,noreferrer");const t=$({baseUrl:It,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:()=>St(!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=Se.accent)&&void 0!==he?he:"#ff0000"}}),n("span",Object.assign({className:"text-sm text-c-secondary font-semilight",style:{color:Se.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:Ne.cornerRadius+"px",borderBottomRightRadius:Ne.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_API_URL}/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:Se.accent,color:Se.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:Se.accent,color:Se.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?Se.accent+"10":void 0,color:en?Se.accent:Se.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,...N].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?Se.accent:sn?Se.accent+"10":void 0,color:Ft?Se.accentText:sn?Se.accent:Se.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?Se.accent:Se.accent+"10",color:Qt||Xn?Se.accentText:Se.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};
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_API_URL}/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_API_URL}/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_API_URL}/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};
@@ -0,0 +1 @@
1
+ import{__awaiter as o}from"../../../_virtual/_tslib.js";import{jsxs as e,jsx as t}from"react/jsx-runtime";import{useRef as n,useState as i}from"react";import s from"../../../common/error.js";import r from"../../Core/Button.js";import c from"../../Core/ErrorAlert.js";import{api as l}from"../../../common/api/api.js";import{initializeEmbedUserId as a}from"../../../common/utils.js";import{useAuthContext as d}from"../Addons/Auth/hooks/useAuthContext.js";import{usePickaxeContext as u}from"../../../hooks/pickaxe/usePickaxeContext.js";const m=({serverId:m,toolkitSlug:p,name:f,resubmitPrompt:g})=>{const{pickaxe:h,sender:b,translations:x,colors:v}=u(),{token:j}=d(),k=n(null),[O,y]=i(!0),[C,w]=i(!1),[N,T]=i(null),A=()=>{if(b)return b;if(k.current)return k.current;const o=a();return k.current=o,o},I=()=>{const o={serverId:m,studioId:null==h?void 0:h.studioid};return j?Object.assign(Object.assign({},o),{studioSessionToken:j}):Object.assign(Object.assign({},o),{userId:A()})};return O?e("div",Object.assign({className:"w-full bg-white border border-c-sep rounded-lg shadow-sm p-4 flex flex-col gap-4"},{children:[e("div",Object.assign({className:"flex flex-col gap-1"},{children:[t("h3",Object.assign({className:"font-semibold text-black/80 text-lg"},{children:(null==x?void 0:x["authentication-required"])||"Authentication Required"})),e("p",Object.assign({className:"text-black/60 text-sm"},{children:[(null==x?void 0:x["composio-auth-description-prefix"])||"The tool you are trying to use requires authentication with"," ",t("span",Object.assign({className:"font-semibold text-black/80"},{children:f||p})),"."]}))]})),N&&t(c,{error:N}),e("div",Object.assign({className:"flex justify-end gap-2"},{children:[t(r,Object.assign({variant:"secondary",onClick:()=>y(!1),className:"text-sm px-3 h-9"},{children:(null==x?void 0:x.dismiss)||"Dismiss"})),t(r,Object.assign({variant:"primary",loadingText:(null==x?void 0:x.connecting)||"Connecting...",isLoading:C,style:{borderColor:v.accent,backgroundColor:v.accent,color:v.accentText},onClick:()=>o(void 0,void 0,void 0,(function*(){if(C)return;const e=I();if("LOGGED OUT"!==e.userId)try{T(null),w(!0);const t=yield l.post("/mcp/composio/connect",e),{connectLinkUrl:n,connected:i}=t.data;if(n&&window.open(n,"_blank","noopener,noreferrer"),!i){const e=yield o(void 0,void 0,void 0,(function*(){for(let o=0;o<180;o+=1){const o=yield l.post("/mcp/composio/status",I()),{connected:e}=o.data;if(e)return!0;yield new Promise((o=>setTimeout(o,1e3)))}return!1}));if(!e)throw new Error((null==x?void 0:x["composio-auth-timeout"])||"Composio authentication timed out.")}y(!1),g()}catch(o){T(s(o))}finally{w(!1)}else T((null==x?void 0:x["must-be-logged-in-to-connect-composio"])||"You must be logged in to connect Composio MCPs.")})),className:"text-sm px-3 h-9 hover:opacity-90"},{children:(null==x?void 0:x.connect)||"Connect"}))]}))]})):null};export{m as default};
@@ -1 +1 @@
1
- import{__awaiter as e}from"../../../../../../_virtual/_tslib.js";import{jsxs as t,jsx as o}from"react/jsx-runtime";import{useState as n}from"react";import{usePickaxeContext as i}from"../../../../../../hooks/pickaxe/usePickaxeContext.js";import{useAuthContext as l}from"../../../../Addons/Auth/hooks/useAuthContext.js";import{useSubmitDocument as a}from"../../../../../../hooks/pickaxe/useSubmitDocument.js";import{usePickaxeMarkdownContext as r}from"../../hooks/usePickaxeMarkdownContext.js";import s from"../../../../../Icons/download.svg.js";import c from"../../../../../Icons/copy.svg.js";import d from"../../../../../Icons/copied.svg.js";import m from"../../../../../Icons/file.svg.js";import p from"../../../../../Icons/upload-cloud.svg.js";import u from"copy-to-clipboard";import f from"../../../../../../common/error.js";const h=/(?:https?:\/\/|www\.)[^\s<>"']+/gi,b=new Set(["jpeg","jpg","gif","bmp","webp","svg","tiff","avif","png","jfif","pjpeg","pjp"]),v=new Set(["mp3","wav","ogg","flac","aac","wma","alac","m4a","aiff","ape","au","mid","midi","opus"]),w=new Set(["mp4","webm","mov","avi","mkv","m4v"]),g=new Set(["csv","tsv","txt","json","xml","md","log","yaml","yml"]),x=new Set(["doc","docx","xls","xlsx","ppt","pptx"]),k=new Set(["pdf","html","htm",...g,...x]),y=e=>b.has(e)?"image":v.has(e)?"audio":w.has(e)?"video":"pdf"===e?"pdf":"html"===e||"htm"===e?"html":g.has(e)?"text":x.has(e)?"office":"file",j=e=>{const t=(e=>{let t=e.trim();for(;/[),.;!?]$/.test(t);)t=t.slice(0,-1);return t})(e);return t.startsWith("http://")?`https://${t.slice(7)}`:t.startsWith("www.")?`https://${t}`:t},N=e=>{try{return new URL(j(e)).pathname.includes("/action_generated_files/")}catch(e){return!1}},C=e=>{try{return new URL(j(e)).pathname.includes("/documentinterrogation/")}catch(e){return!1}},O=e=>{const t=j(e);if(N(t))return!1;if(C(t))return!0;if((e=>{const t=j(e);return/(?:youtube\.com\/watch\?v=|youtu\.be\/)([\w-]+)/i.test(t)||/loom\.com\/(?:share|embed)\/([\w-]+)/i.test(t)||/vimeo\.com\/(?:video\/)?(\d+)/i.test(t)||/streamable\.com\/([\w-]+)/i.test(t)})(t))return!0;const o=(e=>{var t,o,n,i;try{const l=new URL(j(e));return"https:"!==l.protocol&&"http:"!==l.protocol?null:null!==(i=null===(n=null===(o=null===(t=l.pathname.split("/").filter(Boolean).pop())||void 0===t?void 0:t.match(/\.([a-z0-9]{1,10})$/i))||void 0===o?void 0:o[1])||void 0===n?void 0:n.toLowerCase())&&void 0!==i?i:null}catch(e){return null}})(t);return!!o&&k.has(o)},I=(e,t)=>{const o=j(e);return O(o)||(null==t?void 0:t.has(o))},S=(e,t)=>{for(const o of e.matchAll(h))if(I(o[0],t))return!0;return!1},F=e=>{var t,o;try{const n=j(e),i=new URL(n);if("https:"!==i.protocol&&"http:"!==i.protocol)return null;const l=i.pathname.split("/").filter(Boolean).pop();if(!l)return null;const a=decodeURIComponent(l),r=null===(o=null===(t=a.match(/\.([a-z0-9]{1,10})$/i))||void 0===t?void 0:t[1])||void 0===o?void 0:o.toLowerCase();return r?{url:n,fileName:a,extension:r,kind:y(r)}:null}catch(e){return null}},$=(e,t)=>!!e&&(!t||!t.current.has(e.url)&&(t.current.add(e.url),!0)),D=({fileInfo:h,displayName:b})=>{const{theme:v,colors:w,disableHtml:g,disableJs:x}=r(),{contextId:k,pickaxeId:y,pickaxe:j,translations:N}=i(),{isLoggedIn:C,token:O}=l(),I=a(),[S,F]=n(!1),[$,D]=n(!1),[R,U]=n(!1),L=(e,t)=>{var o;return null!==(o=null==N?void 0:N[e])&&void 0!==o?o:t},B="dark"===v?"#30363D":"#D0D7DE",T="dark"===v?"#0D1117":"#F6F8FA",_="dark"===v?"#161B22":"#FFFFFF",A=(null==b?void 0:b.trim())||h.fileName,E=A!==h.fileName,P={display:"inline-flex",width:32,height:32,alignItems:"center",justifyContent:"center",borderRadius:4,color:w.accentText,backgroundColor:w.accent,opacity:.88,flexShrink:0},z=(e,n,i)=>o("div",Object.assign({className:"flex w-full p-4"},{children:t("div",Object.assign({className:"relative w-full overflow-hidden rounded-md shadow-sm",style:{aspectRatio:"8.5 / 11",backgroundColor:_,border:`1px solid ${B}`}},{children:[o("iframe",Object.assign({src:e,title:n},i,{className:"h-full w-full",scrolling:"no",tabIndex:-1,style:{border:"none",pointerEvents:"none"}})),o("div",{className:"pointer-events-none absolute inset-x-0 bottom-0 h-10",style:{background:"dark"===v?"linear-gradient(to top, rgba(22,27,34,0.95), rgba(22,27,34,0))":"linear-gradient(to top, rgba(255,255,255,0.95), rgba(255,255,255,0))"}})]}))}));return t("div",Object.assign({className:"my-2 w-full overflow-hidden rounded-lg",style:{border:`1px solid ${B}`,backgroundColor:T,color:w.secondaryText}},{children:[t("div",Object.assign({className:"flex items-center justify-between gap-3 border-b px-3 py-2",style:{borderColor:B}},{children:[o("a",Object.assign({href:h.url,target:"_blank",rel:"noopener noreferrer",className:"min-w-0 flex-1 truncate text-sm font-semibold hover:underline",style:{color:w.secondaryText},title:E?`${A} (${h.fileName})`:A},{children:A})),t("div",Object.assign({className:"flex shrink-0 items-center gap-1.5"},{children:[o("button",Object.assign({type:"button",onClick:()=>{const e=document.createElement("a");e.href=h.url,e.download=h.fileName,e.target="_blank",e.rel="noopener noreferrer",e.click()},title:L("download","Download"),"aria-label":L("download","Download"),style:P},{children:o(s,{className:"h-[18px] w-[18px]"})})),o("button",Object.assign({type:"button",onClick:()=>{e(void 0,void 0,void 0,(function*(){try{F(!0),u(h.url),yield new Promise((e=>setTimeout(e,1500)))}finally{F(!1)}}))},title:S?L("copied","Copied"):L("copy-link","Copy link"),"aria-label":S?L("copied","Copied"):L("copy-link","Copy link"),style:Object.assign(Object.assign({},P),{opacity:S?1:P.opacity})},{children:o(S?d:c,{className:"h-[18px] w-[18px]"})})),C&&O&&o("button",Object.assign({type:"button",disabled:$||R,onClick:()=>{e(void 0,void 0,void 0,(function*(){if(O&&!$){D(!0),U(!1);try{const e=yield fetch(h.url);if(!e.ok)throw new Error("Failed to download generated file.");const t=yield e.blob(),o=new File([t],h.fileName,{type:t.type||"application/octet-stream"});yield I.document(Object.assign(Object.assign({contextId:k,pickaxeId:y,file:o},(null==j?void 0:j.workspaceid)&&{workspaceId:j.workspaceid}),{studioSessionToken:O,isUserDocument:!0})),U(!0),yield new Promise((e=>setTimeout(e,1500)))}catch(e){alert(f(e))}finally{D(!1),U(!1)}}}))},title:$?L("saving","Saving..."):R?L("saved","Saved"):L("save-to-knowledge-base","Save to Knowledge Base"),"aria-label":$?L("saving","Saving..."):R?L("saved","Saved"):L("save-to-knowledge-base","Save to Knowledge Base"),style:Object.assign(Object.assign({},P),{opacity:$||R?.55:P.opacity,cursor:$||R?"not-allowed":"pointer"})},{children:o(p,{className:"h-[18px] w-[18px]"})}))]}))]})),o("div",{children:(()=>{if("image"===h.kind)return o("img",{src:h.url,alt:h.fileName,className:"block max-h-[420px] w-full object-contain"});if("audio"===h.kind)return o("div",Object.assign({className:"flex min-h-[72px] items-center p-4"},{children:o("audio",{className:"w-full",controls:!0,src:h.url})}));if("video"===h.kind)return o("video",{className:"block max-h-[420px] w-full bg-black",controls:!0,preload:"metadata",src:h.url});if("pdf"===h.kind||"text"===h.kind){const e="pdf"===h.kind?`${h.url}#page=1&toolbar=0&navpanes=0&scrollbar=0&view=FitH`:h.url;return z(e,h.fileName)}if("html"===h.kind&&!g){const e=["allow-same-origin","allow-forms","allow-popups","allow-downloads","allow-modals",x?"":"allow-scripts"].filter(Boolean).join(" ");return z(h.url,h.fileName,{sandbox:e})}return"office"===h.kind?z(`https://view.officeapps.live.com/op/embed.aspx?src=${encodeURIComponent(h.url)}`,h.fileName):t("div",Object.assign({className:"flex min-h-[120px] items-center justify-center gap-3 p-6 text-sm"},{children:[o(m,{className:"h-8 w-8 shrink-0"}),o("span",Object.assign({className:"break-all"},{children:h.extension.toUpperCase()}))]}))})()})]}))};export{D as default,F as getFilePreviewInfo,C as isDocumentSourceUrl,N as isGeneratedFileUrl,O as isSourceLikeRichPreviewUrl,j as normalizeMarkdownUrl,$ as shouldRenderFilePreview,I as shouldSuppressRichPreviewForUrl,S as shouldSuppressRichPreviewInText};
1
+ import{__awaiter as e}from"../../../../../../_virtual/_tslib.js";import{jsxs as t,jsx as o}from"react/jsx-runtime";import{useState as n}from"react";import{usePickaxeContext as i}from"../../../../../../hooks/pickaxe/usePickaxeContext.js";import{useAuthContext as l}from"../../../../Addons/Auth/hooks/useAuthContext.js";import{useSubmitDocument as r}from"../../../../../../hooks/pickaxe/useSubmitDocument.js";import{usePickaxeMarkdownContext as a}from"../../hooks/usePickaxeMarkdownContext.js";import s from"../../../../../Icons/download.svg.js";import c from"../../../../../Icons/copy.svg.js";import d from"../../../../../Icons/copied.svg.js";import m from"../../../../../Icons/file.svg.js";import p from"../../../../../Icons/upload-cloud.svg.js";import u from"copy-to-clipboard";import f from"../../../../../../common/error.js";const h=/(?:https?:\/\/|www\.)[^\s<>"']+/gi,b=new Set(["jpeg","jpg","gif","bmp","webp","svg","tiff","avif","png","jfif","pjpeg","pjp"]),v=new Set(["mp3","wav","ogg","flac","aac","wma","alac","m4a","aiff","ape","au","mid","midi","opus"]),w=new Set(["mp4","webm","mov","avi","mkv","m4v"]),g=new Set(["csv","tsv","txt","json","xml","md","log","yaml","yml"]),x=new Set(["doc","docx","xls","xlsx","ppt","pptx"]),k=new Set(["pdf","html","htm",...g,...x]),y=e=>b.has(e)?"image":v.has(e)?"audio":w.has(e)?"video":"pdf"===e?"pdf":"html"===e||"htm"===e?"html":g.has(e)?"text":x.has(e)?"office":"file",j=e=>{const t=(e=>{let t=e.trim();for(;/[),.;!?]$/.test(t);)t=t.slice(0,-1);return t})(e);return t.startsWith("http://")?`https://${t.slice(7)}`:t.startsWith("www.")?`https://${t}`:t},N=e=>{try{return new URL(j(e)).pathname.includes("/action_generated_files/")}catch(e){return!1}},C=e=>{try{return new URL(j(e)).pathname.includes("/documentinterrogation/")}catch(e){return!1}},O=e=>{const t=j(e);return/(?:youtube\.com\/watch\?v=|youtu\.be\/)([\w-]+)/i.test(t)},I=e=>{const t=j(e);if(N(t))return!1;if(C(t))return!0;if(O(t))return!1;if((e=>{const t=j(e);return/loom\.com\/(?:share|embed)\/([\w-]+)/i.test(t)||/vimeo\.com\/(?:video\/)?(\d+)/i.test(t)||/streamable\.com\/([\w-]+)/i.test(t)})(t))return!0;const o=(e=>{var t,o,n,i;try{const l=new URL(j(e));return"https:"!==l.protocol&&"http:"!==l.protocol?null:null!==(i=null===(n=null===(o=null===(t=l.pathname.split("/").filter(Boolean).pop())||void 0===t?void 0:t.match(/\.([a-z0-9]{1,10})$/i))||void 0===o?void 0:o[1])||void 0===n?void 0:n.toLowerCase())&&void 0!==i?i:null}catch(e){return null}})(t);return!!o&&k.has(o)},S=(e,t)=>{const o=j(e);return!O(o)&&(I(o)||(null==t?void 0:t.has(o)))},F=(e,t)=>{for(const o of e.matchAll(h))if(S(o[0],t))return!0;return!1},$=e=>{var t,o;try{const n=j(e),i=new URL(n);if("https:"!==i.protocol&&"http:"!==i.protocol)return null;const l=i.pathname.split("/").filter(Boolean).pop();if(!l)return null;const r=decodeURIComponent(l),a=null===(o=null===(t=r.match(/\.([a-z0-9]{1,10})$/i))||void 0===t?void 0:t[1])||void 0===o?void 0:o.toLowerCase();return a?{url:n,fileName:r,extension:a,kind:y(a)}:null}catch(e){return null}},D=(e,t)=>!!e&&(!t||!t.current.has(e.url)&&(t.current.add(e.url),!0)),R=({fileInfo:h,displayName:b})=>{const{theme:v,colors:w,disableHtml:g,disableJs:x}=a(),{contextId:k,pickaxeId:y,pickaxe:j,translations:N}=i(),{isLoggedIn:C,token:O}=l(),I=r(),[S,F]=n(!1),[$,D]=n(!1),[R,U]=n(!1),L=(e,t)=>{var o;return null!==(o=null==N?void 0:N[e])&&void 0!==o?o:t},B="dark"===v?"#30363D":"#D0D7DE",T="dark"===v?"#0D1117":"#F6F8FA",_="dark"===v?"#161B22":"#FFFFFF",A=(null==b?void 0:b.trim())||h.fileName,E=A!==h.fileName,P={display:"inline-flex",width:32,height:32,alignItems:"center",justifyContent:"center",borderRadius:4,color:w.accentText,backgroundColor:w.accent,opacity:.88,flexShrink:0},z=(e,n,i)=>o("div",Object.assign({className:"flex w-full p-4"},{children:t("div",Object.assign({className:"relative w-full overflow-hidden rounded-md shadow-sm",style:{aspectRatio:"8.5 / 11",backgroundColor:_,border:`1px solid ${B}`}},{children:[o("iframe",Object.assign({src:e,title:n},i,{className:"h-full w-full",scrolling:"no",tabIndex:-1,style:{border:"none",pointerEvents:"none"}})),o("div",{className:"pointer-events-none absolute inset-x-0 bottom-0 h-10",style:{background:"dark"===v?"linear-gradient(to top, rgba(22,27,34,0.95), rgba(22,27,34,0))":"linear-gradient(to top, rgba(255,255,255,0.95), rgba(255,255,255,0))"}})]}))}));return t("div",Object.assign({className:"my-2 w-full overflow-hidden rounded-lg",style:{border:`1px solid ${B}`,backgroundColor:T,color:w.secondaryText}},{children:[t("div",Object.assign({className:"flex items-center justify-between gap-3 border-b px-3 py-2",style:{borderColor:B}},{children:[o("a",Object.assign({href:h.url,target:"_blank",rel:"noopener noreferrer",className:"min-w-0 flex-1 truncate text-sm font-semibold hover:underline",style:{color:w.secondaryText},title:E?`${A} (${h.fileName})`:A},{children:A})),t("div",Object.assign({className:"flex shrink-0 items-center gap-1.5"},{children:[o("button",Object.assign({type:"button",onClick:()=>{const e=document.createElement("a");e.href=h.url,e.download=h.fileName,e.target="_blank",e.rel="noopener noreferrer",e.click()},title:L("download","Download"),"aria-label":L("download","Download"),style:P},{children:o(s,{className:"h-[18px] w-[18px]"})})),o("button",Object.assign({type:"button",onClick:()=>{e(void 0,void 0,void 0,(function*(){try{F(!0),u(h.url),yield new Promise((e=>setTimeout(e,1500)))}finally{F(!1)}}))},title:S?L("copied","Copied"):L("copy-link","Copy link"),"aria-label":S?L("copied","Copied"):L("copy-link","Copy link"),style:Object.assign(Object.assign({},P),{opacity:S?1:P.opacity})},{children:o(S?d:c,{className:"h-[18px] w-[18px]"})})),C&&O&&o("button",Object.assign({type:"button",disabled:$||R,onClick:()=>{e(void 0,void 0,void 0,(function*(){if(O&&!$){D(!0),U(!1);try{const e=yield fetch(h.url);if(!e.ok)throw new Error("Failed to download generated file.");const t=yield e.blob(),o=new File([t],h.fileName,{type:t.type||"application/octet-stream"});yield I.document(Object.assign(Object.assign({contextId:k,pickaxeId:y,file:o},(null==j?void 0:j.workspaceid)&&{workspaceId:j.workspaceid}),{studioSessionToken:O,isUserDocument:!0})),U(!0),yield new Promise((e=>setTimeout(e,1500)))}catch(e){alert(f(e))}finally{D(!1),U(!1)}}}))},title:$?L("saving","Saving..."):R?L("saved","Saved"):L("save-to-knowledge-base","Save to Knowledge Base"),"aria-label":$?L("saving","Saving..."):R?L("saved","Saved"):L("save-to-knowledge-base","Save to Knowledge Base"),style:Object.assign(Object.assign({},P),{opacity:$||R?.55:P.opacity,cursor:$||R?"not-allowed":"pointer"})},{children:o(p,{className:"h-[18px] w-[18px]"})}))]}))]})),o("div",{children:(()=>{if("image"===h.kind)return o("img",{src:h.url,alt:h.fileName,className:"block max-h-[420px] w-full object-contain"});if("audio"===h.kind)return o("div",Object.assign({className:"flex min-h-[72px] items-center p-4"},{children:o("audio",{className:"w-full",controls:!0,src:h.url})}));if("video"===h.kind)return o("video",{className:"block max-h-[420px] w-full bg-black",controls:!0,preload:"metadata",src:h.url});if("pdf"===h.kind||"text"===h.kind){const e="pdf"===h.kind?`${h.url}#page=1&toolbar=0&navpanes=0&scrollbar=0&view=FitH`:h.url;return z(e,h.fileName)}if("html"===h.kind&&!g){const e=["allow-same-origin","allow-forms","allow-popups","allow-downloads","allow-modals",x?"":"allow-scripts"].filter(Boolean).join(" ");return z(h.url,h.fileName,{sandbox:e})}return"office"===h.kind?z(`https://view.officeapps.live.com/op/embed.aspx?src=${encodeURIComponent(h.url)}`,h.fileName):t("div",Object.assign({className:"flex min-h-[120px] items-center justify-center gap-3 p-6 text-sm"},{children:[o(m,{className:"h-8 w-8 shrink-0"}),o("span",Object.assign({className:"break-all"},{children:h.extension.toUpperCase()}))]}))})()})]}))};export{R as default,$ as getFilePreviewInfo,C as isDocumentSourceUrl,N as isGeneratedFileUrl,I as isSourceLikeRichPreviewUrl,j as normalizeMarkdownUrl,D as shouldRenderFilePreview,S as shouldSuppressRichPreviewForUrl,F as shouldSuppressRichPreviewInText};
@@ -1 +1 @@
1
- import{__awaiter as e}from"../../../_virtual/_tslib.js";import{jsxs as t,jsx as o}from"react/jsx-runtime";import{useState as i,useRef as n,useMemo as r,useEffect as s}from"react";import l from"../../../common/error.js";import{Client as c}from"../../../node_modules/.pnpm/@modelcontextprotocol_sdk@1.20.2/node_modules/@modelcontextprotocol/sdk/dist/esm/client/index.js";import{StreamableHTTPClientTransport as a}from"../../../node_modules/.pnpm/@modelcontextprotocol_sdk@1.20.2/node_modules/@modelcontextprotocol/sdk/dist/esm/client/streamableHttp.js";import d from"../../Core/Button.js";import m from"../../Core/ErrorAlert.js";import{SmitheryAuthProvider as u}from"./SmitheryAuthProvider.js";import{v4 as p}from"uuid";import{api2 as f}from"../../../common/api/api.js";import{pickaxeApi2 as h,isPickaxeDomain as v}from"../../../common/api/pickaxe.js";import{usePickaxeContext as g}from"../../../hooks/pickaxe/usePickaxeContext.js";import{encryptFernet as x}from"../../../common/fernet.js";const b=({serverId:b,smitheryId:j,name:_,resubmitPrompt:O})=>{const{sender:k,translations:N}=g(),[y,I]=i(!0),[E,S]=i(!1),[C,w]=i(null),P=n(null),T=r((()=>p()),[]);s((()=>{let t=null;return E&&(t=setInterval((()=>e(void 0,void 0,void 0,(function*(){const e=yield f.post("/oauth/handshake/check",{sessionId:T}),{success:o,code:i}=e.data;if("failed"===i)return w((null==N?void 0:N["auth-failed"])||"Auth failed"),S(!1),void(t&&clearInterval(t));if(i&&o){t&&clearInterval(t);try{if(!P.current)throw new Error("Transport not available for finalization.");yield P.current.finishAuth(i)}catch(e){return console.error(e),w((null==N?void 0:N["failed-to-finalize-authentication"])||"Failed to finalize authentication."),void S(!1)}const e=localStorage.getItem("mcp_tokens"),o=localStorage.getItem("mcp_client");e&&o&&A(JSON.parse(e),JSON.parse(o))}}))),1e3)),()=>{t&&clearInterval(t)}}),[E]);const A=(t,o)=>e(void 0,void 0,void 0,(function*(){try{yield h.post("/mcp/user/save",{tokens:yield x(JSON.stringify(t)),clientId:o.client_id,serverId:b,userId:k},Object.assign(Object.assign({},(!process.env.NODE_ENV||"development"===process.env.NODE_ENV)&&Object.assign({},process.env.NEXT_PUBLIC_PICKAXE_SESSION_TOKEN&&{headers:{"x-pickaxe-session-token":process.env.NEXT_PUBLIC_PICKAXE_SESSION_TOKEN}})),v&&{credentials:"include"})),localStorage.removeItem("mcp_tokens"),localStorage.removeItem("mcp_client"),I(!1),O()}catch(e){w(l(e))}}));return y?t("div",Object.assign({className:"w-full bg-white border border-c-sep rounded-lg shadow-sm p-4 flex flex-col gap-4"},{children:[t("div",Object.assign({className:"flex flex-col gap-1"},{children:[o("h3",Object.assign({className:"font-semibold text-black/80 text-lg"},{children:(null==N?void 0:N["authentication-required"])||"Authentication Required"})),t("p",Object.assign({className:"text-black/60 text-sm"},{children:[(null==N?void 0:N["smithery-auth-description-prefix"])||"The tool you are trying to use requires authentication with"," ",o("span",Object.assign({className:"font-semibold text-black/80"},{children:_||j})),"."]}))]})),C&&o(m,{error:C}),t("div",Object.assign({className:"flex justify-end gap-2"},{children:[o(d,Object.assign({variant:"secondary",onClick:()=>I(!1),className:"text-sm px-3 h-9"},{children:(null==N?void 0:N.dismiss)||"Dismiss"})),o(d,Object.assign({variant:"primary",loadingText:(null==N?void 0:N.connecting)||"Connecting...",isLoading:E,onClick:()=>e(void 0,void 0,void 0,(function*(){if(!E)if("LOGGED OUT"!==k)try{w(null),S(!0);const e=new u(T),t=new a(new URL(`https://server.smithery.ai/${j}/mcp`),{authProvider:e});P.current=t;const o=new c({name:"Pickaxe",version:"1.0.0"});yield o.connect(t)}catch(e){console.log(l(e))}else w((null==N?void 0:N["must-be-logged-in-to-connect-smithery"])||"You must be logged in to connect Smithery MCPs.")})),className:"text-sm px-3 h-9"},{children:(null==N?void 0:N.connect)||"Connect"}))]}))]})):null};export{b as default};
1
+ import{__awaiter as e}from"../../../_virtual/_tslib.js";import{jsxs as o,jsx as t}from"react/jsx-runtime";import{useState as i,useRef as n,useMemo as r,useEffect as s}from"react";import c from"../../../common/error.js";import{Client as l}from"../../../node_modules/.pnpm/@modelcontextprotocol_sdk@1.20.2/node_modules/@modelcontextprotocol/sdk/dist/esm/client/index.js";import{StreamableHTTPClientTransport as a}from"../../../node_modules/.pnpm/@modelcontextprotocol_sdk@1.20.2/node_modules/@modelcontextprotocol/sdk/dist/esm/client/streamableHttp.js";import d from"../../Core/Button.js";import m from"../../Core/ErrorAlert.js";import{SmitheryAuthProvider as u}from"./SmitheryAuthProvider.js";import{v4 as p}from"uuid";import{api2 as h}from"../../../common/api/api.js";import{pickaxeApi2 as v,isPickaxeDomain as f}from"../../../common/api/pickaxe.js";import{usePickaxeContext as g}from"../../../hooks/pickaxe/usePickaxeContext.js";import{encryptFernet as x}from"../../../common/fernet.js";const b=({serverId:b,smitheryId:j,name:_,resubmitPrompt:k})=>{const{sender:y,translations:O,colors:N}=g(),[I,E]=i(!0),[S,C]=i(!1),[w,P]=i(null),T=n(null),A=r((()=>p()),[]);s((()=>{let o=null;return S&&(o=setInterval((()=>e(void 0,void 0,void 0,(function*(){const e=yield h.post("/oauth/handshake/check",{sessionId:A}),{success:t,code:i}=e.data;if("failed"===i)return P((null==O?void 0:O["auth-failed"])||"Auth failed"),C(!1),void(o&&clearInterval(o));if(i&&t){o&&clearInterval(o);try{if(!T.current)throw new Error("Transport not available for finalization.");yield T.current.finishAuth(i)}catch(e){return console.error(e),P((null==O?void 0:O["failed-to-finalize-authentication"])||"Failed to finalize authentication."),void C(!1)}const e=localStorage.getItem("mcp_tokens"),t=localStorage.getItem("mcp_client");e&&t&&L(JSON.parse(e),JSON.parse(t))}}))),1e3)),()=>{o&&clearInterval(o)}}),[S]);const L=(o,t)=>e(void 0,void 0,void 0,(function*(){try{yield v.post("/mcp/user/save",{tokens:yield x(JSON.stringify(o)),clientId:t.client_id,serverId:b,userId:y},Object.assign(Object.assign({},(!process.env.NODE_ENV||"development"===process.env.NODE_ENV)&&Object.assign({},process.env.NEXT_PUBLIC_PICKAXE_SESSION_TOKEN&&{headers:{"x-pickaxe-session-token":process.env.NEXT_PUBLIC_PICKAXE_SESSION_TOKEN}})),f&&{credentials:"include"})),localStorage.removeItem("mcp_tokens"),localStorage.removeItem("mcp_client"),E(!1),k()}catch(e){P(c(e))}}));return I?o("div",Object.assign({className:"w-full bg-white border border-c-sep rounded-lg shadow-sm p-4 flex flex-col gap-4"},{children:[o("div",Object.assign({className:"flex flex-col gap-1"},{children:[t("h3",Object.assign({className:"font-semibold text-black/80 text-lg"},{children:(null==O?void 0:O["authentication-required"])||"Authentication Required"})),o("p",Object.assign({className:"text-black/60 text-sm"},{children:[(null==O?void 0:O["smithery-auth-description-prefix"])||"The tool you are trying to use requires authentication with"," ",t("span",Object.assign({className:"font-semibold text-black/80"},{children:_||j})),"."]}))]})),w&&t(m,{error:w}),o("div",Object.assign({className:"flex justify-end gap-2"},{children:[t(d,Object.assign({variant:"secondary",onClick:()=>E(!1),className:"text-sm px-3 h-9"},{children:(null==O?void 0:O.dismiss)||"Dismiss"})),t(d,Object.assign({variant:"primary",loadingText:(null==O?void 0:O.connecting)||"Connecting...",isLoading:S,style:{borderColor:N.accent,backgroundColor:N.accent,color:N.accentText},onClick:()=>e(void 0,void 0,void 0,(function*(){if(!S)if("LOGGED OUT"!==y)try{P(null),C(!0);const e=new u(A),o=new a(new URL(`https://server.smithery.ai/${j}/mcp`),{authProvider:e});T.current=o;const t=new l({name:"Pickaxe",version:"1.0.0"});yield t.connect(o)}catch(e){console.log(c(e))}else P((null==O?void 0:O["must-be-logged-in-to-connect-smithery"])||"You must be logged in to connect Smithery MCPs.")})),className:"text-sm px-3 h-9 hover:opacity-90"},{children:(null==O?void 0:O.connect)||"Connect"}))]}))]})):null};export{b as default};
@@ -1,7 +1,9 @@
1
1
  import type { PickaxeHistoryMessage } from "../../../../types/history";
2
2
  interface SmitheryAuthData {
3
+ provider?: "smithery" | "composio";
3
4
  serverId: string;
4
- smitheryId: string;
5
+ smitheryId?: string;
6
+ toolkitSlug?: string;
5
7
  name: string;
6
8
  }
7
9
  interface MessageProps {
@@ -0,0 +1,9 @@
1
+ /// <reference types="react" />
2
+ interface ComposioConnectViewProps {
3
+ serverId: string;
4
+ toolkitSlug: string;
5
+ name?: string;
6
+ resubmitPrompt: () => void;
7
+ }
8
+ declare const ComposioConnectView: ({ serverId, toolkitSlug, name, resubmitPrompt, }: ComposioConnectViewProps) => JSX.Element | null;
9
+ export default ComposioConnectView;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@pickaxeproject/react",
3
- "version": "6.7.1",
3
+ "version": "6.8.1",
4
4
  "description": "Client utility library for Pickaxe",
5
5
  "repository": {
6
6
  "type": "git",