@teodorruskvi/chat-core 0.1.29 → 0.1.30

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