teodor-new-chat-ui 2.0.39 → 2.0.40

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 CHANGED
@@ -3061,43 +3061,41 @@ function Tp({
3061
3061
  return /* @__PURE__ */ c(hs, { className: ve });
3062
3062
  }
3063
3063
  }, le = () => {
3064
- const Z = "group relative mb-4 max-w-full";
3064
+ const Z = "group relative mb-4 flex w-full";
3065
3065
  switch (P) {
3066
3066
  case "user":
3067
- return T(Z, "flex justify-end");
3067
+ return T(Z, "justify-end");
3068
3068
  case "assistant":
3069
3069
  case "tool":
3070
3070
  case "system":
3071
- return T(Z, "flex justify-start");
3071
+ return T(Z, "justify-start");
3072
3072
  default:
3073
3073
  return Z;
3074
3074
  }
3075
3075
  }, ue = () => {
3076
3076
  const Z = T(
3077
- "rounded-lg px-4 py-3 relative transition-all duration-200 min-w-0 break-words",
3077
+ "rounded-lg px-4 py-3 relative transition-all duration-200 min-w-0 max-w-full break-words",
3078
3078
  A && "px-3 py-2 text-sm"
3079
3079
  );
3080
3080
  switch (P) {
3081
3081
  case "user":
3082
3082
  return T(
3083
3083
  Z,
3084
- "max-w-[95%]",
3085
- u === "phone" && "max-w-[98%]",
3084
+ "w-full md:max-w-[95%]",
3086
3085
  "bg-[hsl(var(--chat-bubble-user))] text-[hsl(var(--chat-bubble-user-text))]",
3087
3086
  "border border-transparent"
3088
3087
  );
3089
3088
  case "assistant":
3090
3089
  return T(
3091
3090
  Z,
3092
- "max-w-[95%]",
3093
- u === "phone" && "max-w-[98%]",
3091
+ "w-full md:max-w-[95%]",
3094
3092
  "bg-[hsl(var(--chat-bubble-ai))] text-[hsl(var(--chat-bubble-ai-text))]",
3095
3093
  "border border-border/60 dark:border-border/40"
3096
3094
  );
3097
3095
  case "tool":
3098
- return T(Z, "bg-secondary/50 text-secondary-foreground border border-dashed max-w-[95%]", u === "phone" && "max-w-[98%]");
3096
+ return T(Z, "w-full md:max-w-[95%] bg-secondary/50 text-secondary-foreground border border-dashed");
3099
3097
  case "system":
3100
- return T(Z, "bg-accent/40 text-muted-foreground max-w-[85%] border");
3098
+ return T(Z, "w-full md:max-w-[85%] bg-accent/40 text-muted-foreground border");
3101
3099
  default:
3102
3100
  return Z;
3103
3101
  }
package/dist/index.umd.js CHANGED
@@ -6,7 +6,7 @@
6
6
  `+s):n.stack=s}catch{}}throw n}}_request(t,r){typeof t=="string"?(r=r||{},r.url=t):r=t||{},r=ht(this.defaults,r);const{transitional:n,paramsSerializer:o,headers:s}=r;n!==void 0&&Er.assertOptions(n,{silentJSONParsing:Ke.transitional(Ke.boolean),forcedJSONParsing:Ke.transitional(Ke.boolean),clarifyTimeoutError:Ke.transitional(Ke.boolean)},!1),o!=null&&(S.isFunction(o)?r.paramsSerializer={serialize:o}:Er.assertOptions(o,{encode:Ke.function,serialize:Ke.function},!0)),r.allowAbsoluteUrls!==void 0||(this.defaults.allowAbsoluteUrls!==void 0?r.allowAbsoluteUrls=this.defaults.allowAbsoluteUrls:r.allowAbsoluteUrls=!0),Er.assertOptions(r,{baseUrl:Ke.spelling("baseURL"),withXsrfToken:Ke.spelling("withXSRFToken")},!0),r.method=(r.method||this.defaults.method||"get").toLowerCase();let a=s&&S.merge(s.common,s[r.method]);s&&S.forEach(["delete","get","head","post","put","patch","common"],g=>{delete s[g]}),r.headers=Pe.concat(a,s);const c=[];let d=!0;this.interceptors.request.forEach(function(h){typeof h.runWhen=="function"&&h.runWhen(r)===!1||(d=d&&h.synchronous,c.unshift(h.fulfilled,h.rejected))});const f=[];this.interceptors.response.forEach(function(h){f.push(h.fulfilled,h.rejected)});let u,p=0,m;if(!d){const g=[js.bind(this),void 0];for(g.unshift(...c),g.push(...f),m=g.length,u=Promise.resolve(r);p<m;)u=u.then(g[p++],g[p++]);return u}m=c.length;let v=r;for(;p<m;){const g=c[p++],h=c[p++];try{v=g(v)}catch(b){h.call(this,b);break}}try{u=js.call(this,v)}catch(g){return Promise.reject(g)}for(p=0,m=f.length;p<m;)u=u.then(f[p++],f[p++]);return u}getUri(t){t=ht(this.defaults,t);const r=Ms(t.baseURL,t.url,t.allowAbsoluteUrls);return Es(r,t.params,t.paramsSerializer)}};S.forEach(["delete","get","head","options"],function(t){gt.prototype[t]=function(r,n){return this.request(ht(n||{},{method:t,url:r,data:(n||{}).data}))}}),S.forEach(["post","put","patch"],function(t){function r(n){return function(s,a,c){return this.request(ht(c||{},{method:t,headers:n?{"Content-Type":"multipart/form-data"}:{},url:s,data:a}))}}gt.prototype[t]=r(),gt.prototype[t+"Form"]=r(!0)});let of=class Dd{constructor(t){if(typeof t!="function")throw new TypeError("executor must be a function.");let r;this.promise=new Promise(function(s){r=s});const n=this;this.promise.then(o=>{if(!n._listeners)return;let s=n._listeners.length;for(;s-- >0;)n._listeners[s](o);n._listeners=null}),this.promise.then=o=>{let s;const a=new Promise(c=>{n.subscribe(c),s=c}).then(o);return a.cancel=function(){n.unsubscribe(s)},a},t(function(s,a,c){n.reason||(n.reason=new At(s,a,c),r(n.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 r=this._listeners.indexOf(t);r!==-1&&this._listeners.splice(r,1)}toAbortSignal(){const t=new AbortController,r=n=>{t.abort(n)};return this.subscribe(r),t.signal.unsubscribe=()=>this.unsubscribe(r),t.signal}static source(){let t;return{token:new Dd(function(o){t=o}),cancel:t}}};function sf(e){return function(r){return e.apply(null,r)}}function af(e){return S.isObject(e)&&e.isAxiosError===!0}const Fn={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(Fn).forEach(([e,t])=>{Fn[t]=e});function Gs(e){const t=new gt(e),r=ls(gt.prototype.request,t);return S.extend(r,gt.prototype,t,{allOwnKeys:!0}),S.extend(r,t,null,{allOwnKeys:!0}),r.create=function(o){return Gs(ht(e,o))},r}const we=Gs(Kt);we.Axios=gt,we.CanceledError=At,we.CancelToken=of,we.isCancel=_s,we.VERSION=Rs,we.toFormData=wr,we.AxiosError=ne,we.Cancel=we.CanceledError,we.all=function(t){return Promise.all(t)},we.spread=sf,we.isAxiosError=af,we.mergeConfig=ht,we.AxiosHeaders=Pe,we.formToJSON=e=>As(S.isHTMLForm(e)?new FormData(e):e),we.getAdapter=Vs.getAdapter,we.HttpStatusCode=Fn,we.default=we;const{Axios:Cw,AxiosError:Ew,CanceledError:Nw,isCancel:Tw,CancelToken:Aw,VERSION:Pw,all:_w,Cancel:Iw,isAxiosError:kw,spread:Ow,toFormData:Mw,AxiosHeaders:Dw,HttpStatusCode:Lw,formToJSON:Fw,getAdapter:$w,mergeConfig:Bw}=we,$n={};function qt(){var e;try{return typeof window<"u"&&((e=window.localStorage)==null?void 0:e.getItem("chat-debug"))==="1"}catch{return!1}}const qs=$n==null?void 0:$n.VITE_API_BASE_URL,Xs=qs?qs.replace(/\/+$/,""):void 0;!Xs&&typeof window<"u"&&console.warn("VITE_API_BASE_URL is not set. The API client will need to be configured via apiConfig prop.");let Nr=null;const Bn=new Set;function Un(){return Nr}function Hn(e){Nr=e,Bn.forEach(t=>t(e))}function Ys(e){return Bn.add(e),()=>Bn.delete(e)}const Ge=we.create({baseURL:Xs||"http://localhost:8000",timeout:3e4,withCredentials:!0});Ge.interceptors.request.use(e=>(Nr&&(e.headers.Authorization=`Bearer ${Nr}`),e)),Ge.interceptors.response.use(e=>e,e=>Promise.reject(e));async function mt(e,t){return(await Ge.get(e,t)).data}async function zn(e,t,r){return(await Ge.post(e,t,r)).data}async function Js(e,t,r){return(await Ge.put(e,t,r)).data}async function Zs(e,t){return(await Ge.delete(e,t)).data}async function cf(e,t){var m;if(qt()){let v=t.body;try{const g=JSON.parse(JSON.stringify(t.body));(m=g==null?void 0:g.payload)!=null&&m.files_info&&Array.isArray(g.payload.files_info)&&(g.payload.files_info=g.payload.files_info.map(h=>({...h,data:h!=null&&h.data?`<base64 ${String(h.data).length} chars>`:h==null?void 0:h.data}))),v=g}catch{}console.debug("[api.stream]",t.method,`${Ge.defaults.baseURL}${e}`,v)}const n=(Ge.defaults.baseURL||"").replace(/\/+$|^\s+|\s+$/g,""),o=t.method??"POST",s=Un(),a=t.headers??{},c=e?e.startsWith("/")?e:`/${e}`:"",d=n?`${n}${c}`:c||n,f=await fetch(d,{method:o,headers:{"Content-Type":"application/json",...s?{Authorization:`Bearer ${s}`}:{},...a},body:t.body!==void 0?JSON.stringify(t.body):void 0,credentials:"include",signal:t.signal});if(!f.ok||!f.body){const v=await f.text().catch(()=>"");throw qt()&&console.debug("[api.stream] non-OK",f.status,v==null?void 0:v.slice(0,500)),new Error(`Stream failed: ${f.status} ${f.statusText}${v?": "+v:""}`)}const u=f.body.getReader(),p=new TextDecoder;for(;;){const{done:v,value:g}=await u.read();if(v)break;const h=p.decode(g,{stream:!0});qt()&&console.debug("[api.stream] chunk",h.slice(0,200)),t.onChunk(h)}}function qe(e){return e&&typeof e=="object"&&"data"in e?e.data:e}class Tr{get baseUrl(){const t=Ge.defaults.baseURL||"";return String(t).replace(/\/+$|^\s+|\s+$/g,"")}updateConfig(t){t.baseUrl&&(Ge.defaults.baseURL=String(t.baseUrl).replace(/\/+$/g,"")),t.authToken!==void 0&&Hn(t.authToken)}getAuthToken(){return Un()}setAuthToken(t){Hn(t)}onTokenChange(t){return Ys(t)}async listThreads(){const t=await mt("/chat/threads"),r=qe(t);return(r==null?void 0:r.items)??(t==null?void 0:t.items)??[]}async createThread(t){const n=await zn("/chat/threads",t?{title:t}:void 0);return qe(n)}async updateThread(t,r){const n=await Js(`/chat/threads/${t}`,{title:r});return qe(n)}async deleteThread(t){const r=await Zs(`/chat/threads/${t}`);return qe(r)}async threadInfo(t){const r=await mt(`/chat/threads/${t}/info`);return qe(r)}async getMessages(t){const r=await mt("/chat/messages",{params:{thread_id:t.threadId,checkpoint_id:t.checkpointId,checkpoint_ns:t.checkpointNs,limit:t.limit,before_id:t.beforeId??void 0}});return qe(r)}async getState(t){const r=await mt("/chat/state",{params:{thread_id:t.threadId,checkpoint_id:t.checkpointId,checkpoint_ns:t.checkpointNs}});return qe(r)}async getStateHistory(t){const r=await mt("/chat/state/history",{params:{thread_id:t.threadId,checkpoint_id:t.checkpointId,checkpoint_ns:t.checkpointNs}});return qe(r)}async listCheckpoints(t){const r=await mt("/chat/checkpoints",{params:{thread_id:t}});return qe(r)}async uploadImage(t,r="/upload"){const n=new FormData;n.append("file",t,t.name),qt()&&console.debug("[api.uploadImage] ->",r,{name:t.name,type:t.type,size:t.size});const o=await zn(r,n,{headers:{Accept:"application/json"},maxBodyLength:1/0}),s=qe(o);if(qt()&&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}}}const tt=new Tr;function Qs(e={}){const t=e.baseUrl??"/api/chat",r=e.streamPath??"/stream",[n,o]=T.useState(e.token??null),s=T.useRef(e.headers??{}),[a,c]=T.useState(!1),[d,f]=T.useState(null),[u,p]=T.useState(""),[m,v]=T.useState(null),g=T.useRef(null),h=T.useCallback(x=>{o(x)},[]),b=T.useCallback(()=>{var x;(x=g.current)==null||x.abort(),g.current=null,c(!1)},[]),w=T.useCallback(()=>{p(""),v(null),f(null)},[]),y=T.useCallback((x,C,E)=>{g.current&&(g.current.abort(),g.current=null),c(!0),f(null),e.autoAppendAssistant!==!1&&p("");const O=new AbortController;return g.current=O,(async()=>{var D,$,R,X;const N=(()=>{var B;try{return typeof window<"u"&&((B=window.localStorage)==null?void 0:B.getItem("chat-debug"))==="1"}catch{return!1}})(),L=B=>{var M;try{const J=JSON.parse(JSON.stringify(B));return(M=J==null?void 0:J.payload)!=null&&M.files_info&&Array.isArray(J.payload.files_info)&&(J.payload.files_info=J.payload.files_info.map(F=>({...F,data:F!=null&&F.data?`<base64 ${String(F.data).length} chars>`:F==null?void 0:F.data}))),J}catch{return B}};try{let B={};try{if(n)B={Authorization:`Bearer ${n}`};else if(typeof window<"u"){const _=window.__AUTH_TOKEN__,G=((D=window.localStorage)==null?void 0:D.getItem("authToken"))||null;let j=null;try{const I=($=window.localStorage)==null?void 0:$.getItem("chat-settings");I&&(j=((R=JSON.parse(I))==null?void 0:R.apiKey)||null)}catch{}const Z=_||G||j||null;Z&&(B={Authorization:`Bearer ${Z}`})}}catch{}N&&console.debug("[use-chat] POST",t+r,L(x));const M=await fetch(t+r,{method:"POST",headers:{"Content-Type":"application/json",Accept:"text/event-stream",...B,...s.current},body:JSON.stringify(x),signal:O.signal});if(!M.ok||!M.body){const P=await M.text().catch(()=>"");throw N&&console.debug("[use-chat] non-OK response",M.status,P==null?void 0:P.slice(0,500)),new Error(`stream ${M.status}${P?": "+P:""}`)}const J=M.body.getReader(),F=new TextDecoder;let H="";for(;;){const{value:P,done:_}=await J.read();if(_)break;H+=F.decode(P,{stream:!0});let G;for(;(G=H.indexOf(`
7
7
 
8
8
  `))>=0;){const j=H.slice(0,G);H=H.slice(G+2);const Z=df(j);if(!Z)continue;let I;try{I=JSON.parse(Z)}catch{N&&console.debug("[use-chat] skip malformed SSE data:",Z==null?void 0:Z.slice(0,200));continue}const W=lf(I)?I.data:I;if(N&&console.debug("[use-chat] event:",W==null?void 0:W.type,W),C==null||C(W),W.type==="token")e.autoAppendAssistant!==!1&&p(ge=>ge+W.content);else if(W.type==="message_delta"){const ge=W.delta.filter(he=>he.type==="text").map(he=>he.text).join("");ge&&e.autoAppendAssistant!==!1&&p(he=>he+ge)}else W.type==="checkpoint"?v(W.checkpointId):W.type==="error"&&f(W.message)}}}catch(B){if((B==null?void 0:B.name)==="AbortError")return;const M=(B==null?void 0:B.message)||String(B);N&&console.debug("[use-chat] error:",M),f(M),(X=E==null?void 0:E.onError)==null||X.call(E,M)}finally{c(!1),g.current=null}})(),{close:()=>O.abort()}},[t,n,e.autoAppendAssistant]);return T.useEffect(()=>()=>{var x;return(x=g.current)==null?void 0:x.abort()},[]),{isStreaming:a,error:d,assistantText:u,lastCheckpointId:m,stream:y,stop:b,clear:w,setToken:h}}function lf(e){return!!e&&typeof e=="object"&&e.protocolVersion==="v1"&&"data"in e}function df(e){const t=e.split(/\r?\n/),r=[];for(const n of t)if(n&&!n.startsWith(":")&&n.startsWith("data:")){const o=n.slice(5);r.push(o.startsWith(" ")?o.slice(1):o)}return r.length===0?null:r.join(`
9
- `)}const uf={messages:[],assemblingId:null,lastCheckpointId:null,toolIndex:{}};function ff(e,t){var r,n;switch(t.type){case"reset":return{messages:Wn(((r=t.payload)==null?void 0:r.messages)??[]),assemblingId:null,lastCheckpointId:null,toolIndex:{}};case"seed":return{...e,messages:Wn(t.payload.messages)};case"prepend":{const o=Wn(t.payload.messages);if(!o.length)return e;const s=new Set(e.messages.map(c=>c.id)),a=o.filter(c=>!s.has(c.id));return a.length?{...e,messages:[...a,...e.messages]}:e}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=mf(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??Vn(e.messages);return s?{...e,messages:pf(e.messages,s,o.content)}:e}if(o.type==="message_delta"){const s=e.assemblingId??Vn(e.messages);return s?{...e,messages:ta(e.messages,s,o.delta)}:e}if(o.type==="message_end"){const s=e.assemblingId??Vn(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&&!((n=a[c].content)==null?void 0:n.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?ta(e.messages,s,[a]):[...e.messages,d];return{...e,messages:f}}if(o.type==="checkpoint"){const s=gf(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 ea(e=[]){const[t,r]=T.useReducer(ff,{...uf,messages:e}),n=T.useCallback(s=>{r({type:"event",payload:{ev:s}})},[]),o=T.useMemo(()=>({reset:s=>r({type:"reset",payload:{messages:s}}),seed:s=>r({type:"seed",payload:{messages:s}}),prepend:s=>r({type:"prepend",payload:{messages:s}}),pushUser:s=>r({type:"user_message",payload:{message:s}}),onEvent:n}),[n]);return{state:t,dispatch:r,...o}}function Wn(e){return e.filter(t=>{if(t.role!=="assistant")return!0;const r=(t.content||[]).some(o=>{var s;return o&&o.type==="text"&&((s=o.text)==null?void 0:s.trim())}),n=(t.content||[]).some(o=>o&&o.type==="image_url");return!!(r||n)})}function Vn(e){for(let t=e.length-1;t>=0;t--)if(e[t].role==="assistant")return e[t].id;return null}function pf(e,t,r){return e.map(n=>{if(n.id!==t)return n;const o=n.content.slice(),s=o[o.length-1];return s&&s.type==="text"?s.text+=r:o.push({type:"text",text:r}),{...n,content:o}})}function ta(e,t,r){return e.map(n=>n.id===t?{...n,content:hf(n.content,r)}:n)}function hf(e,t){const r=e.slice();for(const n of t)if(n.type==="text"){const o=r[r.length-1];(o==null?void 0:o.type)==="text"?o.text+=n.text:r.push({type:"text",text:n.text})}else r.push(n);return r}function gf(e,t){for(let r=e.length-1;r>=0;r--)if(e[r].role==="assistant"){const o={...e[r],checkpointId:t};return[...e.slice(0,r),o,...e.slice(r+1)]}return e}function mf(e){if(!e)return null;const t=e.split("/");return t[t.length-1]||null}const ra=T.createContext(null);function Xt({children:e,apiConfig:t,onError:r,onThreadChange:n,initialThreadId:o=null,historyPageSize:s}){const a=tt;T.useEffect(()=>{t&&a.updateConfig({baseUrl:t.baseUrl,authToken:t.apiKey})},[a,t]);const{isStreaming:c,error:d,stream:f,stop:u,setToken:p}=Qs({baseUrl:a.baseUrl,token:null,headers:t==null?void 0:t.headers,streamPath:"/chat/stream"}),[m,v]=T.useState(()=>typeof a.getAuthToken=="function"?a.getAuthToken():null);T.useEffect(()=>{p(typeof a.getAuthToken=="function"?a.getAuthToken():null);const V=a.onTokenChange(K=>{v(K),p(K)});return()=>{V()}},[a,p]);const g=T.useCallback(V=>{a.setAuthToken(V)},[a]),{state:h,seed:b,prepend:w,pushUser:y,onEvent:x,reset:C}=ea(),E=s&&s>0?s:6,[O,N]=T.useState(!1),[L,D]=T.useState(!1),[$,R]=T.useState(null),[X,B]=T.useState(void 0),M=T.useCallback((V,K)=>{const be=Array.isArray(V==null?void 0:V.messages)?V.messages:[];K==="replace"?b(be):K==="prepend"&&be.length&&w(be),R((V==null?void 0:V.nextCursor)??null),N(!!(V!=null&&V.hasMore)),B(ee=>(V==null?void 0:V.checkpointId)??ee??void 0)},[b,w]),[J,F]=T.useState([]),[H,P]=T.useState(null),_=T.useCallback(async()=>{const V=await a.listThreads();F(V)},[a]);T.useEffect(()=>{_().catch(()=>{})},[_]),T.useEffect(()=>{n==null||n(H)},[H,n]);const G=T.useRef(null);T.useEffect(()=>{o&&G.current!==o&&(G.current=o,Z(o).catch(()=>{}))},[o]);const j=T.useRef(null),Z=T.useCallback(async(V,K,be)=>{var ee;if(j.current!==V){j.current=V;try{const ye=K??((ee=(await a.listCheckpoints(V)).checkpoints.slice().sort((fe,Ne)=>new Date(Ne.createdAt).getTime()-new Date(fe.createdAt).getTime())[0])==null?void 0:ee.checkpointId);N(!1),R(null),B(void 0);const ae=await a.getMessages({threadId:V,checkpointId:ye,checkpointNs:be,limit:E});P(V),M(ae,"replace")}finally{j.current=null}}},[a,M]),I=T.useCallback(async V=>a.listCheckpoints(V),[a]),W=T.useCallback(async V=>{if(!H)throw new Error("No active thread");N(!1),R(null),B(void 0);const K=await a.getMessages({threadId:H,checkpointId:V,limit:E});M(K,"replace")},[a,H,M]),ge=T.useCallback(async()=>{if(!H)throw new Error("No active thread");await Z(H)},[H,Z]),he=T.useRef(!1);T.useEffect(()=>{const V=he.current;if(he.current=c,V&&!c&&H){const K=h.lastCheckpointId??void 0;(async()=>{try{const be=await a.getMessages({threadId:H,checkpointId:K,limit:E});M(be,"replace")}catch{}try{await _()}catch{}})()}},[c,H,h.lastCheckpointId,a,M,_]);const z=T.useCallback(async V=>{const K=await a.createThread(V);return await _(),await Z(K.threadId),K.threadId},[a,_,Z]),ce=T.useCallback(async V=>{await a.deleteThread(V),await _(),H===V&&(P(null),C([]),N(!1),R(null),B(void 0))},[a,_,H,C]),pe=T.useCallback(async(V,K)=>{await a.updateThread(V,K),await _()},[a,_]),le=T.useCallback(async(V,K)=>{var Et;if(!H)throw new Error("No active thread");async function be(ie){return await new Promise((Ie,ke)=>{const Re=new FileReader;Re.onload=()=>Ie(String(Re.result)),Re.onerror=k=>ke(k),Re.readAsDataURL(ie)})}async function ee(ie){return await new Promise((Ie,ke)=>{const Re=new FileReader;Re.onload=()=>{try{const k=Re.result;let Y="";const re=new Uint8Array(k),oe=re.byteLength;for(let ve=0;ve<oe;ve++)Y+=String.fromCharCode(re[ve]);Ie(btoa(Y))}catch(k){ke(k)}},Re.onerror=k=>ke(k),Re.readAsArrayBuffer(ie)})}const ye=[];V&&ye.push({type:"text",text:V});const ae=(K==null?void 0:K.attachments)||[];let fe=[];if(ae.length>0)for(const ie of ae)if(ie.type&&ie.type.startsWith("image/")){let Ie=null;try{const ke=await a.uploadImage(ie,(t==null?void 0:t.uploadPath)||"/upload").catch(()=>null);Ie=(ke==null?void 0:ke.url)||null}catch{}if(!Ie)try{Ie=await be(ie)}catch{Ie=null}if(Ie){const ke={type:"image_url",url:Ie,mimeType:ie.type,alt:ie.name};ye.push(ke)}try{fe.push({filename:ie.name,data:await ee(ie),mime_type:ie.type||"application/octet-stream"})}catch{}}else{const Ie=await be(ie).catch(()=>null),ke={type:"file",url:String(Ie),mimeType:ie.type||void 0,name:ie.name,size:ie.size};ye.push(ke);try{fe.push({filename:ie.name,data:await ee(ie),mime_type:ie.type||"application/octet-stream"})}catch{}}const Ne={id:((Et=crypto.randomUUID)==null?void 0:Et.call(crypto))||`user-${Date.now()}`,role:"user",content:ye,createdAt:new Date().toISOString(),checkpointId:(K==null?void 0:K.checkpointId)??h.lastCheckpointId??void 0};y(Ne);const ot={...Ne,content:Ne.content.filter(ie=>ie.type==="text"||ie.type==="image_url")},as={threadId:H,payload:{messages:[ot],attachments:Ne.content.filter(ie=>ie.type==="file").map(ie=>({type:"file",url:ie.url,mimeType:ie.mimeType,name:ie.name,size:ie.size})),files_info:fe,...(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};f(as,ie=>x(ie),{onError:ie=>console.warn("stream error",ie)})},[H,y,f,x,h.lastCheckpointId,a,t==null?void 0:t.uploadPath]),de=T.useCallback(async V=>{if(!H)throw new Error("No active thread");if(L||!O)return;const K=$;if(K){D(!0);try{const be=await a.getMessages({threadId:H,checkpointId:X,limit:(V==null?void 0:V.limit)??E,beforeId:K});M(be,"prepend")}finally{D(!1)}}},[a,H,X,$,O,L,M]),ue={baseUrl:a.baseUrl,token:m,setToken:g,api:a,threads:J,currentThreadId:H,setCurrentThreadId:P,messages:h.messages,isStreaming:c,error:d,lastCheckpointId:h.lastCheckpointId,streamingAssistantId:h.assemblingId,hasMoreHistory:O,isLoadingHistory:L,loadOlderMessages:de,historyPageSize:E,refreshThreads:_,createThread:z,deleteThread:ce,renameThread:pe,loadThread:Z,listCheckpoints:I,navigateToCheckpoint:W,returnToLatest:ge,send:le,stop:u};return i.jsx(ra.Provider,{value:ue,children:e})}function jn(){const e=T.useContext(ra);if(!e)throw new Error("useChat must be used within ChatProvider");return e}function A(...e){return Fd.twMerge(Ld.clsx(e))}const bf=Wt.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"}}),me=l.forwardRef(({className:e,variant:t,size:r,asChild:n=!1,...o},s)=>{const a=n?Oe.Slot:"button";return i.jsx(a,{className:A(bf({variant:t,size:r,className:e})),ref:s,...o})});me.displayName="Button";const na=l.forwardRef(({className:e,...t},r)=>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:r,...t}));na.displayName="Textarea";const vf=Wt.cva("inline-flex items-center rounded-full border px-2.5 py-0.5 text-xs font-semibold transition-colors focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2",{variants:{variant:{default:"border-transparent bg-primary text-primary-foreground hover:bg-primary/80",secondary:"border-transparent bg-secondary text-secondary-foreground hover:bg-secondary/80",destructive:"border-transparent bg-destructive text-destructive-foreground hover:bg-destructive/80",outline:"text-foreground"}},defaultVariants:{variant:"default"}});function oa({className:e,variant:t,...r}){return i.jsx("div",{className:A(vf({variant:t}),e),...r})}function U(e,t,{checkForDefaultPrevented:r=!0}={}){return function(o){if(e==null||e(o),r===!1||!o.defaultPrevented)return t==null?void 0:t(o)}}function wf(e,t){const r=l.createContext(t),n=s=>{const{children:a,...c}=s,d=l.useMemo(()=>c,Object.values(c));return i.jsx(r.Provider,{value:d,children:a})};n.displayName=e+"Provider";function o(s){const a=l.useContext(r);if(a)return a;if(t!==void 0)return t;throw new Error(`\`${s}\` must be used within \`${e}\``)}return[n,o]}function Ue(e,t=[]){let r=[];function n(s,a){const c=l.createContext(a),d=r.length;r=[...r,a];const f=p=>{var w;const{scope:m,children:v,...g}=p,h=((w=m==null?void 0:m[e])==null?void 0:w[d])||c,b=l.useMemo(()=>g,Object.values(g));return i.jsx(h.Provider,{value:b,children:v})};f.displayName=s+"Provider";function u(p,m){var h;const v=((h=m==null?void 0:m[e])==null?void 0:h[d])||c,g=l.useContext(v);if(g)return g;if(a!==void 0)return a;throw new Error(`\`${p}\` must be used within \`${s}\``)}return[f,u]}const o=()=>{const s=r.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,[n,yf(o,...t)]}function yf(...e){const t=e[0];if(e.length===1)return t;const r=()=>{const n=e.map(o=>({useScope:o(),scopeName:o.scopeName}));return function(s){const a=n.reduce((c,{useScope:d,scopeName:f})=>{const p=d(s)[`__scope${f}`];return{...c,...p}},{});return l.useMemo(()=>({[`__scope${t.scopeName}`]:a}),[a])}};return r.scopeName=t.scopeName,r}var xe=globalThis!=null&&globalThis.document?l.useLayoutEffect:()=>{},xf=l[" useInsertionEffect ".trim().toString()]||xe;function st({prop:e,defaultProp:t,onChange:r=()=>{},caller:n}){const[o,s,a]=Sf({defaultProp:t,onChange:r}),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(`${n} 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,n])}const f=l.useCallback(u=>{var p;if(c){const m=Cf(u)?u(e):u;m!==e&&((p=a.current)==null||p.call(a,m))}else s(u)},[c,e,s,a]);return[d,f]}function Sf({defaultProp:e,onChange:t}){const[r,n]=l.useState(e),o=l.useRef(r),s=l.useRef(t);return xf(()=>{s.current=t},[t]),l.useEffect(()=>{var a;o.current!==r&&((a=s.current)==null||a.call(s,r),o.current=r)},[r,o]),[r,n,s]}function Cf(e){return typeof e=="function"}function sa(e,t){if(typeof e=="function")return e(t);e!=null&&(e.current=t)}function Rn(...e){return t=>{let r=!1;const n=e.map(o=>{const s=sa(o,t);return!r&&typeof s=="function"&&(r=!0),s});if(r)return()=>{for(let o=0;o<n.length;o++){const s=n[o];typeof s=="function"?s():sa(e[o],null)}}}}function se(...e){return l.useCallback(Rn(...e),e)}var Ef=["a","button","div","form","h2","h3","img","input","label","li","nav","ol","p","select","span","svg","ul"],Q=Ef.reduce((e,t)=>{const r=Oe.createSlot(`Primitive.${t}`),n=l.forwardRef((o,s)=>{const{asChild:a,...c}=o,d=a?r:t;return typeof window<"u"&&(window[Symbol.for("radix-ui")]=!0),i.jsx(d,{...c,ref:s})});return n.displayName=`Primitive.${t}`,{...e,[t]:n}},{});function aa(e,t){e&&hr.flushSync(()=>e.dispatchEvent(t))}function Nf(e,t){return l.useReducer((r,n)=>t[r][n]??r,e)}var _e=e=>{const{present:t,children:r}=e,n=Tf(t),o=typeof r=="function"?r({present:n.isPresent}):l.Children.only(r),s=se(n.ref,Af(o));return typeof r=="function"||n.isPresent?l.cloneElement(o,{ref:s}):null};_e.displayName="Presence";function Tf(e){const[t,r]=l.useState(),n=l.useRef(null),o=l.useRef(e),s=l.useRef("none"),a=e?"mounted":"unmounted",[c,d]=Nf(a,{mounted:{UNMOUNT:"unmounted",ANIMATION_OUT:"unmountSuspended"},unmountSuspended:{MOUNT:"mounted",ANIMATION_END:"unmounted"},unmounted:{MOUNT:"mounted"}});return l.useEffect(()=>{const f=Ar(n.current);s.current=c==="mounted"?f:"none"},[c]),xe(()=>{const f=n.current,u=o.current;if(u!==e){const m=s.current,v=Ar(f);e?d("MOUNT"):v==="none"||(f==null?void 0:f.display)==="none"?d("UNMOUNT"):d(u&&m!==v?"ANIMATION_OUT":"UNMOUNT"),o.current=e}},[e,d]),xe(()=>{if(t){let f;const u=t.ownerDocument.defaultView??window,p=v=>{const h=Ar(n.current).includes(CSS.escape(v.animationName));if(v.target===t&&h&&(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)})}},m=v=>{v.target===t&&(s.current=Ar(n.current))};return t.addEventListener("animationstart",m),t.addEventListener("animationcancel",p),t.addEventListener("animationend",p),()=>{u.clearTimeout(f),t.removeEventListener("animationstart",m),t.removeEventListener("animationcancel",p),t.removeEventListener("animationend",p)}}else d("ANIMATION_END")},[t,d]),{isPresent:["mounted","unmountSuspended"].includes(c),ref:l.useCallback(f=>{n.current=f?getComputedStyle(f):null,r(f)},[])}}function Ar(e){return(e==null?void 0:e.animationName)||"none"}function Af(e){var n,o;let t=(n=Object.getOwnPropertyDescriptor(e.props,"ref"))==null?void 0:n.get,r=t&&"isReactWarning"in t&&t.isReactWarning;return r?e.ref:(t=(o=Object.getOwnPropertyDescriptor(e,"ref"))==null?void 0:o.get,r=t&&"isReactWarning"in t&&t.isReactWarning,r?e.props.ref:e.props.ref||e.ref)}var Pf=l[" useId ".trim().toString()]||(()=>{}),_f=0;function He(e){const[t,r]=l.useState(Pf());return xe(()=>{r(n=>n??String(_f++))},[e]),t?`radix-${t}`:""}var Pr="Collapsible",[If,Uw]=Ue(Pr),[kf,Kn]=If(Pr),ia=l.forwardRef((e,t)=>{const{__scopeCollapsible:r,open:n,defaultOpen:o,disabled:s,onOpenChange:a,...c}=e,[d,f]=st({prop:n,defaultProp:o??!1,onChange:a,caller:Pr});return i.jsx(kf,{scope:r,disabled:s,contentId:He(),open:d,onOpenToggle:l.useCallback(()=>f(u=>!u),[f]),children:i.jsx(Q.div,{"data-state":qn(d),"data-disabled":s?"":void 0,...c,ref:t})})});ia.displayName=Pr;var ca="CollapsibleTrigger",la=l.forwardRef((e,t)=>{const{__scopeCollapsible:r,...n}=e,o=Kn(ca,r);return i.jsx(Q.button,{type:"button","aria-controls":o.contentId,"aria-expanded":o.open||!1,"data-state":qn(o.open),"data-disabled":o.disabled?"":void 0,disabled:o.disabled,...n,ref:t,onClick:U(e.onClick,o.onOpenToggle)})});la.displayName=ca;var Gn="CollapsibleContent",Of=l.forwardRef((e,t)=>{const{forceMount:r,...n}=e,o=Kn(Gn,e.__scopeCollapsible);return i.jsx(_e,{present:r||o.open,children:({present:s})=>i.jsx(Mf,{...n,ref:t,present:s})})});Of.displayName=Gn;var Mf=l.forwardRef((e,t)=>{const{__scopeCollapsible:r,present:n,children:o,...s}=e,a=Kn(Gn,r),[c,d]=l.useState(n),f=l.useRef(null),u=se(t,f),p=l.useRef(0),m=p.current,v=l.useRef(0),g=v.current,h=a.open||c,b=l.useRef(h),w=l.useRef(void 0);return l.useEffect(()=>{const y=requestAnimationFrame(()=>b.current=!1);return()=>cancelAnimationFrame(y)},[]),xe(()=>{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(n)}},[a.open,n]),i.jsx(Q.div,{"data-state":qn(a.open),"data-disabled":a.disabled?"":void 0,id:a.contentId,hidden:!h,...s,ref:u,style:{"--radix-collapsible-content-height":m?`${m}px`:void 0,"--radix-collapsible-content-width":g?`${g}px`:void 0,...e.style},children:h&&o})});function qn(e){return e?"open":"closed"}var Df=ia;const da=Df,ua=la;function Yt({content:e,className:t=""}){const r=T.useMemo(()=>({table:({node:f,className:u,...p})=>i.jsx("div",{className:"max-w-full",children:i.jsx("table",{...p,className:A("w-full table-fixed border-collapse break-words",u)})}),th:({node:f,className:u,...p})=>i.jsx("th",{...p,className:A("break-words whitespace-normal border-b border-border/60 px-3 py-2 text-left align-top",u)}),td:({node:f,className:u,...p})=>i.jsx("td",{...p,className:A("break-words whitespace-normal border-b border-border/30 px-3 py-2 align-top",u)}),pre:({node:f,className:u,...p})=>i.jsx("pre",{...p,className:A("whitespace-pre-wrap break-words",u)}),code:({node:f,className:u,children:p,...m})=>{const{inline:v,...g}=m;return v?i.jsx("code",{...g,className:A("break-words whitespace-normal",u),children:p}):i.jsx("code",{...g,className:A("block break-words whitespace-pre-wrap",u),children:p})}}),[]),n=A("prose prose-sm max-w-none break-words dark:prose-invert leading-relaxed","prose-headings:break-words prose-p:break-words prose-li:break-words prose-td:break-words prose-th:break-words","prose-a:break-all prose-blockquote:break-words prose-strong:break-words prose-em:break-words","prose-code:break-words 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",t);return i.jsx("div",{className:n,style:{wordBreak:"break-word",overflowWrap:"anywhere"},children:i.jsx($d,{remarkPlugins:[Bd],components:r,children:e})})}const _r="prose prose-sm max-w-none break-words dark:prose-invert prose-headings:break-words prose-p:break-words prose-li:break-words prose-td:break-words prose-th:break-words prose-a:break-all prose-code:break-words prose-blockquote:break-words";function Lf({className:e}){const[t,r]=T.useState(0);return T.useEffect(()=>{const n=setInterval(()=>r(o=>(o+1)%4),500);return()=>clearInterval(n)},[]),i.jsxs("span",{"aria-live":"polite",className:A("inline-block text-xs opacity-70 ml-1",e),children:["Is thinking",".".repeat(t)]})}function fa({message:e,messageIndex:t,isStreamingMessage:r=!1,streamingDebounceMs:n=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:m=200,customStyles:v={},checkpointBranches:g=[],currentCheckpointId:h,onSwitchToCheckpoint:b,onReturnToMainThread:w,temporalNavigation:y,onNavigateToPreviousBranch:x,onNavigateToNextBranch:C,onEdit:E,onRegenerate:O,onEditFromCheckpoint:N,onCancelEdit:L,onCopy:D}){const[$,R]=T.useState(!1),[X,B]=T.useState(!1),[M,J]=T.useState(!1),[F,H]=T.useState(!1),P=d==="phone"||d==="half-screen",_=e.role,G=_==="tool",j=T.useMemo(()=>{switch(_){case"user":return"text-[hsl(var(--chat-bubble-user-text))]";case"assistant":return"text-[hsl(var(--chat-bubble-ai-text))]";case"tool":return"text-secondary-foreground";case"system":return"text-muted-foreground";default:return"text-foreground"}},[_]),Z=T.useMemo(()=>Ff(e.content),[e.content]),I=T.useMemo(()=>Wf(e.content),[e.content]),W=T.useMemo(()=>e.content.filter(ee=>ee.type==="image_url"),[e.content]),ge=T.useMemo(()=>e.content.filter(ee=>ee.type==="file"),[e.content]),he=Rf(Z,r?n:0),z=async()=>{try{const ee=G?Pt(e.content):Z;await navigator.clipboard.writeText(ee),R(!0),setTimeout(()=>R(!1),2e3),D==null||D(ee)}catch(ee){console.error("Failed to copy:",ee)}},ce=()=>{if(!E)return;const ee=G?Pt(e.content):Z;E(e.id,ee)},pe=()=>O==null?void 0:O(t),le=()=>{const ye=A(P?"h-3 w-3":"h-4 w-4","opacity-60 flex-shrink-0",j);switch(_){case"user":return i.jsx(q.User,{className:ye});case"assistant":return i.jsx(q.Bot,{className:ye});case"tool":return i.jsx(q.Wrench,{className:ye});default:return i.jsx(q.Bot,{className:ye})}},de=()=>{const ee="group relative mb-4 max-w-full";switch(_){case"user":return A(ee,"flex justify-end");case"assistant":case"tool":case"system":return A(ee,"flex justify-start");default:return ee}},ue=()=>{const ee=A("rounded-lg px-4 py-3 relative transition-all duration-200 min-w-0 break-words",P&&"px-3 py-2 text-sm");switch(_){case"user":return A(ee,"max-w-[95%]",d==="phone"&&"max-w-[98%]","bg-[hsl(var(--chat-bubble-user))] text-[hsl(var(--chat-bubble-user-text))]","border border-transparent");case"assistant":return A(ee,"max-w-[95%]",d==="phone"&&"max-w-[98%]","bg-[hsl(var(--chat-bubble-ai))] text-[hsl(var(--chat-bubble-ai-text))]","border border-border/60 dark:border-border/40");case"tool":return A(ee,"bg-secondary/50 text-secondary-foreground border border-dashed max-w-[95%]",d==="phone"&&"max-w-[98%]");case"system":return A(ee,"bg-accent/40 text-muted-foreground max-w-[85%] border");default:return ee}},V=ee=>{if(!ee)return"";try{return new Date(ee).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"})}catch{return""}},K=()=>{if(e.model==="reflection"){const ae=Z.trim(),fe=Xn(ae);if(fe&&typeof fe=="object")return i.jsx(Kf,{data:fe})}if(G&&I.name==="get_issues"){const ae=e.content.find(ot=>ot.type==="tool_result"),fe=(ae==null?void 0:ae.output)??Pt(e.content),Ne=ha(fe);if(Ne)return i.jsx(Gf,{issues:Ne})}if(G&&!M){const ae=Pt(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 text-current",P&&"text-[10px]"),children:i.jsxs("span",{className:"truncate max-w-full text-current",children:[ae,ae.length>=80?"…":""]})})}if(G&&f){const ae=Pt(e.content),fe=ae.length>u;return i.jsx(da,{open:X,onOpenChange:B,children:i.jsxs("div",{className:"font-mono text-sm text-current",children:[i.jsx("pre",{className:A("whitespace-pre-wrap break-words text-current",P&&"text-xs"),children:fe&&!X?ae.substring(0,u)+"...":ae}),fe&&i.jsx(ua,{asChild:!0,children:i.jsx(me,{variant:"ghost",size:"sm",className:"h-6 text-xs text-current",children:X?i.jsxs(i.Fragment,{children:[i.jsx(q.ChevronUp,{className:"h-3 w-3 mr-1"}),"Show less"]}):i.jsxs(i.Fragment,{children:[i.jsx(q.ChevronDown,{className:"h-3 w-3 mr-1"}),"Show more (",ae.length-u," chars)"]})})})]})})}if(G&&M&&!f){const ae=zf(e.content);if(ae&&$f(ae))return i.jsx(Yt,{content:ae.trim()});const fe=Pt(e.content);return i.jsx("div",{className:"font-mono text-sm text-current",children:i.jsx("pre",{className:A("whitespace-pre-wrap break-words text-current",P&&"text-xs"),children:fe})})}const ee=W.length>0&&_!=="tool",ye=ge.length>0&&_!=="tool";return i.jsxs("div",{children:[r?i.jsxs("div",{className:"relative",children:[(()=>{const ae=Xn(he);return ae!==null?i.jsx(pa,{data:ae}):i.jsx(Yt,{content:Uf(Bf(he))})})(),i.jsx(Lf,{className:A(j,P?"text-xs":"text-sm")})]}):(()=>{const ae=Xn(Z.trim());if(ae!==null)return i.jsx(pa,{data:ae});if(_==="user"&&p){const fe=Z.trim();if(fe.length>m)return i.jsxs(da,{open:F,onOpenChange:H,children:[i.jsx("div",{className:A("text-sm text-[hsl(var(--chat-bubble-user-text))]",P&&"text-xs"),children:F?i.jsx(Yt,{content:fe}):i.jsxs("pre",{className:A("font-sans whitespace-pre-wrap break-words bg-transparent p-0 m-0 text-[hsl(var(--chat-bubble-user-text))]",P&&"text-xs"),children:[fe.substring(0,m),"..."]})}),i.jsx(ua,{asChild:!0,children:i.jsx(me,{variant:"ghost",size:"sm",className:"h-6 text-xs !text-[hsl(var(--chat-bubble-user-text))]",children:F?i.jsxs(i.Fragment,{children:[i.jsx(q.ChevronUp,{className:"h-3 w-3 mr-1"})," Show less"]}):i.jsxs(i.Fragment,{children:[i.jsx(q.ChevronDown,{className:"h-3 w-3 mr-1"})," Show more (",fe.length-m," chars)"]})})})]})}return i.jsx(Yt,{content:Z.trim()})})(),ee&&i.jsx("div",{className:"mt-2 grid grid-cols-2 gap-2",children:W.map((ae,fe)=>i.jsxs("div",{className:"relative border rounded overflow-hidden",children:[i.jsx("img",{src:ae.url,alt:ae.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(q.Image,{className:"h-3 w-3"}),i.jsx("span",{children:"image"})]})]},fe))}),ye&&i.jsx("div",{className:"mt-2 flex flex-wrap gap-2",children:ge.map((ae,fe)=>{const Ne=ae,ot=Ne.name||"file";return i.jsxs("a",{href:Ne.url,download:ot,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:ot,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:ot})]},fe)})})]})},be=T.useMemo(()=>Vf(e),[e]);return T.useMemo(()=>jf(e,h),[e,h]),i.jsx("div",{className:A(de(),v.container),children:i.jsxs("div",{className:A(ue(),v.content),children:[(a||c||G)&&i.jsxs("div",{className:A("flex items-center justify-between mb-2 pb-2 border-b border-current/10",P&&"mb-1 pb-1",j,v.header),children:[i.jsxs("div",{className:"flex items-center gap-2",children:[le(),c&&be&&i.jsx("span",{className:A("font-medium",P?"text-xs":"text-sm"),children:be}),G&&I.name&&i.jsxs(oa,{variant:"outline",className:A("text-xs flex items-center gap-1 cursor-pointer",j,"border border-current/40",P&&"text-xs h-4"),onClick:()=>J(ee=>!ee),children:[i.jsx("span",{children:I.name}),i.jsx("span",{className:"inline-flex items-center",children:M?i.jsx(q.ChevronUp,{className:"h-3 w-3"}):i.jsx(q.ChevronDown,{className:"h-3 w-3"})})]}),G&&!I.name&&i.jsx(me,{variant:"ghost",size:"sm",className:A("h-6 px-1",j,"hover:bg-foreground/10"),onClick:()=>J(ee=>!ee),children:i.jsxs("span",{className:"text-xs flex items-center gap-1",children:["Tool Output ",M?i.jsx(q.ChevronUp,{className:"h-3 w-3"}):i.jsx(q.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",j,P&&"text-xs"),children:V(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(me,{variant:"ghost",size:"sm",onClick:z,className:A("h-6 w-6 p-0 hover:bg-foreground/10",j,P&&"h-5 w-5"),children:i.jsx(q.Copy,{className:A($?"text-success":j,P?"h-3 w-3":"h-4 w-4")})}),_==="user"&&E&&i.jsx(me,{variant:"ghost",size:"sm",onClick:ce,className:A("h-6 w-6 p-0 hover:bg-foreground/10",j,P&&"h-5 w-5"),children:i.jsx(q.Edit,{className:A(j,P?"h-3 w-3":"h-4 w-4")})}),_==="assistant"&&O&&i.jsx(me,{variant:"ghost",size:"sm",onClick:pe,className:A("h-6 w-6 p-0 hover:bg-foreground/10",j,P&&"h-5 w-5"),children:i.jsx(q.RotateCcw,{className:A(j,P?"h-3 w-3":"h-4 w-4")})})]})]})]}),i.jsx("div",{className:"relative",children:K()}),G&&M&&(I.toolCallId||I.name)&&i.jsxs("div",{className:A("mt-2 pt-2 border-t border-current/10 text-xs opacity-60",P&&"text-xs"),children:[I.name&&i.jsxs("div",{children:["Function: ",I.name]}),I.toolCallId&&i.jsxs("div",{children:["Call ID: ",I.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(q.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(me,{variant:"ghost",size:"sm",className:A("h-6 w-6 p-0",j),disabled:!y.canGoBack,onClick:()=>x==null?void 0:x(),title:"Go back to previous branch",children:i.jsx(q.ChevronLeft,{className:A("h-3 w-3",j)})}),i.jsx(me,{variant:"ghost",size:"sm",className:A("h-6 w-6 p-0",j),disabled:!y.canGoForward,onClick:()=>C==null?void 0:C(),title:"Go forward to next branch",children:i.jsx(q.ChevronRight,{className:A("h-3 w-3",j)})})]})]}),!(a||c||G)&&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(me,{variant:"ghost",size:"sm",onClick:z,className:A("h-6 w-6 p-0 hover:bg-background/50 text-current",P&&"h-5 w-5"),children:i.jsx(q.Copy,{className:A($?"text-success":"text-current",P?"h-3 w-3":"h-4 w-4")})}),_==="user"&&E&&i.jsx(me,{variant:"ghost",size:"sm",onClick:ce,className:A("h-6 w-6 p-0 hover:bg-background/50 text-current",P&&"h-5 w-5"),children:i.jsx(q.Edit,{className:A("text-current",P?"h-3 w-3":"h-4 w-4")})}),_==="assistant"&&O&&i.jsx(me,{variant:"ghost",size:"sm",onClick:pe,className:A("h-6 w-6 p-0 hover:bg-background/50 text-current",P&&"h-5 w-5"),children:i.jsx(q.RotateCcw,{className:A("text-current",P?"h-3 w-3":"h-4 w-4")})})]})]})})}function Ff(e){const t=e.filter(r=>r.type==="text").map(r=>r.text).join("");return t||JSON.stringify(e)}function $f(e){return e.includes(`
9
+ `)}const uf={messages:[],assemblingId:null,lastCheckpointId:null,toolIndex:{}};function ff(e,t){var r,n;switch(t.type){case"reset":return{messages:Wn(((r=t.payload)==null?void 0:r.messages)??[]),assemblingId:null,lastCheckpointId:null,toolIndex:{}};case"seed":return{...e,messages:Wn(t.payload.messages)};case"prepend":{const o=Wn(t.payload.messages);if(!o.length)return e;const s=new Set(e.messages.map(c=>c.id)),a=o.filter(c=>!s.has(c.id));return a.length?{...e,messages:[...a,...e.messages]}:e}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=mf(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??Vn(e.messages);return s?{...e,messages:pf(e.messages,s,o.content)}:e}if(o.type==="message_delta"){const s=e.assemblingId??Vn(e.messages);return s?{...e,messages:ta(e.messages,s,o.delta)}:e}if(o.type==="message_end"){const s=e.assemblingId??Vn(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&&!((n=a[c].content)==null?void 0:n.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?ta(e.messages,s,[a]):[...e.messages,d];return{...e,messages:f}}if(o.type==="checkpoint"){const s=gf(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 ea(e=[]){const[t,r]=T.useReducer(ff,{...uf,messages:e}),n=T.useCallback(s=>{r({type:"event",payload:{ev:s}})},[]),o=T.useMemo(()=>({reset:s=>r({type:"reset",payload:{messages:s}}),seed:s=>r({type:"seed",payload:{messages:s}}),prepend:s=>r({type:"prepend",payload:{messages:s}}),pushUser:s=>r({type:"user_message",payload:{message:s}}),onEvent:n}),[n]);return{state:t,dispatch:r,...o}}function Wn(e){return e.filter(t=>{if(t.role!=="assistant")return!0;const r=(t.content||[]).some(o=>{var s;return o&&o.type==="text"&&((s=o.text)==null?void 0:s.trim())}),n=(t.content||[]).some(o=>o&&o.type==="image_url");return!!(r||n)})}function Vn(e){for(let t=e.length-1;t>=0;t--)if(e[t].role==="assistant")return e[t].id;return null}function pf(e,t,r){return e.map(n=>{if(n.id!==t)return n;const o=n.content.slice(),s=o[o.length-1];return s&&s.type==="text"?s.text+=r:o.push({type:"text",text:r}),{...n,content:o}})}function ta(e,t,r){return e.map(n=>n.id===t?{...n,content:hf(n.content,r)}:n)}function hf(e,t){const r=e.slice();for(const n of t)if(n.type==="text"){const o=r[r.length-1];(o==null?void 0:o.type)==="text"?o.text+=n.text:r.push({type:"text",text:n.text})}else r.push(n);return r}function gf(e,t){for(let r=e.length-1;r>=0;r--)if(e[r].role==="assistant"){const o={...e[r],checkpointId:t};return[...e.slice(0,r),o,...e.slice(r+1)]}return e}function mf(e){if(!e)return null;const t=e.split("/");return t[t.length-1]||null}const ra=T.createContext(null);function Xt({children:e,apiConfig:t,onError:r,onThreadChange:n,initialThreadId:o=null,historyPageSize:s}){const a=tt;T.useEffect(()=>{t&&a.updateConfig({baseUrl:t.baseUrl,authToken:t.apiKey})},[a,t]);const{isStreaming:c,error:d,stream:f,stop:u,setToken:p}=Qs({baseUrl:a.baseUrl,token:null,headers:t==null?void 0:t.headers,streamPath:"/chat/stream"}),[m,v]=T.useState(()=>typeof a.getAuthToken=="function"?a.getAuthToken():null);T.useEffect(()=>{p(typeof a.getAuthToken=="function"?a.getAuthToken():null);const V=a.onTokenChange(K=>{v(K),p(K)});return()=>{V()}},[a,p]);const g=T.useCallback(V=>{a.setAuthToken(V)},[a]),{state:h,seed:b,prepend:w,pushUser:y,onEvent:x,reset:C}=ea(),E=s&&s>0?s:6,[O,N]=T.useState(!1),[L,D]=T.useState(!1),[$,R]=T.useState(null),[X,B]=T.useState(void 0),M=T.useCallback((V,K)=>{const be=Array.isArray(V==null?void 0:V.messages)?V.messages:[];K==="replace"?b(be):K==="prepend"&&be.length&&w(be),R((V==null?void 0:V.nextCursor)??null),N(!!(V!=null&&V.hasMore)),B(ee=>(V==null?void 0:V.checkpointId)??ee??void 0)},[b,w]),[J,F]=T.useState([]),[H,P]=T.useState(null),_=T.useCallback(async()=>{const V=await a.listThreads();F(V)},[a]);T.useEffect(()=>{_().catch(()=>{})},[_]),T.useEffect(()=>{n==null||n(H)},[H,n]);const G=T.useRef(null);T.useEffect(()=>{o&&G.current!==o&&(G.current=o,Z(o).catch(()=>{}))},[o]);const j=T.useRef(null),Z=T.useCallback(async(V,K,be)=>{var ee;if(j.current!==V){j.current=V;try{const ye=K??((ee=(await a.listCheckpoints(V)).checkpoints.slice().sort((fe,Ne)=>new Date(Ne.createdAt).getTime()-new Date(fe.createdAt).getTime())[0])==null?void 0:ee.checkpointId);N(!1),R(null),B(void 0);const ae=await a.getMessages({threadId:V,checkpointId:ye,checkpointNs:be,limit:E});P(V),M(ae,"replace")}finally{j.current=null}}},[a,M]),I=T.useCallback(async V=>a.listCheckpoints(V),[a]),W=T.useCallback(async V=>{if(!H)throw new Error("No active thread");N(!1),R(null),B(void 0);const K=await a.getMessages({threadId:H,checkpointId:V,limit:E});M(K,"replace")},[a,H,M]),ge=T.useCallback(async()=>{if(!H)throw new Error("No active thread");await Z(H)},[H,Z]),he=T.useRef(!1);T.useEffect(()=>{const V=he.current;if(he.current=c,V&&!c&&H){const K=h.lastCheckpointId??void 0;(async()=>{try{const be=await a.getMessages({threadId:H,checkpointId:K,limit:E});M(be,"replace")}catch{}try{await _()}catch{}})()}},[c,H,h.lastCheckpointId,a,M,_]);const z=T.useCallback(async V=>{const K=await a.createThread(V);return await _(),await Z(K.threadId),K.threadId},[a,_,Z]),ce=T.useCallback(async V=>{await a.deleteThread(V),await _(),H===V&&(P(null),C([]),N(!1),R(null),B(void 0))},[a,_,H,C]),pe=T.useCallback(async(V,K)=>{await a.updateThread(V,K),await _()},[a,_]),le=T.useCallback(async(V,K)=>{var Et;if(!H)throw new Error("No active thread");async function be(ie){return await new Promise((Ie,ke)=>{const Re=new FileReader;Re.onload=()=>Ie(String(Re.result)),Re.onerror=k=>ke(k),Re.readAsDataURL(ie)})}async function ee(ie){return await new Promise((Ie,ke)=>{const Re=new FileReader;Re.onload=()=>{try{const k=Re.result;let Y="";const re=new Uint8Array(k),oe=re.byteLength;for(let ve=0;ve<oe;ve++)Y+=String.fromCharCode(re[ve]);Ie(btoa(Y))}catch(k){ke(k)}},Re.onerror=k=>ke(k),Re.readAsArrayBuffer(ie)})}const ye=[];V&&ye.push({type:"text",text:V});const ae=(K==null?void 0:K.attachments)||[];let fe=[];if(ae.length>0)for(const ie of ae)if(ie.type&&ie.type.startsWith("image/")){let Ie=null;try{const ke=await a.uploadImage(ie,(t==null?void 0:t.uploadPath)||"/upload").catch(()=>null);Ie=(ke==null?void 0:ke.url)||null}catch{}if(!Ie)try{Ie=await be(ie)}catch{Ie=null}if(Ie){const ke={type:"image_url",url:Ie,mimeType:ie.type,alt:ie.name};ye.push(ke)}try{fe.push({filename:ie.name,data:await ee(ie),mime_type:ie.type||"application/octet-stream"})}catch{}}else{const Ie=await be(ie).catch(()=>null),ke={type:"file",url:String(Ie),mimeType:ie.type||void 0,name:ie.name,size:ie.size};ye.push(ke);try{fe.push({filename:ie.name,data:await ee(ie),mime_type:ie.type||"application/octet-stream"})}catch{}}const Ne={id:((Et=crypto.randomUUID)==null?void 0:Et.call(crypto))||`user-${Date.now()}`,role:"user",content:ye,createdAt:new Date().toISOString(),checkpointId:(K==null?void 0:K.checkpointId)??h.lastCheckpointId??void 0};y(Ne);const ot={...Ne,content:Ne.content.filter(ie=>ie.type==="text"||ie.type==="image_url")},as={threadId:H,payload:{messages:[ot],attachments:Ne.content.filter(ie=>ie.type==="file").map(ie=>({type:"file",url:ie.url,mimeType:ie.mimeType,name:ie.name,size:ie.size})),files_info:fe,...(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};f(as,ie=>x(ie),{onError:ie=>console.warn("stream error",ie)})},[H,y,f,x,h.lastCheckpointId,a,t==null?void 0:t.uploadPath]),de=T.useCallback(async V=>{if(!H)throw new Error("No active thread");if(L||!O)return;const K=$;if(K){D(!0);try{const be=await a.getMessages({threadId:H,checkpointId:X,limit:(V==null?void 0:V.limit)??E,beforeId:K});M(be,"prepend")}finally{D(!1)}}},[a,H,X,$,O,L,M]),ue={baseUrl:a.baseUrl,token:m,setToken:g,api:a,threads:J,currentThreadId:H,setCurrentThreadId:P,messages:h.messages,isStreaming:c,error:d,lastCheckpointId:h.lastCheckpointId,streamingAssistantId:h.assemblingId,hasMoreHistory:O,isLoadingHistory:L,loadOlderMessages:de,historyPageSize:E,refreshThreads:_,createThread:z,deleteThread:ce,renameThread:pe,loadThread:Z,listCheckpoints:I,navigateToCheckpoint:W,returnToLatest:ge,send:le,stop:u};return i.jsx(ra.Provider,{value:ue,children:e})}function jn(){const e=T.useContext(ra);if(!e)throw new Error("useChat must be used within ChatProvider");return e}function A(...e){return Fd.twMerge(Ld.clsx(e))}const bf=Wt.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"}}),me=l.forwardRef(({className:e,variant:t,size:r,asChild:n=!1,...o},s)=>{const a=n?Oe.Slot:"button";return i.jsx(a,{className:A(bf({variant:t,size:r,className:e})),ref:s,...o})});me.displayName="Button";const na=l.forwardRef(({className:e,...t},r)=>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:r,...t}));na.displayName="Textarea";const vf=Wt.cva("inline-flex items-center rounded-full border px-2.5 py-0.5 text-xs font-semibold transition-colors focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2",{variants:{variant:{default:"border-transparent bg-primary text-primary-foreground hover:bg-primary/80",secondary:"border-transparent bg-secondary text-secondary-foreground hover:bg-secondary/80",destructive:"border-transparent bg-destructive text-destructive-foreground hover:bg-destructive/80",outline:"text-foreground"}},defaultVariants:{variant:"default"}});function oa({className:e,variant:t,...r}){return i.jsx("div",{className:A(vf({variant:t}),e),...r})}function U(e,t,{checkForDefaultPrevented:r=!0}={}){return function(o){if(e==null||e(o),r===!1||!o.defaultPrevented)return t==null?void 0:t(o)}}function wf(e,t){const r=l.createContext(t),n=s=>{const{children:a,...c}=s,d=l.useMemo(()=>c,Object.values(c));return i.jsx(r.Provider,{value:d,children:a})};n.displayName=e+"Provider";function o(s){const a=l.useContext(r);if(a)return a;if(t!==void 0)return t;throw new Error(`\`${s}\` must be used within \`${e}\``)}return[n,o]}function Ue(e,t=[]){let r=[];function n(s,a){const c=l.createContext(a),d=r.length;r=[...r,a];const f=p=>{var w;const{scope:m,children:v,...g}=p,h=((w=m==null?void 0:m[e])==null?void 0:w[d])||c,b=l.useMemo(()=>g,Object.values(g));return i.jsx(h.Provider,{value:b,children:v})};f.displayName=s+"Provider";function u(p,m){var h;const v=((h=m==null?void 0:m[e])==null?void 0:h[d])||c,g=l.useContext(v);if(g)return g;if(a!==void 0)return a;throw new Error(`\`${p}\` must be used within \`${s}\``)}return[f,u]}const o=()=>{const s=r.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,[n,yf(o,...t)]}function yf(...e){const t=e[0];if(e.length===1)return t;const r=()=>{const n=e.map(o=>({useScope:o(),scopeName:o.scopeName}));return function(s){const a=n.reduce((c,{useScope:d,scopeName:f})=>{const p=d(s)[`__scope${f}`];return{...c,...p}},{});return l.useMemo(()=>({[`__scope${t.scopeName}`]:a}),[a])}};return r.scopeName=t.scopeName,r}var xe=globalThis!=null&&globalThis.document?l.useLayoutEffect:()=>{},xf=l[" useInsertionEffect ".trim().toString()]||xe;function st({prop:e,defaultProp:t,onChange:r=()=>{},caller:n}){const[o,s,a]=Sf({defaultProp:t,onChange:r}),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(`${n} 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,n])}const f=l.useCallback(u=>{var p;if(c){const m=Cf(u)?u(e):u;m!==e&&((p=a.current)==null||p.call(a,m))}else s(u)},[c,e,s,a]);return[d,f]}function Sf({defaultProp:e,onChange:t}){const[r,n]=l.useState(e),o=l.useRef(r),s=l.useRef(t);return xf(()=>{s.current=t},[t]),l.useEffect(()=>{var a;o.current!==r&&((a=s.current)==null||a.call(s,r),o.current=r)},[r,o]),[r,n,s]}function Cf(e){return typeof e=="function"}function sa(e,t){if(typeof e=="function")return e(t);e!=null&&(e.current=t)}function Rn(...e){return t=>{let r=!1;const n=e.map(o=>{const s=sa(o,t);return!r&&typeof s=="function"&&(r=!0),s});if(r)return()=>{for(let o=0;o<n.length;o++){const s=n[o];typeof s=="function"?s():sa(e[o],null)}}}}function se(...e){return l.useCallback(Rn(...e),e)}var Ef=["a","button","div","form","h2","h3","img","input","label","li","nav","ol","p","select","span","svg","ul"],Q=Ef.reduce((e,t)=>{const r=Oe.createSlot(`Primitive.${t}`),n=l.forwardRef((o,s)=>{const{asChild:a,...c}=o,d=a?r:t;return typeof window<"u"&&(window[Symbol.for("radix-ui")]=!0),i.jsx(d,{...c,ref:s})});return n.displayName=`Primitive.${t}`,{...e,[t]:n}},{});function aa(e,t){e&&hr.flushSync(()=>e.dispatchEvent(t))}function Nf(e,t){return l.useReducer((r,n)=>t[r][n]??r,e)}var _e=e=>{const{present:t,children:r}=e,n=Tf(t),o=typeof r=="function"?r({present:n.isPresent}):l.Children.only(r),s=se(n.ref,Af(o));return typeof r=="function"||n.isPresent?l.cloneElement(o,{ref:s}):null};_e.displayName="Presence";function Tf(e){const[t,r]=l.useState(),n=l.useRef(null),o=l.useRef(e),s=l.useRef("none"),a=e?"mounted":"unmounted",[c,d]=Nf(a,{mounted:{UNMOUNT:"unmounted",ANIMATION_OUT:"unmountSuspended"},unmountSuspended:{MOUNT:"mounted",ANIMATION_END:"unmounted"},unmounted:{MOUNT:"mounted"}});return l.useEffect(()=>{const f=Ar(n.current);s.current=c==="mounted"?f:"none"},[c]),xe(()=>{const f=n.current,u=o.current;if(u!==e){const m=s.current,v=Ar(f);e?d("MOUNT"):v==="none"||(f==null?void 0:f.display)==="none"?d("UNMOUNT"):d(u&&m!==v?"ANIMATION_OUT":"UNMOUNT"),o.current=e}},[e,d]),xe(()=>{if(t){let f;const u=t.ownerDocument.defaultView??window,p=v=>{const h=Ar(n.current).includes(CSS.escape(v.animationName));if(v.target===t&&h&&(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)})}},m=v=>{v.target===t&&(s.current=Ar(n.current))};return t.addEventListener("animationstart",m),t.addEventListener("animationcancel",p),t.addEventListener("animationend",p),()=>{u.clearTimeout(f),t.removeEventListener("animationstart",m),t.removeEventListener("animationcancel",p),t.removeEventListener("animationend",p)}}else d("ANIMATION_END")},[t,d]),{isPresent:["mounted","unmountSuspended"].includes(c),ref:l.useCallback(f=>{n.current=f?getComputedStyle(f):null,r(f)},[])}}function Ar(e){return(e==null?void 0:e.animationName)||"none"}function Af(e){var n,o;let t=(n=Object.getOwnPropertyDescriptor(e.props,"ref"))==null?void 0:n.get,r=t&&"isReactWarning"in t&&t.isReactWarning;return r?e.ref:(t=(o=Object.getOwnPropertyDescriptor(e,"ref"))==null?void 0:o.get,r=t&&"isReactWarning"in t&&t.isReactWarning,r?e.props.ref:e.props.ref||e.ref)}var Pf=l[" useId ".trim().toString()]||(()=>{}),_f=0;function He(e){const[t,r]=l.useState(Pf());return xe(()=>{r(n=>n??String(_f++))},[e]),t?`radix-${t}`:""}var Pr="Collapsible",[If,Uw]=Ue(Pr),[kf,Kn]=If(Pr),ia=l.forwardRef((e,t)=>{const{__scopeCollapsible:r,open:n,defaultOpen:o,disabled:s,onOpenChange:a,...c}=e,[d,f]=st({prop:n,defaultProp:o??!1,onChange:a,caller:Pr});return i.jsx(kf,{scope:r,disabled:s,contentId:He(),open:d,onOpenToggle:l.useCallback(()=>f(u=>!u),[f]),children:i.jsx(Q.div,{"data-state":qn(d),"data-disabled":s?"":void 0,...c,ref:t})})});ia.displayName=Pr;var ca="CollapsibleTrigger",la=l.forwardRef((e,t)=>{const{__scopeCollapsible:r,...n}=e,o=Kn(ca,r);return i.jsx(Q.button,{type:"button","aria-controls":o.contentId,"aria-expanded":o.open||!1,"data-state":qn(o.open),"data-disabled":o.disabled?"":void 0,disabled:o.disabled,...n,ref:t,onClick:U(e.onClick,o.onOpenToggle)})});la.displayName=ca;var Gn="CollapsibleContent",Of=l.forwardRef((e,t)=>{const{forceMount:r,...n}=e,o=Kn(Gn,e.__scopeCollapsible);return i.jsx(_e,{present:r||o.open,children:({present:s})=>i.jsx(Mf,{...n,ref:t,present:s})})});Of.displayName=Gn;var Mf=l.forwardRef((e,t)=>{const{__scopeCollapsible:r,present:n,children:o,...s}=e,a=Kn(Gn,r),[c,d]=l.useState(n),f=l.useRef(null),u=se(t,f),p=l.useRef(0),m=p.current,v=l.useRef(0),g=v.current,h=a.open||c,b=l.useRef(h),w=l.useRef(void 0);return l.useEffect(()=>{const y=requestAnimationFrame(()=>b.current=!1);return()=>cancelAnimationFrame(y)},[]),xe(()=>{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(n)}},[a.open,n]),i.jsx(Q.div,{"data-state":qn(a.open),"data-disabled":a.disabled?"":void 0,id:a.contentId,hidden:!h,...s,ref:u,style:{"--radix-collapsible-content-height":m?`${m}px`:void 0,"--radix-collapsible-content-width":g?`${g}px`:void 0,...e.style},children:h&&o})});function qn(e){return e?"open":"closed"}var Df=ia;const da=Df,ua=la;function Yt({content:e,className:t=""}){const r=T.useMemo(()=>({table:({node:f,className:u,...p})=>i.jsx("div",{className:"max-w-full",children:i.jsx("table",{...p,className:A("w-full table-fixed border-collapse break-words",u)})}),th:({node:f,className:u,...p})=>i.jsx("th",{...p,className:A("break-words whitespace-normal border-b border-border/60 px-3 py-2 text-left align-top",u)}),td:({node:f,className:u,...p})=>i.jsx("td",{...p,className:A("break-words whitespace-normal border-b border-border/30 px-3 py-2 align-top",u)}),pre:({node:f,className:u,...p})=>i.jsx("pre",{...p,className:A("whitespace-pre-wrap break-words",u)}),code:({node:f,className:u,children:p,...m})=>{const{inline:v,...g}=m;return v?i.jsx("code",{...g,className:A("break-words whitespace-normal",u),children:p}):i.jsx("code",{...g,className:A("block break-words whitespace-pre-wrap",u),children:p})}}),[]),n=A("prose prose-sm max-w-none break-words dark:prose-invert leading-relaxed","prose-headings:break-words prose-p:break-words prose-li:break-words prose-td:break-words prose-th:break-words","prose-a:break-all prose-blockquote:break-words prose-strong:break-words prose-em:break-words","prose-code:break-words 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",t);return i.jsx("div",{className:n,style:{wordBreak:"break-word",overflowWrap:"anywhere"},children:i.jsx($d,{remarkPlugins:[Bd],components:r,children:e})})}const _r="prose prose-sm max-w-none break-words dark:prose-invert prose-headings:break-words prose-p:break-words prose-li:break-words prose-td:break-words prose-th:break-words prose-a:break-all prose-code:break-words prose-blockquote:break-words";function Lf({className:e}){const[t,r]=T.useState(0);return T.useEffect(()=>{const n=setInterval(()=>r(o=>(o+1)%4),500);return()=>clearInterval(n)},[]),i.jsxs("span",{"aria-live":"polite",className:A("inline-block text-xs opacity-70 ml-1",e),children:["Is thinking",".".repeat(t)]})}function fa({message:e,messageIndex:t,isStreamingMessage:r=!1,streamingDebounceMs:n=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:m=200,customStyles:v={},checkpointBranches:g=[],currentCheckpointId:h,onSwitchToCheckpoint:b,onReturnToMainThread:w,temporalNavigation:y,onNavigateToPreviousBranch:x,onNavigateToNextBranch:C,onEdit:E,onRegenerate:O,onEditFromCheckpoint:N,onCancelEdit:L,onCopy:D}){const[$,R]=T.useState(!1),[X,B]=T.useState(!1),[M,J]=T.useState(!1),[F,H]=T.useState(!1),P=d==="phone"||d==="half-screen",_=e.role,G=_==="tool",j=T.useMemo(()=>{switch(_){case"user":return"text-[hsl(var(--chat-bubble-user-text))]";case"assistant":return"text-[hsl(var(--chat-bubble-ai-text))]";case"tool":return"text-secondary-foreground";case"system":return"text-muted-foreground";default:return"text-foreground"}},[_]),Z=T.useMemo(()=>Ff(e.content),[e.content]),I=T.useMemo(()=>Wf(e.content),[e.content]),W=T.useMemo(()=>e.content.filter(ee=>ee.type==="image_url"),[e.content]),ge=T.useMemo(()=>e.content.filter(ee=>ee.type==="file"),[e.content]),he=Rf(Z,r?n:0),z=async()=>{try{const ee=G?Pt(e.content):Z;await navigator.clipboard.writeText(ee),R(!0),setTimeout(()=>R(!1),2e3),D==null||D(ee)}catch(ee){console.error("Failed to copy:",ee)}},ce=()=>{if(!E)return;const ee=G?Pt(e.content):Z;E(e.id,ee)},pe=()=>O==null?void 0:O(t),le=()=>{const ye=A(P?"h-3 w-3":"h-4 w-4","opacity-60 flex-shrink-0",j);switch(_){case"user":return i.jsx(q.User,{className:ye});case"assistant":return i.jsx(q.Bot,{className:ye});case"tool":return i.jsx(q.Wrench,{className:ye});default:return i.jsx(q.Bot,{className:ye})}},de=()=>{const ee="group relative mb-4 flex w-full";switch(_){case"user":return A(ee,"justify-end");case"assistant":case"tool":case"system":return A(ee,"justify-start");default:return ee}},ue=()=>{const ee=A("rounded-lg px-4 py-3 relative transition-all duration-200 min-w-0 max-w-full break-words",P&&"px-3 py-2 text-sm");switch(_){case"user":return A(ee,"w-full md:max-w-[95%]","bg-[hsl(var(--chat-bubble-user))] text-[hsl(var(--chat-bubble-user-text))]","border border-transparent");case"assistant":return A(ee,"w-full md:max-w-[95%]","bg-[hsl(var(--chat-bubble-ai))] text-[hsl(var(--chat-bubble-ai-text))]","border border-border/60 dark:border-border/40");case"tool":return A(ee,"w-full md:max-w-[95%] bg-secondary/50 text-secondary-foreground border border-dashed");case"system":return A(ee,"w-full md:max-w-[85%] bg-accent/40 text-muted-foreground border");default:return ee}},V=ee=>{if(!ee)return"";try{return new Date(ee).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"})}catch{return""}},K=()=>{if(e.model==="reflection"){const ae=Z.trim(),fe=Xn(ae);if(fe&&typeof fe=="object")return i.jsx(Kf,{data:fe})}if(G&&I.name==="get_issues"){const ae=e.content.find(ot=>ot.type==="tool_result"),fe=(ae==null?void 0:ae.output)??Pt(e.content),Ne=ha(fe);if(Ne)return i.jsx(Gf,{issues:Ne})}if(G&&!M){const ae=Pt(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 text-current",P&&"text-[10px]"),children:i.jsxs("span",{className:"truncate max-w-full text-current",children:[ae,ae.length>=80?"…":""]})})}if(G&&f){const ae=Pt(e.content),fe=ae.length>u;return i.jsx(da,{open:X,onOpenChange:B,children:i.jsxs("div",{className:"font-mono text-sm text-current",children:[i.jsx("pre",{className:A("whitespace-pre-wrap break-words text-current",P&&"text-xs"),children:fe&&!X?ae.substring(0,u)+"...":ae}),fe&&i.jsx(ua,{asChild:!0,children:i.jsx(me,{variant:"ghost",size:"sm",className:"h-6 text-xs text-current",children:X?i.jsxs(i.Fragment,{children:[i.jsx(q.ChevronUp,{className:"h-3 w-3 mr-1"}),"Show less"]}):i.jsxs(i.Fragment,{children:[i.jsx(q.ChevronDown,{className:"h-3 w-3 mr-1"}),"Show more (",ae.length-u," chars)"]})})})]})})}if(G&&M&&!f){const ae=zf(e.content);if(ae&&$f(ae))return i.jsx(Yt,{content:ae.trim()});const fe=Pt(e.content);return i.jsx("div",{className:"font-mono text-sm text-current",children:i.jsx("pre",{className:A("whitespace-pre-wrap break-words text-current",P&&"text-xs"),children:fe})})}const ee=W.length>0&&_!=="tool",ye=ge.length>0&&_!=="tool";return i.jsxs("div",{children:[r?i.jsxs("div",{className:"relative",children:[(()=>{const ae=Xn(he);return ae!==null?i.jsx(pa,{data:ae}):i.jsx(Yt,{content:Uf(Bf(he))})})(),i.jsx(Lf,{className:A(j,P?"text-xs":"text-sm")})]}):(()=>{const ae=Xn(Z.trim());if(ae!==null)return i.jsx(pa,{data:ae});if(_==="user"&&p){const fe=Z.trim();if(fe.length>m)return i.jsxs(da,{open:F,onOpenChange:H,children:[i.jsx("div",{className:A("text-sm text-[hsl(var(--chat-bubble-user-text))]",P&&"text-xs"),children:F?i.jsx(Yt,{content:fe}):i.jsxs("pre",{className:A("font-sans whitespace-pre-wrap break-words bg-transparent p-0 m-0 text-[hsl(var(--chat-bubble-user-text))]",P&&"text-xs"),children:[fe.substring(0,m),"..."]})}),i.jsx(ua,{asChild:!0,children:i.jsx(me,{variant:"ghost",size:"sm",className:"h-6 text-xs !text-[hsl(var(--chat-bubble-user-text))]",children:F?i.jsxs(i.Fragment,{children:[i.jsx(q.ChevronUp,{className:"h-3 w-3 mr-1"})," Show less"]}):i.jsxs(i.Fragment,{children:[i.jsx(q.ChevronDown,{className:"h-3 w-3 mr-1"})," Show more (",fe.length-m," chars)"]})})})]})}return i.jsx(Yt,{content:Z.trim()})})(),ee&&i.jsx("div",{className:"mt-2 grid grid-cols-2 gap-2",children:W.map((ae,fe)=>i.jsxs("div",{className:"relative border rounded overflow-hidden",children:[i.jsx("img",{src:ae.url,alt:ae.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(q.Image,{className:"h-3 w-3"}),i.jsx("span",{children:"image"})]})]},fe))}),ye&&i.jsx("div",{className:"mt-2 flex flex-wrap gap-2",children:ge.map((ae,fe)=>{const Ne=ae,ot=Ne.name||"file";return i.jsxs("a",{href:Ne.url,download:ot,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:ot,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:ot})]},fe)})})]})},be=T.useMemo(()=>Vf(e),[e]);return T.useMemo(()=>jf(e,h),[e,h]),i.jsx("div",{className:A(de(),v.container),children:i.jsxs("div",{className:A(ue(),v.content),children:[(a||c||G)&&i.jsxs("div",{className:A("flex items-center justify-between mb-2 pb-2 border-b border-current/10",P&&"mb-1 pb-1",j,v.header),children:[i.jsxs("div",{className:"flex items-center gap-2",children:[le(),c&&be&&i.jsx("span",{className:A("font-medium",P?"text-xs":"text-sm"),children:be}),G&&I.name&&i.jsxs(oa,{variant:"outline",className:A("text-xs flex items-center gap-1 cursor-pointer",j,"border border-current/40",P&&"text-xs h-4"),onClick:()=>J(ee=>!ee),children:[i.jsx("span",{children:I.name}),i.jsx("span",{className:"inline-flex items-center",children:M?i.jsx(q.ChevronUp,{className:"h-3 w-3"}):i.jsx(q.ChevronDown,{className:"h-3 w-3"})})]}),G&&!I.name&&i.jsx(me,{variant:"ghost",size:"sm",className:A("h-6 px-1",j,"hover:bg-foreground/10"),onClick:()=>J(ee=>!ee),children:i.jsxs("span",{className:"text-xs flex items-center gap-1",children:["Tool Output ",M?i.jsx(q.ChevronUp,{className:"h-3 w-3"}):i.jsx(q.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",j,P&&"text-xs"),children:V(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(me,{variant:"ghost",size:"sm",onClick:z,className:A("h-6 w-6 p-0 hover:bg-foreground/10",j,P&&"h-5 w-5"),children:i.jsx(q.Copy,{className:A($?"text-success":j,P?"h-3 w-3":"h-4 w-4")})}),_==="user"&&E&&i.jsx(me,{variant:"ghost",size:"sm",onClick:ce,className:A("h-6 w-6 p-0 hover:bg-foreground/10",j,P&&"h-5 w-5"),children:i.jsx(q.Edit,{className:A(j,P?"h-3 w-3":"h-4 w-4")})}),_==="assistant"&&O&&i.jsx(me,{variant:"ghost",size:"sm",onClick:pe,className:A("h-6 w-6 p-0 hover:bg-foreground/10",j,P&&"h-5 w-5"),children:i.jsx(q.RotateCcw,{className:A(j,P?"h-3 w-3":"h-4 w-4")})})]})]})]}),i.jsx("div",{className:"relative",children:K()}),G&&M&&(I.toolCallId||I.name)&&i.jsxs("div",{className:A("mt-2 pt-2 border-t border-current/10 text-xs opacity-60",P&&"text-xs"),children:[I.name&&i.jsxs("div",{children:["Function: ",I.name]}),I.toolCallId&&i.jsxs("div",{children:["Call ID: ",I.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(q.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(me,{variant:"ghost",size:"sm",className:A("h-6 w-6 p-0",j),disabled:!y.canGoBack,onClick:()=>x==null?void 0:x(),title:"Go back to previous branch",children:i.jsx(q.ChevronLeft,{className:A("h-3 w-3",j)})}),i.jsx(me,{variant:"ghost",size:"sm",className:A("h-6 w-6 p-0",j),disabled:!y.canGoForward,onClick:()=>C==null?void 0:C(),title:"Go forward to next branch",children:i.jsx(q.ChevronRight,{className:A("h-3 w-3",j)})})]})]}),!(a||c||G)&&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(me,{variant:"ghost",size:"sm",onClick:z,className:A("h-6 w-6 p-0 hover:bg-background/50 text-current",P&&"h-5 w-5"),children:i.jsx(q.Copy,{className:A($?"text-success":"text-current",P?"h-3 w-3":"h-4 w-4")})}),_==="user"&&E&&i.jsx(me,{variant:"ghost",size:"sm",onClick:ce,className:A("h-6 w-6 p-0 hover:bg-background/50 text-current",P&&"h-5 w-5"),children:i.jsx(q.Edit,{className:A("text-current",P?"h-3 w-3":"h-4 w-4")})}),_==="assistant"&&O&&i.jsx(me,{variant:"ghost",size:"sm",onClick:pe,className:A("h-6 w-6 p-0 hover:bg-background/50 text-current",P&&"h-5 w-5"),children:i.jsx(q.RotateCcw,{className:A("text-current",P?"h-3 w-3":"h-4 w-4")})})]})]})})}function Ff(e){const t=e.filter(r=>r.type==="text").map(r=>r.text).join("");return t||JSON.stringify(e)}function $f(e){return e.includes(`
10
10
  `)||e.includes("```")||/[-*] /.test(e)||/#+\s/.test(e)}function Bf(e){let t=e;try{(t.match(/```/g)||[]).length%2===1&&(t+="\n```"),(t.replace(/```[\s\S]*?```/g,"").match(new RegExp("(?<!`)`(?!`)","g"))||[]).length%2===1&&(t+="`")}catch{}return t}function Uf(e){let t=e;try{const r=[],n=[],o="\0F",s="\0I";let a=t.replace(/```[\s\S]*?```/g,c=>(r.push(c),`${o}${r.length-1}\0`));a=a.replace(/`[^`]*`/g,c=>(n.push(c),`${s}${n.length-1}\0`)),a=a.replace(/\b([A-Za-z0-9_&\/-]+)\b(\s+\1\b)+/g,"$1").replace(/\b([A-Za-z0-9_&\/-]+\s+[A-Za-z0-9_&\/-]+)\b(\s+\1\b)+/g,"$1").replace(/([\.,;:!\?\-])\1+/g,"$1").replace(/([:;!\?\)])([A-Za-z])/g,"$1 $2").replace(/\s{3,}/g," "),a=a.replace(/\u0000F(\d+)\u0000/g,(c,d)=>r[Number(d)]??""),a=a.replace(/\u0000I(\d+)\u0000/g,(c,d)=>n[Number(d)]??""),t=a}catch{}return t}function Xn(e){const t=e==null?void 0:e.trim();if(!t||!(t.startsWith("{")||t.startsWith("[")))return null;try{return JSON.parse(t)}catch{return null}}function pa({data:e}){if(Array.isArray(e))return e.every(r=>r===null||["string","number","boolean"].includes(typeof r))?i.jsx("div",{className:_r,children:i.jsx("ul",{className:"list-disc pl-5",children:e.map((r,n)=>i.jsx("li",{children:String(r)},n))})}):i.jsx("pre",{className:"font-mono text-xs bg-background/50 rounded border p-2 whitespace-pre-wrap break-words",children:Jt(e)});if(e&&typeof e=="object"){const t=Array.isArray(e.distilled_facts)?e.distilled_facts:null,r=Array.isArray(e.follow_up_queries)?e.follow_up_queries:null,n=typeof e.is_sufficient=="boolean"?e.is_sufficient:void 0;if(t||r||typeof n=="boolean")return i.jsxs("div",{className:_r,children:[typeof n=="boolean"&&i.jsxs("p",{children:[i.jsx("strong",{children:"Is sufficient:"})," ",n?"Yes":"No"]}),r&&r.length>0&&i.jsxs("div",{children:[i.jsx("p",{children:i.jsx("strong",{children:"Follow-up queries:"})}),i.jsx("ul",{className:"list-disc pl-5",children:r.map((s,a)=>i.jsx("li",{children:String(s)},a))})]}),t&&t.length>0&&i.jsxs("div",{children:[i.jsx("p",{children:i.jsx("strong",{children:"Facts:"})}),i.jsx("ul",{className:"list-disc pl-5",children:t.map((s,a)=>i.jsx("li",{children:String(s)},a))})]})]});const o=Object.entries(e);return i.jsx("div",{className:_r,children:i.jsx("dl",{className:"mt-0",children:o.map(([s,a])=>i.jsxs("div",{className:"mb-1",children:[i.jsxs("dt",{className:"inline font-medium mr-1",children:[s,":"]}),i.jsx("dd",{className:"inline",children:Hf(a)})]},s))})})}return i.jsx("pre",{className:"font-mono text-xs bg-background/50 rounded border p-2 whitespace-pre-wrap break-words",children:Jt(e)})}function Hf(e){if(e==null)return String(e);const t=typeof e;if(t==="string"||t==="number"||t==="boolean")return String(e);if(Array.isArray(e)&&e.every(n=>n===null||["string","number","boolean"].includes(typeof n)))return e.join(", ");try{return i.jsx("code",{className:"text-xs",children:JSON.stringify(e)})}catch{return String(e)}}function Pt(e){const t=e.filter(r=>r.type==="tool_result");if(t.length)try{return t.length===1?Jt(t[0].output):Jt(t.map(r=>({toolCallId:r.toolCallId,output:r.output})))}catch{}return Jt(e)}function zf(e){const t=e.find(n=>n.type==="tool_result");if(!t)return null;const r=t.output;return typeof r=="string"?r:null}function Jt(e){if(typeof e=="string")return e;try{return JSON.stringify(e,null,2)}catch{return String(e)}}function Wf(e){const t=e.find(n=>n.type==="tool_call"),r=e.find(n=>n.type==="tool_result");return{name:t==null?void 0:t.name,toolCallId:(r==null?void 0:r.toolCallId)??(t==null?void 0:t.id)}}function Vf(e){return e.name&&e.name.trim()?e.name:e.model&&e.model.includes("/")?e.model.split("/").pop()||null:e.model||null}function jf(e,t){return e.checkpointId||t||null}function Rf(e,t){const[r,n]=T.useState(e);return T.useEffect(()=>{if(!t){n(e);return}const o=setTimeout(()=>n(e),t);return()=>clearTimeout(o)},[e,t]),r}function Kf({data:e}){return i.jsx("dl",{className:"grid grid-cols-1 gap-y-2",children:Object.entries(e).map(([t,r])=>i.jsxs("div",{className:"flex",children:[i.jsxs("dt",{className:"font-semibold mr-2",children:[t,":"]}),i.jsx("dd",{className:"flex-1 break-words",children:Array.isArray(r)?r.map((n,o)=>i.jsxs("div",{className:"ml-4 break-words",children:["- ",String(n)]},o)):String(r)})]},t))})}function ha(e){if(!e)return null;if(typeof e=="object"&&!Array.isArray(e)){if(e.desirability||e.feasibility||e.viability||e.other)return{desirability:Array.isArray(e.desirability)?e.desirability:[],feasibility:Array.isArray(e.feasibility)?e.feasibility:[],viability:Array.isArray(e.viability)?e.viability:[],other:Array.isArray(e.other)?e.other:[]};if(e.output&&typeof e.output!="object")e=e.output;else if(e.output&&typeof e.output=="object")return ha(e.output)}const t=String(e),r={desirability:[],feasibility:[],viability:[],other:[]};let n=t;const o=Math.min(...["desirability=","feasibility=","viability=","other="].map(a=>{const c=n.toLowerCase().indexOf(a);return c===-1?Number.MAX_SAFE_INTEGER:c}));o!==Number.MAX_SAFE_INTEGER&&(n=n.slice(o));for(const a of Object.keys(r)){const d=new RegExp(a+"\\s*=\\s*\\[([\\s\\S]*?)\\]","i").exec(n);if(!d)continue;const f=d[1],u=/Issue\(([\s\S]*?)\)(?:,|$)/g;let p=null;for(;(p=u.exec(f))!==null;){const m=p[1],v=/title\s*=\s*(['"])([\s\S]*?)\1/.exec(m),g=/description\s*=\s*(['"])([\s\S]*?)\1/.exec(m),h=v?v[2].trim():"",b=g?g[2].trim():"";r[a].push({title:h,description:b})}}return Object.values(r).some(a=>a.length>0)?r:null}function Gf({issues:e}){const t=[{key:"desirability",title:"Desirability"},{key:"feasibility",title:"Feasibility"},{key:"viability",title:"Viability"},{key:"other",title:"Other"}];return i.jsx("div",{className:_r,children:t.map(r=>{const n=e[r.key];return!n||!n.length?null:i.jsxs("div",{className:"mb-4",children:[i.jsxs("h4",{className:"font-semibold mb-2",children:[r.title," (",n.length,")"]}),i.jsx("ol",{className:"list-decimal pl-5 space-y-2",children:n.map((o,s)=>i.jsxs("li",{children:[i.jsx("div",{className:"font-medium",children:o.title}),i.jsx("div",{className:"text-sm text-muted-foreground",children:o.description})]},s))})]},r.key)})})}const _t=1e4;function qf(e){if(typeof e!="string")return String(e);const t=[/<script[^>]*>.*?<\/script>/gi,/<iframe[^>]*>.*?<\/iframe>/gi,/javascript:/gi,/vbscript:/gi,/on\w+\s*=/gi,/<object[^>]*>.*?<\/object>/gi,/<embed[^>]*>.*?<\/embed>/gi,/<form[^>]*>.*?<\/form>/gi];let r=e;for(const o of t)r=r.replace(o,"");return/<[^>]+>/.test(r)&&!/<(?!\/?(?:code|strong|em|b|i|br|p|ul|ol|li|h[1-6])\b)[^>]+>/i.test(r)?r.replace(/<code>(.*?)<\/code>/gi,"`$1`").replace(/<strong>(.*?)<\/strong>/gi,"**$1**").replace(/<b>(.*?)<\/b>/gi,"**$1**").replace(/<em>(.*?)<\/em>/gi,"*$1*").replace(/<i>(.*?)<\/i>/gi,"*$1*").replace(/<br\s*\/?>/gi,`
11
11
  `).replace(/<p>(.*?)<\/p>/gi,`$1
12
12
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "teodor-new-chat-ui",
3
- "version": "2.0.39",
3
+ "version": "2.0.40",
4
4
  "description": "React chat UI components with streaming support, tool calls, and modern design",
5
5
  "main": "dist/index.umd.js",
6
6
  "module": "dist/index.esm.js",