teodor-new-chat-ui 4.3.6 → 4.3.7
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import type { ChatMessage, StreamEvent } from "@/types/api";
|
|
1
|
+
import type { ChatMessage, StreamEvent, PendingInterrupt } from "@/types/api";
|
|
2
2
|
export type ReducerStreamEvent = Exclude<StreamEvent, {
|
|
3
3
|
type: "thread_info";
|
|
4
4
|
} | {
|
|
@@ -14,10 +14,7 @@ export interface MessagesState {
|
|
|
14
14
|
lastBranch: Extract<StreamEvent, {
|
|
15
15
|
type: "branch";
|
|
16
16
|
}> | null;
|
|
17
|
-
pendingInterrupt:
|
|
18
|
-
id: string;
|
|
19
|
-
value: any;
|
|
20
|
-
} | null;
|
|
17
|
+
pendingInterrupt: PendingInterrupt;
|
|
21
18
|
messagesStreamMeta?: Record<string, {
|
|
22
19
|
lastSeq?: number | null;
|
|
23
20
|
lastText?: string;
|
|
@@ -34,10 +31,7 @@ export type MessagesAction = {
|
|
|
34
31
|
messages: ChatMessage[];
|
|
35
32
|
checkpointId?: string | null;
|
|
36
33
|
checkpointNs?: string | null;
|
|
37
|
-
pendingInterrupt?:
|
|
38
|
-
id: string;
|
|
39
|
-
value: any;
|
|
40
|
-
} | null;
|
|
34
|
+
pendingInterrupt?: PendingInterrupt;
|
|
41
35
|
};
|
|
42
36
|
} | {
|
|
43
37
|
type: "prepend";
|
package/dist/index.esm.js
CHANGED
|
@@ -4332,7 +4332,7 @@ function wv({
|
|
|
4332
4332
|
hasMore: S.hasMore,
|
|
4333
4333
|
nextCursor: S.nextCursor ?? null,
|
|
4334
4334
|
nextCursorNs: S.nextCursorNs ?? null,
|
|
4335
|
-
pendingInterrupt: S.
|
|
4335
|
+
pendingInterrupt: S.interrupt ?? null
|
|
4336
4336
|
};
|
|
4337
4337
|
if (S.checkpointId) {
|
|
4338
4338
|
const $ = Jo(S.checkpointId, S.checkpointNs ?? null);
|
|
@@ -4343,7 +4343,7 @@ function wv({
|
|
|
4343
4343
|
checkpointNs: S.checkpointNs ?? null,
|
|
4344
4344
|
nextCursor: S.nextCursor ?? null,
|
|
4345
4345
|
nextCursorNs: S.nextCursorNs ?? null,
|
|
4346
|
-
interrupt: S.
|
|
4346
|
+
interrupt: S.interrupt ?? null
|
|
4347
4347
|
}
|
|
4348
4348
|
}, "prepend");
|
|
4349
4349
|
}
|
package/dist/index.umd.js
CHANGED
|
@@ -35,7 +35,7 @@ React keys must be passed directly to JSX without using spread:
|
|
|
35
35
|
`+s):r.stack=s}catch{}}throw r}}_request(t,n){typeof t=="string"?(n=n||{},n.url=t):n=t||{},n=or(this.defaults,n);const{transitional:r,paramsSerializer:o,headers:s}=n;r!==void 0&&Lo.assertOptions(r,{silentJSONParsing:gn.transitional(gn.boolean),forcedJSONParsing:gn.transitional(gn.boolean),clarifyTimeoutError:gn.transitional(gn.boolean)},!1),o!=null&&(R.isFunction(o)?n.paramsSerializer={serialize:o}:Lo.assertOptions(o,{encode:gn.function,serialize:gn.function},!0)),n.allowAbsoluteUrls!==void 0||(this.defaults.allowAbsoluteUrls!==void 0?n.allowAbsoluteUrls=this.defaults.allowAbsoluteUrls:n.allowAbsoluteUrls=!0),Lo.assertOptions(n,{baseUrl:gn.spelling("baseURL"),withXsrfToken:gn.spelling("withXSRFToken")},!0),n.method=(n.method||this.defaults.method||"get").toLowerCase();let i=s&&R.merge(s.common,s[n.method]);s&&R.forEach(["delete","get","head","post","put","patch","common"],b=>{delete s[b]}),n.headers=$t.concat(i,s);const a=[];let l=!0;this.interceptors.request.forEach(function(x){typeof x.runWhen=="function"&&x.runWhen(n)===!1||(l=l&&x.synchronous,a.unshift(x.fulfilled,x.rejected))});const u=[];this.interceptors.response.forEach(function(x){u.push(x.fulfilled,x.rejected)});let d,f=0,h;if(!l){const b=[nc.bind(this),void 0];for(b.unshift(...a),b.push(...u),h=b.length,d=Promise.resolve(n);f<h;)d=d.then(b[f++],b[f++]);return d}h=a.length;let p=n;for(;f<h;){const b=a[f++],x=a[f++];try{p=b(p)}catch(g){x.call(this,g);break}}try{d=nc.call(this,p)}catch(b){return Promise.reject(b)}for(f=0,h=u.length;f<h;)d=d.then(u[f++],u[f++]);return d}getUri(t){t=or(this.defaults,t);const n=Vl(t.baseURL,t.url,t.allowAbsoluteUrls);return Dl(n,t.params,t.paramsSerializer)}};R.forEach(["delete","get","head","options"],function(t){sr.prototype[t]=function(n,r){return this.request(or(r||{},{method:t,url:n,data:(r||{}).data}))}}),R.forEach(["post","put","patch"],function(t){function n(r){return function(s,i,a){return this.request(or(a||{},{method:t,headers:r?{"Content-Type":"multipart/form-data"}:{},url:s,data:i}))}}sr.prototype[t]=n(),sr.prototype[t+"Form"]=n(!0)});let Bg=class gm{constructor(t){if(typeof t!="function")throw new TypeError("executor must be a function.");let n;this.promise=new Promise(function(s){n=s});const r=this;this.promise.then(o=>{if(!r._listeners)return;let s=r._listeners.length;for(;s-- >0;)r._listeners[s](o);r._listeners=null}),this.promise.then=o=>{let s;const i=new Promise(a=>{r.subscribe(a),s=a}).then(o);return i.cancel=function(){r.unsubscribe(s)},i},t(function(s,i,a){r.reason||(r.reason=new Er(s,i,a),n(r.reason))})}throwIfRequested(){if(this.reason)throw this.reason}subscribe(t){if(this.reason){t(this.reason);return}this._listeners?this._listeners.push(t):this._listeners=[t]}unsubscribe(t){if(!this._listeners)return;const n=this._listeners.indexOf(t);n!==-1&&this._listeners.splice(n,1)}toAbortSignal(){const t=new AbortController,n=r=>{t.abort(r)};return this.subscribe(n),t.signal.unsubscribe=()=>this.unsubscribe(n),t.signal}static source(){let t;return{token:new gm(function(o){t=o}),cancel:t}}};function zg(e){return function(n){return e.apply(null,n)}}function Hg(e){return R.isObject(e)&&e.isAxiosError===!0}const bi={Continue:100,SwitchingProtocols:101,Processing:102,EarlyHints:103,Ok:200,Created:201,Accepted:202,NonAuthoritativeInformation:203,NoContent:204,ResetContent:205,PartialContent:206,MultiStatus:207,AlreadyReported:208,ImUsed:226,MultipleChoices:300,MovedPermanently:301,Found:302,SeeOther:303,NotModified:304,UseProxy:305,Unused:306,TemporaryRedirect:307,PermanentRedirect:308,BadRequest:400,Unauthorized:401,PaymentRequired:402,Forbidden:403,NotFound:404,MethodNotAllowed:405,NotAcceptable:406,ProxyAuthenticationRequired:407,RequestTimeout:408,Conflict:409,Gone:410,LengthRequired:411,PreconditionFailed:412,PayloadTooLarge:413,UriTooLong:414,UnsupportedMediaType:415,RangeNotSatisfiable:416,ExpectationFailed:417,ImATeapot:418,MisdirectedRequest:421,UnprocessableEntity:422,Locked:423,FailedDependency:424,TooEarly:425,UpgradeRequired:426,PreconditionRequired:428,TooManyRequests:429,RequestHeaderFieldsTooLarge:431,UnavailableForLegalReasons:451,InternalServerError:500,NotImplemented:501,BadGateway:502,ServiceUnavailable:503,GatewayTimeout:504,HttpVersionNotSupported:505,VariantAlsoNegotiates:506,InsufficientStorage:507,LoopDetected:508,NotExtended:510,NetworkAuthenticationRequired:511};Object.entries(bi).forEach(([e,t])=>{bi[t]=e});function sc(e){const t=new sr(e),n=yl(sr.prototype.request,t);return R.extend(n,sr.prototype,t,{allOwnKeys:!0}),R.extend(n,t,null,{allOwnKeys:!0}),n.create=function(o){return sc(or(e,o))},n}const gt=sc(Xr);gt.Axios=sr,gt.CanceledError=Er,gt.CancelToken=Bg,gt.isCancel=zl,gt.VERSION=rc,gt.toFormData=Ro,gt.AxiosError=$e,gt.Cancel=gt.CanceledError,gt.all=function(t){return Promise.all(t)},gt.spread=zg,gt.isAxiosError=Hg,gt.mergeConfig=or,gt.AxiosHeaders=$t,gt.formToJSON=e=>Fl(R.isHTMLForm(e)?new FormData(e):e),gt.getAdapter=tc.getAdapter,gt.HttpStatusCode=bi,gt.default=gt;const{Axios:jk,AxiosError:Rk,CanceledError:Pk,isCancel:Ok,CancelToken:Mk,VERSION:Dk,all:Lk,Cancel:$k,isAxiosError:Fk,spread:Bk,toFormData:zk,AxiosHeaders:Hk,HttpStatusCode:Uk,formToJSON:Wk,getAdapter:Vk,mergeConfig:Kk}=gt,ic=typeof window<"u"?window.__API_BASE_URL__:void 0,ac=ic?On(ic):void 0;function On(e){const n=(e!=null&&e.trim()?e.trim():"/api/chat").replace(/\/+$/,"");return n?n.endsWith("/chat")?n:`${n}/chat`:"/api/chat"}let $o=null;const wi=new Set;function lc(){return $o}function yi(e){$o=e,wi.forEach(t=>t(e))}function cc(e){return wi.add(e),()=>wi.delete(e)}const Kt=gt.create({...ac?{baseURL:ac}:{},timeout:3e4,withCredentials:!0});Kt.interceptors.request.use(e=>($o&&(e.headers.Authorization=`Bearer ${$o}`),e)),Kt.interceptors.response.use(e=>e,e=>Promise.reject(e));async function nn(e,t){return Kt.defaults.baseURL?(await Kt.get(e,t)).data:Promise.reject(new Error("API base URL is not configured"))}async function Si(e,t,n){return Kt.defaults.baseURL?(await Kt.post(e,t,n)).data:Promise.reject(new Error("API base URL is not configured"))}async function uc(e,t,n){return Kt.defaults.baseURL?(await Kt.put(e,t,n)).data:Promise.reject(new Error("API base URL is not configured"))}async function dc(e,t){return Kt.defaults.baseURL?(await Kt.delete(e,t)).data:Promise.reject(new Error("API base URL is not configured"))}function rn(e){return e&&typeof e=="object"&&"data"in e?e.data:e}class fc{get baseUrl(){const t=Kt.defaults.baseURL;return t?On(String(t)):""}updateConfig(t){t.baseUrl&&(Kt.defaults.baseURL=On(String(t.baseUrl))),t.authToken!==void 0&&yi(t.authToken)}getAuthToken(){return lc()}setAuthToken(t){yi(t)}onTokenChange(t){return cc(t)}async listThreads(){const t=await nn("/threads"),n=rn(t);return(n==null?void 0:n.items)??(t==null?void 0:t.items)??[]}async createThread(t){const r=await Si("/threads",t?{title:t}:void 0);return rn(r)}async updateThread(t,n){const r=await uc(`/threads/${t}`,{title:n});return rn(r)}async deleteThread(t){const n=await dc(`/threads/${t}`);return rn(n)}async threadInfo(t){const n=await nn(`/threads/${t}/info`);return rn(n)}async listAgents(){const t=await nn("/agents"),n=rn(t);return(n==null?void 0:n.items)??[]}async getAgent(t){const n=await nn(`/agents/${t}`);return rn(n)}async getAgentSchema(t){const n=await nn(`/agents/${t}/schema`);return rn(n)}async getMessages(t){const n=await nn(`/threads/${t.threadId}/messages`,{params:{thread_id:t.threadId,checkpoint_id:t.checkpointId,checkpoint_ns:t.checkpointNs,limit:t.limit,before_id:t.beforeId??void 0}});return rn(n)}async getStateHistory(t){const n=await nn(`/threads/${t.threadId}/state/history`,{params:{thread_id:t.threadId,checkpoint_id:t.checkpointId,checkpoint_ns:t.checkpointNs}});return rn(n)}resumeStream(t){}async resume(t){const n=await Si("/runs/resume",{thread_id:t.threadId,value:t.value});return rn(n)}}const Bn=new fc,hc=y.createContext(null);function Ug({children:e,apiConfig:t}){const n=Bn;if(t){const o=n.baseUrl,s=n.getAuthToken();t.baseUrl&&t.baseUrl!==o&&n.updateConfig({baseUrl:t.baseUrl}),t.apiKey!==void 0&&t.apiKey!==s&&n.updateConfig({authToken:t.apiKey})}const r={token:n.getAuthToken(),setToken:o=>n.setAuthToken(o),api:n,baseUrl:n.baseUrl};return c.jsx(hc.Provider,{value:r,children:e})}function Ci(){const e=y.useContext(hc);if(!e)throw new Error("useApi must be used within ApiProvider");return e}async function Wg(e){return await new Promise((t,n)=>{const r=new FileReader;r.onload=()=>{try{const o=r.result,s=new Uint8Array(o);let i="";const a=s.byteLength;for(let l=0;l<a;l++)i+=String.fromCharCode(s[l]);t(btoa(i))}catch(o){n(o)}},r.onerror=o=>n(o),r.readAsArrayBuffer(e)})}async function Vg(e,t=[],n,r,o,s){const i=[],a=[];for(const l of t)try{const u=await Wg(l);a.push({filename:l.name,data:u,mime_type:l.type||"application/octet-stream"})}catch{}return{contentParts:i,filesInfo:a}}const Kg={human:"user",user:"user",ai:"assistant",assistant:"assistant",tool:"tool",function:"tool",system:"system"};function ki(e){if(!e||typeof e!="object")return!1;const t=e;return"values"in t&&"config"in t&&typeof t.values=="object"&&t.values!==null&&typeof t.config=="object"&&t.config!==null}function Fo(e,t){return`${e??""}::${t??""}`}function Ti(e){const t=Array.isArray(e==null?void 0:e.checkpoints)?(e==null?void 0:e.checkpoints)??[]:e!=null&&e.checkpoints?Object.values(e.checkpoints):[],n=(e==null?void 0:e.threadId)??"",r=t[0];if(!ki(r))return{payload:{threadId:n,checkpointId:void 0,checkpointNs:void 0,messages:[],hasMore:!1,nextCursor:null,nextCursorNs:null},checkpoints:[],interrupt:null,snapshots:{}};const{summaries:o,snapshots:s}=Gg(t),i=pc(r,0);return{payload:{threadId:n,checkpointId:(i==null?void 0:i.checkpointId)??void 0,checkpointNs:(i==null?void 0:i.checkpointNs)??void 0,messages:(i==null?void 0:i.messages)??[],hasMore:!!(i!=null&&i.nextCursor),nextCursor:(i==null?void 0:i.nextCursor)??null,nextCursorNs:(i==null?void 0:i.nextCursorNs)??null,pendingInterrupt:(i==null?void 0:i.interrupt)??null},checkpoints:o,interrupt:(i==null?void 0:i.interrupt)??null,snapshots:s}}function pc(e,t){var h,p;if(!ki(e))return null;const n=e.values??{},r=Array.isArray(n==null?void 0:n.messages)?n.messages:[],o=e.tasks,s=r.map((b,x)=>Qg(b,x)).filter(b=>!!b),i=Bt((h=e.config)==null?void 0:h.configurable),a=pt(i,["checkpoint_id","checkpointId"]),l=pt(i,["checkpoint_ns","checkpointNs"]),u=Bt((p=e.parentConfig)==null?void 0:p.configurable),d=pt(u,["checkpoint_id","checkpointId"])??null,f=pt(u,["checkpoint_ns","checkpointNs"])??null;return{messages:s,checkpointId:a??null,checkpointNs:l??null,nextCursor:d,nextCursorNs:f,interrupt:qg(o,s,t)}}function qg(e,t,n){const r=Jg(e,n);return r||Xg(t,n)}function Gg(e){const t=new Map,n={};e.forEach((o,s)=>{if(!ki(o))return;const i=pc(o,s);if(!(i!=null&&i.checkpointId))return;const a=o==null?void 0:o.createdAt,l=typeof a=="string"&&a.trim()?a:new Date(Date.now()-s).toISOString(),u=Yg(i.messages),d=i.messages[i.messages.length-1],f=Bt(o==null?void 0:o.metadata),h=pt(f,["branch_label","branchLabel"]),p=Bt(o==null?void 0:o.parentConfig),b=Bt(p==null?void 0:p.configurable),x=pt(b,["checkpoint_id","checkpointId"]),g={checkpointId:i.checkpointId,checkpointNs:i.checkpointNs??"",createdAt:l,messagesLen:i.messages.length,preview:u??null,role:(d==null?void 0:d.role)??null,parentId:x??null,branchLabel:h??null,lastMessageId:(d==null?void 0:d.id)??null,hasMessages:i.messages.length>0},v=Fo(g.checkpointId,g.checkpointNs);t.has(v)||t.set(v,g),n[v]||(n[v]=i)});const r=Array.from(t.values());return r.sort((o,s)=>gc(s.createdAt)-gc(o.createdAt)),{summaries:r,snapshots:n}}function Yg(e){var t;for(let n=e.length-1;n>=0;n--){const r=((t=e[n])==null?void 0:t.content)??[];for(let o=0;o<r.length;o++){const s=r[o];if(s&&s.type==="text"&&typeof s.text=="string"){const i=s.text.trim();if(i)return i}}}return null}function Xg(e,t){var n;for(let r=e.length-1;r>=0;r--){const o=((n=e[r])==null?void 0:n.content)??[];for(let s=o.length-1;s>=0;s--){const i=o[s];if((i==null?void 0:i.type)==="interrupt"){const a=i;return{id:typeof a.id=="string"&&a.id.trim()?a.id:`interrupt-${t}-${r}-${s}`,value:a.value}}}}return null}function Jg(e,t){if(!Array.isArray(e)||!e.length)return null;for(let n=e.length-1;n>=0;n--){const r=Zg(e[n],`task-${t}-${n}`);if(!r)continue;const o=r.id||`task-${t}-${n}`;if(Array.isArray(r.interrupts)&&r.interrupts.length)for(let s=r.interrupts.length-1;s>=0;s--){const i=Zr(r.interrupts[s],`${o}-interrupt-${s}`);if(i)return i}if(r.state!==void 0&&r.state!==null){const s=Zr(r.state,`${o}-state`);if(s)return s}}return null}function Zg(e,t){if(!e)return null;if(Array.isArray(e)){const[a,l,u,,d,,f,...h]=e,p=typeof a=="string"&&a.trim()?a:t,b=typeof l=="string"&&l.trim()?l:Array.isArray(u)&&typeof u[0]=="string"?String(u[0]):"task",x=Array.isArray(d)?d:void 0,g=h.length?h[h.length-1]:void 0;return{id:p,name:b,interrupts:x,state:g!==void 0?g:f}}const n=Bt(e);if(!n)return null;const r=pt(n,["id","task_id","taskId"])??t,o=pt(n,["name"])??"task",s=Array.isArray(n.interrupts)?n.interrupts:void 0,i=Object.prototype.hasOwnProperty.call(n,"state")?n.state:void 0;return{id:r,name:o,interrupts:s,state:i}}function Zr(e,t,n=0,r=new Set){if(n>6||e==null)return null;if(typeof e=="object"){if(r.has(e))return null;r.add(e)}const o=mc(e,t);if(o)return o;if(Array.isArray(e)){for(let s=e.length-1;s>=0;s--){const i=Zr(e[s],t,n+1,r);if(i)return i}return null}if(typeof e=="object"){const s=e,i=["interrupt","pending_interrupt","pendingInterrupt","value","data","payload","result","response"];for(const a of i)if(a in s){const l=Zr(s[a],t,n+1,r);if(l)return l}for(const[a,l]of Object.entries(s)){if(i.includes(a)||a==="messages"||a==="results")continue;const u=Zr(l,t,n+1,r);if(u)return u}}return null}function mc(e,t){if(!e)return null;if(typeof e=="object"&&!Array.isArray(e)){const n=e,r=pt(n,["type","event","kind"]),o=pt(n,["id","interrupt_id","interruptId","value_id"])??(r&&r.toLowerCase().includes("interrupt")?t:void 0);if(!(Object.prototype.hasOwnProperty.call(n,"value")||Object.prototype.hasOwnProperty.call(n,"data")||Object.prototype.hasOwnProperty.call(n,"payload"))&&!(r&&r.toLowerCase().includes("interrupt")))return null;const i=Object.prototype.hasOwnProperty.call(n,"value")?n.value:Object.prototype.hasOwnProperty.call(n,"data")?n.data:Object.prototype.hasOwnProperty.call(n,"payload")?n.payload:n,a=o&&o.trim()?o:t;return a?{id:a,value:i}:null}if(Array.isArray(e)){for(let n=e.length-1;n>=0;n--){const r=mc(e[n],t);if(r)return r}return e.length>=2&&typeof e[0]=="string"&&e[0].trim()?{id:e[0],value:e[1]}:null}if(typeof e=="string"){const n=e.trim();return n?{id:t||n,value:n}:null}return null}function gc(e){if(!e)return 0;const t=Date.parse(e);return Number.isFinite(t)?t:0}function Qg(e,t){if(!e||typeof e!="object")return null;const n=e,r=Bt(e)??{},o=Bt(n.data)??r,s=String(n.type??o.type??o.role??"").toLowerCase(),i=Kg[s];if(!i)return null;const a=o.id??o.message_id??o.run_id??null,l=typeof a=="string"&&a.trim()?a:`history-${i}-${t}`,u=Bt(o.additional_kwargs)??Bt(o.additionalKwargs),d=Bt(o.response_metadata)??Bt(o.responseMetadata),f=pt(u,["createdAt","created_at"])??pt(o,["created_at","createdAt"]),h=pt(u,["checkpointId","checkpoint_id"]),p=pt(u,["checkpointNs","checkpoint_ns"]),b=ex(o.content),x={id:l,role:i,content:b};f&&(x.createdAt=f),typeof o.name=="string"&&o.name.trim()&&(x.name=o.name),typeof(d==null?void 0:d.model_name)=="string"&&(x.model=String(d.model_name)),!x.model&&typeof o.model=="string"&&(x.model=o.model),h&&(x.checkpointId=h),p&&(x.checkpointNs=p);const g=sx(u,["createdAt","created_at","checkpointId","checkpoint_id","checkpointNs","checkpoint_ns","tool_calls"]),v=d?{...d}:void 0;g&&Object.keys(g).length&&(x.additionalKwargs=g),v&&Object.keys(v).length&&(x.responseMetadata=v);const w=tx((u==null?void 0:u.tool_calls)??o.tool_calls);if(w.length&&(x.content=[...x.content,...w]),i==="tool"){const S=rx(o,x.content);S&&(x.content=S)}return x}function ex(e){if(!e)return[];if(Array.isArray(e))return e.map(t=>xc(t)).filter(t=>!!t);if(typeof e=="string")return e.trim()?[{type:"text",text:e.trim()}]:[];if(typeof e=="object"){const t=xc(e);return t?[t]:[]}return[]}function xc(e){if(!e||typeof e!="object")return typeof e=="string"&&e.trim()?{type:"text",text:e}:null;const t=e,n=String(t.type??"").toLowerCase();if(!n||n==="text"){const o=typeof t.text=="string"?t.text:typeof t.value=="string"?t.value:"";return o.trim()?{type:"text",text:o}:null}if(n==="image"||n==="image_url"){const o=pt(t,["url","src"]);if(!o)return null;const s={type:"image_url",url:o};return typeof t.mimeType=="string"&&(s.mimeType=t.mimeType),typeof t.alt=="string"&&(s.alt=t.alt),s}if(n==="file"){const o=pt(t,["url"]);if(!o)return null;const s={type:"file",url:o};return typeof t.mimeType=="string"&&(s.mimeType=t.mimeType),typeof t.name=="string"&&(s.name=t.name),typeof t.size=="number"&&(s.size=t.size),typeof t.sourceType=="string"&&(s.sourceType=t.sourceType),s}if(n==="tool_call")return nx(t)??null;if(n==="tool_end"){const o=pt(t,["tool_call_id","toolCallId","id"]);if(!o)return null;const s={type:"tool_end",toolCallId:o,output:"output"in t?t.output:t.content};return typeof t.error=="string"&&(s.error=t.error),s}if(n==="interrupt")return{type:"interrupt",value:t.value,...t};if(n==="tool"){const o=pt(t,["text","content"]);if(o)return{type:"text",text:o}}const r=typeof t.content=="string"?t.content:typeof t.value=="string"?t.value:JSON.stringify(t);return r?{type:"text",text:r}:null}function tx(e){return Array.isArray(e)?e.map((t,n)=>{if(!t||typeof t!="object")return null;const r=t,o=pt(r,["id","call_id"]),s=Bt(r.function),i=pt(s,["name"])??"tool",a=s==null?void 0:s.arguments,l=vc(a);return{type:"tool_call",id:o??`tool_call_${n}`,name:i,args:l}}).filter(t=>!!t):[]}function nx(e){const t=pt(e,["id","call_id"]),n=pt(e,["name"]);if(!t||!n)return null;const r=vc(e.args??e.arguments);return{type:"tool_call",id:t,name:n,args:r}}function rx(e,t){const n=pt(e,["tool_call_id","toolCallId","id"]);if(!n)return t;const r=e.content??e.output,o=typeof r=="string"?ox(r):r,s={type:"tool_end",toolCallId:n,output:o};return typeof e.error=="string"&&(s.error=e.error),[s]}function vc(e){if(!e)return{};if(typeof e=="string")try{const t=JSON.parse(e);return typeof t=="object"&&t!==null?t:{raw:e}}catch{return{raw:e}}return typeof e=="object"&&!Array.isArray(e)?{...e}:{}}function ox(e){try{return JSON.parse(e)}catch{return e}}function Bt(e){if(!(!e||typeof e!="object"||Array.isArray(e)))return{...e}}function pt(e,t){if(e)for(const n of t){const r=e[n];if(typeof r=="string"&&r.trim())return r}}function sx(e,t){if(!e)return;const n={};let r=!1;for(const[o,s]of Object.entries(e)){if(t.includes(o)){r=!0;continue}s!==void 0&&(n[o]=s)}return r?Object.keys(n).length?n:void 0:e}function ix(e){return e.type!=="thread_info"&&e.type!=="token"}const ax={messages:[],assemblingId:null,lastCheckpointId:null,lastCheckpointNs:null,toolIndex:{},lastBranch:null,messagesStreamMeta:{},pendingInterrupt:null};function lx(e,t){var n;switch(t.type){case"reset":{console.log("[MessageReducer] 🔄 RESET action received"),console.log("[MessageReducer] 📊 Before reset - messages count:",e.messages.length);const r={messages:Ii(((n=t.payload)==null?void 0:n.messages)??[]),assemblingId:null,lastCheckpointId:null,lastCheckpointNs:null,toolIndex:{},lastBranch:null,pendingInterrupt:null};return console.log("[MessageReducer] 📊 After reset - messages count:",r.messages.length),r}case"seed":{const r=Ii(t.payload.messages),o={...e,messages:r,assemblingId:null,pendingInterrupt:t.payload.pendingInterrupt??null};return Object.prototype.hasOwnProperty.call(t.payload,"checkpointId")&&(o.lastCheckpointId=t.payload.checkpointId??null),Object.prototype.hasOwnProperty.call(t.payload,"checkpointNs")&&(o.lastCheckpointNs=t.payload.checkpointNs??null),console.log("[MessageReducer] seed action (REPLACE mode):",{incomingCount:t.payload.messages.length,sanitizedCount:r.length,previousCount:e.messages.length,checkpointId:o.lastCheckpointId}),o}case"prepend":{const r=Ii(t.payload.messages);if(!r.length)return console.log("[MessageReducer] No incoming messages after sanitize - skipping"),e;const o=new Set(e.messages.map(i=>i.id)),s=r.filter(i=>!o.has(i.id));return console.log("[MessageReducer] After dedup:",{uniqueCount:s.length,duplicates:r.length-s.length,finalTotal:s.length+e.messages.length}),s.length?{...e,messages:[...s,...e.messages]}:(console.log("[MessageReducer] All messages were duplicates - skipping"),e)}case"user_message":{const r=t.payload.message;return e.messages.some(o=>o.id===r.id)?e:{...e,messages:[...e.messages,r]}}case"event":return wc(e,t.payload.ev);case"batch":{const{events:r}=t.payload;return r.length?r.reduce((o,s)=>wc(o,s),e):e}case"interrupt_response":{const{interruptId:r}=t.payload,o=e.messages.map(s=>({...s,content:s.content.filter(i=>i.type!=="interrupt")}));return{...e,messages:o,pendingInterrupt:null}}default:return e}}function bc(e=[]){const[t,n]=y.useReducer(lx,{...ax,messages:e}),r=y.useRef([]),o=y.useRef(null),s=y.useRef(null),i=y.useCallback(()=>{o.current!==null&&typeof window<"u"&&window.cancelAnimationFrame(o.current),s.current!==null&&clearTimeout(s.current),o.current=null,s.current=null;const d=r.current;d.length&&(r.current=[],n({type:"batch",payload:{events:d}}))},[]),a=y.useCallback(()=>{typeof window<"u"&&typeof window.requestAnimationFrame=="function"?o.current===null&&(o.current=window.requestAnimationFrame(()=>i())):s.current===null&&(s.current=setTimeout(i,8))},[i]),l=y.useCallback(d=>{r.current.push(d),a()},[a]);y.useEffect(()=>()=>{o.current!==null&&typeof window<"u"&&window.cancelAnimationFrame(o.current),s.current!==null&&clearTimeout(s.current),r.current=[]},[]);const u=y.useMemo(()=>({reset:d=>n({type:"reset",payload:{messages:d}}),seed:(d,f)=>n({type:"seed",payload:{messages:d,...f??{}}}),prepend:d=>n({type:"prepend",payload:{messages:d}}),pushUser:d=>n({type:"user_message",payload:{message:d}}),onEvent:l}),[l]);return{state:t,dispatch:n,...u}}function wc(e,t){var n,r,o,s;if(t.type==="message_start"&&t.role==="assistant"){const i=t.id,a=dx(t.model);if(e.messages.some(d=>d.id===i)){const d=e.messagesStreamMeta??{},f={...d,[i]:d[i]??{lastSeq:t.seq??null,lastText:""}};return{...e,assemblingId:i,messagesStreamMeta:f}}const u={id:i,role:"assistant",name:a||void 0,model:t.model,createdAt:new Date().toISOString(),content:[]};return{...e,assemblingId:i,messages:[...e.messages,u]}}if(t.type==="message_delta"){const i=e.assemblingId??Ei(e.messages);if(!i)return e;const a=e.messages,l=a.findIndex(S=>S.id===i&&S.role==="assistant");if(l===-1)return e;const u=a[l],d=e.messagesStreamMeta??{},f=d[i]??{lastSeq:null,lastText:Tc(u.content)},h=t.seq??null;if(h!==null&&typeof h=="number"&&typeof f.lastSeq=="number"&&h<=f.lastSeq)return console.debug("[MessageReducer] skipping delta - seq <= lastSeq",{seq:h,lastSeq:f.lastSeq}),e;const{newParts:p,newMeta:b,changed:x}=cx(u.content,t.delta,f,h);if(!x)return e;const g={...u,content:p},v=yc(a,l,g),w={...d,[i]:b};return{...e,messages:v,messagesStreamMeta:w}}if(t.type==="message_end"){const i=e.assemblingId??Ei(e.messages);if(!i)return{...e,assemblingId:null};const a=e.messages,l=a.findIndex(u=>u.id===i&&u.role==="assistant");if(l>=0){const u=a[l];if(!((n=u.content)==null?void 0:n.some(f=>{var h;return(f==null?void 0:f.type)==="text"&&((h=f.text)==null?void 0:h.trim())}))){console.debug("[MessageReducer] pruning assistant message with no visible text",{id:u.id,contentTypes:(r=u.content)==null?void 0:r.map(h=>h==null?void 0:h.type),contentPreview:(o=u.content)==null?void 0:o.map(h=>(h==null?void 0:h.type)==="text"?String(h.text).slice(0,100):h==null?void 0:h.type)});const f=[...a.slice(0,l),...a.slice(l+1)];return{...e,assemblingId:null,messages:f}}}return e}if(t.type==="tool_start"){const i=t.id??t.call_id,a=t.name??t.tool??"tool";if(!i)return e;const l=`tool-${i}`,u={type:"tool_call",id:i,name:a,args:t.args};if(e.messages.find(h=>h.id===l))return{...e,toolIndex:{...e.toolIndex,[i]:l}};const f={id:l,role:"tool",name:a,createdAt:new Date().toISOString(),content:[u]};return{...e,messages:[...e.messages,f],toolIndex:{...e.toolIndex,[i]:l}}}if(t.type==="tool_end"){const i=t.id??t.call_id;if(!i)return e;const a=e.toolIndex[i]??`tool-${i}`,l={type:"tool_end",toolCallId:i,output:t.output,error:t.error},u=e.messages.find(h=>h.id===a),d={id:a,role:"tool",name:t.name??((s=e.messages.find(h=>h.id===a))==null?void 0:s.name),content:[l],createdAt:new Date().toISOString()},f=u?Cc(e.messages,a,[l]):[...e.messages,d];return{...e,messages:f,toolIndex:{...e.toolIndex,[i]:a}}}if(t.type==="checkpoint"){const i=t.checkpointNs??e.lastCheckpointNs??null,a=ux(e.messages,t.checkpointId,i);return{...e,lastCheckpointId:t.checkpointId,lastCheckpointNs:i,messages:a}}if(t.type==="branch"){const i=t.checkpointId??e.lastCheckpointId,a=t.checkpointNs??e.lastCheckpointNs;return{...e,lastBranch:t,lastCheckpointId:i??null,lastCheckpointNs:a??null}}if(t.type==="error"){const i={id:`err-${Date.now()}`,role:"system",content:[{type:"text",text:`Error: ${t.message}`}],createdAt:new Date().toISOString()};return{...e,messages:[...e.messages,i]}}if(t.type==="interrupt"){const i=e.assemblingId??Ei(e.messages),a={type:"interrupt",value:t.value,id:t.id};if(i)return{...e,assemblingId:null,messages:Cc(e.messages,i,[a]),pendingInterrupt:{id:t.id,value:t.value}};const l=`interrupt-${t.id}`;if(e.messages.findIndex(f=>f.id===l)!==-1)return{...e,assemblingId:null,messages:Sc(e.messages,l,f=>({...f,content:kc(f.content??[],[a])})),pendingInterrupt:{id:t.id,value:t.value}};const d={id:l,role:"system",createdAt:new Date().toISOString(),content:[a]};return{...e,messages:[...e.messages,d],pendingInterrupt:{id:t.id,value:t.value}}}return e}function Ii(e){return e.filter(t=>{if(t.role!=="assistant")return!0;const n=(t.content||[]).some(o=>{var s;return o&&o.type==="text"&&((s=o.text)==null?void 0:s.trim())}),r=(t.content||[]).some(o=>o&&o.type==="image_url");return!!(n||r)})}function yc(e,t,n){return t<0||t>=e.length?e:[...e.slice(0,t),n,...e.slice(t+1)]}function Ei(e){for(let t=e.length-1;t>=0;t--)if(e[t].role==="assistant")return e[t].id;return null}function Sc(e,t,n){const r=e.findIndex(i=>i.id===t);if(r===-1)return e;const o=e[r],s=n(o);return s===o?e:[...e.slice(0,r),s,...e.slice(r+1)]}function Cc(e,t,n){return Sc(e,t,r=>({...r,content:kc(r.content,n)}))}function kc(e,t){const n=e.slice();for(const r of t)if(r.type==="text"){const o=n[n.length-1],s=r.text??"";if(!s)continue;if((o==null?void 0:o.type)==="text"){let i=function(p){return p.replace(/\s+/g," ").trim()};const a=o,l=a.text??"";if(console.debug("[MessageReducer] mergeParts",{incomingLength:s.length,previousLength:l.length,incomingSnippet:s.slice(0,100),previousSnippet:l.slice(-100)}),!l){a.text=s;continue}const u=i(s),d=i(l);if(u.startsWith(d)||s.startsWith(l)){console.debug("[MessageReducer] incoming startsWith previous (norm/raw) - replacing",{incomingLength:s.length,previousLength:l.length}),a.text=s;continue}if(u.includes(d)){console.debug("[MessageReducer] incoming includes previous (normalized) - replacing",{incomingLength:s.length,previousLength:l.length}),a.text=s;continue}if(d.includes(u)&&u.length<=3){console.debug("[MessageReducer] previous includes incoming (normalized) - skipping trivial incoming",{incomingLength:s.length,previousLength:l.length});continue}const h=Ec(l,s);h?(console.debug("[MessageReducer] suffix computed",{suffixLength:h.length}),a.text=l+h):(console.debug("[MessageReducer] no overlap detected - appending incoming",{incomingLength:s.length}),a.text=l+s)}else n.push({type:"text",text:s})}else n.push(r);return n}function Tc(e){return!e||!e.length?"":e.filter(t=>t.type==="text").map(t=>t.text??"").join("")}function cx(e,t,n,r){const o={...n};if(r!==null&&typeof r=="number"){if(typeof o.lastSeq=="number"&&r<=o.lastSeq)return{newParts:e,newMeta:o,changed:!1};o.lastSeq=r}const s=t.filter(f=>f.type==="text").map(f=>f.text??"").join(""),i=t.filter(f=>f.type!=="text"),a=o.lastText??Tc(e);let l="",u=e.slice();if(s){const f=Ec(a,s);if(f===""?l="":f===s?l=s:l=f,l){const h=u[u.length-1];if((h==null?void 0:h.type)==="text"){const p=h.text??"",b={...h,text:p+l};u=[...u.slice(0,u.length-1),b]}else u=[...u,{type:"text",text:l}];o.lastText=a+l}else o.lastText=a}i.length&&(u=[...u,...i]);const d=!!(l||i.length);return{newParts:u,newMeta:o,changed:d}}function Ic(e){return e.replace(/\s+/g," ").trim()}function Ec(e,t){if(!t)return"";if(!e)return t;if(e===t)return"";const n=Math.min(e.length,t.length);for(let i=n;i>0;i--)if(e.slice(-i)===t.slice(0,i))return t.slice(i);const r=Ic(e),o=Ic(t);if(r===o)return"";const s=Math.min(r.length,o.length);for(let i=s;i>0;i--)if(r.slice(-i)===o.slice(0,i))return t;return t}function ux(e,t,n){for(let r=e.length-1;r>=0;r--)if(e[r].role==="assistant"){const s={...e[r],checkpointId:t,checkpointNs:n??void 0};return yc(e,r,s)}return e}function dx(e){if(!e)return null;const t=e.split("/");return t[t.length-1]||null}function Nc(e={}){const t=y.useMemo(()=>On(e.baseUrl),[e.baseUrl]),n=e.streamPath??"/runs/stream",[r,o]=y.useState(e.token??null),s=y.useRef(e.headers??{}),i=e.credentials??"include",[a,l]=y.useState(!1),[u,d]=y.useState(null),[f,h]=y.useState(""),[p,b]=y.useState(null),[x,g]=y.useState(0),[v,w]=y.useState(!1),S=y.useRef(null),N=y.useRef(!0),k=y.useRef(0),T=y.useCallback(P=>{o(P)},[]),E=y.useCallback(()=>{var P;(P=S.current)==null||P.abort(),S.current=null,l(!1),w(!1),k.current=0,g(0)},[]),A=y.useCallback(()=>{h(""),b(null),d(null)},[]),j=y.useCallback((P,L,$)=>{S.current&&(S.current.abort(),S.current=null),l(!0),d(null),e.autoAppendAssistant!==!1&&h("");const V=new AbortController;return S.current=V,(async()=>{var G,K,W,z,B,ue,D,te;const M=he=>{var we;try{const ye=JSON.parse(JSON.stringify(he));return(we=ye==null?void 0:ye.payload)!=null&&we.files_info&&Array.isArray(ye.payload.files_info)&&(ye.payload.files_info=ye.payload.files_info.map(Se=>({...Se,data:Se!=null&&Se.data?`<base64 ${String(Se.data).length} chars>`:Se==null?void 0:Se.data}))),ye}catch{return he}};try{let he={};try{if(r)he={Authorization:`Bearer ${r}`};else if(typeof window<"u"){const Ve=window.__AUTH_TOKEN__,ut=((G=window.localStorage)==null?void 0:G.getItem("authToken"))||null;let nt=null;try{const vt=(K=window.localStorage)==null?void 0:K.getItem("chat-settings");vt&&(nt=((W=JSON.parse(vt))==null?void 0:W.apiKey)||null)}catch{}const Ke=Ve||ut||nt||null;Ke&&(he={Authorization:`Bearer ${Ke}`})}}catch{}console.debug("[use-chat] POST",t+n,M(P));const we=await fetch(t+n,{method:"POST",headers:{"Content-Type":"application/json",Accept:"text/event-stream",...he,...s.current},body:JSON.stringify(P),signal:V.signal,credentials:i});if(!we.ok||!we.body){const Pe=await we.text().catch(()=>"");throw console.debug("[use-chat] non-OK response",we.status,Pe==null?void 0:Pe.slice(0,500)),new Error(`stream ${we.status}${Pe?": "+Pe:""}`)}w(!0);const ye=we.body.getReader(),Se=new TextDecoder;let q="",O=[];k.current=0,g(0);let X=0,ne=null;const pe=()=>{if(O.length){const Pe=O.join("");O=[],N.current&&h(Ve=>Ve+Pe)}ne=null},se=()=>{typeof window<"u"&&ne==null&&(ne=requestAnimationFrame(pe))};let me=Date.now();const et=setInterval(()=>{var Pe;if(Date.now()-me>6e4){const Ve="Stream idle timeout";d(Ve),V.abort(),(Pe=$==null?void 0:$.onError)==null||Pe.call($,Ve)}},5e3),tt=1024*1024;try{const Pe=we.headers.get("X-Thread-Id")||we.headers.get("x-thread-id"),Ve=we.headers.get("X-Thread-Created")||we.headers.get("x-thread-created"),ut=Pe??null,nt=String(Ve??"").toLowerCase()==="true";for((z=$==null?void 0:$.onOpen)==null||z.call($,{threadId:ut,created:nt});;){const{value:Ke,done:vt}=await ye.read();if(vt)break;q+=Se.decode(Ke,{stream:!0}),q.length>tt&&(q="",console.warn("Stream buffer reset: exceeded 1MB"));let Q;for(;(Q=q.indexOf(`
|
|
36
36
|
|
|
37
37
|
`))>=0;){const ie=q.slice(0,Q);q=q.slice(Q+2);const xe=hx(ie);if(!xe)continue;let Ce;try{Ce=JSON.parse(xe)}catch{console.debug("[use-chat] malformed SSE:",xe.slice(0,200));continue}const ve=fx(Ce)?Ce.data:Ce;me=Date.now();const Oe=ve.seq;if(Oe!==void 0){if(Oe<=X){console.debug("[use-chat] drop duplicate/out-of-order event",{seq:Oe,lastProcessedSeq:X,type:ve.type});continue}X>0&&Oe>X+1&&((B=$==null?void 0:$.onGap)==null||B.call($,{from:X,to:Oe})),X=Oe,k.current=Oe,g(Oe)}if(console.debug("[use-chat] received event",{seq:ve.seq,type:ve.type,preview:(()=>{var at;try{return ve.type==="message_delta"?{deltaTypes:(at=ve.delta)==null?void 0:at.map(Me=>Me.type),textLen:(ve.delta||[]).filter(Me=>Me.type==="text").map(Me=>String(Me.text||"").length)}:ve.content||ve.delta?{hasContent:!0}:{}}catch(Me){return{err:String(Me)}}})()}),L==null||L(ve),ve.type==="token"&&e.autoAppendAssistant!==!1)O.push(ve.content),se();else if(ve.type==="message_delta"){const at=ve.delta.filter(Me=>Me.type==="text").map(Me=>Me.text).join("");at&&e.autoAppendAssistant!==!1&&(O.push(at),se())}else ve.type==="heartbeat"?console.debug("[use-chat] heartbeat received"):(ne!==null&&cancelAnimationFrame(ne),pe(),ve.type==="checkpoint"?b(ve.checkpointId):ve.type==="error"&&d(ve.message))}}pe()}catch(Pe){if(Pe.name!=="AbortError"){const Ve=Pe.message||String(Pe);d(Ve),(ue=$==null?void 0:$.onError)==null||ue.call($,Ve)}}finally{try{await ye.cancel()}catch{}finally{(D=ye.releaseLock)==null||D.call(ye)}ne!==null&&typeof window<"u"&&window.cancelAnimationFrame(ne),clearInterval(et),l(!1),w(!1),S.current=null,k.current=0,g(0)}}catch(he){if(he.name!=="AbortError"){const we=he.message||String(he);d(we),(te=$==null?void 0:$.onError)==null||te.call($,we)}}finally{l(!1),w(!1),S.current=null,k.current=0,g(0)}})(),{close:()=>V.abort()}},[t,n,r,e.autoAppendAssistant]);return y.useEffect(()=>()=>{var P;N.current=!1,(P=S.current)==null||P.abort()},[]),{isStreaming:a,error:u,assistantText:f,lastCheckpointId:p,lastSeq:x,connected:v,stream:j,stop:E,clear:A,setToken:T}}function fx(e){return!!e&&typeof e=="object"&&e.protocolVersion==="v1"&&"data"in e}function hx(e){const t=e.split(/\r?\n/),n=[];for(const r of t)if(r&&!r.startsWith(":")&&r.startsWith("data:")){const o=r.slice(5);n.push(o.startsWith(" ")?o.slice(1):o)}return n.length===0?null:n.join(`
|
|
38
|
-
`)}function px({baseUrl:e,onThreadInfo:t,onMessageEvent:n,onUnhandledEvent:r,onSequenceGap:o}){const s=y.useRef(null),i=y.useCallback(p=>{const b=p.seq??null;if(b!==null){const x=s.current;if(x!==null){if(b<=x)return;b>x+1&&(o==null||o({from:x,to:b}))}s.current=b}if(p.type==="thread_info"){console.log("[useChatStreamingService] 🎯 Received thread_info event:",p),t(p);return}if(ix(p)){n(p);return}r==null||r(p)},[n,o,t,r]),{stream:a,stop:l,isStreaming:u,error:d,setToken:f}=Nc({baseUrl:e,token:null}),h=y.useCallback((p,b)=>{s.current=null,a(p,i,{onOpen:b==null?void 0:b.onOpen,onError:x=>{var g;(g=b==null?void 0:b.onError)==null||g.call(b,x)},onGap:(b==null?void 0:b.onGap)??o})},[i,o,a]);return y.useMemo(()=>({startStream:h,stop:l,isStreaming:u,error:d,setAuthToken:f}),[h,l,u,d,f])}const Ac=y.createContext(null),_c=y.createContext(null),jc=y.createContext(null),mx=y.createContext(!1),gx="cachedThreads",xx="v1",Bo=300,Ni=200,Rc=50;function vx(e,t,n){return`${e}__${t??""}__${n??""}`}function bx(e,t){if(!e&&!t)return!0;if(!e||!t||e.id!==t.id)return!1;try{return JSON.stringify(e.value)===JSON.stringify(t.value)}catch{return e.value===t.value}}function wx(e){var t;for(let n=e.length-1;n>=0;n--){const r=((t=e[n])==null?void 0:t.content)??[];for(let o=r.length-1;o>=0;o--){const s=r[o];if((s==null?void 0:s.type)==="interrupt"){const i=s.id;return{id:(typeof i=="string"?i:null)??`interrupt-${e[n].id??o}`,value:s.value}}}}return null}function Pc(e){if(typeof window<"u"&&"requestIdleCallback"in window)try{window.requestIdleCallback(e,{timeout:1e3});return}catch{}window.setTimeout(e,Bo)}function Nr(){return typeof window<"u"&&typeof window.localStorage<"u"}function Ai(e){if(!Nr())return null;try{return window.localStorage.getItem(e)}catch{return null}}function Oc(e,t){if(Nr())try{window.localStorage.setItem(e,t)}catch{}}function _i(e){if(Nr())try{window.localStorage.removeItem(e)}catch{}}function yx(){const e=Ai(gx);if(!e)return[];try{const t=JSON.parse(e);return Array.isArray(t)?t.filter(n=>{if(!n||typeof n!="object")return!1;const r=n;return typeof r.threadId=="string"&&typeof r.title=="string"}):[]}catch{return[]}}function Sx(e){let t=5381;for(let n=0;n<e.length;n++)t=(t<<5)+t^e.charCodeAt(n);return(t>>>0).toString(36)}function ji(e,t){return`cachedThreads:v1:${e}:${Sx(t||"anon")}`}function Cx(e){const t=Ai(e);if(!t)return[];try{const n=JSON.parse(t);return Array.isArray(n)?n.filter(r=>{if(!r||typeof r!="object")return!1;const o=r;return typeof o.threadId=="string"&&typeof o.title=="string"}):[]}catch{return[]}}function Ri(e,t){try{Oc(e,JSON.stringify(t))}catch{}}function Pi(e){const t=Cx(e);if(t.length>0)return t;const n=yx();if(n.length>0)try{Ri(e,n.slice(0,Ni))}catch{}return n}function zo(e){const t={},n=[];for(const r of e)!r||typeof r.threadId!="string"||t[r.threadId]||(t[r.threadId]=r,n.push(r.threadId));return{byId:t,order:n}}function Oi(e){return e.order.map(t=>e.byId[t]).filter(Boolean)}function kx({children:e,initialThreadId:t=null,autoLoadInitial:n=!0,disableAutoRestore:r=!1,enableFileAgentRouting:o=!1,fileAgentId:s="invoice_reader",onError:i,onThreadChange:a}){const{api:l,baseUrl:u}=Ci(),d=y.useMemo(()=>On(u),[u]),f=y.useMemo(()=>{try{return new URL(u).host}catch{return"unknown"}},[u]),h=y.useMemo(()=>`threadPayload:${xx}:${f}:`,[f]),p=y.useCallback(C=>`${h}${C}`,[h]),b=y.useCallback(C=>{if(!C||typeof C!="object")return null;const _=C;return typeof _.threadId!="string"||!Array.isArray(_.messages)?null:{threadId:_.threadId,messages:_.messages,hasMore:!!_.hasMore,nextCursor:_.nextCursor??null,checkpointId:_.checkpointId??null,checkpointNs:_.checkpointNs??null,nextCursorNs:_.nextCursorNs??null,pendingInterrupt:_.pendingInterrupt??null}},[]),x=y.useCallback(C=>{const _=Ai(p(C));if(!_)return null;try{const F=JSON.parse(_);return b(F)}catch{return null}},[p,b]),g=y.useCallback((C,_=100)=>{const F={...C,messages:Array.isArray(C.messages)?C.messages.slice(-_):[]};try{Oc(p(C.threadId),JSON.stringify(F))}catch{}},[p]),v=y.useCallback(C=>{_i(p(C))},[p]),w=y.useCallback(()=>{if(Nr())try{const C=h;for(let _=0;_<window.localStorage.length;_++){const F=window.localStorage.key(_);F&&F.startsWith(C)&&window.localStorage.removeItem(F)}}catch{}},[h]),[S,N]=y.useState(()=>{var C;return ji(f,(C=l.getAuthToken)==null?void 0:C.call(l))}),[k,T]=y.useState(()=>{var _;const C=Pi(ji(f,(_=l.getAuthToken)==null?void 0:_.call(l)));return zo(C)}),E=y.useMemo(()=>Oi(k),[k]),[A,j]=y.useState(t),[P,L]=y.useState(!1),[$,V]=y.useState(!1),[M,G]=y.useState(null),[K,W]=y.useState(null),[z,B]=y.useState(null),ue=y.useCallback(()=>{const C=Pi(S);y.startTransition(()=>{T(zo(C))})},[S]),[D,te]=y.useState(!1),[he,we]=y.useState(!1),[ye,Se]=y.useState(null),[q,O]=y.useState(void 0),[X,ne]=y.useState(void 0),[pe,se]=y.useState(void 0),{state:me,dispatch:et,seed:tt,prepend:Pe,pushUser:Ve,onEvent:ut,reset:nt}=bc(),Ke=y.useRef(A);y.useEffect(()=>{Ke.current=A},[A]);const vt=y.useRef(!1),Q=y.useRef([]),ie=y.useRef(null),xe=y.useRef(null),Ce=y.useRef(new Map),ve=y.useRef(A),Oe=y.useRef(!1),at=y.useRef(null),Me=y.useRef(new Map),st=y.useRef(new Map),ft=y.useRef(new Map),It=y.useRef(new Map),Nn=y.useCallback(()=>{var de;const C=It.current;if(C.size<=Rc)return;const _=Array.from(C.entries()).sort((J,Z)=>J[1].timestamp-Z[1].timestamp),F=C.size-Rc;for(let J=0;J<F;J++){const Z=(de=_[J])==null?void 0:de[0];Z&&C.delete(Z)}},[]),dn=y.useCallback((C,_,F)=>{if(!C)return;const de=F==="replace"?[]:Me.current.get(C)??[],J=F==="replace"?_:[..._,...de];if(!J.length){F==="replace"&&Me.current.set(C,[]);return}const Z=new Map;for(const We of J){if(!(We!=null&&We.checkpointId))continue;const Le=`${We.checkpointId}::${We.checkpointNs??""}`;Z.has(Le)||Z.set(Le,We)}const ze=Array.from(Z.values()).sort((We,Le)=>{const ge=Number.isFinite(Date.parse(We.createdAt))?Date.parse(We.createdAt):0;return(Number.isFinite(Date.parse(Le.createdAt))?Date.parse(Le.createdAt):0)-ge});Me.current.set(C,ze)},[]),Zt=y.useCallback((C,_,F)=>{if(!C)return;const de=st.current.get(C),J=F==="replace"||!de?new Map:new Map(de);if(_&&typeof _=="object")for(const[Z,ze]of Object.entries(_)){if(!(ze!=null&&ze.checkpointId))continue;const We=Z||Fo(ze.checkpointId,ze.checkpointNs??null);J.set(We,ze)}st.current.set(C,J)},[]),An=y.useCallback((C,_)=>{const{threadId:F,checkpointId:de=null,checkpointNs:J=null}=C,Z=vx(F,de,J);if(_!=null&&_.force)ft.current.delete(Z),It.current.delete(Z);else{if(_!=null&&_.preferCache){const ge=It.current.get(Z);if(ge)return Promise.resolve(ge.payload)}const Le=ft.current.get(Z);if(Le)return Le}const We=l.getStateHistory({threadId:F,checkpointId:de??void 0,checkpointNs:J??void 0}).then(Le=>(It.current.set(Z,{payload:Le,timestamp:Date.now()}),Nn(),Le)).finally(()=>{ft.current.get(Z)===We&&ft.current.delete(Z)});return ft.current.set(Z,We),We},[l,Nn]),_n=y.useCallback((C,_)=>new Promise((F,de)=>{const J=async()=>{vt.current=!0;try{await C(),F()}catch(Z){de(Z)}finally{vt.current=!1;const Z=Q.current.shift();Z&&Z().catch(()=>{})}};vt.current?Q.current.push(J):J().catch(Z=>{de(Z)})}),[]),Qn=y.useRef(E.length),[To,fn]=y.useState(!1),hn=y.useRef(!1);y.useEffect(()=>{Qn.current=E.length},[E.length]),y.useEffect(()=>{const C=me.pendingInterrupt??wx(me.messages);bx(z,C)||B(C??null)},[z,me.messages,me.pendingInterrupt]);const Et=y.useCallback(async()=>{const C=Qn.current>0;C||L(!0);try{const _=await l.listThreads();y.startTransition(()=>{T(F=>{const de=ze=>ze.map(We=>`${We.threadId}:${We.updatedAt??""}:${We.messageCount??""}`).join("|"),J=Oi(F);return de(J)===de(_)||_.length===0&&J.length>0&&!hn.current?F:zo(_)})}),G(null),hn.current||(hn.current=!0,fn(!0))}catch(_){i==null||i(String(_)),console.error("[ChatSessionProvider] Failed to refresh threads:",_),G(String(_))}finally{C||L(!1)}},[l,i]),Ur=y.useRef(!1),yr=y.useRef(null),yt=y.useRef(null),jn=y.useRef(""),Rn=y.useCallback((C,_)=>{if(!Nr())return;yt.current!==null&&(window.clearTimeout(yt.current),yt.current=null);const F=C.map(J=>`${J.threadId}:${J.updatedAt??""}:${J.messageCount??""}`).join("|");if(C.length===0){try{_i(S)}catch{}jn.current="";return}if(F===jn.current)return;const de=()=>{try{const J=C.slice(0,Ni);Ri(S,J),jn.current=F}catch{}finally{yt.current=null}};if(_!=null&&_.immediate){de();return}yt.current=window.setTimeout(()=>{Pc(de)},Bo)},[S]),Sr=y.useCallback(()=>{Rn(E,{immediate:!0})},[Rn,E]),Qt=y.useCallback((C,_,F,de)=>{const J=Array.isArray(C==null?void 0:C.messages)?C.messages:[],Z=F??(C==null?void 0:C.threadId)??Ke.current,ze=Z!=null&&Z===Ke.current,We=(C==null?void 0:C.pendingInterrupt)??null,Le=(de==null?void 0:de.persist)!==!1;if(_==="replace"){if(Le&&Z){const ge={threadId:Z,messages:J.slice(),hasMore:!!(C!=null&&C.hasMore),nextCursor:(C==null?void 0:C.nextCursor)??null,checkpointId:(C==null?void 0:C.checkpointId)??null,checkpointNs:(C==null?void 0:C.checkpointNs)??null,nextCursorNs:(C==null?void 0:C.nextCursorNs)??null,pendingInterrupt:We};Ce.current.set(Z,ge),ve.current=Z}if(!ze)return;tt(J,{checkpointId:(C==null?void 0:C.checkpointId)??null,checkpointNs:(C==null?void 0:C.checkpointNs)??null,pendingInterrupt:We}),B(We??null)}else if(_==="prepend"&&J.length&&Z){const ge=Ce.current.get(Z),Rt=(ge==null?void 0:ge.messages)??[],mn=new Set,en=[...J,...Rt].filter(kr=>{const tr=kr==null?void 0:kr.id;return tr?mn.has(tr)?!1:(mn.add(tr),!0):!0}),er={threadId:Z,messages:en,hasMore:(C==null?void 0:C.hasMore)??(ge==null?void 0:ge.hasMore)??!1,nextCursor:(C==null?void 0:C.nextCursor)??(ge==null?void 0:ge.nextCursor)??null,checkpointId:(ge==null?void 0:ge.checkpointId)??(C==null?void 0:C.checkpointId)??null,checkpointNs:(ge==null?void 0:ge.checkpointNs)??(C==null?void 0:C.checkpointNs)??null,nextCursorNs:(C==null?void 0:C.nextCursorNs)??(ge==null?void 0:ge.nextCursorNs)??null,pendingInterrupt:(ge==null?void 0:ge.pendingInterrupt)??We??null};if(Ce.current.set(Z,er),!ze)return;Pe(J)}else _==="prepend"&&J.length&&Pe(J);ze&&(_==="replace"?(Se((C==null?void 0:C.nextCursor)??null),te(!!(C!=null&&C.hasMore)),O((C==null?void 0:C.checkpointId)??void 0),ne((C==null?void 0:C.checkpointNs)??void 0),se((C==null?void 0:C.nextCursorNs)??void 0)):(Se(ge=>(C==null?void 0:C.nextCursor)??ge??null),te(ge=>(C==null?void 0:C.hasMore)!==void 0?!!(C!=null&&C.hasMore):ge),O(ge=>(C==null?void 0:C.checkpointId)??ge??void 0),ne(ge=>(C==null?void 0:C.checkpointNs)??ge??void 0),se(ge=>(C==null?void 0:C.nextCursorNs)!==void 0?C.nextCursorNs??void 0:ge)))},[Pe,tt,B]),Cr=y.useCallback(C=>{C.threadId!=null&&C.threadId!==Ke.current||(tt(C.messages,{checkpointId:C.checkpointId,checkpointNs:C.checkpointNs,pendingInterrupt:C.pendingInterrupt??null}),B(C.pendingInterrupt??null),Se(C.nextCursor),te(C.hasMore),O(C.checkpointId??void 0),ne(C.checkpointNs??void 0),se(C.nextCursorNs??void 0),ve.current=C.threadId)},[tt,B]),pn=y.useCallback(C=>{if(!C)return;Ce.current.delete(C),v(C),Me.current.delete(C),st.current.delete(C);const _=`${C}__`;for(const F of ft.current.keys())F.startsWith(_)&&ft.current.delete(F);for(const F of It.current.keys())F.startsWith(_)&&It.current.delete(F);ve.current===C&&(ve.current=null)},[v]),oe=y.useCallback(()=>{const C=Ke.current;C&&pn(C),nt([]),te(!1),we(!1),Se(null),O(void 0),ne(void 0),se(void 0)},[pn,nt]),ke=y.useCallback(({from:C,to:_})=>{const F=Ke.current;F&&console.warn(`[ChatSessionProvider] Stream sequence gap detected (${C} -> ${_}) for thread ${F}`)},[]),qe=y.useCallback(C=>{const _=C.threadId;console.log("[ChatSessionProvider] 📥 Handling thread_info event:",{threadId:_,title:C.title,created:C.created,currentThreads:E.length});const F={threadId:_,title:C.title||`Thread ${_.slice(0,8)}`,createdAt:C.createdAt||new Date().toISOString(),updatedAt:C.updatedAt||new Date().toISOString(),messageCount:C.messageCount||0};Ke.current!==_&&(!Ke.current&&me.messages.length<=1&&(xe.current=_),j(_)),y.startTransition(()=>{T(de=>{const J=de.byId[_];return J?J.title===F.title&&J.updatedAt===F.updatedAt&&J.messageCount===F.messageCount?de:{byId:{...de.byId,[_]:F},order:de.order}:{byId:{...de.byId,[_]:F},order:[_,...de.order]}})})},[me.messages.length]),{startStream:it,stop:Mt,isStreaming:I,error:H,setAuthToken:re}=px({baseUrl:d,onThreadInfo:qe,onMessageEvent:ut,onUnhandledEvent:C=>{console.warn(`[ChatSessionProvider] Unhandled stream event: ${C.type}`,C)},onSequenceGap:ke});y.useEffect(()=>{Ur.current=I},[I]),y.useEffect(()=>{if(!Nr())return;yt.current!==null&&(window.clearTimeout(yt.current),yt.current=null);const C=E.map(F=>`${F.threadId}:${F.updatedAt??""}:${F.messageCount??""}`).join("|");if(E.length===0){try{_i(S)}catch{}jn.current="";return}if(C===jn.current)return;const _=()=>{try{const F=E.slice(0,Ni);Ri(S,F),jn.current=C}catch{}finally{yt.current=null}};return yt.current=window.setTimeout(()=>{Pc(_),yt.current=null},Bo),()=>{yt.current!==null&&(window.clearTimeout(yt.current),yt.current=null)}},[E,Rn]),y.useEffect(()=>{var de;const C=l.getAuthToken();re(C);const _=J=>{const Z=ji(f,J);at.current!==Z&&(at.current=Z,Oe.current=!1),N(Z);const ze=Pi(Z);y.startTransition(()=>{T(zo(ze))}),Oe.current||(Oe.current=!0,Et().catch(()=>{}))};_(C);const F=(de=l.onTokenChange)==null?void 0:de.call(l,J=>{re(J),w(),ft.current.clear(),It.current.clear(),_(J)});return()=>{F==null||F()}},[l,f,re,w,Et]);const Ee=y.useCallback(async C=>{var de;const _=`Thread ${(de=crypto.randomUUID)==null?void 0:de.call(crypto)}`,F={threadId:_,title:C||"New Chat",createdAt:new Date().toISOString(),updatedAt:new Date().toISOString(),messageCount:0};T(J=>({byId:{...J.byId,[_]:F},order:[_,...J.order]})),j(_);try{const J=await l.createThread(C),Z=typeof J=="string"?J:J.threadId;return T(ze=>{const We=ze.byId[_];if(!We)return ze;const Le={...ze.byId};delete Le[_],Le[Z]={...We,threadId:Z};const ge=ze.order.map(Rt=>Rt===_?Z:Rt);return{byId:Le,order:ge}}),j(Z),setTimeout(()=>Et(),10),G(null),Z}catch(J){throw T(Z=>{if(!Z.byId[_])return Z;const ze={...Z.byId};delete ze[_];const We=Z.order.filter(Le=>Le!==_);return{byId:ze,order:We}}),j(null),G(String(J)),J}},[l,Et]),Be=y.useCallback(async C=>{try{await l.deleteThread(C);let _=null;T(F=>{if(!F.byId[C])return F;const de={...F.byId};delete de[C];const J=F.order.filter(ze=>ze!==C),Z={byId:de,order:J};return _=Oi(Z),Z}),_&&Rn(_,{immediate:!0}),pn(C),Ke.current===C&&(xe.current=C,j(null),Ke.current=null,ve.current=null,oe()),await Et(),G(null)}catch(_){throw G(String(_)),_}},[l,oe,pn,Et,Rn]),Xe=y.useCallback(async(C,_)=>{try{await l.updateThread(C,_),T(F=>{const de=F.byId[C];return de?{byId:{...F.byId,[C]:{...de,title:_}},order:F.order}:F}),G(null)}catch(F){throw await Et(),G(String(F)),F}},[l,Et]),De=y.useCallback(async(C,_,F,de=!1)=>{await _n(async()=>{if(xe.current===C&&!de){xe.current=null;return}if(ie.current===C&&!de)return;j(Le=>Le===C?Le:C),Ke.current=C;const J=!de&&!_&&!F;let Z=!1;if(J){const Le=Ce.current.get(C);if(Le)Cr(Le),Z=!0;else{const ge=x(C);ge&&(Ce.current.set(C,ge),Cr(ge),Z=!0)}}const ze=de||!Z||!!_||!!F,We=async Le=>{Le&&V(!0),ie.current=C;try{const ge=await An({threadId:C,checkpointId:_,checkpointNs:F},{force:de}),{payload:Rt,checkpoints:mn,snapshots:en}=Ti(ge);Qt(Rt,"replace",C),dn(C,mn,"replace"),Zt(C,en,"replace"),W(null)}catch(ge){throw(!Z||de||Le)&&(i==null||i(String(ge))),W(String(ge)),ge}finally{ie.current=null,Le&&V(!1)}};ze?await We(!0):J&&Z&&We(!1).catch(Le=>{console.warn("[ChatSessionProvider] Background refresh failed:",Le)})},`loadThread-${C}`)},[Cr,Qt,_n,An,i,dn,Zt]),Ue=y.useCallback(async()=>{await _n(async()=>{const C=Ke.current;C&&pn(C),xe.current=null,j(null),Ke.current=null,ve.current=null,oe(),O(void 0),ne(void 0),se(void 0);try{localStorage.removeItem("lastThreadId")}catch(_){console.warn("[ChatSessionProvider] Failed to clear lastThreadId:",_)}},"clearCurrentThread")},[oe,pn,_n]),kt=y.useCallback(async C=>{const _=Me.current.get(C);if(_)return{threadId:C,checkpoints:_.slice()};const F=await An({threadId:C},{preferCache:!0}),{checkpoints:de,snapshots:J}=Ti(F);dn(C,de,"replace"),Zt(C,J,"replace");const Z=Me.current.get(C)??[];return{threadId:C,checkpoints:Z.slice()}},[An,dn,Zt]),ht=y.useCallback(async(C,_)=>{var Z;const F=Ke.current;if(!F)throw new Error("No active thread");const de=Fo(C,_??null),J=(Z=st.current.get(F))==null?void 0:Z.get(de);if(J){await _n(async()=>{Qt({threadId:F,checkpointId:J.checkpointId??void 0,checkpointNs:J.checkpointNs??void 0,messages:J.messages??[],hasMore:!!J.nextCursor,nextCursor:J.nextCursor??null,nextCursorNs:J.nextCursorNs??null,pendingInterrupt:J.interrupt??null},"replace",F,{persist:!1})},`navigateToCheckpoint-${F}-${de}`);return}await De(F,C,_??void 0,!0)},[Qt,_n,De]),mt=y.useCallback(async()=>{if(!Ke.current)throw new Error("No active thread");await De(Ke.current,void 0,void 0,!0)},[De]),Dt=y.useCallback(async()=>{if(!Ke.current)throw new Error("No active thread");if(he||!D)return;const C=ye;if(C){we(!0);try{const _=Ke.current,F=await An({threadId:_,checkpointId:C??q??null,checkpointNs:pe??X??null}),{payload:de,checkpoints:J,snapshots:Z}=Ti(F);Qt(de,"prepend",_??void 0),_&&(dn(_,J,"prepend"),Zt(_,Z,"prepend")),W(null)}catch(_){throw W(String(_)),_}finally{we(!1)}}},[Qt,An,D,q,X,pe,ye,he,dn,Zt]),$n=y.useCallback(C=>{if(!(C!=null&&C.threadId))return;const _={threadId:C.threadId,checkpointId:C.checkpointId??void 0,checkpointNs:C.checkpointNs??void 0,messages:C.messages??[],hasMore:C.hasMore,nextCursor:C.nextCursor??null,nextCursorNs:C.nextCursorNs??null,pendingInterrupt:C.pendingInterrupt??null};if(C.checkpointId){const F=Fo(C.checkpointId,C.checkpointNs??null);Zt(C.threadId,{[F]:{messages:C.messages??[],checkpointId:C.checkpointId??null,checkpointNs:C.checkpointNs??null,nextCursor:C.nextCursor??null,nextCursorNs:C.nextCursorNs??null,interrupt:C.pendingInterrupt??null}},"prepend")}Qt(_,"replace",C.threadId)},[Qt,Zt]),Pn=y.useCallback(async(C,_)=>{var ii;const F=Ke.current,de=(C==null?void 0:C.text)??"",J=(C==null?void 0:C.attachments)??[],Z=J.length?J:(_==null?void 0:_.attachments)??[],ze={...(_==null?void 0:_.payloadExtras)??{},...(C==null?void 0:C.payload)??{}};if(!F&&!Object.keys(ze).length&&Z.length===0&&!de.trim()){console.warn("[ChatSessionProvider] Nothing to submit - skipping");return}!F&&!ze.messages&&console.warn("[ChatSessionProvider] No thread ID - message will create new thread");const{contentParts:We,filesInfo:Le}=await Vg(l,Z),ge=[...We];de&&de.trim()&&ge.push({type:"text",text:de.trim()});const Rt=!!F,mn=Rt?(_==null?void 0:_.checkpointId)??me.lastCheckpointId??void 0:void 0,en=Rt?(_==null?void 0:_.checkpointNs)??me.lastCheckpointNs??void 0:void 0,er={id:((ii=crypto.randomUUID)==null?void 0:ii.call(crypto))||`user-${Date.now()}`,role:"user",content:ge,createdAt:new Date().toISOString(),...mn!=null?{checkpointId:mn}:{},...en!=null?{checkpointNs:en}:{}};ge.length>0&&Ve(er);const kr={...er,content:ge},tr=Z.length>0,si={...F?{threadId:F}:{},payload:{messages:ge.length>0?[kr]:[],files_info:Le,...o&&tr&&s?{active_agent:s}:{},...ze},...mn!=null?{checkpointId:mn}:{},...en!=null?{checkpointNs:en}:{},nodeFilter:_==null?void 0:_.nodeFilter,config:_==null?void 0:_.config};it(si,{onError:Fn=>{console.warn("[ChatSessionProvider] Stream error:",Fn)},onOpen:({threadId:Fn})=>{!Ke.current&&Fn&&(me.messages.length<=1&&(xe.current=Fn),j(Fn))},onGap:ke})},[l,o,s,ke,me.lastCheckpointId,me.lastCheckpointNs,me.messages.length,Ve,it]),St=y.useCallback(async(C,_,F)=>{var J,Z;const de=Ke.current;if(!de)throw new Error("No active thread to handle interrupt");try{const ze=_?F??!0:!1;try{et({type:"interrupt_response",payload:{interruptId:C}})}catch(er){console.warn("[ChatSessionProvider] optimistic interrupt_response dispatch failed:",er)}const We=`${d}/runs/resume`,Le=(J=l.getAuthToken)==null?void 0:J.call(l),ge=await fetch(We,{method:"POST",headers:{"Content-Type":"application/json",...Le?{Authorization:`Bearer ${Le}`}:{}},body:JSON.stringify({thread_id:de,value:ze})});if(!ge.ok)throw new Error(`Resume failed with status ${ge.status}`);const Rt=(Z=ge.body)==null?void 0:Z.getReader();if(!Rt)throw new Error("No response body for resume stream");const mn=new TextDecoder;let en="";for(;;){const{done:er,value:kr}=await Rt.read();if(er)break;en+=mn.decode(kr,{stream:!0});const tr=en.split(`
|
|
38
|
+
`)}function px({baseUrl:e,onThreadInfo:t,onMessageEvent:n,onUnhandledEvent:r,onSequenceGap:o}){const s=y.useRef(null),i=y.useCallback(p=>{const b=p.seq??null;if(b!==null){const x=s.current;if(x!==null){if(b<=x)return;b>x+1&&(o==null||o({from:x,to:b}))}s.current=b}if(p.type==="thread_info"){console.log("[useChatStreamingService] 🎯 Received thread_info event:",p),t(p);return}if(ix(p)){n(p);return}r==null||r(p)},[n,o,t,r]),{stream:a,stop:l,isStreaming:u,error:d,setToken:f}=Nc({baseUrl:e,token:null}),h=y.useCallback((p,b)=>{s.current=null,a(p,i,{onOpen:b==null?void 0:b.onOpen,onError:x=>{var g;(g=b==null?void 0:b.onError)==null||g.call(b,x)},onGap:(b==null?void 0:b.onGap)??o})},[i,o,a]);return y.useMemo(()=>({startStream:h,stop:l,isStreaming:u,error:d,setAuthToken:f}),[h,l,u,d,f])}const Ac=y.createContext(null),_c=y.createContext(null),jc=y.createContext(null),mx=y.createContext(!1),gx="cachedThreads",xx="v1",Bo=300,Ni=200,Rc=50;function vx(e,t,n){return`${e}__${t??""}__${n??""}`}function bx(e,t){if(!e&&!t)return!0;if(!e||!t||e.id!==t.id)return!1;try{return JSON.stringify(e.value)===JSON.stringify(t.value)}catch{return e.value===t.value}}function wx(e){var t;for(let n=e.length-1;n>=0;n--){const r=((t=e[n])==null?void 0:t.content)??[];for(let o=r.length-1;o>=0;o--){const s=r[o];if((s==null?void 0:s.type)==="interrupt"){const i=s.id;return{id:(typeof i=="string"?i:null)??`interrupt-${e[n].id??o}`,value:s.value}}}}return null}function Pc(e){if(typeof window<"u"&&"requestIdleCallback"in window)try{window.requestIdleCallback(e,{timeout:1e3});return}catch{}window.setTimeout(e,Bo)}function Nr(){return typeof window<"u"&&typeof window.localStorage<"u"}function Ai(e){if(!Nr())return null;try{return window.localStorage.getItem(e)}catch{return null}}function Oc(e,t){if(Nr())try{window.localStorage.setItem(e,t)}catch{}}function _i(e){if(Nr())try{window.localStorage.removeItem(e)}catch{}}function yx(){const e=Ai(gx);if(!e)return[];try{const t=JSON.parse(e);return Array.isArray(t)?t.filter(n=>{if(!n||typeof n!="object")return!1;const r=n;return typeof r.threadId=="string"&&typeof r.title=="string"}):[]}catch{return[]}}function Sx(e){let t=5381;for(let n=0;n<e.length;n++)t=(t<<5)+t^e.charCodeAt(n);return(t>>>0).toString(36)}function ji(e,t){return`cachedThreads:v1:${e}:${Sx(t||"anon")}`}function Cx(e){const t=Ai(e);if(!t)return[];try{const n=JSON.parse(t);return Array.isArray(n)?n.filter(r=>{if(!r||typeof r!="object")return!1;const o=r;return typeof o.threadId=="string"&&typeof o.title=="string"}):[]}catch{return[]}}function Ri(e,t){try{Oc(e,JSON.stringify(t))}catch{}}function Pi(e){const t=Cx(e);if(t.length>0)return t;const n=yx();if(n.length>0)try{Ri(e,n.slice(0,Ni))}catch{}return n}function zo(e){const t={},n=[];for(const r of e)!r||typeof r.threadId!="string"||t[r.threadId]||(t[r.threadId]=r,n.push(r.threadId));return{byId:t,order:n}}function Oi(e){return e.order.map(t=>e.byId[t]).filter(Boolean)}function kx({children:e,initialThreadId:t=null,autoLoadInitial:n=!0,disableAutoRestore:r=!1,enableFileAgentRouting:o=!1,fileAgentId:s="invoice_reader",onError:i,onThreadChange:a}){const{api:l,baseUrl:u}=Ci(),d=y.useMemo(()=>On(u),[u]),f=y.useMemo(()=>{try{return new URL(u).host}catch{return"unknown"}},[u]),h=y.useMemo(()=>`threadPayload:${xx}:${f}:`,[f]),p=y.useCallback(C=>`${h}${C}`,[h]),b=y.useCallback(C=>{if(!C||typeof C!="object")return null;const _=C;return typeof _.threadId!="string"||!Array.isArray(_.messages)?null:{threadId:_.threadId,messages:_.messages,hasMore:!!_.hasMore,nextCursor:_.nextCursor??null,checkpointId:_.checkpointId??null,checkpointNs:_.checkpointNs??null,nextCursorNs:_.nextCursorNs??null,pendingInterrupt:_.pendingInterrupt??null}},[]),x=y.useCallback(C=>{const _=Ai(p(C));if(!_)return null;try{const F=JSON.parse(_);return b(F)}catch{return null}},[p,b]),g=y.useCallback((C,_=100)=>{const F={...C,messages:Array.isArray(C.messages)?C.messages.slice(-_):[]};try{Oc(p(C.threadId),JSON.stringify(F))}catch{}},[p]),v=y.useCallback(C=>{_i(p(C))},[p]),w=y.useCallback(()=>{if(Nr())try{const C=h;for(let _=0;_<window.localStorage.length;_++){const F=window.localStorage.key(_);F&&F.startsWith(C)&&window.localStorage.removeItem(F)}}catch{}},[h]),[S,N]=y.useState(()=>{var C;return ji(f,(C=l.getAuthToken)==null?void 0:C.call(l))}),[k,T]=y.useState(()=>{var _;const C=Pi(ji(f,(_=l.getAuthToken)==null?void 0:_.call(l)));return zo(C)}),E=y.useMemo(()=>Oi(k),[k]),[A,j]=y.useState(t),[P,L]=y.useState(!1),[$,V]=y.useState(!1),[M,G]=y.useState(null),[K,W]=y.useState(null),[z,B]=y.useState(null),ue=y.useCallback(()=>{const C=Pi(S);y.startTransition(()=>{T(zo(C))})},[S]),[D,te]=y.useState(!1),[he,we]=y.useState(!1),[ye,Se]=y.useState(null),[q,O]=y.useState(void 0),[X,ne]=y.useState(void 0),[pe,se]=y.useState(void 0),{state:me,dispatch:et,seed:tt,prepend:Pe,pushUser:Ve,onEvent:ut,reset:nt}=bc(),Ke=y.useRef(A);y.useEffect(()=>{Ke.current=A},[A]);const vt=y.useRef(!1),Q=y.useRef([]),ie=y.useRef(null),xe=y.useRef(null),Ce=y.useRef(new Map),ve=y.useRef(A),Oe=y.useRef(!1),at=y.useRef(null),Me=y.useRef(new Map),st=y.useRef(new Map),ft=y.useRef(new Map),It=y.useRef(new Map),Nn=y.useCallback(()=>{var de;const C=It.current;if(C.size<=Rc)return;const _=Array.from(C.entries()).sort((J,Z)=>J[1].timestamp-Z[1].timestamp),F=C.size-Rc;for(let J=0;J<F;J++){const Z=(de=_[J])==null?void 0:de[0];Z&&C.delete(Z)}},[]),dn=y.useCallback((C,_,F)=>{if(!C)return;const de=F==="replace"?[]:Me.current.get(C)??[],J=F==="replace"?_:[..._,...de];if(!J.length){F==="replace"&&Me.current.set(C,[]);return}const Z=new Map;for(const We of J){if(!(We!=null&&We.checkpointId))continue;const Le=`${We.checkpointId}::${We.checkpointNs??""}`;Z.has(Le)||Z.set(Le,We)}const ze=Array.from(Z.values()).sort((We,Le)=>{const ge=Number.isFinite(Date.parse(We.createdAt))?Date.parse(We.createdAt):0;return(Number.isFinite(Date.parse(Le.createdAt))?Date.parse(Le.createdAt):0)-ge});Me.current.set(C,ze)},[]),Zt=y.useCallback((C,_,F)=>{if(!C)return;const de=st.current.get(C),J=F==="replace"||!de?new Map:new Map(de);if(_&&typeof _=="object")for(const[Z,ze]of Object.entries(_)){if(!(ze!=null&&ze.checkpointId))continue;const We=Z||Fo(ze.checkpointId,ze.checkpointNs??null);J.set(We,ze)}st.current.set(C,J)},[]),An=y.useCallback((C,_)=>{const{threadId:F,checkpointId:de=null,checkpointNs:J=null}=C,Z=vx(F,de,J);if(_!=null&&_.force)ft.current.delete(Z),It.current.delete(Z);else{if(_!=null&&_.preferCache){const ge=It.current.get(Z);if(ge)return Promise.resolve(ge.payload)}const Le=ft.current.get(Z);if(Le)return Le}const We=l.getStateHistory({threadId:F,checkpointId:de??void 0,checkpointNs:J??void 0}).then(Le=>(It.current.set(Z,{payload:Le,timestamp:Date.now()}),Nn(),Le)).finally(()=>{ft.current.get(Z)===We&&ft.current.delete(Z)});return ft.current.set(Z,We),We},[l,Nn]),_n=y.useCallback((C,_)=>new Promise((F,de)=>{const J=async()=>{vt.current=!0;try{await C(),F()}catch(Z){de(Z)}finally{vt.current=!1;const Z=Q.current.shift();Z&&Z().catch(()=>{})}};vt.current?Q.current.push(J):J().catch(Z=>{de(Z)})}),[]),Qn=y.useRef(E.length),[To,fn]=y.useState(!1),hn=y.useRef(!1);y.useEffect(()=>{Qn.current=E.length},[E.length]),y.useEffect(()=>{const C=me.pendingInterrupt??wx(me.messages);bx(z,C)||B(C??null)},[z,me.messages,me.pendingInterrupt]);const Et=y.useCallback(async()=>{const C=Qn.current>0;C||L(!0);try{const _=await l.listThreads();y.startTransition(()=>{T(F=>{const de=ze=>ze.map(We=>`${We.threadId}:${We.updatedAt??""}:${We.messageCount??""}`).join("|"),J=Oi(F);return de(J)===de(_)||_.length===0&&J.length>0&&!hn.current?F:zo(_)})}),G(null),hn.current||(hn.current=!0,fn(!0))}catch(_){i==null||i(String(_)),console.error("[ChatSessionProvider] Failed to refresh threads:",_),G(String(_))}finally{C||L(!1)}},[l,i]),Ur=y.useRef(!1),yr=y.useRef(null),yt=y.useRef(null),jn=y.useRef(""),Rn=y.useCallback((C,_)=>{if(!Nr())return;yt.current!==null&&(window.clearTimeout(yt.current),yt.current=null);const F=C.map(J=>`${J.threadId}:${J.updatedAt??""}:${J.messageCount??""}`).join("|");if(C.length===0){try{_i(S)}catch{}jn.current="";return}if(F===jn.current)return;const de=()=>{try{const J=C.slice(0,Ni);Ri(S,J),jn.current=F}catch{}finally{yt.current=null}};if(_!=null&&_.immediate){de();return}yt.current=window.setTimeout(()=>{Pc(de)},Bo)},[S]),Sr=y.useCallback(()=>{Rn(E,{immediate:!0})},[Rn,E]),Qt=y.useCallback((C,_,F,de)=>{const J=Array.isArray(C==null?void 0:C.messages)?C.messages:[],Z=F??(C==null?void 0:C.threadId)??Ke.current,ze=Z!=null&&Z===Ke.current,We=(C==null?void 0:C.pendingInterrupt)??null,Le=(de==null?void 0:de.persist)!==!1;if(_==="replace"){if(Le&&Z){const ge={threadId:Z,messages:J.slice(),hasMore:!!(C!=null&&C.hasMore),nextCursor:(C==null?void 0:C.nextCursor)??null,checkpointId:(C==null?void 0:C.checkpointId)??null,checkpointNs:(C==null?void 0:C.checkpointNs)??null,nextCursorNs:(C==null?void 0:C.nextCursorNs)??null,pendingInterrupt:We};Ce.current.set(Z,ge),ve.current=Z}if(!ze)return;tt(J,{checkpointId:(C==null?void 0:C.checkpointId)??null,checkpointNs:(C==null?void 0:C.checkpointNs)??null,pendingInterrupt:We}),B(We??null)}else if(_==="prepend"&&J.length&&Z){const ge=Ce.current.get(Z),Rt=(ge==null?void 0:ge.messages)??[],mn=new Set,en=[...J,...Rt].filter(kr=>{const tr=kr==null?void 0:kr.id;return tr?mn.has(tr)?!1:(mn.add(tr),!0):!0}),er={threadId:Z,messages:en,hasMore:(C==null?void 0:C.hasMore)??(ge==null?void 0:ge.hasMore)??!1,nextCursor:(C==null?void 0:C.nextCursor)??(ge==null?void 0:ge.nextCursor)??null,checkpointId:(ge==null?void 0:ge.checkpointId)??(C==null?void 0:C.checkpointId)??null,checkpointNs:(ge==null?void 0:ge.checkpointNs)??(C==null?void 0:C.checkpointNs)??null,nextCursorNs:(C==null?void 0:C.nextCursorNs)??(ge==null?void 0:ge.nextCursorNs)??null,pendingInterrupt:(ge==null?void 0:ge.pendingInterrupt)??We??null};if(Ce.current.set(Z,er),!ze)return;Pe(J)}else _==="prepend"&&J.length&&Pe(J);ze&&(_==="replace"?(Se((C==null?void 0:C.nextCursor)??null),te(!!(C!=null&&C.hasMore)),O((C==null?void 0:C.checkpointId)??void 0),ne((C==null?void 0:C.checkpointNs)??void 0),se((C==null?void 0:C.nextCursorNs)??void 0)):(Se(ge=>(C==null?void 0:C.nextCursor)??ge??null),te(ge=>(C==null?void 0:C.hasMore)!==void 0?!!(C!=null&&C.hasMore):ge),O(ge=>(C==null?void 0:C.checkpointId)??ge??void 0),ne(ge=>(C==null?void 0:C.checkpointNs)??ge??void 0),se(ge=>(C==null?void 0:C.nextCursorNs)!==void 0?C.nextCursorNs??void 0:ge)))},[Pe,tt,B]),Cr=y.useCallback(C=>{C.threadId!=null&&C.threadId!==Ke.current||(tt(C.messages,{checkpointId:C.checkpointId,checkpointNs:C.checkpointNs,pendingInterrupt:C.pendingInterrupt??null}),B(C.pendingInterrupt??null),Se(C.nextCursor),te(C.hasMore),O(C.checkpointId??void 0),ne(C.checkpointNs??void 0),se(C.nextCursorNs??void 0),ve.current=C.threadId)},[tt,B]),pn=y.useCallback(C=>{if(!C)return;Ce.current.delete(C),v(C),Me.current.delete(C),st.current.delete(C);const _=`${C}__`;for(const F of ft.current.keys())F.startsWith(_)&&ft.current.delete(F);for(const F of It.current.keys())F.startsWith(_)&&It.current.delete(F);ve.current===C&&(ve.current=null)},[v]),oe=y.useCallback(()=>{const C=Ke.current;C&&pn(C),nt([]),te(!1),we(!1),Se(null),O(void 0),ne(void 0),se(void 0)},[pn,nt]),ke=y.useCallback(({from:C,to:_})=>{const F=Ke.current;F&&console.warn(`[ChatSessionProvider] Stream sequence gap detected (${C} -> ${_}) for thread ${F}`)},[]),qe=y.useCallback(C=>{const _=C.threadId;console.log("[ChatSessionProvider] 📥 Handling thread_info event:",{threadId:_,title:C.title,created:C.created,currentThreads:E.length});const F={threadId:_,title:C.title||`Thread ${_.slice(0,8)}`,createdAt:C.createdAt||new Date().toISOString(),updatedAt:C.updatedAt||new Date().toISOString(),messageCount:C.messageCount||0};Ke.current!==_&&(!Ke.current&&me.messages.length<=1&&(xe.current=_),j(_)),y.startTransition(()=>{T(de=>{const J=de.byId[_];return J?J.title===F.title&&J.updatedAt===F.updatedAt&&J.messageCount===F.messageCount?de:{byId:{...de.byId,[_]:F},order:de.order}:{byId:{...de.byId,[_]:F},order:[_,...de.order]}})})},[me.messages.length]),{startStream:it,stop:Mt,isStreaming:I,error:H,setAuthToken:re}=px({baseUrl:d,onThreadInfo:qe,onMessageEvent:ut,onUnhandledEvent:C=>{console.warn(`[ChatSessionProvider] Unhandled stream event: ${C.type}`,C)},onSequenceGap:ke});y.useEffect(()=>{Ur.current=I},[I]),y.useEffect(()=>{if(!Nr())return;yt.current!==null&&(window.clearTimeout(yt.current),yt.current=null);const C=E.map(F=>`${F.threadId}:${F.updatedAt??""}:${F.messageCount??""}`).join("|");if(E.length===0){try{_i(S)}catch{}jn.current="";return}if(C===jn.current)return;const _=()=>{try{const F=E.slice(0,Ni);Ri(S,F),jn.current=C}catch{}finally{yt.current=null}};return yt.current=window.setTimeout(()=>{Pc(_),yt.current=null},Bo),()=>{yt.current!==null&&(window.clearTimeout(yt.current),yt.current=null)}},[E,Rn]),y.useEffect(()=>{var de;const C=l.getAuthToken();re(C);const _=J=>{const Z=ji(f,J);at.current!==Z&&(at.current=Z,Oe.current=!1),N(Z);const ze=Pi(Z);y.startTransition(()=>{T(zo(ze))}),Oe.current||(Oe.current=!0,Et().catch(()=>{}))};_(C);const F=(de=l.onTokenChange)==null?void 0:de.call(l,J=>{re(J),w(),ft.current.clear(),It.current.clear(),_(J)});return()=>{F==null||F()}},[l,f,re,w,Et]);const Ee=y.useCallback(async C=>{var de;const _=`Thread ${(de=crypto.randomUUID)==null?void 0:de.call(crypto)}`,F={threadId:_,title:C||"New Chat",createdAt:new Date().toISOString(),updatedAt:new Date().toISOString(),messageCount:0};T(J=>({byId:{...J.byId,[_]:F},order:[_,...J.order]})),j(_);try{const J=await l.createThread(C),Z=typeof J=="string"?J:J.threadId;return T(ze=>{const We=ze.byId[_];if(!We)return ze;const Le={...ze.byId};delete Le[_],Le[Z]={...We,threadId:Z};const ge=ze.order.map(Rt=>Rt===_?Z:Rt);return{byId:Le,order:ge}}),j(Z),setTimeout(()=>Et(),10),G(null),Z}catch(J){throw T(Z=>{if(!Z.byId[_])return Z;const ze={...Z.byId};delete ze[_];const We=Z.order.filter(Le=>Le!==_);return{byId:ze,order:We}}),j(null),G(String(J)),J}},[l,Et]),Be=y.useCallback(async C=>{try{await l.deleteThread(C);let _=null;T(F=>{if(!F.byId[C])return F;const de={...F.byId};delete de[C];const J=F.order.filter(ze=>ze!==C),Z={byId:de,order:J};return _=Oi(Z),Z}),_&&Rn(_,{immediate:!0}),pn(C),Ke.current===C&&(xe.current=C,j(null),Ke.current=null,ve.current=null,oe()),await Et(),G(null)}catch(_){throw G(String(_)),_}},[l,oe,pn,Et,Rn]),Xe=y.useCallback(async(C,_)=>{try{await l.updateThread(C,_),T(F=>{const de=F.byId[C];return de?{byId:{...F.byId,[C]:{...de,title:_}},order:F.order}:F}),G(null)}catch(F){throw await Et(),G(String(F)),F}},[l,Et]),De=y.useCallback(async(C,_,F,de=!1)=>{await _n(async()=>{if(xe.current===C&&!de){xe.current=null;return}if(ie.current===C&&!de)return;j(Le=>Le===C?Le:C),Ke.current=C;const J=!de&&!_&&!F;let Z=!1;if(J){const Le=Ce.current.get(C);if(Le)Cr(Le),Z=!0;else{const ge=x(C);ge&&(Ce.current.set(C,ge),Cr(ge),Z=!0)}}const ze=de||!Z||!!_||!!F,We=async Le=>{Le&&V(!0),ie.current=C;try{const ge=await An({threadId:C,checkpointId:_,checkpointNs:F},{force:de}),{payload:Rt,checkpoints:mn,snapshots:en}=Ti(ge);Qt(Rt,"replace",C),dn(C,mn,"replace"),Zt(C,en,"replace"),W(null)}catch(ge){throw(!Z||de||Le)&&(i==null||i(String(ge))),W(String(ge)),ge}finally{ie.current=null,Le&&V(!1)}};ze?await We(!0):J&&Z&&We(!1).catch(Le=>{console.warn("[ChatSessionProvider] Background refresh failed:",Le)})},`loadThread-${C}`)},[Cr,Qt,_n,An,i,dn,Zt]),Ue=y.useCallback(async()=>{await _n(async()=>{const C=Ke.current;C&&pn(C),xe.current=null,j(null),Ke.current=null,ve.current=null,oe(),O(void 0),ne(void 0),se(void 0);try{localStorage.removeItem("lastThreadId")}catch(_){console.warn("[ChatSessionProvider] Failed to clear lastThreadId:",_)}},"clearCurrentThread")},[oe,pn,_n]),kt=y.useCallback(async C=>{const _=Me.current.get(C);if(_)return{threadId:C,checkpoints:_.slice()};const F=await An({threadId:C},{preferCache:!0}),{checkpoints:de,snapshots:J}=Ti(F);dn(C,de,"replace"),Zt(C,J,"replace");const Z=Me.current.get(C)??[];return{threadId:C,checkpoints:Z.slice()}},[An,dn,Zt]),ht=y.useCallback(async(C,_)=>{var Z;const F=Ke.current;if(!F)throw new Error("No active thread");const de=Fo(C,_??null),J=(Z=st.current.get(F))==null?void 0:Z.get(de);if(J){await _n(async()=>{Qt({threadId:F,checkpointId:J.checkpointId??void 0,checkpointNs:J.checkpointNs??void 0,messages:J.messages??[],hasMore:!!J.nextCursor,nextCursor:J.nextCursor??null,nextCursorNs:J.nextCursorNs??null,pendingInterrupt:J.interrupt??null},"replace",F,{persist:!1})},`navigateToCheckpoint-${F}-${de}`);return}await De(F,C,_??void 0,!0)},[Qt,_n,De]),mt=y.useCallback(async()=>{if(!Ke.current)throw new Error("No active thread");await De(Ke.current,void 0,void 0,!0)},[De]),Dt=y.useCallback(async()=>{if(!Ke.current)throw new Error("No active thread");if(he||!D)return;const C=ye;if(C){we(!0);try{const _=Ke.current,F=await An({threadId:_,checkpointId:C??q??null,checkpointNs:pe??X??null}),{payload:de,checkpoints:J,snapshots:Z}=Ti(F);Qt(de,"prepend",_??void 0),_&&(dn(_,J,"prepend"),Zt(_,Z,"prepend")),W(null)}catch(_){throw W(String(_)),_}finally{we(!1)}}},[Qt,An,D,q,X,pe,ye,he,dn,Zt]),$n=y.useCallback(C=>{if(!(C!=null&&C.threadId))return;const _={threadId:C.threadId,checkpointId:C.checkpointId??void 0,checkpointNs:C.checkpointNs??void 0,messages:C.messages??[],hasMore:C.hasMore,nextCursor:C.nextCursor??null,nextCursorNs:C.nextCursorNs??null,pendingInterrupt:C.interrupt??null};if(C.checkpointId){const F=Fo(C.checkpointId,C.checkpointNs??null);Zt(C.threadId,{[F]:{messages:C.messages??[],checkpointId:C.checkpointId??null,checkpointNs:C.checkpointNs??null,nextCursor:C.nextCursor??null,nextCursorNs:C.nextCursorNs??null,interrupt:C.interrupt??null}},"prepend")}Qt(_,"replace",C.threadId)},[Qt,Zt]),Pn=y.useCallback(async(C,_)=>{var ii;const F=Ke.current,de=(C==null?void 0:C.text)??"",J=(C==null?void 0:C.attachments)??[],Z=J.length?J:(_==null?void 0:_.attachments)??[],ze={...(_==null?void 0:_.payloadExtras)??{},...(C==null?void 0:C.payload)??{}};if(!F&&!Object.keys(ze).length&&Z.length===0&&!de.trim()){console.warn("[ChatSessionProvider] Nothing to submit - skipping");return}!F&&!ze.messages&&console.warn("[ChatSessionProvider] No thread ID - message will create new thread");const{contentParts:We,filesInfo:Le}=await Vg(l,Z),ge=[...We];de&&de.trim()&&ge.push({type:"text",text:de.trim()});const Rt=!!F,mn=Rt?(_==null?void 0:_.checkpointId)??me.lastCheckpointId??void 0:void 0,en=Rt?(_==null?void 0:_.checkpointNs)??me.lastCheckpointNs??void 0:void 0,er={id:((ii=crypto.randomUUID)==null?void 0:ii.call(crypto))||`user-${Date.now()}`,role:"user",content:ge,createdAt:new Date().toISOString(),...mn!=null?{checkpointId:mn}:{},...en!=null?{checkpointNs:en}:{}};ge.length>0&&Ve(er);const kr={...er,content:ge},tr=Z.length>0,si={...F?{threadId:F}:{},payload:{messages:ge.length>0?[kr]:[],files_info:Le,...o&&tr&&s?{active_agent:s}:{},...ze},...mn!=null?{checkpointId:mn}:{},...en!=null?{checkpointNs:en}:{},nodeFilter:_==null?void 0:_.nodeFilter,config:_==null?void 0:_.config};it(si,{onError:Fn=>{console.warn("[ChatSessionProvider] Stream error:",Fn)},onOpen:({threadId:Fn})=>{!Ke.current&&Fn&&(me.messages.length<=1&&(xe.current=Fn),j(Fn))},onGap:ke})},[l,o,s,ke,me.lastCheckpointId,me.lastCheckpointNs,me.messages.length,Ve,it]),St=y.useCallback(async(C,_,F)=>{var J,Z;const de=Ke.current;if(!de)throw new Error("No active thread to handle interrupt");try{const ze=_?F??!0:!1;try{et({type:"interrupt_response",payload:{interruptId:C}})}catch(er){console.warn("[ChatSessionProvider] optimistic interrupt_response dispatch failed:",er)}const We=`${d}/runs/resume`,Le=(J=l.getAuthToken)==null?void 0:J.call(l),ge=await fetch(We,{method:"POST",headers:{"Content-Type":"application/json",...Le?{Authorization:`Bearer ${Le}`}:{}},body:JSON.stringify({thread_id:de,value:ze})});if(!ge.ok)throw new Error(`Resume failed with status ${ge.status}`);const Rt=(Z=ge.body)==null?void 0:Z.getReader();if(!Rt)throw new Error("No response body for resume stream");const mn=new TextDecoder;let en="";for(;;){const{done:er,value:kr}=await Rt.read();if(er)break;en+=mn.decode(kr,{stream:!0});const tr=en.split(`
|
|
39
39
|
`);en=tr.pop()||"";for(const si of tr)if(si.startsWith("data: ")){const ii=si.slice(6);try{const Fn=JSON.parse(ii);et({type:"event",payload:{ev:Fn}})}catch(Fn){console.warn("[ChatSessionProvider] Failed to parse resume SSE event:",Fn)}}}B(null)}catch(ze){throw console.error(`[ChatSessionProvider] Failed to handle interrupt ${C}:`,ze),ze}},[l,et,d]),Wr=y.useCallback(C=>St(C.interruptId,C.approved,C.value),[St]);y.useEffect(()=>{if(a==null||a(A),A)try{localStorage.setItem("lastThreadId",A)}catch(C){console.warn("[ChatSessionProvider] Failed to persist lastThreadId:",C)}},[A,a]),y.useEffect(()=>((async()=>{try{if(Et().catch(_=>{console.error("[ChatSessionProvider] Failed to refresh threads (background):",_),i==null||i(String(_))}),!r&&!t)try{const _=localStorage.getItem("lastThreadId");_&&(j(_),n&&await De(_))}catch(_){console.warn("[ChatSessionProvider] Failed to restore last thread:",_)}else t&&n&&await De(t)}catch(_){console.error("[ChatSessionProvider] Initialization failed:",_),i==null||i(String(_))}})(),()=>{}),[]),y.useEffect(()=>{var J,Z,ze,We;const C=Ke.current;if(!C||ve.current!==C)return;const _={threadId:C,messages:me.messages.slice(),hasMore:D,nextCursor:ye,checkpointId:me.lastCheckpointId??null,checkpointNs:me.lastCheckpointNs??null,nextCursorNs:pe??null,pendingInterrupt:me.pendingInterrupt??z??null},F=Ce.current.get(C);(!F||F.messages.length!==_.messages.length||F.messages.some((Le,ge)=>{var Rt;return(Le==null?void 0:Le.id)!==((Rt=_.messages[ge])==null?void 0:Rt.id)})||(F==null?void 0:F.hasMore)!==_.hasMore||(F==null?void 0:F.nextCursor)!==_.nextCursor||(F==null?void 0:F.nextCursorNs)!==_.nextCursorNs||(F==null?void 0:F.checkpointId)!==_.checkpointId||(F==null?void 0:F.checkpointNs)!==_.checkpointNs||(((J=F==null?void 0:F.pendingInterrupt)==null?void 0:J.id)??null)!==(((Z=_.pendingInterrupt)==null?void 0:Z.id)??null)||JSON.stringify((ze=F==null?void 0:F.pendingInterrupt)==null?void 0:ze.value)!==JSON.stringify((We=_.pendingInterrupt)==null?void 0:We.value))&&(Ce.current.set(C,_),yr.current&&window.clearTimeout(yr.current),yr.current=window.setTimeout(()=>{try{g(_,100)}catch(Le){console.warn("[ChatSessionProvider] Failed to persist thread payload:",Le)}},Bo))},[D,ye,pe,me.lastCheckpointId,me.lastCheckpointNs,me.messages,me.pendingInterrupt,z]);const gl=y.useMemo(()=>({threads:E,currentThreadId:A,setCurrentThreadId:j,isLoading:P,error:M,actions:{createThread:Ee,deleteThread:Be,renameThread:Xe,refreshThreads:()=>Et()},persistThreadsCache:Sr,hydrateFromCache:ue}),[E,A,P,M,Ee,Be,Xe,Et,Sr,ue,j]),xl=y.useMemo(()=>{const C=me.lastBranch??null,_=me.assemblingId??null,F=C||_?{branchLabel:(C==null?void 0:C.branchLabel)??null,lastBranch:C,assemblingMessageId:_}:null;return{threadId:A,messages:me.messages,interrupt:z,checkpoint:{id:me.lastCheckpointId??null,namespace:me.lastCheckpointNs??null},metadata:F,isLoading:$,isHistoryLoading:he,error:K,hasMore:D,loadOlder:Dt,seedFromSnapshot:$n,clearState:oe,listCheckpoints:kt,navigateToCheckpoint:ht,returnToLatest:mt,loadThread:De,clearThread:Ue,respondToInterrupt:St}},[Ue,oe,A,z,D,he,$,kt,Dt,De,me.assemblingId,me.lastBranch,me.lastCheckpointId,me.lastCheckpointNs,me.messages,ht,St,mt,$n,K]),Sk=y.useMemo(()=>({isStreaming:I,error:H,submit:Pn,stop:Mt,resume:Wr,setAuthToken:re}),[I,H,Pn,Mt,Wr,re]);return c.jsx(mx.Provider,{value:!0,children:c.jsx(jc.Provider,{value:Sk,children:c.jsx(Ac.Provider,{value:gl,children:c.jsx(_c.Provider,{value:xl,children:e})})})})}function Ho(){const e=y.useContext(Ac);if(!e)throw new Error("useThreads must be used within ChatSessionProvider");return e}function Uo(){const e=y.useContext(_c);if(!e)throw new Error("useThreadState must be used within ChatSessionProvider");return e}function Mc(){const e=y.useContext(jc);if(!e)throw new Error("useStream must be used within ChatSessionProvider");return e}function Wo({children:e,apiConfig:t,initialThreadId:n=null,autoLoadInitial:r=!0,disableAutoRestore:o=!1,enableFileAgentRouting:s=!1,fileAgentId:i="invoice_reader",onError:a,onThreadChange:l}){return c.jsx(Ug,{apiConfig:t,children:c.jsx(kx,{initialThreadId:n,autoLoadInitial:r,disableAutoRestore:o,enableFileAgentRouting:s,fileAgentId:i,onError:a,onThreadChange:l,children:e})})}function ee(...e){return vm.twMerge(xm.clsx(e))}const Tx=Io.cva("inline-flex items-center justify-center gap-2 whitespace-nowrap rounded-md text-sm font-medium ring-offset-background transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50 [&_svg]:pointer-events-none [&_svg]:size-4 [&_svg]:shrink-0",{variants:{variant:{default:"bg-primary text-primary-foreground hover:bg-primary/90",destructive:"bg-destructive text-destructive-foreground hover:bg-destructive/90",outline:"border border-input bg-background hover:bg-accent hover:text-accent-foreground",secondary:"bg-secondary text-secondary-foreground hover:bg-secondary/80",ghost:"hover:bg-accent hover:text-accent-foreground",link:"text-primary underline-offset-4 hover:underline"},size:{default:"h-10 px-4 py-2",sm:"h-9 rounded-md px-3",lg:"h-11 rounded-md px-8",icon:"h-10 w-10"}},defaultVariants:{variant:"default",size:"default"}}),Je=m.forwardRef(({className:e,variant:t,size:n,asChild:r=!1,...o},s)=>{const i=r?nr.Slot:"button";return c.jsx(i,{className:ee(Tx({variant:t,size:n,className:e})),ref:s,...o})});Je.displayName="Button";const Dc=m.forwardRef(({className:e,...t},n)=>c.jsx("textarea",{className:ee("flex min-h-[80px] w-full rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50",e),ref:n,...t}));Dc.displayName="Textarea";function Ix({initialValue:e="",editingMessageId:t=null,placeholder:n="Type your message...",isStreaming:r=!1,disabled:o=!1,maxLength:s=2e4,onSend:i,onCancelEdit:a,onStop:l,className:u="",textareaClassName:d="",allowEmptySend:f=!1}){const[h,p]=y.useState(e),[b,x]=y.useTransition(),g=y.useRef(null);y.useEffect(()=>{p(e??""),g.current&&(g.current.style.height="auto",g.current.style.height=`${g.current.scrollHeight}px`)},[e,t]);const v=y.useCallback(()=>{const A=g.current;A&&(A.style.height="auto",A.style.height=`${A.scrollHeight}px`)},[]);y.useEffect(()=>{v()},[v]);const w=y.useCallback(async A=>{A&&A.preventDefault();const j=(h??"").trim();!j&&!f||x(()=>{try{const P=i(j);P&&typeof P.then=="function"?P.then(()=>{p(""),g.current&&(g.current.style.height="auto")}).catch(()=>{}):(p(""),g.current&&(g.current.style.height="auto"))}catch{}})},[h,i,f]),S=y.useCallback(A=>{p(A.target.value),g.current&&(g.current.style.height="auto",g.current.style.height=`${g.current.scrollHeight}px`)},[]),N=y.useCallback(A=>{A.key==="Enter"&&!A.shiftKey?(A.preventDefault(),w()):A.key==="Escape"&&t&&(A.preventDefault(),a==null||a())},[w,t,a]),E=`resize-none min-h-[44px] max-h-[20rem] w-full transition-colors ${t?"border-[hsl(var(--ring))] bg-[hsl(var(--card))] text-[hsl(var(--card-foreground))] dark:bg-[hsl(var(--card))] dark:text-[hsl(var(--card-foreground))]":""} ${d}`;return c.jsx("form",{onSubmit:A=>void w(A),className:`w-full ${u}`,children:c.jsxs("div",{className:"flex items-end gap-2",children:[c.jsx("div",{className:"flex-1",children:c.jsx(Dc,{ref:g,value:h,onChange:S,onKeyDown:N,placeholder:t?"Edit your message...":n,className:E,disabled:o,maxLength:s,rows:1,spellCheck:!1,autoCorrect:"off"})}),c.jsx("div",{children:r?c.jsx(Je,{type:"button",onClick:()=>{l==null||l()},size:"icon",variant:"outline",className:"shrink-0",title:"Stop generating",disabled:o||!l,children:c.jsx(ae.Square,{size:16})}):c.jsx(Je,{type:"submit",size:"icon",className:"shrink-0",title:t?"Save changes":"Send message",disabled:o||!h.trim()&&!f||b,children:c.jsx(ae.Send,{size:16})})})]})})}const Ex=y.memo(Ix),Vo=0,zn=1,Ar=2,Lc=4;function $c(e){return()=>e}function Nx(e){e()}function Fc(e,t){return n=>e(t(n))}function Bc(e,t){return()=>e(t)}function Ax(e,t){return n=>e(t,n)}function Mi(e){return e!==void 0}function _x(...e){return()=>{e.map(Nx)}}function _r(){}function Ko(e,t){return t(e),e}function jx(e,t){return t(e)}function lt(...e){return e}function Qe(e,t){return e(zn,t)}function Fe(e,t){e(Vo,t)}function Di(e){e(Ar)}function xt(e){return e(Lc)}function be(e,t){return Qe(e,Ax(t,Vo))}function on(e,t){const n=e(zn,r=>{n(),t(r)});return n}function zc(e){let t,n;return r=>o=>{t=o,n&&clearTimeout(n),n=setTimeout(()=>{r(t)},e)}}function Hc(e,t){return e===t}function ct(e=Hc){let t;return n=>r=>{e(t,r)||(t=r,n(r))}}function Ae(e){return t=>n=>{e(n)&&t(n)}}function le(e){return t=>Fc(t,e)}function xn(e){return t=>()=>{t(e)}}function U(e,...t){const n=Rx(...t);return(r,o)=>{switch(r){case Ar:Di(e);return;case zn:return Qe(e,n(o))}}}function vn(e,t){return n=>r=>{n(t=e(t,r))}}function ir(e){return t=>n=>{e>0?e--:t(n)}}function Mn(e){let t=null,n;return r=>o=>{t=o,!n&&(n=setTimeout(()=>{n=void 0,r(t)},e))}}function He(...e){const t=new Array(e.length);let n=0,r=null;const o=Math.pow(2,e.length)-1;return e.forEach((s,i)=>{const a=Math.pow(2,i);Qe(s,l=>{const u=n;n=n|a,t[i]=l,u!==o&&n===o&&r&&(r(),r=null)})}),s=>i=>{const a=()=>{s([i].concat(t))};n===o?a():r=a}}function Rx(...e){return t=>e.reduceRight(jx,t)}function Px(e){let t,n;const r=()=>t==null?void 0:t();return function(o,s){switch(o){case zn:return s?n===s?void 0:(r(),n=s,t=Qe(e,s),t):(r(),_r);case Ar:r(),n=null;return}}}function Y(e){let t=e;const n=Ye();return(r,o)=>{switch(r){case Vo:t=o;break;case zn:{o(t);break}case Lc:return t}return n(r,o)}}function At(e,t){return Ko(Y(t),n=>be(e,n))}function Ye(){const e=[];return(t,n)=>{switch(t){case Vo:e.slice().forEach(r=>{r(n)});return;case Ar:e.splice(0,e.length);return;case zn:return e.push(n),()=>{const r=e.indexOf(n);r>-1&&e.splice(r,1)}}}}function zt(e){return Ko(Ye(),t=>be(e,t))}function Ze(e,t=[],{singleton:n}={singleton:!0}){return{constructor:e,dependencies:t,id:Ox(),singleton:n}}const Ox=()=>Symbol();function Mx(e){const t=new Map,n=({constructor:r,dependencies:o,id:s,singleton:i})=>{if(i&&t.has(s))return t.get(s);const a=r(o.map(l=>n(l)));return i&&t.set(s,a),a};return n(e)}function bt(...e){const t=Ye(),n=new Array(e.length);let r=0;const o=Math.pow(2,e.length)-1;return e.forEach((s,i)=>{const a=Math.pow(2,i);Qe(s,l=>{n[i]=l,r=r|a,r===o&&Fe(t,n)})}),function(s,i){switch(s){case Ar:{Di(t);return}case zn:return r===o&&i(n),Qe(t,i)}}}function Ne(e,t=Hc){return U(e,ct(t))}function Li(...e){return function(t,n){switch(t){case Ar:return;case zn:return _x(...e.map(r=>Qe(r,n)))}}}var Ft=(e=>(e[e.DEBUG=0]="DEBUG",e[e.INFO=1]="INFO",e[e.WARN=2]="WARN",e[e.ERROR=3]="ERROR",e))(Ft||{});const Dx={0:"debug",3:"error",1:"log",2:"warn"},Lx=()=>typeof globalThis>"u"?window:globalThis,Hn=Ze(()=>{const e=Y(3);return{log:Y((t,n,r=1)=>{var o;const s=(o=Lx().VIRTUOSO_LOG_LEVEL)!=null?o:xt(e);r>=s&&console[Dx[r]]("%creact-virtuoso: %c%s %o","color: #0253b3; font-weight: bold","color: initial",t,n)}),logLevel:e}},[],{singleton:!0});function ar(e,t,n){return $i(e,t,n).callbackRef}function $i(e,t,n){const r=y.useRef(null);let o=i=>{};const s=y.useMemo(()=>typeof ResizeObserver<"u"?new ResizeObserver(i=>{const a=()=>{const l=i[0].target;l.offsetParent!==null&&e(l)};n?a():requestAnimationFrame(a)}):null,[e,n]);return o=i=>{i&&t?(s==null||s.observe(i),r.current=i):(r.current&&(s==null||s.unobserve(r.current)),r.current=null)},{callbackRef:o,ref:r}}function $x(e,t,n,r,o,s,i,a,l){const u=y.useCallback(d=>{const f=Fx(d.children,t,a?"offsetWidth":"offsetHeight",o);let h=d.parentElement;for(;!h.dataset.virtuosoScroller;)h=h.parentElement;const p=h.lastElementChild.dataset.viewportType==="window";let b;p&&(b=h.ownerDocument.defaultView);const x=i?a?i.scrollLeft:i.scrollTop:p?a?b.scrollX||b.document.documentElement.scrollLeft:b.scrollY||b.document.documentElement.scrollTop:a?h.scrollLeft:h.scrollTop,g=i?a?i.scrollWidth:i.scrollHeight:p?a?b.document.documentElement.scrollWidth:b.document.documentElement.scrollHeight:a?h.scrollWidth:h.scrollHeight,v=i?a?i.offsetWidth:i.offsetHeight:p?a?b.innerWidth:b.innerHeight:a?h.offsetWidth:h.offsetHeight;r({scrollHeight:g,scrollTop:Math.max(x,0),viewportHeight:v}),s==null||s(a?Uc("column-gap",getComputedStyle(d).columnGap,o):Uc("row-gap",getComputedStyle(d).rowGap,o)),f!==null&&e(f)},[e,t,o,s,i,r,a]);return $i(u,n,l)}function Fx(e,t,n,r){const o=e.length;if(o===0)return null;const s=[];for(let i=0;i<o;i++){const a=e.item(i);if(a.dataset.index===void 0)continue;const l=parseInt(a.dataset.index),u=parseFloat(a.dataset.knownSize),d=t(a,n);if(d===0&&r("Zero-sized element, this should not happen",{child:a},Ft.ERROR),d===u)continue;const f=s[s.length-1];s.length===0||f.size!==d||f.endIndex!==l-1?s.push({endIndex:l,size:d,startIndex:l}):s[s.length-1].endIndex++}return s}function Uc(e,t,n){return t!=="normal"&&!(t!=null&&t.endsWith("px"))&&n(`${e} was not resolved to pixel value correctly`,t,Ft.WARN),t==="normal"?0:parseInt(t??"0",10)}function Wc(e,t,n){const r=y.useRef(null),o=y.useCallback(l=>{if(!(l!=null&&l.offsetParent))return;const u=l.getBoundingClientRect(),d=u.width;let f,h;if(t){const p=t.getBoundingClientRect(),b=u.top-p.top;h=p.height-Math.max(0,b),f=b+t.scrollTop}else{const p=i.current.ownerDocument.defaultView;h=p.innerHeight-Math.max(0,u.top),f=u.top+p.scrollY}r.current={offsetTop:f,visibleHeight:h,visibleWidth:d},e(r.current)},[e,t]),{callbackRef:s,ref:i}=$i(o,!0,n),a=y.useCallback(()=>{o(i.current)},[o,i]);return y.useEffect(()=>{var l;if(t){t.addEventListener("scroll",a);const u=new ResizeObserver(()=>{requestAnimationFrame(a)});return u.observe(t),()=>{t.removeEventListener("scroll",a),u.unobserve(t)}}else{const u=(l=i.current)==null?void 0:l.ownerDocument.defaultView;return u==null||u.addEventListener("scroll",a),u==null||u.addEventListener("resize",a),()=>{u==null||u.removeEventListener("scroll",a),u==null||u.removeEventListener("resize",a)}}},[a,t,i]),s}const Pt=Ze(()=>{const e=Ye(),t=Ye(),n=Y(0),r=Ye(),o=Y(0),s=Ye(),i=Ye(),a=Y(0),l=Y(0),u=Y(0),d=Y(0),f=Ye(),h=Ye(),p=Y(!1),b=Y(!1),x=Y(!1);return be(U(e,le(({scrollTop:g})=>g)),t),be(U(e,le(({scrollHeight:g})=>g)),i),be(t,o),{deviation:n,fixedFooterHeight:u,fixedHeaderHeight:l,footerHeight:d,headerHeight:a,horizontalDirection:b,scrollBy:h,scrollContainerState:e,scrollHeight:i,scrollingInProgress:p,scrollTo:f,scrollTop:t,skipAnimationFrameInResizeObserver:x,smoothScrollTargetReached:r,statefulScrollTop:o,viewportHeight:s}},[],{singleton:!0}),Qr={lvl:0};function Vc(e,t){const n=e.length;if(n===0)return[];let{index:r,value:o}=t(e[0]);const s=[];for(let i=1;i<n;i++){const{index:a,value:l}=t(e[i]);s.push({end:a-1,start:r,value:o}),r=a,o=l}return s.push({end:1/0,start:r,value:o}),s}function rt(e){return e===Qr}function eo(e,t){if(!rt(e))return t===e.k?e.v:t<e.k?eo(e.l,t):eo(e.r,t)}function sn(e,t,n="k"){if(rt(e))return[-1/0,void 0];if(Number(e[n])===t)return[e.k,e.v];if(Number(e[n])<t){const r=sn(e.r,t,n);return r[0]===-1/0?[e.k,e.v]:r}return sn(e.l,t,n)}function Ht(e,t,n){return rt(e)?Gc(t,n,1):t===e.k?wt(e,{k:t,v:n}):t<e.k?Yc(wt(e,{l:Ht(e.l,t,n)})):Yc(wt(e,{r:Ht(e.r,t,n)}))}function jr(){return Qr}function qo(e,t,n){if(rt(e))return[];const r=sn(e,t)[0];return Bx(Bi(e,r,n))}function Fi(e,t){if(rt(e))return Qr;const{k:n,l:r,r:o}=e;if(t===n){if(rt(r))return o;if(rt(o))return r;{const[s,i]=qc(r);return Go(wt(e,{k:s,l:Kc(r),v:i}))}}else return t<n?Go(wt(e,{l:Fi(r,t)})):Go(wt(e,{r:Fi(o,t)}))}function lr(e){return rt(e)?[]:[...lr(e.l),{k:e.k,v:e.v},...lr(e.r)]}function Bi(e,t,n){if(rt(e))return[];const{k:r,l:o,r:s,v:i}=e;let a=[];return r>t&&(a=a.concat(Bi(o,t,n))),r>=t&&r<=n&&a.push({k:r,v:i}),r<=n&&(a=a.concat(Bi(s,t,n))),a}function Go(e){const{l:t,lvl:n,r}=e;if(r.lvl>=n-1&&t.lvl>=n-1)return e;if(n>r.lvl+1){if(zi(t))return Xc(wt(e,{lvl:n-1}));if(!rt(t)&&!rt(t.r))return wt(t.r,{l:wt(t,{r:t.r.l}),lvl:n,r:wt(e,{l:t.r.r,lvl:n-1})});throw new Error("Unexpected empty nodes")}else{if(zi(e))return Hi(wt(e,{lvl:n-1}));if(!rt(r)&&!rt(r.l)){const o=r.l,s=zi(o)?r.lvl-1:r.lvl;return wt(o,{l:wt(e,{lvl:n-1,r:o.l}),lvl:o.lvl+1,r:Hi(wt(r,{l:o.r,lvl:s}))})}else throw new Error("Unexpected empty nodes")}}function wt(e,t){return Gc(t.k!==void 0?t.k:e.k,t.v!==void 0?t.v:e.v,t.lvl!==void 0?t.lvl:e.lvl,t.l!==void 0?t.l:e.l,t.r!==void 0?t.r:e.r)}function Kc(e){return rt(e.r)?e.l:Go(wt(e,{r:Kc(e.r)}))}function zi(e){return rt(e)||e.lvl>e.r.lvl}function qc(e){return rt(e.r)?[e.k,e.v]:qc(e.r)}function Gc(e,t,n,r=Qr,o=Qr){return{k:e,l:r,lvl:n,r:o,v:t}}function Yc(e){return Hi(Xc(e))}function Xc(e){const{l:t}=e;return!rt(t)&&t.lvl===e.lvl?wt(t,{r:wt(e,{l:t.r})}):e}function Hi(e){const{lvl:t,r:n}=e;return!rt(n)&&!rt(n.r)&&n.lvl===t&&n.r.lvl===t?wt(n,{l:wt(e,{r:n.l}),lvl:t+1}):e}function Bx(e){return Vc(e,({k:t,v:n})=>({index:t,value:n}))}function Jc(e,t){return!!(e&&e.startIndex===t.startIndex&&e.endIndex===t.endIndex)}function to(e,t){return!!(e&&e[0]===t[0]&&e[1]===t[1])}const Ui=Ze(()=>({recalcInProgress:Y(!1)}),[],{singleton:!0});function Zc(e,t,n){return e[Yo(e,t,n)]}function Yo(e,t,n,r=0){let o=e.length-1;for(;r<=o;){const s=Math.floor((r+o)/2),i=e[s],a=n(i,t);if(a===0)return s;if(a===-1){if(o-r<2)return s-1;o=s-1}else{if(o===r)return s;r=s+1}}throw new Error(`Failed binary finding record in array - ${e.join(",")}, searched for ${t}`)}function zx(e,t,n,r){const o=Yo(e,t,r),s=Yo(e,n,r,o);return e.slice(o,s+1)}function Un(e,t){return Math.round(e.getBoundingClientRect()[t])}function Xo(e){return!rt(e.groupOffsetTree)}function Wi({index:e},t){return t===e?0:t<e?-1:1}function Hx(){return{groupIndices:[],groupOffsetTree:jr(),lastIndex:0,lastOffset:0,lastSize:0,offsetTree:[],sizeTree:jr()}}function Ux(e,t){let n=rt(e)?0:1/0;for(const r of t){const{endIndex:o,size:s,startIndex:i}=r;if(n=Math.min(n,i),rt(e)){e=Ht(e,0,s);continue}const a=qo(e,i-1,o+1);if(a.some(Xx(r)))continue;let l=!1,u=!1;for(const{end:d,start:f,value:h}of a)l?(o>=f||s===h)&&(e=Fi(e,f)):(u=h!==s,l=!0),d>o&&o>=f&&h!==s&&(e=Ht(e,o+1,h));u&&(e=Ht(e,i,s))}return[e,n]}function Wx(e){return typeof e.groupIndex<"u"}function Vx({offset:e},t){return t===e?0:t<e?-1:1}function no(e,t,n){if(t.length===0)return 0;const{index:r,offset:o,size:s}=Zc(t,e,Wi),i=e-r,a=s*i+(i-1)*n+o;return a>0?a+n:a}function Qc(e,t){if(!Xo(t))return e;let n=0;for(;t.groupIndices[n]<=e+n;)n++;return e+n}function eu(e,t,n){if(Wx(e))return t.groupIndices[e.groupIndex]+1;{const r=e.index==="LAST"?n:e.index;let o=Qc(r,t);return o=Math.max(0,o,Math.min(n,o)),o}}function Kx(e,t,n,r=0){return r>0&&(t=Math.max(t,Zc(e,r,Wi).offset)),Vc(zx(e,t,n,Vx),Yx)}function qx(e,[t,n,r,o]){t.length>0&&r("received item sizes",t,Ft.DEBUG);const s=e.sizeTree;let i=s,a=0;if(n.length>0&&rt(s)&&t.length===2){const h=t[0].size,p=t[1].size;i=n.reduce((b,x)=>Ht(Ht(b,x,h),x+1,p),i)}else[i,a]=Ux(i,t);if(i===s)return e;const{lastIndex:l,lastOffset:u,lastSize:d,offsetTree:f}=Vi(e.offsetTree,a,i,o);return{groupIndices:n,groupOffsetTree:n.reduce((h,p)=>Ht(h,p,no(p,f,o)),jr()),lastIndex:l,lastOffset:u,lastSize:d,offsetTree:f,sizeTree:i}}function Gx(e){return lr(e).map(({k:t,v:n},r,o)=>{const s=o[r+1];return{endIndex:s?s.k-1:1/0,size:n,startIndex:t}})}function tu(e,t){let n=0,r=0;for(;n<e;)n+=t[r+1]-t[r]-1,r++;return r-(n===e?0:1)}function Vi(e,t,n,r){let o=e,s=0,i=0,a=0,l=0;if(t!==0){l=Yo(o,t-1,Wi),a=o[l].offset;const u=sn(n,t-1);s=u[0],i=u[1],o.length&&o[l].size===sn(n,t)[1]&&(l-=1),o=o.slice(0,l+1)}else o=[];for(const{start:u,value:d}of qo(n,t,1/0)){const f=u-s,h=f*i+a+f*r;o.push({index:u,offset:h,size:d}),s=u,a=h,i=d}return{lastIndex:s,lastOffset:a,lastSize:i,offsetTree:o}}function Yx(e){return{index:e.index,value:e}}function Xx(e){const{endIndex:t,size:n,startIndex:r}=e;return o=>o.start===r&&(o.end===t||o.end===1/0)&&o.value===n}const Jx={offsetHeight:"height",offsetWidth:"width"},bn=Ze(([{log:e},{recalcInProgress:t}])=>{const n=Ye(),r=Ye(),o=At(r,0),s=Ye(),i=Ye(),a=Y(0),l=Y([]),u=Y(void 0),d=Y(void 0),f=Y((k,T)=>Un(k,Jx[T])),h=Y(void 0),p=Y(0),b=Hx(),x=At(U(n,He(l,e,p),vn(qx,b),ct()),b),g=At(U(l,ct(),vn((k,T)=>({current:T,prev:k.current}),{current:[],prev:[]}),le(({prev:k})=>k)),[]);be(U(l,Ae(k=>k.length>0),He(x,p),le(([k,T,E])=>{const A=k.reduce((j,P,L)=>Ht(j,P,no(P,T.offsetTree,E)||L),jr());return{...T,groupIndices:k,groupOffsetTree:A}})),x),be(U(r,He(x),Ae(([k,{lastIndex:T}])=>k<T),le(([k,{lastIndex:T,lastSize:E}])=>[{endIndex:T,size:E,startIndex:k}])),n),be(u,d);const v=At(U(u,le(k=>k===void 0)),!0);be(U(d,Ae(k=>k!==void 0&&rt(xt(x).sizeTree)),le(k=>[{endIndex:0,size:k,startIndex:0}])),n);const w=zt(U(n,He(x),vn(({sizes:k},[T,E])=>({changed:E!==k,sizes:E}),{changed:!1,sizes:b}),le(k=>k.changed)));Qe(U(a,vn((k,T)=>({diff:k.prev-T,prev:T}),{diff:0,prev:0}),le(k=>k.diff)),k=>{const{groupIndices:T}=xt(x);if(k>0)Fe(t,!0),Fe(s,k+tu(k,T));else if(k<0){const E=xt(g);E.length>0&&(k-=tu(-k,E)),Fe(i,k)}}),Qe(U(a,He(e)),([k,T])=>{k<0&&T("`firstItemIndex` prop should not be set to less than zero. If you don't know the total count, just use a very high value",{firstItemIndex:a},Ft.ERROR)});const S=zt(s);be(U(s,He(x),le(([k,T])=>{const E=T.groupIndices.length>0,A=[],j=T.lastSize;if(E){const P=eo(T.sizeTree,0);let L=0,$=0;for(;L<k;){const M=T.groupIndices[$],G=T.groupIndices.length===$+1?1/0:T.groupIndices[$+1]-M-1;A.push({endIndex:M,size:P,startIndex:M}),A.push({endIndex:M+1+G-1,size:j,startIndex:M+1}),$++,L+=G+1}const V=lr(T.sizeTree);return L!==k&&V.shift(),V.reduce((M,{k:G,v:K})=>{let W=M.ranges;return M.prevSize!==0&&(W=[...M.ranges,{endIndex:G+k-1,size:M.prevSize,startIndex:M.prevIndex}]),{prevIndex:G+k,prevSize:K,ranges:W}},{prevIndex:k,prevSize:0,ranges:A}).ranges}return lr(T.sizeTree).reduce((P,{k:L,v:$})=>({prevIndex:L+k,prevSize:$,ranges:[...P.ranges,{endIndex:L+k-1,size:P.prevSize,startIndex:P.prevIndex}]}),{prevIndex:0,prevSize:j,ranges:[]}).ranges})),n);const N=zt(U(i,He(x,p),le(([k,{offsetTree:T},E])=>{const A=-k;return no(A,T,E)})));return be(U(i,He(x,p),le(([k,T,E])=>{if(T.groupIndices.length>0){if(rt(T.sizeTree))return T;let A=jr();const j=xt(g);let P=0,L=0,$=0;for(;P<-k;){$=j[L];const V=j[L+1]-$-1;L++,P+=V+1}if(A=lr(T.sizeTree).reduce((V,{k:M,v:G})=>Ht(V,Math.max(0,M+k),G),A),P!==-k){const V=eo(T.sizeTree,$);A=Ht(A,0,V);const M=sn(T.sizeTree,-k+1)[1];A=Ht(A,1,M)}return{...T,sizeTree:A,...Vi(T.offsetTree,0,A,E)}}else{const A=lr(T.sizeTree).reduce((j,{k:P,v:L})=>Ht(j,Math.max(0,P+k),L),jr());return{...T,sizeTree:A,...Vi(T.offsetTree,0,A,E)}}})),x),{beforeUnshiftWith:S,data:h,defaultItemSize:d,firstItemIndex:a,fixedItemSize:u,gap:p,groupIndices:l,itemSize:f,listRefresh:w,shiftWith:i,shiftWithOffset:N,sizeRanges:n,sizes:x,statefulTotalCount:o,totalCount:r,trackItemSizes:v,unshiftWith:s}},lt(Hn,Ui),{singleton:!0});function Zx(e){return e.reduce((t,n)=>(t.groupIndices.push(t.totalCount),t.totalCount+=n+1,t),{groupIndices:[],totalCount:0})}const nu=Ze(([{groupIndices:e,sizes:t,totalCount:n},{headerHeight:r,scrollTop:o}])=>{const s=Ye(),i=Ye(),a=zt(U(s,le(Zx)));return be(U(a,le(l=>l.totalCount)),n),be(U(a,le(l=>l.groupIndices)),e),be(U(bt(o,t,r),Ae(([l,u])=>Xo(u)),le(([l,u,d])=>sn(u.groupOffsetTree,Math.max(l-d,0),"v")[0]),ct(),le(l=>[l])),i),{groupCounts:s,topItemsIndexes:i}},lt(bn,Pt)),Wn=Ze(([{log:e}])=>{const t=Y(!1),n=zt(U(t,Ae(r=>r),ct()));return Qe(t,r=>{r&&xt(e)("props updated",{},Ft.DEBUG)}),{didMount:n,propsReady:t}},lt(Hn),{singleton:!0}),Qx=typeof document<"u"&&"scrollBehavior"in document.documentElement.style;function ru(e){const t=typeof e=="number"?{index:e}:e;return t.align||(t.align="start"),(!t.behavior||!Qx)&&(t.behavior="auto"),t.offset||(t.offset=0),t}const ro=Ze(([{gap:e,listRefresh:t,sizes:n,totalCount:r},{fixedFooterHeight:o,fixedHeaderHeight:s,footerHeight:i,headerHeight:a,scrollingInProgress:l,scrollTo:u,smoothScrollTargetReached:d,viewportHeight:f},{log:h}])=>{const p=Ye(),b=Ye(),x=Y(0);let g=null,v=null,w=null;function S(){g&&(g(),g=null),w&&(w(),w=null),v&&(clearTimeout(v),v=null),Fe(l,!1)}return be(U(p,He(n,f,r,x,a,i,h),He(e,s,o),le(([[N,k,T,E,A,j,P,L],$,V,M])=>{const G=ru(N),{align:K,behavior:W,offset:z}=G,B=E-1,ue=eu(G,k,B);let D=no(ue,k.offsetTree,$)+j;K==="end"?(D+=V+sn(k.sizeTree,ue)[1]-T+M,ue===B&&(D+=P)):K==="center"?D+=(V+sn(k.sizeTree,ue)[1]-T+M)/2:D-=A,z&&(D+=z);const te=he=>{S(),he?(L("retrying to scroll to",{location:N},Ft.DEBUG),Fe(p,N)):(Fe(b,!0),L("list did not change, scroll successful",{},Ft.DEBUG))};if(S(),W==="smooth"){let he=!1;w=Qe(t,we=>{he=he||we}),g=on(d,()=>{te(he)})}else g=on(U(t,ev(150)),te);return v=setTimeout(()=>{S()},1200),Fe(l,!0),L("scrolling from index to",{behavior:W,index:ue,top:D},Ft.DEBUG),{behavior:W,top:D}})),u),{scrollTargetReached:b,scrollToIndex:p,topListHeight:x}},lt(bn,Pt,Hn),{singleton:!0});function ev(e){return t=>{const n=setTimeout(()=>{t(!1)},e);return r=>{r&&(t(!0),clearTimeout(n))}}}function Ki(e,t){e==0?t():requestAnimationFrame(()=>{Ki(e-1,t)})}function qi(e,t){const n=t-1;return typeof e=="number"?e:e.index==="LAST"?n:e.index}const oo=Ze(([{defaultItemSize:e,listRefresh:t,sizes:n},{scrollTop:r},{scrollTargetReached:o,scrollToIndex:s},{didMount:i}])=>{const a=Y(!0),l=Y(0),u=Y(!0);return be(U(i,He(l),Ae(([d,f])=>!!f),xn(!1)),a),be(U(i,He(l),Ae(([d,f])=>!!f),xn(!1)),u),Qe(U(bt(t,i),He(a,n,e,u),Ae(([[,d],f,{sizeTree:h},p,b])=>d&&(!rt(h)||Mi(p))&&!f&&!b),He(l)),([,d])=>{on(o,()=>{Fe(u,!0)}),Ki(4,()=>{on(r,()=>{Fe(a,!0)}),Fe(s,d)})}),{initialItemFinalLocationReached:u,initialTopMostItemIndex:l,scrolledToInitialItem:a}},lt(bn,Pt,ro,Wn),{singleton:!0});function ou(e,t){return Math.abs(e-t)<1.01}const so="up",io="down",tv="none",nv={atBottom:!1,notAtBottomBecause:"NOT_SHOWING_LAST_ITEM",state:{offsetBottom:0,scrollHeight:0,scrollTop:0,viewportHeight:0}},rv=0,ao=Ze(([{footerHeight:e,headerHeight:t,scrollBy:n,scrollContainerState:r,scrollTop:o,viewportHeight:s}])=>{const i=Y(!1),a=Y(!0),l=Ye(),u=Ye(),d=Y(4),f=Y(rv),h=At(U(Li(U(Ne(o),ir(1),xn(!0)),U(Ne(o),ir(1),xn(!1),zc(100))),ct()),!1),p=At(U(Li(U(n,xn(!0)),U(n,xn(!1),zc(200))),ct()),!1);be(U(bt(Ne(o),Ne(f)),le(([w,S])=>w<=S),ct()),a),be(U(a,Mn(50)),u);const b=zt(U(bt(r,Ne(s),Ne(t),Ne(e),Ne(d)),vn((w,[{scrollHeight:S,scrollTop:N},k,T,E,A])=>{const j=N+k-S>-A,P={scrollHeight:S,scrollTop:N,viewportHeight:k};if(j){let $,V;return N>w.state.scrollTop?($="SCROLLED_DOWN",V=w.state.scrollTop-N):($="SIZE_DECREASED",V=w.state.scrollTop-N||w.scrollTopDelta),{atBottom:!0,atBottomBecause:$,scrollTopDelta:V,state:P}}let L;return P.scrollHeight>w.state.scrollHeight?L="SIZE_INCREASED":k<w.state.viewportHeight?L="VIEWPORT_HEIGHT_DECREASING":N<w.state.scrollTop?L="SCROLLING_UPWARDS":L="NOT_FULLY_SCROLLED_TO_LAST_ITEM_BOTTOM",{atBottom:!1,notAtBottomBecause:L,state:P}},nv),ct((w,S)=>w&&w.atBottom===S.atBottom))),x=At(U(r,vn((w,{scrollHeight:S,scrollTop:N,viewportHeight:k})=>{if(ou(w.scrollHeight,S))return{changed:!1,jump:0,scrollHeight:S,scrollTop:N};{const T=S-(N+k)<1;return w.scrollTop!==N&&T?{changed:!0,jump:w.scrollTop-N,scrollHeight:S,scrollTop:N}:{changed:!0,jump:0,scrollHeight:S,scrollTop:N}}},{changed:!1,jump:0,scrollHeight:0,scrollTop:0}),Ae(w=>w.changed),le(w=>w.jump)),0);be(U(b,le(w=>w.atBottom)),i),be(U(i,Mn(50)),l);const g=Y(io);be(U(r,le(({scrollTop:w})=>w),ct(),vn((w,S)=>xt(p)?{direction:w.direction,prevScrollTop:S}:{direction:S<w.prevScrollTop?so:io,prevScrollTop:S},{direction:io,prevScrollTop:0}),le(w=>w.direction)),g),be(U(r,Mn(50),xn(tv)),g);const v=Y(0);return be(U(h,Ae(w=>!w),xn(0)),v),be(U(o,Mn(100),He(h),Ae(([w,S])=>!!S),vn(([w,S],[N])=>[S,N],[0,0]),le(([w,S])=>S-w)),v),{atBottomState:b,atBottomStateChange:l,atBottomThreshold:d,atTopStateChange:u,atTopThreshold:f,isAtBottom:i,isAtTop:a,isScrolling:h,lastJumpDueToItemResize:x,scrollDirection:g,scrollVelocity:v}},lt(Pt)),Jo="top",Zo="bottom",su="none";function iu(e,t,n){return typeof e=="number"?n===so&&t===Jo||n===io&&t===Zo?e:0:n===so?t===Jo?e.main:e.reverse:t===Zo?e.main:e.reverse}function au(e,t){var n;return typeof e=="number"?e:(n=e[t])!=null?n:0}const Gi=Ze(([{deviation:e,fixedHeaderHeight:t,headerHeight:n,scrollTop:r,viewportHeight:o}])=>{const s=Ye(),i=Y(0),a=Y(0),l=Y(0),u=At(U(bt(Ne(r),Ne(o),Ne(n),Ne(s,to),Ne(l),Ne(i),Ne(t),Ne(e),Ne(a)),le(([d,f,h,[p,b],x,g,v,w,S])=>{const N=d-w,k=g+v,T=Math.max(h-N,0);let E=su;const A=au(S,Jo),j=au(S,Zo);return p-=w,p+=h+v,b+=h+v,b-=w,p>d+k-A&&(E=so),b<d-T+f+j&&(E=io),E!==su?[Math.max(N-h-iu(x,Jo,E)-A,0),N-T-v+f+iu(x,Zo,E)+j]:null}),Ae(d=>d!=null),ct(to)),[0,0]);return{increaseViewportBy:a,listBoundary:s,overscan:l,topListHeight:i,visibleRange:u}},lt(Pt),{singleton:!0});function ov(e,t,n){if(Xo(t)){const r=Qc(e,t);return[{index:sn(t.groupOffsetTree,r)[0],offset:0,size:0},{data:n==null?void 0:n[0],index:r,offset:0,size:0}]}return[{data:n==null?void 0:n[0],index:e,offset:0,size:0}]}const Yi={bottom:0,firstItemIndex:0,items:[],offsetBottom:0,offsetTop:0,top:0,topItems:[],topListHeight:0,totalCount:0};function Qo(e,t,n,r,o,s){const{lastIndex:i,lastOffset:a,lastSize:l}=o;let u=0,d=0;if(e.length>0){u=e[0].offset;const x=e[e.length-1];d=x.offset+x.size}const f=n-i,h=a+f*l+(f-1)*r,p=u,b=h-d;return{bottom:d,firstItemIndex:s,items:cu(e,o,s),offsetBottom:b,offsetTop:u,top:p,topItems:cu(t,o,s),topListHeight:t.reduce((x,g)=>g.size+x,0),totalCount:n}}function lu(e,t,n,r,o,s){let i=0;if(n.groupIndices.length>0)for(const d of n.groupIndices){if(d-i>=e)break;i++}const a=e+i,l=qi(t,a),u=Array.from({length:a}).map((d,f)=>({data:s[f+l],index:f+l,offset:0,size:0}));return Qo(u,[],a,o,n,r)}function cu(e,t,n){if(e.length===0)return[];if(!Xo(t))return e.map(u=>({...u,index:u.index+n,originalIndex:u.index}));const r=e[0].index,o=e[e.length-1].index,s=[],i=qo(t.groupOffsetTree,r,o);let a,l=0;for(const u of e){(!a||a.end<u.index)&&(a=i.shift(),l=t.groupIndices.indexOf(a.start));let d;u.index===a.start?d={index:l,type:"group"}:d={groupIndex:l,index:u.index-(l+1)+n},s.push({...d,data:u.data,offset:u.offset,originalIndex:u.index,size:u.size})}return s}const cr=Ze(([{data:e,firstItemIndex:t,gap:n,sizes:r,totalCount:o},s,{listBoundary:i,topListHeight:a,visibleRange:l},{initialTopMostItemIndex:u,scrolledToInitialItem:d},{topListHeight:f},h,{didMount:p},{recalcInProgress:b}])=>{const x=Y([]),g=Y(0),v=Ye();be(s.topItemsIndexes,x);const w=At(U(bt(p,b,Ne(l,to),Ne(o),Ne(r),Ne(u),d,Ne(x),Ne(t),Ne(n),e),Ae(([T,E,,A,,,,,,,j])=>{const P=j&&j.length!==A;return T&&!E&&!P}),le(([,,[T,E],A,j,P,L,$,V,M,G])=>{const K=j,{offsetTree:W,sizeTree:z}=K,B=xt(g);if(A===0)return{...Yi,totalCount:A};if(T===0&&E===0)return B===0?{...Yi,totalCount:A}:lu(B,P,j,V,M,G||[]);if(rt(z))return B>0?null:Qo(ov(qi(P,A),K,G),[],A,M,K,V);const ue=[];if($.length>0){const ye=$[0],Se=$[$.length-1];let q=0;for(const O of qo(z,ye,Se)){const X=O.value,ne=Math.max(O.start,ye),pe=Math.min(O.end,Se);for(let se=ne;se<=pe;se++)ue.push({data:G==null?void 0:G[se],index:se,offset:q,size:X}),q+=X}}if(!L)return Qo([],ue,A,M,K,V);const D=$.length>0?$[$.length-1]+1:0,te=Kx(W,T,E,D);if(te.length===0)return null;const he=A-1,we=Ko([],ye=>{for(const Se of te){const q=Se.value;let O=q.offset,X=Se.start;const ne=q.size;if(q.offset<T){X+=Math.floor((T-q.offset+M)/(ne+M));const se=X-Se.start;O+=se*ne+se*M}X<D&&(O+=(D-X)*ne,X=D);const pe=Math.min(Se.end,he);for(let se=X;se<=pe&&!(O>=E);se++)ye.push({data:G==null?void 0:G[se],index:se,offset:O,size:ne}),O+=ne+M}});return Qo(we,ue,A,M,K,V)}),Ae(T=>T!==null),ct()),Yi);be(U(e,Ae(Mi),le(T=>T==null?void 0:T.length)),o),be(U(w,le(T=>T.topListHeight)),f),be(f,a),be(U(w,le(T=>[T.top,T.bottom])),i),be(U(w,le(T=>T.items)),v);const S=zt(U(w,Ae(({items:T})=>T.length>0),He(o,e),Ae(([{items:T},E])=>T[T.length-1].originalIndex===E-1),le(([,T,E])=>[T-1,E]),ct(to),le(([T])=>T))),N=zt(U(w,Mn(200),Ae(({items:T,topItems:E})=>T.length>0&&T[0].originalIndex===E.length),le(({items:T})=>T[0].index),ct())),k=zt(U(w,Ae(({items:T})=>T.length>0),le(({items:T})=>{let E=0,A=T.length-1;for(;T[E].type==="group"&&E<A;)E++;for(;T[A].type==="group"&&A>E;)A--;return{endIndex:T[A].index,startIndex:T[E].index}}),ct(Jc)));return{endReached:S,initialItemCount:g,itemsRendered:v,listState:w,rangeChanged:k,startReached:N,topItemsIndexes:x,...h}},lt(bn,nu,Gi,oo,ro,ao,Wn,Ui),{singleton:!0}),uu=Ze(([{fixedFooterHeight:e,fixedHeaderHeight:t,footerHeight:n,headerHeight:r},{listState:o}])=>{const s=Ye(),i=At(U(bt(n,e,r,t,o),le(([a,l,u,d,f])=>a+l+u+d+f.offsetBottom+f.bottom)),0);return be(Ne(i),s),{totalListHeight:i,totalListHeightChanged:s}},lt(Pt,cr),{singleton:!0}),sv=Ze(([{viewportHeight:e},{totalListHeight:t}])=>{const n=Y(!1),r=At(U(bt(n,e,t),Ae(([o])=>o),le(([,o,s])=>Math.max(0,o-s)),Mn(0),ct()),0);return{alignToBottom:n,paddingTopAddition:r}},lt(Pt,uu),{singleton:!0}),du=Ze(()=>({context:Y(null)})),iv=({itemBottom:e,itemTop:t,locationParams:{align:n,behavior:r,...o},viewportBottom:s,viewportTop:i})=>t<i?{...o,align:n??"start",behavior:r}:e>s?{...o,align:n??"end",behavior:r}:null,fu=Ze(([{gap:e,sizes:t,totalCount:n},{fixedFooterHeight:r,fixedHeaderHeight:o,headerHeight:s,scrollingInProgress:i,scrollTop:a,viewportHeight:l},{scrollToIndex:u}])=>{const d=Ye();return be(U(d,He(t,l,n,s,o,r,a),He(e),le(([[f,h,p,b,x,g,v,w],S])=>{const{align:N,behavior:k,calculateViewLocation:T=iv,done:E,...A}=f,j=eu(f,h,b-1),P=no(j,h.offsetTree,S)+x+g,L=P+sn(h.sizeTree,j)[1],$=w+g,V=w+p-v,M=T({itemBottom:L,itemTop:P,locationParams:{align:N,behavior:k,...A},viewportBottom:V,viewportTop:$});return M?E&&on(U(i,Ae(G=>!G),ir(xt(i)?1:2)),E):E&&E(),M}),Ae(f=>f!==null)),u),{scrollIntoView:d}},lt(bn,Pt,ro,cr,Hn),{singleton:!0});function hu(e){return e?e==="smooth"?"smooth":"auto":!1}const av=(e,t)=>typeof e=="function"?hu(e(t)):t&&hu(e),lv=Ze(([{listRefresh:e,totalCount:t,fixedItemSize:n,data:r},{atBottomState:o,isAtBottom:s},{scrollToIndex:i},{scrolledToInitialItem:a},{didMount:l,propsReady:u},{log:d},{scrollingInProgress:f},{context:h},{scrollIntoView:p}])=>{const b=Y(!1),x=Ye();let g=null;function v(k){Fe(i,{align:"end",behavior:k,index:"LAST"})}Qe(U(bt(U(Ne(t),ir(1)),l),He(Ne(b),s,a,f),le(([[k,T],E,A,j,P])=>{let L=T&&j,$="auto";return L&&($=av(E,A||P),L=L&&!!$),{followOutputBehavior:$,shouldFollow:L,totalCount:k}}),Ae(({shouldFollow:k})=>k)),({followOutputBehavior:k,totalCount:T})=>{g&&(g(),g=null),xt(n)?requestAnimationFrame(()=>{xt(d)("following output to ",{totalCount:T},Ft.DEBUG),v(k)}):g=on(e,()=>{xt(d)("following output to ",{totalCount:T},Ft.DEBUG),v(k),g=null})});function w(k){const T=on(o,E=>{k&&!E.atBottom&&E.notAtBottomBecause==="SIZE_INCREASED"&&!g&&(xt(d)("scrolling to bottom due to increased size",{},Ft.DEBUG),v("auto"))});setTimeout(T,100)}Qe(U(bt(Ne(b),t,u),Ae(([k,,T])=>k&&T),vn(({value:k},[,T])=>({refreshed:k===T,value:T}),{refreshed:!1,value:0}),Ae(({refreshed:k})=>k),He(b,t)),([,k])=>{xt(a)&&w(k!==!1)}),Qe(x,()=>{w(xt(b)!==!1)}),Qe(bt(Ne(b),o),([k,T])=>{k&&!T.atBottom&&T.notAtBottomBecause==="VIEWPORT_HEIGHT_DECREASING"&&v("auto")});const S=Y(null),N=Ye();return be(Li(U(Ne(r),le(k=>{var T;return(T=k==null?void 0:k.length)!=null?T:0})),U(Ne(t))),N),Qe(U(bt(U(N,ir(1)),l),He(Ne(S),a,f,h),le(([[k,T],E,A,j,P])=>T&&A&&(E==null?void 0:E({context:P,totalCount:k,scrollingInProgress:j}))),Ae(k=>!!k),Mn(0)),k=>{g&&(g(),g=null),xt(n)?requestAnimationFrame(()=>{xt(d)("scrolling into view",{}),Fe(p,k)}):g=on(e,()=>{xt(d)("scrolling into view",{}),Fe(p,k),g=null})}),{autoscrollToBottom:x,followOutput:b,scrollIntoViewOnChange:S}},lt(bn,ao,ro,oo,Wn,Hn,Pt,du,fu)),cv=Ze(([{data:e,firstItemIndex:t,gap:n,sizes:r},{initialTopMostItemIndex:o},{initialItemCount:s,listState:i},{didMount:a}])=>(be(U(a,He(s),Ae(([,l])=>l!==0),He(o,r,t,n,e),le(([[,l],u,d,f,h,p=[]])=>lu(l,u,d,f,h,p))),i),{}),lt(bn,oo,cr,Wn),{singleton:!0}),uv=Ze(([{didMount:e},{scrollTo:t},{listState:n}])=>{const r=Y(0);return Qe(U(e,He(r),Ae(([,o])=>o!==0),le(([,o])=>({top:o}))),o=>{on(U(n,ir(1),Ae(s=>s.items.length>1)),()=>{requestAnimationFrame(()=>{Fe(t,o)})})}),{initialScrollTop:r}},lt(Wn,Pt,cr),{singleton:!0}),pu=Ze(([{scrollVelocity:e}])=>{const t=Y(!1),n=Ye(),r=Y(!1);return be(U(e,He(r,t,n),Ae(([o,s])=>!!s),le(([o,s,i,a])=>{const{enter:l,exit:u}=s;if(i){if(u(o,a))return!1}else if(l(o,a))return!0;return i}),ct()),t),Qe(U(bt(t,e,n),He(r)),([[o,s,i],a])=>{o&&a&&a.change&&a.change(s,i)}),{isSeeking:t,scrollSeekConfiguration:r,scrollSeekRangeChanged:n,scrollVelocity:e}},lt(ao),{singleton:!0}),Xi=Ze(([{scrollContainerState:e,scrollTo:t}])=>{const n=Ye(),r=Ye(),o=Ye(),s=Y(!1),i=Y(void 0);return be(U(bt(n,r),le(([{scrollHeight:a,scrollTop:l,viewportHeight:u},{offsetTop:d}])=>({scrollHeight:a,scrollTop:Math.max(0,l-d),viewportHeight:u}))),e),be(U(t,He(r),le(([a,{offsetTop:l}])=>({...a,top:a.top+l}))),o),{customScrollParent:i,useWindowScroll:s,windowScrollContainerState:n,windowScrollTo:o,windowViewportRect:r}},lt(Pt)),dv=Ze(([{sizeRanges:e,sizes:t},{headerHeight:n,scrollTop:r},{initialTopMostItemIndex:o},{didMount:s},{useWindowScroll:i,windowScrollContainerState:a,windowViewportRect:l}])=>{const u=Ye(),d=Y(void 0),f=Y(null),h=Y(null);return be(a,f),be(l,h),Qe(U(u,He(t,r,i,f,h,n)),([p,b,x,g,v,w,S])=>{const N=Gx(b.sizeTree);g&&v!==null&&w!==null&&(x=v.scrollTop-w.offsetTop),x-=S,p({ranges:N,scrollTop:x})}),be(U(d,Ae(Mi),le(fv)),o),be(U(s,He(d),Ae(([,p])=>p!==void 0),ct(),le(([,p])=>p.ranges)),e),{getState:u,restoreStateFrom:d}},lt(bn,Pt,oo,Wn,Xi));function fv(e){return{align:"start",index:0,offset:e.scrollTop}}const hv=Ze(([{topItemsIndexes:e}])=>{const t=Y(0);return be(U(t,Ae(n=>n>=0),le(n=>Array.from({length:n}).map((r,o)=>o))),e),{topItemCount:t}},lt(cr));function mu(e){let t=!1,n;return()=>(t||(t=!0,n=e()),n)}const pv=mu(()=>/iP(ad|od|hone)/i.test(navigator.userAgent)&&/WebKit/i.test(navigator.userAgent)),mv=Ze(([{deviation:e,scrollBy:t,scrollingInProgress:n,scrollTop:r},{isAtBottom:o,isScrolling:s,lastJumpDueToItemResize:i,scrollDirection:a},{listState:l},{beforeUnshiftWith:u,gap:d,shiftWithOffset:f,sizes:h},{log:p},{recalcInProgress:b}])=>{const x=zt(U(l,He(i),vn(([,v,w,S],[{bottom:N,items:k,offsetBottom:T,totalCount:E},A])=>{const j=N+T;let P=0;return w===E&&v.length>0&&k.length>0&&(k[0].originalIndex===0&&v[0].originalIndex===0||(P=j-S,P!==0&&(P+=A))),[P,k,E,j]},[0,[],0,0]),Ae(([v])=>v!==0),He(r,a,n,o,p,b),Ae(([,v,w,S,,,N])=>!N&&!S&&v!==0&&w===so),le(([[v],,,,,w])=>(w("Upward scrolling compensation",{amount:v},Ft.DEBUG),v))));function g(v){v>0?(Fe(t,{behavior:"auto",top:-v}),Fe(e,0)):(Fe(e,0),Fe(t,{behavior:"auto",top:-v}))}return Qe(U(x,He(e,s)),([v,w,S])=>{S&&pv()?Fe(e,w-v):g(-v)}),Qe(U(bt(At(s,!1),e,b),Ae(([v,w,S])=>!v&&!S&&w!==0),le(([v,w])=>w),Mn(1)),g),be(U(f,le(v=>({top:-v}))),t),Qe(U(u,He(h,d),le(([v,{groupIndices:w,lastSize:S,sizeTree:N},k])=>{function T(E){return E*(S+k)}if(w.length===0)return T(v);{let E=0;const A=eo(N,0);let j=0,P=0;for(;j<v;){j++,E+=A;let L=w.length===P+1?1/0:w[P+1]-w[P]-1;j+L>v&&(E-=A,L=v-j+1),j+=L,E+=T(L),P++}return E}})),v=>{Fe(e,v),requestAnimationFrame(()=>{Fe(t,{top:v}),requestAnimationFrame(()=>{Fe(e,0),Fe(b,!1)})})}),{deviation:e}},lt(Pt,ao,cr,bn,Hn,Ui)),gv=Ze(([e,t,n,r,o,s,i,a,l,u,d])=>({...e,...t,...n,...r,...o,...s,...i,...a,...l,...u,...d}),lt(Gi,cv,Wn,pu,uu,uv,sv,Xi,fu,Hn,du)),gu=Ze(([{data:e,defaultItemSize:t,firstItemIndex:n,fixedItemSize:r,gap:o,groupIndices:s,itemSize:i,sizeRanges:a,sizes:l,statefulTotalCount:u,totalCount:d,trackItemSizes:f},{initialItemFinalLocationReached:h,initialTopMostItemIndex:p,scrolledToInitialItem:b},x,g,v,{listState:w,topItemsIndexes:S,...N},{scrollToIndex:k},T,{topItemCount:E},{groupCounts:A},j])=>(be(N.rangeChanged,j.scrollSeekRangeChanged),be(U(j.windowViewportRect,le(P=>P.visibleHeight)),x.viewportHeight),{data:e,defaultItemHeight:t,firstItemIndex:n,fixedItemHeight:r,gap:o,groupCounts:A,initialItemFinalLocationReached:h,initialTopMostItemIndex:p,scrolledToInitialItem:b,sizeRanges:a,topItemCount:E,topItemsIndexes:S,totalCount:d,...v,groupIndices:s,itemSize:i,listState:w,scrollToIndex:k,statefulTotalCount:u,trackItemSizes:f,...N,...j,...x,sizes:l,...g}),lt(bn,oo,Pt,dv,lv,cr,ro,mv,hv,nu,gv));function xv(e,t){const n={},r={};let o=0;const s=e.length;for(;o<s;)r[e[o]]=1,o+=1;for(const i in t)Object.hasOwn(r,i)||(n[i]=t[i]);return n}const es=typeof document<"u"?y.useLayoutEffect:y.useEffect;function xu(e,t,n){const r=Object.keys(t.required||{}),o=Object.keys(t.optional||{}),s=Object.keys(t.methods||{}),i=Object.keys(t.events||{}),a=y.createContext({});function l(g,v){g.propsReady&&Fe(g.propsReady,!1);for(const w of r){const S=g[t.required[w]];Fe(S,v[w])}for(const w of o)if(w in v){const S=g[t.optional[w]];Fe(S,v[w])}g.propsReady&&Fe(g.propsReady,!0)}function u(g){return s.reduce((v,w)=>(v[w]=S=>{const N=g[t.methods[w]];Fe(N,S)},v),{})}function d(g){return i.reduce((v,w)=>(v[w]=Px(g[t.events[w]]),v),{})}const f=y.forwardRef((g,v)=>{const{children:w,...S}=g,[N]=y.useState(()=>Ko(Mx(e),E=>{l(E,S)})),[k]=y.useState(Bc(d,N));es(()=>{for(const E of i)E in S&&Qe(k[E],S[E]);return()=>{Object.values(k).map(Di)}},[S,k,N]),es(()=>{l(N,S)}),y.useImperativeHandle(v,$c(u(N)));const T=n;return c.jsx(a.Provider,{value:N,children:n?c.jsx(T,{...xv([...r,...o,...i],S),children:w}):w})}),h=g=>{const v=y.useContext(a);return y.useCallback(w=>{Fe(v[g],w)},[v,g])},p=g=>{const v=y.useContext(a)[g],w=y.useCallback(S=>Qe(v,S),[v]);return y.useSyncExternalStore(w,()=>xt(v),()=>xt(v))},b=g=>{const v=y.useContext(a)[g],[w,S]=y.useState(Bc(xt,v));return es(()=>Qe(v,N=>{N!==w&&S($c(N))}),[v,w]),w},x=y.version.startsWith("18")?p:b;return{Component:f,useEmitter:(g,v)=>{const w=y.useContext(a)[g];es(()=>Qe(w,v),[v,w])},useEmitterValue:x,usePublisher:h}}const vu=y.createContext(void 0),bu=y.createContext(void 0),wu=typeof document<"u"?y.useLayoutEffect:y.useEffect;function Ji(e){return"self"in e}function vv(e){return"body"in e}function yu(e,t,n,r=_r,o,s){const i=y.useRef(null),a=y.useRef(null),l=y.useRef(null),u=y.useCallback(h=>{let p,b,x;const g=h.target;if(vv(g)||Ji(g)){const w=Ji(g)?g:g.defaultView;x=s?w.scrollX:w.scrollY,p=s?w.document.documentElement.scrollWidth:w.document.documentElement.scrollHeight,b=s?w.innerWidth:w.innerHeight}else x=s?g.scrollLeft:g.scrollTop,p=s?g.scrollWidth:g.scrollHeight,b=s?g.offsetWidth:g.offsetHeight;const v=()=>{e({scrollHeight:p,scrollTop:Math.max(x,0),viewportHeight:b})};h.suppressFlushSync?v():ai.flushSync(v),a.current!==null&&(x===a.current||x<=0||x===p-b)&&(a.current=null,t(!0),l.current&&(clearTimeout(l.current),l.current=null))},[e,t,s]);y.useEffect(()=>{const h=o||i.current;return r(o||i.current),u({suppressFlushSync:!0,target:h}),h.addEventListener("scroll",u,{passive:!0}),()=>{r(null),h.removeEventListener("scroll",u)}},[i,u,n,r,o]);function d(h){const p=i.current;if(!p||(s?"offsetWidth"in p&&p.offsetWidth===0:"offsetHeight"in p&&p.offsetHeight===0))return;const b=h.behavior==="smooth";let x,g,v;Ji(p)?(g=Math.max(Un(p.document.documentElement,s?"width":"height"),s?p.document.documentElement.scrollWidth:p.document.documentElement.scrollHeight),x=s?p.innerWidth:p.innerHeight,v=s?window.scrollX:window.scrollY):(g=p[s?"scrollWidth":"scrollHeight"],x=Un(p,s?"width":"height"),v=p[s?"scrollLeft":"scrollTop"]);const w=g-x;if(h.top=Math.ceil(Math.max(Math.min(w,h.top),0)),ou(x,g)||h.top===v){e({scrollHeight:g,scrollTop:v,viewportHeight:x}),b&&t(!0);return}b?(a.current=h.top,l.current&&clearTimeout(l.current),l.current=setTimeout(()=>{l.current=null,a.current=null,t(!0)},1e3)):a.current=null,s&&(h={behavior:h.behavior,left:h.top}),p.scrollTo(h)}function f(h){s&&(h={behavior:h.behavior,left:h.top}),i.current.scrollBy(h)}return{scrollByCallback:f,scrollerRef:i,scrollToCallback:d}}const Zi="-webkit-sticky",Su="sticky",Qi=mu(()=>{if(typeof document>"u")return Su;const e=document.createElement("div");return e.style.position=Zi,e.style.position===Zi?Zi:Su});function ea(e){return e}const bv=Ze(()=>{const e=Y(a=>`Item ${a}`),t=Y(a=>`Group ${a}`),n=Y({}),r=Y(ea),o=Y("div"),s=Y(_r),i=(a,l=null)=>At(U(n,le(u=>u[a]),ct()),l);return{components:n,computeItemKey:r,EmptyPlaceholder:i("EmptyPlaceholder"),FooterComponent:i("Footer"),GroupComponent:i("Group","div"),groupContent:t,HeaderComponent:i("Header"),HeaderFooterTag:o,ItemComponent:i("Item","div"),itemContent:e,ListComponent:i("List","div"),ScrollerComponent:i("Scroller","div"),scrollerRef:s,ScrollSeekPlaceholder:i("ScrollSeekPlaceholder"),TopItemListComponent:i("TopItemList")}}),wv=Ze(([e,t])=>({...e,...t}),lt(gu,bv)),yv=({height:e})=>c.jsx("div",{style:{height:e}}),Sv={overflowAnchor:"none",position:Qi(),zIndex:1},Cu={overflowAnchor:"none"},Cv={...Cu,display:"inline-block",height:"100%"},ku=y.memo(function({showTopList:e=!1}){const t=Re("listState"),n=qt("sizeRanges"),r=Re("useWindowScroll"),o=Re("customScrollParent"),s=qt("windowScrollContainerState"),i=qt("scrollContainerState"),a=o||r?s:i,l=Re("itemContent"),u=Re("context"),d=Re("groupContent"),f=Re("trackItemSizes"),h=Re("itemSize"),p=Re("log"),b=qt("gap"),x=Re("horizontalDirection"),{callbackRef:g}=$x(n,h,f,e?_r:a,p,b,o,x,Re("skipAnimationFrameInResizeObserver")),[v,w]=y.useState(0);ta("deviation",M=>{v!==M&&w(M)});const S=Re("EmptyPlaceholder"),N=Re("ScrollSeekPlaceholder")||yv,k=Re("ListComponent"),T=Re("ItemComponent"),E=Re("GroupComponent"),A=Re("computeItemKey"),j=Re("isSeeking"),P=Re("groupIndices").length>0,L=Re("alignToBottom"),$=Re("initialItemFinalLocationReached"),V=e?{}:{boxSizing:"border-box",...x?{display:"inline-block",height:"100%",marginLeft:v!==0?v:L?"auto":0,paddingLeft:t.offsetTop,paddingRight:t.offsetBottom,whiteSpace:"nowrap"}:{marginTop:v!==0?v:L?"auto":0,paddingBottom:t.offsetBottom,paddingTop:t.offsetTop},...$?{}:{visibility:"hidden"}};return!e&&t.totalCount===0&&S?c.jsx(S,{..._t(S,u)}):c.jsx(k,{..._t(k,u),"data-testid":e?"virtuoso-top-item-list":"virtuoso-item-list",ref:g,style:V,children:(e?t.topItems:t.items).map(M=>{const G=M.originalIndex,K=A(G+t.firstItemIndex,M.data,u);return j?y.createElement(N,{..._t(N,u),height:M.size,index:M.index,key:K,type:M.type||"item",...M.type==="group"?{}:{groupIndex:M.groupIndex}}):M.type==="group"?y.createElement(E,{..._t(E,u),"data-index":G,"data-item-index":M.index,"data-known-size":M.size,key:K,style:Sv},d(M.index,u)):y.createElement(T,{..._t(T,u),...Ev(T,M.data),"data-index":G,"data-item-group-index":M.groupIndex,"data-item-index":M.index,"data-known-size":M.size,key:K,style:x?Cv:Cu},P?l(M.index,M.groupIndex,M.data,u):l(M.index,M.data,u))})})}),kv={height:"100%",outline:"none",overflowY:"auto",position:"relative",WebkitOverflowScrolling:"touch"},Tv={outline:"none",overflowX:"auto",position:"relative"},ts=e=>({height:"100%",position:"absolute",top:0,width:"100%",...e?{display:"flex",flexDirection:"column"}:{}}),Iv={position:Qi(),top:0,width:"100%",zIndex:1};function _t(e,t){if(typeof e!="string")return{context:t}}function Ev(e,t){return{item:typeof e=="string"?void 0:t}}const Nv=y.memo(function(){const e=Re("HeaderComponent"),t=qt("headerHeight"),n=Re("HeaderFooterTag"),r=ar(y.useMemo(()=>s=>{t(Un(s,"height"))},[t]),!0,Re("skipAnimationFrameInResizeObserver")),o=Re("context");return e?c.jsx(n,{ref:r,children:c.jsx(e,{..._t(e,o)})}):null}),Av=y.memo(function(){const e=Re("FooterComponent"),t=qt("footerHeight"),n=Re("HeaderFooterTag"),r=ar(y.useMemo(()=>s=>{t(Un(s,"height"))},[t]),!0,Re("skipAnimationFrameInResizeObserver")),o=Re("context");return e?c.jsx(n,{ref:r,children:c.jsx(e,{..._t(e,o)})}):null});function Tu({useEmitter:e,useEmitterValue:t,usePublisher:n}){return y.memo(function({children:r,style:o,context:s,...i}){const a=n("scrollContainerState"),l=t("ScrollerComponent"),u=n("smoothScrollTargetReached"),d=t("scrollerRef"),f=t("horizontalDirection")||!1,{scrollByCallback:h,scrollerRef:p,scrollToCallback:b}=yu(a,u,l,d,void 0,f);return e("scrollTo",b),e("scrollBy",h),c.jsx(l,{"data-testid":"virtuoso-scroller","data-virtuoso-scroller":!0,ref:p,style:{...f?Tv:kv,...o},tabIndex:0,...i,..._t(l,s),children:r})})}function Iu({useEmitter:e,useEmitterValue:t,usePublisher:n}){return y.memo(function({children:r,style:o,context:s,...i}){const a=n("windowScrollContainerState"),l=t("ScrollerComponent"),u=n("smoothScrollTargetReached"),d=t("totalListHeight"),f=t("deviation"),h=t("customScrollParent"),p=y.useRef(null),b=t("scrollerRef"),{scrollByCallback:x,scrollerRef:g,scrollToCallback:v}=yu(a,u,l,b,h);return wu(()=>{var w;return g.current=h||((w=p.current)==null?void 0:w.ownerDocument.defaultView),()=>{g.current=null}},[g,h]),e("windowScrollTo",v),e("scrollBy",x),c.jsx(l,{ref:p,"data-virtuoso-scroller":!0,style:{position:"relative",...o,...d!==0?{height:d+f}:{}},...i,..._t(l,s),children:r})})}const _v=({children:e})=>{const t=y.useContext(vu),n=qt("viewportHeight"),r=qt("fixedItemHeight"),o=Re("alignToBottom"),s=Re("horizontalDirection"),i=y.useMemo(()=>Fc(n,l=>Un(l,s?"width":"height")),[n,s]),a=ar(i,!0,Re("skipAnimationFrameInResizeObserver"));return y.useEffect(()=>{t&&(n(t.viewportHeight),r(t.itemHeight))},[t,n,r]),c.jsx("div",{"data-viewport-type":"element",ref:a,style:ts(o),children:e})},jv=({children:e})=>{const t=y.useContext(vu),n=qt("windowViewportRect"),r=qt("fixedItemHeight"),o=Re("customScrollParent"),s=Wc(n,o,Re("skipAnimationFrameInResizeObserver")),i=Re("alignToBottom");return y.useEffect(()=>{t&&(r(t.itemHeight),n({offsetTop:0,visibleHeight:t.viewportHeight,visibleWidth:100}))},[t,n,r]),c.jsx("div",{"data-viewport-type":"window",ref:s,style:ts(i),children:e})},Rv=({children:e})=>{const t=Re("TopItemListComponent")||"div",n=Re("headerHeight"),r={...Iv,marginTop:`${n}px`},o=Re("context");return c.jsx(t,{style:r,..._t(t,o),children:e})},Pv=y.memo(function(e){const t=Re("useWindowScroll"),n=Re("topItemsIndexes").length>0,r=Re("customScrollParent"),o=Re("context");return c.jsxs(r||t?Dv:Mv,{...e,context:o,children:[n&&c.jsx(Rv,{children:c.jsx(ku,{showTopList:!0})}),c.jsxs(r||t?jv:_v,{children:[c.jsx(Nv,{}),c.jsx(ku,{}),c.jsx(Av,{})]})]})}),{Component:Ov,useEmitter:ta,useEmitterValue:Re,usePublisher:qt}=xu(wv,{required:{},optional:{restoreStateFrom:"restoreStateFrom",context:"context",followOutput:"followOutput",scrollIntoViewOnChange:"scrollIntoViewOnChange",itemContent:"itemContent",groupContent:"groupContent",overscan:"overscan",increaseViewportBy:"increaseViewportBy",totalCount:"totalCount",groupCounts:"groupCounts",topItemCount:"topItemCount",firstItemIndex:"firstItemIndex",initialTopMostItemIndex:"initialTopMostItemIndex",components:"components",atBottomThreshold:"atBottomThreshold",atTopThreshold:"atTopThreshold",computeItemKey:"computeItemKey",defaultItemHeight:"defaultItemHeight",fixedItemHeight:"fixedItemHeight",itemSize:"itemSize",scrollSeekConfiguration:"scrollSeekConfiguration",headerFooterTag:"HeaderFooterTag",data:"data",initialItemCount:"initialItemCount",initialScrollTop:"initialScrollTop",alignToBottom:"alignToBottom",useWindowScroll:"useWindowScroll",customScrollParent:"customScrollParent",scrollerRef:"scrollerRef",logLevel:"logLevel",horizontalDirection:"horizontalDirection",skipAnimationFrameInResizeObserver:"skipAnimationFrameInResizeObserver"},methods:{scrollToIndex:"scrollToIndex",scrollIntoView:"scrollIntoView",scrollTo:"scrollTo",scrollBy:"scrollBy",autoscrollToBottom:"autoscrollToBottom",getState:"getState"},events:{isScrolling:"isScrolling",endReached:"endReached",startReached:"startReached",rangeChanged:"rangeChanged",atBottomStateChange:"atBottomStateChange",atTopStateChange:"atTopStateChange",totalListHeightChanged:"totalListHeightChanged",itemsRendered:"itemsRendered",groupIndices:"groupIndices"}},Pv),Mv=Tu({useEmitter:ta,useEmitterValue:Re,usePublisher:qt}),Dv=Iu({useEmitter:ta,useEmitterValue:Re,usePublisher:qt}),Lv=Ov;lt(gu,Ze(()=>{const e=Y(u=>c.jsxs("td",{children:["Item $",u]})),t=Y(null),n=Y(u=>c.jsxs("td",{colSpan:1e3,children:["Group ",u]})),r=Y(null),o=Y(null),s=Y({}),i=Y(ea),a=Y(_r),l=(u,d=null)=>At(U(s,le(f=>f[u]),ct()),d);return{components:s,computeItemKey:i,context:t,EmptyPlaceholder:l("EmptyPlaceholder"),FillerRow:l("FillerRow"),fixedFooterContent:o,fixedHeaderContent:r,itemContent:e,groupContent:n,ScrollerComponent:l("Scroller","div"),scrollerRef:a,ScrollSeekPlaceholder:l("ScrollSeekPlaceholder"),TableBodyComponent:l("TableBody","tbody"),TableComponent:l("Table","table"),TableFooterComponent:l("TableFoot","tfoot"),TableHeadComponent:l("TableHead","thead"),TableRowComponent:l("TableRow","tr"),GroupComponent:l("Group","tr")}})),Qi();const Eu={bottom:0,itemHeight:0,items:[],itemWidth:0,offsetBottom:0,offsetTop:0,top:0},$v={bottom:0,itemHeight:0,items:[{index:0}],itemWidth:0,offsetBottom:0,offsetTop:0,top:0},{ceil:Nu,floor:ns,max:lo,min:na,round:Au}=Math;function _u(e,t,n){return Array.from({length:t-e+1}).map((r,o)=>({data:n===null?null:n[o+e],index:o+e}))}function Fv(e){return{...$v,items:e}}function rs(e,t){return e&&e.width===t.width&&e.height===t.height}function Bv(e,t){return e&&e.column===t.column&&e.row===t.row}const zv=Ze(([{increaseViewportBy:e,listBoundary:t,overscan:n,visibleRange:r},{footerHeight:o,headerHeight:s,scrollBy:i,scrollContainerState:a,scrollTo:l,scrollTop:u,smoothScrollTargetReached:d,viewportHeight:f},h,p,{didMount:b,propsReady:x},{customScrollParent:g,useWindowScroll:v,windowScrollContainerState:w,windowScrollTo:S,windowViewportRect:N},k])=>{const T=Y(0),E=Y(0),A=Y(Eu),j=Y({height:0,width:0}),P=Y({height:0,width:0}),L=Ye(),$=Ye(),V=Y(0),M=Y(null),G=Y({column:0,row:0}),K=Ye(),W=Ye(),z=Y(!1),B=Y(0),ue=Y(!0),D=Y(!1),te=Y(!1);Qe(U(b,He(B),Ae(([O,X])=>!!X)),()=>{Fe(ue,!1)}),Qe(U(bt(b,ue,P,j,B,D),Ae(([O,X,ne,pe,,se])=>O&&!X&&ne.height!==0&&pe.height!==0&&!se)),([,,,,O])=>{Fe(D,!0),Ki(1,()=>{Fe(L,O)}),on(U(u),()=>{Fe(t,[0,0]),Fe(ue,!0)})}),be(U(W,Ae(O=>O!=null&&O.scrollTop>0),xn(0)),E),Qe(U(b,He(W),Ae(([,O])=>O!=null)),([,O])=>{O&&(Fe(j,O.viewport),Fe(P,O.item),Fe(G,O.gap),O.scrollTop>0&&(Fe(z,!0),on(U(u,ir(1)),X=>{Fe(z,!1)}),Fe(l,{top:O.scrollTop})))}),be(U(j,le(({height:O})=>O)),f),be(U(bt(Ne(j,rs),Ne(P,rs),Ne(G,(O,X)=>O&&O.column===X.column&&O.row===X.row),Ne(u)),le(([O,X,ne,pe])=>({gap:ne,item:X,scrollTop:pe,viewport:O}))),K),be(U(bt(Ne(T),r,Ne(G,Bv),Ne(P,rs),Ne(j,rs),Ne(M),Ne(E),Ne(z),Ne(ue),Ne(B)),Ae(([,,,,,,,O])=>!O),le(([O,[X,ne],pe,se,me,et,tt,,Pe,Ve])=>{const{column:ut,row:nt}=pe,{height:Ke,width:vt}=se,{width:Q}=me;if(tt===0&&(O===0||Q===0))return Eu;if(vt===0){const ft=qi(Ve,O),It=ft+Math.max(tt-1,0);return Fv(_u(ft,It,et))}const ie=ju(Q,vt,ut);let xe,Ce;Pe?X===0&&ne===0&&tt>0?(xe=0,Ce=tt-1):(xe=ie*ns((X+nt)/(Ke+nt)),Ce=ie*Nu((ne+nt)/(Ke+nt))-1,Ce=na(O-1,lo(Ce,ie-1)),xe=na(Ce,lo(0,xe))):(xe=0,Ce=-1);const ve=_u(xe,Ce,et),{bottom:Oe,top:at}=Ru(me,pe,se,ve),Me=Nu(O/ie),st=Me*Ke+(Me-1)*nt-Oe;return{bottom:Oe,itemHeight:Ke,items:ve,itemWidth:vt,offsetBottom:st,offsetTop:at,top:at}})),A),be(U(M,Ae(O=>O!==null),le(O=>O.length)),T),be(U(bt(j,P,A,G),Ae(([O,X,{items:ne}])=>ne.length>0&&X.height!==0&&O.height!==0),le(([O,X,{items:ne},pe])=>{const{bottom:se,top:me}=Ru(O,pe,X,ne);return[me,se]}),ct(to)),t);const he=Y(!1);be(U(u,He(he),le(([O,X])=>X||O!==0)),he);const we=zt(U(bt(A,T),Ae(([{items:O}])=>O.length>0),He(he),Ae(([[O,X],ne])=>{const pe=O.items[O.items.length-1].index===X-1;return(ne||O.bottom>0&&O.itemHeight>0&&O.offsetBottom===0&&O.items.length===X)&&pe}),le(([[,O]])=>O-1),ct())),ye=zt(U(Ne(A),Ae(({items:O})=>O.length>0&&O[0].index===0),xn(0),ct())),Se=zt(U(Ne(A),He(z),Ae(([{items:O},X])=>O.length>0&&!X),le(([{items:O}])=>({endIndex:O[O.length-1].index,startIndex:O[0].index})),ct(Jc),Mn(0)));be(Se,p.scrollSeekRangeChanged),be(U(L,He(j,P,T,G),le(([O,X,ne,pe,se])=>{const me=ru(O),{align:et,behavior:tt,offset:Pe}=me;let Ve=me.index;Ve==="LAST"&&(Ve=pe-1),Ve=lo(0,Ve,na(pe-1,Ve));let ut=ra(X,se,ne,Ve);return et==="end"?ut=Au(ut-X.height+ne.height):et==="center"&&(ut=Au(ut-X.height/2+ne.height/2)),Pe&&(ut+=Pe),{behavior:tt,top:ut}})),l);const q=At(U(A,le(O=>O.offsetBottom+O.bottom)),0);return be(U(N,le(O=>({height:O.visibleHeight,width:O.visibleWidth}))),j),{customScrollParent:g,data:M,deviation:V,footerHeight:o,gap:G,headerHeight:s,increaseViewportBy:e,initialItemCount:E,itemDimensions:P,overscan:n,restoreStateFrom:W,scrollBy:i,scrollContainerState:a,scrollHeight:$,scrollTo:l,scrollToIndex:L,scrollTop:u,smoothScrollTargetReached:d,totalCount:T,useWindowScroll:v,viewportDimensions:j,windowScrollContainerState:w,windowScrollTo:S,windowViewportRect:N,...p,gridState:A,horizontalDirection:te,initialTopMostItemIndex:B,totalListHeight:q,...h,endReached:we,propsReady:x,rangeChanged:Se,startReached:ye,stateChanged:K,stateRestoreInProgress:z,...k}},lt(Gi,Pt,ao,pu,Wn,Xi,Hn));function ju(e,t,n){return lo(1,ns((e+n)/(ns(t)+n)))}function Ru(e,t,n,r){const{height:o}=n;if(o===void 0||r.length===0)return{bottom:0,top:0};const s=ra(e,t,n,r[0].index);return{bottom:ra(e,t,n,r[r.length-1].index)+o,top:s}}function ra(e,t,n,r){const o=ju(e.width,n.width,t.column),s=ns(r/o),i=s*n.height+lo(0,s-1)*t.row;return i>0?i+t.row:i}const Hv=Ze(()=>{const e=Y(f=>`Item ${f}`),t=Y({}),n=Y(null),r=Y("virtuoso-grid-item"),o=Y("virtuoso-grid-list"),s=Y(ea),i=Y("div"),a=Y(_r),l=(f,h=null)=>At(U(t,le(p=>p[f]),ct()),h),u=Y(!1),d=Y(!1);return be(Ne(d),u),{components:t,computeItemKey:s,context:n,FooterComponent:l("Footer"),HeaderComponent:l("Header"),headerFooterTag:i,itemClassName:r,ItemComponent:l("Item","div"),itemContent:e,listClassName:o,ListComponent:l("List","div"),readyStateChanged:u,reportReadyState:d,ScrollerComponent:l("Scroller","div"),scrollerRef:a,ScrollSeekPlaceholder:l("ScrollSeekPlaceholder","div")}}),Uv=Ze(([e,t])=>({...e,...t}),lt(zv,Hv)),Wv=y.memo(function(){const e=dt("gridState"),t=dt("listClassName"),n=dt("itemClassName"),r=dt("itemContent"),o=dt("computeItemKey"),s=dt("isSeeking"),i=Gt("scrollHeight"),a=dt("ItemComponent"),l=dt("ListComponent"),u=dt("ScrollSeekPlaceholder"),d=dt("context"),f=Gt("itemDimensions"),h=Gt("gap"),p=dt("log"),b=dt("stateRestoreInProgress"),x=Gt("reportReadyState"),g=ar(y.useMemo(()=>v=>{const w=v.parentElement.parentElement.scrollHeight;i(w);const S=v.firstChild;if(S){const{height:N,width:k}=S.getBoundingClientRect();f({height:N,width:k})}h({column:Ou("column-gap",getComputedStyle(v).columnGap,p),row:Ou("row-gap",getComputedStyle(v).rowGap,p)})},[i,f,h,p]),!0,!1);return wu(()=>{e.itemHeight>0&&e.itemWidth>0&&x(!0)},[e]),b?null:c.jsx(l,{className:t,ref:g,..._t(l,d),"data-testid":"virtuoso-item-list",style:{paddingBottom:e.offsetBottom,paddingTop:e.offsetTop},children:e.items.map(v=>{const w=o(v.index,v.data,d);return s?c.jsx(u,{..._t(u,d),height:e.itemHeight,index:v.index,width:e.itemWidth},w):y.createElement(a,{..._t(a,d),className:n,"data-index":v.index,key:w},r(v.index,v.data,d))})})}),Vv=y.memo(function(){const e=dt("HeaderComponent"),t=Gt("headerHeight"),n=dt("headerFooterTag"),r=ar(y.useMemo(()=>s=>{t(Un(s,"height"))},[t]),!0,!1),o=dt("context");return e?c.jsx(n,{ref:r,children:c.jsx(e,{..._t(e,o)})}):null}),Kv=y.memo(function(){const e=dt("FooterComponent"),t=Gt("footerHeight"),n=dt("headerFooterTag"),r=ar(y.useMemo(()=>s=>{t(Un(s,"height"))},[t]),!0,!1),o=dt("context");return e?c.jsx(n,{ref:r,children:c.jsx(e,{..._t(e,o)})}):null}),qv=({children:e})=>{const t=y.useContext(bu),n=Gt("itemDimensions"),r=Gt("viewportDimensions"),o=ar(y.useMemo(()=>s=>{r(s.getBoundingClientRect())},[r]),!0,!1);return y.useEffect(()=>{t&&(r({height:t.viewportHeight,width:t.viewportWidth}),n({height:t.itemHeight,width:t.itemWidth}))},[t,r,n]),c.jsx("div",{ref:o,style:ts(!1),children:e})},Gv=({children:e})=>{const t=y.useContext(bu),n=Gt("windowViewportRect"),r=Gt("itemDimensions"),o=dt("customScrollParent"),s=Wc(n,o,!1);return y.useEffect(()=>{t&&(r({height:t.itemHeight,width:t.itemWidth}),n({offsetTop:0,visibleHeight:t.viewportHeight,visibleWidth:t.viewportWidth}))},[t,n,r]),c.jsx("div",{ref:s,style:ts(!1),children:e})},Yv=y.memo(function({...e}){const t=dt("useWindowScroll"),n=dt("customScrollParent"),r=n||t?Jv:Xv,o=n||t?Gv:qv,s=dt("context");return c.jsx(r,{...e,..._t(r,s),children:c.jsxs(o,{children:[c.jsx(Vv,{}),c.jsx(Wv,{}),c.jsx(Kv,{})]})})}),{useEmitter:Pu,useEmitterValue:dt,usePublisher:Gt}=xu(Uv,{optional:{context:"context",totalCount:"totalCount",overscan:"overscan",itemContent:"itemContent",components:"components",computeItemKey:"computeItemKey",data:"data",initialItemCount:"initialItemCount",scrollSeekConfiguration:"scrollSeekConfiguration",headerFooterTag:"headerFooterTag",listClassName:"listClassName",itemClassName:"itemClassName",useWindowScroll:"useWindowScroll",customScrollParent:"customScrollParent",scrollerRef:"scrollerRef",logLevel:"logLevel",restoreStateFrom:"restoreStateFrom",initialTopMostItemIndex:"initialTopMostItemIndex",increaseViewportBy:"increaseViewportBy"},methods:{scrollTo:"scrollTo",scrollBy:"scrollBy",scrollToIndex:"scrollToIndex"},events:{isScrolling:"isScrolling",endReached:"endReached",startReached:"startReached",rangeChanged:"rangeChanged",atBottomStateChange:"atBottomStateChange",atTopStateChange:"atTopStateChange",stateChanged:"stateChanged",readyStateChanged:"readyStateChanged"}},Yv),Xv=Tu({useEmitter:Pu,useEmitterValue:dt,usePublisher:Gt}),Jv=Iu({useEmitter:Pu,useEmitterValue:dt,usePublisher:Gt});function Ou(e,t,n){return t!=="normal"&&!(t!=null&&t.endsWith("px"))&&n(`${e} was not resolved to pixel value correctly`,t,Ft.WARN),t==="normal"?0:parseInt(t??"0",10)}const Zv=Io.cva("inline-flex items-center rounded-full border px-2.5 py-0.5 text-xs font-semibold transition-colors focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2",{variants:{variant:{default:"border-transparent bg-primary text-primary-foreground hover:bg-primary/80",secondary:"border-transparent bg-secondary text-secondary-foreground hover:bg-secondary/80",destructive:"border-transparent bg-destructive text-destructive-foreground hover:bg-destructive/80",outline:"text-foreground"}},defaultVariants:{variant:"default"}});function oa({className:e,variant:t,...n}){return c.jsx("div",{className:ee(Zv({variant:t}),e),...n})}function fe(e,t,{checkForDefaultPrevented:n=!0}={}){return function(o){if(e==null||e(o),n===!1||!o.defaultPrevented)return t==null?void 0:t(o)}}function Qv(e,t){const n=m.createContext(t),r=s=>{const{children:i,...a}=s,l=m.useMemo(()=>a,Object.values(a));return c.jsx(n.Provider,{value:l,children:i})};r.displayName=e+"Provider";function o(s){const i=m.useContext(n);if(i)return i;if(t!==void 0)return t;throw new Error(`\`${s}\` must be used within \`${e}\``)}return[r,o]}function wn(e,t=[]){let n=[];function r(s,i){const a=m.createContext(i),l=n.length;n=[...n,i];const u=f=>{var v;const{scope:h,children:p,...b}=f,x=((v=h==null?void 0:h[e])==null?void 0:v[l])||a,g=m.useMemo(()=>b,Object.values(b));return c.jsx(x.Provider,{value:g,children:p})};u.displayName=s+"Provider";function d(f,h){var x;const p=((x=h==null?void 0:h[e])==null?void 0:x[l])||a,b=m.useContext(p);if(b)return b;if(i!==void 0)return i;throw new Error(`\`${f}\` must be used within \`${s}\``)}return[u,d]}const o=()=>{const s=n.map(i=>m.createContext(i));return function(a){const l=(a==null?void 0:a[e])||s;return m.useMemo(()=>({[`__scope${e}`]:{...a,[e]:l}}),[a,l])}};return o.scopeName=e,[r,eb(o,...t)]}function eb(...e){const t=e[0];if(e.length===1)return t;const n=()=>{const r=e.map(o=>({useScope:o(),scopeName:o.scopeName}));return function(s){const i=r.reduce((a,{useScope:l,scopeName:u})=>{const f=l(s)[`__scope${u}`];return{...a,...f}},{});return m.useMemo(()=>({[`__scope${t.scopeName}`]:i}),[i])}};return n.scopeName=t.scopeName,n}var Ct=globalThis!=null&&globalThis.document?m.useLayoutEffect:()=>{},tb=m[" useInsertionEffect ".trim().toString()]||Ct;function ur({prop:e,defaultProp:t,onChange:n=()=>{},caller:r}){const[o,s,i]=nb({defaultProp:t,onChange:n}),a=e!==void 0,l=a?e:o;{const d=m.useRef(e!==void 0);m.useEffect(()=>{const f=d.current;f!==a&&console.warn(`${r} is changing from ${f?"controlled":"uncontrolled"} to ${a?"controlled":"uncontrolled"}. Components should not switch from controlled to uncontrolled (or vice versa). Decide between using a controlled or uncontrolled value for the lifetime of the component.`),d.current=a},[a,r])}const u=m.useCallback(d=>{var f;if(a){const h=rb(d)?d(e):d;h!==e&&((f=i.current)==null||f.call(i,h))}else s(d)},[a,e,s,i]);return[l,u]}function nb({defaultProp:e,onChange:t}){const[n,r]=m.useState(e),o=m.useRef(n),s=m.useRef(t);return tb(()=>{s.current=t},[t]),m.useEffect(()=>{var i;o.current!==n&&((i=s.current)==null||i.call(s,n),o.current=n)},[n,o]),[n,r,s]}function rb(e){return typeof e=="function"}function Mu(e,t){if(typeof e=="function")return e(t);e!=null&&(e.current=t)}function sa(...e){return t=>{let n=!1;const r=e.map(o=>{const s=Mu(o,t);return!n&&typeof s=="function"&&(n=!0),s});if(n)return()=>{for(let o=0;o<r.length;o++){const s=r[o];typeof s=="function"?s():Mu(e[o],null)}}}}function Ge(...e){return m.useCallback(sa(...e),e)}var ob=["a","button","div","form","h2","h3","img","input","label","li","nav","ol","p","select","span","svg","ul"],_e=ob.reduce((e,t)=>{const n=nr.createSlot(`Primitive.${t}`),r=m.forwardRef((o,s)=>{const{asChild:i,...a}=o,l=i?n:t;return typeof window<"u"&&(window[Symbol.for("radix-ui")]=!0),c.jsx(l,{...a,ref:s})});return r.displayName=`Primitive.${t}`,{...e,[t]:r}},{});function Du(e,t){e&&Eo.flushSync(()=>e.dispatchEvent(t))}function sb(e,t){return m.useReducer((n,r)=>t[n][r]??n,e)}var Ut=e=>{const{present:t,children:n}=e,r=ib(t),o=typeof n=="function"?n({present:r.isPresent}):m.Children.only(n),s=Ge(r.ref,ab(o));return typeof n=="function"||r.isPresent?m.cloneElement(o,{ref:s}):null};Ut.displayName="Presence";function ib(e){const[t,n]=m.useState(),r=m.useRef(null),o=m.useRef(e),s=m.useRef("none"),i=e?"mounted":"unmounted",[a,l]=sb(i,{mounted:{UNMOUNT:"unmounted",ANIMATION_OUT:"unmountSuspended"},unmountSuspended:{MOUNT:"mounted",ANIMATION_END:"unmounted"},unmounted:{MOUNT:"mounted"}});return m.useEffect(()=>{const u=os(r.current);s.current=a==="mounted"?u:"none"},[a]),Ct(()=>{const u=r.current,d=o.current;if(d!==e){const h=s.current,p=os(u);e?l("MOUNT"):p==="none"||(u==null?void 0:u.display)==="none"?l("UNMOUNT"):l(d&&h!==p?"ANIMATION_OUT":"UNMOUNT"),o.current=e}},[e,l]),Ct(()=>{if(t){let u;const d=t.ownerDocument.defaultView??window,f=p=>{const x=os(r.current).includes(CSS.escape(p.animationName));if(p.target===t&&x&&(l("ANIMATION_END"),!o.current)){const g=t.style.animationFillMode;t.style.animationFillMode="forwards",u=d.setTimeout(()=>{t.style.animationFillMode==="forwards"&&(t.style.animationFillMode=g)})}},h=p=>{p.target===t&&(s.current=os(r.current))};return t.addEventListener("animationstart",h),t.addEventListener("animationcancel",f),t.addEventListener("animationend",f),()=>{d.clearTimeout(u),t.removeEventListener("animationstart",h),t.removeEventListener("animationcancel",f),t.removeEventListener("animationend",f)}}else l("ANIMATION_END")},[t,l]),{isPresent:["mounted","unmountSuspended"].includes(a),ref:m.useCallback(u=>{r.current=u?getComputedStyle(u):null,n(u)},[])}}function os(e){return(e==null?void 0:e.animationName)||"none"}function ab(e){var r,o;let t=(r=Object.getOwnPropertyDescriptor(e.props,"ref"))==null?void 0:r.get,n=t&&"isReactWarning"in t&&t.isReactWarning;return n?e.ref:(t=(o=Object.getOwnPropertyDescriptor(e,"ref"))==null?void 0:o.get,n=t&&"isReactWarning"in t&&t.isReactWarning,n?e.props.ref:e.props.ref||e.ref)}var lb=m[" useId ".trim().toString()]||(()=>{}),cb=0;function yn(e){const[t,n]=m.useState(lb());return Ct(()=>{n(r=>r??String(cb++))},[e]),e||(t?`radix-${t}`:"")}var ss="Collapsible",[ub,Gk]=wn(ss),[db,ia]=ub(ss),Lu=m.forwardRef((e,t)=>{const{__scopeCollapsible:n,open:r,defaultOpen:o,disabled:s,onOpenChange:i,...a}=e,[l,u]=ur({prop:r,defaultProp:o??!1,onChange:i,caller:ss});return c.jsx(db,{scope:n,disabled:s,contentId:yn(),open:l,onOpenToggle:m.useCallback(()=>u(d=>!d),[u]),children:c.jsx(_e.div,{"data-state":la(l),"data-disabled":s?"":void 0,...a,ref:t})})});Lu.displayName=ss;var $u="CollapsibleTrigger",Fu=m.forwardRef((e,t)=>{const{__scopeCollapsible:n,...r}=e,o=ia($u,n);return c.jsx(_e.button,{type:"button","aria-controls":o.contentId,"aria-expanded":o.open||!1,"data-state":la(o.open),"data-disabled":o.disabled?"":void 0,disabled:o.disabled,...r,ref:t,onClick:fe(e.onClick,o.onOpenToggle)})});Fu.displayName=$u;var aa="CollapsibleContent",fb=m.forwardRef((e,t)=>{const{forceMount:n,...r}=e,o=ia(aa,e.__scopeCollapsible);return c.jsx(Ut,{present:n||o.open,children:({present:s})=>c.jsx(hb,{...r,ref:t,present:s})})});fb.displayName=aa;var hb=m.forwardRef((e,t)=>{const{__scopeCollapsible:n,present:r,children:o,...s}=e,i=ia(aa,n),[a,l]=m.useState(r),u=m.useRef(null),d=Ge(t,u),f=m.useRef(0),h=f.current,p=m.useRef(0),b=p.current,x=i.open||a,g=m.useRef(x),v=m.useRef(void 0);return m.useEffect(()=>{const w=requestAnimationFrame(()=>g.current=!1);return()=>cancelAnimationFrame(w)},[]),Ct(()=>{const w=u.current;if(w){v.current=v.current||{transitionDuration:w.style.transitionDuration,animationName:w.style.animationName},w.style.transitionDuration="0s",w.style.animationName="none";const S=w.getBoundingClientRect();f.current=S.height,p.current=S.width,g.current||(w.style.transitionDuration=v.current.transitionDuration,w.style.animationName=v.current.animationName),l(r)}},[i.open,r]),c.jsx(_e.div,{"data-state":la(i.open),"data-disabled":i.disabled?"":void 0,id:i.contentId,hidden:!x,...s,ref:d,style:{"--radix-collapsible-content-height":h?`${h}px`:void 0,"--radix-collapsible-content-width":b?`${b}px`:void 0,...e.style},children:x&&o})});function la(e){return e?"open":"closed"}var pb=Lu;const Bu=pb,zu=Fu,co=m.forwardRef(({className:e,...t},n)=>c.jsx("div",{ref:n,className:ee("rounded-lg border bg-card text-card-foreground shadow-sm",e),...t}));co.displayName="Card";const uo=m.forwardRef(({className:e,...t},n)=>c.jsx("div",{ref:n,className:ee("flex flex-col space-y-1.5 p-6",e),...t}));uo.displayName="CardHeader";const fo=m.forwardRef(({className:e,...t},n)=>c.jsx("h3",{ref:n,className:ee("text-2xl font-semibold leading-none tracking-tight",e),...t}));fo.displayName="CardTitle";const Hu=m.forwardRef(({className:e,...t},n)=>c.jsx("p",{ref:n,className:ee("text-sm text-muted-foreground",e),...t}));Hu.displayName="CardDescription";const is=m.forwardRef(({className:e,...t},n)=>c.jsx("div",{ref:n,className:ee("p-6 pt-0",e),...t}));is.displayName="CardContent";const Uu=m.forwardRef(({className:e,...t},n)=>c.jsx("div",{ref:n,className:ee("flex items-center p-6 pt-0",e),...t}));Uu.displayName="CardFooter";function Wu(){return{async:!1,baseUrl:null,breaks:!1,extensions:null,gfm:!0,headerIds:!0,headerPrefix:"",highlight:null,hooks:null,langPrefix:"language-",mangle:!0,pedantic:!1,renderer:null,sanitize:!1,sanitizer:null,silent:!1,smartypants:!1,tokenizer:null,walkTokens:null,xhtml:!1}}let dr=Wu();function mb(e){dr=e}const Vu=/[&<>"']/,gb=new RegExp(Vu.source,"g"),Ku=/[<>"']|&(?!(#\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\w+);)/,xb=new RegExp(Ku.source,"g"),vb={"&":"&","<":"<",">":">",'"':""","'":"'"},qu=e=>vb[e];function jt(e,t){if(t){if(Vu.test(e))return e.replace(gb,qu)}else if(Ku.test(e))return e.replace(xb,qu);return e}const bb=/&(#(?:\d+)|(?:#x[0-9A-Fa-f]+)|(?:\w+));?/ig;function Gu(e){return e.replace(bb,(t,n)=>(n=n.toLowerCase(),n==="colon"?":":n.charAt(0)==="#"?n.charAt(1)==="x"?String.fromCharCode(parseInt(n.substring(2),16)):String.fromCharCode(+n.substring(1)):""))}const wb=/(^|[^\[])\^/g;function ot(e,t){e=typeof e=="string"?e:e.source,t=t||"";const n={replace:(r,o)=>(o=o.source||o,o=o.replace(wb,"$1"),e=e.replace(r,o),n),getRegex:()=>new RegExp(e,t)};return n}const yb=/[^\w:]/g,Sb=/^$|^[a-z][a-z0-9+.-]*:|^[?#]/i;function Yu(e,t,n){if(e){let r;try{r=decodeURIComponent(Gu(n)).replace(yb,"").toLowerCase()}catch{return null}if(r.indexOf("javascript:")===0||r.indexOf("vbscript:")===0||r.indexOf("data:")===0)return null}t&&!Sb.test(n)&&(n=Ib(t,n));try{n=encodeURI(n).replace(/%25/g,"%")}catch{return null}return n}const as={},Cb=/^[^:]+:\/*[^/]*$/,kb=/^([^:]+:)[\s\S]*$/,Tb=/^([^:]+:\/*[^/]*)[\s\S]*$/;function Ib(e,t){as[" "+e]||(Cb.test(e)?as[" "+e]=e+"/":as[" "+e]=cs(e,"/",!0)),e=as[" "+e];const n=e.indexOf(":")===-1;return t.substring(0,2)==="//"?n?t:e.replace(kb,"$1")+t:t.charAt(0)==="/"?n?t:e.replace(Tb,"$1")+t:e+t}const ls={exec:function(){}};function Xu(e,t){const n=e.replace(/\|/g,(s,i,a)=>{let l=!1,u=i;for(;--u>=0&&a[u]==="\\";)l=!l;return l?"|":" |"}),r=n.split(/ \|/);let o=0;if(r[0].trim()||r.shift(),r.length>0&&!r[r.length-1].trim()&&r.pop(),r.length>t)r.splice(t);else for(;r.length<t;)r.push("");for(;o<r.length;o++)r[o]=r[o].trim().replace(/\\\|/g,"|");return r}function cs(e,t,n){const r=e.length;if(r===0)return"";let o=0;for(;o<r;){const s=e.charAt(r-o-1);if(s===t&&!n)o++;else if(s!==t&&n)o++;else break}return e.slice(0,r-o)}function Eb(e,t){if(e.indexOf(t[1])===-1)return-1;const n=e.length;let r=0,o=0;for(;o<n;o++)if(e[o]==="\\")o++;else if(e[o]===t[0])r++;else if(e[o]===t[1]&&(r--,r<0))return o;return-1}function Nb(e){e&&e.sanitize&&!e.silent&&console.warn("marked(): sanitize and sanitizer parameters are deprecated since version 0.7.0, should not be used and will be removed in the future. Read more here: https://marked.js.org/#/USING_ADVANCED.md#options")}function Ju(e,t){if(t<1)return"";let n="";for(;t>1;)t&1&&(n+=e),t>>=1,e+=e;return n+e}function Zu(e,t,n,r){const o=t.href,s=t.title?jt(t.title):null,i=e[1].replace(/\\([\[\]])/g,"$1");if(e[0].charAt(0)!=="!"){r.state.inLink=!0;const a={type:"link",raw:n,href:o,title:s,text:i,tokens:r.inlineTokens(i)};return r.state.inLink=!1,a}return{type:"image",raw:n,href:o,title:s,text:jt(i)}}function Ab(e,t){const n=e.match(/^(\s+)(?:```)/);if(n===null)return t;const r=n[1];return t.split(`
|
|
40
40
|
`).map(o=>{const s=o.match(/^\s+/);if(s===null)return o;const[i]=s;return i.length>=r.length?o.slice(r.length):o}).join(`
|
|
41
41
|
`)}class ca{constructor(t){this.options=t||dr}space(t){const n=this.rules.block.newline.exec(t);if(n&&n[0].length>0)return{type:"space",raw:n[0]}}code(t){const n=this.rules.block.code.exec(t);if(n){const r=n[0].replace(/^ {1,4}/gm,"");return{type:"code",raw:n[0],codeBlockStyle:"indented",text:this.options.pedantic?r:cs(r,`
|
|
@@ -1,23 +1,12 @@
|
|
|
1
|
-
import type {
|
|
2
|
-
export type HistoryPendingInterrupt =
|
|
3
|
-
id: string;
|
|
4
|
-
value: unknown;
|
|
5
|
-
} | null;
|
|
6
|
-
export type HydratedCheckpointSnapshot = {
|
|
7
|
-
messages: ChatMessage[];
|
|
8
|
-
checkpointId: string | null;
|
|
9
|
-
checkpointNs: string | null;
|
|
10
|
-
nextCursor: string | null;
|
|
11
|
-
nextCursorNs: string | null;
|
|
12
|
-
interrupt: HistoryPendingInterrupt;
|
|
13
|
-
};
|
|
1
|
+
import type { CheckpointSummary, HistoryPayload, HydratedCheckpointSnapshot, MessagesPayload, PendingInterrupt } from "@/types/api";
|
|
2
|
+
export type HistoryPendingInterrupt = PendingInterrupt;
|
|
14
3
|
export type HistoryHydrationResult = {
|
|
15
4
|
payload: MessagesPayload & {
|
|
16
5
|
nextCursorNs?: string | null;
|
|
17
|
-
pendingInterrupt?:
|
|
6
|
+
pendingInterrupt?: PendingInterrupt;
|
|
18
7
|
};
|
|
19
8
|
checkpoints: CheckpointSummary[];
|
|
20
|
-
interrupt:
|
|
9
|
+
interrupt: PendingInterrupt;
|
|
21
10
|
snapshots: Record<string, HydratedCheckpointSnapshot>;
|
|
22
11
|
};
|
|
23
12
|
export declare function buildSnapshotKey(checkpointId: string | null | undefined, checkpointNs: string | null | undefined): string;
|
package/dist/types/api.d.ts
CHANGED
|
@@ -71,6 +71,18 @@ export interface CheckpointSnapshot {
|
|
|
71
71
|
parentConfig?: Record<string, unknown> | null;
|
|
72
72
|
tasks?: PregelTask[] | null;
|
|
73
73
|
}
|
|
74
|
+
export type PendingInterrupt = {
|
|
75
|
+
id: string;
|
|
76
|
+
value: unknown;
|
|
77
|
+
} | null;
|
|
78
|
+
export interface HydratedCheckpointSnapshot {
|
|
79
|
+
checkpointId: string | null;
|
|
80
|
+
checkpointNs: string | null;
|
|
81
|
+
messages: ChatMessage[];
|
|
82
|
+
nextCursor: string | null;
|
|
83
|
+
nextCursorNs: string | null;
|
|
84
|
+
interrupt: PendingInterrupt;
|
|
85
|
+
}
|
|
74
86
|
export interface HistoryPayload {
|
|
75
87
|
version: "chat-history@1";
|
|
76
88
|
threadId: string;
|
|
@@ -84,10 +96,7 @@ export interface MessagesPayload {
|
|
|
84
96
|
hasMore?: boolean;
|
|
85
97
|
nextCursor?: string | null;
|
|
86
98
|
nextCursorNs?: string | null;
|
|
87
|
-
pendingInterrupt?:
|
|
88
|
-
id: string;
|
|
89
|
-
value: any;
|
|
90
|
-
} | null;
|
|
99
|
+
pendingInterrupt?: PendingInterrupt;
|
|
91
100
|
}
|
|
92
101
|
export interface StatePayload {
|
|
93
102
|
threadId: string;
|
|
@@ -300,18 +309,9 @@ export interface ThreadsContextValue {
|
|
|
300
309
|
persistThreadsCache: () => void;
|
|
301
310
|
hydrateFromCache: () => void;
|
|
302
311
|
}
|
|
303
|
-
export interface ThreadSnapshot {
|
|
312
|
+
export interface ThreadSnapshot extends HydratedCheckpointSnapshot {
|
|
304
313
|
threadId: string;
|
|
305
|
-
checkpointId?: string | null;
|
|
306
|
-
checkpointNs?: string | null;
|
|
307
|
-
messages: ChatMessage[];
|
|
308
314
|
hasMore?: boolean;
|
|
309
|
-
nextCursor?: string | null;
|
|
310
|
-
nextCursorNs?: string | null;
|
|
311
|
-
pendingInterrupt?: {
|
|
312
|
-
id: string;
|
|
313
|
-
value: any;
|
|
314
|
-
} | null;
|
|
315
315
|
}
|
|
316
316
|
export interface ThreadStateMetadata {
|
|
317
317
|
branchLabel?: string | null;
|
|
@@ -323,10 +323,7 @@ export interface ThreadStateMetadata {
|
|
|
323
323
|
export interface ThreadStateContextValue {
|
|
324
324
|
threadId: string | null;
|
|
325
325
|
messages: ChatMessage[];
|
|
326
|
-
interrupt:
|
|
327
|
-
id: string;
|
|
328
|
-
value: any;
|
|
329
|
-
} | null;
|
|
326
|
+
interrupt: PendingInterrupt;
|
|
330
327
|
checkpoint: {
|
|
331
328
|
id: string | null;
|
|
332
329
|
namespace: string | null;
|
package/package.json
CHANGED