@teodorruskvi/chat-core 0.1.31 → 0.1.33

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