teodor-new-chat-ui 1.5.27 → 1.5.28
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.esm.js +1 -1
- package/dist/index.umd.js +1 -1
- package/package.json +1 -1
package/dist/index.esm.js
CHANGED
|
@@ -1968,7 +1968,7 @@ class Uf {
|
|
|
1968
1968
|
}
|
|
1969
1969
|
const pt = new Uf();
|
|
1970
1970
|
function zf(e = {}) {
|
|
1971
|
-
const t = e.baseUrl ?? "/api", n = e.streamPath ?? "/stream", [r, o] = ce(e.token ?? null), s = rt(e.headers ?? {}), [a, i] = ce(!1), [u, f] = ce(null), [d, p] = ce(""), [m, v] = ce(null), h = rt(null), g = Se((x) => {
|
|
1971
|
+
const t = e.baseUrl ?? "/api/chat", n = e.streamPath ?? "/stream", [r, o] = ce(e.token ?? null), s = rt(e.headers ?? {}), [a, i] = ce(!1), [u, f] = ce(null), [d, p] = ce(""), [m, v] = ce(null), h = rt(null), g = Se((x) => {
|
|
1972
1972
|
o(x);
|
|
1973
1973
|
}, []), b = Se(() => {
|
|
1974
1974
|
var x;
|
package/dist/index.umd.js
CHANGED
|
@@ -4,7 +4,7 @@
|
|
|
4
4
|
`+a.map(Os).join(`
|
|
5
5
|
`):" "+Os(a[0]):"as no adapter specified";throw new ne("There is no suitable adapter to dispatch the request "+c,"ERR_NOT_SUPPORT")}return o},adapters:Tr};function Ar(e){if(e.cancelToken&&e.cancelToken.throwIfRequested(),e.signal&&e.signal.aborted)throw new wt(null,e)}function Ms(e){return Ar(e),e.headers=Ee.from(e.headers),e.data=Nr.call(e,e.transformRequest),["post","put","patch"].indexOf(e.method)!==-1&&e.headers.setContentType("application/x-www-form-urlencoded",!1),ks.getAdapter(e.adapter||Ut.adapter,e)(e).then(function(r){return Ar(e),r.data=Nr.call(e,e.transformResponse,r),r.headers=Ee.from(r.headers),r},function(r){return vs(r)||(Ar(e),r&&r.response&&(r.response.data=Nr.call(e,e.transformResponse,r.response),r.response.headers=Ee.from(r.response.headers))),Promise.reject(r)})}const Ds="1.12.2",bn={};["object","boolean","number","function","string","symbol"].forEach((e,t)=>{bn[e]=function(r){return typeof r===e||"a"+(t<1?"n ":" ")+e}});const Ls={};bn.transitional=function(t,n,r){function o(s,a){return"[Axios v"+Ds+"] Transitional option '"+s+"'"+a+(r?". "+r:"")}return(s,a,c)=>{if(t===!1)throw new ne(o(a," has been removed"+(n?" in "+n:"")),ne.ERR_DEPRECATED);return n&&!Ls[a]&&(Ls[a]=!0,console.warn(o(a," has been deprecated since v"+n+" and will be removed in the near future"))),t?t(s,a,c):!0}},bn.spelling=function(t){return(n,r)=>(console.warn(`${r} is likely a misspelling of ${t}`),!0)};function qu(e,t,n){if(typeof e!="object")throw new ne("options must be an object",ne.ERR_BAD_OPTION_VALUE);const r=Object.keys(e);let o=r.length;for(;o-- >0;){const s=r[o],a=t[s];if(a){const c=e[s],d=c===void 0||a(c,s,e);if(d!==!0)throw new ne("option "+s+" must be "+d,ne.ERR_BAD_OPTION_VALUE);continue}if(n!==!0)throw new ne("Unknown option "+s,ne.ERR_BAD_OPTION)}}const vn={assertOptions:qu,validators:bn},He=vn.validators;let ct=class{constructor(t){this.defaults=t||{},this.interceptors={request:new hs,response:new hs}}async request(t,n){try{return await this._request(t,n)}catch(r){if(r instanceof Error){let o={};Error.captureStackTrace?Error.captureStackTrace(o):o=new Error;const s=o.stack?o.stack.replace(/^.+\n/,""):"";try{r.stack?s&&!String(r.stack).endsWith(s.replace(/^.+\n.+\n/,""))&&(r.stack+=`
|
|
6
6
|
`+s):r.stack=s}catch{}}throw r}}_request(t,n){typeof t=="string"?(n=n||{},n.url=t):n=t||{},n=it(this.defaults,n);const{transitional:r,paramsSerializer:o,headers:s}=n;r!==void 0&&vn.assertOptions(r,{silentJSONParsing:He.transitional(He.boolean),forcedJSONParsing:He.transitional(He.boolean),clarifyTimeoutError:He.transitional(He.boolean)},!1),o!=null&&(S.isFunction(o)?n.paramsSerializer={serialize:o}:vn.assertOptions(o,{encode:He.function,serialize:He.function},!0)),n.allowAbsoluteUrls!==void 0||(this.defaults.allowAbsoluteUrls!==void 0?n.allowAbsoluteUrls=this.defaults.allowAbsoluteUrls:n.allowAbsoluteUrls=!0),vn.assertOptions(n,{baseUrl:He.spelling("baseURL"),withXsrfToken:He.spelling("withXSRFToken")},!0),n.method=(n.method||this.defaults.method||"get").toLowerCase();let a=s&&S.merge(s.common,s[n.method]);s&&S.forEach(["delete","get","head","post","put","patch","common"],h=>{delete s[h]}),n.headers=Ee.concat(a,s);const c=[];let d=!0;this.interceptors.request.forEach(function(m){typeof m.runWhen=="function"&&m.runWhen(n)===!1||(d=d&&m.synchronous,c.unshift(m.fulfilled,m.rejected))});const f=[];this.interceptors.response.forEach(function(m){f.push(m.fulfilled,m.rejected)});let u,p=0,g;if(!d){const h=[Ms.bind(this),void 0];for(h.unshift(...c),h.push(...f),g=h.length,u=Promise.resolve(n);p<g;)u=u.then(h[p++],h[p++]);return u}g=c.length;let v=n;for(;p<g;){const h=c[p++],m=c[p++];try{v=h(v)}catch(b){m.call(this,b);break}}try{u=Ms.call(this,v)}catch(h){return Promise.reject(h)}for(p=0,g=f.length;p<g;)u=u.then(f[p++],f[p++]);return u}getUri(t){t=it(this.defaults,t);const n=Ss(t.baseURL,t.url,t.allowAbsoluteUrls);return ps(n,t.params,t.paramsSerializer)}};S.forEach(["delete","get","head","options"],function(t){ct.prototype[t]=function(n,r){return this.request(it(r||{},{method:t,url:n,data:(r||{}).data}))}}),S.forEach(["post","put","patch"],function(t){function n(r){return function(s,a,c){return this.request(it(c||{},{method:t,headers:r?{"Content-Type":"multipart/form-data"}:{},url:s,data:a}))}}ct.prototype[t]=n(),ct.prototype[t+"Form"]=n(!0)});let Xu=class Nd{constructor(t){if(typeof t!="function")throw new TypeError("executor must be a function.");let n;this.promise=new Promise(function(s){n=s});const r=this;this.promise.then(o=>{if(!r._listeners)return;let s=r._listeners.length;for(;s-- >0;)r._listeners[s](o);r._listeners=null}),this.promise.then=o=>{let s;const a=new Promise(c=>{r.subscribe(c),s=c}).then(o);return a.cancel=function(){r.unsubscribe(s)},a},t(function(s,a,c){r.reason||(r.reason=new wt(s,a,c),n(r.reason))})}throwIfRequested(){if(this.reason)throw this.reason}subscribe(t){if(this.reason){t(this.reason);return}this._listeners?this._listeners.push(t):this._listeners=[t]}unsubscribe(t){if(!this._listeners)return;const n=this._listeners.indexOf(t);n!==-1&&this._listeners.splice(n,1)}toAbortSignal(){const t=new AbortController,n=r=>{t.abort(r)};return this.subscribe(n),t.signal.unsubscribe=()=>this.unsubscribe(n),t.signal}static source(){let t;return{token:new Nd(function(o){t=o}),cancel:t}}};function Yu(e){return function(n){return e.apply(null,n)}}function Ju(e){return S.isObject(e)&&e.isAxiosError===!0}const Pr={Continue:100,SwitchingProtocols:101,Processing:102,EarlyHints:103,Ok:200,Created:201,Accepted:202,NonAuthoritativeInformation:203,NoContent:204,ResetContent:205,PartialContent:206,MultiStatus:207,AlreadyReported:208,ImUsed:226,MultipleChoices:300,MovedPermanently:301,Found:302,SeeOther:303,NotModified:304,UseProxy:305,Unused:306,TemporaryRedirect:307,PermanentRedirect:308,BadRequest:400,Unauthorized:401,PaymentRequired:402,Forbidden:403,NotFound:404,MethodNotAllowed:405,NotAcceptable:406,ProxyAuthenticationRequired:407,RequestTimeout:408,Conflict:409,Gone:410,LengthRequired:411,PreconditionFailed:412,PayloadTooLarge:413,UriTooLong:414,UnsupportedMediaType:415,RangeNotSatisfiable:416,ExpectationFailed:417,ImATeapot:418,MisdirectedRequest:421,UnprocessableEntity:422,Locked:423,FailedDependency:424,TooEarly:425,UpgradeRequired:426,PreconditionRequired:428,TooManyRequests:429,RequestHeaderFieldsTooLarge:431,UnavailableForLegalReasons:451,InternalServerError:500,NotImplemented:501,BadGateway:502,ServiceUnavailable:503,GatewayTimeout:504,HttpVersionNotSupported:505,VariantAlsoNegotiates:506,InsufficientStorage:507,LoopDetected:508,NotExtended:510,NetworkAuthenticationRequired:511};Object.entries(Pr).forEach(([e,t])=>{Pr[t]=e});function Fs(e){const t=new ct(e),n=Zo(ct.prototype.request,t);return S.extend(n,ct.prototype,t,{allOwnKeys:!0}),S.extend(n,t,null,{allOwnKeys:!0}),n.create=function(o){return Fs(it(e,o))},n}const ge=Fs(Ut);ge.Axios=ct,ge.CanceledError=wt,ge.CancelToken=Xu,ge.isCancel=vs,ge.VERSION=Ds,ge.toFormData=pn,ge.AxiosError=ne,ge.Cancel=ge.CanceledError,ge.all=function(t){return Promise.all(t)},ge.spread=Yu,ge.isAxiosError=Ju,ge.mergeConfig=it,ge.AxiosHeaders=Ee,ge.formToJSON=e=>ms(S.isHTMLForm(e)?new FormData(e):e),ge.getAdapter=ks.getAdapter,ge.HttpStatusCode=Pr,ge.default=ge;const{Axios:dw,AxiosError:uw,CanceledError:fw,isCancel:pw,CancelToken:hw,VERSION:gw,all:mw,Cancel:bw,isAxiosError:vw,spread:ww,toFormData:yw,AxiosHeaders:xw,HttpStatusCode:Sw,formToJSON:Cw,getAdapter:Ew,mergeConfig:Nw}=ge,_r={};function yt(){var e;try{return typeof window<"u"&&((e=window.localStorage)==null?void 0:e.getItem("chat-debug"))==="1"}catch{return!1}}const $s=_r==null?void 0:_r.VITE_API_BASE_URL,Bs=$s?$s.replace(/\/+$/,""):void 0;!Bs&&typeof window<"u"&&console.warn("VITE_API_BASE_URL is not set. The API client will need to be configured via apiConfig prop.");let wn=null;const Ir=new Set;function Or(){return wn}function kr(e){wn=e,Ir.forEach(t=>t(e))}function Us(e){return Ir.add(e),()=>Ir.delete(e)}const We=ge.create({baseURL:Bs||"http://localhost:8000",timeout:3e4,withCredentials:!0});We.interceptors.request.use(e=>(wn&&(e.headers.Authorization=`Bearer ${wn}`),e)),We.interceptors.response.use(e=>e,e=>Promise.reject(e));async function lt(e,t){return(await We.get(e,t)).data}async function Mr(e,t,n){return(await We.post(e,t,n)).data}async function zs(e,t,n){return(await We.put(e,t,n)).data}async function Hs(e,t){return(await We.delete(e,t)).data}async function Ws(e,t){var p;const{method:n="POST",body:r,headers:o={},onChunk:s,signal:a}=t,c=Or();if(yt()){let g=r;try{const v=JSON.parse(JSON.stringify(r));(p=v==null?void 0:v.payload)!=null&&p.files_info&&Array.isArray(v.payload.files_info)&&(v.payload.files_info=v.payload.files_info.map(h=>({...h,data:h!=null&&h.data?`<base64 ${String(h.data).length} chars>`:h==null?void 0:h.data}))),g=v}catch{}console.debug("[api.stream]",n,`${We.defaults.baseURL}${e}`,g)}const d=await fetch(`${We.defaults.baseURL}${e.startsWith("/")?"":"/"}${e}`,{method:n,headers:{"Content-Type":"application/json",...c?{Authorization:`Bearer ${c}`}:{},...o},body:r!==void 0?JSON.stringify(r):void 0,credentials:"include",signal:a});if(!d.ok||!d.body){const g=await d.text().catch(()=>"");throw yt()&&console.debug("[api.stream] non-OK",d.status,g==null?void 0:g.slice(0,500)),new Error(`Stream failed: ${d.status} ${d.statusText}${g?": "+g:""}`)}const f=d.body.getReader(),u=new TextDecoder;for(;;){const{done:g,value:v}=await f.read();if(g)break;const h=u.decode(v,{stream:!0});yt()&&console.debug("[api.stream] chunk",h.slice(0,200)),s(h)}}function Ve(e){return e&&typeof e=="object"&&"data"in e?e.data:e}class yn{get baseUrl(){return We.defaults.baseURL||""}updateConfig(t){t.baseUrl&&(We.defaults.baseURL=t.baseUrl),t.authToken!==void 0&&kr(t.authToken)}getAuthToken(){return Or()}setAuthToken(t){kr(t)}onTokenChange(t){return Us(t)}async listThreads(){const t=await lt("/chat/threads"),n=Ve(t);return(n==null?void 0:n.items)??(t==null?void 0:t.items)??[]}async createThread(t){const r=await Mr("/chat/threads",t?{title:t}:void 0);return Ve(r)}async updateThread(t,n){const r=await zs(`/chat/threads/${t}`,{title:n});return Ve(r)}async deleteThread(t){const n=await Hs(`/chat/threads/${t}`);return Ve(n)}async threadInfo(t){const n=await lt(`/chat/threads/${t}/info`);return Ve(n)}async getMessages(t){const n=await lt("/chat/messages",{params:{thread_id:t.threadId,checkpoint_id:t.checkpointId,checkpoint_ns:t.checkpointNs}});return Ve(n)}async getState(t){const n=await lt("/chat/state",{params:{thread_id:t.threadId,checkpoint_id:t.checkpointId,checkpoint_ns:t.checkpointNs}});return Ve(n)}async getStateHistory(t){const n=await lt("/chat/state/history",{params:{thread_id:t.threadId,checkpoint_id:t.checkpointId,checkpoint_ns:t.checkpointNs}});return Ve(n)}async listCheckpoints(t){const n=await lt("/chat/checkpoints",{params:{thread_id:t}});return Ve(n)}async uploadImage(t,n="/upload"){const r=new FormData;r.append("file",t,t.name),yt()&&console.debug("[api.uploadImage] ->",n,{name:t.name,type:t.type,size:t.size});const o=await Mr(n,r,{headers:{Accept:"application/json"},maxBodyLength:1/0}),s=Ve(o);if(yt()&&console.debug("[api.uploadImage] <-",s),!(s!=null&&s.url))throw new Error("Invalid upload response: missing url");return{url:s.url,mimeType:s.mimeType??t.type,name:s.name??t.name,size:s.size??t.size}}async streamChat(t,n,r){var o;try{await Ws("/chat/stream",{method:"POST",body:t,onChunk:s=>{const a=s.split(`
|
|
7
|
-
`);for(const c of a)if(c.startsWith("data: ")){const d=c.slice(6).trim();if(d==="[DONE]")return;try{const f=JSON.parse(d);n(f)}catch(f){yt()&&console.debug("[api.streamChat] parse error",f,d)}}},signal:r==null?void 0:r.signal})}catch(s){throw(o=r==null?void 0:r.onError)==null||o.call(r,s),s}}}const Ye=new yn;function Vs(e={}){const t=e.baseUrl??"/api",n=e.streamPath??"/stream",[r,o]=P.useState(e.token??null),s=P.useRef(e.headers??{}),[a,c]=P.useState(!1),[d,f]=P.useState(null),[u,p]=P.useState(""),[g,v]=P.useState(null),h=P.useRef(null),m=P.useCallback(x=>{o(x)},[]),b=P.useCallback(()=>{var x;(x=h.current)==null||x.abort(),h.current=null,c(!1)},[]),w=P.useCallback(()=>{p(""),v(null),f(null)},[]),y=P.useCallback((x,E,C)=>{h.current&&(h.current.abort(),h.current=null),c(!0),f(null),e.autoAppendAssistant!==!1&&p("");const O=new AbortController;return h.current=O,(async()=>{var M,D,j,G;const N=(()=>{var V;try{return typeof window<"u"&&((V=window.localStorage)==null?void 0:V.getItem("chat-debug"))==="1"}catch{return!1}})(),L=V=>{var z;try{const X=JSON.parse(JSON.stringify(V));return(z=X==null?void 0:X.payload)!=null&&z.files_info&&Array.isArray(X.payload.files_info)&&(X.payload.files_info=X.payload.files_info.map(F=>({...F,data:F!=null&&F.data?`<base64 ${String(F.data).length} chars>`:F==null?void 0:F.data}))),X}catch{return V}};try{let V={};try{if(r)V={Authorization:`Bearer ${r}`};else if(typeof window<"u"){const _=window.__AUTH_TOKEN__,I=((M=window.localStorage)==null?void 0:M.getItem("authToken"))||null;let k=null;try{const B=(D=window.localStorage)==null?void 0:D.getItem("chat-settings");B&&(k=((j=JSON.parse(B))==null?void 0:j.apiKey)||null)}catch{}const Y=_||I||k||null;Y&&(V={Authorization:`Bearer ${Y}`})}}catch{}N&&console.debug("[use-chat] POST",t+n,L(x));const z=await fetch(t+n,{method:"POST",headers:{"Content-Type":"application/json",Accept:"text/event-stream",...V,...s.current},body:JSON.stringify(x),signal:O.signal});if(!z.ok||!z.body){const T=await z.text().catch(()=>"");throw N&&console.debug("[use-chat] non-OK response",z.status,T==null?void 0:T.slice(0,500)),new Error(`stream ${z.status}${T?": "+T:""}`)}const X=z.body.getReader(),F=new TextDecoder;let q="";for(;;){const{value:T,done:_}=await X.read();if(_)break;q+=F.decode(T,{stream:!0});let I;for(;(I=q.indexOf(`
|
|
7
|
+
`);for(const c of a)if(c.startsWith("data: ")){const d=c.slice(6).trim();if(d==="[DONE]")return;try{const f=JSON.parse(d);n(f)}catch(f){yt()&&console.debug("[api.streamChat] parse error",f,d)}}},signal:r==null?void 0:r.signal})}catch(s){throw(o=r==null?void 0:r.onError)==null||o.call(r,s),s}}}const Ye=new yn;function Vs(e={}){const t=e.baseUrl??"/api/chat",n=e.streamPath??"/stream",[r,o]=P.useState(e.token??null),s=P.useRef(e.headers??{}),[a,c]=P.useState(!1),[d,f]=P.useState(null),[u,p]=P.useState(""),[g,v]=P.useState(null),h=P.useRef(null),m=P.useCallback(x=>{o(x)},[]),b=P.useCallback(()=>{var x;(x=h.current)==null||x.abort(),h.current=null,c(!1)},[]),w=P.useCallback(()=>{p(""),v(null),f(null)},[]),y=P.useCallback((x,E,C)=>{h.current&&(h.current.abort(),h.current=null),c(!0),f(null),e.autoAppendAssistant!==!1&&p("");const O=new AbortController;return h.current=O,(async()=>{var M,D,j,G;const N=(()=>{var V;try{return typeof window<"u"&&((V=window.localStorage)==null?void 0:V.getItem("chat-debug"))==="1"}catch{return!1}})(),L=V=>{var z;try{const X=JSON.parse(JSON.stringify(V));return(z=X==null?void 0:X.payload)!=null&&z.files_info&&Array.isArray(X.payload.files_info)&&(X.payload.files_info=X.payload.files_info.map(F=>({...F,data:F!=null&&F.data?`<base64 ${String(F.data).length} chars>`:F==null?void 0:F.data}))),X}catch{return V}};try{let V={};try{if(r)V={Authorization:`Bearer ${r}`};else if(typeof window<"u"){const _=window.__AUTH_TOKEN__,I=((M=window.localStorage)==null?void 0:M.getItem("authToken"))||null;let k=null;try{const B=(D=window.localStorage)==null?void 0:D.getItem("chat-settings");B&&(k=((j=JSON.parse(B))==null?void 0:j.apiKey)||null)}catch{}const Y=_||I||k||null;Y&&(V={Authorization:`Bearer ${Y}`})}}catch{}N&&console.debug("[use-chat] POST",t+n,L(x));const z=await fetch(t+n,{method:"POST",headers:{"Content-Type":"application/json",Accept:"text/event-stream",...V,...s.current},body:JSON.stringify(x),signal:O.signal});if(!z.ok||!z.body){const T=await z.text().catch(()=>"");throw N&&console.debug("[use-chat] non-OK response",z.status,T==null?void 0:T.slice(0,500)),new Error(`stream ${z.status}${T?": "+T:""}`)}const X=z.body.getReader(),F=new TextDecoder;let q="";for(;;){const{value:T,done:_}=await X.read();if(_)break;q+=F.decode(T,{stream:!0});let I;for(;(I=q.indexOf(`
|
|
8
8
|
|
|
9
9
|
`))>=0;){const k=q.slice(0,I);q=q.slice(I+2);const Y=Qu(k);if(!Y)continue;let B;try{B=JSON.parse(Y)}catch{N&&console.debug("[use-chat] skip malformed SSE data:",Y==null?void 0:Y.slice(0,200));continue}const H=Zu(B)?B.data:B;if(N&&console.debug("[use-chat] event:",H==null?void 0:H.type,H),E==null||E(H),H.type==="token")e.autoAppendAssistant!==!1&&p(de=>de+H.content);else if(H.type==="message_delta"){const de=H.delta.filter(ie=>ie.type==="text").map(ie=>ie.text).join("");de&&e.autoAppendAssistant!==!1&&p(ie=>ie+de)}else H.type==="checkpoint"?v(H.checkpointId):H.type==="error"&&f(H.message)}}}catch(V){if((V==null?void 0:V.name)==="AbortError")return;const z=(V==null?void 0:V.message)||String(V);N&&console.debug("[use-chat] error:",z),f(z),(G=C==null?void 0:C.onError)==null||G.call(C,z)}finally{c(!1),h.current=null}})(),{close:()=>O.abort()}},[t,r,e.autoAppendAssistant]);return P.useEffect(()=>()=>{var x;return(x=h.current)==null?void 0:x.abort()},[]),{isStreaming:a,error:d,assistantText:u,lastCheckpointId:g,stream:y,stop:b,clear:w,setToken:m}}function Zu(e){return!!e&&typeof e=="object"&&e.protocolVersion==="v1"&&"data"in e}function Qu(e){const t=e.split(/\r?\n/),n=[];for(const r of t)if(r&&!r.startsWith(":")&&r.startsWith("data:")){const o=r.slice(5);n.push(o.startsWith(" ")?o.slice(1):o)}return n.length===0?null:n.join(`
|
|
10
10
|
`)}const ef={messages:[],assemblingId:null,lastCheckpointId:null,toolIndex:{}};function tf(e,t){var n,r;switch(t.type){case"reset":return{messages:js(((n=t.payload)==null?void 0:n.messages)??[]),assemblingId:null,lastCheckpointId:null,toolIndex:{}};case"seed":return{...e,messages:js(t.payload.messages)};case"user_message":{const o=t.payload.message;if(e.assemblingId){const s=e.messages.findIndex(a=>a.id===e.assemblingId&&a.role==="assistant");if(s>=0){const a=e.messages.slice(0,s),c=e.messages.slice(s);return{...e,messages:[...a,o,...c]}}}return{...e,messages:[...e.messages,o]}}case"event":{const o=t.payload.ev;if(o.type==="message_start"&&o.role==="assistant"){const s=o.id,a=sf(o.model),c={id:s,role:"assistant",name:a||void 0,model:o.model,createdAt:new Date().toISOString(),content:[]};return{...e,assemblingId:s,messages:[...e.messages,c]}}if(o.type==="token"){const s=e.assemblingId??Dr(e.messages);return s?{...e,messages:nf(e.messages,s,o.content)}:e}if(o.type==="message_delta"){const s=e.assemblingId??Dr(e.messages);return s?{...e,messages:Ks(e.messages,s,o.delta)}:e}if(o.type==="message_end"){const s=e.assemblingId??Dr(e.messages);if(!s)return{...e,assemblingId:null};const a=e.messages,c=a.findIndex(d=>d.id===s&&d.role==="assistant");if(c>=0&&!((r=a[c].content)==null?void 0:r.some(u=>{var p;return(u==null?void 0:u.type)==="text"&&((p=u.text)==null?void 0:p.trim())}))){const u=[...a.slice(0,c),...a.slice(c+1)];return{...e,assemblingId:null,messages:u}}return{...e,assemblingId:null}}if(o.type==="tool_start"){const s=`tool-${o.id}`,a={type:"tool_call",id:o.id,name:o.name,args:o.args},c={id:s,role:"tool",name:o.name,createdAt:new Date().toISOString(),content:[a]};return{...e,messages:[...e.messages,c],toolIndex:{...e.toolIndex,[o.id]:s}}}if(o.type==="tool_result"){const s=e.toolIndex[o.id]??`tool-${o.id}`,a={type:"tool_result",toolCallId:o.id,output:o.output,error:o.error},c=e.messages.find(u=>u.id===s),d={id:s,role:"tool",content:[a],createdAt:new Date().toISOString()},f=c?Ks(e.messages,s,[a]):[...e.messages,d];return{...e,messages:f}}if(o.type==="checkpoint"){const s=of(e.messages,o.checkpointId);return{...e,lastCheckpointId:o.checkpointId,messages:s}}if(o.type==="error"){const s={id:`err-${Date.now()}`,role:"system",content:[{type:"text",text:`Error: ${o.message}`}],createdAt:new Date().toISOString()};return{...e,messages:[...e.messages,s]}}return e}default:return e}}function Rs(e=[]){const[t,n]=P.useReducer(tf,{...ef,messages:e}),r=P.useCallback(s=>{n({type:"event",payload:{ev:s}})},[]),o=P.useMemo(()=>({reset:s=>n({type:"reset",payload:{messages:s}}),seed:s=>n({type:"seed",payload:{messages:s}}),pushUser:s=>n({type:"user_message",payload:{message:s}}),onEvent:r}),[r]);return{state:t,dispatch:n,...o}}function js(e){return e.filter(t=>{if(t.role!=="assistant")return!0;const n=(t.content||[]).some(o=>{var s;return o&&o.type==="text"&&((s=o.text)==null?void 0:s.trim())}),r=(t.content||[]).some(o=>o&&o.type==="image_url");return!!(n||r)})}function Dr(e){for(let t=e.length-1;t>=0;t--)if(e[t].role==="assistant")return e[t].id;return null}function nf(e,t,n){return e.map(r=>{if(r.id!==t)return r;const o=r.content.slice(),s=o[o.length-1];return s&&s.type==="text"?s.text+=n:o.push({type:"text",text:n}),{...r,content:o}})}function Ks(e,t,n){return e.map(r=>r.id===t?{...r,content:rf(r.content,n)}:r)}function rf(e,t){const n=e.slice();for(const r of t)if(r.type==="text"){const o=n[n.length-1];(o==null?void 0:o.type)==="text"?o.text+=r.text:n.push({type:"text",text:r.text})}else n.push(r);return n}function of(e,t){for(let n=e.length-1;n>=0;n--)if(e[n].role==="assistant"){const o={...e[n],checkpointId:t};return[...e.slice(0,n),o,...e.slice(n+1)]}return e}function sf(e){if(!e)return null;const t=e.split("/");return t[t.length-1]||null}const Gs=P.createContext(null);function Ht({children:e,apiConfig:t,onError:n,onThreadChange:r,initialThreadId:o=null}){const s=Ye;P.useEffect(()=>{t&&s.updateConfig({baseUrl:t.baseUrl,authToken:t.apiKey})},[s,t]);const{isStreaming:a,error:c,stream:d,stop:f,setToken:u}=Vs({baseUrl:s.baseUrl,token:null,headers:t==null?void 0:t.headers,streamPath:"/stream"}),[p,g]=P.useState(()=>typeof s.getAuthToken=="function"?s.getAuthToken():null);P.useEffect(()=>{u(typeof s.getAuthToken=="function"?s.getAuthToken():null);const I=s.onTokenChange(k=>{g(k),u(k)});return()=>{I()}},[s,u]);const v=P.useCallback(I=>{s.setAuthToken(I)},[s]),{state:h,seed:m,pushUser:b,onEvent:w,reset:y}=Rs(),[x,E]=P.useState([]),[C,O]=P.useState(null),N=P.useCallback(async()=>{const I=await s.listThreads();E(I)},[s]);P.useEffect(()=>{N().catch(()=>{})},[N]),P.useEffect(()=>{r==null||r(C)},[C,r]);const L=P.useRef(null);P.useEffect(()=>{o&&L.current!==o&&(L.current=o,D(o).catch(()=>{}))},[o]);const M=P.useRef(null),D=P.useCallback(async(I,k,Y)=>{var B;if(M.current!==I){M.current=I;try{const H=k??((B=(await s.listCheckpoints(I)).checkpoints.slice().sort((ie,R)=>new Date(R.createdAt).getTime()-new Date(ie.createdAt).getTime())[0])==null?void 0:B.checkpointId),de=await s.getMessages({threadId:I,checkpointId:H,checkpointNs:Y});O(I),m(de.messages)}finally{M.current=null}}},[s,m]),j=P.useCallback(async I=>s.listCheckpoints(I),[s]),G=P.useCallback(async I=>{if(!C)throw new Error("No active thread");const k=await s.getMessages({threadId:C,checkpointId:I});m(k.messages)},[s,C,m]),V=P.useCallback(async()=>{if(!C)throw new Error("No active thread");await D(C)},[C,D]),z=P.useRef(!1);P.useEffect(()=>{const I=z.current;if(z.current=a,I&&!a&&C){const k=h.lastCheckpointId??void 0;s.getMessages({threadId:C,checkpointId:k}).then(Y=>m(Y.messages)).catch(()=>{})}},[a,C,h.lastCheckpointId,s,m]);const X=P.useCallback(async I=>{const k=await s.createThread(I);return await N(),await D(k.threadId),k.threadId},[s,N,D]),F=P.useCallback(async I=>{await s.deleteThread(I),await N(),C===I&&(O(null),y([]))},[s,N,C,y]),q=P.useCallback(async(I,k)=>{await s.updateThread(I,k),await N()},[s,N]),T=P.useCallback(async(I,k)=>{var ae;if(!C)throw new Error("No active thread");async function Y(W){return await new Promise((ee,pe)=>{const he=new FileReader;he.onload=()=>ee(String(he.result)),he.onerror=J=>pe(J),he.readAsDataURL(W)})}async function B(W){return await new Promise((ee,pe)=>{const he=new FileReader;he.onload=()=>{try{const J=he.result;let ve="";const ce=new Uint8Array(J),me=ce.byteLength;for(let Te=0;Te<me;Te++)ve+=String.fromCharCode(ce[Te]);ee(btoa(ve))}catch(J){pe(J)}},he.onerror=J=>pe(J),he.readAsArrayBuffer(W)})}const H=[];I&&H.push({type:"text",text:I});const de=(k==null?void 0:k.attachments)||[];let ie=[];if(de.length>0)for(const W of de)if(W.type&&W.type.startsWith("image/")){let ee=null;try{const pe=await s.uploadImage(W,(t==null?void 0:t.uploadPath)||"/upload").catch(()=>null);ee=(pe==null?void 0:pe.url)||null}catch{}if(!ee)try{ee=await Y(W)}catch{ee=null}if(ee){const pe={type:"image_url",url:ee,mimeType:W.type,alt:W.name};H.push(pe)}try{ie.push({filename:W.name,data:await B(W),mime_type:W.type||"application/octet-stream"})}catch{}}else{const ee=await Y(W).catch(()=>null),pe={type:"file",url:String(ee),mimeType:W.type||void 0,name:W.name,size:W.size};H.push(pe);try{ie.push({filename:W.name,data:await B(W),mime_type:W.type||"application/octet-stream"})}catch{}}const R={id:((ae=crypto.randomUUID)==null?void 0:ae.call(crypto))||`user-${Date.now()}`,role:"user",content:H,createdAt:new Date().toISOString(),checkpointId:(k==null?void 0:k.checkpointId)??h.lastCheckpointId??void 0};b(R);const se={...R,content:R.content.filter(W=>W.type==="text"||W.type==="image_url")},le={threadId:C,payload:{messages:[se],attachments:R.content.filter(W=>W.type==="file").map(W=>({type:"file",url:W.url,mimeType:W.mimeType,name:W.name,size:W.size})),files_info:ie,...(k==null?void 0:k.payloadExtras)??{}},checkpointId:(k==null?void 0:k.checkpointId)??h.lastCheckpointId??void 0,checkpointNs:k==null?void 0:k.checkpointNs,nodeFilter:k==null?void 0:k.nodeFilter,config:k==null?void 0:k.config};d(le,W=>w(W),{onError:W=>console.warn("stream error",W)})},[C,b,d,w,h.lastCheckpointId,s,t==null?void 0:t.uploadPath]),_={baseUrl:s.baseUrl,token:p,setToken:v,api:s,threads:x,currentThreadId:C,setCurrentThreadId:O,messages:h.messages,isStreaming:a,error:c,lastCheckpointId:h.lastCheckpointId,streamingAssistantId:h.assemblingId,refreshThreads:N,createThread:X,deleteThread:F,renameThread:q,loadThread:D,listCheckpoints:j,navigateToCheckpoint:G,returnToLatest:V,send:T,stop:f};return i.jsx(Gs.Provider,{value:_,children:e})}function Lr(){const e=P.useContext(Gs);if(!e)throw new Error("useChat must be used within ChatProvider");return e}function A(...e){return Ad.twMerge(Td.clsx(e))}const af=Lt.cva("inline-flex items-center justify-center gap-2 whitespace-nowrap rounded-md text-sm font-medium ring-offset-background transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50 [&_svg]:pointer-events-none [&_svg]:size-4 [&_svg]:shrink-0",{variants:{variant:{default:"bg-primary text-primary-foreground hover:bg-primary/90",destructive:"bg-destructive text-destructive-foreground hover:bg-destructive/90",outline:"border border-input bg-background hover:bg-accent hover:text-accent-foreground",secondary:"bg-secondary text-secondary-foreground hover:bg-secondary/80",ghost:"hover:bg-accent hover:text-accent-foreground",link:"text-primary underline-offset-4 hover:underline"},size:{default:"h-10 px-4 py-2",sm:"h-9 rounded-md px-3",lg:"h-11 rounded-md px-8",icon:"h-10 w-10"}},defaultVariants:{variant:"default",size:"default"}}),fe=l.forwardRef(({className:e,variant:t,size:n,asChild:r=!1,...o},s)=>{const a=r?Pe.Slot:"button";return i.jsx(a,{className:A(af({variant:t,size:n,className:e})),ref:s,...o})});fe.displayName="Button";const qs=l.forwardRef(({className:e,...t},n)=>i.jsx("textarea",{className:A("flex min-h-[80px] w-full rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50",e),ref:n,...t}));qs.displayName="Textarea";const cf=Lt.cva("inline-flex items-center rounded-full border px-2.5 py-0.5 text-xs font-semibold transition-colors focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2",{variants:{variant:{default:"border-transparent bg-primary text-primary-foreground hover:bg-primary/80",secondary:"border-transparent bg-secondary text-secondary-foreground hover:bg-secondary/80",destructive:"border-transparent bg-destructive text-destructive-foreground hover:bg-destructive/80",outline:"text-foreground"}},defaultVariants:{variant:"default"}});function Xs({className:e,variant:t,...n}){return i.jsx("div",{className:A(cf({variant:t}),e),...n})}function U(e,t,{checkForDefaultPrevented:n=!0}={}){return function(o){if(e==null||e(o),n===!1||!o.defaultPrevented)return t==null?void 0:t(o)}}function lf(e,t){const n=l.createContext(t),r=s=>{const{children:a,...c}=s,d=l.useMemo(()=>c,Object.values(c));return i.jsx(n.Provider,{value:d,children:a})};r.displayName=e+"Provider";function o(s){const a=l.useContext(n);if(a)return a;if(t!==void 0)return t;throw new Error(`\`${s}\` must be used within \`${e}\``)}return[r,o]}function Le(e,t=[]){let n=[];function r(s,a){const c=l.createContext(a),d=n.length;n=[...n,a];const f=p=>{var w;const{scope:g,children:v,...h}=p,m=((w=g==null?void 0:g[e])==null?void 0:w[d])||c,b=l.useMemo(()=>h,Object.values(h));return i.jsx(m.Provider,{value:b,children:v})};f.displayName=s+"Provider";function u(p,g){var m;const v=((m=g==null?void 0:g[e])==null?void 0:m[d])||c,h=l.useContext(v);if(h)return h;if(a!==void 0)return a;throw new Error(`\`${p}\` must be used within \`${s}\``)}return[f,u]}const o=()=>{const s=n.map(a=>l.createContext(a));return function(c){const d=(c==null?void 0:c[e])||s;return l.useMemo(()=>({[`__scope${e}`]:{...c,[e]:d}}),[c,d])}};return o.scopeName=e,[r,df(o,...t)]}function df(...e){const t=e[0];if(e.length===1)return t;const n=()=>{const r=e.map(o=>({useScope:o(),scopeName:o.scopeName}));return function(s){const a=r.reduce((c,{useScope:d,scopeName:f})=>{const p=d(s)[`__scope${f}`];return{...c,...p}},{});return l.useMemo(()=>({[`__scope${t.scopeName}`]:a}),[a])}};return n.scopeName=t.scopeName,n}var be=globalThis!=null&&globalThis.document?l.useLayoutEffect:()=>{},uf=l[" useInsertionEffect ".trim().toString()]||be;function Qe({prop:e,defaultProp:t,onChange:n=()=>{},caller:r}){const[o,s,a]=ff({defaultProp:t,onChange:n}),c=e!==void 0,d=c?e:o;{const u=l.useRef(e!==void 0);l.useEffect(()=>{const p=u.current;p!==c&&console.warn(`${r} is changing from ${p?"controlled":"uncontrolled"} to ${c?"controlled":"uncontrolled"}. Components should not switch from controlled to uncontrolled (or vice versa). Decide between using a controlled or uncontrolled value for the lifetime of the component.`),u.current=c},[c,r])}const f=l.useCallback(u=>{var p;if(c){const g=pf(u)?u(e):u;g!==e&&((p=a.current)==null||p.call(a,g))}else s(u)},[c,e,s,a]);return[d,f]}function ff({defaultProp:e,onChange:t}){const[n,r]=l.useState(e),o=l.useRef(n),s=l.useRef(t);return uf(()=>{s.current=t},[t]),l.useEffect(()=>{var a;o.current!==n&&((a=s.current)==null||a.call(s,n),o.current=n)},[n,o]),[n,r,s]}function pf(e){return typeof e=="function"}function Ys(e,t){if(typeof e=="function")return e(t);e!=null&&(e.current=t)}function Fr(...e){return t=>{let n=!1;const r=e.map(o=>{const s=Ys(o,t);return!n&&typeof s=="function"&&(n=!0),s});if(n)return()=>{for(let o=0;o<r.length;o++){const s=r[o];typeof s=="function"?s():Ys(e[o],null)}}}}function re(...e){return l.useCallback(Fr(...e),e)}var hf=["a","button","div","form","h2","h3","img","input","label","li","nav","ol","p","select","span","svg","ul"],Z=hf.reduce((e,t)=>{const n=Pe.createSlot(`Primitive.${t}`),r=l.forwardRef((o,s)=>{const{asChild:a,...c}=o,d=a?n:t;return typeof window<"u"&&(window[Symbol.for("radix-ui")]=!0),i.jsx(d,{...c,ref:s})});return r.displayName=`Primitive.${t}`,{...e,[t]:r}},{});function Js(e,t){e&&cn.flushSync(()=>e.dispatchEvent(t))}function gf(e,t){return l.useReducer((n,r)=>t[n][r]??n,e)}var Ne=e=>{const{present:t,children:n}=e,r=mf(t),o=typeof n=="function"?n({present:r.isPresent}):l.Children.only(n),s=re(r.ref,bf(o));return typeof n=="function"||r.isPresent?l.cloneElement(o,{ref:s}):null};Ne.displayName="Presence";function mf(e){const[t,n]=l.useState(),r=l.useRef(null),o=l.useRef(e),s=l.useRef("none"),a=e?"mounted":"unmounted",[c,d]=gf(a,{mounted:{UNMOUNT:"unmounted",ANIMATION_OUT:"unmountSuspended"},unmountSuspended:{MOUNT:"mounted",ANIMATION_END:"unmounted"},unmounted:{MOUNT:"mounted"}});return l.useEffect(()=>{const f=xn(r.current);s.current=c==="mounted"?f:"none"},[c]),be(()=>{const f=r.current,u=o.current;if(u!==e){const g=s.current,v=xn(f);e?d("MOUNT"):v==="none"||(f==null?void 0:f.display)==="none"?d("UNMOUNT"):d(u&&g!==v?"ANIMATION_OUT":"UNMOUNT"),o.current=e}},[e,d]),be(()=>{if(t){let f;const u=t.ownerDocument.defaultView??window,p=v=>{const m=xn(r.current).includes(CSS.escape(v.animationName));if(v.target===t&&m&&(d("ANIMATION_END"),!o.current)){const b=t.style.animationFillMode;t.style.animationFillMode="forwards",f=u.setTimeout(()=>{t.style.animationFillMode==="forwards"&&(t.style.animationFillMode=b)})}},g=v=>{v.target===t&&(s.current=xn(r.current))};return t.addEventListener("animationstart",g),t.addEventListener("animationcancel",p),t.addEventListener("animationend",p),()=>{u.clearTimeout(f),t.removeEventListener("animationstart",g),t.removeEventListener("animationcancel",p),t.removeEventListener("animationend",p)}}else d("ANIMATION_END")},[t,d]),{isPresent:["mounted","unmountSuspended"].includes(c),ref:l.useCallback(f=>{r.current=f?getComputedStyle(f):null,n(f)},[])}}function xn(e){return(e==null?void 0:e.animationName)||"none"}function bf(e){var r,o;let t=(r=Object.getOwnPropertyDescriptor(e.props,"ref"))==null?void 0:r.get,n=t&&"isReactWarning"in t&&t.isReactWarning;return n?e.ref:(t=(o=Object.getOwnPropertyDescriptor(e,"ref"))==null?void 0:o.get,n=t&&"isReactWarning"in t&&t.isReactWarning,n?e.props.ref:e.props.ref||e.ref)}var vf=l[" useId ".trim().toString()]||(()=>{}),wf=0;function Fe(e){const[t,n]=l.useState(vf());return be(()=>{n(r=>r??String(wf++))},[e]),t?`radix-${t}`:""}var Sn="Collapsible",[yf,Tw]=Le(Sn),[xf,$r]=yf(Sn),Zs=l.forwardRef((e,t)=>{const{__scopeCollapsible:n,open:r,defaultOpen:o,disabled:s,onOpenChange:a,...c}=e,[d,f]=Qe({prop:r,defaultProp:o??!1,onChange:a,caller:Sn});return i.jsx(xf,{scope:n,disabled:s,contentId:Fe(),open:d,onOpenToggle:l.useCallback(()=>f(u=>!u),[f]),children:i.jsx(Z.div,{"data-state":Ur(d),"data-disabled":s?"":void 0,...c,ref:t})})});Zs.displayName=Sn;var Qs="CollapsibleTrigger",ea=l.forwardRef((e,t)=>{const{__scopeCollapsible:n,...r}=e,o=$r(Qs,n);return i.jsx(Z.button,{type:"button","aria-controls":o.contentId,"aria-expanded":o.open||!1,"data-state":Ur(o.open),"data-disabled":o.disabled?"":void 0,disabled:o.disabled,...r,ref:t,onClick:U(e.onClick,o.onOpenToggle)})});ea.displayName=Qs;var Br="CollapsibleContent",Sf=l.forwardRef((e,t)=>{const{forceMount:n,...r}=e,o=$r(Br,e.__scopeCollapsible);return i.jsx(Ne,{present:n||o.open,children:({present:s})=>i.jsx(Cf,{...r,ref:t,present:s})})});Sf.displayName=Br;var Cf=l.forwardRef((e,t)=>{const{__scopeCollapsible:n,present:r,children:o,...s}=e,a=$r(Br,n),[c,d]=l.useState(r),f=l.useRef(null),u=re(t,f),p=l.useRef(0),g=p.current,v=l.useRef(0),h=v.current,m=a.open||c,b=l.useRef(m),w=l.useRef(void 0);return l.useEffect(()=>{const y=requestAnimationFrame(()=>b.current=!1);return()=>cancelAnimationFrame(y)},[]),be(()=>{const y=f.current;if(y){w.current=w.current||{transitionDuration:y.style.transitionDuration,animationName:y.style.animationName},y.style.transitionDuration="0s",y.style.animationName="none";const x=y.getBoundingClientRect();p.current=x.height,v.current=x.width,b.current||(y.style.transitionDuration=w.current.transitionDuration,y.style.animationName=w.current.animationName),d(r)}},[a.open,r]),i.jsx(Z.div,{"data-state":Ur(a.open),"data-disabled":a.disabled?"":void 0,id:a.contentId,hidden:!m,...s,ref:u,style:{"--radix-collapsible-content-height":g?`${g}px`:void 0,"--radix-collapsible-content-width":h?`${h}px`:void 0,...e.style},children:m&&o})});function Ur(e){return e?"open":"closed"}var Ef=Zs;const ta=Ef,na=ea;function Wt({content:e,className:t=""}){return i.jsx("div",{className:`prose prose-sm max-w-none dark:prose-invert prose-pre:rounded prose-pre:border prose-pre:bg-background/50 prose-code:bg-background/50 prose-code:px-1 prose-code:py-0.5 prose-code:rounded prose-table:my-4 prose-th:px-2 prose-td:px-2 leading-relaxed ${t}`,children:i.jsx(Pd,{remarkPlugins:[_d],components:{p:({children:n})=>i.jsx("p",{className:"mt-0 mb-3 last:mb-0 whitespace-pre-wrap",children:n}),ul:({children:n})=>i.jsx("ul",{className:"list-disc pl-5 mb-3 space-y-1 marker:text-muted-foreground",children:n}),ol:({children:n})=>i.jsx("ol",{className:"list-decimal pl-5 mb-3 space-y-1 marker:text-muted-foreground",children:n}),li:({children:n})=>i.jsx("li",{className:"leading-snug",children:n}),blockquote:({children:n})=>i.jsx("blockquote",{className:"border-l-4 border-border pl-3 italic text-muted-foreground my-3",children:n}),table:({children:n})=>i.jsx("div",{className:"overflow-x-auto border rounded mb-4",children:i.jsx("table",{className:"w-full border-collapse text-xs",children:n})}),th:({children:n})=>i.jsx("th",{className:"border-b bg-muted/40 px-2 py-1 text-left font-medium text-[11px] uppercase tracking-wide",children:n}),td:({children:n})=>i.jsx("td",{className:"border-b px-2 py-1 align-top",children:n}),code:({className:n,children:r,...o})=>!/language-(\w+)/.exec(n||"")&&!(n!=null&&n.includes("language-"))?i.jsx("code",{className:"text-[12px] font-medium",...o,children:r}):i.jsx("pre",{className:"bg-background/50 p-2 rounded border overflow-x-auto text-xs leading-relaxed",children:i.jsx("code",{className:n,...o,children:r})})},children:e})})}function ra({message:e,messageIndex:t,isStreamingMessage:n=!1,streamingDebounceMs:r=40,isEditing:o=!1,showActions:s=!0,showTimestamp:a=!0,showAgentName:c=!0,layoutSize:d="desktop",truncateToolMessages:f=!0,toolMessagePreviewLength:u=200,truncateUserMessages:p=!0,userMessagePreviewLength:g=200,customStyles:v={},checkpointBranches:h=[],currentCheckpointId:m,onSwitchToCheckpoint:b,onReturnToMainThread:w,temporalNavigation:y,onNavigateToPreviousBranch:x,onNavigateToNextBranch:E,onEdit:C,onRegenerate:O,onEditFromCheckpoint:N,onCancelEdit:L,onCopy:M}){const[D,j]=P.useState(!1),[G,V]=P.useState(!1),[z,X]=P.useState(!1),[F,q]=P.useState(!1),T=d==="phone"||d==="half-screen",_=e.role,I=_==="tool",k=P.useMemo(()=>Nf(e.content),[e.content]),Y=P.useMemo(()=>Of(e.content),[e.content]),B=P.useMemo(()=>e.content.filter(J=>J.type==="image_url"),[e.content]),H=P.useMemo(()=>e.content.filter(J=>J.type==="file"),[e.content]),de=Df(k,n?r:0),ie=async()=>{try{const J=I?Vt(e.content):k;await navigator.clipboard.writeText(J),j(!0),setTimeout(()=>j(!1),2e3),M==null||M(J)}catch(J){console.error("Failed to copy:",J)}},R=()=>{if(!C)return;const J=I?Vt(e.content):k;C(e.id,J)},se=()=>O==null?void 0:O(t),le=()=>{const ve=A(T?"h-3 w-3":"h-4 w-4","opacity-60 flex-shrink-0");switch(_){case"user":return i.jsx(K.User,{className:ve});case"assistant":return i.jsx(K.Bot,{className:ve});case"tool":return i.jsx(K.Wrench,{className:ve});default:return i.jsx(K.Bot,{className:ve})}},ae=()=>{const J="group relative mb-4 max-w-full";switch(_){case"user":return A(J,"flex justify-end");case"assistant":case"tool":case"system":return A(J,"flex justify-start");default:return J}},W=()=>{const J=A("rounded-lg px-4 py-3 relative transition-all duration-200",T&&"px-3 py-2 text-sm");switch(_){case"user":return A(J,"bg-primary text-primary-foreground max-w-[95%]",d==="phone"&&"max-w-[98%]");case"assistant":return A(J,"bg-muted text-muted-foreground max-w-[95%] border",d==="phone"&&"max-w-[98%]");case"tool":return A(J,"bg-secondary/50 text-secondary-foreground border border-dashed max-w-[95%]",d==="phone"&&"max-w-[98%]");case"system":return A(J,"bg-accent/40 text-muted-foreground max-w-[85%] border");default:return J}},ee=J=>{if(!J)return"";try{return new Date(J).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"})}catch{return""}},pe=()=>{if(I&&!z){const ce=Vt(e.content).slice(0,80).replace(/\s+/g," ");return i.jsx("div",{className:A("text-xs font-mono opacity-70 flex items-center justify-between gap-2",T&&"text-[10px]"),children:i.jsxs("span",{className:"truncate max-w-full",children:[ce,ce.length>=80?"…":""]})})}if(I&&f){const ce=Vt(e.content),me=ce.length>u;return i.jsx(ta,{open:G,onOpenChange:V,children:i.jsxs("div",{className:"font-mono text-sm",children:[i.jsx("pre",{className:A("whitespace-pre-wrap break-words",T&&"text-xs"),children:me&&!G?ce.substring(0,u)+"...":ce}),me&&i.jsx(na,{asChild:!0,children:i.jsx(fe,{variant:"ghost",size:"sm",className:"h-6 text-xs",children:G?i.jsxs(i.Fragment,{children:[i.jsx(K.ChevronUp,{className:"h-3 w-3 mr-1"}),"Show less"]}):i.jsxs(i.Fragment,{children:[i.jsx(K.ChevronDown,{className:"h-3 w-3 mr-1"}),"Show more (",ce.length-u," chars)"]})})})]})})}if(I&&z&&!f){const ce=If(e.content);if(ce&&Tf(ce))return i.jsx(Wt,{content:ce.trim()});const me=Vt(e.content);return i.jsx("div",{className:"font-mono text-sm",children:i.jsx("pre",{className:A("whitespace-pre-wrap break-words",T&&"text-xs"),children:me})})}const J=B.length>0&&_!=="tool",ve=H.length>0&&_!=="tool";return i.jsxs("div",{children:[n?i.jsxs("div",{className:"relative",children:[(()=>{const ce=oa(de);return ce!==null?i.jsx(sa,{data:ce}):i.jsx(Wt,{content:Pf(Af(de))})})(),i.jsx("span",{className:"inline-block w-[6px] h-[14px] align-baseline ml-0.5 bg-foreground/40 animate-pulse",style:{verticalAlign:"text-bottom"}})]}):(()=>{const ce=oa(k.trim());if(ce!==null)return i.jsx(sa,{data:ce});if(_==="user"&&p){const me=k.trim();if(me.length>g)return i.jsxs(ta,{open:F,onOpenChange:q,children:[i.jsx("div",{className:A("text-sm",T&&"text-xs"),children:F?i.jsx(Wt,{content:me}):i.jsxs("pre",{className:A("font-sans whitespace-pre-wrap break-words bg-transparent p-0 m-0",T&&"text-xs"),children:[me.substring(0,g),"..."]})}),i.jsx(na,{asChild:!0,children:i.jsx(fe,{variant:"ghost",size:"sm",className:"h-6 text-xs",children:F?i.jsxs(i.Fragment,{children:[i.jsx(K.ChevronUp,{className:"h-3 w-3 mr-1"})," Show less"]}):i.jsxs(i.Fragment,{children:[i.jsx(K.ChevronDown,{className:"h-3 w-3 mr-1"})," Show more (",me.length-g," chars)"]})})})]})}return i.jsx(Wt,{content:k.trim()})})(),J&&i.jsx("div",{className:"mt-2 grid grid-cols-2 gap-2",children:B.map((ce,me)=>i.jsxs("div",{className:"relative border rounded overflow-hidden",children:[i.jsx("img",{src:ce.url,alt:ce.alt??"image",className:"w-full h-auto"}),i.jsxs("div",{className:"absolute top-1 right-1 bg-background/70 rounded px-1 py-0.5 text-[10px] flex items-center gap-1",children:[i.jsx(K.Image,{className:"h-3 w-3"}),i.jsx("span",{children:"image"})]})]},me))}),ve&&i.jsx("div",{className:"mt-2 flex flex-wrap gap-2",children:H.map((ce,me)=>{const Te=ce,$=Te.name||"file";return i.jsxs("a",{href:Te.url,download:$,target:"_blank",rel:"noreferrer",className:"inline-flex items-center gap-2 bg-gray-100 border border-gray-200 rounded px-2 py-1 text-xs hover:bg-gray-200",title:$,children:[i.jsx("span",{className:"inline-block w-1.5 h-1.5 rounded-full bg-gray-400"}),i.jsx("span",{className:"truncate max-w-[180px]",children:$})]},me)})})]})},he=P.useMemo(()=>kf(e),[e]);return P.useMemo(()=>Mf(e,m),[e,m]),i.jsx("div",{className:A(ae(),v.container),children:i.jsxs("div",{className:A(W(),v.content),children:[(a||c||I)&&i.jsxs("div",{className:A("flex items-center justify-between mb-2 pb-2 border-b border-current/10",T&&"mb-1 pb-1",v.header),children:[i.jsxs("div",{className:"flex items-center gap-2",children:[le(),c&&he&&i.jsx("span",{className:A("font-medium",T?"text-xs":"text-sm"),children:he}),I&&Y.name&&i.jsxs(Xs,{variant:"outline",className:A("text-xs flex items-center gap-1 cursor-pointer",T&&"text-xs h-4"),onClick:()=>X(J=>!J),children:[i.jsx("span",{children:Y.name}),i.jsx("span",{className:"inline-flex items-center",children:z?i.jsx(K.ChevronUp,{className:"h-3 w-3"}):i.jsx(K.ChevronDown,{className:"h-3 w-3"})})]}),I&&!Y.name&&i.jsx(fe,{variant:"ghost",size:"sm",className:"h-6 px-1",onClick:()=>X(J=>!J),children:i.jsxs("span",{className:"text-xs flex items-center gap-1",children:["Tool Output ",z?i.jsx(K.ChevronUp,{className:"h-3 w-3"}):i.jsx(K.ChevronDown,{className:"h-3 w-3"})]})})]}),i.jsxs("div",{className:"flex items-center gap-2",children:[a&&i.jsx("span",{className:A("text-xs opacity-60",T&&"text-xs"),children:ee(e.createdAt)}),s&&!o&&i.jsxs("div",{className:A("opacity-0 group-hover:opacity-100 transition-opacity","flex items-center gap-1",v.actions),children:[i.jsx(fe,{variant:"ghost",size:"sm",onClick:ie,className:A("h-6 w-6 p-0 hover:bg-background/50",T&&"h-5 w-5"),children:i.jsx(K.Copy,{className:A(D?"text-success":"",T?"h-3 w-3":"h-4 w-4")})}),_==="user"&&C&&i.jsx(fe,{variant:"ghost",size:"sm",onClick:R,className:A("h-6 w-6 p-0 hover:bg-background/50",T&&"h-5 w-5"),children:i.jsx(K.Edit,{className:A(T?"h-3 w-3":"h-4 w-4")})}),_==="assistant"&&O&&i.jsx(fe,{variant:"ghost",size:"sm",onClick:se,className:A("h-6 w-6 p-0 hover:bg-background/50",T&&"h-5 w-5"),children:i.jsx(K.RotateCcw,{className:A(T?"h-3 w-3":"h-4 w-4")})})]})]})]}),i.jsx("div",{className:"relative",children:pe()}),I&&z&&(Y.toolCallId||Y.name)&&i.jsxs("div",{className:A("mt-2 pt-2 border-t border-current/10 text-xs opacity-60",T&&"text-xs"),children:[Y.name&&i.jsxs("div",{children:["Function: ",Y.name]}),Y.toolCallId&&i.jsxs("div",{children:["Call ID: ",Y.toolCallId]})]}),s&&_==="user"&&y&&y.totalBranches>1&&i.jsxs("div",{className:"flex items-center gap-2 mt-2 p-2 bg-muted/30 rounded border",children:[i.jsx(K.GitBranch,{className:"h-3 w-3 text-muted-foreground"}),i.jsxs("span",{className:"text-xs text-muted-foreground",children:["Branch ",y.currentIndex+1," of ",y.totalBranches]}),i.jsxs("div",{className:"flex items-center gap-1",children:[i.jsx(fe,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0",disabled:!y.canGoBack,onClick:()=>x==null?void 0:x(),title:"Go back to previous branch",children:i.jsx(K.ChevronLeft,{className:"h-3 w-3"})}),i.jsx(fe,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0",disabled:!y.canGoForward,onClick:()=>E==null?void 0:E(),title:"Go forward to next branch",children:i.jsx(K.ChevronRight,{className:"h-3 w-3"})})]})]}),!(a||c||I)&&s&&!o&&i.jsxs("div",{className:A("absolute top-2 right-2 opacity-0 group-hover:opacity-100 transition-opacity","flex items-center gap-1",v.actions),children:[i.jsx(fe,{variant:"ghost",size:"sm",onClick:ie,className:A("h-6 w-6 p-0 hover:bg-background/50",T&&"h-5 w-5"),children:i.jsx(K.Copy,{className:A(D?"text-success":"",T?"h-3 w-3":"h-4 w-4")})}),_==="user"&&C&&i.jsx(fe,{variant:"ghost",size:"sm",onClick:R,className:A("h-6 w-6 p-0 hover:bg-background/50",T&&"h-5 w-5"),children:i.jsx(K.Edit,{className:A(T?"h-3 w-3":"h-4 w-4")})}),_==="assistant"&&O&&i.jsx(fe,{variant:"ghost",size:"sm",onClick:se,className:A("h-6 w-6 p-0 hover:bg-background/50",T&&"h-5 w-5"),children:i.jsx(K.RotateCcw,{className:A(T?"h-3 w-3":"h-4 w-4")})})]})]})})}function Nf(e){const t=e.filter(n=>n.type==="text").map(n=>n.text).join("");return t||JSON.stringify(e)}function Tf(e){return e.includes(`
|
package/package.json
CHANGED