@hybridaione/hybridclaw 0.25.3 → 0.25.4

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 (56) hide show
  1. package/CHANGELOG.md +37 -4
  2. package/README.md +3 -3
  3. package/console/dist/assets/chat-BrrZRNk9.js +4 -0
  4. package/console/dist/assets/{index-DN3T1L-r.js → index-CztnZJx2.js} +37 -37
  5. package/console/dist/assets/index-Ds1CHt-W.css +1 -0
  6. package/console/dist/assets/{terminal-Dwbnwiir.js → terminal-BZHXNlJH.js} +1 -1
  7. package/console/dist/index.html +2 -2
  8. package/console/package.json +1 -1
  9. package/container/npm-shrinkwrap.json +2 -2
  10. package/container/package-lock.json +2 -2
  11. package/container/package.json +1 -1
  12. package/dist/a2a/runtime.js +2 -2
  13. package/dist/a2a/runtime.js.map +1 -1
  14. package/dist/agents/team-structure-revisions.d.ts.map +1 -1
  15. package/dist/agents/team-structure-revisions.js +4 -4
  16. package/dist/agents/team-structure-revisions.js.map +1 -1
  17. package/dist/config/runtime-config-revisions.d.ts +1 -0
  18. package/dist/config/runtime-config-revisions.d.ts.map +1 -1
  19. package/dist/config/runtime-config-revisions.js +17 -13
  20. package/dist/config/runtime-config-revisions.js.map +1 -1
  21. package/dist/gateway/agent-addressing.d.ts +6 -0
  22. package/dist/gateway/agent-addressing.d.ts.map +1 -1
  23. package/dist/gateway/agent-addressing.js +28 -0
  24. package/dist/gateway/agent-addressing.js.map +1 -1
  25. package/dist/gateway/gateway-chat-service.d.ts.map +1 -1
  26. package/dist/gateway/gateway-chat-service.js +61 -0
  27. package/dist/gateway/gateway-chat-service.js.map +1 -1
  28. package/dist/gateway/gateway-http-server.d.ts.map +1 -1
  29. package/dist/gateway/gateway-http-server.js +61 -8
  30. package/dist/gateway/gateway-http-server.js.map +1 -1
  31. package/dist/gateway/gateway-service.d.ts +3 -3
  32. package/dist/gateway/gateway-service.d.ts.map +1 -1
  33. package/dist/gateway/gateway-service.js +167 -13
  34. package/dist/gateway/gateway-service.js.map +1 -1
  35. package/dist/gateway/gateway-tunnel-service.d.ts +4 -1
  36. package/dist/gateway/gateway-tunnel-service.d.ts.map +1 -1
  37. package/dist/gateway/gateway-tunnel-service.js +148 -7
  38. package/dist/gateway/gateway-tunnel-service.js.map +1 -1
  39. package/dist/gateway/gateway-types.d.ts +18 -1
  40. package/dist/gateway/gateway-types.d.ts.map +1 -1
  41. package/dist/gateway/gateway-types.js.map +1 -1
  42. package/dist/security/admin-rbac.d.ts +13 -13
  43. package/dist/security/admin-rbac.d.ts.map +1 -1
  44. package/dist/security/admin-rbac.js +18 -0
  45. package/dist/security/admin-rbac.js.map +1 -1
  46. package/docs/content/README.md +4 -0
  47. package/docs/content/getting-started/installation.md +3 -2
  48. package/docs/index.html +9 -9
  49. package/npm-shrinkwrap.json +5 -5
  50. package/package.json +1 -1
  51. package/console/dist/assets/chat-CDXd1yTl.js +0 -4
  52. package/console/dist/assets/index-DHzWClL-.css +0 -1
  53. package/dist/utils/hash.d.ts +0 -2
  54. package/dist/utils/hash.d.ts.map +0 -1
  55. package/dist/utils/hash.js +0 -5
  56. package/dist/utils/hash.js.map +0 -1
package/CHANGELOG.md CHANGED
@@ -2,6 +2,34 @@
2
2
 
3
3
  ## Unreleased
4
4
 
5
+ ## [0.25.4](https://github.com/HybridAIOne/hybridclaw/tree/v0.25.4) - 2026-06-22
6
+
7
+ ### Added
8
+
9
+ - **Remote agents in chat**: Trusted A2A peer agents now appear in the chat
10
+ agent selector, grouped by remote instance. Selecting a remote agent inserts
11
+ its canonical address and sends the message through the A2A delivery path.
12
+ - **Admin tunnel controls**: The admin dashboard now exposes public tunnel
13
+ configuration, current tunnel health, and managed tunnel start, reconnect,
14
+ and stop actions with validation, pending states, errors, and audit events.
15
+
16
+ ### Changed
17
+
18
+ - **Console loading state**: Replaced the initial auth-check card with a
19
+ branded, accessible HybridClaw loading screen and reduced-motion-aware
20
+ progress treatment.
21
+
22
+ ### Fixed
23
+
24
+ - **Console browser titles**: Chat and Agents routes now receive route-specific
25
+ page titles from both the gateway-served HTML and client-side navigation,
26
+ instead of showing the admin title outside admin pages.
27
+ - **Remote A2A delivery**: Queued remote A2A envelopes are canonicalized before
28
+ persistence and audit recording so sender and recipient ids stay normalized.
29
+ - **Remote selector and tunnel polish**: Remote agent groups use a server icon,
30
+ admin tunnel action buttons align and reflect start, stop, and reconnect
31
+ states consistently, and revision tokens for config/team changes are opaque.
32
+
5
33
  ## [0.25.3](https://github.com/HybridAIOne/hybridclaw/tree/v0.25.3) - 2026-06-22
6
34
 
7
35
  ### Added
@@ -26,13 +54,18 @@
26
54
  message) with explicit success signals, a troubleshooting block, and a command
27
55
  cheat sheet. Relocated the per-channel startup auto-connect conditions into the
28
56
  Channels overview.
29
- - **Apple desktop release**: README and docs point at the signed/notarized Apple
30
- Silicon DMG, and the desktop wrapper captures gateway startup logs, recent
31
- child output, spawn failures, and early exits so packaged app launch failures
32
- are diagnosable.
57
+ - **Apple desktop diagnostics**: The desktop wrapper captures gateway startup
58
+ logs, recent child output, spawn failures, and early exits so packaged app
59
+ launch failures are diagnosable.
60
+ - **Dependency maintenance**: Remediated npm audit dependencies, upgraded
61
+ Nodemailer to 9.0.0, refreshed dependency policy baselines, and clarified the
62
+ dependency lockfile update workflow for future maintenance.
33
63
 
34
64
  ### Fixed
35
65
 
66
+ - **A2A Agent Card public URL**: The A2A Agent Card advertises the configured
67
+ public deployment URL when present, and invalid `deployment.public_url` values
68
+ fail closed instead of falling back to an internal request origin.
36
69
  - **MCP server startup isolation**: A single MCP server that fails to connect or
37
70
  disconnect is logged and skipped instead of aborting the whole chat turn, and
38
71
  unchanged failed server configs are not retried every turn.
package/README.md CHANGED
@@ -71,8 +71,8 @@ Fastest managed launch: [HybridClaw on HybridAI Cloud](https://hybridclaw.io).
71
71
 
72
72
  Apple Desktop App for macOS:
73
73
 
74
- - Download the signed and notarized Apple Silicon DMG:
75
- [HybridClaw-0.25.3-arm64.dmg](https://github.com/HybridAIOne/hybridclaw/releases/download/v0.25.3/HybridClaw-0.25.3-arm64.dmg)
74
+ - Download the signed and notarized Apple Silicon DMG from
75
+ [GitHub Releases](https://github.com/HybridAIOne/hybridclaw/releases/latest).
76
76
  - Open the DMG, drag `HybridClaw.app` into `/Applications`, and launch it.
77
77
  - The desktop app starts the local gateway and opens the chat, agents, and
78
78
  admin surfaces in a native macOS window.
@@ -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.3](https://github.com/HybridAIOne/hybridclaw/releases/tag/v0.25.3).
231
+ Latest release: [v0.25.4](https://github.com/HybridAIOne/hybridclaw/releases/tag/v0.25.4).
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 ee,R as T,S as te,T as ne,U as E,V as re,W as D,X as ie,Y as O,Z as ae,_ as k,a as A,at as oe,b as j,bt as se,c as ce,d as le,dt as ue,et as de,f as M,ft as fe,g as pe,gt as N,h as me,ht as P,i as he,it as ge,k as _e,l as F,lt as I,m as ve,mt as ye,n as be,nt as xe,o as L,ot as Se,p as Ce,pt as we,q as R,r as z,rt as B,s as V,st as Te,t as Ee,tt as H,u as De,ut as Oe,w as U,x as ke,y as Ae,yt as je,z as Me}from"./index-CztnZJx2.js";var W=e(t(),1);function Ne(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),N(`/api/chat/recent?${o.toString()}`,{token:e})}function Pe(e,t,n=80,r){let i=new URLSearchParams({sessionId:t,limit:String(n)});return r&&i.set(`userId`,r),N(`/api/history?${i.toString()}`,{token:e})}function Fe(e,t){return N(`/api/chat/context?${new URLSearchParams({sessionId:t}).toString()}`,{token:e})}function Ie(e,t){return N(t?`/api/chat/commands?q=${encodeURIComponent(t)}`:`/api/chat/commands`,{token:e})}function Le(e,t){return N(`/api/chat/mobile-qr`,{token:e,method:`POST`,body:t})}function Re(e,t,n){return N(`/api/chat/branch`,{token:e,method:`POST`,body:{sessionId:t,beforeMessageId:n}})}function ze(e,t){return N(`/api/chat/rating`,{token:e,method:`POST`,body:t})}function Be(e,t,n,r){return N(`/api/command`,{token:e,method:`POST`,body:I({sessionId:t,args:r,userId:n,username:`web`})})}function Ve(e,t){return N(`/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 He(e){return`/api/artifact?${new URLSearchParams({path:e}).toString()}`}function Ue(e){return e}async function G(e,t){let n=await fetch(t,{headers:P(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&&ue(t),Error(t)}return n.blob()}async function K(e,t){return G(e,He(t))}function We(e,t){return G(e,Ue(t))}var Ge={maxRecentSessions:10,maxSearchResults:50};function Ke(e,t){let[n,r]=(0,W.useState)(e);return(0,W.useEffect)(()=>{let n=window.setTimeout(()=>{r(e)},t);return()=>{window.clearTimeout(n)}},[e,t]),n}var q=`[A-Za-z0-9._-]+(?:@[A-Za-z0-9._-]+@[A-Za-z0-9._-]+)?`,qe=String.raw`(?=$|[\s:.,!?;)\]}])`;RegExp(`^@(${q})${qe}`,`u`);var Je=RegExp(`@(${q})${qe}`,`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:U(),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){return Ze(await Pe(e,t,80,n),t)}var X=i();function $e(e){let t=Te(),n=g(),r=e.searchQuery.trim().length>0;return(0,W.useEffect)(()=>{n.openMobile&&e.onRefreshRecent?.()},[e.onRefreshRecent,n.openMobile]),(0,X.jsxs)(_,{side:`left`,collapsible:`icon`,children:[(0,X.jsxs)(Me,{children:[(0,X.jsxs)(`div`,{className:E.headerRow,children:[(0,X.jsx)(S,{}),(0,X.jsx)(re,{className:E.sidebarToggle})]}),(0,X.jsxs)(`button`,{type:`button`,className:z.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:z.sidebarSearchWrap,children:(0,X.jsx)(`input`,{type:`search`,className:z.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)(T,{children:(0,X.jsxs)(`div`,{className:E.footerBlock,children:[(0,X.jsx)(w,{version:t.gatewayStatus?.version}),(0,X.jsx)(D,{labelClassName:E.themeToggleLabel})]})})]})}function et(e){return(0,X.jsxs)(`div`,{className:z.chatSidebarContent,children:[(0,X.jsxs)(`div`,{className:z.sidebarListHeader,children:[(0,X.jsx)(`div`,{className:z.sidebarLabel,children:e.isSearching?`Search Results`:`Recent Chats`}),(0,X.jsx)(`div`,{className:z.sidebarScopeToggle,children:[`user`,`all`].map(t=>(0,X.jsx)(`button`,{type:`button`,className:H(z.sidebarScopeButton,e.recentScope===t&&z.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:z.sidebarStatus,children:`Searching...`}):e.sessions.length===0?(0,X.jsx)(`div`,{className:z.sidebarStatus,children:e.isSearching?`No matching conversations.`:`No recent chats yet.`}):(0,X.jsx)(`ul`,{className:z.sessionList,"aria-live":`polite`,children:e.sessions.map(t=>(0,X.jsx)(`li`,{children:(0,X.jsxs)(`div`,{className:z.sessionItemRow,children:[(0,X.jsxs)(`button`,{type:`button`,className:H(z.sessionItem,t.sessionId===e.activeSessionId&&z.sessionItemActive,t.sessionId===e.activeSessionId&&e.isPending&&z.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:z.sessionTitle,children:t.title||`Untitled`}),t.searchSnippet?(0,X.jsx)(`span`,{className:z.sessionSnippet,children:t.searchSnippet}):null,(0,X.jsx)(`span`,{className:z.sessionTime,children:C(t.lastActive)})]}),(0,X.jsx)(`button`,{type:`button`,className:z.sessionDeleteButton,"aria-label":`Delete ${t.title||`Untitled`} session`,title:`Delete session`,disabled:e.deleteDisabled,onClick:()=>e.onRequestDeleteSession(t),children:(0,X.jsx)(xe,{className:z.sessionDeleteIcon})})]})},t.sessionId))})]})}var Z=new Map;function tt(e,t){return`${e}\u0000${t}`}function nt(e,t){let n=tt(e,t),r=Z.get(n);return r||(r={objectUrl:null,loading:!1,promise:null,listeners:new Set},Z.set(n,r)),r}function rt(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=nt(r,n);return i.objectUrl?Promise.resolve(i.objectUrl):i.promise?i.promise:(i.loading=!0,i.promise=We(r,n).then(e=>{let t=URL.createObjectURL(e);return i.objectUrl=t,i.loading=!1,i.promise=null,rt(i),t}).catch(()=>(i.objectUrl=null,i.loading=!1,i.promise=null,rt(i),null)),rt(i),i.promise)}function at(e){let t=e.token.trim(),n=e.imageUrl?.trim()??``,[r,i]=(0,W.useState)(()=>{if(!n)return{objectUrl:null,loading:!1};let e=nt(t,n);return{objectUrl:e.objectUrl,loading:e.loading}});return(0,W.useEffect)(()=>{if(!n){i({objectUrl:null,loading:!1});return}let e=nt(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,W.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)(he,{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)(M,{className:z.composerPill,"aria-label":`Switch agent`,disabled:e.disabled,children:[(0,X.jsx)(Ce,{children:n}),(0,X.jsx)(ce,{className:z.composerPillChevron,children:(0,X.jsx)(ot,{})})]}),(0,X.jsxs)(A,{className:z.agentSelectPopup,children:[a?(0,X.jsxs)(L,{children:[(0,X.jsx)(V,{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)(L,{children:[(0,X.jsxs)(V,{className:z.remoteAgentGroupLabel,children:[(0,X.jsx)(oe,{"aria-hidden":`true`,className:z.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)(F,{value:e.agent.id,textValue:t,className:z.agentSelectItem,children:[(0,X.jsx)(lt,{agent:e.agent,token:e.token}),n?(0,X.jsxs)(De,{children:[(0,X.jsx)(`span`,{className:z.agentSelectItemText,children:t}),(0,X.jsx)(le,{children:e.agent.id})]}):(0,X.jsx)(`span`,{className:z.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:z.agentSelectAvatar,src:n.objectUrl,alt:``}):t?(0,X.jsx)(`span`,{className:z.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,W.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)(R,{side:`top`,focusOnOpen:`none`,closeOnEscape:!1,closeOnOutsideClick:!0,sideOffset:4,className:z.slashSuggestions,children:(0,X.jsxs)(ve,{className:z.slashSuggestionsScroll,children:[(0,X.jsx)(k,{id:a,role:`listbox`,"aria-label":d,className:z.slashSuggestionsList,children:e===`list`?n.map((e,n)=>(0,X.jsxs)(`div`,{id:dt(a,n),className:H(z.suggestionItem,t===`agent`&&z.suggestionItemAgent,n===r&&z.suggestionItemActive,(e.depth??1)>=2&&z.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:z.suggestionText,children:[(0,X.jsx)(`span`,{className:z.suggestionLabel,children:ht(e.label,l)}),e.description?(0,X.jsx)(`span`,{className:z.suggestionDesc,children:e.description}):null]})]},e.id)):(0,X.jsx)(`div`,{className:z.suggestionEmpty,role:`status`,children:f})}),(0,X.jsx)(me,{children:(0,X.jsx)(pe,{})})]})})}function pt(e){let t=e.item.imageUrl?.trim(),n=at({token:e.token??``,imageUrl:t});return n.objectUrl?(0,X.jsx)(`img`,{className:z.suggestionAvatar,src:n.objectUrl,alt:``}):t?(0,X.jsx)(`span`,{className:z.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?z.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:z.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(`@(${q})(?=$|[\\s:])`,`gu`),vt=RegExp(`^@${q}(?=$|[\\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,W.useRef)(null),n=(0,W.useRef)(null),r=(0,W.useRef)(null),[i,a]=(0,W.useState)([]),[o,s]=(0,W.useState)(0),[c,l]=(0,W.useState)([]),[u,d]=(0,W.useState)(`slash`),[f,p]=(0,W.useState)(0),[m,g]=(0,W.useState)(`closed`),[_,v]=(0,W.useState)(``),[b,x]=(0,W.useState)(``),S=(0,W.useRef)(null),C=(0,W.useRef)(null),w=(0,W.useRef)(0),ee=(0,W.useRef)(null),T=(0,W.useId)(),ne=m!==`closed`,E=m===`closed`?``:u===`agent`?m===`list`?`${_e(c.length,`agent`)} available`:`No agents match @${_}`:m===`list`?`${_e(c.length,`command`)} available`:`No commands match /${_}`;(0,W.useEffect)(()=>()=>{C.current&&clearTimeout(C.current),w.current+=1},[]),(0,W.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,W.useRef)(e.isStreaming);(0,W.useEffect)(()=>{re.current&&!e.isStreaming&&t.current?.focus(),re.current=e.isStreaming},[e.isStreaming]);let D=(0,W.useCallback)(()=>{let e=t.current;e&&(e.style.height=`36px`,e.style.height=`${Math.max(36,Math.min(e.scrollHeight,180))}px`)},[]);(0,W.useEffect)(()=>{let n=e.initialValue?.trim()||``;if(S.current===n||(S.current=n,!n))return;let r=t.current;r&&(r.value=n,r.setSelectionRange(n.length,n.length),x(n),g(`closed`),w.current+=1,D(),r.focus())},[e.initialValue,D]);let ie=(0,W.useCallback)(()=>{C.current&&=(clearTimeout(C.current),null),w.current+=1},[]),O=(0,W.useCallback)(()=>{ie(),g(`closed`)},[ie]),ae=(0,W.useCallback)(async t=>{let n=w.current;try{let r=await Ie(e.token,t||void 0);if(n!==w.current)return;let i=r.commands??[];l(i),p(0),v(t),i.length>0?g(`list`):g(t===``?`closed`:`empty`)}catch{if(n!==w.current)return;l([]),g(`closed`)}},[e.token]),k=(0,W.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,W.useEffect)(()=>{for(let t of e.agents??[])it(e.token,t.imageUrl)},[e.agents,e.token]);let A=()=>{D();let n=t.current;if(!n)return;x(n.value);let r=n.selectionStart??n.value.length,i=ut(n.value,r);if(i){let e=i.query.trim();d(`slash`),ie(),C.current=setTimeout(()=>{ae(e)},150);return}let a=yt(n.value,r);if(a&&(e.agents?.length??0)>0){ie();let e=k(a.query);l(e),d(`agent`),p(0),v(a.query),g(e.length>0?`list`:a.query===``?`closed`:`empty`)}else O()},oe=e=>{let n=t.current;if(!n)return;let r=n.value,i=n.selectionStart??r.length,a=e.insertText.replace(/\s+$/,``);if(u===`agent`){let e=yt(r,i);if(e){let t=r.slice(0,e.tokenStart),o=r.slice(i),s=o.startsWith(` `)?a:`${a} `;n.value=t+s+o;let c=t.length+s.length;n.setSelectionRange(c,c)}else n.value=`${a} `,n.setSelectionRange(n.value.length,n.value.length);x(n.value),O(),D(),n.focus();return}let o=ut(r,i);if(o){let e=r.slice(0,o.tokenStart),t=r.slice(i),s=t.startsWith(` `)?a:`${a} `;n.value=e+s+t;let c=e.length+s.length;n.setSelectionRange(c,c)}else n.value=`${a} `,n.setSelectionRange(n.value.length,n.value.length);x(n.value),O(),D(),n.focus()},j=(0,W.useCallback)(e=>{let n=t.current;if(!n)return;let r=`@${e}`,i=n.value,a=vt.exec(i);i.trim()?a?n.value=`${r} ${i.slice(a[0].length).trimStart()}`:n.value=`${r} ${i.trimStart()}`:n.value=`${r} `,n.setSelectionRange(n.value.length,n.value.length),x(n.value),O(),D(),n.focus()},[O,D]),se=()=>{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(``),a([]),O(),D())},ce=()=>{let e=t.current,n=ee.current;!e||!n||(n.scrollTop=e.scrollTop,n.scrollLeft=e.scrollLeft)},le=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=ne;if(O(),t){e.preventDefault();return}}e.key===`Enter`&&!e.shiftKey&&(e.preventDefault(),se())}},ue=e=>{let t=te(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))}},M=e=>{let t=Array.from(e.target.files??[]);t.length>0&&de(t),e.target.value=``},fe=e=>{a(t=>t.filter((t,n)=>n!==e))},pe=e.agents??[],N=(0,W.useMemo)(()=>new Map(pe.map(e=>[e.id,e])),[pe]),me=e.selectedAgentId??``,P=e.models??[],he=e.selectedModelId??``;return(0,X.jsxs)(`div`,{className:z.composerWrapper,ref:r,children:[(0,X.jsxs)(h,{open:ne,onOpenChange:e=>{e||O()},children:[(0,X.jsxs)(`div`,{className:z.composer,children:[i.length>0||o>0?(0,X.jsxs)(`div`,{className:z.pendingMediaRow,children:[i.map((e,t)=>(0,X.jsxs)(`span`,{className:z.mediaChip,children:[(0,X.jsx)(`span`,{className:z.mediaChipName,children:e.filename}),(0,X.jsx)(`button`,{type:`button`,className:z.mediaChipRemove,onClick:()=>fe(t),children:`×`})]},e.path)),o>0?(0,X.jsx)(`span`,{className:z.mediaChip,children:`Uploading…`}):null]}):null,(0,X.jsxs)(y,{className:z.composerInputWrap,children:[b?(0,X.jsx)(`div`,{ref:ee,className:z.composerInputOverlay,"aria-hidden":`true`,children:(0,X.jsx)(xt,{value:b,agents:N,token:e.token})}):null,(0,X.jsx)(`textarea`,{ref:t,className:H(z.composerInput,b&&z.composerInputHasOverlay),rows:1,placeholder:`Message HybridClaw`,disabled:e.isStreaming,onInput:A,onKeyDown:le,onPaste:ue,onScroll:ce,"aria-label":`Message input`,role:`combobox`,"aria-autocomplete":`list`,"aria-haspopup":`listbox`,"aria-controls":T,"aria-expanded":ne,"aria-activedescendant":m===`list`&&c.length>0?dt(T,f):void 0})]}),(0,X.jsxs)(`div`,{className:z.composerActions,children:[(0,X.jsxs)(`div`,{className:z.composerLeftActions,children:[(0,X.jsx)(`button`,{type:`button`,className:z.attachButton,onClick:()=>n.current?.click(),"aria-label":`Attach files`,children:`+`}),(0,X.jsx)(st,{agents:pe,selectedAgentId:me,token:e.token,disabled:e.isStreaming,onSwitch:t=>{if(t.source?.type===`remote`){j(t.id);return}e.onAgentSwitch?.(t.id)}}),(0,X.jsx)(be,{models:P,selectedModelId:he,disabled:e.isStreaming,onSwitch:t=>e.onModelSwitch?.(t)})]}),(0,X.jsx)(`button`,{type:`button`,className:H(z.sendButton,e.isStreaming&&z.stopping),onClick:se,"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:M})]})]}),m===`closed`?null:(0,X.jsx)(ft,{mode:m,kind:u,suggestions:c,activeIdx:f,query:_,listboxId:T,token:e.token,onSelect:oe,onActiveChange:p})]}),(0,X.jsx)(`div`,{className:z.slashLiveRegion,"aria-live":`polite`,"aria-atomic":`true`,children:E})]})}function xt(e){let t=[],n=0,r=0;for(let i of e.value.matchAll(_t)){let a=i[0],o=i[1]??``,s=i.index??0,c=e.agents.get(o);c&&(s>n&&t.push(e.value.slice(n,s)),t.push((0,X.jsx)(St,{mention:a,imageUrl:c.imageUrl??null,token:e.token},`mention-${r++}`)),n=s+a.length)}return n<e.value.length&&t.push(e.value.slice(n)),t.length>0?t:e.value}function St(e){let t=at({token:e.token,imageUrl:e.imageUrl});return(0,X.jsxs)(`span`,{className:z.composerMentionPill,children:[t.objectUrl?(0,X.jsx)(`img`,{className:z.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:()=>Fe(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:H(Q.ringFill,s===`warn`&&Q.ringFillWarn,s===`danger`&&Q.ringFillDanger,s===`nominal`&&Q.ringFillNominal),strokeDasharray:wt,strokeDashoffset:l})]}),(0,X.jsx)(`span`,{className:H(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:H(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,W.useMemo)(()=>Ft(t),[t]),r=(0,W.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:z.approvalCard,children:[(0,X.jsxs)(`div`,{className:z.approvalHeader,children:[a?(0,X.jsx)(`span`,{className:z.approvalTier,children:a}):null,(0,X.jsx)(`span`,{className:z.approvalTitle,children:`Confirmation required`})]}),(0,X.jsx)(`p`,{className:z.approvalIntro,children:r}),n.length>0?(0,X.jsx)(`dl`,{className:z.approvalDetails,children:n.map(e=>(0,X.jsxs)(`div`,{className:z.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:z.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:z.approvalTrustActions,children:i.map(t=>(0,X.jsx)(f,{variant:`outline`,size:`sm`,className:z.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,W.useState)(e),a=(0,W.useRef)(e),o=(0,W.useRef)(null);a.current=e,(0,W.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,W.startTransition)(()=>{i(a.current)})},Rt))},[e,t,n,r]),(0,W.useEffect)(()=>()=>{o.current!==null&&window.clearTimeout(o.current)},[]);let s=t?n?r:e:``;return(0,W.useMemo)(()=>t?Ee(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(z.codeBlockLabeled);let n=document.createElement(`span`);n.className=z.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=z.codeCopyButton,n.innerHTML=Bt;let r=e=>{n.setAttribute(`aria-label`,e),n.title=e};r(`Copy code`);let i=null;n.addEventListener(`click`,()=>{ke((e.querySelector(`code`)??e).textContent??``).then(e=>{e&&(n.innerHTML=Vt,n.classList.add(z.codeCopyButtonDone),r(`Copied`),i!==null&&window.clearTimeout(i),i=window.setTimeout(()=>{n.innerHTML=Bt,n.classList.remove(z.codeCopyButtonDone),r(`Copy code`)},1500))})}),e.appendChild(n)}function qt(){let e=(0,W.useRef)(null);return(0,W.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,W.useRef)(null),[i,a]=(0,W.useState)(null),[o,s]=(0,W.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,W.useEffect)(()=>{let e=r.current;if(r.current=null,e&&URL.revokeObjectURL(e),a(null),!p||!t.path)return;let i=!1;return K(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 K(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:H(z.artifactCard,i&&z.artifactCardWithPreview),children:[(0,X.jsxs)(`div`,{className:z.artifactHeader,children:[(0,X.jsx)(`span`,{className:z.artifactFilename,children:l}),t.type?(0,X.jsx)(`span`,{className:z.artifactBadge,children:t.type}):null,t.path?(0,X.jsx)(`button`,{type:`button`,className:z.artifactDownload,disabled:o,onClick:()=>{h()},children:m}):null]}),u&&i?(0,X.jsx)(`div`,{className:z.artifactPreview,children:(0,X.jsx)(`img`,{src:i,alt:l})}):null,f&&i?(0,X.jsx)(`div`,{className:H(z.artifactPreview,z.artifactPdfPreview),children:(0,X.jsx)(`iframe`,{src:i,title:`${l} preview`,sandbox:``})}):null,d&&i?(0,X.jsx)(`div`,{className:H(z.artifactPreview,z.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,W.useRef)(null),[n,r]=(0,W.useState)(null);return(0,W.useEffect)(()=>{let n=t.current;if(t.current=null,n&&URL.revokeObjectURL(n),r(null),!e.imageUrl)return;let i=!1;return We(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,W.memo)(function(e){let{message:t,token:n}=e,[r,i]=(0,W.useState)(!1),a=()=>{e.onCopy(t.rawContent??t.content),i(!0),setTimeout(()=>i(!1),900)},o=(0,W.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:z.thinking,role:`status`,"aria-label":`Assistant is thinking`,children:[(0,X.jsx)(`span`,{className:z.thinkingDot}),(0,X.jsx)(`span`,{className:z.thinkingDot}),(0,X.jsx)(`span`,{className:z.thinkingDot})]});let g=t.role===`user`,_=t.role===`assistant`,v=g||t.content.trim().length>0||o.length===0||s,y=H(z.messageBlock,g&&z.messageBlockUser,(_||t.role===`system`||t.role===`command`||s)&&z.messageBlockAssistant),b=H(z.bubble,g&&z.bubbleUser,(_||s)&&z.bubbleAssistant,s&&z.bubbleApproval,t.role===`system`&&z.bubbleSystem,t.role===`command`&&z.bubbleCommand);return(0,X.jsxs)(`div`,{className:y,children:[_?(0,X.jsxs)(`div`,{className:z.agentLabel,children:[h?(0,X.jsx)(`img`,{className:z.agentAvatar,src:h,alt:``}):(0,X.jsx)(`span`,{className:z.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:z.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:z.messageActions,children:[_&&t.replayRequest?(0,X.jsx)(f,{variant:`ghost`,size:`icon`,className:z.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:H(z.actionButton,t.responseRating===`up`&&z.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)(B,{width:`13`,height:`13`,filled:t.responseRating===`up`})}),(0,X.jsx)(f,{variant:`ghost`,size:`icon`,className:H(z.actionButton,t.responseRating===`down`&&z.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)(ge,{width:`13`,height:`13`,filled:t.responseRating===`down`})})]}):null,(0,X.jsx)(f,{variant:`ghost`,size:`icon`,className:H(z.actionButton,r&&z.actionButtonSuccess),title:`Copy`,"aria-label":r?`Copied`:`Copy message`,onClick:a,children:r?`✓`:`⧉`}),g?(0,X.jsx)(f,{variant:`ghost`,size:`icon`,className:z.actionButton,title:`Edit`,"aria-label":`Edit message`,onClick:()=>e.onEdit(t),children:`✎`}):null,e.branchInfo&&e.branchInfo.total>1?(0,X.jsxs)(`div`,{className:z.branchSwitcher,children:[(0,X.jsx)(f,{variant:`ghost`,size:`icon`,className:z.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:z.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:z.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:z.userAgentMentionPill,children:[t?(0,X.jsx)(`img`,{className:z.userAgentMentionAvatar,src:t,alt:``}):null,(0,X.jsx)(`span`,{children:e.mention})]})}function tn(e){let[t,n]=(0,W.useState)(e.initial);return(0,X.jsxs)(X.Fragment,{children:[(0,X.jsx)(`textarea`,{className:z.editArea,value:t,onChange:e=>n(e.target.value),"aria-label":`Edit message`,autoFocus:!0}),(0,X.jsxs)(`div`,{className:z.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,W.useRef)(null),r=t??n.current??``,i=(0,W.useRef)(r);i.current=r,(0,W.useEffect)(()=>{t&&(n.current=null)},[t]),(0,W.useEffect)(()=>{r&&p(r)},[r]);let a=(0,W.useCallback)(()=>i.current,[]),c=(0,W.useCallback)((t,n)=>e({to:`/chat/$sessionId`,params:{sessionId:t},...n}),[e]);return{sessionId:r,getSessionId:a,navigateToSession:c,switchToSession:(0,W.useCallback)((e,t)=>(n.current=e,i.current=e,c(e,t)),[c]),startFreshChat:(0,W.useCallback)(()=>{n.current=null,e({to:`/chat`})},[e]),ensureSessionForSend:(0,W.useCallback)(()=>{if(i.current)return;let e=d();n.current=e,i.current=e,c(e,{replace:!0})},[c]),handleSessionIdCorrection:(0,W.useCallback)(e=>{e!==i.current&&c(e,{replace:!0})},[c])}}async function rn(e,t){let n=await fetch(e,{method:`POST`,headers:{...P(t.token,t.body),Accept:`application/x-ndjson`},body:JSON.stringify(t.body),signal:t.signal});n.ok||await je(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,W.useRef)(null),[p,m]=(0,W.useState)(!1),[h,g]=(0,W.useState)(null),[_,v]=(0,W.useState)(null),y=(0,W.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,W.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:U();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=U();_(e=>[...e,{id:x,role:`thinking`,content:``,sessionId:h}]);let S=U();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}]})},ee=()=>{C.renderFrame&&=(cancelAnimationFrame(C.renderFrame),0),w()},T=()=>{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,T()},onApproval:e=>{C.pendingApproval=e,C.messageRole=`approval`,C.assistantText.trim()||(C.assistantText=j(e)),T()}}});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),ee();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:U(),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,W.useCallback)(async()=>{let e=f.current;if(!(!e||e.stopping)){e.stopping=!0;try{await Be(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,W.useCallback)(()=>f.current!==null,[])}}var un=120,dn=220;function fn(){let e=(0,W.useRef)(null),t=(0,W.useRef)(null),n=(0,W.useRef)(null),r=(0,W.useRef)(0),[i,a]=(0,W.useState)(!0),o=(0,W.useRef)(!0),s=(0,W.useRef)(!1),c=(0,W.useCallback)(e=>{o.current!==e&&(o.current=e,a(e))},[]),l=(0,W.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,W.useCallback)(()=>{let t=e.current;!t||!o.current||t.scrollHeight<=t.clientHeight||l(t,t.scrollHeight)},[l]),d=(0,W.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,W.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,W.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,W.useCallback)(()=>{c(!0);let t=e.current;t&&l(t,t.scrollHeight)},[c,l]);return(0,W.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?`;function yn(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 bn(e,t,n=``,r=`user`){return[`chat-recent`,e,t,n,r]}function xn(e,t){return[`chat-recent`,e,t]}function Sn(e,t){return[`chat-context`,e,t]}function Cn(){let e=Te(),t=n(),i=(0,W.useRef)(ne()).current,o=(0,W.useMemo)(()=>new URLSearchParams(window.location.search).get(`prompt`)||``,[]),[s,d]=(0,W.useState)({message:``,version:0}),f=s.message,p=(0,W.useCallback)(e=>{d(t=>({message:typeof e==`function`?e(t.message):e,version:t.version+1}))},[]),[h,g]=(0,W.useState)(!1),[_,y]=(0,W.useState)(null),[b,S]=(0,W.useState)(!1),[C,w]=(0,W.useState)(null),[T,te]=(0,W.useState)(!1),[E,re]=(0,W.useState)(null),[D,k]=(0,W.useState)(``),[A,oe]=(0,W.useState)(`user`),[j,ce]=(0,W.useState)(null),[le,ue]=(0,W.useState)(``),M=Ke(le,160).trim(),{scrollRef:pe,contentRef:N,isPinned:me,jumpToBottom:P,resetToBottom:he}=fn(),ge=(0,W.useRef)(null),_e=(0,W.useRef)(null);(0,W.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:F,getSessionId:I,navigateToSession:ve,switchToSession:be,startFreshChat:xe,ensureSessionForSend:L,handleSessionIdCorrection:Ce}=nn(),R=(0,W.useCallback)(()=>{t.invalidateQueries({queryKey:xn(e.token,i)}),t.invalidateQueries({queryKey:Y(e.token,I()),refetchType:`none`})},[t,e.token,i,I]),B=Se(e),V=a({queryKey:[`app-status`,e.token],queryFn:()=>se(e.token),staleTime:1/0,enabled:B,initialData:e.status===`ready`&&e.gatewayStatus?e.gatewayStatus:void 0}),Ee=a({queryKey:[`agents-list`,e.token],queryFn:()=>fe(e.token),staleTime:3e4,enabled:B}),H=a({queryKey:[`models`,e.token],queryFn:()=>we(e.token),staleTime:3e4,enabled:B}),De=a({queryKey:[`skills`,e.token],queryFn:()=>ye(e.token),staleTime:6e4,retry:!1,enabled:B});(0,W.useEffect)(()=>{k(V.data?.defaultModel?.trim()??``)},[F,V.data?.defaultModel]),(0,W.useEffect)(()=>{V.error&&(console.error(`Failed to load gateway status for chat page`,V.error),p(`Failed to load the default agent. New chats will use main until gateway status loads.`))},[V.error,p]),(0,W.useEffect)(()=>{H.error&&(console.error(`Failed to load models list for chat page`,H.error),p(`Failed to load the model list. Model switching is unavailable.`))},[H.error,p]);let je=a({queryKey:bn(e.token,i,M,A),queryFn:()=>Ne(e.token,i,`web`,M?Ge.maxSearchResults:Ge.maxRecentSessions,M||void 0,A),staleTime:1e4,enabled:B}),Me=je.data?.sessions??[],Pe=(0,W.useMemo)(()=>(Ee.data??[]).map(e=>({id:e.id,name:e.name,imageUrl:e.imageUrl??null,emptyChatHeader:e.emptyChatHeader??null,source:e.source})),[Ee.data]),Ie=(0,W.useMemo)(()=>new Map((De.data?.skills??[]).filter(e=>e.userInvocable).map(e=>[e.name.toLowerCase(),e.name])),[De.data?.skills]),He=(0,W.useCallback)(e=>{let t=Ye(e);for(let e of t){let t=Pe.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},[Pe]),Ue=H.data?.models??mn,G=ln({token:e.token,userId:i,getSessionId:I,setError:p,refreshRecent:R,onSessionIdCorrection:Ce,onModelResolved:k,resolveAddressedAgentPresentation:He});(0,W.useEffect)(()=>{let e=s.message;if(g(!1),!e)return;let t=window.setTimeout(()=>{g(!0)},hn),n=window.setTimeout(()=>{p(``),g(!1)},5200);return()=>{window.clearTimeout(t),window.clearTimeout(n)}},[s,p]);let K=a({queryKey:Y(e.token,F),queryFn:()=>Qe(e.token,F,i),enabled:B&&!!F,staleTime:1/0}),We=a({queryKey:Sn(e.token,F),queryFn:()=>Fe(e.token,F),enabled:B&&!!F,staleTime:15e3,refetchOnWindowFocus:!1}),q=K.data?.messages??pn,qe=K.data?.bootstrapAutostart?.status===`starting`,Je=(0,W.useMemo)(()=>qe?[...q,{id:gn,role:`thinking`,content:``,sessionId:F}]:q,[qe,q,F]),J=K.data?.branchFamilies??Xe,Ze=E?.trim().toLowerCase()||K.data?.agentId?.trim().toLowerCase()||V.data?.defaultAgentId?.trim().toLowerCase()||`main`,et=Pe.find(e=>e.id.toLowerCase()===Ze)?.emptyChatHeader?.trim()||vn,Z=r({mutationFn:t=>Oe(e.token,t),onSuccess:n=>{if(!n.deleted){p(`Delete failed: session was not found.`);return}let r=n.sessionId;t.removeQueries({queryKey:Y(e.token,r)}),t.removeQueries({queryKey:Sn(e.token,r)}),t.invalidateQueries({queryKey:xn(e.token,i)}),t.invalidateQueries({queryKey:[`overview`],refetchType:`none`}),ce(null),r===I()&&xe()},onError:e=>{p(`Delete failed: ${l(e)}`)}}),tt=r({mutationFn:t=>{if(!t.message.messageId)throw Error(`This response cannot be rated right now.`);return ze(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=>{p(`Rating failed: ${l(e)}`)}});(0,W.useEffect)(()=>{let e=We.data?.snapshot?.model?.trim()??``;e&&k(e)},[We.data?.snapshot?.model]),(0,W.useEffect)(()=>{re(null)},[F]),(0,W.useEffect)(()=>{K.error&&p(l(K.error))},[K.error,p]),(0,W.useEffect)(()=>{if(K.data?.bootstrapAutostart?.status!==`starting`||K.isFetching)return;let e=window.setTimeout(()=>{K.refetch()},_n);return()=>window.clearTimeout(e)},[K.data?.bootstrapAutostart?.status,K.isFetching,K.refetch]),(0,W.useEffect)(()=>{if(!C)return;let e=document.body.style.overflow,t=document.activeElement;document.body.style.overflow=`hidden`,_e.current?.focus();let n=e=>{if(e.key===`Escape`){e.preventDefault(),w(null);return}if(e.key!==`Tab`)return;let t=Array.from(ge.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()}},[C]),(0,W.useEffect)(()=>{let e=K.data?.resolvedSessionId;!e||e===F||ve(e,{replace:!0})},[K.data?.resolvedSessionId,F,ve]);let nt=(0,W.useMemo)(()=>yn(q,J),[q,J]),rt=(0,W.useRef)(!1);(0,W.useEffect)(()=>{rt.current&&!G.isStreaming&&F&&t.invalidateQueries({queryKey:Sn(e.token,F)}),rt.current=G.isStreaming},[G.isStreaming,t,e.token,F]),(0,W.useEffect)(()=>{F&&he()},[F,he]);let it=(0,W.useCallback)(async(n,r)=>{if(!n.messageId||!n.sessionId){p(`This message cannot be edited right now.`);return}y(null);try{let a=await Re(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 be(a.sessionId),G.sendMessage(r,n.media??[])}catch(e){p(l(e))}},[e.token,t,p,be,G.sendMessage,i]),at=(0,W.useCallback)(e=>{e.replayRequest&&(P(),G.sendMessage(e.replayRequest.content,e.replayRequest.media,{hideUser:!0}))},[P,G.sendMessage]),ot=(0,W.useCallback)(async(e,t)=>{let n=Ae(e,t);if(n){S(!0);try{P(),await G.sendMessage(n,[],{hideUser:!0})}finally{S(!1)}}},[P,G.sendMessage]),st=(0,W.useCallback)((e,t)=>{tt.mutate({message:e,rating:t})},[tt]),ct=(0,W.useCallback)(async t=>{let n=await Promise.allSettled(t.map(t=>Ve(e.token,t))),r=[];for(let e of n)e.status===`fulfilled`&&e.value.media?r.push(e.value.media):e.status===`rejected`&&p(l(e.reason));return r},[e.token,p]),lt=(0,W.useCallback)(()=>{if(G.isActive()){p(`Stop the current run before starting a new chat.`);return}xe(),R()},[G.isActive,xe,R,p]),ut=(0,W.useCallback)((e,t)=>{L(),P(),G.sendMessage(e,t)},[L,P,G.sendMessage]),dt=(0,W.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:U(),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]),ft=(0,W.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]),pt=(0,W.useCallback)(async(n,r,a,o)=>{if(!r||/\s/.test(r))return;if(G.isActive()){p(o);return}L();let s=I();try{let o=await Be(e.token,s,i,[...n,r]),c=o.sessionId?.trim()||s,l=await ft(c);dt(c,o.text),c!==s&&await be(c,{replace:!0}),t.invalidateQueries({queryKey:Sn(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`}}),P()),R(),a(r)}catch(e){p(l(e))}},[dt,e.token,L,ft,I,P,t,R,p,G.isActive,be,i]),mt=(0,W.useCallback)(e=>pt([`agent`,`switch`],e,re,`Could not switch agent — stop the current run and try again.`),[pt]),ht=(0,W.useCallback)(e=>pt([`model`,`set`],e,k,`Could not switch model — stop the current run and try again.`),[pt]),gt=(0,W.useCallback)(e=>{if(G.isActive()){p(`Stop the current run before switching chats.`);return}ve(e)},[G.isActive,ve,p]),_t=(0,W.useCallback)(e=>G.activeSessionId===e?(p(`Stop the current run before deleting this chat.`),!1):!Z.isPending,[Z.isPending,G.activeSessionId,p]),vt=(0,W.useCallback)(e=>{_t(e.sessionId)&&ce(e)},[_t]),yt=(0,W.useCallback)(()=>{if(!j)throw Error(`Delete confirmation is missing a session.`);_t(j.sessionId)&&Z.mutate(j.sessionId)},[_t,Z,j]),xt=(0,W.useCallback)(n=>{n!==I()&&t.prefetchQuery({queryKey:Y(e.token,n),queryFn:()=>Qe(e.token,n,i),staleTime:3e4})},[t,e.token,I,i]),St=(0,W.useCallback)(()=>{t.invalidateQueries({queryKey:bn(e.token,i,M,A)})},[t,e.token,i,M,A]),Q=(0,W.useCallback)(async()=>{let t=I();if(!t){p(`Open or send a chat before creating a mobile QR code.`);return}te(!0);try{w(await Le(e.token,{userId:i,sessionId:t,baseUrl:window.location.origin}))}catch(e){p(l(e))}finally{te(!1)}},[e.token,I,i,p]),Ct=(0,W.useCallback)(e=>{y(e.id)},[]),wt=(0,W.useCallback)((e,t)=>{let n=e.branchKey;if(!n)return;let r=J.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&&gt(o.sessionId)},[J,gt]),$=Je.length===0,Tt=K.isFetching,Et={sessions:Me,activeSessionId:F,onNewChat:lt,onOpenSession:gt,onHoverSession:xt,onRequestDeleteSession:vt,deleteDisabled:Z.isPending,isPending:Tt,searchQuery:le,onSearchQueryChange:ue,recentScope:A,onRecentScopeChange:oe,isLoading:je.isFetching,onRefreshRecent:St};return(0,X.jsx)(u,{children:(0,X.jsxs)(`div`,{className:z.chatPage,"aria-busy":Tt,children:[(0,X.jsx)($e,{...Et}),(0,X.jsxs)(`div`,{className:z.chatMain,children:[(0,X.jsxs)(`div`,{className:z.chatTopbar,children:[(0,X.jsx)(m,{className:z.chatMobileTrigger}),(0,X.jsx)(Dt,{sessionId:F,token:e.token,enabled:B}),(0,X.jsx)(`button`,{type:`button`,className:z.mobileQrButton,onClick:()=>void Q(),disabled:T,"aria-label":`Show mobile QR code`,title:`Show mobile QR code`,children:(0,X.jsxs)(`span`,{"aria-hidden":`true`,className:z.mobileQrIcon,children:[(0,X.jsx)(`span`,{}),(0,X.jsx)(`span`,{}),(0,X.jsx)(`span`,{}),(0,X.jsx)(`span`,{})]})}),(0,X.jsx)(x,{})]}),C?(0,X.jsx)(`div`,{className:z.mobileQrOverlay,children:(0,X.jsxs)(`div`,{ref:ge,className:z.mobileQrDialog,role:`dialog`,"aria-modal":`true`,"aria-labelledby":`mobile-qr-title`,children:[(0,X.jsxs)(`div`,{className:z.mobileQrHeader,children:[(0,X.jsx)(`h2`,{id:`mobile-qr-title`,children:`Open on mobile`}),(0,X.jsx)(`button`,{ref:_e,type:`button`,className:z.mobileQrClose,onClick:()=>w(null),"aria-label":`Close mobile QR code`,children:`x`})]}),(0,X.jsx)(`div`,{className:z.mobileQrImage,children:(0,X.jsx)(`img`,{src:`data:image/svg+xml;charset=utf-8,${encodeURIComponent(C.qrSvg)}`,alt:`Mobile session QR code`})}),(0,X.jsx)(`a`,{className:z.mobileQrLink,href:C.launchUrl,children:`Open link`})]})}):null,$?(0,X.jsx)(`div`,{className:z.emptyState,children:(0,X.jsx)(`h1`,{className:z.greeting,children:et})}):(0,X.jsx)(`div`,{className:z.messageArea,ref:pe,children:(0,X.jsx)(`div`,{className:z.messageList,ref:N,children:Je.map(t=>_===t.id&&t.role!==`thinking`?(0,X.jsx)(`div`,{className:z.messageBlock,children:(0,X.jsx)(tn,{initial:t.rawContent??t.content,onSave:e=>void it(t,e),onCancel:()=>y(null)})},t.id):(0,X.jsx)(Zt,{message:t,token:e.token,isStreaming:t.id===G.streamingMsgId,onCopy:ke,onEdit:Ct,onRegenerate:at,onRate:st,ratingBusy:tt.isPending&&tt.variables?.message.id===t.id,skillInvocationTargets:Ie,onApprovalAction:ot,approvalBusy:b,branchInfo:nt.get(t.id)??null,onBranchNav:wt},t.id))})}),!$&&!me?(0,X.jsxs)(`button`,{type:`button`,className:z.jumpToLatest,onClick:P,"aria-label":`Jump to latest message`,children:[(0,X.jsx)(`span`,{"aria-hidden":`true`,children:`↓`}),(0,X.jsx)(`span`,{children:`Latest`})]}):null,f?(0,X.jsx)(`div`,{className:`${z.errorBanner} ${h?z.errorBannerExiting:``}`,children:f}):null,(0,X.jsx)(bt,{isStreaming:G.isStreaming,onSend:ut,onStop:()=>void G.stopRequest(),onUploadFiles:ct,token:e.token,agents:Pe,selectedAgentId:Ze,onAgentSwitch:e=>void mt(e),models:Ue,selectedModelId:D,onModelSwitch:e=>void ht(e),initialValue:o})]}),(0,X.jsx)(v,{open:j!==null,onOpenChange:e=>{!e&&!Z.isPending&&ce(null)},children:(0,X.jsxs)(ie,{size:`sm`,role:`alertdialog`,preventCloseOnOutsideClick:Z.isPending,children:[(0,X.jsxs)(c,{children:[(0,X.jsx)(de,{children:`Delete session?`}),(0,X.jsx)(ae,{children:`This permanently removes the conversation and associated session records.`})]}),(0,X.jsxs)(ee,{children:[(0,X.jsx)(O,{className:`ghost-button`,disabled:Z.isPending,children:`Cancel`}),(0,X.jsx)(`button`,{type:`button`,className:`danger-button`,disabled:Z.isPending,onClick:yt,children:Z.isPending?`Deleting...`:`Delete`})]})]})})]})})}export{Cn as ChatPage};