opencami 1.8.8 → 1.8.9

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.
Files changed (61) hide show
  1. package/dist/client/assets/{CSPContext-nHSyQniZ.js → CSPContext-DI-5GAnQ.js} +1 -1
  2. package/dist/client/assets/{DirectionContext-B1cuzwIr.js → DirectionContext-CrIsc5n9.js} +1 -1
  3. package/dist/client/assets/_sessionKey-B4NZmxf3.js +21 -0
  4. package/dist/client/assets/agents-bptidK8z.js +2 -0
  5. package/dist/client/assets/{agents-screen-DpNSh5Ok.js → agents-screen-6qdnPmx2.js} +1 -1
  6. package/dist/client/assets/bots-BWpbaQ-E.js +2 -0
  7. package/dist/client/assets/{bots-screen-Qh_IK9hC.js → bots-screen-BTKCOohV.js} +1 -1
  8. package/dist/client/assets/{button-DdG8c-XQ.js → button-8ab4wOwy.js} +1 -1
  9. package/dist/client/assets/{composite-Cx-QHT9o.js → composite-B2qsrzf3.js} +1 -1
  10. package/dist/client/assets/{connect-CSbeSBTn.js → connect-B3_p7C4I.js} +1 -1
  11. package/dist/client/assets/dashboard-BtClHYpn.js +1 -0
  12. package/dist/client/assets/{event-Dwf9IDxK.js → event-DG3RKJz8.js} +1 -1
  13. package/dist/client/assets/{file-explorer-screen-DzDX4HcB.js → file-explorer-screen-Djl8x-8P.js} +1 -1
  14. package/dist/client/assets/files-CjbCJDgC.js +2 -0
  15. package/dist/client/assets/{follow-up-suggestions-BYWq-d8P.js → follow-up-suggestions-BSCMXRXh.js} +1 -1
  16. package/dist/client/assets/{index-BxsgifDH.js → index-BXiha-Vz.js} +1 -1
  17. package/dist/client/assets/{index-B551ln24.js → index-CtlYu8Ug.js} +1 -1
  18. package/dist/client/assets/{keyboard-shortcuts-dialog-BX-hH4Wf.js → keyboard-shortcuts-dialog-HAufCn9C.js} +1 -1
  19. package/dist/client/assets/{main-DBmooBKx.js → main-CQKtcNr3.js} +2 -2
  20. package/dist/client/assets/{markdown-Bpat4kTr.js → markdown-DFJF-FsV.js} +1 -1
  21. package/dist/client/assets/memory-DnJOmcwU.js +2 -0
  22. package/dist/client/assets/{memory-screen-1DgDLyZf.js → memory-screen-Bm4NMAnU.js} +1 -1
  23. package/dist/client/assets/{menu-ByR1BVmq.js → menu-D26Vmgxl.js} +1 -1
  24. package/dist/client/assets/{opencami-logo-BV1uPYe6.js → opencami-logo-BSed2Wez.js} +1 -1
  25. package/dist/client/assets/{popupStateMapping-CGDLUl5Y.js → popupStateMapping-DkI2OCkW.js} +1 -1
  26. package/dist/client/assets/{proxy-DYrSkM35.js → proxy-CHQ-VCN1.js} +1 -1
  27. package/dist/client/assets/{react-dSDkXQu6.js → react-WkSlhZJd.js} +1 -1
  28. package/dist/client/assets/{search-dialog-B3XJLq-O.js → search-dialog-CCl4d0Pi.js} +1 -1
  29. package/dist/client/assets/{search-sources-badge-CTd0gLuz.js → search-sources-badge-Du8KpUEb.js} +1 -1
  30. package/dist/client/assets/{session-export-dialog-Cib97JLm.js → session-export-dialog-io9FvLKq.js} +1 -1
  31. package/dist/client/assets/{settings-dialog-B4NLq1ZS.js → settings-dialog-B93qswor.js} +1 -1
  32. package/dist/client/assets/skills-BNDGnHwM.js +2 -0
  33. package/dist/client/assets/{skills-panel-Cj7yHGbX.js → skills-panel-CVh1I-7D.js} +1 -1
  34. package/dist/client/assets/{switch-kXs1I0oW.js → switch-CSnzINDW.js} +1 -1
  35. package/dist/client/assets/{tabs-B6GW7TBf.js → tabs-CWfn44FL.js} +1 -1
  36. package/dist/client/assets/{thinking-DTP9JDQl.js → thinking-BmoLlbFC.js} +1 -1
  37. package/dist/client/assets/{tooltip-CtHpm-sQ.js → tooltip-CSGMH2t4.js} +1 -1
  38. package/dist/client/assets/{use-file-explorer-state-C-D2CShe.js → use-file-explorer-state-BYVzjwPA.js} +1 -1
  39. package/dist/client/assets/{useBaseUiId-Ckx_aJky.js → useBaseUiId-DiwX_3so.js} +1 -1
  40. package/dist/client/assets/{useCompositeItem-CkvfeGmG.js → useCompositeItem-UPIPwR9H.js} +1 -1
  41. package/dist/client/assets/{useControlled-8D4PSDAL.js → useControlled-CT2hRlcU.js} +1 -1
  42. package/dist/client/assets/{useMutation-DckvFKPC.js → useMutation-rx8UH99I.js} +1 -1
  43. package/dist/client/assets/{useQuery-CtUiG53w.js → useQuery-Boaa6oF3.js} +1 -1
  44. package/dist/server/assets/{_sessionKey-LV6xK9IM.js → _sessionKey-B6iYeyCS.js} +342 -257
  45. package/dist/server/assets/{_tanstack-start-manifest_v-qVhiIEVc.js → _tanstack-start-manifest_v-C9chPgNH.js} +1 -1
  46. package/dist/server/assets/{dashboard-GCKodTiJ.js → dashboard-UYRCu_mQ.js} +19 -3
  47. package/dist/server/assets/{follow-up-suggestions-CSSc4PDe.js → follow-up-suggestions-mzRQIB0k.js} +2 -2
  48. package/dist/server/assets/{index-DMKS4aeI.js → index-COElhwGA.js} +1 -1
  49. package/dist/server/assets/{router-Cr2xCvGA.js → router-BqLGFd4L.js} +3 -3
  50. package/dist/server/assets/{search-dialog-DR6zBnui.js → search-dialog-CmI7naPN.js} +2 -2
  51. package/dist/server/assets/{settings-dialog-DEMlCMCP.js → settings-dialog-BZ67gr9N.js} +2 -2
  52. package/dist/server/assets/{thinking-BpAc3itF.js → thinking-CA8PSwKJ.js} +2 -2
  53. package/dist/server/server.js +2 -2
  54. package/package.json +2 -2
  55. package/dist/client/assets/_sessionKey-CNw4O2rY.js +0 -19
  56. package/dist/client/assets/agents-C6Ev94B1.js +0 -2
  57. package/dist/client/assets/bots-B2_u-OmP.js +0 -2
  58. package/dist/client/assets/dashboard-DA1fTRcH.js +0 -1
  59. package/dist/client/assets/files-PsZnGOUx.js +0 -2
  60. package/dist/client/assets/memory-Bs8hOoEv.js +0 -2
  61. package/dist/client/assets/skills-pueagQNc.js +0 -2
@@ -1 +1 @@
1
- import{r as t}from"./main-DBmooBKx.js";const e=t.createContext(void 0),o={disableStyleElements:!1};function s(){return t.useContext(e)??o}export{s as u};
1
+ import{r as t}from"./main-CQKtcNr3.js";const e=t.createContext(void 0),o={disableStyleElements:!1};function s(){return t.useContext(e)??o}export{s as u};
@@ -1 +1 @@
1
- import{r as l}from"./main-DBmooBKx.js";const E=["top","right","bottom","left"],p=Math.min,h=Math.max,L=Math.round,k=Math.floor,q=t=>({x:t,y:t}),x={left:"right",right:"left",bottom:"top",top:"bottom"},d={start:"end",end:"start"};function R(t,e,n){return h(t,p(e,n))}function T(t,e){return typeof t=="function"?t(e):t}function m(t){return t.split("-")[0]}function g(t){return t.split("-")[1]}function b(t){return t==="x"?"y":"x"}function A(t){return t==="y"?"height":"width"}const P=new Set(["top","bottom"]);function y(t){return P.has(m(t))?"y":"x"}function M(t){return b(y(t))}function v(t,e,n){n===void 0&&(n=!1);const s=g(t),i=M(t),o=A(i);let r=i==="x"?s===(n?"end":"start")?"right":"left":s==="start"?"bottom":"top";return e.reference[o]>e.floating[o]&&(r=a(r)),[r,a(r)]}function z(t){const e=a(t);return[c(t),e,c(e)]}function c(t){return t.replace(/start|end/g,e=>d[e])}const u=["left","right"],f=["right","left"],O=["top","bottom"],S=["bottom","top"];function C(t,e,n){switch(t){case"top":case"bottom":return n?e?f:u:e?u:f;case"left":case"right":return e?O:S;default:return[]}}function B(t,e,n,s){const i=g(t);let o=C(m(t),n==="start",s);return i&&(o=o.map(r=>r+"-"+i),e&&(o=o.concat(o.map(c)))),o}function a(t){return t.replace(/left|right|bottom|top/g,e=>x[e])}function w(t){return{top:0,right:0,bottom:0,left:0,...t}}function F(t){return typeof t!="number"?w(t):{top:t,right:t,bottom:t,left:t}}function G(t){const{x:e,y:n,width:s,height:i}=t;return{width:s,height:i,top:n,left:e,right:e+s,bottom:n+i,x:e,y:n}}const j=l.createContext(void 0);function H(){return l.useContext(j)?.direction??"ltr"}export{y as a,a as b,z as c,B as d,T as e,k as f,m as g,v as h,g as i,h as j,M as k,F as l,p as m,G as n,A as o,R as p,b as q,L as r,E as s,q as t,H as u};
1
+ import{r as l}from"./main-CQKtcNr3.js";const E=["top","right","bottom","left"],p=Math.min,h=Math.max,L=Math.round,k=Math.floor,q=t=>({x:t,y:t}),x={left:"right",right:"left",bottom:"top",top:"bottom"},d={start:"end",end:"start"};function R(t,e,n){return h(t,p(e,n))}function T(t,e){return typeof t=="function"?t(e):t}function m(t){return t.split("-")[0]}function g(t){return t.split("-")[1]}function b(t){return t==="x"?"y":"x"}function A(t){return t==="y"?"height":"width"}const P=new Set(["top","bottom"]);function y(t){return P.has(m(t))?"y":"x"}function M(t){return b(y(t))}function v(t,e,n){n===void 0&&(n=!1);const s=g(t),i=M(t),o=A(i);let r=i==="x"?s===(n?"end":"start")?"right":"left":s==="start"?"bottom":"top";return e.reference[o]>e.floating[o]&&(r=a(r)),[r,a(r)]}function z(t){const e=a(t);return[c(t),e,c(e)]}function c(t){return t.replace(/start|end/g,e=>d[e])}const u=["left","right"],f=["right","left"],O=["top","bottom"],S=["bottom","top"];function C(t,e,n){switch(t){case"top":case"bottom":return n?e?f:u:e?u:f;case"left":case"right":return e?O:S;default:return[]}}function B(t,e,n,s){const i=g(t);let o=C(m(t),n==="start",s);return i&&(o=o.map(r=>r+"-"+i),e&&(o=o.concat(o.map(c)))),o}function a(t){return t.replace(/left|right|bottom|top/g,e=>x[e])}function w(t){return{top:0,right:0,bottom:0,left:0,...t}}function F(t){return typeof t!="number"?w(t):{top:t,right:t,bottom:t,left:t}}function G(t){const{x:e,y:n,width:s,height:i}=t;return{width:s,height:i,top:n,left:e,right:e+s,bottom:n+i,x:e,y:n}}const j=l.createContext(void 0);function H(){return l.useContext(j)?.direction??"ltr"}export{y as a,a as b,z as c,B as d,T as e,k as f,m as g,v as h,g as i,h as j,M as k,F as l,p as m,G as n,A as o,R as p,b as q,L as r,E as s,q as t,H as u};
@@ -0,0 +1,21 @@
1
+ const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/settings-dialog-B93qswor.js","assets/main-CQKtcNr3.js","assets/react-WkSlhZJd.js","assets/button-8ab4wOwy.js","assets/use-file-explorer-state-BYVzjwPA.js","assets/useBaseUiId-DiwX_3so.js","assets/event-DG3RKJz8.js","assets/popupStateMapping-DkI2OCkW.js","assets/visuallyHidden-COI6QeQH.js","assets/composite-B2qsrzf3.js","assets/switch-CSnzINDW.js","assets/useControlled-CT2hRlcU.js","assets/tabs-CWfn44FL.js","assets/useCompositeItem-UPIPwR9H.js","assets/DirectionContext-CrIsc5n9.js","assets/CSPContext-DI-5GAnQ.js","assets/index-BXiha-Vz.js","assets/useQuery-Boaa6oF3.js","assets/tooltip-CSGMH2t4.js","assets/useMutation-rx8UH99I.js","assets/menu-D26Vmgxl.js","assets/opencami-logo-BSed2Wez.js","assets/proxy-CHQ-VCN1.js","assets/markdown-DFJF-FsV.js","assets/index-T4TOjvD0.js","assets/session-export-dialog-io9FvLKq.js","assets/thinking-BmoLlbFC.js","assets/search-sources-badge-Du8KpUEb.js","assets/follow-up-suggestions-BSCMXRXh.js","assets/keyboard-shortcuts-dialog-HAufCn9C.js","assets/search-dialog-CCl4d0Pi.js"])))=>i.map(i=>d[i]);
2
+ import{r as s,u as mt,j as n,L as Xe,_ as et,d as Lt,w as Xr,a as Br,z as Yr}from"./main-CQKtcNr3.js";import{u as Mt}from"./useQuery-Boaa6oF3.js";import{T as Me,a as Ie,b as Ae,c as De,s as Be,d as Gr,g as vn}from"./tooltip-CSGMH2t4.js";import{C as Vr,c as O,B as we,ac as an,ag as qe,E as qr,H as Z,J as Yn,V as Pt,aj as Jr,ak as Qr,al as Zr,a as Gn,am as es,G as ts,an as ns,l as rs,b as Je,I as ss,ao as os,a3 as is,s as Vt,ap as as,L as ls,aq as cs,A as us,N as ds,Q as fs,X as Vn,x as ms,h as ps,ar as qn,as as hs,p as gs,T as Jn,u as Qn,at as jn,au as ys,av as xs,aw as ws}from"./button-8ab4wOwy.js";import{u as Zn}from"./useMutation-rx8UH99I.js";import{j as bs,k as Ss,l as vs,m as js,n as ks,o as Cs,p as Es,q as Ns,r as Ts,s as er,D as Rs,a as Ms,b as Is,c as As,d as Ds,u as Os}from"./use-file-explorer-state-BYVzjwPA.js";import{d as tr,a as Ge,g as nr,t as Ls,u as Oe,f as Ps,n as _s}from"./useBaseUiId-DiwX_3so.js";import{u as Ks}from"./useControlled-CT2hRlcU.js";import{_ as zs,$ as Us,a0 as kn,t as rr,u as $s,G as Ee,e as Hs,a as It}from"./popupStateMapping-DkI2OCkW.js";import{u as Fs,e as Ws,q as Xs}from"./event-DG3RKJz8.js";import{u as Bs}from"./CSPContext-DI-5GAnQ.js";import{u as sr}from"./DirectionContext-CrIsc5n9.js";import{M as ln,a as cn,b as un,c as Ze}from"./menu-D26Vmgxl.js";import{O as Ys,a as Gs}from"./opencami-logo-BSed2Wez.js";import{m as be,A as Re}from"./proxy-CHQ-VCN1.js";import{M as Vs}from"./markdown-DFJF-FsV.js";import{u as qs,p as or}from"./index-BXiha-Vz.js";import{c as ir}from"./react-WkSlhZJd.js";function qt(e){if(!e)return"main";const t=e.trim();if(t.length===0)return"main";const r=t.split(":"),a=(r[r.length-1]??"").trim();return a.length>0?a:t}const Cn=/^Conversation info \(untrusted metadata\):\s*```(?:json)?\s*[\s\S]*?```\s*/,En=/^Conversation info \(untrusted metadata\):\s*\{[\s\S]*?\}\s*/,Js=/^\[(?:[A-Za-z]{3}\s+)?\d{4}-\d{2}-\d{2}\s+\d{2}:\d{2}\s+GMT[+-]?\d+\]\s*/;function ar(e){let t=e;const r=Cn.test(t),o=!r&&En.test(t);return r?t=t.replace(Cn,""):o&&(t=t.replace(En,"")),(r||o)&&(t=t.replace(Js,"")),t.trim()}function Le(e){const r=(Array.isArray(e.content)?e.content:[]).map(o=>o.type==="text"?String(o.text??""):"").join("").trim();return ar(r)}function Ye(e){return(Array.isArray(e.content)?e.content:[]).filter(r=>r.type==="toolCall")}function Qs(e){if(typeof e=="number"&&Number.isFinite(e))return e<1e12?e*1e3:e;if(typeof e=="string"){const t=Date.parse(e);if(!Number.isNaN(t))return t}return null}function Jt(e){const t=[e.createdAt,e.created_at,e.timestamp,e.time,e.ts];for(const r of t){const o=Qs(r);if(o)return o}return Date.now()}const Zs=["agent:main:main","main"];function Qt(e){return Zs.includes(e)}const eo=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function to(e){if(e.includes(":subagent:")||e.startsWith("agent:codex:")||e.includes(":openai:"))return"subagent";if(e.startsWith("isolated:")||e.includes(":cron:"))return"cron";if(e.startsWith("agent:")&&!e.startsWith("agent:main:"))return"other";if(e.startsWith("agent:main:")){const t=e.slice(11);return eo.test(t)?"webchat":"chat"}return"other"}function no(e){return Array.isArray(e)?e.map(t=>{const r=typeof t.key=="string"&&t.key.trim().length>0?t.key.trim():qt(t.friendlyId??t.key),o=typeof t.friendlyId=="string"&&t.friendlyId.trim().length>0?t.friendlyId.trim():qt(r),a=to(r),i=t,l=typeof i.totalTokens=="number"?i.totalTokens:void 0,c=typeof i.contextTokens=="number"?i.contextTokens:void 0,u=typeof i.status=="string"?i.status:void 0;return{key:r,friendlyId:o,title:typeof t.title=="string"?t.title:void 0,derivedTitle:typeof t.derivedTitle=="string"?t.derivedTitle:void 0,label:typeof t.label=="string"?t.label:void 0,updatedAt:typeof t.updatedAt=="number"?t.updatedAt:void 0,lastMessage:t.lastMessage??null,kind:a,status:u,totalTokens:l,contextTokens:c}}):[]}async function Ke(e){try{const t=await e.json();return t?.error?String(t.error):t?.message?String(t.message):JSON.stringify(t)}catch{try{return await e.text()}catch{return e.statusText||"Request failed"}}}const ro="Missing gateway auth. Set CLAWDBOT_GATEWAY_TOKEN (recommended) or CLAWDBOT_GATEWAY_PASSWORD in the server environment.";function Nn(e){return e.includes(ro)}function Tn(e,t){const r=crypto.randomUUID(),o=`opt-${r}`,a=Date.now(),i=[];if(t&&t.length>0)for(const c of t)c.type==="image"&&c.base64&&i.push({type:"image",source:{type:"base64",media_type:c.file.type,data:c.base64}});return e.trim()?i.push({type:"text",text:e}):t&&t.length>0&&i.push({type:"text",text:""}),{clientId:r,optimisticId:o,optimisticMessage:{role:"user",content:i,__optimisticId:o,clientId:r,status:"sending",timestamp:a}}}const fe={sessions:["chat","sessions"],history:function(t,r){return["chat","history",t,r]}};async function so(){const e=await fetch("/api/sessions");if(!e.ok)throw new Error(await Ke(e));const t=await e.json();return no(t.sessions)}async function oo(e){const t=new URLSearchParams({limit:"200"});e.sessionKey&&t.set("sessionKey",e.sessionKey),e.friendlyId&&t.set("friendlyId",e.friendlyId);const r=await fetch(`/api/history?${t.toString()}`);if(!r.ok)throw new Error(await Ke(r));return await r.json()}async function io(){const e=new AbortController,t=window.setTimeout(()=>e.abort(),2500);try{const r=await fetch("/api/ping",{signal:e.signal});if(!r.ok)throw new Error(await Ke(r));return await r.json()}catch(r){throw r instanceof DOMException&&r.name==="AbortError"?new Error("Gateway check timed out"):r}finally{window.clearTimeout(t)}}function dn(e,t,r,o){const a=fe.history(t,r);e.setQueryData(a,function(l){const c=l,u=Array.isArray(c?.messages)?c.messages:[],d=o(u);return{sessionKey:c?.sessionKey??r,sessionId:c?.sessionId,messages:d}})}function zt(e,t,r,o){dn(e,t,r,function(i){return[...i,o]})}function ao(e,t,r,o,a){const i=`opt-${o}`;dn(e,t,r,function(c){return c.map(u=>u.clientId===o||u.__optimisticId===o||u.__optimisticId===i?a(u):u)})}function lo(e,t,r,o,a){dn(e,t,r,function(l){return l.filter(c=>!(c.clientId===o||c.__optimisticId===o||a&&c.__optimisticId===a))})}function Zt(e,t,r){const o=fe.history(t,r);e.setQueryData(o,{sessionKey:r,messages:[]})}function co(e,t,r,o,a){const i=fe.history(t,r),l=fe.history(o,a),c=e.getQueryData(i);if(!c)return;const u=Array.isArray(c.messages)?c.messages:[];e.setQueryData(l,{sessionKey:a,sessionId:c.sessionId,messages:u}),e.removeQueries({queryKey:i,exact:!0})}function uo(e,t,r,o){e.setQueryData(fe.sessions,function(i){return Array.isArray(i)?i.map(l=>l.key!==t&&l.friendlyId!==r?l:{...l,lastMessage:o}):i})}function fo(e,t,r){e.setQueryData(fe.sessions,function(a){return Array.isArray(a)?a.filter(i=>i.key!==t&&i.friendlyId!==r):a}),e.removeQueries({queryKey:["chat","history",r],exact:!1}),t&&t!==r&&e.removeQueries({queryKey:["chat","history",t],exact:!1})}async function mo(e,t,r,o){e.setQueryData(fe.sessions,function(i){return Array.isArray(i)?i.map(l=>l.key===t||l.friendlyId===r?{...l,label:o}:l):i});try{const a=await fetch("/api/sessions",{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({sessionKey:t,friendlyId:r,label:o})});if(!a.ok){const i=await Ke(a);console.error("[updateSessionLabel] Failed to persist:",i)}}catch(a){console.error("[updateSessionLabel] Network error:",a)}}function po(){const[e,t]=s.useState(!1),[r,o]=s.useState(!1),[a,i]=s.useState(null),[l,c]=s.useState(null),u=s.useCallback(async()=>{if(t(!0),i(null),!(r||l)){o(!0);try{const h=await fetch("/api/paths");if(!h.ok)throw new Error(await Ke(h));const v=await h.json();c({agentId:String(v.agentId??"main"),stateDir:String(v.stateDir??""),sessionsDir:String(v.sessionsDir??""),storePath:String(v.storePath??"")})}catch(h){i(h instanceof Error?h.message:String(h))}finally{o(!1)}}},[l,r]),d=s.useCallback(()=>{u()},[u]),f=s.useCallback(()=>{t(!1)},[]),m=s.useCallback(()=>{if(l?.sessionsDir)try{navigator.clipboard.writeText(l.sessionsDir)}catch{}},[l]),p=s.useCallback(()=>{if(l?.storePath)try{navigator.clipboard.writeText(l.storePath)}catch{}},[l]);return{settingsOpen:e,setSettingsOpen:t,pathsLoading:r,pathsError:a,paths:l,handleOpenSettings:d,closeSettings:f,copySessionsDir:m,copyStorePath:p}}let ke=null,fn=!1,Nt=null;function ho(e){ke=e}function Ut(){return ke!==null}function yt(e){fn=e}function $t(){return fn}function At(){ke=null,fn=!1}function go(e,t){if(ke){if(e&&ke.sessionKey===e){At();return}t&&ke.friendlyId===t&&At()}}function yo(e){Nt={friendlyId:e,at:Date.now()}}function lr(e,t=15e3){return!(!Nt||Nt.friendlyId!==e||Date.now()-Nt.at>t)}function xo(e,t){if(!ke)return null;if(e&&ke.sessionKey===e){const r=ke;return ke=null,r}if(t&&ke.friendlyId===t){const r=ke;return ke=null,r}return null}const wo=8e3,Qe=new Map;function bo(e){e&&Qe.set(e,{id:e,expiresAt:Date.now()+wo})}function So(e){e&&Qe.delete(e)}function vo(e){if(Qe.size===0)return e;const t=Date.now();let r=!1;const o=e.filter(a=>{const i=Qe.get(a.key),l=Qe.get(a.friendlyId);return i&&i.expiresAt<=t||l&&l.expiresAt<=t?(i&&i.expiresAt<=t&&Qe.delete(a.key),l&&l.expiresAt<=t&&Qe.delete(a.friendlyId),!0):i||l?(r=!0,!1):!0});return r?o:e}function jo(){const e=mt(),[t,r]=s.useState(!1),[o,a]=s.useState(null),i=Zn({mutationFn:async function(u){const d=new URLSearchParams;u.sessionKey&&d.set("sessionKey",u.sessionKey),u.friendlyId&&d.set("friendlyId",u.friendlyId);const f=await fetch(`/api/sessions?${d.toString()}`,{method:"DELETE"});if(!f.ok)throw new Error(await Ke(f));return u},onMutate:async function(u){a(null),bo(u.sessionKey||u.friendlyId),go(u.sessionKey,u.friendlyId),await e.cancelQueries({queryKey:fe.sessions});const d=e.getQueryData(fe.sessions);return fo(e,u.sessionKey,u.friendlyId),u.isActive&&(u.sessionKey||u.friendlyId)&&Zt(e,u.friendlyId||u.sessionKey,u.sessionKey||u.friendlyId),{previousSessions:d,isActive:u.isActive}},onError:function(u,d,f){f?.previousSessions&&e.setQueryData(fe.sessions,f.previousSessions),So(d.sessionKey||d.friendlyId),a(u instanceof Error?u.message:String(u))},onSuccess:function(u){u.isActive&&At(),e.invalidateQueries({queryKey:fe.sessions})},onSettled:function(){r(!1)}});return{deleteSession:s.useCallback(async(c,u,d)=>{!c&&!u||(r(!0),await i.mutateAsync({sessionKey:c,friendlyId:u,isActive:d}))},[i]),deleting:t,error:o}}function ko(){const e=mt(),[t,r]=s.useState(!1),[o,a]=s.useState(null),i=Zn({mutationFn:async function(u){const d=await fetch("/api/sessions",{method:"PATCH",headers:{"content-type":"application/json"},body:JSON.stringify({sessionKey:u.sessionKey,label:u.newTitle})});if(!d.ok)throw new Error(await Ke(d));return u},onMutate:async function(u){a(null),await e.cancelQueries({queryKey:fe.sessions});const d=e.getQueryData(fe.sessions);return e.setQueryData(fe.sessions,function(m){return Array.isArray(m)?m.map(p=>p.key!==u.sessionKey?p:{...p,label:u.newTitle,title:u.newTitle}):m}),{previousSessions:d}},onError:function(u,d,f){f?.previousSessions&&e.setQueryData(fe.sessions,f.previousSessions),a(u instanceof Error?u.message:String(u))},onSuccess:function(){e.invalidateQueries({queryKey:fe.sessions})},onSettled:function(){r(!1)}});return{renameSession:s.useCallback(async(c,u)=>{!c||!u.trim()||(r(!0),await i.mutateAsync({sessionKey:c,newTitle:u.trim()}))},[i]),renaming:t,error:o}}function cr(e){return!e.content||!Array.isArray(e.content)?"":e.content.filter(t=>t.type==="text").map(t=>t.text||"").join(`
3
+ `)}function Co(e,t,r){const o=[];o.push(`# Conversation: ${e}`),o.push(`Date: ${r.toLocaleString()}`),o.push("");for(const a of t){const i=a.role||"unknown",l=cr(a);if(l){const c=i==="user"?"User":"Assistant";o.push(`## ${c}`),o.push(""),o.push(l),o.push("")}}return o.join(`
4
+ `)}function Eo(e,t,r){const o={title:e,exportDate:r.toISOString(),messages:t.map(a=>({role:a.role,content:a.content,timestamp:a.timestamp}))};return JSON.stringify(o,null,2)}function No(e,t,r){const o=[];o.push(`Conversation: ${e}`),o.push(`Date: ${r.toLocaleString()}`),o.push("─".repeat(60)),o.push("");for(const a of t){const i=a.role||"unknown",l=cr(a);if(l){const c=i==="user"?"User":"Assistant";o.push(`${c}:`),o.push(l),o.push("")}}return o.join(`
5
+ `)}function To(e,t,r){const o=new Date;let a,i,l;switch(r){case"markdown":a=Co(e,t,o),i=`${Ht(e)}.md`,l="text/markdown";break;case"json":a=Eo(e,t,o),i=`${Ht(e)}.json`,l="application/json";break;case"txt":a=No(e,t,o),i=`${Ht(e)}.txt`,l="text/plain";break;default:throw new Error(`Unsupported format: ${r}`)}Ro(a,i,l)}function Ht(e){return e.replace(/[^a-z0-9-_\s]/gi,"").replace(/\s+/g,"-").toLowerCase().slice(0,50)||"conversation"}function Ro(e,t,r){const o=new Blob([e],{type:r}),a=URL.createObjectURL(o),i=document.createElement("a");i.href=a,i.download=t,document.body.appendChild(i),i.click(),document.body.removeChild(i),URL.revokeObjectURL(a)}function Mo(e){const{children:t,open:r,defaultOpen:o=!1,onOpenChange:a,onOpenChangeComplete:i,actionsRef:l,handle:c,triggerId:u,defaultTriggerId:d=null}=e,f=bs(),m=!!f,p=Vr(()=>c?.store??new Ss({open:r??o,activeTriggerId:u!==void 0?u:d,modal:!0,disablePointerDismissal:!0,nested:m,role:"alertdialog"})).current;p.useControlledProp("open",r,o),p.useControlledProp("activeTriggerId",u,d),p.useSyncedValue("nested",m),p.useContextCallback("onOpenChange",a),p.useContextCallback("onOpenChangeComplete",i);const h=p.useState("payload");vs({store:p,actionsRef:l,parentContext:f?.store.context});const v=s.useMemo(()=>({store:p}),[p]);return n.jsx(js.Provider,{value:v,children:typeof t=="function"?t({payload:h}):t})}function Io({children:e,...t}){return n.jsx(Mo,{...t,children:e})}function Ao({className:e,children:t}){return n.jsxs(ks,{children:[n.jsx(Cs,{className:"fixed inset-0 bg-primary-950/20 transition-all duration-150 data-[state=open]:opacity-100 data-[state=closed]:opacity-0"}),n.jsx(Es,{className:O("fixed left-1/2 top-1/2 -translate-x-1/2 -translate-y-1/2","w-[min(400px,92vw)] rounded-xl border border-primary-200 bg-primary-50 p-0 shadow-xl","transition-all duration-150","data-[state=open]:opacity-100 data-[state=closed]:opacity-0","data-[state=open]:scale-100 data-[state=closed]:scale-95",e),children:t})]})}function Do({className:e,...t}){return n.jsx(Ns,{className:O("text-lg font-medium text-primary-900",e),...t})}function Oo({className:e,...t}){return n.jsx(Ts,{className:O("text-sm text-primary-600",e),...t})}function Lo({className:e,...t}){return n.jsx(er,{render:n.jsx(we,{variant:"outline",className:O(e)}),...t})}function Po({className:e,...t}){return n.jsx(er,{render:n.jsx(we,{variant:"destructive",className:O(e)}),...t})}function _o({open:e,onOpenChange:t,sessionTitle:r,onConfirm:o,onCancel:a}){return n.jsx(Io,{open:e,onOpenChange:t,children:n.jsx(Ao,{children:n.jsxs("div",{className:"p-4",children:[n.jsx(Do,{className:"mb-1",children:"Delete Session"}),n.jsxs(Oo,{className:"mb-4",children:['Are you sure you want to delete "',r,'"? This action cannot be undone.']}),n.jsxs("div",{className:"flex justify-end gap-2",children:[n.jsx(Lo,{onClick:a,children:"Cancel"}),n.jsx(Po,{onClick:o,children:"Delete"})]})]})})})}function Ko({open:e,onOpenChange:t,sessionTitle:r,onSave:o,onCancel:a}){return n.jsx(Rs,{open:e,onOpenChange:t,children:n.jsx(Ms,{children:n.jsxs("div",{className:"p-4",children:[n.jsx(Is,{className:"mb-1",children:"Rename"}),n.jsx(As,{className:"mb-4",children:"Enter a new name for this session."}),n.jsx("input",{type:"text",defaultValue:r,onKeyDown:i=>{i.key==="Enter"&&(i.preventDefault(),o(i.currentTarget.value))},className:"w-full rounded-lg border border-primary-200 bg-primary-50 px-3 py-2 text-sm text-primary-900 outline-none focus:border-primary-400",placeholder:"Session name",autoFocus:!0}),n.jsxs("div",{className:"mt-4 flex justify-end gap-2",children:[n.jsx(Ds,{onClick:a,children:"Cancel"}),n.jsx(we,{onClick:i=>{const l=i.currentTarget.parentElement?.previousElementSibling;o(l.value)},children:"Save"})]})]})})})}function zo(e){const{open:t,defaultOpen:r,onOpenChange:o,disabled:a}=e,i=t!==void 0,[l,c]=Ks({controlled:t,default:r,name:"Collapsible",state:"open"}),{mounted:u,setMounted:d,transitionStatus:f}=zs(l,!0,!0),[m,p]=s.useState(l),[{height:h,width:v},g]=s.useState({height:void 0,width:void 0}),j=tr(),[w,y]=s.useState(),P=w??j,[I,z]=s.useState(!1),[T,J]=s.useState(!1),B=s.useRef(null),H=s.useRef(null),te=s.useRef(null),U=s.useRef(null),S=Us(U,!1),E=Ge(k=>{const R=!l,_=nr(Ls,k.nativeEvent);if(o(R,_),_.isCanceled)return;const A=U.current;H.current==="css-animation"&&A!=null&&A.style.removeProperty("animation-name"),!I&&!T&&(H.current!=null&&H.current!=="css-animation"&&!u&&R&&d(!0),H.current==="css-animation"&&(!m&&R&&p(!0),!u&&R&&d(!0))),c(R),H.current==="none"&&u&&!R&&d(!1)});return Oe(()=>{i&&H.current==="none"&&!T&&!l&&d(!1)},[i,T,l,t,d]),s.useMemo(()=>({abortControllerRef:B,animationTypeRef:H,disabled:a,handleTrigger:E,height:h,mounted:u,open:l,panelId:P,panelRef:U,runOnceAnimationsFinish:S,setDimensions:g,setHiddenUntilFound:z,setKeepMounted:J,setMounted:d,setOpen:c,setPanelIdState:y,setVisible:p,transitionDimensionRef:te,transitionStatus:f,visible:m,width:v}),[B,H,a,E,h,u,l,P,U,S,g,z,J,d,c,p,te,f,m,v])}const ur=s.createContext(void 0);function dr(){const e=s.useContext(ur);if(e===void 0)throw new Error(an(15));return e}let xt=(function(e){return e.open="data-open",e.closed="data-closed",e[e.startingStyle=kn.startingStyle]="startingStyle",e[e.endingStyle=kn.endingStyle]="endingStyle",e})({}),Uo=(function(e){return e.panelOpen="data-panel-open",e})({});const $o={[xt.open]:""},Ho={[xt.closed]:""},Fo={open(e){return e?{[Uo.panelOpen]:""}:null}},Wo={open(e){return e?$o:Ho}},fr={...Wo,...rr},Xo=s.forwardRef(function(t,r){const{render:o,className:a,defaultOpen:i=!1,disabled:l=!1,onOpenChange:c,open:u,...d}=t,f=Ge(c),m=zo({open:u,defaultOpen:i,onOpenChange:f,disabled:l}),p=s.useMemo(()=>({open:m.open,disabled:m.disabled,transitionStatus:m.transitionStatus}),[m.open,m.disabled,m.transitionStatus]),h=s.useMemo(()=>({...m,onOpenChange:f,state:p}),[m,f,p]),v=qe("div",t,{state:p,ref:r,props:d,stateAttributesMapping:fr});return n.jsx(ur.Provider,{value:h,children:v})}),Bo={...Fo,...rr},Yo=s.forwardRef(function(t,r){const{panelId:o,open:a,handleTrigger:i,state:l,disabled:c}=dr(),{className:u,disabled:d=c,id:f,render:m,nativeButton:p=!0,...h}=t,{getButtonProps:v,buttonRef:g}=Ps({disabled:d,focusableWhenDisabled:!0,native:p}),j=s.useMemo(()=>({"aria-controls":a?o:void 0,"aria-expanded":a,onClick:i}),[o,a,i]);return qe("button",t,{state:l,ref:[r,g],props:[j,h,v],stateAttributesMapping:Bo})});let Go=(function(e){return e.disabled="data-disabled",e.orientation="data-orientation",e})({});function Vo(e){const{abortControllerRef:t,animationTypeRef:r,externalRef:o,height:a,hiddenUntilFound:i,keepMounted:l,id:c,mounted:u,onOpenChange:d,open:f,panelRef:m,runOnceAnimationsFinish:p,setDimensions:h,setMounted:v,setOpen:g,setVisible:j,transitionDimensionRef:w,visible:y,width:P}=e,I=s.useRef(!1),z=s.useRef(null),T=s.useRef(f),J=s.useRef(f),B=$s(),H=s.useMemo(()=>r.current==="css-animation"?!y:!f&&!u,[f,u,y,r]),te=Ge(S=>{if(!S)return;if(r.current==null||w.current==null){const R=getComputedStyle(S),_=R.animationName!=="none"&&R.animationName!=="",A=R.transitionDuration!=="0s"&&R.transitionDuration!=="";_&&A||(R.animationName==="none"&&R.transitionDuration!=="0s"?r.current="css-transition":R.animationName!=="none"&&R.transitionDuration==="0s"?r.current="css-animation":r.current="none"),S.getAttribute(Go.orientation)==="horizontal"||R.transitionProperty.indexOf("width")>-1?w.current="width":w.current="height"}if(r.current!=="css-transition")return;(a===void 0||P===void 0)&&(h({height:S.scrollHeight,width:S.scrollWidth}),J.current&&S.style.setProperty("transition-duration","0s"));let E=-1,k=-1;return E=Ee.request(()=>{J.current=!1,k=Ee.request(()=>{setTimeout(()=>{S.style.removeProperty("transition-duration")})})}),()=>{Ee.cancel(E),Ee.cancel(k)}}),U=qr(o,m,te);return Oe(()=>{if(r.current!=="css-transition")return;const S=m.current;if(!S)return;let E=-1;if(t.current!=null&&(t.current.abort(),t.current=null),f){const k={"justify-content":S.style.justifyContent,"align-items":S.style.alignItems,"align-content":S.style.alignContent,"justify-items":S.style.justifyItems};Object.keys(k).forEach(R=>{S.style.setProperty(R,"initial","important")}),!J.current&&!l&&S.setAttribute(xt.startingStyle,""),h({height:S.scrollHeight,width:S.scrollWidth}),E=Ee.request(()=>{Object.entries(k).forEach(([R,_])=>{_===""?S.style.removeProperty(R):S.style.setProperty(R,_)})})}else{if(S.scrollHeight===0&&S.scrollWidth===0)return;h({height:S.scrollHeight,width:S.scrollWidth});const k=new AbortController;t.current=k;const R=k.signal;let _=null;const A=xt.endingStyle;return _=new MutationObserver(X=>{X.some(D=>D.type==="attributes"&&D.attributeName===A)&&(_?.disconnect(),_=null,p(()=>{h({height:0,width:0}),S.style.removeProperty("content-visibility"),v(!1),t.current===k&&(t.current=null)},R))}),_.observe(S,{attributes:!0,attributeFilter:[A]}),()=>{_?.disconnect(),B.cancel(),t.current===k&&(k.abort(),t.current=null)}}return()=>{Ee.cancel(E)}},[t,r,B,i,l,u,f,m,p,h,v]),Oe(()=>{if(r.current!=="css-animation")return;const S=m.current;S&&(z.current=S.style.animationName||z.current,S.style.setProperty("animation-name","none"),h({height:S.scrollHeight,width:S.scrollWidth}),!T.current&&!I.current&&S.style.removeProperty("animation-name"),f?(t.current!=null&&(t.current.abort(),t.current=null),v(!0),j(!0)):(t.current=new AbortController,p(()=>{v(!1),j(!1),t.current=null},t.current.signal)))},[t,r,f,m,p,h,v,j,y]),Fs(()=>{const S=Ee.request(()=>{T.current=!1});return()=>Ee.cancel(S)}),Oe(()=>{if(!i)return;const S=m.current;if(!S)return;let E=-1,k=-1;return f&&I.current&&(S.style.transitionDuration="0s",h({height:S.scrollHeight,width:S.scrollWidth}),E=Ee.request(()=>{I.current=!1,k=Ee.request(()=>{setTimeout(()=>{S.style.removeProperty("transition-duration")})})})),()=>{Ee.cancel(E),Ee.cancel(k)}},[i,f,m,h]),Oe(()=>{const S=m.current;S&&i&&H&&(S.setAttribute("hidden","until-found"),r.current==="css-transition"&&S.setAttribute(xt.startingStyle,""))},[i,H,r,m]),s.useEffect(function(){const E=m.current;if(!E)return;function k(R){I.current=!0,g(!0),d(!0,nr(_s,R))}return E.addEventListener("beforematch",k),()=>{E.removeEventListener("beforematch",k)}},[d,m,g]),s.useMemo(()=>({props:{hidden:H,id:c,ref:U}}),[H,c,U])}let Rn=(function(e){return e.collapsiblePanelHeight="--collapsible-panel-height",e.collapsiblePanelWidth="--collapsible-panel-width",e})({});const qo=s.forwardRef(function(t,r){const{className:o,hiddenUntilFound:a,keepMounted:i,render:l,id:c,...u}=t,{abortControllerRef:d,animationTypeRef:f,height:m,mounted:p,onOpenChange:h,open:v,panelId:g,panelRef:j,runOnceAnimationsFinish:w,setDimensions:y,setHiddenUntilFound:P,setKeepMounted:I,setMounted:z,setPanelIdState:T,setOpen:J,setVisible:B,state:H,transitionDimensionRef:te,visible:U,width:S,transitionStatus:E}=dr(),k=a??!1,R=i??!1;Oe(()=>{if(c)return T(c),()=>{T(void 0)}},[c,T]),Oe(()=>{P(k)},[P,k]),Oe(()=>{I(R)},[I,R]);const{props:_}=Vo({abortControllerRef:d,animationTypeRef:f,externalRef:r,height:m,hiddenUntilFound:k,id:g,keepMounted:R,mounted:p,onOpenChange:h,open:v,panelRef:j,runOnceAnimationsFinish:w,setDimensions:y,setMounted:z,setOpen:J,setVisible:B,transitionDimensionRef:te,visible:U,width:S});Hs({open:v&&E==="idle",ref:j,onComplete(){v&&y({height:void 0,width:void 0})}});const A=s.useMemo(()=>({...H,transitionStatus:E}),[H,E]),X=qe("div",t,{state:A,ref:[r,j],props:[_,{style:{[Rn.collapsiblePanelHeight]:m===void 0?"auto":`${m}px`,[Rn.collapsiblePanelWidth]:S===void 0?"auto":`${S}px`}},u],stateAttributesMapping:fr});return R||k||!R&&p?X:null});function en(e){return n.jsx(Xo,{...e})}function tn({className:e,...t}){return n.jsx(Yo,{className:O("group inline-flex items-center gap-1.5 rounded-md px-2 py-1 text-left text-xs font-medium text-primary-500 transition-colors hover:bg-primary-100 hover:text-primary-700 data-panel-open:text-primary-700",e),...t})}function nn({className:e,contentClassName:t,children:r,...o}){return n.jsx(qo,{className:O('flex h-(--collapsible-panel-height) flex-col overflow-hidden text-sm transition-all duration-150 ease-out data-ending-style:h-0 data-starting-style:h-0 [&[hidden]:not([hidden="until-found"])]:hidden',e),...o,children:n.jsx("div",{className:O("pt-1",t),children:r})})}const mr=s.createContext(void 0);function _t(){const e=s.useContext(mr);if(e===void 0)throw new Error(an(53));return e}let Dt=(function(e){return e.scrollAreaCornerHeight="--scroll-area-corner-height",e.scrollAreaCornerWidth="--scroll-area-corner-width",e})({});const kt=500,Mn=16;function Ne(e,t,r){if(!e)return 0;const o=getComputedStyle(e),a=r==="x"?"Inline":"Block";return r==="x"&&t==="margin"?parseFloat(o[`${t}InlineStart`])*2:parseFloat(o[`${t}${a}Start`])+parseFloat(o[`${t}${a}End`])}let Jo=(function(e){return e.orientation="data-orientation",e.hovering="data-hovering",e.scrolling="data-scrolling",e.hasOverflowX="data-has-overflow-x",e.hasOverflowY="data-has-overflow-y",e.overflowXStart="data-overflow-x-start",e.overflowXEnd="data-overflow-x-end",e.overflowYStart="data-overflow-y-start",e.overflowYEnd="data-overflow-y-end",e})({});const Ct="base-ui-disable-scrollbar",pr={className:Ct,getElement(e){return n.jsx("style",{nonce:e,href:Ct,precedence:"base-ui:low",children:`.${Ct}{scrollbar-width:none}.${Ct}::-webkit-scrollbar{display:none}`})}};let lt=(function(e){return e.hasOverflowX="data-has-overflow-x",e.hasOverflowY="data-has-overflow-y",e.overflowXStart="data-overflow-x-start",e.overflowXEnd="data-overflow-x-end",e.overflowYStart="data-overflow-y-start",e.overflowYEnd="data-overflow-y-end",e})({});const mn={hasOverflowX:e=>e?{[lt.hasOverflowX]:""}:null,hasOverflowY:e=>e?{[lt.hasOverflowY]:""}:null,overflowXStart:e=>e?{[lt.overflowXStart]:""}:null,overflowXEnd:e=>e?{[lt.overflowXEnd]:""}:null,overflowYStart:e=>e?{[lt.overflowYStart]:""}:null,overflowYEnd:e=>e?{[lt.overflowYEnd]:""}:null,cornerHidden:()=>null},Qo={x:0,y:0},In={width:0,height:0},Zo={xStart:!1,xEnd:!1,yStart:!1,yEnd:!1},ei={x:!1,y:!1,corner:!1},ti=s.forwardRef(function(t,r){const{render:o,className:a,overflowEdgeThreshold:i,...l}=t,c=ni(i),u=tr(),d=It(),f=It(),{nonce:m,disableStyleElements:p}=Bs(),[h,v]=s.useState(!1),[g,j]=s.useState(!1),[w,y]=s.useState(!1),[P,I]=s.useState(!1),[z,T]=s.useState(In),[J,B]=s.useState(In),[H,te]=s.useState(Zo),[U,S]=s.useState(ei),E=s.useRef(null),k=s.useRef(null),R=s.useRef(null),_=s.useRef(null),A=s.useRef(null),X=s.useRef(null),C=s.useRef(null),D=s.useRef(!1),x=s.useRef(0),L=s.useRef(0),K=s.useRef(0),G=s.useRef(0),q=s.useRef("vertical"),V=s.useRef(Qo),Q=Ge(M=>{const he=M.x-V.current.x,Ce=M.y-V.current.y;V.current=M,Ce!==0&&(y(!0),d.start(kt,()=>{y(!1)})),he!==0&&(j(!0),f.start(kt,()=>{j(!1)}))}),oe=Ge(M=>{M.button===0&&(D.current=!0,x.current=M.clientY,L.current=M.clientX,q.current=M.currentTarget.getAttribute(Jo.orientation),k.current&&(K.current=k.current.scrollTop,G.current=k.current.scrollLeft),A.current&&q.current==="vertical"&&A.current.setPointerCapture(M.pointerId),X.current&&q.current==="horizontal"&&X.current.setPointerCapture(M.pointerId))}),re=Ge(M=>{if(!D.current)return;const he=M.clientY-x.current,Ce=M.clientX-L.current;if(k.current){const ze=k.current.scrollHeight,Ue=k.current.clientHeight,N=k.current.scrollWidth,W=k.current.clientWidth;if(A.current&&R.current&&q.current==="vertical"){const F=Ne(R.current,"padding","y"),le=Ne(A.current,"margin","y"),ne=A.current.offsetHeight,se=R.current.offsetHeight-ne-F-le,ve=he/se;k.current.scrollTop=K.current+ve*(ze-Ue),M.preventDefault(),y(!0),d.start(kt,()=>{y(!1)})}if(X.current&&_.current&&q.current==="horizontal"){const F=Ne(_.current,"padding","x"),le=Ne(X.current,"margin","x"),ne=X.current.offsetWidth,se=_.current.offsetWidth-ne-F-le,ve=Ce/se;k.current.scrollLeft=G.current+ve*(N-W),M.preventDefault(),j(!0),f.start(kt,()=>{j(!1)})}}}),Y=Ge(M=>{D.current=!1,A.current&&q.current==="vertical"&&A.current.releasePointerCapture(M.pointerId),X.current&&q.current==="horizontal"&&X.current.releasePointerCapture(M.pointerId)});function ae(M){I(M.pointerType==="touch")}function me(M){if(ae(M),M.pointerType!=="touch"){const he=Ws(E.current,M.target);v(he)}}const ee=s.useMemo(()=>({hasOverflowX:!U.x,hasOverflowY:!U.y,overflowXStart:H.xStart,overflowXEnd:H.xEnd,overflowYStart:H.yStart,overflowYEnd:H.yEnd,cornerHidden:U.corner}),[U.x,U.y,U.corner,H]),ie={role:"presentation",onPointerEnter:me,onPointerMove:me,onPointerDown:ae,onPointerLeave(){v(!1)},style:{position:"relative",[Dt.scrollAreaCornerHeight]:`${z.height}px`,[Dt.scrollAreaCornerWidth]:`${z.width}px`}},ge=qe("div",t,{state:ee,ref:[r,E],props:[ie,l],stateAttributesMapping:mn}),pe=s.useMemo(()=>({handlePointerDown:oe,handlePointerMove:re,handlePointerUp:Y,handleScroll:Q,cornerSize:z,setCornerSize:T,thumbSize:J,setThumbSize:B,touchModality:P,cornerRef:C,scrollingX:g,setScrollingX:j,scrollingY:w,setScrollingY:y,hovering:h,setHovering:v,viewportRef:k,rootRef:E,scrollbarYRef:R,scrollbarXRef:_,thumbYRef:A,thumbXRef:X,rootId:u,hiddenState:U,setHiddenState:S,overflowEdges:H,setOverflowEdges:te,viewportState:ee,overflowEdgeThreshold:c}),[oe,re,Y,Q,z,J,P,g,j,w,y,h,v,u,U,H,ee,c]);return n.jsxs(mr.Provider,{value:pe,children:[!p&&pr.getElement(m),ge]})});function ni(e){if(typeof e=="number"){const t=Math.max(0,e);return{xStart:t,xEnd:t,yStart:t,yEnd:t}}return{xStart:Math.max(0,e?.xStart||0),xEnd:Math.max(0,e?.xEnd||0),yStart:Math.max(0,e?.yStart||0),yEnd:Math.max(0,e?.yEnd||0)}}const ri=s.createContext(void 0);function He(e,t=Number.MIN_SAFE_INTEGER,r=Number.MAX_SAFE_INTEGER){return Math.max(t,Math.min(e,r))}function si(e,t){if(typeof IntersectionObserver>"u")return()=>{};const r=new IntersectionObserver(o=>{o.forEach(a=>{a.intersectionRatio>0&&(t(),r.disconnect())})});return r.observe(e),()=>{r.disconnect()}}let Ve=(function(e){return e.scrollAreaOverflowXStart="--scroll-area-overflow-x-start",e.scrollAreaOverflowXEnd="--scroll-area-overflow-x-end",e.scrollAreaOverflowYStart="--scroll-area-overflow-y-start",e.scrollAreaOverflowYEnd="--scroll-area-overflow-y-end",e})({}),An=!1;function oi(){An||Xs||(typeof CSS<"u"&&"registerProperty"in CSS&&[Ve.scrollAreaOverflowXStart,Ve.scrollAreaOverflowXEnd,Ve.scrollAreaOverflowYStart,Ve.scrollAreaOverflowYEnd].forEach(e=>{try{CSS.registerProperty({name:e,syntax:"<length>",inherits:!1,initialValue:"0px"})}catch{}}),An=!0)}const ii=s.forwardRef(function(t,r){const{render:o,className:a,...i}=t,{viewportRef:l,scrollbarYRef:c,scrollbarXRef:u,thumbYRef:d,thumbXRef:f,cornerRef:m,cornerSize:p,setCornerSize:h,setThumbSize:v,rootId:g,setHiddenState:j,hiddenState:w,handleScroll:y,setHovering:P,setOverflowEdges:I,overflowEdges:z,overflowEdgeThreshold:T}=_t(),J=sr(),B=s.useRef(!0),H=It(),te=It(),U=Ge(()=>{const A=l.current,X=c.current,C=u.current,D=d.current,x=f.current,L=m.current;if(!A)return;const K=A.scrollHeight,G=A.scrollWidth,q=A.clientHeight,V=A.clientWidth,Q=A.scrollTop,oe=A.scrollLeft;if(K===0||G===0)return;const re=q>=K,Y=V>=G,ae=V/G,me=q/K,ee=Math.max(0,G-V),ie=Math.max(0,K-q);let ge=0,pe=0;Y||(J==="rtl"?ge=He(-oe,0,ee):ge=He(oe,0,ee),pe=ee-ge);const M=re?0:He(Q,0,ie),he=re?0:ie-M,Ce=Y?0:V,ze=re?0:q;let Ue=0,N=0;!Y&&!re&&(Ue=X?.offsetWidth||0,N=C?.offsetHeight||0);const W=p.width===0&&p.height===0,F=W?Ue:0,le=W?N:0,ne=Ne(C,"padding","x"),se=Ne(X,"padding","y"),ve=Ne(x,"margin","x"),tt=Ne(D,"margin","y"),Te=Ce-ne-ve,Pe=ze-se-tt,nt=C?Math.min(C.offsetWidth-F,Te):Te,wt=X?Math.min(X.offsetHeight-le,Pe):Pe,rt=Math.max(Mn,nt*ae),st=Math.max(Mn,wt*me);if(v(ce=>ce.height===st&&ce.width===rt?ce:{width:rt,height:st}),X&&D){const ce=X.offsetHeight-st-se-tt,Se=K-q,$e=Se===0?0:Q/Se,gt=Math.min(ce,Math.max(0,$e*ce));D.style.transform=`translate3d(0,${gt}px,0)`}if(C&&x){const ce=C.offsetWidth-rt-ne-ve,Se=G-V,$e=Se===0?0:oe/Se,gt=J==="rtl"?He($e*ce,-ce,0):He($e*ce,0,ce);x.style.transform=`translate3d(${gt}px,0,0)`}const pt=He(ge,0,ee),bt=He(pe,0,ee),St=He(M,0,ie),ht=He(he,0,ie),vt=[[Ve.scrollAreaOverflowXStart,pt],[Ve.scrollAreaOverflowXEnd,bt],[Ve.scrollAreaOverflowYStart,St],[Ve.scrollAreaOverflowYEnd,ht]];for(const[ce,Se]of vt)A.style.setProperty(ce,`${Se}px`);L&&(Y||re?h({width:0,height:0}):!Y&&!re&&h({width:Ue,height:N})),j(ce=>{const Se=re||Y;return ce.y===re&&ce.x===Y&&ce.corner===Se?ce:{y:re,x:Y,corner:Se}});const je={xStart:!Y&&pt>T.xStart,xEnd:!Y&&bt>T.xEnd,yStart:!re&&St>T.yStart,yEnd:!re&&ht>T.yEnd};I(ce=>ce.xStart===je.xStart&&ce.xEnd===je.xEnd&&ce.yStart===je.yStart&&ce.yEnd===je.yEnd?ce:je)});Oe(()=>{if(!l.current)return;oi();let A=!1;return si(l.current,()=>{if(!A){A=!0;return}U()})},[U,l]),Oe(()=>{queueMicrotask(U)},[U,w,J]),Oe(()=>{l.current?.matches(":hover")&&P(!0)},[l,P]),s.useEffect(()=>{const A=l.current;if(typeof ResizeObserver>"u"||!A)return;let X=!1;const C=new ResizeObserver(()=>{if(!X){X=!0;return}U()});return C.observe(A),te.start(0,()=>{const D=A.getAnimations({subtree:!0});D.length!==0&&Promise.all(D.map(x=>x.finished)).then(U).catch(()=>{})}),()=>{C.disconnect(),te.clear()}},[U,l,te]);function S(){B.current=!1}const E={role:"presentation",...g&&{"data-id":`${g}-viewport`},...(!w.x||!w.y)&&{tabIndex:0},className:pr.className,style:{overflow:"scroll"},onScroll(){l.current&&(U(),B.current||y({x:l.current.scrollLeft,y:l.current.scrollTop}),H.start(100,()=>{B.current=!0}))},onWheel:S,onTouchMove:S,onPointerMove:S,onPointerEnter:S,onKeyDown:S},k=s.useMemo(()=>({hasOverflowX:!w.x,hasOverflowY:!w.y,overflowXStart:z.xStart,overflowXEnd:z.xEnd,overflowYStart:z.yStart,overflowYEnd:z.yEnd,cornerHidden:w.corner}),[w.x,w.y,w.corner,z]),R=qe("div",t,{ref:[r,l],state:k,props:[E,i],stateAttributesMapping:mn}),_=s.useMemo(()=>({computeThumbPosition:U}),[U]);return n.jsx(ri.Provider,{value:_,children:R})}),hr=s.createContext(void 0);function ai(){const e=s.useContext(hr);if(e===void 0)throw new Error(an(54));return e}let Ot=(function(e){return e.scrollAreaThumbHeight="--scroll-area-thumb-height",e.scrollAreaThumbWidth="--scroll-area-thumb-width",e})({});const li=s.forwardRef(function(t,r){const{render:o,className:a,orientation:i="vertical",keepMounted:l=!1,...c}=t,{hovering:u,scrollingX:d,scrollingY:f,hiddenState:m,overflowEdges:p,scrollbarYRef:h,scrollbarXRef:v,viewportRef:g,thumbYRef:j,thumbXRef:w,handlePointerDown:y,handlePointerUp:P,rootId:I,thumbSize:z}=_t(),T=s.useMemo(()=>({hovering:u,scrolling:{horizontal:d,vertical:f}[i],orientation:i,hasOverflowX:!m.x,hasOverflowY:!m.y,overflowXStart:p.xStart,overflowXEnd:p.xEnd,overflowYStart:p.yStart,overflowYEnd:p.yEnd,cornerHidden:m.corner}),[u,d,f,i,m,p]),J=sr();s.useEffect(()=>{const E=g.current,k=i==="vertical"?h.current:v.current;if(!k)return;function R(_){if(!(!E||!k||_.ctrlKey)){if(_.preventDefault(),i==="vertical"){if(E.scrollTop===0&&_.deltaY<0)return}else if(E.scrollLeft===0&&_.deltaX<0)return;if(i==="vertical"){if(E.scrollTop===E.scrollHeight-E.clientHeight&&_.deltaY>0)return}else if(E.scrollLeft===E.scrollWidth-E.clientWidth&&_.deltaX>0)return;i==="vertical"?E.scrollTop+=_.deltaY:E.scrollLeft+=_.deltaX}}return k.addEventListener("wheel",R,{passive:!1}),()=>{k.removeEventListener("wheel",R)}},[i,v,h,g]);const B={...I&&{"data-id":`${I}-scrollbar`},onPointerDown(E){if(E.button===0&&E.currentTarget===E.target&&g.current){if(j.current&&h.current&&i==="vertical"){const k=Ne(j.current,"margin","y"),R=Ne(h.current,"padding","y"),_=j.current.offsetHeight,A=h.current.getBoundingClientRect(),X=E.clientY-A.top-_/2-R+k/2,C=g.current.scrollHeight,D=g.current.clientHeight,x=h.current.offsetHeight-_-R-k,K=X/x*(C-D);g.current.scrollTop=K}if(w.current&&v.current&&i==="horizontal"){const k=Ne(w.current,"margin","x"),R=Ne(v.current,"padding","x"),_=w.current.offsetWidth,A=v.current.getBoundingClientRect(),X=E.clientX-A.left-_/2-R+k/2,C=g.current.scrollWidth,D=g.current.clientWidth,x=v.current.offsetWidth-_-R-k,L=X/x;let K;J==="rtl"?(K=(1-L)*(C-D),g.current.scrollLeft<=0&&(K=-K)):K=L*(C-D),g.current.scrollLeft=K}y(E)}},onPointerUp:P,style:{position:"absolute",touchAction:"none",WebkitUserSelect:"none",userSelect:"none",...i==="vertical"&&{top:0,bottom:`var(${Dt.scrollAreaCornerHeight})`,insetInlineEnd:0,[Ot.scrollAreaThumbHeight]:`${z.height}px`},...i==="horizontal"&&{insetInlineStart:0,insetInlineEnd:`var(${Dt.scrollAreaCornerWidth})`,bottom:0,[Ot.scrollAreaThumbWidth]:`${z.width}px`}}},H=qe("div",t,{ref:[r,i==="vertical"?h:v],state:T,props:[B,c],stateAttributesMapping:mn}),te=s.useMemo(()=>({orientation:i}),[i]),U=i==="vertical"?m.y:m.x;return l||!U?n.jsx(hr.Provider,{value:te,children:H}):null}),ci=s.forwardRef(function(t,r){const{render:o,className:a,...i}=t,{thumbYRef:l,thumbXRef:c,handlePointerDown:u,handlePointerMove:d,handlePointerUp:f,setScrollingX:m,setScrollingY:p}=_t(),{orientation:h}=ai(),v=s.useMemo(()=>({orientation:h}),[h]);return qe("div",t,{ref:[r,h==="vertical"?l:c],state:v,props:[{onPointerDown:u,onPointerMove:d,onPointerUp(j){h==="vertical"&&p(!1),h==="horizontal"&&m(!1),f(j)},style:{...h==="vertical"&&{height:`var(${Ot.scrollAreaThumbHeight})`},...h==="horizontal"&&{width:`var(${Ot.scrollAreaThumbWidth})`}}},i]})}),ui=s.forwardRef(function(t,r){const{render:o,className:a,...i}=t,{cornerRef:l,cornerSize:c,hiddenState:u}=_t(),d=qe("div",t,{ref:[r,l],props:[{style:{position:"absolute",bottom:0,insetInlineEnd:0,width:c.width,height:c.height}},i]});return u.corner?null:d});function gr({className:e,...t}){return n.jsx(ti,{className:O("group/scroll-area relative outline-none focus-visible:outline-none",e),...t})}function yr({className:e,...t}){return n.jsx(ii,{className:O("h-full w-full outline-none focus-visible:outline-none",e),...t})}function xr({className:e,...t}){return n.jsx(li,{className:O("flex w-2 touch-none select-none p-0.5 outline-none focus-visible:outline-none","opacity-0 transition-opacity duration-150","data-hovering:opacity-100 data-scrolling:opacity-100 group-hover/scroll-area:opacity-100",e),...t})}function wr({className:e,...t}){return n.jsx(ci,{className:O("flex-1 rounded-full bg-primary-500 outline-none focus-visible:outline-none",e),...t})}function di({className:e,...t}){return n.jsx(ui,{className:O("bg-primary-100 outline-none focus-visible:outline-none",e),...t})}function fi(e){return e==="subagent"?es:e==="cron"?ts:ns}function mi(e){if(!e||!Array.isArray(e.content))return"";const t=e.content.map(o=>o.type==="text"?String(o.text??""):"").join(" ");return ar(t).replace(/\s+/g," ").trim()}function pi(e){if(typeof e=="number"&&Number.isFinite(e))return e<1e12?e*1e3:e;if(typeof e=="string"){const t=Date.parse(e);if(!Number.isNaN(t))return t}return null}function hi(e){if(!e)return null;const t=[e.createdAt,e.created_at,e.timestamp,e.time,e.ts];for(const r of t){const o=pi(r);if(o)return o}return null}function gi(e){const t=e-Date.now(),r=Math.abs(t),o=[["minute",6e4],["hour",36e5],["day",864e5]];let a="minute",i=6e4;r>=o[2][1]?[a,i]=o[2]:r>=o[1][1]&&([a,i]=o[1]);const l=Math.round(t/i);return new Intl.RelativeTimeFormat("en",{numeric:"auto"}).format(l,a)}function yi(e){const t=String(e??"").toLowerCase().trim();return t?t==="error"||t==="failed"?"error":t==="completed"||t==="ended"||t==="done"?"success":null:null}function xi({session:e,active:t,isGenerating:r=!1,isPinned:o,selectionMode:a=!1,selected:i=!1,onToggleSelect:l,onSelect:c,onTogglePin:u,onRename:d,onDelete:f,onExport:m}){const p=e.label||e.title||e.derivedTitle||e.friendlyId,h=fi(e.kind),v=e.kind==="subagent"&&(e.lastMessage?.role==="assistant"||e.lastMessage?.role==="toolResult")?mi(e.lastMessage):"",g=v.length>50?`${v.slice(0,50).trimEnd()}…`:v,j=e.kind==="subagent"?yi(e.status):null,w=e.kind==="cron"?hi(e.lastMessage):null;return n.jsxs(Xe,{to:"/chat/$sessionKey",params:{sessionKey:e.friendlyId},onClick:y=>{if(a){y.preventDefault(),y.stopPropagation(),l?.(e);return}c?.()},className:O("group inline-flex items-center justify-between","w-full text-left pl-1.5 pr-0.5 min-h-8 py-1 rounded-lg transition-colors duration-0","select-none",t?"bg-[var(--opencami-accent-light)] text-[var(--opencami-accent)]":"bg-transparent text-primary-950 [&:hover:not(:has(button:hover))]:bg-primary-200"),children:[n.jsxs("div",{className:"flex items-center gap-2 flex-1 min-w-0",children:[a?n.jsx("span",{"aria-hidden":"true",className:O("inline-flex items-center justify-center size-4 shrink-0 rounded border transition-colors",i?"bg-primary-700 border-primary-700 text-white":"border-primary-300 bg-surface"),children:i?n.jsx("svg",{viewBox:"0 0 12 12",className:"size-3",fill:"none",stroke:"currentColor",strokeWidth:2,children:n.jsx("path",{d:"M2.5 6l2.5 2.5 4.5-5"})}):null}):null,n.jsxs("div",{className:"flex-1 min-w-0",children:[n.jsxs("div",{className:"flex items-center gap-1.5 min-w-0",children:[n.jsx(Z,{icon:h,size:12,strokeWidth:1.75,className:"text-primary-500/70 shrink-0"}),n.jsxs("div",{className:"min-w-0 truncate text-sm font-[450]",title:p,children:[o?n.jsx("span",{className:"mr-1 text-xs text-primary-700","aria-hidden":"true",children:"📌"}):null,p]}),e.kind==="subagent"?r?n.jsx("span",{"aria-label":"Session active",className:"size-1.5 rounded-full bg-green-500 shrink-0"}):j==="success"?n.jsx(Z,{icon:Yn,size:12,strokeWidth:1.8,className:"text-green-600/80 shrink-0"}):j==="error"?n.jsx(Z,{icon:Pt,size:12,strokeWidth:1.8,className:"text-red-600/80 shrink-0"}):null:null]}),g?n.jsx("div",{className:"text-[11px] text-primary-600/80 line-clamp-1 mt-0.5 pl-[18px]",children:g}):null,e.kind==="cron"&&w?n.jsx("div",{className:"text-[10px] text-primary-500/75 line-clamp-1 mt-0.5 pl-[18px] font-mono",children:gi(w)}):null]})]}),a?null:n.jsxs(ln,{children:[n.jsx(cn,{type:"button",onClick:y=>{y.preventDefault(),y.stopPropagation()},className:O("ml-2 inline-flex size-7 items-center justify-center rounded-md text-primary-700","opacity-0 transition-opacity group-hover:opacity-100 hover:bg-primary-200","aria-expanded:opacity-100 aria-expanded:bg-primary-200"),children:n.jsx(Z,{icon:Jr,size:20,strokeWidth:1.5})}),n.jsxs(un,{side:"bottom",align:"end",children:[n.jsxs(Ze,{onClick:y=>{y.preventDefault(),y.stopPropagation(),u(e)},className:"gap-2",children:[n.jsx("span",{className:"text-xs","aria-hidden":"true",children:"📌"})," ",o?"Unpin Session":"Pin Session"]}),n.jsxs(Ze,{onClick:y=>{y.preventDefault(),y.stopPropagation(),d(e)},className:"gap-2",children:[n.jsx(Z,{icon:Qr,size:20,strokeWidth:1.5})," ","Rename"]}),n.jsxs(Ze,{onClick:y=>{y.preventDefault(),y.stopPropagation(),m(e)},className:"gap-2",children:[n.jsx(Z,{icon:Zr,size:20,strokeWidth:1.5})," ","Export"]}),Qt(e.key)?null:n.jsxs(Ze,{onClick:y=>{y.preventDefault(),y.stopPropagation(),f(e)},className:"text-red-700 gap-2 hover:bg-red-50/80 data-highlighted:bg-red-50/80",children:[n.jsx(Z,{icon:Gn,size:20,strokeWidth:1.5})," ","Delete"]})]})]})]})}function wi(e,t){return e.active!==t.active||e.isGenerating!==t.isGenerating||e.isPinned!==t.isPinned||e.selectionMode!==t.selectionMode||e.selected!==t.selected||e.onToggleSelect!==t.onToggleSelect||e.onSelect!==t.onSelect||e.onTogglePin!==t.onTogglePin||e.onRename!==t.onRename||e.onDelete!==t.onDelete||e.onExport!==t.onExport?!1:e.session===t.session?!0:e.session.key===t.session.key&&e.session.friendlyId===t.session.friendlyId&&e.session.label===t.session.label&&e.session.title===t.session.title&&e.session.derivedTitle===t.session.derivedTitle&&e.session.updatedAt===t.session.updatedAt&&e.session.kind===t.session.kind&&e.session.status===t.session.status&&e.session.lastMessage===t.session.lastMessage}const Ft=s.memo(xi,wi),br="opencami-pinned-sessions",Sr="opencami-sidebar-folders",We={webchat:!1,subagent:!1,cron:!1,other:!1};async function bi(e){const t=new URLSearchParams;e&&t.set("sessionKey",e);const r=await fetch(`/api/sessions?${t.toString()}`,{method:"DELETE"});if(!r.ok)throw new Error(await Ke(r))}async function Si(e,t,r){const o=[];let a=0;const i=Array.from({length:Math.min(t,e.length)},async function(){for(;a<e.length;){const c=a;a+=1;try{await r(e[c])}catch(u){o.push(u)}}});return await Promise.all(i),o}function vi(){if(typeof window>"u")return[];try{const e=localStorage.getItem(br);if(!e)return[];const t=JSON.parse(e);return Array.isArray(t)?t.filter(r=>typeof r=="string"):[]}catch{return[]}}function ji(e){if(!(typeof window>"u"))try{const t=Array.from(new Set(e));localStorage.setItem(br,JSON.stringify(t))}catch{}}function ki(){if(typeof window>"u")return{...We};try{const e=localStorage.getItem(Sr);if(!e)return{...We};const t=JSON.parse(e);return!t||typeof t!="object"?{...We}:{webchat:typeof t.webchat=="boolean"?t.webchat:We.webchat,subagent:typeof t.subagent=="boolean"?t.subagent:We.subagent,cron:typeof t.cron=="boolean"?t.cron:We.cron,other:typeof t.other=="boolean"?t.other:We.other}}catch{return{...We}}}function Ci(e){if(!(typeof window>"u"))try{localStorage.setItem(Sr,JSON.stringify(e))}catch{}}function Tt(e,t,r){return r&&e.key?e.key===r:e.friendlyId===t}function Ei(e){if(!e)return!1;const t=e.toLowerCase();return t.includes("running")||t.includes("active")||t.includes("stream")||t.includes("generat")}function Wt(e,t,r,o){return Tt(e,t,r)&&o?!0:Ei(e.status)}const Ni=s.memo(function({sessions:t,activeFriendlyId:r,activeSessionKey:o,isStreaming:a=!1,defaultOpen:i=!0,onSelect:l,onRename:c,onDelete:u,onExport:d}){const f=s.useDeferredValue(t),m=mt(),[p,h]=s.useState(()=>vi()),[v,g]=s.useState(()=>ki()),[j,w]=s.useState(!1),[y,P]=s.useState(()=>new Set),I=s.useMemo(()=>new Set(p),[p]),z=f.filter(C=>I.has(C.key)),T=f.filter(C=>!I.has(C.key)),J=z.length>0&&T.length>0,B=s.useMemo(()=>{const C={chat:[],webchat:[],subagent:[],cron:[],other:[]};for(const D of T){const x=D.kind??"other";C[x].push(D)}return C},[T]),H=s.useMemo(()=>f.filter(C=>y.has(C.key)),[y,f]),te=H.length,U=s.useCallback(()=>{w(C=>(C&&P(new Set),!C))},[]),S=s.useCallback(C=>{Qt(C.key)||P(D=>{const x=new Set(D);return x.has(C.key)?x.delete(C.key):x.add(C.key),x})},[]),E=s.useCallback(()=>{P(new Set(f.filter(C=>!Qt(C.key)).map(C=>C.key)))},[f]),k=s.useCallback(()=>{w(!1),P(new Set)},[]),R=s.useCallback(async()=>{if(H.length===0||!window.confirm(`Delete ${H.length} sessions? This will archive them.`))return;const D=[];await Si(H,10,async x=>{try{await bi(x.key)}catch(L){throw D.push(x.label||x.title||x.derivedTitle||x.friendlyId),L}}),D.length>0&&(console.error("[sidebar] Bulk delete failed for some sessions",D),window.alert(`Could not delete ${D.length} session${D.length!==1?"s":""}:
6
+
7
+ ${D.join(`
8
+ `)}`)),w(!1),P(new Set),m.invalidateQueries({queryKey:fe.sessions})},[m,H]),_=s.useCallback(C=>{h(D=>{const L=D.includes(C.key)?D.filter(K=>K!==C.key):[...D,C.key];return ji(L),L})},[]),A=s.useCallback((C,D)=>{g(x=>{const L={...x,[C]:D};return Ci(L),L})},[]);function X(C,D,x){return x.length===0?null:n.jsxs(en,{className:"flex flex-col",open:v[C],onOpenChange:L=>A(C,L),children:[n.jsxs(tn,{className:O("w-full justify-between border-l-2 border-primary-200/70 px-2 py-1 text-[11px] font-medium text-primary-500/80 text-balance"),children:[n.jsx("span",{className:"truncate",children:D}),n.jsx("span",{className:O("rounded-full bg-primary-100 px-1.5 py-0.5 text-[10px] font-medium text-primary-700 tabular-nums"),children:x.length})]}),n.jsx(nn,{contentClassName:"flex flex-col gap-px",children:x.map(L=>n.jsx(Ft,{session:L,active:Tt(L,r,o),isGenerating:Wt(L,r,o,a),isPinned:!1,selectionMode:j,selected:y.has(L.key),onToggleSelect:S,onSelect:l,onTogglePin:_,onRename:c,onDelete:u,onExport:d},L.key))})]})}return n.jsxs(en,{className:"flex h-full flex-col flex-1 min-h-0 w-full",defaultOpen:i,children:[n.jsxs("div",{className:"flex items-center justify-between pr-2 shrink-0",children:[n.jsxs(tn,{className:"w-fit pl-1.5 text-balance",children:["Sessions",n.jsx("span",{className:"opacity-0 transition-opacity duration-150 group-hover:opacity-100",children:n.jsx(Z,{icon:rs,className:"size-3 transition-transform duration-150 group-data-panel-open:rotate-90"})})]}),n.jsx("button",{type:"button",onClick:U,className:O("text-[11px] font-medium px-1.5 py-0.5 rounded-md transition-colors",j?"text-primary-900 bg-primary-200":"text-primary-500 hover:text-primary-700 hover:bg-primary-100"),children:j?"Done":"Select"})]}),n.jsx(nn,{className:"w-full flex-1 min-h-0 h-auto data-starting-style:h-0 data-ending-style:h-0",contentClassName:"flex flex-1 min-h-0 flex-col overflow-y-auto",children:n.jsxs(gr,{className:"flex-1 min-h-0",children:[n.jsx(yr,{className:"min-h-0",children:n.jsxs("div",{className:"flex flex-col gap-2 pl-2 pr-2",children:[z.length>0?n.jsx("div",{className:"flex flex-col gap-px",children:z.map(C=>n.jsx(Ft,{session:C,active:Tt(C,r,o),isGenerating:Wt(C,r,o,a),isPinned:!0,selectionMode:j,selected:y.has(C.key),onToggleSelect:S,onSelect:l,onTogglePin:_,onRename:c,onDelete:u,onExport:d},C.key))}):null,J?n.jsx("div",{className:"my-1 border-t border-primary-200/80"}):null,B.chat.length>0?n.jsxs("div",{className:"flex flex-col gap-px",children:[n.jsx("div",{className:O("border-l-2 border-primary-200/70 px-2 py-1 text-[11px] font-medium text-primary-500/80 text-balance"),children:"💬 Chats"}),n.jsx("div",{className:"flex flex-col gap-px",children:B.chat.map(C=>n.jsx(Ft,{session:C,active:Tt(C,r,o),isGenerating:Wt(C,r,o,a),isPinned:!1,selectionMode:j,selected:y.has(C.key),onToggleSelect:S,onSelect:l,onTogglePin:_,onRename:c,onDelete:u,onExport:d},C.key))})]}):null,X("webchat","🦎 OpenCami",B.webchat),X("subagent","🤖 Sub-agents",B.subagent),X("cron","⏰ Cron / Isolated",B.cron),X("other","📁 Other",B.other)]})}),n.jsx(xr,{orientation:"vertical",children:n.jsx(wr,{})})]})}),j?n.jsxs("div",{className:"shrink-0 border-t border-primary-200 bg-surface px-2 py-2 flex flex-col gap-1.5",children:[n.jsxs("div",{className:"flex items-center justify-between",children:[n.jsxs("span",{className:"text-xs text-primary-600 font-medium",children:[te," selected"]}),n.jsx("button",{type:"button",onClick:E,className:"text-[11px] font-medium text-primary-600 hover:text-primary-800",children:"Select all"})]}),n.jsxs("div",{className:"flex gap-1.5",children:[n.jsxs("button",{type:"button",onClick:R,disabled:te===0,className:O("flex-1 inline-flex items-center justify-center gap-1.5 rounded-md px-2 py-1.5 text-xs font-medium transition-colors",te>0?"bg-red-100 text-red-700 hover:bg-red-200":"bg-primary-100 text-primary-400 cursor-not-allowed"),children:[n.jsx(Z,{icon:Gn,size:14,strokeWidth:1.5}),"Delete"]}),n.jsx("button",{type:"button",onClick:k,className:"flex-1 inline-flex items-center justify-center rounded-md px-2 py-1.5 text-xs font-medium bg-primary-100 text-primary-700 hover:bg-primary-200 transition-colors",children:"Cancel"})]})]}):null]})},Ti);function Ti(e,t){if(e.activeFriendlyId!==t.activeFriendlyId||e.activeSessionKey!==t.activeSessionKey||e.isStreaming!==t.isStreaming||e.defaultOpen!==t.defaultOpen||e.onSelect!==t.onSelect||e.onRename!==t.onRename||e.onDelete!==t.onDelete||e.onExport!==t.onExport)return!1;if(e.sessions===t.sessions)return!0;if(e.sessions.length!==t.sessions.length)return!1;for(let r=0;r<e.sessions.length;r+=1){const o=e.sessions[r],a=t.sessions[r];if(o.key!==a.key||o.friendlyId!==a.friendlyId||o.label!==a.label||o.title!==a.title||o.derivedTitle!==a.derivedTitle||o.updatedAt!==a.updatedAt||o.kind!==a.kind||o.status!==a.status||o.lastMessage!==a.lastMessage)return!1}return!0}const Ri=s.lazy(()=>et(()=>import("./settings-dialog-B93qswor.js"),__vite__mapDeps([0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24])).then(e=>({default:e.SettingsDialog}))),Mi=s.lazy(()=>et(()=>import("./session-export-dialog-io9FvLKq.js"),__vite__mapDeps([25,1,4,3,5,6,7,8,9,2])).then(e=>({default:e.SessionExportDialog})));function Ii({sessions:e,activeFriendlyId:t,activeSessionKey:r,isStreaming:o=!1,creatingSession:a,onCreateSession:i,isCollapsed:l,onToggleCollapse:c,onSelectSession:u,onActiveSessionDelete:d,onOpenSearch:f}){const{settingsOpen:m,setSettingsOpen:p,pathsLoading:h,pathsError:v,paths:g,handleOpenSettings:j,closeSettings:w,copySessionsDir:y,copyStorePath:P}=po(),{deleteSession:I}=jo(),{renameSession:z}=ko(),T={duration:.15,ease:l?"easeIn":"easeOut"},[J,B]=s.useState(!1),[H,te]=s.useState(null),[U,S]=s.useState(""),[E,k]=s.useState(!1),[R,_]=s.useState(null),[A,X]=s.useState(null),[C,D]=s.useState(""),[x,L]=s.useState(!1),[K,G]=s.useState(null),[q,V]=s.useState(null),[Q,oe]=s.useState(""),re=mt();function Y(M){te(M.key),S(M.label||M.title||M.derivedTitle||""),B(!0)}function ae(M){H&&z(H,M),B(!1),te(null)}function me(M){_(M.key),X(M.friendlyId),D(M.label||M.title||M.derivedTitle||M.friendlyId),k(!0)}function ee(){if(R&&A){const M=A===t;M&&d&&d(),I(R,A,M)}k(!1),_(null),X(null)}function ie(M){G(M.key),V(M.friendlyId),oe(M.label||M.title||M.derivedTitle||M.friendlyId),L(!0)}function ge(M){if(K&&q){const he=fe.history(q,K),Ce=re.getQueryData(he);Ce?.messages&&To(Q,Ce.messages,M)}L(!1),G(null),V(null)}const pe={className:"border-r border-primary-200 h-full overflow-hidden bg-primary-100 flex flex-col"};return n.jsxs(be.aside,{initial:!1,animate:{width:l?48:"var(--opencami-sidebar-width)"},transition:T,className:pe.className,children:[n.jsxs(be.div,{layout:!0,transition:{layout:T},className:O("flex items-center h-12 px-2 justify-between"),children:[n.jsx(Re,{initial:!1,children:l?null:n.jsx(be.div,{initial:{opacity:0},animate:{opacity:1},exit:{opacity:0},transition:T,children:n.jsxs(Xe,{to:"/new",className:O(Je({variant:"ghost",size:"sm"}),"w-full pl-1.5 justify-start"),children:[n.jsx(Ys,{className:"size-5"}),n.jsx(Gs,{})]})})}),n.jsx(Me,{children:n.jsxs(Ie,{children:[n.jsx(Ae,{onClick:c,render:n.jsx(we,{size:"icon-sm",variant:"ghost",children:n.jsx(Z,{icon:ss,size:20,strokeWidth:1.5})})}),n.jsx(De,{side:"right",children:l?"Open Sidebar":"Close Sidebar"})]})})]}),n.jsxs("div",{className:"px-2 mb-4 flex flex-col gap-1",children:[n.jsxs(be.div,{layout:!0,transition:{layout:T},className:"w-full space-y-2",children:[n.jsxs(we,{disabled:a,variant:"ghost",size:"sm",onClick:i,onMouseUp:u,className:"w-full pl-1.5 justify-start",children:[n.jsx(Z,{icon:os,size:20,strokeWidth:1.5,className:"min-w-5"}),n.jsx(Re,{initial:!1,mode:"wait",children:!l&&n.jsx(be.span,{initial:{opacity:0},animate:{opacity:1},exit:{opacity:0},transition:T,className:"overflow-hidden whitespace-nowrap",children:"New Session"})})]}),(()=>{try{const M=localStorage.getItem("opencami-file-explorer");return M===null?!0:M==="true"}catch{return!0}})()&&n.jsx(Me,{children:n.jsxs(Ie,{children:[n.jsx(Ae,{asChild:!0,children:n.jsxs(Xe,{to:"/files",className:O(Je({variant:"ghost",size:"sm"}),"w-full pl-1.5 justify-start"),onClick:u,children:[n.jsx(Z,{icon:is,size:20,strokeWidth:1.5,className:"min-w-5"}),n.jsx(Re,{initial:!1,mode:"wait",children:!l&&n.jsx(be.span,{initial:{opacity:0},animate:{opacity:1},exit:{opacity:0},transition:T,className:"overflow-hidden whitespace-nowrap",children:"Files"})})]})}),l&&n.jsx(De,{side:"right",children:"Files"})]})}),(()=>{try{const M=localStorage.getItem("opencami-memory-viewer");return M===null?!0:M==="true"}catch{return!0}})()&&n.jsx(Me,{children:n.jsxs(Ie,{children:[n.jsx(Ae,{asChild:!0,children:n.jsxs(Xe,{to:"/memory",className:O(Je({variant:"ghost",size:"sm"}),"w-full pl-1.5 justify-start"),onClick:u,children:[n.jsx(Z,{icon:Vt,size:20,strokeWidth:1.5,className:"min-w-5"}),n.jsx(Re,{initial:!1,mode:"wait",children:!l&&n.jsx(be.span,{initial:{opacity:0},animate:{opacity:1},exit:{opacity:0},transition:T,className:"overflow-hidden whitespace-nowrap",children:"Memory"})})]})}),l&&n.jsx(De,{side:"right",children:"Memory"})]})}),(()=>{try{return localStorage.getItem("opencami-skills-browser")==="true"}catch{return!1}})()&&n.jsx(Me,{children:n.jsxs(Ie,{children:[n.jsx(Ae,{asChild:!0,children:n.jsxs(Xe,{to:"/skills",className:O(Je({variant:"ghost",size:"sm"}),"w-full pl-1.5 justify-start"),onClick:u,children:[n.jsx(Z,{icon:as,size:20,strokeWidth:1.5,className:"min-w-5"}),n.jsx(Re,{initial:!1,mode:"wait",children:!l&&n.jsx(be.span,{initial:{opacity:0},animate:{opacity:1},exit:{opacity:0},transition:T,className:"overflow-hidden whitespace-nowrap",children:"Skills"})})]})}),l&&n.jsx(De,{side:"right",children:"Skills"})]})}),(()=>{try{return localStorage.getItem("opencami-agent-manager")==="true"}catch{return!1}})()&&n.jsx(Me,{children:n.jsxs(Ie,{children:[n.jsx(Ae,{asChild:!0,children:n.jsxs(Xe,{to:"/agents",className:O(Je({variant:"ghost",size:"sm"}),"w-full pl-1.5 justify-start"),onClick:u,children:[n.jsx(Z,{icon:Vt,size:20,strokeWidth:1.5,className:"min-w-5"}),n.jsx(Re,{initial:!1,mode:"wait",children:!l&&n.jsx(be.span,{initial:{opacity:0},animate:{opacity:1},exit:{opacity:0},transition:T,className:"overflow-hidden whitespace-nowrap",children:"Agents"})})]})}),l&&n.jsx(De,{side:"right",children:"Agents"})]})}),(()=>{try{return localStorage.getItem("opencami-cron-manager")==="true"}catch{return!1}})()&&n.jsx(Me,{children:n.jsxs(Ie,{children:[n.jsx(Ae,{asChild:!0,children:n.jsxs(Xe,{to:"/bots",className:O(Je({variant:"ghost",size:"sm"}),"w-full pl-1.5 justify-start"),onClick:u,children:[n.jsx(Z,{icon:ls,size:20,strokeWidth:1.5,className:"min-w-5"}),n.jsx(Re,{initial:!1,mode:"wait",children:!l&&n.jsx(be.span,{initial:{opacity:0},animate:{opacity:1},exit:{opacity:0},transition:T,className:"overflow-hidden whitespace-nowrap",children:"Cron Jobs"})})]})}),l&&n.jsx(De,{side:"right",children:"Cron Jobs"})]})}),(()=>{try{return localStorage.getItem("feature_dashboard")==="true"}catch{return!1}})()&&n.jsx(Me,{children:n.jsxs(Ie,{children:[n.jsx(Ae,{asChild:!0,children:n.jsxs(Xe,{to:"/dashboard",className:O(Je({variant:"ghost",size:"sm"}),"w-full pl-1.5 justify-start"),onClick:u,children:[n.jsx(Z,{icon:cs,size:20,strokeWidth:1.5,className:"min-w-5"}),n.jsx(Re,{initial:!1,mode:"wait",children:!l&&n.jsx(be.span,{initial:{opacity:0},animate:{opacity:1},exit:{opacity:0},transition:T,className:"overflow-hidden whitespace-nowrap",children:"Dashboard"})})]})}),l&&n.jsx(De,{side:"right",children:"Dashboard"})]})})]}),n.jsx(be.div,{layout:!0,transition:{layout:T},className:"w-full",children:n.jsxs(we,{variant:"ghost",size:"sm",onClick:f,className:"w-full pl-1.5 justify-start",children:[n.jsx(Z,{icon:us,size:20,strokeWidth:1.5,className:"min-w-5"}),n.jsx(Re,{initial:!1,mode:"wait",children:!l&&n.jsx(be.span,{initial:{opacity:0},animate:{opacity:1},exit:{opacity:0},transition:T,className:"overflow-hidden whitespace-nowrap",children:"Search"})})]})})]}),n.jsx("div",{className:"flex-1 min-h-0 overflow-hidden",children:n.jsx(Re,{initial:!1,children:!l&&n.jsx(be.div,{initial:{opacity:0},animate:{opacity:1},exit:{opacity:0},transition:T,className:"pt-0 flex flex-col w-full min-h-0 h-full",children:n.jsx("div",{className:"flex-1 min-h-0",children:n.jsx(Ni,{sessions:e,activeFriendlyId:t,activeSessionKey:r,isStreaming:o,onSelect:u,onRename:Y,onDelete:me,onExport:ie})})},"content")})}),n.jsx("div",{className:"px-2 py-3 border-t border-primary-200 bg-primary-100",children:n.jsx(be.div,{layout:!0,transition:{layout:T},className:"w-full",children:n.jsxs(we,{variant:"ghost",size:"sm",onClick:j,title:l?"Settings":void 0,className:"w-full justify-start pl-1.5",children:[n.jsx(Z,{icon:ds,size:20,strokeWidth:1.5,className:"min-w-5"}),n.jsx(Re,{initial:!1,mode:"wait",children:!l&&n.jsx(be.span,{initial:{opacity:0},animate:{opacity:1},exit:{opacity:0},transition:T,className:"overflow-hidden whitespace-nowrap",children:"Settings"})})]})})}),m&&n.jsx(s.Suspense,{fallback:null,children:n.jsx(Ri,{open:m,onOpenChange:p,pathsLoading:h,pathsError:v,paths:g,onClose:w,onCopySessionsDir:y,onCopyStorePath:P})}),n.jsx(Ko,{open:J,onOpenChange:B,sessionTitle:U,onSave:ae,onCancel:()=>B(!1)}),n.jsx(_o,{open:E,onOpenChange:k,sessionTitle:C,onConfirm:ee,onCancel:()=>k(!1)}),x&&n.jsx(s.Suspense,{fallback:null,children:n.jsx(Mi,{open:x,onOpenChange:L,sessionTitle:Q,onExport:ge,onCancel:()=>L(!1)})})]})}function Ai(e,t){if(e===t)return!0;if(e.length!==t.length)return!1;for(let r=0;r<e.length;r+=1){const o=e[r],a=t[r];if(o.key!==a.key||o.friendlyId!==a.friendlyId||o.label!==a.label||o.title!==a.title||o.derivedTitle!==a.derivedTitle||o.updatedAt!==a.updatedAt||o.kind!==a.kind||o.status!==a.status||o.lastMessage!==a.lastMessage)return!1}return!0}function Di(e,t){return!(e.activeFriendlyId!==t.activeFriendlyId||e.activeSessionKey!==t.activeSessionKey||e.isStreaming!==t.isStreaming||e.creatingSession!==t.creatingSession||e.isCollapsed!==t.isCollapsed||!Ai(e.sessions,t.sessions))}const Oi=s.memo(Ii,Di);function Dn(e){if(e<=0)return"0";if(e>=1e6){const t=e/1e6,r=t.toFixed(1);return r.endsWith(".0")?`${Math.round(t)}M`:`${r}M`}if(e>=1e5)return`${Math.round(e/1e3)}K`;if(e>=1e4)return`${Math.round(e/1e3)}K`;if(e>=1e3){const t=e/1e3,r=t.toFixed(1);return r.endsWith(".0")?`${Math.round(t)}K`:`${r}K`}return String(Math.round(e))}function On(e){return e>=90?{bar:"bg-red-500",text:"text-red-600 dark:text-red-400"}:e>=70?{bar:"bg-yellow-500",text:"text-yellow-600 dark:text-yellow-400"}:{bar:"bg-emerald-500",text:"text-emerald-600 dark:text-emerald-400"}}function Li({totalTokens:e,contextTokens:t,className:r}){const{percentage:o,usedStr:a,maxStr:i,colors:l,hasData:c,isNearlyFull:u}=s.useMemo(()=>{if(typeof t!="number"||t<=0)return{percentage:0,usedStr:"",maxStr:"",colors:On(0),hasData:!1,isNearlyFull:!1};const m=typeof e=="number"&&e>0?e:0,p=Math.min(100,Math.round(m/t*100));return{percentage:p,usedStr:Dn(m),maxStr:Dn(t),colors:On(p),hasData:!0,isNearlyFull:p>=95}},[e,t]);if(!c)return null;const d=typeof e=="number"&&e>0?e.toLocaleString():"0",f=typeof t=="number"?t.toLocaleString():"0";return n.jsxs("div",{className:O("group relative flex items-center gap-1.5",r),title:`Context: ${d} / ${f} tokens (${o}%)`,children:[n.jsxs("div",{className:"flex items-center gap-1.5",children:[n.jsx("div",{className:"w-12 h-1.5 rounded-full bg-primary-200 dark:bg-primary-700 overflow-hidden shrink-0 group-hover:h-2 transition-all",children:n.jsx("div",{className:O("h-full rounded-full transition-all duration-500 ease-out",l.bar,u&&"animate-pulse"),style:{width:`${o}%`}})}),n.jsx("span",{className:O("text-[10px] leading-none font-medium tabular-nums whitespace-nowrap",u?l.text:"text-primary-500 dark:text-primary-400"),children:a})]}),n.jsx("div",{className:O("absolute right-0 top-full mt-1 z-50","pointer-events-none opacity-0 scale-95","group-hover:pointer-events-auto group-hover:opacity-100 group-hover:scale-100","transition-all duration-150 origin-top-right"),children:n.jsxs("div",{className:O("rounded-md border border-primary-200 dark:border-primary-700","bg-surface shadow-lg px-3 py-2","text-xs whitespace-nowrap"),children:[n.jsxs("div",{className:"flex items-center gap-2 mb-1.5",children:[n.jsx("span",{className:"text-primary-500 dark:text-primary-400",children:"Context window"}),n.jsxs("span",{className:O("font-semibold",l.text),children:[o,"%"]})]}),n.jsxs("div",{className:"flex items-center gap-1.5 text-primary-700 dark:text-primary-300",children:[n.jsx("span",{className:"font-medium",children:a}),n.jsx("span",{className:"text-primary-400",children:"/"}),n.jsx("span",{children:i}),n.jsx("span",{className:"text-primary-400",children:"tokens"})]}),n.jsx("div",{className:"w-full h-1.5 rounded-full bg-primary-200 dark:bg-primary-700 overflow-hidden mt-1.5",children:n.jsx("div",{className:O("h-full rounded-full transition-all duration-500 ease-out",l.bar),style:{width:`${o}%`}})}),u&&n.jsx("div",{className:"mt-1.5 text-[10px] text-red-500 dark:text-red-400 font-medium",children:"⚠ Context nearly full — consider /compact"})]})})]})}const Pi=s.memo(Li);function _i({activeTitle:e,wrapperRef:t,showSidebarButton:r=!1,onOpenSidebar:o,totalTokens:a,contextTokens:i}){return n.jsxs("div",{ref:t,"data-tauri-drag-region":!0,className:"border-b border-primary-200 px-4 h-12 flex min-w-0 items-center overflow-x-hidden bg-surface tauri-drag-header",children:[r?n.jsx(we,{size:"icon-sm",variant:"ghost",onClick:o,className:"mr-2 text-primary-800 hover:bg-primary-100",style:{WebkitAppRegion:"no-drag"},"aria-label":"Open sidebar",children:n.jsx(Z,{icon:fs,size:18,strokeWidth:1.6})}):null,n.jsx("div",{className:"flex-1 min-w-0 overflow-hidden",children:n.jsx("div",{className:"truncate text-sm font-medium",children:e})}),n.jsx(Pi,{totalTokens:a,contextTokens:i,className:"ml-3 hidden sm:flex"})]})}const Ki=s.memo(_i);function zi(e,t){return e.getFullYear()===t.getFullYear()&&e.getMonth()===t.getMonth()&&e.getDate()===t.getDate()}function Ui(e){const t=new Date(e);return zi(t,new Date)?new Intl.DateTimeFormat("en-GB",{hour:"2-digit",minute:"2-digit"}).format(t):new Intl.DateTimeFormat("en-GB",{day:"2-digit",month:"short"}).format(t)}function $i(e){return new Intl.DateTimeFormat("en-GB",{day:"2-digit",month:"short",year:"numeric",hour:"2-digit",minute:"2-digit",second:"2-digit"}).format(new Date(e))}function Hi({timestamp:e}){const t=Ui(e),r=$i(e);return n.jsx(Me,{children:n.jsxs(Ie,{children:[n.jsx(Ae,{className:"inline-flex items-center text-xs text-primary-600",children:t}),n.jsx(De,{side:"top",children:r})]})})}function Fi({text:e,align:t,timestamp:r,forceVisible:o=!1}){const[a,i]=s.useState(!1),[l,c]=s.useState("idle"),u=s.useRef(null),d=s.useRef(null),f=s.useRef(null),[m,p]=s.useState(()=>{if(typeof window>"u")return!0;try{const w=localStorage.getItem("opencami-tts-enabled");return w===null?!0:w==="true"}catch{return!0}});s.useEffect(()=>{function w(y){y.key==="opencami-tts-enabled"&&p(y.newValue===null?!0:y.newValue==="true")}return window.addEventListener("storage",w),()=>window.removeEventListener("storage",w)},[]),s.useEffect(()=>()=>{f.current?.abort(),u.current&&(u.current.pause(),u.current=null),d.current&&(URL.revokeObjectURL(d.current),d.current=null)},[]);const h=async()=>{try{await navigator.clipboard.writeText(e),i(!0),window.setTimeout(()=>i(!1),1400)}catch{i(!1)}},v=async()=>{if(l==="playing"){f.current?.abort(),u.current&&(u.current.pause(),u.current=null),d.current&&(URL.revokeObjectURL(d.current),d.current=null),c("idle");return}f.current?.abort();const w=new AbortController;f.current=w,c("loading");try{const y=await fetch("/api/tts",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({text:e}),signal:w.signal});if(!y.ok)throw new Error("TTS failed");const P=await y.blob(),I=URL.createObjectURL(P);d.current=I;const z=new Audio(I);u.current=z,z.onended=()=>{c("idle"),d.current&&(URL.revokeObjectURL(d.current),d.current=null),u.current=null},z.onerror=()=>{c("idle"),d.current&&(URL.revokeObjectURL(d.current),d.current=null),u.current=null},await z.play(),c("playing")}catch(y){if(y instanceof Error&&y.name==="AbortError"){c("idle");return}c("idle"),d.current&&(URL.revokeObjectURL(d.current),d.current=null),u.current=null}},g=t==="end"?"justify-end":"justify-start",j=t==="start"&&m&&e.trim().length>0;return n.jsxs("div",{className:O("flex items-center gap-2 text-xs text-primary-600 transition-opacity group-hover:opacity-100 group-focus-within:opacity-100 duration-100 ease-out",o?"opacity-100":"opacity-0",g),children:[n.jsx(Me,{children:n.jsxs(Ie,{children:[n.jsx(Ae,{type:"button",onClick:()=>{h().catch(()=>{})},className:"inline-flex items-center justify-center rounded border border-transparent bg-transparent p-1 text-primary-700 hover:text-primary-900 hover:bg-primary-100",children:n.jsx(Z,{icon:a?Vn:ms,size:16,strokeWidth:1.6})}),n.jsx(De,{side:"top",children:"Copy"})]})}),j&&n.jsx(Me,{children:n.jsxs(Ie,{children:[n.jsx(Ae,{type:"button",onClick:()=>{v().catch(()=>{})},disabled:l==="loading",className:O("inline-flex items-center justify-center rounded border border-transparent bg-transparent p-1 text-primary-700 hover:text-primary-900 hover:bg-primary-100",l==="loading"&&"opacity-60 cursor-wait"),children:n.jsx(Z,{icon:l==="loading"?ps:l==="playing"?qn:hs,size:16,strokeWidth:1.6,className:O(l==="loading"&&"animate-spin")})}),n.jsx(De,{side:"top",children:l==="loading"?"Generating speech…":l==="playing"?"Stop":"Listen"})]})}),n.jsx(Hi,{timestamp:r})]})}function vr({children:e,className:t,...r}){return n.jsx("div",{className:O("flex gap-3 w-full",t),...r,children:e})}function Wi({children:e,markdown:t=!1,className:r,...o}){const a=O("rounded-[12px] break-words whitespace-normal min-w-0 max-w-full overflow-x-hidden",r);return t?n.jsx(Vs,{className:a,...o,children:e}):n.jsx("div",{className:a,...o,children:e})}function Xi({toolPart:e,defaultOpen:t=!1}){const{state:r,input:o,output:a,toolCallId:i}=e,l=(d,f=3200)=>{const m=d===void 0?"undefined":d;let p;if(typeof m=="string")try{p=JSON.stringify(JSON.parse(m),null,2)}catch{p=m}else p=JSON.stringify(m,null,2);return p.length<=f?p:`${p.slice(0,f).trimEnd()}
9
+ …[truncated]`},c=r==="output-error"?Pt:r==="output-available"?Yn:gs,u=r==="output-error"?"text-red-600/80":r==="output-available"?"text-green-600/80":"text-primary-500/80";return n.jsx("div",{className:"inline-flex flex-col w-full",children:n.jsxs(en,{defaultOpen:t,children:[n.jsxs(tn,{render:n.jsx(we,{variant:"ghost",className:"h-auto w-full justify-start gap-1.5 rounded-md px-1.5 py-1"}),children:[n.jsx(Z,{icon:c,size:12,strokeWidth:1.7,className:u}),n.jsx("span",{className:"text-sm font-medium text-primary-900",children:e.type}),n.jsx(Z,{icon:Jn,size:14,strokeWidth:1.5,className:"ml-auto text-primary-700/80 transition-transform duration-150 group-data-panel-open:rotate-180"})]}),n.jsx(nn,{className:"mt-1",children:n.jsxs("div",{className:"space-y-2 rounded-md border border-primary-200 bg-primary-100/70 p-2",children:[n.jsxs("div",{className:"rounded border border-primary-200 bg-primary-50 px-2 py-1.5",children:[n.jsx("div",{className:"text-[11px] font-medium text-primary-600",children:"Tool"}),n.jsx("div",{className:"font-mono text-xs text-primary-800 break-all",children:e.type})]}),o&&Object.keys(o).length>0&&n.jsxs("div",{className:"rounded border border-primary-200 bg-primary-50 px-2 py-1.5",children:[n.jsx("h4",{className:"mb-1 text-[11px] font-medium text-primary-600",children:"Input"}),n.jsx("pre",{className:"max-h-44 overflow-auto whitespace-pre-wrap break-all font-mono text-xs leading-relaxed text-primary-800",children:l(o)})]}),a!=null&&n.jsxs("div",{className:"rounded border border-primary-200 bg-primary-50 px-2 py-1.5",children:[n.jsx("h4",{className:"mb-1 text-[11px] font-medium text-primary-600",children:"Output"}),n.jsx("pre",{className:"max-h-44 overflow-auto whitespace-pre-wrap break-all font-mono text-xs leading-relaxed text-primary-800",children:l(a)})]}),r==="output-error"&&e.errorText&&n.jsxs("div",{className:"rounded border border-red-200 bg-red-50 px-2 py-1.5",children:[n.jsx("h4",{className:"mb-1 text-[11px] font-medium text-red-600",children:"Error"}),n.jsx("div",{className:"text-xs text-red-700",children:e.errorText})]}),i&&n.jsxs("div",{className:"text-[11px] text-primary-500/80 font-mono tabular-nums",children:["ID: ",i.slice(0,16),"..."]})]})})]})})}const Bi=s.lazy(()=>et(()=>import("./thinking-BmoLlbFC.js"),__vite__mapDeps([26,1,3,17,18,7,5,6,8,14,19,4,9,2,11,15,20,13,21,22,23,16,24])).then(e=>({default:e.Thinking}))),Yi=s.lazy(()=>et(()=>import("./search-sources-badge-Du8KpUEb.js"),__vite__mapDeps([27,1,3])).then(e=>({default:e.SearchSourcesBadge})));function Gi(e,t){const r=t!==void 0,o=t?.isError??!1;let a;r?o?a="output-error":a="output-available":a="input-available";let i;o&&t?.content?.[0]?.type==="text"&&(i=t.content[0].text||"Unknown error");const l=t?.content?.map(u=>u.type==="text"?String(u.text??""):"").join("").trim(),c=t?.details??(l&&l.length>0?l:void 0);return{type:e.name||"unknown",state:a,input:e.arguments,output:c,toolCallId:e.id,errorText:i}}function Ln(e){return Ye(e).map(r=>{const o=r.id??"",a=r.name??"",i=r.partialJson??"",l=r.arguments?JSON.stringify(r.arguments):"";return`${o}|${a}|${i}|${l}`}).join("||")}function Vi(e){if(!e)return"missing";const r=(Array.isArray(e.content)?e.content:[]).map(a=>a.type==="text"?String(a.text??""):"").join("").trim(),o=e.details?JSON.stringify(e.details):"";return`${e.toolCallId??""}|${e.toolName??""}|${e.isError?"1":"0"}|${r}|${o}`}function Pn(e,t){if(!t)return"";const r=Ye(e);return r.length===0?"":r.map(o=>o.id?Vi(t.get(o.id)):"missing").join("||")}function qi(e){if(typeof e=="number"&&Number.isFinite(e))return e<1e12?e*1e3:e;if(typeof e=="string"){const t=Date.parse(e);if(!Number.isNaN(t))return t}return null}function _n(e){const t=[e.createdAt,e.created_at,e.timestamp,e.time,e.ts];for(const r of t){const o=qi(r);if(o)return o}return null}function rn(e){const r=(Array.isArray(e.content)?e.content:[]).find(o=>o.type==="thinking");return r&&"thinking"in r?String(r.thinking??""):null}function Ji(e){const t=Array.isArray(e.content)?e.content:[],r=[];for(const o of t)o.type==="image"&&"source"in o&&typeof o.source?.data=="string"&&r.push(o);return r}const ut=/^📎 Uploaded file:\s*(\/uploads\/\S+)\s*$/;function Qi(e){if(e===null||Number.isNaN(e))return"Unknown size";if(e<1024)return`${e} B`;const t=["KB","MB","GB","TB"];let r=e/1024,o=0;for(;r>=1024&&o<t.length-1;)r/=1024,o++;return`${r.toFixed(1)} ${t[o]}`}function Zi(e){if(!e)return[];const t=e.trimStart();if(t.startsWith(">")||t.startsWith("```"))return[];const r=e.split(`
10
+ `),o=[];for(const i of r){if(ut.test(i)){o.push(i);continue}if(o.length>0&&i.trim()===""){o.push(i);continue}break}const a=r[0]??"";return ut.test(a)?o.filter(i=>ut.test(i)):[]}function ea(e){const t=[],r=new Set;for(const o of Zi(e)){const i=o.match(ut)?.[1];!i||r.has(i)||(r.add(i),t.push({path:i,filename:i.split("/").pop()||i}))}return t}function ta(e){const t=e.split(`
11
+ `);if(!ut.test(t[0]??""))return e.trim();let r=0;for(;r<t.length&&ut.test(t[r]);)r++;for(;r<t.length&&t[r].trim()==="";)r++;return t.slice(r).join(`
12
+ `).replace(/\n{3,}/g,`
13
+
14
+ `).trim()}function na({message:e,toolResultsByCallId:t,forceActionsVisible:r=!1,isStreaming:o=!1,isLastAssistant:a=!1,aggregatedSearchSources:i,wrapperRef:l,wrapperClassName:c,wrapperScrollMarginTop:u,messageDomId:d,highlighted:f=!1}){const{settings:m}=qs(),p=e.role||"assistant",h=Le(e),v=rn(e),g=Ji(e),j=p==="user",w=s.useMemo(()=>g.map(E=>`data:${E.source.media_type};base64,${E.source.data}`),[g]),y=Jt(e),P=Lt(),I=Os(E=>E.openInEditor),z=s.useMemo(()=>ea(h),[h]),[T,J]=s.useState({}),B=s.useMemo(()=>ta(h),[h]);s.useEffect(()=>{let E=!1;async function k(){const R={};await Promise.all(z.map(async _=>{try{const A=await fetch(`/api/files/info?path=${encodeURIComponent(_.path)}`);if(!A.ok){R[_.path]=null;return}const X=await A.json();R[_.path]=typeof X.size=="number"?X.size:null}catch{R[_.path]=null}})),E||J(R)}return z.length>0?k():J({}),()=>{E=!0}},[z]);const H=async E=>{I(E),await P({to:"/files"})},te=p==="assistant"?Ye(e):[],U=te.length>0,S=a&&!o&&m.showSearchSources&&i?i:[];return n.jsxs("div",{ref:l,id:d,"data-message-id":d,style:{contentVisibility:"auto",containIntrinsicSize:"auto 120px",...typeof u=="number"?{scrollMarginTop:`${u}px`}:void 0},className:O("opencami-message-item group mx-auto flex w-full max-w-[var(--opencami-chat-width)] flex-col gap-1 py-[var(--opencami-msg-padding-y)]",c,f&&"opencami-message-highlight",j?"items-end":"items-start"),children:[v&&m.showReasoningBlocks&&n.jsx("div",{className:"w-full max-w-[var(--opencami-chat-width)]",children:n.jsx(s.Suspense,{fallback:null,children:n.jsx(Bi,{content:v})})}),g.length>0&&n.jsx("div",{className:O("flex flex-wrap gap-2 mb-2",j?"justify-end":"justify-start"),children:g.map((E,k)=>n.jsx("img",{src:w[k],alt:`Attachment ${k+1}`,loading:"lazy",decoding:"async",fetchPriority:"low",className:"max-w-[300px] max-h-[300px] rounded-lg object-cover"},k))}),z.length>0&&n.jsx("div",{className:O("mb-2 flex w-full flex-col gap-2",j?"items-end":"items-start"),children:z.map(E=>n.jsxs("button",{type:"button",onClick:()=>{H(E.path)},className:"flex max-w-full items-center gap-3 rounded-xl border border-primary-200 bg-primary-50 px-3 py-2 text-left hover:bg-primary-100",children:[n.jsx("div",{className:"flex h-8 w-8 items-center justify-center rounded-lg bg-primary-100",children:n.jsx(Z,{icon:Qn,size:18,className:"text-primary-600"})}),n.jsxs("div",{className:"min-w-0",children:[n.jsx("p",{className:"truncate text-sm font-medium text-primary-900",children:E.filename}),n.jsx("p",{className:"text-xs text-primary-600",children:Qi(T[E.path]??null)})]})]},E.path))}),n.jsx(vr,{className:O("min-w-0 max-w-full",j?"flex-row-reverse":""),children:n.jsx(Wi,{markdown:!j,isStreaming:!j&&o,className:O("text-primary-900 opencami-text-size min-w-0 max-w-full",j?"opencami-message-user bg-primary-100 px-4 py-[var(--opencami-user-bubble-py)] max-w-[85%]":"opencami-message-assistant bg-transparent w-full",!j&&o&&"stream-fade-in"),children:B})}),U&&m.showToolMessages&&n.jsx("div",{className:"mt-2 flex w-full min-w-0 max-w-[var(--opencami-chat-width)] flex-col gap-3 overflow-x-hidden",children:te.map(E=>{const k=E.id?t?.get(E.id):void 0,R=Gi(E,k);return n.jsx(Xi,{toolPart:R,defaultOpen:!1},E.id||E.name)})}),S.length>0&&n.jsx("div",{className:"w-full max-w-[var(--opencami-chat-width)]",children:n.jsx(s.Suspense,{fallback:null,children:n.jsx(Yi,{sources:S})})}),!U&&n.jsx(Fi,{text:h,timestamp:y,align:j?"end":"start",forceVisible:r})]})}function ra(e,t){return!(e.forceActionsVisible!==t.forceActionsVisible||e.isStreaming!==t.isStreaming||e.isLastAssistant!==t.isLastAssistant||e.aggregatedSearchSources!==t.aggregatedSearchSources||e.wrapperClassName!==t.wrapperClassName||e.wrapperRef!==t.wrapperRef||e.wrapperScrollMarginTop!==t.wrapperScrollMarginTop||e.messageDomId!==t.messageDomId||e.highlighted!==t.highlighted||(e.message.role||"assistant")!==(t.message.role||"assistant")||Le(e.message)!==Le(t.message)||rn(e.message)!==rn(t.message)||Ln(e.message)!==Ln(t.message)||Pn(e.message,e.toolResultsByCallId)!==Pn(t.message,t.toolResultsByCallId)||_n(e.message)!==_n(t.message))}const Xt=s.memo(na,ra);function sa({className:e,variant:t="outline",scrollRef:r,...o}){const[a,i]=s.useState(!0),[l,c]=s.useState(!1),u=s.useRef(0),d=s.useCallback(()=>{const f=r.current;if(!f)return;const m=Math.abs(f.scrollHeight-f.scrollTop-f.clientHeight)<100;i(m)},[r]);return s.useLayoutEffect(()=>{const f=r.current;if(!f)return;const m=()=>{u.current=f.scrollTop,d()},p=new MutationObserver(()=>{f&&(f.scrollTop!==u.current&&(u.current=f.scrollTop),d())});return d(),f.addEventListener("scroll",m),p.observe(f,{childList:!0,subtree:!0}),()=>{f.removeEventListener("scroll",m),p.disconnect()}},[d,r]),s.useLayoutEffect(()=>{if(a){c(!1);return}const f=window.setTimeout(()=>{c(!0)},200);return()=>window.clearTimeout(f)},[a]),n.jsx(we,{variant:"secondary",size:"icon-sm",className:O("pointer-events-auto rounded-full shadow-md","transition-all duration-100 ease-in-out",!a&&l?"translate-y-0 scale-100 opacity-100":"pointer-events-none translate-y-4 scale-98 opacity-0",e),onClick:()=>{const f=r.current;f&&(f.scrollTop=f.scrollHeight,i(!0))},...o,children:n.jsx(Z,{icon:Jn,size:18,strokeWidth:1.8})})}function oa({className:e,viewportRef:t,scrollRef:r,viewportProps:o}){return n.jsxs(gr,{className:O("relative flex flex-1 min-h-0 flex-col",e),children:[n.jsx(yr,{className:"relative will-change-transform overflow-x-hidden",ref:t,...o}),n.jsx("div",{className:"relative mx-auto w-full min-w-0 max-w-full px-5 sm:max-w-[768px]",children:n.jsx("div",{className:"pointer-events-none absolute bottom-10 right-10 z-50",children:n.jsx(sa,{scrollRef:r})})}),n.jsx(xr,{orientation:"vertical",children:n.jsx(wr,{})}),n.jsx(di,{})]})}function ia(e,t){if(e===t)return!0;const r=Object.keys(e),o=Object.keys(t);if(r.length!==o.length)return!1;for(const a of r)if(e[a]!==t[a])return!1;return!0}function aa(e,t){return!(e.className!==t.className||e.viewportRef!==t.viewportRef||e.scrollRef!==t.scrollRef||!ia(e.viewportProps,t.viewportProps))}const la=s.memo(oa,aa);function ca({viewportNode:e,children:t}){return e?Xr.createPortal(n.jsx("div",{className:"relative flex w-full min-w-0 max-w-full flex-col overflow-x-hidden",children:t}),e):null}function ua({children:e,className:t,onUserScroll:r,...o}){const a=s.useRef(null),[i,l]=s.useState(null),c=s.useCallback(function(d){a.current=d,l(d)},[]);return s.useLayoutEffect(()=>{const u=a.current;if(!u)return;const d=()=>{r?.(u.scrollTop)};return u.addEventListener("scroll",d),()=>u.removeEventListener("scroll",d)},[r]),n.jsxs(n.Fragment,{children:[n.jsx(la,{className:t,viewportRef:c,scrollRef:a,viewportProps:o}),n.jsx(ca,{viewportNode:i,children:e})]})}const da=s.memo(ua);function fa({children:e,className:t,...r}){return n.jsx("div",{className:O("flex w-full min-w-0 max-w-full flex-col min-h-full overflow-x-hidden",t),...r,children:n.jsx("div",{className:"mx-auto w-full min-w-0 max-w-full px-2 md:px-5 sm:max-w-[768px] flex flex-col flex-1 min-h-full overflow-x-hidden",children:n.jsx("div",{className:"flex min-w-0 max-w-full flex-col space-y-3 md:space-y-6",children:e})})})}function ma({...e}){return n.jsx("div",{className:"h-px w-full shrink-0 scroll-mt-4 pt-6","aria-hidden":"true",...e})}function pa({as:e="span",className:t,duration:r=4,spread:o=20,children:a,...i}){const l=Math.min(Math.max(o,5),45),c=e;return n.jsx(c,{className:O("bg-size-[200%_auto] bg-clip-text font-medium text-transparent","animate-[shimmer_4s_infinite_linear]",t),style:{backgroundImage:`linear-gradient(to right, var(--color-primary-600) ${50-l}%, var(--color-primary-950) 50%, var(--color-primary-600) ${50+l}%)`,animationDuration:`${r}s`},...i,children:a})}function ha({className:e}){return n.jsxs("div",{className:O("flex items-center gap-2",e),children:[n.jsxs("div",{className:"relative flex h-1.5 w-1.5",children:[n.jsx("span",{className:"animate-ping absolute inline-flex h-full w-full rounded-full bg-primary-400 opacity-75"}),n.jsx("span",{className:"relative inline-flex rounded-full h-1.5 w-1.5 bg-size-[200%_auto] animate-[shimmer_2s_infinite_linear]",style:{backgroundImage:"linear-gradient(to right, var(--color-primary-600) 0%, var(--color-primary-950) 50%, var(--color-primary-600) 100%)"}})]}),n.jsx(pa,{className:"text-sm",duration:2,children:"Generating..."})]})}const Kn=s.lazy(()=>et(()=>import("./follow-up-suggestions-BSCMXRXh.js"),__vite__mapDeps([28,1,3,17,18,7,5,6,8,14,19,4,9,2,11,15,20,13,21,22,23,16,24])).then(e=>({default:e.FollowUpSuggestions})));function ga({messages:e,loading:t,empty:r,emptyState:o,notice:a,noticePosition:i="start",waitingForResponse:l,isStreaming:c=!1,sessionKey:u,pinToTop:d,pinGroupMinHeight:f,headerHeight:m,contentStyle:p,onFollowUpClick:h,jumpToMessageId:v}){const g=s.useRef(null),j=s.useRef(null),w=s.useRef(!1),y=s.useRef(d),P=s.useRef(void 0),[I,z]=s.useState(null),T=s.useMemo(()=>e.filter(x=>x.role!=="toolResult"),[e]),J=s.useDeferredValue(T),B=s.useMemo(()=>{const x=new Map;for(const L of e){if(L.role!=="toolResult")continue;const K=L.toolCallId;typeof K=="string"&&K.trim().length>0&&x.set(K,L)}return x},[e]),H=s.useDeferredValue(B),te=s.useMemo(()=>{const x=[];for(const L of J){if(L.role!=="assistant")continue;const K=Ye(L);for(const G of K){if(!G.id)continue;const q=G.name==="web_search",V=G.name==="web_fetch",Q=G.name==="exec";if(!q&&!V&&!Q)continue;const oe=H.get(G.id),re=oe?.content?.map(Y=>Y.type==="text"?String(Y.text??""):"").join("").trim()??"";x.push([G.id,G.name??"",typeof G.arguments?.url=="string"?G.arguments.url:"",oe?.isError?"1":"0",re].join("::"))}}return x.join("||")},[J,H]),U=s.useMemo(()=>{const x=q=>q?q.replace(/SECURITY NOTICE:[\s\S]*?<<<EXTERNAL_UNTRUSTED_CONTENT>>>/g,"").replace(/<<<\/?EXTERNAL_UNTRUSTED_CONTENT>>>/g,"").replace(/<<<\/?END_EXTERNAL_UNTRUSTED_CONTENT>>>/g,"").replace(/Source: Web (?:Search|Fetch)\n---/g,"").replace(/\n{2,}/g,`
15
+ `).trim():"",L=(q,V,Q)=>{try{const oe=JSON.parse(q),re=Array.isArray(oe)?oe:oe?.results??oe?.web?.results??[];if(!Array.isArray(re))return!1;let Y=!1;for(const ae of re)ae?.url&&ae?.title&&!Q.has(ae.url)&&(Q.add(ae.url),V.push({title:x(ae.title),url:ae.url,snippet:x(ae.description||ae.snippet||ae.content||"")}),Y=!0);return Y}catch{return!1}},K=[],G=new Set;for(const q of J){if(q.role!=="assistant")continue;const V=Ye(q);for(const Q of V){if(!Q.id)continue;const oe=Q.name==="web_search",re=Q.name==="web_fetch",Y=Q.name==="exec";if(!oe&&!re&&!Y)continue;const ae=H.get(Q.id);if(!ae)continue;const me=ae.content?.map(ee=>ee.type==="text"?String(ee.text??""):"").join("").trim();if(me){if(oe||Y){if(Y&&(!me.includes('"results"')||!me.includes('"url"')))continue;let ee=me;const ie=me.indexOf("{");ie>0&&(ee=me.slice(ie));const ge=ee.lastIndexOf("}");ge>0&&(ee=ee.slice(0,ge+1)),L(ee,K,G)}else if(re){const ee=Q.arguments?.url;if(ee&&!G.has(ee)){G.add(ee);let ie;try{ie=new URL(ee).hostname}catch{ie=ee}K.push({title:ie,url:ee})}}}}}return K},[te,J,H]),S=T.map((x,L)=>({message:x,index:L})).filter(({message:x})=>x.role!=="user").map(({index:x})=>x).pop(),E=T.map((x,L)=>({message:x,index:L})).filter(({message:x})=>x.role==="assistant").map(({index:x})=>x).pop(),k=T.map((x,L)=>({message:x,index:L})).filter(({message:x})=>x.role==="user").map(({index:x})=>x).pop(),R=l&&(typeof k!="number"||typeof S!="number"||S<k),_=typeof k=="number"?k:-1,A=d&&_>=0,X=typeof E=="number"?T[E]:void 0,C=X?Le(X):"",D=!l&&!c&&C.length>0&&h!==void 0&&(typeof k!="number"||typeof E!="number"||E>k);return s.useLayoutEffect(()=>{if(!t){if(d){const x=!y.current||P.current!==k;y.current=!0,P.current=k,x&&j.current&&(w.current=!0,j.current.scrollIntoView({behavior:"auto",block:"start"}),window.setTimeout(()=>{w.current=!1},0));return}y.current=!1,P.current=k,g.current&&(w.current=!0,g.current.scrollIntoView({behavior:"auto",block:"end"}),window.setTimeout(()=>{w.current=!1},0))}},[t,T.length,u,d,k]),s.useEffect(()=>{if(!v||t)return;const x=document.getElementById(`message-${v}`);if(!x)return;x.scrollIntoView({behavior:"smooth",block:"center"}),z(v);const L=window.setTimeout(()=>{z(K=>K===v?null:K)},1800);return()=>window.clearTimeout(L)},[v,t,T]),n.jsx(da,{className:"flex-1 min-h-0 -mb-4",children:n.jsxs(fa,{className:"pt-6",style:p,children:[a&&i==="start"?a:null,r&&!a?o??n.jsx("div",{"aria-hidden":!0}):A?n.jsxs(n.Fragment,{children:[T.slice(0,_).map((x,L)=>{const K=typeof x.id=="string"?x.id:void 0,G=K||L,q=typeof S=="number"&&L===S,V=typeof S=="number"&&L===S,Q=x.role==="assistant"&&Ye(x).length>0;return n.jsx(Xt,{message:x,toolResultsByCallId:Q?B:void 0,forceActionsVisible:q,isStreaming:V&&c,isLastAssistant:V,aggregatedSearchSources:V?U:void 0,messageDomId:K?`message-${K}`:void 0,highlighted:I===K},G)}),n.jsxs("div",{className:"flex flex-col gap-[var(--opencami-msg-gap)]",style:{minHeight:`${Math.max(0,f)}px`},children:[T.slice(_).map((x,L)=>{const K=_+L,G=typeof x.id=="string"?x.id:void 0,q=G||K,V=typeof S=="number"&&K===S,Q=typeof S=="number"&&K===S,oe=K===k?j:void 0,re=K===k?"scroll-mt-0":void 0,Y=K===k?m:void 0,ae=x.role==="assistant"&&Ye(x).length>0;return n.jsx(Xt,{message:x,toolResultsByCallId:ae?B:void 0,forceActionsVisible:V,isStreaming:Q&&c,isLastAssistant:Q,aggregatedSearchSources:Q?U:void 0,wrapperRef:oe,wrapperClassName:re,wrapperScrollMarginTop:Y,messageDomId:G?`message-${G}`:void 0,highlighted:I===G},q)}),R?n.jsx("div",{className:"py-2",children:n.jsx(ha,{})}):null,D&&h?n.jsx(s.Suspense,{fallback:null,children:n.jsx(Kn,{responseText:C,onSuggestionClick:h,disabled:l})}):null]})]}):n.jsxs(n.Fragment,{children:[T.map((x,L)=>{const K=typeof x.id=="string"?x.id:void 0,G=K||L,q=typeof S=="number"&&L===S,V=typeof S=="number"&&L===S,Q=x.role==="assistant"&&Ye(x).length>0;return n.jsx(Xt,{message:x,toolResultsByCallId:Q?B:void 0,forceActionsVisible:q,isStreaming:V&&c,isLastAssistant:V,aggregatedSearchSources:V?U:void 0,messageDomId:K?`message-${K}`:void 0,highlighted:I===K},G)}),D&&h?n.jsx(s.Suspense,{fallback:null,children:n.jsx(Kn,{responseText:C,onSuggestionClick:h,disabled:l})}):null]}),a&&i==="end"?a:null,n.jsx(ma,{ref:g})]})})}function ya(e,t){return e.messages===t.messages&&e.loading===t.loading&&e.empty===t.empty&&e.emptyState===t.emptyState&&e.notice===t.notice&&e.noticePosition===t.noticePosition&&e.waitingForResponse===t.waitingForResponse&&e.isStreaming===t.isStreaming&&e.sessionKey===t.sessionKey&&e.pinToTop===t.pinToTop&&e.pinGroupMinHeight===t.pinGroupMinHeight&&e.headerHeight===t.headerHeight&&e.contentStyle===t.contentStyle&&e.onFollowUpClick===t.onFollowUpClick&&e.jumpToMessageId===t.jumpToMessageId}const xa=s.memo(ga,ya),sn=ir()(or(e=>({level:"low",setLevel:t=>e({level:t})}),{name:"thinking-level"}));function wa(){const e=sn(r=>r.level),t=sn(r=>r.setLevel);return{level:e,setLevel:t}}const Bt=[{value:"off",label:"Off",description:"No reasoning",shortLabel:"Off"},{value:"low",label:"Low",description:"Think",shortLabel:"Low"},{value:"medium",label:"Medium",description:"Think harder",shortLabel:"Medium"},{value:"high",label:"High",description:"Ultrathink",shortLabel:"High"}];function ba({className:e}){const{level:t,setLevel:r}=wa(),o=Bt.find(a=>a.value===t)??Bt[1];return n.jsxs(ln,{children:[n.jsxs(cn,{className:O("inline-flex h-7 items-center gap-2 rounded-md px-2 text-xs font-[450] text-primary-600 hover:text-primary-900 hover:bg-primary-100",e),children:[n.jsx(Z,{icon:Vt,size:20,strokeWidth:1.5,className:O(t==="off"?"text-primary-400":"text-primary-700")}),n.jsx("span",{className:"text-pretty",children:o.shortLabel})]}),n.jsx(un,{side:"top",align:"start",className:"min-w-[190px]",children:Bt.map(a=>n.jsxs(Ze,{onClick:()=>r(a.value),className:"justify-between",children:[n.jsxs("span",{className:"flex flex-col text-pretty",children:[n.jsx("span",{className:"text-sm text-primary-900",children:a.label}),n.jsx("span",{className:"text-xs text-primary-500",children:a.description})]}),t===a.value&&n.jsx(Z,{icon:Vn,size:20,strokeWidth:1.5,className:"text-primary-600"})]},a.value))})]})}function Sa({commands:e,selectedIndex:t,onSelect:r,className:o}){return e.length===0?null:n.jsx("div",{className:O("absolute left-2 right-2 md:left-5 md:right-5 bottom-full mb-2 z-20 rounded-xl border border-white/10 bg-neutral-900/95 shadow-2xl backdrop-blur-sm overflow-hidden",o),role:"listbox","aria-label":"Slash commands",children:n.jsx("div",{className:"max-h-56 overflow-y-auto p-1",children:e.map((a,i)=>{const l=i===t;return n.jsx("button",{type:"button",role:"option","aria-selected":l,onMouseDown:c=>{c.preventDefault(),r(a)},className:O("w-full rounded-md px-3 py-2 text-left transition-colors",l?"bg-neutral-800":"hover:bg-neutral-800/80"),children:n.jsxs("div",{className:"flex items-start gap-3",children:[n.jsx("code",{className:"min-w-[90px] font-mono text-xs text-primary-300",children:a.command}),n.jsx("span",{className:"text-xs text-neutral-300",children:a.description})]})},a.command)})})})}const va=s.memo(Sa),jr=s.createContext({isLoading:!1,value:"",setValue:()=>{},maxHeight:240,onSubmit:void 0,disabled:!1,textareaRef:Br.createRef()});let dt=null,zn=!1;function ja(){zn||typeof window>"u"||(zn=!0,window.addEventListener("keydown",e=>{if(e.defaultPrevented||e.metaKey||e.ctrlKey||e.altKey)return;const t=e.target;if(!t)return;const r=t.tagName.toLowerCase();if(r==="input"||r==="textarea"||r==="select"||t.isContentEditable)return;const o=e.key.length===1,a=e.key==="Backspace";!o&&!a||!dt||dt.disabled||dt.focus()}))}function kr(){return s.useContext(jr)}function ka({className:e,isLoading:t=!1,maxHeight:r=240,value:o,onValueChange:a,onSubmit:i,children:l,disabled:c=!1,onClick:u,...d}){const[f,m]=s.useState(o||""),p=s.useRef(null);ja();function h(g){m(g),a?.(g)}function v(g){c||p.current?.focus(),u?.(g)}return n.jsx(Me,{children:n.jsx(jr.Provider,{value:{isLoading:t,value:o??f,setValue:a??h,maxHeight:r,onSubmit:i,disabled:c,textareaRef:p},children:n.jsx("div",{onClick:v,className:O("bg-surface cursor-text rounded-[22px] outline outline-ink/10 shadow-[0px_12px_32px_0px_rgba(0,0,0,0.05)] py-3 gap-3 flex flex-col",c&&"cursor-not-allowed opacity-60",e),...d,children:l})})})}function Ca({className:e,onKeyDown:t,disableAutosize:r=!1,inputRef:o,...a}){const{value:i,setValue:l,maxHeight:c,onSubmit:u,disabled:d,textareaRef:f}=kr();function m(g){!g||r||(g.style.height="auto",typeof c=="number"?g.style.height=`${Math.min(g.scrollHeight,c)}px`:g.style.height=`min(${g.scrollHeight}px, ${c})`)}function p(g){f.current=g,typeof o=="function"?o(g):o&&"current"in o&&(o.current=g),g?dt=g:dt===g&&(dt=null),m(g)}s.useLayoutEffect(()=>{if(!f.current||r)return;const g=f.current;g.style.height="auto",typeof c=="number"?g.style.height=`${Math.min(g.scrollHeight,c)}px`:g.style.height=`min(${g.scrollHeight}px, ${c})`},[i,c,r]);function h(g){m(g.target),l(g.target.value)}function v(g){g.key==="Enter"&&!g.shiftKey&&(g.preventDefault(),u?.()),t?.(g)}return n.jsx("textarea",{ref:p,value:i,onChange:h,onKeyDown:v,className:O("text-primary-950 opencami-text-size min-h-[28px] w-full resize-none border-none bg-transparent shadow-none outline-none focus-visible:ring-0 pl-4 pr-1 placeholder:text-primary-500",e),rows:1,readOnly:d,"aria-disabled":d,...a})}function Ea({children:e,className:t,...r}){return n.jsx("div",{className:O("flex items-center gap-2",t),...r,children:e})}function Un({tooltip:e,children:t,className:r,side:o="top",...a}){const{disabled:i}=kr();return n.jsxs(Ie,{...a,children:[n.jsx(Ae,{disabled:i,onClick:l=>l.stopPropagation(),children:t}),n.jsx(De,{side:o,className:r,children:e})]})}const Cr="opencami-personas-enabled",on="opencami-active-persona";function Na(){if(typeof window>"u")return!0;try{const e=localStorage.getItem(Cr);return e===null?!0:e==="true"}catch{return!0}}function Ta(){if(typeof window>"u")return null;try{const e=localStorage.getItem(on);return e?JSON.parse(e):null}catch{return null}}function $n(e){if(!(typeof window>"u"))try{e?localStorage.setItem(on,JSON.stringify(e)):localStorage.removeItem(on)}catch{}}const Ra={core:"Core",creative:"Creative",curator:"Curator",learning:"Learning",lifestyle:"Lifestyle",professional:"Professional"};function Ma({className:e,onSelect:t}){const[r,o]=s.useState({}),[a,i]=s.useState(null),[l,c]=s.useState(!0),[u,d]=s.useState(!1),[f,m]=s.useState(Na),p=s.useRef(null);s.useEffect(()=>{const j=w=>{w.key===Cr&&m(w.newValue===null?!0:w.newValue==="true")};return window.addEventListener("storage",j),()=>window.removeEventListener("storage",j)},[]),s.useEffect(()=>{let j=!0;async function w(){p.current?.abort();const y=new AbortController;p.current=y;try{c(!0);const P=await fetch("/api/personas",{signal:y.signal});if(!P.ok){d(!1);return}const I=await P.json();if(!j)return;I.ok&&I.available?(o(I.personas),d(!0),i(Ta())):d(!1)}catch(P){if(P instanceof Error&&P.name==="AbortError"||!j)return;d(!1)}finally{j&&c(!1)}}return w(),()=>{j=!1,p.current?.abort()}},[]);const h=s.useCallback(j=>{i(j),$n(j),t(`/persona ${j.id}`)},[t]),v=s.useCallback(()=>{i(null),$n(null),t("/persona exit")},[t]);if(l||!u||!f)return null;const g=Object.entries(r);return g.length===0?null:n.jsxs(ln,{children:[n.jsxs(cn,{className:O("inline-flex h-7 items-center gap-1.5 rounded-md px-2 text-xs font-[450] text-primary-600 hover:text-primary-900 hover:bg-primary-100",e),children:[n.jsx("span",{className:"text-sm","aria-hidden":"true",children:"🎭"}),a?n.jsxs("span",{className:"flex items-center gap-1",children:[n.jsx("span",{children:a.emoji}),n.jsx("span",{children:a.name})]}):n.jsx("span",{children:"Persona"})]}),n.jsxs(un,{side:"top",align:"start",className:"w-[300px] max-h-[360px] overflow-y-auto",children:[a&&n.jsxs(n.Fragment,{children:[n.jsxs(Ze,{onClick:v,className:"text-red-600 hover:bg-red-50",children:[n.jsx("span",{className:"text-sm",children:"✕"}),n.jsx("span",{children:"Exit Persona"}),n.jsxs("span",{className:"ml-auto text-[10px] text-primary-400",children:[a.emoji," ",a.name]})]}),n.jsx("div",{className:"my-1 h-px bg-primary-200"})]}),g.map(([j,w])=>n.jsxs("div",{children:[n.jsx("div",{className:"px-2 pb-0.5 pt-2 text-[10px] font-semibold uppercase tracking-wider text-primary-400",children:Ra[j]??j}),w.map(y=>n.jsxs(Ze,{onClick:()=>h(y),className:"justify-between",children:[n.jsxs("span",{className:"flex items-center gap-2 min-w-0",children:[n.jsx("span",{className:"text-sm flex-shrink-0",children:y.emoji}),n.jsx("span",{className:"truncate",children:y.name})]}),n.jsx("span",{className:"text-[11px] text-primary-400 truncate ml-2 max-w-[140px]",children:y.description})]},y.id))]},j))]})]})}const Ia=[{command:"/new",description:"Start a new conversation",usage:"/new"},{command:"/reset",description:"Reset conversation context",usage:"/reset"},{command:"/abort",description:"Abort current generation",usage:"/abort"},{command:"/status",description:"Show session status card",usage:"/status"},{command:"/usage",description:"Show token usage",usage:"/usage [off|tokens|full]"},{command:"/models",description:"List available models",usage:"/models"},{command:"/agents",description:"List available agents",usage:"/agents"},{command:"/sessions",description:"List active sessions",usage:"/sessions"},{command:"/model",description:"Switch model for this session",usage:"/model <alias>"},{command:"/reasoning",description:"Toggle reasoning mode",usage:"/reasoning [on|off|stream]"},{command:"/think",description:"Set thinking budget",usage:"/think [off|minimal|low|medium|high]"},{command:"/verbose",description:"Toggle verbose output",usage:"/verbose [on|full|off]"},{command:"/tts",description:"Text-to-speech controls",usage:"/tts [status|off|always]"},{command:"/settings",description:"Show current settings",usage:"/settings"},{command:"/help",description:"Show help",usage:"/help"}];function Aa({className:e,onCommandSelect:t}){const[r,o]=s.useState(!1);function a(i){t?.(i),o(!1)}return n.jsxs(n.Fragment,{children:[n.jsx(we,{variant:"ghost",size:"sm",onClick:()=>o(!0),className:O("h-7 w-7 p-0",e),title:"Show commands (Ctrl+/)",children:n.jsx(Z,{icon:jn,size:16,className:"text-primary-500"})}),r&&n.jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center bg-black/50 backdrop-blur-sm",children:n.jsxs("div",{className:"bg-white dark:bg-neutral-900 border border-primary-200 dark:border-neutral-700 rounded-xl shadow-2xl w-full max-w-lg max-h-[80vh] overflow-hidden",children:[n.jsxs("div",{className:"flex items-center justify-between px-4 py-3 border-b border-primary-200 dark:border-neutral-700 bg-neutral-50 dark:bg-neutral-800",children:[n.jsxs("div",{className:"flex items-center gap-2",children:[n.jsx(Z,{icon:jn,size:18,className:"text-primary-600 dark:text-primary-400"}),n.jsx("h2",{className:"font-semibold text-primary-900 dark:text-white",children:"Slash Commands"})]}),n.jsx(we,{variant:"ghost",size:"sm",onClick:()=>o(!1),className:"h-7 w-7 p-0",children:n.jsx(Z,{icon:Pt,size:16})})]}),n.jsxs("div",{className:"overflow-y-auto max-h-[60vh] p-2 bg-white dark:bg-neutral-900",children:[n.jsx("div",{className:"text-xs text-primary-500 dark:text-neutral-400 px-2 py-1 mb-2",children:"Type these commands in the chat input"}),Ia.map(i=>n.jsxs("button",{onClick:()=>a(i.command),className:"w-full flex items-start gap-3 px-3 py-2 rounded-lg hover:bg-primary-100 dark:hover:bg-neutral-800 transition-colors text-left",children:[n.jsx("code",{className:"text-sm font-mono font-medium text-primary-700 dark:text-primary-300 bg-primary-100 dark:bg-neutral-800 px-1.5 py-0.5 rounded min-w-[80px]",children:i.command}),n.jsxs("div",{className:"flex-1 min-w-0",children:[n.jsx("div",{className:"text-sm text-primary-900 dark:text-neutral-100",children:i.description}),i.usage&&i.usage!==i.command&&n.jsx("div",{className:"text-xs text-primary-500 dark:text-neutral-500 font-mono mt-0.5",children:i.usage})]})]},i.command))]}),n.jsx("div",{className:"px-4 py-2 border-t border-primary-200 dark:border-neutral-700 bg-neutral-50 dark:bg-neutral-800",children:n.jsxs("div",{className:"text-xs text-primary-500 dark:text-neutral-400",children:["Press ",n.jsx("kbd",{className:"px-1 py-0.5 bg-primary-200 dark:bg-neutral-700 rounded text-primary-700 dark:text-neutral-300",children:"Esc"})," to close"]})})]})})]})}const Da=10*1024*1024,ct=1280,Oa=.75,La=300*1024,Pa=["image/png","image/jpeg","image/gif","image/webp"],Er=["pdf","txt","md","csv","json","xml","yaml","yml","log","py","js","ts","html","css"],_a=[".png",".jpg",".jpeg",".gif",".webp",...Er.map(e=>`.${e}`)].join(",");function Ka(){if(typeof document>"u")return!1;try{const e=document.createElement("canvas");return!!(e.getContext&&e.getContext("2d"))}catch{return!1}}async function za(e){if(!Ka())throw new Error("Image compression not available in this browser");return new Promise((t,r)=>{const o=new Image,a=URL.createObjectURL(e),i=()=>{URL.revokeObjectURL(a)};o.onload=()=>{try{let l=o.width,c=o.height;(l>ct||c>ct)&&(l>c?(c=Math.round(c*ct/l),l=ct):(l=Math.round(l*ct/c),c=ct));const u=document.createElement("canvas");u.width=l,u.height=c;const d=u.getContext("2d");if(!d){i(),r(new Error("Failed to get canvas context"));return}d.drawImage(o,0,0,l,c);const f=e.type==="image/png"?"image/png":"image/jpeg";let m=Oa,p=u.toDataURL(f,m);if(f==="image/jpeg"){const v=La*1.37;for(;p.length>v&&m>.3;)m-=.1,p=u.toDataURL(f,m)}const h=p.split(",")[1];if(!h){i(),r(new Error("Failed to encode image"));return}i(),t(h)}catch(l){i(),r(l instanceof Error?l:new Error("Image compression failed"))}},o.onerror=()=>{i(),r(new Error("Failed to load image"))},o.src=a})}function Nr(e){return Pa.includes(e.type)}function Ua(e){const t=e.name.includes(".")?e.name.split(".").pop()?.toLowerCase():"";return!!(t&&Er.includes(t))}async function $a(e){const t=crypto.randomUUID();if(!Nr(e))return{id:t,file:e,preview:null,type:"file",base64:null,error:"Unsupported image type. Please use PNG, JPG, GIF, or WebP images."};if(e.size>Da)return{id:t,file:e,preview:null,type:"image",base64:null,error:"Image is too large. Maximum size is 10MB."};try{const r=await za(e),o=URL.createObjectURL(e);return{id:t,file:e,preview:o,type:"image",base64:r}}catch(r){return{id:t,file:e,preview:null,type:"image",base64:null,error:r instanceof Error?r.message:"Failed to process image"}}}function Ha({onFilesSelect:e,disabled:t=!1,className:r}){const o=s.useRef(null),a=s.useCallback(()=>{o.current?.click()},[]),i=s.useCallback(async l=>{const c=Array.from(l.target.files??[]);c.length!==0&&(l.target.value="",e(c))},[e]);return n.jsxs(n.Fragment,{children:[n.jsx("input",{ref:o,type:"file",accept:_a,multiple:!0,onChange:i,className:"hidden","aria-hidden":"true"}),n.jsx(we,{variant:"ghost",size:"icon-sm",onClick:a,disabled:t,className:r,"aria-label":"Attach file",type:"button",children:n.jsx(Z,{icon:ys,size:18,strokeWidth:1.8})})]})}function Hn(e){return e<1024?`${e} B`:e<1024*1024?`${(e/1024).toFixed(1)} KB`:`${(e/(1024*1024)).toFixed(1)} MB`}function Fa(e){const t=e.split(".");return t.length>1&&t.pop()?.toUpperCase()||""}function Wa({attachment:e,onRemove:t,className:r}){s.useEffect(()=>()=>{e.preview&&URL.revokeObjectURL(e.preview)},[e.preview]);const o=!!e.error;return e.type==="file"&&!o?n.jsxs("div",{className:O("inline-flex max-w-full items-center gap-2 rounded-full border border-primary-200 bg-primary-50 px-3 py-1.5 text-xs text-primary-800",r),children:[n.jsxs("span",{className:"truncate",children:["📄 ",e.file.name," (",Hn(e.file.size),")"]}),n.jsx("button",{onClick:()=>t(e.id),className:"shrink-0 text-primary-500 hover:text-primary-800","aria-label":"Remove attachment",type:"button",children:"✕"})]}):n.jsxs("div",{className:O("relative flex items-center gap-3 rounded-xl border p-2 pr-3",o?"border-red-300 bg-red-50":"border-primary-200 bg-primary-50",r),children:[n.jsx("div",{className:"relative shrink-0",children:e.type==="image"&&e.preview?n.jsx("img",{src:e.preview,alt:e.file.name,className:"h-12 w-12 rounded-lg object-cover"}):n.jsx("div",{className:"flex h-12 w-12 items-center justify-center rounded-lg bg-primary-100",children:n.jsx(Z,{icon:Qn,size:24,className:"text-primary-500"})})}),n.jsxs("div",{className:"min-w-0 flex-1",children:[n.jsx("p",{className:"truncate text-sm font-medium text-primary-900",children:e.file.name}),o?n.jsx("p",{className:"text-xs text-red-600",children:e.error}):n.jsxs("p",{className:"text-xs text-primary-500",children:[Fa(e.file.name)," •"," ",Hn(e.file.size)]})]}),n.jsx(we,{variant:"ghost",size:"icon-sm",onClick:()=>t(e.id),className:"h-6 w-6 shrink-0 rounded-full hover:bg-primary-200","aria-label":"Remove attachment",type:"button",children:n.jsx(Z,{icon:Pt,size:14})})]})}function Xa({attachments:e,onRemove:t,className:r}){return e.length===0?null:n.jsx("div",{className:O("flex flex-wrap gap-2 px-4",r),children:e.map(o=>n.jsx(Wa,{attachment:o,onRemove:t},o.id))})}const Fn=[{command:"/haiku",description:"Switch to Claude Haiku 4.5"},{command:"/sonnet",description:"Switch to Claude Sonnet 4.5"},{command:"/opus",description:"Switch to Claude Opus 4.5"},{command:"/opus46",description:"Switch to Claude Opus 4.6"},{command:"/codex",description:"Switch to GPT 5.3 Codex"},{command:"/glm",description:"Switch to GLM 4.7"},{command:"/kimi",description:"Switch to Kimi K2.5"},{command:"/minimax",description:"Switch to MiniMax M2.1"},{command:"/grok",description:"Switch to Grok 4.1 Fast"},{command:"/model",description:"Show model picker or switch model"},{command:"/new",description:"New chat (optional: /new model)"},{command:"/reset",description:"Reset session"},{command:"/stop",description:"Stop current generation"},{command:"/compact",description:"Compact conversation context"},{command:"/help",description:"Show available commands"},{command:"/commands",description:"List all commands"},{command:"/status",description:"Show session status & usage"},{command:"/whoami",description:"Show your sender ID"},{command:"/context",description:"Show context window details"},{command:"/usage",description:"Toggle usage footer (off/tokens/full/cost)"},{command:"/think",description:"Set thinking level (off/low/medium/high)"},{command:"/reasoning",description:"Toggle reasoning (on/off/stream)"},{command:"/verbose",description:"Toggle verbose mode (on/full/off)"},{command:"/elevated",description:"Toggle elevated permissions (on/off/ask)"},{command:"/exec",description:"Configure exec settings"},{command:"/queue",description:"Show/configure message queue"},{command:"/tts",description:"Text-to-speech (off/always/tagged/status)"},{command:"/subagents",description:"List/stop/log sub-agent runs"},{command:"/followups",description:"Show follow-up suggestions"},{command:"/skill",description:"Run a skill by name"},{command:"/allowlist",description:"List/add/remove allowlist entries"},{command:"/approve",description:"Resolve exec approval (allow/deny)"},{command:"/config",description:"Show/get/set config (owner-only)"},{command:"/debug",description:"Runtime overrides (owner-only)"},{command:"/send",description:"Toggle message sending (on/off)"},{command:"/restart",description:"Restart gateway"},{command:"/activation",description:"Set activation mode (mention/always)"},{command:"/dock-telegram",description:"Switch replies to Telegram"},{command:"/dock-discord",description:"Switch replies to Discord"},{command:"/bash",description:"Run host shell command"}];function Ba(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Ya(e,t){const r=Ba(t),o=new RegExp(`(?:^|\\n\\n)📎 Uploaded file: ${r}\\n\\nPlease analyze this file\\.(?=\\n\\n|$)`);return e.replace(o,(a,i)=>i===0?"":`
16
+
17
+ `).trim()}function Ga({onSubmit:e,isLoading:t,disabled:r,wrapperRef:o,inputRef:a}){const[i,l]=s.useState(""),[c,u]=s.useState(""),[d,f]=s.useState([]),[m,p]=s.useState(0),[h,v]=s.useState(!1),[g,j]=s.useState(!1),[w,y]=s.useState(!1),[P,I]=s.useState(0),[z,T]=s.useState(!1),[J,B]=s.useState(null),H=s.useRef(null),te=s.useRef([]),U=s.useRef(null),S=s.useRef(null),E=s.useRef(null),k=s.useRef(null),R=s.useMemo(()=>/^\/\S*$/.test(i)&&!h,[i,h]),_=s.useMemo(()=>R?i.slice(1).toLowerCase():"",[R,i]),A=s.useMemo(()=>R?_?Fn.filter(N=>N.command.slice(1).toLowerCase().startsWith(_)):Fn:[],[R,_]),X=s.useCallback(N=>{k.current=N,a&&(typeof a=="function"?a(N):a.current=N)},[a]),C=s.useCallback(()=>{typeof window>"u"||window.requestAnimationFrame(()=>{k.current?.focus()})},[]),D=s.useCallback(N=>{B(N)},[]),x=s.useCallback(()=>{l(""),f([]),p(0),v(!1),C()},[C]),L=s.useCallback(N=>{l(W=>{const F=`📎 Uploaded file: ${N}
18
+
19
+ Please analyze this file.`;return W.trim()?`${W.trim()}
20
+
21
+ ${F}`:F})},[]),K=s.useCallback(async()=>{await fetch("/api/files/mkdir",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({path:"/uploads"})})},[]),G=s.useCallback(async N=>{const W=crypto.randomUUID();if(!Ua(N))return{id:W,file:N,preview:null,type:"file",base64:null,error:"Unsupported file type for upload."};try{await K();const F=new FormData;F.append("path","/uploads"),F.append("file",N);const le=await fetch("/api/files/upload",{method:"POST",body:F});if(!le.ok){const ve=await le.text();throw new Error(ve||"File upload failed")}const se=(await le.json()).files?.[0]?.path;if(!se)throw new Error("Upload succeeded but no path was returned");return L(se),{id:W,file:N,preview:null,type:"file",base64:null,uploadedPath:se}}catch(F){return{id:W,file:N,preview:null,type:"file",base64:null,error:F instanceof Error?F.message:"File upload failed"}}},[L,K]),q=s.useCallback(async N=>{if(N.length===0)return;const W=await Promise.all(N.map(F=>Nr(F)?$a(F):G(F)));f(F=>[...F,...W]),C()},[C,G]),V=s.useCallback(N=>{let W;f(F=>{const le=F.find(ne=>ne.id===N);return le?.uploadedPath&&(W=le.uploadedPath),F.filter(ne=>ne.id!==N)}),W&&l(F=>Ya(F,W))},[]),Q=s.useCallback(N=>{Array.from(N.dataTransfer.types).includes("Files")&&(N.preventDefault(),N.dataTransfer.dropEffect="copy",j(!0))},[]),oe=s.useCallback(N=>{N.preventDefault();const W=N.relatedTarget;W&&N.currentTarget.contains(W)||j(!1)},[]),re=s.useCallback(async N=>{N.preventDefault(),j(!1);const W=Array.from(N.dataTransfer.files);W.length!==0&&await q(W)},[q]),Y=s.useCallback(N=>{l(N),p(0),v(!1),C()},[C]),ae=s.useCallback(N=>{l(N),p(0),v(!1)},[]),me=s.useCallback(N=>{l(`${N.command} `),p(0),v(!1),C()},[C]),ee=s.useCallback(()=>{if(r)return;if(R&&A.length>0){const F=Math.min(m,A.length-1);me(A[F]);return}const N=i.trim(),W=d.filter(F=>!F.error&&F.base64);N.length===0&&W.length===0||(e(N,{reset:x,setValue:Y,model:c||void 0,attachments:W}),C())},[r,R,A,m,me,i,d,e,x,Y,c,C]),ie=s.useCallback(N=>{e(N,{reset:x,setValue:Y,model:c||void 0,attachments:[]}),C()},[C,e,x,Y,c]),ge=s.useCallback(N=>{if(R){if(N.key==="Escape"){N.preventDefault(),v(!0),p(0);return}if(A.length!==0){if(N.key==="ArrowDown"){N.preventDefault(),p(W=>(W+1)%A.length);return}if(N.key==="ArrowUp"){N.preventDefault(),p(W=>(W-1+A.length)%A.length);return}if(N.key==="Tab"){N.preventDefault();const W=Math.min(m,A.length-1);me(A[W])}}}},[R,A,m,me]);s.useEffect(()=>()=>{S.current?.abort(),U.current&&clearInterval(U.current),H.current&&H.current.state!=="inactive"&&H.current.stop(),E.current&&E.current.abort()},[]);const pe=s.useCallback(()=>{if(typeof window>"u")return"auto";try{return localStorage.getItem("opencami-stt-provider")||"auto"}catch{return"auto"}},[]),M=s.useCallback(()=>{H.current&&H.current.state!=="inactive"&&H.current.stop(),E.current&&E.current.stop(),U.current&&(clearInterval(U.current),U.current=null),y(!1),I(0)},[]),he=s.useCallback(async()=>{B(null);const N=pe();if(N==="browser"){const W=window.SpeechRecognition||window.webkitSpeechRecognition;if(!W){D("Web Speech API is not supported in this browser.");return}const F=new W;F.continuous=!0,F.interimResults=!1,F.lang=navigator.language||"en-US",E.current=F,y(!0),I(0),U.current=setInterval(()=>{I(ne=>ne>=119?(M(),0):ne+1)},1e3);let le="";F.onresult=ne=>{for(let se=ne.resultIndex;se<ne.results.length;se++)ne.results[se].isFinal&&(le+=ne.results[se][0].transcript)},F.onend=()=>{y(!1),I(0),U.current&&clearInterval(U.current),le.trim()&&(B(null),l(ne=>ne+(ne?" ":"")+le.trim()),C())},F.onerror=()=>{y(!1),I(0),U.current&&clearInterval(U.current),D("Speech recognition failed. Try the Browser provider again or switch providers in Settings.")},F.start();return}try{const W=await navigator.mediaDevices.getUserMedia({audio:!0}),F=MediaRecorder.isTypeSupported("audio/webm")?"audio/webm":"audio/mp4",le=new MediaRecorder(W,{mimeType:F});H.current=le,te.current=[],le.ondataavailable=ne=>{ne.data.size>0&&te.current.push(ne.data)},le.onstop=async()=>{W.getTracks().forEach(se=>se.stop());const ne=new Blob(te.current,{type:F});if(ne.size!==0){T(!0);try{const se=new FormData;se.append("audio",ne,`recording.${F==="audio/webm"?"webm":"mp4"}`),N!=="auto"&&se.append("provider",N),S.current?.abort();const ve=new AbortController;S.current=ve;const Te=await(await fetch("/api/stt",{method:"POST",body:se,signal:ve.signal})).json();Te.ok&&Te.text?(B(null),l(Pe=>Pe+(Pe?" ":"")+Te.text),C()):Te.ok||(console.warn("STT failed:",Te.error),D(Te.error||"Speech-to-text failed. Try the Browser provider in Settings."))}catch(se){if(se instanceof Error&&se.name==="AbortError")return;console.warn("STT request failed:",se),D("Could not reach speech-to-text service.")}finally{T(!1)}}},y(!0),I(0),U.current=setInterval(()=>{I(ne=>ne>=119?(M(),0):ne+1)},1e3),le.start()}catch(W){const F=W instanceof Error?W.message:String(W);if(F.includes("NotAllowedError")||F.includes("Permission"))try{(await navigator.permissions.query({name:"microphone"})).state==="denied"?D("Microphone access is blocked. Please enable it in your browser/app settings."):D("Microphone permission was not granted. Please try again and allow access when prompted.")}catch{D("Could not access microphone. Please check your browser settings and allow microphone access for this site.")}else D("Could not access microphone: "+F)}},[pe,M,C,D]),Ce=s.useCallback(()=>{w?M():he()},[w,M,he]),ze=d.filter(N=>!N.error&&N.base64),Ue=r||i.trim().length===0&&ze.length===0;return n.jsxs("div",{className:"mx-auto w-full max-w-[var(--opencami-chat-width)] px-2 md:px-5 relative pb-1 md:pb-3",ref:o,onDragOver:Q,onDragLeave:oe,onDrop:re,children:[g&&n.jsx("div",{className:"pointer-events-none absolute inset-2 z-20 flex items-center justify-center rounded-2xl border-2 border-dashed border-primary-400 bg-primary-50/90 text-sm font-medium text-primary-700",children:"Drop files here"}),n.jsxs(ka,{value:i,onValueChange:ae,onSubmit:ee,isLoading:t,disabled:r,children:[n.jsx(Xa,{attachments:d,onRemove:V}),J&&n.jsx("div",{className:"mx-3 mt-3 rounded-lg border border-red-200 bg-red-50 px-3 py-2 text-sm text-red-700 dark:border-red-900/40 dark:bg-red-950/40 dark:text-red-200",role:"alert","aria-live":"polite",children:J}),R&&A.length>0&&n.jsx(va,{commands:A,selectedIndex:Math.min(m,A.length-1),onSelect:me}),n.jsx(Ca,{placeholder:"Type a message…",inputRef:X,onKeyDown:ge}),n.jsxs(Ea,{className:"justify-between px-3",children:[n.jsxs("div",{className:"flex items-center gap-1",children:[n.jsx(ba,{}),n.jsx(Ma,{onSelect:ie}),n.jsx(Aa,{onCommandSelect:N=>ae(N+" ")})]}),n.jsxs("div",{className:"flex items-center gap-1",children:[n.jsx(Ha,{onFilesSelect:q,disabled:r}),n.jsx(Un,{tooltip:w?"Stop recording":"Voice input",children:n.jsx(we,{onClick:Ce,disabled:r||z,size:"icon-sm",variant:w?"destructive":"ghost",className:`rounded-full ${w?"animate-pulse":""}`,"aria-label":w?"Stop recording":"Voice input",children:z?n.jsx("span",{className:"size-4 animate-spin rounded-full border-2 border-current border-t-transparent"}):w?n.jsxs("span",{className:"flex items-center gap-1",children:[n.jsx("span",{className:"size-2 rounded-full bg-red-500"}),n.jsxs("span",{className:"text-xs tabular-nums",children:[Math.floor(P/60),":",String(P%60).padStart(2,"0")]}),n.jsx(Z,{icon:qn,size:14,strokeWidth:2})]}):n.jsx(Z,{icon:xs,size:18,strokeWidth:2})})}),n.jsx(Un,{tooltip:"Send message",children:n.jsx(we,{onClick:ee,disabled:Ue,size:"icon-sm",className:"rounded-full","aria-label":"Send message",children:n.jsx(Z,{icon:ws,size:18,strokeWidth:2})})})]})]})]})]})}const Va=s.memo(Ga);function qa({title:e,description:t,detail:r,actionLabel:o,onAction:a,className:i}){return n.jsx("div",{className:O("w-full max-w-[var(--opencami-chat-width)]",i),children:n.jsx(vr,{children:n.jsxs("div",{className:"w-full rounded-xl border border-primary-200 bg-primary-50 p-4 text-primary-900",children:[n.jsx("div",{className:"text-balance font-medium",children:e}),n.jsx("div",{className:"mt-2 text-pretty text-primary-700",children:t}),r?n.jsx("div",{className:"mt-2 text-xs text-primary-600",children:r}):null,o&&a?n.jsx("div",{className:"mt-3",children:n.jsx(we,{size:"sm",variant:"outline",onClick:a,children:o})}):null]})})})}function Ja({state:e,error:t,onRetry:r,className:o}){const a=e==="checking",i=a?"Checking gateway connection...":"OpenClaw gateway is unreachable",l=a?"This dashboard needs access to the OpenClaw gateway configured by your server environment variables.":"";return n.jsx(qa,{title:i,description:a?l:n.jsxs(n.Fragment,{children:["We could not reach the gateway from the dashboard server. Start the gateway and confirm your server environment has"," ",n.jsx("span",{className:"font-mono",children:"CLAWDBOT_GATEWAY_URL"})," plus"," ",n.jsx("span",{className:"font-mono",children:"CLAWDBOT_GATEWAY_TOKEN"})," (or"," ",n.jsx("span",{className:"font-mono",children:"CLAWDBOT_GATEWAY_PASSWORD"}),")."]}),detail:a?null:t,actionLabel:a?void 0:"Retry",onAction:a?void 0:r,className:o})}function Qa(){const e=s.useRef(null),t=s.useRef(null),r=s.useRef(null),[o,a]=s.useState(0),[i,l]=s.useState(0);return s.useLayoutEffect(()=>{const c=e.current,u=t.current,d=r.current;if(!d)return;const f=()=>{const p=c?.offsetHeight??0,h=u?.offsetHeight??0,v=d.clientHeight;d.style.setProperty("--chat-header-height",`${Math.max(0,p)}px`),d.style.setProperty("--chat-composer-height",`${Math.max(0,h)}px`),l(p),a(Math.max(0,v-p-h))};f();const m=new ResizeObserver(()=>f());return c&&m.observe(c),u&&m.observe(u),()=>m.disconnect()},[]),{headerRef:e,composerRef:t,mainRef:r,pinGroupMinHeight:o,headerHeight:i}}function Za({activeFriendlyId:e,activeSessionKey:t,forcedSessionKey:r,isNewChat:o,isRedirecting:a,activeExists:i,sessionsReady:l,queryClient:c}){const u=r||t||e,d=fe.history(e,u),f=Mt({queryKey:d,queryFn:async function(){const y=c.getQueryData(d),P=Array.isArray(y?.messages)?y.messages.filter(T=>T.status==="sending"||T.__optimisticId?!0:!!T.clientId):[],I=await oo({sessionKey:u,friendlyId:e});if(!P.length)return I;const z=el(I.messages,P);return{...I,messages:z}},enabled:!o&&!!e&&!a&&(!l||i),placeholderData:function(){return c.getQueryData(d)},gcTime:1e3*60*10}),m=s.useRef(""),p=s.useRef([]),h=s.useMemo(()=>{const w=Array.isArray(f.data?.messages)?f.data.messages:[],y=w[w.length-1],P=y&&typeof y.id=="string"?y.id:"",I=`${w.length}:${y?.role??""}:${P}:${Le(y??{content:[]}).slice(-32)}`;return I===m.current?p.current:(m.current=I,p.current=w,w)},[f.data?.messages]),v=f.error instanceof Error?f.error.message:null,g=s.useMemo(()=>{if(r)return r;const w=f.data?.sessionKey;return typeof w=="string"&&w.trim().length>0?w.trim():t},[t,r,f.data?.sessionKey]);return{historyQuery:f,historyMessages:h,displayMessages:h,historyError:v,resolvedSessionKey:g,activeCanonicalKey:o?"new":g||e,sessionKeyForHistory:u}}function el(e,t){if(!t.length)return e;const r=[...e];for(const o of t)e.some(i=>{if(o.clientId&&i.clientId&&o.clientId===i.clientId||o.__optimisticId&&i.__optimisticId&&o.__optimisticId===i.__optimisticId)return!0;if(o.role&&i.role&&o.role!==i.role)return!1;const l=Le(o);if(!l||l!==Le(i))return!1;const c=Jt(o),u=Jt(i);return Math.abs(c-u)<=1e4})||r.push(o);return r}function tl(e){const[t,r]=s.useState(!1);return s.useLayoutEffect(()=>{const o=window.matchMedia("(max-width: 768px)"),a=()=>r(o.matches);return a(),o.addEventListener("change",a),()=>o.removeEventListener("change",a)},[]),s.useLayoutEffect(()=>{t&&Be(e,function(a){return{...a,isSidebarCollapsed:!0}})},[t,e]),{isMobile:t}}function nl({activeFriendlyId:e,isNewChat:t,forcedSessionKey:r}){const[o,a]=s.useState(()=>typeof document>"u"?!0:document.visibilityState==="visible");s.useEffect(()=>{if(typeof document>"u")return;const h=()=>{a(document.visibilityState==="visible")};return h(),document.addEventListener("visibilitychange",h),()=>{document.removeEventListener("visibilitychange",h)}},[]);const i=Mt({queryKey:fe.sessions,queryFn:so,refetchInterval:o?3e4:!1}),l=s.useMemo(()=>{const h=i.data??[];return vo(h)},[i.data]),c=s.useMemo(()=>l.find(h=>h.friendlyId===e),[l,e]),u=s.useMemo(()=>t||r||lr(e)?!0:l.some(h=>h.friendlyId===e),[e,r,t,l]),d=c?.key??"",f=s.useMemo(()=>c?c.label||c.title||c.derivedTitle||c.friendlyId:e,[e,c]),m=i.error instanceof Error?i.error.message:null,p=s.useMemo(()=>({totalTokens:c?.totalTokens,contextTokens:c?.contextTokens}),[c?.totalTokens,c?.contextTokens]);return{sessionsQuery:i,sessions:l,activeSession:c,activeExists:u,activeSessionKey:d,activeTitle:f,activeTokens:p,sessionsError:m}}const rl={openai:{baseUrl:"https://api.openai.com/v1",model:"gpt-4.1-nano"},openrouter:{baseUrl:"https://openrouter.ai/api/v1",model:"openai/gpt-oss-120b"},kilocode:{baseUrl:"https://api.kilo.ai/api/gateway",model:"google/gemini-2.5-flash"},ollama:{baseUrl:"http://localhost:11434/v1",model:"llama3.2"},custom:{baseUrl:"",model:""}},Rt={useLlmTitles:!0,useLlmFollowUps:!0,llmProvider:"openai",llmBaseUrl:"",llmModel:"",llmApiKey:""};function Tr(e){return rl[e]}function sl(e){return e.llmBaseUrl.trim()?e.llmBaseUrl.trim():Tr(e.llmProvider).baseUrl}function ol(e){return e.llmModel.trim()?e.llmModel.trim():Tr(e.llmProvider).model}function Wn(e,t){return e.llmProvider==="ollama"?!0:e.llmProvider==="custom"?!!e.llmApiKey.trim()||!!(e.llmBaseUrl.trim()&&e.llmModel.trim()):t||!!e.llmApiKey.trim()}function il(e){if(!e||typeof e!="object")return{settings:Rt};const{settings:t}=e;if(!t)return{settings:Rt};const{openaiApiKey:r,...o}=t,a=o.llmApiKey??r??"";return{settings:{...Rt,...o,llmApiKey:a}}}const ft=ir()(or(e=>({settings:{...Rt},updateSettings:t=>e(r=>({settings:{...r.settings,...t}})),clearApiKey:()=>e(t=>({settings:{...t.settings,llmApiKey:""}}))}),{name:"llm-settings",version:2,migrate:e=>il(e)}));function Kl(){const e=ft(l=>l.settings),t=ft(l=>l.updateSettings),r=ft(l=>l.clearApiKey),[o,a]=s.useState({hasEnvKey:!1,hasOpenRouterKey:!1,hasKilocodeKey:!1,hasUserKey:!!e.llmApiKey,isAvailable:Wn(e,!1),isLoading:!0,error:null});s.useEffect(()=>{let l=!1;async function c(){try{const u=await fetch("/api/llm-features");if(!u.ok)throw new Error("Failed to check LLM status");const d=await u.json();if(l)return;const f=!!e.llmApiKey,m=e.llmProvider==="openrouter"?!!d.hasOpenRouterKey:e.llmProvider==="kilocode"?!!d.hasKilocodeKey:d.hasEnvKey;a({hasEnvKey:d.hasEnvKey,hasOpenRouterKey:!!d.hasOpenRouterKey,hasKilocodeKey:!!d.hasKilocodeKey,hasUserKey:f,isAvailable:Wn(e,m),isLoading:!1,error:null})}catch(u){if(l)return;a(d=>({...d,isLoading:!1,error:u instanceof Error?u.message:"Failed to check status"}))}}return c(),()=>{l=!0}},[e.llmApiKey,e.llmProvider,e.llmBaseUrl,e.llmModel]);const i=s.useCallback(async l=>{try{const c=Rr({...e,llmApiKey:l}),d=await(await fetch("/api/llm-features",{method:"POST",headers:{"Content-Type":"application/json",...c},body:JSON.stringify({action:"test"})})).json();return d.ok?{valid:d.valid??!1,error:d.error}:{valid:!1,error:d.error||"Test failed"}}catch(c){return{valid:!1,error:c instanceof Error?c.message:"Network error"}}},[e]);return{settings:e,updateSettings:t,clearApiKey:r,status:o,testApiKey:i}}function Rr(e){const t=e.llmApiKey,r=sl(e),o=ol(e);return t?{"X-OpenAI-API-Key":t,...r?{"X-LLM-Base-URL":r}:{},...o?{"X-LLM-Model":o}:{}}:{...r?{"X-LLM-Base-URL":r}:{},...o?{"X-LLM-Model":o}:{}}}function al(){const e=ft.getState().settings;return Rr(e)}function ll(){const e=ft(d=>d.settings),[t,r]=s.useState(!1),[o,a]=s.useState(null),[i,l]=s.useState(null),c=s.useRef(null);return{generateTitle:s.useCallback(async d=>{c.current&&c.current.abort();const f=new AbortController;c.current=f,r(!0);try{const m={"Content-Type":"application/json",...al()},p=await fetch("/api/llm-features",{method:"POST",headers:m,body:JSON.stringify({action:"title",message:d}),signal:f.signal});if(!p.ok)throw new Error(`API error: ${p.status}`);const h=await p.json();if(f.signal.aborted)throw new Error("Aborted");const v=h.title||d.slice(0,50),g=v.length>64?v.slice(0,61)+"...":v,j=h.source||"heuristic";return a(g),l(j),{title:g,source:j,error:h.error}}catch(m){if(m instanceof Error&&m.name==="AbortError")throw m;const p=cl(d);return a(p),l("heuristic"),{title:p,source:"heuristic",error:m instanceof Error?m.message:"Unknown error"}}finally{r(!1),c.current===f&&(c.current=null)}},[e.llmApiKey,e.llmBaseUrl,e.llmModel,e.llmProvider]),isGenerating:t,lastTitle:o,lastSource:i}}function cl(e){let t=e.replace(/```[\s\S]*?```/g," ");t=t.replace(/`[^`]+`/g," "),t=t.replace(/https?:\/\/[^\s]+/g," "),t=t.replace(/[^\w\s.,!?'-]/g," "),t=t.replace(/\s+/g," ").trim();let a=t.split(/\s+/).filter(i=>{if(i.length<=2){const l=i.toUpperCase();return["AI","ML","UI","UX","API","CSS","JS"].includes(l)}return!0}).slice(0,6).join(" ");return a=a.replace(/[.,!?]+$/,""),a.length>60&&(a=a.slice(0,57)+"..."),a||e.slice(0,50)}function ul(){return ft(e=>e.settings.useLlmTitles)}const Yt={active:!1,text:"",tools:[],sessionKey:null};function dl(e){const[t,r]=s.useState(Yt),o=s.useRef(null),a=s.useRef(null),i=s.useRef(null),l=s.useRef(null),c=s.useRef(!1),u=s.useRef(e.onDone),d=s.useRef(e.onError),f=s.useRef(e.onAssistantDelta);u.current=e.onDone,d.current=e.onError,f.current=e.onAssistantDelta;function m(){i.current&&(window.clearTimeout(i.current),i.current=null),a.current&&(window.clearInterval(a.current),a.current=null)}function p(g,j){a.current||(a.current=window.setInterval(async()=>{try{const w=await fetch(`/api/history?sessionKey=${encodeURIComponent(g)}`);if(!w.ok)return;const y=await w.json();if(!(Array.isArray(y.messages)?y.messages:[]).some(z=>!z||z.role!=="assistant"||typeof z.timestamp!="number"?!1:z.timestamp>j-3e3))return;o.current&&(o.current.close(),o.current=null),m(),r(z=>({...z,active:!1})),u.current(g)}catch{}},2e3))}const h=s.useCallback(g=>{if(c.current=!0,m(),o.current&&(o.current.close(),o.current=null),g?.preserveState){r(j=>({...j,active:!1}));return}r(Yt)},[]),v=s.useCallback(function(j){c.current=!1,m(),l.current=Date.now(),o.current&&(o.current.close(),o.current=null),r({active:!0,text:"",tools:[],sessionKey:j});const w=new EventSource(`/api/stream?sessionKey=${encodeURIComponent(j)}`);o.current=w,w.addEventListener("delta",y=>{try{const P=JSON.parse(y.data);r(I=>({...I,text:I.text+P.text})),f.current?.({text:P.text,sessionKey:P.sessionKey})}catch{}}),w.addEventListener("tool",y=>{try{const P=JSON.parse(y.data);r(I=>{const z=I.tools.findIndex(J=>J.id===P.id),T=[...I.tools];return z>=0?T[z]={name:P.name,status:P.status,id:P.id}:T.push({name:P.name,status:P.status,id:P.id}),{...I,tools:T}})}catch{}}),w.addEventListener("done",y=>{try{const P=JSON.parse(y.data);c.current=!0,m(),w.close(),o.current=null,r(I=>({...I,active:!1})),u.current(P.sessionKey)}catch{}}),w.onerror=()=>{w.readyState===EventSource.CLOSED&&(w.close(),o.current=null,r(Yt),d.current?.("Stream connection lost"))},i.current=window.setTimeout(()=>{if(c.current)return;const y=l.current??Date.now();p(j,y)},3e3)},[]);return{streaming:t,startStream:v,stopStream:h}}function fl(e){const t=s.useCallback(r=>{const o=r.target,a=o.tagName==="INPUT"||o.tagName==="TEXTAREA"||o.isContentEditable;if(r.key==="Escape"){e.onEscape?.();return}if(r.key==="?"&&!a&&!r.metaKey&&!r.ctrlKey){r.preventDefault(),e.onShowHelp?.();return}if(a)return;const l=navigator.platform.toUpperCase().indexOf("MAC")>=0?r.metaKey:r.ctrlKey;if(l&&r.key==="k"&&!r.shiftKey){r.preventDefault(),e.onNewChat?.();return}if(l&&r.key==="/"){r.preventDefault(),e.onFocusInput?.();return}if(l&&r.shiftKey&&r.key==="C"){r.preventDefault(),e.onCopyLastResponse?.();return}if(l&&r.key==="f"&&!r.shiftKey){r.preventDefault(),e.onSearch?.();return}if(l&&r.shiftKey&&r.key==="F"){r.preventDefault(),e.onSearchGlobal?.();return}},[e]);s.useEffect(()=>(window.addEventListener("keydown",t),()=>{window.removeEventListener("keydown",t)}),[t])}function Xn(e){const{threshold:t=50,edgeWidth:r,onMove:o,onSwipe:a,onCancel:i,direction:l,enabled:c=!0}=e,u=s.useRef({startX:0,startY:0,tracking:!1,directionLocked:!1}),d=s.useCallback(p=>{if(!c)return;const h=p.touches[0];h&&(r!==void 0&&h.clientX>r||(u.current={startX:h.clientX,startY:h.clientY,tracking:!0,directionLocked:!1}))},[c,r]),f=s.useCallback(p=>{const h=u.current;if(!h.tracking)return;const v=p.touches[0];if(!v)return;const g=v.clientX-h.startX,j=v.clientY-h.startY,w=Math.abs(g),y=Math.abs(j);if(!h.directionLocked){if(w<5&&y<5)return;if(y>w){h.tracking=!1,i?.();return}h.directionLocked=!0}l==="left"&&g>0||l==="right"&&g<0||(p.preventDefault(),o?.(g))},[l,o,i]),m=s.useCallback(p=>{const h=u.current;if(!h.tracking)return;h.tracking=!1;const v=p.changedTouches[0];if(!v){i?.();return}const g=v.clientX-h.startX,j=Math.abs(g);if(!h.directionLocked||j<t){i?.();return}const w=g>0?"right":"left";if(l&&w!==l){i?.();return}a(w)},[l,i,a,t]);return{onTouchStart:d,onTouchMove:f,onTouchEnd:m}}const Mr="opencami-browser-notifications-enabled",ml=5e3;function Gt(){return typeof window<"u"&&"Notification"in window}function Bn(){if(typeof window>"u")return!1;try{return localStorage.getItem(Mr)==="true"}catch{return!1}}function pl(){const e=Lt(),t=s.useRef(0),[r,o]=s.useState(()=>Bn()),a=s.useCallback(async()=>{if(!Gt())return"denied";try{return await Notification.requestPermission()}catch{return"denied"}},[]),i=s.useCallback(async c=>{o(c);try{localStorage.setItem(Mr,String(c))}catch{}c&&Gt()&&Notification.permission==="default"&&await a()},[a]),l=s.useCallback(c=>{if(!r||!Gt()||document.hidden!==!0||Notification.permission!=="granted")return;const u=Date.now();if(u-t.current<ml)return;t.current=u;const d=c.text.slice(0,100),f=new Notification("OpenCami",{body:d,icon:"/pwa-192x192.png"});f.onclick=()=>{window.focus(),e({to:"/chat/$sessionKey",params:{sessionKey:c.sessionFriendlyId}}),f.close()}},[r,e]);return s.useEffect(()=>{const c=()=>o(Bn());return window.addEventListener("storage",c),()=>window.removeEventListener("storage",c)},[]),{notificationsEnabled:r,setNotificationsEnabled:i,requestNotificationPermission:a,maybeNotifyAssistantMessage:l}}const hl=s.lazy(()=>et(()=>import("./keyboard-shortcuts-dialog-HAufCn9C.js"),__vite__mapDeps([29,1,4,3,5,6,7,8,9,2])).then(e=>({default:e.KeyboardShortcutsDialog}))),gl=s.lazy(()=>et(()=>import("./search-dialog-CCl4d0Pi.js"),__vite__mapDeps([30,1,3,4,5,6,7,8,9,2,17,18,14,19,11,15,20,13,21,22,23,16,24])).then(e=>({default:e.SearchDialog}))),Et="opencami-search-jump-target";function yl({activeFriendlyId:e,isNewChat:t=!1,onSessionResolved:r,forcedSessionKey:o}){const a=Lt(),i=mt(),[l,c]=s.useState(!1),[u,d]=s.useState(!1),[f,m]=s.useState(null),[p,h]=s.useState(!1),{headerRef:v,composerRef:g,mainRef:j,pinGroupMinHeight:w,headerHeight:y}=Qa(),[P,I]=s.useState(()=>Ut()||$t()),[z,T]=s.useState(()=>Ut()||$t()),[J,B]=s.useState(!1),[H,te]=s.useState(!1),[U,S]=s.useState("global"),[E,k]=s.useState(null),[R,_]=s.useState(!1),A=sn(b=>b.level),{maybeNotifyAssistantMessage:X}=pl(),C=s.useRef(null),D=s.useRef(null),x=s.useRef(null),L=s.useRef(""),K=s.useRef(()=>{}),G=s.useRef(!1),q=s.useRef(""),{isMobile:V}=tl(i),{sessionsQuery:Q,sessions:oe,activeExists:re,activeSessionKey:Y,activeTitle:ae,activeTokens:me,sessionsError:ee}=nl({activeFriendlyId:e,isNewChat:t,forcedSessionKey:o}),{historyQuery:ie,historyMessages:ge,displayMessages:pe,historyError:M,resolvedSessionKey:he,activeCanonicalKey:Ce,sessionKeyForHistory:ze}=Za({activeFriendlyId:e,activeSessionKey:Y,forcedSessionKey:o,isNewChat:t,isRedirecting:p,activeExists:re,sessionsReady:Q.isSuccess,queryClient:i}),Ue=Mt({queryKey:Gr,queryFn:function(){return vn(i)},initialData:function(){return vn(i)},staleTime:1/0}),N=Mt({queryKey:["gateway","status"],queryFn:io,retry:!1,refetchOnWindowFocus:!1,refetchOnReconnect:!1,refetchOnMount:"always"}),W=s.useRef(Date.now()),F=N.error instanceof Error?N.error.message:N.data&&!N.data.ok?N.data.error||"Gateway unavailable":null,le=F??ee??M,ne=s.useCallback(()=>{N.refetch()},[N]),se=Ue.data?.isSidebarCollapsed??!1,ve=Xn({enabled:V&&se,edgeWidth:40,threshold:50,direction:"right",onSwipe:()=>{Be(i,b=>({...b,isSidebarCollapsed:!1}))}}),tt=Xn({enabled:V&&!se,threshold:50,direction:"left",onSwipe:()=>{Be(i,b=>({...b,isSidebarCollapsed:!0}))}}),Te=s.useCallback(()=>{m(null),h(!0),a({to:"/new",replace:!0})},[a]),Pe=s.useCallback(()=>{D.current&&(window.clearInterval(D.current),D.current=null),x.current&&(window.clearTimeout(x.current),x.current=null)},[]),nt=s.useCallback(()=>{Pe(),yt(!1),I(!1),_(!1)},[Pe]),wt=ul(),{generateTitle:rt}=ll(),st=s.useRef(new Set),pt=2e3,bt=2e3,St=s.useCallback(()=>{!e||t||(D.current&&window.clearInterval(D.current),_(!0),D.current=window.setInterval(()=>{K.current()},pt))},[e,t]),ht=s.useRef(()=>{}),vt=s.useRef(()=>{}),{streaming:je,startStream:ce,stopStream:Se}=dl({onDone:b=>ht.current(b),onError:b=>vt.current(b),onAssistantDelta:({text:b})=>{q.current+=b,X({text:q.current,sessionFriendlyId:e})}});ht.current=s.useCallback(async b=>{await ie.refetch(),Se({preserveState:!0}),nt(),i.invalidateQueries({queryKey:fe.sessions})},[ie,i,Se,nt]),vt.current=s.useCallback(b=>{console.warn("[stream] SSE error, falling back to polling")},[]);const $e=s.useMemo(()=>{if(!je.text)return null;const b=[];for(const $ of je.tools)b.push({type:"toolCall",name:$.name,id:$.id});return b.push({type:"text",text:je.text}),{role:"assistant",content:b,id:"__streaming__",__streaming:!0,timestamp:Date.now()}},[je.text,je.tools]),gt=s.useMemo(()=>{if(!$e)return pe;const b=[...pe].map((ue,ye)=>({message:ue,index:ye})).filter(({message:ue})=>ue.role==="assistant").map(({index:ue})=>ue).pop(),$=[...pe].map((ue,ye)=>({message:ue,index:ye})).filter(({message:ue})=>ue.role==="user").map(({index:ue})=>ue).pop();if(typeof b=="number"&&(typeof $!="number"||b>$)&&typeof b=="number"){const ue=pe[b];if(Le(ue).length>=je.text.length)return pe;const _e=[...pe];return _e[b]=$e,_e}return[...pe,$e]},[pe,$e,je.text]),Ir=s.useMemo(()=>({}),[]);K.current=function(){ie.refetch()},s.useEffect(()=>{if(p){f&&m(null);return}if(ot){f&&m(null);return}if(Q.isSuccess&&!re){f&&m(null);return}const b=ee??M??F;if(!b){f?.startsWith("Failed to load")&&m(null);return}Nn(b)&&a({to:"/connect",replace:!0});const $=ee?`Failed to load sessions. ${ee}`:M?`Failed to load history. ${M}`:F?`Gateway unavailable. ${F}`:null;$&&m($)},[f,F,M,p,a,ee]);const ot=!t&&!o&&!lr(e)&&Q.isSuccess&&oe.length>0&&!oe.some(b=>b.friendlyId===e)&&!ie.isFetching&&!ie.isSuccess;s.useEffect(()=>{if(p){if(t){h(!1);return}!ot&&Q.isSuccess&&h(!1)}},[t,p,Q.isSuccess,ot]),s.useEffect(()=>{t||Q.isSuccess&&oe.length!==0&&ot&&(At(),Zt(i,e,ze),a({to:"/new",replace:!0}))},[e,ie.isFetching,ie.isSuccess,t,a,i,ze,oe,Q.isSuccess,ot]);const pn=ot||p,jt=s.useRef("fast");s.useEffect(()=>{const b=[...ge].reverse().find(de=>de.role==="assistant");if(!b)return;const $=`${ge.length}:${Le(b).slice(-64)}`;$!==L.current&&(L.current=$,jt.current!=="fast"&&D.current&&(window.clearInterval(D.current),D.current=window.setInterval(()=>{K.current()},pt),jt.current="fast"),x.current&&window.clearTimeout(x.current),x.current=window.setTimeout(()=>{D.current&&(window.clearInterval(D.current),D.current=window.setInterval(()=>{K.current()},bt),jt.current="slow"),x.current=window.setTimeout(()=>{nt(),jt.current="fast"},3e3)},1500))},[ge,nt]),s.useEffect(()=>{if(!wt||t||p)return;const b=o||he||Y;if(!b||st.current.has(b))return;const $=ge.filter(ye=>ye.role==="user"),de=ge.filter(ye=>ye.role==="assistant");if($.length===0||de.length===0||$.length!==1)return;const ue=Le($[0]);!ue||ue.length<5||(st.current.add(b),(async()=>{try{const ye=await rt(ue);ye.title&&await mo(i,b,e,ye.title)}catch(ye){console.error("[smart-title] Error generating title:",ye)}})())},[wt,t,p,o,he,Y,e,ge,rt,i]),s.useEffect(()=>{if(t||e){if(Pe(),Se(),L.current="",_(!1),G.current){G.current=!1;return}if(Ut()||$t()){I(!0),T(!0);return}I(!1),T(!1)}},[e,t,Pe,Se]),s.useEffect(()=>{if(!(typeof window>"u"))try{const b=sessionStorage.getItem(Et);if(!b){k(null);return}const $=JSON.parse(b);if(typeof $.at=="number"&&Date.now()-$.at>300*1e3){sessionStorage.removeItem(Et),k(null);return}if($.friendlyId===e&&typeof $.messageId=="string"&&$.messageId.length>0){k($.messageId),sessionStorage.removeItem(Et);return}k(null)}catch{k(null)}},[e]),s.useLayoutEffect(()=>{if(t)return;const b=xo(o||he||Y,e);if(!b)return;G.current=!0;const $=fe.history(b.friendlyId,b.sessionKey),de=i.getQueryData($);(Array.isArray(de?.messages)?de.messages:[]).some(_e=>!!(b.optimisticMessage.clientId&&(_e.clientId===b.optimisticMessage.clientId||_e.__optimisticId===b.optimisticMessage.clientId)||b.optimisticMessage.__optimisticId&&_e.__optimisticId===b.optimisticMessage.__optimisticId))||zt(i,b.friendlyId,b.sessionKey,b.optimisticMessage),I(!0),T(!0),Kt(b.sessionKey,b.friendlyId,b.message,!0,b.attachments)},[e,Y,o,t,i,he]);function Kt(b,$,de,ue=!1,ye,_e){let it="";if(!ue){const{clientId:xe,optimisticMessage:at}=Tn(de,ye);it=xe,zt(i,$,b,at),uo(i,b,$,at)}yt(!0),c(!0),m(null),I(!0),T(!0);const Fe=ye?.map(xe=>({mimeType:xe.file.type,content:xe.base64}));q.current="",St(),fetch("/api/send",{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({sessionKey:b,friendlyId:$,message:de,thinking:A,idempotencyKey:crypto.randomUUID(),attachments:Fe,model:_e||void 0})}).then(async xe=>{if(!xe.ok)throw new Error(await Ke(xe));const Sn=(await xe.json()).sessionKey||b||$;ce(Sn)}).catch(xe=>{const at=xe instanceof Error?xe.message:String(xe);if(Nn(at)){a({to:"/connect",replace:!0});return}it&&ao(i,$,b,it,function(Wr){return{...Wr,status:"error"}}),m(`Failed to send message. ${at}`),yt(!1),I(!1),T(!1)}).finally(()=>{c(!1)})}const hn=s.useCallback(async()=>{d(!0);try{const b=await fetch("/api/sessions",{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({})});if(!b.ok)throw new Error(await Ke(b));const $=await b.json(),de=typeof $.sessionKey=="string"?$.sessionKey:"",ue=typeof $.friendlyId=="string"&&$.friendlyId.trim().length>0?$.friendlyId.trim():qt(de);if(!de||!ue)throw new Error("Invalid session response");return i.invalidateQueries({queryKey:fe.sessions}),{sessionKey:de,friendlyId:ue}}finally{d(!1)}},[i]),Ar=s.useCallback((b,$)=>{const de=$.attachments;if(b.length===0&&(!de||de.length===0))return;if($.reset(),t){const{clientId:ye,optimisticId:_e,optimisticMessage:it}=Tn(b,de);zt(i,"new","new",it),yt(!0),c(!0),I(!0),T(!0),hn().then(({sessionKey:Fe,friendlyId:xe})=>{if(yo(xe),ho({sessionKey:Fe,friendlyId:xe,message:b,optimisticMessage:it,attachments:de}),r){r({sessionKey:Fe,friendlyId:xe});return}a({to:"/chat/$sessionKey",params:{sessionKey:xe},replace:!0})}).catch(Fe=>{lo(i,"new","new",ye,_e),$.setValue(b),m(`Failed to create session. ${Fe instanceof Error?Fe.message:String(Fe)}`),yt(!1),I(!1),T(!1),c(!1)});return}Kt(o||he||Y,e,b,!1,de,$.model)},[e,Y,hn,o,t,a,r,i,he]),gn=s.useCallback(()=>{I(!1),T(!1),Zt(i,"new","new"),a({to:"/new"}),V&&Be(i,function($){return{...$,isSidebarCollapsed:!0}})},[V,a,i]),Dr=s.useCallback(()=>{Be(i,function($){return{...$,isSidebarCollapsed:!$.isSidebarCollapsed}})},[i]),Or=s.useCallback(()=>{V&&Be(i,function($){return{...$,isSidebarCollapsed:!0}})},[V,i]),Lr=s.useCallback(()=>{Be(i,function($){return{...$,isSidebarCollapsed:!1}})},[i]),Pr=s.useCallback(b=>{if(t||!b.trim())return;const $=o||he||Y;$&&Kt($,e,b.trim())},[e,Y,o,t,he]),_r=s.useCallback(()=>{C.current?.focus()},[]),Kr=s.useCallback(()=>{if(J){B(!1);return}document.activeElement instanceof HTMLElement&&document.activeElement.blur()},[J]),zr=s.useCallback(()=>{const b=[...pe].reverse().find(de=>de.role==="assistant");if(!b)return;const $=Le(b);$&&navigator.clipboard.writeText($).catch(()=>{})},[pe]),Ur=s.useCallback(()=>{B(!0)},[]),$r=s.useCallback(()=>{S(t?"global":"current"),te(!0)},[t]),yn=s.useCallback(()=>{S("global"),te(!0)},[]);fl({onNewChat:gn,onFocusInput:_r,onEscape:Kr,onCopyLastResponse:zr,onShowHelp:Ur,onSearch:$r,onSearchGlobal:yn});const xn=ie.isLoading&&!ie.data||p,wn=!!F&&N.errorUpdatedAt>W.current,Hr=!xn&&pe.length===0,Fr=s.useMemo(()=>!wn||!le?null:n.jsx(Ja,{state:"error",error:le,onRetry:ne}),[le,ne,wn]),bn=n.jsx(Oi,{sessions:oe,activeFriendlyId:e,activeSessionKey:ze,creatingSession:u,onCreateSession:gn,isCollapsed:V?!1:se,onToggleCollapse:Dr,onSelectSession:Or,onActiveSessionDelete:Te,onOpenSearch:yn});return n.jsxs("div",{className:"h-screen bg-surface text-primary-900",children:[n.jsxs("div",{className:O("h-full overflow-hidden",V?"relative":"grid grid-cols-[auto_minmax(0,1fr)]"),children:[pn?null:V?n.jsxs(n.Fragment,{children:[!se&&n.jsx("div",{className:"fixed inset-0 z-40 bg-black/40 transition-opacity duration-200",onClick:()=>Be(i,b=>({...b,isSidebarCollapsed:!0})),...tt}),n.jsx("div",{className:O("fixed inset-y-0 left-0 z-50 w-[var(--opencami-sidebar-width)] transition-transform duration-150 safe-area-top",se?"-translate-x-full":"translate-x-0"),...tt,children:bn})]}):bn,n.jsxs("main",{className:"flex flex-col h-full min-h-0 min-w-0 overflow-x-hidden",ref:j,...ve,children:[n.jsx(Ki,{activeTitle:ae,wrapperRef:v,showSidebarButton:V,onOpenSidebar:Lr,totalTokens:me.totalTokens,contextTokens:me.contextTokens}),pn?null:n.jsxs(n.Fragment,{children:[n.jsx(xa,{messages:gt,loading:xn,empty:Hr,notice:Fr,noticePosition:"end",waitingForResponse:P,isStreaming:R,sessionKey:Ce,pinToTop:z,pinGroupMinHeight:w,headerHeight:y,contentStyle:Ir,onFollowUpClick:Pr,jumpToMessageId:E}),n.jsx(Va,{onSubmit:Ar,isLoading:l,disabled:l,wrapperRef:g,inputRef:C})]})]})]}),J&&n.jsx(s.Suspense,{fallback:null,children:n.jsx(hl,{open:J,onOpenChange:B})}),H&&n.jsx(s.Suspense,{fallback:null,children:n.jsx(gl,{open:H,onOpenChange:te,sessions:oe,currentFriendlyId:e,currentSessionKey:Y,mode:U,onJumpToMessage:b=>{if(te(!1),!!b.friendlyId){if(b.messageId&&b.friendlyId===e){k(b.messageId);return}if(b.messageId&&typeof window<"u")try{sessionStorage.setItem(Et,JSON.stringify({friendlyId:b.friendlyId,messageId:b.messageId,at:Date.now()}))}catch{}a({to:"/chat/$sessionKey",params:{sessionKey:b.friendlyId}})}}})})]})}function xl(){const e=mt(),t=Lt(),[r,o]=s.useState(null),a=Yr.useParams(),i=typeof a.sessionKey=="string"?a.sessionKey:"main",l=i==="new",c=r?.friendlyId===i?r.sessionKey:void 0,u=s.useCallback(function(f){co(e,"new","new",f.friendlyId,f.sessionKey),o({friendlyId:f.friendlyId,sessionKey:f.sessionKey}),t({to:"/chat/$sessionKey",params:{sessionKey:f.friendlyId},replace:!0})},[t,e]);return n.jsx(yl,{activeFriendlyId:i,isNewChat:l,forcedSessionKey:c,onSessionResolved:l?u:void 0})}const zl=Object.freeze(Object.defineProperty({__proto__:null,component:xl},Symbol.toStringTag,{value:"Module"}));export{zl as $,en as C,tn as a,nn as b,fe as c,ft as d,al as e,Tr as g,Kl as u};
@@ -0,0 +1,2 @@
1
+ const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/agents-screen-6qdnPmx2.js","assets/main-CQKtcNr3.js","assets/useQuery-Boaa6oF3.js","assets/button-8ab4wOwy.js","assets/switch-CSnzINDW.js","assets/useControlled-CT2hRlcU.js","assets/useBaseUiId-DiwX_3so.js","assets/visuallyHidden-COI6QeQH.js","assets/tooltip-CSGMH2t4.js","assets/popupStateMapping-DkI2OCkW.js","assets/event-DG3RKJz8.js","assets/DirectionContext-CrIsc5n9.js","assets/opencami-logo-BSed2Wez.js","assets/proxy-CHQ-VCN1.js"])))=>i.map(i=>d[i]);
2
+ import{j as e,r as t,_ as r}from"./main-CQKtcNr3.js";const n=t.lazy(()=>r(()=>import("./agents-screen-6qdnPmx2.js"),__vite__mapDeps([0,1,2,3,4,5,6,7,8,9,10,11,12,13])).then(s=>({default:s.AgentsScreen})));function o(){return e.jsx(t.Suspense,{fallback:e.jsx("div",{className:"flex h-screen items-center justify-center text-primary-500 text-sm",children:"Loading…"}),children:e.jsx(n,{})})}export{o as component};
@@ -1 +1 @@
1
- import{u as L,r as t,j as e,L as M}from"./main-DBmooBKx.js";import{u as q}from"./useQuery-CtUiG53w.js";import{c as B,b as O,B as f,H as p,I as Q,r as K,w as R,h as I,U as V,a as H,V as G,q as J}from"./button-DdG8c-XQ.js";import{S as _}from"./switch-kXs1I0oW.js";import{s as X,T as Y,a as Z,b as $,c as ee,d as se,g as P}from"./tooltip-CtHpm-sQ.js";import{O as re,a as ae}from"./opencami-logo-BV1uPYe6.js";import{m as S,A as W}from"./proxy-DYrSkM35.js";import"./useControlled-8D4PSDAL.js";import"./useBaseUiId-Ckx_aJky.js";import"./visuallyHidden-COI6QeQH.js";import"./popupStateMapping-CGDLUl5Y.js";import"./event-Dwf9IDxK.js";import"./DirectionContext-B1cuzwIr.js";async function te(){const s=await fetch("/api/agents");if(!s.ok)throw new Error("Failed to fetch agents");return(await s.json()).agents??[]}async function E(s){return await(await fetch("/api/agents",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(s)})).json()}function ie({agent:s,onEdit:d,onDelete:n}){const c=s.isDefault||s.id==="main",l=s.name||s.id.charAt(0).toUpperCase()+s.id.slice(1),m=s.model?s.model.split("/").pop():void 0;return e.jsx("div",{className:"group rounded-lg border border-primary-100 bg-surface p-4 transition-all duration-150 ease-out hover:border-primary-200 hover:shadow-sm",children:e.jsxs("div",{className:"flex items-start gap-4",children:[e.jsxs("div",{className:"relative flex size-12 shrink-0 items-center justify-center rounded-lg bg-primary-50 text-xl",children:[s.emoji||"🤖",c&&e.jsx("span",{className:"absolute -top-1 -right-1 size-3 rounded-full bg-emerald-500 ring-2 ring-surface"})]}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsxs("div",{className:"flex items-start justify-between gap-3 mb-2",children:[e.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[e.jsx("h4",{className:"text-[13px] font-semibold text-primary-900 leading-tight truncate",children:l}),l!==s.id&&e.jsx("span",{className:"text-[10px] font-mono text-primary-400 shrink-0",children:s.id})]}),c&&e.jsx("span",{className:"inline-flex items-center px-2 py-0.5 text-[11px] font-medium rounded-full bg-emerald-50 text-emerald-600 border border-emerald-100 shrink-0",children:"Primary"})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-1.5 mb-3",children:[m&&e.jsx("span",{className:"inline-flex items-center px-2 py-0.5 text-[10px] font-mono rounded-full bg-primary-50 text-primary-600 border border-primary-100 truncate max-w-[200px]",children:m}),s.sandbox!==void 0&&e.jsx("span",{className:B("inline-flex items-center px-2 py-0.5 text-[10px] font-medium rounded-full border",s.sandbox?"bg-amber-50 text-amber-600 border-amber-100":"bg-primary-50 text-primary-500 border-primary-100"),children:s.sandbox?"🔒 Sandbox":"🔓 Open"}),s.sessionScope&&e.jsx("span",{className:"inline-flex items-center px-2 py-0.5 text-[10px] font-medium rounded-full bg-primary-50 text-primary-500 border border-primary-100",children:s.sessionScope==="per-sender"?"👤 Per-sender":"🌐 Global"})]}),s.tools&&s.tools.length>0&&e.jsxs("div",{className:"flex flex-wrap gap-1 mb-2",children:[s.tools.slice(0,6).map(i=>e.jsx("span",{className:"inline-flex items-center px-1.5 py-0.5 text-[10px] font-mono rounded bg-sky-50 text-sky-600 border border-sky-100",children:i},i)),s.tools.length>6&&e.jsxs("span",{className:"text-[10px] text-primary-400",children:["+",s.tools.length-6," more"]})]}),s.channelBindings&&s.channelBindings.length>0&&e.jsx("div",{className:"flex flex-wrap gap-1 mb-2",children:s.channelBindings.map(i=>e.jsxs("span",{className:"inline-flex items-center px-1.5 py-0.5 text-[10px] rounded bg-violet-50 text-violet-600 border border-violet-100",children:["#",i]},i))}),e.jsxs("div",{className:"flex items-center gap-3 pt-2 border-t border-primary-50",children:[s.workspace&&e.jsx("span",{className:"text-[11px] font-mono text-primary-400 truncate",title:s.workspace,children:s.workspace}),s.activeSessions!==void 0&&s.activeSessions>0&&e.jsxs("span",{className:"text-[11px] text-primary-400",children:[s.activeSessions," active session",s.activeSessions!==1?"s":""]})]})]}),e.jsxs("div",{className:"flex items-center gap-1 shrink-0 opacity-0 group-hover:opacity-100 transition-opacity duration-150",children:[e.jsx(f,{size:"icon-sm",variant:"ghost",onClick:d,"aria-label":"Edit agent",children:e.jsx(p,{icon:V,size:16,strokeWidth:1.5})}),!c&&e.jsx(f,{size:"icon-sm",variant:"ghost",onClick:n,"aria-label":"Delete agent",className:"text-red-500 hover:text-red-600",children:e.jsx(p,{icon:H,size:16,strokeWidth:1.5})})]})]})})}function D({label:s,placeholder:d,values:n,onChange:c}){const[l,m]=t.useState(""),i=o=>{(o.key==="Enter"||o.key===",")&&l.trim()&&(o.preventDefault(),n.includes(l.trim())||c([...n,l.trim()]),m("")),o.key==="Backspace"&&!l&&n.length>0&&c(n.slice(0,-1))};return e.jsxs("div",{children:[e.jsx("label",{className:"block text-xs text-primary-600 mb-1",children:s}),e.jsxs("div",{className:"flex flex-wrap gap-1 p-2 rounded-md border border-primary-200 bg-surface min-h-[36px]",children:[n.map(o=>e.jsxs("span",{className:"inline-flex items-center gap-1 rounded bg-primary-100 px-2 py-0.5 text-xs text-primary-700",children:[o,e.jsx("button",{onClick:()=>c(n.filter(x=>x!==o)),className:"text-primary-400 hover:text-primary-600",children:"×"})]},o)),e.jsx("input",{value:l,onChange:o=>m(o.target.value),onKeyDown:i,placeholder:n.length===0?d:"",className:"flex-1 min-w-[80px] bg-transparent text-sm outline-none"})]})]})}function F({agent:s,onSave:d,onCancel:n,saving:c}){const[l,m]=t.useState(s?.name??""),[i,o]=t.useState(s?.workspace??""),[x,g]=t.useState(s?.emoji??""),[u,v]=t.useState(s?.avatar??""),[b,N]=t.useState(s?.model??""),[w,U]=t.useState(s?.sandbox??!1),[h,z]=t.useState(s?.tools??[]),[j,y]=t.useState(s?.deniedTools??[]),[k,A]=t.useState(s?.channelBindings??[]),[C,T]=t.useState(s?.sessionScope??"per-sender"),r=!!s;return e.jsxs("div",{className:"max-w-2xl mx-auto",children:[e.jsxs("div",{className:"flex items-center justify-between mb-6",children:[e.jsx("h2",{className:"text-lg font-semibold text-primary-900",children:r?"Edit Agent":"Create Agent"}),e.jsx(f,{size:"icon-sm",variant:"ghost",onClick:n,children:e.jsx(p,{icon:G,size:18,strokeWidth:1.5})})]}),e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"rounded-lg border border-primary-100 bg-surface p-4",children:[e.jsx("h3",{className:"text-xs font-medium text-primary-400 uppercase tracking-wider mb-3",children:"Basic Info"}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{className:"col-span-2 sm:col-span-1",children:[e.jsx("label",{className:"block text-xs text-primary-600 mb-1",children:"Name"}),e.jsx("input",{value:l,onChange:a=>m(a.target.value),placeholder:"my-agent",className:"w-full rounded-md border border-primary-200 bg-surface px-3 py-1.5 text-sm focus:outline-none focus:ring-2 focus:ring-primary-500"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-xs text-primary-600 mb-1",children:"Emoji"}),e.jsx("input",{value:x,onChange:a=>g(a.target.value),placeholder:"🤖",className:"w-full rounded-md border border-primary-200 bg-surface px-3 py-1.5 text-sm focus:outline-none focus:ring-2 focus:ring-primary-500"})]}),e.jsxs("div",{className:"col-span-2",children:[e.jsx("label",{className:"block text-xs text-primary-600 mb-1",children:"Avatar URL"}),e.jsx("input",{value:u,onChange:a=>v(a.target.value),placeholder:"https://...",className:"w-full rounded-md border border-primary-200 bg-surface px-3 py-1.5 text-sm font-mono focus:outline-none focus:ring-2 focus:ring-primary-500"})]})]})]}),e.jsxs("div",{className:"rounded-lg border border-primary-100 bg-surface p-4",children:[e.jsx("h3",{className:"text-xs font-medium text-primary-400 uppercase tracking-wider mb-3",children:"Model & Config"}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{children:[e.jsx("label",{className:"block text-xs text-primary-600 mb-1",children:"Model"}),e.jsx("input",{value:b,onChange:a=>N(a.target.value),placeholder:"anthropic/claude-sonnet-4-20250514",className:"w-full rounded-md border border-primary-200 bg-surface px-3 py-1.5 text-sm font-mono focus:outline-none focus:ring-2 focus:ring-primary-500"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-xs text-primary-600 mb-1",children:"Workspace Path"}),e.jsx("input",{value:i,onChange:a=>o(a.target.value),placeholder:"/root/.openclaw/workspace-myagent",className:"w-full rounded-md border border-primary-200 bg-surface px-3 py-1.5 text-sm font-mono focus:outline-none focus:ring-2 focus:ring-primary-500"})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-sm text-primary-800",children:"Sandbox Mode"}),e.jsx("div",{className:"text-xs text-primary-500",children:"Run agent in isolated sandbox"})]}),e.jsx(_,{checked:w,onCheckedChange:U})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-xs text-primary-600 mb-1",children:"Session Scope"}),e.jsxs("select",{value:C,onChange:a=>T(a.target.value),className:"w-full rounded-md border border-primary-200 bg-surface px-3 py-1.5 text-sm focus:outline-none focus:ring-2 focus:ring-primary-500",children:[e.jsx("option",{value:"per-sender",children:"Per-sender"}),e.jsx("option",{value:"global",children:"Global"})]})]})]})]}),e.jsxs("div",{className:"rounded-lg border border-primary-100 bg-surface p-4",children:[e.jsx("h3",{className:"text-xs font-medium text-primary-400 uppercase tracking-wider mb-3",children:"Tools"}),e.jsxs("div",{className:"space-y-3",children:[e.jsx(D,{label:"Allowed Tools",placeholder:"Type tool name and press Enter",values:h,onChange:z}),e.jsx(D,{label:"Denied Tools",placeholder:"Type tool name and press Enter",values:j,onChange:y})]})]}),e.jsxs("div",{className:"rounded-lg border border-primary-100 bg-surface p-4",children:[e.jsx("h3",{className:"text-xs font-medium text-primary-400 uppercase tracking-wider mb-3",children:"Channel Bindings"}),e.jsx(D,{label:"Bound Channels",placeholder:"Type channel name and press Enter",values:k,onChange:A})]})]}),e.jsxs("div",{className:"mt-6 flex justify-end gap-2",children:[e.jsx(f,{size:"sm",variant:"outline",onClick:n,children:"Cancel"}),e.jsx(f,{size:"sm",onClick:()=>d({name:l,workspace:i,emoji:x,model:b,avatar:u,sandbox:w,tools:h,deniedTools:j,channelBindings:k,sessionScope:C}),disabled:!l.trim()||c,children:c?e.jsx(p,{icon:I,size:16,className:"animate-spin"}):r?"Save Changes":"Create Agent"})]})]})}function ne({agent:s,onConfirm:d,onCancel:n,deleting:c}){const[l,m]=t.useState(!1);return e.jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center bg-black/50",onClick:n,children:e.jsxs("div",{className:"w-[min(380px,90vw)] rounded-xl border border-primary-200 bg-surface p-5 shadow-xl",onClick:i=>i.stopPropagation(),children:[e.jsxs("div",{className:"flex items-center gap-2 mb-3",children:[e.jsx(p,{icon:J,size:20,className:"text-red-500"}),e.jsx("h3",{className:"text-sm font-medium text-primary-900",children:"Delete Agent"})]}),e.jsxs("p",{className:"text-sm text-primary-600 mb-4",children:["Are you sure you want to delete ",e.jsx("strong",{children:s.name}),"? This cannot be undone."]}),e.jsxs("label",{className:"flex items-center gap-2 text-sm text-primary-700 mb-4 cursor-pointer",children:[e.jsx("input",{type:"checkbox",checked:l,onChange:i=>m(i.target.checked),className:"rounded border-primary-300"}),"Also delete workspace files"]}),e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsx(f,{size:"sm",variant:"outline",onClick:n,children:"Cancel"}),e.jsx(f,{size:"sm",onClick:()=>d(l),disabled:c,className:"bg-red-600 text-white hover:bg-red-700",children:c?e.jsx(p,{icon:I,size:16,className:"animate-spin"}):"Delete"})]})]})})}function ge(){const s=L(),[d,n]=t.useState([]),[c,l]=t.useState(!0),[m,i]=t.useState(null),[o,x]=t.useState(!1),[g,u]=t.useState("list"),[v,b]=t.useState(null),[N,w]=t.useState(null),h=q({queryKey:se,queryFn:function(){return P(s)},initialData:function(){return P(s)},staleTime:1/0}).data?.isSidebarCollapsed??!1,z=t.useCallback(()=>{X(s,function(a){return{...a,isSidebarCollapsed:!a.isSidebarCollapsed}})},[s]),j=t.useMemo(()=>({duration:.15,ease:h?"easeIn":"easeOut"}),[h]),y=t.useCallback(async()=>{try{i(null);const r=await te();n(r)}catch(r){i(r instanceof Error?r.message:"Failed to load agents")}finally{l(!1)}},[]);t.useEffect(()=>{y()},[y]);const k=async r=>{x(!0);try{const a=await E({action:"create",name:r.name,workspace:r.workspace||void 0,emoji:r.emoji||void 0,avatar:r.avatar||void 0});if(a.error){i(a.error);return}u("list"),await y()}finally{x(!1)}},A=async r=>{if(v){x(!0);try{const a=await E({action:"update",agentId:v.id,name:r.name||void 0,workspace:r.workspace||void 0,model:r.model||void 0,avatar:r.avatar||void 0});if(a.error){i(a.error);return}b(null),u("list"),await y()}finally{x(!1)}}},C=async r=>{if(N){x(!0);try{const a=await E({action:"delete",agentId:N.id,deleteFiles:r});if(a.error){i(a.error);return}w(null),await y()}finally{x(!1)}}},T=e.jsxs(S.aside,{initial:!1,animate:{width:h?48:300},transition:j,className:"border-r border-primary-200 h-full overflow-hidden bg-primary-100 flex flex-col",children:[e.jsxs(S.div,{layout:!0,transition:{layout:j},className:"flex items-center h-12 px-2 justify-between",children:[e.jsx(W,{initial:!1,children:h?null:e.jsx(S.div,{initial:{opacity:0},animate:{opacity:1},exit:{opacity:0},transition:j,children:e.jsxs(M,{to:"/new",className:B(O({variant:"ghost",size:"sm"}),"w-full pl-1.5 justify-start"),children:[e.jsx(re,{className:"size-5"}),e.jsx(ae,{})]})})}),e.jsx(Y,{children:e.jsxs(Z,{children:[e.jsx($,{onClick:z,render:e.jsx(f,{size:"icon-sm",variant:"ghost",children:e.jsx(p,{icon:Q,size:20,strokeWidth:1.5})})}),e.jsx(ee,{side:"right",children:h?"Open Sidebar":"Close Sidebar"})]})})]}),e.jsx("div",{className:"px-2 mb-4",children:e.jsxs(M,{to:"/",className:B(O({variant:"ghost",size:"sm"}),"w-full pl-1.5 justify-start"),children:[e.jsx(p,{icon:K,size:20,strokeWidth:1.5,className:"min-w-5"}),e.jsx(W,{initial:!1,mode:"wait",children:!h&&e.jsx(S.span,{initial:{opacity:0},animate:{opacity:1},exit:{opacity:0},transition:j,className:"overflow-hidden whitespace-nowrap",children:"Back to Chat"})})]})})]});return e.jsx("div",{className:"h-screen bg-surface text-primary-900",children:e.jsxs("div",{className:"h-full overflow-hidden grid grid-cols-[auto_1fr]",children:[T,e.jsxs("main",{"aria-label":"Agent manager",className:"flex flex-col h-full min-h-0",children:[e.jsx("header",{className:"border-b border-primary-200 px-6 py-4",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("h1",{className:"text-lg font-semibold text-primary-900",children:"Agents"}),e.jsxs("p",{className:"text-xs text-primary-500 mt-0.5",children:[d.length," agent",d.length!==1?"s":""," configured"]})]}),g==="list"&&e.jsxs(f,{size:"sm",onClick:()=>{b(null),u("create")},children:[e.jsx(p,{icon:R,size:16,strokeWidth:1.5}),e.jsx("span",{className:"ml-1",children:"Create Agent"})]})]})}),e.jsxs("div",{className:"flex-1 min-h-0 overflow-auto p-6",children:[m&&e.jsx("div",{className:"mb-4 rounded-lg bg-red-50 dark:bg-red-900/20 border border-red-200 dark:border-red-800 p-3 text-sm text-red-600 dark:text-red-400",children:m}),c?e.jsx("div",{className:"flex items-center justify-center py-16",children:e.jsx(p,{icon:I,size:24,className:"animate-spin text-primary-400"})}):g==="list"?e.jsxs("div",{className:"max-w-3xl mx-auto space-y-3",children:[d.map(r=>e.jsx(ie,{agent:r,onEdit:()=>{b(r),u("edit")},onDelete:()=>w(r)},r.id)),d.length===0&&e.jsxs("div",{className:"py-12 text-center",children:[e.jsx("div",{className:"inline-flex items-center justify-center w-12 h-12 rounded-lg bg-primary-50 mb-3",children:e.jsx("span",{className:"text-2xl",children:"🤖"})}),e.jsx("p",{className:"text-sm text-primary-500",children:"No agents found"}),e.jsx("p",{className:"text-xs text-primary-400 mt-1",children:"Create one to get started"})]})]}):g==="create"?e.jsx(F,{onSave:k,onCancel:()=>u("list"),saving:o}):g==="edit"&&v?e.jsx(F,{agent:v,onSave:A,onCancel:()=>{b(null),u("list")},saving:o}):null]}),N&&e.jsx(ne,{agent:N,onConfirm:C,onCancel:()=>w(null),deleting:o})]})]})})}export{ge as AgentsScreen};
1
+ import{u as L,r as t,j as e,L as M}from"./main-CQKtcNr3.js";import{u as q}from"./useQuery-Boaa6oF3.js";import{c as B,b as O,B as f,H as p,I as Q,r as K,w as R,h as I,U as V,a as H,V as G,q as J}from"./button-8ab4wOwy.js";import{S as _}from"./switch-CSnzINDW.js";import{s as X,T as Y,a as Z,b as $,c as ee,d as se,g as P}from"./tooltip-CSGMH2t4.js";import{O as re,a as ae}from"./opencami-logo-BSed2Wez.js";import{m as S,A as W}from"./proxy-CHQ-VCN1.js";import"./useControlled-CT2hRlcU.js";import"./useBaseUiId-DiwX_3so.js";import"./visuallyHidden-COI6QeQH.js";import"./popupStateMapping-DkI2OCkW.js";import"./event-DG3RKJz8.js";import"./DirectionContext-CrIsc5n9.js";async function te(){const s=await fetch("/api/agents");if(!s.ok)throw new Error("Failed to fetch agents");return(await s.json()).agents??[]}async function E(s){return await(await fetch("/api/agents",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(s)})).json()}function ie({agent:s,onEdit:d,onDelete:n}){const c=s.isDefault||s.id==="main",l=s.name||s.id.charAt(0).toUpperCase()+s.id.slice(1),m=s.model?s.model.split("/").pop():void 0;return e.jsx("div",{className:"group rounded-lg border border-primary-100 bg-surface p-4 transition-all duration-150 ease-out hover:border-primary-200 hover:shadow-sm",children:e.jsxs("div",{className:"flex items-start gap-4",children:[e.jsxs("div",{className:"relative flex size-12 shrink-0 items-center justify-center rounded-lg bg-primary-50 text-xl",children:[s.emoji||"🤖",c&&e.jsx("span",{className:"absolute -top-1 -right-1 size-3 rounded-full bg-emerald-500 ring-2 ring-surface"})]}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsxs("div",{className:"flex items-start justify-between gap-3 mb-2",children:[e.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[e.jsx("h4",{className:"text-[13px] font-semibold text-primary-900 leading-tight truncate",children:l}),l!==s.id&&e.jsx("span",{className:"text-[10px] font-mono text-primary-400 shrink-0",children:s.id})]}),c&&e.jsx("span",{className:"inline-flex items-center px-2 py-0.5 text-[11px] font-medium rounded-full bg-emerald-50 text-emerald-600 border border-emerald-100 shrink-0",children:"Primary"})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-1.5 mb-3",children:[m&&e.jsx("span",{className:"inline-flex items-center px-2 py-0.5 text-[10px] font-mono rounded-full bg-primary-50 text-primary-600 border border-primary-100 truncate max-w-[200px]",children:m}),s.sandbox!==void 0&&e.jsx("span",{className:B("inline-flex items-center px-2 py-0.5 text-[10px] font-medium rounded-full border",s.sandbox?"bg-amber-50 text-amber-600 border-amber-100":"bg-primary-50 text-primary-500 border-primary-100"),children:s.sandbox?"🔒 Sandbox":"🔓 Open"}),s.sessionScope&&e.jsx("span",{className:"inline-flex items-center px-2 py-0.5 text-[10px] font-medium rounded-full bg-primary-50 text-primary-500 border border-primary-100",children:s.sessionScope==="per-sender"?"👤 Per-sender":"🌐 Global"})]}),s.tools&&s.tools.length>0&&e.jsxs("div",{className:"flex flex-wrap gap-1 mb-2",children:[s.tools.slice(0,6).map(i=>e.jsx("span",{className:"inline-flex items-center px-1.5 py-0.5 text-[10px] font-mono rounded bg-sky-50 text-sky-600 border border-sky-100",children:i},i)),s.tools.length>6&&e.jsxs("span",{className:"text-[10px] text-primary-400",children:["+",s.tools.length-6," more"]})]}),s.channelBindings&&s.channelBindings.length>0&&e.jsx("div",{className:"flex flex-wrap gap-1 mb-2",children:s.channelBindings.map(i=>e.jsxs("span",{className:"inline-flex items-center px-1.5 py-0.5 text-[10px] rounded bg-violet-50 text-violet-600 border border-violet-100",children:["#",i]},i))}),e.jsxs("div",{className:"flex items-center gap-3 pt-2 border-t border-primary-50",children:[s.workspace&&e.jsx("span",{className:"text-[11px] font-mono text-primary-400 truncate",title:s.workspace,children:s.workspace}),s.activeSessions!==void 0&&s.activeSessions>0&&e.jsxs("span",{className:"text-[11px] text-primary-400",children:[s.activeSessions," active session",s.activeSessions!==1?"s":""]})]})]}),e.jsxs("div",{className:"flex items-center gap-1 shrink-0 opacity-0 group-hover:opacity-100 transition-opacity duration-150",children:[e.jsx(f,{size:"icon-sm",variant:"ghost",onClick:d,"aria-label":"Edit agent",children:e.jsx(p,{icon:V,size:16,strokeWidth:1.5})}),!c&&e.jsx(f,{size:"icon-sm",variant:"ghost",onClick:n,"aria-label":"Delete agent",className:"text-red-500 hover:text-red-600",children:e.jsx(p,{icon:H,size:16,strokeWidth:1.5})})]})]})})}function D({label:s,placeholder:d,values:n,onChange:c}){const[l,m]=t.useState(""),i=o=>{(o.key==="Enter"||o.key===",")&&l.trim()&&(o.preventDefault(),n.includes(l.trim())||c([...n,l.trim()]),m("")),o.key==="Backspace"&&!l&&n.length>0&&c(n.slice(0,-1))};return e.jsxs("div",{children:[e.jsx("label",{className:"block text-xs text-primary-600 mb-1",children:s}),e.jsxs("div",{className:"flex flex-wrap gap-1 p-2 rounded-md border border-primary-200 bg-surface min-h-[36px]",children:[n.map(o=>e.jsxs("span",{className:"inline-flex items-center gap-1 rounded bg-primary-100 px-2 py-0.5 text-xs text-primary-700",children:[o,e.jsx("button",{onClick:()=>c(n.filter(x=>x!==o)),className:"text-primary-400 hover:text-primary-600",children:"×"})]},o)),e.jsx("input",{value:l,onChange:o=>m(o.target.value),onKeyDown:i,placeholder:n.length===0?d:"",className:"flex-1 min-w-[80px] bg-transparent text-sm outline-none"})]})]})}function F({agent:s,onSave:d,onCancel:n,saving:c}){const[l,m]=t.useState(s?.name??""),[i,o]=t.useState(s?.workspace??""),[x,g]=t.useState(s?.emoji??""),[u,v]=t.useState(s?.avatar??""),[b,N]=t.useState(s?.model??""),[w,U]=t.useState(s?.sandbox??!1),[h,z]=t.useState(s?.tools??[]),[j,y]=t.useState(s?.deniedTools??[]),[k,A]=t.useState(s?.channelBindings??[]),[C,T]=t.useState(s?.sessionScope??"per-sender"),r=!!s;return e.jsxs("div",{className:"max-w-2xl mx-auto",children:[e.jsxs("div",{className:"flex items-center justify-between mb-6",children:[e.jsx("h2",{className:"text-lg font-semibold text-primary-900",children:r?"Edit Agent":"Create Agent"}),e.jsx(f,{size:"icon-sm",variant:"ghost",onClick:n,children:e.jsx(p,{icon:G,size:18,strokeWidth:1.5})})]}),e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"rounded-lg border border-primary-100 bg-surface p-4",children:[e.jsx("h3",{className:"text-xs font-medium text-primary-400 uppercase tracking-wider mb-3",children:"Basic Info"}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{className:"col-span-2 sm:col-span-1",children:[e.jsx("label",{className:"block text-xs text-primary-600 mb-1",children:"Name"}),e.jsx("input",{value:l,onChange:a=>m(a.target.value),placeholder:"my-agent",className:"w-full rounded-md border border-primary-200 bg-surface px-3 py-1.5 text-sm focus:outline-none focus:ring-2 focus:ring-primary-500"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-xs text-primary-600 mb-1",children:"Emoji"}),e.jsx("input",{value:x,onChange:a=>g(a.target.value),placeholder:"🤖",className:"w-full rounded-md border border-primary-200 bg-surface px-3 py-1.5 text-sm focus:outline-none focus:ring-2 focus:ring-primary-500"})]}),e.jsxs("div",{className:"col-span-2",children:[e.jsx("label",{className:"block text-xs text-primary-600 mb-1",children:"Avatar URL"}),e.jsx("input",{value:u,onChange:a=>v(a.target.value),placeholder:"https://...",className:"w-full rounded-md border border-primary-200 bg-surface px-3 py-1.5 text-sm font-mono focus:outline-none focus:ring-2 focus:ring-primary-500"})]})]})]}),e.jsxs("div",{className:"rounded-lg border border-primary-100 bg-surface p-4",children:[e.jsx("h3",{className:"text-xs font-medium text-primary-400 uppercase tracking-wider mb-3",children:"Model & Config"}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{children:[e.jsx("label",{className:"block text-xs text-primary-600 mb-1",children:"Model"}),e.jsx("input",{value:b,onChange:a=>N(a.target.value),placeholder:"anthropic/claude-sonnet-4-20250514",className:"w-full rounded-md border border-primary-200 bg-surface px-3 py-1.5 text-sm font-mono focus:outline-none focus:ring-2 focus:ring-primary-500"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-xs text-primary-600 mb-1",children:"Workspace Path"}),e.jsx("input",{value:i,onChange:a=>o(a.target.value),placeholder:"/root/.openclaw/workspace-myagent",className:"w-full rounded-md border border-primary-200 bg-surface px-3 py-1.5 text-sm font-mono focus:outline-none focus:ring-2 focus:ring-primary-500"})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-sm text-primary-800",children:"Sandbox Mode"}),e.jsx("div",{className:"text-xs text-primary-500",children:"Run agent in isolated sandbox"})]}),e.jsx(_,{checked:w,onCheckedChange:U})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-xs text-primary-600 mb-1",children:"Session Scope"}),e.jsxs("select",{value:C,onChange:a=>T(a.target.value),className:"w-full rounded-md border border-primary-200 bg-surface px-3 py-1.5 text-sm focus:outline-none focus:ring-2 focus:ring-primary-500",children:[e.jsx("option",{value:"per-sender",children:"Per-sender"}),e.jsx("option",{value:"global",children:"Global"})]})]})]})]}),e.jsxs("div",{className:"rounded-lg border border-primary-100 bg-surface p-4",children:[e.jsx("h3",{className:"text-xs font-medium text-primary-400 uppercase tracking-wider mb-3",children:"Tools"}),e.jsxs("div",{className:"space-y-3",children:[e.jsx(D,{label:"Allowed Tools",placeholder:"Type tool name and press Enter",values:h,onChange:z}),e.jsx(D,{label:"Denied Tools",placeholder:"Type tool name and press Enter",values:j,onChange:y})]})]}),e.jsxs("div",{className:"rounded-lg border border-primary-100 bg-surface p-4",children:[e.jsx("h3",{className:"text-xs font-medium text-primary-400 uppercase tracking-wider mb-3",children:"Channel Bindings"}),e.jsx(D,{label:"Bound Channels",placeholder:"Type channel name and press Enter",values:k,onChange:A})]})]}),e.jsxs("div",{className:"mt-6 flex justify-end gap-2",children:[e.jsx(f,{size:"sm",variant:"outline",onClick:n,children:"Cancel"}),e.jsx(f,{size:"sm",onClick:()=>d({name:l,workspace:i,emoji:x,model:b,avatar:u,sandbox:w,tools:h,deniedTools:j,channelBindings:k,sessionScope:C}),disabled:!l.trim()||c,children:c?e.jsx(p,{icon:I,size:16,className:"animate-spin"}):r?"Save Changes":"Create Agent"})]})]})}function ne({agent:s,onConfirm:d,onCancel:n,deleting:c}){const[l,m]=t.useState(!1);return e.jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center bg-black/50",onClick:n,children:e.jsxs("div",{className:"w-[min(380px,90vw)] rounded-xl border border-primary-200 bg-surface p-5 shadow-xl",onClick:i=>i.stopPropagation(),children:[e.jsxs("div",{className:"flex items-center gap-2 mb-3",children:[e.jsx(p,{icon:J,size:20,className:"text-red-500"}),e.jsx("h3",{className:"text-sm font-medium text-primary-900",children:"Delete Agent"})]}),e.jsxs("p",{className:"text-sm text-primary-600 mb-4",children:["Are you sure you want to delete ",e.jsx("strong",{children:s.name}),"? This cannot be undone."]}),e.jsxs("label",{className:"flex items-center gap-2 text-sm text-primary-700 mb-4 cursor-pointer",children:[e.jsx("input",{type:"checkbox",checked:l,onChange:i=>m(i.target.checked),className:"rounded border-primary-300"}),"Also delete workspace files"]}),e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsx(f,{size:"sm",variant:"outline",onClick:n,children:"Cancel"}),e.jsx(f,{size:"sm",onClick:()=>d(l),disabled:c,className:"bg-red-600 text-white hover:bg-red-700",children:c?e.jsx(p,{icon:I,size:16,className:"animate-spin"}):"Delete"})]})]})})}function ge(){const s=L(),[d,n]=t.useState([]),[c,l]=t.useState(!0),[m,i]=t.useState(null),[o,x]=t.useState(!1),[g,u]=t.useState("list"),[v,b]=t.useState(null),[N,w]=t.useState(null),h=q({queryKey:se,queryFn:function(){return P(s)},initialData:function(){return P(s)},staleTime:1/0}).data?.isSidebarCollapsed??!1,z=t.useCallback(()=>{X(s,function(a){return{...a,isSidebarCollapsed:!a.isSidebarCollapsed}})},[s]),j=t.useMemo(()=>({duration:.15,ease:h?"easeIn":"easeOut"}),[h]),y=t.useCallback(async()=>{try{i(null);const r=await te();n(r)}catch(r){i(r instanceof Error?r.message:"Failed to load agents")}finally{l(!1)}},[]);t.useEffect(()=>{y()},[y]);const k=async r=>{x(!0);try{const a=await E({action:"create",name:r.name,workspace:r.workspace||void 0,emoji:r.emoji||void 0,avatar:r.avatar||void 0});if(a.error){i(a.error);return}u("list"),await y()}finally{x(!1)}},A=async r=>{if(v){x(!0);try{const a=await E({action:"update",agentId:v.id,name:r.name||void 0,workspace:r.workspace||void 0,model:r.model||void 0,avatar:r.avatar||void 0});if(a.error){i(a.error);return}b(null),u("list"),await y()}finally{x(!1)}}},C=async r=>{if(N){x(!0);try{const a=await E({action:"delete",agentId:N.id,deleteFiles:r});if(a.error){i(a.error);return}w(null),await y()}finally{x(!1)}}},T=e.jsxs(S.aside,{initial:!1,animate:{width:h?48:300},transition:j,className:"border-r border-primary-200 h-full overflow-hidden bg-primary-100 flex flex-col",children:[e.jsxs(S.div,{layout:!0,transition:{layout:j},className:"flex items-center h-12 px-2 justify-between",children:[e.jsx(W,{initial:!1,children:h?null:e.jsx(S.div,{initial:{opacity:0},animate:{opacity:1},exit:{opacity:0},transition:j,children:e.jsxs(M,{to:"/new",className:B(O({variant:"ghost",size:"sm"}),"w-full pl-1.5 justify-start"),children:[e.jsx(re,{className:"size-5"}),e.jsx(ae,{})]})})}),e.jsx(Y,{children:e.jsxs(Z,{children:[e.jsx($,{onClick:z,render:e.jsx(f,{size:"icon-sm",variant:"ghost",children:e.jsx(p,{icon:Q,size:20,strokeWidth:1.5})})}),e.jsx(ee,{side:"right",children:h?"Open Sidebar":"Close Sidebar"})]})})]}),e.jsx("div",{className:"px-2 mb-4",children:e.jsxs(M,{to:"/",className:B(O({variant:"ghost",size:"sm"}),"w-full pl-1.5 justify-start"),children:[e.jsx(p,{icon:K,size:20,strokeWidth:1.5,className:"min-w-5"}),e.jsx(W,{initial:!1,mode:"wait",children:!h&&e.jsx(S.span,{initial:{opacity:0},animate:{opacity:1},exit:{opacity:0},transition:j,className:"overflow-hidden whitespace-nowrap",children:"Back to Chat"})})]})})]});return e.jsx("div",{className:"h-screen bg-surface text-primary-900",children:e.jsxs("div",{className:"h-full overflow-hidden grid grid-cols-[auto_1fr]",children:[T,e.jsxs("main",{"aria-label":"Agent manager",className:"flex flex-col h-full min-h-0",children:[e.jsx("header",{className:"border-b border-primary-200 px-6 py-4",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("h1",{className:"text-lg font-semibold text-primary-900",children:"Agents"}),e.jsxs("p",{className:"text-xs text-primary-500 mt-0.5",children:[d.length," agent",d.length!==1?"s":""," configured"]})]}),g==="list"&&e.jsxs(f,{size:"sm",onClick:()=>{b(null),u("create")},children:[e.jsx(p,{icon:R,size:16,strokeWidth:1.5}),e.jsx("span",{className:"ml-1",children:"Create Agent"})]})]})}),e.jsxs("div",{className:"flex-1 min-h-0 overflow-auto p-6",children:[m&&e.jsx("div",{className:"mb-4 rounded-lg bg-red-50 dark:bg-red-900/20 border border-red-200 dark:border-red-800 p-3 text-sm text-red-600 dark:text-red-400",children:m}),c?e.jsx("div",{className:"flex items-center justify-center py-16",children:e.jsx(p,{icon:I,size:24,className:"animate-spin text-primary-400"})}):g==="list"?e.jsxs("div",{className:"max-w-3xl mx-auto space-y-3",children:[d.map(r=>e.jsx(ie,{agent:r,onEdit:()=>{b(r),u("edit")},onDelete:()=>w(r)},r.id)),d.length===0&&e.jsxs("div",{className:"py-12 text-center",children:[e.jsx("div",{className:"inline-flex items-center justify-center w-12 h-12 rounded-lg bg-primary-50 mb-3",children:e.jsx("span",{className:"text-2xl",children:"🤖"})}),e.jsx("p",{className:"text-sm text-primary-500",children:"No agents found"}),e.jsx("p",{className:"text-xs text-primary-400 mt-1",children:"Create one to get started"})]})]}):g==="create"?e.jsx(F,{onSave:k,onCancel:()=>u("list"),saving:o}):g==="edit"&&v?e.jsx(F,{agent:v,onSave:A,onCancel:()=>{b(null),u("list")},saving:o}):null]}),N&&e.jsx(ne,{agent:N,onConfirm:C,onCancel:()=>w(null),deleting:o})]})]})})}export{ge as AgentsScreen};
@@ -0,0 +1,2 @@
1
+ const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/bots-screen-BTKCOohV.js","assets/main-CQKtcNr3.js","assets/button-8ab4wOwy.js","assets/switch-CSnzINDW.js","assets/useControlled-CT2hRlcU.js","assets/useBaseUiId-DiwX_3so.js","assets/visuallyHidden-COI6QeQH.js","assets/useQuery-Boaa6oF3.js","assets/useMutation-rx8UH99I.js","assets/proxy-CHQ-VCN1.js"])))=>i.map(i=>d[i]);
2
+ import{j as e,r as t,_ as r}from"./main-CQKtcNr3.js";const n=t.lazy(()=>r(()=>import("./bots-screen-BTKCOohV.js"),__vite__mapDeps([0,1,2,3,4,5,6,7,8,9])).then(s=>({default:s.BotsScreen})));function a(){return e.jsx(t.Suspense,{fallback:e.jsx("div",{className:"flex h-screen items-center justify-center text-sm text-primary-500",children:"Loading…"}),children:e.jsx(n,{})})}export{a as component};