@nextclaw/ui 0.12.23 → 0.12.24
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 +97 -0
- package/dist/assets/{api-BGd3rgv_.js → api-D2xRKmZd.js} +2 -2
- package/dist/assets/{app-manager-provider-BuJ_U9eC.js → app-manager-provider-CNaZboG4.js} +1 -1
- package/dist/assets/{app-navigation.config-BTdUuqXS.js → app-navigation.config-Ihhrrt--.js} +1 -1
- package/dist/assets/{channels-list-page-BrwymXPe.js → channels-list-page-p26lgxLk.js} +1 -1
- package/dist/assets/{chat-DGM6K3Qs.js → chat-Dkh2qtuz.js} +8 -8
- package/dist/assets/{chat-page-DpmXMWNS.js → chat-page-DoTmE2wx.js} +1 -1
- package/dist/assets/{desktop-update-config-BGKiqc6q.js → desktop-update-config-DlpzDfKM.js} +1 -1
- package/dist/assets/{dialog-dxsKz7jJ.js → dialog-C3D7Be0p.js} +1 -1
- package/dist/assets/{dist-DsYTOyq7.js → dist-CPlbUgwU.js} +1 -1
- package/dist/assets/{es2015-V75WQJ2s.js → es2015-xqN1slyW.js} +1 -1
- package/dist/assets/{index-BrEdR78s.js → index-pBvbJ5Mt.js} +2 -2
- package/dist/assets/marketplace-page-Cql0kDi-.js +1 -0
- package/dist/assets/{marketplace-page-CPHxlYL8.js → marketplace-page-m4P5g_Ht.js} +1 -1
- package/dist/assets/mcp-marketplace-page-9WVKl1m1.js +1 -0
- package/dist/assets/{mcp-marketplace-page-CswPXSjf.js → mcp-marketplace-page-ByzBQZcx.js} +1 -1
- package/dist/assets/{model-config-Cmruiqdx.js → model-config-Dbr_0APb.js} +1 -1
- package/dist/assets/{notice-card-D1RNsTn_.js → notice-card-BFDbKQDA.js} +1 -1
- package/dist/assets/{popover-BMyiifTA.js → popover-B86Dbfhf.js} +1 -1
- package/dist/assets/{provider-scoped-model-input-D7ACiMAO.js → provider-scoped-model-input-DFm6N2f7.js} +1 -1
- package/dist/assets/{providers-list-gg7LrfuB.js → providers-list-BJcLOjun.js} +1 -1
- package/dist/assets/remote-BOxo9iwd.js +1 -0
- package/dist/assets/{runtime-config-page-BT_VV41p.js → runtime-config-page-CjLhnbSl.js} +1 -1
- package/dist/assets/{search-config-0VTPpz-w.js → search-config-J4Htco-P.js} +1 -1
- package/dist/assets/{secrets-config-DwQbLLEy.js → secrets-config-CUdERjco.js} +1 -1
- package/dist/assets/{select-DTdzR8j8.js → select-CJ0wbo3D.js} +1 -1
- package/dist/assets/{sessions-config-page-CAG7Zevv.js → sessions-config-page-DpK991fs.js} +2 -2
- package/dist/assets/{setting-row-CvKngoNI.js → setting-row-D1Yygqp7.js} +1 -1
- package/dist/assets/{tag-chip-BywQeHJj.js → tag-chip-FrkmkT8r.js} +1 -1
- package/dist/assets/{theme-provider-COAwWFv8.js → theme-provider-0hxjiPc_.js} +1 -1
- package/dist/assets/{tooltip-BOYp8Ue7.js → tooltip-Cj4yA0gH.js} +1 -1
- package/dist/assets/{use-config-DTwhNDQE.js → use-config-38Ur-89i.js} +1 -1
- package/dist/assets/{use-confirm-dialog-oeSqhmrx.js → use-confirm-dialog-DPQThaeU.js} +1 -1
- package/dist/assets/{use-infinite-scroll-loader-X3KGuME8.js → use-infinite-scroll-loader-5Gf1xQi7.js} +1 -1
- package/dist/assets/{use-viewport-layout-C0NJAVXs.js → use-viewport-layout-D1XzKeip.js} +1 -1
- package/dist/index.html +15 -15
- package/package.json +9 -9
- package/src/features/chat/components/chat-sidebar-session-item.tsx +1 -1
- package/src/features/chat/components/conversation/chat-conversation-panel.tsx +2 -2
- package/src/features/chat/components/layout/chat-sidebar.test.tsx +74 -0
- package/src/features/chat/components/layout/chat-sidebar.tsx +28 -29
- package/src/features/chat/hooks/use-hydrated-ncp-agent.test.tsx +6 -0
- package/src/features/chat/hooks/use-ncp-agent-runtime.test.tsx +158 -69
- package/src/features/chat/hooks/use-ncp-chat-derived-state.ts +2 -2
- package/src/features/chat/hooks/use-ncp-chat-page-data.ts +7 -7
- package/src/features/chat/hooks/use-ncp-session-conversation.test.tsx +10 -0
- package/src/features/chat/hooks/use-ncp-session-conversation.ts +2 -1
- package/src/features/chat/hooks/use-selected-session-context-window-indicator.ts +2 -4
- package/src/features/chat/managers/chat-session-list.manager.test.ts +19 -16
- package/src/features/chat/managers/chat-session-list.manager.ts +20 -24
- package/src/features/chat/managers/ncp-chat-input.manager.test.ts +23 -12
- package/src/features/chat/managers/ncp-chat-input.manager.ts +4 -2
- package/src/features/chat/pages/ncp-chat-page.tsx +23 -13
- package/src/features/chat/stores/chat-session-list.store.ts +2 -3
- package/src/features/chat/types/chat-stream.types.ts +1 -1
- package/src/features/chat/utils/ncp-session-adapter.utils.ts +1 -1
- package/src/shared/lib/api/ncp-session-query-cache.test.ts +26 -1
- package/src/shared/lib/api/ncp-session-query-cache.ts +5 -1
- package/dist/assets/marketplace-page-B2Pm2RDJ.js +0 -1
- package/dist/assets/mcp-marketplace-page-BcjVmw36.js +0 -1
- package/dist/assets/remote-Db2M39Cv.js +0 -1
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{_ as e,a as t,d as n,f as r,g as i,h as a,i as o,m as s,n as c,p as l,t as u,u as d}from"./i18n-DnTGDIRw.js";import{At as f,It as p,Kt as m,Lt as h,Mt as g,Nt as _,Pt as v,Rt as y,V as b,Vt as x,_t as S,at as C,bt as w,f as T,h as E,it as D,jt as O,m as ee,n as k,nt as te,p as A,rt as ne,st as j,t as re,v as ie,xt as ae,y as oe,yt as se}from"./api-BGd3rgv_.js";import{a as ce,i as le,n as ue,o as de,r as fe,t as pe}from"./dialog-dxsKz7jJ.js";import{t as M}from"./createLucideIcon-BLMK3QUd.js";import{_ as me,c as he,d as ge,f as _e,g as ve,h as ye,l as be,m as xe,n as Se,p as Ce,s as we,u as Te,v as Ee}from"./theme-provider-COAwWFv8.js";import{n as De,t as Oe}from"./search-CLd7m0M7.js";import{t as ke}from"./book-open-DDlN5MvX.js";import{D as Ae,O as je,_ as Me,b as Ne,c as Pe,d as Fe,f as Ie,g as Le,h as Re,i as ze,k as Be,l as Ve,m as He,n as Ue,o as We,p as Ge,r as Ke,s as qe,t as Je,u as Ye,v as Xe,y as Ze}from"./select-DTdzR8j8.js";import{t as Qe}from"./external-link-DwfSfTLB.js";import{t as $e}from"./folder-CeJKPx5P.js";import{n as et,t as tt}from"./logos-C4sYP1Vl.js";import{t as nt}from"./loader-circle-fd-vQKtW.js";import{t as rt}from"./plus-D8eKFY7h.js";import{t as it}from"./refresh-ccw-ByVwmnN_.js";import{t as at}from"./settings-drbWqzA4.js";import{t as ot}from"./sparkles-DVfeSVJQ.js";import{t as st}from"./trash-2-CBsHCfqq.js";import{t as ct}from"./x-CM-XDMpk.js";import{i as lt}from"./doc-browser-context-BJuMaI3o.js";import{n as ut}from"./doc-browser-C8FM5fC0.js";import{n as dt,t as ft}from"./use-viewport-layout-C0NJAVXs.js";import{m as pt}from"./use-config-DTwhNDQE.js";import{a as mt,c as ht,i as gt,n as _t,o as vt,r as yt,s as bt,t as xt}from"./popover-BMyiifTA.js";import{t as St}from"./logo-badge-KAe-7d8c.js";import{a as Ct,c as wt,i as Tt,l as Et,n as Dt,o as Ot,r as kt,s as At,t as jt}from"./tooltip-BOYp8Ue7.js";import{t as Mt}from"./skeleton-BK1SOSRA.js";var Nt=M(`ArrowUpRight`,[[`path`,{d:`M7 7h10v10`,key:`1tivn9`}],[`path`,{d:`M7 17 17 7`,key:`1vkiza`}]]),Pt=M(`ArrowUp`,[[`path`,{d:`m5 12 7-7 7 7`,key:`hav0vg`}],[`path`,{d:`M12 19V5`,key:`x0mq9r`}]]),Ft=M(`Brain`,[[`path`,{d:`M12 5a3 3 0 1 0-5.997.125 4 4 0 0 0-2.526 5.77 4 4 0 0 0 .556 6.588A4 4 0 1 0 12 18Z`,key:`l5xja`}],[`path`,{d:`M12 5a3 3 0 1 1 5.997.125 4 4 0 0 1 2.526 5.77 4 4 0 0 1-.556 6.588A4 4 0 1 1 12 18Z`,key:`ep3f8r`}],[`path`,{d:`M15 13a4.5 4.5 0 0 1-3-4 4.5 4.5 0 0 1-3 4`,key:`1p4c4q`}],[`path`,{d:`M17.599 6.5a3 3 0 0 0 .399-1.375`,key:`tmeiqw`}],[`path`,{d:`M6.003 5.125A3 3 0 0 0 6.401 6.5`,key:`105sqy`}],[`path`,{d:`M3.477 10.896a4 4 0 0 1 .585-.396`,key:`ql3yin`}],[`path`,{d:`M19.938 10.5a4 4 0 0 1 .585.396`,key:`1qfode`}],[`path`,{d:`M6 18a4 4 0 0 1-1.967-.516`,key:`2e4loj`}],[`path`,{d:`M19.967 17.484A4 4 0 0 1 18 18`,key:`159ez6`}]]),It=M(`ChevronRight`,[[`path`,{d:`m9 18 6-6-6-6`,key:`mthhwq`}]]),Lt=M(`CodeXml`,[[`path`,{d:`m18 16 4-4-4-4`,key:`1inbqp`}],[`path`,{d:`m6 8-4 4 4 4`,key:`15zrgr`}],[`path`,{d:`m14.5 4-5 16`,key:`e7oirm`}]]),Rt=M(`Copy`,[[`rect`,{width:`14`,height:`14`,x:`8`,y:`8`,rx:`2`,ry:`2`,key:`17jyea`}],[`path`,{d:`M4 16c-1.1 0-2-.9-2-2V4c0-1.1.9-2 2-2h10c1.1 0 2 .9 2 2`,key:`zix9uf`}]]),zt=M(`Ellipsis`,[[`circle`,{cx:`12`,cy:`12`,r:`1`,key:`41hilf`}],[`circle`,{cx:`19`,cy:`12`,r:`1`,key:`1wjl8i`}],[`circle`,{cx:`5`,cy:`12`,r:`1`,key:`1pcz8c`}]]),Bt=M(`FileArchive`,[[`path`,{d:`M10 12v-1`,key:`v7bkov`}],[`path`,{d:`M10 18v-2`,key:`1cjy8d`}],[`path`,{d:`M10 7V6`,key:`dljcrl`}],[`path`,{d:`M14 2v4a2 2 0 0 0 2 2h4`,key:`tnqrlb`}],[`path`,{d:`M15.5 22H18a2 2 0 0 0 2-2V7l-5-5H6a2 2 0 0 0-2 2v16a2 2 0 0 0 .274 1.01`,key:`gkbcor`}],[`circle`,{cx:`10`,cy:`20`,r:`2`,key:`1xzdoj`}]]),Vt=M(`FileAudio2`,[[`path`,{d:`M4 22h14a2 2 0 0 0 2-2V7l-5-5H6a2 2 0 0 0-2 2v2`,key:`17k7jt`}],[`path`,{d:`M14 2v4a2 2 0 0 0 2 2h4`,key:`tnqrlb`}],[`circle`,{cx:`3`,cy:`17`,r:`1`,key:`vo6nti`}],[`path`,{d:`M2 17v-3a4 4 0 0 1 8 0v3`,key:`1ggdre`}],[`circle`,{cx:`9`,cy:`17`,r:`1`,key:`bc1fq4`}]]),Ht=M(`FileCode2`,[[`path`,{d:`M4 22h14a2 2 0 0 0 2-2V7l-5-5H6a2 2 0 0 0-2 2v4`,key:`1pf5j1`}],[`path`,{d:`M14 2v4a2 2 0 0 0 2 2h4`,key:`tnqrlb`}],[`path`,{d:`m5 12-3 3 3 3`,key:`oke12k`}],[`path`,{d:`m9 18 3-3-3-3`,key:`112psh`}]]),Ut=M(`FileImage`,[[`path`,{d:`M15 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7Z`,key:`1rqfz7`}],[`path`,{d:`M14 2v4a2 2 0 0 0 2 2h4`,key:`tnqrlb`}],[`circle`,{cx:`10`,cy:`12`,r:`2`,key:`737tya`}],[`path`,{d:`m20 17-1.296-1.296a2.41 2.41 0 0 0-3.408 0L9 22`,key:`wt3hpn`}]]),Wt=M(`FileJson2`,[[`path`,{d:`M4 22h14a2 2 0 0 0 2-2V7l-5-5H6a2 2 0 0 0-2 2v4`,key:`1pf5j1`}],[`path`,{d:`M14 2v4a2 2 0 0 0 2 2h4`,key:`tnqrlb`}],[`path`,{d:`M4 12a1 1 0 0 0-1 1v1a1 1 0 0 1-1 1 1 1 0 0 1 1 1v1a1 1 0 0 0 1 1`,key:`fq0c9t`}],[`path`,{d:`M8 18a1 1 0 0 0 1-1v-1a1 1 0 0 1 1-1 1 1 0 0 1-1-1v-1a1 1 0 0 0-1-1`,key:`4gibmv`}]]),Gt=M(`FileSpreadsheet`,[[`path`,{d:`M15 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7Z`,key:`1rqfz7`}],[`path`,{d:`M14 2v4a2 2 0 0 0 2 2h4`,key:`tnqrlb`}],[`path`,{d:`M8 13h2`,key:`yr2amv`}],[`path`,{d:`M14 13h2`,key:`un5t4a`}],[`path`,{d:`M8 17h2`,key:`2yhykz`}],[`path`,{d:`M14 17h2`,key:`10kma7`}]]),Kt=M(`FileText`,[[`path`,{d:`M15 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7Z`,key:`1rqfz7`}],[`path`,{d:`M14 2v4a2 2 0 0 0 2 2h4`,key:`tnqrlb`}],[`path`,{d:`M10 9H8`,key:`b1mrlr`}],[`path`,{d:`M16 13H8`,key:`t4e002`}],[`path`,{d:`M16 17H8`,key:`z1uh3a`}]]),qt=M(`FileVideo2`,[[`path`,{d:`M4 22h14a2 2 0 0 0 2-2V7l-5-5H6a2 2 0 0 0-2 2v4`,key:`1pf5j1`}],[`path`,{d:`M14 2v4a2 2 0 0 0 2 2h4`,key:`tnqrlb`}],[`rect`,{width:`8`,height:`6`,x:`2`,y:`12`,rx:`1`,key:`1a6c1e`}],[`path`,{d:`m10 15.5 4 2.5v-6l-4 2.5`,key:`t7cp39`}]]),Jt=M(`File`,[[`path`,{d:`M15 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7Z`,key:`1rqfz7`}],[`path`,{d:`M14 2v4a2 2 0 0 0 2 2h4`,key:`tnqrlb`}]]),Yt=M(`FolderGit2`,[[`path`,{d:`M9 20H4a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h3.9a2 2 0 0 1 1.69.9l.81 1.2a2 2 0 0 0 1.67.9H20a2 2 0 0 1 2 2v5`,key:`1w6njk`}],[`circle`,{cx:`13`,cy:`12`,r:`2`,key:`1j92g6`}],[`path`,{d:`M18 19c-2.8 0-5-2.2-5-5v8`,key:`pkpw2h`}],[`circle`,{cx:`20`,cy:`19`,r:`2`,key:`1obnsp`}]]),Xt=M(`FolderOpen`,[[`path`,{d:`m6 14 1.5-2.9A2 2 0 0 1 9.24 10H20a2 2 0 0 1 1.94 2.5l-1.54 6a2 2 0 0 1-1.95 1.5H4a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h3.9a2 2 0 0 1 1.69.9l.81 1.2a2 2 0 0 0 1.67.9H18a2 2 0 0 1 2 2v2`,key:`usdka0`}]]),Zt=M(`FolderTree`,[[`path`,{d:`M20 10a1 1 0 0 0 1-1V6a1 1 0 0 0-1-1h-2.5a1 1 0 0 1-.8-.4l-.9-1.2A1 1 0 0 0 15 3h-2a1 1 0 0 0-1 1v5a1 1 0 0 0 1 1Z`,key:`hod4my`}],[`path`,{d:`M20 21a1 1 0 0 0 1-1v-3a1 1 0 0 0-1-1h-2.9a1 1 0 0 1-.88-.55l-.42-.85a1 1 0 0 0-.92-.6H13a1 1 0 0 0-1 1v5a1 1 0 0 0 1 1Z`,key:`w4yl2u`}],[`path`,{d:`M3 5a2 2 0 0 0 2 2h3`,key:`f2jnh7`}],[`path`,{d:`M3 3v13a2 2 0 0 0 2 2h3`,key:`k8epm1`}]]),Qt=M(`FolderUp`,[[`path`,{d:`M20 20a2 2 0 0 0 2-2V8a2 2 0 0 0-2-2h-7.9a2 2 0 0 1-1.69-.9L9.6 3.9A2 2 0 0 0 7.93 3H4a2 2 0 0 0-2 2v13a2 2 0 0 0 2 2Z`,key:`1kt360`}],[`path`,{d:`M12 10v6`,key:`1bos4e`}],[`path`,{d:`m9 13 3-3 3 3`,key:`1pxg3c`}]]),$t=M(`FolderX`,[[`path`,{d:`M20 20a2 2 0 0 0 2-2V8a2 2 0 0 0-2-2h-7.9a2 2 0 0 1-1.69-.9L9.6 3.9A2 2 0 0 0 7.93 3H4a2 2 0 0 0-2 2v13a2 2 0 0 0 2 2Z`,key:`1kt360`}],[`path`,{d:`m9.5 10.5 5 5`,key:`ra9qjz`}],[`path`,{d:`m14.5 10.5-5 5`,key:`l2rkpq`}]]),en=M(`GitBranch`,[[`line`,{x1:`6`,x2:`6`,y1:`3`,y2:`15`,key:`17qcm7`}],[`circle`,{cx:`18`,cy:`6`,r:`3`,key:`1h7g24`}],[`circle`,{cx:`6`,cy:`18`,r:`3`,key:`fqmcym`}],[`path`,{d:`M18 9a9 9 0 0 1-9 9`,key:`n2h4wq`}]]),tn=M(`House`,[[`path`,{d:`M15 21v-8a1 1 0 0 0-1-1h-4a1 1 0 0 0-1 1v8`,key:`5wwlr5`}],[`path`,{d:`M3 10a2 2 0 0 1 .709-1.528l7-5.999a2 2 0 0 1 2.582 0l7 5.999A2 2 0 0 1 21 10v9a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2z`,key:`1d0kgt`}]]),nn=M(`MessageSquareText`,[[`path`,{d:`M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z`,key:`1lielz`}],[`path`,{d:`M13 8H7`,key:`14i4kc`}],[`path`,{d:`M17 12H7`,key:`16if0g`}]]),rn=M(`Minus`,[[`path`,{d:`M5 12h14`,key:`1ays0h`}]]),an=M(`Paperclip`,[[`path`,{d:`m21.44 11.05-9.19 9.19a6 6 0 0 1-8.49-8.49l8.57-8.57A4 4 0 1 1 18 8.84l-8.59 8.57a2 2 0 0 1-2.83-2.83l8.49-8.48`,key:`1u3ebp`}]]),on=M(`Pencil`,[[`path`,{d:`M21.174 6.812a1 1 0 0 0-3.986-3.987L3.842 16.174a2 2 0 0 0-.5.83l-1.321 4.352a.5.5 0 0 0 .623.622l4.353-1.32a2 2 0 0 0 .83-.497z`,key:`1a8usu`}],[`path`,{d:`m15 5 4 4`,key:`1mk7zo`}]]),sn=M(`Puzzle`,[[`path`,{d:`M15.39 4.39a1 1 0 0 0 1.68-.474 2.5 2.5 0 1 1 3.014 3.015 1 1 0 0 0-.474 1.68l1.683 1.682a2.414 2.414 0 0 1 0 3.414L19.61 15.39a1 1 0 0 1-1.68-.474 2.5 2.5 0 1 0-3.014 3.015 1 1 0 0 1 .474 1.68l-1.683 1.682a2.414 2.414 0 0 1-3.414 0L8.61 19.61a1 1 0 0 0-1.68.474 2.5 2.5 0 1 1-3.014-3.015 1 1 0 0 0 .474-1.68l-1.683-1.682a2.414 2.414 0 0 1 0-3.414L4.39 8.61a1 1 0 0 1 1.68.474 2.5 2.5 0 1 0 3.014-3.015 1 1 0 0 1-.474-1.68l1.683-1.682a2.414 2.414 0 0 1 3.414 0z`,key:`w46dr5`}]]),cn=M(`Terminal`,[[`polyline`,{points:`4 17 10 11 4 5`,key:`akl6gq`}],[`line`,{x1:`12`,x2:`20`,y1:`19`,y2:`19`,key:`q2wloq`}]]),ln=M(`TriangleAlert`,[[`path`,{d:`m21.73 18-8-14a2 2 0 0 0-3.48 0l-8 14A2 2 0 0 0 4 21h16a2 2 0 0 0 1.73-3`,key:`wmoenq`}],[`path`,{d:`M12 9v4`,key:`juzpu7`}],[`path`,{d:`M12 17h.01`,key:`p32p05`}]]),un=M(`User`,[[`path`,{d:`M19 21v-2a4 4 0 0 0-4-4H9a4 4 0 0 0-4 4v2`,key:`975kel`}],[`circle`,{cx:`12`,cy:`7`,r:`4`,key:`17ys0d`}]]),N=l();function dn({isProjectFirstView:e,onSelectMode:t}){return(0,N.jsxs)(`div`,{className:`flex items-center gap-1.5 text-[11px]`,children:[(0,N.jsx)(`button`,{type:`button`,"aria-pressed":!e,onClick:()=>t(`time-first`),className:d(`transition-colors`,e?`text-gray-400 hover:text-gray-600`:`font-medium text-gray-600`),children:o(`chatSidebarViewTime`)}),(0,N.jsx)(`span`,{className:`text-gray-300`,children:`/`}),(0,N.jsx)(`button`,{type:`button`,"aria-pressed":e,onClick:()=>t(`project-first`),className:d(`transition-colors`,e?`font-medium text-gray-600`:`text-gray-400 hover:text-gray-600`),children:o(`chatSidebarViewProject`)})]})}var fn={wx:`weixin`,lark:`feishu`},pn={cron:{icon:`cron`}},mn={codex:`chatSessionTypeCodex`,claude:`chatSessionTypeClaude`};function hn(e){return e?.trim().toLowerCase()??``}function gn(e){return e.split(/[-_]+/g).filter(Boolean).map(e=>e.charAt(0).toUpperCase()+e.slice(1)).join(` `)}function _n(e,t){let n=hn(e);if(!n||n===`native`)return null;let r=t.find(e=>hn(e.value)===n);return r?.label.trim()?r.label.trim():gn(n)}function vn(e,t){let n=hn(e);return!n||n===`native`?null:t.find(e=>hn(e.value)===n)??null}function yn(e){let t=hn(e);if(!t)return null;let n=fn[t]??t;return tt(n)?n:null}function bn(e,t){let n=yn(e.channel??``);if(n)return{icon:{kind:`channel-logo`,channel:n},label:null};let r=pn[hn(e.type)];if(r)return{icon:{kind:`symbol`,icon:r.icon},label:null};let i=hn(e.sessionType),a=vn(i,t);if(a?.icon?.src?.trim())return{icon:{kind:`runtime-image`,src:a.icon.src,alt:a.icon.alt??null,name:a.label},label:null};let s=mn[i];return s?{icon:null,label:o(s)}:{icon:null,label:a?.label?.trim()||_n(e.sessionType,t)}}var xn=`app://`;function Sn(e){let t=e.trim().replace(/^\/+/,``);if(!t)return null;let n=t.split(`/`);return n.some(e=>e.trim().length===0||e===`.`||e===`..`)?null:n.join(`/`)}function Cn(e){let t=e.trim();if(!t)return null;if(!t.startsWith(xn))return t;let n=Sn(t.slice(6));return n?`/${n}`:null}function wn({icon:e,className:t}){if(e.kind===`channel-logo`)return(0,N.jsx)(Tn,{channel:e.channel,className:t});if(e.kind===`runtime-image`){let n=Cn(e.src);return(0,N.jsx)(St,{name:e.name?.trim()||e.alt?.trim()||`runtime`,src:n??void 0,className:d(`h-[1.125rem] w-[1.125rem]`,t),imgClassName:`h-full w-full object-contain`,fallback:(0,N.jsx)(me,{className:d(`h-3 w-3 text-gray-500`,t)})})}return(0,N.jsx)(Ee,{className:d(`h-3.5 w-3.5`,t)})}function Tn({channel:e,className:t}){return(0,N.jsx)(St,{name:e,src:tt(e),className:d(`h-[1.125rem] w-[1.125rem]`,t),imgClassName:`h-full w-full object-contain`,fallback:(0,N.jsx)(me,{className:`h-3 w-3 text-gray-500`})})}function En(e){let{option:t,onSelect:n}=e,r=t.ready===!1?t.reasonMessage?.trim()||o(`statusSetup`):null;return(0,N.jsx)(`button`,{type:`button`,onClick:n,className:`w-full rounded-2xl px-3 py-2.5 text-left transition-colors hover:bg-gray-50`,children:(0,N.jsx)(`div`,{className:`flex items-start gap-3`,children:(0,N.jsxs)(`div`,{className:`flex min-w-0 flex-1 items-start gap-2.5`,children:[t.icon?.src?(0,N.jsx)(`span`,{className:`inline-flex h-5 w-5 shrink-0 items-center justify-center pt-0.5`,children:(0,N.jsx)(wn,{icon:{kind:`runtime-image`,src:t.icon.src,alt:t.icon.alt??null,name:t.label}})}):(0,N.jsx)(`span`,{className:`inline-flex h-5 w-5 shrink-0 items-center justify-center pt-0.5 text-gray-400`,children:(0,N.jsx)(me,{className:`h-4 w-4`})}),(0,N.jsxs)(`div`,{className:`min-w-0 flex-1`,children:[(0,N.jsxs)(`div`,{className:`flex items-center justify-between gap-3`,children:[(0,N.jsx)(`div`,{className:`truncate text-[13px] font-semibold text-gray-900`,children:t.label}),(0,N.jsxs)(`span`,{className:d(`inline-flex shrink-0 items-center gap-1.5 text-[11px] font-medium`,t.ready===!1?`text-amber-700`:`text-emerald-600`),children:[(0,N.jsx)(`span`,{className:d(`h-1.5 w-1.5 rounded-full`,t.ready===!1?`bg-amber-500`:`bg-emerald-500`)}),t.ready===!1?o(`statusSetup`):o(`statusReady`)]})]}),r?(0,N.jsx)(`div`,{className:`mt-1 pr-4 text-[11px] leading-4 text-gray-500`,children:r}):null]})]})})})}var P=e(s(),1);function Dn(e,t){return t.some(t=>t.value===e)?e:t[0]?.value??e}function On(e){let{groups:t,defaultSessionType:n,sessionTypeOptions:r,renderSessionItem:i,onCreateSession:a}=e,[s,c]=(0,P.useState)(null),l=(0,P.useMemo)(()=>Dn(n,r),[n,r]),u=r.length>1;return(0,N.jsx)(`div`,{className:`space-y-3`,children:t.map(e=>{let t=`${o(`chatSidebarNewTask`)} · ${e.projectName}`;return(0,N.jsxs)(`div`,{children:[(0,N.jsxs)(`div`,{className:`flex items-center justify-between gap-2 px-2 py-0.5`,children:[(0,N.jsxs)(`div`,{className:`flex min-w-0 items-center gap-1.5`,children:[(0,N.jsx)(`div`,{className:`truncate text-[11px] font-medium uppercase tracking-wider text-gray-500`,title:e.projectRoot,children:e.projectName}),(0,N.jsx)(`span`,{className:`shrink-0 text-[10px] text-gray-400`,children:e.items.length})]}),u?(0,N.jsxs)(xt,{open:s===e.projectRoot,onOpenChange:t=>{c(t?e.projectRoot:null)},children:[(0,N.jsx)(yt,{asChild:!0,children:(0,N.jsx)(g,{type:`button`,variant:`ghost`,size:`icon`,className:`h-7 w-7 shrink-0 rounded-lg text-gray-400 hover:bg-white hover:text-gray-900`,"aria-label":t,title:t,children:(0,N.jsx)(rt,{className:`h-3.5 w-3.5`})})}),(0,N.jsxs)(_t,{align:`end`,className:`w-56 rounded-2xl border border-gray-200/80 bg-white p-1.5 shadow-[0_24px_60px_-28px_rgba(15,23,42,0.38)]`,children:[(0,N.jsx)(`div`,{className:`px-3 pb-1 pt-2 text-[10px] font-semibold uppercase tracking-[0.18em] text-gray-400`,children:o(`chatSessionTypeLabel`)}),(0,N.jsx)(`div`,{className:`space-y-1`,children:r.map(t=>(0,N.jsx)(En,{option:t,onSelect:()=>{a(t.value,e.projectRoot),c(null)}},`${e.projectRoot}:${t.value}`))})]})]}):(0,N.jsx)(g,{type:`button`,variant:`ghost`,size:`icon`,className:`h-7 w-7 shrink-0 rounded-lg text-gray-400 hover:bg-white hover:text-gray-900`,onClick:()=>a(l,e.projectRoot),"aria-label":t,title:t,children:(0,N.jsx)(rt,{className:`h-3.5 w-3.5`})})]}),(0,N.jsx)(`div`,{className:`space-y-0.5 pl-2`,children:e.items.map(i)})]},e.projectRoot)})})}var kn=[[`bg-amber-100`,`text-amber-700`],[`bg-emerald-100`,`text-emerald-700`],[`bg-blue-100`,`text-blue-700`],[`bg-rose-100`,`text-rose-700`],[`bg-cyan-100`,`text-cyan-700`],[`bg-violet-100`,`text-violet-700`]];function An(e){let t=0;for(let n=0;n<e.length;n+=1)t=(t<<5)-t+e.charCodeAt(n),t|=0;return Math.abs(t)}function jn({agentId:e,displayName:t,avatarUrl:n,className:r}){let i=t?.trim()||e,[a,o]=kn[An(e)%kn.length]??kn[0];return n?.trim()?(0,N.jsx)(`img`,{src:n,alt:t?.trim()||e,className:d(`rounded-full object-cover`,r)}):(0,N.jsx)(`div`,{className:d(`rounded-full flex items-center justify-center font-semibold`,a,o,r),"aria-label":t?.trim()||e,children:e.trim().toLowerCase()===`main`?(0,N.jsx)(me,{className:`h-[55%] w-[55%]`,strokeWidth:2.4}):(i.trim()||`A`).slice(0,1).toUpperCase()})}function Mn({status:e,className:t}){let n=o(e===`running`?`sessionsRunStatusRunning`:`sessionsRunStatusQueued`);return(0,N.jsxs)(`span`,{className:d(`inline-flex h-3.5 w-3.5 items-center justify-center text-gray-400`,t),title:n,"aria-label":n,children:[(0,N.jsx)(nt,{className:`h-3 w-3 animate-spin`}),(0,N.jsx)(`span`,{className:`sr-only`,children:n})]})}function Nn({session:e,draftLabel:t,isSaving:n,onDraftLabelChange:r,onSave:i,onCancel:a}){return(0,N.jsxs)(`div`,{className:`space-y-2`,children:[(0,N.jsx)(O,{value:t,onChange:e=>r(e.target.value),onKeyDown:e=>{e.key===`Enter`?(e.preventDefault(),i()):e.key===`Escape`&&(e.preventDefault(),a())},placeholder:o(`sessionsLabelPlaceholder`),className:`h-8 rounded-lg border-gray-300 bg-white text-xs`,autoFocus:!0,disabled:n}),(0,N.jsxs)(`div`,{className:`flex items-center justify-between gap-2`,children:[(0,N.jsx)(`div`,{className:`min-w-0 text-[11px] text-gray-400 truncate`,children:e.key}),(0,N.jsxs)(`div`,{className:`flex items-center gap-1`,children:[(0,N.jsx)(g,{type:`button`,size:`icon`,variant:`ghost`,className:`h-7 w-7 rounded-lg text-gray-500 hover:bg-white hover:text-gray-900`,onClick:()=>void i(),disabled:n,"aria-label":o(`save`),children:(0,N.jsx)(Be,{className:`h-3.5 w-3.5`})}),(0,N.jsx)(g,{type:`button`,size:`icon`,variant:`ghost`,className:`h-7 w-7 rounded-lg text-gray-500 hover:bg-white hover:text-gray-900`,onClick:a,disabled:n,"aria-label":o(`cancel`),children:(0,N.jsx)(ct,{className:`h-3.5 w-3.5`})})]})]})]})}function Pn({session:e,active:t,showUnreadDot:n,runStatus:r,context:i,title:a,agentId:s,agentLabel:c,agentAvatarUrl:l,childSessionCount:f=0,onSelect:p,onOpenChildSessions:m,onStartEditing:h}){return(0,N.jsxs)(`div`,{className:`group/session relative`,children:[(0,N.jsxs)(`button`,{type:`button`,onClick:p,className:`w-full text-left`,children:[(0,N.jsxs)(`div`,{className:d(`grid grid-cols-[minmax(0,1fr)_auto] items-start gap-2`,f>0&&m?`pr-14`:`pr-6`),children:[(0,N.jsxs)(`span`,{className:`flex min-w-0 items-center gap-1.5`,children:[s?.trim()&&s.trim().toLowerCase()!==`main`?(0,N.jsx)(jn,{agentId:s,displayName:c,avatarUrl:l,className:`h-5 w-5 shrink-0`}):null,(0,N.jsx)(`span`,{className:`truncate font-medium`,children:a}),i.label?(0,N.jsx)(`span`,{className:d(`shrink-0 rounded-full border px-1.5 py-0.5 text-[10px] font-semibold leading-none`,t?`border-gray-300 bg-white/80 text-gray-700`:`border-gray-200 bg-gray-100 text-gray-500`),children:i.label}):null,i.icon?(0,N.jsx)(`span`,{className:`inline-flex h-[1.125rem] w-[1.125rem] shrink-0 items-center justify-center`,children:(0,N.jsx)(wn,{icon:i.icon,className:t?`text-gray-700`:`text-gray-500`})}):null]}),r?(0,N.jsx)(`span`,{className:`inline-flex shrink-0 items-center justify-end gap-1.5 pt-0.5`,children:(0,N.jsx)(Mn,{status:r})}):null]}),(0,N.jsxs)(`div`,{className:`mt-1 flex items-center gap-2 text-[11px] text-gray-400`,children:[(0,N.jsxs)(`span`,{className:`min-w-0 truncate`,children:[c?.trim()?`${c} · `:``,e.messageCount]}),n?(0,N.jsx)(`span`,{"aria-label":o(`chatSessionUnread`),className:`ml-auto h-2 w-2 shrink-0 rounded-full bg-primary`}):(0,N.jsx)(`span`,{className:`ml-auto shrink-0`,children:u(e.updatedAt)})]})]}),f>0&&m?(0,N.jsxs)(`button`,{type:`button`,onClick:e=>{e.stopPropagation(),m()},className:d(`absolute right-6 top-0 inline-flex h-5 items-center gap-1 rounded-md px-1.5 text-[10px] font-medium text-gray-400 transition-all hover:bg-white hover:text-gray-900`,t?`opacity-100`:`opacity-0 group-hover/session:opacity-100 group-focus-within/session:opacity-100`),"aria-label":o(`chatSessionOpenChildSessions`),title:o(`chatSessionOpenChildSessions`),children:[(0,N.jsx)(en,{className:`h-3.5 w-3.5`}),(0,N.jsx)(`span`,{children:f})]}):null,(0,N.jsx)(`button`,{type:`button`,onClick:e=>{e.stopPropagation(),h()},className:d(`absolute right-0 top-0 inline-flex h-5 w-5 items-center justify-center rounded-md text-gray-400 transition-all hover:bg-white hover:text-gray-900`,t?`opacity-100`:`opacity-0 group-hover/session:opacity-100 group-focus-within/session:opacity-100`),"aria-label":o(`edit`),children:(0,N.jsx)(on,{className:`h-3 w-3`})})]})}function Fn({session:e,active:t,showUnreadDot:n,runStatus:r,context:i,title:a,agentId:o,agentLabel:s,agentAvatarUrl:c,childSessionCount:l,isEditing:u,draftLabel:f,isSaving:p,onSelect:m,onOpenChildSessions:h,onStartEditing:g,onDraftLabelChange:_,onSave:v,onCancel:y}){return(0,N.jsx)(`div`,{className:d(`w-full rounded-xl px-3 py-2.5 text-left transition-all text-[13px]`,t?`bg-gray-200 text-gray-900 font-semibold shadow-sm`:`text-gray-700 hover:bg-gray-200/60 hover:text-gray-900`),children:u?(0,N.jsx)(Nn,{session:e,draftLabel:f,isSaving:p,onDraftLabelChange:_,onSave:v,onCancel:y}):(0,N.jsx)(Pn,{session:e,active:t,showUnreadDot:n,runStatus:r,context:i,title:a,agentId:o,agentLabel:s,agentAvatarUrl:c,onSelect:m,childSessionCount:l,onOpenChildSessions:h,onStartEditing:g})})}var In=[{icon:xe,titleKey:`chatWelcomeCapability1Title`,descKey:`chatWelcomeCapability1Desc`},{icon:ve,titleKey:`chatWelcomeCapability2Title`,descKey:`chatWelcomeCapability2Desc`},{icon:Ee,titleKey:`chatWelcomeCapability3Title`,descKey:`chatWelcomeCapability3Desc`}];function Ln({onCreateSession:e,agents:t,selectedAgentId:n,onSelectAgent:r}){let i=t.find(e=>e.id===n)??null;return(0,N.jsx)(`div`,{className:`h-full flex items-center justify-center p-8`,children:(0,N.jsxs)(`div`,{className:`max-w-lg w-full text-center`,children:[(0,N.jsx)(`div`,{className:`mx-auto mb-6 h-16 w-16 rounded-2xl bg-primary/10 flex items-center justify-center`,children:(0,N.jsx)(me,{className:`h-8 w-8 text-primary`})}),(0,N.jsx)(`h2`,{className:`text-xl font-semibold text-gray-900 mb-2`,children:o(`chatWelcomeTitle`)}),(0,N.jsx)(`p`,{className:`text-sm text-gray-500 mb-8`,children:o(`chatWelcomeSubtitle`)}),(0,N.jsxs)(`div`,{className:`mb-6 flex items-center justify-center gap-2.5`,children:[(0,N.jsx)(`span`,{className:`text-[13px] font-medium text-gray-500`,children:o(`chatDraftAgentTitle`)}),(0,N.jsxs)(Je,{value:n,onValueChange:r,children:[(0,N.jsxs)(ze,{"aria-label":o(`chatDraftAgentTitle`),className:`h-auto w-auto gap-1 rounded-full border-0 bg-transparent px-1.5 py-1 text-gray-500 shadow-none hover:bg-white/70 hover:text-gray-800 focus:ring-0`,children:[(0,N.jsx)(`span`,{className:`sr-only`,children:o(`chatDraftAgentTitle`)}),(0,N.jsx)(`div`,{className:`flex items-center gap-1.5`,children:i?(0,N.jsx)(jn,{agentId:i.id,displayName:i.displayName,avatarUrl:i.avatarUrl,className:`h-7 w-7 shrink-0`}):null})]}),(0,N.jsx)(Ue,{className:`rounded-xl border-gray-200/80 shadow-lg`,children:t.map(e=>(0,N.jsx)(Ke,{value:e.id,className:`rounded-lg pr-10`,children:(0,N.jsxs)(`div`,{className:`flex min-w-0 items-center gap-2`,children:[(0,N.jsx)(jn,{agentId:e.id,displayName:e.displayName,avatarUrl:e.avatarUrl,className:`h-5 w-5 shrink-0`}),(0,N.jsx)(`span`,{className:`truncate text-sm font-medium text-gray-700`,children:e.displayName?.trim()||e.id})]})},e.id))})]})]}),(0,N.jsx)(`div`,{className:`grid grid-cols-3 gap-3`,children:In.map(t=>{let n=t.icon;return(0,N.jsxs)(`button`,{onClick:e,className:`rounded-2xl border border-gray-200 bg-white p-4 text-left shadow-card hover:shadow-card-hover transition-shadow cursor-pointer`,children:[(0,N.jsx)(`div`,{className:`h-9 w-9 rounded-xl bg-primary/8 flex items-center justify-center mb-3`,children:(0,N.jsx)(n,{className:`h-4.5 w-4.5 text-primary`})}),(0,N.jsx)(`div`,{className:`text-sm font-semibold text-gray-900 mb-1`,children:o(t.titleKey)}),(0,N.jsx)(`div`,{className:`text-[11px] text-gray-500 leading-relaxed`,children:o(t.descKey)})]},t.titleKey)})})]})})}var Rn=(0,P.createContext)(null);function zn({presenter:e,children:t}){return(0,N.jsx)(Rn.Provider,{value:e,children:t})}function Bn(){let e=(0,P.useContext)(Rn);if(!e)throw Error(`usePresenter must be used inside ChatPresenterProvider`);return e}var Vn=e=>`[data-item-index="${e}"]`;function Hn(e){let{activeIndex:t,containerRef:n,getItemSelector:r,isEnabled:i,itemCount:a}=e,o=r??Vn;(0,P.useEffect)(()=>{if(!i||a===0)return;let e=n.current;if(!e)return;let r=e.querySelector(o(t));typeof r?.scrollIntoView==`function`&&r.scrollIntoView({block:`nearest`,inline:`nearest`})},[t,n,o,i,a])}function Un(){let e=(0,P.useRef)(null),[t,n]=(0,P.useState)(null);return(0,P.useEffect)(()=>{let t=e.current;if(!t||typeof ResizeObserver>`u`)return;let r=()=>{n(t.getBoundingClientRect().width)};r();let i=new ResizeObserver(()=>r());return i.observe(t),()=>i.disconnect()},[]),{elementRef:e,width:t}}function F(...e){return n(r(e))}var Wn=P.forwardRef(({className:e,type:t,...n},r)=>(0,N.jsx)(`input`,{type:t,className:F(`flex h-9 w-full rounded-xl border border-gray-200/80 bg-white px-3.5 py-2 text-sm text-gray-900 file:border-0 file:bg-transparent file:text-sm file:font-medium placeholder:text-gray-300 placeholder:font-normal focus:outline-none focus:ring-1 focus:ring-primary/40 focus:border-primary/40 transition-colors disabled:cursor-not-allowed disabled:opacity-50`,e),ref:r,...n}));Wn.displayName=`ChatInput`;var Gn=bt,Kn=ht,qn=gt,Jn=P.forwardRef(({className:e,sideOffset:t=8,align:n=`start`,...r},i)=>(0,N.jsx)(vt,{children:(0,N.jsx)(mt,{ref:i,sideOffset:t,align:n,className:F(`z-[var(--z-popover,50)] w-72 overflow-hidden rounded-2xl border border-gray-200/50 bg-white p-4 shadow-lg animate-in fade-in-0 zoom-in-95 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2`,e),...r})}));Jn.displayName=mt.displayName;var Yn=He,Xn=qe,Zn=Ze,Qn=P.forwardRef(({className:e,children:t,...n},r)=>(0,N.jsxs)(Xe,{ref:r,className:F(`flex h-9 w-full items-center justify-between whitespace-nowrap rounded-xl border border-gray-200/80 bg-white px-3 py-2 text-sm shadow-sm ring-offset-background placeholder:text-muted-foreground focus:outline-none focus:ring-1 focus:ring-primary/40 disabled:cursor-not-allowed disabled:opacity-50 [&>span]:line-clamp-1`,e),...n,children:[t,(0,N.jsx)(Pe,{asChild:!0,children:(0,N.jsx)(je,{className:`h-4 w-4 opacity-50`})})]}));Qn.displayName=Xe.displayName;var $n=P.forwardRef(({className:e,...t},n)=>(0,N.jsx)(Le,{ref:n,className:F(`flex cursor-default items-center justify-center py-1`,e),...t,children:(0,N.jsx)(Ae,{className:`h-4 w-4`})}));$n.displayName=Le.displayName;var er=P.forwardRef(({className:e,...t},n)=>(0,N.jsx)(Re,{ref:n,className:F(`flex cursor-default items-center justify-center py-1`,e),...t,children:(0,N.jsx)(je,{className:`h-4 w-4`})}));er.displayName=Re.displayName;var tr=P.forwardRef(({className:e,children:t,position:n=`popper`,...r},i)=>(0,N.jsx)(Ge,{children:(0,N.jsxs)(We,{ref:i,className:F(`relative z-50 max-h-96 min-w-[8rem] overflow-hidden rounded-md bg-white text-popover-foreground shadow-md data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2`,n===`popper`&&`data-[side=bottom]:translate-y-1 data-[side=left]:-translate-x-1 data-[side=right]:translate-x-1 data-[side=top]:-translate-y-1`,e),position:n,...r,children:[(0,N.jsx)($n,{}),(0,N.jsx)(Ne,{className:F(`p-1`,n===`popper`&&`h-[var(--radix-select-trigger-height)] w-full min-w-[var(--radix-select-trigger-width)]`),children:t}),(0,N.jsx)(er,{})]})}));tr.displayName=We.displayName;var nr=P.forwardRef(({className:e,...t},n)=>(0,N.jsx)(Ie,{ref:n,className:F(`px-2 py-1 text-[11px] font-semibold uppercase tracking-[0.08em] text-gray-500`,e),...t}));nr.displayName=Ie.displayName;var rr=P.forwardRef(({className:e,children:t,...n},r)=>(0,N.jsxs)(Ve,{ref:r,className:F(`relative flex w-full cursor-default select-none items-center rounded-sm py-1.5 pl-2 pr-8 text-sm outline-none focus:bg-gray-100 data-[disabled]:pointer-events-none data-[disabled]:opacity-50 hover:bg-gray-100`,e),...n,children:[(0,N.jsx)(`span`,{className:`absolute right-2 flex h-3.5 w-3.5 items-center justify-center`,children:(0,N.jsx)(Ye,{children:(0,N.jsx)(Be,{className:`h-4 w-4`})})}),(0,N.jsx)(Fe,{children:t})]}));rr.displayName=Ve.displayName;var ir=P.forwardRef(({className:e,...t},n)=>(0,N.jsx)(Me,{ref:n,className:F(`-mx-1 my-1 h-px bg-gray-100`,e),...t}));ir.displayName=Me.displayName;var ar=At,or=wt,sr=Et,cr=P.forwardRef(({className:e,sideOffset:t=4,...n},r)=>(0,N.jsx)(Ot,{children:(0,N.jsx)(Ct,{ref:r,sideOffset:t,className:F(`z-[var(--z-tooltip)] overflow-hidden rounded-md border bg-popover px-3 py-1.5 text-sm text-popover-foreground shadow-md animate-in fade-in-0 zoom-in-95 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2`,e),...n})}));cr.displayName=Ct.displayName;var lr={Popover:Gn,PopoverAnchor:qn,PopoverContent:Jn,PopoverTrigger:Kn,Input:Wn,Select:Yn,SelectContent:tr,SelectGroup:Xn,SelectItem:rr,SelectLabel:nr,SelectSeparator:ir,SelectTrigger:Qn,SelectValue:Zn,Tooltip:or,TooltipContent:cr,TooltipProvider:ar,TooltipTrigger:sr},ur=680,dr=.82,fr=560;function pr(e){let{Popover:t,PopoverAnchor:n,PopoverContent:r}=lr,{elementRef:i,width:a}=Un(),o=(0,P.useRef)(null),{isOpen:s,isLoading:c,items:l,activeIndex:u,activeItem:d,texts:f,onSelectItem:p,onOpenChange:m,onSetActiveIndex:h}=e,g=(0,P.useMemo)(()=>{if(a)return Math.min(a>fr?a*dr:a,ur)},[a]);return Hn({containerRef:o,activeIndex:u,itemCount:l.length,isEnabled:s&&!c,getItemSelector:e=>`[data-slash-index="${e}"]`}),(0,N.jsxs)(t,{open:s,onOpenChange:m,children:[(0,N.jsx)(n,{asChild:!0,children:(0,N.jsx)(`div`,{ref:i,className:`pointer-events-none absolute bottom-full left-3 right-3 h-0`})}),(0,N.jsx)(r,{side:`top`,align:`start`,sideOffset:10,className:`z-[70] max-w-[calc(100vw-1.5rem)] overflow-hidden rounded-2xl border border-gray-200 bg-white/95 p-0 shadow-2xl backdrop-blur-md`,onOpenAutoFocus:e=>e.preventDefault(),style:g?{width:`${g}px`}:void 0,children:(0,N.jsxs)(`div`,{className:`grid min-h-[240px] grid-cols-[minmax(220px,300px)_minmax(0,1fr)]`,children:[(0,N.jsx)(`div`,{ref:o,role:`listbox`,"aria-label":f.slashSectionLabel,className:`custom-scrollbar max-h-[320px] overflow-y-auto border-r border-gray-200 p-2.5`,children:c?(0,N.jsx)(`div`,{className:`p-2 text-xs text-gray-500`,children:f.slashLoadingLabel}):(0,N.jsxs)(N.Fragment,{children:[(0,N.jsx)(`div`,{className:`mb-2 px-2 text-[11px] font-semibold uppercase tracking-wide text-gray-500`,children:f.slashSectionLabel}),l.length===0?(0,N.jsx)(`div`,{className:`px-2 text-xs text-gray-400`,children:f.slashEmptyLabel}):(0,N.jsx)(`div`,{className:`space-y-1`,children:l.map((e,t)=>{let n=t===u;return(0,N.jsxs)(`button`,{type:`button`,role:`option`,"aria-selected":n,"data-slash-index":t,onMouseEnter:()=>h(t),onClick:()=>p(e),className:`flex w-full items-start gap-2 rounded-lg px-2 py-1.5 text-left transition ${n?`bg-gray-100 text-gray-900`:`text-gray-700 hover:bg-gray-50`}`,children:[(0,N.jsx)(`span`,{className:`truncate text-xs font-semibold`,children:e.title}),(0,N.jsx)(`span`,{className:`truncate text-xs text-gray-500`,children:e.subtitle})]},e.key)})})]})}),(0,N.jsx)(`div`,{className:`min-w-0 p-2.5`,children:d?(0,N.jsxs)(`div`,{className:`space-y-3`,children:[(0,N.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,N.jsx)(`span`,{className:`inline-flex rounded-full bg-primary/10 px-2 py-0.5 text-[11px] font-semibold text-primary`,children:d.subtitle}),(0,N.jsx)(`span`,{className:`text-sm font-semibold text-gray-900`,children:d.title})]}),(0,N.jsx)(`p`,{className:`text-xs leading-5 text-gray-600`,children:d.description}),(0,N.jsx)(`div`,{className:`space-y-1`,children:d.detailLines.map(e=>(0,N.jsx)(`div`,{className:`min-w-0 break-all rounded-md bg-gray-50 px-2 py-1 text-[11px] leading-5 text-gray-600`,children:e},e))}),(0,N.jsx)(`div`,{className:`pt-1 text-[11px] text-gray-500`,children:f.slashSkillHintLabel})]}):(0,N.jsx)(`div`,{className:`text-xs text-gray-500`,children:f.slashHintLabel})})]})})]})}var mr=_(`inline-flex items-center justify-center whitespace-nowrap rounded-full text-sm font-medium ring-offset-background transition-all duration-fast focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50`,{variants:{variant:{default:`bg-primary text-primary-foreground hover:bg-primary-600 active:bg-primary-700 shadow-sm`,destructive:`bg-destructive text-destructive-foreground hover:bg-destructive/90`,outline:`border border-gray-200 bg-white hover:bg-gray-50 hover:text-gray-800 text-gray-600`,secondary:`bg-gray-100 text-gray-700 hover:bg-gray-200/80`,ghost:`hover:bg-gray-100/80 hover:text-gray-800`,link:`text-primary underline-offset-4 hover:underline`,primary:`bg-primary text-primary-foreground hover:bg-primary-600 active:bg-primary-700 shadow-sm`,subtle:`bg-gray-100 text-gray-600 hover:bg-gray-200/80`,"primary-outline":`border border-primary/30 text-primary hover:bg-primary hover:text-primary-foreground`},size:{default:`h-9 px-4 py-2`,sm:`h-8 px-3 text-xs`,lg:`h-11 px-5 text-[14px]`,xl:`h-12 px-6 text-[15px]`,icon:`h-9 w-9`}},defaultVariants:{variant:`default`,size:`default`}}),hr=P.forwardRef(({className:e,variant:t,size:n,...r},i)=>(0,N.jsx)(`button`,{className:F(mr({variant:t,size:n,className:e})),ref:i,...r}));hr.displayName=`ChatButton`;var gr=120;function _r(e){let t=e.replace(/\s+/g,` `).trim();return t.length<=gr?t:`${t.slice(0,gr-1)}…`}function vr(){return(0,N.jsx)(`span`,{"aria-hidden":`true`,"data-testid":`chat-stop-icon`,className:`block h-3 w-3 rounded-[2px] bg-gray-700 shadow-[inset_0_0_0_1px_rgba(17,24,39,0.06)]`})}function yr({contextWindow:e}){let{Tooltip:t,TooltipContent:n,TooltipProvider:r,TooltipTrigger:i}=lr,a=Math.max(0,Math.min(1,e.ratio)),o=Math.round(a*360);return(0,N.jsx)(r,{delayDuration:0,children:(0,N.jsxs)(t,{children:[(0,N.jsx)(i,{asChild:!0,children:(0,N.jsxs)(`button`,{type:`button`,className:`relative inline-flex h-8 w-8 shrink-0 items-center justify-center rounded-lg text-gray-500 transition-colors hover:bg-gray-100 hover:text-gray-700`,"aria-label":e.label,title:e.label,children:[(0,N.jsx)(`span`,{"aria-hidden":`true`,className:`absolute inset-[7px] rounded-full`,style:{background:`conic-gradient(#9ca3af ${o}deg, #e5e7eb 0deg)`}}),(0,N.jsx)(`span`,{"aria-hidden":`true`,className:`absolute inset-[10px] rounded-full bg-white`})]})}),(0,N.jsx)(n,{side:`top`,className:`max-w-[18rem]`,children:(0,N.jsxs)(`div`,{className:`space-y-1.5 text-xs`,children:[(0,N.jsxs)(`div`,{className:`flex items-center justify-between gap-5 font-semibold text-gray-800`,children:[(0,N.jsx)(`span`,{children:e.label}),(0,N.jsx)(`span`,{children:e.percentLabel})]}),e.details.map(e=>(0,N.jsxs)(`div`,{className:`flex items-center justify-between gap-5 text-gray-600`,children:[(0,N.jsx)(`span`,{children:e.label}),(0,N.jsx)(`span`,{className:`font-medium text-gray-800`,children:e.value})]},e.label))]})})]})})}function br({sendError:e,sendErrorDetailsLabel:t,isSending:n,canStopGeneration:r,sendDisabled:i,stopDisabled:a,stopHint:o,sendButtonLabel:s,stopButtonLabel:c,contextWindow:l,onSend:u,onStop:d}){let{Popover:f,PopoverContent:p,PopoverTrigger:m,Tooltip:h,TooltipContent:g,TooltipProvider:_,TooltipTrigger:v}=lr,y=e?.trim()??``,b=y?_r(y):``,x=t?.trim()||`Details`;return(0,N.jsxs)(`div`,{className:`flex shrink-0 flex-col items-end gap-1`,children:[y?(0,N.jsxs)(`div`,{className:`flex max-w-[420px] items-start justify-end gap-2 text-right`,children:[(0,N.jsx)(`div`,{className:`min-w-0 flex-1 text-[11px] text-red-600`,children:(0,N.jsx)(`span`,{className:`block truncate`,title:y,children:b})}),(0,N.jsxs)(f,{children:[(0,N.jsx)(m,{asChild:!0,children:(0,N.jsx)(`button`,{type:`button`,className:`shrink-0 rounded-full border border-red-200/80 bg-red-50 px-2 py-0.5 text-[10px] font-semibold text-red-700 transition-colors hover:bg-red-100`,children:x})}),(0,N.jsxs)(p,{align:`end`,className:`w-[min(32rem,calc(100vw-1.5rem))] border-red-100/80 p-0`,children:[(0,N.jsx)(`div`,{className:`border-b border-red-100 bg-red-50/80 px-4 py-2 text-xs font-semibold text-red-700`,children:x}),(0,N.jsx)(`pre`,{className:`max-h-80 overflow-auto whitespace-pre-wrap break-words px-4 py-3 text-xs leading-relaxed text-red-700`,children:y})]})]})]}):null,(0,N.jsxs)(`div`,{className:`flex items-center gap-2`,children:[l?(0,N.jsx)(yr,{contextWindow:l}):null,n?r?(0,N.jsx)(hr,{size:`icon`,variant:`outline`,className:`h-8 w-8 rounded-full`,"aria-label":c,onClick:()=>void d(),disabled:a,children:(0,N.jsx)(vr,{})}):(0,N.jsx)(_,{children:(0,N.jsxs)(h,{children:[(0,N.jsx)(v,{asChild:!0,children:(0,N.jsx)(`span`,{children:(0,N.jsx)(hr,{size:`icon`,variant:`outline`,className:`h-8 w-8 rounded-full`,"aria-label":c,disabled:!0,children:(0,N.jsx)(vr,{})})})}),(0,N.jsx)(g,{side:`top`,children:(0,N.jsx)(`p`,{className:`text-xs`,children:o})})]})}):(0,N.jsx)(hr,{size:`icon`,className:`h-8 w-8 rounded-full`,"aria-label":s,onClick:()=>void u(),disabled:i,children:(0,N.jsx)(Pt,{className:`h-5 w-5`})})]})]})}function xr(e,t){let n=t.trim().toLowerCase();return n?e.filter(e=>[e.label,e.key,e.description].filter(e=>typeof e==`string`&&e.trim().length>0).join(` `).toLowerCase().includes(n)):e}function Sr(e){let{Input:t,Popover:n,PopoverContent:r,PopoverTrigger:i}=lr,{picker:a}=e,o=(0,P.useRef)(null),s=(0,P.useId)(),[c,l]=(0,P.useState)(``),[u,d]=(0,P.useState)(0),f=(0,P.useMemo)(()=>new Set(a.selectedKeys),[a.selectedKeys]),p=a.selectedKeys.length,m=c.trim().length>0,h=(0,P.useMemo)(()=>{if(m)return null;let e=a.groups?.filter(e=>e.options.length>0)??[];return e.length>0?e:null},[m,a.groups]),g=(0,P.useMemo)(()=>h?h.flatMap(e=>e.options):xr(a.options,c),[h,a.options,c]);(0,P.useEffect)(()=>{d(0)},[c]),(0,P.useEffect)(()=>{d(e=>g.length===0?0:Math.min(e,g.length-1))},[g.length]),Hn({containerRef:o,activeIndex:u,itemCount:g.length,isEnabled:g.length>0,getItemSelector:e=>`[data-skill-index="${e}"]`});let _=e=>{if(f.has(e)){a.onSelectedKeysChange(a.selectedKeys.filter(t=>t!==e));return}a.onSelectedKeysChange([...a.selectedKeys,e])},v=e=>{if(g.length!==0){if(e.key===`ArrowDown`){e.preventDefault(),d(e=>Math.min(e+1,g.length-1));return}if(e.key===`ArrowUp`){e.preventDefault(),d(e=>Math.max(e-1,0));return}if(e.key===`Enter`){e.preventDefault();let t=g[u];t&&_(t.key)}}};return(0,N.jsxs)(n,{children:[(0,N.jsx)(i,{asChild:!0,children:(0,N.jsxs)(`button`,{type:`button`,"aria-haspopup":`listbox`,"aria-label":a.title,className:`relative inline-flex h-8 w-8 shrink-0 items-center justify-center rounded-lg px-0 text-xs font-medium text-gray-600 transition-colors hover:bg-gray-100 hover:text-gray-900 sm:w-auto sm:gap-1.5 sm:px-3`,children:[(0,N.jsx)(ve,{className:`h-4 w-4`}),(0,N.jsx)(`span`,{className:`hidden sm:inline`,children:a.title}),p>0?(0,N.jsx)(`span`,{className:`absolute -right-1 -top-1 flex h-[18px] min-w-[18px] items-center justify-center rounded-full bg-primary px-1 text-[10px] font-semibold leading-none text-white shadow-sm sm:static sm:ml-0.5 sm:bg-primary/10 sm:text-primary sm:shadow-none`,children:p}):null]})}),(0,N.jsxs)(r,{side:`top`,align:`start`,className:`w-[360px] p-0`,children:[(0,N.jsxs)(`div`,{className:`space-y-2 border-b border-gray-100 px-4 py-3`,children:[(0,N.jsx)(`div`,{className:`text-sm font-semibold text-gray-900`,children:a.title}),(0,N.jsxs)(`div`,{className:`relative`,children:[(0,N.jsx)(Oe,{className:`pointer-events-none absolute left-3 top-2.5 h-3.5 w-3.5 text-gray-400`}),(0,N.jsx)(t,{value:c,onChange:e=>l(e.target.value),onKeyDown:v,placeholder:a.searchPlaceholder,role:`combobox`,"aria-controls":s,"aria-expanded":`true`,"aria-autocomplete":`list`,"aria-activedescendant":g[u]?`${s}-option-${u}`:void 0,className:`h-8 rounded-lg pl-8 text-xs`})]})]}),(0,N.jsx)(`div`,{ref:o,id:s,role:`listbox`,"aria-multiselectable":`true`,className:`custom-scrollbar max-h-[320px] overflow-y-auto`,children:a.isLoading?(0,N.jsx)(`div`,{className:`p-4 text-xs text-gray-500`,children:a.loadingLabel}):g.length===0?(0,N.jsx)(`div`,{className:`p-4 text-center text-xs text-gray-500`,children:a.emptyLabel}):(0,N.jsx)(`div`,{className:`py-1`,children:(()=>{let e=h??[{key:`all-skills`,options:g}],t=0;return e.map(e=>(0,N.jsxs)(`div`,{children:[e.label?(0,N.jsx)(`div`,{className:`px-4 pb-1 pt-2 text-[11px] font-semibold uppercase tracking-wide text-gray-500`,children:e.label}):null,e.options.map(e=>{let n=t;t+=1;let r=f.has(e.key),i=n===u;return(0,N.jsxs)(`button`,{type:`button`,id:`${s}-option-${n}`,role:`option`,"aria-selected":r,"data-skill-index":n,onClick:()=>_(e.key),onMouseEnter:()=>d(n),className:`flex w-full items-center gap-3 px-4 py-2.5 text-left transition-colors ${i?`bg-gray-50`:`hover:bg-gray-50`}`,children:[(0,N.jsx)(`div`,{className:`flex h-8 w-8 shrink-0 items-center justify-center rounded-lg bg-gray-100 text-gray-500`,children:(0,N.jsx)(sn,{className:`h-4 w-4`})}),(0,N.jsxs)(`div`,{className:`min-w-0 flex-1`,children:[(0,N.jsxs)(`div`,{className:`flex items-center gap-1.5`,children:[(0,N.jsx)(`span`,{className:`truncate text-sm text-gray-900`,children:e.label}),e.badgeLabel?(0,N.jsx)(`span`,{className:`shrink-0 rounded-full bg-primary/10 px-1.5 py-0.5 text-[10px] font-medium text-primary`,children:e.badgeLabel}):null]}),(0,N.jsx)(`div`,{className:`mt-0.5 truncate text-xs text-gray-500`,children:e.description||e.key})]}),(0,N.jsx)(`div`,{className:`ml-3 shrink-0`,children:(0,N.jsx)(`span`,{className:r?`inline-flex h-5 w-5 items-center justify-center rounded-full bg-primary text-white`:`inline-flex h-5 w-5 items-center justify-center rounded-full border border-gray-300 bg-white`,children:r?(0,N.jsx)(Be,{className:`h-3 w-3`}):null})})]},e.key)})]},e.key))})()})}),a.manageHref&&a.manageLabel?(0,N.jsx)(`div`,{className:`border-t border-gray-100 px-4 py-2.5`,children:(0,N.jsxs)(`a`,{href:a.manageHref,className:`inline-flex items-center gap-1.5 text-xs font-medium text-primary transition-colors hover:text-primary/80`,children:[a.manageLabel,(0,N.jsx)(Qe,{className:`h-3 w-3`})]})}):null]})]})}function Cr({icon:e}){return e===`sparkles`?(0,N.jsx)(ot,{className:`h-3.5 w-3.5 shrink-0 text-primary`}):e===`brain`?(0,N.jsx)(Ft,{className:`h-3.5 w-3.5 shrink-0 text-gray-500`}):null}function wr({icon:e}){return e===`paperclip`?(0,N.jsx)(an,{className:`h-4 w-4`}):(0,N.jsx)(Cr,{icon:e})}var Tr={model:`min-w-0 flex-1 sm:min-w-[220px] sm:flex-none`,"session-type":`shrink-0`,thinking:`shrink-0`},Er={model:`w-[min(18rem,calc(100vw-1rem))] sm:w-[320px]`,"session-type":`w-[220px]`,thinking:`w-[180px]`};function Dr(e){return e.key===`model`&&e.selectedLabel&&e.selectedLabel.split(`/`).slice(1).join(`/`).trim()||e.selectedLabel}function Or({item:e}){let{Select:t,SelectContent:n,SelectGroup:r,SelectItem:i,SelectLabel:a,SelectSeparator:o,SelectTrigger:s,SelectValue:c}=lr,l=e.groups?.filter(e=>e.options.length>0)??(e.options.length>0?[{key:`${e.key}-default`,options:e.options}]:[]),u=l.some(e=>e.options.length>0),d=Dr(e);return(0,N.jsxs)(t,{value:e.value,onValueChange:e.onValueChange,disabled:e.disabled,children:[(0,N.jsx)(s,{className:`h-8 w-auto rounded-lg border-0 bg-transparent px-2 text-xs font-medium text-gray-600 shadow-none hover:bg-gray-100 focus:ring-0 sm:px-3 ${Tr[e.key]??``}`,children:e.selectedLabel?(0,N.jsxs)(`div`,{className:`flex min-w-0 items-center gap-2 text-left`,children:[(0,N.jsx)(Cr,{icon:e.icon}),(0,N.jsx)(`span`,{className:`truncate text-xs font-semibold text-gray-700 sm:hidden`,children:d}),(0,N.jsx)(`span`,{className:`hidden truncate text-xs font-semibold text-gray-700 sm:inline`,children:e.selectedLabel})]}):e.loading?(0,N.jsx)(`div`,{className:`h-3 w-24 animate-pulse rounded bg-gray-200`}):(0,N.jsx)(c,{placeholder:e.placeholder})}),(0,N.jsxs)(n,{className:Er[e.key]??``,children:[u?null:e.loading?(0,N.jsxs)(`div`,{className:`space-y-2 px-3 py-2`,children:[(0,N.jsx)(`div`,{className:`h-3 w-36 animate-pulse rounded bg-gray-200`}),(0,N.jsx)(`div`,{className:`h-3 w-28 animate-pulse rounded bg-gray-200`}),(0,N.jsx)(`div`,{className:`h-3 w-32 animate-pulse rounded bg-gray-200`})]}):e.emptyLabel?(0,N.jsx)(`div`,{className:`px-3 py-2 text-xs text-gray-500`,children:e.emptyLabel}):null,l.map((e,t)=>(0,N.jsxs)(`div`,{children:[t>0?(0,N.jsx)(o,{}):null,(0,N.jsxs)(r,{children:[e.label?(0,N.jsx)(a,{children:e.label}):null,e.options.map(e=>(0,N.jsx)(i,{value:e.value,className:`py-2`,children:e.description?(0,N.jsxs)(`div`,{className:`flex min-w-0 flex-col gap-0.5`,children:[(0,N.jsx)(`span`,{className:`truncate text-xs font-semibold text-gray-800`,children:e.label}),(0,N.jsx)(`span`,{className:`truncate text-[11px] text-gray-500`,children:e.description})]}):(0,N.jsx)(`span`,{className:`truncate text-xs font-semibold text-gray-800`,children:e.label})},e.value))]})]},e.key))]})]})}function kr({actions:e,accessories:t,selects:n,skillPicker:r}){let{Tooltip:i,TooltipContent:a,TooltipProvider:o,TooltipTrigger:s}=lr;return(0,N.jsxs)(`div`,{className:`flex items-center justify-between gap-2 px-3 pb-3`,children:[(0,N.jsxs)(`div`,{className:`flex min-w-0 flex-1 items-center gap-1 overflow-hidden`,children:[r?(0,N.jsx)(Sr,{picker:r}):null,n.map(e=>(0,N.jsx)(Or,{item:e},e.key)),t?.map(e=>{let t=(0,N.jsxs)(`button`,{type:`button`,className:`inline-flex items-center rounded-lg py-1.5 text-xs font-medium text-gray-600 transition-colors hover:bg-gray-100 hover:text-gray-900 disabled:cursor-not-allowed disabled:text-gray-400 ${e.iconOnly?`h-8 w-8 justify-center px-0`:`gap-1.5 px-3`}`,onClick:e.onClick,disabled:e.disabled,"aria-label":e.label,children:[(0,N.jsx)(wr,{icon:e.icon}),e.iconOnly?null:(0,N.jsx)(`span`,{children:e.label})]});return e.tooltip?(0,N.jsx)(o,{children:(0,N.jsxs)(i,{children:[(0,N.jsx)(s,{asChild:!0,children:e.disabled?(0,N.jsx)(`span`,{className:`inline-flex`,children:t}):t}),(0,N.jsx)(a,{side:`top`,children:(0,N.jsx)(`p`,{className:`text-xs`,children:e.tooltip})})]})},e.key):(0,N.jsx)(`div`,{children:t},e.key)})]}),(0,N.jsx)(br,{...e})]})}var Ar=(0,P.createContext)(null);function jr(e,t){let n=null;return e!=null&&(n=e[1]),{getTheme:function(){return t??(n==null?null:n.getTheme())}}}function Mr(){let e=(0,P.useContext)(Ar);return e??function(e,...t){let n=new URL(`https://lexical.dev/docs/error`),r=new URLSearchParams;r.append(`code`,e);for(let e of t)r.append(`v`,e);throw n.search=r.toString(),Error(`Minified Lexical error #${e}; visit ${n.toString()} for the full message or use the non-minified dev environment for full errors and additional helpful warnings.`)}(8),e}function I(e,...t){let n=new URL(`https://lexical.dev/docs/error`),r=new URLSearchParams;r.append(`code`,e);for(let e of t)r.append(`v`,e);throw n.search=r.toString(),Error(`Minified Lexical error #${e}; visit ${n.toString()} for the full message or use the non-minified dev environment for full errors and additional helpful warnings.`)}function Nr(e,...t){let n=new URL(`https://lexical.dev/docs/error`),r=new URLSearchParams;r.append(`code`,e);for(let e of t)r.append(`v`,e);n.search=r.toString(),console.warn(`Minified Lexical warning #${e}; visit ${n.toString()} for the full message or use the non-minified dev environment for full errors and additional helpful warnings.`)}var Pr=typeof window<`u`&&window.document!==void 0&&window.document.createElement!==void 0,Fr=Pr&&`documentMode`in document?document.documentMode:null,Ir=Pr&&/Mac|iPod|iPhone|iPad/.test(navigator.platform),Lr=Pr&&/^(?!.*Seamonkey)(?=.*Firefox).*/i.test(navigator.userAgent),Rr=!(!Pr||!(`InputEvent`in window)||Fr)&&`getTargetRanges`in new window.InputEvent(`input`),zr=Pr&&/iPad|iPhone|iPod/.test(navigator.userAgent)&&!window.MSStream,Br=Pr&&/Android/.test(navigator.userAgent),Vr=Pr&&/Version\/[\d.]+.*Safari/.test(navigator.userAgent)&&!Br,Hr=Pr&&/^(?=.*Chrome).*/i.test(navigator.userAgent),Ur=Pr&&Br&&Hr,Wr=Pr&&/AppleWebKit\/[\d.]+/.test(navigator.userAgent)&&Ir&&!Hr,Gr=0,Kr=1,qr=2,Jr=1,Yr=2,Xr=3,Zr=4,Qr=5,$r=6,ei=Vr||zr||Wr?`\xA0`:``,ti=`
|
|
1
|
+
import{_ as e,a as t,d as n,f as r,g as i,h as a,i as o,m as s,n as c,p as l,t as u,u as d}from"./i18n-DnTGDIRw.js";import{At as f,It as p,Kt as m,Lt as h,Mt as g,Nt as _,Pt as v,Rt as y,V as b,Vt as x,_t as S,at as C,bt as w,f as T,h as E,it as D,jt as O,m as ee,n as k,nt as te,p as A,rt as ne,st as j,t as re,v as ie,xt as ae,y as oe,yt as se}from"./api-D2xRKmZd.js";import{a as ce,i as le,n as ue,o as de,r as fe,t as pe}from"./dialog-C3D7Be0p.js";import{t as M}from"./createLucideIcon-BLMK3QUd.js";import{_ as me,c as he,d as ge,f as _e,g as ve,h as ye,l as be,m as xe,n as Se,p as Ce,s as we,u as Te,v as Ee}from"./theme-provider-0hxjiPc_.js";import{n as De,t as Oe}from"./search-CLd7m0M7.js";import{t as ke}from"./book-open-DDlN5MvX.js";import{D as Ae,O as je,_ as Me,b as Ne,c as Pe,d as Fe,f as Ie,g as Le,h as Re,i as ze,k as Be,l as Ve,m as He,n as Ue,o as We,p as Ge,r as Ke,s as qe,t as Je,u as Ye,v as Xe,y as Ze}from"./select-CJ0wbo3D.js";import{t as Qe}from"./external-link-DwfSfTLB.js";import{t as $e}from"./folder-CeJKPx5P.js";import{n as et,t as tt}from"./logos-C4sYP1Vl.js";import{t as nt}from"./loader-circle-fd-vQKtW.js";import{t as rt}from"./plus-D8eKFY7h.js";import{t as it}from"./refresh-ccw-ByVwmnN_.js";import{t as at}from"./settings-drbWqzA4.js";import{t as ot}from"./sparkles-DVfeSVJQ.js";import{t as st}from"./trash-2-CBsHCfqq.js";import{t as ct}from"./x-CM-XDMpk.js";import{i as lt}from"./doc-browser-context-BJuMaI3o.js";import{n as ut}from"./doc-browser-C8FM5fC0.js";import{n as dt,t as ft}from"./use-viewport-layout-D1XzKeip.js";import{m as pt}from"./use-config-38Ur-89i.js";import{a as mt,c as ht,i as gt,n as _t,o as vt,r as yt,s as bt,t as xt}from"./popover-B86Dbfhf.js";import{t as St}from"./logo-badge-KAe-7d8c.js";import{a as Ct,c as wt,i as Tt,l as Et,n as Dt,o as Ot,r as kt,s as At,t as jt}from"./tooltip-Cj4yA0gH.js";import{t as Mt}from"./skeleton-BK1SOSRA.js";var Nt=M(`ArrowUpRight`,[[`path`,{d:`M7 7h10v10`,key:`1tivn9`}],[`path`,{d:`M7 17 17 7`,key:`1vkiza`}]]),Pt=M(`ArrowUp`,[[`path`,{d:`m5 12 7-7 7 7`,key:`hav0vg`}],[`path`,{d:`M12 19V5`,key:`x0mq9r`}]]),Ft=M(`Brain`,[[`path`,{d:`M12 5a3 3 0 1 0-5.997.125 4 4 0 0 0-2.526 5.77 4 4 0 0 0 .556 6.588A4 4 0 1 0 12 18Z`,key:`l5xja`}],[`path`,{d:`M12 5a3 3 0 1 1 5.997.125 4 4 0 0 1 2.526 5.77 4 4 0 0 1-.556 6.588A4 4 0 1 1 12 18Z`,key:`ep3f8r`}],[`path`,{d:`M15 13a4.5 4.5 0 0 1-3-4 4.5 4.5 0 0 1-3 4`,key:`1p4c4q`}],[`path`,{d:`M17.599 6.5a3 3 0 0 0 .399-1.375`,key:`tmeiqw`}],[`path`,{d:`M6.003 5.125A3 3 0 0 0 6.401 6.5`,key:`105sqy`}],[`path`,{d:`M3.477 10.896a4 4 0 0 1 .585-.396`,key:`ql3yin`}],[`path`,{d:`M19.938 10.5a4 4 0 0 1 .585.396`,key:`1qfode`}],[`path`,{d:`M6 18a4 4 0 0 1-1.967-.516`,key:`2e4loj`}],[`path`,{d:`M19.967 17.484A4 4 0 0 1 18 18`,key:`159ez6`}]]),It=M(`ChevronRight`,[[`path`,{d:`m9 18 6-6-6-6`,key:`mthhwq`}]]),Lt=M(`CodeXml`,[[`path`,{d:`m18 16 4-4-4-4`,key:`1inbqp`}],[`path`,{d:`m6 8-4 4 4 4`,key:`15zrgr`}],[`path`,{d:`m14.5 4-5 16`,key:`e7oirm`}]]),Rt=M(`Copy`,[[`rect`,{width:`14`,height:`14`,x:`8`,y:`8`,rx:`2`,ry:`2`,key:`17jyea`}],[`path`,{d:`M4 16c-1.1 0-2-.9-2-2V4c0-1.1.9-2 2-2h10c1.1 0 2 .9 2 2`,key:`zix9uf`}]]),zt=M(`Ellipsis`,[[`circle`,{cx:`12`,cy:`12`,r:`1`,key:`41hilf`}],[`circle`,{cx:`19`,cy:`12`,r:`1`,key:`1wjl8i`}],[`circle`,{cx:`5`,cy:`12`,r:`1`,key:`1pcz8c`}]]),Bt=M(`FileArchive`,[[`path`,{d:`M10 12v-1`,key:`v7bkov`}],[`path`,{d:`M10 18v-2`,key:`1cjy8d`}],[`path`,{d:`M10 7V6`,key:`dljcrl`}],[`path`,{d:`M14 2v4a2 2 0 0 0 2 2h4`,key:`tnqrlb`}],[`path`,{d:`M15.5 22H18a2 2 0 0 0 2-2V7l-5-5H6a2 2 0 0 0-2 2v16a2 2 0 0 0 .274 1.01`,key:`gkbcor`}],[`circle`,{cx:`10`,cy:`20`,r:`2`,key:`1xzdoj`}]]),Vt=M(`FileAudio2`,[[`path`,{d:`M4 22h14a2 2 0 0 0 2-2V7l-5-5H6a2 2 0 0 0-2 2v2`,key:`17k7jt`}],[`path`,{d:`M14 2v4a2 2 0 0 0 2 2h4`,key:`tnqrlb`}],[`circle`,{cx:`3`,cy:`17`,r:`1`,key:`vo6nti`}],[`path`,{d:`M2 17v-3a4 4 0 0 1 8 0v3`,key:`1ggdre`}],[`circle`,{cx:`9`,cy:`17`,r:`1`,key:`bc1fq4`}]]),Ht=M(`FileCode2`,[[`path`,{d:`M4 22h14a2 2 0 0 0 2-2V7l-5-5H6a2 2 0 0 0-2 2v4`,key:`1pf5j1`}],[`path`,{d:`M14 2v4a2 2 0 0 0 2 2h4`,key:`tnqrlb`}],[`path`,{d:`m5 12-3 3 3 3`,key:`oke12k`}],[`path`,{d:`m9 18 3-3-3-3`,key:`112psh`}]]),Ut=M(`FileImage`,[[`path`,{d:`M15 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7Z`,key:`1rqfz7`}],[`path`,{d:`M14 2v4a2 2 0 0 0 2 2h4`,key:`tnqrlb`}],[`circle`,{cx:`10`,cy:`12`,r:`2`,key:`737tya`}],[`path`,{d:`m20 17-1.296-1.296a2.41 2.41 0 0 0-3.408 0L9 22`,key:`wt3hpn`}]]),Wt=M(`FileJson2`,[[`path`,{d:`M4 22h14a2 2 0 0 0 2-2V7l-5-5H6a2 2 0 0 0-2 2v4`,key:`1pf5j1`}],[`path`,{d:`M14 2v4a2 2 0 0 0 2 2h4`,key:`tnqrlb`}],[`path`,{d:`M4 12a1 1 0 0 0-1 1v1a1 1 0 0 1-1 1 1 1 0 0 1 1 1v1a1 1 0 0 0 1 1`,key:`fq0c9t`}],[`path`,{d:`M8 18a1 1 0 0 0 1-1v-1a1 1 0 0 1 1-1 1 1 0 0 1-1-1v-1a1 1 0 0 0-1-1`,key:`4gibmv`}]]),Gt=M(`FileSpreadsheet`,[[`path`,{d:`M15 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7Z`,key:`1rqfz7`}],[`path`,{d:`M14 2v4a2 2 0 0 0 2 2h4`,key:`tnqrlb`}],[`path`,{d:`M8 13h2`,key:`yr2amv`}],[`path`,{d:`M14 13h2`,key:`un5t4a`}],[`path`,{d:`M8 17h2`,key:`2yhykz`}],[`path`,{d:`M14 17h2`,key:`10kma7`}]]),Kt=M(`FileText`,[[`path`,{d:`M15 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7Z`,key:`1rqfz7`}],[`path`,{d:`M14 2v4a2 2 0 0 0 2 2h4`,key:`tnqrlb`}],[`path`,{d:`M10 9H8`,key:`b1mrlr`}],[`path`,{d:`M16 13H8`,key:`t4e002`}],[`path`,{d:`M16 17H8`,key:`z1uh3a`}]]),qt=M(`FileVideo2`,[[`path`,{d:`M4 22h14a2 2 0 0 0 2-2V7l-5-5H6a2 2 0 0 0-2 2v4`,key:`1pf5j1`}],[`path`,{d:`M14 2v4a2 2 0 0 0 2 2h4`,key:`tnqrlb`}],[`rect`,{width:`8`,height:`6`,x:`2`,y:`12`,rx:`1`,key:`1a6c1e`}],[`path`,{d:`m10 15.5 4 2.5v-6l-4 2.5`,key:`t7cp39`}]]),Jt=M(`File`,[[`path`,{d:`M15 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7Z`,key:`1rqfz7`}],[`path`,{d:`M14 2v4a2 2 0 0 0 2 2h4`,key:`tnqrlb`}]]),Yt=M(`FolderGit2`,[[`path`,{d:`M9 20H4a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h3.9a2 2 0 0 1 1.69.9l.81 1.2a2 2 0 0 0 1.67.9H20a2 2 0 0 1 2 2v5`,key:`1w6njk`}],[`circle`,{cx:`13`,cy:`12`,r:`2`,key:`1j92g6`}],[`path`,{d:`M18 19c-2.8 0-5-2.2-5-5v8`,key:`pkpw2h`}],[`circle`,{cx:`20`,cy:`19`,r:`2`,key:`1obnsp`}]]),Xt=M(`FolderOpen`,[[`path`,{d:`m6 14 1.5-2.9A2 2 0 0 1 9.24 10H20a2 2 0 0 1 1.94 2.5l-1.54 6a2 2 0 0 1-1.95 1.5H4a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h3.9a2 2 0 0 1 1.69.9l.81 1.2a2 2 0 0 0 1.67.9H18a2 2 0 0 1 2 2v2`,key:`usdka0`}]]),Zt=M(`FolderTree`,[[`path`,{d:`M20 10a1 1 0 0 0 1-1V6a1 1 0 0 0-1-1h-2.5a1 1 0 0 1-.8-.4l-.9-1.2A1 1 0 0 0 15 3h-2a1 1 0 0 0-1 1v5a1 1 0 0 0 1 1Z`,key:`hod4my`}],[`path`,{d:`M20 21a1 1 0 0 0 1-1v-3a1 1 0 0 0-1-1h-2.9a1 1 0 0 1-.88-.55l-.42-.85a1 1 0 0 0-.92-.6H13a1 1 0 0 0-1 1v5a1 1 0 0 0 1 1Z`,key:`w4yl2u`}],[`path`,{d:`M3 5a2 2 0 0 0 2 2h3`,key:`f2jnh7`}],[`path`,{d:`M3 3v13a2 2 0 0 0 2 2h3`,key:`k8epm1`}]]),Qt=M(`FolderUp`,[[`path`,{d:`M20 20a2 2 0 0 0 2-2V8a2 2 0 0 0-2-2h-7.9a2 2 0 0 1-1.69-.9L9.6 3.9A2 2 0 0 0 7.93 3H4a2 2 0 0 0-2 2v13a2 2 0 0 0 2 2Z`,key:`1kt360`}],[`path`,{d:`M12 10v6`,key:`1bos4e`}],[`path`,{d:`m9 13 3-3 3 3`,key:`1pxg3c`}]]),$t=M(`FolderX`,[[`path`,{d:`M20 20a2 2 0 0 0 2-2V8a2 2 0 0 0-2-2h-7.9a2 2 0 0 1-1.69-.9L9.6 3.9A2 2 0 0 0 7.93 3H4a2 2 0 0 0-2 2v13a2 2 0 0 0 2 2Z`,key:`1kt360`}],[`path`,{d:`m9.5 10.5 5 5`,key:`ra9qjz`}],[`path`,{d:`m14.5 10.5-5 5`,key:`l2rkpq`}]]),en=M(`GitBranch`,[[`line`,{x1:`6`,x2:`6`,y1:`3`,y2:`15`,key:`17qcm7`}],[`circle`,{cx:`18`,cy:`6`,r:`3`,key:`1h7g24`}],[`circle`,{cx:`6`,cy:`18`,r:`3`,key:`fqmcym`}],[`path`,{d:`M18 9a9 9 0 0 1-9 9`,key:`n2h4wq`}]]),tn=M(`House`,[[`path`,{d:`M15 21v-8a1 1 0 0 0-1-1h-4a1 1 0 0 0-1 1v8`,key:`5wwlr5`}],[`path`,{d:`M3 10a2 2 0 0 1 .709-1.528l7-5.999a2 2 0 0 1 2.582 0l7 5.999A2 2 0 0 1 21 10v9a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2z`,key:`1d0kgt`}]]),nn=M(`MessageSquareText`,[[`path`,{d:`M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z`,key:`1lielz`}],[`path`,{d:`M13 8H7`,key:`14i4kc`}],[`path`,{d:`M17 12H7`,key:`16if0g`}]]),rn=M(`Minus`,[[`path`,{d:`M5 12h14`,key:`1ays0h`}]]),an=M(`Paperclip`,[[`path`,{d:`m21.44 11.05-9.19 9.19a6 6 0 0 1-8.49-8.49l8.57-8.57A4 4 0 1 1 18 8.84l-8.59 8.57a2 2 0 0 1-2.83-2.83l8.49-8.48`,key:`1u3ebp`}]]),on=M(`Pencil`,[[`path`,{d:`M21.174 6.812a1 1 0 0 0-3.986-3.987L3.842 16.174a2 2 0 0 0-.5.83l-1.321 4.352a.5.5 0 0 0 .623.622l4.353-1.32a2 2 0 0 0 .83-.497z`,key:`1a8usu`}],[`path`,{d:`m15 5 4 4`,key:`1mk7zo`}]]),sn=M(`Puzzle`,[[`path`,{d:`M15.39 4.39a1 1 0 0 0 1.68-.474 2.5 2.5 0 1 1 3.014 3.015 1 1 0 0 0-.474 1.68l1.683 1.682a2.414 2.414 0 0 1 0 3.414L19.61 15.39a1 1 0 0 1-1.68-.474 2.5 2.5 0 1 0-3.014 3.015 1 1 0 0 1 .474 1.68l-1.683 1.682a2.414 2.414 0 0 1-3.414 0L8.61 19.61a1 1 0 0 0-1.68.474 2.5 2.5 0 1 1-3.014-3.015 1 1 0 0 0 .474-1.68l-1.683-1.682a2.414 2.414 0 0 1 0-3.414L4.39 8.61a1 1 0 0 1 1.68.474 2.5 2.5 0 1 0 3.014-3.015 1 1 0 0 1-.474-1.68l1.683-1.682a2.414 2.414 0 0 1 3.414 0z`,key:`w46dr5`}]]),cn=M(`Terminal`,[[`polyline`,{points:`4 17 10 11 4 5`,key:`akl6gq`}],[`line`,{x1:`12`,x2:`20`,y1:`19`,y2:`19`,key:`q2wloq`}]]),ln=M(`TriangleAlert`,[[`path`,{d:`m21.73 18-8-14a2 2 0 0 0-3.48 0l-8 14A2 2 0 0 0 4 21h16a2 2 0 0 0 1.73-3`,key:`wmoenq`}],[`path`,{d:`M12 9v4`,key:`juzpu7`}],[`path`,{d:`M12 17h.01`,key:`p32p05`}]]),un=M(`User`,[[`path`,{d:`M19 21v-2a4 4 0 0 0-4-4H9a4 4 0 0 0-4 4v2`,key:`975kel`}],[`circle`,{cx:`12`,cy:`7`,r:`4`,key:`17ys0d`}]]),N=l();function dn({isProjectFirstView:e,onSelectMode:t}){return(0,N.jsxs)(`div`,{className:`flex items-center gap-1.5 text-[11px]`,children:[(0,N.jsx)(`button`,{type:`button`,"aria-pressed":!e,onClick:()=>t(`time-first`),className:d(`transition-colors`,e?`text-gray-400 hover:text-gray-600`:`font-medium text-gray-600`),children:o(`chatSidebarViewTime`)}),(0,N.jsx)(`span`,{className:`text-gray-300`,children:`/`}),(0,N.jsx)(`button`,{type:`button`,"aria-pressed":e,onClick:()=>t(`project-first`),className:d(`transition-colors`,e?`font-medium text-gray-600`:`text-gray-400 hover:text-gray-600`),children:o(`chatSidebarViewProject`)})]})}var fn={wx:`weixin`,lark:`feishu`},pn={cron:{icon:`cron`}},mn={codex:`chatSessionTypeCodex`,claude:`chatSessionTypeClaude`};function hn(e){return e?.trim().toLowerCase()??``}function gn(e){return e.split(/[-_]+/g).filter(Boolean).map(e=>e.charAt(0).toUpperCase()+e.slice(1)).join(` `)}function _n(e,t){let n=hn(e);if(!n||n===`native`)return null;let r=t.find(e=>hn(e.value)===n);return r?.label.trim()?r.label.trim():gn(n)}function vn(e,t){let n=hn(e);return!n||n===`native`?null:t.find(e=>hn(e.value)===n)??null}function yn(e){let t=hn(e);if(!t)return null;let n=fn[t]??t;return tt(n)?n:null}function bn(e,t){let n=yn(e.channel??``);if(n)return{icon:{kind:`channel-logo`,channel:n},label:null};let r=pn[hn(e.type)];if(r)return{icon:{kind:`symbol`,icon:r.icon},label:null};let i=hn(e.sessionType),a=vn(i,t);if(a?.icon?.src?.trim())return{icon:{kind:`runtime-image`,src:a.icon.src,alt:a.icon.alt??null,name:a.label},label:null};let s=mn[i];return s?{icon:null,label:o(s)}:{icon:null,label:a?.label?.trim()||_n(e.sessionType,t)}}var xn=`app://`;function Sn(e){let t=e.trim().replace(/^\/+/,``);if(!t)return null;let n=t.split(`/`);return n.some(e=>e.trim().length===0||e===`.`||e===`..`)?null:n.join(`/`)}function Cn(e){let t=e.trim();if(!t)return null;if(!t.startsWith(xn))return t;let n=Sn(t.slice(6));return n?`/${n}`:null}function wn({icon:e,className:t}){if(e.kind===`channel-logo`)return(0,N.jsx)(Tn,{channel:e.channel,className:t});if(e.kind===`runtime-image`){let n=Cn(e.src);return(0,N.jsx)(St,{name:e.name?.trim()||e.alt?.trim()||`runtime`,src:n??void 0,className:d(`h-[1.125rem] w-[1.125rem]`,t),imgClassName:`h-full w-full object-contain`,fallback:(0,N.jsx)(me,{className:d(`h-3 w-3 text-gray-500`,t)})})}return(0,N.jsx)(Ee,{className:d(`h-3.5 w-3.5`,t)})}function Tn({channel:e,className:t}){return(0,N.jsx)(St,{name:e,src:tt(e),className:d(`h-[1.125rem] w-[1.125rem]`,t),imgClassName:`h-full w-full object-contain`,fallback:(0,N.jsx)(me,{className:`h-3 w-3 text-gray-500`})})}function En(e){let{option:t,onSelect:n}=e,r=t.ready===!1?t.reasonMessage?.trim()||o(`statusSetup`):null;return(0,N.jsx)(`button`,{type:`button`,onClick:n,className:`w-full rounded-2xl px-3 py-2.5 text-left transition-colors hover:bg-gray-50`,children:(0,N.jsx)(`div`,{className:`flex items-start gap-3`,children:(0,N.jsxs)(`div`,{className:`flex min-w-0 flex-1 items-start gap-2.5`,children:[t.icon?.src?(0,N.jsx)(`span`,{className:`inline-flex h-5 w-5 shrink-0 items-center justify-center pt-0.5`,children:(0,N.jsx)(wn,{icon:{kind:`runtime-image`,src:t.icon.src,alt:t.icon.alt??null,name:t.label}})}):(0,N.jsx)(`span`,{className:`inline-flex h-5 w-5 shrink-0 items-center justify-center pt-0.5 text-gray-400`,children:(0,N.jsx)(me,{className:`h-4 w-4`})}),(0,N.jsxs)(`div`,{className:`min-w-0 flex-1`,children:[(0,N.jsxs)(`div`,{className:`flex items-center justify-between gap-3`,children:[(0,N.jsx)(`div`,{className:`truncate text-[13px] font-semibold text-gray-900`,children:t.label}),(0,N.jsxs)(`span`,{className:d(`inline-flex shrink-0 items-center gap-1.5 text-[11px] font-medium`,t.ready===!1?`text-amber-700`:`text-emerald-600`),children:[(0,N.jsx)(`span`,{className:d(`h-1.5 w-1.5 rounded-full`,t.ready===!1?`bg-amber-500`:`bg-emerald-500`)}),t.ready===!1?o(`statusSetup`):o(`statusReady`)]})]}),r?(0,N.jsx)(`div`,{className:`mt-1 pr-4 text-[11px] leading-4 text-gray-500`,children:r}):null]})]})})})}var P=e(s(),1);function Dn(e,t){return t.some(t=>t.value===e)?e:t[0]?.value??e}function On(e){let{groups:t,defaultSessionType:n,sessionTypeOptions:r,renderSessionItem:i,onCreateSession:a}=e,[s,c]=(0,P.useState)(null),l=(0,P.useMemo)(()=>Dn(n,r),[n,r]),u=r.length>1;return(0,N.jsx)(`div`,{className:`space-y-3`,children:t.map(e=>{let t=`${o(`chatSidebarNewTask`)} · ${e.projectName}`;return(0,N.jsxs)(`div`,{children:[(0,N.jsxs)(`div`,{className:`flex items-center justify-between gap-2 px-2 py-0.5`,children:[(0,N.jsxs)(`div`,{className:`flex min-w-0 items-center gap-1.5`,children:[(0,N.jsx)(`div`,{className:`truncate text-[11px] font-medium uppercase tracking-wider text-gray-500`,title:e.projectRoot,children:e.projectName}),(0,N.jsx)(`span`,{className:`shrink-0 text-[10px] text-gray-400`,children:e.items.length})]}),u?(0,N.jsxs)(xt,{open:s===e.projectRoot,onOpenChange:t=>{c(t?e.projectRoot:null)},children:[(0,N.jsx)(yt,{asChild:!0,children:(0,N.jsx)(g,{type:`button`,variant:`ghost`,size:`icon`,className:`h-7 w-7 shrink-0 rounded-lg text-gray-400 hover:bg-white hover:text-gray-900`,"aria-label":t,title:t,children:(0,N.jsx)(rt,{className:`h-3.5 w-3.5`})})}),(0,N.jsxs)(_t,{align:`end`,className:`w-56 rounded-2xl border border-gray-200/80 bg-white p-1.5 shadow-[0_24px_60px_-28px_rgba(15,23,42,0.38)]`,children:[(0,N.jsx)(`div`,{className:`px-3 pb-1 pt-2 text-[10px] font-semibold uppercase tracking-[0.18em] text-gray-400`,children:o(`chatSessionTypeLabel`)}),(0,N.jsx)(`div`,{className:`space-y-1`,children:r.map(t=>(0,N.jsx)(En,{option:t,onSelect:()=>{a(t.value,e.projectRoot),c(null)}},`${e.projectRoot}:${t.value}`))})]})]}):(0,N.jsx)(g,{type:`button`,variant:`ghost`,size:`icon`,className:`h-7 w-7 shrink-0 rounded-lg text-gray-400 hover:bg-white hover:text-gray-900`,onClick:()=>a(l,e.projectRoot),"aria-label":t,title:t,children:(0,N.jsx)(rt,{className:`h-3.5 w-3.5`})})]}),(0,N.jsx)(`div`,{className:`space-y-0.5 pl-2`,children:e.items.map(i)})]},e.projectRoot)})})}var kn=[[`bg-amber-100`,`text-amber-700`],[`bg-emerald-100`,`text-emerald-700`],[`bg-blue-100`,`text-blue-700`],[`bg-rose-100`,`text-rose-700`],[`bg-cyan-100`,`text-cyan-700`],[`bg-violet-100`,`text-violet-700`]];function An(e){let t=0;for(let n=0;n<e.length;n+=1)t=(t<<5)-t+e.charCodeAt(n),t|=0;return Math.abs(t)}function jn({agentId:e,displayName:t,avatarUrl:n,className:r}){let i=t?.trim()||e,[a,o]=kn[An(e)%kn.length]??kn[0];return n?.trim()?(0,N.jsx)(`img`,{src:n,alt:t?.trim()||e,className:d(`rounded-full object-cover`,r)}):(0,N.jsx)(`div`,{className:d(`rounded-full flex items-center justify-center font-semibold`,a,o,r),"aria-label":t?.trim()||e,children:e.trim().toLowerCase()===`main`?(0,N.jsx)(me,{className:`h-[55%] w-[55%]`,strokeWidth:2.4}):(i.trim()||`A`).slice(0,1).toUpperCase()})}function Mn({status:e,className:t}){let n=o(e===`running`?`sessionsRunStatusRunning`:`sessionsRunStatusQueued`);return(0,N.jsxs)(`span`,{className:d(`inline-flex h-3.5 w-3.5 items-center justify-center text-gray-400`,t),title:n,"aria-label":n,children:[(0,N.jsx)(nt,{className:`h-3 w-3 animate-spin`}),(0,N.jsx)(`span`,{className:`sr-only`,children:n})]})}function Nn({session:e,draftLabel:t,isSaving:n,onDraftLabelChange:r,onSave:i,onCancel:a}){return(0,N.jsxs)(`div`,{className:`space-y-2`,children:[(0,N.jsx)(O,{value:t,onChange:e=>r(e.target.value),onKeyDown:e=>{e.key===`Enter`?(e.preventDefault(),i()):e.key===`Escape`&&(e.preventDefault(),a())},placeholder:o(`sessionsLabelPlaceholder`),className:`h-8 rounded-lg border-gray-300 bg-white text-xs`,autoFocus:!0,disabled:n}),(0,N.jsxs)(`div`,{className:`flex items-center justify-between gap-2`,children:[(0,N.jsx)(`div`,{className:`min-w-0 text-[11px] text-gray-400 truncate`,children:e.key}),(0,N.jsxs)(`div`,{className:`flex items-center gap-1`,children:[(0,N.jsx)(g,{type:`button`,size:`icon`,variant:`ghost`,className:`h-7 w-7 rounded-lg text-gray-500 hover:bg-white hover:text-gray-900`,onClick:()=>void i(),disabled:n,"aria-label":o(`save`),children:(0,N.jsx)(Be,{className:`h-3.5 w-3.5`})}),(0,N.jsx)(g,{type:`button`,size:`icon`,variant:`ghost`,className:`h-7 w-7 rounded-lg text-gray-500 hover:bg-white hover:text-gray-900`,onClick:a,disabled:n,"aria-label":o(`cancel`),children:(0,N.jsx)(ct,{className:`h-3.5 w-3.5`})})]})]})]})}function Pn({session:e,active:t,showUnreadDot:n,runStatus:r,context:i,title:a,agentId:s,agentLabel:c,agentAvatarUrl:l,childSessionCount:f=0,onSelect:p,onOpenChildSessions:m,onStartEditing:h}){return(0,N.jsxs)(`div`,{className:`group/session relative`,children:[(0,N.jsxs)(`button`,{type:`button`,onClick:p,className:`w-full text-left`,children:[(0,N.jsxs)(`div`,{className:d(`grid grid-cols-[minmax(0,1fr)_auto] items-start gap-2`,f>0&&m?`pr-14`:`pr-6`),children:[(0,N.jsxs)(`span`,{className:`flex min-w-0 items-center gap-1.5`,children:[s?.trim()&&s.trim().toLowerCase()!==`main`?(0,N.jsx)(jn,{agentId:s,displayName:c,avatarUrl:l,className:`h-5 w-5 shrink-0`}):null,(0,N.jsx)(`span`,{className:`truncate font-medium`,children:a}),i.label?(0,N.jsx)(`span`,{className:d(`shrink-0 rounded-full border px-1.5 py-0.5 text-[10px] font-semibold leading-none`,t?`border-gray-300 bg-white/80 text-gray-700`:`border-gray-200 bg-gray-100 text-gray-500`),children:i.label}):null,i.icon?(0,N.jsx)(`span`,{className:`inline-flex h-[1.125rem] w-[1.125rem] shrink-0 items-center justify-center`,children:(0,N.jsx)(wn,{icon:i.icon,className:t?`text-gray-700`:`text-gray-500`})}):null]}),r?(0,N.jsx)(`span`,{className:`inline-flex shrink-0 items-center justify-end gap-1.5 pt-0.5`,children:(0,N.jsx)(Mn,{status:r})}):null]}),(0,N.jsxs)(`div`,{className:`mt-1 flex items-center gap-2 text-[11px] text-gray-400`,children:[(0,N.jsxs)(`span`,{className:`min-w-0 truncate`,children:[c?.trim()?`${c} · `:``,e.messageCount]}),n?(0,N.jsx)(`span`,{"aria-label":o(`chatSessionUnread`),className:`ml-auto h-2 w-2 shrink-0 rounded-full bg-primary`}):(0,N.jsx)(`span`,{className:`ml-auto shrink-0`,children:u(e.lastMessageAt??e.createdAt)})]})]}),f>0&&m?(0,N.jsxs)(`button`,{type:`button`,onClick:e=>{e.stopPropagation(),m()},className:d(`absolute right-6 top-0 inline-flex h-5 items-center gap-1 rounded-md px-1.5 text-[10px] font-medium text-gray-400 transition-all hover:bg-white hover:text-gray-900`,t?`opacity-100`:`opacity-0 group-hover/session:opacity-100 group-focus-within/session:opacity-100`),"aria-label":o(`chatSessionOpenChildSessions`),title:o(`chatSessionOpenChildSessions`),children:[(0,N.jsx)(en,{className:`h-3.5 w-3.5`}),(0,N.jsx)(`span`,{children:f})]}):null,(0,N.jsx)(`button`,{type:`button`,onClick:e=>{e.stopPropagation(),h()},className:d(`absolute right-0 top-0 inline-flex h-5 w-5 items-center justify-center rounded-md text-gray-400 transition-all hover:bg-white hover:text-gray-900`,t?`opacity-100`:`opacity-0 group-hover/session:opacity-100 group-focus-within/session:opacity-100`),"aria-label":o(`edit`),children:(0,N.jsx)(on,{className:`h-3 w-3`})})]})}function Fn({session:e,active:t,showUnreadDot:n,runStatus:r,context:i,title:a,agentId:o,agentLabel:s,agentAvatarUrl:c,childSessionCount:l,isEditing:u,draftLabel:f,isSaving:p,onSelect:m,onOpenChildSessions:h,onStartEditing:g,onDraftLabelChange:_,onSave:v,onCancel:y}){return(0,N.jsx)(`div`,{className:d(`w-full rounded-xl px-3 py-2.5 text-left transition-all text-[13px]`,t?`bg-gray-200 text-gray-900 font-semibold shadow-sm`:`text-gray-700 hover:bg-gray-200/60 hover:text-gray-900`),children:u?(0,N.jsx)(Nn,{session:e,draftLabel:f,isSaving:p,onDraftLabelChange:_,onSave:v,onCancel:y}):(0,N.jsx)(Pn,{session:e,active:t,showUnreadDot:n,runStatus:r,context:i,title:a,agentId:o,agentLabel:s,agentAvatarUrl:c,onSelect:m,childSessionCount:l,onOpenChildSessions:h,onStartEditing:g})})}var In=[{icon:xe,titleKey:`chatWelcomeCapability1Title`,descKey:`chatWelcomeCapability1Desc`},{icon:ve,titleKey:`chatWelcomeCapability2Title`,descKey:`chatWelcomeCapability2Desc`},{icon:Ee,titleKey:`chatWelcomeCapability3Title`,descKey:`chatWelcomeCapability3Desc`}];function Ln({onCreateSession:e,agents:t,selectedAgentId:n,onSelectAgent:r}){let i=t.find(e=>e.id===n)??null;return(0,N.jsx)(`div`,{className:`h-full flex items-center justify-center p-8`,children:(0,N.jsxs)(`div`,{className:`max-w-lg w-full text-center`,children:[(0,N.jsx)(`div`,{className:`mx-auto mb-6 h-16 w-16 rounded-2xl bg-primary/10 flex items-center justify-center`,children:(0,N.jsx)(me,{className:`h-8 w-8 text-primary`})}),(0,N.jsx)(`h2`,{className:`text-xl font-semibold text-gray-900 mb-2`,children:o(`chatWelcomeTitle`)}),(0,N.jsx)(`p`,{className:`text-sm text-gray-500 mb-8`,children:o(`chatWelcomeSubtitle`)}),(0,N.jsxs)(`div`,{className:`mb-6 flex items-center justify-center gap-2.5`,children:[(0,N.jsx)(`span`,{className:`text-[13px] font-medium text-gray-500`,children:o(`chatDraftAgentTitle`)}),(0,N.jsxs)(Je,{value:n,onValueChange:r,children:[(0,N.jsxs)(ze,{"aria-label":o(`chatDraftAgentTitle`),className:`h-auto w-auto gap-1 rounded-full border-0 bg-transparent px-1.5 py-1 text-gray-500 shadow-none hover:bg-white/70 hover:text-gray-800 focus:ring-0`,children:[(0,N.jsx)(`span`,{className:`sr-only`,children:o(`chatDraftAgentTitle`)}),(0,N.jsx)(`div`,{className:`flex items-center gap-1.5`,children:i?(0,N.jsx)(jn,{agentId:i.id,displayName:i.displayName,avatarUrl:i.avatarUrl,className:`h-7 w-7 shrink-0`}):null})]}),(0,N.jsx)(Ue,{className:`rounded-xl border-gray-200/80 shadow-lg`,children:t.map(e=>(0,N.jsx)(Ke,{value:e.id,className:`rounded-lg pr-10`,children:(0,N.jsxs)(`div`,{className:`flex min-w-0 items-center gap-2`,children:[(0,N.jsx)(jn,{agentId:e.id,displayName:e.displayName,avatarUrl:e.avatarUrl,className:`h-5 w-5 shrink-0`}),(0,N.jsx)(`span`,{className:`truncate text-sm font-medium text-gray-700`,children:e.displayName?.trim()||e.id})]})},e.id))})]})]}),(0,N.jsx)(`div`,{className:`grid grid-cols-3 gap-3`,children:In.map(t=>{let n=t.icon;return(0,N.jsxs)(`button`,{onClick:e,className:`rounded-2xl border border-gray-200 bg-white p-4 text-left shadow-card hover:shadow-card-hover transition-shadow cursor-pointer`,children:[(0,N.jsx)(`div`,{className:`h-9 w-9 rounded-xl bg-primary/8 flex items-center justify-center mb-3`,children:(0,N.jsx)(n,{className:`h-4.5 w-4.5 text-primary`})}),(0,N.jsx)(`div`,{className:`text-sm font-semibold text-gray-900 mb-1`,children:o(t.titleKey)}),(0,N.jsx)(`div`,{className:`text-[11px] text-gray-500 leading-relaxed`,children:o(t.descKey)})]},t.titleKey)})})]})})}var Rn=(0,P.createContext)(null);function zn({presenter:e,children:t}){return(0,N.jsx)(Rn.Provider,{value:e,children:t})}function Bn(){let e=(0,P.useContext)(Rn);if(!e)throw Error(`usePresenter must be used inside ChatPresenterProvider`);return e}var Vn=e=>`[data-item-index="${e}"]`;function Hn(e){let{activeIndex:t,containerRef:n,getItemSelector:r,isEnabled:i,itemCount:a}=e,o=r??Vn;(0,P.useEffect)(()=>{if(!i||a===0)return;let e=n.current;if(!e)return;let r=e.querySelector(o(t));typeof r?.scrollIntoView==`function`&&r.scrollIntoView({block:`nearest`,inline:`nearest`})},[t,n,o,i,a])}function Un(){let e=(0,P.useRef)(null),[t,n]=(0,P.useState)(null);return(0,P.useEffect)(()=>{let t=e.current;if(!t||typeof ResizeObserver>`u`)return;let r=()=>{n(t.getBoundingClientRect().width)};r();let i=new ResizeObserver(()=>r());return i.observe(t),()=>i.disconnect()},[]),{elementRef:e,width:t}}function F(...e){return n(r(e))}var Wn=P.forwardRef(({className:e,type:t,...n},r)=>(0,N.jsx)(`input`,{type:t,className:F(`flex h-9 w-full rounded-xl border border-gray-200/80 bg-white px-3.5 py-2 text-sm text-gray-900 file:border-0 file:bg-transparent file:text-sm file:font-medium placeholder:text-gray-300 placeholder:font-normal focus:outline-none focus:ring-1 focus:ring-primary/40 focus:border-primary/40 transition-colors disabled:cursor-not-allowed disabled:opacity-50`,e),ref:r,...n}));Wn.displayName=`ChatInput`;var Gn=bt,Kn=ht,qn=gt,Jn=P.forwardRef(({className:e,sideOffset:t=8,align:n=`start`,...r},i)=>(0,N.jsx)(vt,{children:(0,N.jsx)(mt,{ref:i,sideOffset:t,align:n,className:F(`z-[var(--z-popover,50)] w-72 overflow-hidden rounded-2xl border border-gray-200/50 bg-white p-4 shadow-lg animate-in fade-in-0 zoom-in-95 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2`,e),...r})}));Jn.displayName=mt.displayName;var Yn=He,Xn=qe,Zn=Ze,Qn=P.forwardRef(({className:e,children:t,...n},r)=>(0,N.jsxs)(Xe,{ref:r,className:F(`flex h-9 w-full items-center justify-between whitespace-nowrap rounded-xl border border-gray-200/80 bg-white px-3 py-2 text-sm shadow-sm ring-offset-background placeholder:text-muted-foreground focus:outline-none focus:ring-1 focus:ring-primary/40 disabled:cursor-not-allowed disabled:opacity-50 [&>span]:line-clamp-1`,e),...n,children:[t,(0,N.jsx)(Pe,{asChild:!0,children:(0,N.jsx)(je,{className:`h-4 w-4 opacity-50`})})]}));Qn.displayName=Xe.displayName;var $n=P.forwardRef(({className:e,...t},n)=>(0,N.jsx)(Le,{ref:n,className:F(`flex cursor-default items-center justify-center py-1`,e),...t,children:(0,N.jsx)(Ae,{className:`h-4 w-4`})}));$n.displayName=Le.displayName;var er=P.forwardRef(({className:e,...t},n)=>(0,N.jsx)(Re,{ref:n,className:F(`flex cursor-default items-center justify-center py-1`,e),...t,children:(0,N.jsx)(je,{className:`h-4 w-4`})}));er.displayName=Re.displayName;var tr=P.forwardRef(({className:e,children:t,position:n=`popper`,...r},i)=>(0,N.jsx)(Ge,{children:(0,N.jsxs)(We,{ref:i,className:F(`relative z-50 max-h-96 min-w-[8rem] overflow-hidden rounded-md bg-white text-popover-foreground shadow-md data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2`,n===`popper`&&`data-[side=bottom]:translate-y-1 data-[side=left]:-translate-x-1 data-[side=right]:translate-x-1 data-[side=top]:-translate-y-1`,e),position:n,...r,children:[(0,N.jsx)($n,{}),(0,N.jsx)(Ne,{className:F(`p-1`,n===`popper`&&`h-[var(--radix-select-trigger-height)] w-full min-w-[var(--radix-select-trigger-width)]`),children:t}),(0,N.jsx)(er,{})]})}));tr.displayName=We.displayName;var nr=P.forwardRef(({className:e,...t},n)=>(0,N.jsx)(Ie,{ref:n,className:F(`px-2 py-1 text-[11px] font-semibold uppercase tracking-[0.08em] text-gray-500`,e),...t}));nr.displayName=Ie.displayName;var rr=P.forwardRef(({className:e,children:t,...n},r)=>(0,N.jsxs)(Ve,{ref:r,className:F(`relative flex w-full cursor-default select-none items-center rounded-sm py-1.5 pl-2 pr-8 text-sm outline-none focus:bg-gray-100 data-[disabled]:pointer-events-none data-[disabled]:opacity-50 hover:bg-gray-100`,e),...n,children:[(0,N.jsx)(`span`,{className:`absolute right-2 flex h-3.5 w-3.5 items-center justify-center`,children:(0,N.jsx)(Ye,{children:(0,N.jsx)(Be,{className:`h-4 w-4`})})}),(0,N.jsx)(Fe,{children:t})]}));rr.displayName=Ve.displayName;var ir=P.forwardRef(({className:e,...t},n)=>(0,N.jsx)(Me,{ref:n,className:F(`-mx-1 my-1 h-px bg-gray-100`,e),...t}));ir.displayName=Me.displayName;var ar=At,or=wt,sr=Et,cr=P.forwardRef(({className:e,sideOffset:t=4,...n},r)=>(0,N.jsx)(Ot,{children:(0,N.jsx)(Ct,{ref:r,sideOffset:t,className:F(`z-[var(--z-tooltip)] overflow-hidden rounded-md border bg-popover px-3 py-1.5 text-sm text-popover-foreground shadow-md animate-in fade-in-0 zoom-in-95 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2`,e),...n})}));cr.displayName=Ct.displayName;var lr={Popover:Gn,PopoverAnchor:qn,PopoverContent:Jn,PopoverTrigger:Kn,Input:Wn,Select:Yn,SelectContent:tr,SelectGroup:Xn,SelectItem:rr,SelectLabel:nr,SelectSeparator:ir,SelectTrigger:Qn,SelectValue:Zn,Tooltip:or,TooltipContent:cr,TooltipProvider:ar,TooltipTrigger:sr},ur=680,dr=.82,fr=560;function pr(e){let{Popover:t,PopoverAnchor:n,PopoverContent:r}=lr,{elementRef:i,width:a}=Un(),o=(0,P.useRef)(null),{isOpen:s,isLoading:c,items:l,activeIndex:u,activeItem:d,texts:f,onSelectItem:p,onOpenChange:m,onSetActiveIndex:h}=e,g=(0,P.useMemo)(()=>{if(a)return Math.min(a>fr?a*dr:a,ur)},[a]);return Hn({containerRef:o,activeIndex:u,itemCount:l.length,isEnabled:s&&!c,getItemSelector:e=>`[data-slash-index="${e}"]`}),(0,N.jsxs)(t,{open:s,onOpenChange:m,children:[(0,N.jsx)(n,{asChild:!0,children:(0,N.jsx)(`div`,{ref:i,className:`pointer-events-none absolute bottom-full left-3 right-3 h-0`})}),(0,N.jsx)(r,{side:`top`,align:`start`,sideOffset:10,className:`z-[70] max-w-[calc(100vw-1.5rem)] overflow-hidden rounded-2xl border border-gray-200 bg-white/95 p-0 shadow-2xl backdrop-blur-md`,onOpenAutoFocus:e=>e.preventDefault(),style:g?{width:`${g}px`}:void 0,children:(0,N.jsxs)(`div`,{className:`grid min-h-[240px] grid-cols-[minmax(220px,300px)_minmax(0,1fr)]`,children:[(0,N.jsx)(`div`,{ref:o,role:`listbox`,"aria-label":f.slashSectionLabel,className:`custom-scrollbar max-h-[320px] overflow-y-auto border-r border-gray-200 p-2.5`,children:c?(0,N.jsx)(`div`,{className:`p-2 text-xs text-gray-500`,children:f.slashLoadingLabel}):(0,N.jsxs)(N.Fragment,{children:[(0,N.jsx)(`div`,{className:`mb-2 px-2 text-[11px] font-semibold uppercase tracking-wide text-gray-500`,children:f.slashSectionLabel}),l.length===0?(0,N.jsx)(`div`,{className:`px-2 text-xs text-gray-400`,children:f.slashEmptyLabel}):(0,N.jsx)(`div`,{className:`space-y-1`,children:l.map((e,t)=>{let n=t===u;return(0,N.jsxs)(`button`,{type:`button`,role:`option`,"aria-selected":n,"data-slash-index":t,onMouseEnter:()=>h(t),onClick:()=>p(e),className:`flex w-full items-start gap-2 rounded-lg px-2 py-1.5 text-left transition ${n?`bg-gray-100 text-gray-900`:`text-gray-700 hover:bg-gray-50`}`,children:[(0,N.jsx)(`span`,{className:`truncate text-xs font-semibold`,children:e.title}),(0,N.jsx)(`span`,{className:`truncate text-xs text-gray-500`,children:e.subtitle})]},e.key)})})]})}),(0,N.jsx)(`div`,{className:`min-w-0 p-2.5`,children:d?(0,N.jsxs)(`div`,{className:`space-y-3`,children:[(0,N.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,N.jsx)(`span`,{className:`inline-flex rounded-full bg-primary/10 px-2 py-0.5 text-[11px] font-semibold text-primary`,children:d.subtitle}),(0,N.jsx)(`span`,{className:`text-sm font-semibold text-gray-900`,children:d.title})]}),(0,N.jsx)(`p`,{className:`text-xs leading-5 text-gray-600`,children:d.description}),(0,N.jsx)(`div`,{className:`space-y-1`,children:d.detailLines.map(e=>(0,N.jsx)(`div`,{className:`min-w-0 break-all rounded-md bg-gray-50 px-2 py-1 text-[11px] leading-5 text-gray-600`,children:e},e))}),(0,N.jsx)(`div`,{className:`pt-1 text-[11px] text-gray-500`,children:f.slashSkillHintLabel})]}):(0,N.jsx)(`div`,{className:`text-xs text-gray-500`,children:f.slashHintLabel})})]})})]})}var mr=_(`inline-flex items-center justify-center whitespace-nowrap rounded-full text-sm font-medium ring-offset-background transition-all duration-fast focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50`,{variants:{variant:{default:`bg-primary text-primary-foreground hover:bg-primary-600 active:bg-primary-700 shadow-sm`,destructive:`bg-destructive text-destructive-foreground hover:bg-destructive/90`,outline:`border border-gray-200 bg-white hover:bg-gray-50 hover:text-gray-800 text-gray-600`,secondary:`bg-gray-100 text-gray-700 hover:bg-gray-200/80`,ghost:`hover:bg-gray-100/80 hover:text-gray-800`,link:`text-primary underline-offset-4 hover:underline`,primary:`bg-primary text-primary-foreground hover:bg-primary-600 active:bg-primary-700 shadow-sm`,subtle:`bg-gray-100 text-gray-600 hover:bg-gray-200/80`,"primary-outline":`border border-primary/30 text-primary hover:bg-primary hover:text-primary-foreground`},size:{default:`h-9 px-4 py-2`,sm:`h-8 px-3 text-xs`,lg:`h-11 px-5 text-[14px]`,xl:`h-12 px-6 text-[15px]`,icon:`h-9 w-9`}},defaultVariants:{variant:`default`,size:`default`}}),hr=P.forwardRef(({className:e,variant:t,size:n,...r},i)=>(0,N.jsx)(`button`,{className:F(mr({variant:t,size:n,className:e})),ref:i,...r}));hr.displayName=`ChatButton`;var gr=120;function _r(e){let t=e.replace(/\s+/g,` `).trim();return t.length<=gr?t:`${t.slice(0,gr-1)}…`}function vr(){return(0,N.jsx)(`span`,{"aria-hidden":`true`,"data-testid":`chat-stop-icon`,className:`block h-3 w-3 rounded-[2px] bg-gray-700 shadow-[inset_0_0_0_1px_rgba(17,24,39,0.06)]`})}function yr({contextWindow:e}){let{Tooltip:t,TooltipContent:n,TooltipProvider:r,TooltipTrigger:i}=lr,a=Math.max(0,Math.min(1,e.ratio)),o=Math.round(a*360);return(0,N.jsx)(r,{delayDuration:0,children:(0,N.jsxs)(t,{children:[(0,N.jsx)(i,{asChild:!0,children:(0,N.jsxs)(`button`,{type:`button`,className:`relative inline-flex h-8 w-8 shrink-0 items-center justify-center rounded-lg text-gray-500 transition-colors hover:bg-gray-100 hover:text-gray-700`,"aria-label":e.label,title:e.label,children:[(0,N.jsx)(`span`,{"aria-hidden":`true`,className:`absolute inset-[7px] rounded-full`,style:{background:`conic-gradient(#9ca3af ${o}deg, #e5e7eb 0deg)`}}),(0,N.jsx)(`span`,{"aria-hidden":`true`,className:`absolute inset-[10px] rounded-full bg-white`})]})}),(0,N.jsx)(n,{side:`top`,className:`max-w-[18rem]`,children:(0,N.jsxs)(`div`,{className:`space-y-1.5 text-xs`,children:[(0,N.jsxs)(`div`,{className:`flex items-center justify-between gap-5 font-semibold text-gray-800`,children:[(0,N.jsx)(`span`,{children:e.label}),(0,N.jsx)(`span`,{children:e.percentLabel})]}),e.details.map(e=>(0,N.jsxs)(`div`,{className:`flex items-center justify-between gap-5 text-gray-600`,children:[(0,N.jsx)(`span`,{children:e.label}),(0,N.jsx)(`span`,{className:`font-medium text-gray-800`,children:e.value})]},e.label))]})})]})})}function br({sendError:e,sendErrorDetailsLabel:t,isSending:n,canStopGeneration:r,sendDisabled:i,stopDisabled:a,stopHint:o,sendButtonLabel:s,stopButtonLabel:c,contextWindow:l,onSend:u,onStop:d}){let{Popover:f,PopoverContent:p,PopoverTrigger:m,Tooltip:h,TooltipContent:g,TooltipProvider:_,TooltipTrigger:v}=lr,y=e?.trim()??``,b=y?_r(y):``,x=t?.trim()||`Details`;return(0,N.jsxs)(`div`,{className:`flex shrink-0 flex-col items-end gap-1`,children:[y?(0,N.jsxs)(`div`,{className:`flex max-w-[420px] items-start justify-end gap-2 text-right`,children:[(0,N.jsx)(`div`,{className:`min-w-0 flex-1 text-[11px] text-red-600`,children:(0,N.jsx)(`span`,{className:`block truncate`,title:y,children:b})}),(0,N.jsxs)(f,{children:[(0,N.jsx)(m,{asChild:!0,children:(0,N.jsx)(`button`,{type:`button`,className:`shrink-0 rounded-full border border-red-200/80 bg-red-50 px-2 py-0.5 text-[10px] font-semibold text-red-700 transition-colors hover:bg-red-100`,children:x})}),(0,N.jsxs)(p,{align:`end`,className:`w-[min(32rem,calc(100vw-1.5rem))] border-red-100/80 p-0`,children:[(0,N.jsx)(`div`,{className:`border-b border-red-100 bg-red-50/80 px-4 py-2 text-xs font-semibold text-red-700`,children:x}),(0,N.jsx)(`pre`,{className:`max-h-80 overflow-auto whitespace-pre-wrap break-words px-4 py-3 text-xs leading-relaxed text-red-700`,children:y})]})]})]}):null,(0,N.jsxs)(`div`,{className:`flex items-center gap-2`,children:[l?(0,N.jsx)(yr,{contextWindow:l}):null,n?r?(0,N.jsx)(hr,{size:`icon`,variant:`outline`,className:`h-8 w-8 rounded-full`,"aria-label":c,onClick:()=>void d(),disabled:a,children:(0,N.jsx)(vr,{})}):(0,N.jsx)(_,{children:(0,N.jsxs)(h,{children:[(0,N.jsx)(v,{asChild:!0,children:(0,N.jsx)(`span`,{children:(0,N.jsx)(hr,{size:`icon`,variant:`outline`,className:`h-8 w-8 rounded-full`,"aria-label":c,disabled:!0,children:(0,N.jsx)(vr,{})})})}),(0,N.jsx)(g,{side:`top`,children:(0,N.jsx)(`p`,{className:`text-xs`,children:o})})]})}):(0,N.jsx)(hr,{size:`icon`,className:`h-8 w-8 rounded-full`,"aria-label":s,onClick:()=>void u(),disabled:i,children:(0,N.jsx)(Pt,{className:`h-5 w-5`})})]})]})}function xr(e,t){let n=t.trim().toLowerCase();return n?e.filter(e=>[e.label,e.key,e.description].filter(e=>typeof e==`string`&&e.trim().length>0).join(` `).toLowerCase().includes(n)):e}function Sr(e){let{Input:t,Popover:n,PopoverContent:r,PopoverTrigger:i}=lr,{picker:a}=e,o=(0,P.useRef)(null),s=(0,P.useId)(),[c,l]=(0,P.useState)(``),[u,d]=(0,P.useState)(0),f=(0,P.useMemo)(()=>new Set(a.selectedKeys),[a.selectedKeys]),p=a.selectedKeys.length,m=c.trim().length>0,h=(0,P.useMemo)(()=>{if(m)return null;let e=a.groups?.filter(e=>e.options.length>0)??[];return e.length>0?e:null},[m,a.groups]),g=(0,P.useMemo)(()=>h?h.flatMap(e=>e.options):xr(a.options,c),[h,a.options,c]);(0,P.useEffect)(()=>{d(0)},[c]),(0,P.useEffect)(()=>{d(e=>g.length===0?0:Math.min(e,g.length-1))},[g.length]),Hn({containerRef:o,activeIndex:u,itemCount:g.length,isEnabled:g.length>0,getItemSelector:e=>`[data-skill-index="${e}"]`});let _=e=>{if(f.has(e)){a.onSelectedKeysChange(a.selectedKeys.filter(t=>t!==e));return}a.onSelectedKeysChange([...a.selectedKeys,e])},v=e=>{if(g.length!==0){if(e.key===`ArrowDown`){e.preventDefault(),d(e=>Math.min(e+1,g.length-1));return}if(e.key===`ArrowUp`){e.preventDefault(),d(e=>Math.max(e-1,0));return}if(e.key===`Enter`){e.preventDefault();let t=g[u];t&&_(t.key)}}};return(0,N.jsxs)(n,{children:[(0,N.jsx)(i,{asChild:!0,children:(0,N.jsxs)(`button`,{type:`button`,"aria-haspopup":`listbox`,"aria-label":a.title,className:`relative inline-flex h-8 w-8 shrink-0 items-center justify-center rounded-lg px-0 text-xs font-medium text-gray-600 transition-colors hover:bg-gray-100 hover:text-gray-900 sm:w-auto sm:gap-1.5 sm:px-3`,children:[(0,N.jsx)(ve,{className:`h-4 w-4`}),(0,N.jsx)(`span`,{className:`hidden sm:inline`,children:a.title}),p>0?(0,N.jsx)(`span`,{className:`absolute -right-1 -top-1 flex h-[18px] min-w-[18px] items-center justify-center rounded-full bg-primary px-1 text-[10px] font-semibold leading-none text-white shadow-sm sm:static sm:ml-0.5 sm:bg-primary/10 sm:text-primary sm:shadow-none`,children:p}):null]})}),(0,N.jsxs)(r,{side:`top`,align:`start`,className:`w-[360px] p-0`,children:[(0,N.jsxs)(`div`,{className:`space-y-2 border-b border-gray-100 px-4 py-3`,children:[(0,N.jsx)(`div`,{className:`text-sm font-semibold text-gray-900`,children:a.title}),(0,N.jsxs)(`div`,{className:`relative`,children:[(0,N.jsx)(Oe,{className:`pointer-events-none absolute left-3 top-2.5 h-3.5 w-3.5 text-gray-400`}),(0,N.jsx)(t,{value:c,onChange:e=>l(e.target.value),onKeyDown:v,placeholder:a.searchPlaceholder,role:`combobox`,"aria-controls":s,"aria-expanded":`true`,"aria-autocomplete":`list`,"aria-activedescendant":g[u]?`${s}-option-${u}`:void 0,className:`h-8 rounded-lg pl-8 text-xs`})]})]}),(0,N.jsx)(`div`,{ref:o,id:s,role:`listbox`,"aria-multiselectable":`true`,className:`custom-scrollbar max-h-[320px] overflow-y-auto`,children:a.isLoading?(0,N.jsx)(`div`,{className:`p-4 text-xs text-gray-500`,children:a.loadingLabel}):g.length===0?(0,N.jsx)(`div`,{className:`p-4 text-center text-xs text-gray-500`,children:a.emptyLabel}):(0,N.jsx)(`div`,{className:`py-1`,children:(()=>{let e=h??[{key:`all-skills`,options:g}],t=0;return e.map(e=>(0,N.jsxs)(`div`,{children:[e.label?(0,N.jsx)(`div`,{className:`px-4 pb-1 pt-2 text-[11px] font-semibold uppercase tracking-wide text-gray-500`,children:e.label}):null,e.options.map(e=>{let n=t;t+=1;let r=f.has(e.key),i=n===u;return(0,N.jsxs)(`button`,{type:`button`,id:`${s}-option-${n}`,role:`option`,"aria-selected":r,"data-skill-index":n,onClick:()=>_(e.key),onMouseEnter:()=>d(n),className:`flex w-full items-center gap-3 px-4 py-2.5 text-left transition-colors ${i?`bg-gray-50`:`hover:bg-gray-50`}`,children:[(0,N.jsx)(`div`,{className:`flex h-8 w-8 shrink-0 items-center justify-center rounded-lg bg-gray-100 text-gray-500`,children:(0,N.jsx)(sn,{className:`h-4 w-4`})}),(0,N.jsxs)(`div`,{className:`min-w-0 flex-1`,children:[(0,N.jsxs)(`div`,{className:`flex items-center gap-1.5`,children:[(0,N.jsx)(`span`,{className:`truncate text-sm text-gray-900`,children:e.label}),e.badgeLabel?(0,N.jsx)(`span`,{className:`shrink-0 rounded-full bg-primary/10 px-1.5 py-0.5 text-[10px] font-medium text-primary`,children:e.badgeLabel}):null]}),(0,N.jsx)(`div`,{className:`mt-0.5 truncate text-xs text-gray-500`,children:e.description||e.key})]}),(0,N.jsx)(`div`,{className:`ml-3 shrink-0`,children:(0,N.jsx)(`span`,{className:r?`inline-flex h-5 w-5 items-center justify-center rounded-full bg-primary text-white`:`inline-flex h-5 w-5 items-center justify-center rounded-full border border-gray-300 bg-white`,children:r?(0,N.jsx)(Be,{className:`h-3 w-3`}):null})})]},e.key)})]},e.key))})()})}),a.manageHref&&a.manageLabel?(0,N.jsx)(`div`,{className:`border-t border-gray-100 px-4 py-2.5`,children:(0,N.jsxs)(`a`,{href:a.manageHref,className:`inline-flex items-center gap-1.5 text-xs font-medium text-primary transition-colors hover:text-primary/80`,children:[a.manageLabel,(0,N.jsx)(Qe,{className:`h-3 w-3`})]})}):null]})]})}function Cr({icon:e}){return e===`sparkles`?(0,N.jsx)(ot,{className:`h-3.5 w-3.5 shrink-0 text-primary`}):e===`brain`?(0,N.jsx)(Ft,{className:`h-3.5 w-3.5 shrink-0 text-gray-500`}):null}function wr({icon:e}){return e===`paperclip`?(0,N.jsx)(an,{className:`h-4 w-4`}):(0,N.jsx)(Cr,{icon:e})}var Tr={model:`min-w-0 flex-1 sm:min-w-[220px] sm:flex-none`,"session-type":`shrink-0`,thinking:`shrink-0`},Er={model:`w-[min(18rem,calc(100vw-1rem))] sm:w-[320px]`,"session-type":`w-[220px]`,thinking:`w-[180px]`};function Dr(e){return e.key===`model`&&e.selectedLabel&&e.selectedLabel.split(`/`).slice(1).join(`/`).trim()||e.selectedLabel}function Or({item:e}){let{Select:t,SelectContent:n,SelectGroup:r,SelectItem:i,SelectLabel:a,SelectSeparator:o,SelectTrigger:s,SelectValue:c}=lr,l=e.groups?.filter(e=>e.options.length>0)??(e.options.length>0?[{key:`${e.key}-default`,options:e.options}]:[]),u=l.some(e=>e.options.length>0),d=Dr(e);return(0,N.jsxs)(t,{value:e.value,onValueChange:e.onValueChange,disabled:e.disabled,children:[(0,N.jsx)(s,{className:`h-8 w-auto rounded-lg border-0 bg-transparent px-2 text-xs font-medium text-gray-600 shadow-none hover:bg-gray-100 focus:ring-0 sm:px-3 ${Tr[e.key]??``}`,children:e.selectedLabel?(0,N.jsxs)(`div`,{className:`flex min-w-0 items-center gap-2 text-left`,children:[(0,N.jsx)(Cr,{icon:e.icon}),(0,N.jsx)(`span`,{className:`truncate text-xs font-semibold text-gray-700 sm:hidden`,children:d}),(0,N.jsx)(`span`,{className:`hidden truncate text-xs font-semibold text-gray-700 sm:inline`,children:e.selectedLabel})]}):e.loading?(0,N.jsx)(`div`,{className:`h-3 w-24 animate-pulse rounded bg-gray-200`}):(0,N.jsx)(c,{placeholder:e.placeholder})}),(0,N.jsxs)(n,{className:Er[e.key]??``,children:[u?null:e.loading?(0,N.jsxs)(`div`,{className:`space-y-2 px-3 py-2`,children:[(0,N.jsx)(`div`,{className:`h-3 w-36 animate-pulse rounded bg-gray-200`}),(0,N.jsx)(`div`,{className:`h-3 w-28 animate-pulse rounded bg-gray-200`}),(0,N.jsx)(`div`,{className:`h-3 w-32 animate-pulse rounded bg-gray-200`})]}):e.emptyLabel?(0,N.jsx)(`div`,{className:`px-3 py-2 text-xs text-gray-500`,children:e.emptyLabel}):null,l.map((e,t)=>(0,N.jsxs)(`div`,{children:[t>0?(0,N.jsx)(o,{}):null,(0,N.jsxs)(r,{children:[e.label?(0,N.jsx)(a,{children:e.label}):null,e.options.map(e=>(0,N.jsx)(i,{value:e.value,className:`py-2`,children:e.description?(0,N.jsxs)(`div`,{className:`flex min-w-0 flex-col gap-0.5`,children:[(0,N.jsx)(`span`,{className:`truncate text-xs font-semibold text-gray-800`,children:e.label}),(0,N.jsx)(`span`,{className:`truncate text-[11px] text-gray-500`,children:e.description})]}):(0,N.jsx)(`span`,{className:`truncate text-xs font-semibold text-gray-800`,children:e.label})},e.value))]})]},e.key))]})]})}function kr({actions:e,accessories:t,selects:n,skillPicker:r}){let{Tooltip:i,TooltipContent:a,TooltipProvider:o,TooltipTrigger:s}=lr;return(0,N.jsxs)(`div`,{className:`flex items-center justify-between gap-2 px-3 pb-3`,children:[(0,N.jsxs)(`div`,{className:`flex min-w-0 flex-1 items-center gap-1 overflow-hidden`,children:[r?(0,N.jsx)(Sr,{picker:r}):null,n.map(e=>(0,N.jsx)(Or,{item:e},e.key)),t?.map(e=>{let t=(0,N.jsxs)(`button`,{type:`button`,className:`inline-flex items-center rounded-lg py-1.5 text-xs font-medium text-gray-600 transition-colors hover:bg-gray-100 hover:text-gray-900 disabled:cursor-not-allowed disabled:text-gray-400 ${e.iconOnly?`h-8 w-8 justify-center px-0`:`gap-1.5 px-3`}`,onClick:e.onClick,disabled:e.disabled,"aria-label":e.label,children:[(0,N.jsx)(wr,{icon:e.icon}),e.iconOnly?null:(0,N.jsx)(`span`,{children:e.label})]});return e.tooltip?(0,N.jsx)(o,{children:(0,N.jsxs)(i,{children:[(0,N.jsx)(s,{asChild:!0,children:e.disabled?(0,N.jsx)(`span`,{className:`inline-flex`,children:t}):t}),(0,N.jsx)(a,{side:`top`,children:(0,N.jsx)(`p`,{className:`text-xs`,children:e.tooltip})})]})},e.key):(0,N.jsx)(`div`,{children:t},e.key)})]}),(0,N.jsx)(br,{...e})]})}var Ar=(0,P.createContext)(null);function jr(e,t){let n=null;return e!=null&&(n=e[1]),{getTheme:function(){return t??(n==null?null:n.getTheme())}}}function Mr(){let e=(0,P.useContext)(Ar);return e??function(e,...t){let n=new URL(`https://lexical.dev/docs/error`),r=new URLSearchParams;r.append(`code`,e);for(let e of t)r.append(`v`,e);throw n.search=r.toString(),Error(`Minified Lexical error #${e}; visit ${n.toString()} for the full message or use the non-minified dev environment for full errors and additional helpful warnings.`)}(8),e}function I(e,...t){let n=new URL(`https://lexical.dev/docs/error`),r=new URLSearchParams;r.append(`code`,e);for(let e of t)r.append(`v`,e);throw n.search=r.toString(),Error(`Minified Lexical error #${e}; visit ${n.toString()} for the full message or use the non-minified dev environment for full errors and additional helpful warnings.`)}function Nr(e,...t){let n=new URL(`https://lexical.dev/docs/error`),r=new URLSearchParams;r.append(`code`,e);for(let e of t)r.append(`v`,e);n.search=r.toString(),console.warn(`Minified Lexical warning #${e}; visit ${n.toString()} for the full message or use the non-minified dev environment for full errors and additional helpful warnings.`)}var Pr=typeof window<`u`&&window.document!==void 0&&window.document.createElement!==void 0,Fr=Pr&&`documentMode`in document?document.documentMode:null,Ir=Pr&&/Mac|iPod|iPhone|iPad/.test(navigator.platform),Lr=Pr&&/^(?!.*Seamonkey)(?=.*Firefox).*/i.test(navigator.userAgent),Rr=!(!Pr||!(`InputEvent`in window)||Fr)&&`getTargetRanges`in new window.InputEvent(`input`),zr=Pr&&/iPad|iPhone|iPod/.test(navigator.userAgent)&&!window.MSStream,Br=Pr&&/Android/.test(navigator.userAgent),Vr=Pr&&/Version\/[\d.]+.*Safari/.test(navigator.userAgent)&&!Br,Hr=Pr&&/^(?=.*Chrome).*/i.test(navigator.userAgent),Ur=Pr&&Br&&Hr,Wr=Pr&&/AppleWebKit\/[\d.]+/.test(navigator.userAgent)&&Ir&&!Hr,Gr=0,Kr=1,qr=2,Jr=1,Yr=2,Xr=3,Zr=4,Qr=5,$r=6,ei=Vr||zr||Wr?`\xA0`:``,ti=`
|
|
2
2
|
|
|
3
3
|
`,ni=Lr?`\xA0`:ei,ri={bold:1,capitalize:1024,code:16,highlight:128,italic:2,lowercase:256,strikethrough:4,subscript:32,superscript:64,underline:8,uppercase:512},ii={directionless:1,unmergeable:2},ai={center:2,end:6,justify:4,left:1,right:3,start:5},oi={[Yr]:`center`,[$r]:`end`,[Zr]:`justify`,[Jr]:`left`,[Xr]:`right`,[Qr]:`start`},si={normal:0,segmented:2,token:1},ci={[Gr]:`normal`,[qr]:`segmented`,[Kr]:`token`},li=`$config`;function ui(e,t,n,r,i,a){let o=e.getFirstChild();for(;o!==null;){let e=o.__key;o.__parent===t&&(V(o)&&ui(o,e,n,r,i,a),n.has(e)||a.delete(e),i.push(e)),o=o.getNextSibling()}}var di=!1,fi=0;function pi(e){fi=e.timeStamp}function mi(e,t,n){let r=e.nodeName===`BR`,i=t.__lexicalLineBreak;return i&&(e===i||r&&e.previousSibling===i)||r&&fl(e,n)!==void 0}function hi(e,t,n){let r=eu(Kl(n)),i=null,a=null;r!==null&&r.anchorNode===e&&(i=r.anchorOffset,a=r.focusOffset);let o=e.nodeValue;o!==null&&Tl(t,o,i,a,!1)}function gi(e,t,n){if(z(e)){let t=e.anchor.getNode();if(t.is(n)&&e.format!==t.getFormat())return!1}return tl(t)&&n.isAttached()}function _i(e,t,n,r){for(let i=e;i&&!hu(i);i=Bl(i)){let e=fl(i,t);if(e!==void 0){let t=ul(e,n);if(t)return Sc(t)||!nu(i)?void 0:[i,t]}else if(i===r)return[r,_l(n)]}}function vi(e,t,n){di=!0;let r=performance.now()-fi>100;try{gc(e,()=>{let i=B()||function(e){return e.getEditorState().read(()=>{let e=B();return e===null?null:e.clone()})}(e),a=new Map,o=e.getRootElement(),s=e._editorState,c=e._blockCursorElement,l=!1,u=``;for(let n=0;n<t.length;n++){let d=t[n],f=d.type,p=d.target,m=_i(p,e,s,o);if(!m)continue;let[h,g]=m;if(f===`characterData`)r&&R(g)&&tl(p)&&gi(i,p,g)&&hi(p,g,e);else if(f===`childList`){l=!0;let t=d.addedNodes;for(let n=0;n<t.length;n++){let r=t[n],i=dl(r),a=r.parentNode;if(a!=null&&r!==c&&i===null&&!mi(r,a,e)){if(Lr){let e=(nu(r)?r.innerText:null)||r.nodeValue;e&&(u+=e)}a.removeChild(r)}}let n=d.removedNodes,r=n.length;if(r>0){let t=0;for(let i=0;i<r;i++){let r=n[i];(mi(r,p,e)||c===r)&&(p.appendChild(r),t++)}r!==t&&a.set(h,g)}}}if(a.size>0)for(let[t,n]of a)n.reconcileObservedMutation(t,e);let d=n.takeRecords();if(d.length>0){for(let t=0;t<d.length;t++){let n=d[t],r=n.addedNodes,i=n.target;for(let t=0;t<r.length;t++){let n=r[t],a=n.parentNode;a==null||n.nodeName!==`BR`||mi(n,i,e)||a.removeChild(n)}}n.takeRecords()}i!==null&&(l&&vl(i),Lr&&Rl(e)&&i.insertRawText(u))})}finally{di=!1}}function yi(e){let t=e._observer;t!==null&&vi(e,t.takeRecords(),t)}function bi(e){(function(e){fi===0&&Kl(e).addEventListener(`textInput`,pi,!0)})(e),e._observer=new MutationObserver((t,n)=>{vi(e,t,n)})}var xi=class{key;parse;unparse;isEqual;defaultValue;resetOnCopyNode;constructor(e,t){this.key=e,this.parse=t.parse.bind(t),this.unparse=(t.unparse||Oi).bind(t),this.isEqual=(t.isEqual||Object.is).bind(t),this.defaultValue=this.parse(void 0),this.resetOnCopyNode=t.resetOnCopyNode||!1}};function Si(e,t){return new xi(e,t)}function Ci(e){let t=new Map,n=new Set;for(let r=typeof e==`function`?e:e.replace;r.prototype&&r.prototype.getType!==void 0;r=Object.getPrototypeOf(r)){let{ownNodeConfig:e}=_u(r);if(e&&e.stateConfigs)for(let r of e.stateConfigs){let e;`stateConfig`in r?(e=r.stateConfig,r.flat&&n.add(e.key)):e=r,t.set(e.key,e)}}return{flatKeys:n,sharedConfigMap:t}}var wi=class e{node;knownState;unknownState;sharedNodeState;size;constructor(e,t,n=void 0,r=new Map,i=void 0){this.node=e,this.sharedNodeState=t,this.unknownState=n,this.knownState=r;let{sharedConfigMap:a}=this.sharedNodeState;this.size=i===void 0?function(e,t,n){let r=n.size;if(t)for(let i in t){let t=e.get(i);t&&n.has(t)||r++}return r}(a,n,r):i}getValue(e){let t=this.knownState.get(e);if(t!==void 0)return t;this.sharedNodeState.sharedConfigMap.set(e.key,e);let n=e.defaultValue;if(this.unknownState&&e.key in this.unknownState){let t=this.unknownState[e.key];t!==void 0&&(n=e.parse(t)),this.updateFromKnown(e,n)}return n}getInternalState(){return[this.unknownState,this.knownState]}toJSON(){let e={...this.unknownState},t={};for(let[t,n]of this.knownState)t.isEqual(n,t.defaultValue)?delete e[t.key]:e[t.key]=t.unparse(n);for(let n of this.sharedNodeState.flatKeys)n in e&&(t[n]=e[n],delete e[n]);return Di(e)&&(t.$=e),t}getWritable(t){if(this.node===t)return this;let{sharedNodeState:n,unknownState:r}=this,i=new Map(this.knownState);return new e(t,n,function(e,t,n){let r;if(n)for(let[i,a]of Object.entries(n)){let n=e.get(i);n?t.has(n)||t.set(n,n.parse(a)):(r||={},r[i]=a)}return r}(n.sharedConfigMap,i,r),i,this.size)}resetOnCopyNode(){for(let e of this.knownState.keys())e.resetOnCopyNode&&this.knownState.set(e,e.defaultValue);return this}updateFromKnown(e,t){let n=e.key;this.sharedNodeState.sharedConfigMap.set(n,e);let{knownState:r,unknownState:i}=this;r.has(e)||i&&n in i||(i&&(delete i[n],this.unknownState=Di(i)),this.size++),r.set(e,t)}updateFromUnknown(e,t){let n=this.sharedNodeState.sharedConfigMap.get(e);n?this.updateFromKnown(n,n.parse(t)):(this.unknownState=this.unknownState||{},e in this.unknownState||this.size++,this.unknownState[e]=t)}updateFromJSON(e){let{knownState:t}=this;for(let e of t.keys())t.set(e,e.defaultValue);if(this.size=t.size,this.unknownState=void 0,e)for(let[t,n]of Object.entries(e))this.updateFromUnknown(t,n)}};function Ti(e){let t=e.getWritable(),n=t.__state?t.__state.getWritable(t):new wi(t,Ei(t));return t.__state=n,n}function Ei(e){return e.__state?e.__state.sharedNodeState:Wc(cu(),e.getType()).sharedNodeState}function Di(e){if(e)for(let t in e)return e}function Oi(e){return e}function ki(e,t,n){for(let[r,i]of t.knownState){if(e.has(r.key))continue;e.add(r.key);let t=n?n.getValue(r):r.defaultValue;if(t!==i&&!r.isEqual(t,i))return!0}return!1}function Ai(e,t,n){let{unknownState:r}=t,i=n?n.unknownState:void 0;if(r){for(let[t,n]of Object.entries(r))if(!e.has(t)&&(e.add(t),n!==(i?i[t]:void 0)))return!0}return!1}function ji(e,t){let n=e.__state;return n&&n.node===e?n.getWritable(t):n}function Mi(e,t){let n=e.__mode,r=e.__format,i=e.__style,a=t.__mode,o=t.__format,s=t.__style,c=e.__state,l=t.__state;return(n===null||n===a)&&(r===null||r===o)&&(i===null||i===s)&&(e.__state===null||c===l||function(e,t){if(e===t)return!0;let n=new Set;return!(e&&ki(n,e,t)||t&&ki(n,t,e)||e&&Ai(n,e,t)||t&&Ai(n,t,e))}(c,l))}function Ni(e,t){let n=e.mergeWithSibling(t),r=rc()._normalizedNodes;return r.add(e.__key),r.add(t.__key),n}function Pi(e){let t,n,r=e;if(r.__text!==``||!r.isSimpleText()||r.isUnmergeable()){for(;(t=r.getPreviousSibling())!==null&&R(t)&&t.isSimpleText()&&!t.isUnmergeable();){if(t.__text!==``){if(Mi(t,r)){r=Ni(t,r);break}break}t.remove()}for(;(n=r.getNextSibling())!==null&&R(n)&&n.isSimpleText()&&!n.isUnmergeable();){if(n.__text!==``){if(Mi(r,n)){r=Ni(r,n);break}break}n.remove()}}else r.remove()}function Fi(e){return Ii(e.anchor),Ii(e.focus),e}function Ii(e){for(;e.type===`element`;){let t=e.getNode(),n=e.offset,r,i;if(n===t.getChildrenSize()?(r=t.getChildAtIndex(n-1),i=!0):(r=t.getChildAtIndex(n),i=!1),R(r)){e.set(r.__key,i?r.getTextContentSize():0,`text`,!0);break}if(!V(r))break;e.set(r.__key,i?r.getChildrenSize():0,`element`,!0)}}var Li,Ri,zi,Bi,Vi,Hi,Ui,Wi,Gi,Ki,qi=``,Ji=null,Yi=null,Xi=!1,Zi=!1;function Qi(e,t){let n=Ui.get(e);if(t!==null){let n=ga(e);n.parentNode===t&&t.removeChild(n)}if(Wi.has(e)||Ri._keyToDOMMap.delete(e),V(n)){let e=ua(n,Ui);$i(e,0,e.length-1,null)}n!==void 0&&Fl(Ki,zi,Bi,n,`destroyed`)}function $i(e,t,n,r){for(let i=t;i<=n;++i){let t=e[i];t!==void 0&&Qi(t,r)}}function ea(e,t){e.setProperty(`text-align`,t)}var ta=`40px`;function na(e,t){let n=Li.theme.indent;if(typeof n==`string`){let r=e.classList.contains(n);t>0&&!r?e.classList.add(n):t<1&&r&&e.classList.remove(n)}if(t===0)return void e.style.setProperty(`padding-inline-start`,``);let r=getComputedStyle(Ri._rootElement||e).getPropertyValue(`--lexical-indent-base-value`)||ta;e.style.setProperty(`padding-inline-start`,`calc(${t} * ${r})`)}function ra(e,t){let n=e.style;t===0?ea(n,``):t===1?ea(n,`left`):t===2?ea(n,`center`):t===3?ea(n,`right`):t===4?ea(n,`justify`):t===5?ea(n,`start`):t===6&&ea(n,`end`)}function ia(e,t){let n=function(e){let t=e.__dir;if(t!==null)return t;if(wc(e))return null;let n=e.getParentOrThrow();return wc(n)&&n.__dir===null?`auto`:null}(t);n===null?e.removeAttribute(`dir`):e.dir=n}function aa(e,t){let n=Wi.get(e);n===void 0&&I(60);let r=n.createDOM(Li,Ri);if(function(e,t,n){let r=n._keyToDOMMap;(function(e,t,n){let r=`__lexicalKey_${t._key}`;e[r]=n})(t,n,e),r.set(e,t)}(e,r,Ri),R(n)?r.setAttribute(`data-lexical-text`,`true`):Sc(n)&&r.setAttribute(`data-lexical-decorator`,`true`),V(n)){let e=n.__indent,t=n.__size;if(ia(r,n),e!==0&&na(r,e),t!==0){let e=t-1;oa(ua(n,Wi),n,0,e,n.getDOMSlot(r))}let i=n.__format;i!==0&&ra(r,i),n.isInline()||ca(null,n,r)}else{let t=n.getTextContent();if(Sc(n)){let t=n.decorate(Ri,Li);t!==null&&fa(e,t),r.contentEditable=`false`}qi+=t}return t!==null&&t.insertChild(r),Fl(Ki,zi,Bi,n,`created`),r}function oa(e,t,n,r,i){let a=qi;qi=``;let o=n;for(;o<=r;++o){aa(e[o],i);let t=Wi.get(e[o]);t!==null&&R(t)?Ji===null&&(Ji=t.getFormat(),Yi=t.getStyle()):V(t)&&o<r&&!t.isInline()&&(qi+=ti)}i.element.__lexicalTextContent=qi,qi=a+qi}function sa(e,t){if(e){let n=e.__last;if(n){let e=t.get(n);if(e)return Jo(e)?`line-break`:Sc(e)&&e.isInline()?`decorator`:null}return`empty`}return null}function ca(e,t,n){let r=sa(e,Ui),i=sa(t,Wi);r!==i&&t.getDOMSlot(n).setManagedLineBreak(i)}function la(e,t,n){var r;Ji=null,Yi=null,function(e,t,n){let r=qi,i=e.__size,a=t.__size;qi=``;let o=n.element;if(i===1&&a===1){let n=e.__first,r=t.__first;if(n===r)da(n,o);else{let e=ga(n),t=aa(r,null);try{o.replaceChild(t,e)}catch(i){if(typeof i==`object`&&i){let a=`${i.toString()} Parent: ${o.tagName}, new child: {tag: ${t.tagName} key: ${r}}, old child: {tag: ${e.tagName}, key: ${n}}.`;throw Error(a)}throw i}Qi(n,null)}let i=Wi.get(r);R(i)&&Ji===null&&(Ji=i.getFormat(),Yi=i.getStyle())}else{let r=ua(e,Ui),s=ua(t,Wi);if(r.length!==i&&I(227),s.length!==a&&I(228),i===0)a!==0&&oa(s,0,0,a-1,n);else if(a===0){if(i!==0){let e=n.after==null&&n.before==null&&n.element.__lexicalLineBreak==null;$i(r,0,i-1,e?null:o),e&&(o.textContent=``)}}else (function(e,t,n,r,i,a){let o=r-1,s=i-1,c,l,u=a.getFirstChild(),d=0,f=0;for(;d<=o&&f<=s;){let e=t[d],r=n[f];if(e===r)u=pa(da(r,a.element)),d++,f++;else{if(l===void 0&&(l=ma(n,f)),c===void 0)c=ma(t,d);else if(!c.has(e)){d++;continue}if(!l.has(e)){u=pa(ga(e)),Qi(e,a.element),d++,c.delete(e);continue}if(c.has(r)){let e=zl(Ri,r);e!==u&&a.withBefore(u).insertChild(e),u=pa(da(r,a.element)),d++,f++}else aa(r,a.withBefore(u)),f++}let i=Wi.get(r);i!==null&&R(i)?Ji===null&&(Ji=i.getFormat(),Yi=i.getStyle()):V(i)&&f<=s&&!i.isInline()&&(qi+=ti)}let p=d>o,m=f>s;if(p&&!m){let e=n[s+1],t=e===void 0?null:Ri.getElementByKey(e);oa(n,0,f,s,a.withBefore(t))}else m&&!p&&$i(t,d,o,a.element)})(0,r,s,i,a,n)}o.__lexicalTextContent=qi,qi=r+qi}(e,t,t.getDOMSlot(n)),r=t,Ji==null||Ji===r.__textFormat||Zi||r.setTextFormat(Ji),function(e){Yi==null||Yi===e.__textStyle||Zi||e.setTextStyle(Yi)}(t)}function ua(e,t){let n=[],r=e.__first;for(;r!==null;){let e=t.get(r);e===void 0&&I(101),n.push(r),r=e.__next}return n}function da(e,t){let n=Ui.get(e),r=Wi.get(e);n!==void 0&&r!==void 0||I(61);let i=Xi||Hi.has(e)||Vi.has(e),a=zl(Ri,e);if(n===r&&!i){let e;if(V(n)){let t=a.__lexicalTextContent;typeof t==`string`?e=t:(e=n.getTextContent(),a.__lexicalTextContent=e)}else e=n.getTextContent();return qi+=e,a}if(n!==r&&i&&Fl(Ki,zi,Bi,r,`updated`),r.updateDOM(n,a,Li)){let n=aa(e,null);return t===null&&I(62),t.replaceChild(n,a),Qi(e,null),n}if(V(n)){V(r)||I(334,e);let t=r.__indent;(Xi||t!==n.__indent)&&na(a,t);let o=r.__format;if((Xi||o!==n.__format)&&ra(a,o),i)la(n,r,a),wc(r)||r.isInline()||ca(n,r,a);else{let e=a.__lexicalTextContent,t;typeof e==`string`?t=e:(t=n.getTextContent(),a.__lexicalTextContent=t),qi+=t}if((Xi||r.__dir!==n.__dir)&&(ia(a,r),wc(r)&&!Xi))for(let e of r.getChildren())V(e)&&ia(zl(Ri,e.getKey()),e)}else{let t=r.getTextContent();if(Sc(r)){let t=r.decorate(Ri,Li);t!==null&&fa(e,t)}qi+=t}if(!Zi&&wc(r)&&r.__cachedText!==qi){let e=r.getWritable();e.__cachedText=qi,r=e}return a}function fa(e,t){let n=Ri._pendingDecorators,r=Ri._decorators;if(n===null){if(r[e]===t)return;n=ml(Ri)}n[e]=t}function pa(e){let t=e.nextSibling;return t!==null&&t===Ri._blockCursorElement&&(t=t.nextSibling),t}function ma(e,t){let n=new Set;for(let r=t;r<e.length;r++)n.add(e[r]);return n}function ha(e,t,n,r,i,a){qi=``,Xi=r===2,Ri=n,Li=n._config,zi=n._nodes,Bi=Ri._listeners.mutation,Vi=i,Hi=a,Ui=e._nodeMap,Wi=t._nodeMap,Zi=t._readOnly,Gi=new Map(n._keyToDOMMap);let o=new Map;return Ki=o,da(`root`,null),Ri=void 0,zi=void 0,Vi=void 0,Hi=void 0,Ui=void 0,Wi=void 0,Li=void 0,Gi=void 0,Ki=void 0,o}function ga(e){let t=Gi.get(e);return t===void 0&&I(75,e),t}function L(e){return{type:e}}var _a=L(`SELECTION_CHANGE_COMMAND`),va=L(`CLICK_COMMAND`),ya=L(`BEFORE_INPUT_COMMAND`),ba=L(`INPUT_COMMAND`),xa=L(`COMPOSITION_START_COMMAND`),Sa=L(`COMPOSITION_END_COMMAND`),Ca=L(`DELETE_CHARACTER_COMMAND`),wa=L(`INSERT_LINE_BREAK_COMMAND`),Ta=L(`INSERT_PARAGRAPH_COMMAND`),Ea=L(`CONTROLLED_TEXT_INSERTION_COMMAND`),Da=L(`PASTE_COMMAND`),Oa=L(`REMOVE_TEXT_COMMAND`),ka=L(`DELETE_WORD_COMMAND`),Aa=L(`DELETE_LINE_COMMAND`),ja=L(`FORMAT_TEXT_COMMAND`),Ma=L(`UNDO_COMMAND`),Na=L(`REDO_COMMAND`),Pa=L(`KEYDOWN_COMMAND`),Fa=L(`KEY_ARROW_RIGHT_COMMAND`),Ia=L(`MOVE_TO_END`),La=L(`KEY_ARROW_LEFT_COMMAND`),Ra=L(`MOVE_TO_START`),za=L(`KEY_ARROW_UP_COMMAND`),Ba=L(`KEY_ARROW_DOWN_COMMAND`),Va=L(`KEY_ENTER_COMMAND`),Ha=L(`KEY_SPACE_COMMAND`),Ua=L(`KEY_BACKSPACE_COMMAND`),Wa=L(`KEY_ESCAPE_COMMAND`),Ga=L(`KEY_DELETE_COMMAND`),Ka=L(`KEY_TAB_COMMAND`),qa=L(`DROP_COMMAND`),Ja=L(`DRAGSTART_COMMAND`),Ya=L(`DRAGOVER_COMMAND`),Xa=L(`DRAGEND_COMMAND`),Za=L(`COPY_COMMAND`),Qa=L(`CUT_COMMAND`),$a=L(`SELECT_ALL_COMMAND`),eo=L(`FOCUS_COMMAND`),to=L(`BLUR_COMMAND`),no=L(`KEY_MODIFIER_COMMAND`),ro=Object.freeze({}),io=[[`keydown`,function(e,t){ao=e.timeStamp,oo=e.key,!t.isComposing()&&U(t,Pa,e)}],[`pointerdown`,function(e,t){let n=e.target,r=e.pointerType;ru(n)&&r!==`touch`&&r!==`pen`&&e.button===0&&gc(t,()=>{qc(n)||(po=!0)})}],[`compositionstart`,function(e,t){U(t,xa,e)}],[`compositionend`,function(e,t){Lr?ho=!0:zr||!Vr&&!Wr?U(t,Sa,e):(go=!0,_o=e.data)}],[`input`,function(e,t){e.stopPropagation(),gc(t,()=>{t.dispatchCommand(ba,e)},{event:e}),co=null}],[`click`,function(e,t){gc(t,()=>{let n=B(),r=eu(Kl(t)),i=Is();if(r){if(z(n)){let t=n.anchor,a=t.getNode();if(t.type===`element`&&t.offset===0&&n.isCollapsed()&&!wc(a)&&gl().getChildrenSize()===1&&a.getTopLevelElementOrThrow().isEmpty()&&i!==null&&n.is(i))r.removeAllRanges(),n.dirty=!0;else if(e.detail===3&&!n.isCollapsed()&&a!==n.focus.getNode()){let e=yu(a,e=>V(e)&&!e.isInline());V(e)&&e.select(0)}}else if(e.pointerType===`touch`||e.pointerType===`pen`){let n=r.anchorNode;(nu(n)||tl(n))&&vl(Fs(i,r,t,e))}}U(t,va,e)})}],[`cut`,ro],[`copy`,ro],[`dragstart`,ro],[`dragover`,ro],[`dragend`,ro],[`paste`,ro],[`focus`,ro],[`blur`,ro],[`drop`,ro]];Rr&&io.push([`beforeinput`,(e,t)=>function(e,t){let n=e.inputType;n===`deleteCompositionText`||Lr&&Rl(t)||n!==`insertCompositionText`&&U(t,ya,e)}(e,t)]);var ao=0,oo=null,so=0,co=null,lo=new WeakMap,uo=new WeakMap,fo=!1,po=!1,mo=!1,ho=!1,go=!1,_o=``,vo=null,yo=[0,``,0,`root`,0];function bo(e,t,n,r,i){let a=e.anchor,o=e.focus,s=a.getNode(),c=rc(),l=eu(Kl(c)),u=l===null?null:l.anchorNode,d=a.key,f=c.getElementByKey(d),p=n.length;return d!==o.key||!R(s)||(!i&&(!Rr||so<r+50)||s.isDirty()&&p<2||bl(n))&&a.offset!==o.offset&&!s.isComposing()||el(s)||s.isDirty()&&p>1||(i||!Rr)&&f!==null&&!s.isComposing()&&u!==rl(f)||l!==null&&t!==null&&(!t.collapsed||t.startContainer!==l.anchorNode||t.startOffset!==l.anchorOffset)||!s.isComposing()&&(s.getFormat()!==e.format||s.getStyle()!==e.style)||function(e,t){if(t.isSegmented())return!0;if(!e.isCollapsed())return!1;let n=e.anchor.offset,r=t.getParentOrThrow(),i=$c(t);return n===0?!t.canInsertTextBefore()||!r.canInsertTextBefore()&&!t.isComposing()||i||function(e){let t=e.getPreviousSibling();return(R(t)||V(t)&&t.isInline())&&!t.canInsertTextAfter()}(t):n===t.getTextContentSize()&&(!t.canInsertTextAfter()||!r.canInsertTextAfter()&&!t.isComposing()||i)}(e,s)}function xo(e,t){return tl(e)&&e.nodeValue!==null&&t!==0&&t!==e.nodeValue.length}function So(e,t,n){let{anchorNode:r,anchorOffset:i,focusNode:a,focusOffset:o}=e;fo&&(fo=!1,xo(r,i)&&xo(a,o)&&!vo)||gc(t,()=>{if(!n)return void vl(null);if(!Yc(t,r,a))return;let s=B();if(vo&&z(s)&&s.isCollapsed()){let e=s.anchor,t=vo.anchor;(e.key===t.key&&e.offset===t.offset+1||e.offset===1&&t.getNode().is(e.getNode().getPreviousSibling()))&&(s=vo.clone(),vl(s))}if(vo=null,z(s)){let n=s.anchor,r=n.getNode();if(s.isCollapsed()){e.type===`Range`&&e.anchorNode===e.focusNode&&(s.dirty=!0);let i=Kl(t).event,a=i?i.timeStamp:performance.now(),[o,c,l,u,d]=yo,f=gl(),p=!1===t.isComposing()&&f.getTextContent()===``;if(a<d+200&&n.offset===l&&n.key===u)Co(s,o,c);else if(n.type===`text`)R(r)||I(141),wo(s,r);else if(n.type===`element`&&!p){V(r)||I(259);let e=n.getNode();e.isEmpty()?function(e,t){Co(e,t.getTextFormat(),t.getTextStyle())}(s,e):Co(s,s.format,``)}}else{let e=n.key,t=s.focus.key,r=s.getNodes(),a=r.length,c=s.isBackward(),l=c?o:i,u=c?i:o,d=c?t:e,f=c?e:t,p=2047,m=!1;for(let e=0;e<a;e++){let t=r[e],n=t.getTextContentSize();if(R(t)&&n!==0&&!(e===0&&t.__key===d&&l===n||e===a-1&&t.__key===f&&u===0)&&(m=!0,p&=t.getFormat(),p===0))break}s.format=m?p:0}}U(t,_a,void 0)})}function Co(e,t,n){e.format===t&&e.style===n||(e.format=t,e.style=n,e.dirty=!0)}function wo(e,t){Co(e,t.getFormat(),t.getStyle())}function To(e){if(!e.getTargetRanges)return null;let t=e.getTargetRanges();return t.length===0?null:t[0]}function Eo(e){let t=e.inputType,n=To(e),r=rc(),i=B();if(t===`deleteContentBackward`){if(i===null){let e=Is();if(!z(e))return!0;vl(e.clone())}if(z(i)){let t=i.anchor.key===i.focus.key;if(a=e.timeStamp,oo===`MediaLast`&&a<ao+30&&r.isComposing()&&t){if(cl(null),ao=0,setTimeout(()=>{gc(r,()=>{cl(null)})},30),z(i)){let e=i.anchor.getNode();e.markDirty(),R(e)||I(142),wo(i,e)}}else{cl(null),e.preventDefault();let n=i.anchor.getNode(),a=n.getTextContent(),o=n.canInsertTextAfter(),s=i.anchor.offset===0&&i.focus.offset===a.length,c=Ur&&t&&!s&&o;if(c&&i.isCollapsed()&&(c=!Sc(Ll(i.anchor,!0))),!c){U(r,Ca,!0);let e=B();Ur&&z(e)&&e.isCollapsed()&&(vo=e,setTimeout(()=>vo=null))}}return!0}}var a;if(!z(i))return!0;let o=e.data;co!==null&&wl(!1,r,co),i.dirty&&co===null||!i.isCollapsed()||wc(i.anchor.getNode())||n===null||i.applyDOMRange(n),co=null;let s=i.anchor,c=i.focus,l=s.getNode(),u=c.getNode();if(t===`insertText`||t===`insertTranspose`){if(o===`
|
|
4
4
|
`)e.preventDefault(),U(r,wa,!1);else if(o===ti)e.preventDefault(),U(r,Ta,void 0);else if(o==null&&e.dataTransfer){let t=e.dataTransfer.getData(`text/plain`);e.preventDefault(),i.insertRawText(t)}else o!=null&&bo(i,n,o,e.timeStamp,!0)?(e.preventDefault(),U(r,Ea,o)):co=o;return so=e.timeStamp,!0}switch(e.preventDefault(),t){case`insertFromYank`:case`insertFromDrop`:case`insertReplacementText`:U(r,Ea,e);break;case`insertFromComposition`:cl(null),U(r,Ea,e);break;case`insertLineBreak`:cl(null),U(r,wa,!1);break;case`insertParagraph`:cl(null),mo&&!zr?(mo=!1,U(r,wa,!1)):U(r,Ta,void 0);break;case`insertFromPaste`:case`insertFromPasteAsQuotation`:U(r,Da,e);break;case`deleteByComposition`:(function(e,t){return e!==t||V(e)||V(t)||!$c(e)||!$c(t)})(l,u)&&U(r,Oa,e);break;case`deleteByDrag`:case`deleteByCut`:U(r,Oa,e);break;case`deleteContent`:U(r,Ca,!1);break;case`deleteWordBackward`:U(r,ka,!0);break;case`deleteWordForward`:U(r,ka,!1);break;case`deleteHardLineBackward`:case`deleteSoftLineBackward`:U(r,Aa,!0);break;case`deleteContentForward`:case`deleteHardLineForward`:case`deleteSoftLineForward`:U(r,Aa,!1);break;case`formatStrikeThrough`:U(r,ja,`strikethrough`);break;case`formatBold`:U(r,ja,`bold`);break;case`formatItalic`:U(r,ja,`italic`);break;case`formatUnderline`:U(r,ja,`underline`);break;case`historyUndo`:U(r,Ma,void 0);break;case`historyRedo`:U(r,Na,void 0)}return!0}function Do(e){if(nu(e.target)&&qc(e.target))return!0;let t=rc(),n=B(),r=e.data,i=To(e);if(r!=null&&z(n)&&bo(n,i,r,e.timeStamp,!1)){ho&&=(Ao(t,r),!1);let i=n.anchor.getNode(),a=eu(Kl(t));if(a===null)return!0;let o=n.isBackward(),s=o?n.anchor.offset:n.focus.offset,c=o?n.focus.offset:n.anchor.offset;Rr&&!n.isCollapsed()&&R(i)&&a.anchorNode!==null&&i.getTextContent().slice(0,s)+r+i.getTextContent().slice(s+c)===Cl(a.anchorNode)||U(t,Ea,r);let l=r.length;Lr&&l>1&&e.inputType===`insertCompositionText`&&!t.isComposing()&&(n.anchor.offset-=l),Ur&&t.isComposing()&&(ao=0,cl(null))}else wl(!1,t,r===null?void 0:r),ho&&=(Ao(t,r||void 0),!1);return function(){ec(),yi(rc())}(),!0}function Oo(e){let t=rc(),n=B();if(z(n)&&!t.isComposing()){let r=n.anchor,i=n.anchor.getNode();cl(r.key),Hl(Uo),(e.timeStamp<ao+30||r.type===`element`||!n.isCollapsed()||i.getFormat()!==n.format||R(i)&&i.getStyle()!==n.style)&&U(t,Ea,ni)}return!0}function ko(e){return Ao(rc(),e.data),Hl(Wo),!0}function Ao(e,t){let n=e._compositionKey;if(cl(null),n!==null&&t!=null){if(t===``){let t=ul(n),r=rl(e.getElementByKey(n));if(r!==null&&r.nodeValue!==null&&R(t)){let n=eu(Kl(e)),i=null,a=null;n!==null&&n.anchorNode===r&&(i=n.anchorOffset,a=n.focusOffset),Tl(t,r.nodeValue,i,a,!0)}return}if(t[t.length-1]===`
|
|
@@ -48,14 +48,14 @@ https://github.com/highlightjs/highlight.js/issues/2277`),i=e,r=t),n===void 0&&(
|
|
|
48
48
|
`)}function SE(e){return/^\+\d+$/.test(e)?`text-emerald-700`:/^-\d+$/.test(e)?`text-rose-700`:`text-stone-500`}function CE(e){let t=e.split(`·`).map(e=>e.trim()).filter(e=>/^\+\d+$/.test(e)||/^-\d+$/.test(e));return t.length===0?null:(0,N.jsx)(`div`,{className:`flex shrink-0 items-center gap-x-1 whitespace-nowrap text-[10px] font-medium uppercase tracking-[0.08em]`,children:t.map((e,t)=>(0,N.jsxs)(P.Fragment,{children:[t>0?(0,N.jsx)(`span`,{className:`text-stone-300`,children:`·`}):null,(0,N.jsx)(`span`,{className:F(SE(e)),children:e})]},`${e}-${t}`))})}function wE(e){return{path:e.path,label:e.path.split(`/`).filter(Boolean).pop()??e.path,viewMode:e.display===`diff`?`diff`:`preview`,...e.rawText?{rawText:e.rawText}:{},...e.beforeText?{beforeText:e.beforeText}:{},...e.afterText?{afterText:e.afterText}:{},...e.patchText?{patchText:e.patchText}:{},...typeof e.oldStartLine==`number`?{oldStartLine:e.oldStartLine}:{},...typeof e.newStartLine==`number`?{newStartLine:e.newStartLine}:{},fullLines:e.fullLines??e.lines}}function TE({children:e,contentVersion:t,resetKey:n,className:r,scrollKind:i}){let a=(0,P.useRef)(null),{onScroll:o}=qT({scrollRef:a,resetKey:n,isLoading:!1,hasContent:!0,contentVersion:t,stickyThresholdPx:20});return(0,N.jsx)(`div`,{ref:a,onScroll:o,"data-file-scroll-kind":i,className:F(`overflow-y-auto bg-white custom-scrollbar-amber`,r),children:e})}function EE({block:e,showPathRow:t,isFirst:n,onFileOpen:r}){let{Tooltip:i,TooltipContent:a,TooltipProvider:o,TooltipTrigger:s}=lr,c=bE(e),l=t||!!e.caption;return(0,N.jsxs)(`section`,{className:F(`overflow-hidden bg-white`,!n&&`border-t border-stone-200/80`),children:[l?(0,N.jsxs)(`div`,{className:F(`flex items-center justify-between gap-4 border-b border-stone-200/80 px-4 text-stone-700`,t?`py-2`:`py-1.5`),children:[(0,N.jsx)(`div`,{className:`min-w-0 flex-1`,children:t?(0,N.jsx)(o,{delayDuration:250,children:(0,N.jsxs)(i,{children:[(0,N.jsx)(s,{asChild:!0,children:(0,N.jsx)(`button`,{type:`button`,onClick:()=>{r&&r(wE(e))},className:F(`w-full truncate whitespace-nowrap text-left font-mono text-[12px] font-medium text-stone-700`,r&&`transition-colors hover:text-amber-900 hover:underline`),title:e.path,children:e.path})}),(0,N.jsx)(a,{side:`top`,className:`max-w-[420px] text-xs font-mono break-all`,children:e.path})]})}):null}),e.caption?CE(e.caption):null]}):null,e.lines.length>0?(0,N.jsx)(TE,{resetKey:`block:${e.key}`,contentVersion:xE(e),className:`max-h-72`,scrollKind:`block`,children:(0,N.jsx)(yE,{block:e})}):e.rawText?(0,N.jsx)(TE,{resetKey:`raw:${e.key}`,contentVersion:e.rawText,className:`max-h-72`,scrollKind:`raw`,children:(0,N.jsx)(`div`,{className:`overflow-x-auto custom-scrollbar-amber`,children:(0,N.jsx)(`pre`,{className:`min-w-max whitespace-pre bg-white px-4 py-2 font-mono text-[11px] leading-5 text-amber-950/80`,children:e.rawText})})}):null,e.truncated&&!c?(0,N.jsx)(`div`,{className:`border-t border-stone-200/85 bg-stone-50 px-4 py-2 text-[10px] text-stone-500`,children:`Showing a shortened diff preview.`}):null]})}function DE({card:e,className:t,onFileOpen:n}){let r=e.fileOperation?.blocks??[],i=e.output?.trim()??``;return r.length===0&&!i?null:(0,N.jsxs)(`div`,{className:F(`overflow-hidden bg-white`,t),children:[r.map((e,t)=>(0,N.jsx)(EE,{block:e,showPathRow:!0,isFirst:t===0,onFileOpen:n},e.key)),i?(0,N.jsx)(TE,{resetKey:`output:${e.toolName}:${e.summary??`none`}`,contentVersion:i,className:F(`max-h-56`,r.length>0&&`border-t border-stone-200/80`),scrollKind:`output`,children:(0,N.jsx)(`div`,{className:`overflow-x-auto custom-scrollbar-amber`,children:(0,N.jsx)(`pre`,{className:`min-w-max whitespace-pre bg-white px-4 py-2 font-mono text-[11px] leading-5 text-amber-950/80`,children:i})})}):null]})}var OE=200,kE=RegExp(`\x1B\\[[0-?]*[ -/]*[@-~]`,`g`);function AE(e){return typeof e==`string`&&e.length>0?e:null}function jE(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function ME(e){return e.replace(kE,``)}function NE(e){return`command`in e||`workingDir`in e||`exitCode`in e||`durationMs`in e||`stdout`in e||`stderr`in e||`aggregated_output`in e||`combinedOutput`in e}function PE(e){let t=AE(e.aggregated_output)??AE(e.combinedOutput)??AE(e.output);if(t)return t;let n=AE(e.stdout),r=AE(e.stderr);return!n&&!r?null:[n,r].filter(e=>!!e).join(`
|
|
49
49
|
`)}function FE(e,t){if(jE(t)){let e=PE(t);if(e)return ME(e);if(NE(t))return``}if(!e)return``;let n=e.trim();if(!n.startsWith(`{`))return ME(e);try{let t=JSON.parse(n);if(!jE(t))return ME(e);let r=PE(t);return r?ME(r):NE(t)?``:ME(e)}catch{return ME(e)}}function IE(e){return e===`write_file`||e===`edit_file`}function LE({canExpand:e,isRunning:t,autoExpandWhileRunning:n=!0,expandOnError:r=!1,statusTone:i}){let[a,o]=(0,P.useState)(!1),[s,c]=(0,P.useState)(!1),l=(0,P.useRef)(null),u=(0,P.useRef)(t),d=(0,P.useRef)(!0);return(0,P.useEffect)(()=>()=>{l.current!==null&&window.clearTimeout(l.current)},[]),(0,P.useEffect)(()=>{if(r&&i===`error`&&e&&!s){l.current!==null&&(window.clearTimeout(l.current),l.current=null),o(!0),u.current=t,d.current=!1;return}n&&t&&e&&!s&&!a&&(d.current||!u.current)&&(l.current=window.setTimeout(()=>{o(!0),l.current=null},OE)),t||(l.current!==null&&(window.clearTimeout(l.current),l.current=null),u.current&&!s&&o(!1)),u.current=t,d.current=!1},[n,e,r,a,s,t,i]),{expanded:a,onToggle:()=>{e&&(l.current!==null&&(window.clearTimeout(l.current),l.current=null),o(e=>!e),c(!0))}}}function RE({label:e,tone:t,children:n}){let r={input:{shell:`border-stone-200/80 bg-stone-50/90`,header:`border-stone-200/80 bg-stone-100/85 text-stone-500`,dot:`bg-stone-400/80`,body:`text-stone-700`},output:{shell:`border-amber-200/70 bg-white/90`,header:`border-amber-200/70 bg-amber-50/90 text-amber-700`,dot:`bg-amber-500/80`,body:`text-amber-950/80`},error:{shell:`border-rose-200/80 bg-rose-50/85`,header:`border-rose-200/80 bg-rose-100/80 text-rose-700`,dot:`bg-rose-500/80`,body:`text-rose-950/85`}}[t];return(0,N.jsxs)(`section`,{className:F(`overflow-hidden rounded-md border shadow-[inset_0_1px_0_rgba(255,255,255,0.45)]`,r.shell),children:[(0,N.jsxs)(`div`,{className:F(`flex items-center gap-2 border-b px-3 py-2 text-[10px] font-semibold uppercase tracking-[0.16em]`,r.header),children:[(0,N.jsx)(`span`,{className:F(`h-1.5 w-1.5 rounded-full`,r.dot)}),(0,N.jsx)(`span`,{children:e})]}),(0,N.jsx)(`div`,{className:`w-full overflow-hidden`,children:(0,N.jsx)(`pre`,{className:F(`w-full max-w-full min-w-0 max-h-64 overflow-x-auto overflow-y-auto px-3 py-2.5 font-mono text-[12px] leading-relaxed whitespace-pre custom-scrollbar-amber`,r.body),children:n})})]})}function zE({card:e}){let t=FE(e.output,e.outputData),n=e.statusTone===`running`,r=!!(e.summary?.trim()||t.trim().length>0),{expanded:i,onToggle:a}=LE({canExpand:t.trim().length>0||n,isRunning:n,autoExpandWhileRunning:!1,expandOnError:r,statusTone:e.statusTone}),o=e.summary?.replace(/^(command|path|args|query|input):\s*/i,``);return(0,N.jsxs)(XT,{children:[(0,N.jsx)(tE,{card:e,icon:cn,expanded:i,canExpand:t.trim().length>0||n,onToggle:a}),i&&(0,N.jsxs)(N.Fragment,{children:[(0,N.jsx)(`div`,{className:`px-3 pb-2 font-mono w-full max-h-48 overflow-y-auto custom-scrollbar-amber min-h-0 text-[12px]`,children:(0,N.jsxs)(`div`,{className:`flex items-start gap-2 leading-relaxed`,children:[(0,N.jsx)(`span`,{className:`text-amber-500/50 font-medium shrink-0 select-none mt-[1px]`,children:`$`}),(0,N.jsx)(`div`,{className:`flex-1 min-w-0`,children:o?(0,N.jsxs)(`div`,{className:`text-amber-950/80 break-words whitespace-pre-wrap tracking-tight font-medium inline-block`,children:[o,n&&!t&&(0,N.jsx)(`span`,{className:`inline-block w-1.5 h-3 ml-1 bg-amber-500/60 animate-pulse align-middle`})]}):(0,N.jsx)(`div`,{className:`h-3 w-32 bg-amber-200/30 rounded animate-pulse mt-2`})})]})}),t&&(0,N.jsx)(ZT,{children:(0,N.jsxs)(`pre`,{className:`font-mono text-[12px] text-amber-950/70 whitespace-pre-wrap break-all w-full max-w-full max-h-64 overflow-y-auto overflow-x-hidden min-w-0 custom-scrollbar-amber leading-relaxed px-0`,children:[t,n&&(0,N.jsx)(`span`,{className:`inline-block w-1.5 h-3 ml-1 bg-amber-500/60 animate-pulse align-middle`})]})})]})]})}function BE({card:e,onFileOpen:t}){let n=e.output?.trim()??``,r=e.statusTone===`running`,i=!!e.fileOperation?.blocks.length,a=i||!!n,o=e.fileOperation?.blocks??[],s=o.reduce((e,t)=>e+t.lines.length,0),c=o.reduce((e,t)=>t.rawText?e+t.rawText.length:e+t.lines.reduce((e,t)=>e+t.text.length+1,0),0),l=IE(e.toolName)&&!(r&&e.toolName===`write_file`&&(s>24||c>1200)),{expanded:u,onToggle:d}=LE({canExpand:a||r,isRunning:r,autoExpandWhileRunning:l,expandOnError:a,statusTone:e.statusTone});return(0,N.jsxs)(XT,{children:[(0,N.jsx)(tE,{card:e,icon:e.toolName===`edit_file`||e.toolName===`write_file`||e.toolName===`apply_patch`||e.toolName===`file_change`?Lt:Kt,expanded:u,canExpand:a||r,hideSummary:u&&i,onToggle:d}),u&&a&&(0,N.jsx)(ZT,{className:`border-t border-amber-200/20 bg-transparent px-0 pt-0 pb-0`,children:(0,N.jsx)(DE,{card:e,onFileOpen:t})})]})}function VE({card:e}){let t=e.statusTone===`running`,n=e.output?.trim()??``,{expanded:r,onToggle:i}=LE({canExpand:!!n||t,isRunning:t,autoExpandWhileRunning:!1,statusTone:e.statusTone});return(0,N.jsxs)(XT,{children:[(0,N.jsx)(tE,{card:e,icon:Oe,expanded:r,canExpand:!!n||t,onToggle:i}),r&&n&&(0,N.jsx)(ZT,{children:(0,N.jsx)(`pre`,{className:`font-mono text-[12px] text-amber-950/70 whitespace-pre-wrap break-all w-full max-w-full max-h-64 overflow-y-auto overflow-x-hidden min-w-0 custom-scrollbar-amber leading-relaxed`,children:n})})]})}function HE({card:e,onToolAction:t,renderToolAgent:n}){let r=e.input?.trim()??``,i=e.output?.trim()??``,a=e.statusTone===`running`,o=r.length>0,s=i.length>0,c=o||s,l=e.inputLabel?.trim()||`Input`,u=e.outputLabel?.trim()||`Output`,{expanded:d,onToggle:f}=LE({canExpand:c||a,isRunning:a,autoExpandWhileRunning:!1,statusTone:e.statusTone});return(0,N.jsxs)(XT,{children:[(0,N.jsx)(tE,{card:e,icon:et,expanded:d,canExpand:c||a,actionSlot:e.agentId||e.action&&t?(0,N.jsxs)(N.Fragment,{children:[e.agentId&&n?n(e.agentId):null,e.action&&t?(0,N.jsx)(nE,{action:e.action,onAction:t}):null]}):void 0,onToggle:f}),d&&c&&(0,N.jsxs)(ZT,{className:`bg-transparent px-2.5 py-2.5`,children:[o&&(0,N.jsx)(RE,{label:l,tone:`input`,children:r}),o&&s&&(0,N.jsx)(`div`,{className:`h-2`}),s&&(0,N.jsx)(RE,{label:u,tone:e.statusTone===`error`?`error`:`output`,children:i})]})]})}function UE(e){let t=e.toLowerCase();return t===`exec`||t===`exec_command`||t===`execute_command`||t===`command_execution`||t===`bash`||t===`shell`||t.includes(`run_`)}function WE(e){let t=e.toLowerCase();return t===`read_file`||t===`write_file`||t===`edit_file`||t===`apply_patch`||t===`file_change`}function GE(e){let t=e.toLowerCase();return t===`grep_search`||t===`find_files`||t.includes(`search`)}function KE({card:e,onToolAction:t,onFileOpen:n,renderToolAgent:r}){return UE(e.toolName)?(0,N.jsx)(zE,{card:e}):WE(e.toolName)?(0,N.jsx)(BE,{card:e,onFileOpen:n}):GE(e.toolName)?(0,N.jsx)(VE,{card:e}):(0,N.jsx)(HE,{card:e,onToolAction:t,renderToolAgent:r})}function qE(e){return(0,N.jsxs)(`div`,{className:`rounded-lg border border-gray-200 bg-gray-50 px-2.5 py-2 text-xs text-gray-600`,children:[(0,N.jsxs)(`div`,{className:`font-semibold text-gray-700`,children:[e.label,`: `,e.rawType]}),e.text?(0,N.jsx)(`pre`,{className:`mt-1 whitespace-pre-wrap break-words text-[11px] text-gray-500`,children:e.text}):null]})}var JE=(0,P.memo)(function(e){let{message:t,texts:n,onToolAction:r,onFileOpen:i,renderToolAgent:a}=e,{role:o}=t,s=o===`user`,c=t.status===`pending`||t.status===`streaming`;return(0,N.jsx)(`div`,{className:F(`inline-block w-fit max-w-full rounded-2xl border px-4 shadow-sm`,s?`border-primary bg-primary py-3 text-white`:o===`assistant`?`border-gray-200 bg-white pb-3 pt-4 text-gray-900`:`border-orange-200/80 bg-orange-50/70 py-3 text-gray-900`),children:(0,N.jsx)(`div`,{className:`space-y-2`,children:t.parts.map((e,l)=>{let{type:u}=e;return u===`markdown`?(0,N.jsx)(cT,{text:e.text,role:o,texts:n,onFileOpen:i},`markdown-${l}`):u===`inline-content`?(0,N.jsx)(fT,{segments:e.segments,role:o,texts:n,onFileOpen:i},`inline-content-${l}`):u===`reasoning`?(0,N.jsx)(YT,{label:e.label,text:e.text,isUser:s,isInProgress:c&&l===t.parts.length-1},`reasoning-${l}`):u===`tool-card`?(0,N.jsx)(`div`,{className:`mt-0.5`,children:(0,N.jsx)(KE,{card:e.card,onToolAction:r,onFileOpen:i,renderToolAgent:a})},`tool-${l}`):u===`file`?(0,N.jsx)(HT,{file:e.file,isUser:s,texts:n},`file-${l}`):u===`unknown`?(0,N.jsx)(qE,{label:e.label,rawType:e.rawType,text:e.text},`unknown-${l}`):null})})})});function YE(e){return(0,N.jsxs)(`div`,{className:F(`px-1 text-[11px] leading-4 text-gray-400`,e.isUser?`text-right`:`text-left`),children:[e.roleLabel,` · `,e.timestampLabel]})}function XE({message:e,texts:t}){let n=(0,P.useMemo)(()=>e.parts.map(e=>e.type===`markdown`||e.type===`unknown`?e.text:``).filter(e=>!!e&&e.trim().length>0).join(`
|
|
50
50
|
|
|
51
|
-
`),[e.parts]),{copied:r,copy:i}=iw({text:n});return n?(0,N.jsx)(`button`,{type:`button`,onClick:()=>void i(),className:`text-gray-400 hover:text-gray-600 transition-colors p-1 rounded-md hover:bg-gray-100 flex items-center justify-center`,"aria-label":r?t.copiedMessageLabel:t.copyMessageLabel,title:r?t.copiedMessageLabel:t.copyMessageLabel,children:r?(0,N.jsx)(Be,{className:`h-3.5 w-3.5`}):(0,N.jsx)(Rt,{className:`h-3.5 w-3.5`})}):null}var ZE=/\u200B|\u200C|\u200D|\u2060|\uFEFF/g;function QE(e){let t=e.trim();return t?t.replace(ZE,``).trim().length>0:!1}function $E(e){return e.parts.some(e=>e.type===`markdown`||e.type===`reasoning`?QE(e.text):!0)}function eD(){return(0,N.jsx)(`div`,{className:`flex items-center gap-2 px-1 py-0.5 text-[11px] text-gray-400`,children:(0,N.jsxs)(`div`,{className:`flex space-x-1 items-center h-full`,children:[(0,N.jsx)(`div`,{className:`h-1.5 w-1.5 rounded-full bg-gray-400 animate-pulse`}),(0,N.jsx)(`div`,{className:`h-1.5 w-1.5 rounded-full bg-gray-400 animate-pulse [animation-delay:200ms]`}),(0,N.jsx)(`div`,{className:`h-1.5 w-1.5 rounded-full bg-gray-400 animate-pulse [animation-delay:400ms]`})]})})}function tD(e){let t=e.messages.filter($E),n=t.some(e=>e.role===`assistant`&&(e.status===`streaming`||e.status===`pending`));return(0,N.jsxs)(`div`,{className:F(`space-y-5`,e.className),children:[t.map(t=>{let n=t.role===`user`,r=!n&&(t.status===`streaming`||t.status===`pending`);return(0,N.jsxs)(`div`,{className:F(`flex gap-3`,n?`justify-end`:`justify-start`),children:[n?null:(0,N.jsx)(_m,{role:t.role}),(0,N.jsxs)(`div`,{className:F(`w-fit max-w-[92%] space-y-2`,n&&`flex flex-col items-end`),children:[(0,N.jsx)(JE,{message:t,texts:e.texts,onToolAction:e.onToolAction,onFileOpen:e.onFileOpen,renderToolAgent:e.renderToolAgent}),(0,N.jsx)(`div`,{className:F(`flex items-center gap-2`,n&&`justify-end`),children:r?(0,N.jsx)(eD,{}):(0,N.jsxs)(N.Fragment,{children:[(0,N.jsx)(YE,{roleLabel:t.roleLabel,timestampLabel:t.timestampLabel,isUser:n}),n?null:(0,N.jsx)(XE,{message:t,texts:e.texts})]})})]}),n?(0,N.jsx)(_m,{role:t.role}):null]},t.id)}),e.isSending&&!n?(0,N.jsxs)(`div`,{className:`flex justify-start gap-3`,children:[(0,N.jsx)(_m,{role:`assistant`}),(0,N.jsx)(`div`,{className:`rounded-2xl border border-gray-200 bg-white px-4 py-3 text-sm text-gray-500 shadow-sm`,children:e.texts.typingLabel})]}):null]})}var nD=function(e){return e.EndpointReady=`endpoint.ready`,e.EndpointError=`endpoint.error`,e.MessageRequest=`message.request`,e.MessageStreamRequest=`message.stream-request`,e.MessageSent=`message.sent`,e.MessageAccepted=`message.accepted`,e.MessageIncoming=`message.incoming`,e.MessageCompleted=`message.completed`,e.MessageFailed=`message.failed`,e.MessageAbort=`message.abort`,e.MessageTextStart=`message.text-start`,e.MessageTextDelta=`message.text-delta`,e.MessageTextEnd=`message.text-end`,e.MessageReasoningStart=`message.reasoning-start`,e.MessageReasoningDelta=`message.reasoning-delta`,e.MessageReasoningEnd=`message.reasoning-end`,e.MessageToolCallStart=`message.tool-call-start`,e.MessageToolCallArgs=`message.tool-call-args`,e.MessageToolCallArgsDelta=`message.tool-call-args-delta`,e.MessageToolCallEnd=`message.tool-call-end`,e.MessageToolCallResult=`message.tool-call-result`,e.MessageRead=`message.read`,e.MessageDelivered=`message.delivered`,e.MessageRecalled=`message.recalled`,e.MessageReaction=`message.reaction`,e.RunStarted=`run.started`,e.RunFinished=`run.finished`,e.RunError=`run.error`,e.RunMetadata=`run.metadata`,e.ContextWindowUpdated=`context-window.updated`,e.TypingStart=`typing.start`,e.TypingEnd=`typing.end`,e.PresenceUpdated=`presence.updated`,e}({}),rD=/\[\[\s*reply_to_current\s*\]\]/gi,iD=/\[\[\s*reply_to\s*:\s*([^\]]+?)\s*\]\]/i;function aD(e){if(typeof e!=`string`)return;let t=e.trim();return t.length>0?t:void 0}function oD(e,t){let n=e,r;rD.test(n)&&(r=aD(t),n=n.replace(rD,``).trim());let i=n.match(iD)?.[1];return i&&(r=aD(i),n=n.replace(iD,``).trim()),r?{content:n,replyTo:r}:{content:n}}function sD(e,t=e.id){if(e.role!==`assistant`)return{...e,parts:[...e.parts],metadata:e.metadata?{...e.metadata}:void 0};let n=e.parts.findIndex(e=>e.type===`text`),r=e.metadata?{...e.metadata}:void 0,i=aD(r?.reply_to);if(n<0)return{...e,parts:[...e.parts],metadata:r};let a=e.parts[n];if(!a||a.type!==`text`)return{...e,parts:[...e.parts],metadata:r};let{content:o,replyTo:s}=oD(a.text,t),c=s??i,l=e.parts.flatMap((e,t)=>t!==n||e.type!==`text`?[e]:o.length===0?[]:[{...e,text:o}]);return c?{...e,parts:l,metadata:{...r,reply_to:c}}:{...e,parts:l,metadata:r}}function cD(e){return{...e,parts:[...e.parts],metadata:e.metadata?{...e.metadata}:void 0}}function lD(e){return cD(sD(e))}var uD=`__nextclaw_aborted_tool_call__`;function dD(e){let t=e.error?.trim();return{code:`runtime-error`,message:t&&t.length>0?t:`Agent run failed.`,details:{sessionId:e.sessionId,messageId:e.messageId,threadId:e.threadId,runId:e.runId}}}function fD(e,t){return t.trim()?e.id.startsWith(`tool-`)?!0:e.parts.some(e=>e.type===`tool-invocation`):!1}function pD(e,t,n){for(let[r,i]of e)i===t&&e.set(r,n)}function mD(e,t,n){for(let[r,i]of e)i===n&&(e.delete(r),t.delete(r))}function hD(e,t){for(let n=e.length-1;n>=0;--n){let r=e[n];if(r.type===`tool-invocation`&&r.toolCallId===t)return r}return null}function gD(e,t){return hD(e,t)?.toolName??null}function _D(e,t){let n=[...e];for(let e=n.length-1;e>=0;--e){let r=n[e];if(r.type===`tool-invocation`&&r.toolCallId===t.toolCallId)return n[e]={...r,...t},n}return n.push(t),n}function vD(e){let t=[];return{parts:e.map(e=>e.type!==`tool-invocation`||!e.toolCallId||e.state===`result`||e.state===`cancelled`?e:(t.push(e.toolCallId),{...e,state:`cancelled`})),toolCallIds:t}}var yD=`assistant`,bD=class{messages=[];streamingMessage=null;error=null;activeRun=null;contextWindow=null;listeners=new Set;toolCallMessageIdByCallId=new Map;toolCallArgsRawByCallId=new Map;lastSettledRunId=null;snapshotCache=null;snapshotVersion=-1;stateVersion=0;getSnapshot=()=>{if(this.snapshotCache&&this.snapshotVersion===this.stateVersion)return this.snapshotCache;let e={messages:this.messages,streamingMessage:this.streamingMessage,error:this.error?{...this.error,details:this.error.details?{...this.error.details}:void 0}:null,activeRun:this.activeRun?{...this.activeRun}:null,contextWindow:this.contextWindow?{...this.contextWindow}:null};return this.snapshotCache=e,this.snapshotVersion=this.stateVersion,e};subscribe=e=>(this.listeners.add(e),()=>this.listeners.delete(e));reset=()=>{this.messages.length===0&&!this.streamingMessage&&!this.error&&!this.activeRun&&!this.contextWindow&&this.toolCallMessageIdByCallId.size===0&&this.toolCallArgsRawByCallId.size===0||(this.messages=[],this.streamingMessage=null,this.error=null,this.activeRun=null,this.contextWindow=null,this.toolCallMessageIdByCallId.clear(),this.toolCallArgsRawByCallId.clear(),this.lastSettledRunId=null,this.stateVersion+=1,this.notifyListeners())};hydrate=e=>{this.messages=e.messages.map(e=>lD(e)),this.streamingMessage=null,this.error=null,this.contextWindow=e.contextWindow?{...e.contextWindow}:null,this.activeRun=e.activeRun?{...e.activeRun,sessionId:e.activeRun.sessionId??e.sessionId,abortDisabledReason:e.activeRun.abortDisabledReason??null}:null,this.toolCallMessageIdByCallId.clear(),this.toolCallArgsRawByCallId.clear(),this.lastSettledRunId=null,this.stateVersion+=1,this.notifyListeners()};dispatch=e=>this.dispatchBatch([e]);dispatchBatch=async e=>{if(!e.length)return;let t=this.stateVersion;e.forEach(this.applyEvent),this.stateVersion!==t&&this.notifyListeners()};applyEvent=e=>{switch(e.type){case nD.MessageSent:this.handleMessageSent(e.payload);break;case nD.MessageAbort:this.handleMessageAbort(e.payload);break;case nD.MessageTextStart:this.handleMessageTextStart(e.payload);break;case nD.MessageTextDelta:this.handleMessageTextDelta(e.payload);break;case nD.MessageTextEnd:this.handleMessageTextEnd(e.payload);break;case nD.MessageReasoningStart:this.handleMessageReasoningStart(e.payload);break;case nD.MessageReasoningDelta:this.handleMessageReasoningDelta(e.payload);break;case nD.MessageReasoningEnd:this.handleMessageReasoningEnd(e.payload);break;case nD.MessageToolCallStart:this.handleMessageToolCallStart(e.payload);break;case nD.MessageToolCallArgs:this.handleMessageToolCallArgs(e.payload);break;case nD.MessageToolCallArgsDelta:this.handleMessageToolCallArgsDelta(e.payload);break;case nD.MessageToolCallEnd:this.handleMessageToolCallEnd(e.payload);break;case nD.MessageToolCallResult:this.handleMessageToolCallResult(e.payload);break;case nD.RunStarted:this.handleRunStarted(e.payload);break;case nD.RunFinished:this.handleRunFinished(e.payload);break;case nD.RunError:this.handleRunError(e.payload);break;case nD.RunMetadata:this.handleRunMetadata(e.payload);break;case nD.ContextWindowUpdated:this.handleContextWindowUpdated(e.payload);break;case nD.EndpointError:this.handleEndpointError(e.payload);break;default:break}};handleMessageSent=e=>{this.upsertMessage(e.message),this.setError(null)};handleMessageAbort=e=>{let t=e.messageId?.trim();if(this.clearActiveRun(),this.setError(null),this.streamingMessage&&(!t||this.streamingMessage.id===t)){let e=this.streamingMessage.id,{parts:n,toolCallIds:r}=vD(this.streamingMessage.parts);this.upsertMessage({...this.streamingMessage,status:`final`,parts:n}),this.replaceStreamingMessage(null),t?mD(this.toolCallMessageIdByCallId,this.toolCallArgsRawByCallId,t):mD(this.toolCallMessageIdByCallId,this.toolCallArgsRawByCallId,e),r.forEach(e=>this.toolCallArgsRawByCallId.set(e,uD))}};handleMessageTextStart=e=>{this.ensureStreamingMessage(e.sessionId,e.messageId,`streaming`),this.setError(null)};handleMessageTextDelta=e=>{if(!e.delta)return;let t=this.ensureStreamingMessage(e.sessionId,e.messageId,`streaming`),n=[...t.parts],r=n[n.length-1];r?.type===`text`?n[n.length-1]={type:`text`,text:`${r.text}${e.delta}`}:n.push({type:`text`,text:e.delta}),this.replaceStreamingMessage({...t,parts:n,status:`streaming`})};handleMessageTextEnd=e=>{this.streamingMessage?.id===e.messageId&&this.streamingMessage.status===`streaming`&&this.replaceStreamingMessage({...this.streamingMessage,status:`pending`})};handleMessageReasoningStart=e=>{this.ensureStreamingMessage(e.sessionId,e.messageId,`streaming`)};handleMessageReasoningDelta=e=>{if(!e.delta)return;let t=this.ensureStreamingMessage(e.sessionId,e.messageId,`streaming`),n=[...t.parts],r=n[n.length-1];r?.type===`reasoning`?n[n.length-1]={type:`reasoning`,text:`${r.text}${e.delta}`}:n.push({type:`reasoning`,text:e.delta}),this.replaceStreamingMessage({...t,parts:n,status:`streaming`})};handleMessageReasoningEnd=e=>{this.streamingMessage?.id,e.messageId};handleMessageToolCallStart=e=>{if(this.toolCallArgsRawByCallId.get(e.toolCallId)===`__nextclaw_aborted_tool_call__`)return;let t=this.resolveToolCallTargetMessage(e.sessionId,e.toolCallId,e.messageId);this.toolCallArgsRawByCallId.set(e.toolCallId,``);let n=_D(t.parts,{type:`tool-invocation`,toolCallId:e.toolCallId,toolName:e.toolName,state:`partial-call`,args:``});this.replaceStreamingMessage({...t,parts:n,status:`streaming`}),this.setError(null)};handleMessageToolCallArgs=e=>{this.toolCallArgsRawByCallId.get(e.toolCallId)!==`__nextclaw_aborted_tool_call__`&&(this.toolCallArgsRawByCallId.set(e.toolCallId,e.args),this.applyToolCallArgs(e.sessionId,e.toolCallId,e.args))};handleMessageToolCallArgsDelta=e=>{if(this.toolCallArgsRawByCallId.get(e.toolCallId)===`__nextclaw_aborted_tool_call__`)return;let t=`${this.toolCallArgsRawByCallId.get(e.toolCallId)??``}${e.delta}`;this.toolCallArgsRawByCallId.set(e.toolCallId,t),this.applyToolCallArgs(e.sessionId,e.toolCallId,t,e.messageId)};handleMessageToolCallEnd=e=>{if(this.toolCallArgsRawByCallId.get(e.toolCallId)===`__nextclaw_aborted_tool_call__`)return;let t=this.resolveToolCallTargetMessage(e.sessionId,e.toolCallId),n=this.toolCallArgsRawByCallId.get(e.toolCallId)??``,r=_D(t.parts,{type:`tool-invocation`,toolCallId:e.toolCallId,toolName:gD(t.parts,e.toolCallId)??`unknown`,state:`call`,args:n});this.replaceStreamingMessage({...t,parts:r,status:`streaming`})};handleMessageToolCallResult=e=>{if(this.toolCallArgsRawByCallId.get(e.toolCallId)!==`__nextclaw_aborted_tool_call__`&&!this.updateMessageContainingToolCall(e.toolCallId,(t,n)=>{let r={type:`tool-invocation`,toolCallId:e.toolCallId,toolName:n.toolName,state:`result`,args:n.args,result:e.content,resultContentItems:e.contentItems};return _D(t.parts,r)})){let t=this.resolveToolCallTargetMessage(e.sessionId,e.toolCallId),n=_D(t.parts,{type:`tool-invocation`,toolCallId:e.toolCallId,toolName:`unknown`,state:`result`,result:e.content,resultContentItems:e.contentItems});this.replaceStreamingMessage({...t,parts:n,status:`streaming`})}};handleRunStarted=e=>{this.isSettledRunId(e.runId)||(this.setError(null),this.activeRun={runId:e.runId??null,sessionId:e.sessionId},this.stateVersion+=1)};handleRunFinished=e=>{this.markRunAsSettled(e.runId??this.activeRun?.runId??null),this.settleStreamingMessage(`final`),this.setError(null),this.clearActiveRun()};handleRunError=e=>{this.markRunAsSettled(e.runId??this.activeRun?.runId??null),this.settleStreamingMessage(`error`),this.setError(dD(e)),this.clearActiveRun()};handleRunMetadata=e=>{let t=e.metadata;if(t?.kind===`ready`){let e=t;if(this.isSettledRunId(e.runId))return;this.activeRun={runId:e.runId??this.activeRun?.runId??null,sessionId:e.sessionId??this.activeRun?.sessionId,abortDisabledReason:e.supportsAbort===!1?e.abortDisabledReason??`Unsupported`:null},this.stateVersion+=1}else t?.kind===`final`&&(this.markRunAsSettled(e.runId??this.activeRun?.runId??null),this.clearActiveRun())};handleContextWindowUpdated=e=>{this.contextWindow={...e.contextWindow},this.stateVersion+=1};handleEndpointError=e=>{if(e.code===`abort-error`){this.handleMessageAbort({sessionId:this.activeRun?.sessionId??this.streamingMessage?.sessionId??``,...this.streamingMessage?.id?{messageId:this.streamingMessage.id}:{}});return}this.settleStreamingMessage(`error`),this.clearActiveRun(),this.setError(e)};applyToolCallArgs=(e,t,n,r)=>{let i=this.resolveToolCallTargetMessage(e,t,r),a=gD(i.parts,t)??`unknown`,o=_D(i.parts,{type:`tool-invocation`,toolCallId:t,toolName:a,state:`partial-call`,args:n});this.replaceStreamingMessage({...i,parts:o,status:`streaming`})};ensureStreamingMessage=(e,t,n)=>{if(this.streamingMessage?.id===t){if(this.streamingMessage.status===n)return this.streamingMessage;let e={...this.streamingMessage,status:n};return this.replaceStreamingMessage(e),e}let r=this.messages.findIndex(e=>e.id===t);if(r>=0){let t=cD(this.messages[r]),i=[...this.messages];i.splice(r,1),this.messages=i,this.stateVersion+=1;let a={...t,sessionId:e,status:n};return this.replaceStreamingMessage(a),a}let i=this.streamingMessage;if(i&&i.id!==t&&i.sessionId===e&&fD(i,t)){let r={...i,id:t,sessionId:e,status:n};return pD(this.toolCallMessageIdByCallId,i.id,t),this.replaceStreamingMessage(r),r}let a={id:t,sessionId:e,role:yD,status:n,parts:[],timestamp:new Date().toISOString()};return this.replaceStreamingMessage(a),a};resolveToolCallTargetMessage=(e,t,n)=>{let r=n?.trim()||this.toolCallMessageIdByCallId.get(t)||this.streamingMessage?.id||`tool-${t}`;return this.toolCallMessageIdByCallId.set(t,r),this.ensureStreamingMessage(e,r,`streaming`)};updateMessageContainingToolCall=(e,t)=>{if(this.streamingMessage){let n=hD(this.streamingMessage.parts,e);if(n){let e=t(this.streamingMessage,n);return this.replaceStreamingMessage({...this.streamingMessage,parts:e}),!0}}for(let n=this.messages.length-1;n>=0;--n){let r=this.messages[n],i=hD(r.parts,e);if(!i)continue;let a=[...this.messages];return a[n]={...r,parts:t(r,i)},this.messages=a,this.stateVersion+=1,!0}return!1};upsertMessage=e=>{let t=lD(e),n=this.messages.findIndex(e=>e.id===t.id);if(n<0){this.messages=[...this.messages,t],this.stateVersion+=1;return}let r=[...this.messages];r[n]=t,this.messages=r,this.stateVersion+=1};replaceStreamingMessage=e=>{!e&&!this.streamingMessage||(this.streamingMessage=e?lD(e):null,this.stateVersion+=1)};setError=e=>{this.error?.code===e?.code&&this.error?.message===e?.message&&this.error?.details===e?.details&&this.error?.cause===e?.cause||(this.error=e?{...e,details:e.details?{...e.details}:void 0}:null,this.stateVersion+=1)};clearActiveRun=()=>{this.activeRun&&(this.activeRun=null,this.stateVersion+=1)};isSettledRunId=e=>!!e?.trim()&&e===this.lastSettledRunId;markRunAsSettled=e=>{this.lastSettledRunId=e?.trim()||null};settleStreamingMessage=e=>{if(!this.streamingMessage)return;let t={...this.streamingMessage,status:e};this.upsertMessage(t),this.replaceStreamingMessage(null),mD(this.toolCallMessageIdByCallId,this.toolCallArgsRawByCallId,t.id)};notifyListeners=()=>{let e=this.getSnapshot();for(let t of this.listeners)t(e)}},xD=16,SD=class{constructor(e){this.dispatchBatch=e,this.queue=[],this.flushTimerId=null,this.isFlushing=!1,this.isDisposed=!1,this.enqueue=e=>{this.isDisposed||(this.queue.push(e),this.scheduleFlush())},this.dispose=()=>{this.isDisposed=!0,this.flushTimerId!==null&&(window.clearTimeout(this.flushTimerId),this.flushTimerId=null),this.queue.length=0},this.scheduleFlush=()=>{this.flushTimerId!==null||this.isFlushing||this.queue.length===0||(this.flushTimerId=window.setTimeout(()=>{this.flushTimerId=null,this.flush()},xD))},this.flush=async()=>{if(!(this.isDisposed||this.isFlushing||this.queue.length===0)){this.isFlushing=!0;try{for(;this.queue.length>0;){let e=this.queue.splice(0);await this.dispatchBatch(e)}}finally{this.isFlushing=!1,this.scheduleFlush()}}}}};function CD(e,t){let n=e.dispatchBatch;return typeof n==`function`?n.call(e,t):t.reduce((t,n)=>t.then(()=>e.dispatch(n)),Promise.resolve())}function wD(e,t){let n=`payload`in e?e.payload:null;return!n||typeof n!=`object`||!(`sessionId`in n)||typeof n.sessionId!=`string`?!0:n.sessionId===t}function TD(e){return e.parts.some(e=>e.type===`text`||e.type===`rich-text`||e.type===`reasoning`?e.text.trim().length>0:!0)}function ED(e,t){if(typeof e==`string`){let n=e.trim();return n?{sessionId:t,message:{id:`user-${Date.now().toString(36)}`,sessionId:t,role:`user`,status:`final`,parts:[{type:`text`,text:n}],timestamp:new Date().toISOString()}}:null}return TD(e.message)?{...e,sessionId:e.sessionId,message:{...e.message,sessionId:e.message.sessionId||e.sessionId}}:null}function DD(e){let t=(0,P.useRef)();return(!t.current||t.current.sessionId!==e)&&(t.current={sessionId:e,manager:new bD}),t.current.manager}function OD({sessionId:e,client:t,manager:n}){let r=(0,P.useSyncExternalStore)(e=>n.subscribe(()=>e()),()=>n.getSnapshot(),()=>n.getSnapshot()),[i,a]=(0,P.useState)(!1);(0,P.useEffect)(()=>{a(!1)},[e]),(0,P.useEffect)(()=>{let r=new SD(e=>CD(n,e)),i=t.subscribe(t=>{wD(t,e)&&r.enqueue(t)});return()=>{i(),r.dispose(),t.stop()}},[t,n,e]);let o=r.streamingMessage?[...r.messages,r.streamingMessage]:r.messages,s=r.activeRun?.runId??null,c=!!r.activeRun;return{snapshot:r,visibleMessages:o,activeRunId:s,isRunning:c,isSending:i,send:async r=>{if(i||c)return;let o=ED(r,e);if(o){a(!0),await n.dispatch({type:nD.MessageSent,payload:{sessionId:e,message:o.message,metadata:o.metadata}});try{await t.send(o)}finally{a(!1)}}},abort:async()=>{r.activeRun&&await t.abort({sessionId:e})},streamRun:async()=>{await t.stop(),await t.stream({sessionId:e})}}}function kD(e){return e instanceof Error?e:Error(String(e))}function AD(e){return e.isHydrating||e.hydratedSessionId!==e.sessionId}function jD({sessionId:e,client:t,loadSeed:n}){let r=DD(e),i=OD({sessionId:e,client:t,manager:r}),[a,o]=(0,P.useState)(!0),[s,c]=(0,P.useState)(null),[l,u]=(0,P.useState)(null),d=(0,P.useRef)({requestId:0,controller:null}),f=(0,P.useCallback)(async()=>{d.current.controller?.abort();let i=new AbortController,a=d.current.requestId+1;d.current={requestId:a,controller:i},await t.stop(),r.reset(),c(null),o(!0);try{let s=await n(e,i.signal);if(i.signal.aborted||d.current.requestId!==a)return;r.hydrate({sessionId:e,messages:s.messages,activeRun:s.status===`running`?{runId:null,sessionId:e,abortDisabledReason:null}:null}),c(null),u(e),o(!1),t.stream({sessionId:e}).catch(e=>{d.current.requestId===a&&c(kD(e))})}catch(t){if(i.signal.aborted||d.current.requestId!==a)return;c(kD(t)),u(e),o(!1)}finally{d.current.controller===i&&(d.current.controller=null)}},[t,n,r,e]);return(0,P.useEffect)(()=>(f(),()=>{d.current.controller?.abort(),d.current.controller=null}),[f]),{...i,isHydrating:AD({sessionId:e,hydratedSessionId:l,isHydrating:a}),hydrateError:s}}var MD=200*1024*1024,ND=`application/octet-stream`;function PD(e){let t=e.type.trim().toLowerCase();return t.length>0?t:ND}function FD(e,t){let n=t.acceptedMimeTypes&&t.acceptedMimeTypes.length>0?new Set(t.acceptedMimeTypes.map(e=>e.trim().toLowerCase())):null,r=t.maxBytes??209715200,i=PD(e);return n&&!n.has(i)?{ok:!1,rejected:{fileName:e.name,mimeType:i,sizeBytes:e.size,reason:`unsupported-type`}}:e.size>r?{ok:!1,rejected:{fileName:e.name,mimeType:i,sizeBytes:e.size,reason:`too-large`}}:{ok:!0,mimeType:i}}function ID(e){let t=e.parts&&e.parts.length>0?e.parts.map(e=>structuredClone(e)):[...e.text?.trim()??``?[{type:`text`,text:e.text.trim()}]:[],...(e.attachments??[]).map(e=>({type:`file`,name:e.name,mimeType:e.mimeType,...e.assetUri?.trim()?{assetUri:e.assetUri.trim()}:{},...e.url?.trim()?{url:e.url.trim()}:{},...e.contentBase64?.trim()?{contentBase64:e.contentBase64.trim()}:{},sizeBytes:e.sizeBytes}))];if(t.length===0)return null;let n=e.timestamp??new Date().toISOString(),r=e.messageId??`user-${Date.now().toString(36)}`;return{sessionId:e.sessionId,message:{id:r,sessionId:e.sessionId,role:`user`,status:`final`,parts:t,timestamp:n,...e.metadata?{metadata:e.metadata}:{}},...e.metadata?{metadata:e.metadata}:{}}}async function LD(e,t){let n=[],r=[];for(let i of e){let e=FD(i,t);if(!e.ok){r.push(e.rejected);continue}n.push(i)}if(n.length===0)return{attachments:[],rejected:r};try{return{attachments:await t.uploadBatch(n),rejected:r}}catch{return r.push(...n.map(e=>({fileName:e.name,mimeType:PD(e),sizeBytes:e.size,reason:`read-failed`}))),{attachments:[],rejected:r}}}function RD(e){let t=e.modelLabel.trim(),n=e.providerLabel.trim();return n?`${n}/${t}`:t}function zD(e){let t=[];for(let n of[`off`,...e])t.includes(n)||t.push(n);return t}function BD(e){return!e.isModelOptionsLoading&&!e.isModelOptionsEmpty?null:e.isModelOptionsLoading?{tone:`neutral`,loading:!0}:{tone:`warning`,text:e.texts.noModelOptionsLabel,actionLabel:e.texts.configureProviderLabel,onAction:e.onGoToProviders}}function VD({modelOptions:e,recentModelValues:t,selectedModel:n,isModelOptionsLoading:r,hasModelOptions:i,onValueChange:a,texts:o}){let s=e.find(e=>e.value===n)??e[0],c=i?s?.value:void 0,l=new Set(t??[]),u=new Map(e.map(e=>[e.value,e])),d=(t??[]).map(e=>u.get(e)).filter(e=>!!e),f=e.filter(e=>!l.has(e.value)),p=d.length>0?[{key:`recent-models`,label:o.recentModelsLabel,options:d.map(e=>({value:e.value,label:RD(e)}))},{key:`all-models`,label:o.allModelsLabel,options:f.map(e=>({value:e.value,label:RD(e)}))}].filter(e=>e.options.length>0):void 0;return{key:`model`,value:c,placeholder:o.modelSelectPlaceholder,selectedLabel:s?RD(s):void 0,icon:`sparkles`,options:e.map(e=>({value:e.value,label:RD(e)})),groups:p,disabled:!i,loading:r,emptyLabel:o.modelNoOptionsLabel,onValueChange:a}}function HD(e){if(e.supportedLevels.length===0)return null;let t=zD(e.supportedLevels),n=t.includes(`off`)?`off`:t[0],r=e.selectedThinkingLevel&&t.includes(e.selectedThinkingLevel)&&e.selectedThinkingLevel||e.defaultThinkingLevel&&t.includes(e.defaultThinkingLevel)&&e.defaultThinkingLevel||n;return{key:`thinking`,value:r,placeholder:e.texts.thinkingLabels[r],selectedLabel:e.texts.thinkingLabels[r],icon:`brain`,options:t.map(t=>({value:t,label:e.texts.thinkingLabels[t]})),onValueChange:t=>e.onValueChange(t)}}var UD={exactSpec:1200,exactLabel:1150,prefixSpec:1e3,prefixLabel:950,prefixToken:900,containsSpec:800,containsLabel:760,containsDescription:500,subsequence:300,fallback:1};function WD(e){return(e??``).trim().toLowerCase()}function GD(e,t){if(!e||!t)return!1;let n=0;for(let r of t)if(r===e[n]&&(n+=1,n>=e.length))return!0;return!1}function KD(e,t){let n=WD(t);if(!n)return UD.fallback;let r=WD(e.key),i=WD(e.label||e.key),a=WD(`${e.descriptionZh??``} ${e.description??``}`),o=i.split(/[\s/_-]+/).filter(Boolean);return r===n?UD.exactSpec:i===n?UD.exactLabel:r.startsWith(n)?UD.prefixSpec:i.startsWith(n)?UD.prefixLabel:o.some(e=>e.startsWith(n))?UD.prefixToken:r.includes(n)?UD.containsSpec:i.includes(n)?UD.containsLabel:a.includes(n)?UD.containsDescription:GD(n,i)||GD(n,r)?UD.subsequence:0}function qD(e){return e>=UD.exactLabel?4:e>=UD.prefixToken?3:e>=UD.containsLabel?2:e>0?1:0}function JD(e){return new Map(e.map((e,t)=>[e,t]))}function YD(e,t){let n=JD(t),r=[],i=[];for(let t of e){if(n.has(t.key)){r.push(t);continue}i.push(t)}return r.sort((e,t)=>(n.get(e.key)??1/0)-(n.get(t.key)??1/0)),[...r,...i]}function XD(e,t,n,r=[]){let i=new Intl.Collator(void 0,{sensitivity:`base`,numeric:!0}),a=JD(r);return e.map((e,n)=>({record:e,order:n,score:KD(e,t)})).filter(e=>e.score>0).sort((e,t)=>{let n=qD(e.score),r=qD(t.score);if(r!==n)return r-n;let o=a.get(e.record.key)??1/0,s=a.get(t.record.key)??1/0;if(o!==s)return o-s;if(t.score!==e.score)return t.score-e.score;let c=(e.record.label||e.record.key).trim(),l=(t.record.label||t.record.key).trim(),u=i.compare(c,l);return u===0?e.order-t.order:u}).map(({record:e})=>({key:`skill:${e.key}`,title:e.label||e.key,subtitle:n.slashSkillSubtitle,description:(e.descriptionZh??e.description??``).trim()||n.noSkillDescription,detailLines:[`${n.slashSkillSpecLabel}: ${e.key}`,...e.scopeLabel?[`${n.slashSkillScopeLabel}: ${e.scopeLabel}`]:[]],value:e.key}))}function ZD(e){return e.map(e=>({key:e.key,label:e.label,description:e.descriptionZh||e.description||``,badgeLabel:e.badgeLabel}))}function QD(e){let t=YD(e.skillRecords,e.recentSkillValues??[]),n=new Set(e.groupedRecentSkillValues??[]),r=ZD(t.filter(e=>n.has(e.key))),i=ZD(t.filter(e=>!n.has(e.key)));return{title:e.texts.title,searchPlaceholder:e.texts.searchPlaceholder,emptyLabel:e.texts.emptyLabel,loadingLabel:e.texts.loadingLabel,isLoading:e.isLoading,manageLabel:e.texts.manageLabel,manageHref:`/marketplace/skills`,options:ZD(t),groups:r.length>0?[{key:`recent-skills`,label:e.texts.recentSkillsLabel,options:r},{key:`all-skills`,label:e.texts.allSkillsLabel,options:i}].filter(e=>e.options.length>0):void 0,selectedKeys:e.selectedSkills,onSelectedKeysChange:e.onSelectedKeysChange}}var $D=`$`;function eO(e,t){if(t.length===0)return e;let n=e[e.length-1];return n?.type===`text`?[...e.slice(0,-1),{...n,text:n.text+t}]:[...e,{type:`text`,text:t}]}function tO(){return wp()}function nO(e){return Tp(e)}function rO(e){return Op(e)}function iO(e){return kp(e,`skill`)}function aO(e){return kp(e,`file`)}function oO(e,t,n){let r=new Set(t),i=Ip(e,e=>e.tokenKind===`skill`&&!r.has(e.tokenKey)),a=kp(i,`skill`),o=new Map(n.map(e=>[e.ref,e])),s=t.filter(e=>!a.includes(e)).map(e=>Sp({tokenKind:`skill`,tokenKey:e,label:o.get(e)?.name||e}));return s.length===0?i:Ep([...i,...s])}function sO(e,t){let n=new Set(t.map(e=>e.id));return Ip(e,e=>e.tokenKind===`file`&&!n.has(e.tokenKey))}function cO(e,t){let n=new Set(aO(e));return t.filter(e=>n.has(e.id))}function lO(e,t){let n=new Map(t.map(e=>[e.id,e])),r=[];for(let t of e){if(t.type===`text`){r=eO(r,t.text);continue}if(t.tokenKind===`skill`){r=eO(r,`${$D}${t.tokenKey}`);continue}if(t.tokenKind!==`file`)continue;let e=n.get(t.tokenKey);e&&r.push({type:`file`,name:e.name,mimeType:e.mimeType,...e.assetUri?{assetUri:e.assetUri}:{},...e.url?{url:e.url}:{},...e.contentBase64?{contentBase64:e.contentBase64}:{},sizeBytes:e.sizeBytes})}return r}var uO={isProviderStateResolved:!1,composerNodes:tO(),attachments:[],draft:``,pendingSessionType:`native`,pendingProjectRoot:null,pendingProjectRootSessionKey:null,defaultSessionType:`native`,canStopGeneration:!1,stopDisabledReason:null,sendError:null,isSending:!1,modelOptions:[],selectedModel:``,selectedThinkingLevel:null,sessionTypeOptions:[],selectedSessionType:void 0,stopSupported:!1,stopReason:void 0,canEditSessionType:!1,sessionTypeUnavailable:!1,skillRecords:[],isSkillsLoading:!1,selectedSkills:[]},Q=w(e=>({snapshot:uO,setSnapshot:t=>e(e=>({snapshot:{...e.snapshot,...t}}))})),dO=class{constructor(e){this.options=e,this.read=()=>{let e=this.getStorage();if(!e)return[];try{return this.normalizeList(JSON.parse(e.getItem(this.options.storageKey)??`[]`))}catch{return[]}},this.remember=e=>{let t=this.normalizeValue(e);if(!t)return this.read();let n=[t,...this.read().filter(e=>e!==t)].slice(0,this.options.limit);return this.write(n),n},this.resolveVisible=e=>{let t=this.normalizeList(e.availableValues,1/0);if(t.length<=e.minAvailableCount)return[];let n=new Set(t),r=[],i=Math.max(1,e.limit??this.options.limit);for(let e of this.read())if(!(!n.has(e)||r.includes(e))&&(r.push(e),r.length>=i))break;return r},this.write=e=>{let t=this.getStorage();if(t)try{t.setItem(this.options.storageKey,JSON.stringify(this.normalizeList(e)))}catch{}},this.getStorage=()=>Object.prototype.hasOwnProperty.call(this.options,`storage`)?this.options.storage??null:typeof window>`u`?null:window.localStorage,this.normalizeList=(e,t=this.options.limit)=>{if(!Array.isArray(e))return[];let n=[];for(let r of e){let e=this.normalizeValue(r);if(!(!e||n.includes(e))&&(n.push(e),n.length>=t))break}return n},this.normalizeValue=e=>{if(typeof e!=`string`)return null;let t=e.trim();return t.length>0?t:null}}},fO=new dO({storageKey:`nextclaw.chat.recent-models`,limit:3}),pO=new dO({storageKey:`nextclaw.chat.recent-skills`,limit:5});function mO(e){return e.modelOptions.length>0}function hO(e){return!e.isProviderStateResolved&&!mO(e)}function gO(e){return e.isProviderStateResolved&&!mO(e)}function _O(e){return!1}function vO(e){let{hasSendableDraft:t,isRuntimeBlocked:n}=e;return n||!t}var yO=function(e){return e.CALL=`call`,e.RESULT=`result`,e.PARTIAL_CALL=`partial-call`,e.ERROR=`error`,e.CANCELLED=`cancelled`,e}({});function bO(e){if(typeof e!=`string`)return null;let t=e.trim();return t.length>0?t:null}function xO(e){return bO(e)}function SO(e){let t=bO(e);if(!t)return null;let n=t.replace(/[\\/]+$/,``);if(!n)return t;let r=n.split(/[\\/]/).filter(Boolean);return r[r.length-1]??n}function CO(e){return/^[A-Za-z]:[\\/]?$/.test(e)||e===`/`?e:e.replace(/[\\/]+$/,``)}function wO(e){let t=CO(e.trim().replace(/\\/g,`/`));return/^[A-Za-z]:/.test(t)?`${t.slice(0,1).toLowerCase()}${t.slice(1)}`:t}function TO(e){let t=e.trim().replace(/\\/g,`/`);return t?/^[A-Za-z]:\//.test(t)?{prefix:t.slice(0,2),segments:t.slice(3).split(`/`).filter(Boolean)}:t.startsWith(`/`)?{prefix:`/`,segments:t.slice(1).split(`/`).filter(Boolean)}:{prefix:null,segments:t.split(`/`).filter(Boolean)}:{prefix:null,segments:[]}}function EO(e){let t=wO(e.path),n=wO(e.sessionProjectRoot);if(!t||!n)return null;if(!t.startsWith(`/`)&&!/^[A-Za-z]:\//.test(t))return t.split(`/`).filter(Boolean);if(t===n)return[];let r=n.endsWith(`/`)?n:`${n}/`;return t.startsWith(r)?t.slice(r.length).split(`/`).filter(Boolean):null}function DO(e){let{labels:t,leading:n=null}=e,r=t.map((e,n)=>({key:`${n}:${e}`,label:e,kind:n===t.length-1?`file`:`directory`,isCurrent:n===t.length-1}));return n?[n,...r]:r}function OO(e){let{column:t,line:n}=e;return typeof n==`number`?`L${n}${typeof t==`number`?`:${t}`:``}`:null}function kO(e){let{column:t,line:n,path:r,sessionProjectRoot:i,truncated:a}=e,o=r.trim(),s=i?.trim()&&o?EO({path:o,sessionProjectRoot:i}):null,c;if(i?.trim()&&s){let e=SO(i)??i.trim();c=DO({labels:s,leading:{key:`workspace:${e}`,label:e,kind:`workspace`,isCurrent:s.length===0}})}else{let{prefix:e,segments:t}=TO(o);c=DO({labels:t,leading:e?{key:`root:${e}`,label:e,kind:`root`,isCurrent:t.length===0}:null})}return c.length===0&&(c=[{key:`file:unknown`,label:o||`file`,kind:`file`,isCurrent:!0}]),{fullPath:o,locationLabel:OO({line:n,column:t}),truncated:a,segments:c}}var AO=new Set([`off`,`minimal`,`low`,`medium`,`high`,`adaptive`,`xhigh`]);function jO(e){if(typeof e==`string`)return e;try{return JSON.stringify(e??{})}catch{return String(e??``)}}function MO(e){return`${ae}/api/ncp/assets/content?${new URLSearchParams({uri:e}).toString()}`}function NO(e){if(typeof e!=`string`)return null;let t=e.trim();return t.length>0?t:null}function PO(e){let{metadata:t}=e;return!t||typeof t!=`object`||Array.isArray(t)?null:t}function FO(e){let t=PO(e);return t?NO(t.preferred_model)??NO(t.preferredModel)??NO(t.model):null}function IO(e){let t=PO(e);if(!t)return null;let n=NO(t.preferred_thinking)??NO(t.thinking)??NO(t.thinking_level)??NO(t.thinkingLevel);if(!n)return null;let r=n.toLowerCase();return AO.has(r)?r:null}function LO(e){let t=PO(e);return t?NO(t.label):null}function RO(e){let t=PO(e);return t?xO(t.project_root??t.projectRoot):null}function zO(e){let t=PO(e);return t?NO(t.ui_last_read_at):null}function BO(e){let t=PO(e);return t?NO(t.runtime)??NO(t.session_type)??NO(t.sessionType)??`native`:`native`}function VO(e){let t=PO(e);return t?NO(t.parent_session_id)??NO(t.parentSessionId):null}function HO(e){let t=PO(e);return t?NO(t.spawned_by_request_id)??NO(t.spawnedByRequestId):null}function UO(e){let t=PO(e);return t?t.child_session_promoted===!0:!1}function WO(e){if(e.startsWith(`cron:`))return{type:`cron`};if(e.startsWith(`agent:`)){let t=e.split(`:`);if(t.length>=3){let e=t[2];if(e&&e!==`main`&&e!==`direct`)return{channel:e}}}return{}}function GO(e){return e.state===`cancelled`?yO.CANCELLED:e.state===`result`?yO.RESULT:e.state===`partial-call`?yO.PARTIAL_CALL:yO.CALL}function KO(e){let t=[];for(let n of e){if(n.type===`text`){t.push({type:`text`,text:n.text});continue}if(n.type===`rich-text`){t.push({type:`text`,text:n.text});continue}if(n.type===`reasoning`){t.push({type:`reasoning`,reasoning:n.text,details:[]});continue}if(n.type===`source`){t.push({type:`source`,source:{sourceType:`url`,id:n.url??n.title??Math.random().toString(36).slice(2,8),url:n.url??``,...n.title?{title:n.title}:{}}});continue}if(n.type===`file`&&n.contentBase64){t.push({type:`file`,...n.name?{name:n.name}:{},mimeType:n.mimeType??`application/octet-stream`,data:n.contentBase64,...n.url?{url:n.url}:{},...typeof n.sizeBytes==`number`?{sizeBytes:n.sizeBytes}:{}});continue}if(n.type===`file`&&n.url){t.push({type:`file`,...n.name?{name:n.name}:{},mimeType:n.mimeType??`application/octet-stream`,data:``,url:n.url,...typeof n.sizeBytes==`number`?{sizeBytes:n.sizeBytes}:{}});continue}if(n.type===`file`&&n.assetUri){t.push({type:`file`,...n.name?{name:n.name}:{},mimeType:n.mimeType??`application/octet-stream`,data:``,url:MO(n.assetUri),...typeof n.sizeBytes==`number`?{sizeBytes:n.sizeBytes}:{}});continue}if(n.type===`step-start`){t.push({type:`step-start`});continue}n.type===`tool-invocation`&&t.push({type:`tool-invocation`,toolInvocation:{status:GO(n),toolCallId:n.toolCallId??`${n.toolName}-${Math.random().toString(36).slice(2,8)}`,toolName:n.toolName,args:jO(n.args),result:n.result}})}return t}function qO(e){return e===`service`?`system`:e===`tool`?`assistant`:e}function JO(e){return{id:e.id,role:qO(e.role),parts:KO(e.parts),meta:{source:`stream`,status:e.status,sessionKey:e.sessionId,timestamp:e.timestamp}}}function YO(e){let t=LO(e),n=FO(e),r=IO(e),i=RO(e),a=zO(e),o=NO(e.lastMessageAt),s=SO(i),c=WO(e.sessionId),l=VO(e),u=HO(e),d=UO(e);return{key:e.sessionId,createdAt:e.updatedAt,updatedAt:e.updatedAt,...o?{lastMessageAt:o}:{},...a?{readAt:a}:{},...typeof e.agentId==`string`&&e.agentId.trim().length>0?{agentId:e.agentId.trim()}:{},...t?{label:t}:{},...c,...n?{preferredModel:n}:{},...r?{preferredThinking:r}:{},...i?{projectRoot:i}:{},...s?{projectName:s}:{},sessionType:BO(e),sessionTypeMutable:!1,isChildSession:!!l,...d?{isPromotedChildSession:d}:{},...l?{parentSessionId:l}:{},...u?{spawnedByRequestId:u}:{},messageCount:e.messageCount}}function XO(e){return e.map(YO)}function ZO(){return`ncp-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,10)}`}function QO(e,t){let n=e?.trim();if(!n)return!1;let r=t?.trim();return r?n.localeCompare(r)>0:!1}function $O(e){let{active:t,readAt:n,runStatus:r,lastMessageAt:i}=e;return t||r===`running`?!1:QO(i,n)}var ek={selectedSessionKey:null,draftSessionKey:ZO(),selectedAgentId:`main`,query:``,listMode:`time-first`};function tk(e){return t=>e(e=>({snapshot:{...e.snapshot,...t}}))}function nk(e){return(t,n)=>e(e=>{let r=t.trim(),i=n?.trim();if(!r||!i)return e;let a=e.optimisticReadAtBySessionKey[r];return a&&a.localeCompare(i)>=0?e:{...e,optimisticReadAtBySessionKey:{...e.optimisticReadAtBySessionKey,[r]:i}}})}var rk=w(e=>({snapshot:ek,optimisticReadAtBySessionKey:{},setSnapshot:tk(e),markSessionRead:nk(e)})),ik={isProviderStateResolved:!1,modelOptions:[],sessionTypeUnavailable:!1,sessionTypeUnavailableMessage:null,sessionTypeLabel:null,sessionTypeIcon:null,sessionKey:null,agentId:null,agentDisplayName:null,agentAvatarUrl:null,availableAgents:[],sessionDisplayName:void 0,sessionProjectRoot:null,sessionProjectName:null,canDeleteSession:!1,isDeletePending:!1,threadRef:null,isHistoryLoading:!1,messages:[],isSending:!1,isAwaitingAssistantOutput:!1,parentSessionKey:null,parentSessionLabel:null,workspacePanelParentKey:null,childSessionTabs:[],activeChildSessionKey:null,workspaceFileTabs:[],activeWorkspaceFileKey:null,contextWindow:null},ak=w(e=>({snapshot:ik,setSnapshot:t=>e(e=>({snapshot:{...e.snapshot,...t}}))}));function ok(e){return e>=1e6?`${(e/1e6).toFixed(e>=1e7?0:1)}M`:e>=1e3?`${(e/1e3).toFixed(e>=1e4?0:1)}k`:String(e)}function sk(e){if(!e||e.totalContextTokens<=0)return null;let t=e.usedContextTokens/e.totalContextTokens,n=Math.max(0,Math.min(1,t)),r=`${Math.round(n*100)}%`,i=n>=.9?`danger`:n>=.75?`warning`:`neutral`,a=[{label:o(`chatContextWindowUsed`),value:ok(e.usedContextTokens)},{label:o(`chatContextWindowTotal`),value:ok(e.totalContextTokens)},{label:o(`chatContextWindowAvailable`),value:ok(e.availableContextTokens)}];return e.prunedUsedContextTokens!==e.usedContextTokens&&a.push({label:o(`chatContextWindowPruned`),value:ok(e.prunedUsedContextTokens)}),e.droppedHistoryCount>0&&a.push({label:o(`chatContextWindowDroppedHistory`),value:String(e.droppedHistoryCount)}),e.truncatedToolResultCount>0&&a.push({label:o(`chatContextWindowTruncatedTools`),value:String(e.truncatedToolResultCount)}),{label:o(`chatContextWindow`),percentLabel:r,ratio:n,tone:i,details:a}}function ck(){let e=rk(e=>e.snapshot.selectedSessionKey),t=rk(e=>e.snapshot.draftSessionKey),n=ak(e=>e.snapshot.sessionKey),r=ak(e=>e.snapshot.contextWindow),i=e??t;return(0,P.useMemo)(()=>n===i&&r?sk(r):null,[i,r,n])}function lk(e){return e.bootstrapStatus?.ncpAgent.state!==`ready`}function uk(e){return e.activeSystemAction?.message?.trim()||(e.lifecyclePhase===`cold-starting`?o(`chatRuntimeInitializing`):e.lifecyclePhase===`startup-failed`?e.bootstrapStatus?.ncpAgent.error?.trim()||e.bootstrapStatus?.lastError?.trim()||e.lastError?.trim()||o(`chatRuntimeInitializationFailed`):null)}function dk(e){let{message:t,status:n}=e,r=t?.trim();if(!r)return uk(n);let i=n.activeSystemAction?.message?.trim();if(n.phase===`service-transitioning`&&i)return i;let a=j(r);return n.phase===`recovering`&&a?o(`runtimeControlRecoveringHelp`):n.phase===`stalled`&&a?null:r}function fk(){return{off:o(`chatThinkingLevelOff`),minimal:o(`chatThinkingLevelMinimal`),low:o(`chatThinkingLevelLow`),medium:o(`chatThinkingLevelMedium`),high:o(`chatThinkingLevelHigh`),adaptive:o(`chatThinkingLevelAdaptive`),xhigh:o(`chatThinkingLevelXhigh`)}}function pk(e,t){return e.map(e=>({key:e.ref,label:e.name,scopeLabel:t[e.scope],description:e.description,descriptionZh:e.descriptionZh,badgeLabel:t[e.scope]}))}function mk(e){return e.map(e=>({value:e.value,modelLabel:e.modelLabel,providerLabel:e.providerLabel,thinkingCapability:e.thinkingCapability?{supported:e.thinkingCapability.supported,default:e.thinkingCapability.default??null}:null}))}function hk(e){return{skillScopeLabels:(0,P.useMemo)(()=>({builtin:o(`chatSkillScopeBuiltin`),project:o(`chatSkillScopeProject`),workspace:o(`chatSkillScopeWorkspace`)}),[e]),slashTexts:(0,P.useMemo)(()=>({slashSkillSubtitle:o(`chatSlashTypeSkill`),slashSkillSpecLabel:o(`chatSlashSkillSpec`),slashSkillScopeLabel:o(`chatSlashSkillScope`),noSkillDescription:o(`chatSkillsPickerNoDescription`)}),[e]),recentModelsLabel:o(`chatPickerRecentModels`),allModelsLabel:o(`chatPickerAllModels`),recentSkillsLabel:o(`chatPickerRecent`),allSkillsLabel:o(`chatPickerAllSkills`)}}function gk(e,t){let n=(0,P.useMemo)(()=>pk(e.skillRecords,t),[e.skillRecords,t]),r=(0,P.useMemo)(()=>mk(e.modelOptions),[e.modelOptions]);return{skillRecords:n,modelRecords:r,recentModelValues:fO.resolveVisible({availableValues:r.map(e=>e.value),minAvailableCount:5}),recentSkillValues:pO.resolveVisible({availableValues:n.map(e=>e.key),minAvailableCount:0}),recentSkillGroupValues:pO.resolveVisible({availableValues:n.map(e=>e.key),minAvailableCount:4})}}function _k(e){let{attachmentSupported:t,inputBarRef:n,presenter:r}=e,i=(0,P.useCallback)(e=>{if(e===`unsupported-type`){p.error(o(`chatInputAttachmentUnsupported`));return}if(e===`too-large`){p.error(o(`chatInputAttachmentTooLarge`).replace(`{maxMb}`,String(MD/(1024*1024))));return}p.error(o(`chatInputAttachmentReadFailed`))},[]),a=(0,P.useCallback)(async e=>{if(!t||e.length===0)return;let a=await LD(e,{uploadBatch:oe});if(a.attachments.length>0){let e=r.chatInputManager.addAttachments?.(a.attachments)??[];e.length>0&&n.current?.insertFileTokens(e.map(e=>({tokenKey:e.id,label:e.name})))}a.rejected.length>0&&i(a.rejected[0].reason)},[t,n,r.chatInputManager,i]);return{handleFilesAdd:a,handleFileInputChange:(0,P.useCallback)(async e=>{let t=Array.from(e.target.files??[]);e.currentTarget.value=``,await a(t)},[a])}}function vk(e){let{allModelsLabel:t,hasModelOptions:n,isModelOptionsLoading:r,modelRecords:i,presenter:a,recentModelValues:s,recentModelsLabel:c,selectedModel:l,selectedThinkingLevel:u,thinkingSupportedLevels:d,thinkingDefaultLevel:f}=e;return[VD({modelOptions:i,recentModelValues:s,selectedModel:l,isModelOptionsLoading:r,hasModelOptions:n,onValueChange:a.chatInputManager.selectModel,texts:{modelSelectPlaceholder:o(`chatSelectModel`),modelNoOptionsLabel:o(`chatModelNoOptions`),recentModelsLabel:c,allModelsLabel:t}}),HD({supportedLevels:d,selectedThinkingLevel:u,defaultThinkingLevel:f,onValueChange:e=>a.chatInputManager.selectThinkingLevel(e),texts:{thinkingLabels:fk()}})].filter(e=>e!==null)}function yk(e){let{allSkillsLabel:t,presenter:n,recentSkillGroupValues:r,recentSkillValues:i,recentSkillsLabel:a,skillRecords:s,snapshot:c}=e;return QD({skillRecords:s,recentSkillValues:i,groupedRecentSkillValues:r,selectedSkills:c.selectedSkills,isLoading:c.isSkillsLoading,onSelectedKeysChange:n.chatInputManager.selectSkills,texts:{title:o(`chatSkillsPickerTitle`),searchPlaceholder:o(`chatSkillsPickerSearchPlaceholder`),emptyLabel:o(`chatSkillsPickerEmpty`),loadingLabel:o(`sessionsLoading`),manageLabel:o(`chatSkillsPickerManage`),recentSkillsLabel:a,allSkillsLabel:t}})}function bk(){let e=Bn(),{language:t}=ut(),{isMobile:n}=ft(),r=Q(e=>e.snapshot),i=lk(S()),[a,s]=(0,P.useState)(null),c=(0,P.useRef)(null),l=(0,P.useRef)(null),u=hk(t),{skillRecords:d,modelRecords:f,recentModelValues:p,recentSkillValues:m,recentSkillGroupValues:h}=gk(r,u.skillScopeLabels),g=mO(r),_=hO(r),v=gO(r),y=_O(r),b=typeof e.chatInputManager.addAttachments==`function`,x=o(v?`chatModelNoOptions`:n?`chatInputPlaceholderCompact`:`chatInputPlaceholder`),C=(0,P.useMemo)(()=>XD(d,a??``,u.slashTexts,m),[u.slashTexts,m,d,a]),w=ck(),T=f.find(e=>e.value===r.selectedModel),E=T?.thinkingCapability?.supported??[],D=r.stopDisabledReason===`__preparing__`?o(`chatStopPreparing`):r.stopDisabledReason?.trim()||o(`chatStopUnavailable`),{handleFilesAdd:O,handleFileInputChange:ee}=_k({attachmentSupported:b,inputBarRef:c,presenter:e}),k=vk({allModelsLabel:u.allModelsLabel,hasModelOptions:g,isModelOptionsLoading:_,modelRecords:f,presenter:e,recentModelValues:p,recentModelsLabel:u.recentModelsLabel,selectedModel:r.selectedModel,selectedThinkingLevel:r.selectedThinkingLevel,thinkingSupportedLevels:E,thinkingDefaultLevel:T?.thinkingCapability?.default??null}),te=yk({allSkillsLabel:u.allSkillsLabel,presenter:e,recentSkillGroupValues:h,recentSkillValues:m,recentSkillsLabel:u.recentSkillsLabel,skillRecords:d,snapshot:r}),A=r.draft.trim().length>0||r.attachments.length>0||iO(r.composerNodes).length>0;return(0,N.jsxs)(N.Fragment,{children:[(0,N.jsx)(gm,{ref:c,composer:{nodes:r.composerNodes,placeholder:x,disabled:y,onNodesChange:e.chatInputManager.setComposerNodes,...b?{onFilesAdd:O}:{},onSlashQueryChange:s},slashMenu:{isLoading:r.isSkillsLoading,items:C,onSelectItem:t=>{t.value&&e.chatInputManager.rememberSkillSelection(t.value)},texts:{slashLoadingLabel:o(`chatSlashLoading`),slashSectionLabel:o(`chatSlashSectionSkills`),slashEmptyLabel:o(`chatSlashNoResult`),slashHintLabel:o(`chatSlashHint`),slashSkillHintLabel:o(`chatSlashSkillHint`)}},hint:BD({isModelOptionsLoading:_,isModelOptionsEmpty:v,onGoToProviders:e.chatInputManager.goToProviders,texts:{noModelOptionsLabel:o(`chatModelNoOptions`),configureProviderLabel:o(`chatGoConfigureProvider`)}}),toolbar:{selects:k,accessories:[{key:`attach`,label:o(`chatInputAttach`),icon:`paperclip`,iconOnly:!0,disabled:!b||y||r.isSending,...b?{onClick:()=>l.current?.click()}:{tooltip:o(`chatInputAttachComingSoon`)}}],skillPicker:te,actions:{sendError:i?null:r.sendError,isSending:r.isSending,canStopGeneration:r.canStopGeneration,sendDisabled:vO({snapshot:r,hasSendableDraft:A,isRuntimeBlocked:i}),stopDisabled:!r.canStopGeneration,stopHint:D,sendButtonLabel:o(`chatSend`),stopButtonLabel:o(`chatStop`),contextWindow:w,onSend:e.chatInputManager.send,onStop:e.chatInputManager.stop}}}),b?(0,N.jsx)(`input`,{ref:l,type:`file`,multiple:!0,className:`hidden`,onChange:ee}):null]})}var xk=[`cmd`,`command`,`query`,`q`,`path`,`url`,`to`,`channel`,`agentId`,`sessionKey`];function Sk(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Ck(e,t=2400){return e.length<=t?e:`${e.slice(0,t)}\n…`}function wk(e,t=120){let n=e.replace(/\s+/g,` `).trim();return n.length<=t?n:t<=1?`…`:`${n.slice(0,t-1)}…`}function Tk(e){if(typeof e==`string`)return e;if(typeof e==`number`||typeof e==`boolean`)return String(e);if(e==null)return``;try{return Ck(JSON.stringify(e,null,2))}catch{return String(e)}}function Ek(e){if(Sk(e))return e;if(typeof e!=`string`)return null;let t=e.trim();if(!t.startsWith(`{`)&&!t.startsWith(`[`))return null;try{let e=JSON.parse(t);return Sk(e)?e:null}catch{return null}}function Dk(e){let t=Ek(e);if(!t){let t=Tk(e).trim();return t?wk(t,120):void 0}let n=[];for(let e of xk){let r=t[e];if(typeof r==`string`&&r.trim()?n.push(`${e}: ${r.trim()}`):(typeof r==`number`||typeof r==`boolean`)&&n.push(`${e}: ${String(r)}`),n.length>=2)break}return n.length>0?wk(n.join(` · `),120):wk(Tk(t),140)}var Ok=`ui_inline_tokens`,kk=`$`;function Ak(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function jk(e){if(typeof e!=`string`)return null;let t=e.trim();return t.length>0?t:null}function Mk(e){let t=new Set,n=[];for(let r of e){let e=`${r.kind}:${r.key}:${r.rawText}`;t.has(e)||(t.add(e),n.push(r))}return n}function Nk(e){let t=[];for(let n of e)n.type!==`token`||n.tokenKind!==`skill`||t.push({kind:`skill`,key:n.tokenKey,label:n.label,rawText:`${kk}${n.tokenKey}`});return Mk(t)}function Pk(e){let t=e?.[Ok];if(!Array.isArray(t))return[];let n=[];for(let e of t){if(!Ak(e))continue;let t=jk(e.kind),r=jk(e.key),i=jk(e.rawText);!t||!r||!i||n.push({kind:t,key:r,rawText:i,label:jk(e.label)??r})}return Mk(n)}function Fk(e,t){if(e.length===0||t.length===0)return e.length===0?[]:[{type:`text`,text:e}];let n=[...t].sort((e,t)=>t.rawText.length-e.rawText.length),r=[],i=0;for(;i<e.length;){let t=null;for(let r of n)if(e.startsWith(r.rawText,i)){t=r;break}if(!t){let t=i+1;for(;t<e.length&&!n.some(n=>e.startsWith(n.rawText,t));)t+=1;r.push({type:`text`,text:e.slice(i,t)}),i=t;continue}r.push({type:`token`,token:t}),i+=t.rawText.length}return r}var Ik=/\u200B|\u200C|\u200D|\u2060|\uFEFF/g;function Lk(e){let t=e.trim();return t&&t.replace(Ik,``).trim()?t:null}function Rk(e){return e.replace(Ik,``).trim().length>0}function zk(e,t){let n=Fk(e,t);if(n.length===0)return null;let r=[],i=!1;for(let e of n){if(e.type===`token`){i=!0,r.push({type:`token`,token:{kind:e.token.kind,key:e.token.key,label:e.token.label,rawText:e.token.rawText}});continue}e.text.length!==0&&(Rk(e.text)&&(i=!0),r.push({type:`markdown`,text:e.text}))}return i?r:null}function Bk(e,t){let n=zk(e.text,t);if(n&&n.some(e=>e.type===`token`))return{type:`inline-content`,segments:n};let r=Lk(e.text);return r?{type:`markdown`,text:r}:null}function Vk(e){return Lk(e)}function Hk(e){return typeof e==`object`&&!!e}function Uk(e){if(typeof e!=`string`)return null;let t=e.trim();return t.length>0?t:null}function Wk(e){if(typeof e==`number`&&Number.isFinite(e)&&e>=0)return e;if(typeof e!=`string`)return null;let t=e.trim();if(!t)return null;let n=Number(t);return Number.isFinite(n)&&n>=0?n:null}function Gk(e){return Hk(e)?`command`in e||`workingDir`in e||`exitCode`in e||`stdout`in e||`stderr`in e||`aggregated_output`in e||`combinedOutput`in e:!1}function Kk(e,t){if(!Hk(e))return null;let n=Hk(e.asset)?e.asset:Array.isArray(e.assets)&&e.assets.length>0&&Hk(e.assets[0])?e.assets[0]:null;if(!n)return null;let r=Uk(n.url),i=Uk(n.mimeType)??`application/octet-stream`,a=Wk(n.sizeBytes);return r?{type:`file`,file:{label:Uk(n.name)??(i.startsWith(`image/`)?t.imageAttachmentLabel:t.fileAttachmentLabel),mimeType:i,dataUrl:r,...a==null?{}:{sizeBytes:a},isImage:i.startsWith(`image/`)}}:null}function qk(e,t){return{kind:e.kind,toolName:e.name,...`agentId`in e&&e.agentId?{agentId:e.agentId}:{},summary:e.detail,inputLabel:t.toolInputLabel,input:`input`in e&&typeof e.input==`string`?e.input:void 0,output:e.text,outputData:e.outputData,hasResult:!!e.hasResult,statusTone:e.statusTone,statusLabel:e.statusLabel,titleLabel:e.kind===`call`?t.toolCallLabel:t.toolResultLabel,outputLabel:t.toolOutputLabel,emptyLabel:t.toolNoOutputLabel,...`action`in e&&e.action?{action:e.action}:{},...`fileOperation`in e&&e.fileOperation?{fileOperation:e.fileOperation}:{}}}function Jk(e){let t=typeof e.status==`string`?e.status.trim().toLowerCase():``,n=typeof e.error==`string`&&e.error.trim().length>0;return e.cancelled===!0||t===`cancelled`?{kind:`result`,hasResult:!0,statusTone:`cancelled`,statusLabel:e.texts.toolStatusCancelledLabel}:n||t===`error`?{kind:`result`,hasResult:!0,statusTone:`error`,statusLabel:e.texts.toolStatusFailedLabel}:t===`result`||e.result!=null?{kind:`result`,hasResult:!0,statusTone:`success`,statusLabel:e.texts.toolStatusCompletedLabel}:{kind:`call`,hasResult:!1,statusTone:`running`,statusLabel:e.texts.toolStatusRunningLabel}}function Yk(e){if(typeof e!=`string`)return e;let t=e.trim();if(!t.startsWith(`{`)&&!t.startsWith(`[`))return e;try{return JSON.parse(t)}catch{return e}}function Xk(e,t){return Tk(t??Yk(e)).trim()||void 0}function Zk(e){return typeof e==`object`&&!!e}function Qk(e){if(typeof e!=`string`)return e;let t=e.trim();if(!t.startsWith(`{`)&&!t.startsWith(`[`))return e;try{return JSON.parse(t)}catch{return e}}function $k(e){if(typeof e!=`string`)return null;let t=e.trim();return t.length>0?t:null}function eA(e){let t=Qk(e);return Zk(t)?$k(t.agentId):null}function tA(e){return eA(e.parsedArgs)??eA(e.args)??eA(e.result)}var nA=12e3,rA=/^@@ -(\d+)(?:,\d+)? \+(\d+)(?:,\d+)? @@/;function iA(e){let t=e.replace(/\r\n/g,`
|
|
51
|
+
`),[e.parts]),{copied:r,copy:i}=iw({text:n});return n?(0,N.jsx)(`button`,{type:`button`,onClick:()=>void i(),className:`text-gray-400 hover:text-gray-600 transition-colors p-1 rounded-md hover:bg-gray-100 flex items-center justify-center`,"aria-label":r?t.copiedMessageLabel:t.copyMessageLabel,title:r?t.copiedMessageLabel:t.copyMessageLabel,children:r?(0,N.jsx)(Be,{className:`h-3.5 w-3.5`}):(0,N.jsx)(Rt,{className:`h-3.5 w-3.5`})}):null}var ZE=/\u200B|\u200C|\u200D|\u2060|\uFEFF/g;function QE(e){let t=e.trim();return t?t.replace(ZE,``).trim().length>0:!1}function $E(e){return e.parts.some(e=>e.type===`markdown`||e.type===`reasoning`?QE(e.text):!0)}function eD(){return(0,N.jsx)(`div`,{className:`flex items-center gap-2 px-1 py-0.5 text-[11px] text-gray-400`,children:(0,N.jsxs)(`div`,{className:`flex space-x-1 items-center h-full`,children:[(0,N.jsx)(`div`,{className:`h-1.5 w-1.5 rounded-full bg-gray-400 animate-pulse`}),(0,N.jsx)(`div`,{className:`h-1.5 w-1.5 rounded-full bg-gray-400 animate-pulse [animation-delay:200ms]`}),(0,N.jsx)(`div`,{className:`h-1.5 w-1.5 rounded-full bg-gray-400 animate-pulse [animation-delay:400ms]`})]})})}function tD(e){let t=e.messages.filter($E),n=t.some(e=>e.role===`assistant`&&(e.status===`streaming`||e.status===`pending`));return(0,N.jsxs)(`div`,{className:F(`space-y-5`,e.className),children:[t.map(t=>{let n=t.role===`user`,r=!n&&(t.status===`streaming`||t.status===`pending`);return(0,N.jsxs)(`div`,{className:F(`flex gap-3`,n?`justify-end`:`justify-start`),children:[n?null:(0,N.jsx)(_m,{role:t.role}),(0,N.jsxs)(`div`,{className:F(`w-fit max-w-[92%] space-y-2`,n&&`flex flex-col items-end`),children:[(0,N.jsx)(JE,{message:t,texts:e.texts,onToolAction:e.onToolAction,onFileOpen:e.onFileOpen,renderToolAgent:e.renderToolAgent}),(0,N.jsx)(`div`,{className:F(`flex items-center gap-2`,n&&`justify-end`),children:r?(0,N.jsx)(eD,{}):(0,N.jsxs)(N.Fragment,{children:[(0,N.jsx)(YE,{roleLabel:t.roleLabel,timestampLabel:t.timestampLabel,isUser:n}),n?null:(0,N.jsx)(XE,{message:t,texts:e.texts})]})})]}),n?(0,N.jsx)(_m,{role:t.role}):null]},t.id)}),e.isSending&&!n?(0,N.jsxs)(`div`,{className:`flex justify-start gap-3`,children:[(0,N.jsx)(_m,{role:`assistant`}),(0,N.jsx)(`div`,{className:`rounded-2xl border border-gray-200 bg-white px-4 py-3 text-sm text-gray-500 shadow-sm`,children:e.texts.typingLabel})]}):null]})}var nD=function(e){return e.EndpointReady=`endpoint.ready`,e.EndpointError=`endpoint.error`,e.MessageRequest=`message.request`,e.MessageStreamRequest=`message.stream-request`,e.MessageSent=`message.sent`,e.MessageAccepted=`message.accepted`,e.MessageIncoming=`message.incoming`,e.MessageCompleted=`message.completed`,e.MessageFailed=`message.failed`,e.MessageAbort=`message.abort`,e.MessageTextStart=`message.text-start`,e.MessageTextDelta=`message.text-delta`,e.MessageTextEnd=`message.text-end`,e.MessageReasoningStart=`message.reasoning-start`,e.MessageReasoningDelta=`message.reasoning-delta`,e.MessageReasoningEnd=`message.reasoning-end`,e.MessageToolCallStart=`message.tool-call-start`,e.MessageToolCallArgs=`message.tool-call-args`,e.MessageToolCallArgsDelta=`message.tool-call-args-delta`,e.MessageToolCallEnd=`message.tool-call-end`,e.MessageToolCallResult=`message.tool-call-result`,e.MessageRead=`message.read`,e.MessageDelivered=`message.delivered`,e.MessageRecalled=`message.recalled`,e.MessageReaction=`message.reaction`,e.RunStarted=`run.started`,e.RunFinished=`run.finished`,e.RunError=`run.error`,e.RunMetadata=`run.metadata`,e.ContextWindowUpdated=`context-window.updated`,e.TypingStart=`typing.start`,e.TypingEnd=`typing.end`,e.PresenceUpdated=`presence.updated`,e}({}),rD=/\[\[\s*reply_to_current\s*\]\]/gi,iD=/\[\[\s*reply_to\s*:\s*([^\]]+?)\s*\]\]/i;function aD(e){if(typeof e!=`string`)return;let t=e.trim();return t.length>0?t:void 0}function oD(e,t){let n=e,r;rD.test(n)&&(r=aD(t),n=n.replace(rD,``).trim());let i=n.match(iD)?.[1];return i&&(r=aD(i),n=n.replace(iD,``).trim()),r?{content:n,replyTo:r}:{content:n}}function sD(e,t=e.id){if(e.role!==`assistant`)return{...e,parts:[...e.parts],metadata:e.metadata?{...e.metadata}:void 0};let n=e.parts.findIndex(e=>e.type===`text`),r=e.metadata?{...e.metadata}:void 0,i=aD(r?.reply_to);if(n<0)return{...e,parts:[...e.parts],metadata:r};let a=e.parts[n];if(!a||a.type!==`text`)return{...e,parts:[...e.parts],metadata:r};let{content:o,replyTo:s}=oD(a.text,t),c=s??i,l=e.parts.flatMap((e,t)=>t!==n||e.type!==`text`?[e]:o.length===0?[]:[{...e,text:o}]);return c?{...e,parts:l,metadata:{...r,reply_to:c}}:{...e,parts:l,metadata:r}}function cD(e){return{...e,parts:[...e.parts],metadata:e.metadata?{...e.metadata}:void 0}}function lD(e){return cD(sD(e))}var uD=`__nextclaw_aborted_tool_call__`;function dD(e){let t=e.error?.trim();return{code:`runtime-error`,message:t&&t.length>0?t:`Agent run failed.`,details:{sessionId:e.sessionId,messageId:e.messageId,threadId:e.threadId,runId:e.runId}}}function fD(e,t){return t.trim()?e.id.startsWith(`tool-`)?!0:e.parts.some(e=>e.type===`tool-invocation`):!1}function pD(e,t,n){for(let[r,i]of e)i===t&&e.set(r,n)}function mD(e,t,n){for(let[r,i]of e)i===n&&(e.delete(r),t.delete(r))}function hD(e,t){for(let n=e.length-1;n>=0;--n){let r=e[n];if(r.type===`tool-invocation`&&r.toolCallId===t)return r}return null}function gD(e,t){return hD(e,t)?.toolName??null}function _D(e,t){let n=[...e];for(let e=n.length-1;e>=0;--e){let r=n[e];if(r.type===`tool-invocation`&&r.toolCallId===t.toolCallId)return n[e]={...r,...t},n}return n.push(t),n}function vD(e){let t=[];return{parts:e.map(e=>e.type!==`tool-invocation`||!e.toolCallId||e.state===`result`||e.state===`cancelled`?e:(t.push(e.toolCallId),{...e,state:`cancelled`})),toolCallIds:t}}var yD=`assistant`,bD=class{messages=[];streamingMessage=null;error=null;activeRun=null;contextWindow=null;listeners=new Set;toolCallMessageIdByCallId=new Map;toolCallArgsRawByCallId=new Map;lastSettledRunId=null;snapshotCache=null;snapshotVersion=-1;stateVersion=0;getSnapshot=()=>{if(this.snapshotCache&&this.snapshotVersion===this.stateVersion)return this.snapshotCache;let e={messages:this.messages,streamingMessage:this.streamingMessage,error:this.error?{...this.error,details:this.error.details?{...this.error.details}:void 0}:null,activeRun:this.activeRun?{...this.activeRun}:null,contextWindow:this.contextWindow?{...this.contextWindow}:null};return this.snapshotCache=e,this.snapshotVersion=this.stateVersion,e};subscribe=e=>(this.listeners.add(e),()=>this.listeners.delete(e));reset=()=>{this.messages.length===0&&!this.streamingMessage&&!this.error&&!this.activeRun&&!this.contextWindow&&this.toolCallMessageIdByCallId.size===0&&this.toolCallArgsRawByCallId.size===0||(this.messages=[],this.streamingMessage=null,this.error=null,this.activeRun=null,this.contextWindow=null,this.toolCallMessageIdByCallId.clear(),this.toolCallArgsRawByCallId.clear(),this.lastSettledRunId=null,this.stateVersion+=1,this.notifyListeners())};hydrate=e=>{this.messages=e.messages.map(e=>lD(e)),this.streamingMessage=null,this.error=null,this.contextWindow=e.contextWindow?{...e.contextWindow}:null,this.activeRun=e.activeRun?{...e.activeRun,sessionId:e.activeRun.sessionId??e.sessionId,abortDisabledReason:e.activeRun.abortDisabledReason??null}:null,this.toolCallMessageIdByCallId.clear(),this.toolCallArgsRawByCallId.clear(),this.lastSettledRunId=null,this.stateVersion+=1,this.notifyListeners()};dispatch=e=>this.dispatchBatch([e]);dispatchBatch=async e=>{if(!e.length)return;let t=this.stateVersion;e.forEach(this.applyEvent),this.stateVersion!==t&&this.notifyListeners()};applyEvent=e=>{switch(e.type){case nD.MessageSent:this.handleMessageSent(e.payload);break;case nD.MessageAbort:this.handleMessageAbort(e.payload);break;case nD.MessageTextStart:this.handleMessageTextStart(e.payload);break;case nD.MessageTextDelta:this.handleMessageTextDelta(e.payload);break;case nD.MessageTextEnd:this.handleMessageTextEnd(e.payload);break;case nD.MessageReasoningStart:this.handleMessageReasoningStart(e.payload);break;case nD.MessageReasoningDelta:this.handleMessageReasoningDelta(e.payload);break;case nD.MessageReasoningEnd:this.handleMessageReasoningEnd(e.payload);break;case nD.MessageToolCallStart:this.handleMessageToolCallStart(e.payload);break;case nD.MessageToolCallArgs:this.handleMessageToolCallArgs(e.payload);break;case nD.MessageToolCallArgsDelta:this.handleMessageToolCallArgsDelta(e.payload);break;case nD.MessageToolCallEnd:this.handleMessageToolCallEnd(e.payload);break;case nD.MessageToolCallResult:this.handleMessageToolCallResult(e.payload);break;case nD.RunStarted:this.handleRunStarted(e.payload);break;case nD.RunFinished:this.handleRunFinished(e.payload);break;case nD.RunError:this.handleRunError(e.payload);break;case nD.RunMetadata:this.handleRunMetadata(e.payload);break;case nD.ContextWindowUpdated:this.handleContextWindowUpdated(e.payload);break;case nD.EndpointError:this.handleEndpointError(e.payload);break;default:break}};handleMessageSent=e=>{this.upsertMessage(e.message),this.setError(null)};handleMessageAbort=e=>{let t=e.messageId?.trim();if(this.clearActiveRun(),this.setError(null),this.streamingMessage&&(!t||this.streamingMessage.id===t)){let e=this.streamingMessage.id,{parts:n,toolCallIds:r}=vD(this.streamingMessage.parts);this.upsertMessage({...this.streamingMessage,status:`final`,parts:n}),this.replaceStreamingMessage(null),t?mD(this.toolCallMessageIdByCallId,this.toolCallArgsRawByCallId,t):mD(this.toolCallMessageIdByCallId,this.toolCallArgsRawByCallId,e),r.forEach(e=>this.toolCallArgsRawByCallId.set(e,uD))}};handleMessageTextStart=e=>{this.ensureStreamingMessage(e.sessionId,e.messageId,`streaming`),this.setError(null)};handleMessageTextDelta=e=>{if(!e.delta)return;let t=this.ensureStreamingMessage(e.sessionId,e.messageId,`streaming`),n=[...t.parts],r=n[n.length-1];r?.type===`text`?n[n.length-1]={type:`text`,text:`${r.text}${e.delta}`}:n.push({type:`text`,text:e.delta}),this.replaceStreamingMessage({...t,parts:n,status:`streaming`})};handleMessageTextEnd=e=>{this.streamingMessage?.id===e.messageId&&this.streamingMessage.status===`streaming`&&this.replaceStreamingMessage({...this.streamingMessage,status:`pending`})};handleMessageReasoningStart=e=>{this.ensureStreamingMessage(e.sessionId,e.messageId,`streaming`)};handleMessageReasoningDelta=e=>{if(!e.delta)return;let t=this.ensureStreamingMessage(e.sessionId,e.messageId,`streaming`),n=[...t.parts],r=n[n.length-1];r?.type===`reasoning`?n[n.length-1]={type:`reasoning`,text:`${r.text}${e.delta}`}:n.push({type:`reasoning`,text:e.delta}),this.replaceStreamingMessage({...t,parts:n,status:`streaming`})};handleMessageReasoningEnd=e=>{this.streamingMessage?.id,e.messageId};handleMessageToolCallStart=e=>{if(this.toolCallArgsRawByCallId.get(e.toolCallId)===`__nextclaw_aborted_tool_call__`)return;let t=this.resolveToolCallTargetMessage(e.sessionId,e.toolCallId,e.messageId);this.toolCallArgsRawByCallId.set(e.toolCallId,``);let n=_D(t.parts,{type:`tool-invocation`,toolCallId:e.toolCallId,toolName:e.toolName,state:`partial-call`,args:``});this.replaceStreamingMessage({...t,parts:n,status:`streaming`}),this.setError(null)};handleMessageToolCallArgs=e=>{this.toolCallArgsRawByCallId.get(e.toolCallId)!==`__nextclaw_aborted_tool_call__`&&(this.toolCallArgsRawByCallId.set(e.toolCallId,e.args),this.applyToolCallArgs(e.sessionId,e.toolCallId,e.args))};handleMessageToolCallArgsDelta=e=>{if(this.toolCallArgsRawByCallId.get(e.toolCallId)===`__nextclaw_aborted_tool_call__`)return;let t=`${this.toolCallArgsRawByCallId.get(e.toolCallId)??``}${e.delta}`;this.toolCallArgsRawByCallId.set(e.toolCallId,t),this.applyToolCallArgs(e.sessionId,e.toolCallId,t,e.messageId)};handleMessageToolCallEnd=e=>{if(this.toolCallArgsRawByCallId.get(e.toolCallId)===`__nextclaw_aborted_tool_call__`)return;let t=this.resolveToolCallTargetMessage(e.sessionId,e.toolCallId),n=this.toolCallArgsRawByCallId.get(e.toolCallId)??``,r=_D(t.parts,{type:`tool-invocation`,toolCallId:e.toolCallId,toolName:gD(t.parts,e.toolCallId)??`unknown`,state:`call`,args:n});this.replaceStreamingMessage({...t,parts:r,status:`streaming`})};handleMessageToolCallResult=e=>{if(this.toolCallArgsRawByCallId.get(e.toolCallId)!==`__nextclaw_aborted_tool_call__`&&!this.updateMessageContainingToolCall(e.toolCallId,(t,n)=>{let r={type:`tool-invocation`,toolCallId:e.toolCallId,toolName:n.toolName,state:`result`,args:n.args,result:e.content,resultContentItems:e.contentItems};return _D(t.parts,r)})){let t=this.resolveToolCallTargetMessage(e.sessionId,e.toolCallId),n=_D(t.parts,{type:`tool-invocation`,toolCallId:e.toolCallId,toolName:`unknown`,state:`result`,result:e.content,resultContentItems:e.contentItems});this.replaceStreamingMessage({...t,parts:n,status:`streaming`})}};handleRunStarted=e=>{this.isSettledRunId(e.runId)||(this.setError(null),this.activeRun={runId:e.runId??null,sessionId:e.sessionId},this.stateVersion+=1)};handleRunFinished=e=>{this.markRunAsSettled(e.runId??this.activeRun?.runId??null),this.settleStreamingMessage(`final`),this.setError(null),this.clearActiveRun()};handleRunError=e=>{this.markRunAsSettled(e.runId??this.activeRun?.runId??null),this.settleStreamingMessage(`error`),this.setError(dD(e)),this.clearActiveRun()};handleRunMetadata=e=>{let t=e.metadata;if(t?.kind===`ready`){let e=t;if(this.isSettledRunId(e.runId))return;this.activeRun={runId:e.runId??this.activeRun?.runId??null,sessionId:e.sessionId??this.activeRun?.sessionId,abortDisabledReason:e.supportsAbort===!1?e.abortDisabledReason??`Unsupported`:null},this.stateVersion+=1}else t?.kind===`final`&&(this.markRunAsSettled(e.runId??this.activeRun?.runId??null),this.clearActiveRun())};handleContextWindowUpdated=e=>{this.contextWindow={...e.contextWindow},this.stateVersion+=1};handleEndpointError=e=>{if(e.code===`abort-error`){this.handleMessageAbort({sessionId:this.activeRun?.sessionId??this.streamingMessage?.sessionId??``,...this.streamingMessage?.id?{messageId:this.streamingMessage.id}:{}});return}this.settleStreamingMessage(`error`),this.clearActiveRun(),this.setError(e)};applyToolCallArgs=(e,t,n,r)=>{let i=this.resolveToolCallTargetMessage(e,t,r),a=gD(i.parts,t)??`unknown`,o=_D(i.parts,{type:`tool-invocation`,toolCallId:t,toolName:a,state:`partial-call`,args:n});this.replaceStreamingMessage({...i,parts:o,status:`streaming`})};ensureStreamingMessage=(e,t,n)=>{if(this.streamingMessage?.id===t){if(this.streamingMessage.status===n)return this.streamingMessage;let e={...this.streamingMessage,status:n};return this.replaceStreamingMessage(e),e}let r=this.messages.findIndex(e=>e.id===t);if(r>=0){let t=cD(this.messages[r]),i=[...this.messages];i.splice(r,1),this.messages=i,this.stateVersion+=1;let a={...t,sessionId:e,status:n};return this.replaceStreamingMessage(a),a}let i=this.streamingMessage;if(i&&i.id!==t&&i.sessionId===e&&fD(i,t)){let r={...i,id:t,sessionId:e,status:n};return pD(this.toolCallMessageIdByCallId,i.id,t),this.replaceStreamingMessage(r),r}let a={id:t,sessionId:e,role:yD,status:n,parts:[],timestamp:new Date().toISOString()};return this.replaceStreamingMessage(a),a};resolveToolCallTargetMessage=(e,t,n)=>{let r=n?.trim()||this.toolCallMessageIdByCallId.get(t)||this.streamingMessage?.id||`tool-${t}`;return this.toolCallMessageIdByCallId.set(t,r),this.ensureStreamingMessage(e,r,`streaming`)};updateMessageContainingToolCall=(e,t)=>{if(this.streamingMessage){let n=hD(this.streamingMessage.parts,e);if(n){let e=t(this.streamingMessage,n);return this.replaceStreamingMessage({...this.streamingMessage,parts:e}),!0}}for(let n=this.messages.length-1;n>=0;--n){let r=this.messages[n],i=hD(r.parts,e);if(!i)continue;let a=[...this.messages];return a[n]={...r,parts:t(r,i)},this.messages=a,this.stateVersion+=1,!0}return!1};upsertMessage=e=>{let t=lD(e),n=this.messages.findIndex(e=>e.id===t.id);if(n<0){this.messages=[...this.messages,t],this.stateVersion+=1;return}let r=[...this.messages];r[n]=t,this.messages=r,this.stateVersion+=1};replaceStreamingMessage=e=>{!e&&!this.streamingMessage||(this.streamingMessage=e?lD(e):null,this.stateVersion+=1)};setError=e=>{this.error?.code===e?.code&&this.error?.message===e?.message&&this.error?.details===e?.details&&this.error?.cause===e?.cause||(this.error=e?{...e,details:e.details?{...e.details}:void 0}:null,this.stateVersion+=1)};clearActiveRun=()=>{this.activeRun&&(this.activeRun=null,this.stateVersion+=1)};isSettledRunId=e=>!!e?.trim()&&e===this.lastSettledRunId;markRunAsSettled=e=>{this.lastSettledRunId=e?.trim()||null};settleStreamingMessage=e=>{if(!this.streamingMessage)return;let t={...this.streamingMessage,status:e};this.upsertMessage(t),this.replaceStreamingMessage(null),mD(this.toolCallMessageIdByCallId,this.toolCallArgsRawByCallId,t.id)};notifyListeners=()=>{let e=this.getSnapshot();for(let t of this.listeners)t(e)}},xD=16,SD=class{constructor(e){this.dispatchBatch=e,this.queue=[],this.flushTimerId=null,this.isFlushing=!1,this.isDisposed=!1,this.enqueue=e=>{this.isDisposed||(this.queue.push(e),this.scheduleFlush())},this.dispose=()=>{this.isDisposed=!0,this.flushTimerId!==null&&(window.clearTimeout(this.flushTimerId),this.flushTimerId=null),this.queue.length=0},this.scheduleFlush=()=>{this.flushTimerId!==null||this.isFlushing||this.queue.length===0||(this.flushTimerId=window.setTimeout(()=>{this.flushTimerId=null,this.flush()},xD))},this.flush=async()=>{if(!(this.isDisposed||this.isFlushing||this.queue.length===0)){this.isFlushing=!0;try{for(;this.queue.length>0;){let e=this.queue.splice(0);await this.dispatchBatch(e)}}finally{this.isFlushing=!1,this.scheduleFlush()}}}}};function CD(e,t){let n=e.dispatchBatch;return typeof n==`function`?n.call(e,t):t.reduce((t,n)=>t.then(()=>e.dispatch(n)),Promise.resolve())}function wD(e,t){if(!t)return!0;let n=`payload`in e?e.payload:null;return!n||typeof n!=`object`||!(`sessionId`in n)||typeof n.sessionId!=`string`?!0:n.sessionId===t}function TD(e){return e.parts.some(e=>e.type===`text`||e.type===`rich-text`||e.type===`reasoning`?e.text.trim().length>0:!0)}function ED(e,t){if(typeof e==`string`){let n=e.trim();return n?{...t?{sessionId:t}:{},message:{id:`user-${Date.now().toString(36)}`,...t?{sessionId:t}:{},role:`user`,status:`final`,parts:[{type:`text`,text:n}],timestamp:new Date().toISOString()}}:null}if(!TD(e.message))return null;let n=e.sessionId||e.message.sessionId||t;return{...e,...n?{sessionId:n}:{},message:{...e.message,...n?{sessionId:n}:{}}}}function DD(e){let t=(0,P.useRef)();return t.current?e&&t.current.sessionId===null?t.current.sessionId=e:t.current.sessionId!==(e??null)&&(t.current={sessionId:e??null,manager:new bD}):t.current={sessionId:e??null,manager:new bD},t.current.manager}function OD({sessionId:e,client:t,manager:n}){let r=(0,P.useRef)(e),i=(0,P.useSyncExternalStore)(e=>n.subscribe(()=>e()),()=>n.getSnapshot(),()=>n.getSnapshot()),[a,o]=(0,P.useState)(!1);(0,P.useEffect)(()=>{r.current=e},[e]),(0,P.useEffect)(()=>{o(!1)},[e]),(0,P.useEffect)(()=>{let e=new SD(e=>CD(n,e)),i=t.subscribe(t=>{wD(t,r.current)&&e.enqueue(t)});return()=>{i(),e.dispose(),t.stop()}},[t,n]);let s=i.streamingMessage?[...i.messages,i.streamingMessage]:i.messages,c=i.activeRun?.runId??null,l=!!i.activeRun;return{snapshot:i,visibleMessages:s,activeRunId:c,isRunning:l,isSending:a,send:async r=>{if(a||l)return;let i=ED(r,e);if(i){o(!0),e&&await n.dispatch({type:nD.MessageSent,payload:{sessionId:e,message:{...i.message,sessionId:e},metadata:i.metadata}});try{await t.send(i)}finally{o(!1)}}},abort:async()=>{!i.activeRun||!e||await t.abort({sessionId:e})},streamRun:async()=>{e&&(await t.stop(),await t.stream({sessionId:e}))}}}function kD(e){return e instanceof Error?e:Error(String(e))}function AD(e){let{hydratedSessionId:t,isHydrating:n,sessionId:r}=e;return r?n||t!==r:!1}function jD(e,t){let n=e.getSnapshot();return n.activeRun?.sessionId===t||n.streamingMessage?.sessionId===t||n.messages.some(e=>e.sessionId===t)}function MD(e,t){return e.status===`running`?{runId:null,sessionId:t,abortDisabledReason:null}:null}function ND(e,t,n){return n.signal.aborted||e.requestId!==t}function PD({sessionId:e,client:t,loadSeed:n}){let r=DD(e),i=OD({sessionId:e,client:t,manager:r}),[a,o]=(0,P.useState)(!0),[s,c]=(0,P.useState)(null),[l,u]=(0,P.useState)(null),d=(0,P.useRef)({requestId:0,controller:null}),f=(0,P.useCallback)(async()=>{await t.stop(),r.reset(),c(null),u(null),o(!1),d.current={requestId:d.current.requestId+1,controller:null}},[t,r]),p=(0,P.useCallback)(e=>{c(null),u(e),o(!1)},[]),m=(0,P.useCallback)(async()=>{if(d.current.controller?.abort(),!e){await f();return}let i=new AbortController,a=d.current.requestId+1;if(d.current={requestId:a,controller:i},jD(r,e)){p(e),d.current.controller===i&&(d.current.controller=null);return}await t.stop(),r.reset(),c(null),o(!0);try{let o=await n(e,i.signal);if(ND(d.current,a,i))return;r.hydrate({sessionId:e,messages:o.messages,activeRun:MD(o,e)}),p(e),t.stream({sessionId:e}).catch(e=>{d.current.requestId===a&&c(kD(e))})}catch(t){if(ND(d.current,a,i))return;c(kD(t)),u(e),o(!1)}finally{d.current.controller===i&&(d.current.controller=null)}},[t,n,r,p,f,e]);return(0,P.useEffect)(()=>(m(),()=>{d.current.controller?.abort(),d.current.controller=null}),[m]),{...i,isHydrating:AD({sessionId:e,hydratedSessionId:l,isHydrating:a}),hydrateError:s}}var FD=200*1024*1024,ID=`application/octet-stream`;function LD(e){let t=e.type.trim().toLowerCase();return t.length>0?t:ID}function RD(e,t){let n=t.acceptedMimeTypes&&t.acceptedMimeTypes.length>0?new Set(t.acceptedMimeTypes.map(e=>e.trim().toLowerCase())):null,r=t.maxBytes??209715200,i=LD(e);return n&&!n.has(i)?{ok:!1,rejected:{fileName:e.name,mimeType:i,sizeBytes:e.size,reason:`unsupported-type`}}:e.size>r?{ok:!1,rejected:{fileName:e.name,mimeType:i,sizeBytes:e.size,reason:`too-large`}}:{ok:!0,mimeType:i}}function zD(e){let t=e.parts&&e.parts.length>0?e.parts.map(e=>structuredClone(e)):[...e.text?.trim()??``?[{type:`text`,text:e.text.trim()}]:[],...(e.attachments??[]).map(e=>({type:`file`,name:e.name,mimeType:e.mimeType,...e.assetUri?.trim()?{assetUri:e.assetUri.trim()}:{},...e.url?.trim()?{url:e.url.trim()}:{},...e.contentBase64?.trim()?{contentBase64:e.contentBase64.trim()}:{},sizeBytes:e.sizeBytes}))];if(t.length===0)return null;let n=e.timestamp??new Date().toISOString(),r=e.messageId??`user-${Date.now().toString(36)}`;return{...e.sessionId?{sessionId:e.sessionId}:{},message:{id:r,...e.sessionId?{sessionId:e.sessionId}:{},role:`user`,status:`final`,parts:t,timestamp:n,...e.metadata?{metadata:e.metadata}:{}},...e.metadata?{metadata:e.metadata}:{}}}async function BD(e,t){let n=[],r=[];for(let i of e){let e=RD(i,t);if(!e.ok){r.push(e.rejected);continue}n.push(i)}if(n.length===0)return{attachments:[],rejected:r};try{return{attachments:await t.uploadBatch(n),rejected:r}}catch{return r.push(...n.map(e=>({fileName:e.name,mimeType:LD(e),sizeBytes:e.size,reason:`read-failed`}))),{attachments:[],rejected:r}}}function VD(e){let t=e.modelLabel.trim(),n=e.providerLabel.trim();return n?`${n}/${t}`:t}function HD(e){let t=[];for(let n of[`off`,...e])t.includes(n)||t.push(n);return t}function UD(e){return!e.isModelOptionsLoading&&!e.isModelOptionsEmpty?null:e.isModelOptionsLoading?{tone:`neutral`,loading:!0}:{tone:`warning`,text:e.texts.noModelOptionsLabel,actionLabel:e.texts.configureProviderLabel,onAction:e.onGoToProviders}}function WD({modelOptions:e,recentModelValues:t,selectedModel:n,isModelOptionsLoading:r,hasModelOptions:i,onValueChange:a,texts:o}){let s=e.find(e=>e.value===n)??e[0],c=i?s?.value:void 0,l=new Set(t??[]),u=new Map(e.map(e=>[e.value,e])),d=(t??[]).map(e=>u.get(e)).filter(e=>!!e),f=e.filter(e=>!l.has(e.value)),p=d.length>0?[{key:`recent-models`,label:o.recentModelsLabel,options:d.map(e=>({value:e.value,label:VD(e)}))},{key:`all-models`,label:o.allModelsLabel,options:f.map(e=>({value:e.value,label:VD(e)}))}].filter(e=>e.options.length>0):void 0;return{key:`model`,value:c,placeholder:o.modelSelectPlaceholder,selectedLabel:s?VD(s):void 0,icon:`sparkles`,options:e.map(e=>({value:e.value,label:VD(e)})),groups:p,disabled:!i,loading:r,emptyLabel:o.modelNoOptionsLabel,onValueChange:a}}function GD(e){if(e.supportedLevels.length===0)return null;let t=HD(e.supportedLevels),n=t.includes(`off`)?`off`:t[0],r=e.selectedThinkingLevel&&t.includes(e.selectedThinkingLevel)&&e.selectedThinkingLevel||e.defaultThinkingLevel&&t.includes(e.defaultThinkingLevel)&&e.defaultThinkingLevel||n;return{key:`thinking`,value:r,placeholder:e.texts.thinkingLabels[r],selectedLabel:e.texts.thinkingLabels[r],icon:`brain`,options:t.map(t=>({value:t,label:e.texts.thinkingLabels[t]})),onValueChange:t=>e.onValueChange(t)}}var KD={exactSpec:1200,exactLabel:1150,prefixSpec:1e3,prefixLabel:950,prefixToken:900,containsSpec:800,containsLabel:760,containsDescription:500,subsequence:300,fallback:1};function qD(e){return(e??``).trim().toLowerCase()}function JD(e,t){if(!e||!t)return!1;let n=0;for(let r of t)if(r===e[n]&&(n+=1,n>=e.length))return!0;return!1}function YD(e,t){let n=qD(t);if(!n)return KD.fallback;let r=qD(e.key),i=qD(e.label||e.key),a=qD(`${e.descriptionZh??``} ${e.description??``}`),o=i.split(/[\s/_-]+/).filter(Boolean);return r===n?KD.exactSpec:i===n?KD.exactLabel:r.startsWith(n)?KD.prefixSpec:i.startsWith(n)?KD.prefixLabel:o.some(e=>e.startsWith(n))?KD.prefixToken:r.includes(n)?KD.containsSpec:i.includes(n)?KD.containsLabel:a.includes(n)?KD.containsDescription:JD(n,i)||JD(n,r)?KD.subsequence:0}function XD(e){return e>=KD.exactLabel?4:e>=KD.prefixToken?3:e>=KD.containsLabel?2:e>0?1:0}function ZD(e){return new Map(e.map((e,t)=>[e,t]))}function QD(e,t){let n=ZD(t),r=[],i=[];for(let t of e){if(n.has(t.key)){r.push(t);continue}i.push(t)}return r.sort((e,t)=>(n.get(e.key)??1/0)-(n.get(t.key)??1/0)),[...r,...i]}function $D(e,t,n,r=[]){let i=new Intl.Collator(void 0,{sensitivity:`base`,numeric:!0}),a=ZD(r);return e.map((e,n)=>({record:e,order:n,score:YD(e,t)})).filter(e=>e.score>0).sort((e,t)=>{let n=XD(e.score),r=XD(t.score);if(r!==n)return r-n;let o=a.get(e.record.key)??1/0,s=a.get(t.record.key)??1/0;if(o!==s)return o-s;if(t.score!==e.score)return t.score-e.score;let c=(e.record.label||e.record.key).trim(),l=(t.record.label||t.record.key).trim(),u=i.compare(c,l);return u===0?e.order-t.order:u}).map(({record:e})=>({key:`skill:${e.key}`,title:e.label||e.key,subtitle:n.slashSkillSubtitle,description:(e.descriptionZh??e.description??``).trim()||n.noSkillDescription,detailLines:[`${n.slashSkillSpecLabel}: ${e.key}`,...e.scopeLabel?[`${n.slashSkillScopeLabel}: ${e.scopeLabel}`]:[]],value:e.key}))}function eO(e){return e.map(e=>({key:e.key,label:e.label,description:e.descriptionZh||e.description||``,badgeLabel:e.badgeLabel}))}function tO(e){let t=QD(e.skillRecords,e.recentSkillValues??[]),n=new Set(e.groupedRecentSkillValues??[]),r=eO(t.filter(e=>n.has(e.key))),i=eO(t.filter(e=>!n.has(e.key)));return{title:e.texts.title,searchPlaceholder:e.texts.searchPlaceholder,emptyLabel:e.texts.emptyLabel,loadingLabel:e.texts.loadingLabel,isLoading:e.isLoading,manageLabel:e.texts.manageLabel,manageHref:`/marketplace/skills`,options:eO(t),groups:r.length>0?[{key:`recent-skills`,label:e.texts.recentSkillsLabel,options:r},{key:`all-skills`,label:e.texts.allSkillsLabel,options:i}].filter(e=>e.options.length>0):void 0,selectedKeys:e.selectedSkills,onSelectedKeysChange:e.onSelectedKeysChange}}var nO=`$`;function rO(e,t){if(t.length===0)return e;let n=e[e.length-1];return n?.type===`text`?[...e.slice(0,-1),{...n,text:n.text+t}]:[...e,{type:`text`,text:t}]}function iO(){return wp()}function aO(e){return Tp(e)}function oO(e){return Op(e)}function sO(e){return kp(e,`skill`)}function cO(e){return kp(e,`file`)}function lO(e,t,n){let r=new Set(t),i=Ip(e,e=>e.tokenKind===`skill`&&!r.has(e.tokenKey)),a=kp(i,`skill`),o=new Map(n.map(e=>[e.ref,e])),s=t.filter(e=>!a.includes(e)).map(e=>Sp({tokenKind:`skill`,tokenKey:e,label:o.get(e)?.name||e}));return s.length===0?i:Ep([...i,...s])}function uO(e,t){let n=new Set(t.map(e=>e.id));return Ip(e,e=>e.tokenKind===`file`&&!n.has(e.tokenKey))}function dO(e,t){let n=new Set(cO(e));return t.filter(e=>n.has(e.id))}function fO(e,t){let n=new Map(t.map(e=>[e.id,e])),r=[];for(let t of e){if(t.type===`text`){r=rO(r,t.text);continue}if(t.tokenKind===`skill`){r=rO(r,`${nO}${t.tokenKey}`);continue}if(t.tokenKind!==`file`)continue;let e=n.get(t.tokenKey);e&&r.push({type:`file`,name:e.name,mimeType:e.mimeType,...e.assetUri?{assetUri:e.assetUri}:{},...e.url?{url:e.url}:{},...e.contentBase64?{contentBase64:e.contentBase64}:{},sizeBytes:e.sizeBytes})}return r}var pO={isProviderStateResolved:!1,composerNodes:iO(),attachments:[],draft:``,pendingSessionType:`native`,pendingProjectRoot:null,pendingProjectRootSessionKey:null,defaultSessionType:`native`,canStopGeneration:!1,stopDisabledReason:null,sendError:null,isSending:!1,modelOptions:[],selectedModel:``,selectedThinkingLevel:null,sessionTypeOptions:[],selectedSessionType:void 0,stopSupported:!1,stopReason:void 0,canEditSessionType:!1,sessionTypeUnavailable:!1,skillRecords:[],isSkillsLoading:!1,selectedSkills:[]},Q=w(e=>({snapshot:pO,setSnapshot:t=>e(e=>({snapshot:{...e.snapshot,...t}}))})),mO=class{constructor(e){this.options=e,this.read=()=>{let e=this.getStorage();if(!e)return[];try{return this.normalizeList(JSON.parse(e.getItem(this.options.storageKey)??`[]`))}catch{return[]}},this.remember=e=>{let t=this.normalizeValue(e);if(!t)return this.read();let n=[t,...this.read().filter(e=>e!==t)].slice(0,this.options.limit);return this.write(n),n},this.resolveVisible=e=>{let t=this.normalizeList(e.availableValues,1/0);if(t.length<=e.minAvailableCount)return[];let n=new Set(t),r=[],i=Math.max(1,e.limit??this.options.limit);for(let e of this.read())if(!(!n.has(e)||r.includes(e))&&(r.push(e),r.length>=i))break;return r},this.write=e=>{let t=this.getStorage();if(t)try{t.setItem(this.options.storageKey,JSON.stringify(this.normalizeList(e)))}catch{}},this.getStorage=()=>Object.prototype.hasOwnProperty.call(this.options,`storage`)?this.options.storage??null:typeof window>`u`?null:window.localStorage,this.normalizeList=(e,t=this.options.limit)=>{if(!Array.isArray(e))return[];let n=[];for(let r of e){let e=this.normalizeValue(r);if(!(!e||n.includes(e))&&(n.push(e),n.length>=t))break}return n},this.normalizeValue=e=>{if(typeof e!=`string`)return null;let t=e.trim();return t.length>0?t:null}}},hO=new mO({storageKey:`nextclaw.chat.recent-models`,limit:3}),gO=new mO({storageKey:`nextclaw.chat.recent-skills`,limit:5});function _O(e){return e.modelOptions.length>0}function vO(e){return!e.isProviderStateResolved&&!_O(e)}function yO(e){return e.isProviderStateResolved&&!_O(e)}function bO(e){return!1}function xO(e){let{hasSendableDraft:t,isRuntimeBlocked:n}=e;return n||!t}function SO(e,t){let n=e?.trim();if(!n)return!1;let r=t?.trim();return r?n.localeCompare(r)>0:!1}function CO(e){let{active:t,readAt:n,runStatus:r,lastMessageAt:i}=e;return t||r===`running`?!1:SO(i,n)}var wO={selectedSessionKey:null,draftSessionKey:null,selectedAgentId:`main`,query:``,listMode:`time-first`};function TO(e){return t=>e(e=>({snapshot:{...e.snapshot,...t}}))}function EO(e){return(t,n)=>e(e=>{let r=t.trim(),i=n?.trim();if(!r||!i)return e;let a=e.optimisticReadAtBySessionKey[r];return a&&a.localeCompare(i)>=0?e:{...e,optimisticReadAtBySessionKey:{...e.optimisticReadAtBySessionKey,[r]:i}}})}var DO=w(e=>({snapshot:wO,optimisticReadAtBySessionKey:{},setSnapshot:TO(e),markSessionRead:EO(e)})),OO={isProviderStateResolved:!1,modelOptions:[],sessionTypeUnavailable:!1,sessionTypeUnavailableMessage:null,sessionTypeLabel:null,sessionTypeIcon:null,sessionKey:null,agentId:null,agentDisplayName:null,agentAvatarUrl:null,availableAgents:[],sessionDisplayName:void 0,sessionProjectRoot:null,sessionProjectName:null,canDeleteSession:!1,isDeletePending:!1,threadRef:null,isHistoryLoading:!1,messages:[],isSending:!1,isAwaitingAssistantOutput:!1,parentSessionKey:null,parentSessionLabel:null,workspacePanelParentKey:null,childSessionTabs:[],activeChildSessionKey:null,workspaceFileTabs:[],activeWorkspaceFileKey:null,contextWindow:null},kO=w(e=>({snapshot:OO,setSnapshot:t=>e(e=>({snapshot:{...e.snapshot,...t}}))}));function AO(e){return e>=1e6?`${(e/1e6).toFixed(e>=1e7?0:1)}M`:e>=1e3?`${(e/1e3).toFixed(e>=1e4?0:1)}k`:String(e)}function jO(e){if(!e||e.totalContextTokens<=0)return null;let t=e.usedContextTokens/e.totalContextTokens,n=Math.max(0,Math.min(1,t)),r=`${Math.round(n*100)}%`,i=n>=.9?`danger`:n>=.75?`warning`:`neutral`,a=[{label:o(`chatContextWindowUsed`),value:AO(e.usedContextTokens)},{label:o(`chatContextWindowTotal`),value:AO(e.totalContextTokens)},{label:o(`chatContextWindowAvailable`),value:AO(e.availableContextTokens)}];return e.prunedUsedContextTokens!==e.usedContextTokens&&a.push({label:o(`chatContextWindowPruned`),value:AO(e.prunedUsedContextTokens)}),e.droppedHistoryCount>0&&a.push({label:o(`chatContextWindowDroppedHistory`),value:String(e.droppedHistoryCount)}),e.truncatedToolResultCount>0&&a.push({label:o(`chatContextWindowTruncatedTools`),value:String(e.truncatedToolResultCount)}),{label:o(`chatContextWindow`),percentLabel:r,ratio:n,tone:i,details:a}}function MO(){let e=DO(e=>e.snapshot.selectedSessionKey),t=kO(e=>e.snapshot.sessionKey),n=kO(e=>e.snapshot.contextWindow);return(0,P.useMemo)(()=>e&&t===e&&n?jO(n):null,[n,t,e])}function NO(e){return e.bootstrapStatus?.ncpAgent.state!==`ready`}function PO(e){return e.activeSystemAction?.message?.trim()||(e.lifecyclePhase===`cold-starting`?o(`chatRuntimeInitializing`):e.lifecyclePhase===`startup-failed`?e.bootstrapStatus?.ncpAgent.error?.trim()||e.bootstrapStatus?.lastError?.trim()||e.lastError?.trim()||o(`chatRuntimeInitializationFailed`):null)}function FO(e){let{message:t,status:n}=e,r=t?.trim();if(!r)return PO(n);let i=n.activeSystemAction?.message?.trim();if(n.phase===`service-transitioning`&&i)return i;let a=j(r);return n.phase===`recovering`&&a?o(`runtimeControlRecoveringHelp`):n.phase===`stalled`&&a?null:r}function IO(){return{off:o(`chatThinkingLevelOff`),minimal:o(`chatThinkingLevelMinimal`),low:o(`chatThinkingLevelLow`),medium:o(`chatThinkingLevelMedium`),high:o(`chatThinkingLevelHigh`),adaptive:o(`chatThinkingLevelAdaptive`),xhigh:o(`chatThinkingLevelXhigh`)}}function LO(e,t){return e.map(e=>({key:e.ref,label:e.name,scopeLabel:t[e.scope],description:e.description,descriptionZh:e.descriptionZh,badgeLabel:t[e.scope]}))}function RO(e){return e.map(e=>({value:e.value,modelLabel:e.modelLabel,providerLabel:e.providerLabel,thinkingCapability:e.thinkingCapability?{supported:e.thinkingCapability.supported,default:e.thinkingCapability.default??null}:null}))}function zO(e){return{skillScopeLabels:(0,P.useMemo)(()=>({builtin:o(`chatSkillScopeBuiltin`),project:o(`chatSkillScopeProject`),workspace:o(`chatSkillScopeWorkspace`)}),[e]),slashTexts:(0,P.useMemo)(()=>({slashSkillSubtitle:o(`chatSlashTypeSkill`),slashSkillSpecLabel:o(`chatSlashSkillSpec`),slashSkillScopeLabel:o(`chatSlashSkillScope`),noSkillDescription:o(`chatSkillsPickerNoDescription`)}),[e]),recentModelsLabel:o(`chatPickerRecentModels`),allModelsLabel:o(`chatPickerAllModels`),recentSkillsLabel:o(`chatPickerRecent`),allSkillsLabel:o(`chatPickerAllSkills`)}}function BO(e,t){let n=(0,P.useMemo)(()=>LO(e.skillRecords,t),[e.skillRecords,t]),r=(0,P.useMemo)(()=>RO(e.modelOptions),[e.modelOptions]);return{skillRecords:n,modelRecords:r,recentModelValues:hO.resolveVisible({availableValues:r.map(e=>e.value),minAvailableCount:5}),recentSkillValues:gO.resolveVisible({availableValues:n.map(e=>e.key),minAvailableCount:0}),recentSkillGroupValues:gO.resolveVisible({availableValues:n.map(e=>e.key),minAvailableCount:4})}}function VO(e){let{attachmentSupported:t,inputBarRef:n,presenter:r}=e,i=(0,P.useCallback)(e=>{if(e===`unsupported-type`){p.error(o(`chatInputAttachmentUnsupported`));return}if(e===`too-large`){p.error(o(`chatInputAttachmentTooLarge`).replace(`{maxMb}`,String(FD/(1024*1024))));return}p.error(o(`chatInputAttachmentReadFailed`))},[]),a=(0,P.useCallback)(async e=>{if(!t||e.length===0)return;let a=await BD(e,{uploadBatch:oe});if(a.attachments.length>0){let e=r.chatInputManager.addAttachments?.(a.attachments)??[];e.length>0&&n.current?.insertFileTokens(e.map(e=>({tokenKey:e.id,label:e.name})))}a.rejected.length>0&&i(a.rejected[0].reason)},[t,n,r.chatInputManager,i]);return{handleFilesAdd:a,handleFileInputChange:(0,P.useCallback)(async e=>{let t=Array.from(e.target.files??[]);e.currentTarget.value=``,await a(t)},[a])}}function HO(e){let{allModelsLabel:t,hasModelOptions:n,isModelOptionsLoading:r,modelRecords:i,presenter:a,recentModelValues:s,recentModelsLabel:c,selectedModel:l,selectedThinkingLevel:u,thinkingSupportedLevels:d,thinkingDefaultLevel:f}=e;return[WD({modelOptions:i,recentModelValues:s,selectedModel:l,isModelOptionsLoading:r,hasModelOptions:n,onValueChange:a.chatInputManager.selectModel,texts:{modelSelectPlaceholder:o(`chatSelectModel`),modelNoOptionsLabel:o(`chatModelNoOptions`),recentModelsLabel:c,allModelsLabel:t}}),GD({supportedLevels:d,selectedThinkingLevel:u,defaultThinkingLevel:f,onValueChange:e=>a.chatInputManager.selectThinkingLevel(e),texts:{thinkingLabels:IO()}})].filter(e=>e!==null)}function UO(e){let{allSkillsLabel:t,presenter:n,recentSkillGroupValues:r,recentSkillValues:i,recentSkillsLabel:a,skillRecords:s,snapshot:c}=e;return tO({skillRecords:s,recentSkillValues:i,groupedRecentSkillValues:r,selectedSkills:c.selectedSkills,isLoading:c.isSkillsLoading,onSelectedKeysChange:n.chatInputManager.selectSkills,texts:{title:o(`chatSkillsPickerTitle`),searchPlaceholder:o(`chatSkillsPickerSearchPlaceholder`),emptyLabel:o(`chatSkillsPickerEmpty`),loadingLabel:o(`sessionsLoading`),manageLabel:o(`chatSkillsPickerManage`),recentSkillsLabel:a,allSkillsLabel:t}})}function WO(){let e=Bn(),{language:t}=ut(),{isMobile:n}=ft(),r=Q(e=>e.snapshot),i=NO(S()),[a,s]=(0,P.useState)(null),c=(0,P.useRef)(null),l=(0,P.useRef)(null),u=zO(t),{skillRecords:d,modelRecords:f,recentModelValues:p,recentSkillValues:m,recentSkillGroupValues:h}=BO(r,u.skillScopeLabels),g=_O(r),_=vO(r),v=yO(r),y=bO(r),b=typeof e.chatInputManager.addAttachments==`function`,x=o(v?`chatModelNoOptions`:n?`chatInputPlaceholderCompact`:`chatInputPlaceholder`),C=(0,P.useMemo)(()=>$D(d,a??``,u.slashTexts,m),[u.slashTexts,m,d,a]),w=MO(),T=f.find(e=>e.value===r.selectedModel),E=T?.thinkingCapability?.supported??[],D=r.stopDisabledReason===`__preparing__`?o(`chatStopPreparing`):r.stopDisabledReason?.trim()||o(`chatStopUnavailable`),{handleFilesAdd:O,handleFileInputChange:ee}=VO({attachmentSupported:b,inputBarRef:c,presenter:e}),k=HO({allModelsLabel:u.allModelsLabel,hasModelOptions:g,isModelOptionsLoading:_,modelRecords:f,presenter:e,recentModelValues:p,recentModelsLabel:u.recentModelsLabel,selectedModel:r.selectedModel,selectedThinkingLevel:r.selectedThinkingLevel,thinkingSupportedLevels:E,thinkingDefaultLevel:T?.thinkingCapability?.default??null}),te=UO({allSkillsLabel:u.allSkillsLabel,presenter:e,recentSkillGroupValues:h,recentSkillValues:m,recentSkillsLabel:u.recentSkillsLabel,skillRecords:d,snapshot:r}),A=r.draft.trim().length>0||r.attachments.length>0||sO(r.composerNodes).length>0;return(0,N.jsxs)(N.Fragment,{children:[(0,N.jsx)(gm,{ref:c,composer:{nodes:r.composerNodes,placeholder:x,disabled:y,onNodesChange:e.chatInputManager.setComposerNodes,...b?{onFilesAdd:O}:{},onSlashQueryChange:s},slashMenu:{isLoading:r.isSkillsLoading,items:C,onSelectItem:t=>{t.value&&e.chatInputManager.rememberSkillSelection(t.value)},texts:{slashLoadingLabel:o(`chatSlashLoading`),slashSectionLabel:o(`chatSlashSectionSkills`),slashEmptyLabel:o(`chatSlashNoResult`),slashHintLabel:o(`chatSlashHint`),slashSkillHintLabel:o(`chatSlashSkillHint`)}},hint:UD({isModelOptionsLoading:_,isModelOptionsEmpty:v,onGoToProviders:e.chatInputManager.goToProviders,texts:{noModelOptionsLabel:o(`chatModelNoOptions`),configureProviderLabel:o(`chatGoConfigureProvider`)}}),toolbar:{selects:k,accessories:[{key:`attach`,label:o(`chatInputAttach`),icon:`paperclip`,iconOnly:!0,disabled:!b||y||r.isSending,...b?{onClick:()=>l.current?.click()}:{tooltip:o(`chatInputAttachComingSoon`)}}],skillPicker:te,actions:{sendError:i?null:r.sendError,isSending:r.isSending,canStopGeneration:r.canStopGeneration,sendDisabled:xO({snapshot:r,hasSendableDraft:A,isRuntimeBlocked:i}),stopDisabled:!r.canStopGeneration,stopHint:D,sendButtonLabel:o(`chatSend`),stopButtonLabel:o(`chatStop`),contextWindow:w,onSend:e.chatInputManager.send,onStop:e.chatInputManager.stop}}}),b?(0,N.jsx)(`input`,{ref:l,type:`file`,multiple:!0,className:`hidden`,onChange:ee}):null]})}var GO=[`cmd`,`command`,`query`,`q`,`path`,`url`,`to`,`channel`,`agentId`,`sessionKey`];function KO(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function qO(e,t=2400){return e.length<=t?e:`${e.slice(0,t)}\n…`}function JO(e,t=120){let n=e.replace(/\s+/g,` `).trim();return n.length<=t?n:t<=1?`…`:`${n.slice(0,t-1)}…`}function YO(e){if(typeof e==`string`)return e;if(typeof e==`number`||typeof e==`boolean`)return String(e);if(e==null)return``;try{return qO(JSON.stringify(e,null,2))}catch{return String(e)}}function XO(e){if(KO(e))return e;if(typeof e!=`string`)return null;let t=e.trim();if(!t.startsWith(`{`)&&!t.startsWith(`[`))return null;try{let e=JSON.parse(t);return KO(e)?e:null}catch{return null}}function ZO(e){let t=XO(e);if(!t){let t=YO(e).trim();return t?JO(t,120):void 0}let n=[];for(let e of GO){let r=t[e];if(typeof r==`string`&&r.trim()?n.push(`${e}: ${r.trim()}`):(typeof r==`number`||typeof r==`boolean`)&&n.push(`${e}: ${String(r)}`),n.length>=2)break}return n.length>0?JO(n.join(` · `),120):JO(YO(t),140)}var QO=`ui_inline_tokens`,$O=`$`;function ek(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function tk(e){if(typeof e!=`string`)return null;let t=e.trim();return t.length>0?t:null}function nk(e){let t=new Set,n=[];for(let r of e){let e=`${r.kind}:${r.key}:${r.rawText}`;t.has(e)||(t.add(e),n.push(r))}return n}function rk(e){let t=[];for(let n of e)n.type!==`token`||n.tokenKind!==`skill`||t.push({kind:`skill`,key:n.tokenKey,label:n.label,rawText:`${$O}${n.tokenKey}`});return nk(t)}function ik(e){let t=e?.[QO];if(!Array.isArray(t))return[];let n=[];for(let e of t){if(!ek(e))continue;let t=tk(e.kind),r=tk(e.key),i=tk(e.rawText);!t||!r||!i||n.push({kind:t,key:r,rawText:i,label:tk(e.label)??r})}return nk(n)}function ak(e,t){if(e.length===0||t.length===0)return e.length===0?[]:[{type:`text`,text:e}];let n=[...t].sort((e,t)=>t.rawText.length-e.rawText.length),r=[],i=0;for(;i<e.length;){let t=null;for(let r of n)if(e.startsWith(r.rawText,i)){t=r;break}if(!t){let t=i+1;for(;t<e.length&&!n.some(n=>e.startsWith(n.rawText,t));)t+=1;r.push({type:`text`,text:e.slice(i,t)}),i=t;continue}r.push({type:`token`,token:t}),i+=t.rawText.length}return r}var ok=/\u200B|\u200C|\u200D|\u2060|\uFEFF/g;function sk(e){let t=e.trim();return t&&t.replace(ok,``).trim()?t:null}function ck(e){return e.replace(ok,``).trim().length>0}function lk(e,t){let n=ak(e,t);if(n.length===0)return null;let r=[],i=!1;for(let e of n){if(e.type===`token`){i=!0,r.push({type:`token`,token:{kind:e.token.kind,key:e.token.key,label:e.token.label,rawText:e.token.rawText}});continue}e.text.length!==0&&(ck(e.text)&&(i=!0),r.push({type:`markdown`,text:e.text}))}return i?r:null}function uk(e,t){let n=lk(e.text,t);if(n&&n.some(e=>e.type===`token`))return{type:`inline-content`,segments:n};let r=sk(e.text);return r?{type:`markdown`,text:r}:null}function dk(e){return sk(e)}function fk(e){return typeof e==`object`&&!!e}function pk(e){if(typeof e!=`string`)return null;let t=e.trim();return t.length>0?t:null}function mk(e){if(typeof e==`number`&&Number.isFinite(e)&&e>=0)return e;if(typeof e!=`string`)return null;let t=e.trim();if(!t)return null;let n=Number(t);return Number.isFinite(n)&&n>=0?n:null}function hk(e){return fk(e)?`command`in e||`workingDir`in e||`exitCode`in e||`stdout`in e||`stderr`in e||`aggregated_output`in e||`combinedOutput`in e:!1}function gk(e,t){if(!fk(e))return null;let n=fk(e.asset)?e.asset:Array.isArray(e.assets)&&e.assets.length>0&&fk(e.assets[0])?e.assets[0]:null;if(!n)return null;let r=pk(n.url),i=pk(n.mimeType)??`application/octet-stream`,a=mk(n.sizeBytes);return r?{type:`file`,file:{label:pk(n.name)??(i.startsWith(`image/`)?t.imageAttachmentLabel:t.fileAttachmentLabel),mimeType:i,dataUrl:r,...a==null?{}:{sizeBytes:a},isImage:i.startsWith(`image/`)}}:null}function _k(e,t){return{kind:e.kind,toolName:e.name,...`agentId`in e&&e.agentId?{agentId:e.agentId}:{},summary:e.detail,inputLabel:t.toolInputLabel,input:`input`in e&&typeof e.input==`string`?e.input:void 0,output:e.text,outputData:e.outputData,hasResult:!!e.hasResult,statusTone:e.statusTone,statusLabel:e.statusLabel,titleLabel:e.kind===`call`?t.toolCallLabel:t.toolResultLabel,outputLabel:t.toolOutputLabel,emptyLabel:t.toolNoOutputLabel,...`action`in e&&e.action?{action:e.action}:{},...`fileOperation`in e&&e.fileOperation?{fileOperation:e.fileOperation}:{}}}function vk(e){let t=typeof e.status==`string`?e.status.trim().toLowerCase():``,n=typeof e.error==`string`&&e.error.trim().length>0;return e.cancelled===!0||t===`cancelled`?{kind:`result`,hasResult:!0,statusTone:`cancelled`,statusLabel:e.texts.toolStatusCancelledLabel}:n||t===`error`?{kind:`result`,hasResult:!0,statusTone:`error`,statusLabel:e.texts.toolStatusFailedLabel}:t===`result`||e.result!=null?{kind:`result`,hasResult:!0,statusTone:`success`,statusLabel:e.texts.toolStatusCompletedLabel}:{kind:`call`,hasResult:!1,statusTone:`running`,statusLabel:e.texts.toolStatusRunningLabel}}function yk(e){if(typeof e!=`string`)return e;let t=e.trim();if(!t.startsWith(`{`)&&!t.startsWith(`[`))return e;try{return JSON.parse(t)}catch{return e}}function bk(e,t){return YO(t??yk(e)).trim()||void 0}function xk(e){return typeof e==`object`&&!!e}function Sk(e){if(typeof e!=`string`)return e;let t=e.trim();if(!t.startsWith(`{`)&&!t.startsWith(`[`))return e;try{return JSON.parse(t)}catch{return e}}function Ck(e){if(typeof e!=`string`)return null;let t=e.trim();return t.length>0?t:null}function wk(e){let t=Sk(e);return xk(t)?Ck(t.agentId):null}function Tk(e){return wk(e.parsedArgs)??wk(e.args)??wk(e.result)}var Ek=12e3,Dk=/^@@ -(\d+)(?:,\d+)? \+(\d+)(?:,\d+)? @@/;function Ok(e){let t=e.replace(/\r\n/g,`
|
|
52
52
|
`).replace(/\r/g,`
|
|
53
53
|
`);return t===``?[]:t.split(`
|
|
54
|
-
`)}function
|
|
55
|
-
`;case`r`:return`\r`;case`t`:return` `;default:return e}}function
|
|
54
|
+
`)}function kk(e){return typeof e==`number`?e+1:void 0}function Ak(e){return{kind:e.kind,text:e.text,...typeof e.oldLineNumber==`number`?{oldLineNumber:e.oldLineNumber}:{},...typeof e.newLineNumber==`number`?{newLineNumber:e.newLineNumber}:{}}}function jk(e){let t=Dk.exec(e);return t?{oldLineNumber:Number(t[1]),newLineNumber:Number(t[2])}:null}function Mk(e){return Ok(e.text).map((t,n)=>e.kind===`add`?Ak({kind:`add`,text:t,newLineNumber:e.newStartLine+n}):Ak({kind:`context`,text:t,oldLineNumber:e.oldStartLine+n,newLineNumber:e.newStartLine+n}))}function Nk(e){let t=e.oldStartLine,n=e.newStartLine;return[...e.beforeLines.map(e=>{let n=Ak({kind:`remove`,text:e,oldLineNumber:t});return t=kk(t),n}),...e.afterLines.map(e=>{let t=Ak({kind:`add`,text:e,newLineNumber:n});return n=kk(n),t})]}function Pk(e){let t=Array.from({length:e.beforeLines.length+1},()=>Array.from({length:e.afterLines.length+1},()=>0));for(let n=e.beforeLines.length-1;n>=0;--n)for(let r=e.afterLines.length-1;r>=0;--r)t[n][r]=e.beforeLines[n]===e.afterLines[r]?(t[n+1][r+1]??0)+1:Math.max(t[n+1][r]??0,t[n][r+1]??0);return t}function Fk(e){for(let t=e.beforeIndex;t<e.beforeLines.length;t+=1)e.lines.push(Ak({kind:`remove`,text:e.beforeLines[t]??``,oldLineNumber:e.oldLineNumber})),e.oldLineNumber=kk(e.oldLineNumber);for(let t=e.afterIndex;t<e.afterLines.length;t+=1)e.lines.push(Ak({kind:`add`,text:e.afterLines[t]??``,newLineNumber:e.newLineNumber})),e.newLineNumber=kk(e.newLineNumber)}function Ik(e){let t=Ok(e.beforeText),n=Ok(e.afterText);if(t.length*n.length>Ek)return Nk({beforeLines:t,afterLines:n,oldStartLine:e.oldStartLine,newStartLine:e.newStartLine});let r=Pk({beforeLines:t,afterLines:n}),i=[],a=0,o=0,s=e.oldStartLine,c=e.newStartLine;for(;a<t.length&&o<n.length;){if(t[a]===n[o]){i.push(Ak({kind:`context`,text:t[a]??``,oldLineNumber:s,newLineNumber:c})),a+=1,o+=1,s=kk(s),c=kk(c);continue}if((r[a+1][o]??0)>=(r[a][o+1]??0)){i.push(Ak({kind:`remove`,text:t[a]??``,oldLineNumber:s})),a+=1,s=kk(s);continue}i.push(Ak({kind:`add`,text:n[o]??``,newLineNumber:c})),o+=1,c=kk(c)}return Fk({lines:i,beforeLines:t,afterLines:n,beforeIndex:a,afterIndex:o,oldLineNumber:s,newLineNumber:c}),i}var Lk=120;function Rk(e){let t=e.lines.filter(e=>e.kind===`add`).length,n=e.lines.filter(e=>e.kind===`remove`).length,r=[],i=e.operation?.trim().toLowerCase()??``;return i&&i!==`update`&&r.push(i),t>0&&r.push(`+${t}`),n>0&&r.push(`-${n}`),r.length>0?r.join(` · `):void 0}function zk(e){let t=e.operation?.trim().toLowerCase()??``;return{oldStartLine:typeof e.oldStartLine==`number`?e.oldStartLine:(t===`delete`||t===`remove`)&&e.beforeText!=null?1:void 0,newStartLine:typeof e.newStartLine==`number`?e.newStartLine:(t===`write`||t===`add`)&&e.afterText!=null?1:void 0}}function Bk(e){return e.length<=Lk?{lines:e,truncated:!1}:{lines:e.slice(0,Lk),truncated:!0}}function Vk(e){let t=Bk(e.lines);return{path:e.path,display:`diff`,caption:Rk({operation:e.operation,lines:e.lines}),lines:t.lines,...t.truncated?{fullLines:e.lines}:{},truncated:t.truncated}}function Hk(e){let t=e.text.trim();if(!t)return null;let n=e.operation?.trim().toLowerCase()===`write`?`add`:`context`,r=typeof e.oldStartLine==`number`?e.oldStartLine:1,i=typeof e.newStartLine==`number`?e.newStartLine:1,a=Mk({text:t,kind:n,oldStartLine:r,newStartLine:i});return{path:e.path,display:`preview`,caption:Rk({operation:e.operation,lines:a}),lines:a,rawText:t,oldStartLine:r,newStartLine:i}}function Uk(e){let{oldStartLine:t,newStartLine:n}=zk(e),r=Ik({beforeText:e.beforeText??``,afterText:e.afterText??``,oldStartLine:t,newStartLine:n}),i=Bk(r);return i.lines.length===0?null:{path:e.path,display:`diff`,caption:Rk({operation:e.operation,lines:r}),lines:i.lines,...i.truncated?{fullLines:r}:{},...e.beforeText==null?{}:{beforeText:e.beforeText},...e.afterText==null?{}:{afterText:e.afterText},...typeof t==`number`?{oldStartLine:t}:{},...typeof n==`number`?{newStartLine:n}:{},truncated:i.truncated}}function Wk(e){return e.line.startsWith(`*** Update File: `)?(e.flushCurrent(),e.setCurrent(e.line.slice(17).trim(),`update`),!0):e.line.startsWith(`*** Add File: `)?(e.flushCurrent(),e.setCurrent(e.line.slice(14).trim(),`add`),!0):e.line.startsWith(`*** Delete File: `)?(e.flushCurrent(),e.setCurrent(e.line.slice(17).trim(),`delete`),!0):!1}function Gk(e){let{currentLines:t,line:n}=e;return n.startsWith(`+`)?(t.push(Ak({kind:`add`,text:n.slice(1),newLineNumber:e.newLineNumber})),{oldLineNumber:e.oldLineNumber,newLineNumber:kk(e.newLineNumber)}):n.startsWith(`-`)?(t.push(Ak({kind:`remove`,text:n.slice(1),oldLineNumber:e.oldLineNumber})),{oldLineNumber:kk(e.oldLineNumber),newLineNumber:e.newLineNumber}):n.startsWith(` `)?(t.push(Ak({kind:`context`,text:n.slice(1),oldLineNumber:e.oldLineNumber,newLineNumber:e.newLineNumber})),{oldLineNumber:kk(e.oldLineNumber),newLineNumber:kk(e.newLineNumber)}):{oldLineNumber:e.oldLineNumber,newLineNumber:e.newLineNumber}}function Kk(e){let t=[],n=null,r=null,i=[],a,o,s=()=>{if(!n){i=[],r=null,a=void 0,o=void 0;return}t.push(Vk({path:n,operation:r,lines:i})),n=null,r=null,i=[],a=void 0,o=void 0};for(let t of Ok(e)){if(Wk({line:t,flushCurrent:s,setCurrent:(e,t)=>{n=e,r=t}})||t.startsWith(`*** Move to: `)||t.startsWith(`*** Begin Patch`)||t.startsWith(`*** End Patch`))continue;if(t.startsWith(`@@`)){let e=jk(t);a=e?.oldLineNumber,o=e?.newLineNumber;continue}if(!n)continue;let e=Gk({currentLines:i,line:t,oldLineNumber:a,newLineNumber:o});a=e.oldLineNumber,o=e.newLineNumber}return s(),t}function qk(e){let t=[],n=null,r=[],i,a,o=()=>{if(!n){r=[],i=void 0,a=void 0;return}t.push(Vk({path:n,operation:`update`,lines:r})),n=null,r=[],i=void 0,a=void 0};for(let t of Ok(e)){if(t.startsWith(`+++ `)){o(),n=t.slice(4).trim().replace(/^b\//,``).replace(/^a\//,``);continue}if(t.startsWith(`--- `))continue;if(t.startsWith(`@@`)){let e=jk(t);i=e?.oldLineNumber,a=e?.newLineNumber;continue}if(!n)continue;let e=Gk({currentLines:r,line:t,oldLineNumber:i,newLineNumber:a});i=e.oldLineNumber,a=e.newLineNumber}return o(),t}function Jk(e){return e.includes(`*** Begin Patch`)?Kk(e):e.includes(`--- `)&&e.includes(`+++ `)?qk(e):[]}function Yk(e){switch(e){case`"`:case`\\`:case`/`:return e;case`b`:return`\b`;case`f`:return`\f`;case`n`:return`
|
|
55
|
+
`;case`r`:return`\r`;case`t`:return` `;default:return e}}function Xk(e,t){let n=`"${t}"`,r=e.indexOf(n);if(r<0)return null;let i=e.indexOf(`:`,r+n.length);if(i<0)return null;let a=i+1;for(;a<e.length&&/\s/.test(e[a]??``);)a+=1;return e[a]===`"`?a+1:null}function Zk(e,t,n=1/0){let r=``,i=!1;for(let a=t;a<e.length;a+=1){let t=e[a];if(t==null)break;if(i){r+=Yk(t),i=!1;continue}if(t===`\\`){i=!0;continue}if(t===`"`)return{value:r,truncated:!1};if(r+=t,r.length>=n)return{value:r,truncated:!0}}return r.length>0?{value:r,truncated:!1}:null}function Qk(e,t,n=1/0){for(let r of t){let t=Xk(e,r);if(t!=null)return Zk(e,t,n)}return null}function $k(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function $(e){if(typeof e!=`string`)return null;let t=e.trim();return t.length>0?t:null}function eA(e){return typeof e==`string`&&e.trim()?e.trim():null}function tA(e){return typeof e==`number`&&Number.isInteger(e)&&e>0?e:typeof e==`string`&&/^\d+$/.test(e.trim())?Number(e.trim()):null}function nA(e){if($k(e))return e;if(typeof e!=`string`)return null;let t=e.trim();if(!t.startsWith(`{`))return null;try{let e=JSON.parse(t);return $k(e)?e:null}catch{return null}}function rA(e){if($k(e))return e;if(typeof e!=`string`)return null;let t=e.trim();if(!t.startsWith(`{`))return null;let n=Qk(t,[`path`,`filePath`,`file_path`,`targetPath`,`target_path`,`filename`,`name`])?.value??null,r=Qk(t,[`content`,`text`,`afterText`,`after_text`])?.value??null,i=Qk(t,[`oldText`,`beforeText`,`before_text`])?.value??null,a=Qk(t,[`newText`,`afterText`,`after_text`])?.value??null,o=Qk(t,[`patch`,`diff`,`unifiedDiff`,`unified_diff`])?.value??null,s={};return n&&(s.path=n),r&&(s.content=r),i&&(s.oldText=i),a&&(s.newText=a),o&&(s.patch=o),Object.keys(s).length>0?s:null}function iA(e){return eA(e.path)??eA(e.filePath)??eA(e.file_path)??eA(e.targetPath)??eA(e.target_path)??eA(e.filename)??eA(e.name)}function aA(e){return $(e.operation)??$(e.op)??$(e.action)??$(e.kind)??$(e.type)??$(e.status)}function oA(e,t){for(let n of t){let t=tA(e[n]);if(t!==null)return t}return null}function sA(e){return oA(e,[`oldStartLine`,`old_start_line`,`startOldLine`,`start_old_line`,`oldLineStart`,`old_line_start`,`oldLineNumber`,`old_line_number`,`lineStart`,`line_start`,`startLine`,`start_line`,`lineNumber`,`line_number`])}function cA(e){return oA(e,[`newStartLine`,`new_start_line`,`startNewLine`,`start_new_line`,`newLineStart`,`new_line_start`,`newLineNumber`,`new_line_number`,`lineStart`,`line_start`,`startLine`,`start_line`,`lineNumber`,`line_number`])}function lA(e){return $(e.patch)??$(e.diff)??$(e.unifiedDiff)??$(e.unified_diff)}function uA(e){return $(e.beforeText)??$(e.before_text)??$(e.oldText)??$(e.old_text)??$(e.oldContent)??$(e.old_content)??$(e.before)??$(e.previous)}function dA(e){return $(e.afterText)??$(e.after_text)??$(e.newText)??$(e.new_text)??$(e.newContent)??$(e.new_content)??$(e.content)??$(e.text)??$(e.after)??$(e.updated)}var fA=new Set([`file_change`,`read_file`,`write_file`,`edit_file`,`apply_patch`]);function pA(e){let t=e.map((e,t)=>({key:`${e.path}-${t+1}`,path:e.path,display:e.display,...e.caption?{caption:e.caption}:{},lines:e.lines,...e.fullLines?{fullLines:e.fullLines}:{},...e.rawText?{rawText:e.rawText}:{},...e.beforeText?{beforeText:e.beforeText}:{},...e.afterText?{afterText:e.afterText}:{},...typeof e.oldStartLine==`number`?{oldStartLine:e.oldStartLine}:{},...typeof e.newStartLine==`number`?{newStartLine:e.newStartLine}:{},...e.truncated?{truncated:!0}:{}})).filter(e=>e.lines.length>0||!!e.rawText);if(t.length===0)return null;let n=t.map(e=>e.path);return{summary:n.length===1?n[0]:`${n.length} files · ${n.slice(0,2).join(` · `)}${n.length>2?` …`:``}`,fileOperation:{blocks:t}}}function mA(e,t){let n=iA(e)??t,r=aA(e),i=sA(e),a=cA(e),o=lA(e);if(o){let e=Jk(o);if(e.length>0)return e[0]??null}let s=uA(e),c=dA(e);if(s!=null||c!=null)return Uk({path:n,beforeText:s,afterText:c,operation:r,oldStartLine:i,newStartLine:a});let l=$(e.preview);return l?Hk({path:n,text:l,operation:r,oldStartLine:i,newStartLine:a}):null}function hA(e){if(!Array.isArray(e))return[];let t=[];return e.forEach((e,n)=>{if(typeof e==`string`){let n=Jk(e);n.length>0&&t.push(...n);return}if(!$k(e))return;let r=mA(e,iA(e)??`file-${n+1}`);if(r){t.push(r);return}let i=Array.isArray(e.changes)?hA(e.changes):[];i.length>0&&t.push(...i)}),t}function gA(e){let t=nA(e.result)??nA(e.parsedArgs)??nA(e.args);return t?pA(hA(t.changes)):null}function _A(e){let t=nA(e.parsedArgs)??nA(e.args)??rA(e.args),n=t&&iA(t),r=$(e.result);return!n||!r?null:pA([Hk({path:n,text:r,operation:`read`})].filter(e=>!!e))}function vA(e){if(e.status===`partial-call`&&typeof e.args==`string`){let t=Qk(e.args,[`path`,`filePath`,`file_path`,`targetPath`,`target_path`,`filename`,`name`]),n=Qk(e.args,[`content`,`text`,`afterText`,`after_text`]);if(t?.value&&n?.value){let e=Hk({path:t.value,text:n.value,operation:`write`});if(e)return pA([e])}}let t=nA(e.parsedArgs)??nA(e.args)??rA(e.args);if(!t)return null;let n=iA(t),r=$(t.content);return!n||!r?null:pA([Hk({path:n,text:r,operation:`write`})].filter(e=>!!e))}function yA(e){let t=nA(e.result),n=nA(e.parsedArgs)??nA(e.args)??rA(e.args);if(!t&&!n)return null;let r=(t?iA(t):null)??(n?iA(n):null),i=(t?uA(t):null)??(n?uA(n):null),a=(t?dA(t):null)??(n?dA(n):null),o=(t?sA(t):null)??(n?sA(n):null),s=(t?cA(t):null)??(n?cA(n):null);return!r||i==null&&a==null?null:pA([Uk({path:r,beforeText:i,afterText:a,operation:`edit`,oldStartLine:o,newStartLine:s})].filter(e=>!!e))}function bA(e){let t=nA(e.parsedArgs),n=nA(e.args)??rA(e.args),r=$(e.args)??(t?$(t.patch):null)??(n?$(n.patch):null);return r?pA(Jk(r)):null}function xA(e){return fA.has(e.toolName)?e.toolName===`file_change`?gA(e):e.toolName===`read_file`?_A(e):e.toolName===`write_file`?vA(e):e.toolName===`edit_file`?yA(e):e.toolName===`apply_patch`?bA(e):null:null}function SA(e){return typeof e==`object`&&!!e}function CA(e){if(typeof e!=`string`)return null;let t=e.trim();return t.length>0?t:null}function wA(e){return!SA(e)||e.kind!==`nextclaw.session_request`?null:e}function TA(e){return!SA(e)||e.kind!==`nextclaw.session`?null:e}function EA(e){if(typeof e!=`string`)return e;let t=e.trim();if(!t.startsWith(`{`)&&!t.startsWith(`[`))return e;try{return JSON.parse(t)}catch{return e}}function DA(e){return YO(EA(e)).trim()||void 0}function OA(e,t){return[CA(e.title)?`title: ${e.title?.trim()}`:null,CA(e.sessionId)?`session: ${e.sessionId?.trim()}`:null,CA(e.task)?`task: ${e.task?.trim()}`:null].filter(e=>!!e).join(` · `)||ZO(t)}function kA(e,t){return[CA(e.title)?`title: ${e.title?.trim()}`:null,CA(e.sessionId)?`session: ${e.sessionId?.trim()}`:null].filter(e=>!!e).join(` · `)||ZO(t)}function AA(e){let t=CA(e.requestId),n=CA(e.sessionId),r=CA(e.title),i=CA(e.task),a=CA(e.status),o=CA(e.notify),s=CA(e.lifecycle),c=CA(e.parentSessionId),l=CA(e.spawnedByRequestId),u=e.message===void 0?``:YO(e.message).trim(),d=e.finalResponseText===void 0?``:YO(e.finalResponseText).trim(),f=e.error===void 0?``:YO(e.error).trim(),p=[t?`Request ID: ${t}`:null,n?`Session ID: ${n}`:null,typeof e.isChildSession==`boolean`?`Target: ${e.isChildSession?`child`:`session`}`:null,a?`Status: ${a}`:null,o?`Notify: ${o}`:null,s?`Lifecycle: ${s}`:null,c?`Parent Session ID: ${c}`:null,l?`Spawned By Request ID: ${l}`:null,r?`Title: ${r}`:null,i?`Task:\n${i}`:null,d?`Final Response:\n${d}`:f?`Error:\n${f}`:u?`Status:\n${u}`:null].filter(e=>!!e);return p.length>0?p.join(`
|
|
56
56
|
|
|
57
|
-
`):void 0}function
|
|
57
|
+
`):void 0}function jA(e){let t=CA(e.sessionId),n=CA(e.title),r=CA(e.sessionType),i=CA(e.lifecycle),a=CA(e.parentSessionId),o=CA(e.createdAt),s=[t?`Session ID: ${t}`:null,typeof e.isChildSession==`boolean`?`Target: ${e.isChildSession?`child`:`session`}`:null,n?`Title: ${n}`:null,r?`Session Type: ${r}`:null,i?`Lifecycle: ${i}`:null,a?`Parent Session ID: ${a}`:null,o?`Created At: ${o}`:null].filter(e=>!!e);return s.length>0?s.join(`
|
|
58
58
|
|
|
59
|
-
`):void 0}function cj(e){let{invocation:t,texts:n}=e,{toolName:r,toolCallId:i,args:a,result:o}=t;if(r!==`spawn`&&r!==`sessions_request`&&r!==`sessions_spawn`)return null;let s=ej(o);if(s){let e=$A(s.status)?.toLowerCase(),t=ij(s,a),o=oj(s),c=$A(s.sessionId),l=tA({args:a,result:s}),u=c?{kind:`open-session`,sessionId:c,sessionKind:s.isChildSession===!0?`child`:`session`,...l?{agentId:l}:{},...$A(s.title)?{label:s.title.trim()}:{},...$A(s.parentSessionId)?{parentSessionId:s.parentSessionId.trim()}:{}}:void 0;return e===`failed`?{kind:`result`,name:r,detail:t,input:rj(a),text:o,callId:i||void 0,hasResult:!!o,statusTone:`error`,statusLabel:n.toolStatusFailedLabel,...l?{agentId:l}:{},...u?{action:u}:{}}:e===`completed`?{kind:`result`,name:r,detail:t,input:rj(a),text:o,callId:i||void 0,hasResult:!!o,statusTone:`success`,statusLabel:n.toolStatusCompletedLabel,...l?{agentId:l}:{},...u?{action:u}:{}}:{kind:`result`,name:r,detail:t,input:rj(a),text:o,callId:i||void 0,hasResult:!!o,statusTone:`running`,statusLabel:n.toolStatusRunningLabel,...l?{agentId:l}:{},...u?{action:u}:{}}}let c=tj(o);if(!c)return null;let l=aj(c,a),u=sj(c),d=$A(c.sessionId),f=tA({args:a,result:c}),p=d?{kind:`open-session`,sessionId:d,sessionKind:c.isChildSession===!0?`child`:`session`,...f?{agentId:f}:{},...$A(c.title)?{label:c.title.trim()}:{},...$A(c.parentSessionId)?{parentSessionId:c.parentSessionId.trim()}:{}}:void 0;return{kind:`result`,name:r,detail:l,input:rj(a),text:u,callId:i||void 0,hasResult:!!u,statusTone:`success`,statusLabel:n.toolStatusCompletedLabel,...f?{agentId:f}:{},...p?{action:p}:{}}}function lj(e,t){let n=Vk(e.reasoning);return n?{type:`reasoning`,text:n,label:t.reasoningLabel}:null}function uj(e,t){let n=e.mimeType.startsWith(`image/`),r=Wk(e.sizeBytes);return{type:`file`,file:{label:typeof e.name==`string`&&e.name.trim()?e.name.trim():n?t.imageAttachmentLabel:t.fileAttachmentLabel,mimeType:e.mimeType,dataUrl:typeof e.url==`string`&&e.url.trim().length>0?e.url.trim():`data:${e.mimeType};base64,${e.data}`,...r==null?{}:{sizeBytes:r},isImage:n}}}function dj(e,t){let n=e.toolInvocation,r=Kk(n.result,t);if(r)return r;let i=cj({invocation:n,texts:{toolStatusRunningLabel:t.toolStatusRunningLabel,toolStatusCompletedLabel:t.toolStatusCompletedLabel,toolStatusFailedLabel:t.toolStatusFailedLabel}});if(i)return{type:`tool-card`,card:qk(i,t)};let a=Jk({status:n.status,error:n.error,cancelled:n.cancelled,result:n.result,texts:t}),o=ZA({toolName:n.toolName,status:n.status,toolCallId:n.toolCallId,args:n.args,parsedArgs:n.parsedArgs,result:n.result}),s=o?.summary??Dk(n.parsedArgs??n.args),c=o?void 0:Xk(n.args,n.parsedArgs),l=typeof n.error==`string`&&n.error.trim()?n.error.trim():n.result==null?``:Tk(n.result).trim(),u=!n.error&&Gk(n.result),d=(!o?.fileOperation||!!n.error)&&!u,f=tA(n);return{type:`tool-card`,card:qk({kind:a.kind,name:n.toolName,...f?{agentId:f}:{},detail:s,...c?{input:c}:{},text:d&&l?l:void 0,outputData:n.result,callId:n.toolCallId||void 0,hasResult:a.hasResult,statusTone:a.statusTone,statusLabel:a.statusLabel,...o?.fileOperation?{fileOperation:o.fileOperation}:{}},t)}}function fj(e,t){return{type:`unknown`,label:t.unknownPartLabel,rawType:typeof e.type==`string`?e.type:`unknown`,text:Tk(e)}}function pj(e){return e.type===`text`&&typeof e.text==`string`}function mj(e){return e.type===`reasoning`&&typeof e.reasoning==`string`}function hj(e){return e.type===`file`&&typeof e.mimeType==`string`&&typeof e.data==`string`}function gj(e){return e.type!==`tool-invocation`||typeof e.toolInvocation!=`object`||e.toolInvocation===null||Array.isArray(e.toolInvocation)?!1:`toolName`in e.toolInvocation&&typeof e.toolInvocation.toolName==`string`}function _j(e){return pj(e.part)?Bk(e.part,e.inlineTokens):mj(e.part)?lj(e.part,e.texts):hj(e.part)?uj(e.part,e.texts):gj(e.part)?dj(e.part,e.texts):fj(e.part,e.texts)}function vj(e){let t=e.meta?.timestamp;return t&&Number.isFinite(Date.parse(t))?t:new Date().toISOString()}function yj(e,t){return e===`user`?t.user:e===`assistant`?t.assistant:e===`tool`?t.tool:e===`system`?t.system:t.fallback}function bj(e){return e===`user`||e===`assistant`||e===`tool`||e===`system`?e:`message`}function xj(e,t){return{id:e.id,role:bj(e.role),roleLabel:yj(e.role,t.texts.roleLabels),timestampLabel:t.formatTimestamp(vj(e)),status:e.meta?.status,parts:e.parts.map(n=>_j({part:n,inlineTokens:e.meta?.inlineTokens??[],texts:t.texts})).filter(e=>e!==null)}}function Sj(e){if(typeof e!=`string`)return null;let t=e.trim();return t.length>0?t:null}function Cj(e){if(typeof e!=`number`||!Number.isFinite(e))return null;let t=Math.trunc(e);return t>=0?t:null}function wj(e){return e===!0}function Tj(e){let t=e;if(!t||typeof t!=`object`||Array.isArray(t))return null;let n=t,r=Cj(n.usedContextTokens),i=Cj(n.totalContextTokens),a=Cj(n.prunedUsedContextTokens),o=Sj(n.updatedAt);if(r===null||i===null||a===null||!o)return null;let s=Cj(n.compactedUsedContextTokens);return{usedContextTokens:r,totalContextTokens:i,prunedUsedContextTokens:a,availableContextTokens:Cj(n.availableContextTokens)??Math.max(0,i-r),droppedHistoryCount:Cj(n.droppedHistoryCount)??0,truncatedToolResultCount:Cj(n.truncatedToolResultCount)??0,truncatedSystemPrompt:wj(n.truncatedSystemPrompt),truncatedUserMessage:wj(n.truncatedUserMessage),compacted:wj(n.compacted),...Sj(n.checkpointId)?{checkpointId:Sj(n.checkpointId)??void 0}:{},compactedMessageCount:Cj(n.compactedMessageCount)??0,...s===null?{}:{compactedUsedContextTokens:s},updatedAt:o}}function Ej(e){let{metadata:t}=e;if(!t||t.nextclaw_timeline_kind!==`context_compaction`)return null;let n=t.checkpoint&&typeof t.checkpoint==`object`&&!Array.isArray(t.checkpoint)?t.checkpoint:null;if(!n)return null;let r=Sj(n.id),i=n.status===`compressing`?`compressing`:n.status===`compressed`?`compressed`:null,a=Sj(n.summary),o=Cj(n.coveredMessageCount),s=Cj(n.coveredSessionMessageCount),c=Cj(n.originalEstimatedTokens),l=Cj(n.projectedEstimatedTokens),u=Sj(n.createdAt),d=Sj(n.updatedAt);return!r||!i||!a||o===null||s===null||c===null||l===null||!u||!d?null:{id:r,status:i,summary:a,coveredMessageCount:o,coveredSessionMessageCount:s,originalEstimatedTokens:c,projectedEstimatedTokens:l,createdAt:u,updatedAt:d}}function Dj(){return y({queryKey:[`agents`],queryFn:D,staleTime:3e4})}function Oj(){let e=x();return h({mutationFn:({data:e})=>te(e),onSuccess:()=>{e.invalidateQueries({queryKey:[`agents`]}),e.invalidateQueries({queryKey:[`config`]}),p.success(o(`configSavedApplied`))},onError:e=>{p.error(o(`configSaveFailed`)+`: `+e.message)}})}function kj(){let e=x();return h({mutationFn:({agentId:e,data:t})=>C(e,t),onSuccess:()=>{e.invalidateQueries({queryKey:[`agents`]}),e.invalidateQueries({queryKey:[`config`]}),p.success(o(`configSavedApplied`))},onError:e=>{p.error(o(`configSaveFailed`)+`: `+e.message)}})}function Aj(){let e=x();return h({mutationFn:({agentId:e})=>ne(e),onSuccess:()=>{e.invalidateQueries({queryKey:[`agents`]}),e.invalidateQueries({queryKey:[`config`]}),p.success(o(`configSavedApplied`))},onError:e=>{p.error(o(`configSaveFailed`)+`: `+e.message)}})}function jj(e,t){return new Map([...t,...e].filter(e=>typeof e.id==`string`&&e.id.trim().length>0).map(e=>[e.id,e]))}function Mj(e){let t=e?.trim()??``,n=ak(e=>e.snapshot.availableAgents??[]),r=Dj(),i=(0,P.useMemo)(()=>jj(n,r.data?.agents??[]),[r.data?.agents,n]);return(0,P.useMemo)(()=>{if(!t)return null;let e=i.get(t)??null;return{agentId:t,profile:e,displayName:e?.displayName?.trim()||t,avatarUrl:e?.avatarUrl?.trim()||null}},[i,t])}function Nj({agentId:e,className:t}){let n=Mj(e);return n?(0,N.jsx)(jn,{agentId:n.agentId,displayName:n.displayName,avatarUrl:n.avatarUrl,className:t}):null}var Pj=new WeakMap;function Fj(e){return{roleLabels:{user:o(`chatRoleUser`),assistant:o(`chatRoleAssistant`),tool:o(`chatRoleTool`),system:o(`chatRoleSystem`),fallback:o(`chatRoleMessage`)},reasoningLabel:o(`chatReasoning`),toolCallLabel:o(`chatToolCall`),toolResultLabel:o(`chatToolResult`),toolInputLabel:o(`chatToolInput`),toolNoOutputLabel:o(`chatToolNoOutput`),toolOutputLabel:o(`chatToolOutput`),toolStatusPreparingLabel:o(`chatToolStatusPreparing`),toolStatusRunningLabel:o(`chatToolStatusRunning`),toolStatusCompletedLabel:o(`chatToolStatusCompleted`),toolStatusFailedLabel:o(`chatToolStatusFailed`),toolStatusCancelledLabel:o(`chatToolStatusCancelled`),imageAttachmentLabel:o(`chatImageAttachment`),fileAttachmentLabel:o(`chatFileAttachment`),unknownPartLabel:o(`chatUnknownPart`)}}function Ij(e){return{copyCodeLabel:o(`chatCodeCopy`),copiedCodeLabel:o(`chatCodeCopied`),copyMessageLabel:o(`chatMessageCopy`),copiedMessageLabel:o(`chatMessageCopied`),typingLabel:o(`chatTyping`),attachmentOpenLabel:o(`chatAttachmentOpen`),attachmentAttachedLabel:o(`chatAttachmentAttached`),attachmentCategoryLabels:{archive:o(`chatAttachmentCategoryArchive`),audio:o(`chatAttachmentCategoryAudio`),code:o(`chatAttachmentCategoryCode`),data:o(`chatAttachmentCategoryData`),document:o(`chatAttachmentCategoryDocument`),generic:o(`chatAttachmentCategoryGeneric`),image:o(`chatAttachmentCategoryImage`),pdf:o(`chatAttachmentCategoryPdf`),sheet:o(`chatAttachmentCategorySheet`),video:o(`chatAttachmentCategoryVideo`)}}}function Lj({checkpoint:e}){return(0,N.jsxs)(`div`,{className:`my-4 flex items-center gap-3 text-[11px] text-gray-500`,title:[`${o(`chatContextCompactionCoveredMessages`)}: ${e.coveredSessionMessageCount}`,`${o(`chatContextCompactionOriginalTokens`)}: ${e.originalEstimatedTokens}`,`${o(`chatContextCompactionProjectedTokens`)}: ${e.projectedEstimatedTokens}`].join(`
|
|
60
|
-
`),children:[(0,N.jsx)(`div`,{className:`h-px flex-1 bg-gray-200`}),(0,N.jsxs)(`div`,{className:`inline-flex items-center gap-2 rounded-full border border-gray-200 bg-gray-50 px-3 py-1`,children:[e.status===`compressing`?(0,N.jsx)(`span`,{className:`h-1.5 w-1.5 rounded-full bg-gray-400 animate-pulse`}):(0,N.jsx)(`span`,{className:`h-1.5 w-1.5 rounded-full bg-gray-300`}),(0,N.jsx)(`span`,{children:e.status===`compressing`?o(`chatContextCompactionCompressing`):o(`chatContextCompactionCompressed`)})]}),(0,N.jsx)(`div`,{className:`h-px flex-1 bg-gray-200`})]})}function Rj(e){let{normalRawMessages:t,rawMessageId:n,rawMessages:r}=e,i=r.findIndex(e=>e.id===n);return i<0?t.length-1:r.slice(0,i).filter(e=>!Ej(e)).length-1}function zj(e){let t=e.rawMessages.filter(e=>!Ej(e)),n=e.rawMessages.map(e=>({rawMessageId:e.id,checkpoint:Ej(e)})).filter(e=>!!e.checkpoint).map(n=>({key:n.rawMessageId,checkpoint:n.checkpoint,boundaryIndex:Rj({rawMessages:e.rawMessages,normalRawMessages:t,rawMessageId:n.rawMessageId})})).sort((e,t)=>e.boundaryIndex-t.boundaryIndex),r=[],i=[],a=0,o=e=>{i.length!==0&&(r.push({kind:`messages`,key:e,messages:i}),i=[])};for(t.forEach((t,s)=>{let c=e.messages[s];for(c&&i.push(c);a<n.length&&n[a]?.boundaryIndex<=s;){let e=n[a];o(`messages-before-${e.key}`),r.push({kind:`compaction`,key:e.key,checkpoint:e.checkpoint}),a+=1}});a<n.length;){let e=n[a];o(`messages-before-${e.key}`),r.push({kind:`compaction`,key:e.key,checkpoint:e.checkpoint}),a+=1}return o(`messages-final`),r.length===0&&r.push({kind:`messages`,key:`messages-empty`,messages:[]}),r}function Bj({messages:e,isSending:t,className:n,onToolAction:r,onFileOpen:i}){let{language:a}=ut(),o=(0,P.useMemo)(()=>Fj(a),[a]),s=(0,P.useMemo)(()=>e.flatMap(e=>{if(Ej(e))return[];let t=Pj.get(e);if(t&&t.language===a)return[t.viewModel];let n=JO(e),r=xj({id:n.id,role:n.role,meta:{timestamp:n.meta?.timestamp,status:n.meta?.status,inlineTokens:Pk(e.metadata)},parts:n.parts},{formatTimestamp:e=>c(e,a),texts:o});return Pj.set(e,{language:a,viewModel:r}),[r]}),[a,e,o]),l=(0,P.useMemo)(()=>s.some(e=>e.role===`assistant`&&(e.status===`streaming`||e.status===`pending`)),[s]),u=(0,P.useMemo)(()=>Ij(a),[a]),d=(0,P.useMemo)(()=>zj({rawMessages:e,messages:s}),[s,e]);return(0,N.jsx)(`div`,{className:n,children:d.map((e,n)=>e.kind===`compaction`?(0,N.jsx)(Lj,{checkpoint:e.checkpoint},e.key):(0,N.jsx)(tD,{messages:e.messages,isSending:n===d.length-1?t:!1,hasAssistantDraft:l,texts:u,onToolAction:r,onFileOpen:i,renderToolAgent:e=>(0,N.jsx)(Nj,{agentId:e,className:`h-4 w-4 shrink-0`})},e.key))})}function Vj(){let e=x();return async t=>{let{sessionKey:n,patch:r,successMessage:i}=t;try{A(e,await ie(n,r)),await e.invalidateQueries({queryKey:[`ncp-session-skills`,n]}),p.success(i??o(`configSavedApplied`))}catch(e){throw p.error(o(`configSaveFailed`)+`: `+(e instanceof Error?e.message:String(e))),e}}}function Hj(){let e=Vj();return async t=>{let{persistToServer:n,projectRoot:r,sessionKey:i}=t,a=o(r?`chatSessionProjectUpdated`:`chatSessionProjectCleared`);if(!n){Q.getState().setSnapshot({pendingProjectRoot:r,pendingProjectRootSessionKey:i}),p.success(a);return}await e({sessionKey:i,patch:{projectRoot:r},successMessage:a})}}function Uj({icon:e,label:t,onClick:n,disabled:r=!1,destructive:i=!1}){return(0,N.jsxs)(`button`,{type:`button`,className:d(`flex w-full items-center gap-2 rounded-xl px-3 py-2 text-left text-sm transition-colors disabled:cursor-not-allowed disabled:opacity-50`,i?`text-destructive hover:bg-destructive/10`:`text-gray-700 hover:bg-gray-100`),onClick:n,disabled:r,children:[(0,N.jsx)(e,{className:`h-4 w-4 shrink-0`}),(0,N.jsx)(`span`,{children:t})]})}function Wj(e){return y({queryKey:[`server-path-browse`,e.path??null,e.includeFiles??!1],queryFn:()=>re({path:e.path,includeFiles:e.includeFiles}),enabled:e.enabled??!0,staleTime:0})}var Gj=P.forwardRef(({className:e,children:t,...n},r)=>(0,N.jsx)(`div`,{ref:r,className:d(`overflow-auto`,e),...n,children:t}));Gj.displayName=`ScrollArea`;function Kj({open:e,currentPath:t,isSaving:n,onOpenChange:r,onConfirm:i,title:a,description:s,pathLabel:c,pathPlaceholder:l,confirmLabel:u,hint:d}){let[p,m]=(0,P.useState)(``),[h,_]=(0,P.useState)(null),[v,y]=(0,P.useState)(``);(0,P.useEffect)(()=>{if(!e)return;let n=t?.trim()||null;m(n??``),_(n),y(``)},[t,e]);let b=Wj({path:h,enabled:e});(0,P.useEffect)(()=>{!e||!b.data||p.trim().length===0&&m(b.data.currentPath)},[b.data,p,e]);let x=p.trim(),S=x.length===0||n,C=(0,P.useMemo)(()=>b.error?b.error instanceof Error?b.error.message:String(b.error):null,[b.error]),w=v.trim().toLowerCase(),T=(0,P.useMemo)(()=>{let e=b.data?.entries??[];return w.length===0?e:e.filter(e=>{let t=e.name.toLowerCase(),n=e.path.toLowerCase();return t.includes(w)||n.includes(w)})},[b.data?.entries,w]),E=e=>{_(e),y(``),e&&m(e)};return(0,N.jsx)(pe,{open:e,onOpenChange:e=>{n||r(e)},children:(0,N.jsxs)(ue,{className:`max-h-[85vh] overflow-hidden sm:h-[42rem] sm:max-w-2xl sm:grid-rows-[auto_minmax(0,1fr)]`,children:[(0,N.jsxs)(ce,{children:[(0,N.jsx)(de,{children:a}),s?(0,N.jsx)(fe,{children:s}):null]}),(0,N.jsxs)(`form`,{className:`flex min-h-0 flex-col gap-4`,onSubmit:e=>{e.preventDefault(),!S&&i(x)},children:[(0,N.jsxs)(`div`,{className:`space-y-2`,children:[(0,N.jsx)(f,{htmlFor:`server-path-picker-input`,children:c}),(0,N.jsxs)(`div`,{className:`flex gap-2`,children:[(0,N.jsx)(O,{id:`server-path-picker-input`,value:p,onChange:e=>m(e.target.value),placeholder:l,autoFocus:!0,disabled:n}),(0,N.jsx)(g,{type:`button`,variant:`outline`,onClick:()=>E(x||null),disabled:n,children:o(`openPath`)})]})]}),(0,N.jsxs)(`div`,{className:`flex min-h-0 flex-1 flex-col overflow-hidden rounded-2xl border border-gray-200 bg-gray-50/70`,children:[(0,N.jsxs)(`div`,{className:`flex flex-wrap items-center gap-2 border-b border-gray-200 px-3 py-2`,children:[(0,N.jsxs)(g,{type:`button`,variant:`ghost`,size:`sm`,onClick:()=>E(b.data?.homePath??null),disabled:n||b.isLoading,children:[(0,N.jsx)(tn,{className:`mr-1 h-4 w-4`}),o(`homeDirectory`)]}),(0,N.jsxs)(g,{type:`button`,variant:`ghost`,size:`sm`,onClick:()=>E(b.data?.parentPath??null),disabled:!b.data?.parentPath||n||b.isLoading,children:[(0,N.jsx)(Qt,{className:`mr-1 h-4 w-4`}),o(`parentDirectory`)]}),(0,N.jsxs)(g,{type:`button`,variant:`ghost`,size:`sm`,onClick:()=>{b.refetch()},disabled:n||b.isLoading,children:[(0,N.jsx)(it,{className:`mr-1 h-4 w-4`}),o(`chatRefresh`)]})]}),(0,N.jsxs)(`div`,{className:`border-b border-gray-200 px-3 py-2`,children:[(0,N.jsx)(`div`,{className:`mb-2 text-xs font-medium text-gray-500`,children:o(`currentDirectory`)}),(0,N.jsx)(`div`,{className:`flex flex-wrap items-center gap-1 text-xs text-gray-600`,children:b.data?.breadcrumbs.map((e,t)=>(0,N.jsxs)(`div`,{className:`flex items-center gap-1`,children:[(0,N.jsx)(`button`,{type:`button`,className:`rounded px-1.5 py-0.5 hover:bg-gray-200`,onClick:()=>E(e.path),disabled:n,children:e.label}),t<b.data.breadcrumbs.length-1?(0,N.jsx)(It,{className:`h-3 w-3 text-gray-400`}):null]},e.path))})]}),(0,N.jsx)(`div`,{className:`border-b border-gray-200 px-3 py-2`,children:(0,N.jsxs)(`div`,{className:`relative`,children:[(0,N.jsx)(Oe,{className:`pointer-events-none absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-gray-400`}),(0,N.jsx)(O,{value:v,onChange:e=>y(e.target.value),placeholder:o(`pathPickerSearchPlaceholder`),disabled:n||b.isLoading,className:`pl-9`})]})}),(0,N.jsx)(Gj,{className:`min-h-0 flex-1 px-2 py-2`,children:b.isLoading?(0,N.jsx)(`div`,{className:`px-2 py-6 text-sm text-gray-500`,children:o(`loading`)}):C?(0,N.jsxs)(`div`,{className:`px-2 py-4 text-sm text-destructive`,children:[o(`pathBrowseFailed`),`: `,C]}):b.data&&T.length>0?(0,N.jsx)(`div`,{className:`space-y-1`,children:T.map(e=>(0,N.jsxs)(`button`,{type:`button`,className:`flex w-full items-center gap-2 rounded-xl px-3 py-2 text-left text-sm text-gray-700 transition-colors hover:bg-white`,onClick:()=>E(e.path),disabled:n,children:[(0,N.jsx)($e,{className:`h-4 w-4 shrink-0 text-emerald-600`}),(0,N.jsx)(`span`,{className:`truncate`,children:e.name})]},e.path))}):b.data&&b.data.entries.length>0?(0,N.jsx)(`div`,{className:`px-2 py-6 text-sm text-gray-500`,children:o(`pathPickerSearchEmpty`)}):(0,N.jsx)(`div`,{className:`px-2 py-6 text-sm text-gray-500`,children:o(`emptyDirectory`)})})]}),d?(0,N.jsx)(`p`,{className:`text-xs leading-relaxed text-gray-500`,children:d}):null,(0,N.jsxs)(le,{children:[(0,N.jsx)(g,{type:`button`,variant:`outline`,onClick:()=>r(!1),disabled:n,children:o(`cancel`)}),(0,N.jsx)(g,{type:`submit`,disabled:S,children:n?o(`saving`):u})]})]})]})})}function qj({open:e,currentProjectRoot:t,isSaving:n,onOpenChange:r,onSave:i}){return(0,N.jsx)(Kj,{open:e,currentPath:t,isSaving:n,onOpenChange:r,onConfirm:i,title:o(`chatSessionProjectDialogTitle`),description:o(`chatSessionProjectDialogDescription`),pathLabel:o(`chatSessionProjectPathLabel`),pathPlaceholder:o(`chatSessionProjectPathPlaceholder`),confirmLabel:o(`chatSessionSetProject`),hint:o(`chatSessionProjectUpdateHint`)})}function Jj({sessionKey:e,canDeleteSession:t,isDeletePending:n,projectRoot:r,childSessionCount:i=0,onOpenChildSessions:a,onDeleteSession:s}){let c=Hj(),[l,u]=(0,P.useState)(!1),[d,f]=(0,P.useState)(!1),[p,m]=(0,P.useState)(!1),h=n||p,_=async n=>{let r=t;m(!0);try{await c({sessionKey:e,projectRoot:n,persistToServer:r}),f(!1),u(!1)}finally{m(!1)}};return(0,N.jsxs)(N.Fragment,{children:[i>0&&a?(0,N.jsx)(g,{type:`button`,variant:`ghost`,size:`icon`,className:`rounded-lg shrink-0 text-gray-400 hover:text-gray-700`,"aria-label":o(`chatSessionOpenChildSessions`),title:o(`chatSessionOpenChildSessions`),onClick:a,disabled:h,children:(0,N.jsx)(en,{className:`h-4 w-4`})}):null,(0,N.jsxs)(xt,{open:l,onOpenChange:u,children:[(0,N.jsx)(yt,{asChild:!0,children:(0,N.jsx)(g,{variant:`ghost`,size:`icon`,className:`rounded-lg shrink-0 text-gray-400 hover:text-gray-700`,"aria-label":o(`chatSessionMoreActions`),disabled:h,children:(0,N.jsx)(zt,{className:`h-4 w-4`})})}),(0,N.jsx)(_t,{align:`end`,className:`w-56 p-2`,children:(0,N.jsxs)(`div`,{className:`space-y-1`,children:[(0,N.jsx)(Uj,{icon:Xt,label:o(`chatSessionSetProject`),onClick:()=>{u(!1),f(!0)},disabled:h}),(0,N.jsx)(Uj,{icon:st,label:o(`chatDeleteSession`),onClick:()=>{u(!1),s()},disabled:!t||h,destructive:!0})]})})]}),(0,N.jsx)(qj,{open:d,currentProjectRoot:r,isSaving:p,onOpenChange:f,onSave:_})]})}function Yj({sessionKey:e,projectName:t,projectRoot:n,persistToServer:r}){let i=Hj(),[a,s]=(0,P.useState)(!1),[c,l]=(0,P.useState)(!1),[u,d]=(0,P.useState)(!1),f=async t=>{d(!0);try{await i({sessionKey:e,projectRoot:t,persistToServer:r}),l(!1),s(!1)}finally{d(!1)}};return(0,N.jsxs)(N.Fragment,{children:[(0,N.jsxs)(xt,{open:a,onOpenChange:s,children:[(0,N.jsx)(yt,{asChild:!0,children:(0,N.jsx)(`button`,{type:`button`,title:n??void 0,className:`min-w-0 max-w-[320px] shrink rounded-full border border-gray-200 bg-gray-100/90 px-2 py-0.5 text-[11px] font-medium text-gray-600 transition-colors hover:border-gray-300 hover:bg-gray-100 disabled:cursor-not-allowed disabled:opacity-60`,"aria-label":o(`chatSessionSetProject`),disabled:u,children:(0,N.jsxs)(`span`,{className:`flex min-w-0 items-center gap-1.5`,children:[(0,N.jsx)(Xt,{className:`h-3.5 w-3.5 shrink-0`}),(0,N.jsx)(`span`,{className:`truncate`,children:t}),(0,N.jsx)(je,{className:`h-3 w-3 shrink-0 opacity-70`})]})})}),(0,N.jsxs)(_t,{align:`start`,className:`w-72 p-2`,children:[(0,N.jsxs)(`div`,{className:`px-3 pb-2 pt-1`,children:[(0,N.jsx)(`div`,{className:`text-[11px] font-medium uppercase tracking-wider text-gray-500`,children:t}),n?(0,N.jsx)(`div`,{className:`mt-1 break-all text-xs text-gray-500`,children:n}):null]}),(0,N.jsxs)(`div`,{className:`space-y-1`,children:[(0,N.jsx)(Uj,{icon:on,label:o(`chatSessionSetProject`),onClick:()=>{s(!1),l(!0)},disabled:u}),(0,N.jsx)(Uj,{icon:$t,label:o(`chatSessionClearProject`),onClick:()=>{f(null)},disabled:u})]})]})]}),(0,N.jsx)(qj,{open:c,currentProjectRoot:n,isSaving:u,onOpenChange:l,onSave:f})]})}function Xj({parentSessionLabel:e,onGoToParentSession:t}){if(!e)return null;let n=e.trim();return(0,N.jsx)(`div`,{className:`border-b border-gray-200/60 bg-white/75 px-4 py-2 backdrop-blur-sm sm:px-5`,children:(0,N.jsxs)(`button`,{type:`button`,onClick:t,className:`inline-flex items-center gap-2 text-xs font-medium text-gray-600 transition-colors hover:text-gray-900`,children:[(0,N.jsx)(De,{className:`h-3.5 w-3.5`}),(0,N.jsxs)(`span`,{children:[o(`chatBackToParent`),n?` · ${n}`:``]})]})})}function Zj({snapshot:e,childSessionCount:t,layoutMode:n,normalizedAgentId:r,sessionHeaderTitle:i,shouldShowHeaderAgentAvatar:a,shouldShowSessionHeader:s,onBackToList:c,onOpenChildSessions:l,onDeleteSession:u}){let f=n===`mobile`;return(0,N.jsxs)(`div`,{className:d(`border-b border-gray-200/60 bg-white/80 backdrop-blur-sm flex items-center justify-between shrink-0 overflow-hidden transition-all duration-200`,f?`px-3 sm:px-3`:`px-4 sm:px-5`,s?`opacity-100`:`h-0 py-0 opacity-0 border-b-0`,s&&(f?`pb-2 pt-2`:`py-3`)),style:f&&s?{paddingTop:`calc(env(safe-area-inset-top, 0px) + 0.5rem)`}:void 0,children:[(0,N.jsxs)(`div`,{className:`min-w-0 flex-1 flex items-center gap-2`,children:[f&&c?(0,N.jsx)(`button`,{type:`button`,onClick:c,className:`inline-flex h-8 w-8 shrink-0 items-center justify-center rounded-full text-gray-600 transition-colors hover:bg-gray-100 hover:text-gray-900`,"aria-label":o(`chat`),children:(0,N.jsx)(De,{className:`h-4 w-4`})}):null,a?(0,N.jsx)(`div`,{className:`inline-flex shrink-0 items-center`,children:(0,N.jsx)(jn,{agentId:r,displayName:e.agentDisplayName,avatarUrl:e.agentAvatarUrl,className:`h-5 w-5`})}):null,(0,N.jsx)(`span`,{className:`text-sm font-medium text-gray-700 truncate`,children:i}),e.sessionTypeLabel?(0,N.jsxs)(`span`,{className:`inline-flex shrink-0 items-center gap-1.5 rounded-full border border-gray-200 bg-gray-100 px-2 py-0.5 text-[11px] font-medium text-gray-600`,children:[e.sessionTypeIcon?.src?(0,N.jsx)(`span`,{className:`inline-flex h-[1.125rem] w-[1.125rem] items-center justify-center`,children:(0,N.jsx)(wn,{icon:{kind:`runtime-image`,src:e.sessionTypeIcon.src,alt:e.sessionTypeIcon.alt??null,name:e.sessionTypeLabel}})}):null,e.sessionTypeLabel]}):null,e.sessionProjectName?(0,N.jsx)(Yj,{sessionKey:e.sessionKey??`draft`,projectName:e.sessionProjectName,projectRoot:e.sessionProjectRoot,persistToServer:e.canDeleteSession}):null]}),e.sessionKey?(0,N.jsx)(Jj,{sessionKey:e.sessionKey,canDeleteSession:e.canDeleteSession,isDeletePending:e.isDeletePending,projectRoot:e.sessionProjectRoot,childSessionCount:t,onOpenChildSessions:l,onDeleteSession:u}):null]})}var Qj=`native`;function $j(e){return typeof e==`string`?e.trim().toLowerCase()||`native`:Qj}function eM(e,t=Qj){return $j(e?.runtime?.trim()||e?.engine?.trim()||t)}function tM(e,t){return e===`native`?o(`chatSessionTypeNative`):t?.trim()||e.trim().split(/[-_]+/g).filter(Boolean).map(e=>e.charAt(0).toUpperCase()+e.slice(1)).join(` `)||e}function nM(e){let t=new Map;for(let n of e){let e=$j(n.value);t.set(e,{value:e,label:n.label?.trim()||tM(e),icon:n.icon??null,ready:n.ready??!0,reason:n.reason??null,reasonMessage:n.reasonMessage??null,supportedModels:n.supportedModels,recommendedModel:n.recommendedModel??null,cta:n.cta??null})}return t.has(`native`)||t.set(Qj,{value:Qj,label:tM(Qj),icon:null,ready:!0,reason:null,reasonMessage:null,supportedModels:void 0,recommendedModel:null,cta:null}),Array.from(t.values()).sort((e,t)=>e.value===`native`?-1:t.value===`native`?1:e.value.localeCompare(t.value))}function rM(e){let{selectedSession:t,pendingSessionType:n,setPendingSessionType:r,sessionTypesData:i}=e,a=(0,P.useMemo)(()=>nM(i?.options??[]),[i?.options]),s=(0,P.useMemo)(()=>{let e=[...a],n=$j(t?.sessionType);return e.some(e=>e.value===n)||e.push({value:n,label:tM(n),icon:null,ready:!0,reason:null,reasonMessage:null,supportedModels:void 0,recommendedModel:null,cta:null}),e.sort((e,t)=>e.value===`native`?-1:t.value===`native`?1:e.value.localeCompare(t.value))},[a,t?.sessionType]),c=(0,P.useMemo)(()=>$j(i?.defaultType??`native`),[i?.defaultType]),l=(0,P.useRef)(null),u=(0,P.useMemo)(()=>$j(t?.sessionType??n??c),[c,n,t?.sessionType]),d=(0,P.useMemo)(()=>s.find(e=>e.value===u)??null,[u,s]);(0,P.useEffect)(()=>{if(t)return;let e=typeof n==`string`?n.trim():``,i=$j(n);(e.length===0||l.current===i||l.current===null&&i===`native`)&&(l.current=c,i!==c&&r(c))},[c,n,t,r]);let f=!t||!!t.sessionTypeMutable,p=(0,P.useMemo)(()=>new Set(a.map(e=>e.value)),[a]);return{sessionTypeOptions:s,selectedSessionTypeOption:d,defaultSessionType:c,selectedSessionType:u,canEditSessionType:f,sessionTypeUnavailable:(0,P.useMemo)(()=>t&&!p.has($j(t.sessionType))?!0:d?.ready===!1,[p,t,d?.ready]),sessionTypeUnavailableMessage:(0,P.useMemo)(()=>t&&!p.has($j(t.sessionType))?`${tM(u)} ${o(`chatSessionTypeUnavailableSuffix`)}`:d?.ready===!1?d.reasonMessage?.trim()||`${d.label} setup required`:null,[p,t,u,d])}}var iM=[{key:`hero`,alignmentClassName:`justify-start`,bubbleClassName:`max-w-[78%] h-32 rounded-[30px]`},{key:`follow-up`,alignmentClassName:`justify-start`,bubbleClassName:`max-w-[62%] h-24 rounded-[28px]`},{key:`reply`,alignmentClassName:`justify-end`,bubbleClassName:`max-w-[70%] h-24 rounded-[28px]`},{key:`detail`,alignmentClassName:`justify-start`,bubbleClassName:`max-w-[88%] h-36 rounded-[30px]`}];function aM(){return(0,N.jsxs)(`section`,{"data-testid":`chat-conversation-skeleton`,className:`flex-1 min-h-0 flex flex-col overflow-hidden bg-gradient-to-b from-gray-50/60 to-white`,children:[(0,N.jsx)(`div`,{className:`flex-1 min-h-0 overflow-y-auto custom-scrollbar`,children:(0,N.jsx)(`div`,{className:`mx-auto flex min-h-full w-full max-w-[min(1120px,100%)] flex-col px-6 py-5`,children:(0,N.jsxs)(`div`,{className:`flex flex-1 flex-col gap-8`,children:[(0,N.jsxs)(`div`,{className:`space-y-6`,children:[(0,N.jsx)(Mt,{className:`h-6 w-52 rounded-lg bg-gray-200/90`}),(0,N.jsx)(`div`,{className:`space-y-5`,children:iM.map(e=>(0,N.jsx)(`div`,{className:d(`flex w-full`,e.alignmentClassName),children:(0,N.jsx)(Mt,{"data-testid":`chat-conversation-skeleton-bubble`,className:d(`w-full bg-gray-200/80`,e.bubbleClassName)})},e.key))})]}),(0,N.jsxs)(`div`,{className:`mt-auto grid gap-4 pb-2 sm:grid-cols-[minmax(0,1fr)_minmax(180px,240px)] sm:items-end`,children:[(0,N.jsxs)(`div`,{className:`space-y-3`,children:[(0,N.jsx)(Mt,{className:`h-4 w-40 rounded-full bg-gray-200/70`}),(0,N.jsx)(Mt,{className:`h-[112px] w-full rounded-[30px] bg-gray-200/70`})]}),(0,N.jsx)(`div`,{className:`hidden justify-end sm:flex`,children:(0,N.jsx)(Mt,{className:`h-10 w-36 rounded-full bg-gray-200/75`})})]})]})})}),(0,N.jsx)(`div`,{className:`border-t border-gray-200/80 bg-white p-4`,children:(0,N.jsx)(`div`,{className:`mx-auto w-full max-w-[min(1120px,100%)]`,children:(0,N.jsxs)(`div`,{className:`overflow-hidden rounded-2xl border border-gray-200 bg-white shadow-card`,children:[(0,N.jsx)(`div`,{className:`px-4 py-2.5`,children:(0,N.jsx)(Mt,{className:`h-[84px] w-full rounded-[28px] bg-gray-200/80`})}),(0,N.jsxs)(`div`,{className:`flex items-center justify-between gap-3 px-3 pb-3`,children:[(0,N.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,N.jsx)(Mt,{className:`h-8 w-20 rounded-full bg-gray-200/75`}),(0,N.jsx)(Mt,{className:`h-8 w-28 rounded-full bg-gray-200/75`}),(0,N.jsx)(Mt,{className:`hidden h-8 w-24 rounded-full bg-gray-200/70 sm:block`})]}),(0,N.jsx)(Mt,{className:`h-8 w-8 rounded-full bg-gray-200/85`})]})]})})})]})}function oM({shouldShowProviderHint:e,sessionTypeUnavailable:t,sessionTypeUnavailableMessage:n,onGoToProviders:r}){return(0,N.jsxs)(N.Fragment,{children:[e?(0,N.jsxs)(`div`,{className:`px-4 py-2.5 border-b border-amber-200/70 bg-amber-50/70 flex items-center justify-between gap-3 shrink-0 sm:px-5`,children:[(0,N.jsx)(`span`,{className:`text-xs text-amber-800`,children:o(`chatModelNoOptions`)}),(0,N.jsx)(`button`,{type:`button`,onClick:r,className:`text-xs font-semibold text-amber-900 underline-offset-2 hover:underline`,children:o(`chatGoConfigureProvider`)})]}):null,t&&n?.trim()?(0,N.jsx)(`div`,{className:`px-4 py-2.5 border-b border-amber-200/70 bg-amber-50/70 shrink-0 sm:px-5`,children:(0,N.jsx)(`span`,{className:`text-xs text-amber-800`,children:n})}):null]})}function sM({snapshot:e,availableAgents:t,hideEmptyHint:n,showWelcome:r,threadRef:i,onScroll:a,onCreateSession:s,onSelectAgent:c,onToolAction:l,onFileOpen:u}){return(0,N.jsx)(`div`,{ref:i,onScroll:a,className:`flex-1 min-h-0 overflow-y-auto custom-scrollbar`,children:r?(0,N.jsx)(Ln,{onCreateSession:s,agents:t,selectedAgentId:e.agentId??`main`,onSelectAgent:c}):n?null:e.messages.length===0?(0,N.jsx)(`div`,{className:`px-4 py-4 text-sm text-gray-500 sm:px-5 sm:py-5`,children:o(`chatNoMessages`)}):(0,N.jsx)(`div`,{className:`mx-auto w-full max-w-[min(1120px,100%)] px-4 py-4 sm:px-6 sm:py-5`,children:(0,N.jsx)(Bj,{messages:e.messages,isSending:e.isSending&&e.isAwaitingAssistantOutput,onToolAction:l,onFileOpen:u},e.sessionKey??`draft`)})})}function cM(e,t,n){return e.workspacePanelParentKey===e.sessionKey?t.length>0||n.length>0:!1}function lM({layoutMode:e=`desktop`,onBackToList:t}){let n=Bn(),r=Q(e=>e.snapshot.defaultSessionType),i=ak(e=>e.snapshot),a=(0,P.useRef)(null),s=i.threadRef??a,c=i.childSessionTabs.filter(e=>e.parentSessionKey===i.sessionKey),l=i.workspaceFileTabs.filter(e=>e.parentSessionKey===i.sessionKey),u=cM(i,c,l),d=!!(i.sessionKey||i.sessionTypeLabel),f=i.sessionDisplayName||(i.canDeleteSession&&i.sessionKey?i.sessionKey:null)||o(`chatSidebarNewTask`),p=i.agentId?.trim()??``,m=p.length>0&&p.toLowerCase()!==`main`,h=!i.canDeleteSession&&i.messages.length===0&&!i.isSending,g=i.modelOptions.length>0,_=i.isProviderStateResolved&&!g,v=i.isHistoryLoading&&i.messages.length===0&&!i.isSending&&!i.isAwaitingAssistantOutput,y=i.availableAgents??[],b=e=>y.find(t=>t.id===e)??null,x=()=>{let t=eM(b(i.agentId??`main`),r),a=n.chatSessionListManager.createSession(t);e===`mobile`&&n.chatUiManager.goToSession(a)},S=e=>{n.chatSessionListManager.setSelectedAgentId(e),n.chatInputManager.setPendingSessionType(eM(b(e),r))},C=e=>{n.chatThreadManager.openFilePreview(e)},w=()=>{i.sessionKey&&n.chatThreadManager.openChildSessionPanel({parentSessionKey:i.sessionKey,activeChildSessionKey:c[0]?.sessionKey??null})},{onScroll:T}=qT({scrollRef:s,resetKey:i.sessionKey,isLoading:i.isHistoryLoading,hasContent:i.messages.length>0,contentVersion:i.messages[i.messages.length-1]??null});return i.isProviderStateResolved?(0,N.jsxs)(`section`,{className:`flex-1 min-h-0 flex overflow-hidden bg-gradient-to-b from-gray-50/60 to-white`,children:[(0,N.jsxs)(`div`,{className:`flex min-h-0 flex-1 flex-col overflow-hidden`,children:[(0,N.jsx)(Xj,{parentSessionLabel:i.parentSessionKey?i.parentSessionLabel??null:null,onGoToParentSession:n.chatThreadManager.goToParentSession}),(0,N.jsx)(Zj,{snapshot:i,childSessionCount:c.length,layoutMode:e,normalizedAgentId:p,sessionHeaderTitle:f,shouldShowHeaderAgentAvatar:m,shouldShowSessionHeader:d,onBackToList:t,onOpenChildSessions:w,onDeleteSession:n.chatThreadManager.deleteSession}),(0,N.jsx)(oM,{shouldShowProviderHint:_,sessionTypeUnavailable:i.sessionTypeUnavailable,sessionTypeUnavailableMessage:i.sessionTypeUnavailableMessage??null,onGoToProviders:n.chatThreadManager.goToProviders}),(0,N.jsx)(sM,{snapshot:i,availableAgents:y,hideEmptyHint:v,showWelcome:h,threadRef:s,onScroll:T,onCreateSession:x,onSelectAgent:S,onToolAction:n.chatThreadManager.openSessionFromToolAction,onFileOpen:C}),(0,N.jsx)(bk,{})]}),u?(0,N.jsx)(PN,{childSessionTabs:c,activeChildSessionKey:i.activeChildSessionKey??null,workspaceFileTabs:l,activeWorkspaceFileKey:i.activeWorkspaceFileKey??null,sessionProjectRoot:i.sessionProjectRoot??null,displayMode:e===`mobile`?`overlay`:`docked`,onSelectSession:n.chatThreadManager.selectChildSessionDetail,onSelectFile:n.chatThreadManager.selectWorkspaceFile,onCloseFile:n.chatThreadManager.closeWorkspaceFile,onClose:n.chatThreadManager.closeWorkspacePanel,onBackToParent:n.chatThreadManager.goToParentSession,onToolAction:n.chatThreadManager.openSessionFromToolAction,onFileOpen:C}):null]}):(0,N.jsx)(aM,{})}var uM={connected:{dotClass:`bg-emerald-500`},disconnected:{dotClass:`h-2.5 w-2.5 rounded-full border border-gray-400 bg-transparent`},connecting:{dotClass:`text-amber-600`}};function dM({status:e,className:t}){let n=uM[e],r=o(e===`connected`?`connected`:e===`disconnected`?`disconnected`:`connecting`);return(0,N.jsx)(kt,{delayDuration:250,children:(0,N.jsxs)(jt,{children:[(0,N.jsx)(Tt,{asChild:!0,children:(0,N.jsx)(`span`,{role:`status`,"aria-label":r,className:d(`inline-flex h-5 w-5 items-center justify-center`,t),children:e===`connecting`?(0,N.jsx)(nt,{className:d(`h-3 w-3 animate-spin`,n.dotClass)}):(0,N.jsx)(`span`,{className:d(e===`connected`?`h-2 w-2 rounded-full`:``,n.dotClass)})})}),(0,N.jsx)(Dt,{side:`bottom`,className:`text-xs`,children:r})]})})}function fM(){let e=Vj();return async t=>{await e({sessionKey:t.sessionKey,patch:{label:t.label},successMessage:o(`configSavedApplied`)})}}function pM(){let e=fM(),[t,n]=(0,P.useState)(null),[r,i]=(0,P.useState)(``),[a,o]=(0,P.useState)(null),s=e=>{n(e.key),i(e.label?.trim()??``)},c=()=>{n(null),i(``),o(null)};return{editingSessionKey:t,draftLabel:r,savingSessionKey:a,setDraftLabel:i,startEditingSessionLabel:s,cancelEditingSessionLabel:c,saveSessionLabel:async t=>{let n=r.trim();if(n===(t.label?.trim()??``)){c();return}o(t.key);try{await e({sessionKey:t.key,label:n||null}),c()}catch{o(null)}}}}function mM(e){let t=e.label?.trim();if(t)return t;let n=e.key.split(`:`);return n[n.length-1]||e.key}function hM(e){return e.trim().toLowerCase()}function gM(e,t){let n=hM(t);return n?[e.key,mM(e),e.projectRoot??``,e.projectName??``].map(hM).some(e=>e.includes(n)):!0}function _M(e,t){return e.filter(e=>gM(e,t))}function vM(e){return e.isChildSession?e.isPromotedChildSession===!0:!0}function yM(e={}){let t=rk(e=>e.snapshot.query),n=pt({limit:e.limit??200}),r=(0,P.useMemo)(()=>{let e=n.data?.sessions??[],r=_M(XO(e).filter(vM),t),i=new Map(e.map(e=>[e.sessionId,e]));return r.map(e=>({session:e,runStatus:i.get(e.key)?.status===`running`?`running`:void 0}))},[t,n.data?.sessions]);return{isLoading:n.isLoading,items:r}}function bM(e){let{item:t,selectedSessionKey:n,optimisticReadAtBySessionKey:r,agentsById:i,childSessionsByParentKey:a,editingSessionKey:o,draftLabel:s,savingSessionKey:c,sessionTitle:l,onSelectSession:u,onOpenChildSessions:d,onStartEditingSessionLabel:f,onDraftLabelChange:p,onSaveSessionLabel:m,onCancelEditingSessionLabel:h}=e,{session:g,runStatus:_}=t,v=Q(e=>e.snapshot),y=n===g.key,b=r[g.key],x=b&&g.readAt?b.localeCompare(g.readAt)>0?b:g.readAt:b??g.readAt,S=a.get(g.key)??[];return(0,N.jsx)(Fn,{session:g,active:y,showUnreadDot:$O({active:y,lastMessageAt:g.lastMessageAt,readAt:x,runStatus:_}),runStatus:_,context:bn(g,v.sessionTypeOptions),title:l(g),agentId:g.agentId??null,agentLabel:g.agentId?i.get(g.agentId)?.displayName??g.agentId:null,agentAvatarUrl:g.agentId?i.get(g.agentId)?.avatarUrl??null:null,childSessionCount:S.length,isEditing:o===g.key,draftLabel:s,isSaving:c===g.key,onSelect:()=>u(g.key),onOpenChildSessions:()=>d(g.key,S[0]?.session.key??null),onStartEditing:()=>f(g),onDraftLabelChange:p,onSave:()=>m(g),onCancel:h})}function xM(e){let t=e.sessionTypeOptions.find(t=>t.value===e.defaultSessionType);return[...t?[t]:[],...e.nonDefaultSessionTypeOptions]}function SM(e){let{query:t,defaultSessionType:n,nonDefaultSessionTypeOptions:r,isCreateMenuOpen:i,onCreateMenuOpenChange:a,onCreateSession:s,onQueryChange:c}=e;return(0,N.jsxs)(N.Fragment,{children:[(0,N.jsx)(`div`,{className:`px-4 pb-3`,children:(0,N.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,N.jsxs)(g,{variant:`primary`,className:d(`min-w-0 rounded-xl`,r.length>0?`flex-1 rounded-r-md`:`w-full`),onClick:()=>{a(!1),s(n)},children:[(0,N.jsx)(rt,{className:`mr-2 h-4 w-4`}),o(`chatSidebarNewTask`)]}),r.length>0?(0,N.jsxs)(xt,{open:i,onOpenChange:a,children:[(0,N.jsx)(yt,{asChild:!0,children:(0,N.jsx)(g,{variant:`primary`,size:`icon`,className:`h-9 w-10 shrink-0 rounded-xl rounded-l-md`,"aria-label":o(`chatSessionTypeLabel`),children:(0,N.jsx)(je,{className:`h-4 w-4`})})}),(0,N.jsxs)(_t,{align:`end`,className:`w-56 rounded-2xl border border-gray-200/80 bg-white p-1.5 shadow-[0_24px_60px_-28px_rgba(15,23,42,0.38)]`,children:[(0,N.jsx)(`div`,{className:`px-3 pb-1 pt-2 text-[10px] font-semibold uppercase tracking-[0.18em] text-gray-400`,children:o(`chatSessionTypeLabel`)}),(0,N.jsx)(`div`,{className:`space-y-1`,children:r.map(e=>(0,N.jsx)(En,{option:e,onSelect:()=>{s(e.value),a(!1)}},e.value))})]})]}):null]})}),(0,N.jsx)(`div`,{className:`px-4 pb-3`,children:(0,N.jsxs)(`div`,{className:`relative`,children:[(0,N.jsx)(Oe,{className:`absolute left-3 top-2.5 h-3.5 w-3.5 text-gray-400`}),(0,N.jsx)(O,{value:t,onChange:e=>c(e.target.value),placeholder:o(`chatSidebarSearchPlaceholder`),className:`h-9 rounded-lg pl-8 text-xs`})]})})]})}function CM(e){let{query:t,defaultSessionType:n,sessionTypeOptions:r,nonDefaultSessionTypeOptions:i,isCreateMenuOpen:a,onCreateMenuOpenChange:s,onCreateSession:c,onQueryChange:l}=e,u=xM({defaultSessionType:n,sessionTypeOptions:r,nonDefaultSessionTypeOptions:i}),d=u.length>1;return(0,N.jsx)(`div`,{className:`px-4 pb-2 pt-1`,children:(0,N.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,N.jsxs)(`div`,{className:`relative min-w-0 flex-1`,children:[(0,N.jsx)(Oe,{className:`absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-gray-400`}),(0,N.jsx)(O,{value:t,onChange:e=>l(e.target.value),placeholder:o(`chatSidebarSearchPlaceholder`),className:`h-9 rounded-full border-transparent bg-gray-100/80 pl-9 pr-3 text-[13px] shadow-none focus:border-gray-200/80 focus:bg-white`})]}),d?(0,N.jsxs)(xt,{open:a,onOpenChange:s,children:[(0,N.jsx)(yt,{asChild:!0,children:(0,N.jsx)(g,{variant:`ghost`,size:`icon`,className:`h-9 w-9 shrink-0 rounded-full bg-gray-100/80 text-gray-700 shadow-none hover:bg-gray-200/80 hover:text-gray-900`,"aria-label":o(`chatSidebarNewTask`),children:(0,N.jsx)(rt,{className:`h-4 w-4`})})}),(0,N.jsxs)(_t,{align:`end`,className:`w-60 rounded-3xl border border-gray-200/80 bg-white p-2 shadow-[0_24px_70px_-30px_rgba(15,23,42,0.45)]`,children:[(0,N.jsx)(`div`,{className:`px-3 pb-1.5 pt-2 text-[11px] font-medium text-gray-400`,children:o(`chatSidebarNewTask`)}),(0,N.jsx)(`div`,{className:`space-y-1`,children:u.map(e=>(0,N.jsx)(En,{option:e,onSelect:()=>{c(e.value),s(!1)}},e.value))})]})]}):(0,N.jsx)(g,{variant:`ghost`,size:`icon`,className:`h-9 w-9 shrink-0 rounded-full bg-gray-100/80 text-gray-700 shadow-none hover:bg-gray-200/80 hover:text-gray-900`,"aria-label":o(`chatSidebarNewTask`),onClick:()=>c(n),children:(0,N.jsx)(rt,{className:`h-4 w-4`})})]})})}function wM(e){return new Date(e.session.updatedAt).getTime()}function TM(e){return[...e].sort((e,t)=>wM(t)-wM(e))}function EM(e){let t=new Date,n=new Date(t.getFullYear(),t.getMonth(),t.getDate()).getTime(),r=n-864e5,i=n-7*864e5,a=[],s=[],c=[],l=[];for(let t of e){let{session:e}=t,o=new Date(e.updatedAt).getTime();o>=n?a.push(t):o>=r?s.push(t):o>=i?c.push(t):l.push(t)}let u=[];return a.length>0&&u.push({label:o(`chatSidebarToday`),items:a}),s.length>0&&u.push({label:o(`chatSidebarYesterday`),items:s}),c.length>0&&u.push({label:o(`chatSidebarPrevious7Days`),items:c}),l.length>0&&u.push({label:o(`chatSidebarOlder`),items:l}),u}function DM(e){let t=new Map;for(let n of e){let e=n.session.projectRoot?.trim();if(!e)continue;let r=t.get(e),i=wM(n);if(r){r.items.push(n),r.latestUpdatedAt=Math.max(r.latestUpdatedAt,i);continue}t.set(e,{projectRoot:e,projectName:n.session.projectName?.trim()||SO(e)||e,items:[n],latestUpdatedAt:i})}return[...t.values()].map(e=>({...e,items:TM(e.items)})).sort((e,t)=>t.latestUpdatedAt-e.latestUpdatedAt)}function OM(e){if(e.label&&e.label.trim())return e.label.trim();let t=e.key.split(`:`);return t[t.length-1]||e.key}var kM=[{target:`/cron`,label:()=>o(`chatSidebarScheduledTasks`),icon:Ee},{target:`/skills`,label:()=>o(`chatSidebarSkills`),icon:ve},{target:`/agents`,label:()=>o(`agentsPageTitle`),icon:me}];function AM(e,t,n){let r=rk(e=>e.optimisticReadAtBySessionKey);return(0,P.useEffect)(()=>{(()=>{if(!t)return;let r=e.find(({session:e})=>e.key===t);if(!r)return;let{session:i}=r;n(i.key,i.lastMessageAt,i.readAt)})()},[e,n,t]),r}function jM({variant:e=`desktop`}){let n=e===`mobile`,r=Bn(),i=lt(),[a,s]=(0,P.useState)(!1),c=Q(e=>e.snapshot),l=rk(e=>e.snapshot),u=S(),f=Dj(),{isLoading:p,items:m}=yM(),{language:h,setLanguage:g}=ut(),{theme:_,setTheme:v}=Se(),y=o(ge.find(e=>e.value===_)?.labelKey??`themeWarm`),b=t.find(e=>e.value===h)?.label??h,x=(0,P.useMemo)(()=>new Map((f.data?.agents??[]).map(e=>[e.id,e])),[f.data?.agents]),C=(0,P.useMemo)(()=>TM(m),[m]),w=(0,P.useMemo)(()=>{let e=new Map;for(let t of m){let n=t.session.parentSessionId?.trim();if(!n)continue;let r=e.get(n)??[];r.push(t),e.set(n,r)}for(let t of e.values())t.sort((e,t)=>wM(t)-wM(e));return e},[m]),T=(0,P.useMemo)(()=>EM(C),[C]),E=(0,P.useMemo)(()=>DM(C),[C]),D=c.defaultSessionType||`native`,O=(0,P.useMemo)(()=>c.sessionTypeOptions.filter(e=>e.value!==D),[D,c.sessionTypeOptions]),ee=l.listMode===`project-first`,k=AM(m,l.selectedSessionKey,r.chatSessionListManager.markSessionRead),{editingSessionKey:te,draftLabel:A,savingSessionKey:ne,setDraftLabel:j,startEditingSessionLabel:re,cancelEditingSessionLabel:ie,saveSessionLabel:ae}=pM(),oe=e=>{h!==e&&(g(e),window.location.reload())},se=e=>(0,N.jsx)(bM,{item:e,selectedSessionKey:l.selectedSessionKey,optimisticReadAtBySessionKey:k,agentsById:x,childSessionsByParentKey:w,editingSessionKey:te,draftLabel:A,savingSessionKey:ne,sessionTitle:OM,onSelectSession:r.chatSessionListManager.selectSession,onOpenChildSessions:(e,t)=>r.chatThreadManager.openChildSessionPanel({parentSessionKey:e,activeChildSessionKey:t}),onStartEditingSessionLabel:re,onDraftLabelChange:j,onSaveSessionLabel:ae,onCancelEditingSessionLabel:ie},e.session.key),ce=(e,t)=>{let i=typeof t==`string`?r.chatSessionListManager.createSession(e,t):r.chatSessionListManager.createSession(e);n&&r.chatUiManager.goToSession(i)};return(0,N.jsxs)(`aside`,{className:d(`flex h-full min-h-0 flex-col bg-secondary`,n?`flex-1 overflow-hidden`:`w-[280px] shrink-0 border-r border-gray-200/60`),children:[n?null:(0,N.jsx)(`div`,{className:`px-5 pt-5 pb-3`,children:(0,N.jsx)(Te,{className:`flex items-center gap-2.5 min-w-0`,suffix:(0,N.jsx)(dM,{status:u.connectionStatus})})}),n?(0,N.jsx)(CM,{query:l.query,defaultSessionType:D,sessionTypeOptions:c.sessionTypeOptions,nonDefaultSessionTypeOptions:O,isCreateMenuOpen:a,onCreateMenuOpenChange:s,onCreateSession:ce,onQueryChange:r.chatSessionListManager.setQuery}):(0,N.jsx)(SM,{query:l.query,defaultSessionType:D,sessionTypeOptions:c.sessionTypeOptions,nonDefaultSessionTypeOptions:O,isCreateMenuOpen:a,onCreateMenuOpenChange:s,onCreateSession:ce,onQueryChange:r.chatSessionListManager.setQuery}),n?null:(0,N.jsx)(`div`,{className:`px-3 pb-2`,children:(0,N.jsx)(`ul`,{className:`space-y-0.5`,children:kM.map(e=>(0,N.jsx)(`li`,{children:(0,N.jsx)(he,{to:e.target,label:e.label(),icon:e.icon,density:`compact`})},e.target))})}),n?null:(0,N.jsx)(`div`,{className:`mx-4 border-t border-gray-200/60`}),(0,N.jsxs)(`div`,{className:`flex items-center justify-between px-5 pb-2 pt-3`,children:[(0,N.jsx)(`div`,{className:`text-[11px] font-medium uppercase tracking-wider text-gray-400`,children:o(`chatSidebarTaskRecords`)}),(0,N.jsx)(dn,{isProjectFirstView:ee,onSelectMode:r.chatSessionListManager.setListMode})]}),(0,N.jsx)(`div`,{className:`flex-1 min-h-0 overflow-y-auto custom-scrollbar px-3 py-2`,children:p?(0,N.jsx)(`div`,{className:`text-xs text-gray-500 p-3`,children:o(`sessionsLoading`)}):ee?E.length===0?(0,N.jsxs)(`div`,{className:`p-4 text-center`,children:[(0,N.jsx)(nn,{className:`h-6 w-6 mx-auto mb-2 text-gray-300`}),(0,N.jsx)(`div`,{className:`text-xs text-gray-500`,children:o(`chatSidebarProjectViewEmpty`)})]}):(0,N.jsx)(On,{groups:E,defaultSessionType:D,sessionTypeOptions:c.sessionTypeOptions,renderSessionItem:se,onCreateSession:ce}):T.length===0?(0,N.jsxs)(`div`,{className:`p-4 text-center`,children:[(0,N.jsx)(nn,{className:`h-6 w-6 mx-auto mb-2 text-gray-300`}),(0,N.jsx)(`div`,{className:`text-xs text-gray-500`,children:o(`sessionsEmpty`)})]}):(0,N.jsx)(`div`,{className:`space-y-3`,children:T.map(e=>(0,N.jsxs)(`div`,{children:[(0,N.jsx)(`div`,{className:`px-2 py-1 text-[11px] font-medium text-gray-400 uppercase tracking-wider`,children:e.label}),(0,N.jsx)(`div`,{className:`space-y-0.5`,children:e.items.map(se)})]},e.label))})}),n?null:(0,N.jsxs)(`div`,{className:`px-3 py-3 border-t border-gray-200/60 space-y-0.5`,children:[(0,N.jsx)(he,{to:`/settings`,label:o(`settings`),icon:at,density:`compact`}),(0,N.jsx)(we,{onClick:()=>i.open(void 0,{kind:`docs`,newTab:!0,title:`Docs`}),icon:ke,label:o(`docBrowserHelp`),density:`compact`}),(0,N.jsx)(be,{value:_,onValueChange:e=>v(e),icon:Ce,label:o(`theme`),valueLabel:y,density:`compact`,children:ge.map(e=>(0,N.jsx)(Ke,{value:e.value,className:`text-xs`,children:o(e.labelKey)},e.value))}),(0,N.jsx)(be,{value:h,onValueChange:e=>oe(e),icon:ye,label:o(`language`),valueLabel:b,density:`compact`,children:t.map(e=>(0,N.jsx)(Ke,{value:e.value,className:`text-xs`,children:e.label},e.value))})]})]})}function MM({tone:e=`neutral`,value:t}){return(0,N.jsx)(`span`,{className:d(`inline-flex h-5 items-center rounded-sm border px-1.5 text-[10px] font-medium leading-none`,e===`warning`?`border-amber-200 bg-amber-50 text-amber-700`:`border-gray-200 bg-gray-50 text-gray-500`),children:t})}function NM({breadcrumb:e}){return(0,N.jsx)(`div`,{"data-testid":`workspace-file-breadcrumbs`,title:e.fullPath,className:`workspace-horizontal-scrollbar overflow-x-auto overflow-y-hidden border-b border-gray-200/80 bg-gray-50/55`,children:(0,N.jsxs)(`div`,{"data-testid":`workspace-file-breadcrumb-scroll`,className:`flex min-w-max items-center gap-2.5 px-3 py-1.5`,children:[(0,N.jsx)(`div`,{className:`flex min-w-0 flex-1 items-center gap-1 pr-1`,children:e.segments.map((t,n)=>(0,N.jsxs)(P.Fragment,{children:[(0,N.jsxs)(`span`,{className:d(`inline-flex h-5 items-center gap-1 rounded-sm px-1 text-[11px] leading-none`,t.kind===`workspace`?`bg-primary/8 text-primary`:t.isCurrent?`bg-gray-200/70 text-gray-900`:`text-gray-500`),children:[t.kind===`workspace`?(0,N.jsx)(Zt,{className:`h-3 w-3 shrink-0`}):t.isCurrent?(0,N.jsx)(Ht,{className:`h-3 w-3 shrink-0`}):null,(0,N.jsx)(`span`,{children:t.label})]}),n<e.segments.length-1?(0,N.jsx)(It,{className:`h-3 w-3 shrink-0 text-gray-300`}):null]},t.key))}),e.locationLabel||e.truncated?(0,N.jsxs)(`div`,{className:`flex shrink-0 flex-wrap items-center justify-end gap-1`,children:[e.locationLabel?(0,N.jsx)(MM,{value:e.locationLabel}):null,e.truncated?(0,N.jsx)(MM,{tone:`warning`,value:o(`chatWorkspacePreviewTruncated`)}):null]}):null]})})}function PM(e){let t=e.path?.trim()??``;return y({queryKey:[`server-path-read`,t,e.basePath??null],queryFn:()=>k({path:t,basePath:e.basePath}),enabled:(e.enabled??!0)&&t.length>0,staleTime:0})}function FM(e){return e.serverKind?e.serverKind:/\.mdx?$/i.test(e.path)?`markdown`:`text`}function IM(e){let{line:t,path:n,text:r}=e,i=t??1;return{key:`preview:${n}`,path:n,display:`preview`,lines:cA({text:r,kind:`context`,oldStartLine:i,newStartLine:i}),rawText:r,oldStartLine:i,newStartLine:i}}function LM(e){if(Array.isArray(e.fullLines)&&e.fullLines.length>0)return{key:`diff:${e.key}`,path:e.path,display:`diff`,lines:e.fullLines,fullLines:e.fullLines,...e.beforeText?{beforeText:e.beforeText}:{},...e.afterText?{afterText:e.afterText}:{},...e.patchText?{patchText:e.patchText}:{},...typeof e.oldStartLine==`number`?{oldStartLine:e.oldStartLine}:{},...typeof e.newStartLine==`number`?{newStartLine:e.newStartLine}:{}};if(e.beforeText==null&&e.afterText==null)return null;let t=fA({beforeText:e.beforeText??``,afterText:e.afterText??``,oldStartLine:e.oldStartLine??void 0,newStartLine:e.newStartLine??void 0});return{key:`diff:${e.key}`,path:e.path,display:`diff`,lines:t,fullLines:t,...e.beforeText?{beforeText:e.beforeText}:{},...e.afterText?{afterText:e.afterText}:{},...typeof e.oldStartLine==`number`?{oldStartLine:e.oldStartLine}:{},...typeof e.newStartLine==`number`?{newStartLine:e.newStartLine}:{}}}function RM({text:e,tone:t=`muted`}){return(0,N.jsx)(`div`,{className:d(`flex h-full items-center justify-center px-6 text-center text-sm`,t===`error`?`text-rose-600`:`text-gray-500`),children:e})}function zM({diffBlock:e}){return e?(0,N.jsx)(BM,{block:e}):(0,N.jsx)(RM,{text:o(`chatWorkspaceDiffEmpty`)})}function BM({block:e}){return(0,N.jsx)(`div`,{className:`h-full overflow-auto custom-scrollbar bg-white`,children:(0,N.jsx)(vE,{block:e,layout:`workspace`})})}function VM({onFileOpen:e,previewBlock:t,previewKind:n,previewQuery:r,previewText:i}){return r.isLoading&&!t?(0,N.jsx)(RM,{text:o(`chatWorkspaceLoadingFile`)}):r.data?.kind===`binary`?(0,N.jsx)(RM,{text:o(`chatWorkspacePreviewUnsupported`)}):r.error&&!t?(0,N.jsx)(RM,{tone:`error`,text:r.error instanceof Error?r.error.message:String(r.error)}):n===`markdown`&&i?(0,N.jsx)(`div`,{className:`h-full overflow-auto custom-scrollbar px-5 py-4`,children:(0,N.jsx)(cT,{text:i,role:`assistant`,texts:{copyCodeLabel:o(`chatCodeCopy`),copiedCodeLabel:o(`chatCodeCopied`)},onFileOpen:e})}):t?(0,N.jsx)(BM,{block:t}):(0,N.jsx)(RM,{text:o(`chatWorkspacePreviewEmpty`)})}function HM({file:e,sessionProjectRoot:t,onFileOpen:n}){let r=e.viewMode===`preview`,i=PM({path:e.path,basePath:t,enabled:r}),a=(0,P.useMemo)(()=>e.viewMode===`diff`?LM(e):null,[e]),o=r?i.data?.text??e.rawText??null:null,s=FM({path:i.data?.resolvedPath??e.path,serverKind:i.data?.kind}),c=(0,P.useMemo)(()=>!r||!o?null:IM({path:i.data?.resolvedPath??e.path,text:o,line:e.line}),[e.line,e.path,r,i.data?.resolvedPath,o]),l=i.data?.resolvedPath??e.path,u=!!i.data?.truncated;return(0,N.jsxs)(`div`,{className:`flex h-full min-h-0 flex-col bg-white`,children:[(0,N.jsx)(NM,{breadcrumb:(0,P.useMemo)(()=>kO({path:l,sessionProjectRoot:t,line:e.line,column:e.column,truncated:u}),[e.column,e.line,u,l,t])}),(0,N.jsx)(`div`,{className:`flex-1 min-h-0 overflow-hidden`,children:e.viewMode===`diff`?(0,N.jsx)(zM,{diffBlock:a}):(0,N.jsx)(VM,{onFileOpen:n,previewBlock:c,previewKind:s,previewQuery:i,previewText:o})})]})}function UM(e,t){return e.label?.trim()?e.label.trim():t?mM(t):e.sessionKey}function WM(e){let t=pt({limit:200}),n=(0,P.useMemo)(()=>t.data?.sessions??[],[t.data?.sessions]),r=(0,P.useMemo)(()=>{let e=XO(n);return new Map(e.map(e=>[e.key,e]))},[n]),i=(0,P.useMemo)(()=>new Map(n.map(e=>[e.sessionId,e])),[n]);return(0,P.useMemo)(()=>e.map(e=>{let t=r.get(e.sessionKey)??null,n=i.get(e.sessionKey)??null,a=e.agentId?.trim()||t?.agentId||null;return{sessionKey:e.sessionKey,parentSessionKey:e.parentSessionKey,title:UM(e,t),agentId:a,updatedAt:t?.updatedAt??null,lastMessageAt:t?.lastMessageAt??null,readAt:t?.readAt??null,runStatus:n?.status===`running`?`running`:void 0,sessionTypeLabel:t?.sessionType?tM(t.sessionType):null,preferredModel:t?.preferredModel?.trim()||null,projectName:t?.projectName?.trim()||null,projectRoot:t?.projectRoot?.trim()||null}}),[r,i,e])}function GM(e){let t=e.split(/\r?\n/),n=`message`,r=[];for(let e of t){let t=e.trimEnd();if(!(!t||t.startsWith(`:`))){if(t.startsWith(`event:`)){n=t.slice(6).trim()||`message`;continue}t.startsWith(`data:`)&&r.push(t.slice(5).trimStart())}}return r.length===0?null:{event:n,data:r.join(`
|
|
61
|
-
`)}}async function*KM(e){let t=e.getReader(),n=new TextDecoder,r=``;try{for(;;){let{value:e,done:i}=await t.read();if(i)break;r+=n.decode(e,{stream:!0});let{frames:a,rest:o}=qM(r);r=o;for(let e of a)yield e}r+=n.decode();let{frames:e}=qM(r,!0);for(let t of e)yield t}finally{t.releaseLock()}}function qM(e,t=!1){let n=e.split(/\r?\n\r?\n/),r=n.pop()??``,i=[];for(let e of n){let t=GM(e);t&&i.push(t)}if(t&&r.trim()){let e=GM(r);return e&&i.push(e),{frames:i,rest:``}}return{frames:i,rest:r}}var JM=`/ncp/agent`,YM=class extends Error{ncpError;alreadyPublished;constructor(e,t=!1){super(e.message),this.name=`NcpHttpAgentClientError(${e.code})`,this.ncpError=e,this.alreadyPublished=t}};function XM(e){let t=e.trim();if(!t)throw Error(`NcpHttpAgentClient requires a non-empty baseUrl.`);return new URL(t)}function ZM(e){if(e)return e;if(typeof globalThis.fetch==`function`)return globalThis.fetch.bind(globalThis);throw Error(`No fetch implementation found. Pass options.fetchImpl explicitly.`)}function QM(e){let t=(e??`/ncp/agent`).trim();if(!t)return JM;let n=t.startsWith(`/`)?t:`/${t}`;return n.endsWith(`/`)?n.slice(0,-1):n}async function $M(e){try{return(await e.text()).trim()}catch{return``}}function eN(e){if(iN(e))return e.ncpError;if(nN(e))return e;let t=e instanceof Error?e.message:String(e??`Unknown error`);return{code:oN(void 0),message:t,...e instanceof Error&&e.stack?{details:{stack:e.stack}}:{}}}function tN(e,t={}){return new YM(e,t.alreadyPublished??!1)}function nN(e){return rN(e)&&typeof e.code==`string`&&typeof e.message==`string`}function rN(e){return!!e&&typeof e==`object`&&!Array.isArray(e)}function iN(e){return e instanceof YM}var aN={"config-error":`config-error`,"auth-error":`auth-error`,"runtime-error":`runtime-error`,"timeout-error":`timeout-error`,"abort-error":`abort-error`};function oN(e){if(!e)return`runtime-error`;let t=aN[e];if(t)return t;let n=e.toLowerCase();return n.includes(`timeout`)?`timeout-error`:n.includes(`abort`)||n.includes(`cancel`)?`abort-error`:n.includes(`auth`)?`auth-error`:n.includes(`config`)?`config-error`:`runtime-error`}function sN(e){let t=lN(e);return!t||typeof t.type!=`string`||!t.type.trim()?null:t}function cN(e){let t=lN(e);if(!t)return{code:`runtime-error`,message:e||`Unknown stream error.`};let n=typeof t.code==`string`?t.code:void 0,r=oN(n),i=rN(t.details)?t.details:{};return n&&n!==r&&(i.originalCode=n),{code:r,message:typeof t.message==`string`&&t.message?t.message:`Unknown stream error.`,...Object.keys(i).length>0?{details:i}:{}}}function lN(e){try{let t=JSON.parse(e);return rN(t)?t:null}catch{return null}}var uN=[`text`,`file`,`source`,`step-start`,`reasoning`,`tool-invocation`,`card`,`rich-text`,`action`,`extension`],dN=class{manifest;baseUrl;basePath;fetchImpl;defaultHeaders;subscribers=new Set;activeControllers=new Set;started=!1;constructor(e){this.baseUrl=XM(e.baseUrl),this.basePath=QM(e.basePath),this.fetchImpl=ZM(e.fetchImpl),this.defaultHeaders=e.headers??{},this.manifest={endpointKind:`custom`,endpointId:e.endpointId?.trim()||`ncp-http-agent-client`,version:`0.1.0`,supportsStreaming:!0,supportsAbort:!0,supportsProactiveMessages:!1,supportsLiveSessionStream:!0,supportedPartTypes:uN,expectedLatency:`seconds`,metadata:{transport:`http+sse`,scope:`agent`}}}async start(){this.started||(this.started=!0,this.publish({type:nD.EndpointReady}))}async stop(){if(this.started){this.started=!1;for(let e of this.activeControllers)e.abort();this.activeControllers.clear()}}async emit(e){switch(e.type){case`message.request`:await this.send(e.payload);return;case`message.stream-request`:await this.stream(e.payload);return;case`message.abort`:await this.abort(e.payload);return;default:this.publish(e);return}}subscribe(e){return this.subscribers.add(e),()=>{this.subscribers.delete(e)}}async send(e){await this.ensureStarted(),await this.jsonRequest({path:`/send`,method:`POST`,body:e})}async stream(e){await this.ensureStarted();let t=new URLSearchParams({sessionId:e.sessionId});await this.streamRequest({path:`/stream?${t.toString()}`,method:`GET`})}async abort(e){await this.ensureStarted();let t=new AbortController;this.activeControllers.add(t);try{let n=await this.fetchImpl(this.resolveUrl(`/abort`),{method:`POST`,headers:{...this.defaultHeaders,"content-type":`application/json`,accept:`application/json`},body:JSON.stringify(e),signal:t.signal});if(!n.ok)throw Error(`Abort request failed with HTTP ${n.status}: ${await $M(n)}`)}catch(e){if(t.signal.aborted)return;let n=eN(e);throw this.publish({type:nD.EndpointError,payload:n}),tN(n)}finally{this.activeControllers.delete(t)}}async ensureStarted(){this.started||await this.start()}publish(e){for(let t of this.subscribers)t(e)}resolveUrl(e){return new URL(`${this.basePath}${e}`,this.baseUrl)}async jsonRequest(e){let t=new AbortController;this.activeControllers.add(t);try{let n=await this.fetchImpl(this.resolveUrl(e.path),{method:e.method,headers:{...this.defaultHeaders,"content-type":`application/json`,accept:`application/json`},body:e.body===void 0?void 0:JSON.stringify(e.body),signal:t.signal});if(!n.ok)throw Error(`NCP request failed with HTTP ${n.status}: ${await $M(n)}`)}catch(e){if(t.signal.aborted)return;if(iN(e))throw e;let n=eN(e);throw this.publish({type:nD.EndpointError,payload:n}),tN(n)}finally{this.activeControllers.delete(t)}}async streamRequest(e){let t=new AbortController;this.activeControllers.add(t);try{let n=await this.fetchImpl(this.resolveUrl(e.path),{method:e.method,headers:{...this.defaultHeaders,accept:`text/event-stream`,...e.body===void 0?{}:{"content-type":`application/json`}},body:e.body===void 0?void 0:JSON.stringify(e.body),signal:t.signal});if(!n.ok)throw Error(`NCP stream request failed with HTTP ${n.status}: ${await $M(n)}`);if(!n.body)throw Error(`NCP stream response has no body.`);for await(let e of KM(n.body)){if(t.signal.aborted)return;this.handleSseFrame(e)}}catch(e){if(t.signal.aborted)return;if(iN(e))throw e;let n=eN(e);throw this.publish({type:nD.EndpointError,payload:n}),tN(n)}finally{this.activeControllers.delete(t)}}handleSseFrame(e){if(e.event===`ncp-event`){let t=sN(e.data);if(!t){this.publish({type:nD.EndpointError,payload:{code:`runtime-error`,message:`Received malformed ncp-event frame.`}});return}this.publish(t);return}if(e.event===`error`){let t=cN(e.data);throw this.publish({type:nD.EndpointError,payload:t}),tN(t,{alreadyPublished:!0})}}};function fN(e){return typeof e==`string`?e:e instanceof URL?e.toString():e.url}function pN(e){if(e instanceof Error){let t=e.name?.trim(),n=e.message?.trim();return t&&n?`${t}: ${n}`:n||t||`Unknown Error`}return String(e??`Unknown error`)}function mN(e,t){let n=Error(e);return t!==void 0&&(n.cause=t),n}function hN(){return async(e,t)=>{try{return await fetch(e,{credentials:`include`,...t})}catch(n){throw se.reportTransportFailure(pN(n)),mN(`NCP fetch failed for ${(t?.method||`GET`).toUpperCase()} ${fN(e)}: ${pN(n)}`,n)}}}var gN=300,_N=`ncp agent unavailable during startup`;function vN(e){return e instanceof Error?e.message.includes(`ncp session not found:`):!1}function yN(e){return e?.trim().toLowerCase().includes(_N)??!1}function bN(){return new dN({baseUrl:ae,basePath:`/api/ncp/agent`,fetchImpl:hN()})}async function xN(e,t,n=gN){t.throwIfAborted();try{let r=await E(e,n);return t.throwIfAborted(),{messages:r.messages,status:r.status??`idle`,contextWindow:r.contextWindow??null}}catch(e){if(t.throwIfAborted(),!vN(e))throw e;return{messages:[],status:`idle`}}}function SN(e,t){let n=(0,P.useRef)(null),r=(0,P.useCallback)(e=>{if(!e){n.current=null;return}n.current!==e&&(n.current=e,t())},[t]);(0,P.useEffect)(()=>{r(e)},[e,r])}function CN(e,t={}){let[n]=(0,P.useState)(()=>bN()),r=S(),[i,a]=(0,P.useState)(0),[o,s]=(0,P.useState)(null),c=t.messageLimit??gN;(0,P.useEffect)(()=>{s(null)},[e]);let l=jD({sessionId:e,client:n,loadSeed:(0,P.useCallback)(async(e,t)=>{let n=await xN(e,t,c);return t.aborted||s(n.contextWindow??null),{messages:n.messages,status:n.status}},[i,c])}),u=l.hydrateError?.message??l.snapshot.error?.message??null;return SN(r.phase===`ready`&&yN(u)?`${e}:${r.lastReadyAt??0}`:null,()=>{a(e=>e+1)}),(0,P.useMemo)(()=>({...l,snapshot:{...l.snapshot,contextWindow:l.snapshot.contextWindow??o}}),[l,o])}function wN(e){return e.label?.trim()||e.path.split(`/`).filter(Boolean).pop()||e.path}function TN(e){let{activeChildSessionKey:t,activeWorkspaceFileKey:n,childSessionTabs:r,workspaceFileTabs:i}=e;if(n){let e=i.find(e=>e.key===n);if(e)return{kind:`file`,file:e}}if(t){let e=r.find(e=>e.sessionKey===t);if(e)return{kind:`child-session`,tab:e}}return r[0]?{kind:`child-session`,tab:r[0]}:i[0]?{kind:`file`,file:i[0]}:null}function EN({agentId:e,kind:t}){return t===`file`?(0,N.jsx)(Ht,{className:`h-3.5 w-3.5 shrink-0 text-gray-400`}):e?(0,N.jsx)(Nj,{agentId:e,className:`h-3.5 w-3.5 shrink-0`}):(0,N.jsx)(nn,{className:`h-3.5 w-3.5 shrink-0 text-gray-400`})}function DN({tab:e}){return(0,N.jsx)(kt,{delayDuration:250,children:(0,N.jsxs)(jt,{children:[(0,N.jsx)(Tt,{asChild:!0,children:(0,N.jsxs)(`div`,{className:d(`group flex max-w-[180px] min-w-0 items-center gap-1.5 border-r border-gray-200/70 border-b-2 px-2.5 py-2 transition-colors`,e.active?`border-b-primary bg-white text-gray-900`:`border-b-transparent bg-gray-50/85 text-gray-500 hover:bg-gray-100`),children:[(0,N.jsxs)(`button`,{type:`button`,onClick:e.onSelect,className:`flex min-w-0 flex-1 items-center gap-1.5 text-left`,children:[(0,N.jsx)(EN,{kind:e.kind,agentId:e.agentId}),(0,N.jsx)(`span`,{className:`min-w-0 truncate text-[12px] font-medium`,children:e.title}),e.kind===`file`&&e.viewMode===`diff`?(0,N.jsx)(`span`,{className:`shrink-0 rounded border border-amber-200 bg-amber-50 px-1 py-0 text-[9px] font-medium uppercase tracking-[0.08em] text-amber-700`,children:o(`chatWorkspaceDiff`)}):null,e.showUnreadDot?(0,N.jsx)(`span`,{"aria-label":o(`chatSessionUnread`),className:`h-2 w-2 shrink-0 rounded-full bg-primary`}):null]}),e.onClose?(0,N.jsx)(`button`,{type:`button`,onClick:t=>{t.stopPropagation(),e.onClose?.()},className:d(`rounded p-0.5 text-gray-400 transition-colors hover:bg-gray-200 hover:text-gray-700`,e.active?`opacity-100`:`opacity-0 group-hover:opacity-100`),"aria-label":o(`chatWorkspaceCloseFile`),children:(0,N.jsx)(ct,{className:`h-3 w-3`})}):null]})}),(0,N.jsx)(Dt,{side:`bottom`,className:`max-w-[320px] text-xs`,children:e.tooltip})]})})}function ON({tabs:e}){return(0,N.jsx)(`div`,{"data-testid":`workspace-tabs-bar`,className:`workspace-horizontal-scrollbar overflow-x-auto overflow-y-hidden border-b border-gray-200/70 bg-gray-50/85`,children:(0,N.jsx)(`div`,{"data-testid":`workspace-tabs-scroll`,className:`flex min-w-max items-stretch`,children:e.map(e=>(0,N.jsx)(DN,{tab:e},e.key))})})}function kN({sessionKey:e,onToolAction:t,onFileOpen:n}){let r=CN(e),i=r.visibleMessages,a=(0,P.useRef)(null),{onScroll:s}=qT({scrollRef:a,resetKey:e,isLoading:r.isHydrating,hasContent:i.length>0,contentVersion:i[i.length-1]??null,stickyThresholdPx:20});return(0,N.jsx)(`div`,{ref:a,onScroll:s,className:`h-full overflow-y-auto custom-scrollbar`,children:r.isHydrating?(0,N.jsxs)(`div`,{className:`flex h-full items-center justify-center text-sm text-gray-500`,children:[(0,N.jsx)(nt,{className:`mr-2 h-4 w-4 animate-spin`}),o(`chatChildSessionLoading`)]}):r.hydrateError?(0,N.jsx)(`div`,{className:`px-4 py-5 text-sm text-rose-600`,children:r.hydrateError.message}):i.length===0&&!r.isRunning?(0,N.jsx)(`div`,{className:`px-4 py-5 text-sm text-gray-500`,children:o(`chatChildSessionEmpty`)}):(0,N.jsx)(`div`,{className:`px-4 py-5`,children:(0,N.jsx)(Bj,{messages:i,isSending:r.isRunning,onToolAction:t,onFileOpen:n})})})}function AN({value:e}){return(0,N.jsx)(`span`,{className:`inline-flex max-w-full items-center rounded border border-gray-200 bg-gray-50 px-2 py-0.5 text-[10px] font-medium text-gray-600`,children:(0,N.jsx)(`span`,{className:`truncate`,children:e})})}function jN({tab:e}){let t=[e.sessionTypeLabel,e.preferredModel,e.projectName].filter(e=>!!e?.trim());return t.length===0&&!e.projectRoot?null:(0,N.jsxs)(`div`,{className:`mt-3 space-y-2`,children:[t.length>0?(0,N.jsx)(`div`,{className:`flex flex-wrap gap-1.5`,children:t.map(e=>(0,N.jsx)(AN,{value:e},e))}):null,e.projectRoot?(0,N.jsx)(`div`,{title:e.projectRoot,className:`truncate rounded border border-gray-200 bg-gray-50 px-2 py-1.5 font-mono text-[11px] text-gray-500`,children:e.projectRoot}):null]})}function MN({tab:e}){return(0,N.jsxs)(`div`,{className:`border-b border-gray-200/70 px-4 py-3`,children:[(0,N.jsxs)(`div`,{className:`flex min-w-0 items-center gap-2 text-sm font-semibold text-gray-900`,children:[e.agentId?(0,N.jsx)(Nj,{agentId:e.agentId,className:`h-4 w-4 shrink-0`}):(0,N.jsx)(Yt,{className:`h-4 w-4 shrink-0 text-gray-400`}),(0,N.jsx)(`span`,{className:`truncate`,children:e.title})]}),(0,N.jsx)(jN,{tab:e})]})}function NN(e){let{resolvedChildTabs:t,workspaceFileTabs:n,activeSelection:r,optimisticReadAtBySessionKey:i,onSelectSession:a,onSelectFile:o,onCloseFile:s}=e,c=t.map(e=>{let t=i[e.sessionKey],n=t&&e.readAt?t.localeCompare(e.readAt)>0?t:e.readAt:t??e.readAt;return{key:`child:${e.sessionKey}`,kind:`child-session`,title:e.title,tooltip:e.title,agentId:e.agentId,active:r?.kind===`child-session`&&r.tab.sessionKey===e.sessionKey,showUnreadDot:$O({active:r?.kind===`child-session`&&r.tab.sessionKey===e.sessionKey,lastMessageAt:e.lastMessageAt,readAt:n,runStatus:e.runStatus}),onSelect:()=>a(e.sessionKey)}}),l=n.map(e=>({key:`file:${e.key}`,kind:`file`,title:wN(e),tooltip:e.path,viewMode:e.viewMode,active:r?.kind===`file`&&r.file.key===e.key,onSelect:()=>o(e.key),onClose:()=>s(e.key)}));return[...c,...l]}function PN({childSessionTabs:e,activeChildSessionKey:t,workspaceFileTabs:n,activeWorkspaceFileKey:r,sessionProjectRoot:i,displayMode:a=`docked`,onSelectSession:s,onSelectFile:c,onCloseFile:l,onClose:u,onBackToParent:f,onToolAction:p,onFileOpen:m}){let h=Bn(),g=WM(e),_=rk(e=>e.optimisticReadAtBySessionKey),v=TN({activeChildSessionKey:t,activeWorkspaceFileKey:r,childSessionTabs:g,workspaceFileTabs:n}),y=g.some(e=>!!e.parentSessionKey);(0,P.useEffect)(()=>{if(v?.kind!==`child-session`)return;let e=v.tab.lastMessageAt?.trim()??null;e&&h.chatSessionListManager.markSessionRead(v.tab.sessionKey,e,v.tab.readAt??null)},[v,h]);let b=(0,P.useMemo)(()=>NN({resolvedChildTabs:g,workspaceFileTabs:n,activeSelection:v,optimisticReadAtBySessionKey:_,onSelectSession:s,onSelectFile:c,onCloseFile:l}),[v,l,c,s,_,g,n]);return v?(0,N.jsx)(`aside`,{className:d(a===`overlay`?`fixed inset-0 z-40 flex bg-white`:`hidden shrink-0 border-l border-gray-200/70 bg-white/95 backdrop-blur-sm md:flex md:w-[26rem] lg:w-[30rem] xl:w-[34rem]`),children:(0,N.jsxs)(`div`,{className:`flex h-full min-h-0 w-full flex-col`,children:[(0,N.jsxs)(`div`,{className:`flex items-center justify-between gap-3 border-b border-gray-200/70 px-4 py-2.5`,children:[(0,N.jsxs)(`button`,{type:`button`,onClick:f,className:d(`inline-flex items-center gap-1 text-xs font-medium text-gray-600 transition-colors hover:text-gray-900`,!y&&`pointer-events-none opacity-0`),children:[(0,N.jsx)(De,{className:`h-3.5 w-3.5`}),(0,N.jsx)(`span`,{children:o(`chatBackToParent`)})]}),(0,N.jsx)(`button`,{type:`button`,onClick:u,className:`rounded-full border border-gray-200/80 p-1.5 text-gray-500 transition-colors hover:bg-gray-100 hover:text-gray-900`,"aria-label":o(`chatWorkspaceClosePanel`),children:(0,N.jsx)(ct,{className:`h-4 w-4`})})]}),(0,N.jsx)(ON,{tabs:b}),(0,N.jsx)(`div`,{className:`flex min-h-0 flex-1 flex-col bg-white`,children:v.kind===`child-session`?(0,N.jsxs)(N.Fragment,{children:[(0,N.jsx)(MN,{tab:v.tab}),(0,N.jsx)(`div`,{className:`flex-1 min-h-0`,children:(0,N.jsx)(kN,{sessionKey:v.tab.sessionKey,onToolAction:p,onFileOpen:m})})]}):(0,N.jsx)(HM,{file:v.file,sessionProjectRoot:i,onFileOpen:m})})]})}):null}function FN(){return y({queryKey:[`ncp-session-types`],queryFn:b,staleTime:1e4,retry:!1})}function IN(e){let t=e.trim();return t.length>0?t:null}function LN(e){return e??null}var RN=class{constructor(e){this.updateSession=e,this.inFlight=null,this.queued=null,this.syncSelectedSessionPreferences=()=>{let e=Q.getState().snapshot,t=rk.getState().snapshot,n=ak.getState().snapshot,r=t.selectedSessionKey;!r||!n.canDeleteSession||this.enqueue({sessionKey:r,patch:{preferredModel:IN(e.selectedModel),preferredThinking:LN(e.selectedThinkingLevel)}})},this.enqueue=e=>{this.queued=e,!this.inFlight&&this.startFlush()},this.startFlush=()=>{this.inFlight=this.flush().catch(e=>{console.error(`Failed to sync chat session preferences: ${String(e)}`)}).finally(()=>{this.inFlight=null,this.queued&&this.startFlush()})},this.flush=async()=>{for(;this.queued;){let e=this.queued;this.queued=null,await this.updateSession(e.sessionKey,e.patch)}}}},zN=class{constructor(e,t,n){this.uiManager=e,this.streamActionsManager=t,this.sessionListManager=n,this.sessionPreferenceSync=new RN(ie),this.buildAttachmentSignature=e=>[e.assetUri??``,e.url??``,e.name,e.mimeType,String(e.sizeBytes),e.contentBase64??``].join(`:`),this.hasSnapshotChanges=e=>{let t=Q.getState().snapshot;for(let[n,r]of Object.entries(e))if(!Object.is(t[n],r))return!0;return!1},this.resolveUpdateValue=(e,t)=>typeof t==`function`?t(e):t,this.isSameStringArray=(e,t)=>e.length===t.length&&e.every((e,n)=>e===t[n]),this.isRuntimeBlockedForSend=()=>lk(se.getStatusView()),this.syncComposerSnapshot=e=>{let t=Q.getState().snapshot.attachments,n=cO(e,t);Q.getState().setSnapshot({composerNodes:e,attachments:n,draft:rO(e),selectedSkills:iO(e)})},this.syncComposerSnapshotWithAttachments=(e,t)=>{Q.getState().setSnapshot({composerNodes:e,attachments:t,draft:rO(e),selectedSkills:iO(e)})},this.dedupeAttachments=e=>{let t=new Set,n=[];for(let r of e){let e=this.buildAttachmentSignature(r);t.has(e)||(t.add(e),n.push(r))}return n},this.syncSnapshot=e=>{if(this.hasSnapshotChanges(e)&&(Q.getState().setSnapshot(e),Object.prototype.hasOwnProperty.call(e,`modelOptions`)||Object.prototype.hasOwnProperty.call(e,`selectedModel`)||Object.prototype.hasOwnProperty.call(e,`selectedThinkingLevel`))){let{selectedModel:e}=Q.getState().snapshot;this.reconcileThinkingForModel(e)}},this.setDraft=e=>{let t=Q.getState().snapshot.draft,n=this.resolveUpdateValue(t,e);n!==t&&this.syncComposerSnapshot(nO(n))},this.setComposerNodes=e=>{let t=Q.getState().snapshot.composerNodes,n=this.resolveUpdateValue(t,e);Object.is(n,t)||this.syncComposerSnapshot(n)},this.addAttachments=e=>{if(e.length===0)return[];let{snapshot:t}=Q.getState(),n=new Set(t.attachments.map(this.buildAttachmentSignature)),r=this.dedupeAttachments([...t.attachments,...e]),i=r.filter(e=>!n.has(this.buildAttachmentSignature(e)));if(i.length===0)return[];let a=sO(t.composerNodes,r);return this.syncComposerSnapshotWithAttachments(a,r),i},this.restoreComposerState=(e,t)=>{let n=this.dedupeAttachments(t),r=sO(e,n);this.syncComposerSnapshotWithAttachments(r,n)},this.setPendingSessionType=e=>{let t=Q.getState().snapshot.pendingSessionType,n=this.resolveUpdateValue(t,e);n!==t&&Q.getState().setSnapshot({pendingSessionType:n})},this.send=async()=>{let e=Q.getState().snapshot,t=rk.getState().snapshot,n=ak.getState().snapshot,r=e.draft.trim(),{attachments:i}=e,a=lO(e.composerNodes,i);if(vO({snapshot:e,hasSendableDraft:a.some(e=>e.type!==`text`||e.text.trim().length>0),isRuntimeBlocked:this.isRuntimeBlockedForSend()}))return;let{selectedSkills:o,composerNodes:s}=e,c=n.sessionKey??t.selectedSessionKey??this.sessionListManager.ensureDraftSession(e.selectedSessionType);this.setComposerNodes(tO()),await this.streamActionsManager.sendMessage({message:r,sessionKey:c,agentId:t.selectedAgentId,sessionType:e.selectedSessionType,model:e.selectedModel||void 0,thinkingLevel:e.selectedThinkingLevel??void 0,stopSupported:!0,requestedSkills:o,attachments:i,parts:a,restoreDraftOnError:!0,composerNodes:s}),this.sessionListManager.promoteRootDraftSessionRoute(c)},this.stop=async()=>{await this.streamActionsManager.stopCurrentRun()},this.goToProviders=()=>{this.uiManager.goToProviders()},this.setSelectedModel=e=>{let t=Q.getState().snapshot.selectedModel,n=this.resolveUpdateValue(t,e);n!==t&&(Q.getState().setSnapshot({selectedModel:n}),this.reconcileThinkingForModel(n))},this.setSelectedThinkingLevel=e=>{let t=Q.getState().snapshot.selectedThinkingLevel,n=this.resolveUpdateValue(t,e);n!==t&&Q.getState().setSnapshot({selectedThinkingLevel:n})},this.selectSessionType=e=>{let t=$j(e);Q.getState().setSnapshot({selectedSessionType:t,pendingSessionType:t})},this.setSelectedSkills=e=>{let{snapshot:t}=Q.getState(),{selectedSkills:n}=t,r=this.resolveUpdateValue(n,e);this.isSameStringArray(r,n)||this.syncComposerSnapshot(oO(t.composerNodes,r,t.skillRecords))},this.selectModel=e=>{this.setSelectedModel(e),fO.remember(e),this.sessionPreferenceSync.syncSelectedSessionPreferences()},this.selectThinkingLevel=e=>{this.setSelectedThinkingLevel(e),this.sessionPreferenceSync.syncSelectedSessionPreferences()},this.rememberSkillSelection=e=>{pO.remember(e)},this.selectSkills=e=>{let t=Q.getState().snapshot.selectedSkills;for(let n of e)t.includes(n)||this.rememberSkillSelection(n);this.setSelectedSkills(e)},this.resolveThinkingForModel=(e,t)=>{let n=e?.thinkingCapability;return!n||n.supported.length===0?null:t===`off`?`off`:t&&n.supported.includes(t)?t:n.default&&n.supported.includes(n.default)?n.default:`off`},this.reconcileThinkingForModel=e=>{let{snapshot:t}=Q.getState(),n=t.modelOptions.find(t=>t.value===e),{selectedThinkingLevel:r}=t,i=this.resolveThinkingForModel(n,r);i!==r&&Q.getState().setSnapshot({selectedThinkingLevel:i})}}},BN=class{constructor(e,t){this.uiManager=e,this.streamActionsManager=t,this.syncDraftThreadState=e=>{ak.getState().setSnapshot({sessionKey:e,sessionDisplayName:void 0,canDeleteSession:!1,isHistoryLoading:!1,messages:[],isSending:!1,isAwaitingAssistantOutput:!1,parentSessionKey:null,parentSessionLabel:null,workspacePanelParentKey:null,childSessionTabs:[],activeChildSessionKey:null,activeWorkspaceFileKey:null})},this.resolveUpdateValue=(e,t)=>typeof t==`function`?t(e):t,this.shouldPersistReadAt=(e,t,n)=>{let r=rk.getState().optimisticReadAtBySessionKey[e],i=r&&n?r.localeCompare(n)>0?r:n:r??n??void 0;return i?t.localeCompare(i)>0:!0},this.setSelectedAgentId=e=>{let t=rk.getState().snapshot.selectedAgentId,n=this.resolveUpdateValue(t,e);n!==t&&rk.getState().setSnapshot({selectedAgentId:n})},this.setSelectedSessionKey=e=>{let t=rk.getState().snapshot.selectedSessionKey,n=this.resolveUpdateValue(t,e);n!==t&&rk.getState().setSnapshot({selectedSessionKey:n})},this.setListMode=e=>{let t=rk.getState().snapshot.listMode,n=this.resolveUpdateValue(t,e);n!==t&&rk.getState().setSnapshot({listMode:n})},this.markSessionRead=(e,t,n)=>{let r=e?.trim(),i=t?.trim();!r||!i||this.shouldPersistReadAt(r,i,n)&&(rk.getState().markSessionRead(r,i),ie(r,{uiReadAt:i}).catch(()=>void 0))},this.createSession=(e,t)=>{let{snapshot:n}=Q.getState(),{defaultSessionType:r}=n,i=r||`native`,a=typeof e==`string`&&e.trim().length>0?e.trim():i,o=xO(t),s=ZO();return this.streamActionsManager.resetStreamState(),rk.getState().setSnapshot({selectedSessionKey:null,draftSessionKey:s}),this.syncDraftThreadState(s),Q.getState().setSnapshot({pendingSessionType:a,pendingProjectRoot:o,pendingProjectRootSessionKey:o?s:null}),this.uiManager.goToChatRoot(),s},this.startAgentDraftChat=(e,t)=>{let n=e.trim()||`main`,r=this.createSession(t);return this.setSelectedAgentId(n),r},this.ensureDraftSession=e=>{let{snapshot:t}=rk.getState();if(t.selectedSessionKey)return t.selectedSessionKey;let n=typeof e==`string`&&e.trim().length>0?e.trim():null;return this.syncDraftThreadState(t.draftSessionKey),n&&Q.getState().setSnapshot({pendingSessionType:n}),t.draftSessionKey},this.promoteRootDraftSessionRoute=e=>{let t=e.trim();if(!t)return;let{snapshot:n}=rk.getState(),{sessionKey:r}=ak.getState().snapshot;n.selectedSessionKey!==null||n.draftSessionKey!==t||r!==t||!this.uiManager.isAtChatRoot()||this.uiManager.goToSession(t,{replace:!0})},this.selectSession=e=>{ak.getState().setSnapshot({workspacePanelParentKey:null,activeChildSessionKey:null,activeWorkspaceFileKey:null}),this.uiManager.goToSession(e)},this.setQuery=e=>{let t=rk.getState().snapshot.query,n=this.resolveUpdateValue(t,e);n!==t&&rk.getState().setSnapshot({query:n})}}},VN=async()=>{},HN=()=>{},UN=class{constructor(){this.actions={sendMessage:VN,stopCurrentRun:VN,resumeRun:VN,resetStreamState:HN,applyHistoryMessages:HN},this.bind=e=>{this.actions={...this.actions,...e}},this.sendMessage=e=>this.actions.sendMessage(e),this.stopCurrentRun=()=>this.actions.stopCurrentRun(),this.resumeRun=e=>this.actions.resumeRun(e),this.resetStreamState=()=>this.actions.resetStreamState(),this.applyHistoryMessages=(e,t)=>this.actions.applyHistoryMessages(e,t)}},WN=`sid_`;function GN(e){let t=new TextEncoder().encode(e),n=``;for(let e of t)n+=String.fromCharCode(e);return`${WN}${btoa(n).replace(/\+/g,`-`).replace(/\//g,`_`).replace(/=+$/g,``)}`}function KN(e){if(!e.startsWith(WN))return null;let t=e.slice(4).replace(/-/g,`+`).replace(/_/g,`/`),n=`=`.repeat((4-t.length%4)%4);try{let e=atob(t+n),r=Uint8Array.from(e,e=>e.charCodeAt(0));return new TextDecoder().decode(r)}catch{return null}}function qN(e){if(!e)return null;let t=KN(e);if(t)return t;try{return decodeURIComponent(e)}catch{return e}}function JN(e){return`/chat/${GN(e)}`}var YN=async e=>!1,XN=class{constructor(){this.state={pathname:``},this.actions={navigate:null,confirm:YN},this.syncState=e=>{this.state={...this.state,...e}},this.bindActions=e=>{this.actions={...this.actions,...e}},this.confirm=async e=>this.actions.confirm(e),this.navigateTo=(e,t)=>{this.actions.navigate&&(this.state.pathname===e&&!t?.replace||(this.actions.navigate(e,t),this.state.pathname=e))},this.goToProviders=()=>{this.navigateTo(`/providers`)},this.goToChatRoot=e=>{this.navigateTo(`/chat`,e)},this.isAtChatRoot=()=>this.state.pathname===`/chat`,this.goToSession=(e,t)=>{this.navigateTo(JN(e),t)}}},ZN=class{constructor(e,t,n){this.uiManager=e,this.sessionListManager=t,this.streamActionsManager=n,this.hasSnapshotChanges=e=>{let t=ak.getState().snapshot;for(let[n,r]of Object.entries(e))if(!Object.is(t[n],r))return!0;return!1},this.syncSnapshot=e=>{this.hasSnapshotChanges(e)&&ak.getState().setSnapshot(e)},this.clearDeletedSessionState=e=>{rk.getState().snapshot.selectedSessionKey===e&&this.sessionListManager.setSelectedSessionKey(null),ak.getState().setSnapshot({sessionKey:null,sessionTypeLabel:null,agentId:null,agentDisplayName:null,agentAvatarUrl:null,sessionDisplayName:void 0,sessionProjectRoot:null,sessionProjectName:null,canDeleteSession:!1,isHistoryLoading:!1,messages:[],isSending:!1,isAwaitingAssistantOutput:!1,parentSessionKey:null,parentSessionLabel:null,workspacePanelParentKey:null,childSessionTabs:[],activeChildSessionKey:null,workspaceFileTabs:[],activeWorkspaceFileKey:null})},this.resolveWorkspaceParentSessionKey=()=>ak.getState().snapshot.sessionKey?.trim()||(rk.getState().snapshot.selectedSessionKey??null),this.buildWorkspaceFileTab=(e,t)=>{let n=e.path.trim();if(!n)return null;let r=t?.trim()||null;return{key:`${r??`draft`}::${e.viewMode}::${n}`,parentSessionKey:r,path:n,label:e.label?.trim()||null,viewMode:e.viewMode,line:e.line??null,column:e.column??null,rawText:e.rawText??null,beforeText:e.beforeText??null,afterText:e.afterText??null,patchText:e.patchText??null,oldStartLine:e.oldStartLine??null,newStartLine:e.newStartLine??null,fullLines:e.fullLines}},this.upsertWorkspaceFileTab=e=>{let{workspaceFileTabs:t}=ak.getState().snapshot,n=t.findIndex(t=>t.key===e.key);if(n===-1)return[e,...t];let r=[...t];return r.splice(n,1),r.unshift({...t[n],...e}),r},this.ensureWorkspaceParentRoute=e=>{if(!e)return;let{snapshot:{selectedSessionKey:t}}=rk.getState();t!==e&&this.uiManager.goToSession(e)},this.deleteSession=()=>{this.deleteCurrentSession()},this.createSession=()=>{this.sessionListManager.createSession()},this.goToProviders=()=>{this.uiManager.goToProviders()},this.openChildSessionPanel=e=>{let t=e.parentSessionKey.trim();if(!t)return;let n=e.activeChildSessionKey?.trim()||null;ak.getState().setSnapshot({workspacePanelParentKey:t,activeChildSessionKey:n,activeWorkspaceFileKey:null}),this.ensureWorkspaceParentRoute(t)},this.openFilePreview=e=>{let t=this.resolveWorkspaceParentSessionKey(),n=this.buildWorkspaceFileTab(e,t);n&&(ak.getState().setSnapshot({workspacePanelParentKey:t,workspaceFileTabs:this.upsertWorkspaceFileTab(n),activeWorkspaceFileKey:n.key,activeChildSessionKey:null}),this.ensureWorkspaceParentRoute(t))},this.openSessionFromToolAction=e=>{if(e.kind===`open-session`){if(e.sessionKind===`child`&&!this.isCompactViewport()){let t=e.parentSessionId?.trim()||rk.getState().snapshot.selectedSessionKey||null;if(t){this.openChildSessionPanel({parentSessionKey:t,activeChildSessionKey:e.sessionId});return}}ak.getState().setSnapshot({workspacePanelParentKey:null,activeChildSessionKey:null,activeWorkspaceFileKey:null}),this.uiManager.goToSession(e.sessionId)}},this.selectChildSessionDetail=e=>{let t=e.trim();if(!t)return;let{childSessionTabs:n}=ak.getState().snapshot;n.some(e=>e.sessionKey===t)&&ak.getState().setSnapshot({activeChildSessionKey:t,activeWorkspaceFileKey:null})},this.selectWorkspaceFile=e=>{let t=e.trim();if(!t)return;let{workspaceFileTabs:n}=ak.getState().snapshot;n.some(e=>e.key===t)&&ak.getState().setSnapshot({activeWorkspaceFileKey:t,activeChildSessionKey:null})},this.closeWorkspaceFile=e=>{let t=e.trim();if(!t)return;let{snapshot:n}=ak.getState(),{activeWorkspaceFileKey:r,workspaceFileTabs:i}=n,a={workspaceFileTabs:i.filter(e=>e.key!==t)};r===t&&(a.activeWorkspaceFileKey=null),ak.getState().setSnapshot(a)},this.closeWorkspacePanel=()=>{ak.getState().setSnapshot({workspacePanelParentKey:null,activeChildSessionKey:null,activeWorkspaceFileKey:null})},this.closeChildSessionDetail=()=>{this.closeWorkspacePanel()},this.goToParentSession=()=>{let{parentSessionKey:e,childSessionTabs:t,activeChildSessionKey:n}=ak.getState().snapshot,r=t.find(e=>e.sessionKey===n)?.parentSessionKey??null,i=e??r;i&&(this.closeWorkspacePanel(),this.uiManager.goToSession(i))},this.isCompactViewport=()=>dt.getSnapshot().mode===`mobile`,this.deleteCurrentSession=async()=>{let{snapshot:{selectedSessionKey:e}}=rk.getState();if(e&&await this.uiManager.confirm({title:o(`chatDeleteSessionConfirm`),variant:`destructive`,confirmLabel:o(`delete`)})){ak.getState().setSnapshot({isDeletePending:!0});try{await ee(e),T(v,e),v.removeQueries({queryKey:[`ncp-session-messages`,e]}),this.streamActionsManager.resetStreamState(),this.clearDeletedSessionState(e),this.uiManager.goToChatRoot({replace:!0})}finally{ak.getState().setSnapshot({isDeletePending:!1})}}}}},QN=class{constructor(){this.chatUiManager=new XN,this.chatStreamActionsManager=new UN,this.chatSessionListManager=new BN(this.chatUiManager,this.chatStreamActionsManager),this.chatInputManager=new zN(this.chatUiManager,this.chatStreamActionsManager,this.chatSessionListManager),this.chatThreadManager=new ZN(this.chatUiManager,this.chatSessionListManager,this.chatStreamActionsManager)}};function $N(e){return e?.trim().toLowerCase()||`native`}function eP(e,t){if(typeof t!=`string`)return!1;let n=t.trim();return n?e.some(e=>e.value===n):!1}function tP(e,t){return typeof t==`string`&&e.includes(t)}function nP(e){return e.length===0?null:e.includes(`off`)?`off`:e[0]??null}function rP(e){let{currentValue:t,selectedSessionPreferredValue:n,fallbackPreferredValue:r,defaultValue:i,isValueSupported:a,firstAvailableValue:o,preferSessionPreferredValue:s=!1,preserveCurrentValueOnSessionChange:c=!1}=e;return a(t)&&(!s||c)?t:a(n)?n:a(r)?r:a(i)?i:o}function iP(e){let{modelOptions:t,currentSelectedModel:n,selectedSessionPreferredModel:r,fallbackPreferredModel:i,defaultModel:a,preferSessionPreferredModel:o,preserveCurrentSelectedModelOnSessionChange:s}=e;return t.length===0?``:rP({currentValue:n,selectedSessionPreferredValue:r,fallbackPreferredValue:i,defaultValue:a,isValueSupported:e=>eP(t,e),firstAvailableValue:t[0]?.value??``,preferSessionPreferredValue:o,preserveCurrentValueOnSessionChange:s})}function aP(e){let{supportedThinkingLevels:t,currentSelectedThinkingLevel:n,selectedSessionPreferredThinking:r,fallbackPreferredThinking:i,defaultThinkingLevel:a,preferSessionPreferredThinking:o,preserveCurrentSelectedThinkingOnSessionChange:s}=e;return t.length===0?null:rP({currentValue:n,selectedSessionPreferredValue:r,fallbackPreferredValue:i,defaultValue:a,isValueSupported:e=>tP(t,e),firstAvailableValue:nP(t)??`off`,preferSessionPreferredValue:o,preserveCurrentValueOnSessionChange:s})}function oP(e){let{sessions:t,selectedSessionKey:n,sessionType:r,readPreference:i}=e,a=$N(r),o,s=-1/0;for(let e of t){if(e.key===n||$N(e.sessionType)!==a)continue;let t=i(e);if(t==null)continue;let r=Date.parse(e.updatedAt),c=Number.isFinite(r)?r:-1/0;(o===void 0||c>s)&&(o=t,s=c)}return o}function sP(e){return e.map(e=>e==null?``:String(e)).join(``)}function cP(e){let{isPreferenceAvailable:t,emptyValue:n,syncKey:r,selectedSessionKey:i,selectedSessionExists:a=!1,setValue:o,resolveValue:s}=e,c=(0,P.useRef)(void 0),l=(0,P.useRef)(s),u=(0,P.useRef)(n);l.current=s,(0,P.useEffect)(()=>{let e=c.current!==i;if(!t){o(n),u.current=n,c.current=i;return}o(t=>{let r=l.current({currentValue:!e&&Object.is(t,u.current)?n:t,sessionChanged:e,preserveCurrentValueOnSessionChange:e&&!!i&&!a});return u.current=r,r}),c.current=i},[n,t,a,i,o,r])}function lP(e){let{modelOptions:t,selectedSessionKey:n,selectedSessionExists:r=!1,selectedSessionPreferredModel:i,fallbackPreferredModel:a,defaultModel:o,setSelectedModel:s}=e;cP({isPreferenceAvailable:t.length>0,emptyValue:``,syncKey:sP([t.map(e=>e.value).join(``),i,a,o]),selectedSessionKey:n,selectedSessionExists:r,setValue:s,resolveValue:({currentValue:e,sessionChanged:n,preserveCurrentValueOnSessionChange:r})=>iP({currentSelectedModel:e,modelOptions:t,selectedSessionPreferredModel:i,fallbackPreferredModel:a,defaultModel:o,preferSessionPreferredModel:n,preserveCurrentSelectedModelOnSessionChange:r})})}function uP(e){let{supportedThinkingLevels:t,selectedSessionKey:n,selectedSessionExists:r=!1,selectedSessionPreferredThinking:i,fallbackPreferredThinking:a,defaultThinkingLevel:o,setSelectedThinkingLevel:s}=e;cP({isPreferenceAvailable:t.length>0,emptyValue:null,syncKey:sP([t.join(``),i,a,o]),selectedSessionKey:n,selectedSessionExists:r,setValue:s,resolveValue:({currentValue:e,sessionChanged:n,preserveCurrentValueOnSessionChange:r})=>aP({currentSelectedThinkingLevel:e,supportedThinkingLevels:t,selectedSessionPreferredThinking:i,fallbackPreferredThinking:a,defaultThinkingLevel:o,preferSessionPreferredThinking:n,preserveCurrentSelectedThinkingOnSessionChange:r})})}export{SO as A,tn as B,Ok as C,rk as D,dk as E,Bn as F,Mn as I,jn as L,Q as M,ID as N,XO as O,zn as P,un as R,Tj as S,lk as T,rM as _,qN as a,Aj as b,CN as c,gM as d,lM as f,tM as g,eM as h,QN as i,xO as j,YO as k,jM as l,$j as m,lP as n,FN as o,nM as p,uP as r,yN as s,oP as t,mM as u,Dj as v,Nk as w,kj as x,Oj as y,on as z};
|
|
59
|
+
`):void 0}function MA(e){let{invocation:t,texts:n}=e,{toolName:r,toolCallId:i,args:a,result:o}=t;if(r!==`spawn`&&r!==`sessions_request`&&r!==`sessions_spawn`)return null;let s=wA(o);if(s){let e=CA(s.status)?.toLowerCase(),t=OA(s,a),o=AA(s),c=CA(s.sessionId),l=Tk({args:a,result:s}),u=c?{kind:`open-session`,sessionId:c,sessionKind:s.isChildSession===!0?`child`:`session`,...l?{agentId:l}:{},...CA(s.title)?{label:s.title.trim()}:{},...CA(s.parentSessionId)?{parentSessionId:s.parentSessionId.trim()}:{}}:void 0;return e===`failed`?{kind:`result`,name:r,detail:t,input:DA(a),text:o,callId:i||void 0,hasResult:!!o,statusTone:`error`,statusLabel:n.toolStatusFailedLabel,...l?{agentId:l}:{},...u?{action:u}:{}}:e===`completed`?{kind:`result`,name:r,detail:t,input:DA(a),text:o,callId:i||void 0,hasResult:!!o,statusTone:`success`,statusLabel:n.toolStatusCompletedLabel,...l?{agentId:l}:{},...u?{action:u}:{}}:{kind:`result`,name:r,detail:t,input:DA(a),text:o,callId:i||void 0,hasResult:!!o,statusTone:`running`,statusLabel:n.toolStatusRunningLabel,...l?{agentId:l}:{},...u?{action:u}:{}}}let c=TA(o);if(!c)return null;let l=kA(c,a),u=jA(c),d=CA(c.sessionId),f=Tk({args:a,result:c}),p=d?{kind:`open-session`,sessionId:d,sessionKind:c.isChildSession===!0?`child`:`session`,...f?{agentId:f}:{},...CA(c.title)?{label:c.title.trim()}:{},...CA(c.parentSessionId)?{parentSessionId:c.parentSessionId.trim()}:{}}:void 0;return{kind:`result`,name:r,detail:l,input:DA(a),text:u,callId:i||void 0,hasResult:!!u,statusTone:`success`,statusLabel:n.toolStatusCompletedLabel,...f?{agentId:f}:{},...p?{action:p}:{}}}function NA(e,t){let n=dk(e.reasoning);return n?{type:`reasoning`,text:n,label:t.reasoningLabel}:null}function PA(e,t){let n=e.mimeType.startsWith(`image/`),r=mk(e.sizeBytes);return{type:`file`,file:{label:typeof e.name==`string`&&e.name.trim()?e.name.trim():n?t.imageAttachmentLabel:t.fileAttachmentLabel,mimeType:e.mimeType,dataUrl:typeof e.url==`string`&&e.url.trim().length>0?e.url.trim():`data:${e.mimeType};base64,${e.data}`,...r==null?{}:{sizeBytes:r},isImage:n}}}function FA(e,t){let n=e.toolInvocation,r=gk(n.result,t);if(r)return r;let i=MA({invocation:n,texts:{toolStatusRunningLabel:t.toolStatusRunningLabel,toolStatusCompletedLabel:t.toolStatusCompletedLabel,toolStatusFailedLabel:t.toolStatusFailedLabel}});if(i)return{type:`tool-card`,card:_k(i,t)};let a=vk({status:n.status,error:n.error,cancelled:n.cancelled,result:n.result,texts:t}),o=xA({toolName:n.toolName,status:n.status,toolCallId:n.toolCallId,args:n.args,parsedArgs:n.parsedArgs,result:n.result}),s=o?.summary??ZO(n.parsedArgs??n.args),c=o?void 0:bk(n.args,n.parsedArgs),l=typeof n.error==`string`&&n.error.trim()?n.error.trim():n.result==null?``:YO(n.result).trim(),u=!n.error&&hk(n.result),d=(!o?.fileOperation||!!n.error)&&!u,f=Tk(n);return{type:`tool-card`,card:_k({kind:a.kind,name:n.toolName,...f?{agentId:f}:{},detail:s,...c?{input:c}:{},text:d&&l?l:void 0,outputData:n.result,callId:n.toolCallId||void 0,hasResult:a.hasResult,statusTone:a.statusTone,statusLabel:a.statusLabel,...o?.fileOperation?{fileOperation:o.fileOperation}:{}},t)}}function IA(e,t){return{type:`unknown`,label:t.unknownPartLabel,rawType:typeof e.type==`string`?e.type:`unknown`,text:YO(e)}}function LA(e){return e.type===`text`&&typeof e.text==`string`}function RA(e){return e.type===`reasoning`&&typeof e.reasoning==`string`}function zA(e){return e.type===`file`&&typeof e.mimeType==`string`&&typeof e.data==`string`}function BA(e){return e.type!==`tool-invocation`||typeof e.toolInvocation!=`object`||e.toolInvocation===null||Array.isArray(e.toolInvocation)?!1:`toolName`in e.toolInvocation&&typeof e.toolInvocation.toolName==`string`}function VA(e){return LA(e.part)?uk(e.part,e.inlineTokens):RA(e.part)?NA(e.part,e.texts):zA(e.part)?PA(e.part,e.texts):BA(e.part)?FA(e.part,e.texts):IA(e.part,e.texts)}function HA(e){let t=e.meta?.timestamp;return t&&Number.isFinite(Date.parse(t))?t:new Date().toISOString()}function UA(e,t){return e===`user`?t.user:e===`assistant`?t.assistant:e===`tool`?t.tool:e===`system`?t.system:t.fallback}function WA(e){return e===`user`||e===`assistant`||e===`tool`||e===`system`?e:`message`}function GA(e,t){return{id:e.id,role:WA(e.role),roleLabel:UA(e.role,t.texts.roleLabels),timestampLabel:t.formatTimestamp(HA(e)),status:e.meta?.status,parts:e.parts.map(n=>VA({part:n,inlineTokens:e.meta?.inlineTokens??[],texts:t.texts})).filter(e=>e!==null)}}var KA=function(e){return e.CALL=`call`,e.RESULT=`result`,e.PARTIAL_CALL=`partial-call`,e.ERROR=`error`,e.CANCELLED=`cancelled`,e}({});function qA(e){if(typeof e!=`string`)return null;let t=e.trim();return t.length>0?t:null}function JA(e){return qA(e)}function YA(e){let t=qA(e);if(!t)return null;let n=t.replace(/[\\/]+$/,``);if(!n)return t;let r=n.split(/[\\/]/).filter(Boolean);return r[r.length-1]??n}function XA(e){return/^[A-Za-z]:[\\/]?$/.test(e)||e===`/`?e:e.replace(/[\\/]+$/,``)}function ZA(e){let t=XA(e.trim().replace(/\\/g,`/`));return/^[A-Za-z]:/.test(t)?`${t.slice(0,1).toLowerCase()}${t.slice(1)}`:t}function QA(e){let t=e.trim().replace(/\\/g,`/`);return t?/^[A-Za-z]:\//.test(t)?{prefix:t.slice(0,2),segments:t.slice(3).split(`/`).filter(Boolean)}:t.startsWith(`/`)?{prefix:`/`,segments:t.slice(1).split(`/`).filter(Boolean)}:{prefix:null,segments:t.split(`/`).filter(Boolean)}:{prefix:null,segments:[]}}function $A(e){let t=ZA(e.path),n=ZA(e.sessionProjectRoot);if(!t||!n)return null;if(!t.startsWith(`/`)&&!/^[A-Za-z]:\//.test(t))return t.split(`/`).filter(Boolean);if(t===n)return[];let r=n.endsWith(`/`)?n:`${n}/`;return t.startsWith(r)?t.slice(r.length).split(`/`).filter(Boolean):null}function ej(e){let{labels:t,leading:n=null}=e,r=t.map((e,n)=>({key:`${n}:${e}`,label:e,kind:n===t.length-1?`file`:`directory`,isCurrent:n===t.length-1}));return n?[n,...r]:r}function tj(e){let{column:t,line:n}=e;return typeof n==`number`?`L${n}${typeof t==`number`?`:${t}`:``}`:null}function nj(e){let{column:t,line:n,path:r,sessionProjectRoot:i,truncated:a}=e,o=r.trim(),s=i?.trim()&&o?$A({path:o,sessionProjectRoot:i}):null,c;if(i?.trim()&&s){let e=YA(i)??i.trim();c=ej({labels:s,leading:{key:`workspace:${e}`,label:e,kind:`workspace`,isCurrent:s.length===0}})}else{let{prefix:e,segments:t}=QA(o);c=ej({labels:t,leading:e?{key:`root:${e}`,label:e,kind:`root`,isCurrent:t.length===0}:null})}return c.length===0&&(c=[{key:`file:unknown`,label:o||`file`,kind:`file`,isCurrent:!0}]),{fullPath:o,locationLabel:tj({line:n,column:t}),truncated:a,segments:c}}var rj=new Set([`off`,`minimal`,`low`,`medium`,`high`,`adaptive`,`xhigh`]);function ij(e){if(typeof e==`string`)return e;try{return JSON.stringify(e??{})}catch{return String(e??``)}}function aj(e){return`${ae}/api/ncp/assets/content?${new URLSearchParams({uri:e}).toString()}`}function oj(e){if(typeof e!=`string`)return null;let t=e.trim();return t.length>0?t:null}function sj(e){let{metadata:t}=e;return!t||typeof t!=`object`||Array.isArray(t)?null:t}function cj(e){let t=sj(e);return t?oj(t.preferred_model)??oj(t.preferredModel)??oj(t.model):null}function lj(e){let t=sj(e);if(!t)return null;let n=oj(t.preferred_thinking)??oj(t.thinking)??oj(t.thinking_level)??oj(t.thinkingLevel);if(!n)return null;let r=n.toLowerCase();return rj.has(r)?r:null}function uj(e){let t=sj(e);return t?oj(t.label):null}function dj(e){let t=sj(e);return t?JA(t.project_root??t.projectRoot):null}function fj(e){let t=sj(e);return t?oj(t.ui_last_read_at):null}function pj(e){let t=sj(e);return t?oj(t.runtime)??oj(t.session_type)??oj(t.sessionType)??`native`:`native`}function mj(e){let t=sj(e);return t?oj(t.parent_session_id)??oj(t.parentSessionId):null}function hj(e){let t=sj(e);return t?oj(t.spawned_by_request_id)??oj(t.spawnedByRequestId):null}function gj(e){let t=sj(e);return t?t.child_session_promoted===!0:!1}function _j(e){if(e.startsWith(`cron:`))return{type:`cron`};if(e.startsWith(`agent:`)){let t=e.split(`:`);if(t.length>=3){let e=t[2];if(e&&e!==`main`&&e!==`direct`)return{channel:e}}}return{}}function vj(e){return e.state===`cancelled`?KA.CANCELLED:e.state===`result`?KA.RESULT:e.state===`partial-call`?KA.PARTIAL_CALL:KA.CALL}function yj(e){let t=[];for(let n of e){if(n.type===`text`){t.push({type:`text`,text:n.text});continue}if(n.type===`rich-text`){t.push({type:`text`,text:n.text});continue}if(n.type===`reasoning`){t.push({type:`reasoning`,reasoning:n.text,details:[]});continue}if(n.type===`source`){t.push({type:`source`,source:{sourceType:`url`,id:n.url??n.title??Math.random().toString(36).slice(2,8),url:n.url??``,...n.title?{title:n.title}:{}}});continue}if(n.type===`file`&&n.contentBase64){t.push({type:`file`,...n.name?{name:n.name}:{},mimeType:n.mimeType??`application/octet-stream`,data:n.contentBase64,...n.url?{url:n.url}:{},...typeof n.sizeBytes==`number`?{sizeBytes:n.sizeBytes}:{}});continue}if(n.type===`file`&&n.url){t.push({type:`file`,...n.name?{name:n.name}:{},mimeType:n.mimeType??`application/octet-stream`,data:``,url:n.url,...typeof n.sizeBytes==`number`?{sizeBytes:n.sizeBytes}:{}});continue}if(n.type===`file`&&n.assetUri){t.push({type:`file`,...n.name?{name:n.name}:{},mimeType:n.mimeType??`application/octet-stream`,data:``,url:aj(n.assetUri),...typeof n.sizeBytes==`number`?{sizeBytes:n.sizeBytes}:{}});continue}if(n.type===`step-start`){t.push({type:`step-start`});continue}n.type===`tool-invocation`&&t.push({type:`tool-invocation`,toolInvocation:{status:vj(n),toolCallId:n.toolCallId??`${n.toolName}-${Math.random().toString(36).slice(2,8)}`,toolName:n.toolName,args:ij(n.args),result:n.result}})}return t}function bj(e){return e===`service`?`system`:e===`tool`?`assistant`:e}function xj(e){return{id:e.id,role:bj(e.role),parts:yj(e.parts),meta:{source:`stream`,status:e.status,sessionKey:e.sessionId,timestamp:e.timestamp}}}function Sj(e){let t=uj(e),n=cj(e),r=lj(e),i=dj(e),a=fj(e),o=oj(e.lastMessageAt),s=YA(i),c=_j(e.sessionId),l=mj(e),u=hj(e),d=gj(e);return{key:e.sessionId,createdAt:e.createdAt??e.updatedAt,updatedAt:e.updatedAt,...o?{lastMessageAt:o}:{},...a?{readAt:a}:{},...typeof e.agentId==`string`&&e.agentId.trim().length>0?{agentId:e.agentId.trim()}:{},...t?{label:t}:{},...c,...n?{preferredModel:n}:{},...r?{preferredThinking:r}:{},...i?{projectRoot:i}:{},...s?{projectName:s}:{},sessionType:pj(e),sessionTypeMutable:!1,isChildSession:!!l,...d?{isPromotedChildSession:d}:{},...l?{parentSessionId:l}:{},...u?{spawnedByRequestId:u}:{},messageCount:e.messageCount}}function Cj(e){return e.map(Sj)}function wj(e){if(typeof e!=`string`)return null;let t=e.trim();return t.length>0?t:null}function Tj(e){if(typeof e!=`number`||!Number.isFinite(e))return null;let t=Math.trunc(e);return t>=0?t:null}function Ej(e){return e===!0}function Dj(e){let t=e;if(!t||typeof t!=`object`||Array.isArray(t))return null;let n=t,r=Tj(n.usedContextTokens),i=Tj(n.totalContextTokens),a=Tj(n.prunedUsedContextTokens),o=wj(n.updatedAt);if(r===null||i===null||a===null||!o)return null;let s=Tj(n.compactedUsedContextTokens);return{usedContextTokens:r,totalContextTokens:i,prunedUsedContextTokens:a,availableContextTokens:Tj(n.availableContextTokens)??Math.max(0,i-r),droppedHistoryCount:Tj(n.droppedHistoryCount)??0,truncatedToolResultCount:Tj(n.truncatedToolResultCount)??0,truncatedSystemPrompt:Ej(n.truncatedSystemPrompt),truncatedUserMessage:Ej(n.truncatedUserMessage),compacted:Ej(n.compacted),...wj(n.checkpointId)?{checkpointId:wj(n.checkpointId)??void 0}:{},compactedMessageCount:Tj(n.compactedMessageCount)??0,...s===null?{}:{compactedUsedContextTokens:s},updatedAt:o}}function Oj(e){let{metadata:t}=e;if(!t||t.nextclaw_timeline_kind!==`context_compaction`)return null;let n=t.checkpoint&&typeof t.checkpoint==`object`&&!Array.isArray(t.checkpoint)?t.checkpoint:null;if(!n)return null;let r=wj(n.id),i=n.status===`compressing`?`compressing`:n.status===`compressed`?`compressed`:null,a=wj(n.summary),o=Tj(n.coveredMessageCount),s=Tj(n.coveredSessionMessageCount),c=Tj(n.originalEstimatedTokens),l=Tj(n.projectedEstimatedTokens),u=wj(n.createdAt),d=wj(n.updatedAt);return!r||!i||!a||o===null||s===null||c===null||l===null||!u||!d?null:{id:r,status:i,summary:a,coveredMessageCount:o,coveredSessionMessageCount:s,originalEstimatedTokens:c,projectedEstimatedTokens:l,createdAt:u,updatedAt:d}}function kj(){return y({queryKey:[`agents`],queryFn:D,staleTime:3e4})}function Aj(){let e=x();return h({mutationFn:({data:e})=>te(e),onSuccess:()=>{e.invalidateQueries({queryKey:[`agents`]}),e.invalidateQueries({queryKey:[`config`]}),p.success(o(`configSavedApplied`))},onError:e=>{p.error(o(`configSaveFailed`)+`: `+e.message)}})}function jj(){let e=x();return h({mutationFn:({agentId:e,data:t})=>C(e,t),onSuccess:()=>{e.invalidateQueries({queryKey:[`agents`]}),e.invalidateQueries({queryKey:[`config`]}),p.success(o(`configSavedApplied`))},onError:e=>{p.error(o(`configSaveFailed`)+`: `+e.message)}})}function Mj(){let e=x();return h({mutationFn:({agentId:e})=>ne(e),onSuccess:()=>{e.invalidateQueries({queryKey:[`agents`]}),e.invalidateQueries({queryKey:[`config`]}),p.success(o(`configSavedApplied`))},onError:e=>{p.error(o(`configSaveFailed`)+`: `+e.message)}})}function Nj(e,t){return new Map([...t,...e].filter(e=>typeof e.id==`string`&&e.id.trim().length>0).map(e=>[e.id,e]))}function Pj(e){let t=e?.trim()??``,n=kO(e=>e.snapshot.availableAgents??[]),r=kj(),i=(0,P.useMemo)(()=>Nj(n,r.data?.agents??[]),[r.data?.agents,n]);return(0,P.useMemo)(()=>{if(!t)return null;let e=i.get(t)??null;return{agentId:t,profile:e,displayName:e?.displayName?.trim()||t,avatarUrl:e?.avatarUrl?.trim()||null}},[i,t])}function Fj({agentId:e,className:t}){let n=Pj(e);return n?(0,N.jsx)(jn,{agentId:n.agentId,displayName:n.displayName,avatarUrl:n.avatarUrl,className:t}):null}var Ij=new WeakMap;function Lj(e){return{roleLabels:{user:o(`chatRoleUser`),assistant:o(`chatRoleAssistant`),tool:o(`chatRoleTool`),system:o(`chatRoleSystem`),fallback:o(`chatRoleMessage`)},reasoningLabel:o(`chatReasoning`),toolCallLabel:o(`chatToolCall`),toolResultLabel:o(`chatToolResult`),toolInputLabel:o(`chatToolInput`),toolNoOutputLabel:o(`chatToolNoOutput`),toolOutputLabel:o(`chatToolOutput`),toolStatusPreparingLabel:o(`chatToolStatusPreparing`),toolStatusRunningLabel:o(`chatToolStatusRunning`),toolStatusCompletedLabel:o(`chatToolStatusCompleted`),toolStatusFailedLabel:o(`chatToolStatusFailed`),toolStatusCancelledLabel:o(`chatToolStatusCancelled`),imageAttachmentLabel:o(`chatImageAttachment`),fileAttachmentLabel:o(`chatFileAttachment`),unknownPartLabel:o(`chatUnknownPart`)}}function Rj(e){return{copyCodeLabel:o(`chatCodeCopy`),copiedCodeLabel:o(`chatCodeCopied`),copyMessageLabel:o(`chatMessageCopy`),copiedMessageLabel:o(`chatMessageCopied`),typingLabel:o(`chatTyping`),attachmentOpenLabel:o(`chatAttachmentOpen`),attachmentAttachedLabel:o(`chatAttachmentAttached`),attachmentCategoryLabels:{archive:o(`chatAttachmentCategoryArchive`),audio:o(`chatAttachmentCategoryAudio`),code:o(`chatAttachmentCategoryCode`),data:o(`chatAttachmentCategoryData`),document:o(`chatAttachmentCategoryDocument`),generic:o(`chatAttachmentCategoryGeneric`),image:o(`chatAttachmentCategoryImage`),pdf:o(`chatAttachmentCategoryPdf`),sheet:o(`chatAttachmentCategorySheet`),video:o(`chatAttachmentCategoryVideo`)}}}function zj({checkpoint:e}){return(0,N.jsxs)(`div`,{className:`my-4 flex items-center gap-3 text-[11px] text-gray-500`,title:[`${o(`chatContextCompactionCoveredMessages`)}: ${e.coveredSessionMessageCount}`,`${o(`chatContextCompactionOriginalTokens`)}: ${e.originalEstimatedTokens}`,`${o(`chatContextCompactionProjectedTokens`)}: ${e.projectedEstimatedTokens}`].join(`
|
|
60
|
+
`),children:[(0,N.jsx)(`div`,{className:`h-px flex-1 bg-gray-200`}),(0,N.jsxs)(`div`,{className:`inline-flex items-center gap-2 rounded-full border border-gray-200 bg-gray-50 px-3 py-1`,children:[e.status===`compressing`?(0,N.jsx)(`span`,{className:`h-1.5 w-1.5 rounded-full bg-gray-400 animate-pulse`}):(0,N.jsx)(`span`,{className:`h-1.5 w-1.5 rounded-full bg-gray-300`}),(0,N.jsx)(`span`,{children:e.status===`compressing`?o(`chatContextCompactionCompressing`):o(`chatContextCompactionCompressed`)})]}),(0,N.jsx)(`div`,{className:`h-px flex-1 bg-gray-200`})]})}function Bj(e){let{normalRawMessages:t,rawMessageId:n,rawMessages:r}=e,i=r.findIndex(e=>e.id===n);return i<0?t.length-1:r.slice(0,i).filter(e=>!Oj(e)).length-1}function Vj(e){let t=e.rawMessages.filter(e=>!Oj(e)),n=e.rawMessages.map(e=>({rawMessageId:e.id,checkpoint:Oj(e)})).filter(e=>!!e.checkpoint).map(n=>({key:n.rawMessageId,checkpoint:n.checkpoint,boundaryIndex:Bj({rawMessages:e.rawMessages,normalRawMessages:t,rawMessageId:n.rawMessageId})})).sort((e,t)=>e.boundaryIndex-t.boundaryIndex),r=[],i=[],a=0,o=e=>{i.length!==0&&(r.push({kind:`messages`,key:e,messages:i}),i=[])};for(t.forEach((t,s)=>{let c=e.messages[s];for(c&&i.push(c);a<n.length&&n[a]?.boundaryIndex<=s;){let e=n[a];o(`messages-before-${e.key}`),r.push({kind:`compaction`,key:e.key,checkpoint:e.checkpoint}),a+=1}});a<n.length;){let e=n[a];o(`messages-before-${e.key}`),r.push({kind:`compaction`,key:e.key,checkpoint:e.checkpoint}),a+=1}return o(`messages-final`),r.length===0&&r.push({kind:`messages`,key:`messages-empty`,messages:[]}),r}function Hj({messages:e,isSending:t,className:n,onToolAction:r,onFileOpen:i}){let{language:a}=ut(),o=(0,P.useMemo)(()=>Lj(a),[a]),s=(0,P.useMemo)(()=>e.flatMap(e=>{if(Oj(e))return[];let t=Ij.get(e);if(t&&t.language===a)return[t.viewModel];let n=xj(e),r=GA({id:n.id,role:n.role,meta:{timestamp:n.meta?.timestamp,status:n.meta?.status,inlineTokens:ik(e.metadata)},parts:n.parts},{formatTimestamp:e=>c(e,a),texts:o});return Ij.set(e,{language:a,viewModel:r}),[r]}),[a,e,o]),l=(0,P.useMemo)(()=>s.some(e=>e.role===`assistant`&&(e.status===`streaming`||e.status===`pending`)),[s]),u=(0,P.useMemo)(()=>Rj(a),[a]),d=(0,P.useMemo)(()=>Vj({rawMessages:e,messages:s}),[s,e]);return(0,N.jsx)(`div`,{className:n,children:d.map((e,n)=>e.kind===`compaction`?(0,N.jsx)(zj,{checkpoint:e.checkpoint},e.key):(0,N.jsx)(tD,{messages:e.messages,isSending:n===d.length-1?t:!1,hasAssistantDraft:l,texts:u,onToolAction:r,onFileOpen:i,renderToolAgent:e=>(0,N.jsx)(Fj,{agentId:e,className:`h-4 w-4 shrink-0`})},e.key))})}function Uj(){let e=x();return async t=>{let{sessionKey:n,patch:r,successMessage:i}=t;try{A(e,await ie(n,r)),await e.invalidateQueries({queryKey:[`ncp-session-skills`,n]}),p.success(i??o(`configSavedApplied`))}catch(e){throw p.error(o(`configSaveFailed`)+`: `+(e instanceof Error?e.message:String(e))),e}}}function Wj(){let e=Uj();return async t=>{let{persistToServer:n,projectRoot:r,sessionKey:i}=t,a=o(r?`chatSessionProjectUpdated`:`chatSessionProjectCleared`);if(!n){Q.getState().setSnapshot({pendingProjectRoot:r,pendingProjectRootSessionKey:i}),p.success(a);return}await e({sessionKey:i,patch:{projectRoot:r},successMessage:a})}}function Gj({icon:e,label:t,onClick:n,disabled:r=!1,destructive:i=!1}){return(0,N.jsxs)(`button`,{type:`button`,className:d(`flex w-full items-center gap-2 rounded-xl px-3 py-2 text-left text-sm transition-colors disabled:cursor-not-allowed disabled:opacity-50`,i?`text-destructive hover:bg-destructive/10`:`text-gray-700 hover:bg-gray-100`),onClick:n,disabled:r,children:[(0,N.jsx)(e,{className:`h-4 w-4 shrink-0`}),(0,N.jsx)(`span`,{children:t})]})}function Kj(e){return y({queryKey:[`server-path-browse`,e.path??null,e.includeFiles??!1],queryFn:()=>re({path:e.path,includeFiles:e.includeFiles}),enabled:e.enabled??!0,staleTime:0})}var qj=P.forwardRef(({className:e,children:t,...n},r)=>(0,N.jsx)(`div`,{ref:r,className:d(`overflow-auto`,e),...n,children:t}));qj.displayName=`ScrollArea`;function Jj({open:e,currentPath:t,isSaving:n,onOpenChange:r,onConfirm:i,title:a,description:s,pathLabel:c,pathPlaceholder:l,confirmLabel:u,hint:d}){let[p,m]=(0,P.useState)(``),[h,_]=(0,P.useState)(null),[v,y]=(0,P.useState)(``);(0,P.useEffect)(()=>{if(!e)return;let n=t?.trim()||null;m(n??``),_(n),y(``)},[t,e]);let b=Kj({path:h,enabled:e});(0,P.useEffect)(()=>{!e||!b.data||p.trim().length===0&&m(b.data.currentPath)},[b.data,p,e]);let x=p.trim(),S=x.length===0||n,C=(0,P.useMemo)(()=>b.error?b.error instanceof Error?b.error.message:String(b.error):null,[b.error]),w=v.trim().toLowerCase(),T=(0,P.useMemo)(()=>{let e=b.data?.entries??[];return w.length===0?e:e.filter(e=>{let t=e.name.toLowerCase(),n=e.path.toLowerCase();return t.includes(w)||n.includes(w)})},[b.data?.entries,w]),E=e=>{_(e),y(``),e&&m(e)};return(0,N.jsx)(pe,{open:e,onOpenChange:e=>{n||r(e)},children:(0,N.jsxs)(ue,{className:`max-h-[85vh] overflow-hidden sm:h-[42rem] sm:max-w-2xl sm:grid-rows-[auto_minmax(0,1fr)]`,children:[(0,N.jsxs)(ce,{children:[(0,N.jsx)(de,{children:a}),s?(0,N.jsx)(fe,{children:s}):null]}),(0,N.jsxs)(`form`,{className:`flex min-h-0 flex-col gap-4`,onSubmit:e=>{e.preventDefault(),!S&&i(x)},children:[(0,N.jsxs)(`div`,{className:`space-y-2`,children:[(0,N.jsx)(f,{htmlFor:`server-path-picker-input`,children:c}),(0,N.jsxs)(`div`,{className:`flex gap-2`,children:[(0,N.jsx)(O,{id:`server-path-picker-input`,value:p,onChange:e=>m(e.target.value),placeholder:l,autoFocus:!0,disabled:n}),(0,N.jsx)(g,{type:`button`,variant:`outline`,onClick:()=>E(x||null),disabled:n,children:o(`openPath`)})]})]}),(0,N.jsxs)(`div`,{className:`flex min-h-0 flex-1 flex-col overflow-hidden rounded-2xl border border-gray-200 bg-gray-50/70`,children:[(0,N.jsxs)(`div`,{className:`flex flex-wrap items-center gap-2 border-b border-gray-200 px-3 py-2`,children:[(0,N.jsxs)(g,{type:`button`,variant:`ghost`,size:`sm`,onClick:()=>E(b.data?.homePath??null),disabled:n||b.isLoading,children:[(0,N.jsx)(tn,{className:`mr-1 h-4 w-4`}),o(`homeDirectory`)]}),(0,N.jsxs)(g,{type:`button`,variant:`ghost`,size:`sm`,onClick:()=>E(b.data?.parentPath??null),disabled:!b.data?.parentPath||n||b.isLoading,children:[(0,N.jsx)(Qt,{className:`mr-1 h-4 w-4`}),o(`parentDirectory`)]}),(0,N.jsxs)(g,{type:`button`,variant:`ghost`,size:`sm`,onClick:()=>{b.refetch()},disabled:n||b.isLoading,children:[(0,N.jsx)(it,{className:`mr-1 h-4 w-4`}),o(`chatRefresh`)]})]}),(0,N.jsxs)(`div`,{className:`border-b border-gray-200 px-3 py-2`,children:[(0,N.jsx)(`div`,{className:`mb-2 text-xs font-medium text-gray-500`,children:o(`currentDirectory`)}),(0,N.jsx)(`div`,{className:`flex flex-wrap items-center gap-1 text-xs text-gray-600`,children:b.data?.breadcrumbs.map((e,t)=>(0,N.jsxs)(`div`,{className:`flex items-center gap-1`,children:[(0,N.jsx)(`button`,{type:`button`,className:`rounded px-1.5 py-0.5 hover:bg-gray-200`,onClick:()=>E(e.path),disabled:n,children:e.label}),t<b.data.breadcrumbs.length-1?(0,N.jsx)(It,{className:`h-3 w-3 text-gray-400`}):null]},e.path))})]}),(0,N.jsx)(`div`,{className:`border-b border-gray-200 px-3 py-2`,children:(0,N.jsxs)(`div`,{className:`relative`,children:[(0,N.jsx)(Oe,{className:`pointer-events-none absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-gray-400`}),(0,N.jsx)(O,{value:v,onChange:e=>y(e.target.value),placeholder:o(`pathPickerSearchPlaceholder`),disabled:n||b.isLoading,className:`pl-9`})]})}),(0,N.jsx)(qj,{className:`min-h-0 flex-1 px-2 py-2`,children:b.isLoading?(0,N.jsx)(`div`,{className:`px-2 py-6 text-sm text-gray-500`,children:o(`loading`)}):C?(0,N.jsxs)(`div`,{className:`px-2 py-4 text-sm text-destructive`,children:[o(`pathBrowseFailed`),`: `,C]}):b.data&&T.length>0?(0,N.jsx)(`div`,{className:`space-y-1`,children:T.map(e=>(0,N.jsxs)(`button`,{type:`button`,className:`flex w-full items-center gap-2 rounded-xl px-3 py-2 text-left text-sm text-gray-700 transition-colors hover:bg-white`,onClick:()=>E(e.path),disabled:n,children:[(0,N.jsx)($e,{className:`h-4 w-4 shrink-0 text-emerald-600`}),(0,N.jsx)(`span`,{className:`truncate`,children:e.name})]},e.path))}):b.data&&b.data.entries.length>0?(0,N.jsx)(`div`,{className:`px-2 py-6 text-sm text-gray-500`,children:o(`pathPickerSearchEmpty`)}):(0,N.jsx)(`div`,{className:`px-2 py-6 text-sm text-gray-500`,children:o(`emptyDirectory`)})})]}),d?(0,N.jsx)(`p`,{className:`text-xs leading-relaxed text-gray-500`,children:d}):null,(0,N.jsxs)(le,{children:[(0,N.jsx)(g,{type:`button`,variant:`outline`,onClick:()=>r(!1),disabled:n,children:o(`cancel`)}),(0,N.jsx)(g,{type:`submit`,disabled:S,children:n?o(`saving`):u})]})]})]})})}function Yj({open:e,currentProjectRoot:t,isSaving:n,onOpenChange:r,onSave:i}){return(0,N.jsx)(Jj,{open:e,currentPath:t,isSaving:n,onOpenChange:r,onConfirm:i,title:o(`chatSessionProjectDialogTitle`),description:o(`chatSessionProjectDialogDescription`),pathLabel:o(`chatSessionProjectPathLabel`),pathPlaceholder:o(`chatSessionProjectPathPlaceholder`),confirmLabel:o(`chatSessionSetProject`),hint:o(`chatSessionProjectUpdateHint`)})}function Xj({sessionKey:e,canDeleteSession:t,isDeletePending:n,projectRoot:r,childSessionCount:i=0,onOpenChildSessions:a,onDeleteSession:s}){let c=Wj(),[l,u]=(0,P.useState)(!1),[d,f]=(0,P.useState)(!1),[p,m]=(0,P.useState)(!1),h=n||p,_=async n=>{let r=t;m(!0);try{await c({sessionKey:e,projectRoot:n,persistToServer:r}),f(!1),u(!1)}finally{m(!1)}};return(0,N.jsxs)(N.Fragment,{children:[i>0&&a?(0,N.jsx)(g,{type:`button`,variant:`ghost`,size:`icon`,className:`rounded-lg shrink-0 text-gray-400 hover:text-gray-700`,"aria-label":o(`chatSessionOpenChildSessions`),title:o(`chatSessionOpenChildSessions`),onClick:a,disabled:h,children:(0,N.jsx)(en,{className:`h-4 w-4`})}):null,(0,N.jsxs)(xt,{open:l,onOpenChange:u,children:[(0,N.jsx)(yt,{asChild:!0,children:(0,N.jsx)(g,{variant:`ghost`,size:`icon`,className:`rounded-lg shrink-0 text-gray-400 hover:text-gray-700`,"aria-label":o(`chatSessionMoreActions`),disabled:h,children:(0,N.jsx)(zt,{className:`h-4 w-4`})})}),(0,N.jsx)(_t,{align:`end`,className:`w-56 p-2`,children:(0,N.jsxs)(`div`,{className:`space-y-1`,children:[(0,N.jsx)(Gj,{icon:Xt,label:o(`chatSessionSetProject`),onClick:()=>{u(!1),f(!0)},disabled:h}),(0,N.jsx)(Gj,{icon:st,label:o(`chatDeleteSession`),onClick:()=>{u(!1),s()},disabled:!t||h,destructive:!0})]})})]}),(0,N.jsx)(Yj,{open:d,currentProjectRoot:r,isSaving:p,onOpenChange:f,onSave:_})]})}function Zj({sessionKey:e,projectName:t,projectRoot:n,persistToServer:r}){let i=Wj(),[a,s]=(0,P.useState)(!1),[c,l]=(0,P.useState)(!1),[u,d]=(0,P.useState)(!1),f=async t=>{d(!0);try{await i({sessionKey:e,projectRoot:t,persistToServer:r}),l(!1),s(!1)}finally{d(!1)}};return(0,N.jsxs)(N.Fragment,{children:[(0,N.jsxs)(xt,{open:a,onOpenChange:s,children:[(0,N.jsx)(yt,{asChild:!0,children:(0,N.jsx)(`button`,{type:`button`,title:n??void 0,className:`min-w-0 max-w-[320px] shrink rounded-full border border-gray-200 bg-gray-100/90 px-2 py-0.5 text-[11px] font-medium text-gray-600 transition-colors hover:border-gray-300 hover:bg-gray-100 disabled:cursor-not-allowed disabled:opacity-60`,"aria-label":o(`chatSessionSetProject`),disabled:u,children:(0,N.jsxs)(`span`,{className:`flex min-w-0 items-center gap-1.5`,children:[(0,N.jsx)(Xt,{className:`h-3.5 w-3.5 shrink-0`}),(0,N.jsx)(`span`,{className:`truncate`,children:t}),(0,N.jsx)(je,{className:`h-3 w-3 shrink-0 opacity-70`})]})})}),(0,N.jsxs)(_t,{align:`start`,className:`w-72 p-2`,children:[(0,N.jsxs)(`div`,{className:`px-3 pb-2 pt-1`,children:[(0,N.jsx)(`div`,{className:`text-[11px] font-medium uppercase tracking-wider text-gray-500`,children:t}),n?(0,N.jsx)(`div`,{className:`mt-1 break-all text-xs text-gray-500`,children:n}):null]}),(0,N.jsxs)(`div`,{className:`space-y-1`,children:[(0,N.jsx)(Gj,{icon:on,label:o(`chatSessionSetProject`),onClick:()=>{s(!1),l(!0)},disabled:u}),(0,N.jsx)(Gj,{icon:$t,label:o(`chatSessionClearProject`),onClick:()=>{f(null)},disabled:u})]})]})]}),(0,N.jsx)(Yj,{open:c,currentProjectRoot:n,isSaving:u,onOpenChange:l,onSave:f})]})}function Qj({parentSessionLabel:e,onGoToParentSession:t}){if(!e)return null;let n=e.trim();return(0,N.jsx)(`div`,{className:`border-b border-gray-200/60 bg-white/75 px-4 py-2 backdrop-blur-sm sm:px-5`,children:(0,N.jsxs)(`button`,{type:`button`,onClick:t,className:`inline-flex items-center gap-2 text-xs font-medium text-gray-600 transition-colors hover:text-gray-900`,children:[(0,N.jsx)(De,{className:`h-3.5 w-3.5`}),(0,N.jsxs)(`span`,{children:[o(`chatBackToParent`),n?` · ${n}`:``]})]})})}function $j({snapshot:e,childSessionCount:t,layoutMode:n,normalizedAgentId:r,sessionHeaderTitle:i,shouldShowHeaderAgentAvatar:a,shouldShowSessionHeader:s,onBackToList:c,onOpenChildSessions:l,onDeleteSession:u}){let f=n===`mobile`;return(0,N.jsxs)(`div`,{className:d(`border-b border-gray-200/60 bg-white/80 backdrop-blur-sm flex items-center justify-between shrink-0 overflow-hidden transition-all duration-200`,f?`px-3 sm:px-3`:`px-4 sm:px-5`,s?`opacity-100`:`h-0 py-0 opacity-0 border-b-0`,s&&(f?`pb-2 pt-2`:`py-3`)),style:f&&s?{paddingTop:`calc(env(safe-area-inset-top, 0px) + 0.5rem)`}:void 0,children:[(0,N.jsxs)(`div`,{className:`min-w-0 flex-1 flex items-center gap-2`,children:[f&&c?(0,N.jsx)(`button`,{type:`button`,onClick:c,className:`inline-flex h-8 w-8 shrink-0 items-center justify-center rounded-full text-gray-600 transition-colors hover:bg-gray-100 hover:text-gray-900`,"aria-label":o(`chat`),children:(0,N.jsx)(De,{className:`h-4 w-4`})}):null,a?(0,N.jsx)(`div`,{className:`inline-flex shrink-0 items-center`,children:(0,N.jsx)(jn,{agentId:r,displayName:e.agentDisplayName,avatarUrl:e.agentAvatarUrl,className:`h-5 w-5`})}):null,(0,N.jsx)(`span`,{className:`text-sm font-medium text-gray-700 truncate`,children:i}),e.sessionTypeLabel?(0,N.jsxs)(`span`,{className:`inline-flex shrink-0 items-center gap-1.5 rounded-full border border-gray-200 bg-gray-100 px-2 py-0.5 text-[11px] font-medium text-gray-600`,children:[e.sessionTypeIcon?.src?(0,N.jsx)(`span`,{className:`inline-flex h-[1.125rem] w-[1.125rem] items-center justify-center`,children:(0,N.jsx)(wn,{icon:{kind:`runtime-image`,src:e.sessionTypeIcon.src,alt:e.sessionTypeIcon.alt??null,name:e.sessionTypeLabel}})}):null,e.sessionTypeLabel]}):null,e.sessionProjectName?(0,N.jsx)(Zj,{sessionKey:e.sessionKey??`draft`,projectName:e.sessionProjectName,projectRoot:e.sessionProjectRoot,persistToServer:e.canDeleteSession}):null]}),e.sessionKey?(0,N.jsx)(Xj,{sessionKey:e.sessionKey,canDeleteSession:e.canDeleteSession,isDeletePending:e.isDeletePending,projectRoot:e.sessionProjectRoot,childSessionCount:t,onOpenChildSessions:l,onDeleteSession:u}):null]})}var eM=`native`;function tM(e){return typeof e==`string`?e.trim().toLowerCase()||`native`:eM}function nM(e,t=eM){return tM(e?.runtime?.trim()||e?.engine?.trim()||t)}function rM(e,t){return e===`native`?o(`chatSessionTypeNative`):t?.trim()||e.trim().split(/[-_]+/g).filter(Boolean).map(e=>e.charAt(0).toUpperCase()+e.slice(1)).join(` `)||e}function iM(e){let t=new Map;for(let n of e){let e=tM(n.value);t.set(e,{value:e,label:n.label?.trim()||rM(e),icon:n.icon??null,ready:n.ready??!0,reason:n.reason??null,reasonMessage:n.reasonMessage??null,supportedModels:n.supportedModels,recommendedModel:n.recommendedModel??null,cta:n.cta??null})}return t.has(`native`)||t.set(eM,{value:eM,label:rM(eM),icon:null,ready:!0,reason:null,reasonMessage:null,supportedModels:void 0,recommendedModel:null,cta:null}),Array.from(t.values()).sort((e,t)=>e.value===`native`?-1:t.value===`native`?1:e.value.localeCompare(t.value))}function aM(e){let{selectedSession:t,pendingSessionType:n,setPendingSessionType:r,sessionTypesData:i}=e,a=(0,P.useMemo)(()=>iM(i?.options??[]),[i?.options]),s=(0,P.useMemo)(()=>{let e=[...a],n=tM(t?.sessionType);return e.some(e=>e.value===n)||e.push({value:n,label:rM(n),icon:null,ready:!0,reason:null,reasonMessage:null,supportedModels:void 0,recommendedModel:null,cta:null}),e.sort((e,t)=>e.value===`native`?-1:t.value===`native`?1:e.value.localeCompare(t.value))},[a,t?.sessionType]),c=(0,P.useMemo)(()=>tM(i?.defaultType??`native`),[i?.defaultType]),l=(0,P.useRef)(null),u=(0,P.useMemo)(()=>tM(t?.sessionType??n??c),[c,n,t?.sessionType]),d=(0,P.useMemo)(()=>s.find(e=>e.value===u)??null,[u,s]);(0,P.useEffect)(()=>{if(t)return;let e=typeof n==`string`?n.trim():``,i=tM(n);(e.length===0||l.current===i||l.current===null&&i===`native`)&&(l.current=c,i!==c&&r(c))},[c,n,t,r]);let f=!t||!!t.sessionTypeMutable,p=(0,P.useMemo)(()=>new Set(a.map(e=>e.value)),[a]);return{sessionTypeOptions:s,selectedSessionTypeOption:d,defaultSessionType:c,selectedSessionType:u,canEditSessionType:f,sessionTypeUnavailable:(0,P.useMemo)(()=>t&&!p.has(tM(t.sessionType))?!0:d?.ready===!1,[p,t,d?.ready]),sessionTypeUnavailableMessage:(0,P.useMemo)(()=>t&&!p.has(tM(t.sessionType))?`${rM(u)} ${o(`chatSessionTypeUnavailableSuffix`)}`:d?.ready===!1?d.reasonMessage?.trim()||`${d.label} setup required`:null,[p,t,u,d])}}var oM=[{key:`hero`,alignmentClassName:`justify-start`,bubbleClassName:`max-w-[78%] h-32 rounded-[30px]`},{key:`follow-up`,alignmentClassName:`justify-start`,bubbleClassName:`max-w-[62%] h-24 rounded-[28px]`},{key:`reply`,alignmentClassName:`justify-end`,bubbleClassName:`max-w-[70%] h-24 rounded-[28px]`},{key:`detail`,alignmentClassName:`justify-start`,bubbleClassName:`max-w-[88%] h-36 rounded-[30px]`}];function sM(){return(0,N.jsxs)(`section`,{"data-testid":`chat-conversation-skeleton`,className:`flex-1 min-h-0 flex flex-col overflow-hidden bg-gradient-to-b from-gray-50/60 to-white`,children:[(0,N.jsx)(`div`,{className:`flex-1 min-h-0 overflow-y-auto custom-scrollbar`,children:(0,N.jsx)(`div`,{className:`mx-auto flex min-h-full w-full max-w-[min(1120px,100%)] flex-col px-6 py-5`,children:(0,N.jsxs)(`div`,{className:`flex flex-1 flex-col gap-8`,children:[(0,N.jsxs)(`div`,{className:`space-y-6`,children:[(0,N.jsx)(Mt,{className:`h-6 w-52 rounded-lg bg-gray-200/90`}),(0,N.jsx)(`div`,{className:`space-y-5`,children:oM.map(e=>(0,N.jsx)(`div`,{className:d(`flex w-full`,e.alignmentClassName),children:(0,N.jsx)(Mt,{"data-testid":`chat-conversation-skeleton-bubble`,className:d(`w-full bg-gray-200/80`,e.bubbleClassName)})},e.key))})]}),(0,N.jsxs)(`div`,{className:`mt-auto grid gap-4 pb-2 sm:grid-cols-[minmax(0,1fr)_minmax(180px,240px)] sm:items-end`,children:[(0,N.jsxs)(`div`,{className:`space-y-3`,children:[(0,N.jsx)(Mt,{className:`h-4 w-40 rounded-full bg-gray-200/70`}),(0,N.jsx)(Mt,{className:`h-[112px] w-full rounded-[30px] bg-gray-200/70`})]}),(0,N.jsx)(`div`,{className:`hidden justify-end sm:flex`,children:(0,N.jsx)(Mt,{className:`h-10 w-36 rounded-full bg-gray-200/75`})})]})]})})}),(0,N.jsx)(`div`,{className:`border-t border-gray-200/80 bg-white p-4`,children:(0,N.jsx)(`div`,{className:`mx-auto w-full max-w-[min(1120px,100%)]`,children:(0,N.jsxs)(`div`,{className:`overflow-hidden rounded-2xl border border-gray-200 bg-white shadow-card`,children:[(0,N.jsx)(`div`,{className:`px-4 py-2.5`,children:(0,N.jsx)(Mt,{className:`h-[84px] w-full rounded-[28px] bg-gray-200/80`})}),(0,N.jsxs)(`div`,{className:`flex items-center justify-between gap-3 px-3 pb-3`,children:[(0,N.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,N.jsx)(Mt,{className:`h-8 w-20 rounded-full bg-gray-200/75`}),(0,N.jsx)(Mt,{className:`h-8 w-28 rounded-full bg-gray-200/75`}),(0,N.jsx)(Mt,{className:`hidden h-8 w-24 rounded-full bg-gray-200/70 sm:block`})]}),(0,N.jsx)(Mt,{className:`h-8 w-8 rounded-full bg-gray-200/85`})]})]})})})]})}function cM({shouldShowProviderHint:e,sessionTypeUnavailable:t,sessionTypeUnavailableMessage:n,onGoToProviders:r}){return(0,N.jsxs)(N.Fragment,{children:[e?(0,N.jsxs)(`div`,{className:`px-4 py-2.5 border-b border-amber-200/70 bg-amber-50/70 flex items-center justify-between gap-3 shrink-0 sm:px-5`,children:[(0,N.jsx)(`span`,{className:`text-xs text-amber-800`,children:o(`chatModelNoOptions`)}),(0,N.jsx)(`button`,{type:`button`,onClick:r,className:`text-xs font-semibold text-amber-900 underline-offset-2 hover:underline`,children:o(`chatGoConfigureProvider`)})]}):null,t&&n?.trim()?(0,N.jsx)(`div`,{className:`px-4 py-2.5 border-b border-amber-200/70 bg-amber-50/70 shrink-0 sm:px-5`,children:(0,N.jsx)(`span`,{className:`text-xs text-amber-800`,children:n})}):null]})}function lM({snapshot:e,availableAgents:t,hideEmptyHint:n,showWelcome:r,threadRef:i,onScroll:a,onCreateSession:s,onSelectAgent:c,onToolAction:l,onFileOpen:u}){return(0,N.jsx)(`div`,{ref:i,onScroll:a,className:`flex-1 min-h-0 overflow-y-auto custom-scrollbar`,children:r?(0,N.jsx)(Ln,{onCreateSession:s,agents:t,selectedAgentId:e.agentId??`main`,onSelectAgent:c}):n?null:e.messages.length===0?(0,N.jsx)(`div`,{className:`px-4 py-4 text-sm text-gray-500 sm:px-5 sm:py-5`,children:o(`chatNoMessages`)}):(0,N.jsx)(`div`,{className:`mx-auto w-full max-w-[min(1120px,100%)] px-4 py-4 sm:px-6 sm:py-5`,children:(0,N.jsx)(Hj,{messages:e.messages,isSending:e.isSending&&e.isAwaitingAssistantOutput,onToolAction:l,onFileOpen:u},e.sessionKey??`draft`)})})}function uM(e,t,n){return e.workspacePanelParentKey===e.sessionKey?t.length>0||n.length>0:!1}function dM({layoutMode:e=`desktop`,onBackToList:t}){let n=Bn(),r=Q(e=>e.snapshot.defaultSessionType),i=kO(e=>e.snapshot),a=(0,P.useRef)(null),s=i.threadRef??a,c=i.childSessionTabs.filter(e=>e.parentSessionKey===i.sessionKey),l=i.workspaceFileTabs.filter(e=>e.parentSessionKey===i.sessionKey),u=uM(i,c,l),d=!!(i.sessionKey||i.sessionTypeLabel),f=i.sessionDisplayName||(i.canDeleteSession&&i.sessionKey?i.sessionKey:null)||o(`chatSidebarNewTask`),p=i.agentId?.trim()??``,m=p.length>0&&p.toLowerCase()!==`main`,h=!i.canDeleteSession&&i.messages.length===0&&!i.isSending,g=i.modelOptions.length>0,_=i.isProviderStateResolved&&!g,v=i.isHistoryLoading&&i.messages.length===0&&!i.isSending&&!i.isAwaitingAssistantOutput,y=i.availableAgents??[],b=e=>y.find(t=>t.id===e)??null,x=()=>{let t=nM(b(i.agentId??`main`),r);n.chatSessionListManager.createSession(t),e===`mobile`&&n.chatUiManager.goToChatRoot()},S=e=>{n.chatSessionListManager.setSelectedAgentId(e),n.chatInputManager.setPendingSessionType(nM(b(e),r))},C=e=>{n.chatThreadManager.openFilePreview(e)},w=()=>{i.sessionKey&&n.chatThreadManager.openChildSessionPanel({parentSessionKey:i.sessionKey,activeChildSessionKey:c[0]?.sessionKey??null})},{onScroll:T}=qT({scrollRef:s,resetKey:i.sessionKey,isLoading:i.isHistoryLoading,hasContent:i.messages.length>0,contentVersion:i.messages[i.messages.length-1]??null});return i.isProviderStateResolved?(0,N.jsxs)(`section`,{className:`flex-1 min-h-0 flex overflow-hidden bg-gradient-to-b from-gray-50/60 to-white`,children:[(0,N.jsxs)(`div`,{className:`flex min-h-0 flex-1 flex-col overflow-hidden`,children:[(0,N.jsx)(Qj,{parentSessionLabel:i.parentSessionKey?i.parentSessionLabel??null:null,onGoToParentSession:n.chatThreadManager.goToParentSession}),(0,N.jsx)($j,{snapshot:i,childSessionCount:c.length,layoutMode:e,normalizedAgentId:p,sessionHeaderTitle:f,shouldShowHeaderAgentAvatar:m,shouldShowSessionHeader:d,onBackToList:t,onOpenChildSessions:w,onDeleteSession:n.chatThreadManager.deleteSession}),(0,N.jsx)(cM,{shouldShowProviderHint:_,sessionTypeUnavailable:i.sessionTypeUnavailable,sessionTypeUnavailableMessage:i.sessionTypeUnavailableMessage??null,onGoToProviders:n.chatThreadManager.goToProviders}),(0,N.jsx)(lM,{snapshot:i,availableAgents:y,hideEmptyHint:v,showWelcome:h,threadRef:s,onScroll:T,onCreateSession:x,onSelectAgent:S,onToolAction:n.chatThreadManager.openSessionFromToolAction,onFileOpen:C}),(0,N.jsx)(WO,{})]}),u?(0,N.jsx)(LN,{childSessionTabs:c,activeChildSessionKey:i.activeChildSessionKey??null,workspaceFileTabs:l,activeWorkspaceFileKey:i.activeWorkspaceFileKey??null,sessionProjectRoot:i.sessionProjectRoot??null,displayMode:e===`mobile`?`overlay`:`docked`,onSelectSession:n.chatThreadManager.selectChildSessionDetail,onSelectFile:n.chatThreadManager.selectWorkspaceFile,onCloseFile:n.chatThreadManager.closeWorkspaceFile,onClose:n.chatThreadManager.closeWorkspacePanel,onBackToParent:n.chatThreadManager.goToParentSession,onToolAction:n.chatThreadManager.openSessionFromToolAction,onFileOpen:C}):null]}):(0,N.jsx)(sM,{})}var fM={connected:{dotClass:`bg-emerald-500`},disconnected:{dotClass:`h-2.5 w-2.5 rounded-full border border-gray-400 bg-transparent`},connecting:{dotClass:`text-amber-600`}};function pM({status:e,className:t}){let n=fM[e],r=o(e===`connected`?`connected`:e===`disconnected`?`disconnected`:`connecting`);return(0,N.jsx)(kt,{delayDuration:250,children:(0,N.jsxs)(jt,{children:[(0,N.jsx)(Tt,{asChild:!0,children:(0,N.jsx)(`span`,{role:`status`,"aria-label":r,className:d(`inline-flex h-5 w-5 items-center justify-center`,t),children:e===`connecting`?(0,N.jsx)(nt,{className:d(`h-3 w-3 animate-spin`,n.dotClass)}):(0,N.jsx)(`span`,{className:d(e===`connected`?`h-2 w-2 rounded-full`:``,n.dotClass)})})}),(0,N.jsx)(Dt,{side:`bottom`,className:`text-xs`,children:r})]})})}function mM(){let e=Uj();return async t=>{await e({sessionKey:t.sessionKey,patch:{label:t.label},successMessage:o(`configSavedApplied`)})}}function hM(){let e=mM(),[t,n]=(0,P.useState)(null),[r,i]=(0,P.useState)(``),[a,o]=(0,P.useState)(null),s=e=>{n(e.key),i(e.label?.trim()??``)},c=()=>{n(null),i(``),o(null)};return{editingSessionKey:t,draftLabel:r,savingSessionKey:a,setDraftLabel:i,startEditingSessionLabel:s,cancelEditingSessionLabel:c,saveSessionLabel:async t=>{let n=r.trim();if(n===(t.label?.trim()??``)){c();return}o(t.key);try{await e({sessionKey:t.key,label:n||null}),c()}catch{o(null)}}}}function gM(e){let t=e.label?.trim();if(t)return t;let n=e.key.split(`:`);return n[n.length-1]||e.key}function _M(e){return e.trim().toLowerCase()}function vM(e,t){let n=_M(t);return n?[e.key,gM(e),e.projectRoot??``,e.projectName??``].map(_M).some(e=>e.includes(n)):!0}function yM(e,t){return e.filter(e=>vM(e,t))}function bM(e){return e.isChildSession?e.isPromotedChildSession===!0:!0}function xM(e={}){let t=DO(e=>e.snapshot.query),n=pt({limit:e.limit??200}),r=(0,P.useMemo)(()=>{let e=n.data?.sessions??[],r=yM(Cj(e).filter(bM),t),i=new Map(e.map(e=>[e.sessionId,e]));return r.map(e=>({session:e,runStatus:i.get(e.key)?.status===`running`?`running`:void 0}))},[t,n.data?.sessions]);return{isLoading:n.isLoading,items:r}}function SM(e){let{item:t,selectedSessionKey:n,optimisticReadAtBySessionKey:r,agentsById:i,childSessionsByParentKey:a,editingSessionKey:o,draftLabel:s,savingSessionKey:c,sessionTitle:l,onSelectSession:u,onOpenChildSessions:d,onStartEditingSessionLabel:f,onDraftLabelChange:p,onSaveSessionLabel:m,onCancelEditingSessionLabel:h}=e,{session:g,runStatus:_}=t,v=Q(e=>e.snapshot),y=n===g.key,b=r[g.key],x=b&&g.readAt?b.localeCompare(g.readAt)>0?b:g.readAt:b??g.readAt,S=a.get(g.key)??[];return(0,N.jsx)(Fn,{session:g,active:y,showUnreadDot:CO({active:y,lastMessageAt:g.lastMessageAt,readAt:x,runStatus:_}),runStatus:_,context:bn(g,v.sessionTypeOptions),title:l(g),agentId:g.agentId??null,agentLabel:g.agentId?i.get(g.agentId)?.displayName??g.agentId:null,agentAvatarUrl:g.agentId?i.get(g.agentId)?.avatarUrl??null:null,childSessionCount:S.length,isEditing:o===g.key,draftLabel:s,isSaving:c===g.key,onSelect:()=>u(g.key),onOpenChildSessions:()=>d(g.key,S[0]?.session.key??null),onStartEditing:()=>f(g),onDraftLabelChange:p,onSave:()=>m(g),onCancel:h})}function CM(e){let t=e.sessionTypeOptions.find(t=>t.value===e.defaultSessionType);return[...t?[t]:[],...e.nonDefaultSessionTypeOptions]}function wM(e){let{query:t,defaultSessionType:n,nonDefaultSessionTypeOptions:r,isCreateMenuOpen:i,onCreateMenuOpenChange:a,onCreateSession:s,onQueryChange:c}=e;return(0,N.jsxs)(N.Fragment,{children:[(0,N.jsx)(`div`,{className:`px-4 pb-3`,children:(0,N.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,N.jsxs)(g,{variant:`primary`,className:d(`min-w-0 rounded-xl`,r.length>0?`flex-1 rounded-r-md`:`w-full`),onClick:()=>{a(!1),s(n)},children:[(0,N.jsx)(rt,{className:`mr-2 h-4 w-4`}),o(`chatSidebarNewTask`)]}),r.length>0?(0,N.jsxs)(xt,{open:i,onOpenChange:a,children:[(0,N.jsx)(yt,{asChild:!0,children:(0,N.jsx)(g,{variant:`primary`,size:`icon`,className:`h-9 w-10 shrink-0 rounded-xl rounded-l-md`,"aria-label":o(`chatSessionTypeLabel`),children:(0,N.jsx)(je,{className:`h-4 w-4`})})}),(0,N.jsxs)(_t,{align:`end`,className:`w-56 rounded-2xl border border-gray-200/80 bg-white p-1.5 shadow-[0_24px_60px_-28px_rgba(15,23,42,0.38)]`,children:[(0,N.jsx)(`div`,{className:`px-3 pb-1 pt-2 text-[10px] font-semibold uppercase tracking-[0.18em] text-gray-400`,children:o(`chatSessionTypeLabel`)}),(0,N.jsx)(`div`,{className:`space-y-1`,children:r.map(e=>(0,N.jsx)(En,{option:e,onSelect:()=>{s(e.value),a(!1)}},e.value))})]})]}):null]})}),(0,N.jsx)(`div`,{className:`px-4 pb-3`,children:(0,N.jsxs)(`div`,{className:`relative`,children:[(0,N.jsx)(Oe,{className:`absolute left-3 top-2.5 h-3.5 w-3.5 text-gray-400`}),(0,N.jsx)(O,{value:t,onChange:e=>c(e.target.value),placeholder:o(`chatSidebarSearchPlaceholder`),className:`h-9 rounded-lg pl-8 text-xs`})]})})]})}function TM(e){let{query:t,defaultSessionType:n,sessionTypeOptions:r,nonDefaultSessionTypeOptions:i,isCreateMenuOpen:a,onCreateMenuOpenChange:s,onCreateSession:c,onQueryChange:l}=e,u=CM({defaultSessionType:n,sessionTypeOptions:r,nonDefaultSessionTypeOptions:i}),d=u.length>1;return(0,N.jsx)(`div`,{className:`px-4 pb-2 pt-1`,children:(0,N.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,N.jsxs)(`div`,{className:`relative min-w-0 flex-1`,children:[(0,N.jsx)(Oe,{className:`absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-gray-400`}),(0,N.jsx)(O,{value:t,onChange:e=>l(e.target.value),placeholder:o(`chatSidebarSearchPlaceholder`),className:`h-9 rounded-full border-transparent bg-gray-100/80 pl-9 pr-3 text-[13px] shadow-none focus:border-gray-200/80 focus:bg-white`})]}),d?(0,N.jsxs)(xt,{open:a,onOpenChange:s,children:[(0,N.jsx)(yt,{asChild:!0,children:(0,N.jsx)(g,{variant:`ghost`,size:`icon`,className:`h-9 w-9 shrink-0 rounded-full bg-gray-100/80 text-gray-700 shadow-none hover:bg-gray-200/80 hover:text-gray-900`,"aria-label":o(`chatSidebarNewTask`),children:(0,N.jsx)(rt,{className:`h-4 w-4`})})}),(0,N.jsxs)(_t,{align:`end`,className:`w-60 rounded-3xl border border-gray-200/80 bg-white p-2 shadow-[0_24px_70px_-30px_rgba(15,23,42,0.45)]`,children:[(0,N.jsx)(`div`,{className:`px-3 pb-1.5 pt-2 text-[11px] font-medium text-gray-400`,children:o(`chatSidebarNewTask`)}),(0,N.jsx)(`div`,{className:`space-y-1`,children:u.map(e=>(0,N.jsx)(En,{option:e,onSelect:()=>{c(e.value),s(!1)}},e.value))})]})]}):(0,N.jsx)(g,{variant:`ghost`,size:`icon`,className:`h-9 w-9 shrink-0 rounded-full bg-gray-100/80 text-gray-700 shadow-none hover:bg-gray-200/80 hover:text-gray-900`,"aria-label":o(`chatSidebarNewTask`),onClick:()=>c(n),children:(0,N.jsx)(rt,{className:`h-4 w-4`})})]})})}function EM(e){return new Date(e.session.lastMessageAt??e.session.createdAt).getTime()}function DM(e){return[...e].sort((e,t)=>EM(t)-EM(e))}function OM(e){let t=new Date,n=new Date(t.getFullYear(),t.getMonth(),t.getDate()).getTime(),r=n-864e5,i=n-7*864e5,a=[],s=[],c=[],l=[];for(let t of e){let e=EM(t);e>=n?a.push(t):e>=r?s.push(t):e>=i?c.push(t):l.push(t)}let u=[];return a.length>0&&u.push({label:o(`chatSidebarToday`),items:a}),s.length>0&&u.push({label:o(`chatSidebarYesterday`),items:s}),c.length>0&&u.push({label:o(`chatSidebarPrevious7Days`),items:c}),l.length>0&&u.push({label:o(`chatSidebarOlder`),items:l}),u}function kM(e){let t=new Map;for(let n of e){let e=n.session.projectRoot?.trim();if(!e)continue;let r=t.get(e),i=EM(n);if(r){r.items.push(n),r.latestUpdatedAt=Math.max(r.latestUpdatedAt,i);continue}t.set(e,{projectRoot:e,projectName:n.session.projectName?.trim()||YA(e)||e,items:[n],latestUpdatedAt:i})}return[...t.values()].map(e=>({...e,items:DM(e.items)})).sort((e,t)=>t.latestUpdatedAt-e.latestUpdatedAt)}function AM(e){let t=new Map;for(let n of e){let e=n.session.parentSessionId?.trim();if(!e)continue;let r=t.get(e)??[];r.push(n),t.set(e,r)}for(let e of t.values())e.sort((e,t)=>EM(t)-EM(e));return t}function jM(e){if(e.label&&e.label.trim())return e.label.trim();let t=e.key.split(`:`);return t[t.length-1]||e.key}var MM=[{target:`/cron`,label:()=>o(`chatSidebarScheduledTasks`),icon:Ee},{target:`/skills`,label:()=>o(`chatSidebarSkills`),icon:ve},{target:`/agents`,label:()=>o(`agentsPageTitle`),icon:me}];function NM(e,t,n){let r=DO(e=>e.optimisticReadAtBySessionKey);return(0,P.useEffect)(()=>{(()=>{if(!t)return;let r=e.find(({session:e})=>e.key===t);if(!r)return;let{session:i}=r;n(i.key,i.lastMessageAt,i.readAt)})()},[e,n,t]),r}function PM({variant:e=`desktop`}){let n=e===`mobile`,r=Bn(),i=lt(),[a,s]=(0,P.useState)(!1),c=Q(e=>e.snapshot),l=DO(e=>e.snapshot),u=S(),f=kj(),{isLoading:p,items:m}=xM(),{language:h,setLanguage:g}=ut(),{theme:_,setTheme:v}=Se(),y=o(ge.find(e=>e.value===_)?.labelKey??`themeWarm`),b=t.find(e=>e.value===h)?.label??h,x=(0,P.useMemo)(()=>new Map((f.data?.agents??[]).map(e=>[e.id,e])),[f.data?.agents]),C=(0,P.useMemo)(()=>DM(m),[m]),w=(0,P.useMemo)(()=>AM(m),[m]),T=(0,P.useMemo)(()=>OM(C),[C]),E=(0,P.useMemo)(()=>kM(C),[C]),D=c.defaultSessionType||`native`,O=(0,P.useMemo)(()=>c.sessionTypeOptions.filter(e=>e.value!==D),[D,c.sessionTypeOptions]),ee=l.listMode===`project-first`,k=NM(m,l.selectedSessionKey,r.chatSessionListManager.markSessionRead),{editingSessionKey:te,draftLabel:A,savingSessionKey:ne,setDraftLabel:j,startEditingSessionLabel:re,cancelEditingSessionLabel:ie,saveSessionLabel:ae}=hM(),oe=e=>{h!==e&&(g(e),window.location.reload())},se=e=>(0,N.jsx)(SM,{item:e,selectedSessionKey:l.selectedSessionKey,optimisticReadAtBySessionKey:k,agentsById:x,childSessionsByParentKey:w,editingSessionKey:te,draftLabel:A,savingSessionKey:ne,sessionTitle:jM,onSelectSession:r.chatSessionListManager.selectSession,onOpenChildSessions:(e,t)=>r.chatThreadManager.openChildSessionPanel({parentSessionKey:e,activeChildSessionKey:t}),onStartEditingSessionLabel:re,onDraftLabelChange:j,onSaveSessionLabel:ae,onCancelEditingSessionLabel:ie},e.session.key),ce=(e,t)=>{r.chatSessionListManager.createSession(e,typeof t==`string`?t:void 0),n&&r.chatUiManager.goToChatRoot()};return(0,N.jsxs)(`aside`,{className:d(`flex h-full min-h-0 flex-col bg-secondary`,n?`flex-1 overflow-hidden`:`w-[280px] shrink-0 border-r border-gray-200/60`),children:[n?null:(0,N.jsx)(`div`,{className:`px-5 pt-5 pb-3`,children:(0,N.jsx)(Te,{className:`flex items-center gap-2.5 min-w-0`,suffix:(0,N.jsx)(pM,{status:u.connectionStatus})})}),n?(0,N.jsx)(TM,{query:l.query,defaultSessionType:D,sessionTypeOptions:c.sessionTypeOptions,nonDefaultSessionTypeOptions:O,isCreateMenuOpen:a,onCreateMenuOpenChange:s,onCreateSession:ce,onQueryChange:r.chatSessionListManager.setQuery}):(0,N.jsx)(wM,{query:l.query,defaultSessionType:D,sessionTypeOptions:c.sessionTypeOptions,nonDefaultSessionTypeOptions:O,isCreateMenuOpen:a,onCreateMenuOpenChange:s,onCreateSession:ce,onQueryChange:r.chatSessionListManager.setQuery}),n?null:(0,N.jsx)(`div`,{className:`px-3 pb-2`,children:(0,N.jsx)(`ul`,{className:`space-y-0.5`,children:MM.map(e=>(0,N.jsx)(`li`,{children:(0,N.jsx)(he,{to:e.target,label:e.label(),icon:e.icon,density:`compact`})},e.target))})}),n?null:(0,N.jsx)(`div`,{className:`mx-4 border-t border-gray-200/60`}),(0,N.jsxs)(`div`,{className:`flex items-center justify-between px-5 pb-2 pt-3`,children:[(0,N.jsx)(`div`,{className:`text-[11px] font-medium uppercase tracking-wider text-gray-400`,children:o(`chatSidebarTaskRecords`)}),(0,N.jsx)(dn,{isProjectFirstView:ee,onSelectMode:r.chatSessionListManager.setListMode})]}),(0,N.jsx)(`div`,{className:`flex-1 min-h-0 overflow-y-auto custom-scrollbar px-3 py-2`,children:p?(0,N.jsx)(`div`,{className:`text-xs text-gray-500 p-3`,children:o(`sessionsLoading`)}):ee?E.length===0?(0,N.jsxs)(`div`,{className:`p-4 text-center`,children:[(0,N.jsx)(nn,{className:`h-6 w-6 mx-auto mb-2 text-gray-300`}),(0,N.jsx)(`div`,{className:`text-xs text-gray-500`,children:o(`chatSidebarProjectViewEmpty`)})]}):(0,N.jsx)(On,{groups:E,defaultSessionType:D,sessionTypeOptions:c.sessionTypeOptions,renderSessionItem:se,onCreateSession:ce}):T.length===0?(0,N.jsxs)(`div`,{className:`p-4 text-center`,children:[(0,N.jsx)(nn,{className:`h-6 w-6 mx-auto mb-2 text-gray-300`}),(0,N.jsx)(`div`,{className:`text-xs text-gray-500`,children:o(`sessionsEmpty`)})]}):(0,N.jsx)(`div`,{className:`space-y-3`,children:T.map(e=>(0,N.jsxs)(`div`,{children:[(0,N.jsx)(`div`,{className:`px-2 py-1 text-[11px] font-medium text-gray-400 uppercase tracking-wider`,children:e.label}),(0,N.jsx)(`div`,{className:`space-y-0.5`,children:e.items.map(se)})]},e.label))})}),n?null:(0,N.jsxs)(`div`,{className:`px-3 py-3 border-t border-gray-200/60 space-y-0.5`,children:[(0,N.jsx)(he,{to:`/settings`,label:o(`settings`),icon:at,density:`compact`}),(0,N.jsx)(we,{onClick:()=>i.open(void 0,{kind:`docs`,newTab:!0,title:`Docs`}),icon:ke,label:o(`docBrowserHelp`),density:`compact`}),(0,N.jsx)(be,{value:_,onValueChange:e=>v(e),icon:Ce,label:o(`theme`),valueLabel:y,density:`compact`,children:ge.map(e=>(0,N.jsx)(Ke,{value:e.value,className:`text-xs`,children:o(e.labelKey)},e.value))}),(0,N.jsx)(be,{value:h,onValueChange:e=>oe(e),icon:ye,label:o(`language`),valueLabel:b,density:`compact`,children:t.map(e=>(0,N.jsx)(Ke,{value:e.value,className:`text-xs`,children:e.label},e.value))})]})]})}function FM({tone:e=`neutral`,value:t}){return(0,N.jsx)(`span`,{className:d(`inline-flex h-5 items-center rounded-sm border px-1.5 text-[10px] font-medium leading-none`,e===`warning`?`border-amber-200 bg-amber-50 text-amber-700`:`border-gray-200 bg-gray-50 text-gray-500`),children:t})}function IM({breadcrumb:e}){return(0,N.jsx)(`div`,{"data-testid":`workspace-file-breadcrumbs`,title:e.fullPath,className:`workspace-horizontal-scrollbar overflow-x-auto overflow-y-hidden border-b border-gray-200/80 bg-gray-50/55`,children:(0,N.jsxs)(`div`,{"data-testid":`workspace-file-breadcrumb-scroll`,className:`flex min-w-max items-center gap-2.5 px-3 py-1.5`,children:[(0,N.jsx)(`div`,{className:`flex min-w-0 flex-1 items-center gap-1 pr-1`,children:e.segments.map((t,n)=>(0,N.jsxs)(P.Fragment,{children:[(0,N.jsxs)(`span`,{className:d(`inline-flex h-5 items-center gap-1 rounded-sm px-1 text-[11px] leading-none`,t.kind===`workspace`?`bg-primary/8 text-primary`:t.isCurrent?`bg-gray-200/70 text-gray-900`:`text-gray-500`),children:[t.kind===`workspace`?(0,N.jsx)(Zt,{className:`h-3 w-3 shrink-0`}):t.isCurrent?(0,N.jsx)(Ht,{className:`h-3 w-3 shrink-0`}):null,(0,N.jsx)(`span`,{children:t.label})]}),n<e.segments.length-1?(0,N.jsx)(It,{className:`h-3 w-3 shrink-0 text-gray-300`}):null]},t.key))}),e.locationLabel||e.truncated?(0,N.jsxs)(`div`,{className:`flex shrink-0 flex-wrap items-center justify-end gap-1`,children:[e.locationLabel?(0,N.jsx)(FM,{value:e.locationLabel}):null,e.truncated?(0,N.jsx)(FM,{tone:`warning`,value:o(`chatWorkspacePreviewTruncated`)}):null]}):null]})})}function LM(e){let t=e.path?.trim()??``;return y({queryKey:[`server-path-read`,t,e.basePath??null],queryFn:()=>k({path:t,basePath:e.basePath}),enabled:(e.enabled??!0)&&t.length>0,staleTime:0})}function RM(e){return e.serverKind?e.serverKind:/\.mdx?$/i.test(e.path)?`markdown`:`text`}function zM(e){let{line:t,path:n,text:r}=e,i=t??1;return{key:`preview:${n}`,path:n,display:`preview`,lines:Mk({text:r,kind:`context`,oldStartLine:i,newStartLine:i}),rawText:r,oldStartLine:i,newStartLine:i}}function BM(e){if(Array.isArray(e.fullLines)&&e.fullLines.length>0)return{key:`diff:${e.key}`,path:e.path,display:`diff`,lines:e.fullLines,fullLines:e.fullLines,...e.beforeText?{beforeText:e.beforeText}:{},...e.afterText?{afterText:e.afterText}:{},...e.patchText?{patchText:e.patchText}:{},...typeof e.oldStartLine==`number`?{oldStartLine:e.oldStartLine}:{},...typeof e.newStartLine==`number`?{newStartLine:e.newStartLine}:{}};if(e.beforeText==null&&e.afterText==null)return null;let t=Ik({beforeText:e.beforeText??``,afterText:e.afterText??``,oldStartLine:e.oldStartLine??void 0,newStartLine:e.newStartLine??void 0});return{key:`diff:${e.key}`,path:e.path,display:`diff`,lines:t,fullLines:t,...e.beforeText?{beforeText:e.beforeText}:{},...e.afterText?{afterText:e.afterText}:{},...typeof e.oldStartLine==`number`?{oldStartLine:e.oldStartLine}:{},...typeof e.newStartLine==`number`?{newStartLine:e.newStartLine}:{}}}function VM({text:e,tone:t=`muted`}){return(0,N.jsx)(`div`,{className:d(`flex h-full items-center justify-center px-6 text-center text-sm`,t===`error`?`text-rose-600`:`text-gray-500`),children:e})}function HM({diffBlock:e}){return e?(0,N.jsx)(UM,{block:e}):(0,N.jsx)(VM,{text:o(`chatWorkspaceDiffEmpty`)})}function UM({block:e}){return(0,N.jsx)(`div`,{className:`h-full overflow-auto custom-scrollbar bg-white`,children:(0,N.jsx)(vE,{block:e,layout:`workspace`})})}function WM({onFileOpen:e,previewBlock:t,previewKind:n,previewQuery:r,previewText:i}){return r.isLoading&&!t?(0,N.jsx)(VM,{text:o(`chatWorkspaceLoadingFile`)}):r.data?.kind===`binary`?(0,N.jsx)(VM,{text:o(`chatWorkspacePreviewUnsupported`)}):r.error&&!t?(0,N.jsx)(VM,{tone:`error`,text:r.error instanceof Error?r.error.message:String(r.error)}):n===`markdown`&&i?(0,N.jsx)(`div`,{className:`h-full overflow-auto custom-scrollbar px-5 py-4`,children:(0,N.jsx)(cT,{text:i,role:`assistant`,texts:{copyCodeLabel:o(`chatCodeCopy`),copiedCodeLabel:o(`chatCodeCopied`)},onFileOpen:e})}):t?(0,N.jsx)(UM,{block:t}):(0,N.jsx)(VM,{text:o(`chatWorkspacePreviewEmpty`)})}function GM({file:e,sessionProjectRoot:t,onFileOpen:n}){let r=e.viewMode===`preview`,i=LM({path:e.path,basePath:t,enabled:r}),a=(0,P.useMemo)(()=>e.viewMode===`diff`?BM(e):null,[e]),o=r?i.data?.text??e.rawText??null:null,s=RM({path:i.data?.resolvedPath??e.path,serverKind:i.data?.kind}),c=(0,P.useMemo)(()=>!r||!o?null:zM({path:i.data?.resolvedPath??e.path,text:o,line:e.line}),[e.line,e.path,r,i.data?.resolvedPath,o]),l=i.data?.resolvedPath??e.path,u=!!i.data?.truncated;return(0,N.jsxs)(`div`,{className:`flex h-full min-h-0 flex-col bg-white`,children:[(0,N.jsx)(IM,{breadcrumb:(0,P.useMemo)(()=>nj({path:l,sessionProjectRoot:t,line:e.line,column:e.column,truncated:u}),[e.column,e.line,u,l,t])}),(0,N.jsx)(`div`,{className:`flex-1 min-h-0 overflow-hidden`,children:e.viewMode===`diff`?(0,N.jsx)(HM,{diffBlock:a}):(0,N.jsx)(WM,{onFileOpen:n,previewBlock:c,previewKind:s,previewQuery:i,previewText:o})})]})}function KM(e,t){return e.label?.trim()?e.label.trim():t?gM(t):e.sessionKey}function qM(e){let t=pt({limit:200}),n=(0,P.useMemo)(()=>t.data?.sessions??[],[t.data?.sessions]),r=(0,P.useMemo)(()=>{let e=Cj(n);return new Map(e.map(e=>[e.key,e]))},[n]),i=(0,P.useMemo)(()=>new Map(n.map(e=>[e.sessionId,e])),[n]);return(0,P.useMemo)(()=>e.map(e=>{let t=r.get(e.sessionKey)??null,n=i.get(e.sessionKey)??null,a=e.agentId?.trim()||t?.agentId||null;return{sessionKey:e.sessionKey,parentSessionKey:e.parentSessionKey,title:KM(e,t),agentId:a,updatedAt:t?.updatedAt??null,lastMessageAt:t?.lastMessageAt??null,readAt:t?.readAt??null,runStatus:n?.status===`running`?`running`:void 0,sessionTypeLabel:t?.sessionType?rM(t.sessionType):null,preferredModel:t?.preferredModel?.trim()||null,projectName:t?.projectName?.trim()||null,projectRoot:t?.projectRoot?.trim()||null}}),[r,i,e])}function JM(e){let t=e.split(/\r?\n/),n=`message`,r=[];for(let e of t){let t=e.trimEnd();if(!(!t||t.startsWith(`:`))){if(t.startsWith(`event:`)){n=t.slice(6).trim()||`message`;continue}t.startsWith(`data:`)&&r.push(t.slice(5).trimStart())}}return r.length===0?null:{event:n,data:r.join(`
|
|
61
|
+
`)}}async function*YM(e){let t=e.getReader(),n=new TextDecoder,r=``;try{for(;;){let{value:e,done:i}=await t.read();if(i)break;r+=n.decode(e,{stream:!0});let{frames:a,rest:o}=XM(r);r=o;for(let e of a)yield e}r+=n.decode();let{frames:e}=XM(r,!0);for(let t of e)yield t}finally{t.releaseLock()}}function XM(e,t=!1){let n=e.split(/\r?\n\r?\n/),r=n.pop()??``,i=[];for(let e of n){let t=JM(e);t&&i.push(t)}if(t&&r.trim()){let e=JM(r);return e&&i.push(e),{frames:i,rest:``}}return{frames:i,rest:r}}var ZM=`/ncp/agent`,QM=class extends Error{ncpError;alreadyPublished;constructor(e,t=!1){super(e.message),this.name=`NcpHttpAgentClientError(${e.code})`,this.ncpError=e,this.alreadyPublished=t}};function $M(e){let t=e.trim();if(!t)throw Error(`NcpHttpAgentClient requires a non-empty baseUrl.`);return new URL(t)}function eN(e){if(e)return e;if(typeof globalThis.fetch==`function`)return globalThis.fetch.bind(globalThis);throw Error(`No fetch implementation found. Pass options.fetchImpl explicitly.`)}function tN(e){let t=(e??`/ncp/agent`).trim();if(!t)return ZM;let n=t.startsWith(`/`)?t:`/${t}`;return n.endsWith(`/`)?n.slice(0,-1):n}async function nN(e){try{return(await e.text()).trim()}catch{return``}}function rN(e){if(sN(e))return e.ncpError;if(aN(e))return e;let t=e instanceof Error?e.message:String(e??`Unknown error`);return{code:lN(void 0),message:t,...e instanceof Error&&e.stack?{details:{stack:e.stack}}:{}}}function iN(e,t={}){return new QM(e,t.alreadyPublished??!1)}function aN(e){return oN(e)&&typeof e.code==`string`&&typeof e.message==`string`}function oN(e){return!!e&&typeof e==`object`&&!Array.isArray(e)}function sN(e){return e instanceof QM}var cN={"config-error":`config-error`,"auth-error":`auth-error`,"runtime-error":`runtime-error`,"timeout-error":`timeout-error`,"abort-error":`abort-error`};function lN(e){if(!e)return`runtime-error`;let t=cN[e];if(t)return t;let n=e.toLowerCase();return n.includes(`timeout`)?`timeout-error`:n.includes(`abort`)||n.includes(`cancel`)?`abort-error`:n.includes(`auth`)?`auth-error`:n.includes(`config`)?`config-error`:`runtime-error`}function uN(e){let t=fN(e);return!t||typeof t.type!=`string`||!t.type.trim()?null:t}function dN(e){let t=fN(e);if(!t)return{code:`runtime-error`,message:e||`Unknown stream error.`};let n=typeof t.code==`string`?t.code:void 0,r=lN(n),i=oN(t.details)?t.details:{};return n&&n!==r&&(i.originalCode=n),{code:r,message:typeof t.message==`string`&&t.message?t.message:`Unknown stream error.`,...Object.keys(i).length>0?{details:i}:{}}}function fN(e){try{let t=JSON.parse(e);return oN(t)?t:null}catch{return null}}var pN=[`text`,`file`,`source`,`step-start`,`reasoning`,`tool-invocation`,`card`,`rich-text`,`action`,`extension`],mN=class{manifest;baseUrl;basePath;fetchImpl;defaultHeaders;subscribers=new Set;activeControllers=new Set;started=!1;constructor(e){this.baseUrl=$M(e.baseUrl),this.basePath=tN(e.basePath),this.fetchImpl=eN(e.fetchImpl),this.defaultHeaders=e.headers??{},this.manifest={endpointKind:`custom`,endpointId:e.endpointId?.trim()||`ncp-http-agent-client`,version:`0.1.0`,supportsStreaming:!0,supportsAbort:!0,supportsProactiveMessages:!1,supportsLiveSessionStream:!0,supportedPartTypes:pN,expectedLatency:`seconds`,metadata:{transport:`http+sse`,scope:`agent`}}}async start(){this.started||(this.started=!0,this.publish({type:nD.EndpointReady}))}async stop(){if(this.started){this.started=!1;for(let e of this.activeControllers)e.abort();this.activeControllers.clear()}}async emit(e){switch(e.type){case`message.request`:await this.send(e.payload);return;case`message.stream-request`:await this.stream(e.payload);return;case`message.abort`:await this.abort(e.payload);return;default:this.publish(e);return}}subscribe(e){return this.subscribers.add(e),()=>{this.subscribers.delete(e)}}async send(e){await this.ensureStarted(),await this.streamRequest({path:`/send`,method:`POST`,body:e})}async stream(e){await this.ensureStarted();let t=new URLSearchParams({sessionId:e.sessionId});await this.streamRequest({path:`/stream?${t.toString()}`,method:`GET`})}async abort(e){await this.ensureStarted();let t=new AbortController;this.activeControllers.add(t);try{let n=await this.fetchImpl(this.resolveUrl(`/abort`),{method:`POST`,headers:{...this.defaultHeaders,"content-type":`application/json`,accept:`application/json`},body:JSON.stringify(e),signal:t.signal});if(!n.ok)throw Error(`Abort request failed with HTTP ${n.status}: ${await nN(n)}`)}catch(e){if(t.signal.aborted)return;let n=rN(e);throw this.publish({type:nD.EndpointError,payload:n}),iN(n)}finally{this.activeControllers.delete(t)}}async ensureStarted(){this.started||await this.start()}publish(e){for(let t of this.subscribers)t(e)}resolveUrl(e){return new URL(`${this.basePath}${e}`,this.baseUrl)}async streamRequest(e){let t=new AbortController;this.activeControllers.add(t);try{let n=await this.fetchImpl(this.resolveUrl(e.path),{method:e.method,headers:{...this.defaultHeaders,accept:`text/event-stream`,...e.body===void 0?{}:{"content-type":`application/json`}},body:e.body===void 0?void 0:JSON.stringify(e.body),signal:t.signal});if(!n.ok)throw Error(`NCP stream request failed with HTTP ${n.status}: ${await nN(n)}`);if(!n.body)throw Error(`NCP stream response has no body.`);for await(let e of YM(n.body)){if(t.signal.aborted)return;this.handleSseFrame(e)}}catch(e){if(t.signal.aborted)return;if(sN(e))throw e;let n=rN(e);throw this.publish({type:nD.EndpointError,payload:n}),iN(n)}finally{this.activeControllers.delete(t)}}handleSseFrame(e){if(e.event===`ncp-event`){let t=uN(e.data);if(!t){this.publish({type:nD.EndpointError,payload:{code:`runtime-error`,message:`Received malformed ncp-event frame.`}});return}this.publish(t);return}if(e.event===`error`){let t=dN(e.data);throw this.publish({type:nD.EndpointError,payload:t}),iN(t,{alreadyPublished:!0})}}};function hN(e){return typeof e==`string`?e:e instanceof URL?e.toString():e.url}function gN(e){if(e instanceof Error){let t=e.name?.trim(),n=e.message?.trim();return t&&n?`${t}: ${n}`:n||t||`Unknown Error`}return String(e??`Unknown error`)}function _N(e,t){let n=Error(e);return t!==void 0&&(n.cause=t),n}function vN(){return async(e,t)=>{try{return await fetch(e,{credentials:`include`,...t})}catch(n){throw se.reportTransportFailure(gN(n)),_N(`NCP fetch failed for ${(t?.method||`GET`).toUpperCase()} ${hN(e)}: ${gN(n)}`,n)}}}var yN=300,bN=`ncp agent unavailable during startup`;function xN(e){return e instanceof Error?e.message.includes(`ncp session not found:`):!1}function SN(e){return e?.trim().toLowerCase().includes(bN)??!1}function CN(){return new mN({baseUrl:ae,basePath:`/api/ncp/agent`,fetchImpl:vN()})}async function wN(e,t,n=yN){t.throwIfAborted();try{let r=await E(e,n);return t.throwIfAborted(),{messages:r.messages,status:r.status??`idle`,contextWindow:r.contextWindow??null}}catch(e){if(t.throwIfAborted(),!xN(e))throw e;return{messages:[],status:`idle`}}}function TN(e,t){let n=(0,P.useRef)(null),r=(0,P.useCallback)(e=>{if(!e){n.current=null;return}n.current!==e&&(n.current=e,t())},[t]);(0,P.useEffect)(()=>{r(e)},[e,r])}function EN(e,t={}){let[n]=(0,P.useState)(()=>CN()),r=S(),[i,a]=(0,P.useState)(0),[o,s]=(0,P.useState)(null),c=t.messageLimit??yN;(0,P.useEffect)(()=>{s(null)},[e]);let l=PD({sessionId:e,client:n,loadSeed:(0,P.useCallback)(async(e,t)=>{let n=await wN(e,t,c);return t.aborted||s(n.contextWindow??null),{messages:n.messages,status:n.status}},[i,c])}),u=l.hydrateError?.message??l.snapshot.error?.message??null;return TN(e&&r.phase===`ready`&&SN(u)?`${e}:${r.lastReadyAt??0}`:null,()=>{a(e=>e+1)}),(0,P.useMemo)(()=>({...l,snapshot:{...l.snapshot,contextWindow:l.snapshot.contextWindow??o}}),[l,o])}function DN(e){return e.label?.trim()||e.path.split(`/`).filter(Boolean).pop()||e.path}function ON(e){let{activeChildSessionKey:t,activeWorkspaceFileKey:n,childSessionTabs:r,workspaceFileTabs:i}=e;if(n){let e=i.find(e=>e.key===n);if(e)return{kind:`file`,file:e}}if(t){let e=r.find(e=>e.sessionKey===t);if(e)return{kind:`child-session`,tab:e}}return r[0]?{kind:`child-session`,tab:r[0]}:i[0]?{kind:`file`,file:i[0]}:null}function kN({agentId:e,kind:t}){return t===`file`?(0,N.jsx)(Ht,{className:`h-3.5 w-3.5 shrink-0 text-gray-400`}):e?(0,N.jsx)(Fj,{agentId:e,className:`h-3.5 w-3.5 shrink-0`}):(0,N.jsx)(nn,{className:`h-3.5 w-3.5 shrink-0 text-gray-400`})}function AN({tab:e}){return(0,N.jsx)(kt,{delayDuration:250,children:(0,N.jsxs)(jt,{children:[(0,N.jsx)(Tt,{asChild:!0,children:(0,N.jsxs)(`div`,{className:d(`group flex max-w-[180px] min-w-0 items-center gap-1.5 border-r border-gray-200/70 border-b-2 px-2.5 py-2 transition-colors`,e.active?`border-b-primary bg-white text-gray-900`:`border-b-transparent bg-gray-50/85 text-gray-500 hover:bg-gray-100`),children:[(0,N.jsxs)(`button`,{type:`button`,onClick:e.onSelect,className:`flex min-w-0 flex-1 items-center gap-1.5 text-left`,children:[(0,N.jsx)(kN,{kind:e.kind,agentId:e.agentId}),(0,N.jsx)(`span`,{className:`min-w-0 truncate text-[12px] font-medium`,children:e.title}),e.kind===`file`&&e.viewMode===`diff`?(0,N.jsx)(`span`,{className:`shrink-0 rounded border border-amber-200 bg-amber-50 px-1 py-0 text-[9px] font-medium uppercase tracking-[0.08em] text-amber-700`,children:o(`chatWorkspaceDiff`)}):null,e.showUnreadDot?(0,N.jsx)(`span`,{"aria-label":o(`chatSessionUnread`),className:`h-2 w-2 shrink-0 rounded-full bg-primary`}):null]}),e.onClose?(0,N.jsx)(`button`,{type:`button`,onClick:t=>{t.stopPropagation(),e.onClose?.()},className:d(`rounded p-0.5 text-gray-400 transition-colors hover:bg-gray-200 hover:text-gray-700`,e.active?`opacity-100`:`opacity-0 group-hover:opacity-100`),"aria-label":o(`chatWorkspaceCloseFile`),children:(0,N.jsx)(ct,{className:`h-3 w-3`})}):null]})}),(0,N.jsx)(Dt,{side:`bottom`,className:`max-w-[320px] text-xs`,children:e.tooltip})]})})}function jN({tabs:e}){return(0,N.jsx)(`div`,{"data-testid":`workspace-tabs-bar`,className:`workspace-horizontal-scrollbar overflow-x-auto overflow-y-hidden border-b border-gray-200/70 bg-gray-50/85`,children:(0,N.jsx)(`div`,{"data-testid":`workspace-tabs-scroll`,className:`flex min-w-max items-stretch`,children:e.map(e=>(0,N.jsx)(AN,{tab:e},e.key))})})}function MN({sessionKey:e,onToolAction:t,onFileOpen:n}){let r=EN(e),i=r.visibleMessages,a=(0,P.useRef)(null),{onScroll:s}=qT({scrollRef:a,resetKey:e,isLoading:r.isHydrating,hasContent:i.length>0,contentVersion:i[i.length-1]??null,stickyThresholdPx:20});return(0,N.jsx)(`div`,{ref:a,onScroll:s,className:`h-full overflow-y-auto custom-scrollbar`,children:r.isHydrating?(0,N.jsxs)(`div`,{className:`flex h-full items-center justify-center text-sm text-gray-500`,children:[(0,N.jsx)(nt,{className:`mr-2 h-4 w-4 animate-spin`}),o(`chatChildSessionLoading`)]}):r.hydrateError?(0,N.jsx)(`div`,{className:`px-4 py-5 text-sm text-rose-600`,children:r.hydrateError.message}):i.length===0&&!r.isRunning?(0,N.jsx)(`div`,{className:`px-4 py-5 text-sm text-gray-500`,children:o(`chatChildSessionEmpty`)}):(0,N.jsx)(`div`,{className:`px-4 py-5`,children:(0,N.jsx)(Hj,{messages:i,isSending:r.isRunning,onToolAction:t,onFileOpen:n})})})}function NN({value:e}){return(0,N.jsx)(`span`,{className:`inline-flex max-w-full items-center rounded border border-gray-200 bg-gray-50 px-2 py-0.5 text-[10px] font-medium text-gray-600`,children:(0,N.jsx)(`span`,{className:`truncate`,children:e})})}function PN({tab:e}){let t=[e.sessionTypeLabel,e.preferredModel,e.projectName].filter(e=>!!e?.trim());return t.length===0&&!e.projectRoot?null:(0,N.jsxs)(`div`,{className:`mt-3 space-y-2`,children:[t.length>0?(0,N.jsx)(`div`,{className:`flex flex-wrap gap-1.5`,children:t.map(e=>(0,N.jsx)(NN,{value:e},e))}):null,e.projectRoot?(0,N.jsx)(`div`,{title:e.projectRoot,className:`truncate rounded border border-gray-200 bg-gray-50 px-2 py-1.5 font-mono text-[11px] text-gray-500`,children:e.projectRoot}):null]})}function FN({tab:e}){return(0,N.jsxs)(`div`,{className:`border-b border-gray-200/70 px-4 py-3`,children:[(0,N.jsxs)(`div`,{className:`flex min-w-0 items-center gap-2 text-sm font-semibold text-gray-900`,children:[e.agentId?(0,N.jsx)(Fj,{agentId:e.agentId,className:`h-4 w-4 shrink-0`}):(0,N.jsx)(Yt,{className:`h-4 w-4 shrink-0 text-gray-400`}),(0,N.jsx)(`span`,{className:`truncate`,children:e.title})]}),(0,N.jsx)(PN,{tab:e})]})}function IN(e){let{resolvedChildTabs:t,workspaceFileTabs:n,activeSelection:r,optimisticReadAtBySessionKey:i,onSelectSession:a,onSelectFile:o,onCloseFile:s}=e,c=t.map(e=>{let t=i[e.sessionKey],n=t&&e.readAt?t.localeCompare(e.readAt)>0?t:e.readAt:t??e.readAt;return{key:`child:${e.sessionKey}`,kind:`child-session`,title:e.title,tooltip:e.title,agentId:e.agentId,active:r?.kind===`child-session`&&r.tab.sessionKey===e.sessionKey,showUnreadDot:CO({active:r?.kind===`child-session`&&r.tab.sessionKey===e.sessionKey,lastMessageAt:e.lastMessageAt,readAt:n,runStatus:e.runStatus}),onSelect:()=>a(e.sessionKey)}}),l=n.map(e=>({key:`file:${e.key}`,kind:`file`,title:DN(e),tooltip:e.path,viewMode:e.viewMode,active:r?.kind===`file`&&r.file.key===e.key,onSelect:()=>o(e.key),onClose:()=>s(e.key)}));return[...c,...l]}function LN({childSessionTabs:e,activeChildSessionKey:t,workspaceFileTabs:n,activeWorkspaceFileKey:r,sessionProjectRoot:i,displayMode:a=`docked`,onSelectSession:s,onSelectFile:c,onCloseFile:l,onClose:u,onBackToParent:f,onToolAction:p,onFileOpen:m}){let h=Bn(),g=qM(e),_=DO(e=>e.optimisticReadAtBySessionKey),v=ON({activeChildSessionKey:t,activeWorkspaceFileKey:r,childSessionTabs:g,workspaceFileTabs:n}),y=g.some(e=>!!e.parentSessionKey);(0,P.useEffect)(()=>{if(v?.kind!==`child-session`)return;let e=v.tab.lastMessageAt?.trim()??null;e&&h.chatSessionListManager.markSessionRead(v.tab.sessionKey,e,v.tab.readAt??null)},[v,h]);let b=(0,P.useMemo)(()=>IN({resolvedChildTabs:g,workspaceFileTabs:n,activeSelection:v,optimisticReadAtBySessionKey:_,onSelectSession:s,onSelectFile:c,onCloseFile:l}),[v,l,c,s,_,g,n]);return v?(0,N.jsx)(`aside`,{className:d(a===`overlay`?`fixed inset-0 z-40 flex bg-white`:`hidden shrink-0 border-l border-gray-200/70 bg-white/95 backdrop-blur-sm md:flex md:w-[26rem] lg:w-[30rem] xl:w-[34rem]`),children:(0,N.jsxs)(`div`,{className:`flex h-full min-h-0 w-full flex-col`,children:[(0,N.jsxs)(`div`,{className:`flex items-center justify-between gap-3 border-b border-gray-200/70 px-4 py-2.5`,children:[(0,N.jsxs)(`button`,{type:`button`,onClick:f,className:d(`inline-flex items-center gap-1 text-xs font-medium text-gray-600 transition-colors hover:text-gray-900`,!y&&`pointer-events-none opacity-0`),children:[(0,N.jsx)(De,{className:`h-3.5 w-3.5`}),(0,N.jsx)(`span`,{children:o(`chatBackToParent`)})]}),(0,N.jsx)(`button`,{type:`button`,onClick:u,className:`rounded-full border border-gray-200/80 p-1.5 text-gray-500 transition-colors hover:bg-gray-100 hover:text-gray-900`,"aria-label":o(`chatWorkspaceClosePanel`),children:(0,N.jsx)(ct,{className:`h-4 w-4`})})]}),(0,N.jsx)(jN,{tabs:b}),(0,N.jsx)(`div`,{className:`flex min-h-0 flex-1 flex-col bg-white`,children:v.kind===`child-session`?(0,N.jsxs)(N.Fragment,{children:[(0,N.jsx)(FN,{tab:v.tab}),(0,N.jsx)(`div`,{className:`flex-1 min-h-0`,children:(0,N.jsx)(MN,{sessionKey:v.tab.sessionKey,onToolAction:p,onFileOpen:m})})]}):(0,N.jsx)(GM,{file:v.file,sessionProjectRoot:i,onFileOpen:m})})]})}):null}function RN(){return y({queryKey:[`ncp-session-types`],queryFn:b,staleTime:1e4,retry:!1})}function zN(e){let t=e.trim();return t.length>0?t:null}function BN(e){return e??null}var VN=class{constructor(e){this.updateSession=e,this.inFlight=null,this.queued=null,this.syncSelectedSessionPreferences=()=>{let e=Q.getState().snapshot,t=DO.getState().snapshot,n=kO.getState().snapshot,r=t.selectedSessionKey;!r||!n.canDeleteSession||this.enqueue({sessionKey:r,patch:{preferredModel:zN(e.selectedModel),preferredThinking:BN(e.selectedThinkingLevel)}})},this.enqueue=e=>{this.queued=e,!this.inFlight&&this.startFlush()},this.startFlush=()=>{this.inFlight=this.flush().catch(e=>{console.error(`Failed to sync chat session preferences: ${String(e)}`)}).finally(()=>{this.inFlight=null,this.queued&&this.startFlush()})},this.flush=async()=>{for(;this.queued;){let e=this.queued;this.queued=null,await this.updateSession(e.sessionKey,e.patch)}}}},HN=class{constructor(e,t,n){this.uiManager=e,this.streamActionsManager=t,this.sessionListManager=n,this.sessionPreferenceSync=new VN(ie),this.buildAttachmentSignature=e=>[e.assetUri??``,e.url??``,e.name,e.mimeType,String(e.sizeBytes),e.contentBase64??``].join(`:`),this.hasSnapshotChanges=e=>{let t=Q.getState().snapshot;for(let[n,r]of Object.entries(e))if(!Object.is(t[n],r))return!0;return!1},this.resolveUpdateValue=(e,t)=>typeof t==`function`?t(e):t,this.isSameStringArray=(e,t)=>e.length===t.length&&e.every((e,n)=>e===t[n]),this.isRuntimeBlockedForSend=()=>NO(se.getStatusView()),this.syncComposerSnapshot=e=>{let t=Q.getState().snapshot.attachments,n=dO(e,t);Q.getState().setSnapshot({composerNodes:e,attachments:n,draft:oO(e),selectedSkills:sO(e)})},this.syncComposerSnapshotWithAttachments=(e,t)=>{Q.getState().setSnapshot({composerNodes:e,attachments:t,draft:oO(e),selectedSkills:sO(e)})},this.dedupeAttachments=e=>{let t=new Set,n=[];for(let r of e){let e=this.buildAttachmentSignature(r);t.has(e)||(t.add(e),n.push(r))}return n},this.syncSnapshot=e=>{if(this.hasSnapshotChanges(e)&&(Q.getState().setSnapshot(e),Object.prototype.hasOwnProperty.call(e,`modelOptions`)||Object.prototype.hasOwnProperty.call(e,`selectedModel`)||Object.prototype.hasOwnProperty.call(e,`selectedThinkingLevel`))){let{selectedModel:e}=Q.getState().snapshot;this.reconcileThinkingForModel(e)}},this.setDraft=e=>{let t=Q.getState().snapshot.draft,n=this.resolveUpdateValue(t,e);n!==t&&this.syncComposerSnapshot(aO(n))},this.setComposerNodes=e=>{let t=Q.getState().snapshot.composerNodes,n=this.resolveUpdateValue(t,e);Object.is(n,t)||this.syncComposerSnapshot(n)},this.addAttachments=e=>{if(e.length===0)return[];let{snapshot:t}=Q.getState(),n=new Set(t.attachments.map(this.buildAttachmentSignature)),r=this.dedupeAttachments([...t.attachments,...e]),i=r.filter(e=>!n.has(this.buildAttachmentSignature(e)));if(i.length===0)return[];let a=uO(t.composerNodes,r);return this.syncComposerSnapshotWithAttachments(a,r),i},this.restoreComposerState=(e,t)=>{let n=this.dedupeAttachments(t),r=uO(e,n);this.syncComposerSnapshotWithAttachments(r,n)},this.setPendingSessionType=e=>{let t=Q.getState().snapshot.pendingSessionType,n=this.resolveUpdateValue(t,e);n!==t&&Q.getState().setSnapshot({pendingSessionType:n})},this.send=async()=>{let e=Q.getState().snapshot,t=DO.getState().snapshot,n=kO.getState().snapshot,r=e.draft.trim(),{attachments:i}=e,a=fO(e.composerNodes,i);if(xO({snapshot:e,hasSendableDraft:a.some(e=>e.type!==`text`||e.text.trim().length>0),isRuntimeBlocked:this.isRuntimeBlockedForSend()}))return;let{selectedSkills:o,composerNodes:s}=e,c=n.sessionKey??t.selectedSessionKey??null;!c&&e.selectedSessionType?.trim()&&this.sessionListManager.ensureDraftSession(e.selectedSessionType),this.setComposerNodes(iO()),await this.streamActionsManager.sendMessage({message:r,...c?{sessionKey:c}:{},agentId:t.selectedAgentId,sessionType:e.selectedSessionType,model:e.selectedModel||void 0,thinkingLevel:e.selectedThinkingLevel??void 0,stopSupported:!0,requestedSkills:o,attachments:i,parts:a,restoreDraftOnError:!0,composerNodes:s})},this.stop=async()=>{await this.streamActionsManager.stopCurrentRun()},this.goToProviders=()=>{this.uiManager.goToProviders()},this.setSelectedModel=e=>{let t=Q.getState().snapshot.selectedModel,n=this.resolveUpdateValue(t,e);n!==t&&(Q.getState().setSnapshot({selectedModel:n}),this.reconcileThinkingForModel(n))},this.setSelectedThinkingLevel=e=>{let t=Q.getState().snapshot.selectedThinkingLevel,n=this.resolveUpdateValue(t,e);n!==t&&Q.getState().setSnapshot({selectedThinkingLevel:n})},this.selectSessionType=e=>{let t=tM(e);Q.getState().setSnapshot({selectedSessionType:t,pendingSessionType:t})},this.setSelectedSkills=e=>{let{snapshot:t}=Q.getState(),{selectedSkills:n}=t,r=this.resolveUpdateValue(n,e);this.isSameStringArray(r,n)||this.syncComposerSnapshot(lO(t.composerNodes,r,t.skillRecords))},this.selectModel=e=>{this.setSelectedModel(e),hO.remember(e),this.sessionPreferenceSync.syncSelectedSessionPreferences()},this.selectThinkingLevel=e=>{this.setSelectedThinkingLevel(e),this.sessionPreferenceSync.syncSelectedSessionPreferences()},this.rememberSkillSelection=e=>{gO.remember(e)},this.selectSkills=e=>{let t=Q.getState().snapshot.selectedSkills;for(let n of e)t.includes(n)||this.rememberSkillSelection(n);this.setSelectedSkills(e)},this.resolveThinkingForModel=(e,t)=>{let n=e?.thinkingCapability;return!n||n.supported.length===0?null:t===`off`?`off`:t&&n.supported.includes(t)?t:n.default&&n.supported.includes(n.default)?n.default:`off`},this.reconcileThinkingForModel=e=>{let{snapshot:t}=Q.getState(),n=t.modelOptions.find(t=>t.value===e),{selectedThinkingLevel:r}=t,i=this.resolveThinkingForModel(n,r);i!==r&&Q.getState().setSnapshot({selectedThinkingLevel:i})}}},UN=class{constructor(e,t){this.uiManager=e,this.streamActionsManager=t,this.syncDraftThreadState=()=>{kO.getState().setSnapshot({sessionKey:null,sessionDisplayName:void 0,canDeleteSession:!1,isHistoryLoading:!1,messages:[],isSending:!1,isAwaitingAssistantOutput:!1,parentSessionKey:null,parentSessionLabel:null,workspacePanelParentKey:null,childSessionTabs:[],activeChildSessionKey:null,activeWorkspaceFileKey:null})},this.resolveUpdateValue=(e,t)=>typeof t==`function`?t(e):t,this.shouldPersistReadAt=(e,t,n)=>{let r=DO.getState().optimisticReadAtBySessionKey[e],i=r&&n?r.localeCompare(n)>0?r:n:r??n??void 0;return i?t.localeCompare(i)>0:!0},this.setSelectedAgentId=e=>{let t=DO.getState().snapshot.selectedAgentId,n=this.resolveUpdateValue(t,e);n!==t&&DO.getState().setSnapshot({selectedAgentId:n})},this.setSelectedSessionKey=e=>{let t=DO.getState().snapshot.selectedSessionKey,n=this.resolveUpdateValue(t,e);n!==t&&DO.getState().setSnapshot({selectedSessionKey:n})},this.setListMode=e=>{let t=DO.getState().snapshot.listMode,n=this.resolveUpdateValue(t,e);n!==t&&DO.getState().setSnapshot({listMode:n})},this.markSessionRead=(e,t,n)=>{let r=e?.trim(),i=t?.trim();!r||!i||this.shouldPersistReadAt(r,i,n)&&(DO.getState().markSessionRead(r,i),ie(r,{uiReadAt:i}).catch(()=>void 0))},this.createSession=(e,t)=>{let{snapshot:n}=Q.getState(),{defaultSessionType:r}=n,i=r||`native`,a=typeof e==`string`&&e.trim().length>0?e.trim():i,o=JA(t);this.streamActionsManager.resetStreamState(),DO.getState().setSnapshot({selectedSessionKey:null,draftSessionKey:null}),this.syncDraftThreadState(),Q.getState().setSnapshot({pendingSessionType:a,pendingProjectRoot:o,pendingProjectRootSessionKey:null}),this.uiManager.goToChatRoot()},this.startAgentDraftChat=(e,t)=>{let n=e.trim()||`main`;this.createSession(t),this.setSelectedAgentId(n)},this.ensureDraftSession=e=>{let{snapshot:t}=DO.getState();if(t.selectedSessionKey)return t.selectedSessionKey;let n=typeof e==`string`&&e.trim().length>0?e.trim():null;return this.syncDraftThreadState(),n&&Q.getState().setSnapshot({pendingSessionType:n}),null},this.materializeRootSessionRoute=e=>{let t=e.trim();t&&this.uiManager.isAtChatRoot()&&(DO.getState().setSnapshot({selectedSessionKey:t,draftSessionKey:null}),kO.getState().setSnapshot({sessionKey:t}),this.uiManager.goToSession(t,{replace:!0}))},this.selectSession=e=>{kO.getState().setSnapshot({workspacePanelParentKey:null,activeChildSessionKey:null,activeWorkspaceFileKey:null}),this.uiManager.goToSession(e)},this.setQuery=e=>{let t=DO.getState().snapshot.query,n=this.resolveUpdateValue(t,e);n!==t&&DO.getState().setSnapshot({query:n})}}},WN=async()=>{},GN=()=>{},KN=class{constructor(){this.actions={sendMessage:WN,stopCurrentRun:WN,resumeRun:WN,resetStreamState:GN,applyHistoryMessages:GN},this.bind=e=>{this.actions={...this.actions,...e}},this.sendMessage=e=>this.actions.sendMessage(e),this.stopCurrentRun=()=>this.actions.stopCurrentRun(),this.resumeRun=e=>this.actions.resumeRun(e),this.resetStreamState=()=>this.actions.resetStreamState(),this.applyHistoryMessages=(e,t)=>this.actions.applyHistoryMessages(e,t)}},qN=`sid_`;function JN(e){let t=new TextEncoder().encode(e),n=``;for(let e of t)n+=String.fromCharCode(e);return`${qN}${btoa(n).replace(/\+/g,`-`).replace(/\//g,`_`).replace(/=+$/g,``)}`}function YN(e){if(!e.startsWith(qN))return null;let t=e.slice(4).replace(/-/g,`+`).replace(/_/g,`/`),n=`=`.repeat((4-t.length%4)%4);try{let e=atob(t+n),r=Uint8Array.from(e,e=>e.charCodeAt(0));return new TextDecoder().decode(r)}catch{return null}}function XN(e){if(!e)return null;let t=YN(e);if(t)return t;try{return decodeURIComponent(e)}catch{return e}}function ZN(e){return`/chat/${JN(e)}`}var QN=async e=>!1,$N=class{constructor(){this.state={pathname:``},this.actions={navigate:null,confirm:QN},this.syncState=e=>{this.state={...this.state,...e}},this.bindActions=e=>{this.actions={...this.actions,...e}},this.confirm=async e=>this.actions.confirm(e),this.navigateTo=(e,t)=>{this.actions.navigate&&(this.state.pathname===e&&!t?.replace||(this.actions.navigate(e,t),this.state.pathname=e))},this.goToProviders=()=>{this.navigateTo(`/providers`)},this.goToChatRoot=e=>{this.navigateTo(`/chat`,e)},this.isAtChatRoot=()=>this.state.pathname===`/chat`,this.goToSession=(e,t)=>{this.navigateTo(ZN(e),t)}}},eP=class{constructor(e,t,n){this.uiManager=e,this.sessionListManager=t,this.streamActionsManager=n,this.hasSnapshotChanges=e=>{let t=kO.getState().snapshot;for(let[n,r]of Object.entries(e))if(!Object.is(t[n],r))return!0;return!1},this.syncSnapshot=e=>{this.hasSnapshotChanges(e)&&kO.getState().setSnapshot(e)},this.clearDeletedSessionState=e=>{DO.getState().snapshot.selectedSessionKey===e&&this.sessionListManager.setSelectedSessionKey(null),kO.getState().setSnapshot({sessionKey:null,sessionTypeLabel:null,agentId:null,agentDisplayName:null,agentAvatarUrl:null,sessionDisplayName:void 0,sessionProjectRoot:null,sessionProjectName:null,canDeleteSession:!1,isHistoryLoading:!1,messages:[],isSending:!1,isAwaitingAssistantOutput:!1,parentSessionKey:null,parentSessionLabel:null,workspacePanelParentKey:null,childSessionTabs:[],activeChildSessionKey:null,workspaceFileTabs:[],activeWorkspaceFileKey:null})},this.resolveWorkspaceParentSessionKey=()=>kO.getState().snapshot.sessionKey?.trim()||(DO.getState().snapshot.selectedSessionKey??null),this.buildWorkspaceFileTab=(e,t)=>{let n=e.path.trim();if(!n)return null;let r=t?.trim()||null;return{key:`${r??`draft`}::${e.viewMode}::${n}`,parentSessionKey:r,path:n,label:e.label?.trim()||null,viewMode:e.viewMode,line:e.line??null,column:e.column??null,rawText:e.rawText??null,beforeText:e.beforeText??null,afterText:e.afterText??null,patchText:e.patchText??null,oldStartLine:e.oldStartLine??null,newStartLine:e.newStartLine??null,fullLines:e.fullLines}},this.upsertWorkspaceFileTab=e=>{let{workspaceFileTabs:t}=kO.getState().snapshot,n=t.findIndex(t=>t.key===e.key);if(n===-1)return[e,...t];let r=[...t];return r.splice(n,1),r.unshift({...t[n],...e}),r},this.ensureWorkspaceParentRoute=e=>{if(!e)return;let{snapshot:{selectedSessionKey:t}}=DO.getState();t!==e&&this.uiManager.goToSession(e)},this.deleteSession=()=>{this.deleteCurrentSession()},this.createSession=()=>{this.sessionListManager.createSession()},this.goToProviders=()=>{this.uiManager.goToProviders()},this.openChildSessionPanel=e=>{let t=e.parentSessionKey.trim();if(!t)return;let n=e.activeChildSessionKey?.trim()||null;kO.getState().setSnapshot({workspacePanelParentKey:t,activeChildSessionKey:n,activeWorkspaceFileKey:null}),this.ensureWorkspaceParentRoute(t)},this.openFilePreview=e=>{let t=this.resolveWorkspaceParentSessionKey(),n=this.buildWorkspaceFileTab(e,t);n&&(kO.getState().setSnapshot({workspacePanelParentKey:t,workspaceFileTabs:this.upsertWorkspaceFileTab(n),activeWorkspaceFileKey:n.key,activeChildSessionKey:null}),this.ensureWorkspaceParentRoute(t))},this.openSessionFromToolAction=e=>{if(e.kind===`open-session`){if(e.sessionKind===`child`&&!this.isCompactViewport()){let t=e.parentSessionId?.trim()||DO.getState().snapshot.selectedSessionKey||null;if(t){this.openChildSessionPanel({parentSessionKey:t,activeChildSessionKey:e.sessionId});return}}kO.getState().setSnapshot({workspacePanelParentKey:null,activeChildSessionKey:null,activeWorkspaceFileKey:null}),this.uiManager.goToSession(e.sessionId)}},this.selectChildSessionDetail=e=>{let t=e.trim();if(!t)return;let{childSessionTabs:n}=kO.getState().snapshot;n.some(e=>e.sessionKey===t)&&kO.getState().setSnapshot({activeChildSessionKey:t,activeWorkspaceFileKey:null})},this.selectWorkspaceFile=e=>{let t=e.trim();if(!t)return;let{workspaceFileTabs:n}=kO.getState().snapshot;n.some(e=>e.key===t)&&kO.getState().setSnapshot({activeWorkspaceFileKey:t,activeChildSessionKey:null})},this.closeWorkspaceFile=e=>{let t=e.trim();if(!t)return;let{snapshot:n}=kO.getState(),{activeWorkspaceFileKey:r,workspaceFileTabs:i}=n,a={workspaceFileTabs:i.filter(e=>e.key!==t)};r===t&&(a.activeWorkspaceFileKey=null),kO.getState().setSnapshot(a)},this.closeWorkspacePanel=()=>{kO.getState().setSnapshot({workspacePanelParentKey:null,activeChildSessionKey:null,activeWorkspaceFileKey:null})},this.closeChildSessionDetail=()=>{this.closeWorkspacePanel()},this.goToParentSession=()=>{let{parentSessionKey:e,childSessionTabs:t,activeChildSessionKey:n}=kO.getState().snapshot,r=t.find(e=>e.sessionKey===n)?.parentSessionKey??null,i=e??r;i&&(this.closeWorkspacePanel(),this.uiManager.goToSession(i))},this.isCompactViewport=()=>dt.getSnapshot().mode===`mobile`,this.deleteCurrentSession=async()=>{let{snapshot:{selectedSessionKey:e}}=DO.getState();if(e&&await this.uiManager.confirm({title:o(`chatDeleteSessionConfirm`),variant:`destructive`,confirmLabel:o(`delete`)})){kO.getState().setSnapshot({isDeletePending:!0});try{await ee(e),T(v,e),v.removeQueries({queryKey:[`ncp-session-messages`,e]}),this.streamActionsManager.resetStreamState(),this.clearDeletedSessionState(e),this.uiManager.goToChatRoot({replace:!0})}finally{kO.getState().setSnapshot({isDeletePending:!1})}}}}},tP=class{constructor(){this.chatUiManager=new $N,this.chatStreamActionsManager=new KN,this.chatSessionListManager=new UN(this.chatUiManager,this.chatStreamActionsManager),this.chatInputManager=new HN(this.chatUiManager,this.chatStreamActionsManager,this.chatSessionListManager),this.chatThreadManager=new eP(this.chatUiManager,this.chatSessionListManager,this.chatStreamActionsManager)}};function nP(e){return e?.trim().toLowerCase()||`native`}function rP(e,t){if(typeof t!=`string`)return!1;let n=t.trim();return n?e.some(e=>e.value===n):!1}function iP(e,t){return typeof t==`string`&&e.includes(t)}function aP(e){return e.length===0?null:e.includes(`off`)?`off`:e[0]??null}function oP(e){let{currentValue:t,selectedSessionPreferredValue:n,fallbackPreferredValue:r,defaultValue:i,isValueSupported:a,firstAvailableValue:o,preferSessionPreferredValue:s=!1,preserveCurrentValueOnSessionChange:c=!1}=e;return a(t)&&(!s||c)?t:a(n)?n:a(r)?r:a(i)?i:o}function sP(e){let{modelOptions:t,currentSelectedModel:n,selectedSessionPreferredModel:r,fallbackPreferredModel:i,defaultModel:a,preferSessionPreferredModel:o,preserveCurrentSelectedModelOnSessionChange:s}=e;return t.length===0?``:oP({currentValue:n,selectedSessionPreferredValue:r,fallbackPreferredValue:i,defaultValue:a,isValueSupported:e=>rP(t,e),firstAvailableValue:t[0]?.value??``,preferSessionPreferredValue:o,preserveCurrentValueOnSessionChange:s})}function cP(e){let{supportedThinkingLevels:t,currentSelectedThinkingLevel:n,selectedSessionPreferredThinking:r,fallbackPreferredThinking:i,defaultThinkingLevel:a,preferSessionPreferredThinking:o,preserveCurrentSelectedThinkingOnSessionChange:s}=e;return t.length===0?null:oP({currentValue:n,selectedSessionPreferredValue:r,fallbackPreferredValue:i,defaultValue:a,isValueSupported:e=>iP(t,e),firstAvailableValue:aP(t)??`off`,preferSessionPreferredValue:o,preserveCurrentValueOnSessionChange:s})}function lP(e){let{sessions:t,selectedSessionKey:n,sessionType:r,readPreference:i}=e,a=nP(r),o,s=-1/0;for(let e of t){if(e.key===n||nP(e.sessionType)!==a)continue;let t=i(e);if(t==null)continue;let r=Date.parse(e.updatedAt),c=Number.isFinite(r)?r:-1/0;(o===void 0||c>s)&&(o=t,s=c)}return o}function uP(e){return e.map(e=>e==null?``:String(e)).join(``)}function dP(e){let{isPreferenceAvailable:t,emptyValue:n,syncKey:r,selectedSessionKey:i,selectedSessionExists:a=!1,setValue:o,resolveValue:s}=e,c=(0,P.useRef)(void 0),l=(0,P.useRef)(s),u=(0,P.useRef)(n);l.current=s,(0,P.useEffect)(()=>{let e=c.current!==i;if(!t){o(n),u.current=n,c.current=i;return}o(t=>{let r=l.current({currentValue:!e&&Object.is(t,u.current)?n:t,sessionChanged:e,preserveCurrentValueOnSessionChange:e&&!!i&&!a});return u.current=r,r}),c.current=i},[n,t,a,i,o,r])}function fP(e){let{modelOptions:t,selectedSessionKey:n,selectedSessionExists:r=!1,selectedSessionPreferredModel:i,fallbackPreferredModel:a,defaultModel:o,setSelectedModel:s}=e;dP({isPreferenceAvailable:t.length>0,emptyValue:``,syncKey:uP([t.map(e=>e.value).join(``),i,a,o]),selectedSessionKey:n,selectedSessionExists:r,setValue:s,resolveValue:({currentValue:e,sessionChanged:n,preserveCurrentValueOnSessionChange:r})=>sP({currentSelectedModel:e,modelOptions:t,selectedSessionPreferredModel:i,fallbackPreferredModel:a,defaultModel:o,preferSessionPreferredModel:n,preserveCurrentSelectedModelOnSessionChange:r})})}function pP(e){let{supportedThinkingLevels:t,selectedSessionKey:n,selectedSessionExists:r=!1,selectedSessionPreferredThinking:i,fallbackPreferredThinking:a,defaultThinkingLevel:o,setSelectedThinkingLevel:s}=e;dP({isPreferenceAvailable:t.length>0,emptyValue:null,syncKey:uP([t.join(``),i,a,o]),selectedSessionKey:n,selectedSessionExists:r,setValue:s,resolveValue:({currentValue:e,sessionChanged:n,preserveCurrentValueOnSessionChange:r})=>cP({currentSelectedThinkingLevel:e,supportedThinkingLevels:t,selectedSessionPreferredThinking:i,fallbackPreferredThinking:a,defaultThinkingLevel:o,preferSessionPreferredThinking:n,preserveCurrentSelectedThinkingOnSessionChange:r})})}export{FO as A,tn as B,Cj as C,QO as D,JA as E,Bn as F,Mn as I,jn as L,Q as M,zD as N,rk as O,zn as P,un as R,Dj as S,YA as T,aM as _,XN as a,Mj as b,EN as c,vM as d,dM as f,rM as g,nM as h,tP as i,DO as j,NO as k,PM as l,tM as m,fP as n,RN as o,iM as p,pP as r,SN as s,lP as t,gM as u,kj as v,Sj as w,jj as x,Aj as y,on as z};
|