@hybridaione/hybridclaw 0.25.5 → 0.25.6
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +16 -0
- package/README.md +1 -1
- package/console/dist/assets/chat-wyTTu2gH.js +4 -0
- package/console/dist/assets/{index-DMXFIc9H.js → index-BnZk53Xc.js} +2 -2
- package/console/dist/assets/{terminal-D71XszaC.js → terminal-DeO2hJXe.js} +1 -1
- package/console/dist/index.html +1 -1
- package/console/package.json +1 -1
- package/container/npm-shrinkwrap.json +2 -2
- package/container/package-lock.json +2 -2
- package/container/package.json +1 -1
- package/dist/cli.d.ts.map +1 -1
- package/dist/cli.js +2 -0
- package/dist/cli.js.map +1 -1
- package/dist/gateway/gateway-http-server.d.ts.map +1 -1
- package/dist/gateway/gateway-http-server.js +22 -5
- package/dist/gateway/gateway-http-server.js.map +1 -1
- package/dist/logger.d.ts +1 -0
- package/dist/logger.d.ts.map +1 -1
- package/dist/logger.js +37 -8
- package/dist/logger.js.map +1 -1
- package/npm-shrinkwrap.json +5 -5
- package/package.json +1 -1
- package/console/dist/assets/chat-Bo80AEih.js +0 -4
package/CHANGELOG.md
CHANGED
|
@@ -2,6 +2,22 @@
|
|
|
2
2
|
|
|
3
3
|
## Unreleased
|
|
4
4
|
|
|
5
|
+
## [0.25.6](https://github.com/HybridAIOne/hybridclaw/tree/v0.25.6) - 2026-06-24
|
|
6
|
+
|
|
7
|
+
### Added
|
|
8
|
+
|
|
9
|
+
- **Launch-agent chat sessions**: `/chat?agent=<id>` links now mint a web chat
|
|
10
|
+
session, preselect the requested local agent, and pass that agent through the
|
|
11
|
+
history bootstrap path so the correct agent autostart runs for the new
|
|
12
|
+
session.
|
|
13
|
+
|
|
14
|
+
### Fixed
|
|
15
|
+
|
|
16
|
+
- **Foreground gateway logging**: `gateway start --foreground` restores
|
|
17
|
+
mirroring to the gateway log file even when the logger initializes before the
|
|
18
|
+
foreground command configures the log path, while avoiding duplicate file
|
|
19
|
+
streams when stdio is already redirected to the gateway log.
|
|
20
|
+
|
|
5
21
|
## [0.25.5](https://github.com/HybridAIOne/hybridclaw/tree/v0.25.5) - 2026-06-22
|
|
6
22
|
|
|
7
23
|
### Fixed
|
package/README.md
CHANGED
|
@@ -228,7 +228,7 @@ Core pieces:
|
|
|
228
228
|
| Build desktop releases | [Desktop Release Builds](https://hybridaione.github.io/hybridclaw/docs/developer-guide/desktop-release) |
|
|
229
229
|
| Contribute | [CONTRIBUTING.md](./CONTRIBUTING.md), [docs/content/README.md](./docs/content/README.md) |
|
|
230
230
|
|
|
231
|
-
Latest release: [v0.25.
|
|
231
|
+
Latest release: [v0.25.6](https://github.com/HybridAIOne/hybridclaw/releases/tag/v0.25.6).
|
|
232
232
|
Release notes: [CHANGELOG.md](./CHANGELOG.md)
|
|
233
233
|
|
|
234
234
|
## Development
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
import{n as e}from"./rolldown-runtime-Bh1tDfsg.js";import{C as t,a as n,n as r,o as i,r as a}from"./query-o_Dd9s85.js";import{d as o,l as s}from"./router-DoNPHesn.js";import{$ as c,A as l,B as u,C as d,D as f,E as p,F as m,G as h,H as g,I as _,J as v,K as y,L as b,M as x,N as S,O as C,P as w,Q as T,R as E,S as ee,T as D,U as O,V as te,W as k,X as ne,Y as re,Z as A,_ as j,a as M,at as N,b as P,bt as ie,c as F,d as ae,dt as oe,et as se,f as ce,ft as le,g as ue,gt as I,h as de,ht as fe,i as pe,it as L,k as me,l as he,lt as ge,m as R,mt as _e,n as z,nt as ve,o as B,ot as ye,p as be,pt as xe,q as V,r as H,rt as Se,s as Ce,st as we,t as Te,tt as U,u as W,ut as Ee,w as De,x as Oe,y as ke,yt as Ae,z as je}from"./index-BnZk53Xc.js";var G=e(t(),1);function Me(e,t,n=`web`,r=10,i,a){let o=new URLSearchParams({userId:t,channelId:n,limit:String(r)});return i&&o.set(`q`,i),a&&o.set(`scope`,a),I(`/api/chat/recent?${o.toString()}`,{token:e})}function Ne(e,t,n=80,r,i){let a=new URLSearchParams({sessionId:t,limit:String(n)});return r&&a.set(`userId`,r),i?.trim()&&a.set(`agentId`,i.trim()),I(`/api/history?${a.toString()}`,{token:e})}function Pe(e,t){return I(`/api/chat/context?${new URLSearchParams({sessionId:t}).toString()}`,{token:e})}function Fe(e,t){return I(t?`/api/chat/commands?q=${encodeURIComponent(t)}`:`/api/chat/commands`,{token:e})}function Ie(e,t){return I(`/api/chat/mobile-qr`,{token:e,method:`POST`,body:t})}function Le(e,t,n){return I(`/api/chat/branch`,{token:e,method:`POST`,body:{sessionId:t,beforeMessageId:n}})}function Re(e,t){return I(`/api/chat/rating`,{token:e,method:`POST`,body:t})}function ze(e,t,n,r){return I(`/api/command`,{token:e,method:`POST`,body:ge({sessionId:t,args:r,userId:n,username:`web`})})}function Be(e,t){return I(`/api/media/upload`,{token:e,method:`POST`,rawBody:t,extraHeaders:{"Content-Type":t.type||`application/octet-stream`,"X-Hybridclaw-Filename":encodeURIComponent(t.name||`upload`)}})}function Ve(e){return`/api/artifact?${new URLSearchParams({path:e}).toString()}`}function He(e){return e}async function Ue(e,t){let n=await fetch(t,{headers:fe(e),cache:`no-store`});if(!n.ok){let e=(n.headers.get(`content-type`)||``).toLowerCase().trim(),t=`${n.status} ${n.statusText}`;if(e.includes(`application/json`)){let e=await n.json().catch(()=>null);t=e?.error||e?.text||t}else{let e=(await n.text().catch(()=>``)).trim();e&&(t=e)}throw n.status===401&&oe(t),Error(t)}return n.blob()}async function We(e,t){return Ue(e,Ve(t))}function Ge(e,t){return Ue(e,He(t))}var Ke={maxRecentSessions:10,maxSearchResults:50};function qe(e,t){let[n,r]=(0,G.useState)(e);return(0,G.useEffect)(()=>{let n=window.setTimeout(()=>{r(e)},t);return()=>{window.clearTimeout(n)}},[e,t]),n}var K=`[A-Za-z0-9._-]+(?:@[A-Za-z0-9._-]+@[A-Za-z0-9._-]+)?`,q=String.raw`(?=$|[\s:.,!?;)\]}])`;RegExp(`^@(${K})${q}`,`u`);var Je=RegExp(`@(${K})${q}`,`gu`);function Ye(e){let t=[];for(let n of e.matchAll(Je)){let r=n[0],i=n[1]??``,a=n.index??0;if(!i)continue;let o=a===0?``:e[a-1];o&&!/[\s([{]/u.test(o)||t.push({mention:r,agentId:i,index:a})}return t}var Xe=new Map;function J(e){return String(e??``).trim().toLowerCase()}function Ze(e,t){let n=e.sessionId??t,r=new Map((e.branchFamilies??[]).map(e=>[`${e.anchorSessionId}:${e.anchorMessageId}`,e.variants])),i=new Map;for(let[e,t]of r.entries()){let r=t.find(e=>e.sessionId===n);r&&i.set(r.messageId,e)}let a=e.history??[],o=J(e.agentId),s=null;return{messages:a.map((e,t)=>{let r=a.slice(t+1).find(e=>e.role!==`system`),c=J(r?.agent_id??r?.assistantPresentation?.agentId),l=e.role===`user`&&r?.role===`assistant`&&c&&c!==o?r?.assistantPresentation??null:null;e.role===`user`&&(s=e.content);let u=e.role===`user`?e.content:e.role===`assistant`?s:null;return{id:De(),role:e.role,content:e.content,rawContent:e.content,sessionId:n,messageId:e.id??null,media:[],artifacts:e.artifacts??[],replayRequest:u===null?null:{content:u,media:[]},assistantPresentation:e.assistantPresentation??null,addressedAgentPresentation:l,responseRating:e.response_rating??null,branchKey:e.id!==void 0&&e.id!==null?i.get(e.id)??null:null}}),branchFamilies:r,resolvedSessionId:n,agentId:e.agentId?.trim()||null,bootstrapAutostart:e.bootstrapAutostart??null}}function Y(e,t){return[`chat-history`,e,t]}async function Qe(e,t,n,r){return Ze(await Ne(e,t,80,n,r),t)}var X=i();function $e(e){let t=we(),n=g(),r=e.searchQuery.trim().length>0;return(0,G.useEffect)(()=>{n.openMobile&&e.onRefreshRecent?.()},[e.onRefreshRecent,n.openMobile]),(0,X.jsxs)(_,{side:`left`,collapsible:`icon`,children:[(0,X.jsxs)(je,{children:[(0,X.jsxs)(`div`,{className:O.headerRow,children:[(0,X.jsx)(S,{}),(0,X.jsx)(te,{className:O.sidebarToggle})]}),(0,X.jsxs)(`button`,{type:`button`,className:H.newChatButton,onClick:e.onNewChat,children:[(0,X.jsx)(`span`,{"aria-hidden":`true`,children:`+`}),(0,X.jsx)(`span`,{children:`New Conversation`})]}),(0,X.jsx)(`div`,{className:H.sidebarSearchWrap,children:(0,X.jsx)(`input`,{type:`search`,className:H.sidebarSearch,value:e.searchQuery,onChange:t=>e.onSearchQueryChange(t.target.value),placeholder:`Search`,"aria-label":`Search conversations`})})]}),(0,X.jsx)(b,{children:(0,X.jsx)(et,{...e,isSearching:r})}),(0,X.jsx)(E,{children:(0,X.jsxs)(`div`,{className:O.footerBlock,children:[(0,X.jsx)(w,{version:t.gatewayStatus?.version}),(0,X.jsx)(k,{labelClassName:O.themeToggleLabel})]})})]})}function et(e){return(0,X.jsxs)(`div`,{className:H.chatSidebarContent,children:[(0,X.jsxs)(`div`,{className:H.sidebarListHeader,children:[(0,X.jsx)(`div`,{className:H.sidebarLabel,children:e.isSearching?`Search Results`:`Recent Chats`}),(0,X.jsx)(`div`,{className:H.sidebarScopeToggle,children:[`user`,`all`].map(t=>(0,X.jsx)(`button`,{type:`button`,className:U(H.sidebarScopeButton,e.recentScope===t&&H.sidebarScopeButtonActive),"aria-pressed":e.recentScope===t,onClick:()=>e.onRecentScopeChange(t),children:t===`user`?`User`:`All`},t))})]}),e.isLoading&&e.isSearching?(0,X.jsx)(`div`,{className:H.sidebarStatus,children:`Searching...`}):e.sessions.length===0?(0,X.jsx)(`div`,{className:H.sidebarStatus,children:e.isSearching?`No matching conversations.`:`No recent chats yet.`}):(0,X.jsx)(`ul`,{className:H.sessionList,"aria-live":`polite`,children:e.sessions.map(t=>(0,X.jsx)(`li`,{children:(0,X.jsxs)(`div`,{className:H.sessionItemRow,children:[(0,X.jsxs)(`button`,{type:`button`,className:U(H.sessionItem,t.sessionId===e.activeSessionId&&H.sessionItemActive,t.sessionId===e.activeSessionId&&e.isPending&&H.sessionItemPending),"aria-current":t.sessionId===e.activeSessionId?`page`:void 0,onMouseEnter:()=>e.onHoverSession?.(t.sessionId),onClick:()=>e.onOpenSession(t.sessionId),children:[(0,X.jsx)(`span`,{className:H.sessionTitle,children:t.title||`Untitled`}),t.searchSnippet?(0,X.jsx)(`span`,{className:H.sessionSnippet,children:t.searchSnippet}):null,(0,X.jsx)(`span`,{className:H.sessionTime,children:C(t.lastActive)})]}),(0,X.jsx)(`button`,{type:`button`,className:H.sessionDeleteButton,"aria-label":`Delete ${t.title||`Untitled`} session`,title:`Delete session`,disabled:e.deleteDisabled,onClick:()=>e.onRequestDeleteSession(t),children:(0,X.jsx)(ve,{className:H.sessionDeleteIcon})})]})},t.sessionId))})]})}var tt=new Map;function nt(e,t){return`${e}\u0000${t}`}function rt(e,t){let n=nt(e,t),r=tt.get(n);return r||(r={objectUrl:null,loading:!1,promise:null,listeners:new Set},tt.set(n,r)),r}function Z(e){for(let t of e.listeners)t()}function it(e,t){let n=t?.trim(),r=e.trim();if(!n)return null;let i=rt(r,n);return i.objectUrl?Promise.resolve(i.objectUrl):i.promise?i.promise:(i.loading=!0,i.promise=Ge(r,n).then(e=>{let t=URL.createObjectURL(e);return i.objectUrl=t,i.loading=!1,i.promise=null,Z(i),t}).catch(()=>(i.objectUrl=null,i.loading=!1,i.promise=null,Z(i),null)),Z(i),i.promise)}function at(e){let t=e.token.trim(),n=e.imageUrl?.trim()??``,[r,i]=(0,G.useState)(()=>{if(!n)return{objectUrl:null,loading:!1};let e=rt(t,n);return{objectUrl:e.objectUrl,loading:e.loading}});return(0,G.useEffect)(()=>{if(!n){i({objectUrl:null,loading:!1});return}let e=rt(t,n),r=()=>{i({objectUrl:e.objectUrl,loading:e.loading})};return e.listeners.add(r),r(),it(t,n),()=>{e.listeners.delete(r)}},[t,n]),r}function ot(){return(0,X.jsx)(`svg`,{"aria-hidden":`true`,focusable:`false`,viewBox:`0 0 24 24`,width:`14`,height:`14`,fill:`none`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`,children:(0,X.jsx)(`path`,{d:`m6 9 6 6 6-6`})})}function st(e){let t=e.agents.find(t=>t.id===e.selectedAgentId),n=t?.name?.trim()||t?.id||`Agent`,{localAgents:r,remoteGroups:i}=(0,G.useMemo)(()=>{let t=e.agents.filter(e=>e.source?.type!==`remote`),n=new Map;for(let t of e.agents){if(t.source?.type!==`remote`)continue;let e=t.source.instanceId;n.set(e,[...n.get(e)??[],t])}return{localAgents:t,remoteGroups:[...n.entries()]}},[e.agents]),a=i.length>0;return e.agents.length===0?null:(0,X.jsxs)(pe,{value:e.selectedAgentId,disabled:e.disabled,onValueChange:t=>{if(!t||t===e.selectedAgentId)return;let n=e.agents.find(e=>e.id===t);n&&e.onSwitch(n)},children:[(0,X.jsxs)(ce,{className:H.composerPill,"aria-label":`Switch agent`,disabled:e.disabled,children:[(0,X.jsx)(be,{children:n}),(0,X.jsx)(F,{className:H.composerPillChevron,children:(0,X.jsx)(ot,{})})]}),(0,X.jsxs)(M,{className:H.agentSelectPopup,children:[a?(0,X.jsxs)(B,{children:[(0,X.jsx)(Ce,{children:`Local`}),r.map(t=>(0,X.jsx)(ct,{agent:t,token:e.token},t.id))]}):r.map(t=>(0,X.jsx)(ct,{agent:t,token:e.token},t.id)),i.map(([t,n])=>(0,X.jsxs)(B,{children:[(0,X.jsxs)(Ce,{className:H.remoteAgentGroupLabel,children:[(0,X.jsx)(N,{"aria-hidden":`true`,className:H.remoteAgentGroupIcon,width:13,height:13}),(0,X.jsx)(`span`,{children:t})]}),n.map(t=>(0,X.jsx)(ct,{agent:t,token:e.token},t.id))]},t))]})]})}function ct(e){let t=e.agent.name?.trim()||e.agent.id,n=e.agent.source?.type===`remote`;return(0,X.jsxs)(he,{value:e.agent.id,textValue:t,className:H.agentSelectItem,children:[(0,X.jsx)(lt,{agent:e.agent,token:e.token}),n?(0,X.jsxs)(W,{children:[(0,X.jsx)(`span`,{className:H.agentSelectItemText,children:t}),(0,X.jsx)(ae,{children:e.agent.id})]}):(0,X.jsx)(`span`,{className:H.agentSelectItemText,children:t})]})}function lt(e){let t=e.agent.imageUrl?.trim(),n=at({token:e.token??``,imageUrl:t});return n.objectUrl?(0,X.jsx)(`img`,{className:H.agentSelectAvatar,src:n.objectUrl,alt:``}):t?(0,X.jsx)(`span`,{className:H.agentSelectAvatarLoading,"aria-hidden":`true`}):null}function ut(e,t){let n=e.lastIndexOf(`
|
|
2
|
+
`,t-1)+1,r=-1;for(let i=n;i<t;i++)e[i]===`/`&&(i===n||/\s/.test(e[i-1]))&&(r=i);return r===-1?null:{query:e.slice(r+1,t),tokenStart:r}}function dt(e,t){return`${e}-opt-${t}`}function ft({mode:e,kind:t=`slash`,suggestions:n,activeIdx:r,query:i,listboxId:a,token:o,onSelect:s,onActiveChange:c}){(0,G.useEffect)(()=>{e!==`list`||n.length===0||document.getElementById(dt(a,r))?.scrollIntoView({block:`nearest`})},[r,e,n.length,a]);let l=i.trim().toLowerCase(),u=t===`agent`?`@`:`/`,d=t===`agent`?`Agents`:`Slash commands`,f=t===`agent`?`No agents match ${u}${i}`:`No commands match ${u}${i}`;return(0,X.jsx)(V,{side:`top`,focusOnOpen:`none`,closeOnEscape:!1,closeOnOutsideClick:!0,sideOffset:4,className:H.slashSuggestions,children:(0,X.jsxs)(R,{className:H.slashSuggestionsScroll,children:[(0,X.jsx)(j,{id:a,role:`listbox`,"aria-label":d,className:H.slashSuggestionsList,children:e===`list`?n.map((e,n)=>(0,X.jsxs)(`div`,{id:dt(a,n),className:U(H.suggestionItem,t===`agent`&&H.suggestionItemAgent,n===r&&H.suggestionItemActive,(e.depth??1)>=2&&H.suggestionItemSub),role:`option`,tabIndex:-1,"aria-selected":n===r,onMouseDown:t=>{t.preventDefault(),s(e)},onMouseEnter:()=>c(n),title:e.description||void 0,children:[t===`agent`?(0,X.jsx)(pt,{item:e,token:o}):null,(0,X.jsxs)(`span`,{className:H.suggestionText,children:[(0,X.jsx)(`span`,{className:H.suggestionLabel,children:ht(e.label,l)}),e.description?(0,X.jsx)(`span`,{className:H.suggestionDesc,children:e.description}):null]})]},e.id)):(0,X.jsx)(`div`,{className:H.suggestionEmpty,role:`status`,children:f})}),(0,X.jsx)(de,{children:(0,X.jsx)(ue,{})})]})})}function pt(e){let t=e.item.imageUrl?.trim(),n=at({token:e.token??``,imageUrl:t});return n.objectUrl?(0,X.jsx)(`img`,{className:H.suggestionAvatar,src:n.objectUrl,alt:``}):t?(0,X.jsx)(`span`,{className:H.suggestionAvatarLoading,"aria-hidden":`true`}):null}var mt=/<[^>]+>|\[[^\]]+\]/g;function ht(e,t){let n=[],r=0,i=0,a=(e,r)=>{if(!e)return;let a=r?H.suggestionLabelMono:void 0,o=t?e.toLowerCase().indexOf(t):-1;n.push(o===-1?(0,X.jsx)(`span`,{className:a,children:e},i++):(0,X.jsxs)(`span`,{className:a,children:[e.slice(0,o),(0,X.jsx)(`mark`,{className:H.suggestionMatch,children:e.slice(o,o+t.length)}),e.slice(o+t.length)]},i++))};for(let t of e.matchAll(mt)){let n=t.index??0;a(e.slice(r,n),!1),a(t[0],!0),r=n+t[0].length}return a(e.slice(r),!1),n}var gt=RegExp(`(?:^|[\\s([{])@([A-Za-z0-9._-]*(?:@[A-Za-z0-9._-]*){0,2})$`,`u`),_t=RegExp(`@(${K})(?=$|[\\s:])`,`gu`),vt=RegExp(`^@${K}(?=$|[\\s:])\\s*`,`u`);function yt(e,t){let n=e.slice(0,t),r=gt.exec(n);if(!r)return null;let i=r[1]??``;return{tokenStart:n.length-i.length-1,query:i}}function bt(e){let t=(0,G.useRef)(null),n=(0,G.useRef)(null),r=(0,G.useRef)(null),[i,a]=(0,G.useState)([]),[o,s]=(0,G.useState)(0),[c,l]=(0,G.useState)([]),[u,d]=(0,G.useState)(`slash`),[f,p]=(0,G.useState)(0),[m,g]=(0,G.useState)(`closed`),[_,v]=(0,G.useState)(``),[b,x]=(0,G.useState)(``),[S,C]=(0,G.useState)(0),w=(0,G.useRef)(null),T=(0,G.useRef)(null),E=(0,G.useRef)(null),D=(0,G.useRef)(0),O=(0,G.useRef)(null),te=(0,G.useId)(),k=m!==`closed`,ne=m===`closed`?``:u===`agent`?m===`list`?`${me(c.length,`agent`)} available`:`No agents match @${_}`:m===`list`?`${me(c.length,`command`)} available`:`No commands match /${_}`;(0,G.useEffect)(()=>()=>{T.current&&clearTimeout(T.current),E.current&&clearTimeout(E.current),D.current+=1},[]),(0,G.useEffect)(()=>{let e=r.current;if(!e)return;let t=()=>{let t=e.getBoundingClientRect().height;!Number.isFinite(t)||t<=0||document.documentElement.style.setProperty(`--chat-composer-height`,`${Math.ceil(t)}px`)};t();let n=typeof ResizeObserver>`u`?null:new ResizeObserver(t);return n?.observe(e),window.addEventListener(`resize`,t),()=>{n?.disconnect(),window.removeEventListener(`resize`,t),document.documentElement.style.removeProperty(`--chat-composer-height`)}},[]);let re=(0,G.useRef)(e.isStreaming);(0,G.useEffect)(()=>{re.current&&!e.isStreaming&&t.current?.focus(),re.current=e.isStreaming},[e.isStreaming]);let A=(0,G.useCallback)(()=>{let e=t.current;e&&(e.style.height=`36px`,e.style.height=`${Math.max(36,Math.min(e.scrollHeight,180))}px`)},[]),j=(0,G.useCallback)(()=>{let e=t.current;e&&C(e.selectionStart??e.value.length)},[]),M=(0,G.useCallback)(e=>{let n=()=>{let n=t.current;if(!n)return;let r=Math.max(0,Math.min(e,n.value.length));n.focus(),n.setSelectionRange(r,r),C(r)};n(),E.current&&clearTimeout(E.current),E.current=setTimeout(()=>{E.current=null,n()},0)},[]);(0,G.useEffect)(()=>{let n=e.initialValue?.trim()||``;if(w.current===n||(w.current=n,!n))return;let r=t.current;r&&(r.value=n,r.setSelectionRange(n.length,n.length),x(n),C(n.length),g(`closed`),D.current+=1,A(),r.focus())},[e.initialValue,A]);let N=(0,G.useCallback)(()=>{T.current&&=(clearTimeout(T.current),null),D.current+=1},[]),P=(0,G.useCallback)(()=>{N(),g(`closed`)},[N]),ie=(0,G.useCallback)(async t=>{let n=D.current;try{let r=await Fe(e.token,t||void 0);if(n!==D.current)return;let i=r.commands??[];l(i),p(0),v(t),i.length>0?g(`list`):g(t===``?`closed`:`empty`)}catch{if(n!==D.current)return;l([]),g(`closed`)}},[e.token]),F=(0,G.useCallback)(t=>{let n=t.trim().toLowerCase();return(e.agents??[]).filter(e=>n?e.id.toLowerCase().includes(n)||(e.name??``).toLowerCase().includes(n):!0).map(e=>{let t=e.name?.trim();return{id:`agent:${e.id}`,label:`@${e.id}`,insertText:`@${e.id}`,description:t&&t!==e.id?t:``,imageUrl:e.imageUrl??null}})},[e.agents]);(0,G.useEffect)(()=>{for(let t of e.agents??[])it(e.token,t.imageUrl)},[e.agents,e.token]);let ae=()=>{A();let n=t.current;if(!n)return;x(n.value);let r=n.selectionStart??n.value.length;C(r);let i=ut(n.value,r);if(i){let e=i.query.trim();d(`slash`),N(),T.current=setTimeout(()=>{ie(e)},150);return}let a=yt(n.value,r);if(a&&(e.agents?.length??0)>0){N();let e=F(a.query);l(e),d(`agent`),p(0),v(a.query),g(e.length>0?`list`:a.query===``?`closed`:`empty`)}else P()},oe=e=>{let n=t.current;if(!n)return;let r=n.value,i=n.selectionStart??r.length,a=e.insertText.replace(/\s+$/,``),o=n.value.length;if(u===`agent`){let e=yt(r,i);if(e){let t=r.slice(0,e.tokenStart),s=r.slice(i),c=s.startsWith(` `)?a:`${a} `;n.value=t+c+s,o=t.length+c.length,n.setSelectionRange(o,o)}else n.value=`${a} `,o=n.value.length,n.setSelectionRange(o,o);x(n.value),C(o),P(),A(),n.focus();return}let s=ut(r,i);if(s){let e=r.slice(0,s.tokenStart),t=r.slice(i),c=t.startsWith(` `)?a:`${a} `;n.value=e+c+t,o=e.length+c.length,n.setSelectionRange(o,o)}else n.value=`${a} `,o=n.value.length,n.setSelectionRange(o,o);x(n.value),C(o),P(),A(),n.focus()},se=(0,G.useCallback)(e=>{let n=t.current;if(!n)return;let r=`${`@${e}`} `,i=n.value,a=vt.exec(i),o;o=i.trim()?a?`${r}${i.slice(a[0].length).trimStart()}`:`${r}${i.trimStart()}`:r,n.value=o,x(n.value),C(r.length),P(),A(),M(r.length)},[P,A,M]),ce=()=>{if(e.isStreaming){e.onStop();return}let n=(t.current?.value??``).trim();!n&&i.length===0||o>0||(e.onSend(n,i),t.current&&(t.current.value=``),x(``),C(0),a([]),P(),A())},le=()=>{let e=t.current,n=O.current;!e||!n||(n.scrollTop=e.scrollTop,n.scrollLeft=e.scrollLeft)},ue=e=>{if(!(e.nativeEvent.isComposing||e.nativeEvent.keyCode===229)){if(m===`list`&&c.length>0){if(e.key===`ArrowDown`){e.preventDefault(),p(e=>(e+1)%c.length);return}if(e.key===`ArrowUp`){e.preventDefault(),p(e=>(e-1+c.length)%c.length);return}if(e.key===`Home`){e.preventDefault(),p(0);return}if(e.key===`End`){e.preventDefault(),p(c.length-1);return}if(e.key===`Tab`){e.preventDefault(),oe(c[f]);return}}if(e.key===`Escape`){let t=k;if(P(),t){e.preventDefault();return}}e.key===`Enter`&&!e.shiftKey&&(e.preventDefault(),ce())}},I=e=>{let t=ee(e.clipboardData);t.length>0&&(e.preventDefault(),de(t))},de=async t=>{s(e=>e+t.length);try{let n=await e.onUploadFiles(t);n.length>0&&a(e=>[...e,...n])}finally{s(e=>Math.max(0,e-t.length))}},fe=e=>{let t=Array.from(e.target.files??[]);t.length>0&&de(t),e.target.value=``},pe=e=>{a(t=>t.filter((t,n)=>n!==e))},L=e.agents??[],he=(0,G.useMemo)(()=>new Map(L.map(e=>[e.id,e])),[L]),ge=e.selectedAgentId??``,R=e.models??[],_e=e.selectedModelId??``;return(0,X.jsxs)(`div`,{className:H.composerWrapper,ref:r,children:[(0,X.jsxs)(h,{open:k,onOpenChange:e=>{e||P()},children:[(0,X.jsxs)(`div`,{className:H.composer,children:[i.length>0||o>0?(0,X.jsxs)(`div`,{className:H.pendingMediaRow,children:[i.map((e,t)=>(0,X.jsxs)(`span`,{className:H.mediaChip,children:[(0,X.jsx)(`span`,{className:H.mediaChipName,children:e.filename}),(0,X.jsx)(`button`,{type:`button`,className:H.mediaChipRemove,onClick:()=>pe(t),children:`×`})]},e.path)),o>0?(0,X.jsx)(`span`,{className:H.mediaChip,children:`Uploading…`}):null]}):null,(0,X.jsxs)(y,{className:H.composerInputWrap,children:[b?(0,X.jsx)(`div`,{ref:O,className:H.composerInputOverlay,"aria-hidden":`true`,children:(0,X.jsx)(xt,{value:b,caretIndex:S,agents:he,token:e.token})}):null,(0,X.jsx)(`textarea`,{ref:t,className:U(H.composerInput,b&&H.composerInputHasOverlay),rows:1,placeholder:`Message HybridClaw`,disabled:e.isStreaming,onInput:ae,onSelect:j,onClick:j,onKeyUp:j,onFocus:j,onKeyDown:ue,onPaste:I,onScroll:le,"aria-label":`Message input`,role:`combobox`,"aria-autocomplete":`list`,"aria-haspopup":`listbox`,"aria-controls":te,"aria-expanded":k,"aria-activedescendant":m===`list`&&c.length>0?dt(te,f):void 0})]}),(0,X.jsxs)(`div`,{className:H.composerActions,children:[(0,X.jsxs)(`div`,{className:H.composerLeftActions,children:[(0,X.jsx)(`button`,{type:`button`,className:H.attachButton,onClick:()=>n.current?.click(),"aria-label":`Attach files`,children:`+`}),(0,X.jsx)(st,{agents:L,selectedAgentId:ge,token:e.token,disabled:e.isStreaming,onSwitch:t=>{if(t.source?.type===`remote`){se(t.id);return}e.onAgentSwitch?.(t.id)}}),(0,X.jsx)(z,{models:R,selectedModelId:_e,disabled:e.isStreaming,onSwitch:t=>e.onModelSwitch?.(t)})]}),(0,X.jsx)(`button`,{type:`button`,className:U(H.sendButton,e.isStreaming&&H.stopping),onClick:ce,"aria-label":e.isStreaming?`Stop`:`Send message`,children:e.isStreaming?(0,X.jsx)(`svg`,{viewBox:`0 0 24 24`,width:`16`,height:`16`,fill:`currentColor`,"aria-hidden":`true`,children:(0,X.jsx)(`rect`,{x:`6`,y:`6`,width:`12`,height:`12`,rx:`2`})}):(0,X.jsxs)(`svg`,{viewBox:`0 0 24 24`,width:`16`,height:`16`,fill:`none`,stroke:`currentColor`,strokeWidth:`2.4`,strokeLinecap:`round`,strokeLinejoin:`round`,"aria-hidden":`true`,children:[(0,X.jsx)(`path`,{d:`M12 19V5`}),(0,X.jsx)(`path`,{d:`m5 12 7-7 7 7`})]})}),(0,X.jsx)(`input`,{ref:n,type:`file`,hidden:!0,multiple:!0,onChange:fe})]})]}),m===`closed`?null:(0,X.jsx)(ft,{mode:m,kind:u,suggestions:c,activeIdx:f,query:_,listboxId:te,token:e.token,onSelect:oe,onActiveChange:p})]}),(0,X.jsx)(`div`,{className:H.slashLiveRegion,"aria-live":`polite`,"aria-atomic":`true`,children:ne})]})}function xt(e){let t=[],n=0,r=0,i=!1,a=Math.max(0,Math.min(e.caretIndex,e.value.length)),o=()=>{i||=(t.push((0,X.jsx)(`span`,{className:H.composerOverlayCaret,"aria-hidden":`true`},`caret-${r++}`)),!0)},s=(e,n)=>{let r=n+e.length;if(a<n||a>r){t.push(e);return}let i=a-n;i>0&&t.push(e.slice(0,i)),o(),i<e.length&&t.push(e.slice(i))};for(let i of e.value.matchAll(_t)){let c=i[0],l=i[1]??``,u=i.index??0,d=u+c.length,f=e.agents.get(l);f&&(u>n&&s(e.value.slice(n,u),n),a>u&&a<d?s(c,u):(a===u&&o(),t.push((0,X.jsx)(St,{mention:c,imageUrl:f.imageUrl??null,token:e.token},`mention-${r++}`)),a===d&&o()),n=d)}return n<e.value.length&&s(e.value.slice(n),n),!i&&a===e.value.length&&o(),t.length>0?t:e.value}function St(e){let t=at({token:e.token,imageUrl:e.imageUrl});return(0,X.jsxs)(`span`,{className:H.composerMentionPill,children:[t.objectUrl?(0,X.jsx)(`img`,{className:H.composerMentionAvatar,src:t.objectUrl,alt:``}):null,(0,X.jsx)(`span`,{children:e.mention})]})}var Q={wrap:`_wrap_jrif0_1`,trigger:`_trigger_jrif0_11`,ring:`_ring_jrif0_33`,ringTrack:`_ringTrack_jrif0_37`,ringFill:`_ringFill_jrif0_43`,ringFillNominal:`_ringFillNominal_jrif0_52`,ringFillWarn:`_ringFillWarn_jrif0_56`,ringFillDanger:`_ringFillDanger_jrif0_60`,ringLabel:`_ringLabel_jrif0_64`,ringLabelUnknown:`_ringLabelUnknown_jrif0_77`,popover:`_popover_jrif0_81`,popoverTitle:`_popoverTitle_jrif0_112`,popoverTitleValue:`_popoverTitleValue_jrif0_121`,popoverRow:`_popoverRow_jrif0_126`,popoverRowValue:`_popoverRowValue_jrif0_133`,popoverProgress:`_popoverProgress_jrif0_138`,popoverProgressFill:`_popoverProgressFill_jrif0_148`,popoverProgressFillWarn:`_popoverProgressFillWarn_jrif0_157`,popoverProgressFillDanger:`_popoverProgressFillDanger_jrif0_161`,popoverFoot:`_popoverFoot_jrif0_165`},Ct=14,wt=2*Math.PI*Ct;function $(e){if(e==null)return`n/a`;let t=Math.abs(e);return t>=1e6?`${(t>=1e7?(e/1e6).toFixed(0):(e/1e6).toFixed(1)).replace(/\.0$/,``)}M`:t>=1e3?`${(t>=1e4?(e/1e3).toFixed(0):(e/1e3).toFixed(1)).replace(/\.0$/,``)}k`:String(Math.round(e))}function Tt(e){return e==null||!Number.isFinite(e)?0:Math.max(0,Math.min(100,e))}function Et(e){return e==null?`nominal`:e>=90?`danger`:e>=70?`warn`:`nominal`}function Dt(e){let t=e.sessionId,n=e.enabled&&!!t,r=a({queryKey:[`chat-context`,e.token,t],queryFn:()=>Pe(e.token,t),enabled:n,staleTime:15e3,refetchOnWindowFocus:!1}).data?.snapshot??null,i=r?.contextUsagePercent??null,o=Tt(i),s=Et(i),c=r?.contextBudgetTokens!=null&&r.contextUsedTokens!=null,l=c?wt*(1-o/100):wt,u=i!=null&&Number.isFinite(i)?Math.max(0,Math.round(i)):null,d=u==null?`–`:`${u}%`,f=r&&c&&u!=null?`Context usage ${u} percent (${$(r.contextUsedTokens)} of ${$(r.contextBudgetTokens)} tokens)`:`Context usage unavailable`;return(0,X.jsxs)(`div`,{className:Q.wrap,children:[(0,X.jsxs)(`button`,{type:`button`,className:Q.trigger,"aria-label":f,children:[(0,X.jsxs)(`svg`,{width:34,height:34,viewBox:`0 0 34 34`,className:Q.ring,"aria-hidden":`true`,children:[(0,X.jsx)(`circle`,{cx:17,cy:17,r:Ct,className:Q.ringTrack}),(0,X.jsx)(`circle`,{cx:17,cy:17,r:Ct,className:U(Q.ringFill,s===`warn`&&Q.ringFillWarn,s===`danger`&&Q.ringFillDanger,s===`nominal`&&Q.ringFillNominal),strokeDasharray:wt,strokeDashoffset:l})]}),(0,X.jsx)(`span`,{className:U(Q.ringLabel,u==null&&Q.ringLabelUnknown),children:d})]}),(0,X.jsxs)(`div`,{role:`tooltip`,className:Q.popover,children:[(0,X.jsxs)(`div`,{className:Q.popoverTitle,children:[(0,X.jsx)(`span`,{children:`Context`}),(0,X.jsx)(`span`,{className:Q.popoverTitleValue,children:r?.model||`unknown model`})]}),r&&c?(0,X.jsxs)(X.Fragment,{children:[(0,X.jsx)(`div`,{className:Q.popoverProgress,children:(0,X.jsx)(`div`,{className:U(Q.popoverProgressFill,s===`warn`&&Q.popoverProgressFillWarn,s===`danger`&&Q.popoverProgressFillDanger),style:{width:`${o}%`}})}),(0,X.jsxs)(`div`,{className:Q.popoverRow,children:[(0,X.jsx)(`span`,{children:`Used`}),(0,X.jsxs)(`span`,{className:Q.popoverRowValue,children:[$(r.contextUsedTokens),` /`,` `,$(r.contextBudgetTokens),` tokens`]})]}),(0,X.jsxs)(`div`,{className:Q.popoverRow,children:[(0,X.jsx)(`span`,{children:`Headroom`}),(0,X.jsxs)(`span`,{className:Q.popoverRowValue,children:[$(r.contextRemainingTokens),` tokens`]})]})]}):(0,X.jsxs)(`div`,{className:Q.popoverRow,children:[(0,X.jsx)(`span`,{children:`Used`}),(0,X.jsx)(`span`,{className:Q.popoverRowValue,children:r?.contextUsedTokens==null?`no usage recorded yet`:`${$(r.contextUsedTokens)} tokens`})]}),(0,X.jsxs)(`div`,{className:Q.popoverRow,children:[(0,X.jsx)(`span`,{children:`Compactions`}),(0,X.jsx)(`span`,{className:Q.popoverRowValue,children:r?`${r.compactionCount} · ${$(r.compactionMessageThreshold)} msgs / ${$(r.compactionTokenBudget)} tokens`:`n/a`})]}),(0,X.jsxs)(`div`,{className:Q.popoverFoot,children:[`Run `,(0,X.jsx)(`code`,{children:`/context`}),` for full details · `,(0,X.jsx)(`code`,{children:`/compact`}),` to archive older history.`]})]})]})}var Ot=[{label:`Trust session`,action:`session`,isAvailable:e=>e.allowSession===!0},{label:`Trust agent`,action:`agent`,isAvailable:e=>e.allowAgent===!0},{label:`Always allow`,action:`all`,isAvailable:e=>e.allowAll===!0}],kt=/^([^:\n]{2,44}):\s+(.+)$/,At=/^(GET|POST|PUT|PATCH|DELETE|HEAD|OPTIONS)\s+/i;function jt(e){return e===`yellow`?`Amber`:e===`red`?`Red`:null}function Mt(e){return/^reply\b/i.test(e)||/^approval expires\b/i.test(e)||/^approval id\b/i.test(e)}function Nt(e){let t=e.trim();return/^proposed action$/i.test(t)?`Request`:/^why$/i.test(t)?`Reason`:t}function Pt(e){let t=[],n,r=e.split(/\r?\n/).map(e=>e.trim()).filter(Boolean);for(let e of r){if(Mt(e)||/^classifier reasoning$/i.test(e)||/^if you skip this/i.test(e))continue;let r=e.match(kt);if(r){let e=Nt(r[1]??``);/^classifier reasoning$/i.test(e)||t.push({label:e,value:r[2]??``});continue}n??=e}return{introLine:n,rows:t}}function Ft(e){let t=[],n=new Set,r=(e,r)=>{let i=e.trim(),a=String(r??``).trim();if(!i||!a)return;let o=`${i.toLowerCase()}:${a}`;n.has(o)||(n.add(o),t.push({label:i,value:a}))};e.intent&&r(`Action`,e.intent),e.commandPreview&&r(At.test(e.commandPreview)?`Request`:`Preview`,e.commandPreview),e.toolName&&r(`Tool`,e.toolName);for(let t of Pt(e.prompt).rows)r(t.label,t.value);if(r(`Approval ID`,e.approvalId),e.expiresAt&&Number.isFinite(e.expiresAt)){let t=new Date(e.expiresAt);Number.isNaN(t.getTime())||r(`Expires`,t.toLocaleTimeString())}return t}function It(e){let{introLine:t}=Pt(e.prompt);return t||(e.summary?e.summary.split(/\r?\n/)[0]??``:e.intent?`Confirmation required for ${e.intent}.`:`Confirmation required before this action can continue.`)}function Lt(e){let{approval:t}=e,n=(0,G.useMemo)(()=>Ft(t),[t]),r=(0,G.useMemo)(()=>It(t),[t]),i=Ot.filter(e=>e.isAvailable(t)),a=jt(t.approvalTier),o=n=>{e.onAction(n,t.approvalId)};return(0,X.jsxs)(`div`,{className:H.approvalCard,children:[(0,X.jsxs)(`div`,{className:H.approvalHeader,children:[a?(0,X.jsx)(`span`,{className:H.approvalTier,children:a}):null,(0,X.jsx)(`span`,{className:H.approvalTitle,children:`Confirmation required`})]}),(0,X.jsx)(`p`,{className:H.approvalIntro,children:r}),n.length>0?(0,X.jsx)(`dl`,{className:H.approvalDetails,children:n.map(e=>(0,X.jsxs)(`div`,{className:H.approvalDetailRow,children:[(0,X.jsx)(`dt`,{children:e.label}),(0,X.jsx)(`dd`,{children:e.value})]},`${e.label}:${e.value}`))}):null,(0,X.jsxs)(`div`,{className:H.approvalPrimaryActions,children:[(0,X.jsx)(f,{size:`sm`,disabled:e.busy,onClick:()=>o(`once`),children:`Allow once`}),(0,X.jsx)(f,{variant:`danger`,size:`sm`,disabled:e.busy,onClick:()=>o(`deny`),children:`Cancel`})]}),i.length>0?(0,X.jsx)(`div`,{className:H.approvalTrustActions,children:i.map(t=>(0,X.jsx)(f,{variant:`outline`,size:`sm`,className:H.approvalAllow,disabled:e.busy,onClick:()=>o(t.action),children:t.label},t.action))}):null]})}var Rt=120;function zt(e,t,n){let[r,i]=(0,G.useState)(e),a=(0,G.useRef)(e),o=(0,G.useRef)(null);a.current=e,(0,G.useEffect)(()=>{if(!t){o.current!==null&&(window.clearTimeout(o.current),o.current=null),i(``);return}if(!n){o.current!==null&&(window.clearTimeout(o.current),o.current=null),i(e);return}o.current!==null||e===r||(o.current=window.setTimeout(()=>{o.current=null,(0,G.startTransition)(()=>{i(a.current)})},Rt))},[e,t,n,r]),(0,G.useEffect)(()=>()=>{o.current!==null&&window.clearTimeout(o.current)},[]);let s=t?n?r:e:``;return(0,G.useMemo)(()=>t?Te(s,{highlight:!n}):``,[t,s,n])}var Bt=`<svg viewBox="0 0 24 24" width="14" height="14" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><rect x="9" y="9" width="11" height="11" rx="2"/><path d="M5 15V5a2 2 0 0 1 2-2h10"/></svg>`,Vt=`<svg viewBox="0 0 24 24" width="14" height="14" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M20 6 9 17l-5-5"/></svg>`,Ht=`<svg viewBox="0 0 24 24" width="11" height="11" fill="none" stroke="currentColor" stroke-width="2.4" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="m9 7-5 5 5 5"/><path d="m15 7 5 5-5 5"/><path d="m13.5 5-3 14"/></svg>`,Ut=/^\/([A-Za-z0-9][A-Za-z0-9._-]*)(?=$|[\s:.,!?;)\]}])/u,Wt=new Set([`text`,`plaintext`,`plain`,`txt`]);function Gt(e){let t=e.querySelector(`code`)?.className.match(/language-([\w#.+-]+)/)?.[1]??``;return Wt.has(t)?``:t}function Kt(e){if(e.querySelector(`button[data-copy-btn]`))return;let t=Gt(e);if(t){e.classList.add(H.codeBlockLabeled);let n=document.createElement(`span`);n.className=H.codeLangLabel,n.setAttribute(`aria-hidden`,`true`),n.innerHTML=Ht;let r=document.createElement(`span`);r.textContent=t,n.appendChild(r),e.appendChild(n)}let n=document.createElement(`button`);n.type=`button`,n.dataset.copyBtn=``,n.className=H.codeCopyButton,n.innerHTML=Bt;let r=e=>{n.setAttribute(`aria-label`,e),n.title=e};r(`Copy code`);let i=null;n.addEventListener(`click`,()=>{Oe((e.querySelector(`code`)??e).textContent??``).then(e=>{e&&(n.innerHTML=Vt,n.classList.add(H.codeCopyButtonDone),r(`Copied`),i!==null&&window.clearTimeout(i),i=window.setTimeout(()=>{n.innerHTML=Bt,n.classList.remove(H.codeCopyButtonDone),r(`Copy code`)},1500))})}),e.appendChild(n)}function qt(){let e=(0,G.useRef)(null);return(0,G.useCallback)(t=>{if(e.current?.disconnect(),e.current=null,!t)return;let n=()=>{for(let e of t.querySelectorAll(`pre`))Kt(e)};n();let r=new MutationObserver(n);r.observe(t,{childList:!0,subtree:!0}),e.current=r},[])}function Jt(e,t){let n=t.split(`;`)[0]?.trim().toLowerCase()||``;return!n||n!==`application/pdf`&&!n.startsWith(`image/`)&&!n.startsWith(`video/`)||e.type.toLowerCase()===n?e:new Blob([e],{type:n})}function Yt(e){let{artifact:t,token:n}=e,r=(0,G.useRef)(null),[i,a]=(0,G.useState)(null),[o,s]=(0,G.useState)(!1),c=(t.mimeType??``).toLowerCase(),l=t.filename??`artifact`,u=c.startsWith(`image/`),d=c.startsWith(`video/`)||/\.(mp4|m4v|mov|webm)$/i.test(t.filename??``)||/\.(mp4|m4v|mov|webm)$/i.test(t.path??``),f=c===`application/pdf`||/\.pdf$/i.test(t.filename??``)||/\.pdf$/i.test(t.path??``),p=u||d||f;(0,G.useEffect)(()=>{let e=r.current;if(r.current=null,e&&URL.revokeObjectURL(e),a(null),!p||!t.path)return;let i=!1;return We(n,t.path).then(e=>{if(i)return;let t=URL.createObjectURL(Jt(e,c));r.current=t,a(t)}).catch(()=>{i||a(null)}),()=>{i=!0;let e=r.current;r.current=null,e&&URL.revokeObjectURL(e)}},[t.path,p,c,n]);let m=o?`Downloading…`:`Download`,h=async()=>{if(!(!t.path||o)){s(!0);try{let e=i??URL.createObjectURL(await We(n,t.path)),r=document.createElement(`a`);r.href=e,r.download=t.filename??`artifact`,r.rel=`noopener noreferrer`,document.body.appendChild(r),r.click(),r.remove(),i||window.setTimeout(()=>URL.revokeObjectURL(e),0)}catch{}finally{s(!1)}}};return(0,X.jsxs)(`div`,{className:U(H.artifactCard,i&&H.artifactCardWithPreview),children:[(0,X.jsxs)(`div`,{className:H.artifactHeader,children:[(0,X.jsx)(`span`,{className:H.artifactFilename,children:l}),t.type?(0,X.jsx)(`span`,{className:H.artifactBadge,children:t.type}):null,t.path?(0,X.jsx)(`button`,{type:`button`,className:H.artifactDownload,disabled:o,onClick:()=>{h()},children:m}):null]}),u&&i?(0,X.jsx)(`div`,{className:H.artifactPreview,children:(0,X.jsx)(`img`,{src:i,alt:l})}):null,f&&i?(0,X.jsx)(`div`,{className:U(H.artifactPreview,H.artifactPdfPreview),children:(0,X.jsx)(`iframe`,{src:i,title:`${l} preview`,sandbox:``})}):null,d&&i?(0,X.jsx)(`div`,{className:U(H.artifactPreview,H.artifactVideoPreview),children:(0,X.jsx)(`video`,{controls:!0,preload:`metadata`,src:i,children:(0,X.jsxs)(`a`,{href:i,download:l,children:[`Download `,l]})})}):null]})}function Xt(e){let t=(0,G.useRef)(null),[n,r]=(0,G.useState)(null);return(0,G.useEffect)(()=>{let n=t.current;if(t.current=null,n&&URL.revokeObjectURL(n),r(null),!e.imageUrl)return;let i=!1;return Ge(e.token,e.imageUrl).then(e=>{if(i)return;let n=URL.createObjectURL(e);t.current=n,r(n)}).catch(()=>{i||r(null)}),()=>{i=!0;let e=t.current;t.current=null,e&&URL.revokeObjectURL(e)}},[e.imageUrl,e.token]),n}var Zt=(0,G.memo)(function(e){let{message:t,token:n}=e,[r,i]=(0,G.useState)(!1),a=()=>{e.onCopy(t.rawContent??t.content),i(!0),setTimeout(()=>i(!1),900)},o=(0,G.useMemo)(()=>{let e=new Map;return(t.artifacts??[]).map(t=>{let n=[t.path,t.filename,t.mimeType,t.type].filter(Boolean),r=n.length>0?n.join(`|`):`artifact`,i=e.get(r)??0;return e.set(r,i+1),{artifact:t,key:`${r}:${i}`}})},[t.artifacts]),s=t.role===`approval`,c=s&&!!t.pendingApproval,l=t.role===`assistant`||t.role===`command`||s&&!c,u=zt(t.content,l,e.isStreaming),d=qt(),p=t.assistantPresentation,m=p?.displayName??`Assistant`,h=Xt({token:n,imageUrl:p?.imageUrl});if(t.role===`thinking`)return(0,X.jsxs)(`div`,{className:H.thinking,role:`status`,"aria-label":`Assistant is thinking`,children:[(0,X.jsx)(`span`,{className:H.thinkingDot}),(0,X.jsx)(`span`,{className:H.thinkingDot}),(0,X.jsx)(`span`,{className:H.thinkingDot})]});let g=t.role===`user`,_=t.role===`assistant`,v=g||t.content.trim().length>0||o.length===0||s,y=U(H.messageBlock,g&&H.messageBlockUser,(_||t.role===`system`||t.role===`command`||s)&&H.messageBlockAssistant),b=U(H.bubble,g&&H.bubbleUser,(_||s)&&H.bubbleAssistant,s&&H.bubbleApproval,t.role===`system`&&H.bubbleSystem,t.role===`command`&&H.bubbleCommand);return(0,X.jsxs)(`div`,{className:y,children:[_?(0,X.jsxs)(`div`,{className:H.agentLabel,children:[h?(0,X.jsx)(`img`,{className:H.agentAvatar,src:h,alt:``}):(0,X.jsx)(`span`,{className:H.agentInitial,children:m.charAt(0).toUpperCase()}),(0,X.jsx)(`span`,{children:m})]}):null,v?(0,X.jsx)(`div`,{className:b,children:c&&t.pendingApproval?(0,X.jsx)(Lt,{approval:t.pendingApproval,busy:e.approvalBusy,onAction:e.onApprovalAction}):l?(0,X.jsx)(`div`,{ref:d,className:H.markdownContent,dangerouslySetInnerHTML:{__html:u}}):g?(0,X.jsx)(Qt,{content:t.content,presentation:t.addressedAgentPresentation,skillInvocationTargets:e.skillInvocationTargets,token:n}):t.content}):null,o.map(({artifact:e,key:t})=>(0,X.jsx)(Yt,{artifact:e,token:n},t)),e.isStreaming?null:(0,X.jsxs)(`div`,{className:H.messageActions,children:[_&&t.replayRequest?(0,X.jsx)(f,{variant:`ghost`,size:`icon`,className:H.actionButton,title:`Regenerate`,"aria-label":`Regenerate response`,onClick:()=>e.onRegenerate(t),children:`↻`}):null,_?(0,X.jsxs)(X.Fragment,{children:[(0,X.jsx)(f,{variant:`ghost`,size:`icon`,className:U(H.actionButton,t.responseRating===`up`&&H.actionButtonSelected),title:t.responseRating===`up`?`Clear thumbs up`:`Thumbs up`,"aria-label":t.responseRating===`up`?`Clear thumbs up rating`:`Rate response thumbs up`,"aria-pressed":t.responseRating===`up`,"data-rating-locked":t.responseRating?`true`:void 0,disabled:e.ratingBusy===!0||!t.messageId||t.responseRating===`down`,onClick:()=>e.onRate?.(t,t.responseRating===`up`?null:`up`),children:(0,X.jsx)(Se,{width:`13`,height:`13`,filled:t.responseRating===`up`})}),(0,X.jsx)(f,{variant:`ghost`,size:`icon`,className:U(H.actionButton,t.responseRating===`down`&&H.actionButtonSelected),title:t.responseRating===`down`?`Clear thumbs down`:`Thumbs down`,"aria-label":t.responseRating===`down`?`Clear thumbs down rating`:`Rate response thumbs down`,"aria-pressed":t.responseRating===`down`,"data-rating-locked":t.responseRating?`true`:void 0,disabled:e.ratingBusy===!0||!t.messageId||t.responseRating===`up`,onClick:()=>e.onRate?.(t,t.responseRating===`down`?null:`down`),children:(0,X.jsx)(L,{width:`13`,height:`13`,filled:t.responseRating===`down`})})]}):null,(0,X.jsx)(f,{variant:`ghost`,size:`icon`,className:U(H.actionButton,r&&H.actionButtonSuccess),title:`Copy`,"aria-label":r?`Copied`:`Copy message`,onClick:a,children:r?`✓`:`⧉`}),g?(0,X.jsx)(f,{variant:`ghost`,size:`icon`,className:H.actionButton,title:`Edit`,"aria-label":`Edit message`,onClick:()=>e.onEdit(t),children:`✎`}):null,e.branchInfo&&e.branchInfo.total>1?(0,X.jsxs)(`div`,{className:H.branchSwitcher,children:[(0,X.jsx)(f,{variant:`ghost`,size:`icon`,className:H.branchButton,"aria-label":`Previous branch`,disabled:e.branchInfo.current<=1,onClick:()=>e.onBranchNav(t,-1),children:`‹`}),(0,X.jsxs)(`span`,{children:[e.branchInfo.current,`/`,e.branchInfo.total]}),(0,X.jsx)(f,{variant:`ghost`,size:`icon`,className:H.branchButton,"aria-label":`Next branch`,disabled:e.branchInfo.current>=e.branchInfo.total,onClick:()=>e.onBranchNav(t,1),children:`›`})]}):null]})]})});function Qt(e){let t=Ye(e.content),n=[],r=0;for(let[i,a]of t.entries()){a.index>r&&$t(n,e.content.slice(r,a.index),`text-${i}`,r===0,e.skillInvocationTargets);let t=e.presentation?.agentId?.toLowerCase()===a.agentId.toLowerCase()?e.presentation:null;n.push((0,X.jsx)(en,{mention:a.mention,imageUrl:t?.imageUrl??null,token:e.token},`${a.index}-${i}`)),r=a.index+a.mention.length}return r<e.content.length&&$t(n,e.content.slice(r),`text-tail`,r===0,e.skillInvocationTargets),(0,X.jsx)(X.Fragment,{children:n})}function $t(e,t,n,r,i){if(!t)return;if(!r||!i){e.push(t);return}let a=Ut.exec(t),o=a?.[1]??``,s=i.get(o.toLowerCase());if(!a||!o||!s){e.push(t);return}let c=a[0];e.push((0,X.jsx)(`a`,{className:H.userSkillCommandLink,href:`/admin/skills/${encodeURIComponent(s)}`,children:c},`${n}-skill-command`));let l=t.slice(c.length);l&&e.push(l)}function en(e){let t=Xt({token:e.token,imageUrl:e.imageUrl});return(0,X.jsxs)(`span`,{className:H.userAgentMentionPill,children:[t?(0,X.jsx)(`img`,{className:H.userAgentMentionAvatar,src:t,alt:``}):null,(0,X.jsx)(`span`,{children:e.mention})]})}function tn(e){let[t,n]=(0,G.useState)(e.initial);return(0,X.jsxs)(X.Fragment,{children:[(0,X.jsx)(`textarea`,{className:H.editArea,value:t,onChange:e=>n(e.target.value),"aria-label":`Edit message`,autoFocus:!0}),(0,X.jsxs)(`div`,{className:H.editButtons,children:[(0,X.jsx)(f,{onClick:()=>e.onSave(t.trim()),disabled:!t.trim(),children:`Save`}),(0,X.jsx)(f,{variant:`ghost`,onClick:e.onCancel,children:`Cancel`})]})]})}function nn(){let e=s(),t=o({strict:!1}).sessionId,n=(0,G.useRef)(null),r=t??n.current??``,i=(0,G.useRef)(r);i.current=r,(0,G.useEffect)(()=>{t&&(n.current=null)},[t]),(0,G.useEffect)(()=>{r&&p(r)},[r]);let a=(0,G.useCallback)(()=>i.current,[]),c=(0,G.useCallback)((t,n)=>e({to:`/chat/$sessionId`,params:{sessionId:t},...n}),[e]);return{sessionId:r,getSessionId:a,navigateToSession:c,switchToSession:(0,G.useCallback)((e,t)=>(n.current=e,i.current=e,c(e,t)),[c]),startFreshChat:(0,G.useCallback)(()=>{n.current=null,e({to:`/chat`})},[e]),ensureSessionForSend:(0,G.useCallback)(()=>{if(i.current)return i.current;let e=d();return n.current=e,i.current=e,c(e,{replace:!0}),e},[c]),handleSessionIdCorrection:(0,G.useCallback)(e=>{e!==i.current&&c(e,{replace:!0})},[c])}}async function rn(e,t){let n=await fetch(e,{method:`POST`,headers:{...fe(t.token,t.body),Accept:`application/x-ndjson`},body:JSON.stringify(t.body),signal:t.signal});n.ok||await Ae(n);let{callbacks:r}=t,i=e=>{let t=String(e||``).trim();if(!t)return null;let n;try{n=JSON.parse(t)}catch{return console.warn(`Ignoring malformed chat stream line`,t),null}return!n||typeof n!=`object`?null:n.type===`text`&&typeof n.delta==`string`?(r.onTextDelta(n.delta),null):n.type===`approval`&&typeof n.approvalId==`string`&&typeof n.prompt==`string`?(r.onApproval(n),null):n.type===`result`&&n.result&&typeof n.result==`object`?n.result:typeof n.status==`string`&&Array.isArray(n.toolsUsed)?n:null};if(!n.body){let e=await n.text().catch(()=>``),t=null;for(let n of e.split(`
|
|
3
|
+
`)){let e=i(n);e&&(t=e)}if(!t)throw Error(`Chat stream ended without a result payload.`);return t}let a=n.body.getReader(),o=new TextDecoder,s=``,c=null,l=(e=!1)=>{let t=s.split(`
|
|
4
|
+
`),n=e?t.pop()??``:null;s=e?``:t.pop()??``;for(let e of t){let t=i(e);t&&(c=t)}if(e&&n?.trim()){let e=i(n);e&&(c=e)}};try{for(;;){let{done:e,value:t}=await a.read();if(e)break;s+=o.decode(t,{stream:!0}),l()}s+=o.decode(),l(!0)}finally{a.releaseLock()}if(!c)throw Error(`Chat stream ended without a result payload.`);return c}function an(e){let t=e.trim().split(/\s+/),n=t[0]?.replace(/^\/+/,``).toLowerCase(),r=t[1]?.toLowerCase();return(n===`agent`||n===`agents`)&&(r===`create`||r===`install`)}function on(e){let t=e.trim().split(/\s+/),n=t[0]?.replace(/^\/+/,``).toLowerCase();if(n!==`agent`&&n!==`agents`||t[1]?.toLowerCase()!==`switch`)return null;let r=t[2]?.trim();return r&&!/\s/.test(r)?r:null}function sn(e){return/^Session agent set to\b/i.test(e.trim())}function cn(e){return/\bBOOTSTRAP\.md\b/i.test(e)}function ln(e){let{token:t,userId:r,getSessionId:i,setError:a,refreshRecent:o,onSessionIdCorrection:s,onModelResolved:c,resolveAddressedAgentPresentation:u}=e,d=n(),f=(0,G.useRef)(null),[p,m]=(0,G.useState)(!1),[h,g]=(0,G.useState)(null),[_,v]=(0,G.useState)(null),y=(0,G.useCallback)((e,n)=>{let r=Y(t,e);d.setQueryData(r,t=>{let r=t?.messages??[],i=typeof n==`function`?n(r):n;return i===r?t:{messages:i,branchFamilies:t?.branchFamilies??new Map,resolvedSessionId:t?.resolvedSessionId??e,agentId:t?.agentId??null,bootstrapAutostart:t?.bootstrapAutostart??null}})},[d,t]);return{sendMessage:(0,G.useCallback)(async(e,n,p)=>{if(f.current)return a(`Wait for the current run to finish before sending another message.`),!1;let h=i(),_=e=>y(h,e),b=p?.hideUser?null:De();if(a(``),b){let t=u?.(e)??null,r={id:b,role:`user`,content:e,rawContent:e,sessionId:h,media:n,artifacts:[],replayRequest:{content:e,media:n},addressedAgentPresentation:t};_(e=>[...e,r])}let x=De();_(e=>[...e,{id:x,role:`thinking`,content:``,sessionId:h}]);let S=De();g(S);let C={controller:new AbortController,sessionId:h,messageRole:`assistant`,assistantText:``,lastRenderedText:``,pendingApproval:null,renderFrame:0,stopping:!1};f.current=C,v(h),m(!0);let w=()=>{if(C.renderFrame=0,C.assistantText===C.lastRenderedText&&!C.pendingApproval)return;C.lastRenderedText=C.assistantText;let e=C.assistantText,t=C.pendingApproval;_(n=>{let r=n.filter(e=>e.id!==x),i=r.find(e=>e.id===S);return i?r.map(n=>n===i?{...n,role:C.messageRole,content:e,pendingApproval:t}:n):[...r,{id:S,role:C.messageRole,content:e,sessionId:C.sessionId,artifacts:[],pendingApproval:t}]})},T=()=>{C.renderFrame&&=(cancelAnimationFrame(C.renderFrame),0),w()},E=()=>{C.renderFrame||=requestAnimationFrame(w)};try{let i=await rn(`/api/chat`,{token:t,body:{sessionId:h,channelId:`web`,userId:r,username:`web`,content:e,stream:!0,...n.length>0?{media:n}:{}},signal:C.controller.signal,callbacks:{onTextDelta:e=>{C.assistantText+=e,E()},onApproval:e=>{C.pendingApproval=e,C.messageRole=`approval`,C.assistantText.trim()||(C.assistantText=P(e)),E()}}});if(i.status===`error`)throw Error(i.error??`Unknown error`);i.sessionId&&i.sessionId!==h&&s(i.sessionId);let a=i.model?.trim();a&&c?.(a),T();let l=i.result??C.assistantText??``,u=C.pendingApproval,f=i.artifacts??[],p=typeof i.addressEnvelope?.to==`string`?i.addressEnvelope.to:null;if(!i.messageRole)throw Error(`Gateway chat result is missing messageRole.`);let m=i.messageRole,g=m===`command`&&l.trim().length===0&&f.length===0,v=(t,r,a)=>({...a,id:t,role:m,content:l,sessionId:r,messageId:i.assistantMessageId??null,artifacts:f,assistantPresentation:i.assistantPresentation??null,pendingApproval:u,responseRating:null,replayRequest:{content:e,media:n}});_(e=>{let t=e.filter(e=>e.id!==x),n=t.some(e=>e.id===S),r=e=>e.id===S?v(S,i.sessionId??e.sessionId,e):b&&e.id===b&&e.role===`user`?{...e,addressedAgentPresentation:p?i.assistantPresentation??null:null,messageId:e.messageId??i.userMessageId??null,sessionId:i.sessionId??e.sessionId}:e;if(g)return t.filter(e=>e.id!==S).map(r);let a=t.map(r);return n?a:[...a,v(S,i.sessionId??C.sessionId)]}),o();let y=m===`command`&&sn(l)?on(e):null;if(y){let e=i.sessionId??h,n=Y(t,e);d.setQueryData(n,e=>e&&{...e,agentId:y,bootstrapAutostart:cn(l)?{status:`starting`,fileName:`BOOTSTRAP.md`}:e.bootstrapAutostart}),d.invalidateQueries({queryKey:n,refetchType:`none`}),d.invalidateQueries({queryKey:[`chat-context`,t,e]})}m===`command`&&an(e)&&d.invalidateQueries({queryKey:[`agents-list`,t]})}catch(e){C.renderFrame&&cancelAnimationFrame(C.renderFrame);let t=l(e);_(e=>{let n=e.filter(e=>e.id!==x);return C.stopping?n:[...n,{id:De(),role:`system`,content:`Error: ${t}`,sessionId:h}]})}finally{f.current=null,v(null),m(!1),g(null)}return!0},[t,r,i,y,s,c,u,d,a,o]),stopRequest:(0,G.useCallback)(async()=>{let e=f.current;if(!(!e||e.stopping)){e.stopping=!0;try{await ze(t,e.sessionId,r,[`stop`])}catch(e){a(`Failed to stop: ${l(e)}`)}finally{e.controller.abort()}}},[t,r,a]),isStreaming:p,streamingMsgId:h,activeSessionId:_,isActive:(0,G.useCallback)(()=>f.current!==null,[])}}var un=120,dn=220;function fn(){let e=(0,G.useRef)(null),t=(0,G.useRef)(null),n=(0,G.useRef)(null),r=(0,G.useRef)(0),[i,a]=(0,G.useState)(!0),o=(0,G.useRef)(!0),s=(0,G.useRef)(!1),c=(0,G.useCallback)(e=>{o.current!==e&&(o.current=e,a(e))},[]),l=(0,G.useCallback)((e,t)=>{let n=Math.max(0,e.scrollHeight-e.clientHeight),r=Math.max(0,Math.min(t,n));r!==e.scrollTop&&(s.current=!0,e.scrollTop=r)},[]),u=(0,G.useCallback)(()=>{let t=e.current;!t||!o.current||t.scrollHeight<=t.clientHeight||l(t,t.scrollHeight)},[l]),d=(0,G.useCallback)(n=>{if(t.current?.abort(),t.current=null,e.current=n,!n)return;let r=new AbortController;t.current=r,n.addEventListener(`scroll`,()=>{if(s.current){s.current=!1;return}c(n.scrollHeight-n.scrollTop-n.clientHeight<=un)},{passive:!0,signal:r.signal}),u()},[c,u]),f=(0,G.useCallback)(e=>{if(n.current?.disconnect(),n.current=null,!e||typeof ResizeObserver>`u`)return;let t=new ResizeObserver(()=>u());t.observe(e),n.current=t},[u]),p=(0,G.useCallback)(()=>{let t=e.current;if(!t)return;if(r.current&&=(cancelAnimationFrame(r.current),0),c(!0),typeof window<`u`&&typeof window.matchMedia==`function`&&window.matchMedia(`(prefers-reduced-motion: reduce)`).matches){l(t,t.scrollHeight);return}let n=t.scrollTop;if(t.scrollHeight-t.clientHeight-n<=0)return;let i=performance.now(),a=()=>{let t=e.current;if(!t){r.current=0;return}let o=Math.min(1,(performance.now()-i)/dn),s=1-(1-o)**3;l(t,n+(t.scrollHeight-t.clientHeight-n)*s),r.current=o<1?requestAnimationFrame(a):0};r.current=requestAnimationFrame(a)},[c,l]),m=(0,G.useCallback)(()=>{c(!0);let t=e.current;t&&l(t,t.scrollHeight)},[c,l]);return(0,G.useEffect)(()=>()=>{t.current?.abort(),n.current?.disconnect(),r.current&&cancelAnimationFrame(r.current)},[]),{scrollRef:d,contentRef:f,isPinned:i,jumpToBottom:p,resetToBottom:m}}var pn=[],mn=[],hn=5e3,gn=`bootstrap-autostart-thinking`,_n=1500,vn=`Ready to claw through your to-do list?`,yn=/^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/;function bn(){let e=new URLSearchParams(window.location.search).get(`agent`)?.trim();return e&&yn.test(e)?e:``}function xn(e,t){let n=new Map;if(t.size===0)return n;for(let r of e){let e=r.branchKey;if(!e)continue;let i=t.get(e);if(!i||i.length<2)continue;let a=i.findIndex(e=>e.sessionId===r.sessionId);a<0||n.set(r.id,{current:a+1,total:i.length})}return n}function Sn(e,t,n=``,r=`user`){return[`chat-recent`,e,t,n,r]}function Cn(e,t){return[`chat-recent`,e,t]}function wn(e,t){return[`chat-context`,e,t]}function Tn(){let e=we(),t=n(),i=(0,G.useRef)(D()).current,o=(0,G.useMemo)(()=>new URLSearchParams(window.location.search).get(`prompt`)||``,[]),s=(0,G.useMemo)(bn,[]),[d,f]=(0,G.useState)({message:``,version:0}),p=d.message,h=(0,G.useCallback)(e=>{f(t=>({message:typeof e==`function`?e(t.message):e,version:t.version+1}))},[]),[g,_]=(0,G.useState)(!1),[y,b]=(0,G.useState)(null),[S,C]=(0,G.useState)(!1),[w,E]=(0,G.useState)(null),[ee,O]=(0,G.useState)(!1),[te,k]=(0,G.useState)(s||null),[j,M]=(0,G.useState)(``),[N,P]=(0,G.useState)(`user`),[F,ae]=(0,G.useState)(null),[oe,ce]=(0,G.useState)(``),ue=(0,G.useRef)(null),I=qe(oe,160).trim(),{scrollRef:de,contentRef:fe,isPinned:pe,jumpToBottom:L,resetToBottom:me}=fn(),he=(0,G.useRef)(null),ge=(0,G.useRef)(null);(0,G.useEffect)(()=>{let e=()=>{let e=window.visualViewport?.height??window.innerHeight;!Number.isFinite(e)||e<=0||(document.documentElement.style.setProperty(`--chat-visual-viewport-height`,`${Math.round(e)}px`),document.scrollingElement?.scrollTo({left:0}),document.body.scrollLeft=0,document.documentElement.scrollLeft=0)};return e(),window.addEventListener(`resize`,e),window.addEventListener(`orientationchange`,e),window.visualViewport?.addEventListener(`resize`,e),window.visualViewport?.addEventListener(`scroll`,e),()=>{window.removeEventListener(`resize`,e),window.removeEventListener(`orientationchange`,e),window.visualViewport?.removeEventListener(`resize`,e),window.visualViewport?.removeEventListener(`scroll`,e),document.documentElement.style.removeProperty(`--chat-visual-viewport-height`)}},[]);let{sessionId:R,getSessionId:z,navigateToSession:ve,switchToSession:B,startFreshChat:be,ensureSessionForSend:V,handleSessionIdCorrection:Se}=nn();(0,G.useEffect)(()=>{s&&(ue.current=V())},[V,s]);let Ce=R&&ue.current===R?s:``,Te=(0,G.useCallback)(()=>{t.invalidateQueries({queryKey:Cn(e.token,i)}),t.invalidateQueries({queryKey:Y(e.token,z()),refetchType:`none`})},[t,e.token,i,z]),U=ye(e),W=a({queryKey:[`app-status`,e.token],queryFn:()=>ie(e.token),staleTime:1/0,enabled:U,initialData:e.status===`ready`&&e.gatewayStatus?e.gatewayStatus:void 0}),Ae=a({queryKey:[`agents-list`,e.token],queryFn:()=>le(e.token),staleTime:3e4,enabled:U}),je=a({queryKey:[`models`,e.token],queryFn:()=>xe(e.token),staleTime:3e4,enabled:U}),Ne=a({queryKey:[`skills`,e.token],queryFn:()=>_e(e.token),staleTime:6e4,retry:!1,enabled:U});(0,G.useEffect)(()=>{M(W.data?.defaultModel?.trim()??``)},[R,W.data?.defaultModel]),(0,G.useEffect)(()=>{W.error&&(console.error(`Failed to load gateway status for chat page`,W.error),h(`Failed to load the default agent. New chats will use main until gateway status loads.`))},[W.error,h]),(0,G.useEffect)(()=>{je.error&&(console.error(`Failed to load models list for chat page`,je.error),h(`Failed to load the model list. Model switching is unavailable.`))},[je.error,h]);let Fe=a({queryKey:Sn(e.token,i,I,N),queryFn:()=>Me(e.token,i,`web`,I?Ke.maxSearchResults:Ke.maxRecentSessions,I||void 0,N),staleTime:1e4,enabled:U}),Ve=Fe.data?.sessions??[],He=(0,G.useMemo)(()=>(Ae.data??[]).map(e=>({id:e.id,name:e.name,imageUrl:e.imageUrl??null,emptyChatHeader:e.emptyChatHeader??null,source:e.source})),[Ae.data]),Ue=(0,G.useMemo)(()=>new Map((Ne.data?.skills??[]).filter(e=>e.userInvocable).map(e=>[e.name.toLowerCase(),e.name])),[Ne.data?.skills]),We=(0,G.useCallback)(e=>{let t=Ye(e);for(let e of t){let t=He.find(t=>t.id.toLowerCase()===e.agentId.toLowerCase());if(t)return{agentId:t.id,displayName:t.name??t.id,imageUrl:t.imageUrl??null}}return null},[He]),Ge=je.data?.models??mn,K=ln({token:e.token,userId:i,getSessionId:z,setError:h,refreshRecent:Te,onSessionIdCorrection:Se,onModelResolved:M,resolveAddressedAgentPresentation:We});(0,G.useEffect)(()=>{let e=d.message;if(_(!1),!e)return;let t=window.setTimeout(()=>{_(!0)},hn),n=window.setTimeout(()=>{h(``),_(!1)},5200);return()=>{window.clearTimeout(t),window.clearTimeout(n)}},[d,h]);let q=a({queryKey:Y(e.token,R),queryFn:()=>Qe(e.token,R,i,Ce||void 0),enabled:U&&!!R,staleTime:1/0}),Je=a({queryKey:wn(e.token,R),queryFn:()=>Pe(e.token,R),enabled:U&&!!R,staleTime:15e3,refetchOnWindowFocus:!1}),J=q.data?.messages??pn,Ze=q.data?.bootstrapAutostart?.status===`starting`,et=(0,G.useMemo)(()=>Ze?[...J,{id:gn,role:`thinking`,content:``,sessionId:R}]:J,[Ze,J,R]),tt=q.data?.branchFamilies??Xe,nt=te?.trim().toLowerCase()||q.data?.agentId?.trim().toLowerCase()||W.data?.defaultAgentId?.trim().toLowerCase()||`main`,rt=He.find(e=>e.id.toLowerCase()===nt)?.emptyChatHeader?.trim()||vn,Z=r({mutationFn:t=>Ee(e.token,t),onSuccess:n=>{if(!n.deleted){h(`Delete failed: session was not found.`);return}let r=n.sessionId;t.removeQueries({queryKey:Y(e.token,r)}),t.removeQueries({queryKey:wn(e.token,r)}),t.invalidateQueries({queryKey:Cn(e.token,i)}),t.invalidateQueries({queryKey:[`overview`],refetchType:`none`}),ae(null),r===z()&&be()},onError:e=>{h(`Delete failed: ${l(e)}`)}}),it=r({mutationFn:t=>{if(!t.message.messageId)throw Error(`This response cannot be rated right now.`);return Re(e.token,{sessionId:t.message.sessionId,messageId:t.message.messageId,userId:i,rating:t.rating})},onSuccess:(n,r)=>{let i=r.message.sessionId;t.setQueryData(Y(e.token,i),e=>e&&{...e,messages:e.messages.map(e=>e.messageId===n.messageId?{...e,responseRating:n.rating}:e)})},onError:e=>{h(`Rating failed: ${l(e)}`)}});(0,G.useEffect)(()=>{let e=Je.data?.snapshot?.model?.trim()??``;e&&M(e)},[Je.data?.snapshot?.model]),(0,G.useEffect)(()=>{if(s&&ue.current===R){k(s);return}k(null)},[s,R]),(0,G.useEffect)(()=>{q.error&&h(l(q.error))},[q.error,h]),(0,G.useEffect)(()=>{if(q.data?.bootstrapAutostart?.status!==`starting`||q.isFetching)return;let e=window.setTimeout(()=>{q.refetch()},_n);return()=>window.clearTimeout(e)},[q.data?.bootstrapAutostart?.status,q.isFetching,q.refetch]),(0,G.useEffect)(()=>{if(!w)return;let e=document.body.style.overflow,t=document.activeElement;document.body.style.overflow=`hidden`,ge.current?.focus();let n=e=>{if(e.key===`Escape`){e.preventDefault(),E(null);return}if(e.key!==`Tab`)return;let t=Array.from(he.current?.querySelectorAll(`a[href], button:not(:disabled)`)??[]);if(t.length===0)return;let n=t[0],r=t[t.length-1];e.shiftKey&&document.activeElement===n?(e.preventDefault(),r?.focus()):!e.shiftKey&&document.activeElement===r&&(e.preventDefault(),n?.focus())};return document.addEventListener(`keydown`,n),()=>{document.removeEventListener(`keydown`,n),document.body.style.overflow=e,t instanceof HTMLElement&&t.focus()}},[w]),(0,G.useEffect)(()=>{let e=q.data?.resolvedSessionId;!e||e===R||ve(e,{replace:!0})},[q.data?.resolvedSessionId,R,ve]);let at=(0,G.useMemo)(()=>xn(J,tt),[J,tt]),ot=(0,G.useRef)(!1);(0,G.useEffect)(()=>{ot.current&&!K.isStreaming&&R&&t.invalidateQueries({queryKey:wn(e.token,R)}),ot.current=K.isStreaming},[K.isStreaming,t,e.token,R]),(0,G.useEffect)(()=>{R&&me()},[R,me]);let st=(0,G.useCallback)(async(n,r)=>{if(!n.messageId||!n.sessionId){h(`This message cannot be edited right now.`);return}b(null);try{let a=await Le(e.token,n.sessionId,n.messageId);t.invalidateQueries({queryKey:Y(e.token,n.sessionId),refetchType:`none`}),await t.ensureQueryData({queryKey:Y(e.token,a.sessionId),queryFn:()=>Qe(e.token,a.sessionId,i)}),await B(a.sessionId),K.sendMessage(r,n.media??[])}catch(e){h(l(e))}},[e.token,t,h,B,K.sendMessage,i]),ct=(0,G.useCallback)(e=>{e.replayRequest&&(L(),K.sendMessage(e.replayRequest.content,e.replayRequest.media,{hideUser:!0}))},[L,K.sendMessage]),lt=(0,G.useCallback)(async(e,t)=>{let n=ke(e,t);if(n){C(!0);try{L(),await K.sendMessage(n,[],{hideUser:!0})}finally{C(!1)}}},[L,K.sendMessage]),ut=(0,G.useCallback)((e,t)=>{it.mutate({message:e,rating:t})},[it]),dt=(0,G.useCallback)(async t=>{let n=await Promise.allSettled(t.map(t=>Be(e.token,t))),r=[];for(let e of n)e.status===`fulfilled`&&e.value.media?r.push(e.value.media):e.status===`rejected`&&h(l(e.reason));return r},[e.token,h]),ft=(0,G.useCallback)(()=>{if(K.isActive()){h(`Stop the current run before starting a new chat.`);return}be(),Te()},[K.isActive,be,Te,h]),pt=(0,G.useCallback)((e,t)=>{V(),L(),K.sendMessage(e,t)},[V,L,K.sendMessage]),mt=(0,G.useCallback)((n,r)=>{let i=r.trim();i&&t.setQueryData(Y(e.token,n),e=>{let t=e?.messages??[];return t.some(e=>e.role===`command`&&(e.rawContent||e.content).trim()===i)?e:{messages:[...t,{id:De(),role:`command`,content:i,rawContent:i,sessionId:n,artifacts:[],replayRequest:null}],branchFamilies:e?.branchFamilies??new Map,resolvedSessionId:n,agentId:e?.agentId??null,bootstrapAutostart:e?.bootstrapAutostart??null}})},[e.token,t]),ht=(0,G.useCallback)(async n=>{let r=Y(e.token,n);return t.fetchQuery({queryKey:r,queryFn:()=>Qe(e.token,n,i),staleTime:0}).catch(e=>(console.warn(`Failed to prefetch chat history before appending switch result`,e),null))},[e.token,t,i]),gt=(0,G.useCallback)(async(n,r,a,o)=>{if(!r||/\s/.test(r))return;if(K.isActive()){h(o);return}V();let s=z();try{let o=await ze(e.token,s,i,[...n,r]),c=o.sessionId?.trim()||s,l=await ht(c);mt(c,o.text),c!==s&&await B(c,{replace:!0}),t.invalidateQueries({queryKey:wn(e.token,c)}),n[0]===`agent`&&n[1]===`switch`&&l?.bootstrapAutostart?.fileName===`BOOTSTRAP.md`&&(l.bootstrapAutostart.status===`idle`||l.bootstrapAutostart.status===`starting`)&&(t.setQueryData(Y(e.token,c),e=>e&&{...e,bootstrapAutostart:{status:`starting`,fileName:`BOOTSTRAP.md`}}),L()),Te(),a(r)}catch(e){h(l(e))}},[mt,e.token,V,ht,z,L,t,Te,h,K.isActive,B,i]),_t=(0,G.useCallback)(e=>gt([`agent`,`switch`],e,k,`Could not switch agent — stop the current run and try again.`),[gt]),vt=(0,G.useCallback)(e=>gt([`model`,`set`],e,M,`Could not switch model — stop the current run and try again.`),[gt]),yt=(0,G.useCallback)(e=>{if(K.isActive()){h(`Stop the current run before switching chats.`);return}ve(e)},[K.isActive,ve,h]),xt=(0,G.useCallback)(e=>K.activeSessionId===e?(h(`Stop the current run before deleting this chat.`),!1):!Z.isPending,[Z.isPending,K.activeSessionId,h]),St=(0,G.useCallback)(e=>{xt(e.sessionId)&&ae(e)},[xt]),Q=(0,G.useCallback)(()=>{if(!F)throw Error(`Delete confirmation is missing a session.`);xt(F.sessionId)&&Z.mutate(F.sessionId)},[xt,Z,F]),Ct=(0,G.useCallback)(n=>{n!==z()&&t.prefetchQuery({queryKey:Y(e.token,n),queryFn:()=>Qe(e.token,n,i),staleTime:3e4})},[t,e.token,z,i]),wt=(0,G.useCallback)(()=>{t.invalidateQueries({queryKey:Sn(e.token,i,I,N)})},[t,e.token,i,I,N]),$=(0,G.useCallback)(async()=>{let t=z();if(!t){h(`Open or send a chat before creating a mobile QR code.`);return}O(!0);try{E(await Ie(e.token,{userId:i,sessionId:t,baseUrl:window.location.origin}))}catch(e){h(l(e))}finally{O(!1)}},[e.token,z,i,h]),Tt=(0,G.useCallback)(e=>{b(e.id)},[]),Et=(0,G.useCallback)((e,t)=>{let n=e.branchKey;if(!n)return;let r=tt.get(n);if(!r||r.length<2)return;let i=r.findIndex(t=>t.sessionId===e.sessionId);if(i<0)return;let a=i+t;if(a<0||a>=r.length)return;let o=r[a];o&&yt(o.sessionId)},[tt,yt]),Ot=et.length===0,kt=q.isFetching,At={sessions:Ve,activeSessionId:R,onNewChat:ft,onOpenSession:yt,onHoverSession:Ct,onRequestDeleteSession:St,deleteDisabled:Z.isPending,isPending:kt,searchQuery:oe,onSearchQueryChange:ce,recentScope:N,onRecentScopeChange:P,isLoading:Fe.isFetching,onRefreshRecent:wt};return(0,X.jsx)(u,{children:(0,X.jsxs)(`div`,{className:H.chatPage,"aria-busy":kt,children:[(0,X.jsx)($e,{...At}),(0,X.jsxs)(`div`,{className:H.chatMain,children:[(0,X.jsxs)(`div`,{className:H.chatTopbar,children:[(0,X.jsx)(m,{className:H.chatMobileTrigger}),(0,X.jsx)(Dt,{sessionId:R,token:e.token,enabled:U}),(0,X.jsx)(`button`,{type:`button`,className:H.mobileQrButton,onClick:()=>void $(),disabled:ee,"aria-label":`Show mobile QR code`,title:`Show mobile QR code`,children:(0,X.jsxs)(`span`,{"aria-hidden":`true`,className:H.mobileQrIcon,children:[(0,X.jsx)(`span`,{}),(0,X.jsx)(`span`,{}),(0,X.jsx)(`span`,{}),(0,X.jsx)(`span`,{})]})}),(0,X.jsx)(x,{})]}),w?(0,X.jsx)(`div`,{className:H.mobileQrOverlay,children:(0,X.jsxs)(`div`,{ref:he,className:H.mobileQrDialog,role:`dialog`,"aria-modal":`true`,"aria-labelledby":`mobile-qr-title`,children:[(0,X.jsxs)(`div`,{className:H.mobileQrHeader,children:[(0,X.jsx)(`h2`,{id:`mobile-qr-title`,children:`Open on mobile`}),(0,X.jsx)(`button`,{ref:ge,type:`button`,className:H.mobileQrClose,onClick:()=>E(null),"aria-label":`Close mobile QR code`,children:`x`})]}),(0,X.jsx)(`div`,{className:H.mobileQrImage,children:(0,X.jsx)(`img`,{src:`data:image/svg+xml;charset=utf-8,${encodeURIComponent(w.qrSvg)}`,alt:`Mobile session QR code`})}),(0,X.jsx)(`a`,{className:H.mobileQrLink,href:w.launchUrl,children:`Open link`})]})}):null,Ot?(0,X.jsx)(`div`,{className:H.emptyState,children:(0,X.jsx)(`h1`,{className:H.greeting,children:rt})}):(0,X.jsx)(`div`,{className:H.messageArea,ref:de,children:(0,X.jsx)(`div`,{className:H.messageList,ref:fe,children:et.map(t=>y===t.id&&t.role!==`thinking`?(0,X.jsx)(`div`,{className:H.messageBlock,children:(0,X.jsx)(tn,{initial:t.rawContent??t.content,onSave:e=>void st(t,e),onCancel:()=>b(null)})},t.id):(0,X.jsx)(Zt,{message:t,token:e.token,isStreaming:t.id===K.streamingMsgId,onCopy:Oe,onEdit:Tt,onRegenerate:ct,onRate:ut,ratingBusy:it.isPending&&it.variables?.message.id===t.id,skillInvocationTargets:Ue,onApprovalAction:lt,approvalBusy:S,branchInfo:at.get(t.id)??null,onBranchNav:Et},t.id))})}),!Ot&&!pe?(0,X.jsxs)(`button`,{type:`button`,className:H.jumpToLatest,onClick:L,"aria-label":`Jump to latest message`,children:[(0,X.jsx)(`span`,{"aria-hidden":`true`,children:`↓`}),(0,X.jsx)(`span`,{children:`Latest`})]}):null,p?(0,X.jsx)(`div`,{className:`${H.errorBanner} ${g?H.errorBannerExiting:``}`,children:p}):null,(0,X.jsx)(bt,{isStreaming:K.isStreaming,onSend:pt,onStop:()=>void K.stopRequest(),onUploadFiles:dt,token:e.token,agents:He,selectedAgentId:nt,onAgentSwitch:e=>void _t(e),models:Ge,selectedModelId:j,onModelSwitch:e=>void vt(e),initialValue:o})]}),(0,X.jsx)(v,{open:F!==null,onOpenChange:e=>{!e&&!Z.isPending&&ae(null)},children:(0,X.jsxs)(ne,{size:`sm`,role:`alertdialog`,preventCloseOnOutsideClick:Z.isPending,children:[(0,X.jsxs)(c,{children:[(0,X.jsx)(se,{children:`Delete session?`}),(0,X.jsx)(A,{children:`This permanently removes the conversation and associated session records.`})]}),(0,X.jsxs)(T,{children:[(0,X.jsx)(re,{className:`ghost-button`,disabled:Z.isPending,children:`Cancel`}),(0,X.jsx)(`button`,{type:`button`,className:`danger-button`,disabled:Z.isPending,onClick:Q,children:Z.isPending?`Deleting...`:`Delete`})]})]})})]})})}export{Tn as ChatPage};
|