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