@teodorruskvi/chat-core 0.1.52 → 0.1.53

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.umd.js CHANGED
@@ -4,6 +4,6 @@
4
4
  `):oe(e.content);if(e.value!==void 0)return oe(e.value)}return typeof e=="object"&&!Array.isArray(e)&&(e.type==="text"&&typeof e.text=="string"||typeof e.text=="string")?e.text:Array.isArray(e)&&e.length>0?oe(e[0]):e}function Vn(e){return e.replace(/[_-](\w)/g,(t,n)=>n?n.toUpperCase():"").replace(/^\w/,t=>t.toLowerCase())}function ae(e){return!e||typeof e!="object"?e:Array.isArray(e)?e.map(ae):Object.fromEntries(Object.entries(e).map(([t,n])=>[Vn(t),ae(n)]))}function We(e){var S,E,A,k,w,b,C;if(!e||typeof e!="object")return null;const t=ae(e),n=Jn(t);if(!n)return null;const r=t.toolCalls??((S=t.additionalKwargs)==null?void 0:S.toolCalls),s=Array.isArray(r)?r.map(Je):void 0,o=Wn(t.content??t.parts,!!(s!=null&&s.length)),a=t.id??`msg-${Date.now().toString(16)}-${Math.random().toString(16).slice(2)}`,i=t.createdAt??((E=t.additionalKwargs)==null?void 0:E.createdAt)??new Date().toISOString(),d=t.name??((A=t.additionalKwargs)==null?void 0:A.agentName)??void 0,l=t.model??((k=t.additionalKwargs)==null?void 0:k.model)??void 0,u=t.toolCallId??void 0,p=t.additionalKwargs??void 0,g=t.responseMetadata??void 0,m=t.checkpointId??((w=t.additionalKwargs)==null?void 0:w.checkpointId)??void 0,v=t.checkpointNs??((b=t.additionalKwargs)==null?void 0:b.checkpointNs)??void 0,f=typeof t.toolStreaming=="boolean"?t.toolStreaming:!!((C=t.additionalKwargs)!=null&&C.toolStreaming);return{...t,id:a,role:n,content:o,createdAt:i,name:d,model:l,toolCallId:u,toolCalls:s,checkpointId:m,checkpointNs:v,toolStreaming:f,additionalKwargs:p,responseMetadata:g,artifact:t.artifact&&typeof t.artifact=="object"&&!t.artifact.type?{...t.artifact,type:t.name}:t.artifact??void 0}}function Gn(e){if(!e||typeof e!="object")return e;const t=ae(e);if(t.tool&&!t.name&&(t.name=t.tool),t.type==="artifact.update"&&t.artifact&&typeof t.artifact=="object"){const n=t.artifact;!n.type&&t.name&&(n.type=t.name)}return t}function Je(e){const t=ae(e),n=t.content??t.output??void 0;return{...t,type:"tool_call",id:t.id??t.callId,name:t.name??t.tool??void 0,args:t.args??t.arguments??void 0,content:typeof n=="string"?n:n?JSON.stringify(n):void 0}}function Wn(e,t){return typeof e=="string"?[{type:"text",text:e}]:Array.isArray(e)?e.map(n=>typeof n=="string"?{type:"text",text:n}:n.type==="tool_call"||n.type==="tool"?t?null:Je(ae(n)):n).filter(n=>!!(n&&typeof n=="object"&&typeof n.type=="string")):[]}function Jn(e){const t=ae(e),n=t.role;if(n&&(n==="assistant"||n==="user"||n==="system"||n==="tool"))return n;const r=t.type;return r?r==="user"||r==="assistant"||r==="system"||r==="tool"?r:r==="human"?"user":r==="ai"?"assistant":null:null}function It(e){if(!e)return null;const t=String(e).toLowerCase();return t==="running"||t==="pending"?"pending":t==="completed"||t==="success"?"completed":t==="error"||t==="failed"||t==="failure"?"error":null}function vt(e){return(Array.isArray(e.toolCalls)?e.toolCalls:wt(e)).map(Je)}function Xe(e,t){return t.find(n=>n.role==="tool"&&(n.toolCallId===e||n.id===e))}function Xn(e,t){const n=t.response??t.content;if(!n)return;const r=typeof n=="string"?n:Ge(n);if(!r.trim())return;const s=[{type:"text",text:r}];return{id:`tool-${t.id}`,role:"tool",content:s,name:t.name,toolCallId:t.id,artifact:t.artifact,createdAt:e.createdAt}}function Tt(e,t=[]){if(Array.isArray(e)){const s=e.filter(a=>a.role==="assistant").flatMap(a=>vt(a)),o=new Map;return s.forEach(a=>o.set(a.id,a)),Array.from(o.values()).map(a=>{var p,g,m;const i=Xe(a.id,e)||Xe(a.id,t),d=Array.isArray((p=i==null?void 0:i.additionalKwargs)==null?void 0:p.toolProgress)?(g=i==null?void 0:i.additionalKwargs)==null?void 0:g.toolProgress:void 0,l=(i==null?void 0:i.artifact)??a.artifact,u=It(a.status)??((m=i==null?void 0:i.additionalKwargs)!=null&&m.toolStreaming?"pending":null)??(i?"completed":"pending");if(i&&!a.content&&u==="completed"){const v=oe(i);typeof v=="string"&&(a.content=v)}return{call:a,result:i,state:u,progress:d,artifact:l}})}if(e.role!=="assistant")return[];const n=vt(e);return n.length===0?[]:n.map(r=>{var d,l,u;const s=Xe(r.id,t)??Xn(e,r),o=Array.isArray((d=s==null?void 0:s.additionalKwargs)==null?void 0:d.toolProgress)?(l=s==null?void 0:s.additionalKwargs)==null?void 0:l.toolProgress:void 0,a=(s==null?void 0:s.artifact)??r.artifact,i=It(r.status)??((u=s==null?void 0:s.additionalKwargs)!=null&&u.toolStreaming?"pending":null)??(s?"completed":"pending");if(s&&!r.content&&i==="completed"){const p=oe(s);typeof p=="string"&&(r.content=p)}return{call:r,result:s,state:i,progress:o,artifact:a}})}function Qn(e,t=[]){return Tt(e,t).map(n=>n.artifact).filter(n=>!!n)}const Ee={authToken:"authToken",authTokenExpiresAt:"authTokenExpiresAt",authSessionId:"authSessionId",chatSettings:"chat-settings",threadManagerView:"thread-manager-view",playgroundSettings:"new-chat-ui-chat-settings",debugLogs:"app:debugLogs"};function Qe(e){return`draft:${e}`}let ze=null;const Ye=new Set;function Ze(){return ze}function pe(e){ze=e,Ye.forEach(t=>t(e))}function Re(e){return Ye.add(e),()=>Ye.delete(e)}const Yn=12e4,Zn=12e4;let et=Yn,St=Zn;const ee=lt.create({timeout:et,withCredentials:!0});function At(e){return typeof e!="number"||!Number.isFinite(e)||e<=0?null:Math.floor(e)}function Rn(e){const t=At(e.requestTimeoutMs),n=At(e.historyTimeoutMs);t!==null&&(et=t,ee.defaults.timeout=et),n!==null&&(St=n)}function er(){return St}ee.interceptors.request.use(e=>(ze&&(e.headers.Authorization=`Bearer ${ze}`),e)),ee.interceptors.response.use(e=>{if(typeof window<"u"&&(e!=null&&e.data))try{const t=e.data,n=t.data||{},r=typeof t.token=="string"&&t.token||typeof n.token=="string"&&n.token||null,s=typeof t.expires_at=="number"&&t.expires_at||typeof n.expires_at=="number"&&n.expires_at||typeof t.expiresAt=="number"&&t.expiresAt||typeof n.expiresAt=="number"&&n.expiresAt||null;r&&(localStorage.setItem(Ee.authToken,r),pe(r)),s&&localStorage.setItem(Ee.authTokenExpiresAt,s.toString()),(r||s)&&window.dispatchEvent(new CustomEvent("smartorg:chat-token-updated",{detail:{token:r,expiresAt:s}}))}catch(t){console.warn("[chat-api] Error storing token:",t)}return e},e=>Promise.reject(e));async function te(e,t){return ee.defaults.baseURL?(await ee.get(e,t)).data:Promise.reject(new Error("API base URL is not configured"))}async function tt(e,t,n){return ee.defaults.baseURL?(await ee.post(e,t,n)).data:Promise.reject(new Error("API base URL is not configured"))}async function tr(e,t,n){return ee.defaults.baseURL?(await ee.put(e,t,n)).data:Promise.reject(new Error("API base URL is not configured"))}async function nr(e,t){return ee.defaults.baseURL?(await ee.delete(e,t)).data:Promise.reject(new Error("API base URL is not configured"))}function se(e){return e&&typeof e=="object"&&"data"in e?e.data:e}class rr{get baseUrl(){return ee.defaults.baseURL||""}updateConfig(t){if(t.chatBaseUrl)ee.defaults.baseURL=t.chatBaseUrl;else if(t.baseUrl){const n=t.baseUrl.replace(/\/+$/,"");ee.defaults.baseURL=n}t.apiKey!==void 0?pe(t.apiKey):t.getToken&&pe(t.getToken()),(t.requestTimeoutMs!==void 0||t.historyTimeoutMs!==void 0)&&Rn({requestTimeoutMs:t.requestTimeoutMs,historyTimeoutMs:t.historyTimeoutMs})}getAuthToken(){return Ze()}setAuthToken(t){pe(t)}onTokenChange(t){return Re(t)}async listThreads(){const t=await te("/threads"),n=se(t);return(n==null?void 0:n.items)??(t==null?void 0:t.items)??[]}async createThread(t,n){const r={};t&&(r.title=t),n&&(r.project=n);const s=await tt("/threads",Object.keys(r).length?r:void 0);return se(s)}async updateThread(t,n){const r=await tr(`/threads/${t}`,{title:n});return se(r)}async deleteThread(t){const n=await nr(`/threads/${t}`);return se(n)}async threadInfo(t){const n=await te(`/threads/${t}/info`);return se(n)}async listAgents(){const t=await te("/agents"),n=se(t);return(n==null?void 0:n.items)??[]}async getAgent(t){const n=await te(`/agents/${t}`);return se(n)}async getAgentSchema(t){const n=await te(`/agents/${t}/schema`);return se(n)}async getState(t){const n=await te(`/threads/${t.threadId}/state`,{params:{checkpoint_id:t.checkpointId,checkpoint_ns:t.checkpointNs}});return se(n)}async getStateHistory(t){const n=await te(`/threads/${t.threadId}/state/history`,{params:{checkpoint_id:t.checkpointId,checkpoint_ns:t.checkpointNs,limit:t.limit??100,offset:t.offset??0,include_messages:t.includeMessages??!0},timeout:er(),signal:t.signal});return se(n)}async cancelRun(t){const n=await tt(`/runs/${t}/cancel`);return se(n)}}const Ct=new rr;class sr{async fetchFileBlob(t,n){return await te(t,{responseType:"blob",onDownloadProgress:s=>{try{if(n&&s.lengthComputable){const o=s.loaded/s.total;n(o)}}catch{}},maxBodyLength:1/0})}async viewFileById(t,n){const r=await this.fetchFileBlob(`/files/${t}/view`,n),s=URL.createObjectURL(r);window.open(s,"_blank"),setTimeout(()=>URL.revokeObjectURL(s),6e4)}async getFileBlob(t,n){return await this.fetchFileBlob(`/files/${t}/view`,n)}async getFileContent(t,n){return await(await this.fetchFileBlob(`/files/${t}/view`,n)).text()}async downloadFileById(t,n){const r=await this.fetchFileBlob(`/files/${t}/download`,n),s=URL.createObjectURL(r);let o=`file_${t}`;try{const i=await te(`/files/${t}`);o=(i==null?void 0:i.filename)??o}catch{}const a=document.createElement("a");a.href=s,a.download=o,document.body.appendChild(a),a.click(),a.remove(),setTimeout(()=>URL.revokeObjectURL(s),6e4)}async getFileInfo(t){return await te(`/files/${t}`)}async listFiles(t,n=50,r=0){const s={limit:n,offset:r};return t&&(s.thread_id=t),await te("/files",{params:s})}async uploadFile(t,n,r){const s=new FormData;return s.append("file",t),n&&s.append("thread_id",n),await tt("/files/upload-form",s,{onUploadProgress:o=>{try{if(r&&o.lengthComputable){const a=o.loaded/o.total;r(a)}}catch{}}})}}const xt=new sr;class or{constructor(){en(this,"_authBaseUrl","")}get baseUrl(){return this._authBaseUrl}updateConfig(t){if(t.authBaseUrl)this._authBaseUrl=t.authBaseUrl;else if(t.baseUrl){const n=t.baseUrl.replace(/\/+$/,"");this._authBaseUrl=`${n}/auth`}t.apiKey!==void 0?pe(t.apiKey):t.getToken&&pe(t.getToken())}getAuthToken(){return Ze()}setAuthToken(t){pe(t)}onTokenChange(t){return Re(t)}async listUsers(){const t=await te("/users",{baseURL:this.baseUrl});return(t==null?void 0:t.users)??[]}}const ar=new or,Mt=c.createContext(null);function ir({children:e,apiConfig:t}){const n=Ct,r=ar;if(t){const o=n.baseUrl,a=r.baseUrl,i=n.getAuthToken(),d=t.requestTimeoutMs!==void 0||t.historyTimeoutMs!==void 0;(t.baseUrl||t.chatBaseUrl||d)&&(d||t.chatBaseUrl&&t.chatBaseUrl!==o||t.baseUrl&&!o.startsWith(t.baseUrl))&&n.updateConfig(t),(t.baseUrl||t.authBaseUrl)&&(t.authBaseUrl&&t.authBaseUrl!==a||t.baseUrl&&!a.startsWith(t.baseUrl))&&r.updateConfig(t),t.apiKey!==void 0&&t.apiKey!==i&&(n.updateConfig({apiKey:t.apiKey}),r.updateConfig({apiKey:t.apiKey}))}const s={token:n.getAuthToken(),setToken:o=>{n.setAuthToken(o),r.setAuthToken(o)},chatApi:n,authApi:r,fileApi:xt,baseUrl:n.baseUrl};return V.jsx(Mt.Provider,{value:s,children:e})}async function lr(e){return await new Promise((t,n)=>{const r=new FileReader;r.onload=()=>{try{const s=r.result,o=new Uint8Array(s);let a="";const i=o.byteLength;for(let d=0;d<i;d++)a+=String.fromCharCode(o[d]);t(btoa(a))}catch(s){n(s)}},r.onerror=s=>n(s),r.readAsArrayBuffer(e)})}async function cr(e=[]){const t=[],n=[];for(const r of e)try{const s=await lr(r),o=r.type||"application/octet-stream";n.push({filename:r.name,data:s,mime_type:o}),o.startsWith("image/")?t.push({type:"image_url",image_url:{url:`data:${o};base64,${s}`}}):t.push({type:"file",url:`data:${o};base64,${s}`,mimeType:o,name:r.name,size:r.size})}catch{}return{contentParts:t,filesInfo:n}}function Et(e){return e.filter(t=>t.type==="text").map(t=>t.text).join("")}function ur(e){if(e==null)return null;const t=String(e).trim();return t.length>0?t:null}function Pt(e){const t=e.toolCallId??(e.role==="tool"?e.id:void 0);return e.role==="tool"&&!t&&console.error("[meta-utils] CRITICAL: Tool message missing toolCallId!",e),{toolCallId:t??void 0,name:e.name??void 0}}function dr(e){var n;if(e.name&&e.name.trim())return e.name;const t=(n=e.additionalKwargs)==null?void 0:n.agentName;return typeof t=="string"&&t.trim()?t:e.model&&e.model.includes("/")?e.model.split("/").pop()||null:e.model||null}function fr(e){const t=e.updatedAt??e.createdAt??"",n=Array.isArray(e.content)?e.content.map(a=>{switch(a.type){case"text":return`t:${a.text.length}`;case"image_url":return"img";default:return a.type==="interrupt"?"interrupt":"unknown"}}).join("|"):"",r="checkpointId"in e&&e.checkpointId?`cp:${e.checkpointId}`:"",s="checkpointNs"in e&&e.checkpointNs?`ns:${e.checkpointNs}`:"",o=[r,s].filter(Boolean).join("|");return`${e.id}:${t}:${n}${o?`:${o}`:""}`}function be(){const e=c.useContext(Mt);if(!e)throw new Error("useApi must be used within ApiProvider");return e}function pr(e,t,n){const r=typeof t=="string"?[{type:"text",text:t}]:t;return{id:`msg-${Date.now()}-${Math.random().toString(36).slice(2,9)}`,role:e,content:r,createdAt:new Date().toISOString(),...n}}function _t(e,t="user"){return typeof e=="string"?pr(t,e):e}function gr(e){return!!e&&typeof e=="object"&&"data"in e}function ve(e){return typeof e=="object"&&e!==null}function mr(e){return ve(e)?typeof e.id=="string"&&typeof e.type=="string"&&"content"in e:!1}function yr(e){return Array.isArray(e)&&e.every(mr)}function hr(e){if(!ve(e))return{};const t={};for(const[n,r]of Object.entries(e))ve(r)&&(t[n]={metadata:ve(r.metadata)?r.metadata:void 0});return t}function br(e,t){if(!e||!ve(t))return t;if(e==="messages/partial"){const r=t;return yr(r.messages)?{type:"messages/partial",messages:r.messages,seq:typeof r.seq=="number"?r.seq:void 0,scope:typeof r.scope=="string"?r.scope:void 0,origin:r.origin==="task"?"task":"agent"}:r.id&&(r.content!==void 0||r.text!==void 0)?{type:"messages/partial",messages:[{id:r.id,type:r.type||"ai",role:r.role||r.type||"assistant",content:r.content??r.text,scope:r.scope,origin:r.origin}],seq:typeof r.seq=="number"?r.seq:void 0,scope:typeof r.scope=="string"?r.scope:void 0,origin:r.origin==="task"?"task":"agent"}:t}if(e==="messages/metadata"){const r=t;return(r==null?void 0:r.type)==="messages/metadata"&&ve(r.metadata)?{type:"messages/metadata",metadata:hr(r.metadata),seq:typeof r.seq=="number"?r.seq:void 0,scope:typeof r.scope=="string"?r.scope:void 0,origin:r.origin==="task"?"task":"agent"}:t}const n=t;return"type"in n||(n.type=e),n}function Nt(e={}){const t=e.baseUrl||"",n=e.streamPath??"/stream",[r,s]=c.useState(e.token??null),o=c.useRef(e.headers??{}),a=e.credentials??"include",i=c.useRef(e);c.useEffect(()=>{i.current=e},[e]);const d=c.useCallback(y=>{var B,P,D,$,N,O,z,X,F,L;const I=i.current;if(!I)return;(B=I.onEvent)==null||B.call(I,y),y.type==="thread_info"&&((P=I.onThreadInfo)==null||P.call(I,y)),y.type==="values"&&((D=I.handleValuesEvent)==null||D.call(I,y)),y.type==="metadata"&&(($=I.onMetadataEvent)==null||$.call(I,y)),typeof y.type=="string"&&(y.type==="custom"||y.type.startsWith("custom."))&&((N=I.onCustomEvent)==null||N.call(I,y)),y.type==="updates"&&((O=I.onUpdateEvent)==null||O.call(I,y)),y.type==="tool.end"?(z=I.onToolEnd)==null||z.call(I,y):y.type==="tool.start"&&((X=I.onToolStart)==null||X.call(I,y)),y.type==="heartbeat"&&((F=I.onHeartbeat)==null||F.call(I,y)),y.type==="token"&&((L=I.onToken)==null||L.call(I,y.token))},[]),[l,u]=c.useState(!1),[p,g]=c.useState(null),[m,v]=c.useState(!1),[f,T]=c.useState(null),S=c.useRef(null),E=c.useRef(!0),A=c.useRef(null),k=c.useCallback(y=>{s(y)},[]),w=c.useCallback(()=>{g(null),T(null)},[]),b=c.useCallback(()=>{var P,D;console.debug("[use-chat] stop() invoked - aborting stream");const y=(P=A.current)==null?void 0:P.threadId,I=(D=A.current)==null?void 0:D.runId,_=()=>{var $;($=S.current)==null||$.abort(),S.current=null,A.current=null,u(!1),v(!1)};(I||y?Ct.cancelRun(I||y).catch($=>{console.warn("[use-chat] cancel run failed:",$)}):Promise.resolve()).finally(_)},[]),C=c.useCallback(y=>{S.current&&(S.current.abort(),S.current=null);const I={text:typeof y.content=="string"?y.content:y.text,threadId:y.threadId,attachments:y.attachments,payload:y.payload?{...y.payload,creativityLevel:y.payload.creativityLevel??"medium"}:{creativityLevel:"medium"},config:y.config,checkpointId:y.checkpointId,checkpointNs:y.checkpointNs||void 0,edit:y.edit??!1,command:y.command};u(!0),g(null),T(null);const _=new AbortController;S.current=_;let B=null,P=!1;return A.current={threadId:I.threadId??void 0,runId:void 0,headers:{},isStreaming:!0},(async()=>{var D,$,N,O,z,X;try{let F={};try{if(r)F={Authorization:`Bearer ${r}`};else if(typeof window<"u"){const R=window.__AUTH_TOKEN__,we=((D=window.localStorage)==null?void 0:D.getItem(Ee.authToken))||null;let Q=null;try{const ge=($=window.localStorage)==null?void 0:$.getItem(Ee.chatSettings);ge&&(Q=((N=JSON.parse(ge))==null?void 0:N.apiKey)||null)}catch{}const Y=R||we||Q||null;Y&&(F={Authorization:`Bearer ${Y}`})}}catch{}console.debug("[use-chat] POST",t+n);let L={};if(typeof window<"u")try{const W=(O=window.localStorage)==null?void 0:O.getItem(Ee.authSessionId);W&&(L={"X-Session-Id":W})}catch{}const G={...F,...L,...o.current},h={"Content-Type":"application/json",Accept:"text/event-stream",...G},U=await fetch(t+n,{method:"POST",headers:h,body:JSON.stringify(I),signal:_.signal,credentials:a});if(A.current&&(A.current.headers=G),!U.ok||!U.body){const W=await U.text().catch(()=>"");console.debug("[use-chat] non-OK response",U.status,W==null?void 0:W.slice(0,500));const R=`stream ${U.status}${W?": "+W:""}`;throw R&&(g(R),B="error"),new Error(R)}v(!0);const x=U.body.getReader(),J=new TextDecoder;let H="",K=0,Z=Date.now();const ne=setInterval(()=>{Date.now()-Z>18e5&&(g("Stream idle timeout"),B="error",_.abort())},5e3),ue=1024*1024;try{const W=U.headers.get("X-Thread-Id")||U.headers.get("x-thread-id"),R=U.headers.get("X-Run-Id")||U.headers.get("x-run-id");for(A.current&&(A.current={...A.current,threadId:W??A.current.threadId,runId:R??A.current.runId});;){const{value:we,done:Q}=await x.read();if(Q)break;H+=J.decode(we,{stream:!0}),H.length>ue&&(H="",console.warn("Stream buffer reset: exceeded 1MB"));let Y;for(;(Y=H.indexOf(`
5
5
 
6
6
  `))>=0;){const ge=H.slice(0,Y);H=H.slice(Y+2);const $e=ge.split(/\r?\n/),De=[];let me=null;for(const he of $e)if(!he.startsWith(":")&&he){if(he.startsWith("event:")){const Ae=he.slice(6).trim();Ae&&(me=Ae);continue}if(he.startsWith("data:")){const Ae=he.slice(5);De.push(Ae.startsWith(" ")?Ae.slice(1):Ae)}}const Te=De.join(`
7
- `);if(!Te)continue;let re;try{re=JSON.parse(Te)}catch{console.debug("[use-chat] malformed SSE:",Te.slice(0,200));continue}re=br(me,re);const Ne=gr(re)?re.data:re;if(!Ne){console.warn("[use-chat] dropped envelope event without payload",re);continue}const Se=Gn(Ne);Z=Date.now();const ye=typeof Se.seq=="number"?Se.seq:void 0;if(ye!==void 0){if(ye<=K){console.debug("[use-chat] drop duplicate/out-of-order event",{seq:ye,lastProcessedSeq:K,type:Se.type});continue}K=ye}d(Se)}}B===null&&!_.signal.aborted&&(B="complete")}catch(W){if(W.name==="AbortError")B=B??"aborted";else{const R=W.message||String(W);B="error",g(R)}}finally{try{await x.cancel()}catch{}finally{(z=x.releaseLock)==null||z.call(x)}clearInterval(ne)}}catch(F){if(F.name==="AbortError")B=B??"aborted";else{const L=F.message||String(F);B="error",g(L),P||(P=!0,(X=e.onConnectionError)==null||X.call(e,L))}}finally{try{if(e.onFinish){const F={lastSeq:0,lastCheckpointId:null,lastCheckpointNs:null,lastValues:null};e.onFinish(F)}}catch(F){console.warn("[use-chat] onClosed callback failed",F)}u(!1),v(!1),S.current=null,A.current=null}})(),Promise.resolve()},[t,n,r,e,d]);return c.useEffect(()=>()=>{var y;E.current=!1,(y=S.current)==null||y.abort()},[]),{isStreaming:l,error:p,assistantText:"",activeMessageId:f,streamedMessages:{},lastCheckpointId:null,lastSeq:0,connected:m,stream:C,stop:b,clear:w,setToken:k,values:{},interrupt:()=>Promise.resolve(),resume:()=>Promise.resolve(),goto:()=>Promise.resolve(),connectionState:p?"error":l?m?"connected":"connecting":"idle",messages:[],submit:C}}function jt({api:e,initialThreadId:t=null,onError:n,onThreadChange:r,onCurrentThreadDeleted:s}){const[o,a]=c.useState([]),[i,d]=c.useState(t),[l,u]=c.useState(!1),[p,g]=c.useState(null),m=c.useRef(i),v=c.useRef(new Map);c.useEffect(()=>{m.current=i},[i]),c.useEffect(()=>{t!==void 0&&t!==m.current&&d(t)},[t]);const f=c.useCallback(async()=>{u(!0),g(null);try{const w=await e.listThreads();a(w??[])}catch(w){const b=String(w);g(b),n==null||n(b)}finally{u(!1)}},[e,n]);c.useEffect(()=>{f()},[f]),c.useEffect(()=>{r==null||r(i)},[i,r]);const T=c.useCallback(async(w,b)=>{try{const C=b&&typeof b=="object"?{id:b.id,name:b.name??""}:void 0,y=await e.createThread(w,C);return d(y.threadId),await f(),y.threadId}catch(C){const y=String(C);return n==null||n(y),null}},[e,n,f]),S=c.useCallback(async w=>{const b=o;a(y=>y.filter(I=>I.threadId!==w));const C=new AbortController;v.current.set(w,C);try{await e.deleteThread(w),m.current===w&&(d(null),s==null||s())}catch(y){a(b);const I=String(y);n==null||n(I)}finally{v.current.delete(w)}},[e,s,n,o]),E=c.useCallback(async(w,b)=>{try{await e.updateThread(w,b),await f()}catch(C){n==null||n(String(C))}},[e,n,f]),A=c.useMemo(()=>({createThread:T,deleteThread:S,renameThread:E,refreshThreads:f}),[T,S,E,f]),k=c.useCallback(w=>{if(!(w!=null&&w.threadId))return;const b={threadId:w.threadId,title:w.title||`Thread ${w.threadId.slice(0,8)}`,project:w.project,createdAt:w.createdAt||new Date().toISOString(),updatedAt:w.updatedAt||new Date().toISOString(),messageCount:w.messageCount??1};a(C=>{let y=!1;const I=C.map(_=>_.threadId===b.threadId?(y=!0,console.debug("[useThreadsState] thread_info: updating existing thread",b.threadId),{..._,title:b.title??_.title,project:b.project??_.project,updatedAt:b.updatedAt??_.updatedAt,messageCount:b.messageCount??_.messageCount}):_);return y?I:(console.debug("[useThreadsState] thread_info: adding thread to list",b.threadId),[b,...C])})},[]);return{threads:o,currentThreadId:i,currentThreadIdRef:m,setCurrentThreadId:d,isLoadingThreads:l,threadsError:p,actions:A,addThreadFromEvent:k}}const zt=c.createContext(null);function Lt({children:e,initialThreadId:t=null,onError:n,onThreadChange:r}){const{chatApi:s}=be(),{threads:o,currentThreadId:a,setCurrentThreadId:i,currentThreadIdRef:d,isLoadingThreads:l,threadsError:u,actions:p,addThreadFromEvent:g}=jt({api:s,initialThreadId:t,onError:n,onThreadChange:r}),m=c.useMemo(()=>({threads:o,currentThreadId:a,setCurrentThreadId:i,currentThreadIdRef:d,isLoading:l,error:u,actions:p,addThreadFromEvent:g}),[o,a,i,d,l,u,p,g]);return V.jsx(zt.Provider,{value:m,children:e})}function Le(e){const t=c.useContext(zt);if(!t&&!(e!=null&&e.optional))throw new Error("useThreads must be used within a ThreadsProvider");return t}function Ut(e){const t=e.artifact;return!t||typeof t!="object"?null:"metadata"in t&&t.metadata?t.metadata:{id:t.id??e.id??`artifact-${Date.now()}`,type:t.type??"unknown",createdAt:e.createdAt??new Date().toISOString(),status:t.status??"completed",progress:t.progress??void 0}}function wr(e,t){const n=Ut(e);if(!n)return e;const r={...n,...t,updatedAt:new Date().toISOString()};return{...e,artifact:{...typeof e.artifact=="object"&&e.artifact?e.artifact:{},metadata:r}}}function kr(e,t,n){return e.find(r=>{const s=Ut(r);return!!((s==null?void 0:s.id)===t||n&&r.toolCallId===n)})??null}function Ue(e){const t=new Set;return e.map(n=>We(n)).filter(n=>!n||t.has(n.id)?!1:(t.add(n.id),!0))}function Bt(e,t,n){return t<0||t>=e.length?e:[...e.slice(0,t),n,...e.slice(t+1)]}function Ir(e,t,n){for(let r=e.length-1;r>=0;r--)if(e[r].role==="assistant"){const o={...e[r],checkpointId:t,checkpointNs:n??void 0};return Bt(e,r,o)}return e}const Ft={status:"idle",messages:[],taskMessagesByScope:{},assemblingId:null,lastCheckpointId:null,lastCheckpointNs:null,messagesStreamMeta:{},pendingInterrupt:null,values:{},error:null};function vr(e,t){var n;switch(t.type){case"status":return{...e,status:t.payload.status,error:t.payload.error??e.error};case"reset":return{...Ft,messages:Ue(((n=t.payload)==null?void 0:n.messages)??[])};case"user_message":{const{message:r,editingMessageId:s}=t.payload;if(s){const o=e.messages.findIndex(a=>a.id===s);if(o!==-1)return{...e,status:"streaming",messages:[...e.messages.slice(0,o),r],assemblingId:null,lastCheckpointId:null,error:null}}return{...e,status:"streaming",messages:[...e.messages,r],assemblingId:null,lastCheckpointId:null,error:null}}case"seed":{const r=Ue(t.payload.messages),s={...e,status:"idle",messages:r,assemblingId:null,pendingInterrupt:t.payload.pendingInterrupt??null,taskMessagesByScope:{},error:null};return Object.prototype.hasOwnProperty.call(t.payload,"checkpointId")&&(s.lastCheckpointId=t.payload.checkpointId??null),Object.prototype.hasOwnProperty.call(t.payload,"checkpointNs")&&(s.lastCheckpointNs=t.payload.checkpointNs??null),Object.prototype.hasOwnProperty.call(t.payload,"values")&&(s.values=t.payload.values??{}),s}case"prepend":{const r=Ue(t.payload.messages);if(!r.length)return e;const s=new Set(e.messages.map(a=>a.id)),o=r.filter(a=>!s.has(a.id));return o.length?{...e,messages:[...o,...e.messages]}:e}case"event":return Ot(e,t.payload.ev);case"batch":{const{events:r}=t.payload;return r.length?r.reduce((s,o)=>Ot(s,o),e):e}default:return e}}function Tr(e=[]){const[t,n]=c.useReducer(vr,{...Ft,messages:e}),r=c.useRef([]),s=c.useRef(null),o=c.useCallback(()=>{s.current!==null&&typeof window<"u"&&window.cancelAnimationFrame(s.current),s.current=null;const l=r.current;l.length&&(r.current=[],n({type:"batch",payload:{events:l}}))},[]),a=c.useCallback(()=>{typeof window<"u"&&typeof window.requestAnimationFrame=="function"?s.current===null&&(s.current=window.requestAnimationFrame(()=>o())):setTimeout(o,8)},[o]),i=c.useCallback(l=>{r.current.push(l),a()},[a]),d=c.useMemo(()=>({setStatus:(l,u)=>n({type:"status",payload:{status:l,error:u}}),reset:l=>n({type:"reset",payload:{messages:l}}),seed:(l,u)=>n({type:"seed",payload:{messages:l,...u??{}}}),pushUser:(l,u)=>n({type:"user_message",payload:{message:l,editingMessageId:u}}),onEvent:i}),[i]);return{state:t,dispatch:n,...d}}function Ot(e,t){const n=t.origin,r=t.scope,s=n==="task"||typeof r=="string"&&r.startsWith("tools:");if(t.type==="checkpoint"){const o=t.checkpointNs??e.lastCheckpointNs??null,a=Ir(e.messages,t.checkpointId,o);return{...e,lastCheckpointId:t.checkpointId,lastCheckpointNs:o,messages:a}}if(t.type==="status"){const o=t.status==="completed"||t.status==="error"?"idle":t.status==="interrupted"?"awaiting_input":e.status;return{...e,status:o}}if(t.type==="interrupt")return{...e,status:"awaiting_input",pendingInterrupt:{id:t.id,value:t.value,alternatives:t.alternatives}};if(t.type==="error"){const o={id:`err-${Date.now()}`,role:"system",content:[{type:"text",text:`Error: ${t.message}`}],createdAt:new Date().toISOString()};return{...e,status:"error",error:t.message,messages:[...e.messages,o]}}if(t.type==="values"){const o=t,a=o.values&&typeof o.values=="object"?{...o.values}:{},i=Array.isArray(o.messages)?o.messages:Array.isArray(a.messages)?a.messages:[];if(!i.length&&Object.keys(a).length===0)return e;const d=Ue(i);delete a.messages;let l=e.lastCheckpointId,u=e.lastCheckpointNs;const p=o.config||o.checkpoint,g=(p==null?void 0:p.configurable)||p;if((g!=null&&g.checkpoint_id||g!=null&&g.checkpointId)&&(l=g.checkpoint_id||g.checkpointId,u=g.checkpoint_ns||g.checkpointNs||null),!l){for(let f=d.length-1;f>=0;f--)if(d[f].checkpointId){l=d[f].checkpointId,u=d[f].checkpointNs??null;break}}const m=o.interrupts||a.__interrupt__||a.interrupts,v=Array.isArray(m)&&m.length>0?{id:m[0].id||"native-interrupt",value:m[0].value||m[0],alternatives:m[0].alternatives}:null;if(s){const f=typeof r=="string"&&r.length>0?r:"task";return{...e,taskMessagesByScope:{...e.taskMessagesByScope,[f]:d},assemblingId:null}}return{...e,status:v?"awaiting_input":e.status==="streaming"?"idle":e.status,messages:d,assemblingId:null,lastCheckpointId:l,lastCheckpointNs:u,pendingInterrupt:v,values:{...e.values,...a}}}if(t.type==="messages/metadata"){const o={...e.messagesStreamMeta??{}},a=t.metadata;return a&&typeof a=="object"&&Object.entries(a).forEach(([i,d])=>{const l=d==null?void 0:d.metadata;if(!l||typeof l!="object")return;const u=o[i]??{};o[i]={...u,lastSeq:t.seq??u.lastSeq??null,metadata:{...u.metadata??{},...l}}}),{...e,messagesStreamMeta:o}}if(t.type==="messages/partial"||t.type==="message.delta"){const o=t.type==="messages/partial"?t:{...t,type:"messages/partial",messages:t.delta?[{id:t.id,type:"ai",content:t.delta,scope:t.scope,origin:t.origin}]:[]};return Sr(e,o,s)}return t.type==="message.start"?{...e,assemblingId:t.id,status:"streaming"}:t.type==="message.end"?{...e,assemblingId:null}:t.type==="tool.start"?{...Ar(e,t,s),status:"streaming"}:t.type==="tool.progress"?Cr(e,t,s):t.type==="tool.end"?xr(e,t,s):t.type==="artifact.update"?Mr(e,t):e}function Sr(e,t,n){var m,v,f,T,S,E,A;const r=t.messages;if(!r.length)return console.warn("[messagesReducer] Dropping messages/partial event without messages[]",t),e;const s=r.find(k=>k.type==="ai"||k.type==="assistant"||k.role==="assistant");if(!s)return e;const o=s.id,a=s.content??"",i=typeof a=="string"?[{type:"text",text:a}]:Array.isArray(a)?a.map(k=>typeof k=="string"?{type:"text",text:k}:(k==null?void 0:k.type)==="text"?{type:"text",text:typeof k.text=="string"?k.text:k.content??""}:((k==null?void 0:k.type)==="reasoning",k)):[],d=i.filter(k=>k.type==="text").map(k=>k.text).join(""),l=e.assemblingId!==o,u=typeof t.scope=="string"&&t.scope.length>0?t.scope:"task";let p=n?[...e.taskMessagesByScope[u]||[]]:[...e.messages];const g=(v=(m=e.messagesStreamMeta)==null?void 0:m[o])==null?void 0:v.metadata;if(l){const k=We({...s,role:"assistant",content:i,scope:t.scope,origin:t.origin,responseMetadata:{...g,...s.responseMetadata??{}}});k&&p.push(k)}else{const k=p.findIndex(w=>w.id===o);if(k!==-1){const w=p[k];p[k]={...w,content:i,scope:t.scope??w.scope,origin:t.origin??w.origin,responseMetadata:{...g,...w.responseMetadata,...s.responseMetadata??{}}}}}return{...e,status:"streaming",messages:n?e.messages:p,taskMessagesByScope:n?{...e.taskMessagesByScope,[u]:p}:e.taskMessagesByScope,assemblingId:o,messagesStreamMeta:{...e.messagesStreamMeta??{},[o]:{...((f=e.messagesStreamMeta)==null?void 0:f[o])??{},lastSeq:t.seq??((S=(T=e.messagesStreamMeta)==null?void 0:T[o])==null?void 0:S.lastSeq)??null,lastText:d||(((A=(E=e.messagesStreamMeta)==null?void 0:E[o])==null?void 0:A.lastText)??"")}}}}function nt(e,t){var n;if(!t)return-1;for(let r=e.length-1;r>=0;r--){const s=e[r];if(s.role==="assistant"&&((n=s.toolCalls)!=null&&n.some(o=>o.id===t)))return r}return-1}function Ar(e,t,n){const r=t.id||t.callId;if(!r)return e;const s=t.name||"tool",o=`Starting ${s}...`,a=typeof t.scope=="string"&&t.scope.length>0?t.scope:"task";let i=n?[...e.taskMessagesByScope[a]||[]]:[...e.messages],d=nt(i,r);if(d===-1){for(let l=i.length-1;l>=0;l--)if(i[l].role==="assistant"){d=l;break}}if(d===-1){const l={id:`assistant-${r}`,role:"assistant",content:[{type:"text",text:""}],createdAt:new Date().toISOString(),toolCalls:[],scope:t.scope,origin:t.origin};i.push(l),d=i.length-1}if(d!==-1){const l=i[d],u=[...l.toolCalls||[]],p=u.findIndex(g=>g.id===r);p>=0?u[p]={...u[p],status:"running",content:o}:u.push({id:r,name:s,args:t.args||{},status:"running",content:o}),i[d]={...l,toolCalls:u,scope:t.scope??l.scope,origin:t.origin??l.origin}}return{...e,messages:n?e.messages:i,taskMessagesByScope:n?{...e.taskMessagesByScope,[a]:i}:e.taskMessagesByScope}}function Cr(e,t,n){const r=t.id;if(!r)return e;const s=typeof t.scope=="string"&&t.scope.length>0?t.scope:"task";let o=n?[...e.taskMessagesByScope[s]||[]]:[...e.messages];const a=nt(o,r);if(a!==-1){const i=o[a],d=oe(t.content),l=(i.toolCalls||[]).map(u=>u.id===r?{...u,content:typeof d=="string"?d:u.content}:u);o[a]={...i,toolCalls:l,scope:t.scope??i.scope,origin:t.origin??i.origin}}return{...e,messages:n?e.messages:o,taskMessagesByScope:n?{...e.taskMessagesByScope,[s]:o}:e.taskMessagesByScope}}function xr(e,t,n){const r=t.id;if(!r)return e;const s=typeof t.scope=="string"&&t.scope.length>0?t.scope:"task";let o=n?[...e.taskMessagesByScope[s]||[]]:[...e.messages];const a=nt(o,r),i=oe(t.content??t.error);if(a!==-1){const l=o[a],u=(l.toolCalls||[]).map(p=>p.id===r?{...p,status:t.error?"failed":"completed",content:typeof i=="string"?i:p.content,artifact:t.artifact}:p);o[a]={...l,toolCalls:u,scope:t.scope??l.scope,origin:t.origin??l.origin}}const d={id:`tool-${r}`,role:"tool",name:t.name,content:[{type:"text",text:typeof i=="string"?i:""}],artifact:t.artifact,toolCallId:r,createdAt:new Date().toISOString(),scope:t.scope,origin:t.origin};return o.push(d),{...e,messages:n?e.messages:o,taskMessagesByScope:n?{...e.taskMessagesByScope,[s]:o}:e.taskMessagesByScope}}function Mr(e,t){const n=t.artifactId,r=kr(e.messages,n,t.callId);if(!r)return e;const s=e.messages.indexOf(r),o=wr(r,{status:t.status,progress:t.progress,error:t.error});return t.partial_data&&o.artifact&&(o.artifact={...o.artifact,...t.partial_data}),{...e,messages:Bt(e.messages,s,o)}}function Pe(e){if(!(!e||typeof e!="object"||Array.isArray(e)))return{...e}}function Be(e,t){if(e)for(const n of t){const r=e[n];if(typeof r=="string"&&r.trim())return r.trim()}}function Er(e,t){if(!e)return null;for(const n of t){const r=e[n];if(typeof r=="number"&&Number.isFinite(r))return r}return null}function $t(e){const t=Pe(e);if(t)return Pe(t.configurable)??t}async function Dt(e,t){var i,d;if(!e)return e??null;const n=ae(e),r=Array.isArray(n.checkpoints)?n.checkpoints:n.checkpoints?Object.values(n.checkpoints):[],s=new Set;for(const l of r){const u=(i=l==null?void 0:l.values)==null?void 0:i.messages;if(Array.isArray(u))for(const p of u){const g=p==null?void 0:p.content;if(Array.isArray(g))for(const m of g){if(!m||typeof m!="object"||m.type!=="image_url"&&m.type!=="file")continue;const v=m.fileId||m.file_id;typeof v=="string"&&v.trim()&&s.add(v)}}}if(s.size===0)return n;const o=await Promise.all(Array.from(s).map(async l=>{try{const u=await t.getFileInfo(l),p=ae(u);return[l,p]}catch{return[l,null]}})),a=new Map(o);for(const l of r){const u=(d=l==null?void 0:l.values)==null?void 0:d.messages;if(Array.isArray(u))for(const p of u){const g=p==null?void 0:p.content;if(Array.isArray(g))for(const m of g){if(!m||typeof m!="object"||m.type!=="image_url"&&m.type!=="file")continue;const v=m.fileId||m.file_id;if(!v)continue;const f=a.get(v),T=(f==null?void 0:f.contentUrl)||(f==null?void 0:f.content_url);T&&(m.type==="image_url"?(m.imageUrl=m.imageUrl||{},m.imageUrl.url=T):m.type==="file"&&(m.url=T,!m.name&&(f!=null&&f.filename||f!=null&&f.name)&&(m.name=(f==null?void 0:f.filename)||(f==null?void 0:f.name))))}}}return n}function rt(e){const r=[...(Array.isArray(e==null?void 0:e.checkpoints)?(e==null?void 0:e.checkpoints)??[]:e!=null&&e.checkpoints?Object.values(e.checkpoints):[]).map((o,a)=>Pr(ae(o),a)).filter(o=>!!o)].sort((o,a)=>qt(a.createdAt)-qt(o.createdAt)),s=r[0]??null;return{threadId:(e==null?void 0:e.threadId)??"",latest:s,checkpoints:r,interrupt:(s==null?void 0:s.interrupt)??null}}function Pr(e,t){var w,b;if(!e)return null;const n=((w=e.values)==null?void 0:w.activeAgent)??null,r=(b=e.values)==null?void 0:b.messages,o=(Array.isArray(r)?r:[]).map(C=>_r(C,n)).filter(C=>!!C),a=Pe(e.metadata)??{},i=$t(e.config),d=Pe(e.parentConfig),l=$t(d),u=Be(i,["checkpointId"]),p=Be(i,["checkpointNs"]),g=Be(l,["checkpointId"]),m=Pe(e.config),v=Array.isArray(e.tasks)?e.tasks.map(C=>({...C})):e.tasks??null,f=Array.isArray(e.next)?[...e.next]:e.next??null,T=typeof e.createdAt=="string"&&e.createdAt.trim()?e.createdAt:new Date(Date.now()-t).toISOString(),S={...a,step:Er(a,["step"])??0,source:Be(a,["source"])??null},E=o.map(C=>({...C,checkpointId:C.checkpointId??u??null,checkpointNs:C.checkpointNs??p??null})),A=e.values,k=Array.isArray(e.interrupts)?e.interrupts:Array.isArray(A==null?void 0:A.interrupts)?A.interrupts:[];return{checkpointId:u??null,checkpointNs:p??null,createdAt:T,parentId:g??null,messages:E,interrupt:Nr(k,t,u??null),metadata:S,config:m??null,parentConfig:d??null,next:f,tasks:v,values:e.values??{}}}function _r(e,t){const n=We(e);return n?(n.role==="assistant"&&!n.name&&t&&(n.name=t),n):null}function Nr(e,t,n){const r=e.length;for(let s=r-1;s>=0;s-=1){const o=e[s];if(!o||typeof o!="object")continue;const a=o,i=a.value??o;if(i==null)continue;return{id:typeof a.id=="string"&&a.id.trim()?a.id:`interrupt-${n??t}-${s}`,value:i}}return null}function qt(e){if(!e)return 0;const t=Date.parse(e);return Number.isFinite(t)?t:0}const Ht=120;function jr(e){if(!Array.isArray(e))return"";const t=e.filter(r=>!!(r&&r.type==="text")).map(r=>(r.text??"").trim()).filter(Boolean);if(!t.length)return"";const n=t.join(" ").replace(/\s+/g," ").trim();return n?n.length>Ht?`${n.slice(0,Ht-3)}…`:n:""}function zr(e){return jr(e.content)||""}function Lr(e){const t=new Map,n=[],r=new Map,s=[];for(let l=0;l<e.length;l++){const u=e[l],p=u.checkpointId,g=p??`cp-${l}`,m=u.metadata??{},v=typeof m.step=="number"?m.step:null,f=typeof m.source=="string"?m.source:null;let T=null,S=null;const E=Array.isArray(u.messages)?u.messages:[];for(const b of E)b.role==="user"&&(S||(S=b),b.id&&(T=b.id));const A=u.next&&u.next.length>0?String(u.next[0]):null,k=u.parentConfig??null,w={id:g,step:v,source:f,createdAt:u.createdAt??null,namespace:u.checkpointNs??null,parentId:u.parentId??null,next:A,parentConfig:k,userMessageId:T};if(s.push(w),p&&t.set(p,w),p&&S){const b=zr(S);b&&r.set(p,b)}n.push({id:g,messageId:T,step:v,source:f,createdAt:u.createdAt??null,next:A,parentConfig:k})}const o=new Map;for(const l of s){if(!l.userMessageId)continue;const u=o.get(l.userMessageId)??[];u.push(l),o.set(l.userMessageId,u)}for(const l of o.values()){if(!l.length)continue;l.sort((p,g)=>{const m=p.createdAt?Date.parse(p.createdAt):0;return(g.createdAt?Date.parse(g.createdAt):0)-m});const u=l.length;for(let p=0;p<l.length;p++){const g=l[p];g.attemptCount=u,g.attemptIndex=p,g.isLatestAttempt=p===0}}return{checkpoints:e,checkpointMetaByCheckpointId:t,timeline:n,messagePreviews:r,getLatest:()=>{const l=n[0];if(l)return t.get(l.id)},getCheckpoint:l=>t.get(l),getMessageAttempts:l=>{const u=[];for(const p of t.values())p.userMessageId===l&&u.push(p);return u.length?(u.sort((p,g)=>{const m=typeof p.attemptIndex=="number"?p.attemptIndex:Number.MAX_SAFE_INTEGER,v=typeof g.attemptIndex=="number"?g.attemptIndex:Number.MAX_SAFE_INTEGER;return m-v}),u):[]}}}function Ur(e,t,n){if(!e)return{attemptCount:1,attemptIndex:0,attempts:[]};const r=n.getMessageAttempts(e);if(!r.length)return{attemptCount:1,attemptIndex:0,attempts:[]};let s=0;if(t){const o=r.findIndex(a=>a.id===t);o>=0&&(s=o)}return{attemptCount:r.length,attemptIndex:s,attempts:r}}function Br(e){return c.useMemo(()=>Lr(e),[e])}function st({api:e,fileApi:t,seed:n,onError:r,currentThreadId:s,autoLoadInitial:o=!0,isStreaming:a,getMessages:i}){const[d,l]=c.useState(null),p=c.useMemo(()=>rt(d),[d]).checkpoints,g=Br(p),m=g.timeline,[v,f]=c.useState(!1),[T,S]=c.useState(!1),[E,A]=c.useState(!1),[k,w]=c.useState(null),b=c.useRef(s),C=c.useRef(null),y=c.useRef(null);c.useEffect(()=>{b.current=s},[s]);const I=c.useCallback(async N=>{const O=await e.getState({threadId:N.threadId,checkpointId:N.checkpointId,checkpointNs:N.checkpointNs}),z={version:"values@1",threadId:N.threadId,checkpoints:[O]},X=t?await Dt(z,t):z,{latest:F}=rt(X);return F},[e,t]),_=c.useCallback(async(N,O)=>{var F;if(!N)return;const z=`${N}:${O??"latest"}`;if(C.current===z||v)return;(F=y.current)==null||F.abort();const X=new AbortController;y.current=X,f(!0),w(null);try{const L=await I({threadId:N,checkpointId:O??void 0});if(b.current!==N){f(!1);return}n((L==null?void 0:L.messages)??[],{checkpointId:(L==null?void 0:L.checkpointId)??null,checkpointNs:(L==null?void 0:L.checkpointNs)??null,pendingInterrupt:(L==null?void 0:L.interrupt)??null,values:L==null?void 0:L.values}),C.current=z,f(!1),A(!0);try{const G=await e.getStateHistory({threadId:N,limit:100,includeMessages:!1});b.current===N&&l(G)}finally{A(!1)}}catch(L){if(f(!1),!lt.isCancel(L)){const G=String(L);w(G),r==null||r(G)}}},[e,n,I,r,i]),B=c.useCallback(async(N,O)=>{if(s){S(!0);try{const z=await I({threadId:s,checkpointId:N,checkpointNs:O??void 0});n((z==null?void 0:z.messages)??[],{checkpointId:(z==null?void 0:z.checkpointId)??N,checkpointNs:(z==null?void 0:z.checkpointNs)??O,pendingInterrupt:(z==null?void 0:z.interrupt)??null,values:z==null?void 0:z.values})}catch(z){console.error("[useThreadHistoryState] Navigation failed",z)}finally{S(!1)}}},[s,I,n]),P=c.useCallback(async()=>{s&&await _(s)},[s,_]),D=c.useCallback(async N=>{const O=(N==null?void 0:N.threadId)||s;!O||s!==O||(l(N),C.current=`${O}:latest`)},[s]);c.useEffect(()=>{if(!o||!s||v||a)return;const N=`${s}:latest`;C.current!==N&&_(s)},[o,s,v,a,_]);const $=c.useCallback(()=>{l(null),f(!1),S(!1),A(!1),w(null),C.current=null},[]);return{threadCheckpoints:p,threadTimeline:m,checkpointIndex:g,isLoadingThread:v,isLoadingCheckpoint:T,isLoadingHistory:E,threadStateError:k,loadThread:_,navigateToCheckpoint:B,setCurrentCheckpointId:(N,O)=>{n(i(),{checkpointId:N,checkpointNs:O})},returnToLatest:P,handleValuesEvent:D,markSkipNextLoad:()=>{},markStreamPendingThread:()=>{},resetHistoryState:$,clearState:$}}const Kt=c.createContext(null),Vt=c.createContext(null);function ot(e){const t=c.useContext(Kt);if(!t&&!(e!=null&&e.optional))throw new Error("useThreadState must be used within a ThreadStateProvider");return t}function Gt(){const e=c.useContext(Vt);if(!e)throw new Error("useThreadStateUpdater must be used within a ThreadStateProvider");return e}function Wt({children:e,initialThreadId:t=null,initialCheckpointId:n=null,initialCheckpointNs:r=null,autoLoadInitial:s=!0,isStreaming:o,onError:a}){const{chatApi:i,fileApi:d}=be(),{currentThreadId:l}=Le(),{state:u,seed:p,onEvent:g,dispatch:m}=Tr(),{threadCheckpoints:v,threadTimeline:f,checkpointIndex:T,isLoadingThread:S,isLoadingCheckpoint:E,isLoadingHistory:A,threadStateError:k,loadThread:w,navigateToCheckpoint:b,setCurrentCheckpointId:C,returnToLatest:y,handleValuesEvent:I,markSkipNextLoad:_,markStreamPendingThread:B,resetHistoryState:P}=st({api:i,fileApi:d,seed:p,onError:a,currentThreadId:l,initialThreadId:t,initialCheckpointId:n,initialCheckpointNs:r,autoLoadInitial:s,isStreaming:o,getMessages:c.useCallback(()=>u.messages,[u.messages])}),D=c.useRef(null),$=c.useCallback(x=>{D.current=x},[]),N=c.useRef(null),O=c.useCallback(x=>{N.current=x},[]),z=c.useMemo(()=>({assemblingMessageId:u.assemblingId??null}),[u.assemblingId]),X=c.useCallback((x,J)=>{const H=_t(x,"user");return m({type:"user_message",payload:{message:H,editingMessageId:J==null?void 0:J.editingMessageId}}),H},[m]),F=c.useCallback(async()=>{D.current?await D.current():(p([],{}),P())},[p,P]),L=c.useCallback(async(x,J,H)=>{await w(x,J,{clearProgress:!1})},[w]),G=c.useMemo(()=>qn(u.messages),[u.messages]),h=c.useMemo(()=>({status:u.status,threadId:l,messages:u.messages,taskMessagesByScope:u.taskMessagesByScope,interrupt:u.pendingInterrupt,checkpoint:{id:u.lastCheckpointId??null,namespace:u.lastCheckpointNs??null},checkpoints:v,checkpointIndex:T,timelineCheckpoints:f,metadata:z,values:u.values??{},isLoading:S,isLoadingCheckpoint:E,isLoadingHistory:A,error:k,loadOlder:async()=>{},seedFromSnapshot:x=>{p(x.messages,{checkpointId:x.checkpointId,checkpointNs:x.checkpointNs,pendingInterrupt:x.interrupt,values:x.values})},clearState:F,navigateToCheckpoint:b,setCurrentCheckpointId:C,returnToLatest:y,loadThread:L,clearThread:F,respondToInterrupt:async(x,J,H)=>{N.current&&await N.current(x,J,H)},messagePreviews:T.messagePreviews,handleValuesEvent:I,markSkipNextLoad:_,markStreamPendingThread:B,resetHistoryState:P,pushUser:X,onEvent:g,artifacts:G}),[l,u.messages,u.taskMessagesByScope,u.pendingInterrupt,u.lastCheckpointId,u.lastCheckpointNs,u.values,v,f,T,z,S,E,A,k,p,F,b,C,y,L,I,_,B,X,g,G]),U=c.useMemo(()=>({registerClearThread:$,registerRespondToInterrupt:O}),[$,O]);return V.jsx(Vt.Provider,{value:U,children:V.jsx(Kt.Provider,{value:h,children:e})})}const Jt=c.createContext(null),Fr=c.createContext(!1);function Or({children:e,onError:t,onAuthError:n,onConnectionError:r,onToolEnd:s,onUpdateEvent:o,onCustomEvent:a,onMetadataEvent:i,onFinish:d,onStreamingChange:l}){const{chatApi:u,baseUrl:p}=be(),g=p,m=le(t),v=le(n),f=le(r),T=le(s),S=le(o),E=le(a),A=le(i),k=le(d),w=le(l),b=c.useMemo(()=>({onError:m,onAuthError:v,onConnectionError:f,onMetadataEvent:A,onCustomEvent:E,onUpdateEvent:S,onToolEnd:T,onFinish:k}),[m,v,f,A,E,S,T,k]);return V.jsx(Fr.Provider,{value:!0,children:V.jsx($r,{api:u,streamBaseUrl:g,handlers:b,onStreamingChange:w,children:e})})}function $r({children:e,api:t,streamBaseUrl:n,handlers:r,onStreamingChange:s}){const{setCurrentThreadId:o,currentThreadIdRef:a,addThreadFromEvent:i,currentThreadId:d}=Le(),{interrupt:l,checkpoint:u,timelineCheckpoints:p,handleValuesEvent:g,markSkipNextLoad:m,markStreamPendingThread:v,resetHistoryState:f,pushUser:T,onEvent:S,messages:E}=ot(),{registerClearThread:A,registerRespondToInterrupt:k}=Gt(),w=c.useCallback(h=>{i(h),v(h.threadId),a.current!==h.threadId&&((h.created??!a.current)&&m(h.threadId),o(h.threadId))},[i,m,v,o,a]),b=Nt({baseUrl:n,onEvent:S,onError:h=>{var U;(U=r.onError)==null||U.call(r,(h==null?void 0:h.message)??String(h))},onAuthError:r.onAuthError,onConnectionError:r.onConnectionError,onFinish:r.onFinish,onThreadInfo:w,onMetadataEvent:r.onMetadataEvent,onCustomEvent:r.onCustomEvent,onUpdateEvent:r.onUpdateEvent,onToolEnd:r.onToolEnd,handleValuesEvent:g});c.useEffect(()=>{s==null||s(b.isStreaming)},[b.isStreaming,s]);const{stream:C,stop:y,clear:I,isStreaming:_,error:B,connected:P,streamedMessages:D,activeMessageId:$}=b;c.useEffect(()=>{d!==void 0&&I()},[d,I]);const N=c.useCallback(async(h,U)=>{await C(h,U)},[C]),O=c.useRef(u);c.useEffect(()=>{O.current=u},[u]);const z=c.useCallback(async(h,U,x)=>{var W;const J=a.current;if(!J)throw new Error("No active thread to handle interrupt");const H=h?U??!0:!1,K=O.current,Z=(x==null?void 0:x.checkpointId)??K.id??void 0,ne=(x==null?void 0:x.checkpointNs)??K.namespace??void 0,ue={threadId:J,checkpointId:Z,checkpointNs:ne,command:{kind:"resume",value:H},payload:{...(x==null?void 0:x.payload)??{},creativityLevel:((W=x==null?void 0:x.payload)==null?void 0:W.creativityLevel)??"medium"},edit:!1};N(ue)},[a,N]);c.useEffect(()=>{k(z)},[z,k]);const X=c.useCallback(async()=>{y(),I(),f(),o(null)},[I,f,o,y]);c.useEffect(()=>{A(X)},[X,A]);const F=c.useCallback(async(h,U)=>{_&&y();let x=a.current;const J=(h==null?void 0:h.text)??"",H=(h==null?void 0:h.attachments)??[],K=(J==null?void 0:J.trim())??"",Z={...(h==null?void 0:h.payload)??{}},ne=Array.isArray(Z.messages)?Z.messages:void 0;ne&&delete Z.messages;const ue=!!(ne&&ne.length),W=!!(h.contentParts&&h.contentParts.length>0);if(!x&&!K&&H.length===0&&!ue&&!W)return;if(!x){const ye=Math.floor(Date.now()/1e3).toString(16).padStart(8,"0"),he=Array.from({length:4},()=>Math.floor(Math.random()*4294967295).toString(16).padStart(8,"0")).join("").slice(0,16);x=`${ye}${he}`,m(x),o(x)}let R=null;h.contentParts&&h.contentParts.length>0&&(R=h.contentParts);const{contentParts:we,filesInfo:Q}=R?{contentParts:R,filesInfo:[]}:await cr(H),Y=[...we];K&&Y.push({type:"text",text:J});const ge=h==null?void 0:h.originalMessageId,$e=!!(h!=null&&h.edit&&ge),De=!ue&&Y.length>0;let me=null;if(De){const ye=$e?ge:`msg-${Date.now()}`;me=_t({id:ye,role:"user",content:Y,createdAt:new Date().toISOString()},"user"),$e?T(me,{editingMessageId:ge}):T(me)}const Te=ue?ne:me?[me]:[],re={...Z,...Q.length?{files_info:Q}:{}};Te.length?re.messages=Te:"messages"in re||(re.messages=[]);const Ne=(h==null?void 0:h.checkpointId)??u.id??void 0;if(h!=null&&h.edit&&!Ne)throw new Error(`[streaming] Missing checkpointId for edit submit. threadId=${x??"null"}`);const Se={threadId:x,content:h==null?void 0:h.text,payload:re,config:h==null?void 0:h.config,checkpointId:Ne,command:h==null?void 0:h.command,edit:h==null?void 0:h.edit};return N(Se,U)},[u,a,_,m,T,N,y,p]),L=c.useMemo(()=>E,[E]),G=c.useMemo(()=>({isStreaming:_,error:B,connectionState:B?"error":_?P?"connected":"connecting":"idle",messages:L,activeMessageId:$,submit:F,stop:y,interrupt:l,resume:()=>Promise.resolve(),goto:(h,U)=>Promise.resolve(),clearError:()=>{}}),[_,B,F,y,l,P,L]);return V.jsx(Jt.Provider,{value:G,children:e})}function le(e){const t=c.useRef(e);return c.useEffect(()=>{t.current=e},[e]),c.useCallback((...n)=>{const r=t.current;if(r)return r(...n)},[])}function Dr(e){return c.useContext(Jt)}function Xt(e){return typeof e=="object"&&e!==null}function qr(e,t){if(Object.is(e,t))return!0;if(!Xt(e)||!Xt(t))return!1;const n=Object.keys(e),r=Object.keys(t);if(n.length!==r.length)return!1;for(const s of n)if(!Object.prototype.hasOwnProperty.call(t,s)||!Object.is(e[s],t[s]))return!1;return!0}function Hr(e){const t=c.useRef(e),n=c.useRef(e);return qr(t.current,e)||(t.current=e,n.current=e),n.current}function Qt(e){const t=e.artifact&&typeof e.artifact=="object"?e.artifact:null,n=!t&&e.content&&typeof e.content=="object"?e.content:null,r=t??n,s=(r==null?void 0:r.task_id)??(r==null?void 0:r.taskId)??null;return typeof s=="string"?s:null}function Kr(e){const{setCurrentTaskId:t,getCurrentTaskId:n,onToolEnd:r}=e;return s=>{const o=Qt(s),a=(n==null?void 0:n())??null;o&&o!==a&&t(o),r==null||r(s)}}function Vr({children:e,apiConfig:t,initialThreadId:n=null,initialCheckpointId:r=null,initialCheckpointNs:s=null,autoLoadInitial:o=!0,onConnectionError:a,onError:i,onAuthError:d,onThreadChange:l,onToolEnd:u,onUpdateEvent:p,onCustomEvent:g,onMetadataEvent:m,onFinish:v}){const f=Hr(t),[T,S]=c.useState(!1),E=ce(i),A=ce(d),k=ce(a),w=ce(l),b=ce(u),C=ce(p),y=ce(g),I=ce(m),_=ce(v),B=c.useMemo(()=>({onError:E,onAuthError:A,onConnectionError:k,onToolEnd:b,onUpdateEvent:C,onCustomEvent:y,onMetadataEvent:I,onFinish:_}),[E,A,k,b,C,y,I,_]);return V.jsx(ir,{apiConfig:f,children:V.jsx(Lt,{initialThreadId:n,onError:E,onThreadChange:w,children:V.jsx(Wt,{initialThreadId:n,initialCheckpointId:r,initialCheckpointNs:s,autoLoadInitial:o,onError:E,isStreaming:T,children:V.jsx(Or,{...B,onStreamingChange:S,children:e})})})})}function ce(e){const t=c.useRef(e);return t.current=e,c.useCallback((...n)=>{const r=t.current;if(r)return r(...n)},[])}const Gr=1,Wr=1e6;let at=0;function Jr(){return at=(at+1)%Number.MAX_SAFE_INTEGER,at.toString()}const it=new Map,Yt=e=>{if(it.has(e))return;const t=setTimeout(()=>{it.delete(e),_e({type:"REMOVE_TOAST",toastId:e})},Wr);it.set(e,t)},Xr=(e,t)=>{switch(t.type){case"ADD_TOAST":return{...e,toasts:[t.toast,...e.toasts].slice(0,Gr)};case"UPDATE_TOAST":return{...e,toasts:e.toasts.map(n=>n.id===t.toast.id?{...n,...t.toast}:n)};case"DISMISS_TOAST":{const{toastId:n}=t;return n?Yt(n):e.toasts.forEach(r=>{Yt(r.id)}),{...e,toasts:e.toasts.map(r=>r.id===n||n===void 0?{...r,open:!1}:r)}}case"REMOVE_TOAST":return t.toastId===void 0?{...e,toasts:[]}:{...e,toasts:e.toasts.filter(n=>n.id!==t.toastId)}}},Fe=[];let Oe={toasts:[]};function _e(e){Oe=Xr(Oe,e),Fe.forEach(t=>{t(Oe)})}function Qr({...e}){const t=Jr(),n=s=>_e({type:"UPDATE_TOAST",toast:{...s,id:t}}),r=()=>_e({type:"DISMISS_TOAST",toastId:t});return _e({type:"ADD_TOAST",toast:{...e,id:t,open:!0,onOpenChange:s=>{s||r()}}}),{id:t,dismiss:r,update:n}}function Yr(){const[e,t]=ct.useState(Oe);return ct.useEffect(()=>(Fe.push(t),()=>{const n=Fe.indexOf(t);n>-1&&Fe.splice(n,1)}),[e]),{...e,toast:Qr,dismiss:n=>_e({type:"DISMISS_TOAST",toastId:n})}}function Zr(e){const{allowFileOpen:t,currentThreadId:n}=e,{fileApi:r}=be(),{toast:s}=Yr(),[o,a]=c.useState({}),[i,d]=c.useState(null),[l,u]=c.useState(!1),p=c.useCallback(()=>{u(!1),d(null)},[]),g=c.useCallback(v=>{d(v),u(!0)},[]),m=c.useCallback(async(v,f,T)=>{var S,E;if(!t){v.preventDefault();return}if(o[T]){v.preventDefault();return}try{const A=String(f.url??""),k=A.match(/\/chat\/files\/([^/]+)(?:\/(view|download))?/);if(k){v.preventDefault();const w=k[1],b=f.name||`file_${w}`,C=f.mimeType||"application/octet-stream";g({id:w,name:b,mimeType:C});return}if(A.startsWith("data:")){v.preventDefault(),a(b=>({...b,[T]:!0}));const w=s({title:"Fetching file...",description:"",open:!0});try{const b=await r.listFiles(n??void 0);if(!b||!Array.isArray(b))throw new Error("Invalid file list response");const C=b.find(y=>!y||typeof y!="object"||!((y.filename??"")===(f.name??""))?!1:typeof f.size=="number"&&typeof y.size=="number"?y.size===f.size:!0);if(!(C!=null&&C.id))throw new Error(`File "${f.name}" is not yet available on the server`);if(!C.id||!C.filename)throw new Error("Invalid file data received from server");g({id:C.id,name:f.name||C.filename||`file_${C.id}`,mimeType:f.mimeType||C.mime_type||"application/octet-stream"}),(S=w.update)==null||S.call(w,{id:w.id,title:"Success",description:`Opened ${f.name}`,open:!0})}catch(b){console.error("Failed to fetch server file:",b);const C=b instanceof Error?b.message:"Unknown error occurred";(E=w.update)==null||E.call(w,{id:w.id,title:"Failed",description:C}),s({title:"Failed to fetch file",description:C,open:!0})}finally{a(b=>({...b,[T]:!1}))}}}catch(A){console.error("File click error:",A),a(k=>({...k,[T]:!1}))}},[t,o,s,n,g]);return{uploadingFiles:o,handleFileClick:m,fileViewerOpen:l,currentFileInfo:i,closeFileViewer:p}}function Rr(e){return c.useMemo(()=>{const t=e;let n=Array.isArray(t.content)?t.content:[];return typeof t.content=="string"&&(n=[{type:"text",text:t.content}]),{contentParts:n,textContent:Et(n),toolMeta:Pt(t),imageParts:n.filter(r=>r.type==="image_url"),fileParts:n.filter(r=>r.type==="file"),toolRaw:kt(n),isToolStreaming:!!t.toolStreaming}},[e])}const Zt="data:";function es(e){if(!e)return[];const t=[],n=e.split(/\r?\n/);for(const r of n){const s=r.trim();if(!s||!s.startsWith(Zt))continue;const o=s.slice(Zt.length).trim();if(!o||o.toLowerCase()==="[done]")continue;const a=je(o);a&&typeof a=="object"&&t.push(a)}return t}function ts(e){for(let t=e.length-1;t>=0;t-=1){const n=e[t];if(n&&typeof n=="object"&&n.type==="tool.end")return n}return null}function ns(e){return c.useMemo(()=>{const t=e.content.filter(d=>d.type==="text");if(!t.length)return null;let r=t.flatMap(d=>es(d.text??""));if(!r.length){const d=t.map(u=>u.text??"").join(`
7
+ `);if(!Te)continue;let re;try{re=JSON.parse(Te)}catch{console.debug("[use-chat] malformed SSE:",Te.slice(0,200));continue}re=br(me,re);const Ne=gr(re)?re.data:re;if(!Ne){console.warn("[use-chat] dropped envelope event without payload",re);continue}const Se=Gn(Ne);Z=Date.now();const ye=typeof Se.seq=="number"?Se.seq:void 0;if(ye!==void 0){if(ye<=K){console.debug("[use-chat] drop duplicate/out-of-order event",{seq:ye,lastProcessedSeq:K,type:Se.type});continue}K=ye}d(Se)}}B===null&&!_.signal.aborted&&(B="complete")}catch(W){if(W.name==="AbortError")B=B??"aborted";else{const R=W.message||String(W);B="error",g(R)}}finally{try{await x.cancel()}catch{}finally{(z=x.releaseLock)==null||z.call(x)}clearInterval(ne)}}catch(F){if(F.name==="AbortError")B=B??"aborted";else{const L=F.message||String(F);B="error",g(L),P||(P=!0,(X=e.onConnectionError)==null||X.call(e,L))}}finally{try{if(e.onFinish){const F={lastSeq:0,lastCheckpointId:null,lastCheckpointNs:null,lastValues:null};e.onFinish(F)}}catch(F){console.warn("[use-chat] onClosed callback failed",F)}u(!1),v(!1),S.current=null,A.current=null}})(),Promise.resolve()},[t,n,r,e,d]);return c.useEffect(()=>()=>{var y;E.current=!1,(y=S.current)==null||y.abort()},[]),{isStreaming:l,error:p,assistantText:"",activeMessageId:f,streamedMessages:{},lastCheckpointId:null,lastSeq:0,connected:m,stream:C,stop:b,clear:w,setToken:k,values:{},interrupt:()=>Promise.resolve(),resume:()=>Promise.resolve(),goto:()=>Promise.resolve(),connectionState:p?"error":l?m?"connected":"connecting":"idle",messages:[],submit:C}}function jt({api:e,initialThreadId:t=null,onError:n,onThreadChange:r,onCurrentThreadDeleted:s}){const[o,a]=c.useState([]),[i,d]=c.useState(t),[l,u]=c.useState(!1),[p,g]=c.useState(null),m=c.useRef(i),v=c.useRef(new Map);c.useEffect(()=>{m.current=i},[i]),c.useEffect(()=>{t!==void 0&&t!==m.current&&d(t)},[t]);const f=c.useCallback(async()=>{u(!0),g(null);try{const w=await e.listThreads();a(w??[])}catch(w){const b=String(w);g(b),n==null||n(b)}finally{u(!1)}},[e,n]);c.useEffect(()=>{f()},[f]),c.useEffect(()=>{r==null||r(i)},[i,r]);const T=c.useCallback(async(w,b)=>{try{const C=b&&typeof b=="object"?{id:b.id,name:b.name??""}:void 0,y=await e.createThread(w,C);return d(y.threadId),await f(),y.threadId}catch(C){const y=String(C);return n==null||n(y),null}},[e,n,f]),S=c.useCallback(async w=>{const b=o;a(y=>y.filter(I=>I.threadId!==w));const C=new AbortController;v.current.set(w,C);try{await e.deleteThread(w),m.current===w&&(d(null),s==null||s())}catch(y){a(b);const I=String(y);n==null||n(I)}finally{v.current.delete(w)}},[e,s,n,o]),E=c.useCallback(async(w,b)=>{try{await e.updateThread(w,b),await f()}catch(C){n==null||n(String(C))}},[e,n,f]),A=c.useMemo(()=>({createThread:T,deleteThread:S,renameThread:E,refreshThreads:f}),[T,S,E,f]),k=c.useCallback(w=>{if(!(w!=null&&w.threadId))return;const b={threadId:w.threadId,title:w.title||`Thread ${w.threadId.slice(0,8)}`,project:w.project,createdAt:w.createdAt||new Date().toISOString(),updatedAt:w.updatedAt||new Date().toISOString(),messageCount:w.messageCount??1};a(C=>{let y=!1;const I=C.map(_=>_.threadId===b.threadId?(y=!0,console.debug("[useThreadsState] thread_info: updating existing thread",b.threadId),{..._,title:b.title??_.title,project:b.project??_.project,updatedAt:b.updatedAt??_.updatedAt,messageCount:b.messageCount??_.messageCount}):_);return y?I:(console.debug("[useThreadsState] thread_info: adding thread to list",b.threadId),[b,...C])})},[]);return{threads:o,currentThreadId:i,currentThreadIdRef:m,setCurrentThreadId:d,isLoadingThreads:l,threadsError:p,actions:A,addThreadFromEvent:k}}const zt=c.createContext(null);function Lt({children:e,initialThreadId:t=null,onError:n,onThreadChange:r}){const{chatApi:s}=be(),{threads:o,currentThreadId:a,setCurrentThreadId:i,currentThreadIdRef:d,isLoadingThreads:l,threadsError:u,actions:p,addThreadFromEvent:g}=jt({api:s,initialThreadId:t,onError:n,onThreadChange:r}),m=c.useMemo(()=>({threads:o,currentThreadId:a,setCurrentThreadId:i,currentThreadIdRef:d,isLoading:l,error:u,actions:p,addThreadFromEvent:g}),[o,a,i,d,l,u,p,g]);return V.jsx(zt.Provider,{value:m,children:e})}function Le(e){const t=c.useContext(zt);if(!t&&!(e!=null&&e.optional))throw new Error("useThreads must be used within a ThreadsProvider");return t}function Ut(e){const t=e.artifact;return!t||typeof t!="object"?null:"metadata"in t&&t.metadata?t.metadata:{id:t.id??e.id??`artifact-${Date.now()}`,type:t.type??"unknown",createdAt:e.createdAt??new Date().toISOString(),status:t.status??"completed",progress:t.progress??void 0}}function wr(e,t){const n=Ut(e);if(!n)return e;const r={...n,...t,updatedAt:new Date().toISOString()};return{...e,artifact:{...typeof e.artifact=="object"&&e.artifact?e.artifact:{},metadata:r}}}function kr(e,t,n){return e.find(r=>{const s=Ut(r);return!!((s==null?void 0:s.id)===t||n&&r.toolCallId===n)})??null}function Ue(e){const t=new Set;return e.map(n=>We(n)).filter(n=>!n||t.has(n.id)?!1:(t.add(n.id),!0))}function Bt(e,t,n){return t<0||t>=e.length?e:[...e.slice(0,t),n,...e.slice(t+1)]}function Ir(e,t,n){for(let r=e.length-1;r>=0;r--)if(e[r].role==="assistant"){const o={...e[r],checkpointId:t,checkpointNs:n??void 0};return Bt(e,r,o)}return e}const Ft={status:"idle",messages:[],taskMessagesByScope:{},assemblingId:null,lastCheckpointId:null,lastCheckpointNs:null,messagesStreamMeta:{},pendingInterrupt:null,values:{},error:null};function vr(e,t){var n;switch(t.type){case"status":return{...e,status:t.payload.status,error:t.payload.error??e.error};case"reset":return{...Ft,messages:Ue(((n=t.payload)==null?void 0:n.messages)??[])};case"user_message":{const{message:r,editingMessageId:s}=t.payload;if(s){const o=e.messages.findIndex(a=>(a.id||a.messageId)===s);if(o!==-1){const a={...r,id:s};return{...e,status:"streaming",messages:[...e.messages.slice(0,o),a],assemblingId:null,lastCheckpointId:null,error:null}}}return{...e,status:"streaming",messages:[...e.messages,r],assemblingId:null,lastCheckpointId:null,error:null}}case"seed":{const r=Ue(t.payload.messages),s={...e,status:"idle",messages:r,assemblingId:null,pendingInterrupt:t.payload.pendingInterrupt??null,taskMessagesByScope:{},error:null};return Object.prototype.hasOwnProperty.call(t.payload,"checkpointId")&&(s.lastCheckpointId=t.payload.checkpointId??null),Object.prototype.hasOwnProperty.call(t.payload,"checkpointNs")&&(s.lastCheckpointNs=t.payload.checkpointNs??null),Object.prototype.hasOwnProperty.call(t.payload,"values")&&(s.values=t.payload.values??{}),s}case"prepend":{const r=Ue(t.payload.messages);if(!r.length)return e;const s=new Set(e.messages.map(a=>a.id)),o=r.filter(a=>!s.has(a.id));return o.length?{...e,messages:[...o,...e.messages]}:e}case"event":return Ot(e,t.payload.ev);case"batch":{const{events:r}=t.payload;return r.length?r.reduce((s,o)=>Ot(s,o),e):e}default:return e}}function Tr(e=[]){const[t,n]=c.useReducer(vr,{...Ft,messages:e}),r=c.useRef([]),s=c.useRef(null),o=c.useCallback(()=>{s.current!==null&&typeof window<"u"&&window.cancelAnimationFrame(s.current),s.current=null;const l=r.current;l.length&&(r.current=[],n({type:"batch",payload:{events:l}}))},[]),a=c.useCallback(()=>{typeof window<"u"&&typeof window.requestAnimationFrame=="function"?s.current===null&&(s.current=window.requestAnimationFrame(()=>o())):setTimeout(o,8)},[o]),i=c.useCallback(l=>{r.current.push(l),a()},[a]),d=c.useMemo(()=>({setStatus:(l,u)=>n({type:"status",payload:{status:l,error:u}}),reset:l=>n({type:"reset",payload:{messages:l}}),seed:(l,u)=>n({type:"seed",payload:{messages:l,...u??{}}}),pushUser:(l,u)=>n({type:"user_message",payload:{message:l,editingMessageId:u}}),onEvent:i}),[i]);return{state:t,dispatch:n,...d}}function Ot(e,t){const n=t.origin,r=t.scope,s=n==="task"||typeof r=="string"&&r.startsWith("tools:");if(t.type==="checkpoint"){const o=t.checkpointNs??e.lastCheckpointNs??null,a=Ir(e.messages,t.checkpointId,o);return{...e,lastCheckpointId:t.checkpointId,lastCheckpointNs:o,messages:a}}if(t.type==="status"){const o=t.status==="completed"||t.status==="error"?"idle":t.status==="interrupted"?"awaiting_input":e.status;return{...e,status:o}}if(t.type==="interrupt")return{...e,status:"awaiting_input",pendingInterrupt:{id:t.id,value:t.value,alternatives:t.alternatives}};if(t.type==="error"){const o={id:`err-${Date.now()}`,role:"system",content:[{type:"text",text:`Error: ${t.message}`}],createdAt:new Date().toISOString()};return{...e,status:"error",error:t.message,messages:[...e.messages,o]}}if(t.type==="values"){const o=t,a=o.values&&typeof o.values=="object"?{...o.values}:{},i=Array.isArray(o.messages)?o.messages:Array.isArray(a.messages)?a.messages:[];if(!i.length&&Object.keys(a).length===0)return e;const d=Ue(i);delete a.messages;let l=e.lastCheckpointId,u=e.lastCheckpointNs;const p=o.config||o.checkpoint,g=(p==null?void 0:p.configurable)||p;if((g!=null&&g.checkpoint_id||g!=null&&g.checkpointId)&&(l=g.checkpoint_id||g.checkpointId,u=g.checkpoint_ns||g.checkpointNs||null),!l){for(let f=d.length-1;f>=0;f--)if(d[f].checkpointId){l=d[f].checkpointId,u=d[f].checkpointNs??null;break}}const m=o.interrupts||a.__interrupt__||a.interrupts,v=Array.isArray(m)&&m.length>0?{id:m[0].id||"native-interrupt",value:m[0].value||m[0],alternatives:m[0].alternatives}:null;if(s){const f=typeof r=="string"&&r.length>0?r:"task";return{...e,taskMessagesByScope:{...e.taskMessagesByScope,[f]:d},assemblingId:null}}return{...e,status:v?"awaiting_input":e.status==="streaming"?"idle":e.status,messages:d,assemblingId:null,lastCheckpointId:l,lastCheckpointNs:u,pendingInterrupt:v,values:{...e.values,...a}}}if(t.type==="messages/metadata"){const o={...e.messagesStreamMeta??{}},a=t.metadata;return a&&typeof a=="object"&&Object.entries(a).forEach(([i,d])=>{const l=d==null?void 0:d.metadata;if(!l||typeof l!="object")return;const u=o[i]??{};o[i]={...u,lastSeq:t.seq??u.lastSeq??null,metadata:{...u.metadata??{},...l}}}),{...e,messagesStreamMeta:o}}if(t.type==="messages/partial"||t.type==="message.delta"){const o=t.type==="messages/partial"?t:{...t,type:"messages/partial",messages:t.delta?[{id:t.id,type:"ai",content:t.delta,scope:t.scope,origin:t.origin}]:[]};return Sr(e,o,s)}return t.type==="message.start"?{...e,assemblingId:t.id,status:"streaming"}:t.type==="message.end"?{...e,assemblingId:null}:t.type==="tool.start"?{...Ar(e,t,s),status:"streaming"}:t.type==="tool.progress"?Cr(e,t,s):t.type==="tool.end"?xr(e,t,s):t.type==="artifact.update"?Mr(e,t):e}function Sr(e,t,n){var m,v,f,T,S,E,A;const r=t.messages;if(!r.length)return console.warn("[messagesReducer] Dropping messages/partial event without messages[]",t),e;const s=r.find(k=>k.type==="ai"||k.type==="assistant"||k.role==="assistant");if(!s)return e;const o=s.id,a=s.content??"",i=typeof a=="string"?[{type:"text",text:a}]:Array.isArray(a)?a.map(k=>typeof k=="string"?{type:"text",text:k}:(k==null?void 0:k.type)==="text"?{type:"text",text:typeof k.text=="string"?k.text:k.content??""}:((k==null?void 0:k.type)==="reasoning",k)):[],d=i.filter(k=>k.type==="text").map(k=>k.text).join(""),l=e.assemblingId!==o,u=typeof t.scope=="string"&&t.scope.length>0?t.scope:"task";let p=n?[...e.taskMessagesByScope[u]||[]]:[...e.messages];const g=(v=(m=e.messagesStreamMeta)==null?void 0:m[o])==null?void 0:v.metadata;if(l){const k=We({...s,role:"assistant",content:i,scope:t.scope,origin:t.origin,responseMetadata:{...g,...s.responseMetadata??{}}});k&&p.push(k)}else{const k=p.findIndex(w=>w.id===o);if(k!==-1){const w=p[k];p[k]={...w,content:i,scope:t.scope??w.scope,origin:t.origin??w.origin,responseMetadata:{...g,...w.responseMetadata,...s.responseMetadata??{}}}}}return{...e,status:"streaming",messages:n?e.messages:p,taskMessagesByScope:n?{...e.taskMessagesByScope,[u]:p}:e.taskMessagesByScope,assemblingId:o,messagesStreamMeta:{...e.messagesStreamMeta??{},[o]:{...((f=e.messagesStreamMeta)==null?void 0:f[o])??{},lastSeq:t.seq??((S=(T=e.messagesStreamMeta)==null?void 0:T[o])==null?void 0:S.lastSeq)??null,lastText:d||(((A=(E=e.messagesStreamMeta)==null?void 0:E[o])==null?void 0:A.lastText)??"")}}}}function nt(e,t){var n;if(!t)return-1;for(let r=e.length-1;r>=0;r--){const s=e[r];if(s.role==="assistant"&&((n=s.toolCalls)!=null&&n.some(o=>o.id===t)))return r}return-1}function Ar(e,t,n){const r=t.id||t.callId;if(!r)return e;const s=t.name||"tool",o=`Starting ${s}...`,a=typeof t.scope=="string"&&t.scope.length>0?t.scope:"task";let i=n?[...e.taskMessagesByScope[a]||[]]:[...e.messages],d=nt(i,r);if(d===-1){for(let l=i.length-1;l>=0;l--)if(i[l].role==="assistant"){d=l;break}}if(d===-1){const l={id:`assistant-${r}`,role:"assistant",content:[{type:"text",text:""}],createdAt:new Date().toISOString(),toolCalls:[],scope:t.scope,origin:t.origin};i.push(l),d=i.length-1}if(d!==-1){const l=i[d],u=[...l.toolCalls||[]],p=u.findIndex(g=>g.id===r);p>=0?u[p]={...u[p],status:"running",content:o}:u.push({id:r,name:s,args:t.args||{},status:"running",content:o}),i[d]={...l,toolCalls:u,scope:t.scope??l.scope,origin:t.origin??l.origin}}return{...e,messages:n?e.messages:i,taskMessagesByScope:n?{...e.taskMessagesByScope,[a]:i}:e.taskMessagesByScope}}function Cr(e,t,n){const r=t.id;if(!r)return e;const s=typeof t.scope=="string"&&t.scope.length>0?t.scope:"task";let o=n?[...e.taskMessagesByScope[s]||[]]:[...e.messages];const a=nt(o,r);if(a!==-1){const i=o[a],d=oe(t.content),l=(i.toolCalls||[]).map(u=>u.id===r?{...u,content:typeof d=="string"?d:u.content}:u);o[a]={...i,toolCalls:l,scope:t.scope??i.scope,origin:t.origin??i.origin}}return{...e,messages:n?e.messages:o,taskMessagesByScope:n?{...e.taskMessagesByScope,[s]:o}:e.taskMessagesByScope}}function xr(e,t,n){const r=t.id;if(!r)return e;const s=typeof t.scope=="string"&&t.scope.length>0?t.scope:"task";let o=n?[...e.taskMessagesByScope[s]||[]]:[...e.messages];const a=nt(o,r),i=oe(t.content??t.error);if(a!==-1){const l=o[a],u=(l.toolCalls||[]).map(p=>p.id===r?{...p,status:t.error?"failed":"completed",content:typeof i=="string"?i:p.content,artifact:t.artifact}:p);o[a]={...l,toolCalls:u,scope:t.scope??l.scope,origin:t.origin??l.origin}}const d={id:`tool-${r}`,role:"tool",name:t.name,content:[{type:"text",text:typeof i=="string"?i:""}],artifact:t.artifact,toolCallId:r,createdAt:new Date().toISOString(),scope:t.scope,origin:t.origin};return o.push(d),{...e,messages:n?e.messages:o,taskMessagesByScope:n?{...e.taskMessagesByScope,[s]:o}:e.taskMessagesByScope}}function Mr(e,t){const n=t.artifactId,r=kr(e.messages,n,t.callId);if(!r)return e;const s=e.messages.indexOf(r),o=wr(r,{status:t.status,progress:t.progress,error:t.error});return t.partial_data&&o.artifact&&(o.artifact={...o.artifact,...t.partial_data}),{...e,messages:Bt(e.messages,s,o)}}function Pe(e){if(!(!e||typeof e!="object"||Array.isArray(e)))return{...e}}function Be(e,t){if(e)for(const n of t){const r=e[n];if(typeof r=="string"&&r.trim())return r.trim()}}function Er(e,t){if(!e)return null;for(const n of t){const r=e[n];if(typeof r=="number"&&Number.isFinite(r))return r}return null}function $t(e){const t=Pe(e);if(t)return Pe(t.configurable)??t}async function Dt(e,t){var i,d;if(!e)return e??null;const n=ae(e),r=Array.isArray(n.checkpoints)?n.checkpoints:n.checkpoints?Object.values(n.checkpoints):[],s=new Set;for(const l of r){const u=(i=l==null?void 0:l.values)==null?void 0:i.messages;if(Array.isArray(u))for(const p of u){const g=p==null?void 0:p.content;if(Array.isArray(g))for(const m of g){if(!m||typeof m!="object"||m.type!=="image_url"&&m.type!=="file")continue;const v=m.fileId||m.file_id;typeof v=="string"&&v.trim()&&s.add(v)}}}if(s.size===0)return n;const o=await Promise.all(Array.from(s).map(async l=>{try{const u=await t.getFileInfo(l),p=ae(u);return[l,p]}catch{return[l,null]}})),a=new Map(o);for(const l of r){const u=(d=l==null?void 0:l.values)==null?void 0:d.messages;if(Array.isArray(u))for(const p of u){const g=p==null?void 0:p.content;if(Array.isArray(g))for(const m of g){if(!m||typeof m!="object"||m.type!=="image_url"&&m.type!=="file")continue;const v=m.fileId||m.file_id;if(!v)continue;const f=a.get(v),T=(f==null?void 0:f.contentUrl)||(f==null?void 0:f.content_url);T&&(m.type==="image_url"?(m.imageUrl=m.imageUrl||{},m.imageUrl.url=T):m.type==="file"&&(m.url=T,!m.name&&(f!=null&&f.filename||f!=null&&f.name)&&(m.name=(f==null?void 0:f.filename)||(f==null?void 0:f.name))))}}}return n}function rt(e){const r=[...(Array.isArray(e==null?void 0:e.checkpoints)?(e==null?void 0:e.checkpoints)??[]:e!=null&&e.checkpoints?Object.values(e.checkpoints):[]).map((o,a)=>Pr(ae(o),a)).filter(o=>!!o)].sort((o,a)=>qt(a.createdAt)-qt(o.createdAt)),s=r[0]??null;return{threadId:(e==null?void 0:e.threadId)??"",latest:s,checkpoints:r,interrupt:(s==null?void 0:s.interrupt)??null}}function Pr(e,t){var w,b;if(!e)return null;const n=((w=e.values)==null?void 0:w.activeAgent)??null,r=(b=e.values)==null?void 0:b.messages,o=(Array.isArray(r)?r:[]).map(C=>_r(C,n)).filter(C=>!!C),a=Pe(e.metadata)??{},i=$t(e.config),d=Pe(e.parentConfig),l=$t(d),u=Be(i,["checkpointId"]),p=Be(i,["checkpointNs"]),g=Be(l,["checkpointId"]),m=Pe(e.config),v=Array.isArray(e.tasks)?e.tasks.map(C=>({...C})):e.tasks??null,f=Array.isArray(e.next)?[...e.next]:e.next??null,T=typeof e.createdAt=="string"&&e.createdAt.trim()?e.createdAt:new Date(Date.now()-t).toISOString(),S={...a,step:Er(a,["step"])??0,source:Be(a,["source"])??null},E=o.map(C=>({...C,checkpointId:C.checkpointId??u??null,checkpointNs:C.checkpointNs??p??null})),A=e.values,k=Array.isArray(e.interrupts)?e.interrupts:Array.isArray(A==null?void 0:A.interrupts)?A.interrupts:[];return{checkpointId:u??null,checkpointNs:p??null,createdAt:T,parentId:g??null,messages:E,interrupt:Nr(k,t,u??null),metadata:S,config:m??null,parentConfig:d??null,next:f,tasks:v,values:e.values??{}}}function _r(e,t){const n=We(e);return n?(n.role==="assistant"&&!n.name&&t&&(n.name=t),n):null}function Nr(e,t,n){const r=e.length;for(let s=r-1;s>=0;s-=1){const o=e[s];if(!o||typeof o!="object")continue;const a=o,i=a.value??o;if(i==null)continue;return{id:typeof a.id=="string"&&a.id.trim()?a.id:`interrupt-${n??t}-${s}`,value:i}}return null}function qt(e){if(!e)return 0;const t=Date.parse(e);return Number.isFinite(t)?t:0}const Ht=120;function jr(e){if(!Array.isArray(e))return"";const t=e.filter(r=>!!(r&&r.type==="text")).map(r=>(r.text??"").trim()).filter(Boolean);if(!t.length)return"";const n=t.join(" ").replace(/\s+/g," ").trim();return n?n.length>Ht?`${n.slice(0,Ht-3)}…`:n:""}function zr(e){return jr(e.content)||""}function Lr(e){const t=new Map,n=[],r=new Map,s=[];for(let l=0;l<e.length;l++){const u=e[l],p=u.checkpointId,g=p??`cp-${l}`,m=u.metadata??{},v=typeof m.step=="number"?m.step:null,f=typeof m.source=="string"?m.source:null;let T=null,S=null;const E=Array.isArray(u.messages)?u.messages:[];for(const b of E)b.role==="user"&&(S||(S=b),b.id&&(T=b.id));const A=u.next&&u.next.length>0?String(u.next[0]):null,k=u.parentConfig??null,w={id:g,step:v,source:f,createdAt:u.createdAt??null,namespace:u.checkpointNs??null,parentId:u.parentId??null,next:A,parentConfig:k,userMessageId:T};if(s.push(w),p&&t.set(p,w),p&&S){const b=zr(S);b&&r.set(p,b)}n.push({id:g,messageId:T,step:v,source:f,createdAt:u.createdAt??null,next:A,parentConfig:k})}const o=new Map;for(const l of s){if(!l.userMessageId)continue;const u=o.get(l.userMessageId)??[];u.push(l),o.set(l.userMessageId,u)}for(const l of o.values()){if(!l.length)continue;l.sort((p,g)=>{const m=p.createdAt?Date.parse(p.createdAt):0;return(g.createdAt?Date.parse(g.createdAt):0)-m});const u=l.length;for(let p=0;p<l.length;p++){const g=l[p];g.attemptCount=u,g.attemptIndex=p,g.isLatestAttempt=p===0}}return{checkpoints:e,checkpointMetaByCheckpointId:t,timeline:n,messagePreviews:r,getLatest:()=>{const l=n[0];if(l)return t.get(l.id)},getCheckpoint:l=>t.get(l),getMessageAttempts:l=>{const u=[];for(const p of t.values())p.userMessageId===l&&u.push(p);return u.length?(u.sort((p,g)=>{const m=typeof p.attemptIndex=="number"?p.attemptIndex:Number.MAX_SAFE_INTEGER,v=typeof g.attemptIndex=="number"?g.attemptIndex:Number.MAX_SAFE_INTEGER;return m-v}),u):[]}}}function Ur(e,t,n){if(!e)return{attemptCount:1,attemptIndex:0,attempts:[]};const r=n.getMessageAttempts(e);if(!r.length)return{attemptCount:1,attemptIndex:0,attempts:[]};let s=0;if(t){const o=r.findIndex(a=>a.id===t);o>=0&&(s=o)}return{attemptCount:r.length,attemptIndex:s,attempts:r}}function Br(e){return c.useMemo(()=>Lr(e),[e])}function st({api:e,fileApi:t,seed:n,onError:r,currentThreadId:s,autoLoadInitial:o=!0,isStreaming:a,getMessages:i}){const[d,l]=c.useState(null),p=c.useMemo(()=>rt(d),[d]).checkpoints,g=Br(p),m=g.timeline,[v,f]=c.useState(!1),[T,S]=c.useState(!1),[E,A]=c.useState(!1),[k,w]=c.useState(null),b=c.useRef(s),C=c.useRef(null),y=c.useRef(null);c.useEffect(()=>{b.current=s},[s]);const I=c.useCallback(async N=>{const O=await e.getState({threadId:N.threadId,checkpointId:N.checkpointId,checkpointNs:N.checkpointNs}),z={version:"values@1",threadId:N.threadId,checkpoints:[O]},X=t?await Dt(z,t):z,{latest:F}=rt(X);return F},[e,t]),_=c.useCallback(async(N,O)=>{var F;if(!N)return;const z=`${N}:${O??"latest"}`;if(C.current===z||v)return;(F=y.current)==null||F.abort();const X=new AbortController;y.current=X,f(!0),w(null);try{const L=await I({threadId:N,checkpointId:O??void 0});if(b.current!==N){f(!1);return}n((L==null?void 0:L.messages)??[],{checkpointId:(L==null?void 0:L.checkpointId)??null,checkpointNs:(L==null?void 0:L.checkpointNs)??null,pendingInterrupt:(L==null?void 0:L.interrupt)??null,values:L==null?void 0:L.values}),C.current=z,f(!1),A(!0);try{const G=await e.getStateHistory({threadId:N,limit:100,includeMessages:!1});b.current===N&&l(G)}finally{A(!1)}}catch(L){if(f(!1),!lt.isCancel(L)){const G=String(L);w(G),r==null||r(G)}}},[e,n,I,r,i]),B=c.useCallback(async(N,O)=>{if(s){S(!0);try{const z=await I({threadId:s,checkpointId:N,checkpointNs:O??void 0});n((z==null?void 0:z.messages)??[],{checkpointId:(z==null?void 0:z.checkpointId)??N,checkpointNs:(z==null?void 0:z.checkpointNs)??O,pendingInterrupt:(z==null?void 0:z.interrupt)??null,values:z==null?void 0:z.values})}catch(z){console.error("[useThreadHistoryState] Navigation failed",z)}finally{S(!1)}}},[s,I,n]),P=c.useCallback(async()=>{s&&await _(s)},[s,_]),D=c.useCallback(async N=>{const O=(N==null?void 0:N.threadId)||s;!O||s!==O||(l(N),C.current=`${O}:latest`)},[s]);c.useEffect(()=>{if(!o||!s||v||a)return;const N=`${s}:latest`;C.current!==N&&_(s)},[o,s,v,a,_]);const $=c.useCallback(()=>{l(null),f(!1),S(!1),A(!1),w(null),C.current=null},[]);return{threadCheckpoints:p,threadTimeline:m,checkpointIndex:g,isLoadingThread:v,isLoadingCheckpoint:T,isLoadingHistory:E,threadStateError:k,loadThread:_,navigateToCheckpoint:B,setCurrentCheckpointId:(N,O)=>{n(i(),{checkpointId:N,checkpointNs:O})},returnToLatest:P,handleValuesEvent:D,markSkipNextLoad:()=>{},markStreamPendingThread:()=>{},resetHistoryState:$,clearState:$}}const Kt=c.createContext(null),Vt=c.createContext(null);function ot(e){const t=c.useContext(Kt);if(!t&&!(e!=null&&e.optional))throw new Error("useThreadState must be used within a ThreadStateProvider");return t}function Gt(){const e=c.useContext(Vt);if(!e)throw new Error("useThreadStateUpdater must be used within a ThreadStateProvider");return e}function Wt({children:e,initialThreadId:t=null,initialCheckpointId:n=null,initialCheckpointNs:r=null,autoLoadInitial:s=!0,isStreaming:o,onError:a}){const{chatApi:i,fileApi:d}=be(),{currentThreadId:l}=Le(),{state:u,seed:p,onEvent:g,dispatch:m}=Tr(),{threadCheckpoints:v,threadTimeline:f,checkpointIndex:T,isLoadingThread:S,isLoadingCheckpoint:E,isLoadingHistory:A,threadStateError:k,loadThread:w,navigateToCheckpoint:b,setCurrentCheckpointId:C,returnToLatest:y,handleValuesEvent:I,markSkipNextLoad:_,markStreamPendingThread:B,resetHistoryState:P}=st({api:i,fileApi:d,seed:p,onError:a,currentThreadId:l,initialThreadId:t,initialCheckpointId:n,initialCheckpointNs:r,autoLoadInitial:s,isStreaming:o,getMessages:c.useCallback(()=>u.messages,[u.messages])}),D=c.useRef(null),$=c.useCallback(x=>{D.current=x},[]),N=c.useRef(null),O=c.useCallback(x=>{N.current=x},[]),z=c.useMemo(()=>({assemblingMessageId:u.assemblingId??null}),[u.assemblingId]),X=c.useCallback((x,J)=>{const H=_t(x,"user");return m({type:"user_message",payload:{message:H,editingMessageId:J==null?void 0:J.editingMessageId}}),H},[m]),F=c.useCallback(async()=>{D.current?await D.current():(p([],{}),P())},[p,P]),L=c.useCallback(async(x,J,H)=>{await w(x,J,{clearProgress:!1})},[w]),G=c.useMemo(()=>qn(u.messages),[u.messages]),h=c.useMemo(()=>({status:u.status,threadId:l,messages:u.messages,taskMessagesByScope:u.taskMessagesByScope,interrupt:u.pendingInterrupt,checkpoint:{id:u.lastCheckpointId??null,namespace:u.lastCheckpointNs??null},checkpoints:v,checkpointIndex:T,timelineCheckpoints:f,metadata:z,values:u.values??{},isLoading:S,isLoadingCheckpoint:E,isLoadingHistory:A,error:k,loadOlder:async()=>{},seedFromSnapshot:x=>{p(x.messages,{checkpointId:x.checkpointId,checkpointNs:x.checkpointNs,pendingInterrupt:x.interrupt,values:x.values})},clearState:F,navigateToCheckpoint:b,setCurrentCheckpointId:C,returnToLatest:y,loadThread:L,clearThread:F,respondToInterrupt:async(x,J,H)=>{N.current&&await N.current(x,J,H)},messagePreviews:T.messagePreviews,handleValuesEvent:I,markSkipNextLoad:_,markStreamPendingThread:B,resetHistoryState:P,pushUser:X,onEvent:g,artifacts:G}),[l,u.messages,u.taskMessagesByScope,u.pendingInterrupt,u.lastCheckpointId,u.lastCheckpointNs,u.values,v,f,T,z,S,E,A,k,p,F,b,C,y,L,I,_,B,X,g,G]),U=c.useMemo(()=>({registerClearThread:$,registerRespondToInterrupt:O}),[$,O]);return V.jsx(Vt.Provider,{value:U,children:V.jsx(Kt.Provider,{value:h,children:e})})}const Jt=c.createContext(null),Fr=c.createContext(!1);function Or({children:e,onError:t,onAuthError:n,onConnectionError:r,onToolEnd:s,onUpdateEvent:o,onCustomEvent:a,onMetadataEvent:i,onFinish:d,onStreamingChange:l}){const{chatApi:u,baseUrl:p}=be(),g=p,m=le(t),v=le(n),f=le(r),T=le(s),S=le(o),E=le(a),A=le(i),k=le(d),w=le(l),b=c.useMemo(()=>({onError:m,onAuthError:v,onConnectionError:f,onMetadataEvent:A,onCustomEvent:E,onUpdateEvent:S,onToolEnd:T,onFinish:k}),[m,v,f,A,E,S,T,k]);return V.jsx(Fr.Provider,{value:!0,children:V.jsx($r,{api:u,streamBaseUrl:g,handlers:b,onStreamingChange:w,children:e})})}function $r({children:e,api:t,streamBaseUrl:n,handlers:r,onStreamingChange:s}){const{setCurrentThreadId:o,currentThreadIdRef:a,addThreadFromEvent:i,currentThreadId:d}=Le(),{interrupt:l,checkpoint:u,timelineCheckpoints:p,handleValuesEvent:g,markSkipNextLoad:m,markStreamPendingThread:v,resetHistoryState:f,pushUser:T,onEvent:S,messages:E}=ot(),{registerClearThread:A,registerRespondToInterrupt:k}=Gt(),w=c.useCallback(h=>{i(h),v(h.threadId),a.current!==h.threadId&&((h.created??!a.current)&&m(h.threadId),o(h.threadId))},[i,m,v,o,a]),b=Nt({baseUrl:n,onEvent:S,onError:h=>{var U;(U=r.onError)==null||U.call(r,(h==null?void 0:h.message)??String(h))},onAuthError:r.onAuthError,onConnectionError:r.onConnectionError,onFinish:r.onFinish,onThreadInfo:w,onMetadataEvent:r.onMetadataEvent,onCustomEvent:r.onCustomEvent,onUpdateEvent:r.onUpdateEvent,onToolEnd:r.onToolEnd,handleValuesEvent:g});c.useEffect(()=>{s==null||s(b.isStreaming)},[b.isStreaming,s]);const{stream:C,stop:y,clear:I,isStreaming:_,error:B,connected:P,streamedMessages:D,activeMessageId:$}=b;c.useEffect(()=>{d!==void 0&&I()},[d,I]);const N=c.useCallback(async(h,U)=>{await C(h,U)},[C]),O=c.useRef(u);c.useEffect(()=>{O.current=u},[u]);const z=c.useCallback(async(h,U,x)=>{var W;const J=a.current;if(!J)throw new Error("No active thread to handle interrupt");const H=h?U??!0:!1,K=O.current,Z=(x==null?void 0:x.checkpointId)??K.id??void 0,ne=(x==null?void 0:x.checkpointNs)??K.namespace??void 0,ue={threadId:J,checkpointId:Z,checkpointNs:ne,command:{kind:"resume",value:H},payload:{...(x==null?void 0:x.payload)??{},creativityLevel:((W=x==null?void 0:x.payload)==null?void 0:W.creativityLevel)??"medium"},edit:!1};N(ue)},[a,N]);c.useEffect(()=>{k(z)},[z,k]);const X=c.useCallback(async()=>{y(),I(),f(),o(null)},[I,f,o,y]);c.useEffect(()=>{A(X)},[X,A]);const F=c.useCallback(async(h,U)=>{_&&y();let x=a.current;const J=(h==null?void 0:h.text)??"",H=(h==null?void 0:h.attachments)??[],K=(J==null?void 0:J.trim())??"",Z={...(h==null?void 0:h.payload)??{}},ne=Array.isArray(Z.messages)?Z.messages:void 0;ne&&delete Z.messages;const ue=!!(ne&&ne.length),W=!!(h.contentParts&&h.contentParts.length>0);if(!x&&!K&&H.length===0&&!ue&&!W)return;if(!x){const ye=Math.floor(Date.now()/1e3).toString(16).padStart(8,"0"),he=Array.from({length:4},()=>Math.floor(Math.random()*4294967295).toString(16).padStart(8,"0")).join("").slice(0,16);x=`${ye}${he}`,m(x),o(x)}let R=null;h.contentParts&&h.contentParts.length>0&&(R=h.contentParts);const{contentParts:we,filesInfo:Q}=R?{contentParts:R,filesInfo:[]}:await cr(H),Y=[...we];K&&Y.push({type:"text",text:J});const ge=h==null?void 0:h.originalMessageId,$e=!!(h!=null&&h.edit&&ge),De=!ue&&Y.length>0;let me=null;if(De){const ye=$e?ge:`msg-${Date.now()}`;me=_t({id:ye,role:"user",content:Y,createdAt:new Date().toISOString()},"user"),$e?T(me,{editingMessageId:ge}):T(me)}const Te=ue?ne:me?[me]:[],re={...Z,...Q.length?{files_info:Q}:{}};Te.length?re.messages=Te:"messages"in re||(re.messages=[]);const Ne=(h==null?void 0:h.checkpointId)??u.id??void 0;if(h!=null&&h.edit&&!Ne)throw new Error(`[streaming] Missing checkpointId for edit submit. threadId=${x??"null"}`);const Se={threadId:x,content:h==null?void 0:h.text,payload:re,config:h==null?void 0:h.config,checkpointId:Ne,command:h==null?void 0:h.command,edit:h==null?void 0:h.edit};return N(Se,U)},[u,a,_,m,T,N,y,p]),L=c.useMemo(()=>E,[E]),G=c.useMemo(()=>({isStreaming:_,error:B,connectionState:B?"error":_?P?"connected":"connecting":"idle",messages:L,activeMessageId:$,submit:F,stop:y,interrupt:l,resume:()=>Promise.resolve(),goto:(h,U)=>Promise.resolve(),clearError:()=>{}}),[_,B,F,y,l,P,L]);return V.jsx(Jt.Provider,{value:G,children:e})}function le(e){const t=c.useRef(e);return c.useEffect(()=>{t.current=e},[e]),c.useCallback((...n)=>{const r=t.current;if(r)return r(...n)},[])}function Dr(e){return c.useContext(Jt)}function Xt(e){return typeof e=="object"&&e!==null}function qr(e,t){if(Object.is(e,t))return!0;if(!Xt(e)||!Xt(t))return!1;const n=Object.keys(e),r=Object.keys(t);if(n.length!==r.length)return!1;for(const s of n)if(!Object.prototype.hasOwnProperty.call(t,s)||!Object.is(e[s],t[s]))return!1;return!0}function Hr(e){const t=c.useRef(e),n=c.useRef(e);return qr(t.current,e)||(t.current=e,n.current=e),n.current}function Qt(e){const t=e.artifact&&typeof e.artifact=="object"?e.artifact:null,n=!t&&e.content&&typeof e.content=="object"?e.content:null,r=t??n,s=(r==null?void 0:r.task_id)??(r==null?void 0:r.taskId)??null;return typeof s=="string"?s:null}function Kr(e){const{setCurrentTaskId:t,getCurrentTaskId:n,onToolEnd:r}=e;return s=>{const o=Qt(s),a=(n==null?void 0:n())??null;o&&o!==a&&t(o),r==null||r(s)}}function Vr({children:e,apiConfig:t,initialThreadId:n=null,initialCheckpointId:r=null,initialCheckpointNs:s=null,autoLoadInitial:o=!0,onConnectionError:a,onError:i,onAuthError:d,onThreadChange:l,onToolEnd:u,onUpdateEvent:p,onCustomEvent:g,onMetadataEvent:m,onFinish:v}){const f=Hr(t),[T,S]=c.useState(!1),E=ce(i),A=ce(d),k=ce(a),w=ce(l),b=ce(u),C=ce(p),y=ce(g),I=ce(m),_=ce(v),B=c.useMemo(()=>({onError:E,onAuthError:A,onConnectionError:k,onToolEnd:b,onUpdateEvent:C,onCustomEvent:y,onMetadataEvent:I,onFinish:_}),[E,A,k,b,C,y,I,_]);return V.jsx(ir,{apiConfig:f,children:V.jsx(Lt,{initialThreadId:n,onError:E,onThreadChange:w,children:V.jsx(Wt,{initialThreadId:n,initialCheckpointId:r,initialCheckpointNs:s,autoLoadInitial:o,onError:E,isStreaming:T,children:V.jsx(Or,{...B,onStreamingChange:S,children:e})})})})}function ce(e){const t=c.useRef(e);return t.current=e,c.useCallback((...n)=>{const r=t.current;if(r)return r(...n)},[])}const Gr=1,Wr=1e6;let at=0;function Jr(){return at=(at+1)%Number.MAX_SAFE_INTEGER,at.toString()}const it=new Map,Yt=e=>{if(it.has(e))return;const t=setTimeout(()=>{it.delete(e),_e({type:"REMOVE_TOAST",toastId:e})},Wr);it.set(e,t)},Xr=(e,t)=>{switch(t.type){case"ADD_TOAST":return{...e,toasts:[t.toast,...e.toasts].slice(0,Gr)};case"UPDATE_TOAST":return{...e,toasts:e.toasts.map(n=>n.id===t.toast.id?{...n,...t.toast}:n)};case"DISMISS_TOAST":{const{toastId:n}=t;return n?Yt(n):e.toasts.forEach(r=>{Yt(r.id)}),{...e,toasts:e.toasts.map(r=>r.id===n||n===void 0?{...r,open:!1}:r)}}case"REMOVE_TOAST":return t.toastId===void 0?{...e,toasts:[]}:{...e,toasts:e.toasts.filter(n=>n.id!==t.toastId)}}},Fe=[];let Oe={toasts:[]};function _e(e){Oe=Xr(Oe,e),Fe.forEach(t=>{t(Oe)})}function Qr({...e}){const t=Jr(),n=s=>_e({type:"UPDATE_TOAST",toast:{...s,id:t}}),r=()=>_e({type:"DISMISS_TOAST",toastId:t});return _e({type:"ADD_TOAST",toast:{...e,id:t,open:!0,onOpenChange:s=>{s||r()}}}),{id:t,dismiss:r,update:n}}function Yr(){const[e,t]=ct.useState(Oe);return ct.useEffect(()=>(Fe.push(t),()=>{const n=Fe.indexOf(t);n>-1&&Fe.splice(n,1)}),[e]),{...e,toast:Qr,dismiss:n=>_e({type:"DISMISS_TOAST",toastId:n})}}function Zr(e){const{allowFileOpen:t,currentThreadId:n}=e,{fileApi:r}=be(),{toast:s}=Yr(),[o,a]=c.useState({}),[i,d]=c.useState(null),[l,u]=c.useState(!1),p=c.useCallback(()=>{u(!1),d(null)},[]),g=c.useCallback(v=>{d(v),u(!0)},[]),m=c.useCallback(async(v,f,T)=>{var S,E;if(!t){v.preventDefault();return}if(o[T]){v.preventDefault();return}try{const A=String(f.url??""),k=A.match(/\/chat\/files\/([^/]+)(?:\/(view|download))?/);if(k){v.preventDefault();const w=k[1],b=f.name||`file_${w}`,C=f.mimeType||"application/octet-stream";g({id:w,name:b,mimeType:C});return}if(A.startsWith("data:")){v.preventDefault(),a(b=>({...b,[T]:!0}));const w=s({title:"Fetching file...",description:"",open:!0});try{const b=await r.listFiles(n??void 0);if(!b||!Array.isArray(b))throw new Error("Invalid file list response");const C=b.find(y=>!y||typeof y!="object"||!((y.filename??"")===(f.name??""))?!1:typeof f.size=="number"&&typeof y.size=="number"?y.size===f.size:!0);if(!(C!=null&&C.id))throw new Error(`File "${f.name}" is not yet available on the server`);if(!C.id||!C.filename)throw new Error("Invalid file data received from server");g({id:C.id,name:f.name||C.filename||`file_${C.id}`,mimeType:f.mimeType||C.mime_type||"application/octet-stream"}),(S=w.update)==null||S.call(w,{id:w.id,title:"Success",description:`Opened ${f.name}`,open:!0})}catch(b){console.error("Failed to fetch server file:",b);const C=b instanceof Error?b.message:"Unknown error occurred";(E=w.update)==null||E.call(w,{id:w.id,title:"Failed",description:C}),s({title:"Failed to fetch file",description:C,open:!0})}finally{a(b=>({...b,[T]:!1}))}}}catch(A){console.error("File click error:",A),a(k=>({...k,[T]:!1}))}},[t,o,s,n,g]);return{uploadingFiles:o,handleFileClick:m,fileViewerOpen:l,currentFileInfo:i,closeFileViewer:p}}function Rr(e){return c.useMemo(()=>{const t=e;let n=Array.isArray(t.content)?t.content:[];return typeof t.content=="string"&&(n=[{type:"text",text:t.content}]),{contentParts:n,textContent:Et(n),toolMeta:Pt(t),imageParts:n.filter(r=>r.type==="image_url"),fileParts:n.filter(r=>r.type==="file"),toolRaw:kt(n),isToolStreaming:!!t.toolStreaming}},[e])}const Zt="data:";function es(e){if(!e)return[];const t=[],n=e.split(/\r?\n/);for(const r of n){const s=r.trim();if(!s||!s.startsWith(Zt))continue;const o=s.slice(Zt.length).trim();if(!o||o.toLowerCase()==="[done]")continue;const a=je(o);a&&typeof a=="object"&&t.push(a)}return t}function ts(e){for(let t=e.length-1;t>=0;t-=1){const n=e[t];if(n&&typeof n=="object"&&n.type==="tool.end")return n}return null}function ns(e){return c.useMemo(()=>{const t=e.content.filter(d=>d.type==="text");if(!t.length)return null;let r=t.flatMap(d=>es(d.text??""));if(!r.length){const d=t.map(u=>u.text??"").join(`
8
8
  `),l=je(d);l&&typeof l=="object"&&(r=[l])}if(!r.length)return null;const o=ts(r)??r[r.length-1];if(!o)return null;const a=o.output??o.payload??o,i=oe(a);return i&&typeof i=="object"&&!Array.isArray(i)?{kind:"dict",value:i,data:i,event:o}:{kind:"generic",value:i,event:o}},[e])}function Rt(e){var P,D;const t=typeof e=="string"?e:e==null?void 0:e.threadId,n=typeof e=="object"?e.lazy:!1,r=Le({optional:!0}),s=ot({optional:!0}),o=Dr(),{currentThreadId:a,setCurrentThreadId:i,actions:d}=r||{currentThreadId:null,setCurrentThreadId:()=>{},actions:{}},l=!!t&&t!==a,[u,p]=c.useState([]),g=c.useCallback($=>{p($)},[]),{isLoadingThread:m,threadStateError:v,threadCheckpoints:f,isLoadingHistory:T,loadThread:S}=st({api:be().chatApi,fileApi:be().fileApi,seed:g,currentThreadId:l?t:null,initialThreadId:l?t:null,isStreaming:!1,getMessages:()=>u,autoLoadInitial:l&&!n});c.useEffect(()=>{!l&&!n&&a&&(s!=null&&s.loadThread)&&s.loadThread(a)},[l,n,a,s==null?void 0:s.loadThread]);const E=c.useMemo(()=>{var $;return(($=f[0])==null?void 0:$.values)||{}},[f]),A=c.useMemo(()=>({timeline:[],messagePreviews:{}}),[]),k=t||a,w=l?m?"loading":"idle":(s==null?void 0:s.status)||"idle",b=l?u:(o==null?void 0:o.messages)||[],C=l?m:(s==null?void 0:s.isLoading)||!1,y=l?T:(s==null?void 0:s.isLoadingHistory)||!1,I=l?E:(s==null?void 0:s.values)||{},_=l?{}:(s==null?void 0:s.taskMessagesByScope)||{},B=l?v:(o==null?void 0:o.error)||(s==null?void 0:s.error)||null;return{threadId:k,status:w,messages:b,isLoading:C,isHistoryLoading:y,error:B,values:I,taskMessagesByScope:_,metadata:l?{}:s==null?void 0:s.metadata,navigateToCheckpoint:l?async()=>{}:(s==null?void 0:s.navigateToCheckpoint)||(async()=>{}),returnToLatest:l?async()=>{}:(s==null?void 0:s.returnToLatest)||(async()=>{}),checkpoint:l?f[0]?{id:f[0].checkpointId,namespace:f[0].checkpointNs}:null:(s==null?void 0:s.checkpoint)||null,checkpoints:l?f:(s==null?void 0:s.checkpoints)||[],checkpointIndex:l?A:(s==null?void 0:s.checkpointIndex)||{timeline:[],messagePreviews:{}},interrupt:l?null:(s==null?void 0:s.interrupt)||null,respondToInterrupt:l?async()=>{}:(s==null?void 0:s.respondToInterrupt)||(async()=>{}),isStreaming:(o==null?void 0:o.isStreaming)||!1,activeMessageId:l?null:((P=s==null?void 0:s.metadata)==null?void 0:P.assemblingMessageId)||(o==null?void 0:o.activeMessageId)||null,connectionState:(o==null?void 0:o.connectionState)||"disconnected",streamingAssistantId:!l&&(o!=null&&o.isStreaming)&&((D=s==null?void 0:s.metadata)!=null&&D.assemblingMessageId)?s.metadata.assemblingMessageId:null,submit:(o==null?void 0:o.submit)||(async()=>{}),stop:(o==null?void 0:o.stop)||(()=>{}),clearThread:l?async()=>{}:(s==null?void 0:s.clearThread)||(async()=>{}),setCurrentThreadId:i,loadHistory:l?async()=>{t&&await S(t)}:async()=>{},onEvent:l?()=>{}:(s==null?void 0:s.onEvent)||(()=>{}),createThread:d==null?void 0:d.createThread,deleteThread:d==null?void 0:d.deleteThread,renameThread:d==null?void 0:d.renameThread,threads:(r==null?void 0:r.threads)||[],isThreadsLoading:(r==null?void 0:r.isLoading)||!1}}function rs({submit:e,chatRequest:t,lastCheckpointId:n,lastCheckpointNs:r,onMessageSent:s,onExcelUploadSuccess:o,onError:a,enableMessageEditing:i,messages:d,setPendingAssistantResponse:l,project:u,onEvent:p,threadId:g,clearComposerOnSend:m=!0}){const{messages:v}=Rt(),[f,T]=c.useState(null),[S,E]=c.useState(""),[A,k]=c.useState(null),[w,b]=c.useState(null),[C,y]=c.useState(!1),[I,_]=c.useState(""),B=c.useRef(I),P=c.useRef(null);c.useEffect(()=>{if(!f)if(g){const h=localStorage.getItem(Qe(g));_(h||"")}else _("")},[g,f]);const D=c.useCallback(h=>{_(h),!f&&g&&localStorage.setItem(Qe(g),h)},[g,f]);c.useEffect(()=>{B.current=I},[I]),c.useEffect(()=>{if(!f){P.current=null;return}P.current===null&&(P.current=B.current),D(S??"")},[S,f,D]);const $=c.useCallback(h=>{D(h)},[D]),N=async(h,U)=>{const x=Array.isArray(U)?{files:U}:U??{},J=x.files??[],H=x.contentParts??[],K=h.trim();if(!(!K&&J.length===0&&H.length===0))try{const Z=J.map(async Q=>{try{const Y=await xt.uploadFile(Q);return{file:Q,record:Y}}catch(Y){throw console.error("Failed to upload file",Q.name,Y),new Error(`Failed to upload ${Q.name}`)}}),ue=(await Promise.all(Z)).map(({record:Q})=>{const Y=Q.mime_type;return Y.startsWith("image/")?{type:"image_url",image_url:{url:Q.content_url}}:{type:"file",url:Q.content_url,mimeType:Y,name:Q.filename,size:Q.size}}),W=[...H,...ue],R=f?(A==null?void 0:A.checkpointId)??n??void 0:n??void 0,we=f?(A==null?void 0:A.checkpointNs)??r??void 0:r??void 0;await e({text:K||"",contentParts:W,attachments:J,payload:t.payload,edit:!!f,checkpointId:R,checkpointNs:we,project:u??void 0,originalMessageId:f??void 0,config:t.config},p?{onEvent:p}:void 0),s==null||s(K),l(!0),m&&(g&&localStorage.removeItem(Qe(g)),D("")),b(null),T(null),E(""),k(null)}catch(Z){const ne=(Z==null?void 0:Z.message)||"Failed to send message";b(ne),a==null||a(ne),l(!1)}},O=(h,U)=>{U||N(h,{files:[]})},z=c.useCallback(async h=>{await e({attachments:[h],payload:t.payload,checkpointId:n??void 0,checkpointNs:r??void 0,project:u??void 0,config:t.config},p?{onEvent:p}:void 0),o==null||o({file:h})},[n,r,t,o,e]),X=c.useCallback((h,U,x)=>{i&&(P.current=I,T(h),E(U),k({checkpointId:(x==null?void 0:x.checkpointId)??null,checkpointNs:(x==null?void 0:x.checkpointNs)??null}),b(null))},[I,i]),F=c.useCallback(()=>{T(null),E(""),k(null),b(null);const h=P.current;h!==null&&_(h),P.current=null},[]),L=c.useCallback(h=>{let U=null;for(let K=h-1;K>=0;K--)if(d[K].role==="user"){U=d[K];break}if(!U)return;const x=Array.isArray(U.content)?U.content:[],H=x.filter(K=>(K==null?void 0:K.type)==="text").map(K=>K.text).join("")||(()=>{try{return JSON.stringify(x,null,2)}catch{return String(x)}})();H&&e({text:H,payload:t.payload,checkpointId:n??void 0,checkpointNs:r??void 0,edit:!0,originalMessageId:U.id,config:t.config},p?{onEvent:p}:void 0)},[d,e,n,r,t]);return{editingMessageId:f,editingInitialValue:S,inputError:w,setInputError:b,dismissError:C,setDismissError:y,composerValue:I,handleComposerChange:$,handleSendMessage:N,handleQuickPrompt:O,handleExcelUpload:z,startEditing:X,cancelEditing:F,handleRegenerateCb:L,displayMessages:v}}function ss(e){return c.useMemo(()=>e?{textContent:On(e),imageParts:$n(e),fileParts:Dn(e),toolCalls:wt(e),contentParts:e.content}:{textContent:"",imageParts:[],fileParts:[],toolCalls:[],contentParts:[]},[e])}function os(e,t,n){const[r,s]=c.useState(e),o=c.useRef(e),a=c.useRef(null);return c.useEffect(()=>{o.current=e;const i=()=>{s(o.current),a.current&&(clearTimeout(a.current),a.current=null)};if(!t||n<=0){i();return}return a.current&&clearTimeout(a.current),a.current=setTimeout(()=>{i()},n),()=>{a.current&&(clearTimeout(a.current),a.current=null)}},[e,t,n]),r}M.ChatProviders=Vr,M.ThreadStateProvider=Wt,M.ThreadsProvider=Lt,M.cn=Ln,M.collectText=Et,M.createTaskSyncToolEndHandler=Kr,M.extractTaskIdFromToolEnd=Qt,M.extractToolMeta=Pt,M.formatToolOutput=Hn,M.getAgentNameFromMessage=dr,M.getChatToken=Ze,M.getMessageAttemptInfo=Ur,M.getToolCallArtifacts=Qn,M.getToolCalls=Tt,M.hasContent=Kn,M.hydrateHistorySnapshots=rt,M.isFileLike=Ve,M.looksLikeMarkdown=bt,M.messageSignature=fr,M.normalizeInterruptId=ur,M.onChatTokenChanged=Re,M.parseJsonSafe=je,M.pretty=Ge,M.refreshHistoryFileUrls=Dt,M.sanitizeForDisplay=Me,M.setChatToken=pe,M.stringifyTool=kt,M.useApi=be,M.useChatController=rs,M.useChatSession=Rt,M.useFilePreview=Zr,M.useMessageContent=ss,M.useParsedMessageContent=Rr,M.useStream=Nt,M.useStreamingMarkdownBuffer=os,M.useThreadHistoryState=st,M.useThreadState=ot,M.useThreadStateUpdater=Gt,M.useThreads=Le,M.useThreadsState=jt,M.useToolPayload=ns,Object.defineProperty(M,Symbol.toStringTag,{value:"Module"})});
9
9
  //# sourceMappingURL=index.umd.js.map