opencami 1.9.1 → 2.0.0

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 (66) hide show
  1. package/dist/client/assets/{CSPContext-B3PAVjBL.js → CSPContext-CrlIQW7-.js} +1 -1
  2. package/dist/client/assets/{DirectionContext-CR5CCisG.js → DirectionContext-X-0CRn1O.js} +1 -1
  3. package/dist/client/assets/_sessionKey-yNQ57svB.js +23 -0
  4. package/dist/client/assets/agents-WqWjsymD.js +2 -0
  5. package/dist/client/assets/{agents-screen--ZMzN5cB.js → agents-screen-BhOVp_S6.js} +1 -1
  6. package/dist/client/assets/bots-DNqiFT7w.js +2 -0
  7. package/dist/client/assets/{bots-screen-C_uJBNwI.js → bots-screen-DLFd0ydi.js} +1 -1
  8. package/dist/client/assets/button-D0n2Qsd_.js +1 -0
  9. package/dist/client/assets/{composite-DArWbFHm.js → composite-GtKwZKbV.js} +1 -1
  10. package/dist/client/assets/{connect-B48HecjN.js → connect-vQWL0_11.js} +1 -1
  11. package/dist/client/assets/{dashboard-BVKx9FMy.js → dashboard-Knwc61i1.js} +1 -1
  12. package/dist/client/assets/{event-BCwqPPkP.js → event-CHpdjYFR.js} +1 -1
  13. package/dist/client/assets/file-explorer-screen-FoYNs9zK.js +1 -0
  14. package/dist/client/assets/files-BtR_gArr.js +2 -0
  15. package/dist/client/assets/follow-up-suggestions-DVXNLqga.js +5 -0
  16. package/dist/client/assets/{index-0gdwm1_H.js → index-CNPHef4O.js} +1 -1
  17. package/dist/client/assets/{index-CGeJcqZ3.js → index-CTT0Y1ya.js} +1 -1
  18. package/dist/client/assets/{keyboard-shortcuts-dialog-CK_XTzLr.js → keyboard-shortcuts-dialog-DP8ptQ7N.js} +1 -1
  19. package/dist/client/assets/{main-B2CrcRuC.js → main-xPlWrMhO.js} +3 -3
  20. package/dist/client/assets/{markdown-CdkuX06F.js → markdown-3Js_RbUp.js} +1 -1
  21. package/dist/client/assets/memory-BRGPq5t6.js +2 -0
  22. package/dist/client/assets/{memory-screen-C1RfLy-d.js → memory-screen-nzRra2Qi.js} +1 -1
  23. package/dist/client/assets/{menu-CIwnliij.js → menu-BnSEqetd.js} +1 -1
  24. package/dist/client/assets/{opencami-logo-SVuYD55V.js → opencami-logo-B_hLbomw.js} +1 -1
  25. package/dist/client/assets/{proxy-BijR8W1L.js → proxy-BnlGpgC1.js} +1 -1
  26. package/dist/client/assets/{react-DWx7OvUo.js → react-BgjQyJHw.js} +1 -1
  27. package/dist/client/assets/{search-dialog-CB4KE8ec.js → search-dialog-Bib2QY9u.js} +1 -1
  28. package/dist/client/assets/{search-sources-badge-B8Z-8sSf.js → search-sources-badge-COHcYFRB.js} +1 -1
  29. package/dist/client/assets/{session-export-dialog-tDiFuv3a.js → session-export-dialog-ooPnfHh_.js} +1 -1
  30. package/dist/client/assets/settings-dialog-B8mz99u-.js +1 -0
  31. package/dist/client/assets/skills-DA9J_tsC.js +2 -0
  32. package/dist/client/assets/{skills-panel-fjJQVMog.js → skills-panel-D2uMdCHp.js} +1 -1
  33. package/dist/client/assets/styles-CWabEzNU.css +1 -0
  34. package/dist/client/assets/{switch-Bn5uei2k.js → switch-BUQ0qH6r.js} +1 -1
  35. package/dist/client/assets/{tabs-DOBNAUVE.js → tabs-BEyU6TjN.js} +1 -1
  36. package/dist/client/assets/{thinking-dfGrFAMV.js → thinking-CA48yhOE.js} +1 -1
  37. package/dist/client/assets/{tooltip-DOKkNFvu.js → tooltip-CcIdgcV0.js} +1 -1
  38. package/dist/client/assets/{use-file-explorer-state-BAa6Cxyr.js → use-file-explorer-state-CN_IJGcd.js} +2 -2
  39. package/dist/client/assets/{useBaseUiId-DFpBD0sg.js → useBaseUiId-ClbEYEil.js} +1 -1
  40. package/dist/client/assets/useCompositeItem-B_OxfJee.js +1 -0
  41. package/dist/client/assets/{useControlled-CQHE0ITz.js → useControlled-CyT-lqbs.js} +1 -1
  42. package/dist/client/assets/{useMutation-BFl-7GnD.js → useMutation-eQUrsn-X.js} +1 -1
  43. package/dist/client/assets/{useOnFirstRender-DlXHIIGk.js → useOnFirstRender-CR_o2MK_.js} +1 -1
  44. package/dist/client/assets/{useQuery-D-sF8Tld.js → useQuery-k6EMRoMD.js} +1 -1
  45. package/dist/server/assets/{_sessionKey-D8TGrDRM.js → _sessionKey-CaFqmyhU.js} +56 -263
  46. package/dist/server/assets/{_tanstack-start-manifest_v-DalBo2bY.js → _tanstack-start-manifest_v-P3skSR3R.js} +1 -1
  47. package/dist/server/assets/{follow-up-suggestions-C65ptDij.js → follow-up-suggestions-DHv2_XzB.js} +13 -74
  48. package/dist/server/assets/{index-gRco4Ina.js → index-C7lmufwX.js} +1 -1
  49. package/dist/server/assets/{router-DaKDqc9w.js → router-X2L0PDPI.js} +124 -287
  50. package/dist/server/assets/{search-dialog-DSSK93kq.js → search-dialog-CXhofdoP.js} +2 -2
  51. package/dist/server/assets/{settings-dialog-DyWNblva.js → settings-dialog-CPdftvjz.js} +1 -254
  52. package/dist/server/assets/{thinking-CU0FRlzT.js → thinking-YkRSlXtf.js} +2 -2
  53. package/dist/server/server.js +2 -2
  54. package/package.json +1 -1
  55. package/dist/client/assets/_sessionKey-Bg_9uype.js +0 -23
  56. package/dist/client/assets/agents-BiTHBb6Z.js +0 -2
  57. package/dist/client/assets/bots-DxhRnQp5.js +0 -2
  58. package/dist/client/assets/button-BciDmec0.js +0 -1
  59. package/dist/client/assets/file-explorer-screen-DPs-FWeA.js +0 -1
  60. package/dist/client/assets/files-SEycwYCa.js +0 -2
  61. package/dist/client/assets/follow-up-suggestions-BPjWBpiy.js +0 -5
  62. package/dist/client/assets/memory-C7lKdkmc.js +0 -2
  63. package/dist/client/assets/settings-dialog-aL-AH4Rt.js +0 -1
  64. package/dist/client/assets/skills-D1T6uemU.js +0 -2
  65. package/dist/client/assets/styles-D0L88B64.css +0 -1
  66. package/dist/client/assets/useCompositeItem-B-Axq9-D.js +0 -1
@@ -1 +1 @@
1
- import{r as t}from"./main-B2CrcRuC.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-xPlWrMhO.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-B2CrcRuC.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-xPlWrMhO.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,23 @@
1
+ const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/settings-dialog-B8mz99u-.js","assets/main-xPlWrMhO.js","assets/react-BgjQyJHw.js","assets/button-D0n2Qsd_.js","assets/use-file-explorer-state-CN_IJGcd.js","assets/useOnFirstRender-CR_o2MK_.js","assets/useBaseUiId-ClbEYEil.js","assets/event-CHpdjYFR.js","assets/visuallyHidden-COI6QeQH.js","assets/composite-GtKwZKbV.js","assets/switch-BUQ0qH6r.js","assets/useControlled-CyT-lqbs.js","assets/tabs-BEyU6TjN.js","assets/useCompositeItem-B_OxfJee.js","assets/DirectionContext-X-0CRn1O.js","assets/CSPContext-CrlIQW7-.js","assets/index-CTT0Y1ya.js","assets/session-export-dialog-ooPnfHh_.js","assets/thinking-CA48yhOE.js","assets/useQuery-k6EMRoMD.js","assets/tooltip-CcIdgcV0.js","assets/useMutation-eQUrsn-X.js","assets/menu-BnSEqetd.js","assets/opencami-logo-B_hLbomw.js","assets/proxy-BnlGpgC1.js","assets/markdown-3Js_RbUp.js","assets/index-T4TOjvD0.js","assets/search-sources-badge-COHcYFRB.js","assets/follow-up-suggestions-DVXNLqga.js","assets/keyboard-shortcuts-dialog-DP8ptQ7N.js","assets/search-dialog-Bib2QY9u.js"])))=>i.map(i=>d[i]);
2
+ import{r as o,u as pt,j as n,L as Xe,_ as nt,d as zt,w as Qr,a as Zr,z as es}from"./main-xPlWrMhO.js";import{u as Mt}from"./useQuery-k6EMRoMD.js";import{T as Me,a as Oe,b as Le,c as _e,s as Be,d as ts,g as En}from"./tooltip-CcIdgcV0.js";import{u as ns,c as L,B as we,aa as cn,ae as Ve,t as rs,H as te,J as tr,V as $t,ah as ss,ai as os,aj as is,a as nr,ak as as,C as ls,al as cs,l as us,b as Ze,I as ds,am as fs,a1 as ms,an as Qt,ao as ps,G as hs,ap as gs,A as xs,L as ys,N as ws,X as rr,x as bs,h as Ss,aq as sr,ar as vs,p as js,T as or,n as ir,as as Cn,at as ks,au as Es,av as Cs}from"./button-D0n2Qsd_.js";import{u as ar}from"./useMutation-eQUrsn-X.js";import{j as Ns,k as Ts,l as Rs,m as Is,n as As,o as Ds,p as Ms,q as Os,r as Ls,s as lr,D as _s,a as Ps,b as zs,c as $s,d as Us,u as Ks}from"./use-file-explorer-state-CN_IJGcd.js";import{e as cr,a as Ge,g as ur,t as Hs,u as Pe,f as Fs,n as Ws}from"./useBaseUiId-ClbEYEil.js";import{u as Xs}from"./useControlled-CyT-lqbs.js";import{a2 as Bs,a3 as Ys,a4 as Nn,t as dr,u as Gs,J as Te,e as qs,a as Ot}from"./useOnFirstRender-CR_o2MK_.js";import{u as Vs,e as Js,p as Qs}from"./event-CHpdjYFR.js";import{u as Zs}from"./CSPContext-CrlIQW7-.js";import{u as fr}from"./DirectionContext-X-0CRn1O.js";import{M as un,a as dn,b as fn,c as tt}from"./menu-BnSEqetd.js";import{O as eo,a as to}from"./opencami-logo-B_hLbomw.js";import{m as be,A as De}from"./proxy-BnlGpgC1.js";import{M as no}from"./markdown-3Js_RbUp.js";import{u as ro,p as so}from"./index-CTT0Y1ya.js";import{c as oo}from"./react-BgjQyJHw.js";function Zt(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 Tn=/^Conversation info \(untrusted metadata\):\s*```(?:json)?\s*[\s\S]*?```\s*/,Rn=/^Conversation info \(untrusted metadata\):\s*\{[\s\S]*?\}\s*/,In=/^Sender \(untrusted metadata\):\s*```(?:[a-zA-Z0-9_-]+)?\s*[\s\S]*?```\s*/gm,io=/^Sender \(untrusted metadata\):\s*\{[^\n]*\}\s*$/gm,An=/<supermemory-context\b[^>]*>[\s\S]*?<\/supermemory-context>/gi,Dn=/<supermemory-containers\b[^>]*>[\s\S]*?<\/supermemory-containers>/gi,ao=/<workspace-critical-rules\b[^>]*>[\s\S]*?<\/workspace-critical-rules>/gi,lo=/^\[(?:[A-Za-z]{3}\s+)?\d{4}-\d{2}-\d{2}\s+\d{2}:\d{2}\s+GMT[+-]?\d+\]\s*/gm,co=/\n{3,}/g;function mr(e){let t=e;t=t.replace(An,"").replace(Dn,"").replace(ao,"").replace(In,"");const r=Tn.test(t),s=!r&&Rn.test(t);return r?t=t.replace(Tn,""):s&&(t=t.replace(Rn,"")),t=t.replace(An,"").replace(Dn,"").replace(In,"").replace(io,"").replace(lo,"").replace(co,`
3
+
4
+ `),t.trim()}function ve(e){const r=(Array.isArray(e.content)?e.content:[]).map(s=>s.type==="text"?String(s.text??""):"").join("").trim();return mr(r)}function Ye(e){return(Array.isArray(e.content)?e.content:[]).filter(r=>r.type==="toolCall")}function uo(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 St(e){const t=[e.createdAt,e.created_at,e.timestamp,e.time,e.ts];for(const r of t){const s=uo(r);if(s)return s}return Date.now()}const fo=["agent:main:main","main"];function en(e){return fo.includes(e)}const mo=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function po(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 mo.test(t)?"webchat":"chat"}return"other"}function ho(e){return Array.isArray(e)?e.map(t=>{const r=typeof t.key=="string"&&t.key.trim().length>0?t.key.trim():Zt(t.friendlyId??t.key),s=typeof t.friendlyId=="string"&&t.friendlyId.trim().length>0?t.friendlyId.trim():Zt(r),a=po(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:s,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 Ue(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 go="Missing gateway auth. Set CLAWDBOT_GATEWAY_TOKEN (recommended) or CLAWDBOT_GATEWAY_PASSWORD in the server environment.";function Mn(e){return e.includes(go)}function On(e,t){const r=crypto.randomUUID(),s=`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:s,optimisticMessage:{role:"user",content:i,__optimisticId:s,clientId:r,status:"sending",timestamp:a}}}const ge={sessions:["chat","sessions"],history:function(t,r){return["chat","history",t,r]}};async function xo(){const e=await fetch("/api/sessions");if(!e.ok)throw new Error(await Ue(e));const t=await e.json();return ho(t.sessions)}async function yo(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 Ue(r));return await r.json()}async function wo(){const e=new AbortController,t=window.setTimeout(()=>e.abort(),8e3);try{const r=await fetch("/api/ping",{signal:e.signal});if(!r.ok)throw new Error(await Ue(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 mn(e,t,r,s){const a=ge.history(t,r);e.setQueryData(a,function(l){const c=l,u=Array.isArray(c?.messages)?c.messages:[],f=s(u);return{sessionKey:c?.sessionKey??r,sessionId:c?.sessionId,messages:f}})}function Ht(e,t,r,s){mn(e,t,r,function(i){return[...i,s]})}function bo(e,t,r,s,a){const i=`opt-${s}`;mn(e,t,r,function(c){return c.map(u=>u.clientId===s||u.__optimisticId===s||u.__optimisticId===i?a(u):u)})}function Ft(e,t,r,s,a){mn(e,t,r,function(l){return l.filter(c=>!(c.clientId===s||c.__optimisticId===s||a&&c.__optimisticId===a))})}function tn(e,t,r){const s=ge.history(t,r);e.setQueryData(s,{sessionKey:r,messages:[]})}function So(e,t,r,s,a){const i=ge.history(t,r),l=ge.history(s,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 vo(e,t,r,s){e.setQueryData(ge.sessions,function(i){return Array.isArray(i)?i.map(l=>l.key!==t&&l.friendlyId!==r?l:{...l,lastMessage:s}):i})}function jo(e,t,r){e.setQueryData(ge.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 ko(e,t,r,s){e.setQueryData(ge.sessions,function(i){return Array.isArray(i)?i.map(l=>l.key===t||l.friendlyId===r?{...l,label:s}:l):i});try{const a=await fetch("/api/sessions",{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({sessionKey:t,friendlyId:r,label:s})});if(!a.ok){const i=await Ue(a);console.error("[updateSessionLabel] Failed to persist:",i)}}catch(a){console.error("[updateSessionLabel] Network error:",a)}}function Eo(){const[e,t]=o.useState(!1),[r,s]=o.useState(!1),[a,i]=o.useState(null),[l,c]=o.useState(null),u=o.useCallback(async()=>{if(t(!0),i(null),!(r||l)){s(!0);try{const m=await fetch("/api/paths");if(!m.ok)throw new Error(await Ue(m));const b=await m.json();c({agentId:String(b.agentId??"main"),stateDir:String(b.stateDir??""),sessionsDir:String(b.sessionsDir??""),storePath:String(b.storePath??"")})}catch(m){i(m instanceof Error?m.message:String(m))}finally{s(!1)}}},[l,r]),f=o.useCallback(()=>{u()},[u]),d=o.useCallback(()=>{t(!1)},[]),h=o.useCallback(()=>{if(l?.sessionsDir)try{navigator.clipboard.writeText(l.sessionsDir)}catch{}},[l]),p=o.useCallback(()=>{if(l?.storePath)try{navigator.clipboard.writeText(l.storePath)}catch{}},[l]);return{settingsOpen:e,setSettingsOpen:t,pathsLoading:r,pathsError:a,paths:l,handleOpenSettings:f,closeSettings:d,copySessionsDir:h,copyStorePath:p}}let Ee=null,pn=!1,At=null;function Co(e){Ee=e}function Wt(){return Ee!==null}function yt(e){pn=e}function Xt(){return pn}function Lt(){Ee=null,pn=!1}function No(e,t){if(Ee){if(e&&Ee.sessionKey===e){Lt();return}t&&Ee.friendlyId===t&&Lt()}}function To(e){At={friendlyId:e,at:Date.now()}}function pr(e,t=15e3){return!(!At||At.friendlyId!==e||Date.now()-At.at>t)}function Ro(e,t){if(!Ee)return null;if(e&&Ee.sessionKey===e){const r=Ee;return Ee=null,r}if(t&&Ee.friendlyId===t){const r=Ee;return Ee=null,r}return null}const Io=8e3,et=new Map;function Ao(e){e&&et.set(e,{id:e,expiresAt:Date.now()+Io})}function Do(e){e&&et.delete(e)}function Mo(e){if(et.size===0)return e;const t=Date.now();let r=!1;const s=e.filter(a=>{const i=et.get(a.key),l=et.get(a.friendlyId);return i&&i.expiresAt<=t||l&&l.expiresAt<=t?(i&&i.expiresAt<=t&&et.delete(a.key),l&&l.expiresAt<=t&&et.delete(a.friendlyId),!0):i||l?(r=!0,!1):!0});return r?s:e}function Oo(){const e=pt(),[t,r]=o.useState(!1),[s,a]=o.useState(null),i=ar({mutationFn:async function(u){const f=new URLSearchParams;u.sessionKey&&f.set("sessionKey",u.sessionKey),u.friendlyId&&f.set("friendlyId",u.friendlyId);const d=await fetch(`/api/sessions?${f.toString()}`,{method:"DELETE"});if(!d.ok)throw new Error(await Ue(d));return u},onMutate:async function(u){a(null),Ao(u.sessionKey||u.friendlyId),No(u.sessionKey,u.friendlyId),await e.cancelQueries({queryKey:ge.sessions});const f=e.getQueryData(ge.sessions);return jo(e,u.sessionKey,u.friendlyId),u.isActive&&(u.sessionKey||u.friendlyId)&&tn(e,u.friendlyId||u.sessionKey,u.sessionKey||u.friendlyId),{previousSessions:f,isActive:u.isActive}},onError:function(u,f,d){d?.previousSessions&&e.setQueryData(ge.sessions,d.previousSessions),Do(f.sessionKey||f.friendlyId),a(u instanceof Error?u.message:String(u))},onSuccess:function(u){u.isActive&&Lt(),e.invalidateQueries({queryKey:ge.sessions})},onSettled:function(){r(!1)}});return{deleteSession:o.useCallback(async(c,u,f)=>{!c&&!u||(r(!0),await i.mutateAsync({sessionKey:c,friendlyId:u,isActive:f}))},[i]),deleting:t,error:s}}function Lo(){const e=pt(),[t,r]=o.useState(!1),[s,a]=o.useState(null),i=ar({mutationFn:async function(u){const f=await fetch("/api/sessions",{method:"PATCH",headers:{"content-type":"application/json"},body:JSON.stringify({sessionKey:u.sessionKey,label:u.newTitle})});if(!f.ok)throw new Error(await Ue(f));return u},onMutate:async function(u){a(null),await e.cancelQueries({queryKey:ge.sessions});const f=e.getQueryData(ge.sessions);return e.setQueryData(ge.sessions,function(h){return Array.isArray(h)?h.map(p=>p.key!==u.sessionKey?p:{...p,label:u.newTitle,title:u.newTitle}):h}),{previousSessions:f}},onError:function(u,f,d){d?.previousSessions&&e.setQueryData(ge.sessions,d.previousSessions),a(u instanceof Error?u.message:String(u))},onSuccess:function(){e.invalidateQueries({queryKey:ge.sessions})},onSettled:function(){r(!1)}});return{renameSession:o.useCallback(async(c,u)=>{!c||!u.trim()||(r(!0),await i.mutateAsync({sessionKey:c,newTitle:u.trim()}))},[i]),renaming:t,error:s}}function hr(e){return!e.content||!Array.isArray(e.content)?"":e.content.filter(t=>t.type==="text").map(t=>t.text||"").join(`
5
+ `)}function _o(e,t,r){const s=[];s.push(`# Conversation: ${e}`),s.push(`Date: ${r.toLocaleString()}`),s.push("");for(const a of t){const i=a.role||"unknown",l=hr(a);if(l){const c=i==="user"?"User":"Assistant";s.push(`## ${c}`),s.push(""),s.push(l),s.push("")}}return s.join(`
6
+ `)}function Po(e,t,r){const s={title:e,exportDate:r.toISOString(),messages:t.map(a=>({role:a.role,content:a.content,timestamp:a.timestamp}))};return JSON.stringify(s,null,2)}function zo(e,t,r){const s=[];s.push(`Conversation: ${e}`),s.push(`Date: ${r.toLocaleString()}`),s.push("─".repeat(60)),s.push("");for(const a of t){const i=a.role||"unknown",l=hr(a);if(l){const c=i==="user"?"User":"Assistant";s.push(`${c}:`),s.push(l),s.push("")}}return s.join(`
7
+ `)}function $o(e,t,r){const s=new Date;let a,i,l;switch(r){case"markdown":a=_o(e,t,s),i=`${Bt(e)}.md`,l="text/markdown";break;case"json":a=Po(e,t,s),i=`${Bt(e)}.json`,l="application/json";break;case"txt":a=zo(e,t,s),i=`${Bt(e)}.txt`,l="text/plain";break;default:throw new Error(`Unsupported format: ${r}`)}Uo(a,i,l)}function Bt(e){return e.replace(/[^a-z0-9-_\s]/gi,"").replace(/\s+/g,"-").toLowerCase().slice(0,50)||"conversation"}function Uo(e,t,r){const s=new Blob([e],{type:r}),a=URL.createObjectURL(s),i=document.createElement("a");i.href=a,i.download=t,document.body.appendChild(i),i.click(),document.body.removeChild(i),URL.revokeObjectURL(a)}function Ko(e){const{children:t,open:r,defaultOpen:s=!1,onOpenChange:a,onOpenChangeComplete:i,actionsRef:l,handle:c,triggerId:u,defaultTriggerId:f=null}=e,d=Ns(),h=!!d,p=ns(()=>c?.store??new Ts({open:s,openProp:r,activeTriggerId:f,triggerIdProp:u,modal:!0,disablePointerDismissal:!0,nested:h,role:"alertdialog"})).current;p.useControlledProp("openProp",r),p.useControlledProp("triggerIdProp",u),p.useSyncedValue("nested",h),p.useContextCallback("onOpenChange",a),p.useContextCallback("onOpenChangeComplete",i);const m=p.useState("payload");Rs({store:p,actionsRef:l,parentContext:d?.store.context});const b=o.useMemo(()=>({store:p}),[p]);return n.jsx(Is.Provider,{value:b,children:typeof t=="function"?t({payload:m}):t})}function Ho({children:e,...t}){return n.jsx(Ko,{...t,children:e})}function Fo({className:e,children:t}){return n.jsxs(As,{children:[n.jsx(Ds,{className:"fixed inset-0 bg-primary-950/20 transition-all duration-150 data-[state=open]:opacity-100 data-[state=closed]:opacity-0"}),n.jsx(Ms,{className:L("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 Wo({className:e,...t}){return n.jsx(Os,{className:L("text-lg font-medium text-primary-900",e),...t})}function Xo({className:e,...t}){return n.jsx(Ls,{className:L("text-sm text-primary-600",e),...t})}function Bo({className:e,...t}){return n.jsx(lr,{render:n.jsx(we,{variant:"outline",className:L(e)}),...t})}function Yo({className:e,...t}){return n.jsx(lr,{render:n.jsx(we,{variant:"destructive",className:L(e)}),...t})}function Go({open:e,onOpenChange:t,sessionTitle:r,onConfirm:s,onCancel:a}){return n.jsx(Ho,{open:e,onOpenChange:t,children:n.jsx(Fo,{children:n.jsxs("div",{className:"p-4",children:[n.jsx(Wo,{className:"mb-1",children:"Delete Session"}),n.jsxs(Xo,{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(Bo,{onClick:a,children:"Cancel"}),n.jsx(Yo,{onClick:s,children:"Delete"})]})]})})})}function qo({open:e,onOpenChange:t,sessionTitle:r,onSave:s,onCancel:a}){return n.jsx(_s,{open:e,onOpenChange:t,children:n.jsx(Ps,{children:n.jsxs("div",{className:"p-4",children:[n.jsx(zs,{className:"mb-1",children:"Rename"}),n.jsx($s,{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(),s(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(Us,{onClick:a,children:"Cancel"}),n.jsx(we,{onClick:i=>{const l=i.currentTarget.parentElement?.previousElementSibling;s(l.value)},children:"Save"})]})]})})})}function Vo(e){const{open:t,defaultOpen:r,onOpenChange:s,disabled:a}=e,i=t!==void 0,[l,c]=Xs({controlled:t,default:r,name:"Collapsible",state:"open"}),{mounted:u,setMounted:f,transitionStatus:d}=Bs(l,!0,!0),[h,p]=o.useState(l),[{height:m,width:b},g]=o.useState({height:void 0,width:void 0}),k=cr(),[w,x]=o.useState(),$=w??k,[I,H]=o.useState(!1),[O,ee]=o.useState(!1),_=o.useRef(null),P=o.useRef(null),Z=o.useRef(null),X=o.useRef(null),C=Ys(X,!1),A=Ge(v=>{const D=!l,j=ur(Hs,v.nativeEvent);if(s(D,j),j.isCanceled)return;const U=X.current;P.current==="css-animation"&&U!=null&&U.style.removeProperty("animation-name"),!I&&!O&&(P.current!=null&&P.current!=="css-animation"&&!u&&D&&f(!0),P.current==="css-animation"&&(!h&&D&&p(!0),!u&&D&&f(!0))),c(D),P.current==="none"&&u&&!D&&f(!1)});return Pe(()=>{i&&P.current==="none"&&!O&&!l&&f(!1)},[i,O,l,t,f]),o.useMemo(()=>({abortControllerRef:_,animationTypeRef:P,disabled:a,handleTrigger:A,height:m,mounted:u,open:l,panelId:$,panelRef:X,runOnceAnimationsFinish:C,setDimensions:g,setHiddenUntilFound:H,setKeepMounted:ee,setMounted:f,setOpen:c,setPanelIdState:x,setVisible:p,transitionDimensionRef:Z,transitionStatus:d,visible:h,width:b}),[_,P,a,A,m,u,l,$,X,C,g,H,ee,f,c,p,Z,d,h,b])}const gr=o.createContext(void 0);function xr(){const e=o.useContext(gr);if(e===void 0)throw new Error(cn(15));return e}let wt=(function(e){return e.open="data-open",e.closed="data-closed",e[e.startingStyle=Nn.startingStyle]="startingStyle",e[e.endingStyle=Nn.endingStyle]="endingStyle",e})({}),Jo=(function(e){return e.panelOpen="data-panel-open",e})({});const Qo={[wt.open]:""},Zo={[wt.closed]:""},ei={open(e){return e?{[Jo.panelOpen]:""}:null}},ti={open(e){return e?Qo:Zo}},yr={...ti,...dr},ni=o.forwardRef(function(t,r){const{render:s,className:a,defaultOpen:i=!1,disabled:l=!1,onOpenChange:c,open:u,...f}=t,d=Ge(c),h=Vo({open:u,defaultOpen:i,onOpenChange:d,disabled:l}),p=o.useMemo(()=>({open:h.open,disabled:h.disabled,transitionStatus:h.transitionStatus}),[h.open,h.disabled,h.transitionStatus]),m=o.useMemo(()=>({...h,onOpenChange:d,state:p}),[h,d,p]),b=Ve("div",t,{state:p,ref:r,props:f,stateAttributesMapping:yr});return n.jsx(gr.Provider,{value:m,children:b})}),ri={...ei,...dr},si=o.forwardRef(function(t,r){const{panelId:s,open:a,handleTrigger:i,state:l,disabled:c}=xr(),{className:u,disabled:f=c,id:d,render:h,nativeButton:p=!0,...m}=t,{getButtonProps:b,buttonRef:g}=Fs({disabled:f,focusableWhenDisabled:!0,native:p}),k=o.useMemo(()=>({"aria-controls":a?s:void 0,"aria-expanded":a,onClick:i}),[s,a,i]);return Ve("button",t,{state:l,ref:[r,g],props:[k,m,b],stateAttributesMapping:ri})});let oi=(function(e){return e.disabled="data-disabled",e.orientation="data-orientation",e})({});function ii(e){const{abortControllerRef:t,animationTypeRef:r,externalRef:s,height:a,hiddenUntilFound:i,keepMounted:l,id:c,mounted:u,onOpenChange:f,open:d,panelRef:h,runOnceAnimationsFinish:p,setDimensions:m,setMounted:b,setOpen:g,setVisible:k,transitionDimensionRef:w,visible:x,width:$}=e,I=o.useRef(!1),H=o.useRef(null),O=o.useRef(d),ee=o.useRef(d),_=Gs(),P=o.useMemo(()=>r.current==="css-animation"?!x:!d&&!u,[d,u,x,r]),Z=Ge(C=>{if(!C)return;if(r.current==null||w.current==null){const D=getComputedStyle(C),j=D.animationName!=="none"&&D.animationName!=="",U=D.transitionDuration!=="0s"&&D.transitionDuration!=="";j&&U||(D.animationName==="none"&&D.transitionDuration!=="0s"?r.current="css-transition":D.animationName!=="none"&&D.transitionDuration==="0s"?r.current="css-animation":r.current="none"),C.getAttribute(oi.orientation)==="horizontal"||D.transitionProperty.indexOf("width")>-1?w.current="width":w.current="height"}if(r.current!=="css-transition")return;(a===void 0||$===void 0)&&(m({height:C.scrollHeight,width:C.scrollWidth}),ee.current&&C.style.setProperty("transition-duration","0s"));let A=-1,v=-1;return A=Te.request(()=>{ee.current=!1,v=Te.request(()=>{setTimeout(()=>{C.style.removeProperty("transition-duration")})})}),()=>{Te.cancel(A),Te.cancel(v)}}),X=rs(s,h,Z);return Pe(()=>{if(r.current!=="css-transition")return;const C=h.current;if(!C)return;let A=-1;if(t.current!=null&&(t.current.abort(),t.current=null),d){const v={"justify-content":C.style.justifyContent,"align-items":C.style.alignItems,"align-content":C.style.alignContent,"justify-items":C.style.justifyItems};Object.keys(v).forEach(D=>{C.style.setProperty(D,"initial","important")}),!ee.current&&!l&&C.setAttribute(wt.startingStyle,""),m({height:C.scrollHeight,width:C.scrollWidth}),A=Te.request(()=>{Object.entries(v).forEach(([D,j])=>{j===""?C.style.removeProperty(D):C.style.setProperty(D,j)})})}else{if(C.scrollHeight===0&&C.scrollWidth===0)return;m({height:C.scrollHeight,width:C.scrollWidth});const v=new AbortController;t.current=v;const D=v.signal;let j=null;const U=wt.endingStyle;return j=new MutationObserver(G=>{G.some(M=>M.type==="attributes"&&M.attributeName===U)&&(j?.disconnect(),j=null,p(()=>{m({height:0,width:0}),C.style.removeProperty("content-visibility"),b(!1),t.current===v&&(t.current=null)},D))}),j.observe(C,{attributes:!0,attributeFilter:[U]}),()=>{j?.disconnect(),_.cancel(),t.current===v&&(v.abort(),t.current=null)}}return()=>{Te.cancel(A)}},[t,r,_,i,l,u,d,h,p,m,b]),Pe(()=>{if(r.current!=="css-animation")return;const C=h.current;C&&(H.current=C.style.animationName||H.current,C.style.setProperty("animation-name","none"),m({height:C.scrollHeight,width:C.scrollWidth}),!O.current&&!I.current&&C.style.removeProperty("animation-name"),d?(t.current!=null&&(t.current.abort(),t.current=null),b(!0),k(!0)):(t.current=new AbortController,p(()=>{b(!1),k(!1),t.current=null},t.current.signal)))},[t,r,d,h,p,m,b,k,x]),Vs(()=>{const C=Te.request(()=>{O.current=!1});return()=>Te.cancel(C)}),Pe(()=>{if(!i)return;const C=h.current;if(!C)return;let A=-1,v=-1;return d&&I.current&&(C.style.transitionDuration="0s",m({height:C.scrollHeight,width:C.scrollWidth}),A=Te.request(()=>{I.current=!1,v=Te.request(()=>{setTimeout(()=>{C.style.removeProperty("transition-duration")})})})),()=>{Te.cancel(A),Te.cancel(v)}},[i,d,h,m]),Pe(()=>{const C=h.current;C&&i&&P&&(C.setAttribute("hidden","until-found"),r.current==="css-transition"&&C.setAttribute(wt.startingStyle,""))},[i,P,r,h]),o.useEffect(function(){const A=h.current;if(!A)return;function v(D){I.current=!0,g(!0),f(!0,ur(Ws,D))}return A.addEventListener("beforematch",v),()=>{A.removeEventListener("beforematch",v)}},[f,h,g]),o.useMemo(()=>({props:{hidden:P,id:c,ref:X}}),[P,c,X])}let Ln=(function(e){return e.collapsiblePanelHeight="--collapsible-panel-height",e.collapsiblePanelWidth="--collapsible-panel-width",e})({});const ai=o.forwardRef(function(t,r){const{className:s,hiddenUntilFound:a,keepMounted:i,render:l,id:c,...u}=t,{abortControllerRef:f,animationTypeRef:d,height:h,mounted:p,onOpenChange:m,open:b,panelId:g,panelRef:k,runOnceAnimationsFinish:w,setDimensions:x,setHiddenUntilFound:$,setKeepMounted:I,setMounted:H,setPanelIdState:O,setOpen:ee,setVisible:_,state:P,transitionDimensionRef:Z,visible:X,width:C,transitionStatus:A}=xr(),v=a??!1,D=i??!1;Pe(()=>{if(c)return O(c),()=>{O(void 0)}},[c,O]),Pe(()=>{$(v)},[$,v]),Pe(()=>{I(D)},[I,D]);const{props:j}=ii({abortControllerRef:f,animationTypeRef:d,externalRef:r,height:h,hiddenUntilFound:v,id:g,keepMounted:D,mounted:p,onOpenChange:m,open:b,panelRef:k,runOnceAnimationsFinish:w,setDimensions:x,setMounted:H,setOpen:ee,setVisible:_,transitionDimensionRef:Z,visible:X,width:C});qs({open:b&&A==="idle",ref:k,onComplete(){b&&x({height:void 0,width:void 0})}});const U=o.useMemo(()=>({...P,transitionStatus:A}),[P,A]),G=Ve("div",t,{state:U,ref:[r,k],props:[j,{style:{[Ln.collapsiblePanelHeight]:h===void 0?"auto":`${h}px`,[Ln.collapsiblePanelWidth]:C===void 0?"auto":`${C}px`}},u],stateAttributesMapping:yr});return D||v||!D&&p?G:null});function nn(e){return n.jsx(ni,{...e})}function rn({className:e,...t}){return n.jsx(si,{className:L("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 sn({className:e,contentClassName:t,children:r,...s}){return n.jsx(ai,{className:L('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),...s,children:n.jsx("div",{className:L("pt-1",t),children:r})})}const wr=o.createContext(void 0);function Ut(){const e=o.useContext(wr);if(e===void 0)throw new Error(cn(53));return e}let _t=(function(e){return e.scrollAreaCornerHeight="--scroll-area-corner-height",e.scrollAreaCornerWidth="--scroll-area-corner-width",e})({});const Tt=500,_n=16;function Re(e,t,r){if(!e)return 0;const s=getComputedStyle(e),a=r==="x"?"Inline":"Block";return r==="x"&&t==="margin"?parseFloat(s[`${t}InlineStart`])*2:parseFloat(s[`${t}${a}Start`])+parseFloat(s[`${t}${a}End`])}let li=(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 Rt="base-ui-disable-scrollbar",br={className:Rt,getElement(e){return n.jsx("style",{nonce:e,href:Rt,precedence:"base-ui:low",children:`.${Rt}{scrollbar-width:none}.${Rt}::-webkit-scrollbar{display:none}`})}};let lt=(function(e){return 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 hn={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},ci={x:0,y:0},Pn={width:0,height:0},ui={xStart:!1,xEnd:!1,yStart:!1,yEnd:!1},di={x:!1,y:!1,corner:!1},fi=o.forwardRef(function(t,r){const{render:s,className:a,overflowEdgeThreshold:i,...l}=t,c=mi(i),u=cr(),f=Ot(),d=Ot(),{nonce:h,disableStyleElements:p}=Zs(),[m,b]=o.useState(!1),[g,k]=o.useState(!1),[w,x]=o.useState(!1),[$,I]=o.useState(!1),[H,O]=o.useState(Pn),[ee,_]=o.useState(Pn),[P,Z]=o.useState(ui),[X,C]=o.useState(di),A=o.useRef(null),v=o.useRef(null),D=o.useRef(null),j=o.useRef(null),U=o.useRef(null),G=o.useRef(null),S=o.useRef(null),M=o.useRef(!1),z=o.useRef(0),B=o.useRef(0),E=o.useRef(0),q=o.useRef(0),F=o.useRef("vertical"),W=o.useRef(ci),J=Ge(T=>{const pe=T.x-W.current.x,Ce=T.y-W.current.y;W.current=T,Ce!==0&&(x(!0),f.start(Tt,()=>{x(!1)})),pe!==0&&(k(!0),d.start(Tt,()=>{k(!1)}))}),re=Ge(T=>{T.button===0&&(M.current=!0,z.current=T.clientY,B.current=T.clientX,F.current=T.currentTarget.getAttribute(li.orientation),v.current&&(E.current=v.current.scrollTop,q.current=v.current.scrollLeft),U.current&&F.current==="vertical"&&U.current.setPointerCapture(T.pointerId),G.current&&F.current==="horizontal"&&G.current.setPointerCapture(T.pointerId))}),ie=Ge(T=>{if(!M.current)return;const pe=T.clientY-z.current,Ce=T.clientX-B.current;if(v.current){const Ie=v.current.scrollHeight,Ke=v.current.clientHeight,N=v.current.scrollWidth,Y=v.current.clientWidth;if(U.current&&D.current&&F.current==="vertical"){const K=Re(D.current,"padding","y"),me=Re(U.current,"margin","y"),se=U.current.offsetHeight,fe=D.current.offsetHeight-se-K-me,Ne=pe/fe;v.current.scrollTop=E.current+Ne*(Ie-Ke),T.preventDefault(),x(!0),f.start(Tt,()=>{x(!1)})}if(G.current&&j.current&&F.current==="horizontal"){const K=Re(j.current,"padding","x"),me=Re(G.current,"margin","x"),se=G.current.offsetWidth,fe=j.current.offsetWidth-se-K-me,Ne=Ce/fe;v.current.scrollLeft=q.current+Ne*(N-Y),T.preventDefault(),k(!0),d.start(Tt,()=>{k(!1)})}}}),V=Ge(T=>{M.current=!1,U.current&&F.current==="vertical"&&U.current.releasePointerCapture(T.pointerId),G.current&&F.current==="horizontal"&&G.current.releasePointerCapture(T.pointerId)});function ae(T){I(T.pointerType==="touch")}function ne(T){if(ae(T),T.pointerType!=="touch"){const pe=Js(A.current,T.target);b(pe)}}const ce=o.useMemo(()=>({scrolling:g||w,hasOverflowX:!X.x,hasOverflowY:!X.y,overflowXStart:P.xStart,overflowXEnd:P.xEnd,overflowYStart:P.yStart,overflowYEnd:P.yEnd,cornerHidden:X.corner}),[g,w,X.x,X.y,X.corner,P]),he={role:"presentation",onPointerEnter:ne,onPointerMove:ne,onPointerDown:ae,onPointerLeave(){b(!1)},style:{position:"relative",[_t.scrollAreaCornerHeight]:`${H.height}px`,[_t.scrollAreaCornerWidth]:`${H.width}px`}},oe=Ve("div",t,{state:ce,ref:[r,A],props:[he,l],stateAttributesMapping:hn}),de=o.useMemo(()=>({handlePointerDown:re,handlePointerMove:ie,handlePointerUp:V,handleScroll:J,cornerSize:H,setCornerSize:O,thumbSize:ee,setThumbSize:_,touchModality:$,cornerRef:S,scrollingX:g,setScrollingX:k,scrollingY:w,setScrollingY:x,hovering:m,setHovering:b,viewportRef:v,rootRef:A,scrollbarYRef:D,scrollbarXRef:j,thumbYRef:U,thumbXRef:G,rootId:u,hiddenState:X,setHiddenState:C,overflowEdges:P,setOverflowEdges:Z,viewportState:ce,overflowEdgeThreshold:c}),[re,ie,V,J,H,ee,$,g,k,w,x,m,b,u,X,P,ce,c]);return n.jsxs(wr.Provider,{value:de,children:[!p&&br.getElement(h),oe]})});function mi(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 pi=o.createContext(void 0);function ut(e,t=Number.MIN_SAFE_INTEGER,r=Number.MAX_SAFE_INTEGER){return Math.max(t,Math.min(e,r))}function hi(e,t){if(typeof IntersectionObserver>"u")return()=>{};const r=new IntersectionObserver(s=>{s.forEach(a=>{a.intersectionRatio>0&&(t(),r.disconnect())})});return r.observe(e),()=>{r.disconnect()}}let qe=(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})({});const zn=1;function $n(e,t){if(t<=0)return 0;const r=ut(e,0,t),s=r,a=t-r,i=s<=zn,l=a<=zn;return i&&l?s<=a?0:t:i?0:l?t:r}let Un=!1;function gi(){Un||Qs||(typeof CSS<"u"&&"registerProperty"in CSS&&[qe.scrollAreaOverflowXStart,qe.scrollAreaOverflowXEnd,qe.scrollAreaOverflowYStart,qe.scrollAreaOverflowYEnd].forEach(e=>{try{CSS.registerProperty({name:e,syntax:"<length>",inherits:!1,initialValue:"0px"})}catch{}}),Un=!0)}const xi=o.forwardRef(function(t,r){const{render:s,className:a,...i}=t,{viewportRef:l,scrollbarYRef:c,scrollbarXRef:u,thumbYRef:f,thumbXRef:d,cornerRef:h,cornerSize:p,setCornerSize:m,setThumbSize:b,rootId:g,setHiddenState:k,hiddenState:w,handleScroll:x,setHovering:$,setOverflowEdges:I,overflowEdges:H,overflowEdgeThreshold:O,scrollingX:ee,scrollingY:_}=Ut(),P=fr(),Z=o.useRef(!0),X=Ot(),C=Ot(),A=Ge(()=>{const S=l.current,M=c.current,z=u.current,B=f.current,E=d.current,q=h.current;if(!S)return;const F=S.scrollHeight,W=S.scrollWidth,J=S.clientHeight,re=S.clientWidth,ie=S.scrollTop,V=S.scrollLeft;if(F===0||W===0)return;const ae=J>=F,ne=re>=W,ce=re/W,he=J/F,oe=Math.max(0,W-re),de=Math.max(0,F-J);let T=0,pe=0;if(!ne){let Q=0;P==="rtl"?Q=ut(-V,0,oe):Q=ut(V,0,oe),T=$n(Q,oe),pe=oe-T}const Ce=ae?0:ut(ie,0,de),Ie=ae?0:$n(Ce,de),Ke=ae?0:de-Ie,N=ne?0:re,Y=ae?0:J;let K=0,me=0;!ne&&!ae&&(K=M?.offsetWidth||0,me=z?.offsetHeight||0);const se=p.width===0&&p.height===0,fe=se?K:0,Ne=se?me:0,rt=Re(z,"padding","x"),Ae=Re(M,"padding","y"),ze=Re(E,"margin","x"),Je=Re(B,"margin","y"),vt=N-rt-ze,ht=Y-Ae-Je,jt=z?Math.min(z.offsetWidth-fe,vt):vt,kt=M?Math.min(M.offsetHeight-Ne,ht):ht,gt=Math.max(_n,jt*ce),xt=Math.max(_n,kt*he);if(b(Q=>Q.height===xt&&Q.width===gt?Q:{width:gt,height:xt}),M&&B){const Q=M.offsetHeight-xt-Ae-Je,je=F-J,Qe=je===0?0:ie/je,Fe=Math.min(Q,Math.max(0,Qe*Q));B.style.transform=`translate3d(0,${Fe}px,0)`}if(z&&E){const Q=z.offsetWidth-gt-rt-ze,je=W-re,Qe=je===0?0:V/je,Fe=P==="rtl"?ut(Qe*Q,-Q,0):ut(Qe*Q,0,Q);E.style.transform=`translate3d(${Fe}px,0,0)`}const Et=[[qe.scrollAreaOverflowXStart,T],[qe.scrollAreaOverflowXEnd,pe],[qe.scrollAreaOverflowYStart,Ie],[qe.scrollAreaOverflowYEnd,Ke]];for(const[Q,je]of Et)S.style.setProperty(Q,`${je}px`);q&&(ne||ae?m({width:0,height:0}):!ne&&!ae&&m({width:K,height:me})),k(Q=>{const je=ae||ne;return Q.y===ae&&Q.x===ne&&Q.corner===je?Q:{y:ae,x:ne,corner:je}});const He={xStart:!ne&&T>O.xStart,xEnd:!ne&&pe>O.xEnd,yStart:!ae&&Ie>O.yStart,yEnd:!ae&&Ke>O.yEnd};I(Q=>Q.xStart===He.xStart&&Q.xEnd===He.xEnd&&Q.yStart===He.yStart&&Q.yEnd===He.yEnd?Q:He)});Pe(()=>{if(!l.current)return;gi();let S=!1;return hi(l.current,()=>{if(!S){S=!0;return}A()})},[A,l]),Pe(()=>{queueMicrotask(A)},[A,w,P]),Pe(()=>{l.current?.matches(":hover")&&$(!0)},[l,$]),o.useEffect(()=>{const S=l.current;if(typeof ResizeObserver>"u"||!S)return;let M=!1;const z=new ResizeObserver(()=>{if(!M){M=!0;return}A()});return z.observe(S),C.start(0,()=>{const B=S.getAnimations({subtree:!0});B.length!==0&&Promise.allSettled(B.map(E=>E.finished)).then(A).catch(()=>{})}),()=>{z.disconnect(),C.clear()}},[A,l,C]);function v(){Z.current=!1}const D={role:"presentation",...g&&{"data-id":`${g}-viewport`},...(!w.x||!w.y)&&{tabIndex:0},className:br.className,style:{overflow:"scroll"},onScroll(){l.current&&(A(),Z.current||x({x:l.current.scrollLeft,y:l.current.scrollTop}),X.start(100,()=>{Z.current=!0}))},onWheel:v,onTouchMove:v,onPointerMove:v,onPointerEnter:v,onKeyDown:v},j=o.useMemo(()=>({scrolling:ee||_,hasOverflowX:!w.x,hasOverflowY:!w.y,overflowXStart:H.xStart,overflowXEnd:H.xEnd,overflowYStart:H.yStart,overflowYEnd:H.yEnd,cornerHidden:w.corner}),[ee,_,w.x,w.y,w.corner,H]),U=Ve("div",t,{ref:[r,l],state:j,props:[D,i],stateAttributesMapping:hn}),G=o.useMemo(()=>({computeThumbPosition:A}),[A]);return n.jsx(pi.Provider,{value:G,children:U})}),Sr=o.createContext(void 0);function yi(){const e=o.useContext(Sr);if(e===void 0)throw new Error(cn(54));return e}let Pt=(function(e){return e.scrollAreaThumbHeight="--scroll-area-thumb-height",e.scrollAreaThumbWidth="--scroll-area-thumb-width",e})({});const wi=o.forwardRef(function(t,r){const{render:s,className:a,orientation:i="vertical",keepMounted:l=!1,...c}=t,{hovering:u,scrollingX:f,scrollingY:d,hiddenState:h,overflowEdges:p,scrollbarYRef:m,scrollbarXRef:b,viewportRef:g,thumbYRef:k,thumbXRef:w,handlePointerDown:x,handlePointerUp:$,rootId:I,thumbSize:H}=Ut(),O={hovering:u,scrolling:{horizontal:f,vertical:d}[i],orientation:i,hasOverflowX:!h.x,hasOverflowY:!h.y,overflowXStart:p.xStart,overflowXEnd:p.xEnd,overflowYStart:p.yStart,overflowYEnd:p.yEnd,cornerHidden:h.corner},ee=fr();o.useEffect(()=>{const A=g.current,v=i==="vertical"?m.current:b.current;if(!v)return;function D(j){if(!(!A||!v||j.ctrlKey)){if(j.preventDefault(),i==="vertical"){if(A.scrollTop===0&&j.deltaY<0)return}else if(A.scrollLeft===0&&j.deltaX<0)return;if(i==="vertical"){if(A.scrollTop===A.scrollHeight-A.clientHeight&&j.deltaY>0)return}else if(A.scrollLeft===A.scrollWidth-A.clientWidth&&j.deltaX>0)return;i==="vertical"?A.scrollTop+=j.deltaY:A.scrollLeft+=j.deltaX}}return v.addEventListener("wheel",D,{passive:!1}),()=>{v.removeEventListener("wheel",D)}},[i,b,m,g]);const _={...I&&{"data-id":`${I}-scrollbar`},onPointerDown(A){if(A.button===0&&A.currentTarget===A.target&&g.current){if(k.current&&m.current&&i==="vertical"){const v=Re(k.current,"margin","y"),D=Re(m.current,"padding","y"),j=k.current.offsetHeight,U=m.current.getBoundingClientRect(),G=A.clientY-U.top-j/2-D+v/2,S=g.current.scrollHeight,M=g.current.clientHeight,z=m.current.offsetHeight-j-D-v,E=G/z*(S-M);g.current.scrollTop=E}if(w.current&&b.current&&i==="horizontal"){const v=Re(w.current,"margin","x"),D=Re(b.current,"padding","x"),j=w.current.offsetWidth,U=b.current.getBoundingClientRect(),G=A.clientX-U.left-j/2-D+v/2,S=g.current.scrollWidth,M=g.current.clientWidth,z=b.current.offsetWidth-j-D-v,B=G/z;let E;ee==="rtl"?(E=(1-B)*(S-M),g.current.scrollLeft<=0&&(E=-E)):E=B*(S-M),g.current.scrollLeft=E}x(A)}},onPointerUp:$,style:{position:"absolute",touchAction:"none",WebkitUserSelect:"none",userSelect:"none",...i==="vertical"&&{top:0,bottom:`var(${_t.scrollAreaCornerHeight})`,insetInlineEnd:0,[Pt.scrollAreaThumbHeight]:`${H.height}px`},...i==="horizontal"&&{insetInlineStart:0,insetInlineEnd:`var(${_t.scrollAreaCornerWidth})`,bottom:0,[Pt.scrollAreaThumbWidth]:`${H.width}px`}}},P=Ve("div",t,{ref:[r,i==="vertical"?m:b],state:O,props:[_,c],stateAttributesMapping:hn}),Z=o.useMemo(()=>({orientation:i}),[i]),X=i==="vertical"?h.y:h.x;return l||!X?n.jsx(Sr.Provider,{value:Z,children:P}):null}),bi=o.forwardRef(function(t,r){const{render:s,className:a,...i}=t,{thumbYRef:l,thumbXRef:c,handlePointerDown:u,handlePointerMove:f,handlePointerUp:d,setScrollingX:h,setScrollingY:p}=Ut(),{orientation:m}=yi();return Ve("div",t,{ref:[r,m==="vertical"?l:c],state:{orientation:m},props:[{onPointerDown:u,onPointerMove:f,onPointerUp(k){m==="vertical"&&p(!1),m==="horizontal"&&h(!1),d(k)},style:{...m==="vertical"&&{height:`var(${Pt.scrollAreaThumbHeight})`},...m==="horizontal"&&{width:`var(${Pt.scrollAreaThumbWidth})`}}},i]})}),Si=o.forwardRef(function(t,r){const{render:s,className:a,...i}=t,{cornerRef:l,cornerSize:c,hiddenState:u}=Ut(),f=Ve("div",t,{ref:[r,l],props:[{style:{position:"absolute",bottom:0,insetInlineEnd:0,width:c.width,height:c.height}},i]});return u.corner?null:f});function vr({className:e,...t}){return n.jsx(fi,{className:L("group/scroll-area relative outline-none focus-visible:outline-none",e),...t})}function jr({className:e,...t}){return n.jsx(xi,{className:L("h-full w-full outline-none focus-visible:outline-none",e),...t})}function kr({className:e,...t}){return n.jsx(wi,{className:L("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 Er({className:e,...t}){return n.jsx(bi,{className:L("flex-1 rounded-full bg-primary-500 outline-none focus-visible:outline-none",e),...t})}function vi({className:e,...t}){return n.jsx(Si,{className:L("bg-primary-100 outline-none focus-visible:outline-none",e),...t})}function ji(e){return e==="subagent"?as:e==="cron"?ls:cs}function ki(e){if(!e||!Array.isArray(e.content))return"";const t=e.content.map(s=>s.type==="text"?String(s.text??""):"").join(" ");return mr(t).replace(/\s+/g," ").trim()}function Ei(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 Ci(e){if(!e)return null;const t=[e.createdAt,e.created_at,e.timestamp,e.time,e.ts];for(const r of t){const s=Ei(r);if(s)return s}return null}function Ni(e){const t=e-Date.now(),r=Math.abs(t),s=[["minute",6e4],["hour",36e5],["day",864e5]];let a="minute",i=6e4;r>=s[2][1]?[a,i]=s[2]:r>=s[1][1]&&([a,i]=s[1]);const l=Math.round(t/i);return new Intl.RelativeTimeFormat("en",{numeric:"auto"}).format(l,a)}function Ti(e){const t=String(e??"").toLowerCase().trim();return t?t==="error"||t==="failed"?"error":t==="completed"||t==="ended"||t==="done"?"success":null:null}function Ri({session:e,active:t,isGenerating:r=!1,isPinned:s,selectionMode:a=!1,selected:i=!1,onToggleSelect:l,onSelect:c,onTogglePin:u,onRename:f,onDelete:d,onExport:h}){const p=e.label||e.title||e.derivedTitle||e.friendlyId,m=ji(e.kind),b=e.kind==="subagent"&&(e.lastMessage?.role==="assistant"||e.lastMessage?.role==="toolResult")?ki(e.lastMessage):"",g=b.length>50?`${b.slice(0,50).trimEnd()}…`:b,k=e.kind==="subagent"?Ti(e.status):null,w=e.kind==="cron"?Ci(e.lastMessage):null;return n.jsxs(Xe,{to:"/chat/$sessionKey",params:{sessionKey:e.friendlyId},onClick:x=>{if(a){x.preventDefault(),x.stopPropagation(),l?.(e);return}c?.()},className:L("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:L("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(te,{icon:m,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:[s?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"}):k==="success"?n.jsx(te,{icon:tr,size:12,strokeWidth:1.8,className:"text-green-600/80 shrink-0"}):k==="error"?n.jsx(te,{icon:$t,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:Ni(w)}):null]})]}),a?null:n.jsxs(un,{children:[n.jsx(dn,{type:"button",onClick:x=>{x.preventDefault(),x.stopPropagation()},className:L("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(te,{icon:ss,size:20,strokeWidth:1.5})}),n.jsxs(fn,{side:"bottom",align:"end",children:[n.jsxs(tt,{onClick:x=>{x.preventDefault(),x.stopPropagation(),u(e)},className:"gap-2",children:[n.jsx("span",{className:"text-xs","aria-hidden":"true",children:"📌"})," ",s?"Unpin Session":"Pin Session"]}),n.jsxs(tt,{onClick:x=>{x.preventDefault(),x.stopPropagation(),f(e)},className:"gap-2",children:[n.jsx(te,{icon:os,size:20,strokeWidth:1.5})," ","Rename"]}),n.jsxs(tt,{onClick:x=>{x.preventDefault(),x.stopPropagation(),h(e)},className:"gap-2",children:[n.jsx(te,{icon:is,size:20,strokeWidth:1.5})," ","Export"]}),en(e.key)?null:n.jsxs(tt,{onClick:x=>{x.preventDefault(),x.stopPropagation(),d(e)},className:"text-red-700 gap-2 hover:bg-red-50/80 data-highlighted:bg-red-50/80",children:[n.jsx(te,{icon:nr,size:20,strokeWidth:1.5})," ","Delete"]})]})]})]})}function Ii(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 Yt=o.memo(Ri,Ii),Cr="opencami-pinned-sessions",Nr="opencami-sidebar-folders",We={webchat:!1,subagent:!1,cron:!1,other:!1};async function Ai(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 Ue(r))}async function Di(e,t,r){const s=[];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){s.push(u)}}});return await Promise.all(i),s}function Mi(){if(typeof window>"u")return[];try{const e=localStorage.getItem(Cr);if(!e)return[];const t=JSON.parse(e);return Array.isArray(t)?t.filter(r=>typeof r=="string"):[]}catch{return[]}}function Oi(e){if(!(typeof window>"u"))try{const t=Array.from(new Set(e));localStorage.setItem(Cr,JSON.stringify(t))}catch{}}function Li(){if(typeof window>"u")return{...We};try{const e=localStorage.getItem(Nr);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 _i(e){if(!(typeof window>"u"))try{localStorage.setItem(Nr,JSON.stringify(e))}catch{}}function Dt(e,t,r){return r&&e.key?e.key===r:e.friendlyId===t}function Pi(e){if(!e)return!1;const t=e.toLowerCase();return t.includes("running")||t.includes("active")||t.includes("stream")||t.includes("generat")}function Gt(e,t,r,s){return Dt(e,t,r)&&s?!0:Pi(e.status)}const zi=o.memo(function({sessions:t,activeFriendlyId:r,activeSessionKey:s,isStreaming:a=!1,defaultOpen:i=!0,onSelect:l,onRename:c,onDelete:u,onExport:f}){const d=o.useDeferredValue(t),h=pt(),[p,m]=o.useState(()=>Mi()),[b,g]=o.useState(()=>Li()),[k,w]=o.useState(!1),[x,$]=o.useState(()=>new Set),I=o.useMemo(()=>new Set(p),[p]),H=d.filter(S=>I.has(S.key)),O=d.filter(S=>!I.has(S.key)),ee=H.length>0&&O.length>0,_=o.useMemo(()=>{const S={chat:[],webchat:[],subagent:[],cron:[],other:[]};for(const M of O){const z=M.kind??"other";S[z].push(M)}return S},[O]),P=o.useMemo(()=>d.filter(S=>x.has(S.key)),[x,d]),Z=P.length,X=o.useCallback(()=>{w(S=>(S&&$(new Set),!S))},[]),C=o.useCallback(S=>{en(S.key)||$(M=>{const z=new Set(M);return z.has(S.key)?z.delete(S.key):z.add(S.key),z})},[]),A=o.useCallback(()=>{$(new Set(d.filter(S=>!en(S.key)).map(S=>S.key)))},[d]),v=o.useCallback(()=>{w(!1),$(new Set)},[]),D=o.useCallback(async()=>{if(P.length===0||!window.confirm(`Delete ${P.length} sessions? This will archive them.`))return;const M=[];await Di(P,10,async z=>{try{await Ai(z.key)}catch(B){throw M.push(z.label||z.title||z.derivedTitle||z.friendlyId),B}}),M.length>0&&(console.error("[sidebar] Bulk delete failed for some sessions",M),window.alert(`Could not delete ${M.length} session${M.length!==1?"s":""}:
8
+
9
+ ${M.join(`
10
+ `)}`)),w(!1),$(new Set),h.invalidateQueries({queryKey:ge.sessions})},[h,P]),j=o.useCallback(S=>{m(M=>{const B=M.includes(S.key)?M.filter(E=>E!==S.key):[...M,S.key];return Oi(B),B})},[]),U=o.useCallback((S,M)=>{g(z=>{const B={...z,[S]:M};return _i(B),B})},[]);function G(S,M,z){return z.length===0?null:n.jsxs(nn,{className:"flex flex-col",open:b[S],onOpenChange:B=>U(S,B),children:[n.jsxs(rn,{className:L("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:M}),n.jsx("span",{className:L("rounded-full bg-primary-100 px-1.5 py-0.5 text-[10px] font-medium text-primary-700 tabular-nums"),children:z.length})]}),n.jsx(sn,{contentClassName:"flex flex-col gap-px",children:z.map(B=>n.jsx(Yt,{session:B,active:Dt(B,r,s),isGenerating:Gt(B,r,s,a),isPinned:!1,selectionMode:k,selected:x.has(B.key),onToggleSelect:C,onSelect:l,onTogglePin:j,onRename:c,onDelete:u,onExport:f},B.key))})]})}return n.jsxs(nn,{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(rn,{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(te,{icon:us,className:"size-3 transition-transform duration-150 group-data-panel-open:rotate-90"})})]}),n.jsx("button",{type:"button",onClick:X,className:L("text-[11px] font-medium px-1.5 py-0.5 rounded-md transition-colors",k?"text-primary-900 bg-primary-200":"text-primary-500 hover:text-primary-700 hover:bg-primary-100"),children:k?"Done":"Select"})]}),n.jsx(sn,{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(vr,{className:"flex-1 min-h-0",children:[n.jsx(jr,{className:"min-h-0",children:n.jsxs("div",{className:"flex flex-col gap-2 pl-2 pr-2",children:[H.length>0?n.jsx("div",{className:"flex flex-col gap-px",children:H.map(S=>n.jsx(Yt,{session:S,active:Dt(S,r,s),isGenerating:Gt(S,r,s,a),isPinned:!0,selectionMode:k,selected:x.has(S.key),onToggleSelect:C,onSelect:l,onTogglePin:j,onRename:c,onDelete:u,onExport:f},S.key))}):null,ee?n.jsx("div",{className:"my-1 border-t border-primary-200/80"}):null,_.chat.length>0?n.jsxs("div",{className:"flex flex-col gap-px",children:[n.jsx("div",{className:L("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:_.chat.map(S=>n.jsx(Yt,{session:S,active:Dt(S,r,s),isGenerating:Gt(S,r,s,a),isPinned:!1,selectionMode:k,selected:x.has(S.key),onToggleSelect:C,onSelect:l,onTogglePin:j,onRename:c,onDelete:u,onExport:f},S.key))})]}):null,G("webchat","🦎 OpenCami",_.webchat),G("subagent","🤖 Sub-agents",_.subagent),G("cron","⏰ Cron / Isolated",_.cron),G("other","📁 Other",_.other)]})}),n.jsx(kr,{orientation:"vertical",children:n.jsx(Er,{})})]})}),k?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:[Z," selected"]}),n.jsx("button",{type:"button",onClick:A,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:D,disabled:Z===0,className:L("flex-1 inline-flex items-center justify-center gap-1.5 rounded-md px-2 py-1.5 text-xs font-medium transition-colors",Z>0?"bg-red-100 text-red-700 hover:bg-red-200":"bg-primary-100 text-primary-400 cursor-not-allowed"),children:[n.jsx(te,{icon:nr,size:14,strokeWidth:1.5}),"Delete"]}),n.jsx("button",{type:"button",onClick:v,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]})},$i);function $i(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 s=e.sessions[r],a=t.sessions[r];if(s.key!==a.key||s.friendlyId!==a.friendlyId||s.label!==a.label||s.title!==a.title||s.derivedTitle!==a.derivedTitle||s.updatedAt!==a.updatedAt||s.kind!==a.kind||s.status!==a.status||s.lastMessage!==a.lastMessage)return!1}return!0}const Ui=o.lazy(()=>nt(()=>import("./settings-dialog-B8mz99u-.js"),__vite__mapDeps([0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16])).then(e=>({default:e.SettingsDialog}))),Ki=o.lazy(()=>nt(()=>import("./session-export-dialog-ooPnfHh_.js"),__vite__mapDeps([17,1,4,3,5,6,7,8,9,2])).then(e=>({default:e.SessionExportDialog})));function Hi({sessions:e,activeFriendlyId:t,activeSessionKey:r,isStreaming:s=!1,creatingSession:a,onCreateSession:i,isCollapsed:l,onToggleCollapse:c,onSelectSession:u,onActiveSessionDelete:f,onOpenSearch:d}){const{settingsOpen:h,setSettingsOpen:p,pathsLoading:m,pathsError:b,paths:g,handleOpenSettings:k,closeSettings:w,copySessionsDir:x,copyStorePath:$}=Eo(),{deleteSession:I}=Oo(),{renameSession:H}=Lo(),O={duration:.15,ease:l?"easeIn":"easeOut"},[ee,_]=o.useState(!1),[P,Z]=o.useState(null),[X,C]=o.useState(""),[A,v]=o.useState(!1),[D,j]=o.useState(null),[U,G]=o.useState(null),[S,M]=o.useState(""),[z,B]=o.useState(!1),[E,q]=o.useState(null),[F,W]=o.useState(null),[J,re]=o.useState(""),ie=pt();function V(T){Z(T.key),C(T.label||T.title||T.derivedTitle||""),_(!0)}function ae(T){P&&H(P,T),_(!1),Z(null)}function ne(T){j(T.key),G(T.friendlyId),M(T.label||T.title||T.derivedTitle||T.friendlyId),v(!0)}function ce(){if(D&&U){const T=U===t;T&&f&&f(),I(D,U,T)}v(!1),j(null),G(null)}function he(T){q(T.key),W(T.friendlyId),re(T.label||T.title||T.derivedTitle||T.friendlyId),B(!0)}function oe(T){if(E&&F){const pe=ge.history(F,E),Ce=ie.getQueryData(pe);Ce?.messages&&$o(J,Ce.messages,T)}B(!1),q(null),W(null)}const de={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:O,className:de.className,children:[n.jsxs(be.div,{layout:!0,transition:{layout:O},className:L("flex items-center h-12 px-2 justify-between"),children:[n.jsx(De,{initial:!1,children:l?null:n.jsx(be.div,{initial:{opacity:0},animate:{opacity:1},exit:{opacity:0},transition:O,children:n.jsxs(Xe,{to:"/new",className:L(Ze({variant:"ghost",size:"sm"}),"w-full pl-1.5 justify-start"),children:[n.jsx(eo,{className:"size-5"}),n.jsx(to,{})]})})}),n.jsx(Me,{children:n.jsxs(Oe,{children:[n.jsx(Le,{onClick:c,render:n.jsx(we,{size:"icon-sm",variant:"ghost",children:n.jsx(te,{icon:ds,size:20,strokeWidth:1.5})})}),n.jsx(_e,{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:O},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(te,{icon:fs,size:20,strokeWidth:1.5,className:"min-w-5"}),n.jsx(De,{initial:!1,mode:"wait",children:!l&&n.jsx(be.span,{initial:{opacity:0},animate:{opacity:1},exit:{opacity:0},transition:O,className:"overflow-hidden whitespace-nowrap",children:"New Session"})})]}),(()=>{try{const T=localStorage.getItem("opencami-file-explorer");return T===null?!0:T==="true"}catch{return!0}})()&&n.jsx(Me,{children:n.jsxs(Oe,{children:[n.jsx(Le,{asChild:!0,children:n.jsxs(Xe,{to:"/files",className:L(Ze({variant:"ghost",size:"sm"}),"w-full pl-1.5 justify-start"),onClick:u,children:[n.jsx(te,{icon:ms,size:20,strokeWidth:1.5,className:"min-w-5"}),n.jsx(De,{initial:!1,mode:"wait",children:!l&&n.jsx(be.span,{initial:{opacity:0},animate:{opacity:1},exit:{opacity:0},transition:O,className:"overflow-hidden whitespace-nowrap",children:"Files"})})]})}),l&&n.jsx(_e,{side:"right",children:"Files"})]})}),(()=>{try{const T=localStorage.getItem("opencami-memory-viewer");return T===null?!0:T==="true"}catch{return!0}})()&&n.jsx(Me,{children:n.jsxs(Oe,{children:[n.jsx(Le,{asChild:!0,children:n.jsxs(Xe,{to:"/memory",className:L(Ze({variant:"ghost",size:"sm"}),"w-full pl-1.5 justify-start"),onClick:u,children:[n.jsx(te,{icon:Qt,size:20,strokeWidth:1.5,className:"min-w-5"}),n.jsx(De,{initial:!1,mode:"wait",children:!l&&n.jsx(be.span,{initial:{opacity:0},animate:{opacity:1},exit:{opacity:0},transition:O,className:"overflow-hidden whitespace-nowrap",children:"Memory"})})]})}),l&&n.jsx(_e,{side:"right",children:"Memory"})]})}),(()=>{try{return localStorage.getItem("opencami-skills-browser")==="true"}catch{return!1}})()&&n.jsx(Me,{children:n.jsxs(Oe,{children:[n.jsx(Le,{asChild:!0,children:n.jsxs(Xe,{to:"/skills",className:L(Ze({variant:"ghost",size:"sm"}),"w-full pl-1.5 justify-start"),onClick:u,children:[n.jsx(te,{icon:ps,size:20,strokeWidth:1.5,className:"min-w-5"}),n.jsx(De,{initial:!1,mode:"wait",children:!l&&n.jsx(be.span,{initial:{opacity:0},animate:{opacity:1},exit:{opacity:0},transition:O,className:"overflow-hidden whitespace-nowrap",children:"Skills"})})]})}),l&&n.jsx(_e,{side:"right",children:"Skills"})]})}),(()=>{try{return localStorage.getItem("opencami-agent-manager")==="true"}catch{return!1}})()&&n.jsx(Me,{children:n.jsxs(Oe,{children:[n.jsx(Le,{asChild:!0,children:n.jsxs(Xe,{to:"/agents",className:L(Ze({variant:"ghost",size:"sm"}),"w-full pl-1.5 justify-start"),onClick:u,children:[n.jsx(te,{icon:Qt,size:20,strokeWidth:1.5,className:"min-w-5"}),n.jsx(De,{initial:!1,mode:"wait",children:!l&&n.jsx(be.span,{initial:{opacity:0},animate:{opacity:1},exit:{opacity:0},transition:O,className:"overflow-hidden whitespace-nowrap",children:"Agents"})})]})}),l&&n.jsx(_e,{side:"right",children:"Agents"})]})}),(()=>{try{return localStorage.getItem("opencami-cron-manager")==="true"}catch{return!1}})()&&n.jsx(Me,{children:n.jsxs(Oe,{children:[n.jsx(Le,{asChild:!0,children:n.jsxs(Xe,{to:"/bots",className:L(Ze({variant:"ghost",size:"sm"}),"w-full pl-1.5 justify-start"),onClick:u,children:[n.jsx(te,{icon:hs,size:20,strokeWidth:1.5,className:"min-w-5"}),n.jsx(De,{initial:!1,mode:"wait",children:!l&&n.jsx(be.span,{initial:{opacity:0},animate:{opacity:1},exit:{opacity:0},transition:O,className:"overflow-hidden whitespace-nowrap",children:"Cron Jobs"})})]})}),l&&n.jsx(_e,{side:"right",children:"Cron Jobs"})]})}),(()=>{try{return localStorage.getItem("feature_dashboard")==="true"}catch{return!1}})()&&n.jsx(Me,{children:n.jsxs(Oe,{children:[n.jsx(Le,{asChild:!0,children:n.jsxs(Xe,{to:"/dashboard",className:L(Ze({variant:"ghost",size:"sm"}),"w-full pl-1.5 justify-start"),onClick:u,children:[n.jsx(te,{icon:gs,size:20,strokeWidth:1.5,className:"min-w-5"}),n.jsx(De,{initial:!1,mode:"wait",children:!l&&n.jsx(be.span,{initial:{opacity:0},animate:{opacity:1},exit:{opacity:0},transition:O,className:"overflow-hidden whitespace-nowrap",children:"Dashboard"})})]})}),l&&n.jsx(_e,{side:"right",children:"Dashboard"})]})})]}),n.jsx(be.div,{layout:!0,transition:{layout:O},className:"w-full",children:n.jsxs(we,{variant:"ghost",size:"sm",onClick:d,className:"w-full pl-1.5 justify-start",children:[n.jsx(te,{icon:xs,size:20,strokeWidth:1.5,className:"min-w-5"}),n.jsx(De,{initial:!1,mode:"wait",children:!l&&n.jsx(be.span,{initial:{opacity:0},animate:{opacity:1},exit:{opacity:0},transition:O,className:"overflow-hidden whitespace-nowrap",children:"Search"})})]})})]}),n.jsx("div",{className:"flex-1 min-h-0 overflow-hidden",children:n.jsx(De,{initial:!1,children:!l&&n.jsx(be.div,{initial:{opacity:0},animate:{opacity:1},exit:{opacity:0},transition:O,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(zi,{sessions:e,activeFriendlyId:t,activeSessionKey:r,isStreaming:s,onSelect:u,onRename:V,onDelete:ne,onExport:he})})},"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:O},className:"w-full",children:n.jsxs(we,{variant:"ghost",size:"sm",onClick:k,title:l?"Settings":void 0,className:"w-full justify-start pl-1.5",children:[n.jsx(te,{icon:ys,size:20,strokeWidth:1.5,className:"min-w-5"}),n.jsx(De,{initial:!1,mode:"wait",children:!l&&n.jsx(be.span,{initial:{opacity:0},animate:{opacity:1},exit:{opacity:0},transition:O,className:"overflow-hidden whitespace-nowrap",children:"Settings"})})]})})}),h&&n.jsx(o.Suspense,{fallback:null,children:n.jsx(Ui,{open:h,onOpenChange:p,pathsLoading:m,pathsError:b,paths:g,onClose:w,onCopySessionsDir:x,onCopyStorePath:$})}),n.jsx(qo,{open:ee,onOpenChange:_,sessionTitle:X,onSave:ae,onCancel:()=>_(!1)}),n.jsx(Go,{open:A,onOpenChange:v,sessionTitle:S,onConfirm:ce,onCancel:()=>v(!1)}),z&&n.jsx(o.Suspense,{fallback:null,children:n.jsx(Ki,{open:z,onOpenChange:B,sessionTitle:J,onExport:oe,onCancel:()=>B(!1)})})]})}function Fi(e,t){if(e===t)return!0;if(e.length!==t.length)return!1;for(let r=0;r<e.length;r+=1){const s=e[r],a=t[r];if(s.key!==a.key||s.friendlyId!==a.friendlyId||s.label!==a.label||s.title!==a.title||s.derivedTitle!==a.derivedTitle||s.updatedAt!==a.updatedAt||s.kind!==a.kind||s.status!==a.status||s.lastMessage!==a.lastMessage)return!1}return!0}function Wi(e,t){return!(e.activeFriendlyId!==t.activeFriendlyId||e.activeSessionKey!==t.activeSessionKey||e.isStreaming!==t.isStreaming||e.creatingSession!==t.creatingSession||e.isCollapsed!==t.isCollapsed||!Fi(e.sessions,t.sessions))}const Xi=o.memo(Hi,Wi);function Kn(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 Hn(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 Bi({totalTokens:e,contextTokens:t,className:r}){const{percentage:s,usedStr:a,maxStr:i,colors:l,hasData:c,isNearlyFull:u}=o.useMemo(()=>{if(typeof t!="number"||t<=0)return{percentage:0,usedStr:"",maxStr:"",colors:Hn(0),hasData:!1,isNearlyFull:!1};const h=typeof e=="number"&&e>0?e:0,p=Math.min(100,Math.round(h/t*100));return{percentage:p,usedStr:Kn(h),maxStr:Kn(t),colors:Hn(p),hasData:!0,isNearlyFull:p>=95}},[e,t]);if(!c)return null;const f=typeof e=="number"&&e>0?e.toLocaleString():"0",d=typeof t=="number"?t.toLocaleString():"0";return n.jsxs("div",{className:L("group relative flex items-center gap-1.5",r),title:`Context: ${f} / ${d} tokens (${s}%)`,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:L("h-full rounded-full transition-all duration-500 ease-out",l.bar,u&&"animate-pulse"),style:{width:`${s}%`}})}),n.jsx("span",{className:L("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:L("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:L("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-500",children:"Context window"}),n.jsxs("span",{className:L("font-semibold",l.text),children:[s,"%"]})]}),n.jsxs("div",{className:"flex items-center gap-1.5 text-primary-700 dark:text-primary-700",children:[n.jsx("span",{className:"font-medium",children:a}),n.jsx("span",{className:"text-primary-400 dark:text-primary-500",children:"/"}),n.jsx("span",{children:i}),n.jsx("span",{className:"text-primary-400 dark:text-primary-500",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:L("h-full rounded-full transition-all duration-500 ease-out",l.bar),style:{width:`${s}%`}})}),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 Yi=o.memo(Bi);function Gi({activeTitle:e,wrapperRef:t,showSidebarButton:r=!1,onOpenSidebar:s,totalTokens:a,contextTokens:i}){return n.jsxs("div",{ref:t,"data-tauri-drag-region":!0,className:"border-b border-primary-200 pr-4 h-12 flex shrink-0 min-w-0 items-center bg-surface tauri-drag-header",children:[r?n.jsx(we,{size:"icon-sm",variant:"ghost",onClick:s,className:"mr-2 text-primary-800 hover:bg-primary-100",style:{WebkitAppRegion:"no-drag"},"aria-label":"Open sidebar",children:n.jsx(te,{icon:ws,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(Yi,{totalTokens:a,contextTokens:i,className:"ml-3 hidden sm:flex"})]})}const qi=o.memo(Gi);function Vi(e,t){return e.getFullYear()===t.getFullYear()&&e.getMonth()===t.getMonth()&&e.getDate()===t.getDate()}function Ji(e){const t=new Date(e);return Vi(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 Qi(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 Zi({timestamp:e}){const t=Ji(e),r=Qi(e);return n.jsx(Me,{children:n.jsxs(Oe,{children:[n.jsx(Le,{className:"inline-flex items-center text-xs text-primary-600",children:t}),n.jsx(_e,{side:"top",children:r})]})})}function ea({text:e,align:t,timestamp:r,forceVisible:s=!1}){const[a,i]=o.useState(!1),[l,c]=o.useState("idle"),u=o.useRef(null),f=o.useRef(null),d=o.useRef(null),[h,p]=o.useState(()=>{if(typeof window>"u")return!0;try{const w=localStorage.getItem("opencami-tts-enabled");return w===null?!0:w==="true"}catch{return!0}});o.useEffect(()=>{function w(x){x.key==="opencami-tts-enabled"&&p(x.newValue===null?!0:x.newValue==="true")}return window.addEventListener("storage",w),()=>window.removeEventListener("storage",w)},[]),o.useEffect(()=>()=>{d.current?.abort(),u.current&&(u.current.pause(),u.current=null),f.current&&(URL.revokeObjectURL(f.current),f.current=null)},[]);const m=async()=>{try{await navigator.clipboard.writeText(e),i(!0),window.setTimeout(()=>i(!1),1400)}catch{i(!1)}},b=async()=>{if(l==="playing"){d.current?.abort(),u.current&&(u.current.pause(),u.current=null),f.current&&(URL.revokeObjectURL(f.current),f.current=null),c("idle");return}d.current?.abort();const w=new AbortController;d.current=w,c("loading");try{const x=await fetch("/api/tts",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({text:e}),signal:w.signal});if(!x.ok)throw new Error("TTS failed");const $=await x.blob(),I=URL.createObjectURL($);f.current=I;const H=new Audio(I);u.current=H,H.onended=()=>{c("idle"),f.current&&(URL.revokeObjectURL(f.current),f.current=null),u.current=null},H.onerror=()=>{c("idle"),f.current&&(URL.revokeObjectURL(f.current),f.current=null),u.current=null},await H.play(),c("playing")}catch(x){if(x instanceof Error&&x.name==="AbortError"){c("idle");return}c("idle"),f.current&&(URL.revokeObjectURL(f.current),f.current=null),u.current=null}},g=t==="end"?"justify-end":"justify-start",k=t==="start"&&h&&e.trim().length>0;return n.jsxs("div",{className:L("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",s?"opacity-100":"opacity-0",g),children:[n.jsx(Me,{children:n.jsxs(Oe,{children:[n.jsx(Le,{type:"button",onClick:()=>{m().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(te,{icon:a?rr:bs,size:16,strokeWidth:1.6})}),n.jsx(_e,{side:"top",children:"Copy"})]})}),k&&n.jsx(Me,{children:n.jsxs(Oe,{children:[n.jsx(Le,{type:"button",onClick:()=>{b().catch(()=>{})},disabled:l==="loading",className:L("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(te,{icon:l==="loading"?Ss:l==="playing"?sr:vs,size:16,strokeWidth:1.6,className:L(l==="loading"&&"animate-spin")})}),n.jsx(_e,{side:"top",children:l==="loading"?"Generating speech…":l==="playing"?"Stop":"Listen"})]})}),n.jsx(Zi,{timestamp:r})]})}function Tr({children:e,className:t,...r}){return n.jsx("div",{className:L("flex gap-3 w-full",t),...r,children:e})}function ta({children:e,markdown:t=!1,className:r,...s}){const a=L("rounded-[12px] break-words whitespace-normal min-w-0 max-w-full overflow-x-hidden",r);return t?n.jsx(no,{className:a,...s,children:e}):n.jsx("div",{className:a,...s,children:e})}function na({toolPart:e,defaultOpen:t=!1}){const{state:r,input:s,output:a,toolCallId:i}=e,l=(f,d=3200)=>{const h=f===void 0?"undefined":f;let p;if(typeof h=="string")try{p=JSON.stringify(JSON.parse(h),null,2)}catch{p=h}else p=JSON.stringify(h,null,2);return p.length<=d?p:`${p.slice(0,d).trimEnd()}
11
+ …[truncated]`},c=r==="output-error"?$t:r==="output-available"?tr:js,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(nn,{defaultOpen:t,children:[n.jsxs(rn,{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(te,{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(te,{icon:or,size:14,strokeWidth:1.5,className:"ml-auto text-primary-700/80 transition-transform duration-150 group-data-panel-open:rotate-180"})]}),n.jsx(sn,{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})]}),s&&Object.keys(s).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(s)})]}),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 ra=o.lazy(()=>nt(()=>import("./thinking-CA48yhOE.js"),__vite__mapDeps([18,1,3,19,20,5,6,7,8,14,21,4,9,2,11,15,22,13,23,24,25,16,26])).then(e=>({default:e.Thinking}))),sa=o.lazy(()=>nt(()=>import("./search-sources-badge-COHcYFRB.js"),__vite__mapDeps([27,1,3])).then(e=>({default:e.SearchSourcesBadge})));function oa(e,t){const r=t!==void 0,s=t?.isError??!1;let a;r?s?a="output-error":a="output-available":a="input-available";let i;s&&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 Fn(e){return Ye(e).map(r=>{const s=r.id??"",a=r.name??"",i=r.partialJson??"",l=r.arguments?JSON.stringify(r.arguments):"";return`${s}|${a}|${i}|${l}`}).join("||")}function ia(e){if(!e)return"missing";const r=(Array.isArray(e.content)?e.content:[]).map(a=>a.type==="text"?String(a.text??""):"").join("").trim(),s=e.details?JSON.stringify(e.details):"";return`${e.toolCallId??""}|${e.toolName??""}|${e.isError?"1":"0"}|${r}|${s}`}function Wn(e,t){if(!t)return"";const r=Ye(e);return r.length===0?"":r.map(s=>s.id?ia(t.get(s.id)):"missing").join("||")}function aa(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 Xn(e){const t=[e.createdAt,e.created_at,e.timestamp,e.time,e.ts];for(const r of t){const s=aa(r);if(s)return s}return null}function on(e){const r=(Array.isArray(e.content)?e.content:[]).find(s=>s.type==="thinking");return r&&"thinking"in r?String(r.thinking??""):null}function la(e){const t=Array.isArray(e.content)?e.content:[],r=[];for(const s of t)s.type==="image"&&"source"in s&&typeof s.source?.data=="string"&&r.push(s);return r}const ft=/^📎 Uploaded file:\s*(\/uploads\/\S+)\s*$/;function ca(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,s=0;for(;r>=1024&&s<t.length-1;)r/=1024,s++;return`${r.toFixed(1)} ${t[s]}`}function ua(e){if(!e)return[];const t=e.trimStart();if(t.startsWith(">")||t.startsWith("```"))return[];const r=e.split(`
12
+ `),s=[];for(const i of r){if(ft.test(i)){s.push(i);continue}if(s.length>0&&i.trim()===""){s.push(i);continue}break}const a=r[0]??"";return ft.test(a)?s.filter(i=>ft.test(i)):[]}function da(e){const t=[],r=new Set;for(const s of ua(e)){const i=s.match(ft)?.[1];!i||r.has(i)||(r.add(i),t.push({path:i,filename:i.split("/").pop()||i}))}return t}function fa(e){const t=e.split(`
13
+ `);if(!ft.test(t[0]??""))return e.trim();let r=0;for(;r<t.length&&ft.test(t[r]);)r++;for(;r<t.length&&t[r].trim()==="";)r++;return t.slice(r).join(`
14
+ `).replace(/\n{3,}/g,`
15
+
16
+ `).trim()}function ma({message:e,toolResultsByCallId:t,forceActionsVisible:r=!1,isStreaming:s=!1,isLastAssistant:a=!1,aggregatedSearchSources:i,wrapperRef:l,wrapperClassName:c,wrapperScrollMarginTop:u,messageDomId:f,highlighted:d=!1,onRetry:h,onDismiss:p}){const{settings:m}=ro(),b=e.role||"assistant",g=ve(e),k=on(e),w=la(e),x=b==="user",$=x&&e.status==="error",I=o.useMemo(()=>w.map(j=>`data:${j.source.media_type};base64,${j.source.data}`),[w]),H=St(e),O=zt(),ee=Ks(j=>j.openInEditor),_=o.useMemo(()=>da(g),[g]),[P,Z]=o.useState({}),X=o.useMemo(()=>fa(g),[g]);o.useEffect(()=>{let j=!1;async function U(){const G={};await Promise.all(_.map(async S=>{try{const M=await fetch(`/api/files/info?path=${encodeURIComponent(S.path)}`);if(!M.ok){G[S.path]=null;return}const z=await M.json();G[S.path]=typeof z.size=="number"?z.size:null}catch{G[S.path]=null}})),j||Z(G)}return _.length>0?U():Z({}),()=>{j=!0}},[_]);const C=async j=>{ee(j),await O({to:"/files"})},A=b==="assistant"?Ye(e):[],v=A.length>0,D=a&&!s&&m.showSearchSources&&i?i:[];return n.jsxs("div",{ref:l,id:f,"data-message-id":f,style:{contentVisibility:"auto",containIntrinsicSize:"auto 120px",...typeof u=="number"?{scrollMarginTop:`${u}px`}:void 0},className:L("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,d&&"opencami-message-highlight",x?"items-end":"items-start"),children:[k&&m.showReasoningBlocks&&n.jsx("div",{className:"w-full max-w-[var(--opencami-chat-width)]",children:n.jsx(o.Suspense,{fallback:null,children:n.jsx(ra,{content:k})})}),w.length>0&&n.jsx("div",{className:L("flex flex-wrap gap-2 mb-2",x?"justify-end":"justify-start"),children:w.map((j,U)=>n.jsx("img",{src:I[U],alt:`Attachment ${U+1}`,loading:"lazy",decoding:"async",fetchPriority:"low",className:"max-w-[300px] max-h-[300px] rounded-lg object-cover"},U))}),_.length>0&&n.jsx("div",{className:L("mb-2 flex w-full flex-col gap-2",x?"items-end":"items-start"),children:_.map(j=>n.jsxs("button",{type:"button",onClick:()=>{C(j.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(te,{icon:ir,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:j.filename}),n.jsx("p",{className:"text-xs text-primary-600",children:ca(P[j.path]??null)})]})]},j.path))}),n.jsx(Tr,{className:L("min-w-0 max-w-full",x?"flex-row-reverse":""),children:n.jsx(ta,{markdown:!x,isStreaming:!x&&s,className:L("text-primary-900 opencami-text-size min-w-0 max-w-full",x?"opencami-message-user bg-primary-100 px-4 py-[var(--opencami-user-bubble-py)] max-w-[85%]":"opencami-message-assistant bg-transparent w-full",!x&&s&&"stream-fade-in",$&&"opacity-60"),children:X})}),$&&n.jsxs("div",{className:"flex items-center gap-2 text-xs text-red-500 dark:text-red-400",children:[n.jsx("span",{children:"Failed to send"}),h&&n.jsx("button",{type:"button",className:"underline hover:text-red-700 dark:hover:text-red-300",onClick:()=>h(e),children:"Retry"}),p&&n.jsx("button",{type:"button",className:"underline hover:text-red-700 dark:hover:text-red-300",onClick:()=>p(e),children:"Dismiss"})]}),v&&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:A.map(j=>{const U=j.id?t?.get(j.id):void 0,G=oa(j,U);return n.jsx(na,{toolPart:G,defaultOpen:!1},j.id||j.name)})}),D.length>0&&n.jsx("div",{className:"w-full max-w-[var(--opencami-chat-width)]",children:n.jsx(o.Suspense,{fallback:null,children:n.jsx(sa,{sources:D})})}),!v&&n.jsx(ea,{text:g,timestamp:H,align:x?"end":"start",forceVisible:r})]})}function pa(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.onRetry!==t.onRetry||e.onDismiss!==t.onDismiss||e.message.status!==t.message.status||(e.message.role||"assistant")!==(t.message.role||"assistant")||ve(e.message)!==ve(t.message)||on(e.message)!==on(t.message)||Fn(e.message)!==Fn(t.message)||Wn(e.message,e.toolResultsByCallId)!==Wn(t.message,t.toolResultsByCallId)||Xn(e.message)!==Xn(t.message))}const qt=o.memo(ma,pa);function ha({className:e,variant:t="outline",scrollRef:r,...s}){const[a,i]=o.useState(!0),[l,c]=o.useState(!1),u=o.useRef(0),f=o.useCallback(()=>{const d=r.current;if(!d)return;const h=Math.abs(d.scrollHeight-d.scrollTop-d.clientHeight)<100;i(h)},[r]);return o.useLayoutEffect(()=>{const d=r.current;if(!d)return;const h=()=>{u.current=d.scrollTop,f()},p=new MutationObserver(()=>{d&&(d.scrollTop!==u.current&&(u.current=d.scrollTop),f())});return f(),d.addEventListener("scroll",h),p.observe(d,{childList:!0,subtree:!0}),()=>{d.removeEventListener("scroll",h),p.disconnect()}},[f,r]),o.useLayoutEffect(()=>{if(a){c(!1);return}const d=window.setTimeout(()=>{c(!0)},200);return()=>window.clearTimeout(d)},[a]),n.jsx(we,{variant:"secondary",size:"icon-sm",className:L("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 d=r.current;d&&(d.scrollTop=d.scrollHeight,i(!0))},...s,children:n.jsx(te,{icon:or,size:18,strokeWidth:1.8})})}function ga({className:e,viewportRef:t,scrollRef:r,viewportProps:s}){return n.jsxs(vr,{className:L("relative flex flex-1 min-h-0 flex-col",e),children:[n.jsx(jr,{className:"relative will-change-transform overflow-x-hidden",ref:t,...s}),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(ha,{scrollRef:r})})}),n.jsx(kr,{orientation:"vertical",children:n.jsx(Er,{})}),n.jsx(vi,{})]})}function xa(e,t){if(e===t)return!0;const r=Object.keys(e),s=Object.keys(t);if(r.length!==s.length)return!1;for(const a of r)if(e[a]!==t[a])return!1;return!0}function ya(e,t){return!(e.className!==t.className||e.viewportRef!==t.viewportRef||e.scrollRef!==t.scrollRef||!xa(e.viewportProps,t.viewportProps))}const wa=o.memo(ga,ya);function ba({viewportNode:e,children:t}){return e?Qr.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 Sa({children:e,className:t,onUserScroll:r,...s}){const a=o.useRef(null),[i,l]=o.useState(null),c=o.useCallback(function(f){a.current=f,l(f)},[]);return o.useLayoutEffect(()=>{const u=a.current;if(!u)return;const f=()=>{r?.(u.scrollTop)};return u.addEventListener("scroll",f),()=>u.removeEventListener("scroll",f)},[r]),n.jsxs(n.Fragment,{children:[n.jsx(wa,{className:t,viewportRef:c,scrollRef:a,viewportProps:s}),n.jsx(ba,{viewportNode:i,children:e})]})}const va=o.memo(Sa);function ja({children:e,className:t,...r}){return n.jsx("div",{className:L("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 ka({...e}){return n.jsx("div",{className:"h-px w-full shrink-0 scroll-mt-4 pt-6","aria-hidden":"true",...e})}function Ea({as:e="span",className:t,duration:r=4,spread:s=20,children:a,...i}){const l=Math.min(Math.max(s,5),45),c=e;return n.jsx(c,{className:L("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 Ca({className:e}){return n.jsxs("div",{className:L("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(Ea,{className:"text-sm",duration:2,children:"Generating..."})]})}const Bn=o.lazy(()=>nt(()=>import("./follow-up-suggestions-DVXNLqga.js"),__vite__mapDeps([28,1,3])).then(e=>({default:e.FollowUpSuggestions})));function Na({messages:e,loading:t,empty:r,emptyState:s,notice:a,noticePosition:i="start",waitingForResponse:l,isStreaming:c=!1,sessionKey:u,pinToTop:f,pinGroupMinHeight:d,headerHeight:h,contentStyle:p,onFollowUpClick:m,jumpToMessageId:b,onRetryMessage:g,onDismissMessage:k}){const w=o.useRef(null),x=o.useRef(null),$=o.useRef(!1),I=o.useRef(f),H=o.useRef(void 0),[O,ee]=o.useState(null),_=o.useMemo(()=>e.filter(E=>E.role!=="toolResult"),[e]),P=o.useDeferredValue(_),Z=o.useMemo(()=>{const E=new Map;for(const q of e){if(q.role!=="toolResult")continue;const F=q.toolCallId;typeof F=="string"&&F.trim().length>0&&E.set(F,q)}return E},[e]),X=o.useDeferredValue(Z),C=o.useMemo(()=>{const E=[];for(const q of P){if(q.role!=="assistant")continue;const F=Ye(q);for(const W of F){if(!W.id)continue;const J=W.name==="web_search",re=W.name==="web_fetch",ie=W.name==="exec";if(!J&&!re&&!ie)continue;const V=X.get(W.id),ae=V?.content?.map(ne=>ne.type==="text"?String(ne.text??""):"").join("").trim()??"";E.push([W.id,W.name??"",typeof W.arguments?.url=="string"?W.arguments.url:"",V?.isError?"1":"0",ae].join("::"))}}return E.join("||")},[P,X]),A=o.useMemo(()=>{const E=J=>J?J.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,`
17
+ `).trim():"",q=(J,re,ie)=>{try{const V=JSON.parse(J),ae=Array.isArray(V)?V:V?.results??V?.web?.results??[];if(!Array.isArray(ae))return!1;let ne=!1;for(const ce of ae)ce?.url&&ce?.title&&!ie.has(ce.url)&&(ie.add(ce.url),re.push({title:E(ce.title),url:ce.url,snippet:E(ce.description||ce.snippet||ce.content||"")}),ne=!0);return ne}catch{return!1}},F=[],W=new Set;for(const J of P){if(J.role!=="assistant")continue;const re=Ye(J);for(const ie of re){if(!ie.id)continue;const V=ie.name==="web_search",ae=ie.name==="web_fetch",ne=ie.name==="exec";if(!V&&!ae&&!ne)continue;const ce=X.get(ie.id);if(!ce)continue;const he=ce.content?.map(oe=>oe.type==="text"?String(oe.text??""):"").join("").trim();if(he){if(V||ne){if(ne&&(!he.includes('"results"')||!he.includes('"url"')))continue;let oe=he;const de=he.indexOf("{");de>0&&(oe=he.slice(de));const T=oe.lastIndexOf("}");T>0&&(oe=oe.slice(0,T+1)),q(oe,F,W)}else if(ae){const oe=ie.arguments?.url;if(oe&&!W.has(oe)){W.add(oe);let de;try{de=new URL(oe).hostname}catch{de=oe}F.push({title:de,url:oe})}}}}}return F},[C,P,X]),v=_.map((E,q)=>({message:E,index:q})).filter(({message:E})=>E.role!=="user").map(({index:E})=>E).pop(),D=_.map((E,q)=>({message:E,index:q})).filter(({message:E})=>E.role==="assistant").map(({index:E})=>E).pop(),j=_.map((E,q)=>({message:E,index:q})).filter(({message:E})=>E.role==="user").map(({index:E})=>E).pop(),U=l&&(typeof j!="number"||typeof v!="number"||v<j),G=typeof j=="number"?j:-1,S=f&&G>=0,M=typeof D=="number"?_[D]:void 0,z=M?ve(M):"",B=!l&&!c&&z.length>0&&m!==void 0&&(typeof j!="number"||typeof D!="number"||D>j);return o.useLayoutEffect(()=>{if(!t){if(f){const E=!I.current||H.current!==j;I.current=!0,H.current=j,E&&x.current&&($.current=!0,x.current.scrollIntoView({behavior:"auto",block:"start"}),window.setTimeout(()=>{$.current=!1},0));return}I.current=!1,H.current=j,w.current&&($.current=!0,w.current.scrollIntoView({behavior:"auto",block:"end"}),window.setTimeout(()=>{$.current=!1},0))}},[t,_.length,u,f,j]),o.useEffect(()=>{if(!b||t)return;const E=document.getElementById(`message-${b}`);if(!E)return;E.scrollIntoView({behavior:"smooth",block:"center"}),ee(b);const q=window.setTimeout(()=>{ee(F=>F===b?null:F)},1800);return()=>window.clearTimeout(q)},[b,t,_]),n.jsx(va,{className:"flex-1 min-h-0 -mb-4",children:n.jsxs(ja,{className:"pt-6",style:p,children:[a&&i==="start"?a:null,r&&!a?s??n.jsx("div",{"aria-hidden":!0}):S?n.jsxs(n.Fragment,{children:[_.slice(0,G).map((E,q)=>{const F=typeof E.id=="string"?E.id:void 0,W=F||q,J=typeof v=="number"&&q===v,re=typeof v=="number"&&q===v,ie=E.role==="assistant"&&Ye(E).length>0;return n.jsx(qt,{message:E,toolResultsByCallId:ie?Z:void 0,forceActionsVisible:J,isStreaming:re&&c,isLastAssistant:re,aggregatedSearchSources:re?A:void 0,messageDomId:F?`message-${F}`:void 0,highlighted:O===F,onRetry:g,onDismiss:k},W)}),n.jsxs("div",{className:"flex flex-col gap-[var(--opencami-msg-gap)]",style:{minHeight:`${Math.max(0,d)}px`},children:[_.slice(G).map((E,q)=>{const F=G+q,W=typeof E.id=="string"?E.id:void 0,J=W||F,re=typeof v=="number"&&F===v,ie=typeof v=="number"&&F===v,V=F===j?x:void 0,ae=F===j?"scroll-mt-0":void 0,ne=F===j?h:void 0,ce=E.role==="assistant"&&Ye(E).length>0;return n.jsx(qt,{message:E,toolResultsByCallId:ce?Z:void 0,forceActionsVisible:re,isStreaming:ie&&c,isLastAssistant:ie,aggregatedSearchSources:ie?A:void 0,wrapperRef:V,wrapperClassName:ae,wrapperScrollMarginTop:ne,messageDomId:W?`message-${W}`:void 0,highlighted:O===W,onRetry:g,onDismiss:k},J)}),U?n.jsx("div",{className:"py-2",children:n.jsx(Ca,{})}):null,B&&m?n.jsx(o.Suspense,{fallback:null,children:n.jsx(Bn,{responseText:z,onSuggestionClick:m,disabled:l})}):null]})]}):n.jsxs(n.Fragment,{children:[_.map((E,q)=>{const F=typeof E.id=="string"?E.id:void 0,W=F||q,J=typeof v=="number"&&q===v,re=typeof v=="number"&&q===v,ie=E.role==="assistant"&&Ye(E).length>0;return n.jsx(qt,{message:E,toolResultsByCallId:ie?Z:void 0,forceActionsVisible:J,isStreaming:re&&c,isLastAssistant:re,aggregatedSearchSources:re?A:void 0,messageDomId:F?`message-${F}`:void 0,highlighted:O===F,onRetry:g,onDismiss:k},W)}),B&&m?n.jsx(o.Suspense,{fallback:null,children:n.jsx(Bn,{responseText:z,onSuggestionClick:m,disabled:l})}):null]}),a&&i==="end"?a:null,n.jsx(ka,{ref:w})]})})}function Ta(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&&e.onRetryMessage===t.onRetryMessage&&e.onDismissMessage===t.onDismissMessage}const Ra=o.memo(Na,Ta),an=oo()(so(e=>({level:"low",setLevel:t=>e({level:t})}),{name:"thinking-level"}));function Ia(){const e=an(r=>r.level),t=an(r=>r.setLevel);return{level:e,setLevel:t}}const Vt=[{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 Aa({className:e}){const{level:t,setLevel:r}=Ia(),s=Vt.find(a=>a.value===t)??Vt[1];return n.jsxs(un,{children:[n.jsxs(dn,{className:L("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(te,{icon:Qt,size:20,strokeWidth:1.5,className:L(t==="off"?"text-primary-400":"text-primary-700")}),n.jsx("span",{className:"text-pretty",children:s.shortLabel})]}),n.jsx(fn,{side:"top",align:"start",className:"min-w-[190px]",children:Vt.map(a=>n.jsxs(tt,{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(te,{icon:rr,size:20,strokeWidth:1.5,className:"text-primary-600"})]},a.value))})]})}function Da({commands:e,selectedIndex:t,onSelect:r,className:s}){return e.length===0?null:n.jsx("div",{className:L("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",s),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:L("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-700 dark:text-primary-700",children:a.command}),n.jsx("span",{className:"text-xs text-primary-600 dark:text-primary-600",children:a.description})]})},a.command)})})})}const Ma=o.memo(Da),Rr=o.createContext({isLoading:!1,value:"",setValue:()=>{},maxHeight:240,onSubmit:void 0,disabled:!1,textareaRef:Zr.createRef()});let mt=null,Yn=!1;function Oa(){Yn||typeof window>"u"||(Yn=!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 s=e.key.length===1,a=e.key==="Backspace";!s&&!a||!mt||mt.disabled||mt.focus()}))}function Ir(){return o.useContext(Rr)}function La({className:e,isLoading:t=!1,maxHeight:r=240,value:s,onValueChange:a,onSubmit:i,children:l,disabled:c=!1,onClick:u,...f}){const[d,h]=o.useState(s||""),p=o.useRef(null);Oa();function m(g){h(g),a?.(g)}function b(g){c||p.current?.focus(),u?.(g)}return n.jsx(Me,{children:n.jsx(Rr.Provider,{value:{isLoading:t,value:s??d,setValue:a??m,maxHeight:r,onSubmit:i,disabled:c,textareaRef:p},children:n.jsx("div",{onClick:b,className:L("bg-surface dark:bg-primary-200 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),...f,children:l})})})}function _a({className:e,onKeyDown:t,disableAutosize:r=!1,inputRef:s,...a}){const{value:i,setValue:l,maxHeight:c,onSubmit:u,disabled:f,textareaRef:d}=Ir();function h(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){d.current=g,typeof s=="function"?s(g):s&&"current"in s&&(s.current=g),g?mt=g:mt===g&&(mt=null),h(g)}o.useLayoutEffect(()=>{if(!d.current||r)return;const g=d.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 m(g){h(g.target),l(g.target.value)}function b(g){g.key==="Enter"&&!g.shiftKey&&(g.preventDefault(),u?.()),t?.(g)}return n.jsx("textarea",{ref:p,value:i,onChange:m,onKeyDown:b,className:L("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:f,"aria-disabled":f,...a})}function Pa({children:e,className:t,...r}){return n.jsx("div",{className:L("flex items-center gap-2",t),...r,children:e})}function Gn({tooltip:e,children:t,className:r,side:s="top",...a}){const{disabled:i}=Ir();return n.jsxs(Oe,{...a,children:[n.jsx(Le,{disabled:i,onClick:l=>l.stopPropagation(),children:t}),n.jsx(_e,{side:s,className:r,children:e})]})}const Ar="opencami-personas-enabled",ln="opencami-active-persona";function za(){if(typeof window>"u")return!0;try{const e=localStorage.getItem(Ar);return e===null?!0:e==="true"}catch{return!0}}function $a(){if(typeof window>"u")return null;try{const e=localStorage.getItem(ln);return e?JSON.parse(e):null}catch{return null}}function qn(e){if(!(typeof window>"u"))try{e?localStorage.setItem(ln,JSON.stringify(e)):localStorage.removeItem(ln)}catch{}}const Ua={core:"Core",creative:"Creative",curator:"Curator",learning:"Learning",lifestyle:"Lifestyle",professional:"Professional"};function Ka({className:e,onSelect:t}){const[r,s]=o.useState({}),[a,i]=o.useState(null),[l,c]=o.useState(!0),[u,f]=o.useState(!1),[d,h]=o.useState(za),p=o.useRef(null);o.useEffect(()=>{const k=w=>{w.key===Ar&&h(w.newValue===null?!0:w.newValue==="true")};return window.addEventListener("storage",k),()=>window.removeEventListener("storage",k)},[]),o.useEffect(()=>{let k=!0;async function w(){p.current?.abort();const x=new AbortController;p.current=x;try{c(!0);const $=await fetch("/api/personas",{signal:x.signal});if(!$.ok){f(!1);return}const I=await $.json();if(!k)return;I.ok&&I.available?(s(I.personas),f(!0),i($a())):f(!1)}catch($){if($ instanceof Error&&$.name==="AbortError"||!k)return;f(!1)}finally{k&&c(!1)}}return w(),()=>{k=!1,p.current?.abort()}},[]);const m=o.useCallback(k=>{i(k),qn(k),t(`/persona ${k.id}`)},[t]),b=o.useCallback(()=>{i(null),qn(null),t("/persona exit")},[t]);if(l||!u||!d)return null;const g=Object.entries(r);return g.length===0?null:n.jsxs(un,{children:[n.jsxs(dn,{className:L("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(fn,{side:"top",align:"start",className:"w-[300px] max-h-[360px] overflow-y-auto",children:[a&&n.jsxs(n.Fragment,{children:[n.jsxs(tt,{onClick:b,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(([k,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:Ua[k]??k}),w.map(x=>n.jsxs(tt,{onClick:()=>m(x),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:x.emoji}),n.jsx("span",{className:"truncate",children:x.name})]}),n.jsx("span",{className:"text-[11px] text-primary-400 truncate ml-2 max-w-[140px]",children:x.description})]},x.id))]},k))]})]})}const Ha=[{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 Fa({className:e,onCommandSelect:t}){const[r,s]=o.useState(!1);function a(i){t?.(i),s(!1)}return n.jsxs(n.Fragment,{children:[n.jsx(we,{variant:"ghost",size:"sm",onClick:()=>s(!0),className:L("h-7 w-7 p-0",e),title:"Show commands (Ctrl+/)",children:n.jsx(te,{icon:Cn,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(te,{icon:Cn,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:()=>s(!1),className:"h-7 w-7 p-0",children:n.jsx(te,{icon:$t,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"}),Ha.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-700 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 Wa=10*1024*1024,ct=1280,Xa=.75,Ba=300*1024,Ya=["image/png","image/jpeg","image/gif","image/webp"],Dr=["pdf","txt","md","csv","json","xml","yaml","yml","log","py","js","ts","html","css"],Ga=[".png",".jpg",".jpeg",".gif",".webp",...Dr.map(e=>`.${e}`)].join(",");function qa(){if(typeof document>"u")return!1;try{const e=document.createElement("canvas");return!!(e.getContext&&e.getContext("2d"))}catch{return!1}}async function Va(e){if(!qa())throw new Error("Image compression not available in this browser");return new Promise((t,r)=>{const s=new Image,a=URL.createObjectURL(e),i=()=>{URL.revokeObjectURL(a)};s.onload=()=>{try{let l=s.width,c=s.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 f=u.getContext("2d");if(!f){i(),r(new Error("Failed to get canvas context"));return}f.drawImage(s,0,0,l,c);const d=e.type==="image/png"?"image/png":"image/jpeg";let h=Xa,p=u.toDataURL(d,h);if(d==="image/jpeg"){const b=Ba*1.37;for(;p.length>b&&h>.3;)h-=.1,p=u.toDataURL(d,h)}const m=p.split(",")[1];if(!m){i(),r(new Error("Failed to encode image"));return}i(),t(m)}catch(l){i(),r(l instanceof Error?l:new Error("Image compression failed"))}},s.onerror=()=>{i(),r(new Error("Failed to load image"))},s.src=a})}function Mr(e){return Ya.includes(e.type)}function Ja(e){const t=e.name.includes(".")?e.name.split(".").pop()?.toLowerCase():"";return!!(t&&Dr.includes(t))}async function Qa(e){const t=crypto.randomUUID();if(!Mr(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>Wa)return{id:t,file:e,preview:null,type:"image",base64:null,error:"Image is too large. Maximum size is 10MB."};try{const r=await Va(e),s=URL.createObjectURL(e);return{id:t,file:e,preview:s,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 Za({onFilesSelect:e,disabled:t=!1,className:r}){const s=o.useRef(null),a=o.useCallback(()=>{s.current?.click()},[]),i=o.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:s,type:"file",accept:Ga,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(te,{icon:ks,size:18,strokeWidth:1.8})})]})}function Vn(e){return e<1024?`${e} B`:e<1024*1024?`${(e/1024).toFixed(1)} KB`:`${(e/(1024*1024)).toFixed(1)} MB`}function el(e){const t=e.split(".");return t.length>1&&t.pop()?.toUpperCase()||""}function tl({attachment:e,onRemove:t,className:r}){o.useEffect(()=>()=>{e.preview&&URL.revokeObjectURL(e.preview)},[e.preview]);const s=!!e.error;return e.type==="file"&&!s?n.jsxs("div",{className:L("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," (",Vn(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:L("relative flex items-center gap-3 rounded-xl border p-2 pr-3",s?"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(te,{icon:ir,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}),s?n.jsx("p",{className:"text-xs text-red-600",children:e.error}):n.jsxs("p",{className:"text-xs text-primary-500",children:[el(e.file.name)," •"," ",Vn(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(te,{icon:$t,size:14})})]})}function nl({attachments:e,onRemove:t,className:r}){return e.length===0?null:n.jsx("div",{className:L("flex flex-wrap gap-2 px-4",r),children:e.map(s=>n.jsx(tl,{attachment:s,onRemove:t},s.id))})}const Jn=[{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 rl(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function sl(e,t){const r=rl(t),s=new RegExp(`(?:^|\\n\\n)📎 Uploaded file: ${r}\\n\\nPlease analyze this file\\.(?=\\n\\n|$)`);return e.replace(s,(a,i)=>i===0?"":`
18
+
19
+ `).trim()}function ol({onSubmit:e,isLoading:t,disabled:r,wrapperRef:s,inputRef:a}){const[i,l]=o.useState(""),[c,u]=o.useState(""),[f,d]=o.useState([]),[h,p]=o.useState(0),[m,b]=o.useState(!1),[g,k]=o.useState(!1),[w,x]=o.useState(!1),[$,I]=o.useState(0),[H,O]=o.useState(!1),[ee,_]=o.useState(null),P=o.useRef(null),Z=o.useRef([]),X=o.useRef(null),C=o.useRef(null),A=o.useRef(null),v=o.useRef(null),D=o.useMemo(()=>/^\/\S*$/.test(i)&&!m,[i,m]),j=o.useMemo(()=>D?i.slice(1).toLowerCase():"",[D,i]),U=o.useMemo(()=>D?j?Jn.filter(N=>N.command.slice(1).toLowerCase().startsWith(j)):Jn:[],[D,j]),G=o.useCallback(N=>{v.current=N,a&&(typeof a=="function"?a(N):a.current=N)},[a]),S=o.useCallback(()=>{typeof window>"u"||window.requestAnimationFrame(()=>{v.current?.focus()})},[]),M=o.useCallback(N=>{_(N)},[]),z=o.useCallback(()=>{l(""),d([]),p(0),b(!1),S()},[S]),B=o.useCallback(N=>{l(Y=>{const K=`📎 Uploaded file: ${N}
20
+
21
+ Please analyze this file.`;return Y.trim()?`${Y.trim()}
22
+
23
+ ${K}`:K})},[]),E=o.useCallback(async()=>{await fetch("/api/files/mkdir",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({path:"/uploads"})})},[]),q=o.useCallback(async N=>{const Y=crypto.randomUUID();if(!Ja(N))return{id:Y,file:N,preview:null,type:"file",base64:null,error:"Unsupported file type for upload."};try{await E();const K=new FormData;K.append("path","/uploads"),K.append("file",N);const me=await fetch("/api/files/upload",{method:"POST",body:K});if(!me.ok){const Ne=await me.text();throw new Error(Ne||"File upload failed")}const fe=(await me.json()).files?.[0]?.path;if(!fe)throw new Error("Upload succeeded but no path was returned");return B(fe),{id:Y,file:N,preview:null,type:"file",base64:null,uploadedPath:fe}}catch(K){return{id:Y,file:N,preview:null,type:"file",base64:null,error:K instanceof Error?K.message:"File upload failed"}}},[B,E]),F=o.useCallback(async N=>{if(N.length===0)return;const Y=await Promise.all(N.map(K=>Mr(K)?Qa(K):q(K)));d(K=>[...K,...Y]),S()},[S,q]),W=o.useCallback(N=>{let Y;d(K=>{const me=K.find(se=>se.id===N);return me?.uploadedPath&&(Y=me.uploadedPath),K.filter(se=>se.id!==N)}),Y&&l(K=>sl(K,Y))},[]),J=o.useCallback(N=>{Array.from(N.dataTransfer.types).includes("Files")&&(N.preventDefault(),N.dataTransfer.dropEffect="copy",k(!0))},[]),re=o.useCallback(N=>{N.preventDefault();const Y=N.relatedTarget;Y&&N.currentTarget.contains(Y)||k(!1)},[]),ie=o.useCallback(async N=>{N.preventDefault(),k(!1);const Y=Array.from(N.dataTransfer.files);Y.length!==0&&await F(Y)},[F]),V=o.useCallback(N=>{l(N),p(0),b(!1),S()},[S]),ae=o.useCallback(N=>{l(N),p(0),b(!1)},[]),ne=o.useCallback(N=>{l(`${N.command} `),p(0),b(!1),S()},[S]),ce=o.useCallback(()=>{if(r)return;if(D&&U.length>0){const K=Math.min(h,U.length-1);ne(U[K]);return}const N=i.trim(),Y=f.filter(K=>!K.error&&K.base64);N.length===0&&Y.length===0||(e(N,{reset:z,setValue:V,model:c||void 0,attachments:Y}),S())},[r,D,U,h,ne,i,f,e,z,V,c,S]),he=o.useCallback(N=>{e(N,{reset:z,setValue:V,model:c||void 0,attachments:[]}),S()},[S,e,z,V,c]),oe=o.useCallback(N=>{if(D){if(N.key==="Escape"){N.preventDefault(),b(!0),p(0);return}if(U.length!==0){if(N.key==="ArrowDown"){N.preventDefault(),p(Y=>(Y+1)%U.length);return}if(N.key==="ArrowUp"){N.preventDefault(),p(Y=>(Y-1+U.length)%U.length);return}if(N.key==="Tab"){N.preventDefault();const Y=Math.min(h,U.length-1);ne(U[Y])}}}},[D,U,h,ne]);o.useEffect(()=>()=>{C.current?.abort(),X.current&&clearInterval(X.current),P.current&&P.current.state!=="inactive"&&P.current.stop(),A.current&&A.current.abort()},[]);const de=o.useCallback(()=>{if(typeof window>"u")return"auto";try{return localStorage.getItem("opencami-stt-provider")||"auto"}catch{return"auto"}},[]),T=o.useCallback(()=>{P.current&&P.current.state!=="inactive"&&P.current.stop(),A.current&&A.current.stop(),X.current&&(clearInterval(X.current),X.current=null),x(!1),I(0)},[]),pe=o.useCallback(async()=>{_(null);const N=de();if(N==="browser"){const Y=window.SpeechRecognition||window.webkitSpeechRecognition;if(!Y){M("Web Speech API is not supported in this browser.");return}const K=new Y;K.continuous=!0,K.interimResults=!1,K.lang=navigator.language||"en-US",A.current=K,x(!0),I(0),X.current=setInterval(()=>{I(se=>se>=119?(T(),0):se+1)},1e3);let me="";K.onresult=se=>{for(let fe=se.resultIndex;fe<se.results.length;fe++)se.results[fe].isFinal&&(me+=se.results[fe][0].transcript)},K.onend=()=>{x(!1),I(0),X.current&&clearInterval(X.current),me.trim()&&(_(null),l(se=>se+(se?" ":"")+me.trim()),S())},K.onerror=()=>{x(!1),I(0),X.current&&clearInterval(X.current),M("Speech recognition failed. Try the Browser provider again or switch providers in Settings.")},K.start();return}try{const Y=await navigator.mediaDevices.getUserMedia({audio:!0}),K=MediaRecorder.isTypeSupported("audio/webm")?"audio/webm":"audio/mp4",me=new MediaRecorder(Y,{mimeType:K});P.current=me,Z.current=[],me.ondataavailable=se=>{se.data.size>0&&Z.current.push(se.data)},me.onstop=async()=>{Y.getTracks().forEach(fe=>fe.stop());const se=new Blob(Z.current,{type:K});if(se.size!==0){O(!0);try{const fe=new FormData;fe.append("audio",se,`recording.${K==="audio/webm"?"webm":"mp4"}`),N!=="auto"&&fe.append("provider",N),C.current?.abort();const Ne=new AbortController;C.current=Ne;const Ae=await(await fetch("/api/stt",{method:"POST",body:fe,signal:Ne.signal})).json();Ae.ok&&Ae.text?(_(null),l(ze=>ze+(ze?" ":"")+Ae.text),S()):Ae.ok||(console.warn("STT failed:",Ae.error),M(Ae.error||"Speech-to-text failed. Try the Browser provider in Settings."))}catch(fe){if(fe instanceof Error&&fe.name==="AbortError")return;console.warn("STT request failed:",fe),M("Could not reach speech-to-text service.")}finally{O(!1)}}},x(!0),I(0),X.current=setInterval(()=>{I(se=>se>=119?(T(),0):se+1)},1e3),me.start()}catch(Y){const K=Y instanceof Error?Y.message:String(Y);if(K.includes("NotAllowedError")||K.includes("Permission"))try{(await navigator.permissions.query({name:"microphone"})).state==="denied"?M("Microphone access is blocked. Please enable it in your browser/app settings."):M("Microphone permission was not granted. Please try again and allow access when prompted.")}catch{M("Could not access microphone. Please check your browser settings and allow microphone access for this site.")}else M("Could not access microphone: "+K)}},[de,T,S,M]),Ce=o.useCallback(()=>{w?T():pe()},[w,T,pe]),Ie=f.filter(N=>!N.error&&N.base64),Ke=r||i.trim().length===0&&Ie.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:s,onDragOver:J,onDragLeave:re,onDrop:ie,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(La,{value:i,onValueChange:ae,onSubmit:ce,isLoading:t,disabled:r,children:[n.jsx(nl,{attachments:f,onRemove:W}),ee&&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:ee}),D&&U.length>0&&n.jsx(Ma,{commands:U,selectedIndex:Math.min(h,U.length-1),onSelect:ne}),n.jsx(_a,{placeholder:"Type a message…",inputRef:G,onKeyDown:oe}),n.jsxs(Pa,{className:"justify-between px-3",children:[n.jsxs("div",{className:"flex items-center gap-1",children:[n.jsx(Aa,{}),n.jsx(Ka,{onSelect:he}),n.jsx(Fa,{onCommandSelect:N=>ae(N+" ")})]}),n.jsxs("div",{className:"flex items-center gap-1",children:[n.jsx(Za,{onFilesSelect:F,disabled:r}),n.jsx(Gn,{tooltip:w?"Stop recording":"Voice input",children:n.jsx(we,{onClick:Ce,disabled:r||H,size:"icon-sm",variant:w?"destructive":"ghost",className:`rounded-full ${w?"animate-pulse":""}`,"aria-label":w?"Stop recording":"Voice input",children:H?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($/60),":",String($%60).padStart(2,"0")]}),n.jsx(te,{icon:sr,size:14,strokeWidth:2})]}):n.jsx(te,{icon:Es,size:18,strokeWidth:2})})}),n.jsx(Gn,{tooltip:"Send message",children:n.jsx(we,{onClick:ce,disabled:Ke,size:"icon-sm",className:"rounded-full","aria-label":"Send message",children:n.jsx(te,{icon:Cs,size:18,strokeWidth:2})})})]})]})]})]})}const il=o.memo(ol);function al({title:e,description:t,detail:r,actionLabel:s,onAction:a,className:i}){return n.jsx("div",{className:L("w-full max-w-[var(--opencami-chat-width)]",i),children:n.jsx(Tr,{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,s&&a?n.jsx("div",{className:"mt-3",children:n.jsx(we,{size:"sm",variant:"outline",onClick:a,children:s})}):null]})})})}function ll({state:e,error:t,onRetry:r,className:s}){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(al,{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:s})}function cl(){const e=o.useRef(null),t=o.useRef(null),r=o.useRef(null),[s,a]=o.useState(0),[i,l]=o.useState(0);return o.useLayoutEffect(()=>{const c=e.current,u=t.current,f=r.current;if(!f)return;const d=()=>{const p=c?.offsetHeight??0,m=u?.offsetHeight??0,b=f.clientHeight;f.style.setProperty("--chat-header-height",`${Math.max(0,p)}px`),f.style.setProperty("--chat-composer-height",`${Math.max(0,m)}px`),l(p),a(Math.max(0,b-p-m))};d();const h=new ResizeObserver(()=>d());return c&&h.observe(c),u&&h.observe(u),()=>h.disconnect()},[]),{headerRef:e,composerRef:t,mainRef:r,pinGroupMinHeight:s,headerHeight:i}}function ul({activeFriendlyId:e,activeSessionKey:t,forcedSessionKey:r,isNewChat:s,isRedirecting:a,activeExists:i,sessionsReady:l,queryClient:c}){const u=r||t||e,f=ge.history(e,u),d=Mt({queryKey:f,queryFn:async function(){const x=c.getQueryData(f),$=Array.isArray(x?.messages)?x.messages.filter(_=>_.status==="sending"||_.__optimisticId?!0:!!_.clientId):[],I=Array.isArray(x?.messages)?x.messages:[],H=await yo({sessionKey:u,friendlyId:e}),O=fl(H.messages,I);if(!$.length)return{...H,messages:O};const ee=ml(O,$);return{...H,messages:ee}},enabled:!s&&!!e&&!a&&(!l||i),placeholderData:function(){return c.getQueryData(f)},gcTime:1e3*60*10}),h=o.useRef(""),p=o.useRef([]),m=o.useMemo(()=>{const w=Array.isArray(d.data?.messages)?d.data.messages:[],x=w[w.length-1],$=x&&typeof x.id=="string"?x.id:"",I=`${w.length}:${x?.role??""}:${$}:${ve(x??{content:[]}).slice(-32)}`;return I===h.current?p.current:(h.current=I,p.current=w,w)},[d.data?.messages]),b=d.error instanceof Error?d.error.message:null,g=o.useMemo(()=>{if(r)return r;const w=d.data?.sessionKey;return typeof w=="string"&&w.trim().length>0?w.trim():t},[t,r,d.data?.sessionKey]);return{historyQuery:d,historyMessages:m,displayMessages:m,historyError:b,resolvedSessionKey:g,activeCanonicalKey:s?"new":g||e,sessionKeyForHistory:u}}function dl(e,t){return e.findIndex(r=>{if(t.clientId&&r.clientId&&t.clientId===r.clientId||t.__optimisticId&&r.__optimisticId&&t.__optimisticId===r.__optimisticId)return!0;if(t.role&&r.role&&t.role!==r.role)return!1;const s=ve(t);if(!s||s!==ve(r))return!1;const a=St(t),i=St(r);return Math.abs(a-i)<=1e4})}function bt(e){return Array.isArray(e.content)?e.content.filter(t=>{if(typeof t!="object"||t===null)return!1;const r=t;if(r.type!=="image")return!1;const s=r.source;return typeof s?.data=="string"&&s.data.length>0}):[]}function fl(e,t){const r=t.filter(s=>bt(s).length>0);return r.length?e.map(s=>{if(bt(s).length>0)return s;const a=r.find(l=>{if(s.role!==l.role)return!1;if(s.id&&l.id&&s.id===l.id||s.clientId&&l.clientId&&s.clientId===l.clientId)return!0;const c=ve(s),u=ve(l);return!c||c!==u?!1:Math.abs(St(s)-St(l))<=3e4});if(!a)return s;const i=bt(a);return i.length?{...s,content:[...i,...Array.isArray(s.content)?s.content:[]]}:s}):e}function ml(e,t){if(!t.length)return e;const r=[...e];for(const s of t){const a=dl(r,s);if(a===-1){r.push(s);continue}const i=bt(s),l=r[a],c=bt(l),u=i.length>0&&c.length===0,f=!!(s.__optimisticId&&!l.__optimisticId),d=!!(s.clientId&&!l.clientId);!u&&!f&&!d||(r[a]={...l,...f?{__optimisticId:s.__optimisticId}:{},...d?{clientId:s.clientId}:{},...u?{content:[...i,...Array.isArray(l.content)?l.content:[]]}:{}})}return r}function pl(e){const[t,r]=o.useState(!1);return o.useLayoutEffect(()=>{const s=window.matchMedia("(max-width: 768px)"),a=()=>r(s.matches);return a(),s.addEventListener("change",a),()=>s.removeEventListener("change",a)},[]),o.useLayoutEffect(()=>{t&&Be(e,function(a){return{...a,isSidebarCollapsed:!0}})},[t,e]),{isMobile:t}}function hl({activeFriendlyId:e,isNewChat:t,forcedSessionKey:r}){const[s,a]=o.useState(()=>typeof document>"u"?!0:document.visibilityState==="visible");o.useEffect(()=>{if(typeof document>"u")return;const m=()=>{a(document.visibilityState==="visible")};return m(),document.addEventListener("visibilitychange",m),()=>{document.removeEventListener("visibilitychange",m)}},[]);const i=Mt({queryKey:ge.sessions,queryFn:xo,refetchInterval:s?3e4:!1}),l=o.useMemo(()=>{const m=i.data??[];return Mo(m)},[i.data]),c=o.useMemo(()=>l.find(m=>m.friendlyId===e),[l,e]),u=o.useMemo(()=>t||r||pr(e)?!0:l.some(m=>m.friendlyId===e),[e,r,t,l]),f=c?.key??"",d=o.useMemo(()=>c?c.label||c.title||c.derivedTitle||c.friendlyId:e,[e,c]),h=i.error instanceof Error?i.error.message:null,p=o.useMemo(()=>({totalTokens:c?.totalTokens,contextTokens:c?.contextTokens}),[c?.totalTokens,c?.contextTokens]);return{sessionsQuery:i,sessions:l,activeSession:c,activeExists:u,activeSessionKey:f,activeTitle:d,activeTokens:p,sessionsError:h}}function gl(){const[e,t]=o.useState(!1),[r,s]=o.useState(null),[a,i]=o.useState(null),l=o.useRef(null);return{generateTitle:o.useCallback(async u=>{l.current&&l.current.abort();const f=new AbortController;l.current=f,t(!0);try{const d=await fetch("/api/llm-features",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({action:"title",message:u}),signal:f.signal});if(!d.ok)throw new Error(`API error: ${d.status}`);const h=await d.json();if(f.signal.aborted)throw new Error("Aborted");const p=h.title||u.slice(0,50),m=p.length>64?p.slice(0,61)+"...":p,b=h.source||"heuristic";return s(m),i(b),{title:m,source:b,error:h.error}}catch(d){if(d instanceof Error&&d.name==="AbortError")throw d;const h=xl(u);return s(h),i("heuristic"),{title:h,source:"heuristic",error:d instanceof Error?d.message:"Unknown error"}}finally{t(!1),l.current===f&&(l.current=null)}},[]),isGenerating:e,lastTitle:r,lastSource:a}}function xl(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 yl(){return!0}function wl(e,t,r){const s=dt(e),a=ye(s?.stream),i=ye(s?.runId),l=ye(s?.sessionKey)||t,c=dt(s?.data);if(i)if(r.anyRunSeen.current=!0,a==="lifecycle"){const m=ye(c?.phase);m==="end"||m==="error"||m==="abort"?r.activeRuns.delete(i):m&&r.activeRuns.add(i)}else r.activeRuns.add(i);if(a==="assistant"){const m=ye(c?.delta)||ye(c?.text);if(!m)return;r.setState(b=>{const g=[...b.contentBlocks],k=g[g.length-1];return k?.kind==="text"?g[g.length-1]={...k,text:k.text+m}:g.push({kind:"text",text:m}),{...b,sessionKey:l,text:b.text+m,contentBlocks:g}}),r.onAssistantDelta?.({text:m,sessionKey:l});return}if(!a.includes("tool"))return;const u=ye(c?.toolCallId)||ye(c?.id)||ye(c?.callId)||`${i||"tool"}:${ye(c?.toolName)||ye(c?.name)||"unknown"}`,f=ye(c?.toolName)||ye(c?.name)||"Tool",d=bl(a,c),h=dt(c?.arguments)||dt(c?.input)||dt(c?.params)||null,p=ye(c?.result)||ye(c?.output)||(a.includes("result")?ye(c?.text):"");r.setState(m=>{const b=[...m.tools],g=b.findIndex(H=>H.id===u),k={id:u,name:f,status:d};g>=0?b[g]=k:b.push(k);const w=[...m.contentBlocks],x=w.findIndex(H=>H.kind==="tool"&&H.id===u),$=x>=0?w[x]:null,I={kind:"tool",name:f,id:u,status:d,arguments:h??$?.arguments,output:p||$?.output||void 0};return x>=0?w[x]=I:w.push(I),{...m,sessionKey:l,tools:b,contentBlocks:w}})}function bl(e,t){const r=ye(t?.phase)||ye(t?.status)||ye(t?.state);return r||(e.includes("result")||e.includes("output")?"done":(e.includes("call"),"running"))}function dt(e){return e&&typeof e=="object"?e:null}function ye(e){return typeof e=="string"?e.trim():""}const Qn={active:!1,text:"",tools:[],contentBlocks:[],sessionKey:null};function Sl(e){const[t,r]=o.useState(Qn),s=o.useRef(null),a=o.useRef(!1),i=o.useRef(!1),l=o.useRef(new Set),c=o.useRef(-1),u=o.useRef(""),f=o.useRef(!1),d=o.useRef(""),h=o.useRef(e.onDone),p=o.useRef(e.onError),m=o.useRef(e.onAssistantDelta);h.current=e.onDone,p.current=e.onError,m.current=e.onAssistantDelta;const b=o.useCallback(k=>{if(a.current=!0,i.current=!1,l.current.clear(),f.current=!1,c.current=-1,u.current="",s.current&&(s.current.close(),s.current=null),k?.preserveState){r(w=>({...w,active:!1}));return}r(Qn)},[]),g=o.useCallback(function(w){if(d.current=w,s.current&&!a.current){r($=>({...$,sessionKey:w,active:!0}));return}if(a.current=!1,i.current=!1,l.current.clear(),f.current=!1,c.current=-1,u.current="",r({active:!0,text:"",tools:[],contentBlocks:[],sessionKey:w}),s.current)return;const x=new EventSource(`/api/stream?sessionKey=${encodeURIComponent(w)}`);s.current=x,x.addEventListener("message",$=>{try{const I=JSON.parse($.data);if(typeof I.seq=="number"){if(I.seq<=c.current)return;c.current=I.seq}const H=d.current;if(I.event==="agent"){const O=JSON.stringify(I.payload);if(O===u.current)return;u.current=O,wl(I.payload,H,{setState:r,onAssistantDelta:m.current,activeRuns:l.current,anyRunSeen:f});return}if(I.event==="chat"){const O=dt(I.payload),ee=ye(O?.sessionKey)||H,_=ye(O?.state);_==="final"&&(i.current=!0),!a.current&&i.current&&(_==="final"||f.current&&l.current.size===0)&&(a.current=!0,r(P=>({...P,active:!1})),h.current(ee));return}if(I.event==="error"){const O=typeof I.payload=="string"?I.payload:"Stream connection lost";p.current?.(O)}}catch{}}),x.onerror=()=>{a.current||x.readyState===EventSource.CLOSED&&(s.current=null,r($=>({...$,active:!1})),p.current?.("Stream connection lost"))}},[]);return{streaming:t,startStream:g,stopStream:b}}function vl(e){const t=o.useCallback(r=>{const s=r.target,a=s.tagName==="INPUT"||s.tagName==="TEXTAREA"||s.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]);o.useEffect(()=>(window.addEventListener("keydown",t),()=>{window.removeEventListener("keydown",t)}),[t])}function Zn(e){const{threshold:t=50,edgeWidth:r,onMove:s,onSwipe:a,onCancel:i,direction:l,enabled:c=!0}=e,u=o.useRef({startX:0,startY:0,tracking:!1,directionLocked:!1}),f=o.useCallback(p=>{if(!c)return;const m=p.touches[0];m&&(r!==void 0&&m.clientX>r||(u.current={startX:m.clientX,startY:m.clientY,tracking:!0,directionLocked:!1}))},[c,r]),d=o.useCallback(p=>{const m=u.current;if(!m.tracking)return;const b=p.touches[0];if(!b)return;const g=b.clientX-m.startX,k=b.clientY-m.startY,w=Math.abs(g),x=Math.abs(k);if(!m.directionLocked){if(w<5&&x<5)return;if(x>w){m.tracking=!1,i?.();return}m.directionLocked=!0}l==="left"&&g>0||l==="right"&&g<0||(p.preventDefault(),s?.(g))},[l,s,i]),h=o.useCallback(p=>{const m=u.current;if(!m.tracking)return;m.tracking=!1;const b=p.changedTouches[0];if(!b){i?.();return}const g=b.clientX-m.startX,k=Math.abs(g);if(!m.directionLocked||k<t){i?.();return}const w=g>0?"right":"left";if(l&&w!==l){i?.();return}a(w)},[l,i,a,t]);return{onTouchStart:f,onTouchMove:d,onTouchEnd:h}}const Or="opencami-browser-notifications-enabled",jl=5e3;function Jt(){return typeof window<"u"&&"Notification"in window}function er(){if(typeof window>"u")return!1;try{return localStorage.getItem(Or)==="true"}catch{return!1}}function kl(){const e=zt(),t=o.useRef(0),[r,s]=o.useState(()=>er()),a=o.useCallback(async()=>{if(!Jt())return"denied";try{return await Notification.requestPermission()}catch{return"denied"}},[]),i=o.useCallback(async c=>{s(c);try{localStorage.setItem(Or,String(c))}catch{}c&&Jt()&&Notification.permission==="default"&&await a()},[a]),l=o.useCallback(c=>{if(!r||!Jt()||document.hidden!==!0||Notification.permission!=="granted")return;const u=Date.now();if(u-t.current<jl)return;t.current=u;const f=c.text.slice(0,100),d=new Notification("OpenCami",{body:f,icon:"/pwa-192x192.png"});d.onclick=()=>{window.focus(),e({to:"/chat/$sessionKey",params:{sessionKey:c.sessionFriendlyId}}),d.close()}},[r,e]);return o.useEffect(()=>{const c=()=>s(er());return window.addEventListener("storage",c),()=>window.removeEventListener("storage",c)},[]),{notificationsEnabled:r,setNotificationsEnabled:i,requestNotificationPermission:a,maybeNotifyAssistantMessage:l}}const El=o.lazy(()=>nt(()=>import("./keyboard-shortcuts-dialog-DP8ptQ7N.js"),__vite__mapDeps([29,1,4,3,5,6,7,8,9,2])).then(e=>({default:e.KeyboardShortcutsDialog}))),Cl=o.lazy(()=>nt(()=>import("./search-dialog-Bib2QY9u.js"),__vite__mapDeps([30,1,3,4,5,6,7,8,9,2,19,20,14,21,11,15,22,13,23,24,25,16,26])).then(e=>({default:e.SearchDialog}))),It="opencami-search-jump-target";function Nl(e){const t=Array.isArray(e.content)?e.content:[],r=[],s=[];for(const[a,i]of t.entries()){if(i.type!=="image"||!("source"in i)||typeof i.source?.data!="string"||i.source.data.length===0)continue;const l=typeof i.source?.media_type=="string"&&i.source.media_type.length>0?i.source.media_type:"image/jpeg",c=i.source.data;r.push({id:crypto.randomUUID(),file:new File([],`retry-attachment-${a+1}`,{type:l}),preview:null,type:"image",base64:c}),s.push({mimeType:l,content:c})}return{attachments:r,payload:s}}function Tl({activeFriendlyId:e,isNewChat:t=!1,onSessionResolved:r,forcedSessionKey:s}){const a=zt(),i=pt(),[l,c]=o.useState(!1),[u,f]=o.useState(!1),[d,h]=o.useState(null),[p,m]=o.useState(!1),{headerRef:b,composerRef:g,mainRef:k,pinGroupMinHeight:w,headerHeight:x}=cl(),[$,I]=o.useState(()=>Wt()||Xt()),[H,O]=o.useState(()=>Wt()||Xt()),[ee,_]=o.useState(!1),[P,Z]=o.useState(!1),[X,C]=o.useState("global"),[A,v]=o.useState(null),[D,j]=o.useState(!1),U=an(y=>y.level),{maybeNotifyAssistantMessage:G}=kl(),S=o.useRef(null),M=o.useRef(null),z=o.useRef(null),B=o.useRef(""),E=o.useRef(()=>{}),q=o.useRef(!1),F=o.useRef(""),{isMobile:W}=pl(i),{sessionsQuery:J,sessions:re,activeExists:ie,activeSessionKey:V,activeTitle:ae,activeTokens:ne,sessionsError:ce}=hl({activeFriendlyId:e,isNewChat:t,forcedSessionKey:s}),{historyQuery:he,historyMessages:oe,displayMessages:de,historyError:T,resolvedSessionKey:pe,activeCanonicalKey:Ce,sessionKeyForHistory:Ie}=ul({activeFriendlyId:e,activeSessionKey:V,forcedSessionKey:s,isNewChat:t,isRedirecting:p,activeExists:ie,sessionsReady:J.isSuccess,queryClient:i}),Ke=Mt({queryKey:ts,queryFn:function(){return En(i)},initialData:function(){return En(i)},staleTime:1/0}),N=Mt({queryKey:["gateway","status"],queryFn:wo,retry:2,retryDelay:y=>Math.min(2e3*2**y,8e3),refetchOnWindowFocus:!1,refetchOnReconnect:!0,refetchOnMount:"always"}),Y=o.useRef(Date.now()),K=N.error instanceof Error?N.error.message:N.data&&!N.data.ok?N.data.error||"Gateway unavailable":null,me=K??ce??T,se=o.useCallback(()=>{N.refetch()},[N]),fe=Ke.data?.isSidebarCollapsed??!1;o.useEffect(()=>{J.isSuccess&&N.isError&&N.refetch()},[J.isSuccess,N.isError]);const Ne=Zn({enabled:W&&fe,edgeWidth:40,threshold:50,direction:"right",onSwipe:()=>{Be(i,y=>({...y,isSidebarCollapsed:!1}))}}),rt=Zn({enabled:W&&!fe,threshold:50,direction:"left",onSwipe:()=>{Be(i,y=>({...y,isSidebarCollapsed:!0}))}}),Ae=o.useCallback(()=>{h(null),m(!0),a({to:"/new",replace:!0})},[a]),ze=o.useCallback(()=>{M.current&&(window.clearInterval(M.current),M.current=null),z.current&&(window.clearTimeout(z.current),z.current=null)},[]),Je=o.useCallback(()=>{ze(),yt(!1),I(!1),j(!1)},[ze]),vt=yl(),{generateTitle:ht}=gl(),jt=o.useRef(new Set),kt=2e3,gt=2e3,xt=o.useCallback(()=>{!e||t||(M.current&&window.clearInterval(M.current),j(!0),M.current=window.setInterval(()=>{E.current()},kt))},[e,t]),Et=o.useRef(()=>{}),He=o.useRef(()=>{}),{streaming:Q,startStream:je,stopStream:Qe}=Sl({onDone:y=>Et.current(y),onError:y=>He.current(y),onAssistantDelta:({text:y})=>{F.current+=y,G({text:F.current,sessionFriendlyId:e})}});Et.current=o.useCallback(async y=>{await he.refetch(),Je(),i.invalidateQueries({queryKey:ge.sessions})},[he,i,Je]),He.current=o.useCallback(y=>{console.warn("[stream] SSE error, falling back to polling")},[]);const Fe=o.useMemo(()=>{if(Q.contentBlocks.length===0)return null;const y=[];for(const R of Q.contentBlocks)R.kind==="text"&&R.text?y.push({type:"text",text:R.text}):R.kind==="tool"&&y.push({type:"toolCall",name:R.name,id:R.id,arguments:R.arguments});return y.length===0?null:{role:"assistant",content:y,id:"__streaming__",__streaming:!0,timestamp:Date.now()}},[Q.contentBlocks]),Kt=o.useMemo(()=>{const y=[];for(const R of Q.contentBlocks)R.kind==="tool"&&R.status==="done"&&y.push({role:"toolResult",toolCallId:R.id,toolName:R.name,content:R.output?[{type:"text",text:R.output}]:[]});return y},[Q.contentBlocks]),Lr=o.useMemo(()=>{if(!Fe)return de;const y=[...de].map((le,Se)=>({message:le,index:Se})).filter(({message:le})=>le.role==="assistant").map(({index:le})=>le).pop(),R=[...de].map((le,Se)=>({message:le,index:Se})).filter(({message:le})=>le.role==="user").map(({index:le})=>le).pop(),ue=typeof y=="number"&&(typeof R!="number"||y>R);if(!Q.active&&ue)return de;let xe;if(ue&&typeof y=="number"){const le=de[y];if(ve(le).length>=Q.text.length&&Q.tools.length===0)return de;xe=[...de],xe[y]=Fe}else xe=[...de,Fe];return Kt.length>0&&(xe=[...xe,...Kt]),xe},[de,Fe,Kt,Q.active,Q.text,Q.tools]),_r=o.useMemo(()=>({}),[]);E.current=function(){he.refetch()},o.useEffect(()=>{if(p){d&&h(null);return}if(st){d&&h(null);return}if(J.isSuccess&&!ie){d&&h(null);return}const y=ce??T??K;if(!y){d?.startsWith("Failed to load")&&h(null);return}Mn(y)&&a({to:"/connect",replace:!0});const R=ce?`Failed to load sessions. ${ce}`:T?`Failed to load history. ${T}`:K?`Gateway unavailable. ${K}`:null;R&&h(R)},[d,K,T,p,a,ce]);const st=!t&&!s&&!pr(e)&&J.isSuccess&&re.length>0&&!re.some(y=>y.friendlyId===e)&&!he.isFetching&&!he.isSuccess;o.useEffect(()=>{if(p){if(t){m(!1);return}!st&&J.isSuccess&&m(!1)}},[t,p,J.isSuccess,st]),o.useEffect(()=>{t||J.isSuccess&&re.length!==0&&st&&(Lt(),tn(i,e,Ie),a({to:"/new",replace:!0}))},[e,he.isFetching,he.isSuccess,t,a,i,Ie,re,J.isSuccess,st]);const gn=st||p,Ct=o.useRef("fast");o.useEffect(()=>{const y=[...oe].reverse().find(ue=>ue.role==="assistant");if(!y)return;const R=`${oe.length}:${ve(y).slice(-64)}`;R!==B.current&&(B.current=R,Ct.current!=="fast"&&M.current&&(window.clearInterval(M.current),M.current=window.setInterval(()=>{E.current()},kt),Ct.current="fast"),z.current&&window.clearTimeout(z.current),z.current=window.setTimeout(()=>{M.current&&(window.clearInterval(M.current),M.current=window.setInterval(()=>{E.current()},gt),Ct.current="slow"),z.current=window.setTimeout(()=>{Je(),Ct.current="fast"},3e3)},1500))},[oe,Je]),o.useEffect(()=>{if(t||p)return;const y=s||pe||V;if(!y||jt.current.has(y))return;const R=oe.filter(le=>le.role==="user"),ue=oe.filter(le=>le.role==="assistant");if(R.length===0||ue.length===0||R.length!==1)return;const xe=ve(R[0]);!xe||xe.length<5||(jt.current.add(y),(async()=>{try{const le=await ht(xe);le.title&&await ko(i,y,e,le.title)}catch(le){console.error("[smart-title] Error generating title:",le)}})())},[vt,t,p,s,pe,V,e,oe,ht,i]),o.useEffect(()=>{if(t||e){if(ze(),Qe(),B.current="",j(!1),q.current){q.current=!1;return}if(Wt()||Xt()){I(!0),O(!0);return}I(!1),O(!1)}},[e,t,ze,Qe]),o.useEffect(()=>{if(!(typeof window>"u"))try{const y=sessionStorage.getItem(It);if(!y){v(null);return}const R=JSON.parse(y);if(typeof R.at=="number"&&Date.now()-R.at>300*1e3){sessionStorage.removeItem(It),v(null);return}if(R.friendlyId===e&&typeof R.messageId=="string"&&R.messageId.length>0){v(R.messageId),sessionStorage.removeItem(It);return}v(null)}catch{v(null)}},[e]),o.useLayoutEffect(()=>{if(t)return;const y=Ro(s||pe||V,e);if(!y)return;q.current=!0;const R=ge.history(y.friendlyId,y.sessionKey),ue=i.getQueryData(R);(Array.isArray(ue?.messages)?ue.messages:[]).some(Se=>!!(y.optimisticMessage.clientId&&(Se.clientId===y.optimisticMessage.clientId||Se.__optimisticId===y.optimisticMessage.clientId)||y.optimisticMessage.__optimisticId&&Se.__optimisticId===y.optimisticMessage.__optimisticId))||Ht(i,y.friendlyId,y.sessionKey,y.optimisticMessage),I(!0),O(!0),Nt(y.sessionKey,y.friendlyId,y.message,!0,y.attachments)},[e,V,s,t,i,pe]);function Nt(y,R,ue,xe=!1,le,Se,ot){let $e="";if(!xe){const{clientId:ke,optimisticMessage:at}=On(ue,le);$e=ke,Ht(i,R,y,at),vo(i,y,R,at)}yt(!0),c(!0),h(null),I(!0),O(!0);const it=ot??le?.flatMap(ke=>ke.base64?[{mimeType:ke.file.type,content:ke.base64}]:[]);F.current="",xt();const jn=y||R;jn&&je(jn),fetch("/api/send",{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({sessionKey:y,friendlyId:R,message:ue,thinking:U,idempotencyKey:crypto.randomUUID(),attachments:it,model:Se||void 0})}).then(async ke=>{if(!ke.ok)throw new Error(await Ue(ke));const kn=(await ke.json()).sessionKey||y||R;je(kn)}).catch(ke=>{const at=ke instanceof Error?ke.message:String(ke);if(Mn(at)){a({to:"/connect",replace:!0});return}$e&&bo(i,R,y,$e,function(Jr){return{...Jr,status:"error"}}),h(`Failed to send message. ${at}`),yt(!1),I(!1),O(!1)}).finally(()=>{c(!1)})}const xn=o.useCallback(async()=>{f(!0);try{const y=await fetch("/api/sessions",{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({})});if(!y.ok)throw new Error(await Ue(y));const R=await y.json(),ue=typeof R.sessionKey=="string"?R.sessionKey:"",xe=typeof R.friendlyId=="string"&&R.friendlyId.trim().length>0?R.friendlyId.trim():Zt(ue);if(!ue||!xe)throw new Error("Invalid session response");return i.invalidateQueries({queryKey:ge.sessions}),{sessionKey:ue,friendlyId:xe}}finally{f(!1)}},[i]),Pr=o.useCallback((y,R)=>{const ue=R.attachments;if(y.length===0&&(!ue||ue.length===0))return;if(R.reset(),t){const{clientId:le,optimisticId:Se,optimisticMessage:ot}=On(y,ue);Ht(i,"new","new",ot),yt(!0),c(!0),I(!0),O(!0),xn().then(({sessionKey:$e,friendlyId:it})=>{if(To(it),Co({sessionKey:$e,friendlyId:it,message:y,optimisticMessage:ot,attachments:ue}),r){r({sessionKey:$e,friendlyId:it});return}a({to:"/chat/$sessionKey",params:{sessionKey:it},replace:!0})}).catch($e=>{Ft(i,"new","new",le,Se),R.setValue(y),h(`Failed to create session. ${$e instanceof Error?$e.message:String($e)}`),yt(!1),I(!1),O(!1),c(!1)});return}Nt(s||pe||V,e,y,!1,ue,R.model)},[e,V,xn,s,t,a,r,i,pe]),yn=o.useCallback(()=>{I(!1),O(!1),tn(i,"new","new"),a({to:"/new"}),W&&Be(i,function(R){return{...R,isSidebarCollapsed:!0}})},[W,a,i]),zr=o.useCallback(()=>{Be(i,function(R){return{...R,isSidebarCollapsed:!R.isSidebarCollapsed}})},[i]),$r=o.useCallback(()=>{W&&Be(i,function(R){return{...R,isSidebarCollapsed:!0}})},[W,i]),Ur=o.useCallback(()=>{Be(i,function(R){return{...R,isSidebarCollapsed:!1}})},[i]),Kr=o.useCallback(y=>{const R=ve(y),{attachments:ue,payload:xe}=Nl(y);if(!R&&ue.length===0)return;const le=s||pe||V;if(!le)return;const Se=y.clientId,ot=y.__optimisticId;Se&&Ft(i,e,le,Se,ot),Nt(le,e,R,!1,ue,void 0,xe)},[e,V,s,i,pe]),Hr=o.useCallback(y=>{const R=s||pe||V;if(!R)return;const ue=y.clientId,xe=y.__optimisticId;ue&&Ft(i,e,R,ue,xe),h(null)},[e,V,s,i,pe]),Fr=o.useCallback(y=>{if(t||!y.trim())return;const R=s||pe||V;R&&Nt(R,e,y.trim())},[e,V,s,t,pe]),Wr=o.useCallback(()=>{S.current?.focus()},[]),Xr=o.useCallback(()=>{if(ee){_(!1);return}document.activeElement instanceof HTMLElement&&document.activeElement.blur()},[ee]),Br=o.useCallback(()=>{const y=[...de].reverse().find(ue=>ue.role==="assistant");if(!y)return;const R=ve(y);R&&navigator.clipboard.writeText(R).catch(()=>{})},[de]),Yr=o.useCallback(()=>{_(!0)},[]),Gr=o.useCallback(()=>{C(t?"global":"current"),Z(!0)},[t]),wn=o.useCallback(()=>{C("global"),Z(!0)},[]);vl({onNewChat:yn,onFocusInput:Wr,onEscape:Xr,onCopyLastResponse:Br,onShowHelp:Yr,onSearch:Gr,onSearchGlobal:wn});const bn=he.isLoading&&!he.data||p,Sn=!!K&&!J.isSuccess&&N.errorUpdatedAt>Y.current,qr=!bn&&de.length===0,Vr=o.useMemo(()=>!Sn||!me?null:n.jsx(ll,{state:"error",error:me,onRetry:se}),[me,se,Sn]),vn=n.jsx(Xi,{sessions:re,activeFriendlyId:e,activeSessionKey:Ie,creatingSession:u,onCreateSession:yn,isCollapsed:W?!1:fe,onToggleCollapse:zr,onSelectSession:$r,onActiveSessionDelete:Ae,onOpenSearch:wn});return n.jsxs("div",{className:"h-screen bg-surface text-primary-900",children:[n.jsxs("div",{className:L("h-full overflow-hidden",W?"relative":"grid grid-cols-[auto_minmax(0,1fr)]"),children:[gn?null:W?n.jsxs(n.Fragment,{children:[!fe&&n.jsx("div",{className:"fixed inset-0 z-40 bg-black/40 transition-opacity duration-200",onClick:()=>Be(i,y=>({...y,isSidebarCollapsed:!0})),...rt}),n.jsx("div",{className:L("fixed inset-y-0 left-0 z-50 w-[var(--opencami-sidebar-width)] transition-transform duration-150 safe-area-top",fe?"-translate-x-full":"translate-x-0"),...rt,children:vn})]}):vn,n.jsxs("main",{className:"flex flex-col h-full min-h-0 min-w-0 overflow-x-hidden",ref:k,...Ne,children:[n.jsx(qi,{activeTitle:ae,wrapperRef:b,showSidebarButton:W,onOpenSidebar:Ur,totalTokens:ne.totalTokens,contextTokens:ne.contextTokens}),gn?null:n.jsxs(n.Fragment,{children:[n.jsx(Ra,{messages:Lr,loading:bn,empty:qr,notice:Vr,noticePosition:"end",waitingForResponse:$,isStreaming:D,sessionKey:Ce,pinToTop:H,pinGroupMinHeight:w,headerHeight:x,contentStyle:_r,onFollowUpClick:Fr,jumpToMessageId:A,onRetryMessage:Kr,onDismissMessage:Hr}),n.jsx(il,{onSubmit:Pr,isLoading:l,disabled:l,wrapperRef:g,inputRef:S})]})]})]}),ee&&n.jsx(o.Suspense,{fallback:null,children:n.jsx(El,{open:ee,onOpenChange:_})}),P&&n.jsx(o.Suspense,{fallback:null,children:n.jsx(Cl,{open:P,onOpenChange:Z,sessions:re,currentFriendlyId:e,currentSessionKey:V,mode:X,onJumpToMessage:y=>{if(Z(!1),!!y.friendlyId){if(y.messageId&&y.friendlyId===e){v(y.messageId);return}if(y.messageId&&typeof window<"u")try{sessionStorage.setItem(It,JSON.stringify({friendlyId:y.friendlyId,messageId:y.messageId,at:Date.now()}))}catch{}a({to:"/chat/$sessionKey",params:{sessionKey:y.friendlyId}})}}})})]})}function Rl(){const e=pt(),t=zt(),[r,s]=o.useState(null),a=es.useParams(),i=typeof a.sessionKey=="string"?a.sessionKey:"main",l=i==="new",c=r?.friendlyId===i?r.sessionKey:void 0,u=o.useCallback(function(d){So(e,"new","new",d.friendlyId,d.sessionKey),s({friendlyId:d.friendlyId,sessionKey:d.sessionKey}),t({to:"/chat/$sessionKey",params:{sessionKey:d.friendlyId},replace:!0})},[t,e]);return n.jsx(Tl,{activeFriendlyId:i,isNewChat:l,forcedSessionKey:c,onSessionResolved:l?u:void 0})}const ql=Object.freeze(Object.defineProperty({__proto__:null,component:Rl},Symbol.toStringTag,{value:"Module"}));export{ql as $,nn as C,rn as a,sn as b,ge as c};
@@ -0,0 +1,2 @@
1
+ const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/agents-screen-BhOVp_S6.js","assets/main-xPlWrMhO.js","assets/useQuery-k6EMRoMD.js","assets/button-D0n2Qsd_.js","assets/switch-BUQ0qH6r.js","assets/useControlled-CyT-lqbs.js","assets/useBaseUiId-ClbEYEil.js","assets/visuallyHidden-COI6QeQH.js","assets/tooltip-CcIdgcV0.js","assets/useOnFirstRender-CR_o2MK_.js","assets/event-CHpdjYFR.js","assets/DirectionContext-X-0CRn1O.js","assets/opencami-logo-B_hLbomw.js","assets/proxy-BnlGpgC1.js"])))=>i.map(i=>d[i]);
2
+ import{j as e,r as t,_ as r}from"./main-xPlWrMhO.js";const n=t.lazy(()=>r(()=>import("./agents-screen-BhOVp_S6.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-B2CrcRuC.js";import{u as q}from"./useQuery-D-sF8Tld.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-BciDmec0.js";import{S as _}from"./switch-Bn5uei2k.js";import{s as X,T as Y,a as Z,b as $,c as ee,d as se,g as P}from"./tooltip-DOKkNFvu.js";import{O as re,a as ae}from"./opencami-logo-SVuYD55V.js";import{m as S,A as W}from"./proxy-BijR8W1L.js";import"./useControlled-CQHE0ITz.js";import"./useBaseUiId-DFpBD0sg.js";import"./visuallyHidden-COI6QeQH.js";import"./useOnFirstRender-DlXHIIGk.js";import"./event-BCwqPPkP.js";import"./DirectionContext-CR5CCisG.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-xPlWrMhO.js";import{u as q}from"./useQuery-k6EMRoMD.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-D0n2Qsd_.js";import{S as _}from"./switch-BUQ0qH6r.js";import{s as X,T as Y,a as Z,b as $,c as ee,d as se,g as P}from"./tooltip-CcIdgcV0.js";import{O as re,a as ae}from"./opencami-logo-B_hLbomw.js";import{m as S,A as W}from"./proxy-BnlGpgC1.js";import"./useControlled-CyT-lqbs.js";import"./useBaseUiId-ClbEYEil.js";import"./visuallyHidden-COI6QeQH.js";import"./useOnFirstRender-CR_o2MK_.js";import"./event-CHpdjYFR.js";import"./DirectionContext-X-0CRn1O.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-DLFd0ydi.js","assets/main-xPlWrMhO.js","assets/button-D0n2Qsd_.js","assets/switch-BUQ0qH6r.js","assets/useControlled-CyT-lqbs.js","assets/useBaseUiId-ClbEYEil.js","assets/visuallyHidden-COI6QeQH.js","assets/useQuery-k6EMRoMD.js","assets/useMutation-eQUrsn-X.js","assets/proxy-BnlGpgC1.js"])))=>i.map(i=>d[i]);
2
+ import{j as e,r as t,_ as r}from"./main-xPlWrMhO.js";const n=t.lazy(()=>r(()=>import("./bots-screen-DLFd0ydi.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};