@teodorruskvi/chat-core 0.1.35 → 0.1.37

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.umd.js CHANGED
@@ -1,9 +1,9 @@
1
- (function(C,G){typeof exports=="object"&&typeof module<"u"?G(exports,require("react/jsx-runtime"),require("react"),require("axios")):typeof define=="function"&&define.amd?define(["exports","react/jsx-runtime","react","axios"],G):(C=typeof globalThis<"u"?globalThis:C||self,G(C.ChatCore={},C.jsxRuntime,C.React,C.axios))})(this,function(C,G,l,lt){"use strict";var ss=Object.defineProperty;var os=(C,G,l)=>G in C?ss(C,G,{enumerable:!0,configurable:!0,writable:!0,value:l}):C[G]=l;var tn=(C,G,l)=>os(C,typeof G!="symbol"?G+"":G,l);function nn(e){const t=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(e){for(const n in e)if(n!=="default"){const r=Object.getOwnPropertyDescriptor(e,n);Object.defineProperty(t,n,r.get?r:{enumerable:!0,get:()=>e[n]})}}return t.default=e,Object.freeze(t)}const ct=nn(l);function ut(e){var t,n,r="";if(typeof e=="string"||typeof e=="number")r+=e;else if(typeof e=="object")if(Array.isArray(e)){var s=e.length;for(t=0;t<s;t++)e[t]&&(n=ut(e[t]))&&(r&&(r+=" "),r+=n)}else for(n in e)e[n]&&(r&&(r+=" "),r+=n);return r}function rn(){for(var e,t,n=0,r="",s=arguments.length;n<s;n++)(e=arguments[n])&&(t=ut(e))&&(r&&(r+=" "),r+=t);return r}const Ke="-",sn=e=>{const t=an(e),{conflictingClassGroups:n,conflictingClassGroupModifiers:r}=e;return{getClassGroupId:a=>{const i=a.split(Ke);return i[0]===""&&i.length!==1&&i.shift(),dt(i,t)||on(a)},getConflictingClassGroupIds:(a,i)=>{const d=n[a]||[];return i&&r[a]?[...d,...r[a]]:d}}},dt=(e,t)=>{var a;if(e.length===0)return t.classGroupId;const n=e[0],r=t.nextPart.get(n),s=r?dt(e.slice(1),r):void 0;if(s)return s;if(t.validators.length===0)return;const o=e.join(Ke);return(a=t.validators.find(({validator:i})=>i(o)))==null?void 0:a.classGroupId},ft=/^\[(.+)\]$/,on=e=>{if(ft.test(e)){const t=ft.exec(e)[1],n=t==null?void 0:t.substring(0,t.indexOf(":"));if(n)return"arbitrary.."+n}},an=e=>{const{theme:t,prefix:n}=e,r={nextPart:new Map,validators:[]};return cn(Object.entries(e.classGroups),n).forEach(([o,a])=>{He(a,r,o,t)}),r},He=(e,t,n,r)=>{e.forEach(s=>{if(typeof s=="string"){const o=s===""?t:pt(t,s);o.classGroupId=n;return}if(typeof s=="function"){if(ln(s)){He(s(r),t,n,r);return}t.validators.push({validator:s,classGroupId:n});return}Object.entries(s).forEach(([o,a])=>{He(a,pt(t,o),n,r)})})},pt=(e,t)=>{let n=e;return t.split(Ke).forEach(r=>{n.nextPart.has(r)||n.nextPart.set(r,{nextPart:new Map,validators:[]}),n=n.nextPart.get(r)}),n},ln=e=>e.isThemeGetter,cn=(e,t)=>t?e.map(([n,r])=>{const s=r.map(o=>typeof o=="string"?t+o:typeof o=="object"?Object.fromEntries(Object.entries(o).map(([a,i])=>[t+a,i])):o);return[n,s]}):e,un=e=>{if(e<1)return{get:()=>{},set:()=>{}};let t=0,n=new Map,r=new Map;const s=(o,a)=>{n.set(o,a),t++,t>e&&(t=0,r=n,n=new Map)};return{get(o){let a=n.get(o);if(a!==void 0)return a;if((a=r.get(o))!==void 0)return s(o,a),a},set(o,a){n.has(o)?n.set(o,a):s(o,a)}}},gt="!",dn=e=>{const{separator:t,experimentalParseClassName:n}=e,r=t.length===1,s=t[0],o=t.length,a=i=>{const d=[];let c=0,u=0,g;for(let k=0;k<i.length;k++){let T=i[k];if(c===0){if(T===s&&(r||i.slice(k,k+o)===t)){d.push(i.slice(u,k)),u=k+o;continue}if(T==="/"){g=k;continue}}T==="["?c++:T==="]"&&c--}const h=d.length===0?i:i.substring(u),y=h.startsWith(gt),v=y?h.substring(1):h,p=g&&g>u?g-u:void 0;return{modifiers:d,hasImportantModifier:y,baseClassName:v,maybePostfixModifierPosition:p}};return n?i=>n({className:i,parseClassName:a}):a},fn=e=>{if(e.length<=1)return e;const t=[];let n=[];return e.forEach(r=>{r[0]==="["?(t.push(...n.sort(),r),n=[]):n.push(r)}),t.push(...n.sort()),t},pn=e=>({cache:un(e.cacheSize),parseClassName:dn(e),...sn(e)}),gn=/\s+/,mn=(e,t)=>{const{parseClassName:n,getClassGroupId:r,getConflictingClassGroupIds:s}=t,o=[],a=e.trim().split(gn);let i="";for(let d=a.length-1;d>=0;d-=1){const c=a[d],{modifiers:u,hasImportantModifier:g,baseClassName:h,maybePostfixModifierPosition:y}=n(c);let v=!!y,p=r(v?h.substring(0,y):h);if(!p){if(!v){i=c+(i.length>0?" "+i:i);continue}if(p=r(h),!p){i=c+(i.length>0?" "+i:i);continue}v=!1}const k=fn(u).join(":"),T=g?k+gt:k,E=T+p;if(o.includes(E))continue;o.push(E);const I=s(p,v);for(let j=0;j<I.length;++j){const z=I[j];o.push(T+z)}i=c+(i.length>0?" "+i:i)}return i};function hn(){let e=0,t,n,r="";for(;e<arguments.length;)(t=arguments[e++])&&(n=mt(t))&&(r&&(r+=" "),r+=n);return r}const mt=e=>{if(typeof e=="string")return e;let t,n="";for(let r=0;r<e.length;r++)e[r]&&(t=mt(e[r]))&&(n&&(n+=" "),n+=t);return n};function yn(e,...t){let n,r,s,o=a;function a(d){const c=t.reduce((u,g)=>g(u),e());return n=pn(c),r=n.cache.get,s=n.cache.set,o=i,i(d)}function i(d){const c=r(d);if(c)return c;const u=mn(d,n);return s(d,u),u}return function(){return o(hn.apply(null,arguments))}}const V=e=>{const t=n=>n[e]||[];return t.isThemeGetter=!0,t},ht=/^\[(?:([a-z-]+):)?(.+)\]$/i,bn=/^\d+\/\d+$/,wn=new Set(["px","full","screen"]),kn=/^(\d+(\.\d+)?)?(xs|sm|md|lg|xl)$/,vn=/\d+(%|px|r?em|[sdl]?v([hwib]|min|max)|pt|pc|in|cm|mm|cap|ch|ex|r?lh|cq(w|h|i|b|min|max))|\b(calc|min|max|clamp)\(.+\)|^0$/,Tn=/^(rgba?|hsla?|hwb|(ok)?(lab|lch))\(.+\)$/,In=/^(inset_)?-?((\d+)?\.?(\d+)[a-z]+|0)_-?((\d+)?\.?(\d+)[a-z]+|0)/,Sn=/^(url|image|image-set|cross-fade|element|(repeating-)?(linear|radial|conic)-gradient)\(.+\)$/,ie=e=>ke(e)||wn.has(e)||bn.test(e),fe=e=>ve(e,"length",zn),ke=e=>!!e&&!Number.isNaN(Number(e)),Ge=e=>ve(e,"number",ke),Se=e=>!!e&&Number.isInteger(Number(e)),An=e=>e.endsWith("%")&&ke(e.slice(0,-1)),L=e=>ht.test(e),pe=e=>kn.test(e),Cn=new Set(["length","size","percentage"]),xn=e=>ve(e,Cn,yt),Mn=e=>ve(e,"position",yt),En=new Set(["image","url"]),Pn=e=>ve(e,En,jn),_n=e=>ve(e,"",Nn),Ae=()=>!0,ve=(e,t,n)=>{const r=ht.exec(e);return r?r[1]?typeof t=="string"?r[1]===t:t.has(r[1]):n(r[2]):!1},zn=e=>vn.test(e)&&!Tn.test(e),yt=()=>!1,Nn=e=>In.test(e),jn=e=>Sn.test(e),Un=yn(()=>{const e=V("colors"),t=V("spacing"),n=V("blur"),r=V("brightness"),s=V("borderColor"),o=V("borderRadius"),a=V("borderSpacing"),i=V("borderWidth"),d=V("contrast"),c=V("grayscale"),u=V("hueRotate"),g=V("invert"),h=V("gap"),y=V("gradientColorStops"),v=V("gradientColorStopPositions"),p=V("inset"),k=V("margin"),T=V("opacity"),E=V("padding"),I=V("saturate"),j=V("scale"),z=V("sepia"),A=V("skew"),P=V("space"),m=V("translate"),b=()=>["auto","contain","none"],$=()=>["auto","hidden","clip","visible","scroll"],F=()=>["auto",L,t],M=()=>[L,t],_=()=>["",ie,fe],O=()=>["auto",ke,L],U=()=>["bottom","center","left","left-bottom","left-top","right","right-bottom","right-top","top"],K=()=>["solid","dashed","dotted","double","none"],q=()=>["normal","multiply","screen","overlay","darken","lighten","color-dodge","color-burn","hard-light","soft-light","difference","exclusion","hue","saturation","color","luminosity"],w=()=>["start","end","center","between","around","evenly","stretch"],S=()=>["","0",L],D=()=>["auto","avoid","all","avoid-page","page","left","right","column"],B=()=>[ke,L];return{cacheSize:500,separator:":",theme:{colors:[Ae],spacing:[ie,fe],blur:["none","",pe,L],brightness:B(),borderColor:[e],borderRadius:["none","","full",pe,L],borderSpacing:M(),borderWidth:_(),contrast:B(),grayscale:S(),hueRotate:B(),invert:S(),gap:M(),gradientColorStops:[e],gradientColorStopPositions:[An,fe],inset:F(),margin:F(),opacity:B(),padding:M(),saturate:B(),scale:B(),sepia:S(),skew:B(),space:M(),translate:M()},classGroups:{aspect:[{aspect:["auto","square","video",L]}],container:["container"],columns:[{columns:[pe]}],"break-after":[{"break-after":D()}],"break-before":[{"break-before":D()}],"break-inside":[{"break-inside":["auto","avoid","avoid-page","avoid-column"]}],"box-decoration":[{"box-decoration":["slice","clone"]}],box:[{box:["border","content"]}],display:["block","inline-block","inline","flex","inline-flex","table","inline-table","table-caption","table-cell","table-column","table-column-group","table-footer-group","table-header-group","table-row-group","table-row","flow-root","grid","inline-grid","contents","list-item","hidden"],float:[{float:["right","left","none","start","end"]}],clear:[{clear:["left","right","both","none","start","end"]}],isolation:["isolate","isolation-auto"],"object-fit":[{object:["contain","cover","fill","none","scale-down"]}],"object-position":[{object:[...U(),L]}],overflow:[{overflow:$()}],"overflow-x":[{"overflow-x":$()}],"overflow-y":[{"overflow-y":$()}],overscroll:[{overscroll:b()}],"overscroll-x":[{"overscroll-x":b()}],"overscroll-y":[{"overscroll-y":b()}],position:["static","fixed","absolute","relative","sticky"],inset:[{inset:[p]}],"inset-x":[{"inset-x":[p]}],"inset-y":[{"inset-y":[p]}],start:[{start:[p]}],end:[{end:[p]}],top:[{top:[p]}],right:[{right:[p]}],bottom:[{bottom:[p]}],left:[{left:[p]}],visibility:["visible","invisible","collapse"],z:[{z:["auto",Se,L]}],basis:[{basis:F()}],"flex-direction":[{flex:["row","row-reverse","col","col-reverse"]}],"flex-wrap":[{flex:["wrap","wrap-reverse","nowrap"]}],flex:[{flex:["1","auto","initial","none",L]}],grow:[{grow:S()}],shrink:[{shrink:S()}],order:[{order:["first","last","none",Se,L]}],"grid-cols":[{"grid-cols":[Ae]}],"col-start-end":[{col:["auto",{span:["full",Se,L]},L]}],"col-start":[{"col-start":O()}],"col-end":[{"col-end":O()}],"grid-rows":[{"grid-rows":[Ae]}],"row-start-end":[{row:["auto",{span:[Se,L]},L]}],"row-start":[{"row-start":O()}],"row-end":[{"row-end":O()}],"grid-flow":[{"grid-flow":["row","col","dense","row-dense","col-dense"]}],"auto-cols":[{"auto-cols":["auto","min","max","fr",L]}],"auto-rows":[{"auto-rows":["auto","min","max","fr",L]}],gap:[{gap:[h]}],"gap-x":[{"gap-x":[h]}],"gap-y":[{"gap-y":[h]}],"justify-content":[{justify:["normal",...w()]}],"justify-items":[{"justify-items":["start","end","center","stretch"]}],"justify-self":[{"justify-self":["auto","start","end","center","stretch"]}],"align-content":[{content:["normal",...w(),"baseline"]}],"align-items":[{items:["start","end","center","baseline","stretch"]}],"align-self":[{self:["auto","start","end","center","stretch","baseline"]}],"place-content":[{"place-content":[...w(),"baseline"]}],"place-items":[{"place-items":["start","end","center","baseline","stretch"]}],"place-self":[{"place-self":["auto","start","end","center","stretch"]}],p:[{p:[E]}],px:[{px:[E]}],py:[{py:[E]}],ps:[{ps:[E]}],pe:[{pe:[E]}],pt:[{pt:[E]}],pr:[{pr:[E]}],pb:[{pb:[E]}],pl:[{pl:[E]}],m:[{m:[k]}],mx:[{mx:[k]}],my:[{my:[k]}],ms:[{ms:[k]}],me:[{me:[k]}],mt:[{mt:[k]}],mr:[{mr:[k]}],mb:[{mb:[k]}],ml:[{ml:[k]}],"space-x":[{"space-x":[P]}],"space-x-reverse":["space-x-reverse"],"space-y":[{"space-y":[P]}],"space-y-reverse":["space-y-reverse"],w:[{w:["auto","min","max","fit","svw","lvw","dvw",L,t]}],"min-w":[{"min-w":[L,t,"min","max","fit"]}],"max-w":[{"max-w":[L,t,"none","full","min","max","fit","prose",{screen:[pe]},pe]}],h:[{h:[L,t,"auto","min","max","fit","svh","lvh","dvh"]}],"min-h":[{"min-h":[L,t,"min","max","fit","svh","lvh","dvh"]}],"max-h":[{"max-h":[L,t,"min","max","fit","svh","lvh","dvh"]}],size:[{size:[L,t,"auto","min","max","fit"]}],"font-size":[{text:["base",pe,fe]}],"font-smoothing":["antialiased","subpixel-antialiased"],"font-style":["italic","not-italic"],"font-weight":[{font:["thin","extralight","light","normal","medium","semibold","bold","extrabold","black",Ge]}],"font-family":[{font:[Ae]}],"fvn-normal":["normal-nums"],"fvn-ordinal":["ordinal"],"fvn-slashed-zero":["slashed-zero"],"fvn-figure":["lining-nums","oldstyle-nums"],"fvn-spacing":["proportional-nums","tabular-nums"],"fvn-fraction":["diagonal-fractions","stacked-fractions"],tracking:[{tracking:["tighter","tight","normal","wide","wider","widest",L]}],"line-clamp":[{"line-clamp":["none",ke,Ge]}],leading:[{leading:["none","tight","snug","normal","relaxed","loose",ie,L]}],"list-image":[{"list-image":["none",L]}],"list-style-type":[{list:["none","disc","decimal",L]}],"list-style-position":[{list:["inside","outside"]}],"placeholder-color":[{placeholder:[e]}],"placeholder-opacity":[{"placeholder-opacity":[T]}],"text-alignment":[{text:["left","center","right","justify","start","end"]}],"text-color":[{text:[e]}],"text-opacity":[{"text-opacity":[T]}],"text-decoration":["underline","overline","line-through","no-underline"],"text-decoration-style":[{decoration:[...K(),"wavy"]}],"text-decoration-thickness":[{decoration:["auto","from-font",ie,fe]}],"underline-offset":[{"underline-offset":["auto",ie,L]}],"text-decoration-color":[{decoration:[e]}],"text-transform":["uppercase","lowercase","capitalize","normal-case"],"text-overflow":["truncate","text-ellipsis","text-clip"],"text-wrap":[{text:["wrap","nowrap","balance","pretty"]}],indent:[{indent:M()}],"vertical-align":[{align:["baseline","top","middle","bottom","text-top","text-bottom","sub","super",L]}],whitespace:[{whitespace:["normal","nowrap","pre","pre-line","pre-wrap","break-spaces"]}],break:[{break:["normal","words","all","keep"]}],hyphens:[{hyphens:["none","manual","auto"]}],content:[{content:["none",L]}],"bg-attachment":[{bg:["fixed","local","scroll"]}],"bg-clip":[{"bg-clip":["border","padding","content","text"]}],"bg-opacity":[{"bg-opacity":[T]}],"bg-origin":[{"bg-origin":["border","padding","content"]}],"bg-position":[{bg:[...U(),Mn]}],"bg-repeat":[{bg:["no-repeat",{repeat:["","x","y","round","space"]}]}],"bg-size":[{bg:["auto","cover","contain",xn]}],"bg-image":[{bg:["none",{"gradient-to":["t","tr","r","br","b","bl","l","tl"]},Pn]}],"bg-color":[{bg:[e]}],"gradient-from-pos":[{from:[v]}],"gradient-via-pos":[{via:[v]}],"gradient-to-pos":[{to:[v]}],"gradient-from":[{from:[y]}],"gradient-via":[{via:[y]}],"gradient-to":[{to:[y]}],rounded:[{rounded:[o]}],"rounded-s":[{"rounded-s":[o]}],"rounded-e":[{"rounded-e":[o]}],"rounded-t":[{"rounded-t":[o]}],"rounded-r":[{"rounded-r":[o]}],"rounded-b":[{"rounded-b":[o]}],"rounded-l":[{"rounded-l":[o]}],"rounded-ss":[{"rounded-ss":[o]}],"rounded-se":[{"rounded-se":[o]}],"rounded-ee":[{"rounded-ee":[o]}],"rounded-es":[{"rounded-es":[o]}],"rounded-tl":[{"rounded-tl":[o]}],"rounded-tr":[{"rounded-tr":[o]}],"rounded-br":[{"rounded-br":[o]}],"rounded-bl":[{"rounded-bl":[o]}],"border-w":[{border:[i]}],"border-w-x":[{"border-x":[i]}],"border-w-y":[{"border-y":[i]}],"border-w-s":[{"border-s":[i]}],"border-w-e":[{"border-e":[i]}],"border-w-t":[{"border-t":[i]}],"border-w-r":[{"border-r":[i]}],"border-w-b":[{"border-b":[i]}],"border-w-l":[{"border-l":[i]}],"border-opacity":[{"border-opacity":[T]}],"border-style":[{border:[...K(),"hidden"]}],"divide-x":[{"divide-x":[i]}],"divide-x-reverse":["divide-x-reverse"],"divide-y":[{"divide-y":[i]}],"divide-y-reverse":["divide-y-reverse"],"divide-opacity":[{"divide-opacity":[T]}],"divide-style":[{divide:K()}],"border-color":[{border:[s]}],"border-color-x":[{"border-x":[s]}],"border-color-y":[{"border-y":[s]}],"border-color-s":[{"border-s":[s]}],"border-color-e":[{"border-e":[s]}],"border-color-t":[{"border-t":[s]}],"border-color-r":[{"border-r":[s]}],"border-color-b":[{"border-b":[s]}],"border-color-l":[{"border-l":[s]}],"divide-color":[{divide:[s]}],"outline-style":[{outline:["",...K()]}],"outline-offset":[{"outline-offset":[ie,L]}],"outline-w":[{outline:[ie,fe]}],"outline-color":[{outline:[e]}],"ring-w":[{ring:_()}],"ring-w-inset":["ring-inset"],"ring-color":[{ring:[e]}],"ring-opacity":[{"ring-opacity":[T]}],"ring-offset-w":[{"ring-offset":[ie,fe]}],"ring-offset-color":[{"ring-offset":[e]}],shadow:[{shadow:["","inner","none",pe,_n]}],"shadow-color":[{shadow:[Ae]}],opacity:[{opacity:[T]}],"mix-blend":[{"mix-blend":[...q(),"plus-lighter","plus-darker"]}],"bg-blend":[{"bg-blend":q()}],filter:[{filter:["","none"]}],blur:[{blur:[n]}],brightness:[{brightness:[r]}],contrast:[{contrast:[d]}],"drop-shadow":[{"drop-shadow":["","none",pe,L]}],grayscale:[{grayscale:[c]}],"hue-rotate":[{"hue-rotate":[u]}],invert:[{invert:[g]}],saturate:[{saturate:[I]}],sepia:[{sepia:[z]}],"backdrop-filter":[{"backdrop-filter":["","none"]}],"backdrop-blur":[{"backdrop-blur":[n]}],"backdrop-brightness":[{"backdrop-brightness":[r]}],"backdrop-contrast":[{"backdrop-contrast":[d]}],"backdrop-grayscale":[{"backdrop-grayscale":[c]}],"backdrop-hue-rotate":[{"backdrop-hue-rotate":[u]}],"backdrop-invert":[{"backdrop-invert":[g]}],"backdrop-opacity":[{"backdrop-opacity":[T]}],"backdrop-saturate":[{"backdrop-saturate":[I]}],"backdrop-sepia":[{"backdrop-sepia":[z]}],"border-collapse":[{border:["collapse","separate"]}],"border-spacing":[{"border-spacing":[a]}],"border-spacing-x":[{"border-spacing-x":[a]}],"border-spacing-y":[{"border-spacing-y":[a]}],"table-layout":[{table:["auto","fixed"]}],caption:[{caption:["top","bottom"]}],transition:[{transition:["none","all","","colors","opacity","shadow","transform",L]}],duration:[{duration:B()}],ease:[{ease:["linear","in","out","in-out",L]}],delay:[{delay:B()}],animate:[{animate:["none","spin","ping","pulse","bounce",L]}],transform:[{transform:["","gpu","none"]}],scale:[{scale:[j]}],"scale-x":[{"scale-x":[j]}],"scale-y":[{"scale-y":[j]}],rotate:[{rotate:[Se,L]}],"translate-x":[{"translate-x":[m]}],"translate-y":[{"translate-y":[m]}],"skew-x":[{"skew-x":[A]}],"skew-y":[{"skew-y":[A]}],"transform-origin":[{origin:["center","top","top-right","right","bottom-right","bottom","bottom-left","left","top-left",L]}],accent:[{accent:["auto",e]}],appearance:[{appearance:["none","auto"]}],cursor:[{cursor:["auto","default","pointer","wait","text","move","help","not-allowed","none","context-menu","progress","cell","crosshair","vertical-text","alias","copy","no-drop","grab","grabbing","all-scroll","col-resize","row-resize","n-resize","e-resize","s-resize","w-resize","ne-resize","nw-resize","se-resize","sw-resize","ew-resize","ns-resize","nesw-resize","nwse-resize","zoom-in","zoom-out",L]}],"caret-color":[{caret:[e]}],"pointer-events":[{"pointer-events":["none","auto"]}],resize:[{resize:["none","y","x",""]}],"scroll-behavior":[{scroll:["auto","smooth"]}],"scroll-m":[{"scroll-m":M()}],"scroll-mx":[{"scroll-mx":M()}],"scroll-my":[{"scroll-my":M()}],"scroll-ms":[{"scroll-ms":M()}],"scroll-me":[{"scroll-me":M()}],"scroll-mt":[{"scroll-mt":M()}],"scroll-mr":[{"scroll-mr":M()}],"scroll-mb":[{"scroll-mb":M()}],"scroll-ml":[{"scroll-ml":M()}],"scroll-p":[{"scroll-p":M()}],"scroll-px":[{"scroll-px":M()}],"scroll-py":[{"scroll-py":M()}],"scroll-ps":[{"scroll-ps":M()}],"scroll-pe":[{"scroll-pe":M()}],"scroll-pt":[{"scroll-pt":M()}],"scroll-pr":[{"scroll-pr":M()}],"scroll-pb":[{"scroll-pb":M()}],"scroll-pl":[{"scroll-pl":M()}],"snap-align":[{snap:["start","end","center","align-none"]}],"snap-stop":[{snap:["normal","always"]}],"snap-type":[{snap:["none","x","y","both"]}],"snap-strictness":[{snap:["mandatory","proximity"]}],touch:[{touch:["auto","none","manipulation"]}],"touch-x":[{"touch-pan":["x","left","right"]}],"touch-y":[{"touch-pan":["y","up","down"]}],"touch-pz":["touch-pinch-zoom"],select:[{select:["none","text","all","auto"]}],"will-change":[{"will-change":["auto","scroll","contents","transform",L]}],fill:[{fill:[e,"none"]}],"stroke-w":[{stroke:[ie,fe,Ge]}],stroke:[{stroke:[e,"none"]}],sr:["sr-only","not-sr-only"],"forced-color-adjust":[{"forced-color-adjust":["auto","none"]}]},conflictingClassGroups:{overflow:["overflow-x","overflow-y"],overscroll:["overscroll-x","overscroll-y"],inset:["inset-x","inset-y","start","end","top","right","bottom","left"],"inset-x":["right","left"],"inset-y":["top","bottom"],flex:["basis","grow","shrink"],gap:["gap-x","gap-y"],p:["px","py","ps","pe","pt","pr","pb","pl"],px:["pr","pl"],py:["pt","pb"],m:["mx","my","ms","me","mt","mr","mb","ml"],mx:["mr","ml"],my:["mt","mb"],size:["w","h"],"font-size":["leading"],"fvn-normal":["fvn-ordinal","fvn-slashed-zero","fvn-figure","fvn-spacing","fvn-fraction"],"fvn-ordinal":["fvn-normal"],"fvn-slashed-zero":["fvn-normal"],"fvn-figure":["fvn-normal"],"fvn-spacing":["fvn-normal"],"fvn-fraction":["fvn-normal"],"line-clamp":["display","overflow"],rounded:["rounded-s","rounded-e","rounded-t","rounded-r","rounded-b","rounded-l","rounded-ss","rounded-se","rounded-ee","rounded-es","rounded-tl","rounded-tr","rounded-br","rounded-bl"],"rounded-s":["rounded-ss","rounded-es"],"rounded-e":["rounded-se","rounded-ee"],"rounded-t":["rounded-tl","rounded-tr"],"rounded-r":["rounded-tr","rounded-br"],"rounded-b":["rounded-br","rounded-bl"],"rounded-l":["rounded-tl","rounded-bl"],"border-spacing":["border-spacing-x","border-spacing-y"],"border-w":["border-w-s","border-w-e","border-w-t","border-w-r","border-w-b","border-w-l"],"border-w-x":["border-w-r","border-w-l"],"border-w-y":["border-w-t","border-w-b"],"border-color":["border-color-s","border-color-e","border-color-t","border-color-r","border-color-b","border-color-l"],"border-color-x":["border-color-r","border-color-l"],"border-color-y":["border-color-t","border-color-b"],"scroll-m":["scroll-mx","scroll-my","scroll-ms","scroll-me","scroll-mt","scroll-mr","scroll-mb","scroll-ml"],"scroll-mx":["scroll-mr","scroll-ml"],"scroll-my":["scroll-mt","scroll-mb"],"scroll-p":["scroll-px","scroll-py","scroll-ps","scroll-pe","scroll-pt","scroll-pr","scroll-pb","scroll-pl"],"scroll-px":["scroll-pr","scroll-pl"],"scroll-py":["scroll-pt","scroll-pb"],touch:["touch-x","touch-y","touch-pz"],"touch-x":["touch"],"touch-y":["touch"],"touch-pz":["touch"]},conflictingClassGroupModifiers:{"font-size":["leading"]}}});function Fn(...e){return Un(rn(e))}function Ln(e){let t=!1,n="";for(const s of e){if(s==="\\"){n+=s,t=!t;continue}if(s==="'"&&!t){n+='"';continue}n+=s,t=!1}return n.replace(/\bTrue\b/g,"true").replace(/\bFalse\b/g,"false").replace(/\bNone\b/g,"null")}function ze(e){const t=e==null?void 0:e.trim();if(!t||!(t.startsWith("{")||t.startsWith("[")))return null;try{return JSON.parse(t)}catch{const n=Ln(t);if(n)try{return JSON.parse(n)}catch{return null}return null}}function bt(e){return typeof e!="string"?!1:/^[\s\n]*[-*]\s|^[\s\n]*#+\s|```|^\s*\[.*\]\(|^>\s/.test(e)}function On(e){return e.type==="image_url"}function $n(e){return e.type==="file"}function Bn(e){return Array.isArray(e.content)?e.content.filter(t=>t.type==="text").map(t=>t.text).join(`
1
+ (function(A,q){typeof exports=="object"&&typeof module<"u"?q(exports,require("react/jsx-runtime"),require("react"),require("axios")):typeof define=="function"&&define.amd?define(["exports","react/jsx-runtime","react","axios"],q):(A=typeof globalThis<"u"?globalThis:A||self,q(A.ChatCore={},A.jsxRuntime,A.React,A.axios))})(this,function(A,q,l,lt){"use strict";var ss=Object.defineProperty;var os=(A,q,l)=>q in A?ss(A,q,{enumerable:!0,configurable:!0,writable:!0,value:l}):A[q]=l;var tn=(A,q,l)=>os(A,typeof q!="symbol"?q+"":q,l);function nn(e){const t=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(e){for(const n in e)if(n!=="default"){const r=Object.getOwnPropertyDescriptor(e,n);Object.defineProperty(t,n,r.get?r:{enumerable:!0,get:()=>e[n]})}}return t.default=e,Object.freeze(t)}const ct=nn(l);function ut(e){var t,n,r="";if(typeof e=="string"||typeof e=="number")r+=e;else if(typeof e=="object")if(Array.isArray(e)){var s=e.length;for(t=0;t<s;t++)e[t]&&(n=ut(e[t]))&&(r&&(r+=" "),r+=n)}else for(n in e)e[n]&&(r&&(r+=" "),r+=n);return r}function rn(){for(var e,t,n=0,r="",s=arguments.length;n<s;n++)(e=arguments[n])&&(t=ut(e))&&(r&&(r+=" "),r+=t);return r}const Ke="-",sn=e=>{const t=an(e),{conflictingClassGroups:n,conflictingClassGroupModifiers:r}=e;return{getClassGroupId:a=>{const i=a.split(Ke);return i[0]===""&&i.length!==1&&i.shift(),dt(i,t)||on(a)},getConflictingClassGroupIds:(a,i)=>{const d=n[a]||[];return i&&r[a]?[...d,...r[a]]:d}}},dt=(e,t)=>{var a;if(e.length===0)return t.classGroupId;const n=e[0],r=t.nextPart.get(n),s=r?dt(e.slice(1),r):void 0;if(s)return s;if(t.validators.length===0)return;const o=e.join(Ke);return(a=t.validators.find(({validator:i})=>i(o)))==null?void 0:a.classGroupId},ft=/^\[(.+)\]$/,on=e=>{if(ft.test(e)){const t=ft.exec(e)[1],n=t==null?void 0:t.substring(0,t.indexOf(":"));if(n)return"arbitrary.."+n}},an=e=>{const{theme:t,prefix:n}=e,r={nextPart:new Map,validators:[]};return cn(Object.entries(e.classGroups),n).forEach(([o,a])=>{He(a,r,o,t)}),r},He=(e,t,n,r)=>{e.forEach(s=>{if(typeof s=="string"){const o=s===""?t:pt(t,s);o.classGroupId=n;return}if(typeof s=="function"){if(ln(s)){He(s(r),t,n,r);return}t.validators.push({validator:s,classGroupId:n});return}Object.entries(s).forEach(([o,a])=>{He(a,pt(t,o),n,r)})})},pt=(e,t)=>{let n=e;return t.split(Ke).forEach(r=>{n.nextPart.has(r)||n.nextPart.set(r,{nextPart:new Map,validators:[]}),n=n.nextPart.get(r)}),n},ln=e=>e.isThemeGetter,cn=(e,t)=>t?e.map(([n,r])=>{const s=r.map(o=>typeof o=="string"?t+o:typeof o=="object"?Object.fromEntries(Object.entries(o).map(([a,i])=>[t+a,i])):o);return[n,s]}):e,un=e=>{if(e<1)return{get:()=>{},set:()=>{}};let t=0,n=new Map,r=new Map;const s=(o,a)=>{n.set(o,a),t++,t>e&&(t=0,r=n,n=new Map)};return{get(o){let a=n.get(o);if(a!==void 0)return a;if((a=r.get(o))!==void 0)return s(o,a),a},set(o,a){n.has(o)?n.set(o,a):s(o,a)}}},gt="!",dn=e=>{const{separator:t,experimentalParseClassName:n}=e,r=t.length===1,s=t[0],o=t.length,a=i=>{const d=[];let c=0,u=0,g;for(let k=0;k<i.length;k++){let T=i[k];if(c===0){if(T===s&&(r||i.slice(k,k+o)===t)){d.push(i.slice(u,k)),u=k+o;continue}if(T==="/"){g=k;continue}}T==="["?c++:T==="]"&&c--}const h=d.length===0?i:i.substring(u),y=h.startsWith(gt),v=y?h.substring(1):h,p=g&&g>u?g-u:void 0;return{modifiers:d,hasImportantModifier:y,baseClassName:v,maybePostfixModifierPosition:p}};return n?i=>n({className:i,parseClassName:a}):a},fn=e=>{if(e.length<=1)return e;const t=[];let n=[];return e.forEach(r=>{r[0]==="["?(t.push(...n.sort(),r),n=[]):n.push(r)}),t.push(...n.sort()),t},pn=e=>({cache:un(e.cacheSize),parseClassName:dn(e),...sn(e)}),gn=/\s+/,mn=(e,t)=>{const{parseClassName:n,getClassGroupId:r,getConflictingClassGroupIds:s}=t,o=[],a=e.trim().split(gn);let i="";for(let d=a.length-1;d>=0;d-=1){const c=a[d],{modifiers:u,hasImportantModifier:g,baseClassName:h,maybePostfixModifierPosition:y}=n(c);let v=!!y,p=r(v?h.substring(0,y):h);if(!p){if(!v){i=c+(i.length>0?" "+i:i);continue}if(p=r(h),!p){i=c+(i.length>0?" "+i:i);continue}v=!1}const k=fn(u).join(":"),T=g?k+gt:k,_=T+p;if(o.includes(_))continue;o.push(_);const I=s(p,v);for(let j=0;j<I.length;++j){const N=I[j];o.push(T+N)}i=c+(i.length>0?" "+i:i)}return i};function hn(){let e=0,t,n,r="";for(;e<arguments.length;)(t=arguments[e++])&&(n=mt(t))&&(r&&(r+=" "),r+=n);return r}const mt=e=>{if(typeof e=="string")return e;let t,n="";for(let r=0;r<e.length;r++)e[r]&&(t=mt(e[r]))&&(n&&(n+=" "),n+=t);return n};function yn(e,...t){let n,r,s,o=a;function a(d){const c=t.reduce((u,g)=>g(u),e());return n=pn(c),r=n.cache.get,s=n.cache.set,o=i,i(d)}function i(d){const c=r(d);if(c)return c;const u=mn(d,n);return s(d,u),u}return function(){return o(hn.apply(null,arguments))}}const H=e=>{const t=n=>n[e]||[];return t.isThemeGetter=!0,t},ht=/^\[(?:([a-z-]+):)?(.+)\]$/i,bn=/^\d+\/\d+$/,wn=new Set(["px","full","screen"]),kn=/^(\d+(\.\d+)?)?(xs|sm|md|lg|xl)$/,vn=/\d+(%|px|r?em|[sdl]?v([hwib]|min|max)|pt|pc|in|cm|mm|cap|ch|ex|r?lh|cq(w|h|i|b|min|max))|\b(calc|min|max|clamp)\(.+\)|^0$/,Tn=/^(rgba?|hsla?|hwb|(ok)?(lab|lch))\(.+\)$/,In=/^(inset_)?-?((\d+)?\.?(\d+)[a-z]+|0)_-?((\d+)?\.?(\d+)[a-z]+|0)/,Sn=/^(url|image|image-set|cross-fade|element|(repeating-)?(linear|radial|conic)-gradient)\(.+\)$/,ie=e=>ke(e)||wn.has(e)||bn.test(e),fe=e=>ve(e,"length",Nn),ke=e=>!!e&&!Number.isNaN(Number(e)),Ge=e=>ve(e,"number",ke),Se=e=>!!e&&Number.isInteger(Number(e)),An=e=>e.endsWith("%")&&ke(e.slice(0,-1)),F=e=>ht.test(e),pe=e=>kn.test(e),Cn=new Set(["length","size","percentage"]),xn=e=>ve(e,Cn,yt),Mn=e=>ve(e,"position",yt),En=new Set(["image","url"]),Pn=e=>ve(e,En,jn),_n=e=>ve(e,"",zn),Ae=()=>!0,ve=(e,t,n)=>{const r=ht.exec(e);return r?r[1]?typeof t=="string"?r[1]===t:t.has(r[1]):n(r[2]):!1},Nn=e=>vn.test(e)&&!Tn.test(e),yt=()=>!1,zn=e=>In.test(e),jn=e=>Sn.test(e),Un=yn(()=>{const e=H("colors"),t=H("spacing"),n=H("blur"),r=H("brightness"),s=H("borderColor"),o=H("borderRadius"),a=H("borderSpacing"),i=H("borderWidth"),d=H("contrast"),c=H("grayscale"),u=H("hueRotate"),g=H("invert"),h=H("gap"),y=H("gradientColorStops"),v=H("gradientColorStopPositions"),p=H("inset"),k=H("margin"),T=H("opacity"),_=H("padding"),I=H("saturate"),j=H("scale"),N=H("sepia"),S=H("skew"),M=H("space"),m=H("translate"),w=()=>["auto","contain","none"],B=()=>["auto","hidden","clip","visible","scroll"],L=()=>["auto",F,t],E=()=>[F,t],P=()=>["",ie,fe],O=()=>["auto",ke,F],U=()=>["bottom","center","left","left-bottom","left-top","right","right-bottom","right-top","top"],K=()=>["solid","dashed","dotted","double","none"],V=()=>["normal","multiply","screen","overlay","darken","lighten","color-dodge","color-burn","hard-light","soft-light","difference","exclusion","hue","saturation","color","luminosity"],x=()=>["start","end","center","between","around","evenly","stretch"],b=()=>["","0",F],$=()=>["auto","avoid","all","avoid-page","page","left","right","column"],D=()=>[ke,F];return{cacheSize:500,separator:":",theme:{colors:[Ae],spacing:[ie,fe],blur:["none","",pe,F],brightness:D(),borderColor:[e],borderRadius:["none","","full",pe,F],borderSpacing:E(),borderWidth:P(),contrast:D(),grayscale:b(),hueRotate:D(),invert:b(),gap:E(),gradientColorStops:[e],gradientColorStopPositions:[An,fe],inset:L(),margin:L(),opacity:D(),padding:E(),saturate:D(),scale:D(),sepia:b(),skew:D(),space:E(),translate:E()},classGroups:{aspect:[{aspect:["auto","square","video",F]}],container:["container"],columns:[{columns:[pe]}],"break-after":[{"break-after":$()}],"break-before":[{"break-before":$()}],"break-inside":[{"break-inside":["auto","avoid","avoid-page","avoid-column"]}],"box-decoration":[{"box-decoration":["slice","clone"]}],box:[{box:["border","content"]}],display:["block","inline-block","inline","flex","inline-flex","table","inline-table","table-caption","table-cell","table-column","table-column-group","table-footer-group","table-header-group","table-row-group","table-row","flow-root","grid","inline-grid","contents","list-item","hidden"],float:[{float:["right","left","none","start","end"]}],clear:[{clear:["left","right","both","none","start","end"]}],isolation:["isolate","isolation-auto"],"object-fit":[{object:["contain","cover","fill","none","scale-down"]}],"object-position":[{object:[...U(),F]}],overflow:[{overflow:B()}],"overflow-x":[{"overflow-x":B()}],"overflow-y":[{"overflow-y":B()}],overscroll:[{overscroll:w()}],"overscroll-x":[{"overscroll-x":w()}],"overscroll-y":[{"overscroll-y":w()}],position:["static","fixed","absolute","relative","sticky"],inset:[{inset:[p]}],"inset-x":[{"inset-x":[p]}],"inset-y":[{"inset-y":[p]}],start:[{start:[p]}],end:[{end:[p]}],top:[{top:[p]}],right:[{right:[p]}],bottom:[{bottom:[p]}],left:[{left:[p]}],visibility:["visible","invisible","collapse"],z:[{z:["auto",Se,F]}],basis:[{basis:L()}],"flex-direction":[{flex:["row","row-reverse","col","col-reverse"]}],"flex-wrap":[{flex:["wrap","wrap-reverse","nowrap"]}],flex:[{flex:["1","auto","initial","none",F]}],grow:[{grow:b()}],shrink:[{shrink:b()}],order:[{order:["first","last","none",Se,F]}],"grid-cols":[{"grid-cols":[Ae]}],"col-start-end":[{col:["auto",{span:["full",Se,F]},F]}],"col-start":[{"col-start":O()}],"col-end":[{"col-end":O()}],"grid-rows":[{"grid-rows":[Ae]}],"row-start-end":[{row:["auto",{span:[Se,F]},F]}],"row-start":[{"row-start":O()}],"row-end":[{"row-end":O()}],"grid-flow":[{"grid-flow":["row","col","dense","row-dense","col-dense"]}],"auto-cols":[{"auto-cols":["auto","min","max","fr",F]}],"auto-rows":[{"auto-rows":["auto","min","max","fr",F]}],gap:[{gap:[h]}],"gap-x":[{"gap-x":[h]}],"gap-y":[{"gap-y":[h]}],"justify-content":[{justify:["normal",...x()]}],"justify-items":[{"justify-items":["start","end","center","stretch"]}],"justify-self":[{"justify-self":["auto","start","end","center","stretch"]}],"align-content":[{content:["normal",...x(),"baseline"]}],"align-items":[{items:["start","end","center","baseline","stretch"]}],"align-self":[{self:["auto","start","end","center","stretch","baseline"]}],"place-content":[{"place-content":[...x(),"baseline"]}],"place-items":[{"place-items":["start","end","center","baseline","stretch"]}],"place-self":[{"place-self":["auto","start","end","center","stretch"]}],p:[{p:[_]}],px:[{px:[_]}],py:[{py:[_]}],ps:[{ps:[_]}],pe:[{pe:[_]}],pt:[{pt:[_]}],pr:[{pr:[_]}],pb:[{pb:[_]}],pl:[{pl:[_]}],m:[{m:[k]}],mx:[{mx:[k]}],my:[{my:[k]}],ms:[{ms:[k]}],me:[{me:[k]}],mt:[{mt:[k]}],mr:[{mr:[k]}],mb:[{mb:[k]}],ml:[{ml:[k]}],"space-x":[{"space-x":[M]}],"space-x-reverse":["space-x-reverse"],"space-y":[{"space-y":[M]}],"space-y-reverse":["space-y-reverse"],w:[{w:["auto","min","max","fit","svw","lvw","dvw",F,t]}],"min-w":[{"min-w":[F,t,"min","max","fit"]}],"max-w":[{"max-w":[F,t,"none","full","min","max","fit","prose",{screen:[pe]},pe]}],h:[{h:[F,t,"auto","min","max","fit","svh","lvh","dvh"]}],"min-h":[{"min-h":[F,t,"min","max","fit","svh","lvh","dvh"]}],"max-h":[{"max-h":[F,t,"min","max","fit","svh","lvh","dvh"]}],size:[{size:[F,t,"auto","min","max","fit"]}],"font-size":[{text:["base",pe,fe]}],"font-smoothing":["antialiased","subpixel-antialiased"],"font-style":["italic","not-italic"],"font-weight":[{font:["thin","extralight","light","normal","medium","semibold","bold","extrabold","black",Ge]}],"font-family":[{font:[Ae]}],"fvn-normal":["normal-nums"],"fvn-ordinal":["ordinal"],"fvn-slashed-zero":["slashed-zero"],"fvn-figure":["lining-nums","oldstyle-nums"],"fvn-spacing":["proportional-nums","tabular-nums"],"fvn-fraction":["diagonal-fractions","stacked-fractions"],tracking:[{tracking:["tighter","tight","normal","wide","wider","widest",F]}],"line-clamp":[{"line-clamp":["none",ke,Ge]}],leading:[{leading:["none","tight","snug","normal","relaxed","loose",ie,F]}],"list-image":[{"list-image":["none",F]}],"list-style-type":[{list:["none","disc","decimal",F]}],"list-style-position":[{list:["inside","outside"]}],"placeholder-color":[{placeholder:[e]}],"placeholder-opacity":[{"placeholder-opacity":[T]}],"text-alignment":[{text:["left","center","right","justify","start","end"]}],"text-color":[{text:[e]}],"text-opacity":[{"text-opacity":[T]}],"text-decoration":["underline","overline","line-through","no-underline"],"text-decoration-style":[{decoration:[...K(),"wavy"]}],"text-decoration-thickness":[{decoration:["auto","from-font",ie,fe]}],"underline-offset":[{"underline-offset":["auto",ie,F]}],"text-decoration-color":[{decoration:[e]}],"text-transform":["uppercase","lowercase","capitalize","normal-case"],"text-overflow":["truncate","text-ellipsis","text-clip"],"text-wrap":[{text:["wrap","nowrap","balance","pretty"]}],indent:[{indent:E()}],"vertical-align":[{align:["baseline","top","middle","bottom","text-top","text-bottom","sub","super",F]}],whitespace:[{whitespace:["normal","nowrap","pre","pre-line","pre-wrap","break-spaces"]}],break:[{break:["normal","words","all","keep"]}],hyphens:[{hyphens:["none","manual","auto"]}],content:[{content:["none",F]}],"bg-attachment":[{bg:["fixed","local","scroll"]}],"bg-clip":[{"bg-clip":["border","padding","content","text"]}],"bg-opacity":[{"bg-opacity":[T]}],"bg-origin":[{"bg-origin":["border","padding","content"]}],"bg-position":[{bg:[...U(),Mn]}],"bg-repeat":[{bg:["no-repeat",{repeat:["","x","y","round","space"]}]}],"bg-size":[{bg:["auto","cover","contain",xn]}],"bg-image":[{bg:["none",{"gradient-to":["t","tr","r","br","b","bl","l","tl"]},Pn]}],"bg-color":[{bg:[e]}],"gradient-from-pos":[{from:[v]}],"gradient-via-pos":[{via:[v]}],"gradient-to-pos":[{to:[v]}],"gradient-from":[{from:[y]}],"gradient-via":[{via:[y]}],"gradient-to":[{to:[y]}],rounded:[{rounded:[o]}],"rounded-s":[{"rounded-s":[o]}],"rounded-e":[{"rounded-e":[o]}],"rounded-t":[{"rounded-t":[o]}],"rounded-r":[{"rounded-r":[o]}],"rounded-b":[{"rounded-b":[o]}],"rounded-l":[{"rounded-l":[o]}],"rounded-ss":[{"rounded-ss":[o]}],"rounded-se":[{"rounded-se":[o]}],"rounded-ee":[{"rounded-ee":[o]}],"rounded-es":[{"rounded-es":[o]}],"rounded-tl":[{"rounded-tl":[o]}],"rounded-tr":[{"rounded-tr":[o]}],"rounded-br":[{"rounded-br":[o]}],"rounded-bl":[{"rounded-bl":[o]}],"border-w":[{border:[i]}],"border-w-x":[{"border-x":[i]}],"border-w-y":[{"border-y":[i]}],"border-w-s":[{"border-s":[i]}],"border-w-e":[{"border-e":[i]}],"border-w-t":[{"border-t":[i]}],"border-w-r":[{"border-r":[i]}],"border-w-b":[{"border-b":[i]}],"border-w-l":[{"border-l":[i]}],"border-opacity":[{"border-opacity":[T]}],"border-style":[{border:[...K(),"hidden"]}],"divide-x":[{"divide-x":[i]}],"divide-x-reverse":["divide-x-reverse"],"divide-y":[{"divide-y":[i]}],"divide-y-reverse":["divide-y-reverse"],"divide-opacity":[{"divide-opacity":[T]}],"divide-style":[{divide:K()}],"border-color":[{border:[s]}],"border-color-x":[{"border-x":[s]}],"border-color-y":[{"border-y":[s]}],"border-color-s":[{"border-s":[s]}],"border-color-e":[{"border-e":[s]}],"border-color-t":[{"border-t":[s]}],"border-color-r":[{"border-r":[s]}],"border-color-b":[{"border-b":[s]}],"border-color-l":[{"border-l":[s]}],"divide-color":[{divide:[s]}],"outline-style":[{outline:["",...K()]}],"outline-offset":[{"outline-offset":[ie,F]}],"outline-w":[{outline:[ie,fe]}],"outline-color":[{outline:[e]}],"ring-w":[{ring:P()}],"ring-w-inset":["ring-inset"],"ring-color":[{ring:[e]}],"ring-opacity":[{"ring-opacity":[T]}],"ring-offset-w":[{"ring-offset":[ie,fe]}],"ring-offset-color":[{"ring-offset":[e]}],shadow:[{shadow:["","inner","none",pe,_n]}],"shadow-color":[{shadow:[Ae]}],opacity:[{opacity:[T]}],"mix-blend":[{"mix-blend":[...V(),"plus-lighter","plus-darker"]}],"bg-blend":[{"bg-blend":V()}],filter:[{filter:["","none"]}],blur:[{blur:[n]}],brightness:[{brightness:[r]}],contrast:[{contrast:[d]}],"drop-shadow":[{"drop-shadow":["","none",pe,F]}],grayscale:[{grayscale:[c]}],"hue-rotate":[{"hue-rotate":[u]}],invert:[{invert:[g]}],saturate:[{saturate:[I]}],sepia:[{sepia:[N]}],"backdrop-filter":[{"backdrop-filter":["","none"]}],"backdrop-blur":[{"backdrop-blur":[n]}],"backdrop-brightness":[{"backdrop-brightness":[r]}],"backdrop-contrast":[{"backdrop-contrast":[d]}],"backdrop-grayscale":[{"backdrop-grayscale":[c]}],"backdrop-hue-rotate":[{"backdrop-hue-rotate":[u]}],"backdrop-invert":[{"backdrop-invert":[g]}],"backdrop-opacity":[{"backdrop-opacity":[T]}],"backdrop-saturate":[{"backdrop-saturate":[I]}],"backdrop-sepia":[{"backdrop-sepia":[N]}],"border-collapse":[{border:["collapse","separate"]}],"border-spacing":[{"border-spacing":[a]}],"border-spacing-x":[{"border-spacing-x":[a]}],"border-spacing-y":[{"border-spacing-y":[a]}],"table-layout":[{table:["auto","fixed"]}],caption:[{caption:["top","bottom"]}],transition:[{transition:["none","all","","colors","opacity","shadow","transform",F]}],duration:[{duration:D()}],ease:[{ease:["linear","in","out","in-out",F]}],delay:[{delay:D()}],animate:[{animate:["none","spin","ping","pulse","bounce",F]}],transform:[{transform:["","gpu","none"]}],scale:[{scale:[j]}],"scale-x":[{"scale-x":[j]}],"scale-y":[{"scale-y":[j]}],rotate:[{rotate:[Se,F]}],"translate-x":[{"translate-x":[m]}],"translate-y":[{"translate-y":[m]}],"skew-x":[{"skew-x":[S]}],"skew-y":[{"skew-y":[S]}],"transform-origin":[{origin:["center","top","top-right","right","bottom-right","bottom","bottom-left","left","top-left",F]}],accent:[{accent:["auto",e]}],appearance:[{appearance:["none","auto"]}],cursor:[{cursor:["auto","default","pointer","wait","text","move","help","not-allowed","none","context-menu","progress","cell","crosshair","vertical-text","alias","copy","no-drop","grab","grabbing","all-scroll","col-resize","row-resize","n-resize","e-resize","s-resize","w-resize","ne-resize","nw-resize","se-resize","sw-resize","ew-resize","ns-resize","nesw-resize","nwse-resize","zoom-in","zoom-out",F]}],"caret-color":[{caret:[e]}],"pointer-events":[{"pointer-events":["none","auto"]}],resize:[{resize:["none","y","x",""]}],"scroll-behavior":[{scroll:["auto","smooth"]}],"scroll-m":[{"scroll-m":E()}],"scroll-mx":[{"scroll-mx":E()}],"scroll-my":[{"scroll-my":E()}],"scroll-ms":[{"scroll-ms":E()}],"scroll-me":[{"scroll-me":E()}],"scroll-mt":[{"scroll-mt":E()}],"scroll-mr":[{"scroll-mr":E()}],"scroll-mb":[{"scroll-mb":E()}],"scroll-ml":[{"scroll-ml":E()}],"scroll-p":[{"scroll-p":E()}],"scroll-px":[{"scroll-px":E()}],"scroll-py":[{"scroll-py":E()}],"scroll-ps":[{"scroll-ps":E()}],"scroll-pe":[{"scroll-pe":E()}],"scroll-pt":[{"scroll-pt":E()}],"scroll-pr":[{"scroll-pr":E()}],"scroll-pb":[{"scroll-pb":E()}],"scroll-pl":[{"scroll-pl":E()}],"snap-align":[{snap:["start","end","center","align-none"]}],"snap-stop":[{snap:["normal","always"]}],"snap-type":[{snap:["none","x","y","both"]}],"snap-strictness":[{snap:["mandatory","proximity"]}],touch:[{touch:["auto","none","manipulation"]}],"touch-x":[{"touch-pan":["x","left","right"]}],"touch-y":[{"touch-pan":["y","up","down"]}],"touch-pz":["touch-pinch-zoom"],select:[{select:["none","text","all","auto"]}],"will-change":[{"will-change":["auto","scroll","contents","transform",F]}],fill:[{fill:[e,"none"]}],"stroke-w":[{stroke:[ie,fe,Ge]}],stroke:[{stroke:[e,"none"]}],sr:["sr-only","not-sr-only"],"forced-color-adjust":[{"forced-color-adjust":["auto","none"]}]},conflictingClassGroups:{overflow:["overflow-x","overflow-y"],overscroll:["overscroll-x","overscroll-y"],inset:["inset-x","inset-y","start","end","top","right","bottom","left"],"inset-x":["right","left"],"inset-y":["top","bottom"],flex:["basis","grow","shrink"],gap:["gap-x","gap-y"],p:["px","py","ps","pe","pt","pr","pb","pl"],px:["pr","pl"],py:["pt","pb"],m:["mx","my","ms","me","mt","mr","mb","ml"],mx:["mr","ml"],my:["mt","mb"],size:["w","h"],"font-size":["leading"],"fvn-normal":["fvn-ordinal","fvn-slashed-zero","fvn-figure","fvn-spacing","fvn-fraction"],"fvn-ordinal":["fvn-normal"],"fvn-slashed-zero":["fvn-normal"],"fvn-figure":["fvn-normal"],"fvn-spacing":["fvn-normal"],"fvn-fraction":["fvn-normal"],"line-clamp":["display","overflow"],rounded:["rounded-s","rounded-e","rounded-t","rounded-r","rounded-b","rounded-l","rounded-ss","rounded-se","rounded-ee","rounded-es","rounded-tl","rounded-tr","rounded-br","rounded-bl"],"rounded-s":["rounded-ss","rounded-es"],"rounded-e":["rounded-se","rounded-ee"],"rounded-t":["rounded-tl","rounded-tr"],"rounded-r":["rounded-tr","rounded-br"],"rounded-b":["rounded-br","rounded-bl"],"rounded-l":["rounded-tl","rounded-bl"],"border-spacing":["border-spacing-x","border-spacing-y"],"border-w":["border-w-s","border-w-e","border-w-t","border-w-r","border-w-b","border-w-l"],"border-w-x":["border-w-r","border-w-l"],"border-w-y":["border-w-t","border-w-b"],"border-color":["border-color-s","border-color-e","border-color-t","border-color-r","border-color-b","border-color-l"],"border-color-x":["border-color-r","border-color-l"],"border-color-y":["border-color-t","border-color-b"],"scroll-m":["scroll-mx","scroll-my","scroll-ms","scroll-me","scroll-mt","scroll-mr","scroll-mb","scroll-ml"],"scroll-mx":["scroll-mr","scroll-ml"],"scroll-my":["scroll-mt","scroll-mb"],"scroll-p":["scroll-px","scroll-py","scroll-ps","scroll-pe","scroll-pt","scroll-pr","scroll-pb","scroll-pl"],"scroll-px":["scroll-pr","scroll-pl"],"scroll-py":["scroll-pt","scroll-pb"],touch:["touch-x","touch-y","touch-pz"],"touch-x":["touch"],"touch-y":["touch"],"touch-pz":["touch"]},conflictingClassGroupModifiers:{"font-size":["leading"]}}});function Fn(...e){return Un(rn(e))}function Ln(e){let t=!1,n="";for(const s of e){if(s==="\\"){n+=s,t=!t;continue}if(s==="'"&&!t){n+='"';continue}n+=s,t=!1}return n.replace(/\bTrue\b/g,"true").replace(/\bFalse\b/g,"false").replace(/\bNone\b/g,"null")}function Ne(e){const t=e==null?void 0:e.trim();if(!t||!(t.startsWith("{")||t.startsWith("[")))return null;try{return JSON.parse(t)}catch{const n=Ln(t);if(n)try{return JSON.parse(n)}catch{return null}return null}}function bt(e){return typeof e!="string"?!1:/^[\s\n]*[-*]\s|^[\s\n]*#+\s|```|^\s*\[.*\]\(|^>\s/.test(e)}function On(e){return e.type==="image_url"}function $n(e){return e.type==="file"}function Bn(e){return Array.isArray(e.content)?e.content.filter(t=>t.type==="text").map(t=>t.text).join(`
2
2
  `).trim():typeof e.content=="string"?e.content:""}function Dn(e){return e.content.filter(On)}function Vn(e){return e.content.filter($n)}function wt(e){return Array.isArray(e.toolCalls)?e.toolCalls:[]}function Kn(e){const t=[];return e.forEach(n=>{n.artifact&&t.push(n.artifact),Array.isArray(n.toolCalls)&&n.toolCalls.forEach(r=>{r!=null&&r.artifact&&t.push(r.artifact)})}),t}function qe(e){return!!(e&&typeof e=="object"&&(e.type==="file"||e.mimeType||e.filename||e.sourceType==="base64"))}function Ce(e){if(typeof e=="string")return e;if(e&&typeof e=="object"){if(Array.isArray(e)){const n=e.map(Ce).filter(r=>r!==void 0);if(!n.length){console.debug("[message-utils] sanitizeForDisplay - array emptied -> returning undefined",{originalLength:e.length});return}return n}if(qe(e)){try{console.debug("[message-utils] sanitizeForDisplay - dropping file-like object",{sampleFilename:e&&(e.filename||e.name)?e.filename||e.name:void 0,keys:Object.keys(e||{})})}catch(n){console.debug("[message-utils] sanitizeForDisplay - dropped file-like (unable to inspect)",{err:String(n)})}return}const t={};for(const n of Object.keys(e)){const r=e[n];if(n==="data"&&typeof r=="string"&&r.length>100)t[n]=`[base64 ${r.length} chars omitted]`;else{const s=Ce(r);s!==void 0&&(t[n]=s)}}if(Object.keys(t).length)return t;try{console.debug("[message-utils] sanitizeForDisplay - object emptied -> returning undefined",{originalKeys:Object.keys(e||{})})}catch(n){console.debug("[message-utils] sanitizeForDisplay - object emptied -> returning undefined (inspect failed)",{err:String(n)})}return}return e}function We(e){if(typeof e=="string")return e;if(qe(e))return"";try{const t=Ce(e);return t===void 0?"":typeof t=="string"?t:JSON.stringify(t,null,2)}catch{return""}}function Hn(e){const t=We(e);return typeof e=="string"&&bt(e)?{content:e,isMarkdown:!0}:{content:t,isMarkdown:!1}}function kt(e){const t=r=>{try{const s=Ce(r);return typeof s=="string"?s:JSON.stringify(s??"")}catch{return""}},n=e.filter(r=>r.type==="text");return n.length?t(n.map(r=>r.text).join(`
3
- `)):t(e)}function Gn(e){return e.content.some(t=>t.type==="text"?t.text.trim().length>0:t.type==="image_url"||t.type==="file")}function oe(e){if(e==null)return e;if(typeof e=="string"){const t=e.trim();if(t.startsWith("{")||t.startsWith("[")){const n=ze(t);if(n!==null)return oe(n)}return e}if(typeof e=="object"&&!Array.isArray(e)){if(e.content!==void 0)return Array.isArray(e.content)?e.content.map(t=>oe(t)).filter(Boolean).join(`
4
- `):oe(e.content);if(e.value!==void 0)return oe(e.value)}return typeof e=="object"&&!Array.isArray(e)&&(e.type==="text"&&typeof e.text=="string"||typeof e.text=="string")?e.text:Array.isArray(e)&&e.length>0?oe(e[0]):e}function qn(e){return e.replace(/[_-](\w)/g,(t,n)=>n?n.toUpperCase():"").replace(/^\w/,t=>t.toLowerCase())}function ae(e){return!e||typeof e!="object"?e:Array.isArray(e)?e.map(ae):Object.fromEntries(Object.entries(e).map(([t,n])=>[qn(t),ae(n)]))}function Je(e){var k,T,E,I,j,z;if(!e||typeof e!="object")return null;const t=ae(e),n=Xn(t);if(!n)return null;const r=Array.isArray(t.toolCalls)?t.toolCalls.map(Xe):void 0,s=Jn(t.content??t.parts,!!(r!=null&&r.length)),o=t.id??`msg-${Date.now().toString(16)}-${Math.random().toString(16).slice(2)}`,a=t.createdAt??((k=t.additionalKwargs)==null?void 0:k.createdAt)??new Date().toISOString(),i=t.name??((T=t.additionalKwargs)==null?void 0:T.agentName)??void 0,d=t.model??((E=t.additionalKwargs)==null?void 0:E.model)??void 0,c=t.toolCallId??void 0,u=t.additionalKwargs??void 0,g=t.responseMetadata??void 0,h=t.checkpointId??((I=t.additionalKwargs)==null?void 0:I.checkpointId)??void 0,y=t.checkpointNs??((j=t.additionalKwargs)==null?void 0:j.checkpointNs)??void 0,v=typeof t.toolStreaming=="boolean"?t.toolStreaming:!!((z=t.additionalKwargs)!=null&&z.toolStreaming);return{...t,id:o,role:n,content:s,createdAt:a,name:i,model:d,toolCallId:c,toolCalls:r,checkpointId:h,checkpointNs:y,toolStreaming:v,additionalKwargs:u,responseMetadata:g,artifact:t.artifact??void 0}}function Wn(e){if(!e||typeof e!="object")return e;const t=ae(e);if(t.tool&&!t.name&&(t.name=t.tool),t.type==="artifact.update"&&t.artifact&&typeof t.artifact=="object"){const n=t.artifact;!n.id&&n.artifactId&&(n.id=n.artifactId),!n.type&&n.artifactType&&(n.type=n.artifactType)}return t}function Xe(e){const t=ae(e),n=t.content??t.output??void 0;return{...t,type:"tool_call",id:t.id??t.callId,name:t.name??t.tool??void 0,args:t.args??t.arguments??void 0,content:typeof n=="string"?n:n?JSON.stringify(n):void 0}}function Jn(e,t){return Array.isArray(e)?e.map(n=>n.type==="tool_call"||n.type==="tool"?t?null:Xe(ae(n)):n).filter(n=>!!(n&&typeof n=="object"&&typeof n.type=="string")):[]}function Xn(e){const t=ae(e),n=t.role;if(n&&(n==="assistant"||n==="user"||n==="system"||n==="tool"||n==="interrupt"))return n;const r=t.type;return r==="human"?"user":r==="ai"?"assistant":r==="tool"?"tool":r==="system"?"system":null}function vt(e){if(!e)return null;const t=String(e).toLowerCase();return t==="running"||t==="pending"?"pending":t==="completed"||t==="success"?"completed":t==="error"||t==="failed"||t==="failure"?"error":null}function Tt(e){return(Array.isArray(e.toolCalls)?e.toolCalls:wt(e)).map(Xe)}function Qe(e,t){return t.find(n=>n.role==="tool"&&(n.toolCallId===e||n.id===e))}function Qn(e,t){const n=t.response??t.content;if(!n)return;const r=typeof n=="string"?n:We(n);if(!r.trim())return;const s=[{type:"text",text:r}];return{id:`tool-${t.id}`,role:"tool",content:s,name:t.name,toolCallId:t.id,artifact:t.artifact,createdAt:e.createdAt}}function It(e,t=[]){if(Array.isArray(e)){const s=e.filter(a=>a.role==="assistant").flatMap(a=>Tt(a)),o=new Map;return s.forEach(a=>o.set(a.id,a)),Array.from(o.values()).map(a=>{var g,h,y;const i=Qe(a.id,e)||Qe(a.id,t),d=Array.isArray((g=i==null?void 0:i.additionalKwargs)==null?void 0:g.toolProgress)?(h=i==null?void 0:i.additionalKwargs)==null?void 0:h.toolProgress:void 0,c=(i==null?void 0:i.artifact)??a.artifact,u=vt(a.status)??((y=i==null?void 0:i.additionalKwargs)!=null&&y.toolStreaming?"pending":null)??(i?"completed":"pending");if(i&&!a.content&&u==="completed"){const v=oe(i);typeof v=="string"&&(a.content=v)}return{call:a,result:i,state:u,progress:d,artifact:c}})}if(e.role!=="assistant")return[];const n=Tt(e);return n.length===0?[]:n.map(r=>{var d,c,u;const s=Qe(r.id,t)??Qn(e,r),o=Array.isArray((d=s==null?void 0:s.additionalKwargs)==null?void 0:d.toolProgress)?(c=s==null?void 0:s.additionalKwargs)==null?void 0:c.toolProgress:void 0,a=(s==null?void 0:s.artifact)??r.artifact,i=vt(r.status)??((u=s==null?void 0:s.additionalKwargs)!=null&&u.toolStreaming?"pending":null)??(s?"completed":"pending");if(s&&!r.content&&i==="completed"){const g=oe(s);typeof g=="string"&&(r.content=g)}return{call:r,result:s,state:i,progress:o,artifact:a}})}function Yn(e,t=[]){return It(e,t).map(n=>n.artifact).filter(n=>!!n)}const xe={authToken:"authToken",authTokenExpiresAt:"authTokenExpiresAt",authSessionId:"authSessionId",chatSettings:"chat-settings",threadManagerView:"thread-manager-view",playgroundSettings:"new-chat-ui-chat-settings",debugLogs:"app:debugLogs"};function Ye(e){return`draft:${e}`}let Ne=null;const Ze=new Set;function Re(){return Ne}function ge(e){Ne=e,Ze.forEach(t=>t(e))}function et(e){return Ze.add(e),()=>Ze.delete(e)}const Zn=12e4,Rn=12e4;let tt=Zn,St=Rn;const R=lt.create({timeout:tt,withCredentials:!0});function At(e){return typeof e!="number"||!Number.isFinite(e)||e<=0?null:Math.floor(e)}function er(e){const t=At(e.requestTimeoutMs),n=At(e.historyTimeoutMs);t!==null&&(tt=t,R.defaults.timeout=tt),n!==null&&(St=n)}function tr(){return St}R.interceptors.request.use(e=>(Ne&&(e.headers.Authorization=`Bearer ${Ne}`),e)),R.interceptors.response.use(e=>{if(typeof window<"u"&&(e!=null&&e.data))try{const t=e.data,n=t.data||{},r=typeof t.token=="string"&&t.token||typeof n.token=="string"&&n.token||null,s=typeof t.expires_at=="number"&&t.expires_at||typeof n.expires_at=="number"&&n.expires_at||typeof t.expiresAt=="number"&&t.expiresAt||typeof n.expiresAt=="number"&&n.expiresAt||null;r&&(localStorage.setItem(xe.authToken,r),ge(r)),s&&localStorage.setItem(xe.authTokenExpiresAt,s.toString()),(r||s)&&window.dispatchEvent(new CustomEvent("smartorg:chat-token-updated",{detail:{token:r,expiresAt:s}}))}catch(t){console.warn("[chat-api] Error storing token:",t)}return e},e=>Promise.reject(e));async function re(e,t){return R.defaults.baseURL?(await R.get(e,t)).data:Promise.reject(new Error("API base URL is not configured"))}async function je(e,t,n){return R.defaults.baseURL?(await R.post(e,t,n)).data:Promise.reject(new Error("API base URL is not configured"))}async function nr(e,t,n){return R.defaults.baseURL?(await R.put(e,t,n)).data:Promise.reject(new Error("API base URL is not configured"))}async function Ct(e,t){return R.defaults.baseURL?(await R.delete(e,t)).data:Promise.reject(new Error("API base URL is not configured"))}function ee(e){return e&&typeof e=="object"&&"data"in e?e.data:e}class rr{get baseUrl(){return R.defaults.baseURL||""}updateConfig(t){if(t.chatBaseUrl)R.defaults.baseURL=t.chatBaseUrl;else if(t.baseUrl){const n=t.baseUrl.replace(/\/+$/,"");R.defaults.baseURL=n}t.apiKey!==void 0?ge(t.apiKey):t.getToken&&ge(t.getToken()),(t.requestTimeoutMs!==void 0||t.historyTimeoutMs!==void 0)&&er({requestTimeoutMs:t.requestTimeoutMs,historyTimeoutMs:t.historyTimeoutMs})}getAuthToken(){return Re()}setAuthToken(t){ge(t)}onTokenChange(t){return et(t)}async listThreads(){const t=await re("/threads"),n=ee(t);return(n==null?void 0:n.items)??(t==null?void 0:t.items)??[]}async listSharedThreads(){const t=await re("/threads/shared"),n=ee(t);return(n==null?void 0:n.items)??(t==null?void 0:t.items)??[]}async createThread(t,n){const r={};t&&(r.title=t),n&&(r.project=n);const s=await je("/threads",Object.keys(r).length?r:void 0);return ee(s)}async updateThread(t,n){const r=await nr(`/threads/${t}`,{title:n});return ee(r)}async deleteThread(t){const n=await Ct(`/threads/${t}`);return ee(n)}async shareThread(t,n){const r=await je(`/threads/${t}/share`,{shared_with_user_id:n});return ee(r)}async threadInfo(t){const n=await re(`/threads/${t}/info`);return ee(n)}async listAgents(){const t=await re("/agents"),n=ee(t);return(n==null?void 0:n.items)??[]}async getAgent(t){const n=await re(`/agents/${t}`);return ee(n)}async getAgentSchema(t){const n=await re(`/agents/${t}/schema`);return ee(n)}async getState(t){const n=await re(`/threads/${t.threadId}/state`,{params:{checkpoint_id:t.checkpointId,checkpoint_ns:t.checkpointNs}});return ee(n)}async getStateHistory(t){const n=await re(`/threads/${t.threadId}/state/history`,{params:{checkpoint_id:t.checkpointId,checkpoint_ns:t.checkpointNs,limit:t.limit??100,offset:t.offset??0,include_messages:t.includeMessages??!0},timeout:tr(),signal:t.signal});return ee(n)}async cancelRun(t){const n=await je(`/runs/${t}/cancel`);return ee(n)}async unshareThread(t,n){const r=await Ct(`/threads/${t}/share/${n}`);return ee(r)}}const xt=new rr;class sr{async fetchFileBlob(t,n){return await re(t,{responseType:"blob",onDownloadProgress:s=>{try{if(n&&s.lengthComputable){const o=s.loaded/s.total;n(o)}}catch{}},maxBodyLength:1/0})}async viewFileById(t,n){const r=await this.fetchFileBlob(`/files/${t}/view`,n),s=URL.createObjectURL(r);window.open(s,"_blank"),setTimeout(()=>URL.revokeObjectURL(s),6e4)}async getFileBlob(t,n){return await this.fetchFileBlob(`/files/${t}/view`,n)}async getFileContent(t,n){return await(await this.fetchFileBlob(`/files/${t}/view`,n)).text()}async downloadFileById(t,n){const r=await this.fetchFileBlob(`/files/${t}/download`,n),s=URL.createObjectURL(r);let o=`file_${t}`;try{const i=await re(`/files/${t}`);o=(i==null?void 0:i.filename)??o}catch{}const a=document.createElement("a");a.href=s,a.download=o,document.body.appendChild(a),a.click(),a.remove(),setTimeout(()=>URL.revokeObjectURL(s),6e4)}async getFileInfo(t){return await re(`/files/${t}`)}async listFiles(t,n=50,r=0){const s={limit:n,offset:r};return t&&(s.thread_id=t),await re("/files",{params:s})}async uploadFile(t,n,r){const s=new FormData;return s.append("file",t),n&&s.append("thread_id",n),await je("/files/upload-form",s,{onUploadProgress:o=>{try{if(r&&o.lengthComputable){const a=o.loaded/o.total;r(a)}}catch{}}})}}const Mt=new sr;class or{constructor(){tn(this,"_authBaseUrl","")}get baseUrl(){return this._authBaseUrl}updateConfig(t){if(t.authBaseUrl)this._authBaseUrl=t.authBaseUrl;else if(t.baseUrl){const n=t.baseUrl.replace(/\/+$/,"");this._authBaseUrl=`${n}/auth`}t.apiKey!==void 0?ge(t.apiKey):t.getToken&&ge(t.getToken())}getAuthToken(){return Re()}setAuthToken(t){ge(t)}onTokenChange(t){return et(t)}async listUsers(){const t=await re("/users",{baseURL:this.baseUrl});return(t==null?void 0:t.users)??[]}}const ar=new or,Et=l.createContext(null);function ir({children:e,apiConfig:t}){const n=xt,r=ar;if(t){const o=n.baseUrl,a=r.baseUrl,i=n.getAuthToken(),d=t.requestTimeoutMs!==void 0||t.historyTimeoutMs!==void 0;(t.baseUrl||t.chatBaseUrl||d)&&(d||t.chatBaseUrl&&t.chatBaseUrl!==o||t.baseUrl&&!o.startsWith(t.baseUrl))&&n.updateConfig(t),(t.baseUrl||t.authBaseUrl)&&(t.authBaseUrl&&t.authBaseUrl!==a||t.baseUrl&&!a.startsWith(t.baseUrl))&&r.updateConfig(t),t.apiKey!==void 0&&t.apiKey!==i&&(n.updateConfig({apiKey:t.apiKey}),r.updateConfig({apiKey:t.apiKey}))}const s={token:n.getAuthToken(),setToken:o=>{n.setAuthToken(o),r.setAuthToken(o)},chatApi:n,authApi:r,fileApi:Mt,baseUrl:n.baseUrl};return G.jsx(Et.Provider,{value:s,children:e})}async function lr(e){return await new Promise((t,n)=>{const r=new FileReader;r.onload=()=>{try{const s=r.result,o=new Uint8Array(s);let a="";const i=o.byteLength;for(let d=0;d<i;d++)a+=String.fromCharCode(o[d]);t(btoa(a))}catch(s){n(s)}},r.onerror=s=>n(s),r.readAsArrayBuffer(e)})}async function cr(e=[]){const t=[],n=[];for(const r of e)try{const s=await lr(r),o=r.type||"application/octet-stream";n.push({filename:r.name,data:s,mime_type:o}),o.startsWith("image/")?t.push({type:"image_url",image_url:{url:`data:${o};base64,${s}`}}):t.push({type:"file",url:`data:${o};base64,${s}`,mimeType:o,name:r.name,size:r.size})}catch{}return{contentParts:t,filesInfo:n}}function Pt(e){return e.filter(t=>t.type==="text").map(t=>t.text).join("")}function ur(e){if(e==null)return null;const t=String(e).trim();return t.length>0?t:null}function _t(e){const t=e.toolCallId??(e.role==="tool"?e.id:void 0);return e.role==="tool"&&!t&&console.error("[meta-utils] CRITICAL: Tool message missing toolCallId!",e),{toolCallId:t??void 0,name:e.name??void 0}}function dr(e){var n;if(e.name&&e.name.trim())return e.name;const t=(n=e.additionalKwargs)==null?void 0:n.agentName;return typeof t=="string"&&t.trim()?t:e.model&&e.model.includes("/")?e.model.split("/").pop()||null:e.model||null}function fr(e){const t=e.updatedAt??e.createdAt??"",n=Array.isArray(e.content)?e.content.map(a=>{switch(a.type){case"text":return`t:${a.text.length}`;case"image_url":return"img";default:return a.type==="interrupt"?"interrupt":"unknown"}}).join("|"):"",r="checkpointId"in e&&e.checkpointId?`cp:${e.checkpointId}`:"",s="checkpointNs"in e&&e.checkpointNs?`ns:${e.checkpointNs}`:"",o=[r,s].filter(Boolean).join("|");return`${e.id}:${t}:${n}${o?`:${o}`:""}`}function be(){const e=l.useContext(Et);if(!e)throw new Error("useApi must be used within ApiProvider");return e}function pr(e,t,n){const r=typeof t=="string"?[{type:"text",text:t}]:t;return{id:`msg-${Date.now()}-${Math.random().toString(36).slice(2,9)}`,role:e,content:r,createdAt:new Date().toISOString(),...n}}function zt(e,t="user"){return typeof e=="string"?pr(t,e):e}function gr(e){return!!e&&typeof e=="object"&&"data"in e}function Nt(e={}){const t=e.baseUrl||"",n=e.streamPath??"/runs/stream",[r,s]=l.useState(e.token??null),o=l.useRef(e.headers??{}),a=e.credentials??"include",i=l.useRef(e);l.useEffect(()=>{i.current=e},[e]);const d=l.useCallback(m=>{var F,M,_,O,U,K,q,w,S,D;const b=i.current;if(!b)return;(F=b.onEvent)==null||F.call(b,m),m.type==="thread_info"&&((M=b.onThreadInfo)==null||M.call(b,m)),m.type==="values"&&Array.isArray(m.checkpoints)&&((_=b.handleValuesEvent)==null||_.call(b,m)),m.type==="metadata"&&((O=b.onMetadataEvent)==null||O.call(b,m)),typeof m.type=="string"&&(m.type==="custom"||m.type.startsWith("custom."))&&((U=b.onCustomEvent)==null||U.call(b,m)),m.type==="updates"&&((K=b.onUpdateEvent)==null||K.call(b,m)),m.type==="tool.end"?(q=b.onToolEnd)==null||q.call(b,m):m.type==="tool.start"&&((w=b.onToolStart)==null||w.call(b,m)),m.type==="heartbeat"&&((S=b.onHeartbeat)==null||S.call(b,m)),m.type==="token"&&((D=b.onToken)==null||D.call(b,m.token))},[]),[c,u]=l.useState(!1),[g,h]=l.useState(null),[y,v]=l.useState(!1),[p,k]=l.useState(null),T=l.useRef(null),E=l.useRef(!0),I=l.useRef(null),j=l.useCallback(m=>{s(m)},[]),z=l.useCallback(()=>{h(null),k(null)},[]),A=l.useCallback(()=>{var M,_;console.debug("[use-chat] stop() invoked - aborting stream");const m=(M=I.current)==null?void 0:M.threadId,b=(_=I.current)==null?void 0:_.runId,$=()=>{var O;(O=T.current)==null||O.abort(),T.current=null,I.current=null,u(!1),v(!1)};(b||m?xt.cancelRun(b||m).catch(O=>{console.warn("[use-chat] cancel run failed:",O)}):Promise.resolve()).finally($)},[]),P=l.useCallback(m=>{T.current&&(T.current.abort(),T.current=null);const b={text:typeof m.content=="string"?m.content:m.text,threadId:m.threadId,attachments:m.attachments,payload:m.payload,config:m.config,checkpointId:m.checkpointId,checkpointNs:m.checkpointNs||void 0,edit:m.edit,command:m.command};u(!0),h(null),k(null);const $=new AbortController;T.current=$;let F=null,M=!1;return I.current={threadId:b.threadId??void 0,runId:void 0,headers:{},isStreaming:!0},(async()=>{var _,O,U,K,q,w;try{let S={};try{if(r)S={Authorization:`Bearer ${r}`};else if(typeof window<"u"){const Z=window.__AUTH_TOKEN__,we=((_=window.localStorage)==null?void 0:_.getItem(xe.authToken))||null;let X=null;try{const me=(O=window.localStorage)==null?void 0:O.getItem(xe.chatSettings);me&&(X=((U=JSON.parse(me))==null?void 0:U.apiKey)||null)}catch{}const Q=Z||we||X||null;Q&&(S={Authorization:`Bearer ${Q}`})}}catch{}console.debug("[use-chat] POST",t+n);let D={};if(typeof window<"u")try{const W=(K=window.localStorage)==null?void 0:K.getItem(xe.authSessionId);W&&(D={"X-Session-Id":W})}catch{}const B={...S,...D,...o.current},f={"Content-Type":"application/json",Accept:"text/event-stream",...B},x=await fetch(t+n,{method:"POST",headers:f,body:JSON.stringify(b),signal:$.signal,credentials:a});if(I.current&&(I.current.headers=B),!x.ok||!x.body){const W=await x.text().catch(()=>"");console.debug("[use-chat] non-OK response",x.status,W==null?void 0:W.slice(0,500));const Z=`stream ${x.status}${W?": "+W:""}`;throw Z&&(h(Z),F="error"),new Error(Z)}v(!0);const N=x.body.getReader(),te=new TextDecoder;let J="",H=0,Y=Date.now();const se=setInterval(()=>{Date.now()-Y>18e5&&(h("Stream idle timeout"),F="error",$.abort())},5e3),ue=1024*1024;try{const W=x.headers.get("X-Thread-Id")||x.headers.get("x-thread-id"),Z=x.headers.get("X-Run-Id")||x.headers.get("x-run-id");for(I.current&&(I.current={...I.current,threadId:W??I.current.threadId,runId:Z??I.current.runId});;){const{value:we,done:X}=await N.read();if(X)break;J+=te.decode(we,{stream:!0}),J.length>ue&&(J="",console.warn("Stream buffer reset: exceeded 1MB"));let Q;for(;(Q=J.indexOf(`
3
+ `)):t(e)}function Gn(e){return e.content.some(t=>t.type==="text"?t.text.trim().length>0:t.type==="image_url"||t.type==="file")}function oe(e){if(e==null)return e;if(typeof e=="string"){const t=e.trim();if(t.startsWith("{")||t.startsWith("[")){const n=Ne(t);if(n!==null)return oe(n)}return e}if(typeof e=="object"&&!Array.isArray(e)){if(e.content!==void 0)return Array.isArray(e.content)?e.content.map(t=>oe(t)).filter(Boolean).join(`
4
+ `):oe(e.content);if(e.value!==void 0)return oe(e.value)}return typeof e=="object"&&!Array.isArray(e)&&(e.type==="text"&&typeof e.text=="string"||typeof e.text=="string")?e.text:Array.isArray(e)&&e.length>0?oe(e[0]):e}function qn(e){return e.replace(/[_-](\w)/g,(t,n)=>n?n.toUpperCase():"").replace(/^\w/,t=>t.toLowerCase())}function ae(e){return!e||typeof e!="object"?e:Array.isArray(e)?e.map(ae):Object.fromEntries(Object.entries(e).map(([t,n])=>[qn(t),ae(n)]))}function Je(e){var k,T,_,I,j,N;if(!e||typeof e!="object")return null;const t=ae(e),n=Xn(t);if(!n)return null;const r=Array.isArray(t.toolCalls)?t.toolCalls.map(Xe):void 0,s=Jn(t.content??t.parts,!!(r!=null&&r.length)),o=t.id??`msg-${Date.now().toString(16)}-${Math.random().toString(16).slice(2)}`,a=t.createdAt??((k=t.additionalKwargs)==null?void 0:k.createdAt)??new Date().toISOString(),i=t.name??((T=t.additionalKwargs)==null?void 0:T.agentName)??void 0,d=t.model??((_=t.additionalKwargs)==null?void 0:_.model)??void 0,c=t.toolCallId??void 0,u=t.additionalKwargs??void 0,g=t.responseMetadata??void 0,h=t.checkpointId??((I=t.additionalKwargs)==null?void 0:I.checkpointId)??void 0,y=t.checkpointNs??((j=t.additionalKwargs)==null?void 0:j.checkpointNs)??void 0,v=typeof t.toolStreaming=="boolean"?t.toolStreaming:!!((N=t.additionalKwargs)!=null&&N.toolStreaming);return{...t,id:o,role:n,content:s,createdAt:a,name:i,model:d,toolCallId:c,toolCalls:r,checkpointId:h,checkpointNs:y,toolStreaming:v,additionalKwargs:u,responseMetadata:g,artifact:t.artifact??void 0}}function Wn(e){if(!e||typeof e!="object")return e;const t=ae(e);if(t.tool&&!t.name&&(t.name=t.tool),t.type==="artifact.update"&&t.artifact&&typeof t.artifact=="object"){const n=t.artifact;!n.id&&n.artifactId&&(n.id=n.artifactId),!n.type&&n.artifactType&&(n.type=n.artifactType)}return t}function Xe(e){const t=ae(e),n=t.content??t.output??void 0;return{...t,type:"tool_call",id:t.id??t.callId,name:t.name??t.tool??void 0,args:t.args??t.arguments??void 0,content:typeof n=="string"?n:n?JSON.stringify(n):void 0}}function Jn(e,t){return typeof e=="string"?[{type:"text",text:e}]:Array.isArray(e)?e.map(n=>typeof n=="string"?{type:"text",text:n}:n.type==="tool_call"||n.type==="tool"?t?null:Xe(ae(n)):n).filter(n=>!!(n&&typeof n=="object"&&typeof n.type=="string")):[]}function Xn(e){const t=ae(e),n=t.role;if(n&&(n==="assistant"||n==="user"||n==="system"||n==="tool"||n==="interrupt"))return n;const r=t.type;return r==="human"?"user":r==="ai"?"assistant":r==="tool"?"tool":r==="system"?"system":null}function vt(e){if(!e)return null;const t=String(e).toLowerCase();return t==="running"||t==="pending"?"pending":t==="completed"||t==="success"?"completed":t==="error"||t==="failed"||t==="failure"?"error":null}function Tt(e){return(Array.isArray(e.toolCalls)?e.toolCalls:wt(e)).map(Xe)}function Qe(e,t){return t.find(n=>n.role==="tool"&&(n.toolCallId===e||n.id===e))}function Qn(e,t){const n=t.response??t.content;if(!n)return;const r=typeof n=="string"?n:We(n);if(!r.trim())return;const s=[{type:"text",text:r}];return{id:`tool-${t.id}`,role:"tool",content:s,name:t.name,toolCallId:t.id,artifact:t.artifact,createdAt:e.createdAt}}function It(e,t=[]){if(Array.isArray(e)){const s=e.filter(a=>a.role==="assistant").flatMap(a=>Tt(a)),o=new Map;return s.forEach(a=>o.set(a.id,a)),Array.from(o.values()).map(a=>{var g,h,y;const i=Qe(a.id,e)||Qe(a.id,t),d=Array.isArray((g=i==null?void 0:i.additionalKwargs)==null?void 0:g.toolProgress)?(h=i==null?void 0:i.additionalKwargs)==null?void 0:h.toolProgress:void 0,c=(i==null?void 0:i.artifact)??a.artifact,u=vt(a.status)??((y=i==null?void 0:i.additionalKwargs)!=null&&y.toolStreaming?"pending":null)??(i?"completed":"pending");if(i&&!a.content&&u==="completed"){const v=oe(i);typeof v=="string"&&(a.content=v)}return{call:a,result:i,state:u,progress:d,artifact:c}})}if(e.role!=="assistant")return[];const n=Tt(e);return n.length===0?[]:n.map(r=>{var d,c,u;const s=Qe(r.id,t)??Qn(e,r),o=Array.isArray((d=s==null?void 0:s.additionalKwargs)==null?void 0:d.toolProgress)?(c=s==null?void 0:s.additionalKwargs)==null?void 0:c.toolProgress:void 0,a=(s==null?void 0:s.artifact)??r.artifact,i=vt(r.status)??((u=s==null?void 0:s.additionalKwargs)!=null&&u.toolStreaming?"pending":null)??(s?"completed":"pending");if(s&&!r.content&&i==="completed"){const g=oe(s);typeof g=="string"&&(r.content=g)}return{call:r,result:s,state:i,progress:o,artifact:a}})}function Yn(e,t=[]){return It(e,t).map(n=>n.artifact).filter(n=>!!n)}const xe={authToken:"authToken",authTokenExpiresAt:"authTokenExpiresAt",authSessionId:"authSessionId",chatSettings:"chat-settings",threadManagerView:"thread-manager-view",playgroundSettings:"new-chat-ui-chat-settings",debugLogs:"app:debugLogs"};function Ye(e){return`draft:${e}`}let ze=null;const Ze=new Set;function Re(){return ze}function ge(e){ze=e,Ze.forEach(t=>t(e))}function et(e){return Ze.add(e),()=>Ze.delete(e)}const Zn=12e4,Rn=12e4;let tt=Zn,St=Rn;const R=lt.create({timeout:tt,withCredentials:!0});function At(e){return typeof e!="number"||!Number.isFinite(e)||e<=0?null:Math.floor(e)}function er(e){const t=At(e.requestTimeoutMs),n=At(e.historyTimeoutMs);t!==null&&(tt=t,R.defaults.timeout=tt),n!==null&&(St=n)}function tr(){return St}R.interceptors.request.use(e=>(ze&&(e.headers.Authorization=`Bearer ${ze}`),e)),R.interceptors.response.use(e=>{if(typeof window<"u"&&(e!=null&&e.data))try{const t=e.data,n=t.data||{},r=typeof t.token=="string"&&t.token||typeof n.token=="string"&&n.token||null,s=typeof t.expires_at=="number"&&t.expires_at||typeof n.expires_at=="number"&&n.expires_at||typeof t.expiresAt=="number"&&t.expiresAt||typeof n.expiresAt=="number"&&n.expiresAt||null;r&&(localStorage.setItem(xe.authToken,r),ge(r)),s&&localStorage.setItem(xe.authTokenExpiresAt,s.toString()),(r||s)&&window.dispatchEvent(new CustomEvent("smartorg:chat-token-updated",{detail:{token:r,expiresAt:s}}))}catch(t){console.warn("[chat-api] Error storing token:",t)}return e},e=>Promise.reject(e));async function re(e,t){return R.defaults.baseURL?(await R.get(e,t)).data:Promise.reject(new Error("API base URL is not configured"))}async function je(e,t,n){return R.defaults.baseURL?(await R.post(e,t,n)).data:Promise.reject(new Error("API base URL is not configured"))}async function nr(e,t,n){return R.defaults.baseURL?(await R.put(e,t,n)).data:Promise.reject(new Error("API base URL is not configured"))}async function Ct(e,t){return R.defaults.baseURL?(await R.delete(e,t)).data:Promise.reject(new Error("API base URL is not configured"))}function ee(e){return e&&typeof e=="object"&&"data"in e?e.data:e}class rr{get baseUrl(){return R.defaults.baseURL||""}updateConfig(t){if(t.chatBaseUrl)R.defaults.baseURL=t.chatBaseUrl;else if(t.baseUrl){const n=t.baseUrl.replace(/\/+$/,"");R.defaults.baseURL=n}t.apiKey!==void 0?ge(t.apiKey):t.getToken&&ge(t.getToken()),(t.requestTimeoutMs!==void 0||t.historyTimeoutMs!==void 0)&&er({requestTimeoutMs:t.requestTimeoutMs,historyTimeoutMs:t.historyTimeoutMs})}getAuthToken(){return Re()}setAuthToken(t){ge(t)}onTokenChange(t){return et(t)}async listThreads(){const t=await re("/threads"),n=ee(t);return(n==null?void 0:n.items)??(t==null?void 0:t.items)??[]}async listSharedThreads(){const t=await re("/threads/shared"),n=ee(t);return(n==null?void 0:n.items)??(t==null?void 0:t.items)??[]}async createThread(t,n){const r={};t&&(r.title=t),n&&(r.project=n);const s=await je("/threads",Object.keys(r).length?r:void 0);return ee(s)}async updateThread(t,n){const r=await nr(`/threads/${t}`,{title:n});return ee(r)}async deleteThread(t){const n=await Ct(`/threads/${t}`);return ee(n)}async shareThread(t,n){const r=await je(`/threads/${t}/share`,{shared_with_user_id:n});return ee(r)}async threadInfo(t){const n=await re(`/threads/${t}/info`);return ee(n)}async listAgents(){const t=await re("/agents"),n=ee(t);return(n==null?void 0:n.items)??[]}async getAgent(t){const n=await re(`/agents/${t}`);return ee(n)}async getAgentSchema(t){const n=await re(`/agents/${t}/schema`);return ee(n)}async getState(t){const n=await re(`/threads/${t.threadId}/state`,{params:{checkpoint_id:t.checkpointId,checkpoint_ns:t.checkpointNs}});return ee(n)}async getStateHistory(t){const n=await re(`/threads/${t.threadId}/state/history`,{params:{checkpoint_id:t.checkpointId,checkpoint_ns:t.checkpointNs,limit:t.limit??100,offset:t.offset??0,include_messages:t.includeMessages??!0},timeout:tr(),signal:t.signal});return ee(n)}async cancelRun(t){const n=await je(`/runs/${t}/cancel`);return ee(n)}async unshareThread(t,n){const r=await Ct(`/threads/${t}/share/${n}`);return ee(r)}}const xt=new rr;class sr{async fetchFileBlob(t,n){return await re(t,{responseType:"blob",onDownloadProgress:s=>{try{if(n&&s.lengthComputable){const o=s.loaded/s.total;n(o)}}catch{}},maxBodyLength:1/0})}async viewFileById(t,n){const r=await this.fetchFileBlob(`/files/${t}/view`,n),s=URL.createObjectURL(r);window.open(s,"_blank"),setTimeout(()=>URL.revokeObjectURL(s),6e4)}async getFileBlob(t,n){return await this.fetchFileBlob(`/files/${t}/view`,n)}async getFileContent(t,n){return await(await this.fetchFileBlob(`/files/${t}/view`,n)).text()}async downloadFileById(t,n){const r=await this.fetchFileBlob(`/files/${t}/download`,n),s=URL.createObjectURL(r);let o=`file_${t}`;try{const i=await re(`/files/${t}`);o=(i==null?void 0:i.filename)??o}catch{}const a=document.createElement("a");a.href=s,a.download=o,document.body.appendChild(a),a.click(),a.remove(),setTimeout(()=>URL.revokeObjectURL(s),6e4)}async getFileInfo(t){return await re(`/files/${t}`)}async listFiles(t,n=50,r=0){const s={limit:n,offset:r};return t&&(s.thread_id=t),await re("/files",{params:s})}async uploadFile(t,n,r){const s=new FormData;return s.append("file",t),n&&s.append("thread_id",n),await je("/files/upload-form",s,{onUploadProgress:o=>{try{if(r&&o.lengthComputable){const a=o.loaded/o.total;r(a)}}catch{}}})}}const Mt=new sr;class or{constructor(){tn(this,"_authBaseUrl","")}get baseUrl(){return this._authBaseUrl}updateConfig(t){if(t.authBaseUrl)this._authBaseUrl=t.authBaseUrl;else if(t.baseUrl){const n=t.baseUrl.replace(/\/+$/,"");this._authBaseUrl=`${n}/auth`}t.apiKey!==void 0?ge(t.apiKey):t.getToken&&ge(t.getToken())}getAuthToken(){return Re()}setAuthToken(t){ge(t)}onTokenChange(t){return et(t)}async listUsers(){const t=await re("/users",{baseURL:this.baseUrl});return(t==null?void 0:t.users)??[]}}const ar=new or,Et=l.createContext(null);function ir({children:e,apiConfig:t}){const n=xt,r=ar;if(t){const o=n.baseUrl,a=r.baseUrl,i=n.getAuthToken(),d=t.requestTimeoutMs!==void 0||t.historyTimeoutMs!==void 0;(t.baseUrl||t.chatBaseUrl||d)&&(d||t.chatBaseUrl&&t.chatBaseUrl!==o||t.baseUrl&&!o.startsWith(t.baseUrl))&&n.updateConfig(t),(t.baseUrl||t.authBaseUrl)&&(t.authBaseUrl&&t.authBaseUrl!==a||t.baseUrl&&!a.startsWith(t.baseUrl))&&r.updateConfig(t),t.apiKey!==void 0&&t.apiKey!==i&&(n.updateConfig({apiKey:t.apiKey}),r.updateConfig({apiKey:t.apiKey}))}const s={token:n.getAuthToken(),setToken:o=>{n.setAuthToken(o),r.setAuthToken(o)},chatApi:n,authApi:r,fileApi:Mt,baseUrl:n.baseUrl};return q.jsx(Et.Provider,{value:s,children:e})}async function lr(e){return await new Promise((t,n)=>{const r=new FileReader;r.onload=()=>{try{const s=r.result,o=new Uint8Array(s);let a="";const i=o.byteLength;for(let d=0;d<i;d++)a+=String.fromCharCode(o[d]);t(btoa(a))}catch(s){n(s)}},r.onerror=s=>n(s),r.readAsArrayBuffer(e)})}async function cr(e=[]){const t=[],n=[];for(const r of e)try{const s=await lr(r),o=r.type||"application/octet-stream";n.push({filename:r.name,data:s,mime_type:o}),o.startsWith("image/")?t.push({type:"image_url",image_url:{url:`data:${o};base64,${s}`}}):t.push({type:"file",url:`data:${o};base64,${s}`,mimeType:o,name:r.name,size:r.size})}catch{}return{contentParts:t,filesInfo:n}}function Pt(e){return e.filter(t=>t.type==="text").map(t=>t.text).join("")}function ur(e){if(e==null)return null;const t=String(e).trim();return t.length>0?t:null}function _t(e){const t=e.toolCallId??(e.role==="tool"?e.id:void 0);return e.role==="tool"&&!t&&console.error("[meta-utils] CRITICAL: Tool message missing toolCallId!",e),{toolCallId:t??void 0,name:e.name??void 0}}function dr(e){var n;if(e.name&&e.name.trim())return e.name;const t=(n=e.additionalKwargs)==null?void 0:n.agentName;return typeof t=="string"&&t.trim()?t:e.model&&e.model.includes("/")?e.model.split("/").pop()||null:e.model||null}function fr(e){const t=e.updatedAt??e.createdAt??"",n=Array.isArray(e.content)?e.content.map(a=>{switch(a.type){case"text":return`t:${a.text.length}`;case"image_url":return"img";default:return a.type==="interrupt"?"interrupt":"unknown"}}).join("|"):"",r="checkpointId"in e&&e.checkpointId?`cp:${e.checkpointId}`:"",s="checkpointNs"in e&&e.checkpointNs?`ns:${e.checkpointNs}`:"",o=[r,s].filter(Boolean).join("|");return`${e.id}:${t}:${n}${o?`:${o}`:""}`}function be(){const e=l.useContext(Et);if(!e)throw new Error("useApi must be used within ApiProvider");return e}function pr(e,t,n){const r=typeof t=="string"?[{type:"text",text:t}]:t;return{id:`msg-${Date.now()}-${Math.random().toString(36).slice(2,9)}`,role:e,content:r,createdAt:new Date().toISOString(),...n}}function Nt(e,t="user"){return typeof e=="string"?pr(t,e):e}function gr(e){return!!e&&typeof e=="object"&&"data"in e}function zt(e={}){const t=e.baseUrl||"",n=e.streamPath??"/runs/stream",[r,s]=l.useState(e.token??null),o=l.useRef(e.headers??{}),a=e.credentials??"include",i=l.useRef(e);l.useEffect(()=>{i.current=e},[e]);const d=l.useCallback(m=>{var L,E,P,O,U,K,V,x,b,$;const w=i.current;if(!w)return;(L=w.onEvent)==null||L.call(w,m),m.type==="thread_info"&&((E=w.onThreadInfo)==null||E.call(w,m)),m.type==="values"&&Array.isArray(m.checkpoints)&&((P=w.handleValuesEvent)==null||P.call(w,m)),m.type==="metadata"&&((O=w.onMetadataEvent)==null||O.call(w,m)),typeof m.type=="string"&&(m.type==="custom"||m.type.startsWith("custom."))&&((U=w.onCustomEvent)==null||U.call(w,m)),m.type==="updates"&&((K=w.onUpdateEvent)==null||K.call(w,m)),m.type==="tool.end"?(V=w.onToolEnd)==null||V.call(w,m):m.type==="tool.start"&&((x=w.onToolStart)==null||x.call(w,m)),m.type==="heartbeat"&&((b=w.onHeartbeat)==null||b.call(w,m)),m.type==="token"&&(($=w.onToken)==null||$.call(w,m.token))},[]),[c,u]=l.useState(!1),[g,h]=l.useState(null),[y,v]=l.useState(!1),[p,k]=l.useState(null),T=l.useRef(null),_=l.useRef(!0),I=l.useRef(null),j=l.useCallback(m=>{s(m)},[]),N=l.useCallback(()=>{h(null),k(null)},[]),S=l.useCallback(()=>{var E,P;console.debug("[use-chat] stop() invoked - aborting stream");const m=(E=I.current)==null?void 0:E.threadId,w=(P=I.current)==null?void 0:P.runId,B=()=>{var O;(O=T.current)==null||O.abort(),T.current=null,I.current=null,u(!1),v(!1)};(w||m?xt.cancelRun(w||m).catch(O=>{console.warn("[use-chat] cancel run failed:",O)}):Promise.resolve()).finally(B)},[]),M=l.useCallback(m=>{T.current&&(T.current.abort(),T.current=null);const w={text:typeof m.content=="string"?m.content:m.text,threadId:m.threadId,attachments:m.attachments,payload:m.payload,config:m.config,checkpointId:m.checkpointId,checkpointNs:m.checkpointNs||void 0,edit:m.edit,command:m.command};u(!0),h(null),k(null);const B=new AbortController;T.current=B;let L=null,E=!1;return I.current={threadId:w.threadId??void 0,runId:void 0,headers:{},isStreaming:!0},(async()=>{var P,O,U,K,V,x;try{let b={};try{if(r)b={Authorization:`Bearer ${r}`};else if(typeof window<"u"){const Z=window.__AUTH_TOKEN__,we=((P=window.localStorage)==null?void 0:P.getItem(xe.authToken))||null;let X=null;try{const me=(O=window.localStorage)==null?void 0:O.getItem(xe.chatSettings);me&&(X=((U=JSON.parse(me))==null?void 0:U.apiKey)||null)}catch{}const Q=Z||we||X||null;Q&&(b={Authorization:`Bearer ${Q}`})}}catch{}console.debug("[use-chat] POST",t+n);let $={};if(typeof window<"u")try{const W=(K=window.localStorage)==null?void 0:K.getItem(xe.authSessionId);W&&($={"X-Session-Id":W})}catch{}const D={...b,...$,...o.current},f={"Content-Type":"application/json",Accept:"text/event-stream",...D},C=await fetch(t+n,{method:"POST",headers:f,body:JSON.stringify(w),signal:B.signal,credentials:a});if(I.current&&(I.current.headers=D),!C.ok||!C.body){const W=await C.text().catch(()=>"");console.debug("[use-chat] non-OK response",C.status,W==null?void 0:W.slice(0,500));const Z=`stream ${C.status}${W?": "+W:""}`;throw Z&&(h(Z),L="error"),new Error(Z)}v(!0);const z=C.body.getReader(),te=new TextDecoder;let J="",G=0,Y=Date.now();const se=setInterval(()=>{Date.now()-Y>18e5&&(h("Stream idle timeout"),L="error",B.abort())},5e3),ue=1024*1024;try{const W=C.headers.get("X-Thread-Id")||C.headers.get("x-thread-id"),Z=C.headers.get("X-Run-Id")||C.headers.get("x-run-id");for(I.current&&(I.current={...I.current,threadId:W??I.current.threadId,runId:Z??I.current.runId});;){const{value:we,done:X}=await z.read();if(X)break;J+=te.decode(we,{stream:!0}),J.length>ue&&(J="",console.warn("Stream buffer reset: exceeded 1MB"));let Q;for(;(Q=J.indexOf(`
5
5
 
6
6
  `))>=0;){const me=J.slice(0,Q);J=J.slice(Q+2);const De=me.split(/\r?\n/),Ve=[];let de=null;for(const ye of De)if(!ye.startsWith(":")&&ye){if(ye.startsWith("event:")){const Ie=ye.slice(6).trim();Ie&&(de=Ie);continue}if(ye.startsWith("data:")){const Ie=ye.slice(5);Ve.push(Ie.startsWith(" ")?Ie.slice(1):Ie)}}const Te=Ve.join(`
7
- `);if(!Te)continue;let ne;try{ne=JSON.parse(Te)}catch{console.debug("[use-chat] malformed SSE:",Te.slice(0,200));continue}de&&typeof ne=="object"&&ne!==null&&!("type"in ne)&&(ne.type=de);const Pe=gr(ne)?ne.data:ne;if(!Pe){console.warn("[use-chat] dropped envelope event without payload",ne);continue}const _e=Wn(Pe);Y=Date.now();const he=_e.seq;if(he!==void 0){if(he<=H){console.debug("[use-chat] drop duplicate/out-of-order event",{seq:he,lastProcessedSeq:H,type:_e.type});continue}H=he}d(_e)}}F===null&&!$.signal.aborted&&(F="complete")}catch(W){if(W.name==="AbortError")F=F??"aborted";else{const Z=W.message||String(W);F="error",h(Z)}}finally{try{await N.cancel()}catch{}finally{(q=N.releaseLock)==null||q.call(N)}clearInterval(se)}}catch(S){if(S.name==="AbortError")F=F??"aborted";else{const D=S.message||String(S);F="error",h(D),M||(M=!0,(w=e.onConnectionError)==null||w.call(e,D))}}finally{try{if(e.onFinish){const S={lastSeq:0,lastCheckpointId:null,lastCheckpointNs:null,lastValues:null};e.onFinish(S)}}catch(S){console.warn("[use-chat] onClosed callback failed",S)}u(!1),v(!1),T.current=null,I.current=null}})(),Promise.resolve()},[t,n,r,e,d]);return l.useEffect(()=>()=>{var m;E.current=!1,(m=T.current)==null||m.abort()},[]),{isStreaming:c,error:g,assistantText:"",activeMessageId:p,streamedMessages:{},lastCheckpointId:null,lastSeq:0,connected:y,stream:P,stop:A,clear:z,setToken:j,values:{},interrupt:()=>Promise.resolve(),resume:()=>Promise.resolve(),goto:()=>Promise.resolve(),connectionState:g?"error":c?y?"connected":"connecting":"idle",messages:[],submit:P}}const mr=["detail","message","error","description","title"];function Ue(e){if(!e)return null;if(typeof e=="string"){const t=e.trim();return t.length?t:null}if(Array.isArray(e)){for(const t of e){const n=Ue(t);if(n)return n}return null}if(typeof e=="object"){const t=e;for(const n of mr){const r=Ue(t[n]);if(r)return r}if("errors"in t){const n=Ue(t.errors);if(n)return n}}return null}function hr(e){if(!e)return"Request failed";const t=e.response,n=Ue(t==null?void 0:t.data);if(n)return n;if(t!=null&&t.statusText)return t.statusText;if(e instanceof Error&&e.message)return e.message;if(typeof e=="string"){const r=e.trim();if(r.length)return r}return t!=null&&t.status?`Request failed with status code ${t.status}`:"Request failed"}function jt({api:e,initialThreadId:t=null,onError:n,onThreadChange:r,onCurrentThreadDeleted:s}){const[o,a]=l.useState([]),[i,d]=l.useState(t),[c,u]=l.useState(!1),[g,h]=l.useState(null),[y,v]=l.useState([]),[p,k]=l.useState(!1),[,T]=l.useState(null),[E,I]=l.useState(null),[j,z]=l.useState(!1),A=l.useRef(i),P=l.useRef(new Map);l.useEffect(()=>{A.current=i},[i]),l.useEffect(()=>{t!==void 0&&t!==A.current&&d(t)},[t]);const m=l.useCallback(async()=>{u(!0),h(null);try{const w=await e.listThreads();a(w??[])}catch(w){const S=String(w);h(S),n==null||n(S)}finally{u(!1)}},[e,n]),b=l.useCallback(async()=>{k(!0),T(null);try{const w=await e.listSharedThreads();v(w??[])}catch(w){const S=String(w);T(S),n==null||n(S)}finally{k(!1)}},[e,n]);l.useEffect(()=>{m()},[m]),l.useEffect(()=>{b()},[b]),l.useEffect(()=>{r==null||r(i)},[i,r]);const $=l.useCallback(async(w,S)=>{try{const D=S&&typeof S=="object"?{id:S.id,name:S.name??""}:void 0,B=await e.createThread(w,D);return d(B.threadId),await m(),B.threadId}catch(D){const B=String(D);return n==null||n(B),null}},[e,n,m]),F=l.useCallback(async w=>{const S=o;a(B=>B.filter(f=>f.threadId!==w));const D=new AbortController;P.current.set(w,D);try{await e.deleteThread(w),A.current===w&&(d(null),s==null||s())}catch(B){a(S);const f=String(B);n==null||n(f)}finally{P.current.delete(w)}},[e,s,n,o]),M=l.useCallback(async(w,S)=>{try{await e.updateThread(w,S),await m()}catch(D){n==null||n(String(D))}},[e,n,m]),_=l.useCallback(async(w,S)=>{z(!0),I("Sharing thread…");try{await e.shareThread(w,S),await b(),I("Shared successfully")}catch(D){const B=hr(D);throw n==null||n(B),I(`Failed to share: ${B}`),new Error(B)}finally{z(!1)}},[e,n,b]),O=l.useCallback(async(w,S)=>{try{await e.unshareThread(w,S),await b()}catch(D){const B=String(D);throw n==null||n(B),D}},[e,n,b]),U=l.useMemo(()=>({createThread:$,deleteThread:F,renameThread:M,refreshThreads:m,refreshSharedThreads:b,shareThread:_,unshareThread:O}),[$,F,M,m,b,_,O]),K=l.useCallback(w=>{if(!(w!=null&&w.threadId))return;const S={threadId:w.threadId,title:w.title||`Thread ${w.threadId.slice(0,8)}`,project:w.project,createdAt:w.createdAt||new Date().toISOString(),updatedAt:w.updatedAt||new Date().toISOString(),messageCount:w.messageCount??1};a(D=>{let B=!1;const f=D.map(x=>x.threadId===S.threadId?(B=!0,console.debug("[useThreadsState] thread_info: updating existing thread",S.threadId),{...x,title:S.title??x.title,project:S.project??x.project,updatedAt:S.updatedAt??x.updatedAt,messageCount:S.messageCount??x.messageCount}):x);return B?f:(console.debug("[useThreadsState] thread_info: adding thread to list",S.threadId),[S,...D])})},[]),q=l.useCallback(()=>I(null),[]);return{threads:o,currentThreadId:i,currentThreadIdRef:A,setCurrentThreadId:d,isLoadingThreads:c,threadsError:g,sharedThreads:y,isLoadingSharedThreads:p,actions:U,addThreadFromEvent:K,shareInFlight:j,shareStatus:E,clearShareStatus:q}}const Ut=l.createContext(null);function Ft({children:e,initialThreadId:t=null,onError:n,onThreadChange:r}){const{chatApi:s}=be(),{threads:o,currentThreadId:a,setCurrentThreadId:i,currentThreadIdRef:d,isLoadingThreads:c,threadsError:u,sharedThreads:g,isLoadingSharedThreads:h,actions:y,addThreadFromEvent:v,shareInFlight:p,shareStatus:k,clearShareStatus:T}=jt({api:s,initialThreadId:t,onError:n,onThreadChange:r}),E=l.useMemo(()=>({threads:o,currentThreadId:a,setCurrentThreadId:i,currentThreadIdRef:d,isLoading:c,error:u,sharedThreads:g,isLoadingSharedThreads:h,actions:y,shareInFlight:p,shareStatus:k,clearShareStatus:T,addThreadFromEvent:v}),[o,a,i,d,c,u,g,h,y,p,k,T,v]);return G.jsx(Ut.Provider,{value:E,children:e})}function Fe(e){const t=l.useContext(Ut);if(!t&&!(e!=null&&e.optional))throw new Error("useThreads must be used within a ThreadsProvider");return t}function Lt(e){const t=e.artifact;return!t||typeof t!="object"?null:"metadata"in t&&t.metadata?t.metadata:{id:t.id??e.id??`artifact-${Date.now()}`,type:t.type??"unknown",createdAt:e.createdAt??new Date().toISOString(),status:t.status??"completed",progress:t.progress??void 0}}function yr(e,t){const n=Lt(e);if(!n)return e;const r={...n,...t,updatedAt:new Date().toISOString()};return{...e,artifact:{...typeof e.artifact=="object"&&e.artifact?e.artifact:{},metadata:r}}}function br(e,t,n){return e.find(r=>{const s=Lt(r);return!!((s==null?void 0:s.id)===t||n&&r.toolCallId===n)})??null}function Le(e){return e.map(t=>Je(t)).filter(t=>!!t)}function Ot(e,t,n){return t<0||t>=e.length?e:[...e.slice(0,t),n,...e.slice(t+1)]}function wr(e,t,n){for(let r=e.length-1;r>=0;r--)if(e[r].role==="assistant"){const o={...e[r],checkpointId:t,checkpointNs:n??void 0};return Ot(e,r,o)}return e}const $t={status:"idle",messages:[],taskMessagesByScope:{},assemblingId:null,lastCheckpointId:null,lastCheckpointNs:null,messagesStreamMeta:{},pendingInterrupt:null,values:{},error:null};function kr(e,t){var n;switch(t.type){case"status":return{...e,status:t.payload.status,error:t.payload.error??e.error};case"reset":return{...$t,messages:Le(((n=t.payload)==null?void 0:n.messages)??[])};case"user_message":{const{message:r}=t.payload;return{...e,status:"streaming",messages:[...e.messages,r],assemblingId:null,lastCheckpointId:null,error:null}}case"seed":{const r=Le(t.payload.messages),s={...e,status:"idle",messages:r,assemblingId:null,pendingInterrupt:t.payload.pendingInterrupt??null,taskMessagesByScope:{},error:null};return Object.prototype.hasOwnProperty.call(t.payload,"checkpointId")&&(s.lastCheckpointId=t.payload.checkpointId??null),Object.prototype.hasOwnProperty.call(t.payload,"checkpointNs")&&(s.lastCheckpointNs=t.payload.checkpointNs??null),Object.prototype.hasOwnProperty.call(t.payload,"values")&&(s.values=t.payload.values??{}),s}case"prepend":{const r=Le(t.payload.messages);if(!r.length)return e;const s=new Set(e.messages.map(a=>a.id)),o=r.filter(a=>!s.has(a.id));return o.length?{...e,messages:[...o,...e.messages]}:e}case"event":return Bt(e,t.payload.ev);case"batch":{const{events:r}=t.payload;return r.length?r.reduce((s,o)=>Bt(s,o),e):e}default:return e}}function vr(e=[]){const[t,n]=l.useReducer(kr,{...$t,messages:e}),r=l.useRef([]),s=l.useRef(null),o=l.useCallback(()=>{s.current!==null&&typeof window<"u"&&window.cancelAnimationFrame(s.current),s.current=null;const c=r.current;c.length&&(r.current=[],n({type:"batch",payload:{events:c}}))},[]),a=l.useCallback(()=>{typeof window<"u"&&typeof window.requestAnimationFrame=="function"?s.current===null&&(s.current=window.requestAnimationFrame(()=>o())):setTimeout(o,8)},[o]),i=l.useCallback(c=>{r.current.push(c),a()},[a]),d=l.useMemo(()=>({setStatus:(c,u)=>n({type:"status",payload:{status:c,error:u}}),reset:c=>n({type:"reset",payload:{messages:c}}),seed:(c,u)=>n({type:"seed",payload:{messages:c,...u??{}}}),pushUser:(c,u)=>n({type:"user_message",payload:{message:c,editingMessageId:u}}),onEvent:i}),[i]);return{state:t,dispatch:n,...d}}function Bt(e,t){var a;const n=t,r=n==null?void 0:n.origin,s=n==null?void 0:n.scope,o=r==="task"||typeof s=="string"&&s.startsWith("tools:");if(t.type==="checkpoint"){const i=t.checkpointNs??e.lastCheckpointNs??null,d=wr(e.messages,t.checkpointId,i);return{...e,lastCheckpointId:t.checkpointId,lastCheckpointNs:i,messages:d}}if(t.type==="status"){const i=n.status==="completed"||n.status==="error"?"idle":n.status==="interrupted"?"awaiting_input":e.status;return{...e,status:i}}if(t.type==="error"){const i={id:`err-${Date.now()}`,role:"system",content:[{type:"text",text:`Error: ${t.message}`}],createdAt:new Date().toISOString()};return{...e,status:"error",error:t.message,messages:[...e.messages,i]}}if(t.type==="values"&&((a=n.values)!=null&&a.messages)){const i=n.values,d=Array.isArray(i.messages)?i.messages:[],c=Le(d),{messages:u,...g}=i;if(o){const h=typeof s=="string"&&s.length>0?s:"task";return{...e,taskMessagesByScope:{...e.taskMessagesByScope,[h]:c}}}return{...e,status:e.status==="streaming"?"idle":e.status,messages:c,assemblingId:null,pendingInterrupt:null,values:g}}return t.type==="messages/partial"?Tr(e,n):t.type==="tool.start"?o?e:Ir(e,t):t.type==="tool.progress"?o?e:Sr(e,t):t.type==="tool.end"?o?e:Ar(e,t):t.type==="artifact.update"?Cr(e,t):e}function Tr(e,t){const r=(t.messages||[t]).find(d=>d.type==="ai"||d.role==="assistant");if(!r)return e;const s=r.id,o=r.content??"",a=e.assemblingId!==s;let i=[...e.messages];if(a){const d=Je({...r,role:"assistant",content:typeof o=="string"?[{type:"text",text:o}]:o});d&&i.push(d)}else{const d=i.findIndex(c=>c.id===s);if(d!==-1){const c=i[d],u=o;i[d]={...c,content:[{type:"text",text:u}]}}}return{...e,status:"streaming",messages:i,assemblingId:s}}function nt(e,t){var n;if(!t)return-1;for(let r=e.length-1;r>=0;r--){const s=e[r];if(s.role==="assistant"&&((n=s.toolCalls)!=null&&n.some(o=>o.id===t)))return r}return-1}function Ir(e,t){const n=t,r=n.id||n.callId;if(!r)return e;const s=n.name||"tool",o=`Starting ${s}...`;let a=[...e.messages],i=nt(a,r);if(i===-1){for(let d=a.length-1;d>=0;d--)if(a[d].role==="assistant"){i=d;break}}if(i!==-1){const d=a[i],c=[...d.toolCalls||[]],u=c.findIndex(g=>g.id===r);u>=0?c[u]={...c[u],status:"running",content:o}:c.push({id:r,name:s,args:n.args||{},status:"running",content:o}),a[i]={...d,toolCalls:c}}return{...e,messages:a}}function Sr(e,t){const n=t.id;if(!n)return e;let r=[...e.messages];const s=nt(r,n);if(s!==-1){const o=r[s],a=oe(t.content),i=(o.toolCalls||[]).map(d=>d.id===n?{...d,content:typeof a=="string"?a:d.content}:d);r[s]={...o,toolCalls:i}}return{...e,messages:r}}function Ar(e,t){const n=t.id;if(!n)return e;let r=[...e.messages];const s=nt(r,n),o=oe(t.content??t.error);if(s!==-1){const i=r[s],d=(i.toolCalls||[]).map(c=>c.id===n?{...c,status:t.error?"failed":"completed",content:typeof o=="string"?o:c.content,artifact:t.artifact}:c);r[s]={...i,toolCalls:d}}const a={id:`tool-${n}`,role:"tool",name:t.name,content:[{type:"text",text:typeof o=="string"?o:""}],artifact:t.artifact,toolCallId:n,createdAt:new Date().toISOString()};return{...e,messages:[...r,a]}}function Cr(e,t){const n=t.artifactId,r=br(e.messages,n,t.callId);if(!r)return e;const s=e.messages.indexOf(r),o=yr(r,{status:t.status,progress:t.progress,error:t.error});return t.partial_data&&o.artifact&&(o.artifact={...o.artifact,...t.partial_data}),{...e,messages:Ot(e.messages,s,o)}}function Me(e){if(!(!e||typeof e!="object"||Array.isArray(e)))return{...e}}function Oe(e,t){if(e)for(const n of t){const r=e[n];if(typeof r=="string"&&r.trim())return r.trim()}}function xr(e,t){if(!e)return null;for(const n of t){const r=e[n];if(typeof r=="number"&&Number.isFinite(r))return r}return null}function Dt(e){const t=Me(e);if(t)return Me(t.configurable)??t}async function Vt(e,t){var i,d;if(!e)return e??null;const n=ae(e),r=Array.isArray(n.checkpoints)?n.checkpoints:n.checkpoints?Object.values(n.checkpoints):[],s=new Set;for(const c of r){const u=(i=c==null?void 0:c.values)==null?void 0:i.messages;if(Array.isArray(u))for(const g of u){const h=g==null?void 0:g.content;if(Array.isArray(h))for(const y of h){if(!y||typeof y!="object"||y.type!=="image_url"&&y.type!=="file")continue;const v=y.fileId||y.file_id;typeof v=="string"&&v.trim()&&s.add(v)}}}if(s.size===0)return n;const o=await Promise.all(Array.from(s).map(async c=>{try{const u=await t.getFileInfo(c),g=ae(u);return[c,g]}catch{return[c,null]}})),a=new Map(o);for(const c of r){const u=(d=c==null?void 0:c.values)==null?void 0:d.messages;if(Array.isArray(u))for(const g of u){const h=g==null?void 0:g.content;if(Array.isArray(h))for(const y of h){if(!y||typeof y!="object"||y.type!=="image_url"&&y.type!=="file")continue;const v=y.fileId||y.file_id;if(!v)continue;const p=a.get(v),k=(p==null?void 0:p.contentUrl)||(p==null?void 0:p.content_url);k&&(y.type==="image_url"?(y.imageUrl=y.imageUrl||{},y.imageUrl.url=k):y.type==="file"&&(y.url=k,!y.name&&(p!=null&&p.filename||p!=null&&p.name)&&(y.name=(p==null?void 0:p.filename)||(p==null?void 0:p.name))))}}}return n}function rt(e){const r=[...(Array.isArray(e==null?void 0:e.checkpoints)?(e==null?void 0:e.checkpoints)??[]:e!=null&&e.checkpoints?Object.values(e.checkpoints):[]).map((o,a)=>Mr(ae(o),a)).filter(o=>!!o)].sort((o,a)=>Kt(a.createdAt)-Kt(o.createdAt)),s=r[0]??null;return{threadId:(e==null?void 0:e.threadId)??"",latest:s,checkpoints:r,interrupt:(s==null?void 0:s.interrupt)??null}}function Mr(e,t){var z,A;if(!e)return null;const n=((z=e.values)==null?void 0:z.activeAgent)??null,r=(A=e.values)==null?void 0:A.messages,o=(Array.isArray(r)?r:[]).map(P=>Er(P,n)).filter(P=>!!P),a=Me(e.metadata)??{},i=Dt(e.config),d=Me(e.parentConfig),c=Dt(d),u=Oe(i,["checkpointId"]),g=Oe(i,["checkpointNs"]),h=Oe(c,["checkpointId"]),y=Me(e.config),v=Array.isArray(e.tasks)?e.tasks.map(P=>({...P})):e.tasks??null,p=Array.isArray(e.next)?[...e.next]:e.next??null,k=typeof e.createdAt=="string"&&e.createdAt.trim()?e.createdAt:new Date(Date.now()-t).toISOString(),T={...a,step:xr(a,["step"])??0,source:Oe(a,["source"])??null},E=o.map(P=>({...P,checkpointId:P.checkpointId??u??null,checkpointNs:P.checkpointNs??g??null})),I=e.values,j=Array.isArray(e.interrupts)?e.interrupts:Array.isArray(I==null?void 0:I.interrupts)?I.interrupts:[];return{checkpointId:u??null,checkpointNs:g??null,createdAt:k,parentId:h??null,messages:E,interrupt:Pr(j,t,u??null),metadata:T,config:y??null,parentConfig:d??null,next:p,tasks:v,values:e.values??{}}}function Er(e,t){const n=Je(e);return n?(n.role==="assistant"&&!n.name&&t&&(n.name=t),n):null}function Pr(e,t,n){const r=e.length;for(let s=r-1;s>=0;s-=1){const o=e[s];if(!o||typeof o!="object")continue;const a=o,i=a.value??o;if(i==null)continue;return{id:typeof a.id=="string"&&a.id.trim()?a.id:`interrupt-${n??t}-${s}`,value:i}}return null}function Kt(e){if(!e)return 0;const t=Date.parse(e);return Number.isFinite(t)?t:0}const Ht=120;function _r(e){if(!Array.isArray(e))return"";const t=e.filter(r=>!!(r&&r.type==="text")).map(r=>(r.text??"").trim()).filter(Boolean);if(!t.length)return"";const n=t.join(" ").replace(/\s+/g," ").trim();return n?n.length>Ht?`${n.slice(0,Ht-3)}…`:n:""}function zr(e){return _r(e.content)||""}function Nr(e){const t=new Map,n=[],r=new Map,s=[];for(let c=0;c<e.length;c++){const u=e[c],g=u.checkpointId,h=g??`cp-${c}`,y=u.metadata??{},v=typeof y.step=="number"?y.step:null,p=typeof y.source=="string"?y.source:null;let k=null,T=null;const E=Array.isArray(u.messages)?u.messages:[];for(const A of E)A.role==="user"&&(T||(T=A),A.id&&(k=A.id));const I=u.next&&u.next.length>0?String(u.next[0]):null,j=u.parentConfig??null,z={id:h,step:v,source:p,createdAt:u.createdAt??null,namespace:u.checkpointNs??null,parentId:u.parentId??null,next:I,parentConfig:j,userMessageId:k};if(s.push(z),g&&t.set(g,z),g&&T){const A=zr(T);A&&r.set(g,A)}n.push({id:h,messageId:k,step:v,source:p,createdAt:u.createdAt??null,next:I,parentConfig:j})}const o=new Map;for(const c of s){if(!c.userMessageId)continue;const u=o.get(c.userMessageId)??[];u.push(c),o.set(c.userMessageId,u)}for(const c of o.values()){if(!c.length)continue;c.sort((g,h)=>{const y=g.createdAt?Date.parse(g.createdAt):0;return(h.createdAt?Date.parse(h.createdAt):0)-y});const u=c.length;for(let g=0;g<c.length;g++){const h=c[g];h.attemptCount=u,h.attemptIndex=g,h.isLatestAttempt=g===0}}return{checkpoints:e,checkpointMetaByCheckpointId:t,timeline:n,messagePreviews:r,getLatest:()=>{const c=n[0];if(c)return t.get(c.id)},getCheckpoint:c=>t.get(c),getMessageAttempts:c=>{const u=[];for(const g of t.values())g.userMessageId===c&&u.push(g);return u.length?(u.sort((g,h)=>{const y=typeof g.attemptIndex=="number"?g.attemptIndex:Number.MAX_SAFE_INTEGER,v=typeof h.attemptIndex=="number"?h.attemptIndex:Number.MAX_SAFE_INTEGER;return y-v}),u):[]}}}function jr(e,t,n){if(!e)return{attemptCount:1,attemptIndex:0,attempts:[]};const r=n.getMessageAttempts(e);if(!r.length)return{attemptCount:1,attemptIndex:0,attempts:[]};let s=0;if(t){const o=r.findIndex(a=>a.id===t);o>=0&&(s=o)}return{attemptCount:r.length,attemptIndex:s,attempts:r}}function Ur(e){return l.useMemo(()=>Nr(e),[e])}function st({api:e,fileApi:t,seed:n,onError:r,currentThreadId:s,autoLoadInitial:o=!0,isStreaming:a,getMessages:i}){const[d,c]=l.useState(null),g=l.useMemo(()=>rt(d),[d]).checkpoints,h=Ur(g),y=h.timeline,[v,p]=l.useState(!1),[k,T]=l.useState(!1),[E,I]=l.useState(null),j=l.useRef(s),z=l.useRef(null),A=l.useRef(null);l.useEffect(()=>{j.current=s},[s]);const P=l.useCallback(async _=>{const O=await e.getState({threadId:_.threadId,checkpointId:_.checkpointId,checkpointNs:_.checkpointNs}),U={version:"values@1",threadId:_.threadId,checkpoints:[O]},K=t?await Vt(U,t):U,{latest:q}=rt(K);return q},[e,t]),m=l.useCallback(async(_,O)=>{var q;if(!_)return;const U=`${_}:${O??"latest"}`;if(z.current===U&&!v)return;(q=A.current)==null||q.abort();const K=new AbortController;A.current=K,p(!0),I(null);try{const w=await P({threadId:_,checkpointId:O??void 0});if(j.current!==_)return;n((w==null?void 0:w.messages)??[],{checkpointId:(w==null?void 0:w.checkpointId)??null,checkpointNs:(w==null?void 0:w.checkpointNs)??null,pendingInterrupt:(w==null?void 0:w.interrupt)??null,values:w==null?void 0:w.values}),z.current=U;const S=await e.getStateHistory({threadId:_,limit:100,includeMessages:!1});j.current===_&&c(S)}catch(w){if(!lt.isCancel(w)){const S=String(w);I(S),r==null||r(S)}}finally{p(!1)}},[e,n,P,r,v]),b=l.useCallback(async(_,O)=>{if(s){T(!0);try{const U=await P({threadId:s,checkpointId:_,checkpointNs:O??void 0});n((U==null?void 0:U.messages)??[],{checkpointId:(U==null?void 0:U.checkpointId)??_,checkpointNs:(U==null?void 0:U.checkpointNs)??O,pendingInterrupt:(U==null?void 0:U.interrupt)??null,values:U==null?void 0:U.values})}catch(U){console.error("[useThreadHistoryState] Navigation failed",U)}finally{T(!1)}}},[s,P,n]),$=l.useCallback(async()=>{s&&await m(s)},[s,m]),F=l.useCallback(async _=>{const O=(_==null?void 0:_.threadId)||s;!O||s!==O||(c(_),z.current=`${O}:latest`)},[s]);l.useEffect(()=>{if(!o||!s||v||a)return;const _=`${s}:latest`;z.current!==_&&m(s)},[o,s,v,a,m]);const M=l.useCallback(()=>{c(null),p(!1),T(!1),I(null),z.current=null},[]);return{threadCheckpoints:g,threadTimeline:y,checkpointIndex:h,isLoadingThread:v,isLoadingCheckpoint:k,threadStateError:E,loadThread:m,navigateToCheckpoint:b,setCurrentCheckpointId:(_,O)=>{n(i(),{checkpointId:_,checkpointNs:O})},returnToLatest:$,handleValuesEvent:F,markSkipNextLoad:()=>{},markStreamPendingThread:()=>{},resetHistoryState:M,clearState:M}}const Gt=l.createContext(null),qt=l.createContext(null);function ot(e){const t=l.useContext(Gt);if(!t&&!(e!=null&&e.optional))throw new Error("useThreadState must be used within a ThreadStateProvider");return t}function Wt(){const e=l.useContext(qt);if(!e)throw new Error("useThreadStateUpdater must be used within a ThreadStateProvider");return e}function Jt({children:e,initialThreadId:t=null,initialCheckpointId:n=null,initialCheckpointNs:r=null,autoLoadInitial:s=!0,isStreaming:o,onError:a}){const{chatApi:i,fileApi:d}=be(),{currentThreadId:c}=Fe(),{state:u,seed:g,onEvent:h,dispatch:y}=vr(),{threadCheckpoints:v,threadTimeline:p,checkpointIndex:k,isLoadingThread:T,isLoadingCheckpoint:E,threadStateError:I,loadThread:j,navigateToCheckpoint:z,setCurrentCheckpointId:A,returnToLatest:P,handleValuesEvent:m,markSkipNextLoad:b,markStreamPendingThread:$,resetHistoryState:F}=st({api:i,fileApi:d,seed:g,onError:a,currentThreadId:c,initialThreadId:t,initialCheckpointId:n,initialCheckpointNs:r,autoLoadInitial:s,isStreaming:o,getMessages:l.useCallback(()=>u.messages,[u.messages])});l.useEffect(()=>{c||(g([],{}),F())},[c,g,F]);const M=l.useRef(null),_=l.useCallback(f=>{M.current=f},[]),O=l.useRef(null),U=l.useCallback(f=>{O.current=f},[]),K=l.useMemo(()=>({assemblingMessageId:u.assemblingId??null}),[u.assemblingId]),q=l.useCallback((f,x)=>{const N=zt(f,"user");return y({type:"user_message",payload:{message:N,editingMessageId:x==null?void 0:x.editingMessageId}}),N},[y]),w=l.useCallback(async()=>{M.current?await M.current():(g([],{}),F())},[g,F]),S=l.useMemo(()=>Kn(u.messages),[u.messages]),D=l.useMemo(()=>({status:u.status,threadId:c,messages:u.messages,taskMessagesByScope:u.taskMessagesByScope,interrupt:u.pendingInterrupt,checkpoint:{id:u.lastCheckpointId??null,namespace:u.lastCheckpointNs??null},checkpoints:v,checkpointIndex:k,timelineCheckpoints:p,metadata:K,values:u.values??{},isLoading:T,isLoadingCheckpoint:E,error:I,loadOlder:async()=>{},seedFromSnapshot:f=>{g(f.messages,{checkpointId:f.checkpointId,checkpointNs:f.checkpointNs,pendingInterrupt:f.interrupt,values:f.values})},clearState:w,navigateToCheckpoint:z,setCurrentCheckpointId:A,returnToLatest:P,loadThread:async(f,x,N)=>{await j(f,x,{clearProgress:!1})},clearThread:w,respondToInterrupt:async(f,x,N)=>{O.current&&await O.current(f,x,N)},messagePreviews:k.messagePreviews,handleValuesEvent:m,markSkipNextLoad:b,markStreamPendingThread:$,resetHistoryState:F,pushUser:q,onEvent:h,artifacts:S}),[c,u.messages,u.taskMessagesByScope,u.pendingInterrupt,u.lastCheckpointId,u.lastCheckpointNs,u.values,v,p,k,K,T,E,I,g,w,z,A,P,j,m,b,$,q,h,S]),B=l.useMemo(()=>({registerClearThread:_,registerRespondToInterrupt:U}),[_,U]);return G.jsx(qt.Provider,{value:B,children:G.jsx(Gt.Provider,{value:D,children:e})})}const Xt=l.createContext(null),Fr=l.createContext(!1);function Lr({children:e,onError:t,onAuthError:n,onConnectionError:r,onToolEnd:s,onUpdateEvent:o,onCustomEvent:a,onMetadataEvent:i,onFinish:d,onStreamingChange:c}){const{chatApi:u,baseUrl:g}=be(),h=g,y=le(t),v=le(n),p=le(r),k=le(s),T=le(o),E=le(a),I=le(i),j=le(d),z=le(c),A=l.useMemo(()=>({onError:y,onAuthError:v,onConnectionError:p,onMetadataEvent:I,onCustomEvent:E,onUpdateEvent:T,onToolEnd:k,onFinish:j}),[y,v,p,I,E,T,k,j]);return G.jsx(Fr.Provider,{value:!0,children:G.jsx(Or,{api:u,streamBaseUrl:h,handlers:A,onStreamingChange:z,children:e})})}function Or({children:e,api:t,streamBaseUrl:n,handlers:r,onStreamingChange:s}){const{setCurrentThreadId:o,currentThreadIdRef:a,addThreadFromEvent:i,currentThreadId:d}=Fe(),{interrupt:c,checkpoint:u,timelineCheckpoints:g,handleValuesEvent:h,markSkipNextLoad:y,markStreamPendingThread:v,resetHistoryState:p,pushUser:k,onEvent:T,messages:E}=ot(),{registerClearThread:I,registerRespondToInterrupt:j}=Wt(),z=l.useCallback(f=>{i(f),v(f.threadId),a.current!==f.threadId&&((f.created??!a.current)&&y(f.threadId),o(f.threadId))},[i,y,v,o,a]),A=Nt({baseUrl:n,onEvent:T,onError:f=>{var x;(x=r.onError)==null||x.call(r,(f==null?void 0:f.message)??String(f))},onAuthError:r.onAuthError,onConnectionError:r.onConnectionError,onFinish:r.onFinish,onThreadInfo:z,onMetadataEvent:r.onMetadataEvent,onCustomEvent:r.onCustomEvent,onUpdateEvent:r.onUpdateEvent,onToolEnd:r.onToolEnd,handleValuesEvent:h});l.useEffect(()=>{s==null||s(A.isStreaming)},[A.isStreaming,s]);const{stream:P,stop:m,clear:b,isStreaming:$,error:F,connected:M,streamedMessages:_,activeMessageId:O}=A;l.useEffect(()=>{d!==void 0&&b()},[d,b]);const U=l.useCallback(async(f,x)=>{await P(f,x)},[P]),K=l.useRef(u);l.useEffect(()=>{K.current=u},[u]);const q=l.useCallback(async(f,x,N)=>{const te=a.current;if(!te)throw new Error("No active thread to handle interrupt");const J=f?x??!0:!1,H=K.current,Y=(N==null?void 0:N.checkpointId)??H.id??void 0,se=(N==null?void 0:N.checkpointNs)??H.namespace??void 0,ue={threadId:te,checkpointId:Y,checkpointNs:se,command:{kind:"resume",value:J},payload:N==null?void 0:N.payload};U(ue)},[a,U]);l.useEffect(()=>{j(q)},[q,j]);const w=l.useCallback(async()=>{m(),b(),p(),o(null)},[b,p,o,m]);l.useEffect(()=>{I(w)},[w,I]);const S=l.useCallback(async(f,x)=>{$&&m();let N=a.current;const te=(f==null?void 0:f.text)??"",J=(f==null?void 0:f.attachments)??[],H=(te==null?void 0:te.trim())??"",Y={...(f==null?void 0:f.payload)??{}},se=Array.isArray(Y.messages)?Y.messages:void 0;se&&delete Y.messages;const ue=!!(se&&se.length),W=!!(f.contentParts&&f.contentParts.length>0);if(!N&&!H&&J.length===0&&!ue&&!W)return;if(!N){const he=Math.floor(Date.now()/1e3).toString(16).padStart(8,"0"),ye=Array.from({length:4},()=>Math.floor(Math.random()*4294967295).toString(16).padStart(8,"0")).join("").slice(0,16);N=`${he}${ye}`,y(N),o(N)}let Z=null;f.contentParts&&f.contentParts.length>0&&(Z=f.contentParts);const{contentParts:we,filesInfo:X}=Z?{contentParts:Z,filesInfo:[]}:await cr(J),Q=[...we];H&&Q.push({type:"text",text:te});const me=f==null?void 0:f.originalMessageId,De=!!(f!=null&&f.edit&&me),Ve=!ue&&Q.length>0;let de=null;if(Ve){const he=De?me:`msg-${Date.now()}`;de=zt({id:he,role:"user",content:Q,createdAt:new Date().toISOString()},"user"),De?k(de,{editingMessageId:me}):k(de)}const Te=ue?se:de?[de]:[],ne={...Y,...X.length?{files_info:X}:{}};Te.length?ne.messages=Te:"messages"in ne||(ne.messages=[]);const Pe=(f==null?void 0:f.checkpointId)??u.id??void 0;if(f!=null&&f.edit&&!Pe)throw new Error(`[streaming] Missing checkpointId for edit submit. threadId=${N??"null"}`);const _e={threadId:N,content:f==null?void 0:f.text,payload:ne,config:f==null?void 0:f.config,checkpointId:Pe,command:f==null?void 0:f.command,edit:f==null?void 0:f.edit};return U(_e,x)},[u,a,$,y,k,U,m,g]),D=l.useMemo(()=>{const f=Object.keys(_).length>0;if(!$&&!f)return E;const x=new Map;return E.forEach(N=>x.set(N.id,N)),Object.values(_).forEach(N=>{x.set(N.id,N)}),Array.from(x.values())},[$,_,E]),B=l.useMemo(()=>({isStreaming:$,error:F,connectionState:F?"error":$?M?"connected":"connecting":"idle",messages:D,activeMessageId:O,submit:S,stop:m,interrupt:c,resume:()=>Promise.resolve(),goto:(f,x)=>Promise.resolve(),clearError:()=>{}}),[$,F,S,m,c,M,D]);return G.jsx(Xt.Provider,{value:B,children:e})}function le(e){const t=l.useRef(e);return l.useEffect(()=>{t.current=e},[e]),l.useCallback((...n)=>{const r=t.current;if(r)return r(...n)},[])}function $r(e){return l.useContext(Xt)}function Qt(e){return typeof e=="object"&&e!==null}function Br(e,t){if(Object.is(e,t))return!0;if(!Qt(e)||!Qt(t))return!1;const n=Object.keys(e),r=Object.keys(t);if(n.length!==r.length)return!1;for(const s of n)if(!Object.prototype.hasOwnProperty.call(t,s)||!Object.is(e[s],t[s]))return!1;return!0}function Dr(e){const t=l.useRef(e),n=l.useRef(e);return Br(t.current,e)||(t.current=e,n.current=e),n.current}function Yt(e){const t=e.artifact&&typeof e.artifact=="object"?e.artifact:null,n=!t&&e.content&&typeof e.content=="object"?e.content:null,r=t??n,s=(r==null?void 0:r.task_id)??(r==null?void 0:r.taskId)??null;return typeof s=="string"?s:null}function Vr(e){const{setCurrentTaskId:t,getCurrentTaskId:n,onToolEnd:r}=e;return s=>{const o=Yt(s),a=(n==null?void 0:n())??null;o&&o!==a&&t(o),r==null||r(s)}}function Kr({children:e,apiConfig:t,initialThreadId:n=null,initialCheckpointId:r=null,initialCheckpointNs:s=null,autoLoadInitial:o=!0,onConnectionError:a,onError:i,onAuthError:d,onThreadChange:c,onToolEnd:u,onUpdateEvent:g,onCustomEvent:h,onMetadataEvent:y,onFinish:v}){const p=Dr(t),[k,T]=l.useState(!1),E=ce(i),I=ce(d),j=ce(a),z=ce(c),A=ce(u),P=ce(g),m=ce(h),b=ce(y),$=ce(v),F=l.useMemo(()=>({onError:E,onAuthError:I,onConnectionError:j,onToolEnd:A,onUpdateEvent:P,onCustomEvent:m,onMetadataEvent:b,onFinish:$}),[E,I,j,A,P,m,b,$]);return G.jsx(ir,{apiConfig:p,children:G.jsx(Ft,{initialThreadId:n,onError:E,onThreadChange:z,children:G.jsx(Jt,{initialThreadId:n,initialCheckpointId:r,initialCheckpointNs:s,autoLoadInitial:o,onError:E,isStreaming:k,children:G.jsx(Lr,{...F,onStreamingChange:T,children:e})})})})}function ce(e){const t=l.useRef(e);return t.current=e,l.useCallback((...n)=>{const r=t.current;if(r)return r(...n)},[])}const Hr=1,Gr=1e6;let at=0;function qr(){return at=(at+1)%Number.MAX_SAFE_INTEGER,at.toString()}const it=new Map,Zt=e=>{if(it.has(e))return;const t=setTimeout(()=>{it.delete(e),Ee({type:"REMOVE_TOAST",toastId:e})},Gr);it.set(e,t)},Wr=(e,t)=>{switch(t.type){case"ADD_TOAST":return{...e,toasts:[t.toast,...e.toasts].slice(0,Hr)};case"UPDATE_TOAST":return{...e,toasts:e.toasts.map(n=>n.id===t.toast.id?{...n,...t.toast}:n)};case"DISMISS_TOAST":{const{toastId:n}=t;return n?Zt(n):e.toasts.forEach(r=>{Zt(r.id)}),{...e,toasts:e.toasts.map(r=>r.id===n||n===void 0?{...r,open:!1}:r)}}case"REMOVE_TOAST":return t.toastId===void 0?{...e,toasts:[]}:{...e,toasts:e.toasts.filter(n=>n.id!==t.toastId)}}},$e=[];let Be={toasts:[]};function Ee(e){Be=Wr(Be,e),$e.forEach(t=>{t(Be)})}function Jr({...e}){const t=qr(),n=s=>Ee({type:"UPDATE_TOAST",toast:{...s,id:t}}),r=()=>Ee({type:"DISMISS_TOAST",toastId:t});return Ee({type:"ADD_TOAST",toast:{...e,id:t,open:!0,onOpenChange:s=>{s||r()}}}),{id:t,dismiss:r,update:n}}function Xr(){const[e,t]=ct.useState(Be);return ct.useEffect(()=>($e.push(t),()=>{const n=$e.indexOf(t);n>-1&&$e.splice(n,1)}),[e]),{...e,toast:Jr,dismiss:n=>Ee({type:"DISMISS_TOAST",toastId:n})}}function Qr(e){const{allowFileOpen:t,currentThreadId:n}=e,{fileApi:r}=be(),{toast:s}=Xr(),[o,a]=l.useState({}),[i,d]=l.useState(null),[c,u]=l.useState(!1),g=l.useCallback(()=>{u(!1),d(null)},[]),h=l.useCallback(v=>{d(v),u(!0)},[]),y=l.useCallback(async(v,p,k)=>{var T,E;if(!t){v.preventDefault();return}if(o[k]){v.preventDefault();return}try{const I=String(p.url??""),j=I.match(/\/chat\/files\/([^/]+)(?:\/(view|download))?/);if(j){v.preventDefault();const z=j[1],A=p.name||`file_${z}`,P=p.mimeType||"application/octet-stream";h({id:z,name:A,mimeType:P});return}if(I.startsWith("data:")){v.preventDefault(),a(A=>({...A,[k]:!0}));const z=s({title:"Fetching file...",description:"",open:!0});try{const A=await r.listFiles(n??void 0);if(!A||!Array.isArray(A))throw new Error("Invalid file list response");const P=A.find(m=>!m||typeof m!="object"||!((m.filename??"")===(p.name??""))?!1:typeof p.size=="number"&&typeof m.size=="number"?m.size===p.size:!0);if(!(P!=null&&P.id))throw new Error(`File "${p.name}" is not yet available on the server`);if(!P.id||!P.filename)throw new Error("Invalid file data received from server");h({id:P.id,name:p.name||P.filename||`file_${P.id}`,mimeType:p.mimeType||P.mime_type||"application/octet-stream"}),(T=z.update)==null||T.call(z,{id:z.id,title:"Success",description:`Opened ${p.name}`,open:!0})}catch(A){console.error("Failed to fetch server file:",A);const P=A instanceof Error?A.message:"Unknown error occurred";(E=z.update)==null||E.call(z,{id:z.id,title:"Failed",description:P}),s({title:"Failed to fetch file",description:P,open:!0})}finally{a(A=>({...A,[k]:!1}))}}}catch(I){console.error("File click error:",I),a(j=>({...j,[k]:!1}))}},[t,o,s,n,h]);return{uploadingFiles:o,handleFileClick:y,fileViewerOpen:c,currentFileInfo:i,closeFileViewer:g}}function Yr(e){return l.useMemo(()=>{const t=e;let n=Array.isArray(t.content)?t.content:[];return typeof t.content=="string"&&(n=[{type:"text",text:t.content}]),{contentParts:n,textContent:Pt(n),toolMeta:_t(t),imageParts:n.filter(r=>r.type==="image_url"),fileParts:n.filter(r=>r.type==="file"),toolRaw:kt(n),isToolStreaming:!!t.toolStreaming}},[e])}const Rt="data:";function Zr(e){if(!e)return[];const t=[],n=e.split(/\r?\n/);for(const r of n){const s=r.trim();if(!s||!s.startsWith(Rt))continue;const o=s.slice(Rt.length).trim();if(!o||o.toLowerCase()==="[done]")continue;const a=ze(o);a&&typeof a=="object"&&t.push(a)}return t}function Rr(e){for(let t=e.length-1;t>=0;t-=1){const n=e[t];if(n&&typeof n=="object"&&n.type==="tool.end")return n}return null}function es(e){return l.useMemo(()=>{const t=e.content.filter(d=>d.type==="text");if(!t.length)return null;let r=t.flatMap(d=>Zr(d.text??""));if(!r.length){const d=t.map(u=>u.text??"").join(`
8
- `),c=ze(d);c&&typeof c=="object"&&(r=[c])}if(!r.length)return null;const o=Rr(r)??r[r.length-1];if(!o)return null;const a=o.output??o.payload??o,i=oe(a);return i&&typeof i=="object"&&!Array.isArray(i)?{kind:"dict",value:i,data:i,event:o}:{kind:"generic",value:i,event:o}},[e])}function en(e){var $;const t=typeof e=="string"?e:e==null?void 0:e.threadId,n=typeof e=="object"?e.lazy:!1,r=Fe({optional:!0}),s=ot({optional:!0}),o=$r(),{currentThreadId:a,setCurrentThreadId:i,actions:d}=r||{currentThreadId:null,setCurrentThreadId:()=>{},actions:{}},c=!!t&&t!==a,[u,g]=l.useState([]),h=l.useCallback(F=>{g(F)},[]),{isLoadingThread:y,threadStateError:v,threadCheckpoints:p,loadThread:k}=st({api:be().chatApi,fileApi:be().fileApi,seed:h,currentThreadId:c?t:null,initialThreadId:c?t:null,isStreaming:!1,getMessages:()=>u,autoLoadInitial:c&&!n}),T=l.useMemo(()=>{var F;return((F=p[0])==null?void 0:F.values)||{}},[p]),E=l.useMemo(()=>({timeline:[],messagePreviews:{}}),[]),I=t||a,j=c?y?"loading":"idle":(s==null?void 0:s.status)||"idle",z=c?u:(o==null?void 0:o.messages)||[],A=c?y:(s==null?void 0:s.isLoading)||!1,P=c?T:(s==null?void 0:s.values)||{},m=c?{}:(s==null?void 0:s.taskMessagesByScope)||{},b=c?v:(o==null?void 0:o.error)||(s==null?void 0:s.error)||null;return{threadId:I,status:j,messages:z,isLoading:A,isHistoryLoading:A,error:b,values:P,taskMessagesByScope:m,metadata:c?{}:s==null?void 0:s.metadata,navigateToCheckpoint:c?async()=>{}:(s==null?void 0:s.navigateToCheckpoint)||(async()=>{}),returnToLatest:c?async()=>{}:(s==null?void 0:s.returnToLatest)||(async()=>{}),checkpoint:c?p[0]?{id:p[0].checkpointId,namespace:p[0].checkpointNs}:null:(s==null?void 0:s.checkpoint)||null,checkpoints:c?p:(s==null?void 0:s.checkpoints)||[],checkpointIndex:c?E:(s==null?void 0:s.checkpointIndex)||{timeline:[],messagePreviews:{}},interrupt:c?null:(s==null?void 0:s.interrupt)||null,respondToInterrupt:c?async()=>{}:(s==null?void 0:s.respondToInterrupt)||(async()=>{}),isStreaming:(o==null?void 0:o.isStreaming)||!1,activeMessageId:(o==null?void 0:o.activeMessageId)||null,connectionState:(o==null?void 0:o.connectionState)||"disconnected",streamingAssistantId:!c&&(o!=null&&o.isStreaming)&&(($=s==null?void 0:s.metadata)!=null&&$.assemblingMessageId)?s.metadata.assemblingMessageId:null,submit:(o==null?void 0:o.submit)||(async()=>{}),stop:(o==null?void 0:o.stop)||(()=>{}),clearThread:c?async()=>{}:(s==null?void 0:s.clearThread)||(async()=>{}),setCurrentThreadId:i,loadHistory:c?async()=>{t&&await k(t)}:async()=>{},createThread:d==null?void 0:d.createThread,deleteThread:d==null?void 0:d.deleteThread,renameThread:d==null?void 0:d.renameThread,shareThread:d==null?void 0:d.shareThread,threads:(r==null?void 0:r.threads)||[],isThreadsLoading:(r==null?void 0:r.isLoading)||!1}}function ts({submit:e,chatRequest:t,lastCheckpointId:n,lastCheckpointNs:r,onMessageSent:s,onExcelUploadSuccess:o,onError:a,enableMessageEditing:i,messages:d,setPendingAssistantResponse:c,project:u,onEvent:g,threadId:h,clearComposerOnSend:y=!0}){const{messages:v}=en(),[p,k]=l.useState(null),[T,E]=l.useState(""),[I,j]=l.useState(null),[z,A]=l.useState(null),[P,m]=l.useState(!1),[b,$]=l.useState(""),F=l.useRef(b),M=l.useRef(null);l.useEffect(()=>{if(!p)if(h){const f=localStorage.getItem(Ye(h));$(f||"")}else $("")},[h,p]);const _=l.useCallback(f=>{$(f),!p&&h&&localStorage.setItem(Ye(h),f)},[h,p]);l.useEffect(()=>{F.current=b},[b]),l.useEffect(()=>{if(!p){M.current=null;return}M.current===null&&(M.current=F.current),_(T??"")},[T,p,_]);const O=l.useCallback(f=>{_(f)},[_]),U=async(f,x)=>{const N=Array.isArray(x)?{files:x}:x??{},te=N.files??[],J=N.contentParts??[],H=f.trim();if(!(!H&&te.length===0&&J.length===0))try{const Y=te.map(async X=>{try{const Q=await Mt.uploadFile(X);return{file:X,record:Q}}catch(Q){throw console.error("Failed to upload file",X.name,Q),new Error(`Failed to upload ${X.name}`)}}),ue=(await Promise.all(Y)).map(({record:X})=>{const Q=X.mime_type;return Q.startsWith("image/")?{type:"image_url",image_url:{url:X.content_url}}:{type:"file",url:X.content_url,mimeType:Q,name:X.filename,size:X.size}}),W=[...J,...ue],Z=p?(I==null?void 0:I.checkpointId)??n??void 0:n??void 0,we=p?(I==null?void 0:I.checkpointNs)??r??void 0:r??void 0;await e({text:H||"",contentParts:W,attachments:te,payload:t.payload,edit:!!p,checkpointId:Z,checkpointNs:we,project:u??void 0,originalMessageId:p??void 0,config:t.config},g?{onEvent:g}:void 0),s==null||s(H),c(!0),y&&(h&&localStorage.removeItem(Ye(h)),_("")),A(null),k(null),E(""),j(null)}catch(Y){const se=(Y==null?void 0:Y.message)||"Failed to send message";A(se),a==null||a(se),c(!1)}},K=(f,x)=>{x||U(f,{files:[]})},q=l.useCallback(async f=>{await e({attachments:[f],payload:t.payload,checkpointId:n??void 0,checkpointNs:r??void 0,project:u??void 0,config:t.config},g?{onEvent:g}:void 0),o==null||o({file:f})},[n,r,t,o,e]),w=l.useCallback((f,x,N)=>{i&&(M.current=b,k(f),E(x),j({checkpointId:(N==null?void 0:N.checkpointId)??null,checkpointNs:(N==null?void 0:N.checkpointNs)??null}),A(null))},[b,i]),S=l.useCallback(()=>{k(null),E(""),j(null),A(null);const f=M.current;f!==null&&$(f),M.current=null},[]),D=l.useCallback(f=>{let x=null;for(let H=f-1;H>=0;H--)if(d[H].role==="user"){x=d[H];break}if(!x)return;const N=Array.isArray(x.content)?x.content:[],J=N.filter(H=>(H==null?void 0:H.type)==="text").map(H=>H.text).join("")||(()=>{try{return JSON.stringify(N,null,2)}catch{return String(N)}})();J&&e({text:J,payload:t.payload,checkpointId:n??void 0,checkpointNs:r??void 0,edit:!0,originalMessageId:x.id,config:t.config},g?{onEvent:g}:void 0)},[d,e,n,r,t]);return{editingMessageId:p,editingInitialValue:T,inputError:z,setInputError:A,dismissError:P,setDismissError:m,composerValue:b,handleComposerChange:O,handleSendMessage:U,handleQuickPrompt:K,handleExcelUpload:q,startEditing:w,cancelEditing:S,handleRegenerateCb:D,displayMessages:v}}function ns(e){return l.useMemo(()=>e?{textContent:Bn(e),imageParts:Dn(e),fileParts:Vn(e),toolCalls:wt(e),contentParts:e.content}:{textContent:"",imageParts:[],fileParts:[],toolCalls:[],contentParts:[]},[e])}function rs(e,t,n){const[r,s]=l.useState(e),o=l.useRef(e),a=l.useRef(null);return l.useEffect(()=>{o.current=e;const i=()=>{s(o.current),a.current&&(clearTimeout(a.current),a.current=null)};if(!t||n<=0){i();return}return a.current&&clearTimeout(a.current),a.current=setTimeout(()=>{i()},n),()=>{a.current&&(clearTimeout(a.current),a.current=null)}},[e,t,n]),r}C.ChatProviders=Kr,C.ThreadStateProvider=Jt,C.ThreadsProvider=Ft,C.cn=Fn,C.collectText=Pt,C.createTaskSyncToolEndHandler=Vr,C.extractTaskIdFromToolEnd=Yt,C.extractToolMeta=_t,C.formatToolOutput=Hn,C.getAgentNameFromMessage=dr,C.getChatToken=Re,C.getMessageAttemptInfo=jr,C.getToolCallArtifacts=Yn,C.getToolCalls=It,C.hasContent=Gn,C.hydrateHistorySnapshots=rt,C.isFileLike=qe,C.looksLikeMarkdown=bt,C.messageSignature=fr,C.normalizeInterruptId=ur,C.onChatTokenChanged=et,C.parseJsonSafe=ze,C.pretty=We,C.refreshHistoryFileUrls=Vt,C.sanitizeForDisplay=Ce,C.setChatToken=ge,C.stringifyTool=kt,C.useApi=be,C.useChatController=ts,C.useChatSession=en,C.useFilePreview=Qr,C.useMessageContent=ns,C.useParsedMessageContent=Yr,C.useStream=Nt,C.useStreamingMarkdownBuffer=rs,C.useThreadHistoryState=st,C.useThreadState=ot,C.useThreadStateUpdater=Wt,C.useThreads=Fe,C.useThreadsState=jt,C.useToolPayload=es,Object.defineProperty(C,Symbol.toStringTag,{value:"Module"})});
7
+ `);if(!Te)continue;let ne;try{ne=JSON.parse(Te)}catch{console.debug("[use-chat] malformed SSE:",Te.slice(0,200));continue}de&&typeof ne=="object"&&ne!==null&&!("type"in ne)&&(ne.type=de);const Pe=gr(ne)?ne.data:ne;if(!Pe){console.warn("[use-chat] dropped envelope event without payload",ne);continue}const _e=Wn(Pe);Y=Date.now();const he=_e.seq;if(he!==void 0){if(he<=G){console.debug("[use-chat] drop duplicate/out-of-order event",{seq:he,lastProcessedSeq:G,type:_e.type});continue}G=he}d(_e)}}L===null&&!B.signal.aborted&&(L="complete")}catch(W){if(W.name==="AbortError")L=L??"aborted";else{const Z=W.message||String(W);L="error",h(Z)}}finally{try{await z.cancel()}catch{}finally{(V=z.releaseLock)==null||V.call(z)}clearInterval(se)}}catch(b){if(b.name==="AbortError")L=L??"aborted";else{const $=b.message||String(b);L="error",h($),E||(E=!0,(x=e.onConnectionError)==null||x.call(e,$))}}finally{try{if(e.onFinish){const b={lastSeq:0,lastCheckpointId:null,lastCheckpointNs:null,lastValues:null};e.onFinish(b)}}catch(b){console.warn("[use-chat] onClosed callback failed",b)}u(!1),v(!1),T.current=null,I.current=null}})(),Promise.resolve()},[t,n,r,e,d]);return l.useEffect(()=>()=>{var m;_.current=!1,(m=T.current)==null||m.abort()},[]),{isStreaming:c,error:g,assistantText:"",activeMessageId:p,streamedMessages:{},lastCheckpointId:null,lastSeq:0,connected:y,stream:M,stop:S,clear:N,setToken:j,values:{},interrupt:()=>Promise.resolve(),resume:()=>Promise.resolve(),goto:()=>Promise.resolve(),connectionState:g?"error":c?y?"connected":"connecting":"idle",messages:[],submit:M}}const mr=["detail","message","error","description","title"];function Ue(e){if(!e)return null;if(typeof e=="string"){const t=e.trim();return t.length?t:null}if(Array.isArray(e)){for(const t of e){const n=Ue(t);if(n)return n}return null}if(typeof e=="object"){const t=e;for(const n of mr){const r=Ue(t[n]);if(r)return r}if("errors"in t){const n=Ue(t.errors);if(n)return n}}return null}function hr(e){if(!e)return"Request failed";const t=e.response,n=Ue(t==null?void 0:t.data);if(n)return n;if(t!=null&&t.statusText)return t.statusText;if(e instanceof Error&&e.message)return e.message;if(typeof e=="string"){const r=e.trim();if(r.length)return r}return t!=null&&t.status?`Request failed with status code ${t.status}`:"Request failed"}function jt({api:e,initialThreadId:t=null,onError:n,onThreadChange:r,onCurrentThreadDeleted:s}){const[o,a]=l.useState([]),[i,d]=l.useState(t),[c,u]=l.useState(!1),[g,h]=l.useState(null),[y,v]=l.useState([]),[p,k]=l.useState(!1),[,T]=l.useState(null),[_,I]=l.useState(null),[j,N]=l.useState(!1),S=l.useRef(i),M=l.useRef(new Map);l.useEffect(()=>{S.current=i},[i]),l.useEffect(()=>{t!==void 0&&t!==S.current&&d(t)},[t]);const m=l.useCallback(async()=>{u(!0),h(null);try{const x=await e.listThreads();a(x??[])}catch(x){const b=String(x);h(b),n==null||n(b)}finally{u(!1)}},[e,n]),w=l.useCallback(async()=>{k(!0),T(null);try{const x=await e.listSharedThreads();v(x??[])}catch(x){const b=String(x);T(b),n==null||n(b)}finally{k(!1)}},[e,n]);l.useEffect(()=>{m()},[m]),l.useEffect(()=>{w()},[w]),l.useEffect(()=>{r==null||r(i)},[i,r]);const B=l.useCallback(async(x,b)=>{try{const $=b&&typeof b=="object"?{id:b.id,name:b.name??""}:void 0,D=await e.createThread(x,$);return d(D.threadId),await m(),D.threadId}catch($){const D=String($);return n==null||n(D),null}},[e,n,m]),L=l.useCallback(async x=>{const b=o;a(D=>D.filter(f=>f.threadId!==x));const $=new AbortController;M.current.set(x,$);try{await e.deleteThread(x),S.current===x&&(d(null),s==null||s())}catch(D){a(b);const f=String(D);n==null||n(f)}finally{M.current.delete(x)}},[e,s,n,o]),E=l.useCallback(async(x,b)=>{try{await e.updateThread(x,b),await m()}catch($){n==null||n(String($))}},[e,n,m]),P=l.useCallback(async(x,b)=>{N(!0),I("Sharing thread…");try{await e.shareThread(x,b),await w(),I("Shared successfully")}catch($){const D=hr($);throw n==null||n(D),I(`Failed to share: ${D}`),new Error(D)}finally{N(!1)}},[e,n,w]),O=l.useCallback(async(x,b)=>{try{await e.unshareThread(x,b),await w()}catch($){const D=String($);throw n==null||n(D),$}},[e,n,w]),U=l.useMemo(()=>({createThread:B,deleteThread:L,renameThread:E,refreshThreads:m,refreshSharedThreads:w,shareThread:P,unshareThread:O}),[B,L,E,m,w,P,O]),K=l.useCallback(x=>{if(!(x!=null&&x.threadId))return;const b={threadId:x.threadId,title:x.title||`Thread ${x.threadId.slice(0,8)}`,project:x.project,createdAt:x.createdAt||new Date().toISOString(),updatedAt:x.updatedAt||new Date().toISOString(),messageCount:x.messageCount??1};a($=>{let D=!1;const f=$.map(C=>C.threadId===b.threadId?(D=!0,console.debug("[useThreadsState] thread_info: updating existing thread",b.threadId),{...C,title:b.title??C.title,project:b.project??C.project,updatedAt:b.updatedAt??C.updatedAt,messageCount:b.messageCount??C.messageCount}):C);return D?f:(console.debug("[useThreadsState] thread_info: adding thread to list",b.threadId),[b,...$])})},[]),V=l.useCallback(()=>I(null),[]);return{threads:o,currentThreadId:i,currentThreadIdRef:S,setCurrentThreadId:d,isLoadingThreads:c,threadsError:g,sharedThreads:y,isLoadingSharedThreads:p,actions:U,addThreadFromEvent:K,shareInFlight:j,shareStatus:_,clearShareStatus:V}}const Ut=l.createContext(null);function Ft({children:e,initialThreadId:t=null,onError:n,onThreadChange:r}){const{chatApi:s}=be(),{threads:o,currentThreadId:a,setCurrentThreadId:i,currentThreadIdRef:d,isLoadingThreads:c,threadsError:u,sharedThreads:g,isLoadingSharedThreads:h,actions:y,addThreadFromEvent:v,shareInFlight:p,shareStatus:k,clearShareStatus:T}=jt({api:s,initialThreadId:t,onError:n,onThreadChange:r}),_=l.useMemo(()=>({threads:o,currentThreadId:a,setCurrentThreadId:i,currentThreadIdRef:d,isLoading:c,error:u,sharedThreads:g,isLoadingSharedThreads:h,actions:y,shareInFlight:p,shareStatus:k,clearShareStatus:T,addThreadFromEvent:v}),[o,a,i,d,c,u,g,h,y,p,k,T,v]);return q.jsx(Ut.Provider,{value:_,children:e})}function Fe(e){const t=l.useContext(Ut);if(!t&&!(e!=null&&e.optional))throw new Error("useThreads must be used within a ThreadsProvider");return t}function Lt(e){const t=e.artifact;return!t||typeof t!="object"?null:"metadata"in t&&t.metadata?t.metadata:{id:t.id??e.id??`artifact-${Date.now()}`,type:t.type??"unknown",createdAt:e.createdAt??new Date().toISOString(),status:t.status??"completed",progress:t.progress??void 0}}function yr(e,t){const n=Lt(e);if(!n)return e;const r={...n,...t,updatedAt:new Date().toISOString()};return{...e,artifact:{...typeof e.artifact=="object"&&e.artifact?e.artifact:{},metadata:r}}}function br(e,t,n){return e.find(r=>{const s=Lt(r);return!!((s==null?void 0:s.id)===t||n&&r.toolCallId===n)})??null}function Le(e){return e.map(t=>Je(t)).filter(t=>!!t)}function Ot(e,t,n){return t<0||t>=e.length?e:[...e.slice(0,t),n,...e.slice(t+1)]}function wr(e,t,n){for(let r=e.length-1;r>=0;r--)if(e[r].role==="assistant"){const o={...e[r],checkpointId:t,checkpointNs:n??void 0};return Ot(e,r,o)}return e}const $t={status:"idle",messages:[],taskMessagesByScope:{},assemblingId:null,lastCheckpointId:null,lastCheckpointNs:null,messagesStreamMeta:{},pendingInterrupt:null,values:{},error:null};function kr(e,t){var n;switch(t.type){case"status":return{...e,status:t.payload.status,error:t.payload.error??e.error};case"reset":return{...$t,messages:Le(((n=t.payload)==null?void 0:n.messages)??[])};case"user_message":{const{message:r}=t.payload;return{...e,status:"streaming",messages:[...e.messages,r],assemblingId:null,lastCheckpointId:null,error:null}}case"seed":{const r=Le(t.payload.messages),s={...e,status:"idle",messages:r,assemblingId:null,pendingInterrupt:t.payload.pendingInterrupt??null,taskMessagesByScope:{},error:null};return Object.prototype.hasOwnProperty.call(t.payload,"checkpointId")&&(s.lastCheckpointId=t.payload.checkpointId??null),Object.prototype.hasOwnProperty.call(t.payload,"checkpointNs")&&(s.lastCheckpointNs=t.payload.checkpointNs??null),Object.prototype.hasOwnProperty.call(t.payload,"values")&&(s.values=t.payload.values??{}),s}case"prepend":{const r=Le(t.payload.messages);if(!r.length)return e;const s=new Set(e.messages.map(a=>a.id)),o=r.filter(a=>!s.has(a.id));return o.length?{...e,messages:[...o,...e.messages]}:e}case"event":return Bt(e,t.payload.ev);case"batch":{const{events:r}=t.payload;return r.length?r.reduce((s,o)=>Bt(s,o),e):e}default:return e}}function vr(e=[]){const[t,n]=l.useReducer(kr,{...$t,messages:e}),r=l.useRef([]),s=l.useRef(null),o=l.useCallback(()=>{s.current!==null&&typeof window<"u"&&window.cancelAnimationFrame(s.current),s.current=null;const c=r.current;c.length&&(r.current=[],n({type:"batch",payload:{events:c}}))},[]),a=l.useCallback(()=>{typeof window<"u"&&typeof window.requestAnimationFrame=="function"?s.current===null&&(s.current=window.requestAnimationFrame(()=>o())):setTimeout(o,8)},[o]),i=l.useCallback(c=>{r.current.push(c),a()},[a]),d=l.useMemo(()=>({setStatus:(c,u)=>n({type:"status",payload:{status:c,error:u}}),reset:c=>n({type:"reset",payload:{messages:c}}),seed:(c,u)=>n({type:"seed",payload:{messages:c,...u??{}}}),pushUser:(c,u)=>n({type:"user_message",payload:{message:c,editingMessageId:u}}),onEvent:i}),[i]);return{state:t,dispatch:n,...d}}function Bt(e,t){var a;const n=t,r=n==null?void 0:n.origin,s=n==null?void 0:n.scope,o=r==="task"||typeof s=="string"&&s.startsWith("tools:");if(t.type==="checkpoint"){const i=t.checkpointNs??e.lastCheckpointNs??null,d=wr(e.messages,t.checkpointId,i);return{...e,lastCheckpointId:t.checkpointId,lastCheckpointNs:i,messages:d}}if(t.type==="status"){const i=n.status==="completed"||n.status==="error"?"idle":n.status==="interrupted"?"awaiting_input":e.status;return{...e,status:i}}if(t.type==="error"){const i={id:`err-${Date.now()}`,role:"system",content:[{type:"text",text:`Error: ${t.message}`}],createdAt:new Date().toISOString()};return{...e,status:"error",error:t.message,messages:[...e.messages,i]}}if(t.type==="values"&&((a=n.values)!=null&&a.messages)){const i=n.values,d=Array.isArray(i.messages)?i.messages:[],c=Le(d),{messages:u,...g}=i;if(o){const h=typeof s=="string"&&s.length>0?s:"task";return{...e,taskMessagesByScope:{...e.taskMessagesByScope,[h]:c}}}return{...e,status:e.status==="streaming"?"idle":e.status,messages:c,assemblingId:null,pendingInterrupt:null,values:g}}return t.type==="messages/partial"?Tr(e,n):t.type==="tool.start"?o?e:Ir(e,t):t.type==="tool.progress"?o?e:Sr(e,t):t.type==="tool.end"?o?e:Ar(e,t):t.type==="artifact.update"?Cr(e,t):e}function Tr(e,t){const r=(t.messages||[t]).find(d=>d.type==="ai"||d.role==="assistant");if(!r)return e;const s=r.id,o=r.content??"",a=e.assemblingId!==s;let i=[...e.messages];if(a){const d=Je({...r,role:"assistant",content:typeof o=="string"?[{type:"text",text:o}]:o});d&&i.push(d)}else{const d=i.findIndex(c=>c.id===s);if(d!==-1){const c=i[d],u=o;i[d]={...c,content:[{type:"text",text:u}]}}}return{...e,status:"streaming",messages:i,assemblingId:s}}function nt(e,t){var n;if(!t)return-1;for(let r=e.length-1;r>=0;r--){const s=e[r];if(s.role==="assistant"&&((n=s.toolCalls)!=null&&n.some(o=>o.id===t)))return r}return-1}function Ir(e,t){const n=t,r=n.id||n.callId;if(!r)return e;const s=n.name||"tool",o=`Starting ${s}...`;let a=[...e.messages],i=nt(a,r);if(i===-1){for(let d=a.length-1;d>=0;d--)if(a[d].role==="assistant"){i=d;break}}if(i!==-1){const d=a[i],c=[...d.toolCalls||[]],u=c.findIndex(g=>g.id===r);u>=0?c[u]={...c[u],status:"running",content:o}:c.push({id:r,name:s,args:n.args||{},status:"running",content:o}),a[i]={...d,toolCalls:c}}return{...e,messages:a}}function Sr(e,t){const n=t.id;if(!n)return e;let r=[...e.messages];const s=nt(r,n);if(s!==-1){const o=r[s],a=oe(t.content),i=(o.toolCalls||[]).map(d=>d.id===n?{...d,content:typeof a=="string"?a:d.content}:d);r[s]={...o,toolCalls:i}}return{...e,messages:r}}function Ar(e,t){const n=t.id;if(!n)return e;let r=[...e.messages];const s=nt(r,n),o=oe(t.content??t.error);if(s!==-1){const i=r[s],d=(i.toolCalls||[]).map(c=>c.id===n?{...c,status:t.error?"failed":"completed",content:typeof o=="string"?o:c.content,artifact:t.artifact}:c);r[s]={...i,toolCalls:d}}const a={id:`tool-${n}`,role:"tool",name:t.name,content:[{type:"text",text:typeof o=="string"?o:""}],artifact:t.artifact,toolCallId:n,createdAt:new Date().toISOString()};return{...e,messages:[...r,a]}}function Cr(e,t){const n=t.artifactId,r=br(e.messages,n,t.callId);if(!r)return e;const s=e.messages.indexOf(r),o=yr(r,{status:t.status,progress:t.progress,error:t.error});return t.partial_data&&o.artifact&&(o.artifact={...o.artifact,...t.partial_data}),{...e,messages:Ot(e.messages,s,o)}}function Me(e){if(!(!e||typeof e!="object"||Array.isArray(e)))return{...e}}function Oe(e,t){if(e)for(const n of t){const r=e[n];if(typeof r=="string"&&r.trim())return r.trim()}}function xr(e,t){if(!e)return null;for(const n of t){const r=e[n];if(typeof r=="number"&&Number.isFinite(r))return r}return null}function Dt(e){const t=Me(e);if(t)return Me(t.configurable)??t}async function Vt(e,t){var i,d;if(!e)return e??null;const n=ae(e),r=Array.isArray(n.checkpoints)?n.checkpoints:n.checkpoints?Object.values(n.checkpoints):[],s=new Set;for(const c of r){const u=(i=c==null?void 0:c.values)==null?void 0:i.messages;if(Array.isArray(u))for(const g of u){const h=g==null?void 0:g.content;if(Array.isArray(h))for(const y of h){if(!y||typeof y!="object"||y.type!=="image_url"&&y.type!=="file")continue;const v=y.fileId||y.file_id;typeof v=="string"&&v.trim()&&s.add(v)}}}if(s.size===0)return n;const o=await Promise.all(Array.from(s).map(async c=>{try{const u=await t.getFileInfo(c),g=ae(u);return[c,g]}catch{return[c,null]}})),a=new Map(o);for(const c of r){const u=(d=c==null?void 0:c.values)==null?void 0:d.messages;if(Array.isArray(u))for(const g of u){const h=g==null?void 0:g.content;if(Array.isArray(h))for(const y of h){if(!y||typeof y!="object"||y.type!=="image_url"&&y.type!=="file")continue;const v=y.fileId||y.file_id;if(!v)continue;const p=a.get(v),k=(p==null?void 0:p.contentUrl)||(p==null?void 0:p.content_url);k&&(y.type==="image_url"?(y.imageUrl=y.imageUrl||{},y.imageUrl.url=k):y.type==="file"&&(y.url=k,!y.name&&(p!=null&&p.filename||p!=null&&p.name)&&(y.name=(p==null?void 0:p.filename)||(p==null?void 0:p.name))))}}}return n}function rt(e){const r=[...(Array.isArray(e==null?void 0:e.checkpoints)?(e==null?void 0:e.checkpoints)??[]:e!=null&&e.checkpoints?Object.values(e.checkpoints):[]).map((o,a)=>Mr(ae(o),a)).filter(o=>!!o)].sort((o,a)=>Kt(a.createdAt)-Kt(o.createdAt)),s=r[0]??null;return{threadId:(e==null?void 0:e.threadId)??"",latest:s,checkpoints:r,interrupt:(s==null?void 0:s.interrupt)??null}}function Mr(e,t){var N,S;if(!e)return null;const n=((N=e.values)==null?void 0:N.activeAgent)??null,r=(S=e.values)==null?void 0:S.messages,o=(Array.isArray(r)?r:[]).map(M=>Er(M,n)).filter(M=>!!M),a=Me(e.metadata)??{},i=Dt(e.config),d=Me(e.parentConfig),c=Dt(d),u=Oe(i,["checkpointId"]),g=Oe(i,["checkpointNs"]),h=Oe(c,["checkpointId"]),y=Me(e.config),v=Array.isArray(e.tasks)?e.tasks.map(M=>({...M})):e.tasks??null,p=Array.isArray(e.next)?[...e.next]:e.next??null,k=typeof e.createdAt=="string"&&e.createdAt.trim()?e.createdAt:new Date(Date.now()-t).toISOString(),T={...a,step:xr(a,["step"])??0,source:Oe(a,["source"])??null},_=o.map(M=>({...M,checkpointId:M.checkpointId??u??null,checkpointNs:M.checkpointNs??g??null})),I=e.values,j=Array.isArray(e.interrupts)?e.interrupts:Array.isArray(I==null?void 0:I.interrupts)?I.interrupts:[];return{checkpointId:u??null,checkpointNs:g??null,createdAt:k,parentId:h??null,messages:_,interrupt:Pr(j,t,u??null),metadata:T,config:y??null,parentConfig:d??null,next:p,tasks:v,values:e.values??{}}}function Er(e,t){const n=Je(e);return n?(n.role==="assistant"&&!n.name&&t&&(n.name=t),n):null}function Pr(e,t,n){const r=e.length;for(let s=r-1;s>=0;s-=1){const o=e[s];if(!o||typeof o!="object")continue;const a=o,i=a.value??o;if(i==null)continue;return{id:typeof a.id=="string"&&a.id.trim()?a.id:`interrupt-${n??t}-${s}`,value:i}}return null}function Kt(e){if(!e)return 0;const t=Date.parse(e);return Number.isFinite(t)?t:0}const Ht=120;function _r(e){if(!Array.isArray(e))return"";const t=e.filter(r=>!!(r&&r.type==="text")).map(r=>(r.text??"").trim()).filter(Boolean);if(!t.length)return"";const n=t.join(" ").replace(/\s+/g," ").trim();return n?n.length>Ht?`${n.slice(0,Ht-3)}…`:n:""}function Nr(e){return _r(e.content)||""}function zr(e){const t=new Map,n=[],r=new Map,s=[];for(let c=0;c<e.length;c++){const u=e[c],g=u.checkpointId,h=g??`cp-${c}`,y=u.metadata??{},v=typeof y.step=="number"?y.step:null,p=typeof y.source=="string"?y.source:null;let k=null,T=null;const _=Array.isArray(u.messages)?u.messages:[];for(const S of _)S.role==="user"&&(T||(T=S),S.id&&(k=S.id));const I=u.next&&u.next.length>0?String(u.next[0]):null,j=u.parentConfig??null,N={id:h,step:v,source:p,createdAt:u.createdAt??null,namespace:u.checkpointNs??null,parentId:u.parentId??null,next:I,parentConfig:j,userMessageId:k};if(s.push(N),g&&t.set(g,N),g&&T){const S=Nr(T);S&&r.set(g,S)}n.push({id:h,messageId:k,step:v,source:p,createdAt:u.createdAt??null,next:I,parentConfig:j})}const o=new Map;for(const c of s){if(!c.userMessageId)continue;const u=o.get(c.userMessageId)??[];u.push(c),o.set(c.userMessageId,u)}for(const c of o.values()){if(!c.length)continue;c.sort((g,h)=>{const y=g.createdAt?Date.parse(g.createdAt):0;return(h.createdAt?Date.parse(h.createdAt):0)-y});const u=c.length;for(let g=0;g<c.length;g++){const h=c[g];h.attemptCount=u,h.attemptIndex=g,h.isLatestAttempt=g===0}}return{checkpoints:e,checkpointMetaByCheckpointId:t,timeline:n,messagePreviews:r,getLatest:()=>{const c=n[0];if(c)return t.get(c.id)},getCheckpoint:c=>t.get(c),getMessageAttempts:c=>{const u=[];for(const g of t.values())g.userMessageId===c&&u.push(g);return u.length?(u.sort((g,h)=>{const y=typeof g.attemptIndex=="number"?g.attemptIndex:Number.MAX_SAFE_INTEGER,v=typeof h.attemptIndex=="number"?h.attemptIndex:Number.MAX_SAFE_INTEGER;return y-v}),u):[]}}}function jr(e,t,n){if(!e)return{attemptCount:1,attemptIndex:0,attempts:[]};const r=n.getMessageAttempts(e);if(!r.length)return{attemptCount:1,attemptIndex:0,attempts:[]};let s=0;if(t){const o=r.findIndex(a=>a.id===t);o>=0&&(s=o)}return{attemptCount:r.length,attemptIndex:s,attempts:r}}function Ur(e){return l.useMemo(()=>zr(e),[e])}function st({api:e,fileApi:t,seed:n,onError:r,currentThreadId:s,autoLoadInitial:o=!0,isStreaming:a,getMessages:i}){const[d,c]=l.useState(null),g=l.useMemo(()=>rt(d),[d]).checkpoints,h=Ur(g),y=h.timeline,[v,p]=l.useState(!1),[k,T]=l.useState(!1),[_,I]=l.useState(null),j=l.useRef(s),N=l.useRef(null),S=l.useRef(null);l.useEffect(()=>{j.current=s},[s]);const M=l.useCallback(async P=>{const O=await e.getState({threadId:P.threadId,checkpointId:P.checkpointId,checkpointNs:P.checkpointNs}),U={version:"values@1",threadId:P.threadId,checkpoints:[O]},K=t?await Vt(U,t):U,{latest:V}=rt(K);return V},[e,t]),m=l.useCallback(async(P,O)=>{var x;if(!P)return;const U=`${P}:${O??"latest"}`,K=i();if(N.current===U&&!v&&K.length>0)return;(x=S.current)==null||x.abort();const V=new AbortController;S.current=V,p(!0),I(null);try{const b=await M({threadId:P,checkpointId:O??void 0});if(j.current!==P)return;n((b==null?void 0:b.messages)??[],{checkpointId:(b==null?void 0:b.checkpointId)??null,checkpointNs:(b==null?void 0:b.checkpointNs)??null,pendingInterrupt:(b==null?void 0:b.interrupt)??null,values:b==null?void 0:b.values}),N.current=U;const $=await e.getStateHistory({threadId:P,limit:100,includeMessages:!1});j.current===P&&c($)}catch(b){if(!lt.isCancel(b)){const $=String(b);I($),r==null||r($)}}finally{p(!1)}},[e,n,M,r,v,i]),w=l.useCallback(async(P,O)=>{if(s){T(!0);try{const U=await M({threadId:s,checkpointId:P,checkpointNs:O??void 0});n((U==null?void 0:U.messages)??[],{checkpointId:(U==null?void 0:U.checkpointId)??P,checkpointNs:(U==null?void 0:U.checkpointNs)??O,pendingInterrupt:(U==null?void 0:U.interrupt)??null,values:U==null?void 0:U.values})}catch(U){console.error("[useThreadHistoryState] Navigation failed",U)}finally{T(!1)}}},[s,M,n]),B=l.useCallback(async()=>{s&&await m(s)},[s,m]),L=l.useCallback(async P=>{var K;const O=(P==null?void 0:P.threadId)||s;if(!O||s!==O)return;if(c(P),N.current=`${O}:latest`,(K=P.values)!=null&&K.messages){const V=await M({threadId:O});V&&n(V.messages??[],{checkpointId:V.checkpointId??null,checkpointNs:V.checkpointNs??null,pendingInterrupt:V.interrupt??null,values:V.values})}},[s,M,n]);l.useEffect(()=>{if(!o||!s||v||a)return;const P=`${s}:latest`;N.current!==P&&m(s)},[o,s,v,a,m]);const E=l.useCallback(()=>{c(null),p(!1),T(!1),I(null),N.current=null},[]);return{threadCheckpoints:g,threadTimeline:y,checkpointIndex:h,isLoadingThread:v,isLoadingCheckpoint:k,threadStateError:_,loadThread:m,navigateToCheckpoint:w,setCurrentCheckpointId:(P,O)=>{n(i(),{checkpointId:P,checkpointNs:O})},returnToLatest:B,handleValuesEvent:L,markSkipNextLoad:()=>{},markStreamPendingThread:()=>{},resetHistoryState:E,clearState:E}}const Gt=l.createContext(null),qt=l.createContext(null);function ot(e){const t=l.useContext(Gt);if(!t&&!(e!=null&&e.optional))throw new Error("useThreadState must be used within a ThreadStateProvider");return t}function Wt(){const e=l.useContext(qt);if(!e)throw new Error("useThreadStateUpdater must be used within a ThreadStateProvider");return e}function Jt({children:e,initialThreadId:t=null,initialCheckpointId:n=null,initialCheckpointNs:r=null,autoLoadInitial:s=!0,isStreaming:o,onError:a}){const{chatApi:i,fileApi:d}=be(),{currentThreadId:c}=Fe(),{state:u,seed:g,onEvent:h,dispatch:y}=vr(),{threadCheckpoints:v,threadTimeline:p,checkpointIndex:k,isLoadingThread:T,isLoadingCheckpoint:_,threadStateError:I,loadThread:j,navigateToCheckpoint:N,setCurrentCheckpointId:S,returnToLatest:M,handleValuesEvent:m,markSkipNextLoad:w,markStreamPendingThread:B,resetHistoryState:L}=st({api:i,fileApi:d,seed:g,onError:a,currentThreadId:c,initialThreadId:t,initialCheckpointId:n,initialCheckpointNs:r,autoLoadInitial:s,isStreaming:o,getMessages:l.useCallback(()=>u.messages,[u.messages])}),E=l.useRef(null),P=l.useCallback(f=>{E.current=f},[]),O=l.useRef(null),U=l.useCallback(f=>{O.current=f},[]),K=l.useMemo(()=>({assemblingMessageId:u.assemblingId??null}),[u.assemblingId]),V=l.useCallback((f,C)=>{const z=Nt(f,"user");return y({type:"user_message",payload:{message:z,editingMessageId:C==null?void 0:C.editingMessageId}}),z},[y]),x=l.useCallback(async()=>{E.current?await E.current():(g([],{}),L())},[g,L]),b=l.useMemo(()=>Kn(u.messages),[u.messages]),$=l.useMemo(()=>({status:u.status,threadId:c,messages:u.messages,taskMessagesByScope:u.taskMessagesByScope,interrupt:u.pendingInterrupt,checkpoint:{id:u.lastCheckpointId??null,namespace:u.lastCheckpointNs??null},checkpoints:v,checkpointIndex:k,timelineCheckpoints:p,metadata:K,values:u.values??{},isLoading:T,isLoadingCheckpoint:_,error:I,loadOlder:async()=>{},seedFromSnapshot:f=>{g(f.messages,{checkpointId:f.checkpointId,checkpointNs:f.checkpointNs,pendingInterrupt:f.interrupt,values:f.values})},clearState:x,navigateToCheckpoint:N,setCurrentCheckpointId:S,returnToLatest:M,loadThread:async(f,C,z)=>{await j(f,C,{clearProgress:!1})},clearThread:x,respondToInterrupt:async(f,C,z)=>{O.current&&await O.current(f,C,z)},messagePreviews:k.messagePreviews,handleValuesEvent:m,markSkipNextLoad:w,markStreamPendingThread:B,resetHistoryState:L,pushUser:V,onEvent:h,artifacts:b}),[c,u.messages,u.taskMessagesByScope,u.pendingInterrupt,u.lastCheckpointId,u.lastCheckpointNs,u.values,v,p,k,K,T,_,I,g,x,N,S,M,j,m,w,B,V,h,b]),D=l.useMemo(()=>({registerClearThread:P,registerRespondToInterrupt:U}),[P,U]);return q.jsx(qt.Provider,{value:D,children:q.jsx(Gt.Provider,{value:$,children:e})})}const Xt=l.createContext(null),Fr=l.createContext(!1);function Lr({children:e,onError:t,onAuthError:n,onConnectionError:r,onToolEnd:s,onUpdateEvent:o,onCustomEvent:a,onMetadataEvent:i,onFinish:d,onStreamingChange:c}){const{chatApi:u,baseUrl:g}=be(),h=g,y=le(t),v=le(n),p=le(r),k=le(s),T=le(o),_=le(a),I=le(i),j=le(d),N=le(c),S=l.useMemo(()=>({onError:y,onAuthError:v,onConnectionError:p,onMetadataEvent:I,onCustomEvent:_,onUpdateEvent:T,onToolEnd:k,onFinish:j}),[y,v,p,I,_,T,k,j]);return q.jsx(Fr.Provider,{value:!0,children:q.jsx(Or,{api:u,streamBaseUrl:h,handlers:S,onStreamingChange:N,children:e})})}function Or({children:e,api:t,streamBaseUrl:n,handlers:r,onStreamingChange:s}){const{setCurrentThreadId:o,currentThreadIdRef:a,addThreadFromEvent:i,currentThreadId:d}=Fe(),{interrupt:c,checkpoint:u,timelineCheckpoints:g,handleValuesEvent:h,markSkipNextLoad:y,markStreamPendingThread:v,resetHistoryState:p,pushUser:k,onEvent:T,messages:_}=ot(),{registerClearThread:I,registerRespondToInterrupt:j}=Wt(),N=l.useCallback(f=>{i(f),v(f.threadId),a.current!==f.threadId&&((f.created??!a.current)&&y(f.threadId),o(f.threadId))},[i,y,v,o,a]),S=zt({baseUrl:n,onEvent:T,onError:f=>{var C;(C=r.onError)==null||C.call(r,(f==null?void 0:f.message)??String(f))},onAuthError:r.onAuthError,onConnectionError:r.onConnectionError,onFinish:r.onFinish,onThreadInfo:N,onMetadataEvent:r.onMetadataEvent,onCustomEvent:r.onCustomEvent,onUpdateEvent:r.onUpdateEvent,onToolEnd:r.onToolEnd,handleValuesEvent:h});l.useEffect(()=>{s==null||s(S.isStreaming)},[S.isStreaming,s]);const{stream:M,stop:m,clear:w,isStreaming:B,error:L,connected:E,streamedMessages:P,activeMessageId:O}=S;l.useEffect(()=>{d!==void 0&&w()},[d,w]);const U=l.useCallback(async(f,C)=>{await M(f,C)},[M]),K=l.useRef(u);l.useEffect(()=>{K.current=u},[u]);const V=l.useCallback(async(f,C,z)=>{const te=a.current;if(!te)throw new Error("No active thread to handle interrupt");const J=f?C??!0:!1,G=K.current,Y=(z==null?void 0:z.checkpointId)??G.id??void 0,se=(z==null?void 0:z.checkpointNs)??G.namespace??void 0,ue={threadId:te,checkpointId:Y,checkpointNs:se,command:{kind:"resume",value:J},payload:z==null?void 0:z.payload};U(ue)},[a,U]);l.useEffect(()=>{j(V)},[V,j]);const x=l.useCallback(async()=>{m(),w(),p(),o(null)},[w,p,o,m]);l.useEffect(()=>{I(x)},[x,I]);const b=l.useCallback(async(f,C)=>{B&&m();let z=a.current;const te=(f==null?void 0:f.text)??"",J=(f==null?void 0:f.attachments)??[],G=(te==null?void 0:te.trim())??"",Y={...(f==null?void 0:f.payload)??{}},se=Array.isArray(Y.messages)?Y.messages:void 0;se&&delete Y.messages;const ue=!!(se&&se.length),W=!!(f.contentParts&&f.contentParts.length>0);if(!z&&!G&&J.length===0&&!ue&&!W)return;if(!z){const he=Math.floor(Date.now()/1e3).toString(16).padStart(8,"0"),ye=Array.from({length:4},()=>Math.floor(Math.random()*4294967295).toString(16).padStart(8,"0")).join("").slice(0,16);z=`${he}${ye}`,y(z),o(z)}let Z=null;f.contentParts&&f.contentParts.length>0&&(Z=f.contentParts);const{contentParts:we,filesInfo:X}=Z?{contentParts:Z,filesInfo:[]}:await cr(J),Q=[...we];G&&Q.push({type:"text",text:te});const me=f==null?void 0:f.originalMessageId,De=!!(f!=null&&f.edit&&me),Ve=!ue&&Q.length>0;let de=null;if(Ve){const he=De?me:`msg-${Date.now()}`;de=Nt({id:he,role:"user",content:Q,createdAt:new Date().toISOString()},"user"),De?k(de,{editingMessageId:me}):k(de)}const Te=ue?se:de?[de]:[],ne={...Y,...X.length?{files_info:X}:{}};Te.length?ne.messages=Te:"messages"in ne||(ne.messages=[]);const Pe=(f==null?void 0:f.checkpointId)??u.id??void 0;if(f!=null&&f.edit&&!Pe)throw new Error(`[streaming] Missing checkpointId for edit submit. threadId=${z??"null"}`);const _e={threadId:z,content:f==null?void 0:f.text,payload:ne,config:f==null?void 0:f.config,checkpointId:Pe,command:f==null?void 0:f.command,edit:f==null?void 0:f.edit};return U(_e,C)},[u,a,B,y,k,U,m,g]),$=l.useMemo(()=>{const f=Object.keys(P).length>0;if(!B&&!f)return _;const C=new Map;return _.forEach(z=>C.set(z.id,z)),Object.values(P).forEach(z=>{C.set(z.id,z)}),Array.from(C.values())},[B,P,_]),D=l.useMemo(()=>({isStreaming:B,error:L,connectionState:L?"error":B?E?"connected":"connecting":"idle",messages:$,activeMessageId:O,submit:b,stop:m,interrupt:c,resume:()=>Promise.resolve(),goto:(f,C)=>Promise.resolve(),clearError:()=>{}}),[B,L,b,m,c,E,$]);return q.jsx(Xt.Provider,{value:D,children:e})}function le(e){const t=l.useRef(e);return l.useEffect(()=>{t.current=e},[e]),l.useCallback((...n)=>{const r=t.current;if(r)return r(...n)},[])}function $r(e){return l.useContext(Xt)}function Qt(e){return typeof e=="object"&&e!==null}function Br(e,t){if(Object.is(e,t))return!0;if(!Qt(e)||!Qt(t))return!1;const n=Object.keys(e),r=Object.keys(t);if(n.length!==r.length)return!1;for(const s of n)if(!Object.prototype.hasOwnProperty.call(t,s)||!Object.is(e[s],t[s]))return!1;return!0}function Dr(e){const t=l.useRef(e),n=l.useRef(e);return Br(t.current,e)||(t.current=e,n.current=e),n.current}function Yt(e){const t=e.artifact&&typeof e.artifact=="object"?e.artifact:null,n=!t&&e.content&&typeof e.content=="object"?e.content:null,r=t??n,s=(r==null?void 0:r.task_id)??(r==null?void 0:r.taskId)??null;return typeof s=="string"?s:null}function Vr(e){const{setCurrentTaskId:t,getCurrentTaskId:n,onToolEnd:r}=e;return s=>{const o=Yt(s),a=(n==null?void 0:n())??null;o&&o!==a&&t(o),r==null||r(s)}}function Kr({children:e,apiConfig:t,initialThreadId:n=null,initialCheckpointId:r=null,initialCheckpointNs:s=null,autoLoadInitial:o=!0,onConnectionError:a,onError:i,onAuthError:d,onThreadChange:c,onToolEnd:u,onUpdateEvent:g,onCustomEvent:h,onMetadataEvent:y,onFinish:v}){const p=Dr(t),[k,T]=l.useState(!1),_=ce(i),I=ce(d),j=ce(a),N=ce(c),S=ce(u),M=ce(g),m=ce(h),w=ce(y),B=ce(v),L=l.useMemo(()=>({onError:_,onAuthError:I,onConnectionError:j,onToolEnd:S,onUpdateEvent:M,onCustomEvent:m,onMetadataEvent:w,onFinish:B}),[_,I,j,S,M,m,w,B]);return q.jsx(ir,{apiConfig:p,children:q.jsx(Ft,{initialThreadId:n,onError:_,onThreadChange:N,children:q.jsx(Jt,{initialThreadId:n,initialCheckpointId:r,initialCheckpointNs:s,autoLoadInitial:o,onError:_,isStreaming:k,children:q.jsx(Lr,{...L,onStreamingChange:T,children:e})})})})}function ce(e){const t=l.useRef(e);return t.current=e,l.useCallback((...n)=>{const r=t.current;if(r)return r(...n)},[])}const Hr=1,Gr=1e6;let at=0;function qr(){return at=(at+1)%Number.MAX_SAFE_INTEGER,at.toString()}const it=new Map,Zt=e=>{if(it.has(e))return;const t=setTimeout(()=>{it.delete(e),Ee({type:"REMOVE_TOAST",toastId:e})},Gr);it.set(e,t)},Wr=(e,t)=>{switch(t.type){case"ADD_TOAST":return{...e,toasts:[t.toast,...e.toasts].slice(0,Hr)};case"UPDATE_TOAST":return{...e,toasts:e.toasts.map(n=>n.id===t.toast.id?{...n,...t.toast}:n)};case"DISMISS_TOAST":{const{toastId:n}=t;return n?Zt(n):e.toasts.forEach(r=>{Zt(r.id)}),{...e,toasts:e.toasts.map(r=>r.id===n||n===void 0?{...r,open:!1}:r)}}case"REMOVE_TOAST":return t.toastId===void 0?{...e,toasts:[]}:{...e,toasts:e.toasts.filter(n=>n.id!==t.toastId)}}},$e=[];let Be={toasts:[]};function Ee(e){Be=Wr(Be,e),$e.forEach(t=>{t(Be)})}function Jr({...e}){const t=qr(),n=s=>Ee({type:"UPDATE_TOAST",toast:{...s,id:t}}),r=()=>Ee({type:"DISMISS_TOAST",toastId:t});return Ee({type:"ADD_TOAST",toast:{...e,id:t,open:!0,onOpenChange:s=>{s||r()}}}),{id:t,dismiss:r,update:n}}function Xr(){const[e,t]=ct.useState(Be);return ct.useEffect(()=>($e.push(t),()=>{const n=$e.indexOf(t);n>-1&&$e.splice(n,1)}),[e]),{...e,toast:Jr,dismiss:n=>Ee({type:"DISMISS_TOAST",toastId:n})}}function Qr(e){const{allowFileOpen:t,currentThreadId:n}=e,{fileApi:r}=be(),{toast:s}=Xr(),[o,a]=l.useState({}),[i,d]=l.useState(null),[c,u]=l.useState(!1),g=l.useCallback(()=>{u(!1),d(null)},[]),h=l.useCallback(v=>{d(v),u(!0)},[]),y=l.useCallback(async(v,p,k)=>{var T,_;if(!t){v.preventDefault();return}if(o[k]){v.preventDefault();return}try{const I=String(p.url??""),j=I.match(/\/chat\/files\/([^/]+)(?:\/(view|download))?/);if(j){v.preventDefault();const N=j[1],S=p.name||`file_${N}`,M=p.mimeType||"application/octet-stream";h({id:N,name:S,mimeType:M});return}if(I.startsWith("data:")){v.preventDefault(),a(S=>({...S,[k]:!0}));const N=s({title:"Fetching file...",description:"",open:!0});try{const S=await r.listFiles(n??void 0);if(!S||!Array.isArray(S))throw new Error("Invalid file list response");const M=S.find(m=>!m||typeof m!="object"||!((m.filename??"")===(p.name??""))?!1:typeof p.size=="number"&&typeof m.size=="number"?m.size===p.size:!0);if(!(M!=null&&M.id))throw new Error(`File "${p.name}" is not yet available on the server`);if(!M.id||!M.filename)throw new Error("Invalid file data received from server");h({id:M.id,name:p.name||M.filename||`file_${M.id}`,mimeType:p.mimeType||M.mime_type||"application/octet-stream"}),(T=N.update)==null||T.call(N,{id:N.id,title:"Success",description:`Opened ${p.name}`,open:!0})}catch(S){console.error("Failed to fetch server file:",S);const M=S instanceof Error?S.message:"Unknown error occurred";(_=N.update)==null||_.call(N,{id:N.id,title:"Failed",description:M}),s({title:"Failed to fetch file",description:M,open:!0})}finally{a(S=>({...S,[k]:!1}))}}}catch(I){console.error("File click error:",I),a(j=>({...j,[k]:!1}))}},[t,o,s,n,h]);return{uploadingFiles:o,handleFileClick:y,fileViewerOpen:c,currentFileInfo:i,closeFileViewer:g}}function Yr(e){return l.useMemo(()=>{const t=e;let n=Array.isArray(t.content)?t.content:[];return typeof t.content=="string"&&(n=[{type:"text",text:t.content}]),{contentParts:n,textContent:Pt(n),toolMeta:_t(t),imageParts:n.filter(r=>r.type==="image_url"),fileParts:n.filter(r=>r.type==="file"),toolRaw:kt(n),isToolStreaming:!!t.toolStreaming}},[e])}const Rt="data:";function Zr(e){if(!e)return[];const t=[],n=e.split(/\r?\n/);for(const r of n){const s=r.trim();if(!s||!s.startsWith(Rt))continue;const o=s.slice(Rt.length).trim();if(!o||o.toLowerCase()==="[done]")continue;const a=Ne(o);a&&typeof a=="object"&&t.push(a)}return t}function Rr(e){for(let t=e.length-1;t>=0;t-=1){const n=e[t];if(n&&typeof n=="object"&&n.type==="tool.end")return n}return null}function es(e){return l.useMemo(()=>{const t=e.content.filter(d=>d.type==="text");if(!t.length)return null;let r=t.flatMap(d=>Zr(d.text??""));if(!r.length){const d=t.map(u=>u.text??"").join(`
8
+ `),c=Ne(d);c&&typeof c=="object"&&(r=[c])}if(!r.length)return null;const o=Rr(r)??r[r.length-1];if(!o)return null;const a=o.output??o.payload??o,i=oe(a);return i&&typeof i=="object"&&!Array.isArray(i)?{kind:"dict",value:i,data:i,event:o}:{kind:"generic",value:i,event:o}},[e])}function en(e){var B;const t=typeof e=="string"?e:e==null?void 0:e.threadId,n=typeof e=="object"?e.lazy:!1,r=Fe({optional:!0}),s=ot({optional:!0}),o=$r(),{currentThreadId:a,setCurrentThreadId:i,actions:d}=r||{currentThreadId:null,setCurrentThreadId:()=>{},actions:{}},c=!!t&&t!==a,[u,g]=l.useState([]),h=l.useCallback(L=>{g(L)},[]),{isLoadingThread:y,threadStateError:v,threadCheckpoints:p,loadThread:k}=st({api:be().chatApi,fileApi:be().fileApi,seed:h,currentThreadId:c?t:null,initialThreadId:c?t:null,isStreaming:!1,getMessages:()=>u,autoLoadInitial:c&&!n});l.useEffect(()=>{!c&&!n&&a&&(s!=null&&s.loadThread)&&s.loadThread(a)},[c,n,a,s==null?void 0:s.loadThread]);const T=l.useMemo(()=>{var L;return((L=p[0])==null?void 0:L.values)||{}},[p]),_=l.useMemo(()=>({timeline:[],messagePreviews:{}}),[]),I=t||a,j=c?y?"loading":"idle":(s==null?void 0:s.status)||"idle",N=c?u:(o==null?void 0:o.messages)||[],S=c?y:(s==null?void 0:s.isLoading)||!1,M=c?T:(s==null?void 0:s.values)||{},m=c?{}:(s==null?void 0:s.taskMessagesByScope)||{},w=c?v:(o==null?void 0:o.error)||(s==null?void 0:s.error)||null;return{threadId:I,status:j,messages:N,isLoading:S,isHistoryLoading:S,error:w,values:M,taskMessagesByScope:m,metadata:c?{}:s==null?void 0:s.metadata,navigateToCheckpoint:c?async()=>{}:(s==null?void 0:s.navigateToCheckpoint)||(async()=>{}),returnToLatest:c?async()=>{}:(s==null?void 0:s.returnToLatest)||(async()=>{}),checkpoint:c?p[0]?{id:p[0].checkpointId,namespace:p[0].checkpointNs}:null:(s==null?void 0:s.checkpoint)||null,checkpoints:c?p:(s==null?void 0:s.checkpoints)||[],checkpointIndex:c?_:(s==null?void 0:s.checkpointIndex)||{timeline:[],messagePreviews:{}},interrupt:c?null:(s==null?void 0:s.interrupt)||null,respondToInterrupt:c?async()=>{}:(s==null?void 0:s.respondToInterrupt)||(async()=>{}),isStreaming:(o==null?void 0:o.isStreaming)||!1,activeMessageId:(o==null?void 0:o.activeMessageId)||null,connectionState:(o==null?void 0:o.connectionState)||"disconnected",streamingAssistantId:!c&&(o!=null&&o.isStreaming)&&((B=s==null?void 0:s.metadata)!=null&&B.assemblingMessageId)?s.metadata.assemblingMessageId:null,submit:(o==null?void 0:o.submit)||(async()=>{}),stop:(o==null?void 0:o.stop)||(()=>{}),clearThread:c?async()=>{}:(s==null?void 0:s.clearThread)||(async()=>{}),setCurrentThreadId:i,loadHistory:c?async()=>{t&&await k(t)}:async()=>{},createThread:d==null?void 0:d.createThread,deleteThread:d==null?void 0:d.deleteThread,renameThread:d==null?void 0:d.renameThread,shareThread:d==null?void 0:d.shareThread,threads:(r==null?void 0:r.threads)||[],isThreadsLoading:(r==null?void 0:r.isLoading)||!1}}function ts({submit:e,chatRequest:t,lastCheckpointId:n,lastCheckpointNs:r,onMessageSent:s,onExcelUploadSuccess:o,onError:a,enableMessageEditing:i,messages:d,setPendingAssistantResponse:c,project:u,onEvent:g,threadId:h,clearComposerOnSend:y=!0}){const{messages:v}=en(),[p,k]=l.useState(null),[T,_]=l.useState(""),[I,j]=l.useState(null),[N,S]=l.useState(null),[M,m]=l.useState(!1),[w,B]=l.useState(""),L=l.useRef(w),E=l.useRef(null);l.useEffect(()=>{if(!p)if(h){const f=localStorage.getItem(Ye(h));B(f||"")}else B("")},[h,p]);const P=l.useCallback(f=>{B(f),!p&&h&&localStorage.setItem(Ye(h),f)},[h,p]);l.useEffect(()=>{L.current=w},[w]),l.useEffect(()=>{if(!p){E.current=null;return}E.current===null&&(E.current=L.current),P(T??"")},[T,p,P]);const O=l.useCallback(f=>{P(f)},[P]),U=async(f,C)=>{const z=Array.isArray(C)?{files:C}:C??{},te=z.files??[],J=z.contentParts??[],G=f.trim();if(!(!G&&te.length===0&&J.length===0))try{const Y=te.map(async X=>{try{const Q=await Mt.uploadFile(X);return{file:X,record:Q}}catch(Q){throw console.error("Failed to upload file",X.name,Q),new Error(`Failed to upload ${X.name}`)}}),ue=(await Promise.all(Y)).map(({record:X})=>{const Q=X.mime_type;return Q.startsWith("image/")?{type:"image_url",image_url:{url:X.content_url}}:{type:"file",url:X.content_url,mimeType:Q,name:X.filename,size:X.size}}),W=[...J,...ue],Z=p?(I==null?void 0:I.checkpointId)??n??void 0:n??void 0,we=p?(I==null?void 0:I.checkpointNs)??r??void 0:r??void 0;await e({text:G||"",contentParts:W,attachments:te,payload:t.payload,edit:!!p,checkpointId:Z,checkpointNs:we,project:u??void 0,originalMessageId:p??void 0,config:t.config},g?{onEvent:g}:void 0),s==null||s(G),c(!0),y&&(h&&localStorage.removeItem(Ye(h)),P("")),S(null),k(null),_(""),j(null)}catch(Y){const se=(Y==null?void 0:Y.message)||"Failed to send message";S(se),a==null||a(se),c(!1)}},K=(f,C)=>{C||U(f,{files:[]})},V=l.useCallback(async f=>{await e({attachments:[f],payload:t.payload,checkpointId:n??void 0,checkpointNs:r??void 0,project:u??void 0,config:t.config},g?{onEvent:g}:void 0),o==null||o({file:f})},[n,r,t,o,e]),x=l.useCallback((f,C,z)=>{i&&(E.current=w,k(f),_(C),j({checkpointId:(z==null?void 0:z.checkpointId)??null,checkpointNs:(z==null?void 0:z.checkpointNs)??null}),S(null))},[w,i]),b=l.useCallback(()=>{k(null),_(""),j(null),S(null);const f=E.current;f!==null&&B(f),E.current=null},[]),$=l.useCallback(f=>{let C=null;for(let G=f-1;G>=0;G--)if(d[G].role==="user"){C=d[G];break}if(!C)return;const z=Array.isArray(C.content)?C.content:[],J=z.filter(G=>(G==null?void 0:G.type)==="text").map(G=>G.text).join("")||(()=>{try{return JSON.stringify(z,null,2)}catch{return String(z)}})();J&&e({text:J,payload:t.payload,checkpointId:n??void 0,checkpointNs:r??void 0,edit:!0,originalMessageId:C.id,config:t.config},g?{onEvent:g}:void 0)},[d,e,n,r,t]);return{editingMessageId:p,editingInitialValue:T,inputError:N,setInputError:S,dismissError:M,setDismissError:m,composerValue:w,handleComposerChange:O,handleSendMessage:U,handleQuickPrompt:K,handleExcelUpload:V,startEditing:x,cancelEditing:b,handleRegenerateCb:$,displayMessages:v}}function ns(e){return l.useMemo(()=>e?{textContent:Bn(e),imageParts:Dn(e),fileParts:Vn(e),toolCalls:wt(e),contentParts:e.content}:{textContent:"",imageParts:[],fileParts:[],toolCalls:[],contentParts:[]},[e])}function rs(e,t,n){const[r,s]=l.useState(e),o=l.useRef(e),a=l.useRef(null);return l.useEffect(()=>{o.current=e;const i=()=>{s(o.current),a.current&&(clearTimeout(a.current),a.current=null)};if(!t||n<=0){i();return}return a.current&&clearTimeout(a.current),a.current=setTimeout(()=>{i()},n),()=>{a.current&&(clearTimeout(a.current),a.current=null)}},[e,t,n]),r}A.ChatProviders=Kr,A.ThreadStateProvider=Jt,A.ThreadsProvider=Ft,A.cn=Fn,A.collectText=Pt,A.createTaskSyncToolEndHandler=Vr,A.extractTaskIdFromToolEnd=Yt,A.extractToolMeta=_t,A.formatToolOutput=Hn,A.getAgentNameFromMessage=dr,A.getChatToken=Re,A.getMessageAttemptInfo=jr,A.getToolCallArtifacts=Yn,A.getToolCalls=It,A.hasContent=Gn,A.hydrateHistorySnapshots=rt,A.isFileLike=qe,A.looksLikeMarkdown=bt,A.messageSignature=fr,A.normalizeInterruptId=ur,A.onChatTokenChanged=et,A.parseJsonSafe=Ne,A.pretty=We,A.refreshHistoryFileUrls=Vt,A.sanitizeForDisplay=Ce,A.setChatToken=ge,A.stringifyTool=kt,A.useApi=be,A.useChatController=ts,A.useChatSession=en,A.useFilePreview=Qr,A.useMessageContent=ns,A.useParsedMessageContent=Yr,A.useStream=zt,A.useStreamingMarkdownBuffer=rs,A.useThreadHistoryState=st,A.useThreadState=ot,A.useThreadStateUpdater=Wt,A.useThreads=Fe,A.useThreadsState=jt,A.useToolPayload=es,Object.defineProperty(A,Symbol.toStringTag,{value:"Module"})});
9
9
  //# sourceMappingURL=index.umd.js.map