local-operator-ui 0.31.27 → 0.31.28

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (113) hide show
  1. package/out/main/index.js +240 -39
  2. package/out/preload/index.js +37 -0
  3. package/out/renderer/assets/{_basePickBy-oM-LmypH.js → _basePickBy-D16oopNi.js} +1 -1
  4. package/out/renderer/assets/{_baseUniq-CfyEpPZd.js → _baseUniq-BYKYfwtj.js} +1 -1
  5. package/out/renderer/assets/{agent-details-page-DIBks4X5.js → agent-details-page-CpwkLhdq.js} +2 -2
  6. package/out/renderer/assets/{agent-hub-page-oV4gEqC4.js → agent-hub-page-BYeba0zC.js} +3 -3
  7. package/out/renderer/assets/{agents-page-CZrNPorc.js → agents-page-BQdR1fgV.js} +3 -3
  8. package/out/renderer/assets/arc-BYg3WIzZ.js +1 -0
  9. package/out/renderer/assets/architectureDiagram-IEHRJDOE-np6HwkQz.js +36 -0
  10. package/out/renderer/assets/{blockDiagram-JOT3LUYC-Cn1dvDZU.js → blockDiagram-JOT3LUYC-CaR7YwVl.js} +2 -2
  11. package/out/renderer/assets/{book-open-P6KBj9Du.js → book-open--g1VlVMp.js} +1 -1
  12. package/out/renderer/assets/browser-page-BPwZPQY2.js +1 -0
  13. package/out/renderer/assets/browser-webauthn-prompt-Bsk0eXNZ.js +1 -0
  14. package/out/renderer/assets/{c4Diagram-VJAJSXHY-B8F1XGHT.js → c4Diagram-VJAJSXHY-DqBT3rl5.js} +4 -4
  15. package/out/renderer/assets/channel-mWTr8anL.js +1 -0
  16. package/out/renderer/assets/{chunk-4BMEZGHF-CVoXO2u6.js → chunk-4BMEZGHF-B7-MzFPi.js} +1 -1
  17. package/out/renderer/assets/{chunk-A2AXSNBT-LFo0s6P7.js → chunk-A2AXSNBT-B9IqNrNg.js} +1 -1
  18. package/out/renderer/assets/{chunk-AEK57VVT-B8s36YJo.js → chunk-AEK57VVT-DFzBJNd9.js} +1 -1
  19. package/out/renderer/assets/{chunk-D6G4REZN-BKkRpyOx.js → chunk-D6G4REZN-DW-XzsAv.js} +1 -1
  20. package/out/renderer/assets/{chunk-RZ5BOZE2-qoB87AlE.js → chunk-RZ5BOZE2-C7el6yre.js} +1 -1
  21. package/out/renderer/assets/{chunk-XZIHB7SX-BACgoEDe.js → chunk-XZIHB7SX-BGYrq1Wn.js} +1 -1
  22. package/out/renderer/assets/classDiagram-GIVACNV2-DsNAZ0y6.js +1 -0
  23. package/out/renderer/assets/classDiagram-v2-COTLJTTW-DsNAZ0y6.js +1 -0
  24. package/out/renderer/assets/clone-48M_nlg0.js +1 -0
  25. package/out/renderer/assets/{console-mirror-fXJ5fMxl.js → console-mirror-ffbsozOd.js} +1 -1
  26. package/out/renderer/assets/{consoleCapture-Df4uIOqu.js → consoleCapture-CiApa6fi.js} +1 -1
  27. package/out/renderer/assets/conversation-input-sync-CIGg7Rga.css +1 -0
  28. package/out/renderer/assets/conversation-input-sync-DQUYkOfh.js +911 -0
  29. package/out/renderer/assets/dagre-OKDRZEBW-BVScRDvj.js +4 -0
  30. package/out/renderer/assets/diagram-SSKATNLV-B0iQ6YY1.js +43 -0
  31. package/out/renderer/assets/diagram-VNBRO52H-Co6YPtUT.js +24 -0
  32. package/out/renderer/assets/{erDiagram-Q7BY3M3F-CGjlhqbg.js → erDiagram-Q7BY3M3F-C9XIuSQl.js} +2 -2
  33. package/out/renderer/assets/error-boundary-DH4MhqhL.js +126 -0
  34. package/out/renderer/assets/{flowDiagram-4HSFHLVR-rb1I18B8.js → flowDiagram-4HSFHLVR-QTHrGPk1.js} +2 -2
  35. package/out/renderer/assets/{ganttDiagram-APWFNJXF-D-bSpERZ.js → ganttDiagram-APWFNJXF-qC1VnBIz.js} +2 -2
  36. package/out/renderer/assets/gitGraphDiagram-7IBYFJ6S-D7UGP8uH.js +65 -0
  37. package/out/renderer/assets/{graph-BkNT14na.js → graph-BIUuz2bp.js} +1 -1
  38. package/out/renderer/assets/index-C5Ighs_C.css +1 -0
  39. package/out/renderer/assets/index-Ckvy9Zge.js +1 -0
  40. package/out/renderer/assets/{index-_dbvHdgc.js → index-D-TXozHA.js} +1 -1
  41. package/out/renderer/assets/index-DHKnfVbX.css +1 -0
  42. package/out/renderer/assets/index-DTc-sJ8S.js +7 -0
  43. package/out/renderer/assets/index-vK67PDia.js +784 -0
  44. package/out/renderer/assets/infoDiagram-PH2N3AL5-DYtVGJC7.js +2 -0
  45. package/out/renderer/assets/installer-BcSiJA6N.js +1 -0
  46. package/out/renderer/assets/{journeyDiagram-U35MCT3I-B5bji5kb.js → journeyDiagram-U35MCT3I-vVg2sFTp.js} +6 -6
  47. package/out/renderer/assets/{kanban-definition-NDS4AKOZ-BGi8PMEB.js → kanban-definition-NDS4AKOZ-BE36wSk2.js} +4 -4
  48. package/out/renderer/assets/{layout-D3rwe0Wt.js → layout-bOQrw0b8.js} +1 -1
  49. package/out/renderer/assets/{legacy-agents-page-DnpWTuf8.js → legacy-agents-page-BSKz_UrV.js} +4 -4
  50. package/out/renderer/assets/{mermaid.core-CHiYins7.js → mermaid.core-DpvY6Bhk.js} +5 -5
  51. package/out/renderer/assets/mesh-page-9Q8Sc9J_.js +1 -0
  52. package/out/renderer/assets/mindmap-definition-ALO5MXBD-B9PPN6sb.js +95 -0
  53. package/out/renderer/assets/mini-ySULdryU.js +1 -0
  54. package/out/renderer/assets/org-surface-gate-Dl4zcl5q.js +1 -0
  55. package/out/renderer/assets/{page-header-B3kbzqCp.js → page-header-DazB-GQz.js} +1 -1
  56. package/out/renderer/assets/pieDiagram-IB7DONF6-DkioNhQY.js +30 -0
  57. package/out/renderer/assets/projects-page-C37RiUJz.js +35 -0
  58. package/out/renderer/assets/{quadrantDiagram-7GDLP6J5-BZkLgvoE.js → quadrantDiagram-7GDLP6J5-4m3m0N6F.js} +4 -4
  59. package/out/renderer/assets/{radar-MK3ICKWK-QB0E4nFC.js → radar-MK3ICKWK-DS8YGAOb.js} +1 -1
  60. package/out/renderer/assets/radient-auth-buttons-DZeHRL7u.js +1 -0
  61. package/out/renderer/assets/{requirementDiagram-KVF5MWMF-Cb1rqfe3.js → requirementDiagram-KVF5MWMF-DsBdUu3C.js} +3 -3
  62. package/out/renderer/assets/sankeyDiagram-QLVOVGJD-CnaPYKR6.js +10 -0
  63. package/out/renderer/assets/{schedules-page-DnHKOQij.js → schedules-page-B0dSGpXt.js} +12 -12
  64. package/out/renderer/assets/{sequenceDiagram-X6HHIX6F-Bh-yCDC0.js → sequenceDiagram-X6HHIX6F-C3eja1QY.js} +2 -2
  65. package/out/renderer/assets/settings-page-CrMsVX3d.js +292 -0
  66. package/out/renderer/assets/{settings-section-C9etJXA9.js → settings-section-BGG4XzV0.js} +1 -1
  67. package/out/renderer/assets/stateDiagram-DGXRK772-CjFKiyXn.js +1 -0
  68. package/out/renderer/assets/stateDiagram-v2-YXO3MK2T-BsbYpgkp.js +1 -0
  69. package/out/renderer/assets/{timeline-definition-BDJGKUSR-pgK_gxyk.js → timeline-definition-BDJGKUSR-CAXy0nQD.js} +2 -2
  70. package/out/renderer/assets/ui-preferences-store-B6Fr0UX9.js +1 -0
  71. package/out/renderer/assets/{use-download-agent-mutation-CXw_g4Rv.js → use-download-agent-mutation-LsNre_-6.js} +3 -3
  72. package/out/renderer/assets/use-memberships-query-BgiSfYgr.js +1 -0
  73. package/out/renderer/assets/{xychartDiagram-VJFVF3MP-CYYxIZAM.js → xychartDiagram-VJFVF3MP-CfNm8SWG.js} +6 -6
  74. package/out/renderer/console-capture.html +5 -5
  75. package/out/renderer/index.html +9 -9
  76. package/out/renderer/installer.html +4 -5
  77. package/out/renderer/mini.html +7 -6
  78. package/package.json +2 -3
  79. package/out/renderer/assets/aida-control-CQx1CGx-.js +0 -50
  80. package/out/renderer/assets/arc-DXJiD7SC.js +0 -1
  81. package/out/renderer/assets/architectureDiagram-IEHRJDOE-VHM5BLyo.js +0 -36
  82. package/out/renderer/assets/browser-page-D6eiItUp.js +0 -1
  83. package/out/renderer/assets/browser-webauthn-prompt-CByfVm08.js +0 -1
  84. package/out/renderer/assets/channel-DZQWNfux.js +0 -1
  85. package/out/renderer/assets/classDiagram-GIVACNV2-jw9F6ZK-.js +0 -1
  86. package/out/renderer/assets/classDiagram-v2-COTLJTTW-jw9F6ZK-.js +0 -1
  87. package/out/renderer/assets/clone-DzWAH3PE.js +0 -1
  88. package/out/renderer/assets/dagre-OKDRZEBW-CLMw1D7m.js +0 -4
  89. package/out/renderer/assets/diagram-SSKATNLV-plMydQ5N.js +0 -43
  90. package/out/renderer/assets/diagram-VNBRO52H-BptPse7H.js +0 -24
  91. package/out/renderer/assets/error-boundary-D3Um1PIl.js +0 -6
  92. package/out/renderer/assets/gitGraphDiagram-7IBYFJ6S-DDJQIXgd.js +0 -65
  93. package/out/renderer/assets/index-2qmFWi_F.css +0 -1
  94. package/out/renderer/assets/index-BXamXVGw.js +0 -7
  95. package/out/renderer/assets/index-D3ICBbhi.js +0 -1642
  96. package/out/renderer/assets/index-DHcQTmYa.js +0 -1
  97. package/out/renderer/assets/index-DuUnXH9L.css +0 -1
  98. package/out/renderer/assets/infoDiagram-PH2N3AL5-Bg2dnJEw.js +0 -2
  99. package/out/renderer/assets/installer-D-IQpqXR.js +0 -1
  100. package/out/renderer/assets/mesh-page-B2_ZtHTQ.js +0 -1
  101. package/out/renderer/assets/mindmap-definition-ALO5MXBD-BwO55Ck2.js +0 -95
  102. package/out/renderer/assets/mini-D7VYY0xP.js +0 -1
  103. package/out/renderer/assets/org-surface-gate-Da1VmZbG.js +0 -1
  104. package/out/renderer/assets/pieDiagram-IB7DONF6-j0i7dQ2D.js +0 -30
  105. package/out/renderer/assets/projects-page-f-tkHojn.js +0 -35
  106. package/out/renderer/assets/radient-auth-buttons-2wnsv7f6.js +0 -1
  107. package/out/renderer/assets/sankeyDiagram-QLVOVGJD-ST_5m9Zy.js +0 -10
  108. package/out/renderer/assets/settings-page-D1dF4GZE.js +0 -292
  109. package/out/renderer/assets/stateDiagram-DGXRK772-D6MGh56o.js +0 -1
  110. package/out/renderer/assets/stateDiagram-v2-YXO3MK2T-Dvv5Bcoz.js +0 -1
  111. package/out/renderer/assets/textarea-DeXGhzIK.js +0 -121
  112. package/out/renderer/assets/ui-preferences-store-BLiDaCIL.js +0 -1
  113. package/out/renderer/assets/use-memberships-query-BGPQ6jDl.js +0 -1
@@ -1,11 +1,11 @@
1
- import{r,j as e,c as C}from"./index-_dbvHdgc.js";import{B as ms,C as hs,u as xs,f as Re,x as De,a as gs,I as fs}from"./aida-control-CQx1CGx-.js";import{P as ps}from"./page-header-B3kbzqCp.js";import{c as Be,g as Q,B as f,f as x,r as bs,A as J,h as ee,i as se,z as js,E as vs,F as Ns,G as ys,I as ws,s as _e,t as Ae,u as Pe,v as Oe,w as Ee}from"./textarea-DeXGhzIK.js";import{a3 as Ue,Z as xe,a7 as ks,a8 as ze,bj as Ts,bh as Cs,bk as Ss,_ as Rs,bl as _s,$ as As,bm as Ps,V as Os,b0 as Es,bn as zs,bo as Is,bp as Ms,bq as Fs}from"./index-D3ICBbhi.js";import{e as $s,f as Ls,p as Ds,P as Bs,b as Us,h as Vs}from"./use-memberships-query-BGPQ6jDl.js";import{O as qs,A as Hs,f as Ys,H as Qs,a as Ws,b as Gs,c as Zs,d as Ve,C as Xs,e as Ks,u as Js,i as et}from"./use-download-agent-mutation-CXw_g4Rv.js";import{R as st}from"./radient-auth-buttons-2wnsv7f6.js";import{o as qe,u as tt,a as at,b as nt}from"./org-surface-gate-Da1VmZbG.js";import{f as it}from"./format-CZUObkkr.js";import"./ui-preferences-store-BLiDaCIL.js";import"./error-boundary-D3Um1PIl.js";import"./console-mirror-fXJ5fMxl.js";import"./en-US-BcB1DWxG.js";import"./book-open-P6KBj9Du.js";/**
1
+ import{r,j as e,c as C}from"./index-D-TXozHA.js";import{aP as De,aL as xe,aR as Re,aF as ms,aG as hs,u as xs,aM as gs,bc as fs,aN as ps,a8 as _e,bd as bs,ay as js,ax as Be,b1 as vs,be as Ns,a as ys,bf as ws,aY as ks,bg as Ts}from"./conversation-input-sync-DQUYkOfh.js";import{P as Cs}from"./page-header-DazB-GQz.js";import{c as Ue,f as Q,B as f,e as x,r as Ss,A as J,g as ee,h as se,z as Rs,F as _s,G as As,H as Ps,I as Os,s as Ae,t as Pe,u as Oe,v as Ee,w as ze}from"./error-boundary-DH4MhqhL.js";import{e as Es,f as zs,p as Is,P as Ms,b as Fs,h as Ls}from"./use-memberships-query-BgiSfYgr.js";import{O as $s,A as Ds,f as Bs,H as Us,a as Vs,b as qs,c as Hs,d as Ve,C as Ys,e as Qs,u as Ws,i as Gs}from"./use-download-agent-mutation-LsNre_-6.js";import{c as Xs,a9 as Zs,a8 as Ks,aa as Js,ab as et}from"./index-vK67PDia.js";import{R as st}from"./radient-auth-buttons-DZeHRL7u.js";import{o as qe,u as tt,a as at,b as nt}from"./org-surface-gate-Dl4zcl5q.js";import{f as it}from"./format-CZUObkkr.js";import"./ui-preferences-store-B6Fr0UX9.js";import"./en-US-BcB1DWxG.js";import"./book-open--g1VlVMp.js";import"./console-mirror-ffbsozOd.js";/**
2
2
  * @license lucide-react v0.507.0 - ISC
3
3
  *
4
4
  * This source code is licensed under the ISC license.
5
5
  * See the LICENSE file in the root directory of this source tree.
6
- */const rt=[["path",{d:"M6 22V4a2 2 0 0 1 2-2h8a2 2 0 0 1 2 2v18Z",key:"1b4qmf"}],["path",{d:"M6 12H4a2 2 0 0 0-2 2v6a2 2 0 0 0 2 2h2",key:"i71pzd"}],["path",{d:"M18 9h2a2 2 0 0 1 2 2v9a2 2 0 0 1-2 2h-2",key:"10jefs"}],["path",{d:"M10 6h4",key:"1itunk"}],["path",{d:"M10 10h4",key:"tcdvrf"}],["path",{d:"M10 14h4",key:"kelpxr"}],["path",{d:"M10 18h4",key:"1ulq68"}]],He=Be("building-2",rt);/**
6
+ */const rt=[["path",{d:"M6 22V4a2 2 0 0 1 2-2h8a2 2 0 0 1 2 2v18Z",key:"1b4qmf"}],["path",{d:"M6 12H4a2 2 0 0 0-2 2v6a2 2 0 0 0 2 2h2",key:"i71pzd"}],["path",{d:"M18 9h2a2 2 0 0 1 2 2v9a2 2 0 0 1-2 2h-2",key:"10jefs"}],["path",{d:"M10 6h4",key:"1itunk"}],["path",{d:"M10 10h4",key:"tcdvrf"}],["path",{d:"M10 14h4",key:"kelpxr"}],["path",{d:"M10 18h4",key:"1ulq68"}]],He=Ue("building-2",rt);/**
7
7
  * @license lucide-react v0.507.0 - ISC
8
8
  *
9
9
  * This source code is licensed under the ISC license.
10
10
  * See the LICENSE file in the root directory of this source tree.
11
- */const lt=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"M17 12h.01",key:"1m0b6t"}],["path",{d:"M12 12h.01",key:"1mp3jc"}],["path",{d:"M7 12h.01",key:"eqddd0"}]],ot=Be("circle-ellipsis",lt),ct=({agent:s,isLiked:t,isFavourited:n,onLikeToggle:i,onFavouriteToggle:l,onDownload:o,isLikeActionLoading:h=!1,isFavouriteActionLoading:j=!1,isDownloading:g=!1,actionError:u=null,onRetryAction:v,showActions:N=!0,viewerStateKnown:p=!0,orgName:b=null})=>{const y=Ue(),{isAuthenticated:m}=xe(),L=s.description??"",[D,I]=r.useState(!1),S=r.useRef(null),M=r.useCallback(d=>{if(S.current?.disconnect(),S.current=null,!d)return;const $=()=>I(d.scrollHeight-d.clientHeight>1);$();const P=new ResizeObserver($);P.observe(d),S.current=P},[]),Y=m?p?t?"Unlike agent":"Like agent":"Your likes could not be read, so this is not shown as unliked.":"Log in to Radient to like agents",B=m?p?n?"Unfavourite agent":"Favourite agent":"Your favourites could not be read, so this is not shown as unfavourited.":"Log in to Radient to favourite agents",F=p?t?"Unlike agent":"Like agent":"Like state unavailable",A=p?n?"Unfavourite agent":"Favourite agent":"Favourite state unavailable",c=s.visibility==="org";return e.jsxs("div",{className:"flex h-full flex-col overflow-hidden rounded-md bg-surface transition-colors duration-fast ease-out-quart hover:bg-elevated",children:[e.jsxs("button",{type:"button",onClick:()=>y(`/agent-hub/${s.id}`),className:"flex min-h-0 flex-1 cursor-pointer flex-col gap-2 p-4 text-left","aria-label":`View details for ${s.name}`,children:[e.jsx("h3",{className:"truncate font-medium text-heading text-ink",children:s.name}),c&&e.jsx(qs,{orgName:b}),e.jsx(Q,{content:D?L:"",children:e.jsx("span",{ref:M,className:"line-clamp-3 min-h-0 text-body-sm text-ink-muted",children:L})}),e.jsxs("div",{className:"mt-auto flex flex-col gap-2 pt-2",children:[e.jsx(Hs,{tags:s.tags,categories:s.categories}),e.jsxs("p",{className:"truncate text-ink-dim text-meta",children:[s.account_metadata?.name??"Unknown author",e.jsx("span",{"aria-hidden":"true",className:"mx-1.5",children:"·"}),"updated ",Ys(new Date(s.updated_at))," ago"]})]})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-x-2 gap-y-1 border-t border-hairline px-3 py-2",children:[e.jsxs("div",{className:"flex min-w-0 items-center gap-0.5","data-viewer-state":c?"org":m?p?"known":"unknown":"signed-out",children:[!c&&e.jsxs(e.Fragment,{children:[e.jsx(Q,{content:Y,children:e.jsx("span",{children:e.jsxs(f,{variant:"ghost",size:"sm",onClick:m&&p?()=>i(s.id):void 0,disabled:h||!m||!p,"aria-label":F,className:C(t&&"text-danger"),children:[e.jsx(Qs,{fill:t?"currentColor":"none","data-testid":"agent-like-heart"}),e.jsx("span",{"data-testid":"agent-like-count",className:"inline-flex h-4 min-w-4 items-center font-mono text-mono-sm text-ink-muted",children:s.like_count??0})]})})}),e.jsx(Q,{content:B,children:e.jsx("span",{children:e.jsxs(f,{variant:"ghost",size:"sm",onClick:m?()=>l(s.id):void 0,disabled:j||!m||!p,"aria-label":A,className:C(n&&"text-warning"),children:[e.jsx(ks,{fill:n?"currentColor":"none","data-testid":"agent-favourite-star"}),e.jsx("span",{"data-testid":"agent-favourite-count",className:"inline-flex h-4 min-w-4 items-center font-mono text-mono-sm text-ink-muted",children:s.favourite_count??0})]})})})]}),e.jsx(Q,{content:"Downloads",children:e.jsxs("span",{className:"ml-1 inline-flex items-center gap-1 pr-1 text-ink-dim",children:[e.jsx(ze,{"aria-hidden":"true",className:"size-3.5"}),e.jsx("span",{className:"inline-flex h-4 min-w-6 items-center font-mono text-mono-sm",children:g?e.jsx(x,{className:"h-3 w-6"}):(s.download_count??0).toLocaleString()})]})})]}),N&&o&&e.jsx("div",{className:"ml-auto flex shrink-0 items-center",children:e.jsxs(f,{variant:"secondary",size:"sm",onClick:()=>o(s),disabled:g,"aria-label":`Download ${s.name}`,"data-tour-tag":"agent-hub-download-button",children:[e.jsx(ze,{"data-testid":"agent-download"}),"Get"]})})]}),u&&e.jsxs("output",{"data-testid":"agent-card-error",className:"flex flex-wrap items-center gap-x-2 gap-y-1 border-t border-hairline px-3 py-2 text-body-sm text-danger",children:[e.jsx("span",{className:"min-w-0 flex-1",children:u}),v&&e.jsx(f,{variant:"ghost",size:"sm",onClick:v,children:"Try again"})]})]})},dt=({agent:s,status:t,viewerStateKnown:n=!0,orgName:i=null})=>{const{isAuthenticated:l}=xe(),[o,h]=r.useState(null),j=t?.liked??!1,g=t?.favourited??!1,u=Ws(),v=Gs(),N=Zs(),p=()=>{!l||u.isPending||(h(null),u.mutate({agentId:s.id,isCurrentlyLiked:j},{onError:()=>h("like")}))},b=()=>{!l||v.isPending||(h(null),v.mutate({agentId:s.id,isCurrentlyFavourited:g},{onError:()=>h("favourite")}))},y=()=>{N.isPending||(h(null),N.mutate({agentId:s.id,agentName:s.name},{onError:()=>h("download")}))},m=o?o==="like"?{action:"like",error:u.error,retry:p}:o==="favourite"?{action:"favourite",error:v.error,retry:b}:{action:"download",error:N.error,retry:y}:null;return e.jsx(ct,{agent:s,isLiked:l&&j,isFavourited:l&&g,onLikeToggle:p,onFavouriteToggle:b,onDownload:y,isLikeActionLoading:u.isPending,isFavouriteActionLoading:v.isPending,isDownloading:N.isPending,viewerStateKnown:n,orgName:i,actionError:m?$s(m.action,m.error,s.name):null,onRetryAction:m?.retry})},Ie=({selected:s,onClick:t,children:n,...i})=>e.jsx("button",{type:"button",onClick:t,"aria-pressed":s,className:C("flex w-full cursor-pointer items-center gap-2.5 rounded-sm px-3 py-1.5 text-left","text-body-sm transition-colors duration-fast ease-out-quart",s?Cs:"text-ink hover:bg-row-hover"),...i,children:n}),Me=Object.keys(Xs),ut=s=>[...s].sort((t,n)=>{const i=Me.indexOf(t),l=Me.indexOf(n);return i!==-1&&l!==-1?i-l:i!==-1?-1:l!==-1?1:t.localeCompare(n)}),mt=({selectedCategory:s,onSelectCategory:t,categories:n})=>{const i=ut(s&&!n.includes(s)?[...n,s]:n);return e.jsxs("div",{className:"flex h-full flex-col overflow-y-auto",children:[e.jsx("h2",{className:"mb-2 px-3 font-medium text-ink-dim text-meta",children:"Categories"}),e.jsxs("div",{className:"flex flex-col gap-0.5",children:[e.jsxs(Ie,{selected:s===null,onClick:()=>t(null),"data-testid":"category-all",children:[e.jsx("span",{className:"flex size-4 shrink-0 items-center justify-center",children:e.jsx(Ts,{size:16,"aria-hidden":"true"})}),"All categories"]}),i.map(l=>{const o=Ve(l),h=l==="other"?e.jsx(ot,{size:16}):o.icon;return e.jsxs(Ie,{selected:s===l,onClick:()=>t(l),"data-testid":`category-${l}`,children:[e.jsx("span",{className:"flex size-4 shrink-0 items-center justify-center",children:h}),o.label]},l)})]})]})},ht=({page:s,count:t,onChange:n})=>{const i=r.useRef(null),l=r.useRef(null),o=r.useRef(null);return r.useEffect(()=>{const h=o.current;o.current=null,h==="previous"&&i.current?.focus(),h==="next"&&l.current?.focus()},[s]),t<=1?null:e.jsxs("nav",{"aria-label":"Agent pages",className:"mt-6 flex min-h-13 items-center justify-between gap-3 border-t border-hairline","data-testid":"agent-hub-pager",children:[e.jsxs("span",{className:"select-none text-meta text-ink-dim",children:["Page ",s," of ",t]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(f,{variant:"secondary",size:"sm",ref:i,onClick:()=>{s-1<=1&&(o.current="next"),n(s-1)},disabled:s<=1,"aria-label":"Previous page",children:[e.jsx(Ss,{"aria-hidden":"true"}),"Previous"]}),e.jsxs(f,{variant:"secondary",size:"sm",ref:l,onClick:()=>{s+1>=t&&(o.current="previous"),n(s+1)},disabled:s>=t,"aria-label":"Next page",children:["Next",e.jsx(bs,{"aria-hidden":"true"})]})]})]})},Ye={all:["org-teams"],list:s=>[...Ye.all,"list",s]},Qe=({tenantId:s,enabled:t=!0})=>{const n=ms({queryKey:Ye.list(s??""),queryFn:async()=>(await Ls(s)).result??{teams:[]},enabled:t&&!!s,staleTime:3e5,gcTime:6e5,refetchOnWindowFocus:!1,retryOnMount:!1,retry:hs});return{...n,teams:n.data?.teams??[]}},xt=(s,t)=>{const n=s?.name?.trim()||t?.trim()||"Team",i=s?.renamed_from?.trim()||null;return s?.invalid_name===!0&&i?{level:"warning",message:`Pulled "${n}". The published name "${i}" is not usable locally, so the team was stored as "${n}".`}:i?{level:"success",message:`Pulled "${n}" (you already have a team called "${i}").`}:{level:"success",message:`Pulled team "${n}".`}},gt=()=>{const s=xs();return Rs({mutationFn:async({teamId:t,tenantId:n})=>{if(!Re.baseUrl)throw new Error("Local Operator API URL is not configured.");return Ps.pullOrgTeamFromRadient(Re.baseUrl,t,n)},onSuccess:(t,n)=>{const i=xt(t.result,n.name);i.level==="warning"?_s(i.message):As(i.message),s.invalidateQueries({queryKey:["desktop","teams"]})},onError:t=>{console.error("Pulling an organization team failed:",t)}})},ft=/^v/i,pt=s=>s.members.reduce((t,n)=>t+n.count,0),bt=s=>s.count>1?`${s.role} ×${s.count}`:s.role,jt=s=>s.members.map(bt).join(", "),vt=s=>{const t=(s.version??"").trim().replace(ft,"").trim();return t===""?null:t},Nt=s=>{const t=s.account_metadata?.name?.trim();return t||null},yt=s=>{const t=(s.description??"").trim();return t===""?null:t},he=240,wt=he/2,kt=(s,t)=>{if(t||s.length<=he)return s;const n=s.slice(0,he),i=n.lastIndexOf(" ");return`${(i>=wt?n.slice(0,i):n).trimEnd()}…`},te=s=>it(s,"d MMM yyyy"),ae=s=>{if(!s)return null;const t=new Date(s);return Number.isNaN(t.getTime())?null:t},Fe=(s,t,n)=>{const i=n-t.getTime();let l;return i<0?l=te(t):i<6e4?l="just now":l=`${Ks(t,new Date(n))} ago`,{label:s,when:l,iso:t.toISOString(),exact:te(t)}},Tt=(s,t=Date.now())=>{const n=ae(s.updated_at);if(n)return Fe("updated",n,t);const i=ae(s.created_date);return i?Fe("created",i,t):null},Ct=s=>{const t=ae(s.created_date),n=ae(s.updated_at);return{created:t?te(t):null,updated:n?te(n):null}},St=s=>s==="role"?"Role":s==="specialist"?"Specialist":s,Rt=["refresh-hub","retry","sign-in"],_t=({tenantId:s,orgName:t})=>{const{teams:n,isLoading:i,isFetching:l,isError:o,error:h,refetch:j}=Qe({tenantId:s}),g=qe(h),u=gt(),[v,N]=r.useState(null),[p,b]=r.useState(null),y=r.useRef(new Map),m=r.useRef(null);r.useEffect(()=>{u.isPending||m.current===null||(y.current.get(m.current)?.focus(),m.current=null)},[u.isPending]);const[L,D]=r.useState(!1),[I,S]=r.useState(()=>new Set),M=(c,d)=>S($=>{const P=new Set($);return d?P.add(c):P.delete(c),P}),Y=(c,d)=>{c.key!=="Escape"||!I.has(d)||(c.target instanceof Element?c.target:null)?.closest('[data-testid="org-team-pull-error"]')||(M(d,!1),c.currentTarget.querySelector("button[aria-expanded]")?.focus(),c.preventDefault())},B=r.useMemo(()=>{if(!Os(u.error))return null;const c=n.find(d=>d.id===v);return Ds({code:u.error.code,message:u.error.message,details:u.error.details},{name:c?.name??"this team",hubAgentId:null,surface:"pull"})},[u.error,v,n]),F=(c,d)=>{switch(c){case"refresh-hub":j();break;case"retry":A(d);break;case"sign-in":D(!0);break}},A=c=>{u.isPending||(m.current=c.id,N(null),b(c.id),u.mutate({teamId:c.id,tenantId:s,name:c.name},{onSettled:()=>b(null),onError:()=>N(c.id)}))};return e.jsxs("section",{className:"mb-6 max-w-4xl rounded-md bg-surface","aria-label":`Teams shared with ${t??"this organization"}`,"data-testid":"org-teams",children:[i&&e.jsxs("div",{"aria-hidden":"true",className:"flex flex-col divide-y divide-hairline","data-testid":"org-teams-loading",children:[e.jsx(me,{}),e.jsx(me,{}),e.jsx(me,{})]}),!i&&o&&e.jsxs(J,{variant:g?"warning":"danger",className:"m-4 w-auto","data-testid":"org-teams-error",children:[e.jsx(ee,{children:g==="plan"?"That organization needs an active Team plan":g==="no_access"?"You do not have access to that organization":"Teams could not be loaded"}),e.jsx(se,{children:g==="plan"?`Reading an organization's teams is part of the Team plan. An owner of ${t??"this organization"} can activate it in the Radient console, and then its teams will be listed here.`:g==="no_access"?`You are not a member of ${t??"that organization"}, so its teams are not listed here. An owner can invite you again.`:De("The teams shared with this organization could not be read.",h)}),g!=="no_access"&&e.jsx("div",{className:"mt-2",children:e.jsx(f,{variant:"primary",size:"sm",onClick:()=>void j(),disabled:l,"aria-busy":l,children:l?"Trying…":"Try again"})})]}),!i&&!o&&n.length===0&&e.jsx("p",{className:"p-4 text-body-sm text-ink-muted","data-testid":"org-teams-empty",children:`Teams shared into ${t??"this organization"} appear here for its members.`}),!i&&!o&&n.length>0&&e.jsx("ul",{className:"flex flex-col divide-y divide-hairline",children:n.map(c=>e.jsxs("li",{className:C(We,"transition-colors duration-fast ease-out-quart hover:bg-elevated first:rounded-t-md last:rounded-b-md"),onKeyDown:d=>Y(d,c.id),children:[e.jsx(Es,{className:"min-w-0",open:I.has(c.id),onOpenChange:d=>M(c.id,d),summaryAlign:"firstLine",triggerClassName:"min-w-0",chevronClassName:"text-ink-dim mt-1",rowClassName:"py-0",summary:e.jsx(Ot,{team:c,expanded:I.has(c.id)}),trailing:e.jsx("div",{className:"-mt-1 ml-3 shrink-0 self-start",children:e.jsx(f,{ref:d=>{d?y.current.set(c.id,d):y.current.delete(c.id)},variant:"secondary",size:"sm",onClick:()=>A(c),disabled:u.isPending,"aria-label":`Pull team ${c.name}`,children:p===c.id?"Pulling…":"Pull"})}),children:e.jsx(Et,{team:c})}),v===c.id&&e.jsxs("div",{className:"mt-1 flex flex-col items-start gap-1 pl-5","data-testid":"org-team-pull-error",children:[e.jsx("output",{className:"text-meta text-danger",children:B?.body??u.error?.message??`"${c.name}" could not be pulled.`}),B?.actions.filter(d=>Rt.includes(d)).map(d=>e.jsx(f,{variant:"primary",size:"sm",onClick:()=>F(d,c),children:Bs[d]},d)),L&&e.jsx("div",{className:"mt-1","data-testid":"org-team-pull-reauth",children:e.jsx(st,{titleText:"Sign in again",descriptionText:"",onSignInSuccess:()=>{D(!1),N(null),j()}})})]})]},c.id))})]})},We="px-4 py-3",Ge=()=>e.jsxs(e.Fragment,{children:[e.jsx("span",{"aria-hidden":"true",className:"mx-1.5",children:"·"}),e.jsx("span",{className:"sr-only",children:", "})]}),At=({team:s})=>{const t=s.manager?.trim(),n=pt(s);return e.jsxs("span",{className:"block truncate text-meta",children:[t?e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"text-ink-dim",children:"Manager:"})," ",e.jsx("span",{className:"text-ink-muted",children:t})]}):null,t?e.jsx(Ge,{}):null,s.members.length===0?e.jsx("span",{className:"text-ink-dim",children:"No members"}):e.jsxs(e.Fragment,{children:[e.jsxs("span",{className:"text-ink-dim",children:[n," ",n===1?"member":"members",":"]})," ",e.jsx("span",{className:"text-ink-muted",children:jt(s)})]})]})},Pt=({team:s})=>{const t=s.project?.trim(),n=Nt(s),i=Tt(s),l=[];return t&&l.push({key:"project",node:t}),n&&l.push({key:"author",node:n}),i&&l.push({key:"recency",node:e.jsxs(e.Fragment,{children:[i.label," ",e.jsx(Q,{content:i.exact,children:e.jsx("time",{dateTime:i.iso,children:i.when})})]})}),l.length===0?null:e.jsx("span",{className:"block truncate text-ink-dim text-meta",children:l.map((o,h)=>e.jsxs("span",{children:[h>0?e.jsx(Ge,{}):null,o.node]},o.key))})},Ot=({team:s,expanded:t})=>{const n=yt(s),i=vt(s);return e.jsxs("span",{className:"flex min-w-0 flex-col",children:[e.jsxs("span",{className:"flex min-w-0 items-baseline",children:[e.jsx("span",{className:"truncate font-medium text-body text-ink",children:s.name}),i?e.jsxs("span",{className:"ml-2 shrink-0 text-ink-dim text-meta",children:["v",i]}):null]}),n?e.jsxs(e.Fragment,{children:[e.jsx("span",{...zs,"aria-hidden":"true",className:C("mt-1 select-text break-words text-body-sm text-ink-muted",t?"line-clamp-[12] whitespace-pre-line":"line-clamp-2"),children:n}),e.jsx("span",{className:"sr-only",children:kt(n,t)})]}):e.jsx("span",{className:"mt-1 text-body-sm text-ink-dim",children:"No description"}),e.jsxs("span",{className:"mt-1 flex min-w-0 flex-col",children:[e.jsx(At,{team:s}),e.jsx(Pt,{team:s})]})]})},Et=({team:s})=>{const t=s.manager?.trim(),n=Ct(s),i=[n.created?`Created ${n.created}`:null,n.updated?`Updated ${n.updated}`:null].filter(o=>o!==null),l=!!t||s.members.length>0;return e.jsxs("div",{className:"mt-1 flex flex-col gap-2",children:[l||i.length===0?e.jsxs("div",{className:"flex flex-col gap-1",children:[e.jsx("p",{className:"text-ink-dim text-meta",children:"Members"}),e.jsxs("ul",{className:"flex flex-col gap-0.5",children:[t?e.jsxs("li",{className:"flex items-baseline gap-1.5",children:[e.jsx("span",{className:"text-body-sm text-ink-muted",children:t}),e.jsx("span",{className:"text-ink-dim text-meta",children:"Manager"})]}):null,s.members.map(o=>e.jsxs("li",{className:"flex items-baseline gap-1.5",children:[e.jsx("span",{className:"text-body-sm text-ink-muted",children:o.role}),e.jsx("span",{className:"text-ink-dim text-meta",children:St(o.kind)}),o.count>1?e.jsxs("span",{className:"text-ink-dim text-meta tabular-nums",children:["×",o.count]}):null]},`${o.kind}:${o.role}`)),l?null:e.jsx("li",{className:"text-ink-dim text-meta",children:"No members"})]})]}):null,i.length>0?e.jsx("p",{className:"text-ink-dim text-meta",children:i.join(" · ")}):null]})},me=()=>e.jsxs("div",{className:C(We,"pl-9"),"data-testid":"org-team-skeleton-row",children:[e.jsx("div",{className:"flex h-[1lh] items-center text-body",children:e.jsx(x,{className:"h-4.5 w-40"})}),e.jsxs("div",{className:"mt-1 flex h-[2lh] flex-col justify-evenly text-body-sm",children:[e.jsx(x,{className:"h-3.5 w-full"}),e.jsx(x,{className:"h-3.5 w-2/3"})]}),e.jsx("div",{className:"mt-1 flex h-[1lh] items-center text-meta",children:e.jsx(x,{className:"h-3 w-64"})}),e.jsx("div",{className:"flex h-[1lh] items-center text-meta",children:e.jsx(x,{className:"h-3 w-48"})})]}),zt={loading:"The public hub lists agents only. Checking your organizations…",orgs:"The public hub lists agents only. Choose an organization to see the teams it has shared with its members.","signed-out":"The public hub lists agents only. Sign in to Radient to see the teams shared with the organizations you belong to.",unavailable:"The public hub lists agents only, and this backend does not serve organizations, so there are no teams to list here.",unreadable:"The public hub lists agents only, and your organizations could not be read, so no teams can be listed.",none:"The public hub lists agents only. You are not in an organization on the Team plan yet, and an organization owner can add you or activate the plan in the Radient console."},It=({reason:s,orgs:t,onPickOrg:n,onOpenSettings:i,onRetry:l,retrying:o})=>{const h=r.useRef(null),j=r.useRef(null),g=r.useRef(!1);return r.useEffect(()=>{g.current&&(g.current=!1,(j.current??h.current)?.focus())}),e.jsxs("section",{ref:h,tabIndex:-1,className:"flex max-w-2xl flex-col items-start gap-2 rounded-md bg-surface px-6 py-8","aria-labelledby":"agent-hub-teams-public-heading","data-testid":"agent-hub-teams-public",children:[e.jsx("h2",{id:"agent-hub-teams-public-heading",className:"font-medium text-heading text-ink",children:"Teams are shared inside organizations"}),e.jsx("output",{className:"block max-w-md text-body-sm text-ink-muted",children:zt[s]}),s==="orgs"&&e.jsx("div",{className:"mt-2 flex flex-wrap items-center gap-2",children:t.map(u=>e.jsxs(f,{variant:"secondary",onClick:()=>n(u.tenant_id),children:[e.jsx(He,{"aria-hidden":"true"}),e.jsx("span",{className:"max-w-48 truncate",children:u.tenant_name||"Organization"})]},u.tenant_id))}),s==="signed-out"&&e.jsx("div",{className:"mt-2",children:e.jsx(f,{variant:"secondary",onClick:i,children:"Open settings to sign in"})}),s==="unreadable"&&e.jsx("div",{className:"mt-2",children:e.jsx(f,{ref:j,variant:"secondary",onClick:()=>{g.current=!0,l()},disabled:o,"aria-busy":o,children:o?"Trying…":"Try again"})})]})},Mt=(s,t)=>{const[n,i]=r.useState(s);return r.useEffect(()=>{const l=setTimeout(()=>i(s),t);return()=>clearTimeout(l)},[s,t]),n},K=[{value:"download_count:desc",label:"Most downloaded",sort:"download_count",order:"desc"},{value:"like_count:desc",label:"Most liked",sort:"like_count",order:"desc"},{value:"favourite_count:desc",label:"Most favourited",sort:"favourite_count",order:"desc"},{value:"created_at:desc",label:"Newest",sort:"created_at",order:"desc"},{value:"updated_at:desc",label:"Recently updated",sort:"updated_at",order:"desc"},{value:"name:asc",label:"Name (A to Z)",sort:"name",order:"asc"}],Ft=[{value:"name",label:"Name"},{value:"description",label:"Description"}],$t=300,H="public",$e={agents:"agent-hub-view-agents",teams:"agent-hub-view-teams"},Le="agent-hub-view-panel",Lt=()=>e.jsxs("div",{className:"flex h-full flex-col overflow-hidden rounded-md bg-surface",children:[e.jsxs("div",{className:"flex min-h-0 flex-1 flex-col gap-2 p-4",children:[e.jsx(x,{className:"h-5.5 w-2/3"}),e.jsx(x,{className:"h-3.5 w-full"}),e.jsx(x,{className:"h-3.5 w-full"}),e.jsx(x,{className:"h-3.5 w-1/2"}),e.jsxs("div",{className:"mt-auto flex flex-col gap-2 pt-2",children:[e.jsxs("div",{className:"flex flex-col gap-1.5",children:[e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx(x,{className:"h-5.5 w-24"}),e.jsx(x,{className:"h-5.5 w-20"})]}),e.jsx("div",{className:"flex items-center gap-1.5",children:e.jsx(x,{className:"h-5.5 w-24"})})]}),e.jsx(x,{className:"h-4.5 w-32"})]})]}),e.jsxs("div",{className:"flex items-center gap-2 border-t border-hairline px-3 py-2",children:[e.jsx(x,{className:"size-4"}),e.jsx(x,{className:"h-4 w-6"}),e.jsx(x,{className:"size-4"}),e.jsx(x,{className:"h-4 w-6"}),e.jsx(x,{className:"ml-auto h-7 w-16"})]})]}),sa=()=>{const s=Ue(),{isAuthenticated:t}=xe(),[n,i]=r.useState(1),[l]=r.useState(12),[o,h]=r.useState(null),[j,g]=r.useState(""),[u,v]=r.useState("name"),[N,p]=r.useState(K[0].value),[b,y]=r.useState(H),[m,L]=r.useState("agents"),[D,I]=r.useState([]),S=Mt(j,$t),M=K.find(a=>a.value===N)??K[0],Y=gs(),B=Is(),F=fs(Y.data,"radient_org"),A=t?at(F,B??null):null,{memberships:c,isError:d,isPending:$,isFetching:P,refetch:Ze}=Us({enabled:nt(F)}),U=r.useMemo(()=>tt(c),[c]),ge=b===H||U.some(a=>a.tenant_id===b);r.useEffect(()=>{ge||y(H)},[ge]);const w=b===H?null:U.find(a=>a.tenant_id===b)??null,T=w?.tenant_id,fe=w?.tenant_name||null,V=o!==null||S!=="",ne=Qe({tenantId:T}),W=T&&ne.isSuccess&&!V?ne.teams.length:null,Xe=w?.role==="owner"||w?.role==="admin",Ke=r.useMemo(()=>new Map(c.map(a=>[a.tenant_id,a.tenant_name])),[c]),{data:G,agents:Je,isLoading:es,isFetching:R,error:O,refetch:pe,pagination:_}=Vs({page:n,perPage:l,categories:o?[o]:void 0,name:u==="name"&&S||void 0,description:u==="description"&&S||void 0,sort:M.sort,order:M.order,tenantId:T}),q=w?qe(O):null,Z=Je??[],be=R&&G!==void 0,{statuses:je,isKnown:ss,isError:ts,isFetching:ie,refetch:as}=Js({agentIds:T?[]:Z.map(a=>a.id)}),re=r.useRef(null),le=r.useRef(null),[ve,ns]=r.useState(0);r.useEffect(()=>{ve!==0&&(re.current??le.current)?.focus()},[ve]);const Ne=r.useRef(null),oe=r.useRef(!1),ce=r.useMemo(()=>[...new Set((G?.records??[]).flatMap(a=>a.categories??[]))],[G]);r.useEffect(()=>{I(a=>ce.every(z=>a.includes(z))?a:[...new Set([...a,...ce])])},[ce]);const is=()=>{h(null),g(""),i(1),ns(a=>a+1)},k=(es||R)&&G===void 0,ye=!k&&!V&&(O!==null||Z.length===0);r.useEffect(()=>{!oe.current||k||(oe.current=!1,O?Ne.current?.focus():(re.current??le.current)?.focus())},[k,O]);const we=r.useRef(null),rs=a=>{i(a),we.current?.scrollIntoView({block:"nearest"})},ls=a=>{h(a),i(1)},os=a=>{g(a),i(1)},ke=a=>{y(a),i(1)},de=r.useRef(new Map),X=r.useRef(null);r.useEffect(()=>{X.current!==null&&(de.current.get(X.current)?.focus(),X.current=null)},[b]);const cs=a=>{v(a),i(1)},Te=_&&!V?_.totalRecords:null,ds=U.length>0?"orgs":t?A?"unavailable":d?"unreadable":F==="unknown"||$?"loading":"none":"signed-out",ue=T?`shared with ${fe??"this organization"}`:"in the public hub",Ce=(a,z)=>`${a} ${z}${a===1?"":"s"} ${ue}`;let E;return m==="teams"?T?ne.isLoading?E="Loading teams…":W!==null?E=Ce(W,"team"):E=`Teams ${ue}`:E=" ":k?E="Loading agents…":_?E=Ce(_.totalRecords,"agent"):E=`Agents ${ue}`,e.jsxs("div",{className:"flex h-full flex-col gap-8 p-6",children:[e.jsx(ps,{title:"Agent hub",subtitle:"Discover and download community agents on Radient",icon:Ms}),e.jsxs("div",{className:"flex min-h-0 flex-1 flex-col gap-4",children:[A&&e.jsxs(J,{variant:"warning",className:"max-w-2xl","data-testid":"agent-hub-org-unavailable",children:[e.jsx(ee,{children:"Organizations are unavailable"}),e.jsx(se,{children:A})]}),e.jsxs("div",{className:"flex shrink-0 flex-wrap items-center gap-x-4 gap-y-2","data-testid":"agent-hub-browse-bar",children:[e.jsx(js,{value:m,onValueChange:a=>L(a),children:e.jsx(vs,{"aria-label":"Browse the hub by type",children:["agents","teams"].map(a=>e.jsxs(Ns,{value:a,id:$e[a],"aria-controls":m===a?Le:void 0,"data-testid":`agent-hub-view-${a}`,children:[a==="agents"?"Agents":"Teams",(a==="agents"?Te:W)!==null&&e.jsx("span",{className:"min-w-[2ch] font-normal text-ink-dim tabular-nums",children:a==="agents"?Te:W})]},a))})}),U.length>0&&e.jsxs("div",{className:"ml-auto flex min-w-0 items-center gap-2",children:[e.jsx("span",{"aria-hidden":"true",className:"text-meta text-ink-muted",children:"Showing"}),e.jsxs("fieldset",{className:"m-0 min-w-0 border-0 p-0","data-testid":"agent-hub-scope",children:[e.jsx("legend",{className:"sr-only",children:"Show the hub of"}),e.jsx("div",{className:"flex flex-wrap gap-0.5 rounded-md bg-sunken p-0.5",children:[{value:H,label:"Public hub",Icon:Fs},...U.map(a=>({value:a.tenant_id,label:a.tenant_name||"Organization",Icon:He}))].map(({value:a,label:z,Icon:us})=>e.jsxs(f,{ref:Se=>{Se?de.current.set(a,Se):de.current.delete(a)},variant:"ghost",size:"sm","aria-pressed":b===a,onClick:()=>ke(a),title:z,"data-testid":`agent-hub-scope-${a===H?"public":`org-${a}`}`,className:C("max-w-48",b===a&&"bg-surface text-ink hover:bg-surface"),children:[e.jsx(us,{"aria-hidden":"true"}),e.jsx("span",{className:"truncate",children:z})]},a))})]})]})]}),e.jsx(ys,{id:Le,labelledBy:$e[m],children:e.jsxs("div",{className:"flex min-h-0 flex-1 flex-row overflow-hidden",children:[m==="agents"&&e.jsx(e.Fragment,{children:e.jsx("div",{className:"mr-6 hidden w-60 shrink-0 rounded-md bg-surface p-2 md:block","data-tour-tag":"agent-hub-sidebar-container",children:!ye&&e.jsx(mt,{selectedCategory:o,onSelectCategory:ls,categories:D})})}),e.jsxs("div",{className:"flex min-w-0 flex-1 flex-col overflow-y-auto",children:[m==="agents"&&!ye&&e.jsxs("div",{className:"mb-4 flex flex-wrap items-center gap-2",children:[e.jsxs("div",{className:C("flex min-w-56 flex-1 items-center rounded-sm border border-control bg-surface","transition-colors duration-fast ease-out-quart","has-[:focus-visible]:outline-solid has-[:focus-visible]:outline-2","has-[:focus-visible]:outline-accent has-[:focus-visible]:outline-offset-2"),children:[e.jsx(ws,{ref:re,type:"search",value:j,onChange:a=>os(a.target.value),placeholder:"Search agents","aria-label":"Search agents",className:"h-8 min-w-0 flex-1 border-0 bg-transparent outline-none","data-testid":"agent-hub-search"}),e.jsxs(_e,{value:u,onValueChange:cs,children:[e.jsx(Ae,{className:"w-auto shrink-0 border-y-0 border-l border-hairline border-r-0 bg-transparent pl-2 outline-none","aria-label":"Search in","data-testid":"agent-hub-search-scope",children:e.jsx(Pe,{})}),e.jsx(Oe,{children:Ft.map(a=>e.jsx(Ee,{value:a.value,children:a.label},a.value))})]})]}),e.jsxs(_e,{value:N,onValueChange:p,children:[e.jsx(Ae,{className:"w-48","aria-label":"Sort agents","data-testid":"agent-hub-sort",children:e.jsx(Pe,{})}),e.jsx(Oe,{children:K.map(a=>e.jsx(Ee,{value:a.value,children:a.label},a.value))})]})]}),e.jsxs("p",{ref:we,"aria-live":"polite",className:"mb-3 text-meta text-ink-dim","data-testid":"agent-hub-status",children:[E,m==="agents"&&be?e.jsxs(e.Fragment,{children:[" ",e.jsx("span",{"data-testid":"agent-hub-updating",children:"Updating…"})]}):null]}),m==="agents"&&e.jsxs(e.Fragment,{children:[t&&ts&&e.jsxs("output",{className:"mb-3 flex flex-wrap items-center gap-2 text-meta text-warning","data-testid":"agent-hub-status-unknown",children:[e.jsx("span",{children:"Your likes and favourites could not be read, so no card shows a viewer state."}),e.jsx(f,{variant:"ghost",size:"sm",onClick:()=>void as(),disabled:ie,"aria-busy":ie,children:ie?"Trying…":"Try again"})]}),k&&e.jsx("div",{"data-testid":"agent-hub-loading",className:"grid grid-cols-[repeat(auto-fill,minmax(17.5rem,1fr))] gap-6",children:Array.from({length:6},(a,z)=>e.jsx(Lt,{},z))}),k&&_===void 0&&e.jsx("div",{"aria-hidden":"true",className:"mt-6 flex min-h-13 items-center justify-center","data-testid":"agent-hub-pager-placeholder",children:e.jsx(x,{className:"h-4 w-24"})}),e.jsx("output",{"aria-live":"polite","data-testid":"agent-hub-outage",className:C(!k&&O&&!q?"block":"sr-only"),children:!k&&O&&!q&&e.jsxs(J,{variant:"danger",className:"max-w-2xl","aria-busy":R,"data-testid":"agent-hub-error",children:[e.jsx(ee,{children:t?"The hub could not be loaded":"Sign in to use the hub"}),e.jsx(se,{children:t?De("The agent list could not be loaded.",O):"You are not signed in to Radient, so the hub has no credential to read the agent list with. Sign in on the settings page, then try again."}),e.jsx("div",{className:"mt-2",children:e.jsx(f,{ref:Ne,variant:"outline",size:"sm",onClick:()=>{oe.current=!0,pe()},disabled:R,"aria-busy":R,children:R?"Trying…":"Try again"})})]})}),!k&&q&&w&&e.jsxs(J,{variant:"warning",className:"max-w-2xl","data-testid":"agent-hub-org-no-access",children:[e.jsx(ee,{children:q==="plan"?"That organization needs an active Team plan":"You do not have access to that organization"}),e.jsx(se,{children:q==="plan"?`Sharing agents inside an organization is part of the Team plan. An owner of ${w.tenant_name||"this organization"} can activate it in the Radient console, and then its agents will be listed here.`:`You are not a member of ${w.tenant_name||"that organization"}, so its agents are not listed here. An owner can invite you again.`}),q==="plan"&&e.jsx("div",{className:"mt-2",children:e.jsx(f,{variant:"primary",size:"sm",onClick:()=>void pe(),disabled:R,"aria-busy":R,children:R?"Trying…":"Try again"})})]}),!k&&!O&&e.jsx("div",{className:"grid grid-cols-[repeat(auto-fill,minmax(17.5rem,1fr))] gap-6","aria-busy":be,children:Z.length===0?e.jsxs("div",{"data-testid":"agent-hub-empty",className:C("col-span-full w-full flex flex-col items-center gap-2 rounded-md bg-surface px-6 py-10 text-center",!T&&"max-w-2xl justify-self-center"),children:[e.jsx("p",{className:"text-heading text-ink",children:T?"This organization has no shared agents yet.":o?`No agents in ${Ve(o).label}.`:V?"No agents match that search.":"The hub is empty."}),e.jsx("p",{className:"max-w-md text-body-sm text-ink-muted",children:T?`Agents published into ${w?.tenant_name||"this organization"} appear here for its members.`:o?"Nothing in this category yet. Clear the filter to see the whole hub.":V?"No agent's name or description carries that. Clear it to see the whole hub.":"Nobody has published an agent yet. Yours could be the first."}),e.jsx("div",{className:"mt-2 flex flex-wrap items-center justify-center gap-2",children:V?e.jsx(f,{variant:"secondary",onClick:is,children:o?"Clear filter":"Clear search"}):T&&!Xe?null:e.jsx(f,{ref:le,variant:"secondary",onClick:()=>s("/agents"),children:"Publish an agent"})})]}):Z.map(a=>e.jsx(dt,{agent:a,status:t?je[a.id]:void 0,viewerStateKnown:t&&et(ss,je,a.id),orgName:a.visibility==="org"?Ke.get(a.tenant_id)??null:null},a.id))}),!k&&_&&_.totalPages>1&&e.jsx(ht,{count:_.totalPages,page:_.page,onChange:rs})]}),m==="teams"&&(w?e.jsx(_t,{tenantId:w.tenant_id,orgName:fe}):e.jsx(It,{reason:ds,orgs:U,onPickOrg:a=>{X.current=a,ke(a)},onOpenSettings:()=>s("/settings"),onRetry:()=>void Ze(),retrying:P}))]})]})})]})]})};export{sa as AgentHubPage};
11
+ */const lt=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"M17 12h.01",key:"1m0b6t"}],["path",{d:"M12 12h.01",key:"1mp3jc"}],["path",{d:"M7 12h.01",key:"eqddd0"}]],ot=Ue("circle-ellipsis",lt),ct=({agent:s,isLiked:t,isFavourited:n,onLikeToggle:i,onFavouriteToggle:l,onDownload:o,isLikeActionLoading:h=!1,isFavouriteActionLoading:j=!1,isDownloading:g=!1,actionError:u=null,onRetryAction:v,showActions:N=!0,viewerStateKnown:p=!0,orgName:b=null})=>{const y=De(),{isAuthenticated:m}=xe(),$=s.description??"",[D,I]=r.useState(!1),S=r.useRef(null),M=r.useCallback(d=>{if(S.current?.disconnect(),S.current=null,!d)return;const L=()=>I(d.scrollHeight-d.clientHeight>1);L();const P=new ResizeObserver(L);P.observe(d),S.current=P},[]),Y=m?p?t?"Unlike agent":"Like agent":"Your likes could not be read, so this is not shown as unliked.":"Log in to Radient to like agents",B=m?p?n?"Unfavourite agent":"Favourite agent":"Your favourites could not be read, so this is not shown as unfavourited.":"Log in to Radient to favourite agents",F=p?t?"Unlike agent":"Like agent":"Like state unavailable",A=p?n?"Unfavourite agent":"Favourite agent":"Favourite state unavailable",c=s.visibility==="org";return e.jsxs("div",{className:"flex h-full flex-col overflow-hidden rounded-md bg-surface transition-colors duration-fast ease-out-quart hover:bg-elevated",children:[e.jsxs("button",{type:"button",onClick:()=>y(`/agent-hub/${s.id}`),className:"flex min-h-0 flex-1 cursor-pointer flex-col gap-2 p-4 text-left","aria-label":`View details for ${s.name}`,children:[e.jsx("h3",{className:"truncate font-medium text-heading text-ink",children:s.name}),c&&e.jsx($s,{orgName:b}),e.jsx(Q,{content:D?$:"",children:e.jsx("span",{ref:M,className:"line-clamp-3 min-h-0 text-body-sm text-ink-muted",children:$})}),e.jsxs("div",{className:"mt-auto flex flex-col gap-2 pt-2",children:[e.jsx(Ds,{tags:s.tags,categories:s.categories}),e.jsxs("p",{className:"truncate text-ink-dim text-meta",children:[s.account_metadata?.name??"Unknown author",e.jsx("span",{"aria-hidden":"true",className:"mx-1.5",children:"·"}),"updated ",Bs(new Date(s.updated_at))," ago"]})]})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-x-2 gap-y-1 border-t border-hairline px-3 py-2",children:[e.jsxs("div",{className:"flex min-w-0 items-center gap-0.5","data-viewer-state":c?"org":m?p?"known":"unknown":"signed-out",children:[!c&&e.jsxs(e.Fragment,{children:[e.jsx(Q,{content:Y,children:e.jsx("span",{children:e.jsxs(f,{variant:"ghost",size:"sm",onClick:m&&p?()=>i(s.id):void 0,disabled:h||!m||!p,"aria-label":F,className:C(t&&"text-danger"),children:[e.jsx(Us,{fill:t?"currentColor":"none","data-testid":"agent-like-heart"}),e.jsx("span",{"data-testid":"agent-like-count",className:"inline-flex h-4 min-w-4 items-center font-mono text-mono-sm text-ink-muted",children:s.like_count??0})]})})}),e.jsx(Q,{content:B,children:e.jsx("span",{children:e.jsxs(f,{variant:"ghost",size:"sm",onClick:m?()=>l(s.id):void 0,disabled:j||!m||!p,"aria-label":A,className:C(n&&"text-warning"),children:[e.jsx(Xs,{fill:n?"currentColor":"none","data-testid":"agent-favourite-star"}),e.jsx("span",{"data-testid":"agent-favourite-count",className:"inline-flex h-4 min-w-4 items-center font-mono text-mono-sm text-ink-muted",children:s.favourite_count??0})]})})})]}),e.jsx(Q,{content:"Downloads",children:e.jsxs("span",{className:"ml-1 inline-flex items-center gap-1 pr-1 text-ink-dim",children:[e.jsx(Re,{"aria-hidden":"true",className:"size-3.5"}),e.jsx("span",{className:"inline-flex h-4 min-w-6 items-center font-mono text-mono-sm",children:g?e.jsx(x,{className:"h-3 w-6"}):(s.download_count??0).toLocaleString()})]})})]}),N&&o&&e.jsx("div",{className:"ml-auto flex shrink-0 items-center",children:e.jsxs(f,{variant:"secondary",size:"sm",onClick:()=>o(s),disabled:g,"aria-label":`Download ${s.name}`,"data-tour-tag":"agent-hub-download-button",children:[e.jsx(Re,{"data-testid":"agent-download"}),"Get"]})})]}),u&&e.jsxs("output",{"data-testid":"agent-card-error",className:"flex flex-wrap items-center gap-x-2 gap-y-1 border-t border-hairline px-3 py-2 text-body-sm text-danger",children:[e.jsx("span",{className:"min-w-0 flex-1",children:u}),v&&e.jsx(f,{variant:"ghost",size:"sm",onClick:v,children:"Try again"})]})]})},dt=({agent:s,status:t,viewerStateKnown:n=!0,orgName:i=null})=>{const{isAuthenticated:l}=xe(),[o,h]=r.useState(null),j=t?.liked??!1,g=t?.favourited??!1,u=Vs(),v=qs(),N=Hs(),p=()=>{!l||u.isPending||(h(null),u.mutate({agentId:s.id,isCurrentlyLiked:j},{onError:()=>h("like")}))},b=()=>{!l||v.isPending||(h(null),v.mutate({agentId:s.id,isCurrentlyFavourited:g},{onError:()=>h("favourite")}))},y=()=>{N.isPending||(h(null),N.mutate({agentId:s.id,agentName:s.name},{onError:()=>h("download")}))},m=o?o==="like"?{action:"like",error:u.error,retry:p}:o==="favourite"?{action:"favourite",error:v.error,retry:b}:{action:"download",error:N.error,retry:y}:null;return e.jsx(ct,{agent:s,isLiked:l&&j,isFavourited:l&&g,onLikeToggle:p,onFavouriteToggle:b,onDownload:y,isLikeActionLoading:u.isPending,isFavouriteActionLoading:v.isPending,isDownloading:N.isPending,viewerStateKnown:n,orgName:i,actionError:m?Es(m.action,m.error,s.name):null,onRetryAction:m?.retry})},Ie=({selected:s,onClick:t,children:n,...i})=>e.jsx("button",{type:"button",onClick:t,"aria-pressed":s,className:C("flex w-full cursor-pointer items-center gap-2.5 rounded-sm px-3 py-1.5 text-left","text-body-sm transition-colors duration-fast ease-out-quart",s?Ks:"text-ink hover:bg-row-hover"),...i,children:n}),Me=Object.keys(Ys),ut=s=>[...s].sort((t,n)=>{const i=Me.indexOf(t),l=Me.indexOf(n);return i!==-1&&l!==-1?i-l:i!==-1?-1:l!==-1?1:t.localeCompare(n)}),mt=({selectedCategory:s,onSelectCategory:t,categories:n})=>{const i=ut(s&&!n.includes(s)?[...n,s]:n);return e.jsxs("div",{className:"flex h-full flex-col overflow-y-auto",children:[e.jsx("h2",{className:"mb-2 px-3 font-medium text-ink-dim text-meta",children:"Categories"}),e.jsxs("div",{className:"flex flex-col gap-0.5",children:[e.jsxs(Ie,{selected:s===null,onClick:()=>t(null),"data-testid":"category-all",children:[e.jsx("span",{className:"flex size-4 shrink-0 items-center justify-center",children:e.jsx(Zs,{size:16,"aria-hidden":"true"})}),"All categories"]}),i.map(l=>{const o=Ve(l),h=l==="other"?e.jsx(ot,{size:16}):o.icon;return e.jsxs(Ie,{selected:s===l,onClick:()=>t(l),"data-testid":`category-${l}`,children:[e.jsx("span",{className:"flex size-4 shrink-0 items-center justify-center",children:h}),o.label]},l)})]})]})},ht=({page:s,count:t,onChange:n})=>{const i=r.useRef(null),l=r.useRef(null),o=r.useRef(null);return r.useEffect(()=>{const h=o.current;o.current=null,h==="previous"&&i.current?.focus(),h==="next"&&l.current?.focus()},[s]),t<=1?null:e.jsxs("nav",{"aria-label":"Agent pages",className:"mt-6 flex min-h-13 items-center justify-between gap-3 border-t border-hairline","data-testid":"agent-hub-pager",children:[e.jsxs("span",{className:"select-none text-meta text-ink-dim",children:["Page ",s," of ",t]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(f,{variant:"secondary",size:"sm",ref:i,onClick:()=>{s-1<=1&&(o.current="next"),n(s-1)},disabled:s<=1,"aria-label":"Previous page",children:[e.jsx(Js,{"aria-hidden":"true"}),"Previous"]}),e.jsxs(f,{variant:"secondary",size:"sm",ref:l,onClick:()=>{s+1>=t&&(o.current="previous"),n(s+1)},disabled:s>=t,"aria-label":"Next page",children:["Next",e.jsx(Ss,{"aria-hidden":"true"})]})]})]})},Ye={all:["org-teams"],list:s=>[...Ye.all,"list",s]},Qe=({tenantId:s,enabled:t=!0})=>{const n=ms({queryKey:Ye.list(s??""),queryFn:async()=>(await zs(s)).result??{teams:[]},enabled:t&&!!s,staleTime:3e5,gcTime:6e5,refetchOnWindowFocus:!1,retryOnMount:!1,retry:hs});return{...n,teams:n.data?.teams??[]}},xt=(s,t)=>{const n=s?.name?.trim()||t?.trim()||"Team",i=s?.renamed_from?.trim()||null;return s?.invalid_name===!0&&i?{level:"warning",message:`Pulled "${n}". The published name "${i}" is not usable locally, so the team was stored as "${n}".`}:i?{level:"success",message:`Pulled "${n}" (you already have a team called "${i}").`}:{level:"success",message:`Pulled team "${n}".`}},gt=()=>{const s=xs();return gs({mutationFn:async({teamId:t,tenantId:n})=>{if(!_e.baseUrl)throw new Error("Local Operator API URL is not configured.");return bs.pullOrgTeamFromRadient(_e.baseUrl,t,n)},onSuccess:(t,n)=>{const i=xt(t.result,n.name);i.level==="warning"?fs(i.message):ps(i.message),s.invalidateQueries({queryKey:["desktop","teams"]})},onError:t=>{console.error("Pulling an organization team failed:",t)}})},ft=/^v/i,pt=s=>s.members.reduce((t,n)=>t+n.count,0),bt=s=>s.count>1?`${s.role} ×${s.count}`:s.role,jt=s=>s.members.map(bt).join(", "),vt=s=>{const t=(s.version??"").trim().replace(ft,"").trim();return t===""?null:t},Nt=s=>{const t=s.account_metadata?.name?.trim();return t||null},yt=s=>{const t=(s.description??"").trim();return t===""?null:t},he=240,wt=he/2,kt=(s,t)=>{if(t||s.length<=he)return s;const n=s.slice(0,he),i=n.lastIndexOf(" ");return`${(i>=wt?n.slice(0,i):n).trimEnd()}…`},te=s=>it(s,"d MMM yyyy"),ae=s=>{if(!s)return null;const t=new Date(s);return Number.isNaN(t.getTime())?null:t},Fe=(s,t,n)=>{const i=n-t.getTime();let l;return i<0?l=te(t):i<6e4?l="just now":l=`${Qs(t,new Date(n))} ago`,{label:s,when:l,iso:t.toISOString(),exact:te(t)}},Tt=(s,t=Date.now())=>{const n=ae(s.updated_at);if(n)return Fe("updated",n,t);const i=ae(s.created_date);return i?Fe("created",i,t):null},Ct=s=>{const t=ae(s.created_date),n=ae(s.updated_at);return{created:t?te(t):null,updated:n?te(n):null}},St=s=>s==="role"?"Role":s==="specialist"?"Specialist":s,Rt=["refresh-hub","retry","sign-in"],_t=({tenantId:s,orgName:t})=>{const{teams:n,isLoading:i,isFetching:l,isError:o,error:h,refetch:j}=Qe({tenantId:s}),g=qe(h),u=gt(),[v,N]=r.useState(null),[p,b]=r.useState(null),y=r.useRef(new Map),m=r.useRef(null);r.useEffect(()=>{u.isPending||m.current===null||(y.current.get(m.current)?.focus(),m.current=null)},[u.isPending]);const[$,D]=r.useState(!1),[I,S]=r.useState(()=>new Set),M=(c,d)=>S(L=>{const P=new Set(L);return d?P.add(c):P.delete(c),P}),Y=(c,d)=>{c.key!=="Escape"||!I.has(d)||(c.target instanceof Element?c.target:null)?.closest('[data-testid="org-team-pull-error"]')||(M(d,!1),c.currentTarget.querySelector("button[aria-expanded]")?.focus(),c.preventDefault())},B=r.useMemo(()=>{if(!js(u.error))return null;const c=n.find(d=>d.id===v);return Is({code:u.error.code,message:u.error.message,details:u.error.details},{name:c?.name??"this team",hubAgentId:null,surface:"pull"})},[u.error,v,n]),F=(c,d)=>{switch(c){case"refresh-hub":j();break;case"retry":A(d);break;case"sign-in":D(!0);break}},A=c=>{u.isPending||(m.current=c.id,N(null),b(c.id),u.mutate({teamId:c.id,tenantId:s,name:c.name},{onSettled:()=>b(null),onError:()=>N(c.id)}))};return e.jsxs("section",{className:"mb-6 max-w-4xl rounded-md bg-surface","aria-label":`Teams shared with ${t??"this organization"}`,"data-testid":"org-teams",children:[i&&e.jsxs("div",{"aria-hidden":"true",className:"flex flex-col divide-y divide-hairline","data-testid":"org-teams-loading",children:[e.jsx(me,{}),e.jsx(me,{}),e.jsx(me,{})]}),!i&&o&&e.jsxs(J,{variant:g?"warning":"danger",className:"m-4 w-auto","data-testid":"org-teams-error",children:[e.jsx(ee,{children:g==="plan"?"That organization needs an active Team plan":g==="no_access"?"You do not have access to that organization":"Teams could not be loaded"}),e.jsx(se,{children:g==="plan"?`Reading an organization's teams is part of the Team plan. An owner of ${t??"this organization"} can activate it in the Radient console, and then its teams will be listed here.`:g==="no_access"?`You are not a member of ${t??"that organization"}, so its teams are not listed here. An owner can invite you again.`:Be("The teams shared with this organization could not be read.",h)}),g!=="no_access"&&e.jsx("div",{className:"mt-2",children:e.jsx(f,{variant:"primary",size:"sm",onClick:()=>void j(),disabled:l,"aria-busy":l,children:l?"Trying…":"Try again"})})]}),!i&&!o&&n.length===0&&e.jsx("p",{className:"p-4 text-body-sm text-ink-muted","data-testid":"org-teams-empty",children:`Teams shared into ${t??"this organization"} appear here for its members.`}),!i&&!o&&n.length>0&&e.jsx("ul",{className:"flex flex-col divide-y divide-hairline",children:n.map(c=>e.jsxs("li",{className:C(We,"transition-colors duration-fast ease-out-quart hover:bg-elevated first:rounded-t-md last:rounded-b-md"),onKeyDown:d=>Y(d,c.id),children:[e.jsx(vs,{className:"min-w-0",open:I.has(c.id),onOpenChange:d=>M(c.id,d),summaryAlign:"firstLine",triggerClassName:"min-w-0",chevronClassName:"text-ink-dim mt-1",rowClassName:"py-0",summary:e.jsx(Ot,{team:c,expanded:I.has(c.id)}),trailing:e.jsx("div",{className:"-mt-1 ml-3 shrink-0 self-start",children:e.jsx(f,{ref:d=>{d?y.current.set(c.id,d):y.current.delete(c.id)},variant:"secondary",size:"sm",onClick:()=>A(c),disabled:u.isPending,"aria-label":`Pull team ${c.name}`,children:p===c.id?"Pulling…":"Pull"})}),children:e.jsx(Et,{team:c})}),v===c.id&&e.jsxs("div",{className:"mt-1 flex flex-col items-start gap-1 pl-5","data-testid":"org-team-pull-error",children:[e.jsx("output",{className:"text-meta text-danger",children:B?.body??u.error?.message??`"${c.name}" could not be pulled.`}),B?.actions.filter(d=>Rt.includes(d)).map(d=>e.jsx(f,{variant:"primary",size:"sm",onClick:()=>F(d,c),children:Ms[d]},d)),$&&e.jsx("div",{className:"mt-1","data-testid":"org-team-pull-reauth",children:e.jsx(st,{titleText:"Sign in again",descriptionText:"",onSignInSuccess:()=>{D(!1),N(null),j()}})})]})]},c.id))})]})},We="px-4 py-3",Ge=()=>e.jsxs(e.Fragment,{children:[e.jsx("span",{"aria-hidden":"true",className:"mx-1.5",children:"·"}),e.jsx("span",{className:"sr-only",children:", "})]}),At=({team:s})=>{const t=s.manager?.trim(),n=pt(s);return e.jsxs("span",{className:"block truncate text-meta",children:[t?e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"text-ink-dim",children:"Manager:"})," ",e.jsx("span",{className:"text-ink-muted",children:t})]}):null,t?e.jsx(Ge,{}):null,s.members.length===0?e.jsx("span",{className:"text-ink-dim",children:"No members"}):e.jsxs(e.Fragment,{children:[e.jsxs("span",{className:"text-ink-dim",children:[n," ",n===1?"member":"members",":"]})," ",e.jsx("span",{className:"text-ink-muted",children:jt(s)})]})]})},Pt=({team:s})=>{const t=s.project?.trim(),n=Nt(s),i=Tt(s),l=[];return t&&l.push({key:"project",node:t}),n&&l.push({key:"author",node:n}),i&&l.push({key:"recency",node:e.jsxs(e.Fragment,{children:[i.label," ",e.jsx(Q,{content:i.exact,children:e.jsx("time",{dateTime:i.iso,children:i.when})})]})}),l.length===0?null:e.jsx("span",{className:"block truncate text-ink-dim text-meta",children:l.map((o,h)=>e.jsxs("span",{children:[h>0?e.jsx(Ge,{}):null,o.node]},o.key))})},Ot=({team:s,expanded:t})=>{const n=yt(s),i=vt(s);return e.jsxs("span",{className:"flex min-w-0 flex-col",children:[e.jsxs("span",{className:"flex min-w-0 items-baseline",children:[e.jsx("span",{className:"truncate font-medium text-body text-ink",children:s.name}),i?e.jsxs("span",{className:"ml-2 shrink-0 text-ink-dim text-meta",children:["v",i]}):null]}),n?e.jsxs(e.Fragment,{children:[e.jsx("span",{...Ns,"aria-hidden":"true",className:C("mt-1 select-text break-words text-body-sm text-ink-muted",t?"line-clamp-[12] whitespace-pre-line":"line-clamp-2"),children:n}),e.jsx("span",{className:"sr-only",children:kt(n,t)})]}):e.jsx("span",{className:"mt-1 text-body-sm text-ink-dim",children:"No description"}),e.jsxs("span",{className:"mt-1 flex min-w-0 flex-col",children:[e.jsx(At,{team:s}),e.jsx(Pt,{team:s})]})]})},Et=({team:s})=>{const t=s.manager?.trim(),n=Ct(s),i=[n.created?`Created ${n.created}`:null,n.updated?`Updated ${n.updated}`:null].filter(o=>o!==null),l=!!t||s.members.length>0;return e.jsxs("div",{className:"mt-1 flex flex-col gap-2",children:[l||i.length===0?e.jsxs("div",{className:"flex flex-col gap-1",children:[e.jsx("p",{className:"text-ink-dim text-meta",children:"Members"}),e.jsxs("ul",{className:"flex flex-col gap-0.5",children:[t?e.jsxs("li",{className:"flex items-baseline gap-1.5",children:[e.jsx("span",{className:"text-body-sm text-ink-muted",children:t}),e.jsx("span",{className:"text-ink-dim text-meta",children:"Manager"})]}):null,s.members.map(o=>e.jsxs("li",{className:"flex items-baseline gap-1.5",children:[e.jsx("span",{className:"text-body-sm text-ink-muted",children:o.role}),e.jsx("span",{className:"text-ink-dim text-meta",children:St(o.kind)}),o.count>1?e.jsxs("span",{className:"text-ink-dim text-meta tabular-nums",children:["×",o.count]}):null]},`${o.kind}:${o.role}`)),l?null:e.jsx("li",{className:"text-ink-dim text-meta",children:"No members"})]})]}):null,i.length>0?e.jsx("p",{className:"text-ink-dim text-meta",children:i.join(" · ")}):null]})},me=()=>e.jsxs("div",{className:C(We,"pl-9"),"data-testid":"org-team-skeleton-row",children:[e.jsx("div",{className:"flex h-[1lh] items-center text-body",children:e.jsx(x,{className:"h-4.5 w-40"})}),e.jsxs("div",{className:"mt-1 flex h-[2lh] flex-col justify-evenly text-body-sm",children:[e.jsx(x,{className:"h-3.5 w-full"}),e.jsx(x,{className:"h-3.5 w-2/3"})]}),e.jsx("div",{className:"mt-1 flex h-[1lh] items-center text-meta",children:e.jsx(x,{className:"h-3 w-64"})}),e.jsx("div",{className:"flex h-[1lh] items-center text-meta",children:e.jsx(x,{className:"h-3 w-48"})})]}),zt={loading:"The public hub lists agents only. Checking your organizations…",orgs:"The public hub lists agents only. Choose an organization to see the teams it has shared with its members.","signed-out":"The public hub lists agents only. Sign in to Radient to see the teams shared with the organizations you belong to.",unavailable:"The public hub lists agents only, and this backend does not serve organizations, so there are no teams to list here.",unreadable:"The public hub lists agents only, and your organizations could not be read, so no teams can be listed.",none:"The public hub lists agents only. You are not in an organization on the Team plan yet, and an organization owner can add you or activate the plan in the Radient console."},It=({reason:s,orgs:t,onPickOrg:n,onOpenSettings:i,onRetry:l,retrying:o})=>{const h=r.useRef(null),j=r.useRef(null),g=r.useRef(!1);return r.useEffect(()=>{g.current&&(g.current=!1,(j.current??h.current)?.focus())}),e.jsxs("section",{ref:h,tabIndex:-1,className:"flex max-w-2xl flex-col items-start gap-2 rounded-md bg-surface px-6 py-8","aria-labelledby":"agent-hub-teams-public-heading","data-testid":"agent-hub-teams-public",children:[e.jsx("h2",{id:"agent-hub-teams-public-heading",className:"font-medium text-heading text-ink",children:"Teams are shared inside organizations"}),e.jsx("output",{className:"block max-w-md text-body-sm text-ink-muted",children:zt[s]}),s==="orgs"&&e.jsx("div",{className:"mt-2 flex flex-wrap items-center gap-2",children:t.map(u=>e.jsxs(f,{variant:"secondary",onClick:()=>n(u.tenant_id),children:[e.jsx(He,{"aria-hidden":"true"}),e.jsx("span",{className:"max-w-48 truncate",children:u.tenant_name||"Organization"})]},u.tenant_id))}),s==="signed-out"&&e.jsx("div",{className:"mt-2",children:e.jsx(f,{variant:"secondary",onClick:i,children:"Open settings to sign in"})}),s==="unreadable"&&e.jsx("div",{className:"mt-2",children:e.jsx(f,{ref:j,variant:"secondary",onClick:()=>{g.current=!0,l()},disabled:o,"aria-busy":o,children:o?"Trying…":"Try again"})})]})},Mt=(s,t)=>{const[n,i]=r.useState(s);return r.useEffect(()=>{const l=setTimeout(()=>i(s),t);return()=>clearTimeout(l)},[s,t]),n},K=[{value:"download_count:desc",label:"Most downloaded",sort:"download_count",order:"desc"},{value:"like_count:desc",label:"Most liked",sort:"like_count",order:"desc"},{value:"favourite_count:desc",label:"Most favourited",sort:"favourite_count",order:"desc"},{value:"created_at:desc",label:"Newest",sort:"created_at",order:"desc"},{value:"updated_at:desc",label:"Recently updated",sort:"updated_at",order:"desc"},{value:"name:asc",label:"Name (A to Z)",sort:"name",order:"asc"}],Ft=[{value:"name",label:"Name"},{value:"description",label:"Description"}],Lt=300,H="public",Le={agents:"agent-hub-view-agents",teams:"agent-hub-view-teams"},$e="agent-hub-view-panel",$t=()=>e.jsxs("div",{className:"flex h-full flex-col overflow-hidden rounded-md bg-surface",children:[e.jsxs("div",{className:"flex min-h-0 flex-1 flex-col gap-2 p-4",children:[e.jsx(x,{className:"h-5.5 w-2/3"}),e.jsx(x,{className:"h-3.5 w-full"}),e.jsx(x,{className:"h-3.5 w-full"}),e.jsx(x,{className:"h-3.5 w-1/2"}),e.jsxs("div",{className:"mt-auto flex flex-col gap-2 pt-2",children:[e.jsxs("div",{className:"flex flex-col gap-1.5",children:[e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx(x,{className:"h-5.5 w-24"}),e.jsx(x,{className:"h-5.5 w-20"})]}),e.jsx("div",{className:"flex items-center gap-1.5",children:e.jsx(x,{className:"h-5.5 w-24"})})]}),e.jsx(x,{className:"h-4.5 w-32"})]})]}),e.jsxs("div",{className:"flex items-center gap-2 border-t border-hairline px-3 py-2",children:[e.jsx(x,{className:"size-4"}),e.jsx(x,{className:"h-4 w-6"}),e.jsx(x,{className:"size-4"}),e.jsx(x,{className:"h-4 w-6"}),e.jsx(x,{className:"ml-auto h-7 w-16"})]})]}),ea=()=>{const s=De(),{isAuthenticated:t}=xe(),[n,i]=r.useState(1),[l]=r.useState(12),[o,h]=r.useState(null),[j,g]=r.useState(""),[u,v]=r.useState("name"),[N,p]=r.useState(K[0].value),[b,y]=r.useState(H),[m,$]=r.useState("agents"),[D,I]=r.useState([]),S=Mt(j,Lt),M=K.find(a=>a.value===N)??K[0],Y=ys(),B=ws(),F=ks(Y.data,"radient_org"),A=t?at(F,B??null):null,{memberships:c,isError:d,isPending:L,isFetching:P,refetch:Xe}=Fs({enabled:nt(F)}),U=r.useMemo(()=>tt(c),[c]),ge=b===H||U.some(a=>a.tenant_id===b);r.useEffect(()=>{ge||y(H)},[ge]);const w=b===H?null:U.find(a=>a.tenant_id===b)??null,T=w?.tenant_id,fe=w?.tenant_name||null,V=o!==null||S!=="",ne=Qe({tenantId:T}),W=T&&ne.isSuccess&&!V?ne.teams.length:null,Ze=w?.role==="owner"||w?.role==="admin",Ke=r.useMemo(()=>new Map(c.map(a=>[a.tenant_id,a.tenant_name])),[c]),{data:G,agents:Je,isLoading:es,isFetching:R,error:O,refetch:pe,pagination:_}=Ls({page:n,perPage:l,categories:o?[o]:void 0,name:u==="name"&&S||void 0,description:u==="description"&&S||void 0,sort:M.sort,order:M.order,tenantId:T}),q=w?qe(O):null,X=Je??[],be=R&&G!==void 0,{statuses:je,isKnown:ss,isError:ts,isFetching:ie,refetch:as}=Ws({agentIds:T?[]:X.map(a=>a.id)}),re=r.useRef(null),le=r.useRef(null),[ve,ns]=r.useState(0);r.useEffect(()=>{ve!==0&&(re.current??le.current)?.focus()},[ve]);const Ne=r.useRef(null),oe=r.useRef(!1),ce=r.useMemo(()=>[...new Set((G?.records??[]).flatMap(a=>a.categories??[]))],[G]);r.useEffect(()=>{I(a=>ce.every(z=>a.includes(z))?a:[...new Set([...a,...ce])])},[ce]);const is=()=>{h(null),g(""),i(1),ns(a=>a+1)},k=(es||R)&&G===void 0,ye=!k&&!V&&(O!==null||X.length===0);r.useEffect(()=>{!oe.current||k||(oe.current=!1,O?Ne.current?.focus():(re.current??le.current)?.focus())},[k,O]);const we=r.useRef(null),rs=a=>{i(a),we.current?.scrollIntoView({block:"nearest"})},ls=a=>{h(a),i(1)},os=a=>{g(a),i(1)},ke=a=>{y(a),i(1)},de=r.useRef(new Map),Z=r.useRef(null);r.useEffect(()=>{Z.current!==null&&(de.current.get(Z.current)?.focus(),Z.current=null)},[b]);const cs=a=>{v(a),i(1)},Te=_&&!V?_.totalRecords:null,ds=U.length>0?"orgs":t?A?"unavailable":d?"unreadable":F==="unknown"||L?"loading":"none":"signed-out",ue=T?`shared with ${fe??"this organization"}`:"in the public hub",Ce=(a,z)=>`${a} ${z}${a===1?"":"s"} ${ue}`;let E;return m==="teams"?T?ne.isLoading?E="Loading teams…":W!==null?E=Ce(W,"team"):E=`Teams ${ue}`:E=" ":k?E="Loading agents…":_?E=Ce(_.totalRecords,"agent"):E=`Agents ${ue}`,e.jsxs("div",{className:"flex h-full flex-col gap-8 p-6",children:[e.jsx(Cs,{title:"Agent hub",subtitle:"Discover and download community agents on Radient",icon:et}),e.jsxs("div",{className:"flex min-h-0 flex-1 flex-col gap-4",children:[A&&e.jsxs(J,{variant:"warning",className:"max-w-2xl","data-testid":"agent-hub-org-unavailable",children:[e.jsx(ee,{children:"Organizations are unavailable"}),e.jsx(se,{children:A})]}),e.jsxs("div",{className:"flex shrink-0 flex-wrap items-center gap-x-4 gap-y-2","data-testid":"agent-hub-browse-bar",children:[e.jsx(Rs,{value:m,onValueChange:a=>$(a),children:e.jsx(_s,{"aria-label":"Browse the hub by type",children:["agents","teams"].map(a=>e.jsxs(As,{value:a,id:Le[a],"aria-controls":m===a?$e:void 0,"data-testid":`agent-hub-view-${a}`,children:[a==="agents"?"Agents":"Teams",(a==="agents"?Te:W)!==null&&e.jsx("span",{className:"min-w-[2ch] font-normal text-ink-dim tabular-nums",children:a==="agents"?Te:W})]},a))})}),U.length>0&&e.jsxs("div",{className:"ml-auto flex min-w-0 items-center gap-2",children:[e.jsx("span",{"aria-hidden":"true",className:"text-meta text-ink-muted",children:"Showing"}),e.jsxs("fieldset",{className:"m-0 min-w-0 border-0 p-0","data-testid":"agent-hub-scope",children:[e.jsx("legend",{className:"sr-only",children:"Show the hub of"}),e.jsx("div",{className:"flex flex-wrap gap-0.5 rounded-md bg-sunken p-0.5",children:[{value:H,label:"Public hub",Icon:Ts},...U.map(a=>({value:a.tenant_id,label:a.tenant_name||"Organization",Icon:He}))].map(({value:a,label:z,Icon:us})=>e.jsxs(f,{ref:Se=>{Se?de.current.set(a,Se):de.current.delete(a)},variant:"ghost",size:"sm","aria-pressed":b===a,onClick:()=>ke(a),title:z,"data-testid":`agent-hub-scope-${a===H?"public":`org-${a}`}`,className:C("max-w-48",b===a&&"bg-surface text-ink hover:bg-surface"),children:[e.jsx(us,{"aria-hidden":"true"}),e.jsx("span",{className:"truncate",children:z})]},a))})]})]})]}),e.jsx(Ps,{id:$e,labelledBy:Le[m],children:e.jsxs("div",{className:"flex min-h-0 flex-1 flex-row overflow-hidden",children:[m==="agents"&&e.jsx(e.Fragment,{children:e.jsx("div",{className:"mr-6 hidden w-60 shrink-0 rounded-md bg-surface p-2 md:block","data-tour-tag":"agent-hub-sidebar-container",children:!ye&&e.jsx(mt,{selectedCategory:o,onSelectCategory:ls,categories:D})})}),e.jsxs("div",{className:"flex min-w-0 flex-1 flex-col overflow-y-auto",children:[m==="agents"&&!ye&&e.jsxs("div",{className:"mb-4 flex flex-wrap items-center gap-2",children:[e.jsxs("div",{className:C("flex min-w-56 flex-1 items-center rounded-sm border border-control bg-surface","transition-colors duration-fast ease-out-quart","has-[:focus-visible]:outline-solid has-[:focus-visible]:outline-2","has-[:focus-visible]:outline-accent has-[:focus-visible]:outline-offset-2"),children:[e.jsx(Os,{ref:re,type:"search",value:j,onChange:a=>os(a.target.value),placeholder:"Search agents","aria-label":"Search agents",className:"h-8 min-w-0 flex-1 border-0 bg-transparent outline-none","data-testid":"agent-hub-search"}),e.jsxs(Ae,{value:u,onValueChange:cs,children:[e.jsx(Pe,{className:"w-auto shrink-0 border-y-0 border-l border-hairline border-r-0 bg-transparent pl-2 outline-none","aria-label":"Search in","data-testid":"agent-hub-search-scope",children:e.jsx(Oe,{})}),e.jsx(Ee,{children:Ft.map(a=>e.jsx(ze,{value:a.value,children:a.label},a.value))})]})]}),e.jsxs(Ae,{value:N,onValueChange:p,children:[e.jsx(Pe,{className:"w-48","aria-label":"Sort agents","data-testid":"agent-hub-sort",children:e.jsx(Oe,{})}),e.jsx(Ee,{children:K.map(a=>e.jsx(ze,{value:a.value,children:a.label},a.value))})]})]}),e.jsxs("p",{ref:we,"aria-live":"polite",className:"mb-3 text-meta text-ink-dim","data-testid":"agent-hub-status",children:[E,m==="agents"&&be?e.jsxs(e.Fragment,{children:[" ",e.jsx("span",{"data-testid":"agent-hub-updating",children:"Updating…"})]}):null]}),m==="agents"&&e.jsxs(e.Fragment,{children:[t&&ts&&e.jsxs("output",{className:"mb-3 flex flex-wrap items-center gap-2 text-meta text-warning","data-testid":"agent-hub-status-unknown",children:[e.jsx("span",{children:"Your likes and favourites could not be read, so no card shows a viewer state."}),e.jsx(f,{variant:"ghost",size:"sm",onClick:()=>void as(),disabled:ie,"aria-busy":ie,children:ie?"Trying…":"Try again"})]}),k&&e.jsx("div",{"data-testid":"agent-hub-loading",className:"grid grid-cols-[repeat(auto-fill,minmax(17.5rem,1fr))] gap-6",children:Array.from({length:6},(a,z)=>e.jsx($t,{},z))}),k&&_===void 0&&e.jsx("div",{"aria-hidden":"true",className:"mt-6 flex min-h-13 items-center justify-center","data-testid":"agent-hub-pager-placeholder",children:e.jsx(x,{className:"h-4 w-24"})}),e.jsx("output",{"aria-live":"polite","data-testid":"agent-hub-outage",className:C(!k&&O&&!q?"block":"sr-only"),children:!k&&O&&!q&&e.jsxs(J,{variant:"danger",className:"max-w-2xl","aria-busy":R,"data-testid":"agent-hub-error",children:[e.jsx(ee,{children:t?"The hub could not be loaded":"Sign in to use the hub"}),e.jsx(se,{children:t?Be("The agent list could not be loaded.",O):"You are not signed in to Radient, so the hub has no credential to read the agent list with. Sign in on the settings page, then try again."}),e.jsx("div",{className:"mt-2",children:e.jsx(f,{ref:Ne,variant:"outline",size:"sm",onClick:()=>{oe.current=!0,pe()},disabled:R,"aria-busy":R,children:R?"Trying…":"Try again"})})]})}),!k&&q&&w&&e.jsxs(J,{variant:"warning",className:"max-w-2xl","data-testid":"agent-hub-org-no-access",children:[e.jsx(ee,{children:q==="plan"?"That organization needs an active Team plan":"You do not have access to that organization"}),e.jsx(se,{children:q==="plan"?`Sharing agents inside an organization is part of the Team plan. An owner of ${w.tenant_name||"this organization"} can activate it in the Radient console, and then its agents will be listed here.`:`You are not a member of ${w.tenant_name||"that organization"}, so its agents are not listed here. An owner can invite you again.`}),q==="plan"&&e.jsx("div",{className:"mt-2",children:e.jsx(f,{variant:"primary",size:"sm",onClick:()=>void pe(),disabled:R,"aria-busy":R,children:R?"Trying…":"Try again"})})]}),!k&&!O&&e.jsx("div",{className:"grid grid-cols-[repeat(auto-fill,minmax(17.5rem,1fr))] gap-6","aria-busy":be,children:X.length===0?e.jsxs("div",{"data-testid":"agent-hub-empty",className:C("col-span-full w-full flex flex-col items-center gap-2 rounded-md bg-surface px-6 py-10 text-center",!T&&"max-w-2xl justify-self-center"),children:[e.jsx("p",{className:"text-heading text-ink",children:T?"This organization has no shared agents yet.":o?`No agents in ${Ve(o).label}.`:V?"No agents match that search.":"The hub is empty."}),e.jsx("p",{className:"max-w-md text-body-sm text-ink-muted",children:T?`Agents published into ${w?.tenant_name||"this organization"} appear here for its members.`:o?"Nothing in this category yet. Clear the filter to see the whole hub.":V?"No agent's name or description carries that. Clear it to see the whole hub.":"Nobody has published an agent yet. Yours could be the first."}),e.jsx("div",{className:"mt-2 flex flex-wrap items-center justify-center gap-2",children:V?e.jsx(f,{variant:"secondary",onClick:is,children:o?"Clear filter":"Clear search"}):T&&!Ze?null:e.jsx(f,{ref:le,variant:"secondary",onClick:()=>s("/agents"),children:"Publish an agent"})})]}):X.map(a=>e.jsx(dt,{agent:a,status:t?je[a.id]:void 0,viewerStateKnown:t&&Gs(ss,je,a.id),orgName:a.visibility==="org"?Ke.get(a.tenant_id)??null:null},a.id))}),!k&&_&&_.totalPages>1&&e.jsx(ht,{count:_.totalPages,page:_.page,onChange:rs})]}),m==="teams"&&(w?e.jsx(_t,{tenantId:w.tenant_id,orgName:fe}):e.jsx(It,{reason:ds,orgs:U,onPickOrg:a=>{Z.current=a,ke(a)},onOpenSettings:()=>s("/settings"),onRetry:()=>void Xe(),retrying:P}))]})]})})]})]})};export{ea as AgentHubPage};
@@ -1,7 +1,7 @@
1
- const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["./legacy-agents-page-DnpWTuf8.js","./index-_dbvHdgc.js","./index-DuUnXH9L.css","./index-D3ICBbhi.js","./aida-control-CQx1CGx-.js","./ui-preferences-store-BLiDaCIL.js","./textarea-DeXGhzIK.js","./error-boundary-D3Um1PIl.js","./console-mirror-fXJ5fMxl.js","./console-mirror-DOrYoP_4.css","./index-2qmFWi_F.css","./page-header-B3kbzqCp.js","./settings-section-C9etJXA9.js","./use-memberships-query-BGPQ6jDl.js","./org-surface-gate-Da1VmZbG.js","./radient-auth-buttons-2wnsv7f6.js"])))=>i.map(i=>d[i]);
2
- import{aZ as ot,a_ as De,$ as fe,a$ as lt,a3 as ze,b0 as Ke,U as Se,b1 as ct,b2 as dt,b3 as ut,b4 as mt,b5 as ht,b6 as ft,b7 as gt,b8 as We,b9 as pt,a4 as xt,ba as bt,bb as jt,bc as yt,bd as Te,be as vt,a6 as kt,bf as Nt,bg as wt,bh as He,a5 as St,bi as Ct}from"./index-D3ICBbhi.js";import{r as l,j as e,c as Y}from"./index-_dbvHdgc.js";import{v as Et,a as Ve,u as At,J as It,h as V,d as re,y as Ne,D as $t,j as Je,B as Dt}from"./aida-control-CQx1CGx-.js";import{c as Tt,p as U,B as k,a as pe,q as Rt,r as Lt,f as ie,A as ee,h as te,i as se,I as le,s as Ge,t as Ye,u as Qe,v as Ze,w as xe,x as Ee,y as be,M as Ft,z as Ot,E as _t,F as Re}from"./textarea-DeXGhzIK.js";import{c as Ut}from"./ui-preferences-store-BLiDaCIL.js";import"./error-boundary-D3Um1PIl.js";import"./console-mirror-fXJ5fMxl.js";/**
1
+ const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["./legacy-agents-page-BSKz_UrV.js","./index-D-TXozHA.js","./index-C5Ighs_C.css","./conversation-input-sync-DQUYkOfh.js","./ui-preferences-store-B6Fr0UX9.js","./error-boundary-DH4MhqhL.js","./conversation-input-sync-CIGg7Rga.css","./page-header-DazB-GQz.js","./index-vK67PDia.js","./console-mirror-ffbsozOd.js","./console-mirror-DOrYoP_4.css","./index-DHKnfVbX.css","./settings-section-BGG4XzV0.js","./use-memberships-query-BgiSfYgr.js","./org-surface-gate-Dl4zcl5q.js","./radient-auth-buttons-DZeHRL7u.js"])))=>i.map(i=>d[i]);
2
+ import{a_ as lt,a as ze,u as ct,a$ as dt,X as V,b0 as Te,aN as fe,d as re,az as Ne,S as ut,aP as Ke,ag as We,b1 as He,aw as Se,b2 as Ve,b3 as mt,aQ as ht,b4 as ft,b5 as gt,b6 as pt,b7 as De,b8 as xt,aF as bt,b9 as jt,ba as yt,bb as vt}from"./conversation-input-sync-DQUYkOfh.js";import{r as l,j as e,c as Y}from"./index-D-TXozHA.js";import{_ as kt,$ as Nt,a0 as wt,a1 as St,a2 as Ct,a3 as Et,a4 as At,a5 as It,a6 as $t,a7 as Ge,b as Tt,a8 as Je,A as Dt}from"./index-vK67PDia.js";import{c as Rt,p as U,B as k,T as pe,q as Lt,r as Ft,e as ie,A as ee,g as te,h as se,I as le,s as Ye,t as Qe,u as Xe,v as Ze,w as xe,x as Ee,y as be,M as Ot,z as _t,F as Ut,G as Re}from"./error-boundary-DH4MhqhL.js";import{c as Mt}from"./ui-preferences-store-B6Fr0UX9.js";import"./console-mirror-ffbsozOd.js";/**
3
3
  * @license lucide-react v0.507.0 - ISC
4
4
  *
5
5
  * This source code is licensed under the ISC license.
6
6
  * See the LICENSE file in the root directory of this source tree.
7
- */const Mt=[["path",{d:"M15 3h4a2 2 0 0 1 2 2v14a2 2 0 0 1-2 2h-4",key:"u53s6r"}],["polyline",{points:"10 17 15 12 10 7",key:"1ail0h"}],["line",{x1:"15",x2:"3",y1:"12",y2:"12",key:"v6grx8"}]],Pt=Tt("log-in",Mt),Bt=["A reviewer that only reads code","Add the coder twice to release-crew","A team called shipping with a manager and two coders"],qt={idle:"bg-ink-dim",running:"bg-accent",stopping:"bg-warning",done:"bg-success",stopped:"bg-ink-muted",error:"bg-danger"};function zt({status:t,pulse:s}){return e.jsx("span",{"aria-hidden":"true",className:Y("size-2 shrink-0 rounded-full",qt[t]??"bg-ink-dim",s&&"animate-pulse")})}function Kt({run:t}){return t.activity.length===0?e.jsx("p",{className:"text-meta text-ink-muted",children:"Nothing to show yet — the run has not called a tool."}):e.jsx("ul",{className:"max-h-48 space-y-1 overflow-y-auto",children:t.activity.map((s,n)=>e.jsxs("li",{className:"flex items-baseline gap-2 text-body-sm",children:[e.jsx("span",{className:"text-ink-dim tabular-nums",children:new Date(s.ts).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"})}),e.jsx("span",{className:"text-ink",children:s.verb})]},`${s.ts}:${s.verb}:${n}`))})}function Le({run:t,onDismiss:s}){const[n,a]=l.useState(!1),r=l.useRef(null),d=t.status==="running"||t.status==="stopping";l.useEffect(()=>{if(!d)return;const h=g=>{g.key!=="Escape"||g.defaultPrevented||document.querySelector('[role="alertdialog"], [role="dialog"]')||r.current?.focus()};return window.addEventListener("keydown",h),()=>window.removeEventListener("keydown",h)},[d]);const f=t.status==="running"?t.step??"Working on your request":t.status==="stopping"?"Stopping":t.status==="done"?t.results.length>0?"Finished":"Finished without changing anything":t.status==="stopped"?"Stopped":t.status==="error"?t.canRetry?"Stopped with an error":"Finished with an error":"";return e.jsxs("div",{className:"border-hairline border-b pb-2","data-testid":"config-run-strip",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-x-3 gap-y-1",children:[e.jsx(zt,{status:t.status,pulse:d}),e.jsx("span",{"aria-live":"polite",className:"text-body-sm text-ink",children:f}),(d||t.status==="stopped"||t.status==="done")&&t.elapsed!=="0s"?e.jsx("span",{className:"text-meta text-ink-muted tabular-nums",children:t.elapsed}):null,t.touched.length>0?e.jsx(U,{variant:"neutral",children:t.touched.length===1?"1 definition":`${t.touched.length} definitions`}):null,e.jsxs("div",{className:"ml-auto flex items-center gap-1",children:[t.activity.length>0?e.jsxs(k,{variant:"ghost",size:"sm","aria-expanded":n,onClick:()=>a(h=>!h),children:[n?e.jsx(Rt,{className:"size-3.5"}):e.jsx(Lt,{className:"size-3.5"}),"Watch"]}):null,d?e.jsxs(k,{ref:r,variant:"secondary",size:"sm",disabled:t.status==="stopping",onClick:()=>void t.stop(),children:[e.jsx(Et,{className:"size-3.5"}),t.status==="stopping"?"Stopping…":"Stop"]}):e.jsx(k,{variant:"ghost",size:"sm",onClick:()=>s?s():t.dismiss(),children:"Dismiss"})]})]}),t.attached?e.jsx("p",{className:"mt-1 text-meta text-ink-muted",children:"Another configuration run was already going, so this page attached to it. Your request was not sent — it is still in the box."}):null,t.stopError?e.jsxs("div",{className:"mt-2 border-danger-border border-t pt-2","data-testid":"config-stop-refused",children:[e.jsx("p",{className:"text-body-sm text-danger",children:"The stop did not take — the run is still going."}),e.jsx("p",{className:"mt-0.5 text-meta text-ink-muted",children:t.stopError})]}):null,n?e.jsx("div",{className:"mt-2 border-hairline border-t pt-2",children:e.jsx(Kt,{run:t})}):null,t.status==="stopped"?e.jsxs("div",{className:"mt-2 space-y-1 border-hairline border-t pt-2 text-body-sm",children:[e.jsx("p",{className:"text-ink",children:t.results.length>0?"Stopped. Changes it had already made were kept.":"Stopped. Nothing had been changed yet."}),t.results.length>0?e.jsx("ul",{className:"space-y-0.5",children:t.results.map(h=>e.jsxs("li",{className:"text-ink-muted",children:[h.created?"Created ":"Changed ",e.jsx("span",{className:"text-ink",children:h.target.name})]},`${h.target.kind}:${h.target.name}`))}):null]}):null,t.status==="done"?e.jsx(Wt,{run:t}):null,t.status==="error"&&t.error?e.jsxs("div",{className:"mt-2 border-danger-border border-t pt-2",children:[e.jsx("p",{className:"text-body-sm text-danger",children:t.error}),e.jsxs("div",{className:"mt-1 flex items-center gap-2",children:[t.canRetry?e.jsx(k,{variant:"secondary",size:"sm","data-testid":"config-retry",disabled:t.starting,onClick:()=>void t.retry(),children:t.starting?"Sending…":"Retry"}):null,e.jsx("p",{className:"text-meta text-ink-muted",children:"Nothing else was changed by this run."})]})]}):null]})}function Wt({run:t}){return t.results.length===0?e.jsxs("div",{className:"mt-2 border-hairline border-t pt-2 text-body-sm",children:[e.jsx("p",{className:"text-ink-muted",children:"The run answered without changing any agent or team."}),t.answer?e.jsx("p",{className:"mt-1 whitespace-pre-wrap text-ink",children:t.answer}):null,t.topic?e.jsxs("p",{className:"mt-1 text-meta text-ink-muted",children:["You asked: ",t.topic]}):null]}):e.jsxs("div",{className:"mt-2 space-y-1 border-hairline border-t pt-2",children:[e.jsx("ul",{className:"space-y-1 text-body-sm",children:t.results.map(s=>e.jsxs("li",{children:[e.jsxs("span",{className:"text-ink",children:[s.created?"Created ":"Updated ",s.target.name]}),e.jsxs("span",{className:"text-ink-muted",children:[" (",s.target.kind,")"]}),s.changes.length>0?e.jsxs("span",{className:"text-ink-muted",children:[": ",s.changes.map(n=>n.label).join(", ")]}):s.created?null:e.jsx("span",{className:"text-ink-muted",children:": its settings changed. The list does not show instructions, so open it to see what was written."})]},`${s.target.kind}:${s.target.name}`))}),t.answer?e.jsx("p",{className:"whitespace-pre-wrap text-body-sm text-ink-muted",children:t.answer}):null]})}function Xe({run:t,hero:s=!1,blockedReason:n,about:a,onClearAbout:r,onStripHeightChange:d}){const f=l.useRef(null),h=l.useRef(null),g=l.useCallback(u=>{if(h.current?.disconnect(),h.current=null,!d)return;if(!u){d(0);return}const C=()=>d(u.getBoundingClientRect().height);if(C(),typeof ResizeObserver>"u")return;const E=new ResizeObserver(C);E.observe(u),h.current=E},[d]),i=t.status==="running"||t.status==="stopping",c=!t.enabled||i||!!n,b=a?`Change ${a.name}…`:t.enabled?"Ask for a new agent or change a team…":"Configure agents by conversation",y=a?`${a.kind}:${a.name}`:null;l.useEffect(()=>{if(!y)return;const u=f.current;if(!u||u.disabled)return;u.focus();const C=u.value.length;u.setSelectionRange?.(C,C)},[y]);const v=()=>{const u=t.draft.trim();!u||c||t.start(u,a)},j=()=>{t.dismiss(),f.current?.focus()},A=()=>{r(),f.current?.focus()};return e.jsxs("div",{className:Y("relative rounded-md border border-hairline bg-surface p-3",s&&"shadow-none"),"data-testid":"config-composer",children:[e.jsx("div",{className:"sr-only",id:"config-composer-label",children:"Ask for an agent or team change"}),t.enabled&&t.status!=="idle"?s?e.jsx(Le,{run:t,onDismiss:j}):e.jsx("div",{ref:g,className:"absolute inset-x-0 bottom-full rounded-t-md border-hairline border bg-canvas p-3",children:e.jsx(Le,{run:t,onDismiss:j})}):null,a?e.jsxs("div",{className:"mb-2 flex items-center gap-2",children:[e.jsxs(U,{variant:"accent","data-testid":"config-composer-about",children:["About ",a.kind," ",a.name]}),e.jsx(k,{variant:"ghost",size:"sm",onClick:A,children:"Clear"})]}):null,e.jsx("label",{className:"sr-only",htmlFor:"config-composer-input",children:b}),e.jsx(pe,{id:"config-composer-input",ref:f,"aria-describedby":"config-composer-note",className:"min-h-16",placeholder:b,value:t.draft,disabled:c||!t.enabled,onChange:u=>t.setDraft(u.target.value),onKeyDown:u=>{u.key==="Enter"&&!u.shiftKey&&(u.preventDefault(),v())}}),t.enabled&&!a&&!i&&!t.draft?e.jsx("div",{className:"mt-2 flex flex-wrap gap-1.5",children:Bt.map(u=>e.jsx(k,{variant:"outline",size:"sm",disabled:c,onClick:()=>{t.setDraft(u),f.current?.focus()},children:u},u))}):null,e.jsxs("div",{className:"mt-2 flex flex-wrap items-center gap-x-3 gap-y-2",children:[e.jsx(k,{variant:"primary",disabled:c||!t.draft.trim(),onClick:v,children:t.starting?"Starting…":"Ask for a change"}),n?e.jsx("p",{className:"text-meta text-warning",children:n}):null,e.jsx("p",{id:"config-composer-note",className:"text-meta text-ink-muted",children:t.enabled?"Runs in the background. This does not appear in your conversation.":t.disabledReason})]})]})}const Fe=(t,s)=>t.kind===s.kind&&t.name===s.name;function Ht(t){return`${t.kind}:${t.name}`}const K=Ut(t=>({sessionId:null,status:"idle",topic:"",draft:"",about:null,error:null,stopError:null,unsent:!1,startedAt:null,settledAt:null,touched:[],results:[],answer:"",marks:[],before:null,setDraft:s=>t({draft:s}),setAbout:s=>t({about:s}),adopt:(s,n,a)=>t({sessionId:s,status:"running",topic:n,error:null,stopError:null,startedAt:Date.now(),settledAt:null,touched:[],results:[],answer:"",before:a,unsent:!1}),acceptDraft:()=>t({draft:""}),noteTouched:s=>t(n=>n.touched.some(a=>Fe(a,s))?n:{touched:[...n.touched,s]}),stopping:()=>t(s=>s.status==="running"?{status:"stopping",stopError:null}:s),stopFailed:s=>t({status:"running",stopError:s}),settle:(s,n,a)=>t(()=>({status:n,settledAt:Date.now(),results:s,answer:a,marks:s.map(r=>({...r.target,created:r.created})),sessionId:null,stopError:null,before:null,unsent:!1})),fail:s=>t({status:"error",error:s,unsent:!1,stopError:null}),failUnsent:s=>t({status:"error",error:s,unsent:!0,stopError:null}),dismiss:()=>t({status:"idle",sessionId:null,error:null,stopError:null,unsent:!1,topic:"",touched:[],results:[],answer:"",marks:[],startedAt:null,settledAt:null,before:null}),clearMark:s=>t(n=>({marks:n.marks.filter(a=>!Fe(a,s))}))})),Vt=new Set(["agent","team"]);function Jt(t){const s=typeof t.args?.op=="string"?t.args.op:null,n=typeof t.args?.name=="string"?t.args.name:null,a=t.toolName==="team"?"team":"agent",r=n?{kind:a,name:n}:null,d=t.phase==="done"&&!t.isError&&!t.notRunReason&&!t.neverSent,f=h=>({writes:h&&d});switch(s){case"create":return{verb:n?`Creating ${a} ${n}`:`Creating a ${a}`,target:r,...f(!0)};case"update":return{verb:n?`Updating ${a} ${n}`:`Updating a ${a}`,target:r,...f(!0)};case"install":return{verb:n?`Installing ${n}`:"Installing an agent",target:r,...f(!0)};case"list":case"search":case"show":return{verb:n?`Reading ${n}`:`Reading ${a}s`,target:r,...f(!1)};default:return{verb:t.phase==="running"?`Working on ${a}s`:`Checked ${a}s`,target:r,...f(!0)}}}const Gt={description:"description",kind:"kind",tools:"tools",effort:"effort tier",delegate:"delegation",action_class:"class",manager:"manager",members:"members",instructions:"instructions"};function Yt(t){return{description:t.description??"",kind:t.kind,tools:t.tools&&t.tools.length>0?[...t.tools].sort().join(","):"*",effort:t.effort??"inherit",delegate:String(!!t.delegate)}}function Qt(t){return{description:t.description??"",manager:t.manager??"",members:(t.members??[]).map(s=>`${s.kind}:${s.role}x${s.count}`).sort().join(",")}}function Oe(t,s){return{agents:Object.fromEntries((t??[]).map(n=>[n.name,Yt(n)])),teams:Object.fromEntries((s??[]).map(n=>[n.name,Qt(n)]))}}function Zt(t,s){if(t===s)return"tools";const n=h=>h==="*"?null:new Set(h.split(",")),a=n(t),r=n(s);if(r===null)return"tools widened to every tool";if(a===null)return"tools narrowed to a list";const d=[...r].filter(h=>!a.has(h)),f=[...a].filter(h=>!r.has(h));return d.length&&!f.length?d.length===1?`tool added: ${d[0]}`:`${d.length} tools added`:f.length&&!d.length?f.length===1?`tool removed: ${f[0]}`:`${f.length} tools removed`:"tools changed"}function Xt(t,s,n){if(t==="tools")return Zt(s,n);if(t==="delegate")return n==="true"?"delegation turned on":"delegation turned off";if(t==="members"){const a=r=>r?r.split(",").length:0;return`members changed (${a(s)} to ${a(n)})`}return`${Gt[t]??t} changed`}function es(t,s,n){const a=[],r=new Set;for(const d of n){const f=`${d.kind}:${d.name}`;if(r.has(f))continue;r.add(f);const h=t[d.kind==="agent"?"agents":"teams"][d.name],g=s[d.kind==="agent"?"agents":"teams"][d.name];if(!g)continue;if(!h){a.push({target:d,created:!0,changes:[]});continue}const i=[];for(const c of Object.keys(g))g[c]!==h[c]&&i.push({label:Xt(c,h[c],g[c]),before:h[c],after:g[c]});a.push({target:d,created:!1,changes:i})}for(const[d,f]of[["agent",s.agents],["team",s.teams]])for(const h of Object.keys(f))r.has(`${d}:${h}`)||(d==="agent"?t.agents[h]:t.teams[h])||a.push({target:{kind:d,name:h},created:!0,changes:[]});return a}function ts(t){return re(t,"agents_config")&&re(t,"session_interrupt")&&re(t,"profile_catalogue")&&re(t,"team_catalogue")}function ss(t){if(!(t instanceof $t)||t.status!==409)return null;const n=t.detail?.session_id;return typeof n=="string"&&n.length>0?n:null}function ns(t,s){const[n,a]=l.useState(()=>Date.now());return l.useEffect(()=>{if(!t||!s)return;const r=setInterval(()=>a(Date.now()),1e3);return()=>clearInterval(r)},[t,s]),t?Math.max(0,n-t):0}function as(t){const s=Math.floor(t/1e3);return s<60?`${s}s`:`${Math.floor(s/60)}m ${String(s%60).padStart(2,"0")}s`}function _e(t){for(let s=(t?.length??0)-1;s>=0;s-=1){const n=t?.[s];if(n?.kind==="assistant"&&n.text?.trim())return n.text.trim()}return""}function rs(t){const n=t?.payload?.frontend;if(!n||typeof n!="object")return null;const a=n.streaming;if(typeof a=="boolean")return a;const r=n.snapshot?.streaming;return typeof r=="boolean"?r:null}function is(){const t=Ve(),s=ts(t.data),n=At(),a=K(),[r,d]=l.useState(!1),[f,h]=l.useState(!1),g=l.useRef(!1),i=a.status==="running"||a.status==="stopping",c=It(a.sessionId??void 0,!!a.sessionId),b=l.useMemo(()=>_e(c.transcript?.records),[c.transcript?.records]);ot(a.sessionId??void 0,c.subscriptionId);const y=c.transcript?.records,v=l.useRef(y);l.useEffect(()=>{v.current=y},[y]);const j=l.useMemo(()=>(c.transcript?.records??[]).filter(w=>w.kind==="tool"&&Vt.has(w.toolName)).map(w=>({...Jt({toolName:w.toolName,args:w.args??null,phase:w.phase,ts:w.ts,isError:w.isError,notRunReason:w.notRunReason,neverSent:w.neverSent}),ts:w.ts})),[c.transcript]);l.useEffect(()=>{if(i)for(const x of j)x.target&&x.writes&&a.noteTouched(x.target)},[j,i,a]);const A=i&&j.length>0?j[j.length-1].verb:null,u=as(ns(a.startedAt,i)),C=l.useCallback(async(x,w="")=>{if(g.current)return;g.current=!0;const M=a.before;let S=[];try{const[T,R]=await Promise.all([V({op:"profiles.list"}),V({op:"teams.list"})]);M&&(S=es(M,Oe(T.profiles,R.teams),a.touched))}catch{K.getState().fail("The run finished, but the agents and teams lists could not be read to describe what changed."),De(n);return}if(De(n),K.getState().settle(S,x,w),x==="done"&&S.length>0){const T=S.filter(R=>R.created).length;fe(T>0?`Configuration run finished: ${S.length} definition${S.length===1?"":"s"} changed.`:`Configuration run finished: ${S.length} definition${S.length===1?"":"s"} updated.`)}},[n,a.before,a.touched]);l.useEffect(()=>{if(i){if(c.failure){K.getState().fail(c.failure.statement);return}g.current||c.frontend&&(c.frontend.streaming||c.turnsCompleted!==0&&C(a.status==="stopping"?"stopped":"done",b))}},[i,b,c.failure,c.frontend,c.turnsCompleted,a.status,C]),l.useEffect(()=>{const x=a.sessionId;if(!i||!x)return;let w=!1;const M=async()=>{if(!(w||g.current))try{const R=await V({op:"sessions.get",sessionId:x});if(w||g.current||rs(R)!==!1)return;const _=_e(v.current);if(!_)return;C(K.getState().status==="stopping"?"stopped":"done",_)}catch{}},S=setTimeout(()=>void M(),400),T=setInterval(()=>void M(),4e3);return()=>{w=!0,clearTimeout(S),clearInterval(T)}},[i,a.sessionId,C]);const E=async(x,w)=>{if(r||!x.trim())return;d(!0),h(!1),g.current=!1;const M=Oe(n.getQueryData(["desktop","profiles"]),n.getQueryData(["desktop","teams"])),S=w?`About the ${w.kind} “${w.name}”: ${x.trim()}`:x.trim();try{let T;try{T=(await V({op:"sessions.create",requestId:crypto.randomUUID(),purpose:"agents-config"})).session_id}catch(R){const _=ss(R);if(_){h(!0),a.adopt(_,x.trim(),M);return}throw R}a.adopt(T,S,M),await B(T,S),a.acceptDraft()}catch(T){const R=K.getState().sessionId;K.getState().failUnsent(Ne(T,R?"The run was set up, but your request could not be sent. It is still in the box — send it again when the backend is reachable.":"The configuration run could not be started. Your request is still here."))}finally{d(!1)}},B=async(x,w)=>{await V({op:"sessions.message",sessionId:x,requestId:crypto.randomUUID(),text:w})},F=async()=>{const x=K.getState();if(!(r||!x.unsent||!x.sessionId||!x.topic)){d(!0);try{await B(x.sessionId,x.topic),a.acceptDraft(),a.adopt(x.sessionId,x.topic,x.before),g.current=!1}catch(w){K.getState().failUnsent(Ne(w,"The request could not be sent. It is still in the box."))}finally{d(!1)}}},P=async()=>{const x=K.getState().sessionId;if(x){a.stopping();try{await lt(x,crypto.randomUUID())}catch(w){K.getState().stopFailed(Ne(w,"The run did not acknowledge the request."))}}},N=s?null:t.isLoading?"Connecting to the backend…":t.error?"The backend could not be reached, so the composer is unavailable for now.":"Ask for a change needs a newer backend. Update Local Operator to configure agents by conversation.";return{enabled:s,disabledReason:N,status:a.status,sessionId:a.sessionId,topic:a.topic,error:a.error,stopError:a.stopError,draft:a.draft,setDraft:a.setDraft,about:a.about,setAbout:a.setAbout,touched:a.touched,results:a.results,answer:a.answer,step:A,elapsed:u,activity:j,start:E,stop:P,retry:F,canRetry:a.unsent&&!!a.sessionId,dismiss:a.dismiss,starting:r,attached:f}}const os=/Value error,\s*([\s\S]*?)\s*\[type=/,ls=/^\d+ validation errors? for \S+[\s\S]*?\n\s*/i,cs=/\s*\[type=[^\]]*\][\s\S]*$/m,ds=/\s*For further information visit \S+/g,us=/'([^']+)' already exists/,ms=/cannot contain spaces or path separators/i,hs=/effort tier '([^']+)' is unavailable/i,fs=/team name must be/i,gs=/manager '([^']+)'/i,ps=/(?:member|role) '([^']+)' (?:is not|does not)/i,xs=/depth|cycle|circular/i,bs=/instructions/i,js=/description/i;function ys(t){const s=t.match(os);return s?.[1]?s[1].trim():t.replace(ls,"").replace(cs,"").replace(ds,"").trim()}function je(t){const s=ys(t),n=s.match(us);if(n)return{message:`An agent called “${n[1]}” already exists. Choose another name, or open the existing one to change it.`,field:"name"};if(ms.test(s))return{message:"Names cannot contain spaces or slashes.",field:"name"};const a=s.match(hs);if(a)return{message:`“${a[1]}” is not a configured effort tier. Use inherit, or add the tier in Settings.`,field:"effort"};if(s.match(fs))return{message:"A team name is 1-64 characters.",field:"name"};const d=s.match(gs);if(d)return{message:`“${d[1]}” is not an agent or a team on this machine.`,field:"manager"};const f=s.match(ps);return f?{message:`“${f[1]}” is not an agent or a team on this machine.`,field:"members"}:xs.test(s)?{message:"That team would nest too deeply, or would contain itself. Check its members.",field:"members"}:bs.test(s)?{message:s,field:"instructions"}:js.test(s)?{message:s,field:"description"}:{message:s,field:null}}function vs(t,s){const n=new Set(s),a=`${t}-copy`;if(!n.has(a))return a;for(let r=2;r<100;r+=1){const d=`${a}-${r}`;if(!n.has(d))return d}return a}function L({title:t,description:s,actions:n,children:a,className:r}){return e.jsxs("section",{className:Y("space-y-2 border-hairline border-t pt-4 first:border-t-0 first:pt-0",r),children:[e.jsxs("div",{className:"flex flex-wrap items-baseline justify-between gap-x-3 gap-y-1",children:[e.jsx("h3",{className:"text-heading",children:t}),n]}),s?e.jsx("p",{className:"text-meta text-ink-muted",children:s}):null,a]})}function oe({text:t,empty:s="Nothing here yet.",mono:n=!1}){const[a,r]=l.useState(!1),[d,f]=l.useState(!1),h=l.useRef(null);return l.useEffect(()=>{if(a)return;const g=h.current;g&&f(!!t&&g.scrollHeight>g.clientHeight+1)},[t,a]),t.trim()?e.jsxs("div",{className:"space-y-1",children:[e.jsx("div",{ref:h,tabIndex:0,"aria-label":"The full text",className:Y("whitespace-pre-wrap rounded-sm border border-hairline bg-surface px-3 py-2 text-body-sm text-ink",!a&&"max-h-64 overflow-y-auto",n&&"font-mono text-meta"),children:t}),d?e.jsx(k,{variant:"link",size:"sm",onClick:()=>r(g=>!g),children:a?"Show less":"Show all"}):null]}):e.jsx("p",{className:"text-body-sm text-ink-muted",children:s})}function et({source:t,appearance:s="chip"}){const n=t==="builtin"?"Built-in":t==="installed"?"Installed":"Custom";return s==="text"?e.jsx("span",{className:"shrink-0 text-meta text-ink-dim",children:n}):e.jsx(U,{variant:"neutral",children:n})}function tt(t,s){l.useEffect(()=>{if(!s)return;const n=a=>{a.key!=="Escape"||a.defaultPrevented||(a.preventDefault(),t())};return window.addEventListener("keydown",n),()=>window.removeEventListener("keydown",n)},[s,t])}function Ae({dirty:t,pending:s,onSave:n,onCancel:a,saveLabel:r="Save changes",pendingLabel:d="Saving…",dirtyHint:f,submit:h,confirming:g,onConfirmingChange:i}){const[c,b]=l.useState(!1),y=l.useRef(null),v=g!==void 0,j=v?g:c,A=u=>{v||b(u),i?.(u)};return l.useEffect(()=>{t||(v||b(!1),i?.(!1))},[t,v,i]),e.jsxs("div",{"data-testid":"edit-footer",className:"sticky bottom-0 z-10 -mx-6 mt-6 flex flex-wrap items-center gap-2 border-hairline border-t bg-canvas px-6 py-3",children:[e.jsx(k,{ref:y,type:h?"submit":void 0,variant:"primary",onClick:h?void 0:n,disabled:s,children:s?d:r}),j?e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"text-body-sm text-ink-muted",children:f??"Discard your unsaved changes?"}),e.jsx(k,{variant:"danger",onClick:a,children:"Discard changes"}),e.jsx(k,{variant:"ghost",onClick:()=>{A(!1),y.current?.focus()},children:"Keep editing"})]}):e.jsx(k,{variant:"ghost",onClick:()=>t?A(!0):a(),disabled:s,children:"Cancel"}),t&&!j?e.jsx("span",{className:"text-meta text-ink-muted",children:"Unsaved changes"}):null]})}let Ce=!1;function st(){Ce=!0}function nt(){const t=Ce;return Ce=!1,t}function ks({rows:t=6}){return e.jsx("div",{className:"space-y-1","aria-hidden":"true",children:Ns.slice(0,t).map(s=>e.jsx(ie,{className:"h-11 w-full"},s))})}const Ns=["a","b","c","d","e","f","g","h"];function Ue(){return e.jsxs("div",{className:"max-w-3xl space-y-6","aria-hidden":"true",children:[e.jsx(ie,{className:"h-7 w-64"}),e.jsx(ie,{className:"h-5 w-40"}),e.jsx(ie,{className:"h-28 w-full"}),e.jsx(ie,{className:"h-24 w-full"})]})}function Me({title:t,what:s,meaning:n,onRetry:a,retrying:r=!1}){return e.jsxs("div",{role:"alert",className:"max-w-xl space-y-2",children:[e.jsx("h2",{className:"text-heading",children:t}),e.jsx("p",{className:"text-body-sm text-ink",children:s}),e.jsx("p",{className:"text-body-sm text-ink-muted",children:n}),e.jsx(k,{variant:"secondary",onClick:a,disabled:r,children:r?"Retrying…":"Retry"})]})}function G({label:t,htmlFor:s,error:n}){return e.jsxs("div",{className:"flex items-baseline justify-between gap-2",children:[e.jsx("label",{htmlFor:s,className:"text-body-sm text-ink-muted",children:t}),n?e.jsx("span",{className:"text-meta text-danger",role:"alert",children:n}):null]})}const ws=/^[A-Za-z0-9_.:-]{1,128}$/;function Q(t){return{description:t.description??"",instructions:t.instructions??"",tools:t.tools&&t.tools.length>0?[...t.tools]:null,effort:t.effort??"inherit",delegate:t.delegate??!1}}function Ss(t,s){const n={};return s.description!==t.description&&(n.description=s.description),s.instructions!==t.instructions&&(n.instructions=s.instructions),JSON.stringify(s.tools)!==JSON.stringify(t.tools)&&(n.tools=s.tools??[]),s.effort!==t.effort&&(n.effort=s.effort),s.delegate!==t.delegate&&(n.delegate=s.delegate),n}function Cs({profile:t}){return e.jsxs("div",{className:"flex flex-wrap items-center gap-1.5",children:[e.jsx(et,{source:t.source}),t.divergent_fields?.length?e.jsx(U,{variant:"warning",children:"Modified"}):null,t.kind==="specialist"?e.jsx(U,{variant:"neutral",children:"Specialist"}):null,t.delegate?e.jsx(U,{variant:"neutral",children:"Delegates"}):null,t.tools&&t.tools.length>0?e.jsx(U,{variant:"neutral",children:t.tools.length===1?"1 tool":`${t.tools.length} tools`}):null]})}function at({tools:t,onChange:s,error:n}){const[a,r]=l.useState(""),[d,f]=l.useState(null),h=l.useId(),g=()=>{const i=a.trim();if(i){if(!ws.test(i)){f("Tool names are letters, digits, dot, underscore, dash or colon.");return}if(t?.includes(i)){f("That tool is already listed.");return}f(null),r(""),s([...t??[],i])}};return e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-2 text-body-sm",children:[e.jsx(Ee,{checked:t===null,onCheckedChange:i=>s(i?null:[]),"aria-label":"Give this agent every tool"}),e.jsx("span",{children:"All tools"})]}),t===null?e.jsx("p",{className:"text-meta text-ink-muted",children:"This agent may use whatever the session offers."}):e.jsxs(e.Fragment,{children:[t.length>0?e.jsx("ul",{className:"flex flex-wrap gap-1.5",children:t.map(i=>e.jsx("li",{children:e.jsxs(U,{variant:"outline",children:[i,e.jsx(k,{variant:"ghost",size:"sm","aria-label":`Remove ${i}`,onClick:()=>s(t.filter(c=>c!==i)),className:"ml-1 h-4 px-1",children:"×"})]})},i))}):e.jsx("p",{className:"text-meta text-ink-muted",children:"No tools yet. Add one below, or turn on All tools."}),e.jsxs("div",{className:"flex items-end gap-2",children:[e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx(G,{label:"Add a tool",htmlFor:h,error:d??n}),e.jsx(le,{id:h,value:a,inputSize:"md",placeholder:"Tool name","aria-invalid":!!(d??n),onChange:i=>{r(i.target.value),f(null)},onKeyDown:i=>{i.key==="Enter"&&(i.preventDefault(),g())}})]}),e.jsx(k,{variant:"secondary",onClick:g,disabled:!a.trim(),children:"Add"})]})]})]})}function Es({profile:t,teams:s,effortTiers:n,askEnabled:a,onSaved:r,onDuplicate:d,onOpenTeam:f,onAskAgent:h,onDirtyChange:g}){const[i,c]=l.useState(!1),[b,y]=l.useState(()=>Q(t)),[v,j]=l.useState(()=>Q(t)),[A,u]=l.useState(!1),[C,E]=l.useState(null),[B,F]=l.useState(null),[P,N]=l.useState(!1),[x,w]=l.useState(!1),[M,S]=l.useState(!1),T=l.useRef(null),R=ze(),_=JSON.stringify(v)!==JSON.stringify(b);l.useEffect(()=>(g?.(i&&_),()=>g?.(!1)),[g,i,_]),l.useEffect(()=>{nt()&&requestAnimationFrame(()=>T.current?.focus())},[]),l.useEffect(()=>{if(i&&_)return;const o=Q(t);y(o),j(o)},[t,i,_]),l.useEffect(()=>{if(!i){w(!1);return}const o=Q(t);w(_&&JSON.stringify(o)!==JSON.stringify(b))},[t,i,_,b]);const z=()=>{c(!1),E(null),F(null),N(!1),S(!1);const o=Q(t);y(o),j(o)};tt(()=>{if(M){S(!1);return}_?S(!0):z()},i);const de=async o=>{if(o?.preventDefault(),A)return;const p=Ss(b,v);if(Object.keys(p).length===0){z();return}if(typeof p.instructions=="string"&&!p.instructions.trim()){E("Give the agent instructions."),F("instructions");return}u(!0),E(null),F(null);try{const D=await V({op:"profiles.update",name:t.name,requestId:crypto.randomUUID(),fields:p});c(!1),N(!1);const $=Q(D);y($),j($),r(D.name),fe(`Saved ${D.name}.`),requestAnimationFrame(()=>T.current?.focus())}catch(D){const $=je(D instanceof Error?D.message:"The agent could not be saved.");E($.message),F($.field);const W=D?.status,J=typeof W=="number"&&W!==408&&W>=400&&W<500;N(!J),J||Se("The save could not be confirmed. Check whether it was applied before retrying.")}finally{u(!1)}},Z=async()=>{if(!A){u(!0),E(null);try{const o=await V({op:"profiles.install",name:t.name,requestId:crypto.randomUUID()}),p=Q(o);y(p),j(p),r(o.name),fe(`Installed ${o.name}. It can be edited now.`),requestAnimationFrame(()=>T.current?.focus())}catch(o){const p=je(o instanceof Error?o.message:"The agent could not be installed.");E(p.message),Se(p.message)}finally{u(!1)}}},I=(s??[]).filter(o=>o.manager===t.name||(o.members??[]).some(p=>p.role===t.name)),q=t.source==="builtin";return e.jsxs("div",{className:"max-w-3xl space-y-6",children:[e.jsxs("header",{className:"space-y-3",children:[e.jsxs("div",{className:"flex flex-wrap items-start justify-between gap-x-4 gap-y-3",children:[e.jsxs("div",{className:"min-w-0 space-y-2",children:[e.jsx("h2",{ref:T,tabIndex:-1,className:"text-title focus:outline-none",children:t.name}),e.jsx(Cs,{profile:t})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx(k,{variant:"primary",onClick:()=>{Je.getState().stageDraft({kind:"agent",name:t.name}),R("/chat")},children:"New chat"}),q?e.jsxs(k,{variant:"secondary",onClick:Z,disabled:A,children:[e.jsx(Pt,{className:"size-4"}),A?"Installing…":"Install to edit"]}):e.jsx(k,{variant:"secondary",onClick:()=>{c(!0),E(null),F(null)},children:"Edit"}),e.jsx(k,{variant:"ghost",onClick:()=>d(t),children:"Duplicate as new agent"}),a?e.jsx(k,{variant:"ghost",onClick:()=>h(`Change the agent ${t.name}: `),children:"Ask for a change"}):null]})]}),q?e.jsxs(ee,{variant:"info",children:[e.jsx(te,{children:"Built-in agent"}),e.jsx(se,{children:"This one ships with the app and cannot be edited in place. Install it to get an editable copy, or duplicate it as a new agent."})]}):null,x?e.jsxs(ee,{variant:"warning","data-testid":"agent-conflict",children:[e.jsx(te,{children:"This changed while you were editing"}),e.jsxs(se,{children:[e.jsx("span",{className:"block",children:"Something else — a configuration run, or another window — wrote to this agent after you opened it. Your edits are kept; saving writes only the fields you changed."}),e.jsx(k,{variant:"secondary",size:"sm",className:"mt-2",onClick:z,children:"Reload the saved version"})]})]}):null,P?e.jsxs(ee,{variant:"danger","data-testid":"agent-unconfirmed",children:[e.jsx(te,{children:"The last save was not confirmed"}),e.jsx(se,{children:"The backend did not answer, so the write may or may not have landed. Check the agent below, then edit again."})]}):null,C&&!B?e.jsxs(ee,{variant:"danger",role:"alert","data-testid":"agent-save-error",children:[e.jsx(te,{children:"That did not save"}),e.jsx(se,{children:C})]}):null]}),e.jsx("form",{noValidate:!0,onSubmit:o=>{o.preventDefault(),de(o)},className:"space-y-6",children:i?e.jsxs(e.Fragment,{children:[e.jsx(ye,{title:"When to use it",description:"One sentence the model reads to decide when this agent is the right one.",label:"When to use this agent",value:v.description,error:B==="description"?C:null,onChange:o=>j(p=>({...p,description:o}))}),e.jsx(ye,{title:"Instructions",description:"What the agent is told to do. This is the agent's whole behaviour.",label:"Instructions",value:v.instructions,rows:12,required:!0,error:B==="instructions"?C:null,onChange:o=>j(p=>({...p,instructions:o}))}),e.jsx(L,{title:"Tools",children:e.jsx(at,{tools:v.tools,error:B==="tools"?C:null,onChange:o=>j(p=>({...p,tools:o}))})}),e.jsx(L,{title:"Delegation and effort",description:"Whether this agent may hand work to subagents, and which effort tier it runs at.",children:e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-body-sm",children:[e.jsx(Ee,{checked:v.delegate,onCheckedChange:o=>j(p=>({...p,delegate:o})),"aria-label":"May delegate to subagents"}),e.jsx("span",{children:"May delegate to subagents"})]}),e.jsxs("div",{className:"max-w-sm space-y-1",children:[e.jsx(G,{label:"Effort tier",htmlFor:"agent-effort",error:B==="effort"?C:null}),e.jsx(be,{ariaLabel:"Effort tier",showLabel:!1,placeholder:"Choose an effort tier",busyLabel:"Loading effort tiers",options:["inherit",...n].map(o=>({id:o,name:o,description:o==="inherit"?"Use the session's own effort":void 0})),selected:{id:v.effort,name:v.effort},onSelect:o=>j(p=>({...p,effort:o.id})),helperText:"Tiers come from the backend's subagent model settings."})]})]})}),e.jsx(Ae,{submit:!0,confirming:M,onConfirmingChange:S,dirty:_,pending:A,onSave:()=>void de(),onCancel:z,saveLabel:"Save changes",dirtyHint:"Discard your unsaved changes to this agent?"})]}):e.jsxs(e.Fragment,{children:[e.jsx(L,{title:"When to use it",children:e.jsx(oe,{text:t.description||"",empty:"No description yet — add one so a model knows when to pick this agent."})}),e.jsx(L,{title:"Instructions",children:e.jsx(oe,{text:t.instructions??t.packaged_instructions??"",empty:"No instructions yet."})}),e.jsx(L,{title:"Tools",children:t.tools&&t.tools.length>0?e.jsx("ul",{className:"flex flex-wrap gap-1.5",children:t.tools.map(o=>e.jsx("li",{children:e.jsx(U,{variant:"outline",children:o})},o))}):e.jsx(U,{variant:"neutral",children:"All tools"})}),e.jsxs(L,{title:"Delegation and effort",children:[e.jsx("p",{className:"text-body-sm text-ink",children:t.delegate?"May hand work to subagents.":"Does its own work; it does not delegate."}),e.jsxs("p",{className:"text-body-sm text-ink-muted",children:["Effort tier: ",t.effort??"inherit"]})]}),e.jsx(L,{title:"Used by",description:"Teams that name this agent as a manager or a member.",children:I.length>0?e.jsx("ul",{className:"flex flex-wrap gap-x-3 gap-y-1",children:I.map(o=>e.jsx("li",{children:e.jsx(k,{variant:"link",onClick:()=>f(o.name),children:o.name})},o.id))}):e.jsx("p",{className:"text-body-sm text-ink-muted",children:"No team uses it yet."})}),e.jsxs(L,{title:"Where it came from",description:t.source==="builtin"?"Shipped with the app.":t.source==="installed"?"Installed from a packaged starter.":"Created on this machine.",children:[e.jsxs("dl",{className:"space-y-1 text-body-sm",children:[t.seed_origin?e.jsxs("div",{className:"flex gap-2",children:[e.jsx("dt",{className:"text-ink-muted",children:"Source"}),e.jsx("dd",{className:"text-ink",children:t.seed_origin})]}):null,t.divergent_fields?.length?e.jsxs("div",{className:"flex gap-2",children:[e.jsx("dt",{className:"text-ink-muted",children:"Changed from the packaged copy"}),e.jsx("dd",{className:"text-ink",children:t.divergent_fields.join(", ")})]}):null]}),t.packaged_instructions&&t.divergent_fields?.length?e.jsx(Ke,{summary:"Compare with the packaged instructions",className:"mt-2",children:e.jsx(oe,{text:t.packaged_instructions,mono:!0})}):null]})]})})]})}function ye({title:t,description:s,label:n,value:a,onChange:r,rows:d,required:f,error:h,fieldRef:g}){const i=l.useId();return e.jsxs(L,{title:t,description:s,children:[e.jsx(G,{label:n,htmlFor:i,error:h}),d?e.jsx(pe,{id:i,ref:g,value:a,rows:d,required:f,"aria-invalid":!!h,className:Y("min-h-0"),onChange:c=>r(c.target.value)}):e.jsx(le,{id:i,value:a,"aria-invalid":!!h,onChange:c=>r(c.target.value)})]})}function As({initial:t,takenNames:s,effortTiers:n,onDirtyChange:a,onSaved:r,onCancel:d}){const[f,h]=l.useState(()=>t?vs(t.name,s):""),[g,i]=l.useState(t?.kind??"role"),[c,b]=l.useState(()=>t?{...Q(t),description:t.description??""}:{description:"",instructions:"",tools:null,effort:"inherit",delegate:!1}),[y,v]=l.useState(!1),[j,A]=l.useState(null),[u,C]=l.useState(null),E=l.useRef(null),B=l.useRef(null);l.useEffect(()=>(a?.(!!(f.trim()||c.instructions.trim())),()=>a?.(!1)),[a,f,c.instructions]),l.useEffect(()=>{E.current?.focus(),E.current?.select()},[]);const F=async N=>{if(N?.preventDefault(),!y){if(!f.trim()){A("Give the agent a name."),C("name"),E.current?.focus();return}if(/[\\/\s]/.test(f.trim())){A("Names cannot contain spaces or slashes."),C("name"),E.current?.focus();return}if(s.includes(f.trim())){A(`An agent called “${f.trim()}” already exists. Choose another name, or open the existing one to change it.`),C("name"),E.current?.focus();return}if(!c.instructions.trim()){A("Give the agent instructions."),C("instructions"),B.current?.focus();return}v(!0),A(null),C(null);try{const x=await V({op:"profiles.create",requestId:crypto.randomUUID(),name:f.trim(),fields:{kind:g,description:c.description,instructions:c.instructions,tools:c.tools??[],effort:c.effort,delegate:c.delegate}});fe(`Created ${x.name}.`),st(),r(x.name)}catch(x){const w=je(x instanceof Error?x.message:"The agent could not be created.");A(w.message),C(w.field)}finally{v(!1)}}},P=t?"Duplicate as a new agent":"New agent";return e.jsxs("div",{className:"max-w-3xl space-y-6",children:[e.jsxs("header",{className:"space-y-2",children:[e.jsx("h2",{className:"text-title",children:P}),e.jsx("p",{className:"text-body-sm text-ink-muted",children:t?`A copy of ${t.name}. It is a separate agent: changing it does not change the original.`:"Reusable instructions shared by agent commands, subagents and teams. Chats stay separate."})]}),j&&!u?e.jsxs(ee,{variant:"danger",role:"alert","data-testid":"agent-create-error",children:[e.jsx(te,{children:"That did not save"}),e.jsx(se,{children:j})]}):null,e.jsxs("form",{noValidate:!0,onSubmit:N=>{N.preventDefault(),F(N)},className:"space-y-6",children:[e.jsx(L,{title:"Name and role",children:e.jsxs("div",{className:"grid gap-4 sm:grid-cols-2",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx(G,{label:"Name",htmlFor:"agent-create-name",error:u==="name"?j:null}),e.jsx(le,{id:"agent-create-name",ref:E,value:f,required:!0,"aria-invalid":u==="name",onChange:N=>h(N.target.value)})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(G,{label:"How it works with others",htmlFor:"agent-create-kind"}),e.jsxs(Ge,{value:g,onValueChange:N=>i(N),children:[e.jsx(Ye,{id:"agent-create-kind",children:e.jsx(Qe,{})}),e.jsxs(Ze,{children:[e.jsx(xe,{value:"role",children:"You can chat with it directly"}),e.jsx(xe,{value:"specialist",children:"Other agents can call on it"})]})]})]})]})}),e.jsx(ye,{title:"When to use it",description:"One sentence the model reads to decide when this agent is the right one.",label:"When to use this agent",value:c.description,error:u==="description"?j:null,onChange:N=>b(x=>({...x,description:N}))}),e.jsx(ye,{title:"Instructions",description:"What the agent is told to do. This is the agent's whole behaviour.",label:"Instructions",value:c.instructions,rows:12,required:!0,fieldRef:B,error:u==="instructions"?j:null,onChange:N=>b(x=>({...x,instructions:N}))}),e.jsx(L,{title:"Delegation and effort",children:e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-body-sm",children:[e.jsx(Ee,{checked:c.delegate,onCheckedChange:N=>b(x=>({...x,delegate:N})),"aria-label":"May delegate to subagents"}),e.jsx("span",{children:"May delegate to subagents"})]}),e.jsxs("div",{className:"max-w-sm space-y-1",children:[e.jsx(G,{label:"Effort tier",htmlFor:"agent-create-effort"}),e.jsx(be,{ariaLabel:"Effort tier",showLabel:!1,busyLabel:"Loading effort tiers",placeholder:"Choose an effort tier",options:["inherit",...n].map(N=>({id:N,name:N,description:N==="inherit"?"Use the session's own effort":"A tier configured in Settings"})),selected:{id:c.effort,name:c.effort},onSelect:N=>b(x=>({...x,effort:N.id}))})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx("span",{className:"text-body-sm text-ink-muted",children:"Tools"}),e.jsx(at,{tools:c.tools,error:u==="tools"?j:null,onChange:N=>b(x=>({...x,tools:N}))})]})]})}),e.jsx(Ae,{submit:!0,dirty:!!(f.trim()||c.instructions),pending:y,saveLabel:t?"Create the copy":"Create agent",pendingLabel:"Creating…",dirtyHint:"Discard this new agent?",onSave:()=>void F(),onCancel:d})]})]})}const ve=t=>t==null?"":typeof t=="string"?t:JSON.stringify(t,null,2),Is={available:"border-hairline",updating:"border-hairline",applied:"border-hairline",review:"border-warning-border",failed:"border-danger-border"};function $s(t){const s=[];for(const n of t??[])for(const a of n.fields??[])for(const r of a.regions??[])(r.provenance==="unresolved"||ve(r.local)!==ve(r.remote))&&s.push({field:a.field,region:r});return s}function Ds({regions:t}){return t.length?e.jsx("ul",{className:"space-y-3","data-testid":"hub-update-preview",children:t.map(({field:s,region:n},a)=>e.jsxs("li",{className:"space-y-1 text-meta",children:[e.jsx("p",{className:"font-medium text-ink",children:n.heading||n.name||s}),e.jsxs("div",{className:"grid gap-2 sm:grid-cols-2",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-ink-muted",children:"Yours"}),e.jsx("pre",{className:"max-h-40 overflow-auto whitespace-pre-wrap rounded-sm border border-hairline p-2 text-ink",children:ve(n.local)||"(nothing)"})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-ink-muted",children:"The hub's"}),e.jsx("pre",{className:"max-h-40 overflow-auto whitespace-pre-wrap rounded-sm border border-hairline p-2 text-ink",children:ve(n.remote)||"(nothing)"})]})]})]},`${s}:${n.id??a}`))}):e.jsx("p",{className:"text-meta text-ink-muted",children:"No differences to show: the hub's version matches yours."})}function Ts({kind:t,name:s,enabled:n}){const a=ct(n),r=dt(),[d,f]=l.useState(null),h=mt(t,s),g=ut(a.data).get(h),i=ht(g),c=r.notes[h],b=r.pending.has(h);if(!g||!i)return c?e.jsx("section",{"data-testid":"hub-update-panel","aria-label":"Hub update",className:"mb-6 max-w-3xl rounded-md border border-hairline p-3 text-body-sm",children:e.jsx("p",{role:c.tone==="error"?"alert":"status",className:c.tone==="error"?"text-danger":"text-ink",children:c.message})}):null;const y=i.kind==="review",v=g.classification==="baseline-unknown",j=u=>({prefer:u,acknowledgeUnknownBaseline:v}),A=async()=>{const u=await r.applyItem(t,s,{...j(),dryRun:!0});f(u??[])};return e.jsxs("section",{"data-testid":"hub-update-panel","aria-label":"Hub update",className:Y("mb-6 max-w-3xl space-y-2 rounded-md border p-3 text-body-sm",Is[i.kind]),children:[e.jsxs("p",{className:"flex items-start gap-2 text-ink",children:[e.jsx(ft,{mark:i,className:"mt-0.5"}),e.jsx("span",{className:Y(i.kind==="failed"&&"text-danger"),children:gt(g,i)})]}),y&&v&&e.jsx("p",{className:"text-meta text-ink-muted",children:"Nothing records what you changed on this device. Either choice adds the hub's additions and deletes nothing of yours; where the two versions differ, your choice decides which wording stays."}),y&&!v&&e.jsx("p",{className:"text-meta text-ink-muted",children:"Where the two versions differ, your choice decides which wording stays. Everything else is merged, and your current version is saved as a backup first."}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[i.kind==="available"&&e.jsx(k,{size:"sm",variant:"outline","aria-disabled":b||void 0,onClick:()=>!b&&void r.applyItem(t,s),children:b?"Updating…":"Update from the hub"}),i.kind==="failed"&&i.retryable&&e.jsx(k,{size:"sm",variant:"outline","aria-disabled":b||void 0,onClick:()=>!b&&void r.retryItem(t,s),children:b?"Retrying…":"Retry"}),y&&e.jsxs(e.Fragment,{children:[e.jsx(k,{size:"sm",variant:"outline","aria-disabled":b||void 0,onClick:()=>!b&&void A(),children:b&&!d?"Loading…":"Preview the differences"}),e.jsx(k,{size:"sm",variant:"ghost","aria-disabled":b||void 0,onClick:()=>!b&&void r.applyItem(t,s,j("local")),children:"Keep mine where they differ"}),e.jsx(k,{size:"sm",variant:"ghost","aria-disabled":b||void 0,onClick:()=>!b&&void r.applyItem(t,s,j("remote")),children:"Use the hub's where they differ"})]})]}),d&&y&&e.jsx(Ds,{regions:$s(d)}),c&&e.jsx("p",{role:c.tone==="error"?"alert":"status",className:c.tone==="error"?"text-meta text-danger":"text-meta text-ink-muted",children:c.message})]})}function he(t){return{description:t?.description??"",manager:t?.manager??"manager",members:(t?.members??[]).map(s=>({...s,key:crypto.randomUUID()})),instructions:t?.instructions??"",project:t?.project??""}}function Rs(t,s){const n={};return s.description!==t.description&&(n.description=s.description),s.manager!==t.manager&&(n.manager=s.manager),JSON.stringify(s.members.map(({key:a,...r})=>r))!==JSON.stringify(t.members.map(({key:a,...r})=>r))&&(n.members=s.members.map(({key:a,...r})=>r)),s.instructions!==t.instructions&&(n.instructions=s.instructions),s.project!==t.project&&(n.project=s.project),n}function Pe(t,s,n){return(t.kind==="agent"?(s??[]).map(r=>r.name):(n??[]).map(r=>r.name)).includes(t.role)}function Be({team:t,agents:s,teams:n,askEnabled:a,onSaved:r,onCancelCreate:d,onOpenAgent:f,onAskAgent:h,onDirtyChange:g}){const i=!t,[c,b]=l.useState(i),[y,v]=l.useState(t?.name??""),[j,A]=l.useState(()=>he(t)),[u,C]=l.useState(()=>he(t)),[E,B]=l.useState(!1),[F,P]=l.useState(null),[N,x]=l.useState(null),[w,M]=l.useState(!1),S=l.useRef(null),T=l.useRef(null),R=l.useRef(null);l.useEffect(()=>{nt()&&requestAnimationFrame(()=>S.current?.focus())},[]);const _=ze(),z=i?!!(y.trim()||u.description||u.members.length):JSON.stringify(u)!==JSON.stringify(j);l.useEffect(()=>(g?.((i||c)&&z),()=>g?.(!1)),[g,i,c,z]),l.useEffect(()=>{if(c&&z)return;const o=he(t);A(o),C(o)},[t,c,z]);const ce=()=>{if(i){d?.();return}b(!1),P(null),x(null),M(!1);const o=he(t);A(o),C(o)};tt(()=>{if(w){M(!1);return}z?M(!0):ce()},c);const Z=async o=>{if(o?.preventDefault(),!E){if(i&&!y.trim()){P("Give the team a name."),x("name"),R.current?.focus();return}if(i&&/[\\/\s]/.test(y.trim())){P("Names cannot contain spaces or slashes."),x("name"),R.current?.focus();return}if(i&&(n??[]).some(p=>p.name===y.trim())){P(`A team called “${y.trim()}” already exists. Open it to change it, or choose another name.`),x("name"),R.current?.focus();return}if(i&&!u.instructions.trim()){P("Give the team instructions."),x("instructions"),T.current?.focus();return}B(!0),P(null),x(null);try{const p=t?await V({op:"teams.update",name:t.name,requestId:crypto.randomUUID(),fields:Rs(j,u)}):await V({op:"teams.create",requestId:crypto.randomUUID(),fields:{name:y,description:u.description,manager:u.manager,members:u.members.map(({key:$,...W})=>W),instructions:u.instructions,project:u.project}}),D=he(p);A(D),C(D),b(!1),r(p.name),fe(`${i?"Created":"Saved"} ${p.name}.`),i&&st(),requestAnimationFrame(()=>S.current?.focus())}catch(p){const D=je(p instanceof Error?p.message:"The team could not be saved.");P(D.message),x(D.field),Se(D.message)}finally{B(!1)}}},I=(o,p)=>C(D=>({...D,members:D.members.map(($,W)=>W===o?{...$,...p}:$)})),q=(u.members.length?u.members:t?.members??[]).reduce((o,p)=>o+(p.count||1),0);return e.jsxs("div",{className:"max-w-3xl space-y-6",children:[e.jsxs("header",{className:"space-y-3",children:[e.jsxs("div",{className:"flex flex-wrap items-start justify-between gap-x-4 gap-y-3",children:[e.jsxs("div",{className:"min-w-0 space-y-2",children:[e.jsx("h2",{ref:S,tabIndex:-1,className:"text-title focus:outline-none",children:t?t.name:"New team"}),e.jsxs("div",{className:"flex flex-wrap items-center gap-1.5",children:[e.jsx(U,{variant:"neutral",children:q===1?"1 agent":`${q} agents`}),u.members.some(o=>o.kind==="team")?e.jsx(U,{variant:"neutral",children:"Includes a team"}):null]})]}),t?e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx(k,{variant:"primary",onClick:()=>{Je.getState().stageDraft({kind:"team",name:t.name}),_("/chat")},children:"New team chat"}),c?null:e.jsx(k,{variant:"secondary",onClick:()=>b(!0),children:"Edit"}),a?e.jsx(k,{variant:"ghost",onClick:()=>h(`Change the team ${t.name}: `),children:"Ask for a change"}):null]}):null]}),F&&!N?e.jsxs(ee,{variant:"danger",role:"alert","data-testid":"team-save-error",children:[e.jsx(te,{children:"That did not save"}),e.jsx(se,{children:F})]}):null]}),e.jsx("form",{noValidate:!0,onSubmit:o=>{o.preventDefault(),Z(o)},className:"space-y-6",children:i||c?e.jsxs(e.Fragment,{children:[i?e.jsxs(L,{title:"Name",description:"How you and your chats will refer to this team.",children:[e.jsx(G,{label:"Team name",htmlFor:"team-name",error:N==="name"?F:null}),e.jsx(le,{ref:R,id:"team-name","data-testid":"team-name-input",value:y,required:!0,maxLength:64,autoFocus:!0,"aria-invalid":N==="name",onChange:o=>v(o.target.value)})]}):null,e.jsx(L,{title:"Manager",description:"The agent that leads the chat and decides who works on what.",children:e.jsxs("div",{className:"max-w-md space-y-2",children:[e.jsx(G,{label:"Manager agent",htmlFor:"team-manager",error:N==="manager"?F:null}),e.jsx(be,{ariaLabel:"Manager agent",showLabel:!1,placeholder:"Choose a manager",busyLabel:"Loading agents",options:ae(s,n),selected:ae(s,n).find(o=>o.id===u.manager)??null,onSelect:o=>C(p=>({...p,manager:o.id})),onCustomSubmit:o=>C(p=>({...p,manager:o})),listNotice:"Agents and teams on this machine"}),ae(s,n).some(o=>o.id===u.manager)?null:e.jsxs(U,{variant:"warning","data-testid":"team-manager-missing",children:["Not found: ",u.manager]})]})}),e.jsx(L,{title:"Members",description:"Who the manager can delegate to, and how many of each.",children:e.jsxs("div",{className:"space-y-2",children:[u.members.map((o,p)=>{const D=!Pe(o,s,n);return e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx("div",{className:"w-56",children:e.jsx(be,{ariaLabel:`Member ${p+1}`,showLabel:!1,placeholder:"Choose an agent or team",busyLabel:"Loading agents",options:[...ae(s,n).filter($=>o.kind==="team"?$.group==="Teams":$.group==="Agents")],selected:ae(s,n).find($=>$.id===o.role)??null,onSelect:$=>I(p,{role:$.id,kind:$.group==="Teams"?"team":"agent"}),onCustomSubmit:$=>I(p,{role:$})})}),e.jsxs(Ge,{value:o.kind,onValueChange:$=>I(p,{kind:$}),children:[e.jsx(Ye,{"aria-label":`Member ${p+1} kind`,className:"w-32",children:e.jsx(Qe,{})}),e.jsxs(Ze,{children:[e.jsx(xe,{value:"agent",children:"Agent"}),e.jsx(xe,{value:"team",children:"Team"})]})]}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(k,{variant:"secondary",size:"icon-sm","aria-label":`One fewer ${o.role}`,disabled:o.count<=1,onClick:()=>I(p,{count:o.count-1}),children:e.jsx(Ft,{"aria-hidden":"true"})}),e.jsx("span",{className:"min-w-6 text-center text-body-sm tabular-nums","aria-label":`${o.count} of ${o.role}`,children:o.count}),e.jsx(k,{variant:"secondary",size:"icon-sm","aria-label":`One more ${o.role}`,disabled:o.count>=16,onClick:()=>I(p,{count:o.count+1}),children:e.jsx(We,{"aria-hidden":"true"})})]}),e.jsx(k,{variant:"ghost",onClick:()=>C($=>({...$,members:$.members.filter((W,J)=>J!==p)})),children:"Remove"}),D?e.jsxs(U,{variant:"warning",children:["Not found: ",o.role]}):null]},o.key)}),e.jsx(k,{variant:"secondary",onClick:()=>C(o=>({...o,members:[...o.members,{role:"",count:1,kind:"agent",key:crypto.randomUUID()}]})),children:"Add member"})]})}),e.jsxs(L,{title:"Description",children:[e.jsx(G,{label:"What this team is for",htmlFor:"team-description",error:N==="description"?F:null}),e.jsx(le,{id:"team-description",value:u.description,onChange:o=>C(p=>({...p,description:o.target.value}))})]}),e.jsxs(L,{title:"Collaboration instructions",children:[N==="instructions"?e.jsx("p",{className:"text-meta text-danger",role:"alert","data-testid":"team-instructions-error",children:F}):null,e.jsx(pe,{ref:T,"aria-label":"Collaboration instructions","aria-invalid":N==="instructions",className:"min-h-36",maxLength:8e3,value:u.instructions,onChange:o=>C(p=>({...p,instructions:o.target.value}))})]}),e.jsx(L,{title:"Project brief",children:e.jsx(pe,{"aria-label":"Project brief",className:"min-h-36",maxLength:8e3,value:u.project,onChange:o=>C(p=>({...p,project:o.target.value}))})}),e.jsx(Ae,{submit:!0,confirming:w,onConfirmingChange:M,dirty:z,pending:E,saveLabel:i?"Create team":"Save changes",pendingLabel:i?"Creating…":"Saving…",dirtyHint:"Discard this team?",onSave:()=>void Z(),onCancel:ce})]}):e.jsxs(e.Fragment,{children:[e.jsx(L,{title:"Manager",description:"The agent that leads the chat.",children:e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx(k,{variant:"link",onClick:()=>f(u.manager),children:u.manager}),ae(s,n).some(o=>o.id===u.manager)?null:e.jsx(U,{variant:"warning","data-testid":"team-manager-missing",children:"Not found"})]})}),e.jsx(L,{title:"Members",children:e.jsx("ul",{className:"space-y-1",children:(t?.members??[]).map(o=>e.jsxs("li",{className:"flex flex-wrap items-center gap-2 text-body-sm",children:[e.jsx("span",{className:"text-ink",children:o.role}),e.jsx(U,{variant:"neutral",children:o.kind==="team"?"Team":"Agent"}),e.jsx("span",{className:"text-ink-muted",children:o.count===1?"×1":`×${o.count}`}),Pe(o,s,n)?null:e.jsx(U,{variant:"warning","data-testid":"team-member-missing",children:"Not found"})]},`${o.kind}:${o.role}`))})}),e.jsx(L,{title:"What it is for",children:e.jsx(oe,{text:t?.description??"",empty:"No description yet."})}),t?.instructions?e.jsx(L,{title:"Collaboration instructions",children:e.jsx(oe,{text:t.instructions})}):null,t?.project?e.jsx(Ke,{summary:"Project brief",children:e.jsx(oe,{text:t.project})}):null]})})]})}function ae(t,s){return[...(t??[]).map(n=>({id:n.name,name:n.name,description:n.description,group:"Agents"})),...(s??[]).map(n=>({id:n.name,name:n.name,description:n.description,group:"Teams"}))]}const Ls=l.lazy(()=>Ct(()=>import("./legacy-agents-page-DnpWTuf8.js"),__vite__mapDeps([0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15]),import.meta.url).then(t=>({default:t.LegacyAgentsPage}))),qe=/^subagents\.models\.([^.]+)$/,Fs=["lo","med","hi"],we={all:"All",custom:"Custom",installed:"Installed",builtin:"Built-in"},ge=t=>{const s=JSON.stringify(t)??"";let n=5381;for(let a=0;a<s.length;a+=1)n=(n*33^s.charCodeAt(a))>>>0;return`${s.length}.${n.toString(36)}`};function Vs(){const t=pt("surface"),{agentId:s}=xt(),[n,a]=bt(),r=n.get("kind")==="team"||n.get("create")==="team",d=n.has("create"),f=n.get("name"),h=n.get("duplicate"),g=Ve(),i=re(g.data,r?"team_catalogue":"profile_catalogue"),c=jt(i),b=yt(i),y=i&&!!f&&!d,v=Te(r?null:f,y),j=vt(r?f:null,y),A=Te(r?null:h,!!h),[u,C]=l.useState(""),[E,B]=l.useState("all"),[F,P]=l.useState(null),[N,x]=l.useState(null),[w,M]=l.useState(0),S=is(),T=K(m=>m.marks),R=K(m=>m.clearMark),_=Dt({queryKey:["desktop","settings","effort-tiers"],enabled:i,queryFn:()=>V({op:"settings.list"}),staleTime:6e4}),z=l.useMemo(()=>(_.data?.settings??[]).filter(m=>{const O=m.key.match(qe)?.[1];return!O||!Fs.includes(O)?!1:typeof m.value=="string"&&m.value.trim().length>0}).map(m=>m.key.match(qe)?.[1]).filter(m=>!!m),[_.data]),ce=l.useMemo(()=>Us(c.data,u,E),[c.data,u,E]),de=l.useMemo(()=>Ms(b.data,u),[b.data,u]),Z=r?de:ce,I=f??null,q=l.useCallback(m=>{const O=new URLSearchParams;(m.kind??(r?"team":"agent"))==="team"&&O.set("kind","team"),m.name&&O.set("name",m.name),m.create!==null&&m.create!==void 0&&O.set("create",m.create),m.duplicate&&O.set("duplicate",m.duplicate),P(null),a(O)},[r,a]),o=`${r?"team":"agent"}:${d??""}:${I??""}`,p=l.useCallback(m=>x(m?o:null),[o]),D=N!==null&&N===o,[$,W]=l.useState(!1),J=`${r?"team":"agent"}:${I??""}`,X=r?j.data?ge(j.data):null:v.data?ge(v.data):null,ne=l.useRef({identity:J,content:X});l.useEffect(()=>{if(ne.current.identity!==J){ne.current={identity:J,content:X},W(!1);return}if(X===null||ne.current.content===null){ne.current={identity:J,content:X};return}ne.current.content!==X&&(ne.current.content=X,D&&W(!0))},[J,X,D]);const Ie=(m,O)=>e.jsxs(e.Fragment,{children:[e.jsx(Ts,{kind:m,name:O,enabled:re(g.data,"hub_updates")}),$&&e.jsx("output",{className:"mb-6 block max-w-3xl rounded-md border border-warning-border px-3 py-2 text-meta text-ink-muted",children:"The hub updated this definition while you were editing, and the form below now shows the merged version. Edits you had not saved were replaced."})]}),H=l.useCallback(m=>{if(D){P(m);return}q(m)},[D,q]);l.useEffect(()=>{const m=O=>{O.key!=="Escape"||O.defaultPrevented||window.matchMedia("(max-width: 999px)").matches&&(!I&&!d||(O.preventDefault(),H({name:null})))};return window.addEventListener("keydown",m),()=>window.removeEventListener("keydown",m)},[H,I,d]),l.useEffect(()=>{const m=K.getState(),O=m.about;if(!O)return;const $e=r?"team":"agent";I&&O.kind===$e&&O.name===I||(S.setAbout(null),m.draft.trim()===`Change the ${O.kind} ${O.name}:`.trim()&&S.setDraft(""))},[I,r,S]),l.useEffect(()=>{I&&R({kind:r?"team":"agent",name:I})},[I,r,R]);const ue=()=>{c.refetch(),b.refetch(),v.refetch(),j.refetch()};if(s)return e.jsx(l.Suspense,{fallback:e.jsx("p",{className:"p-6 text-body",children:"Loading saved agent…"}),children:e.jsx(Ls,{})});const ke=r?j.error:v.error,me=r?b.error:c.error,rt=i&&!me&&!d&&!I,it=r?j.isLoading:v.isLoading;return e.jsxs("div",{className:"flex h-full min-h-0 bg-canvas text-ink",children:[e.jsxs("aside",{ref:t,"data-open":I?"true":void 0,className:"flex w-72 shrink-0 flex-col gap-3 bg-surface p-4 max-[999px]:data-[open=true]:hidden",children:[e.jsx("h1",{className:"text-heading",children:"Agents and teams"}),e.jsx(Ot,{value:r?"team":"agent",onValueChange:m=>H({kind:m,name:null}),children:e.jsxs(_t,{"aria-label":"Browse definitions by type",className:"w-full",children:[e.jsxs(Re,{value:"agent",className:"flex-1","data-testid":"agents-tab",children:[e.jsx(kt,{className:"size-3.5"}),"Agents",c.data?e.jsx("span",{className:"min-w-[2ch] font-normal text-ink-dim tabular-nums",children:c.data.length}):null]}),e.jsxs(Re,{value:"team",className:"flex-1","data-testid":"teams-tab",children:[e.jsx(Nt,{className:"size-3.5"}),"Teams",b.data?e.jsx("span",{className:"min-w-[2ch] font-normal text-ink-dim tabular-nums",children:b.data.length}):null]})]})}),e.jsxs("div",{className:"relative",children:[e.jsx(wt,{"aria-hidden":"true",className:"pointer-events-none absolute top-2 left-2 size-4 text-ink-dim"}),e.jsx(le,{className:"pl-8",type:"search","aria-label":"Search agents and teams",placeholder:r?"Search teams":"Search agents",value:u,onChange:m=>C(m.target.value)})]}),!r&&c.data?e.jsxs("div",{className:"flex flex-wrap items-center gap-x-2 gap-y-1",children:[e.jsx("span",{"aria-hidden":"true",className:"text-meta text-ink-muted",children:"Showing"}),e.jsxs("fieldset",{className:"m-0 min-w-0 border-0 p-0",children:[e.jsx("legend",{className:"sr-only",children:"Show definitions owned by"}),e.jsx("div",{className:"flex flex-wrap gap-0.5 rounded-md bg-sunken p-0.5",children:Object.keys(we).map(m=>e.jsx(k,{variant:"ghost",size:"sm","aria-pressed":E===m,onClick:()=>B(m),className:Y(E===m&&He),children:we[m]},m))})]})]}):null,e.jsx("div",{className:"min-h-0 flex-1 overflow-y-auto",children:me?null:!c.data&&!b.data?e.jsx(ks,{}):Z.length===0?e.jsx("p",{className:"px-1 py-2 text-body-sm text-ink-muted",children:u?`Nothing matches “${u}”.`:r?"No teams yet. Ask for one below, or add one by hand.":E==="all"?"No agents yet. Ask for one below, or add one by hand.":`No ${we[E].toLowerCase()} agents.`}):e.jsx(_s,{rows:Z,name:d?null:I,teamMode:r,marked:new Map(T.map(m=>[Ht(m),m.created])),onOpen:m=>H({name:m})})}),e.jsxs(k,{variant:"secondary",disabled:!i,onClick:()=>H({create:r?"team":"agent"}),children:[e.jsx(We,{className:"size-4"}),r?"Add team manually":"Add agent manually"]})]}),e.jsxs("main",{className:"flex min-w-0 flex-1 flex-col",children:[I||d?e.jsx("div",{className:"flex shrink-0 items-center border-hairline border-b px-4 py-2 min-[1000px]:hidden",children:e.jsxs(k,{variant:"ghost",size:"sm",onClick:()=>H({name:null}),children:[e.jsx(St,{className:"size-4"}),"Back to the list"]})}):null,e.jsx("div",{className:"min-h-0 flex-1 overflow-auto p-6 pb-0",style:w>0?{paddingBottom:w+16}:void 0,children:i?me?e.jsx(Me,{title:r?"Teams could not be read":"Agents could not be read",what:me instanceof Error?me.message:"The request did not complete.",meaning:"Nothing is lost. This is a read that failed — the backend answered an error, which is different from the backend being out of date.",onRetry:ue,retrying:c.isFetching||b.isFetching}):I&&it?e.jsx(Ue,{}):I&&ke?e.jsx(Me,{title:r?`“${I}” could not be read`:`“${I}” could not be read`,what:ke instanceof Error?ke.message:"The request did not complete.",meaning:"The definition may have been removed, or the backend refused the read.",onRetry:()=>{v.refetch(),j.refetch()},retrying:v.isFetching||j.isFetching}):d&&r?e.jsx(Be,{agents:c.data,teams:b.data,askEnabled:S.enabled,onDirtyChange:p,onSaved:m=>{ue(),q({name:m})},onCancelCreate:()=>q({name:null}),onOpenAgent:m=>H({kind:"agent",name:m}),onAskAgent:m=>{S.setAbout({kind:"team",name:f??""}),S.setDraft(m)}},"team:create"):d&&h&&A.isLoading?e.jsx(Ue,{}):d?e.jsx(As,{initial:A.data??null,takenNames:(c.data??[]).map(m=>m.name),effortTiers:z,onDirtyChange:p,onSaved:m=>{ue(),q({name:m})},onCancel:()=>q({name:null})},"agent:create"):r&&j.data?e.jsxs(e.Fragment,{children:[Ie("team",j.data.name),e.jsx(Be,{team:j.data,agents:c.data,teams:b.data,askEnabled:S.enabled,onDirtyChange:p,onSaved:m=>{ue(),q({name:m})},onOpenAgent:m=>H({kind:"agent",name:m}),onAskAgent:m=>{S.setAbout({kind:"team",name:j.data?.name??""}),S.setDraft(m)}},`team:${j.data.name}:${ge(j.data)}`)]}):!r&&v.data?e.jsxs(e.Fragment,{children:[Ie("agent",v.data.name),e.jsx(Es,{profile:v.data,teams:b.data,effortTiers:z,askEnabled:S.enabled,onDirtyChange:p,onSaved:m=>{ue(),q({name:m})},onDuplicate:m=>H({create:"agent",duplicate:m.name}),onOpenTeam:m=>H({kind:"team",name:m}),onAskAgent:m=>{S.setAbout({kind:"agent",name:v.data?.name??""}),S.setDraft(m)}},`agent:${v.data.name}:${v.data.source}:${ge(v.data)}`)]}):I?e.jsx(ie,{className:"h-6 w-40"}):e.jsx(Os,{teamMode:r,run:S,onAddManually:()=>H({create:r?"team":"agent"})}):e.jsxs(ee,{variant:g.isLoading?"neutral":"warning",className:"max-w-xl",children:[e.jsx(te,{children:g.isLoading?"Connecting to the backend":g.error?"The backend could not be reached":"Reusable agents need a newer backend"}),e.jsx(se,{children:g.isLoading?"Loading what this backend can do…":g.error?g.error.message:"Update the backend to manage reusable agents and teams. Saved chats are unchanged."})]})}),F?e.jsxs("div",{className:"flex flex-wrap items-center gap-2 border-hairline border-t bg-surface px-4 py-3",role:"alertdialog","aria-label":"Discard your unsaved changes?",children:[e.jsx("span",{className:"text-body-sm text-ink",children:r?"Discard your unsaved changes to this team?":"Discard your unsaved changes to this agent?"}),e.jsx(k,{variant:"danger",onClick:()=>{x(null),q(F)},children:"Discard changes"}),e.jsx(k,{variant:"ghost",onClick:()=>P(null),children:"Keep editing"})]}):null,rt?null:e.jsx("div",{className:"shrink-0 border-hairline border-t bg-canvas p-4",children:e.jsx(Xe,{run:S,about:S.about,onClearAbout:()=>S.setAbout(null),onStripHeightChange:M,blockedReason:D?"Finish or cancel your edit first.":null})})]})]})}function Os({teamMode:t,run:s,onAddManually:n}){return e.jsxs("div",{className:"max-w-xl space-y-4",children:[e.jsx("h2",{className:"text-title",children:t?"Ask for a team":"Ask for an agent"}),e.jsx("p",{className:"text-body text-ink-muted",children:t?"A team has one agent that leads the chat and members it can hand work to. Describe what you want and a configuration run sets it up.":"An agent is a reusable set of instructions you can start a chat with, or let other agents call on. Describe what you want and a configuration run sets it up."}),e.jsx(Xe,{run:s,hero:!0,about:s.about,onClearAbout:()=>s.setAbout(null)}),e.jsx(k,{variant:"ghost",onClick:n,children:t?"Or add a team by hand":"Or add an agent by hand"})]})}function _s({rows:t,name:s,teamMode:n,marked:a,onOpen:r}){const d=l.useRef(new Map),[f,h]=l.useState(s),g=(i,c)=>{const b=t.findIndex(v=>v.name===i);if(b<0)return;const y=t[Math.min(t.length-1,Math.max(0,b+c))];y&&(h(y.name),d.current.get(y.name)?.focus())};return e.jsx("ul",{"aria-label":n?"Teams":"Agents",className:"space-y-1",children:t.map(i=>{const c="source"in i,b=a.get(`${n?"team":"agent"}:${i.name}`);return e.jsx("li",{children:e.jsxs("button",{ref:y=>{y?d.current.set(i.name,y):d.current.delete(i.name)},type:"button","aria-current":i.name===s?"true":void 0,tabIndex:i.name===(f??t[0]?.name)?0:-1,"data-testid":`roster-row-${i.name}`,className:Y("flex min-h-11 w-full flex-col items-start gap-0.5 rounded-md px-2 py-1.5 text-left hover:bg-row-hover",i.name===s&&He),onFocus:()=>h(i.name),onClick:()=>r(i.name),onKeyDown:y=>{y.key==="ArrowDown"?(y.preventDefault(),g(i.name,1)):y.key==="ArrowUp"?(y.preventDefault(),g(i.name,-1)):y.key==="Home"?(y.preventDefault(),g(i.name,-t.length)):y.key==="End"&&(y.preventDefault(),g(i.name,t.length))},children:[e.jsxs("span",{className:"flex w-full items-center gap-2",children:[e.jsx("span",{className:"truncate text-body-sm text-ink",children:i.name}),c?e.jsx(et,{source:i.source,appearance:"text"}):null,b!==void 0?e.jsx(U,{variant:"attention","data-testid":"roster-row-updated",children:b?"New":"Updated"}):null]}),e.jsxs("span",{className:"flex w-full flex-wrap items-center gap-1.5",children:["members"in i?e.jsx(U,{variant:"neutral",children:i.members.length===1?"1 member":`${i.members.length} members`}):null,i.description?e.jsx("span",{className:"min-w-0 flex-1 truncate text-meta text-ink-muted",children:i.description}):null]})]})},i.name)})})}function Us(t,s,n){const a=s.trim().toLowerCase();return(t??[]).filter(r=>n==="builtin"&&r.source!=="builtin"||n==="installed"&&r.source!=="installed"||n==="custom"&&r.source!=="custom"?!1:a?r.name.toLowerCase().includes(a)||(r.description??"").toLowerCase().includes(a):!0)}function Ms(t,s){const n=s.trim().toLowerCase();return(t??[]).filter(a=>!n||a.name.toLowerCase().includes(n)||(a.description??"").toLowerCase().includes(n))}export{Vs as AgentsPage};
7
+ */const Pt=[["path",{d:"M15 3h4a2 2 0 0 1 2 2v14a2 2 0 0 1-2 2h-4",key:"u53s6r"}],["polyline",{points:"10 17 15 12 10 7",key:"1ail0h"}],["line",{x1:"15",x2:"3",y1:"12",y2:"12",key:"v6grx8"}]],Bt=Rt("log-in",Pt),qt=["A reviewer that only reads code","Add the coder twice to release-crew","A team called shipping with a manager and two coders"],zt={idle:"bg-ink-dim",running:"bg-accent",stopping:"bg-warning",done:"bg-success",stopped:"bg-ink-muted",error:"bg-danger"};function Kt({status:t,pulse:s}){return e.jsx("span",{"aria-hidden":"true",className:Y("size-2 shrink-0 rounded-full",zt[t]??"bg-ink-dim",s&&"animate-pulse")})}function Wt({run:t}){return t.activity.length===0?e.jsx("p",{className:"text-meta text-ink-muted",children:"Nothing to show yet — the run has not called a tool."}):e.jsx("ul",{className:"max-h-48 space-y-1 overflow-y-auto",children:t.activity.map((s,n)=>e.jsxs("li",{className:"flex items-baseline gap-2 text-body-sm",children:[e.jsx("span",{className:"text-ink-dim tabular-nums",children:new Date(s.ts).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"})}),e.jsx("span",{className:"text-ink",children:s.verb})]},`${s.ts}:${s.verb}:${n}`))})}function Le({run:t,onDismiss:s}){const[n,a]=l.useState(!1),r=l.useRef(null),d=t.status==="running"||t.status==="stopping";l.useEffect(()=>{if(!d)return;const h=g=>{g.key!=="Escape"||g.defaultPrevented||document.querySelector('[role="alertdialog"], [role="dialog"]')||r.current?.focus()};return window.addEventListener("keydown",h),()=>window.removeEventListener("keydown",h)},[d]);const f=t.status==="running"?t.step??"Working on your request":t.status==="stopping"?"Stopping":t.status==="done"?t.results.length>0?"Finished":"Finished without changing anything":t.status==="stopped"?"Stopped":t.status==="error"?t.canRetry?"Stopped with an error":"Finished with an error":"";return e.jsxs("div",{className:"border-hairline border-b pb-2","data-testid":"config-run-strip",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-x-3 gap-y-1",children:[e.jsx(Kt,{status:t.status,pulse:d}),e.jsx("span",{"aria-live":"polite",className:"text-body-sm text-ink",children:f}),(d||t.status==="stopped"||t.status==="done")&&t.elapsed!=="0s"?e.jsx("span",{className:"text-meta text-ink-muted tabular-nums",children:t.elapsed}):null,t.touched.length>0?e.jsx(U,{variant:"neutral",children:t.touched.length===1?"1 definition":`${t.touched.length} definitions`}):null,e.jsxs("div",{className:"ml-auto flex items-center gap-1",children:[t.activity.length>0?e.jsxs(k,{variant:"ghost",size:"sm","aria-expanded":n,onClick:()=>a(h=>!h),children:[n?e.jsx(Lt,{className:"size-3.5"}):e.jsx(Ft,{className:"size-3.5"}),"Watch"]}):null,d?e.jsxs(k,{ref:r,variant:"secondary",size:"sm",disabled:t.status==="stopping",onClick:()=>void t.stop(),children:[e.jsx(lt,{className:"size-3.5"}),t.status==="stopping"?"Stopping…":"Stop"]}):e.jsx(k,{variant:"ghost",size:"sm",onClick:()=>s?s():t.dismiss(),children:"Dismiss"})]})]}),t.attached?e.jsx("p",{className:"mt-1 text-meta text-ink-muted",children:"Another configuration run was already going, so this page attached to it. Your request was not sent — it is still in the box."}):null,t.stopError?e.jsxs("div",{className:"mt-2 border-danger-border border-t pt-2","data-testid":"config-stop-refused",children:[e.jsx("p",{className:"text-body-sm text-danger",children:"The stop did not take — the run is still going."}),e.jsx("p",{className:"mt-0.5 text-meta text-ink-muted",children:t.stopError})]}):null,n?e.jsx("div",{className:"mt-2 border-hairline border-t pt-2",children:e.jsx(Wt,{run:t})}):null,t.status==="stopped"?e.jsxs("div",{className:"mt-2 space-y-1 border-hairline border-t pt-2 text-body-sm",children:[e.jsx("p",{className:"text-ink",children:t.results.length>0?"Stopped. Changes it had already made were kept.":"Stopped. Nothing had been changed yet."}),t.results.length>0?e.jsx("ul",{className:"space-y-0.5",children:t.results.map(h=>e.jsxs("li",{className:"text-ink-muted",children:[h.created?"Created ":"Changed ",e.jsx("span",{className:"text-ink",children:h.target.name})]},`${h.target.kind}:${h.target.name}`))}):null]}):null,t.status==="done"?e.jsx(Ht,{run:t}):null,t.status==="error"&&t.error?e.jsxs("div",{className:"mt-2 border-danger-border border-t pt-2",children:[e.jsx("p",{className:"text-body-sm text-danger",children:t.error}),e.jsxs("div",{className:"mt-1 flex items-center gap-2",children:[t.canRetry?e.jsx(k,{variant:"secondary",size:"sm","data-testid":"config-retry",disabled:t.starting,onClick:()=>void t.retry(),children:t.starting?"Sending…":"Retry"}):null,e.jsx("p",{className:"text-meta text-ink-muted",children:"Nothing else was changed by this run."})]})]}):null]})}function Ht({run:t}){return t.results.length===0?e.jsxs("div",{className:"mt-2 border-hairline border-t pt-2 text-body-sm",children:[e.jsx("p",{className:"text-ink-muted",children:"The run answered without changing any agent or team."}),t.answer?e.jsx("p",{className:"mt-1 whitespace-pre-wrap text-ink",children:t.answer}):null,t.topic?e.jsxs("p",{className:"mt-1 text-meta text-ink-muted",children:["You asked: ",t.topic]}):null]}):e.jsxs("div",{className:"mt-2 space-y-1 border-hairline border-t pt-2",children:[e.jsx("ul",{className:"space-y-1 text-body-sm",children:t.results.map(s=>e.jsxs("li",{children:[e.jsxs("span",{className:"text-ink",children:[s.created?"Created ":"Updated ",s.target.name]}),e.jsxs("span",{className:"text-ink-muted",children:[" (",s.target.kind,")"]}),s.changes.length>0?e.jsxs("span",{className:"text-ink-muted",children:[": ",s.changes.map(n=>n.label).join(", ")]}):s.created?null:e.jsx("span",{className:"text-ink-muted",children:": its settings changed. The list does not show instructions, so open it to see what was written."})]},`${s.target.kind}:${s.target.name}`))}),t.answer?e.jsx("p",{className:"whitespace-pre-wrap text-body-sm text-ink-muted",children:t.answer}):null]})}function et({run:t,hero:s=!1,blockedReason:n,about:a,onClearAbout:r,onStripHeightChange:d}){const f=l.useRef(null),h=l.useRef(null),g=l.useCallback(u=>{if(h.current?.disconnect(),h.current=null,!d)return;if(!u){d(0);return}const C=()=>d(u.getBoundingClientRect().height);if(C(),typeof ResizeObserver>"u")return;const E=new ResizeObserver(C);E.observe(u),h.current=E},[d]),i=t.status==="running"||t.status==="stopping",c=!t.enabled||i||!!n,b=a?`Change ${a.name}…`:t.enabled?"Ask for a new agent or change a team…":"Configure agents by conversation",y=a?`${a.kind}:${a.name}`:null;l.useEffect(()=>{if(!y)return;const u=f.current;if(!u||u.disabled)return;u.focus();const C=u.value.length;u.setSelectionRange?.(C,C)},[y]);const v=()=>{const u=t.draft.trim();!u||c||t.start(u,a)},j=()=>{t.dismiss(),f.current?.focus()},A=()=>{r(),f.current?.focus()};return e.jsxs("div",{className:Y("relative rounded-md border border-hairline bg-surface p-3",s&&"shadow-none"),"data-testid":"config-composer",children:[e.jsx("div",{className:"sr-only",id:"config-composer-label",children:"Ask for an agent or team change"}),t.enabled&&t.status!=="idle"?s?e.jsx(Le,{run:t,onDismiss:j}):e.jsx("div",{ref:g,className:"absolute inset-x-0 bottom-full rounded-t-md border-hairline border bg-canvas p-3",children:e.jsx(Le,{run:t,onDismiss:j})}):null,a?e.jsxs("div",{className:"mb-2 flex items-center gap-2",children:[e.jsxs(U,{variant:"accent","data-testid":"config-composer-about",children:["About ",a.kind," ",a.name]}),e.jsx(k,{variant:"ghost",size:"sm",onClick:A,children:"Clear"})]}):null,e.jsx("label",{className:"sr-only",htmlFor:"config-composer-input",children:b}),e.jsx(pe,{id:"config-composer-input",ref:f,"aria-describedby":"config-composer-note",className:"min-h-16",placeholder:b,value:t.draft,disabled:c||!t.enabled,onChange:u=>t.setDraft(u.target.value),onKeyDown:u=>{u.key==="Enter"&&!u.shiftKey&&(u.preventDefault(),v())}}),t.enabled&&!a&&!i&&!t.draft?e.jsx("div",{className:"mt-2 flex flex-wrap gap-1.5",children:qt.map(u=>e.jsx(k,{variant:"outline",size:"sm",disabled:c,onClick:()=>{t.setDraft(u),f.current?.focus()},children:u},u))}):null,e.jsxs("div",{className:"mt-2 flex flex-wrap items-center gap-x-3 gap-y-2",children:[e.jsx(k,{variant:"primary",disabled:c||!t.draft.trim(),onClick:v,children:t.starting?"Starting…":"Ask for a change"}),n?e.jsx("p",{className:"text-meta text-warning",children:n}):null,e.jsx("p",{id:"config-composer-note",className:"text-meta text-ink-muted",children:t.enabled?"Runs in the background. This does not appear in your conversation.":t.disabledReason})]})]})}const Fe=(t,s)=>t.kind===s.kind&&t.name===s.name;function Vt(t){return`${t.kind}:${t.name}`}const K=Mt(t=>({sessionId:null,status:"idle",topic:"",draft:"",about:null,error:null,stopError:null,unsent:!1,startedAt:null,settledAt:null,touched:[],results:[],answer:"",marks:[],before:null,setDraft:s=>t({draft:s}),setAbout:s=>t({about:s}),adopt:(s,n,a)=>t({sessionId:s,status:"running",topic:n,error:null,stopError:null,startedAt:Date.now(),settledAt:null,touched:[],results:[],answer:"",before:a,unsent:!1}),acceptDraft:()=>t({draft:""}),noteTouched:s=>t(n=>n.touched.some(a=>Fe(a,s))?n:{touched:[...n.touched,s]}),stopping:()=>t(s=>s.status==="running"?{status:"stopping",stopError:null}:s),stopFailed:s=>t({status:"running",stopError:s}),settle:(s,n,a)=>t(()=>({status:n,settledAt:Date.now(),results:s,answer:a,marks:s.map(r=>({...r.target,created:r.created})),sessionId:null,stopError:null,before:null,unsent:!1})),fail:s=>t({status:"error",error:s,unsent:!1,stopError:null}),failUnsent:s=>t({status:"error",error:s,unsent:!0,stopError:null}),dismiss:()=>t({status:"idle",sessionId:null,error:null,stopError:null,unsent:!1,topic:"",touched:[],results:[],answer:"",marks:[],startedAt:null,settledAt:null,before:null}),clearMark:s=>t(n=>({marks:n.marks.filter(a=>!Fe(a,s))}))})),Gt=new Set(["agent","team"]);function Jt(t){const s=typeof t.args?.op=="string"?t.args.op:null,n=typeof t.args?.name=="string"?t.args.name:null,a=t.toolName==="team"?"team":"agent",r=n?{kind:a,name:n}:null,d=t.phase==="done"&&!t.isError&&!t.notRunReason&&!t.neverSent,f=h=>({writes:h&&d});switch(s){case"create":return{verb:n?`Creating ${a} ${n}`:`Creating a ${a}`,target:r,...f(!0)};case"update":return{verb:n?`Updating ${a} ${n}`:`Updating a ${a}`,target:r,...f(!0)};case"install":return{verb:n?`Installing ${n}`:"Installing an agent",target:r,...f(!0)};case"list":case"search":case"show":return{verb:n?`Reading ${n}`:`Reading ${a}s`,target:r,...f(!1)};default:return{verb:t.phase==="running"?`Working on ${a}s`:`Checked ${a}s`,target:r,...f(!0)}}}const Yt={description:"description",kind:"kind",tools:"tools",effort:"effort tier",delegate:"delegation",action_class:"class",manager:"manager",members:"members",instructions:"instructions"};function Qt(t){return{description:t.description??"",kind:t.kind,tools:t.tools&&t.tools.length>0?[...t.tools].sort().join(","):"*",effort:t.effort??"inherit",delegate:String(!!t.delegate)}}function Xt(t){return{description:t.description??"",manager:t.manager??"",members:(t.members??[]).map(s=>`${s.kind}:${s.role}x${s.count}`).sort().join(",")}}function Oe(t,s){return{agents:Object.fromEntries((t??[]).map(n=>[n.name,Qt(n)])),teams:Object.fromEntries((s??[]).map(n=>[n.name,Xt(n)]))}}function Zt(t,s){if(t===s)return"tools";const n=h=>h==="*"?null:new Set(h.split(",")),a=n(t),r=n(s);if(r===null)return"tools widened to every tool";if(a===null)return"tools narrowed to a list";const d=[...r].filter(h=>!a.has(h)),f=[...a].filter(h=>!r.has(h));return d.length&&!f.length?d.length===1?`tool added: ${d[0]}`:`${d.length} tools added`:f.length&&!d.length?f.length===1?`tool removed: ${f[0]}`:`${f.length} tools removed`:"tools changed"}function es(t,s,n){if(t==="tools")return Zt(s,n);if(t==="delegate")return n==="true"?"delegation turned on":"delegation turned off";if(t==="members"){const a=r=>r?r.split(",").length:0;return`members changed (${a(s)} to ${a(n)})`}return`${Yt[t]??t} changed`}function ts(t,s,n){const a=[],r=new Set;for(const d of n){const f=`${d.kind}:${d.name}`;if(r.has(f))continue;r.add(f);const h=t[d.kind==="agent"?"agents":"teams"][d.name],g=s[d.kind==="agent"?"agents":"teams"][d.name];if(!g)continue;if(!h){a.push({target:d,created:!0,changes:[]});continue}const i=[];for(const c of Object.keys(g))g[c]!==h[c]&&i.push({label:es(c,h[c],g[c]),before:h[c],after:g[c]});a.push({target:d,created:!1,changes:i})}for(const[d,f]of[["agent",s.agents],["team",s.teams]])for(const h of Object.keys(f))r.has(`${d}:${h}`)||(d==="agent"?t.agents[h]:t.teams[h])||a.push({target:{kind:d,name:h},created:!0,changes:[]});return a}function ss(t){return re(t,"agents_config")&&re(t,"session_interrupt")&&re(t,"profile_catalogue")&&re(t,"team_catalogue")}function ns(t){if(!(t instanceof ut)||t.status!==409)return null;const n=t.detail?.session_id;return typeof n=="string"&&n.length>0?n:null}function as(t,s){const[n,a]=l.useState(()=>Date.now());return l.useEffect(()=>{if(!t||!s)return;const r=setInterval(()=>a(Date.now()),1e3);return()=>clearInterval(r)},[t,s]),t?Math.max(0,n-t):0}function rs(t){const s=Math.floor(t/1e3);return s<60?`${s}s`:`${Math.floor(s/60)}m ${String(s%60).padStart(2,"0")}s`}function _e(t){for(let s=(t?.length??0)-1;s>=0;s-=1){const n=t?.[s];if(n?.kind==="assistant"&&n.text?.trim())return n.text.trim()}return""}function is(t){const n=t?.payload?.frontend;if(!n||typeof n!="object")return null;const a=n.streaming;if(typeof a=="boolean")return a;const r=n.snapshot?.streaming;return typeof r=="boolean"?r:null}function os(){const t=ze(),s=ss(t.data),n=ct(),a=K(),[r,d]=l.useState(!1),[f,h]=l.useState(!1),g=l.useRef(!1),i=a.status==="running"||a.status==="stopping",c=dt(a.sessionId??void 0,!!a.sessionId),b=l.useMemo(()=>_e(c.transcript?.records),[c.transcript?.records]);kt(a.sessionId??void 0,c.subscriptionId);const y=c.transcript?.records,v=l.useRef(y);l.useEffect(()=>{v.current=y},[y]);const j=l.useMemo(()=>(c.transcript?.records??[]).filter(w=>w.kind==="tool"&&Gt.has(w.toolName)).map(w=>({...Jt({toolName:w.toolName,args:w.args??null,phase:w.phase,ts:w.ts,isError:w.isError,notRunReason:w.notRunReason,neverSent:w.neverSent}),ts:w.ts})),[c.transcript]);l.useEffect(()=>{if(i)for(const x of j)x.target&&x.writes&&a.noteTouched(x.target)},[j,i,a]);const A=i&&j.length>0?j[j.length-1].verb:null,u=rs(as(a.startedAt,i)),C=l.useCallback(async(x,w="")=>{if(g.current)return;g.current=!0;const M=a.before;let S=[];try{const[D,R]=await Promise.all([V({op:"profiles.list"}),V({op:"teams.list"})]);M&&(S=ts(M,Oe(D.profiles,R.teams),a.touched))}catch{K.getState().fail("The run finished, but the agents and teams lists could not be read to describe what changed."),Te(n);return}if(Te(n),K.getState().settle(S,x,w),x==="done"&&S.length>0){const D=S.filter(R=>R.created).length;fe(D>0?`Configuration run finished: ${S.length} definition${S.length===1?"":"s"} changed.`:`Configuration run finished: ${S.length} definition${S.length===1?"":"s"} updated.`)}},[n,a.before,a.touched]);l.useEffect(()=>{if(i){if(c.failure){K.getState().fail(c.failure.statement);return}g.current||c.frontend&&(c.frontend.streaming||c.turnsCompleted!==0&&C(a.status==="stopping"?"stopped":"done",b))}},[i,b,c.failure,c.frontend,c.turnsCompleted,a.status,C]),l.useEffect(()=>{const x=a.sessionId;if(!i||!x)return;let w=!1;const M=async()=>{if(!(w||g.current))try{const R=await V({op:"sessions.get",sessionId:x});if(w||g.current||is(R)!==!1)return;const _=_e(v.current);if(!_)return;C(K.getState().status==="stopping"?"stopped":"done",_)}catch{}},S=setTimeout(()=>void M(),400),D=setInterval(()=>void M(),4e3);return()=>{w=!0,clearTimeout(S),clearInterval(D)}},[i,a.sessionId,C]);const E=async(x,w)=>{if(r||!x.trim())return;d(!0),h(!1),g.current=!1;const M=Oe(n.getQueryData(["desktop","profiles"]),n.getQueryData(["desktop","teams"])),S=w?`About the ${w.kind} “${w.name}”: ${x.trim()}`:x.trim();try{let D;try{D=(await V({op:"sessions.create",requestId:crypto.randomUUID(),purpose:"agents-config"})).session_id}catch(R){const _=ns(R);if(_){h(!0),a.adopt(_,x.trim(),M);return}throw R}a.adopt(D,S,M),await B(D,S),a.acceptDraft()}catch(D){const R=K.getState().sessionId;K.getState().failUnsent(Ne(D,R?"The run was set up, but your request could not be sent. It is still in the box — send it again when the backend is reachable.":"The configuration run could not be started. Your request is still here."))}finally{d(!1)}},B=async(x,w)=>{await V({op:"sessions.message",sessionId:x,requestId:crypto.randomUUID(),text:w})},F=async()=>{const x=K.getState();if(!(r||!x.unsent||!x.sessionId||!x.topic)){d(!0);try{await B(x.sessionId,x.topic),a.acceptDraft(),a.adopt(x.sessionId,x.topic,x.before),g.current=!1}catch(w){K.getState().failUnsent(Ne(w,"The request could not be sent. It is still in the box."))}finally{d(!1)}}},P=async()=>{const x=K.getState().sessionId;if(x){a.stopping();try{await Nt(x,crypto.randomUUID())}catch(w){K.getState().stopFailed(Ne(w,"The run did not acknowledge the request."))}}},N=s?null:t.isLoading?"Connecting to the backend…":t.error?"The backend could not be reached, so the composer is unavailable for now.":"Ask for a change needs a newer backend. Update Local Operator to configure agents by conversation.";return{enabled:s,disabledReason:N,status:a.status,sessionId:a.sessionId,topic:a.topic,error:a.error,stopError:a.stopError,draft:a.draft,setDraft:a.setDraft,about:a.about,setAbout:a.setAbout,touched:a.touched,results:a.results,answer:a.answer,step:A,elapsed:u,activity:j,start:E,stop:P,retry:F,canRetry:a.unsent&&!!a.sessionId,dismiss:a.dismiss,starting:r,attached:f}}const ls=/Value error,\s*([\s\S]*?)\s*\[type=/,cs=/^\d+ validation errors? for \S+[\s\S]*?\n\s*/i,ds=/\s*\[type=[^\]]*\][\s\S]*$/m,us=/\s*For further information visit \S+/g,ms=/'([^']+)' already exists/,hs=/cannot contain spaces or path separators/i,fs=/effort tier '([^']+)' is unavailable/i,gs=/team name must be/i,ps=/manager '([^']+)'/i,xs=/(?:member|role) '([^']+)' (?:is not|does not)/i,bs=/depth|cycle|circular/i,js=/instructions/i,ys=/description/i;function vs(t){const s=t.match(ls);return s?.[1]?s[1].trim():t.replace(cs,"").replace(ds,"").replace(us,"").trim()}function je(t){const s=vs(t),n=s.match(ms);if(n)return{message:`An agent called “${n[1]}” already exists. Choose another name, or open the existing one to change it.`,field:"name"};if(hs.test(s))return{message:"Names cannot contain spaces or slashes.",field:"name"};const a=s.match(fs);if(a)return{message:`“${a[1]}” is not a configured effort tier. Use inherit, or add the tier in Settings.`,field:"effort"};if(s.match(gs))return{message:"A team name is 1-64 characters.",field:"name"};const d=s.match(ps);if(d)return{message:`“${d[1]}” is not an agent or a team on this machine.`,field:"manager"};const f=s.match(xs);return f?{message:`“${f[1]}” is not an agent or a team on this machine.`,field:"members"}:bs.test(s)?{message:"That team would nest too deeply, or would contain itself. Check its members.",field:"members"}:js.test(s)?{message:s,field:"instructions"}:ys.test(s)?{message:s,field:"description"}:{message:s,field:null}}function ks(t,s){const n=new Set(s),a=`${t}-copy`;if(!n.has(a))return a;for(let r=2;r<100;r+=1){const d=`${a}-${r}`;if(!n.has(d))return d}return a}function L({title:t,description:s,actions:n,children:a,className:r}){return e.jsxs("section",{className:Y("space-y-2 border-hairline border-t pt-4 first:border-t-0 first:pt-0",r),children:[e.jsxs("div",{className:"flex flex-wrap items-baseline justify-between gap-x-3 gap-y-1",children:[e.jsx("h3",{className:"text-heading",children:t}),n]}),s?e.jsx("p",{className:"text-meta text-ink-muted",children:s}):null,a]})}function oe({text:t,empty:s="Nothing here yet.",mono:n=!1}){const[a,r]=l.useState(!1),[d,f]=l.useState(!1),h=l.useRef(null);return l.useEffect(()=>{if(a)return;const g=h.current;g&&f(!!t&&g.scrollHeight>g.clientHeight+1)},[t,a]),t.trim()?e.jsxs("div",{className:"space-y-1",children:[e.jsx("div",{ref:h,tabIndex:0,"aria-label":"The full text",className:Y("whitespace-pre-wrap rounded-sm border border-hairline bg-surface px-3 py-2 text-body-sm text-ink",!a&&"max-h-64 overflow-y-auto",n&&"font-mono text-meta"),children:t}),d?e.jsx(k,{variant:"link",size:"sm",onClick:()=>r(g=>!g),children:a?"Show less":"Show all"}):null]}):e.jsx("p",{className:"text-body-sm text-ink-muted",children:s})}function tt({source:t,appearance:s="chip"}){const n=t==="builtin"?"Built-in":t==="installed"?"Installed":"Custom";return s==="text"?e.jsx("span",{className:"shrink-0 text-meta text-ink-dim",children:n}):e.jsx(U,{variant:"neutral",children:n})}function st(t,s){l.useEffect(()=>{if(!s)return;const n=a=>{a.key!=="Escape"||a.defaultPrevented||(a.preventDefault(),t())};return window.addEventListener("keydown",n),()=>window.removeEventListener("keydown",n)},[s,t])}function Ae({dirty:t,pending:s,onSave:n,onCancel:a,saveLabel:r="Save changes",pendingLabel:d="Saving…",dirtyHint:f,submit:h,confirming:g,onConfirmingChange:i}){const[c,b]=l.useState(!1),y=l.useRef(null),v=g!==void 0,j=v?g:c,A=u=>{v||b(u),i?.(u)};return l.useEffect(()=>{t||(v||b(!1),i?.(!1))},[t,v,i]),e.jsxs("div",{"data-testid":"edit-footer",className:"sticky bottom-0 z-10 -mx-6 mt-6 flex flex-wrap items-center gap-2 border-hairline border-t bg-canvas px-6 py-3",children:[e.jsx(k,{ref:y,type:h?"submit":void 0,variant:"primary",onClick:h?void 0:n,disabled:s,children:s?d:r}),j?e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"text-body-sm text-ink-muted",children:f??"Discard your unsaved changes?"}),e.jsx(k,{variant:"danger",onClick:a,children:"Discard changes"}),e.jsx(k,{variant:"ghost",onClick:()=>{A(!1),y.current?.focus()},children:"Keep editing"})]}):e.jsx(k,{variant:"ghost",onClick:()=>t?A(!0):a(),disabled:s,children:"Cancel"}),t&&!j?e.jsx("span",{className:"text-meta text-ink-muted",children:"Unsaved changes"}):null]})}let Ce=!1;function nt(){Ce=!0}function at(){const t=Ce;return Ce=!1,t}function Ns({rows:t=6}){return e.jsx("div",{className:"space-y-1","aria-hidden":"true",children:ws.slice(0,t).map(s=>e.jsx(ie,{className:"h-11 w-full"},s))})}const ws=["a","b","c","d","e","f","g","h"];function Ue(){return e.jsxs("div",{className:"max-w-3xl space-y-6","aria-hidden":"true",children:[e.jsx(ie,{className:"h-7 w-64"}),e.jsx(ie,{className:"h-5 w-40"}),e.jsx(ie,{className:"h-28 w-full"}),e.jsx(ie,{className:"h-24 w-full"})]})}function Me({title:t,what:s,meaning:n,onRetry:a,retrying:r=!1}){return e.jsxs("div",{role:"alert",className:"max-w-xl space-y-2",children:[e.jsx("h2",{className:"text-heading",children:t}),e.jsx("p",{className:"text-body-sm text-ink",children:s}),e.jsx("p",{className:"text-body-sm text-ink-muted",children:n}),e.jsx(k,{variant:"secondary",onClick:a,disabled:r,children:r?"Retrying…":"Retry"})]})}function J({label:t,htmlFor:s,error:n}){return e.jsxs("div",{className:"flex items-baseline justify-between gap-2",children:[e.jsx("label",{htmlFor:s,className:"text-body-sm text-ink-muted",children:t}),n?e.jsx("span",{className:"text-meta text-danger",role:"alert",children:n}):null]})}const Ss=/^[A-Za-z0-9_.:-]{1,128}$/;function Q(t){return{description:t.description??"",instructions:t.instructions??"",tools:t.tools&&t.tools.length>0?[...t.tools]:null,effort:t.effort??"inherit",delegate:t.delegate??!1}}function Cs(t,s){const n={};return s.description!==t.description&&(n.description=s.description),s.instructions!==t.instructions&&(n.instructions=s.instructions),JSON.stringify(s.tools)!==JSON.stringify(t.tools)&&(n.tools=s.tools??[]),s.effort!==t.effort&&(n.effort=s.effort),s.delegate!==t.delegate&&(n.delegate=s.delegate),n}function Es({profile:t}){return e.jsxs("div",{className:"flex flex-wrap items-center gap-1.5",children:[e.jsx(tt,{source:t.source}),t.divergent_fields?.length?e.jsx(U,{variant:"warning",children:"Modified"}):null,t.kind==="specialist"?e.jsx(U,{variant:"neutral",children:"Specialist"}):null,t.delegate?e.jsx(U,{variant:"neutral",children:"Delegates"}):null,t.tools&&t.tools.length>0?e.jsx(U,{variant:"neutral",children:t.tools.length===1?"1 tool":`${t.tools.length} tools`}):null]})}function rt({tools:t,onChange:s,error:n}){const[a,r]=l.useState(""),[d,f]=l.useState(null),h=l.useId(),g=()=>{const i=a.trim();if(i){if(!Ss.test(i)){f("Tool names are letters, digits, dot, underscore, dash or colon.");return}if(t?.includes(i)){f("That tool is already listed.");return}f(null),r(""),s([...t??[],i])}};return e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-2 text-body-sm",children:[e.jsx(Ee,{checked:t===null,onCheckedChange:i=>s(i?null:[]),"aria-label":"Give this agent every tool"}),e.jsx("span",{children:"All tools"})]}),t===null?e.jsx("p",{className:"text-meta text-ink-muted",children:"This agent may use whatever the session offers."}):e.jsxs(e.Fragment,{children:[t.length>0?e.jsx("ul",{className:"flex flex-wrap gap-1.5",children:t.map(i=>e.jsx("li",{children:e.jsxs(U,{variant:"outline",children:[i,e.jsx(k,{variant:"ghost",size:"sm","aria-label":`Remove ${i}`,onClick:()=>s(t.filter(c=>c!==i)),className:"ml-1 h-4 px-1",children:"×"})]})},i))}):e.jsx("p",{className:"text-meta text-ink-muted",children:"No tools yet. Add one below, or turn on All tools."}),e.jsxs("div",{className:"flex items-end gap-2",children:[e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx(J,{label:"Add a tool",htmlFor:h,error:d??n}),e.jsx(le,{id:h,value:a,inputSize:"md",placeholder:"Tool name","aria-invalid":!!(d??n),onChange:i=>{r(i.target.value),f(null)},onKeyDown:i=>{i.key==="Enter"&&(i.preventDefault(),g())}})]}),e.jsx(k,{variant:"secondary",onClick:g,disabled:!a.trim(),children:"Add"})]})]})]})}function As({profile:t,teams:s,effortTiers:n,askEnabled:a,onSaved:r,onDuplicate:d,onOpenTeam:f,onAskAgent:h,onDirtyChange:g}){const[i,c]=l.useState(!1),[b,y]=l.useState(()=>Q(t)),[v,j]=l.useState(()=>Q(t)),[A,u]=l.useState(!1),[C,E]=l.useState(null),[B,F]=l.useState(null),[P,N]=l.useState(!1),[x,w]=l.useState(!1),[M,S]=l.useState(!1),D=l.useRef(null),R=Ke(),_=JSON.stringify(v)!==JSON.stringify(b);l.useEffect(()=>(g?.(i&&_),()=>g?.(!1)),[g,i,_]),l.useEffect(()=>{at()&&requestAnimationFrame(()=>D.current?.focus())},[]),l.useEffect(()=>{if(i&&_)return;const o=Q(t);y(o),j(o)},[t,i,_]),l.useEffect(()=>{if(!i){w(!1);return}const o=Q(t);w(_&&JSON.stringify(o)!==JSON.stringify(b))},[t,i,_,b]);const z=()=>{c(!1),E(null),F(null),N(!1),S(!1);const o=Q(t);y(o),j(o)};st(()=>{if(M){S(!1);return}_?S(!0):z()},i);const de=async o=>{if(o?.preventDefault(),A)return;const p=Cs(b,v);if(Object.keys(p).length===0){z();return}if(typeof p.instructions=="string"&&!p.instructions.trim()){E("Give the agent instructions."),F("instructions");return}u(!0),E(null),F(null);try{const T=await V({op:"profiles.update",name:t.name,requestId:crypto.randomUUID(),fields:p});c(!1),N(!1);const $=Q(T);y($),j($),r(T.name),fe(`Saved ${T.name}.`),requestAnimationFrame(()=>D.current?.focus())}catch(T){const $=je(T instanceof Error?T.message:"The agent could not be saved.");E($.message),F($.field);const W=T?.status,G=typeof W=="number"&&W!==408&&W>=400&&W<500;N(!G),G||Se("The save could not be confirmed. Check whether it was applied before retrying.")}finally{u(!1)}},X=async()=>{if(!A){u(!0),E(null);try{const o=await V({op:"profiles.install",name:t.name,requestId:crypto.randomUUID()}),p=Q(o);y(p),j(p),r(o.name),fe(`Installed ${o.name}. It can be edited now.`),requestAnimationFrame(()=>D.current?.focus())}catch(o){const p=je(o instanceof Error?o.message:"The agent could not be installed.");E(p.message),Se(p.message)}finally{u(!1)}}},I=(s??[]).filter(o=>o.manager===t.name||(o.members??[]).some(p=>p.role===t.name)),q=t.source==="builtin";return e.jsxs("div",{className:"max-w-3xl space-y-6",children:[e.jsxs("header",{className:"space-y-3",children:[e.jsxs("div",{className:"flex flex-wrap items-start justify-between gap-x-4 gap-y-3",children:[e.jsxs("div",{className:"min-w-0 space-y-2",children:[e.jsx("h2",{ref:D,tabIndex:-1,className:"text-title focus:outline-none",children:t.name}),e.jsx(Es,{profile:t})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx(k,{variant:"primary",onClick:()=>{We.getState().stageDraft({kind:"agent",name:t.name}),R("/chat")},children:"New chat"}),q?e.jsxs(k,{variant:"secondary",onClick:X,disabled:A,children:[e.jsx(Bt,{className:"size-4"}),A?"Installing…":"Install to edit"]}):e.jsx(k,{variant:"secondary",onClick:()=>{c(!0),E(null),F(null)},children:"Edit"}),e.jsx(k,{variant:"ghost",onClick:()=>d(t),children:"Duplicate as new agent"}),a?e.jsx(k,{variant:"ghost",onClick:()=>h(`Change the agent ${t.name}: `),children:"Ask for a change"}):null]})]}),q?e.jsxs(ee,{variant:"info",children:[e.jsx(te,{children:"Built-in agent"}),e.jsx(se,{children:"This one ships with the app and cannot be edited in place. Install it to get an editable copy, or duplicate it as a new agent."})]}):null,x?e.jsxs(ee,{variant:"warning","data-testid":"agent-conflict",children:[e.jsx(te,{children:"This changed while you were editing"}),e.jsxs(se,{children:[e.jsx("span",{className:"block",children:"Something else — a configuration run, or another window — wrote to this agent after you opened it. Your edits are kept; saving writes only the fields you changed."}),e.jsx(k,{variant:"secondary",size:"sm",className:"mt-2",onClick:z,children:"Reload the saved version"})]})]}):null,P?e.jsxs(ee,{variant:"danger","data-testid":"agent-unconfirmed",children:[e.jsx(te,{children:"The last save was not confirmed"}),e.jsx(se,{children:"The backend did not answer, so the write may or may not have landed. Check the agent below, then edit again."})]}):null,C&&!B?e.jsxs(ee,{variant:"danger",role:"alert","data-testid":"agent-save-error",children:[e.jsx(te,{children:"That did not save"}),e.jsx(se,{children:C})]}):null]}),e.jsx("form",{noValidate:!0,onSubmit:o=>{o.preventDefault(),de(o)},className:"space-y-6",children:i?e.jsxs(e.Fragment,{children:[e.jsx(ye,{title:"When to use it",description:"One sentence the model reads to decide when this agent is the right one.",label:"When to use this agent",value:v.description,error:B==="description"?C:null,onChange:o=>j(p=>({...p,description:o}))}),e.jsx(ye,{title:"Instructions",description:"What the agent is told to do. This is the agent's whole behaviour.",label:"Instructions",value:v.instructions,rows:12,required:!0,error:B==="instructions"?C:null,onChange:o=>j(p=>({...p,instructions:o}))}),e.jsx(L,{title:"Tools",children:e.jsx(rt,{tools:v.tools,error:B==="tools"?C:null,onChange:o=>j(p=>({...p,tools:o}))})}),e.jsx(L,{title:"Delegation and effort",description:"Whether this agent may hand work to subagents, and which effort tier it runs at.",children:e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-body-sm",children:[e.jsx(Ee,{checked:v.delegate,onCheckedChange:o=>j(p=>({...p,delegate:o})),"aria-label":"May delegate to subagents"}),e.jsx("span",{children:"May delegate to subagents"})]}),e.jsxs("div",{className:"max-w-sm space-y-1",children:[e.jsx(J,{label:"Effort tier",htmlFor:"agent-effort",error:B==="effort"?C:null}),e.jsx(be,{ariaLabel:"Effort tier",showLabel:!1,placeholder:"Choose an effort tier",busyLabel:"Loading effort tiers",options:["inherit",...n].map(o=>({id:o,name:o,description:o==="inherit"?"Use the session's own effort":void 0})),selected:{id:v.effort,name:v.effort},onSelect:o=>j(p=>({...p,effort:o.id})),helperText:"Tiers come from the backend's subagent model settings."})]})]})}),e.jsx(Ae,{submit:!0,confirming:M,onConfirmingChange:S,dirty:_,pending:A,onSave:()=>void de(),onCancel:z,saveLabel:"Save changes",dirtyHint:"Discard your unsaved changes to this agent?"})]}):e.jsxs(e.Fragment,{children:[e.jsx(L,{title:"When to use it",children:e.jsx(oe,{text:t.description||"",empty:"No description yet — add one so a model knows when to pick this agent."})}),e.jsx(L,{title:"Instructions",children:e.jsx(oe,{text:t.instructions??t.packaged_instructions??"",empty:"No instructions yet."})}),e.jsx(L,{title:"Tools",children:t.tools&&t.tools.length>0?e.jsx("ul",{className:"flex flex-wrap gap-1.5",children:t.tools.map(o=>e.jsx("li",{children:e.jsx(U,{variant:"outline",children:o})},o))}):e.jsx(U,{variant:"neutral",children:"All tools"})}),e.jsxs(L,{title:"Delegation and effort",children:[e.jsx("p",{className:"text-body-sm text-ink",children:t.delegate?"May hand work to subagents.":"Does its own work; it does not delegate."}),e.jsxs("p",{className:"text-body-sm text-ink-muted",children:["Effort tier: ",t.effort??"inherit"]})]}),e.jsx(L,{title:"Used by",description:"Teams that name this agent as a manager or a member.",children:I.length>0?e.jsx("ul",{className:"flex flex-wrap gap-x-3 gap-y-1",children:I.map(o=>e.jsx("li",{children:e.jsx(k,{variant:"link",onClick:()=>f(o.name),children:o.name})},o.id))}):e.jsx("p",{className:"text-body-sm text-ink-muted",children:"No team uses it yet."})}),e.jsxs(L,{title:"Where it came from",description:t.source==="builtin"?"Shipped with the app.":t.source==="installed"?"Installed from a packaged starter.":"Created on this machine.",children:[e.jsxs("dl",{className:"space-y-1 text-body-sm",children:[t.seed_origin?e.jsxs("div",{className:"flex gap-2",children:[e.jsx("dt",{className:"text-ink-muted",children:"Source"}),e.jsx("dd",{className:"text-ink",children:t.seed_origin})]}):null,t.divergent_fields?.length?e.jsxs("div",{className:"flex gap-2",children:[e.jsx("dt",{className:"text-ink-muted",children:"Changed from the packaged copy"}),e.jsx("dd",{className:"text-ink",children:t.divergent_fields.join(", ")})]}):null]}),t.packaged_instructions&&t.divergent_fields?.length?e.jsx(He,{summary:"Compare with the packaged instructions",className:"mt-2",children:e.jsx(oe,{text:t.packaged_instructions,mono:!0})}):null]})]})})]})}function ye({title:t,description:s,label:n,value:a,onChange:r,rows:d,required:f,error:h,fieldRef:g}){const i=l.useId();return e.jsxs(L,{title:t,description:s,children:[e.jsx(J,{label:n,htmlFor:i,error:h}),d?e.jsx(pe,{id:i,ref:g,value:a,rows:d,required:f,"aria-invalid":!!h,className:Y("min-h-0"),onChange:c=>r(c.target.value)}):e.jsx(le,{id:i,value:a,"aria-invalid":!!h,onChange:c=>r(c.target.value)})]})}function Is({initial:t,takenNames:s,effortTiers:n,onDirtyChange:a,onSaved:r,onCancel:d}){const[f,h]=l.useState(()=>t?ks(t.name,s):""),[g,i]=l.useState(t?.kind??"role"),[c,b]=l.useState(()=>t?{...Q(t),description:t.description??""}:{description:"",instructions:"",tools:null,effort:"inherit",delegate:!1}),[y,v]=l.useState(!1),[j,A]=l.useState(null),[u,C]=l.useState(null),E=l.useRef(null),B=l.useRef(null);l.useEffect(()=>(a?.(!!(f.trim()||c.instructions.trim())),()=>a?.(!1)),[a,f,c.instructions]),l.useEffect(()=>{E.current?.focus(),E.current?.select()},[]);const F=async N=>{if(N?.preventDefault(),!y){if(!f.trim()){A("Give the agent a name."),C("name"),E.current?.focus();return}if(/[\\/\s]/.test(f.trim())){A("Names cannot contain spaces or slashes."),C("name"),E.current?.focus();return}if(s.includes(f.trim())){A(`An agent called “${f.trim()}” already exists. Choose another name, or open the existing one to change it.`),C("name"),E.current?.focus();return}if(!c.instructions.trim()){A("Give the agent instructions."),C("instructions"),B.current?.focus();return}v(!0),A(null),C(null);try{const x=await V({op:"profiles.create",requestId:crypto.randomUUID(),name:f.trim(),fields:{kind:g,description:c.description,instructions:c.instructions,tools:c.tools??[],effort:c.effort,delegate:c.delegate}});fe(`Created ${x.name}.`),nt(),r(x.name)}catch(x){const w=je(x instanceof Error?x.message:"The agent could not be created.");A(w.message),C(w.field)}finally{v(!1)}}},P=t?"Duplicate as a new agent":"New agent";return e.jsxs("div",{className:"max-w-3xl space-y-6",children:[e.jsxs("header",{className:"space-y-2",children:[e.jsx("h2",{className:"text-title",children:P}),e.jsx("p",{className:"text-body-sm text-ink-muted",children:t?`A copy of ${t.name}. It is a separate agent: changing it does not change the original.`:"Reusable instructions shared by agent commands, subagents and teams. Chats stay separate."})]}),j&&!u?e.jsxs(ee,{variant:"danger",role:"alert","data-testid":"agent-create-error",children:[e.jsx(te,{children:"That did not save"}),e.jsx(se,{children:j})]}):null,e.jsxs("form",{noValidate:!0,onSubmit:N=>{N.preventDefault(),F(N)},className:"space-y-6",children:[e.jsx(L,{title:"Name and role",children:e.jsxs("div",{className:"grid gap-4 sm:grid-cols-2",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx(J,{label:"Name",htmlFor:"agent-create-name",error:u==="name"?j:null}),e.jsx(le,{id:"agent-create-name",ref:E,value:f,required:!0,"aria-invalid":u==="name",onChange:N=>h(N.target.value)})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(J,{label:"How it works with others",htmlFor:"agent-create-kind"}),e.jsxs(Ye,{value:g,onValueChange:N=>i(N),children:[e.jsx(Qe,{id:"agent-create-kind",children:e.jsx(Xe,{})}),e.jsxs(Ze,{children:[e.jsx(xe,{value:"role",children:"You can chat with it directly"}),e.jsx(xe,{value:"specialist",children:"Other agents can call on it"})]})]})]})]})}),e.jsx(ye,{title:"When to use it",description:"One sentence the model reads to decide when this agent is the right one.",label:"When to use this agent",value:c.description,error:u==="description"?j:null,onChange:N=>b(x=>({...x,description:N}))}),e.jsx(ye,{title:"Instructions",description:"What the agent is told to do. This is the agent's whole behaviour.",label:"Instructions",value:c.instructions,rows:12,required:!0,fieldRef:B,error:u==="instructions"?j:null,onChange:N=>b(x=>({...x,instructions:N}))}),e.jsx(L,{title:"Delegation and effort",children:e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-body-sm",children:[e.jsx(Ee,{checked:c.delegate,onCheckedChange:N=>b(x=>({...x,delegate:N})),"aria-label":"May delegate to subagents"}),e.jsx("span",{children:"May delegate to subagents"})]}),e.jsxs("div",{className:"max-w-sm space-y-1",children:[e.jsx(J,{label:"Effort tier",htmlFor:"agent-create-effort"}),e.jsx(be,{ariaLabel:"Effort tier",showLabel:!1,busyLabel:"Loading effort tiers",placeholder:"Choose an effort tier",options:["inherit",...n].map(N=>({id:N,name:N,description:N==="inherit"?"Use the session's own effort":"A tier configured in Settings"})),selected:{id:c.effort,name:c.effort},onSelect:N=>b(x=>({...x,effort:N.id}))})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx("span",{className:"text-body-sm text-ink-muted",children:"Tools"}),e.jsx(rt,{tools:c.tools,error:u==="tools"?j:null,onChange:N=>b(x=>({...x,tools:N}))})]})]})}),e.jsx(Ae,{submit:!0,dirty:!!(f.trim()||c.instructions),pending:y,saveLabel:t?"Create the copy":"Create agent",pendingLabel:"Creating…",dirtyHint:"Discard this new agent?",onSave:()=>void F(),onCancel:d})]})]})}const ve=t=>t==null?"":typeof t=="string"?t:JSON.stringify(t,null,2),$s={available:"border-hairline",updating:"border-hairline",applied:"border-hairline",review:"border-warning-border",failed:"border-danger-border"};function Ts(t){const s=[];for(const n of t??[])for(const a of n.fields??[])for(const r of a.regions??[])(r.provenance==="unresolved"||ve(r.local)!==ve(r.remote))&&s.push({field:a.field,region:r});return s}function Ds({regions:t}){return t.length?e.jsx("ul",{className:"space-y-3","data-testid":"hub-update-preview",children:t.map(({field:s,region:n},a)=>e.jsxs("li",{className:"space-y-1 text-meta",children:[e.jsx("p",{className:"font-medium text-ink",children:n.heading||n.name||s}),e.jsxs("div",{className:"grid gap-2 sm:grid-cols-2",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-ink-muted",children:"Yours"}),e.jsx("pre",{className:"max-h-40 overflow-auto whitespace-pre-wrap rounded-sm border border-hairline p-2 text-ink",children:ve(n.local)||"(nothing)"})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-ink-muted",children:"The hub's"}),e.jsx("pre",{className:"max-h-40 overflow-auto whitespace-pre-wrap rounded-sm border border-hairline p-2 text-ink",children:ve(n.remote)||"(nothing)"})]})]})]},`${s}:${n.id??a}`))}):e.jsx("p",{className:"text-meta text-ink-muted",children:"No differences to show: the hub's version matches yours."})}function Rs({kind:t,name:s,enabled:n}){const a=wt(n),r=St(),[d,f]=l.useState(null),h=Et(t,s),g=Ct(a.data).get(h),i=At(g),c=r.notes[h],b=r.pending.has(h);if(!g||!i)return c?e.jsx("section",{"data-testid":"hub-update-panel","aria-label":"Hub update",className:"mb-6 max-w-3xl rounded-md border border-hairline p-3 text-body-sm",children:e.jsx("p",{role:c.tone==="error"?"alert":"status",className:c.tone==="error"?"text-danger":"text-ink",children:c.message})}):null;const y=i.kind==="review",v=g.classification==="baseline-unknown",j=u=>({prefer:u,acknowledgeUnknownBaseline:v}),A=async()=>{const u=await r.applyItem(t,s,{...j(),dryRun:!0});f(u??[])};return e.jsxs("section",{"data-testid":"hub-update-panel","aria-label":"Hub update",className:Y("mb-6 max-w-3xl space-y-2 rounded-md border p-3 text-body-sm",$s[i.kind]),children:[e.jsxs("p",{className:"flex items-start gap-2 text-ink",children:[e.jsx(It,{mark:i,className:"mt-0.5"}),e.jsx("span",{className:Y(i.kind==="failed"&&"text-danger"),children:$t(g,i)})]}),y&&v&&e.jsx("p",{className:"text-meta text-ink-muted",children:"Nothing records what you changed on this device. Either choice adds the hub's additions and deletes nothing of yours; where the two versions differ, your choice decides which wording stays."}),y&&!v&&e.jsx("p",{className:"text-meta text-ink-muted",children:"Where the two versions differ, your choice decides which wording stays. Everything else is merged, and your current version is saved as a backup first."}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[i.kind==="available"&&e.jsx(k,{size:"sm",variant:"outline","aria-disabled":b||void 0,onClick:()=>!b&&void r.applyItem(t,s),children:b?"Updating…":"Update from the hub"}),i.kind==="failed"&&i.retryable&&e.jsx(k,{size:"sm",variant:"outline","aria-disabled":b||void 0,onClick:()=>!b&&void r.retryItem(t,s),children:b?"Retrying…":"Retry"}),y&&e.jsxs(e.Fragment,{children:[e.jsx(k,{size:"sm",variant:"outline","aria-disabled":b||void 0,onClick:()=>!b&&void A(),children:b&&!d?"Loading…":"Preview the differences"}),e.jsx(k,{size:"sm",variant:"ghost","aria-disabled":b||void 0,onClick:()=>!b&&void r.applyItem(t,s,j("local")),children:"Keep mine where they differ"}),e.jsx(k,{size:"sm",variant:"ghost","aria-disabled":b||void 0,onClick:()=>!b&&void r.applyItem(t,s,j("remote")),children:"Use the hub's where they differ"})]})]}),d&&y&&e.jsx(Ds,{regions:Ts(d)}),c&&e.jsx("p",{role:c.tone==="error"?"alert":"status",className:c.tone==="error"?"text-meta text-danger":"text-meta text-ink-muted",children:c.message})]})}function he(t){return{description:t?.description??"",manager:t?.manager??"manager",members:(t?.members??[]).map(s=>({...s,key:crypto.randomUUID()})),instructions:t?.instructions??"",project:t?.project??""}}function Ls(t,s){const n={};return s.description!==t.description&&(n.description=s.description),s.manager!==t.manager&&(n.manager=s.manager),JSON.stringify(s.members.map(({key:a,...r})=>r))!==JSON.stringify(t.members.map(({key:a,...r})=>r))&&(n.members=s.members.map(({key:a,...r})=>r)),s.instructions!==t.instructions&&(n.instructions=s.instructions),s.project!==t.project&&(n.project=s.project),n}function Pe(t,s,n){return(t.kind==="agent"?(s??[]).map(r=>r.name):(n??[]).map(r=>r.name)).includes(t.role)}function Be({team:t,agents:s,teams:n,askEnabled:a,onSaved:r,onCancelCreate:d,onOpenAgent:f,onAskAgent:h,onDirtyChange:g}){const i=!t,[c,b]=l.useState(i),[y,v]=l.useState(t?.name??""),[j,A]=l.useState(()=>he(t)),[u,C]=l.useState(()=>he(t)),[E,B]=l.useState(!1),[F,P]=l.useState(null),[N,x]=l.useState(null),[w,M]=l.useState(!1),S=l.useRef(null),D=l.useRef(null),R=l.useRef(null);l.useEffect(()=>{at()&&requestAnimationFrame(()=>S.current?.focus())},[]);const _=Ke(),z=i?!!(y.trim()||u.description||u.members.length):JSON.stringify(u)!==JSON.stringify(j);l.useEffect(()=>(g?.((i||c)&&z),()=>g?.(!1)),[g,i,c,z]),l.useEffect(()=>{if(c&&z)return;const o=he(t);A(o),C(o)},[t,c,z]);const ce=()=>{if(i){d?.();return}b(!1),P(null),x(null),M(!1);const o=he(t);A(o),C(o)};st(()=>{if(w){M(!1);return}z?M(!0):ce()},c);const X=async o=>{if(o?.preventDefault(),!E){if(i&&!y.trim()){P("Give the team a name."),x("name"),R.current?.focus();return}if(i&&/[\\/\s]/.test(y.trim())){P("Names cannot contain spaces or slashes."),x("name"),R.current?.focus();return}if(i&&(n??[]).some(p=>p.name===y.trim())){P(`A team called “${y.trim()}” already exists. Open it to change it, or choose another name.`),x("name"),R.current?.focus();return}if(i&&!u.instructions.trim()){P("Give the team instructions."),x("instructions"),D.current?.focus();return}B(!0),P(null),x(null);try{const p=t?await V({op:"teams.update",name:t.name,requestId:crypto.randomUUID(),fields:Ls(j,u)}):await V({op:"teams.create",requestId:crypto.randomUUID(),fields:{name:y,description:u.description,manager:u.manager,members:u.members.map(({key:$,...W})=>W),instructions:u.instructions,project:u.project}}),T=he(p);A(T),C(T),b(!1),r(p.name),fe(`${i?"Created":"Saved"} ${p.name}.`),i&&nt(),requestAnimationFrame(()=>S.current?.focus())}catch(p){const T=je(p instanceof Error?p.message:"The team could not be saved.");P(T.message),x(T.field),Se(T.message)}finally{B(!1)}}},I=(o,p)=>C(T=>({...T,members:T.members.map(($,W)=>W===o?{...$,...p}:$)})),q=(u.members.length?u.members:t?.members??[]).reduce((o,p)=>o+(p.count||1),0);return e.jsxs("div",{className:"max-w-3xl space-y-6",children:[e.jsxs("header",{className:"space-y-3",children:[e.jsxs("div",{className:"flex flex-wrap items-start justify-between gap-x-4 gap-y-3",children:[e.jsxs("div",{className:"min-w-0 space-y-2",children:[e.jsx("h2",{ref:S,tabIndex:-1,className:"text-title focus:outline-none",children:t?Ve(t):"New team"}),e.jsxs("div",{className:"flex flex-wrap items-center gap-1.5",children:[e.jsx(U,{variant:"neutral",children:q===1?"1 agent":`${q} agents`}),u.members.some(o=>o.kind==="team")?e.jsx(U,{variant:"neutral",children:"Includes a team"}):null]})]}),t?e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx(k,{variant:"primary",onClick:()=>{We.getState().stageDraft({kind:"team",name:t.name}),_("/chat")},children:"New team chat"}),c?null:e.jsx(k,{variant:"secondary",onClick:()=>b(!0),children:"Edit"}),a?e.jsx(k,{variant:"ghost",onClick:()=>h(`Change the team ${t.name}: `),children:"Ask for a change"}):null]}):null]}),F&&!N?e.jsxs(ee,{variant:"danger",role:"alert","data-testid":"team-save-error",children:[e.jsx(te,{children:"That did not save"}),e.jsx(se,{children:F})]}):null]}),e.jsx("form",{noValidate:!0,onSubmit:o=>{o.preventDefault(),X(o)},className:"space-y-6",children:i||c?e.jsxs(e.Fragment,{children:[i?e.jsxs(L,{title:"Name",description:"How you and your chats will refer to this team.",children:[e.jsx(J,{label:"Team name",htmlFor:"team-name",error:N==="name"?F:null}),e.jsx(le,{ref:R,id:"team-name","data-testid":"team-name-input",value:y,required:!0,maxLength:64,autoFocus:!0,"aria-invalid":N==="name",onChange:o=>v(o.target.value)})]}):null,e.jsx(L,{title:"Manager",description:"The agent that leads the chat and decides who works on what.",children:e.jsxs("div",{className:"max-w-md space-y-2",children:[e.jsx(J,{label:"Manager agent",htmlFor:"team-manager",error:N==="manager"?F:null}),e.jsx(be,{ariaLabel:"Manager agent",showLabel:!1,placeholder:"Choose a manager",busyLabel:"Loading agents",options:ae(s,n),selected:ae(s,n).find(o=>o.id===u.manager)??null,onSelect:o=>C(p=>({...p,manager:o.id})),onCustomSubmit:o=>C(p=>({...p,manager:o})),listNotice:"Agents and teams on this machine"}),ae(s,n).some(o=>o.id===u.manager)?null:e.jsxs(U,{variant:"warning","data-testid":"team-manager-missing",children:["Not found: ",u.manager]})]})}),e.jsx(L,{title:"Members",description:"Who the manager can delegate to, and how many of each.",children:e.jsxs("div",{className:"space-y-2",children:[u.members.map((o,p)=>{const T=!Pe(o,s,n);return e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx("div",{className:"w-56",children:e.jsx(be,{ariaLabel:`Member ${p+1}`,showLabel:!1,placeholder:"Choose an agent or team",busyLabel:"Loading agents",options:[...ae(s,n).filter($=>o.kind==="team"?$.group==="Teams":$.group==="Agents")],selected:ae(s,n).find($=>$.id===o.role)??null,onSelect:$=>I(p,{role:$.id,kind:$.group==="Teams"?"team":"agent"}),onCustomSubmit:$=>I(p,{role:$})})}),e.jsxs(Ye,{value:o.kind,onValueChange:$=>I(p,{kind:$}),children:[e.jsx(Qe,{"aria-label":`Member ${p+1} kind`,className:"w-32",children:e.jsx(Xe,{})}),e.jsxs(Ze,{children:[e.jsx(xe,{value:"agent",children:"Agent"}),e.jsx(xe,{value:"team",children:"Team"})]})]}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(k,{variant:"secondary",size:"icon-sm","aria-label":`One fewer ${o.role}`,disabled:o.count<=1,onClick:()=>I(p,{count:o.count-1}),children:e.jsx(Ot,{"aria-hidden":"true"})}),e.jsx("span",{className:"min-w-6 text-center text-body-sm tabular-nums","aria-label":`${o.count} of ${o.role}`,children:o.count}),e.jsx(k,{variant:"secondary",size:"icon-sm","aria-label":`One more ${o.role}`,disabled:o.count>=16,onClick:()=>I(p,{count:o.count+1}),children:e.jsx(Ge,{"aria-hidden":"true"})})]}),e.jsx(k,{variant:"ghost",onClick:()=>C($=>({...$,members:$.members.filter((W,G)=>G!==p)})),children:"Remove"}),T?e.jsxs(U,{variant:"warning",children:["Not found: ",o.role]}):null]},o.key)}),e.jsx(k,{variant:"secondary",onClick:()=>C(o=>({...o,members:[...o.members,{role:"",count:1,kind:"agent",key:crypto.randomUUID()}]})),children:"Add member"})]})}),e.jsxs(L,{title:"Description",children:[e.jsx(J,{label:"What this team is for",htmlFor:"team-description",error:N==="description"?F:null}),e.jsx(le,{id:"team-description",value:u.description,onChange:o=>C(p=>({...p,description:o.target.value}))})]}),e.jsxs(L,{title:"Collaboration instructions",children:[N==="instructions"?e.jsx("p",{className:"text-meta text-danger",role:"alert","data-testid":"team-instructions-error",children:F}):null,e.jsx(pe,{ref:D,"aria-label":"Collaboration instructions","aria-invalid":N==="instructions",className:"min-h-36",maxLength:8e3,value:u.instructions,onChange:o=>C(p=>({...p,instructions:o.target.value}))})]}),e.jsx(L,{title:"Project brief",children:e.jsx(pe,{"aria-label":"Project brief",className:"min-h-36",maxLength:8e3,value:u.project,onChange:o=>C(p=>({...p,project:o.target.value}))})}),e.jsx(Ae,{submit:!0,confirming:w,onConfirmingChange:M,dirty:z,pending:E,saveLabel:i?"Create team":"Save changes",pendingLabel:i?"Creating…":"Saving…",dirtyHint:"Discard this team?",onSave:()=>void X(),onCancel:ce})]}):e.jsxs(e.Fragment,{children:[e.jsx(L,{title:"Manager",description:"The agent that leads the chat.",children:e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx(k,{variant:"link",onClick:()=>f(u.manager),children:u.manager}),ae(s,n).some(o=>o.id===u.manager)?null:e.jsx(U,{variant:"warning","data-testid":"team-manager-missing",children:"Not found"})]})}),e.jsx(L,{title:"Members",children:e.jsx("ul",{className:"space-y-1",children:(t?.members??[]).map(o=>e.jsxs("li",{className:"flex flex-wrap items-center gap-2 text-body-sm",children:[e.jsx("span",{className:"text-ink",children:o.role}),e.jsx(U,{variant:"neutral",children:o.kind==="team"?"Team":"Agent"}),e.jsx("span",{className:"text-ink-muted",children:o.count===1?"×1":`×${o.count}`}),Pe(o,s,n)?null:e.jsx(U,{variant:"warning","data-testid":"team-member-missing",children:"Not found"})]},`${o.kind}:${o.role}`))})}),e.jsx(L,{title:"What it is for",children:e.jsx(oe,{text:t?.description??"",empty:"No description yet."})}),t?.instructions?e.jsx(L,{title:"Collaboration instructions",children:e.jsx(oe,{text:t.instructions})}):null,t?.project?e.jsx(He,{summary:"Project brief",children:e.jsx(oe,{text:t.project})}):null]})})]})}function ae(t,s){return[...(t??[]).map(n=>({id:n.name,name:n.name,description:n.description,group:"Agents"})),...(s??[]).map(n=>({id:n.name,name:n.name,description:n.description,group:"Teams"}))]}const Fs=l.lazy(()=>vt(()=>import("./legacy-agents-page-BSKz_UrV.js"),__vite__mapDeps([0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15]),import.meta.url).then(t=>({default:t.LegacyAgentsPage}))),qe=/^subagents\.models\.([^.]+)$/,Os=["lo","med","hi"],we={all:"All",custom:"Custom",installed:"Installed",builtin:"Built-in"},ge=t=>{const s=JSON.stringify(t)??"";let n=5381;for(let a=0;a<s.length;a+=1)n=(n*33^s.charCodeAt(a))>>>0;return`${s.length}.${n.toString(36)}`};function Vs(){const t=mt("surface"),{agentId:s}=ht(),[n,a]=ft(),r=n.get("kind")==="team"||n.get("create")==="team",d=n.has("create"),f=n.get("name"),h=n.get("duplicate"),g=ze(),i=re(g.data,r?"team_catalogue":"profile_catalogue"),c=gt(i),b=pt(i),y=i&&!!f&&!d,v=De(r?null:f,y),j=xt(r?f:null,y),A=De(r?null:h,!!h),[u,C]=l.useState(""),[E,B]=l.useState("all"),[F,P]=l.useState(null),[N,x]=l.useState(null),[w,M]=l.useState(0),S=os(),D=K(m=>m.marks),R=K(m=>m.clearMark),_=bt({queryKey:["desktop","settings","effort-tiers"],enabled:i,queryFn:()=>V({op:"settings.list"}),staleTime:6e4}),z=l.useMemo(()=>(_.data?.settings??[]).filter(m=>{const O=m.key.match(qe)?.[1];return!O||!Os.includes(O)?!1:typeof m.value=="string"&&m.value.trim().length>0}).map(m=>m.key.match(qe)?.[1]).filter(m=>!!m),[_.data]),ce=l.useMemo(()=>Ms(c.data,u,E),[c.data,u,E]),de=l.useMemo(()=>Ps(b.data,u),[b.data,u]),X=r?de:ce,I=f??null,q=l.useCallback(m=>{const O=new URLSearchParams;(m.kind??(r?"team":"agent"))==="team"&&O.set("kind","team"),m.name&&O.set("name",m.name),m.create!==null&&m.create!==void 0&&O.set("create",m.create),m.duplicate&&O.set("duplicate",m.duplicate),P(null),a(O)},[r,a]),o=`${r?"team":"agent"}:${d??""}:${I??""}`,p=l.useCallback(m=>x(m?o:null),[o]),T=N!==null&&N===o,[$,W]=l.useState(!1),G=`${r?"team":"agent"}:${I??""}`,Z=r?j.data?ge(j.data):null:v.data?ge(v.data):null,ne=l.useRef({identity:G,content:Z});l.useEffect(()=>{if(ne.current.identity!==G){ne.current={identity:G,content:Z},W(!1);return}if(Z===null||ne.current.content===null){ne.current={identity:G,content:Z};return}ne.current.content!==Z&&(ne.current.content=Z,T&&W(!0))},[G,Z,T]);const Ie=(m,O)=>e.jsxs(e.Fragment,{children:[e.jsx(Rs,{kind:m,name:O,enabled:re(g.data,"hub_updates")}),$&&e.jsx("output",{className:"mb-6 block max-w-3xl rounded-md border border-warning-border px-3 py-2 text-meta text-ink-muted",children:"The hub updated this definition while you were editing, and the form below now shows the merged version. Edits you had not saved were replaced."})]}),H=l.useCallback(m=>{if(T){P(m);return}q(m)},[T,q]);l.useEffect(()=>{const m=O=>{O.key!=="Escape"||O.defaultPrevented||window.matchMedia("(max-width: 999px)").matches&&(!I&&!d||(O.preventDefault(),H({name:null})))};return window.addEventListener("keydown",m),()=>window.removeEventListener("keydown",m)},[H,I,d]),l.useEffect(()=>{const m=K.getState(),O=m.about;if(!O)return;const $e=r?"team":"agent";I&&O.kind===$e&&O.name===I||(S.setAbout(null),m.draft.trim()===`Change the ${O.kind} ${O.name}:`.trim()&&S.setDraft(""))},[I,r,S]),l.useEffect(()=>{I&&R({kind:r?"team":"agent",name:I})},[I,r,R]);const ue=()=>{c.refetch(),b.refetch(),v.refetch(),j.refetch()};if(s)return e.jsx(l.Suspense,{fallback:e.jsx("p",{className:"p-6 text-body",children:"Loading saved agent…"}),children:e.jsx(Fs,{})});const ke=r?j.error:v.error,me=r?b.error:c.error,it=i&&!me&&!d&&!I,ot=r?j.isLoading:v.isLoading;return e.jsxs("div",{className:"flex h-full min-h-0 bg-canvas text-ink",children:[e.jsxs("aside",{ref:t,"data-open":I?"true":void 0,className:"flex w-72 shrink-0 flex-col gap-3 bg-surface p-4 max-[999px]:data-[open=true]:hidden",children:[e.jsx("h1",{className:"text-heading",children:"Agents and teams"}),e.jsx(_t,{value:r?"team":"agent",onValueChange:m=>H({kind:m,name:null}),children:e.jsxs(Ut,{"aria-label":"Browse definitions by type",className:"w-full",children:[e.jsxs(Re,{value:"agent",className:"flex-1","data-testid":"agents-tab",children:[e.jsx(Tt,{className:"size-3.5"}),"Agents",c.data?e.jsx("span",{className:"min-w-[2ch] font-normal text-ink-dim tabular-nums",children:c.data.length}):null]}),e.jsxs(Re,{value:"team",className:"flex-1","data-testid":"teams-tab",children:[e.jsx(jt,{className:"size-3.5"}),"Teams",b.data?e.jsx("span",{className:"min-w-[2ch] font-normal text-ink-dim tabular-nums",children:b.data.length}):null]})]})}),e.jsxs("div",{className:"relative",children:[e.jsx(yt,{"aria-hidden":"true",className:"pointer-events-none absolute top-2 left-2 size-4 text-ink-dim"}),e.jsx(le,{className:"pl-8",type:"search","aria-label":"Search agents and teams",placeholder:r?"Search teams":"Search agents",value:u,onChange:m=>C(m.target.value)})]}),!r&&c.data?e.jsxs("div",{className:"flex flex-wrap items-center gap-x-2 gap-y-1",children:[e.jsx("span",{"aria-hidden":"true",className:"text-meta text-ink-muted",children:"Showing"}),e.jsxs("fieldset",{className:"m-0 min-w-0 border-0 p-0",children:[e.jsx("legend",{className:"sr-only",children:"Show definitions owned by"}),e.jsx("div",{className:"flex flex-wrap gap-0.5 rounded-md bg-sunken p-0.5",children:Object.keys(we).map(m=>e.jsx(k,{variant:"ghost",size:"sm","aria-pressed":E===m,onClick:()=>B(m),className:Y(E===m&&Je),children:we[m]},m))})]})]}):null,e.jsx("div",{className:"min-h-0 flex-1 overflow-y-auto",children:me?null:!c.data&&!b.data?e.jsx(Ns,{}):X.length===0?e.jsx("p",{className:"px-1 py-2 text-body-sm text-ink-muted",children:u?`Nothing matches “${u}”.`:r?"No teams yet. Ask for one below, or add one by hand.":E==="all"?"No agents yet. Ask for one below, or add one by hand.":`No ${we[E].toLowerCase()} agents.`}):e.jsx(Us,{rows:X,name:d?null:I,teamMode:r,marked:new Map(D.map(m=>[Vt(m),m.created])),onOpen:m=>H({name:m})})}),e.jsxs(k,{variant:"secondary",disabled:!i,onClick:()=>H({create:r?"team":"agent"}),children:[e.jsx(Ge,{className:"size-4"}),r?"Add team manually":"Add agent manually"]})]}),e.jsxs("main",{className:"flex min-w-0 flex-1 flex-col",children:[I||d?e.jsx("div",{className:"flex shrink-0 items-center border-hairline border-b px-4 py-2 min-[1000px]:hidden",children:e.jsxs(k,{variant:"ghost",size:"sm",onClick:()=>H({name:null}),children:[e.jsx(Dt,{className:"size-4"}),"Back to the list"]})}):null,e.jsx("div",{className:"min-h-0 flex-1 overflow-auto p-6 pb-0",style:w>0?{paddingBottom:w+16}:void 0,children:i?me?e.jsx(Me,{title:r?"Teams could not be read":"Agents could not be read",what:me instanceof Error?me.message:"The request did not complete.",meaning:"Nothing is lost. This is a read that failed — the backend answered an error, which is different from the backend being out of date.",onRetry:ue,retrying:c.isFetching||b.isFetching}):I&&ot?e.jsx(Ue,{}):I&&ke?e.jsx(Me,{title:r?`“${I}” could not be read`:`“${I}” could not be read`,what:ke instanceof Error?ke.message:"The request did not complete.",meaning:"The definition may have been removed, or the backend refused the read.",onRetry:()=>{v.refetch(),j.refetch()},retrying:v.isFetching||j.isFetching}):d&&r?e.jsx(Be,{agents:c.data,teams:b.data,askEnabled:S.enabled,onDirtyChange:p,onSaved:m=>{ue(),q({name:m})},onCancelCreate:()=>q({name:null}),onOpenAgent:m=>H({kind:"agent",name:m}),onAskAgent:m=>{S.setAbout({kind:"team",name:f??""}),S.setDraft(m)}},"team:create"):d&&h&&A.isLoading?e.jsx(Ue,{}):d?e.jsx(Is,{initial:A.data??null,takenNames:(c.data??[]).map(m=>m.name),effortTiers:z,onDirtyChange:p,onSaved:m=>{ue(),q({name:m})},onCancel:()=>q({name:null})},"agent:create"):r&&j.data?e.jsxs(e.Fragment,{children:[Ie("team",j.data.name),e.jsx(Be,{team:j.data,agents:c.data,teams:b.data,askEnabled:S.enabled,onDirtyChange:p,onSaved:m=>{ue(),q({name:m})},onOpenAgent:m=>H({kind:"agent",name:m}),onAskAgent:m=>{S.setAbout({kind:"team",name:j.data?.name??""}),S.setDraft(m)}},`team:${j.data.name}:${ge(j.data)}`)]}):!r&&v.data?e.jsxs(e.Fragment,{children:[Ie("agent",v.data.name),e.jsx(As,{profile:v.data,teams:b.data,effortTiers:z,askEnabled:S.enabled,onDirtyChange:p,onSaved:m=>{ue(),q({name:m})},onDuplicate:m=>H({create:"agent",duplicate:m.name}),onOpenTeam:m=>H({kind:"team",name:m}),onAskAgent:m=>{S.setAbout({kind:"agent",name:v.data?.name??""}),S.setDraft(m)}},`agent:${v.data.name}:${v.data.source}:${ge(v.data)}`)]}):I?e.jsx(ie,{className:"h-6 w-40"}):e.jsx(_s,{teamMode:r,run:S,onAddManually:()=>H({create:r?"team":"agent"})}):e.jsxs(ee,{variant:g.isLoading?"neutral":"warning",className:"max-w-xl",children:[e.jsx(te,{children:g.isLoading?"Connecting to the backend":g.error?"The backend could not be reached":"Reusable agents need a newer backend"}),e.jsx(se,{children:g.isLoading?"Loading what this backend can do…":g.error?g.error.message:"Update the backend to manage reusable agents and teams. Saved chats are unchanged."})]})}),F?e.jsxs("div",{className:"flex flex-wrap items-center gap-2 border-hairline border-t bg-surface px-4 py-3",role:"alertdialog","aria-label":"Discard your unsaved changes?",children:[e.jsx("span",{className:"text-body-sm text-ink",children:r?"Discard your unsaved changes to this team?":"Discard your unsaved changes to this agent?"}),e.jsx(k,{variant:"danger",onClick:()=>{x(null),q(F)},children:"Discard changes"}),e.jsx(k,{variant:"ghost",onClick:()=>P(null),children:"Keep editing"})]}):null,it?null:e.jsx("div",{className:"shrink-0 border-hairline border-t bg-canvas p-4",children:e.jsx(et,{run:S,about:S.about,onClearAbout:()=>S.setAbout(null),onStripHeightChange:M,blockedReason:T?"Finish or cancel your edit first.":null})})]})]})}function _s({teamMode:t,run:s,onAddManually:n}){return e.jsxs("div",{className:"max-w-xl space-y-4",children:[e.jsx("h2",{className:"text-title",children:t?"Ask for a team":"Ask for an agent"}),e.jsx("p",{className:"text-body text-ink-muted",children:t?"A team has one agent that leads the chat and members it can hand work to. Describe what you want and a configuration run sets it up.":"An agent is a reusable set of instructions you can start a chat with, or let other agents call on. Describe what you want and a configuration run sets it up."}),e.jsx(et,{run:s,hero:!0,about:s.about,onClearAbout:()=>s.setAbout(null)}),e.jsx(k,{variant:"ghost",onClick:n,children:t?"Or add a team by hand":"Or add an agent by hand"})]})}function Us({rows:t,name:s,teamMode:n,marked:a,onOpen:r}){const d=l.useRef(new Map),[f,h]=l.useState(s),g=(i,c)=>{const b=t.findIndex(v=>v.name===i);if(b<0)return;const y=t[Math.min(t.length-1,Math.max(0,b+c))];y&&(h(y.name),d.current.get(y.name)?.focus())};return e.jsx("ul",{"aria-label":n?"Teams":"Agents",className:"space-y-1",children:t.map(i=>{const c="source"in i,b=a.get(`${n?"team":"agent"}:${i.name}`);return e.jsx("li",{children:e.jsxs("button",{ref:y=>{y?d.current.set(i.name,y):d.current.delete(i.name)},type:"button","aria-current":i.name===s?"true":void 0,tabIndex:i.name===(f??t[0]?.name)?0:-1,"data-testid":`roster-row-${i.name}`,className:Y("flex min-h-11 w-full flex-col items-start gap-0.5 rounded-md px-2 py-1.5 text-left hover:bg-row-hover",i.name===s&&Je),onFocus:()=>h(i.name),onClick:()=>r(i.name),onKeyDown:y=>{y.key==="ArrowDown"?(y.preventDefault(),g(i.name,1)):y.key==="ArrowUp"?(y.preventDefault(),g(i.name,-1)):y.key==="Home"?(y.preventDefault(),g(i.name,-t.length)):y.key==="End"&&(y.preventDefault(),g(i.name,t.length))},children:[e.jsxs("span",{className:"flex w-full items-center gap-2",children:[e.jsx("span",{className:"truncate text-body-sm text-ink",children:"members"in i?Ve(i):i.name}),c?e.jsx(tt,{source:i.source,appearance:"text"}):null,b!==void 0?e.jsx(U,{variant:"attention","data-testid":"roster-row-updated",children:b?"New":"Updated"}):null]}),e.jsxs("span",{className:"flex w-full flex-wrap items-center gap-1.5",children:["members"in i?e.jsx(U,{variant:"neutral",children:i.members.length===1?"1 member":`${i.members.length} members`}):null,i.description?e.jsx("span",{className:"min-w-0 flex-1 truncate text-meta text-ink-muted",children:i.description}):null]})]})},i.name)})})}function Ms(t,s,n){const a=s.trim().toLowerCase();return(t??[]).filter(r=>n==="builtin"&&r.source!=="builtin"||n==="installed"&&r.source!=="installed"||n==="custom"&&r.source!=="custom"?!1:a?r.name.toLowerCase().includes(a)||(r.description??"").toLowerCase().includes(a):!0)}function Ps(t,s){const n=s.trim().toLowerCase();return(t??[]).filter(a=>!n||a.name.toLowerCase().includes(n)||(a.label??"").toLowerCase().includes(n)||(a.description??"").toLowerCase().includes(n))}export{Vs as AgentsPage};