@tickernelz/paperclip-pro-ui 2026.1025.1 → 2026.1025.2

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 (64) hide show
  1. package/dist/assets/{AgentAvatar-a7bfB7xg.js → AgentAvatar-BtQCvYNI.js} +1 -1
  2. package/dist/assets/{Agents.production-CYv4yLRB.js → Agents.production-DbtoAoUQ.js} +2 -2
  3. package/dist/assets/{BreadcrumbContext-DLK8i_g2.js → BreadcrumbContext-DSzhZWh7.js} +1 -1
  4. package/dist/assets/{CompanyActivity.production-C2uGYQY6.js → CompanyActivity.production-Bx3wHHDp.js} +1 -1
  5. package/dist/assets/{CompanyExport-s-XLEAp4.js → CompanyExport-kpky2xuC.js} +1 -1
  6. package/dist/assets/{CompanySkills.production-DxzVSVNR.js → CompanySkills.production-BuVkNosy.js} +1 -1
  7. package/dist/assets/{EmptyState-QDPrmKhy.js → EmptyState-BWnCbo9i.js} +1 -1
  8. package/dist/assets/{MarkdownBody-BzeXdCZ_.js → MarkdownBody-5YQEeTHc.js} +1 -1
  9. package/dist/assets/{MarkdownEditor-CNWCu03H.js → MarkdownEditor-B01YT6TZ.js} +1 -1
  10. package/dist/assets/{OrgChart.production-BUtz4rsX.js → OrgChart.production-D-XB4GXh.js} +1 -1
  11. package/dist/assets/{PageSkeleton-BI65cMt2.js → PageSkeleton-DazUbswA.js} +1 -1
  12. package/dist/assets/{RoutineDetail.production-DdnWpLkf.js → RoutineDetail.production-B1919-qY.js} +1 -1
  13. package/dist/assets/{RoutineRunVariablesDialog-RFvGPey9.js → RoutineRunVariablesDialog-CWOnQljf.js} +1 -1
  14. package/dist/assets/{Routines.production-BIUgcKXN.js → Routines.production-CWKuR092.js} +1 -1
  15. package/dist/assets/{SearchableSelect-eKlsFAD7.js → SearchableSelect-BNdmZ91w.js} +1 -1
  16. package/dist/assets/{StatusIcon-BjNEucdG.js → StatusIcon-CDeLAAD6.js} +1 -1
  17. package/dist/assets/{Terminal-DGY5mL23.js → Terminal-BTETQQTg.js} +1 -1
  18. package/dist/assets/{ToastContext-5j4RZIE4.js → ToastContext-BhcEr0eG.js} +1 -1
  19. package/dist/assets/{access-BnSEFN27.js → access-CNVV-JPP.js} +1 -1
  20. package/dist/assets/agent-avatar-url-B3rF018s.js +1 -0
  21. package/dist/assets/{agents-B86qNZJT.js → agents-Be9FZXvR.js} +1 -1
  22. package/dist/assets/{alert-dialog-DHPsjJQF.js → alert-dialog-B9yc0xH5.js} +1 -1
  23. package/dist/assets/{arrow-right-B5yVL9Ho.js → arrow-right-DKHsAC4Q.js} +1 -1
  24. package/dist/assets/{badge-D_lRmUyU.js → badge-DKn90tZY.js} +1 -1
  25. package/dist/assets/{bot-BfjqAUbf.js → bot-ByBGWg5B.js} +1 -1
  26. package/dist/assets/{boxes-B_lUFC64.js → boxes-DLOydH_J.js} +56 -56
  27. package/dist/assets/{card-DR2Yz7xM.js → card-CIjSpeNG.js} +1 -1
  28. package/dist/assets/{check-BsQi0EEa.js → check-BwfUaND_.js} +1 -1
  29. package/dist/assets/{checkbox-B5a5-ayj.js → checkbox-DXAjlowZ.js} +1 -1
  30. package/dist/assets/{chevron-down-CxvFJ6Cw.js → chevron-down-n6cWCeT6.js} +1 -1
  31. package/dist/assets/{clipboard-C7Ql1dcp.js → clipboard-DfO4drH0.js} +1 -1
  32. package/dist/assets/{definition-BTeHNPYD.js → definition-g8Ojcw3n.js} +1 -1
  33. package/dist/assets/{dialog-T8GEoNcs.js → dialog-wSBPUZbR.js} +1 -1
  34. package/dist/assets/{dist-Dj-vtmDY.js → dist-Bh1tkrMN.js} +1 -1
  35. package/dist/assets/{dist-B-toxhvL.js → dist-Cbbod8tH.js} +1 -1
  36. package/dist/assets/{dist-CGPViZUA.js → dist-D1PYISjh.js} +1 -1
  37. package/dist/assets/{dist-BAlazNZs.js → dist-DAe64jq9.js} +1 -1
  38. package/dist/assets/{dist-De4zHy4P.js → dist-byHTiYvx.js} +1 -1
  39. package/dist/assets/{environments-D9A0D9Yc.js → environments-lOEya-g2.js} +1 -1
  40. package/dist/assets/{external-link-BzVQLoT1.js → external-link-CF7uAxuI.js} +1 -1
  41. package/dist/assets/{file-text-Bah9hFgx.js → file-text-_ZIlOXhw.js} +1 -1
  42. package/dist/assets/{health-Bswc2x2o.js → health-RLGdw6VN.js} +1 -1
  43. package/dist/assets/{heartbeats-DLg4CQMs.js → heartbeats-CtRu34PZ.js} +1 -1
  44. package/dist/assets/{index-UbNAxRQz.js → index-DGvCVg4n.js} +5 -5
  45. package/dist/assets/{input-p1LAHZWh.js → input-BLjkJw2C.js} +1 -1
  46. package/dist/assets/{instanceSettings-Dedq1Td_.js → instanceSettings-6aWAmT0B.js} +1 -1
  47. package/dist/assets/{label-D1JakEGT.js → label-BF7N7Ewo.js} +1 -1
  48. package/dist/assets/{mention-chips-CWTDajKR.js → mention-chips-DgHq43TZ.js} +1 -1
  49. package/dist/assets/{rotate-ccw-OivKhbwi.js → rotate-ccw-BW12Hr0F.js} +1 -1
  50. package/dist/assets/{save-azQ0lziL.js → save-BPX30Z4U.js} +1 -1
  51. package/dist/assets/{select-B77a5jtu.js → select-B93rxRbm.js} +1 -1
  52. package/dist/assets/{sheet-CjZsTn3Y.js → sheet-ClwtvLVS.js} +1 -1
  53. package/dist/assets/{skeleton-BCo4Krll.js → skeleton-CeDio6tF.js} +1 -1
  54. package/dist/assets/{tabs-BZnu46UX.js → tabs-LnaduMig.js} +1 -1
  55. package/dist/assets/{use-adapter-capabilities-3Qz_-Kk2.js → use-adapter-capabilities-DVwRtrsr.js} +1 -1
  56. package/dist/assets/{useHiddenSettings-Bxwcr3Ga.js → useHiddenSettings-u2chU7_y.js} +1 -1
  57. package/dist/assets/{usePrefersReducedMotion-DrOq9JVO.js → usePrefersReducedMotion-Bi8tEcS2.js} +1 -1
  58. package/dist/assets/{x-BBGMK4Si.js → x-DwA5I4ik.js} +1 -1
  59. package/dist/downloads/local-browser-chromium.zip +0 -0
  60. package/dist/downloads/local-browser-firefox-unsigned.zip +0 -0
  61. package/dist/index.html +49 -49
  62. package/dist/sw.js +1 -1
  63. package/package.json +1 -1
  64. package/dist/assets/agent-avatar-url-BETvvDkB.js +0 -1
@@ -1,5 +1,5 @@
1
- const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/runtime-IAg0vdY9.js","assets/model-DL5biheO.js","assets/definition-BTeHNPYD.js","assets/character-CguPM7IG.js","assets/prod-COP_vZWu.js","assets/rolldown-runtime-ZpX3ckPj.js","assets/CompanyExport-s-XLEAp4.js","assets/boxes-B_lUFC64.js","assets/BreadcrumbContext-DLK8i_g2.js","assets/preload-helper-CceJXRIF.js","assets/StatusIcon-BjNEucdG.js","assets/usePrefersReducedMotion-DrOq9JVO.js","assets/badge-D_lRmUyU.js","assets/MarkdownBody-BzeXdCZ_.js","assets/mention-chips-CWTDajKR.js","assets/agent-avatar-url-BETvvDkB.js","assets/check-BsQi0EEa.js","assets/clipboard-C7Ql1dcp.js","assets/external-link-BzVQLoT1.js","assets/agents-B86qNZJT.js","assets/rotate-ccw-OivKhbwi.js","assets/x-BBGMK4Si.js","assets/ToastContext-5j4RZIE4.js","assets/EmptyState-QDPrmKhy.js","assets/PageSkeleton-BI65cMt2.js","assets/skeleton-BCo4Krll.js","assets/Agents.production-CYv4yLRB.js","assets/alert-dialog-DHPsjJQF.js","assets/dist-BAlazNZs.js","assets/dist-B-toxhvL.js","assets/dist-Dj-vtmDY.js","assets/AgentAvatar-a7bfB7xg.js","assets/tabs-BZnu46UX.js","assets/dist-De4zHy4P.js","assets/bot-BfjqAUbf.js","assets/heartbeats-DLg4CQMs.js","assets/instanceSettings-Dedq1Td_.js","assets/environments-D9A0D9Yc.js","assets/Routines.production-BIUgcKXN.js","assets/SearchableSelect-eKlsFAD7.js","assets/dialog-T8GEoNcs.js","assets/RoutineRunVariablesDialog-RFvGPey9.js","assets/checkbox-B5a5-ayj.js","assets/label-D1JakEGT.js","assets/MarkdownEditor-CNWCu03H.js","assets/dist-CGPViZUA.js","assets/dist-BhxPxuMy.js","assets/select-B77a5jtu.js","assets/chevron-down-CxvFJ6Cw.js","assets/sheet-CjZsTn3Y.js","assets/useHiddenSettings-Bxwcr3Ga.js","assets/health-Bswc2x2o.js","assets/input-p1LAHZWh.js","assets/access-BnSEFN27.js","assets/company-members-Duugb3uG.js","assets/card-DR2Yz7xM.js","assets/RoutineDetail.production-DdnWpLkf.js","assets/arrow-right-B5yVL9Ho.js","assets/save-azQ0lziL.js","assets/CompanySkills.production-DxzVSVNR.js","assets/use-adapter-capabilities-3Qz_-Kk2.js","assets/file-text-Bah9hFgx.js","assets/CompanyActivity.production-C2uGYQY6.js","assets/Terminal-DGY5mL23.js","assets/OrgChart.production-BUtz4rsX.js"])))=>i.map(i=>d[i]);
2
- var e$e=Object.defineProperty;var r=(e,s)=>e$e(e,"name",{value:s,configurable:!0});import{i as hL,n as t$e,t as Fj}from"./rolldown-runtime-ZpX3ckPj.js";import{$ as QB,$i as Mv,$n as Mge,$r as Pge,$t as o3,A as qh,Aa as jee,Ai as s$e,An as n$e,Ar as r$e,At as l3,B as om,Ba as a$e,Bi as pk,Bn as wee,Br as T0,Bt as Dge,Ci as uR,Cn as i$e,Cr as NQ,Ct as Pa,D as pL,Di as $ge,Dn as o$e,Dr as Oge,Dt as l$e,Ei as WB,En as c$e,Er as HB,Et as d$e,Fi as u$e,Fn as m$e,Fr as h$e,Ft as p$e,G as W,Gi as f$e,Gn as x$e,Gr as Bge,Gt as Fge,H as kee,Ha as g$e,Hi as zge,Hn as b$e,Hr as mR,Ht as qge,Ii as hR,In as v$e,Ir as Uge,It as y$e,J as Xr,Ji as ke,Jn as Kge,Jr as j$e,Jt as w$e,K as k$e,Ki as ql,Kn as N$e,Kr as cj,Kt as S$e,L as HN,Li as C$e,Ln as Qge,Lr as _$e,M as VN,Mn as Wge,Mr as A$e,Mt as I$e,Ni as pR,Nn as T$e,Nr as R$e,O as E$e,Oi as L$e,On as M$e,Or as P$e,Ot as Nee,P as D$e,Pi as See,Pn as $$e,Pr as O$e,Pt as B$e,Q as F$e,Qn as z$e,Qr as Cee,Qt as q$e,R as zj,Ri as U$e,Rn as K$e,Rr as fk,Rt as _ee,Sa as Q$e,Si as Aee,Sn as Hge,Sr as W$e,St as D,T as vy,Ti as H$e,Tn as V$e,Tr as G$e,Tt as Iee,U as Tee,Ua as Vge,Ui as Y$e,Un as Z$e,Ur as GN,Ut as Gge,V as J$e,Va as wt,Vi as Ree,Vn as X$e,Vr as Yge,Vt as yS,W as SQ,Wa as CQ,Wi as _Q,Wn as eOe,Wr as Zge,Wt as tOe,X as Zd,Xi as Eee,Xn as Jge,Xr as Vp,Xt as Kx,Y as Xge,Yi as sOe,Yn as nOe,Yr as ebe,Yt as tbe,Z as yr,Zi as rOe,Zn as aOe,Zr as sbe,Zt as Lee,_i as iOe,_n as oOe,_r as lOe,_t as cOe,aa as tv,ai as HP,an as L_,ar as Mee,at as Qx,bi as nbe,bn as sv,br as Pee,bt as If,ca as te,ci as dOe,cn as M_,cr as FT,ct as hm,di as fL,dn as YN,dr as VB,dt as rbe,ea as uOe,ei as mOe,en as abe,er as ibe,et as Wi,fi as obe,fn as AQ,fr as hOe,ft as lbe,gi as pOe,gn as xL,gr as cbe,gt as dbe,hi as fOe,hn as ube,hr as fR,ht as fs,ia as nN,ii as xOe,in as Wm,ir as gOe,it as xR,j as mbe,ji as bOe,jn as vOe,jr as yOe,jt as rf,k as jOe,ki as IQ,kn as wOe,kr as nv,kt as af,la as kOe,li as gL,ln as Dee,lr as $ee,lt as TQ,mi as NOe,mn as SOe,mr as COe,mt as _Oe,n as qt,ni as Oee,nn as AOe,nr as IOe,nt as Km,oa as TOe,oi as ROe,on as hbe,or as EOe,ot as P_,pi as LOe,pn as Bee,pr as pbe,q as fbe,qi as nn,qn as MOe,qr as RQ,qt as POe,ra as DOe,ri as $Oe,rn as Yh,rr as OOe,rt as ka,sa as we,si as BOe,sn as EQ,sr as YC,st as ZC,t as Ac,ta as gR,ti as xbe,tn as Fee,tr as FOe,tt as zOe,ui as qOe,un as UOe,ur as GB,ut as gr,vi as KOe,vn as QOe,vr as WOe,vt as HOe,wi as VOe,wn as bR,wr as rN,wt as gbe,xa as GOe,xi as bbe,xn as YB,xr as YOe,xt as LQ,ya as ZOe,yi as ZN,yn as zT,yr as zee,yt as JOe,z as Hl,za as c3,zi as VP,zn as MQ,zr as XOe,zt as qee}from"./boxes-B_lUFC64.js";import{t as bd}from"./preload-helper-CceJXRIF.js";import{$ as H0,$t as eBe,A as tBe,An as sBe,At as qj,Bn as hi,Bt as ZB,C as nh,Cn as nBe,Ct as d3,Dn as vbe,Dt as ybe,E as rBe,En as aBe,Et as vR,F as JB,Fn as iBe,Ft as Lx,G as XB,Ht as oBe,In as la,It as D_,Jt as jbe,Kt as lBe,L as cBe,Ln as wbe,Lt as Hm,M as dBe,Mn as rv,Mt as bL,Nn as rt,Nt as fa,O as uBe,On as mBe,Ot as kbe,Pn as hBe,Pt as Ky,Q as pBe,Qt as Uee,Rn as vL,Rt as fBe,S as xBe,Sn as qT,St as zl,T as u3,Tn as gBe,Tt as Vm,Ut as bBe,V as vBe,Vt as nr,Wt as wr,X as pf,Xt as yBe,Y as yR,Yt as Kee,Z as ff,Zt as jBe,_ as dj,_n as Qee,_t as wm,a as PQ,an as Nbe,at as wBe,b as kBe,bn as NBe,bt as Ql,c as In,cn as L1,ct as t0,d as Gn,dn as jR,dt as ko,en as SBe,et as V0,fn as JN,ft as m3,g as CBe,gn as GP,gt as h3,h as DQ,hn as _Be,ht as fC,i as UT,in as Wee,it as ABe,j as db,jn as Md,jt as nm,kn as io,kt as xf,l as IBe,ln as yt,lt as O0,m as TBe,mn as Hee,mt as Jd,n as Vn,nn as RBe,nt as p3,o as We,on as EBe,ot as Mx,pn as hl,pt as Vl,q as LBe,qt as wR,r as $,rn as uI,rt as Yr,s as av,sn as MBe,st as bn,t as PBe,tn as Sbe,tt as G0,u as XN,un as kR,ut as $Q,v as yL,vn as Wx,vt as Xi,w as DBe,wn as $Be,wt as jL,x as OBe,xn as BBe,xt as FBe,y as Cbe,yn as Hx,yt as _be,z as Abe,zn as xa,zt as dr}from"./BreadcrumbContext-DLK8i_g2.js";import{S as e2,_ as tl,a as wL,b as ho,c as f3,d as Ju,f as t2,g as zBe,h as xx,i as qBe,l as UBe,m as s2,n as KBe,o as QBe,p as Xo,s as ai,t as lg,u as n2,v as sl,x as kL,y as Dl}from"./SearchableSelect-eKlsFAD7.js";import{$ as WBe,$n as Ibe,$t as HBe,A as OQ,An as Vee,Ar as r2,At as VBe,B as GBe,Bn as NR,Br as NL,Bt as YBe,C as ZBe,Cn as xk,Cr as Tbe,Ct as eF,D as tF,Dn as Rbe,Dr as x3,Dt as Ebe,E as Lbe,En as gk,Er as Mbe,Et as JBe,Fn as Gee,Fr as Pbe,Ft as uj,G as a2,Gn as XBe,Gt as i2,H as Dbe,Hn as SR,Ht as gx,In as Yee,Ir as eFe,It as mj,J as tFe,Jn as CR,Jt as sFe,K as Uj,Kn as nFe,Kt as rFe,L as $be,Ln as Obe,Lr as aFe,Lt as $_,M as iFe,Mn as oFe,Mr as Zee,Mt as Ob,N as lFe,Nn as Bbe,Nr as lm,Nt as g3,O as cFe,On as _R,Or as dFe,Ot as uFe,P as mFe,Pn as Fbe,Pr as cg,Pt as sF,Q as hFe,Qn as zbe,Qt as Jee,R as pFe,Rn as BQ,Rr as Y0,Rt as fFe,S as xFe,Sn as _x,Sr as gFe,St as nF,T as AR,Tn as O_,Tr as FQ,Tt as bFe,U as Bb,Un as IR,Ut as qbe,V as dg,Vn as Ube,Vr as pm,Vt as bk,W as rF,Wn as vFe,Wt as _c,X as yFe,Xn as Xee,Xt as vk,Y as Kbe,Yn as Qbe,Yt as jFe,Z as wFe,Zn as Wbe,Zt as kFe,_ as NFe,_n as Hbe,_r as SFe,_t as b3,a as CFe,an as _Fe,ar as Vbe,at as AFe,b as Gbe,bn as TR,br as v3,bt as Ybe,c as ete,cn as aN,cr as Zbe,ct as Jbe,d as Xbe,dr as IFe,dt as TFe,en as RFe,er as Fh,et as EFe,f as eve,fn as yk,fr as tve,ft as zQ,g as RR,gn as LFe,gr as SL,gt as Z0,h as sve,hn as nve,hr as o2,ht as MFe,i as PFe,in as qQ,ir as Qy,it as DFe,j as $Fe,jn as tte,jr as l2,jt as hj,k as OFe,kn as ER,kr as gf,kt as BFe,l as YP,ln as FFe,lr as LR,lt as ste,m as rve,mn as ave,mr as zFe,mt as Kj,n as qFe,nn as UFe,nr as Jm,nt as KFe,o as QFe,on as Ec,or as iN,ot as ive,p as B_,pn as WFe,pr as HFe,pt as ove,q as VFe,qn as lve,qt as GFe,r as Vx,rn as nte,rr as aF,rt as cve,s as YFe,sn as dve,sr as UQ,st as MR,t as KQ,tn as F_,tr as uve,tt as ZFe,u as JFe,un as XFe,ur as eze,ut as mve,v as tze,vn as hve,vr as pve,vt as sze,w as QQ,wn as fve,wr as WQ,wt as cm,x as ZP,xn as xve,xr as c2,xt as gve,y as rte,yn as bve,yr as d2,yt as nze,z as rze,zn as vve,zr as z_,zt as aze}from"./RoutineRunVariablesDialog-RFvGPey9.js";import{$ as yve,a as ize,at as oze,it as lze,o as cze,s as dze}from"./mention-chips-CWTDajKR.js";import{i as uze}from"./dist-De4zHy4P.js";import{a as mze,o as hze,r as pze,t as fze}from"./dist-BAlazNZs.js";import{a as ac,c as ic,d as On,f as Zc,i as oc,l as y3,m as Es,n as Rc,o as lc,p as Bn,r as cc,s as dc,t as uc,u as Fn}from"./alert-dialog-DHPsjJQF.js";import{a as bo,c as xze,i as iv,l as Jc,n as gze,o as vo,r as yo,s as jve,t as lr}from"./AgentAvatar-a7bfB7xg.js";import{a as _i,i as eu,n as Hn,r as Ii,t as ei}from"./checkbox-B5a5-ayj.js";import{A as wve,C as ma,D as bze,E as vze,O as yze,S as ta,T as jze,_ as ri,a as cr,b as HQ,c as Ks,d as VQ,f as sa,g as Uh,h as Nb,i as mn,k as wze,l as Gx,m as ov,n as kze,o as rn,p as us,r as Qs,s as Nze,t as Fs,u as na,v as Sze,w as Cze,x as GQ,y as YQ}from"./dialog-T8GEoNcs.js";import{n as CL,r as u2,t as $s}from"./label-D1JakEGT.js";import{g as _ze}from"./dist-CGPViZUA.js";import{a as ZQ,c as oa,d as gd,f as kve,h as Aze,i as Ize,l as ki,m as Fb,o as Tze,p as ug,r as Rze,s as Nve,t as Xc,u as fm}from"./MarkdownEditor-CNWCu03H.js";import{i as La,n as pa,r as vd,t as Li}from"./tabs-BZnu46UX.js";import{_ as oN,a as JQ,b as yd,c as Sve,d as PR,f as Cve,h as aa,i as _ve,l as Ave,p as nc,t as ro,u as Ive,v as XQ,x as rm,y as Eze}from"./StatusIcon-BjNEucdG.js";import{a as ua,c as s0,i as j3,l as rh,n as Oh,o as Bi,r as Qj,s as Ml,t as Wj,u as wl}from"./use-adapter-capabilities-3Qz_-Kk2.js";import{t as pl}from"./arrow-right-B5yVL9Ho.js";import{t as ao}from"./bot-BfjqAUbf.js";import{t as ms}from"./check-BsQi0EEa.js";import{t as an}from"./chevron-down-CxvFJ6Cw.js";import{a as Ln,i as br,n as Tve,r as Lze,t as wa}from"./clipboard-C7Ql1dcp.js";import{a as un,c as Na,d as Mze,f as lv,i as Pze,l as Sa,n as Ca,o as Dze,r as _a,s as Rve,t as eW,u as $ze}from"./select-B77a5jtu.js";import{n as Ji,t as of}from"./save-azQ0lziL.js";import{n as Ic,t as $n}from"./external-link-BzVQLoT1.js";import{i as No,n as Si,r as nl,t as tW}from"./usePrefersReducedMotion-DrOq9JVO.js";import{C as Oze,E as r0,S as zb,T as Bze,_ as Fze,a as zze,b as qze,c as Uze,d as Eve,f as Kze,g as ate,h as Qze,i as Wze,l as Hze,m as Lve,n as sW,o as Mve,p as Pve,r as Vze,s as Gze,t as An,u as Yze,v as lf,w as Zze,x as pj,y as Jze}from"./MarkdownBody-BzeXdCZ_.js";import{t as Za}from"./file-text-Bah9hFgx.js";import{a as Dve,c as $ve,d as _L,i as q_,l as tu,n as Xze,o as J0,r as a0,s as ah,t as i0,u as rc}from"./sheet-CjZsTn3Y.js";import{a as AL,i as al,n as eqe,o as Ove,r as w3,t as ea}from"./heartbeats-DLg4CQMs.js";import{n as tqe,r as st,t as ot}from"./badge-D_lRmUyU.js";import{n as k3,t as Eu}from"./useHiddenSettings-Bxwcr3Ga.js";import{t as Ai}from"./rotate-ccw-OivKhbwi.js";import{t as Mn}from"./x-BBGMK4Si.js";import{n as sqe,r as Ua,t as jr}from"./instanceSettings-Dedq1Td_.js";import"./agent-avatar-url-BETvvDkB.js";import{a as Zr,i as Ti,n as jd,o as nqe,r as rqe,t as aqe}from"./ToastContext-5j4RZIE4.js";import{t as Nt}from"./agents-B86qNZJT.js";import{t as dt}from"./input-p1LAHZWh.js";import{t as or}from"./access-BnSEFN27.js";import{t as Lu}from"./health-Bswc2x2o.js";import{t as yn}from"./skeleton-BCo4Krll.js";import{a as bf,i as N3,n as S3,r as mg,t as m2}from"./company-members-Duugb3uG.js";import{t as $i}from"./environments-D9A0D9Yc.js";import{a as iqe,i as Vc,n as oqe,o as mo,r as Xa,s as Oo,t as sn}from"./card-DR2Yz7xM.js";import{t as Wn}from"./EmptyState-QDPrmKhy.js";import{t as Ma}from"./PageSkeleton-BI65cMt2.js";r((function(){const s=document.createElement("link").relList;if(s&&s.supports&&s.supports("modulepreload"))return;for(const i of document.querySelectorAll('link[rel="modulepreload"]'))a(i);new MutationObserver(i=>{for(const o of i)if(o.type==="childList")for(const l of o.addedNodes)l.tagName==="LINK"&&l.rel==="modulepreload"&&a(l)}).observe(document,{childList:!0,subtree:!0});function n(i){const o={};return i.integrity&&(o.integrity=i.integrity),i.referrerPolicy&&(o.referrerPolicy=i.referrerPolicy),i.crossOrigin==="use-credentials"?o.credentials="include":i.crossOrigin==="anonymous"?o.credentials="omit":o.credentials="same-origin",o}r(n,"getFetchOpts");function a(i){if(i.ep)return;i.ep=!0;const o=n(i);fetch(i.href,o)}r(a,"processPreload")}),"polyfill")();var lqe=class extends ZOe{static{r(this,"InfiniteQueryObserver")}constructor(e,s){super(e,s)}bindMethods(){super.bindMethods(),this.fetchNextPage=this.fetchNextPage.bind(this),this.fetchPreviousPage=this.fetchPreviousPage.bind(this)}setOptions(e){e._type="infinite",super.setOptions(e)}getOptimisticResult(e){return e._type="infinite",super.getOptimisticResult(e)}fetchNextPage(e){return this.fetch({...e,meta:{fetchMore:{direction:"forward"}}})}fetchPreviousPage(e){return this.fetch({...e,meta:{fetchMore:{direction:"backward"}}})}createResult(e,s){const{state:n}=e,a=super.createResult(e,s),{isFetching:i,isRefetching:o,isError:l,isRefetchError:c}=a,d=n.fetchMeta?.fetchMore?.direction,u=l&&d==="forward",h=i&&d==="forward",p=l&&d==="backward",f=i&&d==="backward";return{...a,fetchNextPage:this.fetchNextPage,fetchPreviousPage:this.fetchPreviousPage,hasNextPage:GOe(s,n.data),hasPreviousPage:Q$e(s,n.data),isFetchNextPageError:u,isFetchingNextPage:h,isFetchPreviousPageError:p,isFetchingPreviousPage:f,isRefetchError:c&&!u&&!p,isRefetching:o&&!h&&!f}}};function hg(e,s){return kOe(e,lqe,s)}r(hg,"useInfiniteQuery");var cqe="adapter_auth_missing",dqe="document",uqe=80,mqe={markdown:"md",html:"html",json:"json",text:"txt"};function hqe(e){return e.normalize("NFKD").replace(/[\u0300-\u036f]/g,"").toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,uqe).replace(/-+$/g,"")||dqe}r(hqe,"documentExportSlug");function pqe(e){return mqe[(e??"").trim().toLowerCase()]??"md"}r(pqe,"documentExportExtension");function ite(e,s){const n=s.replace(/^\.+/,"").toLowerCase()||"md";return`${hqe(e)}.${n}`}r(ite,"documentExportFileName");function iF(e){const s=new Set([e.targetIssueId]);if(e.type==="create_issue"){e.draft.parentId&&s.add(e.draft.parentId);for(const n of e.draft.blockedByIssueIds??[])s.add(n)}if(e.type==="resolve_blocker")for(const n of e.removeBlockedByIssueIds)s.add(n);return[...s]}r(iF,"decisionEffectTargetIssueIds");var fqe=new Set(["terminated","pending_approval","paused"]),xqe=new Set(["active","idle","running","error"]);function gqe(e){return xqe.has(e)&&!fqe.has(e)}r(gqe,"isAgentStatusInvokable");function jS(e){return e==="done"||e==="cancelled"}r(jS,"isPipelineTerminalStageKind");function Bve(e){const s={};for(const n of e)(s[n.stageId]??=[]).push(n);return s}r(Bve,"groupWarningsByStage");function Fve(e){return e==="RESPONSIBLE_USER_UNAUTHORIZED"||e==="RESPONSIBLE_USER_UNAVAILABLE"}r(Fve,"isResponsibleUserDenialCode");function C3(e){const s=e?.trim();return s&&s.length>0?s:"the responsible user"}r(C3,"responsibleUserLabel");function oF(e,s={}){const n=C3(s.userName);return e==="RESPONSIBLE_USER_UNAVAILABLE"?{code:e,tone:"unavailable",title:"Responsible user unavailable",description:`This run acts on behalf of ${n}, but that account was removed or deactivated, so its permissions can no longer be evaluated. The agent's own permissions are not enough on their own — every action still requires an active responsible user.`,recommendedAction:"Mark the work blocked and reassign a responsible user (or reactivate the account) before the agent continues."}:{code:e,tone:"unauthorized",title:"Responsible user not authorized",description:`This action was denied because ${n} — the user this run acts on behalf of — does not have permission to perform it. The agent may be allowed, but a run can never exceed the permissions of the user it acts for, so the action is blocked.`,recommendedAction:`Grant ${n} the required permission, or have someone who is authorized take this action instead.`}}r(oF,"describeResponsibleUserDenial");var bqe=["issue_write_not_visible","issue_write_actor_class_excluded","issue_write_responsible_user_ceiling","issue_write_responsible_user_unavailable","issue_write_assignee_run_lock","cross_issue_influence_cap_exceeded","cross_issue_influence_run_context_required","issue_write_attribution_spoof_rejected"];function vqe(e){const s=e?.trim();return s&&s.length>0?s:"this task"}r(vqe,"issueLabel$2");function yqe(e){const s=e?.trim();return s&&s.length>0?s:"the current assignee"}r(yqe,"assigneeLabel");function jqe(e){const s=e?.trim();return s&&s.length>0?s:"this agent"}r(jqe,"actorLabel$1");var wqe="create a child issue with the request in its description (issue creation is a separate, open write path) and let its assignee act";function kqe(e,s={}){const n=vqe(s.issueIdentifier),a=jqe(s.actorLabel),i=yqe(s.assigneeLabel),o=C3(s.responsibleUserName);switch(e){case"issue_write_not_visible":return{code:e,status:403,tone:"boundary",boundary:"Issue visibility",title:"Task is outside this actor's visibility",description:`Issue writes are open by default, but only for tasks the actor can already read. ${n} is not visible to ${a}, so its comment, update, child, and assignment channels are all closed — the wall is visibility, not the write itself.`,whoCanAct:`${i}, and any agent or board member the task is visible to.`,sanctionedPath:`Ask the board to widen visibility for ${a}, or ${wqe}.`};case"issue_write_actor_class_excluded":return{code:e,status:403,tone:"boundary",boundary:"Actor-class boundary",title:"This actor class cannot write to tasks",description:`Default-open issue writes are a standard-trust privilege. Low-trust, skill-test, and task-bridge scopes keep their existing tight walls, so ${a} cannot write to ${n} no matter who it acts for.`,whoCanAct:"A standard-trust agent in this company, or a board member.",sanctionedPath:"Report the request upward and let a standard-trust agent make the write — actor-class scope cannot be widened per task."};case"issue_write_responsible_user_ceiling":{const l=oF("RESPONSIBLE_USER_UNAUTHORIZED",{userName:s.responsibleUserName});return{code:e,status:403,tone:"boundary",boundary:"Responsible-user ceiling",title:l.title,description:`${l.description} The write to ${n} was refused for that reason.`,whoCanAct:`${o} once authorized, or anyone already permitted to write to ${n}.`,sanctionedPath:l.recommendedAction}}case"issue_write_responsible_user_unavailable":{const l=oF("RESPONSIBLE_USER_UNAVAILABLE",{userName:s.responsibleUserName});return{code:e,status:403,tone:"boundary",boundary:"Responsible-user availability",title:l.title,description:`${l.description} The write to ${n} was refused for that reason.`,whoCanAct:`A board member, or ${a} once it has an active responsible user.`,sanctionedPath:l.recommendedAction}}case"issue_write_assignee_run_lock":return{code:e,status:409,tone:"lock",boundary:"Run checkout lock",title:"Another agent's run owns this task",description:`${i} has ${n} checked out and a run is live. Checkout and run ownership stay assignee-scoped even though writes are open, so field edits belong to the run that holds the lock until it finishes.`,whoCanAct:`${i}'s live run, or an agent holding the manage-active-checkouts permission.`,sanctionedPath:`Comment instead of patching — comments stay open and wake ${i} — or wait for the run to release the lock and retry.`};case"cross_issue_influence_cap_exceeded":{const l=s.cap??20,c=s.count??null;return{code:e,status:429,tone:"cap",boundary:`Per-run cross-issue cap of ${l} writes`,title:"This run has spent its cross-issue write budget",description:`A single heartbeat run may make at most ${l} cross-issue comments or task updates combined${c!==null?`; this was attempt ${c}`:""}. The cap bounds runaway comment sprays and loops — it is a rate backstop, not a permission decision, so ${a} is still allowed to write to ${n}.`,whoCanAct:`${a} on its next heartbeat run, or ${i} on ${n} directly.`,sanctionedPath:"Consolidate what is left into one comment on your own task, or end the run and continue on the next heartbeat — the budget resets per run."}}case"cross_issue_influence_run_context_required":return{code:e,status:403,tone:"boundary",boundary:"Heartbeat run context",title:"Cross-issue writes need a run to attribute them to",description:"Every agent comment and task update is attributed to a heartbeat run so the cross-issue cap can be counted and the audit trail can name who acted for whom. This request arrived without a valid run, so it could not be contained.",whoCanAct:`${a}, once the request carries its own run id.`,sanctionedPath:"Send the `X-Paperclip-Run-Id` header with your current run (`$PAPERCLIP_RUN_ID`) and retry."};case"issue_write_attribution_spoof_rejected":return{code:e,status:422,tone:"attribution",boundary:"Server-derived attribution",title:"Responsible user cannot be chosen by the caller",description:"`onBehalfOfUserId` is derived from the authenticated actor, never from the request body — an agent cannot pick the human whose authority it rides. The attempt was recorded in the audit log.",whoCanAct:`${a} itself: the write is allowed, only the chosen attribution is not.`,sanctionedPath:`Remove \`onBehalfOfUserId\` from the request and retry; the server fills in ${o} from your run.`}}}r(kqe,"describeIssueWriteDenial");function zve(e){return(typeof e=="string"?e:e?.name??"").trim()}r(zve,"rawNameOf");function qve(e){const s=e.toLowerCase();return!!(s.includes("://")||s==="localhost"||s.startsWith("localhost:")||/^\d{1,3}(\.\d{1,3}){3}(:\d+)?$/.test(s)||/^[a-z0-9.-]+:\d+$/.test(s))}r(qve,"looksLikeNetworkAddress");function lF(e){return e.split(/[\s._-]+/).filter(Boolean).map(s=>s.charAt(0).toUpperCase()+s.slice(1).toLowerCase()).join(" ")}r(lF,"titleCaseIdentifier");function Nqe(e){const s=/^plugin:\s*(.+)$/i.exec(e);if(!s)return null;let n=s[1].trim();return n=n.slice(n.lastIndexOf(".")+1),n=n.replace(/^plugin[-_]/i,""),lF(n)||"Custom app"}r(Nqe,"pluginPackageLabel");function vf(e,s={}){const n=s.title?.trim();if(n)return n;const a=zve(e);if(!a||qve(a))return"Custom app";const i=Nqe(a);if(i)return i;if(a.includes(":")&&!a.includes("://")){const o=a.slice(a.lastIndexOf(":")+1).trim();if(o)return lF(o)}return/\s/.test(a)||/[A-Z]/.test(a)?a:/[._-]/.test(a)?lF(a):a}r(vf,"humanizeConnectionDisplayName");function ote(e){const s=zve(e);return s&&qve(s)?`hosted at ${s}`:null}r(ote,"connectionDisplaySecondaryHint");var lte=`I want to connect an MCP (Model Context Protocol) server to Paperclip, and I need a paste-ready config.
1
+ const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/runtime-IAg0vdY9.js","assets/model-DL5biheO.js","assets/definition-g8Ojcw3n.js","assets/character-CguPM7IG.js","assets/prod-COP_vZWu.js","assets/rolldown-runtime-ZpX3ckPj.js","assets/CompanyExport-kpky2xuC.js","assets/boxes-DLOydH_J.js","assets/BreadcrumbContext-DSzhZWh7.js","assets/preload-helper-CceJXRIF.js","assets/StatusIcon-CDeLAAD6.js","assets/usePrefersReducedMotion-Bi8tEcS2.js","assets/badge-DKn90tZY.js","assets/MarkdownBody-5YQEeTHc.js","assets/mention-chips-DgHq43TZ.js","assets/agent-avatar-url-B3rF018s.js","assets/check-BwfUaND_.js","assets/clipboard-DfO4drH0.js","assets/external-link-CF7uAxuI.js","assets/agents-Be9FZXvR.js","assets/rotate-ccw-BW12Hr0F.js","assets/x-DwA5I4ik.js","assets/ToastContext-BhcEr0eG.js","assets/EmptyState-BWnCbo9i.js","assets/PageSkeleton-DazUbswA.js","assets/skeleton-CeDio6tF.js","assets/Agents.production-DbtoAoUQ.js","assets/alert-dialog-B9yc0xH5.js","assets/dist-DAe64jq9.js","assets/dist-Cbbod8tH.js","assets/dist-Bh1tkrMN.js","assets/AgentAvatar-BtQCvYNI.js","assets/tabs-LnaduMig.js","assets/dist-byHTiYvx.js","assets/bot-ByBGWg5B.js","assets/heartbeats-CtRu34PZ.js","assets/instanceSettings-6aWAmT0B.js","assets/environments-lOEya-g2.js","assets/Routines.production-CWKuR092.js","assets/SearchableSelect-BNdmZ91w.js","assets/dialog-wSBPUZbR.js","assets/RoutineRunVariablesDialog-CWOnQljf.js","assets/checkbox-DXAjlowZ.js","assets/label-BF7N7Ewo.js","assets/MarkdownEditor-B01YT6TZ.js","assets/dist-D1PYISjh.js","assets/dist-BhxPxuMy.js","assets/select-B93rxRbm.js","assets/chevron-down-n6cWCeT6.js","assets/sheet-ClwtvLVS.js","assets/useHiddenSettings-u2chU7_y.js","assets/health-RLGdw6VN.js","assets/input-BLjkJw2C.js","assets/access-CNVV-JPP.js","assets/company-members-Duugb3uG.js","assets/card-CIjSpeNG.js","assets/RoutineDetail.production-B1919-qY.js","assets/arrow-right-DKHsAC4Q.js","assets/save-BPX30Z4U.js","assets/CompanySkills.production-BuVkNosy.js","assets/use-adapter-capabilities-DVwRtrsr.js","assets/file-text-_ZIlOXhw.js","assets/CompanyActivity.production-Bx3wHHDp.js","assets/Terminal-BTETQQTg.js","assets/OrgChart.production-D-XB4GXh.js"])))=>i.map(i=>d[i]);
2
+ var e$e=Object.defineProperty;var r=(e,s)=>e$e(e,"name",{value:s,configurable:!0});import{i as hL,n as t$e,t as Fj}from"./rolldown-runtime-ZpX3ckPj.js";import{$ as QB,$i as Mv,$n as Mge,$r as Pge,$t as o3,A as qh,Aa as jee,Ai as s$e,An as n$e,Ar as r$e,At as l3,B as om,Ba as a$e,Bi as pk,Bn as wee,Br as T0,Bt as Dge,Ci as uR,Cn as i$e,Cr as NQ,Ct as Pa,D as pL,Di as $ge,Dn as o$e,Dr as Oge,Dt as l$e,Ei as WB,En as c$e,Er as HB,Et as d$e,Fi as u$e,Fn as m$e,Fr as h$e,Ft as p$e,G as W,Gi as f$e,Gn as x$e,Gr as Bge,Gt as Fge,H as kee,Ha as g$e,Hi as zge,Hn as b$e,Hr as mR,Ht as qge,Ii as hR,In as v$e,Ir as Uge,It as y$e,J as Xr,Ji as ke,Jn as Kge,Jr as j$e,Jt as w$e,K as k$e,Ki as ql,Kn as N$e,Kr as cj,Kt as S$e,L as HN,Li as C$e,Ln as Qge,Lr as _$e,M as VN,Mn as Wge,Mr as A$e,Mt as I$e,Ni as pR,Nn as T$e,Nr as R$e,O as E$e,Oi as L$e,On as M$e,Or as P$e,Ot as Nee,P as D$e,Pi as See,Pn as $$e,Pr as O$e,Pt as B$e,Q as F$e,Qn as z$e,Qr as Cee,Qt as q$e,R as zj,Ri as U$e,Rn as K$e,Rr as fk,Rt as _ee,Sa as Q$e,Si as Aee,Sn as Hge,Sr as W$e,St as D,T as vy,Ti as H$e,Tn as V$e,Tr as G$e,Tt as Iee,U as Tee,Ua as Vge,Ui as Y$e,Un as Z$e,Ur as GN,Ut as Gge,V as J$e,Va as wt,Vi as Ree,Vn as X$e,Vr as Yge,Vt as yS,W as SQ,Wa as CQ,Wi as _Q,Wn as eOe,Wr as Zge,Wt as tOe,X as Zd,Xi as Eee,Xn as Jge,Xr as Vp,Xt as Kx,Y as Xge,Yi as sOe,Yn as nOe,Yr as ebe,Yt as tbe,Z as yr,Zi as rOe,Zn as aOe,Zr as sbe,Zt as Lee,_i as iOe,_n as oOe,_r as lOe,_t as cOe,aa as tv,ai as HP,an as L_,ar as Mee,at as Qx,bi as nbe,bn as sv,br as Pee,bt as If,ca as te,ci as dOe,cn as M_,cr as FT,ct as hm,di as fL,dn as YN,dr as VB,dt as rbe,ea as uOe,ei as mOe,en as abe,er as ibe,et as Wi,fi as obe,fn as AQ,fr as hOe,ft as lbe,gi as pOe,gn as xL,gr as cbe,gt as dbe,hi as fOe,hn as ube,hr as fR,ht as fs,ia as nN,ii as xOe,in as Wm,ir as gOe,it as xR,j as mbe,ji as bOe,jn as vOe,jr as yOe,jt as rf,k as jOe,ki as IQ,kn as wOe,kr as nv,kt as af,la as kOe,li as gL,ln as Dee,lr as $ee,lt as TQ,mi as NOe,mn as SOe,mr as COe,mt as _Oe,n as qt,ni as Oee,nn as AOe,nr as IOe,nt as Km,oa as TOe,oi as ROe,on as hbe,or as EOe,ot as P_,pi as LOe,pn as Bee,pr as pbe,q as fbe,qi as nn,qn as MOe,qr as RQ,qt as POe,ra as DOe,ri as $Oe,rn as Yh,rr as OOe,rt as ka,sa as we,si as BOe,sn as EQ,sr as YC,st as ZC,t as Ac,ta as gR,ti as xbe,tn as Fee,tr as FOe,tt as zOe,ui as qOe,un as UOe,ur as GB,ut as gr,vi as KOe,vn as QOe,vr as WOe,vt as HOe,wi as VOe,wn as bR,wr as rN,wt as gbe,xa as GOe,xi as bbe,xn as YB,xr as YOe,xt as LQ,ya as ZOe,yi as ZN,yn as zT,yr as zee,yt as JOe,z as Hl,za as c3,zi as VP,zn as MQ,zr as XOe,zt as qee}from"./boxes-DLOydH_J.js";import{t as bd}from"./preload-helper-CceJXRIF.js";import{$ as H0,$t as eBe,A as tBe,An as sBe,At as qj,Bn as hi,Bt as ZB,C as nh,Cn as nBe,Ct as d3,Dn as vbe,Dt as ybe,E as rBe,En as aBe,Et as vR,F as JB,Fn as iBe,Ft as Lx,G as XB,Ht as oBe,In as la,It as D_,Jt as jbe,Kt as lBe,L as cBe,Ln as wbe,Lt as Hm,M as dBe,Mn as rv,Mt as bL,Nn as rt,Nt as fa,O as uBe,On as mBe,Ot as kbe,Pn as hBe,Pt as Ky,Q as pBe,Qt as Uee,Rn as vL,Rt as fBe,S as xBe,Sn as qT,St as zl,T as u3,Tn as gBe,Tt as Vm,Ut as bBe,V as vBe,Vt as nr,Wt as wr,X as pf,Xt as yBe,Y as yR,Yt as Kee,Z as ff,Zt as jBe,_ as dj,_n as Qee,_t as wm,a as PQ,an as Nbe,at as wBe,b as kBe,bn as NBe,bt as Ql,c as In,cn as L1,ct as t0,d as Gn,dn as jR,dt as ko,en as SBe,et as V0,fn as JN,ft as m3,g as CBe,gn as GP,gt as h3,h as DQ,hn as _Be,ht as fC,i as UT,in as Wee,it as ABe,j as db,jn as Md,jt as nm,kn as io,kt as xf,l as IBe,ln as yt,lt as O0,m as TBe,mn as Hee,mt as Jd,n as Vn,nn as RBe,nt as p3,o as We,on as EBe,ot as Mx,pn as hl,pt as Vl,q as LBe,qt as wR,r as $,rn as uI,rt as Yr,s as av,sn as MBe,st as bn,t as PBe,tn as Sbe,tt as G0,u as XN,un as kR,ut as $Q,v as yL,vn as Wx,vt as Xi,w as DBe,wn as $Be,wt as jL,x as OBe,xn as BBe,xt as FBe,y as Cbe,yn as Hx,yt as _be,z as Abe,zn as xa,zt as dr}from"./BreadcrumbContext-DSzhZWh7.js";import{S as e2,_ as tl,a as wL,b as ho,c as f3,d as Ju,f as t2,g as zBe,h as xx,i as qBe,l as UBe,m as s2,n as KBe,o as QBe,p as Xo,s as ai,t as lg,u as n2,v as sl,x as kL,y as Dl}from"./SearchableSelect-BNdmZ91w.js";import{$ as WBe,$n as Ibe,$t as HBe,A as OQ,An as Vee,Ar as r2,At as VBe,B as GBe,Bn as NR,Br as NL,Bt as YBe,C as ZBe,Cn as xk,Cr as Tbe,Ct as eF,D as tF,Dn as Rbe,Dr as x3,Dt as Ebe,E as Lbe,En as gk,Er as Mbe,Et as JBe,Fn as Gee,Fr as Pbe,Ft as uj,G as a2,Gn as XBe,Gt as i2,H as Dbe,Hn as SR,Ht as gx,In as Yee,Ir as eFe,It as mj,J as tFe,Jn as CR,Jt as sFe,K as Uj,Kn as nFe,Kt as rFe,L as $be,Ln as Obe,Lr as aFe,Lt as $_,M as iFe,Mn as oFe,Mr as Zee,Mt as Ob,N as lFe,Nn as Bbe,Nr as lm,Nt as g3,O as cFe,On as _R,Or as dFe,Ot as uFe,P as mFe,Pn as Fbe,Pr as cg,Pt as sF,Q as hFe,Qn as zbe,Qt as Jee,R as pFe,Rn as BQ,Rr as Y0,Rt as fFe,S as xFe,Sn as _x,Sr as gFe,St as nF,T as AR,Tn as O_,Tr as FQ,Tt as bFe,U as Bb,Un as IR,Ut as qbe,V as dg,Vn as Ube,Vr as pm,Vt as bk,W as rF,Wn as vFe,Wt as _c,X as yFe,Xn as Xee,Xt as vk,Y as Kbe,Yn as Qbe,Yt as jFe,Z as wFe,Zn as Wbe,Zt as kFe,_ as NFe,_n as Hbe,_r as SFe,_t as b3,a as CFe,an as _Fe,ar as Vbe,at as AFe,b as Gbe,bn as TR,br as v3,bt as Ybe,c as ete,cn as aN,cr as Zbe,ct as Jbe,d as Xbe,dr as IFe,dt as TFe,en as RFe,er as Fh,et as EFe,f as eve,fn as yk,fr as tve,ft as zQ,g as RR,gn as LFe,gr as SL,gt as Z0,h as sve,hn as nve,hr as o2,ht as MFe,i as PFe,in as qQ,ir as Qy,it as DFe,j as $Fe,jn as tte,jr as l2,jt as hj,k as OFe,kn as ER,kr as gf,kt as BFe,l as YP,ln as FFe,lr as LR,lt as ste,m as rve,mn as ave,mr as zFe,mt as Kj,n as qFe,nn as UFe,nr as Jm,nt as KFe,o as QFe,on as Ec,or as iN,ot as ive,p as B_,pn as WFe,pr as HFe,pt as ove,q as VFe,qn as lve,qt as GFe,r as Vx,rn as nte,rr as aF,rt as cve,s as YFe,sn as dve,sr as UQ,st as MR,t as KQ,tn as F_,tr as uve,tt as ZFe,u as JFe,un as XFe,ur as eze,ut as mve,v as tze,vn as hve,vr as pve,vt as sze,w as QQ,wn as fve,wr as WQ,wt as cm,x as ZP,xn as xve,xr as c2,xt as gve,y as rte,yn as bve,yr as d2,yt as nze,z as rze,zn as vve,zr as z_,zt as aze}from"./RoutineRunVariablesDialog-CWOnQljf.js";import{$ as yve,a as ize,at as oze,it as lze,o as cze,s as dze}from"./mention-chips-DgHq43TZ.js";import{i as uze}from"./dist-byHTiYvx.js";import{a as mze,o as hze,r as pze,t as fze}from"./dist-DAe64jq9.js";import{a as ac,c as ic,d as On,f as Zc,i as oc,l as y3,m as Es,n as Rc,o as lc,p as Bn,r as cc,s as dc,t as uc,u as Fn}from"./alert-dialog-B9yc0xH5.js";import{a as bo,c as xze,i as iv,l as Jc,n as gze,o as vo,r as yo,s as jve,t as lr}from"./AgentAvatar-BtQCvYNI.js";import{a as _i,i as eu,n as Hn,r as Ii,t as ei}from"./checkbox-DXAjlowZ.js";import{A as wve,C as ma,D as bze,E as vze,O as yze,S as ta,T as jze,_ as ri,a as cr,b as HQ,c as Ks,d as VQ,f as sa,g as Uh,h as Nb,i as mn,k as wze,l as Gx,m as ov,n as kze,o as rn,p as us,r as Qs,s as Nze,t as Fs,u as na,v as Sze,w as Cze,x as GQ,y as YQ}from"./dialog-wSBPUZbR.js";import{n as CL,r as u2,t as $s}from"./label-BF7N7Ewo.js";import{g as _ze}from"./dist-D1PYISjh.js";import{a as ZQ,c as oa,d as gd,f as kve,h as Aze,i as Ize,l as ki,m as Fb,o as Tze,p as ug,r as Rze,s as Nve,t as Xc,u as fm}from"./MarkdownEditor-B01YT6TZ.js";import{i as La,n as pa,r as vd,t as Li}from"./tabs-LnaduMig.js";import{_ as oN,a as JQ,b as yd,c as Sve,d as PR,f as Cve,h as aa,i as _ve,l as Ave,p as nc,t as ro,u as Ive,v as XQ,x as rm,y as Eze}from"./StatusIcon-CDeLAAD6.js";import{a as ua,c as s0,i as j3,l as rh,n as Oh,o as Bi,r as Qj,s as Ml,t as Wj,u as wl}from"./use-adapter-capabilities-DVwRtrsr.js";import{t as pl}from"./arrow-right-DKHsAC4Q.js";import{t as ao}from"./bot-ByBGWg5B.js";import{t as ms}from"./check-BwfUaND_.js";import{t as an}from"./chevron-down-n6cWCeT6.js";import{a as Ln,i as br,n as Tve,r as Lze,t as wa}from"./clipboard-DfO4drH0.js";import{a as un,c as Na,d as Mze,f as lv,i as Pze,l as Sa,n as Ca,o as Dze,r as _a,s as Rve,t as eW,u as $ze}from"./select-B93rxRbm.js";import{n as Ji,t as of}from"./save-BPX30Z4U.js";import{n as Ic,t as $n}from"./external-link-CF7uAxuI.js";import{i as No,n as Si,r as nl,t as tW}from"./usePrefersReducedMotion-Bi8tEcS2.js";import{C as Oze,E as r0,S as zb,T as Bze,_ as Fze,a as zze,b as qze,c as Uze,d as Eve,f as Kze,g as ate,h as Qze,i as Wze,l as Hze,m as Lve,n as sW,o as Mve,p as Pve,r as Vze,s as Gze,t as An,u as Yze,v as lf,w as Zze,x as pj,y as Jze}from"./MarkdownBody-5YQEeTHc.js";import{t as Za}from"./file-text-_ZIlOXhw.js";import{a as Dve,c as $ve,d as _L,i as q_,l as tu,n as Xze,o as J0,r as a0,s as ah,t as i0,u as rc}from"./sheet-ClwtvLVS.js";import{a as AL,i as al,n as eqe,o as Ove,r as w3,t as ea}from"./heartbeats-CtRu34PZ.js";import{n as tqe,r as st,t as ot}from"./badge-DKn90tZY.js";import{n as k3,t as Eu}from"./useHiddenSettings-u2chU7_y.js";import{t as Ai}from"./rotate-ccw-BW12Hr0F.js";import{t as Mn}from"./x-DwA5I4ik.js";import{n as sqe,r as Ua,t as jr}from"./instanceSettings-6aWAmT0B.js";import"./agent-avatar-url-B3rF018s.js";import{a as Zr,i as Ti,n as jd,o as nqe,r as rqe,t as aqe}from"./ToastContext-BhcEr0eG.js";import{t as Nt}from"./agents-Be9FZXvR.js";import{t as dt}from"./input-BLjkJw2C.js";import{t as or}from"./access-CNVV-JPP.js";import{t as Lu}from"./health-RLGdw6VN.js";import{t as yn}from"./skeleton-CeDio6tF.js";import{a as bf,i as N3,n as S3,r as mg,t as m2}from"./company-members-Duugb3uG.js";import{t as $i}from"./environments-lOEya-g2.js";import{a as iqe,i as Vc,n as oqe,o as mo,r as Xa,s as Oo,t as sn}from"./card-CIjSpeNG.js";import{t as Wn}from"./EmptyState-BWnCbo9i.js";import{t as Ma}from"./PageSkeleton-DazUbswA.js";r((function(){const s=document.createElement("link").relList;if(s&&s.supports&&s.supports("modulepreload"))return;for(const i of document.querySelectorAll('link[rel="modulepreload"]'))a(i);new MutationObserver(i=>{for(const o of i)if(o.type==="childList")for(const l of o.addedNodes)l.tagName==="LINK"&&l.rel==="modulepreload"&&a(l)}).observe(document,{childList:!0,subtree:!0});function n(i){const o={};return i.integrity&&(o.integrity=i.integrity),i.referrerPolicy&&(o.referrerPolicy=i.referrerPolicy),i.crossOrigin==="use-credentials"?o.credentials="include":i.crossOrigin==="anonymous"?o.credentials="omit":o.credentials="same-origin",o}r(n,"getFetchOpts");function a(i){if(i.ep)return;i.ep=!0;const o=n(i);fetch(i.href,o)}r(a,"processPreload")}),"polyfill")();var lqe=class extends ZOe{static{r(this,"InfiniteQueryObserver")}constructor(e,s){super(e,s)}bindMethods(){super.bindMethods(),this.fetchNextPage=this.fetchNextPage.bind(this),this.fetchPreviousPage=this.fetchPreviousPage.bind(this)}setOptions(e){e._type="infinite",super.setOptions(e)}getOptimisticResult(e){return e._type="infinite",super.getOptimisticResult(e)}fetchNextPage(e){return this.fetch({...e,meta:{fetchMore:{direction:"forward"}}})}fetchPreviousPage(e){return this.fetch({...e,meta:{fetchMore:{direction:"backward"}}})}createResult(e,s){const{state:n}=e,a=super.createResult(e,s),{isFetching:i,isRefetching:o,isError:l,isRefetchError:c}=a,d=n.fetchMeta?.fetchMore?.direction,u=l&&d==="forward",h=i&&d==="forward",p=l&&d==="backward",f=i&&d==="backward";return{...a,fetchNextPage:this.fetchNextPage,fetchPreviousPage:this.fetchPreviousPage,hasNextPage:GOe(s,n.data),hasPreviousPage:Q$e(s,n.data),isFetchNextPageError:u,isFetchingNextPage:h,isFetchPreviousPageError:p,isFetchingPreviousPage:f,isRefetchError:c&&!u&&!p,isRefetching:o&&!h&&!f}}};function hg(e,s){return kOe(e,lqe,s)}r(hg,"useInfiniteQuery");var cqe="adapter_auth_missing",dqe="document",uqe=80,mqe={markdown:"md",html:"html",json:"json",text:"txt"};function hqe(e){return e.normalize("NFKD").replace(/[\u0300-\u036f]/g,"").toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,uqe).replace(/-+$/g,"")||dqe}r(hqe,"documentExportSlug");function pqe(e){return mqe[(e??"").trim().toLowerCase()]??"md"}r(pqe,"documentExportExtension");function ite(e,s){const n=s.replace(/^\.+/,"").toLowerCase()||"md";return`${hqe(e)}.${n}`}r(ite,"documentExportFileName");function iF(e){const s=new Set([e.targetIssueId]);if(e.type==="create_issue"){e.draft.parentId&&s.add(e.draft.parentId);for(const n of e.draft.blockedByIssueIds??[])s.add(n)}if(e.type==="resolve_blocker")for(const n of e.removeBlockedByIssueIds)s.add(n);return[...s]}r(iF,"decisionEffectTargetIssueIds");var fqe=new Set(["terminated","pending_approval","paused"]),xqe=new Set(["active","idle","running","error"]);function gqe(e){return xqe.has(e)&&!fqe.has(e)}r(gqe,"isAgentStatusInvokable");function jS(e){return e==="done"||e==="cancelled"}r(jS,"isPipelineTerminalStageKind");function Bve(e){const s={};for(const n of e)(s[n.stageId]??=[]).push(n);return s}r(Bve,"groupWarningsByStage");function Fve(e){return e==="RESPONSIBLE_USER_UNAUTHORIZED"||e==="RESPONSIBLE_USER_UNAVAILABLE"}r(Fve,"isResponsibleUserDenialCode");function C3(e){const s=e?.trim();return s&&s.length>0?s:"the responsible user"}r(C3,"responsibleUserLabel");function oF(e,s={}){const n=C3(s.userName);return e==="RESPONSIBLE_USER_UNAVAILABLE"?{code:e,tone:"unavailable",title:"Responsible user unavailable",description:`This run acts on behalf of ${n}, but that account was removed or deactivated, so its permissions can no longer be evaluated. The agent's own permissions are not enough on their own — every action still requires an active responsible user.`,recommendedAction:"Mark the work blocked and reassign a responsible user (or reactivate the account) before the agent continues."}:{code:e,tone:"unauthorized",title:"Responsible user not authorized",description:`This action was denied because ${n} — the user this run acts on behalf of — does not have permission to perform it. The agent may be allowed, but a run can never exceed the permissions of the user it acts for, so the action is blocked.`,recommendedAction:`Grant ${n} the required permission, or have someone who is authorized take this action instead.`}}r(oF,"describeResponsibleUserDenial");var bqe=["issue_write_not_visible","issue_write_actor_class_excluded","issue_write_responsible_user_ceiling","issue_write_responsible_user_unavailable","issue_write_assignee_run_lock","cross_issue_influence_cap_exceeded","cross_issue_influence_run_context_required","issue_write_attribution_spoof_rejected"];function vqe(e){const s=e?.trim();return s&&s.length>0?s:"this task"}r(vqe,"issueLabel$2");function yqe(e){const s=e?.trim();return s&&s.length>0?s:"the current assignee"}r(yqe,"assigneeLabel");function jqe(e){const s=e?.trim();return s&&s.length>0?s:"this agent"}r(jqe,"actorLabel$1");var wqe="create a child issue with the request in its description (issue creation is a separate, open write path) and let its assignee act";function kqe(e,s={}){const n=vqe(s.issueIdentifier),a=jqe(s.actorLabel),i=yqe(s.assigneeLabel),o=C3(s.responsibleUserName);switch(e){case"issue_write_not_visible":return{code:e,status:403,tone:"boundary",boundary:"Issue visibility",title:"Task is outside this actor's visibility",description:`Issue writes are open by default, but only for tasks the actor can already read. ${n} is not visible to ${a}, so its comment, update, child, and assignment channels are all closed — the wall is visibility, not the write itself.`,whoCanAct:`${i}, and any agent or board member the task is visible to.`,sanctionedPath:`Ask the board to widen visibility for ${a}, or ${wqe}.`};case"issue_write_actor_class_excluded":return{code:e,status:403,tone:"boundary",boundary:"Actor-class boundary",title:"This actor class cannot write to tasks",description:`Default-open issue writes are a standard-trust privilege. Low-trust, skill-test, and task-bridge scopes keep their existing tight walls, so ${a} cannot write to ${n} no matter who it acts for.`,whoCanAct:"A standard-trust agent in this company, or a board member.",sanctionedPath:"Report the request upward and let a standard-trust agent make the write — actor-class scope cannot be widened per task."};case"issue_write_responsible_user_ceiling":{const l=oF("RESPONSIBLE_USER_UNAUTHORIZED",{userName:s.responsibleUserName});return{code:e,status:403,tone:"boundary",boundary:"Responsible-user ceiling",title:l.title,description:`${l.description} The write to ${n} was refused for that reason.`,whoCanAct:`${o} once authorized, or anyone already permitted to write to ${n}.`,sanctionedPath:l.recommendedAction}}case"issue_write_responsible_user_unavailable":{const l=oF("RESPONSIBLE_USER_UNAVAILABLE",{userName:s.responsibleUserName});return{code:e,status:403,tone:"boundary",boundary:"Responsible-user availability",title:l.title,description:`${l.description} The write to ${n} was refused for that reason.`,whoCanAct:`A board member, or ${a} once it has an active responsible user.`,sanctionedPath:l.recommendedAction}}case"issue_write_assignee_run_lock":return{code:e,status:409,tone:"lock",boundary:"Run checkout lock",title:"Another agent's run owns this task",description:`${i} has ${n} checked out and a run is live. Checkout and run ownership stay assignee-scoped even though writes are open, so field edits belong to the run that holds the lock until it finishes.`,whoCanAct:`${i}'s live run, or an agent holding the manage-active-checkouts permission.`,sanctionedPath:`Comment instead of patching — comments stay open and wake ${i} — or wait for the run to release the lock and retry.`};case"cross_issue_influence_cap_exceeded":{const l=s.cap??20,c=s.count??null;return{code:e,status:429,tone:"cap",boundary:`Per-run cross-issue cap of ${l} writes`,title:"This run has spent its cross-issue write budget",description:`A single heartbeat run may make at most ${l} cross-issue comments or task updates combined${c!==null?`; this was attempt ${c}`:""}. The cap bounds runaway comment sprays and loops — it is a rate backstop, not a permission decision, so ${a} is still allowed to write to ${n}.`,whoCanAct:`${a} on its next heartbeat run, or ${i} on ${n} directly.`,sanctionedPath:"Consolidate what is left into one comment on your own task, or end the run and continue on the next heartbeat — the budget resets per run."}}case"cross_issue_influence_run_context_required":return{code:e,status:403,tone:"boundary",boundary:"Heartbeat run context",title:"Cross-issue writes need a run to attribute them to",description:"Every agent comment and task update is attributed to a heartbeat run so the cross-issue cap can be counted and the audit trail can name who acted for whom. This request arrived without a valid run, so it could not be contained.",whoCanAct:`${a}, once the request carries its own run id.`,sanctionedPath:"Send the `X-Paperclip-Run-Id` header with your current run (`$PAPERCLIP_RUN_ID`) and retry."};case"issue_write_attribution_spoof_rejected":return{code:e,status:422,tone:"attribution",boundary:"Server-derived attribution",title:"Responsible user cannot be chosen by the caller",description:"`onBehalfOfUserId` is derived from the authenticated actor, never from the request body — an agent cannot pick the human whose authority it rides. The attempt was recorded in the audit log.",whoCanAct:`${a} itself: the write is allowed, only the chosen attribution is not.`,sanctionedPath:`Remove \`onBehalfOfUserId\` from the request and retry; the server fills in ${o} from your run.`}}}r(kqe,"describeIssueWriteDenial");function zve(e){return(typeof e=="string"?e:e?.name??"").trim()}r(zve,"rawNameOf");function qve(e){const s=e.toLowerCase();return!!(s.includes("://")||s==="localhost"||s.startsWith("localhost:")||/^\d{1,3}(\.\d{1,3}){3}(:\d+)?$/.test(s)||/^[a-z0-9.-]+:\d+$/.test(s))}r(qve,"looksLikeNetworkAddress");function lF(e){return e.split(/[\s._-]+/).filter(Boolean).map(s=>s.charAt(0).toUpperCase()+s.slice(1).toLowerCase()).join(" ")}r(lF,"titleCaseIdentifier");function Nqe(e){const s=/^plugin:\s*(.+)$/i.exec(e);if(!s)return null;let n=s[1].trim();return n=n.slice(n.lastIndexOf(".")+1),n=n.replace(/^plugin[-_]/i,""),lF(n)||"Custom app"}r(Nqe,"pluginPackageLabel");function vf(e,s={}){const n=s.title?.trim();if(n)return n;const a=zve(e);if(!a||qve(a))return"Custom app";const i=Nqe(a);if(i)return i;if(a.includes(":")&&!a.includes("://")){const o=a.slice(a.lastIndexOf(":")+1).trim();if(o)return lF(o)}return/\s/.test(a)||/[A-Z]/.test(a)?a:/[._-]/.test(a)?lF(a):a}r(vf,"humanizeConnectionDisplayName");function ote(e){const s=zve(e);return s&&qve(s)?`hosted at ${s}`:null}r(ote,"connectionDisplaySecondaryHint");var lte=`I want to connect an MCP (Model Context Protocol) server to Paperclip, and I need a paste-ready config.
3
3
 
4
4
  Target server: <name the server, or ask me if I have not said>
5
5
 
@@ -327,7 +327,7 @@ self.onmessage = function (e) {
327
327
  }
328
328
 
329
329
  };
330
- `;function gdt(){const e=new Blob([xdt],{type:"application/javascript"}),s=URL.createObjectURL(e);try{return new Worker(s)}finally{URL.revokeObjectURL(s)}}r(gdt,"createSandboxedWorker");var Sz=new Map,NE=new Map,c6=new Set,d6=new Map,j_e=null;function bdt(e){j_e=e}r(bdt,"setDynamicParserResultNotifier");function w_e(e,s){e.worker.postMessage(s)}r(w_e,"sendToWorker");function vdt(e){return e.nextId++}r(vdt,"nextRequestId");function ydt(e,s){return`${s}\0${e}`}r(ydt,"lineCacheKey");function jdt(){j_e?.()}r(jdt,"notifyResultReady");function wdt(e,s,n){return new Promise(a=>{const i=vdt(e);e.pendingResolves.set(i,a),w_e(e,{type:"parse",id:i,line:s,ts:n})})}r(wdt,"parseLineAsync");function NC(e){for(const s of e.pendingResolves.values())s([]);e.pendingResolves.clear()}r(NC,"drainPendingRequests");function kdt(e){return new Promise((s,n)=>{const a=gdt(),i={worker:a,ready:!1,nextId:1,pendingResolves:new Map},o=setTimeout(()=>{NC(i),a.terminate(),n(new Error("Parser worker init timed out"))},5e3);a.onmessage=l=>{const c=l.data;if(c.type==="ready"){clearTimeout(o),i.ready=!0,a.onmessage=d=>{const u=d.data;if(u.type==="result"){const h=i.pendingResolves.get(u.id);h&&(i.pendingResolves.delete(u.id),h(u.entries))}else u.type==="error"&&NC(i)},s(i);return}if(c.type==="error"){clearTimeout(o),NC(i),a.terminate(),n(new Error(c.message));return}},a.onerror=l=>{clearTimeout(o),NC(i),a.terminate(),n(new Error(`Worker error: ${l.message}`))},w_e(i,{type:"init",source:e})})}r(kdt,"initSandboxedWorker");function Ndt(e){const s=new Map,n=new Set;return{parseStdoutLine:r((i,o)=>{const l=ydt(i,o),c=s.get(l);return c?c.slice():(n.has(l)||(n.add(l),wdt(e,i,o).then(d=>{n.delete(l),s.set(l,d),jdt()})),[])},"parseStdoutLine")}}r(Ndt,"buildParserModule");async function Cz(e){const s=NE.get(e);if(s)return s;if(c6.has(e))return null;const n=d6.get(e);if(n)return n;const a=(async()=>{try{const i=await fetch(`/api/adapters/${encodeURIComponent(e)}/ui-parser.js`);if(!i.ok)return c6.add(e),null;const o=await kdt(await i.text());Sz.set(e,o);const l=Ndt(o);return NE.set(e,l),l}catch{return c6.add(e),null}finally{d6.delete(e)}})();return d6.set(e,a),a}r(Cz,"loadDynamicParser");function _z(e){const s=NE.has(e);NE.delete(e),c6.delete(e),d6.delete(e);const n=Sz.get(e);return n&&(NC(n),n.worker.terminate(),Sz.delete(e)),s}r(_z,"invalidateDynamicParser");var u6=[],jM=new Map,Az=new Set,k_e=new Map,J9=new Set,AI=new Map,Iz=new Set;function N_e(e){return Iz.add(e),()=>Iz.delete(e)}r(N_e,"onAdapterChange");function S_e(){for(const e of Iz)e()}r(S_e,"notifyAdapterChange");bdt(S_e);function Sdt(){for(const e of[iot,wot,qot,Vot,glt,Tlt,qlt,Zlt,lct,bct,qct,Pct,olt,rdt,kE,fdt])Az.add(e.type),k_e.set(e.type,e),wy(e)}r(Sdt,"registerBuiltInUIAdapters");function wy(e){const s=u6.findIndex(n=>n.type===e.type);s>=0?u6.splice(s,1,e):u6.push(e),jM.set(e.type,e),S_e()}r(wy,"registerUIAdapter");function C_e(e){return jM.get(e)??null}r(C_e,"findUIAdapter");Sdt();function _2(e){const s=jM.get(e);if(!s){let n=!1;return{type:e,label:e,parseStdoutLine:r((a,i)=>(n||(n=!0,Cz(e).then(o=>{o&&wy({type:e,label:e,parseStdoutLine:o.parseStdoutLine,createStdoutParser:o.createStdoutParser,ConfigFields:jj,buildAdapterConfig:wj})})),kE.parseStdoutLine(a,i)),"parseStdoutLine"),ConfigFields:jj,buildAdapterConfig:wj}}return s}r(_2,"getUIAdapter");function Cdt(e){const s=new Set(e.filter(a=>!a.disabled&&!a.overrideDisabled).map(a=>a.type)),n=new Set(e.map(a=>a.type));for(const a of Az){const i=k_e.get(a);if(!i)continue;const o=n.has(a),l=s.has(a),c=J9.has(a);if(o&&l&&!c){J9.add(a);const d=(AI.get(a)??0)+1;AI.set(a,d);let u=!1;const h=i.parseStdoutLine,p=e.find(f=>f.type===a)?.label??a;wy({type:a,label:p,parseStdoutLine:r((f,x)=>(u||(u=!0,Cz(a).then(g=>{g&&AI.get(a)===d&&wy({type:a,label:p,parseStdoutLine:g.parseStdoutLine,createStdoutParser:g.createStdoutParser,ConfigFields:i.ConfigFields,buildAdapterConfig:i.buildAdapterConfig})})),h(f,x)),"parseStdoutLine"),ConfigFields:i.ConfigFields,buildAdapterConfig:i.buildAdapterConfig})}else(!o||!l)&&c&&(J9.delete(a),AI.delete(a),_z(a),wy(i))}for(const{type:a,label:i}of e){if(Az.has(a))continue;const o=jM.get(a);if(o&&o!==kE)continue;let l=!1;const c=o?.parseStdoutLine??kE.parseStdoutLine;wy({type:a,label:i,parseStdoutLine:r((d,u)=>(l||(l=!0,Cz(a).then(h=>{h&&wy({type:a,label:i,parseStdoutLine:h.parseStdoutLine,createStdoutParser:h.createStdoutParser,ConfigFields:o?.ConfigFields??jj,buildAdapterConfig:o?.buildAdapterConfig??wj})})),c(d,u)),"parseStdoutLine"),ConfigFields:o?.ConfigFields??jj,buildAdapterConfig:o?.buildAdapterConfig??wj})}}r(Cdt,"syncExternalAdapters");function gV(){return[...u6]}r(gV,"listUIAdapters");function Tz(e){if(typeof e=="function")return{parseLine:e,reset:null};if(e.createStdoutParser){const s=e.createStdoutParser();return{parseLine:s.parseLine,reset:s.reset}}return{parseLine:e.parseStdoutLine,reset:null}}r(Tz,"resolveStdoutParser");function __e(e,s){if((s.kind==="thinking"||s.kind==="assistant")&&s.delta){const n=e[e.length-1];if(n&&n.kind===s.kind&&n.delta&&n.channel===s.channel){n.text+=s.text,n.ts=s.ts;return}}e.push(s)}r(__e,"appendTranscriptEntry");function _dt(e,s){for(const n of s)__e(e,n)}r(_dt,"appendTranscriptEntries");function Adt(e,s=160){return e.length<=s?e:`${e.slice(0,s-3)}...`}r(Adt,"truncateTranscriptLine");function Idt(e){if(e instanceof Error&&e.message)return e.message;if(typeof e=="string"&&e)return e;try{return JSON.stringify(e)}catch{return String(e)}}r(Idt,"formatTranscriptParserError");function Tdt(e,s,n,a){const i=Idt(n)||"unknown parser error",o=Adt(e);return{kind:"result",ts:s,text:Um(`Chat transcript error: ${i}. Falling back for line: ${o}`,a),inputTokens:0,outputTokens:0,cachedTokens:0,costUsd:0,subtype:"transcript_parse_error",isError:!0,errors:[]}}r(Tdt,"createTranscriptParseErrorEntry");function bV(e){const{entries:s,line:n,ts:a,parseLine:i,reset:o,redactionOptions:l}=e;try{_dt(s,i(n,a).map(c=>wat(c,l)))}catch(c){o?.(),__e(s,Tdt(n,a,c,l))}}r(bV,"appendParsedTranscriptLine");function A_e(e){const{entries:s,chunks:n,from:a,parseLine:i,reset:o,redactionOptions:l}=e;let c=e.stdoutBuffer;for(let d=a;d<n.length;d+=1){const u=n[d];if(u.stream==="stderr"){s.push({kind:"stderr",ts:u.ts,text:Um(u.chunk,l)});continue}if(u.stream==="system"){s.push({kind:"system",ts:u.ts,text:Um(u.chunk,l)});continue}const h=(c+u.chunk).split(/\r?\n/);c=h.pop()??"";for(const p of h){const f=p.trim();f&&bV({entries:s,line:f,ts:u.ts,parseLine:i,reset:o,redactionOptions:l})}}return c}r(A_e,"foldTranscriptChunks");function I_e(e,s,n){const a=[],i={enabled:n?.censorUsernameInLogs??!1},{parseLine:o,reset:l}=Tz(s),c=A_e({entries:a,chunks:e,from:0,stdoutBuffer:"",parseLine:o,reset:l,redactionOptions:i}).trim();return c&&bV({entries:a,line:c,ts:e.length>0?e[e.length-1].ts:new Date().toISOString(),parseLine:o,reset:l,redactionOptions:i}),l?.(),a}r(I_e,"buildTranscript");var Bre=[];function Rdt(e,s){const n={enabled:s?.censorUsernameInLogs??!1},a=typeof e!="function"&&typeof e.createStdoutParser=="function";let i=Tz(e),o=[],l="",c=Bre,d=[];const u=r(()=>{i=Tz(e),o=[],l="",c=Bre},"restart"),h=r(f=>{if(f.length<c.length)return!1;for(let x=0;x<c.length;x+=1)if(f[x]!==c[x])return!1;return!0},"extendsFolded"),p=r(f=>{const x=l.trim();if(x&&a)return I_e(f,e,s);const g=o.slice(),v=g.length-1;return v>=0&&(g[v]={...g[v]}),x&&bV({entries:g,line:x,ts:f.length>0?f[f.length-1].ts:new Date().toISOString(),parseLine:i.parseLine,reset:i.reset,redactionOptions:n}),g},"publish");return{update(f){return f===c||(h(f)||u(),l=A_e({entries:o,chunks:f,from:c.length,stdoutBuffer:l,parseLine:i.parseLine,reset:i.reset,redactionOptions:n}),c=f,d=p(f)),d}}}r(Rdt,"createIncrementalTranscript");function Edt({agents:e,value:s,onChange:n,disabled:a=!1,excludeAgentIds:i=[],disabledEmptyLabel:o="Reports to: N/A (CEO)",chooseLabel:l="Reports to..."}){const[c,d]=(0,m.useState)(!1),u=new Set(i),h=e.filter(g=>g.status!=="terminated"&&!u.has(g.id)),p=s?e.find(g=>g.id===s):null,f=p?.status==="terminated",x=!!(s&&!p);return(0,t.jsxs)(dr,{open:c,onOpenChange:d,children:[(0,t.jsx)(wr,{asChild:!0,children:(0,t.jsx)("button",{type:"button",className:W("inline-flex max-w-full min-w-0 items-center gap-1.5 overflow-hidden rounded-md border border-border px-2 py-1 text-xs hover:bg-accent/50 transition-colors",f&&"border-amber-600/45 bg-amber-500/5",a&&"opacity-60 cursor-not-allowed"),disabled:a,children:x?(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)(gd,{className:"h-3 w-3 shrink-0 text-muted-foreground"}),(0,t.jsx)("span",{className:"min-w-0 truncate text-muted-foreground",children:"Unknown manager (stale ID)"})]}):p?(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)(lr,{agent:p,size:16,className:"h-3 w-3 shrink-0 text-muted-foreground"}),(0,t.jsx)("span",{className:W("min-w-0 truncate",f&&"text-amber-900 dark:text-amber-200"),children:`Reports to ${p.name}${f?" (terminated)":""}`})]}):(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)(gd,{className:"h-3 w-3 shrink-0 text-muted-foreground"}),(0,t.jsx)("span",{className:"min-w-0 truncate",children:a?o:l})]})})}),(0,t.jsxs)(nr,{className:"w-48 p-1",align:"start",children:[(0,t.jsx)("button",{type:"button",className:W("flex items-center gap-2 w-full px-2 py-1.5 text-xs rounded hover:bg-accent/50",s===null&&"bg-accent"),onClick:r(()=>{n(null),d(!1)},"onClick"),children:"No manager"}),f&&(0,t.jsxs)("div",{className:"flex min-w-0 items-center gap-2 overflow-hidden px-2 py-1.5 text-xs text-muted-foreground border-b border-border mb-0.5",children:[(0,t.jsx)(lr,{agent:p,size:16,className:"shrink-0 h-3 w-3"}),(0,t.jsxs)("span",{className:"min-w-0 truncate",children:["Current: ",p.name," (terminated)"]})]}),x&&(0,t.jsx)("div",{className:"px-2 py-1.5 text-xs text-muted-foreground border-b border-border mb-0.5",children:"Saved manager is missing from this organization. Choose a new manager or clear."}),h.map(g=>(0,t.jsxs)("button",{type:"button",className:W("flex items-center gap-2 w-full min-w-0 px-2 py-1.5 text-xs rounded hover:bg-accent/50 overflow-hidden",g.id===s&&"bg-accent"),onClick:r(()=>{n(g.id),d(!1)},"onClick"),children:[(0,t.jsx)(lr,{agent:g,size:16,className:"shrink-0 h-3 w-3 text-muted-foreground"}),(0,t.jsx)("span",{className:"min-w-0 truncate",children:g.name}),(0,t.jsx)("span",{className:"text-muted-foreground ml-auto shrink-0",children:GCe[g.role]??g.role})]},g.id))]})]})}r(Edt,"ReportsToPicker");var Ldt="__secret_folder__:";function Mdt(e){return!e||e==="active"?null:(0,t.jsx)(ot,{variant:"outline",className:"ml-auto text-(length:--text-nano) font-normal text-muted-foreground",children:e})}r(Mdt,"statusBadge");function T_e(e){return e.split("/").filter(s=>s.length>0)}r(T_e,"splitSecretPath$1");function m6(e){return e.join("/")}r(m6,"pathKey$1");function AS(e){return e.length>0?`/${e.join("/")}`:"/"}r(AS,"pathLabel");function Pdt(e,s){return e.length<s.length?!1:s.every((n,a)=>e[a]===n)}r(Pdt,"pathStartsWith");function Fre(e){return`${Ldt}${m6(e)}`}r(Fre,"folderValue");function Ddt(e,s,n){const a=s.length,i=new Map,o=[];for(const c of e){const d=T_e(c.name);if(Pdt(d,s)){if(d.length>a+1){const u=d.slice(0,a+1),h=m6(u);if(!i.has(h)){const p=u[u.length-1]??"/",f=AS(u);i.set(h,{key:`folder-${h||"root"}`,value:Fre(u),label:p,title:f,searchText:f,kind:"folder",folderPath:h,pathHint:f})}continue}if(d.length===a+1||a===0&&d.length===0){const u=d.at(-1)??c.name;o.push({key:`browse-${c.id}`,value:c.id,label:u,title:c.name,searchText:`${c.key} ${c.name}`,secret:c,status:c.status,kind:"secret",pathHint:c.name,disabled:c.status!=="active"&&c.id!==n})}}}const l=[];if(s.length>0){const c=s.slice(0,-1);l.push({key:`folder-up-${m6(s)}`,value:Fre(c),label:"Up one folder",title:AS(c),searchText:AS(c),kind:"back",folderPath:m6(c),pathHint:AS(c)})}return l.push(...i.values(),...o),{id:"browse-secrets",label:s.length>0?AS(s):"Browse secrets",options:l}}r(Ddt,"buildFolderGroup");function vV({secretId:e,secrets:s,recentlyUsedSecrets:n,disabled:a,onSelect:i,onCreateNew:o,triggerClassName:l,disablePortal:c}){const[d,u]=(0,m.useState)(""),h=(0,m.useMemo)(()=>s.find(y=>y.id===e)??null,[s,e]),p=!!e&&!h,f=(0,m.useMemo)(()=>d?d.split("/"):[],[d]),x=(0,m.useMemo)(()=>s.some(y=>T_e(y.name).length>1),[s]),g=(0,m.useMemo)(()=>{const y=[];p&&y.push({id:"current-missing",label:"Current",options:[{key:`missing-${e}`,value:e,label:`Missing secret (${e.slice(0,8)}…)`,title:`Missing secret (${e})`,missing:!0,disabled:!0}]});const k=(n??[]).filter(w=>w.status==="active"&&w.id!==e);return k.length>0&&y.push({id:"recently-used",label:"Recently used",options:k.map(w=>({key:`recent-${w.id}`,value:w.id,label:w.name,title:w.name,searchText:`${w.key} ${w.name}`,secret:w,status:w.status,kind:"secret"}))}),y.push({id:"all-secrets",label:k.length>0?"All secrets":void 0,options:s.map(w=>({key:`all-${w.id}`,value:w.id,label:w.name,title:w.name,searchText:`${w.key} ${w.name}`,secret:w,status:w.status,kind:"secret",disabled:w.status!=="active"&&w.id!==e}))}),y},[p,n,e,s]),v=(0,m.useCallback)((y,k)=>{if(!x||KBe(y))return k;const w=Ddt(s,f,e),N=k.filter(S=>S.id==="current-missing"||S.id==="recently-used");return w.options.length>0?[...N,w]:N},[f,x,e,s]);return(0,t.jsx)(lg,{value:e||"",groups:g,onValueChange:r((y,k)=>{if(k.folderPath!==void 0)return u(k.folderPath),!1;u(""),i(y)},"onValueChange"),deriveGroups:v,disabled:a,disablePortal:c,placeholder:"Select secret…",searchPlaceholder:"Search secrets…",emptyMessage:"No matching secrets",triggerClassName:W("h-(--sz-34px) min-h-(--sz-34px) font-mono text-sm",p&&"border-destructive text-destructive",h&&h.status!=="active"&&"border-amber-500/60",l),renderValue:r(y=>{if(!y)return(0,t.jsx)("span",{className:"text-muted-foreground",children:"Select secret…"});if(y.missing)return(0,t.jsxs)("span",{className:"flex w-full min-w-0 items-center gap-1.5 text-destructive",children:[(0,t.jsx)(Si,{className:"size-3.5 shrink-0"}),(0,t.jsx)("span",{className:"min-w-0 flex-1 truncate",children:y.label})]});const k=y.status&&y.status!=="active";return(0,t.jsxs)("span",{className:"flex w-full min-w-0 items-center gap-1.5",title:y.title,children:[(0,t.jsx)(Si,{className:W("size-3.5 shrink-0",k?"text-amber-600":"text-muted-foreground")}),(0,t.jsx)("span",{className:"min-w-0 flex-1 truncate",children:y.label}),k?(0,t.jsxs)("span",{className:"text-amber-600",children:["(",y.status,")"]}):null]})},"renderValue"),renderOption:r((y,{selected:k})=>{if(y.kind==="folder"||y.kind==="back"){const w=y.kind==="back"?dKe:Ql;return(0,t.jsxs)("span",{className:"flex min-w-0 flex-1 items-center gap-1.5",title:y.title??y.label,children:[(0,t.jsx)(w,{className:"size-3.5 shrink-0 text-muted-foreground"}),(0,t.jsxs)("span",{className:"flex min-w-0 flex-col",children:[(0,t.jsx)("span",{className:W("truncate text-sm",k&&"font-medium"),children:y.label}),y.pathHint?(0,t.jsx)("span",{className:"truncate font-mono text-(length:--text-micro) text-muted-foreground",children:y.pathHint}):null]})]})}return(0,t.jsxs)("span",{className:W("flex min-w-0 flex-1 items-center gap-1.5",y.disabled&&"opacity-60"),title:y.title??y.label,children:[(0,t.jsx)(Si,{className:"size-3.5 shrink-0 text-muted-foreground"}),(0,t.jsxs)("span",{className:"flex min-w-0 flex-col",children:[(0,t.jsx)("span",{className:W("min-w-0 truncate font-mono text-sm",k&&"font-medium"),children:y.label}),y.pathHint&&y.pathHint!==y.label?(0,t.jsx)("span",{className:"truncate font-mono text-(length:--text-micro) text-muted-foreground",children:y.pathHint}):null]}),Mdt(y.status)]})},"renderOption"),createItem:o?{render:r(y=>(0,t.jsxs)("span",{className:"flex items-center gap-1.5 text-sm",children:[(0,t.jsx)(bn,{className:"size-3.5 shrink-0"}),y.trim()?(0,t.jsxs)("span",{children:["Create secret ",(0,t.jsxs)("span",{className:"font-mono",children:["“",y.trim(),"”"]}),"…"]}):(0,t.jsx)("span",{children:"Create new secret…"})]}),"render"),onSelect:r(y=>o(y),"onSelect")}:void 0})}r(vV,"SecretPicker");var $dt=/^[a-z][a-z0-9_]*$/,zre="w-full rounded-md border border-border px-2.5 py-1.5 bg-transparent outline-none text-sm font-mono placeholder:text-muted-foreground/40 focus-visible:ring-2 focus-visible:ring-ring/40";function R_e({mode:e,initialName:s,initialValue:n,existingSecretNames:a,onCancel:i,onSubmit:o}){const[l,c]=(0,m.useState)(s),[d,u]=(0,m.useState)(n),[h,p]=(0,m.useState)(!1),[f,x]=(0,m.useState)(!1),[g,v]=(0,m.useState)(null),[y,k]=(0,m.useState)(!1),w=l.trim(),N=w?$dt.test(w)?a?.some(I=>I.toLowerCase()===w)?"A secret with this name already exists":null:"Use lowercase letters, digits and _":y?"Name is required":null,S=d.length===0&&y?"Value is required":null,C=!f&&w.length>0&&d.length>0&&!N;async function _(){if(k(!0),!!C){x(!0),v(null);try{await o(w,d)}catch(I){v(I instanceof Error?I.message:"Failed to create secret"),x(!1)}}}r(_,"handleSubmit");const R=e==="create"?"Create & bind":"Store & bind";return(0,t.jsxs)("div",{className:"w-72 space-y-3",children:[(0,t.jsxs)("div",{className:"space-y-1",children:[(0,t.jsx)(bBe,{className:"text-sm font-medium",children:e==="create"?"Create secret":"Store value as secret"}),e==="store"?(0,t.jsxs)(oBe,{className:"text-(length:--text-micro) text-muted-foreground",children:["Moves the typed value into an encrypted organization secret and binds"," ",(0,t.jsx)("span",{className:"font-mono",children:s||"this variable"})," to it."]}):null]}),(0,t.jsxs)("label",{className:"block space-y-1",children:[(0,t.jsx)("span",{className:"text-(length:--text-micro) font-medium text-muted-foreground",children:"Name"}),(0,t.jsx)("input",{className:W(zre,N&&"border-destructive focus-visible:ring-destructive/40"),value:l,autoFocus:!0,spellCheck:!1,placeholder:"secret_name","aria-label":"Secret name","aria-invalid":N?!0:void 0,onChange:r(I=>c(I.target.value),"onChange"),onBlur:r(()=>k(!0),"onBlur"),onKeyDown:r(I=>{I.key==="Enter"&&(I.preventDefault(),_())},"onKeyDown")}),N?(0,t.jsx)("span",{className:"block text-(length:--text-micro) text-destructive",children:N}):null]}),(0,t.jsxs)("label",{className:"block space-y-1",children:[(0,t.jsx)("span",{className:"text-(length:--text-micro) font-medium text-muted-foreground",children:"Value"}),(0,t.jsxs)("div",{className:"relative",children:[(0,t.jsx)("input",{className:W(zre,"pr-8",S&&"border-destructive focus-visible:ring-destructive/40"),type:h?"text":"password",value:d,readOnly:e==="store",spellCheck:!1,placeholder:e==="create"?"value":void 0,"aria-label":"Secret value","aria-invalid":S?!0:void 0,onChange:e==="create"?I=>u(I.target.value):void 0}),(0,t.jsx)("button",{type:"button",className:"absolute right-1.5 top-1/2 -translate-y-1/2 rounded p-1 text-muted-foreground hover:text-foreground","aria-label":h?"Hide value":"Show value",onClick:r(()=>p(I=>!I),"onClick"),children:h?(0,t.jsx)(ih,{className:"h-3.5 w-3.5"}):(0,t.jsx)(eu,{className:"h-3.5 w-3.5"})})]}),S?(0,t.jsx)("span",{className:"block text-(length:--text-micro) text-destructive",children:S}):null]}),g?(0,t.jsx)("p",{className:"text-(length:--text-micro) text-destructive",children:g}):null,(0,t.jsxs)("div",{className:"flex items-center justify-end gap-2 pt-0.5",children:[(0,t.jsx)($,{type:"button",variant:"ghost",size:"sm",onClick:i,disabled:f,children:"Cancel"}),(0,t.jsxs)($,{type:"button",size:"sm",onClick:r(()=>{_()},"onClick"),disabled:!C,children:[f?(0,t.jsx)(st,{className:"h-3.5 w-3.5 animate-spin"}):null,R]})]})]})}r(R_e,"SecretPopoverForm");function E_e(e){return(0,t.jsx)(R_e,{mode:"create",...e})}r(E_e,"CreateSecretPopover");function Odt(e){return(0,t.jsx)(R_e,{mode:"store",...e})}r(Odt,"ConvertToSecretPopover");var Bdt=/(api[-_]?key|access[-_]?token|auth(?:_?token)?|authorization|bearer|secret|passwd|password|credential|jwt|private[-_]?key|cookie|connectionstring)/i,Fdt=[/^sk-[A-Za-z0-9-_]{16,}$/,/^gh[pousr]_[A-Za-z0-9]{20,}$/,/^github_pat_[A-Za-z0-9_]{20,}$/,/^xox[baprs]-[A-Za-z0-9-]{10,}$/,/^AKIA[0-9A-Z]{16}$/,/^AIza[0-9A-Za-z\-_]{20,}$/,/-----BEGIN (?:[A-Z ]+ )?PRIVATE KEY-----/,/^eyJ[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+$/];function zdt(e){return e.length<24||/\s/.test(e)||!/^[A-Za-z0-9+/=_\-.]+$/.test(e)?!1:[/[a-z]/.test(e),/[A-Z]/.test(e),/[0-9]/.test(e)].filter(Boolean).length>=2}r(zdt,"looksHighEntropy");function qdt(e,s){return s?Bdt.test(e)||Fdt.some(n=>n.test(s))?!0:zdt(s):!1}r(qdt,"isSensitiveEnv");var qre=0;function Udt(){return qre+=1,`env-row-${qre}`}r(Udt,"nextRowId");function jx(e="text"){return{id:Udt(),name:"",source:e,textValue:"",secretId:"",userSecretKey:"",required:!0,version:"latest"}}r(jx,"emptyRow");function Kdt(e){return typeof e=="object"&&e!==null&&"type"in e&&e.type==="secret_ref"}r(Kdt,"isSecretRef");function Qdt(e){return typeof e=="object"&&e!==null&&"type"in e&&e.type==="plain"}r(Qdt,"isPlainObj");function Wdt(e){return typeof e=="object"&&e!==null&&"type"in e&&e.type==="user_secret_ref"}r(Wdt,"isUserSecretRef");function X9(e){return!e||typeof e!="object"?[]:Object.entries(e).map(([s,n])=>{if(typeof n=="string")return{...jx(),name:s,textValue:n};if(Kdt(n)){const a=typeof n.version=="number"?n.version:"latest";return{...jx(),name:s,source:"secret",secretId:typeof n.secretId=="string"?n.secretId:"",version:a}}if(Wdt(n)){const a=typeof n.version=="number"?n.version:"latest";return{...jx(),name:s,source:"user_secret",userSecretKey:typeof n.key=="string"?n.key:"",required:n.required!==!1,version:a}}return Qdt(n)?{...jx(),name:s,source:"text",textValue:typeof n.value=="string"?n.value:""}:{...jx(),name:s}})}r(X9,"rowsFromValue");function h6(e){const s={};for(const n of e){const a=n.name.trim();if(a)if(n.source==="secret"){if(!n.secretId)continue;s[a]={type:"secret_ref",secretId:n.secretId,version:n.version}}else if(n.source==="user_secret"){const i=n.userSecretKey.trim();if(!i)continue;s[a]={type:"user_secret_ref",key:i,version:n.version,required:n.required}}else s[a]={type:"plain",value:n.textValue}}return Object.keys(s).length>0?s:void 0}r(h6,"valueFromRows");var Ure="CLAUDE_CODE_OAUTH_TOKEN";function tk(){return h6([{...jx("user_secret"),name:"CLAUDE_CODE_OAUTH_TOKEN",userSecretKey:"CLAUDE_CODE_OAUTH_TOKEN",required:!0,version:"latest"}])??{}}r(tk,"buildFixedClaudeOAuthBinding");var Hdt=/^[A-Za-z_][A-Za-z0-9_]*$/;function Vdt(e,s,n){const a=e.trim();if(!a)return null;if(!Hdt.test(a))return{level:"error",message:"Invalid name — use letters, digits and _"};if(s.has(a))return{level:"error",message:"Duplicate name"};for(const i of n)if(i&&a.startsWith(i))return{level:"warn",message:"Reserved prefix — provided automatically and may be overridden"};return null}r(Vdt,"validateName");function Gdt(e){const s=new Map;for(const a of e){const i=a.name.trim();i&&s.set(i,(s.get(i)??0)+1)}const n=new Set;for(const[a,i]of s)i>1&&n.add(a);return n}r(Gdt,"computeDuplicateNames");function Ydt(e,s){return s===e.source?{kind:"noop"}:s==="secret"?e.textValue.trim()?{kind:"open-store",name:SE(e.name)||"secret",value:e.textValue}:{kind:"to-secret"}:{kind:"to-text",undoFrom:e.secretId?{...e}:null}}r(Ydt,"planSourceSwitch");function L_e(e,s){if(e.source!=="secret"||!e.secretId)return null;const n=s.find(a=>a.id===e.secretId);return n?n.status!=="active"?{level:"warn",kind:"disabled",message:"Runs will fail until re-enabled or rebound."}:null:{level:"error",kind:"missing",message:"This secret no longer exists — runs will fail until you rebind."}}r(L_e,"computeRowHealth");function M_e(e,s){if(e.source!=="user_secret"||!e.userSecretKey||!s?.length)return null;const n=s.find(a=>a.key===e.userSecretKey);return n?n.status!=="active"?{level:"warn",kind:"disabled",message:"Runs will fail until this user secret definition is re-enabled or rebound."}:null:{level:"error",kind:"missing",message:"This user secret definition no longer exists — runs will fail until you rebind."}}r(M_e,"computeUserSecretRowHealth");function SE(e){return e.trim().toLowerCase().replace(/[^a-z0-9_]+/g,"_").replace(/^_+|_+$/g,"").slice(0,64)}r(SE,"secretNameFromKey");function c_(e){return e.trim().toUpperCase().replace(/[^A-Z0-9_]+/g,"_").replace(/^_+|_+$/g,"").slice(0,64)}r(c_,"envKeyFromSecretName");var Zdt="w-full rounded-md border border-border px-2.5 py-1.5 bg-transparent outline-none text-sm font-mono placeholder:text-muted-foreground/40 focus-visible:ring-2 focus-visible:ring-ring/40",Kre="min-w-0 flex-1 bg-transparent px-2 py-1.5 text-sm font-mono outline-none placeholder:text-muted-foreground/40";function Jdt({row:e,isLast:s,secrets:n,userSecretDefinitions:a,recentlyUsedSecrets:i,disabled:o,nameIssue:l,showNameIssue:c,dirtyFields:d,onPatch:u,onRemove:h,onNameBlur:p,onNamePaste:f,onEnterInValueLast:x,onCreateSecret:g,onToast:v,focusRequest:y,onFocusConsumed:k}){const w=(0,m.useRef)(null),N=(0,m.useRef)(null),S=(0,m.useRef)(null),[C,_]=(0,m.useState)(null),[R,I]=(0,m.useState)(!1),[T,E]=(0,m.useState)(null),P=L_e(e,n)??M_e(e,a),O=e.source==="secret"?n.find(J=>J.id===e.secretId)??null:null,M=(a?.length??0)>0,Q=e.source==="text"&&!e.sensitiveDismissed&&qdt(e.name,e.textValue);(0,m.useEffect)(()=>{y&&(y==="name"?w.current?.focus():e.source==="text"?N.current?.focus():e.source==="secret"?S.current?.querySelector("[role=combobox]")?.focus():S.current?.querySelector("select,input")?.focus(),k())},[y,k,e.source]),(0,m.useEffect)(()=>{if(!T)return;const J=window.setTimeout(()=>E(null),5e3);return()=>window.clearTimeout(J)},[T]);function L(J){if(J==="user_secret"){if(e.source==="user_secret")return;u({source:"user_secret",secretId:"",version:"latest"}),window.setTimeout(()=>S.current?.querySelector("select,input")?.focus(),0);return}const ae=Ydt(e,J);switch(ae.kind){case"noop":return;case"open-store":{const{name:oe,value:G}=ae;window.setTimeout(()=>_({mode:"store",name:oe,value:G}),0);return}case"to-secret":u({source:"secret",userSecretKey:"",required:!0}),window.setTimeout(()=>{S.current?.querySelector("[role=combobox]")?.focus()},0);return;case"to-text":ae.undoFrom&&E(ae.undoFrom),u({source:"text",secretId:"",userSecretKey:"",required:!0,version:"latest"}),window.setTimeout(()=>N.current?.focus(),0);return}}r(L,"switchSource");async function F(J,ae){const oe=await g(J,ae);u({source:"secret",secretId:oe.id,userSecretKey:"",required:!0,version:"latest",textValue:""}),v(`Secret ${oe.name} created`),_(null)}r(F,"submitSecretPopover");function q(){const J=SE(e.name)||"secret",{textValue:ae}=e;window.setTimeout(()=>_({mode:"store",name:J,value:ae}),0)}r(q,"openStoreAsSecret");const z=e.source==="text"?"Text value":e.source==="secret"?"Organization secret reference":"User secret reference",K=`${e.id}-name-error`,U=`${e.id}-health`,V=d.name||d.value,ne=O?Math.max(0,O.latestVersion):0,Z=e.version==="latest"?"latest":`v${e.version}`,ie=e.version!=="latest";return(0,t.jsxs)("div",{className:W("group/row grid grid-cols-(--gtc-13) items-start gap-x-1.5 gap-y-1 rounded-md px-1 py-1","@[40rem]/env:grid-cols-(--gtc-14) @[40rem]/env:items-center",V&&"bg-amber-500/[0.06] ring-1 ring-amber-500/20"),children:[(0,t.jsx)("div",{className:"col-start-1 row-start-1 min-w-0 @[40rem]/env:row-start-1 @[40rem]/env:self-start",children:(0,t.jsx)("input",{ref:w,className:W(Zdt,d.name&&"border-amber-500/70 bg-amber-500/10 focus-visible:ring-amber-500/40",c&&l?.level==="error"&&"border-destructive focus-visible:ring-destructive/40",c&&l?.level==="warn"&&"border-amber-500 focus-visible:ring-amber-500/40"),placeholder:"KEY",value:e.name,spellCheck:!1,disabled:o,"aria-label":"Variable name","aria-invalid":c&&l?.level==="error"?!0:void 0,"aria-describedby":c&&l?K:void 0,onChange:r(J=>u({name:J.target.value}),"onChange"),onBlur:p,onPaste:r(J=>{e.name||f(J.clipboardData.getData("text"))&&J.preventDefault()},"onPaste"),onKeyDown:r(J=>{J.key==="Enter"&&(J.preventDefault(),e.source==="text"?N.current?.focus():S.current?.querySelector("[role=combobox],select,input")?.focus())},"onKeyDown")})}),(0,t.jsxs)("div",{className:"col-span-2 col-start-1 row-start-2 min-w-0 @[40rem]/env:col-span-1 @[40rem]/env:col-start-2 @[40rem]/env:row-start-1",children:[(0,t.jsxs)(dr,{open:C!==null,onOpenChange:r(J=>{J||_(null)},"onOpenChange"),children:[(0,t.jsx)(ZB,{asChild:!0,children:(0,t.jsxs)("div",{ref:S,className:W("relative flex items-stretch overflow-hidden rounded-md border border-border bg-transparent focus-within:ring-2 focus-within:ring-ring/40",d.value&&"border-amber-500/70 bg-amber-500/10 focus-within:ring-amber-500/40",o&&"opacity-60"),children:[(0,t.jsxs)(na,{children:[(0,t.jsxs)(Fn,{children:[(0,t.jsx)(Bn,{asChild:!0,children:(0,t.jsx)(ta,{asChild:!0,disabled:o,children:(0,t.jsxs)("button",{type:"button","aria-label":"Value source",className:"flex shrink-0 items-center gap-0.5 border-r border-border px-2 text-muted-foreground hover:bg-accent/50 disabled:pointer-events-none",children:[e.source==="text"?(0,t.jsx)(VKe,{className:"size-3.5"}):e.source==="secret"?(0,t.jsx)(Si,{className:"size-3.5"}):(0,t.jsx)(oh,{className:"size-3.5"}),(0,t.jsx)(an,{className:"size-3 opacity-60"})]})})}),(0,t.jsx)(On,{side:"top",children:z})]}),(0,t.jsxs)(sa,{align:"start",className:"w-56",children:[(0,t.jsxs)(us,{className:"flex-col items-start gap-0.5",onSelect:r(()=>L("text"),"onSelect"),children:[(0,t.jsx)("span",{className:"text-sm",children:"Text value"}),(0,t.jsx)("span",{className:"text-(length:--text-micro) text-muted-foreground",children:"Store the value inline as plain text."})]}),(0,t.jsxs)(us,{className:"flex-col items-start gap-0.5",onSelect:r(()=>L("secret"),"onSelect"),children:[(0,t.jsx)("span",{className:"text-sm",children:"Organization secret"}),(0,t.jsx)("span",{className:"text-(length:--text-micro) text-muted-foreground",children:"Resolve a stored organization secret at run start."})]}),(0,t.jsxs)(us,{className:"flex-col items-start gap-0.5",onSelect:r(()=>L("user_secret"),"onSelect"),children:[(0,t.jsx)("span",{className:"text-sm",children:"User secret"}),(0,t.jsx)("span",{className:"text-(length:--text-micro) text-muted-foreground",children:"Resolve the responsible user's own value at run start."})]})]})]}),e.source==="text"?(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)("input",{ref:N,className:Kre,placeholder:"value",value:e.textValue,type:Q?"password":"text",spellCheck:!1,disabled:o,"aria-label":"Variable value",onChange:r(J=>u({textValue:J.target.value}),"onChange"),onKeyDown:r(J=>{J.key==="Enter"&&s&&(J.preventDefault(),x())},"onKeyDown")}),Q?(0,t.jsxs)("div",{className:"flex shrink-0 items-stretch border-l border-border",children:[(0,t.jsxs)("button",{type:"button",onClick:q,disabled:o,className:"flex items-center gap-1 px-2 text-(length:--text-micro) text-amber-700 hover:bg-amber-500/10 dark:text-amber-400",title:"This value looks sensitive — store it as a secret",children:[(0,t.jsx)(Tc,{className:"size-3.5"}),(0,t.jsx)("span",{className:"hidden @[30rem]/env:inline",children:"Store as secret"})]}),(0,t.jsx)("button",{type:"button",onClick:r(()=>u({sensitiveDismissed:!0}),"onClick"),disabled:o,"aria-label":"Dismiss sensitive-value suggestion",title:"Dismiss — keep this value as plain text",className:"flex items-center px-1.5 text-amber-700/60 hover:bg-amber-500/10 hover:text-amber-700 dark:text-amber-400/60 dark:hover:text-amber-400",children:(0,t.jsx)(Mn,{className:"size-3"})})]}):null]}):e.source==="secret"?(0,t.jsxs)("div",{className:"relative min-w-0 flex-1",children:[(0,t.jsx)(vV,{secretId:e.secretId,secrets:n,recentlyUsedSecrets:i,disabled:o,onSelect:r(J=>u({secretId:J,version:"latest"}),"onSelect"),onCreateNew:r(J=>_({mode:"create",name:SE(J)||J.trim(),value:""}),"onCreateNew"),triggerClassName:W("rounded-none border-0 bg-transparent shadow-none focus-visible:ring-0",O&&O.status==="active"&&"pr-24 has-[>svg]:!pr-24")}),O&&O.status==="active"?(0,t.jsxs)(dr,{open:R,onOpenChange:I,children:[(0,t.jsx)(ZB,{asChild:!0,children:(0,t.jsx)("button",{type:"button",disabled:o,onClick:r(J=>{J.preventDefault(),J.stopPropagation(),I(ae=>!ae)},"onClick"),"aria-label":"Version",className:W("absolute right-8 top-1/2 z-10 -translate-y-1/2 rounded px-1.5 py-0.5 text-(length:--text-nano) font-medium",ie?"bg-amber-500/15 text-amber-700 dark:text-amber-400":"text-muted-foreground hover:bg-accent"),children:Z})}),(0,t.jsxs)(nr,{align:"end",className:"w-44 p-1",role:"radiogroup","aria-label":"Secret version",children:[(0,t.jsxs)("button",{type:"button",role:"radio","aria-checked":e.version==="latest",onClick:r(()=>{u({version:"latest"}),I(!1)},"onClick"),className:W("flex w-full items-center justify-between rounded px-2 py-1.5 text-sm hover:bg-accent",e.version==="latest"&&"font-medium"),children:["latest ",(0,t.jsx)("span",{className:"text-(length:--text-micro) text-muted-foreground",children:"(recommended)"})]}),Array.from({length:ne},(J,ae)=>ne-ae).filter(J=>J>0).map(J=>(0,t.jsxs)("button",{type:"button",role:"radio","aria-checked":e.version===J,onClick:r(()=>{u({version:J}),I(!1)},"onClick"),className:W("flex w-full items-center rounded px-2 py-1.5 text-sm hover:bg-accent",e.version===J&&"font-medium text-amber-700 dark:text-amber-400"),children:["v",J]},J))]})]}):null]}):(0,t.jsxs)("div",{className:"grid min-w-0 flex-1 grid-cols-(--gtc-13)",children:[M?(0,t.jsxs)("select",{"aria-label":"User secret",value:e.userSecretKey,disabled:o,onChange:r(J=>{const ae=J.target.value,oe=a?.find(G=>G.key===ae);u({userSecretKey:ae,...oe&&!e.name.trim()?{name:oe.key.toUpperCase()}:{}})},"onChange"),className:"min-w-0 bg-transparent px-2 py-1.5 text-sm font-mono outline-none disabled:pointer-events-none",children:[(0,t.jsx)("option",{value:"",children:"Select user secret..."}),e.userSecretKey&&!a?.some(J=>J.key===e.userSecretKey)?(0,t.jsxs)("option",{value:e.userSecretKey,children:["Unknown (",e.userSecretKey,")"]}):null,(a??[]).map(J=>(0,t.jsxs)("option",{value:J.key,children:[J.name,J.status!=="active"?` (${J.status})`:""]},J.id))]}):(0,t.jsx)("input",{className:Kre,placeholder:"user-secret key",value:e.userSecretKey,spellCheck:!1,disabled:o,"aria-label":"User secret key",onChange:r(J=>u({userSecretKey:J.target.value}),"onChange")}),(0,t.jsxs)("select",{"aria-label":"Requirement",value:e.required?"required":"optional",disabled:o,onChange:r(J=>u({required:J.target.value==="required"}),"onChange"),className:"border-l border-border bg-transparent px-2 py-1.5 text-xs font-medium text-muted-foreground outline-none disabled:pointer-events-none",children:[(0,t.jsx)("option",{value:"required",children:"Required"}),(0,t.jsx)("option",{value:"optional",children:"Optional"})]})]})]})}),(0,t.jsx)(nr,{align:"start",className:"w-auto p-3",onInteractOutside:r(J=>{const ae=J.detail.originalEvent.target;ae&&S.current?.contains(ae)&&J.preventDefault()},"onInteractOutside"),children:C?.mode==="store"?(0,t.jsx)(Odt,{initialName:C.name,initialValue:C.value,existingSecretNames:n.map(J=>J.name),onCancel:r(()=>_(null),"onCancel"),onSubmit:F}):C?.mode==="create"?(0,t.jsx)(E_e,{initialName:C.name,initialValue:C.value,existingSecretNames:n.map(J=>J.name),onCancel:r(()=>_(null),"onCancel"),onSubmit:F}):null})]}),P?(0,t.jsx)("p",{id:U,role:"status",className:W("mt-0.5 text-(length:--text-micro)",P.level==="error"?"text-destructive":"text-amber-600 dark:text-amber-400"),children:P.message}):null,T?(0,t.jsxs)("p",{className:"mt-0.5 inline-flex items-center gap-2 text-(length:--text-micro) text-muted-foreground",children:["Reverted to text —"," ",(0,t.jsx)("button",{type:"button",className:"font-medium text-foreground underline underline-offset-2 hover:text-primary",onClick:r(()=>{u({source:"secret",secretId:T.secretId,version:T.version,textValue:""}),E(null)},"onClick"),children:"Undo"})]}):null]}),c&&l?(0,t.jsx)("p",{id:K,className:W("col-span-2 col-start-1 row-start-3 min-w-0 text-(length:--text-micro) @[40rem]/env:col-span-2 @[40rem]/env:row-start-2",l.level==="error"?"text-destructive":"text-amber-600 dark:text-amber-400"),children:l.message}):null,(0,t.jsxs)("div",{className:"col-start-2 row-start-1 flex items-center justify-end gap-0.5 self-start @[40rem]/env:col-start-3 @[40rem]/env:self-center",children:[e.source==="text"&&!Q&&(e.name.trim()||e.textValue)?(0,t.jsxs)(na,{children:[(0,t.jsx)(ta,{asChild:!0,disabled:o,children:(0,t.jsx)("button",{type:"button","aria-label":"More actions",className:"rounded p-1 text-muted-foreground opacity-100 hover:bg-accent hover:text-foreground @[40rem]/env:opacity-0 @[40rem]/env:group-hover/row:opacity-100 @[40rem]/env:group-focus-within/row:opacity-100",children:(0,t.jsx)(_i,{className:"size-4"})})}),(0,t.jsx)(sa,{align:"end",children:(0,t.jsx)(us,{onSelect:r(()=>{window.setTimeout(q,0)},"onSelect"),children:"Store as secret…"})})]}):null,(0,t.jsx)("button",{type:"button",onClick:h,disabled:o,"aria-label":`Remove ${e.name.trim()||"variable"}`,className:"rounded p-1 text-muted-foreground opacity-100 hover:bg-destructive/10 hover:text-destructive @[40rem]/env:opacity-0 @[40rem]/env:group-hover/row:opacity-100 @[40rem]/env:group-focus-within/row:opacity-100",children:(0,t.jsx)(Mn,{className:"size-4"})})]})]})}r(Jdt,"EnvironmentVariableRow");var Xdt=/^\s*(?:export\s+)?([A-Za-z_][A-Za-z0-9_]*)\s*=(.*)$/;function eut(e){const s=e.indexOf(" #");return s>=0?e.slice(0,s):e}r(eut,"stripInlineComment");function tut(e){const s=e.trim();if(s.length>=2){const n=s[0],a=s[s.length-1];if(n==='"'&&a==='"'||n==="'"&&a==="'")return s.slice(1,-1)}return eut(s).trim()}r(tut,"unquote");function sut(e){const s=[];for(const n of e.split(/\r?\n/)){const a=n.trim();if(!a||a.startsWith("#"))continue;const i=Xdt.exec(a);if(!i)continue;const o=i[1],l=tut(i[2]);s.push({key:o,value:l})}return s}r(sut,"parseDotenv");var nut=["PAPERCLIP_"],rut="Set the KEY to the env var name the process expects, for example GH_TOKEN. Choose a secret to resolve a stored value at run start. PAPERCLIP_* variables are injected automatically.";function Rz(e){if(!e||typeof e!="object")return[];const s=new Map;for(const[n,a]of Object.entries(e)){const i=n.trim();if(i)if(typeof a=="string")s.set(i,{type:"plain",value:a});else if(a?.type==="secret_ref"){const o=typeof a.secretId=="string"?a.secretId:"";if(!o)continue;s.set(i,{type:"secret_ref",secretId:o,version:typeof a.version=="number"?a.version:"latest"})}else if(a?.type==="user_secret_ref"){const o=typeof a.key=="string"?a.key.trim():"";if(!o)continue;s.set(i,{type:"user_secret_ref",key:o,version:typeof a.version=="number"?a.version:"latest",required:a.required!==!1})}else a?.type==="plain"?s.set(i,{type:"plain",value:typeof a.value=="string"?a.value:""}):s.set(i,{type:"plain",value:""})}return[...s.entries()].sort(([n],[a])=>n.localeCompare(a))}r(Rz,"normalizedEnvEntries");function IS(e){return JSON.stringify(Rz(e))}r(IS,"normalizedEnvKey");var eD=3;function tD(e){const s=e.slice(0,eD).join(", ");return e.length>eD?`${s} +${e.length-eD} more`:s}r(tD,"formatChangedNames");function Qre(e){return e.map(s=>({...s}))}r(Qre,"cloneRows");function aut(e,s){return s?{name:e.name.trim()!==s.name.trim(),value:e.source!==s.source||e.textValue!==s.textValue||e.secretId!==s.secretId||e.userSecretKey!==s.userSecretKey||e.required!==s.required||e.version!==s.version}:{name:!!e.name.trim(),value:e.source!=="text"||!!e.textValue||!!e.secretId||e.version!=="latest"}}r(aut,"rowDirtyFields");var kj=(0,m.forwardRef)(r(function({value:s,onChange:n,secrets:a,userSecretDefinitions:i,onCreateSecret:o,recentlyUsedSecrets:l,disabled:c,reservedPrefixes:d=nut,footerHint:u,onDirtyChange:h,hideDraftActions:p=!1},f){const x=jd(),g=(0,m.useRef)(null),[v,y]=(0,m.useState)(()=>X9(s)),k=(0,m.useRef)(v),[w,N]=(0,m.useState)(()=>Qre(v)),S=(0,m.useMemo)(()=>IS(s),[]),C=(0,m.useRef)(S),_=(0,m.useRef)(S),R=(0,m.useRef)(null),[I,T]=(0,m.useState)(S),[E,P]=(0,m.useState)(()=>new Set(X9(s).map(de=>de.name.trim()).filter(Boolean))),[O,M]=(0,m.useState)(null);(0,m.useEffect)(()=>{k.current=v},[v]);function Q(de,xe=k.current){C.current=de,T(de),N(Qre(xe))}r(Q,"markCommitted");function L(de){P(xe=>{const le=new Set(xe);for(const Re of de){const Le=Re.name.trim();Le&&le.add(Le)}return le})}r(L,"touchCommittedNames");function F(de){const xe=X9(de);return y(xe),L(xe),xe}r(F,"adoptExternalValue"),(0,m.useEffect)(()=>{const de=IS(s);if(de===_.current)return;_.current=de;const xe=IS(h6(k.current)),le=xe!==C.current,Re=R.current===de;if(Re&&(R.current=null),!le){Q(de,F(s));return}(Re||xe===de)&&(L(k.current),Q(de))},[s]);const q=(0,m.useMemo)(()=>h6(v),[v]),z=(0,m.useMemo)(()=>IS(q),[q]),K=z!==I;(0,m.useEffect)(()=>{h?.(!c&&K)},[c,K,h]);const U=(0,m.useMemo)(()=>{const de=new Map(Rz(h6(w)).map(([Le,je])=>[Le,JSON.stringify(je)])),xe=new Map(Rz(q).map(([Le,je])=>[Le,JSON.stringify(je)])),le=[],Re=[];for(const[Le,je]of xe)de.has(Le)?de.get(Le)!==je&&Re.push(Le):le.push(Le);return{added:le,changed:Re,removed:[...de.keys()].filter(Le=>!xe.has(Le))}},[w,q]),V=(0,m.useMemo)(()=>{const de=[];return U.added.length>0&&de.push(`New: ${tD(U.added)}`),U.changed.length>0&&de.push(`Edited: ${tD(U.changed)}`),U.removed.length>0&&de.push(`Removed: ${tD(U.removed)}`),de.join(" · ")},[U]);(0,m.useEffect)(()=>{if(c||!K)return;function de(xe){xe.preventDefault(),xe.returnValue=""}return r(de,"handleBeforeUnload"),window.addEventListener("beforeunload",de),()=>window.removeEventListener("beforeunload",de)},[c,K]);const ne=(0,m.useCallback)(()=>c||!K?null:(R.current=z,(0,F0.flushSync)(()=>{n(q)}),q??{}),[c,q,z,K,n]);(0,m.useImperativeHandle)(f,()=>({flushPendingDraft:ne}),[ne]),(0,m.useEffect)(()=>{const de=g.current?.closest("form");if(!de)return;function xe(){ne()}return r(xe,"handleSubmit"),de.addEventListener("submit",xe,!0),()=>de.removeEventListener("submit",xe,!0)},[ne]),(0,m.useEffect)(()=>{const de=g.current;if(!de)return;const xe=de;function le(Re){const Le=Re.target;if(!(Le instanceof Element)||xe.contains(Le))return;const je=Le.closest("button");if(!je||je.disabled)return;const _e=`${je.getAttribute("aria-label")??""} ${je.textContent??""}`;(je.type==="submit"||/\b(save|create|update|test|import)\b/i.test(_e))&&ne()}return r(le,"handleDocumentClick"),document.addEventListener("click",le,!0),()=>document.removeEventListener("click",le,!0)},[ne]);function Z(de){y(de)}r(Z,"updateDraft");function ie(de,xe){Z(v.map(le=>le.id===de?{...le,...xe}:le))}r(ie,"patchRow");function J(de){Z(v.filter(xe=>xe.id!==de))}r(J,"removeRow");function ae(){const de=jx();y([...v,de]),M({rowId:de.id,field:"name"})}r(ae,"addRow");function oe(de){const xe=v.find(le=>le.id===de)?.name.trim();xe&&P(le=>{if(le.has(xe))return le;const Re=new Set(le);return Re.add(xe),Re})}r(oe,"markTouched");function G(de,xe){const le=sut(de);if(le.length===0)return!1;const Re=v.filter(Le=>Le.id!==xe).map(Le=>({...Le}));for(const{key:Le,value:je}of le){const _e=Re.find(Ze=>Ze.name.trim()===Le);_e?(_e.name=Le,_e.source="text",_e.textValue=je,_e.secretId="",_e.sensitiveDismissed=!1,_e.userSecretKey="",_e.required=!0):Re.push({...jx(),name:Le,textValue:je})}return Z(Re),x?.pushToast({title:`Imported ${le.length} variable${le.length===1?"":"s"}`,tone:"success"}),!0}r(G,"bulkImport");function X(de){const xe=v.map(Le=>({...Le})),le=xe[xe.length-1];let Re;le&&!le.name&&!le.textValue&&!le.secretId&&!le.userSecretKey?Re=le:(Re=jx(),xe.push(Re)),Re.source="secret",Re.secretId=de.id,Re.version="latest",Re.name||(Re.name=c_(de.name)),Z(xe)}r(X,"bindRecentSecret");function Y(){K&&(R.current=z,n(q))}r(Y,"saveDraft");function re(){R.current=null,_.current=IS(s);const de=F(s);Q(_.current,de)}r(re,"revertDraft");const se=(0,m.useMemo)(()=>Gdt(v),[v]),ce=(0,m.useMemo)(()=>v.reduce((de,xe)=>L_e(xe,a)||M_e(xe,i)?de+1:de,0),[v,a,i]),pe=(0,m.useMemo)(()=>{const de=new Set(v.filter(xe=>xe.source==="secret"&&xe.secretId).map(xe=>xe.secretId));return(l??[]).filter(xe=>xe.status==="active"&&!de.has(xe.id)).slice(0,8)},[l,v]),fe=v.length>0,ve=u===void 0?rut:u,Ie=(0,m.useMemo)(()=>new Map(w.map(de=>[de.id,de])),[w]);return(0,t.jsx)(Zc,{children:(0,t.jsxs)("div",{ref:g,className:"@container/env space-y-2",children:[ce>1?(0,t.jsxs)("p",{className:"inline-flex items-center gap-1.5 text-(length:--text-micro) font-medium text-amber-700 dark:text-amber-400",children:[(0,t.jsx)(Ji,{className:"size-3.5"}),ce," bindings need attention"]}):null,fe?(0,t.jsxs)(t.Fragment,{children:[(0,t.jsxs)("div",{className:"hidden gap-x-1.5 @[40rem]/env:grid @[40rem]/env:grid-cols-(--gtc-14)",children:[(0,t.jsx)("span",{className:"text-(length:--text-micro) font-medium uppercase tracking-wide text-muted-foreground",children:"Name"}),(0,t.jsx)("span",{className:"text-(length:--text-micro) font-medium uppercase tracking-wide text-muted-foreground",children:"Value"}),(0,t.jsx)("span",{})]}),v.map((de,xe)=>{const le=Vdt(de.name,se,d),Re=E.has(de.name.trim());return(0,t.jsx)(Jdt,{row:de,isLast:xe===v.length-1,secrets:a,userSecretDefinitions:i,recentlyUsedSecrets:l,disabled:c,nameIssue:le,showNameIssue:Re,dirtyFields:aut(de,Ie.get(de.id)),onPatch:r(Le=>ie(de.id,Le),"onPatch"),onRemove:r(()=>J(de.id),"onRemove"),onNameBlur:r(()=>oe(de.id),"onNameBlur"),onNamePaste:r(Le=>G(Le,de.id),"onNamePaste"),onEnterInValueLast:ae,onCreateSecret:o,onToast:r(Le=>x?.pushToast({title:Le,tone:"success"}),"onToast"),focusRequest:O?.rowId===de.id?O.field:null,onFocusConsumed:r(()=>M(null),"onFocusConsumed")},de.id)})]}):(0,t.jsx)("p",{className:"text-sm text-muted-foreground",children:"No environment variables"}),(0,t.jsxs)("div",{className:"flex flex-wrap items-center justify-between gap-2 pt-1",children:[(0,t.jsxs)("button",{type:"button",onClick:ae,disabled:c,className:"inline-flex items-center gap-1 rounded-md px-2 py-1 text-xs font-medium text-muted-foreground transition-colors hover:bg-accent hover:text-foreground disabled:pointer-events-none disabled:opacity-50",children:[(0,t.jsx)(bn,{className:"size-3.5"}),"Add variable"]}),pe.length>0&&!c?(0,t.jsxs)("div",{className:"flex flex-wrap items-center gap-1.5",children:[(0,t.jsxs)("span",{className:"inline-flex items-center gap-1 text-(length:--text-micro) text-muted-foreground/70",children:[(0,t.jsx)(Si,{className:"size-3"}),"Recently used:"]}),pe.map(de=>(0,t.jsxs)("button",{type:"button",onClick:r(()=>X(de),"onClick"),className:"inline-flex items-center gap-1 rounded-full border border-border px-2 py-0.5 font-mono text-(length:--text-micro) text-muted-foreground transition-colors hover:bg-accent/50 hover:text-foreground",title:`Bind ${de.name}`,children:["+ ",de.name]},de.id))]}):null]}),K&&!c&&!p?(0,t.jsxs)("div",{role:"status",className:"mt-3 flex w-full flex-col gap-3 rounded-md border border-amber-500/30 bg-amber-500/10 px-3 py-3 text-amber-950 shadow-sm dark:bg-amber-500/15 dark:text-amber-100 @[34rem]/env:flex-row @[34rem]/env:items-center @[34rem]/env:justify-between",children:[(0,t.jsxs)("div",{className:"flex min-w-0 flex-col gap-0.5",children:[(0,t.jsxs)("div",{className:"flex items-center gap-2 text-sm font-medium",children:[(0,t.jsx)("span",{className:"size-2 rounded-full bg-amber-500 shadow-(--shadow-extract-13)"}),(0,t.jsx)("span",{children:"Unsaved changes"})]}),V?(0,t.jsx)("p",{className:"min-w-0 truncate pl-4 text-xs text-amber-950/80 dark:text-amber-100/80",title:V,children:V}):null]}),(0,t.jsxs)("div",{className:"flex items-center gap-2",children:[(0,t.jsxs)("button",{type:"button",onClick:re,className:"inline-flex h-9 items-center gap-1.5 rounded-md border border-amber-500/30 bg-background px-3 text-sm font-medium text-foreground transition-colors hover:bg-amber-500/10 dark:bg-background/80",children:[(0,t.jsx)(Ai,{className:"size-4"}),"Revert"]}),(0,t.jsxs)("button",{type:"button",onClick:Y,className:"inline-flex h-9 items-center gap-1.5 rounded-md bg-primary px-4 text-sm font-medium text-primary-foreground transition-colors hover:bg-primary/90",children:[(0,t.jsx)(of,{className:"size-4"}),"Save"]})]})]}):null,ve?(0,t.jsx)("p",{className:"text-(length:--text-micro) text-muted-foreground/70",children:ve}):null,v.some(de=>de.source==="user_secret"&&de.userSecretKey)?(0,t.jsxs)("p",{className:"inline-flex items-start gap-1 text-(length:--text-micro) text-muted-foreground/70",children:[(0,t.jsx)(oh,{className:"mt-0.5 size-3 shrink-0"}),(0,t.jsx)("span",{children:"User secrets resolve from the user responsible for the run. Required bindings fail until that user sets their value under Secrets → My secrets."})]}):null]})})},"EnvironmentVariablesEditor")),iut="env.",Y3="access.",Ez=/^[A-Za-z_][A-Za-z0-9_]*$/;function P_e(e){return e?e.startsWith("access.")?"api":e.startsWith("env.")?"env":"config":"config"}r(P_e,"deliveryModeForConfigPath");function D_e(e){switch(e){case"env":return"Env var";case"api":return"API access";default:return"Config"}}r(D_e,"deliveryModeLabel");function out(e){switch(e){case"env":return"Injected as an environment variable at run start.";case"api":return"Fetched on demand via the run-bound agent API. Never written to the environment.";default:return"Provided through adapter configuration."}}r(out,"deliveryModeDescription");function $_e(e){return e?e.startsWith("access.")?e.slice(7):e.startsWith("env.")?e.slice(4):e:""}r($_e,"aliasFromConfigPath");function lut(e){switch(e){case"agent_api":return"Agent API";case"plugin_worker":return"Plugin worker";case"tool_connection":return"Tool connection";default:return e.charAt(0).toUpperCase()+e.slice(1)}}r(lut,"consumerTypeLabel");var cut={numeric:!0,sensitivity:"base"};function SC(e){return e.kind==="company"?e.secret.name:e.definition.name}r(SC,"getSecretPathRowName");function kN(e){return e.split("/").filter(s=>s.length>0)}r(kN,"splitSecretPath");function sD(e){return kN(e).join("/")}r(sD,"normalizeSecretPath");function Wre(e,s){return s.every((n,a)=>e[a]===n)}r(Wre,"startsWithSegments");function Hre(e,s){return e.localeCompare(s,void 0,cut)}r(Hre,"compareNames");function dut(e,s){const n=kN(s),a=e.map(c=>({row:c,name:SC(c),segments:kN(SC(c))})),i=new Set,o=[];for(const c of a){if(!Wre(c.segments,n))continue;const d=c.segments.length-n.length;(d===0||d===1)&&o.push(c.row),d>=2&&i.add(c.segments[n.length])}const l=[...i].map(c=>{const d=[...n,c],u=new Set;let h=0;for(const p of a){if(!Wre(p.segments,d))continue;const f=p.segments.length-d.length;if(!(f<1)){h+=1;for(let x=1;x<f;x+=1)u.add(p.segments.slice(d.length,d.length+x).join("/"))}}return{name:c,path:d.join("/"),secretCount:h,folderCount:u.size}});return l.sort((c,d)=>Hre(c.name,d.name)),o.sort((c,d)=>Hre(SC(c),SC(d))),{folders:l,secrets:o}}r(dut,"buildSecretPathListing");function uut(e){const s=kN(e);return s.map((n,a)=>({name:n,path:s.slice(0,a+1).join("/")}))}r(uut,"buildSecretPathBreadcrumbs");function mut(e){return e.trim()?e.includes("/")?"Folder name cannot contain slashes.":null:"Folder name is required."}r(mut,"validateSecretFolderSegment");function g5({name:e,basePath:s="",className:n,leafClassName:a}){const i=kN(e),o=kN(s),l=o.length>0&&o.every((h,p)=>i[p]===h)&&i.length>o.length?i.slice(o.length):i,c=l.length>0?l:[e],d=c[c.length-1],u=c.slice(0,-1).join("/");return(0,t.jsxs)("span",{className:W("min-w-0 truncate",n),children:[u?(0,t.jsxs)("span",{className:"text-muted-foreground",children:[u,"/"]}):null,(0,t.jsx)("span",{className:W("font-medium text-foreground",a),children:d})]})}r(g5,"SecretPathName");function hut(e,s){const n=e?`sha256:${e.slice(0,10)}…`:"no fingerprint",a=typeof s=="number"?`${s} ${s===1?"byte":"bytes"}`:null;return a?`${n} · ${a}`:n}r(hut,"fingerprintLabel");function O_e({fingerprint:e,length:s,className:n}){const{pushToast:a}=Zr(),i=hut(e,s);if(!e)return(0,t.jsxs)("span",{className:W("inline-flex items-center gap-1 font-mono",n),children:[(0,t.jsx)(pF,{className:"size-3 shrink-0"}),i]});const o=`sha256:${e}`;return(0,t.jsxs)("button",{type:"button",onClick:r(()=>{wa(o).then(()=>a({title:"Fingerprint copied",tone:"success"})).catch(()=>a({title:"Couldn’t copy fingerprint",tone:"error"}))},"onClick"),title:`Copy full digest — ${o}`,className:W("inline-flex items-center gap-1 font-mono hover:text-foreground",n),children:[(0,t.jsx)(pF,{className:"size-3 shrink-0"}),i,(0,t.jsx)(br,{className:"size-3 shrink-0 opacity-60"})]})}r(O_e,"FingerprintChip");function yV({justification:e,className:s}){return(0,t.jsxs)("div",{className:W("space-y-0.5",s),children:[(0,t.jsx)("p",{className:"text-(length:--text-micro) text-muted-foreground",children:"Reason given by the agent"}),(0,t.jsxs)("p",{className:"whitespace-pre-wrap break-words text-xs text-foreground/80",children:["“",e,"”"]})]})}r(yV,"ProposalJustification");function b5({agent:e,className:s}){return(0,t.jsxs)("span",{className:W("inline-flex min-w-0 items-center gap-1",s),children:[(0,t.jsx)(lr,{agent:e,size:16,className:"h-3.5 w-3.5 shrink-0 text-muted-foreground"}),(0,t.jsx)("span",{className:"min-w-0 truncate",children:e.name})]})}r(b5,"AgentRefChip");function jV({configPath:e}){const s=P_e(e),n=s==="env",a=s==="api";return(0,t.jsxs)(ot,{variant:"outline",className:W("h-5 gap-1 px-1.5 text-(length:--text-nano) font-normal",n&&"border-sky-500/30 bg-sky-500/10 text-sky-700 dark:text-sky-300",a&&"border-violet-500/30 bg-violet-500/10 text-violet-700 dark:text-violet-300",!n&&!a&&"border-border bg-muted/40 text-muted-foreground"),children:[n?(0,t.jsx)(V1e,{className:"size-3"}):a?(0,t.jsx)(PL,{className:"size-3"}):null,D_e(s)]})}r(jV,"DeliveryBadge$1");function wV({className:e}){return(0,t.jsxs)(ot,{variant:"outline",className:W("h-5 gap-1 px-1.5 text-(length:--text-nano) font-medium","border-amber-500/40 bg-amber-500/10 text-amber-700 dark:text-amber-300",e),children:[(0,t.jsx)(Tc,{className:"size-3"})," Proposed"]})}r(wV,"ProposedBadge");function wM(e){return $_e(e.configPath)}r(wM,"bindingEnvKey");function kV(e){return e.secretProposalId?{name:e.secretProposalName??"proposed secret",pending:!0}:{name:e.secretName??"secret",pending:!1}}r(kV,"bindingSecretLabel");function Vre(e){return e instanceof nn?e.message||`Request failed: ${e.status}`:e instanceof Error?e.message:"Something went wrong. Try again."}r(Vre,"readableError");function B_e(e,s=[]){const n=wt(),{pushToast:a}=Zr(),[i,o]=(0,m.useState)(null),[l,c]=(0,m.useState)(null),[d,u]=(0,m.useState)(""),[h,p]=(0,m.useState)(null),f=(0,m.useCallback)(()=>{e&&(n.invalidateQueries({queryKey:["secret-proposals",e]}),n.invalidateQueries({queryKey:D.secrets.list(e)}))},[e,n]),x=we({mutationFn:r(w=>{const{proposal:N}=w;if(N.kind==="secret"){const S=w.folder.trim()?`${w.folder.trim().replace(/\/+$/,"")}/${w.leaf.trim()}`:w.leaf.trim();return Rr.approveProposal(e,N.id,{overrides:{name:S,description:w.description.trim()||null,providerConfigId:w.providerConfigId||null}})}return Rr.approveProposal(e,N.id,{cascade:w.cascade||void 0})},"mutationFn"),onSuccess:r(w=>{a({title:w.kind==="secret"?"Secret approved":"Binding approved",body:w.kind==="secret"?w.proposedName??"Secret created":`${w.target?.name??"Agent"} · ${wM(w)||"binding"}`,tone:"success"}),o(null),p(null),f()},"onSuccess"),onError:r(w=>p(Vre(w)),"onError")}),g=we({mutationFn:r(({proposal:w,reason:N})=>Rr.rejectProposal(e,w.id,{reason:N.trim()}),"mutationFn"),onSuccess:r(w=>{a({title:"Proposal rejected",body:w.kind==="secret"?w.proposedName??void 0:void 0,tone:"info"}),c(null),u(""),p(null),f()},"onSuccess"),onError:r(w=>p(Vre(w)),"onError")}),v=(0,m.useCallback)(w=>{p(null);const N=(w.proposedName??"").split("/"),S=N.pop()??"";o({proposal:w,folder:N.join("/"),leaf:S,description:w.proposedDescription??"",providerConfigId:s.find(C=>C.provider==="local_encrypted"&&C.isDefault)?.id??"",cascade:!!w.secretProposalId})},[s]),y=(0,m.useCallback)(w=>{p(null),u(""),c(w)},[]),k=(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)(put,{draft:i,error:h,pending:x.isPending,providerConfigs:s,onChange:o,onCancel:r(()=>{o(null),p(null)},"onCancel"),onConfirm:r(()=>i&&x.mutate(i),"onConfirm")}),(0,t.jsx)(xut,{proposal:l,reason:d,error:h,pending:g.isPending,onReasonChange:u,onCancel:r(()=>{c(null),u(""),p(null)},"onCancel"),onConfirm:r(()=>l&&g.mutate({proposal:l,reason:d}),"onConfirm")})]});return{requestApprove:v,requestReject:y,isBusy:x.isPending||g.isPending,dialogs:k}}r(B_e,"useProposalReview");function put({draft:e,error:s,pending:n,providerConfigs:a,onChange:i,onCancel:o,onConfirm:l}){const c=e?.proposal.kind==="secret",d=e?e.folder.trim()?`${e.folder.trim().replace(/\/+$/,"")}/${e.leaf.trim()}`:e.leaf.trim():"",u=a.filter(p=>p.provider==="local_encrypted"),h=c?!!(e&&e.leaf.trim()):!0;return(0,t.jsx)(Fs,{open:!!e,onOpenChange:r(p=>!p&&o(),"onOpenChange"),children:(0,t.jsx)(Qs,{className:"sm:max-w-lg",children:e?(0,t.jsxs)(t.Fragment,{children:[(0,t.jsxs)(rn,{children:[(0,t.jsx)(Ks,{children:c?"Approve & create secret":"Approve binding"}),(0,t.jsx)(mn,{children:c?"The value is created as the proposing agent recorded it. Re-folder or rename it before it lands.":"Grant the target agent access to this secret. This runs with your permissions."})]}),(0,t.jsxs)("div",{className:"space-y-1.5 rounded-md border border-border bg-muted/30 p-2.5 text-xs",children:[(0,t.jsxs)("div",{className:"flex items-center gap-1.5 text-muted-foreground",children:[(0,t.jsx)("span",{children:"Proposed by"}),(0,t.jsx)(b5,{agent:e.proposal.proposedBy,className:"font-medium text-foreground"})]}),(0,t.jsx)(yV,{justification:e.proposal.justification})]}),c?(0,t.jsxs)("div",{className:"space-y-3",children:[(0,t.jsxs)("div",{className:"grid grid-cols-2 gap-2",children:[(0,t.jsxs)("div",{className:"space-y-1",children:[(0,t.jsx)($s,{htmlFor:"approve-folder",children:"Folder"}),(0,t.jsx)(dt,{id:"approve-folder",value:e.folder,onChange:r(p=>i({...e,folder:p.target.value}),"onChange"),placeholder:"dev/github",className:"font-mono text-xs"})]}),(0,t.jsxs)("div",{className:"space-y-1",children:[(0,t.jsx)($s,{htmlFor:"approve-name",children:"Name"}),(0,t.jsx)(dt,{id:"approve-name",value:e.leaf,onChange:r(p=>i({...e,leaf:p.target.value}),"onChange"),placeholder:"client-secret",autoFocus:!0,"aria-invalid":!e.leaf.trim(),className:"font-mono text-xs"})]})]}),(0,t.jsxs)("p",{className:"text-(length:--text-micro) text-muted-foreground",children:["Lands as"," ",d?(0,t.jsx)(g5,{name:d,className:"font-mono"}):(0,t.jsx)("span",{className:"italic",children:"enter a name"})]}),(0,t.jsxs)("div",{className:"space-y-1",children:[(0,t.jsx)($s,{htmlFor:"approve-description",children:"Description"}),(0,t.jsx)(dt,{id:"approve-description",value:e.description,onChange:r(p=>i({...e,description:p.target.value}),"onChange"),placeholder:"Optional"})]}),u.length>0?(0,t.jsxs)("div",{className:"space-y-1",children:[(0,t.jsx)($s,{htmlFor:"approve-provider-config",children:"Provider vault"}),(0,t.jsxs)("select",{id:"approve-provider-config",value:e.providerConfigId,onChange:r(p=>i({...e,providerConfigId:p.target.value}),"onChange"),className:"h-9 w-full rounded-md border border-input bg-transparent px-2 text-sm outline-none focus-visible:border-ring focus-visible:ring-3 focus-visible:ring-ring/50",children:[(0,t.jsx)("option",{value:"",children:"Deployment default"}),u.map(p=>(0,t.jsx)("option",{value:p.id,children:p.displayName},p.id))]})]}):null,(0,t.jsx)("div",{className:"rounded-md border border-border bg-background px-2.5 py-1.5 text-xs text-muted-foreground",children:(0,t.jsx)(O_e,{fingerprint:e.proposal.valueFingerprintSha256,length:e.proposal.valueLength})})]}):(0,t.jsx)(fut,{draft:e,onChange:i}),s?(0,t.jsx)("p",{className:"text-xs text-destructive",role:"alert",children:s}):null,(0,t.jsxs)(cr,{children:[(0,t.jsx)($,{variant:"ghost",onClick:o,disabled:n,children:"Cancel"}),(0,t.jsx)($,{onClick:l,disabled:n||!h,children:n?"Approving…":c?"Approve & create":e.cascade?"Approve secret & bind":"Approve binding"})]})]}):null})})}r(put,"ApproveDialog");function fut({draft:e,onChange:s}){const{proposal:n}=e,a=kV(n),i=wM(n);return(0,t.jsxs)("div",{className:"space-y-3 text-sm",children:[(0,t.jsxs)("div",{className:"space-y-2 rounded-md border border-border p-3",children:[(0,t.jsxs)("div",{className:"flex items-center justify-between gap-2",children:[(0,t.jsx)("span",{className:"text-xs text-muted-foreground",children:"Target agent"}),n.target?(0,t.jsx)(b5,{agent:n.target,className:"text-sm font-medium"}):(0,t.jsx)("span",{className:"text-muted-foreground",children:"—"})]}),(0,t.jsxs)("div",{className:"flex items-center justify-between gap-2",children:[(0,t.jsx)("span",{className:"text-xs text-muted-foreground",children:"Delivered as"}),(0,t.jsxs)("span",{className:"flex items-center gap-1.5",children:[(0,t.jsx)(jV,{configPath:n.configPath}),(0,t.jsx)("code",{className:"font-mono text-xs",children:i||n.configPath})]})]}),(0,t.jsxs)("div",{className:"flex items-center justify-between gap-2",children:[(0,t.jsx)("span",{className:"text-xs text-muted-foreground",children:"Secret"}),(0,t.jsxs)("span",{className:"flex items-center gap-1.5",children:[(0,t.jsx)(Si,{className:"size-3.5 text-muted-foreground"}),(0,t.jsx)("span",{className:"font-medium",children:a.name}),a.pending?(0,t.jsx)(wV,{}):null]})]})]}),n.secretProposalId?(0,t.jsxs)("label",{className:"flex items-start gap-2 rounded-md border border-amber-500/30 bg-amber-500/5 p-2.5 text-xs",children:[(0,t.jsx)(ei,{checked:e.cascade,onCheckedChange:r(o=>s({...e,cascade:o===!0}),"onCheckedChange"),className:"mt-0.5","aria-label":"Also approve the proposed secret"}),(0,t.jsxs)("span",{className:"text-foreground/90",children:["Also approve the proposed secret"," ",(0,t.jsx)("span",{className:"font-medium",children:a.name})," and create it in the same step. The binding can’t land without it."]})]}):null]})}r(fut,"BindingApproveBody");function xut({proposal:e,reason:s,error:n,pending:a,onReasonChange:i,onCancel:o,onConfirm:l}){const c=s.trim().length>0;return(0,t.jsx)(Fs,{open:!!e,onOpenChange:r(d=>!d&&o(),"onOpenChange"),children:(0,t.jsx)(Qs,{className:"sm:max-w-md",children:e?(0,t.jsxs)(t.Fragment,{children:[(0,t.jsxs)(rn,{children:[(0,t.jsx)(Ks,{children:"Reject proposal"}),(0,t.jsxs)(mn,{children:["The reason is sent back to"," ",(0,t.jsx)(b5,{agent:e.proposedBy,className:"text-foreground"}),". Dependent bindings are rejected too."]})]}),(0,t.jsxs)("div",{className:"space-y-1",children:[(0,t.jsx)($s,{htmlFor:"reject-reason",children:"Reason"}),(0,t.jsx)(Hn,{id:"reject-reason",value:s,onChange:r(d=>i(d.target.value),"onChange"),rows:3,autoFocus:!0,placeholder:"Why is this being rejected?"})]}),n?(0,t.jsx)("p",{className:"text-xs text-destructive",role:"alert",children:n}):null,(0,t.jsxs)(cr,{children:[(0,t.jsx)($,{variant:"ghost",onClick:o,disabled:a,children:"Cancel"}),(0,t.jsx)($,{variant:"destructive",onClick:l,disabled:a||!c,children:a?"Rejecting…":"Reject"})]})]}):null})})}r(xut,"RejectDialog");function F_e({proposal:e,onApprove:s,onReject:n,disabled:a,size:i="sm"}){const o=!e.viewerCanApprove,l=i==="xs"?"h-7 px-2 text-xs":"",c=(0,t.jsx)($,{size:"sm",className:l,disabled:a||o,onClick:r(()=>s(e),"onClick"),children:"Approve"});return(0,t.jsxs)("div",{className:"flex items-center gap-1.5",children:[o?(0,t.jsx)(Zc,{children:(0,t.jsxs)(Fn,{children:[(0,t.jsx)(Bn,{asChild:!0,children:(0,t.jsx)("span",{tabIndex:0,children:c})}),(0,t.jsx)(On,{className:"max-w-72",children:e.approveBlockReason??"You don’t have permission to approve this."})]})}):c,(0,t.jsx)($,{size:"sm",variant:"outline",className:l,disabled:a,onClick:r(()=>n(e),"onClick"),children:"Reject"})]})}r(F_e,"ProposalActions");function z_e(e){return typeof e!="object"||e===null||Array.isArray(e)?null:e}r(z_e,"asRecord$16");function q_e(e){const s=z_e(e);if(!s||s.type!=="secret_ref")return null;const n=typeof s.secretId=="string"?s.secretId:"";return n?{secretId:n,version:typeof s.version=="number"?s.version:"latest"}:null}r(q_e,"readSecretRef");function gut(e){const s=z_e(e?.env);if(!s)return[];const n=[];for(const[a,i]of Object.entries(s)){const o=q_e(i);o&&n.push({name:a,...o})}return n}r(gut,"parseEnvSecretRefs");function but(e){if(!e)return[];const s=[];for(const[n,a]of Object.entries(e)){if(!n.startsWith("access."))continue;const i=q_e(a);i&&s.push({name:n.slice(Y3.length),...i})}return s}r(but,"parseAccessGrants");function vut(e,s){const n=new Map,a=r(i=>{let o=n.get(i);return o||(o={secretId:i,envKeys:[],apiAliases:[]},n.set(i,o)),o},"ensure");for(const i of e)a(i.secretId).envKeys.push(i.name);for(const i of s)a(i.secretId).apiAliases.push(i.name);return[...n.values()]}r(vut,"summarizeAgentBindings");var Gre=0;function U_e(){return Gre+=1,`access-row-${Gre}`}r(U_e,"nextAccessRowId");function nD(e){return e.map(s=>({id:U_e(),alias:s.name,secretId:s.secretId,version:s.version}))}r(nD,"entriesToRows");function Yre(e){const s={};for(const n of e){const a=n.alias.trim();!a||!Ez.test(a)||!n.secretId||(s[a]={type:"secret_ref",secretId:n.secretId,version:n.version})}return s}r(Yre,"rowsToAccessMap");function Zre(e){return JSON.stringify(Object.keys(e).sort().map(s=>{const n=e[s];return[s,n.secretId,n.version??"latest"]}))}r(Zre,"normalizeAccessMapKey");function Jre({mode:e}){return e==="env"?(0,t.jsxs)(ot,{variant:"outline",className:"h-5 gap-1 px-1.5 text-(length:--text-nano) font-normal border-sky-500/30 bg-sky-500/10 text-sky-700 dark:text-sky-300",children:[(0,t.jsx)(V1e,{className:"size-3"})," Env var"]}):(0,t.jsxs)(ot,{variant:"outline",className:"h-5 gap-1 px-1.5 text-(length:--text-nano) font-normal border-violet-500/30 bg-violet-500/10 text-violet-700 dark:text-violet-300",children:[(0,t.jsx)(PL,{className:"size-3"})," API access"]})}r(Jre,"DeliveryBadge");function yut({config:e,secrets:s,onChange:n,onCreateSecret:a,disabled:i,proposals:o,onApproveProposal:l,onRejectProposal:c}){const d=(0,m.useMemo)(()=>(o??[]).filter(O=>O.kind==="binding"),[o]),u=(0,m.useMemo)(()=>gut(e),[e]),h=(0,m.useMemo)(()=>but(e),[e]),p=(0,m.useMemo)(()=>vut(u,h),[u,h]),f=(0,m.useMemo)(()=>Yre(nD(h)),[h]),x=(0,m.useMemo)(()=>Zre(f),[f]),[g,v]=(0,m.useState)(()=>nD(h)),[y,k]=(0,m.useState)(null),w=(0,m.useRef)(new Map),N=(0,m.useRef)(x),S=(0,m.useRef)(x);(0,m.useEffect)(()=>{x!==S.current&&(S.current=x,x!==N.current&&v(nD(h)))},[x,h]);const C=r(O=>s.find(M=>M.id===O)?.name??`${O.slice(0,8)}…`,"secretName");function _(O){v(O);const M=Yre(O);N.current=Zre(M),n(M)}r(_,"emit");function R(O,M){_(g.map(Q=>Q.id===O?{...Q,...M}:Q))}r(R,"patchRow");function I(O){_(g.filter(M=>M.id!==O))}r(I,"removeRow");function T(){v(O=>[...O,{id:U_e(),alias:"",secretId:"",version:"latest"}])}r(T,"addRow");const E=(0,m.useMemo)(()=>{const O=new Map;for(const M of g){const Q=M.alias.trim();Q&&O.set(Q,(O.get(Q)??0)+1)}return O},[g]),P=p.length>0;return(0,t.jsxs)("div",{className:"space-y-3",children:[P?(0,t.jsx)("div",{className:"space-y-1.5",children:p.map(O=>(0,t.jsxs)("div",{className:"flex flex-wrap items-center gap-x-2 gap-y-1 rounded-md border border-border bg-muted/30 px-2.5 py-1.5 text-xs",children:[(0,t.jsx)(Si,{className:"size-3.5 shrink-0 text-muted-foreground"}),(0,t.jsx)("span",{className:"font-medium",children:C(O.secretId)}),O.envKeys.length>0?(0,t.jsx)(Jre,{mode:"env"}):null,O.apiAliases.length>0?(0,t.jsx)(Jre,{mode:"api"}):null,(0,t.jsx)("span",{className:"min-w-0 truncate font-mono text-(length:--text-micro) text-muted-foreground",children:[...O.envKeys.map(M=>`${iut}${M}`),...O.apiAliases.map(M=>`${Y3}${M}`)].join(" · ")})]},O.secretId))}):(0,t.jsx)("p",{className:"text-sm text-muted-foreground",children:"No secrets are bound to this agent yet."}),d.length>0&&l&&c?(0,t.jsxs)("div",{className:"space-y-2",children:[(0,t.jsx)("div",{className:"text-(length:--text-micro) font-medium uppercase tracking-wide text-muted-foreground",children:"Proposed access"}),d.map(O=>{const M=kV(O),Q=wM(O);return(0,t.jsxs)("div",{className:"flex flex-col gap-2 rounded-md border border-amber-500/30 bg-amber-500/5 px-2.5 py-2 text-xs sm:flex-row sm:items-center",children:[(0,t.jsxs)("div",{className:"min-w-0 flex-1 space-y-1",children:[(0,t.jsxs)("div",{className:"flex min-w-0 flex-wrap items-center gap-1.5",children:[(0,t.jsx)(jV,{configPath:O.configPath}),(0,t.jsx)("code",{className:"font-mono",children:Q||O.configPath}),(0,t.jsx)("span",{className:"text-muted-foreground",children:"→"}),(0,t.jsx)(Si,{className:"size-3 text-muted-foreground"}),(0,t.jsx)("span",{className:"font-medium",children:M.name}),M.pending?(0,t.jsx)(wV,{}):null]}),(0,t.jsxs)("p",{className:"flex flex-wrap items-center gap-1 text-muted-foreground",children:[(0,t.jsxs)("span",{children:["proposed by ",O.proposedBy.name]}),(0,t.jsx)("span",{"aria-hidden":"true",children:"·"}),(0,t.jsxs)("span",{className:"truncate italic",children:["“",O.justification,"”"]})]})]}),(0,t.jsx)(F_e,{proposal:O,onApprove:l,onReject:c,disabled:i,size:"xs"})]},O.id)})]}):null,(0,t.jsxs)("div",{className:"space-y-2",children:[(0,t.jsx)("div",{className:"text-(length:--text-micro) font-medium uppercase tracking-wide text-muted-foreground",children:"API access (no env var)"}),g.length>0?(0,t.jsx)("div",{className:"space-y-2",children:g.map(O=>{const M=O.alias.trim(),Q=!!M&&!Ez.test(M),L=!!M&&(E.get(M)??0)>1,F=s.find(q=>q.id===O.secretId)??null;return(0,t.jsxs)("div",{className:"space-y-1",children:[(0,t.jsxs)("div",{className:"grid grid-cols-(--gtc-65) items-start gap-1.5",children:[(0,t.jsx)("div",{children:(0,t.jsx)(dt,{value:O.alias,onChange:r(q=>R(O.id,{alias:q.target.value}),"onChange"),onBlur:r(q=>{const z=q.target.value.trim();if(z&&!Ez.test(z)){const K=c_(z);K&&K!==z&&R(O.id,{alias:K})}},"onBlur"),placeholder:"ALIAS","aria-label":"Access alias",disabled:i,className:W("h-9 font-mono text-sm",(Q||L)&&"border-destructive text-destructive")})}),(0,t.jsxs)("div",{className:"flex min-w-0 items-start gap-1.5",children:[(0,t.jsxs)(dr,{open:y?.rowId===O.id,onOpenChange:r(q=>{!q&&y?.rowId===O.id&&k(null)},"onOpenChange"),children:[(0,t.jsx)(ZB,{asChild:!0,children:(0,t.jsx)("div",{ref:r(q=>{q?w.current.set(O.id,q):w.current.delete(O.id)},"ref"),className:"min-w-0 flex-1",children:(0,t.jsx)(vV,{secretId:O.secretId,secrets:s,onSelect:r(q=>R(O.id,{secretId:q,version:"latest",alias:!O.alias.trim()&&q?c_(C(q)):O.alias}),"onSelect"),onCreateNew:a?q=>{window.setTimeout(()=>{k({rowId:O.id,name:SE(q)||q.trim()})},0)}:void 0,disabled:i,triggerClassName:"h-9 min-h-9"})})}),(0,t.jsx)(nr,{align:"start",className:"w-auto p-3",onInteractOutside:r(q=>{const z=q.detail.originalEvent.target;z&&w.current.get(O.id)?.contains(z)&&q.preventDefault()},"onInteractOutside"),children:y?.rowId===O.id&&a?(0,t.jsx)(E_e,{initialName:y.name,initialValue:"",existingSecretNames:s.map(q=>q.name),onCancel:r(()=>k(null),"onCancel"),onSubmit:r(async(q,z)=>{const K=await a(q,z);R(O.id,{secretId:K.id,version:"latest",alias:O.alias.trim()||c_(K.name)}),k(null)},"onSubmit")}):null})]}),(0,t.jsxs)("select",{className:"h-9 shrink-0 rounded-md border border-border bg-background px-2 text-xs outline-none disabled:cursor-not-allowed disabled:opacity-60",value:O.version===void 0?"latest":String(O.version),onChange:r(q=>{const z=q.target.value;R(O.id,{version:z==="latest"?"latest":Number.parseInt(z,10)})},"onChange"),disabled:i||!F,"aria-label":"Version",children:[(0,t.jsx)("option",{value:"latest",children:"latest"}),F?Array.from({length:Math.max(0,F.latestVersion)},(q,z)=>{const K=F.latestVersion-z;return K<=0?null:(0,t.jsxs)("option",{value:K,children:["v",K]},K)}):null]})]}),(0,t.jsx)("button",{type:"button",onClick:r(()=>I(O.id),"onClick"),disabled:i,"aria-label":"Remove API access",className:"mt-1 inline-flex size-7 shrink-0 items-center justify-center rounded-md text-muted-foreground transition-colors hover:bg-accent hover:text-foreground disabled:pointer-events-none disabled:opacity-50",children:(0,t.jsx)(ma,{className:"size-3.5"})})]}),Q?(0,t.jsx)("p",{className:"pl-0.5 text-(length:--text-micro) text-destructive",children:"Invalid alias — use letters, digits and _"}):L?(0,t.jsx)("p",{className:"pl-0.5 text-(length:--text-micro) text-destructive",children:"Duplicate alias"}):null]},O.id)})}):null,(0,t.jsxs)("button",{type:"button",onClick:T,disabled:i,className:"inline-flex items-center gap-1 rounded-md px-2 py-1 text-xs font-medium text-muted-foreground transition-colors hover:bg-accent hover:text-foreground disabled:pointer-events-none disabled:opacity-50",children:[(0,t.jsx)(bn,{className:"size-3.5"}),"Add API access"]})]}),(0,t.jsxs)("p",{className:"text-(length:--text-micro) text-muted-foreground/70",children:[out("api")," The agent reads them by alias through ",(0,t.jsx)("code",{children:"GET /agents/me/secrets"}),"."]})]})}r(yut,"AgentSecretAccessEditor");function jut(e){if(typeof e!="string")return null;const s=e.trim();return s.length>0?s:null}r(jut,"asNonEmptyString$3");function wut(e){return jut(e)!==null}r(wut,"hasLegacyWorkingDirectory");function kut(e){return e.isCreate?!1:wut(e.adapterConfig?.cwd)}r(kut,"shouldShowLegacyWorkingDirectoryField");var K_e=new Set;function Nut(e){return K_e.has(e)}r(Nut,"isAdapterTypeHidden");function Sut(e){K_e=new Set(e)}r(Sut,"setDisabledAdapterTypes");function Cut(e){return!th(e).hideFromVisualSelection}r(Cut,"isVisualAdapterChoice");function Q_e(e,s=gV()){const n=e??kf;return s.map(a=>({value:a.type,label:n(a.type),comingSoon:!!th(a.type).comingSoon,hidden:Nut(a.type),experimental:!!th(a.type).experimental}))}r(Q_e,"listAdapterOptions");function W_e(e={}){const s=e.enabled??!0,{data:n}=te({queryKey:D.adapters.all,queryFn:r(()=>Oh.list(),"queryFn"),enabled:s,staleTime:3e5});return n&&Cdt(n.filter(a=>a.source==="external").map(a=>({type:a.type,label:a.label,disabled:a.disabled,overrideDisabled:a.overridePaused}))),(0,m.useEffect)(()=>{n&&Sut(n.filter(a=>a.disabled).map(a=>a.type))},[n]),(0,m.useMemo)(()=>new Set(n?.filter(a=>a.disabled).map(a=>a.type)??[]),[n])}r(W_e,"useDisabledAdaptersSync");function _ut(e={}){const s=e.enabled??!0,{data:n}=te({queryKey:D.adapters.all,queryFn:r(()=>Oh.list(),"queryFn"),enabled:s,staleTime:3e5});return n!==void 0}r(_ut,"useAdapterRegistryLoaded");function CE(e){return Object.fromEntries(Object.entries(e).filter(([,s])=>s!==void 0))}r(CE,"omitUndefinedEntries");function II(e,s){const n={};if(Object.keys(s.identity).length>0&&Object.assign(n,s.identity),s.adapterType!==void 0&&(n.adapterType=s.adapterType),s.adapterType!==void 0||Object.keys(s.adapterConfig).length>0){const a=e.adapterConfig??{};n.adapterConfig=CE(s.adapterType!==void 0?{...Object.fromEntries(fOe.filter(i=>a[i]!==void 0).map(i=>[i,a[i]])),...s.adapterConfig}:{...a,...s.adapterConfig}),n.replaceAdapterConfig=!0}if(Object.keys(s.heartbeat).length>0||Object.keys(s.debug).length>0){const a=e.runtimeConfig??{},i=n.runtimeConfig??{...a};if(Object.keys(s.heartbeat).length>0&&(i.heartbeat={...a.heartbeat??{},...s.heartbeat}),Object.keys(s.debug).length>0){const o=CE({...a.debug??{},...s.debug});Object.keys(o).length===0?delete i.debug:i.debug=o}n.runtimeConfig=i}return Object.keys(s.runtime).length>0&&Object.assign(n,s.runtime),n}r(II,"buildAgentUpdatePatch");var Aut="kubernetes";function Iut(e){return e.driver!=="sandbox"?!1:e.config?.provider===Aut}r(Iut,"isKubernetesSandboxEnvironment");function NV(e,s){return e!=="kubernetes"?{forced:!1,kubernetesEnvironment:null}:{forced:!0,kubernetesEnvironment:s.find(n=>Iut(n))??null}}r(NV,"resolveForcedKubernetesEnvironment");var rD={identity:{},adapterConfig:{},heartbeat:{},debug:{},runtime:{}},TS={};function Tut(e){return e==="claude_local"||e==="codex_local"||e==="paperclip_runner"||e==="opencode_local"}r(Tut,"supportsAdapterModelRefresh");function Rut(e,s){return $Ce(e,s).model}r(Rut,"resolvePaperclipRunnerTransitionModel");function Xre(e){return Object.keys(e.identity).length>0||e.adapterType!==void 0||Object.keys(e.adapterConfig).length>0||Object.keys(e.heartbeat).length>0||Object.keys(e.debug).length>0||Object.keys(e.runtime).length>0}r(Xre,"isOverlayDirty");function Lz(e,s){if(Object.is(e,s))return!0;if(Array.isArray(e)&&Array.isArray(s))return e.length===s.length&&e.every((n,a)=>Lz(n,s[a]));if(typeof e=="object"&&e!==null&&!Array.isArray(e)&&typeof s=="object"&&s!==null&&!Array.isArray(s)){const n=Object.entries(e),a=s;return n.length===Object.keys(a).length&&n.every(([i,o])=>i in a&&Lz(o,a[i]))}return!1}r(Lz,"overlayValuesEqual");function Eut(e,s){const n=r((a,i)=>Object.fromEntries(Object.entries(a).filter(([o,l])=>!(o in i)||!Lz(l,i[o]))),"subtractGroup");return{identity:n(e.identity,s.identity),...e.adapterType!==void 0&&e.adapterType!==s.adapterType?{adapterType:e.adapterType}:{},adapterConfig:n(e.adapterConfig,s.adapterConfig),heartbeat:n(e.heartbeat,s.heartbeat),debug:n(e.debug,s.debug),runtime:n(e.runtime,s.runtime)}}r(Eut,"subtractPersistedOverlay");var Ch="w-full rounded-md border border-border px-2.5 py-1.5 bg-transparent outline-none text-sm font-mono placeholder:text-muted-foreground/40";function Lut(e){return e.split(",").map(s=>s.trim()).filter(Boolean)}r(Lut,"parseCommaArgs");function Mut(e){return Array.isArray(e)?e.filter(s=>typeof s=="string").join(", "):typeof e=="string"?e:""}r(Mut,"formatArgList");var Put=[{id:"",label:"Auto"},{id:"minimal",label:"Minimal"},{id:"low",label:"Low"},{id:"medium",label:"Medium"},{id:"high",label:"High"},{id:"xhigh",label:"X-High"},{id:"max",label:"Max"}],Dut=[{id:"",label:"Auto"},{id:"plan",label:"Plan"},{id:"ask",label:"Ask"}],$ut=[{id:"",label:"Auto"},{id:"low",label:"Low"},{id:"medium",label:"Medium"},{id:"high",label:"High"}],Out=[{id:"",label:"Auto"},{id:"low",label:"Low"},{id:"high",label:"High"},{id:"max",label:"Max"}],But=2,eae=10,Fut=1,H_e=300;function p6(e,s,n){return Math.max(s,Math.min(n,Math.floor(e)))}r(p6,"clampInteger");function zut(e){return p6(e,0,H_e)*1e3}r(zut,"clampDelayMsFromSeconds");function qut({order:e,className:s,children:n}){if(!e)return(0,t.jsx)("div",{className:s,children:n});const a=r(o=>{const l=(0,m.isValidElement)(o)?o.props["data-config-section"]:void 0,c=l?e.indexOf(l):-1;return c<0?e.length:c},"rank"),i=m.Children.toArray(n).sort((o,l)=>a(o)-a(l));return(0,t.jsx)("div",{className:s,children:i})}r(qut,"ConfigSections");function V_e(e){const{mode:s,adapterModels:n}=e,a=s==="create",i=e.sectionLayout==="cards",o=e.showAdapterTypeField??!0,l=e.showAdapterTestEnvironmentButton??!0,c=l&&!e.onTestActionChange&&!e.compactTestFeedback,d=!e.onTestFeedbackChange,u=e.showCreateRunPolicySection??!0,h=e.hideInstructionsFile??!1,p=e.canConfigureProviderTrace===!0,{selectedCompanyId:f}=fs(),x=wt(),g=(0,m.useRef)(null),v=W_e(),{data:y=[]}=te({queryKey:f?D.secrets.list(f):["secrets","none"],queryFn:r(()=>Rr.list(f),"queryFn"),enabled:!!f}),{data:k=[]}=te({queryKey:f?D.secrets.userDefinitions(f):["user-secret-definitions","none"],queryFn:r(()=>Rr.listUserSecretDefinitions(f),"queryFn"),enabled:!!f,retry:!1}),w=a?null:e.agent.id,{data:N=[]}=te({queryKey:f?D.secrets.proposals(f,"pending"):["secret-proposals","none"],queryFn:r(()=>Rr.listProposals(f,"pending"),"queryFn"),enabled:!!f&&!a,retry:!1}),S=(0,m.useMemo)(()=>N.filter(pt=>pt.kind==="binding"&&pt.target?.id===w),[N,w]),C=B_e(f,[]),{data:_}=te({queryKey:D.instance.experimentalSettings,queryFn:r(()=>jr.getExperimental(),"queryFn"),retry:!1}),R=(0,m.useMemo)(()=>{const pt=new Set(v);return _?.enableNativeRunner!==!0&&pt.add("paperclip_runner"),(_?.enableOpenAiDot!==!0||v.has("paperclip_runner"))&&pt.add("openai_dot"),pt},[v,_?.enableNativeRunner,_?.enableOpenAiDot]),I=_?.enableEnvironments===!0,T=_?.enableManagedSandboxOnly===!0,E=_===void 0||T,{data:P}=te({queryKey:D.instance.generalSettings,queryFn:r(()=>jr.getGeneral(),"queryFn"),retry:!1}),{data:O}=te({queryKey:D.instance.settings,queryFn:r(()=>jr.get(),"queryFn"),retry:!1}),{data:M=[]}=te({queryKey:f?D.environments.list(f):["environments","none"],queryFn:r(()=>$i.list(f),"queryFn"),enabled:!!f&&(I||P?.executionMode==="kubernetes")}),{forced:Q,kubernetesEnvironment:L}=(0,m.useMemo)(()=>NV(P?.executionMode,M),[P?.executionMode,M]),F=we({mutationFn:r(pt=>{if(!f)throw new Error("Select an organization to create secrets");return Rr.create(f,pt)},"mutationFn"),onSuccess:r(()=>{f&&x.invalidateQueries({queryKey:D.secrets.list(f)})},"onSuccess")}),q=we({mutationFn:r(async({file:pt,namespace:Is})=>{if(!f)throw new Error("Select an organization to upload images");return dv.uploadImage(f,pt,Is)},"mutationFn")}),[z,K]=(0,m.useState)(rD),[U,V]=(0,m.useState)(!1),[ne,Z]=(0,m.useState)(0),ie=(0,m.useRef)(null),J=(0,m.useRef)(null),ae=(0,m.useRef)(!1);(0,m.useEffect)(()=>{if(!a){if(ie.current!==null&&e.agent!==ie.current&&!ae.current){const pt=J.current;J.current=null,K(Is=>pt?Eut(Is,pt):{...rD})}ie.current=e.agent}},[a,a?void 0:e.agent]);const oe=!a&&(Xre(z)||U);function G(pt,Is,dn){const _n=z[pt];return Is in _n?_n[Is]:dn}r(G,"eff");function X(pt,Is,dn){K(_n=>({..._n,[pt]:{..._n[pt],[Is]:dn}}))}r(X,"mark");function Y(){return g.current?.flushPendingDraft()??null}r(Y,"flushEnvironmentDraft");const re=(0,m.useCallback)(pt=>{a||K(Is=>{const dn={...e.agent.adapterConfig??{},...Is.adapterConfig},_n={...Is.adapterConfig};for(const[fn,Sr]of Object.entries(pt))_n[`${Y3}${fn}`]=Sr;for(const fn of Object.keys(dn))fn.startsWith("access.")&&(fn.slice(7)in pt||(_n[fn]=void 0));return{...Is,adapterConfig:_n}})},[a,a?void 0:e.agent]),se=(0,m.useCallback)(()=>{K({...rD}),V(!1),Z(pt=>pt+1)},[]),ce=(0,m.useCallback)(async()=>{if(a)return;const pt=Y(),Is=pt?{...z,adapterConfig:{...z.adapterConfig,env:pt}}:z;Xre(Is)&&await e.onSave(II(e.agent,Is))},[a,oe,z,e]);(0,m.useEffect)(()=>{a||(e.onDirtyChange?.(oe),e.onSaveActionChange?.(ce),e.onCancelActionChange?.(se))},[a,oe,e.onDirtyChange,e.onSaveActionChange,e.onCancelActionChange,ce,se]),(0,m.useEffect)(()=>{if(!a)return()=>{e.onSaveActionChange?.(null),e.onCancelActionChange?.(null),e.onDirtyChange?.(!1)}},[a,e.onDirtyChange,e.onSaveActionChange,e.onCancelActionChange]);const pe=a?{}:e.agent.adapterConfig??{},fe=a?{}:e.agent.runtimeConfig??{},ve=a?{}:fe.heartbeat??{},Ie=a?{}:fe.debug??{},de=a?e.values.adapterType:z.adapterType??e.agent.adapterType,xe=Wj(),le=xe(de),Re=de==="paperclip_runner"&&(a?e.values.adapterSchemaValues?.provider:G("adapterConfig","provider",pe.provider))==="openai_dot",Le=!Re&&(le.supportsInstructionsBundle||le.supportsSkills||le.supportsLocalAgentJwt),je=Le&&!E&&kut({isCreate:a,adapterConfig:pe}),_e=(0,m.useMemo)(()=>_2(de),[de]),Ze=(0,m.useMemo)(()=>new Set(eUe(de)),[de]),ue=a?e.values:null,Fe=a?pt=>e.onChange(pt):null;a&&ue.claudeStoredSessionId;const mt=r(()=>{f&&x.invalidateQueries({queryKey:D.secrets.userDefinitions(f)})},"invalidateUserSecretDefinitions"),bt=r(pt=>{if(!a||!Fe)return;const Is=ue.envBindings??{};Fe({envBindings:{...Is,...tk()},claudeStoredSessionId:pt}),mt()},"handleClaudeLoginStored"),et=r(async()=>{if(a)return;const pt={...Y()??G("adapterConfig","env",pe.env??TS),...tk()},Is={...z,adapterConfig:{...z.adapterConfig,env:pt}};K(Is),await e.onSave({...II(e.agent,Is),applyStoredClaudeLogin:!0}),mt()},"handleClaudeLoginStoredEdit"),qe=r(async pt=>{if(a||!pt.companyIdentityDiffers)return;const Is={...Y()??G("adapterConfig","env",pe.env??TS),CODEX_HOME:{type:"secret_ref",secretId:pt.secretId,version:"latest"}},dn={...z,adapterConfig:{...z.adapterConfig,env:Is}};K(dn),J.current=dn,ae.current=!0;try{await e.onSave(II(e.agent,dn))}catch(_n){throw J.current=null,_n}finally{ae.current=!1}mt()},"handleCodexAccountBindingEdit"),it=r(()=>{if(!a||!Fe)return;const pt=ue.envBindings??{};Fe({envBindings:{...pt,...tk()},claudeApplyStoredLogin:!0}),mt()},"handleApplyStoredClaudeLogin"),_t=r(async()=>{if(a)return;const pt={...Y()??G("adapterConfig","env",pe.env??TS),...tk()},Is={...z,adapterConfig:{...z.adapterConfig,env:pt}};K(Is),await e.onSave({...II(e.agent,Is),applyStoredClaudeLogin:!0}),mt()},"handleApplyStoredClaudeLoginEdit"),$t=a?ue.defaultEnvironmentId??"":G("identity","defaultEnvironmentId",e.agent.defaultEnvironmentId??""),Ot=(0,m.useMemo)(()=>$t?(M.find(pt=>pt.id===$t)??null)?.driver==="local"?"":$t:"",[M,$t]),at=(0,m.useMemo)(()=>M.find(pt=>pt.id===Ot)??null,[Ot,M]),Me=(0,m.useMemo)(()=>{const pt=O?.defaultEnvironmentId??null;return pt?(M.find(Is=>Is.id===pt)??null)?.driver==="local"?"":pt:""},[M,O?.defaultEnvironmentId]),De=(0,m.useMemo)(()=>M.find(pt=>pt.id===Me)??null,[M,Me]),ut=(0,m.useMemo)(()=>{try{return vN({agentDefaultEnvironmentId:$t||null,instanceDefaultEnvironmentId:O?.defaultEnvironmentId??null,localDefaultEnvironmentId:jN(M),managedSandboxOnly:_?.enableManagedSandboxOnly===!0,managedSandboxEnvironmentId:yN(M),visibleEnvironmentIds:M.map(pt=>pt.id)})}catch{return null}},[$t,O?.defaultEnvironmentId,M,_?.enableManagedSandboxOnly]),Pt=(0,m.useMemo)(()=>M.find(pt=>pt.id===ut)??null,[M,ut]),{data:Rt}=te({queryKey:f?D.environments.capabilities(f):["environment-capabilities","none"],queryFn:r(()=>$i.capabilities(f),"queryFn"),enabled:!!f&&le.login!=null});(0,m.useEffect)(()=>{!a||!Fe||!Q||!L||Ot!==L.id&&Fe({defaultEnvironmentId:L.id})},[a,Fe,Q,L,Ot]);const Qe=(0,m.useMemo)(()=>M.filter(pt=>{if(!Ze.has(pt.driver)||pt.driver==="local")return!1;if(pt.driver!=="sandbox")return!0;const Is=typeof pt.config?.provider=="string"?pt.config.provider:null;return Is!==null&&Is!=="fake"}),[M,Ze]),Be=(0,m.useMemo)(()=>!at||Qe.some(pt=>pt.id===at.id)?Qe:[...Qe,at],[at,Qe]),Oe=I&&(Q||Ot.length>0||Qe.length>=1),Pe=De?wN(De):T?"Paperclip Computer":"Local",Ve=de==="paperclip_runner"?String(a?e.values.adapterSchemaValues?.provider??"codex":G("adapterConfig","provider",pe.provider==="acpx"&&pe.acpxAgent==="codex"?"codex":pe.provider??"codex")):void 0,be=de==="opencode_local"&&GB.safeParse(z.runtime.runtimeConfig?.aiConnection??fe.aiConnection).data?.provider==="openrouter"?"openrouter":Ve,nt=RCe(f,a?void 0:GB.safeParse(z.runtime.runtimeConfig?.aiConnection??fe.aiConnection).data,zee(de,Ve,G("adapterConfig","acpxAgent",pe.acpxAgent))),Lt=f?D.agents.adapterModels(f,de,Ot||null,be):["agents","none","adapter-models",de],{data:Cs,error:lt,isLoading:Os}=te({queryKey:Lt,queryFn:r(()=>Nt.adapterModels(f,de,{environmentId:Ot||null,provider:be}),"queryFn"),enabled:!!f&&!nt}),[Ke,ge]=(0,m.useState)(null),[Xe,xt]=(0,m.useState)(!1),Ht=nt?.models??Cs??n??[],ht=nt?nt.error:lt,zt="command",{data:$e,refetch:he}=te({queryKey:f?D.agents.detectModel(f,de):["agents","none","detect-model",de],queryFn:r(()=>{if(!f)throw new Error("Select an organization to detect the model");return Nt.detectModel(f,de)},"queryFn"),enabled:!!(f&&Le&&de!=="opencode_local"&&de!=="paperclip_runner")}),Vt=$e?.model??null;$e?.candidates;const{data:Dt=[]}=te({queryKey:f?D.agents.list(f):["agents","none","list"],queryFn:r(()=>Nt.list(f),"queryFn"),enabled:!!(!a&&f)}),ns={companyId:f??void 0,agentId:a?void 0:e.agent.id,mode:s,isCreate:a,adapterType:de,values:a?e.values:null,set:a?pt=>e.onChange(pt):null,config:pe,eff:G,mark:X,models:Ht,hideInstructionsFile:h||E||Re,managedSandboxOnly:E||Re,openAiDotEnabled:_?.enableOpenAiDot===!0},[_s,cn]=(0,m.useState)(!1),[mr,pn]=(0,m.useState)(!1),Bt=dV(de),Ls=r(pt=>(0,t.jsxs)(t.Fragment,{children:[de==="claude_local"&&(0,t.jsx)(aot,{...ns,section:pt}),(0,t.jsx)(_e.ConfigFields,{...ns,section:pt,hideModel:Le})]}),"renderAdapterFields"),[Ee,jt]=(0,m.useState)(!1),[ze,St]=(0,m.useState)(!1);function Ut(pt){if(a){const dn=_e.buildAdapterConfig(ue);return pt&&Object.assign(dn,pt),CE(dn)}const Is={...pe,...z.adapterConfig};return pt&&Object.assign(Is,pt),CE(Is)}r(Ut,"buildAdapterConfigForTest");const Ct=we({mutationFn:r(async()=>{if(!f)throw new Error("Select an organization to test adapter environment");const pt=Y(),Is=pt?{env:pt}:void 0;let dn=O,_n=M,fn=_?.enableManagedSandboxOnly===!0;if(!$t)try{const[ln,Tr,Zn]=await Promise.all([x.ensureQueryData({queryKey:D.instance.settings,queryFn:r(()=>jr.get(),"queryFn")}),x.ensureQueryData({queryKey:D.environments.list(f),queryFn:r(()=>$i.list(f),"queryFn")}),x.ensureQueryData({queryKey:D.instance.experimentalSettings,queryFn:r(()=>jr.getExperimental(),"queryFn")})]);dn=ln,_n=Tr,fn=Zn?.enableManagedSandboxOnly===!0}catch{throw new Error("Could not load environment settings to determine which environment to test in. Retry the test.")}const Sr=vN({agentDefaultEnvironmentId:$t||null,instanceDefaultEnvironmentId:dn?.defaultEnvironmentId??null,localDefaultEnvironmentId:jN(_n),managedSandboxOnly:fn,managedSandboxEnvironmentId:yN(_n),visibleEnvironmentIds:_n.map(ln=>ln.id)}),ia=Ut(Is),Da=a?void 0:e.agent.id,Ts=a?void 0:Bee.safeParse(z.runtime.runtimeConfig?.aiConnection??e.agent.runtimeConfig.aiConnection).data;if(e.compactTestFeedback){const ln=de==="paperclip_runner"?ia.provider==="codex"?"codex_local":ia.provider==="acpx"&&ia.acpxAgent==="grok"?"grok_local":ia.provider==="acpx"&&ia.acpxAgent==="claude"?"claude_local":de:de;return ECe({companyId:f,adapterType:de,providerAdapter:ln,adapterConfig:ia,agentId:Da,aiConnection:Ts,environmentId:Sr})}return Nt.testEnvironment(f,de,{adapterConfig:ia,agentId:Da,aiConnection:Ts,environmentId:Sr})},"mutationFn")}),[os,vs]=(0,m.useState)(!1),[Bs,qs]=(0,m.useState)(null),Rn="Test",Ns=!a&&!!e.isSaving,Yn=os||Ns||!f,Xt=(0,m.useRef)(Ct.reset);Xt.current=Ct.reset;const Hs=(0,m.useRef)(()=>{});Hs.current=()=>{if(!a||!Fe)return;const pt=ue.envBindings??{},Is=ue.claudeStoredSessionId!=null||ue.claudeApplyStoredLogin===!0,dn=Ure in pt;if(!Is&&!dn)return;const _n={...pt};delete _n[Ure],Fe({envBindings:_n,claudeStoredSessionId:null,claudeApplyStoredLogin:!1})},(0,m.useEffect)(()=>{Xt.current(),qs(null),Hs.current()},[de,ut]);const on=le.login!=null,Tt=Ct.data,as=Tt!=null&&xe(Tt.adapterType).login!=null,Xs=Tt&&as?Tt.checks.find(pt=>pt.code==="adapter_auth_missing")??null:null,bs=typeof Pt?.config?.provider=="string"?Pt.config.provider:null,Zs=bs!=null&&Rt?.sandboxProviders?.[bs]?.supportsLoginPty===!0,Nn=le.login!=null,hr=(a||!(z.runtime.runtimeConfig?.aiConnection??fe.aiConnection))&&on&&Pt?.driver==="sandbox"&&!!ut&&!!f&&!!Xs&&(!Nn||Zs),qn=(0,m.useCallback)(async()=>{if(!f)throw new Error("Select an organization to test adapter environment");vs(!0),qs(null),Ct.reset();try{return await Ct.mutateAsync()}catch(pt){throw qs(pt instanceof Error?pt.message:"Environment test failed"),pt}finally{vs(!1)}},[f,Ct]),qr=(0,m.useRef)(()=>{});(0,m.useEffect)(()=>{qr.current=()=>{Yn||qn().catch(()=>{})}},[qn,Yn]);const Cr=(0,m.useCallback)(()=>{qr.current()},[]);(0,m.useEffect)(()=>{if(!(!l||!e.onTestActionChange))return e.onTestActionChange(Cr),()=>{e.onTestActionChange?.(null)}},[l,e.onTestActionChange,Cr]),(0,m.useEffect)(()=>{if(!(!l||!e.onTestActionStateChange))return e.onTestActionStateChange({disabled:Yn,pending:os}),()=>{e.onTestActionStateChange?.({disabled:!0,pending:!1})}},[l,e.onTestActionStateChange,Yn,os]),(0,m.useEffect)(()=>{if(e.onTestFeedbackChange)return e.onTestFeedbackChange({errorMessage:Bs??(Ct.error instanceof Error?Ct.error.message:Ct.error?"Environment test failed":null),result:Ct.data??null,login:hr&&f&&ut?{companyId:f,adapterType:de,environmentId:ut}:null}),()=>{e.onTestFeedbackChange?.({errorMessage:null,result:null,login:null})}},[e.onTestFeedbackChange,Bs,Ct.data,Ct.error,hr,f,de,ut]);const pr=a?ue.model??"":G("adapterConfig","model",String(pe.model??"")),Cn=typeof pr=="string"?pr:"";async function Nr(){if(f){xt(!0),ge(null);try{const pt=await Nt.adapterModels(f,de,{refresh:!0,environmentId:Ot||null,provider:be});x.setQueryData(Lt,pt)}catch(pt){ge(pt instanceof Error?pt.message:"Failed to refresh adapter models.")}finally{xt(!1)}}}r(Nr,"handleRefreshModels");const Or=de==="codex_local"?"modelReasoningEffort":de==="cursor"?"mode":de==="opencode_local"?"variant":de==="grok_local"?"reasoningEffort":de==="pi_local"||de==="omp_local"?"thinking":"effort",Ur=de==="codex_local"?iV(Cn,"Auto").map(pt=>({id:pt.value,label:pt.label})):de==="cursor"?Dut:de==="opencode_local"?Put:de==="kimi_local"?Out:de==="pi_local"?[{id:"",label:"Auto"},...["off","minimal","low","medium","high","xhigh"].map(pt=>({id:pt,label:pt}))]:de==="claude_local"||de==="grok_local"?[{id:"",label:"Auto"},...vE(de,Cn).map(pt=>({id:pt,label:pt==="xhigh"?"X-High":pt[0].toUpperCase()+pt.slice(1)}))]:$ut,ga=de==="omp_local",ar=a?ga?String(ue.adapterSchemaValues?.thinking??""):ue.thinkingEffort:de==="codex_local"?G("adapterConfig","modelReasoningEffort",String(pe.modelReasoningEffort??pe.reasoningEffort??"")):de==="cursor"?G("adapterConfig","mode",String(pe.mode??"")):de==="opencode_local"?G("adapterConfig","variant",String(pe.variant??"")):G("adapterConfig",Or,String(pe[Or]??"")),ur=de!=="gemini_local"&&de!=="cursor_cloud"&&de!=="paperclip_runner"&&!ga,gt=r(pt=>{if(a){Fe(ga?{adapterSchemaValues:{...ue.adapterSchemaValues,thinking:pt??void 0}}:{thinkingEffort:pt??""});return}X("adapterConfig",Or,pt||void 0)},"setThinkingEffort"),Ge=de==="codex_local"?a?!!ue.search:G("adapterConfig","search",!!pe.search):!1,es=(0,m.useMemo)(()=>{if(a)return{heartbeat:{enabled:ue.heartbeatEnabled,intervalSec:ue.intervalSec}};const pt={...fe.heartbeat&&typeof fe.heartbeat=="object"?fe.heartbeat:{},...z.heartbeat};return{...fe,heartbeat:pt}},[a,z.heartbeat,fe,ue]),hs=Tee(es.heartbeat),As=Tee(hs.maxTurnContinuation),ss=J$e(As.enabled,!0),ks=p6(kee(As.maxAttempts,But),0,eae),kn=p6(kee(As.delayMs,Fut*1e3)/1e3,0,H_e);function vn(pt){X("heartbeat","maxTurnContinuation",{...As,...pt})}r(vn,"updateMaxTurnContinuation");const Un=(0,t.jsx)(kj,{ref:g,onDirtyChange:V,hideDraftActions:!a&&e.hideInlineSave,value:a?ue.envBindings??TS:G("adapterConfig","env",pe.env??TS),secrets:y,userSecretDefinitions:k,onCreateSecret:r(async(pt,Is)=>await F.mutateAsync({name:pt,value:Is}),"onCreateSecret"),onChange:r(pt=>a?Fe({envBindings:pt??{},envVars:""}):X("adapterConfig","env",pt),"onChange")},ne);return!a&&e.content==="secrets"?(0,t.jsxs)("div",{className:W("relative",i&&"space-y-6"),children:[oe&&!e.hideInlineSave&&(0,t.jsx)("div",{className:"sticky top-0 z-10 flex items-center justify-end border-b border-primary/20 bg-background/90 px-4 py-2 backdrop-blur-sm",children:(0,t.jsxs)("div",{className:"flex items-center gap-3",children:[(0,t.jsx)("span",{className:"text-xs text-muted-foreground",children:"Unsaved changes"}),(0,t.jsx)($,{size:"sm",onClick:ce,disabled:e.isSaving,children:e.isSaving?"Saving...":"Save"})]})}),e.environmentVariablesPlacement==="secrets"&&(0,t.jsxs)("div",{"data-config-section":"environment-variables",className:W(!i&&"border-b border-border"),children:[i?(0,t.jsx)("h3",{className:"mb-3 text-sm font-medium",children:"Environment variables"}):(0,t.jsx)("div",{className:"px-4 py-2 text-xs font-medium text-muted-foreground",children:"Environment variables"}),(0,t.jsx)("div",{className:W(i?"rounded-lg border border-border p-4":"px-4 pb-3"),children:Un})]}),(0,t.jsxs)("div",{"data-config-section":"secrets",className:W(!i&&"border-b border-border"),children:[i?(0,t.jsx)("h3",{className:"mb-3 text-sm font-medium",children:"Secret access"}):(0,t.jsx)("div",{className:"px-4 py-2 text-xs font-medium text-muted-foreground",children:"Secret access"}),(0,t.jsxs)("div",{className:W(i?"space-y-3 rounded-lg border border-border p-4":"space-y-3 px-4 pb-3"),children:[(0,t.jsx)("p",{className:"text-xs text-muted-foreground",children:wi.secretAccess}),(0,t.jsx)(yut,{config:{...pe,...z.adapterConfig},secrets:y,onChange:re,onCreateSecret:r((pt,Is)=>F.mutateAsync({name:pt,value:Is}),"onCreateSecret"),proposals:S,onApproveProposal:C.requestApprove,onRejectProposal:C.requestReject}),C.dialogs]})]})]}):(0,t.jsxs)(qut,{order:e.sectionOrder,className:W("relative",i&&"space-y-6"),children:[oe&&!e.hideInlineSave&&(0,t.jsx)("div",{className:"sticky top-0 z-10 flex items-center justify-end px-4 py-2 bg-background/90 backdrop-blur-sm border-b border-primary/20",children:(0,t.jsxs)("div",{className:"flex items-center gap-3",children:[(0,t.jsx)("span",{className:"text-xs text-muted-foreground",children:"Unsaved changes"}),(0,t.jsx)($,{size:"sm",onClick:ce,disabled:!a&&e.isSaving,children:!a&&e.isSaving?"Saving...":"Save"})]})}),!a&&(0,t.jsxs)("div",{"data-config-section":"identity",className:W(!i&&"border-b border-border"),children:[i?(0,t.jsx)("h3",{className:"text-sm font-medium mb-3",children:e.sectionTitles?.identity??"Identity"}):(0,t.jsx)("div",{className:"px-4 py-2 text-xs font-medium text-muted-foreground",children:"Identity"}),(0,t.jsxs)("div",{className:W(i?"border border-border rounded-lg p-4 space-y-3":"px-4 pb-3 space-y-3"),children:[(0,t.jsx)(Ss,{label:"Name",hint:wi.name,children:(0,t.jsx)(Wa,{value:G("identity","name",e.agent.name),onCommit:r(pt=>X("identity","name",pt),"onCommit"),immediate:!0,className:Ch,placeholder:"Agent name"})}),(0,t.jsx)(Ss,{label:"Title",hint:wi.title,children:(0,t.jsx)(Wa,{value:G("identity","title",e.agent.title??""),onCommit:r(pt=>X("identity","title",pt||null),"onCommit"),immediate:!0,className:Ch,placeholder:"e.g. VP of Engineering"})}),(0,t.jsx)(Ss,{label:"Reports to",hint:wi.reportsTo,children:(0,t.jsx)(Edt,{agents:Dt,value:G("identity","reportsTo",e.agent.reportsTo??null),onChange:r(pt=>X("identity","reportsTo",pt),"onChange"),excludeAgentIds:[e.agent.id],chooseLabel:"Choose manager…"})}),Le&&!e.hidePromptTemplate&&(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)(Ss,{label:"Prompt Template",hint:wi.promptTemplate,children:(0,t.jsx)(Xc,{value:G("adapterConfig","promptTemplate",String(pe.promptTemplate??"")),onChange:r(pt=>X("adapterConfig","promptTemplate",pt??""),"onChange"),placeholder:"You are agent {{ agent.name }}. Your role is {{ agent.role }}...",contentClassName:"min-h-(--sz-88px) text-sm font-mono",imageUploadHandler:r(async pt=>{const Is=`agents/${e.agent.id}/prompt-template`;return(await q.mutateAsync({file:pt,namespace:Is})).contentPath},"imageUploadHandler")})}),(0,t.jsx)("div",{className:"rounded-md border border-amber-500/25 bg-amber-500/10 px-3 py-2 text-xs text-amber-900 dark:text-amber-100",children:"Prompt template is replayed on every heartbeat. Keep it compact and dynamic to avoid recurring token cost and cache churn."})]})]})]}),Q?(0,t.jsxs)("div",{"data-config-section":"environment",className:W(!i&&(a?"border-t border-border":"border-b border-border")),children:[i?(0,t.jsx)("h3",{className:"text-sm font-medium mb-3",children:"Environment"}):(0,t.jsx)("div",{className:"px-4 py-2 text-xs font-medium text-muted-foreground",children:"Environment"}),(0,t.jsx)("div",{className:W(i?"border border-border rounded-lg p-4 space-y-3":"px-4 pb-3 space-y-3"),children:(0,t.jsx)(Ss,{label:"Default environment",hint:"This instance runs all agents in the Kubernetes sandbox. Local execution is disabled.",children:L?(0,t.jsxs)("div",{className:W(Ch,"flex items-center text-muted-foreground"),children:[L.name," · Kubernetes sandbox"]}):(0,t.jsx)("div",{className:"rounded-md border border-amber-500/25 bg-amber-500/10 px-3 py-2 text-xs text-amber-800 dark:text-amber-200",children:"This instance requires the Kubernetes sandbox, but no managed Kubernetes environment is available for this organization yet. Configure one before creating agents; execution will not fall back to local."})})})]}):Oe?(0,t.jsxs)("div",{"data-config-section":"environment",className:W(!i&&(a?"border-t border-border":"border-b border-border")),children:[i?(0,t.jsx)("h3",{className:"text-sm font-medium mb-3",children:"Environment"}):(0,t.jsx)("div",{className:"px-4 py-2 text-xs font-medium text-muted-foreground",children:"Environment"}),(0,t.jsx)("div",{className:W(i?"border border-border rounded-lg p-4 space-y-3":"px-4 pb-3 space-y-3"),children:(0,t.jsx)(Ss,{label:"Environment override",children:(0,t.jsx)("div",{className:"space-y-2",children:(0,t.jsxs)("select",{className:Ch,value:Ot,onChange:r(pt=>{const Is=pt.target.value;if(a){Fe({defaultEnvironmentId:Is});return}X("identity","defaultEnvironmentId",Is||null)},"onChange"),children:[(0,t.jsxs)("option",{value:"",children:["Default: ",Pe]}),Be.map(pt=>(0,t.jsx)("option",{value:pt.id,children:wN(pt)},pt.id))]})})})})]}):null,(0,t.jsxs)("div",{"data-config-section":"adapter",className:W(!i&&(a?"border-t border-border":"border-b border-border")),children:[(0,t.jsxs)("div",{className:W(i?"flex items-center justify-between mb-3":"px-4 py-2 flex items-center justify-between gap-2"),children:[i?(0,t.jsx)("h3",{className:"text-sm font-medium",children:e.sectionTitles?.adapter??"Adapter"}):(0,t.jsx)("span",{className:"text-xs font-medium text-muted-foreground",children:"Adapter"}),c&&(0,t.jsx)($,{type:"button",variant:"outline",size:"sm",className:"h-7 px-2.5 text-xs",onClick:Cr,disabled:Yn,children:os?`${Rn}...`:Rn})]}),(0,t.jsxs)("div",{className:W(i?"border border-border rounded-lg p-4 space-y-3":"px-4 pb-3 space-y-3"),children:[o&&(0,t.jsx)(Ss,{label:"Adapter type",hint:wi.adapterType,children:(0,t.jsx)(Y_e,{value:Re?"openai_dot":de,disabledTypes:R,openAiDotEnabled:_?.enableOpenAiDot===!0,onChange:r(pt=>{const Is=pt==="openai_dot",dn=Is?"paperclip_runner":pt;if(a){const{adapterType:_n,...fn}=Ab,Sr={...fn,adapterType:dn};dn==="codex_local"?Sr.dangerouslyBypassSandbox=!0:dn==="gemini_local"?Sr.model="auto":dn==="kimi_local"?Sr.model="kimi-code/kimi-for-coding":dn==="cursor"?Sr.model="auto":dn==="opencode_local"?Sr.model="openai/gpt-5.2-codex":dn==="paperclip_runner"&&(Sr.model=bN),Is&&(Sr.model="",Sr.adapterSchemaValues={provider:"openai_dot"}),Fe(Sr)}else K(_n=>({..._n,adapterType:dn,adapterConfig:{model:dn==="gemini_local"?"auto":dn==="kimi_local"?"kimi-code/kimi-for-coding":dn==="opencode_local"?"openai/gpt-5.2-codex":dn==="cursor"?"auto":Is?"":dn==="paperclip_runner"?Rut(de,pe.model):"",effort:"",modelReasoningEffort:"",variant:"",mode:"",...dn==="codex_local"?{dangerouslyBypassApprovalsAndSandbox:!0}:Is?{provider:"openai_dot",lifecycleMode:"per_turn",allowUnmeteredProvider:!1,dotAttachmentAccess:!1,dotWorkspaceAccess:!1}:dn==="paperclip_runner"?{...$Ce(de,G("adapterConfig","model",pe.model))}:{}}}))},"onChange")})}),!Re&&!a&&f&&(0,t.jsx)(pz,{companyId:f,agentId:e.agent.id,agentName:e.agent.name,adapterType:zee(de,G("adapterConfig","provider",pe.provider),G("adapterConfig","acpxAgent",pe.acpxAgent)),routerAdapterType:de,value:Bee.safeParse(z.runtime.runtimeConfig?.aiConnection??fe.aiConnection).data,model:String(G("adapterConfig","model",pe.model)??""),environmentId:Ot||void 0,legacy:!0,onChange:r(pt=>X("runtime","runtimeConfig",{...fe,aiConnection:pt}),"onChange")}),d&&!e.compactTestFeedback&&(Bs||Ct.error)&&(0,t.jsx)("div",{className:"rounded-md border border-destructive/30 bg-destructive/10 px-3 py-2 text-xs text-destructive",children:Bs??(Ct.error instanceof Error?Ct.error.message:"Environment test failed")}),d&&!e.compactTestFeedback&&Ct.data&&(0,t.jsx)(Gut,{result:Ct.data}),d&&hr&&(0,t.jsx)(SV,{companyId:f,adapterType:de,environmentId:ut,onStored:a?bt:et,onApplyStored:a?it:_t,onAccountBinding:a?void 0:qe},`${de}:${ut}`),je&&(0,t.jsx)(Ss,{label:"Working directory (deprecated)",hint:wi.cwd,children:(0,t.jsxs)("div",{className:"flex items-center gap-2 rounded-md border border-border px-2.5 py-1.5",children:[(0,t.jsx)(nl,{className:"h-3.5 w-3.5 text-muted-foreground shrink-0"}),(0,t.jsx)(Wa,{value:a?ue.cwd:G("adapterConfig","cwd",String(pe.cwd??"")),onCommit:r(pt=>a?Fe({cwd:pt}):X("adapterConfig","cwd",pt||void 0),"onCommit"),immediate:!0,className:"w-full bg-transparent outline-none text-sm font-mono placeholder:text-muted-foreground/40",placeholder:"/path/to/project"}),(0,t.jsx)(nu,{})]})}),Ls("adapter"),Le&&(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)(CV,{models:Ht,loadingModels:nt?.isLoading??Os,value:Cn,effort:ga?{value:ar||null,onChange:gt}:void 0,onChange:r(pt=>{ga&&!hM(ar,pt,Ht.map(_n=>Ik(_n,!1)))&&gt(null);const Is=vE(de,pt),dn=["codex_local","claude_local","grok_local"].includes(de)&&!!ar&&!Is.includes(String(ar));if(a){Fe({model:pt,...dn?{thinkingEffort:""}:{}});return}X("adapterConfig","model",nt?.resolveModel(pt)||pt||void 0),dn&&(X("adapterConfig",Or,void 0),X("adapterConfig","reasoningEffort",void 0))},"onChange"),open:Ee,onOpenChange:jt,defaultLabel:de==="claude_local"?"Default (claude-opus-5)":void 0,allowDefault:de!=="opencode_local"&&de!=="pi_local"&&de!=="paperclip_runner",required:de==="opencode_local"||de==="pi_local",groupByProvider:!nt&&(de==="opencode_local"||de==="pi_local"),preserveOrder:!!nt||lV(de),creatable:!0,detectedModel:nt?void 0:Vt,detectedModelCandidates:[],onDetectModel:nt||de==="opencode_local"||de==="paperclip_runner"?void 0:async()=>(await he()).data?.model??null,onRefreshModels:nt?nt.refreshModels:Tut(de)?Nr:void 0,refreshingModels:nt?.refreshing??Xe,detectModelLabel:"Detect model",emptyDetectHint:"No model detected. Select or enter one manually."}),(Ke||ht)&&(0,t.jsx)("p",{className:"text-xs text-destructive",children:Ke??(ht instanceof Error?ht.message:"Failed to load adapter models.")}),de==="opencode_local"&&!nt&&at&&at.driver!=="local"&&(0,t.jsxs)("p",{className:"text-xs text-muted-foreground",children:["Live OpenCode model discovery only runs for Local environments. Using the curated list and manual entry for ",at.name,"."]}),ur&&(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)(Yut,{value:ar,options:Ur,onChange:r(pt=>a?Fe({thinkingEffort:pt}):X("adapterConfig",Or,pt||void 0),"onChange"),open:ze,onOpenChange:St}),de==="codex_local"&&Ge&&ar==="minimal"&&(0,t.jsx)("p",{className:"text-xs text-amber-400",children:"Codex may reject `minimal` thinking when search is enabled."})]})]})]})]}),(0,t.jsxs)("div",{"data-config-section":"configuration",className:W(!i&&"border-b border-border"),children:[i?(0,t.jsx)("h3",{className:"text-sm font-medium mb-3",children:"Configuration"}):(0,t.jsx)("div",{className:"px-4 py-2 text-xs font-medium text-muted-foreground",children:"Configuration"}),(0,t.jsxs)("div",{className:W(i?"border border-border rounded-lg p-4 space-y-3":"px-4 pb-3 space-y-3"),children:[!a&&typeof pe.bootstrapPromptTemplate=="string"&&pe.bootstrapPromptTemplate&&(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)(Ss,{label:"Bootstrap prompt (legacy)",hint:wi.bootstrapPrompt,children:(0,t.jsx)(Xc,{value:G("adapterConfig","bootstrapPromptTemplate",String(pe.bootstrapPromptTemplate??"")),onChange:r(pt=>X("adapterConfig","bootstrapPromptTemplate",pt||void 0),"onChange"),placeholder:"Optional initial setup prompt for the first run",contentClassName:"min-h-(--sz-44px) text-sm font-mono",imageUploadHandler:r(async pt=>{const Is=`agents/${e.agent.id}/bootstrap-prompt`;return(await q.mutateAsync({file:pt,namespace:Is})).contentPath},"imageUploadHandler")})}),(0,t.jsx)("div",{className:"rounded-md border border-amber-500/25 bg-amber-500/10 px-3 py-2 text-xs text-amber-800 dark:text-amber-200",children:"Bootstrap prompt is legacy and will be removed in a future release. Consider moving this content into the agent's prompt template or instructions file instead."})]}),Ls("configuration"),(Le||de==="process"||Bt?.fields.some(pt=>bz(pt.key)==="advanced"))&&(0,t.jsx)(o6,{title:"Advanced",open:mr,onToggle:r(()=>pn(!mr),"onToggle"),children:(0,t.jsxs)("div",{className:"space-y-3",children:[Le&&(0,t.jsxs)(t.Fragment,{children:[" ",!E&&(0,t.jsx)(Ss,{label:"Command",hint:wi.localCommand,children:(0,t.jsx)(Wa,{value:a?ue.command:G("adapterConfig",zt,String(pe.command??"")),onCommit:r(pt=>a?Fe({command:pt}):X("adapterConfig",zt,pt||null),"onCommit"),immediate:!0,className:Ch,placeholder:{claude_local:"claude",codex_local:"codex",gemini_local:"gemini",kimi_local:"kimi",pi_local:"pi",cursor:"agent",opencode_local:"opencode"}[de]??de.replace(/_local$/,"")})}),(0,t.jsx)(Ss,{label:"Extra args (comma-separated)",hint:wi.extraArgs,children:(0,t.jsx)(Wa,{value:a?ue.extraArgs:G("adapterConfig","extraArgs",Mut(pe.extraArgs)),onCommit:r(pt=>a?Fe({extraArgs:pt}):X("adapterConfig","extraArgs",pt?.trim()?Lut(pt):null),"onCommit"),className:Ch,placeholder:"e.g. --verbose, --foo=bar"})})]}),Ls("advanced")]})})]})]}),e.environmentVariablesPlacement!=="secrets"&&(Le||Bt?.fields.some(pt=>bz(pt.key)==="environment"))&&(0,t.jsxs)("div",{"data-config-section":"environment-variables",className:W(!i&&"border-b border-border"),children:[i?(0,t.jsx)("h3",{className:"text-sm font-medium mb-3",children:"Environment variables"}):(0,t.jsx)("div",{className:"px-4 py-2 text-xs font-medium text-muted-foreground",children:"Environment variables"}),(0,t.jsx)("div",{className:W(i?"border border-border rounded-lg p-4 space-y-3":"px-4 pb-3 space-y-3"),children:Le?Un:Ls("environment")})]}),a&&u?(0,t.jsxs)("div",{"data-config-section":"run-policy",className:W(!i&&"border-b border-border"),children:[i?(0,t.jsxs)("h3",{className:"text-sm font-medium flex items-center gap-2 mb-3",children:[(0,t.jsx)(fC,{className:"h-3 w-3"})," Run Policy"]}):(0,t.jsxs)("div",{className:"px-4 py-2 text-xs font-medium text-muted-foreground flex items-center gap-2",children:[(0,t.jsx)(fC,{className:"h-3 w-3"})," Run Policy"]}),(0,t.jsxs)("div",{className:W(i?"border border-border rounded-lg p-4 space-y-3":"px-4 pb-3 space-y-3"),children:[(0,t.jsx)(fre,{label:"Heartbeat on interval",hint:wi.heartbeatInterval,checked:ue.heartbeatEnabled,onCheckedChange:r(pt=>Fe({heartbeatEnabled:pt}),"onCheckedChange"),number:ue.intervalSec,onNumberChange:r(pt=>Fe({intervalSec:pt}),"onNumberChange"),numberLabel:"sec",numberPrefix:"Run heartbeat every",numberHint:wi.intervalSec,showNumber:ue.heartbeatEnabled}),(0,t.jsx)(o6,{title:"Advanced Run Policy",open:_s,onToggle:r(()=>cn(!_s),"onToggle"),children:(0,t.jsx)("div",{className:"space-y-3",children:Ls("runPolicy")})})]})]}):a?null:(0,t.jsxs)("div",{"data-config-section":"run-policy",className:W(!i&&"border-b border-border"),children:[i?(0,t.jsxs)("h3",{className:"text-sm font-medium flex items-center gap-2 mb-3",children:[(0,t.jsx)(fC,{className:"h-3 w-3"})," Run Policy"]}):(0,t.jsxs)("div",{className:"px-4 py-2 text-xs font-medium text-muted-foreground flex items-center gap-2",children:[(0,t.jsx)(fC,{className:"h-3 w-3"})," Run Policy"]}),(0,t.jsxs)("div",{className:W(i?"border border-border rounded-lg overflow-hidden":""),children:[(0,t.jsx)("div",{className:W(i?"p-4 space-y-3":"px-4 pb-3 space-y-3"),children:(0,t.jsx)(fre,{label:"Heartbeat on interval",hint:wi.heartbeatInterval,checked:G("heartbeat","enabled",ve.enabled===!0),onCheckedChange:r(pt=>X("heartbeat","enabled",pt),"onCheckedChange"),number:G("heartbeat","intervalSec",Number(ve.intervalSec??300)),onNumberChange:r(pt=>X("heartbeat","intervalSec",pt),"onNumberChange"),numberLabel:"sec",numberPrefix:"Run heartbeat every",numberHint:wi.intervalSec,showNumber:G("heartbeat","enabled",ve.enabled===!0)})}),(0,t.jsx)(o6,{title:"Advanced Run Policy",bordered:i,open:_s,onToggle:r(()=>cn(!_s),"onToggle"),children:(0,t.jsxs)("div",{className:"space-y-3",children:[Ls("runPolicy"),Le&&(0,t.jsx)(t.Fragment,{children:!a&&(0,t.jsxs)(t.Fragment,{children:[!Bt?.fields.some(pt=>pt.key==="timeoutSec")&&(0,t.jsx)(Ss,{label:"Timeout (sec)",hint:wi.timeoutSec,children:(0,t.jsx)(Wc,{value:G("adapterConfig","timeoutSec",Number(pe.timeoutSec??0)),onCommit:r(pt=>X("adapterConfig","timeoutSec",pt),"onCommit"),immediate:!0,className:Ch})}),!Bt?.fields.some(pt=>pt.key==="graceSec")&&(0,t.jsx)(Ss,{label:"Interrupt grace period (sec)",hint:wi.graceSec,children:(0,t.jsx)(Wc,{value:G("adapterConfig","graceSec",Number(pe.graceSec??15)),onCommit:r(pt=>X("adapterConfig","graceSec",pt),"onCommit"),immediate:!0,className:Ch})})]})}),(0,t.jsx)(yl,{label:"Wake on demand",hint:wi.wakeOnDemand,checked:G("heartbeat","wakeOnDemand",ve.wakeOnDemand!==!1),onChange:r(pt=>X("heartbeat","wakeOnDemand",pt),"onChange")}),(0,t.jsx)(Ss,{label:"Cooldown (sec)",hint:wi.cooldownSec,children:(0,t.jsx)(Wc,{value:G("heartbeat","cooldownSec",Number(ve.cooldownSec??10)),onCommit:r(pt=>X("heartbeat","cooldownSec",pt),"onCommit"),immediate:!0,className:Ch})}),(0,t.jsx)(Ss,{label:"Max concurrent runs",hint:wi.maxConcurrentRuns,children:(0,t.jsx)(Wc,{value:G("heartbeat","maxConcurrentRuns",Number(ve.maxConcurrentRuns??20)),onCommit:r(pt=>X("heartbeat","maxConcurrentRuns",pt),"onCommit"),immediate:!0,className:Ch})}),(0,t.jsxs)("div",{className:"rounded-md border border-border/70 px-3 py-2",children:[(0,t.jsx)(yl,{label:"Continue after max-turn stop",hint:wi.maxTurnContinuationEnabled,checked:ss,onChange:r(pt=>vn({enabled:pt}),"onChange")}),ss?(0,t.jsxs)("div",{className:"mt-3 grid gap-3 sm:grid-cols-2",children:[(0,t.jsx)(Ss,{label:"Continuation attempts",hint:wi.maxTurnContinuationMaxAttempts,children:(0,t.jsx)(Wc,{value:ks,onCommit:r(pt=>vn({maxAttempts:p6(pt,0,eae)}),"onCommit"),immediate:!0,className:Ch})}),(0,t.jsx)(Ss,{label:"Continuation delay (sec)",hint:wi.maxTurnContinuationDelaySec,children:(0,t.jsx)(Wc,{value:kn,onCommit:r(pt=>vn({delayMs:zut(pt)}),"onCommit"),immediate:!0,className:Ch})})]}):null]})]})})]})]}),!a&&p?(0,t.jsxs)("div",{className:W(!i&&"border-b border-border"),children:[i?(0,t.jsxs)("h3",{className:"mb-3 flex items-center gap-2 text-sm font-medium",children:[(0,t.jsx)(Ky,{className:"h-3 w-3"})," Debugging"]}):(0,t.jsxs)("div",{className:"flex items-center gap-2 px-4 py-2 text-xs font-medium text-muted-foreground",children:[(0,t.jsx)(Ky,{className:"h-3 w-3"})," Debugging"]}),(0,t.jsxs)("div",{className:W("border-border bg-accent/30",i?"rounded-lg border p-4":"mx-4 mb-4 rounded-md border px-3 py-3"),children:[(0,t.jsx)(yl,{label:"Capture raw provider traces",hint:"Stores exact provider traffic for every future run until disabled. Traces may contain sensitive prompts and tool arguments, are administrator-only, and expire after 24 hours.",checked:G("debug","providerTrace",Ie.providerTrace)==="raw",onChange:r(pt=>X("debug","providerTrace",pt?"raw":void 0),"onChange")}),G("debug","providerTrace",Ie.providerTrace)==="raw"?(0,t.jsxs)("div",{className:"mt-3 flex items-start gap-2 rounded-md border border-border bg-background/60 px-3 py-2 text-xs text-foreground",children:[(0,t.jsx)(Ky,{className:"mt-0.5 h-3.5 w-3.5 shrink-0"}),(0,t.jsx)("span",{children:"Raw tracing is on for future runs. Paperclip keeps at most 64 MiB per run and automatically deletes it after 24 hours."})]}):null]})]}):null,e.compactTestFeedback&&d&&l&&(0,t.jsx)(KCe,{variant:Re?"prerequisites":"connection",state:os?"running":Bs||Ct.error?"fail":Tt?.status??"idle",result:Tt??null,error:Bs??(Ct.error instanceof Error?Ct.error.message:null),onTest:Cr,disabled:Yn})]})}r(V_e,"AgentConfigForm");var Mz=new Set(["authenticated","failed","timed_out","cancelled"]),Pz=2e3;function Dz({value:e,label:s}){const[n,a]=(0,m.useState)(!1),i=(0,m.useRef)(null);return(0,m.useEffect)(()=>()=>{i.current&&clearTimeout(i.current)},[]),(0,t.jsx)($,{type:"button",variant:"ghost",size:"icon-xs","aria-label":s,title:s,className:"text-muted-foreground hover:text-foreground",onClick:r(async()=>{try{await wa(e),a(!0)}catch{a(!1)}i.current&&clearTimeout(i.current),i.current=setTimeout(()=>a(!1),1500)},"onClick"),children:n?(0,t.jsx)(ms,{className:"size-3"}):(0,t.jsx)(br,{className:"size-3"})})}r(Dz,"AdapterLoginCopyButton");function Uut({status:e,message:s}){return e==="authenticated"?(0,t.jsxs)("div",{className:"flex items-center gap-2 text-(length:--text-micro) text-foreground",children:[(0,t.jsx)(ms,{className:"size-3 shrink-0"}),(0,t.jsx)("span",{children:"Authenticated. The environment has credentials now."})]}):(0,t.jsxs)("div",{className:"flex items-start gap-2 text-(length:--text-micro) text-destructive",children:[(0,t.jsx)(Es,{className:"size-3 shrink-0"}),(0,t.jsxs)("span",{children:[e==="timed_out"?"Login timed out":e==="cancelled"?"Login cancelled":"Login failed",s?`: ${s}`:"."]})]})}r(Uut,"AdapterLoginTerminalState");var Kut={claude_local:"Anthropic",codex_local:"OpenAI"};function G_e(e){const s=Kut[e];return s?`Sign in to ${s}`:"Sign in to the environment"}r(G_e,"adapterLoginTitle");function SV(e){return Wj()(e.adapterType).login?.panelMode==="submitted_browser_code"?(0,t.jsx)(Vut,{...e}):(0,t.jsx)(Qut,{...e})}r(SV,"AdapterLoginPanel");var aD=class extends Error{static{r(this,"AdapterLoginConflictError")}sessionId;constructor(e){super("Another sign-in attempt is active. Finish or cancel that attempt before starting a new sign-in."),this.sessionId=e}};function Qut({companyId:e,adapterType:s,environmentId:n,autoStart:a,onConnected:i,onAccountBinding:o,chrome:l="panel",aiConnection:c,onPromptReady:d}){const[u,h]=(0,m.useState)(null),[p,f]=(0,m.useState)(null),[x,g]=(0,m.useState)(null),[v,y]=(0,m.useState)("idle"),k=(0,m.useRef)(!1),w=we({mutationFn:r(()=>Nt.startAdapterAuthLogin(e,s,{environmentId:n,aiConnection:c}),"mutationFn"),onSuccess:r(ae=>{k.current=!1,f(null),g(null),y("idle"),h(ae.sessionId)},"onSuccess"),onError:r(ae=>{f(ae instanceof Error?ae.message:"Could not start the login.")},"onError")}),N=(0,m.useCallback)(()=>{k.current=!1,h(null),g(null),f(null)},[]),S=we({mutationFn:r(()=>Nt.cancelAdapterAuthLogin(e,s,u),"mutationFn"),onSuccess:N,onError:r(ae=>{f(ae instanceof Error?ae.message:"Could not cancel the login.")},"onError")}),C=te({queryKey:["adapter-login-active-session",e,s],queryFn:r(async()=>{try{const ae=await Nt.getActiveAdapterAuthLoginSession(e,s);if(!ae)return null;if(c&&ae.environmentId!==n||!!ae.aiConnection!=!!c||c&&(ae.aiConnection?.provider!==c.provider||ae.aiConnection?.method!==c.method||ae.aiConnection?.connectionId!==c.connectionId||ae.aiConnection?.ownership!==c.ownership||ae.aiConnection?.allAgents!==c.allAgents||JSON.stringify(ae.aiConnection?.agentIds)!==JSON.stringify(c.agentIds)))throw new aD(ae.sessionId);return ae}catch(ae){if(ae instanceof nn&&ae.status===404)return null;throw ae}},"queryFn"),retry:!1,gcTime:0,staleTime:0}),[_,R]=(0,m.useState)(!1),I=te({queryKey:["adapter-login-status",e,s,u],queryFn:r(()=>Nt.getAdapterAuthLoginStatus(e,s,u),"queryFn"),enabled:!!u&&!_,retry:r((ae,oe)=>oe instanceof nn&&oe.status===404?!1:ae<3,"retry"),refetchInterval:r(ae=>{const oe=ae.state.data?.status;return oe&&Mz.has(oe)?!1:Pz},"refetchInterval")});(0,m.useEffect)(()=>{const ae=I.data?.prompt??null;ae&&g(ae)},[I.data]);const T=I.data??w.data??null,E=T?.status??null,P=x,O=E?Mz.has(E):!1,M=!!u&&!O,Q=w.isPending||M||v==="saving",L=(0,m.useRef)(!1);(0,m.useEffect)(()=>{if(L.current||!C.isFetched)return;L.current=!0;const ae=C.data;ae&&(k.current=!0,f(null),g(ae.prompt??null),h(ae.sessionId))},[C.isFetched,C.data]),(0,m.useEffect)(()=>{const ae=I.error;if(!(ae instanceof nn&&ae.status===404)||!k.current||_)return;R(!0);const oe=u;(async()=>(oe&&await Nt.cancelAdapterAuthLogin(e,s,oe).catch(()=>{}),R(!1),N()))()},[I.error,_,u,e,s,N]);const F=(0,m.useRef)(!1),q=we({mutationFn:r(async()=>{const ae=C.error;ae instanceof aD&&await Nt.cancelAdapterAuthLogin(e,s,ae.sessionId)},"mutationFn"),onSuccess:r(async()=>{F.current=!1,L.current=!1,f(null),await C.refetch()},"onSuccess"),onError:r(()=>f("Could not cancel the previous sign-in. Retry before starting a new one."),"onError")}),z=(0,m.useRef)(w.mutate);z.current=w.mutate,(0,m.useEffect)(()=>{if(!(!a||F.current)){if(C.isError){F.current=!0,f(C.error instanceof Error?C.error.message:"Could not check for an active login.");return}C.isSuccess&&(F.current=!0,!C.data&&z.current())}},[a,C.isSuccess,C.isError,C.data,C.error]);const K=(0,m.useRef)(!1),U=(0,m.useRef)(i);U.current=i,(0,m.useEffect)(()=>{E!=="authenticated"||K.current||(K.current=!0,U.current?.(u??void 0))},[E]);const V=(0,m.useRef)(null),ne=(0,m.useRef)(o);ne.current=o;const Z=I.data?.codexAccountBinding??null,ie=(0,m.useCallback)(async ae=>{const oe=ne.current;if(oe){y("saving");try{await oe(ae),y("bound")}catch{y("failed")}}},[]);(0,m.useEffect)(()=>{E!=="authenticated"||!u||V.current!==u&&(!Z||!Z.companyIdentityDiffers||!ne.current||(V.current=u,ie(Z)))},[E,u,Z,ie]);const J=(0,m.useRef)(d);if(J.current=d,(0,m.useEffect)(()=>{J.current?.(P?.url??null)},[P]),l==="onboarding"){const ae=O&&E&&E!=="authenticated";return(0,t.jsx)(fV,{loading:!P&&!p&&!ae,providerName:pV(s),authorizationUrl:P?.url,mode:"displayed_code",children:p?(0,t.jsxs)("div",{children:[(0,t.jsx)("p",{role:"alert",className:"pl-2 text-xs text-destructive",children:p}),C.error instanceof aD&&(0,t.jsx)($,{type:"button",variant:"outline",disabled:q.isPending,onClick:r(()=>q.mutate(),"onClick"),children:"Cancel previous sign-in and retry"})]}):ae?(0,t.jsx)("p",{role:"alert",className:"pl-2 text-xs text-destructive",children:E==="timed_out"?"The login timed out. Start it again.":E==="cancelled"?"The login was cancelled.":"The login did not finish. Start it again."}):(0,t.jsx)(s_e,{code:P?.code??"",autoCopy:!0})})}return(0,t.jsxs)("div",{className:"rounded-md border border-border bg-muted/40 px-3 py-2 flex flex-col gap-2",children:[(0,t.jsxs)("div",{className:"flex items-center justify-between gap-2",children:[(0,t.jsx)("span",{className:"text-xs font-medium text-foreground",children:G_e(s)}),(0,t.jsxs)("div",{className:"flex items-center gap-1.5",children:[M&&(0,t.jsx)($,{type:"button",variant:"ghost",size:"sm",className:"h-7 px-2.5 text-xs text-muted-foreground hover:text-foreground",disabled:S.isPending,onClick:r(()=>S.mutate(),"onClick"),children:"Cancel"}),(0,t.jsx)($,{type:"button",variant:"outline",size:"sm",className:"h-7 px-2.5 text-xs",disabled:Q,onClick:r(()=>w.mutate(),"onClick"),children:"Sign in"})]})]}),p&&(0,t.jsx)("div",{role:"alert",className:"text-(length:--text-micro) text-destructive",children:p}),(0,t.jsxs)("div",{role:"status","aria-live":"polite",className:"space-y-2 empty:hidden",children:[M&&!P&&(0,t.jsxs)("div",{className:"flex items-center gap-2 text-(length:--text-micro) text-muted-foreground",children:[(0,t.jsx)(st,{className:"size-3 animate-spin shrink-0"}),(0,t.jsx)("span",{children:"Preparing..."})]}),M&&P&&(0,t.jsxs)("div",{className:"space-y-2",children:[(0,t.jsx)("div",{className:"text-(length:--text-micro) text-muted-foreground",children:"Copy the code, then open the authentication page."}),(0,t.jsxs)("div",{className:"flex items-center justify-between gap-2",children:[(0,t.jsxs)("div",{className:"min-w-0",children:[(0,t.jsx)("div",{className:"text-(length:--text-micro) uppercase tracking-wide text-muted-foreground",children:"1. Code"}),(0,t.jsx)("span",{className:"font-mono text-xs text-foreground break-all",children:P.code})]}),(0,t.jsx)(Dz,{value:P.code,label:"Copy code"})]}),(0,t.jsxs)("div",{className:"flex items-center justify-between gap-2",children:[(0,t.jsxs)("div",{className:"min-w-0",children:[(0,t.jsx)("div",{className:"text-(length:--text-micro) uppercase tracking-wide text-muted-foreground",children:"2. Authentication URL"}),(0,t.jsx)("span",{className:"font-mono text-xs text-foreground break-all",children:P.url})]}),(0,t.jsxs)("div",{className:"flex items-center",children:[(0,t.jsx)(Dz,{value:P.url,label:"Copy URL"}),(0,t.jsx)($,{asChild:!0,type:"button",variant:"ghost",size:"icon-xs","aria-label":"Open the authentication page",title:"Open the authentication page",className:"text-muted-foreground hover:text-foreground",children:(0,t.jsx)("a",{href:P.url,target:"_blank",rel:"noreferrer noopener",children:(0,t.jsx)($n,{className:"size-3"})})})]})]})]}),O&&E&&(0,t.jsx)(Uut,{status:E,message:T?.failure?.message??null}),E==="authenticated"&&v==="saving"&&(0,t.jsxs)("div",{className:"flex items-center gap-2 text-(length:--text-micro) text-muted-foreground",children:[(0,t.jsx)(st,{className:"size-3 animate-spin shrink-0"}),(0,t.jsx)("span",{children:"Binding this agent to the signed-in account..."})]}),E==="authenticated"&&v==="bound"&&(0,t.jsxs)("div",{className:"flex items-center gap-2 text-(length:--text-micro) text-foreground",children:[(0,t.jsx)(ms,{className:"size-3 shrink-0"}),(0,t.jsx)("span",{children:"Agent bound to the signed-in account."})]}),E==="authenticated"&&v==="failed"&&(0,t.jsxs)("div",{className:"flex items-center gap-2 text-(length:--text-micro)",children:[(0,t.jsx)(Es,{className:"size-3 shrink-0 text-destructive"}),(0,t.jsx)("span",{className:"text-destructive",children:"Could not bind this agent to the signed-in account."}),(0,t.jsx)($,{type:"button",variant:"outline",size:"sm",className:"h-6 px-2 text-xs",onClick:r(()=>{Z&&ie(Z)},"onClick"),children:"Retry"})]})]})]})}r(Qut,"DisplayedCodeLoginPanel");var Wut=new Set(["failed","timed_out","cancelled"]),tae="The login did not finish. Start the login again.",Hut=9e5,sae="The login timed out. Start the login again.";function Vut({companyId:e,adapterType:s,environmentId:n,onStored:a,onApplyStored:i,autoStart:o,onConnected:l,onCodeSubmitted:c,onSubmitFailed:d,chrome:u="panel",aiConnection:h,onPromptReady:p}){const[f,x]=(0,m.useState)(null),[g,v]=(0,m.useState)(null),[y,k]=(0,m.useState)(null),[w,N]=(0,m.useState)(!1),[S,C]=(0,m.useState)(""),[_,R]=(0,m.useState)(null),[I,T]=(0,m.useState)(!1),[E,P]=(0,m.useState)(!1),[O,M]=(0,m.useState)(!1),[Q,L]=(0,m.useState)(!1),F=(0,m.useRef)(!1),[q,z]=(0,m.useState)(!1),K=(0,m.useRef)(!1),U=r(()=>{v(null),k(null),N(!1),C(""),R(null),T(!1),P(!1),L(!1),M(!1),F.current=!1},"resetLocalState"),V=te({queryKey:["claude-oauth-token-status",e],queryFn:r(async()=>{try{return await Nt.getClaudeOAuthTokenStatus(e)}catch(at){if(at instanceof nn&&at.status===404)return null;throw at}},"queryFn"),retry:r((at,Me)=>Me instanceof nn&&Me.status===404?!1:at<2,"retry")}).data??null,ne=we({mutationFn:r(()=>Nt.startClaudeSetupTokenLogin(e,{environmentId:n,aiConnection:h,...V&&!h?{overwrite:{expectedSecretId:V.secretId,expectedLatestVersion:V.latestVersion}}:{}}),"mutationFn"),onSuccess:r(at=>{K.current=!1,U(),x(at.sessionId)},"onSuccess"),onError:r(at=>{v(at instanceof Error?at.message:"Could not start the login.")},"onError")}),Z=r(()=>{K.current=!1,x(null),U()},"clearActiveSession"),ie=we({mutationFn:r(()=>Nt.cancelClaudeSetupTokenLogin(e,f),"mutationFn"),onSuccess:r(()=>{Z()},"onSuccess"),onError:r(at=>{if(at instanceof nn&&at.status===404){Z();return}v(at instanceof Error?at.message:"Could not cancel the login.")},"onError")}),J=(0,m.useCallback)(at=>{Nt.cancelClaudeSetupTokenLogin(e,at).catch(()=>{})},[e]),ae=te({queryKey:["claude-setup-token-active-session",e],queryFn:r(async()=>{try{const at=await Nt.getActiveClaudeSetupTokenLoginSession(e);if(!at)return null;if(h&&at.environmentId!==n||!!at.aiConnection!=!!h||h&&(at.aiConnection?.provider!==h.provider||at.aiConnection?.method!==h.method||at.aiConnection?.connectionId!==h.connectionId||at.aiConnection?.ownership!==h.ownership||at.aiConnection?.allAgents!==h.allAgents||JSON.stringify(at.aiConnection?.agentIds)!==JSON.stringify(h.agentIds)))throw new Error("Another sign-in attempt is active. Finish or cancel it in its original account setup before starting this one.");return at}catch(at){if(at instanceof nn&&at.status===404)return null;throw at}},"queryFn"),retry:!1,gcTime:0,staleTime:0}),[oe,G]=(0,m.useState)(!1),X=!!f&&!E&&!Q&&!oe,Y=te({queryKey:["claude-setup-token-status",e,f],queryFn:r(()=>Nt.getClaudeSetupTokenLoginStatus(e,f),"queryFn"),enabled:X,retry:r((at,Me)=>Me instanceof nn&&Me.status===404?!1:at<3,"retry"),refetchInterval:r(at=>{if(E||Q)return!1;const Me=at.state.data?.status;return Me&&Mz.has(Me)?!1:Pz},"refetchInterval")});(0,m.useEffect)(()=>{const at=Y.error;if(at instanceof nn&&at.status===404){if(K.current){if(oe)return;G(!0);const Me=f;(async()=>(Me&&await Nt.cancelClaudeSetupTokenLogin(e,Me).catch(()=>{}),G(!1),Z()))();return}L(!0)}},[Y.error,oe,f,e]);const re=(0,m.useRef)(!1);(0,m.useEffect)(()=>{if(re.current||!ae.isFetched)return;re.current=!0;const at=ae.data;at&&(K.current=!0,U(),x(at.sessionId),at.prompt&&(k(at.prompt.authorizationUrl),at.prompt.transportAdvisory&&N(!0)))},[ae.isFetched,ae.data]);const se=te({queryKey:["claude-setup-token-prompt",e,f],enabled:X&&!y,queryFn:r(async()=>{try{return await Nt.getClaudeSetupTokenLoginPrompt(e,f)}catch(at){if(at instanceof nn&&at.status===404)return null;throw at}},"queryFn"),refetchInterval:r(at=>E||at.state.data?.authorizationUrl?!1:Pz,"refetchInterval")});(0,m.useEffect)(()=>{const at=se.data?.authorizationUrl??null;at&&k(at),se.data?.transportAdvisory&&N(!0)},[se.data]);const ce=we({mutationFn:r(at=>Nt.submitClaudeSetupTokenBrowserCode(e,f,at),"mutationFn"),onError:r(at=>{v(at instanceof Error?at.message:"Could not submit the browser code.")},"onError")}),pe=we({mutationFn:r(()=>Nt.completeClaudeSetupTokenLogin(e,f),"mutationFn"),onSuccess:r(at=>{R(at.storedSessionId),a?.(at.storedSessionId)},"onSuccess"),onError:r(()=>{T(!0)},"onError")}),fe=Y.data?.status??ne.data?.status??null,ve=Y.data?.expiresAt??ne.data?.expiresAt??null,Ie=(0,m.useRef)(pe.mutate);Ie.current=pe.mutate,(0,m.useEffect)(()=>{fe==="authenticated"&&!F.current&&(F.current=!0,Ie.current())},[fe]);const de=_!==null,xe=I||Q||!!(fe&&Wut.has(fe)),le=fe==="authenticated"&&!de&&!I,Re=!!f&&!de&&!xe&&!E,Le=ne.isPending||Re;(0,m.useEffect)(()=>{if(!Re)return;const at=ve!==null?new Date(ve).getTime():NaN,Me=Number.isFinite(at)?Math.max(0,at-Date.now()):Hut,De=setTimeout(()=>{f&&J(f),P(!0)},Me);return()=>clearTimeout(De)},[Re,ve,f,J]);const je=S.trim(),_e=Re&&!!y&&!le&&i$e(je)&&!ce.isPending&&!O,Ze=(0,m.useRef)(c);Ze.current=c;const ue=(0,m.useRef)(d);ue.current=d;const Fe=r(()=>{_e&&(v(null),ce.mutate(je),M(!0),Ze.current?.(),u!=="onboarding"&&C(""))},"handleSubmit"),mt=(0,m.useRef)(!1),bt=(0,m.useRef)(ne.mutate);bt.current=ne.mutate,(0,m.useEffect)(()=>{if(!(!o||mt.current)){if(ae.isError){mt.current=!0,v(ae.error instanceof Error?ae.error.message:"Could not check for an active login.");return}ae.isSuccess&&(mt.current=!0,!ae.data&&bt.current())}},[o,ae.isSuccess,ae.isError,ae.data,ae.error]);const et=(0,m.useRef)(Fe);et.current=Fe;const qe=u==="onboarding",it=(0,m.useRef)(!1);(0,m.useEffect)(()=>{!qe||!it.current||(it.current=!1,_e&&et.current())},[qe,_e,S]);const _t=(0,m.useRef)(!1),$t=(0,m.useRef)(l);$t.current=l,(0,m.useEffect)(()=>{!de||_t.current||(_t.current=!0,$t.current?.(f??void 0))},[de]),(0,m.useEffect)(()=>{O&&(!g&&!xe&&!E||(M(!1),ue.current?.()))},[O,g,xe,E]);const Ot=(0,m.useRef)(p);if(Ot.current=p,(0,m.useEffect)(()=>{Ot.current?.(y)},[y]),u==="onboarding"){const at=xe||E;return(0,t.jsxs)(fV,{loading:!y&&!g&&!at,providerName:pV(s),authorizationUrl:y??void 0,mode:"submitted_code",children:[w&&(0,t.jsxs)("p",{className:"flex items-start gap-2 pl-2 text-xs text-amber-700 dark:text-amber-200",children:[(0,t.jsx)(Es,{className:"mt-0.5 size-3 shrink-0"}),"This connection is not encrypted. The login code travels in clear text on this network. Continue only on a network you trust."]}),g?(0,t.jsx)("p",{role:"alert",className:"pl-2 text-xs text-destructive",children:g}):at?(0,t.jsx)("p",{role:"alert",className:"pl-2 text-xs text-destructive",children:E&&!xe?sae:tae}):(0,t.jsx)(V3,{value:S,onChange:C,onSubmit:Fe,onPaste:r(()=>{it.current=!0},"onPaste"),masked:!0,disabled:ce.isPending||le||O})]})}return(0,t.jsxs)("div",{className:"rounded-md border border-border bg-muted/40 px-3 py-2 flex flex-col gap-2",children:[(0,t.jsxs)("div",{className:"flex items-center justify-between gap-2",children:[(0,t.jsx)("span",{className:"text-xs font-medium text-foreground",children:G_e(s)}),(0,t.jsxs)("div",{className:"flex items-center gap-1.5",children:[Re&&(0,t.jsx)($,{type:"button",variant:"ghost",size:"sm",className:"h-7 px-2.5 text-xs text-muted-foreground hover:text-foreground",disabled:ie.isPending,onClick:r(()=>ie.mutate(),"onClick"),children:"Cancel"}),i&&V&&!Re&&!de&&!q&&(0,t.jsx)($,{type:"button",variant:"default",size:"sm",className:"h-7 px-2.5 text-xs",onClick:r(()=>{i(),z(!0)},"onClick"),children:"Use saved login"}),(0,t.jsx)($,{type:"button",variant:"outline",size:"sm",className:"h-7 px-2.5 text-xs",disabled:Le,onClick:r(()=>ne.mutate(),"onClick"),children:V&&!Re&&!de?"Sign in to replace":"Sign in"})]})]}),V&&!Re&&!de&&!q&&(0,t.jsx)("div",{className:"text-(length:--text-micro) text-muted-foreground",children:"You have a saved Claude login. Use it to bind this agent, or log in again to replace the stored token."}),q&&(0,t.jsxs)("div",{className:"flex items-center gap-2 text-(length:--text-micro) text-foreground",children:[(0,t.jsx)(ms,{className:"size-3 shrink-0"}),(0,t.jsx)("span",{children:"The saved Claude login is bound to this agent now."})]}),g&&(0,t.jsx)("div",{role:"alert",className:"text-(length:--text-micro) text-destructive",children:g}),(0,t.jsxs)("div",{role:"status","aria-live":"polite",className:"space-y-2 empty:hidden",children:[Re&&!y&&!le&&(0,t.jsxs)("div",{className:"flex items-center gap-2 text-(length:--text-micro) text-muted-foreground",children:[(0,t.jsx)(st,{className:"size-3 animate-spin shrink-0"}),(0,t.jsx)("span",{children:"Preparing..."})]}),Re&&y&&!le&&(0,t.jsxs)("div",{className:"space-y-2",children:[w&&(0,t.jsxs)("div",{className:"flex items-start gap-2 rounded-md border border-amber-300 bg-amber-50 px-2 py-1.5 text-(length:--text-micro) text-amber-800 dark:border-amber-500/40 dark:bg-amber-500/10 dark:text-amber-200",children:[(0,t.jsx)(Es,{className:"size-3 shrink-0 mt-0.5"}),(0,t.jsx)("span",{children:"This connection is not encrypted. The login code travels in clear text on this network. Continue only on a network you trust."})]}),(0,t.jsx)("div",{className:"text-(length:--text-micro) text-muted-foreground",children:"Open the authorization page, then enter the browser code it shows."}),(0,t.jsxs)("div",{className:"flex items-center justify-between gap-2",children:[(0,t.jsxs)("div",{className:"min-w-0",children:[(0,t.jsx)("div",{className:"text-(length:--text-micro) uppercase tracking-wide text-muted-foreground",children:"1. Authorization URL"}),(0,t.jsx)("span",{className:"font-mono text-xs text-foreground break-all",children:y})]}),(0,t.jsxs)("div",{className:"flex items-center",children:[(0,t.jsx)(Dz,{value:y,label:"Copy URL"}),(0,t.jsx)($,{asChild:!0,type:"button",variant:"ghost",size:"icon-xs","aria-label":"Open the authorization page",title:"Open the authorization page",className:"text-muted-foreground hover:text-foreground",children:(0,t.jsx)("a",{href:y,target:"_blank",rel:"noreferrer noopener",children:(0,t.jsx)($n,{className:"size-3"})})})]})]}),(0,t.jsxs)("div",{className:"space-y-1",children:[(0,t.jsx)("div",{className:"text-(length:--text-micro) uppercase tracking-wide text-muted-foreground",children:"2. Browser code"}),(0,t.jsxs)("div",{className:"flex items-center gap-2",children:[(0,t.jsx)("input",{"aria-label":"Browser code",type:"text",autoComplete:"off",spellCheck:!1,value:S,onChange:r(at=>C(at.target.value),"onChange"),onKeyDown:r(at=>{at.key==="Enter"&&(at.preventDefault(),Fe())},"onKeyDown"),className:"flex-1 min-w-0 rounded-md border border-border bg-background px-2 py-1 font-mono text-xs text-foreground"}),(0,t.jsx)($,{type:"button",variant:"outline",size:"sm",className:"h-7 px-2.5 text-xs",disabled:!_e,onClick:Fe,children:"Submit"})]})]})]}),le&&(0,t.jsxs)("div",{className:"flex items-center gap-2 text-(length:--text-micro) text-muted-foreground",children:[(0,t.jsx)(st,{className:"size-3 animate-spin shrink-0"}),(0,t.jsx)("span",{children:"Completing the login…"})]}),de&&(0,t.jsxs)("div",{className:"flex items-center gap-2 text-(length:--text-micro) text-foreground",children:[(0,t.jsx)(ms,{className:"size-3 shrink-0"}),(0,t.jsx)("span",{children:"Authenticated. The environment has credentials now."})]}),xe&&(0,t.jsxs)("div",{className:"flex items-start gap-2 text-(length:--text-micro) text-destructive",children:[(0,t.jsx)(Es,{className:"size-3 shrink-0"}),(0,t.jsx)("span",{children:tae})]}),E&&!xe&&!de&&(0,t.jsxs)("div",{className:"flex items-start gap-2 text-(length:--text-micro) text-destructive",children:[(0,t.jsx)(Es,{className:"size-3 shrink-0"}),(0,t.jsx)("span",{children:sae})]})]})]})}r(Vut,"SubmittedBrowserCodeLoginPanel");function Gut({result:e}){const s=e.status==="pass"?"Passed":e.status==="warn"?"Warnings":"Failed",n=e.status==="pass"?"text-green-700 dark:text-green-300 border-green-300 dark:border-green-500/40 bg-green-50 dark:bg-green-500/10":e.status==="warn"?"text-amber-700 dark:text-amber-300 border-amber-300 dark:border-amber-500/40 bg-amber-50 dark:bg-amber-500/10":"text-red-700 dark:text-red-300 border-red-300 dark:border-red-500/40 bg-red-50 dark:bg-red-500/10";return(0,t.jsxs)("div",{className:`rounded-md border px-3 py-2 text-xs ${n}`,children:[(0,t.jsxs)("div",{className:"flex items-center justify-between gap-2",children:[(0,t.jsx)("span",{className:"font-medium",children:s}),(0,t.jsx)("span",{className:"text-(length:--text-micro) opacity-80",children:new Date(e.testedAt).toLocaleTimeString()})]}),(0,t.jsx)("div",{className:"mt-2 space-y-1.5",children:e.checks.map((a,i)=>(0,t.jsxs)("div",{className:"text-(length:--text-micro) leading-relaxed break-words",children:[(0,t.jsx)("span",{className:"font-medium uppercase tracking-wide opacity-80",children:a.level}),(0,t.jsx)("span",{className:"mx-1 opacity-60",children:"·"}),(0,t.jsx)("span",{children:a.message}),a.detail&&(0,t.jsxs)("span",{className:"block opacity-75 break-all",children:["(",a.detail,")"]}),a.hint&&(0,t.jsxs)("span",{className:"block opacity-90 break-words",children:["Hint: ",a.hint]})]},`${a.code}-${i}`))})]})}r(Gut,"AdapterEnvironmentResult$1");function Y_e({value:e,onChange:s,disabledTypes:n,openAiDotEnabled:a=!1}){const[i,o]=(0,m.useState)(!1),l=th(e),c=(0,m.useMemo)(()=>[...Q_e(d=>m5[d]??kf(d)),...a?[{value:"openai_dot",label:"OpenAI Dot",experimental:!0,comingSoon:!1}]:[]].filter(d=>!n.has(d.value)),[n,a]);return(0,t.jsxs)(dr,{open:i,onOpenChange:o,children:[(0,t.jsx)(wr,{asChild:!0,children:(0,t.jsxs)("button",{type:"button","data-size":"default",className:W(Mze,"w-full"),children:[(0,t.jsxs)("span",{className:"inline-flex min-w-0 items-center gap-1.5",children:[(0,t.jsx)("span",{"aria-hidden":"true",className:"inline-flex shrink-0",children:(0,t.jsx)(q0,{type:e,className:"size-4"})}),(0,t.jsx)("span",{className:"truncate",children:m5[e]??kf(e)}),l.experimental&&(0,t.jsx)(nae,{})]}),(0,t.jsx)(an,{className:"size-4 opacity-50"})]})}),(0,t.jsx)(nr,{className:"w-(--radix-popover-trigger-width) p-1",align:"start",children:c.map(d=>(0,t.jsxs)("button",{type:"button",disabled:d.comingSoon,className:W("flex items-center justify-between w-full px-2 py-1.5 text-sm rounded",d.comingSoon?"opacity-40 cursor-not-allowed":"hover:bg-accent/50",d.value===e&&!d.comingSoon&&"bg-accent"),onClick:r(()=>{d.comingSoon||(s(d.value),o(!1))},"onClick"),children:[(0,t.jsxs)("span",{className:"inline-flex items-center gap-1.5",children:[(0,t.jsx)("span",{"aria-hidden":"true",className:"inline-flex shrink-0",children:(0,t.jsx)(q0,{type:d.value,className:"size-4"})}),(0,t.jsx)("span",{children:d.label}),d.experimental&&(0,t.jsx)(nae,{})]}),d.comingSoon&&(0,t.jsx)("span",{className:"text-(length:--text-nano) text-muted-foreground",children:"Coming soon"})]},d.value))})]})}r(Y_e,"AdapterTypeDropdown");function nae(){return(0,t.jsx)("span",{className:"shrink-0 rounded border border-amber-500/30 bg-amber-500/10 px-1.5 py-0.5 text-(length:--text-nano) font-medium leading-none text-amber-700 dark:text-amber-200",children:"Experimental"})}r(nae,"ExperimentalBadge$1");function CV({models:e,value:s,onChange:n,open:a,onOpenChange:i,allowDefault:o,required:l,groupByProvider:c,preserveOrder:d,creatable:u,detectedModel:h,detectedModelCandidates:p,onDetectModel:f,onRefreshModels:x,refreshingModels:g,loadingModels:v,detectModelLabel:y,emptyDetectHint:k,defaultLabel:w,presentation:N="searchable",effort:S}){const[C,_]=(0,m.useState)(""),[R,I]=(0,m.useState)(!1),[T,E]=(0,m.useState)(!1),P=C.trim(),O=!!(u&&P&&!e.some(K=>K.id.toLowerCase()===P.toLowerCase())),M=(0,m.useMemo)(()=>{const K=new Set;h&&K.add(h);for(const U of p??[])U&&K.add(U);return K},[h,p]),Q=(0,m.useMemo)(()=>e.filter(K=>{if(M.has(K.id))return!1;const U=jE(K.id);return YL({...Ik(K,c),...U&&!K.provider?{group:U}:{}},C)}),[e,C,M,c]),L=(0,m.useMemo)(()=>new Map(e.map(K=>[K.id,Ik(K,c)])),[e,c]),F=s?su(s,[...L.values()]):null,q=(0,m.useMemo)(()=>{if(!c&&Q.some(U=>U.provider)){const U=new Map;for(const V of Q){const ne=V.provider??"other";U.set(ne,[...U.get(ne)??[],V])}return Array.from(U.entries()).map(([V,ne])=>({provider:V,entries:ne}))}if(!c)return[{provider:null,entries:d?Q:[...Q].sort((U,V)=>U.id.localeCompare(V.id))}];const K=new Map;for(const U of Q){const V=jE(U.id)??"other",ne=K.get(V)??[];ne.push(U),K.set(V,ne)}return Array.from(K.entries()).sort(([U],[V])=>U.localeCompare(V)).map(([U,V])=>({provider:U,entries:[...V].sort((ne,Z)=>ne.id.localeCompare(Z.id))}))},[Q,c,d]);async function z(){if(f){E(!0);try{const K=await f();K&&(n(K),i(!1),_(""))}finally{E(!1)}}}if(r(z,"handleDetectModel"),N==="native"){const K="__paperclip_custom_model__",U=[...new Set([s,...M])].filter(V=>!!V&&(!e.some(ne=>ne.id===V)||M.has(V)));return(0,t.jsxs)(Ss,{label:"Model",hint:wi.model,children:[(0,t.jsxs)(eW,{"aria-label":"Model","aria-busy":v||g,value:R?K:s,required:l&&!R,onChange:r(V=>{const ne=V.target.value;I(ne===K),ne!==K&&n(ne)},"onChange"),children:[(0,t.jsx)("option",{value:"",disabled:!o,children:o?w??"Default":v?"Loading models…":l?"Select model (required)":"Select model"}),U.map(V=>(0,t.jsx)("option",{value:V,children:e.find(ne=>ne.id===V)?.label??V},V)),q.map(({provider:V,entries:ne})=>c?(0,t.jsx)("optgroup",{label:V??void 0,children:ne.map(Z=>(0,t.jsx)("option",{value:Z.id,children:Z.label},Z.id))},V):ne.map(Z=>(0,t.jsx)("option",{value:Z.id,children:Z.label},Z.id))),u&&(0,t.jsx)("option",{value:K,children:"Enter custom model…"})]}),R&&(0,t.jsxs)("label",{className:"mt-3 block space-y-1 text-xs text-muted-foreground",children:["Model ID",(0,t.jsx)(dt,{"aria-label":"Model ID",value:s,onChange:r(V=>n(V.target.value),"onChange"),placeholder:"Enter model ID or alias",autoFocus:!0,required:l})]}),v&&(0,t.jsx)("p",{role:"status",className:"mt-2 text-xs text-muted-foreground",children:"Loading models…"}),x&&(0,t.jsx)($,{type:"button",variant:"ghost",size:"sm",disabled:g,onClick:r(()=>{x()},"onClick"),children:g?"Refreshing…":"Refresh models"})]})}return(0,t.jsx)(Ss,{label:"Model",hint:wi.model,children:(0,t.jsxs)(dr,{open:a,onOpenChange:r(K=>{i(K),K||_("")},"onOpenChange"),children:[(0,t.jsx)(wr,{asChild:!0,children:(0,t.jsxs)("button",{type:"button","aria-label":"Model",className:"flex w-full min-w-0 items-center gap-2 rounded-md border border-border px-2.5 py-1.5 text-left text-sm transition-colors hover:bg-accent/50","data-testid":"model-dropdown-trigger",children:[F?(0,t.jsx)(jf,{display:F,layout:"inline",className:"min-w-0 flex-1"}):(0,t.jsx)("span",{className:"min-w-0 flex-1 truncate text-muted-foreground",children:o?w??"Default":l?"Select model (required)":"Select model"}),S&&s&&yj(S.value,s,[...L.values()])?(0,t.jsxs)("span",{className:W("shrink-0 text-xs",S.value?"text-foreground":"text-muted-foreground"),"data-testid":"model-dropdown-effort-value",children:["· ",S.value??"Auto effort"]}):null,(0,t.jsx)(an,{className:"size-4 shrink-0 text-muted-foreground"})]})}),(0,t.jsxs)(nr,{className:"w-(--radix-popover-trigger-width) p-1",align:"start",children:[S&&s&&yj(S.value,s,[...L.values()])?(0,t.jsxs)("div",{className:"-mx-1 -mt-1 mb-1 space-y-1.5 border-b border-border px-2.5 py-2",children:[(0,t.jsx)("span",{className:"block text-xs font-medium text-muted-foreground",children:"Thinking effort"}),(0,t.jsx)(pM,{levels:Xx(s,[...L.values()]),value:S.value,onChange:r(K=>{S.onChange(K),i(!1)},"onChange"),defaultLabel:"Auto",label:"Thinking effort",testId:"model-dropdown-effort"})]}):null,(0,t.jsxs)("div",{className:"relative -mx-1 -mt-1 mb-1 border-b border-border",children:[(0,t.jsx)(Yr,{className:"pointer-events-none absolute left-2.5 top-1/2 size-4 -translate-y-1/2 text-muted-foreground","aria-hidden":"true"}),(0,t.jsx)("input",{"aria-label":"Search models",className:"h-9 w-full bg-transparent pl-8 pr-7 text-sm outline-none placeholder:text-muted-foreground",placeholder:u?C2:"Search models",value:C,onChange:r(K=>_(K.target.value),"onChange"),autoFocus:!0}),C&&(0,t.jsx)("button",{type:"button","aria-label":"Clear search",className:"absolute right-2.5 top-1/2 -translate-y-1/2 text-muted-foreground hover:text-foreground",onClick:r(()=>_(""),"onClick"),children:(0,t.jsxs)("svg",{"aria-hidden":"true",focusable:"false",className:"h-3 w-3",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,t.jsx)("line",{x1:"18",y1:"6",x2:"6",y2:"18"}),(0,t.jsx)("line",{x1:"6",y1:"6",x2:"18",y2:"18"})]})})]}),f&&!C.trim()&&(0,t.jsxs)("button",{type:"button",className:"flex items-center gap-1.5 w-full px-2 py-1.5 text-xs rounded hover:bg-accent/50 text-muted-foreground",onClick:r(()=>{z()},"onClick"),disabled:T,children:[(0,t.jsxs)("svg",{"aria-hidden":"true",focusable:"false",className:"h-3 w-3",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,t.jsx)("path",{d:"M21 12a9 9 0 0 0-9-9 9.75 9.75 0 0 0-6.74 2.74L3 8"}),(0,t.jsx)("path",{d:"M3 3v5h5"})]}),T?"Detecting...":h?y?.replace(/^Detect\b/,"Re-detect")??"Re-detect from config":y??"Detect from config"]}),x&&!C.trim()&&(0,t.jsxs)("button",{type:"button",className:"flex items-center gap-1.5 w-full px-2 py-1.5 text-xs rounded hover:bg-accent/50 text-muted-foreground",onClick:r(()=>{x()},"onClick"),disabled:g,children:[(0,t.jsxs)("svg",{"aria-hidden":"true",focusable:"false",className:"h-3 w-3",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,t.jsx)("path",{d:"M3 12a9 9 0 0 1 15.28-6.36L21 8"}),(0,t.jsx)("path",{d:"M21 3v5h-5"}),(0,t.jsx)("path",{d:"M21 12a9 9 0 0 1-15.28 6.36L3 16"}),(0,t.jsx)("path",{d:"M8 16H3v5"})]}),g?"Refreshing...":"Refresh models"]}),s&&(!e.some(K=>K.id===s)||M.has(s))&&(0,t.jsxs)("button",{type:"button",className:W("flex items-center w-full px-2 py-1.5 text-sm rounded bg-accent/50"),onClick:r(()=>{i(!1)},"onClick"),children:[F?(0,t.jsx)(jf,{display:F,layout:"inline",className:"flex-1"}):null,(0,t.jsx)(ot,{variant:"outline",className:"ml-auto text-(length:--text-nano) px-1.5 bg-green-500/15 text-green-400 border-green-500/20",children:"current"})]}),h&&h!==s&&(0,t.jsxs)("button",{type:"button",className:W("flex items-center w-full px-2 py-1.5 text-sm rounded hover:bg-accent/50"),onClick:r(()=>{n(h),i(!1)},"onClick"),children:[(0,t.jsx)("span",{className:"block w-full text-left truncate font-mono text-xs",title:h,children:e.find(K=>K.id===h)?.label??h}),(0,t.jsx)(ot,{variant:"outline",className:"ml-auto text-(length:--text-nano) px-1.5 bg-blue-500/15 text-blue-400 border-blue-500/20",children:"detected"})]}),p?.filter(K=>K&&K!==h&&K!==s).map(K=>{const U=e.find(V=>V.id===K);return(0,t.jsxs)("button",{type:"button",className:W("flex items-center w-full px-2 py-1.5 text-sm rounded hover:bg-accent/50"),onClick:r(()=>{n(K),i(!1)},"onClick"),children:[(0,t.jsx)("span",{className:"block w-full text-left truncate font-mono text-xs",title:K,children:U?.label??K}),(0,t.jsx)(ot,{variant:"outline",className:"ml-auto text-(length:--text-nano) px-1.5 bg-sky-500/15 text-sky-400 border-sky-500/20",children:"config"})]},`detected-${K}`)}),(0,t.jsxs)("div",{className:"max-h-(--sz-240px) overflow-y-auto",children:[o&&(0,t.jsx)("button",{type:"button",className:W("flex items-center gap-2 w-full px-2 py-1.5 text-sm rounded hover:bg-accent/50",!s&&"bg-accent"),onClick:r(()=>{n(""),i(!1)},"onClick"),children:"Default"}),O&&(0,t.jsxs)("button",{type:"button",className:"flex items-center justify-between gap-2 w-full px-2 py-1.5 text-sm rounded hover:bg-accent/50",onClick:r(()=>{n(P),i(!1),_("")},"onClick"),children:[(0,t.jsx)("span",{children:"Use manual model"}),(0,t.jsx)("span",{className:"text-xs font-mono text-muted-foreground",children:P})]}),q.map(K=>(0,t.jsxs)("div",{className:"mb-1 last:mb-0",children:[K.provider&&(0,t.jsx)(JL,{provider:K.provider,testId:`model-dropdown-group-${K.provider}`}),K.entries.map(U=>(0,t.jsxs)("button",{type:"button",className:W("flex items-center gap-2 w-full px-2 py-1.5 text-left text-sm rounded hover:bg-accent/50",U.id===s&&"bg-accent"),onClick:r(()=>{n(U.id),S&&Xx(U.id,[...L.values()]).length>0||i(!1)},"onClick"),children:[(0,t.jsx)(ZL,{option:L.get(U.id)??Ik(U,c)}),U.id===s?(0,t.jsx)(ms,{className:"size-4 shrink-0","aria-hidden":"true"}):null]},U.id))]},K.provider??"")),Q.length===0&&!O&&M.size===0&&(0,t.jsx)("div",{className:"px-2 py-2 space-y-2",children:(0,t.jsx)("p",{className:"text-xs text-muted-foreground",children:v?"Loading models…":f?k??"No model detected yet. Enter a provider/model manually.":"No models found."})})]})]})]})})}r(CV,"ModelDropdown");function Yut({value:e,options:s,onChange:n,open:a,onOpenChange:i}){const o=s.find(l=>l.id===e)??s[0];return(0,t.jsx)(Ss,{label:"Thinking effort",hint:wi.thinkingEffort,children:(0,t.jsxs)(dr,{open:a,onOpenChange:i,children:[(0,t.jsx)(wr,{asChild:!0,children:(0,t.jsxs)("button",{className:"inline-flex items-center gap-1.5 rounded-md border border-border px-2.5 py-1.5 text-sm hover:bg-accent/50 transition-colors w-full justify-between",children:[(0,t.jsx)("span",{className:W(!e&&"text-muted-foreground"),children:o?.label??"Auto"}),(0,t.jsx)(an,{className:"h-3 w-3 text-muted-foreground"})]})}),(0,t.jsx)(nr,{className:"w-(--radix-popover-trigger-width) p-1",align:"start",children:s.map(l=>(0,t.jsxs)("button",{className:W("flex items-center justify-between w-full px-2 py-1.5 text-sm rounded hover:bg-accent/50",l.id===e&&"bg-accent"),onClick:r(()=>{n(l.id),i(!1)},"onClick"),children:[(0,t.jsx)("span",{children:l.label}),l.id?(0,t.jsx)("span",{className:"text-xs text-muted-foreground font-mono",children:l.id}):null]},l.id||"auto"))})]})})}r(Yut,"ThinkingEffortDropdown");function Z_e(e){const s=`paperclip.agent-appearance.${e}`;function n(){try{const l=ube.safeParse(JSON.parse(sessionStorage.getItem(s)??"null"));if(l.success)return l.data}catch{}const o=zT();try{sessionStorage.setItem(s,JSON.stringify(o))}catch{}return o}r(n,"readDraft");const[a,i]=(0,m.useState)(()=>({key:s,appearance:n()}));return a.key!==s&&i({key:s,appearance:n()}),{appearance:a.appearance,clear(){try{sessionStorage.removeItem(s)}catch{}}}}r(Z_e,"useAgentAppearanceDraft");var RS=null,TI=new Set,ES={subscribe(e){return TI.add(e),()=>{TI.delete(e)}},getSnapshot(){return RS},acquire(e){if(RS)return!1;RS=e;for(const s of TI)s();return!0},release(e){if(RS===e){RS=null;for(const s of TI)s()}}};function NN({agent:e,appearance:s,size:n=256,state:a="idle",muted:i=!1,motion:o="auto",trackingRegion:l,trackingScope:c="region",followCursor:d=!0,followRotation:u=!0,className:h,label:p,name:f}){const x=(0,m.useMemo)(()=>sv(s??e?.appearance,e?.id),[s,e?.appearance,e?.id]),g=(0,m.useRef)(null),v=(0,m.useRef)(null),y=(0,m.useRef)(null),k=(0,m.useRef)(Symbol("agent-character")),w=(0,m.useSyncExternalStore)(ES.subscribe,ES.getSnapshot,()=>null),[N,S]=(0,m.useState)(!1),[C,_]=(0,m.useState)(!0),[R,I]=(0,m.useState)(!1),[T,E]=(0,m.useState)(!1),P=!x.customAvatarAssetId&&N&&!C&&!R&&o==="auto"&&a!=="rest";return(0,m.useEffect)(()=>{if(typeof matchMedia!="function"||typeof IntersectionObserver!="function")return;const O=matchMedia("(prefers-reduced-motion: reduce)"),M=r(()=>_(O.matches),"change");M(),O.addEventListener("change",M);const Q=new IntersectionObserver(L=>S(L[0]?.isIntersecting??!1));return g.current&&Q.observe(g.current),()=>{Q.disconnect(),O.removeEventListener("change",M)}},[]),(0,m.useEffect)(()=>{P&&w===null&&ES.acquire(k.current),P||ES.release(k.current)},[P,w]),(0,m.useEffect)(()=>()=>ES.release(k.current),[]),(0,m.useEffect)(()=>{if(!P||w!==k.current)return;let O=!1;return E(!1),Promise.all([bd(()=>import("./runtime-IAg0vdY9.js"),__vite__mapDeps([0,1])),bd(()=>import("./definition-BTeHNPYD.js"),__vite__mapDeps([2,3,1]))]).then(([M,Q])=>{O||!v.current||(y.current=M.createCharacter(v.current,Q.characterDefinition(x,i),{animation:Q.animationId(a),trackingRegion:l?.current??g.current??void 0,followCursor:d,followRotation:u,trackingScope:c,displaySize:n,onError:r(()=>I(!0),"onError")}),E(!0))}).catch(()=>{O||I(!0)}),()=>{O=!0,y.current?.destroy(),y.current=null,E(!1)}},[P,w,l,c,n,d,u]),(0,m.useEffect)(()=>{y.current&&bd(()=>import("./definition-BTeHNPYD.js").then(O=>{y.current?.setDefinition(O.characterDefinition(x,i)),y.current?.setAnimation(O.animationId(a))}),__vite__mapDeps([2,3,1]))},[x,i,a,T]),(0,t.jsxs)("span",{ref:g,role:p?"img":void 0,"aria-label":p,"aria-hidden":p?void 0:!0,className:W("relative inline-block shrink-0",gze[n],h),children:[(0,t.jsx)(lr,{agent:e,appearance:x,size:n<256?256:n,name:f,pose:a,muted:i,className:W("size-full",T&&!x.customAvatarAssetId&&"invisible")}),(0,t.jsx)("span",{ref:v,className:"absolute inset-0"})]})}r(NN,"AgentCharacter");var Zut=new Set(["claude_local","codex_local","opencode_local","grok_local"]);function J_e(e,{cloud:s,nativeRunnerEnabled:n,openAiDotEnabled:a=!1,runnerProvider:i}){return e==="openai_dot"||e==="paperclip_runner"&&i==="openai_dot"?a:e==="paperclip_runner"?n:s?Zut.has(e):!0}r(J_e,"isNewAgentAdapterAllowed");function Jut(){const{selectedCompanyId:e}=fs(),{appearance:s}=Z_e(`${e}:new-agent`);return(0,t.jsx)(NN,{appearance:s,state:"sleepy",muted:!0,size:256,className:"size-48",trackingScope:"page"})}r(Jut,"AgentBasicsCharacter");function X_e({open:e,onClose:s,onContinue:n,initialAdapter:a="",onInvite:i}){const o=(0,m.useId)(),l=!!td(),c=te({queryKey:D.instance.experimentalSettings,queryFn:jr.getExperimental,enabled:e,retry:!1}),[d,u]=(0,m.useState)(""),[h,p]=(0,m.useState)(a),[f,x]=(0,m.useState)("codex"),[g,v]=(0,m.useState)("name"),{data:y,isPending:k,error:w}=te({queryKey:D.adapters.all,queryFn:Oh.list,enabled:e}),N=(y??[]).filter(C=>C.loaded&&!C.disabled&&J_e(C.type,{cloud:l,nativeRunnerEnabled:c.data?.enableNativeRunner===!0})&&!["process","http"].includes(C.type)&&!th(C.type).comingSoon),S=N.some(C=>C.type===h);return(0,t.jsx)(Fs,{open:e,onOpenChange:r(C=>{C||s()},"onOpenChange"),children:(0,t.jsxs)(Qs,{className:W("flex max-h-(--sz-calc-18) flex-col gap-0 overflow-hidden p-0 sm:max-w-(--sz-640px)",g==="name"&&"sm:max-w-(--sz-560px)"),children:[(0,t.jsxs)("div",{className:"flex items-center gap-2 px-6 py-5 text-xs text-muted-foreground","aria-label":"New agent progress",children:[(0,t.jsx)("span",{className:W(g==="name"&&"font-medium text-foreground"),children:"1. Name"}),(0,t.jsx)(Ln,{className:"size-3"}),(0,t.jsx)("span",{className:W(g==="adapter"&&"font-medium text-foreground"),children:"2. Adapter"})]}),(0,t.jsxs)("form",{className:"flex min-h-0 flex-col",onSubmit:r(C=>{C.preventDefault(),d.trim()&&(g==="name"?v("adapter"):S&&n({name:d.trim(),adapterType:h==="openai_dot"?"paperclip_runner":h,runnerProvider:h==="openai_dot"?"openai_dot":f}))},"onSubmit"),children:[(0,t.jsxs)("div",{className:"flex min-h-0 flex-col gap-7 overflow-y-auto px-6 pb-8 sm:px-10",children:[(0,t.jsxs)("div",{className:"flex flex-col items-center gap-4 text-center",children:[e&&(0,t.jsx)(Jut,{}),(0,t.jsxs)("div",{className:"space-y-2",children:[(0,t.jsx)(Ks,{className:"text-3xl font-semibold tracking-tight",children:g==="name"?"Meet your next agent":"Choose an adapter"}),(0,t.jsx)(mn,{className:"text-base",children:g==="name"?"Start with a name. Make them your own.":`How should ${d.trim()} work?`})]})]}),g==="name"?(0,t.jsxs)("div",{className:"space-y-2",children:[(0,t.jsx)("label",{htmlFor:o,className:"text-sm font-medium",children:"Agent name"}),(0,t.jsx)(dt,{id:o,autoFocus:!0,maxLength:100,placeholder:"e.g. Darnold",value:d,onChange:r(C=>u(C.target.value),"onChange"),className:"h-12 text-base"}),i&&(0,t.jsx)($,{type:"button",variant:"link",className:"px-0 text-muted-foreground",onClick:i,children:"Invite an external agent"})]}):(0,t.jsxs)("fieldset",{className:"space-y-4",children:[(0,t.jsx)("legend",{className:"sr-only",children:"Adapter"}),k&&(0,t.jsx)("p",{role:"status",className:"text-sm text-muted-foreground",children:"Loading adapters…"}),w&&(0,t.jsx)("p",{role:"alert",className:"text-sm text-destructive",children:w.message}),(0,t.jsx)("div",{className:W("grid grid-cols-2 gap-3",N.length!==4&&"sm:grid-cols-3"),children:N.map(C=>{const _=th(C.type);return(0,t.jsxs)("label",{className:"relative cursor-pointer",children:[(0,t.jsx)("input",{type:"radio",name:"new-agent-adapter",value:C.type,checked:h===C.type,onChange:r(()=>p(C.type),"onChange"),className:"peer sr-only"}),(0,t.jsxs)("span",{className:W("flex h-full flex-col items-center gap-2 rounded-lg border px-3 py-4 text-center peer-focus-visible:ring-2 peer-focus-visible:ring-ring hover:bg-accent/40",h===C.type?"border-foreground/40 bg-accent":"border-border bg-card"),children:[(0,t.jsx)(q0,{type:C.type}),(0,t.jsx)("span",{className:"text-sm font-medium",children:_.label}),h===C.type&&(0,t.jsx)(ms,{className:"absolute right-2 top-2 size-3.5"})]})]},C.type)})}),S&&h==="paperclip_runner"&&(0,t.jsxs)("label",{className:"flex flex-col gap-2 text-sm font-medium",children:["Runner",(0,t.jsxs)("select",{className:"rounded-md border border-border bg-background px-3 py-2",value:f,onChange:r(C=>x(C.target.value),"onChange"),children:[(0,t.jsx)("option",{value:"codex",children:"Codex (app server)"}),(0,t.jsx)("option",{value:"claude",children:"Claude (ACPX)"}),(0,t.jsx)("option",{value:"grok",children:"Grok Build (ACPX)"}),(0,t.jsx)("option",{value:"opencode",children:"OpenCode"})]})]})]})]}),(0,t.jsxs)("div",{className:"flex justify-between gap-4 border-t border-border px-6 py-4",children:[(0,t.jsx)($,{type:"button",variant:"ghost",onClick:r(()=>g==="name"?s():v("name"),"onClick"),children:g==="name"?"Cancel":(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)(wl,{className:"size-4"}),"Back"]})}),(0,t.jsxs)($,{type:"submit",disabled:!d.trim()||g==="adapter"&&!S,children:[g==="name"?"Choose adapter":"Configure agent",(0,t.jsx)(pl,{className:"size-4"})]})]})]})]})})}r(X_e,"AgentBasicsDialog");var Xut={subscription:"Subscription",api:"API key",advanced:"Custom Gateway"};function emt({mode:e}){return(0,t.jsx)("span",{className:"relative flex h-4 w-full items-center justify-center overflow-hidden text-(length:--text-micro) text-muted-foreground",children:(0,t.jsx)(S2,{initial:!1,mode:"sync",children:(0,t.jsx)(Rl.span,{className:"absolute inset-0 flex items-center justify-center whitespace-nowrap",initial:{opacity:0,y:bre},animate:{opacity:1,y:0,transition:Nit},exit:{opacity:0,y:bre,transition:Sit},children:Xut[e]},e)})})}r(emt,"CredentialTag");function tmt({source:e,mode:s,selected:n,onSelect:a,buttonRef:i,settling:o}){return(0,t.jsxs)("button",{ref:i,type:"button",role:"radio","aria-checked":n,onClick:a,className:W("flex min-w-0 flex-1 cursor-pointer flex-col items-center gap-1.5 self-stretch rounded-md border p-3","transition-(--tp-border-color-background-color) ease-(--motion-ease-standard)",o?"duration-(--motion-duration-slow)":"duration-(--motion-duration-fast)","outline-none focus-visible:ring-ring/50 focus-visible:ring-(length:--rad-3)",n?"border-foreground/40 bg-accent":"border-border bg-card hover:bg-accent/40"),children:[(0,t.jsx)("span",{className:"flex size-(--sz-30px) shrink-0 items-center justify-center",children:e.icon}),(0,t.jsx)("span",{className:"text-(length:--text-compact) font-medium text-foreground",children:e.label}),s?(0,t.jsx)(emt,{mode:s}):(0,t.jsx)("span",{"aria-hidden":!0,className:"h-4"})]})}r(tmt,"ModelSourceTile");function e5e({sources:e,mode:s,selectedId:n,onSelect:a,label:i,collapsed:o=!1,settling:l=!1}){const c=(0,m.useRef)(new Map),d=r(h=>{if(e.length===0)return;const p=e.findIndex(x=>x.id===n),f=e[((p===-1?h>0?-1:0:p)+h+e.length)%e.length];a(f.id),c.current.get(f.id)?.focus()},"moveSelection"),u=o?e.filter(h=>h.id===n):e;return(0,t.jsx)("div",{role:"radiogroup","aria-label":i,className:W("flex items-start gap-3",o&&"justify-center"),onKeyDown:r(h=>{o||(h.key==="ArrowRight"||h.key==="ArrowDown"?(h.preventDefault(),d(1)):(h.key==="ArrowLeft"||h.key==="ArrowUp")&&(h.preventDefault(),d(-1)))},"onKeyDown"),children:(0,t.jsx)(S2,{initial:!1,mode:"popLayout",children:u.map(h=>(0,t.jsx)(Rl.div,{layout:!0,transition:e_e,exit:{opacity:0,transition:Pit},className:W("flex min-w-0",o?"w-(--sz-source-tile-two-up)":"flex-1"),children:(0,t.jsx)(tmt,{source:h,mode:h.credentialMode===void 0?s:h.credentialMode,selected:h.id===n,onSelect:r(()=>a(h.id),"onSelect"),settling:l,buttonRef:r(p=>{p?c.current.set(h.id,p):c.current.delete(h.id)},"buttonRef")})},h.id))})})}r(e5e,"ModelSourceTiles");var iD={subscription:"Use subscription instead",api:"Use API key instead"},smt=["subscription","api"],rae={subscription:"api",api:"subscription"};function t5e({mode:e,onChange:s}){return(0,t.jsx)(nmt,{destination:rae[e],onClick:r(()=>s(rae[e]),"onClick"),modes:smt})}r(t5e,"CredentialModeLink");function nmt({destination:e,onClick:s,modes:n}){return(0,t.jsxs)("button",{type:"button","aria-label":iD[e],onClick:s,className:W("group grid cursor-pointer px-3 py-2 text-left text-sm font-medium","rounded-md outline-none focus-visible:ring-ring/50 focus-visible:ring-(length:--rad-3)"),children:[n.map(a=>(0,t.jsx)("span",{"aria-hidden":!0,className:"invisible col-start-1 row-start-1 whitespace-nowrap",children:iD[a]},a)),(0,t.jsx)(S2,{initial:!1,mode:"sync",children:(0,t.jsx)(Rl.span,{className:W("col-start-1 row-start-1 justify-self-start whitespace-nowrap","underline decoration-muted-foreground/40 underline-offset-4","text-muted-foreground transition-colors","group-hover:text-foreground group-hover:decoration-foreground/40"),initial:{opacity:0},animate:{opacity:1,transition:hV},exit:{opacity:0,transition:Cit},children:iD[e]},e)})]})}r(nmt,"ModeLink");function $z({onBack:e,primaryLabel:s,primaryDisabled:n,loading:a,loadingLabel:i,primaryIcon:o,onPrimary:l}){const c=a&&i?i:s,d=o??(a?"spinner":"arrow");return(0,t.jsxs)("div",{className:"flex items-center justify-between pt-9",children:[e?(0,t.jsxs)($,{variant:"ghost",size:"lg",className:"rounded-full has-[>svg]:pl-4 has-[>svg]:pr-5",onClick:e,disabled:a,children:[(0,t.jsx)(wl,{className:"mr-1 size-3.5"}),"Back"]}):(0,t.jsx)("span",{}),(0,t.jsx)(Rl.div,{layout:!0,transition:Iit,className:"min-w-0",children:(0,t.jsx)($,{size:"lg",className:"w-full rounded-full px-6",onClick:l,disabled:n||a,children:(0,t.jsxs)(Rl.span,{className:"flex items-center whitespace-nowrap",initial:{opacity:0},animate:{opacity:1},transition:Tit,children:[d==="spinner"?(0,t.jsx)(st,{className:"mr-1 size-4 animate-spin"}):null,c,d==="arrow"?(0,t.jsx)(pl,{className:"ml-1 size-3.5"}):null]},`${c}:${d}`)})})]})}r($z,"FooterNav");function s5e({companyId:e,adapterType:s,environmentId:n,canLogin:a,localEnvironment:i=!1,onConnected:o,onDraftChanged:l,onBack:c,testConnection:d,testError:u,managedAccount:h,advancedConnection:p}){const f=te({queryKey:D.health,queryFn:Lu.get,enabled:i}),x=i&&(f.data?.localAiLoginSupported??f.data?.deploymentMode==="local_trusted"),g=(0,m.useRef)(0);(0,m.useEffect)(()=>()=>{g.current++},[]);const v=r(()=>{g.current++,Q(!1),C(!1),R(null),T("preparing")},"cancel"),[y,k]=(0,m.useState)(h?.initialMethod==="api_key"?"api":h?"subscription":null),[w,N]=(0,m.useState)(!1),[S,C]=(0,m.useState)(!!(p||h)),[_,R]=(0,m.useState)(null),[I,T]=(0,m.useState)("preparing"),E=(0,m.useRef)("ready"),[P,O]=(0,m.useState)(""),[M,Q]=(0,m.useState)(!1),[L,F]=(0,m.useState)(null),[q,z]=(0,m.useState)(null),K=s==="claude_local"?"Claude":s==="grok_local"?"Grok":"OpenAI",U=s==="claude_local"?"ANTHROPIC_API_KEY":s==="grok_local"?"XAI_API_KEY":"OPENAI_API_KEY",V=s==="claude_local"?"anthropic":s==="grok_local"?"xai":"openai",ne=TCe(e,U),Z=h?{...ne,options:[],subscriptions:[],loading:!1}:ne,[ie,J]=(0,m.useState)(null),ae=Z.subscriptions.length?Z.subscriptions.find(Re=>Re.id===(ie??Z.subscriptions[0]?.id)):void 0,[oe,G]=(0,m.useState)(null),X=Z.options.find(Re=>Re.id===(oe??Z.options[0]?.id)),Y=h?{...Z.storedLogin,data:void 0,isPending:!1,isError:!1}:Z.storedLogin,re=(0,m.useRef)(null),se=y??(Z.subscriptions.length>0||s==="claude_local"&&!ae&&Y.data?"subscription":Z.options.length?"api":"subscription"),ce=se==="api"?"api_key":"subscription",pe=h?.intent.connectionId&&(h.fixedMethod!==!1||h.initialMethod===ce),fe=h?{...h.intent,connectionId:pe?h.intent.connectionId:void 0,name:pe?h.intent.name:h.nameForMethod?.(ce)??h.intent.name}:void 0,ve=G2e(e,fe??{provider:V,method:"subscription",name:`My ${K} subscription`,ownership:"personal",agentIds:[],allAgents:!0},!w&&x&&se==="subscription"&&!ae&&!Y.data),Ie=te({queryKey:D.agents.authSignal(e,s,n),queryFn:r(()=>Nt.getAdapterAuthSignal(e,s,n??void 0),"queryFn"),retry:!1,enabled:!h&&!w});async function de(){if(M||h?.disabled)return;const Re=++g.current;Q(!0),F(null);try{if(h&&fe){if(se==="subscription"&&!x)return;const _e=re.current??await(se==="api"?Ll.create(e,{...fe,method:"api_key",apiKey:P.trim()}):ve.connect(fe));re.current=_e,O(""),Re===g.current&&h.onComplete({..._e,method:se==="api"?"api_key":"subscription"});return}let Le=se==="api"?X?X.aiConnection?{env:{},aiConnection:X.aiConnection}:{env:{[U]:X.binding}}:q??{env:{},credentials:{[U]:P.trim()}}:{...ae?.aiConnection?{aiConnection:ae.aiConnection}:{},env:ae?.binding?{CODEX_HOME:ae.binding}:{},...s==="claude_local"&&!ae&&Y.data?{env:tk(),applyStoredClaudeLogin:!0}:{}};if(se==="subscription"&&x&&!ae&&!Y.data&&(re.current??=await ve.connect(),Le={env:{},aiConnection:{provider:V,method:"subscription",mode:"responsible_user"}}),Le.credentials&&(await Ll.create(e,{provider:V,method:"api_key",name:`My ${K} API`,ownership:"personal",apiKey:Le.credentials[U],agentIds:[],allAgents:!0}),Le={env:{},aiConnection:{provider:V,method:"api_key",mode:"responsible_user"}}),Re!==g.current)return;se==="api"&&(O(""),X||z(Le));const je=await d(Le);if(Re!==g.current)return;je?o(Le):F("The provider did not respond. Check the connection and try again.")}catch(Le){if(Re!==g.current)return;h&&O(""),F(Le instanceof Error?Le.message:"Could not connect to the provider.")}finally{Re===g.current&&Q(!1)}}r(de,"connect");const xe=se==="subscription"&&a&&n&&!ae&&!Z.loading&&!Y.data&&(!!h||Ie.data?.status!=="present"||ie===""),le=r(Re=>{p&&Re===(w?"advanced":se)||(l?.(),v(),N(Re==="advanced"),C(p?!0:S),re.current=null,Re!=="advanced"&&k(Re),O(""),z(null),F(null))},"switchMode");return(0,t.jsxs)("div",{className:"min-w-0 max-w-full",children:[(0,t.jsx)(e5e,{label:p?"Connection type":"Connect your model provider",sources:p?[{id:"subscription",label:K,icon:(0,t.jsx)(q0,{type:s}),credentialMode:"subscription"},{id:"api",label:K,icon:(0,t.jsx)(q0,{type:s}),credentialMode:"api"},{id:"advanced",label:"Advanced",icon:(0,t.jsx)(tKe,{className:"size-6 text-muted-foreground"}),credentialMode:"advanced"}]:[{id:s,label:K,icon:(0,t.jsx)(q0,{type:s})}],mode:w?"advanced":se,selectedId:p?w?"advanced":se:S?s:null,collapsed:!p&&S,onSelect:r(Re=>{h?.disabled||(p?le(Re):C(!0))},"onSelect")}),!p&&(!S||h)&&!h?.fixedMethod&&(0,t.jsx)("div",{className:"-ml-3 mt-1",children:(0,t.jsx)(t5e,{mode:se,onChange:le})}),w&&p?(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)("div",{className:"pt-5",children:p.content}),(0,t.jsx)($z,{onBack:c,primaryLabel:"Use connection",primaryDisabled:!p.value,onPrimary:r(()=>{p.value&&o({env:{},aiConnection:p.value})},"onPrimary")})]}):(0,t.jsxs)(t.Fragment,{children:[!S&&Z.options.length>0&&(0,t.jsxs)("p",{className:"mt-2 text-sm text-muted-foreground",children:[Z.options.length," saved API"," ",Z.options.length===1?"key available":"keys available","."]}),se==="subscription"&&Z.subscriptions.length>0&&(0,t.jsx)("div",{className:p?"pt-5":void 0,children:(0,t.jsx)(Ak,{options:Z.subscriptions,value:ae?.id??"",onChange:r(Re=>{l?.(),J(Re)},"onChange"),loading:!1,error:!1,kind:"subscription",disabled:M})}),(0,t.jsx)(Rl.div,{initial:!1,animate:{height:S?"auto":0,opacity:S?1:0},transition:{height:Yd,opacity:gM},className:"overflow-hidden",children:S&&(0,t.jsx)("div",{className:"pt-5",children:se==="api"?(0,t.jsxs)(bM,{instruction:Z.options.length?"Choose a saved API key or enter a new one":`Provide your ${K} API key to connect`,children:[(0,t.jsx)(Ak,{...Z,value:X?.id??"",disabled:M,onChange:r(Re=>{l?.(),G(Re),O(""),z(null),F(null)},"onChange")}),!X&&(0,t.jsx)(V3,{label:"API key",masked:!0,autoFocus:!0,value:P,placeholder:q?"Key entered. Retry the connection.":"Enter API key here",onChange:r(Re=>{l?.(),G(""),O(Re),z(null)},"onChange"),onSubmit:r(()=>{de()},"onSubmit"),disabled:M})]}):xe?(0,t.jsx)(SV,{companyId:e,adapterType:s,environmentId:n,chrome:"onboarding",aiConnection:fe??{provider:V,method:"subscription",name:`My ${K} subscription`,ownership:"personal",agentIds:[],allAgents:!0},autoStart:!0,onStored:r(()=>{},"onStored"),onPromptReady:r(Re=>{R(Re),T(Le=>Re?Le==="preparing"?"ready":Le:"preparing")},"onPromptReady"),onCodeSubmitted:r(()=>{E.current=I==="waiting"?"waiting":"ready",T("connecting")},"onCodeSubmitted"),onSubmitFailed:r(()=>{T(Re=>Re==="connecting"?E.current:Re)},"onSubmitFailed"),onConnected:r(Re=>{if(h){if(!Re){F("The login did not return a saved connection. Try again.");return}const je=g.current;T("connecting"),Ll.loginResult(e,Re).then(_e=>{je===g.current&&h.onComplete({..._e,method:"subscription"})}).catch(()=>{je===g.current&&(T("ready"),F("Could not retrieve the saved connection. Go back and retry."))});return}const Le={env:{},aiConnection:{provider:V,method:"subscription",mode:"responsible_user"}};z(Le),o(Le)},"onConnected")}):ae?null:x&&!Y.data?(0,t.jsx)(xV,{adapterType:s,login:{...ve,retry:r(()=>{F(null),ve.retry()},"retry")}}):(0,t.jsx)("p",{className:"text-sm text-muted-foreground",children:Y.data?"Use your saved Claude subscription for this agent.":a?"Use the existing provider connection for this environment.":"This environment does not support browser sign-in. Choose a sign-in environment or connect with an API key."})})}),se==="subscription"&&Y.isError&&(0,t.jsx)("p",{role:"alert",className:"mt-4 text-sm text-destructive",children:"Could not check your saved Claude subscription. Try again."}),L&&(0,t.jsx)("p",{role:"alert",className:"mt-4 text-sm text-destructive",children:u??L}),i&&f.isError&&(0,t.jsx)("p",{role:"alert",className:"mt-4 text-sm text-destructive",children:"Could not prepare sign-in. Reload this page to try again."}),(0,t.jsx)($z,{onBack:r(()=>{S&&!p?v():c()},"onBack"),primaryLabel:S&&xe?I==="waiting"?"Waiting for code":I==="connecting"?"Connecting":`Sign in to ${K}`:M?"Connecting":se==="subscription"&&(Y.data||ae)?"Use saved subscription":se==="api"&&X?"Use saved API key":"Connect",primaryDisabled:h?.disabled||!!h&&se==="subscription"&&!a&&!x||i&&f.isPending||ve.preparing||!!ve.error||se==="subscription"&&x&&!ae&&!Y.data&&ve.status!=="ready"||!h&&Ie.isPending||Z.loading||s==="claude_local"&&Y.isPending||!S&&!(se==="subscription"&&ae)||!!xe&&(!_||I!=="ready")||se==="api"&&!P.trim()&&!q&&!X,loading:M,primaryIcon:S&&xe?I==="ready"?"none":"spinner":void 0,onPrimary:r(()=>{if(xe){if(!_||I!=="ready")return;window.open(_,"_blank","noreferrer,noopener"),T("waiting")}else de()},"onPrimary")})]})]})}r(s5e,"AgentProviderConnection");function v5(e){return e.provider==="openrouter"||e.provider==="google"?(0,t.jsx)(amt,{...e}):(0,t.jsx)(rmt,{...e})}r(v5,"AiConnectionCredentialStep");function rmt({companyId:e,provider:s,initialMethod:n,fixedMethod:a,connectionId:i,name:o,hideName:l,nameForMethod:c,ownership:d,agentIds:u,allAgents:h,environmentId:p,onComplete:f,onCancel:x,defaults:g,disabled:v}){const[y,k]=(0,m.useState)(o),[w,N]=(0,m.useState)(),S=wt(),C=te({queryKey:D.environments.list(e),queryFn:r(()=>$i.list(e),"queryFn")}),_=te({queryKey:D.environments.capabilities(e),queryFn:r(()=>$i.capabilities(e),"queryFn")}),R=te({queryKey:D.instance.settings,queryFn:jr.get}),I=te({queryKey:D.instance.experimentalSettings,queryFn:jr.getExperimental}),T=te({queryKey:D.instance.generalSettings,queryFn:jr.getGeneral}),E=NV(T.data?.executionMode,C.data??[]);let P=null,O;try{P=E.forced?E.kubernetesEnvironment?.id??null:vN({agentDefaultEnvironmentId:p??w,instanceDefaultEnvironmentId:R.data?.defaultEnvironmentId,localDefaultEnvironmentId:jN(C.data),managedSandboxOnly:I.data?.enableManagedSandboxOnly,managedSandboxEnvironmentId:yN(C.data),visibleEnvironmentIds:C.data?.map(U=>U.id)})}catch(U){O=U instanceof Error?U.message:"Could not resolve the sign-in environment."}const M=(C.data??[]).filter(U=>U.status==="active"&&(U.driver==="local"||U.driver==="sandbox"&&typeof U.config.provider=="string"&&_.data?.sandboxProviders?.[U.config.provider]?.supportsLoginPty===!0));!E.forced&&!p&&!w&&!M.some(U=>U.id===P)&&(P=M[0]?.id??null);const Q=C.data?.find(U=>U.id===P),L=typeof Q?.config.provider=="string"?Q.config.provider:"",F=Q?.driver==="sandbox"&&_.data?.sandboxProviders?.[L]?.supportsLoginPty===!0,q=[C,_,R,I,T].some(U=>U.isPending),z=O??[C,_,R,I,T].find(U=>U.error)?.error?.message,K={provider:s,method:"subscription",name:y,ownership:d,agentIds:u,allAgents:h,connectionId:i};return(0,t.jsxs)("div",{className:"mx-auto w-full min-w-0 max-w-xl space-y-6",children:[!l&&(0,t.jsxs)("label",{className:"block space-y-2 text-sm",children:["Connection name",(0,t.jsx)(dt,{value:y,onChange:r(U=>k(U.target.value),"onChange"),disabled:!!i})]}),!p&&!E.forced&&M.length>1&&(0,t.jsxs)(Ca,{value:P??"",onValueChange:N,children:[(0,t.jsx)(Na,{"aria-label":"Sign-in environment",children:(0,t.jsx)(Sa,{placeholder:"Sign-in environment"})}),(0,t.jsx)(_a,{children:M.map(U=>(0,t.jsx)(un,{value:U.id,children:U.name},U.id))})]}),z&&(0,t.jsx)("p",{role:"alert",className:"text-sm text-destructive",children:z}),g,q?(0,t.jsx)("p",{role:"status",className:"text-sm text-muted-foreground",children:"Preparing sign-in…"}):(0,t.jsx)(s5e,{companyId:e,adapterType:s==="anthropic"?"claude_local":s==="xai"?"grok_local":"codex_local",environmentId:P,canLogin:F,localEnvironment:Q?.driver==="local",onBack:x,onConnected:r(()=>{},"onConnected"),testConnection:r(async()=>!1,"testConnection"),managedAccount:{intent:K,nameForMethod:c,initialMethod:n,fixedMethod:a??!!i,disabled:v||q||!!z||!y.trim(),onComplete:r(U=>{S.invalidateQueries({queryKey:["ai-connections",e]}),S.invalidateQueries({queryKey:["tools"]}),f(U)},"onComplete")}},P??"local")]})}r(rmt,"SubscriptionConnectionStep");function amt({companyId:e,provider:s,connectionId:n,name:a,hideName:i,nameForMethod:o,ownership:l,agentIds:c,allAgents:d,onComplete:u,onCancel:h,defaults:p,disabled:f}){const[x,g]=(0,m.useState)(a),[v,y]=(0,m.useState)(""),k=wt(),w=we({mutationFn:r(()=>Ll.create(e,{provider:s,method:"api_key",name:n?x:o?.("api_key")??x,ownership:l,agentIds:c,allAgents:d,connectionId:n,apiKey:v}),"mutationFn"),onSuccess:r(N=>{k.invalidateQueries({queryKey:["ai-connections",e]}),k.invalidateQueries({queryKey:["tools"]}),u({...N,method:"api_key"})},"onSuccess"),onSettled:r(()=>y(""),"onSettled")});return(0,t.jsxs)("div",{className:"mx-auto w-full min-w-0 max-w-xl space-y-4",children:[!i&&(0,t.jsxs)("label",{className:"block space-y-2 text-sm",children:["Connection name",(0,t.jsx)(dt,{value:x,onChange:r(N=>g(N.target.value),"onChange"),disabled:!!n})]}),w.error&&(0,t.jsx)("p",{role:"alert",className:"text-sm text-destructive",children:w.error.message}),(0,t.jsx)(n_e,{providerName:s==="google"?"Google":"OpenRouter",value:v,onChange:y,onSubmit:r(()=>w.mutate(),"onSubmit"),disabled:f||w.isPending,placeholder:"Enter API key here",autoFocus:!0}),p,(0,t.jsxs)("div",{className:"flex justify-between gap-2",children:[(0,t.jsx)($,{variant:"ghost",onClick:h,children:"Cancel"}),(0,t.jsx)($,{disabled:f||!x.trim()||!v.trim()||w.isPending,onClick:r(()=>w.mutate(),"onClick"),children:w.isPending?"Connecting…":"Connect"})]})]})}r(amt,"ApiKeyConnectionStep");var imt=null;function sw(){const e=(0,m.useContext)(c3),{data:s,isFetched:n,isError:a}=te({queryKey:D.instance.experimentalSettings,queryFn:r(()=>jr.getExperimental(),"queryFn"),enabled:e!=null},e??(imt??=new e2));return e?{enabled:!a&&s?.enableChatConnectors===!0,githubEnabled:!a&&s?.enableGitHubReviewBots===!0,loaded:n}:{enabled:!1,githubEnabled:!1,loaded:!0}}r(sw,"useChatConnectorsEnabled");function Jp(e,s,n){return e==="agentmail"||(e==="github"||e==="github-code-review-bot"?n:s)}r(Jp,"chatProviderVisible");var omt=new RegExp(`\\b(${["mcp","server","profile","policy","gateway","transport","stdio","endpoint"].join("|")})s?\\b`,"gi");function n5e(e){return e.replace(omt,"").replace(/\s{2,}/g," ").replace(/\s+([.,])/g,"$1").trim()}r(n5e,"sanitizeProsumerCopy");var lmt={zapier:{tagline:"Reach 9,000+ apps your team already uses.",short:"Reach 9,000+ apps from your agents."},github:{tagline:"Read code and pull requests, comment on issues.",short:"Read code and pull requests, comment on issues."},slack:{tagline:"Send and read messages in your team's channels.",short:"Send and read messages in your channels."},notion:{tagline:"Read and update pages in your workspace.",short:"Read and update pages in your workspace."},railway:{tagline:"Inspect services, read logs, and manage deployments.",short:"Connect Railway for deployments, logs, and container access."},posthog:{tagline:"Explore product usage, errors, flags, and experiments.",short:"Sign in with PostHog. Project pinning and access controls are optional."},gauge:{tagline:"Track your brand in AI answers and run content workflows.",short:"Sign in with Gauge and pick an organization. API keys are optional."},neon:{tagline:"Manage Postgres projects, branches, and queries.",short:"Sign in with Neon. Project pinning and read-only mode are optional."},superagent:{tagline:"Review security findings and run red-team checks.",short:"Connect with a Superagent API key. Billable and destructive tools stay under action policies."},linear:{tagline:"Create, update and read tickets.",short:"Create, update and read tickets."},"google-sheets":{tagline:"Read and update selected spreadsheets.",short:"Read spreadsheets or update the files you choose."},gmail:{tagline:"Read mail and create drafts for your review.",short:"Read mail and create drafts for your review."},"google-drive":{tagline:"Find, read, and create files in Drive.",short:"Find, read, and create files in Drive."},"google-docs":{tagline:"Read and update documents.",short:"Read and update documents."},"google-slides":{tagline:"Read and update presentations.",short:"Read and update presentations."},"google-calendar":{tagline:"Review calendars and manage events.",short:"Review calendars and manage events."},"google-chat":{tagline:"Read conversations and send messages.",short:"Read conversations and send messages."},"google-people":{tagline:"Look up contacts and people in your directory.",short:"Look up contacts and people in your directory."},"google-workspace-search":{tagline:"Search across your Google workspace.",short:"Search across your Google workspace."},hubspot:{tagline:"Look up contacts and update deal stages.",short:"Look up contacts and update deal stages."},intercom:{tagline:"Read and reply to customer conversations.",short:"Read and reply to customer conversations."},figma:{tagline:"Read files and post comments on frames.",short:"Read files and post comments on frames."},stripe:{tagline:"Read customers, invoices, and payouts.",short:"Read customers, invoices, and payouts."},context7:{tagline:"Look up up-to-date docs for your libraries.",short:"Look up up-to-date docs for your libraries."}},cmt={tagline:"Give your agents access to this app.",short:"Give your agents access to this app."};function r5e(e,s){const n=lmt[e];if(n)return n;if(s){const a=n5e(s);if(a)return{tagline:a,short:a}}return cmt}r(r5e,"appCopyFor");function aae(e,s,n){return n<=1?`Your ${e} key`:n5e(s)||`Your ${e} key`}r(aae,"credentialFieldLabel");var dmt=1500;function ep(e=dmt){const[s,n]=(0,m.useState)("idle"),a=(0,m.useRef)(null),i=(0,m.useRef)(0);(0,m.useEffect)(()=>()=>{a.current!==null&&window.clearTimeout(a.current)},[]);const o=(0,m.useCallback)(async l=>{const c=++i.current;let d="copied";try{await wa(l)}catch{d="failed"}return i.current!==c||(n(d),a.current!==null&&window.clearTimeout(a.current),a.current=window.setTimeout(()=>{i.current===c&&(n("idle"),a.current=null)},e)),d},[e]);return{status:s,copied:s==="copied",failed:s==="failed",copy:o}}r(ep,"useCopyAction");function kM(){const e=jd()?.pushToast;return(0,m.useCallback)(async(s,n="Copied")=>{try{return await wa(s),e?.({title:n,tone:"success",dedupeKey:`copy:${n}`}),!0}catch{return e?.({title:"Couldn’t copy to clipboard",body:"Select and copy the value manually.",tone:"error",dedupeKey:"copy-failed"}),!1}},[e])}r(kM,"useCopyToast");var umt="/cloud/connections/handoff",mmt="/cloud/connections/reauth",_E="paperclip.cloud-oauth-handoff.v1",Bx=class extends Error{static{r(this,"OAuthHandoffError")}code;constructor(e,s){super(e),this.code=s,this.name="OAuthHandoffError"}};function _V(e){if(e===void 0)return null;if(!e||typeof e!="object"||Array.isArray(e))throw new Bx("Paperclip Cloud returned an invalid sign-in handoff.","invalid_handoff");const s=e;if(s.kind!=="paperclip_cloud"||typeof s.session!="string"||s.session.length<16||s.session.length>512||!/^[A-Za-z0-9_-]+$/.test(s.session))throw new Bx("Paperclip Cloud returned an invalid sign-in handoff.","invalid_handoff");return{kind:"paperclip_cloud",session:s.session}}r(_V,"parseHandoff");function hmt(e,s){return e===404||s==="SESSION_NOT_AVAILABLE"?new Bx("This sign-in expired. Start the connection again.","expired"):e===401||e===403?new Bx("Paperclip Cloud could not authorize this connection for your account.","forbidden"):new Bx("Paperclip Cloud couldn’t prepare secure sign-in. Try again.","unavailable")}r(hmt,"handoffFailure");async function pmt(e,s){const n=s.request??fetch;let a,i;for(let o=0;o<2;o+=1)try{if(a=await n(umt,{method:"POST",headers:{"content-type":"application/json",accept:"application/json"},credentials:"include",body:JSON.stringify({session:e}),signal:s.signal}),a.status<500||o===1)return a}catch(l){if(s.signal?.aborted||l instanceof DOMException&&l.name==="AbortError")throw l;if(i=l,o===1)break}if(a)return a;throw new Bx(i instanceof Error?i.message:"Paperclip Cloud couldn’t prepare secure sign-in. Try again.","unavailable")}r(pmt,"postCloudHandoff");function fmt(e,s){if(typeof e!="string"||typeof window>"u")return null;try{const n=new URL(e,window.location.origin);return n.origin!==window.location.origin||n.pathname!==mmt||n.username||n.password||n.hash||n.searchParams.size!==1||n.searchParams.get("session")!==s?null:{kind:"reauthentication",url:n.toString(),host:n.host}}catch{return null}}r(fmt,"exactReauthenticationTarget");async function SN(e,s={}){const n=_V(e.handoff);if(!n){const l=tE(e.authorizationUrl);if(!l.ok)throw new Bx(l.message,"invalid_handoff");return{kind:"authorization",url:l.url,host:l.host}}const a=await pmt(n.session,s),i=await a.json().catch(()=>null);if(!a.ok){if(i?.error==="RECENT_LOGIN_REQUIRED"){const l=fmt(i.reauthenticationUrl,n.session);if(l)return l}throw hmt(a.status,i?.error)}const o=tE(typeof i?.authorizationUrl=="string"?i.authorizationUrl:void 0);if(!o.ok)throw new Bx("Paperclip Cloud returned an invalid provider sign-in address.","invalid_handoff");return{kind:"authorization",url:o.url,host:o.host}}r(SN,"prepareOAuthNavigation");function y5(e,s=window.sessionStorage){const n=_V({kind:"paperclip_cloud",session:e});if(!n)throw new Bx("Paperclip Cloud returned an invalid sign-in handoff.","invalid_handoff");const a={version:1,session:n.session,savedAt:Date.now()};s.setItem(_E,JSON.stringify(a))}r(y5,"savePendingCloudHandoff");function xmt(e=window.sessionStorage){const s=e.getItem(_E);if(!s)return null;try{const n=JSON.parse(s);if(n.version!==1||typeof n.savedAt!="number"||Date.now()-n.savedAt>9e5)throw new Error("expired");return _V({kind:"paperclip_cloud",session:n.session})}catch{return e.removeItem(_E),null}}r(xmt,"readPendingCloudHandoff");function iae(e=window.sessionStorage){e.removeItem(_E)}r(iae,"clearPendingCloudHandoff");function NM(e){return!!(e&&Uge({...e,methods:e.methods.filter(s=>(s.purpose??"tool")!=="channel"&&s.transport!=="chat_sdk")}))}r(NM,"appSupportsToolCatalogSetup");var gmt=O$e.filter(e=>Bge(e).some(s=>T0(s))).map(e=>e.slug);function bmt(e){return gmt.some(s=>s===e)}r(bmt,"isMcpDirectOAuthConnectSlug");function j5(e,s){const n=new URLSearchParams({source:e});return s&&n.set("intent",s),`/apps/connect?${n.toString()}`}r(j5,"appSourceConnectHref");function oae(e,s){return`/apps/connect?${new URLSearchParams({source:e,resume:s}).toString()}`}r(oae,"appSourceResumeHref");function oD(e){return e?`/apps/vercel-connect?${new URLSearchParams({source:e}).toString()}`:"/apps/vercel-connect"}r(oD,"vercelConnectSourceHref");function vmt(e){return e.serviceSlug??e.appKey??e.sourceSlug??void 0}r(vmt,"resolveAppsConnectRouteKey");function ymt(e,{chatConnectorsEnabled:s=!1,githubReviewBotsEnabled:n=!1}={}){if(e.get("byo")==="1")return!!(e.get("reconnect")?.trim()&&e.get("applicationId")?.trim()&&e.get("link")?.trim());const a=e.get("source")??"";if(["google-ai","gateway"].includes(a)||/^ai-router-(?:[a-f0-9]{2})+$/.test(a))return!0;const i=GN(a),o=a==="github-code-review-bot"?n:s;return!o&&i?.methods.some(l=>l.transport==="chat_sdk")&&!i.methods.some(l=>(l.purpose??"tool")!=="channel"&&l.transport!=="chat_sdk")?!1:cj(a)&&(e.get("reconnect")?.trim()||e.get("resume")?.trim())?!0:a==="agentmail"||o?Uge(i):NM(i)}r(ymt,"canEnterAppsConnect");var lD=" for the organization",jmt=" for the company";function lae(e,s){const n=e.trim();if(s!=="organization")return n;const a=n.toLocaleLowerCase();return a.endsWith(lD)?n:a.endsWith(jmt)?`${n.slice(0,n.length-16).trimEnd()}${lD}`:`${n}${lD}`}r(lae,"connectionNameForGrantKind");function wmt(e){switch(e){case"active":return"Connected";case"needs_reauthorization":return"Needs attention";case"expired":return"Expired";case"revoked":return"Revoked";default:return"Not connected"}}r(wmt,"grantStatusLabel");function kmt(e){switch(e){case"active":return"connected";case"needs_reauthorization":case"expired":return"attention";case"revoked":return"inactive";default:return"missing"}}r(kmt,"grantStatusTone");function Nmt(e,s={}){const n=e?.providerTenant?.name?.trim();return n||(e?.kind==="user"?s.subjectLabel?.trim()||"Connected account":e?.kind==="agent"?s.subjectLabel?.trim()||"Dedicated account":"Shared credential")}r(Nmt,"grantAccountLabel");function Smt(e){return new Set((e?.members??[]).filter(s=>s.subjectType==="user").map(s=>s.subjectId))}r(Smt,"audienceUserIds");function Cmt(e){return e.find(s=>s.kind==="organization"&&s.isDefault)??e.find(s=>s.kind==="organization")??null}r(Cmt,"organizationGrant");function _mt(e,s){return s?e.find(n=>n.kind==="user"&&n.subjectUserId===s)??null:null}r(_mt,"personalGrantFor");function Amt(e,s){if(!s)return null;const n=e.find(a=>a.userId===s);return n&&(n.name?.trim()||n.email?.trim())||null}r(Amt,"memberLabel");var cae=0;function Oz(){return cae+=1,{id:`header-${cae}`,name:"",value:""}}r(Oz,"newCustomHeaderRow");function d_(e){try{return new URL(e).host||null}catch{return null}}r(d_,"endpointHost");function Imt(e=window.location.origin,s){if(s)return s;const n=new URL("/api/tools/oauth/callback",e),a=n.hostname.toLowerCase().replace(/^\[|\]$/g,"");return n.protocol==="http:"&&(a==="127.0.0.1"||a==="::1")&&(n.hostname="localhost"),n.toString()}r(Imt,"oauthCallbackUrlForBrowser");function cD(e){try{const s=new URL(e);return`${s.host.replace(/^www\./,"")}${s.pathname==="/"?"":s.pathname.replace(/\/+$/,"")}`.slice(0,160)||null}catch{return null}}r(cD,"defaultGenericMcpName");function dae(e,s){const n=s?.trim()||"Paperclip couldn't connect to that address. Check it and try again.";switch(e){case"mcp_remote_url_missing":case"mcp_remote_url_invalid":return{title:"That doesn't look like a server address",body:"Paste the full address, starting with https:// — for example https://mcp.example.com/mcp.",focus:"url"};case"remote_http_private_endpoint":return{title:"That address is inside a private network",body:"This Paperclip is reachable from the internet, so it won't call addresses on your local network. Use the server's public address instead.",focus:"url"};case"remote_http_dns_failed":return{title:"We couldn't find that host",body:"The address didn't resolve. Check the spelling, or confirm the server is published on the internet.",focus:"url"};case"mcp_header_rejected":return{title:"Paperclip can't send that header",body:n,focus:"credentials"};case"tool_access_name_conflict":return{title:"Paperclip couldn’t name this connection",body:"Try connecting again.",focus:"none"};case"oauth_challenge":return{title:"This server wants a credential",body:"It asked us to authenticate but didn't offer a sign-in Paperclip can complete on its own. Add the key or headers its docs list under Advanced authentication.",focus:"credentials"};case"oauth_manual_client_required":case"oauth_manual_client_rebinding_required":return{title:"This server needs sign-in details you create yourself",body:"Register Paperclip in the provider's settings, then add the client ID and secret it gives you under Advanced authentication.",focus:"credentials"};case"oauth_redirect_origin_unsupported":case"oauth_redirect_uri_invalid":return{title:"This Paperclip needs a public HTTPS address first",body:"Sign-in sends the operator back to Paperclip, so this instance has to be reachable over HTTPS. Ask your Paperclip admin to configure it.",focus:"deployment"};case"runtime_error":return{title:"We couldn't reach that server",body:"Nothing answered at that address. Confirm the server is running and the address is right, then try again.",focus:"url"};default:return{title:"Paperclip couldn't connect",body:n,focus:"none"}}}r(dae,"genericConnectGuidance");function a5e(e){const s=new Set;for(const n of e){const a=n.name.trim();if(!a&&!n.value.trim())continue;const i=OOe(a);if(!i.ok)return Mee(a,i.reason);const o=gOe(n.value);if(!o.ok)return Mee(a,o.reason);if(!n.value.trim())return`Add a value for "${a}", or remove the row.`;const l=a.toLowerCase();if(s.has(l))return`"${a}" is listed twice.`;s.add(l)}return null}r(a5e,"customHeaderError");function Tmt(e){const s={},n=e.keyValue.trim();if((e.authMode==="bearer"||e.authMode==="auto"&&e.needsKey)&&n&&(s["credentials.authorization"]=n),e.authMode==="custom_headers")for(const l of e.headers){const c=l.name.trim();!c||!l.value.trim()||(s[`headers.${c}`]=l.value)}const a=e.name.trim(),i=e.oauthClientId.trim(),o=e.oauthClientSecret.trim();return{link:e.link,...a?{name:a}:{},...e.authMode==="auto"?{}:{authMode:e.authMode},...Object.keys(s).length>0?{credentialValues:s}:{},...e.authMode==="oauth"&&i?{oauthClient:{clientId:i,...o?{clientSecret:o}:{}}}:{}}}r(Tmt,"genericConnectPayload");function Rmt(e){return e.link.trim()?e.authMode==="auto"?!e.needsKey||e.keyValue.trim().length>0:e.authMode==="bearer"?e.keyValue.trim().length>0:e.authMode==="custom_headers"?e.headers.filter(s=>s.name.trim()&&s.value.trim()).length>0&&a5e(e.headers)===null:!0:!1}r(Rmt,"canSubmitGenericConnect");function CN(e){const s=new Set;let n=!1;for(const a of e??[])a.targetType==="company"?n=!0:a.targetType==="agent"&&s.add(a.targetId);return{onAll:n,agentIds:s}}r(CN,"installStateFrom");function i5e(e,s){return e.onAll||e.agentIds.has(s)}r(i5e,"isAgentInstalled");function o5e(e,s){return s.onAll?[{targetType:"company",targetId:e}]:[...s.agentIds].map(n=>({targetType:"agent",targetId:n}))}r(o5e,"installPayload");var Emt="Has access — tick to load its tools into this agent's context.";function l5e(e){return`paperclip.connector-enrollment-access:${e}`}r(l5e,"enrollmentAccessStorageKey");function Lmt(e){if(!e||typeof e!="object"||Array.isArray(e))return!1;const s=e;if(typeof s.companyId!="string"||!s.companyId.trim()||!(s.grantKind==="user"||s.grantKind==="agent"||s.grantKind==="organization")||s.installChoice!=="specific"&&s.installChoice!=="all"||!Array.isArray(s.agentIds)||s.agentIds.some(a=>typeof a!="string"||!a.trim()))return!1;const n=new Set(s.agentIds);return n.size!==s.agentIds.length?!1:s.grantKind==="agent"?s.installChoice==="specific"&&n.size===1:s.installChoice==="all"?n.size===0:n.size>0}r(Lmt,"validEnrollmentAccessState");function Mmt(e,s,n){try{window.sessionStorage.setItem(l5e(s),JSON.stringify({...n,companyId:e}))}catch{}}r(Mmt,"saveEnrollmentAccessState");function Pmt(e){const s=l5e(e);try{const n=window.sessionStorage.getItem(s);if(window.sessionStorage.removeItem(s),!n)return null;const a=JSON.parse(n);return Lmt(a)?a:null}catch{return null}}r(Pmt,"consumeEnrollmentAccessState");function uae(e){if(!e)return null;try{const s=new URL(e);return s.protocol==="https:"&&s.hostname.toLowerCase()==="github.com"?s.toString():null}catch{return null}}r(uae,"githubRecoveryUrl");function mae(e,s){return e==="denied"?"Authorization was cancelled or declined. Your saved connection was not changed.":s==="github_installation_required"?"GitHub access is required. Install Paperclip and grant at least one repository, then try again.":"Authorization did not complete. Your saved connection is still here, so you can try again."}r(mae,"oauthCallbackErrorMessage");var Dmt={key:"setup",success:"complete"};function hae(e){return e.requestedAppKey||e.hasPrefilledLink||e.zapierSource?"key":"gallery"}r(hae,"requestedConnectionInitialStep");function $mt(e){const s=e.galleryApps.find(a=>a.slug===e.requestedAppKey);if(s)return s;if(c5e({requestedAppKey:e.requestedAppKey,resumeConnection:e.resumeConnection,resumeApplication:e.resumeApplication,completedResumeConnectionId:e.completedResumeConnectionId}))return cj(e.requestedAppKey);if(!e.reconnectConnection)return null;const n=e.applications.find(a=>a.id===e.reconnectConnection?.applicationId);return yf(n)!==e.requestedAppKey?null:cj(e.requestedAppKey)}r($mt,"requestedConnectionEntry");function c5e(e){const{requestedAppKey:s,resumeConnection:n,resumeApplication:a,completedResumeConnectionId:i}=e;return!!(n&&(n.status==="draft"||n.status==="active"&&n.id===i)&&a&&n.applicationId===a.id&&n.companyId===a.companyId&&yf(a)===s&&bu(n)===s)}r(c5e,"retainedResumeMatches");function Omt(e){return!e.reconnectConnection||!e.reconnectApplication||e.reconnectConnection.applicationId!==e.reconnectApplication.id?!1:e.requestedAppKey?yf(e.reconnectApplication)===e.requestedAppKey:e.byo&&e.applicationId===e.reconnectApplication.id}r(Omt,"retainedReconnectMatches");function Bmt(e){return e.credentialSource==="vercel_connect"&&!e.available&&!e.retainedReconnectMatches}r(Bmt,"isVercelConnectUnavailable");function Fmt(e){return e.available===!1&&!(e.reconnectConnectionId&&e.reconnectSourceMatches)}r(Fmt,"isConnectionDefinitionUnavailable");function zmt(e){return!e.hasRequestedEntry||e.supportedMethodCount===0||e.unsupportedOAuth||e.vercelUnavailable||e.definitionUnavailable?e.reconnectConnectionId?"reconnect_unavailable":"fallback":"ready"}r(zmt,"requestedConnectionSetupResolution");function pae(e,s,n,a){const i=Dmt[s]??"setup",o=new URLSearchParams({source:e,stage:i});return a?.resumeConnectionId&&o.set("resume",a.resumeConnectionId),a?.reconnectConnectionId&&o.set("reconnect",a.reconnectConnectionId),a?.interactionId&&o.set("intent",a.interactionId),a?.connectionMethodKey&&o.set("method",a.connectionMethodKey),`${n==="vercel_connect"?"/apps/vercel-connect":"/apps/connect"}?${o.toString()}`}r(pae,"appConnectHref");function RI(e,s){if(!s)return e;const[n,a=""]=e.split("?",2),i=new URLSearchParams(a);return i.set("intent",s),`${n}?${i.toString()}`}r(RI,"withConnectionIntent");var fae=["Pick app","Add your key"],xae={gallery:0,key:1},qmt={key:0},Umt=["Add MCP URL"],Kmt=["Sign in"];function dD(e,s=!1){return s&&e?.auth!=="none"&&(!e?.grantKinds||e.grantKinds.includes("user"))?"user":e?.grantKinds?.length===1||e?.grantKinds&&!e.grantKinds.includes("organization")?e.grantKinds[0]:"organization"}r(dD,"defaultGrantKindFor");function Qmt(e){const s=e.config?.oauth;if(!s||typeof s!="object"||Array.isArray(s))return;const n=s.connectorSubjectAgentId;return typeof n=="string"?n:void 0}r(Qmt,"configuredAgentIdentity");function CC(e,s){const n=typeof s=="string"?s:s?.key;return e?.slug==="google-sheets"&&n==="local"}r(CC,"isGoogleSheetsRobotMethod");function LS(e){return e?Object.fromEntries([...e.tenantFields??[],...e.extensionFields??[]].filter(s=>s.defaultValue!==void 0).map(s=>[s.key,s.defaultValue])):{}}r(LS,"defaultMethodConfig");function D1(e,s){if(!e)return[];const n=Z3(e);return s==="vercel_connect"?n.filter(a=>!!a.credentialSources?.vercelConnect):n}r(D1,"connectionMethodsForCredentialSource");function Z3(e){return Bge(e).filter(s=>(s.purpose??"tool")!=="channel")}r(Z3,"availableToolConnectionMethods");function EI(e,s){const n=Z3(e);return s?n.find(a=>a.key===s)??null:RQ(n)}r(EI,"availableToolConnectionMethod");function Rk(e){return RQ(e)}r(Rk,"recommendedSetupConnectionMethod");function gae(e){return Rk(e?e.methods.filter(s=>(s.purpose??"tool")==="tool"&&(s.oauthStrategy==="paperclip_cloud_connector"||s.oauthStrategy==="paperclip_id_connector")):[])}r(gae,"recommendedManagedConnectorMethod");function bae(e){if(!e)return!1;const s=Z3(e),n=s.length===1?s[0]:null;return!!(n&&T0(n)&&!XOe(n))}r(bae,"canUseAutomaticOAuthFastPath");function vae(e){if(!e)return null;const s=Z3(e),n=s.length===1?s[0]:null;return n&&T0(n)?n:null}r(vae,"automaticOAuthMethod");function Wmt(e){const s=e.metadata;if(!s)return null;const n=s.sourceTemplateKey??s.galleryKey;return typeof n=="string"?n:null}r(Wmt,"appSourceSlug");function Hmt(e){const s=e.config?.sourceTemplateKey??e.transportConfig.sourceTemplateKey;return typeof s=="string"?s:null}r(Hmt,"connectionSourceSlug");function yae(e,s,n,a={}){if(!e)return null;const i=new Set(s.filter(o=>o.status!=="archived"&&Wmt(o)===e&&(!a.applicationId||o.id===a.applicationId)).map(o=>o.id));return n.find(o=>{const l=a.applicationId?o.applicationId===a.applicationId:i.has(o.applicationId)||Hmt(o)===e;return o.status!=="archived"&&(!a.draftOnly||o.status==="draft")&&o.authKind==="oauth"&&l})??null}r(yae,"reusableOAuthConnection");function d5e(e,s,n){if(e.origin!==s||!e.data||typeof e.data!="object")return null;const a=e.data;return a.type!=="paperclip.connection-intent.oauth"||a.interactionId!==n?null:a.outcome==="connected"||a.outcome==="declined"||a.outcome==="failed"?a.outcome:null}r(d5e,"readConnectionIntentOAuthOutcome");function A2(e={}){const[s]=hi(),n=xa(),{selectedCompanyId:a}=fs(),i=SH(),o=e.interactionId||s.get("intent")||void 0,l=e.serviceSlug||s.get("source")||n.appKey||s.get("appKey"),c=(0,m.useMemo)(()=>{if(o&&YC(l))try{return sessionStorage.getItem(`paperclip:mcp-intent-draft:${a}:${o}`)}catch{}return null},[o,a,l]),d=e.configuredConnection?.id||s.get("resume")||s.get("reconnect")||c,u=!!(d&&(!l||YC(l)||DR(l))),h=te({queryKey:["tools","connection",d],queryFn:r(()=>ts.getConnection(d),"queryFn"),enabled:u}),p=l||h.data?.config?.sourceTemplateKey,f=s.get("method")||h.data?.config?.connectionMethodKey;if(u&&h.isPending)return(0,t.jsx)("p",{className:"p-6 text-sm text-muted-foreground",children:"Loading connection…"});if(u&&h.isError)return(0,t.jsxs)("div",{role:"alert",className:"space-y-3 p-6",children:[(0,t.jsx)("p",{children:"Could not load this connection. Your saved access and credentials have not changed."}),(0,t.jsx)($,{variant:"outline",onClick:r(()=>{h.refetch()},"onClick"),children:"Try again"})]});if(DR(p)&&!(h.data&&h.data.status!=="draft"&&h.data.config?.sourceTemplateKey===p)){if(!i.loaded)return(0,t.jsx)("p",{className:"p-6 text-sm text-muted-foreground",children:"Loading connection settings…"});if(!i.enabled)return(0,t.jsx)("p",{role:"status",className:"p-6 text-sm text-muted-foreground",children:"Enable memory connectors in Settings → Experimental to set up this connection."})}if(!e.byoOnly&&(e.credentialSource??"paperclip_vault")==="paperclip_vault"&&YC(p)&&(!f||FT(p,f))){const x=qge(p,s.get("targetToolkit"));return(0,t.jsx)(met,{...e,upstreamServiceName:e.upstreamServiceName??x?.name,interactionId:o,providerId:p,connection:h.data},`${o||"page"}:${p}`)}return(0,t.jsx)(Vmt,{...e})}r(A2,"ConnectionSetupFlow");function Vmt({additionalSettings:e,connectionSettings:s,additionalSettingsValid:n=!0,byoOnly:a=!1,credentialSource:i="paperclip_vault",host:o="page",serviceSlug:l,requestedAgentId:c,interactionId:d,forceNewConnection:u=!1,existingConnections:h=[],configuredConnection:p,onUseExisting:f,onComplete:x,onOAuthDeclined:g,aiConnection:v,requiredAiOwnership:y,onPhaseChange:k,onCancel:w,renderCredentialStep:N}={}){const S=wt(),C=Gn(),_=(0,m.useCallback)((ct,xs)=>{o==="page"&&(xs?C(ct,xs):C(ct))},[o,C]),R=xa(),{selectedCompany:I,selectedCompanyId:T}=fs(),{enabled:E,githubEnabled:P}=sw(),{enabled:O}=SH(),{setBreadcrumbs:M}=Vn(),{pushToast:Q}=Ti(),[L]=hi(),F=d?.trim()||L.get("intent")?.trim()||null,q=R.appKey??L.get("appKey")??void 0,z=L.get("source")?.trim()||null,K=u||L.get("new")==="1",U=L.get("stage")?.trim()||null,V=L.get("method")?.trim()||null,ne=L.get("resume")?.trim()||null,Z=L.get("oauth"),ie=L.get("code"),J=uae(L.get("installation_url")),ae=uae(L.get("management_url")),oe=p?.id??(L.get("reconnect")?.trim()||null),G=L.get("identity")==="user"?"user":L.get("identity")==="organization"?"organization":null,X=i==="vercel_connect",Y=l??z,re=i==="paperclip_vault"&&bmt(Y)?Y:null,se=vmt({serviceSlug:l,appKey:q,sourceSlug:z}),ce=(l??z??q)==="zapier",pe=ce?void 0:se,fe=!!p||o==="page"&&(a||L.get("byo")==="1"),[ve]=(0,m.useState)(()=>o==="page"&&L.get("cloud_connector")==="enrolled"&&pe?Pmt(pe):null),[Ie]=(0,m.useState)(()=>{const ct=L.get("link")?.trim()??"";return{link:/^https?:\/\//i.test(ct)?ct:"",name:p?.name??L.get("name")?.trim()??"",applicationId:p?.applicationId??(L.get("applicationId")?.trim()||void 0)}}),[de,xe]=(0,m.useState)(()=>hae({requestedAppKey:pe,routeStage:U,resumeConnectionId:ne,hasPrefilledLink:!!Ie.link,zapierSource:ce})),[le,Re]=(0,m.useState)(null),[Le,je]=(0,m.useState)(""),[_e,Ze]=(0,m.useState)(Ie.link),[ue,Fe]=(0,m.useState)(Ie.name||(ce?"Zapier":"")),[mt,bt]=(0,m.useState)(!1),[et,qe]=(0,m.useState)(""),[it,_t]=(0,m.useState)("auto"),[$t,Ot]=(0,m.useState)(()=>[Oz()]),[at,Me]=(0,m.useState)(""),[De,ut]=(0,m.useState)(""),[Pt,Rt]=(0,m.useState)(!1),[Qe,Be]=(0,m.useState)(null),[Oe,Pe]=(0,m.useState)(!1),[Ve,be]=(0,m.useState)({}),[nt,Lt]=(0,m.useState)(""),[Cs,lt]=(0,m.useState)(""),[Os,Ke]=(0,m.useState)(""),[ge,Xe]=(0,m.useState)(v&&v.mode!=="responsible_user"?`ai-${v.method}`:""),[xt,Ht]=(0,m.useState)(null),[ht,zt]=(0,m.useState)({}),[$e,he]=(0,m.useState)(""),[Vt,Dt]=(0,m.useState)(null),[ns,_s]=(0,m.useState)(null),[cn,mr]=(0,m.useState)({}),[pn,Bt]=(0,m.useState)("all"),[Ls,Ee]=(0,m.useState)(new Set),[jt,ze]=(0,m.useState)(()=>new Set(ve?.agentIds??(c?[c]:[]))),[St,Ut]=(0,m.useState)(ve?.grantKind??G??(c?"user":"organization")),[Ct,os]=(0,m.useState)(ve?.installChoice??(c?"specific":"all")),vs=!!(ne&&(Z==="failed"||Z==="denied")),[Bs,qs]=(0,m.useState)(vs?"error":"entry"),[Rn,Ns]=(0,m.useState)(()=>vs?mae(Z,ie):null),[Yn,Xt]=(0,m.useState)(null),Hs=(0,m.useRef)(!1),on=(0,m.useRef)(!1),Tt=(0,m.useRef)(null),as=(0,m.useRef)(null),[Xs,bs]=(0,m.useState)(null),[Zs,Nn]=(0,m.useState)(null),hr=(0,m.useRef)(null),[qn,qr]=(0,m.useState)(null),[Cr,pr]=(0,m.useState)(null),Cn=(0,m.useRef)(null),[Nr,Or]=(0,m.useState)(h.length>0&&!!f),[Ur,ga]=(0,m.useState)(null),[ar,ur]=(0,m.useState)(null),[gt,Ge]=(0,m.useState)(null),es=(0,m.useCallback)(()=>{o!=="dialog"||hr.current?.closed===!1||(hr.current=window.open("about:blank","paperclip-connection-oauth","popup,width=720,height=760,resizable=yes,scrollbars=yes"))},[o]),hs=(0,m.useCallback)(ct=>{if(o!=="dialog"){lh(ct);return}pr(ct);const xs=hr.current;if(!xs||xs.closed){qs("error"),Ns("Paperclip couldn’t open the sign-in window. Open sign-in in a new tab to continue."),k?.("needs_retry");return}xs.location.assign(ct),xs.focus()},[o,k]),As=(0,m.useCallback)(()=>{hr.current=null,Ns(null),qs("redirecting"),k?.("authorizing")},[k]);(0,m.useEffect)(()=>{if(o!=="dialog"||Bs!=="redirecting")return;const ct=window.setInterval(()=>{hr.current?.closed&&(qs("error"),Ns("The sign-in window closed. If authorization did not finish, try again."),pr(null),k?.("needs_retry"))},1e3);return()=>window.clearInterval(ct)},[o,Bs,k]);const ss=(0,m.useCallback)(async ct=>{Cn.current?.abort();const xs=new AbortController;Cn.current=xs;try{const Ws=await SN(ct,{signal:xs.signal});if(Ws.kind==="reauthentication"){const Sn=o==="dialog"?hr.current:window;if(!Sn||Sn.closed||!ct.handoff)throw new Error("Paperclip couldn’t preserve this sign-in while refreshing your account.");y5(ct.handoff.session,Sn.sessionStorage),qs("starting")}else Xt(Ws.host),qs("redirecting");hs(Ws.url)}catch(Ws){if(xs.signal.aborted)return;qs("error"),Ns(Ws instanceof Error?Ws.message:"Paperclip couldn’t start secure sign-in. Try again."),k?.("needs_retry")}finally{Cn.current===xs&&(Cn.current=null)}},[o,k,hs]);(0,m.useEffect)(()=>()=>Cn.current?.abort(),[]),(0,m.useEffect)(()=>{if(o!=="dialog"||!F)return;const ct=r(xs=>{const Ws=d5e(xs,window.location.origin,F);if(Ws==="connected"){qs("entry"),pr(null),x?.({resolvedByCallback:!0});return}if(Ws==="declined"){qs("error"),Ns("Authorization was cancelled. You can try again."),k?.("needs_retry");return}Ws==="failed"&&(qs("error"),Ns("Authorization did not complete. Try again when you’re ready."))},"receiveOAuthOutcome");return window.addEventListener("message",ct),()=>window.removeEventListener("message",ct)},[F,o,x,g]),(0,m.useEffect)(()=>{if(o!=="dialog"||F||!qn)return;let ct=!1,xs=!1;const Ws=window.setInterval(async()=>{if(xs||ct)return;const Sn=hr.current;if(!Sn||Sn.closed){qr(null),qs("error"),Ns("The sign-in window closed. Try again to finish connecting GitHub.");return}let Jn;try{Jn=new URL(Sn.location.href)}catch{return}if(!(Jn.origin!==window.location.origin||!Jn.pathname.includes(qn))){if(Jn.searchParams.has("oauth")){qr(null),qs("error"),Ns("Authorization did not complete. Finish setup in the sign-in window or try again.");return}if(Jn.searchParams.get("success")==="1"){xs=!0;try{const wn=await ts.getConnection(qn);!ct&&wn.status==="active"&&(qr(null),Sn.close(),x?.({connectionId:wn.id}))}catch{ct||(qr(null),qs("error"),Ns("Could not confirm the connection. Try again."))}finally{xs=!1}}}},1e3);return()=>{ct=!0,window.clearInterval(Ws)}},[F,qn,o,x]);const ks=r(()=>{_t("auto"),Ot([Oz()]),Me(""),ut(""),Rt(!1),Be(null),Pe(!1)},"resetGenericAuthState"),kn=r(ct=>{if(o==="page"&&!F&&i==="paperclip_vault"&&YC(ct.slug)){_(`/apps/connect?source=${ct.slug}`);return}if(ct.slug==="zapier"){Re(null),je(""),Ze(""),Fe("Zapier"),bt(!1),qe(""),ks(),be({}),_s(null),xe("key"),_(RI("/apps/connect?source=zapier",F));return}if(i==="paperclip_vault"&&bae(ct)){_(j5(ct.slug,F));return}Re(ct),je(ct.name),Ze(""),Fe(""),bt(!1),qe(""),ks(),be({}),Lt(""),lt(""),Ke("");const xs=Rk(D1(ct,i));Xe(xs?.key??""),zt(LS(xs)),he(""),Dt(null),_s(null),ze(new Set(c?[c]:[])),os(c?"specific":"all"),Ut(Te??dD(xs,!!c)),xe("key"),_(i==="vercel_connect"?RI(oD(ct.slug),F):j5(ct.slug,F))},"useMatchedGalleryEntry"),vn=r(()=>{xe("gallery"),_(RI(i==="vercel_connect"?oD():a?"/apps/byo":"/apps",F))},"backToGallery");(0,m.useEffect)(()=>{if(o==="page")return M([{label:"Connectors",href:"/apps"},{label:X?"Vercel Connect":a?"Connect your own tool":"Connect an app"}]),()=>M([])},[a,o,M,X]);const Un=te({queryKey:D.apps.gallery(T??"__none__"),queryFn:r(()=>ts.listGallery(T),"queryFn"),select:(0,m.useCallback)(ct=>F||v?{...ct,apps:ct.apps.map(xs=>({...xs,methods:xs.methods.filter(Ws=>v?Ws.ai?.provider===v.provider&&(v.mode==="responsible_user"||Ws.ai.method===v.method):Ws.transport!=="runtime_auth")})).filter(xs=>xs.methods.length>0)}:ct,[F,v?.provider,v?.method,v?.mode]),enabled:!!T}),pt=Imt(window.location.origin,Un.data?.oauthCallbackUrl),Is=(0,m.useMemo)(()=>(Un.data?.apps??[]).filter(ct=>O||!DR(ct.slug)).filter(ct=>Jp(ct.slug,E,P)||!ct.methods.some(xs=>xs.transport==="chat_sdk")||NM(ct)),[Un.data,E,P,O]),dn=pe?cj(pe):null,_n=dn?.methods.find(ct=>fk(ct)&&!T0(ct)),fn=!(_n&&ge===_n.key)&&!!dn?.methods.some(ct=>ct.oauthStrategy==="paperclip_cloud_connector"||ct.oauthStrategy==="paperclip_id_connector"),Sr=!!le?.methods.some(ct=>ct.oauthStrategy==="paperclip_cloud_connector"||ct.oauthStrategy==="paperclip_id_connector"),ia=le&&fn&&!Sr?gae(dn):null,[Da,Ts]=(0,m.useState)(null),ln=te({queryKey:["cloud-connector","enrollment"],queryFn:r(()=>ts.getCloudConnectorEnrollment(),"queryFn"),refetchInterval:Da?2e3:!1,enabled:!!(T&&fn&&!Sr)}),[Tr,Zn]=(0,m.useState)(null),Kn=(0,m.useCallback)(()=>{hr.current?.close(),hr.current=null,Ts(null)},[]),Wr=(0,m.useCallback)(()=>{!T||!pe||Mmt(T,pe,{grantKind:St,installChoice:Ct,agentIds:Ct==="specific"?[...jt]:[]})},[St,jt,Ct,pe,T]),Ms=(0,m.useCallback)(ct=>{const xs=tE(ct);if(!xs.ok){Kn(),Zn(xs.message);return}if(o==="dialog"){Ts(xs.url);const Ws=hr.current;Ws&&!Ws.closed?(Ws.location.assign(xs.url),Ws.focus()):Zn("Open authorization in a new tab to continue.");return}lh(xs.url)},[o,Kn]);(0,m.useEffect)(()=>{!Da||ln.data?.status!=="active"||(Kn(),Zn(null),Un.refetch())},[Da,ln.data?.status,Un.refetch,Kn]);const jn=we({mutationFn:r(()=>ts.startCloudConnectorEnrollment(T,I?.name,pe?pae(pe,"key",i,{resumeConnectionId:ne,reconnectConnectionId:oe,interactionId:F})+(o==="dialog"?"&enrollment_host=dialog":""):void 0),"mutationFn"),onSuccess:r(ct=>{if(!ct.verificationUrl){Kn(),Zn("Paperclip Cloud did not return an enrollment link. Try again.");return}Ms(ct.verificationUrl)},"onSuccess"),onError:r(ct=>{Kn(),Zn(ct instanceof Error?ct.message:"Paperclip couldn’t reach Paperclip Cloud. Try again.")},"onError")}),En=te({queryKey:D.tools.applications(T??"__none__"),queryFn:r(()=>ts.listApplications(T),"queryFn"),enabled:!!T&&(!!re||!!ne||!!oe),refetchOnMount:"always"}),zs=te({queryKey:D.tools.connections(T??"__none__"),queryFn:r(()=>ts.listConnections(T),"queryFn"),enabled:!!T&&(!!re||!!ne||!!oe),refetchOnMount:"always"}),rr=(0,m.useMemo)(()=>u?null:yae(re,En.data?.applications??[],zs.data?.connections??[],K?{applicationId:Ie.applicationId,draftOnly:!0}:{}),[En.data,zs.data,K,re,Ie.applicationId,u]),hn=(0,m.useMemo)(()=>oe?(zs.data?.connections??[]).find(ct=>ct.id===oe)??null:null,[zs.data,oe]),Jr=(0,m.useRef)(null);(0,m.useEffect)(()=>{if(!p||!zs.isFetchedAfterMount||!hn||Jr.current===hn.id)return;const ct=hn.config?.url??hn.transportConfig?.url??hn.transportConfig?.serverUrl??hn.config?.serverUrl;typeof ct!="string"||!/^https?:\/\//i.test(ct)||(Jr.current=hn.id,Ze(xs=>xs||ct))},[p,zs.isFetchedAfterMount,hn]);const Ae=(0,m.useMemo)(()=>hn?(En.data?.applications??[]).find(ct=>ct.id===hn.applicationId)??null:null,[En.data,hn]),Zt=Omt({requestedAppKey:pe,byo:fe,applicationId:Ie.applicationId,reconnectConnection:hn,reconnectApplication:Ae}),xn=(0,m.useMemo)(()=>ne?(zs.data?.connections??[]).find(ct=>ct.id===ne)??null:null,[zs.data,ne]),Dr=(0,m.useMemo)(()=>xn?(En.data?.applications??[]).find(ct=>ct.id===xn.applicationId)??null:null,[En.data,xn]),ba=U==="complete"&&xn?.status==="active"?xn.id:null,Fa=pe?c5e({requestedAppKey:pe,resumeConnection:xn,resumeApplication:Dr,completedResumeConnectionId:Zs??ba}):!1,ps=xn??hn,Te=ps?ps.credentialPolicy==="per_user"?"user":ps.credentialPolicy==="per_agent"?"agent":"organization":G,Wt=xn?.authKind==="oauth"?xn:rr,Jt=rr?rr.credentialPolicy==="per_user"?"user":rr.credentialPolicy==="per_agent"?"agent":"organization":null,Js=Te??Jt??(y==="shared"?"organization":null);(0,m.useEffect)(()=>{Js&&Ut(Js)},[Js]);const gn=(0,m.useMemo)(()=>_e&&!le?mR(_e,Is):null,[le,Is,_e]),_r=le?EI(le,ge||null):null,ti=_r&&T0(_r)?_r:vae(le),fr=i==="paperclip_vault"&&ti?le:null,Ta=i==="paperclip_vault"&&bae(le)?le:null,vi=!!re&&(!En.isFetchedAfterMount||!zs.isFetchedAfterMount),Ha=r(ct=>{xe(ct),le&&_(pae(le.slug,ct,i,{connectionMethodKey:le.methods.find(xs=>xs.key===ge)?.ai?ge:void 0,resumeConnectionId:ne,reconnectConnectionId:oe,interactionId:F}))},"setAppStep"),Er=xn??hn??Wt,Mi=le?.agentInstructions,ir=le&&Mi?xt?.slug===le.slug?xt.value:Er?Er.agentInstructions??{...rN(Mi),enabled:!1}:rN(Mi):null,Vi=!ir||!!ir.text.trim(),il=we({mutationFn:r(async ct=>(ir&&JSON.stringify(ir)!==JSON.stringify(ct.agentInstructions)&&await ts.updateConnection(ct.id,{agentInstructions:ir}),ts.startOAuth(ct.id,{asCurrentUser:ct.credentialPolicy==="per_user",...ct.credentialPolicy==="per_agent"?{asAgentId:Qmt(ct)??[...jt][0]}:{},...F?{interactionId:F}:{}})),"mutationFn"),onSuccess:r(ct=>{ss(ct)},"onSuccess"),onError:r(ct=>{const xs=ct instanceof nn&&ct.body&&typeof ct.body=="object"?ct.body.details:null;qs("error"),k?.("needs_retry"),Ns(xs?.code==="invalid_grant"?"Your authorization expired or was revoked. Reconnect to continue.":ct instanceof Error?ct.message:"Paperclip couldn’t start secure sign-in. Try again.")},"onError")}),So=il.mutate,eo=(0,m.useCallback)(ct=>{k?.("authorizing"),es(),o==="dialog"&&!F&&qr(ct.id),So(ct)},[So,k,es,o,F]),ye=r(async ct=>{if(c)return;const xs=o5e(T,(Js??St)!=="agent"&&Ct==="all"?{onAll:!0,agentIds:new Set}:{onAll:!1,agentIds:jt});await ts.putConnectionInstalls(ct,xs)},"applyAccessInstalls"),ft=Js??St,ds=we({mutationFn:r(async ct=>{const xs=ct??le;let Ws;if(xs){const Sn=Js??St,Jn=EI(xs,ge||null),wn=CC(xs,Jn)?zF($e).ids:[],ca=Le.trim(),Ga=lae(ca||xs.name,Sn);Ws=await ts.connectApp(T,{galleryKey:xs.slug,...ir?{agentInstructions:ir}:{},...ge?{connectionMethodKey:ge}:{},name:Ga,credentialSource:i,...i==="paperclip_vault"?{credentialValues:Ve}:{},...i==="vercel_connect"?{vercelConnect:{connector:Os.trim()}}:{},...nt.trim()?{oauthClient:{clientId:nt.trim(),...Cs?{clientSecret:Cs}:{}}}:{},configValues:CC(xs,Jn)?{allowedSpreadsheetIds:wn}:Object.keys(ht).length>0?ht:void 0,applicationId:Ie.applicationId,...ne??Tt.current?{resumeConnectionId:ne??Tt.current}:oe?{reconnectConnectionId:oe}:{},...Sn!=="organization"?{grantKind:Sn}:{},...Sn==="agent"?{subjectAgentId:[...jt][0]}:{}}),Tt.current=null}else{const Sn=Tmt({link:_e,name:ue,authMode:it,needsKey:mt,keyValue:et,headers:$t,oauthClientId:at,oauthClientSecret:De}),Jn=lae(Sn.name??cD(_e)??"Custom app",ft);Ws=await ts.connectApp(T,{...Sn,...oe?{reconnectConnectionId:oe}:{},...ce||gn?.slug==="zapier"?{galleryKey:"zapier",connectionMethodKey:"generated-url"}:{},name:Jn,applicationId:Ie.applicationId,...ft!=="organization"?{grantKind:ft}:{},...ft==="agent"?{subjectAgentId:[...jt][0]}:{}})}return Ws.auth?.kind==="oauth"&&!ne&&!oe&&await ye(Ws.connectionId),Ws},"mutationFn"),onSuccess:r(ct=>{if(ct.auth?.kind==="oauth"){if(_s(ct),ct.auth.manualClientRequired){Be(dae("oauth_manual_client_required",null)),_t("oauth"),Rt(!0),Pe(!1);return}if(o==="dialog"||F){qs("starting"),Pe(!le),eo(ct.connection);return}const Ws=ct.auth.startUrl?.trim();if(!Ws){qs("starting"),Pe(!0),eo(ct.connection);return}Pe(!0),ss({authorizationUrl:Ws,handoff:ct.auth.handoff});return}Be(null),_s(ct);const xs={};for(const Ws of ct.actions.readOnly)xs[Ws.catalogEntryId]=!0;for(const Ws of ct.actions.canMakeChanges)xs[Ws.catalogEntryId]=!0;mr(xs),Va.mutate({result:ct,enabled:xs})},"onSuccess"),onError:r(ct=>{const xs=ct instanceof nn&&ct.body&&typeof ct.body=="object"?ct.body.details:null;if(fr){qs("error"),k?.("needs_retry"),Ns(xs?.code==="invalid_grant"?"Your authorization expired or was revoked. Reconnect to continue.":ct instanceof Error?ct.message:"Paperclip couldn’t start secure sign-in. Try again.");return}if(!le&&_e){const Ws=typeof xs?.code=="string"?xs.code:null,Sn=dae(Ws,ct instanceof Error?ct.message:null);Be(Sn),Pe(!1),Sn.focus==="credentials"&&(bt(!0),Rt(!0));return}Q({title:"Couldn’t connect",body:ct instanceof Error?ct.message:"Please check your key and try again.",tone:"error"})},"onError")}),Qn=ds.mutate,ra=(0,m.useCallback)(ct=>{const xs=ct??le;(xs?EI(xs,ge||null):null)?.auth==="oauth"&&es(),Qn(ct)},[ge,le,Qn,es]);(0,m.useEffect)(()=>{if(!pe||Un.isLoading||!Un.data||(ne||oe)&&(!zs.isFetchedAfterMount||!En.isFetchedAfterMount))return;if(ne&&U==="complete"&&xn?.status==="active"&&Zs!==ne&&Fa){_(`/apps/${xn.id}/permissions`,{replace:!0});return}if(ne&&!Fa)return;const ct=$mt({requestedAppKey:pe,galleryApps:Un.data.apps,reconnectConnection:hn,resumeConnection:xn,resumeApplication:Dr,completedResumeConnectionId:Zs,applications:En.data?.applications??[]}),xs=!!ct?.methods.some(Se=>Se.oauthStrategy==="paperclip_cloud_connector"||Se.oauthStrategy==="paperclip_id_connector");if(fn&&!xs&&ln.isLoading)return;const Ws=D1(ct,i),Sn=v??(hn?.connectionPurpose==="ai"?VB.safeParse(hn.config?.ai).data:void 0),Jn=Ws.find(Se=>Sn?Se.ai?.provider===Sn.provider&&(!("mode"in Sn)||Sn.mode!=="responsible_user")&&Se.ai.method===Sn.method:Se.key===V)??(fn&&!xs?gae(dn):null)??Rk(Ws),wn=Ws.length===1?Ws[0]:null,ca=i==="paperclip_vault"&&!!vae(ct),Ga=Bmt({credentialSource:i,available:Un.data.credentialSources?.vercelConnect.available===!0,retainedReconnectMatches:!!(oe&&Zt)}),Ye=Ws.length===1&&wn?.auth==="oauth"&&!T0(wn)&&!fk(wn),Ft=Fmt({available:ct?.availability?.available,reconnectConnectionId:oe,reconnectSourceMatches:Zt}),ys=zmt({reconnectConnectionId:oe,hasRequestedEntry:!!ct,supportedMethodCount:Ws.length,unsupportedOAuth:Ye,vercelUnavailable:Ga,definitionUnavailable:Ft});if(ys!=="ready"){if(Re(null),xe("gallery"),ys==="reconnect_unavailable"&&oe){Ge(oe);return}_(RI(i==="vercel_connect"?oD():"/apps/connect",F),{replace:!0});return}if(Ge(null),!!ct){if(le?.slug!==ct.slug){Re(ct),je(ct.name),Ze(""),Fe(""),bt(!1),qe(""),be({}),Lt(""),lt(""),Ke(""),Xe(Jn?.key??""),zt(LS(Jn)),he(""),Dt(null),_s(null);const Se=ve?.companyId===T?ve:null;Ut(Te??Se?.grantKind??dD(Jn,!!c)),ze(new Set(Se?.agentIds??(c?[c]:[]))),os(Se?.installChoice??(c?"specific":"all")),xe(hae({requestedAppKey:pe,routeStage:U,resumeConnectionId:ne,hasPrefilledLink:!!Ie.link,zapierSource:ce}))}else Sr!==xs&&(Re(ct),Xe(Jn?.key??""),zt(LS(Jn)));if(!(ca&&(!En.isFetchedAfterMount||!zs.isFetchedAfterMount))&&!(ca&&on.current)&&ca&&(En.isError||zs.isError)){qs("error"),Ns("Paperclip couldn’t check for an existing connection. Try again."),xe("key");return}}},[v,V,En.isError,En.isFetchedAfterMount,En.data,zs.isError,zs.isFetchedAfterMount,ln.data?.configured,ln.isLoading,ge,i,le?.slug,Sr,Un.data,Un.isLoading,_,Te,hn,oe,Zt,xn,Dr,Fa,Zs,ba,U,ne,dn,pe,c,ve,U,ce]),(0,m.useEffect)(()=>{as.current=null,bs(null)},[ne]),(0,m.useEffect)(()=>{const ct=xn??hn;if(!ct||!le||as.current===ct.id)return;const xs=NQ(ct),Ws=typeof xs.sourceTemplateKey=="string"?xs.sourceTemplateKey:null;if(Ws&&Ws!==le.slug)return;const Sn=typeof xs.connectionMethodKey=="string"?xs.connectionMethodKey:null,Jn=Sn?D1(le,i).find(ca=>ca.key===Sn)??null:null;if(je(ct.name||le.name),Jn){Xe(Jn.key);const ca=xs.methodConfig&&typeof xs.methodConfig=="object"?xs.methodConfig:{};zt({...LS(Jn),...Object.fromEntries(Object.entries(ca).filter(Ga=>typeof Ga[1]=="string"||typeof Ga[1]=="boolean"))})}const wn=xs.oauth&&typeof xs.oauth=="object"?xs.oauth:null;wn?.clientRegistrationSource==="manual"&&typeof wn.clientId=="string"&&Lt(wn.clientId),Z==="failed"||Z==="denied"?(qs("error"),Ns(mae(Z,ie))):(qs("entry"),Ns(null)),xe("key"),as.current=ct.id,bs(ct.id)},[i,le,ie,Z,xn,hn]);const Va=we({mutationFn:r(async ct=>{const{result:xs,enabled:Ws}=ct,Sn=Object.entries(Ws).filter(([,Ga])=>Ga).map(([Ga])=>Ga),Jn=C2e(xs,Ga=>!!Ws[Ga]),wn=Ct==="all"?"all_agents":{agentIds:Array.from(jt)},ca=await ts.finishApp(T,xs.connectionId,{enabledCatalogEntryIds:Sn,askFirstCatalogEntryIds:Jn,...ir?{agentInstructions:ir}:{},access:wn,...c?{preserveExistingAccess:!0}:{}});return await ye(xs.connectionId),ca},"mutationFn"),onSuccess:r(async(ct,xs)=>{ne&&xs.result.connectionId===ne&&Nn(ne),await S.invalidateQueries({queryKey:["tools"]}),await S.invalidateQueries({queryKey:D.apps.attention(T)}),Ha("success"),x?.({connectionId:xs.result.connectionId})},"onSuccess"),onError:r(ct=>{Ha("key"),Q({title:"Couldn’t finish setup",body:ct instanceof Error?ct.message:"Please try again.",tone:"error"})},"onError")});if(!T)return(0,t.jsx)("div",{className:"p-6 text-sm text-muted-foreground",children:"Select an organization to connect apps."});if((ne||oe)&&(zs.isError||En.isError))return(0,t.jsxs)("div",{className:"mx-auto max-w-xl rounded-xl border border-border bg-card p-6",children:[(0,t.jsx)("h2",{className:"text-lg font-semibold text-foreground",children:"Couldn’t load connection setup"}),(0,t.jsx)("p",{className:"mt-2 text-sm text-muted-foreground",children:"Paperclip couldn’t check the retained connection. The retained connection was not changed."}),(0,t.jsxs)("div",{className:"mt-5 flex flex-wrap gap-2",children:[(0,t.jsx)($,{type:"button",onClick:r(async()=>{const[ct,xs]=await Promise.all([zs.refetch(),En.refetch()]);!ct.isError&&!xs.isError&&(Ns(null),qs("entry"))},"onClick"),children:"Try again"}),(0,t.jsx)($,{type:"button",variant:"outline",onClick:r(()=>_("/apps"),"onClick"),children:"Back to apps"})]})]});if(ne&&zs.isFetchedAfterMount&&!xn)return(0,t.jsxs)("div",{className:"mx-auto max-w-xl rounded-xl border border-border bg-card p-6",children:[(0,t.jsx)("h2",{className:"text-lg font-semibold text-foreground",children:"This setup can’t be resumed"}),(0,t.jsx)("p",{className:"mt-2 text-sm text-muted-foreground",children:"The saved connection no longer exists or is not available to this organization."}),(0,t.jsx)($,{type:"button",variant:"outline",className:"mt-5",onClick:r(()=>_("/apps"),"onClick"),children:"Back to apps"})]});if(ne&&zs.isFetchedAfterMount&&En.isFetchedAfterMount&&xn&&!Fa)return(0,t.jsxs)("div",{className:"mx-auto max-w-xl rounded-xl border border-border bg-card p-6",children:[(0,t.jsx)("h2",{className:"text-lg font-semibold text-foreground",children:"This setup can’t be resumed"}),(0,t.jsx)("p",{className:"mt-2 text-sm text-muted-foreground",children:"This saved draft does not match the requested provider. The connection was not changed."}),(0,t.jsx)($,{type:"button",variant:"outline",className:"mt-5",onClick:r(()=>_("/apps"),"onClick"),children:"Back to apps"})]});if(oe&&zs.isFetchedAfterMount&&En.isFetchedAfterMount&&(!hn||!Zt))return(0,t.jsxs)("div",{className:"mx-auto max-w-xl rounded-xl border border-border bg-card p-6",children:[(0,t.jsx)("h2",{className:"text-lg font-semibold text-foreground",children:"This connection can’t be reconnected"}),(0,t.jsx)("p",{className:"mt-2 text-sm text-muted-foreground",children:hn?"This reconnect link does not match the retained connection's provider.":"The retained connection no longer exists or is not available to this organization."}),(0,t.jsx)($,{type:"button",variant:"outline",className:"mt-5",onClick:r(()=>_("/apps"),"onClick"),children:"Back to apps"})]});if((ne||oe)&&Un.isError)return(0,t.jsxs)("div",{className:"mx-auto max-w-xl rounded-xl border border-border bg-card p-6",children:[(0,t.jsx)("h2",{className:"text-lg font-semibold text-foreground",children:"Couldn’t load connection setup"}),(0,t.jsx)("p",{className:"mt-2 text-sm text-muted-foreground",children:"Paperclip couldn’t load the provider details needed to restore this connection. The retained connection was not changed."}),(0,t.jsxs)("div",{className:"mt-5 flex flex-wrap gap-2",children:[(0,t.jsx)($,{type:"button",onClick:r(()=>{Un.refetch()},"onClick"),children:"Try again"}),(0,t.jsx)($,{type:"button",variant:"outline",onClick:r(()=>_("/apps"),"onClick"),children:"Back to apps"})]})]});if(oe&&gt===oe)return(0,t.jsxs)("div",{className:"mx-auto max-w-xl rounded-xl border border-border bg-card p-6",children:[(0,t.jsx)("h2",{className:"text-lg font-semibold text-foreground",children:"This connection can’t be reconnected"}),(0,t.jsx)("p",{className:"mt-2 text-sm text-muted-foreground",children:"Paperclip no longer has a supported setup method for this retained connection. The retained connection was not changed."}),(0,t.jsx)($,{type:"button",variant:"outline",className:"mt-5",onClick:r(()=>_("/apps"),"onClick"),children:"Back to apps"})]});if(ne&&(!zs.isFetchedAfterMount||Un.isLoading||!le||Xs!==xn?.id))return(0,t.jsxs)("div",{className:"mx-auto max-w-xl space-y-4","aria-label":"Loading saved connection setup",children:[(0,t.jsx)(yn,{className:"h-8 w-48"}),(0,t.jsx)(yn,{className:"h-40 w-full rounded-xl"})]});if(oe&&(!zs.isFetchedAfterMount||!En.isFetchedAfterMount||Un.isLoading||pe&&!le))return(0,t.jsxs)("div",{className:"mx-auto max-w-xl space-y-4","aria-label":"Loading retained connection setup",children:[(0,t.jsx)(yn,{className:"h-8 w-48"}),(0,t.jsx)(yn,{className:"h-40 w-full rounded-xl"})]});if(Nr&&f)return(0,t.jsxs)("div",{className:"max-w-5xl","data-testid":"connection-existing-choice",children:[(0,t.jsxs)("div",{className:"mb-6",children:[(0,t.jsxs)("h1",{className:"text-2xl font-bold tracking-tight",children:["Use an existing ",pe?"connection":"app connection"]}),(0,t.jsx)("p",{className:"mt-1 text-sm text-muted-foreground",children:"Reuse a connection without changing who already has access, or connect a new one."})]}),(0,t.jsx)(uv,{choices:h.map(ct=>({id:ct.id,name:ct.name,description:ct.status==="active"&&ct.enabled?"Ready to use":"Setup needs attention"})),pendingId:Ur,onSelect:r(async ct=>{ga(ct),ur(null);try{await f(ct)}catch(xs){ur(xs instanceof Error?xs.message:"Couldn’t use this connection."),ga(null)}},"onSelect")}),ar?(0,t.jsx)(ua,{tone:"danger",className:"mt-4",children:ar}):null,(0,t.jsxs)("div",{className:"mt-5 flex flex-wrap gap-2",children:[(0,t.jsx)($,{type:"button",variant:"outline",onClick:r(()=>Or(!1),"onClick"),children:p?"Review connection setup":"Connect new"}),w?(0,t.jsx)($,{type:"button",variant:"ghost",onClick:w,children:"Cancel"}):null]})]});const ci=D1(le,i),oi=ia?[ia]:ci,Ka=le?ge?oi.find(ct=>ct.key===ge)??null:oi[0]??null:null,Lr=le?Ka?.auth??"none":it==="none"?"none":it==="oauth"?"oauth":"api_key",di=de==="key"?((ct,xs)=>(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)(IV,{extra:ct,forceOpen:xs,companyId:T,sentence:AE({grantKind:ft,authKind:Lr,installChoice:Ct,installCount:jt.size,lockedAgentId:c??null,preserveAgentAccess:!!(fr&&(Wt||hn))}),notice:[Un.data?.capabilities?.canCreateOrganizationGrant===!1?Un.data.capabilities.organizationGrantReason??"Only a connection manager can share this credential with the organization.":null,Un.data?.capabilities?.canSetCompanyInstall===!1?Un.data.capabilities.companyInstallReason??"Only someone who can configure this connection can give every agent access.":null,c?"This task grants access only to the agent that asked for it.":null].filter(Ws=>!!Ws),authKind:Lr,grantKinds:Js?[Js]:Ka?.grantKinds,grantKind:ft,setGrantKind:Ut,installChoice:Ct,setInstallChoice:os,installAgentIds:jt,setInstallAgentIds:ze,lockedAgentId:c,capabilities:Un.data?.capabilities,githubIdentity:le?.slug==="github",identityLoading:!!fr&&vi,preserveAgentAccess:!!(fr&&(Wt||hn)),disabled:ds.isPending||il.isPending},"connection-defaults"),le&&Mi&&ir&&(0,t.jsx)("div",{className:"mt-6",children:(0,t.jsx)(wH,{provider:le.name,template:Mi,value:ir,onChange:r(Ws=>Ht({slug:le.slug,value:Ws}),"onChange"),disabled:ds.isPending||il.isPending})}),e&&(0,t.jsx)("div",{className:"mt-6",children:e})]})):null,zi=fr&&ti&&fk(ti)?ti:null,Co=zi&&fr?(0,t.jsx)(zz,{entry:fr,method:zi,callbackUrl:pt,clientId:nt,onClientIdChange:Lt,clientSecret:Cs,onClientSecretChange:lt,required:!1}):null,za=di?.()??null,pi=Co?di?.(Co,Bs==="error"||nt.trim().length>0)??null:za,_o=!!(fr&&de==="key"&&(Ta||Bs!=="entry")),Fd=!!(de==="key"&&le&&fn&&!Sr&&ln.data?.configured===!0),nd=!!(de==="key"&&le&&fn&&!Sr&&(ln.isLoading||ln.isError||ln.data?.configured!==!0));if(_o&&fr)return(0,t.jsx)(Bz,{entry:fr,resuming:!!ne,phase:Bs,error:Rn,recoveryActions:ie==="github_installation_required"?{installationUrl:J,managementUrl:ae}:void 0,authorizationHost:Yn,authorizationUrl:Cr,guidance:le?.slug==="railway"&&Ka?(0,t.jsxs)("div",{className:"space-y-3 text-sm text-muted-foreground",children:[(0,t.jsx)("p",{children:Ka.guidanceMd}),(0,t.jsx)("ul",{className:"list-disc space-y-2 pl-5",children:Ka.warnings?.map(ct=>(0,t.jsx)("li",{children:ct},ct))})]}):null,defaults:pi,settingsValid:n&&Vi,onOpenAuthorization:As,onRetry:r(async()=>{const ct=!Hs.current;Hs.current=!0,Ns(null),qs("starting");const xs=ns?.connection??Wt;if(xs&&Co&&nt.trim()){Tt.current=xs.id,ra(fr);return}if(xs){eo(xs);return}if(ct&&!ne&&!En.isError&&!zs.isError){ra(fr);return}on.current=!0;try{const[Ws,Sn]=await Promise.all([En.refetch(),zs.refetch()]);if(Ws.isError||Sn.isError){qs("error"),Ns("Paperclip couldn’t check for an existing connection. Try again.");return}const Jn=(ne?(Sn.data?.connections??[]).find(wn=>wn.id===ne&&wn.authKind==="oauth")??null:null)??yae(re,Ws.data?.applications??[],Sn.data?.connections??[],K?{applicationId:Ie.applicationId,draftOnly:!0}:{});Jn&&!ne&&Ut(Jn.credentialPolicy==="per_user"?"user":Jn.credentialPolicy==="per_agent"?"agent":"organization"),Jn?eo(Jn):ds.mutate(fr)}finally{on.current=!1}},"onRetry"),onBack:r(()=>{Cn.current?.abort(),qs("entry"),Ns(null),vn()},"onBack"),onCancel:r(()=>{Cn.current?.abort(),(w??(()=>_("/apps")))()},"onCancel")});if(Oe&&!le&&_e&&de==="key")return(0,t.jsx)(Bz,{identity:{name:ue.trim()||d_(_e)||"this server",unverifiedHost:d_(_e)},steps:{labels:fae,activeIndex:xae.key},phase:Bs,error:Rn,authorizationHost:Yn,authorizationUrl:Cr,defaults:za,onOpenAuthorization:As,onRetry:r(()=>{Ns(null);const ct=ns?.connection;if(ct){qs("starting"),eo(ct);return}Pe(!1),qs("entry")},"onRetry"),onBack:r(()=>{Cn.current?.abort(),Pe(!1),qs("entry"),Ns(null)},"onBack"),onCancel:r(()=>{Cn.current?.abort(),(w??(()=>_("/apps")))()},"onCancel")});const Ue=ns?.application.name??le?.name??(ue.trim()||cD(_e)||"this app"),Et=X?Is.filter(ct=>D1(ct,i).length>0):Is,Kt=ce?Un.data?.apps.find(ct=>ct.slug==="zapier")??null:null,Ds=(hn?.connectionPurpose==="ai"?VB.safeParse(hn.config?.ai).data:void 0)??le?.methods.find(ct=>ct.key===ge)?.ai??(!ge&&le?.methods.every(ct=>ct.ai)?le.methods[0]?.ai:void 0),en=le?N?.({app:le,name:Le||le.name,grantKind:ft,agentIds:[...jt],allAgents:Ct==="all",onBack:r(()=>vn(),"onBack")})??(Ds&&T?(0,t.jsx)(t.Fragment,{children:(0,t.jsx)(v5,{defaults:hn?void 0:za,companyId:T,provider:Ds.provider,fixedMethod:!!(v&&v.mode!=="responsible_user"),initialMethod:hn?.connectionPurpose==="ai"?(hn.config?.ai).method:Ds.method,connectionId:hn?.connectionPurpose==="ai"?hn.id:void 0,name:hn?.connectionPurpose==="ai"?hn.name:Le||`My ${le.name} ${Ds.method==="subscription"?"subscription":"API"}`,ownership:(hn?.connectionPurpose==="ai"?hn.credentialPolicy==="shared":ft==="organization")?"shared":"personal",agentIds:[...jt],allAgents:Ct==="all",onCancel:r(()=>w?w():_("/apps"),"onCancel"),onComplete:r(ct=>{x?.({connectionId:ct.connectionId}),x||_(`/apps/${ct.connectionId}/permissions`)},"onComplete")})}):void 0):void 0,si=hn?.connectionPurpose==="ai"?["Reconnect account"]:en!==void 0?["Connect account"]:ce?Umt:le&&oi.length>1?["Choose connection"]:le&&oi[0]?.auth==="oauth"?["Sign in"]:CC(le,ge)?["Share sheet"]:le?["Add your key"]:fae,Ra=hn?.connectionPurpose==="ai"?0:(ce||le)&&de!=="gallery"&&de!=="success"?qmt[de]:de==="success"?si.length:xae[de];return(0,t.jsxs)("div",{className:"max-w-5xl",children:[de!=="success"&&!(a&&de==="gallery")&&(0,t.jsx)(sM,{subtitle:de==="gallery"?X?"Choose a reviewed app to connect through Vercel.":"Pick the app you want your agents to use.":si.length<=1?void 0:`Step ${Ra+1} of ${si.length}`,step:de,activeIndex:Ra,labels:si,appIdentity:ce?{name:"Zapier",logoUrl:Kt?.branding.logoUrl??null,darkLogoUrl:Kt?.branding.darkLogoUrl??null}:le&&de!=="gallery"?{name:le.name,logoUrl:le.branding.logoUrl,darkLogoUrl:le.branding.darkLogoUrl??null}:void 0,unverifiedHost:!le&&!ce&&de!=="gallery"?d_(_e):null,onCancel:w??(()=>_("/apps"))}),de==="key"&&s&&(0,t.jsx)("div",{className:"mx-auto mb-6 max-w-xl",children:s}),de==="gallery"&&(0,t.jsx)(Ymt,{loading:Un.isLoading,initialLink:_e,apps:Et,vercelConnect:X,vercelConnectAvailability:Un.data?.credentialSources?.vercelConnect??null,byo:fe,byoOnly:a,source:L.get("source"),onPick:kn,onUseLink:r(ct=>{const xs=mR(ct,Is);Re(null),je(""),Ze(ct),Fe(xs?.name??cD(ct)??""),bt(!1),qe(""),be({}),he(""),Dt(null),ze(new Set(c?[c]:[])),os(c?"specific":"all"),Ut(Te??(c?"user":"organization")),xe("key")},"onUseLink")}),Fd&&le?(0,t.jsxs)("div",{className:"mx-auto max-w-xl rounded-xl border border-border bg-card p-6",children:[(0,t.jsxs)("h2",{className:"text-lg font-semibold text-foreground",children:[le.name," sign-in is unavailable"]}),(0,t.jsxs)("p",{className:"mt-2 text-sm text-muted-foreground",children:["This instance is connected to Paperclip, but ",le.name," sign-in is not currently available. Try again shortly or contact your instance administrator."]}),_n?(0,t.jsxs)($,{type:"button",variant:"link",className:"mt-4 h-auto p-0 text-xs",onClick:r(()=>Xe(_n.key),"onClick"),children:["Use your own ",le.name," OAuth app"]}):null,(0,t.jsxs)("div",{className:"mt-6 flex items-center justify-between gap-3",children:[(0,t.jsx)($,{type:"button",variant:"ghost",onClick:vn,children:"Back"}),(0,t.jsxs)($,{type:"button",disabled:Un.isFetching,onClick:r(()=>{Un.refetch()},"onClick"),children:[Un.isFetching?(0,t.jsx)(st,{className:"h-4 w-4 animate-spin"}):null,"Try again"]})]})]}):de==="key"&&le&&nd?(0,t.jsx)("div",{className:"mx-auto max-w-xl",children:(0,t.jsxs)("div",{className:"rounded-xl border border-border bg-card p-6",children:[(0,t.jsxs)("div",{className:"flex items-start gap-3",children:[(0,t.jsx)("div",{className:"rounded-lg bg-muted p-2 text-muted-foreground",children:(0,t.jsx)(qb,{className:"h-5 w-5"})}),(0,t.jsxs)("div",{className:"min-w-0",children:[(0,t.jsx)("h2",{className:"text-lg font-semibold text-foreground",children:"Connect with Paperclip"}),(0,t.jsxs)("p",{className:"mt-2 text-sm text-muted-foreground",children:["You must connect this instance to Paperclip to connect to ",le.name," (you only need to do this once)."]})]})]}),_n?(0,t.jsxs)($,{type:"button",variant:"link",className:"mt-4 h-auto p-0 text-xs",onClick:r(()=>Xe(_n.key),"onClick"),children:["Use your own ",le.name," OAuth app"]}):null,ln.isError||Tr?(0,t.jsx)(ua,{tone:"danger",className:"mt-4",children:Tr??"Paperclip couldn’t check Cloud registration. Try again."}):null,Da?(0,t.jsxs)("p",{className:"mt-4 text-sm text-muted-foreground",children:["Finish authorization in the opened window."," ",(0,t.jsx)("a",{className:"underline",href:Da,target:"_blank",rel:"noopener noreferrer",children:"Open authorization in a new tab"})]}):null,za,(0,t.jsxs)("div",{className:"mt-6 flex items-center justify-between gap-3",children:[(0,t.jsx)($,{type:"button",variant:"ghost",onClick:vn,children:"Back"}),(0,t.jsxs)($,{type:"button",disabled:ln.isLoading||jn.isPending,onClick:r(()=>{Zn(null),es(),Wr(),jn.mutate()},"onClick"),children:[jn.isPending?(0,t.jsx)(st,{className:"h-4 w-4 animate-spin"}):null,ln.data?.status==="pending"?"Continue":"Connect with Paperclip"]})]})]})}):de==="key"&&le&&en!==void 0?en:de==="key"&&le?(0,t.jsx)(Xmt,{settingsValid:n&&Vi,entry:le,error:ds.isError?ds.error instanceof Error?ds.error.message:"Please check your key and try again.":null,values:Ve,onChange:be,oauthClientId:nt,onOAuthClientIdChange:Lt,oauthClientSecret:Cs,oauthCallbackUrl:pt,canReuseOAuthClientSecret:!!(ps?.config?.oauth&&ps.config.oauth.clientId===nt.trim()&&ps.hasSavedOAuthClientSecret),onOAuthClientSecretChange:lt,credentialSource:i,vercelConnector:Os,onVercelConnectorChange:Ke,vercelConnectAvailability:Un.data?.credentialSources?.vercelConnect??null,methodKey:ge,onMethodChange:r(ct=>{Xe(ct?.key??""),!Te&&ct?.grantKinds&&!ct.grantKinds.includes(St)&&Ut(dD(ct,!!c)),be({}),Lt(""),lt(""),Ke(""),zt(LS(ct))},"onMethodChange"),configValues:ht,onConfigChange:zt,googleSheetsLinks:$e,googleSheetsError:Vt,onGoogleSheetsLinksChange:r(ct=>{he(ct),Dt(null)},"onGoogleSheetsLinksChange"),submitting:ds.isPending,renderDefaults:di??void 0,onBack:vn,onConnect:r(()=>{if(CC(le,ge)){const Ws=zF($e);if(Ws.invalidCount>0){Dt("That doesn't look like a Google Sheets link.");return}if(Ws.ids.length===0){Dt("Paste at least one Google Sheets link.");return}}const ct=EI(le,ge||null),xs=!!(ct?.credentialFields?.length||ct?.tenantFields?.some(Ws=>!Ws.hidden)||ct?.extensionFields?.some(Ws=>!Ws.hidden));if(ct&&T0(ct)&&Wt&&!xs&&!nt.trim()){Hs.current=!0,Ns(null),qs("starting"),eo(Wt);return}ct&&T0(ct)&&(Hs.current=!0,Ns(null),qs("starting")),ra()},"onConnect")}):null,de==="key"&&!le&&!_e&&!ce&&pe&&(0,t.jsxs)("div",{className:"mx-auto max-w-xl","aria-busy":"true","aria-label":`Loading ${pe} setup`,children:[(0,t.jsx)(yn,{className:"h-6 w-2/3 rounded-md"}),(0,t.jsx)(yn,{className:"mt-3 h-4 w-full rounded-md"}),(0,t.jsx)(yn,{className:"mt-8 h-11 w-40 rounded-md"})]}),de==="key"&&!le&&_e&&!ce&&(0,t.jsx)(Zmt,{link:_e,name:ue,needsKey:mt,keyValue:et,onKeyChange:qe,authMode:it,onAuthModeChange:r(ct=>{_t(ct),Be(null),ct!=="auto"&&bt(!1),ct!=="bearer"&&ct!=="auto"&&qe("")},"onAuthModeChange"),headers:$t,onHeadersChange:r(ct=>{Ot(ct),Be(null)},"onHeadersChange"),oauthClientId:at,onOAuthClientIdChange:Me,oauthClientSecret:De,onOAuthClientSecretChange:ut,advancedOpen:Pt,onAdvancedOpenChange:Rt,guidance:Qe,matchedEntry:gn,onUseMatchedEntry:gn?()=>kn(gn):void 0,submitting:ds.isPending||Oe,defaults:za,onBack:vn,onConnect:r(()=>{Be(null),ds.mutate(void 0)},"onConnect")}),de==="key"&&!le&&ce&&(0,t.jsx)(Gmt,{link:_e,onLinkChange:Ze,submitting:ds.isPending,defaults:za,onBack:vn,onConnect:r(()=>ds.mutate(void 0),"onConnect")}),de==="success"&&(0,t.jsx)(nht,{appName:Ue,logoUrl:le?.branding.logoUrl,darkLogoUrl:le?.branding.darkLogoUrl,summary:sht({grantKind:ft,authKind:Lr,installChoice:Ct,installCount:jt.size,enabledCount:Object.values(cn).filter(Boolean).length}),statedDefault:AE({grantKind:ft,authKind:Lr,installChoice:Ct,installCount:jt.size,lockedAgentId:c??null}),onDone:w??(()=>_(o==="page"&&ns?.connectionId?`/apps/${ns.connectionId}/permissions`:"/apps"))})]})}r(Vmt,"StandardConnectionSetupFlow");function Bz({entry:e,identity:s,resuming:n=!1,phase:a,error:i,recoveryActions:o,authorizationHost:l,authorizationUrl:c,steps:d={labels:Kmt,activeIndex:0},guidance:u,defaults:h,onRetry:p,settingsValid:f=!0,onOpenAuthorization:x,onBack:g,onCancel:v}){const y=e?.name??s?.name??"this server",k=e?null:s?.unverifiedHost??null,w=a==="entry"?{title:n?`Finish connecting ${y}`:`Connect ${y} to Paperclip`,body:n?`Your connection is saved. Continue in ${y} to approve access; its identity and agent access will stay the same.`:`Paperclip will open ${y} so you can choose a workspace and approve access.`}:a==="starting"?{title:"Preparing secure sign-in",body:`Paperclip is creating a secure ${y} connection.`}:a==="redirecting"?{title:`Opening ${y}`,body:l?`Continue at ${l} to choose a workspace and approve access. Only approve access if you recognize that address.`:`Continue in ${y} to choose a workspace and approve access.`}:{title:`${y} couldn’t connect`,body:i??"Paperclip couldn’t start secure sign-in. Try again."};return(0,t.jsxs)("div",{className:"max-w-5xl",children:[(0,t.jsx)(sM,{subtitle:"Secure MCP sign-in",step:"key",activeIndex:d.activeIndex,labels:d.labels,appIdentity:e?{name:e.name,logoUrl:e.branding.logoUrl,darkLogoUrl:e.branding.darkLogoUrl}:void 0,unverifiedHost:k,onCancel:v}),(0,t.jsxs)("div",{className:"mx-auto max-w-xl",children:[(0,t.jsxs)("div",{className:"flex items-start gap-3",children:[(0,t.jsx)("span",{className:"mt-1 inline-flex h-10 w-10 shrink-0 items-center justify-center rounded-lg border border-border bg-background",children:a==="error"?(0,t.jsx)(Ml,{className:"h-5 w-5 text-destructive"}):a==="entry"?(0,t.jsx)(ko,{className:"h-5 w-5 text-muted-foreground"}):(0,t.jsx)(st,{className:"h-5 w-5 animate-spin text-muted-foreground"})}),(0,t.jsxs)("div",{className:"min-w-0",children:[(0,t.jsx)("h2",{className:"text-xl font-bold tracking-tight",children:w.title}),(0,t.jsx)("p",{className:"mt-1 text-sm text-muted-foreground",children:w.body}),k?(0,t.jsx)(tM,{host:k,className:"mt-2"}):null]})]}),a==="entry"&&u?(0,t.jsx)("div",{className:"mt-4",children:u}):null,a==="entry"||a==="error"?h:null,a==="error"&&o&&(o.installationUrl||o.managementUrl)?(0,t.jsxs)("div",{className:"mt-4 flex flex-wrap gap-2",children:[o.installationUrl?(0,t.jsx)($,{type:"button",variant:"outline",asChild:!0,children:(0,t.jsxs)("a",{href:o.installationUrl,target:"_blank",rel:"noreferrer",children:["Install Paperclip on GitHub",(0,t.jsx)(oo,{className:"ml-1.5 h-3.5 w-3.5"})]})}):null,o.managementUrl?(0,t.jsx)($,{type:"button",variant:"ghost",asChild:!0,children:(0,t.jsx)("a",{href:o.managementUrl,target:"_blank",rel:"noreferrer",children:"Manage repositories on GitHub"})}):null]}):null,(0,t.jsxs)("div",{className:"mt-6 flex items-center gap-2",children:[a==="error"||a==="entry"?(0,t.jsxs)($,{type:"button",onClick:p,disabled:!f,children:[a==="entry"?n?`Finish with ${y}`:`Continue to ${y}`:"Try again",a==="entry"?(0,t.jsx)(oo,{className:"h-4 w-4","aria-hidden":"true"}):null]}):(0,t.jsx)($,{type:"button",disabled:!0,children:a==="redirecting"?`Opening ${y}…`:"Preparing…"}),c?(0,t.jsx)($,{variant:"outline",asChild:!0,children:(0,t.jsx)("a",{href:c,target:"_blank",rel:"noopener noreferrer",onClick:x,children:"Open sign-in in a new tab"})}):null,(0,t.jsx)($,{type:"button",variant:"ghost",onClick:g,children:"Back"})]})]})]})}r(Bz,"OAuthConnectStateScreen");function Gmt({link:e,onLinkChange:s,submitting:n,defaults:a,onBack:i,onConnect:o}){const l=Fz(e),c=l?new URL(l).hostname:"",d=c==="zapier.com"||c.endsWith(".zapier.com");return(0,t.jsxs)("div",{className:"mx-auto max-w-xl",children:[(0,t.jsxs)("div",{children:[(0,t.jsx)("label",{className:"text-sm font-medium text-foreground",children:"Zapier MCP URL"}),(0,t.jsx)(dt,{type:"password",autoComplete:"off",spellCheck:!1,value:e,onChange:r(u=>s(u.target.value),"onChange"),onKeyDown:r(u=>{u.key==="Enter"&&d&&!n&&o()},"onKeyDown"),placeholder:"https://mcp.zapier.com/api/v1/connect?token=…",className:"mt-2 h-11",autoFocus:!0}),e.trim()&&!d&&(0,t.jsx)("p",{className:"mt-2 text-xs text-destructive",children:"Paste a valid Zapier URL to continue."})]}),a,(0,t.jsxs)("div",{className:"mt-6 flex items-center justify-between",children:[(0,t.jsx)($,{variant:"ghost",onClick:i,disabled:n,children:"Back"}),(0,t.jsxs)($,{onClick:o,disabled:n||!d,children:[n&&(0,t.jsx)(st,{className:"mr-2 h-4 w-4 animate-spin"}),n?"Checking…":"Check link"]})]})]})}r(Gmt,"ZapierConnectStep");function Ymt({loading:e,initialLink:s="",apps:n,byo:a=!1,byoOnly:i=!1,vercelConnect:o=!1,vercelConnectAvailability:l=null,source:c=null,onPick:d,onUseLink:u}){const[h,p]=(0,m.useState)(""),[f,x]=(0,m.useState)(s),g=(0,m.useRef)(!1);(0,m.useEffect)(()=>{g.current||x(s)},[s]);const[v,y]=(0,m.useState)(null),k=(0,m.useRef)(null),w=(0,m.useRef)(null),N=(0,m.useRef)(!1);(0,m.useEffect)(()=>{!a||e&&!i||N.current||(i||k.current?.scrollIntoView?.({block:"center"}),w.current?.focus(),w.current?.select(),N.current=!0)},[a,i,e]);const S=(0,m.useMemo)(()=>{const T=h.trim().toLowerCase();return n.filter(E=>!T||E.name.toLowerCase().includes(T))},[n,h]),C=Fz(f),_=C?mR(C,n):null,R=c==="zapier",I=r(()=>{const T=Fz(f);if(!T){y("Paste a full http or https link.");return}y(null),u(T)},"continueWithLink");return e&&!i?(0,t.jsx)("div",{className:"grid grid-cols-2 gap-4 sm:grid-cols-3 lg:grid-cols-4",children:Array.from({length:8}).map((T,E)=>(0,t.jsx)(yn,{className:"h-32 w-full rounded-xl"},E))}):(0,t.jsxs)("div",{className:"space-y-6",children:[o?(0,t.jsxs)("div",{className:"rounded-xl border border-border bg-card p-5",children:[(0,t.jsxs)("div",{className:"flex flex-col gap-3 sm:flex-row sm:items-start sm:justify-between",children:[(0,t.jsxs)("div",{children:[(0,t.jsx)("h2",{className:"text-lg font-bold tracking-tight",children:"Connect through Vercel"}),(0,t.jsx)("p",{className:"mt-1 max-w-2xl text-sm text-muted-foreground",children:"Create and manage the provider connector in Vercel. Paperclip stores its reference and applies agent access, policy, approval, and audit controls here."})]}),l?(0,t.jsx)($,{asChild:!0,variant:"outline",size:"sm",className:"shrink-0",children:(0,t.jsxs)("a",{href:l.manageUrl,target:"_blank",rel:"noreferrer",children:["Open Vercel Connect",(0,t.jsx)(oo,{className:"ml-2 h-3.5 w-3.5"})]})}):null]}),l?.available===!1?(0,t.jsx)(ua,{tone:"danger",compact:!0,className:"mt-4",children:l.reason??"Vercel Connect is unavailable on this instance."}):null]}):null,!i&&(0,t.jsxs)(t.Fragment,{children:[(0,t.jsxs)("div",{className:"relative",children:[(0,t.jsx)(Yr,{className:"pointer-events-none absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground"}),(0,t.jsx)(dt,{value:h,onChange:r(T=>p(T.target.value),"onChange"),placeholder:"Search apps…",className:"h-11 pl-9"})]}),(0,t.jsx)("div",{className:"grid grid-cols-2 gap-4 sm:grid-cols-3 lg:grid-cols-4",children:S.map(T=>{const E=r5e(T.slug,T.description),P=Z3(T),O=P.length===0||P.every(Q=>Q.auth==="oauth"&&!T0(Q)&&!fk(Q)),M=T.availability?.available===!1||o&&l?.available!==!0;return(0,t.jsxs)("button",{type:"button",disabled:O||M,title:M?T.availability?.reason??l?.reason??void 0:void 0,onClick:r(()=>d(T),"onClick"),className:W("flex flex-col rounded-xl border border-border bg-card p-4 text-left transition-colors",O||M?"cursor-not-allowed opacity-60":"hover:border-foreground/30 hover:bg-accent/40"),children:[(0,t.jsx)(Hi,{name:T.name,logoUrl:T.branding.logoUrl,darkLogoUrl:T.branding.darkLogoUrl,size:36}),(0,t.jsx)("div",{className:"mt-3 text-sm font-bold text-foreground",children:T.name}),(0,t.jsx)("div",{className:"mt-1 line-clamp-2 text-xs text-muted-foreground",children:E.tagline}),(0,t.jsx)("div",{className:"mt-3 text-xs font-semibold text-foreground",children:M?(0,t.jsx)("span",{className:"text-muted-foreground",children:T.availability?.reason??l?.reason??"Unavailable on this instance."}):O?(0,t.jsx)("span",{className:"text-muted-foreground",children:"Unavailable"}):(0,t.jsx)("span",{children:"Connect →"})})]},T.slug)})}),S.length===0&&(0,t.jsxs)("div",{className:"py-10 text-center text-sm text-muted-foreground",children:["No apps match “",h,"”."]})]}),o?null:(0,t.jsxs)("div",{ref:k,className:W("grid gap-4 border-t border-border pt-5 md:grid-cols-(--gtc-13)",a&&"-mx-3 rounded-xl border border-primary/40 bg-primary/[0.04] px-3 pb-4 md:mx-0"),children:[(0,t.jsxs)("div",{children:[(0,t.jsxs)("div",{className:"flex items-center gap-2 text-sm font-semibold text-foreground",children:[(0,t.jsx)(Ml,{className:"h-4 w-4 text-muted-foreground"}),R?"Connect Zapier":a?"Connect your own MCP server":"Connect with a link"]}),(0,t.jsx)("p",{className:"mt-1 text-xs text-muted-foreground",children:R?"Paste the complete MCP URL Zapier gives you, including its token.":a?"Paste your MCP server’s URL and every discovered tool will be available immediately.":"Paste a setup link from an app that is not listed here."}),!R&&(0,t.jsxs)("p",{className:"mt-1 text-xs text-muted-foreground",children:["Any remote tool URL works here — including a local MCP server like"," ",(0,t.jsx)("code",{className:"rounded bg-muted px-1 py-0.5 text-xs",children:"http://127.0.0.1:8848/mcp"}),"."]}),_&&(0,t.jsxs)("div",{className:"mt-3 flex items-center justify-between gap-3 rounded-lg border border-border bg-muted/40 px-3 py-2",children:[(0,t.jsxs)("div",{className:"flex min-w-0 items-center gap-2 text-sm",children:[(0,t.jsx)(Hi,{name:_.name,logoUrl:_.branding.logoUrl,darkLogoUrl:_.branding.darkLogoUrl,size:24}),(0,t.jsxs)("span",{className:"truncate",children:["This looks like ",_.name,"."]})]}),(0,t.jsx)($,{type:"button",size:"sm",variant:"outline",disabled:_.availability?.available===!1,onClick:r(()=>{if(y(null),_.slug==="zapier"){I();return}d(_)},"onClick"),children:_.availability?.available===!1?"Not available":_.slug==="zapier"?"Continue":`Use ${_.name}`})]})]}),(0,t.jsxs)("div",{className:"flex min-w-0 flex-col gap-2 sm:min-w-(--sz-360px)",children:[(0,t.jsxs)("div",{className:"flex gap-2",children:[(0,t.jsx)(dt,{ref:w,type:R||_?.slug==="zapier"?"password":"url",autoComplete:"off",spellCheck:!1,"aria-label":"MCP server URL",value:f,onChange:r(T=>{g.current=!0,x(T.target.value),y(null)},"onChange"),onKeyDown:r(T=>{T.key==="Enter"&&I()},"onKeyDown"),placeholder:R?"https://mcp.zapier.com/api/v1/connect?token=…":"https://example.com/actions",className:"h-10"}),(0,t.jsx)($,{type:"button",variant:"outline",onClick:I,children:"Continue"})]}),v&&(0,t.jsx)("div",{className:"text-xs text-destructive",children:v})]})]})]})}r(Ymt,"GalleryStep");function Fz(e){try{const s=new URL(e.trim());return s.protocol!=="http:"&&s.protocol!=="https:"?null:s.toString()}catch{return null}}r(Fz,"normalizeAppLink");function Zmt({link:e,name:s,needsKey:n,keyValue:a,onKeyChange:i,authMode:o,onAuthModeChange:l,headers:c,onHeadersChange:d,oauthClientId:u,onOAuthClientIdChange:h,oauthClientSecret:p,onOAuthClientSecretChange:f,advancedOpen:x,onAdvancedOpenChange:g,guidance:v,matchedEntry:y,onUseMatchedEntry:k,submitting:w,defaults:N,onBack:S,onConnect:C}){const _=d_(e),R=o==="custom_headers"?a5e(c):null,I=Rmt({link:e,name:s,authMode:o,needsKey:n,keyValue:a,headers:c,oauthClientId:u,oauthClientSecret:p}),T=o==="auto"&&n||o==="bearer",E=y?.slug==="zapier"?gbe(e):e,P=r((O,M)=>{d(c.map(Q=>Q.id===O?{...Q,...M}:Q))},"updateHeader");return(0,t.jsxs)("div",{className:"mx-auto max-w-xl",children:[(0,t.jsxs)("div",{className:"flex items-center justify-between gap-3",children:[(0,t.jsx)("p",{className:"min-w-0 truncate font-mono text-sm text-muted-foreground",title:E,children:E}),(0,t.jsx)(tM,{host:_})]}),y&&k?(0,t.jsxs)("div",{className:"mt-6 flex flex-wrap items-center justify-between gap-3 rounded-lg border border-border bg-muted/40 px-3 py-2",children:[(0,t.jsxs)("div",{className:"flex min-w-0 items-center gap-2 text-sm",children:[(0,t.jsx)(Hi,{name:y.name,logoUrl:y.branding.logoUrl,darkLogoUrl:y.branding.darkLogoUrl,size:24}),(0,t.jsxs)("span",{className:"truncate",children:["Paperclip has a guided setup for ",y.name,"."]})]}),(0,t.jsxs)($,{type:"button",size:"sm",variant:"outline",onClick:k,children:["Use ",y.name]})]}):null,v?(0,t.jsx)("div",{className:"mt-6",children:(0,t.jsx)(ua,{tone:"warning",title:v.title,children:v.body})}):null,(0,t.jsxs)("div",{className:"mt-6 space-y-6",children:[T?(0,t.jsx)("div",{className:"space-y-4",children:(0,t.jsxs)("div",{children:[(0,t.jsx)("label",{className:"text-sm font-medium text-foreground",htmlFor:"generic-mcp-key",children:"App key"}),(0,t.jsx)(dt,{id:"generic-mcp-key",type:"password",autoComplete:"off",value:a,onChange:r(O=>i(O.target.value),"onChange"),placeholder:"••••••••••••••••",className:"mt-2 h-11 font-mono"}),(0,t.jsx)("p",{className:"mt-2 text-xs text-muted-foreground",children:"Grant this key read and write access to the resources your agents need. Paperclip cannot increase its permissions."})]})}):null,(0,t.jsxs)(tl,{open:x,onOpenChange:g,children:[(0,t.jsxs)(Dl,{className:"flex w-full items-center justify-between rounded-lg border border-border bg-background px-3 py-2 text-left text-sm font-medium text-foreground hover:bg-accent/40",children:["Advanced authentication",(0,t.jsx)(an,{className:W("h-4 w-4 text-muted-foreground transition-transform",x&&"rotate-180")})]}),(0,t.jsxs)(sl,{className:"space-y-5 pt-4",children:[(0,t.jsx)("p",{className:"text-xs text-muted-foreground",children:"Only needed when the server's docs are specific about how to authenticate."}),(0,t.jsx)("div",{className:"flex flex-wrap gap-2",children:jae.map(O=>(0,t.jsx)(Jmt,{label:O.label,selected:o===O.mode,onClick:r(()=>l(O.mode),"onClick")},O.mode))}),(0,t.jsx)("p",{className:"text-xs text-muted-foreground",children:jae.find(O=>O.mode===o)?.hint}),o==="custom_headers"?(0,t.jsxs)("div",{className:"space-y-3",children:[c.map(O=>(0,t.jsxs)("div",{className:"flex items-start gap-2",children:[(0,t.jsx)(dt,{value:O.name,onChange:r(M=>P(O.id,{name:M.target.value}),"onChange"),placeholder:"Header name","aria-label":"Header name",className:"h-10 font-mono"}),(0,t.jsx)(dt,{type:"password",autoComplete:"off",value:O.value,onChange:r(M=>P(O.id,{value:M.target.value}),"onChange"),placeholder:"Value","aria-label":O.name.trim()?`Value for ${O.name.trim()}`:"Header value",className:"h-10 font-mono"}),(0,t.jsx)($,{type:"button",variant:"ghost",size:"sm",className:"h-10 shrink-0",onClick:r(()=>d(c.filter(M=>M.id!==O.id)),"onClick"),disabled:c.length===1,children:"Remove"})]},O.id)),(0,t.jsx)($,{type:"button",variant:"outline",size:"sm",onClick:r(()=>d([...c,Oz()]),"onClick"),children:"Add another header"}),R?(0,t.jsx)("p",{className:"text-xs text-destructive",children:R}):null]}):null,o==="oauth"?(0,t.jsxs)("div",{className:"space-y-4",children:[(0,t.jsx)("p",{className:"text-xs text-muted-foreground",children:"Paperclip sets sign-in up on its own whenever the server allows it. Only fill these in when the server's docs tell you to register Paperclip yourself first."}),(0,t.jsxs)("div",{children:[(0,t.jsx)("label",{className:"text-sm font-medium text-foreground",htmlFor:"generic-mcp-client-id",children:"Client ID"}),(0,t.jsx)(dt,{id:"generic-mcp-client-id",value:u,onChange:r(O=>h(O.target.value),"onChange"),autoComplete:"off",placeholder:"Optional",className:"mt-2 h-11 font-mono"})]}),(0,t.jsxs)("div",{children:[(0,t.jsx)("label",{className:"text-sm font-medium text-foreground",htmlFor:"generic-mcp-client-secret",children:"Client secret"}),(0,t.jsx)(dt,{id:"generic-mcp-client-secret",type:"password",autoComplete:"off",value:p,onChange:r(O=>f(O.target.value),"onChange"),placeholder:"Optional",className:"mt-2 h-11 font-mono"})]})]}):null]})]})]}),N,(0,t.jsxs)("div",{className:"mt-8 flex items-center justify-between",children:[(0,t.jsx)($,{variant:"ghost",onClick:S,disabled:w,children:"Back"}),(0,t.jsxs)($,{onClick:C,disabled:w||!I||!!R,children:[w&&(0,t.jsx)(st,{className:"mr-2 h-4 w-4 animate-spin"}),w?"Checking…":"Check link"]})]})]})}r(Zmt,"LinkConnectStep");var jae=[{mode:"auto",label:"Let Paperclip check",hint:"Paperclip asks the server what it needs and walks you through it. Start here."},{mode:"none",label:"No sign-in needed",hint:"The server is open to anyone with the address."},{mode:"bearer",label:"Key or token",hint:"Paperclip sends your key as an Authorization header."},{mode:"custom_headers",label:"Custom headers",hint:"For servers that name their own headers. Values are stored as Paperclip secrets and can’t be read back."},{mode:"oauth",label:"Browser sign-in",hint:"You’ll sign in at the provider. Add a client ID and secret only if the provider requires you to register Paperclip first."}];function Jmt({label:e,selected:s,onClick:n}){return(0,t.jsx)("button",{type:"button",onClick:n,"aria-pressed":s,className:W("min-w-(--sz-64px) rounded-md px-4 py-1.5 text-sm font-medium transition-colors",s?"bg-background text-foreground shadow-sm":"text-muted-foreground hover:text-foreground"),children:e})}r(Jmt,"SegmentedOption");function Xmt({settingsValid:e=!0,entry:s,error:n,values:a,onChange:i,oauthClientId:o,onOAuthClientIdChange:l,oauthClientSecret:c,oauthCallbackUrl:d,canReuseOAuthClientSecret:u,onOAuthClientSecretChange:h,credentialSource:p,vercelConnector:f,onVercelConnectorChange:x,vercelConnectAvailability:g,methodKey:v,onMethodChange:y,configValues:k,onConfigChange:w,googleSheetsLinks:N,googleSheetsError:S,onGoogleSheetsLinksChange:C,submitting:_,renderDefaults:R,onBack:I,onConnect:T}){const E=(0,m.useMemo)(()=>D1(s,p),[p,s]),P=v?E.find(qe=>qe.key===v)??null:Rk(E),O=(0,m.useMemo)(()=>E.some(qe=>qe.capabilityProfile)?Array.from(E.reduce((qe,it)=>{const _t=it.capabilityProfile.key,$t=qe.get(_t);return $t?$t.methods.push(it):qe.set(_t,{key:_t,label:it.capabilityProfile?.label??it.label??it.key,description:it.capabilityProfile?.description??it.whenToUse,methods:[it]}),qe},new Map)).map(([,qe])=>qe):[],[E]),M=P?.capabilityProfile?.key??P?.key??"",Q=O.map(qe=>qe.key).join("|"),[L,F]=(0,m.useState)(M||Rk(E)?.capabilityProfile?.key||(O.length===1?O[0].key:""));(0,m.useEffect)(()=>{if(M){F(M);return}F(qe=>O.some(it=>it.key===qe)?qe:Rk(E)?.capabilityProfile?.key||(O.length===1?O[0].key:""))},[Q,O,E,M]);const q=O.length>1?O.find(qe=>qe.key===L)?.methods??[]:E,z=(P?.credentialFields??[]).map(qe=>({...qe,configPath:Yge(qe,P),helpUrl:P?.consoleLinks?.keys??P?.consoleLinks?.docs??""})),K=P?.credentialSources?.vercelConnect??null,U=p==="vercel_connect",V=U||z.every(qe=>qe.required===!1||(a[qe.configPath]?.trim().length??0)>0),ne=fk(P),Z=ne&&!T0(P),ie=U||!Z||o.trim().length>0&&(!P?.oauthClientSecretRequired||u||c.trim().length>0),J=!U||f.trim().length>0,ae=P?.auth==="oauth"&&ne?d:null,oe=[...P?.tenantFields??[],...P?.extensionFields??[]],G=oe.filter(qe=>!qe.hidden),X=G.filter(qe=>qe.advanced!==!0),Y=G.filter(qe=>qe.advanced===!0),re=oe.every(qe=>{if(!qe.required)return!0;const it=k[qe.key];return typeof it=="boolean"||typeof it=="string"&&it.trim().length>0}),se=P?.configRequirements?.atLeastOneOf??[],ce=se.length===0||se.some(qe=>{const it=k[qe];return typeof it=="string"&&it.trim().length>0}),pe=(O.length<=1||!!L)&&(q.length<=1?!!P:!!v),fe=s.availability?.robotEmail??null,ve=s.availability?.available===!1,Ie=!U&&ne&&!Z,de=O.length>1||q.length>1,xe=O.length>1?(0,t.jsxs)("div",{children:[(0,t.jsx)("label",{className:"text-sm font-medium text-foreground",children:"What should Paperclip be able to do?"}),(0,t.jsx)(am,{ariaLabel:`Access level for ${s.name}`,className:"mt-2",value:L,onValueChange:r(qe=>{const it=O.find(_t=>_t.key===qe);it&&(F(qe),y(RQ(it.methods)))},"onValueChange"),options:O.map(qe=>({value:qe.key,title:qe.label,description:qe.description}))}),!L&&(0,t.jsx)("p",{className:"mt-2 text-xs text-muted-foreground",children:"Choose an access level to continue."})]}):null,le=q.find(qe=>qe.oauthStrategy==="paperclip_cloud_connector"),Re=le&&q.find(qe=>fk(qe)&&!T0(qe)),Le=P?.key===Re?.key,je=(0,m.useId)(),_e=le&&Re&&q.length===2?(0,t.jsx)($,{type:"button",variant:"link",className:"h-auto p-0 text-xs text-muted-foreground underline underline-offset-2 hover:text-foreground","aria-expanded":Le,"aria-controls":je,disabled:_,onClick:r(()=>y(Le?le:Re),"onClick"),children:Le?"Use Paperclip instead":`Use your own ${A$e(le.connectorProfile??"")?"Google":s.name} OAuth app`}):q.length>1?(0,t.jsxs)("div",{children:[(0,t.jsx)("label",{className:"text-sm font-medium text-foreground",children:"How do you want to connect?"}),(0,t.jsx)(am,{ariaLabel:`How to connect ${s.name}`,className:"mt-2",value:v,onValueChange:r(qe=>{const it=q.find(_t=>_t.key===qe);it&&y(it)},"onValueChange"),options:q.map(qe=>({value:qe.key,title:qe.label??(qe.auth==="oauth"?`Sign in with ${s.name}`:"Use an API key")}))}),!P&&(0,t.jsx)("p",{className:"mt-2 text-xs text-muted-foreground",children:"Choose a connection method to continue."})]}):null,Ze=Y.length>0||Ie||de,ue=Le||!pe,Fe=Ze?(0,t.jsxs)("div",{className:"space-y-6",children:[xe,_e,Y.map(qe=>(0,t.jsx)(wae,{field:qe,value:k[qe.key],onChange:r(it=>w({...k,[qe.key]:it}),"onChange")},qe.key)),Ie?(0,t.jsx)(zz,{entry:s,method:P,callbackUrl:ae,clientId:o,onClientIdChange:l,clientSecret:c,onClientSecretChange:h,required:!1}):null]}):null,mt=R?.(Fe,ue)??null;if(CC(s,P)){const qe=zF(N),it=e&&!ve&&!!fe&&N.trim().length>0;return(0,t.jsxs)("div",{className:"mx-auto max-w-xl",children:[(0,t.jsxs)("div",{className:"space-y-6",children:[xe,fe?(0,t.jsxs)("div",{children:[(0,t.jsx)("label",{className:"text-sm font-medium text-foreground",children:"Share each sheet with this email"}),(0,t.jsxs)("div",{className:"mt-2 flex min-w-0 flex-col gap-2 sm:flex-row",children:[(0,t.jsx)("div",{title:fe,className:"min-h-11 min-w-0 flex-1 rounded-md border border-input bg-muted/40 px-3 py-2.5 font-mono text-xs leading-tight text-foreground break-all",children:fe}),(0,t.jsx)(u5e,{value:fe,ariaLabel:"Copy sharing email"})]}),(0,t.jsx)("p",{className:"mt-2 text-xs text-muted-foreground",children:"In Google Sheets, click Share and add this email as an Editor. Then paste the sheet links below."})]}):(0,t.jsx)("div",{className:"rounded-lg bg-muted/50 p-4 text-sm text-muted-foreground",children:"Google Sheets is not available on this instance yet."}),(0,t.jsxs)("div",{children:[(0,t.jsx)("label",{className:"text-sm font-medium text-foreground",children:"Paste links to the sheets you shared"}),(0,t.jsx)(Hn,{value:N,onChange:r(_t=>C(_t.target.value),"onChange"),placeholder:"https://docs.google.com/spreadsheets/d/...",className:"mt-2 min-h-28"}),(0,t.jsx)("div",{className:"mt-2 text-xs text-muted-foreground",children:qe.ids.length>0?`${qe.ids.length} ${qe.ids.length===1?"sheet":"sheets"} ready to connect.`:"Paste one link per line. Both .../edit and .../edit#gid=... links work."}),S&&(0,t.jsx)("div",{className:"mt-2 text-xs text-destructive",children:S})]})]}),mt,(0,t.jsxs)("div",{className:"mt-8 flex items-center justify-between",children:[(0,t.jsx)($,{variant:"ghost",onClick:I,disabled:_,children:"Back"}),(0,t.jsxs)($,{onClick:T,disabled:_||!it,children:[_&&(0,t.jsx)(st,{className:"mr-2 h-4 w-4 animate-spin"}),_?"Checking…":"Connect"]})]})]})}const bt=P?.connectorProfile==="asana.mcp",et=bt?null:P?.consoleLinks?.docs??s.docsUrl;return(0,t.jsxs)("div",{className:"mx-auto max-w-xl",children:[et?(0,t.jsx)("div",{className:"mb-4 flex justify-end",children:(0,t.jsxs)("a",{href:et,target:"_blank",rel:"noreferrer",className:"inline-flex items-center gap-1 text-xs font-medium text-muted-foreground underline underline-offset-2 hover:text-foreground",children:["Review requirements",(0,t.jsx)(oo,{className:"h-3 w-3"})]})}):null,(0,t.jsxs)("div",{className:"space-y-6",children:[bt?(0,t.jsx)("p",{className:"text-sm text-muted-foreground",children:"Sign in with Asana to choose your workspace and connect it to Paperclip."}):null,P?.capabilityProfile&&(0,t.jsxs)("p",{className:"text-sm text-muted-foreground",children:[P.capabilityProfile.label,": ",P.capabilityProfile.description]}),U&&K&&g?(0,t.jsxs)("div",{className:"space-y-4 rounded-lg border border-border p-4",children:[(0,t.jsxs)("div",{children:[(0,t.jsx)("div",{className:"text-sm font-medium text-foreground",children:"Create or attach the connector in Vercel"}),(0,t.jsx)("p",{className:"mt-1 text-xs text-muted-foreground",children:"Paperclip does not copy Vercel’s setup forms. Finish connector setup there, then paste its UID below."}),(0,t.jsxs)("a",{href:g.manageUrl,target:"_blank",rel:"noreferrer",className:"mt-2 inline-flex items-center gap-1 text-xs font-semibold text-foreground underline underline-offset-2",children:["Open Vercel Connect",(0,t.jsx)(oo,{className:"h-3 w-3"})]})]}),(0,t.jsxs)("div",{children:[(0,t.jsx)("label",{className:"text-sm font-medium text-foreground",htmlFor:"vercel-connect-connector",children:"Connector UID or ID"}),(0,t.jsx)(dt,{id:"vercel-connect-connector",value:f,onChange:r(qe=>x(qe.target.value),"onChange"),autoComplete:"off",placeholder:"service/my-connector or scl_…",className:"mt-2 h-11 font-mono"}),(0,t.jsx)("p",{className:"mt-2 text-xs text-muted-foreground",children:"Paperclip validates the connector and stores only its reference and redacted verification metadata."})]})]}):null,n?(0,t.jsx)("div",{role:"alert",children:(0,t.jsx)(ua,{tone:"danger",children:n})}):null,X.map(qe=>(0,t.jsx)(wae,{field:qe,value:k[qe.key],onChange:r(it=>w({...k,[qe.key]:it}),"onChange")},qe.key)),!U&&P?.auth==="oauth"&&Z?(0,t.jsx)("div",{id:je,role:"region","aria-label":"Your OAuth app",children:(0,t.jsx)(zz,{entry:s,method:P,callbackUrl:ae,clientId:o,onClientIdChange:l,clientSecret:c,onClientSecretChange:h,required:!0})}):null,U||!P||z.length===0?null:z.map(qe=>(0,t.jsxs)("div",{children:[(0,t.jsx)("label",{className:"text-sm font-medium text-foreground",children:aae(s.name,qe.label,z.length)}),(0,t.jsx)(dt,{type:qe.type==="text"&&qe.secret===!1?"text":"password","aria-label":aae(s.name,qe.label,z.length),autoComplete:"off",value:a[qe.configPath]??"",onChange:r(it=>i({...a,[qe.configPath]:it.target.value}),"onChange"),placeholder:qe.type==="text"&&qe.secret===!1?qe.placeholder:"••••••••••••••••",className:"mt-2 h-11 font-mono"}),qe.helperMd&&(0,t.jsx)("p",{className:"mt-2 text-xs text-muted-foreground",children:qe.helperMd}),qe.helpUrl&&(0,t.jsxs)("a",{href:qe.helpUrl,target:"_blank",rel:"noreferrer",className:"mt-2 inline-flex items-center gap-1 text-xs font-semibold text-foreground underline underline-offset-2",children:["Where do I find this?",(0,t.jsx)(oo,{className:"h-3 w-3"})]})]},qe.configPath))]}),mt,(0,t.jsxs)("div",{className:"mt-8 flex items-center justify-between",children:[(0,t.jsx)($,{variant:"ghost",onClick:I,disabled:_,children:"Back"}),(0,t.jsxs)($,{onClick:T,disabled:_||!e||!pe||!V||!ie||!J||!re||!ce,children:[_&&(0,t.jsx)(st,{className:"mr-2 h-4 w-4 animate-spin"}),_?"Checking…":U?P?.auth==="oauth"?"Validate and continue":"Validate and connect":P?.auth==="oauth"?s.slug==="github"?"Continue to GitHub":"Continue to sign in":"Connect"]})]})]})}r(Xmt,"KeyStep");function u5e({value:e,ariaLabel:s}){const{copied:n,failed:a,copy:i}=ep();return(0,t.jsxs)($,{type:"button",variant:"outline",className:"shrink-0","aria-label":s,onClick:r(()=>{i(e)},"onClick"),children:[n?(0,t.jsx)(ms,{className:"mr-2 h-4 w-4"}):(0,t.jsx)(br,{className:"mr-2 h-4 w-4"}),n?"Copied":a?"Copy failed":"Copy"]})}r(u5e,"CopyValueButton");function zz({entry:e,method:s,callbackUrl:n,clientId:a,onClientIdChange:i,clientSecret:o,onClientSecretChange:l,required:c}){return(0,t.jsxs)("div",{className:"space-y-4 rounded-lg border border-border p-4",children:[(0,t.jsxs)("div",{children:[(0,t.jsx)("div",{className:"text-sm font-medium text-foreground",children:c?s.oauthClientSecretRequired?"Your OAuth app":`${e.name} needs its own OAuth app`:"Use your own OAuth app"}),(0,t.jsx)("p",{className:"mt-1 text-xs text-muted-foreground",children:s.oauthClientSecretRequired?s.guidanceMd:c?`${e.name} does not let Paperclip register itself automatically, so this connector needs an OAuth app you create. Add the callback URL below in ${e.name}, then paste the client details back here.`:`Register Paperclip's callback URI in ${e.name}, then enter the customer-owned client details.`}),s.consoleLinks?.register?(0,t.jsxs)("a",{href:s.consoleLinks.register,target:"_blank",rel:"noreferrer",className:"mt-2 inline-flex items-center gap-1 text-xs font-semibold text-foreground underline underline-offset-2",children:["Open ",e.name," app settings",(0,t.jsx)(oo,{className:"h-3 w-3"})]}):null]}),n?(0,t.jsxs)("div",{children:[(0,t.jsx)("label",{className:"text-sm font-medium text-foreground",children:"Paperclip callback URL"}),(0,t.jsxs)("div",{className:"mt-2 flex min-w-0 flex-col gap-2 sm:flex-row",children:[(0,t.jsx)("div",{title:n,className:"min-h-11 min-w-0 flex-1 rounded-md border border-input bg-muted/40 px-3 py-2.5 font-mono text-xs leading-tight text-foreground break-all",children:n}),(0,t.jsx)(u5e,{value:n,ariaLabel:"Copy callback URL"})]}),(0,t.jsxs)("p",{className:"mt-2 text-xs text-muted-foreground",children:["Add this exact URL to ",e.name," before continuing. It must match the authorization request."]})]}):null,(0,t.jsxs)("div",{children:[(0,t.jsx)("label",{className:"text-sm font-medium text-foreground",htmlFor:"curated-oauth-client-id",children:"Client ID"}),(0,t.jsx)(dt,{id:"curated-oauth-client-id",value:a,onChange:r(d=>i(d.target.value),"onChange"),autoComplete:"off",placeholder:c?"Required":"Optional",className:"mt-2 h-11 font-mono"})]}),(0,t.jsxs)("div",{children:[(0,t.jsx)("label",{className:"text-sm font-medium text-foreground",htmlFor:"curated-oauth-client-secret",children:"Client secret"}),(0,t.jsx)(dt,{id:"curated-oauth-client-secret",type:"password",value:o,onChange:r(d=>l(d.target.value),"onChange"),autoComplete:"off",placeholder:s.oauthClientSecretRequired?"Required":"Optional for public clients",className:"mt-2 h-11 font-mono"})]})]})}r(zz,"OAuthClientFields");function wae({field:e,value:s,onChange:n}){return e.type==="checkbox"?(0,t.jsxs)("div",{className:"flex items-start justify-between gap-4 rounded-lg border border-border p-4",children:[(0,t.jsxs)("div",{children:[(0,t.jsx)("div",{className:"text-sm font-medium text-foreground",children:e.label}),e.helperMd&&(0,t.jsx)("div",{className:"mt-1 text-xs text-muted-foreground",children:e.helperMd})]}),(0,t.jsx)(ai,{checked:s===!0,onCheckedChange:n})]}):(0,t.jsxs)("div",{children:[(0,t.jsx)("label",{className:"text-sm font-medium text-foreground",children:e.label}),e.type==="textarea"?(0,t.jsx)(Hn,{value:typeof s=="string"?s:"",onChange:r(a=>n(a.target.value),"onChange"),placeholder:e.placeholder,className:"mt-2 min-h-24"}):e.type==="select"?(0,t.jsxs)("select",{value:typeof s=="string"?s:"",onChange:r(a=>n(a.target.value),"onChange"),className:"mt-2 h-11 w-full rounded-md border border-input bg-background px-3 text-sm text-foreground outline-none focus-visible:border-ring focus-visible:ring-3 focus-visible:ring-ring/30",children:[(0,t.jsx)("option",{value:"",disabled:!0,children:"Select an option"}),(e.options??[]).map(a=>(0,t.jsx)("option",{value:a.value,children:a.label},a.value))]}):(0,t.jsx)(dt,{value:typeof s=="string"?s:"",onChange:r(a=>n(a.target.value),"onChange"),placeholder:e.placeholder,"aria-label":e.label,maxLength:e.validation?.maxLength,className:"mt-2 h-11"}),e.required&&(typeof s!="string"||!s.trim())&&(0,t.jsxs)("p",{className:"mt-2 text-xs text-muted-foreground",children:[e.label," is required."]}),e.helperMd&&(0,t.jsx)("p",{className:"mt-2 text-xs text-muted-foreground",children:e.helperMd})]})}r(wae,"MethodConfigField");function eht({companyId:e,...s}){const n=te({queryKey:D.agents.list(e),queryFn:r(()=>Nt.list(e),"queryFn")});return(0,t.jsx)(AV,{...s,agents:(n.data??[]).filter(a=>a.status!=="terminated"),agentsLoading:n.isLoading})}r(eht,"AccessStep");function AV({agents:e,agentsLoading:s=!1,authKind:n,grantKinds:a,grantKind:i,setGrantKind:o,installChoice:l,setInstallChoice:c,installAgentIds:d,setInstallAgentIds:u,lockedAgentId:h,capabilities:p,githubIdentity:f=!1,submitLabel:x,continuesToProvider:g=!1,identityLoading:v=!1,preserveAgentAccess:y=!1,pending:k=!1,hideFooter:w=!1,bare:N=!1,onBack:S,onContinue:C}){const _=p?.editableAgentIds,R=_?e.filter(q=>_.includes(q.id)):e,I=p?.canSetCompanyInstall??!0,T=p?.canCreateOrganizationGrant??!0,E=n!=="none",P=a??["user","organization"],O=(!E||i==="user"||i==="agent"||T)&&(y?!0:h?d.has(h):i==="agent"?l==="specific"&&d.size===1:l==="all"?I:d.size>0),M=h?e.find(q=>q.id===h)?.name??"the requesting agent":null,Q=f?"Connect GitHub as":"Which humans can use this credential?",L=i==="agent"?"Which agent owns this GitHub account?":f&&i==="user"?"Which agents may use your GitHub when you’re responsible?":f?"Which agents may use the shared GitHub account?":"Which agents can use this connection?",F=f?L:"Which agents can use this connection?";return(0,t.jsxs)("div",{className:N?"":"mx-auto max-w-2xl",children:[(0,t.jsx)("div",{className:"overflow-hidden rounded-xl border border-border bg-background",children:(0,t.jsxs)("div",{className:"divide-y divide-border",children:[(0,t.jsxs)("section",{className:"p-6",children:[(0,t.jsx)("h2",{className:"text-sm font-semibold text-foreground",children:Q}),f&&i==="agent"?(0,t.jsx)("p",{className:"mt-2 text-sm text-muted-foreground",children:"This agent uses this GitHub account for everyone’s work, instead of the person giving instructions."}):null,v?(0,t.jsxs)("div",{className:"mt-4 grid gap-2 sm:grid-cols-2","aria-label":"Loading connection identity",children:[(0,t.jsx)(yn,{className:"h-20 w-full rounded-md"}),(0,t.jsx)(yn,{className:"h-20 w-full rounded-md"})]}):E&&P.length===1?(0,t.jsxs)("div",{className:"mt-4 flex items-center gap-3 rounded-md border border-border p-4",children:[P[0]==="user"?(0,t.jsx)(oh,{className:"h-4 w-4 shrink-0 text-muted-foreground","aria-hidden":"true"}):P[0]==="agent"?(0,t.jsx)(ao,{className:"h-4 w-4 shrink-0 text-muted-foreground","aria-hidden":"true"}):(0,t.jsx)(jk,{className:"h-4 w-4 shrink-0 text-muted-foreground","aria-hidden":"true"}),(0,t.jsxs)("div",{children:[(0,t.jsx)("div",{className:"text-sm font-medium text-foreground",children:P[0]==="user"?f?"My GitHub account":"Just me":P[0]==="agent"?"A dedicated account for an agent":f?"Shared organization GitHub account (advanced)":"Any human in the organization"}),f?(0,t.jsx)("p",{className:"mt-1 text-xs text-muted-foreground",children:P[0]==="user"?"Agents use it only for runs where you are the responsible person.":P[0]==="agent"?"That agent always uses this account, regardless of who starts the run.":"Eligible agents use one shared credential, regardless of who starts the run."}):null]})]}):E?(0,t.jsx)(am,{ariaLabel:f?Q:"Which humans can use this credential?",className:"mt-4 sm:grid-cols-2",value:i,onValueChange:r(q=>{const z=q;o(z),z==="agent"&&(c("specific"),d.size>1&&u(new Set([[...d][0]])))},"onValueChange"),options:[{value:"user",title:f?"My GitHub account":"Just me",description:f?"Agents use it only for runs where you are the responsible person.":void 0,icon:(0,t.jsx)(oh,{className:"h-4 w-4","aria-hidden":"true"})},{value:"agent",title:"A dedicated account for an agent",description:f?"That agent always uses this account, regardless of who starts the run.":void 0,icon:(0,t.jsx)(ao,{className:"h-4 w-4","aria-hidden":"true"})},{value:"organization",title:f?"Shared organization GitHub account (advanced)":"Any human in the organization",description:f?"Eligible agents use one shared credential, regardless of who starts the run.":void 0,icon:(0,t.jsx)(jk,{className:"h-4 w-4","aria-hidden":"true"}),accessibleLabel:T?f?"Shared organization GitHub account (advanced)":"Any human in the organization":`${f?"Shared organization GitHub account (advanced)":"Any human in the organization"}. Unavailable: ${p?.organizationGrantReason??"Only a connection manager can share this credential with the organization."}`,tooltip:T?void 0:p?.organizationGrantReason??"Only a connection manager can share this credential with the organization.",disabled:!T}].filter(q=>P.includes(q.value))}):(0,t.jsx)("p",{className:"mt-4 text-sm text-muted-foreground",children:"No identity required"})]}),(0,t.jsxs)("section",{className:"p-6",children:[(0,t.jsx)("h2",{className:"text-sm font-semibold text-foreground",children:L}),y?(0,t.jsxs)("div",{className:"mt-4 flex items-start gap-3 rounded-md border border-border bg-muted/40 p-4",children:[(0,t.jsx)(jk,{className:"mt-0.5 h-4 w-4 shrink-0 text-primary","aria-hidden":"true"}),(0,t.jsxs)("div",{children:[(0,t.jsx)("div",{className:"text-sm font-medium text-foreground",children:"Existing agent access stays the same"}),(0,t.jsx)("p",{className:"mt-1 text-xs text-muted-foreground",children:"Reconnecting replaces the credential without changing which agents can use it."})]})]}):h?(0,t.jsxs)("p",{className:"mt-2 text-sm text-muted-foreground",children:["This task grants access only to ",(0,t.jsx)("span",{className:"font-medium text-foreground",children:M}),". Existing connection access is left unchanged."]}):i==="agent"?(0,t.jsx)("p",{className:"mt-2 text-sm text-muted-foreground",children:"Choose exactly one agent. This identity cannot be shared with other agents."}):(0,t.jsx)(am,{ariaLabel:F,className:"mt-4 sm:grid-cols-2",value:l,onValueChange:r(q=>c(q),"onValueChange"),options:[{value:"specific",title:f?"Only agents I choose":"Just agents I pick",description:f?i==="user"?"Only selected agents may use your GitHub when you’re responsible.":"Only selected agents may use the shared account.":void 0,icon:(0,t.jsx)(ao,{className:"h-4 w-4","aria-hidden":"true"})},{value:"all",title:"Any agent",description:f?i==="user"?"Every agent may use your GitHub when you’re responsible.":"Every agent may use the shared account.":void 0,icon:(0,t.jsx)(tht,{}),accessibleLabel:I?"Any agent":`Any agent. Unavailable: ${p?.companyInstallReason??"Only someone who can configure this connection can choose this."}`,tooltip:I?void 0:p?.companyInstallReason??"Only someone who can configure this connection can choose this.",disabled:!I}]}),!y&&!h&&l==="specific"?(0,t.jsx)("div",{className:"mt-3",children:(0,t.jsx)(Qj,{agents:R,selectedAgentIds:d,onChange:r(q=>u(i==="agent"&&q.size>1?new Set([[...q].at(-1)]):q),"onChange"),loading:s,emptyMessage:"You cannot edit any agents yet.",showSelectionPreview:!1})}):null]})]})}),w?null:(0,t.jsxs)("div",{className:"mt-6 flex flex-col-reverse gap-2 sm:flex-row sm:items-center sm:justify-between",children:[(0,t.jsx)($,{variant:"ghost",className:"w-full sm:w-auto",onClick:S,disabled:k,children:"Back"}),(0,t.jsxs)($,{className:"w-full sm:w-auto",onClick:C,disabled:!O||v||k,children:[k?(0,t.jsx)(st,{className:"h-4 w-4 animate-spin","aria-hidden":"true"}):null,x,!k&&g?(0,t.jsx)(oo,{className:"h-4 w-4","aria-hidden":"true"}):null]})]})]})}r(AV,"AccessStepContent");function AE(e){return`${e.authKind==="none"?"No sign-in needed":e.grantKind==="user"?"Connects as you":e.grantKind==="agent"?"Connects as a dedicated agent account":"Connects for everyone in your organization"}, ${e.preserveAgentAccess?"agent access stays as it is":e.lockedAgentId?"available to the agent that asked for it":e.installChoice==="all"?"available to all agents":e.installCount===0?"no agents selected yet":`available to ${e.installCount} selected ${e.installCount===1?"agent":"agents"}`}.`}r(AE,"connectionDefaultSummarySentence");function IV({companyId:e,agents:s,sentence:n,notice:a,extra:i,forceOpen:o=!1,disabled:l=!1,...c}){const[d,u]=(0,m.useState)(!1);return(0,t.jsxs)(tl,{open:d||o,onOpenChange:u,className:"mt-6 rounded-lg border border-border bg-muted/30 px-4 py-3",children:[(0,t.jsxs)("div",{className:"flex flex-wrap items-baseline justify-between gap-x-3 gap-y-1",children:[(0,t.jsx)("p",{className:"text-sm text-muted-foreground",children:n}),(0,t.jsx)(Dl,{asChild:!0,children:(0,t.jsx)($,{type:"button",variant:"link",className:"h-auto p-0 text-xs font-semibold underline underline-offset-2",disabled:l,children:"Change"})})]}),(a??[]).map(h=>(0,t.jsx)("p",{className:"mt-2 text-xs text-muted-foreground",children:h},h)),(0,t.jsx)(sl,{children:(0,t.jsxs)("div",{className:"mt-3 space-y-6",children:[i,s?(0,t.jsx)(AV,{...c,agents:s,bare:!0,hideFooter:!0,submitLabel:"",onBack:r(()=>{},"onBack"),onContinue:r(()=>{},"onContinue")}):(0,t.jsx)(eht,{...c,companyId:e,bare:!0,hideFooter:!0,submitLabel:"",onBack:r(()=>{},"onBack"),onContinue:r(()=>{},"onContinue")})]})})]})}r(IV,"ConnectionAccessDefaults");function tht(){return(0,t.jsxs)("span",{className:"relative block h-4 w-5","aria-hidden":"true",children:[(0,t.jsx)(ao,{className:"absolute left-0 top-0 h-3.5 w-3.5"}),(0,t.jsx)(ao,{className:"absolute bottom-0 right-0 h-3.5 w-3.5"})]})}r(tht,"BotGroupIcon");function sht(e){const s=e.authKind==="none"?"No identity required":e.grantKind==="user"?"Your identity":e.grantKind==="agent"?"Dedicated agent identity":"Organization identity",n=e.installChoice==="all"?"Any agent":`${e.installCount} selected ${e.installCount===1?"agent":"agents"}`;return[{label:"Identity",value:s},{label:"Available to",value:n},{label:"Actions",value:`${e.enabledCount} ${e.enabledCount===1?"action":"actions"} on`}]}r(sht,"accessSummaryLines");function nht({appName:e,logoUrl:s,darkLogoUrl:n,summary:a,statedDefault:i,onDone:o}){return(0,t.jsxs)("div",{className:"mx-auto max-w-md py-10 text-center",children:[(0,t.jsx)("div",{className:"mx-auto flex h-20 w-20 items-center justify-center rounded-full border-2 border-emerald-500 bg-emerald-500/10",children:(0,t.jsx)(ms,{className:"h-9 w-9 text-emerald-600 dark:text-emerald-400"})}),(0,t.jsxs)("div",{className:"mt-6 flex items-center justify-center gap-2",children:[(0,t.jsx)(Hi,{name:e,logoUrl:s,darkLogoUrl:n,size:28}),(0,t.jsxs)("h2",{className:"text-2xl font-bold tracking-tight",children:[e," is ready."]})]}),i?(0,t.jsx)("p",{className:"mt-3 text-sm text-muted-foreground",children:i}):null,(0,t.jsx)("dl",{className:"mx-auto mt-6 max-w-xs space-y-1 text-left",children:a.map(l=>(0,t.jsxs)("div",{className:"flex items-baseline justify-between gap-4",children:[(0,t.jsx)("dt",{className:"text-xs font-medium text-muted-foreground",children:l.label}),(0,t.jsx)("dd",{className:"text-sm text-foreground",children:l.value})]},l.label))}),(0,t.jsx)("div",{className:"mt-8",children:(0,t.jsx)($,{size:"lg",className:"px-10",onClick:o,children:"View connection"})})]})}r(nht,"ConnectionSetupCompletionScreen");function m5e(){const{newProjectOpen:e,closeNewProject:s}=w3(),{selectedCompanyId:n}=fs();return n&&e?(0,t.jsx)(rht,{companyId:n,onClose:s},n):null}r(m5e,"NewProjectDialog");function rht({companyId:e,onClose:s}){const n=wt(),[a,i]=(0,m.useState)(""),[o]=(0,m.useState)(()=>hR[Math.floor(Math.random()*hR.length)]),[l,c]=(0,m.useState)([]),[d,u]=(0,m.useState)(!1),h=(0,m.useRef)(null),p=we({mutationFn:r(()=>aa.create(e,{name:a.trim(),color:o,status:"planned",repositoryIds:l.map(f=>f.id)}),"mutationFn"),onSuccess:r(f=>{Ob(f.id,e),n.invalidateQueries({queryKey:D.projects.all(e)}),s()},"onSuccess")});return(0,t.jsx)(Fs,{open:!0,onOpenChange:r(f=>{!f&&!p.isPending&&s()},"onOpenChange"),children:(0,t.jsx)(Qs,{showCloseButton:!1,"aria-describedby":void 0,className:"flex max-h-(--sz-calc-18) flex-col gap-0 overflow-hidden p-0 shadow-sm sm:max-w-lg",onOpenAutoFocus:r(f=>{f.preventDefault(),h.current?.focus()},"onOpenAutoFocus"),children:d?(0,t.jsxs)("div",{className:"min-h-0 overflow-y-auto p-5",children:[(0,t.jsx)(Ks,{className:"sr-only",children:"Connect GitHub"}),(0,t.jsx)(A2,{host:"dialog",serviceSlug:"github",forceNewConnection:!0,onCancel:r(()=>u(!1),"onCancel"),onComplete:r(()=>{n.invalidateQueries({queryKey:jH(e)}),u(!1)},"onComplete")})]}):(0,t.jsxs)("form",{className:"flex min-h-0 flex-col overflow-hidden",onSubmit:r(f=>{f.preventDefault(),a.trim()&&!p.isPending&&p.mutate()},"onSubmit"),children:[(0,t.jsxs)("div",{className:"flex shrink-0 flex-col gap-4 px-5 pb-4 pt-5",children:[(0,t.jsxs)("div",{className:"flex items-center justify-between gap-3",children:[(0,t.jsx)(Ks,{className:"text-lg font-semibold",children:"Create project"}),(0,t.jsx)($,{type:"button",variant:"ghost",size:"icon-sm",disabled:p.isPending,"aria-label":"Close new project",onClick:s,children:(0,t.jsx)(Mn,{className:"size-4"})})]}),(0,t.jsxs)("div",{className:"flex items-center gap-3 rounded-lg border border-input px-3 focus-within:border-ring focus-within:ring-1 focus-within:ring-ring",children:[(0,t.jsx)(nh,{color:o,size:"sm"}),(0,t.jsx)("input",{ref:h,"aria-label":"Project name",value:a,disabled:p.isPending,onChange:r(f=>i(f.target.value),"onChange"),placeholder:"Project name",required:!0,className:"h-10 w-full min-w-0 border-0 bg-transparent text-base outline-none placeholder:text-muted-foreground md:text-sm"})]})]}),(0,t.jsx)("div",{role:"region","aria-label":"Source repositories",tabIndex:0,className:"min-h-0 overflow-y-auto overscroll-contain px-5 pb-1 outline-none focus-visible:ring-1 focus-visible:ring-inset focus-visible:ring-ring",children:(0,t.jsx)(S2e,{companyId:e,selected:l,onChange:c,onConnect:r(()=>u(!0),"onConnect"),disabled:p.isPending})}),p.isError&&(0,t.jsx)("p",{role:"alert",className:"px-5 pt-3 text-sm text-destructive",children:p.error.message}),(0,t.jsxs)("div",{className:"flex shrink-0 justify-end gap-2 px-5 py-5",children:[(0,t.jsx)($,{type:"button",variant:"ghost",disabled:p.isPending,onClick:s,children:"Cancel"}),(0,t.jsx)($,{type:"submit",disabled:!a.trim()||p.isPending,children:p.isPending?"Creating…":"Create project"})]})]})})})}r(rht,"NewProjectForm");var Fx={list:r(e=>ke.get(`/companies/${e}/goals`),"list"),get:r(e=>ke.get(`/goals/${e}`),"get"),create:r((e,s)=>ke.post(`/companies/${e}/goals`,s),"create"),update:r((e,s)=>ke.patch(`/goals/${e}`,s),"update"),remove:r(e=>ke.delete(`/goals/${e}`),"remove")};function h5e(e){return{"--sc":`var(${e})`}}r(h5e,"scStyle");function aht(e){const s=e.replace(/_/g," ");return s.charAt(0).toUpperCase()+s.slice(1)}r(aht,"sentenceCaseStatus");function ii({status:e,label:s}){return(0,t.jsx)("span",{className:W("inline-flex items-center rounded-full px-2.5 py-0.5 text-xs font-medium whitespace-nowrap shrink-0",XB[e]??"bg-muted text-muted-foreground"),children:s??e.replace(/[_-]/g," ")})}r(ii,"StatusBadge$5");function p5e({status:e}){const s=uBe[e]??"--status-agent-idle",n=e==="active"?"idle":e;return(0,t.jsx)("span",{className:"status-chip inline-flex items-center rounded-full border px-3 py-1 text-xs font-medium leading-none whitespace-nowrap shrink-0",style:h5e(s),children:n.replace(/_/g," ")})}r(p5e,"AgentStatusBadge");function A0({status:e,externalConversationState:s}){const n=e==="in_review"&&s==="waiting"?"idle":e,a=LBe[n]??"--status-task-backlog";return(0,t.jsxs)("span",{className:W("status-chip inline-flex items-center gap-1.5 rounded-full border px-3 py-1 text-xs font-normal leading-none whitespace-nowrap shrink-0",n==="cancelled"&&"line-through"),style:h5e(a),children:[(0,t.jsx)(u3,{status:n,size:"sm"}),aht(n)]})}r(A0,"IssueStatusBadge");var kae={company:"Organization",team:"Team",agent:"Agent",task:"Task"};function f5e(){const{newGoalOpen:e,newGoalDefaults:s,closeNewGoal:n}=w3(),{selectedCompanyId:a,selectedCompany:i}=fs(),o=wt(),[l,c]=(0,m.useState)(""),[d,u]=(0,m.useState)(""),[h,p]=(0,m.useState)("planned"),[f,x]=(0,m.useState)("task"),[g,v]=(0,m.useState)(""),[y,k]=(0,m.useState)(!1),[w,N]=(0,m.useState)(!1),[S,C]=(0,m.useState)(!1),[_,R]=(0,m.useState)(!1),I=(0,m.useRef)(null),T=g||s.parentId||"",{data:E}=te({queryKey:D.goals.list(a),queryFn:r(()=>Fx.list(a),"queryFn"),enabled:!!a&&e}),P=we({mutationFn:r(q=>Fx.create(a,q),"mutationFn"),onSuccess:r(()=>{o.invalidateQueries({queryKey:D.goals.list(a)}),M(),n()},"onSuccess")}),O=we({mutationFn:r(async q=>{if(!a)throw new Error("No organization selected");return dv.uploadImage(a,q,"goals/drafts")},"mutationFn")});function M(){c(""),u(""),p("planned"),x("task"),v(""),k(!1)}r(M,"reset");function Q(){!a||!l.trim()||P.mutate({title:l.trim(),description:d.trim()||void 0,status:h,level:f,...T?{parentId:T}:{}})}r(Q,"handleSubmit");function L(q){q.key==="Enter"&&(q.metaKey||q.ctrlKey)&&(q.preventDefault(),Q())}r(L,"handleKeyDown");const F=(E??[]).find(q=>q.id===T);return(0,t.jsx)(Fs,{open:e,onOpenChange:r(q=>{q||(M(),n())},"onOpenChange"),children:(0,t.jsxs)(Qs,{showCloseButton:!1,className:W("p-0 gap-0",y?"sm:max-w-2xl":"sm:max-w-lg"),onKeyDown:L,children:[(0,t.jsxs)("div",{className:"flex items-center justify-between px-4 py-2.5 border-b border-border",children:[(0,t.jsxs)("div",{className:"flex items-center gap-2 text-sm text-muted-foreground",children:[i&&(0,t.jsx)("span",{className:"bg-muted px-1.5 py-0.5 rounded text-xs font-medium",children:i.issuePrefix}),(0,t.jsx)("span",{className:"text-muted-foreground/60",children:"›"}),(0,t.jsx)("span",{children:s.parentId?"New sub-goal":"New goal"})]}),(0,t.jsxs)("div",{className:"flex items-center gap-1",children:[(0,t.jsx)($,{variant:"ghost",size:"icon-xs",className:"text-muted-foreground",onClick:r(()=>k(!y),"onClick"),children:y?(0,t.jsx)(pwe,{className:"h-3.5 w-3.5"}):(0,t.jsx)(Vj,{className:"h-3.5 w-3.5"})}),(0,t.jsx)($,{variant:"ghost",size:"icon-xs",className:"text-muted-foreground",onClick:r(()=>{M(),n()},"onClick"),children:(0,t.jsx)("span",{className:"text-lg leading-none",children:"×"})})]})]}),(0,t.jsx)("div",{className:"px-4 pt-4 pb-2 shrink-0",children:(0,t.jsx)("input",{className:"w-full text-lg font-semibold bg-transparent outline-none placeholder:text-muted-foreground/50",placeholder:"Goal title",value:l,onChange:r(q=>c(q.target.value),"onChange"),onKeyDown:r(q=>{q.key==="Tab"&&!q.shiftKey&&(q.preventDefault(),I.current?.focus())},"onKeyDown"),autoFocus:!0})}),(0,t.jsx)("div",{className:"px-4 pb-2 overflow-y-auto max-h-(--sz-50vh)",children:(0,t.jsx)(Xc,{ref:I,value:d,onChange:u,placeholder:"Add description...",bordered:!1,contentClassName:W("text-sm text-muted-foreground",y?"min-h-(--sz-220px)":"min-h-(--sz-120px)"),imageUploadHandler:r(async q=>(await O.mutateAsync(q)).contentPath,"imageUploadHandler")})}),(0,t.jsxs)("div",{className:"flex items-center gap-1.5 px-4 py-2 border-t border-border flex-wrap",children:[(0,t.jsxs)(dr,{open:w,onOpenChange:N,children:[(0,t.jsx)(wr,{asChild:!0,children:(0,t.jsx)("button",{className:"inline-flex items-center gap-1.5 rounded-md border border-border px-2 py-1 text-xs hover:bg-accent/50 transition-colors",children:(0,t.jsx)(ii,{status:h})})}),(0,t.jsx)(nr,{className:"w-40 p-1",align:"start",children:bbe.map(q=>(0,t.jsx)("button",{className:W("flex items-center gap-2 w-full px-2 py-1.5 text-xs rounded hover:bg-accent/50 capitalize",q===h&&"bg-accent"),onClick:r(()=>{p(q),N(!1)},"onClick"),children:q},q))})]}),(0,t.jsxs)(dr,{open:S,onOpenChange:C,children:[(0,t.jsx)(wr,{asChild:!0,children:(0,t.jsxs)("button",{className:"inline-flex items-center gap-1.5 rounded-md border border-border px-2 py-1 text-xs hover:bg-accent/50 transition-colors",children:[(0,t.jsx)(Vl,{className:"h-3 w-3 text-muted-foreground"}),kae[f]??f]})}),(0,t.jsx)(nr,{className:"w-40 p-1",align:"start",children:nbe.map(q=>(0,t.jsx)("button",{className:W("flex items-center gap-2 w-full px-2 py-1.5 text-xs rounded hover:bg-accent/50",q===f&&"bg-accent"),onClick:r(()=>{x(q),C(!1)},"onClick"),children:kae[q]??q},q))})]}),(0,t.jsxs)(dr,{open:_,onOpenChange:R,children:[(0,t.jsx)(wr,{asChild:!0,children:(0,t.jsxs)("button",{className:"inline-flex items-center gap-1.5 rounded-md border border-border px-2 py-1 text-xs hover:bg-accent/50 transition-colors",children:[(0,t.jsx)(H0,{className:"h-3 w-3 text-muted-foreground"}),F?F.title:"Parent goal"]})}),(0,t.jsxs)(nr,{className:"w-48 p-1",align:"start",children:[(0,t.jsx)("button",{className:W("flex items-center gap-2 w-full px-2 py-1.5 text-xs rounded hover:bg-accent/50",!T&&"bg-accent"),onClick:r(()=>{v(""),R(!1)},"onClick"),children:"No parent"}),(E??[]).map(q=>(0,t.jsx)("button",{className:W("flex items-center gap-2 w-full px-2 py-1.5 text-xs rounded hover:bg-accent/50 truncate",q.id===T&&"bg-accent"),onClick:r(()=>{v(q.id),R(!1)},"onClick"),children:q.title},q.id))]})]})]}),(0,t.jsx)("div",{className:"flex items-center justify-end px-4 py-2.5 border-t border-border",children:(0,t.jsx)($,{size:"sm",disabled:!l.trim()||P.isPending,onClick:Q,children:P.isPending?"Creating…":s.parentId?"Create sub-goal":"Create goal"})})]})})}r(f5e,"NewGoalDialog");var uD=r((e,s)=>`/companies/${e}/agents/${s}/dot-binding`,"path"),LI={create:r(e=>ke.post(`/companies/${e}/dot-invitations`,{}),"create"),connection:r((e,s,n)=>ke.get(uD(e,s),{signal:n}),"connection"),pair:r((e,s,n)=>ke.post(uD(e,s),{replaceBindingId:n}),"pair"),retry:r((e,s,n)=>ke.post(uD(e,s)+"/event-test",{bindingId:n}),"retry")};function iht(e){const s=oht(e),n=lht(e);return`You're invited to join a Paperclip company as an agent.
330
+ `;function gdt(){const e=new Blob([xdt],{type:"application/javascript"}),s=URL.createObjectURL(e);try{return new Worker(s)}finally{URL.revokeObjectURL(s)}}r(gdt,"createSandboxedWorker");var Sz=new Map,NE=new Map,c6=new Set,d6=new Map,j_e=null;function bdt(e){j_e=e}r(bdt,"setDynamicParserResultNotifier");function w_e(e,s){e.worker.postMessage(s)}r(w_e,"sendToWorker");function vdt(e){return e.nextId++}r(vdt,"nextRequestId");function ydt(e,s){return`${s}\0${e}`}r(ydt,"lineCacheKey");function jdt(){j_e?.()}r(jdt,"notifyResultReady");function wdt(e,s,n){return new Promise(a=>{const i=vdt(e);e.pendingResolves.set(i,a),w_e(e,{type:"parse",id:i,line:s,ts:n})})}r(wdt,"parseLineAsync");function NC(e){for(const s of e.pendingResolves.values())s([]);e.pendingResolves.clear()}r(NC,"drainPendingRequests");function kdt(e){return new Promise((s,n)=>{const a=gdt(),i={worker:a,ready:!1,nextId:1,pendingResolves:new Map},o=setTimeout(()=>{NC(i),a.terminate(),n(new Error("Parser worker init timed out"))},5e3);a.onmessage=l=>{const c=l.data;if(c.type==="ready"){clearTimeout(o),i.ready=!0,a.onmessage=d=>{const u=d.data;if(u.type==="result"){const h=i.pendingResolves.get(u.id);h&&(i.pendingResolves.delete(u.id),h(u.entries))}else u.type==="error"&&NC(i)},s(i);return}if(c.type==="error"){clearTimeout(o),NC(i),a.terminate(),n(new Error(c.message));return}},a.onerror=l=>{clearTimeout(o),NC(i),a.terminate(),n(new Error(`Worker error: ${l.message}`))},w_e(i,{type:"init",source:e})})}r(kdt,"initSandboxedWorker");function Ndt(e){const s=new Map,n=new Set;return{parseStdoutLine:r((i,o)=>{const l=ydt(i,o),c=s.get(l);return c?c.slice():(n.has(l)||(n.add(l),wdt(e,i,o).then(d=>{n.delete(l),s.set(l,d),jdt()})),[])},"parseStdoutLine")}}r(Ndt,"buildParserModule");async function Cz(e){const s=NE.get(e);if(s)return s;if(c6.has(e))return null;const n=d6.get(e);if(n)return n;const a=(async()=>{try{const i=await fetch(`/api/adapters/${encodeURIComponent(e)}/ui-parser.js`);if(!i.ok)return c6.add(e),null;const o=await kdt(await i.text());Sz.set(e,o);const l=Ndt(o);return NE.set(e,l),l}catch{return c6.add(e),null}finally{d6.delete(e)}})();return d6.set(e,a),a}r(Cz,"loadDynamicParser");function _z(e){const s=NE.has(e);NE.delete(e),c6.delete(e),d6.delete(e);const n=Sz.get(e);return n&&(NC(n),n.worker.terminate(),Sz.delete(e)),s}r(_z,"invalidateDynamicParser");var u6=[],jM=new Map,Az=new Set,k_e=new Map,J9=new Set,AI=new Map,Iz=new Set;function N_e(e){return Iz.add(e),()=>Iz.delete(e)}r(N_e,"onAdapterChange");function S_e(){for(const e of Iz)e()}r(S_e,"notifyAdapterChange");bdt(S_e);function Sdt(){for(const e of[iot,wot,qot,Vot,glt,Tlt,qlt,Zlt,lct,bct,qct,Pct,olt,rdt,kE,fdt])Az.add(e.type),k_e.set(e.type,e),wy(e)}r(Sdt,"registerBuiltInUIAdapters");function wy(e){const s=u6.findIndex(n=>n.type===e.type);s>=0?u6.splice(s,1,e):u6.push(e),jM.set(e.type,e),S_e()}r(wy,"registerUIAdapter");function C_e(e){return jM.get(e)??null}r(C_e,"findUIAdapter");Sdt();function _2(e){const s=jM.get(e);if(!s){let n=!1;return{type:e,label:e,parseStdoutLine:r((a,i)=>(n||(n=!0,Cz(e).then(o=>{o&&wy({type:e,label:e,parseStdoutLine:o.parseStdoutLine,createStdoutParser:o.createStdoutParser,ConfigFields:jj,buildAdapterConfig:wj})})),kE.parseStdoutLine(a,i)),"parseStdoutLine"),ConfigFields:jj,buildAdapterConfig:wj}}return s}r(_2,"getUIAdapter");function Cdt(e){const s=new Set(e.filter(a=>!a.disabled&&!a.overrideDisabled).map(a=>a.type)),n=new Set(e.map(a=>a.type));for(const a of Az){const i=k_e.get(a);if(!i)continue;const o=n.has(a),l=s.has(a),c=J9.has(a);if(o&&l&&!c){J9.add(a);const d=(AI.get(a)??0)+1;AI.set(a,d);let u=!1;const h=i.parseStdoutLine,p=e.find(f=>f.type===a)?.label??a;wy({type:a,label:p,parseStdoutLine:r((f,x)=>(u||(u=!0,Cz(a).then(g=>{g&&AI.get(a)===d&&wy({type:a,label:p,parseStdoutLine:g.parseStdoutLine,createStdoutParser:g.createStdoutParser,ConfigFields:i.ConfigFields,buildAdapterConfig:i.buildAdapterConfig})})),h(f,x)),"parseStdoutLine"),ConfigFields:i.ConfigFields,buildAdapterConfig:i.buildAdapterConfig})}else(!o||!l)&&c&&(J9.delete(a),AI.delete(a),_z(a),wy(i))}for(const{type:a,label:i}of e){if(Az.has(a))continue;const o=jM.get(a);if(o&&o!==kE)continue;let l=!1;const c=o?.parseStdoutLine??kE.parseStdoutLine;wy({type:a,label:i,parseStdoutLine:r((d,u)=>(l||(l=!0,Cz(a).then(h=>{h&&wy({type:a,label:i,parseStdoutLine:h.parseStdoutLine,createStdoutParser:h.createStdoutParser,ConfigFields:o?.ConfigFields??jj,buildAdapterConfig:o?.buildAdapterConfig??wj})})),c(d,u)),"parseStdoutLine"),ConfigFields:o?.ConfigFields??jj,buildAdapterConfig:o?.buildAdapterConfig??wj})}}r(Cdt,"syncExternalAdapters");function gV(){return[...u6]}r(gV,"listUIAdapters");function Tz(e){if(typeof e=="function")return{parseLine:e,reset:null};if(e.createStdoutParser){const s=e.createStdoutParser();return{parseLine:s.parseLine,reset:s.reset}}return{parseLine:e.parseStdoutLine,reset:null}}r(Tz,"resolveStdoutParser");function __e(e,s){if((s.kind==="thinking"||s.kind==="assistant")&&s.delta){const n=e[e.length-1];if(n&&n.kind===s.kind&&n.delta&&n.channel===s.channel){n.text+=s.text,n.ts=s.ts;return}}e.push(s)}r(__e,"appendTranscriptEntry");function _dt(e,s){for(const n of s)__e(e,n)}r(_dt,"appendTranscriptEntries");function Adt(e,s=160){return e.length<=s?e:`${e.slice(0,s-3)}...`}r(Adt,"truncateTranscriptLine");function Idt(e){if(e instanceof Error&&e.message)return e.message;if(typeof e=="string"&&e)return e;try{return JSON.stringify(e)}catch{return String(e)}}r(Idt,"formatTranscriptParserError");function Tdt(e,s,n,a){const i=Idt(n)||"unknown parser error",o=Adt(e);return{kind:"result",ts:s,text:Um(`Chat transcript error: ${i}. Falling back for line: ${o}`,a),inputTokens:0,outputTokens:0,cachedTokens:0,costUsd:0,subtype:"transcript_parse_error",isError:!0,errors:[]}}r(Tdt,"createTranscriptParseErrorEntry");function bV(e){const{entries:s,line:n,ts:a,parseLine:i,reset:o,redactionOptions:l}=e;try{_dt(s,i(n,a).map(c=>wat(c,l)))}catch(c){o?.(),__e(s,Tdt(n,a,c,l))}}r(bV,"appendParsedTranscriptLine");function A_e(e){const{entries:s,chunks:n,from:a,parseLine:i,reset:o,redactionOptions:l}=e;let c=e.stdoutBuffer;for(let d=a;d<n.length;d+=1){const u=n[d];if(u.stream==="stderr"){s.push({kind:"stderr",ts:u.ts,text:Um(u.chunk,l)});continue}if(u.stream==="system"){s.push({kind:"system",ts:u.ts,text:Um(u.chunk,l)});continue}const h=(c+u.chunk).split(/\r?\n/);c=h.pop()??"";for(const p of h){const f=p.trim();f&&bV({entries:s,line:f,ts:u.ts,parseLine:i,reset:o,redactionOptions:l})}}return c}r(A_e,"foldTranscriptChunks");function I_e(e,s,n){const a=[],i={enabled:n?.censorUsernameInLogs??!1},{parseLine:o,reset:l}=Tz(s),c=A_e({entries:a,chunks:e,from:0,stdoutBuffer:"",parseLine:o,reset:l,redactionOptions:i}).trim();return c&&bV({entries:a,line:c,ts:e.length>0?e[e.length-1].ts:new Date().toISOString(),parseLine:o,reset:l,redactionOptions:i}),l?.(),a}r(I_e,"buildTranscript");var Bre=[];function Rdt(e,s){const n={enabled:s?.censorUsernameInLogs??!1},a=typeof e!="function"&&typeof e.createStdoutParser=="function";let i=Tz(e),o=[],l="",c=Bre,d=[];const u=r(()=>{i=Tz(e),o=[],l="",c=Bre},"restart"),h=r(f=>{if(f.length<c.length)return!1;for(let x=0;x<c.length;x+=1)if(f[x]!==c[x])return!1;return!0},"extendsFolded"),p=r(f=>{const x=l.trim();if(x&&a)return I_e(f,e,s);const g=o.slice(),v=g.length-1;return v>=0&&(g[v]={...g[v]}),x&&bV({entries:g,line:x,ts:f.length>0?f[f.length-1].ts:new Date().toISOString(),parseLine:i.parseLine,reset:i.reset,redactionOptions:n}),g},"publish");return{update(f){return f===c||(h(f)||u(),l=A_e({entries:o,chunks:f,from:c.length,stdoutBuffer:l,parseLine:i.parseLine,reset:i.reset,redactionOptions:n}),c=f,d=p(f)),d}}}r(Rdt,"createIncrementalTranscript");function Edt({agents:e,value:s,onChange:n,disabled:a=!1,excludeAgentIds:i=[],disabledEmptyLabel:o="Reports to: N/A (CEO)",chooseLabel:l="Reports to..."}){const[c,d]=(0,m.useState)(!1),u=new Set(i),h=e.filter(g=>g.status!=="terminated"&&!u.has(g.id)),p=s?e.find(g=>g.id===s):null,f=p?.status==="terminated",x=!!(s&&!p);return(0,t.jsxs)(dr,{open:c,onOpenChange:d,children:[(0,t.jsx)(wr,{asChild:!0,children:(0,t.jsx)("button",{type:"button",className:W("inline-flex max-w-full min-w-0 items-center gap-1.5 overflow-hidden rounded-md border border-border px-2 py-1 text-xs hover:bg-accent/50 transition-colors",f&&"border-amber-600/45 bg-amber-500/5",a&&"opacity-60 cursor-not-allowed"),disabled:a,children:x?(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)(gd,{className:"h-3 w-3 shrink-0 text-muted-foreground"}),(0,t.jsx)("span",{className:"min-w-0 truncate text-muted-foreground",children:"Unknown manager (stale ID)"})]}):p?(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)(lr,{agent:p,size:16,className:"h-3 w-3 shrink-0 text-muted-foreground"}),(0,t.jsx)("span",{className:W("min-w-0 truncate",f&&"text-amber-900 dark:text-amber-200"),children:`Reports to ${p.name}${f?" (terminated)":""}`})]}):(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)(gd,{className:"h-3 w-3 shrink-0 text-muted-foreground"}),(0,t.jsx)("span",{className:"min-w-0 truncate",children:a?o:l})]})})}),(0,t.jsxs)(nr,{className:"w-48 p-1",align:"start",children:[(0,t.jsx)("button",{type:"button",className:W("flex items-center gap-2 w-full px-2 py-1.5 text-xs rounded hover:bg-accent/50",s===null&&"bg-accent"),onClick:r(()=>{n(null),d(!1)},"onClick"),children:"No manager"}),f&&(0,t.jsxs)("div",{className:"flex min-w-0 items-center gap-2 overflow-hidden px-2 py-1.5 text-xs text-muted-foreground border-b border-border mb-0.5",children:[(0,t.jsx)(lr,{agent:p,size:16,className:"shrink-0 h-3 w-3"}),(0,t.jsxs)("span",{className:"min-w-0 truncate",children:["Current: ",p.name," (terminated)"]})]}),x&&(0,t.jsx)("div",{className:"px-2 py-1.5 text-xs text-muted-foreground border-b border-border mb-0.5",children:"Saved manager is missing from this organization. Choose a new manager or clear."}),h.map(g=>(0,t.jsxs)("button",{type:"button",className:W("flex items-center gap-2 w-full min-w-0 px-2 py-1.5 text-xs rounded hover:bg-accent/50 overflow-hidden",g.id===s&&"bg-accent"),onClick:r(()=>{n(g.id),d(!1)},"onClick"),children:[(0,t.jsx)(lr,{agent:g,size:16,className:"shrink-0 h-3 w-3 text-muted-foreground"}),(0,t.jsx)("span",{className:"min-w-0 truncate",children:g.name}),(0,t.jsx)("span",{className:"text-muted-foreground ml-auto shrink-0",children:GCe[g.role]??g.role})]},g.id))]})]})}r(Edt,"ReportsToPicker");var Ldt="__secret_folder__:";function Mdt(e){return!e||e==="active"?null:(0,t.jsx)(ot,{variant:"outline",className:"ml-auto text-(length:--text-nano) font-normal text-muted-foreground",children:e})}r(Mdt,"statusBadge");function T_e(e){return e.split("/").filter(s=>s.length>0)}r(T_e,"splitSecretPath$1");function m6(e){return e.join("/")}r(m6,"pathKey$1");function AS(e){return e.length>0?`/${e.join("/")}`:"/"}r(AS,"pathLabel");function Pdt(e,s){return e.length<s.length?!1:s.every((n,a)=>e[a]===n)}r(Pdt,"pathStartsWith");function Fre(e){return`${Ldt}${m6(e)}`}r(Fre,"folderValue");function Ddt(e,s,n){const a=s.length,i=new Map,o=[];for(const c of e){const d=T_e(c.name);if(Pdt(d,s)){if(d.length>a+1){const u=d.slice(0,a+1),h=m6(u);if(!i.has(h)){const p=u[u.length-1]??"/",f=AS(u);i.set(h,{key:`folder-${h||"root"}`,value:Fre(u),label:p,title:f,searchText:f,kind:"folder",folderPath:h,pathHint:f})}continue}if(d.length===a+1||a===0&&d.length===0){const u=d.at(-1)??c.name;o.push({key:`browse-${c.id}`,value:c.id,label:u,title:c.name,searchText:`${c.key} ${c.name}`,secret:c,status:c.status,kind:"secret",pathHint:c.name,disabled:c.status!=="active"&&c.id!==n})}}}const l=[];if(s.length>0){const c=s.slice(0,-1);l.push({key:`folder-up-${m6(s)}`,value:Fre(c),label:"Up one folder",title:AS(c),searchText:AS(c),kind:"back",folderPath:m6(c),pathHint:AS(c)})}return l.push(...i.values(),...o),{id:"browse-secrets",label:s.length>0?AS(s):"Browse secrets",options:l}}r(Ddt,"buildFolderGroup");function vV({secretId:e,secrets:s,recentlyUsedSecrets:n,disabled:a,onSelect:i,onCreateNew:o,triggerClassName:l,disablePortal:c}){const[d,u]=(0,m.useState)(""),h=(0,m.useMemo)(()=>s.find(y=>y.id===e)??null,[s,e]),p=!!e&&!h,f=(0,m.useMemo)(()=>d?d.split("/"):[],[d]),x=(0,m.useMemo)(()=>s.some(y=>T_e(y.name).length>1),[s]),g=(0,m.useMemo)(()=>{const y=[];p&&y.push({id:"current-missing",label:"Current",options:[{key:`missing-${e}`,value:e,label:`Missing secret (${e.slice(0,8)}…)`,title:`Missing secret (${e})`,missing:!0,disabled:!0}]});const k=(n??[]).filter(w=>w.status==="active"&&w.id!==e);return k.length>0&&y.push({id:"recently-used",label:"Recently used",options:k.map(w=>({key:`recent-${w.id}`,value:w.id,label:w.name,title:w.name,searchText:`${w.key} ${w.name}`,secret:w,status:w.status,kind:"secret"}))}),y.push({id:"all-secrets",label:k.length>0?"All secrets":void 0,options:s.map(w=>({key:`all-${w.id}`,value:w.id,label:w.name,title:w.name,searchText:`${w.key} ${w.name}`,secret:w,status:w.status,kind:"secret",disabled:w.status!=="active"&&w.id!==e}))}),y},[p,n,e,s]),v=(0,m.useCallback)((y,k)=>{if(!x||KBe(y))return k;const w=Ddt(s,f,e),N=k.filter(S=>S.id==="current-missing"||S.id==="recently-used");return w.options.length>0?[...N,w]:N},[f,x,e,s]);return(0,t.jsx)(lg,{value:e||"",groups:g,onValueChange:r((y,k)=>{if(k.folderPath!==void 0)return u(k.folderPath),!1;u(""),i(y)},"onValueChange"),deriveGroups:v,disabled:a,disablePortal:c,placeholder:"Select secret…",searchPlaceholder:"Search secrets…",emptyMessage:"No matching secrets",triggerClassName:W("h-(--sz-34px) min-h-(--sz-34px) font-mono text-sm",p&&"border-destructive text-destructive",h&&h.status!=="active"&&"border-amber-500/60",l),renderValue:r(y=>{if(!y)return(0,t.jsx)("span",{className:"text-muted-foreground",children:"Select secret…"});if(y.missing)return(0,t.jsxs)("span",{className:"flex w-full min-w-0 items-center gap-1.5 text-destructive",children:[(0,t.jsx)(Si,{className:"size-3.5 shrink-0"}),(0,t.jsx)("span",{className:"min-w-0 flex-1 truncate",children:y.label})]});const k=y.status&&y.status!=="active";return(0,t.jsxs)("span",{className:"flex w-full min-w-0 items-center gap-1.5",title:y.title,children:[(0,t.jsx)(Si,{className:W("size-3.5 shrink-0",k?"text-amber-600":"text-muted-foreground")}),(0,t.jsx)("span",{className:"min-w-0 flex-1 truncate",children:y.label}),k?(0,t.jsxs)("span",{className:"text-amber-600",children:["(",y.status,")"]}):null]})},"renderValue"),renderOption:r((y,{selected:k})=>{if(y.kind==="folder"||y.kind==="back"){const w=y.kind==="back"?dKe:Ql;return(0,t.jsxs)("span",{className:"flex min-w-0 flex-1 items-center gap-1.5",title:y.title??y.label,children:[(0,t.jsx)(w,{className:"size-3.5 shrink-0 text-muted-foreground"}),(0,t.jsxs)("span",{className:"flex min-w-0 flex-col",children:[(0,t.jsx)("span",{className:W("truncate text-sm",k&&"font-medium"),children:y.label}),y.pathHint?(0,t.jsx)("span",{className:"truncate font-mono text-(length:--text-micro) text-muted-foreground",children:y.pathHint}):null]})]})}return(0,t.jsxs)("span",{className:W("flex min-w-0 flex-1 items-center gap-1.5",y.disabled&&"opacity-60"),title:y.title??y.label,children:[(0,t.jsx)(Si,{className:"size-3.5 shrink-0 text-muted-foreground"}),(0,t.jsxs)("span",{className:"flex min-w-0 flex-col",children:[(0,t.jsx)("span",{className:W("min-w-0 truncate font-mono text-sm",k&&"font-medium"),children:y.label}),y.pathHint&&y.pathHint!==y.label?(0,t.jsx)("span",{className:"truncate font-mono text-(length:--text-micro) text-muted-foreground",children:y.pathHint}):null]}),Mdt(y.status)]})},"renderOption"),createItem:o?{render:r(y=>(0,t.jsxs)("span",{className:"flex items-center gap-1.5 text-sm",children:[(0,t.jsx)(bn,{className:"size-3.5 shrink-0"}),y.trim()?(0,t.jsxs)("span",{children:["Create secret ",(0,t.jsxs)("span",{className:"font-mono",children:["“",y.trim(),"”"]}),"…"]}):(0,t.jsx)("span",{children:"Create new secret…"})]}),"render"),onSelect:r(y=>o(y),"onSelect")}:void 0})}r(vV,"SecretPicker");var $dt=/^[a-z][a-z0-9_]*$/,zre="w-full rounded-md border border-border px-2.5 py-1.5 bg-transparent outline-none text-sm font-mono placeholder:text-muted-foreground/40 focus-visible:ring-2 focus-visible:ring-ring/40";function R_e({mode:e,initialName:s,initialValue:n,existingSecretNames:a,onCancel:i,onSubmit:o}){const[l,c]=(0,m.useState)(s),[d,u]=(0,m.useState)(n),[h,p]=(0,m.useState)(!1),[f,x]=(0,m.useState)(!1),[g,v]=(0,m.useState)(null),[y,k]=(0,m.useState)(!1),w=l.trim(),N=w?$dt.test(w)?a?.some(I=>I.toLowerCase()===w)?"A secret with this name already exists":null:"Use lowercase letters, digits and _":y?"Name is required":null,S=d.length===0&&y?"Value is required":null,C=!f&&w.length>0&&d.length>0&&!N;async function _(){if(k(!0),!!C){x(!0),v(null);try{await o(w,d)}catch(I){v(I instanceof Error?I.message:"Failed to create secret"),x(!1)}}}r(_,"handleSubmit");const R=e==="create"?"Create & bind":"Store & bind";return(0,t.jsxs)("div",{className:"w-72 space-y-3",children:[(0,t.jsxs)("div",{className:"space-y-1",children:[(0,t.jsx)(bBe,{className:"text-sm font-medium",children:e==="create"?"Create secret":"Store value as secret"}),e==="store"?(0,t.jsxs)(oBe,{className:"text-(length:--text-micro) text-muted-foreground",children:["Moves the typed value into an encrypted organization secret and binds"," ",(0,t.jsx)("span",{className:"font-mono",children:s||"this variable"})," to it."]}):null]}),(0,t.jsxs)("label",{className:"block space-y-1",children:[(0,t.jsx)("span",{className:"text-(length:--text-micro) font-medium text-muted-foreground",children:"Name"}),(0,t.jsx)("input",{className:W(zre,N&&"border-destructive focus-visible:ring-destructive/40"),value:l,autoFocus:!0,spellCheck:!1,placeholder:"secret_name","aria-label":"Secret name","aria-invalid":N?!0:void 0,onChange:r(I=>c(I.target.value),"onChange"),onBlur:r(()=>k(!0),"onBlur"),onKeyDown:r(I=>{I.key==="Enter"&&(I.preventDefault(),_())},"onKeyDown")}),N?(0,t.jsx)("span",{className:"block text-(length:--text-micro) text-destructive",children:N}):null]}),(0,t.jsxs)("label",{className:"block space-y-1",children:[(0,t.jsx)("span",{className:"text-(length:--text-micro) font-medium text-muted-foreground",children:"Value"}),(0,t.jsxs)("div",{className:"relative",children:[(0,t.jsx)("input",{className:W(zre,"pr-8",S&&"border-destructive focus-visible:ring-destructive/40"),type:h?"text":"password",value:d,readOnly:e==="store",spellCheck:!1,placeholder:e==="create"?"value":void 0,"aria-label":"Secret value","aria-invalid":S?!0:void 0,onChange:e==="create"?I=>u(I.target.value):void 0}),(0,t.jsx)("button",{type:"button",className:"absolute right-1.5 top-1/2 -translate-y-1/2 rounded p-1 text-muted-foreground hover:text-foreground","aria-label":h?"Hide value":"Show value",onClick:r(()=>p(I=>!I),"onClick"),children:h?(0,t.jsx)(ih,{className:"h-3.5 w-3.5"}):(0,t.jsx)(eu,{className:"h-3.5 w-3.5"})})]}),S?(0,t.jsx)("span",{className:"block text-(length:--text-micro) text-destructive",children:S}):null]}),g?(0,t.jsx)("p",{className:"text-(length:--text-micro) text-destructive",children:g}):null,(0,t.jsxs)("div",{className:"flex items-center justify-end gap-2 pt-0.5",children:[(0,t.jsx)($,{type:"button",variant:"ghost",size:"sm",onClick:i,disabled:f,children:"Cancel"}),(0,t.jsxs)($,{type:"button",size:"sm",onClick:r(()=>{_()},"onClick"),disabled:!C,children:[f?(0,t.jsx)(st,{className:"h-3.5 w-3.5 animate-spin"}):null,R]})]})]})}r(R_e,"SecretPopoverForm");function E_e(e){return(0,t.jsx)(R_e,{mode:"create",...e})}r(E_e,"CreateSecretPopover");function Odt(e){return(0,t.jsx)(R_e,{mode:"store",...e})}r(Odt,"ConvertToSecretPopover");var Bdt=/(api[-_]?key|access[-_]?token|auth(?:_?token)?|authorization|bearer|secret|passwd|password|credential|jwt|private[-_]?key|cookie|connectionstring)/i,Fdt=[/^sk-[A-Za-z0-9-_]{16,}$/,/^gh[pousr]_[A-Za-z0-9]{20,}$/,/^github_pat_[A-Za-z0-9_]{20,}$/,/^xox[baprs]-[A-Za-z0-9-]{10,}$/,/^AKIA[0-9A-Z]{16}$/,/^AIza[0-9A-Za-z\-_]{20,}$/,/-----BEGIN (?:[A-Z ]+ )?PRIVATE KEY-----/,/^eyJ[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+$/];function zdt(e){return e.length<24||/\s/.test(e)||!/^[A-Za-z0-9+/=_\-.]+$/.test(e)?!1:[/[a-z]/.test(e),/[A-Z]/.test(e),/[0-9]/.test(e)].filter(Boolean).length>=2}r(zdt,"looksHighEntropy");function qdt(e,s){return s?Bdt.test(e)||Fdt.some(n=>n.test(s))?!0:zdt(s):!1}r(qdt,"isSensitiveEnv");var qre=0;function Udt(){return qre+=1,`env-row-${qre}`}r(Udt,"nextRowId");function jx(e="text"){return{id:Udt(),name:"",source:e,textValue:"",secretId:"",userSecretKey:"",required:!0,version:"latest"}}r(jx,"emptyRow");function Kdt(e){return typeof e=="object"&&e!==null&&"type"in e&&e.type==="secret_ref"}r(Kdt,"isSecretRef");function Qdt(e){return typeof e=="object"&&e!==null&&"type"in e&&e.type==="plain"}r(Qdt,"isPlainObj");function Wdt(e){return typeof e=="object"&&e!==null&&"type"in e&&e.type==="user_secret_ref"}r(Wdt,"isUserSecretRef");function X9(e){return!e||typeof e!="object"?[]:Object.entries(e).map(([s,n])=>{if(typeof n=="string")return{...jx(),name:s,textValue:n};if(Kdt(n)){const a=typeof n.version=="number"?n.version:"latest";return{...jx(),name:s,source:"secret",secretId:typeof n.secretId=="string"?n.secretId:"",version:a}}if(Wdt(n)){const a=typeof n.version=="number"?n.version:"latest";return{...jx(),name:s,source:"user_secret",userSecretKey:typeof n.key=="string"?n.key:"",required:n.required!==!1,version:a}}return Qdt(n)?{...jx(),name:s,source:"text",textValue:typeof n.value=="string"?n.value:""}:{...jx(),name:s}})}r(X9,"rowsFromValue");function h6(e){const s={};for(const n of e){const a=n.name.trim();if(a)if(n.source==="secret"){if(!n.secretId)continue;s[a]={type:"secret_ref",secretId:n.secretId,version:n.version}}else if(n.source==="user_secret"){const i=n.userSecretKey.trim();if(!i)continue;s[a]={type:"user_secret_ref",key:i,version:n.version,required:n.required}}else s[a]={type:"plain",value:n.textValue}}return Object.keys(s).length>0?s:void 0}r(h6,"valueFromRows");var Ure="CLAUDE_CODE_OAUTH_TOKEN";function tk(){return h6([{...jx("user_secret"),name:"CLAUDE_CODE_OAUTH_TOKEN",userSecretKey:"CLAUDE_CODE_OAUTH_TOKEN",required:!0,version:"latest"}])??{}}r(tk,"buildFixedClaudeOAuthBinding");var Hdt=/^[A-Za-z_][A-Za-z0-9_]*$/;function Vdt(e,s,n){const a=e.trim();if(!a)return null;if(!Hdt.test(a))return{level:"error",message:"Invalid name — use letters, digits and _"};if(s.has(a))return{level:"error",message:"Duplicate name"};for(const i of n)if(i&&a.startsWith(i))return{level:"warn",message:"Reserved prefix — provided automatically and may be overridden"};return null}r(Vdt,"validateName");function Gdt(e){const s=new Map;for(const a of e){const i=a.name.trim();i&&s.set(i,(s.get(i)??0)+1)}const n=new Set;for(const[a,i]of s)i>1&&n.add(a);return n}r(Gdt,"computeDuplicateNames");function Ydt(e,s){return s===e.source?{kind:"noop"}:s==="secret"?e.textValue.trim()?{kind:"open-store",name:SE(e.name)||"secret",value:e.textValue}:{kind:"to-secret"}:{kind:"to-text",undoFrom:e.secretId?{...e}:null}}r(Ydt,"planSourceSwitch");function L_e(e,s){if(e.source!=="secret"||!e.secretId)return null;const n=s.find(a=>a.id===e.secretId);return n?n.status!=="active"?{level:"warn",kind:"disabled",message:"Runs will fail until re-enabled or rebound."}:null:{level:"error",kind:"missing",message:"This secret no longer exists — runs will fail until you rebind."}}r(L_e,"computeRowHealth");function M_e(e,s){if(e.source!=="user_secret"||!e.userSecretKey||!s?.length)return null;const n=s.find(a=>a.key===e.userSecretKey);return n?n.status!=="active"?{level:"warn",kind:"disabled",message:"Runs will fail until this user secret definition is re-enabled or rebound."}:null:{level:"error",kind:"missing",message:"This user secret definition no longer exists — runs will fail until you rebind."}}r(M_e,"computeUserSecretRowHealth");function SE(e){return e.trim().toLowerCase().replace(/[^a-z0-9_]+/g,"_").replace(/^_+|_+$/g,"").slice(0,64)}r(SE,"secretNameFromKey");function c_(e){return e.trim().toUpperCase().replace(/[^A-Z0-9_]+/g,"_").replace(/^_+|_+$/g,"").slice(0,64)}r(c_,"envKeyFromSecretName");var Zdt="w-full rounded-md border border-border px-2.5 py-1.5 bg-transparent outline-none text-sm font-mono placeholder:text-muted-foreground/40 focus-visible:ring-2 focus-visible:ring-ring/40",Kre="min-w-0 flex-1 bg-transparent px-2 py-1.5 text-sm font-mono outline-none placeholder:text-muted-foreground/40";function Jdt({row:e,isLast:s,secrets:n,userSecretDefinitions:a,recentlyUsedSecrets:i,disabled:o,nameIssue:l,showNameIssue:c,dirtyFields:d,onPatch:u,onRemove:h,onNameBlur:p,onNamePaste:f,onEnterInValueLast:x,onCreateSecret:g,onToast:v,focusRequest:y,onFocusConsumed:k}){const w=(0,m.useRef)(null),N=(0,m.useRef)(null),S=(0,m.useRef)(null),[C,_]=(0,m.useState)(null),[R,I]=(0,m.useState)(!1),[T,E]=(0,m.useState)(null),P=L_e(e,n)??M_e(e,a),O=e.source==="secret"?n.find(J=>J.id===e.secretId)??null:null,M=(a?.length??0)>0,Q=e.source==="text"&&!e.sensitiveDismissed&&qdt(e.name,e.textValue);(0,m.useEffect)(()=>{y&&(y==="name"?w.current?.focus():e.source==="text"?N.current?.focus():e.source==="secret"?S.current?.querySelector("[role=combobox]")?.focus():S.current?.querySelector("select,input")?.focus(),k())},[y,k,e.source]),(0,m.useEffect)(()=>{if(!T)return;const J=window.setTimeout(()=>E(null),5e3);return()=>window.clearTimeout(J)},[T]);function L(J){if(J==="user_secret"){if(e.source==="user_secret")return;u({source:"user_secret",secretId:"",version:"latest"}),window.setTimeout(()=>S.current?.querySelector("select,input")?.focus(),0);return}const ae=Ydt(e,J);switch(ae.kind){case"noop":return;case"open-store":{const{name:oe,value:G}=ae;window.setTimeout(()=>_({mode:"store",name:oe,value:G}),0);return}case"to-secret":u({source:"secret",userSecretKey:"",required:!0}),window.setTimeout(()=>{S.current?.querySelector("[role=combobox]")?.focus()},0);return;case"to-text":ae.undoFrom&&E(ae.undoFrom),u({source:"text",secretId:"",userSecretKey:"",required:!0,version:"latest"}),window.setTimeout(()=>N.current?.focus(),0);return}}r(L,"switchSource");async function F(J,ae){const oe=await g(J,ae);u({source:"secret",secretId:oe.id,userSecretKey:"",required:!0,version:"latest",textValue:""}),v(`Secret ${oe.name} created`),_(null)}r(F,"submitSecretPopover");function q(){const J=SE(e.name)||"secret",{textValue:ae}=e;window.setTimeout(()=>_({mode:"store",name:J,value:ae}),0)}r(q,"openStoreAsSecret");const z=e.source==="text"?"Text value":e.source==="secret"?"Organization secret reference":"User secret reference",K=`${e.id}-name-error`,U=`${e.id}-health`,V=d.name||d.value,ne=O?Math.max(0,O.latestVersion):0,Z=e.version==="latest"?"latest":`v${e.version}`,ie=e.version!=="latest";return(0,t.jsxs)("div",{className:W("group/row grid grid-cols-(--gtc-13) items-start gap-x-1.5 gap-y-1 rounded-md px-1 py-1","@[40rem]/env:grid-cols-(--gtc-14) @[40rem]/env:items-center",V&&"bg-amber-500/[0.06] ring-1 ring-amber-500/20"),children:[(0,t.jsx)("div",{className:"col-start-1 row-start-1 min-w-0 @[40rem]/env:row-start-1 @[40rem]/env:self-start",children:(0,t.jsx)("input",{ref:w,className:W(Zdt,d.name&&"border-amber-500/70 bg-amber-500/10 focus-visible:ring-amber-500/40",c&&l?.level==="error"&&"border-destructive focus-visible:ring-destructive/40",c&&l?.level==="warn"&&"border-amber-500 focus-visible:ring-amber-500/40"),placeholder:"KEY",value:e.name,spellCheck:!1,disabled:o,"aria-label":"Variable name","aria-invalid":c&&l?.level==="error"?!0:void 0,"aria-describedby":c&&l?K:void 0,onChange:r(J=>u({name:J.target.value}),"onChange"),onBlur:p,onPaste:r(J=>{e.name||f(J.clipboardData.getData("text"))&&J.preventDefault()},"onPaste"),onKeyDown:r(J=>{J.key==="Enter"&&(J.preventDefault(),e.source==="text"?N.current?.focus():S.current?.querySelector("[role=combobox],select,input")?.focus())},"onKeyDown")})}),(0,t.jsxs)("div",{className:"col-span-2 col-start-1 row-start-2 min-w-0 @[40rem]/env:col-span-1 @[40rem]/env:col-start-2 @[40rem]/env:row-start-1",children:[(0,t.jsxs)(dr,{open:C!==null,onOpenChange:r(J=>{J||_(null)},"onOpenChange"),children:[(0,t.jsx)(ZB,{asChild:!0,children:(0,t.jsxs)("div",{ref:S,className:W("relative flex items-stretch overflow-hidden rounded-md border border-border bg-transparent focus-within:ring-2 focus-within:ring-ring/40",d.value&&"border-amber-500/70 bg-amber-500/10 focus-within:ring-amber-500/40",o&&"opacity-60"),children:[(0,t.jsxs)(na,{children:[(0,t.jsxs)(Fn,{children:[(0,t.jsx)(Bn,{asChild:!0,children:(0,t.jsx)(ta,{asChild:!0,disabled:o,children:(0,t.jsxs)("button",{type:"button","aria-label":"Value source",className:"flex shrink-0 items-center gap-0.5 border-r border-border px-2 text-muted-foreground hover:bg-accent/50 disabled:pointer-events-none",children:[e.source==="text"?(0,t.jsx)(VKe,{className:"size-3.5"}):e.source==="secret"?(0,t.jsx)(Si,{className:"size-3.5"}):(0,t.jsx)(oh,{className:"size-3.5"}),(0,t.jsx)(an,{className:"size-3 opacity-60"})]})})}),(0,t.jsx)(On,{side:"top",children:z})]}),(0,t.jsxs)(sa,{align:"start",className:"w-56",children:[(0,t.jsxs)(us,{className:"flex-col items-start gap-0.5",onSelect:r(()=>L("text"),"onSelect"),children:[(0,t.jsx)("span",{className:"text-sm",children:"Text value"}),(0,t.jsx)("span",{className:"text-(length:--text-micro) text-muted-foreground",children:"Store the value inline as plain text."})]}),(0,t.jsxs)(us,{className:"flex-col items-start gap-0.5",onSelect:r(()=>L("secret"),"onSelect"),children:[(0,t.jsx)("span",{className:"text-sm",children:"Organization secret"}),(0,t.jsx)("span",{className:"text-(length:--text-micro) text-muted-foreground",children:"Resolve a stored organization secret at run start."})]}),(0,t.jsxs)(us,{className:"flex-col items-start gap-0.5",onSelect:r(()=>L("user_secret"),"onSelect"),children:[(0,t.jsx)("span",{className:"text-sm",children:"User secret"}),(0,t.jsx)("span",{className:"text-(length:--text-micro) text-muted-foreground",children:"Resolve the responsible user's own value at run start."})]})]})]}),e.source==="text"?(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)("input",{ref:N,className:Kre,placeholder:"value",value:e.textValue,type:Q?"password":"text",spellCheck:!1,disabled:o,"aria-label":"Variable value",onChange:r(J=>u({textValue:J.target.value}),"onChange"),onKeyDown:r(J=>{J.key==="Enter"&&s&&(J.preventDefault(),x())},"onKeyDown")}),Q?(0,t.jsxs)("div",{className:"flex shrink-0 items-stretch border-l border-border",children:[(0,t.jsxs)("button",{type:"button",onClick:q,disabled:o,className:"flex items-center gap-1 px-2 text-(length:--text-micro) text-amber-700 hover:bg-amber-500/10 dark:text-amber-400",title:"This value looks sensitive — store it as a secret",children:[(0,t.jsx)(Tc,{className:"size-3.5"}),(0,t.jsx)("span",{className:"hidden @[30rem]/env:inline",children:"Store as secret"})]}),(0,t.jsx)("button",{type:"button",onClick:r(()=>u({sensitiveDismissed:!0}),"onClick"),disabled:o,"aria-label":"Dismiss sensitive-value suggestion",title:"Dismiss — keep this value as plain text",className:"flex items-center px-1.5 text-amber-700/60 hover:bg-amber-500/10 hover:text-amber-700 dark:text-amber-400/60 dark:hover:text-amber-400",children:(0,t.jsx)(Mn,{className:"size-3"})})]}):null]}):e.source==="secret"?(0,t.jsxs)("div",{className:"relative min-w-0 flex-1",children:[(0,t.jsx)(vV,{secretId:e.secretId,secrets:n,recentlyUsedSecrets:i,disabled:o,onSelect:r(J=>u({secretId:J,version:"latest"}),"onSelect"),onCreateNew:r(J=>_({mode:"create",name:SE(J)||J.trim(),value:""}),"onCreateNew"),triggerClassName:W("rounded-none border-0 bg-transparent shadow-none focus-visible:ring-0",O&&O.status==="active"&&"pr-24 has-[>svg]:!pr-24")}),O&&O.status==="active"?(0,t.jsxs)(dr,{open:R,onOpenChange:I,children:[(0,t.jsx)(ZB,{asChild:!0,children:(0,t.jsx)("button",{type:"button",disabled:o,onClick:r(J=>{J.preventDefault(),J.stopPropagation(),I(ae=>!ae)},"onClick"),"aria-label":"Version",className:W("absolute right-8 top-1/2 z-10 -translate-y-1/2 rounded px-1.5 py-0.5 text-(length:--text-nano) font-medium",ie?"bg-amber-500/15 text-amber-700 dark:text-amber-400":"text-muted-foreground hover:bg-accent"),children:Z})}),(0,t.jsxs)(nr,{align:"end",className:"w-44 p-1",role:"radiogroup","aria-label":"Secret version",children:[(0,t.jsxs)("button",{type:"button",role:"radio","aria-checked":e.version==="latest",onClick:r(()=>{u({version:"latest"}),I(!1)},"onClick"),className:W("flex w-full items-center justify-between rounded px-2 py-1.5 text-sm hover:bg-accent",e.version==="latest"&&"font-medium"),children:["latest ",(0,t.jsx)("span",{className:"text-(length:--text-micro) text-muted-foreground",children:"(recommended)"})]}),Array.from({length:ne},(J,ae)=>ne-ae).filter(J=>J>0).map(J=>(0,t.jsxs)("button",{type:"button",role:"radio","aria-checked":e.version===J,onClick:r(()=>{u({version:J}),I(!1)},"onClick"),className:W("flex w-full items-center rounded px-2 py-1.5 text-sm hover:bg-accent",e.version===J&&"font-medium text-amber-700 dark:text-amber-400"),children:["v",J]},J))]})]}):null]}):(0,t.jsxs)("div",{className:"grid min-w-0 flex-1 grid-cols-(--gtc-13)",children:[M?(0,t.jsxs)("select",{"aria-label":"User secret",value:e.userSecretKey,disabled:o,onChange:r(J=>{const ae=J.target.value,oe=a?.find(G=>G.key===ae);u({userSecretKey:ae,...oe&&!e.name.trim()?{name:oe.key.toUpperCase()}:{}})},"onChange"),className:"min-w-0 bg-transparent px-2 py-1.5 text-sm font-mono outline-none disabled:pointer-events-none",children:[(0,t.jsx)("option",{value:"",children:"Select user secret..."}),e.userSecretKey&&!a?.some(J=>J.key===e.userSecretKey)?(0,t.jsxs)("option",{value:e.userSecretKey,children:["Unknown (",e.userSecretKey,")"]}):null,(a??[]).map(J=>(0,t.jsxs)("option",{value:J.key,children:[J.name,J.status!=="active"?` (${J.status})`:""]},J.id))]}):(0,t.jsx)("input",{className:Kre,placeholder:"user-secret key",value:e.userSecretKey,spellCheck:!1,disabled:o,"aria-label":"User secret key",onChange:r(J=>u({userSecretKey:J.target.value}),"onChange")}),(0,t.jsxs)("select",{"aria-label":"Requirement",value:e.required?"required":"optional",disabled:o,onChange:r(J=>u({required:J.target.value==="required"}),"onChange"),className:"border-l border-border bg-transparent px-2 py-1.5 text-xs font-medium text-muted-foreground outline-none disabled:pointer-events-none",children:[(0,t.jsx)("option",{value:"required",children:"Required"}),(0,t.jsx)("option",{value:"optional",children:"Optional"})]})]})]})}),(0,t.jsx)(nr,{align:"start",className:"w-auto p-3",onInteractOutside:r(J=>{const ae=J.detail.originalEvent.target;ae&&S.current?.contains(ae)&&J.preventDefault()},"onInteractOutside"),children:C?.mode==="store"?(0,t.jsx)(Odt,{initialName:C.name,initialValue:C.value,existingSecretNames:n.map(J=>J.name),onCancel:r(()=>_(null),"onCancel"),onSubmit:F}):C?.mode==="create"?(0,t.jsx)(E_e,{initialName:C.name,initialValue:C.value,existingSecretNames:n.map(J=>J.name),onCancel:r(()=>_(null),"onCancel"),onSubmit:F}):null})]}),P?(0,t.jsx)("p",{id:U,role:"status",className:W("mt-0.5 text-(length:--text-micro)",P.level==="error"?"text-destructive":"text-amber-600 dark:text-amber-400"),children:P.message}):null,T?(0,t.jsxs)("p",{className:"mt-0.5 inline-flex items-center gap-2 text-(length:--text-micro) text-muted-foreground",children:["Reverted to text —"," ",(0,t.jsx)("button",{type:"button",className:"font-medium text-foreground underline underline-offset-2 hover:text-primary",onClick:r(()=>{u({source:"secret",secretId:T.secretId,version:T.version,textValue:""}),E(null)},"onClick"),children:"Undo"})]}):null]}),c&&l?(0,t.jsx)("p",{id:K,className:W("col-span-2 col-start-1 row-start-3 min-w-0 text-(length:--text-micro) @[40rem]/env:col-span-2 @[40rem]/env:row-start-2",l.level==="error"?"text-destructive":"text-amber-600 dark:text-amber-400"),children:l.message}):null,(0,t.jsxs)("div",{className:"col-start-2 row-start-1 flex items-center justify-end gap-0.5 self-start @[40rem]/env:col-start-3 @[40rem]/env:self-center",children:[e.source==="text"&&!Q&&(e.name.trim()||e.textValue)?(0,t.jsxs)(na,{children:[(0,t.jsx)(ta,{asChild:!0,disabled:o,children:(0,t.jsx)("button",{type:"button","aria-label":"More actions",className:"rounded p-1 text-muted-foreground opacity-100 hover:bg-accent hover:text-foreground @[40rem]/env:opacity-0 @[40rem]/env:group-hover/row:opacity-100 @[40rem]/env:group-focus-within/row:opacity-100",children:(0,t.jsx)(_i,{className:"size-4"})})}),(0,t.jsx)(sa,{align:"end",children:(0,t.jsx)(us,{onSelect:r(()=>{window.setTimeout(q,0)},"onSelect"),children:"Store as secret…"})})]}):null,(0,t.jsx)("button",{type:"button",onClick:h,disabled:o,"aria-label":`Remove ${e.name.trim()||"variable"}`,className:"rounded p-1 text-muted-foreground opacity-100 hover:bg-destructive/10 hover:text-destructive @[40rem]/env:opacity-0 @[40rem]/env:group-hover/row:opacity-100 @[40rem]/env:group-focus-within/row:opacity-100",children:(0,t.jsx)(Mn,{className:"size-4"})})]})]})}r(Jdt,"EnvironmentVariableRow");var Xdt=/^\s*(?:export\s+)?([A-Za-z_][A-Za-z0-9_]*)\s*=(.*)$/;function eut(e){const s=e.indexOf(" #");return s>=0?e.slice(0,s):e}r(eut,"stripInlineComment");function tut(e){const s=e.trim();if(s.length>=2){const n=s[0],a=s[s.length-1];if(n==='"'&&a==='"'||n==="'"&&a==="'")return s.slice(1,-1)}return eut(s).trim()}r(tut,"unquote");function sut(e){const s=[];for(const n of e.split(/\r?\n/)){const a=n.trim();if(!a||a.startsWith("#"))continue;const i=Xdt.exec(a);if(!i)continue;const o=i[1],l=tut(i[2]);s.push({key:o,value:l})}return s}r(sut,"parseDotenv");var nut=["PAPERCLIP_"],rut="Set the KEY to the env var name the process expects, for example GH_TOKEN. Choose a secret to resolve a stored value at run start. PAPERCLIP_* variables are injected automatically.";function Rz(e){if(!e||typeof e!="object")return[];const s=new Map;for(const[n,a]of Object.entries(e)){const i=n.trim();if(i)if(typeof a=="string")s.set(i,{type:"plain",value:a});else if(a?.type==="secret_ref"){const o=typeof a.secretId=="string"?a.secretId:"";if(!o)continue;s.set(i,{type:"secret_ref",secretId:o,version:typeof a.version=="number"?a.version:"latest"})}else if(a?.type==="user_secret_ref"){const o=typeof a.key=="string"?a.key.trim():"";if(!o)continue;s.set(i,{type:"user_secret_ref",key:o,version:typeof a.version=="number"?a.version:"latest",required:a.required!==!1})}else a?.type==="plain"?s.set(i,{type:"plain",value:typeof a.value=="string"?a.value:""}):s.set(i,{type:"plain",value:""})}return[...s.entries()].sort(([n],[a])=>n.localeCompare(a))}r(Rz,"normalizedEnvEntries");function IS(e){return JSON.stringify(Rz(e))}r(IS,"normalizedEnvKey");var eD=3;function tD(e){const s=e.slice(0,eD).join(", ");return e.length>eD?`${s} +${e.length-eD} more`:s}r(tD,"formatChangedNames");function Qre(e){return e.map(s=>({...s}))}r(Qre,"cloneRows");function aut(e,s){return s?{name:e.name.trim()!==s.name.trim(),value:e.source!==s.source||e.textValue!==s.textValue||e.secretId!==s.secretId||e.userSecretKey!==s.userSecretKey||e.required!==s.required||e.version!==s.version}:{name:!!e.name.trim(),value:e.source!=="text"||!!e.textValue||!!e.secretId||e.version!=="latest"}}r(aut,"rowDirtyFields");var kj=(0,m.forwardRef)(r(function({value:s,onChange:n,secrets:a,userSecretDefinitions:i,onCreateSecret:o,recentlyUsedSecrets:l,disabled:c,reservedPrefixes:d=nut,footerHint:u,onDirtyChange:h,hideDraftActions:p=!1},f){const x=jd(),g=(0,m.useRef)(null),[v,y]=(0,m.useState)(()=>X9(s)),k=(0,m.useRef)(v),[w,N]=(0,m.useState)(()=>Qre(v)),S=(0,m.useMemo)(()=>IS(s),[]),C=(0,m.useRef)(S),_=(0,m.useRef)(S),R=(0,m.useRef)(null),[I,T]=(0,m.useState)(S),[E,P]=(0,m.useState)(()=>new Set(X9(s).map(de=>de.name.trim()).filter(Boolean))),[O,M]=(0,m.useState)(null);(0,m.useEffect)(()=>{k.current=v},[v]);function Q(de,xe=k.current){C.current=de,T(de),N(Qre(xe))}r(Q,"markCommitted");function L(de){P(xe=>{const le=new Set(xe);for(const Re of de){const Le=Re.name.trim();Le&&le.add(Le)}return le})}r(L,"touchCommittedNames");function F(de){const xe=X9(de);return y(xe),L(xe),xe}r(F,"adoptExternalValue"),(0,m.useEffect)(()=>{const de=IS(s);if(de===_.current)return;_.current=de;const xe=IS(h6(k.current)),le=xe!==C.current,Re=R.current===de;if(Re&&(R.current=null),!le){Q(de,F(s));return}(Re||xe===de)&&(L(k.current),Q(de))},[s]);const q=(0,m.useMemo)(()=>h6(v),[v]),z=(0,m.useMemo)(()=>IS(q),[q]),K=z!==I;(0,m.useEffect)(()=>{h?.(!c&&K)},[c,K,h]);const U=(0,m.useMemo)(()=>{const de=new Map(Rz(h6(w)).map(([Le,je])=>[Le,JSON.stringify(je)])),xe=new Map(Rz(q).map(([Le,je])=>[Le,JSON.stringify(je)])),le=[],Re=[];for(const[Le,je]of xe)de.has(Le)?de.get(Le)!==je&&Re.push(Le):le.push(Le);return{added:le,changed:Re,removed:[...de.keys()].filter(Le=>!xe.has(Le))}},[w,q]),V=(0,m.useMemo)(()=>{const de=[];return U.added.length>0&&de.push(`New: ${tD(U.added)}`),U.changed.length>0&&de.push(`Edited: ${tD(U.changed)}`),U.removed.length>0&&de.push(`Removed: ${tD(U.removed)}`),de.join(" · ")},[U]);(0,m.useEffect)(()=>{if(c||!K)return;function de(xe){xe.preventDefault(),xe.returnValue=""}return r(de,"handleBeforeUnload"),window.addEventListener("beforeunload",de),()=>window.removeEventListener("beforeunload",de)},[c,K]);const ne=(0,m.useCallback)(()=>c||!K?null:(R.current=z,(0,F0.flushSync)(()=>{n(q)}),q??{}),[c,q,z,K,n]);(0,m.useImperativeHandle)(f,()=>({flushPendingDraft:ne}),[ne]),(0,m.useEffect)(()=>{const de=g.current?.closest("form");if(!de)return;function xe(){ne()}return r(xe,"handleSubmit"),de.addEventListener("submit",xe,!0),()=>de.removeEventListener("submit",xe,!0)},[ne]),(0,m.useEffect)(()=>{const de=g.current;if(!de)return;const xe=de;function le(Re){const Le=Re.target;if(!(Le instanceof Element)||xe.contains(Le))return;const je=Le.closest("button");if(!je||je.disabled)return;const _e=`${je.getAttribute("aria-label")??""} ${je.textContent??""}`;(je.type==="submit"||/\b(save|create|update|test|import)\b/i.test(_e))&&ne()}return r(le,"handleDocumentClick"),document.addEventListener("click",le,!0),()=>document.removeEventListener("click",le,!0)},[ne]);function Z(de){y(de)}r(Z,"updateDraft");function ie(de,xe){Z(v.map(le=>le.id===de?{...le,...xe}:le))}r(ie,"patchRow");function J(de){Z(v.filter(xe=>xe.id!==de))}r(J,"removeRow");function ae(){const de=jx();y([...v,de]),M({rowId:de.id,field:"name"})}r(ae,"addRow");function oe(de){const xe=v.find(le=>le.id===de)?.name.trim();xe&&P(le=>{if(le.has(xe))return le;const Re=new Set(le);return Re.add(xe),Re})}r(oe,"markTouched");function G(de,xe){const le=sut(de);if(le.length===0)return!1;const Re=v.filter(Le=>Le.id!==xe).map(Le=>({...Le}));for(const{key:Le,value:je}of le){const _e=Re.find(Ze=>Ze.name.trim()===Le);_e?(_e.name=Le,_e.source="text",_e.textValue=je,_e.secretId="",_e.sensitiveDismissed=!1,_e.userSecretKey="",_e.required=!0):Re.push({...jx(),name:Le,textValue:je})}return Z(Re),x?.pushToast({title:`Imported ${le.length} variable${le.length===1?"":"s"}`,tone:"success"}),!0}r(G,"bulkImport");function X(de){const xe=v.map(Le=>({...Le})),le=xe[xe.length-1];let Re;le&&!le.name&&!le.textValue&&!le.secretId&&!le.userSecretKey?Re=le:(Re=jx(),xe.push(Re)),Re.source="secret",Re.secretId=de.id,Re.version="latest",Re.name||(Re.name=c_(de.name)),Z(xe)}r(X,"bindRecentSecret");function Y(){K&&(R.current=z,n(q))}r(Y,"saveDraft");function re(){R.current=null,_.current=IS(s);const de=F(s);Q(_.current,de)}r(re,"revertDraft");const se=(0,m.useMemo)(()=>Gdt(v),[v]),ce=(0,m.useMemo)(()=>v.reduce((de,xe)=>L_e(xe,a)||M_e(xe,i)?de+1:de,0),[v,a,i]),pe=(0,m.useMemo)(()=>{const de=new Set(v.filter(xe=>xe.source==="secret"&&xe.secretId).map(xe=>xe.secretId));return(l??[]).filter(xe=>xe.status==="active"&&!de.has(xe.id)).slice(0,8)},[l,v]),fe=v.length>0,ve=u===void 0?rut:u,Ie=(0,m.useMemo)(()=>new Map(w.map(de=>[de.id,de])),[w]);return(0,t.jsx)(Zc,{children:(0,t.jsxs)("div",{ref:g,className:"@container/env space-y-2",children:[ce>1?(0,t.jsxs)("p",{className:"inline-flex items-center gap-1.5 text-(length:--text-micro) font-medium text-amber-700 dark:text-amber-400",children:[(0,t.jsx)(Ji,{className:"size-3.5"}),ce," bindings need attention"]}):null,fe?(0,t.jsxs)(t.Fragment,{children:[(0,t.jsxs)("div",{className:"hidden gap-x-1.5 @[40rem]/env:grid @[40rem]/env:grid-cols-(--gtc-14)",children:[(0,t.jsx)("span",{className:"text-(length:--text-micro) font-medium uppercase tracking-wide text-muted-foreground",children:"Name"}),(0,t.jsx)("span",{className:"text-(length:--text-micro) font-medium uppercase tracking-wide text-muted-foreground",children:"Value"}),(0,t.jsx)("span",{})]}),v.map((de,xe)=>{const le=Vdt(de.name,se,d),Re=E.has(de.name.trim());return(0,t.jsx)(Jdt,{row:de,isLast:xe===v.length-1,secrets:a,userSecretDefinitions:i,recentlyUsedSecrets:l,disabled:c,nameIssue:le,showNameIssue:Re,dirtyFields:aut(de,Ie.get(de.id)),onPatch:r(Le=>ie(de.id,Le),"onPatch"),onRemove:r(()=>J(de.id),"onRemove"),onNameBlur:r(()=>oe(de.id),"onNameBlur"),onNamePaste:r(Le=>G(Le,de.id),"onNamePaste"),onEnterInValueLast:ae,onCreateSecret:o,onToast:r(Le=>x?.pushToast({title:Le,tone:"success"}),"onToast"),focusRequest:O?.rowId===de.id?O.field:null,onFocusConsumed:r(()=>M(null),"onFocusConsumed")},de.id)})]}):(0,t.jsx)("p",{className:"text-sm text-muted-foreground",children:"No environment variables"}),(0,t.jsxs)("div",{className:"flex flex-wrap items-center justify-between gap-2 pt-1",children:[(0,t.jsxs)("button",{type:"button",onClick:ae,disabled:c,className:"inline-flex items-center gap-1 rounded-md px-2 py-1 text-xs font-medium text-muted-foreground transition-colors hover:bg-accent hover:text-foreground disabled:pointer-events-none disabled:opacity-50",children:[(0,t.jsx)(bn,{className:"size-3.5"}),"Add variable"]}),pe.length>0&&!c?(0,t.jsxs)("div",{className:"flex flex-wrap items-center gap-1.5",children:[(0,t.jsxs)("span",{className:"inline-flex items-center gap-1 text-(length:--text-micro) text-muted-foreground/70",children:[(0,t.jsx)(Si,{className:"size-3"}),"Recently used:"]}),pe.map(de=>(0,t.jsxs)("button",{type:"button",onClick:r(()=>X(de),"onClick"),className:"inline-flex items-center gap-1 rounded-full border border-border px-2 py-0.5 font-mono text-(length:--text-micro) text-muted-foreground transition-colors hover:bg-accent/50 hover:text-foreground",title:`Bind ${de.name}`,children:["+ ",de.name]},de.id))]}):null]}),K&&!c&&!p?(0,t.jsxs)("div",{role:"status",className:"mt-3 flex w-full flex-col gap-3 rounded-md border border-amber-500/30 bg-amber-500/10 px-3 py-3 text-amber-950 shadow-sm dark:bg-amber-500/15 dark:text-amber-100 @[34rem]/env:flex-row @[34rem]/env:items-center @[34rem]/env:justify-between",children:[(0,t.jsxs)("div",{className:"flex min-w-0 flex-col gap-0.5",children:[(0,t.jsxs)("div",{className:"flex items-center gap-2 text-sm font-medium",children:[(0,t.jsx)("span",{className:"size-2 rounded-full bg-amber-500 shadow-(--shadow-extract-13)"}),(0,t.jsx)("span",{children:"Unsaved changes"})]}),V?(0,t.jsx)("p",{className:"min-w-0 truncate pl-4 text-xs text-amber-950/80 dark:text-amber-100/80",title:V,children:V}):null]}),(0,t.jsxs)("div",{className:"flex items-center gap-2",children:[(0,t.jsxs)("button",{type:"button",onClick:re,className:"inline-flex h-9 items-center gap-1.5 rounded-md border border-amber-500/30 bg-background px-3 text-sm font-medium text-foreground transition-colors hover:bg-amber-500/10 dark:bg-background/80",children:[(0,t.jsx)(Ai,{className:"size-4"}),"Revert"]}),(0,t.jsxs)("button",{type:"button",onClick:Y,className:"inline-flex h-9 items-center gap-1.5 rounded-md bg-primary px-4 text-sm font-medium text-primary-foreground transition-colors hover:bg-primary/90",children:[(0,t.jsx)(of,{className:"size-4"}),"Save"]})]})]}):null,ve?(0,t.jsx)("p",{className:"text-(length:--text-micro) text-muted-foreground/70",children:ve}):null,v.some(de=>de.source==="user_secret"&&de.userSecretKey)?(0,t.jsxs)("p",{className:"inline-flex items-start gap-1 text-(length:--text-micro) text-muted-foreground/70",children:[(0,t.jsx)(oh,{className:"mt-0.5 size-3 shrink-0"}),(0,t.jsx)("span",{children:"User secrets resolve from the user responsible for the run. Required bindings fail until that user sets their value under Secrets → My secrets."})]}):null]})})},"EnvironmentVariablesEditor")),iut="env.",Y3="access.",Ez=/^[A-Za-z_][A-Za-z0-9_]*$/;function P_e(e){return e?e.startsWith("access.")?"api":e.startsWith("env.")?"env":"config":"config"}r(P_e,"deliveryModeForConfigPath");function D_e(e){switch(e){case"env":return"Env var";case"api":return"API access";default:return"Config"}}r(D_e,"deliveryModeLabel");function out(e){switch(e){case"env":return"Injected as an environment variable at run start.";case"api":return"Fetched on demand via the run-bound agent API. Never written to the environment.";default:return"Provided through adapter configuration."}}r(out,"deliveryModeDescription");function $_e(e){return e?e.startsWith("access.")?e.slice(7):e.startsWith("env.")?e.slice(4):e:""}r($_e,"aliasFromConfigPath");function lut(e){switch(e){case"agent_api":return"Agent API";case"plugin_worker":return"Plugin worker";case"tool_connection":return"Tool connection";default:return e.charAt(0).toUpperCase()+e.slice(1)}}r(lut,"consumerTypeLabel");var cut={numeric:!0,sensitivity:"base"};function SC(e){return e.kind==="company"?e.secret.name:e.definition.name}r(SC,"getSecretPathRowName");function kN(e){return e.split("/").filter(s=>s.length>0)}r(kN,"splitSecretPath");function sD(e){return kN(e).join("/")}r(sD,"normalizeSecretPath");function Wre(e,s){return s.every((n,a)=>e[a]===n)}r(Wre,"startsWithSegments");function Hre(e,s){return e.localeCompare(s,void 0,cut)}r(Hre,"compareNames");function dut(e,s){const n=kN(s),a=e.map(c=>({row:c,name:SC(c),segments:kN(SC(c))})),i=new Set,o=[];for(const c of a){if(!Wre(c.segments,n))continue;const d=c.segments.length-n.length;(d===0||d===1)&&o.push(c.row),d>=2&&i.add(c.segments[n.length])}const l=[...i].map(c=>{const d=[...n,c],u=new Set;let h=0;for(const p of a){if(!Wre(p.segments,d))continue;const f=p.segments.length-d.length;if(!(f<1)){h+=1;for(let x=1;x<f;x+=1)u.add(p.segments.slice(d.length,d.length+x).join("/"))}}return{name:c,path:d.join("/"),secretCount:h,folderCount:u.size}});return l.sort((c,d)=>Hre(c.name,d.name)),o.sort((c,d)=>Hre(SC(c),SC(d))),{folders:l,secrets:o}}r(dut,"buildSecretPathListing");function uut(e){const s=kN(e);return s.map((n,a)=>({name:n,path:s.slice(0,a+1).join("/")}))}r(uut,"buildSecretPathBreadcrumbs");function mut(e){return e.trim()?e.includes("/")?"Folder name cannot contain slashes.":null:"Folder name is required."}r(mut,"validateSecretFolderSegment");function g5({name:e,basePath:s="",className:n,leafClassName:a}){const i=kN(e),o=kN(s),l=o.length>0&&o.every((h,p)=>i[p]===h)&&i.length>o.length?i.slice(o.length):i,c=l.length>0?l:[e],d=c[c.length-1],u=c.slice(0,-1).join("/");return(0,t.jsxs)("span",{className:W("min-w-0 truncate",n),children:[u?(0,t.jsxs)("span",{className:"text-muted-foreground",children:[u,"/"]}):null,(0,t.jsx)("span",{className:W("font-medium text-foreground",a),children:d})]})}r(g5,"SecretPathName");function hut(e,s){const n=e?`sha256:${e.slice(0,10)}…`:"no fingerprint",a=typeof s=="number"?`${s} ${s===1?"byte":"bytes"}`:null;return a?`${n} · ${a}`:n}r(hut,"fingerprintLabel");function O_e({fingerprint:e,length:s,className:n}){const{pushToast:a}=Zr(),i=hut(e,s);if(!e)return(0,t.jsxs)("span",{className:W("inline-flex items-center gap-1 font-mono",n),children:[(0,t.jsx)(pF,{className:"size-3 shrink-0"}),i]});const o=`sha256:${e}`;return(0,t.jsxs)("button",{type:"button",onClick:r(()=>{wa(o).then(()=>a({title:"Fingerprint copied",tone:"success"})).catch(()=>a({title:"Couldn’t copy fingerprint",tone:"error"}))},"onClick"),title:`Copy full digest — ${o}`,className:W("inline-flex items-center gap-1 font-mono hover:text-foreground",n),children:[(0,t.jsx)(pF,{className:"size-3 shrink-0"}),i,(0,t.jsx)(br,{className:"size-3 shrink-0 opacity-60"})]})}r(O_e,"FingerprintChip");function yV({justification:e,className:s}){return(0,t.jsxs)("div",{className:W("space-y-0.5",s),children:[(0,t.jsx)("p",{className:"text-(length:--text-micro) text-muted-foreground",children:"Reason given by the agent"}),(0,t.jsxs)("p",{className:"whitespace-pre-wrap break-words text-xs text-foreground/80",children:["“",e,"”"]})]})}r(yV,"ProposalJustification");function b5({agent:e,className:s}){return(0,t.jsxs)("span",{className:W("inline-flex min-w-0 items-center gap-1",s),children:[(0,t.jsx)(lr,{agent:e,size:16,className:"h-3.5 w-3.5 shrink-0 text-muted-foreground"}),(0,t.jsx)("span",{className:"min-w-0 truncate",children:e.name})]})}r(b5,"AgentRefChip");function jV({configPath:e}){const s=P_e(e),n=s==="env",a=s==="api";return(0,t.jsxs)(ot,{variant:"outline",className:W("h-5 gap-1 px-1.5 text-(length:--text-nano) font-normal",n&&"border-sky-500/30 bg-sky-500/10 text-sky-700 dark:text-sky-300",a&&"border-violet-500/30 bg-violet-500/10 text-violet-700 dark:text-violet-300",!n&&!a&&"border-border bg-muted/40 text-muted-foreground"),children:[n?(0,t.jsx)(V1e,{className:"size-3"}):a?(0,t.jsx)(PL,{className:"size-3"}):null,D_e(s)]})}r(jV,"DeliveryBadge$1");function wV({className:e}){return(0,t.jsxs)(ot,{variant:"outline",className:W("h-5 gap-1 px-1.5 text-(length:--text-nano) font-medium","border-amber-500/40 bg-amber-500/10 text-amber-700 dark:text-amber-300",e),children:[(0,t.jsx)(Tc,{className:"size-3"})," Proposed"]})}r(wV,"ProposedBadge");function wM(e){return $_e(e.configPath)}r(wM,"bindingEnvKey");function kV(e){return e.secretProposalId?{name:e.secretProposalName??"proposed secret",pending:!0}:{name:e.secretName??"secret",pending:!1}}r(kV,"bindingSecretLabel");function Vre(e){return e instanceof nn?e.message||`Request failed: ${e.status}`:e instanceof Error?e.message:"Something went wrong. Try again."}r(Vre,"readableError");function B_e(e,s=[]){const n=wt(),{pushToast:a}=Zr(),[i,o]=(0,m.useState)(null),[l,c]=(0,m.useState)(null),[d,u]=(0,m.useState)(""),[h,p]=(0,m.useState)(null),f=(0,m.useCallback)(()=>{e&&(n.invalidateQueries({queryKey:["secret-proposals",e]}),n.invalidateQueries({queryKey:D.secrets.list(e)}))},[e,n]),x=we({mutationFn:r(w=>{const{proposal:N}=w;if(N.kind==="secret"){const S=w.folder.trim()?`${w.folder.trim().replace(/\/+$/,"")}/${w.leaf.trim()}`:w.leaf.trim();return Rr.approveProposal(e,N.id,{overrides:{name:S,description:w.description.trim()||null,providerConfigId:w.providerConfigId||null}})}return Rr.approveProposal(e,N.id,{cascade:w.cascade||void 0})},"mutationFn"),onSuccess:r(w=>{a({title:w.kind==="secret"?"Secret approved":"Binding approved",body:w.kind==="secret"?w.proposedName??"Secret created":`${w.target?.name??"Agent"} · ${wM(w)||"binding"}`,tone:"success"}),o(null),p(null),f()},"onSuccess"),onError:r(w=>p(Vre(w)),"onError")}),g=we({mutationFn:r(({proposal:w,reason:N})=>Rr.rejectProposal(e,w.id,{reason:N.trim()}),"mutationFn"),onSuccess:r(w=>{a({title:"Proposal rejected",body:w.kind==="secret"?w.proposedName??void 0:void 0,tone:"info"}),c(null),u(""),p(null),f()},"onSuccess"),onError:r(w=>p(Vre(w)),"onError")}),v=(0,m.useCallback)(w=>{p(null);const N=(w.proposedName??"").split("/"),S=N.pop()??"";o({proposal:w,folder:N.join("/"),leaf:S,description:w.proposedDescription??"",providerConfigId:s.find(C=>C.provider==="local_encrypted"&&C.isDefault)?.id??"",cascade:!!w.secretProposalId})},[s]),y=(0,m.useCallback)(w=>{p(null),u(""),c(w)},[]),k=(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)(put,{draft:i,error:h,pending:x.isPending,providerConfigs:s,onChange:o,onCancel:r(()=>{o(null),p(null)},"onCancel"),onConfirm:r(()=>i&&x.mutate(i),"onConfirm")}),(0,t.jsx)(xut,{proposal:l,reason:d,error:h,pending:g.isPending,onReasonChange:u,onCancel:r(()=>{c(null),u(""),p(null)},"onCancel"),onConfirm:r(()=>l&&g.mutate({proposal:l,reason:d}),"onConfirm")})]});return{requestApprove:v,requestReject:y,isBusy:x.isPending||g.isPending,dialogs:k}}r(B_e,"useProposalReview");function put({draft:e,error:s,pending:n,providerConfigs:a,onChange:i,onCancel:o,onConfirm:l}){const c=e?.proposal.kind==="secret",d=e?e.folder.trim()?`${e.folder.trim().replace(/\/+$/,"")}/${e.leaf.trim()}`:e.leaf.trim():"",u=a.filter(p=>p.provider==="local_encrypted"),h=c?!!(e&&e.leaf.trim()):!0;return(0,t.jsx)(Fs,{open:!!e,onOpenChange:r(p=>!p&&o(),"onOpenChange"),children:(0,t.jsx)(Qs,{className:"sm:max-w-lg",children:e?(0,t.jsxs)(t.Fragment,{children:[(0,t.jsxs)(rn,{children:[(0,t.jsx)(Ks,{children:c?"Approve & create secret":"Approve binding"}),(0,t.jsx)(mn,{children:c?"The value is created as the proposing agent recorded it. Re-folder or rename it before it lands.":"Grant the target agent access to this secret. This runs with your permissions."})]}),(0,t.jsxs)("div",{className:"space-y-1.5 rounded-md border border-border bg-muted/30 p-2.5 text-xs",children:[(0,t.jsxs)("div",{className:"flex items-center gap-1.5 text-muted-foreground",children:[(0,t.jsx)("span",{children:"Proposed by"}),(0,t.jsx)(b5,{agent:e.proposal.proposedBy,className:"font-medium text-foreground"})]}),(0,t.jsx)(yV,{justification:e.proposal.justification})]}),c?(0,t.jsxs)("div",{className:"space-y-3",children:[(0,t.jsxs)("div",{className:"grid grid-cols-2 gap-2",children:[(0,t.jsxs)("div",{className:"space-y-1",children:[(0,t.jsx)($s,{htmlFor:"approve-folder",children:"Folder"}),(0,t.jsx)(dt,{id:"approve-folder",value:e.folder,onChange:r(p=>i({...e,folder:p.target.value}),"onChange"),placeholder:"dev/github",className:"font-mono text-xs"})]}),(0,t.jsxs)("div",{className:"space-y-1",children:[(0,t.jsx)($s,{htmlFor:"approve-name",children:"Name"}),(0,t.jsx)(dt,{id:"approve-name",value:e.leaf,onChange:r(p=>i({...e,leaf:p.target.value}),"onChange"),placeholder:"client-secret",autoFocus:!0,"aria-invalid":!e.leaf.trim(),className:"font-mono text-xs"})]})]}),(0,t.jsxs)("p",{className:"text-(length:--text-micro) text-muted-foreground",children:["Lands as"," ",d?(0,t.jsx)(g5,{name:d,className:"font-mono"}):(0,t.jsx)("span",{className:"italic",children:"enter a name"})]}),(0,t.jsxs)("div",{className:"space-y-1",children:[(0,t.jsx)($s,{htmlFor:"approve-description",children:"Description"}),(0,t.jsx)(dt,{id:"approve-description",value:e.description,onChange:r(p=>i({...e,description:p.target.value}),"onChange"),placeholder:"Optional"})]}),u.length>0?(0,t.jsxs)("div",{className:"space-y-1",children:[(0,t.jsx)($s,{htmlFor:"approve-provider-config",children:"Provider vault"}),(0,t.jsxs)("select",{id:"approve-provider-config",value:e.providerConfigId,onChange:r(p=>i({...e,providerConfigId:p.target.value}),"onChange"),className:"h-9 w-full rounded-md border border-input bg-transparent px-2 text-sm outline-none focus-visible:border-ring focus-visible:ring-3 focus-visible:ring-ring/50",children:[(0,t.jsx)("option",{value:"",children:"Deployment default"}),u.map(p=>(0,t.jsx)("option",{value:p.id,children:p.displayName},p.id))]})]}):null,(0,t.jsx)("div",{className:"rounded-md border border-border bg-background px-2.5 py-1.5 text-xs text-muted-foreground",children:(0,t.jsx)(O_e,{fingerprint:e.proposal.valueFingerprintSha256,length:e.proposal.valueLength})})]}):(0,t.jsx)(fut,{draft:e,onChange:i}),s?(0,t.jsx)("p",{className:"text-xs text-destructive",role:"alert",children:s}):null,(0,t.jsxs)(cr,{children:[(0,t.jsx)($,{variant:"ghost",onClick:o,disabled:n,children:"Cancel"}),(0,t.jsx)($,{onClick:l,disabled:n||!h,children:n?"Approving…":c?"Approve & create":e.cascade?"Approve secret & bind":"Approve binding"})]})]}):null})})}r(put,"ApproveDialog");function fut({draft:e,onChange:s}){const{proposal:n}=e,a=kV(n),i=wM(n);return(0,t.jsxs)("div",{className:"space-y-3 text-sm",children:[(0,t.jsxs)("div",{className:"space-y-2 rounded-md border border-border p-3",children:[(0,t.jsxs)("div",{className:"flex items-center justify-between gap-2",children:[(0,t.jsx)("span",{className:"text-xs text-muted-foreground",children:"Target agent"}),n.target?(0,t.jsx)(b5,{agent:n.target,className:"text-sm font-medium"}):(0,t.jsx)("span",{className:"text-muted-foreground",children:"—"})]}),(0,t.jsxs)("div",{className:"flex items-center justify-between gap-2",children:[(0,t.jsx)("span",{className:"text-xs text-muted-foreground",children:"Delivered as"}),(0,t.jsxs)("span",{className:"flex items-center gap-1.5",children:[(0,t.jsx)(jV,{configPath:n.configPath}),(0,t.jsx)("code",{className:"font-mono text-xs",children:i||n.configPath})]})]}),(0,t.jsxs)("div",{className:"flex items-center justify-between gap-2",children:[(0,t.jsx)("span",{className:"text-xs text-muted-foreground",children:"Secret"}),(0,t.jsxs)("span",{className:"flex items-center gap-1.5",children:[(0,t.jsx)(Si,{className:"size-3.5 text-muted-foreground"}),(0,t.jsx)("span",{className:"font-medium",children:a.name}),a.pending?(0,t.jsx)(wV,{}):null]})]})]}),n.secretProposalId?(0,t.jsxs)("label",{className:"flex items-start gap-2 rounded-md border border-amber-500/30 bg-amber-500/5 p-2.5 text-xs",children:[(0,t.jsx)(ei,{checked:e.cascade,onCheckedChange:r(o=>s({...e,cascade:o===!0}),"onCheckedChange"),className:"mt-0.5","aria-label":"Also approve the proposed secret"}),(0,t.jsxs)("span",{className:"text-foreground/90",children:["Also approve the proposed secret"," ",(0,t.jsx)("span",{className:"font-medium",children:a.name})," and create it in the same step. The binding can’t land without it."]})]}):null]})}r(fut,"BindingApproveBody");function xut({proposal:e,reason:s,error:n,pending:a,onReasonChange:i,onCancel:o,onConfirm:l}){const c=s.trim().length>0;return(0,t.jsx)(Fs,{open:!!e,onOpenChange:r(d=>!d&&o(),"onOpenChange"),children:(0,t.jsx)(Qs,{className:"sm:max-w-md",children:e?(0,t.jsxs)(t.Fragment,{children:[(0,t.jsxs)(rn,{children:[(0,t.jsx)(Ks,{children:"Reject proposal"}),(0,t.jsxs)(mn,{children:["The reason is sent back to"," ",(0,t.jsx)(b5,{agent:e.proposedBy,className:"text-foreground"}),". Dependent bindings are rejected too."]})]}),(0,t.jsxs)("div",{className:"space-y-1",children:[(0,t.jsx)($s,{htmlFor:"reject-reason",children:"Reason"}),(0,t.jsx)(Hn,{id:"reject-reason",value:s,onChange:r(d=>i(d.target.value),"onChange"),rows:3,autoFocus:!0,placeholder:"Why is this being rejected?"})]}),n?(0,t.jsx)("p",{className:"text-xs text-destructive",role:"alert",children:n}):null,(0,t.jsxs)(cr,{children:[(0,t.jsx)($,{variant:"ghost",onClick:o,disabled:a,children:"Cancel"}),(0,t.jsx)($,{variant:"destructive",onClick:l,disabled:a||!c,children:a?"Rejecting…":"Reject"})]})]}):null})})}r(xut,"RejectDialog");function F_e({proposal:e,onApprove:s,onReject:n,disabled:a,size:i="sm"}){const o=!e.viewerCanApprove,l=i==="xs"?"h-7 px-2 text-xs":"",c=(0,t.jsx)($,{size:"sm",className:l,disabled:a||o,onClick:r(()=>s(e),"onClick"),children:"Approve"});return(0,t.jsxs)("div",{className:"flex items-center gap-1.5",children:[o?(0,t.jsx)(Zc,{children:(0,t.jsxs)(Fn,{children:[(0,t.jsx)(Bn,{asChild:!0,children:(0,t.jsx)("span",{tabIndex:0,children:c})}),(0,t.jsx)(On,{className:"max-w-72",children:e.approveBlockReason??"You don’t have permission to approve this."})]})}):c,(0,t.jsx)($,{size:"sm",variant:"outline",className:l,disabled:a,onClick:r(()=>n(e),"onClick"),children:"Reject"})]})}r(F_e,"ProposalActions");function z_e(e){return typeof e!="object"||e===null||Array.isArray(e)?null:e}r(z_e,"asRecord$16");function q_e(e){const s=z_e(e);if(!s||s.type!=="secret_ref")return null;const n=typeof s.secretId=="string"?s.secretId:"";return n?{secretId:n,version:typeof s.version=="number"?s.version:"latest"}:null}r(q_e,"readSecretRef");function gut(e){const s=z_e(e?.env);if(!s)return[];const n=[];for(const[a,i]of Object.entries(s)){const o=q_e(i);o&&n.push({name:a,...o})}return n}r(gut,"parseEnvSecretRefs");function but(e){if(!e)return[];const s=[];for(const[n,a]of Object.entries(e)){if(!n.startsWith("access."))continue;const i=q_e(a);i&&s.push({name:n.slice(Y3.length),...i})}return s}r(but,"parseAccessGrants");function vut(e,s){const n=new Map,a=r(i=>{let o=n.get(i);return o||(o={secretId:i,envKeys:[],apiAliases:[]},n.set(i,o)),o},"ensure");for(const i of e)a(i.secretId).envKeys.push(i.name);for(const i of s)a(i.secretId).apiAliases.push(i.name);return[...n.values()]}r(vut,"summarizeAgentBindings");var Gre=0;function U_e(){return Gre+=1,`access-row-${Gre}`}r(U_e,"nextAccessRowId");function nD(e){return e.map(s=>({id:U_e(),alias:s.name,secretId:s.secretId,version:s.version}))}r(nD,"entriesToRows");function Yre(e){const s={};for(const n of e){const a=n.alias.trim();!a||!Ez.test(a)||!n.secretId||(s[a]={type:"secret_ref",secretId:n.secretId,version:n.version})}return s}r(Yre,"rowsToAccessMap");function Zre(e){return JSON.stringify(Object.keys(e).sort().map(s=>{const n=e[s];return[s,n.secretId,n.version??"latest"]}))}r(Zre,"normalizeAccessMapKey");function Jre({mode:e}){return e==="env"?(0,t.jsxs)(ot,{variant:"outline",className:"h-5 gap-1 px-1.5 text-(length:--text-nano) font-normal border-sky-500/30 bg-sky-500/10 text-sky-700 dark:text-sky-300",children:[(0,t.jsx)(V1e,{className:"size-3"})," Env var"]}):(0,t.jsxs)(ot,{variant:"outline",className:"h-5 gap-1 px-1.5 text-(length:--text-nano) font-normal border-violet-500/30 bg-violet-500/10 text-violet-700 dark:text-violet-300",children:[(0,t.jsx)(PL,{className:"size-3"})," API access"]})}r(Jre,"DeliveryBadge");function yut({config:e,secrets:s,onChange:n,onCreateSecret:a,disabled:i,proposals:o,onApproveProposal:l,onRejectProposal:c}){const d=(0,m.useMemo)(()=>(o??[]).filter(O=>O.kind==="binding"),[o]),u=(0,m.useMemo)(()=>gut(e),[e]),h=(0,m.useMemo)(()=>but(e),[e]),p=(0,m.useMemo)(()=>vut(u,h),[u,h]),f=(0,m.useMemo)(()=>Yre(nD(h)),[h]),x=(0,m.useMemo)(()=>Zre(f),[f]),[g,v]=(0,m.useState)(()=>nD(h)),[y,k]=(0,m.useState)(null),w=(0,m.useRef)(new Map),N=(0,m.useRef)(x),S=(0,m.useRef)(x);(0,m.useEffect)(()=>{x!==S.current&&(S.current=x,x!==N.current&&v(nD(h)))},[x,h]);const C=r(O=>s.find(M=>M.id===O)?.name??`${O.slice(0,8)}…`,"secretName");function _(O){v(O);const M=Yre(O);N.current=Zre(M),n(M)}r(_,"emit");function R(O,M){_(g.map(Q=>Q.id===O?{...Q,...M}:Q))}r(R,"patchRow");function I(O){_(g.filter(M=>M.id!==O))}r(I,"removeRow");function T(){v(O=>[...O,{id:U_e(),alias:"",secretId:"",version:"latest"}])}r(T,"addRow");const E=(0,m.useMemo)(()=>{const O=new Map;for(const M of g){const Q=M.alias.trim();Q&&O.set(Q,(O.get(Q)??0)+1)}return O},[g]),P=p.length>0;return(0,t.jsxs)("div",{className:"space-y-3",children:[P?(0,t.jsx)("div",{className:"space-y-1.5",children:p.map(O=>(0,t.jsxs)("div",{className:"flex flex-wrap items-center gap-x-2 gap-y-1 rounded-md border border-border bg-muted/30 px-2.5 py-1.5 text-xs",children:[(0,t.jsx)(Si,{className:"size-3.5 shrink-0 text-muted-foreground"}),(0,t.jsx)("span",{className:"font-medium",children:C(O.secretId)}),O.envKeys.length>0?(0,t.jsx)(Jre,{mode:"env"}):null,O.apiAliases.length>0?(0,t.jsx)(Jre,{mode:"api"}):null,(0,t.jsx)("span",{className:"min-w-0 truncate font-mono text-(length:--text-micro) text-muted-foreground",children:[...O.envKeys.map(M=>`${iut}${M}`),...O.apiAliases.map(M=>`${Y3}${M}`)].join(" · ")})]},O.secretId))}):(0,t.jsx)("p",{className:"text-sm text-muted-foreground",children:"No secrets are bound to this agent yet."}),d.length>0&&l&&c?(0,t.jsxs)("div",{className:"space-y-2",children:[(0,t.jsx)("div",{className:"text-(length:--text-micro) font-medium uppercase tracking-wide text-muted-foreground",children:"Proposed access"}),d.map(O=>{const M=kV(O),Q=wM(O);return(0,t.jsxs)("div",{className:"flex flex-col gap-2 rounded-md border border-amber-500/30 bg-amber-500/5 px-2.5 py-2 text-xs sm:flex-row sm:items-center",children:[(0,t.jsxs)("div",{className:"min-w-0 flex-1 space-y-1",children:[(0,t.jsxs)("div",{className:"flex min-w-0 flex-wrap items-center gap-1.5",children:[(0,t.jsx)(jV,{configPath:O.configPath}),(0,t.jsx)("code",{className:"font-mono",children:Q||O.configPath}),(0,t.jsx)("span",{className:"text-muted-foreground",children:"→"}),(0,t.jsx)(Si,{className:"size-3 text-muted-foreground"}),(0,t.jsx)("span",{className:"font-medium",children:M.name}),M.pending?(0,t.jsx)(wV,{}):null]}),(0,t.jsxs)("p",{className:"flex flex-wrap items-center gap-1 text-muted-foreground",children:[(0,t.jsxs)("span",{children:["proposed by ",O.proposedBy.name]}),(0,t.jsx)("span",{"aria-hidden":"true",children:"·"}),(0,t.jsxs)("span",{className:"truncate italic",children:["“",O.justification,"”"]})]})]}),(0,t.jsx)(F_e,{proposal:O,onApprove:l,onReject:c,disabled:i,size:"xs"})]},O.id)})]}):null,(0,t.jsxs)("div",{className:"space-y-2",children:[(0,t.jsx)("div",{className:"text-(length:--text-micro) font-medium uppercase tracking-wide text-muted-foreground",children:"API access (no env var)"}),g.length>0?(0,t.jsx)("div",{className:"space-y-2",children:g.map(O=>{const M=O.alias.trim(),Q=!!M&&!Ez.test(M),L=!!M&&(E.get(M)??0)>1,F=s.find(q=>q.id===O.secretId)??null;return(0,t.jsxs)("div",{className:"space-y-1",children:[(0,t.jsxs)("div",{className:"grid grid-cols-(--gtc-65) items-start gap-1.5",children:[(0,t.jsx)("div",{children:(0,t.jsx)(dt,{value:O.alias,onChange:r(q=>R(O.id,{alias:q.target.value}),"onChange"),onBlur:r(q=>{const z=q.target.value.trim();if(z&&!Ez.test(z)){const K=c_(z);K&&K!==z&&R(O.id,{alias:K})}},"onBlur"),placeholder:"ALIAS","aria-label":"Access alias",disabled:i,className:W("h-9 font-mono text-sm",(Q||L)&&"border-destructive text-destructive")})}),(0,t.jsxs)("div",{className:"flex min-w-0 items-start gap-1.5",children:[(0,t.jsxs)(dr,{open:y?.rowId===O.id,onOpenChange:r(q=>{!q&&y?.rowId===O.id&&k(null)},"onOpenChange"),children:[(0,t.jsx)(ZB,{asChild:!0,children:(0,t.jsx)("div",{ref:r(q=>{q?w.current.set(O.id,q):w.current.delete(O.id)},"ref"),className:"min-w-0 flex-1",children:(0,t.jsx)(vV,{secretId:O.secretId,secrets:s,onSelect:r(q=>R(O.id,{secretId:q,version:"latest",alias:!O.alias.trim()&&q?c_(C(q)):O.alias}),"onSelect"),onCreateNew:a?q=>{window.setTimeout(()=>{k({rowId:O.id,name:SE(q)||q.trim()})},0)}:void 0,disabled:i,triggerClassName:"h-9 min-h-9"})})}),(0,t.jsx)(nr,{align:"start",className:"w-auto p-3",onInteractOutside:r(q=>{const z=q.detail.originalEvent.target;z&&w.current.get(O.id)?.contains(z)&&q.preventDefault()},"onInteractOutside"),children:y?.rowId===O.id&&a?(0,t.jsx)(E_e,{initialName:y.name,initialValue:"",existingSecretNames:s.map(q=>q.name),onCancel:r(()=>k(null),"onCancel"),onSubmit:r(async(q,z)=>{const K=await a(q,z);R(O.id,{secretId:K.id,version:"latest",alias:O.alias.trim()||c_(K.name)}),k(null)},"onSubmit")}):null})]}),(0,t.jsxs)("select",{className:"h-9 shrink-0 rounded-md border border-border bg-background px-2 text-xs outline-none disabled:cursor-not-allowed disabled:opacity-60",value:O.version===void 0?"latest":String(O.version),onChange:r(q=>{const z=q.target.value;R(O.id,{version:z==="latest"?"latest":Number.parseInt(z,10)})},"onChange"),disabled:i||!F,"aria-label":"Version",children:[(0,t.jsx)("option",{value:"latest",children:"latest"}),F?Array.from({length:Math.max(0,F.latestVersion)},(q,z)=>{const K=F.latestVersion-z;return K<=0?null:(0,t.jsxs)("option",{value:K,children:["v",K]},K)}):null]})]}),(0,t.jsx)("button",{type:"button",onClick:r(()=>I(O.id),"onClick"),disabled:i,"aria-label":"Remove API access",className:"mt-1 inline-flex size-7 shrink-0 items-center justify-center rounded-md text-muted-foreground transition-colors hover:bg-accent hover:text-foreground disabled:pointer-events-none disabled:opacity-50",children:(0,t.jsx)(ma,{className:"size-3.5"})})]}),Q?(0,t.jsx)("p",{className:"pl-0.5 text-(length:--text-micro) text-destructive",children:"Invalid alias — use letters, digits and _"}):L?(0,t.jsx)("p",{className:"pl-0.5 text-(length:--text-micro) text-destructive",children:"Duplicate alias"}):null]},O.id)})}):null,(0,t.jsxs)("button",{type:"button",onClick:T,disabled:i,className:"inline-flex items-center gap-1 rounded-md px-2 py-1 text-xs font-medium text-muted-foreground transition-colors hover:bg-accent hover:text-foreground disabled:pointer-events-none disabled:opacity-50",children:[(0,t.jsx)(bn,{className:"size-3.5"}),"Add API access"]})]}),(0,t.jsxs)("p",{className:"text-(length:--text-micro) text-muted-foreground/70",children:[out("api")," The agent reads them by alias through ",(0,t.jsx)("code",{children:"GET /agents/me/secrets"}),"."]})]})}r(yut,"AgentSecretAccessEditor");function jut(e){if(typeof e!="string")return null;const s=e.trim();return s.length>0?s:null}r(jut,"asNonEmptyString$3");function wut(e){return jut(e)!==null}r(wut,"hasLegacyWorkingDirectory");function kut(e){return e.isCreate?!1:wut(e.adapterConfig?.cwd)}r(kut,"shouldShowLegacyWorkingDirectoryField");var K_e=new Set;function Nut(e){return K_e.has(e)}r(Nut,"isAdapterTypeHidden");function Sut(e){K_e=new Set(e)}r(Sut,"setDisabledAdapterTypes");function Cut(e){return!th(e).hideFromVisualSelection}r(Cut,"isVisualAdapterChoice");function Q_e(e,s=gV()){const n=e??kf;return s.map(a=>({value:a.type,label:n(a.type),comingSoon:!!th(a.type).comingSoon,hidden:Nut(a.type),experimental:!!th(a.type).experimental}))}r(Q_e,"listAdapterOptions");function W_e(e={}){const s=e.enabled??!0,{data:n}=te({queryKey:D.adapters.all,queryFn:r(()=>Oh.list(),"queryFn"),enabled:s,staleTime:3e5});return n&&Cdt(n.filter(a=>a.source==="external").map(a=>({type:a.type,label:a.label,disabled:a.disabled,overrideDisabled:a.overridePaused}))),(0,m.useEffect)(()=>{n&&Sut(n.filter(a=>a.disabled).map(a=>a.type))},[n]),(0,m.useMemo)(()=>new Set(n?.filter(a=>a.disabled).map(a=>a.type)??[]),[n])}r(W_e,"useDisabledAdaptersSync");function _ut(e={}){const s=e.enabled??!0,{data:n}=te({queryKey:D.adapters.all,queryFn:r(()=>Oh.list(),"queryFn"),enabled:s,staleTime:3e5});return n!==void 0}r(_ut,"useAdapterRegistryLoaded");function CE(e){return Object.fromEntries(Object.entries(e).filter(([,s])=>s!==void 0))}r(CE,"omitUndefinedEntries");function II(e,s){const n={};if(Object.keys(s.identity).length>0&&Object.assign(n,s.identity),s.adapterType!==void 0&&(n.adapterType=s.adapterType),s.adapterType!==void 0||Object.keys(s.adapterConfig).length>0){const a=e.adapterConfig??{};n.adapterConfig=CE(s.adapterType!==void 0?{...Object.fromEntries(fOe.filter(i=>a[i]!==void 0).map(i=>[i,a[i]])),...s.adapterConfig}:{...a,...s.adapterConfig}),n.replaceAdapterConfig=!0}if(Object.keys(s.heartbeat).length>0||Object.keys(s.debug).length>0){const a=e.runtimeConfig??{},i=n.runtimeConfig??{...a};if(Object.keys(s.heartbeat).length>0&&(i.heartbeat={...a.heartbeat??{},...s.heartbeat}),Object.keys(s.debug).length>0){const o=CE({...a.debug??{},...s.debug});Object.keys(o).length===0?delete i.debug:i.debug=o}n.runtimeConfig=i}return Object.keys(s.runtime).length>0&&Object.assign(n,s.runtime),n}r(II,"buildAgentUpdatePatch");var Aut="kubernetes";function Iut(e){return e.driver!=="sandbox"?!1:e.config?.provider===Aut}r(Iut,"isKubernetesSandboxEnvironment");function NV(e,s){return e!=="kubernetes"?{forced:!1,kubernetesEnvironment:null}:{forced:!0,kubernetesEnvironment:s.find(n=>Iut(n))??null}}r(NV,"resolveForcedKubernetesEnvironment");var rD={identity:{},adapterConfig:{},heartbeat:{},debug:{},runtime:{}},TS={};function Tut(e){return e==="claude_local"||e==="codex_local"||e==="paperclip_runner"||e==="opencode_local"}r(Tut,"supportsAdapterModelRefresh");function Rut(e,s){return $Ce(e,s).model}r(Rut,"resolvePaperclipRunnerTransitionModel");function Xre(e){return Object.keys(e.identity).length>0||e.adapterType!==void 0||Object.keys(e.adapterConfig).length>0||Object.keys(e.heartbeat).length>0||Object.keys(e.debug).length>0||Object.keys(e.runtime).length>0}r(Xre,"isOverlayDirty");function Lz(e,s){if(Object.is(e,s))return!0;if(Array.isArray(e)&&Array.isArray(s))return e.length===s.length&&e.every((n,a)=>Lz(n,s[a]));if(typeof e=="object"&&e!==null&&!Array.isArray(e)&&typeof s=="object"&&s!==null&&!Array.isArray(s)){const n=Object.entries(e),a=s;return n.length===Object.keys(a).length&&n.every(([i,o])=>i in a&&Lz(o,a[i]))}return!1}r(Lz,"overlayValuesEqual");function Eut(e,s){const n=r((a,i)=>Object.fromEntries(Object.entries(a).filter(([o,l])=>!(o in i)||!Lz(l,i[o]))),"subtractGroup");return{identity:n(e.identity,s.identity),...e.adapterType!==void 0&&e.adapterType!==s.adapterType?{adapterType:e.adapterType}:{},adapterConfig:n(e.adapterConfig,s.adapterConfig),heartbeat:n(e.heartbeat,s.heartbeat),debug:n(e.debug,s.debug),runtime:n(e.runtime,s.runtime)}}r(Eut,"subtractPersistedOverlay");var Ch="w-full rounded-md border border-border px-2.5 py-1.5 bg-transparent outline-none text-sm font-mono placeholder:text-muted-foreground/40";function Lut(e){return e.split(",").map(s=>s.trim()).filter(Boolean)}r(Lut,"parseCommaArgs");function Mut(e){return Array.isArray(e)?e.filter(s=>typeof s=="string").join(", "):typeof e=="string"?e:""}r(Mut,"formatArgList");var Put=[{id:"",label:"Auto"},{id:"minimal",label:"Minimal"},{id:"low",label:"Low"},{id:"medium",label:"Medium"},{id:"high",label:"High"},{id:"xhigh",label:"X-High"},{id:"max",label:"Max"}],Dut=[{id:"",label:"Auto"},{id:"plan",label:"Plan"},{id:"ask",label:"Ask"}],$ut=[{id:"",label:"Auto"},{id:"low",label:"Low"},{id:"medium",label:"Medium"},{id:"high",label:"High"}],Out=[{id:"",label:"Auto"},{id:"low",label:"Low"},{id:"high",label:"High"},{id:"max",label:"Max"}],But=2,eae=10,Fut=1,H_e=300;function p6(e,s,n){return Math.max(s,Math.min(n,Math.floor(e)))}r(p6,"clampInteger");function zut(e){return p6(e,0,H_e)*1e3}r(zut,"clampDelayMsFromSeconds");function qut({order:e,className:s,children:n}){if(!e)return(0,t.jsx)("div",{className:s,children:n});const a=r(o=>{const l=(0,m.isValidElement)(o)?o.props["data-config-section"]:void 0,c=l?e.indexOf(l):-1;return c<0?e.length:c},"rank"),i=m.Children.toArray(n).sort((o,l)=>a(o)-a(l));return(0,t.jsx)("div",{className:s,children:i})}r(qut,"ConfigSections");function V_e(e){const{mode:s,adapterModels:n}=e,a=s==="create",i=e.sectionLayout==="cards",o=e.showAdapterTypeField??!0,l=e.showAdapterTestEnvironmentButton??!0,c=l&&!e.onTestActionChange&&!e.compactTestFeedback,d=!e.onTestFeedbackChange,u=e.showCreateRunPolicySection??!0,h=e.hideInstructionsFile??!1,p=e.canConfigureProviderTrace===!0,{selectedCompanyId:f}=fs(),x=wt(),g=(0,m.useRef)(null),v=W_e(),{data:y=[]}=te({queryKey:f?D.secrets.list(f):["secrets","none"],queryFn:r(()=>Rr.list(f),"queryFn"),enabled:!!f}),{data:k=[]}=te({queryKey:f?D.secrets.userDefinitions(f):["user-secret-definitions","none"],queryFn:r(()=>Rr.listUserSecretDefinitions(f),"queryFn"),enabled:!!f,retry:!1}),w=a?null:e.agent.id,{data:N=[]}=te({queryKey:f?D.secrets.proposals(f,"pending"):["secret-proposals","none"],queryFn:r(()=>Rr.listProposals(f,"pending"),"queryFn"),enabled:!!f&&!a,retry:!1}),S=(0,m.useMemo)(()=>N.filter(pt=>pt.kind==="binding"&&pt.target?.id===w),[N,w]),C=B_e(f,[]),{data:_}=te({queryKey:D.instance.experimentalSettings,queryFn:r(()=>jr.getExperimental(),"queryFn"),retry:!1}),R=(0,m.useMemo)(()=>{const pt=new Set(v);return _?.enableNativeRunner!==!0&&pt.add("paperclip_runner"),(_?.enableOpenAiDot!==!0||v.has("paperclip_runner"))&&pt.add("openai_dot"),pt},[v,_?.enableNativeRunner,_?.enableOpenAiDot]),I=_?.enableEnvironments===!0,T=_?.enableManagedSandboxOnly===!0,E=_===void 0||T,{data:P}=te({queryKey:D.instance.generalSettings,queryFn:r(()=>jr.getGeneral(),"queryFn"),retry:!1}),{data:O}=te({queryKey:D.instance.settings,queryFn:r(()=>jr.get(),"queryFn"),retry:!1}),{data:M=[]}=te({queryKey:f?D.environments.list(f):["environments","none"],queryFn:r(()=>$i.list(f),"queryFn"),enabled:!!f&&(I||P?.executionMode==="kubernetes")}),{forced:Q,kubernetesEnvironment:L}=(0,m.useMemo)(()=>NV(P?.executionMode,M),[P?.executionMode,M]),F=we({mutationFn:r(pt=>{if(!f)throw new Error("Select an organization to create secrets");return Rr.create(f,pt)},"mutationFn"),onSuccess:r(()=>{f&&x.invalidateQueries({queryKey:D.secrets.list(f)})},"onSuccess")}),q=we({mutationFn:r(async({file:pt,namespace:Is})=>{if(!f)throw new Error("Select an organization to upload images");return dv.uploadImage(f,pt,Is)},"mutationFn")}),[z,K]=(0,m.useState)(rD),[U,V]=(0,m.useState)(!1),[ne,Z]=(0,m.useState)(0),ie=(0,m.useRef)(null),J=(0,m.useRef)(null),ae=(0,m.useRef)(!1);(0,m.useEffect)(()=>{if(!a){if(ie.current!==null&&e.agent!==ie.current&&!ae.current){const pt=J.current;J.current=null,K(Is=>pt?Eut(Is,pt):{...rD})}ie.current=e.agent}},[a,a?void 0:e.agent]);const oe=!a&&(Xre(z)||U);function G(pt,Is,dn){const _n=z[pt];return Is in _n?_n[Is]:dn}r(G,"eff");function X(pt,Is,dn){K(_n=>({..._n,[pt]:{..._n[pt],[Is]:dn}}))}r(X,"mark");function Y(){return g.current?.flushPendingDraft()??null}r(Y,"flushEnvironmentDraft");const re=(0,m.useCallback)(pt=>{a||K(Is=>{const dn={...e.agent.adapterConfig??{},...Is.adapterConfig},_n={...Is.adapterConfig};for(const[fn,Sr]of Object.entries(pt))_n[`${Y3}${fn}`]=Sr;for(const fn of Object.keys(dn))fn.startsWith("access.")&&(fn.slice(7)in pt||(_n[fn]=void 0));return{...Is,adapterConfig:_n}})},[a,a?void 0:e.agent]),se=(0,m.useCallback)(()=>{K({...rD}),V(!1),Z(pt=>pt+1)},[]),ce=(0,m.useCallback)(async()=>{if(a)return;const pt=Y(),Is=pt?{...z,adapterConfig:{...z.adapterConfig,env:pt}}:z;Xre(Is)&&await e.onSave(II(e.agent,Is))},[a,oe,z,e]);(0,m.useEffect)(()=>{a||(e.onDirtyChange?.(oe),e.onSaveActionChange?.(ce),e.onCancelActionChange?.(se))},[a,oe,e.onDirtyChange,e.onSaveActionChange,e.onCancelActionChange,ce,se]),(0,m.useEffect)(()=>{if(!a)return()=>{e.onSaveActionChange?.(null),e.onCancelActionChange?.(null),e.onDirtyChange?.(!1)}},[a,e.onDirtyChange,e.onSaveActionChange,e.onCancelActionChange]);const pe=a?{}:e.agent.adapterConfig??{},fe=a?{}:e.agent.runtimeConfig??{},ve=a?{}:fe.heartbeat??{},Ie=a?{}:fe.debug??{},de=a?e.values.adapterType:z.adapterType??e.agent.adapterType,xe=Wj(),le=xe(de),Re=de==="paperclip_runner"&&(a?e.values.adapterSchemaValues?.provider:G("adapterConfig","provider",pe.provider))==="openai_dot",Le=!Re&&(le.supportsInstructionsBundle||le.supportsSkills||le.supportsLocalAgentJwt),je=Le&&!E&&kut({isCreate:a,adapterConfig:pe}),_e=(0,m.useMemo)(()=>_2(de),[de]),Ze=(0,m.useMemo)(()=>new Set(eUe(de)),[de]),ue=a?e.values:null,Fe=a?pt=>e.onChange(pt):null;a&&ue.claudeStoredSessionId;const mt=r(()=>{f&&x.invalidateQueries({queryKey:D.secrets.userDefinitions(f)})},"invalidateUserSecretDefinitions"),bt=r(pt=>{if(!a||!Fe)return;const Is=ue.envBindings??{};Fe({envBindings:{...Is,...tk()},claudeStoredSessionId:pt}),mt()},"handleClaudeLoginStored"),et=r(async()=>{if(a)return;const pt={...Y()??G("adapterConfig","env",pe.env??TS),...tk()},Is={...z,adapterConfig:{...z.adapterConfig,env:pt}};K(Is),await e.onSave({...II(e.agent,Is),applyStoredClaudeLogin:!0}),mt()},"handleClaudeLoginStoredEdit"),qe=r(async pt=>{if(a||!pt.companyIdentityDiffers)return;const Is={...Y()??G("adapterConfig","env",pe.env??TS),CODEX_HOME:{type:"secret_ref",secretId:pt.secretId,version:"latest"}},dn={...z,adapterConfig:{...z.adapterConfig,env:Is}};K(dn),J.current=dn,ae.current=!0;try{await e.onSave(II(e.agent,dn))}catch(_n){throw J.current=null,_n}finally{ae.current=!1}mt()},"handleCodexAccountBindingEdit"),it=r(()=>{if(!a||!Fe)return;const pt=ue.envBindings??{};Fe({envBindings:{...pt,...tk()},claudeApplyStoredLogin:!0}),mt()},"handleApplyStoredClaudeLogin"),_t=r(async()=>{if(a)return;const pt={...Y()??G("adapterConfig","env",pe.env??TS),...tk()},Is={...z,adapterConfig:{...z.adapterConfig,env:pt}};K(Is),await e.onSave({...II(e.agent,Is),applyStoredClaudeLogin:!0}),mt()},"handleApplyStoredClaudeLoginEdit"),$t=a?ue.defaultEnvironmentId??"":G("identity","defaultEnvironmentId",e.agent.defaultEnvironmentId??""),Ot=(0,m.useMemo)(()=>$t?(M.find(pt=>pt.id===$t)??null)?.driver==="local"?"":$t:"",[M,$t]),at=(0,m.useMemo)(()=>M.find(pt=>pt.id===Ot)??null,[Ot,M]),Me=(0,m.useMemo)(()=>{const pt=O?.defaultEnvironmentId??null;return pt?(M.find(Is=>Is.id===pt)??null)?.driver==="local"?"":pt:""},[M,O?.defaultEnvironmentId]),De=(0,m.useMemo)(()=>M.find(pt=>pt.id===Me)??null,[M,Me]),ut=(0,m.useMemo)(()=>{try{return vN({agentDefaultEnvironmentId:$t||null,instanceDefaultEnvironmentId:O?.defaultEnvironmentId??null,localDefaultEnvironmentId:jN(M),managedSandboxOnly:_?.enableManagedSandboxOnly===!0,managedSandboxEnvironmentId:yN(M),visibleEnvironmentIds:M.map(pt=>pt.id)})}catch{return null}},[$t,O?.defaultEnvironmentId,M,_?.enableManagedSandboxOnly]),Pt=(0,m.useMemo)(()=>M.find(pt=>pt.id===ut)??null,[M,ut]),{data:Rt}=te({queryKey:f?D.environments.capabilities(f):["environment-capabilities","none"],queryFn:r(()=>$i.capabilities(f),"queryFn"),enabled:!!f&&le.login!=null});(0,m.useEffect)(()=>{!a||!Fe||!Q||!L||Ot!==L.id&&Fe({defaultEnvironmentId:L.id})},[a,Fe,Q,L,Ot]);const Qe=(0,m.useMemo)(()=>M.filter(pt=>{if(!Ze.has(pt.driver)||pt.driver==="local")return!1;if(pt.driver!=="sandbox")return!0;const Is=typeof pt.config?.provider=="string"?pt.config.provider:null;return Is!==null&&Is!=="fake"}),[M,Ze]),Be=(0,m.useMemo)(()=>!at||Qe.some(pt=>pt.id===at.id)?Qe:[...Qe,at],[at,Qe]),Oe=I&&(Q||Ot.length>0||Qe.length>=1),Pe=De?wN(De):T?"Paperclip Computer":"Local",Ve=de==="paperclip_runner"?String(a?e.values.adapterSchemaValues?.provider??"codex":G("adapterConfig","provider",pe.provider==="acpx"&&pe.acpxAgent==="codex"?"codex":pe.provider??"codex")):void 0,be=de==="opencode_local"&&GB.safeParse(z.runtime.runtimeConfig?.aiConnection??fe.aiConnection).data?.provider==="openrouter"?"openrouter":Ve,nt=RCe(f,a?void 0:GB.safeParse(z.runtime.runtimeConfig?.aiConnection??fe.aiConnection).data,zee(de,Ve,G("adapterConfig","acpxAgent",pe.acpxAgent))),Lt=f?D.agents.adapterModels(f,de,Ot||null,be):["agents","none","adapter-models",de],{data:Cs,error:lt,isLoading:Os}=te({queryKey:Lt,queryFn:r(()=>Nt.adapterModels(f,de,{environmentId:Ot||null,provider:be}),"queryFn"),enabled:!!f&&!nt}),[Ke,ge]=(0,m.useState)(null),[Xe,xt]=(0,m.useState)(!1),Ht=nt?.models??Cs??n??[],ht=nt?nt.error:lt,zt="command",{data:$e,refetch:he}=te({queryKey:f?D.agents.detectModel(f,de):["agents","none","detect-model",de],queryFn:r(()=>{if(!f)throw new Error("Select an organization to detect the model");return Nt.detectModel(f,de)},"queryFn"),enabled:!!(f&&Le&&de!=="opencode_local"&&de!=="paperclip_runner")}),Vt=$e?.model??null;$e?.candidates;const{data:Dt=[]}=te({queryKey:f?D.agents.list(f):["agents","none","list"],queryFn:r(()=>Nt.list(f),"queryFn"),enabled:!!(!a&&f)}),ns={companyId:f??void 0,agentId:a?void 0:e.agent.id,mode:s,isCreate:a,adapterType:de,values:a?e.values:null,set:a?pt=>e.onChange(pt):null,config:pe,eff:G,mark:X,models:Ht,hideInstructionsFile:h||E||Re,managedSandboxOnly:E||Re,openAiDotEnabled:_?.enableOpenAiDot===!0},[_s,cn]=(0,m.useState)(!1),[mr,pn]=(0,m.useState)(!1),Bt=dV(de),Ls=r(pt=>(0,t.jsxs)(t.Fragment,{children:[de==="claude_local"&&(0,t.jsx)(aot,{...ns,section:pt}),(0,t.jsx)(_e.ConfigFields,{...ns,section:pt,hideModel:Le})]}),"renderAdapterFields"),[Ee,jt]=(0,m.useState)(!1),[ze,St]=(0,m.useState)(!1);function Ut(pt){if(a){const dn=_e.buildAdapterConfig(ue);return pt&&Object.assign(dn,pt),CE(dn)}const Is={...pe,...z.adapterConfig};return pt&&Object.assign(Is,pt),CE(Is)}r(Ut,"buildAdapterConfigForTest");const Ct=we({mutationFn:r(async()=>{if(!f)throw new Error("Select an organization to test adapter environment");const pt=Y(),Is=pt?{env:pt}:void 0;let dn=O,_n=M,fn=_?.enableManagedSandboxOnly===!0;if(!$t)try{const[ln,Tr,Zn]=await Promise.all([x.ensureQueryData({queryKey:D.instance.settings,queryFn:r(()=>jr.get(),"queryFn")}),x.ensureQueryData({queryKey:D.environments.list(f),queryFn:r(()=>$i.list(f),"queryFn")}),x.ensureQueryData({queryKey:D.instance.experimentalSettings,queryFn:r(()=>jr.getExperimental(),"queryFn")})]);dn=ln,_n=Tr,fn=Zn?.enableManagedSandboxOnly===!0}catch{throw new Error("Could not load environment settings to determine which environment to test in. Retry the test.")}const Sr=vN({agentDefaultEnvironmentId:$t||null,instanceDefaultEnvironmentId:dn?.defaultEnvironmentId??null,localDefaultEnvironmentId:jN(_n),managedSandboxOnly:fn,managedSandboxEnvironmentId:yN(_n),visibleEnvironmentIds:_n.map(ln=>ln.id)}),ia=Ut(Is),Da=a?void 0:e.agent.id,Ts=a?void 0:Bee.safeParse(z.runtime.runtimeConfig?.aiConnection??e.agent.runtimeConfig.aiConnection).data;if(e.compactTestFeedback){const ln=de==="paperclip_runner"?ia.provider==="codex"?"codex_local":ia.provider==="acpx"&&ia.acpxAgent==="grok"?"grok_local":ia.provider==="acpx"&&ia.acpxAgent==="claude"?"claude_local":de:de;return ECe({companyId:f,adapterType:de,providerAdapter:ln,adapterConfig:ia,agentId:Da,aiConnection:Ts,environmentId:Sr})}return Nt.testEnvironment(f,de,{adapterConfig:ia,agentId:Da,aiConnection:Ts,environmentId:Sr})},"mutationFn")}),[os,vs]=(0,m.useState)(!1),[Bs,qs]=(0,m.useState)(null),Rn="Test",Ns=!a&&!!e.isSaving,Yn=os||Ns||!f,Xt=(0,m.useRef)(Ct.reset);Xt.current=Ct.reset;const Hs=(0,m.useRef)(()=>{});Hs.current=()=>{if(!a||!Fe)return;const pt=ue.envBindings??{},Is=ue.claudeStoredSessionId!=null||ue.claudeApplyStoredLogin===!0,dn=Ure in pt;if(!Is&&!dn)return;const _n={...pt};delete _n[Ure],Fe({envBindings:_n,claudeStoredSessionId:null,claudeApplyStoredLogin:!1})},(0,m.useEffect)(()=>{Xt.current(),qs(null),Hs.current()},[de,ut]);const on=le.login!=null,Tt=Ct.data,as=Tt!=null&&xe(Tt.adapterType).login!=null,Xs=Tt&&as?Tt.checks.find(pt=>pt.code==="adapter_auth_missing")??null:null,bs=typeof Pt?.config?.provider=="string"?Pt.config.provider:null,Zs=bs!=null&&Rt?.sandboxProviders?.[bs]?.supportsLoginPty===!0,Nn=le.login!=null,hr=(a||!(z.runtime.runtimeConfig?.aiConnection??fe.aiConnection))&&on&&Pt?.driver==="sandbox"&&!!ut&&!!f&&!!Xs&&(!Nn||Zs),qn=(0,m.useCallback)(async()=>{if(!f)throw new Error("Select an organization to test adapter environment");vs(!0),qs(null),Ct.reset();try{return await Ct.mutateAsync()}catch(pt){throw qs(pt instanceof Error?pt.message:"Environment test failed"),pt}finally{vs(!1)}},[f,Ct]),qr=(0,m.useRef)(()=>{});(0,m.useEffect)(()=>{qr.current=()=>{Yn||qn().catch(()=>{})}},[qn,Yn]);const Cr=(0,m.useCallback)(()=>{qr.current()},[]);(0,m.useEffect)(()=>{if(!(!l||!e.onTestActionChange))return e.onTestActionChange(Cr),()=>{e.onTestActionChange?.(null)}},[l,e.onTestActionChange,Cr]),(0,m.useEffect)(()=>{if(!(!l||!e.onTestActionStateChange))return e.onTestActionStateChange({disabled:Yn,pending:os}),()=>{e.onTestActionStateChange?.({disabled:!0,pending:!1})}},[l,e.onTestActionStateChange,Yn,os]),(0,m.useEffect)(()=>{if(e.onTestFeedbackChange)return e.onTestFeedbackChange({errorMessage:Bs??(Ct.error instanceof Error?Ct.error.message:Ct.error?"Environment test failed":null),result:Ct.data??null,login:hr&&f&&ut?{companyId:f,adapterType:de,environmentId:ut}:null}),()=>{e.onTestFeedbackChange?.({errorMessage:null,result:null,login:null})}},[e.onTestFeedbackChange,Bs,Ct.data,Ct.error,hr,f,de,ut]);const pr=a?ue.model??"":G("adapterConfig","model",String(pe.model??"")),Cn=typeof pr=="string"?pr:"";async function Nr(){if(f){xt(!0),ge(null);try{const pt=await Nt.adapterModels(f,de,{refresh:!0,environmentId:Ot||null,provider:be});x.setQueryData(Lt,pt)}catch(pt){ge(pt instanceof Error?pt.message:"Failed to refresh adapter models.")}finally{xt(!1)}}}r(Nr,"handleRefreshModels");const Or=de==="codex_local"?"modelReasoningEffort":de==="cursor"?"mode":de==="opencode_local"?"variant":de==="grok_local"?"reasoningEffort":de==="pi_local"||de==="omp_local"?"thinking":"effort",Ur=de==="codex_local"?iV(Cn,"Auto").map(pt=>({id:pt.value,label:pt.label})):de==="cursor"?Dut:de==="opencode_local"?Put:de==="kimi_local"?Out:de==="pi_local"?[{id:"",label:"Auto"},...["off","minimal","low","medium","high","xhigh"].map(pt=>({id:pt,label:pt}))]:de==="claude_local"||de==="grok_local"?[{id:"",label:"Auto"},...vE(de,Cn).map(pt=>({id:pt,label:pt==="xhigh"?"X-High":pt[0].toUpperCase()+pt.slice(1)}))]:$ut,ga=de==="omp_local",ar=a?ga?String(ue.adapterSchemaValues?.thinking??""):ue.thinkingEffort:de==="codex_local"?G("adapterConfig","modelReasoningEffort",String(pe.modelReasoningEffort??pe.reasoningEffort??"")):de==="cursor"?G("adapterConfig","mode",String(pe.mode??"")):de==="opencode_local"?G("adapterConfig","variant",String(pe.variant??"")):G("adapterConfig",Or,String(pe[Or]??"")),ur=de!=="gemini_local"&&de!=="cursor_cloud"&&de!=="paperclip_runner"&&!ga,gt=r(pt=>{if(a){Fe(ga?{adapterSchemaValues:{...ue.adapterSchemaValues,thinking:pt??void 0}}:{thinkingEffort:pt??""});return}X("adapterConfig",Or,pt||void 0)},"setThinkingEffort"),Ge=de==="codex_local"?a?!!ue.search:G("adapterConfig","search",!!pe.search):!1,es=(0,m.useMemo)(()=>{if(a)return{heartbeat:{enabled:ue.heartbeatEnabled,intervalSec:ue.intervalSec}};const pt={...fe.heartbeat&&typeof fe.heartbeat=="object"?fe.heartbeat:{},...z.heartbeat};return{...fe,heartbeat:pt}},[a,z.heartbeat,fe,ue]),hs=Tee(es.heartbeat),As=Tee(hs.maxTurnContinuation),ss=J$e(As.enabled,!0),ks=p6(kee(As.maxAttempts,But),0,eae),kn=p6(kee(As.delayMs,Fut*1e3)/1e3,0,H_e);function vn(pt){X("heartbeat","maxTurnContinuation",{...As,...pt})}r(vn,"updateMaxTurnContinuation");const Un=(0,t.jsx)(kj,{ref:g,onDirtyChange:V,hideDraftActions:!a&&e.hideInlineSave,value:a?ue.envBindings??TS:G("adapterConfig","env",pe.env??TS),secrets:y,userSecretDefinitions:k,onCreateSecret:r(async(pt,Is)=>await F.mutateAsync({name:pt,value:Is}),"onCreateSecret"),onChange:r(pt=>a?Fe({envBindings:pt??{},envVars:""}):X("adapterConfig","env",pt),"onChange")},ne);return!a&&e.content==="secrets"?(0,t.jsxs)("div",{className:W("relative",i&&"space-y-6"),children:[oe&&!e.hideInlineSave&&(0,t.jsx)("div",{className:"sticky top-0 z-10 flex items-center justify-end border-b border-primary/20 bg-background/90 px-4 py-2 backdrop-blur-sm",children:(0,t.jsxs)("div",{className:"flex items-center gap-3",children:[(0,t.jsx)("span",{className:"text-xs text-muted-foreground",children:"Unsaved changes"}),(0,t.jsx)($,{size:"sm",onClick:ce,disabled:e.isSaving,children:e.isSaving?"Saving...":"Save"})]})}),e.environmentVariablesPlacement==="secrets"&&(0,t.jsxs)("div",{"data-config-section":"environment-variables",className:W(!i&&"border-b border-border"),children:[i?(0,t.jsx)("h3",{className:"mb-3 text-sm font-medium",children:"Environment variables"}):(0,t.jsx)("div",{className:"px-4 py-2 text-xs font-medium text-muted-foreground",children:"Environment variables"}),(0,t.jsx)("div",{className:W(i?"rounded-lg border border-border p-4":"px-4 pb-3"),children:Un})]}),(0,t.jsxs)("div",{"data-config-section":"secrets",className:W(!i&&"border-b border-border"),children:[i?(0,t.jsx)("h3",{className:"mb-3 text-sm font-medium",children:"Secret access"}):(0,t.jsx)("div",{className:"px-4 py-2 text-xs font-medium text-muted-foreground",children:"Secret access"}),(0,t.jsxs)("div",{className:W(i?"space-y-3 rounded-lg border border-border p-4":"space-y-3 px-4 pb-3"),children:[(0,t.jsx)("p",{className:"text-xs text-muted-foreground",children:wi.secretAccess}),(0,t.jsx)(yut,{config:{...pe,...z.adapterConfig},secrets:y,onChange:re,onCreateSecret:r((pt,Is)=>F.mutateAsync({name:pt,value:Is}),"onCreateSecret"),proposals:S,onApproveProposal:C.requestApprove,onRejectProposal:C.requestReject}),C.dialogs]})]})]}):(0,t.jsxs)(qut,{order:e.sectionOrder,className:W("relative",i&&"space-y-6"),children:[oe&&!e.hideInlineSave&&(0,t.jsx)("div",{className:"sticky top-0 z-10 flex items-center justify-end px-4 py-2 bg-background/90 backdrop-blur-sm border-b border-primary/20",children:(0,t.jsxs)("div",{className:"flex items-center gap-3",children:[(0,t.jsx)("span",{className:"text-xs text-muted-foreground",children:"Unsaved changes"}),(0,t.jsx)($,{size:"sm",onClick:ce,disabled:!a&&e.isSaving,children:!a&&e.isSaving?"Saving...":"Save"})]})}),!a&&(0,t.jsxs)("div",{"data-config-section":"identity",className:W(!i&&"border-b border-border"),children:[i?(0,t.jsx)("h3",{className:"text-sm font-medium mb-3",children:e.sectionTitles?.identity??"Identity"}):(0,t.jsx)("div",{className:"px-4 py-2 text-xs font-medium text-muted-foreground",children:"Identity"}),(0,t.jsxs)("div",{className:W(i?"border border-border rounded-lg p-4 space-y-3":"px-4 pb-3 space-y-3"),children:[(0,t.jsx)(Ss,{label:"Name",hint:wi.name,children:(0,t.jsx)(Wa,{value:G("identity","name",e.agent.name),onCommit:r(pt=>X("identity","name",pt),"onCommit"),immediate:!0,className:Ch,placeholder:"Agent name"})}),(0,t.jsx)(Ss,{label:"Title",hint:wi.title,children:(0,t.jsx)(Wa,{value:G("identity","title",e.agent.title??""),onCommit:r(pt=>X("identity","title",pt||null),"onCommit"),immediate:!0,className:Ch,placeholder:"e.g. VP of Engineering"})}),(0,t.jsx)(Ss,{label:"Reports to",hint:wi.reportsTo,children:(0,t.jsx)(Edt,{agents:Dt,value:G("identity","reportsTo",e.agent.reportsTo??null),onChange:r(pt=>X("identity","reportsTo",pt),"onChange"),excludeAgentIds:[e.agent.id],chooseLabel:"Choose manager…"})}),Le&&!e.hidePromptTemplate&&(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)(Ss,{label:"Prompt Template",hint:wi.promptTemplate,children:(0,t.jsx)(Xc,{value:G("adapterConfig","promptTemplate",String(pe.promptTemplate??"")),onChange:r(pt=>X("adapterConfig","promptTemplate",pt??""),"onChange"),placeholder:"You are agent {{ agent.name }}. Your role is {{ agent.role }}...",contentClassName:"min-h-(--sz-88px) text-sm font-mono",imageUploadHandler:r(async pt=>{const Is=`agents/${e.agent.id}/prompt-template`;return(await q.mutateAsync({file:pt,namespace:Is})).contentPath},"imageUploadHandler")})}),(0,t.jsx)("div",{className:"rounded-md border border-amber-500/25 bg-amber-500/10 px-3 py-2 text-xs text-amber-900 dark:text-amber-100",children:"Prompt template is replayed on every heartbeat. Keep it compact and dynamic to avoid recurring token cost and cache churn."})]})]})]}),Q?(0,t.jsxs)("div",{"data-config-section":"environment",className:W(!i&&(a?"border-t border-border":"border-b border-border")),children:[i?(0,t.jsx)("h3",{className:"text-sm font-medium mb-3",children:"Environment"}):(0,t.jsx)("div",{className:"px-4 py-2 text-xs font-medium text-muted-foreground",children:"Environment"}),(0,t.jsx)("div",{className:W(i?"border border-border rounded-lg p-4 space-y-3":"px-4 pb-3 space-y-3"),children:(0,t.jsx)(Ss,{label:"Default environment",hint:"This instance runs all agents in the Kubernetes sandbox. Local execution is disabled.",children:L?(0,t.jsxs)("div",{className:W(Ch,"flex items-center text-muted-foreground"),children:[L.name," · Kubernetes sandbox"]}):(0,t.jsx)("div",{className:"rounded-md border border-amber-500/25 bg-amber-500/10 px-3 py-2 text-xs text-amber-800 dark:text-amber-200",children:"This instance requires the Kubernetes sandbox, but no managed Kubernetes environment is available for this organization yet. Configure one before creating agents; execution will not fall back to local."})})})]}):Oe?(0,t.jsxs)("div",{"data-config-section":"environment",className:W(!i&&(a?"border-t border-border":"border-b border-border")),children:[i?(0,t.jsx)("h3",{className:"text-sm font-medium mb-3",children:"Environment"}):(0,t.jsx)("div",{className:"px-4 py-2 text-xs font-medium text-muted-foreground",children:"Environment"}),(0,t.jsx)("div",{className:W(i?"border border-border rounded-lg p-4 space-y-3":"px-4 pb-3 space-y-3"),children:(0,t.jsx)(Ss,{label:"Environment override",children:(0,t.jsx)("div",{className:"space-y-2",children:(0,t.jsxs)("select",{className:Ch,value:Ot,onChange:r(pt=>{const Is=pt.target.value;if(a){Fe({defaultEnvironmentId:Is});return}X("identity","defaultEnvironmentId",Is||null)},"onChange"),children:[(0,t.jsxs)("option",{value:"",children:["Default: ",Pe]}),Be.map(pt=>(0,t.jsx)("option",{value:pt.id,children:wN(pt)},pt.id))]})})})})]}):null,(0,t.jsxs)("div",{"data-config-section":"adapter",className:W(!i&&(a?"border-t border-border":"border-b border-border")),children:[(0,t.jsxs)("div",{className:W(i?"flex items-center justify-between mb-3":"px-4 py-2 flex items-center justify-between gap-2"),children:[i?(0,t.jsx)("h3",{className:"text-sm font-medium",children:e.sectionTitles?.adapter??"Adapter"}):(0,t.jsx)("span",{className:"text-xs font-medium text-muted-foreground",children:"Adapter"}),c&&(0,t.jsx)($,{type:"button",variant:"outline",size:"sm",className:"h-7 px-2.5 text-xs",onClick:Cr,disabled:Yn,children:os?`${Rn}...`:Rn})]}),(0,t.jsxs)("div",{className:W(i?"border border-border rounded-lg p-4 space-y-3":"px-4 pb-3 space-y-3"),children:[o&&(0,t.jsx)(Ss,{label:"Adapter type",hint:wi.adapterType,children:(0,t.jsx)(Y_e,{value:Re?"openai_dot":de,disabledTypes:R,openAiDotEnabled:_?.enableOpenAiDot===!0,onChange:r(pt=>{const Is=pt==="openai_dot",dn=Is?"paperclip_runner":pt;if(a){const{adapterType:_n,...fn}=Ab,Sr={...fn,adapterType:dn};dn==="codex_local"?Sr.dangerouslyBypassSandbox=!0:dn==="gemini_local"?Sr.model="auto":dn==="kimi_local"?Sr.model="kimi-code/kimi-for-coding":dn==="cursor"?Sr.model="auto":dn==="opencode_local"?Sr.model="openai/gpt-5.2-codex":dn==="paperclip_runner"&&(Sr.model=bN),Is&&(Sr.model="",Sr.adapterSchemaValues={provider:"openai_dot"}),Fe(Sr)}else K(_n=>({..._n,adapterType:dn,adapterConfig:{model:dn==="gemini_local"?"auto":dn==="kimi_local"?"kimi-code/kimi-for-coding":dn==="opencode_local"?"openai/gpt-5.2-codex":dn==="cursor"?"auto":Is?"":dn==="paperclip_runner"?Rut(de,pe.model):"",effort:"",modelReasoningEffort:"",variant:"",mode:"",...dn==="codex_local"?{dangerouslyBypassApprovalsAndSandbox:!0}:Is?{provider:"openai_dot",lifecycleMode:"per_turn",allowUnmeteredProvider:!1,dotAttachmentAccess:!1,dotWorkspaceAccess:!1}:dn==="paperclip_runner"?{...$Ce(de,G("adapterConfig","model",pe.model))}:{}}}))},"onChange")})}),!Re&&!a&&f&&(0,t.jsx)(pz,{companyId:f,agentId:e.agent.id,agentName:e.agent.name,adapterType:zee(de,G("adapterConfig","provider",pe.provider),G("adapterConfig","acpxAgent",pe.acpxAgent)),routerAdapterType:de,value:Bee.safeParse(z.runtime.runtimeConfig?.aiConnection??fe.aiConnection).data,model:String(G("adapterConfig","model",pe.model)??""),environmentId:Ot||void 0,legacy:!0,onChange:r(pt=>X("runtime","runtimeConfig",{...fe,aiConnection:pt}),"onChange")}),d&&!e.compactTestFeedback&&(Bs||Ct.error)&&(0,t.jsx)("div",{className:"rounded-md border border-destructive/30 bg-destructive/10 px-3 py-2 text-xs text-destructive",children:Bs??(Ct.error instanceof Error?Ct.error.message:"Environment test failed")}),d&&!e.compactTestFeedback&&Ct.data&&(0,t.jsx)(Gut,{result:Ct.data}),d&&hr&&(0,t.jsx)(SV,{companyId:f,adapterType:de,environmentId:ut,onStored:a?bt:et,onApplyStored:a?it:_t,onAccountBinding:a?void 0:qe},`${de}:${ut}`),je&&(0,t.jsx)(Ss,{label:"Working directory (deprecated)",hint:wi.cwd,children:(0,t.jsxs)("div",{className:"flex items-center gap-2 rounded-md border border-border px-2.5 py-1.5",children:[(0,t.jsx)(nl,{className:"h-3.5 w-3.5 text-muted-foreground shrink-0"}),(0,t.jsx)(Wa,{value:a?ue.cwd:G("adapterConfig","cwd",String(pe.cwd??"")),onCommit:r(pt=>a?Fe({cwd:pt}):X("adapterConfig","cwd",pt||void 0),"onCommit"),immediate:!0,className:"w-full bg-transparent outline-none text-sm font-mono placeholder:text-muted-foreground/40",placeholder:"/path/to/project"}),(0,t.jsx)(nu,{})]})}),Ls("adapter"),Le&&(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)(CV,{models:Ht,loadingModels:nt?.isLoading??Os,value:Cn,effort:ga?{value:ar||null,onChange:gt}:void 0,onChange:r(pt=>{ga&&!hM(ar,pt,Ht.map(_n=>Ik(_n,!1)))&&gt(null);const Is=vE(de,pt),dn=["codex_local","claude_local","grok_local"].includes(de)&&!!ar&&!Is.includes(String(ar));if(a){Fe({model:pt,...dn?{thinkingEffort:""}:{}});return}X("adapterConfig","model",nt?.resolveModel(pt)||pt||void 0),dn&&(X("adapterConfig",Or,void 0),X("adapterConfig","reasoningEffort",void 0))},"onChange"),open:Ee,onOpenChange:jt,defaultLabel:de==="claude_local"?"Default (claude-opus-5)":void 0,allowDefault:de!=="opencode_local"&&de!=="pi_local"&&de!=="paperclip_runner",required:de==="opencode_local"||de==="pi_local",groupByProvider:!nt&&(de==="opencode_local"||de==="pi_local"),preserveOrder:!!nt||lV(de),creatable:!0,detectedModel:nt?void 0:Vt,detectedModelCandidates:[],onDetectModel:nt||de==="opencode_local"||de==="paperclip_runner"?void 0:async()=>(await he()).data?.model??null,onRefreshModels:nt?nt.refreshModels:Tut(de)?Nr:void 0,refreshingModels:nt?.refreshing??Xe,detectModelLabel:"Detect model",emptyDetectHint:"No model detected. Select or enter one manually."}),(Ke||ht)&&(0,t.jsx)("p",{className:"text-xs text-destructive",children:Ke??(ht instanceof Error?ht.message:"Failed to load adapter models.")}),de==="opencode_local"&&!nt&&at&&at.driver!=="local"&&(0,t.jsxs)("p",{className:"text-xs text-muted-foreground",children:["Live OpenCode model discovery only runs for Local environments. Using the curated list and manual entry for ",at.name,"."]}),ur&&(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)(Yut,{value:ar,options:Ur,onChange:r(pt=>a?Fe({thinkingEffort:pt}):X("adapterConfig",Or,pt||void 0),"onChange"),open:ze,onOpenChange:St}),de==="codex_local"&&Ge&&ar==="minimal"&&(0,t.jsx)("p",{className:"text-xs text-amber-400",children:"Codex may reject `minimal` thinking when search is enabled."})]})]})]})]}),(0,t.jsxs)("div",{"data-config-section":"configuration",className:W(!i&&"border-b border-border"),children:[i?(0,t.jsx)("h3",{className:"text-sm font-medium mb-3",children:"Configuration"}):(0,t.jsx)("div",{className:"px-4 py-2 text-xs font-medium text-muted-foreground",children:"Configuration"}),(0,t.jsxs)("div",{className:W(i?"border border-border rounded-lg p-4 space-y-3":"px-4 pb-3 space-y-3"),children:[!a&&typeof pe.bootstrapPromptTemplate=="string"&&pe.bootstrapPromptTemplate&&(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)(Ss,{label:"Bootstrap prompt (legacy)",hint:wi.bootstrapPrompt,children:(0,t.jsx)(Xc,{value:G("adapterConfig","bootstrapPromptTemplate",String(pe.bootstrapPromptTemplate??"")),onChange:r(pt=>X("adapterConfig","bootstrapPromptTemplate",pt||void 0),"onChange"),placeholder:"Optional initial setup prompt for the first run",contentClassName:"min-h-(--sz-44px) text-sm font-mono",imageUploadHandler:r(async pt=>{const Is=`agents/${e.agent.id}/bootstrap-prompt`;return(await q.mutateAsync({file:pt,namespace:Is})).contentPath},"imageUploadHandler")})}),(0,t.jsx)("div",{className:"rounded-md border border-amber-500/25 bg-amber-500/10 px-3 py-2 text-xs text-amber-800 dark:text-amber-200",children:"Bootstrap prompt is legacy and will be removed in a future release. Consider moving this content into the agent's prompt template or instructions file instead."})]}),Ls("configuration"),(Le||de==="process"||Bt?.fields.some(pt=>bz(pt.key)==="advanced"))&&(0,t.jsx)(o6,{title:"Advanced",open:mr,onToggle:r(()=>pn(!mr),"onToggle"),children:(0,t.jsxs)("div",{className:"space-y-3",children:[Le&&(0,t.jsxs)(t.Fragment,{children:[" ",!E&&(0,t.jsx)(Ss,{label:"Command",hint:wi.localCommand,children:(0,t.jsx)(Wa,{value:a?ue.command:G("adapterConfig",zt,String(pe.command??"")),onCommit:r(pt=>a?Fe({command:pt}):X("adapterConfig",zt,pt||null),"onCommit"),immediate:!0,className:Ch,placeholder:{claude_local:"claude",codex_local:"codex",gemini_local:"gemini",kimi_local:"kimi",pi_local:"pi",cursor:"agent",opencode_local:"opencode"}[de]??de.replace(/_local$/,"")})}),(0,t.jsx)(Ss,{label:"Extra args (comma-separated)",hint:wi.extraArgs,children:(0,t.jsx)(Wa,{value:a?ue.extraArgs:G("adapterConfig","extraArgs",Mut(pe.extraArgs)),onCommit:r(pt=>a?Fe({extraArgs:pt}):X("adapterConfig","extraArgs",pt?.trim()?Lut(pt):null),"onCommit"),className:Ch,placeholder:"e.g. --verbose, --foo=bar"})})]}),Ls("advanced")]})})]})]}),e.environmentVariablesPlacement!=="secrets"&&(Le||Bt?.fields.some(pt=>bz(pt.key)==="environment"))&&(0,t.jsxs)("div",{"data-config-section":"environment-variables",className:W(!i&&"border-b border-border"),children:[i?(0,t.jsx)("h3",{className:"text-sm font-medium mb-3",children:"Environment variables"}):(0,t.jsx)("div",{className:"px-4 py-2 text-xs font-medium text-muted-foreground",children:"Environment variables"}),(0,t.jsx)("div",{className:W(i?"border border-border rounded-lg p-4 space-y-3":"px-4 pb-3 space-y-3"),children:Le?Un:Ls("environment")})]}),a&&u?(0,t.jsxs)("div",{"data-config-section":"run-policy",className:W(!i&&"border-b border-border"),children:[i?(0,t.jsxs)("h3",{className:"text-sm font-medium flex items-center gap-2 mb-3",children:[(0,t.jsx)(fC,{className:"h-3 w-3"})," Run Policy"]}):(0,t.jsxs)("div",{className:"px-4 py-2 text-xs font-medium text-muted-foreground flex items-center gap-2",children:[(0,t.jsx)(fC,{className:"h-3 w-3"})," Run Policy"]}),(0,t.jsxs)("div",{className:W(i?"border border-border rounded-lg p-4 space-y-3":"px-4 pb-3 space-y-3"),children:[(0,t.jsx)(fre,{label:"Heartbeat on interval",hint:wi.heartbeatInterval,checked:ue.heartbeatEnabled,onCheckedChange:r(pt=>Fe({heartbeatEnabled:pt}),"onCheckedChange"),number:ue.intervalSec,onNumberChange:r(pt=>Fe({intervalSec:pt}),"onNumberChange"),numberLabel:"sec",numberPrefix:"Run heartbeat every",numberHint:wi.intervalSec,showNumber:ue.heartbeatEnabled}),(0,t.jsx)(o6,{title:"Advanced Run Policy",open:_s,onToggle:r(()=>cn(!_s),"onToggle"),children:(0,t.jsx)("div",{className:"space-y-3",children:Ls("runPolicy")})})]})]}):a?null:(0,t.jsxs)("div",{"data-config-section":"run-policy",className:W(!i&&"border-b border-border"),children:[i?(0,t.jsxs)("h3",{className:"text-sm font-medium flex items-center gap-2 mb-3",children:[(0,t.jsx)(fC,{className:"h-3 w-3"})," Run Policy"]}):(0,t.jsxs)("div",{className:"px-4 py-2 text-xs font-medium text-muted-foreground flex items-center gap-2",children:[(0,t.jsx)(fC,{className:"h-3 w-3"})," Run Policy"]}),(0,t.jsxs)("div",{className:W(i?"border border-border rounded-lg overflow-hidden":""),children:[(0,t.jsx)("div",{className:W(i?"p-4 space-y-3":"px-4 pb-3 space-y-3"),children:(0,t.jsx)(fre,{label:"Heartbeat on interval",hint:wi.heartbeatInterval,checked:G("heartbeat","enabled",ve.enabled===!0),onCheckedChange:r(pt=>X("heartbeat","enabled",pt),"onCheckedChange"),number:G("heartbeat","intervalSec",Number(ve.intervalSec??300)),onNumberChange:r(pt=>X("heartbeat","intervalSec",pt),"onNumberChange"),numberLabel:"sec",numberPrefix:"Run heartbeat every",numberHint:wi.intervalSec,showNumber:G("heartbeat","enabled",ve.enabled===!0)})}),(0,t.jsx)(o6,{title:"Advanced Run Policy",bordered:i,open:_s,onToggle:r(()=>cn(!_s),"onToggle"),children:(0,t.jsxs)("div",{className:"space-y-3",children:[Ls("runPolicy"),Le&&(0,t.jsx)(t.Fragment,{children:!a&&(0,t.jsxs)(t.Fragment,{children:[!Bt?.fields.some(pt=>pt.key==="timeoutSec")&&(0,t.jsx)(Ss,{label:"Timeout (sec)",hint:wi.timeoutSec,children:(0,t.jsx)(Wc,{value:G("adapterConfig","timeoutSec",Number(pe.timeoutSec??0)),onCommit:r(pt=>X("adapterConfig","timeoutSec",pt),"onCommit"),immediate:!0,className:Ch})}),!Bt?.fields.some(pt=>pt.key==="graceSec")&&(0,t.jsx)(Ss,{label:"Interrupt grace period (sec)",hint:wi.graceSec,children:(0,t.jsx)(Wc,{value:G("adapterConfig","graceSec",Number(pe.graceSec??15)),onCommit:r(pt=>X("adapterConfig","graceSec",pt),"onCommit"),immediate:!0,className:Ch})})]})}),(0,t.jsx)(yl,{label:"Wake on demand",hint:wi.wakeOnDemand,checked:G("heartbeat","wakeOnDemand",ve.wakeOnDemand!==!1),onChange:r(pt=>X("heartbeat","wakeOnDemand",pt),"onChange")}),(0,t.jsx)(Ss,{label:"Cooldown (sec)",hint:wi.cooldownSec,children:(0,t.jsx)(Wc,{value:G("heartbeat","cooldownSec",Number(ve.cooldownSec??10)),onCommit:r(pt=>X("heartbeat","cooldownSec",pt),"onCommit"),immediate:!0,className:Ch})}),(0,t.jsx)(Ss,{label:"Max concurrent runs",hint:wi.maxConcurrentRuns,children:(0,t.jsx)(Wc,{value:G("heartbeat","maxConcurrentRuns",Number(ve.maxConcurrentRuns??20)),onCommit:r(pt=>X("heartbeat","maxConcurrentRuns",pt),"onCommit"),immediate:!0,className:Ch})}),(0,t.jsxs)("div",{className:"rounded-md border border-border/70 px-3 py-2",children:[(0,t.jsx)(yl,{label:"Continue after max-turn stop",hint:wi.maxTurnContinuationEnabled,checked:ss,onChange:r(pt=>vn({enabled:pt}),"onChange")}),ss?(0,t.jsxs)("div",{className:"mt-3 grid gap-3 sm:grid-cols-2",children:[(0,t.jsx)(Ss,{label:"Continuation attempts",hint:wi.maxTurnContinuationMaxAttempts,children:(0,t.jsx)(Wc,{value:ks,onCommit:r(pt=>vn({maxAttempts:p6(pt,0,eae)}),"onCommit"),immediate:!0,className:Ch})}),(0,t.jsx)(Ss,{label:"Continuation delay (sec)",hint:wi.maxTurnContinuationDelaySec,children:(0,t.jsx)(Wc,{value:kn,onCommit:r(pt=>vn({delayMs:zut(pt)}),"onCommit"),immediate:!0,className:Ch})})]}):null]})]})})]})]}),!a&&p?(0,t.jsxs)("div",{className:W(!i&&"border-b border-border"),children:[i?(0,t.jsxs)("h3",{className:"mb-3 flex items-center gap-2 text-sm font-medium",children:[(0,t.jsx)(Ky,{className:"h-3 w-3"})," Debugging"]}):(0,t.jsxs)("div",{className:"flex items-center gap-2 px-4 py-2 text-xs font-medium text-muted-foreground",children:[(0,t.jsx)(Ky,{className:"h-3 w-3"})," Debugging"]}),(0,t.jsxs)("div",{className:W("border-border bg-accent/30",i?"rounded-lg border p-4":"mx-4 mb-4 rounded-md border px-3 py-3"),children:[(0,t.jsx)(yl,{label:"Capture raw provider traces",hint:"Stores exact provider traffic for every future run until disabled. Traces may contain sensitive prompts and tool arguments, are administrator-only, and expire after 24 hours.",checked:G("debug","providerTrace",Ie.providerTrace)==="raw",onChange:r(pt=>X("debug","providerTrace",pt?"raw":void 0),"onChange")}),G("debug","providerTrace",Ie.providerTrace)==="raw"?(0,t.jsxs)("div",{className:"mt-3 flex items-start gap-2 rounded-md border border-border bg-background/60 px-3 py-2 text-xs text-foreground",children:[(0,t.jsx)(Ky,{className:"mt-0.5 h-3.5 w-3.5 shrink-0"}),(0,t.jsx)("span",{children:"Raw tracing is on for future runs. Paperclip keeps at most 64 MiB per run and automatically deletes it after 24 hours."})]}):null]})]}):null,e.compactTestFeedback&&d&&l&&(0,t.jsx)(KCe,{variant:Re?"prerequisites":"connection",state:os?"running":Bs||Ct.error?"fail":Tt?.status??"idle",result:Tt??null,error:Bs??(Ct.error instanceof Error?Ct.error.message:null),onTest:Cr,disabled:Yn})]})}r(V_e,"AgentConfigForm");var Mz=new Set(["authenticated","failed","timed_out","cancelled"]),Pz=2e3;function Dz({value:e,label:s}){const[n,a]=(0,m.useState)(!1),i=(0,m.useRef)(null);return(0,m.useEffect)(()=>()=>{i.current&&clearTimeout(i.current)},[]),(0,t.jsx)($,{type:"button",variant:"ghost",size:"icon-xs","aria-label":s,title:s,className:"text-muted-foreground hover:text-foreground",onClick:r(async()=>{try{await wa(e),a(!0)}catch{a(!1)}i.current&&clearTimeout(i.current),i.current=setTimeout(()=>a(!1),1500)},"onClick"),children:n?(0,t.jsx)(ms,{className:"size-3"}):(0,t.jsx)(br,{className:"size-3"})})}r(Dz,"AdapterLoginCopyButton");function Uut({status:e,message:s}){return e==="authenticated"?(0,t.jsxs)("div",{className:"flex items-center gap-2 text-(length:--text-micro) text-foreground",children:[(0,t.jsx)(ms,{className:"size-3 shrink-0"}),(0,t.jsx)("span",{children:"Authenticated. The environment has credentials now."})]}):(0,t.jsxs)("div",{className:"flex items-start gap-2 text-(length:--text-micro) text-destructive",children:[(0,t.jsx)(Es,{className:"size-3 shrink-0"}),(0,t.jsxs)("span",{children:[e==="timed_out"?"Login timed out":e==="cancelled"?"Login cancelled":"Login failed",s?`: ${s}`:"."]})]})}r(Uut,"AdapterLoginTerminalState");var Kut={claude_local:"Anthropic",codex_local:"OpenAI"};function G_e(e){const s=Kut[e];return s?`Sign in to ${s}`:"Sign in to the environment"}r(G_e,"adapterLoginTitle");function SV(e){return Wj()(e.adapterType).login?.panelMode==="submitted_browser_code"?(0,t.jsx)(Vut,{...e}):(0,t.jsx)(Qut,{...e})}r(SV,"AdapterLoginPanel");var aD=class extends Error{static{r(this,"AdapterLoginConflictError")}sessionId;constructor(e){super("Another sign-in attempt is active. Finish or cancel that attempt before starting a new sign-in."),this.sessionId=e}};function Qut({companyId:e,adapterType:s,environmentId:n,autoStart:a,onConnected:i,onAccountBinding:o,chrome:l="panel",aiConnection:c,onPromptReady:d}){const[u,h]=(0,m.useState)(null),[p,f]=(0,m.useState)(null),[x,g]=(0,m.useState)(null),[v,y]=(0,m.useState)("idle"),k=(0,m.useRef)(!1),w=we({mutationFn:r(()=>Nt.startAdapterAuthLogin(e,s,{environmentId:n,aiConnection:c}),"mutationFn"),onSuccess:r(ae=>{k.current=!1,f(null),g(null),y("idle"),h(ae.sessionId)},"onSuccess"),onError:r(ae=>{f(ae instanceof Error?ae.message:"Could not start the login.")},"onError")}),N=(0,m.useCallback)(()=>{k.current=!1,h(null),g(null),f(null)},[]),S=we({mutationFn:r(()=>Nt.cancelAdapterAuthLogin(e,s,u),"mutationFn"),onSuccess:N,onError:r(ae=>{f(ae instanceof Error?ae.message:"Could not cancel the login.")},"onError")}),C=te({queryKey:["adapter-login-active-session",e,s],queryFn:r(async()=>{try{const ae=await Nt.getActiveAdapterAuthLoginSession(e,s);if(!ae)return null;if(c&&ae.environmentId!==n||!!ae.aiConnection!=!!c||c&&(ae.aiConnection?.provider!==c.provider||ae.aiConnection?.method!==c.method||ae.aiConnection?.connectionId!==c.connectionId||ae.aiConnection?.ownership!==c.ownership||ae.aiConnection?.allAgents!==c.allAgents||JSON.stringify(ae.aiConnection?.agentIds)!==JSON.stringify(c.agentIds)))throw new aD(ae.sessionId);return ae}catch(ae){if(ae instanceof nn&&ae.status===404)return null;throw ae}},"queryFn"),retry:!1,gcTime:0,staleTime:0}),[_,R]=(0,m.useState)(!1),I=te({queryKey:["adapter-login-status",e,s,u],queryFn:r(()=>Nt.getAdapterAuthLoginStatus(e,s,u),"queryFn"),enabled:!!u&&!_,retry:r((ae,oe)=>oe instanceof nn&&oe.status===404?!1:ae<3,"retry"),refetchInterval:r(ae=>{const oe=ae.state.data?.status;return oe&&Mz.has(oe)?!1:Pz},"refetchInterval")});(0,m.useEffect)(()=>{const ae=I.data?.prompt??null;ae&&g(ae)},[I.data]);const T=I.data??w.data??null,E=T?.status??null,P=x,O=E?Mz.has(E):!1,M=!!u&&!O,Q=w.isPending||M||v==="saving",L=(0,m.useRef)(!1);(0,m.useEffect)(()=>{if(L.current||!C.isFetched)return;L.current=!0;const ae=C.data;ae&&(k.current=!0,f(null),g(ae.prompt??null),h(ae.sessionId))},[C.isFetched,C.data]),(0,m.useEffect)(()=>{const ae=I.error;if(!(ae instanceof nn&&ae.status===404)||!k.current||_)return;R(!0);const oe=u;(async()=>(oe&&await Nt.cancelAdapterAuthLogin(e,s,oe).catch(()=>{}),R(!1),N()))()},[I.error,_,u,e,s,N]);const F=(0,m.useRef)(!1),q=we({mutationFn:r(async()=>{const ae=C.error;ae instanceof aD&&await Nt.cancelAdapterAuthLogin(e,s,ae.sessionId)},"mutationFn"),onSuccess:r(async()=>{F.current=!1,L.current=!1,f(null),await C.refetch()},"onSuccess"),onError:r(()=>f("Could not cancel the previous sign-in. Retry before starting a new one."),"onError")}),z=(0,m.useRef)(w.mutate);z.current=w.mutate,(0,m.useEffect)(()=>{if(!(!a||F.current)){if(C.isError){F.current=!0,f(C.error instanceof Error?C.error.message:"Could not check for an active login.");return}C.isSuccess&&(F.current=!0,!C.data&&z.current())}},[a,C.isSuccess,C.isError,C.data,C.error]);const K=(0,m.useRef)(!1),U=(0,m.useRef)(i);U.current=i,(0,m.useEffect)(()=>{E!=="authenticated"||K.current||(K.current=!0,U.current?.(u??void 0))},[E]);const V=(0,m.useRef)(null),ne=(0,m.useRef)(o);ne.current=o;const Z=I.data?.codexAccountBinding??null,ie=(0,m.useCallback)(async ae=>{const oe=ne.current;if(oe){y("saving");try{await oe(ae),y("bound")}catch{y("failed")}}},[]);(0,m.useEffect)(()=>{E!=="authenticated"||!u||V.current!==u&&(!Z||!Z.companyIdentityDiffers||!ne.current||(V.current=u,ie(Z)))},[E,u,Z,ie]);const J=(0,m.useRef)(d);if(J.current=d,(0,m.useEffect)(()=>{J.current?.(P?.url??null)},[P]),l==="onboarding"){const ae=O&&E&&E!=="authenticated";return(0,t.jsx)(fV,{loading:!P&&!p&&!ae,providerName:pV(s),authorizationUrl:P?.url,mode:"displayed_code",children:p?(0,t.jsxs)("div",{children:[(0,t.jsx)("p",{role:"alert",className:"pl-2 text-xs text-destructive",children:p}),C.error instanceof aD&&(0,t.jsx)($,{type:"button",variant:"outline",disabled:q.isPending,onClick:r(()=>q.mutate(),"onClick"),children:"Cancel previous sign-in and retry"})]}):ae?(0,t.jsx)("p",{role:"alert",className:"pl-2 text-xs text-destructive",children:E==="timed_out"?"The login timed out. Start it again.":E==="cancelled"?"The login was cancelled.":"The login did not finish. Start it again."}):(0,t.jsx)(s_e,{code:P?.code??"",autoCopy:!0})})}return(0,t.jsxs)("div",{className:"rounded-md border border-border bg-muted/40 px-3 py-2 flex flex-col gap-2",children:[(0,t.jsxs)("div",{className:"flex items-center justify-between gap-2",children:[(0,t.jsx)("span",{className:"text-xs font-medium text-foreground",children:G_e(s)}),(0,t.jsxs)("div",{className:"flex items-center gap-1.5",children:[M&&(0,t.jsx)($,{type:"button",variant:"ghost",size:"sm",className:"h-7 px-2.5 text-xs text-muted-foreground hover:text-foreground",disabled:S.isPending,onClick:r(()=>S.mutate(),"onClick"),children:"Cancel"}),(0,t.jsx)($,{type:"button",variant:"outline",size:"sm",className:"h-7 px-2.5 text-xs",disabled:Q,onClick:r(()=>w.mutate(),"onClick"),children:"Sign in"})]})]}),p&&(0,t.jsx)("div",{role:"alert",className:"text-(length:--text-micro) text-destructive",children:p}),(0,t.jsxs)("div",{role:"status","aria-live":"polite",className:"space-y-2 empty:hidden",children:[M&&!P&&(0,t.jsxs)("div",{className:"flex items-center gap-2 text-(length:--text-micro) text-muted-foreground",children:[(0,t.jsx)(st,{className:"size-3 animate-spin shrink-0"}),(0,t.jsx)("span",{children:"Preparing..."})]}),M&&P&&(0,t.jsxs)("div",{className:"space-y-2",children:[(0,t.jsx)("div",{className:"text-(length:--text-micro) text-muted-foreground",children:"Copy the code, then open the authentication page."}),(0,t.jsxs)("div",{className:"flex items-center justify-between gap-2",children:[(0,t.jsxs)("div",{className:"min-w-0",children:[(0,t.jsx)("div",{className:"text-(length:--text-micro) uppercase tracking-wide text-muted-foreground",children:"1. Code"}),(0,t.jsx)("span",{className:"font-mono text-xs text-foreground break-all",children:P.code})]}),(0,t.jsx)(Dz,{value:P.code,label:"Copy code"})]}),(0,t.jsxs)("div",{className:"flex items-center justify-between gap-2",children:[(0,t.jsxs)("div",{className:"min-w-0",children:[(0,t.jsx)("div",{className:"text-(length:--text-micro) uppercase tracking-wide text-muted-foreground",children:"2. Authentication URL"}),(0,t.jsx)("span",{className:"font-mono text-xs text-foreground break-all",children:P.url})]}),(0,t.jsxs)("div",{className:"flex items-center",children:[(0,t.jsx)(Dz,{value:P.url,label:"Copy URL"}),(0,t.jsx)($,{asChild:!0,type:"button",variant:"ghost",size:"icon-xs","aria-label":"Open the authentication page",title:"Open the authentication page",className:"text-muted-foreground hover:text-foreground",children:(0,t.jsx)("a",{href:P.url,target:"_blank",rel:"noreferrer noopener",children:(0,t.jsx)($n,{className:"size-3"})})})]})]})]}),O&&E&&(0,t.jsx)(Uut,{status:E,message:T?.failure?.message??null}),E==="authenticated"&&v==="saving"&&(0,t.jsxs)("div",{className:"flex items-center gap-2 text-(length:--text-micro) text-muted-foreground",children:[(0,t.jsx)(st,{className:"size-3 animate-spin shrink-0"}),(0,t.jsx)("span",{children:"Binding this agent to the signed-in account..."})]}),E==="authenticated"&&v==="bound"&&(0,t.jsxs)("div",{className:"flex items-center gap-2 text-(length:--text-micro) text-foreground",children:[(0,t.jsx)(ms,{className:"size-3 shrink-0"}),(0,t.jsx)("span",{children:"Agent bound to the signed-in account."})]}),E==="authenticated"&&v==="failed"&&(0,t.jsxs)("div",{className:"flex items-center gap-2 text-(length:--text-micro)",children:[(0,t.jsx)(Es,{className:"size-3 shrink-0 text-destructive"}),(0,t.jsx)("span",{className:"text-destructive",children:"Could not bind this agent to the signed-in account."}),(0,t.jsx)($,{type:"button",variant:"outline",size:"sm",className:"h-6 px-2 text-xs",onClick:r(()=>{Z&&ie(Z)},"onClick"),children:"Retry"})]})]})]})}r(Qut,"DisplayedCodeLoginPanel");var Wut=new Set(["failed","timed_out","cancelled"]),tae="The login did not finish. Start the login again.",Hut=9e5,sae="The login timed out. Start the login again.";function Vut({companyId:e,adapterType:s,environmentId:n,onStored:a,onApplyStored:i,autoStart:o,onConnected:l,onCodeSubmitted:c,onSubmitFailed:d,chrome:u="panel",aiConnection:h,onPromptReady:p}){const[f,x]=(0,m.useState)(null),[g,v]=(0,m.useState)(null),[y,k]=(0,m.useState)(null),[w,N]=(0,m.useState)(!1),[S,C]=(0,m.useState)(""),[_,R]=(0,m.useState)(null),[I,T]=(0,m.useState)(!1),[E,P]=(0,m.useState)(!1),[O,M]=(0,m.useState)(!1),[Q,L]=(0,m.useState)(!1),F=(0,m.useRef)(!1),[q,z]=(0,m.useState)(!1),K=(0,m.useRef)(!1),U=r(()=>{v(null),k(null),N(!1),C(""),R(null),T(!1),P(!1),L(!1),M(!1),F.current=!1},"resetLocalState"),V=te({queryKey:["claude-oauth-token-status",e],queryFn:r(async()=>{try{return await Nt.getClaudeOAuthTokenStatus(e)}catch(at){if(at instanceof nn&&at.status===404)return null;throw at}},"queryFn"),retry:r((at,Me)=>Me instanceof nn&&Me.status===404?!1:at<2,"retry")}).data??null,ne=we({mutationFn:r(()=>Nt.startClaudeSetupTokenLogin(e,{environmentId:n,aiConnection:h,...V&&!h?{overwrite:{expectedSecretId:V.secretId,expectedLatestVersion:V.latestVersion}}:{}}),"mutationFn"),onSuccess:r(at=>{K.current=!1,U(),x(at.sessionId)},"onSuccess"),onError:r(at=>{v(at instanceof Error?at.message:"Could not start the login.")},"onError")}),Z=r(()=>{K.current=!1,x(null),U()},"clearActiveSession"),ie=we({mutationFn:r(()=>Nt.cancelClaudeSetupTokenLogin(e,f),"mutationFn"),onSuccess:r(()=>{Z()},"onSuccess"),onError:r(at=>{if(at instanceof nn&&at.status===404){Z();return}v(at instanceof Error?at.message:"Could not cancel the login.")},"onError")}),J=(0,m.useCallback)(at=>{Nt.cancelClaudeSetupTokenLogin(e,at).catch(()=>{})},[e]),ae=te({queryKey:["claude-setup-token-active-session",e],queryFn:r(async()=>{try{const at=await Nt.getActiveClaudeSetupTokenLoginSession(e);if(!at)return null;if(h&&at.environmentId!==n||!!at.aiConnection!=!!h||h&&(at.aiConnection?.provider!==h.provider||at.aiConnection?.method!==h.method||at.aiConnection?.connectionId!==h.connectionId||at.aiConnection?.ownership!==h.ownership||at.aiConnection?.allAgents!==h.allAgents||JSON.stringify(at.aiConnection?.agentIds)!==JSON.stringify(h.agentIds)))throw new Error("Another sign-in attempt is active. Finish or cancel it in its original account setup before starting this one.");return at}catch(at){if(at instanceof nn&&at.status===404)return null;throw at}},"queryFn"),retry:!1,gcTime:0,staleTime:0}),[oe,G]=(0,m.useState)(!1),X=!!f&&!E&&!Q&&!oe,Y=te({queryKey:["claude-setup-token-status",e,f],queryFn:r(()=>Nt.getClaudeSetupTokenLoginStatus(e,f),"queryFn"),enabled:X,retry:r((at,Me)=>Me instanceof nn&&Me.status===404?!1:at<3,"retry"),refetchInterval:r(at=>{if(E||Q)return!1;const Me=at.state.data?.status;return Me&&Mz.has(Me)?!1:Pz},"refetchInterval")});(0,m.useEffect)(()=>{const at=Y.error;if(at instanceof nn&&at.status===404){if(K.current){if(oe)return;G(!0);const Me=f;(async()=>(Me&&await Nt.cancelClaudeSetupTokenLogin(e,Me).catch(()=>{}),G(!1),Z()))();return}L(!0)}},[Y.error,oe,f,e]);const re=(0,m.useRef)(!1);(0,m.useEffect)(()=>{if(re.current||!ae.isFetched)return;re.current=!0;const at=ae.data;at&&(K.current=!0,U(),x(at.sessionId),at.prompt&&(k(at.prompt.authorizationUrl),at.prompt.transportAdvisory&&N(!0)))},[ae.isFetched,ae.data]);const se=te({queryKey:["claude-setup-token-prompt",e,f],enabled:X&&!y,queryFn:r(async()=>{try{return await Nt.getClaudeSetupTokenLoginPrompt(e,f)}catch(at){if(at instanceof nn&&at.status===404)return null;throw at}},"queryFn"),refetchInterval:r(at=>E||at.state.data?.authorizationUrl?!1:Pz,"refetchInterval")});(0,m.useEffect)(()=>{const at=se.data?.authorizationUrl??null;at&&k(at),se.data?.transportAdvisory&&N(!0)},[se.data]);const ce=we({mutationFn:r(at=>Nt.submitClaudeSetupTokenBrowserCode(e,f,at),"mutationFn"),onError:r(at=>{v(at instanceof Error?at.message:"Could not submit the browser code.")},"onError")}),pe=we({mutationFn:r(()=>Nt.completeClaudeSetupTokenLogin(e,f),"mutationFn"),onSuccess:r(at=>{R(at.storedSessionId),a?.(at.storedSessionId)},"onSuccess"),onError:r(()=>{T(!0)},"onError")}),fe=Y.data?.status??ne.data?.status??null,ve=Y.data?.expiresAt??ne.data?.expiresAt??null,Ie=(0,m.useRef)(pe.mutate);Ie.current=pe.mutate,(0,m.useEffect)(()=>{fe==="authenticated"&&!F.current&&(F.current=!0,Ie.current())},[fe]);const de=_!==null,xe=I||Q||!!(fe&&Wut.has(fe)),le=fe==="authenticated"&&!de&&!I,Re=!!f&&!de&&!xe&&!E,Le=ne.isPending||Re;(0,m.useEffect)(()=>{if(!Re)return;const at=ve!==null?new Date(ve).getTime():NaN,Me=Number.isFinite(at)?Math.max(0,at-Date.now()):Hut,De=setTimeout(()=>{f&&J(f),P(!0)},Me);return()=>clearTimeout(De)},[Re,ve,f,J]);const je=S.trim(),_e=Re&&!!y&&!le&&i$e(je)&&!ce.isPending&&!O,Ze=(0,m.useRef)(c);Ze.current=c;const ue=(0,m.useRef)(d);ue.current=d;const Fe=r(()=>{_e&&(v(null),ce.mutate(je),M(!0),Ze.current?.(),u!=="onboarding"&&C(""))},"handleSubmit"),mt=(0,m.useRef)(!1),bt=(0,m.useRef)(ne.mutate);bt.current=ne.mutate,(0,m.useEffect)(()=>{if(!(!o||mt.current)){if(ae.isError){mt.current=!0,v(ae.error instanceof Error?ae.error.message:"Could not check for an active login.");return}ae.isSuccess&&(mt.current=!0,!ae.data&&bt.current())}},[o,ae.isSuccess,ae.isError,ae.data,ae.error]);const et=(0,m.useRef)(Fe);et.current=Fe;const qe=u==="onboarding",it=(0,m.useRef)(!1);(0,m.useEffect)(()=>{!qe||!it.current||(it.current=!1,_e&&et.current())},[qe,_e,S]);const _t=(0,m.useRef)(!1),$t=(0,m.useRef)(l);$t.current=l,(0,m.useEffect)(()=>{!de||_t.current||(_t.current=!0,$t.current?.(f??void 0))},[de]),(0,m.useEffect)(()=>{O&&(!g&&!xe&&!E||(M(!1),ue.current?.()))},[O,g,xe,E]);const Ot=(0,m.useRef)(p);if(Ot.current=p,(0,m.useEffect)(()=>{Ot.current?.(y)},[y]),u==="onboarding"){const at=xe||E;return(0,t.jsxs)(fV,{loading:!y&&!g&&!at,providerName:pV(s),authorizationUrl:y??void 0,mode:"submitted_code",children:[w&&(0,t.jsxs)("p",{className:"flex items-start gap-2 pl-2 text-xs text-amber-700 dark:text-amber-200",children:[(0,t.jsx)(Es,{className:"mt-0.5 size-3 shrink-0"}),"This connection is not encrypted. The login code travels in clear text on this network. Continue only on a network you trust."]}),g?(0,t.jsx)("p",{role:"alert",className:"pl-2 text-xs text-destructive",children:g}):at?(0,t.jsx)("p",{role:"alert",className:"pl-2 text-xs text-destructive",children:E&&!xe?sae:tae}):(0,t.jsx)(V3,{value:S,onChange:C,onSubmit:Fe,onPaste:r(()=>{it.current=!0},"onPaste"),masked:!0,disabled:ce.isPending||le||O})]})}return(0,t.jsxs)("div",{className:"rounded-md border border-border bg-muted/40 px-3 py-2 flex flex-col gap-2",children:[(0,t.jsxs)("div",{className:"flex items-center justify-between gap-2",children:[(0,t.jsx)("span",{className:"text-xs font-medium text-foreground",children:G_e(s)}),(0,t.jsxs)("div",{className:"flex items-center gap-1.5",children:[Re&&(0,t.jsx)($,{type:"button",variant:"ghost",size:"sm",className:"h-7 px-2.5 text-xs text-muted-foreground hover:text-foreground",disabled:ie.isPending,onClick:r(()=>ie.mutate(),"onClick"),children:"Cancel"}),i&&V&&!Re&&!de&&!q&&(0,t.jsx)($,{type:"button",variant:"default",size:"sm",className:"h-7 px-2.5 text-xs",onClick:r(()=>{i(),z(!0)},"onClick"),children:"Use saved login"}),(0,t.jsx)($,{type:"button",variant:"outline",size:"sm",className:"h-7 px-2.5 text-xs",disabled:Le,onClick:r(()=>ne.mutate(),"onClick"),children:V&&!Re&&!de?"Sign in to replace":"Sign in"})]})]}),V&&!Re&&!de&&!q&&(0,t.jsx)("div",{className:"text-(length:--text-micro) text-muted-foreground",children:"You have a saved Claude login. Use it to bind this agent, or log in again to replace the stored token."}),q&&(0,t.jsxs)("div",{className:"flex items-center gap-2 text-(length:--text-micro) text-foreground",children:[(0,t.jsx)(ms,{className:"size-3 shrink-0"}),(0,t.jsx)("span",{children:"The saved Claude login is bound to this agent now."})]}),g&&(0,t.jsx)("div",{role:"alert",className:"text-(length:--text-micro) text-destructive",children:g}),(0,t.jsxs)("div",{role:"status","aria-live":"polite",className:"space-y-2 empty:hidden",children:[Re&&!y&&!le&&(0,t.jsxs)("div",{className:"flex items-center gap-2 text-(length:--text-micro) text-muted-foreground",children:[(0,t.jsx)(st,{className:"size-3 animate-spin shrink-0"}),(0,t.jsx)("span",{children:"Preparing..."})]}),Re&&y&&!le&&(0,t.jsxs)("div",{className:"space-y-2",children:[w&&(0,t.jsxs)("div",{className:"flex items-start gap-2 rounded-md border border-amber-300 bg-amber-50 px-2 py-1.5 text-(length:--text-micro) text-amber-800 dark:border-amber-500/40 dark:bg-amber-500/10 dark:text-amber-200",children:[(0,t.jsx)(Es,{className:"size-3 shrink-0 mt-0.5"}),(0,t.jsx)("span",{children:"This connection is not encrypted. The login code travels in clear text on this network. Continue only on a network you trust."})]}),(0,t.jsx)("div",{className:"text-(length:--text-micro) text-muted-foreground",children:"Open the authorization page, then enter the browser code it shows."}),(0,t.jsxs)("div",{className:"flex items-center justify-between gap-2",children:[(0,t.jsxs)("div",{className:"min-w-0",children:[(0,t.jsx)("div",{className:"text-(length:--text-micro) uppercase tracking-wide text-muted-foreground",children:"1. Authorization URL"}),(0,t.jsx)("span",{className:"font-mono text-xs text-foreground break-all",children:y})]}),(0,t.jsxs)("div",{className:"flex items-center",children:[(0,t.jsx)(Dz,{value:y,label:"Copy URL"}),(0,t.jsx)($,{asChild:!0,type:"button",variant:"ghost",size:"icon-xs","aria-label":"Open the authorization page",title:"Open the authorization page",className:"text-muted-foreground hover:text-foreground",children:(0,t.jsx)("a",{href:y,target:"_blank",rel:"noreferrer noopener",children:(0,t.jsx)($n,{className:"size-3"})})})]})]}),(0,t.jsxs)("div",{className:"space-y-1",children:[(0,t.jsx)("div",{className:"text-(length:--text-micro) uppercase tracking-wide text-muted-foreground",children:"2. Browser code"}),(0,t.jsxs)("div",{className:"flex items-center gap-2",children:[(0,t.jsx)("input",{"aria-label":"Browser code",type:"text",autoComplete:"off",spellCheck:!1,value:S,onChange:r(at=>C(at.target.value),"onChange"),onKeyDown:r(at=>{at.key==="Enter"&&(at.preventDefault(),Fe())},"onKeyDown"),className:"flex-1 min-w-0 rounded-md border border-border bg-background px-2 py-1 font-mono text-xs text-foreground"}),(0,t.jsx)($,{type:"button",variant:"outline",size:"sm",className:"h-7 px-2.5 text-xs",disabled:!_e,onClick:Fe,children:"Submit"})]})]})]}),le&&(0,t.jsxs)("div",{className:"flex items-center gap-2 text-(length:--text-micro) text-muted-foreground",children:[(0,t.jsx)(st,{className:"size-3 animate-spin shrink-0"}),(0,t.jsx)("span",{children:"Completing the login…"})]}),de&&(0,t.jsxs)("div",{className:"flex items-center gap-2 text-(length:--text-micro) text-foreground",children:[(0,t.jsx)(ms,{className:"size-3 shrink-0"}),(0,t.jsx)("span",{children:"Authenticated. The environment has credentials now."})]}),xe&&(0,t.jsxs)("div",{className:"flex items-start gap-2 text-(length:--text-micro) text-destructive",children:[(0,t.jsx)(Es,{className:"size-3 shrink-0"}),(0,t.jsx)("span",{children:tae})]}),E&&!xe&&!de&&(0,t.jsxs)("div",{className:"flex items-start gap-2 text-(length:--text-micro) text-destructive",children:[(0,t.jsx)(Es,{className:"size-3 shrink-0"}),(0,t.jsx)("span",{children:sae})]})]})]})}r(Vut,"SubmittedBrowserCodeLoginPanel");function Gut({result:e}){const s=e.status==="pass"?"Passed":e.status==="warn"?"Warnings":"Failed",n=e.status==="pass"?"text-green-700 dark:text-green-300 border-green-300 dark:border-green-500/40 bg-green-50 dark:bg-green-500/10":e.status==="warn"?"text-amber-700 dark:text-amber-300 border-amber-300 dark:border-amber-500/40 bg-amber-50 dark:bg-amber-500/10":"text-red-700 dark:text-red-300 border-red-300 dark:border-red-500/40 bg-red-50 dark:bg-red-500/10";return(0,t.jsxs)("div",{className:`rounded-md border px-3 py-2 text-xs ${n}`,children:[(0,t.jsxs)("div",{className:"flex items-center justify-between gap-2",children:[(0,t.jsx)("span",{className:"font-medium",children:s}),(0,t.jsx)("span",{className:"text-(length:--text-micro) opacity-80",children:new Date(e.testedAt).toLocaleTimeString()})]}),(0,t.jsx)("div",{className:"mt-2 space-y-1.5",children:e.checks.map((a,i)=>(0,t.jsxs)("div",{className:"text-(length:--text-micro) leading-relaxed break-words",children:[(0,t.jsx)("span",{className:"font-medium uppercase tracking-wide opacity-80",children:a.level}),(0,t.jsx)("span",{className:"mx-1 opacity-60",children:"·"}),(0,t.jsx)("span",{children:a.message}),a.detail&&(0,t.jsxs)("span",{className:"block opacity-75 break-all",children:["(",a.detail,")"]}),a.hint&&(0,t.jsxs)("span",{className:"block opacity-90 break-words",children:["Hint: ",a.hint]})]},`${a.code}-${i}`))})]})}r(Gut,"AdapterEnvironmentResult$1");function Y_e({value:e,onChange:s,disabledTypes:n,openAiDotEnabled:a=!1}){const[i,o]=(0,m.useState)(!1),l=th(e),c=(0,m.useMemo)(()=>[...Q_e(d=>m5[d]??kf(d)),...a?[{value:"openai_dot",label:"OpenAI Dot",experimental:!0,comingSoon:!1}]:[]].filter(d=>!n.has(d.value)),[n,a]);return(0,t.jsxs)(dr,{open:i,onOpenChange:o,children:[(0,t.jsx)(wr,{asChild:!0,children:(0,t.jsxs)("button",{type:"button","data-size":"default",className:W(Mze,"w-full"),children:[(0,t.jsxs)("span",{className:"inline-flex min-w-0 items-center gap-1.5",children:[(0,t.jsx)("span",{"aria-hidden":"true",className:"inline-flex shrink-0",children:(0,t.jsx)(q0,{type:e,className:"size-4"})}),(0,t.jsx)("span",{className:"truncate",children:m5[e]??kf(e)}),l.experimental&&(0,t.jsx)(nae,{})]}),(0,t.jsx)(an,{className:"size-4 opacity-50"})]})}),(0,t.jsx)(nr,{className:"w-(--radix-popover-trigger-width) p-1",align:"start",children:c.map(d=>(0,t.jsxs)("button",{type:"button",disabled:d.comingSoon,className:W("flex items-center justify-between w-full px-2 py-1.5 text-sm rounded",d.comingSoon?"opacity-40 cursor-not-allowed":"hover:bg-accent/50",d.value===e&&!d.comingSoon&&"bg-accent"),onClick:r(()=>{d.comingSoon||(s(d.value),o(!1))},"onClick"),children:[(0,t.jsxs)("span",{className:"inline-flex items-center gap-1.5",children:[(0,t.jsx)("span",{"aria-hidden":"true",className:"inline-flex shrink-0",children:(0,t.jsx)(q0,{type:d.value,className:"size-4"})}),(0,t.jsx)("span",{children:d.label}),d.experimental&&(0,t.jsx)(nae,{})]}),d.comingSoon&&(0,t.jsx)("span",{className:"text-(length:--text-nano) text-muted-foreground",children:"Coming soon"})]},d.value))})]})}r(Y_e,"AdapterTypeDropdown");function nae(){return(0,t.jsx)("span",{className:"shrink-0 rounded border border-amber-500/30 bg-amber-500/10 px-1.5 py-0.5 text-(length:--text-nano) font-medium leading-none text-amber-700 dark:text-amber-200",children:"Experimental"})}r(nae,"ExperimentalBadge$1");function CV({models:e,value:s,onChange:n,open:a,onOpenChange:i,allowDefault:o,required:l,groupByProvider:c,preserveOrder:d,creatable:u,detectedModel:h,detectedModelCandidates:p,onDetectModel:f,onRefreshModels:x,refreshingModels:g,loadingModels:v,detectModelLabel:y,emptyDetectHint:k,defaultLabel:w,presentation:N="searchable",effort:S}){const[C,_]=(0,m.useState)(""),[R,I]=(0,m.useState)(!1),[T,E]=(0,m.useState)(!1),P=C.trim(),O=!!(u&&P&&!e.some(K=>K.id.toLowerCase()===P.toLowerCase())),M=(0,m.useMemo)(()=>{const K=new Set;h&&K.add(h);for(const U of p??[])U&&K.add(U);return K},[h,p]),Q=(0,m.useMemo)(()=>e.filter(K=>{if(M.has(K.id))return!1;const U=jE(K.id);return YL({...Ik(K,c),...U&&!K.provider?{group:U}:{}},C)}),[e,C,M,c]),L=(0,m.useMemo)(()=>new Map(e.map(K=>[K.id,Ik(K,c)])),[e,c]),F=s?su(s,[...L.values()]):null,q=(0,m.useMemo)(()=>{if(!c&&Q.some(U=>U.provider)){const U=new Map;for(const V of Q){const ne=V.provider??"other";U.set(ne,[...U.get(ne)??[],V])}return Array.from(U.entries()).map(([V,ne])=>({provider:V,entries:ne}))}if(!c)return[{provider:null,entries:d?Q:[...Q].sort((U,V)=>U.id.localeCompare(V.id))}];const K=new Map;for(const U of Q){const V=jE(U.id)??"other",ne=K.get(V)??[];ne.push(U),K.set(V,ne)}return Array.from(K.entries()).sort(([U],[V])=>U.localeCompare(V)).map(([U,V])=>({provider:U,entries:[...V].sort((ne,Z)=>ne.id.localeCompare(Z.id))}))},[Q,c,d]);async function z(){if(f){E(!0);try{const K=await f();K&&(n(K),i(!1),_(""))}finally{E(!1)}}}if(r(z,"handleDetectModel"),N==="native"){const K="__paperclip_custom_model__",U=[...new Set([s,...M])].filter(V=>!!V&&(!e.some(ne=>ne.id===V)||M.has(V)));return(0,t.jsxs)(Ss,{label:"Model",hint:wi.model,children:[(0,t.jsxs)(eW,{"aria-label":"Model","aria-busy":v||g,value:R?K:s,required:l&&!R,onChange:r(V=>{const ne=V.target.value;I(ne===K),ne!==K&&n(ne)},"onChange"),children:[(0,t.jsx)("option",{value:"",disabled:!o,children:o?w??"Default":v?"Loading models…":l?"Select model (required)":"Select model"}),U.map(V=>(0,t.jsx)("option",{value:V,children:e.find(ne=>ne.id===V)?.label??V},V)),q.map(({provider:V,entries:ne})=>c?(0,t.jsx)("optgroup",{label:V??void 0,children:ne.map(Z=>(0,t.jsx)("option",{value:Z.id,children:Z.label},Z.id))},V):ne.map(Z=>(0,t.jsx)("option",{value:Z.id,children:Z.label},Z.id))),u&&(0,t.jsx)("option",{value:K,children:"Enter custom model…"})]}),R&&(0,t.jsxs)("label",{className:"mt-3 block space-y-1 text-xs text-muted-foreground",children:["Model ID",(0,t.jsx)(dt,{"aria-label":"Model ID",value:s,onChange:r(V=>n(V.target.value),"onChange"),placeholder:"Enter model ID or alias",autoFocus:!0,required:l})]}),v&&(0,t.jsx)("p",{role:"status",className:"mt-2 text-xs text-muted-foreground",children:"Loading models…"}),x&&(0,t.jsx)($,{type:"button",variant:"ghost",size:"sm",disabled:g,onClick:r(()=>{x()},"onClick"),children:g?"Refreshing…":"Refresh models"})]})}return(0,t.jsx)(Ss,{label:"Model",hint:wi.model,children:(0,t.jsxs)(dr,{open:a,onOpenChange:r(K=>{i(K),K||_("")},"onOpenChange"),children:[(0,t.jsx)(wr,{asChild:!0,children:(0,t.jsxs)("button",{type:"button","aria-label":"Model",className:"flex w-full min-w-0 items-center gap-2 rounded-md border border-border px-2.5 py-1.5 text-left text-sm transition-colors hover:bg-accent/50","data-testid":"model-dropdown-trigger",children:[F?(0,t.jsx)(jf,{display:F,layout:"inline",className:"min-w-0 flex-1"}):(0,t.jsx)("span",{className:"min-w-0 flex-1 truncate text-muted-foreground",children:o?w??"Default":l?"Select model (required)":"Select model"}),S&&s&&yj(S.value,s,[...L.values()])?(0,t.jsxs)("span",{className:W("shrink-0 text-xs",S.value?"text-foreground":"text-muted-foreground"),"data-testid":"model-dropdown-effort-value",children:["· ",S.value??"Auto effort"]}):null,(0,t.jsx)(an,{className:"size-4 shrink-0 text-muted-foreground"})]})}),(0,t.jsxs)(nr,{className:"w-(--radix-popover-trigger-width) p-1",align:"start",children:[S&&s&&yj(S.value,s,[...L.values()])?(0,t.jsxs)("div",{className:"-mx-1 -mt-1 mb-1 space-y-1.5 border-b border-border px-2.5 py-2",children:[(0,t.jsx)("span",{className:"block text-xs font-medium text-muted-foreground",children:"Thinking effort"}),(0,t.jsx)(pM,{levels:Xx(s,[...L.values()]),value:S.value,onChange:r(K=>{S.onChange(K),i(!1)},"onChange"),defaultLabel:"Auto",label:"Thinking effort",testId:"model-dropdown-effort"})]}):null,(0,t.jsxs)("div",{className:"relative -mx-1 -mt-1 mb-1 border-b border-border",children:[(0,t.jsx)(Yr,{className:"pointer-events-none absolute left-2.5 top-1/2 size-4 -translate-y-1/2 text-muted-foreground","aria-hidden":"true"}),(0,t.jsx)("input",{"aria-label":"Search models",className:"h-9 w-full bg-transparent pl-8 pr-7 text-sm outline-none placeholder:text-muted-foreground",placeholder:u?C2:"Search models",value:C,onChange:r(K=>_(K.target.value),"onChange"),autoFocus:!0}),C&&(0,t.jsx)("button",{type:"button","aria-label":"Clear search",className:"absolute right-2.5 top-1/2 -translate-y-1/2 text-muted-foreground hover:text-foreground",onClick:r(()=>_(""),"onClick"),children:(0,t.jsxs)("svg",{"aria-hidden":"true",focusable:"false",className:"h-3 w-3",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,t.jsx)("line",{x1:"18",y1:"6",x2:"6",y2:"18"}),(0,t.jsx)("line",{x1:"6",y1:"6",x2:"18",y2:"18"})]})})]}),f&&!C.trim()&&(0,t.jsxs)("button",{type:"button",className:"flex items-center gap-1.5 w-full px-2 py-1.5 text-xs rounded hover:bg-accent/50 text-muted-foreground",onClick:r(()=>{z()},"onClick"),disabled:T,children:[(0,t.jsxs)("svg",{"aria-hidden":"true",focusable:"false",className:"h-3 w-3",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,t.jsx)("path",{d:"M21 12a9 9 0 0 0-9-9 9.75 9.75 0 0 0-6.74 2.74L3 8"}),(0,t.jsx)("path",{d:"M3 3v5h5"})]}),T?"Detecting...":h?y?.replace(/^Detect\b/,"Re-detect")??"Re-detect from config":y??"Detect from config"]}),x&&!C.trim()&&(0,t.jsxs)("button",{type:"button",className:"flex items-center gap-1.5 w-full px-2 py-1.5 text-xs rounded hover:bg-accent/50 text-muted-foreground",onClick:r(()=>{x()},"onClick"),disabled:g,children:[(0,t.jsxs)("svg",{"aria-hidden":"true",focusable:"false",className:"h-3 w-3",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,t.jsx)("path",{d:"M3 12a9 9 0 0 1 15.28-6.36L21 8"}),(0,t.jsx)("path",{d:"M21 3v5h-5"}),(0,t.jsx)("path",{d:"M21 12a9 9 0 0 1-15.28 6.36L3 16"}),(0,t.jsx)("path",{d:"M8 16H3v5"})]}),g?"Refreshing...":"Refresh models"]}),s&&(!e.some(K=>K.id===s)||M.has(s))&&(0,t.jsxs)("button",{type:"button",className:W("flex items-center w-full px-2 py-1.5 text-sm rounded bg-accent/50"),onClick:r(()=>{i(!1)},"onClick"),children:[F?(0,t.jsx)(jf,{display:F,layout:"inline",className:"flex-1"}):null,(0,t.jsx)(ot,{variant:"outline",className:"ml-auto text-(length:--text-nano) px-1.5 bg-green-500/15 text-green-400 border-green-500/20",children:"current"})]}),h&&h!==s&&(0,t.jsxs)("button",{type:"button",className:W("flex items-center w-full px-2 py-1.5 text-sm rounded hover:bg-accent/50"),onClick:r(()=>{n(h),i(!1)},"onClick"),children:[(0,t.jsx)("span",{className:"block w-full text-left truncate font-mono text-xs",title:h,children:e.find(K=>K.id===h)?.label??h}),(0,t.jsx)(ot,{variant:"outline",className:"ml-auto text-(length:--text-nano) px-1.5 bg-blue-500/15 text-blue-400 border-blue-500/20",children:"detected"})]}),p?.filter(K=>K&&K!==h&&K!==s).map(K=>{const U=e.find(V=>V.id===K);return(0,t.jsxs)("button",{type:"button",className:W("flex items-center w-full px-2 py-1.5 text-sm rounded hover:bg-accent/50"),onClick:r(()=>{n(K),i(!1)},"onClick"),children:[(0,t.jsx)("span",{className:"block w-full text-left truncate font-mono text-xs",title:K,children:U?.label??K}),(0,t.jsx)(ot,{variant:"outline",className:"ml-auto text-(length:--text-nano) px-1.5 bg-sky-500/15 text-sky-400 border-sky-500/20",children:"config"})]},`detected-${K}`)}),(0,t.jsxs)("div",{className:"max-h-(--sz-240px) overflow-y-auto",children:[o&&(0,t.jsx)("button",{type:"button",className:W("flex items-center gap-2 w-full px-2 py-1.5 text-sm rounded hover:bg-accent/50",!s&&"bg-accent"),onClick:r(()=>{n(""),i(!1)},"onClick"),children:"Default"}),O&&(0,t.jsxs)("button",{type:"button",className:"flex items-center justify-between gap-2 w-full px-2 py-1.5 text-sm rounded hover:bg-accent/50",onClick:r(()=>{n(P),i(!1),_("")},"onClick"),children:[(0,t.jsx)("span",{children:"Use manual model"}),(0,t.jsx)("span",{className:"text-xs font-mono text-muted-foreground",children:P})]}),q.map(K=>(0,t.jsxs)("div",{className:"mb-1 last:mb-0",children:[K.provider&&(0,t.jsx)(JL,{provider:K.provider,testId:`model-dropdown-group-${K.provider}`}),K.entries.map(U=>(0,t.jsxs)("button",{type:"button",className:W("flex items-center gap-2 w-full px-2 py-1.5 text-left text-sm rounded hover:bg-accent/50",U.id===s&&"bg-accent"),onClick:r(()=>{n(U.id),S&&Xx(U.id,[...L.values()]).length>0||i(!1)},"onClick"),children:[(0,t.jsx)(ZL,{option:L.get(U.id)??Ik(U,c)}),U.id===s?(0,t.jsx)(ms,{className:"size-4 shrink-0","aria-hidden":"true"}):null]},U.id))]},K.provider??"")),Q.length===0&&!O&&M.size===0&&(0,t.jsx)("div",{className:"px-2 py-2 space-y-2",children:(0,t.jsx)("p",{className:"text-xs text-muted-foreground",children:v?"Loading models…":f?k??"No model detected yet. Enter a provider/model manually.":"No models found."})})]})]})]})})}r(CV,"ModelDropdown");function Yut({value:e,options:s,onChange:n,open:a,onOpenChange:i}){const o=s.find(l=>l.id===e)??s[0];return(0,t.jsx)(Ss,{label:"Thinking effort",hint:wi.thinkingEffort,children:(0,t.jsxs)(dr,{open:a,onOpenChange:i,children:[(0,t.jsx)(wr,{asChild:!0,children:(0,t.jsxs)("button",{className:"inline-flex items-center gap-1.5 rounded-md border border-border px-2.5 py-1.5 text-sm hover:bg-accent/50 transition-colors w-full justify-between",children:[(0,t.jsx)("span",{className:W(!e&&"text-muted-foreground"),children:o?.label??"Auto"}),(0,t.jsx)(an,{className:"h-3 w-3 text-muted-foreground"})]})}),(0,t.jsx)(nr,{className:"w-(--radix-popover-trigger-width) p-1",align:"start",children:s.map(l=>(0,t.jsxs)("button",{className:W("flex items-center justify-between w-full px-2 py-1.5 text-sm rounded hover:bg-accent/50",l.id===e&&"bg-accent"),onClick:r(()=>{n(l.id),i(!1)},"onClick"),children:[(0,t.jsx)("span",{children:l.label}),l.id?(0,t.jsx)("span",{className:"text-xs text-muted-foreground font-mono",children:l.id}):null]},l.id||"auto"))})]})})}r(Yut,"ThinkingEffortDropdown");function Z_e(e){const s=`paperclip.agent-appearance.${e}`;function n(){try{const l=ube.safeParse(JSON.parse(sessionStorage.getItem(s)??"null"));if(l.success)return l.data}catch{}const o=zT();try{sessionStorage.setItem(s,JSON.stringify(o))}catch{}return o}r(n,"readDraft");const[a,i]=(0,m.useState)(()=>({key:s,appearance:n()}));return a.key!==s&&i({key:s,appearance:n()}),{appearance:a.appearance,clear(){try{sessionStorage.removeItem(s)}catch{}}}}r(Z_e,"useAgentAppearanceDraft");var RS=null,TI=new Set,ES={subscribe(e){return TI.add(e),()=>{TI.delete(e)}},getSnapshot(){return RS},acquire(e){if(RS)return!1;RS=e;for(const s of TI)s();return!0},release(e){if(RS===e){RS=null;for(const s of TI)s()}}};function NN({agent:e,appearance:s,size:n=256,state:a="idle",muted:i=!1,motion:o="auto",trackingRegion:l,trackingScope:c="region",followCursor:d=!0,followRotation:u=!0,className:h,label:p,name:f}){const x=(0,m.useMemo)(()=>sv(s??e?.appearance,e?.id),[s,e?.appearance,e?.id]),g=(0,m.useRef)(null),v=(0,m.useRef)(null),y=(0,m.useRef)(null),k=(0,m.useRef)(Symbol("agent-character")),w=(0,m.useSyncExternalStore)(ES.subscribe,ES.getSnapshot,()=>null),[N,S]=(0,m.useState)(!1),[C,_]=(0,m.useState)(!0),[R,I]=(0,m.useState)(!1),[T,E]=(0,m.useState)(!1),P=!x.customAvatarAssetId&&N&&!C&&!R&&o==="auto"&&a!=="rest";return(0,m.useEffect)(()=>{if(typeof matchMedia!="function"||typeof IntersectionObserver!="function")return;const O=matchMedia("(prefers-reduced-motion: reduce)"),M=r(()=>_(O.matches),"change");M(),O.addEventListener("change",M);const Q=new IntersectionObserver(L=>S(L[0]?.isIntersecting??!1));return g.current&&Q.observe(g.current),()=>{Q.disconnect(),O.removeEventListener("change",M)}},[]),(0,m.useEffect)(()=>{P&&w===null&&ES.acquire(k.current),P||ES.release(k.current)},[P,w]),(0,m.useEffect)(()=>()=>ES.release(k.current),[]),(0,m.useEffect)(()=>{if(!P||w!==k.current)return;let O=!1;return E(!1),Promise.all([bd(()=>import("./runtime-IAg0vdY9.js"),__vite__mapDeps([0,1])),bd(()=>import("./definition-g8Ojcw3n.js"),__vite__mapDeps([2,3,1]))]).then(([M,Q])=>{O||!v.current||(y.current=M.createCharacter(v.current,Q.characterDefinition(x,i),{animation:Q.animationId(a),trackingRegion:l?.current??g.current??void 0,followCursor:d,followRotation:u,trackingScope:c,displaySize:n,onError:r(()=>I(!0),"onError")}),E(!0))}).catch(()=>{O||I(!0)}),()=>{O=!0,y.current?.destroy(),y.current=null,E(!1)}},[P,w,l,c,n,d,u]),(0,m.useEffect)(()=>{y.current&&bd(()=>import("./definition-g8Ojcw3n.js").then(O=>{y.current?.setDefinition(O.characterDefinition(x,i)),y.current?.setAnimation(O.animationId(a))}),__vite__mapDeps([2,3,1]))},[x,i,a,T]),(0,t.jsxs)("span",{ref:g,role:p?"img":void 0,"aria-label":p,"aria-hidden":p?void 0:!0,className:W("relative inline-block shrink-0",gze[n],h),children:[(0,t.jsx)(lr,{agent:e,appearance:x,size:n<256?256:n,name:f,pose:a,muted:i,className:W("size-full",T&&!x.customAvatarAssetId&&"invisible")}),(0,t.jsx)("span",{ref:v,className:"absolute inset-0"})]})}r(NN,"AgentCharacter");var Zut=new Set(["claude_local","codex_local","opencode_local","grok_local"]);function J_e(e,{cloud:s,nativeRunnerEnabled:n,openAiDotEnabled:a=!1,runnerProvider:i}){return e==="openai_dot"||e==="paperclip_runner"&&i==="openai_dot"?a:e==="paperclip_runner"?n:s?Zut.has(e):!0}r(J_e,"isNewAgentAdapterAllowed");function Jut(){const{selectedCompanyId:e}=fs(),{appearance:s}=Z_e(`${e}:new-agent`);return(0,t.jsx)(NN,{appearance:s,state:"sleepy",muted:!0,size:256,className:"size-48",trackingScope:"page"})}r(Jut,"AgentBasicsCharacter");function X_e({open:e,onClose:s,onContinue:n,initialAdapter:a="",onInvite:i}){const o=(0,m.useId)(),l=!!td(),c=te({queryKey:D.instance.experimentalSettings,queryFn:jr.getExperimental,enabled:e,retry:!1}),[d,u]=(0,m.useState)(""),[h,p]=(0,m.useState)(a),[f,x]=(0,m.useState)("codex"),[g,v]=(0,m.useState)("name"),{data:y,isPending:k,error:w}=te({queryKey:D.adapters.all,queryFn:Oh.list,enabled:e}),N=(y??[]).filter(C=>C.loaded&&!C.disabled&&J_e(C.type,{cloud:l,nativeRunnerEnabled:c.data?.enableNativeRunner===!0})&&!["process","http"].includes(C.type)&&!th(C.type).comingSoon),S=N.some(C=>C.type===h);return(0,t.jsx)(Fs,{open:e,onOpenChange:r(C=>{C||s()},"onOpenChange"),children:(0,t.jsxs)(Qs,{className:W("flex max-h-(--sz-calc-18) flex-col gap-0 overflow-hidden p-0 sm:max-w-(--sz-640px)",g==="name"&&"sm:max-w-(--sz-560px)"),children:[(0,t.jsxs)("div",{className:"flex items-center gap-2 px-6 py-5 text-xs text-muted-foreground","aria-label":"New agent progress",children:[(0,t.jsx)("span",{className:W(g==="name"&&"font-medium text-foreground"),children:"1. Name"}),(0,t.jsx)(Ln,{className:"size-3"}),(0,t.jsx)("span",{className:W(g==="adapter"&&"font-medium text-foreground"),children:"2. Adapter"})]}),(0,t.jsxs)("form",{className:"flex min-h-0 flex-col",onSubmit:r(C=>{C.preventDefault(),d.trim()&&(g==="name"?v("adapter"):S&&n({name:d.trim(),adapterType:h==="openai_dot"?"paperclip_runner":h,runnerProvider:h==="openai_dot"?"openai_dot":f}))},"onSubmit"),children:[(0,t.jsxs)("div",{className:"flex min-h-0 flex-col gap-7 overflow-y-auto px-6 pb-8 sm:px-10",children:[(0,t.jsxs)("div",{className:"flex flex-col items-center gap-4 text-center",children:[e&&(0,t.jsx)(Jut,{}),(0,t.jsxs)("div",{className:"space-y-2",children:[(0,t.jsx)(Ks,{className:"text-3xl font-semibold tracking-tight",children:g==="name"?"Meet your next agent":"Choose an adapter"}),(0,t.jsx)(mn,{className:"text-base",children:g==="name"?"Start with a name. Make them your own.":`How should ${d.trim()} work?`})]})]}),g==="name"?(0,t.jsxs)("div",{className:"space-y-2",children:[(0,t.jsx)("label",{htmlFor:o,className:"text-sm font-medium",children:"Agent name"}),(0,t.jsx)(dt,{id:o,autoFocus:!0,maxLength:100,placeholder:"e.g. Darnold",value:d,onChange:r(C=>u(C.target.value),"onChange"),className:"h-12 text-base"}),i&&(0,t.jsx)($,{type:"button",variant:"link",className:"px-0 text-muted-foreground",onClick:i,children:"Invite an external agent"})]}):(0,t.jsxs)("fieldset",{className:"space-y-4",children:[(0,t.jsx)("legend",{className:"sr-only",children:"Adapter"}),k&&(0,t.jsx)("p",{role:"status",className:"text-sm text-muted-foreground",children:"Loading adapters…"}),w&&(0,t.jsx)("p",{role:"alert",className:"text-sm text-destructive",children:w.message}),(0,t.jsx)("div",{className:W("grid grid-cols-2 gap-3",N.length!==4&&"sm:grid-cols-3"),children:N.map(C=>{const _=th(C.type);return(0,t.jsxs)("label",{className:"relative cursor-pointer",children:[(0,t.jsx)("input",{type:"radio",name:"new-agent-adapter",value:C.type,checked:h===C.type,onChange:r(()=>p(C.type),"onChange"),className:"peer sr-only"}),(0,t.jsxs)("span",{className:W("flex h-full flex-col items-center gap-2 rounded-lg border px-3 py-4 text-center peer-focus-visible:ring-2 peer-focus-visible:ring-ring hover:bg-accent/40",h===C.type?"border-foreground/40 bg-accent":"border-border bg-card"),children:[(0,t.jsx)(q0,{type:C.type}),(0,t.jsx)("span",{className:"text-sm font-medium",children:_.label}),h===C.type&&(0,t.jsx)(ms,{className:"absolute right-2 top-2 size-3.5"})]})]},C.type)})}),S&&h==="paperclip_runner"&&(0,t.jsxs)("label",{className:"flex flex-col gap-2 text-sm font-medium",children:["Runner",(0,t.jsxs)("select",{className:"rounded-md border border-border bg-background px-3 py-2",value:f,onChange:r(C=>x(C.target.value),"onChange"),children:[(0,t.jsx)("option",{value:"codex",children:"Codex (app server)"}),(0,t.jsx)("option",{value:"claude",children:"Claude (ACPX)"}),(0,t.jsx)("option",{value:"grok",children:"Grok Build (ACPX)"}),(0,t.jsx)("option",{value:"opencode",children:"OpenCode"})]})]})]})]}),(0,t.jsxs)("div",{className:"flex justify-between gap-4 border-t border-border px-6 py-4",children:[(0,t.jsx)($,{type:"button",variant:"ghost",onClick:r(()=>g==="name"?s():v("name"),"onClick"),children:g==="name"?"Cancel":(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)(wl,{className:"size-4"}),"Back"]})}),(0,t.jsxs)($,{type:"submit",disabled:!d.trim()||g==="adapter"&&!S,children:[g==="name"?"Choose adapter":"Configure agent",(0,t.jsx)(pl,{className:"size-4"})]})]})]})]})})}r(X_e,"AgentBasicsDialog");var Xut={subscription:"Subscription",api:"API key",advanced:"Custom Gateway"};function emt({mode:e}){return(0,t.jsx)("span",{className:"relative flex h-4 w-full items-center justify-center overflow-hidden text-(length:--text-micro) text-muted-foreground",children:(0,t.jsx)(S2,{initial:!1,mode:"sync",children:(0,t.jsx)(Rl.span,{className:"absolute inset-0 flex items-center justify-center whitespace-nowrap",initial:{opacity:0,y:bre},animate:{opacity:1,y:0,transition:Nit},exit:{opacity:0,y:bre,transition:Sit},children:Xut[e]},e)})})}r(emt,"CredentialTag");function tmt({source:e,mode:s,selected:n,onSelect:a,buttonRef:i,settling:o}){return(0,t.jsxs)("button",{ref:i,type:"button",role:"radio","aria-checked":n,onClick:a,className:W("flex min-w-0 flex-1 cursor-pointer flex-col items-center gap-1.5 self-stretch rounded-md border p-3","transition-(--tp-border-color-background-color) ease-(--motion-ease-standard)",o?"duration-(--motion-duration-slow)":"duration-(--motion-duration-fast)","outline-none focus-visible:ring-ring/50 focus-visible:ring-(length:--rad-3)",n?"border-foreground/40 bg-accent":"border-border bg-card hover:bg-accent/40"),children:[(0,t.jsx)("span",{className:"flex size-(--sz-30px) shrink-0 items-center justify-center",children:e.icon}),(0,t.jsx)("span",{className:"text-(length:--text-compact) font-medium text-foreground",children:e.label}),s?(0,t.jsx)(emt,{mode:s}):(0,t.jsx)("span",{"aria-hidden":!0,className:"h-4"})]})}r(tmt,"ModelSourceTile");function e5e({sources:e,mode:s,selectedId:n,onSelect:a,label:i,collapsed:o=!1,settling:l=!1}){const c=(0,m.useRef)(new Map),d=r(h=>{if(e.length===0)return;const p=e.findIndex(x=>x.id===n),f=e[((p===-1?h>0?-1:0:p)+h+e.length)%e.length];a(f.id),c.current.get(f.id)?.focus()},"moveSelection"),u=o?e.filter(h=>h.id===n):e;return(0,t.jsx)("div",{role:"radiogroup","aria-label":i,className:W("flex items-start gap-3",o&&"justify-center"),onKeyDown:r(h=>{o||(h.key==="ArrowRight"||h.key==="ArrowDown"?(h.preventDefault(),d(1)):(h.key==="ArrowLeft"||h.key==="ArrowUp")&&(h.preventDefault(),d(-1)))},"onKeyDown"),children:(0,t.jsx)(S2,{initial:!1,mode:"popLayout",children:u.map(h=>(0,t.jsx)(Rl.div,{layout:!0,transition:e_e,exit:{opacity:0,transition:Pit},className:W("flex min-w-0",o?"w-(--sz-source-tile-two-up)":"flex-1"),children:(0,t.jsx)(tmt,{source:h,mode:h.credentialMode===void 0?s:h.credentialMode,selected:h.id===n,onSelect:r(()=>a(h.id),"onSelect"),settling:l,buttonRef:r(p=>{p?c.current.set(h.id,p):c.current.delete(h.id)},"buttonRef")})},h.id))})})}r(e5e,"ModelSourceTiles");var iD={subscription:"Use subscription instead",api:"Use API key instead"},smt=["subscription","api"],rae={subscription:"api",api:"subscription"};function t5e({mode:e,onChange:s}){return(0,t.jsx)(nmt,{destination:rae[e],onClick:r(()=>s(rae[e]),"onClick"),modes:smt})}r(t5e,"CredentialModeLink");function nmt({destination:e,onClick:s,modes:n}){return(0,t.jsxs)("button",{type:"button","aria-label":iD[e],onClick:s,className:W("group grid cursor-pointer px-3 py-2 text-left text-sm font-medium","rounded-md outline-none focus-visible:ring-ring/50 focus-visible:ring-(length:--rad-3)"),children:[n.map(a=>(0,t.jsx)("span",{"aria-hidden":!0,className:"invisible col-start-1 row-start-1 whitespace-nowrap",children:iD[a]},a)),(0,t.jsx)(S2,{initial:!1,mode:"sync",children:(0,t.jsx)(Rl.span,{className:W("col-start-1 row-start-1 justify-self-start whitespace-nowrap","underline decoration-muted-foreground/40 underline-offset-4","text-muted-foreground transition-colors","group-hover:text-foreground group-hover:decoration-foreground/40"),initial:{opacity:0},animate:{opacity:1,transition:hV},exit:{opacity:0,transition:Cit},children:iD[e]},e)})]})}r(nmt,"ModeLink");function $z({onBack:e,primaryLabel:s,primaryDisabled:n,loading:a,loadingLabel:i,primaryIcon:o,onPrimary:l}){const c=a&&i?i:s,d=o??(a?"spinner":"arrow");return(0,t.jsxs)("div",{className:"flex items-center justify-between pt-9",children:[e?(0,t.jsxs)($,{variant:"ghost",size:"lg",className:"rounded-full has-[>svg]:pl-4 has-[>svg]:pr-5",onClick:e,disabled:a,children:[(0,t.jsx)(wl,{className:"mr-1 size-3.5"}),"Back"]}):(0,t.jsx)("span",{}),(0,t.jsx)(Rl.div,{layout:!0,transition:Iit,className:"min-w-0",children:(0,t.jsx)($,{size:"lg",className:"w-full rounded-full px-6",onClick:l,disabled:n||a,children:(0,t.jsxs)(Rl.span,{className:"flex items-center whitespace-nowrap",initial:{opacity:0},animate:{opacity:1},transition:Tit,children:[d==="spinner"?(0,t.jsx)(st,{className:"mr-1 size-4 animate-spin"}):null,c,d==="arrow"?(0,t.jsx)(pl,{className:"ml-1 size-3.5"}):null]},`${c}:${d}`)})})]})}r($z,"FooterNav");function s5e({companyId:e,adapterType:s,environmentId:n,canLogin:a,localEnvironment:i=!1,onConnected:o,onDraftChanged:l,onBack:c,testConnection:d,testError:u,managedAccount:h,advancedConnection:p}){const f=te({queryKey:D.health,queryFn:Lu.get,enabled:i}),x=i&&(f.data?.localAiLoginSupported??f.data?.deploymentMode==="local_trusted"),g=(0,m.useRef)(0);(0,m.useEffect)(()=>()=>{g.current++},[]);const v=r(()=>{g.current++,Q(!1),C(!1),R(null),T("preparing")},"cancel"),[y,k]=(0,m.useState)(h?.initialMethod==="api_key"?"api":h?"subscription":null),[w,N]=(0,m.useState)(!1),[S,C]=(0,m.useState)(!!(p||h)),[_,R]=(0,m.useState)(null),[I,T]=(0,m.useState)("preparing"),E=(0,m.useRef)("ready"),[P,O]=(0,m.useState)(""),[M,Q]=(0,m.useState)(!1),[L,F]=(0,m.useState)(null),[q,z]=(0,m.useState)(null),K=s==="claude_local"?"Claude":s==="grok_local"?"Grok":"OpenAI",U=s==="claude_local"?"ANTHROPIC_API_KEY":s==="grok_local"?"XAI_API_KEY":"OPENAI_API_KEY",V=s==="claude_local"?"anthropic":s==="grok_local"?"xai":"openai",ne=TCe(e,U),Z=h?{...ne,options:[],subscriptions:[],loading:!1}:ne,[ie,J]=(0,m.useState)(null),ae=Z.subscriptions.length?Z.subscriptions.find(Re=>Re.id===(ie??Z.subscriptions[0]?.id)):void 0,[oe,G]=(0,m.useState)(null),X=Z.options.find(Re=>Re.id===(oe??Z.options[0]?.id)),Y=h?{...Z.storedLogin,data:void 0,isPending:!1,isError:!1}:Z.storedLogin,re=(0,m.useRef)(null),se=y??(Z.subscriptions.length>0||s==="claude_local"&&!ae&&Y.data?"subscription":Z.options.length?"api":"subscription"),ce=se==="api"?"api_key":"subscription",pe=h?.intent.connectionId&&(h.fixedMethod!==!1||h.initialMethod===ce),fe=h?{...h.intent,connectionId:pe?h.intent.connectionId:void 0,name:pe?h.intent.name:h.nameForMethod?.(ce)??h.intent.name}:void 0,ve=G2e(e,fe??{provider:V,method:"subscription",name:`My ${K} subscription`,ownership:"personal",agentIds:[],allAgents:!0},!w&&x&&se==="subscription"&&!ae&&!Y.data),Ie=te({queryKey:D.agents.authSignal(e,s,n),queryFn:r(()=>Nt.getAdapterAuthSignal(e,s,n??void 0),"queryFn"),retry:!1,enabled:!h&&!w});async function de(){if(M||h?.disabled)return;const Re=++g.current;Q(!0),F(null);try{if(h&&fe){if(se==="subscription"&&!x)return;const _e=re.current??await(se==="api"?Ll.create(e,{...fe,method:"api_key",apiKey:P.trim()}):ve.connect(fe));re.current=_e,O(""),Re===g.current&&h.onComplete({..._e,method:se==="api"?"api_key":"subscription"});return}let Le=se==="api"?X?X.aiConnection?{env:{},aiConnection:X.aiConnection}:{env:{[U]:X.binding}}:q??{env:{},credentials:{[U]:P.trim()}}:{...ae?.aiConnection?{aiConnection:ae.aiConnection}:{},env:ae?.binding?{CODEX_HOME:ae.binding}:{},...s==="claude_local"&&!ae&&Y.data?{env:tk(),applyStoredClaudeLogin:!0}:{}};if(se==="subscription"&&x&&!ae&&!Y.data&&(re.current??=await ve.connect(),Le={env:{},aiConnection:{provider:V,method:"subscription",mode:"responsible_user"}}),Le.credentials&&(await Ll.create(e,{provider:V,method:"api_key",name:`My ${K} API`,ownership:"personal",apiKey:Le.credentials[U],agentIds:[],allAgents:!0}),Le={env:{},aiConnection:{provider:V,method:"api_key",mode:"responsible_user"}}),Re!==g.current)return;se==="api"&&(O(""),X||z(Le));const je=await d(Le);if(Re!==g.current)return;je?o(Le):F("The provider did not respond. Check the connection and try again.")}catch(Le){if(Re!==g.current)return;h&&O(""),F(Le instanceof Error?Le.message:"Could not connect to the provider.")}finally{Re===g.current&&Q(!1)}}r(de,"connect");const xe=se==="subscription"&&a&&n&&!ae&&!Z.loading&&!Y.data&&(!!h||Ie.data?.status!=="present"||ie===""),le=r(Re=>{p&&Re===(w?"advanced":se)||(l?.(),v(),N(Re==="advanced"),C(p?!0:S),re.current=null,Re!=="advanced"&&k(Re),O(""),z(null),F(null))},"switchMode");return(0,t.jsxs)("div",{className:"min-w-0 max-w-full",children:[(0,t.jsx)(e5e,{label:p?"Connection type":"Connect your model provider",sources:p?[{id:"subscription",label:K,icon:(0,t.jsx)(q0,{type:s}),credentialMode:"subscription"},{id:"api",label:K,icon:(0,t.jsx)(q0,{type:s}),credentialMode:"api"},{id:"advanced",label:"Advanced",icon:(0,t.jsx)(tKe,{className:"size-6 text-muted-foreground"}),credentialMode:"advanced"}]:[{id:s,label:K,icon:(0,t.jsx)(q0,{type:s})}],mode:w?"advanced":se,selectedId:p?w?"advanced":se:S?s:null,collapsed:!p&&S,onSelect:r(Re=>{h?.disabled||(p?le(Re):C(!0))},"onSelect")}),!p&&(!S||h)&&!h?.fixedMethod&&(0,t.jsx)("div",{className:"-ml-3 mt-1",children:(0,t.jsx)(t5e,{mode:se,onChange:le})}),w&&p?(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)("div",{className:"pt-5",children:p.content}),(0,t.jsx)($z,{onBack:c,primaryLabel:"Use connection",primaryDisabled:!p.value,onPrimary:r(()=>{p.value&&o({env:{},aiConnection:p.value})},"onPrimary")})]}):(0,t.jsxs)(t.Fragment,{children:[!S&&Z.options.length>0&&(0,t.jsxs)("p",{className:"mt-2 text-sm text-muted-foreground",children:[Z.options.length," saved API"," ",Z.options.length===1?"key available":"keys available","."]}),se==="subscription"&&Z.subscriptions.length>0&&(0,t.jsx)("div",{className:p?"pt-5":void 0,children:(0,t.jsx)(Ak,{options:Z.subscriptions,value:ae?.id??"",onChange:r(Re=>{l?.(),J(Re)},"onChange"),loading:!1,error:!1,kind:"subscription",disabled:M})}),(0,t.jsx)(Rl.div,{initial:!1,animate:{height:S?"auto":0,opacity:S?1:0},transition:{height:Yd,opacity:gM},className:"overflow-hidden",children:S&&(0,t.jsx)("div",{className:"pt-5",children:se==="api"?(0,t.jsxs)(bM,{instruction:Z.options.length?"Choose a saved API key or enter a new one":`Provide your ${K} API key to connect`,children:[(0,t.jsx)(Ak,{...Z,value:X?.id??"",disabled:M,onChange:r(Re=>{l?.(),G(Re),O(""),z(null),F(null)},"onChange")}),!X&&(0,t.jsx)(V3,{label:"API key",masked:!0,autoFocus:!0,value:P,placeholder:q?"Key entered. Retry the connection.":"Enter API key here",onChange:r(Re=>{l?.(),G(""),O(Re),z(null)},"onChange"),onSubmit:r(()=>{de()},"onSubmit"),disabled:M})]}):xe?(0,t.jsx)(SV,{companyId:e,adapterType:s,environmentId:n,chrome:"onboarding",aiConnection:fe??{provider:V,method:"subscription",name:`My ${K} subscription`,ownership:"personal",agentIds:[],allAgents:!0},autoStart:!0,onStored:r(()=>{},"onStored"),onPromptReady:r(Re=>{R(Re),T(Le=>Re?Le==="preparing"?"ready":Le:"preparing")},"onPromptReady"),onCodeSubmitted:r(()=>{E.current=I==="waiting"?"waiting":"ready",T("connecting")},"onCodeSubmitted"),onSubmitFailed:r(()=>{T(Re=>Re==="connecting"?E.current:Re)},"onSubmitFailed"),onConnected:r(Re=>{if(h){if(!Re){F("The login did not return a saved connection. Try again.");return}const je=g.current;T("connecting"),Ll.loginResult(e,Re).then(_e=>{je===g.current&&h.onComplete({..._e,method:"subscription"})}).catch(()=>{je===g.current&&(T("ready"),F("Could not retrieve the saved connection. Go back and retry."))});return}const Le={env:{},aiConnection:{provider:V,method:"subscription",mode:"responsible_user"}};z(Le),o(Le)},"onConnected")}):ae?null:x&&!Y.data?(0,t.jsx)(xV,{adapterType:s,login:{...ve,retry:r(()=>{F(null),ve.retry()},"retry")}}):(0,t.jsx)("p",{className:"text-sm text-muted-foreground",children:Y.data?"Use your saved Claude subscription for this agent.":a?"Use the existing provider connection for this environment.":"This environment does not support browser sign-in. Choose a sign-in environment or connect with an API key."})})}),se==="subscription"&&Y.isError&&(0,t.jsx)("p",{role:"alert",className:"mt-4 text-sm text-destructive",children:"Could not check your saved Claude subscription. Try again."}),L&&(0,t.jsx)("p",{role:"alert",className:"mt-4 text-sm text-destructive",children:u??L}),i&&f.isError&&(0,t.jsx)("p",{role:"alert",className:"mt-4 text-sm text-destructive",children:"Could not prepare sign-in. Reload this page to try again."}),(0,t.jsx)($z,{onBack:r(()=>{S&&!p?v():c()},"onBack"),primaryLabel:S&&xe?I==="waiting"?"Waiting for code":I==="connecting"?"Connecting":`Sign in to ${K}`:M?"Connecting":se==="subscription"&&(Y.data||ae)?"Use saved subscription":se==="api"&&X?"Use saved API key":"Connect",primaryDisabled:h?.disabled||!!h&&se==="subscription"&&!a&&!x||i&&f.isPending||ve.preparing||!!ve.error||se==="subscription"&&x&&!ae&&!Y.data&&ve.status!=="ready"||!h&&Ie.isPending||Z.loading||s==="claude_local"&&Y.isPending||!S&&!(se==="subscription"&&ae)||!!xe&&(!_||I!=="ready")||se==="api"&&!P.trim()&&!q&&!X,loading:M,primaryIcon:S&&xe?I==="ready"?"none":"spinner":void 0,onPrimary:r(()=>{if(xe){if(!_||I!=="ready")return;window.open(_,"_blank","noreferrer,noopener"),T("waiting")}else de()},"onPrimary")})]})]})}r(s5e,"AgentProviderConnection");function v5(e){return e.provider==="openrouter"||e.provider==="google"?(0,t.jsx)(amt,{...e}):(0,t.jsx)(rmt,{...e})}r(v5,"AiConnectionCredentialStep");function rmt({companyId:e,provider:s,initialMethod:n,fixedMethod:a,connectionId:i,name:o,hideName:l,nameForMethod:c,ownership:d,agentIds:u,allAgents:h,environmentId:p,onComplete:f,onCancel:x,defaults:g,disabled:v}){const[y,k]=(0,m.useState)(o),[w,N]=(0,m.useState)(),S=wt(),C=te({queryKey:D.environments.list(e),queryFn:r(()=>$i.list(e),"queryFn")}),_=te({queryKey:D.environments.capabilities(e),queryFn:r(()=>$i.capabilities(e),"queryFn")}),R=te({queryKey:D.instance.settings,queryFn:jr.get}),I=te({queryKey:D.instance.experimentalSettings,queryFn:jr.getExperimental}),T=te({queryKey:D.instance.generalSettings,queryFn:jr.getGeneral}),E=NV(T.data?.executionMode,C.data??[]);let P=null,O;try{P=E.forced?E.kubernetesEnvironment?.id??null:vN({agentDefaultEnvironmentId:p??w,instanceDefaultEnvironmentId:R.data?.defaultEnvironmentId,localDefaultEnvironmentId:jN(C.data),managedSandboxOnly:I.data?.enableManagedSandboxOnly,managedSandboxEnvironmentId:yN(C.data),visibleEnvironmentIds:C.data?.map(U=>U.id)})}catch(U){O=U instanceof Error?U.message:"Could not resolve the sign-in environment."}const M=(C.data??[]).filter(U=>U.status==="active"&&(U.driver==="local"||U.driver==="sandbox"&&typeof U.config.provider=="string"&&_.data?.sandboxProviders?.[U.config.provider]?.supportsLoginPty===!0));!E.forced&&!p&&!w&&!M.some(U=>U.id===P)&&(P=M[0]?.id??null);const Q=C.data?.find(U=>U.id===P),L=typeof Q?.config.provider=="string"?Q.config.provider:"",F=Q?.driver==="sandbox"&&_.data?.sandboxProviders?.[L]?.supportsLoginPty===!0,q=[C,_,R,I,T].some(U=>U.isPending),z=O??[C,_,R,I,T].find(U=>U.error)?.error?.message,K={provider:s,method:"subscription",name:y,ownership:d,agentIds:u,allAgents:h,connectionId:i};return(0,t.jsxs)("div",{className:"mx-auto w-full min-w-0 max-w-xl space-y-6",children:[!l&&(0,t.jsxs)("label",{className:"block space-y-2 text-sm",children:["Connection name",(0,t.jsx)(dt,{value:y,onChange:r(U=>k(U.target.value),"onChange"),disabled:!!i})]}),!p&&!E.forced&&M.length>1&&(0,t.jsxs)(Ca,{value:P??"",onValueChange:N,children:[(0,t.jsx)(Na,{"aria-label":"Sign-in environment",children:(0,t.jsx)(Sa,{placeholder:"Sign-in environment"})}),(0,t.jsx)(_a,{children:M.map(U=>(0,t.jsx)(un,{value:U.id,children:U.name},U.id))})]}),z&&(0,t.jsx)("p",{role:"alert",className:"text-sm text-destructive",children:z}),g,q?(0,t.jsx)("p",{role:"status",className:"text-sm text-muted-foreground",children:"Preparing sign-in…"}):(0,t.jsx)(s5e,{companyId:e,adapterType:s==="anthropic"?"claude_local":s==="xai"?"grok_local":"codex_local",environmentId:P,canLogin:F,localEnvironment:Q?.driver==="local",onBack:x,onConnected:r(()=>{},"onConnected"),testConnection:r(async()=>!1,"testConnection"),managedAccount:{intent:K,nameForMethod:c,initialMethod:n,fixedMethod:a??!!i,disabled:v||q||!!z||!y.trim(),onComplete:r(U=>{S.invalidateQueries({queryKey:["ai-connections",e]}),S.invalidateQueries({queryKey:["tools"]}),f(U)},"onComplete")}},P??"local")]})}r(rmt,"SubscriptionConnectionStep");function amt({companyId:e,provider:s,connectionId:n,name:a,hideName:i,nameForMethod:o,ownership:l,agentIds:c,allAgents:d,onComplete:u,onCancel:h,defaults:p,disabled:f}){const[x,g]=(0,m.useState)(a),[v,y]=(0,m.useState)(""),k=wt(),w=we({mutationFn:r(()=>Ll.create(e,{provider:s,method:"api_key",name:n?x:o?.("api_key")??x,ownership:l,agentIds:c,allAgents:d,connectionId:n,apiKey:v}),"mutationFn"),onSuccess:r(N=>{k.invalidateQueries({queryKey:["ai-connections",e]}),k.invalidateQueries({queryKey:["tools"]}),u({...N,method:"api_key"})},"onSuccess"),onSettled:r(()=>y(""),"onSettled")});return(0,t.jsxs)("div",{className:"mx-auto w-full min-w-0 max-w-xl space-y-4",children:[!i&&(0,t.jsxs)("label",{className:"block space-y-2 text-sm",children:["Connection name",(0,t.jsx)(dt,{value:x,onChange:r(N=>g(N.target.value),"onChange"),disabled:!!n})]}),w.error&&(0,t.jsx)("p",{role:"alert",className:"text-sm text-destructive",children:w.error.message}),(0,t.jsx)(n_e,{providerName:s==="google"?"Google":"OpenRouter",value:v,onChange:y,onSubmit:r(()=>w.mutate(),"onSubmit"),disabled:f||w.isPending,placeholder:"Enter API key here",autoFocus:!0}),p,(0,t.jsxs)("div",{className:"flex justify-between gap-2",children:[(0,t.jsx)($,{variant:"ghost",onClick:h,children:"Cancel"}),(0,t.jsx)($,{disabled:f||!x.trim()||!v.trim()||w.isPending,onClick:r(()=>w.mutate(),"onClick"),children:w.isPending?"Connecting…":"Connect"})]})]})}r(amt,"ApiKeyConnectionStep");var imt=null;function sw(){const e=(0,m.useContext)(c3),{data:s,isFetched:n,isError:a}=te({queryKey:D.instance.experimentalSettings,queryFn:r(()=>jr.getExperimental(),"queryFn"),enabled:e!=null},e??(imt??=new e2));return e?{enabled:!a&&s?.enableChatConnectors===!0,githubEnabled:!a&&s?.enableGitHubReviewBots===!0,loaded:n}:{enabled:!1,githubEnabled:!1,loaded:!0}}r(sw,"useChatConnectorsEnabled");function Jp(e,s,n){return e==="agentmail"||(e==="github"||e==="github-code-review-bot"?n:s)}r(Jp,"chatProviderVisible");var omt=new RegExp(`\\b(${["mcp","server","profile","policy","gateway","transport","stdio","endpoint"].join("|")})s?\\b`,"gi");function n5e(e){return e.replace(omt,"").replace(/\s{2,}/g," ").replace(/\s+([.,])/g,"$1").trim()}r(n5e,"sanitizeProsumerCopy");var lmt={zapier:{tagline:"Reach 9,000+ apps your team already uses.",short:"Reach 9,000+ apps from your agents."},github:{tagline:"Read code and pull requests, comment on issues.",short:"Read code and pull requests, comment on issues."},slack:{tagline:"Send and read messages in your team's channels.",short:"Send and read messages in your channels."},notion:{tagline:"Read and update pages in your workspace.",short:"Read and update pages in your workspace."},railway:{tagline:"Inspect services, read logs, and manage deployments.",short:"Connect Railway for deployments, logs, and container access."},posthog:{tagline:"Explore product usage, errors, flags, and experiments.",short:"Sign in with PostHog. Project pinning and access controls are optional."},gauge:{tagline:"Track your brand in AI answers and run content workflows.",short:"Sign in with Gauge and pick an organization. API keys are optional."},neon:{tagline:"Manage Postgres projects, branches, and queries.",short:"Sign in with Neon. Project pinning and read-only mode are optional."},superagent:{tagline:"Review security findings and run red-team checks.",short:"Connect with a Superagent API key. Billable and destructive tools stay under action policies."},linear:{tagline:"Create, update and read tickets.",short:"Create, update and read tickets."},"google-sheets":{tagline:"Read and update selected spreadsheets.",short:"Read spreadsheets or update the files you choose."},gmail:{tagline:"Read mail and create drafts for your review.",short:"Read mail and create drafts for your review."},"google-drive":{tagline:"Find, read, and create files in Drive.",short:"Find, read, and create files in Drive."},"google-docs":{tagline:"Read and update documents.",short:"Read and update documents."},"google-slides":{tagline:"Read and update presentations.",short:"Read and update presentations."},"google-calendar":{tagline:"Review calendars and manage events.",short:"Review calendars and manage events."},"google-chat":{tagline:"Read conversations and send messages.",short:"Read conversations and send messages."},"google-people":{tagline:"Look up contacts and people in your directory.",short:"Look up contacts and people in your directory."},"google-workspace-search":{tagline:"Search across your Google workspace.",short:"Search across your Google workspace."},hubspot:{tagline:"Look up contacts and update deal stages.",short:"Look up contacts and update deal stages."},intercom:{tagline:"Read and reply to customer conversations.",short:"Read and reply to customer conversations."},figma:{tagline:"Read files and post comments on frames.",short:"Read files and post comments on frames."},stripe:{tagline:"Read customers, invoices, and payouts.",short:"Read customers, invoices, and payouts."},context7:{tagline:"Look up up-to-date docs for your libraries.",short:"Look up up-to-date docs for your libraries."}},cmt={tagline:"Give your agents access to this app.",short:"Give your agents access to this app."};function r5e(e,s){const n=lmt[e];if(n)return n;if(s){const a=n5e(s);if(a)return{tagline:a,short:a}}return cmt}r(r5e,"appCopyFor");function aae(e,s,n){return n<=1?`Your ${e} key`:n5e(s)||`Your ${e} key`}r(aae,"credentialFieldLabel");var dmt=1500;function ep(e=dmt){const[s,n]=(0,m.useState)("idle"),a=(0,m.useRef)(null),i=(0,m.useRef)(0);(0,m.useEffect)(()=>()=>{a.current!==null&&window.clearTimeout(a.current)},[]);const o=(0,m.useCallback)(async l=>{const c=++i.current;let d="copied";try{await wa(l)}catch{d="failed"}return i.current!==c||(n(d),a.current!==null&&window.clearTimeout(a.current),a.current=window.setTimeout(()=>{i.current===c&&(n("idle"),a.current=null)},e)),d},[e]);return{status:s,copied:s==="copied",failed:s==="failed",copy:o}}r(ep,"useCopyAction");function kM(){const e=jd()?.pushToast;return(0,m.useCallback)(async(s,n="Copied")=>{try{return await wa(s),e?.({title:n,tone:"success",dedupeKey:`copy:${n}`}),!0}catch{return e?.({title:"Couldn’t copy to clipboard",body:"Select and copy the value manually.",tone:"error",dedupeKey:"copy-failed"}),!1}},[e])}r(kM,"useCopyToast");var umt="/cloud/connections/handoff",mmt="/cloud/connections/reauth",_E="paperclip.cloud-oauth-handoff.v1",Bx=class extends Error{static{r(this,"OAuthHandoffError")}code;constructor(e,s){super(e),this.code=s,this.name="OAuthHandoffError"}};function _V(e){if(e===void 0)return null;if(!e||typeof e!="object"||Array.isArray(e))throw new Bx("Paperclip Cloud returned an invalid sign-in handoff.","invalid_handoff");const s=e;if(s.kind!=="paperclip_cloud"||typeof s.session!="string"||s.session.length<16||s.session.length>512||!/^[A-Za-z0-9_-]+$/.test(s.session))throw new Bx("Paperclip Cloud returned an invalid sign-in handoff.","invalid_handoff");return{kind:"paperclip_cloud",session:s.session}}r(_V,"parseHandoff");function hmt(e,s){return e===404||s==="SESSION_NOT_AVAILABLE"?new Bx("This sign-in expired. Start the connection again.","expired"):e===401||e===403?new Bx("Paperclip Cloud could not authorize this connection for your account.","forbidden"):new Bx("Paperclip Cloud couldn’t prepare secure sign-in. Try again.","unavailable")}r(hmt,"handoffFailure");async function pmt(e,s){const n=s.request??fetch;let a,i;for(let o=0;o<2;o+=1)try{if(a=await n(umt,{method:"POST",headers:{"content-type":"application/json",accept:"application/json"},credentials:"include",body:JSON.stringify({session:e}),signal:s.signal}),a.status<500||o===1)return a}catch(l){if(s.signal?.aborted||l instanceof DOMException&&l.name==="AbortError")throw l;if(i=l,o===1)break}if(a)return a;throw new Bx(i instanceof Error?i.message:"Paperclip Cloud couldn’t prepare secure sign-in. Try again.","unavailable")}r(pmt,"postCloudHandoff");function fmt(e,s){if(typeof e!="string"||typeof window>"u")return null;try{const n=new URL(e,window.location.origin);return n.origin!==window.location.origin||n.pathname!==mmt||n.username||n.password||n.hash||n.searchParams.size!==1||n.searchParams.get("session")!==s?null:{kind:"reauthentication",url:n.toString(),host:n.host}}catch{return null}}r(fmt,"exactReauthenticationTarget");async function SN(e,s={}){const n=_V(e.handoff);if(!n){const l=tE(e.authorizationUrl);if(!l.ok)throw new Bx(l.message,"invalid_handoff");return{kind:"authorization",url:l.url,host:l.host}}const a=await pmt(n.session,s),i=await a.json().catch(()=>null);if(!a.ok){if(i?.error==="RECENT_LOGIN_REQUIRED"){const l=fmt(i.reauthenticationUrl,n.session);if(l)return l}throw hmt(a.status,i?.error)}const o=tE(typeof i?.authorizationUrl=="string"?i.authorizationUrl:void 0);if(!o.ok)throw new Bx("Paperclip Cloud returned an invalid provider sign-in address.","invalid_handoff");return{kind:"authorization",url:o.url,host:o.host}}r(SN,"prepareOAuthNavigation");function y5(e,s=window.sessionStorage){const n=_V({kind:"paperclip_cloud",session:e});if(!n)throw new Bx("Paperclip Cloud returned an invalid sign-in handoff.","invalid_handoff");const a={version:1,session:n.session,savedAt:Date.now()};s.setItem(_E,JSON.stringify(a))}r(y5,"savePendingCloudHandoff");function xmt(e=window.sessionStorage){const s=e.getItem(_E);if(!s)return null;try{const n=JSON.parse(s);if(n.version!==1||typeof n.savedAt!="number"||Date.now()-n.savedAt>9e5)throw new Error("expired");return _V({kind:"paperclip_cloud",session:n.session})}catch{return e.removeItem(_E),null}}r(xmt,"readPendingCloudHandoff");function iae(e=window.sessionStorage){e.removeItem(_E)}r(iae,"clearPendingCloudHandoff");function NM(e){return!!(e&&Uge({...e,methods:e.methods.filter(s=>(s.purpose??"tool")!=="channel"&&s.transport!=="chat_sdk")}))}r(NM,"appSupportsToolCatalogSetup");var gmt=O$e.filter(e=>Bge(e).some(s=>T0(s))).map(e=>e.slug);function bmt(e){return gmt.some(s=>s===e)}r(bmt,"isMcpDirectOAuthConnectSlug");function j5(e,s){const n=new URLSearchParams({source:e});return s&&n.set("intent",s),`/apps/connect?${n.toString()}`}r(j5,"appSourceConnectHref");function oae(e,s){return`/apps/connect?${new URLSearchParams({source:e,resume:s}).toString()}`}r(oae,"appSourceResumeHref");function oD(e){return e?`/apps/vercel-connect?${new URLSearchParams({source:e}).toString()}`:"/apps/vercel-connect"}r(oD,"vercelConnectSourceHref");function vmt(e){return e.serviceSlug??e.appKey??e.sourceSlug??void 0}r(vmt,"resolveAppsConnectRouteKey");function ymt(e,{chatConnectorsEnabled:s=!1,githubReviewBotsEnabled:n=!1}={}){if(e.get("byo")==="1")return!!(e.get("reconnect")?.trim()&&e.get("applicationId")?.trim()&&e.get("link")?.trim());const a=e.get("source")??"";if(["google-ai","gateway"].includes(a)||/^ai-router-(?:[a-f0-9]{2})+$/.test(a))return!0;const i=GN(a),o=a==="github-code-review-bot"?n:s;return!o&&i?.methods.some(l=>l.transport==="chat_sdk")&&!i.methods.some(l=>(l.purpose??"tool")!=="channel"&&l.transport!=="chat_sdk")?!1:cj(a)&&(e.get("reconnect")?.trim()||e.get("resume")?.trim())?!0:a==="agentmail"||o?Uge(i):NM(i)}r(ymt,"canEnterAppsConnect");var lD=" for the organization",jmt=" for the company";function lae(e,s){const n=e.trim();if(s!=="organization")return n;const a=n.toLocaleLowerCase();return a.endsWith(lD)?n:a.endsWith(jmt)?`${n.slice(0,n.length-16).trimEnd()}${lD}`:`${n}${lD}`}r(lae,"connectionNameForGrantKind");function wmt(e){switch(e){case"active":return"Connected";case"needs_reauthorization":return"Needs attention";case"expired":return"Expired";case"revoked":return"Revoked";default:return"Not connected"}}r(wmt,"grantStatusLabel");function kmt(e){switch(e){case"active":return"connected";case"needs_reauthorization":case"expired":return"attention";case"revoked":return"inactive";default:return"missing"}}r(kmt,"grantStatusTone");function Nmt(e,s={}){const n=e?.providerTenant?.name?.trim();return n||(e?.kind==="user"?s.subjectLabel?.trim()||"Connected account":e?.kind==="agent"?s.subjectLabel?.trim()||"Dedicated account":"Shared credential")}r(Nmt,"grantAccountLabel");function Smt(e){return new Set((e?.members??[]).filter(s=>s.subjectType==="user").map(s=>s.subjectId))}r(Smt,"audienceUserIds");function Cmt(e){return e.find(s=>s.kind==="organization"&&s.isDefault)??e.find(s=>s.kind==="organization")??null}r(Cmt,"organizationGrant");function _mt(e,s){return s?e.find(n=>n.kind==="user"&&n.subjectUserId===s)??null:null}r(_mt,"personalGrantFor");function Amt(e,s){if(!s)return null;const n=e.find(a=>a.userId===s);return n&&(n.name?.trim()||n.email?.trim())||null}r(Amt,"memberLabel");var cae=0;function Oz(){return cae+=1,{id:`header-${cae}`,name:"",value:""}}r(Oz,"newCustomHeaderRow");function d_(e){try{return new URL(e).host||null}catch{return null}}r(d_,"endpointHost");function Imt(e=window.location.origin,s){if(s)return s;const n=new URL("/api/tools/oauth/callback",e),a=n.hostname.toLowerCase().replace(/^\[|\]$/g,"");return n.protocol==="http:"&&(a==="127.0.0.1"||a==="::1")&&(n.hostname="localhost"),n.toString()}r(Imt,"oauthCallbackUrlForBrowser");function cD(e){try{const s=new URL(e);return`${s.host.replace(/^www\./,"")}${s.pathname==="/"?"":s.pathname.replace(/\/+$/,"")}`.slice(0,160)||null}catch{return null}}r(cD,"defaultGenericMcpName");function dae(e,s){const n=s?.trim()||"Paperclip couldn't connect to that address. Check it and try again.";switch(e){case"mcp_remote_url_missing":case"mcp_remote_url_invalid":return{title:"That doesn't look like a server address",body:"Paste the full address, starting with https:// — for example https://mcp.example.com/mcp.",focus:"url"};case"remote_http_private_endpoint":return{title:"That address is inside a private network",body:"This Paperclip is reachable from the internet, so it won't call addresses on your local network. Use the server's public address instead.",focus:"url"};case"remote_http_dns_failed":return{title:"We couldn't find that host",body:"The address didn't resolve. Check the spelling, or confirm the server is published on the internet.",focus:"url"};case"mcp_header_rejected":return{title:"Paperclip can't send that header",body:n,focus:"credentials"};case"tool_access_name_conflict":return{title:"Paperclip couldn’t name this connection",body:"Try connecting again.",focus:"none"};case"oauth_challenge":return{title:"This server wants a credential",body:"It asked us to authenticate but didn't offer a sign-in Paperclip can complete on its own. Add the key or headers its docs list under Advanced authentication.",focus:"credentials"};case"oauth_manual_client_required":case"oauth_manual_client_rebinding_required":return{title:"This server needs sign-in details you create yourself",body:"Register Paperclip in the provider's settings, then add the client ID and secret it gives you under Advanced authentication.",focus:"credentials"};case"oauth_redirect_origin_unsupported":case"oauth_redirect_uri_invalid":return{title:"This Paperclip needs a public HTTPS address first",body:"Sign-in sends the operator back to Paperclip, so this instance has to be reachable over HTTPS. Ask your Paperclip admin to configure it.",focus:"deployment"};case"runtime_error":return{title:"We couldn't reach that server",body:"Nothing answered at that address. Confirm the server is running and the address is right, then try again.",focus:"url"};default:return{title:"Paperclip couldn't connect",body:n,focus:"none"}}}r(dae,"genericConnectGuidance");function a5e(e){const s=new Set;for(const n of e){const a=n.name.trim();if(!a&&!n.value.trim())continue;const i=OOe(a);if(!i.ok)return Mee(a,i.reason);const o=gOe(n.value);if(!o.ok)return Mee(a,o.reason);if(!n.value.trim())return`Add a value for "${a}", or remove the row.`;const l=a.toLowerCase();if(s.has(l))return`"${a}" is listed twice.`;s.add(l)}return null}r(a5e,"customHeaderError");function Tmt(e){const s={},n=e.keyValue.trim();if((e.authMode==="bearer"||e.authMode==="auto"&&e.needsKey)&&n&&(s["credentials.authorization"]=n),e.authMode==="custom_headers")for(const l of e.headers){const c=l.name.trim();!c||!l.value.trim()||(s[`headers.${c}`]=l.value)}const a=e.name.trim(),i=e.oauthClientId.trim(),o=e.oauthClientSecret.trim();return{link:e.link,...a?{name:a}:{},...e.authMode==="auto"?{}:{authMode:e.authMode},...Object.keys(s).length>0?{credentialValues:s}:{},...e.authMode==="oauth"&&i?{oauthClient:{clientId:i,...o?{clientSecret:o}:{}}}:{}}}r(Tmt,"genericConnectPayload");function Rmt(e){return e.link.trim()?e.authMode==="auto"?!e.needsKey||e.keyValue.trim().length>0:e.authMode==="bearer"?e.keyValue.trim().length>0:e.authMode==="custom_headers"?e.headers.filter(s=>s.name.trim()&&s.value.trim()).length>0&&a5e(e.headers)===null:!0:!1}r(Rmt,"canSubmitGenericConnect");function CN(e){const s=new Set;let n=!1;for(const a of e??[])a.targetType==="company"?n=!0:a.targetType==="agent"&&s.add(a.targetId);return{onAll:n,agentIds:s}}r(CN,"installStateFrom");function i5e(e,s){return e.onAll||e.agentIds.has(s)}r(i5e,"isAgentInstalled");function o5e(e,s){return s.onAll?[{targetType:"company",targetId:e}]:[...s.agentIds].map(n=>({targetType:"agent",targetId:n}))}r(o5e,"installPayload");var Emt="Has access — tick to load its tools into this agent's context.";function l5e(e){return`paperclip.connector-enrollment-access:${e}`}r(l5e,"enrollmentAccessStorageKey");function Lmt(e){if(!e||typeof e!="object"||Array.isArray(e))return!1;const s=e;if(typeof s.companyId!="string"||!s.companyId.trim()||!(s.grantKind==="user"||s.grantKind==="agent"||s.grantKind==="organization")||s.installChoice!=="specific"&&s.installChoice!=="all"||!Array.isArray(s.agentIds)||s.agentIds.some(a=>typeof a!="string"||!a.trim()))return!1;const n=new Set(s.agentIds);return n.size!==s.agentIds.length?!1:s.grantKind==="agent"?s.installChoice==="specific"&&n.size===1:s.installChoice==="all"?n.size===0:n.size>0}r(Lmt,"validEnrollmentAccessState");function Mmt(e,s,n){try{window.sessionStorage.setItem(l5e(s),JSON.stringify({...n,companyId:e}))}catch{}}r(Mmt,"saveEnrollmentAccessState");function Pmt(e){const s=l5e(e);try{const n=window.sessionStorage.getItem(s);if(window.sessionStorage.removeItem(s),!n)return null;const a=JSON.parse(n);return Lmt(a)?a:null}catch{return null}}r(Pmt,"consumeEnrollmentAccessState");function uae(e){if(!e)return null;try{const s=new URL(e);return s.protocol==="https:"&&s.hostname.toLowerCase()==="github.com"?s.toString():null}catch{return null}}r(uae,"githubRecoveryUrl");function mae(e,s){return e==="denied"?"Authorization was cancelled or declined. Your saved connection was not changed.":s==="github_installation_required"?"GitHub access is required. Install Paperclip and grant at least one repository, then try again.":"Authorization did not complete. Your saved connection is still here, so you can try again."}r(mae,"oauthCallbackErrorMessage");var Dmt={key:"setup",success:"complete"};function hae(e){return e.requestedAppKey||e.hasPrefilledLink||e.zapierSource?"key":"gallery"}r(hae,"requestedConnectionInitialStep");function $mt(e){const s=e.galleryApps.find(a=>a.slug===e.requestedAppKey);if(s)return s;if(c5e({requestedAppKey:e.requestedAppKey,resumeConnection:e.resumeConnection,resumeApplication:e.resumeApplication,completedResumeConnectionId:e.completedResumeConnectionId}))return cj(e.requestedAppKey);if(!e.reconnectConnection)return null;const n=e.applications.find(a=>a.id===e.reconnectConnection?.applicationId);return yf(n)!==e.requestedAppKey?null:cj(e.requestedAppKey)}r($mt,"requestedConnectionEntry");function c5e(e){const{requestedAppKey:s,resumeConnection:n,resumeApplication:a,completedResumeConnectionId:i}=e;return!!(n&&(n.status==="draft"||n.status==="active"&&n.id===i)&&a&&n.applicationId===a.id&&n.companyId===a.companyId&&yf(a)===s&&bu(n)===s)}r(c5e,"retainedResumeMatches");function Omt(e){return!e.reconnectConnection||!e.reconnectApplication||e.reconnectConnection.applicationId!==e.reconnectApplication.id?!1:e.requestedAppKey?yf(e.reconnectApplication)===e.requestedAppKey:e.byo&&e.applicationId===e.reconnectApplication.id}r(Omt,"retainedReconnectMatches");function Bmt(e){return e.credentialSource==="vercel_connect"&&!e.available&&!e.retainedReconnectMatches}r(Bmt,"isVercelConnectUnavailable");function Fmt(e){return e.available===!1&&!(e.reconnectConnectionId&&e.reconnectSourceMatches)}r(Fmt,"isConnectionDefinitionUnavailable");function zmt(e){return!e.hasRequestedEntry||e.supportedMethodCount===0||e.unsupportedOAuth||e.vercelUnavailable||e.definitionUnavailable?e.reconnectConnectionId?"reconnect_unavailable":"fallback":"ready"}r(zmt,"requestedConnectionSetupResolution");function pae(e,s,n,a){const i=Dmt[s]??"setup",o=new URLSearchParams({source:e,stage:i});return a?.resumeConnectionId&&o.set("resume",a.resumeConnectionId),a?.reconnectConnectionId&&o.set("reconnect",a.reconnectConnectionId),a?.interactionId&&o.set("intent",a.interactionId),a?.connectionMethodKey&&o.set("method",a.connectionMethodKey),`${n==="vercel_connect"?"/apps/vercel-connect":"/apps/connect"}?${o.toString()}`}r(pae,"appConnectHref");function RI(e,s){if(!s)return e;const[n,a=""]=e.split("?",2),i=new URLSearchParams(a);return i.set("intent",s),`${n}?${i.toString()}`}r(RI,"withConnectionIntent");var fae=["Pick app","Add your key"],xae={gallery:0,key:1},qmt={key:0},Umt=["Add MCP URL"],Kmt=["Sign in"];function dD(e,s=!1){return s&&e?.auth!=="none"&&(!e?.grantKinds||e.grantKinds.includes("user"))?"user":e?.grantKinds?.length===1||e?.grantKinds&&!e.grantKinds.includes("organization")?e.grantKinds[0]:"organization"}r(dD,"defaultGrantKindFor");function Qmt(e){const s=e.config?.oauth;if(!s||typeof s!="object"||Array.isArray(s))return;const n=s.connectorSubjectAgentId;return typeof n=="string"?n:void 0}r(Qmt,"configuredAgentIdentity");function CC(e,s){const n=typeof s=="string"?s:s?.key;return e?.slug==="google-sheets"&&n==="local"}r(CC,"isGoogleSheetsRobotMethod");function LS(e){return e?Object.fromEntries([...e.tenantFields??[],...e.extensionFields??[]].filter(s=>s.defaultValue!==void 0).map(s=>[s.key,s.defaultValue])):{}}r(LS,"defaultMethodConfig");function D1(e,s){if(!e)return[];const n=Z3(e);return s==="vercel_connect"?n.filter(a=>!!a.credentialSources?.vercelConnect):n}r(D1,"connectionMethodsForCredentialSource");function Z3(e){return Bge(e).filter(s=>(s.purpose??"tool")!=="channel")}r(Z3,"availableToolConnectionMethods");function EI(e,s){const n=Z3(e);return s?n.find(a=>a.key===s)??null:RQ(n)}r(EI,"availableToolConnectionMethod");function Rk(e){return RQ(e)}r(Rk,"recommendedSetupConnectionMethod");function gae(e){return Rk(e?e.methods.filter(s=>(s.purpose??"tool")==="tool"&&(s.oauthStrategy==="paperclip_cloud_connector"||s.oauthStrategy==="paperclip_id_connector")):[])}r(gae,"recommendedManagedConnectorMethod");function bae(e){if(!e)return!1;const s=Z3(e),n=s.length===1?s[0]:null;return!!(n&&T0(n)&&!XOe(n))}r(bae,"canUseAutomaticOAuthFastPath");function vae(e){if(!e)return null;const s=Z3(e),n=s.length===1?s[0]:null;return n&&T0(n)?n:null}r(vae,"automaticOAuthMethod");function Wmt(e){const s=e.metadata;if(!s)return null;const n=s.sourceTemplateKey??s.galleryKey;return typeof n=="string"?n:null}r(Wmt,"appSourceSlug");function Hmt(e){const s=e.config?.sourceTemplateKey??e.transportConfig.sourceTemplateKey;return typeof s=="string"?s:null}r(Hmt,"connectionSourceSlug");function yae(e,s,n,a={}){if(!e)return null;const i=new Set(s.filter(o=>o.status!=="archived"&&Wmt(o)===e&&(!a.applicationId||o.id===a.applicationId)).map(o=>o.id));return n.find(o=>{const l=a.applicationId?o.applicationId===a.applicationId:i.has(o.applicationId)||Hmt(o)===e;return o.status!=="archived"&&(!a.draftOnly||o.status==="draft")&&o.authKind==="oauth"&&l})??null}r(yae,"reusableOAuthConnection");function d5e(e,s,n){if(e.origin!==s||!e.data||typeof e.data!="object")return null;const a=e.data;return a.type!=="paperclip.connection-intent.oauth"||a.interactionId!==n?null:a.outcome==="connected"||a.outcome==="declined"||a.outcome==="failed"?a.outcome:null}r(d5e,"readConnectionIntentOAuthOutcome");function A2(e={}){const[s]=hi(),n=xa(),{selectedCompanyId:a}=fs(),i=SH(),o=e.interactionId||s.get("intent")||void 0,l=e.serviceSlug||s.get("source")||n.appKey||s.get("appKey"),c=(0,m.useMemo)(()=>{if(o&&YC(l))try{return sessionStorage.getItem(`paperclip:mcp-intent-draft:${a}:${o}`)}catch{}return null},[o,a,l]),d=e.configuredConnection?.id||s.get("resume")||s.get("reconnect")||c,u=!!(d&&(!l||YC(l)||DR(l))),h=te({queryKey:["tools","connection",d],queryFn:r(()=>ts.getConnection(d),"queryFn"),enabled:u}),p=l||h.data?.config?.sourceTemplateKey,f=s.get("method")||h.data?.config?.connectionMethodKey;if(u&&h.isPending)return(0,t.jsx)("p",{className:"p-6 text-sm text-muted-foreground",children:"Loading connection…"});if(u&&h.isError)return(0,t.jsxs)("div",{role:"alert",className:"space-y-3 p-6",children:[(0,t.jsx)("p",{children:"Could not load this connection. Your saved access and credentials have not changed."}),(0,t.jsx)($,{variant:"outline",onClick:r(()=>{h.refetch()},"onClick"),children:"Try again"})]});if(DR(p)&&!(h.data&&h.data.status!=="draft"&&h.data.config?.sourceTemplateKey===p)){if(!i.loaded)return(0,t.jsx)("p",{className:"p-6 text-sm text-muted-foreground",children:"Loading connection settings…"});if(!i.enabled)return(0,t.jsx)("p",{role:"status",className:"p-6 text-sm text-muted-foreground",children:"Enable memory connectors in Settings → Experimental to set up this connection."})}if(!e.byoOnly&&(e.credentialSource??"paperclip_vault")==="paperclip_vault"&&YC(p)&&(!f||FT(p,f))){const x=qge(p,s.get("targetToolkit"));return(0,t.jsx)(met,{...e,upstreamServiceName:e.upstreamServiceName??x?.name,interactionId:o,providerId:p,connection:h.data},`${o||"page"}:${p}`)}return(0,t.jsx)(Vmt,{...e})}r(A2,"ConnectionSetupFlow");function Vmt({additionalSettings:e,connectionSettings:s,additionalSettingsValid:n=!0,byoOnly:a=!1,credentialSource:i="paperclip_vault",host:o="page",serviceSlug:l,requestedAgentId:c,interactionId:d,forceNewConnection:u=!1,existingConnections:h=[],configuredConnection:p,onUseExisting:f,onComplete:x,onOAuthDeclined:g,aiConnection:v,requiredAiOwnership:y,onPhaseChange:k,onCancel:w,renderCredentialStep:N}={}){const S=wt(),C=Gn(),_=(0,m.useCallback)((ct,xs)=>{o==="page"&&(xs?C(ct,xs):C(ct))},[o,C]),R=xa(),{selectedCompany:I,selectedCompanyId:T}=fs(),{enabled:E,githubEnabled:P}=sw(),{enabled:O}=SH(),{setBreadcrumbs:M}=Vn(),{pushToast:Q}=Ti(),[L]=hi(),F=d?.trim()||L.get("intent")?.trim()||null,q=R.appKey??L.get("appKey")??void 0,z=L.get("source")?.trim()||null,K=u||L.get("new")==="1",U=L.get("stage")?.trim()||null,V=L.get("method")?.trim()||null,ne=L.get("resume")?.trim()||null,Z=L.get("oauth"),ie=L.get("code"),J=uae(L.get("installation_url")),ae=uae(L.get("management_url")),oe=p?.id??(L.get("reconnect")?.trim()||null),G=L.get("identity")==="user"?"user":L.get("identity")==="organization"?"organization":null,X=i==="vercel_connect",Y=l??z,re=i==="paperclip_vault"&&bmt(Y)?Y:null,se=vmt({serviceSlug:l,appKey:q,sourceSlug:z}),ce=(l??z??q)==="zapier",pe=ce?void 0:se,fe=!!p||o==="page"&&(a||L.get("byo")==="1"),[ve]=(0,m.useState)(()=>o==="page"&&L.get("cloud_connector")==="enrolled"&&pe?Pmt(pe):null),[Ie]=(0,m.useState)(()=>{const ct=L.get("link")?.trim()??"";return{link:/^https?:\/\//i.test(ct)?ct:"",name:p?.name??L.get("name")?.trim()??"",applicationId:p?.applicationId??(L.get("applicationId")?.trim()||void 0)}}),[de,xe]=(0,m.useState)(()=>hae({requestedAppKey:pe,routeStage:U,resumeConnectionId:ne,hasPrefilledLink:!!Ie.link,zapierSource:ce})),[le,Re]=(0,m.useState)(null),[Le,je]=(0,m.useState)(""),[_e,Ze]=(0,m.useState)(Ie.link),[ue,Fe]=(0,m.useState)(Ie.name||(ce?"Zapier":"")),[mt,bt]=(0,m.useState)(!1),[et,qe]=(0,m.useState)(""),[it,_t]=(0,m.useState)("auto"),[$t,Ot]=(0,m.useState)(()=>[Oz()]),[at,Me]=(0,m.useState)(""),[De,ut]=(0,m.useState)(""),[Pt,Rt]=(0,m.useState)(!1),[Qe,Be]=(0,m.useState)(null),[Oe,Pe]=(0,m.useState)(!1),[Ve,be]=(0,m.useState)({}),[nt,Lt]=(0,m.useState)(""),[Cs,lt]=(0,m.useState)(""),[Os,Ke]=(0,m.useState)(""),[ge,Xe]=(0,m.useState)(v&&v.mode!=="responsible_user"?`ai-${v.method}`:""),[xt,Ht]=(0,m.useState)(null),[ht,zt]=(0,m.useState)({}),[$e,he]=(0,m.useState)(""),[Vt,Dt]=(0,m.useState)(null),[ns,_s]=(0,m.useState)(null),[cn,mr]=(0,m.useState)({}),[pn,Bt]=(0,m.useState)("all"),[Ls,Ee]=(0,m.useState)(new Set),[jt,ze]=(0,m.useState)(()=>new Set(ve?.agentIds??(c?[c]:[]))),[St,Ut]=(0,m.useState)(ve?.grantKind??G??(c?"user":"organization")),[Ct,os]=(0,m.useState)(ve?.installChoice??(c?"specific":"all")),vs=!!(ne&&(Z==="failed"||Z==="denied")),[Bs,qs]=(0,m.useState)(vs?"error":"entry"),[Rn,Ns]=(0,m.useState)(()=>vs?mae(Z,ie):null),[Yn,Xt]=(0,m.useState)(null),Hs=(0,m.useRef)(!1),on=(0,m.useRef)(!1),Tt=(0,m.useRef)(null),as=(0,m.useRef)(null),[Xs,bs]=(0,m.useState)(null),[Zs,Nn]=(0,m.useState)(null),hr=(0,m.useRef)(null),[qn,qr]=(0,m.useState)(null),[Cr,pr]=(0,m.useState)(null),Cn=(0,m.useRef)(null),[Nr,Or]=(0,m.useState)(h.length>0&&!!f),[Ur,ga]=(0,m.useState)(null),[ar,ur]=(0,m.useState)(null),[gt,Ge]=(0,m.useState)(null),es=(0,m.useCallback)(()=>{o!=="dialog"||hr.current?.closed===!1||(hr.current=window.open("about:blank","paperclip-connection-oauth","popup,width=720,height=760,resizable=yes,scrollbars=yes"))},[o]),hs=(0,m.useCallback)(ct=>{if(o!=="dialog"){lh(ct);return}pr(ct);const xs=hr.current;if(!xs||xs.closed){qs("error"),Ns("Paperclip couldn’t open the sign-in window. Open sign-in in a new tab to continue."),k?.("needs_retry");return}xs.location.assign(ct),xs.focus()},[o,k]),As=(0,m.useCallback)(()=>{hr.current=null,Ns(null),qs("redirecting"),k?.("authorizing")},[k]);(0,m.useEffect)(()=>{if(o!=="dialog"||Bs!=="redirecting")return;const ct=window.setInterval(()=>{hr.current?.closed&&(qs("error"),Ns("The sign-in window closed. If authorization did not finish, try again."),pr(null),k?.("needs_retry"))},1e3);return()=>window.clearInterval(ct)},[o,Bs,k]);const ss=(0,m.useCallback)(async ct=>{Cn.current?.abort();const xs=new AbortController;Cn.current=xs;try{const Ws=await SN(ct,{signal:xs.signal});if(Ws.kind==="reauthentication"){const Sn=o==="dialog"?hr.current:window;if(!Sn||Sn.closed||!ct.handoff)throw new Error("Paperclip couldn’t preserve this sign-in while refreshing your account.");y5(ct.handoff.session,Sn.sessionStorage),qs("starting")}else Xt(Ws.host),qs("redirecting");hs(Ws.url)}catch(Ws){if(xs.signal.aborted)return;qs("error"),Ns(Ws instanceof Error?Ws.message:"Paperclip couldn’t start secure sign-in. Try again."),k?.("needs_retry")}finally{Cn.current===xs&&(Cn.current=null)}},[o,k,hs]);(0,m.useEffect)(()=>()=>Cn.current?.abort(),[]),(0,m.useEffect)(()=>{if(o!=="dialog"||!F)return;const ct=r(xs=>{const Ws=d5e(xs,window.location.origin,F);if(Ws==="connected"){qs("entry"),pr(null),x?.({resolvedByCallback:!0});return}if(Ws==="declined"){qs("error"),Ns("Authorization was cancelled. You can try again."),k?.("needs_retry");return}Ws==="failed"&&(qs("error"),Ns("Authorization did not complete. Try again when you’re ready."))},"receiveOAuthOutcome");return window.addEventListener("message",ct),()=>window.removeEventListener("message",ct)},[F,o,x,g]),(0,m.useEffect)(()=>{if(o!=="dialog"||F||!qn)return;let ct=!1,xs=!1;const Ws=window.setInterval(async()=>{if(xs||ct)return;const Sn=hr.current;if(!Sn||Sn.closed){qr(null),qs("error"),Ns("The sign-in window closed. Try again to finish connecting GitHub.");return}let Jn;try{Jn=new URL(Sn.location.href)}catch{return}if(!(Jn.origin!==window.location.origin||!Jn.pathname.includes(qn))){if(Jn.searchParams.has("oauth")){qr(null),qs("error"),Ns("Authorization did not complete. Finish setup in the sign-in window or try again.");return}if(Jn.searchParams.get("success")==="1"){xs=!0;try{const wn=await ts.getConnection(qn);!ct&&wn.status==="active"&&(qr(null),Sn.close(),x?.({connectionId:wn.id}))}catch{ct||(qr(null),qs("error"),Ns("Could not confirm the connection. Try again."))}finally{xs=!1}}}},1e3);return()=>{ct=!0,window.clearInterval(Ws)}},[F,qn,o,x]);const ks=r(()=>{_t("auto"),Ot([Oz()]),Me(""),ut(""),Rt(!1),Be(null),Pe(!1)},"resetGenericAuthState"),kn=r(ct=>{if(o==="page"&&!F&&i==="paperclip_vault"&&YC(ct.slug)){_(`/apps/connect?source=${ct.slug}`);return}if(ct.slug==="zapier"){Re(null),je(""),Ze(""),Fe("Zapier"),bt(!1),qe(""),ks(),be({}),_s(null),xe("key"),_(RI("/apps/connect?source=zapier",F));return}if(i==="paperclip_vault"&&bae(ct)){_(j5(ct.slug,F));return}Re(ct),je(ct.name),Ze(""),Fe(""),bt(!1),qe(""),ks(),be({}),Lt(""),lt(""),Ke("");const xs=Rk(D1(ct,i));Xe(xs?.key??""),zt(LS(xs)),he(""),Dt(null),_s(null),ze(new Set(c?[c]:[])),os(c?"specific":"all"),Ut(Te??dD(xs,!!c)),xe("key"),_(i==="vercel_connect"?RI(oD(ct.slug),F):j5(ct.slug,F))},"useMatchedGalleryEntry"),vn=r(()=>{xe("gallery"),_(RI(i==="vercel_connect"?oD():a?"/apps/byo":"/apps",F))},"backToGallery");(0,m.useEffect)(()=>{if(o==="page")return M([{label:"Connectors",href:"/apps"},{label:X?"Vercel Connect":a?"Connect your own tool":"Connect an app"}]),()=>M([])},[a,o,M,X]);const Un=te({queryKey:D.apps.gallery(T??"__none__"),queryFn:r(()=>ts.listGallery(T),"queryFn"),select:(0,m.useCallback)(ct=>F||v?{...ct,apps:ct.apps.map(xs=>({...xs,methods:xs.methods.filter(Ws=>v?Ws.ai?.provider===v.provider&&(v.mode==="responsible_user"||Ws.ai.method===v.method):Ws.transport!=="runtime_auth")})).filter(xs=>xs.methods.length>0)}:ct,[F,v?.provider,v?.method,v?.mode]),enabled:!!T}),pt=Imt(window.location.origin,Un.data?.oauthCallbackUrl),Is=(0,m.useMemo)(()=>(Un.data?.apps??[]).filter(ct=>O||!DR(ct.slug)).filter(ct=>Jp(ct.slug,E,P)||!ct.methods.some(xs=>xs.transport==="chat_sdk")||NM(ct)),[Un.data,E,P,O]),dn=pe?cj(pe):null,_n=dn?.methods.find(ct=>fk(ct)&&!T0(ct)),fn=!(_n&&ge===_n.key)&&!!dn?.methods.some(ct=>ct.oauthStrategy==="paperclip_cloud_connector"||ct.oauthStrategy==="paperclip_id_connector"),Sr=!!le?.methods.some(ct=>ct.oauthStrategy==="paperclip_cloud_connector"||ct.oauthStrategy==="paperclip_id_connector"),ia=le&&fn&&!Sr?gae(dn):null,[Da,Ts]=(0,m.useState)(null),ln=te({queryKey:["cloud-connector","enrollment"],queryFn:r(()=>ts.getCloudConnectorEnrollment(),"queryFn"),refetchInterval:Da?2e3:!1,enabled:!!(T&&fn&&!Sr)}),[Tr,Zn]=(0,m.useState)(null),Kn=(0,m.useCallback)(()=>{hr.current?.close(),hr.current=null,Ts(null)},[]),Wr=(0,m.useCallback)(()=>{!T||!pe||Mmt(T,pe,{grantKind:St,installChoice:Ct,agentIds:Ct==="specific"?[...jt]:[]})},[St,jt,Ct,pe,T]),Ms=(0,m.useCallback)(ct=>{const xs=tE(ct);if(!xs.ok){Kn(),Zn(xs.message);return}if(o==="dialog"){Ts(xs.url);const Ws=hr.current;Ws&&!Ws.closed?(Ws.location.assign(xs.url),Ws.focus()):Zn("Open authorization in a new tab to continue.");return}lh(xs.url)},[o,Kn]);(0,m.useEffect)(()=>{!Da||ln.data?.status!=="active"||(Kn(),Zn(null),Un.refetch())},[Da,ln.data?.status,Un.refetch,Kn]);const jn=we({mutationFn:r(()=>ts.startCloudConnectorEnrollment(T,I?.name,pe?pae(pe,"key",i,{resumeConnectionId:ne,reconnectConnectionId:oe,interactionId:F})+(o==="dialog"?"&enrollment_host=dialog":""):void 0),"mutationFn"),onSuccess:r(ct=>{if(!ct.verificationUrl){Kn(),Zn("Paperclip Cloud did not return an enrollment link. Try again.");return}Ms(ct.verificationUrl)},"onSuccess"),onError:r(ct=>{Kn(),Zn(ct instanceof Error?ct.message:"Paperclip couldn’t reach Paperclip Cloud. Try again.")},"onError")}),En=te({queryKey:D.tools.applications(T??"__none__"),queryFn:r(()=>ts.listApplications(T),"queryFn"),enabled:!!T&&(!!re||!!ne||!!oe),refetchOnMount:"always"}),zs=te({queryKey:D.tools.connections(T??"__none__"),queryFn:r(()=>ts.listConnections(T),"queryFn"),enabled:!!T&&(!!re||!!ne||!!oe),refetchOnMount:"always"}),rr=(0,m.useMemo)(()=>u?null:yae(re,En.data?.applications??[],zs.data?.connections??[],K?{applicationId:Ie.applicationId,draftOnly:!0}:{}),[En.data,zs.data,K,re,Ie.applicationId,u]),hn=(0,m.useMemo)(()=>oe?(zs.data?.connections??[]).find(ct=>ct.id===oe)??null:null,[zs.data,oe]),Jr=(0,m.useRef)(null);(0,m.useEffect)(()=>{if(!p||!zs.isFetchedAfterMount||!hn||Jr.current===hn.id)return;const ct=hn.config?.url??hn.transportConfig?.url??hn.transportConfig?.serverUrl??hn.config?.serverUrl;typeof ct!="string"||!/^https?:\/\//i.test(ct)||(Jr.current=hn.id,Ze(xs=>xs||ct))},[p,zs.isFetchedAfterMount,hn]);const Ae=(0,m.useMemo)(()=>hn?(En.data?.applications??[]).find(ct=>ct.id===hn.applicationId)??null:null,[En.data,hn]),Zt=Omt({requestedAppKey:pe,byo:fe,applicationId:Ie.applicationId,reconnectConnection:hn,reconnectApplication:Ae}),xn=(0,m.useMemo)(()=>ne?(zs.data?.connections??[]).find(ct=>ct.id===ne)??null:null,[zs.data,ne]),Dr=(0,m.useMemo)(()=>xn?(En.data?.applications??[]).find(ct=>ct.id===xn.applicationId)??null:null,[En.data,xn]),ba=U==="complete"&&xn?.status==="active"?xn.id:null,Fa=pe?c5e({requestedAppKey:pe,resumeConnection:xn,resumeApplication:Dr,completedResumeConnectionId:Zs??ba}):!1,ps=xn??hn,Te=ps?ps.credentialPolicy==="per_user"?"user":ps.credentialPolicy==="per_agent"?"agent":"organization":G,Wt=xn?.authKind==="oauth"?xn:rr,Jt=rr?rr.credentialPolicy==="per_user"?"user":rr.credentialPolicy==="per_agent"?"agent":"organization":null,Js=Te??Jt??(y==="shared"?"organization":null);(0,m.useEffect)(()=>{Js&&Ut(Js)},[Js]);const gn=(0,m.useMemo)(()=>_e&&!le?mR(_e,Is):null,[le,Is,_e]),_r=le?EI(le,ge||null):null,ti=_r&&T0(_r)?_r:vae(le),fr=i==="paperclip_vault"&&ti?le:null,Ta=i==="paperclip_vault"&&bae(le)?le:null,vi=!!re&&(!En.isFetchedAfterMount||!zs.isFetchedAfterMount),Ha=r(ct=>{xe(ct),le&&_(pae(le.slug,ct,i,{connectionMethodKey:le.methods.find(xs=>xs.key===ge)?.ai?ge:void 0,resumeConnectionId:ne,reconnectConnectionId:oe,interactionId:F}))},"setAppStep"),Er=xn??hn??Wt,Mi=le?.agentInstructions,ir=le&&Mi?xt?.slug===le.slug?xt.value:Er?Er.agentInstructions??{...rN(Mi),enabled:!1}:rN(Mi):null,Vi=!ir||!!ir.text.trim(),il=we({mutationFn:r(async ct=>(ir&&JSON.stringify(ir)!==JSON.stringify(ct.agentInstructions)&&await ts.updateConnection(ct.id,{agentInstructions:ir}),ts.startOAuth(ct.id,{asCurrentUser:ct.credentialPolicy==="per_user",...ct.credentialPolicy==="per_agent"?{asAgentId:Qmt(ct)??[...jt][0]}:{},...F?{interactionId:F}:{}})),"mutationFn"),onSuccess:r(ct=>{ss(ct)},"onSuccess"),onError:r(ct=>{const xs=ct instanceof nn&&ct.body&&typeof ct.body=="object"?ct.body.details:null;qs("error"),k?.("needs_retry"),Ns(xs?.code==="invalid_grant"?"Your authorization expired or was revoked. Reconnect to continue.":ct instanceof Error?ct.message:"Paperclip couldn’t start secure sign-in. Try again.")},"onError")}),So=il.mutate,eo=(0,m.useCallback)(ct=>{k?.("authorizing"),es(),o==="dialog"&&!F&&qr(ct.id),So(ct)},[So,k,es,o,F]),ye=r(async ct=>{if(c)return;const xs=o5e(T,(Js??St)!=="agent"&&Ct==="all"?{onAll:!0,agentIds:new Set}:{onAll:!1,agentIds:jt});await ts.putConnectionInstalls(ct,xs)},"applyAccessInstalls"),ft=Js??St,ds=we({mutationFn:r(async ct=>{const xs=ct??le;let Ws;if(xs){const Sn=Js??St,Jn=EI(xs,ge||null),wn=CC(xs,Jn)?zF($e).ids:[],ca=Le.trim(),Ga=lae(ca||xs.name,Sn);Ws=await ts.connectApp(T,{galleryKey:xs.slug,...ir?{agentInstructions:ir}:{},...ge?{connectionMethodKey:ge}:{},name:Ga,credentialSource:i,...i==="paperclip_vault"?{credentialValues:Ve}:{},...i==="vercel_connect"?{vercelConnect:{connector:Os.trim()}}:{},...nt.trim()?{oauthClient:{clientId:nt.trim(),...Cs?{clientSecret:Cs}:{}}}:{},configValues:CC(xs,Jn)?{allowedSpreadsheetIds:wn}:Object.keys(ht).length>0?ht:void 0,applicationId:Ie.applicationId,...ne??Tt.current?{resumeConnectionId:ne??Tt.current}:oe?{reconnectConnectionId:oe}:{},...Sn!=="organization"?{grantKind:Sn}:{},...Sn==="agent"?{subjectAgentId:[...jt][0]}:{}}),Tt.current=null}else{const Sn=Tmt({link:_e,name:ue,authMode:it,needsKey:mt,keyValue:et,headers:$t,oauthClientId:at,oauthClientSecret:De}),Jn=lae(Sn.name??cD(_e)??"Custom app",ft);Ws=await ts.connectApp(T,{...Sn,...oe?{reconnectConnectionId:oe}:{},...ce||gn?.slug==="zapier"?{galleryKey:"zapier",connectionMethodKey:"generated-url"}:{},name:Jn,applicationId:Ie.applicationId,...ft!=="organization"?{grantKind:ft}:{},...ft==="agent"?{subjectAgentId:[...jt][0]}:{}})}return Ws.auth?.kind==="oauth"&&!ne&&!oe&&await ye(Ws.connectionId),Ws},"mutationFn"),onSuccess:r(ct=>{if(ct.auth?.kind==="oauth"){if(_s(ct),ct.auth.manualClientRequired){Be(dae("oauth_manual_client_required",null)),_t("oauth"),Rt(!0),Pe(!1);return}if(o==="dialog"||F){qs("starting"),Pe(!le),eo(ct.connection);return}const Ws=ct.auth.startUrl?.trim();if(!Ws){qs("starting"),Pe(!0),eo(ct.connection);return}Pe(!0),ss({authorizationUrl:Ws,handoff:ct.auth.handoff});return}Be(null),_s(ct);const xs={};for(const Ws of ct.actions.readOnly)xs[Ws.catalogEntryId]=!0;for(const Ws of ct.actions.canMakeChanges)xs[Ws.catalogEntryId]=!0;mr(xs),Va.mutate({result:ct,enabled:xs})},"onSuccess"),onError:r(ct=>{const xs=ct instanceof nn&&ct.body&&typeof ct.body=="object"?ct.body.details:null;if(fr){qs("error"),k?.("needs_retry"),Ns(xs?.code==="invalid_grant"?"Your authorization expired or was revoked. Reconnect to continue.":ct instanceof Error?ct.message:"Paperclip couldn’t start secure sign-in. Try again.");return}if(!le&&_e){const Ws=typeof xs?.code=="string"?xs.code:null,Sn=dae(Ws,ct instanceof Error?ct.message:null);Be(Sn),Pe(!1),Sn.focus==="credentials"&&(bt(!0),Rt(!0));return}Q({title:"Couldn’t connect",body:ct instanceof Error?ct.message:"Please check your key and try again.",tone:"error"})},"onError")}),Qn=ds.mutate,ra=(0,m.useCallback)(ct=>{const xs=ct??le;(xs?EI(xs,ge||null):null)?.auth==="oauth"&&es(),Qn(ct)},[ge,le,Qn,es]);(0,m.useEffect)(()=>{if(!pe||Un.isLoading||!Un.data||(ne||oe)&&(!zs.isFetchedAfterMount||!En.isFetchedAfterMount))return;if(ne&&U==="complete"&&xn?.status==="active"&&Zs!==ne&&Fa){_(`/apps/${xn.id}/permissions`,{replace:!0});return}if(ne&&!Fa)return;const ct=$mt({requestedAppKey:pe,galleryApps:Un.data.apps,reconnectConnection:hn,resumeConnection:xn,resumeApplication:Dr,completedResumeConnectionId:Zs,applications:En.data?.applications??[]}),xs=!!ct?.methods.some(Se=>Se.oauthStrategy==="paperclip_cloud_connector"||Se.oauthStrategy==="paperclip_id_connector");if(fn&&!xs&&ln.isLoading)return;const Ws=D1(ct,i),Sn=v??(hn?.connectionPurpose==="ai"?VB.safeParse(hn.config?.ai).data:void 0),Jn=Ws.find(Se=>Sn?Se.ai?.provider===Sn.provider&&(!("mode"in Sn)||Sn.mode!=="responsible_user")&&Se.ai.method===Sn.method:Se.key===V)??(fn&&!xs?gae(dn):null)??Rk(Ws),wn=Ws.length===1?Ws[0]:null,ca=i==="paperclip_vault"&&!!vae(ct),Ga=Bmt({credentialSource:i,available:Un.data.credentialSources?.vercelConnect.available===!0,retainedReconnectMatches:!!(oe&&Zt)}),Ye=Ws.length===1&&wn?.auth==="oauth"&&!T0(wn)&&!fk(wn),Ft=Fmt({available:ct?.availability?.available,reconnectConnectionId:oe,reconnectSourceMatches:Zt}),ys=zmt({reconnectConnectionId:oe,hasRequestedEntry:!!ct,supportedMethodCount:Ws.length,unsupportedOAuth:Ye,vercelUnavailable:Ga,definitionUnavailable:Ft});if(ys!=="ready"){if(Re(null),xe("gallery"),ys==="reconnect_unavailable"&&oe){Ge(oe);return}_(RI(i==="vercel_connect"?oD():"/apps/connect",F),{replace:!0});return}if(Ge(null),!!ct){if(le?.slug!==ct.slug){Re(ct),je(ct.name),Ze(""),Fe(""),bt(!1),qe(""),be({}),Lt(""),lt(""),Ke(""),Xe(Jn?.key??""),zt(LS(Jn)),he(""),Dt(null),_s(null);const Se=ve?.companyId===T?ve:null;Ut(Te??Se?.grantKind??dD(Jn,!!c)),ze(new Set(Se?.agentIds??(c?[c]:[]))),os(Se?.installChoice??(c?"specific":"all")),xe(hae({requestedAppKey:pe,routeStage:U,resumeConnectionId:ne,hasPrefilledLink:!!Ie.link,zapierSource:ce}))}else Sr!==xs&&(Re(ct),Xe(Jn?.key??""),zt(LS(Jn)));if(!(ca&&(!En.isFetchedAfterMount||!zs.isFetchedAfterMount))&&!(ca&&on.current)&&ca&&(En.isError||zs.isError)){qs("error"),Ns("Paperclip couldn’t check for an existing connection. Try again."),xe("key");return}}},[v,V,En.isError,En.isFetchedAfterMount,En.data,zs.isError,zs.isFetchedAfterMount,ln.data?.configured,ln.isLoading,ge,i,le?.slug,Sr,Un.data,Un.isLoading,_,Te,hn,oe,Zt,xn,Dr,Fa,Zs,ba,U,ne,dn,pe,c,ve,U,ce]),(0,m.useEffect)(()=>{as.current=null,bs(null)},[ne]),(0,m.useEffect)(()=>{const ct=xn??hn;if(!ct||!le||as.current===ct.id)return;const xs=NQ(ct),Ws=typeof xs.sourceTemplateKey=="string"?xs.sourceTemplateKey:null;if(Ws&&Ws!==le.slug)return;const Sn=typeof xs.connectionMethodKey=="string"?xs.connectionMethodKey:null,Jn=Sn?D1(le,i).find(ca=>ca.key===Sn)??null:null;if(je(ct.name||le.name),Jn){Xe(Jn.key);const ca=xs.methodConfig&&typeof xs.methodConfig=="object"?xs.methodConfig:{};zt({...LS(Jn),...Object.fromEntries(Object.entries(ca).filter(Ga=>typeof Ga[1]=="string"||typeof Ga[1]=="boolean"))})}const wn=xs.oauth&&typeof xs.oauth=="object"?xs.oauth:null;wn?.clientRegistrationSource==="manual"&&typeof wn.clientId=="string"&&Lt(wn.clientId),Z==="failed"||Z==="denied"?(qs("error"),Ns(mae(Z,ie))):(qs("entry"),Ns(null)),xe("key"),as.current=ct.id,bs(ct.id)},[i,le,ie,Z,xn,hn]);const Va=we({mutationFn:r(async ct=>{const{result:xs,enabled:Ws}=ct,Sn=Object.entries(Ws).filter(([,Ga])=>Ga).map(([Ga])=>Ga),Jn=C2e(xs,Ga=>!!Ws[Ga]),wn=Ct==="all"?"all_agents":{agentIds:Array.from(jt)},ca=await ts.finishApp(T,xs.connectionId,{enabledCatalogEntryIds:Sn,askFirstCatalogEntryIds:Jn,...ir?{agentInstructions:ir}:{},access:wn,...c?{preserveExistingAccess:!0}:{}});return await ye(xs.connectionId),ca},"mutationFn"),onSuccess:r(async(ct,xs)=>{ne&&xs.result.connectionId===ne&&Nn(ne),await S.invalidateQueries({queryKey:["tools"]}),await S.invalidateQueries({queryKey:D.apps.attention(T)}),Ha("success"),x?.({connectionId:xs.result.connectionId})},"onSuccess"),onError:r(ct=>{Ha("key"),Q({title:"Couldn’t finish setup",body:ct instanceof Error?ct.message:"Please try again.",tone:"error"})},"onError")});if(!T)return(0,t.jsx)("div",{className:"p-6 text-sm text-muted-foreground",children:"Select an organization to connect apps."});if((ne||oe)&&(zs.isError||En.isError))return(0,t.jsxs)("div",{className:"mx-auto max-w-xl rounded-xl border border-border bg-card p-6",children:[(0,t.jsx)("h2",{className:"text-lg font-semibold text-foreground",children:"Couldn’t load connection setup"}),(0,t.jsx)("p",{className:"mt-2 text-sm text-muted-foreground",children:"Paperclip couldn’t check the retained connection. The retained connection was not changed."}),(0,t.jsxs)("div",{className:"mt-5 flex flex-wrap gap-2",children:[(0,t.jsx)($,{type:"button",onClick:r(async()=>{const[ct,xs]=await Promise.all([zs.refetch(),En.refetch()]);!ct.isError&&!xs.isError&&(Ns(null),qs("entry"))},"onClick"),children:"Try again"}),(0,t.jsx)($,{type:"button",variant:"outline",onClick:r(()=>_("/apps"),"onClick"),children:"Back to apps"})]})]});if(ne&&zs.isFetchedAfterMount&&!xn)return(0,t.jsxs)("div",{className:"mx-auto max-w-xl rounded-xl border border-border bg-card p-6",children:[(0,t.jsx)("h2",{className:"text-lg font-semibold text-foreground",children:"This setup can’t be resumed"}),(0,t.jsx)("p",{className:"mt-2 text-sm text-muted-foreground",children:"The saved connection no longer exists or is not available to this organization."}),(0,t.jsx)($,{type:"button",variant:"outline",className:"mt-5",onClick:r(()=>_("/apps"),"onClick"),children:"Back to apps"})]});if(ne&&zs.isFetchedAfterMount&&En.isFetchedAfterMount&&xn&&!Fa)return(0,t.jsxs)("div",{className:"mx-auto max-w-xl rounded-xl border border-border bg-card p-6",children:[(0,t.jsx)("h2",{className:"text-lg font-semibold text-foreground",children:"This setup can’t be resumed"}),(0,t.jsx)("p",{className:"mt-2 text-sm text-muted-foreground",children:"This saved draft does not match the requested provider. The connection was not changed."}),(0,t.jsx)($,{type:"button",variant:"outline",className:"mt-5",onClick:r(()=>_("/apps"),"onClick"),children:"Back to apps"})]});if(oe&&zs.isFetchedAfterMount&&En.isFetchedAfterMount&&(!hn||!Zt))return(0,t.jsxs)("div",{className:"mx-auto max-w-xl rounded-xl border border-border bg-card p-6",children:[(0,t.jsx)("h2",{className:"text-lg font-semibold text-foreground",children:"This connection can’t be reconnected"}),(0,t.jsx)("p",{className:"mt-2 text-sm text-muted-foreground",children:hn?"This reconnect link does not match the retained connection's provider.":"The retained connection no longer exists or is not available to this organization."}),(0,t.jsx)($,{type:"button",variant:"outline",className:"mt-5",onClick:r(()=>_("/apps"),"onClick"),children:"Back to apps"})]});if((ne||oe)&&Un.isError)return(0,t.jsxs)("div",{className:"mx-auto max-w-xl rounded-xl border border-border bg-card p-6",children:[(0,t.jsx)("h2",{className:"text-lg font-semibold text-foreground",children:"Couldn’t load connection setup"}),(0,t.jsx)("p",{className:"mt-2 text-sm text-muted-foreground",children:"Paperclip couldn’t load the provider details needed to restore this connection. The retained connection was not changed."}),(0,t.jsxs)("div",{className:"mt-5 flex flex-wrap gap-2",children:[(0,t.jsx)($,{type:"button",onClick:r(()=>{Un.refetch()},"onClick"),children:"Try again"}),(0,t.jsx)($,{type:"button",variant:"outline",onClick:r(()=>_("/apps"),"onClick"),children:"Back to apps"})]})]});if(oe&&gt===oe)return(0,t.jsxs)("div",{className:"mx-auto max-w-xl rounded-xl border border-border bg-card p-6",children:[(0,t.jsx)("h2",{className:"text-lg font-semibold text-foreground",children:"This connection can’t be reconnected"}),(0,t.jsx)("p",{className:"mt-2 text-sm text-muted-foreground",children:"Paperclip no longer has a supported setup method for this retained connection. The retained connection was not changed."}),(0,t.jsx)($,{type:"button",variant:"outline",className:"mt-5",onClick:r(()=>_("/apps"),"onClick"),children:"Back to apps"})]});if(ne&&(!zs.isFetchedAfterMount||Un.isLoading||!le||Xs!==xn?.id))return(0,t.jsxs)("div",{className:"mx-auto max-w-xl space-y-4","aria-label":"Loading saved connection setup",children:[(0,t.jsx)(yn,{className:"h-8 w-48"}),(0,t.jsx)(yn,{className:"h-40 w-full rounded-xl"})]});if(oe&&(!zs.isFetchedAfterMount||!En.isFetchedAfterMount||Un.isLoading||pe&&!le))return(0,t.jsxs)("div",{className:"mx-auto max-w-xl space-y-4","aria-label":"Loading retained connection setup",children:[(0,t.jsx)(yn,{className:"h-8 w-48"}),(0,t.jsx)(yn,{className:"h-40 w-full rounded-xl"})]});if(Nr&&f)return(0,t.jsxs)("div",{className:"max-w-5xl","data-testid":"connection-existing-choice",children:[(0,t.jsxs)("div",{className:"mb-6",children:[(0,t.jsxs)("h1",{className:"text-2xl font-bold tracking-tight",children:["Use an existing ",pe?"connection":"app connection"]}),(0,t.jsx)("p",{className:"mt-1 text-sm text-muted-foreground",children:"Reuse a connection without changing who already has access, or connect a new one."})]}),(0,t.jsx)(uv,{choices:h.map(ct=>({id:ct.id,name:ct.name,description:ct.status==="active"&&ct.enabled?"Ready to use":"Setup needs attention"})),pendingId:Ur,onSelect:r(async ct=>{ga(ct),ur(null);try{await f(ct)}catch(xs){ur(xs instanceof Error?xs.message:"Couldn’t use this connection."),ga(null)}},"onSelect")}),ar?(0,t.jsx)(ua,{tone:"danger",className:"mt-4",children:ar}):null,(0,t.jsxs)("div",{className:"mt-5 flex flex-wrap gap-2",children:[(0,t.jsx)($,{type:"button",variant:"outline",onClick:r(()=>Or(!1),"onClick"),children:p?"Review connection setup":"Connect new"}),w?(0,t.jsx)($,{type:"button",variant:"ghost",onClick:w,children:"Cancel"}):null]})]});const ci=D1(le,i),oi=ia?[ia]:ci,Ka=le?ge?oi.find(ct=>ct.key===ge)??null:oi[0]??null:null,Lr=le?Ka?.auth??"none":it==="none"?"none":it==="oauth"?"oauth":"api_key",di=de==="key"?((ct,xs)=>(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)(IV,{extra:ct,forceOpen:xs,companyId:T,sentence:AE({grantKind:ft,authKind:Lr,installChoice:Ct,installCount:jt.size,lockedAgentId:c??null,preserveAgentAccess:!!(fr&&(Wt||hn))}),notice:[Un.data?.capabilities?.canCreateOrganizationGrant===!1?Un.data.capabilities.organizationGrantReason??"Only a connection manager can share this credential with the organization.":null,Un.data?.capabilities?.canSetCompanyInstall===!1?Un.data.capabilities.companyInstallReason??"Only someone who can configure this connection can give every agent access.":null,c?"This task grants access only to the agent that asked for it.":null].filter(Ws=>!!Ws),authKind:Lr,grantKinds:Js?[Js]:Ka?.grantKinds,grantKind:ft,setGrantKind:Ut,installChoice:Ct,setInstallChoice:os,installAgentIds:jt,setInstallAgentIds:ze,lockedAgentId:c,capabilities:Un.data?.capabilities,githubIdentity:le?.slug==="github",identityLoading:!!fr&&vi,preserveAgentAccess:!!(fr&&(Wt||hn)),disabled:ds.isPending||il.isPending},"connection-defaults"),le&&Mi&&ir&&(0,t.jsx)("div",{className:"mt-6",children:(0,t.jsx)(wH,{provider:le.name,template:Mi,value:ir,onChange:r(Ws=>Ht({slug:le.slug,value:Ws}),"onChange"),disabled:ds.isPending||il.isPending})}),e&&(0,t.jsx)("div",{className:"mt-6",children:e})]})):null,zi=fr&&ti&&fk(ti)?ti:null,Co=zi&&fr?(0,t.jsx)(zz,{entry:fr,method:zi,callbackUrl:pt,clientId:nt,onClientIdChange:Lt,clientSecret:Cs,onClientSecretChange:lt,required:!1}):null,za=di?.()??null,pi=Co?di?.(Co,Bs==="error"||nt.trim().length>0)??null:za,_o=!!(fr&&de==="key"&&(Ta||Bs!=="entry")),Fd=!!(de==="key"&&le&&fn&&!Sr&&ln.data?.configured===!0),nd=!!(de==="key"&&le&&fn&&!Sr&&(ln.isLoading||ln.isError||ln.data?.configured!==!0));if(_o&&fr)return(0,t.jsx)(Bz,{entry:fr,resuming:!!ne,phase:Bs,error:Rn,recoveryActions:ie==="github_installation_required"?{installationUrl:J,managementUrl:ae}:void 0,authorizationHost:Yn,authorizationUrl:Cr,guidance:le?.slug==="railway"&&Ka?(0,t.jsxs)("div",{className:"space-y-3 text-sm text-muted-foreground",children:[(0,t.jsx)("p",{children:Ka.guidanceMd}),(0,t.jsx)("ul",{className:"list-disc space-y-2 pl-5",children:Ka.warnings?.map(ct=>(0,t.jsx)("li",{children:ct},ct))})]}):null,defaults:pi,settingsValid:n&&Vi,onOpenAuthorization:As,onRetry:r(async()=>{const ct=!Hs.current;Hs.current=!0,Ns(null),qs("starting");const xs=ns?.connection??Wt;if(xs&&Co&&nt.trim()){Tt.current=xs.id,ra(fr);return}if(xs){eo(xs);return}if(ct&&!ne&&!En.isError&&!zs.isError){ra(fr);return}on.current=!0;try{const[Ws,Sn]=await Promise.all([En.refetch(),zs.refetch()]);if(Ws.isError||Sn.isError){qs("error"),Ns("Paperclip couldn’t check for an existing connection. Try again.");return}const Jn=(ne?(Sn.data?.connections??[]).find(wn=>wn.id===ne&&wn.authKind==="oauth")??null:null)??yae(re,Ws.data?.applications??[],Sn.data?.connections??[],K?{applicationId:Ie.applicationId,draftOnly:!0}:{});Jn&&!ne&&Ut(Jn.credentialPolicy==="per_user"?"user":Jn.credentialPolicy==="per_agent"?"agent":"organization"),Jn?eo(Jn):ds.mutate(fr)}finally{on.current=!1}},"onRetry"),onBack:r(()=>{Cn.current?.abort(),qs("entry"),Ns(null),vn()},"onBack"),onCancel:r(()=>{Cn.current?.abort(),(w??(()=>_("/apps")))()},"onCancel")});if(Oe&&!le&&_e&&de==="key")return(0,t.jsx)(Bz,{identity:{name:ue.trim()||d_(_e)||"this server",unverifiedHost:d_(_e)},steps:{labels:fae,activeIndex:xae.key},phase:Bs,error:Rn,authorizationHost:Yn,authorizationUrl:Cr,defaults:za,onOpenAuthorization:As,onRetry:r(()=>{Ns(null);const ct=ns?.connection;if(ct){qs("starting"),eo(ct);return}Pe(!1),qs("entry")},"onRetry"),onBack:r(()=>{Cn.current?.abort(),Pe(!1),qs("entry"),Ns(null)},"onBack"),onCancel:r(()=>{Cn.current?.abort(),(w??(()=>_("/apps")))()},"onCancel")});const Ue=ns?.application.name??le?.name??(ue.trim()||cD(_e)||"this app"),Et=X?Is.filter(ct=>D1(ct,i).length>0):Is,Kt=ce?Un.data?.apps.find(ct=>ct.slug==="zapier")??null:null,Ds=(hn?.connectionPurpose==="ai"?VB.safeParse(hn.config?.ai).data:void 0)??le?.methods.find(ct=>ct.key===ge)?.ai??(!ge&&le?.methods.every(ct=>ct.ai)?le.methods[0]?.ai:void 0),en=le?N?.({app:le,name:Le||le.name,grantKind:ft,agentIds:[...jt],allAgents:Ct==="all",onBack:r(()=>vn(),"onBack")})??(Ds&&T?(0,t.jsx)(t.Fragment,{children:(0,t.jsx)(v5,{defaults:hn?void 0:za,companyId:T,provider:Ds.provider,fixedMethod:!!(v&&v.mode!=="responsible_user"),initialMethod:hn?.connectionPurpose==="ai"?(hn.config?.ai).method:Ds.method,connectionId:hn?.connectionPurpose==="ai"?hn.id:void 0,name:hn?.connectionPurpose==="ai"?hn.name:Le||`My ${le.name} ${Ds.method==="subscription"?"subscription":"API"}`,ownership:(hn?.connectionPurpose==="ai"?hn.credentialPolicy==="shared":ft==="organization")?"shared":"personal",agentIds:[...jt],allAgents:Ct==="all",onCancel:r(()=>w?w():_("/apps"),"onCancel"),onComplete:r(ct=>{x?.({connectionId:ct.connectionId}),x||_(`/apps/${ct.connectionId}/permissions`)},"onComplete")})}):void 0):void 0,si=hn?.connectionPurpose==="ai"?["Reconnect account"]:en!==void 0?["Connect account"]:ce?Umt:le&&oi.length>1?["Choose connection"]:le&&oi[0]?.auth==="oauth"?["Sign in"]:CC(le,ge)?["Share sheet"]:le?["Add your key"]:fae,Ra=hn?.connectionPurpose==="ai"?0:(ce||le)&&de!=="gallery"&&de!=="success"?qmt[de]:de==="success"?si.length:xae[de];return(0,t.jsxs)("div",{className:"max-w-5xl",children:[de!=="success"&&!(a&&de==="gallery")&&(0,t.jsx)(sM,{subtitle:de==="gallery"?X?"Choose a reviewed app to connect through Vercel.":"Pick the app you want your agents to use.":si.length<=1?void 0:`Step ${Ra+1} of ${si.length}`,step:de,activeIndex:Ra,labels:si,appIdentity:ce?{name:"Zapier",logoUrl:Kt?.branding.logoUrl??null,darkLogoUrl:Kt?.branding.darkLogoUrl??null}:le&&de!=="gallery"?{name:le.name,logoUrl:le.branding.logoUrl,darkLogoUrl:le.branding.darkLogoUrl??null}:void 0,unverifiedHost:!le&&!ce&&de!=="gallery"?d_(_e):null,onCancel:w??(()=>_("/apps"))}),de==="key"&&s&&(0,t.jsx)("div",{className:"mx-auto mb-6 max-w-xl",children:s}),de==="gallery"&&(0,t.jsx)(Ymt,{loading:Un.isLoading,initialLink:_e,apps:Et,vercelConnect:X,vercelConnectAvailability:Un.data?.credentialSources?.vercelConnect??null,byo:fe,byoOnly:a,source:L.get("source"),onPick:kn,onUseLink:r(ct=>{const xs=mR(ct,Is);Re(null),je(""),Ze(ct),Fe(xs?.name??cD(ct)??""),bt(!1),qe(""),be({}),he(""),Dt(null),ze(new Set(c?[c]:[])),os(c?"specific":"all"),Ut(Te??(c?"user":"organization")),xe("key")},"onUseLink")}),Fd&&le?(0,t.jsxs)("div",{className:"mx-auto max-w-xl rounded-xl border border-border bg-card p-6",children:[(0,t.jsxs)("h2",{className:"text-lg font-semibold text-foreground",children:[le.name," sign-in is unavailable"]}),(0,t.jsxs)("p",{className:"mt-2 text-sm text-muted-foreground",children:["This instance is connected to Paperclip, but ",le.name," sign-in is not currently available. Try again shortly or contact your instance administrator."]}),_n?(0,t.jsxs)($,{type:"button",variant:"link",className:"mt-4 h-auto p-0 text-xs",onClick:r(()=>Xe(_n.key),"onClick"),children:["Use your own ",le.name," OAuth app"]}):null,(0,t.jsxs)("div",{className:"mt-6 flex items-center justify-between gap-3",children:[(0,t.jsx)($,{type:"button",variant:"ghost",onClick:vn,children:"Back"}),(0,t.jsxs)($,{type:"button",disabled:Un.isFetching,onClick:r(()=>{Un.refetch()},"onClick"),children:[Un.isFetching?(0,t.jsx)(st,{className:"h-4 w-4 animate-spin"}):null,"Try again"]})]})]}):de==="key"&&le&&nd?(0,t.jsx)("div",{className:"mx-auto max-w-xl",children:(0,t.jsxs)("div",{className:"rounded-xl border border-border bg-card p-6",children:[(0,t.jsxs)("div",{className:"flex items-start gap-3",children:[(0,t.jsx)("div",{className:"rounded-lg bg-muted p-2 text-muted-foreground",children:(0,t.jsx)(qb,{className:"h-5 w-5"})}),(0,t.jsxs)("div",{className:"min-w-0",children:[(0,t.jsx)("h2",{className:"text-lg font-semibold text-foreground",children:"Connect with Paperclip"}),(0,t.jsxs)("p",{className:"mt-2 text-sm text-muted-foreground",children:["You must connect this instance to Paperclip to connect to ",le.name," (you only need to do this once)."]})]})]}),_n?(0,t.jsxs)($,{type:"button",variant:"link",className:"mt-4 h-auto p-0 text-xs",onClick:r(()=>Xe(_n.key),"onClick"),children:["Use your own ",le.name," OAuth app"]}):null,ln.isError||Tr?(0,t.jsx)(ua,{tone:"danger",className:"mt-4",children:Tr??"Paperclip couldn’t check Cloud registration. Try again."}):null,Da?(0,t.jsxs)("p",{className:"mt-4 text-sm text-muted-foreground",children:["Finish authorization in the opened window."," ",(0,t.jsx)("a",{className:"underline",href:Da,target:"_blank",rel:"noopener noreferrer",children:"Open authorization in a new tab"})]}):null,za,(0,t.jsxs)("div",{className:"mt-6 flex items-center justify-between gap-3",children:[(0,t.jsx)($,{type:"button",variant:"ghost",onClick:vn,children:"Back"}),(0,t.jsxs)($,{type:"button",disabled:ln.isLoading||jn.isPending,onClick:r(()=>{Zn(null),es(),Wr(),jn.mutate()},"onClick"),children:[jn.isPending?(0,t.jsx)(st,{className:"h-4 w-4 animate-spin"}):null,ln.data?.status==="pending"?"Continue":"Connect with Paperclip"]})]})]})}):de==="key"&&le&&en!==void 0?en:de==="key"&&le?(0,t.jsx)(Xmt,{settingsValid:n&&Vi,entry:le,error:ds.isError?ds.error instanceof Error?ds.error.message:"Please check your key and try again.":null,values:Ve,onChange:be,oauthClientId:nt,onOAuthClientIdChange:Lt,oauthClientSecret:Cs,oauthCallbackUrl:pt,canReuseOAuthClientSecret:!!(ps?.config?.oauth&&ps.config.oauth.clientId===nt.trim()&&ps.hasSavedOAuthClientSecret),onOAuthClientSecretChange:lt,credentialSource:i,vercelConnector:Os,onVercelConnectorChange:Ke,vercelConnectAvailability:Un.data?.credentialSources?.vercelConnect??null,methodKey:ge,onMethodChange:r(ct=>{Xe(ct?.key??""),!Te&&ct?.grantKinds&&!ct.grantKinds.includes(St)&&Ut(dD(ct,!!c)),be({}),Lt(""),lt(""),Ke(""),zt(LS(ct))},"onMethodChange"),configValues:ht,onConfigChange:zt,googleSheetsLinks:$e,googleSheetsError:Vt,onGoogleSheetsLinksChange:r(ct=>{he(ct),Dt(null)},"onGoogleSheetsLinksChange"),submitting:ds.isPending,renderDefaults:di??void 0,onBack:vn,onConnect:r(()=>{if(CC(le,ge)){const Ws=zF($e);if(Ws.invalidCount>0){Dt("That doesn't look like a Google Sheets link.");return}if(Ws.ids.length===0){Dt("Paste at least one Google Sheets link.");return}}const ct=EI(le,ge||null),xs=!!(ct?.credentialFields?.length||ct?.tenantFields?.some(Ws=>!Ws.hidden)||ct?.extensionFields?.some(Ws=>!Ws.hidden));if(ct&&T0(ct)&&Wt&&!xs&&!nt.trim()){Hs.current=!0,Ns(null),qs("starting"),eo(Wt);return}ct&&T0(ct)&&(Hs.current=!0,Ns(null),qs("starting")),ra()},"onConnect")}):null,de==="key"&&!le&&!_e&&!ce&&pe&&(0,t.jsxs)("div",{className:"mx-auto max-w-xl","aria-busy":"true","aria-label":`Loading ${pe} setup`,children:[(0,t.jsx)(yn,{className:"h-6 w-2/3 rounded-md"}),(0,t.jsx)(yn,{className:"mt-3 h-4 w-full rounded-md"}),(0,t.jsx)(yn,{className:"mt-8 h-11 w-40 rounded-md"})]}),de==="key"&&!le&&_e&&!ce&&(0,t.jsx)(Zmt,{link:_e,name:ue,needsKey:mt,keyValue:et,onKeyChange:qe,authMode:it,onAuthModeChange:r(ct=>{_t(ct),Be(null),ct!=="auto"&&bt(!1),ct!=="bearer"&&ct!=="auto"&&qe("")},"onAuthModeChange"),headers:$t,onHeadersChange:r(ct=>{Ot(ct),Be(null)},"onHeadersChange"),oauthClientId:at,onOAuthClientIdChange:Me,oauthClientSecret:De,onOAuthClientSecretChange:ut,advancedOpen:Pt,onAdvancedOpenChange:Rt,guidance:Qe,matchedEntry:gn,onUseMatchedEntry:gn?()=>kn(gn):void 0,submitting:ds.isPending||Oe,defaults:za,onBack:vn,onConnect:r(()=>{Be(null),ds.mutate(void 0)},"onConnect")}),de==="key"&&!le&&ce&&(0,t.jsx)(Gmt,{link:_e,onLinkChange:Ze,submitting:ds.isPending,defaults:za,onBack:vn,onConnect:r(()=>ds.mutate(void 0),"onConnect")}),de==="success"&&(0,t.jsx)(nht,{appName:Ue,logoUrl:le?.branding.logoUrl,darkLogoUrl:le?.branding.darkLogoUrl,summary:sht({grantKind:ft,authKind:Lr,installChoice:Ct,installCount:jt.size,enabledCount:Object.values(cn).filter(Boolean).length}),statedDefault:AE({grantKind:ft,authKind:Lr,installChoice:Ct,installCount:jt.size,lockedAgentId:c??null}),onDone:w??(()=>_(o==="page"&&ns?.connectionId?`/apps/${ns.connectionId}/permissions`:"/apps"))})]})}r(Vmt,"StandardConnectionSetupFlow");function Bz({entry:e,identity:s,resuming:n=!1,phase:a,error:i,recoveryActions:o,authorizationHost:l,authorizationUrl:c,steps:d={labels:Kmt,activeIndex:0},guidance:u,defaults:h,onRetry:p,settingsValid:f=!0,onOpenAuthorization:x,onBack:g,onCancel:v}){const y=e?.name??s?.name??"this server",k=e?null:s?.unverifiedHost??null,w=a==="entry"?{title:n?`Finish connecting ${y}`:`Connect ${y} to Paperclip`,body:n?`Your connection is saved. Continue in ${y} to approve access; its identity and agent access will stay the same.`:`Paperclip will open ${y} so you can choose a workspace and approve access.`}:a==="starting"?{title:"Preparing secure sign-in",body:`Paperclip is creating a secure ${y} connection.`}:a==="redirecting"?{title:`Opening ${y}`,body:l?`Continue at ${l} to choose a workspace and approve access. Only approve access if you recognize that address.`:`Continue in ${y} to choose a workspace and approve access.`}:{title:`${y} couldn’t connect`,body:i??"Paperclip couldn’t start secure sign-in. Try again."};return(0,t.jsxs)("div",{className:"max-w-5xl",children:[(0,t.jsx)(sM,{subtitle:"Secure MCP sign-in",step:"key",activeIndex:d.activeIndex,labels:d.labels,appIdentity:e?{name:e.name,logoUrl:e.branding.logoUrl,darkLogoUrl:e.branding.darkLogoUrl}:void 0,unverifiedHost:k,onCancel:v}),(0,t.jsxs)("div",{className:"mx-auto max-w-xl",children:[(0,t.jsxs)("div",{className:"flex items-start gap-3",children:[(0,t.jsx)("span",{className:"mt-1 inline-flex h-10 w-10 shrink-0 items-center justify-center rounded-lg border border-border bg-background",children:a==="error"?(0,t.jsx)(Ml,{className:"h-5 w-5 text-destructive"}):a==="entry"?(0,t.jsx)(ko,{className:"h-5 w-5 text-muted-foreground"}):(0,t.jsx)(st,{className:"h-5 w-5 animate-spin text-muted-foreground"})}),(0,t.jsxs)("div",{className:"min-w-0",children:[(0,t.jsx)("h2",{className:"text-xl font-bold tracking-tight",children:w.title}),(0,t.jsx)("p",{className:"mt-1 text-sm text-muted-foreground",children:w.body}),k?(0,t.jsx)(tM,{host:k,className:"mt-2"}):null]})]}),a==="entry"&&u?(0,t.jsx)("div",{className:"mt-4",children:u}):null,a==="entry"||a==="error"?h:null,a==="error"&&o&&(o.installationUrl||o.managementUrl)?(0,t.jsxs)("div",{className:"mt-4 flex flex-wrap gap-2",children:[o.installationUrl?(0,t.jsx)($,{type:"button",variant:"outline",asChild:!0,children:(0,t.jsxs)("a",{href:o.installationUrl,target:"_blank",rel:"noreferrer",children:["Install Paperclip on GitHub",(0,t.jsx)(oo,{className:"ml-1.5 h-3.5 w-3.5"})]})}):null,o.managementUrl?(0,t.jsx)($,{type:"button",variant:"ghost",asChild:!0,children:(0,t.jsx)("a",{href:o.managementUrl,target:"_blank",rel:"noreferrer",children:"Manage repositories on GitHub"})}):null]}):null,(0,t.jsxs)("div",{className:"mt-6 flex items-center gap-2",children:[a==="error"||a==="entry"?(0,t.jsxs)($,{type:"button",onClick:p,disabled:!f,children:[a==="entry"?n?`Finish with ${y}`:`Continue to ${y}`:"Try again",a==="entry"?(0,t.jsx)(oo,{className:"h-4 w-4","aria-hidden":"true"}):null]}):(0,t.jsx)($,{type:"button",disabled:!0,children:a==="redirecting"?`Opening ${y}…`:"Preparing…"}),c?(0,t.jsx)($,{variant:"outline",asChild:!0,children:(0,t.jsx)("a",{href:c,target:"_blank",rel:"noopener noreferrer",onClick:x,children:"Open sign-in in a new tab"})}):null,(0,t.jsx)($,{type:"button",variant:"ghost",onClick:g,children:"Back"})]})]})]})}r(Bz,"OAuthConnectStateScreen");function Gmt({link:e,onLinkChange:s,submitting:n,defaults:a,onBack:i,onConnect:o}){const l=Fz(e),c=l?new URL(l).hostname:"",d=c==="zapier.com"||c.endsWith(".zapier.com");return(0,t.jsxs)("div",{className:"mx-auto max-w-xl",children:[(0,t.jsxs)("div",{children:[(0,t.jsx)("label",{className:"text-sm font-medium text-foreground",children:"Zapier MCP URL"}),(0,t.jsx)(dt,{type:"password",autoComplete:"off",spellCheck:!1,value:e,onChange:r(u=>s(u.target.value),"onChange"),onKeyDown:r(u=>{u.key==="Enter"&&d&&!n&&o()},"onKeyDown"),placeholder:"https://mcp.zapier.com/api/v1/connect?token=…",className:"mt-2 h-11",autoFocus:!0}),e.trim()&&!d&&(0,t.jsx)("p",{className:"mt-2 text-xs text-destructive",children:"Paste a valid Zapier URL to continue."})]}),a,(0,t.jsxs)("div",{className:"mt-6 flex items-center justify-between",children:[(0,t.jsx)($,{variant:"ghost",onClick:i,disabled:n,children:"Back"}),(0,t.jsxs)($,{onClick:o,disabled:n||!d,children:[n&&(0,t.jsx)(st,{className:"mr-2 h-4 w-4 animate-spin"}),n?"Checking…":"Check link"]})]})]})}r(Gmt,"ZapierConnectStep");function Ymt({loading:e,initialLink:s="",apps:n,byo:a=!1,byoOnly:i=!1,vercelConnect:o=!1,vercelConnectAvailability:l=null,source:c=null,onPick:d,onUseLink:u}){const[h,p]=(0,m.useState)(""),[f,x]=(0,m.useState)(s),g=(0,m.useRef)(!1);(0,m.useEffect)(()=>{g.current||x(s)},[s]);const[v,y]=(0,m.useState)(null),k=(0,m.useRef)(null),w=(0,m.useRef)(null),N=(0,m.useRef)(!1);(0,m.useEffect)(()=>{!a||e&&!i||N.current||(i||k.current?.scrollIntoView?.({block:"center"}),w.current?.focus(),w.current?.select(),N.current=!0)},[a,i,e]);const S=(0,m.useMemo)(()=>{const T=h.trim().toLowerCase();return n.filter(E=>!T||E.name.toLowerCase().includes(T))},[n,h]),C=Fz(f),_=C?mR(C,n):null,R=c==="zapier",I=r(()=>{const T=Fz(f);if(!T){y("Paste a full http or https link.");return}y(null),u(T)},"continueWithLink");return e&&!i?(0,t.jsx)("div",{className:"grid grid-cols-2 gap-4 sm:grid-cols-3 lg:grid-cols-4",children:Array.from({length:8}).map((T,E)=>(0,t.jsx)(yn,{className:"h-32 w-full rounded-xl"},E))}):(0,t.jsxs)("div",{className:"space-y-6",children:[o?(0,t.jsxs)("div",{className:"rounded-xl border border-border bg-card p-5",children:[(0,t.jsxs)("div",{className:"flex flex-col gap-3 sm:flex-row sm:items-start sm:justify-between",children:[(0,t.jsxs)("div",{children:[(0,t.jsx)("h2",{className:"text-lg font-bold tracking-tight",children:"Connect through Vercel"}),(0,t.jsx)("p",{className:"mt-1 max-w-2xl text-sm text-muted-foreground",children:"Create and manage the provider connector in Vercel. Paperclip stores its reference and applies agent access, policy, approval, and audit controls here."})]}),l?(0,t.jsx)($,{asChild:!0,variant:"outline",size:"sm",className:"shrink-0",children:(0,t.jsxs)("a",{href:l.manageUrl,target:"_blank",rel:"noreferrer",children:["Open Vercel Connect",(0,t.jsx)(oo,{className:"ml-2 h-3.5 w-3.5"})]})}):null]}),l?.available===!1?(0,t.jsx)(ua,{tone:"danger",compact:!0,className:"mt-4",children:l.reason??"Vercel Connect is unavailable on this instance."}):null]}):null,!i&&(0,t.jsxs)(t.Fragment,{children:[(0,t.jsxs)("div",{className:"relative",children:[(0,t.jsx)(Yr,{className:"pointer-events-none absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground"}),(0,t.jsx)(dt,{value:h,onChange:r(T=>p(T.target.value),"onChange"),placeholder:"Search apps…",className:"h-11 pl-9"})]}),(0,t.jsx)("div",{className:"grid grid-cols-2 gap-4 sm:grid-cols-3 lg:grid-cols-4",children:S.map(T=>{const E=r5e(T.slug,T.description),P=Z3(T),O=P.length===0||P.every(Q=>Q.auth==="oauth"&&!T0(Q)&&!fk(Q)),M=T.availability?.available===!1||o&&l?.available!==!0;return(0,t.jsxs)("button",{type:"button",disabled:O||M,title:M?T.availability?.reason??l?.reason??void 0:void 0,onClick:r(()=>d(T),"onClick"),className:W("flex flex-col rounded-xl border border-border bg-card p-4 text-left transition-colors",O||M?"cursor-not-allowed opacity-60":"hover:border-foreground/30 hover:bg-accent/40"),children:[(0,t.jsx)(Hi,{name:T.name,logoUrl:T.branding.logoUrl,darkLogoUrl:T.branding.darkLogoUrl,size:36}),(0,t.jsx)("div",{className:"mt-3 text-sm font-bold text-foreground",children:T.name}),(0,t.jsx)("div",{className:"mt-1 line-clamp-2 text-xs text-muted-foreground",children:E.tagline}),(0,t.jsx)("div",{className:"mt-3 text-xs font-semibold text-foreground",children:M?(0,t.jsx)("span",{className:"text-muted-foreground",children:T.availability?.reason??l?.reason??"Unavailable on this instance."}):O?(0,t.jsx)("span",{className:"text-muted-foreground",children:"Unavailable"}):(0,t.jsx)("span",{children:"Connect →"})})]},T.slug)})}),S.length===0&&(0,t.jsxs)("div",{className:"py-10 text-center text-sm text-muted-foreground",children:["No apps match “",h,"”."]})]}),o?null:(0,t.jsxs)("div",{ref:k,className:W("grid gap-4 border-t border-border pt-5 md:grid-cols-(--gtc-13)",a&&"-mx-3 rounded-xl border border-primary/40 bg-primary/[0.04] px-3 pb-4 md:mx-0"),children:[(0,t.jsxs)("div",{children:[(0,t.jsxs)("div",{className:"flex items-center gap-2 text-sm font-semibold text-foreground",children:[(0,t.jsx)(Ml,{className:"h-4 w-4 text-muted-foreground"}),R?"Connect Zapier":a?"Connect your own MCP server":"Connect with a link"]}),(0,t.jsx)("p",{className:"mt-1 text-xs text-muted-foreground",children:R?"Paste the complete MCP URL Zapier gives you, including its token.":a?"Paste your MCP server’s URL and every discovered tool will be available immediately.":"Paste a setup link from an app that is not listed here."}),!R&&(0,t.jsxs)("p",{className:"mt-1 text-xs text-muted-foreground",children:["Any remote tool URL works here — including a local MCP server like"," ",(0,t.jsx)("code",{className:"rounded bg-muted px-1 py-0.5 text-xs",children:"http://127.0.0.1:8848/mcp"}),"."]}),_&&(0,t.jsxs)("div",{className:"mt-3 flex items-center justify-between gap-3 rounded-lg border border-border bg-muted/40 px-3 py-2",children:[(0,t.jsxs)("div",{className:"flex min-w-0 items-center gap-2 text-sm",children:[(0,t.jsx)(Hi,{name:_.name,logoUrl:_.branding.logoUrl,darkLogoUrl:_.branding.darkLogoUrl,size:24}),(0,t.jsxs)("span",{className:"truncate",children:["This looks like ",_.name,"."]})]}),(0,t.jsx)($,{type:"button",size:"sm",variant:"outline",disabled:_.availability?.available===!1,onClick:r(()=>{if(y(null),_.slug==="zapier"){I();return}d(_)},"onClick"),children:_.availability?.available===!1?"Not available":_.slug==="zapier"?"Continue":`Use ${_.name}`})]})]}),(0,t.jsxs)("div",{className:"flex min-w-0 flex-col gap-2 sm:min-w-(--sz-360px)",children:[(0,t.jsxs)("div",{className:"flex gap-2",children:[(0,t.jsx)(dt,{ref:w,type:R||_?.slug==="zapier"?"password":"url",autoComplete:"off",spellCheck:!1,"aria-label":"MCP server URL",value:f,onChange:r(T=>{g.current=!0,x(T.target.value),y(null)},"onChange"),onKeyDown:r(T=>{T.key==="Enter"&&I()},"onKeyDown"),placeholder:R?"https://mcp.zapier.com/api/v1/connect?token=…":"https://example.com/actions",className:"h-10"}),(0,t.jsx)($,{type:"button",variant:"outline",onClick:I,children:"Continue"})]}),v&&(0,t.jsx)("div",{className:"text-xs text-destructive",children:v})]})]})]})}r(Ymt,"GalleryStep");function Fz(e){try{const s=new URL(e.trim());return s.protocol!=="http:"&&s.protocol!=="https:"?null:s.toString()}catch{return null}}r(Fz,"normalizeAppLink");function Zmt({link:e,name:s,needsKey:n,keyValue:a,onKeyChange:i,authMode:o,onAuthModeChange:l,headers:c,onHeadersChange:d,oauthClientId:u,onOAuthClientIdChange:h,oauthClientSecret:p,onOAuthClientSecretChange:f,advancedOpen:x,onAdvancedOpenChange:g,guidance:v,matchedEntry:y,onUseMatchedEntry:k,submitting:w,defaults:N,onBack:S,onConnect:C}){const _=d_(e),R=o==="custom_headers"?a5e(c):null,I=Rmt({link:e,name:s,authMode:o,needsKey:n,keyValue:a,headers:c,oauthClientId:u,oauthClientSecret:p}),T=o==="auto"&&n||o==="bearer",E=y?.slug==="zapier"?gbe(e):e,P=r((O,M)=>{d(c.map(Q=>Q.id===O?{...Q,...M}:Q))},"updateHeader");return(0,t.jsxs)("div",{className:"mx-auto max-w-xl",children:[(0,t.jsxs)("div",{className:"flex items-center justify-between gap-3",children:[(0,t.jsx)("p",{className:"min-w-0 truncate font-mono text-sm text-muted-foreground",title:E,children:E}),(0,t.jsx)(tM,{host:_})]}),y&&k?(0,t.jsxs)("div",{className:"mt-6 flex flex-wrap items-center justify-between gap-3 rounded-lg border border-border bg-muted/40 px-3 py-2",children:[(0,t.jsxs)("div",{className:"flex min-w-0 items-center gap-2 text-sm",children:[(0,t.jsx)(Hi,{name:y.name,logoUrl:y.branding.logoUrl,darkLogoUrl:y.branding.darkLogoUrl,size:24}),(0,t.jsxs)("span",{className:"truncate",children:["Paperclip has a guided setup for ",y.name,"."]})]}),(0,t.jsxs)($,{type:"button",size:"sm",variant:"outline",onClick:k,children:["Use ",y.name]})]}):null,v?(0,t.jsx)("div",{className:"mt-6",children:(0,t.jsx)(ua,{tone:"warning",title:v.title,children:v.body})}):null,(0,t.jsxs)("div",{className:"mt-6 space-y-6",children:[T?(0,t.jsx)("div",{className:"space-y-4",children:(0,t.jsxs)("div",{children:[(0,t.jsx)("label",{className:"text-sm font-medium text-foreground",htmlFor:"generic-mcp-key",children:"App key"}),(0,t.jsx)(dt,{id:"generic-mcp-key",type:"password",autoComplete:"off",value:a,onChange:r(O=>i(O.target.value),"onChange"),placeholder:"••••••••••••••••",className:"mt-2 h-11 font-mono"}),(0,t.jsx)("p",{className:"mt-2 text-xs text-muted-foreground",children:"Grant this key read and write access to the resources your agents need. Paperclip cannot increase its permissions."})]})}):null,(0,t.jsxs)(tl,{open:x,onOpenChange:g,children:[(0,t.jsxs)(Dl,{className:"flex w-full items-center justify-between rounded-lg border border-border bg-background px-3 py-2 text-left text-sm font-medium text-foreground hover:bg-accent/40",children:["Advanced authentication",(0,t.jsx)(an,{className:W("h-4 w-4 text-muted-foreground transition-transform",x&&"rotate-180")})]}),(0,t.jsxs)(sl,{className:"space-y-5 pt-4",children:[(0,t.jsx)("p",{className:"text-xs text-muted-foreground",children:"Only needed when the server's docs are specific about how to authenticate."}),(0,t.jsx)("div",{className:"flex flex-wrap gap-2",children:jae.map(O=>(0,t.jsx)(Jmt,{label:O.label,selected:o===O.mode,onClick:r(()=>l(O.mode),"onClick")},O.mode))}),(0,t.jsx)("p",{className:"text-xs text-muted-foreground",children:jae.find(O=>O.mode===o)?.hint}),o==="custom_headers"?(0,t.jsxs)("div",{className:"space-y-3",children:[c.map(O=>(0,t.jsxs)("div",{className:"flex items-start gap-2",children:[(0,t.jsx)(dt,{value:O.name,onChange:r(M=>P(O.id,{name:M.target.value}),"onChange"),placeholder:"Header name","aria-label":"Header name",className:"h-10 font-mono"}),(0,t.jsx)(dt,{type:"password",autoComplete:"off",value:O.value,onChange:r(M=>P(O.id,{value:M.target.value}),"onChange"),placeholder:"Value","aria-label":O.name.trim()?`Value for ${O.name.trim()}`:"Header value",className:"h-10 font-mono"}),(0,t.jsx)($,{type:"button",variant:"ghost",size:"sm",className:"h-10 shrink-0",onClick:r(()=>d(c.filter(M=>M.id!==O.id)),"onClick"),disabled:c.length===1,children:"Remove"})]},O.id)),(0,t.jsx)($,{type:"button",variant:"outline",size:"sm",onClick:r(()=>d([...c,Oz()]),"onClick"),children:"Add another header"}),R?(0,t.jsx)("p",{className:"text-xs text-destructive",children:R}):null]}):null,o==="oauth"?(0,t.jsxs)("div",{className:"space-y-4",children:[(0,t.jsx)("p",{className:"text-xs text-muted-foreground",children:"Paperclip sets sign-in up on its own whenever the server allows it. Only fill these in when the server's docs tell you to register Paperclip yourself first."}),(0,t.jsxs)("div",{children:[(0,t.jsx)("label",{className:"text-sm font-medium text-foreground",htmlFor:"generic-mcp-client-id",children:"Client ID"}),(0,t.jsx)(dt,{id:"generic-mcp-client-id",value:u,onChange:r(O=>h(O.target.value),"onChange"),autoComplete:"off",placeholder:"Optional",className:"mt-2 h-11 font-mono"})]}),(0,t.jsxs)("div",{children:[(0,t.jsx)("label",{className:"text-sm font-medium text-foreground",htmlFor:"generic-mcp-client-secret",children:"Client secret"}),(0,t.jsx)(dt,{id:"generic-mcp-client-secret",type:"password",autoComplete:"off",value:p,onChange:r(O=>f(O.target.value),"onChange"),placeholder:"Optional",className:"mt-2 h-11 font-mono"})]})]}):null]})]})]}),N,(0,t.jsxs)("div",{className:"mt-8 flex items-center justify-between",children:[(0,t.jsx)($,{variant:"ghost",onClick:S,disabled:w,children:"Back"}),(0,t.jsxs)($,{onClick:C,disabled:w||!I||!!R,children:[w&&(0,t.jsx)(st,{className:"mr-2 h-4 w-4 animate-spin"}),w?"Checking…":"Check link"]})]})]})}r(Zmt,"LinkConnectStep");var jae=[{mode:"auto",label:"Let Paperclip check",hint:"Paperclip asks the server what it needs and walks you through it. Start here."},{mode:"none",label:"No sign-in needed",hint:"The server is open to anyone with the address."},{mode:"bearer",label:"Key or token",hint:"Paperclip sends your key as an Authorization header."},{mode:"custom_headers",label:"Custom headers",hint:"For servers that name their own headers. Values are stored as Paperclip secrets and can’t be read back."},{mode:"oauth",label:"Browser sign-in",hint:"You’ll sign in at the provider. Add a client ID and secret only if the provider requires you to register Paperclip first."}];function Jmt({label:e,selected:s,onClick:n}){return(0,t.jsx)("button",{type:"button",onClick:n,"aria-pressed":s,className:W("min-w-(--sz-64px) rounded-md px-4 py-1.5 text-sm font-medium transition-colors",s?"bg-background text-foreground shadow-sm":"text-muted-foreground hover:text-foreground"),children:e})}r(Jmt,"SegmentedOption");function Xmt({settingsValid:e=!0,entry:s,error:n,values:a,onChange:i,oauthClientId:o,onOAuthClientIdChange:l,oauthClientSecret:c,oauthCallbackUrl:d,canReuseOAuthClientSecret:u,onOAuthClientSecretChange:h,credentialSource:p,vercelConnector:f,onVercelConnectorChange:x,vercelConnectAvailability:g,methodKey:v,onMethodChange:y,configValues:k,onConfigChange:w,googleSheetsLinks:N,googleSheetsError:S,onGoogleSheetsLinksChange:C,submitting:_,renderDefaults:R,onBack:I,onConnect:T}){const E=(0,m.useMemo)(()=>D1(s,p),[p,s]),P=v?E.find(qe=>qe.key===v)??null:Rk(E),O=(0,m.useMemo)(()=>E.some(qe=>qe.capabilityProfile)?Array.from(E.reduce((qe,it)=>{const _t=it.capabilityProfile.key,$t=qe.get(_t);return $t?$t.methods.push(it):qe.set(_t,{key:_t,label:it.capabilityProfile?.label??it.label??it.key,description:it.capabilityProfile?.description??it.whenToUse,methods:[it]}),qe},new Map)).map(([,qe])=>qe):[],[E]),M=P?.capabilityProfile?.key??P?.key??"",Q=O.map(qe=>qe.key).join("|"),[L,F]=(0,m.useState)(M||Rk(E)?.capabilityProfile?.key||(O.length===1?O[0].key:""));(0,m.useEffect)(()=>{if(M){F(M);return}F(qe=>O.some(it=>it.key===qe)?qe:Rk(E)?.capabilityProfile?.key||(O.length===1?O[0].key:""))},[Q,O,E,M]);const q=O.length>1?O.find(qe=>qe.key===L)?.methods??[]:E,z=(P?.credentialFields??[]).map(qe=>({...qe,configPath:Yge(qe,P),helpUrl:P?.consoleLinks?.keys??P?.consoleLinks?.docs??""})),K=P?.credentialSources?.vercelConnect??null,U=p==="vercel_connect",V=U||z.every(qe=>qe.required===!1||(a[qe.configPath]?.trim().length??0)>0),ne=fk(P),Z=ne&&!T0(P),ie=U||!Z||o.trim().length>0&&(!P?.oauthClientSecretRequired||u||c.trim().length>0),J=!U||f.trim().length>0,ae=P?.auth==="oauth"&&ne?d:null,oe=[...P?.tenantFields??[],...P?.extensionFields??[]],G=oe.filter(qe=>!qe.hidden),X=G.filter(qe=>qe.advanced!==!0),Y=G.filter(qe=>qe.advanced===!0),re=oe.every(qe=>{if(!qe.required)return!0;const it=k[qe.key];return typeof it=="boolean"||typeof it=="string"&&it.trim().length>0}),se=P?.configRequirements?.atLeastOneOf??[],ce=se.length===0||se.some(qe=>{const it=k[qe];return typeof it=="string"&&it.trim().length>0}),pe=(O.length<=1||!!L)&&(q.length<=1?!!P:!!v),fe=s.availability?.robotEmail??null,ve=s.availability?.available===!1,Ie=!U&&ne&&!Z,de=O.length>1||q.length>1,xe=O.length>1?(0,t.jsxs)("div",{children:[(0,t.jsx)("label",{className:"text-sm font-medium text-foreground",children:"What should Paperclip be able to do?"}),(0,t.jsx)(am,{ariaLabel:`Access level for ${s.name}`,className:"mt-2",value:L,onValueChange:r(qe=>{const it=O.find(_t=>_t.key===qe);it&&(F(qe),y(RQ(it.methods)))},"onValueChange"),options:O.map(qe=>({value:qe.key,title:qe.label,description:qe.description}))}),!L&&(0,t.jsx)("p",{className:"mt-2 text-xs text-muted-foreground",children:"Choose an access level to continue."})]}):null,le=q.find(qe=>qe.oauthStrategy==="paperclip_cloud_connector"),Re=le&&q.find(qe=>fk(qe)&&!T0(qe)),Le=P?.key===Re?.key,je=(0,m.useId)(),_e=le&&Re&&q.length===2?(0,t.jsx)($,{type:"button",variant:"link",className:"h-auto p-0 text-xs text-muted-foreground underline underline-offset-2 hover:text-foreground","aria-expanded":Le,"aria-controls":je,disabled:_,onClick:r(()=>y(Le?le:Re),"onClick"),children:Le?"Use Paperclip instead":`Use your own ${A$e(le.connectorProfile??"")?"Google":s.name} OAuth app`}):q.length>1?(0,t.jsxs)("div",{children:[(0,t.jsx)("label",{className:"text-sm font-medium text-foreground",children:"How do you want to connect?"}),(0,t.jsx)(am,{ariaLabel:`How to connect ${s.name}`,className:"mt-2",value:v,onValueChange:r(qe=>{const it=q.find(_t=>_t.key===qe);it&&y(it)},"onValueChange"),options:q.map(qe=>({value:qe.key,title:qe.label??(qe.auth==="oauth"?`Sign in with ${s.name}`:"Use an API key")}))}),!P&&(0,t.jsx)("p",{className:"mt-2 text-xs text-muted-foreground",children:"Choose a connection method to continue."})]}):null,Ze=Y.length>0||Ie||de,ue=Le||!pe,Fe=Ze?(0,t.jsxs)("div",{className:"space-y-6",children:[xe,_e,Y.map(qe=>(0,t.jsx)(wae,{field:qe,value:k[qe.key],onChange:r(it=>w({...k,[qe.key]:it}),"onChange")},qe.key)),Ie?(0,t.jsx)(zz,{entry:s,method:P,callbackUrl:ae,clientId:o,onClientIdChange:l,clientSecret:c,onClientSecretChange:h,required:!1}):null]}):null,mt=R?.(Fe,ue)??null;if(CC(s,P)){const qe=zF(N),it=e&&!ve&&!!fe&&N.trim().length>0;return(0,t.jsxs)("div",{className:"mx-auto max-w-xl",children:[(0,t.jsxs)("div",{className:"space-y-6",children:[xe,fe?(0,t.jsxs)("div",{children:[(0,t.jsx)("label",{className:"text-sm font-medium text-foreground",children:"Share each sheet with this email"}),(0,t.jsxs)("div",{className:"mt-2 flex min-w-0 flex-col gap-2 sm:flex-row",children:[(0,t.jsx)("div",{title:fe,className:"min-h-11 min-w-0 flex-1 rounded-md border border-input bg-muted/40 px-3 py-2.5 font-mono text-xs leading-tight text-foreground break-all",children:fe}),(0,t.jsx)(u5e,{value:fe,ariaLabel:"Copy sharing email"})]}),(0,t.jsx)("p",{className:"mt-2 text-xs text-muted-foreground",children:"In Google Sheets, click Share and add this email as an Editor. Then paste the sheet links below."})]}):(0,t.jsx)("div",{className:"rounded-lg bg-muted/50 p-4 text-sm text-muted-foreground",children:"Google Sheets is not available on this instance yet."}),(0,t.jsxs)("div",{children:[(0,t.jsx)("label",{className:"text-sm font-medium text-foreground",children:"Paste links to the sheets you shared"}),(0,t.jsx)(Hn,{value:N,onChange:r(_t=>C(_t.target.value),"onChange"),placeholder:"https://docs.google.com/spreadsheets/d/...",className:"mt-2 min-h-28"}),(0,t.jsx)("div",{className:"mt-2 text-xs text-muted-foreground",children:qe.ids.length>0?`${qe.ids.length} ${qe.ids.length===1?"sheet":"sheets"} ready to connect.`:"Paste one link per line. Both .../edit and .../edit#gid=... links work."}),S&&(0,t.jsx)("div",{className:"mt-2 text-xs text-destructive",children:S})]})]}),mt,(0,t.jsxs)("div",{className:"mt-8 flex items-center justify-between",children:[(0,t.jsx)($,{variant:"ghost",onClick:I,disabled:_,children:"Back"}),(0,t.jsxs)($,{onClick:T,disabled:_||!it,children:[_&&(0,t.jsx)(st,{className:"mr-2 h-4 w-4 animate-spin"}),_?"Checking…":"Connect"]})]})]})}const bt=P?.connectorProfile==="asana.mcp",et=bt?null:P?.consoleLinks?.docs??s.docsUrl;return(0,t.jsxs)("div",{className:"mx-auto max-w-xl",children:[et?(0,t.jsx)("div",{className:"mb-4 flex justify-end",children:(0,t.jsxs)("a",{href:et,target:"_blank",rel:"noreferrer",className:"inline-flex items-center gap-1 text-xs font-medium text-muted-foreground underline underline-offset-2 hover:text-foreground",children:["Review requirements",(0,t.jsx)(oo,{className:"h-3 w-3"})]})}):null,(0,t.jsxs)("div",{className:"space-y-6",children:[bt?(0,t.jsx)("p",{className:"text-sm text-muted-foreground",children:"Sign in with Asana to choose your workspace and connect it to Paperclip."}):null,P?.capabilityProfile&&(0,t.jsxs)("p",{className:"text-sm text-muted-foreground",children:[P.capabilityProfile.label,": ",P.capabilityProfile.description]}),U&&K&&g?(0,t.jsxs)("div",{className:"space-y-4 rounded-lg border border-border p-4",children:[(0,t.jsxs)("div",{children:[(0,t.jsx)("div",{className:"text-sm font-medium text-foreground",children:"Create or attach the connector in Vercel"}),(0,t.jsx)("p",{className:"mt-1 text-xs text-muted-foreground",children:"Paperclip does not copy Vercel’s setup forms. Finish connector setup there, then paste its UID below."}),(0,t.jsxs)("a",{href:g.manageUrl,target:"_blank",rel:"noreferrer",className:"mt-2 inline-flex items-center gap-1 text-xs font-semibold text-foreground underline underline-offset-2",children:["Open Vercel Connect",(0,t.jsx)(oo,{className:"h-3 w-3"})]})]}),(0,t.jsxs)("div",{children:[(0,t.jsx)("label",{className:"text-sm font-medium text-foreground",htmlFor:"vercel-connect-connector",children:"Connector UID or ID"}),(0,t.jsx)(dt,{id:"vercel-connect-connector",value:f,onChange:r(qe=>x(qe.target.value),"onChange"),autoComplete:"off",placeholder:"service/my-connector or scl_…",className:"mt-2 h-11 font-mono"}),(0,t.jsx)("p",{className:"mt-2 text-xs text-muted-foreground",children:"Paperclip validates the connector and stores only its reference and redacted verification metadata."})]})]}):null,n?(0,t.jsx)("div",{role:"alert",children:(0,t.jsx)(ua,{tone:"danger",children:n})}):null,X.map(qe=>(0,t.jsx)(wae,{field:qe,value:k[qe.key],onChange:r(it=>w({...k,[qe.key]:it}),"onChange")},qe.key)),!U&&P?.auth==="oauth"&&Z?(0,t.jsx)("div",{id:je,role:"region","aria-label":"Your OAuth app",children:(0,t.jsx)(zz,{entry:s,method:P,callbackUrl:ae,clientId:o,onClientIdChange:l,clientSecret:c,onClientSecretChange:h,required:!0})}):null,U||!P||z.length===0?null:z.map(qe=>(0,t.jsxs)("div",{children:[(0,t.jsx)("label",{className:"text-sm font-medium text-foreground",children:aae(s.name,qe.label,z.length)}),(0,t.jsx)(dt,{type:qe.type==="text"&&qe.secret===!1?"text":"password","aria-label":aae(s.name,qe.label,z.length),autoComplete:"off",value:a[qe.configPath]??"",onChange:r(it=>i({...a,[qe.configPath]:it.target.value}),"onChange"),placeholder:qe.type==="text"&&qe.secret===!1?qe.placeholder:"••••••••••••••••",className:"mt-2 h-11 font-mono"}),qe.helperMd&&(0,t.jsx)("p",{className:"mt-2 text-xs text-muted-foreground",children:qe.helperMd}),qe.helpUrl&&(0,t.jsxs)("a",{href:qe.helpUrl,target:"_blank",rel:"noreferrer",className:"mt-2 inline-flex items-center gap-1 text-xs font-semibold text-foreground underline underline-offset-2",children:["Where do I find this?",(0,t.jsx)(oo,{className:"h-3 w-3"})]})]},qe.configPath))]}),mt,(0,t.jsxs)("div",{className:"mt-8 flex items-center justify-between",children:[(0,t.jsx)($,{variant:"ghost",onClick:I,disabled:_,children:"Back"}),(0,t.jsxs)($,{onClick:T,disabled:_||!e||!pe||!V||!ie||!J||!re||!ce,children:[_&&(0,t.jsx)(st,{className:"mr-2 h-4 w-4 animate-spin"}),_?"Checking…":U?P?.auth==="oauth"?"Validate and continue":"Validate and connect":P?.auth==="oauth"?s.slug==="github"?"Continue to GitHub":"Continue to sign in":"Connect"]})]})]})}r(Xmt,"KeyStep");function u5e({value:e,ariaLabel:s}){const{copied:n,failed:a,copy:i}=ep();return(0,t.jsxs)($,{type:"button",variant:"outline",className:"shrink-0","aria-label":s,onClick:r(()=>{i(e)},"onClick"),children:[n?(0,t.jsx)(ms,{className:"mr-2 h-4 w-4"}):(0,t.jsx)(br,{className:"mr-2 h-4 w-4"}),n?"Copied":a?"Copy failed":"Copy"]})}r(u5e,"CopyValueButton");function zz({entry:e,method:s,callbackUrl:n,clientId:a,onClientIdChange:i,clientSecret:o,onClientSecretChange:l,required:c}){return(0,t.jsxs)("div",{className:"space-y-4 rounded-lg border border-border p-4",children:[(0,t.jsxs)("div",{children:[(0,t.jsx)("div",{className:"text-sm font-medium text-foreground",children:c?s.oauthClientSecretRequired?"Your OAuth app":`${e.name} needs its own OAuth app`:"Use your own OAuth app"}),(0,t.jsx)("p",{className:"mt-1 text-xs text-muted-foreground",children:s.oauthClientSecretRequired?s.guidanceMd:c?`${e.name} does not let Paperclip register itself automatically, so this connector needs an OAuth app you create. Add the callback URL below in ${e.name}, then paste the client details back here.`:`Register Paperclip's callback URI in ${e.name}, then enter the customer-owned client details.`}),s.consoleLinks?.register?(0,t.jsxs)("a",{href:s.consoleLinks.register,target:"_blank",rel:"noreferrer",className:"mt-2 inline-flex items-center gap-1 text-xs font-semibold text-foreground underline underline-offset-2",children:["Open ",e.name," app settings",(0,t.jsx)(oo,{className:"h-3 w-3"})]}):null]}),n?(0,t.jsxs)("div",{children:[(0,t.jsx)("label",{className:"text-sm font-medium text-foreground",children:"Paperclip callback URL"}),(0,t.jsxs)("div",{className:"mt-2 flex min-w-0 flex-col gap-2 sm:flex-row",children:[(0,t.jsx)("div",{title:n,className:"min-h-11 min-w-0 flex-1 rounded-md border border-input bg-muted/40 px-3 py-2.5 font-mono text-xs leading-tight text-foreground break-all",children:n}),(0,t.jsx)(u5e,{value:n,ariaLabel:"Copy callback URL"})]}),(0,t.jsxs)("p",{className:"mt-2 text-xs text-muted-foreground",children:["Add this exact URL to ",e.name," before continuing. It must match the authorization request."]})]}):null,(0,t.jsxs)("div",{children:[(0,t.jsx)("label",{className:"text-sm font-medium text-foreground",htmlFor:"curated-oauth-client-id",children:"Client ID"}),(0,t.jsx)(dt,{id:"curated-oauth-client-id",value:a,onChange:r(d=>i(d.target.value),"onChange"),autoComplete:"off",placeholder:c?"Required":"Optional",className:"mt-2 h-11 font-mono"})]}),(0,t.jsxs)("div",{children:[(0,t.jsx)("label",{className:"text-sm font-medium text-foreground",htmlFor:"curated-oauth-client-secret",children:"Client secret"}),(0,t.jsx)(dt,{id:"curated-oauth-client-secret",type:"password",value:o,onChange:r(d=>l(d.target.value),"onChange"),autoComplete:"off",placeholder:s.oauthClientSecretRequired?"Required":"Optional for public clients",className:"mt-2 h-11 font-mono"})]})]})}r(zz,"OAuthClientFields");function wae({field:e,value:s,onChange:n}){return e.type==="checkbox"?(0,t.jsxs)("div",{className:"flex items-start justify-between gap-4 rounded-lg border border-border p-4",children:[(0,t.jsxs)("div",{children:[(0,t.jsx)("div",{className:"text-sm font-medium text-foreground",children:e.label}),e.helperMd&&(0,t.jsx)("div",{className:"mt-1 text-xs text-muted-foreground",children:e.helperMd})]}),(0,t.jsx)(ai,{checked:s===!0,onCheckedChange:n})]}):(0,t.jsxs)("div",{children:[(0,t.jsx)("label",{className:"text-sm font-medium text-foreground",children:e.label}),e.type==="textarea"?(0,t.jsx)(Hn,{value:typeof s=="string"?s:"",onChange:r(a=>n(a.target.value),"onChange"),placeholder:e.placeholder,className:"mt-2 min-h-24"}):e.type==="select"?(0,t.jsxs)("select",{value:typeof s=="string"?s:"",onChange:r(a=>n(a.target.value),"onChange"),className:"mt-2 h-11 w-full rounded-md border border-input bg-background px-3 text-sm text-foreground outline-none focus-visible:border-ring focus-visible:ring-3 focus-visible:ring-ring/30",children:[(0,t.jsx)("option",{value:"",disabled:!0,children:"Select an option"}),(e.options??[]).map(a=>(0,t.jsx)("option",{value:a.value,children:a.label},a.value))]}):(0,t.jsx)(dt,{value:typeof s=="string"?s:"",onChange:r(a=>n(a.target.value),"onChange"),placeholder:e.placeholder,"aria-label":e.label,maxLength:e.validation?.maxLength,className:"mt-2 h-11"}),e.required&&(typeof s!="string"||!s.trim())&&(0,t.jsxs)("p",{className:"mt-2 text-xs text-muted-foreground",children:[e.label," is required."]}),e.helperMd&&(0,t.jsx)("p",{className:"mt-2 text-xs text-muted-foreground",children:e.helperMd})]})}r(wae,"MethodConfigField");function eht({companyId:e,...s}){const n=te({queryKey:D.agents.list(e),queryFn:r(()=>Nt.list(e),"queryFn")});return(0,t.jsx)(AV,{...s,agents:(n.data??[]).filter(a=>a.status!=="terminated"),agentsLoading:n.isLoading})}r(eht,"AccessStep");function AV({agents:e,agentsLoading:s=!1,authKind:n,grantKinds:a,grantKind:i,setGrantKind:o,installChoice:l,setInstallChoice:c,installAgentIds:d,setInstallAgentIds:u,lockedAgentId:h,capabilities:p,githubIdentity:f=!1,submitLabel:x,continuesToProvider:g=!1,identityLoading:v=!1,preserveAgentAccess:y=!1,pending:k=!1,hideFooter:w=!1,bare:N=!1,onBack:S,onContinue:C}){const _=p?.editableAgentIds,R=_?e.filter(q=>_.includes(q.id)):e,I=p?.canSetCompanyInstall??!0,T=p?.canCreateOrganizationGrant??!0,E=n!=="none",P=a??["user","organization"],O=(!E||i==="user"||i==="agent"||T)&&(y?!0:h?d.has(h):i==="agent"?l==="specific"&&d.size===1:l==="all"?I:d.size>0),M=h?e.find(q=>q.id===h)?.name??"the requesting agent":null,Q=f?"Connect GitHub as":"Which humans can use this credential?",L=i==="agent"?"Which agent owns this GitHub account?":f&&i==="user"?"Which agents may use your GitHub when you’re responsible?":f?"Which agents may use the shared GitHub account?":"Which agents can use this connection?",F=f?L:"Which agents can use this connection?";return(0,t.jsxs)("div",{className:N?"":"mx-auto max-w-2xl",children:[(0,t.jsx)("div",{className:"overflow-hidden rounded-xl border border-border bg-background",children:(0,t.jsxs)("div",{className:"divide-y divide-border",children:[(0,t.jsxs)("section",{className:"p-6",children:[(0,t.jsx)("h2",{className:"text-sm font-semibold text-foreground",children:Q}),f&&i==="agent"?(0,t.jsx)("p",{className:"mt-2 text-sm text-muted-foreground",children:"This agent uses this GitHub account for everyone’s work, instead of the person giving instructions."}):null,v?(0,t.jsxs)("div",{className:"mt-4 grid gap-2 sm:grid-cols-2","aria-label":"Loading connection identity",children:[(0,t.jsx)(yn,{className:"h-20 w-full rounded-md"}),(0,t.jsx)(yn,{className:"h-20 w-full rounded-md"})]}):E&&P.length===1?(0,t.jsxs)("div",{className:"mt-4 flex items-center gap-3 rounded-md border border-border p-4",children:[P[0]==="user"?(0,t.jsx)(oh,{className:"h-4 w-4 shrink-0 text-muted-foreground","aria-hidden":"true"}):P[0]==="agent"?(0,t.jsx)(ao,{className:"h-4 w-4 shrink-0 text-muted-foreground","aria-hidden":"true"}):(0,t.jsx)(jk,{className:"h-4 w-4 shrink-0 text-muted-foreground","aria-hidden":"true"}),(0,t.jsxs)("div",{children:[(0,t.jsx)("div",{className:"text-sm font-medium text-foreground",children:P[0]==="user"?f?"My GitHub account":"Just me":P[0]==="agent"?"A dedicated account for an agent":f?"Shared organization GitHub account (advanced)":"Any human in the organization"}),f?(0,t.jsx)("p",{className:"mt-1 text-xs text-muted-foreground",children:P[0]==="user"?"Agents use it only for runs where you are the responsible person.":P[0]==="agent"?"That agent always uses this account, regardless of who starts the run.":"Eligible agents use one shared credential, regardless of who starts the run."}):null]})]}):E?(0,t.jsx)(am,{ariaLabel:f?Q:"Which humans can use this credential?",className:"mt-4 sm:grid-cols-2",value:i,onValueChange:r(q=>{const z=q;o(z),z==="agent"&&(c("specific"),d.size>1&&u(new Set([[...d][0]])))},"onValueChange"),options:[{value:"user",title:f?"My GitHub account":"Just me",description:f?"Agents use it only for runs where you are the responsible person.":void 0,icon:(0,t.jsx)(oh,{className:"h-4 w-4","aria-hidden":"true"})},{value:"agent",title:"A dedicated account for an agent",description:f?"That agent always uses this account, regardless of who starts the run.":void 0,icon:(0,t.jsx)(ao,{className:"h-4 w-4","aria-hidden":"true"})},{value:"organization",title:f?"Shared organization GitHub account (advanced)":"Any human in the organization",description:f?"Eligible agents use one shared credential, regardless of who starts the run.":void 0,icon:(0,t.jsx)(jk,{className:"h-4 w-4","aria-hidden":"true"}),accessibleLabel:T?f?"Shared organization GitHub account (advanced)":"Any human in the organization":`${f?"Shared organization GitHub account (advanced)":"Any human in the organization"}. Unavailable: ${p?.organizationGrantReason??"Only a connection manager can share this credential with the organization."}`,tooltip:T?void 0:p?.organizationGrantReason??"Only a connection manager can share this credential with the organization.",disabled:!T}].filter(q=>P.includes(q.value))}):(0,t.jsx)("p",{className:"mt-4 text-sm text-muted-foreground",children:"No identity required"})]}),(0,t.jsxs)("section",{className:"p-6",children:[(0,t.jsx)("h2",{className:"text-sm font-semibold text-foreground",children:L}),y?(0,t.jsxs)("div",{className:"mt-4 flex items-start gap-3 rounded-md border border-border bg-muted/40 p-4",children:[(0,t.jsx)(jk,{className:"mt-0.5 h-4 w-4 shrink-0 text-primary","aria-hidden":"true"}),(0,t.jsxs)("div",{children:[(0,t.jsx)("div",{className:"text-sm font-medium text-foreground",children:"Existing agent access stays the same"}),(0,t.jsx)("p",{className:"mt-1 text-xs text-muted-foreground",children:"Reconnecting replaces the credential without changing which agents can use it."})]})]}):h?(0,t.jsxs)("p",{className:"mt-2 text-sm text-muted-foreground",children:["This task grants access only to ",(0,t.jsx)("span",{className:"font-medium text-foreground",children:M}),". Existing connection access is left unchanged."]}):i==="agent"?(0,t.jsx)("p",{className:"mt-2 text-sm text-muted-foreground",children:"Choose exactly one agent. This identity cannot be shared with other agents."}):(0,t.jsx)(am,{ariaLabel:F,className:"mt-4 sm:grid-cols-2",value:l,onValueChange:r(q=>c(q),"onValueChange"),options:[{value:"specific",title:f?"Only agents I choose":"Just agents I pick",description:f?i==="user"?"Only selected agents may use your GitHub when you’re responsible.":"Only selected agents may use the shared account.":void 0,icon:(0,t.jsx)(ao,{className:"h-4 w-4","aria-hidden":"true"})},{value:"all",title:"Any agent",description:f?i==="user"?"Every agent may use your GitHub when you’re responsible.":"Every agent may use the shared account.":void 0,icon:(0,t.jsx)(tht,{}),accessibleLabel:I?"Any agent":`Any agent. Unavailable: ${p?.companyInstallReason??"Only someone who can configure this connection can choose this."}`,tooltip:I?void 0:p?.companyInstallReason??"Only someone who can configure this connection can choose this.",disabled:!I}]}),!y&&!h&&l==="specific"?(0,t.jsx)("div",{className:"mt-3",children:(0,t.jsx)(Qj,{agents:R,selectedAgentIds:d,onChange:r(q=>u(i==="agent"&&q.size>1?new Set([[...q].at(-1)]):q),"onChange"),loading:s,emptyMessage:"You cannot edit any agents yet.",showSelectionPreview:!1})}):null]})]})}),w?null:(0,t.jsxs)("div",{className:"mt-6 flex flex-col-reverse gap-2 sm:flex-row sm:items-center sm:justify-between",children:[(0,t.jsx)($,{variant:"ghost",className:"w-full sm:w-auto",onClick:S,disabled:k,children:"Back"}),(0,t.jsxs)($,{className:"w-full sm:w-auto",onClick:C,disabled:!O||v||k,children:[k?(0,t.jsx)(st,{className:"h-4 w-4 animate-spin","aria-hidden":"true"}):null,x,!k&&g?(0,t.jsx)(oo,{className:"h-4 w-4","aria-hidden":"true"}):null]})]})]})}r(AV,"AccessStepContent");function AE(e){return`${e.authKind==="none"?"No sign-in needed":e.grantKind==="user"?"Connects as you":e.grantKind==="agent"?"Connects as a dedicated agent account":"Connects for everyone in your organization"}, ${e.preserveAgentAccess?"agent access stays as it is":e.lockedAgentId?"available to the agent that asked for it":e.installChoice==="all"?"available to all agents":e.installCount===0?"no agents selected yet":`available to ${e.installCount} selected ${e.installCount===1?"agent":"agents"}`}.`}r(AE,"connectionDefaultSummarySentence");function IV({companyId:e,agents:s,sentence:n,notice:a,extra:i,forceOpen:o=!1,disabled:l=!1,...c}){const[d,u]=(0,m.useState)(!1);return(0,t.jsxs)(tl,{open:d||o,onOpenChange:u,className:"mt-6 rounded-lg border border-border bg-muted/30 px-4 py-3",children:[(0,t.jsxs)("div",{className:"flex flex-wrap items-baseline justify-between gap-x-3 gap-y-1",children:[(0,t.jsx)("p",{className:"text-sm text-muted-foreground",children:n}),(0,t.jsx)(Dl,{asChild:!0,children:(0,t.jsx)($,{type:"button",variant:"link",className:"h-auto p-0 text-xs font-semibold underline underline-offset-2",disabled:l,children:"Change"})})]}),(a??[]).map(h=>(0,t.jsx)("p",{className:"mt-2 text-xs text-muted-foreground",children:h},h)),(0,t.jsx)(sl,{children:(0,t.jsxs)("div",{className:"mt-3 space-y-6",children:[i,s?(0,t.jsx)(AV,{...c,agents:s,bare:!0,hideFooter:!0,submitLabel:"",onBack:r(()=>{},"onBack"),onContinue:r(()=>{},"onContinue")}):(0,t.jsx)(eht,{...c,companyId:e,bare:!0,hideFooter:!0,submitLabel:"",onBack:r(()=>{},"onBack"),onContinue:r(()=>{},"onContinue")})]})})]})}r(IV,"ConnectionAccessDefaults");function tht(){return(0,t.jsxs)("span",{className:"relative block h-4 w-5","aria-hidden":"true",children:[(0,t.jsx)(ao,{className:"absolute left-0 top-0 h-3.5 w-3.5"}),(0,t.jsx)(ao,{className:"absolute bottom-0 right-0 h-3.5 w-3.5"})]})}r(tht,"BotGroupIcon");function sht(e){const s=e.authKind==="none"?"No identity required":e.grantKind==="user"?"Your identity":e.grantKind==="agent"?"Dedicated agent identity":"Organization identity",n=e.installChoice==="all"?"Any agent":`${e.installCount} selected ${e.installCount===1?"agent":"agents"}`;return[{label:"Identity",value:s},{label:"Available to",value:n},{label:"Actions",value:`${e.enabledCount} ${e.enabledCount===1?"action":"actions"} on`}]}r(sht,"accessSummaryLines");function nht({appName:e,logoUrl:s,darkLogoUrl:n,summary:a,statedDefault:i,onDone:o}){return(0,t.jsxs)("div",{className:"mx-auto max-w-md py-10 text-center",children:[(0,t.jsx)("div",{className:"mx-auto flex h-20 w-20 items-center justify-center rounded-full border-2 border-emerald-500 bg-emerald-500/10",children:(0,t.jsx)(ms,{className:"h-9 w-9 text-emerald-600 dark:text-emerald-400"})}),(0,t.jsxs)("div",{className:"mt-6 flex items-center justify-center gap-2",children:[(0,t.jsx)(Hi,{name:e,logoUrl:s,darkLogoUrl:n,size:28}),(0,t.jsxs)("h2",{className:"text-2xl font-bold tracking-tight",children:[e," is ready."]})]}),i?(0,t.jsx)("p",{className:"mt-3 text-sm text-muted-foreground",children:i}):null,(0,t.jsx)("dl",{className:"mx-auto mt-6 max-w-xs space-y-1 text-left",children:a.map(l=>(0,t.jsxs)("div",{className:"flex items-baseline justify-between gap-4",children:[(0,t.jsx)("dt",{className:"text-xs font-medium text-muted-foreground",children:l.label}),(0,t.jsx)("dd",{className:"text-sm text-foreground",children:l.value})]},l.label))}),(0,t.jsx)("div",{className:"mt-8",children:(0,t.jsx)($,{size:"lg",className:"px-10",onClick:o,children:"View connection"})})]})}r(nht,"ConnectionSetupCompletionScreen");function m5e(){const{newProjectOpen:e,closeNewProject:s}=w3(),{selectedCompanyId:n}=fs();return n&&e?(0,t.jsx)(rht,{companyId:n,onClose:s},n):null}r(m5e,"NewProjectDialog");function rht({companyId:e,onClose:s}){const n=wt(),[a,i]=(0,m.useState)(""),[o]=(0,m.useState)(()=>hR[Math.floor(Math.random()*hR.length)]),[l,c]=(0,m.useState)([]),[d,u]=(0,m.useState)(!1),h=(0,m.useRef)(null),p=we({mutationFn:r(()=>aa.create(e,{name:a.trim(),color:o,status:"planned",repositoryIds:l.map(f=>f.id)}),"mutationFn"),onSuccess:r(f=>{Ob(f.id,e),n.invalidateQueries({queryKey:D.projects.all(e)}),s()},"onSuccess")});return(0,t.jsx)(Fs,{open:!0,onOpenChange:r(f=>{!f&&!p.isPending&&s()},"onOpenChange"),children:(0,t.jsx)(Qs,{showCloseButton:!1,"aria-describedby":void 0,className:"flex max-h-(--sz-calc-18) flex-col gap-0 overflow-hidden p-0 shadow-sm sm:max-w-lg",onOpenAutoFocus:r(f=>{f.preventDefault(),h.current?.focus()},"onOpenAutoFocus"),children:d?(0,t.jsxs)("div",{className:"min-h-0 overflow-y-auto p-5",children:[(0,t.jsx)(Ks,{className:"sr-only",children:"Connect GitHub"}),(0,t.jsx)(A2,{host:"dialog",serviceSlug:"github",forceNewConnection:!0,onCancel:r(()=>u(!1),"onCancel"),onComplete:r(()=>{n.invalidateQueries({queryKey:jH(e)}),u(!1)},"onComplete")})]}):(0,t.jsxs)("form",{className:"flex min-h-0 flex-col overflow-hidden",onSubmit:r(f=>{f.preventDefault(),a.trim()&&!p.isPending&&p.mutate()},"onSubmit"),children:[(0,t.jsxs)("div",{className:"flex shrink-0 flex-col gap-4 px-5 pb-4 pt-5",children:[(0,t.jsxs)("div",{className:"flex items-center justify-between gap-3",children:[(0,t.jsx)(Ks,{className:"text-lg font-semibold",children:"Create project"}),(0,t.jsx)($,{type:"button",variant:"ghost",size:"icon-sm",disabled:p.isPending,"aria-label":"Close new project",onClick:s,children:(0,t.jsx)(Mn,{className:"size-4"})})]}),(0,t.jsxs)("div",{className:"flex items-center gap-3 rounded-lg border border-input px-3 focus-within:border-ring focus-within:ring-1 focus-within:ring-ring",children:[(0,t.jsx)(nh,{color:o,size:"sm"}),(0,t.jsx)("input",{ref:h,"aria-label":"Project name",value:a,disabled:p.isPending,onChange:r(f=>i(f.target.value),"onChange"),placeholder:"Project name",required:!0,className:"h-10 w-full min-w-0 border-0 bg-transparent text-base outline-none placeholder:text-muted-foreground md:text-sm"})]})]}),(0,t.jsx)("div",{role:"region","aria-label":"Source repositories",tabIndex:0,className:"min-h-0 overflow-y-auto overscroll-contain px-5 pb-1 outline-none focus-visible:ring-1 focus-visible:ring-inset focus-visible:ring-ring",children:(0,t.jsx)(S2e,{companyId:e,selected:l,onChange:c,onConnect:r(()=>u(!0),"onConnect"),disabled:p.isPending})}),p.isError&&(0,t.jsx)("p",{role:"alert",className:"px-5 pt-3 text-sm text-destructive",children:p.error.message}),(0,t.jsxs)("div",{className:"flex shrink-0 justify-end gap-2 px-5 py-5",children:[(0,t.jsx)($,{type:"button",variant:"ghost",disabled:p.isPending,onClick:s,children:"Cancel"}),(0,t.jsx)($,{type:"submit",disabled:!a.trim()||p.isPending,children:p.isPending?"Creating…":"Create project"})]})]})})})}r(rht,"NewProjectForm");var Fx={list:r(e=>ke.get(`/companies/${e}/goals`),"list"),get:r(e=>ke.get(`/goals/${e}`),"get"),create:r((e,s)=>ke.post(`/companies/${e}/goals`,s),"create"),update:r((e,s)=>ke.patch(`/goals/${e}`,s),"update"),remove:r(e=>ke.delete(`/goals/${e}`),"remove")};function h5e(e){return{"--sc":`var(${e})`}}r(h5e,"scStyle");function aht(e){const s=e.replace(/_/g," ");return s.charAt(0).toUpperCase()+s.slice(1)}r(aht,"sentenceCaseStatus");function ii({status:e,label:s}){return(0,t.jsx)("span",{className:W("inline-flex items-center rounded-full px-2.5 py-0.5 text-xs font-medium whitespace-nowrap shrink-0",XB[e]??"bg-muted text-muted-foreground"),children:s??e.replace(/[_-]/g," ")})}r(ii,"StatusBadge$5");function p5e({status:e}){const s=uBe[e]??"--status-agent-idle",n=e==="active"?"idle":e;return(0,t.jsx)("span",{className:"status-chip inline-flex items-center rounded-full border px-3 py-1 text-xs font-medium leading-none whitespace-nowrap shrink-0",style:h5e(s),children:n.replace(/_/g," ")})}r(p5e,"AgentStatusBadge");function A0({status:e,externalConversationState:s}){const n=e==="in_review"&&s==="waiting"?"idle":e,a=LBe[n]??"--status-task-backlog";return(0,t.jsxs)("span",{className:W("status-chip inline-flex items-center gap-1.5 rounded-full border px-3 py-1 text-xs font-normal leading-none whitespace-nowrap shrink-0",n==="cancelled"&&"line-through"),style:h5e(a),children:[(0,t.jsx)(u3,{status:n,size:"sm"}),aht(n)]})}r(A0,"IssueStatusBadge");var kae={company:"Organization",team:"Team",agent:"Agent",task:"Task"};function f5e(){const{newGoalOpen:e,newGoalDefaults:s,closeNewGoal:n}=w3(),{selectedCompanyId:a,selectedCompany:i}=fs(),o=wt(),[l,c]=(0,m.useState)(""),[d,u]=(0,m.useState)(""),[h,p]=(0,m.useState)("planned"),[f,x]=(0,m.useState)("task"),[g,v]=(0,m.useState)(""),[y,k]=(0,m.useState)(!1),[w,N]=(0,m.useState)(!1),[S,C]=(0,m.useState)(!1),[_,R]=(0,m.useState)(!1),I=(0,m.useRef)(null),T=g||s.parentId||"",{data:E}=te({queryKey:D.goals.list(a),queryFn:r(()=>Fx.list(a),"queryFn"),enabled:!!a&&e}),P=we({mutationFn:r(q=>Fx.create(a,q),"mutationFn"),onSuccess:r(()=>{o.invalidateQueries({queryKey:D.goals.list(a)}),M(),n()},"onSuccess")}),O=we({mutationFn:r(async q=>{if(!a)throw new Error("No organization selected");return dv.uploadImage(a,q,"goals/drafts")},"mutationFn")});function M(){c(""),u(""),p("planned"),x("task"),v(""),k(!1)}r(M,"reset");function Q(){!a||!l.trim()||P.mutate({title:l.trim(),description:d.trim()||void 0,status:h,level:f,...T?{parentId:T}:{}})}r(Q,"handleSubmit");function L(q){q.key==="Enter"&&(q.metaKey||q.ctrlKey)&&(q.preventDefault(),Q())}r(L,"handleKeyDown");const F=(E??[]).find(q=>q.id===T);return(0,t.jsx)(Fs,{open:e,onOpenChange:r(q=>{q||(M(),n())},"onOpenChange"),children:(0,t.jsxs)(Qs,{showCloseButton:!1,className:W("p-0 gap-0",y?"sm:max-w-2xl":"sm:max-w-lg"),onKeyDown:L,children:[(0,t.jsxs)("div",{className:"flex items-center justify-between px-4 py-2.5 border-b border-border",children:[(0,t.jsxs)("div",{className:"flex items-center gap-2 text-sm text-muted-foreground",children:[i&&(0,t.jsx)("span",{className:"bg-muted px-1.5 py-0.5 rounded text-xs font-medium",children:i.issuePrefix}),(0,t.jsx)("span",{className:"text-muted-foreground/60",children:"›"}),(0,t.jsx)("span",{children:s.parentId?"New sub-goal":"New goal"})]}),(0,t.jsxs)("div",{className:"flex items-center gap-1",children:[(0,t.jsx)($,{variant:"ghost",size:"icon-xs",className:"text-muted-foreground",onClick:r(()=>k(!y),"onClick"),children:y?(0,t.jsx)(pwe,{className:"h-3.5 w-3.5"}):(0,t.jsx)(Vj,{className:"h-3.5 w-3.5"})}),(0,t.jsx)($,{variant:"ghost",size:"icon-xs",className:"text-muted-foreground",onClick:r(()=>{M(),n()},"onClick"),children:(0,t.jsx)("span",{className:"text-lg leading-none",children:"×"})})]})]}),(0,t.jsx)("div",{className:"px-4 pt-4 pb-2 shrink-0",children:(0,t.jsx)("input",{className:"w-full text-lg font-semibold bg-transparent outline-none placeholder:text-muted-foreground/50",placeholder:"Goal title",value:l,onChange:r(q=>c(q.target.value),"onChange"),onKeyDown:r(q=>{q.key==="Tab"&&!q.shiftKey&&(q.preventDefault(),I.current?.focus())},"onKeyDown"),autoFocus:!0})}),(0,t.jsx)("div",{className:"px-4 pb-2 overflow-y-auto max-h-(--sz-50vh)",children:(0,t.jsx)(Xc,{ref:I,value:d,onChange:u,placeholder:"Add description...",bordered:!1,contentClassName:W("text-sm text-muted-foreground",y?"min-h-(--sz-220px)":"min-h-(--sz-120px)"),imageUploadHandler:r(async q=>(await O.mutateAsync(q)).contentPath,"imageUploadHandler")})}),(0,t.jsxs)("div",{className:"flex items-center gap-1.5 px-4 py-2 border-t border-border flex-wrap",children:[(0,t.jsxs)(dr,{open:w,onOpenChange:N,children:[(0,t.jsx)(wr,{asChild:!0,children:(0,t.jsx)("button",{className:"inline-flex items-center gap-1.5 rounded-md border border-border px-2 py-1 text-xs hover:bg-accent/50 transition-colors",children:(0,t.jsx)(ii,{status:h})})}),(0,t.jsx)(nr,{className:"w-40 p-1",align:"start",children:bbe.map(q=>(0,t.jsx)("button",{className:W("flex items-center gap-2 w-full px-2 py-1.5 text-xs rounded hover:bg-accent/50 capitalize",q===h&&"bg-accent"),onClick:r(()=>{p(q),N(!1)},"onClick"),children:q},q))})]}),(0,t.jsxs)(dr,{open:S,onOpenChange:C,children:[(0,t.jsx)(wr,{asChild:!0,children:(0,t.jsxs)("button",{className:"inline-flex items-center gap-1.5 rounded-md border border-border px-2 py-1 text-xs hover:bg-accent/50 transition-colors",children:[(0,t.jsx)(Vl,{className:"h-3 w-3 text-muted-foreground"}),kae[f]??f]})}),(0,t.jsx)(nr,{className:"w-40 p-1",align:"start",children:nbe.map(q=>(0,t.jsx)("button",{className:W("flex items-center gap-2 w-full px-2 py-1.5 text-xs rounded hover:bg-accent/50",q===f&&"bg-accent"),onClick:r(()=>{x(q),C(!1)},"onClick"),children:kae[q]??q},q))})]}),(0,t.jsxs)(dr,{open:_,onOpenChange:R,children:[(0,t.jsx)(wr,{asChild:!0,children:(0,t.jsxs)("button",{className:"inline-flex items-center gap-1.5 rounded-md border border-border px-2 py-1 text-xs hover:bg-accent/50 transition-colors",children:[(0,t.jsx)(H0,{className:"h-3 w-3 text-muted-foreground"}),F?F.title:"Parent goal"]})}),(0,t.jsxs)(nr,{className:"w-48 p-1",align:"start",children:[(0,t.jsx)("button",{className:W("flex items-center gap-2 w-full px-2 py-1.5 text-xs rounded hover:bg-accent/50",!T&&"bg-accent"),onClick:r(()=>{v(""),R(!1)},"onClick"),children:"No parent"}),(E??[]).map(q=>(0,t.jsx)("button",{className:W("flex items-center gap-2 w-full px-2 py-1.5 text-xs rounded hover:bg-accent/50 truncate",q.id===T&&"bg-accent"),onClick:r(()=>{v(q.id),R(!1)},"onClick"),children:q.title},q.id))]})]})]}),(0,t.jsx)("div",{className:"flex items-center justify-end px-4 py-2.5 border-t border-border",children:(0,t.jsx)($,{size:"sm",disabled:!l.trim()||P.isPending,onClick:Q,children:P.isPending?"Creating…":s.parentId?"Create sub-goal":"Create goal"})})]})})}r(f5e,"NewGoalDialog");var uD=r((e,s)=>`/companies/${e}/agents/${s}/dot-binding`,"path"),LI={create:r(e=>ke.post(`/companies/${e}/dot-invitations`,{}),"create"),connection:r((e,s,n)=>ke.get(uD(e,s),{signal:n}),"connection"),pair:r((e,s,n)=>ke.post(uD(e,s),{replaceBindingId:n}),"pair"),retry:r((e,s,n)=>ke.post(uD(e,s)+"/event-test",{bindingId:n}),"retry")};function iht(e){const s=oht(e),n=lht(e);return`You're invited to join a Paperclip company as an agent.
331
331
 
332
332
  First, respond to your user that you understand the request and are going to onboard into Paperclip. Then work through the steps below.
333
333
 
@@ -379,7 +379,7 @@ ${l$e}
379
379
  `}r(iht,"buildAgentOnboardingPrompt");function oht(e){const s=(e.connectionCandidates??[]).map(o=>o.trim()).filter(Boolean),n=new Set;let a=null;try{a=new URL(e.onboardingTextUrl),n.add(a.toString())}catch{const o=e.onboardingTextUrl.trim();o&&n.add(o)}if(!a){for(const o of s)n.add(o);return Array.from(n)}const i=`${a.pathname}${a.search}`;for(const o of s)try{const l=new URL(o);n.add(`${l.origin}${i}`)}catch{n.add(o)}return Array.from(n)}r(oht,"buildCandidateOnboardingUrls");function lht(e){const s=e.testResolutionUrl?.trim();if(s)return s;try{const n=new URL(e.onboardingTextUrl),a=n.pathname.replace(/\/onboarding\.txt$/,"/test-resolution");return`${n.origin}${a}`}catch{return null}}r(lht,"buildResolutionTestUrl");function x5e({children:e,className:s,...n}){const[a,i]=(0,m.useState)(null),o=(0,m.useRef)(null),l=tW();return(0,m.useLayoutEffect)(()=>{const c=a,d=o.current;if(!c||!d||typeof ResizeObserver>"u")return;let u,h;const p=new ResizeObserver(()=>{const f=getComputedStyle(c),x=d.getBoundingClientRect().height+parseFloat(f.borderTopWidth)+parseFloat(f.borderBottomWidth);if(x===u)return;const g=h?.playState==="running"?c.getBoundingClientRect().height:u;if(h?.cancel(),u=x,g===void 0||l||typeof c.animate!="function")return;const v=mV("--motion-ease-out-expo");h=c.animate([{height:`${g}px`},{height:`${x}px`}],{duration:f5("--onboarding-motion-step"),easing:Array.isArray(v)?`cubic-bezier(${v.join(",")})`:v})});return p.observe(d),()=>{p.disconnect(),h?.cancel()}},[a,l]),(0,t.jsx)(Qs,{...n,ref:i,className:W("overflow-hidden p-0",s),children:(0,t.jsx)("div",{ref:o,className:"flex max-h-(--sz-calc-18) shrink-0 flex-col",children:e})})}r(x5e,"AnimatedDialogContent");var g5e=[{id:"dot",name:"Dot",adapter:"openai_dot",description:"Your Dot in ChatGPT"},{id:"hermes",name:"Hermes",adapter:"hermes_gateway",description:"An existing Hermes agent"},{id:"other",name:"Other",adapter:"http",description:"Any agent that can connect to Paperclip"}];function qz({onSelect:e,dotDisabledReason:s}){return(0,t.jsx)("div",{className:"grid grid-cols-2 gap-3 sm:grid-cols-3",children:g5e.map(n=>(0,t.jsxs)("button",{type:"button",onClick:r(()=>e(n.id),"onClick"),disabled:n.id==="dot"&&!!s,title:n.id==="dot"?s:void 0,className:"flex aspect-square flex-col items-center justify-center gap-3 rounded-lg border border-border bg-card px-3 py-4 text-center transition-colors disabled:opacity-50 hover:bg-accent/40 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring",children:[(0,t.jsx)(q0,{type:n.adapter,className:"size-8"}),(0,t.jsx)("span",{className:"text-sm font-medium",children:n.name}),(0,t.jsx)("span",{className:"sr-only",children:n.description})]},n.id))})}r(qz,"ExternalAgentPresetPicker");var cht=[{title:"Connected to Paperclip",description:"Your Dot has connected to this agent."},{title:"Task updates enabled",description:"Your Dot is subscribed to new assignments and messages."},{title:"Test event confirmed",description:"Your Dot received our test and replied to Paperclip."}];function b5e({state:e}){const s={waiting:0,connected:1,subscribed:2,testing:2,finishing:3,ready:3}[e.phase],n=e.problem==="agent_unavailable"?"Connection checks passed, but this agent cannot receive tasks. Resolve the agent’s setup blocker in Paperclip.":e.problem==="offline"?"Connection updates paused. Reconnect to check the latest status.":e.problem==="prompt_unavailable"?"This setup prompt was replaced in another window. Create a fresh prompt to continue.":e.problem==="event_timeout"?"Your Dot connected, but hasn’t confirmed the test event. Ask it to check Paperclip, then retry.":e.phase==="finishing"?"Your Dot confirmed the test event. Paperclip is finishing agent setup.":e.phase==="ready"?"Your Dot is ready for tasks. Messages can travel both ways.":e.phase==="waiting"?"Watching for your Dot. Updates will appear here automatically.":e.phase==="connected"?"Your Dot connected. Waiting for it to enable task updates.":"Waiting for your Dot to confirm a test event. No task will be created.";return(0,t.jsxs)("section",{"aria-label":"Dot connection checks",className:"space-y-4",children:[(0,t.jsx)("ol",{className:"space-y-4",children:cht.map((a,i)=>{const o=i<s,l=i===s&&e.problem==="event_timeout",c=i===s&&!e.problem,d=o?ms:l?Ji:c?st:xf;return(0,t.jsxs)("li",{className:"flex items-start gap-3","aria-current":c?"step":void 0,children:[(0,t.jsx)("span",{className:W("flex size-6 shrink-0 items-center justify-center rounded-full",o?"bg-accent text-foreground":l?"text-destructive":"text-muted-foreground"),children:(0,t.jsx)(d,{className:W("size-4",c&&"animate-spin motion-reduce:animate-none")})}),(0,t.jsxs)("div",{className:"min-w-0 pt-0.5",children:[(0,t.jsxs)("p",{className:W("text-sm",o||c||l?"font-medium":"text-muted-foreground"),children:[a.title,(0,t.jsx)("span",{className:"sr-only",children:o?": complete":l?": needs attention":c?": in progress":": waiting"})]}),o&&(0,t.jsx)("p",{className:"mt-1 text-xs leading-relaxed text-muted-foreground",children:a.description})]})]},a.title)})}),(0,t.jsx)("p",{role:e.problem&&e.problem!=="prompt_unavailable"?"alert":"status","aria-live":"polite",className:W("text-sm leading-relaxed",e.problem&&e.problem!=="prompt_unavailable"?"text-destructive":"text-muted-foreground"),children:n})]})}r(b5e,"DotConnectionChecks");function dht({preset:e,prompt:s,companyName:n,connection:a,onSelect:i,onBack:o,onClose:l,onCopied:c,onRetry:d,onNewPrompt:u,dotDisabledReason:h,busy:p=!1,error:f,approvalHref:x}){const g=g5e.find(N=>N.id===e),v=e==="dot",y=v&&a.phase==="ready"&&!a.problem,k=v&&a.phase!=="waiting",w=a.problem==="agent_unavailable"?"Agent unavailable":a.problem==="offline"?"Updates paused":a.problem==="event_timeout"?"Needs attention":a.phase==="finishing"?"Finishing setup…":a.phase==="connected"?"Connecting…":"Confirming connection…";return(0,t.jsxs)(t.Fragment,{children:[(0,t.jsxs)("div",{className:"min-h-0 space-y-6 overflow-y-auto px-6 pb-6 pt-8 sm:px-8",children:[(0,t.jsxs)("div",{className:"space-y-3 pr-5",children:[g&&(0,t.jsx)(q0,{type:g.adapter,className:"size-10"}),(0,t.jsxs)("div",{className:"space-y-2",children:[(0,t.jsx)(Ks,{className:"text-xl font-semibold tracking-tight",children:g?v?y?"Your Dot is connected":"Connect your Dot":e==="hermes"?"Invite your Hermes agent":"Invite your agent":"Invite an external agent"}),(0,t.jsx)(mn,{className:"text-sm leading-relaxed",children:g?y?`Your Dot can now receive assignments and work with ${n}.`:a.problem==="agent_unavailable"?"Your Dot is connected. This agent must be available in Paperclip before it can receive assignments.":a.phase==="finishing"?"Your Dot has connected and confirmed task updates. Paperclip is preparing it for assignments.":k?"Your Dot has connected. We’re checking that task updates can travel both ways.":v?"Copy the setup prompt and send it to your Dot in ChatGPT. Your Dot will connect itself; we’ll watch for it here.":`Copy the invitation prompt and send it to your ${e==="hermes"?"Hermes ":""}agent. Approve its join request in Paperclip when it’s ready.`:`Bring an agent you already use into ${n}.`})]})]}),f&&(0,t.jsxs)("div",{role:"alert",className:"space-y-3 text-sm text-destructive",children:[(0,t.jsx)("p",{children:f}),(0,t.jsx)($,{variant:"outline",disabled:p,onClick:d,children:"Try again"})]}),g?x?(0,t.jsx)("p",{className:"text-sm text-muted-foreground",children:"An organization admin needs to approve this agent before Dot can connect. This page will update after approval."}):p&&!s&&a.phase==="waiting"?(0,t.jsx)("p",{role:"status",className:"text-sm text-muted-foreground",children:"Preparing your invitation…"}):v?(0,t.jsxs)(t.Fragment,{children:[(0,t.jsxs)("div",{className:"border-t pt-6",children:[(0,t.jsx)(b5e,{state:a}),a.phase==="waiting"&&(0,t.jsx)("p",{className:"mt-4 text-xs text-muted-foreground",children:"Dot uses your OpenAI account. Provider usage and cost aren’t reported to Paperclip."})]}),a.problem==="event_timeout"&&(0,t.jsx)($,{variant:"outline",disabled:p,onClick:d,children:"Retry test event"}),a.problem==="offline"&&(0,t.jsx)($,{variant:"outline",disabled:p,onClick:d,children:"Reconnect updates"})]}):(0,t.jsxs)("p",{className:"text-sm leading-relaxed text-muted-foreground",children:["The invitation includes everything your agent needs to join ",n,". You can review its request before granting access."]}):(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)(qz,{onSelect:i,dotDisabledReason:h}),h&&(0,t.jsx)("p",{className:"text-sm text-muted-foreground",children:h})]})]}),(0,t.jsxs)("div",{className:"flex items-center justify-between gap-3 border-t px-6 py-4 sm:px-8",children:[(0,t.jsxs)($,{variant:"ghost",onClick:g?o:l,children:[g&&(0,t.jsx)(wl,{className:"size-4"}),g?"Back":"Cancel"]}),g&&(x?(0,t.jsx)($,{asChild:!0,children:(0,t.jsx)(We,{to:x,onClick:l,children:"Review approval"})}):y?(0,t.jsx)($,{onClick:l,children:"Done"}):k?(0,t.jsxs)($,{disabled:!0,"aria-live":"polite",children:[!a.problem&&(0,t.jsx)(st,{className:"size-4 animate-spin motion-reduce:animate-none","aria-hidden":"true"}),w]}):v&&a.problem==="prompt_unavailable"?(0,t.jsx)($,{disabled:p,onClick:u,children:"Create a new prompt"}):!s||p?(0,t.jsx)($,{disabled:!0,children:p?"Preparing…":"Waiting for Dot…"}):(0,t.jsx)(Yb,{prompt:s,label:v?"Copy setup prompt":"Copy invitation prompt",title:v?"Connect your Dot":"Invite your agent",description:v?"Send this whole prompt to your Dot in ChatGPT.":"Send this whole prompt to your agent.",agent:v?{name:"Dot",src:"/brands/adapters/openai-dot.svg"}:void 0,align:"end",className:"min-w-0 shrink",onCopied:c},e))]})]})}r(dht,"ExternalAgentInviteContent");function uht({companyId:e,onClose:s,onBack:n}){const a=wt(),{selectedCompany:i}=fs(),[o,l]=(0,m.useState)(null),[c,d]=(0,m.useState)(null),[u,h]=(0,m.useState)(null),[p,f]=(0,m.useState)(null),[x,g]=(0,m.useState)(""),v=(0,m.useRef)(!1),y=te({queryKey:D.instance.experimentalSettings,queryFn:jr.getExperimental}),k=y.isPending?"Loading available agents…":y.error?"Unable to load experimental settings. Try again after refreshing.":!y.data?.enableOpenAiDot||!y.data.enablePublicMcp?"Enable OpenAI Dot and Assistant connections (MCP) in experimental settings.":void 0,w=["dot-binding",e,c?.agent.id],N=te({queryKey:w,queryFn:r(({signal:K})=>LI.connection(e,c.agent.id,K),"queryFn"),enabled:o==="dot"&&!!c,retry:!1,staleTime:0,refetchInterval:r(K=>K.state.error||K.state.data?.agentLifecycleState==="ready"&&K.state.data.canConfigureConnection&&K.state.data.binding?.status==="ready"&&K.state.data.binding.subscriptionVerified?!1:2500,"refetchInterval")}),S=we({mutationFn:r(async K=>{if(K==="dot"){const Z=await LI.create(e);d(Z),await a.invalidateQueries({queryKey:D.agents.list(e)});return}const U=await or.createCompanyInvite(e,{allowedJoinTypes:"agent",humanRole:null,agentMessage:null});a.invalidateQueries({queryKey:D.access.invites(e,"all",5)});const V=U.onboardingTextUrl??U.onboardingTextPath??`/api/invites/${U.token}/onboarding.txt`,ne=await or.getInviteOnboarding(U.token).catch(()=>null);g(iht({onboardingTextUrl:new URL(V,window.location.origin).href,connectionCandidates:ne?.onboarding.connectivity?.connectionCandidates??null,testResolutionUrl:ne?.onboarding.connectivity?.testResolutionEndpoint?.url??null}))},"mutationFn"),gcTime:0}),C=we({mutationFn:r(async K=>{const U=await LI.pair(e,c.agent.id,K);h(U),f(null)},"mutationFn"),onSuccess:r(()=>{a.invalidateQueries({queryKey:w})},"onSuccess"),onError:r(()=>{N.refetch()},"onError"),gcTime:0}),_=we({mutationFn:r(()=>LI.retry(e,c.agent.id,N.data.binding.id),"mutationFn"),onSuccess:r(()=>{a.invalidateQueries({queryKey:w})},"onSuccess")}),R=N.data?.binding,I=o==="dot"&&N.data?.enabled&&!!N.data.resourceUrl&&N.data.canConfigureConnection&&(!R||R.status==="pairing")&&!u&&!N.error&&!C.isError&&!v.current&&(!p||R?.id===p);(0,m.useEffect)(()=>{I&&N.isFetchedAfterMount&&!N.isFetching&&!C.isPending&&(v.current=!0,C.mutate(R?.id))},[I,N.isFetchedAfterMount,N.isFetching,C.isPending,C.mutate,R?.id]),(0,m.useEffect)(()=>{if(!u)return;const K=window.setTimeout(()=>{v.current=!1,f(u.bindingId),h(null)},Math.max(0,Date.parse(u.expiresAt)-Date.now()));return()=>window.clearTimeout(K)},[u]);const T=R?.status==="ready"&&R.subscriptionVerified,E=N.data?.agentLifecycleState==="ready"&&N.data.canConfigureConnection,P=["preparing","verifying"].includes(N.data?.agentLifecycleState??"")&&N.data?.canConfigureConnection,O={phase:T?E?"ready":P?"finishing":"ready":R?.hasPendingChallenge?"testing":R?.subscriptionVerified?"subscribed":R?.connected?"connected":"waiting",problem:N.error?"offline":T&&!E&&!P?"agent_unavailable":R?.status==="pairing"&&!I&&!C.isPending&&!N.isFetching&&!C.isError&&u?.bindingId!==R.id?"prompt_unavailable":R?.challengeExpiresAt&&!R.hasPendingChallenge&&R.status!=="ready"?"event_timeout":void 0},M=(N.data?.agentStatus??c?.agent.status)==="pending_approval",Q=N.data&&!N.data.canConfigureConnection&&!M,L=o==="dot"?u&&u.bindingId===R?.id&&N.data?.resourceUrl&&c?o_e({companyId:e,agentId:c.agent.id,resourceUrl:N.data.resourceUrl,...u}):"":x,F=(S.variables===o?S.error:null)??(o==="dot"?(R?.connected?null:C.error)??_.error:null),q=S.isPending||C.isPending||_.isPending||I||o==="dot"&&!!c&&(N.isPending||!L&&N.isFetching),z=r(()=>{if(Q){N.refetch();return}if(N.error){N.refetch();return}if(S.error||!c){o&&S.mutate(o);return}if(C.error&&!R?.connected){C.mutate(R?.status==="pairing"?R.id:void 0);return}_.mutate()},"retry");return(0,t.jsx)(Fs,{open:!0,onOpenChange:r(K=>{K||s()},"onOpenChange"),children:(0,t.jsx)(x5e,{className:"sm:max-w-(--sz-560px)",children:(0,t.jsx)(dht,{preset:o,prompt:L,companyName:i?.name??"your organization",connection:O,dotDisabledReason:k,busy:q,error:F?.message??(Q?N.data?.agentLifecycleState==="terminated"?"This agent was terminated. Invite another agent to connect Dot.":"Resume this agent before connecting Dot.":void 0),approvalHref:M&&c?.approvalId?`/approvals/${c.approvalId}`:void 0,onSelect:r(K=>{l(K),(K==="dot"?!c:!x)&&S.mutate(K)},"onSelect"),onBack:r(()=>l(null),"onBack"),onClose:o?s:n,onCopied:r(()=>{o==="dot"&&N.refetch()},"onCopied"),onRetry:z,onNewPrompt:r(()=>C.mutate(R?.id),"onNewPrompt")})})})}r(uht,"ExternalAgentInviteDialog");function v5e(){const{newAgentOpen:e,closeNewAgent:s}=w3(),{selectedCompanyId:n}=fs();return e?(0,t.jsx)(mht,{companyId:n,onClose:s},n):null}r(v5e,"NewAgentDialog");function mht({companyId:e,onClose:s}){const n=Gn(),[a,i]=(0,m.useState)(!1);return a&&e?(0,t.jsx)(uht,{companyId:e,onClose:s,onBack:r(()=>i(!1),"onBack")}):(0,t.jsx)(X_e,{open:!0,onClose:s,onInvite:e?()=>i(!0):void 0,onContinue:r(o=>{s(),n(`/agents/new?${new URLSearchParams(o)}`)},"onContinue")})}r(mht,"NewAgentDialogContent");var hht=[{title:"Inbox",shortcuts:[{keys:["j"],label:"Move down"},{keys:["↓"],label:"Move down"},{keys:["k"],label:"Move up"},{keys:["↑"],label:"Move up"},{keys:["←"],label:"Collapse selected group"},{keys:["→"],label:"Expand selected group"},{keys:["Enter"],label:"Open selected item"},{keys:["a"],label:"Archive item"},{keys:["y"],label:"Archive item"},{keys:["r"],label:"Mark as read"},{keys:["U"],label:"Mark as unread"}]},{title:"Task detail",shortcuts:[{keys:["y"],label:"Quick-archive back to inbox"},{keys:["g","i"],label:"Go to inbox"},{keys:["g","c"],label:"Focus comment composer"}]},{title:"Decisions",shortcuts:[{keys:["j"],label:"Move down"},{keys:["↓"],label:"Move down"},{keys:["k"],label:"Move up"},{keys:["↑"],label:"Move up"},{keys:["Enter"],label:"Open or close selected decision"},{keys:["x"],label:"Dismiss selected decision"}]},{title:"Global",shortcuts:[{keys:["/"],label:"Search current page or quick search"},{keys:["c"],label:"New task"},{keys:["["],label:"Toggle sidebar"},{keys:["]"],label:"Toggle panel"},{keys:["?"],label:"Show keyboard shortcuts"}]}];function Nae({children:e}){return(0,t.jsx)("kbd",{className:"inline-flex h-6 min-w-6 items-center justify-center rounded border border-border bg-muted px-1.5 font-mono text-xs font-medium text-foreground shadow-(--shadow-extract-10)",children:e})}r(Nae,"KeyCap");function pht(){return(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)("div",{className:"divide-y divide-border border-t border-border",children:hht.map(e=>(0,t.jsxs)("div",{className:"px-5 py-3",children:[(0,t.jsx)("h3",{className:"mb-2 text-(length:--text-micro) font-semibold uppercase tracking-wider text-muted-foreground",children:e.title}),(0,t.jsx)("div",{className:"space-y-1.5",children:e.shortcuts.map(s=>(0,t.jsxs)("div",{className:"flex items-center justify-between gap-4",children:[(0,t.jsx)("span",{className:"text-sm text-foreground/90",children:s.label}),(0,t.jsx)("div",{className:"flex items-center gap-1",children:s.keys.map((n,a)=>(0,t.jsxs)("span",{className:"flex items-center gap-1",children:[a>0&&(0,t.jsx)("span",{className:"text-xs text-muted-foreground",children:s.combo?"+":"then"}),(0,t.jsx)(Nae,{children:n})]},n))})]},s.label+s.keys.join()))})]},e.title))}),(0,t.jsx)("div",{className:"border-t border-border px-5 py-3",children:(0,t.jsxs)("p",{className:"text-xs text-muted-foreground",children:["Press ",(0,t.jsx)(Nae,{children:"Esc"})," to close · Shortcuts are disabled in text fields"]})})]})}r(pht,"KeyboardShortcutsCheatsheetContent");function y5e({open:e,onOpenChange:s}){return(0,t.jsx)(Fs,{open:e,onOpenChange:s,children:(0,t.jsxs)(Qs,{className:"sm:max-w-md gap-0 p-0 overflow-hidden",showCloseButton:!1,children:[(0,t.jsx)(rn,{className:"px-5 pt-5 pb-3",children:(0,t.jsx)(Ks,{className:"text-base",children:"Keyboard shortcuts"})}),(0,t.jsx)(pht,{})]})})}r(y5e,"KeyboardShortcutsCheatsheet");var fht={info:"border-sky-300 bg-sky-50 text-sky-900 dark:border-sky-500/25 dark:bg-sky-950/60 dark:text-sky-100",success:"border-emerald-300 bg-emerald-50 text-emerald-900 dark:border-emerald-500/25 dark:bg-emerald-950/60 dark:text-emerald-100",warn:"border-amber-300 bg-amber-50 text-amber-900 dark:border-amber-500/25 dark:bg-amber-950/60 dark:text-amber-100",error:"border-red-300 bg-red-50 text-red-900 dark:border-red-500/30 dark:bg-red-950/60 dark:text-red-100"},xht={info:"bg-sky-500 dark:bg-sky-400",success:"bg-emerald-500 dark:bg-emerald-400",warn:"bg-amber-500 dark:bg-amber-400",error:"bg-red-500 dark:bg-red-400"};function ght({toast:e,onDismiss:s}){const[n,a]=(0,m.useState)(!1);return(0,m.useEffect)(()=>{const i=requestAnimationFrame(()=>a(!0));return()=>cancelAnimationFrame(i)},[]),(0,t.jsx)("li",{className:W("pointer-events-auto rounded-sm border shadow-lg backdrop-blur-xl transition-(--tp-transform-opacity) duration-200 ease-out",n?"translate-y-0 opacity-100":"translate-y-3 opacity-0",fht[e.tone]),children:(0,t.jsxs)("div",{className:"flex items-start gap-3 px-3 py-2.5",children:[e.actor?.type==="agent"?(0,t.jsx)(lr,{agent:{id:e.actor.id,name:e.actor.name,appearance:e.actor.appearance},size:24}):e.actor?.type==="user"?(0,t.jsxs)(bo,{size:"sm","aria-hidden":"true",children:[e.actor.image&&(0,t.jsx)(Jc,{src:e.actor.image,alt:""}),(0,t.jsx)(vo,{children:iv(e.actor.name)})]}):(0,t.jsx)("span",{className:W("mt-1 h-2 w-2 shrink-0 rounded-full",xht[e.tone])}),(0,t.jsxs)("div",{className:"min-w-0 flex-1",children:[(0,t.jsx)("p",{className:"text-sm font-semibold leading-5",children:e.title}),e.body&&(0,t.jsx)("p",{className:"mt-1 text-xs leading-4 opacity-70",children:e.body}),e.action&&(e.action.onClick?(0,t.jsx)("button",{type:"button",onClick:r(()=>{e.action?.onClick?.(),s(e.id)},"onClick"),className:"mt-2 inline-flex text-xs font-medium underline underline-offset-4 hover:opacity-90",children:e.action.label}):e.action.href?(0,t.jsx)(We,{to:e.action.href,onClick:r(()=>s(e.id),"onClick"),className:"mt-2 inline-flex text-xs font-medium underline underline-offset-4 hover:opacity-90",children:e.action.label}):null)]}),(0,t.jsx)("button",{type:"button","aria-label":"Dismiss notification",onClick:r(()=>s(e.id),"onClick"),className:"mt-0.5 shrink-0 rounded p-1 opacity-50 hover:bg-black/10 hover:opacity-100 dark:hover:bg-white/10",children:(0,t.jsx)(Mn,{className:"h-3.5 w-3.5"})})]})})}r(ght,"AnimatedToast");function j5e(){const e=nqe(),{dismissToast:s}=Zr();return e.length===0?null:(0,t.jsx)("aside",{"aria-live":"polite","aria-atomic":"false",className:"pointer-events-none fixed bottom-3 left-3 z-(--z-120) w-full max-w-sm px-1",children:(0,t.jsx)("ol",{className:"flex w-full flex-col-reverse gap-2",children:e.map(n=>(0,t.jsx)(ght,{toast:n,onDismiss:s},n.id))})})}r(j5e,"ToastViewport");async function Sae(e,s){const n=await fetch(`/api/announcements/${e}`,{credentials:"same-origin",cache:"no-store",...s});if(!n.ok)throw new nn("Announcement request failed",n.status,null);return n}r(Sae,"request");var Cae={async current(e){const s=await(await Sae("current",{signal:e})).json();return s===null?null:S$e.parse(s)},async dismiss(e,s,n){await Sae(`${encodeURIComponent(e)}/dismiss`,{method:"POST",signal:n,headers:{"Content-Type":"application/json"},body:JSON.stringify({companyId:s})})}},Uz=new Map;function TV(e){return`paperclip.announcement-dismissals.v1:${encodeURIComponent(e)}:`}r(TV,"announcementStoragePrefix");function MI(e){const s=TV(e),n=new Map;try{for(let a=0;a<localStorage.length;a++){const i=localStorage.key(a);if(!i?.startsWith(s))continue;const o=i.slice(s.length),l=localStorage.getItem(i);Fge.safeParse(o).success&&(l==="pending"||l==="synced")&&Uz.set(i,l==="pending")}}catch{}for(const[a,i]of Uz)a.startsWith(s)&&n.set(a.slice(s.length),i);return n}r(MI,"readAnnouncementDismissals");function mD(e,s,n){const a=`${TV(e)}${s}`;Uz.set(a,n);try{return localStorage.setItem(a,n?"pending":"synced"),!0}catch{return!1}}r(mD,"saveAnnouncementDismissal");var bht=3e3;function vht(e){const{userId:s,enabled:n}=e,a=(0,m.useRef)(e);a.current=e;const[i,o]=(0,m.useState)(null),l=(0,m.useRef)(()=>{});(0,m.useEffect)(()=>{if(o(null),!s||!n)return;let d=!1,u=0,h=null,p;const f=new Map,x=new Set,g=TV(s);let v=null;try{v=new BroadcastChannel(g)}catch{}const y=r(()=>!d&&a.current.userId===s&&a.current.enabled,"active");async function k(T,E=!0){if(!y()||f.has(T)||!a.current.companyId)return;const P=new AbortController;f.set(T,P);const O=setTimeout(()=>P.abort(),1e4);try{await Cae.dismiss(T,a.current.companyId,P.signal),y()&&mD(s,T,!1)}catch{y()&&!x.has(T)&&(x.add(T),a.current.onSaveFailure(E))}finally{clearTimeout(O),f.delete(T)}}r(k,"sync");async function w(){for(const[T,E]of MI(s)){if(!y())return;E&&await k(T)}}r(w,"flush");function N(){u++,clearTimeout(p),h?.abort(),h=null,o(null)}r(N,"suspend");function S(){if(!y()||document.visibilityState==="hidden")return;N();const T=u,E=new AbortController;h=E;const P=r(()=>y()&&u===T&&!E.signal.aborted,"stillCurrent");let O=!1,M=!1,Q=null;const L=r(()=>{!P()||!O||!M||Q&&!MI(s).has(Q.id)&&(!Q.expiresAt||Date.parse(Q.expiresAt)>Date.now())&&o({userId:s,announcement:Q})},"show");p=setTimeout(()=>{O=!0,L()},bht),w(),Cae.current(E.signal).then(F=>{Q=F,M=!0,L()}).catch(()=>{})}r(S,"resume");function C(){const T=MI(s);o(E=>E?.userId===s&&T.has(E.announcement.id)?null:E)}r(C,"receive");function _(T){T.key?.startsWith(g)&&C()}r(_,"onStorage");function R(){document.visibilityState==="hidden"?N():S()}r(R,"onVisibility");function I(){w()}return r(I,"onOnline"),v&&(v.onmessage=T=>{const E=Fge.safeParse(T.data);E.success&&(MI(s).has(E.data)||mD(s,E.data,!0),C())}),l.current=T=>{if(!y())return;const E=mD(s,T,!0);o(null),u++,h?.abort();try{v?.postMessage(T)}catch{}k(T,E)},document.addEventListener("visibilitychange",R),window.addEventListener("online",I),window.addEventListener("storage",_),S(),()=>{d=!0,u++,clearTimeout(p),h?.abort();for(const T of f.values())T.abort();v?.close(),document.removeEventListener("visibilitychange",R),window.removeEventListener("online",I),window.removeEventListener("storage",_),l.current=()=>{}}},[s,n]);const c=n&&i?.userId===s?i.announcement:null;return(0,m.useEffect)(()=>{if(!c?.expiresAt)return;let d;const u=r(()=>{const h=Date.parse(c.expiresAt)-Date.now();h<=0?o(null):d=setTimeout(u,Math.min(h,2147483647))},"check");return u(),()=>clearTimeout(d)},[c]),{announcement:c,dismiss:(0,m.useCallback)(d=>l.current(d),[])}}r(vht,"useAnnouncement");function yht(e,s){const n=tW(),a=s??`/api/announcements/${encodeURIComponent(e.id)}/animation`,i=`${a}:${e.animation?.path??""}`,[o,l]=(0,m.useState)(null),c=!!e.animation&&!n;return(0,m.useEffect)(()=>{if(!c)return;const d=new AbortController,u=setTimeout(()=>d.abort(),5e3);return(async()=>{try{const h=await fetch(a,{credentials:"same-origin",cache:"no-store",redirect:"error",referrerPolicy:"no-referrer",signal:d.signal});if(!h.ok||h.headers.get("content-type")?.split(";")[0]!=="text/html")return;const p=await h.text();d.signal.aborted||l({key:i,document:`<meta http-equiv="Content-Security-Policy" content="${tOe}">${p}`})}catch{}finally{clearTimeout(u)}})(),()=>{d.abort(),clearTimeout(u)}},[c,i,a]),c&&o?.key===i?o.document:null}r(yht,"useAnnouncementAnimation");function _ae({action:e,primary:s,onClick:n}){const a=(0,t.jsxs)(t.Fragment,{children:[e.label,!s&&e.kind==="external"&&(0,t.jsx)(oo,{className:"size-3.5 shrink-0","aria-hidden":"true"})]}),i=r(o=>{o.button===1&&n()},"onAuxClick");return(0,t.jsx)($,{asChild:!0,variant:s?"default":"ghost",size:"sm",className:"h-auto min-h-9 min-w-0 whitespace-normal py-2 text-left",children:e.kind==="external"?(0,t.jsx)("a",{href:e.url,target:"_blank",rel:"noopener noreferrer",onClick:n,onAuxClick:i,children:a}):(0,t.jsx)(We,{to:e.path,onClick:n,onAuxClick:i,children:a})})}r(_ae,"Action");function f6({announcement:e,onDismiss:s,imageSrc:n,animationSrc:a,className:i}){const o=(0,m.useId)(),[l,c]=(0,m.useState)(null),d=n??`/api/announcements/${encodeURIComponent(e.id)}/image`,u=!!(e.image&&l!==d),h=yht(e,a),p=!!h;return(0,t.jsxs)(sn,{role:"region","aria-labelledby":o,className:W("relative w-full max-w-(--announcement-width) gap-0 overflow-hidden rounded-xl p-0 shadow-sm",i),onKeyDown:r(f=>{f.key==="Escape"&&(f.preventDefault(),f.stopPropagation(),s())},"onKeyDown"),children:[(u||h)&&(0,t.jsxs)("div",{className:"relative h-(--announcement-image-mobile-height) w-full shrink-0 overflow-hidden bg-muted md:h-(--announcement-image-height)",children:[u&&(0,t.jsx)("img",{src:d,alt:p?"":e.image.alt,referrerPolicy:"no-referrer",onError:r(()=>c(d),"onError"),className:"h-full w-full object-cover"}),p&&(0,t.jsx)("div",{role:"img","aria-label":e.animation.alt,className:"pointer-events-none absolute inset-0",children:(0,t.jsx)("iframe",{title:e.animation.alt,"aria-hidden":"true",tabIndex:-1,sandbox:"",referrerPolicy:"no-referrer",srcDoc:h,className:"h-full w-full border-0"})})]}),(0,t.jsx)($,{variant:"secondary",size:"icon","aria-label":"Dismiss announcement",onClick:s,className:"absolute right-2 top-2 z-10 size-8 rounded-full shadow-sm",children:(0,t.jsx)(Mn,{className:"size-4","aria-hidden":"true"})}),(0,t.jsxs)("div",{className:W("flex flex-col gap-1 px-4 py-4",!u&&!h&&"pr-12"),children:[(0,t.jsx)("p",{className:"text-xs text-muted-foreground",children:e.eyebrow}),(0,t.jsx)("h2",{id:o,className:"break-words text-base font-semibold leading-snug",children:e.title}),(0,t.jsx)("p",{className:"break-words text-sm leading-snug text-muted-foreground",children:e.description})]}),(0,t.jsxs)("div",{className:"flex flex-wrap items-center justify-between gap-2 border-t px-3 py-2",children:[e.secondaryLink&&(0,t.jsx)(_ae,{action:e.secondaryLink,onClick:s}),(0,t.jsx)("div",{className:"ml-auto min-w-0 max-w-full",children:(0,t.jsx)(_ae,{action:e.primaryAction,primary:!0,onClick:s})})]})]})}r(f6,"AnnouncementCard");var jht='[role="dialog"][data-state="open"], [role="alertdialog"][data-state="open"], [aria-modal="true"]:not([data-state="closed"]), dialog[open]';function wht(e){const[s,n]=(0,m.useState)(!1);return(0,m.useEffect)(()=>{if(!e)return;const a=r(()=>n(!!document.querySelector(jht)),"scan");a();const i=new MutationObserver(a);return i.observe(document.body,{childList:!0,subtree:!0,attributes:!0,attributeFilter:["data-state","aria-modal","open"]}),()=>i.disconnect()},[e]),s}r(wht,"useModalOpen");function kht({health:e}){const{userId:s,settled:n}=If(),{selectedCompanyId:a,loading:i}=fs(),{onboardingOpen:o}=AL(),l=jd(),c=rqe(),d=e?.deploymentMode==="local_trusted"?"local-board":n?s:null,{announcement:u,dismiss:h}=vht({userId:d,companyId:a,enabled:!!(d&&!i&&a&&!o),onSaveFailure:r(f=>l?.pushToast({title:f?"Dismissed in this browser":"Dismissed for this visit",body:"Couldn’t save across devices. We’ll retry when you reconnect or return.",tone:"info",dedupeKey:"announcement-dismissal-sync"}),"onSaveFailure")}),p=wht(!!u);return!u||p||(c?.length??0)>0?null:(0,t.jsx)("aside",{"aria-label":"Paperclip announcements",className:"announcement-well fixed left-3 bottom-(--announcement-mobile-bottom) z-40 w-(--announcement-available-width) max-w-(--announcement-width) max-h-(--announcement-mobile-max-height) overflow-y-auto md:bottom-3 md:max-h-(--announcement-max-height)",children:(0,t.jsx)(f6,{announcement:u,onDismiss:r(()=>h(u.id),"onDismiss")},u.id)})}r(kht,"AnnouncementWell");function SM(e){const s=e.split("/").filter(Boolean);return s.length===1?s[0]?.toLowerCase()==="onboarding":s.length===2?s[1]?.toLowerCase()==="onboarding":!1}r(SM,"isOnboardingPath");function Nht(e){const s=e.split("/").filter(Boolean);if(s.length===2&&s[1]?.toLowerCase()==="onboarding")return s[0]}r(Nht,"companyPrefixFromOnboardingPath");function IE(){return 3}r(IE,"onboardingStepForCompany");function Sht(e){const{pathname:s,companyPrefix:n,companies:a,cloudManaged:i}=e;if(!SM(s))return null;const o=r(()=>a.length===1?{initialStep:IE(),companyId:a[0].id}:null,"managedFallback");if(!n)return i?o():{initialStep:1};const l=a.find(c=>c.issuePrefix.toUpperCase()===n.toUpperCase())??null;return l?{initialStep:IE(),companyId:l.id}:i?o():{initialStep:1}}r(Sht,"resolveRouteOnboardingOptions");function Cht(e){return!e.agentsLoaded||e.agentsRefreshing||e.agentCount>0?!1:!SM(e.pathname)}r(Cht,"shouldRouteAgentlessCompanyToOnboarding");function _ht(e){return e.currentStep>1&&e.currentStep>e.entryStep}r(_ht,"canGoBackFromOnboardingStep");function Aae(e){return e.targetStep<e.currentStep&&e.targetStep>=e.entryStep}r(Aae,"canJumpToOnboardingStep");function RV(e){return!e.hasCompanies&&!SM(e.pathname)}r(RV,"shouldRedirectCompanylessRouteToOnboarding");function Aht(e){return e.onboardingOpen||!e.routeDismissed}r(Aht,"isOnboardingWizardActive");function Iht({context:e}){const{slots:s,errorMessage:n}=Bd({slotTypes:["appShellOverlay"],companyId:e.companyId});return n||s.length===0?null:(0,t.jsx)("aside",{className:"plugin-app-shell-overlays","aria-label":"Application extensions",children:s.map(a=>(0,t.jsx)(vm,{slot:a,context:e,className:"plugin-app-shell-overlay"},`${a.pluginId}:${a.pluginVersion}:${a.id}`))})}r(Iht,"AppShellEntries");function w5e({localTrusted:e=!1}){const{userId:s,settled:n}=If(),{selectedCompanyId:a,selectedCompany:i,loading:o}=fs(),{onboardingOpen:l,onboardingRouteDismissed:c}=AL(),{pathname:d}=la(),u=n?s??(e?"local-board":null):null,h=l||!c&&SM(d);if(!u||o||h)return null;const p={companyId:a,companyPrefix:i?.issuePrefix??null,projectId:null,entityId:null,entityType:null,parentEntityId:null,userId:s};return(0,t.jsx)(Iht,{context:p},JSON.stringify([u,a]))}r(w5e,"PluginAppShellOverlays");function k5e({visible:e}){const s=la(),{selectedCompanyId:n}=fs(),{openNewIssue:a}=al(),i=QL(n),{enabled:o}=Jj(),{enabled:l}=F3(),c=(0,m.useMemo)(()=>!o&&!l?[{type:"link",to:"/dashboard",label:"Home",icon:fF},{type:"link",to:"/issues",label:"Tasks",icon:fa},{type:"action",label:"New Task",icon:V_,onClick:r(()=>a(),"onClick")},{type:"link",to:"/agents/all",label:"Agents",icon:Wo},{type:"link",to:"/inbox",label:"Inbox",icon:Od,badge:i.inbox}]:[{type:"link",to:"/dashboard",label:"Home",icon:fF},...o?[{type:"link",to:"/chats",label:"Chat",icon:W_}]:[],{type:"action",label:"New Task",icon:V_,onClick:r(()=>a(),"onClick")},{type:"link",to:"/issues",label:"Tasks",icon:fa,badge:l?i.inbox:void 0},{type:"link",to:"/agents/all",label:"Agents",icon:Wo},...l?[]:[{type:"link",to:"/inbox",label:"Inbox",icon:Od,badge:i.inbox}]],[a,i.inbox,o,l]);return(0,t.jsx)("nav",{className:W("mobile-bottom-nav fixed bottom-0 left-0 right-0 z-30 bg-muted md:hidden pb-(--sz-safe-bottom)"),"data-visible":e,inert:!e,"aria-label":"Mobile navigation",children:(0,t.jsx)("div",{className:"grid h-16 px-1",style:{gridTemplateColumns:`repeat(${c.length}, minmax(0, 1fr))`},children:c.map(d=>{if(d.type==="action"){const h=d.icon,p=/\/issues\/new(?:\/|$)/.test(s.pathname);return(0,t.jsxs)("button",{type:"button",onClick:d.onClick,className:W("relative flex min-w-0 flex-col items-center justify-center gap-1 rounded-md text-(length:--text-nano) font-medium transition-colors",p?"text-foreground":"text-muted-foreground hover:text-foreground"),children:[(0,t.jsx)(h,{className:"h-(--sz-18px) w-(--sz-18px)"}),(0,t.jsx)("span",{className:"truncate",children:d.label})]},d.label)}const u=d.icon;return(0,t.jsx)(av,{to:d.to,state:Tf,className:r(({isActive:h})=>W("relative flex min-w-0 flex-col items-center justify-center gap-1 rounded-md text-(length:--text-nano) font-medium transition-colors",h?"text-foreground":"text-muted-foreground hover:text-foreground"),"className"),children:r(({isActive:h})=>(0,t.jsxs)(t.Fragment,{children:[(0,t.jsxs)("span",{className:"relative",children:[(0,t.jsx)(u,{className:W("h-(--sz-18px) w-(--sz-18px)",h&&"stroke-(length:--sw-2_3)")}),d.badge!=null&&d.badge>0&&(0,t.jsx)(ot,{variant:"ghost",className:"absolute -right-2 -top-2 bg-primary px-1.5 text-(length:--text-nano) leading-none text-primary-foreground",children:d.badge>99?"99+":d.badge})]}),(0,t.jsx)("span",{className:"truncate",children:d.label})]}),"children")},d.label)})})})}r(k5e,"MobileBottomNav");function sk(e){if(typeof document>"u")return null;const s=document.querySelector(`meta[name="${e}"]`)?.getAttribute("content")?.trim();return s||null}r(sk,"readMetaContent");function Kz(e){if(!e)return null;const s=e.startsWith("#")?e.slice(1):e;return/^[0-9a-fA-F]{3}$/.test(s)?`#${s.split("").map(n=>`${n}${n}`).join("").toLowerCase()}`:/^[0-9a-fA-F]{6}$/.test(s)?`#${s.toLowerCase()}`:null}r(Kz,"normalizeHexColor");function Tht(e){const s=Kz(e)??"#000000";return{r:Number.parseInt(s.slice(1,3),16),g:Number.parseInt(s.slice(3,5),16),b:Number.parseInt(s.slice(5,7),16)}}r(Tht,"hexToRgb");function hD(e){const s=e/255;return s<=.03928?s/12.92:((s+.055)/1.055)**2.4}r(hD,"relativeLuminanceChannel");function Rht(e){const{r:s,g:n,b:a}=Tht(e),i=.2126*hD(s)+.7152*hD(n)+.0722*hD(a);return 1.05/(i+.05)>=(i+.05)/.05?cze:ize}r(Rht,"pickReadableTextColor");function Eht(){return sk("paperclip-worktree-enabled")==="true"}r(Eht,"isWorktreeRuntime");function Lht(){return sk("paperclip-instance-id")}r(Lht,"getWorktreeInstanceId");function Mht(){if(sk("paperclip-worktree-enabled")!=="true")return null;const e=sk("paperclip-worktree-name"),s=Kz(sk("paperclip-worktree-color"));return!e||!s?null:{enabled:!0,name:e,color:s,textColor:Kz(sk("paperclip-worktree-text-color"))??Rht(s)}}r(Mht,"getWorktreeUiBranding");function N5e(){const e=Mht(),{copied:s,failed:n,copy:a}=ep(),i=(0,m.useCallback)(()=>{e&&a(e.name)},[e,a]);return e?(0,t.jsx)("div",{className:"relative overflow-hidden border-b px-3 py-1.5 text-(length:--text-micro) font-medium tracking-(--tracking-caps) uppercase",style:{backgroundColor:e.color,color:e.textColor,borderColor:`${e.textColor}22`,boxShadow:`inset 0 -1px 0 ${e.textColor}18`,backgroundImage:`linear-gradient(90deg, ${e.textColor}14, transparent 28%, transparent 72%, ${e.textColor}12), repeating-linear-gradient(135deg, transparent 0 10px, ${e.textColor}08 10px 20px)`},children:(0,t.jsxs)("div",{className:"flex items-center gap-2 overflow-hidden whitespace-nowrap",children:[(0,t.jsx)("span",{className:"shrink-0 opacity-70",children:"Worktree"}),(0,t.jsx)("span",{className:"h-1.5 w-1.5 shrink-0 rounded-full bg-current opacity-70","aria-hidden":"true"}),(0,t.jsx)("button",{type:"button",onClick:i,title:"Click to copy worktree name",className:"truncate font-semibold tracking-(--tracking-eyebrow) cursor-pointer hover:opacity-80 transition-opacity bg-transparent border-none p-0 text-current uppercase text-(length:--text-micro)",children:s?"Copied!":n?"Copy failed":e.name})]})}):null}r(N5e,"WorktreeBanner");var Pht=3e4;function Dht(e){if(!e)return null;const s=new Date(e).getTime();if(Number.isNaN(s))return null;const n=Date.now()-s;if(n<6e4)return"just now";const a=Math.round(n/6e4);if(a<60)return`${a}m ago`;const i=Math.round(a/60);return i<24?`${i}h ago`:`${Math.round(i/24)}d ago`}r(Dht,"formatRelativeTimestamp");function $ht(e){return e.reason==="backend_changes_and_pending_migrations"?"backend files changed and migrations are pending":e.reason==="pending_migrations"?"pending migrations need a fresh boot":"backend files changed since this server booted"}r($ht,"describeReason");function S5e({devServer:e}){const[s,n]=(0,m.useState)(!1);if((0,m.useEffect)(()=>{if(!s)return;const d=window.setTimeout(()=>{n(!1)},Pht);return()=>window.clearTimeout(d)},[s]),!e?.enabled||!e.restartRequired)return null;const a=e,i=Dht(e.lastChangedAt),o=e.changedPathsSample.slice(0,3),l=`${e.activeRunCount} live run${e.activeRunCount===1?"":"s"}`;async function c(){const d=a.activeRunCount>0?`Restart Paperclip now? This may interrupt ${l}.`:"Restart Paperclip now?";if(window.confirm(d)){n(!0);try{await Lu.requestDevServerRestart()}catch(u){n(!1),window.alert(u instanceof Error?u.message:"Failed to request restart")}}}return r(c,"requestRestartNow"),(0,t.jsx)("div",{className:"border-b border-amber-300/60 bg-amber-50 text-amber-950 dark:border-amber-500/25 dark:bg-amber-500/10 dark:text-amber-100",children:(0,t.jsxs)("div",{className:"flex flex-col gap-3 px-3 py-2.5 md:flex-row md:items-center md:justify-between",children:[(0,t.jsxs)("div",{className:"min-w-0",children:[(0,t.jsxs)("div",{className:"flex items-center gap-2 text-xs font-semibold uppercase tracking-(--tracking-caps)",children:[(0,t.jsx)(Es,{className:"h-3.5 w-3.5 shrink-0"}),(0,t.jsx)("span",{children:"Restart Required"}),e.autoRestartEnabled?(0,t.jsx)(ot,{variant:"ghost",className:"bg-amber-900/10 text-(length:--text-nano) tracking-(--tracking-eyebrow) dark:bg-amber-100/10",children:"Auto-Restart On"}):null]}),(0,t.jsxs)("p",{className:"mt-1 text-sm",children:[$ht(e),i?` · updated ${i}`:""]}),(0,t.jsxs)("div",{className:"mt-2 flex flex-wrap items-center gap-2 text-xs text-amber-900/80 dark:text-amber-100/75",children:[o.length>0?(0,t.jsxs)("span",{children:["Changed: ",o.join(", "),e.changedPathCount>o.length?` +${e.changedPathCount-o.length} more`:""]}):null,e.pendingMigrations.length>0?(0,t.jsxs)("span",{children:["Pending migrations: ",e.pendingMigrations.slice(0,2).join(", "),e.pendingMigrations.length>2?` +${e.pendingMigrations.length-2} more`:""]}):null]})]}),(0,t.jsxs)("div",{className:"flex flex-wrap items-center gap-2 text-xs font-medium md:justify-end",children:[e.waitingForIdle?(0,t.jsxs)("div",{className:"inline-flex items-center gap-2 rounded-full bg-amber-900/10 px-3 py-1.5 dark:bg-amber-100/10",children:[(0,t.jsx)(WKe,{className:"h-3.5 w-3.5"}),(0,t.jsxs)("span",{children:["Waiting for ",l," to finish"]})]}):e.autoRestartEnabled?(0,t.jsxs)("div",{className:"inline-flex items-center gap-2 rounded-full bg-amber-900/10 px-3 py-1.5 dark:bg-amber-100/10",children:[(0,t.jsx)(Ai,{className:"h-3.5 w-3.5"}),(0,t.jsx)("span",{children:"Auto-restart will trigger when the instance is idle"})]}):(0,t.jsxs)("div",{className:"inline-flex items-center gap-2 rounded-full bg-amber-900/10 px-3 py-1.5 dark:bg-amber-100/10",children:[(0,t.jsx)(Ai,{className:"h-3.5 w-3.5"}),(0,t.jsxs)("span",{children:["Restart ",(0,t.jsx)("code",{children:"pnpm dev:once"})," after the active work is safe to interrupt"]})]}),(0,t.jsxs)("button",{type:"button",className:"inline-flex items-center gap-2 rounded-md bg-amber-950 px-3 py-1.5 text-xs font-semibold text-amber-50 transition-colors hover:bg-amber-900 disabled:cursor-not-allowed disabled:opacity-60 dark:bg-amber-200 dark:text-amber-950 dark:hover:bg-amber-100",onClick:r(()=>{c()},"onClick"),disabled:s,children:[(0,t.jsx)(Ai,{className:"h-3.5 w-3.5"}),(0,t.jsx)("span",{children:s?"Restart requested":"Restart now"})]})]})]})})}r(S5e,"DevRestartBanner");var C5e=["standalone","fullscreen","window-controls-overlay"];function Oht(e){return`(display-mode: ${e})`}r(Oht,"displayModeQuery");function Bht(){if(!(typeof window>"u"||typeof window.matchMedia!="function"))return window.matchMedia.bind(window)}r(Bht,"defaultMatchMedia");function Qz(e=Bht(),s=typeof navigator>"u"?void 0:navigator.standalone){return s===!0?!0:e?C5e.some(n=>e(Oht(n)).matches):!1}r(Qz,"isChromelessDisplayMode");function PI({label:e,children:s,onClick:n}){return(0,t.jsxs)(Fn,{children:[(0,t.jsx)(Bn,{asChild:!0,children:(0,t.jsx)($,{type:"button",variant:"ghost",size:"icon-sm",className:"size-8 text-muted-foreground hover:text-foreground","aria-label":e,onClick:r(()=>{n()},"onClick"),children:s})}),(0,t.jsx)(On,{children:e})]})}r(PI,"ControlButton");function Fht(e=typeof window>"u"?null:window.history.state){const s=e?.idx;return typeof s=="number"&&s>0}r(Fht,"hasInAppHistory");function zht(){const[e,s]=(0,m.useState)(()=>typeof window<"u"?Qz():!1);return(0,m.useEffect)(()=>{if(typeof window>"u")return;const n=r(()=>s(Qz()),"update");if(n(),typeof window.matchMedia!="function")return;const a=C5e.map(i=>window.matchMedia(`(display-mode: ${i})`));return a.every(i=>typeof i.addEventListener=="function")?(a.forEach(i=>i.addEventListener("change",n)),()=>a.forEach(i=>i.removeEventListener("change",n))):(a.forEach(i=>i.addListener(n)),()=>a.forEach(i=>i.removeListener(n)))},[]),e}r(zht,"useChromeless");function Wz({mobile:e,onNavigateHome:s}){const n=zht(),a=jd(),i=(0,m.useCallback)(()=>{if(Fht()){window.history.back();return}s?s():window.location.assign("/dashboard")},[s]),o=(0,m.useCallback)(()=>{window.location.reload()},[]),l=(0,m.useCallback)(async()=>{const d=window.location.href;try{if(navigator.share){await navigator.share({title:document.title||"Paperclip",url:d});return}await wa(d),a?.pushToast({title:"Link copied",tone:"success"})}catch(u){if(u instanceof DOMException&&u.name==="AbortError")return;a?.pushToast({title:"Share failed",body:"Try opening the page in your browser.",tone:"error"})}},[a]),c=(0,m.useCallback)(()=>{window.open(window.location.href,"_blank","noopener,noreferrer")},[]);return n?(0,t.jsxs)("div",{className:W("flex items-center gap-1",e?"h-10 border-b border-border bg-background/95 px-3 backdrop-blur supports-[backdrop-filter]:bg-background/85":"h-9 border-b border-border px-2"),children:[(0,t.jsx)(PI,{label:"Back",onClick:i,children:(0,t.jsx)(wl,{className:"h-4 w-4"})}),(0,t.jsx)("div",{className:"flex-1"}),(0,t.jsx)(PI,{label:"Refresh",onClick:o,children:(0,t.jsx)(Ii,{className:"h-4 w-4"})}),(0,t.jsx)(PI,{label:"Share",onClick:l,children:(0,t.jsx)(wW,{className:"h-4 w-4"})}),(0,t.jsx)(PI,{label:"Open in Browser",onClick:c,children:(0,t.jsx)($n,{className:"h-4 w-4"})})]}):null}r(Wz,"StandaloneBrowserControls");var qht=16384,Uht=40;function Kht(e){if(!e)return;const s=[];for(const n of e.slice(0,qht).split(`
380
380
  `).slice(0,41)){const a=/^\s*(?:at|in) ([A-Za-z_$][\w$.-]{0,99})(?:\s|$)/.exec(n)?.[1]??/^([A-Za-z_$][\w$.-]{0,99})@/.exec(n)?.[1];if(a&&s.push(` at ${a}`),s.length===Uht)break}return s.length?`
381
381
  ${s.join(`
382
- `)}`:void 0}r(Kht,"sanitizeComponentStack");function _5e(){const e={};if(typeof document<"u"){try{const s=document.readyState;(s==="loading"||s==="interactive"||s==="complete")&&(e.ready_state=s)}catch{}try{const s=document.visibilityState;(s==="visible"||s==="hidden")&&(e.visibility_state=s)}catch{}try{const s=document.documentElement.classList;e.translation_marker=s.contains("translated-ltr")||s.contains("translated-rtl")}catch{}}return e}r(_5e,"readBrowserErrorState");function Qht(e){const s=Kht(e.componentStack);return{tags:{react_error_boundary:e.boundary},contexts:{react:s?{componentStack:s}:{},browser_state:_5e()}}}r(Qht,"buildBrowserErrorContext");var Iae=Promise.resolve();function EV(e){const s=Iae.then(e);return Iae=s.catch(()=>{}),s}r(EV,"enqueue");var _N=null;function Wht(e,s){return EV(async()=>{if(!_N)try{const n=await bd(()=>import("./prod-COP_vZWu.js"),__vite__mapDeps([4,5]));n.init(Vht(e,s)),_N=n}catch{}})}r(Wht,"initBrowserErrorMonitoring");function Hht(){return EV(async()=>{const e=_N;if(_N=null,!e)return;const s=e.getClient();try{e.getCurrentScope().setClient(void 0)}catch{}try{await s?.close(2e3)}catch{}})}r(Hht,"teardownBrowserErrorMonitoring");function LV(e,s){let n;try{s&&(n=Qht(s))}catch{}EV(async()=>{try{n?_N?.captureException(e,n):_N?.captureException(e)}catch{}})}r(LV,"captureBrowserException");function Vht(e,s){return{dsn:e,environment:s??void 0,release:"6252a176e9c51640682a210ba5d45196c317fb39",tracesSampleRate:0,sendDefaultPii:!1,beforeSend:r((n,a)=>{try{if(n.contexts={...n.contexts,browser_state:n.contexts?.browser_state??_5e()},n.tags={...n.tags,browser_build_mode:"production"},n.exception?.values?.some(i=>i.mechanism?.type==="onunhandledrejection"||i.mechanism?.type==="auto.browser.global_handlers.onunhandledrejection")){const i=a.originalException;n.tags.browser_rejection_kind=i===null?"null":typeof i}}catch{}return n},"beforeSend"),integrations:r(n=>n.filter(a=>a.name!=="HttpContext"&&a.name!=="Breadcrumbs"),"integrations")}}r(Vht,"buildBrowserSentryInitOptions");var Ght=class extends m.Component{static{r(this,"RouteErrorBoundaryInner")}state={error:null};static getDerivedStateFromError(e){return{error:e instanceof Error?e:new Error(String(e))}}componentDidCatch(e,s){LV(e,{boundary:"route",componentStack:s.componentStack})}componentDidUpdate(e){this.state.error&&e.resetKey!==this.props.resetKey&&this.setState({error:null})}render(){const{error:e}=this.state;return e?(0,t.jsxs)("div",{className:"mx-auto max-w-2xl space-y-4 px-4 py-10",children:[(0,t.jsxs)("div",{children:[(0,t.jsx)("h1",{className:"text-lg font-semibold",children:"This page hit an error"}),(0,t.jsx)("p",{className:"mt-1 text-sm text-muted-foreground",children:"Something went wrong while rendering this page. You can go back and try again, or reload."})]}),(0,t.jsx)("pre",{className:"overflow-auto rounded-md border border-destructive/30 bg-destructive/10 px-3 py-2 text-xs text-destructive whitespace-pre-wrap",children:e.message}),(0,t.jsxs)("div",{className:"flex items-center gap-2",children:[(0,t.jsx)($,{variant:"outline",size:"sm",onClick:this.props.onReset,children:"Go back"}),(0,t.jsx)($,{size:"sm",onClick:r(()=>window.location.reload(),"onClick"),children:"Reload page"})]})]}):this.props.children}};function A5e({children:e}){const s=la(),n=Gn(),a=`${s.pathname}${s.search}`;return(0,t.jsx)(Ght,{resetKey:a,onReset:r(()=>n(-1),"onReset"),children:e})}r(A5e,"RouteErrorBoundary");var Tae={bot:ao,cpu:Vm,brain:Lx,zap:yR,rocket:ABe,code:kbe,terminal:ff,shield:p3,eye:eu,search:Yr,wrench:pf,hammer:h3,lightbulb:m3,sparkles:G0,star:V0,heart:fC,flame:FBe,bug:Ky,cog:ybe,database:d3,globe:wm,lock:ko,mail:$Q,"message-square":O0,"file-code":zl,"git-branch":Xi,package:t0,puzzle:Mx,target:H0,wand:SW,atom:fBe,"circuit-board":oKe,radar:wBe,swords:KKe,telescope:pBe,microscope:_Ke,crown:jL,gem:_be,hexagon:Jd,pentagon:RKe,fingerprint:pF},Yht="bot";function Zht(e){return e&&iOe.includes(e)?Tae[e]:Tae[Yht]}r(Zht,"getAgentIcon");function TE({icon:e,className:s}){const n=Zht(e);return(0,t.jsx)(n,{className:s})}r(TE,"AgentIcon");function I5e({open:e,onOpenChange:s,...n}){return(0,t.jsx)(Fs,{open:e,onOpenChange:s,children:(0,t.jsxs)(Qs,{"aria-describedby":void 0,className:"gap-0 overflow-hidden p-0 sm:max-w-md",children:[(0,t.jsxs)("div",{className:"px-4 pt-4 pb-3",children:[(0,t.jsx)(Ks,{children:"Chat with an agent"}),n.existingChatAgentIds&&(0,t.jsx)("p",{className:"mt-2 text-sm text-muted-foreground",children:"One conversation per agent. Pick up where you left off."})]}),(0,t.jsx)(Jht,{...n,onComplete:r(()=>s(!1),"onComplete")},String(e))]})})}r(I5e,"AgentChatPicker");function Jht({agents:e,onSelect:s,onComplete:n,loading:a,error:i,onRetry:o,existingChatAgentIds:l,renderAgentIcon:c}){const d=(0,m.useRef)(!1),u=(0,m.useRef)(null);(0,m.useEffect)(()=>(d.current=!0,()=>{d.current=!1,u.current?.abort()}),[]);const[h,p]=(0,m.useState)(""),[f,x]=(0,m.useState)(null),[g,v]=(0,m.useState)(null);async function y(k){if(f)return;x(k.id),v(null);const w=new AbortController;u.current=w;try{await s(k,w.signal),d.current&&n()}catch(N){v(N instanceof Error?N.message:"Couldn’t open chat. Try again.")}finally{x(null)}}return r(y,"selectAgent"),(0,t.jsxs)(f3,{children:[(0,t.jsx)(t2,{"aria-label":"Search agents by name or role",placeholder:"Search by name or role…",value:h,onValueChange:p}),g&&(0,t.jsx)("p",{role:"alert",className:"px-4 py-3 text-sm text-destructive",children:g}),f&&(0,t.jsx)("p",{role:"status",className:"sr-only",children:"Opening conversation…"}),i?(0,t.jsxs)("div",{role:"alert",className:"flex flex-col items-start gap-2 p-4 text-sm",children:[(0,t.jsx)("p",{children:"Couldn’t load agents. Try again."}),o&&(0,t.jsx)($,{variant:"outline",size:"sm",onClick:o,children:"Retry"})]}):a?(0,t.jsx)("p",{role:"status",className:"p-4 text-sm text-muted-foreground",children:"Loading agents…"}):(0,t.jsxs)(s2,{children:[(0,t.jsx)(n2,{children:(0,t.jsxs)("div",{className:"flex flex-col items-center gap-2 px-4",children:[(0,t.jsx)("span",{children:e.length?`No agents match “${h}”`:"No agents yet."}),e.length?(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)("span",{className:"text-xs text-muted-foreground",children:"Try another name or role."}),(0,t.jsx)($,{variant:"ghost",size:"sm",onClick:r(()=>p(""),"onClick"),children:"Clear search"})]}):(0,t.jsx)("span",{className:"text-xs text-muted-foreground",children:"Create an agent from the Agents page to start chatting."})]})}),(0,t.jsx)(Ju,{children:e.map(k=>(0,t.jsxs)(Xo,{value:k.id,keywords:[k.name,k.title??"",k.role],onSelect:r(()=>{y(k)},"onSelect"),disabled:f!==null,className:"gap-3 px-3 py-3",children:[c?c(k):(0,t.jsx)(TE,{icon:k.icon,className:"size-4 shrink-0"}),(0,t.jsxs)("span",{className:"flex min-w-0 flex-1 flex-col gap-0.5",children:[(0,t.jsx)("span",{className:"truncate font-medium",children:k.name}),(0,t.jsx)("span",{className:"truncate text-xs text-muted-foreground",children:k.title??k.role})]}),l&&(0,t.jsx)("span",{className:"shrink-0 text-xs text-muted-foreground",children:l.includes(k.id)?"Open chat":"New chat"}),k.status==="paused"&&(0,t.jsx)("span",{className:"text-xs text-(--status-agent-paused)",children:"Paused"}),k.status==="terminated"&&(0,t.jsx)("span",{className:"text-xs text-muted-foreground",children:"Terminated"}),k.status==="pending_approval"&&(0,t.jsx)("span",{className:"text-xs text-muted-foreground",children:"Awaiting approval"})]},k.id))})]})]})}r(Jht,"AgentChatPickerResults");function x6({agents:e,existingChatAgentIds:s,availableAgents:n=e,activeId:a,previews:i={},loading:o=!1,error:l,onRetry:c,initialSearch:d="",onSelect:u,onBrowse:h,onAddChat:p,historyLoading:f,historyError:x,onRetryHistory:g}){const v=Gn(),[y,k]=(0,m.useState)(!1),[w,N]=(0,m.useState)(d),S=(0,m.useRef)(null),C=(0,m.useId)(),_=w.trim().toLocaleLowerCase(),R=e.filter(T=>`${T.name} ${T.title??""} ${T.role}`.toLocaleLowerCase().includes(_));function I(){N(""),S.current?.focus()}return r(I,"focusSearch"),(0,t.jsxs)("aside",{"aria-labelledby":C,className:"flex h-full min-h-0 flex-col border-r border-border bg-background",children:[(0,t.jsxs)("div",{className:"flex shrink-0 flex-col gap-4 px-3 pb-4 pt-4",children:[(0,t.jsxs)("div",{className:"flex items-center justify-between gap-2",children:[(0,t.jsx)("h2",{id:C,className:"text-sm font-semibold",children:"Chat"}),(0,t.jsx)($,{variant:"outline",size:"icon-sm","aria-label":"Add chat",title:"Add chat",onClick:r(()=>k(!0),"onClick"),children:(0,t.jsx)(bn,{className:"size-4"})})]}),(0,t.jsxs)("div",{className:"relative",children:[(0,t.jsx)(Yr,{"aria-hidden":"true",className:"pointer-events-none absolute left-3 top-1/2 size-3.5 -translate-y-1/2 text-muted-foreground"}),(0,t.jsx)(dt,{ref:S,"aria-label":"Search agents",placeholder:"Find an agent",value:w,onChange:r(T=>N(T.target.value),"onChange"),onKeyDown:r(T=>{T.key==="Escape"&&(T.stopPropagation(),N(""))},"onKeyDown"),className:"h-8 pl-8 pr-8 text-xs md:text-xs"}),w&&(0,t.jsx)($,{variant:"ghost",size:"icon-xs","aria-label":"Clear search",className:"absolute right-1 top-1/2 -translate-y-1/2",onClick:I,children:(0,t.jsx)(Mn,{className:"size-3"})})]})]}),(0,t.jsxs)("div",{className:"flex min-h-0 flex-1 flex-col gap-2 overflow-y-auto px-3 pb-3 scrollbar-auto-hide",children:[(0,t.jsx)("p",{className:"px-2 text-(length:--text-micro) font-medium uppercase tracking-widest text-muted-foreground",children:_?"Search results":"Teammates"}),(0,t.jsx)("span",{role:"status",className:"sr-only",children:o?"Loading agents":`${R.length} ${R.length===1?"agent":"agents"}`}),f&&(0,t.jsx)("p",{role:"status",className:"px-2 text-xs text-muted-foreground",children:"Loading chat history…"}),x&&(0,t.jsxs)("div",{role:"alert",className:"flex flex-col items-start gap-2 px-2 py-3",children:[(0,t.jsx)("p",{className:"text-xs text-muted-foreground",children:"Some chat history couldn’t load."}),(0,t.jsx)($,{variant:"outline",size:"sm",onClick:g,children:"Retry chat history"})]}),l?(0,t.jsxs)("div",{role:"alert",className:"flex flex-col items-start gap-2 px-2 py-6",children:[(0,t.jsx)("p",{className:"text-sm",children:"Couldn’t load your chats."}),(0,t.jsx)($,{variant:"outline",size:"sm",onClick:c,children:"Try again"})]}):o?(0,t.jsx)("div",{"aria-hidden":"true",className:"flex flex-col gap-1",children:[0,1,2,3].map(T=>(0,t.jsxs)("div",{className:"flex items-center gap-3 rounded-md px-2 py-3 motion-safe:animate-pulse",children:[(0,t.jsx)("div",{className:"size-8 shrink-0 rounded-lg bg-muted"}),(0,t.jsxs)("div",{className:"flex flex-1 flex-col gap-2",children:[(0,t.jsx)("div",{className:"h-3 w-2/3 rounded-sm bg-muted"}),(0,t.jsx)("div",{className:"h-2 w-full rounded-sm bg-muted"})]})]},T))}):R.length?(0,t.jsx)("nav",{"aria-label":"Agent conversations",className:"flex flex-col gap-1",children:R.map(T=>(0,t.jsxs)(We,{to:`/chats/${encodeURIComponent(T.status==="terminated"?T.id:Hl(T))}`,"aria-current":a===T.id?"page":void 0,title:`${T.name}${T.title?` · ${T.title}`:""}`,onClick:r(E=>{u&&(E.preventDefault(),u(T))},"onClick"),className:W("flex min-w-0 items-center gap-3 rounded-md px-2 py-3 text-left transition-colors hover:bg-accent/60 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-ring",a===T.id&&"bg-accent text-accent-foreground"),children:[(0,t.jsx)(lr,{agent:T,size:32}),(0,t.jsxs)("span",{className:"flex min-w-0 flex-1 flex-col gap-0.5",children:[(0,t.jsx)("span",{className:"truncate text-sm font-medium",children:T.name}),(0,t.jsx)("span",{className:"truncate text-xs text-muted-foreground",children:T.status==="terminated"?"Terminated":T.status==="paused"?"Paused":i[T.id]??T.title??"Start a conversation"})]})]},T.id))}):!e.length&&(f||x)?null:(0,t.jsxs)("div",{className:"flex flex-col items-start gap-2 px-2 py-6",children:[(0,t.jsx)("p",{className:"text-sm font-medium",children:e.length?"No agents found":"No chats yet"}),(0,t.jsx)("p",{className:"text-xs leading-relaxed text-muted-foreground",children:e.length?"Try another name or role.":"Choose an agent to start a conversation."}),!e.length&&(0,t.jsx)($,{variant:"outline",size:"sm",onClick:r(()=>k(!0),"onClick"),children:"Choose an agent"}),e.length>0&&(0,t.jsx)($,{variant:"outline",size:"sm",onClick:I,children:"Clear search"})]})]}),(0,t.jsx)("div",{className:"shrink-0 px-3 py-4",children:(0,t.jsx)($,{variant:"ghost",size:"sm",className:"w-full justify-start gap-2 px-2 text-muted-foreground",asChild:!h,onClick:h,children:h?(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)(Wo,{className:"size-4"}),"Browse all agents"]}):(0,t.jsxs)(We,{to:"/agents/all",children:[(0,t.jsx)(Wo,{className:"size-4"}),"Browse all agents"]})})}),(0,t.jsx)(I5e,{agents:n,open:y,onOpenChange:k,existingChatAgentIds:s??e.map(T=>T.id),loading:o,error:l,onRetry:c,renderAgentIcon:r(T=>(0,t.jsx)(lr,{agent:T,size:32}),"renderAgentIcon"),onSelect:r(async(T,E)=>{p?await p(T,E):u?await u(T,E):v(`/chats/${encodeURIComponent(Hl(T))}`),E?.aborted||N("")},"onSelect")})]})}r(x6,"AgentConversationSidebar");var RE={list:r(e=>ke.get(`/companies/${e}/chats`),"list"),get:r((e,s)=>ke.get(`/companies/${e}/chats/${encodeURIComponent(s)}`),"get"),ensure:r((e,s)=>ke.post(`/companies/${e}/chats/${encodeURIComponent(s)}`,{}),"ensure")};function T5e(){const{selectedCompanyId:e}=fs(),{enabled:s,loaded:n}=Jj(),a=te({queryKey:D.auth.session,queryFn:r(()=>Pa.getSession(),"queryFn")}),i=a.data?.user?.id??a.data?.session?.userId??null;return{companyId:e,userId:i,enabled:s,loaded:n,agents:te({queryKey:D.agents.list(e),queryFn:r(()=>Nt.list(e),"queryFn"),enabled:s&&!!e}),chats:te({queryKey:D.agentChats.list(e,i),queryFn:r(()=>RE.list(e),"queryFn"),enabled:s&&!!e&&a.isSuccess}),session:a}}r(T5e,"useAgentChatNavigation");function R5e(e,s){const n=wt(),a=Gn(),{isMobile:i,setSidebarOpen:o}=Ua(),l=(0,m.useRef)({companyId:e,userId:s,mounted:!0});return(0,m.useEffect)(()=>{const c={companyId:e,userId:s,mounted:!0};return l.current=c,()=>{c.mounted=!1}},[e,s]),(0,m.useCallback)(async(c,d)=>{if(!e||c.companyId!==e)throw new Error("Choose an agent from this company.");const u=l.current,h=await RE.ensure(e,c.id);n.setQueryData(D.agentChats.detail(e,s,c.id),h),n.setQueryData(D.issues.detail(h.id),h),n.setQueryData(D.agentChats.list(e,s),p=>[h,...(p??[]).filter(f=>f.id!==h.id)].sort((f,x)=>new Date(x.updatedAt).getTime()-new Date(f.updatedAt).getTime()||x.id.localeCompare(f.id))),!(!u.mounted||l.current!==u||d?.aborted)&&(a(`/chats/${encodeURIComponent(Hl(c))}`),i&&o(!1))},[n,e,s,a,i,o])}r(R5e,"useOpenAgentChat");function Xht(){const{companyId:e,userId:s,agents:n,chats:a,session:i}=T5e(),o=R5e(e,s),l=Gn(),c=Rf(e),{isMobile:d,setSidebarOpen:u}=Ua(),{pathname:h}=la(),p=h.split("/chats/")[1]?.split("/")[0],f=n.data??[],x=n.isSuccess?[...new Set((a.data??[]).flatMap(C=>C.conversationAgentId&&!f.some(_=>_.id===C.conversationAgentId)?[C.conversationAgentId]:[]))]:[],g=pm({queries:x.map(C=>({queryKey:D.agents.detail(C),queryFn:r(()=>Nt.get(C,e),"queryFn")}))}),v=new Map(f.map(C=>[C.id,C]));for(const C of g)C.data&&v.set(C.data.id,C.data);const y=[...v.values()].find(C=>C.id===p||C.status!=="terminated"&&encodeURIComponent(Hl(C))===p),k=(a.data??[]).flatMap(C=>{const _=C.conversationAgentId?v.get(C.conversationAgentId):void 0;return _?[_]:[]});y&&!k.some(C=>C.id===y.id)&&k.unshift(y);const w=new Set(k.map(C=>C.id)),N=f.filter(C=>!w.has(C.id)&&C.status!=="terminated"&&(!c.isSuccess||Yx(c.data,"agent",C.id)!=="left")).sort((C,_)=>C.name.localeCompare(_.name,void 0,{sensitivity:"base"})),S=Object.fromEntries((a.data??[]).filter(C=>C.conversationState==="active").map(C=>[C.conversationAgentId,"Working…"]));return(0,t.jsx)(x6,{agents:[...k,...N],availableAgents:f,existingChatAgentIds:k.map(C=>C.id),activeId:y?.id,previews:S,loading:n.isPending||a.isPending||i.isPending,error:n.error??a.error??i.error,onRetry:r(()=>{n.refetch(),a.refetch(),i.refetch()},"onRetry"),historyLoading:g.some(C=>C.isPending),historyError:g.find(C=>C.error)?.error,onRetryHistory:r(()=>{g.filter(C=>C.isError).forEach(C=>{C.refetch()})},"onRetryHistory"),onAddChat:o,onSelect:r(C=>{l(`/chats/${encodeURIComponent(C.status==="terminated"?C.id:Hl(C))}`),d&&u(!1)},"onSelect")},`${e}:${s}`)}r(Xht,"AgentConversationsSidebar");var DI=240,Hz=208,Vz=420,Rae=16;function EE(e){return Math.min(Vz,Math.max(Hz,e))}r(EE,"clampSidebarWidth$1");function Eae(e){if(typeof window>"u")return DI;try{const s=window.localStorage.getItem(e);if(!s)return DI;const n=Number.parseInt(s,10);return Number.isFinite(n)?EE(n):DI}catch{return DI}}r(Eae,"readStoredSidebarWidth$1");function Lae(e,s){if(!(typeof window>"u"))try{window.localStorage.setItem(e,String(EE(s)))}catch{}}r(Lae,"writeStoredSidebarWidth$1");function e0t({children:e,open:s,collapsed:n=!1,peeking:a=!1,resizable:i=!1,storageKey:o="paperclip.sidebar.width",className:l,onPanelMouseEnter:c,onPanelMouseLeave:d,onPanelFocusCapture:u,onPanelBlurCapture:h}){const[p,f]=(0,m.useState)(()=>Eae(o)),[x,g]=(0,m.useState)(!1),v=(0,m.useRef)(p),y=(0,m.useRef)(null);(0,m.useEffect)(()=>{const M=Eae(o);v.current=M,f(M)},[o]);const k=s?p:0,w=s?n?64:k:0,N=s?n&&!a?64:k:0,S=N>w,C=i&&s&&!n,_=(0,m.useMemo)(()=>({width:`${w}px`}),[w]),R=(0,m.useMemo)(()=>({width:`${N}px`}),[N]),I=(0,m.useCallback)(M=>{const Q=EE(M);v.current=Q,f(Q),Lae(o,Q)},[o]),T=(0,m.useCallback)(M=>{C&&(M.preventDefault(),M.currentTarget.setPointerCapture(M.pointerId),y.current={startX:M.clientX,startWidth:v.current},g(!0))},[C]),E=(0,m.useCallback)(M=>{if(!y.current)return;const Q=EE(y.current.startWidth+M.clientX-y.current.startX);v.current=Q,f(Q)},[]),P=(0,m.useCallback)(()=>{y.current&&(y.current=null,g(!1),Lae(o,v.current))},[o]),O=(0,m.useCallback)(M=>{C&&(M.key==="ArrowLeft"?(M.preventDefault(),I(p-Rae)):M.key==="ArrowRight"?(M.preventDefault(),I(p+Rae)):M.key==="Home"?(M.preventDefault(),I(Hz)):M.key==="End"&&(M.preventDefault(),I(Vz)))},[C,I,p]);return(0,t.jsxs)("div",{className:W("relative h-full shrink-0",l),style:_,children:[(0,t.jsx)("div",{className:W("absolute inset-y-0 left-0 flex flex-col overflow-hidden",S?"z-30 border-r border-border bg-background shadow-lg":"z-0"),style:R,"data-sidebar-overlay":S?"":void 0,onMouseEnter:c,onMouseLeave:d,onFocusCapture:u,onBlurCapture:h,children:e}),C?(0,t.jsx)("div",{role:"separator","aria-label":"Resize sidebar","aria-orientation":"vertical","aria-valuemin":Hz,"aria-valuemax":Vz,"aria-valuenow":p,tabIndex:0,"data-dragging":x?"":void 0,className:"group absolute inset-y-0 z-20 cursor-col-resize touch-none outline-none",style:{right:-4,width:8},onPointerDown:T,onPointerMove:E,onPointerUp:P,onPointerCancel:P,onLostPointerCapture:P,onKeyDown:O,children:(0,t.jsx)("div",{className:W("mx-auto h-full w-0.5 transition-colors",x?"bg-ring":"bg-transparent group-hover:bg-ring group-focus-visible:bg-ring")})}):null]})}r(e0t,"SidebarShell$1");function $I({children:e,className:s}){return(0,t.jsx)("div",{"data-secondary-sidebar":"",className:W("h-full w-full min-w-0 overflow-hidden",s),children:(0,t.jsx)(xke,{children:e})})}r($I,"SecondarySidebar$1");var E5e={listStacks:r(()=>ke.get("/cloud/stacks"),"listStacks")};function CM(e,s){const n=e?.trim();if(!n)return null;try{const a=new URL(s,n);return a.protocol!=="https:"&&a.protocol!=="http:"?null:a.toString()}catch{return null}}r(CM,"cloudAppUrl");function L5e(e){return CM(e,"/stacks/new")}r(L5e,"cloudStackCreateUrl");function M5e(e){if(!e.startsWith("/")||e.startsWith("//")||/[\\\x00-\x20]/.test(e))return"/";const s=new URL(e,"https://tenant.invalid");return s.pathname.replace(/\/+$/,"")==="/auth"?"/":`${s.pathname}${s.search}${s.hash}`}r(M5e,"tenantSignInReturnPath");function t0t(e,s,n){const a=s?.trim();if(!a)return null;const i=CM(e,`/v1/stacks/${encodeURIComponent(a)}/entry-redirect`);if(!i)return null;const o=new URL(i);return o.searchParams.set("returnTo",M5e(n)),o.toString()}r(t0t,"cloudStackEntryUrl");function P5e(e,s){const n=s?.trim();return n?CM(e,`/workspaces/${encodeURIComponent(n)}/settings?section=people`):null}r(P5e,"cloudStackInviteUrl");function s0t(e){return CM(e,"/orgs?manage=1")}r(s0t,"cloudPortfolioManageUrl");function D5e(){const e=td(),s=!!e,n=te({queryKey:D.cloud.stacks,queryFn:r(()=>E5e.listStacks(),"queryFn"),enabled:s,staleTime:3e4,retry:!1});if(!e||n.isError)return null;const a=n.data?.stacks.find(i=>i.isCurrent);return a?.role!=="owner"&&a?.role!=="admin"?null:P5e(e.cloudBaseUrl,a.stackSlug)}r(D5e,"useCloudInviteUrl");function n0t(e,s){if(!s)return!1;if(s.source==="local_implicit"||s.isInstanceAdmin)return!0;if(!e)return!1;const n=s.memberships?.find(a=>a.companyId===e&&a.status==="active");return n?.membershipRole==="owner"||n?.membershipRole==="admin"||n?.membershipRole==="operator"||n?.membershipRole==="member"}r(n0t,"canInviteCompanyMembers");function $5e(e=!0){const s=dbe(),n=te({queryKey:D.access.currentBoardAccess,queryFn:r(()=>or.getCurrentBoardAccess(),"queryFn"),enabled:e,retry:!1,staleTime:3e4});return e&&n0t(s?.selectedCompanyId,n.data)}r($5e,"useCanInviteCompanyMembers");function O5e(e){const s=window.location.hostname.endsWith(".staging.paperclip.app"),{data:n,isError:a}=te({queryKey:D.stagingCommit,queryFn:r(()=>Lu.get(),"queryFn"),enabled:s&&e,staleTime:0,retry:!1});return s&&!a?n?.commit??null:null}r(O5e,"useStagingCommit");function r0t(e){return e?.trim().toLowerCase().replace(/['"]/g,"").replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")||null}r(r0t,"slugifyUserPart");function B5e(e){const s=[e?.id,e?.name,e?.email?.split("@")[0],e?.email];for(const n of s){const a=r0t(n);if(a)return`/u/${a}`}return"/u/me"}r(B5e,"userProfilePath");var a0t="Toggle the app appearance.";function Ek({className:e,variant:s="icon",onAfterToggle:n}){const{theme:a,toggleTheme:i}=Bze(),o=a==="dark",l=o?"Switch to light mode":"Switch to dark mode",c=o?j1e:vwe;function d(){i(),n?.()}return r(d,"handleClick"),s==="compact-menu-action"?(0,t.jsxs)("button",{type:"button",className:W("flex h-(--profile-popover-row-height) w-full items-center gap-(--profile-popover-row-gap) rounded-lg px-2.5 text-left text-(length:--text-compact) font-medium leading-(--profile-popover-label-line-height) text-foreground transition-colors hover:bg-accent",e),onClick:d,"aria-label":l,children:[(0,t.jsx)("span",{className:"flex size-5 shrink-0 items-center justify-center text-muted-foreground",children:(0,t.jsx)(c,{className:"size-4"})}),(0,t.jsx)("span",{className:"min-w-0 flex-1 truncate",children:l})]}):s==="menu-action"?(0,t.jsxs)("button",{type:"button",className:W("flex w-full items-start gap-3 rounded-xl px-3 py-3 text-left transition-colors hover:bg-accent/60",e),onClick:d,"aria-label":l,children:[(0,t.jsx)("span",{className:"mt-0.5 rounded-lg border border-border bg-background/70 p-2 text-muted-foreground",children:(0,t.jsx)(c,{className:"size-4"})}),(0,t.jsxs)("span",{className:"min-w-0 flex-1",children:[(0,t.jsx)("span",{className:"block text-sm font-medium text-foreground",children:l}),(0,t.jsx)("span",{className:"block text-xs text-muted-foreground",children:a0t})]})]}):(0,t.jsx)($,{type:"button",variant:"ghost",size:"icon-sm",onClick:d,"aria-label":l,title:l,className:W("text-muted-foreground",e),children:(0,t.jsx)(c,{})})}r(Ek,"ThemeToggle");var w5=null,F5e=!1,Gz=!1,Yz=new Set;function LE(){for(const e of Yz)e()}r(LE,"emit");function i0t(e=typeof navigator>"u"?"":navigator.userAgent,s=typeof navigator>"u"?0:navigator.maxTouchPoints){return/iPhone|iPad|iPod/i.test(e)?!0:/Macintosh/i.test(e)&&s>1}r(i0t,"isIosSafariLike");function o0t(e=window){const s=r(a=>{a.preventDefault(),w5=a,LE()},"onPrompt"),n=r(()=>{w5=null,F5e=!0,LE()},"onInstalled");return e.addEventListener("beforeinstallprompt",s),e.addEventListener("appinstalled",n),()=>{e.removeEventListener("beforeinstallprompt",s),e.removeEventListener("appinstalled",n)}}r(o0t,"captureInstallPrompt");function l0t(){return F5e||Qz()?"installed":w5?"prompt":i0t()?"ios-manual":"unavailable"}r(l0t,"installAvailability");async function c0t(){const e=w5;if(!e)return"unavailable";w5=null,LE(),await e.prompt();const{outcome:s}=await e.userChoice;return s}r(c0t,"promptInstall");function Zz(e){Gz!==e&&(Gz=e,LE())}r(Zz,"setIosInstallHelpOpen");function d0t(){return Gz}r(d0t,"iosInstallHelpOpen");function u0t(){return(0,m.useSyncExternalStore)(z5e,d0t,()=>!1)}r(u0t,"useIosInstallHelpOpen");function z5e(e){return Yz.add(e),()=>{Yz.delete(e)}}r(z5e,"subscribe$1");function m0t(){return(0,m.useSyncExternalStore)(z5e,l0t,()=>"unavailable")}r(m0t,"useInstallAvailability");var Mae="Install app",h0t="Add Paperclip to your home screen or dock.";function q5e({variant:e,onAfterAction:s}){const n=m0t();if(n==="installed"||n==="unavailable")return null;const a=r(()=>{n==="ios-manual"?Zz(!0):c0t(),s?.()},"handleClick");return e==="compact-menu-action"?(0,t.jsxs)("button",{type:"button",className:"flex h-(--profile-popover-row-height) w-full items-center gap-(--profile-popover-row-gap) rounded-lg px-2.5 text-left text-(length:--text-compact) font-medium leading-(--profile-popover-label-line-height) text-foreground transition-colors hover:bg-accent",onClick:a,children:[(0,t.jsx)("span",{className:"flex size-5 shrink-0 items-center justify-center text-muted-foreground",children:(0,t.jsx)(Fi,{className:"size-4"})}),(0,t.jsx)("span",{className:"min-w-0 flex-1 truncate",children:Mae})]}):(0,t.jsxs)("button",{type:"button",className:"flex w-full items-start gap-3 rounded-xl px-3 py-3 text-left transition-colors hover:bg-accent/60",onClick:a,children:[(0,t.jsx)("span",{className:"mt-0.5 rounded-lg border border-border bg-background/70 p-2 text-muted-foreground",children:(0,t.jsx)(Fi,{className:"size-4"})}),(0,t.jsxs)("span",{className:"min-w-0 flex-1",children:[(0,t.jsx)("span",{className:"block text-sm font-medium text-foreground",children:Mae}),(0,t.jsx)("span",{className:"block text-xs text-muted-foreground",children:h0t})]})]})}r(q5e,"InstallAppMenuAction");function p0t(){const e=u0t();return(0,t.jsx)(Fs,{open:e,onOpenChange:Zz,children:(0,t.jsxs)(Qs,{children:[(0,t.jsxs)(rn,{children:[(0,t.jsx)(Ks,{children:"Install Paperclip"}),(0,t.jsx)(mn,{children:"Add Paperclip to your Home Screen from Safari."})]}),(0,t.jsxs)("ol",{className:"space-y-3 text-sm text-foreground",children:[(0,t.jsxs)(pD,{index:1,icon:(0,t.jsx)(FKe,{className:"size-4"}),children:["Tap ",(0,t.jsx)("strong",{children:"Share"})," in the Safari toolbar."]}),(0,t.jsxs)(pD,{index:2,icon:(0,t.jsx)(UKe,{className:"size-4"}),children:["Choose ",(0,t.jsx)("strong",{children:"Add to Home Screen"}),"."]}),(0,t.jsxs)(pD,{index:3,children:["Keep ",(0,t.jsx)("strong",{children:"Open as Web App"})," on, then tap ",(0,t.jsx)("strong",{children:"Add"}),"."]})]}),(0,t.jsx)(cr,{children:(0,t.jsx)($,{type:"button",onClick:r(()=>Zz(!1),"onClick"),children:"Done"})})]})})}r(p0t,"IosInstallHelpDialog");function pD({index:e,icon:s,children:n}){return(0,t.jsxs)("li",{className:"flex items-start gap-3",children:[(0,t.jsx)("span",{className:"flex size-6 shrink-0 items-center justify-center rounded-full border border-border text-xs font-semibold text-muted-foreground",children:e}),(0,t.jsxs)("span",{className:"flex min-w-0 flex-1 items-center gap-2",children:[s?(0,t.jsx)("span",{className:"text-muted-foreground",children:s}):null,(0,t.jsx)("span",{children:n})]})]})}r(pD,"InstallStep");function f0t(e){if(!e)return"Unavailable";const s=new Date(e);return Number.isNaN(s.getTime())?"Unavailable":new Intl.DateTimeFormat(void 0,{dateStyle:"medium",timeStyle:"short"}).format(s)}r(f0t,"formatTimestamp$2");function x0t(e){return!!e&&!Number.isNaN(new Date(e).getTime())}r(x0t,"isValidTimestamp");function g0t(e){return e?.devServer?.lastRestartAt??e?.serverInfo?.processStartedAt??null}r(g0t,"restartTimestamp");function b0t(e){const s=e?.serverInfo?.git;return s?.available?`${s.shortSha} · ${s.subject}`:"Commit unavailable"}r(b0t,"commitLabel");function v0t(e){const s=e?.serverInfo?.git;if(!s?.available)return"Unavailable";const n=s.localChanges;if(!n||!n.available)return"Change status unavailable";if(!n.hasLocalChanges)return"Clean checkout";const a=[[n.stagedFileCount,"staged"],[n.unstagedFileCount,"unstaged"],[n.untrackedFileCount,"untracked"]].filter(([i])=>Number(i)>0).map(([i,o])=>`${i} ${o}`);return a.length>0?`Local changes present (${a.join(", ")})`:"Local changes present"}r(v0t,"localChangesLabel");function fD({icon:e,label:s,value:n,dateTime:a}){return(0,t.jsxs)("div",{className:"flex w-full items-start gap-3 rounded-xl px-3 py-3 text-left",children:[(0,t.jsx)("span",{className:"mt-0.5 rounded-lg border border-border bg-background/70 p-2 text-muted-foreground",children:(0,t.jsx)(e,{className:"size-4"})}),(0,t.jsxs)("span",{className:"min-w-0 flex-1",children:[(0,t.jsx)("span",{className:"block text-sm font-medium text-foreground",children:s}),a?(0,t.jsx)("time",{dateTime:a,className:"block break-words text-xs text-muted-foreground",children:n}):(0,t.jsx)("span",{className:"block break-words text-xs text-muted-foreground",children:n})]})]})}r(fD,"ServerInfoRow");function U5e(){const e=te({queryKey:D.instance.experimentalSettings,queryFn:r(()=>jr.getExperimental(),"queryFn")}).data?.enableServerInfoDebugView===!0,s=te({queryKey:D.health,queryFn:r(()=>Lu.get(),"queryFn"),enabled:e,refetchOnMount:"always",refetchInterval:r(h=>h.state.data?.devServer?.enabled?2e3:!1,"refetchInterval")});if(!e)return null;const n=s.data,a=s.isLoading&&!n,i=s.isError,o=g0t(n),l=x0t(o),c=i?"Health unavailable":a?"Loading...":f0t(o),d=i?"Health unavailable":a?"Loading...":b0t(n),u=i?"Health unavailable":a?"Loading...":v0t(n);return(0,t.jsxs)("div",{className:"mt-2 border-t border-border pt-2",children:[(0,t.jsx)("p",{className:"px-3 pb-1 pt-1 text-(length:--text-micro) font-medium uppercase tracking-wide text-muted-foreground",children:"Server"}),(0,t.jsx)(fD,{icon:Au,label:"Last restarted",value:c,dateTime:!i&&!a&&l?o:null}),(0,t.jsx)(fD,{icon:pW,label:"Running commit",value:d}),(0,t.jsx)(fD,{icon:pKe,label:"Checkout state",value:u})]})}r(U5e,"SidebarServerInfo");var y0t="/company/settings/members?tab=invites",j0t="https://docs.paperclip.ing/",w0t="https://paperclip.ing/feedback";function k0t(e){const s=e.trim().split(/\s+/).filter(Boolean);return s.length>=2?`${s[0]?.[0]??""}${s[s.length-1]?.[0]??""}`.toUpperCase():e.slice(0,2).toUpperCase()}r(k0t,"deriveInitials$2");function xD({label:e,icon:s,onClick:n,href:a,external:i=!1,topLevel:o=!1}){const l="flex h-(--profile-popover-row-height) w-full items-center gap-(--profile-popover-row-gap) rounded-lg px-2.5 text-left text-(length:--text-compact) font-medium leading-(--profile-popover-label-line-height) text-foreground transition-colors hover:bg-accent",c=(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)("span",{className:"flex size-5 shrink-0 items-center justify-center text-muted-foreground",children:(0,t.jsx)(s,{className:"size-4"})}),(0,t.jsx)("span",{className:"min-w-0 flex-1 truncate",children:e})]});return a?i?(0,t.jsx)("a",{href:a,target:"_blank",rel:"noreferrer",className:l,onClick:n,children:c}):o?(0,t.jsx)("a",{href:a,className:l,onClick:n,children:c}):(0,t.jsx)(We,{to:a,className:l,onClick:n,children:c}):(0,t.jsx)("button",{type:"button",className:l,onClick:n,children:c})}r(xD,"MenuAction$1");function Pae({deploymentMode:e,open:s,onOpenChange:n,forceExpanded:a=!1}){const o=!!td(),{hidden:l,loaded:c}=Eu(),d=D5e(),u=$5e(!o),h=o?d:u?y0t:null,p=c&&h!==null&&!Kx(l,"company.members")&&!Kx(l,"company.invites"),[f,x]=(0,m.useState)(!1),{isMobile:g,setSidebarOpen:v,collapsed:y,peeking:k}=Ua(),w=y&&!k&&!a,N=s??f,S=O5e(N),C=n??x,{data:_}=te({queryKey:D.auth.session,queryFn:r(()=>Pa.getSession(),"queryFn"),retry:!1}),R=j2({onSignedOut:O}),I=_?.user.name?.trim()||"Board",T=_?.user.email?.trim()||(e==="authenticated"?"Signed in":"Local workspace board"),E=k0t(I),P=B5e(_?.user);function O(){C(!1),g&&v(!1)}r(O,"closeNavigationChrome");function M(){R.mutate()}return r(M,"handleSignOut"),(0,t.jsx)("div",{className:"bg-border/50 px-3 py-2 dark:bg-muted",children:(0,t.jsxs)("div",{className:W("flex items-center gap-0.5",!w&&"px-2"),children:[(0,t.jsxs)(dr,{open:N,onOpenChange:C,children:[(0,t.jsx)(wr,{asChild:!0,children:(0,t.jsxs)("button",{type:"button",className:W("flex min-w-0 items-center gap-2.5 rounded-lg text-left text-(length:--text-compact) font-medium text-foreground/80 transition-colors hover:bg-sidebar-accent hover:text-sidebar-accent-foreground",w?"w-full px-3 py-2":"flex-1 px-2 py-1.5"),"aria-label":"Open account menu",children:[(0,t.jsxs)(bo,{size:"sm",children:[_?.user.image?(0,t.jsx)(Jc,{src:_.user.image,alt:I}):null,(0,t.jsx)(vo,{children:E})]}),(0,t.jsx)("span",{className:W("min-w-0 flex-1 truncate",w&&"block w-0 min-w-0 overflow-hidden whitespace-nowrap text-transparent select-none"),children:I})]})}),(0,t.jsxs)(nr,{side:"top",align:"start",sideOffset:10,className:"min-h-(--profile-popover-min-height) w-(--profile-popover-width) max-w-(--sz-calc-24) overflow-hidden rounded-xl border-border bg-popover p-0 shadow-(--shadow-profile-popover)",children:[(0,t.jsxs)("div",{className:"relative flex h-(--profile-popover-header-height) shrink-0 items-center gap-2.5 px-3.5",children:[(0,t.jsx)(We,{to:P,"aria-label":"View profile",onClick:O,className:"absolute inset-0 transition-colors hover:bg-accent focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-ring"}),(0,t.jsxs)(bo,{className:"pointer-events-none relative size-9",children:[_?.user.image?(0,t.jsx)(Jc,{src:_.user.image,alt:I}):null,(0,t.jsx)(vo,{className:"text-xs text-foreground",children:E})]}),(0,t.jsxs)("div",{className:"pointer-events-none relative min-w-0 flex-1",children:[(0,t.jsx)("h2",{className:"truncate text-sm font-semibold leading-(--profile-popover-label-line-height) text-foreground",children:I}),(0,t.jsx)("p",{className:"truncate text-(length:--text-micro) leading-(--profile-popover-meta-line-height) text-muted-foreground",children:T}),S?(0,t.jsxs)("a",{className:"pointer-events-auto block truncate font-mono text-(length:--text-micro) leading-(--profile-popover-meta-line-height) text-muted-foreground hover:underline focus-visible:underline",href:`https://github.com/paperclipai/paperclip/commit/${S}`,target:"_blank",rel:"noreferrer","aria-label":`View commit ${S} on GitHub`,title:S,children:["SHA ",S.slice(0,7)]}):null]})]}),(0,t.jsxs)("div",{className:"flex flex-1 flex-col gap-0.5 border-t border-border px-2.5 pb-2.5 pt-2",children:[(0,t.jsx)(xD,{label:"Settings",icon:Iu,href:"/company/settings",onClick:O}),p&&h?(0,t.jsx)(xD,{label:"Invite",icon:hh,href:h,topLevel:o,onClick:O}):null,(0,t.jsx)(xD,{label:"Documentation",icon:p2,href:j0t,external:!0,onClick:r(()=>C(!1),"onClick")}),(0,t.jsx)(Ek,{variant:"compact-menu-action",onAfterToggle:r(()=>C(!1),"onAfterToggle")}),(0,t.jsx)(q5e,{variant:"compact-menu-action",onAfterAction:r(()=>C(!1),"onAfterAction")}),e==="authenticated"?(0,t.jsxs)("button",{type:"button",className:W("flex h-(--profile-popover-row-height) w-full items-center gap-(--profile-popover-row-gap) rounded-lg px-2.5 text-left text-(length:--text-compact) font-medium leading-(--profile-popover-label-line-height) text-foreground transition-colors hover:bg-destructive/10",R.isPending&&"cursor-not-allowed opacity-60"),onClick:M,disabled:R.isPending,children:[(0,t.jsx)("span",{className:"flex size-5 shrink-0 items-center justify-center text-muted-foreground",children:(0,t.jsx)(rp,{className:"size-4"})}),(0,t.jsx)("span",{className:"min-w-0 flex-1 truncate",children:R.isPending?"Signing out...":"Sign out"})]}):null,(0,t.jsx)(U5e,{})]})]})]}),!w&&!o?(0,t.jsxs)(Fn,{children:[(0,t.jsx)(Bn,{asChild:!0,children:(0,t.jsx)("a",{href:w0t,target:"_blank",rel:"noreferrer","aria-label":"Share feedback",className:"flex size-8 shrink-0 items-center justify-center rounded-lg text-muted-foreground/50 transition-colors hover:bg-sidebar-accent hover:text-sidebar-accent-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring",children:(0,t.jsx)(ug,{className:"h-4 w-4","aria-hidden":"true"})})}),(0,t.jsx)(On,{side:"top",children:"Share feedback"})]}):null]})})}r(Pae,"SidebarAccountMenu$1");function K5e({onNewIssue:e,onSearch:s,onToggleSidebar:n,onTogglePanel:a,onShowShortcuts:i,onGoToInbox:o}){(0,m.useEffect)(()=>{let l=!1,c=null;const d=r(()=>{c!==null&&(window.clearTimeout(c),c=null)},"clearGoChordTimeout"),u=r(()=>{l=!1,d()},"disarmGoChord"),h=r(()=>{l=!0,d(),c=window.setTimeout(()=>{l=!1,c=null},1200)},"armGoChord");function p(g){if(g.defaultPrevented){u();return}if(o){const v=gve({armed:l,defaultPrevented:g.defaultPrevented,key:g.key,metaKey:g.metaKey,ctrlKey:g.ctrlKey,altKey:g.altKey,target:g.target,hasOpenDialog:Z0()});if(v==="arm"){h();return}if(v==="navigate_inbox"){u(),g.preventDefault(),o();return}if(v==="focus_comment"||v==="open_file_viewer"){u(),g.preventDefault();return}v==="disarm"&&u()}if(!b3(g.target)&&!Z0()){if(g.key==="/"&&!g.metaKey&&!g.ctrlKey&&!g.altKey){g.preventDefault(),MFe()||s?.();return}if(g.key==="?"&&!g.metaKey&&!g.ctrlKey&&!g.altKey){g.preventDefault(),i?.();return}g.key==="c"&&!g.metaKey&&!g.ctrlKey&&!g.altKey&&(g.preventDefault(),e?.()),g.key==="["&&!g.metaKey&&!g.ctrlKey&&(g.preventDefault(),n?.()),g.key==="]"&&!g.metaKey&&!g.ctrlKey&&(g.preventDefault(),a?.())}}r(p,"handleKeyDown");const f=r(()=>u(),"handlePointerDown"),x=r(g=>{g.target instanceof HTMLElement&&g.target!==document.body&&u()},"handleFocusIn");return document.addEventListener("pointerdown",f,!0),document.addEventListener("focusin",x,!0),document.addEventListener("keydown",p),()=>{u(),document.removeEventListener("pointerdown",f,!0),document.removeEventListener("focusin",x,!0),document.removeEventListener("keydown",p)}},[e,s,n,a,i,o])}r(K5e,"useKeyboardShortcuts");var N0t=new Set(["auth","invite","board-claim","cli-auth","docs","s"]);function Q5e(e){const s=(e.split("?")[0]??"").split("/").filter(Boolean);if(s.length===0)return!0;const[n]=s;return!N0t.has(n)}r(Q5e,"isRememberableCompanyPath");function S0t(e){const s=dj(e.companyPrefix);return e.companies.find(n=>dj(n.issuePrefix)===s)??null}r(S0t,"findCompanyByPrefix");function C0t(e){const s=DQ(e.pathname);return s?S0t({companies:e.companies,companyPrefix:s})?.id??null:e.fallbackCompanyId}r(C0t,"getRememberedPathOwnerCompanyId");function _0t(e){const s=e.path?yL(e.path):"/dashboard";if(!Q5e(s))return"/dashboard";const[n,a]=(s.split("?")[0]??"").split("/").filter(Boolean);if(n==="issues"&&a){const i=/^([A-Za-z]+)-\d+$/.exec(a);if(i&&dj(i[1]??"")!==dj(e.companyPrefix))return"/dashboard"}return s}r(_0t,"sanitizeRememberedPathForCompany");var W5e="paperclip.companyPaths";function H5e(){try{const e=localStorage.getItem(W5e);if(e)return JSON.parse(e)}catch{}return{}}r(H5e,"getCompanyPaths");function A0t(e,s){const n=H5e();n[e]=s,localStorage.setItem(W5e,JSON.stringify(n))}r(A0t,"saveCompanyPath");function V5e(){const{companies:e,selectedCompanyId:s,selectedCompany:n,selectionSource:a}=fs(),i=la(),o=Gn(),l=(0,m.useRef)(s),c=(0,m.useMemo)(()=>C0t({companies:e,pathname:i.pathname,fallbackCompanyId:l.current}),[e,i.pathname]),d=i.pathname+i.search;(0,m.useEffect)(()=>{const u=c,h=yL(d);u&&Q5e(h)&&A0t(u,h)},[d,c]),(0,m.useEffect)(()=>{if(s){if(l.current!==null&&s!==l.current&&a!=="route_sync"&&n){const u=H5e(),h=_0t({path:u[s],companyPrefix:n.issuePrefix});o(`/${n.issuePrefix}${h}`,{replace:!0})}l.current=s}},[n,s,a,o])}r(V5e,"useCompanyPageMemory");var I0t=class{static{r(this,"MobileNavScrollTracker")}options;lastTop;lastMaxTop;visible=!0;direction=0;distance=0;constructor(e,s,n){this.options=e,this.lastTop=s,this.lastMaxTop=n}update(e,s){const n=Math.max(0,Math.min(e,s)),a=n-Math.max(this.lastTop,this.options.topZone),i=s!==this.lastMaxTop;if(this.lastTop=n,this.lastMaxTop=s,n<=this.options.topZone)this.visible=!0,this.direction=0,this.distance=0;else if(i)this.direction=0,this.distance=0;else if(a!==0){const o=Math.sign(a);o!==this.direction&&(this.distance=0),this.direction=o,this.distance+=Math.abs(a);const l=o>0?this.options.hideDistance:this.options.showDistance;this.distance>=l&&(this.visible=o<0,this.distance=0)}return this.visible}};function G5e(e,s){const[n,a]=(0,m.useState)(!0);return(0,m.useEffect)(()=>{if(a(!0),!e)return;const i=getComputedStyle(document.documentElement),o=r(p=>Number.parseFloat(i.getPropertyValue(p))||0,"distance"),l=r(()=>{const p=document.scrollingElement??document.documentElement;return{top:window.scrollY||p.scrollTop||0,max:Math.max(0,p.scrollHeight-p.clientHeight)}},"scrollBounds"),c=l(),d=new I0t({topZone:o("--mobile-nav-scroll-top-zone"),hideDistance:o("--mobile-nav-scroll-hide-distance"),showDistance:o("--mobile-nav-scroll-show-distance")},c.top,c.max);let u=null;const h=r(()=>{u===null&&(u=requestAnimationFrame(()=>{u=null;const{top:p,max:f}=l(),x=d.visible,g=d.update(p,f);g!==x&&a(g)}))},"onScroll");return window.addEventListener("scroll",h,{passive:!0}),()=>{window.removeEventListener("scroll",h),u!==null&&cancelAnimationFrame(u)}},[e,s]),n}r(G5e,"useMobileNavVisibility");function Y5e(e){const{matchedCompany:s,selectedCompanyId:n,companies:a}=e;return!s||s.status!=="archived"||n===s.id?null:a.find(i=>i.id===n&&i.status!=="archived")??a.find(i=>i.status!=="archived")??null}r(Y5e,"resolveArchivedCompanyBounce");function T0t(e){const{archivedCompanyId:s,companies:n,cloudPortfolioUrl:a}=e,i=n.find(o=>o.id!==s&&o.status!=="archived");return i?{kind:"company",company:i}:a?{kind:"cloud_portfolio",url:a}:{kind:"companies_list"}}r(T0t,"resolveCompanyArchiveDeparture");function Z5e(e){const{selectionSource:s,selectedCompanyId:n,routeCompanyId:a}=e;return!(n===a||s==="manual"&&n)}r(Z5e,"shouldSyncCompanySelectionFromRoute");function R0t(e,s){return e instanceof HTMLElement?!(s instanceof HTMLElement)||!document.contains(s)||s===document.body||s===document.documentElement?!0:!e.contains(s):!1}r(R0t,"shouldFocusMainContentAfterNavigation");function J5e(e){if(!(e instanceof HTMLElement))return()=>{};const s=window.requestAnimationFrame(()=>{R0t(e,document.activeElement)&&e.focus({preventScroll:!0})});return()=>window.cancelAnimationFrame(s)}r(J5e,"scheduleMainContentFocus");function X5e(e=document,s=window){const n=r(()=>{e.documentElement.scrollTop!==0&&(e.documentElement.scrollTop=0),e.body.scrollTop!==0&&(e.body.scrollTop=0)},"onScroll");return s.addEventListener("scroll",n,{capture:!0}),()=>s.removeEventListener("scroll",n,{capture:!0})}r(X5e,"pinDocumentScrollToZero");function mm({scope:e="global",requestedPrefix:s}){const n=la(),{setBreadcrumbs:a}=Vn(),{companies:i,selectedCompany:o}=fs();(0,m.useEffect)(()=>{a([{label:"Not Found"}])},[a]);const l=o??i[0]??null,c=l?`/${l.issuePrefix}/dashboard`:"/",d=`${n.pathname}${n.search}${n.hash}`,u=s?.toUpperCase(),h=e==="invalid_company_prefix"?"Organization not found":"Page not found",p=e==="invalid_company_prefix"?`No organization matches prefix "${u??"unknown"}".`:"This route does not exist.";return(0,t.jsx)("div",{className:"mx-auto max-w-2xl py-10",children:(0,t.jsxs)(sn,{className:"block p-6",children:[(0,t.jsxs)("div",{className:"flex items-center gap-3",children:[(0,t.jsx)("div",{className:"rounded-md border border-destructive/20 bg-destructive/10 p-2",children:(0,t.jsx)(Es,{className:"h-5 w-5 text-destructive"})}),(0,t.jsxs)("div",{children:[(0,t.jsx)("h1",{className:"text-xl font-semibold",children:h}),(0,t.jsx)("p",{className:"text-sm text-muted-foreground",children:p})]})]}),(0,t.jsxs)("div",{className:"mt-4 rounded-md border border-border bg-muted/20 px-3 py-2 text-xs text-muted-foreground",children:["Requested path: ",(0,t.jsx)("code",{className:"font-mono",children:d})]}),(0,t.jsxs)("div",{className:"mt-5 flex flex-wrap gap-2",children:[(0,t.jsx)($,{asChild:!0,children:(0,t.jsxs)(We,{to:c,children:[(0,t.jsx)(vR,{className:"mr-1.5 h-4 w-4"}),"Open dashboard"]})}),(0,t.jsx)($,{variant:"outline",asChild:!0,children:(0,t.jsx)(We,{to:"/",children:"Go home"})})]})]})})}r(mm,"NotFoundPage");function E0t(e,s){return kNe(e,s)[0]?.toLowerCase()??null}r(E0t,"getCompanyRouteSegment$1");var L0t=new Set(["browse","connections","assistant-connection","connect","chat","vercel-connect","review","attention","gateways","advanced","app"]);function M0t({sidebarSections:e}){const{sidebarOpen:s,setSidebarOpen:n,toggleSidebar:a,collapsed:i,peeking:o,setPeeking:l,isMobile:c,setForceCollapsed:d}=Ua(),{openNewIssue:u,openOnboarding:h}=al(),{togglePanelVisible:p}=Ef(),f=jd()?.pushToast??null,{companies:x,loading:g,selectedCompany:v,selectedCompanyId:y,selectionSource:k,setSelectedCompanyId:w}=fs(),{companyPrefix:N,pluginRoutePath:S,agentId:C,routineId:_}=xa(),R=Gn(),I=la(),T=vL(),{enabled:E}=Ec(),P=NNe(I.pathname,N),O=P.builtInContextualSurface==="settings",M=P.companySegments,Q=P.isTaskDetail,{enabled:L}=Jj(),F=L&&M[0]?.toLowerCase()==="chats",q=E&&(Q||F),z=M[0]?.toLowerCase()==="tools",K=M[0]?.toLowerCase()==="apps",U=K&&M[1]&&!L0t.has(M[1].toLowerCase())?M[1]:null,V=K&&M[1]?.toLowerCase()==="app"&&M[2]?M[2]:null,ne=(0,m.useRef)(!1),Z=(0,m.useRef)(null),ie=(0,m.useRef)(null),J=(0,m.useRef)(new hke),ae=(0,m.useRef)(I.key),oe=G5e(c&&!Q,I.pathname),[G,X]=(0,m.useState)(!1),Y=(0,m.useMemo)(()=>{if(!N)return null;const Rt=N.toUpperCase();return x.find(Qe=>Qe.issuePrefix.toUpperCase()===Rt)??null},[x,N]),re=!!N&&!g&&x.length>0&&!Y,se=(0,m.useMemo)(()=>S?.toLowerCase()??E0t(I.pathname,N),[N,I.pathname,S]),ce=Y?.id??null,pe=Y?.issuePrefix??null,{slots:fe}=Bd({slotTypes:["page","routeSidebar"],companyId:ce,enabled:!!(ce&&se)}),ve=(0,m.useMemo)(()=>$W(fe,se),[se,fe]),Ie=(0,m.useMemo)(()=>({companyId:ce,companyPrefix:pe}),[ce,pe]),de=O?(0,t.jsx)(DYe,{}):!E&&P.builtInContextualSurface==="skills"?(0,t.jsx)(pse,{}):U?(0,t.jsx)(mse,{kind:"connection",connectionId:U}):V?(0,t.jsx)(mse,{kind:"application",applicationId:V}):K||z?(0,t.jsx)(KYe,{}):ve?E?(0,t.jsx)(O3,{surface:`plugin:${ve.id}`,title:ve.displayName,children:(0,t.jsx)(vm,{slot:ve,context:Ie,className:"min-h-0 flex-1",missingBehavior:"placeholder"})}):(0,t.jsx)(vm,{slot:ve,context:Ie,className:"h-full w-full",missingBehavior:"placeholder"}):null,xe=F?(0,t.jsx)(Xht,{}):P.builtInContextualSurface==="agent"&&C?(0,t.jsx)(rZe,{agentRef:C}):E&&P.builtInContextualSurface==="routine"&&_?(0,t.jsx)(CHe,{children:(0,t.jsx)(oZe,{routineId:_})}):E&&P.builtInContextualSurface==="skills"?(0,t.jsx)(pse,{}):de,le=xe!=null,Re=E&&le&&(F||P.builtInContextualSurface==="skills"||P.builtInContextualSurface==="agent"||P.builtInContextualSurface==="routine"||K||z),Le=E&&le&&!Re,je=le&&(!E||Re),_e=!E||!le?null:ve&&!P.builtInContextualSurface?`plugin:${ve.id}`:P.builtInContextualSurface,Ze=(0,m.useRef)(null),{data:ue}=te({queryKey:D.health,queryFn:r(()=>Lu.get(),"queryFn"),retry:!1,refetchInterval:r(Rt=>Rt.state.data?.devServer?.enabled?2e3:!1,"refetchInterval"),refetchIntervalInBackground:!1});(0,m.useLayoutEffect)(()=>(d(!E&&le),()=>d(!1)),[le,d,E]),(0,m.useEffect)(()=>{const Rt=Ze.current;_e&&N&&Rt&&Rt.surface!==_e&&Rt.pathname!==I.pathname&&LYe({surface:_e,companyPrefix:N,previousPathname:Rt.pathname}),Ze.current={pathname:I.pathname,surface:_e}},[N,_e,I.pathname]),(0,m.useEffect)(()=>{g||ne.current||ue?.deploymentMode!=="authenticated"&&(ue?.cloud||x.length===0&&(ne.current=!0,h()))},[x,g,h,ue?.cloud,ue?.deploymentMode]),(0,m.useEffect)(()=>{if(!N||g||x.length===0)return;if(!Y){const Qe=(y?x.find(Be=>Be.id===y):null)??x[0]??null;Qe&&y!==Qe.id&&w(Qe.id,{source:"route_sync"});return}if(N!==Y.issuePrefix){const Qe=I.pathname.replace(/^\/[^/]+/,"");R(`/${Y.issuePrefix}${Qe}${I.search}`,{replace:!0});return}const Rt=Y5e({matchedCompany:Y,selectedCompanyId:y,companies:x});if(Rt){f?.({title:`${Y.name} is archived`,body:`Switched to ${Rt.name}.`,tone:"info",dedupeKey:`archived-company-bounce:${Y.id}`}),w(Rt.id,{source:"route_sync"}),R(`/${Rt.issuePrefix}/dashboard`,{replace:!0});return}Z5e({selectionSource:k,selectedCompanyId:y,routeCompanyId:Y.id})&&w(Y.id,{source:"route_sync"})},[N,x,g,Y,I.pathname,I.search,R,f,k,y,w]);const Fe=p,mt=(0,m.useCallback)(()=>{document.dispatchEvent(new KeyboardEvent("keydown",{key:"k",metaKey:!0,bubbles:!0,cancelable:!0}))},[]),bt=(0,m.useRef)(null),et=(0,m.useRef)(!1),qe=(0,m.useRef)(!1),it=(0,m.useCallback)(()=>{bt.current!==null&&(window.clearTimeout(bt.current),bt.current=null)},[]),_t=(0,m.useCallback)(()=>{it(),bt.current=window.setTimeout(()=>l(!0),50)},[it,l]),$t=(0,m.useCallback)(()=>{it(),l(!0)},[it,l]),Ot=(0,m.useCallback)(()=>{it(),bt.current=window.setTimeout(()=>l(!1),120)},[it,l]),at=(0,m.useCallback)(()=>{et.current=!0,i&&!qe.current&&_t()},[i,_t]),Me=(0,m.useCallback)(()=>{et.current=!1,qe.current=!1,Ot()},[Ot]),De=(0,m.useCallback)(()=>{qe.current||$t()},[$t]),ut=(0,m.useCallback)(()=>{et.current||Ot()},[Ot]);(0,m.useEffect)(()=>it,[it]);const Pt=(0,m.useRef)(i);return(0,m.useEffect)(()=>{i!==Pt.current&&(i?(it(),l(!1),qe.current=et.current):qe.current=!1,Pt.current=i)},[i,it,l]),(0,m.useEffect)(()=>{if(!o)return;const Rt=r(Qe=>{Qe.key==="Escape"&&(it(),l(!1))},"onKeyDown");return window.addEventListener("keydown",Rt),()=>window.removeEventListener("keydown",Rt)},[o,it,l]),V5e(),K5e({onNewIssue:r(()=>u(),"onNewIssue"),onSearch:mt,onToggleSidebar:a,onTogglePanel:Fe,onShowShortcuts:r(()=>X(!0),"onShowShortcuts"),onGoToInbox:r(()=>R("/inbox"),"onGoToInbox")}),(0,m.useEffect)(()=>{if(!c)return;const Rt=30,Qe=50,Be=75;let Oe=0,Pe=0;const Ve=r(nt=>{const Lt=nt.touches[0];Oe=Lt.clientX,Pe=Lt.clientY},"onTouchStart"),be=r(nt=>{const Lt=nt.changedTouches[0],Cs=Lt.clientX-Oe;if(!(Math.abs(Lt.clientY-Pe)>Be)){if(!s&&Oe<Rt&&Cs>Qe){n(!0);return}s&&Cs<-50&&n(!1)}},"onTouchEnd");return document.addEventListener("touchstart",Ve,{passive:!0}),document.addEventListener("touchend",be,{passive:!0}),()=>{document.removeEventListener("touchstart",Ve),document.removeEventListener("touchend",be)}},[c,s,n]),(0,m.useEffect)(()=>{const Rt=document.body.style.overflow;return document.body.style.overflow=c?"visible":"clip",()=>{document.body.style.overflow=Rt}},[c]),(0,m.useEffect)(()=>{if(!c)return X5e()},[c]),(0,m.useEffect)(()=>{if(typeof document>"u")return;const Rt=ie.current;return J5e(Rt)},[I.pathname]),(0,m.useEffect)(()=>{const Rt=ie.current;if(!Rt)return;const Qe=r(()=>{J.current.remember(ae.current,Rt.scrollTop)},"recordScroll");return Rt.addEventListener("scroll",Qe,{passive:!0}),()=>Rt.removeEventListener("scroll",Qe)},[]),(0,m.useLayoutEffect)(()=>{const Rt=ie.current,Qe=mke({previousPathname:Z.current,pathname:I.pathname,navigationType:T,state:I.state});Z.current=I.pathname;const Be=T==="POP",Oe=Be?J.current.recall(I.key):0;if(ae.current=I.key,Be){FR(Rt,Oe);const Pe=requestAnimationFrame(()=>FR(Rt,Oe));return()=>cancelAnimationFrame(Pe)}Qe&&pke(Rt)},[I.key,I.pathname,I.state,T]),(0,t.jsx)(dke,{children:(0,t.jsxs)("div",{className:W("bg-background text-foreground pt-(--sz-safe-top)",c?"min-h-dvh overflow-x-clip":"flex h-dvh flex-col overflow-clip"),children:[(0,t.jsx)("a",{href:"#main-content",className:"sr-only focus:not-sr-only focus:fixed focus:left-3 focus:top-3 focus:z-(--z-200) focus:rounded-md focus:bg-background focus:px-3 focus:py-2 focus:text-sm focus:font-medium focus:shadow-lg focus:outline-none focus-visible:ring-2 focus-visible:ring-ring",children:"Skip to Main Content"}),(0,t.jsx)(N5e,{}),(0,t.jsx)(S5e,{devServer:ue?.devServer}),(0,t.jsxs)("div",{className:W("min-h-0 flex-1",c?"w-full":"flex overflow-clip"),children:[c&&s&&(0,t.jsx)("button",{type:"button",className:"fixed inset-0 z-40 bg-black/50",onClick:r(()=>n(!1),"onClick"),"aria-label":"Close sidebar"}),c?(0,t.jsxs)("div",{className:W("fixed inset-y-0 left-0 z-50 flex flex-col overflow-hidden pt-(--sz-safe-top) transition-transform duration-100 ease-out",s?"translate-x-0":"-translate-x-full"),children:[(0,t.jsx)("div",{className:"flex flex-1 min-h-0 overflow-hidden",children:(0,t.jsx)("div",{className:"w-60 shrink-0 overflow-hidden",children:le?(0,t.jsx)($I,{children:xe}):(0,t.jsx)(lse,{children:e})})}),(0,t.jsx)(Pae,{deploymentMode:ue?.deploymentMode,forceExpanded:Le})]}):(0,t.jsxs)(e0t,{open:s,collapsed:Le?!1:i,peeking:Le?!1:o,resizable:!0,onPanelMouseEnter:Le?void 0:at,onPanelMouseLeave:Le?void 0:Me,onPanelFocusCapture:!Le&&i?De:void 0,onPanelBlurCapture:!Le&&i?ut:void 0,children:[(0,t.jsx)("div",{className:"flex flex-1 min-h-0",children:Le?(0,t.jsx)($I,{children:xe}):(0,t.jsx)(lse,{children:e})}),(0,t.jsx)(Pae,{deploymentMode:ue?.deploymentMode,forceExpanded:Le})]}),!c&&je&&!Re?(0,t.jsx)($I,{className:"w-60 shrink-0",children:xe}):null,(0,t.jsxs)("div",{className:W("flex min-w-0 flex-col",c?"w-full":"h-full flex-1"),children:[(0,t.jsxs)("div",{"data-slot":c?"mobile-topbar":void 0,className:W(!c&&q&&"hidden",c&&"sticky top-0 z-20 bg-background/95 backdrop-blur supports-[backdrop-filter]:bg-background/85"),children:[(0,t.jsx)(Wz,{mobile:c,onNavigateHome:r(()=>R("/dashboard"),"onNavigateHome")}),(0,t.jsx)(xse,{}),c&&O?(0,t.jsx)("div",{className:"border-b border-border px-4 pb-3",children:(0,t.jsx)(_Ne,{})}):null]}),(0,t.jsxs)("div",{className:W(c?"block":"flex flex-1 min-h-0",!c&&q&&"streamlined-task-detail-surface"),children:[!c&&Re?(0,t.jsx)($I,{className:"w-60 shrink-0 bg-background",children:xe}):null,(0,t.jsxs)("div",{className:W(!c&&q?"flex min-w-0 flex-1 flex-col":"contents"),children:[!c&&q?(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)(Wz,{mobile:!1,onNavigateHome:r(()=>R("/dashboard"),"onNavigateHome")}),(0,t.jsx)(xse,{taskDetailLayout:!0})]}):null,(0,t.jsx)("main",{id:"main-content",ref:ie,tabIndex:-1,style:c?{"--tc-composer-bottom":"var(--sz-calc-14)"}:void 0,className:W("flex-1 p-4 outline-none md:p-6",!c&&q&&"pt-0 md:pt-0",c?"overflow-visible pb-(--sz-calc-14)":"overflow-auto [scrollbar-gutter:stable]"),children:re?(0,t.jsx)(mm,{scope:"invalid_company_prefix",requestedPrefix:N??v?.issuePrefix}):(0,t.jsx)(A5e,{children:(0,t.jsx)(rv,{})})})]}),(0,t.jsx)(BNe,{taskDetailLayout:!c&&q})]})]})]}),c&&(0,t.jsx)(k5e,{visible:oe}),(0,t.jsx)(FNe,{}),(0,t.jsx)(N2e,{}),(0,t.jsx)(m5e,{}),(0,t.jsx)(f5e,{}),(0,t.jsx)(v5e,{}),(0,t.jsx)(y5e,{open:G,onOpenChange:X}),(0,t.jsx)(j5e,{}),(0,t.jsx)(kht,{health:ue}),(0,t.jsx)(w5e,{localTrusted:ue?.deploymentMode==="local_trusted"})]})})}r(M0t,"Layout$1");var e3e=(0,m.createContext)(!1);function P0t({children:e}){return(0,t.jsx)(e3e.Provider,{value:!0,children:e})}r(P0t,"SidebarNavExpandedProvider");function D0t(){return(0,m.useContext)(e3e)}r(D0t,"useSidebarNavExpanded");function Ya({to:e,label:s,icon:n,iconNode:a,end:i,className:o,labelClassName:l,badge:c,badgeTone:d="default",badgeLabel:u,textBadge:h,textBadgeTone:p="default",alert:f=!1,liveCount:x,active:g,trailing:v,trailingLabel:y,liveAccessory:k}){const{isMobile:w,setSidebarOpen:N,collapsed:S,peeking:C}=Ua(),_=D0t(),R=S&&!C&&!_,I=c!=null&&c>0,T=x!=null&&x>0,E=T?`${x} live`:I?`${c}${u?` ${u}`:""}`:f?"attention needed":void 0,P=!R||!E&&!y?void 0:`${s}${E?`, ${E}`:""}${y?`, ${y}`:""}`,O=(0,t.jsxs)(av,{to:e,state:Tf,end:i,"aria-label":P,onClick:r(()=>{w&&N(!1)},"onClick"),className:r(({isActive:M})=>W("flex items-center gap-2.5 mx-2 rounded-lg px-2 py-1.5 pointer-coarse:py-1 text-(length:--text-compact) font-medium transition-colors",g??M?"bg-accent text-foreground":"text-foreground/80 hover:bg-accent/50 hover:text-foreground",o),"className"),children:[(0,t.jsxs)("span",{className:"relative shrink-0",children:[a??(n?(0,t.jsx)(n,{className:"h-4 w-4"}):null),f&&(0,t.jsx)("span",{className:"absolute -right-0.5 -top-0.5 h-2 w-2 rounded-full bg-red-500 shadow-(--shadow-extract-12)","aria-hidden":"true"}),R&&!f&&T&&(0,t.jsxs)("span",{className:"absolute -right-0.5 -top-0.5 flex h-2 w-2","aria-hidden":"true",children:[(0,t.jsx)("span",{className:"animate-pulse absolute inline-flex h-full w-full rounded-full bg-blue-600 dark:bg-blue-400 opacity-75"}),(0,t.jsx)("span",{className:"relative inline-flex h-2 w-2 rounded-full bg-blue-600 dark:bg-blue-400 shadow-(--shadow-extract-12)"})]}),R&&!f&&!T&&I&&(0,t.jsx)("span",{className:W("absolute -right-0.5 -top-0.5 h-2 w-2 rounded-full shadow-(--shadow-extract-12)",d==="danger"?"bg-red-600":d==="warning"?"bg-amber-500":"bg-primary"),"aria-hidden":"true"})]}),(0,t.jsx)("span",{className:R?zj:W("min-w-0 flex-1 truncate",l),children:s}),!R&&v,!R&&h&&(0,t.jsx)(ot,{variant:"ghost",className:W("ml-auto px-1.5 text-(length:--text-nano) leading-none",p==="amber"?"bg-amber-100 text-amber-800 dark:bg-amber-900/30 dark:text-amber-400":"bg-muted text-muted-foreground"),children:h}),!R&&(T||k)&&(0,t.jsxs)("span",{className:"ml-auto flex items-center gap-1.5",children:[k,T&&(0,t.jsxs)(t.Fragment,{children:[(0,t.jsxs)("span",{className:"relative flex h-2 w-2",children:[(0,t.jsx)("span",{className:"animate-pulse absolute inline-flex h-full w-full rounded-full bg-blue-600 dark:bg-blue-400 opacity-75"}),(0,t.jsx)("span",{className:"relative inline-flex rounded-full h-2 w-2 bg-blue-600 dark:bg-blue-400"})]}),(0,t.jsxs)("span",{className:"text-(length:--text-micro) font-medium text-blue-600 dark:text-blue-400",children:[x," live"]})]})]}),!R&&I&&(0,t.jsx)(ot,{variant:"ghost",className:W("ml-auto px-1.5 leading-none",d==="danger"?"bg-red-600/90 text-red-50":d==="warning"?"bg-amber-500/90 text-amber-50":"bg-primary text-primary-foreground"),children:c})]});return R?(0,t.jsxs)(Fn,{children:[(0,t.jsx)(Bn,{asChild:!0,children:(0,t.jsx)("div",{children:O})}),(0,t.jsx)(On,{side:"right",children:s})]}):O}r(Ya,"SidebarNavItem");var $0t=3,Dae=12e4,O0t=[{value:"top",label:"Top"},{value:"alphabetical",label:"Alphabetical"},{value:"recent",label:"Recent"}];function Zw(e,s){const n=e[s];if(!n)return 0;const a=new Date(n).getTime();return Number.isFinite(a)?a:0}r(Zw,"agentTimestamp");function $ae(e,s){if(s==="top")return e;const n=[...e];return s==="alphabetical"?(n.sort((a,i)=>a.name.localeCompare(i.name,void 0,{sensitivity:"base"})),n):(n.sort((a,i)=>{const o=Zw(i,"lastHeartbeatAt")-Zw(a,"lastHeartbeatAt");if(o!==0)return o;const l=Zw(i,"updatedAt")-Zw(a,"updatedAt");if(l!==0)return l;const c=Zw(i,"createdAt")-Zw(a,"createdAt");return c!==0?c:a.name.localeCompare(i.name,void 0,{sensitivity:"base"})}),n)}r($ae,"sortAgents");var B0t="opacity-0 transition-opacity group-hover/agent:opacity-100 group-focus-within/agent:opacity-100";function F0t({activeAgentId:e,activeTab:s,agent:n,disabled:a,isMobile:i,leaving:o,onLeaveAgent:l,onPauseResume:c,rail:d,runCount:u,setSidebarOpen:h,builtInStatus:p,starred:f=!1,onToggleStar:x,starPending:g=!1}){const v=Hl(n),y=s?`${om(n)}/${s}`:om(n),k=`${om(n)}/configuration`,w=e===v,N=n.status==="paused",S=N&&n.pauseReason==="budget",C=n.orgChainHealth?.status==="invalid_org_chain",_=N?"Resume agent":"Pause agent",R=a||n.status==="pending_approval"||S||N&&C,I=a?"Updating...":S?"Budget paused":N&&C?"Invalid org chain":_,T=p==="needs_setup"||p==="pending_approval",E=[T?`Built-in agent ${p.replace(/_/g," ")}`:null,C?"Invalid reporting chain":null].filter(Boolean).join(", ")||void 0,P=(0,t.jsx)(Ya,{to:y,label:n.name,iconNode:(0,t.jsx)(lr,{agent:n,size:16,className:"shrink-0 h-4 w-4"}),active:w,liveCount:u,labelClassName:T?"min-w-(--sz-4_5rem) flex-initial":void 0,className:W("min-w-0 flex-1",f&&!i?"pr-14":"pr-8"),trailing:T||C?(0,t.jsxs)("span",{className:"ml-1 flex shrink-0 items-center gap-1",children:[T?(0,t.jsx)(kk,{status:p,compact:!0}):null,C?(0,t.jsx)(Es,{className:"h-3.5 w-3.5 shrink-0 text-amber-500","aria-label":"Invalid reporting chain"}):null]}):void 0,trailingLabel:E,liveAccessory:n.pauseReason==="budget"?(0,t.jsx)(P3,{title:"Agent paused by budget"}):void 0});return d?P:(0,t.jsxs)("div",{className:"group/agent relative flex items-center",children:[P,f&&!i&&x?(0,t.jsx)("span",{className:"absolute right-10 top-1/2 -translate-y-1/2",children:(0,t.jsx)(Yj,{size:"row",quiet:!0,starred:!0,pending:g,resourceName:n.name,onToggle:r(()=>x(n,!1),"onToggle"),revealClassName:B0t})}):null,(0,t.jsxs)(na,{children:[(0,t.jsx)(ta,{asChild:!0,children:(0,t.jsx)($,{variant:"ghost",size:"icon-xs",className:W("absolute right-3 top-1/2 h-6 w-6 -translate-y-1/2 transition-opacity data-[state=open]:pointer-events-auto data-[state=open]:opacity-100",i?"opacity-100":"pointer-events-none opacity-0 group-hover/agent:pointer-events-auto group-hover/agent:opacity-100 group-focus-within/agent:pointer-events-auto group-focus-within/agent:opacity-100"),"aria-label":`Open actions for ${n.name}`,children:(0,t.jsx)(_i,{className:"h-3.5 w-3.5"})})}),(0,t.jsxs)(sa,{align:"end",className:"w-48",children:[x?(0,t.jsxs)(t.Fragment,{children:[(0,t.jsxs)(us,{onClick:r(()=>{g||x(n,!f)},"onClick"),disabled:g,children:[g?(0,t.jsx)(st,{className:"size-4 motion-safe:animate-spin"}):(0,t.jsx)(V0,{className:W("size-4",f&&"fill-amber-500 text-amber-500")}),(0,t.jsx)("span",{children:f?"Remove from starred":"Star agent"})]}),(0,t.jsx)(ri,{})]}):null,(0,t.jsx)(us,{asChild:!0,children:(0,t.jsxs)(We,{to:k,onClick:r(()=>{i&&h(!1)},"onClick"),children:[(0,t.jsx)(rc,{className:"size-4"}),(0,t.jsx)("span",{children:"Edit agent"})]})}),(0,t.jsx)(ri,{}),(0,t.jsxs)(us,{onClick:r(()=>{R||c(n,N?"resume":"pause")},"onClick"),disabled:R,title:S?"Agent was paused by budget limits":void 0,children:[N?(0,t.jsx)(I3,{className:"size-4"}):(0,t.jsx)(Xd,{className:"size-4"}),(0,t.jsx)("span",{children:I})]}),(0,t.jsx)(ri,{}),(0,t.jsxs)(us,{onClick:r(()=>{o||l(n)},"onClick"),disabled:o,children:[o?(0,t.jsx)(st,{className:"size-4 motion-safe:animate-spin"}):(0,t.jsx)(rp,{className:"size-4"}),(0,t.jsx)("span",{children:o?"Leaving...":"Leave agent"})]})]})]})]})}r(F0t,"SidebarAgentItem");function z0t({streamlined:e=!1}={}){const[s,n]=(0,m.useState)(!0),[a,i]=(0,m.useState)(()=>new Set),[o,l]=(0,m.useState)(0),c=(0,m.useRef)(new Map),d=wt(),{selectedCompanyId:u}=fs(),h=g2(u),{openNewAgent:p}=al(),{isMobile:f,setSidebarOpen:x,collapsed:g,peeking:v}=Ua(),y=g&&!v,{pushToast:k}=Zr(),w=la(),{data:N}=te({queryKey:D.agents.list(u),queryFn:r(()=>Nt.list(u),"queryFn"),enabled:!!u}),{data:S}=te({queryKey:D.instance.experimentalSettings,queryFn:r(()=>jr.getExperimental(),"queryFn"),enabled:!!u}),C=S?.enableBuiltInAgents===!0,{data:_}=te({queryKey:D.builtInAgents.list(u),queryFn:r(()=>S0.list(u),"queryFn"),enabled:!!u&&C}),R=(0,m.useMemo)(()=>{const je=new Map;if(!C)return je;for(const _e of _??[])_e.agentId&&je.set(_e.agentId,_e.status);return je},[_,C]),{data:I}=te({queryKey:D.auth.session,queryFn:r(()=>Pa.getSession(),"queryFn")}),T=Rf(u),E=cv(u),P=D.liveRuns(u),O=jo({companyId:u,resourceKey:"live-runs",queryKey:P,enabled:!!u,refetchInterval:!1,leaderOnly:!0}),{data:M,dataUpdatedAt:Q}=te({queryKey:P,queryFn:r(()=>ea.liveRunsForCompany(u),"queryFn"),enabled:O.enabled,refetchInterval:O.refetchInterval});wo(O,M,Q);const L=(0,m.useMemo)(()=>{const je=new Map;for(const _e of M??[])je.set(_e.agentId,(je.get(_e.agentId)??0)+1);return je},[M]),F=(0,m.useMemo)(()=>{const je=new Set;for(const[_e,Ze]of L)Ze>0&&je.add(_e);return je},[L]),q=(0,m.useMemo)(()=>(N??[]).filter(je=>je.status!=="terminated"&&(!T.isSuccess||Yx(T.data,"agent",je.id)!=="left")),[N,T.data,T.isSuccess]),z=I?.user?.id??I?.session?.userId??null,K=(0,m.useMemo)(()=>u?Nke(u,z):null,[z,u]),[U,V]=(0,m.useState)(()=>K?Nk(K):"top"),{orderedAgents:ne}=_ke({agents:q,companyId:u,userId:z}),Z=(0,m.useMemo)(()=>$ae(ne,U),[ne,U]),ie=(0,m.useMemo)(()=>new Set(Z.map(je=>je.id)),[Z]);(0,m.useEffect)(()=>{const je=Date.now();for(const _e of F)c.current.set(_e,je);for(const _e of c.current.keys())ie.has(_e)||c.current.delete(_e)},[F,ie]);const J=(0,m.useMemo)(()=>{const je=Date.now(),_e=c.current;return Z.filter(Ze=>{if((L.get(Ze.id)??0)>0)return!0;const ue=_e.get(Ze.id);return ue!==void 0&&je-ue<=Dae})},[L,o,Z]),ae=J.length>0,oe=e?ae?J:Z.slice(0,$0t):Z,G=e&&Z.length>0,X=w.pathname.match(/^\/(?:[^/]+\/)?agents\/([^/]+)(?:\/([^/]+))?/),Y=X?.[1]??null,re=X?.[2]??null;(0,m.useEffect)(()=>{if(!K){V("top");return}V(Nk(K))},[K]),(0,m.useEffect)(()=>{if(!K)return;const je=r(Ze=>{Ze.key===K&&V(Nk(K))},"onStorage"),_e=r(Ze=>{const ue=Ze.detail;!ue||ue.storageKey!==K||V(ue.sortMode)},"onCustomEvent");return window.addEventListener("storage",je),window.addEventListener(Z_,_e),()=>{window.removeEventListener("storage",je),window.removeEventListener(Z_,_e)}},[K]),(0,m.useEffect)(()=>{if(!e)return;const je=Date.now();let _e=null;for(const ue of Z){if((L.get(ue.id)??0)>0)continue;const Fe=c.current.get(ue.id);if(Fe===void 0)continue;const mt=Fe+Dae;mt<je||(_e=_e===null?mt:Math.min(_e,mt))}if(_e===null)return;const Ze=window.setTimeout(()=>{l(ue=>ue+1)},Math.max(0,_e-je+1));return()=>{window.clearTimeout(Ze)}},[e,Z,L,o]);const se=(0,m.useCallback)(je=>{const _e=je==="alphabetical"||je==="recent"?je:"top";V(_e),K&&Cke(K,_e)},[K]),ce=we({mutationFn:r(({agent:je,action:_e})=>_e==="pause"?Nt.pause(je.id,u??void 0):Nt.resume(je.id,u??void 0),"mutationFn"),onMutate:r(({agent:je})=>{i(_e=>{const Ze=new Set(_e);return Ze.add(je.id),Ze})},"onMutate"),onSuccess:r(async(je,{agent:_e,action:Ze})=>{u&&await Promise.all([d.invalidateQueries({queryKey:D.agents.list(u)}),d.invalidateQueries({queryKey:D.liveRuns(u)}),d.invalidateQueries({queryKey:D.dashboard(u)})]),await Promise.all([d.invalidateQueries({queryKey:D.agents.detail(_e.id)}),d.invalidateQueries({queryKey:D.agents.detail(Hl(_e))})]),k({title:Ze==="pause"?"Agent paused":"Agent resumed",body:_e.name,tone:"success"})},"onSuccess"),onError:r((je,{agent:_e,action:Ze})=>{k({title:Ze==="pause"?"Could not pause agent":"Could not resume agent",body:je instanceof Error?je.message:_e.name,tone:"error"})},"onError"),onSettled:r((je,_e,{agent:Ze})=>{i(ue=>{const Fe=new Set(ue);return Fe.delete(Ze.id),Fe})},"onSettled")}),pe=(0,m.useCallback)(je=>E.mutate({resourceType:"agent",resourceId:je.id,resourceName:je.name,state:"left"}),[E]),fe=(0,m.useCallback)(je=>E.isPending&&E.variables?.resourceType==="agent"&&E.variables.resourceId===je.id,[E.isPending,E.variables]),ve=(0,m.useCallback)((je,_e)=>E.mutate({resourceType:"agent",resourceId:je.id,resourceName:je.name,starred:_e}),[E]),Ie=(0,m.useCallback)(je=>E.isPending&&E.variables?.resourceType==="agent"&&E.variables.resourceId===je.id&&E.variables.starred!==void 0,[E.isPending,E.variables]),de=(0,m.useMemo)(()=>new Set(zL(T.data,"agent")),[T.data]),xe=(0,m.useMemo)(()=>$ae(q.filter(je=>de.has(je.id)),"alphabetical"),[q,de]),le=(0,m.useMemo)(()=>oe.filter(je=>!de.has(je.id)),[oe,de]),Re=h&&!h.loading?q.find(je=>je.id===h.primaryAgentId):void 0,Le=r((je,_e)=>(0,t.jsx)(F0t,{activeAgentId:Y,activeTab:re,agent:je,disabled:a.has(je.id),isMobile:f,leaving:fe(je),onLeaveAgent:pe,onPauseResume:r((Ze,ue)=>ce.mutate({agent:Ze,action:ue}),"onPauseResume"),rail:y,runCount:L.get(je.id)??0,setSidebarOpen:x,builtInStatus:R.get(je.id),starred:_e||Gj(T.data,"agent",je.id),onToggleStar:ve,starPending:Ie(je)},je.id),"renderAgentRow");return(0,t.jsxs)($x,{label:"Agents",collapsible:{open:s,onOpenChange:n},headerAction:{ariaLabel:"New agent",icon:bn,onClick:p},menu:{ariaLabel:"Agents section actions",actions:[{type:"item",label:"Browse agents",icon:Wo,href:"/agents/all"},{type:"separator"}],radioLabel:"Agent sort",radioChoices:O0t,radioValue:U,onRadioValueChange:se},children:[[...Re?[Re]:[],...xe.filter(je=>je.id!==Re?.id),...le.filter(je=>je.id!==Re?.id)].map(je=>Le(je,de.has(je.id))),G&&(()=>{const je=(0,t.jsxs)(We,{to:"/agents/all",state:Tf,"aria-label":y?"See all agents":void 0,onClick:r(()=>{f&&x(!1)},"onClick"),className:"flex items-center gap-2.5 mx-2 rounded-lg px-2 py-1.5 pointer-coarse:py-1 text-(length:--text-compact) font-medium text-muted-foreground transition-colors hover:bg-accent/50 hover:text-foreground",children:[(0,t.jsx)(Wo,{className:"shrink-0 h-4 w-4"}),(0,t.jsx)("span",{className:y?"block w-0 min-w-0 overflow-hidden whitespace-nowrap text-transparent select-none":void 0,children:"See all agents"})]});return y?(0,t.jsxs)(Fn,{children:[(0,t.jsx)(Bn,{asChild:!0,children:je}),(0,t.jsx)(On,{side:"right",children:"See all agents"})]}):je})()]})}r(z0t,"SidebarAgents");var q0t="opacity-0 transition-opacity group-hover/starred-project:opacity-100 group-focus-within/starred-project:opacity-100";function U0t(){const{selectedCompanyId:e}=fs(),{isMobile:s,setSidebarOpen:n,collapsed:a,peeking:i}=Ua(),o=a&&!i,l=la(),{data:c}=te({queryKey:D.projects.list(e),queryFn:r(()=>aa.list(e),"queryFn"),enabled:!!e}),d=Rf(e),u=cv(e),h=l.pathname.match(/^\/(?:[^/]+\/)?projects\/([^/]+)/)?.[1]??null,p=(0,m.useMemo)(()=>{if(!d.isSuccess)return[];const v=new Set(zL(d.data,"project"));if(v.size===0)return[];const y=new Map((c??[]).map(k=>[k.id,k]));return Array.from(v).map(k=>y.get(k)).filter(k=>!!k).sort((k,w)=>k.name.localeCompare(w.name,void 0,{sensitivity:"base"}))},[d.data,d.isSuccess,c]),f=(0,m.useCallback)(v=>u.mutate({resourceType:"project",resourceId:v.id,resourceName:v.name,starred:!1}),[u]),x=(0,m.useCallback)(v=>u.mutate({resourceType:"project",resourceId:v.id,resourceName:v.name,state:"left"}),[u]),g=(0,m.useCallback)(v=>u.isPending&&u.variables?.resourceType==="project"&&u.variables.resourceId===v.id,[u.isPending,u.variables]);return!d.isSuccess||p.length===0?null:(0,t.jsx)("div",{className:"flex flex-col gap-0.5","aria-label":"Starred projects",children:p.map(v=>{const y=Qx(v),k=h===y||h===v.id,w=g(v),N=w&&u.variables?.starred===!1,S=w&&u.variables?.state==="left",C=Gj(d.data,"project",v.id),_=(0,t.jsxs)(av,{to:`/projects/${y}/issues`,state:Tf,onClick:r(()=>{s&&n(!1)},"onClick"),className:W("flex min-w-0 flex-1 items-center gap-2.5 mx-2 rounded-lg px-2 py-1.5 pointer-coarse:py-1 pr-8 text-(length:--text-compact) font-medium transition-colors",!o&&"pl-6",k?"bg-accent text-foreground":"text-foreground/80 hover:bg-accent/50 hover:text-foreground"),children:[(0,t.jsx)(nh,{color:v.color??null,icon:v.icon??null,size:"xs"}),(0,t.jsx)("span",{className:o?zj:"flex-1 truncate",children:v.name}),!o&&v.visibility==="private"?(0,t.jsx)(ko,{className:"size-3.5 shrink-0 text-muted-foreground","aria-label":"Private project"}):null,!o&&v.pauseReason==="budget"?(0,t.jsx)(P3,{title:"Project paused by budget"}):null]});return(0,t.jsxs)("div",{className:"group/starred-project relative flex items-center",children:[o?(0,t.jsxs)(Fn,{children:[(0,t.jsx)(Bn,{asChild:!0,children:(0,t.jsx)("div",{className:"min-w-0 flex-1",children:_})}),(0,t.jsx)(On,{side:"right",children:v.name})]}):_,!o&&!s?(0,t.jsx)("span",{className:"absolute right-3 top-1/2 -translate-y-1/2",children:(0,t.jsx)(Yj,{size:"row",quiet:!0,starred:C,pending:N,resourceName:v.name,onToggle:r(()=>f(v),"onToggle"),revealClassName:q0t})}):null,!o&&s?(0,t.jsxs)(na,{children:[(0,t.jsx)(ta,{asChild:!0,children:(0,t.jsx)($,{variant:"ghost",size:"icon-xs",className:"absolute right-3 top-1/2 h-6 w-6 -translate-y-1/2 opacity-100","aria-label":`Open actions for ${v.name}`,children:(0,t.jsx)(_i,{className:"h-3.5 w-3.5"})})}),(0,t.jsxs)(sa,{align:"end",className:"w-48",children:[(0,t.jsxs)(us,{onClick:r(()=>{w||f(v)},"onClick"),disabled:w,children:[N?(0,t.jsx)(st,{className:"size-4 motion-safe:animate-spin"}):(0,t.jsx)(V0,{className:"size-4 fill-amber-500 text-amber-500"}),(0,t.jsx)("span",{children:"Remove from starred"})]}),(0,t.jsx)(ri,{}),(0,t.jsxs)(us,{onClick:r(()=>{w||x(v)},"onClick"),disabled:w,children:[S?(0,t.jsx)(st,{className:"size-4 motion-safe:animate-spin"}):(0,t.jsx)(rp,{className:"size-4"}),(0,t.jsx)("span",{children:"Leave project"})]})]})]}):null]},v.id)})})}r(U0t,"SidebarStarredProjects");var K0t="size-5 shrink-0 rounded-md text-(length:--text-micro)",Q0t="size-(--organization-popover-avatar-size) shrink-0 rounded-lg text-(length:--text-micro)",W0t="h-(--organization-popover-company-row-height) min-w-0 gap-(--organization-popover-row-gap) rounded-lg px-2.5 py-0 text-(length:--text-compact) focus:bg-accent/50 focus:text-foreground",gD="h-(--organization-popover-action-row-height) gap-(--organization-popover-row-gap) rounded-lg px-2.5 py-0 text-(length:--text-compact) font-medium leading-(--organization-popover-action-line-height) text-foreground focus:bg-accent/50 focus:text-foreground";function t3e({company:e,inPopover:s=!1}){return(0,t.jsx)(Zx,{companyName:e.name,logoUrl:e.logoUrl,className:s?Q0t:K0t})}r(t3e,"WorkspaceIcon");function H0t({company:e,isEditing:s,isSelected:n,onSelect:a}){const{attributes:i,listeners:o,setActivatorNodeRef:l,setNodeRef:c,transform:d,transition:u,isDragging:h}=d2({id:e.id,disabled:!s});return(0,t.jsxs)(us,{ref:c,style:{transform:l2.Transform.toString(d),transition:u,zIndex:h?10:void 0},onSelect:r(p=>{if(s){p.preventDefault();return}a(e)},"onSelect"),className:W(W0t,s&&"cursor-grab",h&&"opacity-80"),children:[(0,t.jsx)(t3e,{company:e,inPopover:!0}),(0,t.jsxs)("span",{className:"min-w-0 flex-1",children:[(0,t.jsx)("span",{className:"block truncate font-medium leading-(--organization-popover-name-line-height)",children:e.name}),s?null:(0,t.jsx)("span",{className:"block truncate text-(length:--text-nano) leading-(--organization-popover-prefix-line-height) text-muted-foreground",children:e.issuePrefix})]}),s?(0,t.jsx)("button",{type:"button",ref:l,"aria-label":`Reorder ${e.name}`,className:"inline-flex size-8 shrink-0 items-center justify-center rounded text-muted-foreground hover:bg-accent hover:text-foreground focus-visible:outline-none focus-visible:ring-(length:--rad-2) focus-visible:ring-ring",onClick:r(p=>{p.preventDefault(),p.stopPropagation()},"onClick"),...i,...o,children:(0,t.jsx)(LL,{className:"size-4","aria-hidden":"true"})}):(0,t.jsx)("span",{className:"flex size-5 shrink-0 items-center justify-center",children:n?(0,t.jsx)(ms,{className:"size-4 text-foreground"}):null})]})}r(H0t,"SortableCompanyItem");function V0t(e={}){return(0,t.jsx)(jNe,{...e,children:(0,t.jsx)(G0t,{...e})})}r(V0t,"SidebarCompanyMenu");function G0t({open:e,onOpenChange:s}){const[n,a]=(0,m.useState)(!1),[i,o]=(0,m.useState)(!1),{companies:l,selectedCompany:c,setSelectedCompanyId:d,companyListUnavailable:u,retryCompanies:h}=fs(),{openOnboarding:p}=al(),{isMobile:f,setSidebarOpen:x,collapsed:g,peeking:v}=Ua(),y=g&&!v,k=la(),w=Gn(),N=e??n,S=s??a,C=r2(gf(WQ,{activationConstraint:{distance:8}}),gf(Mbe,{activationConstraint:{delay:180,tolerance:6}})),_=(0,m.useMemo)(()=>l.filter(Z=>Z.status!=="archived"),[l]),{data:R}=te({queryKey:D.auth.session,queryFn:r(()=>Pa.getSession(),"queryFn"),retry:!1}),I=R?.user?.id??R?.session?.userId??null,{orderedCompanies:T,persistOrder:E}=yNe({companies:_,userId:I}),{hidden:P,loaded:O}=Eu(),M=O&&!Kx(P,"company.members")&&!Kx(P,"company.invites"),Q="company",L=c?.name??null,F=!!td(),q=j2({onSignedOut:K});function z(Z){Z||o(!1),S(Z)}r(z,"handleOpenChange");function K(){S(!1),o(!1),f&&x(!1)}r(K,"closeNavigationChrome");function U(Z){const ie=k.pathname.split("/")[1]?.toUpperCase(),J=_.some(oe=>oe.issuePrefix.toUpperCase()===ie),ae=Z.id!==c?.id&&(k.pathname.startsWith("/instance/")||J);d(Z.id),S(!1),f&&x(!1),ae&&w(`/${Z.issuePrefix}/dashboard`)}r(U,"selectCompany");function V(){F||(S(!1),f&&x(!1),p({initialStep:1}))}r(V,"addCompany");const ne=(0,m.useCallback)(Z=>{const{active:ie,over:J}=Z;if(!J||ie.id===J.id)return;const ae=T.map(X=>X.id),oe=ae.indexOf(ie.id),G=ae.indexOf(J.id);oe===-1||G===-1||E(SL(ae,oe,G))},[T,E]);return(0,t.jsxs)(na,{open:N,onOpenChange:z,children:[(0,t.jsx)(ta,{asChild:!0,children:(0,t.jsxs)($,{variant:"ghost",className:"h-9 min-w-0 flex-1 justify-start gap-2 px-4 text-left hover:bg-accent/50 hover:text-foreground has-[>svg]:px-4 dark:hover:bg-accent/50","aria-label":L?`Open ${L} ${Q} switcher`:`Open ${Q} switcher`,children:[(0,t.jsxs)("span",{className:"flex min-w-0 flex-1 items-center gap-2",children:[c?(0,t.jsx)(t3e,{company:c}):null,(0,t.jsx)("span",{className:W("min-w-0 truncate text-sm font-bold text-foreground",y&&"block w-0 min-w-0 overflow-hidden whitespace-nowrap text-transparent select-none"),title:L??void 0,children:L??`Select ${Q}`})]}),!y&&(0,t.jsx)(kL,{className:"size-3.5 shrink-0 text-muted-foreground"})]})}),(0,t.jsxs)(sa,{align:"start",sideOffset:8,className:"ml-2 w-(--organization-popover-width) max-w-(--sz-calc-24) overflow-hidden rounded-xl border-border bg-popover p-0 shadow-(--shadow-profile-popover)",children:[(0,t.jsxs)("div",{className:"flex h-(--organization-popover-header-height) items-center justify-between gap-2 px-3.5",children:[(0,t.jsx)(ov,{className:"p-0 text-(length:--text-compact) font-semibold text-foreground",children:"Organizations"}),(0,t.jsx)("button",{type:"button",onClick:r(Z=>{Z.preventDefault(),Z.stopPropagation(),o(ie=>!ie)},"onClick"),className:"rounded px-1.5 py-0.5 text-xs font-medium text-muted-foreground transition-colors hover:bg-accent hover:text-foreground",children:i?"Done":"Edit"})]}),(0,t.jsxs)("div",{className:"flex max-h-96 flex-col gap-0.5 overflow-y-auto px-2.5 pb-2 pt-1",children:[(0,t.jsx)(c2,{sensors:C,collisionDetection:x3,onDragEnd:ne,children:(0,t.jsx)(o2,{items:T.map(Z=>Z.id),strategy:v3,children:T.map(Z=>(0,t.jsx)(H0t,{company:Z,isEditing:i,isSelected:Z.id===c?.id,onSelect:U},Z.id))})}),T.length===0?u?(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)(us,{disabled:!0,children:"Couldn't load companies"}),(0,t.jsxs)(us,{onSelect:r(Z=>{Z.preventDefault(),h()},"onSelect"),children:[(0,t.jsx)(Ii,{className:"h-4 w-4 mr-2"}),"Try again"]})]}):(0,t.jsx)(us,{disabled:!0,children:"No companies"}):null]}),(0,t.jsxs)("div",{className:"flex flex-col gap-0.5 border-t border-border px-2.5 pb-2.5 pt-2",children:[!F&&(0,t.jsxs)(us,{onClick:V,className:gD,disabled:i,children:[(0,t.jsx)("span",{className:"flex size-5 shrink-0 items-center justify-center text-muted-foreground",children:(0,t.jsx)(bn,{className:"size-4"})}),(0,t.jsx)("span",{className:"min-w-0 flex-1 truncate",children:"Create organization"})]}),M?(0,t.jsx)(us,{asChild:!0,disabled:i,className:gD,children:(0,t.jsxs)(We,{to:"/company/settings/invites",onClick:r(Z=>{if(i){Z.preventDefault();return}K()},"onClick"),children:[(0,t.jsx)("span",{className:"flex size-5 shrink-0 items-center justify-center text-muted-foreground",children:(0,t.jsx)(hh,{className:"size-4"})}),(0,t.jsx)("span",{className:"min-w-0 flex-1 truncate",children:L?`Invite people to ${L}`:"Invite people"})]})}):null,R?.session?(0,t.jsxs)(us,{className:gD,onClick:r(()=>q.mutate(),"onClick"),disabled:i||q.isPending,children:[(0,t.jsx)("span",{className:"flex size-5 shrink-0 items-center justify-center text-muted-foreground",children:(0,t.jsx)(rp,{className:"size-4"})}),(0,t.jsx)("span",{className:"min-w-0 flex-1 truncate",children:q.isPending?"Signing out...":"Sign out"})]}):null]})]})]})}r(G0t,"BuiltinCompanyMenu");function Oae(){const{openNewIssue:e}=al(),[s,n]=(0,m.useState)(!0),[a,i]=(0,m.useState)(!0),{selectedCompanyId:o,selectedCompany:l}=fs(),{collapsed:c,peeking:d}=Ua(),u=c&&!d,h=QL(o),{data:p,isFetched:f}=te({queryKey:D.instance.experimentalSettings,queryFn:r(()=>jr.getExperimental(),"queryFn")}),x=D.liveRuns(o),g=jo({companyId:o,resourceKey:"live-runs",queryKey:x,enabled:!!o,refetchInterval:!1,leaderOnly:!0}),{data:v,dataUpdatedAt:y}=te({queryKey:x,queryFn:r(()=>ea.liveRunsForCompany(o),"queryFn"),enabled:g.enabled,refetchInterval:g.refetchInterval});wo(g,v,y);const k=v?.length??0,w=p?.enableIsolatedWorkspaces===!0,N=p?.enableApps===!0,S=p?.enablePipelines===!0,C=p?.enableStatusCards===!0,_=!f,R=p?.enableGoalsSidebarLink===!0,I=p?.enableDecisions===!0,{data:T}=te({queryKey:D.attention(o),queryFn:r(()=>b2.list(o),"queryFn"),enabled:!!o&&I,refetchInterval:6e4}),E=Yke(T),P=p?.enableCases===!0,O=!0,M=p?.enableConferenceRoomChat===!0,Q={companyId:o,companyPrefix:l?.issuePrefix??null};return(0,t.jsxs)("aside",{className:"w-full h-full min-h-0 border-r border-border bg-background flex flex-col",children:[(0,t.jsx)("div",{className:"flex items-center gap-1 px-3 h-12 shrink-0",children:(0,t.jsx)(V0t,{})}),(0,t.jsxs)("nav",{className:"flex-1 min-h-0 overflow-y-auto scrollbar-auto-hide flex flex-col gap-4 pointer-coarse:gap-3 px-3 py-2",children:[(0,t.jsxs)("div",{className:"flex flex-col gap-0.5",children:[(()=>{const L=(0,t.jsxs)("button",{onClick:r(()=>e(),"onClick"),"data-slot":"icon-button","aria-label":u?"New Task":void 0,className:"flex items-center gap-2.5 mx-2 rounded-lg px-2 py-1.5 pointer-coarse:py-1 text-(length:--text-compact) font-medium text-foreground/80 hover:bg-accent/50 hover:text-foreground transition-colors",children:[(0,t.jsx)(V_,{className:"h-4 w-4 shrink-0"}),(0,t.jsx)("span",{className:u?zj:"truncate",children:"New Task"})]});return u?(0,t.jsxs)(Fn,{children:[(0,t.jsx)(Bn,{asChild:!0,children:L}),(0,t.jsx)(On,{side:"right",children:"New Task"})]}):L})(),(0,t.jsx)(Ya,{to:"/search",label:"Search",icon:Yr}),(0,t.jsx)(Ya,{to:"/dashboard",label:"Dashboard",icon:Dx,liveCount:k}),(0,t.jsx)(Ya,{to:"/inbox",label:"Inbox",icon:Od,badge:h.inbox,badgeLabel:"unread",badgeTone:h.failedRuns>0?"danger":"default",alert:h.failedRuns>0}),I?(0,t.jsx)(Ya,{to:"/decisions",label:"Decisions",icon:Hj,badge:E,badgeLabel:"decisions"}):null,C?(0,t.jsx)(Ya,{to:"/status",label:"Status",icon:f2,textBadge:"beta"}):null,M?(0,t.jsx)(Ya,{to:"/board-chat",label:"Conference Room",icon:uwe}):null]}),(0,t.jsxs)($x,{label:"Work",collapsible:{open:s,onOpenChange:n},children:[(0,t.jsx)(Ya,{to:"/issues",label:"Tasks",icon:nm}),P?(0,t.jsx)(Ya,{to:"/cases",label:"Cases",icon:Vl,textBadge:"beta"}):null,(0,t.jsx)(Ya,{to:"/routines",label:"Routines",icon:lm}),S?(0,t.jsx)(Ya,{to:"/pipelines",label:"Pipelines",icon:Xi}):null,R?(0,t.jsx)(Ya,{to:"/goals",label:"Goals",icon:H0}):_?(0,t.jsx)("div",{"data-testid":"sidebar-goals-placeholder",className:"h-8 pointer-coarse:h-7","aria-hidden":"true"}):null,(0,t.jsx)(Ya,{to:"/artifacts",label:"Artifacts",icon:t0}),(0,t.jsx)(Ya,{to:"/skills",label:"Skills",icon:Ac}),w?(0,t.jsx)(Ya,{to:"/workspaces",label:"Workspaces",icon:Xi}):null,(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)(Ya,{to:"/projects",label:"Projects",icon:nl}),(0,t.jsx)(U0t,{})]}),(0,t.jsx)(X0,{errorBehavior:"hidden",slotTypes:["sidebar"],context:Q,className:"flex flex-col gap-0.5",itemClassName:"text-(length:--text-compact) font-medium",missingBehavior:"placeholder"}),(0,t.jsx)(y2,{errorBehavior:"hidden",placementZones:["sidebar"],context:Q,className:"flex flex-col gap-0.5",itemClassName:"text-(length:--text-compact) font-medium"})]}),null,(0,t.jsx)(z0t,{streamlined:O}),(0,t.jsxs)($x,{label:"Company",collapsible:{open:a,onOpenChange:i},children:[(0,t.jsx)(Ya,{to:"/org",label:"Org",icon:Ub}),N?(0,t.jsx)(Ya,{to:"/apps",label:"Connectors",icon:OR}):null,(0,t.jsx)(Ya,{to:"/timeline",label:"Timeline",icon:ob}),(0,t.jsx)(Ya,{to:"/costs",label:"Costs",icon:B0}),(0,t.jsx)(Ya,{to:"/activity",label:"Activity",icon:mc}),(0,t.jsx)(Ya,{to:"/company/settings",label:"Settings",icon:Iu})]}),(0,t.jsx)(X0,{errorBehavior:"hidden",slotTypes:["sidebarPanel"],context:Q,className:"flex flex-col gap-3",itemClassName:"rounded-lg border border-border p-3",missingBehavior:"placeholder"})]})]})}r(Oae,"Sidebar");function Y0t(e){const s=e.manifestJson.environmentDrivers??[];return s.length===0?!1:s.every(n=>n.kind==="sandbox_provider")}r(Y0t,"isSandboxProviderOnly");function Z0t(){const{selectedCompany:e,selectedCompanyId:s}=fs(),{isMobile:n,setSidebarOpen:a}=Ua(),{hidden:i}=Eu(),{enabled:o}=Xj(),l=r(x=>!i.has(x),"showPage"),c=l("instance.plugins"),d=!!td(),{slots:u}=Bd({slotTypes:["companySettingsPage"],companyId:s,enabled:!!s}),{data:h}=te({queryKey:s?D.sidebarBadges(s):["sidebar-badges","__disabled__"],queryFn:r(async()=>{try{return await UW.get(s)}catch(x){if(x instanceof nn&&(x.status===401||x.status===403))return null;throw x}},"queryFn"),enabled:!!s,retry:!1,refetchInterval:15e3}),{data:p}=te({queryKey:D.plugins.all,queryFn:r(()=>El.list(),"queryFn"),enabled:c}),f=(p??[]).filter(x=>!Y0t(x));return(0,t.jsxs)("aside",{className:"w-full h-full min-h-0 border-r border-border bg-background flex flex-col",children:[(0,t.jsx)("div",{className:"flex flex-col gap-1 px-3 py-3 shrink-0",children:(0,t.jsxs)(We,{to:"/dashboard",onClick:r(()=>{n&&a(!1)},"onClick"),className:"flex items-center gap-1.5 rounded-md px-2 py-1 text-xs text-muted-foreground transition-colors hover:bg-accent/50 hover:text-foreground",children:[(0,t.jsx)(xm,{className:"h-3.5 w-3.5 shrink-0"}),(0,t.jsx)("span",{className:"truncate",children:e?.name??"Company"})]})}),(0,t.jsx)("nav",{className:"flex-1 min-h-0 overflow-y-auto scrollbar-auto-hide px-3 py-2",children:(0,t.jsxs)("div",{className:"flex flex-col gap-0.5",children:[(0,t.jsx)(Ya,{to:"/company/settings",label:"General",icon:gm,end:!0}),l("instance.profile")&&(0,t.jsx)(Ya,{to:"/company/settings/instance/profile",label:"Profile",icon:$L,end:!0}),l("company.members")&&(0,t.jsx)(Ya,{to:"/company/settings/members",label:"Members",icon:Wo,badge:h?.joinRequests??0,end:!0}),u.filter(x=>x.routePath).map(x=>(0,t.jsx)(Ya,{to:`/company/settings/${x.routePath}`,label:x.displayName,icon:Mx,end:!0},`${x.pluginKey}:${x.id}`)),l("company.invites")&&(0,t.jsx)(Ya,{to:"/company/settings/invites",label:"Invites",icon:SKe,end:!0}),l("company.secrets")&&(0,t.jsx)(Ya,{to:"/company/settings/secrets",label:"Secrets",icon:Si,end:!0}),l("instance.environments")&&(0,t.jsx)(Ya,{to:"/company/settings/instance/environments",label:"Environments",icon:xwe,end:!0}),o&&(0,t.jsx)(Ya,{to:"/company/settings/connections",label:"Connections",icon:Ml,end:!0}),l("instance.access")&&(0,t.jsx)(Ya,{to:"/company/settings/instance/access",label:"Access",icon:p3,end:!0}),l("instance.heartbeats")&&(0,t.jsx)(Ya,{to:"/company/settings/instance/heartbeats",label:"Heartbeats",icon:Au,end:!0}),l("company.export")&&(0,t.jsx)(Ya,{to:"/company/export",label:"Export",icon:Fi}),!d&&l("company.import")&&(0,t.jsx)(Ya,{to:"/company/import",label:"Import",icon:Kb,end:!0}),l("instance.experimental")&&(0,t.jsx)(Ya,{to:"/company/settings/instance/experimental",label:"Experimental",icon:rh}),c&&(0,t.jsx)(Ya,{to:"/company/settings/instance/plugins",label:"Plugins",icon:Mx}),c&&f.length>0?(0,t.jsx)("div",{className:"ml-4 mt-1 flex flex-col gap-0.5 border-l border-border/70 pl-3",children:f.map(x=>(0,t.jsx)(av,{to:`${C0}/plugins/${x.id}`,state:Tf,className:r(({isActive:g})=>["rounded-md px-2 py-1.5 text-xs transition-colors",g?"bg-accent text-foreground":"text-muted-foreground hover:bg-accent/50 hover:text-foreground"].join(" "),"className"),children:x.manifestJson.displayName??x.packageName},x.id))}):null,l("instance.adapters")&&(0,t.jsx)(Ya,{to:"/company/settings/instance/adapters",label:"Adapters",icon:Vm})]})})]})}r(Z0t,"CompanySettingsSidebar");function J0t(){const{pathname:e}=la(),{selectedCompany:s}=fs(),{isMobile:n,setSidebarOpen:a}=Ua(),i=TNe(),{enabled:o}=WL(),l=GW.filter(d=>!INe(d.key)||o);if(e.endsWith("/apps/chat/connect"))return(0,t.jsx)(ANe,{NavItem:Ya});const c=e.match(/\/apps\/chat\/([^/]+)(?:\/(?:settings|access|conversations|activity|approvals|audit)|\/reviews(?:\/[^/]+)?)?\/?$/);return c?(0,t.jsx)(WW,{endpointId:c[1],NavItem:Ya}):(0,t.jsxs)("aside",{className:"w-full h-full min-h-0 border-r border-border bg-background flex flex-col",children:[(0,t.jsxs)("div",{className:"flex flex-col gap-1 px-3 py-3 shrink-0",children:[(0,t.jsxs)(We,{to:"/dashboard",onClick:r(()=>{n&&a(!1)},"onClick"),className:"flex items-center gap-1.5 rounded-md px-2 py-1 text-xs text-muted-foreground transition-colors hover:bg-accent/50 hover:text-foreground",children:[(0,t.jsx)(xm,{className:"h-3.5 w-3.5 shrink-0"}),(0,t.jsx)("span",{className:"truncate",children:s?.name??"Company"})]}),(0,t.jsxs)("div",{className:"flex items-center gap-2 px-2 py-1",children:[(0,t.jsx)(ute,{className:"h-4 w-4 text-muted-foreground shrink-0"}),(0,t.jsx)("span",{className:"flex-1 truncate text-sm font-bold text-foreground",children:"Connectors"})]})]}),(0,t.jsxs)("nav",{className:"flex-1 min-h-0 overflow-y-auto scrollbar-auto-hide px-3 py-2",children:[(0,t.jsx)("div",{className:"px-3 pb-1 text-(length:--text-micro) font-semibold uppercase tracking-wide text-muted-foreground",children:"Connectors"}),(0,t.jsxs)("div",{className:"flex flex-col gap-0.5",children:[(0,t.jsx)(Ya,{to:"/apps",label:"Browse",icon:G_,end:!0}),(0,t.jsx)(Ya,{to:"/apps/review",label:"Review",icon:x2,badge:i>0?i:void 0,badgeTone:"warning",badgeLabel:"waiting for your OK"})]}),(0,t.jsx)("div",{className:"px-3 pb-1 pt-4 text-(length:--text-micro) font-semibold uppercase tracking-wide text-muted-foreground",children:"Developer"}),(0,t.jsx)("p",{className:"px-3 pb-1.5 text-(length:--text-micro) leading-snug text-muted-foreground/70",children:"Advanced setup for developers. Most teams never open this."}),(0,t.jsxs)("div",{className:"flex flex-col gap-0.5",children:[(0,t.jsx)(Ya,{to:"/apps/connections",label:"Connections",icon:ute,end:!0}),l.map(d=>(0,t.jsx)(Ya,{to:Sb(d.key),label:d.label,icon:d.icon,end:!0},d.key))]})]})]})}r(J0t,"AppsSidebar");function Bae(e){const{selectedCompanyId:s}=fs(),{isMobile:n,setSidebarOpen:a}=Ua(),i=te({queryKey:D.tools.connection(e.kind==="connection"?e.connectionId:"__none__"),queryFn:r(()=>ts.getConnection(e.kind==="connection"?e.connectionId:""),"queryFn"),enabled:e.kind==="connection"&&!!e.connectionId}),o=te({queryKey:D.tools.applications(s??"__none__"),queryFn:r(()=>ts.listApplications(s),"queryFn"),enabled:e.kind==="application"&&!!s}),l=te({queryKey:D.tools.connections(s??"__none__"),queryFn:r(()=>ts.listConnections(s),"queryFn"),enabled:e.kind==="application"&&!!s}),c=te({queryKey:D.apps.gallery(s??"__none__"),queryFn:r(()=>ts.listGallery(s),"queryFn"),enabled:!!s}),d=te({queryKey:D.apps.attention(s??"__none__"),queryFn:r(()=>ts.listAppsAttention(s),"queryFn"),enabled:!!s,refetchInterval:3e4}),u=i.data,h=e.kind==="application"?(o.data?.applications??[]).find(k=>k.id===e.applicationId):null,p=tpt(e.kind==="application"?(l.data?.connections??[]).filter(k=>k.applicationId===e.applicationId):[]),f=u?vf(u):h?.name??"App",x=ept(c.data?.apps??[],u,h??void 0),g=u?.id??p?.id??null,v=g?d.data?.apps.find(k=>k.connection.id===g):null,y=(v?.pendingActionRequestCount??0)+((v?.quarantinedCatalogEntryCount??0)>0?1:0);return(0,t.jsxs)("aside",{className:"flex h-full min-h-0 w-full flex-col border-r border-border bg-background",children:[(0,t.jsxs)("div",{className:"flex shrink-0 flex-col gap-3 px-3 py-3",children:[(0,t.jsxs)(We,{to:"/apps/connections",onClick:r(()=>{n&&a(!1)},"onClick"),className:"flex items-center gap-1.5 rounded-md px-2 py-1 text-xs text-muted-foreground transition-colors hover:bg-accent/50 hover:text-foreground",children:[(0,t.jsx)(xm,{className:"h-3.5 w-3.5 shrink-0"}),(0,t.jsx)("span",{className:"truncate",children:"All apps"})]}),(0,t.jsxs)("div",{className:"flex min-w-0 items-center gap-2 px-2 py-1",children:[(0,t.jsx)(Hi,{name:f,logoUrl:B3(x),size:28}),(0,t.jsx)("span",{className:"flex-1 truncate text-sm font-bold text-foreground",children:f})]})]}),(0,t.jsx)("nav",{className:"scrollbar-auto-hide min-h-0 flex-1 overflow-y-auto px-3 py-2",children:(0,t.jsx)("div",{className:"flex flex-col gap-0.5",children:HL.map(k=>(0,t.jsx)(Ya,{to:X0t(e,k.key),label:k.label,icon:k.icon,end:!0,badge:k.key==="review"&&y>0?y:void 0,badgeTone:"danger",badgeLabel:"needing review"},k.key))})})]})}r(Bae,"AppDetailSidebar");function X0t(e,s){return e.kind==="connection"?Qm(e.connectionId,s):s_(e.applicationId,s)}r(X0t,"tabHref");function ept(e,s,n){if(n?.applicationKey){const i=e.find(o=>kc(o)===n.applicationKey);if(i)return i}const a=(s?.name??n?.name)?.toLowerCase();return a?e.find(i=>Ox(i).toLowerCase()===a)??e.find(i=>kc(i)===a)??null:null}r(ept,"galleryEntryFor$1");function tpt(e){const s=e.filter(n=>n.status==="archived");return s.length===0?null:s.reduce((n,a)=>{const i=new Date(n.updatedAt??n.createdAt??0).getTime();return new Date(a.updatedAt??a.createdAt??0).getTime()>i?a:n})}r(tpt,"latestArchivedConnection$1");function bD({identifier:e}){return e?(0,t.jsx)("span",{className:"shrink-0 font-mono text-muted-foreground",children:e}):null}r(bD,"CrumbIdentifier");function spt({context:e}){const{slots:s}=Bd({slotTypes:["globalToolbarButton"],companyId:e.companyId}),{launchers:n}=QW({placementZones:["globalToolbarButton"],companyId:e.companyId,enabled:!!e.companyId});return(0,t.jsxs)("div",{className:"ml-auto flex shrink-0 items-center gap-1 pl-2 empty:hidden",children:[s.length>0?(0,t.jsx)(X0,{slotTypes:["globalToolbarButton"],context:e,className:"flex items-center gap-1"}):null,n.length>0?(0,t.jsx)(y2,{placementZones:["globalToolbarButton"],context:e,className:"flex items-center gap-1"}):null]})}r(spt,"GlobalToolbar");function npt(){const{breadcrumbs:e,mobileToolbar:s}=Vn(),{toggleSidebar:n,isMobile:a}=Ua(),{selectedCompanyId:i,selectedCompany:o}=fs(),l=(0,m.useMemo)(()=>({companyId:i??null,companyPrefix:o?.issuePrefix??null}),[i,o?.issuePrefix]),c=(0,t.jsx)(spt,{context:l});if(a&&s)return(0,t.jsx)("div",{className:"border-b border-border px-2 h-12 shrink-0 flex items-center",children:s});if(e.length===0)return(0,t.jsx)("div",{className:"border-b border-border px-4 md:px-6 h-12 shrink-0 flex items-center justify-end",children:c});const d=a&&(0,t.jsx)($,{variant:"ghost",size:"icon-sm",className:"mr-2 shrink-0",onClick:n,"aria-label":"Open sidebar",children:(0,t.jsx)(swe,{className:"h-5 w-5"})});return e.length===1?(0,t.jsxs)("div",{className:"border-b border-border px-4 md:px-6 h-12 shrink-0 flex items-center",children:[d,(0,t.jsx)("div",{className:"min-w-0 overflow-hidden flex-1",children:e[0].leading||e[0].identifier?(0,t.jsxs)("h1",{className:"flex items-center gap-1.5 text-sm font-semibold uppercase tracking-wider",children:[e[0].leading&&(0,t.jsx)("span",{className:"flex shrink-0 items-center",children:e[0].leading}),(0,t.jsx)(bD,{identifier:e[0].identifier}),(0,t.jsx)("span",{className:"truncate",children:e[0].label})]}):(0,t.jsx)("h1",{className:"text-sm font-semibold uppercase tracking-wider truncate",children:e[0].label})}),c]}):(0,t.jsxs)("div",{className:"border-b border-border px-4 md:px-6 h-12 shrink-0 flex items-center",children:[d,(0,t.jsx)("div",{className:"min-w-0 overflow-hidden flex-1",children:(0,t.jsx)(YW,{className:"min-w-0 overflow-hidden",children:(0,t.jsx)(ZW,{className:"flex-nowrap",children:e.map((u,h)=>{const p=h===e.length-1;return(0,t.jsxs)(m.Fragment,{children:[h>0&&(0,t.jsx)(GR,{}),(0,t.jsx)(n_,{className:p?"min-w-0":"shrink-0",children:p||!u.href?u.leading||u.identifier?(0,t.jsxs)(s5,{className:"flex min-w-0 items-center gap-1.5",children:[u.leading&&(0,t.jsx)("span",{className:"flex shrink-0 items-center",children:u.leading}),(0,t.jsx)(bD,{identifier:u.identifier}),(0,t.jsx)("span",{className:"truncate",children:u.label})]}):(0,t.jsx)(s5,{className:"truncate",children:u.label}):(0,t.jsx)(VR,{asChild:!0,children:u.leading||u.identifier?(0,t.jsxs)(We,{to:u.href,onClick:u.onClick,className:"flex items-center gap-1.5",children:[u.leading&&(0,t.jsx)("span",{className:"flex shrink-0 items-center",children:u.leading}),(0,t.jsx)(bD,{identifier:u.identifier}),(0,t.jsx)("span",{className:"truncate",children:u.label})]}):(0,t.jsx)(We,{to:u.href,onClick:u.onClick,children:u.label})})})]},h)})})})}),c]})}r(npt,"BreadcrumbBar");var OI=240,Jz=208,Xz=420,Fae=16;function ME(e){return Math.min(Xz,Math.max(Jz,e))}r(ME,"clampSidebarWidth");function zae(e){if(typeof window>"u")return OI;try{const s=window.localStorage.getItem(e);if(!s)return OI;const n=Number.parseInt(s,10);return Number.isFinite(n)?ME(n):OI}catch{return OI}}r(zae,"readStoredSidebarWidth");function qae(e,s){if(!(typeof window>"u"))try{window.localStorage.setItem(e,String(ME(s)))}catch{}}r(qae,"writeStoredSidebarWidth");function rpt({children:e,open:s,collapsed:n=!1,peeking:a=!1,resizable:i=!1,storageKey:o="paperclip.sidebar.width",className:l,onPanelMouseEnter:c,onPanelMouseLeave:d,onPanelFocusCapture:u,onPanelBlurCapture:h}){const[p,f]=(0,m.useState)(()=>zae(o)),[x,g]=(0,m.useState)(!1),v=(0,m.useRef)(p),y=(0,m.useRef)(null);(0,m.useEffect)(()=>{const M=zae(o);v.current=M,f(M)},[o]);const k=s?p:0,w=s?n?64:k:0,N=s?n&&!a?64:k:0,S=N>w,C=i&&s&&!n,_=(0,m.useMemo)(()=>({width:`${w}px`}),[w]),R=(0,m.useMemo)(()=>({width:`${N}px`}),[N]),I=(0,m.useCallback)(M=>{const Q=ME(M);v.current=Q,f(Q),qae(o,Q)},[o]),T=(0,m.useCallback)(M=>{C&&(M.preventDefault(),M.currentTarget.setPointerCapture(M.pointerId),y.current={startX:M.clientX,startWidth:v.current},g(!0))},[C]),E=(0,m.useCallback)(M=>{if(!y.current)return;const Q=ME(y.current.startWidth+M.clientX-y.current.startX);v.current=Q,f(Q)},[]),P=(0,m.useCallback)(()=>{y.current&&(y.current=null,g(!1),qae(o,v.current))},[o]),O=(0,m.useCallback)(M=>{C&&(M.key==="ArrowLeft"?(M.preventDefault(),I(p-Fae)):M.key==="ArrowRight"?(M.preventDefault(),I(p+Fae)):M.key==="Home"?(M.preventDefault(),I(Jz)):M.key==="End"&&(M.preventDefault(),I(Xz)))},[C,I,p]);return(0,t.jsx)("div",{className:W("relative h-full shrink-0",l),style:_,children:(0,t.jsxs)("div",{className:W("absolute inset-y-0 left-0 flex flex-col overflow-hidden",S?"z-30 border-r border-border bg-background shadow-lg":"z-0"),style:R,"data-sidebar-overlay":S?"":void 0,onMouseEnter:c,onMouseLeave:d,onFocusCapture:u,onBlurCapture:h,children:[e,C?(0,t.jsx)("div",{role:"separator","aria-label":"Resize sidebar","aria-orientation":"vertical","aria-valuemin":Jz,"aria-valuemax":Xz,"aria-valuenow":p,tabIndex:0,className:W("absolute inset-y-0 right-0 z-20 w-3 cursor-col-resize touch-none outline-none","before:absolute before:inset-y-0 before:left-1/2 before:w-px before:-translate-x-1/2 before:bg-transparent before:transition-colors","hover:before:bg-border focus-visible:before:bg-ring",x&&"before:bg-ring"),onPointerDown:T,onPointerMove:E,onPointerUp:P,onPointerCancel:P,onLostPointerCapture:P,onKeyDown:O}):null]})})}r(rpt,"SidebarShell");function apt({children:e,className:s}){return(0,t.jsx)("div",{"data-secondary-sidebar":"",className:W("h-full w-60 shrink-0 overflow-y-auto border-r border-border bg-background",s),children:(0,t.jsx)(P0t,{children:e})})}r(apt,"SecondarySidebar");var ipt="/company/settings/members?tab=invites",opt="https://docs.paperclip.ing/",lpt="https://paperclip.ing/feedback";function cpt(e){const s=e.trim().split(/\s+/).filter(Boolean);return s.length>=2?`${s[0]?.[0]??""}${s[s.length-1]?.[0]??""}`.toUpperCase():e.slice(0,2).toUpperCase()}r(cpt,"deriveInitials$1");function Uae({label:e,description:s,icon:n,onClick:a,href:i,external:o=!1,topLevel:l=!1}){const c="flex w-full items-start gap-3 rounded-xl px-3 py-3 text-left transition-colors hover:bg-accent/60",d=(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)("span",{className:"mt-0.5 rounded-lg border border-border bg-background/70 p-2 text-muted-foreground",children:(0,t.jsx)(n,{className:"size-4"})}),(0,t.jsxs)("span",{className:"min-w-0 flex-1",children:[(0,t.jsx)("span",{className:"block text-sm font-medium text-foreground",children:e}),(0,t.jsx)("span",{className:"block text-xs text-muted-foreground",children:s})]})]});return i?o?(0,t.jsx)("a",{href:i,target:"_blank",rel:"noreferrer",className:c,onClick:a,children:d}):l?(0,t.jsx)("a",{href:i,className:c,onClick:a,children:d}):(0,t.jsx)(We,{to:i,className:c,onClick:a,children:d}):(0,t.jsx)("button",{type:"button",className:c,onClick:a,children:d})}r(Uae,"MenuAction");function Kae({deploymentMode:e,open:s,onOpenChange:n}){const i=!!td(),{hidden:o,loaded:l}=Eu(),c=D5e(),d=$5e(!i),u=i?c:d?ipt:null,h=l&&u!==null&&!Kx(o,"company.members")&&!Kx(o,"company.invites"),[p,f]=(0,m.useState)(!1),{isMobile:x,setSidebarOpen:g,collapsed:v,peeking:y}=Ua(),k=v&&!y,w=s??p,N=O5e(w),S=n??f,{data:C}=te({queryKey:D.auth.session,queryFn:r(()=>Pa.getSession(),"queryFn"),retry:!1}),_=j2({onSignedOut:P}),R=C?.user.name?.trim()||"Board",I=C?.user.email?.trim()||(e==="authenticated"?"Signed in":"Local workspace board"),T=cpt(R),E=B5e(C?.user);function P(){S(!1),x&&g(!1)}r(P,"closeNavigationChrome");function O(){_.mutate()}return r(O,"handleSignOut"),(0,t.jsx)("div",{className:"border-t border-r border-border bg-background px-3 py-2",children:(0,t.jsxs)("div",{className:W("flex items-center gap-0.5",!k&&"px-2"),children:[(0,t.jsxs)(dr,{open:w,onOpenChange:S,children:[(0,t.jsx)(wr,{asChild:!0,children:(0,t.jsxs)("button",{type:"button",className:W("flex min-w-0 items-center gap-2.5 rounded-lg text-left text-(length:--text-compact) font-medium text-foreground/80 transition-colors hover:bg-accent/50 hover:text-foreground",k?"w-full px-3 py-2":"flex-1 px-2 py-1.5"),"aria-label":"Open account menu",children:[(0,t.jsxs)(bo,{size:"sm",children:[C?.user.image?(0,t.jsx)(Jc,{src:C.user.image,alt:R}):null,(0,t.jsx)(vo,{children:T})]}),(0,t.jsx)("span",{className:W("min-w-0 flex-1 truncate",k&&"block w-0 min-w-0 overflow-hidden whitespace-nowrap text-transparent select-none"),children:R})]})}),(0,t.jsxs)(nr,{side:"top",align:"start",sideOffset:10,className:"w-(--sz-277px) max-w-(--sz-calc-24) overflow-hidden rounded-t-2xl rounded-b-none border-border p-0 shadow-2xl",children:[(0,t.jsx)("div",{className:"h-24 bg-(image:--gradient-extract-25)"}),(0,t.jsxs)("div",{className:"-mt-8 px-4 pb-4",children:[(0,t.jsxs)("div",{className:"relative flex items-start gap-3",children:[(0,t.jsx)(We,{to:E,"aria-label":"View profile",onClick:P,className:"absolute inset-0 rounded-xl transition-colors hover:bg-accent/60 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"}),(0,t.jsx)("div",{className:"pointer-events-none relative rounded-2xl border-4 border-popover bg-popover p-0.5 shadow-sm",children:(0,t.jsxs)(bo,{size:"lg",children:[C?.user.image?(0,t.jsx)(Jc,{src:C.user.image,alt:R}):null,(0,t.jsx)(vo,{children:T})]})}),(0,t.jsxs)("div",{className:"pointer-events-none relative min-w-0 flex-1 pt-1",children:[(0,t.jsx)("h2",{className:"truncate text-base font-semibold text-foreground",children:R}),(0,t.jsx)("p",{className:"truncate text-sm text-muted-foreground",children:I}),N?(0,t.jsxs)("a",{className:"pointer-events-auto block truncate font-mono text-(length:--text-micro) leading-(--profile-popover-meta-line-height) text-muted-foreground hover:underline focus-visible:underline",href:`https://github.com/paperclipai/paperclip/commit/${N}`,target:"_blank",rel:"noreferrer","aria-label":`View commit ${N} on GitHub`,title:N,children:["SHA ",N.slice(0,7)]}):null]})]}),(0,t.jsxs)("div",{className:"mt-4 space-y-1",children:[h&&u?(0,t.jsx)(Uae,{label:"Invite",description:"Invite people to your organization.",icon:hh,href:u,topLevel:i,onClick:P}):null,(0,t.jsx)(Uae,{label:"Documentation",description:"Open Paperclip docs in a new tab.",icon:p2,href:opt,external:!0,onClick:r(()=>S(!1),"onClick")}),(0,t.jsx)(Ek,{variant:"menu-action",onAfterToggle:r(()=>S(!1),"onAfterToggle")}),(0,t.jsx)(q5e,{variant:"menu-action",onAfterAction:r(()=>S(!1),"onAfterAction")}),e==="authenticated"?(0,t.jsxs)("button",{type:"button",className:W("flex w-full items-start gap-3 rounded-xl px-3 py-3 text-left transition-colors hover:bg-destructive/10",_.isPending&&"cursor-not-allowed opacity-60"),onClick:O,disabled:_.isPending,children:[(0,t.jsx)("span",{className:"mt-0.5 rounded-lg border border-border bg-background/70 p-2 text-muted-foreground",children:(0,t.jsx)(rp,{className:"size-4"})}),(0,t.jsxs)("span",{className:"min-w-0 flex-1",children:[(0,t.jsx)("span",{className:"block text-sm font-medium text-foreground",children:_.isPending?"Signing out...":"Sign out"}),(0,t.jsx)("span",{className:"block text-xs text-muted-foreground",children:"End this browser session."})]})]}):null,(0,t.jsx)(U5e,{})]})]})]})]}),!k&&!i?(0,t.jsxs)(Fn,{children:[(0,t.jsx)(Bn,{asChild:!0,children:(0,t.jsx)("a",{href:lpt,target:"_blank",rel:"noreferrer","aria-label":"Share feedback",className:"flex size-8 shrink-0 items-center justify-center rounded-lg text-muted-foreground/50 transition-colors hover:bg-accent/50 hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring",children:(0,t.jsx)(ug,{className:"h-4 w-4","aria-hidden":"true"})})}),(0,t.jsx)(On,{side:"top",children:"Share feedback"})]}):null]})})}r(Kae,"SidebarAccountMenu");function dpt(e,s){return s3e(e,s)[0]?.toLowerCase()??null}r(dpt,"getCompanyRouteSegment");function s3e(e,s){if(!s)return[];const n=e.split("/").filter(Boolean);return n.length<2?[]:n[0]?.toUpperCase()!==s.toUpperCase()?[]:n.slice(1)}r(s3e,"getCompanyPathSegments");var upt=new Set(["browse","connections","connect","chat","review","attention","gateways","advanced","app"]);function mpt(e,s){const n=e.split("/").filter(Boolean);return n[0]?.toLowerCase()==="skills"?!0:s?n[0]?.toUpperCase()===s.toUpperCase()&&n[1]?.toLowerCase()==="skills":!1}r(mpt,"isSkillsStoreRoute");function hpt(){const{sidebarOpen:e,setSidebarOpen:s,toggleSidebar:n,collapsed:a,peeking:i,setPeeking:o,isMobile:l,setForceCollapsed:c}=Ua(),{openNewIssue:d,openOnboarding:u}=al(),{togglePanelVisible:h}=Ef(),p=jd()?.pushToast??null,{companies:f,loading:x,selectedCompany:g,selectedCompanyId:v,selectionSource:y,setSelectedCompanyId:k}=fs(),{companyPrefix:w,pluginRoutePath:N}=xa(),S=Gn(),C=la(),_=vL(),R=NNe(C.pathname,w).isTaskDetail,I=["/company/settings","/company/export","/company/import"].some(bt=>C.pathname.includes(bt)),T=s3e(C.pathname,w),E=T[0]?.toLowerCase()==="tools",P=T[0]?.toLowerCase()==="apps",O=P&&T[1]&&!upt.has(T[1].toLowerCase())?T[1]:null,M=P&&T[1]?.toLowerCase()==="app"&&T[2]?T[2]:null,Q=mpt(C.pathname,w),L=(0,m.useRef)(!1),F=(0,m.useRef)(null),q=(0,m.useRef)(null),z=(0,m.useRef)(new hke),K=(0,m.useRef)(C.key),U=G5e(l&&!R,C.pathname),[V,ne]=(0,m.useState)(!1),Z=(0,m.useMemo)(()=>{if(!w)return null;const bt=w.toUpperCase();return f.find(et=>et.issuePrefix.toUpperCase()===bt)??null},[f,w]),ie=!!w&&!x&&f.length>0&&!Z,J=(0,m.useMemo)(()=>N?.toLowerCase()??dpt(C.pathname,w),[w,C.pathname,N]),ae=Z?.id??null,oe=Z?.issuePrefix??null,{slots:G}=Bd({slotTypes:["page","routeSidebar"],companyId:ae,enabled:!!(ae&&J)}),X=(0,m.useMemo)(()=>$W(G,J),[J,G]),Y=(0,m.useMemo)(()=>({companyId:ae,companyPrefix:oe}),[ae,oe]),re=I?(0,t.jsx)(Z0t,{}):O?(0,t.jsx)(Bae,{kind:"connection",connectionId:O}):M?(0,t.jsx)(Bae,{kind:"application",applicationId:M}):P||E?(0,t.jsx)(J0t,{}):X?(0,t.jsx)(vm,{slot:X,context:Y,className:"h-full w-full",missingBehavior:"placeholder"}):null,se=re!=null,{data:ce}=te({queryKey:D.health,queryFn:r(()=>Lu.get(),"queryFn"),retry:!1,refetchInterval:r(bt=>bt.state.data?.devServer?.enabled?2e3:!1,"refetchInterval"),refetchIntervalInBackground:!1}),pe=se||Q;(0,m.useLayoutEffect)(()=>(c(pe),()=>c(!1)),[pe,c]),(0,m.useEffect)(()=>{x||L.current||ce?.deploymentMode!=="authenticated"&&(ce?.cloud||f.length===0&&(L.current=!0,u()))},[f,x,u,ce?.cloud,ce?.deploymentMode]),(0,m.useEffect)(()=>{if(!w||x||f.length===0)return;if(!Z){const et=(v?f.find(qe=>qe.id===v):null)??f[0]??null;et&&v!==et.id&&k(et.id,{source:"route_sync"});return}if(w!==Z.issuePrefix){const et=C.pathname.replace(/^\/[^/]+/,"");S(`/${Z.issuePrefix}${et}${C.search}`,{replace:!0});return}const bt=Y5e({matchedCompany:Z,selectedCompanyId:v,companies:f});if(bt){p?.({title:`${Z.name} is archived`,body:`Switched to ${bt.name}.`,tone:"info",dedupeKey:`archived-company-bounce:${Z.id}`}),k(bt.id,{source:"route_sync"}),S(`/${bt.issuePrefix}/dashboard`,{replace:!0});return}Z5e({selectionSource:y,selectedCompanyId:v,routeCompanyId:Z.id})&&k(Z.id,{source:"route_sync"})},[w,f,x,Z,C.pathname,C.search,S,p,y,v,k]);const fe=h,ve=(0,m.useCallback)(()=>{document.dispatchEvent(new KeyboardEvent("keydown",{key:"k",metaKey:!0,bubbles:!0,cancelable:!0}))},[]),Ie=(0,m.useRef)(null),de=(0,m.useRef)(!1),xe=(0,m.useRef)(!1),le=(0,m.useCallback)(()=>{Ie.current!==null&&(window.clearTimeout(Ie.current),Ie.current=null)},[]),Re=(0,m.useCallback)(()=>{le(),Ie.current=window.setTimeout(()=>o(!0),50)},[le,o]),Le=(0,m.useCallback)(()=>{le(),o(!0)},[le,o]),je=(0,m.useCallback)(()=>{le(),Ie.current=window.setTimeout(()=>o(!1),120)},[le,o]),_e=(0,m.useCallback)(()=>{de.current=!0,a&&!xe.current&&Re()},[a,Re]),Ze=(0,m.useCallback)(()=>{de.current=!1,xe.current=!1,je()},[je]),ue=(0,m.useCallback)(()=>{xe.current||Le()},[Le]),Fe=(0,m.useCallback)(()=>{de.current||je()},[je]);(0,m.useEffect)(()=>le,[le]);const mt=(0,m.useRef)(a);return(0,m.useEffect)(()=>{a!==mt.current&&(a?(le(),o(!1),xe.current=de.current):xe.current=!1,mt.current=a)},[a,le,o]),(0,m.useEffect)(()=>{if(!i)return;const bt=r(et=>{et.key==="Escape"&&(le(),o(!1))},"onKeyDown");return window.addEventListener("keydown",bt),()=>window.removeEventListener("keydown",bt)},[i,le,o]),V5e(),K5e({onNewIssue:r(()=>d(),"onNewIssue"),onSearch:ve,onToggleSidebar:n,onTogglePanel:fe,onShowShortcuts:r(()=>ne(!0),"onShowShortcuts"),onGoToInbox:r(()=>S("/inbox"),"onGoToInbox")}),(0,m.useEffect)(()=>{if(!l)return;const bt=30,et=50,qe=75;let it=0,_t=0;const $t=r(at=>{const Me=at.touches[0];it=Me.clientX,_t=Me.clientY},"onTouchStart"),Ot=r(at=>{const Me=at.changedTouches[0],De=Me.clientX-it;if(!(Math.abs(Me.clientY-_t)>qe)){if(!e&&it<bt&&De>et){s(!0);return}e&&De<-50&&s(!1)}},"onTouchEnd");return document.addEventListener("touchstart",$t,{passive:!0}),document.addEventListener("touchend",Ot,{passive:!0}),()=>{document.removeEventListener("touchstart",$t),document.removeEventListener("touchend",Ot)}},[l,e,s]),(0,m.useEffect)(()=>{const bt=document.body.style.overflow;return document.body.style.overflow=l?"visible":"clip",()=>{document.body.style.overflow=bt}},[l]),(0,m.useEffect)(()=>{if(!l)return X5e()},[l]),(0,m.useEffect)(()=>{if(typeof document>"u")return;const bt=q.current;return J5e(bt)},[C.pathname]),(0,m.useEffect)(()=>{const bt=q.current;if(!bt)return;const et=r(()=>{z.current.remember(K.current,bt.scrollTop)},"recordScroll");return bt.addEventListener("scroll",et,{passive:!0}),()=>bt.removeEventListener("scroll",et)},[]),(0,m.useLayoutEffect)(()=>{const bt=q.current,et=mke({previousPathname:F.current,pathname:C.pathname,navigationType:_,state:C.state});F.current=C.pathname;const qe=_==="POP",it=qe?z.current.recall(C.key):0;if(K.current=C.key,qe){FR(bt,it);const _t=requestAnimationFrame(()=>FR(bt,it));return()=>cancelAnimationFrame(_t)}et&&pke(bt)},[C.key,C.pathname,C.state,_]),(0,t.jsx)(dke,{children:(0,t.jsxs)("div",{className:W("bg-background text-foreground pt-(--sz-safe-top)",l?"min-h-dvh overflow-x-clip":"flex h-dvh flex-col overflow-clip"),children:[(0,t.jsx)("a",{href:"#main-content",className:"sr-only focus:not-sr-only focus:fixed focus:left-3 focus:top-3 focus:z-(--z-200) focus:rounded-md focus:bg-background focus:px-3 focus:py-2 focus:text-sm focus:font-medium focus:shadow-lg focus:outline-none focus-visible:ring-2 focus-visible:ring-ring",children:"Skip to Main Content"}),(0,t.jsx)(N5e,{}),(0,t.jsx)(S5e,{devServer:ce?.devServer}),(0,t.jsxs)("div",{className:W("min-h-0 flex-1",l?"w-full":"flex overflow-clip"),children:[l&&e&&(0,t.jsx)("button",{type:"button",className:"fixed inset-0 z-40 bg-black/50",onClick:r(()=>s(!1),"onClick"),"aria-label":"Close sidebar"}),l?(0,t.jsxs)("div",{className:W("fixed inset-y-0 left-0 z-50 flex flex-col overflow-hidden pt-(--sz-safe-top) transition-transform duration-100 ease-out",e?"translate-x-0":"-translate-x-full"),children:[(0,t.jsx)("div",{className:"flex flex-1 min-h-0 overflow-hidden",children:(0,t.jsx)("div",{className:"w-60 shrink-0 overflow-hidden",children:se?re:(0,t.jsx)(Oae,{})})}),(0,t.jsx)(Kae,{deploymentMode:ce?.deploymentMode})]}):(0,t.jsxs)(rpt,{open:e,collapsed:a,peeking:i,resizable:!0,onPanelMouseEnter:_e,onPanelMouseLeave:Ze,onPanelFocusCapture:a?ue:void 0,onPanelBlurCapture:a?Fe:void 0,children:[(0,t.jsx)("div",{className:"flex flex-1 min-h-0",children:(0,t.jsx)(Oae,{})}),(0,t.jsx)(Kae,{deploymentMode:ce?.deploymentMode})]}),!l&&se?(0,t.jsx)(apt,{children:re}):null,(0,t.jsxs)("div",{className:W("flex min-w-0 flex-col",l?"w-full":"h-full flex-1"),children:[(0,t.jsxs)("div",{className:W(l&&"sticky top-0 z-20 bg-background/95 backdrop-blur supports-[backdrop-filter]:bg-background/85"),children:[(0,t.jsx)(Wz,{mobile:l,onNavigateHome:r(()=>S("/dashboard"),"onNavigateHome")}),(0,t.jsx)(npt,{}),l&&I?(0,t.jsx)("div",{className:"border-b border-border px-4 pb-3",children:(0,t.jsx)(_Ne,{})}):null]}),(0,t.jsxs)("div",{className:W(l?"block":"flex flex-1 min-h-0"),children:[(0,t.jsx)("main",{id:"main-content",ref:q,tabIndex:-1,style:l?{"--tc-composer-bottom":"var(--sz-calc-14)"}:void 0,className:W("flex-1 p-4 outline-none md:p-6",l?"overflow-visible pb-(--sz-calc-14)":"overflow-auto [scrollbar-gutter:stable]"),children:ie?(0,t.jsx)(mm,{scope:"invalid_company_prefix",requestedPrefix:w??g?.issuePrefix}):(0,t.jsx)(A5e,{children:(0,t.jsx)(rv,{})})}),(0,t.jsx)(BNe,{})]})]})]}),l&&(0,t.jsx)(k5e,{visible:U}),(0,t.jsx)(FNe,{}),(0,t.jsx)(N2e,{}),(0,t.jsx)(m5e,{}),(0,t.jsx)(f5e,{}),(0,t.jsx)(v5e,{}),(0,t.jsx)(y5e,{open:V,onOpenChange:ne}),(0,t.jsx)(j5e,{}),(0,t.jsx)(w5e,{localTrusted:ce?.deploymentMode==="local_trusted"})]})})}r(hpt,"Layout");var Qae=null;function ppt(){return Qae??=new e2,Qae}r(ppt,"getDetachedClient");function fpt(){const e=(0,m.useContext)(c3),{data:s,isFetched:n}=te({queryKey:D.instance.experimentalSettings,queryFn:r(()=>jr.getExperimental(),"queryFn"),enabled:e!=null},e??ppt());return e?{enabled:s?.enableConferenceRoomChat===!0,loaded:n}:{enabled:!1,loaded:!0}}r(fpt,"useConferenceRoomChatEnabled");function xpt(){const{enabled:e,loaded:s}=fpt();return s?e?(0,t.jsx)(rv,{}):(0,t.jsx)(In,{to:"/dashboard",replace:!0}):null}r(xpt,"ConferenceRoomChatGate");var gpt=["session-start","human-message","agent-message","thinking","responding","responding-burst","tool-call","diff","working","running","completed","activity-phases","awaiting-approval","plan-todo","interrupted","refused","truncated","live-token-cost"],bpt={"session-start":{id:"session-start",label:"Session start",tier:"live",surface:"thread",protocol:'acpx.session → TranscriptEntry kind:"init"'},"human-message":{id:"human-message",label:"Human message",tier:"live",surface:"thread",protocol:'IssueComment authorType:"user"'},"agent-message":{id:"agent-message",label:"Final response",tier:"live",surface:"thread",protocol:'PRP item.delta kind:"agentMessage" channel:"final"'},thinking:{id:"thinking",label:"Thinking",tier:"live",surface:"thread",protocol:"text_delta stream:thought (ACP agent_thought_chunk)"},responding:{id:"responding",label:"Progress update (streaming)",tier:"live",surface:"thread",protocol:'PRP item.delta kind:"agentMessage" channel:"progress"'},"responding-burst":{id:"responding-burst",label:"Progress update burst",tier:"live",surface:"thread",protocol:"text_delta stream:output ×N, tool calls between (PAP-368 dwell)"},"tool-call":{id:"tool-call",label:"Tool call",tier:"live",surface:"thread",protocol:"acpx.tool_call (ACP tool_call / tool_call_update)"},diff:{id:"diff",label:"Diff",tier:"live",surface:"thread",protocol:'ToolCallContent type:"diff" → TranscriptEntry kind:"diff"'},working:{id:"working",label:"Working",tier:"live",surface:"thread",protocol:"heartbeat.run.progress + acpx.status"},running:{id:"running",label:"Running",tier:"live",surface:"thread",protocol:'message.status.type === "running"'},completed:{id:"completed",label:"Completed (collapsed)",tier:"live",surface:"thread",protocol:"acpx.result (StopReason in subtype)"},"activity-phases":{id:"activity-phases",label:"Long-run activity phases",tier:"live",surface:"thread",protocol:"assistant boundaries + chronological tool calls"},"awaiting-approval":{id:"awaiting-approval",label:"Awaiting approval",tier:"tier-b",surface:"thread",protocol:"ACP RequestPermissionRequest + PermissionOptionKind"},"plan-todo":{id:"plan-todo",label:"Plan / todo",tier:"tier-b",surface:"plan",protocol:"ACP Plan { entries: PlanEntry[] }, PlanEntryStatus"},interrupted:{id:"interrupted",label:"Interrupted",tier:"tier-b",surface:"thread",protocol:'AcpRuntimeTurnResult.status:"cancelled" / StopReason "cancelled"'},refused:{id:"refused",label:"Refused",tier:"tier-b",surface:"thread",protocol:'StopReason "refusal"'},truncated:{id:"truncated",label:"Truncated",tier:"tier-b",surface:"thread",protocol:'StopReason "max_tokens" | "max_turn_requests"'},"live-token-cost":{id:"live-token-cost",label:"Live token / cost",tier:"tier-b",surface:"thread",protocol:"ACP UsageUpdate { used, size, cost }"}},Sbs=gpt.map(e=>bpt[e]);function n3e({browser:e,label:s="Browser",onOpen:n}){const a=e.status==="closed"||e.status==="failed";return(0,t.jsxs)("div",{className:"flex flex-wrap items-center gap-2 py-1 text-sm","aria-label":`${s} session`,children:[(0,t.jsx)(wm,{className:"size-4 shrink-0 text-muted-foreground","aria-hidden":!0}),(0,t.jsx)("span",{children:s}),(0,t.jsxs)("span",{className:"text-muted-foreground",children:["· ",e.status]}),n&&(0,t.jsx)($,{variant:"ghost",size:"sm",onClick:r(()=>n(e.id),"onClick"),children:a?"View session":"Open browser"})]})}r(n3e,"TaskBrowserActivity");function r3e({item:e}){return(0,t.jsx)("article",{className:"rounded-lg border border-border bg-card p-3","aria-label":`Project created: ${e.name}`,children:(0,t.jsxs)("div",{className:"flex items-start gap-3",children:[(0,t.jsx)(gKe,{className:"mt-0.5 size-4 shrink-0 text-muted-foreground","aria-hidden":!0}),(0,t.jsxs)("div",{className:"min-w-0 flex-1 space-y-1",children:[(0,t.jsx)("p",{className:"text-xs text-muted-foreground",children:"Project created"}),(0,t.jsx)(We,{to:`/projects/${e.projectId}`,className:"break-words text-sm font-medium hover:underline focus-visible:underline",children:e.name}),e.description&&(0,t.jsx)("p",{className:"line-clamp-3 text-sm text-muted-foreground",children:e.description}),e.repositories.length>0&&(0,t.jsx)("ul",{className:"space-y-1 pt-1",children:e.repositories.map(s=>(0,t.jsxs)("li",{className:"flex min-w-0 items-center gap-2 text-xs text-muted-foreground",children:[(0,t.jsx)(Xi,{className:"size-3 shrink-0","aria-hidden":!0}),(0,t.jsx)("a",{className:"truncate hover:underline focus-visible:underline",href:s.url,target:"_blank",rel:"noreferrer",children:s.name})]},s.id))})]})]})})}r(r3e,"TaskChatProjectCreatedCard");function vpt({item:e,onOpen:s}){return(0,t.jsx)("article",{className:"rounded-lg border border-border bg-card p-3","aria-label":`Skill created: ${e.name}`,children:(0,t.jsxs)("button",{type:"button",className:"flex w-full items-start gap-3 text-left",onClick:r(()=>s?.(e.skillId,e.name),"onClick"),children:[(0,t.jsx)(pf,{className:"mt-0.5 size-4 shrink-0 text-muted-foreground","aria-hidden":!0}),(0,t.jsxs)("span",{className:"min-w-0 flex-1 space-y-1",children:[(0,t.jsx)("span",{className:"block text-xs text-muted-foreground",children:"Skill created"}),(0,t.jsx)("span",{className:"block break-words text-sm font-medium hover:underline focus-visible:underline",children:e.name}),e.description?(0,t.jsx)("span",{className:"block line-clamp-3 text-sm text-muted-foreground",children:e.description}):null]})]})})}r(vpt,"TaskChatSkillCreatedCard");function ypt(e){return(0,t.jsxs)("svg",{viewBox:"0 0 180 180",fill:"none",stroke:"currentColor",strokeWidth:14,strokeLinecap:"round",xmlns:"http://www.w3.org/2000/svg",...e,children:[(0,t.jsx)("path",{d:"M18 84.8528L85.8822 16.9706C95.2548 7.59798 110.451 7.59798 119.823 16.9706C129.196 26.3431 129.196 41.5391 119.823 50.9117L68.5581 102.177"}),(0,t.jsx)("path",{d:"M69.2652 101.47L119.823 50.9117C129.196 41.5391 144.392 41.5391 153.765 50.9117L154.118 51.2652C163.491 60.6378 163.491 75.8338 154.118 85.2063L92.7248 146.6C89.6006 149.724 89.6006 154.789 92.7248 157.913L105.331 170.52"}),(0,t.jsx)("path",{d:"M102.853 33.9411L52.6482 84.1457C43.2756 93.5183 43.2756 108.714 52.6482 118.087C62.0208 127.459 77.2167 127.459 86.5893 118.087L136.794 67.8822"})]})}r(ypt,"McpIcon");var jpt=new Set(["tool","tool call","tool_call","acp_tool"]);function Su(e){const s=(e??"").trim().toLowerCase().replace(/\s*\((?:pending|in[_ -]?progress|completed|failed|cancelled|canceled)\)$/,"");return!s||jpt.has(s)}r(Su,"isGenericToolName");function MV(e){const s=e.match(/^mcp__(.+?)__(.+)$/i);if(s)return{namespace:s[1],name:s[2]};const n=e.match(/^mcp\.([^.]+)\.(.+)$/i);return n?{namespace:n[1],name:n[2]}:null}r(MV,"mcpToolIdentity");function PV(e){return e.replace(/([a-z0-9])([A-Z])/g,"$1 $2").replace(/([A-Z]+)([A-Z][a-z])/g,"$1 $2").replace(/[^A-Za-z0-9]+/g," ").trim().toLowerCase().split(/\s+/).filter(Boolean)}r(PV,"identifierWords");function a3e(e){if(e.length===0)return"";const s=e.map(n=>["api","id","lsp","mcp","pr","url"].includes(n)?n.toUpperCase():n).join(" ");return s.charAt(0).toUpperCase()+s.slice(1)}r(a3e,"sentenceCase");function Lk(e){const s=(e??"").trim();return Su(s)?"Unnamed tool":a3e(PV(MV(s)?.name??s))}r(Lk,"humanizeToolName");var Vd=r((e,s,n)=>({key:e,singular:s,plural:n}),"group"),wpt={bash:{action:"run"},terminal:{action:"run"},shell:{action:"run"},command:{action:"run"},run:{action:"run"},execute:{action:"run"},exec_command:{action:"run"},apply_patch:{action:"update",running:"Applying a patch",completed:"Applied a patch"},read:{action:"read",running:"Reading a file",completed:"Read a file"},write:{action:"update",running:"Writing a file",completed:"Wrote a file"},edit:{action:"update",running:"Editing a file",completed:"Edited a file"},notebook_read:{action:"read",running:"Reading a notebook",completed:"Read a notebook"},notebook_edit:{action:"update",running:"Editing a notebook",completed:"Edited a notebook"},glob:{action:"search",running:"Searching files",completed:"Searched files"},grep:{action:"search",running:"Searching file contents",completed:"Searched file contents",family:"grep"},tool_search:{action:"search",running:"Searching available tools",completed:"Searched available tools",group:Vd("tool_search","tool search","tool searches")},web_search:{action:"search",running:"Searching the web",completed:"Searched the web",family:"web"},web_fetch:{action:"fetch",running:"Fetching a web page",completed:"Fetched a web page",family:"web"},todo_write:{action:"update",running:"Updating the task list",completed:"Updated the task list",family:"plan",group:Vd("task_operation","task operation","task operations")},task_create:{action:"create",running:"Creating a task",completed:"Created a task",family:"plan",group:Vd("task_operation","task operation","task operations")},task_update:{action:"update",running:"Updating a task",completed:"Updated a task",family:"plan",group:Vd("task_operation","task operation","task operations")},task_list:{action:"list",running:"Listing tasks",completed:"Listed tasks",family:"plan",group:Vd("task_operation","task operation","task operations")},task_get:{action:"read",running:"Reading a task",completed:"Read a task",family:"plan",group:Vd("task_operation","task operation","task operations")},enter_plan_mode:{action:"switch",running:"Entering plan mode",completed:"Entered plan mode",family:"plan"},exit_plan_mode:{action:"switch",running:"Leaving plan mode",completed:"Left plan mode",family:"plan"},skill:{action:"read",running:"Loading a skill",completed:"Loaded a skill"},ask_user_question:{action:"request",running:"Requesting input",completed:"Requested input",family:"question"},request_human_input:{action:"request",running:"Requesting input",completed:"Requested input",family:"question",group:Vd("task_operation","task operation","task operations")},agent:{action:"start",running:"Starting a subagent",completed:"Started a subagent",family:"agent"},task:{action:"start",running:"Starting a subagent",completed:"Started a subagent",family:"agent"},task_output:{action:"read",running:"Checking subagent progress",completed:"Checked subagent progress",family:"agent"},task_stop:{action:"stop",running:"Stopping a subagent",completed:"Stopped a subagent",family:"agent"},send_message:{action:"post",running:"Messaging a subagent",completed:"Messaged a subagent",family:"agent"},spawn_agent:{action:"start",running:"Starting a subagent",completed:"Started a subagent",family:"agent"},wait_agent:{action:"wait",running:"Checking subagent progress",completed:"Checked subagent progress",family:"agent"},wait_threads:{action:"wait",running:"Checking task progress",completed:"Checked task progress",family:"agent"},interrupt_agent:{action:"stop",running:"Interrupting a subagent",completed:"Interrupted a subagent",family:"agent"},report_findings:{action:"post",running:"Reporting findings",completed:"Reported findings",family:"safety"},guardian_review:{action:"think",running:"Reviewing safety",completed:"Reviewed safety",family:"safety"},lsp:{action:"read",running:"Inspecting code intelligence",completed:"Inspected code intelligence"},compact_conversation:{action:"think",running:"Compacting context",completed:"Compacted context"},image_generation:{action:"create",running:"Generating an image",completed:"Generated an image",family:"image"},view_image:{action:"read",running:"Viewing an image",completed:"Viewed an image",family:"image"},multi_tool_use_parallel:{action:"run",running:"Running tools in parallel",completed:"Ran tools in parallel"},get_task_context:{action:"read",running:"Reading task context",completed:"Read task context"},get_task_history:{action:"read",running:"Reading task history",completed:"Read task history"},list_documents:{action:"list",running:"Listing documents",completed:"Listed documents"},read_document:{action:"read",running:"Reading a document",completed:"Read a document"},list_document_revisions:{action:"list",running:"Listing document revisions",completed:"Listed document revisions"},report_progress:{action:"post",running:"Reporting progress",completed:"Reported progress"},answer_status_question:{action:"post",running:"Answering a status question",completed:"Answered a status question"},write_document:{action:"update",running:"Writing a document",completed:"Wrote a document"},register_deliverable:{action:"create",running:"Registering a deliverable",completed:"Registered a deliverable"},finish_task:{action:"finish",running:"Reporting completion",completed:"Reported completion"},paperclip_finish:{action:"finish",running:"Reporting completion",completed:"Reported completion"},block_task:{action:"block",running:"Reporting a blocker",completed:"Reported a blocker"},paperclip_block:{action:"block",running:"Reporting a blocker",completed:"Reported a blocker"},request_review:{action:"request",running:"Requesting review",completed:"Requested review"},list_agents:{action:"list",running:"Listing agents",completed:"Listed agents"},get_agent:{action:"read",running:"Reading agent details",completed:"Read agent details"},search_tasks:{action:"search",running:"Searching tasks",completed:"Searched tasks"},list_approvals:{action:"list",running:"Listing approvals",completed:"Listed approvals"},get_approval:{action:"read",running:"Reading an approval",completed:"Read an approval"},get_approval_context:{action:"read",running:"Reading approval context",completed:"Read approval context"},get_workspace_runtime:{action:"read",running:"Reading workspace status",completed:"Read workspace status"},control_workspace_service:{action:"run",running:"Controlling a workspace service",completed:"Controlled a workspace service"},set_dependencies:{action:"update",running:"Updating task dependencies",completed:"Updated task dependencies"},set_task_title:{action:"update",running:"Naming the task",completed:"Named the task"},create_task:{action:"create",running:"Creating a task",completed:"Created a task"},request_approval:{action:"request",running:"Requesting approval",completed:"Requested approval"},decide_approval:{action:"update",running:"Deciding an approval",completed:"Decided an approval"},comment_on_approval:{action:"post",running:"Commenting on an approval",completed:"Commented on an approval"},schedule_wake:{action:"create",running:"Scheduling a wake-up",completed:"Scheduled a wake-up",family:"wait"},generic_api_request:{action:"request",running:"Calling the Paperclip API",completed:"Called the Paperclip API"}},kpt={read:["get","read","inspect","view"],list:["list","glob"],search:["find","search","grep","query","lookup"],fetch:["fetch","browse"],open:["open"],update:["write","edit","update","set","patch","upsert","sync"],create:["create","add","register","upload"],delete:["delete","remove"],move:["move","rename"],run:["run","execute","bash","shell","command"],request:["request","ask","prompt"],post:["send","message","comment","report","answer"],start:["start","spawn","delegate"],stop:["stop","cancel","interrupt"],wait:["wait","sleep","poll"],finish:["finish","complete"],block:["block"],think:["think","reason","compact","review"],switch:["switch","enter","exit"],other:[]},Npt={read:"read",edit:"update",delete:"delete",move:"move",search:"search",list:"list",execute:"run",think:"think",fetch:"fetch",switch_mode:"switch"};function Spt(e){return PV(e).join("_")}r(Spt,"normalizedKey");function Cpt(e){const s=e[0];if(!s)return null;for(const[n,a]of Object.entries(kpt))if(a.includes(s))return n;return null}r(Cpt,"inferredAction");function _pt(e){return e==="run"?"terminal":e==="read"||e==="list"?"read":e==="search"?"search":e==="fetch"||e==="open"?"web":["update","create","delete","move"].includes(e)?"edit":e==="request"?"question":e==="start"||e==="stop"?"agent":e==="wait"?"wait":"other"}r(_pt,"actionFamily");var Apt={terminal:ff,grep:$Ke,search:Yr,read:p2,edit:RL,web:rKe,plan:Hj,question:Ic,agent:Ub,safety:Bi,image:R3,wait:Au,mcp:ypt,other:pf};function Ipt(e,s){const n=s?` ${s}`:"";switch(e){case"read":return{running:`Reading${n||" data"}`,completed:`Read${n||" data"}`};case"list":return{running:`Listing${n||" items"}`,completed:`Listed${n||" items"}`};case"search":return{running:`Searching${n||""}`,completed:`Searched${n||""}`};case"fetch":return{running:`Fetching${n||" data"}`,completed:`Fetched${n||" data"}`};case"open":return{running:`Opening${n||" an item"}`,completed:`Opened${n||" an item"}`};case"update":return{running:`Updating${n||" data"}`,completed:`Updated${n||" data"}`};case"create":return{running:`Creating${n||" an item"}`,completed:`Created${n||" an item"}`};case"delete":return{running:`Deleting${n||" an item"}`,completed:`Deleted${n||" an item"}`};case"move":return{running:`Moving${n||" an item"}`,completed:`Moved${n||" an item"}`};case"run":return{running:"Running a command",completed:"Ran a command"};case"request":return{running:`Requesting${n||" input"}`,completed:`Requested${n||" input"}`};case"post":return{running:`Posting${n||" an update"}`,completed:`Posted${n||" an update"}`};case"start":return{running:`Starting${n||" an operation"}`,completed:`Started${n||" an operation"}`};case"stop":return{running:`Stopping${n||" an operation"}`,completed:`Stopped${n||" an operation"}`};case"wait":return{running:"Waiting",completed:"Finished waiting"};case"finish":return{running:"Reporting completion",completed:"Reported completion"};case"block":return{running:"Reporting a blocker",completed:"Reported a blocker"};case"think":return{running:"Thinking",completed:"Finished thinking"};case"switch":return{running:`Switching${n||" mode"}`,completed:`Switched${n||" mode"}`};case"other":return{running:"Running",completed:"Ran"}}}r(Ipt,"actionCopy");function Tpt(e){switch(e){case"run":return Vd("command","command","commands");case"read":case"list":return Vd("read","read","reads");case"search":return Vd("search","search","searches");case"update":case"create":case"delete":case"move":return Vd("file_change","file change","file changes");case"start":case"stop":return Vd("delegation","delegation","delegations");case"wait":return Vd("wait","wait","waits");default:return Vd("tool_action","tool action","tool actions")}}r(Tpt,"defaultSummaryGroup");function Rpt(e){return e==="read"||e==="list"?Vd("paperclip_read","Paperclip read","Paperclip reads"):Vd("task_operation","task operation","task operations")}r(Rpt,"paperclipSummaryGroup");function Nj(e){const s=(e.name??"").trim(),n=MV(s),a=(e.namespace??n?.namespace??"").trim(),i=(n?"mcp":e.transport??"builtin").toLowerCase(),o=(n?.name??s).trim(),l=PV(o),c=Spt(o),d=wpt[c],u=Npt[(e.operation??"").trim().toLowerCase()],h=Cpt(l),p=d?.action??u??h??"other",f=d?"exact":u?"kind":h?"inferred":Su(o)?"unnamed":"fallback",x=Su(o)?"Unnamed tool":Lk(o),g=/^[A-Za-z][A-Za-z0-9_.:-]*$/.test(o),v=h&&g&&l.length>1?l.slice(1):[],y=v.length?a3e(v).replace(/^./,_=>_.toLowerCase()):void 0,k=d?.running&&d.completed?{running:d.running,completed:d.completed}:p==="other"?Su(o)?{running:"Running an unnamed tool",completed:"Ran an unnamed tool"}:{running:`Running ${x}`,completed:`Ran ${x}`}:Ipt(p,d?void 0:y),w=d?.family??_pt(p),N=i==="mcp"?"mcp":w,S=a?Lk(a):i==="mcp"?"MCP":void 0,C=a.toLowerCase()==="paperclip"?Rpt(p):d?.group??Tpt(p);return{icon:Apt[N],family:N,runningLabel:k.running,completedLabel:k.completed,failedLabel:`${k.completed} · failed`,interruptedLabel:`${k.running} · stopped`,displayName:x,sourceLabel:S,technicalName:s||void 0,confidence:f,summaryGroup:C}}r(Nj,"toolActivityPresentation");function AN(e){const s=Nj({name:e});return{family:s.family,icon:s.icon,verbLabel:s.runningLabel}}r(AN,"toolTaxonomy");function i3e(e){const s=(e??"").trim().toLowerCase();return s==="thinking"?Lx:s==="responding"||s.startsWith("responding (")?CKe:null}r(i3e,"statusLabelIcon");var vD=["Clipping","Organizing","Sorting","Synthesizing","Analyzing","Filing","Collating","Stapling","Indexing","Annotating","Drafting","Proofreading","Alphabetizing","Photocopying","Laminating","Hole-punching","Bookmarking","Highlighting","Typing","Trimming","Aligning","Combining","Whiteboarding","Diagramming","Sketching","Labeling","Sticky-noting"],yD=["Brewing","Tinkering","Distilling","Deliberating"],Wae=(()=>{const e=[],s=Math.max(vD.length,yD.length);for(let n=0;n<s;n++)n<vD.length&&e.push(vD[n]),n<yD.length&&e.push(yD[n]);return e})(),Ept=1e4;function Lpt(e){const s=(e??"").trim().toLowerCase();return s==="running"||s==="working"}r(Lpt,"isGenericStatusLabel");function Mpt(e){let s=2166136261;for(let n=0;n<e.length;n++)s^=e.charCodeAt(n),s=Math.imul(s,16777619);return s>>>0}r(Mpt,"fnv1a");function Ppt(e,s=0){const n=Math.floor(Math.max(0,s)/Ept);return Wae[(Mpt(e)+n)%Wae.length]}r(Ppt,"whimsyWord");var Dpt=[{name:"--motion-ease-out-expo",group:"Easing",kind:"easing"},{name:"--motion-ease-standard",group:"Easing",kind:"easing"},{name:"--motion-ease-out",group:"Easing",kind:"easing"},{name:"--motion-ease-scroll-pill-in",group:"Easing",kind:"easing"},{name:"--motion-ease-scroll-pill-out",group:"Easing",kind:"easing"},{name:"--motion-ease-in",group:"Easing",kind:"easing"},{name:"--motion-duration-instant",group:"Durations",kind:"time",min:0,max:1e3,step:10},{name:"--motion-duration-fast",group:"Durations",kind:"time",min:0,max:1e3,step:10},{name:"--motion-duration-base",group:"Durations",kind:"time",min:0,max:1e3,step:10},{name:"--motion-duration-slow",group:"Durations",kind:"time",min:0,max:1500,step:10},{name:"--motion-duration-deliberate",group:"Durations",kind:"time",min:0,max:2e3,step:10},{name:"--motion-duration-enter",group:"Durations",kind:"time",min:0,max:1e3,step:10},{name:"--motion-duration-exit",group:"Durations",kind:"time",min:0,max:1e3,step:10},{name:"--motion-duration-swap",group:"Durations",kind:"time",min:0,max:1e3,step:10},{name:"--motion-marker-enter",group:"States",kind:"time",min:0,max:1500,step:10},{name:"--motion-bubble-enter",group:"States",kind:"time",min:0,max:1500,step:10},{name:"--motion-cot-line-stagger",group:"States",kind:"time",min:0,max:300,step:5},{name:"--motion-cot-collapse",group:"States",kind:"time",min:0,max:1500,step:10},{name:"--motion-tool-enter",group:"States",kind:"time",min:0,max:1500,step:10},{name:"--motion-diff-reveal",group:"States",kind:"time",min:0,max:1500,step:10},{name:"--motion-status-enter",group:"States",kind:"time",min:0,max:1500,step:10},{name:"--motion-status-exit",group:"States",kind:"time",min:0,max:1500,step:10},{name:"--motion-approval-pulse",group:"States",kind:"time",min:0,max:3e3,step:20},{name:"--motion-plan-entry-stagger",group:"States",kind:"time",min:0,max:300,step:5},{name:"--motion-plan-check",group:"States",kind:"time",min:0,max:1500,step:10},{name:"--motion-question-page-enter",group:"States",kind:"time",min:0,max:1e3,step:10},{name:"--motion-count-tween",group:"States",kind:"time",min:0,max:1500,step:10},{name:"--motion-streaming-cursor-blink",group:"States",kind:"time",min:0,max:3e3,step:20},{name:"--motion-turn-fold",group:"States",kind:"time",min:0,max:1500,step:10},{name:"--motion-turn-meta",group:"States",kind:"time",min:0,max:1500,step:10},{name:"--motion-line-scroll",group:"States",kind:"time",min:0,max:1500,step:10},{name:"--motion-interstitial-dwell",group:"States",kind:"time",min:0,max:1e4,step:100},{name:"--motion-scroll-pill-enter",group:"States",kind:"time",min:0,max:1500,step:10},{name:"--motion-scroll-pill-exit",group:"States",kind:"time",min:0,max:1500,step:10},{name:"--motion-mobile-nav-enter",group:"States",kind:"time",min:0,max:1500,step:10},{name:"--motion-mobile-nav-exit",group:"States",kind:"time",min:0,max:1500,step:10},{name:"--motion-scrollbar-idle-delay",group:"States",kind:"time",min:0,max:2e3,step:10},{name:"--motion-pane-glide",group:"States",kind:"time",min:0,max:1500,step:10},{name:"--motion-side-panel-tab",group:"States",kind:"time",min:0,max:1500,step:10},{name:"--motion-live-now-sweep",group:"States",kind:"time",min:0,max:5e3,step:100},{name:"--motion-live-now-breathe",group:"States",kind:"time",min:0,max:5e3,step:100}],Cbs=Array.from(new Set(Dpt.map(e=>e.group)));function o3e(e){const s=e.trim();if(s.endsWith("ms"))return parseFloat(s);if(s.endsWith("s"))return parseFloat(s)*1e3;const n=parseFloat(s);return Number.isFinite(n)?n:0}r(o3e,"parseCssTimeMs");function $pt(e){if(e==null)return null;const s=Math.round(e/1e3);return s<60?`${s}s`:`${Math.floor(s/60)}m ${s%60}s`}r($pt,"elapsedLabel");function Opt(e){if(e==null)return null;const s=Math.max(0,e)/1e3;return s<60?`${s.toFixed(1)}s`:`${Math.floor(s/60)}m ${(s%60).toFixed(1)}s`}r(Opt,"liveElapsedLabel");function Bpt(e,s){const[n,a]=(0,m.useState)(()=>Date.now());return(0,m.useEffect)(()=>{if(e==null||!s)return;const i=window.setInterval(()=>a(Date.now()),100);return()=>window.clearInterval(i)},[e,s]),e==null?void 0:Math.max(0,n-e)}r(Bpt,"useLiveElapsedMs");function Fpt(e,s){return!Number.isFinite(e)||!Number.isFinite(s)||s<=0?0:Math.max(0,Math.round(e/s)-1)}r(Fpt,"lineScrollOffset");function g6(e){const s=getComputedStyle(document.documentElement).getPropertyValue(e),n=o3e(s);return Number.isFinite(n)?n:0}r(g6,"motionTokenMs");function zpt({text:e,streaming:s,leaving:n}){const a=(0,m.useRef)(null),[i,o]=(0,m.useState)(0),[l,c]=(0,m.useState)(!1),[d,u]=(0,m.useState)(!1);(0,m.useLayoutEffect)(()=>{const p=a.current;if(!p)return;const f=r(()=>{const g=parseFloat(window.getComputedStyle(p).lineHeight);o(Fpt(p.scrollHeight,g))},"measure");if(f(),typeof ResizeObserver>"u")return;const x=new ResizeObserver(f);return x.observe(p),()=>x.disconnect()},[e,s]),(0,m.useEffect)(()=>{const p=requestAnimationFrame(()=>c(!0)),f=window.setTimeout(()=>u(!0),g6("--motion-line-scroll"));return()=>{cancelAnimationFrame(p),window.clearTimeout(f)}},[]);const h=l?n?-1:s?-i:0:1;return(0,t.jsx)("span",{className:"tc-line-scroll min-w-0 flex-1","data-testid":"task-chat-live-self-talk","data-streaming":s||void 0,"data-leaving":n||void 0,children:(0,t.jsx)("span",{ref:a,className:W("tc-line-scroll-inner block",!s&&"truncate"),style:{transform:h!==0?`translateY(calc(${h} * 1lh))`:void 0,transition:d&&!n?"none":void 0},children:e})})}r(zpt,"LiveSelfTalkLine");function qpt(e,s){const[n,a]=(0,m.useState)(null),i=(0,m.useRef)(n),o=(0,m.useRef)(null),l=(0,m.useRef)(e),c=(0,m.useRef)(0),d=(0,m.useRef)(null),u=(0,m.useRef)(null),h=(0,m.useRef)(null);return l.current=e,(0,m.useEffect)(()=>{const p=r(y=>{y.current!=null&&(window.clearTimeout(y.current),y.current=null)},"clear"),f=r(y=>{i.current=y,a(y)},"show"),x=r(()=>{p(u),p(h),u.current=window.setTimeout(()=>{if(u.current=null,o.current!=null)return;const y=i.current;y==null||y.streaming||(f({...y,leaving:!0}),h.current=window.setTimeout(()=>{h.current=null,i.current?.leaving&&f(null)},g6("--motion-line-scroll")))},g6("--motion-interstitial-dwell"))},"scheduleLeave"),g=r((y,k)=>{p(u),p(h),c.current=Date.now(),f({text:y,streaming:k,swapKey:(i.current?.swapKey??0)+1}),k||x()},"swapIn");if(!s){p(d),p(u),p(h),o.current=null,i.current&&f(null);return}const v=i.current;if(e==null){v?.streaming&&(f({...v,streaming:!1}),x());return}if(v==null){g(e,!0);return}if(v.streaming){v.text!==e&&f({...v,text:e});return}if(o.current=e,d.current==null){const y=g6("--motion-interstitial-dwell"),k=Math.max(0,c.current+y-Date.now());d.current=window.setTimeout(()=>{d.current=null;const w=o.current;o.current=null,w!=null&&g(w,l.current!=null)},k)}},[e,s]),(0,m.useEffect)(()=>()=>{d.current!=null&&window.clearTimeout(d.current),u.current!=null&&window.clearTimeout(u.current),h.current!=null&&window.clearTimeout(h.current)},[]),n}r(qpt,"useHeldSelfTalk");var Upt={running:{Icon:st,spin:!0,tone:"text-(--status-agent-running)"},working:{Icon:st,spin:!0,tone:"text-(--status-agent-running)"},awaiting_approval:{Icon:x2,spin:!1,tone:"text-primary"},interrupted:{Icon:gW,spin:!1,tone:"text-destructive"},refused:{Icon:Hm,spin:!1,tone:"text-destructive"},truncated:{Icon:DKe,spin:!1,tone:"text-(--status-agent-paused)"}};function l3e({item:e,onApprovalDecision:s,chevronOpen:n,onToggle:a}){const{Icon:i,spin:o,tone:l}=Upt[e.status],c=e.status==="awaiting_approval",d=e.status==="running"||e.status==="working",u=Bpt(e.startedAtMs,d),h=qpt(d?e.selfTalk:void 0,d),p=$pt(e.elapsedMs);if(d){const f=Opt(u??e.elapsedMs),x=e.selfTalk!=null,g=e.toolName?AN(e.toolName).icon:x?null:i3e(e.label),v=x||Lpt(e.label)?Ppt(e.id,u??e.elapsedMs??0):e.label,y=(0,t.jsxs)("div",{className:"tc-enter-status flex items-center gap-2 py-0.5 text-xs text-muted-foreground",children:[n!==void 0?(0,t.jsx)("span",{className:"flex h-3.5 w-3.5 shrink-0 items-center justify-center","data-testid":"task-chat-status-caret-slot",children:(0,t.jsx)(Ln,{className:W("h-3 w-3 transition-transform",n?"rotate-90":null),"aria-hidden":!0})}):null,(0,t.jsx)("span",{className:"flex h-3.5 w-3.5 shrink-0 items-center justify-center","data-testid":"task-chat-status-dot-slot",children:(0,t.jsx)("span",{"aria-hidden":!0,className:"h-2 w-2 animate-pulse rounded-full bg-(--status-agent-running)"})}),g?(0,t.jsx)(g,{className:"h-3.5 w-3.5 shrink-0","aria-hidden":!0}):null,(0,t.jsxs)("span",{className:"flex min-w-0 flex-1 items-baseline gap-2",children:[(0,t.jsxs)("span",{className:"shimmer-text shimmer-text-muted shrink-0 font-medium",children:[v,"…"]}),f?(0,t.jsx)("span",{className:"shrink-0 font-mono tabular-nums text-(length:--text-micro)",children:f}):null,e.detail?(0,t.jsx)("span",{className:"min-w-0 truncate font-mono text-(length:--text-micro)",children:e.detail}):null,e.tokens?(0,t.jsxs)("span",{className:"ml-auto shrink-0 font-mono text-(length:--text-micro)",children:[e.tokens.used.toLocaleString(),"/",e.tokens.size.toLocaleString()," ctx"]}):null]})]});return(0,t.jsxs)("div",{className:"flex flex-col",children:[(0,t.jsxs)("div",{className:"flex items-center gap-2 py-0.5 text-xs text-muted-foreground","data-testid":"task-chat-interstitial-row",children:[(0,t.jsx)("span",{"aria-hidden":!0,className:"h-3.5 w-3.5 shrink-0"}),h?(0,t.jsx)(zpt,{text:h.text,streaming:h.streaming,leaving:h.leaving},h.swapKey):(0,t.jsx)("span",{"aria-hidden":!0,className:"tc-line-scroll min-w-0 flex-1"})]}),a?(0,t.jsx)("button",{type:"button",onClick:a,"aria-expanded":n,className:"-mx-1.5 block w-full rounded-sm px-1.5 text-left transition-colors hover:bg-muted/60","data-testid":"task-chat-live-turn",children:y}):y]})}return(0,t.jsxs)("div",{className:W("tc-enter-status flex flex-col gap-2 rounded-lg border px-3 py-2 text-sm",c?"tc-approval border-primary/40 bg-primary/5":"border-border bg-muted/40"),children:[(0,t.jsxs)("div",{className:"flex min-w-0 items-center gap-2",children:[(0,t.jsx)(i,{className:W("h-4 w-4 shrink-0",l,o&&"animate-spin")}),(0,t.jsx)("span",{className:"min-w-0 truncate font-medium",children:e.label}),(0,t.jsxs)("span",{className:"ml-auto flex shrink-0 items-center gap-2 text-xs text-muted-foreground",children:[p?(0,t.jsx)("span",{children:p}):null,e.tokens?(0,t.jsxs)("span",{children:[e.tokens.used.toLocaleString(),"/",e.tokens.size.toLocaleString()," ctx"]}):null]})]}),e.detail?(0,t.jsx)("p",{className:"text-xs text-muted-foreground",children:e.detail}):null,c&&e.approval?(0,t.jsx)("div",{className:"flex flex-wrap justify-end gap-2 pt-1",children:e.approval.options.map(f=>{const x=f.kind.startsWith("reject");return(0,t.jsx)("button",{type:"button",onClick:r(()=>s?.(f.id),"onClick"),className:W("rounded-md border px-2.5 py-1 text-xs font-medium transition-colors",x?"border-border text-muted-foreground hover:bg-accent/50 hover:text-foreground":"border-primary bg-primary text-primary-foreground hover:bg-primary/90"),children:f.label},f.id)})}):null]})}r(l3e,"TaskChatStatusPill");var gg=(0,m.createContext)(null);function nw(e){if(!Number.isFinite(e)||e<0)return"0 B";if(e<1024)return`${Math.round(e)} B`;const s=["KB","MB","GB","TB"];let n=e/1024,a=0;for(;n>=1024&&a<s.length-1;)n/=1024,a+=1;const i=n.toFixed(1);return`${i.endsWith(".0")?i.slice(0,-2):i} ${s[a]}`}r(nw,"formatBytes$4");var PE=new Set(["application/octet-stream","binary/octet-stream","application/x-binary"]),Kpt=[".mp4",".m4v",".webm",".mov",".qt",".quicktime"],Qpt=[".png",".jpg",".jpeg",".gif",".webp",".avif",".bmp",".ico"],Wpt=new Set(["application/wasm"]),Hpt=new Set(["application/zip","application/x-zip","application/x-zip-compressed"]),c3e=new Set(["text/markdown","text/x-markdown","application/markdown","application/x-markdown"]),Vpt=new Set(["application/csv","application/ecmascript","application/graphql","application/html","application/javascript","application/json","application/ld+json","application/sql","application/toml","application/x-httpd-php","application/x-javascript","application/x-python","application/x-sh","application/x-yaml","application/xhtml+xml","application/xml","application/yaml"]),Gpt=[".csv",".css",".graphql",".htm",".html",".js",".json",".jsx",".log",".markdown",".md",".mdx",".php",".py",".sh",".sql",".toml",".ts",".tsx",".txt",".xml",".yaml",".yml"];function J3(e){return(e??"").toLowerCase().split(";")[0]?.trim()??""}r(J3,"normalizeOutputContentType");function Ypt(e){const s=(e??"").trim().toLowerCase();return s?Gpt.some(n=>s.endsWith(n)):!1}r(Ypt,"hasDocumentLikeFilename");function d3e(e){return Hpt.has(e)||e.endsWith("+zip")}r(d3e,"isZipContentType");function Zpt(e){return e?!!(e.startsWith("text/")||c3e.has(e)||Vpt.has(e)||e.startsWith("application/")&&(e.endsWith("+json")||e.endsWith("+xml"))):!1}r(Zpt,"isDocumentLikeOutputContentType");function Jpt(e,s){const n=J3(e);return!n||Zpt(n)||PE.has(n)&&Ypt(s)?!1:n.startsWith("video/")||n.startsWith("image/")||n==="application/pdf"||Wpt.has(n)||d3e(n)||PE.has(n)}r(Jpt,"isOutputEligibleContentType");function Xpt(e){const s=J3(e);if(s.startsWith("video/")){const n=s.slice(6);return n==="quicktime"?{label:"MOV",tone:"video"}:{label:(n||"vid").toUpperCase().slice(0,4),tone:"video"}}return s==="application/pdf"?{label:"PDF",tone:"pdf"}:d3e(s)?{label:"ZIP",tone:"zip"}:s.startsWith("image/")?{label:"IMG",tone:"image"}:c3e.has(s)?{label:"MD",tone:"bin"}:s==="text/plain"?{label:"TXT",tone:"bin"}:s==="text/csv"||s==="application/csv"?{label:"CSV",tone:"bin"}:s==="text/html"||s==="application/html"||s==="application/xhtml+xml"?{label:"HTML",tone:"bin"}:s==="application/json"||s.endsWith("+json")?{label:"JSON",tone:"bin"}:s==="application/xml"||s==="text/xml"||s.endsWith("+xml")?{label:"XML",tone:"bin"}:s==="application/wasm"?{label:"WASM",tone:"bin"}:{label:"BIN",tone:"bin"}}r(Xpt,"getOutputFileGlyph");function ym(e,s){const n=J3(e);if(n.startsWith("video/"))return!0;if(!PE.has(n))return!1;const a=(s??"").trim().toLowerCase();return Kpt.some(i=>a.endsWith(i))}r(ym,"isVideoLikeOutput");function Sj(e){const s=J3(e);return s.startsWith("image/")&&s!=="image/svg+xml"}r(Sj,"isImageContentType");function _M(e,s){const n=J3(e);if(Sj(n))return!0;if(n&&!PE.has(n))return!1;const a=(s??"").trim().toLowerCase();return Qpt.some(i=>a.endsWith(i))}r(_M,"isImageLikeOutput");function Hae(e){const s=new Date(e).getTime();return Number.isNaN(s)?0:s}r(Hae,"toTime");function AM(e){const s=(e??[]).filter(n=>n.type==="artifact"&&n.provider==="paperclip").flatMap(n=>{const a=LOe.safeParse(n.metadata);return a.success&&!Jpt(a.data.contentType,a.data.originalFilename)?[]:[{id:n.id,title:n.title,status:typeof n.status=="string"?n.status:"active",isPrimary:!!n.isPrimary,createdAt:n.createdAt,metadata:a.success?a.data:null,degraded:!a.success,workProduct:n}]});return s.sort((n,a)=>n.isPrimary!==a.isPrimary?n.isPrimary?-1:1:Hae(a.createdAt)-Hae(n.createdAt)),{items:s,primary:s[0]??null,rest:s.slice(1),count:s.length}}r(AM,"getIssueOutputs");function DV(e){return e.metadata?.originalFilename||e.title||"output"}r(DV,"outputFilename");function u3e(e){return new Set(AM(e).items.flatMap(s=>{const n=s.metadata?.attachmentId;return n?[n]:[]}))}r(u3e,"getPromotedOutputAttachmentIds");function X3(e,s){const n=e?.toLowerCase().split(";")[0].trim();return n==="text/html"||n==="application/xhtml+xml"||/\.html?$/i.test(s??"")}r(X3,"isHtmlPreview");var eft=["default-src 'none'","script-src 'unsafe-inline'","style-src 'unsafe-inline'","img-src data:","font-src data:","media-src data:","connect-src 'none'","frame-src 'none'","object-src 'none'","base-uri 'none'","form-action 'none'"].join("; ");function tft(e){return`<!doctype html><html><head><meta charset="utf-8"><meta http-equiv="Content-Security-Policy" content="${eft}"><meta name="referrer" content="no-referrer"></head><body>${e}</body></html>`}r(tft,"htmlPreviewDocument");function sft(e){return e.contentType.toLowerCase().split(";")[0]?.trim()??""}r(sft,"normalizedContentType");function sg(e){return e.originalFilename??e.id}r(sg,"attachmentFilename");function IM(e){return e.openPath??e.contentPath}r(IM,"attachmentOpenPath");function I2(e){return e.downloadPath??`${e.contentPath}?download=1`}r(I2,"attachmentDownloadPath");function m3e(e){const s=sft(e);return _M(s,e.originalFilename)&&!/^image\/hei[cf](?:-sequence)?$/.test(s)}r(m3e,"isImageAttachment$1");function h3e(e){return ym(e.contentType,e.originalFilename)}r(h3e,"isVideoAttachment");function p3e(e){return obe(e)}r(p3e,"isMarkdownAttachment");function rw(e){const s=e.contentType.toLowerCase().split(";")[0].trim();return obe(e)||X3(s,e.originalFilename)||s.startsWith("text/")||/^(application\/(json|xml|javascript|x-yaml|yaml)|application\/[\w.-]+\+json)$/.test(s)||["","application/octet-stream"].includes(s)&&/\.(txt|log|csv|json|yaml|yml|toml|ini|sh|ts|tsx|js|jsx|py|css|html)$/i.test(e.originalFilename??"")}r(rw,"isTextAttachment");function f3e(e,s){const n=URL.createObjectURL(s),a=document.createElement("a");a.href=n,a.download=e,a.rel="noreferrer",a.style.display="none",document.body.appendChild(a),a.click(),document.body.removeChild(a),URL.revokeObjectURL(n)}r(f3e,"downloadBlob$1");function nft(e,s,n){f3e(e,new Blob([s],{type:`${n};charset=utf-8`}))}r(nft,"downloadTextFile");var jD="flex h-7 w-7 items-center justify-center rounded-md text-muted-foreground transition-colors hover:bg-accent hover:text-foreground disabled:opacity-50";function x3e({issueId:e,documentKey:s,title:n,format:a,body:i,className:o}){const[l,c]=(0,m.useState)(null),[d,u]=(0,m.useState)(null),[h,p]=(0,m.useState)(null),{copy:f,copied:x,failed:g}=ep(),v=(0,m.useRef)(void 0);(0,m.useEffect)(()=>()=>clearTimeout(v.current),[]);const y=(0,m.useCallback)(async(_,R)=>{c(_),p(null);try{await R(),u(_)}catch(I){u(null),p(I instanceof Error?I.message:"Export failed")}finally{c(null)}clearTimeout(v.current),v.current=setTimeout(()=>{u(null),p(null)},2e3)},[]),k=(0,m.useCallback)(async()=>i??(await yt.getDocument(e,s)).body,[i,s,e]),w=(0,m.useCallback)(()=>{c("copy"),p(null),(async()=>{try{await f(await k())==="failed"&&p("Copy failed")}catch(_){p(_ instanceof Error?_.message:"Copy failed")}finally{c(null)}})()},[f,k]),N=g||h==="Copy failed"?"Copy failed":x?"Copied!":"Copy full content",S=d==="download"?"Downloaded!":"Download source",C=d==="pdf"?"Downloaded!":"Export to PDF";return(0,t.jsxs)("div",{className:W("flex items-center gap-0.5",o),"data-testid":"document-export-actions",children:[(0,t.jsx)("button",{type:"button",className:jD,disabled:l!==null,"aria-label":"Copy full content",title:N,"data-testid":"document-export-copy",onClick:r(_=>{_.preventDefault(),_.stopPropagation(),w()},"onClick"),children:x?(0,t.jsx)(ms,{"aria-hidden":"true",className:"h-3.5 w-3.5"}):(0,t.jsx)(br,{"aria-hidden":"true",className:"h-3.5 w-3.5"})}),(0,t.jsx)("button",{type:"button",className:jD,disabled:l!==null,"aria-label":"Download source",title:S,"data-testid":"document-export-download",onClick:r(_=>{_.preventDefault(),_.stopPropagation(),y("download",async()=>{const R=pqe(a);nft(ite(n,R),await k(),R==="md"?"text/markdown":"text/plain")})},"onClick"),children:(0,t.jsx)(Fi,{"aria-hidden":"true",className:"h-3.5 w-3.5"})}),(0,t.jsx)("button",{type:"button",className:jD,disabled:l!==null,"aria-label":"Export to PDF",title:C,"data-testid":"document-export-pdf",onClick:r(_=>{_.preventDefault(),_.stopPropagation(),y("pdf",async()=>{f3e(ite(n,"pdf"),await yt.getDocumentPdf(e,s))})},"onClick"),children:(0,t.jsx)(fKe,{"aria-hidden":"true",className:"h-3.5 w-3.5"})}),(0,t.jsx)("span",{className:"sr-only",role:"status","aria-live":"polite",children:h??(x?"Copied!":g?"Copy failed":d?"Downloaded!":"")})]})}r(x3e,"DocumentExportActions");function k5({children:e,className:s}){return(0,t.jsx)("div",{className:W("relative aspect-video w-full overflow-hidden bg-accent/20",s),children:e})}r(k5,"PreviewFrame");function DE({label:e}){return(0,t.jsx)(k5,{className:"flex items-center justify-center",children:(0,t.jsxs)("div",{className:"flex flex-col items-center gap-1.5 text-muted-foreground/50",children:[(0,t.jsx)(kl,{className:"h-7 w-7","aria-hidden":"true"}),e?(0,t.jsx)("span",{className:"text-(length:--text-micro) font-medium uppercase tracking-wide",children:e}):null]})})}r(DE,"PlaceholderPreview");function rft({artifact:e}){const[s,n]=(0,m.useState)(!1);return s||!e.contentPath?(0,t.jsx)(DE,{label:"Image"}):(0,t.jsx)(k5,{children:(0,t.jsx)("img",{src:e.contentPath,alt:e.title,loading:"lazy",className:"h-full w-full object-cover",onError:r(()=>n(!0),"onError")})})}r(rft,"ImagePreview");function aft({artifact:e}){const[s,n]=(0,m.useState)(!1),[a,i]=(0,m.useState)(!1),o=(0,m.useRef)(!1),l=(0,m.useRef)(null);if((0,m.useEffect)(()=>()=>{l.current!==null&&window.clearTimeout(l.current)},[]),s||!e.contentPath)return(0,t.jsx)(k5,{className:"flex items-center justify-center bg-black/80",children:(0,t.jsx)("div",{className:"flex h-11 w-11 items-center justify-center rounded-full bg-white/15",children:(0,t.jsx)(ho,{className:"h-5 w-5 translate-x-0.5 text-white","aria-hidden":"true"})})});const c=r(()=>{l.current!==null&&(window.clearTimeout(l.current),l.current=null),i(!0)},"markFrameReady"),d=r(()=>{l.current!==null&&window.clearTimeout(l.current),l.current=window.setTimeout(c,3e3)},"scheduleFrameReadyFallback"),u=r(p=>{if(o.current)return;o.current=!0;const f=p.currentTarget,x=Number.isFinite(f.duration)&&f.duration>0?f.duration:0,g=x>0?Math.min(1,x/4):.05;try{Math.abs(f.currentTime-g)>.001?(f.currentTime=g,d()):c()}catch{c()}},"loadThumbnailFrame"),h=r(p=>{(o.current||p.currentTarget.currentTime>0)&&c()},"handleLoadedData");return(0,t.jsxs)(k5,{className:"bg-black",children:[(0,t.jsx)("video",{src:e.contentPath,preload:"metadata",muted:!0,playsInline:!0,"data-frame-ready":a?"true":"false",className:W("h-full w-full object-contain transition-opacity",a?"opacity-100":"opacity-0"),onLoadedMetadata:u,onLoadedData:h,onSeeked:c,onError:r(()=>n(!0),"onError")}),(0,t.jsx)("div",{className:"pointer-events-none absolute inset-0 flex items-center justify-center",children:(0,t.jsx)("div",{className:"flex h-11 w-11 items-center justify-center rounded-full bg-black/55",children:(0,t.jsx)(ho,{className:"h-5 w-5 translate-x-0.5 text-white","aria-hidden":"true"})})})]})}r(aft,"VideoPreview");function ift({artifact:e}){const s=e.previewText?.trim();return s?(0,t.jsxs)(k5,{className:"bg-card",children:[(0,t.jsx)("div",{className:"absolute inset-0 overflow-hidden p-3",children:(0,t.jsx)("p",{className:"max-h-full overflow-hidden whitespace-pre-wrap break-words text-base leading-6 text-muted-foreground/75",children:s})}),(0,t.jsx)("div",{className:"pointer-events-none absolute bottom-0 left-0 right-0 h-10 bg-gradient-to-t from-card to-transparent"})]}):(0,t.jsx)(DE,{label:e.source==="document"?"Document":"Text"})}r(ift,"TextPreview");function eA({artifact:e}){switch(e.mediaKind){case"image":return(0,t.jsx)(rft,{artifact:e},e.contentPath);case"video":return(0,t.jsx)(aft,{artifact:e},e.contentPath);case"text":case"document":return(0,t.jsx)(ift,{artifact:e});case"file":return(0,t.jsx)(DE,{label:"File"});default:return(0,t.jsx)(DE,{})}}r(eA,"ArtifactPreview");function Vae({href:e,download:s,title:n,children:a}){return(0,t.jsx)("a",{href:e,...s?{download:""}:{target:"_blank",rel:"noreferrer"},title:n,"aria-label":n,onClick:r(i=>i.stopPropagation(),"onClick"),className:"flex h-7 w-7 items-center justify-center rounded-md text-muted-foreground transition-colors hover:bg-accent hover:text-foreground",children:a})}r(Vae,"SecondaryAction");function oft({artifact:e}){return(0,t.jsxs)(We,{to:e.href,disableIssueQuicklook:!0,"data-testid":"artifact-card","data-media-kind":e.mediaKind,className:"group flex flex-col overflow-hidden rounded-lg border border-border bg-card cursor-pointer transition-colors hover:border-foreground/20 hover:shadow-md focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring",children:[(0,t.jsx)(eA,{artifact:e}),(0,t.jsxs)("div",{className:"flex flex-1 flex-col gap-1 p-3",children:[(0,t.jsxs)("div",{className:"flex h-7 items-start justify-between gap-2",children:[(0,t.jsx)("h3",{className:"min-w-0 flex-1 truncate text-sm font-medium leading-7 text-foreground/85",title:e.title,children:e.title}),(0,t.jsxs)("div",{className:"flex shrink-0 items-center gap-0.5 opacity-0 transition-opacity group-hover:opacity-100 focus-within:opacity-100",children:[e.source==="document"&&e.documentKey?(0,t.jsx)(x3e,{issueId:e.issue.id,documentKey:e.documentKey,title:e.title}):null,e.openPath?(0,t.jsx)(Vae,{href:e.openPath,title:"Open file in new tab",children:(0,t.jsx)($n,{className:"h-3.5 w-3.5"})}):null,e.downloadPath?(0,t.jsx)(Vae,{href:e.downloadPath,download:!0,title:"Download file",children:(0,t.jsx)(Fi,{className:"h-3.5 w-3.5"})}):null]})]}),(0,t.jsxs)("div",{className:"mt-0.5 flex items-center gap-1.5 text-(length:--text-micro) text-muted-foreground/65",children:[(0,t.jsxs)("span",{children:["Last edited ",Zd(e.updatedAt)]}),e.createdByAgent?(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)("span",{className:"text-muted-foreground/50",children:"·"}),(0,t.jsx)("span",{className:"truncate",children:e.createdByAgent.name})]}):null]})]})]})}r(oft,"ArtifactCard");function lft(e){return e&&/^\/api\/assets\/[^/?#]+\/content$/.test(e)?e:null}r(lft,"paperclipHumanAvatarUrl");function g3e(e){const{authorName:s,authorUserId:n,currentUserId:a,userProfileMap:i}=e,o=n?i?.get(n):null,l=!!(n&&a&&n===a);return{isCurrentUser:l,authorName:o?.label?.trim()||s?.trim()||(n==="local-board"?"Board":l?"You":"User"),avatarUrl:o?.image??null}}r(g3e,"resolveIssueChatHumanAuthor");var sc={credentials:r(e=>ke.get(`/companies/${e}/email/connections`),"credentials"),checkAddress:r((e,s,n,a)=>ke.post(`/companies/${e}/email/connections/${s}/check-address`,n,{signal:a}),"checkAddress"),connect:r((e,s)=>ke.post(`/companies/${e}/email/connections`,s),"connect"),inspectSaved:r((e,s)=>ke.post(`/companies/${e}/email/connections/${s}/inspect`,{}),"inspectSaved"),list:r(e=>ke.get(`/companies/${e}/email/inboxes`),"list"),setup:r((e,s)=>ke.post(`/companies/${e}/email/inboxes`,s),"setup"),inspect:r((e,s)=>ke.post(`/companies/${e}/email/inspect`,{apiKey:s}),"inspect"),control:r((e,s)=>ke.post(`/email/inboxes/${e}/control`,{action:s}),"control"),reconnect:r((e,s,n)=>ke.post(`/email/inboxes/${e}/reconnect`,{apiKey:s,receiveMode:n}),"reconnect"),resolve:r((e,s,n,a)=>ke.post(`/companies/${e}/email/deliveries/${s}/resolve`,{outcome:n,providerMessageId:a}),"resolve"),thread:r((e,s)=>ke.get(`/companies/${e}/email/tasks/${s}`),"thread"),send:r((e,s)=>ke.post(`/companies/${e}/email/send`,s),"send")};function b3e(e,s){return te({queryKey:["email-thread",e,s],queryFn:r(()=>sc.thread(e,s),"queryFn"),enabled:!!(e&&s)&&!s.startsWith("chat:"),refetchInterval:r(n=>n.state.data===null?!1:3e3,"refetchInterval")})}r(b3e,"useEmailThread");var v3e=(0,m.createContext)(null);function cft({companyId:e,issueId:s,children:n}){const a=b3e(e,s);return(0,t.jsx)(v3e.Provider,{value:a.data??null,children:n})}r(cft,"EmailThreadProvider");function y3e(e){const s=(0,m.useContext)(v3e),n=s?.messages.find(a=>a.commentId===e);return n&&s?(0,t.jsx)(j3e,{message:n,publication:s.publications.find(a=>a.providerMessageId===n.providerMessageId),issueId:s.issueId}):null}r(y3e,"useEmailComment");function j3e({message:e,publication:s,issueId:n,contextNotice:a=!1}){const i=te({queryKey:["email-attachments",n],queryFn:r(()=>yt.listAttachments(n),"queryFn"),enabled:e.attachmentIds.length>0});return(0,t.jsxs)("article",{"aria-label":e.direction==="inbound"?"Email received":"Email sent",className:a?"task-context-notice space-y-3":"space-y-4 rounded-xl border border-border bg-card p-5",children:[(0,t.jsxs)("div",{className:"flex flex-wrap items-center justify-between gap-2",children:[(0,t.jsxs)("span",{className:"flex items-center gap-2 text-sm font-semibold",children:[(0,t.jsx)($Q,{className:"size-4"}),e.direction==="inbound"?"Email received":"Email sent"]}),(0,t.jsx)("span",{className:"text-xs text-muted-foreground",children:new Date(e.timestamp).toLocaleString()})]}),(0,t.jsxs)("div",{className:"space-y-1",children:[(0,t.jsxs)("p",{className:"text-sm font-medium",children:[e.from,e.direction==="inbound"&&(0,t.jsx)("span",{className:"ml-2 rounded-md bg-muted px-2 py-1 text-xs text-muted-foreground",children:"External"})]}),(0,t.jsxs)("p",{className:"break-words text-xs text-muted-foreground",children:["To: ",e.to.join(", ")]}),!!e.cc?.length&&(0,t.jsxs)("p",{className:"break-words text-xs text-muted-foreground",children:["Cc: ",e.cc.join(", ")]}),(0,t.jsx)("p",{className:"text-sm font-semibold",children:e.subject})]}),(0,t.jsx)("div",{className:"whitespace-pre-wrap break-words text-sm",children:e.text||"(No text body)"}),!!e.attachmentIds.length&&(0,t.jsx)("div",{className:"flex flex-wrap gap-2",children:e.attachmentIds.map(o=>{const l=i.data?.find(c=>c.id===o);return(0,t.jsxs)("a",{href:`/api/attachments/${o}/content`,target:"_blank",rel:"noreferrer",className:"flex items-center gap-2 rounded-md border border-border px-3 py-2 text-xs",children:[(0,t.jsx)(kl,{className:"size-3.5"}),l?.originalFilename??"Open attachment"]},o)})}),(0,t.jsxs)("details",{className:"text-xs text-muted-foreground",children:[(0,t.jsx)("summary",{className:"cursor-pointer",children:"Email details"}),(0,t.jsxs)("div",{className:"space-y-2 pt-3",children:[!!e.bcc?.length&&(0,t.jsxs)("p",{children:["Bcc: ",e.bcc.join(", ")]}),(0,t.jsxs)("p",{className:"break-all",children:["Message ID: ",e.providerMessageId]}),e.fullText!==e.text&&(0,t.jsx)("div",{className:"whitespace-pre-wrap break-words",children:e.fullText})]})]}),s&&(0,t.jsxs)("p",{className:"border-t border-border pt-3 text-xs text-muted-foreground",children:[s.outcome==="delivered"?"Delivered":s.outcome==="failed"?"Delivery failed":s.outcome==="uncertain"?"Delivery uncertain":s.outcome==="queued"?"Queued":"Sent",s.error?` · ${s.error}`:""]}),i.error&&(0,t.jsx)("p",{role:"alert",className:"text-xs text-destructive",children:"Attachments could not be loaded."})]})}r(j3e,"EmailMessageCard");var Jy=(0,m.createContext)(null);function aw({items:e,initialIndex:s,open:n,onOpenChange:a}){const[i,o]=(0,m.useState)(s),l=(0,m.useRef)(null),c=(0,m.useCallback)(g=>{l.current=g},[]);(0,m.useEffect)(()=>{n&&o(s)},[n,s]);const d=(0,m.useCallback)(()=>{o(g=>(g+1)%e.length)},[e.length]),u=(0,m.useCallback)(()=>{o(g=>(g-1+e.length)%e.length)},[e.length]);(0,m.useEffect)(()=>{i<e.length||o(0)},[i,e.length]),(0,m.useEffect)(()=>{if(!n)return;const g=r(v=>{v.key==="ArrowRight"?d():v.key==="ArrowLeft"?u():v.key==="Escape"&&a(!1)},"handler");return window.addEventListener("keydown",g),()=>window.removeEventListener("keydown",g)},[n,d,u,a]);const h=(0,m.useCallback)(g=>{const v=g.target;v.closest("button")||v.closest("a")||v===l.current||a(!1)},[a]);if(e.length===0)return null;const p=e[i];if(!p)return null;const f=sg(p),x=ym(p.contentType,p.originalFilename);return(0,t.jsx)(fze,{open:n,onOpenChange:a,children:(0,t.jsxs)(hze,{children:[(0,t.jsx)(mze,{className:"fixed inset-0 z-50 bg-black/90 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 duration-200"}),(0,t.jsxs)(pze,{className:"fixed inset-0 z-50 flex flex-col outline-none data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 duration-200",onClick:h,children:[(0,t.jsxs)("div",{className:"flex items-center justify-between px-5 py-3 text-white/80 text-sm shrink-0",children:[(0,t.jsx)("span",{className:"truncate max-w-(--pct-50) font-medium",title:f,children:f}),(0,t.jsxs)("div",{className:"flex items-center gap-4",children:[(0,t.jsxs)("span",{className:"text-white/40 tabular-nums text-xs",children:[i+1," / ",e.length]}),(0,t.jsx)("a",{href:I2(p),download:f,className:"text-white/50 hover:text-white transition-colors",title:"Download","aria-label":`Download ${f}`,onClick:r(g=>g.stopPropagation(),"onClick"),children:(0,t.jsx)(Fi,{className:"h-4.5 w-4.5"})}),(0,t.jsx)("button",{type:"button",onClick:r(()=>a(!1),"onClick"),className:"text-white/50 hover:text-white transition-colors",title:"Close",children:(0,t.jsx)(Mn,{className:"h-5 w-5"})})]})]}),(0,t.jsxs)("div",{className:"flex-1 flex items-center min-h-0",children:[(0,t.jsx)("div",{className:"w-16 md:w-24 shrink-0 flex items-center justify-center h-full",children:e.length>1&&(0,t.jsx)("button",{type:"button",onClick:u,className:"rounded-full bg-white/10 p-3 text-white/60 hover:text-white hover:bg-white/20 transition-colors",title:"Previous",children:(0,t.jsx)(xm,{className:"h-7 w-7"})})}),(0,t.jsx)("div",{className:"flex-1 flex items-center justify-center min-w-0 min-h-0 h-full px-2",children:x?(0,t.jsx)("video",{ref:c,src:p.contentPath,className:"max-w-full max-h-full rounded-lg",controls:!0,playsInline:!0}):(0,t.jsx)("img",{ref:c,src:p.contentPath,alt:f,className:"max-w-full max-h-full object-contain select-none rounded-lg",draggable:!1})}),(0,t.jsx)("div",{className:"w-16 md:w-24 shrink-0 flex items-center justify-center h-full",children:e.length>1&&(0,t.jsx)("button",{type:"button",onClick:d,className:"rounded-full bg-white/10 p-3 text-white/60 hover:text-white hover:bg-white/20 transition-colors",title:"Next",children:(0,t.jsx)(Ln,{className:"h-7 w-7"})})})]}),(0,t.jsx)("div",{className:"h-6 shrink-0"})]})]})})}r(aw,"ImageGalleryModal");function $v(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:{}}r($v,"record$6");var w3e=(0,m.createContext)(null);function k3e(e){const s=(0,m.useContext)(w3e);return s&&e?.sourceRunId===s.runId&&e.sections.some(n=>n.rows.some(a=>a.type==="key_value"&&a.value===s.actionId))?s:null}r(k3e,"useWorkspaceBaseRefRecovery");function dft({issue:e,agentMap:s,unavailableReason:n,onRepaired:a,children:i}){const o=e.activeRecoveryAction,l=o?.cause==="configuration_incomplete"&&typeof o.evidence.latestRunId=="string"?o.evidence.latestRunId:null,{data:c}=te({queryKey:["workspace-base-ref-recovery",e.companyId,e.id,l],queryFn:r(()=>ea.get(l),"queryFn"),enabled:!!l,staleTime:1/0,retry:!1}),d=$v($v(c?.resultJson).configurationIncomplete);let u=null;if(o&&l&&c?.companyId===e.companyId&&$v(c.contextSnapshot).issueId===e.id&&d.reason==="workspace_base_ref_unresolved"&&typeof d.requestedRef=="string"){const h=e.assigneeAgentId?s.get(e.assigneeAgentId):void 0,p=d.requestedRef,f=e.project?.workspaces?.find(y=>y.id===e.projectWorkspaceId)??e.project?.primaryWorkspace;let x="The task’s repository";if(f?.repoUrl)try{const y=new URL(f.repoUrl);(y.protocol==="https:"||y.protocol==="http:")&&(x=`${y.hostname}${y.pathname.replace(/\.git$/,"")}`)}catch{}const g=$v($v(e.executionWorkspaceSettings).workspaceStrategy).baseRef,v=o.status!=="active"||e.status!=="blocked"||e.assigneeAgentId!==o.returnOwnerAgentId||c.agentId!==e.assigneeAgentId||typeof g=="string"&&g.trim()&&g!==p?"This repair no longer matches the task. Refresh to review its current state.":n??(e.executionRunId||e.checkoutRunId?"Wait for the current run to finish.":null)??(h?.status==="paused"||h?.status==="terminated"?"The assigned agent is unavailable.":null)??(e.executionState?.status==="pending"?"Complete the pending review or approval before retrying.":null)??(e.blockedBy?.some(y=>y.status!=="done"&&y.status!=="cancelled")?"Resolve the task’s blockers before retrying.":null);u={actionId:o.id,runId:l,props:{requestedRef:p,repository:x,taskOverride:g===p,defaultBranch:typeof d.defaultBranch=="string"?d.defaultBranch:null,agentName:h?.name??"The assigned agent",unavailableReason:v,failureKind:typeof d.fetchError=="string"&&d.fetchError.includes(`couldn't find remote ref refs/heads/${p}`)?"missing_branch":"unresolved_ref",onRepair:r(async y=>{try{const k=await yt.resolveRecoveryAction(e.id,{actionId:o.id,outcome:"restored",sourceIssueStatus:"todo",workspaceBaseRef:{requestedRef:p,branch:y}});if(k.issue.status!=="todo"||k.issue.assigneeAgentId!==e.assigneeAgentId||$v($v(k.issue.executionWorkspaceSettings).workspaceStrategy).baseRef!==y)throw new Error("The task changed while saving. Refresh to check its current state.")}finally{a()}},"onRepair")}}}return(0,t.jsx)(w3e.Provider,{value:u,children:i})}r(dft,"WorkspaceBaseRefRecoveryProvider");var N3e={neutral:{container:"border-border bg-muted/35 dark:bg-muted/20",iconWrap:"bg-muted text-foreground/70",icon:s0,iconClass:"text-muted-foreground",label:"text-muted-foreground",divider:"border-border/70"},info:{container:"border-sky-300/70 bg-sky-50/70 dark:border-sky-500/30 dark:bg-sky-500/10",iconWrap:"bg-sky-100 text-sky-700 dark:bg-sky-500/20 dark:text-sky-200",icon:s0,iconClass:"text-sky-700 dark:text-sky-300",label:"text-sky-800 dark:text-sky-200",divider:"border-sky-300/50 dark:border-sky-500/30"},success:{container:"border-emerald-300/70 bg-emerald-50/70 dark:border-emerald-500/30 dark:bg-emerald-500/10",iconWrap:"bg-emerald-100 text-emerald-700 dark:bg-emerald-500/20 dark:text-emerald-200",icon:fa,iconClass:"text-emerald-700 dark:text-emerald-300",label:"text-emerald-800 dark:text-emerald-200",divider:"border-emerald-300/50 dark:border-emerald-500/30"},warning:{container:"border-amber-300/70 bg-amber-50/80 dark:border-amber-500/30 dark:bg-amber-500/10",iconWrap:"bg-amber-100 text-amber-800 dark:bg-amber-500/20 dark:text-amber-200",icon:Es,iconClass:"text-amber-700 dark:text-amber-300",label:"text-amber-900 dark:text-amber-200",divider:"border-amber-300/60 dark:border-amber-500/30"},danger:{container:"border-red-400/60 bg-red-50/80 dark:border-red-500/35 dark:bg-red-500/10",iconWrap:"bg-red-100 text-red-700 dark:bg-red-500/20 dark:text-red-200",icon:oN,iconClass:"text-red-700 dark:text-red-300",label:"text-red-900 dark:text-red-200",divider:"border-red-400/50 dark:border-red-500/30"}};function uft(e){try{return new Date(e).toLocaleString(void 0,{month:"short",day:"numeric",hour:"numeric",minute:"2-digit"})}catch{return e}}r(uft,"formatTimestamp$1");function mft({row:e,tone:s}){return(0,t.jsxs)("div",{className:"grid grid-cols-(--gtc-8) gap-x-3 gap-y-0.5 px-3 py-1.5 text-xs",children:[(0,t.jsx)("div",{className:"truncate text-(length:--text-micro) font-medium uppercase tracking-(--tracking-label) text-muted-foreground",children:e.label}),(0,t.jsx)("div",{className:"min-w-0 break-words text-foreground/90",children:(()=>{switch(e.kind){case"text":return(0,t.jsx)("span",{children:e.value});case"code":return(0,t.jsx)("code",{className:"rounded bg-muted px-1.5 py-0.5 font-mono text-(length:--text-micro) text-foreground/80",children:e.value});case"issue":{const n=(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)("span",{children:e.identifier}),e.title?(0,t.jsxs)("span",{className:"text-muted-foreground",children:["— ",e.title]}):null]});return e.href?(0,t.jsx)("a",{href:e.href,className:W("inline-flex items-center gap-1 rounded-sm font-medium underline-offset-2 hover:underline",s.label),children:n}):(0,t.jsx)("span",{className:W("inline-flex items-center gap-1 font-medium",s.label),children:n})}case"agent":return e.href?(0,t.jsx)("a",{href:e.href,className:W("inline-flex items-center gap-1 rounded-sm font-medium underline-offset-2 hover:underline",s.label),children:e.name}):(0,t.jsx)("span",{className:W("font-medium",s.label),children:e.name});case"run":{const n=e.runId.length>12?`${e.runId.slice(0,8)}…`:e.runId,a=(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)("code",{className:"rounded bg-muted px-1.5 py-0.5 text-foreground/80",children:n}),e.status?(0,t.jsx)("span",{className:W("font-sans",s.label),children:e.status}):null]});return e.href?(0,t.jsx)("a",{href:e.href,className:"inline-flex items-center gap-2 rounded-sm font-mono text-(length:--text-micro) underline-offset-2 hover:underline",children:a}):(0,t.jsx)("span",{className:"inline-flex items-center gap-2 font-mono text-(length:--text-micro)",children:a})}}})()})]})}r(mft,"MetadataRow$1");function $V({sections:e,tone:s="neutral"}){const n=N3e[s];return(0,t.jsx)("div",{className:"divide-y divide-border/50 px-1 py-1",children:e.map((a,i)=>(0,t.jsxs)("div",{className:"py-1.5 first:pt-2 last:pb-2",children:[a.title?(0,t.jsx)("div",{className:"px-3 pb-1 pt-0.5 text-(length:--text-nano) font-semibold uppercase tracking-(--tracking-caps) text-muted-foreground",children:a.title}):null,(0,t.jsx)("div",{children:a.rows.map((o,l)=>(0,t.jsx)(mft,{row:o,tone:n},l))})]},i))})}r($V,"SystemNoticeMetadataSections");function OV({tone:e="neutral",label:s,body:n,source:a,metadata:i,detailsDefaultOpen:o=!1,timestamp:l,className:c}){const d=N3e[e],u=d.icon,[h,p]=(0,m.useState)(o),f=(0,m.useId)(),x=!!(i&&i.length>0),g=s??{neutral:"System notice",info:"System notice",success:"System notice",warning:"System warning",danger:"System alert"}[e];return(0,t.jsxs)("section",{role:"status","aria-label":g,className:W("relative w-full overflow-hidden rounded-lg border text-sm shadow-(--shadow-extract-8)",d.container,c),children:[(0,t.jsxs)("header",{className:"flex items-start gap-3 px-3 py-2.5 sm:px-4",children:[(0,t.jsx)("span",{className:W("mt-0.5 flex h-7 w-7 shrink-0 items-center justify-center rounded-md",d.iconWrap),"aria-hidden":!0,children:(0,t.jsx)(u,{className:W("h-4 w-4",d.iconClass)})}),(0,t.jsxs)("div",{className:"min-w-0 flex-1",children:[(0,t.jsxs)("div",{className:"flex flex-wrap items-center gap-x-2 gap-y-0.5 text-(length:--text-micro) font-semibold uppercase tracking-(--tracking-eyebrow)",children:[(0,t.jsx)("span",{className:d.label,children:g}),a?(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)("span",{className:"text-muted-foreground/60","aria-hidden":!0,children:"·"}),a.href?(0,t.jsx)("a",{href:a.href,className:"rounded-sm font-medium normal-case tracking-normal text-muted-foreground underline-offset-2 hover:text-foreground hover:underline",children:a.label}):(0,t.jsx)("span",{className:"font-medium normal-case tracking-normal text-muted-foreground",children:a.label})]}):null,l?(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)("span",{className:"text-muted-foreground/60","aria-hidden":!0,children:"·"}),(0,t.jsx)("span",{className:"font-medium normal-case tracking-normal text-muted-foreground",children:uft(l)})]}):null]}),(0,t.jsx)("div",{className:"mt-1 break-words text-sm leading-6 text-foreground",children:n})]}),x?(0,t.jsxs)("button",{type:"button",onClick:r(()=>p(v=>!v),"onClick"),"aria-expanded":h,"aria-controls":f,className:W("ml-1 inline-flex h-7 shrink-0 items-center gap-1 rounded-md border border-transparent px-2 text-(length:--text-micro) font-medium uppercase tracking-(--tracking-eyebrow) text-muted-foreground transition-(--tp-background-color-border-color-color)","hover:border-border/70 hover:bg-background/70 hover:text-foreground","focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring/50"),children:[(0,t.jsx)("span",{children:h?"Hide details":"Details"}),(0,t.jsx)(an,{className:W("h-3.5 w-3.5 transition-transform duration-150",h&&"rotate-180")})]}):null]}),x&&h?(0,t.jsx)("div",{id:f,className:W("border-t bg-background/50 dark:bg-background/30",d.divider),children:(0,t.jsx)($V,{sections:i,tone:e})}):null]})}r(OV,"SystemNotice");function S3e({requestedRef:e,repository:s,defaultBranch:n,agentName:a,configuredBy:i,taskOverride:o=!0,failureKind:l="unresolved_ref",unavailableReason:c,onRepair:d}){const u=(0,m.useId)(),[h,p]=(0,m.useState)(!n),[f,x]=(0,m.useState)(n??""),[g,v]=(0,m.useState)(!1),[y,k]=(0,m.useState)(!1),[w,N]=(0,m.useState)(null),[S,C]=(0,m.useState)(null),_=(0,m.useRef)(!1),R=f.trim().length>0&&f.trim()!==e;async function I(T){const E=T.trim();if(!(!E||E===e||c||_.current||S)){if(!FOe(E)){N("Enter a valid branch name, such as master or release/next.");return}_.current=!0,k(!0),N(null);try{await d(E),C(E)}catch(P){N(P instanceof Error?P.message:"Refresh the task to check its current state, then try again.")}finally{_.current=!1,k(!1)}}}return r(I,"repair"),(0,t.jsxs)("section",{"aria-labelledby":`${u}-title`,className:"flex min-w-0 gap-3 rounded-lg border border-border bg-muted/20 p-4","data-testid":"workspace-base-ref-recovery",children:[S?(0,t.jsx)(ms,{"aria-hidden":!0,className:"mt-0.5 size-4 shrink-0 text-(--status-task-icon-done)"}):(0,t.jsx)(Es,{"aria-hidden":!0,className:"mt-0.5 size-4 shrink-0 text-(--status-task-icon-blocked)"}),(0,t.jsxs)("div",{className:"flex min-w-0 flex-1 flex-col gap-3",children:[(0,t.jsxs)("div",{className:"flex flex-col gap-1",role:"status","aria-live":"polite",children:[(0,t.jsx)("h2",{id:`${u}-title`,className:"break-words text-sm font-semibold",children:S?"Branch updated · retry requested":l==="missing_branch"?(0,t.jsxs)(t.Fragment,{children:["Branch ",(0,t.jsx)("code",{className:"font-mono",children:e})," was not found"]}):(0,t.jsxs)(t.Fragment,{children:["Couldn’t use branch ",(0,t.jsx)("code",{className:"font-mono",children:e})]})}),(0,t.jsx)("p",{className:"text-sm leading-relaxed text-muted-foreground",children:S?(0,t.jsxs)(t.Fragment,{children:["This task now starts from ",(0,t.jsx)("code",{className:"font-mono text-foreground",children:S}),". A retry has been requested for ",a,"."]}):(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)("span",{className:"break-all text-foreground",children:s}),l==="missing_branch"?(0,t.jsxs)(t.Fragment,{children:[" has no branch named ",(0,t.jsx)("code",{className:"font-mono text-foreground",children:e}),"."]}):" could not resolve the starting branch. Check the branch name and repository access."," ",a," hasn’t started."]})})]}),!S&&(0,t.jsxs)(t.Fragment,{children:[n&&!h&&(0,t.jsxs)("p",{className:"flex flex-wrap items-center gap-1.5 text-sm",children:[(0,t.jsx)(Xi,{"aria-hidden":!0,className:"size-4 text-muted-foreground"}),(0,t.jsx)("code",{className:"font-mono",children:n}),(0,t.jsx)("span",{className:"text-muted-foreground",children:"is the repository’s default branch."})]}),(0,t.jsx)("p",{className:"text-xs text-muted-foreground",children:"Changes only this task’s starting branch."}),c&&(0,t.jsx)("p",{id:`${u}-unavailable`,className:"text-sm text-muted-foreground",children:c}),w&&(0,t.jsxs)("p",{role:"alert",id:`${u}-error`,className:"text-sm text-destructive",children:["Couldn’t confirm the repair. ",w]}),h?(0,t.jsxs)("form",{className:"flex flex-col gap-3",onSubmit:r(T=>{T.preventDefault(),I(f)},"onSubmit"),children:[(0,t.jsxs)("div",{className:"flex flex-col gap-1.5",children:[(0,t.jsx)($s,{htmlFor:`${u}-branch`,children:"Starting branch"}),(0,t.jsx)(dt,{id:`${u}-branch`,autoFocus:!0,value:f,disabled:y||!!c,onChange:r(T=>x(T.target.value),"onChange"),placeholder:"Branch name",className:"font-mono","aria-describedby":w?`${u}-error`:void 0,autoComplete:"off",spellCheck:!1})]}),(0,t.jsxs)("div",{className:"flex flex-wrap items-center justify-between gap-2",children:[n?(0,t.jsx)($,{type:"button",variant:"ghost",size:"sm",disabled:y,onClick:r(()=>{p(!1),N(null)},"onClick"),children:"Cancel"}):(0,t.jsx)("span",{}),(0,t.jsxs)($,{type:"submit",size:"sm",disabled:y||!R||!!c,"aria-describedby":c?`${u}-unavailable`:void 0,children:[y&&(0,t.jsx)(st,{"aria-hidden":!0,className:"size-3.5 animate-spin motion-reduce:animate-none"}),y?"Saving & requesting retry…":"Save branch & retry"]})]})]}):(0,t.jsxs)("div",{className:"flex flex-wrap items-center justify-between gap-2",children:[(0,t.jsx)($,{type:"button",variant:"ghost",size:"sm",disabled:y||!!c,onClick:r(()=>p(!0),"onClick"),children:"Choose another branch"}),(0,t.jsxs)($,{type:"button",size:"sm",disabled:y||!!c||n===e,"aria-describedby":c?`${u}-unavailable`:void 0,onClick:r(()=>{I(n)},"onClick"),children:[y&&(0,t.jsx)(st,{"aria-hidden":!0,className:"size-3.5 animate-spin motion-reduce:animate-none"}),y?"Saving & requesting retry…":`Use ${n} & retry`]})]})]}),(0,t.jsxs)("div",{children:[(0,t.jsxs)($,{type:"button",variant:"ghost",size:"xs",className:"text-muted-foreground","aria-expanded":g,"aria-controls":`${u}-details`,onClick:r(()=>v(T=>!T),"onClick"),children:[g?"Hide details":"Why did this happen?",(0,t.jsx)(an,{"aria-hidden":!0,className:W("size-3",g&&"rotate-180")})]}),g&&(0,t.jsx)("div",{id:`${u}-details`,className:"mt-2 rounded-md border border-border bg-background",children:(0,t.jsx)($V,{tone:"neutral",sections:[{rows:[{kind:"text",label:"Setting",value:o?"Task-specific starting branch":"Workspace starting branch"},{kind:"code",label:"Requested branch",value:e},...i?[{kind:"text",label:"Set by",value:i}]:[],{kind:"text",label:"Why it stopped",value:o?"An explicit task branch overrides the repository default. Paperclip does not silently switch branches.":"The configured starting branch must resolve before the agent can start. This repair overrides it for this task."}]}]})})]})]})]})}r(S3e,"WorkspaceBaseRefRecoveryNotice");var BV=(0,m.createContext)(null);function hft({value:e,children:s}){return(0,t.jsx)(BV.Provider,{value:e,children:s})}r(hft,"DispositionRecoveryProvider");function pft(e,s){if(e?.recovery?.kind==="disposition_repair_escalated")return e.recovery;if(!e||!s||s.kind!=="deliberate_wait_without_target"||s.ownerType!=="board"||s.wakePolicy?.type!=="board_escalation")return null;const n=s.evidence;return!e.sourceRunId||e.sourceRunId!==n?.latestRunId||!e.sections.some(a=>a.rows.some(i=>i.type==="key_value"&&i.value===s.id))||typeof n.terminalReason!="string"||typeof n.sourceAttemptCount!="number"||!Number.isInteger(n.sourceAttemptCount)||n.sourceAttemptCount<0||typeof n.sourceMaxAttempts!="number"||!Number.isInteger(n.sourceMaxAttempts)||n.sourceMaxAttempts<=0?null:{kind:"disposition_repair_escalated",actionId:s.id,attemptCount:n.sourceAttemptCount,maxAttempts:n.sourceMaxAttempts,reason:n.terminalReason,assigneeAgentId:s.returnOwnerAgentId}}r(pft,"readDispositionRecoverySnapshot");function C3e(e){return pft(e,(0,m.useContext)(BV)?.issue.activeRecoveryAction)}r(C3e,"useDispositionRecoverySnapshot");function fft(e,s){if(!s)return"Open the task to review its current state.";const{issue:n}=s,a=n.activeRecoveryAction;if(!a||a.id!==e.actionId||a.status!=="active")return"This recovery notice is no longer active.";if(n.status!=="blocked")return"The task’s state has changed. Review its current state before retrying.";if(a.kind!=="deliberate_wait_without_target"||a.ownerType!=="board"||a.wakePolicy?.type!=="board_escalation")return"The task’s recovery state has changed. Refresh to see the current action.";if(!e.assigneeAgentId||n.assigneeAgentId!==e.assigneeAgentId||a.returnOwnerAgentId!==e.assigneeAgentId)return"The assigned agent has changed. Review the task before retrying.";if(s.unavailableReason)return s.unavailableReason;if(s.hasPendingInteraction)return"Respond to the pending question or confirmation before retrying.";if(n.executionRunId||n.checkoutRunId)return"The task already has an active run. Wait for it to finish.";if(n.executionState?.status==="pending")return"The task is waiting for a review or approval.";if(n.blockedBy?.some(o=>o.status!=="done"&&o.status!=="cancelled"))return"Resolve the task’s blockers before retrying.";const i=s.agentMap?.get(e.assigneeAgentId);return i?.status==="paused"?"The assigned agent is paused. Resume the agent before retrying.":i?.status==="terminated"?"The assigned agent is no longer available.":null}r(fft,"dispositionRetryUnavailableReason");function xft(e){const s="The agent stopped without recording an outcome or a next step.";return e.reason==="owner_budget_blocked"?`${s} Automatic recovery stopped because a spending or pause limit prevents the agent from running.`:e.reason==="owner_not_invokable"?`${s} Automatic recovery stopped because the assigned agent is unavailable.`:e.reason==="unchanged_source_state_exhausted"?`${s} ${e.attemptCount===2?"Two":String(e.attemptCount)} automatic ${e.attemptCount===1?"attempt":"attempts"} to resolve this failed.`:`${s} Automatic recovery stopped. Review the details before trying again.`}r(xft,"descriptionFor");function FV({snapshot:e,createdAt:s,defaultExpanded:n=!1}){const a=(0,m.useContext)(BV),[i,o]=(0,m.useState)(n),[l,c]=(0,m.useState)(!1),[d,u]=(0,m.useState)(!1),[h,p]=(0,m.useState)(null),f=(0,m.useRef)(!1),x=(0,m.useId)(),g=(0,m.useId)(),v=(0,m.useId)(),y=fft(e,a),k=!!(a&&a.issue.activeRecoveryAction?.id!==e.actionId),w=e.assigneeAgentId&&a?.agentMap?.get(e.assigneeAgentId)?.name||"the assigned agent",N=d||k?ms:Es;async function S(){if(!(!a||y||f.current)){f.current=!0,c(!0),p(null);try{await a.onRetry(e.actionId),u(!0)}catch(C){p(C instanceof Error?C.message:"Refresh the task to check its current state, then try again.")}finally{f.current=!1,c(!1)}}}return r(S,"retry"),(0,t.jsxs)("section",{"aria-labelledby":g,className:"flex min-w-0 gap-2.5 py-3","data-testid":"disposition-recovery-notice",children:[(0,t.jsx)(N,{"aria-hidden":"true",className:W("mt-0.5 size-4 shrink-0",d||k?"text-muted-foreground":"text-(--status-task-icon-todo)")}),(0,t.jsxs)("div",{className:"flex min-w-0 flex-1 flex-col gap-2",children:[(0,t.jsxs)("div",{className:"flex flex-col gap-1",role:"status","aria-live":"polite",children:[(0,t.jsx)("h2",{id:g,className:"break-words text-sm font-medium text-foreground",children:d?"Retry requested":k?"Agent needed attention":"Agent needs attention"}),(0,t.jsx)("p",{className:"text-sm leading-relaxed text-muted-foreground",children:d?`The task was returned to To do for ${w}.`:xft(e)})]}),y&&!d?(0,t.jsxs)("p",{id:v,className:"text-xs leading-relaxed text-muted-foreground",children:[!k&&(0,t.jsx)("span",{className:"font-medium text-foreground",children:"Retry unavailable. "}),y]}):null,h?(0,t.jsxs)("p",{role:"alert",className:"text-sm text-destructive",children:["Couldn’t confirm the retry. ",h]}):null,(0,t.jsxs)("div",{className:"flex flex-wrap items-center gap-2",children:[!d&&!k?(0,t.jsxs)($,{size:"xs",variant:"outline",disabled:l||!!y,"aria-describedby":y?v:void 0,onClick:r(()=>{S()},"onClick"),children:[l?(0,t.jsx)(st,{"aria-hidden":"true",className:"size-3 animate-spin motion-reduce:animate-none"}):(0,t.jsx)(Ai,{"aria-hidden":"true",className:"size-3"}),l?"Requesting retry…":"Retry agent"]}):null,(0,t.jsxs)($,{size:"xs",variant:"ghost",className:"text-muted-foreground","aria-expanded":i,"aria-controls":x,onClick:r(()=>o(C=>!C),"onClick"),children:[i?"Hide details":"View details",(0,t.jsx)(an,{"aria-hidden":"true",className:W("size-3",i&&"rotate-180")})]}),s?(0,t.jsx)("time",{dateTime:s,className:"font-mono text-xs text-muted-foreground sm:ml-auto",children:io(s)}):null]}),i?(0,t.jsxs)("div",{id:x,className:"flex flex-col gap-3 rounded-lg border border-border bg-muted/20 p-3",children:[(0,t.jsxs)("dl",{className:"flex flex-col gap-2 text-xs",children:[(0,t.jsxs)("div",{className:"flex flex-wrap justify-between gap-1",children:[(0,t.jsx)("dt",{className:"text-muted-foreground",children:"Assigned when recovery stopped"}),(0,t.jsx)("dd",{children:w})]}),(0,t.jsxs)("div",{className:"flex flex-wrap justify-between gap-1",children:[(0,t.jsx)("dt",{className:"text-muted-foreground",children:"Automatic attempts"}),(0,t.jsxs)("dd",{className:"font-mono",children:[e.attemptCount," of ",e.maxAttempts]})]}),(0,t.jsxs)("div",{className:"flex flex-wrap justify-between gap-1",children:[(0,t.jsx)("dt",{className:"text-muted-foreground",children:"Automatic retries for this recovery"}),(0,t.jsx)("dd",{children:"Stopped"})]})]}),(0,t.jsx)("p",{className:"text-xs leading-relaxed text-muted-foreground",children:"Recovery asked the assigned agent to record an outcome or a next step. Retrying keeps the same task and agent, and checks the task’s current controls before continuing."}),(0,t.jsxs)("div",{className:"flex flex-col gap-1",children:[(0,t.jsx)("span",{className:"text-xs text-muted-foreground",children:"Technical reason"}),(0,t.jsx)("code",{className:"break-all font-mono text-xs",children:e.reason})]})]}):null]})]})}r(FV,"DispositionRecoveryNotice");var gft="System update",bft=80;function vft(e){const s=e.match(/Latest retry failure: `([^`]+)`/);return s?s[1]:null}r(vft,"retryFailureCode");function yft(e){const s=e.match(/Recovery owner: \[([^\]]+)\]\(/)?.[1]?.trim();return s&&s.length>0?s:null}r(yft,"recoveryOwnerName");function jft(e){const s=e.split(`
382
+ `)}`:void 0}r(Kht,"sanitizeComponentStack");function _5e(){const e={};if(typeof document<"u"){try{const s=document.readyState;(s==="loading"||s==="interactive"||s==="complete")&&(e.ready_state=s)}catch{}try{const s=document.visibilityState;(s==="visible"||s==="hidden")&&(e.visibility_state=s)}catch{}try{const s=document.documentElement.classList;e.translation_marker=s.contains("translated-ltr")||s.contains("translated-rtl")}catch{}}return e}r(_5e,"readBrowserErrorState");function Qht(e){const s=Kht(e.componentStack);return{tags:{react_error_boundary:e.boundary},contexts:{react:s?{componentStack:s}:{},browser_state:_5e()}}}r(Qht,"buildBrowserErrorContext");var Iae=Promise.resolve();function EV(e){const s=Iae.then(e);return Iae=s.catch(()=>{}),s}r(EV,"enqueue");var _N=null;function Wht(e,s){return EV(async()=>{if(!_N)try{const n=await bd(()=>import("./prod-COP_vZWu.js"),__vite__mapDeps([4,5]));n.init(Vht(e,s)),_N=n}catch{}})}r(Wht,"initBrowserErrorMonitoring");function Hht(){return EV(async()=>{const e=_N;if(_N=null,!e)return;const s=e.getClient();try{e.getCurrentScope().setClient(void 0)}catch{}try{await s?.close(2e3)}catch{}})}r(Hht,"teardownBrowserErrorMonitoring");function LV(e,s){let n;try{s&&(n=Qht(s))}catch{}EV(async()=>{try{n?_N?.captureException(e,n):_N?.captureException(e)}catch{}})}r(LV,"captureBrowserException");function Vht(e,s){return{dsn:e,environment:s??void 0,release:"fef514f6c2865c257e6d1eecba5547410b41c3c5",tracesSampleRate:0,sendDefaultPii:!1,beforeSend:r((n,a)=>{try{if(n.contexts={...n.contexts,browser_state:n.contexts?.browser_state??_5e()},n.tags={...n.tags,browser_build_mode:"production"},n.exception?.values?.some(i=>i.mechanism?.type==="onunhandledrejection"||i.mechanism?.type==="auto.browser.global_handlers.onunhandledrejection")){const i=a.originalException;n.tags.browser_rejection_kind=i===null?"null":typeof i}}catch{}return n},"beforeSend"),integrations:r(n=>n.filter(a=>a.name!=="HttpContext"&&a.name!=="Breadcrumbs"),"integrations")}}r(Vht,"buildBrowserSentryInitOptions");var Ght=class extends m.Component{static{r(this,"RouteErrorBoundaryInner")}state={error:null};static getDerivedStateFromError(e){return{error:e instanceof Error?e:new Error(String(e))}}componentDidCatch(e,s){LV(e,{boundary:"route",componentStack:s.componentStack})}componentDidUpdate(e){this.state.error&&e.resetKey!==this.props.resetKey&&this.setState({error:null})}render(){const{error:e}=this.state;return e?(0,t.jsxs)("div",{className:"mx-auto max-w-2xl space-y-4 px-4 py-10",children:[(0,t.jsxs)("div",{children:[(0,t.jsx)("h1",{className:"text-lg font-semibold",children:"This page hit an error"}),(0,t.jsx)("p",{className:"mt-1 text-sm text-muted-foreground",children:"Something went wrong while rendering this page. You can go back and try again, or reload."})]}),(0,t.jsx)("pre",{className:"overflow-auto rounded-md border border-destructive/30 bg-destructive/10 px-3 py-2 text-xs text-destructive whitespace-pre-wrap",children:e.message}),(0,t.jsxs)("div",{className:"flex items-center gap-2",children:[(0,t.jsx)($,{variant:"outline",size:"sm",onClick:this.props.onReset,children:"Go back"}),(0,t.jsx)($,{size:"sm",onClick:r(()=>window.location.reload(),"onClick"),children:"Reload page"})]})]}):this.props.children}};function A5e({children:e}){const s=la(),n=Gn(),a=`${s.pathname}${s.search}`;return(0,t.jsx)(Ght,{resetKey:a,onReset:r(()=>n(-1),"onReset"),children:e})}r(A5e,"RouteErrorBoundary");var Tae={bot:ao,cpu:Vm,brain:Lx,zap:yR,rocket:ABe,code:kbe,terminal:ff,shield:p3,eye:eu,search:Yr,wrench:pf,hammer:h3,lightbulb:m3,sparkles:G0,star:V0,heart:fC,flame:FBe,bug:Ky,cog:ybe,database:d3,globe:wm,lock:ko,mail:$Q,"message-square":O0,"file-code":zl,"git-branch":Xi,package:t0,puzzle:Mx,target:H0,wand:SW,atom:fBe,"circuit-board":oKe,radar:wBe,swords:KKe,telescope:pBe,microscope:_Ke,crown:jL,gem:_be,hexagon:Jd,pentagon:RKe,fingerprint:pF},Yht="bot";function Zht(e){return e&&iOe.includes(e)?Tae[e]:Tae[Yht]}r(Zht,"getAgentIcon");function TE({icon:e,className:s}){const n=Zht(e);return(0,t.jsx)(n,{className:s})}r(TE,"AgentIcon");function I5e({open:e,onOpenChange:s,...n}){return(0,t.jsx)(Fs,{open:e,onOpenChange:s,children:(0,t.jsxs)(Qs,{"aria-describedby":void 0,className:"gap-0 overflow-hidden p-0 sm:max-w-md",children:[(0,t.jsxs)("div",{className:"px-4 pt-4 pb-3",children:[(0,t.jsx)(Ks,{children:"Chat with an agent"}),n.existingChatAgentIds&&(0,t.jsx)("p",{className:"mt-2 text-sm text-muted-foreground",children:"One conversation per agent. Pick up where you left off."})]}),(0,t.jsx)(Jht,{...n,onComplete:r(()=>s(!1),"onComplete")},String(e))]})})}r(I5e,"AgentChatPicker");function Jht({agents:e,onSelect:s,onComplete:n,loading:a,error:i,onRetry:o,existingChatAgentIds:l,renderAgentIcon:c}){const d=(0,m.useRef)(!1),u=(0,m.useRef)(null);(0,m.useEffect)(()=>(d.current=!0,()=>{d.current=!1,u.current?.abort()}),[]);const[h,p]=(0,m.useState)(""),[f,x]=(0,m.useState)(null),[g,v]=(0,m.useState)(null);async function y(k){if(f)return;x(k.id),v(null);const w=new AbortController;u.current=w;try{await s(k,w.signal),d.current&&n()}catch(N){v(N instanceof Error?N.message:"Couldn’t open chat. Try again.")}finally{x(null)}}return r(y,"selectAgent"),(0,t.jsxs)(f3,{children:[(0,t.jsx)(t2,{"aria-label":"Search agents by name or role",placeholder:"Search by name or role…",value:h,onValueChange:p}),g&&(0,t.jsx)("p",{role:"alert",className:"px-4 py-3 text-sm text-destructive",children:g}),f&&(0,t.jsx)("p",{role:"status",className:"sr-only",children:"Opening conversation…"}),i?(0,t.jsxs)("div",{role:"alert",className:"flex flex-col items-start gap-2 p-4 text-sm",children:[(0,t.jsx)("p",{children:"Couldn’t load agents. Try again."}),o&&(0,t.jsx)($,{variant:"outline",size:"sm",onClick:o,children:"Retry"})]}):a?(0,t.jsx)("p",{role:"status",className:"p-4 text-sm text-muted-foreground",children:"Loading agents…"}):(0,t.jsxs)(s2,{children:[(0,t.jsx)(n2,{children:(0,t.jsxs)("div",{className:"flex flex-col items-center gap-2 px-4",children:[(0,t.jsx)("span",{children:e.length?`No agents match “${h}”`:"No agents yet."}),e.length?(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)("span",{className:"text-xs text-muted-foreground",children:"Try another name or role."}),(0,t.jsx)($,{variant:"ghost",size:"sm",onClick:r(()=>p(""),"onClick"),children:"Clear search"})]}):(0,t.jsx)("span",{className:"text-xs text-muted-foreground",children:"Create an agent from the Agents page to start chatting."})]})}),(0,t.jsx)(Ju,{children:e.map(k=>(0,t.jsxs)(Xo,{value:k.id,keywords:[k.name,k.title??"",k.role],onSelect:r(()=>{y(k)},"onSelect"),disabled:f!==null,className:"gap-3 px-3 py-3",children:[c?c(k):(0,t.jsx)(TE,{icon:k.icon,className:"size-4 shrink-0"}),(0,t.jsxs)("span",{className:"flex min-w-0 flex-1 flex-col gap-0.5",children:[(0,t.jsx)("span",{className:"truncate font-medium",children:k.name}),(0,t.jsx)("span",{className:"truncate text-xs text-muted-foreground",children:k.title??k.role})]}),l&&(0,t.jsx)("span",{className:"shrink-0 text-xs text-muted-foreground",children:l.includes(k.id)?"Open chat":"New chat"}),k.status==="paused"&&(0,t.jsx)("span",{className:"text-xs text-(--status-agent-paused)",children:"Paused"}),k.status==="terminated"&&(0,t.jsx)("span",{className:"text-xs text-muted-foreground",children:"Terminated"}),k.status==="pending_approval"&&(0,t.jsx)("span",{className:"text-xs text-muted-foreground",children:"Awaiting approval"})]},k.id))})]})]})}r(Jht,"AgentChatPickerResults");function x6({agents:e,existingChatAgentIds:s,availableAgents:n=e,activeId:a,previews:i={},loading:o=!1,error:l,onRetry:c,initialSearch:d="",onSelect:u,onBrowse:h,onAddChat:p,historyLoading:f,historyError:x,onRetryHistory:g}){const v=Gn(),[y,k]=(0,m.useState)(!1),[w,N]=(0,m.useState)(d),S=(0,m.useRef)(null),C=(0,m.useId)(),_=w.trim().toLocaleLowerCase(),R=e.filter(T=>`${T.name} ${T.title??""} ${T.role}`.toLocaleLowerCase().includes(_));function I(){N(""),S.current?.focus()}return r(I,"focusSearch"),(0,t.jsxs)("aside",{"aria-labelledby":C,className:"flex h-full min-h-0 flex-col border-r border-border bg-background",children:[(0,t.jsxs)("div",{className:"flex shrink-0 flex-col gap-4 px-3 pb-4 pt-4",children:[(0,t.jsxs)("div",{className:"flex items-center justify-between gap-2",children:[(0,t.jsx)("h2",{id:C,className:"text-sm font-semibold",children:"Chat"}),(0,t.jsx)($,{variant:"outline",size:"icon-sm","aria-label":"Add chat",title:"Add chat",onClick:r(()=>k(!0),"onClick"),children:(0,t.jsx)(bn,{className:"size-4"})})]}),(0,t.jsxs)("div",{className:"relative",children:[(0,t.jsx)(Yr,{"aria-hidden":"true",className:"pointer-events-none absolute left-3 top-1/2 size-3.5 -translate-y-1/2 text-muted-foreground"}),(0,t.jsx)(dt,{ref:S,"aria-label":"Search agents",placeholder:"Find an agent",value:w,onChange:r(T=>N(T.target.value),"onChange"),onKeyDown:r(T=>{T.key==="Escape"&&(T.stopPropagation(),N(""))},"onKeyDown"),className:"h-8 pl-8 pr-8 text-xs md:text-xs"}),w&&(0,t.jsx)($,{variant:"ghost",size:"icon-xs","aria-label":"Clear search",className:"absolute right-1 top-1/2 -translate-y-1/2",onClick:I,children:(0,t.jsx)(Mn,{className:"size-3"})})]})]}),(0,t.jsxs)("div",{className:"flex min-h-0 flex-1 flex-col gap-2 overflow-y-auto px-3 pb-3 scrollbar-auto-hide",children:[(0,t.jsx)("p",{className:"px-2 text-(length:--text-micro) font-medium uppercase tracking-widest text-muted-foreground",children:_?"Search results":"Teammates"}),(0,t.jsx)("span",{role:"status",className:"sr-only",children:o?"Loading agents":`${R.length} ${R.length===1?"agent":"agents"}`}),f&&(0,t.jsx)("p",{role:"status",className:"px-2 text-xs text-muted-foreground",children:"Loading chat history…"}),x&&(0,t.jsxs)("div",{role:"alert",className:"flex flex-col items-start gap-2 px-2 py-3",children:[(0,t.jsx)("p",{className:"text-xs text-muted-foreground",children:"Some chat history couldn’t load."}),(0,t.jsx)($,{variant:"outline",size:"sm",onClick:g,children:"Retry chat history"})]}),l?(0,t.jsxs)("div",{role:"alert",className:"flex flex-col items-start gap-2 px-2 py-6",children:[(0,t.jsx)("p",{className:"text-sm",children:"Couldn’t load your chats."}),(0,t.jsx)($,{variant:"outline",size:"sm",onClick:c,children:"Try again"})]}):o?(0,t.jsx)("div",{"aria-hidden":"true",className:"flex flex-col gap-1",children:[0,1,2,3].map(T=>(0,t.jsxs)("div",{className:"flex items-center gap-3 rounded-md px-2 py-3 motion-safe:animate-pulse",children:[(0,t.jsx)("div",{className:"size-8 shrink-0 rounded-lg bg-muted"}),(0,t.jsxs)("div",{className:"flex flex-1 flex-col gap-2",children:[(0,t.jsx)("div",{className:"h-3 w-2/3 rounded-sm bg-muted"}),(0,t.jsx)("div",{className:"h-2 w-full rounded-sm bg-muted"})]})]},T))}):R.length?(0,t.jsx)("nav",{"aria-label":"Agent conversations",className:"flex flex-col gap-1",children:R.map(T=>(0,t.jsxs)(We,{to:`/chats/${encodeURIComponent(T.status==="terminated"?T.id:Hl(T))}`,"aria-current":a===T.id?"page":void 0,title:`${T.name}${T.title?` · ${T.title}`:""}`,onClick:r(E=>{u&&(E.preventDefault(),u(T))},"onClick"),className:W("flex min-w-0 items-center gap-3 rounded-md px-2 py-3 text-left transition-colors hover:bg-accent/60 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-ring",a===T.id&&"bg-accent text-accent-foreground"),children:[(0,t.jsx)(lr,{agent:T,size:32}),(0,t.jsxs)("span",{className:"flex min-w-0 flex-1 flex-col gap-0.5",children:[(0,t.jsx)("span",{className:"truncate text-sm font-medium",children:T.name}),(0,t.jsx)("span",{className:"truncate text-xs text-muted-foreground",children:T.status==="terminated"?"Terminated":T.status==="paused"?"Paused":i[T.id]??T.title??"Start a conversation"})]})]},T.id))}):!e.length&&(f||x)?null:(0,t.jsxs)("div",{className:"flex flex-col items-start gap-2 px-2 py-6",children:[(0,t.jsx)("p",{className:"text-sm font-medium",children:e.length?"No agents found":"No chats yet"}),(0,t.jsx)("p",{className:"text-xs leading-relaxed text-muted-foreground",children:e.length?"Try another name or role.":"Choose an agent to start a conversation."}),!e.length&&(0,t.jsx)($,{variant:"outline",size:"sm",onClick:r(()=>k(!0),"onClick"),children:"Choose an agent"}),e.length>0&&(0,t.jsx)($,{variant:"outline",size:"sm",onClick:I,children:"Clear search"})]})]}),(0,t.jsx)("div",{className:"shrink-0 px-3 py-4",children:(0,t.jsx)($,{variant:"ghost",size:"sm",className:"w-full justify-start gap-2 px-2 text-muted-foreground",asChild:!h,onClick:h,children:h?(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)(Wo,{className:"size-4"}),"Browse all agents"]}):(0,t.jsxs)(We,{to:"/agents/all",children:[(0,t.jsx)(Wo,{className:"size-4"}),"Browse all agents"]})})}),(0,t.jsx)(I5e,{agents:n,open:y,onOpenChange:k,existingChatAgentIds:s??e.map(T=>T.id),loading:o,error:l,onRetry:c,renderAgentIcon:r(T=>(0,t.jsx)(lr,{agent:T,size:32}),"renderAgentIcon"),onSelect:r(async(T,E)=>{p?await p(T,E):u?await u(T,E):v(`/chats/${encodeURIComponent(Hl(T))}`),E?.aborted||N("")},"onSelect")})]})}r(x6,"AgentConversationSidebar");var RE={list:r(e=>ke.get(`/companies/${e}/chats`),"list"),get:r((e,s)=>ke.get(`/companies/${e}/chats/${encodeURIComponent(s)}`),"get"),ensure:r((e,s)=>ke.post(`/companies/${e}/chats/${encodeURIComponent(s)}`,{}),"ensure")};function T5e(){const{selectedCompanyId:e}=fs(),{enabled:s,loaded:n}=Jj(),a=te({queryKey:D.auth.session,queryFn:r(()=>Pa.getSession(),"queryFn")}),i=a.data?.user?.id??a.data?.session?.userId??null;return{companyId:e,userId:i,enabled:s,loaded:n,agents:te({queryKey:D.agents.list(e),queryFn:r(()=>Nt.list(e),"queryFn"),enabled:s&&!!e}),chats:te({queryKey:D.agentChats.list(e,i),queryFn:r(()=>RE.list(e),"queryFn"),enabled:s&&!!e&&a.isSuccess}),session:a}}r(T5e,"useAgentChatNavigation");function R5e(e,s){const n=wt(),a=Gn(),{isMobile:i,setSidebarOpen:o}=Ua(),l=(0,m.useRef)({companyId:e,userId:s,mounted:!0});return(0,m.useEffect)(()=>{const c={companyId:e,userId:s,mounted:!0};return l.current=c,()=>{c.mounted=!1}},[e,s]),(0,m.useCallback)(async(c,d)=>{if(!e||c.companyId!==e)throw new Error("Choose an agent from this company.");const u=l.current,h=await RE.ensure(e,c.id);n.setQueryData(D.agentChats.detail(e,s,c.id),h),n.setQueryData(D.issues.detail(h.id),h),n.setQueryData(D.agentChats.list(e,s),p=>[h,...(p??[]).filter(f=>f.id!==h.id)].sort((f,x)=>new Date(x.updatedAt).getTime()-new Date(f.updatedAt).getTime()||x.id.localeCompare(f.id))),!(!u.mounted||l.current!==u||d?.aborted)&&(a(`/chats/${encodeURIComponent(Hl(c))}`),i&&o(!1))},[n,e,s,a,i,o])}r(R5e,"useOpenAgentChat");function Xht(){const{companyId:e,userId:s,agents:n,chats:a,session:i}=T5e(),o=R5e(e,s),l=Gn(),c=Rf(e),{isMobile:d,setSidebarOpen:u}=Ua(),{pathname:h}=la(),p=h.split("/chats/")[1]?.split("/")[0],f=n.data??[],x=n.isSuccess?[...new Set((a.data??[]).flatMap(C=>C.conversationAgentId&&!f.some(_=>_.id===C.conversationAgentId)?[C.conversationAgentId]:[]))]:[],g=pm({queries:x.map(C=>({queryKey:D.agents.detail(C),queryFn:r(()=>Nt.get(C,e),"queryFn")}))}),v=new Map(f.map(C=>[C.id,C]));for(const C of g)C.data&&v.set(C.data.id,C.data);const y=[...v.values()].find(C=>C.id===p||C.status!=="terminated"&&encodeURIComponent(Hl(C))===p),k=(a.data??[]).flatMap(C=>{const _=C.conversationAgentId?v.get(C.conversationAgentId):void 0;return _?[_]:[]});y&&!k.some(C=>C.id===y.id)&&k.unshift(y);const w=new Set(k.map(C=>C.id)),N=f.filter(C=>!w.has(C.id)&&C.status!=="terminated"&&(!c.isSuccess||Yx(c.data,"agent",C.id)!=="left")).sort((C,_)=>C.name.localeCompare(_.name,void 0,{sensitivity:"base"})),S=Object.fromEntries((a.data??[]).filter(C=>C.conversationState==="active").map(C=>[C.conversationAgentId,"Working…"]));return(0,t.jsx)(x6,{agents:[...k,...N],availableAgents:f,existingChatAgentIds:k.map(C=>C.id),activeId:y?.id,previews:S,loading:n.isPending||a.isPending||i.isPending,error:n.error??a.error??i.error,onRetry:r(()=>{n.refetch(),a.refetch(),i.refetch()},"onRetry"),historyLoading:g.some(C=>C.isPending),historyError:g.find(C=>C.error)?.error,onRetryHistory:r(()=>{g.filter(C=>C.isError).forEach(C=>{C.refetch()})},"onRetryHistory"),onAddChat:o,onSelect:r(C=>{l(`/chats/${encodeURIComponent(C.status==="terminated"?C.id:Hl(C))}`),d&&u(!1)},"onSelect")},`${e}:${s}`)}r(Xht,"AgentConversationsSidebar");var DI=240,Hz=208,Vz=420,Rae=16;function EE(e){return Math.min(Vz,Math.max(Hz,e))}r(EE,"clampSidebarWidth$1");function Eae(e){if(typeof window>"u")return DI;try{const s=window.localStorage.getItem(e);if(!s)return DI;const n=Number.parseInt(s,10);return Number.isFinite(n)?EE(n):DI}catch{return DI}}r(Eae,"readStoredSidebarWidth$1");function Lae(e,s){if(!(typeof window>"u"))try{window.localStorage.setItem(e,String(EE(s)))}catch{}}r(Lae,"writeStoredSidebarWidth$1");function e0t({children:e,open:s,collapsed:n=!1,peeking:a=!1,resizable:i=!1,storageKey:o="paperclip.sidebar.width",className:l,onPanelMouseEnter:c,onPanelMouseLeave:d,onPanelFocusCapture:u,onPanelBlurCapture:h}){const[p,f]=(0,m.useState)(()=>Eae(o)),[x,g]=(0,m.useState)(!1),v=(0,m.useRef)(p),y=(0,m.useRef)(null);(0,m.useEffect)(()=>{const M=Eae(o);v.current=M,f(M)},[o]);const k=s?p:0,w=s?n?64:k:0,N=s?n&&!a?64:k:0,S=N>w,C=i&&s&&!n,_=(0,m.useMemo)(()=>({width:`${w}px`}),[w]),R=(0,m.useMemo)(()=>({width:`${N}px`}),[N]),I=(0,m.useCallback)(M=>{const Q=EE(M);v.current=Q,f(Q),Lae(o,Q)},[o]),T=(0,m.useCallback)(M=>{C&&(M.preventDefault(),M.currentTarget.setPointerCapture(M.pointerId),y.current={startX:M.clientX,startWidth:v.current},g(!0))},[C]),E=(0,m.useCallback)(M=>{if(!y.current)return;const Q=EE(y.current.startWidth+M.clientX-y.current.startX);v.current=Q,f(Q)},[]),P=(0,m.useCallback)(()=>{y.current&&(y.current=null,g(!1),Lae(o,v.current))},[o]),O=(0,m.useCallback)(M=>{C&&(M.key==="ArrowLeft"?(M.preventDefault(),I(p-Rae)):M.key==="ArrowRight"?(M.preventDefault(),I(p+Rae)):M.key==="Home"?(M.preventDefault(),I(Hz)):M.key==="End"&&(M.preventDefault(),I(Vz)))},[C,I,p]);return(0,t.jsxs)("div",{className:W("relative h-full shrink-0",l),style:_,children:[(0,t.jsx)("div",{className:W("absolute inset-y-0 left-0 flex flex-col overflow-hidden",S?"z-30 border-r border-border bg-background shadow-lg":"z-0"),style:R,"data-sidebar-overlay":S?"":void 0,onMouseEnter:c,onMouseLeave:d,onFocusCapture:u,onBlurCapture:h,children:e}),C?(0,t.jsx)("div",{role:"separator","aria-label":"Resize sidebar","aria-orientation":"vertical","aria-valuemin":Hz,"aria-valuemax":Vz,"aria-valuenow":p,tabIndex:0,"data-dragging":x?"":void 0,className:"group absolute inset-y-0 z-20 cursor-col-resize touch-none outline-none",style:{right:-4,width:8},onPointerDown:T,onPointerMove:E,onPointerUp:P,onPointerCancel:P,onLostPointerCapture:P,onKeyDown:O,children:(0,t.jsx)("div",{className:W("mx-auto h-full w-0.5 transition-colors",x?"bg-ring":"bg-transparent group-hover:bg-ring group-focus-visible:bg-ring")})}):null]})}r(e0t,"SidebarShell$1");function $I({children:e,className:s}){return(0,t.jsx)("div",{"data-secondary-sidebar":"",className:W("h-full w-full min-w-0 overflow-hidden",s),children:(0,t.jsx)(xke,{children:e})})}r($I,"SecondarySidebar$1");var E5e={listStacks:r(()=>ke.get("/cloud/stacks"),"listStacks")};function CM(e,s){const n=e?.trim();if(!n)return null;try{const a=new URL(s,n);return a.protocol!=="https:"&&a.protocol!=="http:"?null:a.toString()}catch{return null}}r(CM,"cloudAppUrl");function L5e(e){return CM(e,"/stacks/new")}r(L5e,"cloudStackCreateUrl");function M5e(e){if(!e.startsWith("/")||e.startsWith("//")||/[\\\x00-\x20]/.test(e))return"/";const s=new URL(e,"https://tenant.invalid");return s.pathname.replace(/\/+$/,"")==="/auth"?"/":`${s.pathname}${s.search}${s.hash}`}r(M5e,"tenantSignInReturnPath");function t0t(e,s,n){const a=s?.trim();if(!a)return null;const i=CM(e,`/v1/stacks/${encodeURIComponent(a)}/entry-redirect`);if(!i)return null;const o=new URL(i);return o.searchParams.set("returnTo",M5e(n)),o.toString()}r(t0t,"cloudStackEntryUrl");function P5e(e,s){const n=s?.trim();return n?CM(e,`/workspaces/${encodeURIComponent(n)}/settings?section=people`):null}r(P5e,"cloudStackInviteUrl");function s0t(e){return CM(e,"/orgs?manage=1")}r(s0t,"cloudPortfolioManageUrl");function D5e(){const e=td(),s=!!e,n=te({queryKey:D.cloud.stacks,queryFn:r(()=>E5e.listStacks(),"queryFn"),enabled:s,staleTime:3e4,retry:!1});if(!e||n.isError)return null;const a=n.data?.stacks.find(i=>i.isCurrent);return a?.role!=="owner"&&a?.role!=="admin"?null:P5e(e.cloudBaseUrl,a.stackSlug)}r(D5e,"useCloudInviteUrl");function n0t(e,s){if(!s)return!1;if(s.source==="local_implicit"||s.isInstanceAdmin)return!0;if(!e)return!1;const n=s.memberships?.find(a=>a.companyId===e&&a.status==="active");return n?.membershipRole==="owner"||n?.membershipRole==="admin"||n?.membershipRole==="operator"||n?.membershipRole==="member"}r(n0t,"canInviteCompanyMembers");function $5e(e=!0){const s=dbe(),n=te({queryKey:D.access.currentBoardAccess,queryFn:r(()=>or.getCurrentBoardAccess(),"queryFn"),enabled:e,retry:!1,staleTime:3e4});return e&&n0t(s?.selectedCompanyId,n.data)}r($5e,"useCanInviteCompanyMembers");function O5e(e){const s=window.location.hostname.endsWith(".staging.paperclip.app"),{data:n,isError:a}=te({queryKey:D.stagingCommit,queryFn:r(()=>Lu.get(),"queryFn"),enabled:s&&e,staleTime:0,retry:!1});return s&&!a?n?.commit??null:null}r(O5e,"useStagingCommit");function r0t(e){return e?.trim().toLowerCase().replace(/['"]/g,"").replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")||null}r(r0t,"slugifyUserPart");function B5e(e){const s=[e?.id,e?.name,e?.email?.split("@")[0],e?.email];for(const n of s){const a=r0t(n);if(a)return`/u/${a}`}return"/u/me"}r(B5e,"userProfilePath");var a0t="Toggle the app appearance.";function Ek({className:e,variant:s="icon",onAfterToggle:n}){const{theme:a,toggleTheme:i}=Bze(),o=a==="dark",l=o?"Switch to light mode":"Switch to dark mode",c=o?j1e:vwe;function d(){i(),n?.()}return r(d,"handleClick"),s==="compact-menu-action"?(0,t.jsxs)("button",{type:"button",className:W("flex h-(--profile-popover-row-height) w-full items-center gap-(--profile-popover-row-gap) rounded-lg px-2.5 text-left text-(length:--text-compact) font-medium leading-(--profile-popover-label-line-height) text-foreground transition-colors hover:bg-accent",e),onClick:d,"aria-label":l,children:[(0,t.jsx)("span",{className:"flex size-5 shrink-0 items-center justify-center text-muted-foreground",children:(0,t.jsx)(c,{className:"size-4"})}),(0,t.jsx)("span",{className:"min-w-0 flex-1 truncate",children:l})]}):s==="menu-action"?(0,t.jsxs)("button",{type:"button",className:W("flex w-full items-start gap-3 rounded-xl px-3 py-3 text-left transition-colors hover:bg-accent/60",e),onClick:d,"aria-label":l,children:[(0,t.jsx)("span",{className:"mt-0.5 rounded-lg border border-border bg-background/70 p-2 text-muted-foreground",children:(0,t.jsx)(c,{className:"size-4"})}),(0,t.jsxs)("span",{className:"min-w-0 flex-1",children:[(0,t.jsx)("span",{className:"block text-sm font-medium text-foreground",children:l}),(0,t.jsx)("span",{className:"block text-xs text-muted-foreground",children:a0t})]})]}):(0,t.jsx)($,{type:"button",variant:"ghost",size:"icon-sm",onClick:d,"aria-label":l,title:l,className:W("text-muted-foreground",e),children:(0,t.jsx)(c,{})})}r(Ek,"ThemeToggle");var w5=null,F5e=!1,Gz=!1,Yz=new Set;function LE(){for(const e of Yz)e()}r(LE,"emit");function i0t(e=typeof navigator>"u"?"":navigator.userAgent,s=typeof navigator>"u"?0:navigator.maxTouchPoints){return/iPhone|iPad|iPod/i.test(e)?!0:/Macintosh/i.test(e)&&s>1}r(i0t,"isIosSafariLike");function o0t(e=window){const s=r(a=>{a.preventDefault(),w5=a,LE()},"onPrompt"),n=r(()=>{w5=null,F5e=!0,LE()},"onInstalled");return e.addEventListener("beforeinstallprompt",s),e.addEventListener("appinstalled",n),()=>{e.removeEventListener("beforeinstallprompt",s),e.removeEventListener("appinstalled",n)}}r(o0t,"captureInstallPrompt");function l0t(){return F5e||Qz()?"installed":w5?"prompt":i0t()?"ios-manual":"unavailable"}r(l0t,"installAvailability");async function c0t(){const e=w5;if(!e)return"unavailable";w5=null,LE(),await e.prompt();const{outcome:s}=await e.userChoice;return s}r(c0t,"promptInstall");function Zz(e){Gz!==e&&(Gz=e,LE())}r(Zz,"setIosInstallHelpOpen");function d0t(){return Gz}r(d0t,"iosInstallHelpOpen");function u0t(){return(0,m.useSyncExternalStore)(z5e,d0t,()=>!1)}r(u0t,"useIosInstallHelpOpen");function z5e(e){return Yz.add(e),()=>{Yz.delete(e)}}r(z5e,"subscribe$1");function m0t(){return(0,m.useSyncExternalStore)(z5e,l0t,()=>"unavailable")}r(m0t,"useInstallAvailability");var Mae="Install app",h0t="Add Paperclip to your home screen or dock.";function q5e({variant:e,onAfterAction:s}){const n=m0t();if(n==="installed"||n==="unavailable")return null;const a=r(()=>{n==="ios-manual"?Zz(!0):c0t(),s?.()},"handleClick");return e==="compact-menu-action"?(0,t.jsxs)("button",{type:"button",className:"flex h-(--profile-popover-row-height) w-full items-center gap-(--profile-popover-row-gap) rounded-lg px-2.5 text-left text-(length:--text-compact) font-medium leading-(--profile-popover-label-line-height) text-foreground transition-colors hover:bg-accent",onClick:a,children:[(0,t.jsx)("span",{className:"flex size-5 shrink-0 items-center justify-center text-muted-foreground",children:(0,t.jsx)(Fi,{className:"size-4"})}),(0,t.jsx)("span",{className:"min-w-0 flex-1 truncate",children:Mae})]}):(0,t.jsxs)("button",{type:"button",className:"flex w-full items-start gap-3 rounded-xl px-3 py-3 text-left transition-colors hover:bg-accent/60",onClick:a,children:[(0,t.jsx)("span",{className:"mt-0.5 rounded-lg border border-border bg-background/70 p-2 text-muted-foreground",children:(0,t.jsx)(Fi,{className:"size-4"})}),(0,t.jsxs)("span",{className:"min-w-0 flex-1",children:[(0,t.jsx)("span",{className:"block text-sm font-medium text-foreground",children:Mae}),(0,t.jsx)("span",{className:"block text-xs text-muted-foreground",children:h0t})]})]})}r(q5e,"InstallAppMenuAction");function p0t(){const e=u0t();return(0,t.jsx)(Fs,{open:e,onOpenChange:Zz,children:(0,t.jsxs)(Qs,{children:[(0,t.jsxs)(rn,{children:[(0,t.jsx)(Ks,{children:"Install Paperclip"}),(0,t.jsx)(mn,{children:"Add Paperclip to your Home Screen from Safari."})]}),(0,t.jsxs)("ol",{className:"space-y-3 text-sm text-foreground",children:[(0,t.jsxs)(pD,{index:1,icon:(0,t.jsx)(FKe,{className:"size-4"}),children:["Tap ",(0,t.jsx)("strong",{children:"Share"})," in the Safari toolbar."]}),(0,t.jsxs)(pD,{index:2,icon:(0,t.jsx)(UKe,{className:"size-4"}),children:["Choose ",(0,t.jsx)("strong",{children:"Add to Home Screen"}),"."]}),(0,t.jsxs)(pD,{index:3,children:["Keep ",(0,t.jsx)("strong",{children:"Open as Web App"})," on, then tap ",(0,t.jsx)("strong",{children:"Add"}),"."]})]}),(0,t.jsx)(cr,{children:(0,t.jsx)($,{type:"button",onClick:r(()=>Zz(!1),"onClick"),children:"Done"})})]})})}r(p0t,"IosInstallHelpDialog");function pD({index:e,icon:s,children:n}){return(0,t.jsxs)("li",{className:"flex items-start gap-3",children:[(0,t.jsx)("span",{className:"flex size-6 shrink-0 items-center justify-center rounded-full border border-border text-xs font-semibold text-muted-foreground",children:e}),(0,t.jsxs)("span",{className:"flex min-w-0 flex-1 items-center gap-2",children:[s?(0,t.jsx)("span",{className:"text-muted-foreground",children:s}):null,(0,t.jsx)("span",{children:n})]})]})}r(pD,"InstallStep");function f0t(e){if(!e)return"Unavailable";const s=new Date(e);return Number.isNaN(s.getTime())?"Unavailable":new Intl.DateTimeFormat(void 0,{dateStyle:"medium",timeStyle:"short"}).format(s)}r(f0t,"formatTimestamp$2");function x0t(e){return!!e&&!Number.isNaN(new Date(e).getTime())}r(x0t,"isValidTimestamp");function g0t(e){return e?.devServer?.lastRestartAt??e?.serverInfo?.processStartedAt??null}r(g0t,"restartTimestamp");function b0t(e){const s=e?.serverInfo?.git;return s?.available?`${s.shortSha} · ${s.subject}`:"Commit unavailable"}r(b0t,"commitLabel");function v0t(e){const s=e?.serverInfo?.git;if(!s?.available)return"Unavailable";const n=s.localChanges;if(!n||!n.available)return"Change status unavailable";if(!n.hasLocalChanges)return"Clean checkout";const a=[[n.stagedFileCount,"staged"],[n.unstagedFileCount,"unstaged"],[n.untrackedFileCount,"untracked"]].filter(([i])=>Number(i)>0).map(([i,o])=>`${i} ${o}`);return a.length>0?`Local changes present (${a.join(", ")})`:"Local changes present"}r(v0t,"localChangesLabel");function fD({icon:e,label:s,value:n,dateTime:a}){return(0,t.jsxs)("div",{className:"flex w-full items-start gap-3 rounded-xl px-3 py-3 text-left",children:[(0,t.jsx)("span",{className:"mt-0.5 rounded-lg border border-border bg-background/70 p-2 text-muted-foreground",children:(0,t.jsx)(e,{className:"size-4"})}),(0,t.jsxs)("span",{className:"min-w-0 flex-1",children:[(0,t.jsx)("span",{className:"block text-sm font-medium text-foreground",children:s}),a?(0,t.jsx)("time",{dateTime:a,className:"block break-words text-xs text-muted-foreground",children:n}):(0,t.jsx)("span",{className:"block break-words text-xs text-muted-foreground",children:n})]})]})}r(fD,"ServerInfoRow");function U5e(){const e=te({queryKey:D.instance.experimentalSettings,queryFn:r(()=>jr.getExperimental(),"queryFn")}).data?.enableServerInfoDebugView===!0,s=te({queryKey:D.health,queryFn:r(()=>Lu.get(),"queryFn"),enabled:e,refetchOnMount:"always",refetchInterval:r(h=>h.state.data?.devServer?.enabled?2e3:!1,"refetchInterval")});if(!e)return null;const n=s.data,a=s.isLoading&&!n,i=s.isError,o=g0t(n),l=x0t(o),c=i?"Health unavailable":a?"Loading...":f0t(o),d=i?"Health unavailable":a?"Loading...":b0t(n),u=i?"Health unavailable":a?"Loading...":v0t(n);return(0,t.jsxs)("div",{className:"mt-2 border-t border-border pt-2",children:[(0,t.jsx)("p",{className:"px-3 pb-1 pt-1 text-(length:--text-micro) font-medium uppercase tracking-wide text-muted-foreground",children:"Server"}),(0,t.jsx)(fD,{icon:Au,label:"Last restarted",value:c,dateTime:!i&&!a&&l?o:null}),(0,t.jsx)(fD,{icon:pW,label:"Running commit",value:d}),(0,t.jsx)(fD,{icon:pKe,label:"Checkout state",value:u})]})}r(U5e,"SidebarServerInfo");var y0t="/company/settings/members?tab=invites",j0t="https://docs.paperclip.ing/",w0t="https://paperclip.ing/feedback";function k0t(e){const s=e.trim().split(/\s+/).filter(Boolean);return s.length>=2?`${s[0]?.[0]??""}${s[s.length-1]?.[0]??""}`.toUpperCase():e.slice(0,2).toUpperCase()}r(k0t,"deriveInitials$2");function xD({label:e,icon:s,onClick:n,href:a,external:i=!1,topLevel:o=!1}){const l="flex h-(--profile-popover-row-height) w-full items-center gap-(--profile-popover-row-gap) rounded-lg px-2.5 text-left text-(length:--text-compact) font-medium leading-(--profile-popover-label-line-height) text-foreground transition-colors hover:bg-accent",c=(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)("span",{className:"flex size-5 shrink-0 items-center justify-center text-muted-foreground",children:(0,t.jsx)(s,{className:"size-4"})}),(0,t.jsx)("span",{className:"min-w-0 flex-1 truncate",children:e})]});return a?i?(0,t.jsx)("a",{href:a,target:"_blank",rel:"noreferrer",className:l,onClick:n,children:c}):o?(0,t.jsx)("a",{href:a,className:l,onClick:n,children:c}):(0,t.jsx)(We,{to:a,className:l,onClick:n,children:c}):(0,t.jsx)("button",{type:"button",className:l,onClick:n,children:c})}r(xD,"MenuAction$1");function Pae({deploymentMode:e,open:s,onOpenChange:n,forceExpanded:a=!1}){const o=!!td(),{hidden:l,loaded:c}=Eu(),d=D5e(),u=$5e(!o),h=o?d:u?y0t:null,p=c&&h!==null&&!Kx(l,"company.members")&&!Kx(l,"company.invites"),[f,x]=(0,m.useState)(!1),{isMobile:g,setSidebarOpen:v,collapsed:y,peeking:k}=Ua(),w=y&&!k&&!a,N=s??f,S=O5e(N),C=n??x,{data:_}=te({queryKey:D.auth.session,queryFn:r(()=>Pa.getSession(),"queryFn"),retry:!1}),R=j2({onSignedOut:O}),I=_?.user.name?.trim()||"Board",T=_?.user.email?.trim()||(e==="authenticated"?"Signed in":"Local workspace board"),E=k0t(I),P=B5e(_?.user);function O(){C(!1),g&&v(!1)}r(O,"closeNavigationChrome");function M(){R.mutate()}return r(M,"handleSignOut"),(0,t.jsx)("div",{className:"bg-border/50 px-3 py-2 dark:bg-muted",children:(0,t.jsxs)("div",{className:W("flex items-center gap-0.5",!w&&"px-2"),children:[(0,t.jsxs)(dr,{open:N,onOpenChange:C,children:[(0,t.jsx)(wr,{asChild:!0,children:(0,t.jsxs)("button",{type:"button",className:W("flex min-w-0 items-center gap-2.5 rounded-lg text-left text-(length:--text-compact) font-medium text-foreground/80 transition-colors hover:bg-sidebar-accent hover:text-sidebar-accent-foreground",w?"w-full px-3 py-2":"flex-1 px-2 py-1.5"),"aria-label":"Open account menu",children:[(0,t.jsxs)(bo,{size:"sm",children:[_?.user.image?(0,t.jsx)(Jc,{src:_.user.image,alt:I}):null,(0,t.jsx)(vo,{children:E})]}),(0,t.jsx)("span",{className:W("min-w-0 flex-1 truncate",w&&"block w-0 min-w-0 overflow-hidden whitespace-nowrap text-transparent select-none"),children:I})]})}),(0,t.jsxs)(nr,{side:"top",align:"start",sideOffset:10,className:"min-h-(--profile-popover-min-height) w-(--profile-popover-width) max-w-(--sz-calc-24) overflow-hidden rounded-xl border-border bg-popover p-0 shadow-(--shadow-profile-popover)",children:[(0,t.jsxs)("div",{className:"relative flex h-(--profile-popover-header-height) shrink-0 items-center gap-2.5 px-3.5",children:[(0,t.jsx)(We,{to:P,"aria-label":"View profile",onClick:O,className:"absolute inset-0 transition-colors hover:bg-accent focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-ring"}),(0,t.jsxs)(bo,{className:"pointer-events-none relative size-9",children:[_?.user.image?(0,t.jsx)(Jc,{src:_.user.image,alt:I}):null,(0,t.jsx)(vo,{className:"text-xs text-foreground",children:E})]}),(0,t.jsxs)("div",{className:"pointer-events-none relative min-w-0 flex-1",children:[(0,t.jsx)("h2",{className:"truncate text-sm font-semibold leading-(--profile-popover-label-line-height) text-foreground",children:I}),(0,t.jsx)("p",{className:"truncate text-(length:--text-micro) leading-(--profile-popover-meta-line-height) text-muted-foreground",children:T}),S?(0,t.jsxs)("a",{className:"pointer-events-auto block truncate font-mono text-(length:--text-micro) leading-(--profile-popover-meta-line-height) text-muted-foreground hover:underline focus-visible:underline",href:`https://github.com/paperclipai/paperclip/commit/${S}`,target:"_blank",rel:"noreferrer","aria-label":`View commit ${S} on GitHub`,title:S,children:["SHA ",S.slice(0,7)]}):null]})]}),(0,t.jsxs)("div",{className:"flex flex-1 flex-col gap-0.5 border-t border-border px-2.5 pb-2.5 pt-2",children:[(0,t.jsx)(xD,{label:"Settings",icon:Iu,href:"/company/settings",onClick:O}),p&&h?(0,t.jsx)(xD,{label:"Invite",icon:hh,href:h,topLevel:o,onClick:O}):null,(0,t.jsx)(xD,{label:"Documentation",icon:p2,href:j0t,external:!0,onClick:r(()=>C(!1),"onClick")}),(0,t.jsx)(Ek,{variant:"compact-menu-action",onAfterToggle:r(()=>C(!1),"onAfterToggle")}),(0,t.jsx)(q5e,{variant:"compact-menu-action",onAfterAction:r(()=>C(!1),"onAfterAction")}),e==="authenticated"?(0,t.jsxs)("button",{type:"button",className:W("flex h-(--profile-popover-row-height) w-full items-center gap-(--profile-popover-row-gap) rounded-lg px-2.5 text-left text-(length:--text-compact) font-medium leading-(--profile-popover-label-line-height) text-foreground transition-colors hover:bg-destructive/10",R.isPending&&"cursor-not-allowed opacity-60"),onClick:M,disabled:R.isPending,children:[(0,t.jsx)("span",{className:"flex size-5 shrink-0 items-center justify-center text-muted-foreground",children:(0,t.jsx)(rp,{className:"size-4"})}),(0,t.jsx)("span",{className:"min-w-0 flex-1 truncate",children:R.isPending?"Signing out...":"Sign out"})]}):null,(0,t.jsx)(U5e,{})]})]})]}),!w&&!o?(0,t.jsxs)(Fn,{children:[(0,t.jsx)(Bn,{asChild:!0,children:(0,t.jsx)("a",{href:w0t,target:"_blank",rel:"noreferrer","aria-label":"Share feedback",className:"flex size-8 shrink-0 items-center justify-center rounded-lg text-muted-foreground/50 transition-colors hover:bg-sidebar-accent hover:text-sidebar-accent-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring",children:(0,t.jsx)(ug,{className:"h-4 w-4","aria-hidden":"true"})})}),(0,t.jsx)(On,{side:"top",children:"Share feedback"})]}):null]})})}r(Pae,"SidebarAccountMenu$1");function K5e({onNewIssue:e,onSearch:s,onToggleSidebar:n,onTogglePanel:a,onShowShortcuts:i,onGoToInbox:o}){(0,m.useEffect)(()=>{let l=!1,c=null;const d=r(()=>{c!==null&&(window.clearTimeout(c),c=null)},"clearGoChordTimeout"),u=r(()=>{l=!1,d()},"disarmGoChord"),h=r(()=>{l=!0,d(),c=window.setTimeout(()=>{l=!1,c=null},1200)},"armGoChord");function p(g){if(g.defaultPrevented){u();return}if(o){const v=gve({armed:l,defaultPrevented:g.defaultPrevented,key:g.key,metaKey:g.metaKey,ctrlKey:g.ctrlKey,altKey:g.altKey,target:g.target,hasOpenDialog:Z0()});if(v==="arm"){h();return}if(v==="navigate_inbox"){u(),g.preventDefault(),o();return}if(v==="focus_comment"||v==="open_file_viewer"){u(),g.preventDefault();return}v==="disarm"&&u()}if(!b3(g.target)&&!Z0()){if(g.key==="/"&&!g.metaKey&&!g.ctrlKey&&!g.altKey){g.preventDefault(),MFe()||s?.();return}if(g.key==="?"&&!g.metaKey&&!g.ctrlKey&&!g.altKey){g.preventDefault(),i?.();return}g.key==="c"&&!g.metaKey&&!g.ctrlKey&&!g.altKey&&(g.preventDefault(),e?.()),g.key==="["&&!g.metaKey&&!g.ctrlKey&&(g.preventDefault(),n?.()),g.key==="]"&&!g.metaKey&&!g.ctrlKey&&(g.preventDefault(),a?.())}}r(p,"handleKeyDown");const f=r(()=>u(),"handlePointerDown"),x=r(g=>{g.target instanceof HTMLElement&&g.target!==document.body&&u()},"handleFocusIn");return document.addEventListener("pointerdown",f,!0),document.addEventListener("focusin",x,!0),document.addEventListener("keydown",p),()=>{u(),document.removeEventListener("pointerdown",f,!0),document.removeEventListener("focusin",x,!0),document.removeEventListener("keydown",p)}},[e,s,n,a,i,o])}r(K5e,"useKeyboardShortcuts");var N0t=new Set(["auth","invite","board-claim","cli-auth","docs","s"]);function Q5e(e){const s=(e.split("?")[0]??"").split("/").filter(Boolean);if(s.length===0)return!0;const[n]=s;return!N0t.has(n)}r(Q5e,"isRememberableCompanyPath");function S0t(e){const s=dj(e.companyPrefix);return e.companies.find(n=>dj(n.issuePrefix)===s)??null}r(S0t,"findCompanyByPrefix");function C0t(e){const s=DQ(e.pathname);return s?S0t({companies:e.companies,companyPrefix:s})?.id??null:e.fallbackCompanyId}r(C0t,"getRememberedPathOwnerCompanyId");function _0t(e){const s=e.path?yL(e.path):"/dashboard";if(!Q5e(s))return"/dashboard";const[n,a]=(s.split("?")[0]??"").split("/").filter(Boolean);if(n==="issues"&&a){const i=/^([A-Za-z]+)-\d+$/.exec(a);if(i&&dj(i[1]??"")!==dj(e.companyPrefix))return"/dashboard"}return s}r(_0t,"sanitizeRememberedPathForCompany");var W5e="paperclip.companyPaths";function H5e(){try{const e=localStorage.getItem(W5e);if(e)return JSON.parse(e)}catch{}return{}}r(H5e,"getCompanyPaths");function A0t(e,s){const n=H5e();n[e]=s,localStorage.setItem(W5e,JSON.stringify(n))}r(A0t,"saveCompanyPath");function V5e(){const{companies:e,selectedCompanyId:s,selectedCompany:n,selectionSource:a}=fs(),i=la(),o=Gn(),l=(0,m.useRef)(s),c=(0,m.useMemo)(()=>C0t({companies:e,pathname:i.pathname,fallbackCompanyId:l.current}),[e,i.pathname]),d=i.pathname+i.search;(0,m.useEffect)(()=>{const u=c,h=yL(d);u&&Q5e(h)&&A0t(u,h)},[d,c]),(0,m.useEffect)(()=>{if(s){if(l.current!==null&&s!==l.current&&a!=="route_sync"&&n){const u=H5e(),h=_0t({path:u[s],companyPrefix:n.issuePrefix});o(`/${n.issuePrefix}${h}`,{replace:!0})}l.current=s}},[n,s,a,o])}r(V5e,"useCompanyPageMemory");var I0t=class{static{r(this,"MobileNavScrollTracker")}options;lastTop;lastMaxTop;visible=!0;direction=0;distance=0;constructor(e,s,n){this.options=e,this.lastTop=s,this.lastMaxTop=n}update(e,s){const n=Math.max(0,Math.min(e,s)),a=n-Math.max(this.lastTop,this.options.topZone),i=s!==this.lastMaxTop;if(this.lastTop=n,this.lastMaxTop=s,n<=this.options.topZone)this.visible=!0,this.direction=0,this.distance=0;else if(i)this.direction=0,this.distance=0;else if(a!==0){const o=Math.sign(a);o!==this.direction&&(this.distance=0),this.direction=o,this.distance+=Math.abs(a);const l=o>0?this.options.hideDistance:this.options.showDistance;this.distance>=l&&(this.visible=o<0,this.distance=0)}return this.visible}};function G5e(e,s){const[n,a]=(0,m.useState)(!0);return(0,m.useEffect)(()=>{if(a(!0),!e)return;const i=getComputedStyle(document.documentElement),o=r(p=>Number.parseFloat(i.getPropertyValue(p))||0,"distance"),l=r(()=>{const p=document.scrollingElement??document.documentElement;return{top:window.scrollY||p.scrollTop||0,max:Math.max(0,p.scrollHeight-p.clientHeight)}},"scrollBounds"),c=l(),d=new I0t({topZone:o("--mobile-nav-scroll-top-zone"),hideDistance:o("--mobile-nav-scroll-hide-distance"),showDistance:o("--mobile-nav-scroll-show-distance")},c.top,c.max);let u=null;const h=r(()=>{u===null&&(u=requestAnimationFrame(()=>{u=null;const{top:p,max:f}=l(),x=d.visible,g=d.update(p,f);g!==x&&a(g)}))},"onScroll");return window.addEventListener("scroll",h,{passive:!0}),()=>{window.removeEventListener("scroll",h),u!==null&&cancelAnimationFrame(u)}},[e,s]),n}r(G5e,"useMobileNavVisibility");function Y5e(e){const{matchedCompany:s,selectedCompanyId:n,companies:a}=e;return!s||s.status!=="archived"||n===s.id?null:a.find(i=>i.id===n&&i.status!=="archived")??a.find(i=>i.status!=="archived")??null}r(Y5e,"resolveArchivedCompanyBounce");function T0t(e){const{archivedCompanyId:s,companies:n,cloudPortfolioUrl:a}=e,i=n.find(o=>o.id!==s&&o.status!=="archived");return i?{kind:"company",company:i}:a?{kind:"cloud_portfolio",url:a}:{kind:"companies_list"}}r(T0t,"resolveCompanyArchiveDeparture");function Z5e(e){const{selectionSource:s,selectedCompanyId:n,routeCompanyId:a}=e;return!(n===a||s==="manual"&&n)}r(Z5e,"shouldSyncCompanySelectionFromRoute");function R0t(e,s){return e instanceof HTMLElement?!(s instanceof HTMLElement)||!document.contains(s)||s===document.body||s===document.documentElement?!0:!e.contains(s):!1}r(R0t,"shouldFocusMainContentAfterNavigation");function J5e(e){if(!(e instanceof HTMLElement))return()=>{};const s=window.requestAnimationFrame(()=>{R0t(e,document.activeElement)&&e.focus({preventScroll:!0})});return()=>window.cancelAnimationFrame(s)}r(J5e,"scheduleMainContentFocus");function X5e(e=document,s=window){const n=r(()=>{e.documentElement.scrollTop!==0&&(e.documentElement.scrollTop=0),e.body.scrollTop!==0&&(e.body.scrollTop=0)},"onScroll");return s.addEventListener("scroll",n,{capture:!0}),()=>s.removeEventListener("scroll",n,{capture:!0})}r(X5e,"pinDocumentScrollToZero");function mm({scope:e="global",requestedPrefix:s}){const n=la(),{setBreadcrumbs:a}=Vn(),{companies:i,selectedCompany:o}=fs();(0,m.useEffect)(()=>{a([{label:"Not Found"}])},[a]);const l=o??i[0]??null,c=l?`/${l.issuePrefix}/dashboard`:"/",d=`${n.pathname}${n.search}${n.hash}`,u=s?.toUpperCase(),h=e==="invalid_company_prefix"?"Organization not found":"Page not found",p=e==="invalid_company_prefix"?`No organization matches prefix "${u??"unknown"}".`:"This route does not exist.";return(0,t.jsx)("div",{className:"mx-auto max-w-2xl py-10",children:(0,t.jsxs)(sn,{className:"block p-6",children:[(0,t.jsxs)("div",{className:"flex items-center gap-3",children:[(0,t.jsx)("div",{className:"rounded-md border border-destructive/20 bg-destructive/10 p-2",children:(0,t.jsx)(Es,{className:"h-5 w-5 text-destructive"})}),(0,t.jsxs)("div",{children:[(0,t.jsx)("h1",{className:"text-xl font-semibold",children:h}),(0,t.jsx)("p",{className:"text-sm text-muted-foreground",children:p})]})]}),(0,t.jsxs)("div",{className:"mt-4 rounded-md border border-border bg-muted/20 px-3 py-2 text-xs text-muted-foreground",children:["Requested path: ",(0,t.jsx)("code",{className:"font-mono",children:d})]}),(0,t.jsxs)("div",{className:"mt-5 flex flex-wrap gap-2",children:[(0,t.jsx)($,{asChild:!0,children:(0,t.jsxs)(We,{to:c,children:[(0,t.jsx)(vR,{className:"mr-1.5 h-4 w-4"}),"Open dashboard"]})}),(0,t.jsx)($,{variant:"outline",asChild:!0,children:(0,t.jsx)(We,{to:"/",children:"Go home"})})]})]})})}r(mm,"NotFoundPage");function E0t(e,s){return kNe(e,s)[0]?.toLowerCase()??null}r(E0t,"getCompanyRouteSegment$1");var L0t=new Set(["browse","connections","assistant-connection","connect","chat","vercel-connect","review","attention","gateways","advanced","app"]);function M0t({sidebarSections:e}){const{sidebarOpen:s,setSidebarOpen:n,toggleSidebar:a,collapsed:i,peeking:o,setPeeking:l,isMobile:c,setForceCollapsed:d}=Ua(),{openNewIssue:u,openOnboarding:h}=al(),{togglePanelVisible:p}=Ef(),f=jd()?.pushToast??null,{companies:x,loading:g,selectedCompany:v,selectedCompanyId:y,selectionSource:k,setSelectedCompanyId:w}=fs(),{companyPrefix:N,pluginRoutePath:S,agentId:C,routineId:_}=xa(),R=Gn(),I=la(),T=vL(),{enabled:E}=Ec(),P=NNe(I.pathname,N),O=P.builtInContextualSurface==="settings",M=P.companySegments,Q=P.isTaskDetail,{enabled:L}=Jj(),F=L&&M[0]?.toLowerCase()==="chats",q=E&&(Q||F),z=M[0]?.toLowerCase()==="tools",K=M[0]?.toLowerCase()==="apps",U=K&&M[1]&&!L0t.has(M[1].toLowerCase())?M[1]:null,V=K&&M[1]?.toLowerCase()==="app"&&M[2]?M[2]:null,ne=(0,m.useRef)(!1),Z=(0,m.useRef)(null),ie=(0,m.useRef)(null),J=(0,m.useRef)(new hke),ae=(0,m.useRef)(I.key),oe=G5e(c&&!Q,I.pathname),[G,X]=(0,m.useState)(!1),Y=(0,m.useMemo)(()=>{if(!N)return null;const Rt=N.toUpperCase();return x.find(Qe=>Qe.issuePrefix.toUpperCase()===Rt)??null},[x,N]),re=!!N&&!g&&x.length>0&&!Y,se=(0,m.useMemo)(()=>S?.toLowerCase()??E0t(I.pathname,N),[N,I.pathname,S]),ce=Y?.id??null,pe=Y?.issuePrefix??null,{slots:fe}=Bd({slotTypes:["page","routeSidebar"],companyId:ce,enabled:!!(ce&&se)}),ve=(0,m.useMemo)(()=>$W(fe,se),[se,fe]),Ie=(0,m.useMemo)(()=>({companyId:ce,companyPrefix:pe}),[ce,pe]),de=O?(0,t.jsx)(DYe,{}):!E&&P.builtInContextualSurface==="skills"?(0,t.jsx)(pse,{}):U?(0,t.jsx)(mse,{kind:"connection",connectionId:U}):V?(0,t.jsx)(mse,{kind:"application",applicationId:V}):K||z?(0,t.jsx)(KYe,{}):ve?E?(0,t.jsx)(O3,{surface:`plugin:${ve.id}`,title:ve.displayName,children:(0,t.jsx)(vm,{slot:ve,context:Ie,className:"min-h-0 flex-1",missingBehavior:"placeholder"})}):(0,t.jsx)(vm,{slot:ve,context:Ie,className:"h-full w-full",missingBehavior:"placeholder"}):null,xe=F?(0,t.jsx)(Xht,{}):P.builtInContextualSurface==="agent"&&C?(0,t.jsx)(rZe,{agentRef:C}):E&&P.builtInContextualSurface==="routine"&&_?(0,t.jsx)(CHe,{children:(0,t.jsx)(oZe,{routineId:_})}):E&&P.builtInContextualSurface==="skills"?(0,t.jsx)(pse,{}):de,le=xe!=null,Re=E&&le&&(F||P.builtInContextualSurface==="skills"||P.builtInContextualSurface==="agent"||P.builtInContextualSurface==="routine"||K||z),Le=E&&le&&!Re,je=le&&(!E||Re),_e=!E||!le?null:ve&&!P.builtInContextualSurface?`plugin:${ve.id}`:P.builtInContextualSurface,Ze=(0,m.useRef)(null),{data:ue}=te({queryKey:D.health,queryFn:r(()=>Lu.get(),"queryFn"),retry:!1,refetchInterval:r(Rt=>Rt.state.data?.devServer?.enabled?2e3:!1,"refetchInterval"),refetchIntervalInBackground:!1});(0,m.useLayoutEffect)(()=>(d(!E&&le),()=>d(!1)),[le,d,E]),(0,m.useEffect)(()=>{const Rt=Ze.current;_e&&N&&Rt&&Rt.surface!==_e&&Rt.pathname!==I.pathname&&LYe({surface:_e,companyPrefix:N,previousPathname:Rt.pathname}),Ze.current={pathname:I.pathname,surface:_e}},[N,_e,I.pathname]),(0,m.useEffect)(()=>{g||ne.current||ue?.deploymentMode!=="authenticated"&&(ue?.cloud||x.length===0&&(ne.current=!0,h()))},[x,g,h,ue?.cloud,ue?.deploymentMode]),(0,m.useEffect)(()=>{if(!N||g||x.length===0)return;if(!Y){const Qe=(y?x.find(Be=>Be.id===y):null)??x[0]??null;Qe&&y!==Qe.id&&w(Qe.id,{source:"route_sync"});return}if(N!==Y.issuePrefix){const Qe=I.pathname.replace(/^\/[^/]+/,"");R(`/${Y.issuePrefix}${Qe}${I.search}`,{replace:!0});return}const Rt=Y5e({matchedCompany:Y,selectedCompanyId:y,companies:x});if(Rt){f?.({title:`${Y.name} is archived`,body:`Switched to ${Rt.name}.`,tone:"info",dedupeKey:`archived-company-bounce:${Y.id}`}),w(Rt.id,{source:"route_sync"}),R(`/${Rt.issuePrefix}/dashboard`,{replace:!0});return}Z5e({selectionSource:k,selectedCompanyId:y,routeCompanyId:Y.id})&&w(Y.id,{source:"route_sync"})},[N,x,g,Y,I.pathname,I.search,R,f,k,y,w]);const Fe=p,mt=(0,m.useCallback)(()=>{document.dispatchEvent(new KeyboardEvent("keydown",{key:"k",metaKey:!0,bubbles:!0,cancelable:!0}))},[]),bt=(0,m.useRef)(null),et=(0,m.useRef)(!1),qe=(0,m.useRef)(!1),it=(0,m.useCallback)(()=>{bt.current!==null&&(window.clearTimeout(bt.current),bt.current=null)},[]),_t=(0,m.useCallback)(()=>{it(),bt.current=window.setTimeout(()=>l(!0),50)},[it,l]),$t=(0,m.useCallback)(()=>{it(),l(!0)},[it,l]),Ot=(0,m.useCallback)(()=>{it(),bt.current=window.setTimeout(()=>l(!1),120)},[it,l]),at=(0,m.useCallback)(()=>{et.current=!0,i&&!qe.current&&_t()},[i,_t]),Me=(0,m.useCallback)(()=>{et.current=!1,qe.current=!1,Ot()},[Ot]),De=(0,m.useCallback)(()=>{qe.current||$t()},[$t]),ut=(0,m.useCallback)(()=>{et.current||Ot()},[Ot]);(0,m.useEffect)(()=>it,[it]);const Pt=(0,m.useRef)(i);return(0,m.useEffect)(()=>{i!==Pt.current&&(i?(it(),l(!1),qe.current=et.current):qe.current=!1,Pt.current=i)},[i,it,l]),(0,m.useEffect)(()=>{if(!o)return;const Rt=r(Qe=>{Qe.key==="Escape"&&(it(),l(!1))},"onKeyDown");return window.addEventListener("keydown",Rt),()=>window.removeEventListener("keydown",Rt)},[o,it,l]),V5e(),K5e({onNewIssue:r(()=>u(),"onNewIssue"),onSearch:mt,onToggleSidebar:a,onTogglePanel:Fe,onShowShortcuts:r(()=>X(!0),"onShowShortcuts"),onGoToInbox:r(()=>R("/inbox"),"onGoToInbox")}),(0,m.useEffect)(()=>{if(!c)return;const Rt=30,Qe=50,Be=75;let Oe=0,Pe=0;const Ve=r(nt=>{const Lt=nt.touches[0];Oe=Lt.clientX,Pe=Lt.clientY},"onTouchStart"),be=r(nt=>{const Lt=nt.changedTouches[0],Cs=Lt.clientX-Oe;if(!(Math.abs(Lt.clientY-Pe)>Be)){if(!s&&Oe<Rt&&Cs>Qe){n(!0);return}s&&Cs<-50&&n(!1)}},"onTouchEnd");return document.addEventListener("touchstart",Ve,{passive:!0}),document.addEventListener("touchend",be,{passive:!0}),()=>{document.removeEventListener("touchstart",Ve),document.removeEventListener("touchend",be)}},[c,s,n]),(0,m.useEffect)(()=>{const Rt=document.body.style.overflow;return document.body.style.overflow=c?"visible":"clip",()=>{document.body.style.overflow=Rt}},[c]),(0,m.useEffect)(()=>{if(!c)return X5e()},[c]),(0,m.useEffect)(()=>{if(typeof document>"u")return;const Rt=ie.current;return J5e(Rt)},[I.pathname]),(0,m.useEffect)(()=>{const Rt=ie.current;if(!Rt)return;const Qe=r(()=>{J.current.remember(ae.current,Rt.scrollTop)},"recordScroll");return Rt.addEventListener("scroll",Qe,{passive:!0}),()=>Rt.removeEventListener("scroll",Qe)},[]),(0,m.useLayoutEffect)(()=>{const Rt=ie.current,Qe=mke({previousPathname:Z.current,pathname:I.pathname,navigationType:T,state:I.state});Z.current=I.pathname;const Be=T==="POP",Oe=Be?J.current.recall(I.key):0;if(ae.current=I.key,Be){FR(Rt,Oe);const Pe=requestAnimationFrame(()=>FR(Rt,Oe));return()=>cancelAnimationFrame(Pe)}Qe&&pke(Rt)},[I.key,I.pathname,I.state,T]),(0,t.jsx)(dke,{children:(0,t.jsxs)("div",{className:W("bg-background text-foreground pt-(--sz-safe-top)",c?"min-h-dvh overflow-x-clip":"flex h-dvh flex-col overflow-clip"),children:[(0,t.jsx)("a",{href:"#main-content",className:"sr-only focus:not-sr-only focus:fixed focus:left-3 focus:top-3 focus:z-(--z-200) focus:rounded-md focus:bg-background focus:px-3 focus:py-2 focus:text-sm focus:font-medium focus:shadow-lg focus:outline-none focus-visible:ring-2 focus-visible:ring-ring",children:"Skip to Main Content"}),(0,t.jsx)(N5e,{}),(0,t.jsx)(S5e,{devServer:ue?.devServer}),(0,t.jsxs)("div",{className:W("min-h-0 flex-1",c?"w-full":"flex overflow-clip"),children:[c&&s&&(0,t.jsx)("button",{type:"button",className:"fixed inset-0 z-40 bg-black/50",onClick:r(()=>n(!1),"onClick"),"aria-label":"Close sidebar"}),c?(0,t.jsxs)("div",{className:W("fixed inset-y-0 left-0 z-50 flex flex-col overflow-hidden pt-(--sz-safe-top) transition-transform duration-100 ease-out",s?"translate-x-0":"-translate-x-full"),children:[(0,t.jsx)("div",{className:"flex flex-1 min-h-0 overflow-hidden",children:(0,t.jsx)("div",{className:"w-60 shrink-0 overflow-hidden",children:le?(0,t.jsx)($I,{children:xe}):(0,t.jsx)(lse,{children:e})})}),(0,t.jsx)(Pae,{deploymentMode:ue?.deploymentMode,forceExpanded:Le})]}):(0,t.jsxs)(e0t,{open:s,collapsed:Le?!1:i,peeking:Le?!1:o,resizable:!0,onPanelMouseEnter:Le?void 0:at,onPanelMouseLeave:Le?void 0:Me,onPanelFocusCapture:!Le&&i?De:void 0,onPanelBlurCapture:!Le&&i?ut:void 0,children:[(0,t.jsx)("div",{className:"flex flex-1 min-h-0",children:Le?(0,t.jsx)($I,{children:xe}):(0,t.jsx)(lse,{children:e})}),(0,t.jsx)(Pae,{deploymentMode:ue?.deploymentMode,forceExpanded:Le})]}),!c&&je&&!Re?(0,t.jsx)($I,{className:"w-60 shrink-0",children:xe}):null,(0,t.jsxs)("div",{className:W("flex min-w-0 flex-col",c?"w-full":"h-full flex-1"),children:[(0,t.jsxs)("div",{"data-slot":c?"mobile-topbar":void 0,className:W(!c&&q&&"hidden",c&&"sticky top-0 z-20 bg-background/95 backdrop-blur supports-[backdrop-filter]:bg-background/85"),children:[(0,t.jsx)(Wz,{mobile:c,onNavigateHome:r(()=>R("/dashboard"),"onNavigateHome")}),(0,t.jsx)(xse,{}),c&&O?(0,t.jsx)("div",{className:"border-b border-border px-4 pb-3",children:(0,t.jsx)(_Ne,{})}):null]}),(0,t.jsxs)("div",{className:W(c?"block":"flex flex-1 min-h-0",!c&&q&&"streamlined-task-detail-surface"),children:[!c&&Re?(0,t.jsx)($I,{className:"w-60 shrink-0 bg-background",children:xe}):null,(0,t.jsxs)("div",{className:W(!c&&q?"flex min-w-0 flex-1 flex-col":"contents"),children:[!c&&q?(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)(Wz,{mobile:!1,onNavigateHome:r(()=>R("/dashboard"),"onNavigateHome")}),(0,t.jsx)(xse,{taskDetailLayout:!0})]}):null,(0,t.jsx)("main",{id:"main-content",ref:ie,tabIndex:-1,style:c?{"--tc-composer-bottom":"var(--sz-calc-14)"}:void 0,className:W("flex-1 p-4 outline-none md:p-6",!c&&q&&"pt-0 md:pt-0",c?"overflow-visible pb-(--sz-calc-14)":"overflow-auto [scrollbar-gutter:stable]"),children:re?(0,t.jsx)(mm,{scope:"invalid_company_prefix",requestedPrefix:N??v?.issuePrefix}):(0,t.jsx)(A5e,{children:(0,t.jsx)(rv,{})})})]}),(0,t.jsx)(BNe,{taskDetailLayout:!c&&q})]})]})]}),c&&(0,t.jsx)(k5e,{visible:oe}),(0,t.jsx)(FNe,{}),(0,t.jsx)(N2e,{}),(0,t.jsx)(m5e,{}),(0,t.jsx)(f5e,{}),(0,t.jsx)(v5e,{}),(0,t.jsx)(y5e,{open:G,onOpenChange:X}),(0,t.jsx)(j5e,{}),(0,t.jsx)(kht,{health:ue}),(0,t.jsx)(w5e,{localTrusted:ue?.deploymentMode==="local_trusted"})]})})}r(M0t,"Layout$1");var e3e=(0,m.createContext)(!1);function P0t({children:e}){return(0,t.jsx)(e3e.Provider,{value:!0,children:e})}r(P0t,"SidebarNavExpandedProvider");function D0t(){return(0,m.useContext)(e3e)}r(D0t,"useSidebarNavExpanded");function Ya({to:e,label:s,icon:n,iconNode:a,end:i,className:o,labelClassName:l,badge:c,badgeTone:d="default",badgeLabel:u,textBadge:h,textBadgeTone:p="default",alert:f=!1,liveCount:x,active:g,trailing:v,trailingLabel:y,liveAccessory:k}){const{isMobile:w,setSidebarOpen:N,collapsed:S,peeking:C}=Ua(),_=D0t(),R=S&&!C&&!_,I=c!=null&&c>0,T=x!=null&&x>0,E=T?`${x} live`:I?`${c}${u?` ${u}`:""}`:f?"attention needed":void 0,P=!R||!E&&!y?void 0:`${s}${E?`, ${E}`:""}${y?`, ${y}`:""}`,O=(0,t.jsxs)(av,{to:e,state:Tf,end:i,"aria-label":P,onClick:r(()=>{w&&N(!1)},"onClick"),className:r(({isActive:M})=>W("flex items-center gap-2.5 mx-2 rounded-lg px-2 py-1.5 pointer-coarse:py-1 text-(length:--text-compact) font-medium transition-colors",g??M?"bg-accent text-foreground":"text-foreground/80 hover:bg-accent/50 hover:text-foreground",o),"className"),children:[(0,t.jsxs)("span",{className:"relative shrink-0",children:[a??(n?(0,t.jsx)(n,{className:"h-4 w-4"}):null),f&&(0,t.jsx)("span",{className:"absolute -right-0.5 -top-0.5 h-2 w-2 rounded-full bg-red-500 shadow-(--shadow-extract-12)","aria-hidden":"true"}),R&&!f&&T&&(0,t.jsxs)("span",{className:"absolute -right-0.5 -top-0.5 flex h-2 w-2","aria-hidden":"true",children:[(0,t.jsx)("span",{className:"animate-pulse absolute inline-flex h-full w-full rounded-full bg-blue-600 dark:bg-blue-400 opacity-75"}),(0,t.jsx)("span",{className:"relative inline-flex h-2 w-2 rounded-full bg-blue-600 dark:bg-blue-400 shadow-(--shadow-extract-12)"})]}),R&&!f&&!T&&I&&(0,t.jsx)("span",{className:W("absolute -right-0.5 -top-0.5 h-2 w-2 rounded-full shadow-(--shadow-extract-12)",d==="danger"?"bg-red-600":d==="warning"?"bg-amber-500":"bg-primary"),"aria-hidden":"true"})]}),(0,t.jsx)("span",{className:R?zj:W("min-w-0 flex-1 truncate",l),children:s}),!R&&v,!R&&h&&(0,t.jsx)(ot,{variant:"ghost",className:W("ml-auto px-1.5 text-(length:--text-nano) leading-none",p==="amber"?"bg-amber-100 text-amber-800 dark:bg-amber-900/30 dark:text-amber-400":"bg-muted text-muted-foreground"),children:h}),!R&&(T||k)&&(0,t.jsxs)("span",{className:"ml-auto flex items-center gap-1.5",children:[k,T&&(0,t.jsxs)(t.Fragment,{children:[(0,t.jsxs)("span",{className:"relative flex h-2 w-2",children:[(0,t.jsx)("span",{className:"animate-pulse absolute inline-flex h-full w-full rounded-full bg-blue-600 dark:bg-blue-400 opacity-75"}),(0,t.jsx)("span",{className:"relative inline-flex rounded-full h-2 w-2 bg-blue-600 dark:bg-blue-400"})]}),(0,t.jsxs)("span",{className:"text-(length:--text-micro) font-medium text-blue-600 dark:text-blue-400",children:[x," live"]})]})]}),!R&&I&&(0,t.jsx)(ot,{variant:"ghost",className:W("ml-auto px-1.5 leading-none",d==="danger"?"bg-red-600/90 text-red-50":d==="warning"?"bg-amber-500/90 text-amber-50":"bg-primary text-primary-foreground"),children:c})]});return R?(0,t.jsxs)(Fn,{children:[(0,t.jsx)(Bn,{asChild:!0,children:(0,t.jsx)("div",{children:O})}),(0,t.jsx)(On,{side:"right",children:s})]}):O}r(Ya,"SidebarNavItem");var $0t=3,Dae=12e4,O0t=[{value:"top",label:"Top"},{value:"alphabetical",label:"Alphabetical"},{value:"recent",label:"Recent"}];function Zw(e,s){const n=e[s];if(!n)return 0;const a=new Date(n).getTime();return Number.isFinite(a)?a:0}r(Zw,"agentTimestamp");function $ae(e,s){if(s==="top")return e;const n=[...e];return s==="alphabetical"?(n.sort((a,i)=>a.name.localeCompare(i.name,void 0,{sensitivity:"base"})),n):(n.sort((a,i)=>{const o=Zw(i,"lastHeartbeatAt")-Zw(a,"lastHeartbeatAt");if(o!==0)return o;const l=Zw(i,"updatedAt")-Zw(a,"updatedAt");if(l!==0)return l;const c=Zw(i,"createdAt")-Zw(a,"createdAt");return c!==0?c:a.name.localeCompare(i.name,void 0,{sensitivity:"base"})}),n)}r($ae,"sortAgents");var B0t="opacity-0 transition-opacity group-hover/agent:opacity-100 group-focus-within/agent:opacity-100";function F0t({activeAgentId:e,activeTab:s,agent:n,disabled:a,isMobile:i,leaving:o,onLeaveAgent:l,onPauseResume:c,rail:d,runCount:u,setSidebarOpen:h,builtInStatus:p,starred:f=!1,onToggleStar:x,starPending:g=!1}){const v=Hl(n),y=s?`${om(n)}/${s}`:om(n),k=`${om(n)}/configuration`,w=e===v,N=n.status==="paused",S=N&&n.pauseReason==="budget",C=n.orgChainHealth?.status==="invalid_org_chain",_=N?"Resume agent":"Pause agent",R=a||n.status==="pending_approval"||S||N&&C,I=a?"Updating...":S?"Budget paused":N&&C?"Invalid org chain":_,T=p==="needs_setup"||p==="pending_approval",E=[T?`Built-in agent ${p.replace(/_/g," ")}`:null,C?"Invalid reporting chain":null].filter(Boolean).join(", ")||void 0,P=(0,t.jsx)(Ya,{to:y,label:n.name,iconNode:(0,t.jsx)(lr,{agent:n,size:16,className:"shrink-0 h-4 w-4"}),active:w,liveCount:u,labelClassName:T?"min-w-(--sz-4_5rem) flex-initial":void 0,className:W("min-w-0 flex-1",f&&!i?"pr-14":"pr-8"),trailing:T||C?(0,t.jsxs)("span",{className:"ml-1 flex shrink-0 items-center gap-1",children:[T?(0,t.jsx)(kk,{status:p,compact:!0}):null,C?(0,t.jsx)(Es,{className:"h-3.5 w-3.5 shrink-0 text-amber-500","aria-label":"Invalid reporting chain"}):null]}):void 0,trailingLabel:E,liveAccessory:n.pauseReason==="budget"?(0,t.jsx)(P3,{title:"Agent paused by budget"}):void 0});return d?P:(0,t.jsxs)("div",{className:"group/agent relative flex items-center",children:[P,f&&!i&&x?(0,t.jsx)("span",{className:"absolute right-10 top-1/2 -translate-y-1/2",children:(0,t.jsx)(Yj,{size:"row",quiet:!0,starred:!0,pending:g,resourceName:n.name,onToggle:r(()=>x(n,!1),"onToggle"),revealClassName:B0t})}):null,(0,t.jsxs)(na,{children:[(0,t.jsx)(ta,{asChild:!0,children:(0,t.jsx)($,{variant:"ghost",size:"icon-xs",className:W("absolute right-3 top-1/2 h-6 w-6 -translate-y-1/2 transition-opacity data-[state=open]:pointer-events-auto data-[state=open]:opacity-100",i?"opacity-100":"pointer-events-none opacity-0 group-hover/agent:pointer-events-auto group-hover/agent:opacity-100 group-focus-within/agent:pointer-events-auto group-focus-within/agent:opacity-100"),"aria-label":`Open actions for ${n.name}`,children:(0,t.jsx)(_i,{className:"h-3.5 w-3.5"})})}),(0,t.jsxs)(sa,{align:"end",className:"w-48",children:[x?(0,t.jsxs)(t.Fragment,{children:[(0,t.jsxs)(us,{onClick:r(()=>{g||x(n,!f)},"onClick"),disabled:g,children:[g?(0,t.jsx)(st,{className:"size-4 motion-safe:animate-spin"}):(0,t.jsx)(V0,{className:W("size-4",f&&"fill-amber-500 text-amber-500")}),(0,t.jsx)("span",{children:f?"Remove from starred":"Star agent"})]}),(0,t.jsx)(ri,{})]}):null,(0,t.jsx)(us,{asChild:!0,children:(0,t.jsxs)(We,{to:k,onClick:r(()=>{i&&h(!1)},"onClick"),children:[(0,t.jsx)(rc,{className:"size-4"}),(0,t.jsx)("span",{children:"Edit agent"})]})}),(0,t.jsx)(ri,{}),(0,t.jsxs)(us,{onClick:r(()=>{R||c(n,N?"resume":"pause")},"onClick"),disabled:R,title:S?"Agent was paused by budget limits":void 0,children:[N?(0,t.jsx)(I3,{className:"size-4"}):(0,t.jsx)(Xd,{className:"size-4"}),(0,t.jsx)("span",{children:I})]}),(0,t.jsx)(ri,{}),(0,t.jsxs)(us,{onClick:r(()=>{o||l(n)},"onClick"),disabled:o,children:[o?(0,t.jsx)(st,{className:"size-4 motion-safe:animate-spin"}):(0,t.jsx)(rp,{className:"size-4"}),(0,t.jsx)("span",{children:o?"Leaving...":"Leave agent"})]})]})]})]})}r(F0t,"SidebarAgentItem");function z0t({streamlined:e=!1}={}){const[s,n]=(0,m.useState)(!0),[a,i]=(0,m.useState)(()=>new Set),[o,l]=(0,m.useState)(0),c=(0,m.useRef)(new Map),d=wt(),{selectedCompanyId:u}=fs(),h=g2(u),{openNewAgent:p}=al(),{isMobile:f,setSidebarOpen:x,collapsed:g,peeking:v}=Ua(),y=g&&!v,{pushToast:k}=Zr(),w=la(),{data:N}=te({queryKey:D.agents.list(u),queryFn:r(()=>Nt.list(u),"queryFn"),enabled:!!u}),{data:S}=te({queryKey:D.instance.experimentalSettings,queryFn:r(()=>jr.getExperimental(),"queryFn"),enabled:!!u}),C=S?.enableBuiltInAgents===!0,{data:_}=te({queryKey:D.builtInAgents.list(u),queryFn:r(()=>S0.list(u),"queryFn"),enabled:!!u&&C}),R=(0,m.useMemo)(()=>{const je=new Map;if(!C)return je;for(const _e of _??[])_e.agentId&&je.set(_e.agentId,_e.status);return je},[_,C]),{data:I}=te({queryKey:D.auth.session,queryFn:r(()=>Pa.getSession(),"queryFn")}),T=Rf(u),E=cv(u),P=D.liveRuns(u),O=jo({companyId:u,resourceKey:"live-runs",queryKey:P,enabled:!!u,refetchInterval:!1,leaderOnly:!0}),{data:M,dataUpdatedAt:Q}=te({queryKey:P,queryFn:r(()=>ea.liveRunsForCompany(u),"queryFn"),enabled:O.enabled,refetchInterval:O.refetchInterval});wo(O,M,Q);const L=(0,m.useMemo)(()=>{const je=new Map;for(const _e of M??[])je.set(_e.agentId,(je.get(_e.agentId)??0)+1);return je},[M]),F=(0,m.useMemo)(()=>{const je=new Set;for(const[_e,Ze]of L)Ze>0&&je.add(_e);return je},[L]),q=(0,m.useMemo)(()=>(N??[]).filter(je=>je.status!=="terminated"&&(!T.isSuccess||Yx(T.data,"agent",je.id)!=="left")),[N,T.data,T.isSuccess]),z=I?.user?.id??I?.session?.userId??null,K=(0,m.useMemo)(()=>u?Nke(u,z):null,[z,u]),[U,V]=(0,m.useState)(()=>K?Nk(K):"top"),{orderedAgents:ne}=_ke({agents:q,companyId:u,userId:z}),Z=(0,m.useMemo)(()=>$ae(ne,U),[ne,U]),ie=(0,m.useMemo)(()=>new Set(Z.map(je=>je.id)),[Z]);(0,m.useEffect)(()=>{const je=Date.now();for(const _e of F)c.current.set(_e,je);for(const _e of c.current.keys())ie.has(_e)||c.current.delete(_e)},[F,ie]);const J=(0,m.useMemo)(()=>{const je=Date.now(),_e=c.current;return Z.filter(Ze=>{if((L.get(Ze.id)??0)>0)return!0;const ue=_e.get(Ze.id);return ue!==void 0&&je-ue<=Dae})},[L,o,Z]),ae=J.length>0,oe=e?ae?J:Z.slice(0,$0t):Z,G=e&&Z.length>0,X=w.pathname.match(/^\/(?:[^/]+\/)?agents\/([^/]+)(?:\/([^/]+))?/),Y=X?.[1]??null,re=X?.[2]??null;(0,m.useEffect)(()=>{if(!K){V("top");return}V(Nk(K))},[K]),(0,m.useEffect)(()=>{if(!K)return;const je=r(Ze=>{Ze.key===K&&V(Nk(K))},"onStorage"),_e=r(Ze=>{const ue=Ze.detail;!ue||ue.storageKey!==K||V(ue.sortMode)},"onCustomEvent");return window.addEventListener("storage",je),window.addEventListener(Z_,_e),()=>{window.removeEventListener("storage",je),window.removeEventListener(Z_,_e)}},[K]),(0,m.useEffect)(()=>{if(!e)return;const je=Date.now();let _e=null;for(const ue of Z){if((L.get(ue.id)??0)>0)continue;const Fe=c.current.get(ue.id);if(Fe===void 0)continue;const mt=Fe+Dae;mt<je||(_e=_e===null?mt:Math.min(_e,mt))}if(_e===null)return;const Ze=window.setTimeout(()=>{l(ue=>ue+1)},Math.max(0,_e-je+1));return()=>{window.clearTimeout(Ze)}},[e,Z,L,o]);const se=(0,m.useCallback)(je=>{const _e=je==="alphabetical"||je==="recent"?je:"top";V(_e),K&&Cke(K,_e)},[K]),ce=we({mutationFn:r(({agent:je,action:_e})=>_e==="pause"?Nt.pause(je.id,u??void 0):Nt.resume(je.id,u??void 0),"mutationFn"),onMutate:r(({agent:je})=>{i(_e=>{const Ze=new Set(_e);return Ze.add(je.id),Ze})},"onMutate"),onSuccess:r(async(je,{agent:_e,action:Ze})=>{u&&await Promise.all([d.invalidateQueries({queryKey:D.agents.list(u)}),d.invalidateQueries({queryKey:D.liveRuns(u)}),d.invalidateQueries({queryKey:D.dashboard(u)})]),await Promise.all([d.invalidateQueries({queryKey:D.agents.detail(_e.id)}),d.invalidateQueries({queryKey:D.agents.detail(Hl(_e))})]),k({title:Ze==="pause"?"Agent paused":"Agent resumed",body:_e.name,tone:"success"})},"onSuccess"),onError:r((je,{agent:_e,action:Ze})=>{k({title:Ze==="pause"?"Could not pause agent":"Could not resume agent",body:je instanceof Error?je.message:_e.name,tone:"error"})},"onError"),onSettled:r((je,_e,{agent:Ze})=>{i(ue=>{const Fe=new Set(ue);return Fe.delete(Ze.id),Fe})},"onSettled")}),pe=(0,m.useCallback)(je=>E.mutate({resourceType:"agent",resourceId:je.id,resourceName:je.name,state:"left"}),[E]),fe=(0,m.useCallback)(je=>E.isPending&&E.variables?.resourceType==="agent"&&E.variables.resourceId===je.id,[E.isPending,E.variables]),ve=(0,m.useCallback)((je,_e)=>E.mutate({resourceType:"agent",resourceId:je.id,resourceName:je.name,starred:_e}),[E]),Ie=(0,m.useCallback)(je=>E.isPending&&E.variables?.resourceType==="agent"&&E.variables.resourceId===je.id&&E.variables.starred!==void 0,[E.isPending,E.variables]),de=(0,m.useMemo)(()=>new Set(zL(T.data,"agent")),[T.data]),xe=(0,m.useMemo)(()=>$ae(q.filter(je=>de.has(je.id)),"alphabetical"),[q,de]),le=(0,m.useMemo)(()=>oe.filter(je=>!de.has(je.id)),[oe,de]),Re=h&&!h.loading?q.find(je=>je.id===h.primaryAgentId):void 0,Le=r((je,_e)=>(0,t.jsx)(F0t,{activeAgentId:Y,activeTab:re,agent:je,disabled:a.has(je.id),isMobile:f,leaving:fe(je),onLeaveAgent:pe,onPauseResume:r((Ze,ue)=>ce.mutate({agent:Ze,action:ue}),"onPauseResume"),rail:y,runCount:L.get(je.id)??0,setSidebarOpen:x,builtInStatus:R.get(je.id),starred:_e||Gj(T.data,"agent",je.id),onToggleStar:ve,starPending:Ie(je)},je.id),"renderAgentRow");return(0,t.jsxs)($x,{label:"Agents",collapsible:{open:s,onOpenChange:n},headerAction:{ariaLabel:"New agent",icon:bn,onClick:p},menu:{ariaLabel:"Agents section actions",actions:[{type:"item",label:"Browse agents",icon:Wo,href:"/agents/all"},{type:"separator"}],radioLabel:"Agent sort",radioChoices:O0t,radioValue:U,onRadioValueChange:se},children:[[...Re?[Re]:[],...xe.filter(je=>je.id!==Re?.id),...le.filter(je=>je.id!==Re?.id)].map(je=>Le(je,de.has(je.id))),G&&(()=>{const je=(0,t.jsxs)(We,{to:"/agents/all",state:Tf,"aria-label":y?"See all agents":void 0,onClick:r(()=>{f&&x(!1)},"onClick"),className:"flex items-center gap-2.5 mx-2 rounded-lg px-2 py-1.5 pointer-coarse:py-1 text-(length:--text-compact) font-medium text-muted-foreground transition-colors hover:bg-accent/50 hover:text-foreground",children:[(0,t.jsx)(Wo,{className:"shrink-0 h-4 w-4"}),(0,t.jsx)("span",{className:y?"block w-0 min-w-0 overflow-hidden whitespace-nowrap text-transparent select-none":void 0,children:"See all agents"})]});return y?(0,t.jsxs)(Fn,{children:[(0,t.jsx)(Bn,{asChild:!0,children:je}),(0,t.jsx)(On,{side:"right",children:"See all agents"})]}):je})()]})}r(z0t,"SidebarAgents");var q0t="opacity-0 transition-opacity group-hover/starred-project:opacity-100 group-focus-within/starred-project:opacity-100";function U0t(){const{selectedCompanyId:e}=fs(),{isMobile:s,setSidebarOpen:n,collapsed:a,peeking:i}=Ua(),o=a&&!i,l=la(),{data:c}=te({queryKey:D.projects.list(e),queryFn:r(()=>aa.list(e),"queryFn"),enabled:!!e}),d=Rf(e),u=cv(e),h=l.pathname.match(/^\/(?:[^/]+\/)?projects\/([^/]+)/)?.[1]??null,p=(0,m.useMemo)(()=>{if(!d.isSuccess)return[];const v=new Set(zL(d.data,"project"));if(v.size===0)return[];const y=new Map((c??[]).map(k=>[k.id,k]));return Array.from(v).map(k=>y.get(k)).filter(k=>!!k).sort((k,w)=>k.name.localeCompare(w.name,void 0,{sensitivity:"base"}))},[d.data,d.isSuccess,c]),f=(0,m.useCallback)(v=>u.mutate({resourceType:"project",resourceId:v.id,resourceName:v.name,starred:!1}),[u]),x=(0,m.useCallback)(v=>u.mutate({resourceType:"project",resourceId:v.id,resourceName:v.name,state:"left"}),[u]),g=(0,m.useCallback)(v=>u.isPending&&u.variables?.resourceType==="project"&&u.variables.resourceId===v.id,[u.isPending,u.variables]);return!d.isSuccess||p.length===0?null:(0,t.jsx)("div",{className:"flex flex-col gap-0.5","aria-label":"Starred projects",children:p.map(v=>{const y=Qx(v),k=h===y||h===v.id,w=g(v),N=w&&u.variables?.starred===!1,S=w&&u.variables?.state==="left",C=Gj(d.data,"project",v.id),_=(0,t.jsxs)(av,{to:`/projects/${y}/issues`,state:Tf,onClick:r(()=>{s&&n(!1)},"onClick"),className:W("flex min-w-0 flex-1 items-center gap-2.5 mx-2 rounded-lg px-2 py-1.5 pointer-coarse:py-1 pr-8 text-(length:--text-compact) font-medium transition-colors",!o&&"pl-6",k?"bg-accent text-foreground":"text-foreground/80 hover:bg-accent/50 hover:text-foreground"),children:[(0,t.jsx)(nh,{color:v.color??null,icon:v.icon??null,size:"xs"}),(0,t.jsx)("span",{className:o?zj:"flex-1 truncate",children:v.name}),!o&&v.visibility==="private"?(0,t.jsx)(ko,{className:"size-3.5 shrink-0 text-muted-foreground","aria-label":"Private project"}):null,!o&&v.pauseReason==="budget"?(0,t.jsx)(P3,{title:"Project paused by budget"}):null]});return(0,t.jsxs)("div",{className:"group/starred-project relative flex items-center",children:[o?(0,t.jsxs)(Fn,{children:[(0,t.jsx)(Bn,{asChild:!0,children:(0,t.jsx)("div",{className:"min-w-0 flex-1",children:_})}),(0,t.jsx)(On,{side:"right",children:v.name})]}):_,!o&&!s?(0,t.jsx)("span",{className:"absolute right-3 top-1/2 -translate-y-1/2",children:(0,t.jsx)(Yj,{size:"row",quiet:!0,starred:C,pending:N,resourceName:v.name,onToggle:r(()=>f(v),"onToggle"),revealClassName:q0t})}):null,!o&&s?(0,t.jsxs)(na,{children:[(0,t.jsx)(ta,{asChild:!0,children:(0,t.jsx)($,{variant:"ghost",size:"icon-xs",className:"absolute right-3 top-1/2 h-6 w-6 -translate-y-1/2 opacity-100","aria-label":`Open actions for ${v.name}`,children:(0,t.jsx)(_i,{className:"h-3.5 w-3.5"})})}),(0,t.jsxs)(sa,{align:"end",className:"w-48",children:[(0,t.jsxs)(us,{onClick:r(()=>{w||f(v)},"onClick"),disabled:w,children:[N?(0,t.jsx)(st,{className:"size-4 motion-safe:animate-spin"}):(0,t.jsx)(V0,{className:"size-4 fill-amber-500 text-amber-500"}),(0,t.jsx)("span",{children:"Remove from starred"})]}),(0,t.jsx)(ri,{}),(0,t.jsxs)(us,{onClick:r(()=>{w||x(v)},"onClick"),disabled:w,children:[S?(0,t.jsx)(st,{className:"size-4 motion-safe:animate-spin"}):(0,t.jsx)(rp,{className:"size-4"}),(0,t.jsx)("span",{children:"Leave project"})]})]})]}):null]},v.id)})})}r(U0t,"SidebarStarredProjects");var K0t="size-5 shrink-0 rounded-md text-(length:--text-micro)",Q0t="size-(--organization-popover-avatar-size) shrink-0 rounded-lg text-(length:--text-micro)",W0t="h-(--organization-popover-company-row-height) min-w-0 gap-(--organization-popover-row-gap) rounded-lg px-2.5 py-0 text-(length:--text-compact) focus:bg-accent/50 focus:text-foreground",gD="h-(--organization-popover-action-row-height) gap-(--organization-popover-row-gap) rounded-lg px-2.5 py-0 text-(length:--text-compact) font-medium leading-(--organization-popover-action-line-height) text-foreground focus:bg-accent/50 focus:text-foreground";function t3e({company:e,inPopover:s=!1}){return(0,t.jsx)(Zx,{companyName:e.name,logoUrl:e.logoUrl,className:s?Q0t:K0t})}r(t3e,"WorkspaceIcon");function H0t({company:e,isEditing:s,isSelected:n,onSelect:a}){const{attributes:i,listeners:o,setActivatorNodeRef:l,setNodeRef:c,transform:d,transition:u,isDragging:h}=d2({id:e.id,disabled:!s});return(0,t.jsxs)(us,{ref:c,style:{transform:l2.Transform.toString(d),transition:u,zIndex:h?10:void 0},onSelect:r(p=>{if(s){p.preventDefault();return}a(e)},"onSelect"),className:W(W0t,s&&"cursor-grab",h&&"opacity-80"),children:[(0,t.jsx)(t3e,{company:e,inPopover:!0}),(0,t.jsxs)("span",{className:"min-w-0 flex-1",children:[(0,t.jsx)("span",{className:"block truncate font-medium leading-(--organization-popover-name-line-height)",children:e.name}),s?null:(0,t.jsx)("span",{className:"block truncate text-(length:--text-nano) leading-(--organization-popover-prefix-line-height) text-muted-foreground",children:e.issuePrefix})]}),s?(0,t.jsx)("button",{type:"button",ref:l,"aria-label":`Reorder ${e.name}`,className:"inline-flex size-8 shrink-0 items-center justify-center rounded text-muted-foreground hover:bg-accent hover:text-foreground focus-visible:outline-none focus-visible:ring-(length:--rad-2) focus-visible:ring-ring",onClick:r(p=>{p.preventDefault(),p.stopPropagation()},"onClick"),...i,...o,children:(0,t.jsx)(LL,{className:"size-4","aria-hidden":"true"})}):(0,t.jsx)("span",{className:"flex size-5 shrink-0 items-center justify-center",children:n?(0,t.jsx)(ms,{className:"size-4 text-foreground"}):null})]})}r(H0t,"SortableCompanyItem");function V0t(e={}){return(0,t.jsx)(jNe,{...e,children:(0,t.jsx)(G0t,{...e})})}r(V0t,"SidebarCompanyMenu");function G0t({open:e,onOpenChange:s}){const[n,a]=(0,m.useState)(!1),[i,o]=(0,m.useState)(!1),{companies:l,selectedCompany:c,setSelectedCompanyId:d,companyListUnavailable:u,retryCompanies:h}=fs(),{openOnboarding:p}=al(),{isMobile:f,setSidebarOpen:x,collapsed:g,peeking:v}=Ua(),y=g&&!v,k=la(),w=Gn(),N=e??n,S=s??a,C=r2(gf(WQ,{activationConstraint:{distance:8}}),gf(Mbe,{activationConstraint:{delay:180,tolerance:6}})),_=(0,m.useMemo)(()=>l.filter(Z=>Z.status!=="archived"),[l]),{data:R}=te({queryKey:D.auth.session,queryFn:r(()=>Pa.getSession(),"queryFn"),retry:!1}),I=R?.user?.id??R?.session?.userId??null,{orderedCompanies:T,persistOrder:E}=yNe({companies:_,userId:I}),{hidden:P,loaded:O}=Eu(),M=O&&!Kx(P,"company.members")&&!Kx(P,"company.invites"),Q="company",L=c?.name??null,F=!!td(),q=j2({onSignedOut:K});function z(Z){Z||o(!1),S(Z)}r(z,"handleOpenChange");function K(){S(!1),o(!1),f&&x(!1)}r(K,"closeNavigationChrome");function U(Z){const ie=k.pathname.split("/")[1]?.toUpperCase(),J=_.some(oe=>oe.issuePrefix.toUpperCase()===ie),ae=Z.id!==c?.id&&(k.pathname.startsWith("/instance/")||J);d(Z.id),S(!1),f&&x(!1),ae&&w(`/${Z.issuePrefix}/dashboard`)}r(U,"selectCompany");function V(){F||(S(!1),f&&x(!1),p({initialStep:1}))}r(V,"addCompany");const ne=(0,m.useCallback)(Z=>{const{active:ie,over:J}=Z;if(!J||ie.id===J.id)return;const ae=T.map(X=>X.id),oe=ae.indexOf(ie.id),G=ae.indexOf(J.id);oe===-1||G===-1||E(SL(ae,oe,G))},[T,E]);return(0,t.jsxs)(na,{open:N,onOpenChange:z,children:[(0,t.jsx)(ta,{asChild:!0,children:(0,t.jsxs)($,{variant:"ghost",className:"h-9 min-w-0 flex-1 justify-start gap-2 px-4 text-left hover:bg-accent/50 hover:text-foreground has-[>svg]:px-4 dark:hover:bg-accent/50","aria-label":L?`Open ${L} ${Q} switcher`:`Open ${Q} switcher`,children:[(0,t.jsxs)("span",{className:"flex min-w-0 flex-1 items-center gap-2",children:[c?(0,t.jsx)(t3e,{company:c}):null,(0,t.jsx)("span",{className:W("min-w-0 truncate text-sm font-bold text-foreground",y&&"block w-0 min-w-0 overflow-hidden whitespace-nowrap text-transparent select-none"),title:L??void 0,children:L??`Select ${Q}`})]}),!y&&(0,t.jsx)(kL,{className:"size-3.5 shrink-0 text-muted-foreground"})]})}),(0,t.jsxs)(sa,{align:"start",sideOffset:8,className:"ml-2 w-(--organization-popover-width) max-w-(--sz-calc-24) overflow-hidden rounded-xl border-border bg-popover p-0 shadow-(--shadow-profile-popover)",children:[(0,t.jsxs)("div",{className:"flex h-(--organization-popover-header-height) items-center justify-between gap-2 px-3.5",children:[(0,t.jsx)(ov,{className:"p-0 text-(length:--text-compact) font-semibold text-foreground",children:"Organizations"}),(0,t.jsx)("button",{type:"button",onClick:r(Z=>{Z.preventDefault(),Z.stopPropagation(),o(ie=>!ie)},"onClick"),className:"rounded px-1.5 py-0.5 text-xs font-medium text-muted-foreground transition-colors hover:bg-accent hover:text-foreground",children:i?"Done":"Edit"})]}),(0,t.jsxs)("div",{className:"flex max-h-96 flex-col gap-0.5 overflow-y-auto px-2.5 pb-2 pt-1",children:[(0,t.jsx)(c2,{sensors:C,collisionDetection:x3,onDragEnd:ne,children:(0,t.jsx)(o2,{items:T.map(Z=>Z.id),strategy:v3,children:T.map(Z=>(0,t.jsx)(H0t,{company:Z,isEditing:i,isSelected:Z.id===c?.id,onSelect:U},Z.id))})}),T.length===0?u?(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)(us,{disabled:!0,children:"Couldn't load companies"}),(0,t.jsxs)(us,{onSelect:r(Z=>{Z.preventDefault(),h()},"onSelect"),children:[(0,t.jsx)(Ii,{className:"h-4 w-4 mr-2"}),"Try again"]})]}):(0,t.jsx)(us,{disabled:!0,children:"No companies"}):null]}),(0,t.jsxs)("div",{className:"flex flex-col gap-0.5 border-t border-border px-2.5 pb-2.5 pt-2",children:[!F&&(0,t.jsxs)(us,{onClick:V,className:gD,disabled:i,children:[(0,t.jsx)("span",{className:"flex size-5 shrink-0 items-center justify-center text-muted-foreground",children:(0,t.jsx)(bn,{className:"size-4"})}),(0,t.jsx)("span",{className:"min-w-0 flex-1 truncate",children:"Create organization"})]}),M?(0,t.jsx)(us,{asChild:!0,disabled:i,className:gD,children:(0,t.jsxs)(We,{to:"/company/settings/invites",onClick:r(Z=>{if(i){Z.preventDefault();return}K()},"onClick"),children:[(0,t.jsx)("span",{className:"flex size-5 shrink-0 items-center justify-center text-muted-foreground",children:(0,t.jsx)(hh,{className:"size-4"})}),(0,t.jsx)("span",{className:"min-w-0 flex-1 truncate",children:L?`Invite people to ${L}`:"Invite people"})]})}):null,R?.session?(0,t.jsxs)(us,{className:gD,onClick:r(()=>q.mutate(),"onClick"),disabled:i||q.isPending,children:[(0,t.jsx)("span",{className:"flex size-5 shrink-0 items-center justify-center text-muted-foreground",children:(0,t.jsx)(rp,{className:"size-4"})}),(0,t.jsx)("span",{className:"min-w-0 flex-1 truncate",children:q.isPending?"Signing out...":"Sign out"})]}):null]})]})]})}r(G0t,"BuiltinCompanyMenu");function Oae(){const{openNewIssue:e}=al(),[s,n]=(0,m.useState)(!0),[a,i]=(0,m.useState)(!0),{selectedCompanyId:o,selectedCompany:l}=fs(),{collapsed:c,peeking:d}=Ua(),u=c&&!d,h=QL(o),{data:p,isFetched:f}=te({queryKey:D.instance.experimentalSettings,queryFn:r(()=>jr.getExperimental(),"queryFn")}),x=D.liveRuns(o),g=jo({companyId:o,resourceKey:"live-runs",queryKey:x,enabled:!!o,refetchInterval:!1,leaderOnly:!0}),{data:v,dataUpdatedAt:y}=te({queryKey:x,queryFn:r(()=>ea.liveRunsForCompany(o),"queryFn"),enabled:g.enabled,refetchInterval:g.refetchInterval});wo(g,v,y);const k=v?.length??0,w=p?.enableIsolatedWorkspaces===!0,N=p?.enableApps===!0,S=p?.enablePipelines===!0,C=p?.enableStatusCards===!0,_=!f,R=p?.enableGoalsSidebarLink===!0,I=p?.enableDecisions===!0,{data:T}=te({queryKey:D.attention(o),queryFn:r(()=>b2.list(o),"queryFn"),enabled:!!o&&I,refetchInterval:6e4}),E=Yke(T),P=p?.enableCases===!0,O=!0,M=p?.enableConferenceRoomChat===!0,Q={companyId:o,companyPrefix:l?.issuePrefix??null};return(0,t.jsxs)("aside",{className:"w-full h-full min-h-0 border-r border-border bg-background flex flex-col",children:[(0,t.jsx)("div",{className:"flex items-center gap-1 px-3 h-12 shrink-0",children:(0,t.jsx)(V0t,{})}),(0,t.jsxs)("nav",{className:"flex-1 min-h-0 overflow-y-auto scrollbar-auto-hide flex flex-col gap-4 pointer-coarse:gap-3 px-3 py-2",children:[(0,t.jsxs)("div",{className:"flex flex-col gap-0.5",children:[(()=>{const L=(0,t.jsxs)("button",{onClick:r(()=>e(),"onClick"),"data-slot":"icon-button","aria-label":u?"New Task":void 0,className:"flex items-center gap-2.5 mx-2 rounded-lg px-2 py-1.5 pointer-coarse:py-1 text-(length:--text-compact) font-medium text-foreground/80 hover:bg-accent/50 hover:text-foreground transition-colors",children:[(0,t.jsx)(V_,{className:"h-4 w-4 shrink-0"}),(0,t.jsx)("span",{className:u?zj:"truncate",children:"New Task"})]});return u?(0,t.jsxs)(Fn,{children:[(0,t.jsx)(Bn,{asChild:!0,children:L}),(0,t.jsx)(On,{side:"right",children:"New Task"})]}):L})(),(0,t.jsx)(Ya,{to:"/search",label:"Search",icon:Yr}),(0,t.jsx)(Ya,{to:"/dashboard",label:"Dashboard",icon:Dx,liveCount:k}),(0,t.jsx)(Ya,{to:"/inbox",label:"Inbox",icon:Od,badge:h.inbox,badgeLabel:"unread",badgeTone:h.failedRuns>0?"danger":"default",alert:h.failedRuns>0}),I?(0,t.jsx)(Ya,{to:"/decisions",label:"Decisions",icon:Hj,badge:E,badgeLabel:"decisions"}):null,C?(0,t.jsx)(Ya,{to:"/status",label:"Status",icon:f2,textBadge:"beta"}):null,M?(0,t.jsx)(Ya,{to:"/board-chat",label:"Conference Room",icon:uwe}):null]}),(0,t.jsxs)($x,{label:"Work",collapsible:{open:s,onOpenChange:n},children:[(0,t.jsx)(Ya,{to:"/issues",label:"Tasks",icon:nm}),P?(0,t.jsx)(Ya,{to:"/cases",label:"Cases",icon:Vl,textBadge:"beta"}):null,(0,t.jsx)(Ya,{to:"/routines",label:"Routines",icon:lm}),S?(0,t.jsx)(Ya,{to:"/pipelines",label:"Pipelines",icon:Xi}):null,R?(0,t.jsx)(Ya,{to:"/goals",label:"Goals",icon:H0}):_?(0,t.jsx)("div",{"data-testid":"sidebar-goals-placeholder",className:"h-8 pointer-coarse:h-7","aria-hidden":"true"}):null,(0,t.jsx)(Ya,{to:"/artifacts",label:"Artifacts",icon:t0}),(0,t.jsx)(Ya,{to:"/skills",label:"Skills",icon:Ac}),w?(0,t.jsx)(Ya,{to:"/workspaces",label:"Workspaces",icon:Xi}):null,(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)(Ya,{to:"/projects",label:"Projects",icon:nl}),(0,t.jsx)(U0t,{})]}),(0,t.jsx)(X0,{errorBehavior:"hidden",slotTypes:["sidebar"],context:Q,className:"flex flex-col gap-0.5",itemClassName:"text-(length:--text-compact) font-medium",missingBehavior:"placeholder"}),(0,t.jsx)(y2,{errorBehavior:"hidden",placementZones:["sidebar"],context:Q,className:"flex flex-col gap-0.5",itemClassName:"text-(length:--text-compact) font-medium"})]}),null,(0,t.jsx)(z0t,{streamlined:O}),(0,t.jsxs)($x,{label:"Company",collapsible:{open:a,onOpenChange:i},children:[(0,t.jsx)(Ya,{to:"/org",label:"Org",icon:Ub}),N?(0,t.jsx)(Ya,{to:"/apps",label:"Connectors",icon:OR}):null,(0,t.jsx)(Ya,{to:"/timeline",label:"Timeline",icon:ob}),(0,t.jsx)(Ya,{to:"/costs",label:"Costs",icon:B0}),(0,t.jsx)(Ya,{to:"/activity",label:"Activity",icon:mc}),(0,t.jsx)(Ya,{to:"/company/settings",label:"Settings",icon:Iu})]}),(0,t.jsx)(X0,{errorBehavior:"hidden",slotTypes:["sidebarPanel"],context:Q,className:"flex flex-col gap-3",itemClassName:"rounded-lg border border-border p-3",missingBehavior:"placeholder"})]})]})}r(Oae,"Sidebar");function Y0t(e){const s=e.manifestJson.environmentDrivers??[];return s.length===0?!1:s.every(n=>n.kind==="sandbox_provider")}r(Y0t,"isSandboxProviderOnly");function Z0t(){const{selectedCompany:e,selectedCompanyId:s}=fs(),{isMobile:n,setSidebarOpen:a}=Ua(),{hidden:i}=Eu(),{enabled:o}=Xj(),l=r(x=>!i.has(x),"showPage"),c=l("instance.plugins"),d=!!td(),{slots:u}=Bd({slotTypes:["companySettingsPage"],companyId:s,enabled:!!s}),{data:h}=te({queryKey:s?D.sidebarBadges(s):["sidebar-badges","__disabled__"],queryFn:r(async()=>{try{return await UW.get(s)}catch(x){if(x instanceof nn&&(x.status===401||x.status===403))return null;throw x}},"queryFn"),enabled:!!s,retry:!1,refetchInterval:15e3}),{data:p}=te({queryKey:D.plugins.all,queryFn:r(()=>El.list(),"queryFn"),enabled:c}),f=(p??[]).filter(x=>!Y0t(x));return(0,t.jsxs)("aside",{className:"w-full h-full min-h-0 border-r border-border bg-background flex flex-col",children:[(0,t.jsx)("div",{className:"flex flex-col gap-1 px-3 py-3 shrink-0",children:(0,t.jsxs)(We,{to:"/dashboard",onClick:r(()=>{n&&a(!1)},"onClick"),className:"flex items-center gap-1.5 rounded-md px-2 py-1 text-xs text-muted-foreground transition-colors hover:bg-accent/50 hover:text-foreground",children:[(0,t.jsx)(xm,{className:"h-3.5 w-3.5 shrink-0"}),(0,t.jsx)("span",{className:"truncate",children:e?.name??"Company"})]})}),(0,t.jsx)("nav",{className:"flex-1 min-h-0 overflow-y-auto scrollbar-auto-hide px-3 py-2",children:(0,t.jsxs)("div",{className:"flex flex-col gap-0.5",children:[(0,t.jsx)(Ya,{to:"/company/settings",label:"General",icon:gm,end:!0}),l("instance.profile")&&(0,t.jsx)(Ya,{to:"/company/settings/instance/profile",label:"Profile",icon:$L,end:!0}),l("company.members")&&(0,t.jsx)(Ya,{to:"/company/settings/members",label:"Members",icon:Wo,badge:h?.joinRequests??0,end:!0}),u.filter(x=>x.routePath).map(x=>(0,t.jsx)(Ya,{to:`/company/settings/${x.routePath}`,label:x.displayName,icon:Mx,end:!0},`${x.pluginKey}:${x.id}`)),l("company.invites")&&(0,t.jsx)(Ya,{to:"/company/settings/invites",label:"Invites",icon:SKe,end:!0}),l("company.secrets")&&(0,t.jsx)(Ya,{to:"/company/settings/secrets",label:"Secrets",icon:Si,end:!0}),l("instance.environments")&&(0,t.jsx)(Ya,{to:"/company/settings/instance/environments",label:"Environments",icon:xwe,end:!0}),o&&(0,t.jsx)(Ya,{to:"/company/settings/connections",label:"Connections",icon:Ml,end:!0}),l("instance.access")&&(0,t.jsx)(Ya,{to:"/company/settings/instance/access",label:"Access",icon:p3,end:!0}),l("instance.heartbeats")&&(0,t.jsx)(Ya,{to:"/company/settings/instance/heartbeats",label:"Heartbeats",icon:Au,end:!0}),l("company.export")&&(0,t.jsx)(Ya,{to:"/company/export",label:"Export",icon:Fi}),!d&&l("company.import")&&(0,t.jsx)(Ya,{to:"/company/import",label:"Import",icon:Kb,end:!0}),l("instance.experimental")&&(0,t.jsx)(Ya,{to:"/company/settings/instance/experimental",label:"Experimental",icon:rh}),c&&(0,t.jsx)(Ya,{to:"/company/settings/instance/plugins",label:"Plugins",icon:Mx}),c&&f.length>0?(0,t.jsx)("div",{className:"ml-4 mt-1 flex flex-col gap-0.5 border-l border-border/70 pl-3",children:f.map(x=>(0,t.jsx)(av,{to:`${C0}/plugins/${x.id}`,state:Tf,className:r(({isActive:g})=>["rounded-md px-2 py-1.5 text-xs transition-colors",g?"bg-accent text-foreground":"text-muted-foreground hover:bg-accent/50 hover:text-foreground"].join(" "),"className"),children:x.manifestJson.displayName??x.packageName},x.id))}):null,l("instance.adapters")&&(0,t.jsx)(Ya,{to:"/company/settings/instance/adapters",label:"Adapters",icon:Vm})]})})]})}r(Z0t,"CompanySettingsSidebar");function J0t(){const{pathname:e}=la(),{selectedCompany:s}=fs(),{isMobile:n,setSidebarOpen:a}=Ua(),i=TNe(),{enabled:o}=WL(),l=GW.filter(d=>!INe(d.key)||o);if(e.endsWith("/apps/chat/connect"))return(0,t.jsx)(ANe,{NavItem:Ya});const c=e.match(/\/apps\/chat\/([^/]+)(?:\/(?:settings|access|conversations|activity|approvals|audit)|\/reviews(?:\/[^/]+)?)?\/?$/);return c?(0,t.jsx)(WW,{endpointId:c[1],NavItem:Ya}):(0,t.jsxs)("aside",{className:"w-full h-full min-h-0 border-r border-border bg-background flex flex-col",children:[(0,t.jsxs)("div",{className:"flex flex-col gap-1 px-3 py-3 shrink-0",children:[(0,t.jsxs)(We,{to:"/dashboard",onClick:r(()=>{n&&a(!1)},"onClick"),className:"flex items-center gap-1.5 rounded-md px-2 py-1 text-xs text-muted-foreground transition-colors hover:bg-accent/50 hover:text-foreground",children:[(0,t.jsx)(xm,{className:"h-3.5 w-3.5 shrink-0"}),(0,t.jsx)("span",{className:"truncate",children:s?.name??"Company"})]}),(0,t.jsxs)("div",{className:"flex items-center gap-2 px-2 py-1",children:[(0,t.jsx)(ute,{className:"h-4 w-4 text-muted-foreground shrink-0"}),(0,t.jsx)("span",{className:"flex-1 truncate text-sm font-bold text-foreground",children:"Connectors"})]})]}),(0,t.jsxs)("nav",{className:"flex-1 min-h-0 overflow-y-auto scrollbar-auto-hide px-3 py-2",children:[(0,t.jsx)("div",{className:"px-3 pb-1 text-(length:--text-micro) font-semibold uppercase tracking-wide text-muted-foreground",children:"Connectors"}),(0,t.jsxs)("div",{className:"flex flex-col gap-0.5",children:[(0,t.jsx)(Ya,{to:"/apps",label:"Browse",icon:G_,end:!0}),(0,t.jsx)(Ya,{to:"/apps/review",label:"Review",icon:x2,badge:i>0?i:void 0,badgeTone:"warning",badgeLabel:"waiting for your OK"})]}),(0,t.jsx)("div",{className:"px-3 pb-1 pt-4 text-(length:--text-micro) font-semibold uppercase tracking-wide text-muted-foreground",children:"Developer"}),(0,t.jsx)("p",{className:"px-3 pb-1.5 text-(length:--text-micro) leading-snug text-muted-foreground/70",children:"Advanced setup for developers. Most teams never open this."}),(0,t.jsxs)("div",{className:"flex flex-col gap-0.5",children:[(0,t.jsx)(Ya,{to:"/apps/connections",label:"Connections",icon:ute,end:!0}),l.map(d=>(0,t.jsx)(Ya,{to:Sb(d.key),label:d.label,icon:d.icon,end:!0},d.key))]})]})]})}r(J0t,"AppsSidebar");function Bae(e){const{selectedCompanyId:s}=fs(),{isMobile:n,setSidebarOpen:a}=Ua(),i=te({queryKey:D.tools.connection(e.kind==="connection"?e.connectionId:"__none__"),queryFn:r(()=>ts.getConnection(e.kind==="connection"?e.connectionId:""),"queryFn"),enabled:e.kind==="connection"&&!!e.connectionId}),o=te({queryKey:D.tools.applications(s??"__none__"),queryFn:r(()=>ts.listApplications(s),"queryFn"),enabled:e.kind==="application"&&!!s}),l=te({queryKey:D.tools.connections(s??"__none__"),queryFn:r(()=>ts.listConnections(s),"queryFn"),enabled:e.kind==="application"&&!!s}),c=te({queryKey:D.apps.gallery(s??"__none__"),queryFn:r(()=>ts.listGallery(s),"queryFn"),enabled:!!s}),d=te({queryKey:D.apps.attention(s??"__none__"),queryFn:r(()=>ts.listAppsAttention(s),"queryFn"),enabled:!!s,refetchInterval:3e4}),u=i.data,h=e.kind==="application"?(o.data?.applications??[]).find(k=>k.id===e.applicationId):null,p=tpt(e.kind==="application"?(l.data?.connections??[]).filter(k=>k.applicationId===e.applicationId):[]),f=u?vf(u):h?.name??"App",x=ept(c.data?.apps??[],u,h??void 0),g=u?.id??p?.id??null,v=g?d.data?.apps.find(k=>k.connection.id===g):null,y=(v?.pendingActionRequestCount??0)+((v?.quarantinedCatalogEntryCount??0)>0?1:0);return(0,t.jsxs)("aside",{className:"flex h-full min-h-0 w-full flex-col border-r border-border bg-background",children:[(0,t.jsxs)("div",{className:"flex shrink-0 flex-col gap-3 px-3 py-3",children:[(0,t.jsxs)(We,{to:"/apps/connections",onClick:r(()=>{n&&a(!1)},"onClick"),className:"flex items-center gap-1.5 rounded-md px-2 py-1 text-xs text-muted-foreground transition-colors hover:bg-accent/50 hover:text-foreground",children:[(0,t.jsx)(xm,{className:"h-3.5 w-3.5 shrink-0"}),(0,t.jsx)("span",{className:"truncate",children:"All apps"})]}),(0,t.jsxs)("div",{className:"flex min-w-0 items-center gap-2 px-2 py-1",children:[(0,t.jsx)(Hi,{name:f,logoUrl:B3(x),size:28}),(0,t.jsx)("span",{className:"flex-1 truncate text-sm font-bold text-foreground",children:f})]})]}),(0,t.jsx)("nav",{className:"scrollbar-auto-hide min-h-0 flex-1 overflow-y-auto px-3 py-2",children:(0,t.jsx)("div",{className:"flex flex-col gap-0.5",children:HL.map(k=>(0,t.jsx)(Ya,{to:X0t(e,k.key),label:k.label,icon:k.icon,end:!0,badge:k.key==="review"&&y>0?y:void 0,badgeTone:"danger",badgeLabel:"needing review"},k.key))})})]})}r(Bae,"AppDetailSidebar");function X0t(e,s){return e.kind==="connection"?Qm(e.connectionId,s):s_(e.applicationId,s)}r(X0t,"tabHref");function ept(e,s,n){if(n?.applicationKey){const i=e.find(o=>kc(o)===n.applicationKey);if(i)return i}const a=(s?.name??n?.name)?.toLowerCase();return a?e.find(i=>Ox(i).toLowerCase()===a)??e.find(i=>kc(i)===a)??null:null}r(ept,"galleryEntryFor$1");function tpt(e){const s=e.filter(n=>n.status==="archived");return s.length===0?null:s.reduce((n,a)=>{const i=new Date(n.updatedAt??n.createdAt??0).getTime();return new Date(a.updatedAt??a.createdAt??0).getTime()>i?a:n})}r(tpt,"latestArchivedConnection$1");function bD({identifier:e}){return e?(0,t.jsx)("span",{className:"shrink-0 font-mono text-muted-foreground",children:e}):null}r(bD,"CrumbIdentifier");function spt({context:e}){const{slots:s}=Bd({slotTypes:["globalToolbarButton"],companyId:e.companyId}),{launchers:n}=QW({placementZones:["globalToolbarButton"],companyId:e.companyId,enabled:!!e.companyId});return(0,t.jsxs)("div",{className:"ml-auto flex shrink-0 items-center gap-1 pl-2 empty:hidden",children:[s.length>0?(0,t.jsx)(X0,{slotTypes:["globalToolbarButton"],context:e,className:"flex items-center gap-1"}):null,n.length>0?(0,t.jsx)(y2,{placementZones:["globalToolbarButton"],context:e,className:"flex items-center gap-1"}):null]})}r(spt,"GlobalToolbar");function npt(){const{breadcrumbs:e,mobileToolbar:s}=Vn(),{toggleSidebar:n,isMobile:a}=Ua(),{selectedCompanyId:i,selectedCompany:o}=fs(),l=(0,m.useMemo)(()=>({companyId:i??null,companyPrefix:o?.issuePrefix??null}),[i,o?.issuePrefix]),c=(0,t.jsx)(spt,{context:l});if(a&&s)return(0,t.jsx)("div",{className:"border-b border-border px-2 h-12 shrink-0 flex items-center",children:s});if(e.length===0)return(0,t.jsx)("div",{className:"border-b border-border px-4 md:px-6 h-12 shrink-0 flex items-center justify-end",children:c});const d=a&&(0,t.jsx)($,{variant:"ghost",size:"icon-sm",className:"mr-2 shrink-0",onClick:n,"aria-label":"Open sidebar",children:(0,t.jsx)(swe,{className:"h-5 w-5"})});return e.length===1?(0,t.jsxs)("div",{className:"border-b border-border px-4 md:px-6 h-12 shrink-0 flex items-center",children:[d,(0,t.jsx)("div",{className:"min-w-0 overflow-hidden flex-1",children:e[0].leading||e[0].identifier?(0,t.jsxs)("h1",{className:"flex items-center gap-1.5 text-sm font-semibold uppercase tracking-wider",children:[e[0].leading&&(0,t.jsx)("span",{className:"flex shrink-0 items-center",children:e[0].leading}),(0,t.jsx)(bD,{identifier:e[0].identifier}),(0,t.jsx)("span",{className:"truncate",children:e[0].label})]}):(0,t.jsx)("h1",{className:"text-sm font-semibold uppercase tracking-wider truncate",children:e[0].label})}),c]}):(0,t.jsxs)("div",{className:"border-b border-border px-4 md:px-6 h-12 shrink-0 flex items-center",children:[d,(0,t.jsx)("div",{className:"min-w-0 overflow-hidden flex-1",children:(0,t.jsx)(YW,{className:"min-w-0 overflow-hidden",children:(0,t.jsx)(ZW,{className:"flex-nowrap",children:e.map((u,h)=>{const p=h===e.length-1;return(0,t.jsxs)(m.Fragment,{children:[h>0&&(0,t.jsx)(GR,{}),(0,t.jsx)(n_,{className:p?"min-w-0":"shrink-0",children:p||!u.href?u.leading||u.identifier?(0,t.jsxs)(s5,{className:"flex min-w-0 items-center gap-1.5",children:[u.leading&&(0,t.jsx)("span",{className:"flex shrink-0 items-center",children:u.leading}),(0,t.jsx)(bD,{identifier:u.identifier}),(0,t.jsx)("span",{className:"truncate",children:u.label})]}):(0,t.jsx)(s5,{className:"truncate",children:u.label}):(0,t.jsx)(VR,{asChild:!0,children:u.leading||u.identifier?(0,t.jsxs)(We,{to:u.href,onClick:u.onClick,className:"flex items-center gap-1.5",children:[u.leading&&(0,t.jsx)("span",{className:"flex shrink-0 items-center",children:u.leading}),(0,t.jsx)(bD,{identifier:u.identifier}),(0,t.jsx)("span",{className:"truncate",children:u.label})]}):(0,t.jsx)(We,{to:u.href,onClick:u.onClick,children:u.label})})})]},h)})})})}),c]})}r(npt,"BreadcrumbBar");var OI=240,Jz=208,Xz=420,Fae=16;function ME(e){return Math.min(Xz,Math.max(Jz,e))}r(ME,"clampSidebarWidth");function zae(e){if(typeof window>"u")return OI;try{const s=window.localStorage.getItem(e);if(!s)return OI;const n=Number.parseInt(s,10);return Number.isFinite(n)?ME(n):OI}catch{return OI}}r(zae,"readStoredSidebarWidth");function qae(e,s){if(!(typeof window>"u"))try{window.localStorage.setItem(e,String(ME(s)))}catch{}}r(qae,"writeStoredSidebarWidth");function rpt({children:e,open:s,collapsed:n=!1,peeking:a=!1,resizable:i=!1,storageKey:o="paperclip.sidebar.width",className:l,onPanelMouseEnter:c,onPanelMouseLeave:d,onPanelFocusCapture:u,onPanelBlurCapture:h}){const[p,f]=(0,m.useState)(()=>zae(o)),[x,g]=(0,m.useState)(!1),v=(0,m.useRef)(p),y=(0,m.useRef)(null);(0,m.useEffect)(()=>{const M=zae(o);v.current=M,f(M)},[o]);const k=s?p:0,w=s?n?64:k:0,N=s?n&&!a?64:k:0,S=N>w,C=i&&s&&!n,_=(0,m.useMemo)(()=>({width:`${w}px`}),[w]),R=(0,m.useMemo)(()=>({width:`${N}px`}),[N]),I=(0,m.useCallback)(M=>{const Q=ME(M);v.current=Q,f(Q),qae(o,Q)},[o]),T=(0,m.useCallback)(M=>{C&&(M.preventDefault(),M.currentTarget.setPointerCapture(M.pointerId),y.current={startX:M.clientX,startWidth:v.current},g(!0))},[C]),E=(0,m.useCallback)(M=>{if(!y.current)return;const Q=ME(y.current.startWidth+M.clientX-y.current.startX);v.current=Q,f(Q)},[]),P=(0,m.useCallback)(()=>{y.current&&(y.current=null,g(!1),qae(o,v.current))},[o]),O=(0,m.useCallback)(M=>{C&&(M.key==="ArrowLeft"?(M.preventDefault(),I(p-Fae)):M.key==="ArrowRight"?(M.preventDefault(),I(p+Fae)):M.key==="Home"?(M.preventDefault(),I(Jz)):M.key==="End"&&(M.preventDefault(),I(Xz)))},[C,I,p]);return(0,t.jsx)("div",{className:W("relative h-full shrink-0",l),style:_,children:(0,t.jsxs)("div",{className:W("absolute inset-y-0 left-0 flex flex-col overflow-hidden",S?"z-30 border-r border-border bg-background shadow-lg":"z-0"),style:R,"data-sidebar-overlay":S?"":void 0,onMouseEnter:c,onMouseLeave:d,onFocusCapture:u,onBlurCapture:h,children:[e,C?(0,t.jsx)("div",{role:"separator","aria-label":"Resize sidebar","aria-orientation":"vertical","aria-valuemin":Jz,"aria-valuemax":Xz,"aria-valuenow":p,tabIndex:0,className:W("absolute inset-y-0 right-0 z-20 w-3 cursor-col-resize touch-none outline-none","before:absolute before:inset-y-0 before:left-1/2 before:w-px before:-translate-x-1/2 before:bg-transparent before:transition-colors","hover:before:bg-border focus-visible:before:bg-ring",x&&"before:bg-ring"),onPointerDown:T,onPointerMove:E,onPointerUp:P,onPointerCancel:P,onLostPointerCapture:P,onKeyDown:O}):null]})})}r(rpt,"SidebarShell");function apt({children:e,className:s}){return(0,t.jsx)("div",{"data-secondary-sidebar":"",className:W("h-full w-60 shrink-0 overflow-y-auto border-r border-border bg-background",s),children:(0,t.jsx)(P0t,{children:e})})}r(apt,"SecondarySidebar");var ipt="/company/settings/members?tab=invites",opt="https://docs.paperclip.ing/",lpt="https://paperclip.ing/feedback";function cpt(e){const s=e.trim().split(/\s+/).filter(Boolean);return s.length>=2?`${s[0]?.[0]??""}${s[s.length-1]?.[0]??""}`.toUpperCase():e.slice(0,2).toUpperCase()}r(cpt,"deriveInitials$1");function Uae({label:e,description:s,icon:n,onClick:a,href:i,external:o=!1,topLevel:l=!1}){const c="flex w-full items-start gap-3 rounded-xl px-3 py-3 text-left transition-colors hover:bg-accent/60",d=(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)("span",{className:"mt-0.5 rounded-lg border border-border bg-background/70 p-2 text-muted-foreground",children:(0,t.jsx)(n,{className:"size-4"})}),(0,t.jsxs)("span",{className:"min-w-0 flex-1",children:[(0,t.jsx)("span",{className:"block text-sm font-medium text-foreground",children:e}),(0,t.jsx)("span",{className:"block text-xs text-muted-foreground",children:s})]})]});return i?o?(0,t.jsx)("a",{href:i,target:"_blank",rel:"noreferrer",className:c,onClick:a,children:d}):l?(0,t.jsx)("a",{href:i,className:c,onClick:a,children:d}):(0,t.jsx)(We,{to:i,className:c,onClick:a,children:d}):(0,t.jsx)("button",{type:"button",className:c,onClick:a,children:d})}r(Uae,"MenuAction");function Kae({deploymentMode:e,open:s,onOpenChange:n}){const i=!!td(),{hidden:o,loaded:l}=Eu(),c=D5e(),d=$5e(!i),u=i?c:d?ipt:null,h=l&&u!==null&&!Kx(o,"company.members")&&!Kx(o,"company.invites"),[p,f]=(0,m.useState)(!1),{isMobile:x,setSidebarOpen:g,collapsed:v,peeking:y}=Ua(),k=v&&!y,w=s??p,N=O5e(w),S=n??f,{data:C}=te({queryKey:D.auth.session,queryFn:r(()=>Pa.getSession(),"queryFn"),retry:!1}),_=j2({onSignedOut:P}),R=C?.user.name?.trim()||"Board",I=C?.user.email?.trim()||(e==="authenticated"?"Signed in":"Local workspace board"),T=cpt(R),E=B5e(C?.user);function P(){S(!1),x&&g(!1)}r(P,"closeNavigationChrome");function O(){_.mutate()}return r(O,"handleSignOut"),(0,t.jsx)("div",{className:"border-t border-r border-border bg-background px-3 py-2",children:(0,t.jsxs)("div",{className:W("flex items-center gap-0.5",!k&&"px-2"),children:[(0,t.jsxs)(dr,{open:w,onOpenChange:S,children:[(0,t.jsx)(wr,{asChild:!0,children:(0,t.jsxs)("button",{type:"button",className:W("flex min-w-0 items-center gap-2.5 rounded-lg text-left text-(length:--text-compact) font-medium text-foreground/80 transition-colors hover:bg-accent/50 hover:text-foreground",k?"w-full px-3 py-2":"flex-1 px-2 py-1.5"),"aria-label":"Open account menu",children:[(0,t.jsxs)(bo,{size:"sm",children:[C?.user.image?(0,t.jsx)(Jc,{src:C.user.image,alt:R}):null,(0,t.jsx)(vo,{children:T})]}),(0,t.jsx)("span",{className:W("min-w-0 flex-1 truncate",k&&"block w-0 min-w-0 overflow-hidden whitespace-nowrap text-transparent select-none"),children:R})]})}),(0,t.jsxs)(nr,{side:"top",align:"start",sideOffset:10,className:"w-(--sz-277px) max-w-(--sz-calc-24) overflow-hidden rounded-t-2xl rounded-b-none border-border p-0 shadow-2xl",children:[(0,t.jsx)("div",{className:"h-24 bg-(image:--gradient-extract-25)"}),(0,t.jsxs)("div",{className:"-mt-8 px-4 pb-4",children:[(0,t.jsxs)("div",{className:"relative flex items-start gap-3",children:[(0,t.jsx)(We,{to:E,"aria-label":"View profile",onClick:P,className:"absolute inset-0 rounded-xl transition-colors hover:bg-accent/60 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"}),(0,t.jsx)("div",{className:"pointer-events-none relative rounded-2xl border-4 border-popover bg-popover p-0.5 shadow-sm",children:(0,t.jsxs)(bo,{size:"lg",children:[C?.user.image?(0,t.jsx)(Jc,{src:C.user.image,alt:R}):null,(0,t.jsx)(vo,{children:T})]})}),(0,t.jsxs)("div",{className:"pointer-events-none relative min-w-0 flex-1 pt-1",children:[(0,t.jsx)("h2",{className:"truncate text-base font-semibold text-foreground",children:R}),(0,t.jsx)("p",{className:"truncate text-sm text-muted-foreground",children:I}),N?(0,t.jsxs)("a",{className:"pointer-events-auto block truncate font-mono text-(length:--text-micro) leading-(--profile-popover-meta-line-height) text-muted-foreground hover:underline focus-visible:underline",href:`https://github.com/paperclipai/paperclip/commit/${N}`,target:"_blank",rel:"noreferrer","aria-label":`View commit ${N} on GitHub`,title:N,children:["SHA ",N.slice(0,7)]}):null]})]}),(0,t.jsxs)("div",{className:"mt-4 space-y-1",children:[h&&u?(0,t.jsx)(Uae,{label:"Invite",description:"Invite people to your organization.",icon:hh,href:u,topLevel:i,onClick:P}):null,(0,t.jsx)(Uae,{label:"Documentation",description:"Open Paperclip docs in a new tab.",icon:p2,href:opt,external:!0,onClick:r(()=>S(!1),"onClick")}),(0,t.jsx)(Ek,{variant:"menu-action",onAfterToggle:r(()=>S(!1),"onAfterToggle")}),(0,t.jsx)(q5e,{variant:"menu-action",onAfterAction:r(()=>S(!1),"onAfterAction")}),e==="authenticated"?(0,t.jsxs)("button",{type:"button",className:W("flex w-full items-start gap-3 rounded-xl px-3 py-3 text-left transition-colors hover:bg-destructive/10",_.isPending&&"cursor-not-allowed opacity-60"),onClick:O,disabled:_.isPending,children:[(0,t.jsx)("span",{className:"mt-0.5 rounded-lg border border-border bg-background/70 p-2 text-muted-foreground",children:(0,t.jsx)(rp,{className:"size-4"})}),(0,t.jsxs)("span",{className:"min-w-0 flex-1",children:[(0,t.jsx)("span",{className:"block text-sm font-medium text-foreground",children:_.isPending?"Signing out...":"Sign out"}),(0,t.jsx)("span",{className:"block text-xs text-muted-foreground",children:"End this browser session."})]})]}):null,(0,t.jsx)(U5e,{})]})]})]})]}),!k&&!i?(0,t.jsxs)(Fn,{children:[(0,t.jsx)(Bn,{asChild:!0,children:(0,t.jsx)("a",{href:lpt,target:"_blank",rel:"noreferrer","aria-label":"Share feedback",className:"flex size-8 shrink-0 items-center justify-center rounded-lg text-muted-foreground/50 transition-colors hover:bg-accent/50 hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring",children:(0,t.jsx)(ug,{className:"h-4 w-4","aria-hidden":"true"})})}),(0,t.jsx)(On,{side:"top",children:"Share feedback"})]}):null]})})}r(Kae,"SidebarAccountMenu");function dpt(e,s){return s3e(e,s)[0]?.toLowerCase()??null}r(dpt,"getCompanyRouteSegment");function s3e(e,s){if(!s)return[];const n=e.split("/").filter(Boolean);return n.length<2?[]:n[0]?.toUpperCase()!==s.toUpperCase()?[]:n.slice(1)}r(s3e,"getCompanyPathSegments");var upt=new Set(["browse","connections","connect","chat","review","attention","gateways","advanced","app"]);function mpt(e,s){const n=e.split("/").filter(Boolean);return n[0]?.toLowerCase()==="skills"?!0:s?n[0]?.toUpperCase()===s.toUpperCase()&&n[1]?.toLowerCase()==="skills":!1}r(mpt,"isSkillsStoreRoute");function hpt(){const{sidebarOpen:e,setSidebarOpen:s,toggleSidebar:n,collapsed:a,peeking:i,setPeeking:o,isMobile:l,setForceCollapsed:c}=Ua(),{openNewIssue:d,openOnboarding:u}=al(),{togglePanelVisible:h}=Ef(),p=jd()?.pushToast??null,{companies:f,loading:x,selectedCompany:g,selectedCompanyId:v,selectionSource:y,setSelectedCompanyId:k}=fs(),{companyPrefix:w,pluginRoutePath:N}=xa(),S=Gn(),C=la(),_=vL(),R=NNe(C.pathname,w).isTaskDetail,I=["/company/settings","/company/export","/company/import"].some(bt=>C.pathname.includes(bt)),T=s3e(C.pathname,w),E=T[0]?.toLowerCase()==="tools",P=T[0]?.toLowerCase()==="apps",O=P&&T[1]&&!upt.has(T[1].toLowerCase())?T[1]:null,M=P&&T[1]?.toLowerCase()==="app"&&T[2]?T[2]:null,Q=mpt(C.pathname,w),L=(0,m.useRef)(!1),F=(0,m.useRef)(null),q=(0,m.useRef)(null),z=(0,m.useRef)(new hke),K=(0,m.useRef)(C.key),U=G5e(l&&!R,C.pathname),[V,ne]=(0,m.useState)(!1),Z=(0,m.useMemo)(()=>{if(!w)return null;const bt=w.toUpperCase();return f.find(et=>et.issuePrefix.toUpperCase()===bt)??null},[f,w]),ie=!!w&&!x&&f.length>0&&!Z,J=(0,m.useMemo)(()=>N?.toLowerCase()??dpt(C.pathname,w),[w,C.pathname,N]),ae=Z?.id??null,oe=Z?.issuePrefix??null,{slots:G}=Bd({slotTypes:["page","routeSidebar"],companyId:ae,enabled:!!(ae&&J)}),X=(0,m.useMemo)(()=>$W(G,J),[J,G]),Y=(0,m.useMemo)(()=>({companyId:ae,companyPrefix:oe}),[ae,oe]),re=I?(0,t.jsx)(Z0t,{}):O?(0,t.jsx)(Bae,{kind:"connection",connectionId:O}):M?(0,t.jsx)(Bae,{kind:"application",applicationId:M}):P||E?(0,t.jsx)(J0t,{}):X?(0,t.jsx)(vm,{slot:X,context:Y,className:"h-full w-full",missingBehavior:"placeholder"}):null,se=re!=null,{data:ce}=te({queryKey:D.health,queryFn:r(()=>Lu.get(),"queryFn"),retry:!1,refetchInterval:r(bt=>bt.state.data?.devServer?.enabled?2e3:!1,"refetchInterval"),refetchIntervalInBackground:!1}),pe=se||Q;(0,m.useLayoutEffect)(()=>(c(pe),()=>c(!1)),[pe,c]),(0,m.useEffect)(()=>{x||L.current||ce?.deploymentMode!=="authenticated"&&(ce?.cloud||f.length===0&&(L.current=!0,u()))},[f,x,u,ce?.cloud,ce?.deploymentMode]),(0,m.useEffect)(()=>{if(!w||x||f.length===0)return;if(!Z){const et=(v?f.find(qe=>qe.id===v):null)??f[0]??null;et&&v!==et.id&&k(et.id,{source:"route_sync"});return}if(w!==Z.issuePrefix){const et=C.pathname.replace(/^\/[^/]+/,"");S(`/${Z.issuePrefix}${et}${C.search}`,{replace:!0});return}const bt=Y5e({matchedCompany:Z,selectedCompanyId:v,companies:f});if(bt){p?.({title:`${Z.name} is archived`,body:`Switched to ${bt.name}.`,tone:"info",dedupeKey:`archived-company-bounce:${Z.id}`}),k(bt.id,{source:"route_sync"}),S(`/${bt.issuePrefix}/dashboard`,{replace:!0});return}Z5e({selectionSource:y,selectedCompanyId:v,routeCompanyId:Z.id})&&k(Z.id,{source:"route_sync"})},[w,f,x,Z,C.pathname,C.search,S,p,y,v,k]);const fe=h,ve=(0,m.useCallback)(()=>{document.dispatchEvent(new KeyboardEvent("keydown",{key:"k",metaKey:!0,bubbles:!0,cancelable:!0}))},[]),Ie=(0,m.useRef)(null),de=(0,m.useRef)(!1),xe=(0,m.useRef)(!1),le=(0,m.useCallback)(()=>{Ie.current!==null&&(window.clearTimeout(Ie.current),Ie.current=null)},[]),Re=(0,m.useCallback)(()=>{le(),Ie.current=window.setTimeout(()=>o(!0),50)},[le,o]),Le=(0,m.useCallback)(()=>{le(),o(!0)},[le,o]),je=(0,m.useCallback)(()=>{le(),Ie.current=window.setTimeout(()=>o(!1),120)},[le,o]),_e=(0,m.useCallback)(()=>{de.current=!0,a&&!xe.current&&Re()},[a,Re]),Ze=(0,m.useCallback)(()=>{de.current=!1,xe.current=!1,je()},[je]),ue=(0,m.useCallback)(()=>{xe.current||Le()},[Le]),Fe=(0,m.useCallback)(()=>{de.current||je()},[je]);(0,m.useEffect)(()=>le,[le]);const mt=(0,m.useRef)(a);return(0,m.useEffect)(()=>{a!==mt.current&&(a?(le(),o(!1),xe.current=de.current):xe.current=!1,mt.current=a)},[a,le,o]),(0,m.useEffect)(()=>{if(!i)return;const bt=r(et=>{et.key==="Escape"&&(le(),o(!1))},"onKeyDown");return window.addEventListener("keydown",bt),()=>window.removeEventListener("keydown",bt)},[i,le,o]),V5e(),K5e({onNewIssue:r(()=>d(),"onNewIssue"),onSearch:ve,onToggleSidebar:n,onTogglePanel:fe,onShowShortcuts:r(()=>ne(!0),"onShowShortcuts"),onGoToInbox:r(()=>S("/inbox"),"onGoToInbox")}),(0,m.useEffect)(()=>{if(!l)return;const bt=30,et=50,qe=75;let it=0,_t=0;const $t=r(at=>{const Me=at.touches[0];it=Me.clientX,_t=Me.clientY},"onTouchStart"),Ot=r(at=>{const Me=at.changedTouches[0],De=Me.clientX-it;if(!(Math.abs(Me.clientY-_t)>qe)){if(!e&&it<bt&&De>et){s(!0);return}e&&De<-50&&s(!1)}},"onTouchEnd");return document.addEventListener("touchstart",$t,{passive:!0}),document.addEventListener("touchend",Ot,{passive:!0}),()=>{document.removeEventListener("touchstart",$t),document.removeEventListener("touchend",Ot)}},[l,e,s]),(0,m.useEffect)(()=>{const bt=document.body.style.overflow;return document.body.style.overflow=l?"visible":"clip",()=>{document.body.style.overflow=bt}},[l]),(0,m.useEffect)(()=>{if(!l)return X5e()},[l]),(0,m.useEffect)(()=>{if(typeof document>"u")return;const bt=q.current;return J5e(bt)},[C.pathname]),(0,m.useEffect)(()=>{const bt=q.current;if(!bt)return;const et=r(()=>{z.current.remember(K.current,bt.scrollTop)},"recordScroll");return bt.addEventListener("scroll",et,{passive:!0}),()=>bt.removeEventListener("scroll",et)},[]),(0,m.useLayoutEffect)(()=>{const bt=q.current,et=mke({previousPathname:F.current,pathname:C.pathname,navigationType:_,state:C.state});F.current=C.pathname;const qe=_==="POP",it=qe?z.current.recall(C.key):0;if(K.current=C.key,qe){FR(bt,it);const _t=requestAnimationFrame(()=>FR(bt,it));return()=>cancelAnimationFrame(_t)}et&&pke(bt)},[C.key,C.pathname,C.state,_]),(0,t.jsx)(dke,{children:(0,t.jsxs)("div",{className:W("bg-background text-foreground pt-(--sz-safe-top)",l?"min-h-dvh overflow-x-clip":"flex h-dvh flex-col overflow-clip"),children:[(0,t.jsx)("a",{href:"#main-content",className:"sr-only focus:not-sr-only focus:fixed focus:left-3 focus:top-3 focus:z-(--z-200) focus:rounded-md focus:bg-background focus:px-3 focus:py-2 focus:text-sm focus:font-medium focus:shadow-lg focus:outline-none focus-visible:ring-2 focus-visible:ring-ring",children:"Skip to Main Content"}),(0,t.jsx)(N5e,{}),(0,t.jsx)(S5e,{devServer:ce?.devServer}),(0,t.jsxs)("div",{className:W("min-h-0 flex-1",l?"w-full":"flex overflow-clip"),children:[l&&e&&(0,t.jsx)("button",{type:"button",className:"fixed inset-0 z-40 bg-black/50",onClick:r(()=>s(!1),"onClick"),"aria-label":"Close sidebar"}),l?(0,t.jsxs)("div",{className:W("fixed inset-y-0 left-0 z-50 flex flex-col overflow-hidden pt-(--sz-safe-top) transition-transform duration-100 ease-out",e?"translate-x-0":"-translate-x-full"),children:[(0,t.jsx)("div",{className:"flex flex-1 min-h-0 overflow-hidden",children:(0,t.jsx)("div",{className:"w-60 shrink-0 overflow-hidden",children:se?re:(0,t.jsx)(Oae,{})})}),(0,t.jsx)(Kae,{deploymentMode:ce?.deploymentMode})]}):(0,t.jsxs)(rpt,{open:e,collapsed:a,peeking:i,resizable:!0,onPanelMouseEnter:_e,onPanelMouseLeave:Ze,onPanelFocusCapture:a?ue:void 0,onPanelBlurCapture:a?Fe:void 0,children:[(0,t.jsx)("div",{className:"flex flex-1 min-h-0",children:(0,t.jsx)(Oae,{})}),(0,t.jsx)(Kae,{deploymentMode:ce?.deploymentMode})]}),!l&&se?(0,t.jsx)(apt,{children:re}):null,(0,t.jsxs)("div",{className:W("flex min-w-0 flex-col",l?"w-full":"h-full flex-1"),children:[(0,t.jsxs)("div",{className:W(l&&"sticky top-0 z-20 bg-background/95 backdrop-blur supports-[backdrop-filter]:bg-background/85"),children:[(0,t.jsx)(Wz,{mobile:l,onNavigateHome:r(()=>S("/dashboard"),"onNavigateHome")}),(0,t.jsx)(npt,{}),l&&I?(0,t.jsx)("div",{className:"border-b border-border px-4 pb-3",children:(0,t.jsx)(_Ne,{})}):null]}),(0,t.jsxs)("div",{className:W(l?"block":"flex flex-1 min-h-0"),children:[(0,t.jsx)("main",{id:"main-content",ref:q,tabIndex:-1,style:l?{"--tc-composer-bottom":"var(--sz-calc-14)"}:void 0,className:W("flex-1 p-4 outline-none md:p-6",l?"overflow-visible pb-(--sz-calc-14)":"overflow-auto [scrollbar-gutter:stable]"),children:ie?(0,t.jsx)(mm,{scope:"invalid_company_prefix",requestedPrefix:w??g?.issuePrefix}):(0,t.jsx)(A5e,{children:(0,t.jsx)(rv,{})})}),(0,t.jsx)(BNe,{})]})]})]}),l&&(0,t.jsx)(k5e,{visible:U}),(0,t.jsx)(FNe,{}),(0,t.jsx)(N2e,{}),(0,t.jsx)(m5e,{}),(0,t.jsx)(f5e,{}),(0,t.jsx)(v5e,{}),(0,t.jsx)(y5e,{open:V,onOpenChange:ne}),(0,t.jsx)(j5e,{}),(0,t.jsx)(w5e,{localTrusted:ce?.deploymentMode==="local_trusted"})]})})}r(hpt,"Layout");var Qae=null;function ppt(){return Qae??=new e2,Qae}r(ppt,"getDetachedClient");function fpt(){const e=(0,m.useContext)(c3),{data:s,isFetched:n}=te({queryKey:D.instance.experimentalSettings,queryFn:r(()=>jr.getExperimental(),"queryFn"),enabled:e!=null},e??ppt());return e?{enabled:s?.enableConferenceRoomChat===!0,loaded:n}:{enabled:!1,loaded:!0}}r(fpt,"useConferenceRoomChatEnabled");function xpt(){const{enabled:e,loaded:s}=fpt();return s?e?(0,t.jsx)(rv,{}):(0,t.jsx)(In,{to:"/dashboard",replace:!0}):null}r(xpt,"ConferenceRoomChatGate");var gpt=["session-start","human-message","agent-message","thinking","responding","responding-burst","tool-call","diff","working","running","completed","activity-phases","awaiting-approval","plan-todo","interrupted","refused","truncated","live-token-cost"],bpt={"session-start":{id:"session-start",label:"Session start",tier:"live",surface:"thread",protocol:'acpx.session → TranscriptEntry kind:"init"'},"human-message":{id:"human-message",label:"Human message",tier:"live",surface:"thread",protocol:'IssueComment authorType:"user"'},"agent-message":{id:"agent-message",label:"Final response",tier:"live",surface:"thread",protocol:'PRP item.delta kind:"agentMessage" channel:"final"'},thinking:{id:"thinking",label:"Thinking",tier:"live",surface:"thread",protocol:"text_delta stream:thought (ACP agent_thought_chunk)"},responding:{id:"responding",label:"Progress update (streaming)",tier:"live",surface:"thread",protocol:'PRP item.delta kind:"agentMessage" channel:"progress"'},"responding-burst":{id:"responding-burst",label:"Progress update burst",tier:"live",surface:"thread",protocol:"text_delta stream:output ×N, tool calls between (PAP-368 dwell)"},"tool-call":{id:"tool-call",label:"Tool call",tier:"live",surface:"thread",protocol:"acpx.tool_call (ACP tool_call / tool_call_update)"},diff:{id:"diff",label:"Diff",tier:"live",surface:"thread",protocol:'ToolCallContent type:"diff" → TranscriptEntry kind:"diff"'},working:{id:"working",label:"Working",tier:"live",surface:"thread",protocol:"heartbeat.run.progress + acpx.status"},running:{id:"running",label:"Running",tier:"live",surface:"thread",protocol:'message.status.type === "running"'},completed:{id:"completed",label:"Completed (collapsed)",tier:"live",surface:"thread",protocol:"acpx.result (StopReason in subtype)"},"activity-phases":{id:"activity-phases",label:"Long-run activity phases",tier:"live",surface:"thread",protocol:"assistant boundaries + chronological tool calls"},"awaiting-approval":{id:"awaiting-approval",label:"Awaiting approval",tier:"tier-b",surface:"thread",protocol:"ACP RequestPermissionRequest + PermissionOptionKind"},"plan-todo":{id:"plan-todo",label:"Plan / todo",tier:"tier-b",surface:"plan",protocol:"ACP Plan { entries: PlanEntry[] }, PlanEntryStatus"},interrupted:{id:"interrupted",label:"Interrupted",tier:"tier-b",surface:"thread",protocol:'AcpRuntimeTurnResult.status:"cancelled" / StopReason "cancelled"'},refused:{id:"refused",label:"Refused",tier:"tier-b",surface:"thread",protocol:'StopReason "refusal"'},truncated:{id:"truncated",label:"Truncated",tier:"tier-b",surface:"thread",protocol:'StopReason "max_tokens" | "max_turn_requests"'},"live-token-cost":{id:"live-token-cost",label:"Live token / cost",tier:"tier-b",surface:"thread",protocol:"ACP UsageUpdate { used, size, cost }"}},Sbs=gpt.map(e=>bpt[e]);function n3e({browser:e,label:s="Browser",onOpen:n}){const a=e.status==="closed"||e.status==="failed";return(0,t.jsxs)("div",{className:"flex flex-wrap items-center gap-2 py-1 text-sm","aria-label":`${s} session`,children:[(0,t.jsx)(wm,{className:"size-4 shrink-0 text-muted-foreground","aria-hidden":!0}),(0,t.jsx)("span",{children:s}),(0,t.jsxs)("span",{className:"text-muted-foreground",children:["· ",e.status]}),n&&(0,t.jsx)($,{variant:"ghost",size:"sm",onClick:r(()=>n(e.id),"onClick"),children:a?"View session":"Open browser"})]})}r(n3e,"TaskBrowserActivity");function r3e({item:e}){return(0,t.jsx)("article",{className:"rounded-lg border border-border bg-card p-3","aria-label":`Project created: ${e.name}`,children:(0,t.jsxs)("div",{className:"flex items-start gap-3",children:[(0,t.jsx)(gKe,{className:"mt-0.5 size-4 shrink-0 text-muted-foreground","aria-hidden":!0}),(0,t.jsxs)("div",{className:"min-w-0 flex-1 space-y-1",children:[(0,t.jsx)("p",{className:"text-xs text-muted-foreground",children:"Project created"}),(0,t.jsx)(We,{to:`/projects/${e.projectId}`,className:"break-words text-sm font-medium hover:underline focus-visible:underline",children:e.name}),e.description&&(0,t.jsx)("p",{className:"line-clamp-3 text-sm text-muted-foreground",children:e.description}),e.repositories.length>0&&(0,t.jsx)("ul",{className:"space-y-1 pt-1",children:e.repositories.map(s=>(0,t.jsxs)("li",{className:"flex min-w-0 items-center gap-2 text-xs text-muted-foreground",children:[(0,t.jsx)(Xi,{className:"size-3 shrink-0","aria-hidden":!0}),(0,t.jsx)("a",{className:"truncate hover:underline focus-visible:underline",href:s.url,target:"_blank",rel:"noreferrer",children:s.name})]},s.id))})]})]})})}r(r3e,"TaskChatProjectCreatedCard");function vpt({item:e,onOpen:s}){return(0,t.jsx)("article",{className:"rounded-lg border border-border bg-card p-3","aria-label":`Skill created: ${e.name}`,children:(0,t.jsxs)("button",{type:"button",className:"flex w-full items-start gap-3 text-left",onClick:r(()=>s?.(e.skillId,e.name),"onClick"),children:[(0,t.jsx)(pf,{className:"mt-0.5 size-4 shrink-0 text-muted-foreground","aria-hidden":!0}),(0,t.jsxs)("span",{className:"min-w-0 flex-1 space-y-1",children:[(0,t.jsx)("span",{className:"block text-xs text-muted-foreground",children:"Skill created"}),(0,t.jsx)("span",{className:"block break-words text-sm font-medium hover:underline focus-visible:underline",children:e.name}),e.description?(0,t.jsx)("span",{className:"block line-clamp-3 text-sm text-muted-foreground",children:e.description}):null]})]})})}r(vpt,"TaskChatSkillCreatedCard");function ypt(e){return(0,t.jsxs)("svg",{viewBox:"0 0 180 180",fill:"none",stroke:"currentColor",strokeWidth:14,strokeLinecap:"round",xmlns:"http://www.w3.org/2000/svg",...e,children:[(0,t.jsx)("path",{d:"M18 84.8528L85.8822 16.9706C95.2548 7.59798 110.451 7.59798 119.823 16.9706C129.196 26.3431 129.196 41.5391 119.823 50.9117L68.5581 102.177"}),(0,t.jsx)("path",{d:"M69.2652 101.47L119.823 50.9117C129.196 41.5391 144.392 41.5391 153.765 50.9117L154.118 51.2652C163.491 60.6378 163.491 75.8338 154.118 85.2063L92.7248 146.6C89.6006 149.724 89.6006 154.789 92.7248 157.913L105.331 170.52"}),(0,t.jsx)("path",{d:"M102.853 33.9411L52.6482 84.1457C43.2756 93.5183 43.2756 108.714 52.6482 118.087C62.0208 127.459 77.2167 127.459 86.5893 118.087L136.794 67.8822"})]})}r(ypt,"McpIcon");var jpt=new Set(["tool","tool call","tool_call","acp_tool"]);function Su(e){const s=(e??"").trim().toLowerCase().replace(/\s*\((?:pending|in[_ -]?progress|completed|failed|cancelled|canceled)\)$/,"");return!s||jpt.has(s)}r(Su,"isGenericToolName");function MV(e){const s=e.match(/^mcp__(.+?)__(.+)$/i);if(s)return{namespace:s[1],name:s[2]};const n=e.match(/^mcp\.([^.]+)\.(.+)$/i);return n?{namespace:n[1],name:n[2]}:null}r(MV,"mcpToolIdentity");function PV(e){return e.replace(/([a-z0-9])([A-Z])/g,"$1 $2").replace(/([A-Z]+)([A-Z][a-z])/g,"$1 $2").replace(/[^A-Za-z0-9]+/g," ").trim().toLowerCase().split(/\s+/).filter(Boolean)}r(PV,"identifierWords");function a3e(e){if(e.length===0)return"";const s=e.map(n=>["api","id","lsp","mcp","pr","url"].includes(n)?n.toUpperCase():n).join(" ");return s.charAt(0).toUpperCase()+s.slice(1)}r(a3e,"sentenceCase");function Lk(e){const s=(e??"").trim();return Su(s)?"Unnamed tool":a3e(PV(MV(s)?.name??s))}r(Lk,"humanizeToolName");var Vd=r((e,s,n)=>({key:e,singular:s,plural:n}),"group"),wpt={bash:{action:"run"},terminal:{action:"run"},shell:{action:"run"},command:{action:"run"},run:{action:"run"},execute:{action:"run"},exec_command:{action:"run"},apply_patch:{action:"update",running:"Applying a patch",completed:"Applied a patch"},read:{action:"read",running:"Reading a file",completed:"Read a file"},write:{action:"update",running:"Writing a file",completed:"Wrote a file"},edit:{action:"update",running:"Editing a file",completed:"Edited a file"},notebook_read:{action:"read",running:"Reading a notebook",completed:"Read a notebook"},notebook_edit:{action:"update",running:"Editing a notebook",completed:"Edited a notebook"},glob:{action:"search",running:"Searching files",completed:"Searched files"},grep:{action:"search",running:"Searching file contents",completed:"Searched file contents",family:"grep"},tool_search:{action:"search",running:"Searching available tools",completed:"Searched available tools",group:Vd("tool_search","tool search","tool searches")},web_search:{action:"search",running:"Searching the web",completed:"Searched the web",family:"web"},web_fetch:{action:"fetch",running:"Fetching a web page",completed:"Fetched a web page",family:"web"},todo_write:{action:"update",running:"Updating the task list",completed:"Updated the task list",family:"plan",group:Vd("task_operation","task operation","task operations")},task_create:{action:"create",running:"Creating a task",completed:"Created a task",family:"plan",group:Vd("task_operation","task operation","task operations")},task_update:{action:"update",running:"Updating a task",completed:"Updated a task",family:"plan",group:Vd("task_operation","task operation","task operations")},task_list:{action:"list",running:"Listing tasks",completed:"Listed tasks",family:"plan",group:Vd("task_operation","task operation","task operations")},task_get:{action:"read",running:"Reading a task",completed:"Read a task",family:"plan",group:Vd("task_operation","task operation","task operations")},enter_plan_mode:{action:"switch",running:"Entering plan mode",completed:"Entered plan mode",family:"plan"},exit_plan_mode:{action:"switch",running:"Leaving plan mode",completed:"Left plan mode",family:"plan"},skill:{action:"read",running:"Loading a skill",completed:"Loaded a skill"},ask_user_question:{action:"request",running:"Requesting input",completed:"Requested input",family:"question"},request_human_input:{action:"request",running:"Requesting input",completed:"Requested input",family:"question",group:Vd("task_operation","task operation","task operations")},agent:{action:"start",running:"Starting a subagent",completed:"Started a subagent",family:"agent"},task:{action:"start",running:"Starting a subagent",completed:"Started a subagent",family:"agent"},task_output:{action:"read",running:"Checking subagent progress",completed:"Checked subagent progress",family:"agent"},task_stop:{action:"stop",running:"Stopping a subagent",completed:"Stopped a subagent",family:"agent"},send_message:{action:"post",running:"Messaging a subagent",completed:"Messaged a subagent",family:"agent"},spawn_agent:{action:"start",running:"Starting a subagent",completed:"Started a subagent",family:"agent"},wait_agent:{action:"wait",running:"Checking subagent progress",completed:"Checked subagent progress",family:"agent"},wait_threads:{action:"wait",running:"Checking task progress",completed:"Checked task progress",family:"agent"},interrupt_agent:{action:"stop",running:"Interrupting a subagent",completed:"Interrupted a subagent",family:"agent"},report_findings:{action:"post",running:"Reporting findings",completed:"Reported findings",family:"safety"},guardian_review:{action:"think",running:"Reviewing safety",completed:"Reviewed safety",family:"safety"},lsp:{action:"read",running:"Inspecting code intelligence",completed:"Inspected code intelligence"},compact_conversation:{action:"think",running:"Compacting context",completed:"Compacted context"},image_generation:{action:"create",running:"Generating an image",completed:"Generated an image",family:"image"},view_image:{action:"read",running:"Viewing an image",completed:"Viewed an image",family:"image"},multi_tool_use_parallel:{action:"run",running:"Running tools in parallel",completed:"Ran tools in parallel"},get_task_context:{action:"read",running:"Reading task context",completed:"Read task context"},get_task_history:{action:"read",running:"Reading task history",completed:"Read task history"},list_documents:{action:"list",running:"Listing documents",completed:"Listed documents"},read_document:{action:"read",running:"Reading a document",completed:"Read a document"},list_document_revisions:{action:"list",running:"Listing document revisions",completed:"Listed document revisions"},report_progress:{action:"post",running:"Reporting progress",completed:"Reported progress"},answer_status_question:{action:"post",running:"Answering a status question",completed:"Answered a status question"},write_document:{action:"update",running:"Writing a document",completed:"Wrote a document"},register_deliverable:{action:"create",running:"Registering a deliverable",completed:"Registered a deliverable"},finish_task:{action:"finish",running:"Reporting completion",completed:"Reported completion"},paperclip_finish:{action:"finish",running:"Reporting completion",completed:"Reported completion"},block_task:{action:"block",running:"Reporting a blocker",completed:"Reported a blocker"},paperclip_block:{action:"block",running:"Reporting a blocker",completed:"Reported a blocker"},request_review:{action:"request",running:"Requesting review",completed:"Requested review"},list_agents:{action:"list",running:"Listing agents",completed:"Listed agents"},get_agent:{action:"read",running:"Reading agent details",completed:"Read agent details"},search_tasks:{action:"search",running:"Searching tasks",completed:"Searched tasks"},list_approvals:{action:"list",running:"Listing approvals",completed:"Listed approvals"},get_approval:{action:"read",running:"Reading an approval",completed:"Read an approval"},get_approval_context:{action:"read",running:"Reading approval context",completed:"Read approval context"},get_workspace_runtime:{action:"read",running:"Reading workspace status",completed:"Read workspace status"},control_workspace_service:{action:"run",running:"Controlling a workspace service",completed:"Controlled a workspace service"},set_dependencies:{action:"update",running:"Updating task dependencies",completed:"Updated task dependencies"},set_task_title:{action:"update",running:"Naming the task",completed:"Named the task"},create_task:{action:"create",running:"Creating a task",completed:"Created a task"},request_approval:{action:"request",running:"Requesting approval",completed:"Requested approval"},decide_approval:{action:"update",running:"Deciding an approval",completed:"Decided an approval"},comment_on_approval:{action:"post",running:"Commenting on an approval",completed:"Commented on an approval"},schedule_wake:{action:"create",running:"Scheduling a wake-up",completed:"Scheduled a wake-up",family:"wait"},generic_api_request:{action:"request",running:"Calling the Paperclip API",completed:"Called the Paperclip API"}},kpt={read:["get","read","inspect","view"],list:["list","glob"],search:["find","search","grep","query","lookup"],fetch:["fetch","browse"],open:["open"],update:["write","edit","update","set","patch","upsert","sync"],create:["create","add","register","upload"],delete:["delete","remove"],move:["move","rename"],run:["run","execute","bash","shell","command"],request:["request","ask","prompt"],post:["send","message","comment","report","answer"],start:["start","spawn","delegate"],stop:["stop","cancel","interrupt"],wait:["wait","sleep","poll"],finish:["finish","complete"],block:["block"],think:["think","reason","compact","review"],switch:["switch","enter","exit"],other:[]},Npt={read:"read",edit:"update",delete:"delete",move:"move",search:"search",list:"list",execute:"run",think:"think",fetch:"fetch",switch_mode:"switch"};function Spt(e){return PV(e).join("_")}r(Spt,"normalizedKey");function Cpt(e){const s=e[0];if(!s)return null;for(const[n,a]of Object.entries(kpt))if(a.includes(s))return n;return null}r(Cpt,"inferredAction");function _pt(e){return e==="run"?"terminal":e==="read"||e==="list"?"read":e==="search"?"search":e==="fetch"||e==="open"?"web":["update","create","delete","move"].includes(e)?"edit":e==="request"?"question":e==="start"||e==="stop"?"agent":e==="wait"?"wait":"other"}r(_pt,"actionFamily");var Apt={terminal:ff,grep:$Ke,search:Yr,read:p2,edit:RL,web:rKe,plan:Hj,question:Ic,agent:Ub,safety:Bi,image:R3,wait:Au,mcp:ypt,other:pf};function Ipt(e,s){const n=s?` ${s}`:"";switch(e){case"read":return{running:`Reading${n||" data"}`,completed:`Read${n||" data"}`};case"list":return{running:`Listing${n||" items"}`,completed:`Listed${n||" items"}`};case"search":return{running:`Searching${n||""}`,completed:`Searched${n||""}`};case"fetch":return{running:`Fetching${n||" data"}`,completed:`Fetched${n||" data"}`};case"open":return{running:`Opening${n||" an item"}`,completed:`Opened${n||" an item"}`};case"update":return{running:`Updating${n||" data"}`,completed:`Updated${n||" data"}`};case"create":return{running:`Creating${n||" an item"}`,completed:`Created${n||" an item"}`};case"delete":return{running:`Deleting${n||" an item"}`,completed:`Deleted${n||" an item"}`};case"move":return{running:`Moving${n||" an item"}`,completed:`Moved${n||" an item"}`};case"run":return{running:"Running a command",completed:"Ran a command"};case"request":return{running:`Requesting${n||" input"}`,completed:`Requested${n||" input"}`};case"post":return{running:`Posting${n||" an update"}`,completed:`Posted${n||" an update"}`};case"start":return{running:`Starting${n||" an operation"}`,completed:`Started${n||" an operation"}`};case"stop":return{running:`Stopping${n||" an operation"}`,completed:`Stopped${n||" an operation"}`};case"wait":return{running:"Waiting",completed:"Finished waiting"};case"finish":return{running:"Reporting completion",completed:"Reported completion"};case"block":return{running:"Reporting a blocker",completed:"Reported a blocker"};case"think":return{running:"Thinking",completed:"Finished thinking"};case"switch":return{running:`Switching${n||" mode"}`,completed:`Switched${n||" mode"}`};case"other":return{running:"Running",completed:"Ran"}}}r(Ipt,"actionCopy");function Tpt(e){switch(e){case"run":return Vd("command","command","commands");case"read":case"list":return Vd("read","read","reads");case"search":return Vd("search","search","searches");case"update":case"create":case"delete":case"move":return Vd("file_change","file change","file changes");case"start":case"stop":return Vd("delegation","delegation","delegations");case"wait":return Vd("wait","wait","waits");default:return Vd("tool_action","tool action","tool actions")}}r(Tpt,"defaultSummaryGroup");function Rpt(e){return e==="read"||e==="list"?Vd("paperclip_read","Paperclip read","Paperclip reads"):Vd("task_operation","task operation","task operations")}r(Rpt,"paperclipSummaryGroup");function Nj(e){const s=(e.name??"").trim(),n=MV(s),a=(e.namespace??n?.namespace??"").trim(),i=(n?"mcp":e.transport??"builtin").toLowerCase(),o=(n?.name??s).trim(),l=PV(o),c=Spt(o),d=wpt[c],u=Npt[(e.operation??"").trim().toLowerCase()],h=Cpt(l),p=d?.action??u??h??"other",f=d?"exact":u?"kind":h?"inferred":Su(o)?"unnamed":"fallback",x=Su(o)?"Unnamed tool":Lk(o),g=/^[A-Za-z][A-Za-z0-9_.:-]*$/.test(o),v=h&&g&&l.length>1?l.slice(1):[],y=v.length?a3e(v).replace(/^./,_=>_.toLowerCase()):void 0,k=d?.running&&d.completed?{running:d.running,completed:d.completed}:p==="other"?Su(o)?{running:"Running an unnamed tool",completed:"Ran an unnamed tool"}:{running:`Running ${x}`,completed:`Ran ${x}`}:Ipt(p,d?void 0:y),w=d?.family??_pt(p),N=i==="mcp"?"mcp":w,S=a?Lk(a):i==="mcp"?"MCP":void 0,C=a.toLowerCase()==="paperclip"?Rpt(p):d?.group??Tpt(p);return{icon:Apt[N],family:N,runningLabel:k.running,completedLabel:k.completed,failedLabel:`${k.completed} · failed`,interruptedLabel:`${k.running} · stopped`,displayName:x,sourceLabel:S,technicalName:s||void 0,confidence:f,summaryGroup:C}}r(Nj,"toolActivityPresentation");function AN(e){const s=Nj({name:e});return{family:s.family,icon:s.icon,verbLabel:s.runningLabel}}r(AN,"toolTaxonomy");function i3e(e){const s=(e??"").trim().toLowerCase();return s==="thinking"?Lx:s==="responding"||s.startsWith("responding (")?CKe:null}r(i3e,"statusLabelIcon");var vD=["Clipping","Organizing","Sorting","Synthesizing","Analyzing","Filing","Collating","Stapling","Indexing","Annotating","Drafting","Proofreading","Alphabetizing","Photocopying","Laminating","Hole-punching","Bookmarking","Highlighting","Typing","Trimming","Aligning","Combining","Whiteboarding","Diagramming","Sketching","Labeling","Sticky-noting"],yD=["Brewing","Tinkering","Distilling","Deliberating"],Wae=(()=>{const e=[],s=Math.max(vD.length,yD.length);for(let n=0;n<s;n++)n<vD.length&&e.push(vD[n]),n<yD.length&&e.push(yD[n]);return e})(),Ept=1e4;function Lpt(e){const s=(e??"").trim().toLowerCase();return s==="running"||s==="working"}r(Lpt,"isGenericStatusLabel");function Mpt(e){let s=2166136261;for(let n=0;n<e.length;n++)s^=e.charCodeAt(n),s=Math.imul(s,16777619);return s>>>0}r(Mpt,"fnv1a");function Ppt(e,s=0){const n=Math.floor(Math.max(0,s)/Ept);return Wae[(Mpt(e)+n)%Wae.length]}r(Ppt,"whimsyWord");var Dpt=[{name:"--motion-ease-out-expo",group:"Easing",kind:"easing"},{name:"--motion-ease-standard",group:"Easing",kind:"easing"},{name:"--motion-ease-out",group:"Easing",kind:"easing"},{name:"--motion-ease-scroll-pill-in",group:"Easing",kind:"easing"},{name:"--motion-ease-scroll-pill-out",group:"Easing",kind:"easing"},{name:"--motion-ease-in",group:"Easing",kind:"easing"},{name:"--motion-duration-instant",group:"Durations",kind:"time",min:0,max:1e3,step:10},{name:"--motion-duration-fast",group:"Durations",kind:"time",min:0,max:1e3,step:10},{name:"--motion-duration-base",group:"Durations",kind:"time",min:0,max:1e3,step:10},{name:"--motion-duration-slow",group:"Durations",kind:"time",min:0,max:1500,step:10},{name:"--motion-duration-deliberate",group:"Durations",kind:"time",min:0,max:2e3,step:10},{name:"--motion-duration-enter",group:"Durations",kind:"time",min:0,max:1e3,step:10},{name:"--motion-duration-exit",group:"Durations",kind:"time",min:0,max:1e3,step:10},{name:"--motion-duration-swap",group:"Durations",kind:"time",min:0,max:1e3,step:10},{name:"--motion-marker-enter",group:"States",kind:"time",min:0,max:1500,step:10},{name:"--motion-bubble-enter",group:"States",kind:"time",min:0,max:1500,step:10},{name:"--motion-cot-line-stagger",group:"States",kind:"time",min:0,max:300,step:5},{name:"--motion-cot-collapse",group:"States",kind:"time",min:0,max:1500,step:10},{name:"--motion-tool-enter",group:"States",kind:"time",min:0,max:1500,step:10},{name:"--motion-diff-reveal",group:"States",kind:"time",min:0,max:1500,step:10},{name:"--motion-status-enter",group:"States",kind:"time",min:0,max:1500,step:10},{name:"--motion-status-exit",group:"States",kind:"time",min:0,max:1500,step:10},{name:"--motion-approval-pulse",group:"States",kind:"time",min:0,max:3e3,step:20},{name:"--motion-plan-entry-stagger",group:"States",kind:"time",min:0,max:300,step:5},{name:"--motion-plan-check",group:"States",kind:"time",min:0,max:1500,step:10},{name:"--motion-question-page-enter",group:"States",kind:"time",min:0,max:1e3,step:10},{name:"--motion-count-tween",group:"States",kind:"time",min:0,max:1500,step:10},{name:"--motion-streaming-cursor-blink",group:"States",kind:"time",min:0,max:3e3,step:20},{name:"--motion-turn-fold",group:"States",kind:"time",min:0,max:1500,step:10},{name:"--motion-turn-meta",group:"States",kind:"time",min:0,max:1500,step:10},{name:"--motion-line-scroll",group:"States",kind:"time",min:0,max:1500,step:10},{name:"--motion-interstitial-dwell",group:"States",kind:"time",min:0,max:1e4,step:100},{name:"--motion-scroll-pill-enter",group:"States",kind:"time",min:0,max:1500,step:10},{name:"--motion-scroll-pill-exit",group:"States",kind:"time",min:0,max:1500,step:10},{name:"--motion-mobile-nav-enter",group:"States",kind:"time",min:0,max:1500,step:10},{name:"--motion-mobile-nav-exit",group:"States",kind:"time",min:0,max:1500,step:10},{name:"--motion-scrollbar-idle-delay",group:"States",kind:"time",min:0,max:2e3,step:10},{name:"--motion-pane-glide",group:"States",kind:"time",min:0,max:1500,step:10},{name:"--motion-side-panel-tab",group:"States",kind:"time",min:0,max:1500,step:10},{name:"--motion-live-now-sweep",group:"States",kind:"time",min:0,max:5e3,step:100},{name:"--motion-live-now-breathe",group:"States",kind:"time",min:0,max:5e3,step:100}],Cbs=Array.from(new Set(Dpt.map(e=>e.group)));function o3e(e){const s=e.trim();if(s.endsWith("ms"))return parseFloat(s);if(s.endsWith("s"))return parseFloat(s)*1e3;const n=parseFloat(s);return Number.isFinite(n)?n:0}r(o3e,"parseCssTimeMs");function $pt(e){if(e==null)return null;const s=Math.round(e/1e3);return s<60?`${s}s`:`${Math.floor(s/60)}m ${s%60}s`}r($pt,"elapsedLabel");function Opt(e){if(e==null)return null;const s=Math.max(0,e)/1e3;return s<60?`${s.toFixed(1)}s`:`${Math.floor(s/60)}m ${(s%60).toFixed(1)}s`}r(Opt,"liveElapsedLabel");function Bpt(e,s){const[n,a]=(0,m.useState)(()=>Date.now());return(0,m.useEffect)(()=>{if(e==null||!s)return;const i=window.setInterval(()=>a(Date.now()),100);return()=>window.clearInterval(i)},[e,s]),e==null?void 0:Math.max(0,n-e)}r(Bpt,"useLiveElapsedMs");function Fpt(e,s){return!Number.isFinite(e)||!Number.isFinite(s)||s<=0?0:Math.max(0,Math.round(e/s)-1)}r(Fpt,"lineScrollOffset");function g6(e){const s=getComputedStyle(document.documentElement).getPropertyValue(e),n=o3e(s);return Number.isFinite(n)?n:0}r(g6,"motionTokenMs");function zpt({text:e,streaming:s,leaving:n}){const a=(0,m.useRef)(null),[i,o]=(0,m.useState)(0),[l,c]=(0,m.useState)(!1),[d,u]=(0,m.useState)(!1);(0,m.useLayoutEffect)(()=>{const p=a.current;if(!p)return;const f=r(()=>{const g=parseFloat(window.getComputedStyle(p).lineHeight);o(Fpt(p.scrollHeight,g))},"measure");if(f(),typeof ResizeObserver>"u")return;const x=new ResizeObserver(f);return x.observe(p),()=>x.disconnect()},[e,s]),(0,m.useEffect)(()=>{const p=requestAnimationFrame(()=>c(!0)),f=window.setTimeout(()=>u(!0),g6("--motion-line-scroll"));return()=>{cancelAnimationFrame(p),window.clearTimeout(f)}},[]);const h=l?n?-1:s?-i:0:1;return(0,t.jsx)("span",{className:"tc-line-scroll min-w-0 flex-1","data-testid":"task-chat-live-self-talk","data-streaming":s||void 0,"data-leaving":n||void 0,children:(0,t.jsx)("span",{ref:a,className:W("tc-line-scroll-inner block",!s&&"truncate"),style:{transform:h!==0?`translateY(calc(${h} * 1lh))`:void 0,transition:d&&!n?"none":void 0},children:e})})}r(zpt,"LiveSelfTalkLine");function qpt(e,s){const[n,a]=(0,m.useState)(null),i=(0,m.useRef)(n),o=(0,m.useRef)(null),l=(0,m.useRef)(e),c=(0,m.useRef)(0),d=(0,m.useRef)(null),u=(0,m.useRef)(null),h=(0,m.useRef)(null);return l.current=e,(0,m.useEffect)(()=>{const p=r(y=>{y.current!=null&&(window.clearTimeout(y.current),y.current=null)},"clear"),f=r(y=>{i.current=y,a(y)},"show"),x=r(()=>{p(u),p(h),u.current=window.setTimeout(()=>{if(u.current=null,o.current!=null)return;const y=i.current;y==null||y.streaming||(f({...y,leaving:!0}),h.current=window.setTimeout(()=>{h.current=null,i.current?.leaving&&f(null)},g6("--motion-line-scroll")))},g6("--motion-interstitial-dwell"))},"scheduleLeave"),g=r((y,k)=>{p(u),p(h),c.current=Date.now(),f({text:y,streaming:k,swapKey:(i.current?.swapKey??0)+1}),k||x()},"swapIn");if(!s){p(d),p(u),p(h),o.current=null,i.current&&f(null);return}const v=i.current;if(e==null){v?.streaming&&(f({...v,streaming:!1}),x());return}if(v==null){g(e,!0);return}if(v.streaming){v.text!==e&&f({...v,text:e});return}if(o.current=e,d.current==null){const y=g6("--motion-interstitial-dwell"),k=Math.max(0,c.current+y-Date.now());d.current=window.setTimeout(()=>{d.current=null;const w=o.current;o.current=null,w!=null&&g(w,l.current!=null)},k)}},[e,s]),(0,m.useEffect)(()=>()=>{d.current!=null&&window.clearTimeout(d.current),u.current!=null&&window.clearTimeout(u.current),h.current!=null&&window.clearTimeout(h.current)},[]),n}r(qpt,"useHeldSelfTalk");var Upt={running:{Icon:st,spin:!0,tone:"text-(--status-agent-running)"},working:{Icon:st,spin:!0,tone:"text-(--status-agent-running)"},awaiting_approval:{Icon:x2,spin:!1,tone:"text-primary"},interrupted:{Icon:gW,spin:!1,tone:"text-destructive"},refused:{Icon:Hm,spin:!1,tone:"text-destructive"},truncated:{Icon:DKe,spin:!1,tone:"text-(--status-agent-paused)"}};function l3e({item:e,onApprovalDecision:s,chevronOpen:n,onToggle:a}){const{Icon:i,spin:o,tone:l}=Upt[e.status],c=e.status==="awaiting_approval",d=e.status==="running"||e.status==="working",u=Bpt(e.startedAtMs,d),h=qpt(d?e.selfTalk:void 0,d),p=$pt(e.elapsedMs);if(d){const f=Opt(u??e.elapsedMs),x=e.selfTalk!=null,g=e.toolName?AN(e.toolName).icon:x?null:i3e(e.label),v=x||Lpt(e.label)?Ppt(e.id,u??e.elapsedMs??0):e.label,y=(0,t.jsxs)("div",{className:"tc-enter-status flex items-center gap-2 py-0.5 text-xs text-muted-foreground",children:[n!==void 0?(0,t.jsx)("span",{className:"flex h-3.5 w-3.5 shrink-0 items-center justify-center","data-testid":"task-chat-status-caret-slot",children:(0,t.jsx)(Ln,{className:W("h-3 w-3 transition-transform",n?"rotate-90":null),"aria-hidden":!0})}):null,(0,t.jsx)("span",{className:"flex h-3.5 w-3.5 shrink-0 items-center justify-center","data-testid":"task-chat-status-dot-slot",children:(0,t.jsx)("span",{"aria-hidden":!0,className:"h-2 w-2 animate-pulse rounded-full bg-(--status-agent-running)"})}),g?(0,t.jsx)(g,{className:"h-3.5 w-3.5 shrink-0","aria-hidden":!0}):null,(0,t.jsxs)("span",{className:"flex min-w-0 flex-1 items-baseline gap-2",children:[(0,t.jsxs)("span",{className:"shimmer-text shimmer-text-muted shrink-0 font-medium",children:[v,"…"]}),f?(0,t.jsx)("span",{className:"shrink-0 font-mono tabular-nums text-(length:--text-micro)",children:f}):null,e.detail?(0,t.jsx)("span",{className:"min-w-0 truncate font-mono text-(length:--text-micro)",children:e.detail}):null,e.tokens?(0,t.jsxs)("span",{className:"ml-auto shrink-0 font-mono text-(length:--text-micro)",children:[e.tokens.used.toLocaleString(),"/",e.tokens.size.toLocaleString()," ctx"]}):null]})]});return(0,t.jsxs)("div",{className:"flex flex-col",children:[(0,t.jsxs)("div",{className:"flex items-center gap-2 py-0.5 text-xs text-muted-foreground","data-testid":"task-chat-interstitial-row",children:[(0,t.jsx)("span",{"aria-hidden":!0,className:"h-3.5 w-3.5 shrink-0"}),h?(0,t.jsx)(zpt,{text:h.text,streaming:h.streaming,leaving:h.leaving},h.swapKey):(0,t.jsx)("span",{"aria-hidden":!0,className:"tc-line-scroll min-w-0 flex-1"})]}),a?(0,t.jsx)("button",{type:"button",onClick:a,"aria-expanded":n,className:"-mx-1.5 block w-full rounded-sm px-1.5 text-left transition-colors hover:bg-muted/60","data-testid":"task-chat-live-turn",children:y}):y]})}return(0,t.jsxs)("div",{className:W("tc-enter-status flex flex-col gap-2 rounded-lg border px-3 py-2 text-sm",c?"tc-approval border-primary/40 bg-primary/5":"border-border bg-muted/40"),children:[(0,t.jsxs)("div",{className:"flex min-w-0 items-center gap-2",children:[(0,t.jsx)(i,{className:W("h-4 w-4 shrink-0",l,o&&"animate-spin")}),(0,t.jsx)("span",{className:"min-w-0 truncate font-medium",children:e.label}),(0,t.jsxs)("span",{className:"ml-auto flex shrink-0 items-center gap-2 text-xs text-muted-foreground",children:[p?(0,t.jsx)("span",{children:p}):null,e.tokens?(0,t.jsxs)("span",{children:[e.tokens.used.toLocaleString(),"/",e.tokens.size.toLocaleString()," ctx"]}):null]})]}),e.detail?(0,t.jsx)("p",{className:"text-xs text-muted-foreground",children:e.detail}):null,c&&e.approval?(0,t.jsx)("div",{className:"flex flex-wrap justify-end gap-2 pt-1",children:e.approval.options.map(f=>{const x=f.kind.startsWith("reject");return(0,t.jsx)("button",{type:"button",onClick:r(()=>s?.(f.id),"onClick"),className:W("rounded-md border px-2.5 py-1 text-xs font-medium transition-colors",x?"border-border text-muted-foreground hover:bg-accent/50 hover:text-foreground":"border-primary bg-primary text-primary-foreground hover:bg-primary/90"),children:f.label},f.id)})}):null]})}r(l3e,"TaskChatStatusPill");var gg=(0,m.createContext)(null);function nw(e){if(!Number.isFinite(e)||e<0)return"0 B";if(e<1024)return`${Math.round(e)} B`;const s=["KB","MB","GB","TB"];let n=e/1024,a=0;for(;n>=1024&&a<s.length-1;)n/=1024,a+=1;const i=n.toFixed(1);return`${i.endsWith(".0")?i.slice(0,-2):i} ${s[a]}`}r(nw,"formatBytes$4");var PE=new Set(["application/octet-stream","binary/octet-stream","application/x-binary"]),Kpt=[".mp4",".m4v",".webm",".mov",".qt",".quicktime"],Qpt=[".png",".jpg",".jpeg",".gif",".webp",".avif",".bmp",".ico"],Wpt=new Set(["application/wasm"]),Hpt=new Set(["application/zip","application/x-zip","application/x-zip-compressed"]),c3e=new Set(["text/markdown","text/x-markdown","application/markdown","application/x-markdown"]),Vpt=new Set(["application/csv","application/ecmascript","application/graphql","application/html","application/javascript","application/json","application/ld+json","application/sql","application/toml","application/x-httpd-php","application/x-javascript","application/x-python","application/x-sh","application/x-yaml","application/xhtml+xml","application/xml","application/yaml"]),Gpt=[".csv",".css",".graphql",".htm",".html",".js",".json",".jsx",".log",".markdown",".md",".mdx",".php",".py",".sh",".sql",".toml",".ts",".tsx",".txt",".xml",".yaml",".yml"];function J3(e){return(e??"").toLowerCase().split(";")[0]?.trim()??""}r(J3,"normalizeOutputContentType");function Ypt(e){const s=(e??"").trim().toLowerCase();return s?Gpt.some(n=>s.endsWith(n)):!1}r(Ypt,"hasDocumentLikeFilename");function d3e(e){return Hpt.has(e)||e.endsWith("+zip")}r(d3e,"isZipContentType");function Zpt(e){return e?!!(e.startsWith("text/")||c3e.has(e)||Vpt.has(e)||e.startsWith("application/")&&(e.endsWith("+json")||e.endsWith("+xml"))):!1}r(Zpt,"isDocumentLikeOutputContentType");function Jpt(e,s){const n=J3(e);return!n||Zpt(n)||PE.has(n)&&Ypt(s)?!1:n.startsWith("video/")||n.startsWith("image/")||n==="application/pdf"||Wpt.has(n)||d3e(n)||PE.has(n)}r(Jpt,"isOutputEligibleContentType");function Xpt(e){const s=J3(e);if(s.startsWith("video/")){const n=s.slice(6);return n==="quicktime"?{label:"MOV",tone:"video"}:{label:(n||"vid").toUpperCase().slice(0,4),tone:"video"}}return s==="application/pdf"?{label:"PDF",tone:"pdf"}:d3e(s)?{label:"ZIP",tone:"zip"}:s.startsWith("image/")?{label:"IMG",tone:"image"}:c3e.has(s)?{label:"MD",tone:"bin"}:s==="text/plain"?{label:"TXT",tone:"bin"}:s==="text/csv"||s==="application/csv"?{label:"CSV",tone:"bin"}:s==="text/html"||s==="application/html"||s==="application/xhtml+xml"?{label:"HTML",tone:"bin"}:s==="application/json"||s.endsWith("+json")?{label:"JSON",tone:"bin"}:s==="application/xml"||s==="text/xml"||s.endsWith("+xml")?{label:"XML",tone:"bin"}:s==="application/wasm"?{label:"WASM",tone:"bin"}:{label:"BIN",tone:"bin"}}r(Xpt,"getOutputFileGlyph");function ym(e,s){const n=J3(e);if(n.startsWith("video/"))return!0;if(!PE.has(n))return!1;const a=(s??"").trim().toLowerCase();return Kpt.some(i=>a.endsWith(i))}r(ym,"isVideoLikeOutput");function Sj(e){const s=J3(e);return s.startsWith("image/")&&s!=="image/svg+xml"}r(Sj,"isImageContentType");function _M(e,s){const n=J3(e);if(Sj(n))return!0;if(n&&!PE.has(n))return!1;const a=(s??"").trim().toLowerCase();return Qpt.some(i=>a.endsWith(i))}r(_M,"isImageLikeOutput");function Hae(e){const s=new Date(e).getTime();return Number.isNaN(s)?0:s}r(Hae,"toTime");function AM(e){const s=(e??[]).filter(n=>n.type==="artifact"&&n.provider==="paperclip").flatMap(n=>{const a=LOe.safeParse(n.metadata);return a.success&&!Jpt(a.data.contentType,a.data.originalFilename)?[]:[{id:n.id,title:n.title,status:typeof n.status=="string"?n.status:"active",isPrimary:!!n.isPrimary,createdAt:n.createdAt,metadata:a.success?a.data:null,degraded:!a.success,workProduct:n}]});return s.sort((n,a)=>n.isPrimary!==a.isPrimary?n.isPrimary?-1:1:Hae(a.createdAt)-Hae(n.createdAt)),{items:s,primary:s[0]??null,rest:s.slice(1),count:s.length}}r(AM,"getIssueOutputs");function DV(e){return e.metadata?.originalFilename||e.title||"output"}r(DV,"outputFilename");function u3e(e){return new Set(AM(e).items.flatMap(s=>{const n=s.metadata?.attachmentId;return n?[n]:[]}))}r(u3e,"getPromotedOutputAttachmentIds");function X3(e,s){const n=e?.toLowerCase().split(";")[0].trim();return n==="text/html"||n==="application/xhtml+xml"||/\.html?$/i.test(s??"")}r(X3,"isHtmlPreview");var eft=["default-src 'none'","script-src 'unsafe-inline'","style-src 'unsafe-inline'","img-src data:","font-src data:","media-src data:","connect-src 'none'","frame-src 'none'","object-src 'none'","base-uri 'none'","form-action 'none'"].join("; ");function tft(e){return`<!doctype html><html><head><meta charset="utf-8"><meta http-equiv="Content-Security-Policy" content="${eft}"><meta name="referrer" content="no-referrer"></head><body>${e}</body></html>`}r(tft,"htmlPreviewDocument");function sft(e){return e.contentType.toLowerCase().split(";")[0]?.trim()??""}r(sft,"normalizedContentType");function sg(e){return e.originalFilename??e.id}r(sg,"attachmentFilename");function IM(e){return e.openPath??e.contentPath}r(IM,"attachmentOpenPath");function I2(e){return e.downloadPath??`${e.contentPath}?download=1`}r(I2,"attachmentDownloadPath");function m3e(e){const s=sft(e);return _M(s,e.originalFilename)&&!/^image\/hei[cf](?:-sequence)?$/.test(s)}r(m3e,"isImageAttachment$1");function h3e(e){return ym(e.contentType,e.originalFilename)}r(h3e,"isVideoAttachment");function p3e(e){return obe(e)}r(p3e,"isMarkdownAttachment");function rw(e){const s=e.contentType.toLowerCase().split(";")[0].trim();return obe(e)||X3(s,e.originalFilename)||s.startsWith("text/")||/^(application\/(json|xml|javascript|x-yaml|yaml)|application\/[\w.-]+\+json)$/.test(s)||["","application/octet-stream"].includes(s)&&/\.(txt|log|csv|json|yaml|yml|toml|ini|sh|ts|tsx|js|jsx|py|css|html)$/i.test(e.originalFilename??"")}r(rw,"isTextAttachment");function f3e(e,s){const n=URL.createObjectURL(s),a=document.createElement("a");a.href=n,a.download=e,a.rel="noreferrer",a.style.display="none",document.body.appendChild(a),a.click(),document.body.removeChild(a),URL.revokeObjectURL(n)}r(f3e,"downloadBlob$1");function nft(e,s,n){f3e(e,new Blob([s],{type:`${n};charset=utf-8`}))}r(nft,"downloadTextFile");var jD="flex h-7 w-7 items-center justify-center rounded-md text-muted-foreground transition-colors hover:bg-accent hover:text-foreground disabled:opacity-50";function x3e({issueId:e,documentKey:s,title:n,format:a,body:i,className:o}){const[l,c]=(0,m.useState)(null),[d,u]=(0,m.useState)(null),[h,p]=(0,m.useState)(null),{copy:f,copied:x,failed:g}=ep(),v=(0,m.useRef)(void 0);(0,m.useEffect)(()=>()=>clearTimeout(v.current),[]);const y=(0,m.useCallback)(async(_,R)=>{c(_),p(null);try{await R(),u(_)}catch(I){u(null),p(I instanceof Error?I.message:"Export failed")}finally{c(null)}clearTimeout(v.current),v.current=setTimeout(()=>{u(null),p(null)},2e3)},[]),k=(0,m.useCallback)(async()=>i??(await yt.getDocument(e,s)).body,[i,s,e]),w=(0,m.useCallback)(()=>{c("copy"),p(null),(async()=>{try{await f(await k())==="failed"&&p("Copy failed")}catch(_){p(_ instanceof Error?_.message:"Copy failed")}finally{c(null)}})()},[f,k]),N=g||h==="Copy failed"?"Copy failed":x?"Copied!":"Copy full content",S=d==="download"?"Downloaded!":"Download source",C=d==="pdf"?"Downloaded!":"Export to PDF";return(0,t.jsxs)("div",{className:W("flex items-center gap-0.5",o),"data-testid":"document-export-actions",children:[(0,t.jsx)("button",{type:"button",className:jD,disabled:l!==null,"aria-label":"Copy full content",title:N,"data-testid":"document-export-copy",onClick:r(_=>{_.preventDefault(),_.stopPropagation(),w()},"onClick"),children:x?(0,t.jsx)(ms,{"aria-hidden":"true",className:"h-3.5 w-3.5"}):(0,t.jsx)(br,{"aria-hidden":"true",className:"h-3.5 w-3.5"})}),(0,t.jsx)("button",{type:"button",className:jD,disabled:l!==null,"aria-label":"Download source",title:S,"data-testid":"document-export-download",onClick:r(_=>{_.preventDefault(),_.stopPropagation(),y("download",async()=>{const R=pqe(a);nft(ite(n,R),await k(),R==="md"?"text/markdown":"text/plain")})},"onClick"),children:(0,t.jsx)(Fi,{"aria-hidden":"true",className:"h-3.5 w-3.5"})}),(0,t.jsx)("button",{type:"button",className:jD,disabled:l!==null,"aria-label":"Export to PDF",title:C,"data-testid":"document-export-pdf",onClick:r(_=>{_.preventDefault(),_.stopPropagation(),y("pdf",async()=>{f3e(ite(n,"pdf"),await yt.getDocumentPdf(e,s))})},"onClick"),children:(0,t.jsx)(fKe,{"aria-hidden":"true",className:"h-3.5 w-3.5"})}),(0,t.jsx)("span",{className:"sr-only",role:"status","aria-live":"polite",children:h??(x?"Copied!":g?"Copy failed":d?"Downloaded!":"")})]})}r(x3e,"DocumentExportActions");function k5({children:e,className:s}){return(0,t.jsx)("div",{className:W("relative aspect-video w-full overflow-hidden bg-accent/20",s),children:e})}r(k5,"PreviewFrame");function DE({label:e}){return(0,t.jsx)(k5,{className:"flex items-center justify-center",children:(0,t.jsxs)("div",{className:"flex flex-col items-center gap-1.5 text-muted-foreground/50",children:[(0,t.jsx)(kl,{className:"h-7 w-7","aria-hidden":"true"}),e?(0,t.jsx)("span",{className:"text-(length:--text-micro) font-medium uppercase tracking-wide",children:e}):null]})})}r(DE,"PlaceholderPreview");function rft({artifact:e}){const[s,n]=(0,m.useState)(!1);return s||!e.contentPath?(0,t.jsx)(DE,{label:"Image"}):(0,t.jsx)(k5,{children:(0,t.jsx)("img",{src:e.contentPath,alt:e.title,loading:"lazy",className:"h-full w-full object-cover",onError:r(()=>n(!0),"onError")})})}r(rft,"ImagePreview");function aft({artifact:e}){const[s,n]=(0,m.useState)(!1),[a,i]=(0,m.useState)(!1),o=(0,m.useRef)(!1),l=(0,m.useRef)(null);if((0,m.useEffect)(()=>()=>{l.current!==null&&window.clearTimeout(l.current)},[]),s||!e.contentPath)return(0,t.jsx)(k5,{className:"flex items-center justify-center bg-black/80",children:(0,t.jsx)("div",{className:"flex h-11 w-11 items-center justify-center rounded-full bg-white/15",children:(0,t.jsx)(ho,{className:"h-5 w-5 translate-x-0.5 text-white","aria-hidden":"true"})})});const c=r(()=>{l.current!==null&&(window.clearTimeout(l.current),l.current=null),i(!0)},"markFrameReady"),d=r(()=>{l.current!==null&&window.clearTimeout(l.current),l.current=window.setTimeout(c,3e3)},"scheduleFrameReadyFallback"),u=r(p=>{if(o.current)return;o.current=!0;const f=p.currentTarget,x=Number.isFinite(f.duration)&&f.duration>0?f.duration:0,g=x>0?Math.min(1,x/4):.05;try{Math.abs(f.currentTime-g)>.001?(f.currentTime=g,d()):c()}catch{c()}},"loadThumbnailFrame"),h=r(p=>{(o.current||p.currentTarget.currentTime>0)&&c()},"handleLoadedData");return(0,t.jsxs)(k5,{className:"bg-black",children:[(0,t.jsx)("video",{src:e.contentPath,preload:"metadata",muted:!0,playsInline:!0,"data-frame-ready":a?"true":"false",className:W("h-full w-full object-contain transition-opacity",a?"opacity-100":"opacity-0"),onLoadedMetadata:u,onLoadedData:h,onSeeked:c,onError:r(()=>n(!0),"onError")}),(0,t.jsx)("div",{className:"pointer-events-none absolute inset-0 flex items-center justify-center",children:(0,t.jsx)("div",{className:"flex h-11 w-11 items-center justify-center rounded-full bg-black/55",children:(0,t.jsx)(ho,{className:"h-5 w-5 translate-x-0.5 text-white","aria-hidden":"true"})})})]})}r(aft,"VideoPreview");function ift({artifact:e}){const s=e.previewText?.trim();return s?(0,t.jsxs)(k5,{className:"bg-card",children:[(0,t.jsx)("div",{className:"absolute inset-0 overflow-hidden p-3",children:(0,t.jsx)("p",{className:"max-h-full overflow-hidden whitespace-pre-wrap break-words text-base leading-6 text-muted-foreground/75",children:s})}),(0,t.jsx)("div",{className:"pointer-events-none absolute bottom-0 left-0 right-0 h-10 bg-gradient-to-t from-card to-transparent"})]}):(0,t.jsx)(DE,{label:e.source==="document"?"Document":"Text"})}r(ift,"TextPreview");function eA({artifact:e}){switch(e.mediaKind){case"image":return(0,t.jsx)(rft,{artifact:e},e.contentPath);case"video":return(0,t.jsx)(aft,{artifact:e},e.contentPath);case"text":case"document":return(0,t.jsx)(ift,{artifact:e});case"file":return(0,t.jsx)(DE,{label:"File"});default:return(0,t.jsx)(DE,{})}}r(eA,"ArtifactPreview");function Vae({href:e,download:s,title:n,children:a}){return(0,t.jsx)("a",{href:e,...s?{download:""}:{target:"_blank",rel:"noreferrer"},title:n,"aria-label":n,onClick:r(i=>i.stopPropagation(),"onClick"),className:"flex h-7 w-7 items-center justify-center rounded-md text-muted-foreground transition-colors hover:bg-accent hover:text-foreground",children:a})}r(Vae,"SecondaryAction");function oft({artifact:e}){return(0,t.jsxs)(We,{to:e.href,disableIssueQuicklook:!0,"data-testid":"artifact-card","data-media-kind":e.mediaKind,className:"group flex flex-col overflow-hidden rounded-lg border border-border bg-card cursor-pointer transition-colors hover:border-foreground/20 hover:shadow-md focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring",children:[(0,t.jsx)(eA,{artifact:e}),(0,t.jsxs)("div",{className:"flex flex-1 flex-col gap-1 p-3",children:[(0,t.jsxs)("div",{className:"flex h-7 items-start justify-between gap-2",children:[(0,t.jsx)("h3",{className:"min-w-0 flex-1 truncate text-sm font-medium leading-7 text-foreground/85",title:e.title,children:e.title}),(0,t.jsxs)("div",{className:"flex shrink-0 items-center gap-0.5 opacity-0 transition-opacity group-hover:opacity-100 focus-within:opacity-100",children:[e.source==="document"&&e.documentKey?(0,t.jsx)(x3e,{issueId:e.issue.id,documentKey:e.documentKey,title:e.title}):null,e.openPath?(0,t.jsx)(Vae,{href:e.openPath,title:"Open file in new tab",children:(0,t.jsx)($n,{className:"h-3.5 w-3.5"})}):null,e.downloadPath?(0,t.jsx)(Vae,{href:e.downloadPath,download:!0,title:"Download file",children:(0,t.jsx)(Fi,{className:"h-3.5 w-3.5"})}):null]})]}),(0,t.jsxs)("div",{className:"mt-0.5 flex items-center gap-1.5 text-(length:--text-micro) text-muted-foreground/65",children:[(0,t.jsxs)("span",{children:["Last edited ",Zd(e.updatedAt)]}),e.createdByAgent?(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)("span",{className:"text-muted-foreground/50",children:"·"}),(0,t.jsx)("span",{className:"truncate",children:e.createdByAgent.name})]}):null]})]})]})}r(oft,"ArtifactCard");function lft(e){return e&&/^\/api\/assets\/[^/?#]+\/content$/.test(e)?e:null}r(lft,"paperclipHumanAvatarUrl");function g3e(e){const{authorName:s,authorUserId:n,currentUserId:a,userProfileMap:i}=e,o=n?i?.get(n):null,l=!!(n&&a&&n===a);return{isCurrentUser:l,authorName:o?.label?.trim()||s?.trim()||(n==="local-board"?"Board":l?"You":"User"),avatarUrl:o?.image??null}}r(g3e,"resolveIssueChatHumanAuthor");var sc={credentials:r(e=>ke.get(`/companies/${e}/email/connections`),"credentials"),checkAddress:r((e,s,n,a)=>ke.post(`/companies/${e}/email/connections/${s}/check-address`,n,{signal:a}),"checkAddress"),connect:r((e,s)=>ke.post(`/companies/${e}/email/connections`,s),"connect"),inspectSaved:r((e,s)=>ke.post(`/companies/${e}/email/connections/${s}/inspect`,{}),"inspectSaved"),list:r(e=>ke.get(`/companies/${e}/email/inboxes`),"list"),setup:r((e,s)=>ke.post(`/companies/${e}/email/inboxes`,s),"setup"),inspect:r((e,s)=>ke.post(`/companies/${e}/email/inspect`,{apiKey:s}),"inspect"),control:r((e,s)=>ke.post(`/email/inboxes/${e}/control`,{action:s}),"control"),reconnect:r((e,s,n)=>ke.post(`/email/inboxes/${e}/reconnect`,{apiKey:s,receiveMode:n}),"reconnect"),resolve:r((e,s,n,a)=>ke.post(`/companies/${e}/email/deliveries/${s}/resolve`,{outcome:n,providerMessageId:a}),"resolve"),thread:r((e,s)=>ke.get(`/companies/${e}/email/tasks/${s}`),"thread"),send:r((e,s)=>ke.post(`/companies/${e}/email/send`,s),"send")};function b3e(e,s){return te({queryKey:["email-thread",e,s],queryFn:r(()=>sc.thread(e,s),"queryFn"),enabled:!!(e&&s)&&!s.startsWith("chat:"),refetchInterval:r(n=>n.state.data===null?!1:3e3,"refetchInterval")})}r(b3e,"useEmailThread");var v3e=(0,m.createContext)(null);function cft({companyId:e,issueId:s,children:n}){const a=b3e(e,s);return(0,t.jsx)(v3e.Provider,{value:a.data??null,children:n})}r(cft,"EmailThreadProvider");function y3e(e){const s=(0,m.useContext)(v3e),n=s?.messages.find(a=>a.commentId===e);return n&&s?(0,t.jsx)(j3e,{message:n,publication:s.publications.find(a=>a.providerMessageId===n.providerMessageId),issueId:s.issueId}):null}r(y3e,"useEmailComment");function j3e({message:e,publication:s,issueId:n,contextNotice:a=!1}){const i=te({queryKey:["email-attachments",n],queryFn:r(()=>yt.listAttachments(n),"queryFn"),enabled:e.attachmentIds.length>0});return(0,t.jsxs)("article",{"aria-label":e.direction==="inbound"?"Email received":"Email sent",className:a?"task-context-notice space-y-3":"space-y-4 rounded-xl border border-border bg-card p-5",children:[(0,t.jsxs)("div",{className:"flex flex-wrap items-center justify-between gap-2",children:[(0,t.jsxs)("span",{className:"flex items-center gap-2 text-sm font-semibold",children:[(0,t.jsx)($Q,{className:"size-4"}),e.direction==="inbound"?"Email received":"Email sent"]}),(0,t.jsx)("span",{className:"text-xs text-muted-foreground",children:new Date(e.timestamp).toLocaleString()})]}),(0,t.jsxs)("div",{className:"space-y-1",children:[(0,t.jsxs)("p",{className:"text-sm font-medium",children:[e.from,e.direction==="inbound"&&(0,t.jsx)("span",{className:"ml-2 rounded-md bg-muted px-2 py-1 text-xs text-muted-foreground",children:"External"})]}),(0,t.jsxs)("p",{className:"break-words text-xs text-muted-foreground",children:["To: ",e.to.join(", ")]}),!!e.cc?.length&&(0,t.jsxs)("p",{className:"break-words text-xs text-muted-foreground",children:["Cc: ",e.cc.join(", ")]}),(0,t.jsx)("p",{className:"text-sm font-semibold",children:e.subject})]}),(0,t.jsx)("div",{className:"whitespace-pre-wrap break-words text-sm",children:e.text||"(No text body)"}),!!e.attachmentIds.length&&(0,t.jsx)("div",{className:"flex flex-wrap gap-2",children:e.attachmentIds.map(o=>{const l=i.data?.find(c=>c.id===o);return(0,t.jsxs)("a",{href:`/api/attachments/${o}/content`,target:"_blank",rel:"noreferrer",className:"flex items-center gap-2 rounded-md border border-border px-3 py-2 text-xs",children:[(0,t.jsx)(kl,{className:"size-3.5"}),l?.originalFilename??"Open attachment"]},o)})}),(0,t.jsxs)("details",{className:"text-xs text-muted-foreground",children:[(0,t.jsx)("summary",{className:"cursor-pointer",children:"Email details"}),(0,t.jsxs)("div",{className:"space-y-2 pt-3",children:[!!e.bcc?.length&&(0,t.jsxs)("p",{children:["Bcc: ",e.bcc.join(", ")]}),(0,t.jsxs)("p",{className:"break-all",children:["Message ID: ",e.providerMessageId]}),e.fullText!==e.text&&(0,t.jsx)("div",{className:"whitespace-pre-wrap break-words",children:e.fullText})]})]}),s&&(0,t.jsxs)("p",{className:"border-t border-border pt-3 text-xs text-muted-foreground",children:[s.outcome==="delivered"?"Delivered":s.outcome==="failed"?"Delivery failed":s.outcome==="uncertain"?"Delivery uncertain":s.outcome==="queued"?"Queued":"Sent",s.error?` · ${s.error}`:""]}),i.error&&(0,t.jsx)("p",{role:"alert",className:"text-xs text-destructive",children:"Attachments could not be loaded."})]})}r(j3e,"EmailMessageCard");var Jy=(0,m.createContext)(null);function aw({items:e,initialIndex:s,open:n,onOpenChange:a}){const[i,o]=(0,m.useState)(s),l=(0,m.useRef)(null),c=(0,m.useCallback)(g=>{l.current=g},[]);(0,m.useEffect)(()=>{n&&o(s)},[n,s]);const d=(0,m.useCallback)(()=>{o(g=>(g+1)%e.length)},[e.length]),u=(0,m.useCallback)(()=>{o(g=>(g-1+e.length)%e.length)},[e.length]);(0,m.useEffect)(()=>{i<e.length||o(0)},[i,e.length]),(0,m.useEffect)(()=>{if(!n)return;const g=r(v=>{v.key==="ArrowRight"?d():v.key==="ArrowLeft"?u():v.key==="Escape"&&a(!1)},"handler");return window.addEventListener("keydown",g),()=>window.removeEventListener("keydown",g)},[n,d,u,a]);const h=(0,m.useCallback)(g=>{const v=g.target;v.closest("button")||v.closest("a")||v===l.current||a(!1)},[a]);if(e.length===0)return null;const p=e[i];if(!p)return null;const f=sg(p),x=ym(p.contentType,p.originalFilename);return(0,t.jsx)(fze,{open:n,onOpenChange:a,children:(0,t.jsxs)(hze,{children:[(0,t.jsx)(mze,{className:"fixed inset-0 z-50 bg-black/90 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 duration-200"}),(0,t.jsxs)(pze,{className:"fixed inset-0 z-50 flex flex-col outline-none data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 duration-200",onClick:h,children:[(0,t.jsxs)("div",{className:"flex items-center justify-between px-5 py-3 text-white/80 text-sm shrink-0",children:[(0,t.jsx)("span",{className:"truncate max-w-(--pct-50) font-medium",title:f,children:f}),(0,t.jsxs)("div",{className:"flex items-center gap-4",children:[(0,t.jsxs)("span",{className:"text-white/40 tabular-nums text-xs",children:[i+1," / ",e.length]}),(0,t.jsx)("a",{href:I2(p),download:f,className:"text-white/50 hover:text-white transition-colors",title:"Download","aria-label":`Download ${f}`,onClick:r(g=>g.stopPropagation(),"onClick"),children:(0,t.jsx)(Fi,{className:"h-4.5 w-4.5"})}),(0,t.jsx)("button",{type:"button",onClick:r(()=>a(!1),"onClick"),className:"text-white/50 hover:text-white transition-colors",title:"Close",children:(0,t.jsx)(Mn,{className:"h-5 w-5"})})]})]}),(0,t.jsxs)("div",{className:"flex-1 flex items-center min-h-0",children:[(0,t.jsx)("div",{className:"w-16 md:w-24 shrink-0 flex items-center justify-center h-full",children:e.length>1&&(0,t.jsx)("button",{type:"button",onClick:u,className:"rounded-full bg-white/10 p-3 text-white/60 hover:text-white hover:bg-white/20 transition-colors",title:"Previous",children:(0,t.jsx)(xm,{className:"h-7 w-7"})})}),(0,t.jsx)("div",{className:"flex-1 flex items-center justify-center min-w-0 min-h-0 h-full px-2",children:x?(0,t.jsx)("video",{ref:c,src:p.contentPath,className:"max-w-full max-h-full rounded-lg",controls:!0,playsInline:!0}):(0,t.jsx)("img",{ref:c,src:p.contentPath,alt:f,className:"max-w-full max-h-full object-contain select-none rounded-lg",draggable:!1})}),(0,t.jsx)("div",{className:"w-16 md:w-24 shrink-0 flex items-center justify-center h-full",children:e.length>1&&(0,t.jsx)("button",{type:"button",onClick:d,className:"rounded-full bg-white/10 p-3 text-white/60 hover:text-white hover:bg-white/20 transition-colors",title:"Next",children:(0,t.jsx)(Ln,{className:"h-7 w-7"})})})]}),(0,t.jsx)("div",{className:"h-6 shrink-0"})]})]})})}r(aw,"ImageGalleryModal");function $v(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:{}}r($v,"record$6");var w3e=(0,m.createContext)(null);function k3e(e){const s=(0,m.useContext)(w3e);return s&&e?.sourceRunId===s.runId&&e.sections.some(n=>n.rows.some(a=>a.type==="key_value"&&a.value===s.actionId))?s:null}r(k3e,"useWorkspaceBaseRefRecovery");function dft({issue:e,agentMap:s,unavailableReason:n,onRepaired:a,children:i}){const o=e.activeRecoveryAction,l=o?.cause==="configuration_incomplete"&&typeof o.evidence.latestRunId=="string"?o.evidence.latestRunId:null,{data:c}=te({queryKey:["workspace-base-ref-recovery",e.companyId,e.id,l],queryFn:r(()=>ea.get(l),"queryFn"),enabled:!!l,staleTime:1/0,retry:!1}),d=$v($v(c?.resultJson).configurationIncomplete);let u=null;if(o&&l&&c?.companyId===e.companyId&&$v(c.contextSnapshot).issueId===e.id&&d.reason==="workspace_base_ref_unresolved"&&typeof d.requestedRef=="string"){const h=e.assigneeAgentId?s.get(e.assigneeAgentId):void 0,p=d.requestedRef,f=e.project?.workspaces?.find(y=>y.id===e.projectWorkspaceId)??e.project?.primaryWorkspace;let x="The task’s repository";if(f?.repoUrl)try{const y=new URL(f.repoUrl);(y.protocol==="https:"||y.protocol==="http:")&&(x=`${y.hostname}${y.pathname.replace(/\.git$/,"")}`)}catch{}const g=$v($v(e.executionWorkspaceSettings).workspaceStrategy).baseRef,v=o.status!=="active"||e.status!=="blocked"||e.assigneeAgentId!==o.returnOwnerAgentId||c.agentId!==e.assigneeAgentId||typeof g=="string"&&g.trim()&&g!==p?"This repair no longer matches the task. Refresh to review its current state.":n??(e.executionRunId||e.checkoutRunId?"Wait for the current run to finish.":null)??(h?.status==="paused"||h?.status==="terminated"?"The assigned agent is unavailable.":null)??(e.executionState?.status==="pending"?"Complete the pending review or approval before retrying.":null)??(e.blockedBy?.some(y=>y.status!=="done"&&y.status!=="cancelled")?"Resolve the task’s blockers before retrying.":null);u={actionId:o.id,runId:l,props:{requestedRef:p,repository:x,taskOverride:g===p,defaultBranch:typeof d.defaultBranch=="string"?d.defaultBranch:null,agentName:h?.name??"The assigned agent",unavailableReason:v,failureKind:typeof d.fetchError=="string"&&d.fetchError.includes(`couldn't find remote ref refs/heads/${p}`)?"missing_branch":"unresolved_ref",onRepair:r(async y=>{try{const k=await yt.resolveRecoveryAction(e.id,{actionId:o.id,outcome:"restored",sourceIssueStatus:"todo",workspaceBaseRef:{requestedRef:p,branch:y}});if(k.issue.status!=="todo"||k.issue.assigneeAgentId!==e.assigneeAgentId||$v($v(k.issue.executionWorkspaceSettings).workspaceStrategy).baseRef!==y)throw new Error("The task changed while saving. Refresh to check its current state.")}finally{a()}},"onRepair")}}}return(0,t.jsx)(w3e.Provider,{value:u,children:i})}r(dft,"WorkspaceBaseRefRecoveryProvider");var N3e={neutral:{container:"border-border bg-muted/35 dark:bg-muted/20",iconWrap:"bg-muted text-foreground/70",icon:s0,iconClass:"text-muted-foreground",label:"text-muted-foreground",divider:"border-border/70"},info:{container:"border-sky-300/70 bg-sky-50/70 dark:border-sky-500/30 dark:bg-sky-500/10",iconWrap:"bg-sky-100 text-sky-700 dark:bg-sky-500/20 dark:text-sky-200",icon:s0,iconClass:"text-sky-700 dark:text-sky-300",label:"text-sky-800 dark:text-sky-200",divider:"border-sky-300/50 dark:border-sky-500/30"},success:{container:"border-emerald-300/70 bg-emerald-50/70 dark:border-emerald-500/30 dark:bg-emerald-500/10",iconWrap:"bg-emerald-100 text-emerald-700 dark:bg-emerald-500/20 dark:text-emerald-200",icon:fa,iconClass:"text-emerald-700 dark:text-emerald-300",label:"text-emerald-800 dark:text-emerald-200",divider:"border-emerald-300/50 dark:border-emerald-500/30"},warning:{container:"border-amber-300/70 bg-amber-50/80 dark:border-amber-500/30 dark:bg-amber-500/10",iconWrap:"bg-amber-100 text-amber-800 dark:bg-amber-500/20 dark:text-amber-200",icon:Es,iconClass:"text-amber-700 dark:text-amber-300",label:"text-amber-900 dark:text-amber-200",divider:"border-amber-300/60 dark:border-amber-500/30"},danger:{container:"border-red-400/60 bg-red-50/80 dark:border-red-500/35 dark:bg-red-500/10",iconWrap:"bg-red-100 text-red-700 dark:bg-red-500/20 dark:text-red-200",icon:oN,iconClass:"text-red-700 dark:text-red-300",label:"text-red-900 dark:text-red-200",divider:"border-red-400/50 dark:border-red-500/30"}};function uft(e){try{return new Date(e).toLocaleString(void 0,{month:"short",day:"numeric",hour:"numeric",minute:"2-digit"})}catch{return e}}r(uft,"formatTimestamp$1");function mft({row:e,tone:s}){return(0,t.jsxs)("div",{className:"grid grid-cols-(--gtc-8) gap-x-3 gap-y-0.5 px-3 py-1.5 text-xs",children:[(0,t.jsx)("div",{className:"truncate text-(length:--text-micro) font-medium uppercase tracking-(--tracking-label) text-muted-foreground",children:e.label}),(0,t.jsx)("div",{className:"min-w-0 break-words text-foreground/90",children:(()=>{switch(e.kind){case"text":return(0,t.jsx)("span",{children:e.value});case"code":return(0,t.jsx)("code",{className:"rounded bg-muted px-1.5 py-0.5 font-mono text-(length:--text-micro) text-foreground/80",children:e.value});case"issue":{const n=(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)("span",{children:e.identifier}),e.title?(0,t.jsxs)("span",{className:"text-muted-foreground",children:["— ",e.title]}):null]});return e.href?(0,t.jsx)("a",{href:e.href,className:W("inline-flex items-center gap-1 rounded-sm font-medium underline-offset-2 hover:underline",s.label),children:n}):(0,t.jsx)("span",{className:W("inline-flex items-center gap-1 font-medium",s.label),children:n})}case"agent":return e.href?(0,t.jsx)("a",{href:e.href,className:W("inline-flex items-center gap-1 rounded-sm font-medium underline-offset-2 hover:underline",s.label),children:e.name}):(0,t.jsx)("span",{className:W("font-medium",s.label),children:e.name});case"run":{const n=e.runId.length>12?`${e.runId.slice(0,8)}…`:e.runId,a=(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)("code",{className:"rounded bg-muted px-1.5 py-0.5 text-foreground/80",children:n}),e.status?(0,t.jsx)("span",{className:W("font-sans",s.label),children:e.status}):null]});return e.href?(0,t.jsx)("a",{href:e.href,className:"inline-flex items-center gap-2 rounded-sm font-mono text-(length:--text-micro) underline-offset-2 hover:underline",children:a}):(0,t.jsx)("span",{className:"inline-flex items-center gap-2 font-mono text-(length:--text-micro)",children:a})}}})()})]})}r(mft,"MetadataRow$1");function $V({sections:e,tone:s="neutral"}){const n=N3e[s];return(0,t.jsx)("div",{className:"divide-y divide-border/50 px-1 py-1",children:e.map((a,i)=>(0,t.jsxs)("div",{className:"py-1.5 first:pt-2 last:pb-2",children:[a.title?(0,t.jsx)("div",{className:"px-3 pb-1 pt-0.5 text-(length:--text-nano) font-semibold uppercase tracking-(--tracking-caps) text-muted-foreground",children:a.title}):null,(0,t.jsx)("div",{children:a.rows.map((o,l)=>(0,t.jsx)(mft,{row:o,tone:n},l))})]},i))})}r($V,"SystemNoticeMetadataSections");function OV({tone:e="neutral",label:s,body:n,source:a,metadata:i,detailsDefaultOpen:o=!1,timestamp:l,className:c}){const d=N3e[e],u=d.icon,[h,p]=(0,m.useState)(o),f=(0,m.useId)(),x=!!(i&&i.length>0),g=s??{neutral:"System notice",info:"System notice",success:"System notice",warning:"System warning",danger:"System alert"}[e];return(0,t.jsxs)("section",{role:"status","aria-label":g,className:W("relative w-full overflow-hidden rounded-lg border text-sm shadow-(--shadow-extract-8)",d.container,c),children:[(0,t.jsxs)("header",{className:"flex items-start gap-3 px-3 py-2.5 sm:px-4",children:[(0,t.jsx)("span",{className:W("mt-0.5 flex h-7 w-7 shrink-0 items-center justify-center rounded-md",d.iconWrap),"aria-hidden":!0,children:(0,t.jsx)(u,{className:W("h-4 w-4",d.iconClass)})}),(0,t.jsxs)("div",{className:"min-w-0 flex-1",children:[(0,t.jsxs)("div",{className:"flex flex-wrap items-center gap-x-2 gap-y-0.5 text-(length:--text-micro) font-semibold uppercase tracking-(--tracking-eyebrow)",children:[(0,t.jsx)("span",{className:d.label,children:g}),a?(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)("span",{className:"text-muted-foreground/60","aria-hidden":!0,children:"·"}),a.href?(0,t.jsx)("a",{href:a.href,className:"rounded-sm font-medium normal-case tracking-normal text-muted-foreground underline-offset-2 hover:text-foreground hover:underline",children:a.label}):(0,t.jsx)("span",{className:"font-medium normal-case tracking-normal text-muted-foreground",children:a.label})]}):null,l?(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)("span",{className:"text-muted-foreground/60","aria-hidden":!0,children:"·"}),(0,t.jsx)("span",{className:"font-medium normal-case tracking-normal text-muted-foreground",children:uft(l)})]}):null]}),(0,t.jsx)("div",{className:"mt-1 break-words text-sm leading-6 text-foreground",children:n})]}),x?(0,t.jsxs)("button",{type:"button",onClick:r(()=>p(v=>!v),"onClick"),"aria-expanded":h,"aria-controls":f,className:W("ml-1 inline-flex h-7 shrink-0 items-center gap-1 rounded-md border border-transparent px-2 text-(length:--text-micro) font-medium uppercase tracking-(--tracking-eyebrow) text-muted-foreground transition-(--tp-background-color-border-color-color)","hover:border-border/70 hover:bg-background/70 hover:text-foreground","focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring/50"),children:[(0,t.jsx)("span",{children:h?"Hide details":"Details"}),(0,t.jsx)(an,{className:W("h-3.5 w-3.5 transition-transform duration-150",h&&"rotate-180")})]}):null]}),x&&h?(0,t.jsx)("div",{id:f,className:W("border-t bg-background/50 dark:bg-background/30",d.divider),children:(0,t.jsx)($V,{sections:i,tone:e})}):null]})}r(OV,"SystemNotice");function S3e({requestedRef:e,repository:s,defaultBranch:n,agentName:a,configuredBy:i,taskOverride:o=!0,failureKind:l="unresolved_ref",unavailableReason:c,onRepair:d}){const u=(0,m.useId)(),[h,p]=(0,m.useState)(!n),[f,x]=(0,m.useState)(n??""),[g,v]=(0,m.useState)(!1),[y,k]=(0,m.useState)(!1),[w,N]=(0,m.useState)(null),[S,C]=(0,m.useState)(null),_=(0,m.useRef)(!1),R=f.trim().length>0&&f.trim()!==e;async function I(T){const E=T.trim();if(!(!E||E===e||c||_.current||S)){if(!FOe(E)){N("Enter a valid branch name, such as master or release/next.");return}_.current=!0,k(!0),N(null);try{await d(E),C(E)}catch(P){N(P instanceof Error?P.message:"Refresh the task to check its current state, then try again.")}finally{_.current=!1,k(!1)}}}return r(I,"repair"),(0,t.jsxs)("section",{"aria-labelledby":`${u}-title`,className:"flex min-w-0 gap-3 rounded-lg border border-border bg-muted/20 p-4","data-testid":"workspace-base-ref-recovery",children:[S?(0,t.jsx)(ms,{"aria-hidden":!0,className:"mt-0.5 size-4 shrink-0 text-(--status-task-icon-done)"}):(0,t.jsx)(Es,{"aria-hidden":!0,className:"mt-0.5 size-4 shrink-0 text-(--status-task-icon-blocked)"}),(0,t.jsxs)("div",{className:"flex min-w-0 flex-1 flex-col gap-3",children:[(0,t.jsxs)("div",{className:"flex flex-col gap-1",role:"status","aria-live":"polite",children:[(0,t.jsx)("h2",{id:`${u}-title`,className:"break-words text-sm font-semibold",children:S?"Branch updated · retry requested":l==="missing_branch"?(0,t.jsxs)(t.Fragment,{children:["Branch ",(0,t.jsx)("code",{className:"font-mono",children:e})," was not found"]}):(0,t.jsxs)(t.Fragment,{children:["Couldn’t use branch ",(0,t.jsx)("code",{className:"font-mono",children:e})]})}),(0,t.jsx)("p",{className:"text-sm leading-relaxed text-muted-foreground",children:S?(0,t.jsxs)(t.Fragment,{children:["This task now starts from ",(0,t.jsx)("code",{className:"font-mono text-foreground",children:S}),". A retry has been requested for ",a,"."]}):(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)("span",{className:"break-all text-foreground",children:s}),l==="missing_branch"?(0,t.jsxs)(t.Fragment,{children:[" has no branch named ",(0,t.jsx)("code",{className:"font-mono text-foreground",children:e}),"."]}):" could not resolve the starting branch. Check the branch name and repository access."," ",a," hasn’t started."]})})]}),!S&&(0,t.jsxs)(t.Fragment,{children:[n&&!h&&(0,t.jsxs)("p",{className:"flex flex-wrap items-center gap-1.5 text-sm",children:[(0,t.jsx)(Xi,{"aria-hidden":!0,className:"size-4 text-muted-foreground"}),(0,t.jsx)("code",{className:"font-mono",children:n}),(0,t.jsx)("span",{className:"text-muted-foreground",children:"is the repository’s default branch."})]}),(0,t.jsx)("p",{className:"text-xs text-muted-foreground",children:"Changes only this task’s starting branch."}),c&&(0,t.jsx)("p",{id:`${u}-unavailable`,className:"text-sm text-muted-foreground",children:c}),w&&(0,t.jsxs)("p",{role:"alert",id:`${u}-error`,className:"text-sm text-destructive",children:["Couldn’t confirm the repair. ",w]}),h?(0,t.jsxs)("form",{className:"flex flex-col gap-3",onSubmit:r(T=>{T.preventDefault(),I(f)},"onSubmit"),children:[(0,t.jsxs)("div",{className:"flex flex-col gap-1.5",children:[(0,t.jsx)($s,{htmlFor:`${u}-branch`,children:"Starting branch"}),(0,t.jsx)(dt,{id:`${u}-branch`,autoFocus:!0,value:f,disabled:y||!!c,onChange:r(T=>x(T.target.value),"onChange"),placeholder:"Branch name",className:"font-mono","aria-describedby":w?`${u}-error`:void 0,autoComplete:"off",spellCheck:!1})]}),(0,t.jsxs)("div",{className:"flex flex-wrap items-center justify-between gap-2",children:[n?(0,t.jsx)($,{type:"button",variant:"ghost",size:"sm",disabled:y,onClick:r(()=>{p(!1),N(null)},"onClick"),children:"Cancel"}):(0,t.jsx)("span",{}),(0,t.jsxs)($,{type:"submit",size:"sm",disabled:y||!R||!!c,"aria-describedby":c?`${u}-unavailable`:void 0,children:[y&&(0,t.jsx)(st,{"aria-hidden":!0,className:"size-3.5 animate-spin motion-reduce:animate-none"}),y?"Saving & requesting retry…":"Save branch & retry"]})]})]}):(0,t.jsxs)("div",{className:"flex flex-wrap items-center justify-between gap-2",children:[(0,t.jsx)($,{type:"button",variant:"ghost",size:"sm",disabled:y||!!c,onClick:r(()=>p(!0),"onClick"),children:"Choose another branch"}),(0,t.jsxs)($,{type:"button",size:"sm",disabled:y||!!c||n===e,"aria-describedby":c?`${u}-unavailable`:void 0,onClick:r(()=>{I(n)},"onClick"),children:[y&&(0,t.jsx)(st,{"aria-hidden":!0,className:"size-3.5 animate-spin motion-reduce:animate-none"}),y?"Saving & requesting retry…":`Use ${n} & retry`]})]})]}),(0,t.jsxs)("div",{children:[(0,t.jsxs)($,{type:"button",variant:"ghost",size:"xs",className:"text-muted-foreground","aria-expanded":g,"aria-controls":`${u}-details`,onClick:r(()=>v(T=>!T),"onClick"),children:[g?"Hide details":"Why did this happen?",(0,t.jsx)(an,{"aria-hidden":!0,className:W("size-3",g&&"rotate-180")})]}),g&&(0,t.jsx)("div",{id:`${u}-details`,className:"mt-2 rounded-md border border-border bg-background",children:(0,t.jsx)($V,{tone:"neutral",sections:[{rows:[{kind:"text",label:"Setting",value:o?"Task-specific starting branch":"Workspace starting branch"},{kind:"code",label:"Requested branch",value:e},...i?[{kind:"text",label:"Set by",value:i}]:[],{kind:"text",label:"Why it stopped",value:o?"An explicit task branch overrides the repository default. Paperclip does not silently switch branches.":"The configured starting branch must resolve before the agent can start. This repair overrides it for this task."}]}]})})]})]})]})}r(S3e,"WorkspaceBaseRefRecoveryNotice");var BV=(0,m.createContext)(null);function hft({value:e,children:s}){return(0,t.jsx)(BV.Provider,{value:e,children:s})}r(hft,"DispositionRecoveryProvider");function pft(e,s){if(e?.recovery?.kind==="disposition_repair_escalated")return e.recovery;if(!e||!s||s.kind!=="deliberate_wait_without_target"||s.ownerType!=="board"||s.wakePolicy?.type!=="board_escalation")return null;const n=s.evidence;return!e.sourceRunId||e.sourceRunId!==n?.latestRunId||!e.sections.some(a=>a.rows.some(i=>i.type==="key_value"&&i.value===s.id))||typeof n.terminalReason!="string"||typeof n.sourceAttemptCount!="number"||!Number.isInteger(n.sourceAttemptCount)||n.sourceAttemptCount<0||typeof n.sourceMaxAttempts!="number"||!Number.isInteger(n.sourceMaxAttempts)||n.sourceMaxAttempts<=0?null:{kind:"disposition_repair_escalated",actionId:s.id,attemptCount:n.sourceAttemptCount,maxAttempts:n.sourceMaxAttempts,reason:n.terminalReason,assigneeAgentId:s.returnOwnerAgentId}}r(pft,"readDispositionRecoverySnapshot");function C3e(e){return pft(e,(0,m.useContext)(BV)?.issue.activeRecoveryAction)}r(C3e,"useDispositionRecoverySnapshot");function fft(e,s){if(!s)return"Open the task to review its current state.";const{issue:n}=s,a=n.activeRecoveryAction;if(!a||a.id!==e.actionId||a.status!=="active")return"This recovery notice is no longer active.";if(n.status!=="blocked")return"The task’s state has changed. Review its current state before retrying.";if(a.kind!=="deliberate_wait_without_target"||a.ownerType!=="board"||a.wakePolicy?.type!=="board_escalation")return"The task’s recovery state has changed. Refresh to see the current action.";if(!e.assigneeAgentId||n.assigneeAgentId!==e.assigneeAgentId||a.returnOwnerAgentId!==e.assigneeAgentId)return"The assigned agent has changed. Review the task before retrying.";if(s.unavailableReason)return s.unavailableReason;if(s.hasPendingInteraction)return"Respond to the pending question or confirmation before retrying.";if(n.executionRunId||n.checkoutRunId)return"The task already has an active run. Wait for it to finish.";if(n.executionState?.status==="pending")return"The task is waiting for a review or approval.";if(n.blockedBy?.some(o=>o.status!=="done"&&o.status!=="cancelled"))return"Resolve the task’s blockers before retrying.";const i=s.agentMap?.get(e.assigneeAgentId);return i?.status==="paused"?"The assigned agent is paused. Resume the agent before retrying.":i?.status==="terminated"?"The assigned agent is no longer available.":null}r(fft,"dispositionRetryUnavailableReason");function xft(e){const s="The agent stopped without recording an outcome or a next step.";return e.reason==="owner_budget_blocked"?`${s} Automatic recovery stopped because a spending or pause limit prevents the agent from running.`:e.reason==="owner_not_invokable"?`${s} Automatic recovery stopped because the assigned agent is unavailable.`:e.reason==="unchanged_source_state_exhausted"?`${s} ${e.attemptCount===2?"Two":String(e.attemptCount)} automatic ${e.attemptCount===1?"attempt":"attempts"} to resolve this failed.`:`${s} Automatic recovery stopped. Review the details before trying again.`}r(xft,"descriptionFor");function FV({snapshot:e,createdAt:s,defaultExpanded:n=!1}){const a=(0,m.useContext)(BV),[i,o]=(0,m.useState)(n),[l,c]=(0,m.useState)(!1),[d,u]=(0,m.useState)(!1),[h,p]=(0,m.useState)(null),f=(0,m.useRef)(!1),x=(0,m.useId)(),g=(0,m.useId)(),v=(0,m.useId)(),y=fft(e,a),k=!!(a&&a.issue.activeRecoveryAction?.id!==e.actionId),w=e.assigneeAgentId&&a?.agentMap?.get(e.assigneeAgentId)?.name||"the assigned agent",N=d||k?ms:Es;async function S(){if(!(!a||y||f.current)){f.current=!0,c(!0),p(null);try{await a.onRetry(e.actionId),u(!0)}catch(C){p(C instanceof Error?C.message:"Refresh the task to check its current state, then try again.")}finally{f.current=!1,c(!1)}}}return r(S,"retry"),(0,t.jsxs)("section",{"aria-labelledby":g,className:"flex min-w-0 gap-2.5 py-3","data-testid":"disposition-recovery-notice",children:[(0,t.jsx)(N,{"aria-hidden":"true",className:W("mt-0.5 size-4 shrink-0",d||k?"text-muted-foreground":"text-(--status-task-icon-todo)")}),(0,t.jsxs)("div",{className:"flex min-w-0 flex-1 flex-col gap-2",children:[(0,t.jsxs)("div",{className:"flex flex-col gap-1",role:"status","aria-live":"polite",children:[(0,t.jsx)("h2",{id:g,className:"break-words text-sm font-medium text-foreground",children:d?"Retry requested":k?"Agent needed attention":"Agent needs attention"}),(0,t.jsx)("p",{className:"text-sm leading-relaxed text-muted-foreground",children:d?`The task was returned to To do for ${w}.`:xft(e)})]}),y&&!d?(0,t.jsxs)("p",{id:v,className:"text-xs leading-relaxed text-muted-foreground",children:[!k&&(0,t.jsx)("span",{className:"font-medium text-foreground",children:"Retry unavailable. "}),y]}):null,h?(0,t.jsxs)("p",{role:"alert",className:"text-sm text-destructive",children:["Couldn’t confirm the retry. ",h]}):null,(0,t.jsxs)("div",{className:"flex flex-wrap items-center gap-2",children:[!d&&!k?(0,t.jsxs)($,{size:"xs",variant:"outline",disabled:l||!!y,"aria-describedby":y?v:void 0,onClick:r(()=>{S()},"onClick"),children:[l?(0,t.jsx)(st,{"aria-hidden":"true",className:"size-3 animate-spin motion-reduce:animate-none"}):(0,t.jsx)(Ai,{"aria-hidden":"true",className:"size-3"}),l?"Requesting retry…":"Retry agent"]}):null,(0,t.jsxs)($,{size:"xs",variant:"ghost",className:"text-muted-foreground","aria-expanded":i,"aria-controls":x,onClick:r(()=>o(C=>!C),"onClick"),children:[i?"Hide details":"View details",(0,t.jsx)(an,{"aria-hidden":"true",className:W("size-3",i&&"rotate-180")})]}),s?(0,t.jsx)("time",{dateTime:s,className:"font-mono text-xs text-muted-foreground sm:ml-auto",children:io(s)}):null]}),i?(0,t.jsxs)("div",{id:x,className:"flex flex-col gap-3 rounded-lg border border-border bg-muted/20 p-3",children:[(0,t.jsxs)("dl",{className:"flex flex-col gap-2 text-xs",children:[(0,t.jsxs)("div",{className:"flex flex-wrap justify-between gap-1",children:[(0,t.jsx)("dt",{className:"text-muted-foreground",children:"Assigned when recovery stopped"}),(0,t.jsx)("dd",{children:w})]}),(0,t.jsxs)("div",{className:"flex flex-wrap justify-between gap-1",children:[(0,t.jsx)("dt",{className:"text-muted-foreground",children:"Automatic attempts"}),(0,t.jsxs)("dd",{className:"font-mono",children:[e.attemptCount," of ",e.maxAttempts]})]}),(0,t.jsxs)("div",{className:"flex flex-wrap justify-between gap-1",children:[(0,t.jsx)("dt",{className:"text-muted-foreground",children:"Automatic retries for this recovery"}),(0,t.jsx)("dd",{children:"Stopped"})]})]}),(0,t.jsx)("p",{className:"text-xs leading-relaxed text-muted-foreground",children:"Recovery asked the assigned agent to record an outcome or a next step. Retrying keeps the same task and agent, and checks the task’s current controls before continuing."}),(0,t.jsxs)("div",{className:"flex flex-col gap-1",children:[(0,t.jsx)("span",{className:"text-xs text-muted-foreground",children:"Technical reason"}),(0,t.jsx)("code",{className:"break-all font-mono text-xs",children:e.reason})]})]}):null]})]})}r(FV,"DispositionRecoveryNotice");var gft="System update",bft=80;function vft(e){const s=e.match(/Latest retry failure: `([^`]+)`/);return s?s[1]:null}r(vft,"retryFailureCode");function yft(e){const s=e.match(/Recovery owner: \[([^\]]+)\]\(/)?.[1]?.trim();return s&&s.length>0?s:null}r(yft,"recoveryOwnerName");function jft(e){const s=e.split(`
383
383
  `).map(i=>i.trim()).find(i=>i.length>0);if(!s)return;const n=s.search(/[.!?](\s|$)/),a=n>=0?s.slice(0,n+1):s;return a.length<=bft?a:`${a.slice(0,79).trimEnd()}…`}r(jft,"firstSentence");function wft(e){const s=e.presentation?.title?.trim(),n=e.presentation?.tone;if(s)return{title:s,tone:n??"neutral"};const a=e.body??"",i=vft(a);if(i==="claude_auth_required")return{title:"Task paused — Claude needs re-authentication",tone:n??"warning"};if(i==="configuration_incomplete"||a.includes("secret/env bindings are missing"))return{title:"Task paused — a secret/config binding is missing",tone:n??"warning"};if(i==="workspace_validation_failed"||a.includes("workspace failed validation"))return{title:"Task paused — workspace problem",tone:n??"warning"};if(a.includes("no live execution path")){const o=yft(a);return{title:o?`Task paused — waiting on ${o}`:"Task paused — waiting on a recovery owner",tone:n??"warning"}}return{title:gft,tone:n??"neutral",detail:jft(a)}}r(wft,"humanizeSystemNotice");var kft={neutral:"System notice",info:"System notice",success:"System notice",warning:"System warning",danger:"System alert"};function Jw(e,s){const n=e.label?.trim();return n&&n.length>0?n:s}r(Jw,"metadataRowText");function Nft(e,s){switch(e.type){case"text":return{kind:"text",label:Jw(e,"Detail"),value:e.text};case"code":return{kind:"code",label:Jw(e,"Code"),value:e.code};case"key_value":return{kind:"text",label:e.label,value:e.value};case"issue_link":{const n=e.identifier??null;return n?{kind:"issue",label:Jw(e,"Task"),identifier:n,href:`/issues/${n}`,title:e.title??void 0}:{kind:"text",label:Jw(e,"Task"),value:e.title??"unknown"}}case"agent_link":{const n=e.name?.trim()||e.agentId.slice(0,8);return{kind:"agent",label:Jw(e,"Agent"),name:n,href:`/agents/${e.agentId}`}}case"run_link":{const n=e.agentId??s.runAgentId??null,a=n?`/agents/${n}/runs/${e.runId}`:void 0;return{kind:"run",label:Jw(e,"Run"),runId:e.runId,href:a,status:e.title??void 0}}default:return null}}r(Nft,"mapMetadataRow");function zV(e,s={}){return!e||!Array.isArray(e.sections)?[]:e.sections.map(n=>{const a=n.rows.map(o=>Nft(o,s)).filter(o=>o!==null);if(a.length===0)return null;const i={rows:a};return n.title&&(i.title=n.title),i}).filter(n=>n!==null)}r(zV,"mapCommentMetadataToSystemNoticeSections");function _3e(e,s){const n=s?.trim();return n&&n.length>0?n:kft[e]}r(_3e,"systemNoticeLabelForTone");function Sft(e){const s=e.presentation?.tone??"neutral",n=_3e(s,e.presentation?.title),a=!!e.presentation?.detailsDefaultOpen,i=zV(e.metadata,{runAgentId:e.runAgentId??null});return{tone:s,label:n,body:e.body,metadata:i.length>0?i:void 0,detailsDefaultOpen:a,timestamp:e.timestamp,source:e.source}}r(Sft,"buildSystemNoticeProps");var Cft={neutral:s0,info:s0,success:fa,warning:Es,danger:oN},_ft={neutral:"text-muted-foreground",info:"text-(--status-task-icon-in_progress)",success:"text-(--status-task-icon-done)",warning:"text-(--status-task-icon-todo)",danger:"text-(--status-task-icon-blocked)"};function Aft({item:e,onTryAgainNoLiveExecutionPath:s,tryAgainNoLiveExecutionPathPending:n=!1}){const a=C3e(e.metadata),i=k3e(e.metadata),o=ap(),[l,c]=(0,m.useState)(!!e.presentation?.detailsDefaultOpen),d=(0,m.useId)(),{title:u,tone:h,detail:p}=wft({body:e.text,presentation:e.presentation}),f=zV(e.metadata,{runAgentId:e.runAgentId}),x=!(e.presentation?.kind==="system_notice"&&e.presentation.title?.trim().toLowerCase().startsWith("workspace ready")===!0&&f.some(w=>w.title?.trim().toLowerCase()==="workspace")),g=Cft[h],v=e.createdAtIso?io(e.createdAtIso):void 0,y=!!s&&(e.presentation?.title?.trim()==="No live execution path"||e.text.toLowerCase().includes("no live execution path")),k=r(()=>{Promise.resolve().then(()=>s?.()).catch(()=>{})},"handleTryAgain");return e.author==="system"&&i?(0,t.jsx)(S3e,{...i.props},`${i.actionId}:${i.runId}`):e.author==="system"&&a?(0,t.jsx)(FV,{snapshot:a,createdAt:e.createdAtIso,defaultExpanded:e.presentation?.detailsDefaultOpen}):(0,t.jsxs)("div",{className:W("tc-enter-bubble flex flex-col items-start",o?"py-0.5":"py-1"),"data-testid":"task-chat-system-notice","data-tone":o?h:void 0,role:o?"group":void 0,"aria-label":o?`System update: ${u}`:void 0,children:[(0,t.jsxs)("div",{className:"flex max-w-(--pct-85) items-center gap-1.5",children:[(0,t.jsxs)("button",{type:"button",onClick:r(()=>c(w=>!w),"onClick"),"aria-expanded":l,"aria-controls":d,className:W("flex min-w-0 items-center gap-1.5 rounded-md px-2 py-0.5 text-xs text-muted-foreground","hover:bg-muted/50 hover:text-foreground","focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring/50"),children:[(0,t.jsx)(g,{className:W("h-3.5 w-3.5 shrink-0",_ft[h]),"aria-hidden":!0}),(0,t.jsx)("span",{className:"truncate font-medium",children:u}),p?(0,t.jsxs)("span",{className:"hidden truncate sm:inline",children:["· ",p]}):null,v?(0,t.jsxs)("span",{className:"shrink-0 text-muted-foreground/70",children:["· ",v]}):null,(0,t.jsx)(an,{className:W("tc-notice-chevron h-3.5 w-3.5 shrink-0 transition-transform",l&&"rotate-180"),"aria-hidden":!0})]}),y&&!l?(0,t.jsx)($,{type:"button",variant:"outline",size:"xs",onClick:k,disabled:n,"data-testid":"task-chat-no-live-path-try-again",children:n?"Trying again...":"Try again"}):null]}),l?(0,t.jsxs)("div",{id:d,"data-testid":"task-chat-system-notice-details",className:"mt-1 w-full max-w-(--pct-85) overflow-hidden rounded-lg border border-border bg-muted/25 text-left text-sm dark:bg-muted/15",children:[x?(0,t.jsx)("div",{className:"px-3 py-2.5 text-foreground/90",children:(0,t.jsx)(An,{softBreaks:!0,linkIssueReferences:!0,children:e.text})}):null,f.length>0?(0,t.jsx)("div",{className:W("bg-background/50 dark:bg-background/30",x&&"border-t border-border/70"),children:(0,t.jsx)($V,{sections:f,tone:h})}):null,y?(0,t.jsx)("div",{className:"flex justify-end border-t border-border/70 bg-background/50 px-3 py-2 dark:bg-background/30",children:(0,t.jsx)($,{type:"button",size:"xs",onClick:k,disabled:n,"data-testid":"task-chat-no-live-path-try-again",children:n?"Trying again...":"Try again"})}):null]}):null]})}r(Aft,"TaskChatSystemNotice");function qV({agentName:e,agentIcon:s,agent:n}){return(0,t.jsxs)("span",{className:"flex items-center gap-2 px-1","data-testid":"task-chat-agent-identity",children:[(0,t.jsx)("span",{"data-testid":"task-chat-agent-avatar",children:(0,t.jsx)(lr,{agent:n,name:e,size:24})}),(0,t.jsx)("span",{className:"text-sm font-semibold text-foreground",children:e})]})}r(qV,"TaskChatAgentIdentity");function Gae(e,s,n){return{id:n?.id??e,contentPath:n?.openPath??e,openPath:n?.openPath,downloadPath:n?.downloadPath,contentType:n?.contentType??"",originalFilename:s?.trim()?s:"image"}}r(Gae,"galleryItemForMedia");function Yae(e){return e.filter((s,n)=>e.findIndex(a=>s.id&&a.id===s.id||a.url===s.url)===n)}r(Yae,"uniqueAttachmentRefs");function A3e(e){return y3e(e.item.id)??(0,t.jsx)(Ift,{...e})}r(A3e,"TaskChatBubble");function Ift({item:e,animateEntry:s=!0,queuedAction:n,attachedTurn:a,beforeTurn:i,hideAgentIdentity:o=!1,actions:l,attachments:c=[],onTryAgainNoLiveExecutionPath:d,tryAgainNoLiveExecutionPathPending:u}){const h=ap(),p=(0,m.useContext)(gg),f=(0,m.useContext)(Jy),[x,g]=(0,m.useState)(null),v=(0,m.useCallback)(L=>{f?.(L)||g(L)},[f]);if(e.interstitial)return null;if(e.author==="system")return(0,t.jsx)(Aft,{item:e,onTryAgainNoLiveExecutionPath:d,tryAgainNoLiveExecutionPathPending:u});const y=e.author==="human",k=y&&e.isCurrentUser===!0,w=y&&e.sourceChannel==="imessage-photon",{refs:N,text:S}=UJe(e.text),C=zJe(S),_=qJe(S),R=Ese(N,c),I=Ese(C,c),T=c.filter(L=>L.issueCommentId===e.id).map(L=>({id:L.id,name:L.originalFilename?.trim()||"attachment",url:L.contentPath,contentType:L.contentType,byteSize:L.byteSize,openPath:L.openPath,downloadPath:L.downloadPath})),E=Yae([...I,...R.filter(bI),...T.filter(bI)]),P=Yae([...R.filter(L=>!bI(L)),...T.filter(L=>!bI(L))]),O=[...E,...P.filter(L=>ym(L.contentType,L.name))],M=x!==null&&!O.some(L=>L.url===x)?[Gae(x)]:O.map(L=>Gae(L.url,L.name,L)),Q=x===null?-1:Math.max(0,O.findIndex(L=>L.url===x));return(0,t.jsxs)("div",{className:W("flex w-full flex-col gap-1",s&&"tc-enter-bubble",k?"items-end":"items-start"),children:[i?(0,t.jsx)("div",{className:"w-full pb-1",children:i}):null,y&&!e.isCurrentUser&&e.authorName?(0,t.jsx)("span",{className:"px-1 text-sm font-semibold text-foreground","data-testid":"task-chat-human-identity","data-author-user-id":e.authorUserId,children:(0,t.jsx)(yo,{name:e.authorName,avatarUrl:lft(e.authorAvatarUrl),size:"default",className:"gap-2"})}):null,!y&&e.authorName&&!o?(0,t.jsx)(qV,{agentName:e.authorName,agentIcon:e.agentIcon,agent:e.agent}):null,_.length>0?(0,t.jsx)("div",{"data-testid":y?"task-chat-human-bubble":"task-chat-agent-bubble",className:W("break-words py-2 text-sm",k?"max-w-(--pct-85) rounded-2xl rounded-br-sm bg-(--liveness-blue) px-3.5 text-white":"w-full bg-transparent px-1 text-foreground"),children:(0,t.jsx)(An,{className:k?"paperclip-markdown-on-accent":void 0,softBreaks:!0,linkIssueReferences:!0,onImageClick:v,children:_})}):null,E.length>0?(0,t.jsxs)("div",{className:"flex max-w-(--pct-85) flex-col gap-2","data-testid":"task-chat-bubble-media",children:[(0,t.jsxs)("span",{className:"text-xs text-muted-foreground",children:["Images · ",E.length]}),(0,t.jsxs)("div",{className:"grid grid-cols-4 gap-2",children:[E.slice(0,E.length>4?3:4).map((L,F)=>(0,t.jsx)("button",{type:"button",className:"group aspect-video min-w-0 overflow-hidden rounded-md bg-muted outline-none focus-visible:ring-2 focus-visible:ring-ring","aria-label":`Open ${L.name||`image ${F+1}`}`,onClick:r(()=>v(L.url),"onClick"),children:(0,t.jsx)("img",{src:L.openPath??L.url,alt:L.name,loading:"lazy",className:"h-full w-full object-cover transition-transform group-hover:scale-(--s-1_02)"})},L.url)),E.length>4?(0,t.jsxs)("button",{type:"button",className:"aspect-video min-w-0 rounded-md bg-muted text-sm font-semibold text-foreground outline-none focus-visible:ring-2 focus-visible:ring-ring","aria-label":`Open ${E.length-3} more screenshots`,onClick:r(()=>v(E[3].url),"onClick"),children:["+",E.length-3]}):null]}),(0,t.jsx)("span",{className:"truncate text-xs text-muted-foreground",children:E.map(L=>L.name||"image").join(" · ")})]}):null,P.length>0?(0,t.jsxs)("div",{className:"flex max-w-(--pct-85) flex-col gap-2",children:[(0,t.jsxs)("span",{className:"text-xs text-muted-foreground",children:["Files · ",P.length]}),(0,t.jsx)(mH,{"data-testid":"task-chat-bubble-attachments",children:P.map(L=>{const F=l2e(L),q=F.icon,z=hH(L.byteSize),K=ym(L.contentType,L.name);return(0,t.jsxs)(oH,{size:"sm",children:[(0,t.jsx)(lH,{className:K?"aspect-video group-data-[size=sm]/attachment:w-20":void 0,children:K?(0,t.jsx)(eA,{artifact:{title:L.name,contentPath:L.openPath??L.url,mediaKind:"video"}}):(0,t.jsx)(q,{"aria-hidden":!0})}),(0,t.jsxs)(cH,{children:[(0,t.jsx)(dH,{className:"max-w-48",children:L.name}),(0,t.jsx)(uH,{className:"max-w-48",children:z?`${F.label} · ${z}`:F.label})]}),(0,t.jsx)(r2e,{"aria-label":`Open ${L.name}`,onClick:K?()=>v(L.url):void 0,render:K?(0,t.jsx)("button",{type:"button"}):(0,t.jsx)("a",{href:L.openPath??L.url,onClick:r(U=>{p&&L.id&&rw({contentType:L.contentType??"",originalFilename:L.name})&&!U.metaKey&&!U.ctrlKey&&!U.shiftKey&&!U.altKey&&(U.preventDefault(),p(L.id,L.name))},"onClick"),target:"_blank",rel:"noreferrer"})})]},L.url)})})]}):null,!y&&e.verificationCaveats?.length?(0,t.jsxs)("div",{className:"mx-1 w-(--sz-calc-7) rounded-md border border-amber-500/25 bg-amber-500/5 px-3 py-2 text-xs","data-testid":"task-chat-verification-caveats",children:[(0,t.jsx)("p",{className:"font-medium text-amber-800 dark:text-amber-200",children:"Verification caveat"}),(0,t.jsx)("ul",{className:"mt-1 space-y-1 text-muted-foreground",children:e.verificationCaveats.map((L,F)=>(0,t.jsxs)("li",{children:[(0,t.jsx)("span",{className:"font-mono text-foreground",children:L.commandOrCheck}),L.reasonCode?` · ${L.reasonCode.replaceAll("_"," ")}`:"",L.detail?(0,t.jsx)("span",{className:"block",children:L.detail}):null]},`${L.commandOrCheck}:${F}`))})]}):null,e.optimistic?(0,t.jsxs)("span",{className:"flex items-center gap-1 px-1 text-(length:--text-micro) text-muted-foreground",children:[(0,t.jsx)("span",{children:e.optimistic==="queued"?"Queued":"Sending…"}),e.optimistic==="queued"?n:null]}):a?(0,t.jsx)("div",{className:"self-stretch","data-testid":"task-chat-bubble-attached-turn",children:a}):l?h?(0,t.jsxs)("div",{className:"flex w-full items-center justify-between gap-2 px-1",children:[e.timestamp||w?(0,t.jsxs)("span",{className:"text-(length:--text-micro) text-muted-foreground",children:[w?"Sent from iMessage":null,w&&e.timestamp?" · ":null,e.timestamp]}):null,l]}):(0,t.jsxs)("div",{className:"flex items-center gap-1",children:[l,e.timestamp||w?(0,t.jsxs)("span",{className:"px-1 text-(length:--text-micro) text-muted-foreground",children:[w?"Sent from iMessage":null,w&&e.timestamp?" · ":null,e.timestamp]}):null]}):e.timestamp||w?(0,t.jsxs)("span",{className:"px-1 text-(length:--text-micro) text-muted-foreground",children:[w?"Sent from iMessage":null,w&&e.timestamp?" · ":null,e.timestamp]}):null,x!==null&&Q>=0?(0,t.jsx)(aw,{items:M,initialIndex:Q,open:!0,onOpenChange:r(L=>{L||g(null)},"onOpenChange")}):null]})}r(Ift,"TaskChatBubbleContent");function Zae(e){const s=[];return e.durationLabel&&s.push(e.durationLabel),e.toolCount>0&&s.push(`${e.toolCount} tool${e.toolCount===1?"":"s"}`),(e.added>0||e.removed>0)&&s.push(`+${e.added} −${e.removed}`),e.tokensLabel&&s.push(e.tokensLabel),s.join(" · ")}r(Zae,"turnSummaryMetrics");function Jae({item:e,renderChild:s,timestampPrefix:n,leading:a}){const i=ap(),o=!e.settled&&e.liveStatus!=null;if(e.standaloneHeader)return(0,t.jsxs)("div",{"data-testid":"task-chat-turn","data-settled":e.settled?"true":"false",children:[e.agentName||!e.historical?(0,t.jsxs)("div",{className:"flex min-h-8 w-full min-w-0 items-center gap-2 pb-1 pt-1.5 text-sm text-muted-foreground","data-testid":"task-chat-turn-summary","data-turn-position":"identity",children:[e.agentName?(0,t.jsx)(qV,{agentName:e.agentName,agentIcon:e.agentIcon,agent:e.agent}):null,e.historical?null:(0,t.jsxs)("span",{className:"min-w-0 truncate",children:[e.continuedAfterSteering?"Continued after steering · ":"",e.summary.durationLabel?`${e.summary.failed?"Stopped":"Worked"} for ${e.summary.durationLabel}`:e.summary.failed?"Stopped":"Worked"]})]}):null,e.items.length>0?(0,t.jsx)("div",{className:"flex min-w-0 flex-col gap-2 py-1","data-testid":"task-chat-turn-timeline",children:e.items.map(C=>(0,t.jsx)("div",{className:"min-w-0","data-testid":"task-chat-turn-timeline-row","data-timeline-row-id":C.id,"data-thread-anchor":C.id,children:s(C)},C.id))}):null,e.finalResponse?(0,t.jsx)("div",{className:"w-full","data-testid":"task-chat-final-response",children:(0,t.jsx)("div",{className:"break-words px-1 py-2 text-sm text-foreground","data-testid":"task-chat-agent-bubble",children:(0,t.jsx)(An,{softBreaks:!0,linkIssueReferences:!0,children:e.finalResponse.text})})}):null]});const l=e.settled?e.items.filter(C=>C.kind==="protocol"&&C.surface==="runtime_request"):[],c=new Set(l.map(C=>C.id)),d=l.length>0?e.items.filter(C=>!c.has(C.id)):e.items,[u,h]=(0,m.useState)(()=>!e.settled&&e.liveStatus==null),[p,f]=(0,m.useState)(u);u&&!p&&f(!0);const[x,g]=(0,m.useState)(e.settled),[v,y]=(0,m.useState)(o);o&&!v&&y(!0),e.settled!==x&&(g(e.settled),e.settled&&!v&&h(!1));const k=d.length>0,w=(e.settled||o)&&!u,N=e.summary.failed?Mn:ms,S=e.settled&&(!e.historical||k)?(0,t.jsxs)("button",{type:"button",onClick:r(()=>h(C=>!C),"onClick"),"aria-expanded":u,className:W("group flex w-full items-center gap-2 px-1 text-muted-foreground transition-colors hover:text-foreground",e.standaloneHeader?"border-b border-border/70 py-2 text-sm":"py-0.5 text-xs",i&&"min-w-0"),"data-testid":"task-chat-turn-summary",children:[n?(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)("span",{className:"text-(length:--text-micro)",children:n}),(0,t.jsx)("span",{"aria-hidden":!0,className:"text-(length:--text-micro)",children:"·"})]}):null,!e.standaloneHeader&&!e.historical?(0,t.jsx)(N,{className:"h-3.5 w-3.5 shrink-0"}):null,(0,t.jsx)("span",{children:e.historical?"Activity":e.standaloneHeader&&e.summary.durationLabel?`${e.summary.failed?"Stopped":"Worked"} for ${e.summary.durationLabel}`:e.summary.failed?"Stopped":"Worked"}),!e.standaloneHeader&&Zae(e.summary)?(0,t.jsx)("span",{className:"tc-turn-metrics","data-visible":u?"true":"false",children:(0,t.jsx)("span",{className:"min-w-0 overflow-hidden whitespace-nowrap font-mono text-(length:--text-micro)",children:Zae(e.summary)})}):null,(0,t.jsx)(Ln,{className:W("h-3 w-3 shrink-0 transition-transform",e.standaloneHeader&&"ml-auto",u?"rotate-90":null),"aria-hidden":!0})]}):o?(0,t.jsx)(l3e,{item:e.liveStatus,chevronOpen:k?u:void 0,onToggle:k?()=>h(C=>!C):void 0}):null;return(0,t.jsxs)("div",{"data-testid":"task-chat-turn","data-settled":e.settled?"true":"false",children:[a?i?(0,t.jsxs)("div",{className:"flex w-full items-center justify-between gap-2",children:[(0,t.jsx)("div",{className:"min-w-0",children:S}),(0,t.jsx)("div",{className:"shrink-0",children:a})]}):(0,t.jsxs)("div",{className:"flex items-center gap-1",children:[a,S]}):S,(0,t.jsx)("div",{className:"tc-turn-fold","data-folded":w?"true":"false","aria-hidden":w,children:(0,t.jsx)("div",{children:(0,t.jsx)("div",{className:"flex flex-col gap-2 pt-1",children:p&&d.map(C=>(0,t.jsx)("div",{children:s(C)},C.id))})})}),l.length>0?(0,t.jsx)("div",{className:"flex flex-col gap-2 pt-2","data-testid":"task-chat-turn-persistent-history",children:l.map(C=>(0,t.jsx)("div",{children:s(C)},C.id))}):null]})}r(Jae,"TaskChatTurn");var Tft={session_start:nm,interrupted:gW,turn_boundary:ug};function I3e({item:e,onTryAgain:s,tryAgainPending:n=!1}){const[a,i]=(0,m.useState)(!1),o=(0,m.useId)(),l=ap(),c=e.tone==="neutral"?fg:Tft[e.variant],d=e.variant==="interrupted"&&e.tone!=="neutral",u=e.createdAtIso?io(e.createdAtIso):void 0,h=r(()=>{Promise.resolve().then(()=>s?.()).catch(()=>{})},"handleTryAgain");if(e.credentialAccess){const{agentName:p,credentialName:f,deniedUser:x,settingsHref:g}=e.credentialAccess;return(0,t.jsxs)("div",{role:"alert","data-testid":"task-chat-credential-access-notice",className:"tc-enter-marker flex w-full items-start gap-3 rounded-lg border border-destructive/40 bg-destructive/10 p-4 text-sm",children:[(0,t.jsx)(Si,{className:"mt-0.5 size-5 shrink-0 text-destructive","aria-hidden":!0}),(0,t.jsxs)("div",{className:"flex min-w-0 flex-1 flex-col gap-2",children:[(0,t.jsxs)("p",{className:"font-semibold text-destructive",children:[p," couldn’t start"]}),(0,t.jsxs)("p",{className:"break-words font-medium text-foreground",children:[p," is configured to use ",f||"an AI credential",", but ",x==="you"?"you don’t":`${x} doesn’t`," have access to that credential."]}),(0,t.jsxs)("p",{className:"text-muted-foreground",children:["Choose an AI connection ",x==="you"?"you can":`${x} can`," use, or ask an administrator to update ",p,"’s connection. Then try again."]}),(0,t.jsxs)("div",{className:"flex flex-wrap items-center gap-2 pt-1",children:[(0,t.jsx)($,{asChild:!0,variant:"outline",size:"sm",children:(0,t.jsx)(We,{to:g,children:"Change AI connection"})}),e.runHref&&(0,t.jsx)($,{asChild:!0,variant:"ghost",size:"sm",children:(0,t.jsx)(We,{to:e.runHref,children:"View run"})})]})]})]})}return e.collapsible?(0,t.jsxs)("div",{className:"tc-enter-marker flex flex-col items-start py-1 text-xs text-muted-foreground","data-testid":"task-chat-collapsible-marker",children:[(0,t.jsxs)("div",{className:"flex max-w-(--pct-85) items-center gap-1.5",children:[(0,t.jsxs)("button",{type:"button",onClick:r(()=>i(p=>!p),"onClick"),"aria-expanded":a,"aria-controls":o,className:W("flex min-w-0 items-center gap-1.5 rounded-md px-2 py-0.5",d?"text-destructive":"text-muted-foreground","hover:bg-muted/50 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring/50"),children:[(0,t.jsx)(c,{className:"h-3.5 w-3.5 shrink-0","aria-hidden":!0}),(0,t.jsx)("span",{className:"truncate font-medium",children:e.label}),u?(0,t.jsxs)("span",{className:"shrink-0 text-muted-foreground/70",children:["· ",u]}):null,(0,t.jsx)(an,{className:W("tc-notice-chevron h-3.5 w-3.5 shrink-0 transition-transform",a&&"rotate-180"),"aria-hidden":!0})]}),s&&!a?(0,t.jsx)($,{type:"button",variant:"outline",size:"xs",onClick:h,disabled:n,"data-testid":"task-chat-run-failed-try-again",children:n?"Trying again...":"Try again"}):null]}),a?(0,t.jsxs)("div",{id:o,"data-testid":"task-chat-collapsible-marker-details",className:"mt-1 w-full max-w-(--pct-85) overflow-hidden rounded-lg border border-border bg-muted/25 text-left text-sm dark:bg-muted/15",children:[e.detail?(0,t.jsx)("div",{className:"px-3 py-2.5 text-foreground/90",children:e.detail}):null,e.runHref||e.planHref||s?(0,t.jsxs)("div",{className:"flex items-center justify-end gap-2 border-t border-border/70 bg-background/50 px-3 py-2 dark:bg-background/30",children:[e.planHref?(0,t.jsx)($,{asChild:!0,variant:"ghost",size:"xs",children:(0,t.jsx)(We,{to:e.planHref,children:"View saved plan"})}):null,e.runHref?(0,t.jsx)($,{asChild:!0,variant:"ghost",size:"xs",children:(0,t.jsx)(We,{to:e.runHref,children:"View run"})}):null,s?(0,t.jsx)($,{type:"button",size:"xs",onClick:h,disabled:n,"data-testid":"task-chat-run-failed-try-again",children:n?"Trying again...":"Try again"}):null]}):null]}):null]}):(0,t.jsxs)("div",{className:"tc-enter-marker flex items-center gap-2 py-1 text-xs text-muted-foreground",role:l?"separator":void 0,"aria-label":l?e.label:void 0,children:[(0,t.jsx)("span",{className:W("h-px flex-1",d?"border-t border-dashed border-destructive/50":"bg-border")}),(0,t.jsxs)("span",{className:W("flex items-center gap-1.5",d&&"text-destructive"),children:[(0,t.jsx)(c,{className:"h-3.5 w-3.5"}),(0,t.jsx)("span",{className:"font-medium",children:e.label}),e.detail?(0,t.jsxs)("span",{className:"text-muted-foreground",children:["· ",e.detail]}):null,s?(0,t.jsx)($,{type:"button",variant:"outline",size:"xs",onClick:h,disabled:n,"data-testid":"task-chat-run-failed-try-again",children:n?"Trying again...":"Try again"}):null]}),(0,t.jsx)("span",{className:W("h-px flex-1",d?"border-t border-dashed border-destructive/50":"bg-border")})]})}r(I3e,"TaskChatMarker");var T3e=(0,m.createContext)(null);function Rft(e){const[s,n]=(0,m.useState)(()=>({issueId:e,memory:new Map}));if(s.issueId===e)return s.memory;const a={issueId:e,memory:new Map};return n(a),a.memory}r(Rft,"useIssueExpansionMemory");function TM(e,s){const n=(0,m.useContext)(T3e),[a,i]=(0,m.useState)(()=>n?.get(e));return[a??n?.get(e)??s,(0,m.useCallback)(o=>{i(l=>{const c=l??n?.get(e)??s,d=typeof o=="function"?o(c):o;return n?.set(e,d),d})},[e,n,s])]}r(TM,"useTaskChatExpansion");var Eft={pending:{Icon:st,spin:!1,tone:"text-muted-foreground"},in_progress:{Icon:st,spin:!0,tone:"text-(--status-agent-running)"},completed:{Icon:ms,spin:!1,tone:"text-muted-foreground"},failed:{Icon:Mn,spin:!1,tone:"text-destructive"},interrupted:{Icon:Mn,spin:!1,tone:"text-muted-foreground"}};function R3e({item:e}){const{Icon:s,spin:n,tone:a}=Eft[e.status],i=AN(e.rawName??e.name).icon,[o,l]=TM(e.id,!1),c=!!(e.target||e.detail||e.diff);return(0,t.jsxs)("div",{"data-testid":"task-chat-tool-card",className:"flex min-w-0 max-w-full flex-col text-xs",children:[(0,t.jsxs)("button",{type:"button",onClick:c?()=>l(d=>!d):void 0,"aria-expanded":c?o:void 0,className:W("group/tool -mx-1.5 flex min-h-6 w-full min-w-0 max-w-full items-center gap-2 overflow-hidden rounded-sm px-1.5 py-1 text-left leading-none text-muted-foreground",c?"cursor-pointer transition-colors hover:bg-muted/60 hover:text-foreground":"cursor-default"),children:[(0,t.jsx)("span",{className:"flex w-5 shrink-0 items-center justify-center",children:(0,t.jsx)(i,{className:"h-3.5 w-3.5 shrink-0","aria-hidden":!0,"data-testid":"task-chat-tool-icon"})}),(0,t.jsxs)("span",{className:"flex min-w-0 flex-1 items-baseline gap-2 overflow-hidden",children:[(0,t.jsx)("span",{className:"shrink-0 font-medium leading-4",children:e.name}),e.target?(0,t.jsx)("span",{className:"task-chat-collapsed-line-fade min-w-0 flex-1 font-mono text-(length:--text-micro) leading-4",children:e.target}):null]}),(0,t.jsxs)("span",{className:"ml-auto flex shrink-0 items-center gap-2",children:[e.decision?(0,t.jsxs)("span",{className:W("flex items-center gap-1 text-(length:--text-micro)",e.decision==="allowed"?"text-(--status-task-icon-done)":"text-destructive"),children:[e.decision==="allowed"?(0,t.jsx)(Bi,{className:"h-3 w-3"}):(0,t.jsx)(kW,{className:"h-3 w-3"}),e.decision]}):null,c?(0,t.jsx)(Ln,{className:W("h-3 w-3 opacity-0 transition-[opacity,transform] group-hover/tool:opacity-80",o?"rotate-90":null),"aria-hidden":!0}):null,(0,t.jsx)(s,{className:W("h-3.5 w-3.5",a,n&&"animate-spin"),"aria-hidden":!0}),e.status==="interrupted"?(0,t.jsx)("span",{className:"text-(length:--text-micro) text-muted-foreground",children:"Interrupted"}):null]})]}),e.target&&o?(0,t.jsx)("div",{className:"task-chat-expanded-line-wrap ml-1.5 mt-0.5 min-w-0 max-w-full overflow-hidden border-l-2 border-border py-1 pl-2.5 font-mono text-(length:--text-micro) leading-relaxed text-muted-foreground","data-testid":"task-chat-tool-target-detail",children:e.target}):null,e.detail&&o?(0,t.jsx)("pre",{className:"task-chat-expanded-line-wrap ml-1.5 mt-0.5 min-w-0 max-w-full overflow-hidden whitespace-pre-wrap border-l-2 border-border py-1 pl-2.5 font-mono text-(length:--text-micro) leading-relaxed text-muted-foreground",children:e.detail}):null,e.diff&&o?(0,t.jsx)("div",{className:"ml-1.5 mt-0.5 border-l-2 border-border py-1 pl-2.5","data-testid":"task-chat-tool-change-summary",children:(0,t.jsxs)("div",{className:"flex min-w-0 items-center gap-2 text-(length:--text-micro) text-muted-foreground",children:[(0,t.jsx)("span",{className:"shrink-0",children:"Changed"}),e.diff.path?(0,t.jsx)("span",{className:"min-w-0 truncate font-mono text-foreground",children:e.diff.path}):null,(0,t.jsxs)("span",{className:"ml-auto shrink-0 font-mono",children:["+",e.diff.added," −",e.diff.removed]})]})}):null]})}r(R3e,"TaskChatToolCard");function UV({item:e}){const{used:s,size:n,inputTokens:a,outputTokens:i,costUsd:o}=e.usage,l=typeof n=="number"&&n>0?n:null,c=l?Math.min(100,Math.round(s/l*100)):0;return(0,t.jsxs)("div",{className:"flex flex-col gap-1 px-1 py-1 text-(length:--text-micro) text-muted-foreground",children:[(0,t.jsxs)("div",{className:"flex items-center gap-1.5",children:[(0,t.jsx)(hW,{className:"h-3 w-3"}),e.label?(0,t.jsx)("span",{className:"font-medium",children:e.label}):null,l?(0,t.jsxs)("span",{children:[s.toLocaleString(),"/",l.toLocaleString()," ctx (",c,"%)"]}):null,a!=null||i!=null?(0,t.jsxs)("span",{children:["· ↑",(a??0).toLocaleString()," ↓",(i??0).toLocaleString()]}):null,o!=null?(0,t.jsxs)("span",{children:["· $",o.toFixed(4)]}):null]}),e.detail?(0,t.jsx)("div",{children:e.detail}):null,l?(0,t.jsx)("div",{className:"h-1 w-full overflow-hidden rounded-full bg-border",children:(0,t.jsx)("div",{className:W("h-full rounded-full bg-(--status-agent-running)"),style:{width:`${c}%`}})}):null]})}r(UV,"TaskChatUsageReadout");function E3e(e){const s=e.details.find(n=>n.label==="Severity")?.value;return e.status==="failed"||s==="error"?"error":s==="info"?"info":"warning"}r(E3e,"providerNoticeSeverity");function xp(e,...s){return e.details.find(n=>s.includes(n.label))?.value}r(xp,"providerDetail");function wD(e){if(!(!e||Su(e)||/^tool(?:\s+|_)call\b/i.test(e)))return e}r(wD,"meaningfulToolDetail");function Lft(e){const s=e.summary??xp(e,"Query","URL","Target","Name","Reference","Reason","Summary");switch(e.family){case"research":{const n=xp(e,"Action")?.toLowerCase();return n==="open_page"?{icon:Yr,runningLabel:"Opening a web page",completedLabel:"Opened a web page",failedLabel:"Couldn’t open the web page",interruptedLabel:"Stopped opening the web page",detail:s}:n==="find_in_page"?{icon:Yr,runningLabel:"Searching the page",completedLabel:"Searched the page",failedLabel:"Page search failed",interruptedLabel:"Page search stopped",detail:s}:{icon:Yr,runningLabel:"Searching the web",completedLabel:"Searched the web",failedLabel:"Web search failed",interruptedLabel:"Web search stopped",detail:s}}case"tool_execution":{const n=xp(e,"Name"),a=xp(e,"Target"),i=xp(e,"Progress"),o=Nj({name:n,transport:xp(e,"Transport"),namespace:xp(e,"Namespace"),operation:xp(e,"Operation"),target:a,progress:i}),l=wD(e.summary)??wD(i)??wD(a),c=!!(l&&n&&Lk(l)===Lk(n)),d=n?MV(n)?.name??n:o.displayName,u=o.sourceLabel?`${o.sourceLabel} · ${d}`:n&&!Su(n)&&Lk(n)!==o.runningLabel.replace(/^Running /,"")?n:void 0;return{icon:o.icon,runningLabel:o.runningLabel,completedLabel:o.completedLabel,failedLabel:o.failedLabel,interruptedLabel:o.interruptedLabel,detail:[c?void 0:l,u].filter(Boolean).join(" · ")||void 0}}case"plan":return{icon:Hj,runningLabel:"Updating the plan",completedLabel:"Updated the plan",failedLabel:"Plan update failed",interruptedLabel:"Plan update stopped",detail:s};case"delegation":{const n=xp(e,"Action")?.toLowerCase();return n==="message"?{icon:Wo,runningLabel:"Messaging a subagent",completedLabel:"Messaged a subagent",failedLabel:"Subagent message failed",interruptedLabel:"Subagent message stopped",detail:s}:n==="resume"?{icon:Wo,runningLabel:"Resuming a subagent",completedLabel:"Resumed a subagent",failedLabel:"Couldn’t resume the subagent",interruptedLabel:"Subagent resume stopped",detail:s}:n==="close"?{icon:Wo,runningLabel:"Closing a subagent",completedLabel:"Closed a subagent",failedLabel:"Couldn’t close the subagent",interruptedLabel:"Subagent close stopped",detail:s}:n==="wait"?{icon:Wo,runningLabel:"Waiting for subagents",completedLabel:"Finished waiting for subagents",failedLabel:"Subagent wait failed",interruptedLabel:"Stopped waiting for subagents",detail:s}:{icon:Wo,runningLabel:"Starting a subagent",completedLabel:"Started a subagent",failedLabel:"Subagent start failed",interruptedLabel:"Subagent start stopped",detail:s}}case"model_identity":return e.eventType==="model.route.changed"?{icon:ao,runningLabel:"Switching models",completedLabel:"Switched models",failedLabel:"Model switch failed",interruptedLabel:"Model switch stopped",detail:s}:{icon:ao,runningLabel:"Verifying the model",completedLabel:"Verified the model",failedLabel:"Model verification failed",interruptedLabel:"Model verification stopped",detail:s};case"context":return{icon:d3,runningLabel:"Compacting context",completedLabel:"Compacted context",failedLabel:"Context compaction failed",interruptedLabel:"Context compaction stopped",detail:s};case"artifact":return e.eventType==="artifact.viewed"?{icon:D_,runningLabel:"Viewing an artifact",completedLabel:"Viewed an artifact",failedLabel:"Couldn’t view the artifact",interruptedLabel:"Artifact view stopped",detail:s}:{icon:D_,runningLabel:"Generating an artifact",completedLabel:"Generated an artifact",failedLabel:"Artifact generation failed",interruptedLabel:"Artifact generation stopped",detail:s};case"review":return xp(e,"State")?.toLowerCase()==="exited"?{icon:hte,runningLabel:"Leaving review mode",completedLabel:"Left review mode",failedLabel:"Couldn’t leave review mode",interruptedLabel:"Review-mode change stopped",detail:s}:{icon:hte,runningLabel:"Entering review mode",completedLabel:"Entered review mode",failedLabel:"Couldn’t enter review mode",interruptedLabel:"Review-mode change stopped",detail:s};case"hook":return{icon:Xi,runningLabel:"Running a hook",completedLabel:"Ran a hook",failedLabel:"Hook failed",interruptedLabel:"Hook stopped",detail:s};case"memory":return{icon:p2,runningLabel:"Checking memory",completedLabel:"Referenced memory",failedLabel:"Memory lookup failed",interruptedLabel:"Memory lookup stopped",detail:s};case"safety":return{icon:Bi,runningLabel:"Reviewing safety",completedLabel:"Reviewed safety",failedLabel:"Safety review failed",interruptedLabel:"Safety review stopped",detail:s};case"terminal":return{icon:bm,runningLabel:"Sending terminal input",completedLabel:"Sent terminal input",failedLabel:"Terminal input failed",interruptedLabel:"Terminal input stopped",detail:s};case"wait":return{icon:Au,runningLabel:"Waiting",completedLabel:"Finished waiting",failedLabel:"Wait failed",interruptedLabel:"Wait stopped",detail:s};case"provider_notice":return{icon:E3e(e)==="info"?s0:Es,runningLabel:"Provider notice",completedLabel:"Provider notice",failedLabel:"Provider error",interruptedLabel:"Provider notice",detail:s}}}r(Lft,"providerActivityPresentation$1");function Mft(e){const s=e.totals.files||e.files.length,n=s>0?`${s} ${s===1?"file":"files"}`:void 0;return{icon:RL,runningLabel:"Editing files",completedLabel:"Edited files",detail:n}}r(Mft,"workspaceChangePresentation");function Pft(e){return{icon:Za,runningLabel:"Referencing a file",completedLabel:"Referenced a file",detail:e.line==null?e.path:`${e.path}:${e.line}`}}r(Pft,"workspaceFilePresentation");function Dft(e){return{icon:e.resourceKind==="document"?Za:lN,runningLabel:"Saving a resource",completedLabel:e.resourceKind==="document"?"Added a document":"Added a deliverable",detail:e.title}}r(Dft,"resourcePresentation");function L3e(e){switch(e.surface){case"provider_activity":return Lft(e);case"workspace_change":return Mft(e);case"workspace_file":return Pft(e);case"resource":return Dft(e);case"runtime_request":case"run_result":case"run_terminal":return null}}r(L3e,"protocolActivityPresentation");function M3e(e){return e.surface==="provider_activity"?e.status==="running":e.surface==="workspace_change"?!e.complete:!1}r(M3e,"protocolActivityIsRunning");function $ft(e,s){return e.surface!=="provider_activity"?M3e(e)?s.runningLabel:s.completedLabel:e.status==="failed"?s.failedLabel??`${s.completedLabel} · failed`:e.status==="interrupted"?s.interruptedLabel??`${s.completedLabel} · interrupted`:e.status==="running"?s.runningLabel:s.completedLabel}r($ft,"protocolActivityLabel");var Oft={terminal:"Ran commands",grep:"Searched files",search:"Searched files",read:"Read files",edit:"Edited files",web:"Searched the web",plan:"Worked on a plan",question:"Requested input",agent:"Worked with agents",safety:"Reviewed safety",image:"Worked with images",wait:"Waited",mcp:"Used connected tools",other:"Used tools"};function Bft(e){const s=new Map,n=r((u,h,p=0)=>{const f=s.get(u);(!f||p<f.order)&&s.set(u,{label:u,icon:h,order:p})},"add"),a=[],i=[];for(const[u,h]of e.entries())if(h.kind==="tool"){const p=Nj({name:h.rawName??h.name,target:h.target});a.push({...p,order:u,completed:h.status==="completed"})}else if(h.kind==="protocol")if(h.surface==="provider_activity"&&h.family==="tool_execution"){const p=r(x=>h.details.find(g=>g.label===x)?.value,"value"),f=Nj({name:p("Name"),operation:p("Operation"),transport:p("Transport"),namespace:p("Namespace"),target:p("Target")});a.push({...f,order:u,completed:h.status==="completed"})}else{const p=L3e(h);if(!p)continue;if(h.surface==="provider_activity"&&h.family==="provider_notice"){const f=h.summary?.trim()||h.details.find(x=>x.label==="Summary")?.value.trim();i.push({summary:f,severity:E3e(h),icon:p.icon,order:u});continue}n({research:"Searched the web",plan:"Worked on a plan",delegation:"Worked with agents",artifact:"Worked with artifacts",context:"Managed context",memory:"Checked memory",model_identity:"Checked model settings",review:"Worked in review mode",hook:"Ran hooks",safety:"Reviewed safety",terminal:"Ran commands",wait:"Waited",workspace_change:"Worked on files",workspace_file:"Referenced files",resource:"Added resources"}[h.surface==="provider_activity"?h.family:h.surface]??"Used tools",p.icon,u)}if(i.length){const u=i.find(h=>h.severity==="error")??i.find(h=>h.severity==="warning")??i[0];n(i.length===1?u.summary||"Received a provider update":u.severity==="error"?"Provider error reported":u.severity==="warning"?"Provider warning reported":"Received provider updates",u.icon,u.severity==="info"?i[0].order:-1)}const o=new Set(a.filter(u=>u.completed).map(u=>u.family));for(const u of a){const h=o.has(u.family);n(u.family==="read"&&!h?"Checked files":u.family==="edit"&&!h?"Worked on files":Oft[u.family],u.icon,u.order)}s.size||(e.some(u=>u.kind==="thinking")?n("Thought through the task",Lx):e.some(u=>u.kind==="marker")?n("Activity stopped",Xd):n("Recorded usage",hW));const l=[...s.values()].sort((u,h)=>u.order-h.order),c=r(u=>u.map((h,p)=>p?h.charAt(0).toLowerCase()+h.slice(1):h).join(", "),"join"),d=c(l.map(u=>u.label));return{label:l.length>3?`${c(l.slice(0,2).map(u=>u.label))}, and more`:d,fullLabel:d,icon:l.length===1?l[0].icon:Vl}}r(Bft,"completedActivitySummary");var Xae=5,Fft=8;function zft(e,s=!1){return s&&(e==="blocked"||e==="failed")?(0,t.jsx)(xf,{className:"h-3 w-3 text-muted-foreground","aria-hidden":!0}):e==="in_progress"?(0,t.jsx)(st,{className:"h-3 w-3 animate-spin text-(--status-agent-running)","aria-hidden":!0}):e==="completed"?(0,t.jsx)(ms,{className:"h-3 w-3 text-(--status-task-icon-done)","aria-hidden":!0}):e==="blocked"||e==="failed"?(0,t.jsx)(Mn,{className:"h-3 w-3 text-destructive","aria-hidden":!0}):(0,t.jsx)(xf,{className:"h-3 w-3 text-muted-foreground","aria-hidden":!0})}r(zft,"stepStatusIcon");function P3e({details:e}){return e.length===0?null:(0,t.jsx)("dl",{className:"flex min-w-0 flex-col gap-1.5","data-testid":"task-chat-provider-detail-list",children:e.map(s=>(0,t.jsxs)("div",{className:"grid min-w-0 grid-cols-1 gap-0.5 sm:grid-cols-(--gtc-task-chat-details) sm:gap-3",children:[(0,t.jsx)("dt",{className:"text-muted-foreground",children:s.label}),(0,t.jsx)("dd",{className:W("min-w-0 break-words text-foreground",s.mono&&"font-mono"),children:s.value})]},`${s.label}:${s.value}`))})}r(P3e,"DetailList");function qft(e){try{return new URL(e).hostname.replace(/^www\./,"")}catch{return e}}r(qft,"sourceHostname");function Uft({item:e}){const[s,n]=(0,m.useState)(!1),a=e.details.find(c=>c.label.toLowerCase()==="query"),i=e.details.filter(c=>!["action","query","status"].includes(c.label.toLowerCase())),o=s?e.links:e.links.slice(0,Xae),l=e.links.length-o.length;return(0,t.jsxs)("div",{className:"flex min-w-0 flex-col gap-2.5",children:[a?(0,t.jsxs)("div",{className:"min-w-0 rounded-sm bg-muted/40 px-2.5 py-2","data-testid":"task-chat-research-query",children:[(0,t.jsx)("p",{className:"text-(length:--text-nano) font-medium uppercase tracking-wide text-muted-foreground",children:"Query"}),(0,t.jsx)("p",{className:"mt-0.5 min-w-0 break-words font-mono text-(length:--text-micro) text-foreground",children:a.value})]}):null,e.links.length>0?(0,t.jsxs)("div",{className:"min-w-0",children:[(0,t.jsxs)("p",{className:"mb-1 text-(length:--text-nano) font-medium uppercase tracking-wide text-muted-foreground",children:[e.links.length," ",e.links.length===1?"result":"results"]}),(0,t.jsx)("ol",{className:"divide-y divide-border/60","aria-label":"Research sources",children:o.map((c,d)=>(0,t.jsxs)("li",{className:"min-w-0 py-1.5 first:pt-0 last:pb-0",children:[(0,t.jsxs)("a",{className:"flex min-w-0 items-center gap-1 font-medium text-foreground hover:underline",href:c.href,target:"_blank",rel:"noreferrer",children:[(0,t.jsx)("span",{className:"truncate",children:c.label}),(0,t.jsx)($n,{className:"h-3 w-3 shrink-0","aria-hidden":!0})]}),(0,t.jsxs)("p",{className:"mt-0.5 flex min-w-0 gap-2 text-muted-foreground",children:[(0,t.jsx)("span",{className:"shrink-0",children:qft(c.href)}),c.description?(0,t.jsx)("span",{className:"min-w-0 truncate",children:c.description}):null]})]},`${c.href}:${d}`))}),l>0?(0,t.jsxs)("button",{type:"button",className:"mt-1.5 text-muted-foreground hover:text-foreground",onClick:r(()=>n(!0),"onClick"),children:["Show ",l," more ",l===1?"result":"results"]}):s&&e.links.length>Xae?(0,t.jsx)("button",{type:"button",className:"mt-1.5 text-muted-foreground hover:text-foreground",onClick:r(()=>n(!1),"onClick"),children:"Show fewer results"}):null]}):null,(0,t.jsx)(P3e,{details:i}),e.output||e.outputTruncated?(0,t.jsx)("p",{className:"text-muted-foreground",children:"Additional provider output is available in Runner Inspector."}):null]})}r(Uft,"ResearchDetails");function Kft({item:e,neutral:s=!1}){return e.family==="research"?(0,t.jsx)(Uft,{item:e}):(0,t.jsxs)("div",{className:"flex min-w-0 flex-col gap-2",children:[e.steps.length>0?(0,t.jsx)("ol",{className:"flex flex-col gap-1","aria-label":"Plan steps",children:e.steps.map(n=>(0,t.jsxs)("li",{className:"flex min-w-0 items-start gap-2",children:[(0,t.jsx)("span",{className:"mt-0.5 shrink-0",children:zft(n.status,s)}),(0,t.jsx)("span",{className:W("min-w-0",n.status==="completed"&&"text-muted-foreground line-through"),children:n.label})]},n.id))}):null,e.links.length>0?(0,t.jsx)("ul",{className:"flex flex-col gap-1.5","aria-label":"Research sources",children:e.links.map(n=>(0,t.jsxs)("li",{children:[(0,t.jsxs)("a",{className:"inline-flex min-w-0 items-center gap-1 font-medium text-primary hover:underline",href:n.href,target:"_blank",rel:"noreferrer",children:[(0,t.jsx)("span",{className:"truncate",children:n.label}),(0,t.jsx)($n,{className:"h-3 w-3 shrink-0","aria-hidden":!0})]}),n.description?(0,t.jsx)("p",{className:"mt-0.5 text-muted-foreground",children:n.description}):null]},n.href))}):null,e.children.length>0?(0,t.jsx)("ul",{className:"flex flex-col gap-1.5","aria-label":"Delegated agents",children:e.children.map(n=>(0,t.jsxs)("li",{className:"flex min-w-0 flex-col gap-0.5",children:[(0,t.jsxs)("span",{className:"flex min-w-0 items-center gap-2",children:[(0,t.jsx)("span",{className:"font-medium text-foreground",children:n.title}),(0,t.jsx)("span",{className:"capitalize text-muted-foreground",children:n.status}),n.metadata?(0,t.jsx)("span",{className:"min-w-0 truncate font-mono text-(length:--text-micro)",children:n.metadata}):null]}),n.summary?(0,t.jsx)("span",{className:"text-muted-foreground",children:n.summary}):null]},n.id))}):null,e.details.length>0?(0,t.jsx)(P3e,{details:e.details}):null,e.output?(0,t.jsx)("pre",{className:"max-h-(--sz-64) overflow-auto whitespace-pre-wrap rounded-sm bg-muted/50 p-2 font-mono text-(length:--text-micro) text-foreground",children:e.output}):null,e.outputTruncated?(0,t.jsx)("p",{className:"text-muted-foreground",children:"Output truncated to 8 KiB."}):null]})}r(Kft,"ProviderDetails");function Qft({item:e}){if(e.files.length===0)return(0,t.jsx)("p",{className:"text-muted-foreground",children:"No changed-file details were reported."});const s=e.files.slice(0,Fft),n=e.files.length-s.length;return(0,t.jsxs)("div",{className:"min-w-0","data-testid":"task-chat-workspace-change-details",children:[(0,t.jsx)("ul",{className:"flex min-w-0 flex-col divide-y divide-border/60","aria-label":"Changed files",children:s.map(a=>(0,t.jsxs)("li",{className:"flex min-w-0 items-center gap-2 py-1.5 first:pt-0 last:pb-0",children:[(0,t.jsx)("span",{className:"min-w-0 flex-1 truncate font-mono text-foreground",title:a.previousPath?`${a.previousPath} → ${a.path}`:a.path,children:a.previousPath?`${a.previousPath} → ${a.path}`:a.path}),(0,t.jsx)("span",{className:"shrink-0 capitalize text-muted-foreground",children:a.operation.replaceAll("_"," ")}),a.additions!=null||a.deletions!=null?(0,t.jsxs)("span",{className:"shrink-0 font-mono text-(length:--text-micro) text-muted-foreground",children:[a.additions==null?"":`+${a.additions}`," ",a.deletions==null?"":`−${a.deletions}`]}):null]},`${a.operation}:${a.path}`))}),n>0?(0,t.jsxs)("p",{className:"mt-1.5 text-muted-foreground",children:[n," more ",n===1?"file":"files"," not shown"]}):null]})}r(Qft,"WorkspaceChangeDetails");function Wft({item:e}){const s={path:e.path,resourceKind:"file",line:e.line,column:null,raw:e.path};return(0,t.jsxs)("div",{className:"flex min-w-0 flex-col gap-2",children:[(0,t.jsx)(Mve,{workspaceFileRef:s,label:e.path}),e.preview?e.presentation==="document"?(0,t.jsx)("div",{className:"max-h-(--sz-64) overflow-auto rounded-sm bg-muted/30 p-2 text-foreground",children:(0,t.jsx)(An,{children:e.preview})}):(0,t.jsx)("pre",{className:"max-h-(--sz-64) overflow-auto whitespace-pre-wrap rounded-sm bg-muted/50 p-2 font-mono text-(length:--text-micro) text-foreground",children:e.preview}):(0,t.jsx)("p",{className:"text-muted-foreground",children:"Preview unavailable."}),e.previewTruncated?(0,t.jsx)("p",{className:"text-muted-foreground",children:"Preview truncated by the runner."}):null]})}r(Wft,"WorkspaceFileDetails");function D3e(e,s=!1){switch(e.surface){case"provider_activity":return e.details.length>0||e.steps.length>0||e.links.length>0||e.children.length>0||e.output||e.outputTruncated?(0,t.jsx)(Kft,{item:e,neutral:s}):null;case"workspace_change":return(0,t.jsx)(Qft,{item:e});case"workspace_file":return(0,t.jsx)(Wft,{item:e});case"resource":case"runtime_request":case"run_result":case"run_terminal":return null}}r(D3e,"detailContent");function $3e(e){if(e)try{const s=new URL(e,"https://paperclip.invalid");return s.protocol==="https:"||s.protocol==="http:"?e:void 0}catch{return}}r($3e,"safeActivityHref");function Hft(e){return e.surface==="resource"?!!$3e(e.href):D3e(e)!==null||e.surface==="provider_activity"&&!!e.summary?.trim()}r(Hft,"hasTaskChatProtocolActivityDetails");function Vft({item:e,neutral:s=!1}){const n=D3e(e,s);if(e.surface==="resource"){const a=$3e(e.href);return a?(0,t.jsx)("a",{href:a,className:"text-foreground underline",children:e.title}):(0,t.jsx)("p",{children:e.title})}return(0,t.jsxs)(t.Fragment,{children:[e.surface==="provider_activity"&&e.summary?(0,t.jsx)("p",{className:"whitespace-pre-wrap break-words",children:e.summary}):null,n]})}r(Vft,"TaskChatProtocolActivityDetails");function O3e(e,s){if(e.kind==="tool"){const d=Nj({name:e.rawName??e.name,target:e.target}),u=s&&(e.status==="pending"||e.status==="in_progress");return{icon:d.icon,label:e.status==="failed"?d.failedLabel:e.status==="interrupted"?d.interruptedLabel:u?d.runningLabel:d.completedLabel,target:e.target,mono:!0,running:u}}if(e.kind==="thinking"){const d=s&&!!e.streaming;return{icon:Lx,label:d?"Thinking":"Thought",target:e.lines.filter(u=>u.trim()).at(-1)?.trim(),mono:!1,running:d}}if(e.kind==="protocol"){const d=L3e(e);return d?{icon:d.icon,label:$ft(e,d),target:d.detail,mono:!0,running:s&&M3e(e)}:null}if(e.kind==="marker")return{icon:Xd,label:e.label,target:e.detail,mono:!1,running:!1};const{used:n,size:a,inputTokens:i,outputTokens:o,costUsd:l}=e.usage,c=[a>0?`${n.toLocaleString()}/${a.toLocaleString()} ctx`:void 0,i!=null||o!=null?`↑${(i??0).toLocaleString()} ↓${(o??0).toLocaleString()}`:void 0,l!=null?`$${l.toFixed(4)}`:void 0].filter(Boolean).join(" · ");return{icon:hW,label:e.label??"Token usage",target:c||e.detail,mono:!1,running:!1}}r(O3e,"presentation");function Gft({item:e,active:s}){const n=O3e(e,s);if(!n)return null;const a=n.icon;return(0,t.jsxs)("span",{className:"flex min-w-0 flex-1 items-center gap-2","data-activity-row":e.id,"data-activity-family":e.kind==="protocol"?e.surface==="provider_activity"?e.family:e.surface:void 0,children:[(0,t.jsx)("span",{className:"flex size-5 shrink-0 items-center justify-center","data-activity-icon":!0,children:(0,t.jsx)(a,{className:"size-3.5","aria-hidden":"true"})}),(0,t.jsxs)("span",{className:"flex min-w-0 flex-1 items-center gap-2 overflow-hidden whitespace-nowrap",children:[(0,t.jsx)("span",{className:W("max-w-full shrink-0 truncate text-xs",n.running&&"text-foreground"),children:n.label}),n.target?(0,t.jsx)("span",{title:n.target,className:W("truncate text-xs text-muted-foreground",n.mono&&"font-mono"),children:n.target}):null]})]})}r(Gft,"ActivityContent");function Yft({item:e}){return e.kind==="thinking"?(0,t.jsx)(An,{softBreaks:!0,children:e.lines.join(`
384
384
  `)}):e.kind==="usage"?(0,t.jsx)(UV,{item:e}):e.kind==="protocol"?(0,t.jsx)(Vft,{item:e,neutral:!0}):e.kind==="marker"?(0,t.jsx)("p",{className:"whitespace-pre-wrap break-words",children:e.detail??e.label}):(0,t.jsxs)(t.Fragment,{children:[e.target?(0,t.jsx)("p",{className:"break-all font-mono",children:e.target}):null,e.detail?(0,t.jsx)("pre",{className:"whitespace-pre-wrap break-words font-mono",children:e.detail}):null,e.decision?(0,t.jsxs)("p",{children:["Permission ",e.decision]}):null,e.diff?(0,t.jsxs)("p",{className:"break-all font-mono",children:[e.diff.path," · +",e.diff.added," −",e.diff.removed]}):null]})}r(Yft,"ActivityDetails");function Zft(e){return e.kind==="protocol"?Hft(e):e.kind==="thinking"?e.lines.some(s=>s.trim()):e.kind==="tool"?!!(e.target?.trim()||e.detail?.trim()||e.diff||e.decision):e.kind==="marker"?!!e.detail?.trim():!!(e.detail||e.usage.size>0||e.usage.inputTokens!=null||e.usage.outputTokens!=null||e.usage.costUsd!=null)}r(Zft,"hasActivityDetails");var Jft=24;function Xft(e){const s=(0,m.useRef)(null),n=(0,m.useRef)(e),a=(0,m.useRef)(0),i=(0,m.useCallback)(()=>{const l=s.current;l&&(n.current=!0,l.scrollTop=l.scrollHeight,a.current=l.scrollTop)},[]),o=(0,m.useCallback)(()=>{const l=s.current;if(!l)return;const c=l.scrollTop,d=c-a.current;if(a.current=c,d<-24){n.current=!1;return}d>0&&l.scrollHeight-c-l.clientHeight<=Jft&&(n.current=!0)},[]);return(0,m.useLayoutEffect)(()=>{e&&i()},[e,i]),(0,m.useEffect)(()=>{const l=s.current;if(!l||typeof ResizeObserver>"u")return;const c=new ResizeObserver(()=>{n.current&&(l.scrollTop=l.scrollHeight,a.current=l.scrollTop)});for(const d of l.children)c.observe(d);return()=>c.disconnect()},[]),{ref:s,onScroll:o}}r(Xft,"useFollowDetailBottom");var ext=new Set;function B3e(e){return e.items.filter(s=>O3e(s,!1)!==null)}r(B3e,"visibleActivities");function KV(e){const s=e.flatMap(n=>B3e(n).map(a=>a.id));return new Set(s.slice(-3))}r(KV,"newestActivityIds");function F3e({item:e,active:s,auto:n,current:a=!1}){const[i,o]=TM(`runner-detail:${e.id}`,n),[l,c]=(0,m.useState)(i),d=Xft(i&&a===!0);i&&!l&&c(!0);const u=(0,m.useId)(),h=Zft(e),p=(0,t.jsx)(Gft,{item:e,active:s});return(0,t.jsxs)("li",{className:"min-w-0","data-activity-item-id":e.id,"data-activity-open":h?i:void 0,"data-testid":a?"task-chat-activity-current":void 0,children:[h?(0,t.jsxs)("button",{type:"button",className:"flex h-8 w-full min-w-0 items-center gap-2 rounded-sm text-left text-muted-foreground hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring",onClick:r(()=>o(!i),"onClick"),"aria-expanded":i,"aria-controls":l?u:void 0,children:[p,(0,t.jsx)(Ln,{className:W("size-3.5 shrink-0",i&&"rotate-90"),"aria-hidden":"true"})]}):(0,t.jsx)("div",{className:"flex h-8 w-full min-w-0 items-center gap-2 text-muted-foreground",children:p}),h&&l?(0,t.jsx)("div",{id:u,hidden:!i,ref:d.ref,onScroll:d.onScroll,className:"flex max-h-(--sz-64) min-w-0 flex-col gap-2 overflow-y-auto rounded-md bg-muted/40 p-3 text-xs leading-relaxed text-muted-foreground [&>*]:shrink-0","data-testid":"task-chat-runner-activity-detail",children:(0,t.jsx)("div",{className:"flex min-w-0 flex-col gap-2","data-testid":"task-chat-runner-activity-body",children:(0,t.jsx)(Yft,{item:e})})}):null]})}r(F3e,"ExpandedActivity");function txt({phaseId:e,activities:s,openIds:n,active:a}){const[i,o]=TM(`runner-earlier:${e}`,!1),l=(0,m.useId)(),c=s.at(-1),d=s.filter(h=>!n.has(h.id)).length,u=s.filter(h=>i||n.has(h.id));return(0,t.jsxs)("div",{className:"flex min-w-0 flex-col gap-1",children:[d>0?(0,t.jsxs)("button",{type:"button",className:"flex h-8 w-full min-w-0 items-center gap-2 rounded-sm text-left text-xs text-muted-foreground hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring","data-testid":"task-chat-activity-earlier-toggle",onClick:r(()=>o(!i),"onClick"),"aria-expanded":i,"aria-controls":l,children:[(0,t.jsx)("span",{className:"flex size-5 shrink-0 items-center justify-center",children:(0,t.jsx)(Ln,{className:W("size-3.5",i&&"rotate-90"),"aria-hidden":"true"})}),(0,t.jsx)("span",{children:i?`Hide ${d} earlier`:`+${d} earlier`})]}):null,(0,t.jsx)("ol",{id:l,className:"flex min-w-0 flex-col gap-1","aria-label":"Activity history","data-testid":"task-chat-runner-activity-list",children:u.map(h=>(0,t.jsx)(F3e,{item:h,active:a&&h===c,auto:n.has(h.id),current:h===c},h.id))})]})}r(txt,"LiveActivities");function sxt({phaseId:e,activities:s}){const[n,a]=TM(e,!1),i=(0,m.useId)(),o=Bft(s),l=o.icon,c=`${s.length} ${s.length===1?"activity":"activities"}`;return(0,t.jsxs)("div",{className:"min-w-0",children:[(0,t.jsxs)("button",{type:"button",className:"flex min-h-8 w-full min-w-0 items-center gap-2 rounded-sm text-left text-muted-foreground hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring","data-testid":"task-chat-activity-phase-toggle",onClick:r(()=>a(!n),"onClick"),"aria-expanded":n,"aria-controls":n?i:void 0,"aria-label":`${n?"Collapse":"Expand"} ${o.fullLabel.toLowerCase()} (${c})`,children:[(0,t.jsxs)("span",{className:"flex h-8 min-w-0 flex-1 items-center gap-2 text-xs","data-completed-summary":!0,children:[(0,t.jsx)("span",{className:"flex size-5 shrink-0 items-center justify-center",children:(0,t.jsx)(l,{className:"size-3.5","aria-hidden":"true"})}),(0,t.jsx)("span",{className:"truncate",title:o.fullLabel,children:o.label})]}),(0,t.jsxs)("span",{className:"flex shrink-0 items-center gap-1 text-xs",children:[n?c:null,(0,t.jsx)(Ln,{className:W("size-3.5",n&&"rotate-90"),"aria-hidden":"true"})]})]}),n?(0,t.jsx)("ol",{id:i,className:"flex min-w-0 flex-col gap-1","aria-label":"Activity history","data-testid":"task-chat-runner-activity-list",children:s.map(d=>(0,t.jsx)(F3e,{item:d,active:!1,auto:!1},d.id))}):null]})}r(sxt,"SettledActivities");function N5({item:e,openActivityIds:s}){const n=B3e(e),a=s??(e.active?KV([e]):ext),i=n.some(o=>a.has(o.id));return(0,t.jsxs)("section",{className:"flex min-w-0 flex-col gap-2","data-testid":"task-chat-activity-phase","data-activity-group":e.id,"data-activity-mode":i?"live":"settled",children:[e.interstitial?(0,t.jsx)("div",{className:"min-w-0 px-1 text-sm text-foreground/90","data-testid":"task-chat-phase-interstitial",children:(0,t.jsx)(An,{softBreaks:!0,linkIssueReferences:!0,children:e.interstitial.text})}):null,i?(0,t.jsx)(txt,{phaseId:e.id,activities:n,openIds:a,active:e.active}):n.length>0?(0,t.jsx)(sxt,{phaseId:e.id,activities:n}):null]})}r(N5,"TaskChatRunnerActivityGroup");var nxt=new Set(["failed","timed_out","cancelled","interrupted","succeeded"]);function Xy(e){return e!=null&&nxt.has(e)}r(Xy,"isTerminalRunStatus$1");function eie(e,s,n){const a=[...new Set(n.filter(Number.isFinite))].sort((i,o)=>i-o);return a.length===0?[{startMs:s,endMs:Number.POSITIVE_INFINITY,entries:[...e]}]:[s,...a].map((i,o)=>{const l=a[o]??Number.POSITIVE_INFINITY;return{startMs:i,endMs:l,entries:e.filter(c=>{const d=Date.parse(c.ts),u=Number.isFinite(d)?d:0;return(o===0||u>=i)&&u<l})}})}r(eie,"splitTranscriptAtAnchors");function rxt(e){return e.replace(/```[a-z]*\n?/gi," ").replace(/`/g,"").replace(/^#{1,6}\s+/gm,"").replace(/^\s*[-*+]\s+/gm,"").replace(/^\s*>\s?/gm,"").replace(/!?\[([^\]]*)\]\(([^)]*)\)/g,"$1").replace(/\*+/g,"").replace(/__/g,"").replace(/\s+/g," ").trim()}r(rxt,"flattenSelfTalk");function axt(e){return e==="add"?"add":e==="remove"?"remove":"context"}r(axt,"diffKind");var ixt=["file_path","path","notebook_path","command","pattern","query","url","prompt","description","skill","subject"],_C=96,oxt=/^xd:\/\/([A-Za-z0-9_]+)$/,lxt={resolve:!0,reject:!0,propose:!0,report_issue:!0};function cxt(e){if(typeof e!="string")return null;const s=oxt.exec(e.trim());return s?s[1]in lxt?null:s[1]:null}r(cxt,"xdDeviceFromPath");function dxt(e,s){if(e?.trim()!=="write"||s==null||typeof s!="object")return null;const n=s,a=cxt(n.path);return a||(typeof n.path=="string"||!("content"in n)?null:mxt(n.content))}r(dxt,"xdDeviceToolName");var uxt=/"code"\s*:\s*"[\s\S]{0,400}?omp\./;function mxt(e){return typeof e!="string"?null:uxt.test(e)?"fabric_exec":null}r(mxt,"fabricDeviceFromPayload");function hb(e,s){const n=e.replace(/\s+/g," ").trim();return n.length>s?`${n.slice(0,s-1)}…`:n}r(hb,"clip");function hxt(e){if(e==null)return;if(typeof e=="string")return e.trim()?hb(e,_C):void 0;if(typeof e!="object")return hb(String(e),_C);const s=e;for(const a of ixt){const i=s[a];if(typeof i=="string"&&i.trim())return hb(i,_C)}const n=Object.entries(s).filter(([a,i])=>(typeof i=="string"||typeof i=="number"||typeof i=="boolean")&&a!=="text"&&a!=="status");if(n.length!==0)return hb(n.map(([a,i])=>`${a}: ${String(i)}`).join(", "),_C)}r(hxt,"summarizeToolInput$2");function kD(e){const s=(e??"").trim();return Su(s)?"Unnamed tool":Lk(s)}r(kD,"toolDisplayName");function pxt(e,s){if(!e)return;const n=Date.parse(e),a=Date.parse(s);if(!Number.isFinite(n)||!Number.isFinite(a))return;const i=Math.round((a-n)/1e3);if(!(i<1))return i<60?`Thought for ${i}s`:`Thought for ${Math.floor(i/60)}m ${i%60}s`}r(pxt,"thoughtDurationLabel");function fxt(e,s,n){const a=s.split(`
385
385
  `);if(!n||e.length===0){e.push(...a);return}e[e.length-1]=`${e[e.length-1]??""}${a[0]??""}`,e.push(...a.slice(1))}r(fxt,"appendThinkingText");var tie=600,u_=8192;function BI(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)?e:{}}r(BI,"objectRecord");function od(e){return typeof e=="string"&&e.trim().length>0?e.trim():void 0}r(od,"stringValue");function xxt(e){if(typeof e=="string"&&e.trim())return e.trim();if(typeof e=="number"&&Number.isFinite(e))return String(e);if(typeof e=="boolean")return e?"Yes":"No"}r(xxt,"scalarValue");function gxt(e){return e.replace(/([a-z0-9])([A-Z])/g,"$1 $2").replaceAll("_"," ").replace(/\b\w/g,s=>s.toUpperCase())}r(gxt,"titleCaseKey$1");function bxt(e){const s=od(e);if(!s)return null;try{const n=new URL(s);return n.protocol==="http:"||n.protocol==="https:"?s:null}catch{return null}}r(bxt,"safeHttpHref");var vxt={plan:["revision","syncStatus","documentRevision","complete"],tool_execution:["transport","operation","name","target","namespace","readOnly","status","progress","durationMs","exitCode","outputBytes"],research:["action","status","query","pattern","url"],delegation:["action","status"],model_identity:["provider","requestedModel","fromModel","effectiveModel","reason","status","buffering","summary"],context:["reason","preTokens","postTokens","sameSession"],artifact:["status","reference","mediaType","title","registered","transparentBackground","failure"],review:["state","scope"],hook:["event","scope","status","blocking","durationMs","summary"],memory:["label","available","reference"],safety:["status","decision","targetExecutionId","summary"],terminal:["origin","inputClass","byteCount"],wait:["reason","status","plannedDurationMs","elapsedDurationMs"],provider_notice:["severity","category","scope","recoverable","userActionable","summary"]};function z3e(e){for(const s of["planId","executionId","researchId","delegationId","routeId","verificationId","compactionId","artifactId","reviewId","hookId","citationId","waitId","noticeId"]){const n=od(e.payload[s]);if(n)return`${e.family}:${n}`}return`${e.family}:${e.eventType}:${e.ts}`}r(z3e,"providerActivityKey");function yxt(e,s,n){const a=[];for(const h of vxt[e.family]){const p=xxt(e.payload[h]);p&&(e.family==="tool_execution"&&h==="name"&&Su(p)||e.family==="tool_execution"&&h==="progress"&&!eq(p)||a.push({label:gxt(h),value:hb(p,e.family==="provider_notice"&&(h==="summary"||h==="message")?4e3:h==="message"||h==="summary"||h==="reason"?320:160),mono:/(?:id|model|target|reference|url|code|bytes)$/i.test(h)}))}if(e.family==="provider_notice"&&Array.isArray(e.payload.details))for(const h of e.payload.details.slice(0,64)){const p=BI(h);typeof p.name=="string"&&typeof p.value=="string"&&a.push({label:hb(p.name,160),value:hb(p.value,4e3),mono:!1})}const i=e.family==="plan"&&Array.isArray(e.payload.steps)?e.payload.steps.map(BI).slice(0,256).map((h,p)=>{const f=od(h.status),x=f==="in_progress"||f==="completed"||f==="blocked"?f:"pending";return{id:od(h.stepId)??`${s}:plan-step:${p}`,label:od(h.body)??"Plan step",status:x}}):[],o=e.family==="research"&&Array.isArray(e.payload.sources)?e.payload.sources.map(BI).slice(0,64).flatMap(h=>{const p=bxt(h.url);return p?[{label:od(h.title)??p,href:p,description:od(h.snippet)}]:[]}):[],l=e.family==="delegation"&&Array.isArray(e.payload.children)?e.payload.children.map(BI).slice(0,64).map((h,p)=>({id:od(h.childId)??`${s}:delegation:${p}`,title:od(h.role)??"Subagent",status:od(h.status)??"unknown",metadata:[od(h.model),od(h.activitySummary)].filter(Boolean).join(" · ")||void 0,summary:od(h.summary)})):[],c=e.family==="tool_execution"?od(e.payload.output):void 0,d=e.payload.outputTruncated===!0||!!(c&&c.length>u_),u=e.summary&&e.summary!==e.eventType?e.summary:od(e.payload.explanation)??od(e.payload.progress)??od(e.payload.message)??od(e.payload.summary);return{id:`${s}:provider:${z3e(e)}:${n}`,kind:"protocol",surface:"provider_activity",family:e.family,eventType:e.eventType,status:e.status,title:e.title,summary:u,details:a,steps:i,links:o,children:l,output:c?c.slice(0,u_):void 0,outputTruncated:d,transcriptIndex:n}}r(yxt,"providerActivityItem");function yu(e,s){return e.details.find(n=>n.label===s)?.value}r(yu,"providerItemDetail");function eq(e){return!!(e&&!Su(e)&&!/^tool(?:\s+|_)call\b/i.test(e))}r(eq,"meaningfulProviderToolSummary");function jxt(e,s){if(e.family!=="tool_execution"||s.family!=="tool_execution")return{...s,id:e.id};const n=new Map(e.details.map(l=>[l.label,l])),a=yu(s,"Name"),i=Su(a),o=new Set(["Name","Transport","Namespace","Operation","Target"]);for(const l of s.details)o.has(l.label)&&i&&n.has(l.label)||l.label==="Progress"&&!eq(l.value)&&n.has("Progress")||n.set(l.label,l);return{...s,id:e.id,summary:eq(s.summary)?s.summary:e.summary,details:[...n.values()]}}r(jxt,"mergeProviderActivityItem");function wxt(e){if(e==null)return;const s=(typeof e=="string"?e:String(e)).trim();if(s)return s.length>tie?`${s.slice(0,tie)}
@@ -703,7 +703,7 @@ Last resolved: user values resolve per member`;return(0,t.jsxs)("div",{role:"row
703
703
 
704
704
  Review the **original** file.`,markdown:!0,downloadUrl:"data:text/markdown,%23%20Project%20notes"}),(0,t.jsx)(kU,{title:"notes.txt",text:"Plain text stays literal: <example>",markdown:!1,downloadUrl:"data:text/plain,Plain%20text"})]})]}),(0,t.jsxs)(kr,{title:"Connection recovery",children:[(0,t.jsx)(tr,{title:"Waiting for server",children:(0,t.jsx)(w6,{temporary:!0,retrying:!1,onRetry:r(()=>{},"onRetry")})}),(0,t.jsx)(tr,{title:"Checking connection",children:(0,t.jsx)(w6,{temporary:!0,retrying:!0,onRetry:r(()=>{},"onRetry")})}),(0,t.jsx)(tr,{title:"Access check failed",children:(0,t.jsx)(w6,{temporary:!1,retrying:!1,onRetry:r(()=>{},"onRetry")})})]}),(0,t.jsxs)(kr,{title:"Browser session footer",children:[(0,t.jsx)("p",{className:"text-sm text-muted-foreground",children:"Fit to pane follows the visible panel. Fixed viewport presets and session actions live in the footer menu. Costs stay in task reporting. The idle countdown appears only in the final five minutes. Full panel, activity, and settings states are in Storybook under Browser Use."}),["running","idle","closing-soon","closed"].map(O=>(0,t.jsx)(tr,{title:O==="closing-soon"?"Closing soon":O,children:(0,t.jsx)(GEe,{browser:{id:"design-browser",sessionId:"design-session",issueId:"design-task",status:O==="closing-soon"?"idle":O,runStatus:"completed",progress:null,error:null,costCents:15,idleDeadline:new Date(O==="closing-soon"?282e3:6e5).toISOString(),expiresAt:null,createdAt:new Date(0).toISOString()},now:0,onControl:r(()=>{},"onControl"),onReconnect:r(()=>{},"onReconnect"),onResize:r(()=>{},"onResize")})},O))]}),(0,t.jsxs)(kr,{title:"Browser activity in the task feed",children:[(0,t.jsx)("p",{className:"text-sm text-muted-foreground",children:"Each browser appears once at its opening time among the task messages. Its status updates in place; the action opens its side-panel tab."}),["starting","running","idle","closed","failed"].map(O=>(0,t.jsx)(tr,{title:O,children:(0,t.jsx)(n3e,{browser:{id:`design-${O}`,sessionId:`design-${O}`,issueId:"design-task",status:O,runStatus:"completed",progress:null,error:null,costCents:0,idleDeadline:null,expiresAt:null,createdAt:new Date(0).toISOString()},onOpen:r(()=>{},"onOpen")})},O))]}),(0,t.jsxs)(kr,{title:"Media artifacts",children:[(0,t.jsx)("p",{className:"text-sm text-muted-foreground",children:"Images and videos use gallery tiles. The whole tile opens the task gallery; files and links keep compact, fully clickable rows. Task/Artifact Gallery in Storybook covers playable videos, mixed files, narrow panels, and unavailable previews."}),(0,t.jsxs)("div",{className:"grid max-w-2xl grid-cols-1 gap-3 sm:grid-cols-2",children:[(0,t.jsx)(rq,{id:"design-image",title:"Launch artwork",contentPath:"/announcement-preview.svg",contentType:"image/svg+xml",originalFilename:"launch.svg",detail:"Image"}),(0,t.jsx)(rq,{id:"design-video",title:"Video preview unavailable",contentPath:"",contentType:"video/mp4",originalFilename:"preview.mp4",detail:"Video"})]})]}),(0,t.jsx)(kr,{title:"AI Connections",children:(0,t.jsx)(X0s,{})}),(0,t.jsxs)(kr,{title:"Built-in Agent Lifecycle Chips",children:[(0,t.jsxs)("p",{className:"text-sm text-muted-foreground",children:["A derived lifecycle chip (amber) for attention states. The lifecycle chip is separate from the agent status vocabulary and only shows for"," ",(0,t.jsx)("span",{className:"font-mono",children:"needs_setup"})," / ",(0,t.jsx)("span",{className:"font-mono",children:"pending_approval"}),"."]}),(0,t.jsxs)("div",{className:"flex flex-wrap items-center gap-4",children:[(0,t.jsx)(kk,{status:"needs_setup"}),(0,t.jsx)(kk,{status:"pending_approval"}),(0,t.jsx)(kk,{status:"needs_setup",compact:!0})]}),(0,t.jsxs)("p",{className:"mt-3 text-sm text-muted-foreground",children:[(0,t.jsx)("span",{className:"font-mono",children:"<BuiltInAgentGate agentKey>"})," composes"," ",(0,t.jsx)("span",{className:"font-mono",children:"PageSkeleton"})," + ",(0,t.jsx)("span",{className:"font-mono",children:"EmptyState"})," ","+ ",(0,t.jsx)("span",{className:"font-mono",children:"InlineBanner"})," to render the loading / setup / pending-approval / paused / ready states of a feature that depends on a built-in agent."]})]})]})}r(Bps,"DesignGuide");function Fps(){const e=[{path:".agents/review/SKILL.md",name:"Review",description:"Review changes before release.",error:null,inspection:{requirements:null,references:[],warnings:[],files:[{path:"SKILL.md",kind:"skill",sizeBytes:120,encoding:"utf8",executable:!1},{path:"scripts/check.sh",kind:"script",sizeBytes:45,encoding:"utf8",executable:!0}]}},{path:".agents/review/nested/SKILL.md",name:"Nested skill",description:"An independently selected package.",error:null,note:"New skill"},{path:"broken/SKILL.md",name:"Needs attention",description:null,error:"Missing required description."}],[s,n]=(0,m.useState)(new Set(e.map(o=>o.path))),[a,i]=(0,m.useState)([]);return(0,t.jsx)($Pe,{candidates:e,selected:s,excludedFolders:a,onChange:r((o,l)=>{n(o),i(l)},"onChange")})}r(Fps,"SkillSourceTreeShowcase");function zps(e,s){return e?.enableWorktreeRunExecution!==!0?{kind:"off"}:e.worktreeRunExecutionActivatedAt?s?e.worktreeRunExecutionActivationInstanceId!==s?{kind:"fail_closed",reason:"instance_mismatch"}:{kind:"armed",activatedAt:e.worktreeRunExecutionActivatedAt}:{kind:"fail_closed",reason:"missing_instance_id"}:{kind:"fail_closed",reason:"missing_cutoff"}}r(zps,"resolveWorktreeRunExecutionDisplayState");function qps(e){const s=new Date(e);return Number.isNaN(s.getTime())?e:s.toLocaleString(void 0,{dateStyle:"medium",timeStyle:"short"})}r(qps,"formatActivationTimestamp");function T9e(){return(0,t.jsxs)(ot,{variant:"outline",className:"text-muted-foreground",children:[(0,t.jsx)(ko,{"aria-hidden":"true"}),"Managed by Paperclip Cloud"]})}r(T9e,"ManagedByCloudBadge");function Zi({title:e,description:s,footnote:n,checked:a,onCheckedChange:i,disabled:o,settingKey:l,managed:c,ariaLabel:d}){const{hidden:u}=Eu(),h=c?.managed===!0;return u.has(tbe(l))?null:(0,t.jsx)(sn,{className:"block bg-transparent p-5",children:(0,t.jsxs)("div",{className:"flex items-start justify-between gap-4",children:[(0,t.jsxs)("div",{className:"space-y-1.5",children:[(0,t.jsxs)("div",{className:"flex flex-wrap items-center gap-2",children:[(0,t.jsx)("h3",{className:"text-sm font-semibold",children:e}),h?(0,t.jsx)(T9e,{}):null]}),(0,t.jsx)("p",{className:"max-w-2xl text-sm text-muted-foreground",children:s}),n?(0,t.jsx)("p",{className:"max-w-2xl text-xs text-muted-foreground",children:n}):null]}),(0,t.jsx)(ai,{checked:a,onCheckedChange:r(p=>{h||i(p)},"onCheckedChange"),disabled:o||h,"aria-label":d})]})})}r(Zi,"ExperimentalToggleCard");function Ups(){const{setBreadcrumbs:e}=Vn(),s=wt(),{hidden:n}=Eu(),[a,i]=(0,m.useState)(null);(0,m.useEffect)(()=>{e([{label:"Settings",href:"/company/settings"},{label:"Experimental"}])},[e]);const o=te({queryKey:D.instance.experimentalSettings,queryFn:r(()=>jr.getExperimental(),"queryFn")}),l=we({mutationFn:r(async G=>jr.updateExperimental(G),"mutationFn"),onMutate:r(async G=>{await s.cancelQueries({queryKey:D.instance.experimentalSettings});const X=s.getQueryData(D.instance.experimentalSettings);return X&&s.setQueryData(D.instance.experimentalSettings,{...X,...G}),{previousSettings:X}},"onMutate"),onSuccess:r(async G=>{i(null),s.setQueryData(D.instance.experimentalSettings,G),await Promise.all([s.invalidateQueries({queryKey:D.instance.experimentalSettings}),s.invalidateQueries({queryKey:D.adapters.all}),s.invalidateQueries({queryKey:["built-in-agents"]}),s.invalidateQueries({queryKey:D.health}),s.invalidateQueries({queryKey:["apps"]})])},"onSuccess"),onError:r((G,X,Y)=>{Y?.previousSettings&&s.setQueryData(D.instance.experimentalSettings,Y.previousSettings),i(G instanceof Error?G.message:"Failed to update experimental settings.")},"onError")});if(o.isLoading)return(0,t.jsx)("div",{className:"text-sm text-muted-foreground",children:"Loading experimental settings..."});if(o.error)return(0,t.jsx)("div",{className:"text-sm text-destructive",children:o.error instanceof Error?o.error.message:"Failed to load experimental settings."});const c=Eht(),d=o.data?.managedKeys??{},u=o.data?.enableWorktreeRunExecution===!0,h=d.enableWorktreeRunExecution?.managed===!0,p=zps(o.data,Lht()),f=o.data?.enableEnvironments===!0,x=o.data?.enableNativeRunner===!0,g=o.data?.enableChatConnectors===!0,v=o.data?.enableManagedSandboxOnly===!0,y=o.data?.enableIsolatedWorkspaces===!0,k=o.data?.enableIsolatedWorkspacesByDefault===!0,w=o.data?.enableStreamlinedUi!==!1;o.data?.enableConferenceRoomChat;const N=o.data?.enableClassicTaskInterface===!0,S=o.data?.enableIssuePlanDecompositions===!0,C=o.data?.enableExperimentalFileViewer===!0,_=o.data?.enableExternalObjects===!0,R=o.data?.enableBuiltInAgents===!0,I=o.data?.enableBetaSkills===!0,T=o.data?.enableSummaries===!0,E=o.data?.enableStatusCards===!0,P=d.enableSummaries?.managed===!0,O=d.enableStatusCards?.managed===!0,M=P&&!T,Q=O&&E,L=o.data?.enableDecisions===!0,F=o.data?.enableGoalsSidebarLink===!0,q=o.data?.enableCases===!0,z=o.data?.enableServerInfoDebugView===!0,K=o.data?.enablePaperclipDeveloperMode===!0,U=o.data?.enableSimplifiedEnglishInteractions===!0,V=o.data?.enableFirstTaskPlanProposal===!0,ne=o.data?.enableSmokeLab===!0,Z=o.data?.autoRestartDevServerWhenIdle===!0,ie=r(G=>!n.has(tbe(G)),"isVisible"),J=c&&ie("enableWorktreeRunExecution"),ae=J||["autoRestartDevServerWhenIdle","enableManagedSandboxOnly","enablePaperclipDeveloperMode","enableServerInfoDebugView","enableSmokeLab","enableIssuePlanDecompositions"].some(ie),oe=ie("enableClassicTaskInterface")||ie("enableGoalsSidebarLink");return(0,t.jsxs)("div",{className:"max-w-6xl space-y-6",children:[(0,t.jsxs)("div",{className:"space-y-2",children:[(0,t.jsxs)("div",{className:"flex items-center gap-2",children:[(0,t.jsx)(rh,{className:"h-5 w-5 text-muted-foreground"}),(0,t.jsx)("h1",{className:"text-lg font-semibold",children:"Experimental"})]}),(0,t.jsx)("p",{className:"text-sm text-muted-foreground",children:"Opt into features that are still being evaluated before they become default behavior."})]}),(0,t.jsx)("div",{role:"alert",className:"rounded-lg border border-amber-500/30 bg-amber-500/5 px-4 py-3",children:(0,t.jsxs)("div",{className:"flex items-start gap-3",children:[(0,t.jsx)(Es,{className:"mt-0.5 h-4 w-4 shrink-0 text-amber-700"}),(0,t.jsxs)("div",{className:"space-y-1 text-sm",children:[(0,t.jsx)("p",{className:"font-medium text-foreground",children:"Experimental features may break at any time."}),(0,t.jsx)("p",{className:"text-muted-foreground",children:"These features are opt-in and come with no compatibility guarantees. They may change, break, or be removed without notice. Avoid relying on them for critical or production workflows."})]})]})}),a&&(0,t.jsx)("div",{className:"rounded-md border border-destructive/40 bg-destructive/5 px-3 py-2 text-sm text-destructive",children:a}),(0,t.jsxs)("section",{className:"space-y-3","aria-labelledby":"experimental-features-heading",children:[(0,t.jsxs)("div",{className:"space-y-1",children:[(0,t.jsx)("h2",{id:"experimental-features-heading",className:"text-sm font-semibold",children:"Experimental features"}),(0,t.jsx)("p",{className:"text-sm text-muted-foreground",children:"Optional product features that are still being evaluated."})]}),(0,t.jsx)(Zi,{title:"Agent Chat",description:"Talk to each agent in one ongoing conversation. Clarify goals and create tasks for execution. Chat leads the Work group and opens an agent rail beside the nav, and each chat's side panel shows the agent's tasks and artifacts as cards.",footnote:"Turning this off preserves conversations and lets active runs finish, but prevents new messages.",checked:o.data?.enableAgentChat??!1,onCheckedChange:r(G=>l.mutate({enableAgentChat:G}),"onCheckedChange"),disabled:l.isPending,settingKey:"enableAgentChat",managed:d.enableAgentChat,ariaLabel:"Toggle agent chat experimental setting"}),(0,t.jsx)(Zi,{title:"Assistant connections (MCP)",description:"Connect Codex, Claude, and other assistants to your Paperclip organization. People sign in, select an organization once, and approve access to review work, delegate tasks, and add feedback.",footnote:(0,t.jsxs)(t.Fragment,{children:["Requires an authenticated instance with a configured public URL. Takes effect immediately. Turning this off blocks assistant calls and event delivery; work already delegated continues.",o.data?.enablePublicMcp&&(0,t.jsxs)(t.Fragment,{children:[" ",(0,t.jsx)(We,{className:"underline",to:"/apps/assistant-connection",children:"Set up an assistant connection"})]})]}),checked:o.data?.enablePublicMcp===!0,onCheckedChange:r(G=>l.mutate({enablePublicMcp:G}),"onCheckedChange"),disabled:l.isPending,settingKey:"enablePublicMcp",managed:d.enablePublicMcp,ariaLabel:"Toggle assistant connections experimental setting"}),(0,t.jsx)(Zi,{title:"Beta skills",description:"Allow agents to pin beta releases of the Paperclip core skill. Disabling this returns every agent to the default live skill without removing saved pins.",checked:I,onCheckedChange:r(G=>l.mutate({enableBetaSkills:G}),"onCheckedChange"),disabled:l.isPending,settingKey:"enableBetaSkills",managed:d.enableBetaSkills,ariaLabel:"Toggle beta skills experimental setting"}),(0,t.jsx)(Zi,{title:"Built-in Agents",description:"Show Paperclip-managed built-in agent surfaces, including built-in roster badges, the Built-in agents tab, and built-in agent setup controls.",checked:R,onCheckedChange:r(G=>l.mutate({enableBuiltInAgents:G}),"onCheckedChange"),disabled:l.isPending,settingKey:"enableBuiltInAgents",managed:d.enableBuiltInAgents,ariaLabel:"Toggle built-in agents experimental setting"}),(0,t.jsx)(Zi,{title:"Cases",description:"Durable work products (blog posts, tweet storms…) that tasks create and iterate on. Adds the Cases tab and the agent case API.",footnote:"Turning Cases off hides the tab and blocks the case API; existing case data is kept.",checked:q,onCheckedChange:r(G=>l.mutate({enableCases:G}),"onCheckedChange"),disabled:l.isPending,settingKey:"enableCases",managed:d.enableCases,ariaLabel:"Toggle cases experimental setting"}),(0,t.jsx)(Zi,{title:"Chat connectors",description:"Connect agents to Slack, Discord, Microsoft Teams, and Telegram conversations.",footnote:"Turning this off hides experimental chat setup and connected-task controls. Existing chat connections keep running. AgentMail, GitHub review bots, and tool connectors are controlled separately.",checked:g,onCheckedChange:r(G=>l.mutate({enableChatConnectors:G}),"onCheckedChange"),disabled:l.isPending,settingKey:"enableChatConnectors",managed:d.enableChatConnectors,ariaLabel:"Toggle chat connectors experimental setting"}),(0,t.jsx)(Zi,{title:"Combined Inbox + Task List",description:"Fold Inbox into Tasks. One Tasks row carries the unread badge, and a Views menu reaches every inbox view (Mine, Unread, Blocked, Recent, Everything) and every task view.",footnote:"Old Inbox links redirect to the matching view. Turning this off restores the separate Inbox; no data changes.",checked:o.data?.enableCombinedInboxTasks??!1,onCheckedChange:r(G=>l.mutate({enableCombinedInboxTasks:G}),"onCheckedChange"),disabled:l.isPending,settingKey:"enableCombinedInboxTasks",managed:d.enableCombinedInboxTasks,ariaLabel:"Toggle combined inbox and task list experimental setting"}),null,(0,t.jsx)(Zi,{title:"Decisions",description:"Show the Decisions item in the main sidebar — the attention home that surfaces the tasks awaiting your input — while the surface is still being evaluated.",checked:L,onCheckedChange:r(G=>l.mutate({enableDecisions:G}),"onCheckedChange"),disabled:l.isPending,settingKey:"enableDecisions",managed:d.enableDecisions,ariaLabel:"Toggle decisions experimental setting"}),(0,t.jsx)(Zi,{title:"Enable Environments",description:"Show environment management in company settings and allow project and agent environment assignment controls.",checked:f,onCheckedChange:r(G=>l.mutate({enableEnvironments:G}),"onCheckedChange"),disabled:l.isPending,settingKey:"enableEnvironments",managed:d.enableEnvironments,ariaLabel:"Toggle environments experimental setting"}),(0,t.jsx)(Zi,{title:"Enable External Objects",description:"Detect external URLs in issues and show resolved status for pull requests, tickets, and other referenced work objects.",checked:_,onCheckedChange:r(G=>l.mutate({enableExternalObjects:G}),"onCheckedChange"),disabled:l.isPending,settingKey:"enableExternalObjects",managed:d.enableExternalObjects,ariaLabel:"Toggle external objects experimental setting"}),(0,t.jsx)(Zi,{title:"Enable Isolated Workspaces",description:"Show execution workspace controls in project configuration and allow isolated workspace behavior for new and existing task runs.",checked:y,onCheckedChange:r(G=>l.mutate({enableIsolatedWorkspaces:G}),"onCheckedChange"),disabled:l.isPending,settingKey:"enableIsolatedWorkspaces",managed:d.enableIsolatedWorkspaces,ariaLabel:"Toggle isolated workspaces experimental setting"}),(0,t.jsx)(Zi,{title:"Experimental fast responses",description:"Show Connections in company settings and allow short acknowledgements while agents begin work.",checked:o.data?.enableFastResponses??!1,onCheckedChange:r(G=>l.mutate({enableFastResponses:G}),"onCheckedChange"),disabled:l.isPending,settingKey:"enableFastResponses",managed:d.enableFastResponses,ariaLabel:"Toggle fast responses experimental setting"}),(0,t.jsx)(Zi,{title:"Experimental File Viewer",description:"Show task detail controls for browsing and previewing workspace files relative to a task.",checked:C,onCheckedChange:r(G=>l.mutate({enableExperimentalFileViewer:G}),"onCheckedChange"),disabled:l.isPending,settingKey:"enableExperimentalFileViewer",managed:d.enableExperimentalFileViewer,ariaLabel:"Toggle experimental file viewer setting"}),(0,t.jsx)(Zi,{title:"First task: propose with a plan document",description:"When the user's first request is a single task, the chief of staff writes a short plan document and a checkbox card instead of a one-card confirmation. Applies to organizations created after the toggle is flipped.",checked:V,onCheckedChange:r(G=>l.mutate({enableFirstTaskPlanProposal:G}),"onCheckedChange"),disabled:l.isPending,settingKey:"enableFirstTaskPlanProposal",managed:d.enableFirstTaskPlanProposal,ariaLabel:"Toggle first task plan proposal experimental setting"}),(0,t.jsx)(Zi,{title:"GitHub review bots",description:"Connect agents to GitHub with their own App identity to review pull requests and respond to issues.",footnote:"Independent of Chat connectors. Turning this off hides setup and management; existing bots keep running. GitHub tool connections stay available.",checked:o.data?.enableGitHubReviewBots===!0,onCheckedChange:r(G=>l.mutate({enableGitHubReviewBots:G}),"onCheckedChange"),disabled:l.isPending,settingKey:"enableGitHubReviewBots",managed:d.enableGitHubReviewBots,ariaLabel:"Toggle GitHub review bots experimental setting"}),(0,t.jsx)(Zi,{title:"Memory connectors",description:"Connect Mem0, Zep, Supermemory, Cognee, and Honcho for long-term memory and context.",footnote:"Turning this off hides setup for these connectors. Existing connections keep running.",checked:o.data?.enableMemoryConnectors===!0,onCheckedChange:r(G=>l.mutate({enableMemoryConnectors:G}),"onCheckedChange"),disabled:l.isPending,settingKey:"enableMemoryConnectors",managed:d.enableMemoryConnectors,ariaLabel:"Toggle memory connectors experimental setting"}),(0,t.jsx)(Zi,{title:"OpenAI Dot",description:"Add OpenAI Dot as a standalone agent choice. Pair your Dot and verify event delivery before assigning work.",footnote:"Requires Assistant connections (MCP) and an authenticated instance with a public HTTPS URL. Turning this off blocks Dot calls and new work; saved connections are kept.",checked:o.data?.enableOpenAiDot===!0,onCheckedChange:r(G=>l.mutate({enableOpenAiDot:G}),"onCheckedChange"),disabled:l.isPending,settingKey:"enableOpenAiDot",managed:d.enableOpenAiDot,ariaLabel:"Toggle OpenAI Dot experimental setting"}),(0,t.jsx)(Zi,{title:"Paperclip Runner",description:"Allow new Codex agents to select the experimental Rust Paperclip Runner, including authenticated runner ingress when a sandbox requires it. Onboarding continues to use legacy adapters. Turning this off hides the choice without affecting existing native runs.",checked:x,onCheckedChange:r(G=>l.mutate({enableNativeRunner:G}),"onCheckedChange"),disabled:l.isPending,settingKey:"enableNativeRunner",managed:d.enableNativeRunner,ariaLabel:"Toggle Paperclip Runner experimental setting"}),(0,t.jsx)(Zi,{title:"Pixels Office",description:"Show a live pixel-art office floor plan where each agent is a character and each character shows how many tasks that agent is holding.",checked:o.data?.enablePixelsOffice===!0,onCheckedChange:r(G=>l.mutate({enablePixelsOffice:G}),"onCheckedChange"),disabled:l.isPending,settingKey:"enablePixelsOffice",managed:d.enablePixelsOffice,ariaLabel:"Toggle Pixels Office experimental setting"}),(0,t.jsx)(Zi,{title:"Simplified English Interactions",description:"Instruct agents to write user interactions (plan confirmations, questions, suggested tasks, checkbox prompts) in ASD-STE100 Simplified Technical English, with brief context on what information the decision needs and what happens for each choice.",checked:U,onCheckedChange:r(G=>l.mutate({enableSimplifiedEnglishInteractions:G}),"onCheckedChange"),disabled:l.isPending,settingKey:"enableSimplifiedEnglishInteractions",managed:d.enableSimplifiedEnglishInteractions,ariaLabel:"Toggle simplified english interactions experimental setting"}),(0,t.jsx)(Zi,{title:"Status Cards",description:"Enable the experimental shared status-card board and its gated API. Existing card data is kept when this is disabled.",footnote:"Enabling Status Cards also enables Summaries.",checked:E,onCheckedChange:r(G=>l.mutate(G?{enableSummaries:!0,enableStatusCards:!0}:{enableStatusCards:!1}),"onCheckedChange"),disabled:l.isPending||M,settingKey:"enableStatusCards",managed:d.enableStatusCards,ariaLabel:"Toggle status cards experimental setting"}),(0,t.jsx)(Zi,{title:"Streamlined UI",description:"Use the simplified main sidebar, shared Tasks and Inbox presentation, focused task detail layout, and contextual navigation across Agents, Routines, Skills, and Settings.",footnote:"Turning this off restores the legacy shell and navigation. Task and page data are unchanged.",checked:w,onCheckedChange:r(G=>l.mutate({enableStreamlinedUi:G}),"onCheckedChange"),disabled:l.isPending,settingKey:"enableStreamlinedUi",managed:d.enableStreamlinedUi,ariaLabel:"Toggle Streamlined UI experimental setting"}),(0,t.jsx)(Zi,{title:"Summaries",description:"Show Summarizer-generated status slots on project and workspace pages, with on-demand refresh and revision history. Existing summary data is kept when this is disabled.",footnote:"Status Cards requires Summaries. Disabling Summaries also disables Status Cards.",checked:T,onCheckedChange:r(G=>l.mutate(G||!E?{enableSummaries:G}:{enableSummaries:!1,enableStatusCards:!1}),"onCheckedChange"),disabled:l.isPending||Q,settingKey:"enableSummaries",managed:d.enableSummaries,ariaLabel:"Toggle summaries experimental setting"}),y&&(0,t.jsx)(Zi,{title:"Use Isolated Workspaces By Default",description:"Treat a project that has no execution workspace policy of its own as if it selected isolated workspaces, so its tasks get a per-task worktree instead of sharing the project checkout. A project that carries its own policy keeps it.",checked:k,onCheckedChange:r(G=>l.mutate({enableIsolatedWorkspacesByDefault:G}),"onCheckedChange"),disabled:l.isPending,settingKey:"enableIsolatedWorkspacesByDefault",managed:d.enableIsolatedWorkspacesByDefault,ariaLabel:"Toggle isolated workspaces by default experimental setting"})]}),ae?(0,t.jsxs)("section",{className:"space-y-3","aria-labelledby":"developer-mode-heading",children:[(0,t.jsxs)("div",{className:"space-y-1",children:[(0,t.jsx)("h2",{id:"developer-mode-heading",className:"text-sm font-semibold",children:"Paperclip Developer Mode"}),(0,t.jsx)("p",{className:"text-sm text-muted-foreground",children:"Internal tools for developing, testing, and debugging Paperclip."})]}),(0,t.jsx)(Zi,{title:"Auto-Restart Dev Server When Idle",description:"In `pnpm dev:once`, wait for all queued and running local agent runs to finish, then restart the server automatically when backend changes or migrations make the current boot stale.",checked:Z,onCheckedChange:r(G=>l.mutate({autoRestartDevServerWhenIdle:G}),"onCheckedChange"),disabled:l.isPending,settingKey:"autoRestartDevServerWhenIdle",managed:d.autoRestartDevServerWhenIdle,ariaLabel:"Toggle guarded dev-server auto-restart"}),(0,t.jsx)(Zi,{title:"Managed Environment Only",description:"Hide the local environment and run all agents in the platform-managed environment.",checked:v,onCheckedChange:r(G=>l.mutate({enableManagedSandboxOnly:G}),"onCheckedChange"),disabled:l.isPending,settingKey:"enableManagedSandboxOnly",managed:d.enableManagedSandboxOnly,ariaLabel:"Toggle managed environment only experimental setting"}),(0,t.jsx)(Zi,{title:"Paperclip Developer Mode",description:"Show internal Paperclip maintainer tools and observability links, including Honeycomb trace queries on run pages.",checked:K,onCheckedChange:r(G=>l.mutate({enablePaperclipDeveloperMode:G}),"onCheckedChange"),disabled:l.isPending,settingKey:"enablePaperclipDeveloperMode",managed:d.enablePaperclipDeveloperMode,ariaLabel:"Toggle Paperclip developer mode experimental setting"}),J?(0,t.jsx)(sn,{className:"block bg-transparent p-5",children:(0,t.jsxs)("div",{className:"flex flex-col gap-4",children:[(0,t.jsxs)("div",{className:"flex items-start justify-between gap-4",children:[(0,t.jsxs)("div",{className:"space-y-1.5",children:[(0,t.jsxs)("div",{className:"flex flex-wrap items-center gap-2",children:[(0,t.jsx)("h3",{className:"text-sm font-semibold",children:"Run tasks in this worktree"}),h?(0,t.jsx)(T9e,{}):null]}),(0,t.jsx)("p",{className:"max-w-2xl text-sm text-muted-foreground",children:"This is an isolated git-worktree preview instance. Turn this on to let the scheduler execute runs here. Only tasks created after enabling will run automatically — copied/pre-existing tasks stay parked. Toggling off and on resets the cutoff."})]}),(0,t.jsx)(ai,{checked:u,onCheckedChange:r(G=>{h||l.mutate({enableWorktreeRunExecution:G})},"onCheckedChange"),disabled:l.isPending||h,"aria-label":"Toggle worktree run execution setting"})]}),p.kind==="armed"?(0,t.jsxs)("div",{className:"flex items-center gap-2 rounded-md border border-emerald-500/30 bg-emerald-500/5 px-3 py-2 text-sm text-foreground",children:[(0,t.jsx)(ho,{className:"h-4 w-4 shrink-0 text-emerald-600"}),(0,t.jsxs)("span",{children:["Running tasks created after"," ",(0,t.jsx)("span",{className:"font-medium",children:qps(p.activatedAt)}),"."]})]}):null,p.kind==="fail_closed"?(0,t.jsxs)("div",{className:"flex items-start gap-2 rounded-md border border-amber-500/30 bg-amber-500/5 px-3 py-2 text-sm",children:[(0,t.jsx)(Es,{className:"mt-0.5 h-4 w-4 shrink-0 text-amber-700"}),(0,t.jsxs)("div",{className:"space-y-0.5",children:[(0,t.jsx)("p",{className:"font-medium text-foreground",children:"Execution is suppressed — effectively off."}),(0,t.jsxs)("p",{className:"text-muted-foreground",children:[p.reason==="instance_mismatch"?"This setting was armed in a different instance and copied here, so no tasks run automatically.":"This setting is missing its activation cutoff, so no tasks run automatically."," ","Toggle it off and back on to arm execution for tasks created here."]})]})]}):null]})}):null,(0,t.jsx)(Zi,{title:"Server Info Debug View",description:'Show a "Server" section in the account drawer with the current server restart time and running commit.',checked:z,onCheckedChange:r(G=>l.mutate({enableServerInfoDebugView:G}),"onCheckedChange"),disabled:l.isPending,settingKey:"enableServerInfoDebugView",managed:d.enableServerInfoDebugView,ariaLabel:"Toggle server info debug view experimental setting"}),(0,t.jsx)(Zi,{title:"Smoke Lab",description:'Add a "Smoke Lab" tab under Apps → Developer and an "Integration smoke" card on the dashboard for exercising every integration path against deterministic local fixtures (fake OAuth provider + loopback MCP servers). Private (non-public) deployments only.',checked:ne,onCheckedChange:r(G=>l.mutate({enableSmokeLab:G}),"onCheckedChange"),disabled:l.isPending,settingKey:"enableSmokeLab",managed:d.enableSmokeLab,ariaLabel:"Toggle smoke lab experimental setting"}),(0,t.jsx)(Zi,{title:"Task Plan Decomposition",description:"Show accepted-plan decomposition history on task detail pages. Intended for debugging and validating subtask creation behavior while the presentation is still being refined.",checked:S,onCheckedChange:r(G=>l.mutate({enableIssuePlanDecompositions:G}),"onCheckedChange"),disabled:l.isPending,settingKey:"enableIssuePlanDecompositions",managed:d.enableIssuePlanDecompositions,ariaLabel:"Toggle task plan decomposition panel experimental setting"})]}):null,oe?(0,t.jsxs)("section",{className:"space-y-3","aria-labelledby":"legacy-heading",children:[(0,t.jsxs)("div",{className:"space-y-1",children:[(0,t.jsx)("h2",{id:"legacy-heading",className:"text-sm font-semibold",children:"Legacy"}),(0,t.jsx)("p",{className:"text-sm text-muted-foreground",children:"These features are going to be removed."})]}),(0,t.jsx)(Zi,{title:"Classic Task Interface",description:"Restores the previous task detail page: the page-level header with inline description editing, the plain comment thread, and the fixed Properties sidebar. Chat-only features — streaming activity folding, inline plan and question cards, the three-mode composer — are unavailable in the classic view.",footnote:"Switching takes effect immediately. No task data is affected.",checked:N,onCheckedChange:r(G=>l.mutate({enableClassicTaskInterface:G}),"onCheckedChange"),disabled:l.isPending,settingKey:"enableClassicTaskInterface",managed:d.enableClassicTaskInterface,ariaLabel:"Toggle classic task interface experimental setting"}),(0,t.jsx)(Zi,{title:"Goals Sidebar Link",description:"Restore the Goals item in the main sidebar while the goals surface is being evaluated.",checked:F,onCheckedChange:r(G=>l.mutate({enableGoalsSidebarLink:G}),"onCheckedChange"),disabled:l.isPending,settingKey:"enableGoalsSidebarLink",managed:d.enableGoalsSidebarLink,ariaLabel:"Toggle goals sidebar link experimental setting"})]}):null]})}r(Ups,"InstanceExperimentalSettings");function Kps(){const{userId:e,settled:s}=If(),{setBreadcrumbs:n}=Vn(),{pushToast:a}=Ti(),i=wt(),[o,l]=(0,m.useState)(""),[c,d]=(0,m.useState)(null),[u,h]=(0,m.useState)(new Set);(0,m.useEffect)(()=>{n([{label:"Settings",href:"/company/settings"},{label:"Instance settings",href:"/company/settings/instance/general"},{label:"Access"}])},[n]);const p=te({queryKey:D.access.adminUsers(o),queryFn:r(()=>or.searchAdminUsers(o),"queryFn")}),f=te({...cOe(e),enabled:s&&p.isSuccess}),x=f.data??[],g=(0,m.useMemo)(()=>p.data?.find(w=>w.id===c)??null,[c,p.data]),v=te({queryKey:D.access.userCompanyAccess(c??""),queryFn:r(()=>or.getUserCompanyAccess(c),"queryFn"),enabled:!!c});(0,m.useEffect)(()=>{!c&&p.data?.[0]&&d(p.data[0].id)},[c,p.data]),(0,m.useEffect)(()=>{v.data&&h(new Set(v.data.companyAccess.filter(w=>w.status==="active").map(w=>w.companyId)))},[v.data]);const y=we({mutationFn:r(()=>or.setUserCompanyAccess(c,[...u]),"mutationFn"),onSuccess:r(async()=>{await i.invalidateQueries({queryKey:D.access.userCompanyAccess(c)}),await i.invalidateQueries({queryKey:D.access.adminUsers(o)}),await i.invalidateQueries({queryKey:D.companies.all}),a({title:"Organization access updated",tone:"success"})},"onSuccess")}),k=we({mutationFn:r(async w=>{if(!c)throw new Error("No user selected");return w?or.promoteInstanceAdmin(c):or.demoteInstanceAdmin(c)},"mutationFn"),onSuccess:r(async()=>{await i.invalidateQueries({queryKey:D.access.adminUsers(o)}),c&&await i.invalidateQueries({queryKey:D.access.userCompanyAccess(c)}),a({title:"Instance role updated",tone:"success"})},"onSuccess")});if(p.isLoading||!s||p.isSuccess&&f.isPending)return(0,t.jsx)("div",{className:"text-sm text-muted-foreground",children:"Loading instance access…"});if(p.error){const w=p.error instanceof nn&&p.error.status===403?"Instance admin access is required to manage users.":p.error instanceof Error?p.error.message:"Failed to load users.";return(0,t.jsx)("div",{className:"text-sm text-destructive",children:w})}return f.error?(0,t.jsxs)("div",{className:"space-y-3",children:[(0,t.jsx)("p",{className:"text-sm text-destructive",children:"Failed to load organizations. Try again before changing access."}),(0,t.jsx)($,{onClick:r(()=>{f.refetch()},"onClick"),children:"Try again"})]}):(0,t.jsxs)("div",{className:"max-w-6xl space-y-6",children:[(0,t.jsxs)("div",{className:"space-y-3",children:[(0,t.jsxs)("div",{className:"flex items-center gap-2",children:[(0,t.jsx)(p3,{className:"h-5 w-5 text-muted-foreground"}),(0,t.jsx)("h1",{className:"text-lg font-semibold",children:"Instance Access"})]}),(0,t.jsx)("p",{className:"max-w-3xl text-sm text-muted-foreground",children:"Search users, manage instance-admin status, and control which organizations they can access."})]}),(0,t.jsxs)("div",{className:"grid gap-6 lg:grid-cols-(--gtc-34)",children:[(0,t.jsxs)(sn,{className:"block space-y-4 p-4",children:[(0,t.jsxs)("label",{className:"block space-y-2 text-sm",children:[(0,t.jsx)("span",{className:"font-medium",children:"Search users"}),(0,t.jsx)("input",{className:"w-full rounded-md border border-border bg-background px-3 py-2",value:o,onChange:r(w=>l(w.target.value),"onChange"),placeholder:"Search by name or email"})]}),(0,t.jsx)("div",{className:"space-y-2",children:(p.data??[]).map(w=>(0,t.jsxs)("button",{type:"button",onClick:r(()=>d(w.id),"onClick"),className:`w-full rounded-lg border px-3 py-3 text-left transition-colors ${w.id===c?"border-foreground bg-accent":"border-border hover:bg-accent/40"}`,children:[(0,t.jsxs)("div",{className:"flex items-center justify-between gap-2",children:[(0,t.jsxs)("div",{className:"min-w-0",children:[(0,t.jsx)("div",{className:"truncate font-medium",children:w.name||w.email||w.id}),(0,t.jsx)("div",{className:"truncate text-sm text-muted-foreground",children:w.email||w.id})]}),w.isInstanceAdmin?(0,t.jsx)(Bi,{className:"h-4 w-4 text-emerald-600"}):null]}),(0,t.jsxs)("div",{className:"mt-2 text-xs text-muted-foreground",children:[w.activeCompanyMembershipCount," active organization memberships"]})]},w.id))})]}),(0,t.jsx)(sn,{className:"block space-y-4 p-5",children:c?v.isLoading?(0,t.jsx)("div",{className:"text-sm text-muted-foreground",children:"Loading user access…"}):v.error?(0,t.jsx)("div",{className:"text-sm text-destructive",children:v.error instanceof Error?v.error.message:"Failed to load user access."}):(0,t.jsxs)(t.Fragment,{children:[(0,t.jsxs)("div",{className:"flex flex-wrap items-start justify-between gap-4",children:[(0,t.jsxs)("div",{children:[(0,t.jsx)("div",{className:"text-lg font-semibold",children:g?.name||g?.email||c}),(0,t.jsx)("div",{className:"text-sm text-muted-foreground",children:g?.email||c})]}),(0,t.jsx)($,{variant:g?.isInstanceAdmin?"outline":"default",onClick:r(()=>k.mutate(!(g?.isInstanceAdmin??!1)),"onClick"),disabled:k.isPending,children:g?.isInstanceAdmin?"Remove instance admin":"Promote to instance admin"})]}),(0,t.jsxs)("div",{className:"space-y-3",children:[(0,t.jsxs)("div",{children:[(0,t.jsx)("h2",{className:"text-sm font-semibold",children:"Organization access"}),(0,t.jsx)("p",{className:"text-sm text-muted-foreground",children:"Toggle organization membership for this user. New access defaults to an active operator membership."})]}),(0,t.jsx)("div",{className:"grid gap-3 md:grid-cols-2",children:x.map(w=>(0,t.jsxs)("label",{className:"flex items-start gap-3 rounded-lg border border-border px-3 py-3",children:[(0,t.jsx)(ei,{checked:u.has(w.id),onCheckedChange:r(N=>{h(S=>{const C=new Set(S);return N?C.add(w.id):C.delete(w.id),C})},"onCheckedChange")}),(0,t.jsxs)("span",{className:"space-y-1",children:[(0,t.jsx)("span",{className:"block text-sm font-medium",children:w.name}),(0,t.jsx)("span",{className:"block text-xs text-muted-foreground",children:w.issuePrefix})]})]},w.id))}),(0,t.jsx)("div",{className:"flex justify-end",children:(0,t.jsx)($,{onClick:r(()=>y.mutate(),"onClick"),disabled:y.isPending,children:y.isPending?"Saving…":"Save organization access"})})]}),(0,t.jsxs)("div",{className:"space-y-2",children:[(0,t.jsx)("h2",{className:"text-sm font-semibold",children:"Current memberships"}),(0,t.jsx)("div",{className:"space-y-2",children:(v.data?.companyAccess??[]).map(w=>(0,t.jsxs)("div",{className:"flex items-center justify-between rounded-lg border border-border px-3 py-2 text-sm",children:[(0,t.jsxs)("div",{children:[(0,t.jsx)("div",{className:"font-medium",children:w.companyName||w.companyId}),(0,t.jsxs)("div",{className:"text-muted-foreground",children:[w.membershipRole||"unset"," • ",w.status]})]}),(0,t.jsx)("div",{className:"text-xs text-muted-foreground",children:new Date(w.updatedAt).toLocaleDateString()})]},w.id))})]})]}):(0,t.jsx)("div",{className:"text-sm text-muted-foreground",children:"Select a user to inspect instance access."})})]})]})}r(Kps,"InstanceAccess");var nge={getMine:r(e=>ke.get(`/companies/${e}/users/me/inbox-agent-policy`),"getMine"),updateMine:r((e,s)=>ke.put(`/companies/${e}/users/me/inbox-agent-policy`,s),"updateMine")},Qps=[{value:"open",title:"Any of my agents",description:"Let any agent you manage archive tasks out of your inbox."},{value:"allowlist",title:"Only chosen agents",description:"Restrict inbox tidying to the agents you pick below."},{value:"disabled",title:"Off",description:"Agents can never archive tasks from your inbox."}];function $T(e,s){return`${e}:${[...s].sort().join(",")}`}r($T,"policyKey");function Wps({companyId:e}){const s=wt(),[n,a]=(0,m.useState)(null),i=(0,m.useRef)(null),o=te({queryKey:e?D.inboxAgentPolicy.mine(e):["inbox-agent-policy","none"],queryFn:r(()=>nge.getMine(e),"queryFn"),enabled:!!e}),l=o.data,c=te({queryKey:e?D.agents.list(e):["agents","none"],queryFn:r(()=>Nt.list(e),"queryFn"),enabled:!!e}),d=(0,m.useMemo)(()=>(c.data??[]).filter(bf),[c.data]),u=(0,m.useMemo)(()=>d.map(x=>({id:x.id,name:x.name,title:x.title??x.role,icon:x.icon})),[d]),h=(0,m.useMemo)(()=>new Set(n?.allowedAgentIds??[]),[n?.allowedAgentIds]);(0,m.useEffect)(()=>{if(!l)return;const x=$T(l.mode,l.allowedAgentIds);a(g=>g===null||$T(g.mode,g.allowedAgentIds)===i.current?{mode:l.mode,allowedAgentIds:l.allowedAgentIds}:g),i.current=x},[l]);const p=we({mutationFn:r(x=>nge.updateMine(e,{mode:x.mode,allowedAgentIds:x.mode==="allowlist"?x.allowedAgentIds:[]}),"mutationFn"),onSuccess:r(x=>{s.setQueryData(D.inboxAgentPolicy.mine(e),x)},"onSuccess")}),f=!!(n&&l&&$T(n.mode,n.allowedAgentIds)!==$T(l.mode,l.allowedAgentIds));return o.error?(0,t.jsx)("div",{className:"text-sm text-destructive",children:o.error instanceof Error?o.error.message:"Failed to load inbox agent policy."}):o.isLoading||!n?(0,t.jsx)("div",{className:"text-sm text-muted-foreground",children:"Loading inbox agent policy…"}):(0,t.jsxs)("section",{className:"space-y-4","aria-label":"Let agents tidy my inbox",children:[(0,t.jsxs)("div",{className:"space-y-1",children:[(0,t.jsxs)("div",{className:"flex items-center gap-2",children:[(0,t.jsx)(Od,{className:"h-5 w-5 text-muted-foreground"}),(0,t.jsx)("h2",{className:"text-base font-semibold",children:"Let agents tidy my inbox"})]}),(0,t.jsx)("p",{className:"max-w-2xl text-sm text-muted-foreground",children:"Choose whether the agents you manage may archive tasks out of your inbox on your behalf. You can undo any archive, and every agent archive is attributed in the task's properties."})]}),(0,t.jsx)(am,{ariaLabel:"Inbox agent archiving policy",value:n.mode,onValueChange:r(x=>a(g=>g&&{...g,mode:x}),"onValueChange"),options:Qps,className:"max-w-2xl"}),n.mode==="allowlist"?(0,t.jsxs)("div",{className:"max-w-2xl space-y-2",children:[(0,t.jsx)("div",{className:"text-sm font-medium",children:"Agents allowed to tidy my inbox"}),(0,t.jsx)(Qj,{agents:u,selectedAgentIds:h,onChange:r(x=>a(g=>g&&{...g,allowedAgentIds:[...x]}),"onChange"),triggerLabel:h.size===0?"Select agents":`${h.size} ${h.size===1?"agent":"agents"} selected`,triggerFullWidth:!1,showSelectionPreview:!1,emptyMessage:"You don’t manage any agents yet."})]}):null,p.error?(0,t.jsx)("div",{className:"max-w-2xl rounded-md border border-destructive/40 bg-destructive/5 px-3 py-2 text-sm text-destructive",children:p.error instanceof Error?p.error.message:"Failed to save inbox agent policy."}):null,(0,t.jsxs)("div",{className:"flex max-w-2xl items-center justify-end gap-3",children:[p.isSuccess&&!f?(0,t.jsx)("span",{className:"text-xs text-muted-foreground",role:"status",children:"Saved"}):null,(0,t.jsxs)($,{type:"button",disabled:!f||p.isPending,onClick:r(()=>n&&p.mutate(n),"onClick"),children:[p.isPending?(0,t.jsx)(st,{className:"size-4 animate-spin"}):(0,t.jsx)(of,{className:"size-4"}),p.isPending?"Saving…":"Save"]})]})]})}r(Wps,"InboxAgentPolicyControl");var Hps={granted:"Allowed",denied:"Blocked in browser settings",default:"Not requested yet",unsupported:"Not supported in this browser"},rge={unknown:"Checking…",active:"Active on this device",off:"Off",unsupported:"Not supported in this browser",permission:"Waiting for notification permission","server-disabled":"Not available on this server",error:"Subscription failed"};function Vps(){const[e,s]=(0,m.useState)({});return(0,m.useEffect)(()=>{let n=!1;const a=r(()=>{Promise.all(o3.map(async o=>[o,(await bRe(o))?.name])).then(o=>{if(n)return;const l={};for(const[c,d]of o)d&&(l[c]=d);s(l)})},"refresh");a();const i=xRe(a);return()=>{n=!0,i()}},[]),e}r(Vps,"useCustomSoundNames");function Gps({kind:e,customName:s,disabled:n,onError:a}){const i=IRe(),o=i.kinds[e],l=(0,m.useId)(),[c,d]=(0,m.useState)(!1),u=xEt[e];async function h(x){const g=pRe(x);if(!g.ok){a(`${u}: ${g.error}`);return}d(!0);try{await hEt(e,x),C4(e,{soundId:Ice}),a(null)}catch(v){a(v instanceof Error?v.message:"Could not save the custom sound.")}finally{d(!1)}}r(h,"upload");async function p(){d(!0);try{await pEt(e),ag().kinds[e].soundId==="custom"&&C4(e,{soundId:y8[e]})}finally{d(!1)}}r(p,"remove");const f=n||!o.enabled;return(0,t.jsxs)("div",{className:"flex flex-col gap-2 border-b border-border/70 py-3 last:border-b-0 sm:flex-row sm:items-center sm:gap-3",children:[(0,t.jsxs)("div",{className:"flex min-w-0 items-center gap-3 sm:w-48 sm:shrink-0",children:[(0,t.jsx)(ai,{checked:o.enabled,onCheckedChange:r(x=>C4(e,{enabled:x}),"onCheckedChange"),disabled:n,"aria-label":`${u} notifications`}),(0,t.jsx)("div",{className:"min-w-0 flex-1 truncate text-sm font-medium",title:u,children:u})]}),(0,t.jsxs)("div",{className:"flex min-w-0 flex-wrap items-center gap-2 sm:flex-1 sm:flex-nowrap",children:[(0,t.jsxs)(Ca,{value:o.soundId,onValueChange:r(x=>C4(e,{soundId:x}),"onValueChange"),disabled:f,children:[(0,t.jsx)(Na,{className:"min-w-0 flex-1 sm:w-(--sz-170px) sm:flex-none","aria-label":`${u} sound`,children:(0,t.jsx)(Sa,{})}),(0,t.jsxs)(_a,{children:[vRe.map(x=>(0,t.jsx)(un,{value:x.id,children:x.label},x.id)),s?(0,t.jsxs)(un,{value:Ice,children:["Custom: ",s]}):null,(0,t.jsx)(un,{value:fEt,children:"No sound"})]})]}),(0,t.jsx)($,{type:"button",variant:"outline",size:"icon-sm","aria-label":`Preview ${u} sound`,disabled:f||o.soundId==="none",onClick:r(()=>{NRe(e,o.soundId,i.volume)},"onClick"),children:(0,t.jsx)(ho,{})}),(0,t.jsx)("input",{id:l,type:"file",accept:"audio/*",className:"sr-only",disabled:f||c,onChange:r(x=>{const g=x.target.files?.[0];x.target.value="",g&&h(g)},"onChange")}),(0,t.jsxs)($,{type:"button",variant:"outline",size:"sm",disabled:f||c,onClick:r(()=>document.getElementById(l)?.click(),"onClick"),children:[c?(0,t.jsx)(st,{className:"animate-spin"}):(0,t.jsx)(Kb,{}),s?"Replace":"Custom"]}),s?(0,t.jsx)($,{type:"button",variant:"ghost",size:"icon-sm","aria-label":`Remove custom ${u} sound`,disabled:c,onClick:r(()=>{p()},"onClick"),children:(0,t.jsx)(ma,{})}):null]})]})}r(Gps,"KindRow");function Yps({userId:e}){const s=IRe(),n=_Et(),a=Vps(),[i,o]=(0,m.useState)(()=>j_()),[l,c]=(0,m.useState)(null),[d,u]=(0,m.useState)(null),[h,p]=(0,m.useState)(!1),f=uRe(),x=n.status==="active",g=(0,m.useCallback)(()=>{e&&pU(ag(),e)},[e]);async function v(){const S=await tEt();return o(S),S==="granted"&&g(),S}r(v,"askPermission");async function y(S){T6(C=>({...C,enabled:S})),S&&j_()==="default"&&await v()}r(y,"setEnabled");async function k(S){T6(C=>({...C,pushEnabled:S})),S&&j_()==="default"&&await v()}r(k,"setPushEnabled");async function w(){p(!0),c(null),u(null);try{const S=await w8.sendWebPushTest();c(S.sent>0?`Test sent to ${S.sent} device${S.sent===1?"":"s"}.`:"No device has push turned on for your account yet.")}catch(S){u(S instanceof Error?S.message:"Could not send the test notification.")}finally{p(!1)}}r(w,"sendTest");const N=!s.enabled;return(0,t.jsxs)("section",{className:"space-y-4","aria-label":"Notifications",children:[(0,t.jsxs)("div",{className:"space-y-1",children:[(0,t.jsxs)("div",{className:"flex items-center gap-2",children:[(0,t.jsx)(JUe,{className:"h-5 w-5 text-muted-foreground"}),(0,t.jsx)("h2",{className:"text-base font-semibold",children:"Notifications"})]}),(0,t.jsx)("p",{className:"max-w-2xl text-sm text-muted-foreground",children:"Sounds and alerts for approvals, agent questions, comments, assignments, reviews, failed runs and join requests. These settings apply to this browser only."})]}),(0,t.jsxs)("div",{className:"max-w-3xl space-y-4 rounded-md border border-border/70 p-4",children:[(0,t.jsxs)("div",{className:"flex items-center justify-between gap-4",children:[(0,t.jsxs)("div",{className:"min-w-0",children:[(0,t.jsx)("div",{className:"text-sm font-medium",children:"Notifications on this device"}),(0,t.jsx)("div",{className:"text-xs text-muted-foreground",children:"Play sounds and show alerts for new inbox items."})]}),(0,t.jsx)(ai,{checked:s.enabled,onCheckedChange:r(S=>{y(S)},"onCheckedChange"),"aria-label":"Notifications on this device"})]}),(0,t.jsxs)("div",{className:"flex items-center justify-between gap-4",children:[(0,t.jsxs)("div",{className:"min-w-0",children:[(0,t.jsx)("div",{className:"text-sm font-medium",children:"Browser permission"}),(0,t.jsx)("div",{className:"text-xs text-muted-foreground",children:Hps[i]})]}),i==="default"?(0,t.jsx)($,{type:"button",variant:"outline",size:"sm",className:"shrink-0",onClick:r(()=>{v()},"onClick"),children:"Allow notifications"}):null]}),(0,t.jsxs)("div",{className:"flex items-center justify-between gap-4",children:[(0,t.jsxs)("div",{className:"min-w-0",children:[(0,t.jsx)("div",{className:"text-sm font-medium",children:"Push when Paperclip is closed"}),(0,t.jsxs)("div",{className:"text-xs text-muted-foreground",children:[f?rge[n.status]:rge.unsupported,n.error?`: ${n.error}`:""]})]}),(0,t.jsx)(ai,{checked:s.pushEnabled,onCheckedChange:r(S=>{k(S)},"onCheckedChange"),disabled:N||!f,"aria-label":"Push when Paperclip is closed"})]}),s.enabled&&!x?(0,t.jsx)("p",{className:"rounded-md bg-muted px-3 py-2 text-xs text-muted-foreground",children:"Push is off on this device, so background alerts only work while a Paperclip tab is visible."}):null,sEt()?(0,t.jsx)("p",{className:"rounded-md bg-muted px-3 py-2 text-xs text-muted-foreground",children:"On iPhone and iPad, push notifications need Paperclip added to the Home Screen (Share, then Add to Home Screen) and opened from there."}):null,(0,t.jsxs)("div",{className:"flex items-center gap-4",children:[(0,t.jsx)("label",{htmlFor:"notification-volume",className:"text-sm font-medium",children:"Volume"}),(0,t.jsx)("input",{id:"notification-volume",type:"range",min:0,max:100,step:5,value:Math.round(s.volume*100),disabled:N,onChange:r(S=>T6(C=>({...C,volume:Number(S.target.value)/100})),"onChange"),className:"h-1.5 w-full max-w-xs"}),(0,t.jsxs)("span",{className:"w-10 text-right text-xs text-muted-foreground",children:[Math.round(s.volume*100),"%"]})]}),(0,t.jsx)("div",{children:o3.map(S=>(0,t.jsx)(Gps,{kind:S,customName:a[S],disabled:N,onError:u},S))}),(0,t.jsx)("p",{className:"text-xs text-muted-foreground",children:"Custom sounds must be audio files of 512 KB or less. They play only while Paperclip is open; push notifications use your system sound."}),(0,t.jsxs)("div",{className:"flex flex-wrap items-center gap-3",children:[(0,t.jsxs)($,{type:"button",variant:"secondary",onClick:r(()=>{w()},"onClick"),disabled:h||N,children:[h?(0,t.jsx)(st,{className:"animate-spin"}):(0,t.jsx)(L3,{}),"Send test notification"]}),l?(0,t.jsx)("span",{className:"text-sm text-muted-foreground",children:l}):null]}),d?(0,t.jsx)("div",{className:"text-sm text-destructive",children:d}):null]})]})}r(Yps,"NotificationSettingsSection");function Zps(e){const s=e.trim().split(/\s+/).filter(Boolean);return s.length>=2?`${s[0]?.[0]??""}${s[s.length-1]?.[0]??""}`.toUpperCase():e.slice(0,2).toUpperCase()}r(Zps,"deriveInitials");function Jps(){const{setBreadcrumbs:e}=Vn(),{selectedCompanyId:s,selectedCompany:n}=fs(),a=wt(),i=(0,m.useId)(),o=(0,m.useRef)(null),[l,c]=(0,m.useState)(""),[d,u]=(0,m.useState)(""),[h,p]=(0,m.useState)(null),f=te({queryKey:D.auth.session,queryFn:r(()=>Pa.getSession(),"queryFn"),retry:!1});(0,m.useEffect)(()=>{e([{label:"Settings",href:"/company/settings"},{label:"Profile"}])},[e]),(0,m.useEffect)(()=>{const I=f.data;I&&(c(I.user.name??""),u(I.user.image??""))},[f.data]);function x(I){a.setQueryData(D.auth.session,T=>T&&{...T,user:{...T.user,...I}})}r(x,"syncSessionProfile");async function g(I){const T=await Pa.updateProfile(I);return x(T),T}r(g,"persistProfile");function v(){return l.trim()||f.data?.user.name||"Board"}r(v,"resolveProfileName");const y=we({mutationFn:r(I=>g(I),"mutationFn"),onSuccess:r(I=>{p(null),c(I.name??""),u(I.image??"")},"onSuccess"),onError:r(I=>{p(I instanceof Error?I.message:"Failed to update profile.")},"onError")}),k=we({mutationFn:r(async I=>{if(!s)throw new Error("Select an organization before uploading a profile avatar.");const T=await dv.uploadImage(s,I,`profiles/${f.data?.user.id??"board-user"}`);return g({name:v(),image:T.contentPath})},"mutationFn"),onSuccess:r(I=>{p(null),c(I.name??""),u(I.image??"")},"onSuccess"),onError:r(I=>{p(I instanceof Error?I.message:"Failed to upload avatar.")},"onError")}),w=we({mutationFn:r(()=>g({name:v(),image:null}),"mutationFn"),onSuccess:r(I=>{p(null),c(I.name??""),u(I.image??"")},"onSuccess"),onError:r(I=>{p(I instanceof Error?I.message:"Failed to remove avatar.")},"onError")});if(f.isLoading)return(0,t.jsx)("div",{className:"text-sm text-muted-foreground",children:"Loading profile..."});if(f.error||!f.data)return(0,t.jsx)("div",{className:"text-sm text-destructive",children:f.error instanceof Error?f.error.message:"Failed to load profile."});const N=l.trim()||f.data.user.name||"Board",S=d.trim()||null,C=Zps(N),_=y.isPending||k.isPending||w.isPending,R=n?`Stored in Paperclip file storage for ${n.name}.`:"Select an organization to upload an avatar into Paperclip storage.";return(0,t.jsxs)("div",{className:"max-w-6xl space-y-6",children:[(0,t.jsxs)("div",{className:"space-y-2",children:[(0,t.jsxs)("div",{className:"flex items-center gap-2",children:[(0,t.jsx)($L,{className:"h-5 w-5 text-muted-foreground"}),(0,t.jsx)("h1",{className:"text-lg font-semibold",children:"Profile"})]}),(0,t.jsx)("p",{className:"text-sm text-muted-foreground",children:"Control how your account appears in the sidebar and other board surfaces."})]}),h?(0,t.jsx)("div",{className:"rounded-md border border-destructive/40 bg-destructive/5 px-3 py-2 text-sm text-destructive",children:h}):null,(0,t.jsxs)("section",{className:"space-y-8",children:[(0,t.jsxs)(sn,{className:"block relative overflow-hidden rounded-(--rad-28) border-border/70",children:[(0,t.jsx)("div",{className:"absolute inset-x-0 top-0 h-32 bg-(image:--gradient-extract-26)"}),(0,t.jsx)("div",{className:"absolute inset-0 bg-(image:--gradient-extract-7)"}),(0,t.jsx)("div",{className:"relative p-6 pt-10",children:(0,t.jsxs)("div",{className:"flex flex-wrap items-end gap-5 rounded-(--rad-24) border border-border/70 bg-background/92 p-5 shadow-(--shadow-extract-18) backdrop-blur-sm",children:[(0,t.jsxs)("div",{className:"space-y-3",children:[(0,t.jsxs)("label",{htmlFor:i,className:"group relative block cursor-pointer rounded-full focus-within:outline-none focus-within:ring-2 focus-within:ring-ring focus-within:ring-offset-2 focus-within:ring-offset-background",children:[(0,t.jsx)("input",{ref:o,id:i,type:"file",accept:"image/*",className:"sr-only",disabled:!s||_,onChange:r(I=>{const T=I.target.files?.[0];T&&(k.mutate(T),I.target.value="")},"onChange")}),(0,t.jsx)("span",{className:"absolute inset-0 z-10 rounded-full bg-black/0 transition-colors group-hover:bg-black/14 group-focus-within:bg-black/14"}),(0,t.jsx)("span",{className:"absolute bottom-1 right-1 z-20 flex size-9 items-center justify-center rounded-full border border-background bg-primary text-primary-foreground shadow-sm",children:k.isPending?(0,t.jsx)(st,{className:"size-4 animate-spin"}):(0,t.jsx)(mte,{className:"size-4"})}),(0,t.jsxs)(bo,{size:"lg",className:"data-[size=lg]:size-24 ring-4 ring-background shadow-xl",children:[S?(0,t.jsx)(Jc,{src:S,alt:N}):null,(0,t.jsx)(vo,{children:C})]})]}),(0,t.jsxs)("div",{className:"flex flex-wrap items-center gap-2",children:[(0,t.jsxs)($,{type:"button",variant:"secondary",onClick:r(()=>o.current?.click(),"onClick"),disabled:!s||_,children:[k.isPending?(0,t.jsx)(st,{className:"size-4 animate-spin"}):(0,t.jsx)(mte,{className:"size-4"}),S?"Change photo":"Upload photo"]}),S?(0,t.jsxs)($,{type:"button",variant:"outline",onClick:r(()=>w.mutate(),"onClick"),disabled:_,children:[w.isPending?(0,t.jsx)(st,{className:"size-4 animate-spin"}):(0,t.jsx)(ma,{className:"size-4"}),"Remove"]}):null]})]}),(0,t.jsxs)("div",{className:"min-w-0 flex-1 space-y-2 pb-1",children:[(0,t.jsxs)("div",{children:[(0,t.jsx)("h2",{className:"truncate text-2xl font-semibold text-foreground",children:N}),(0,t.jsx)("p",{className:"truncate text-sm text-muted-foreground",children:f.data.user.email??"No email"})]}),(0,t.jsxs)("p",{className:"max-w-2xl text-sm leading-6 text-muted-foreground",children:["Click the avatar to upload a new image. ",R]})]})]})})]}),(0,t.jsxs)("form",{className:"grid gap-6 md:grid-cols-2",onSubmit:r(I=>{I.preventDefault(),y.mutate({name:v(),image:d.trim()||null})},"onSubmit"),children:[(0,t.jsxs)("div",{className:"space-y-2",children:[(0,t.jsx)($s,{htmlFor:"profile-name",children:"Display name"}),(0,t.jsx)(dt,{id:"profile-name",value:l,onChange:r(I=>c(I.target.value),"onChange"),maxLength:120,placeholder:"Board"}),(0,t.jsx)("p",{className:"text-xs text-muted-foreground",children:"Shown in the sidebar account footer and comment author surfaces."})]}),(0,t.jsxs)("div",{className:"space-y-2",children:[(0,t.jsx)($s,{htmlFor:"profile-email",children:"Email"}),(0,t.jsx)(dt,{id:"profile-email",value:f.data.user.email??"",readOnly:!0,disabled:!0}),(0,t.jsx)("p",{className:"text-xs text-muted-foreground",children:"Email is managed by your auth session and is read-only here."})]}),(0,t.jsx)("div",{className:"md:col-span-2 flex justify-end",children:(0,t.jsxs)($,{type:"submit",disabled:_||!l.trim(),children:[y.isPending?(0,t.jsx)(st,{className:"size-4 animate-spin"}):(0,t.jsx)(of,{className:"size-4"}),y.isPending?"Saving...":"Save profile"]})})]}),(0,t.jsx)(Wps,{companyId:s}),(0,t.jsx)(Yps,{userId:f.data.user.id??null})]})]})}r(Jps,"ProfileSettings");function Xps(e){return e?e.split(/\r?\n/).map(s=>s.trim()).find(Boolean)??null:null}r(Xps,"firstNonEmptyLine");function age(e){return Xps(e.lastError)??"Plugin entered an error state without a stored error message."}r(age,"getPluginErrorSummary");function ige(e){if(e.bundledExperimental)return!0;const s=e.packageName??"",n=e.packagePath??"";return s.includes("sandbox")||n.includes("sandbox")?!0:e.manifestJson?.environmentDrivers?.some(a=>a.kind==="sandbox_provider")===!0}r(ige,"isExperimentalPluginIdentity");function oge(){return(0,t.jsx)(ot,{variant:"outline",className:"border-amber-500/30 bg-amber-500/10 text-amber-700 hover:bg-amber-500/10 dark:text-amber-200",children:"Experimental"})}r(oge,"ExperimentalBadge");function efs(){const{selectedCompany:e}=fs(),{setBreadcrumbs:s}=Vn(),n=wt(),{pushToast:a}=Zr(),[i,o]=(0,m.useState)(""),[l,c]=(0,m.useState)(!1),[d,u]=(0,m.useState)(null),[h,p]=(0,m.useState)(""),[f,x]=(0,m.useState)(null);(0,m.useEffect)(()=>{s([{label:e?.name??"Organization",href:"/dashboard"},{label:"Settings",href:"/company/settings"},{label:"Plugins"}])},[e?.name,s]);const{data:g,isLoading:v,error:y}=te({queryKey:D.plugins.all,queryFn:r(()=>El.list(),"queryFn")}),k=te({queryKey:D.plugins.examples,queryFn:r(()=>El.listBundled(),"queryFn")}),w=r(()=>{n.invalidateQueries({queryKey:D.plugins.all}),n.invalidateQueries({queryKey:D.plugins.examples}),n.invalidateQueries({queryKey:D.plugins.uiContributions})},"invalidatePluginQueries"),N=we({mutationFn:r(M=>El.install(M),"mutationFn"),onSuccess:r(()=>{w(),c(!1),o(""),a({title:"Plugin installed successfully",tone:"success"})},"onSuccess"),onError:r(M=>{a({title:"Failed to install plugin",body:M.message,tone:"error"})},"onError")}),S=we({mutationFn:r(M=>El.uninstall(M),"mutationFn"),onSuccess:r(()=>{w(),a({title:"Plugin uninstalled successfully",tone:"success"})},"onSuccess"),onError:r(M=>{a({title:"Failed to uninstall plugin",body:M.message,tone:"error"})},"onError")}),C=we({mutationFn:r(M=>El.enable(M),"mutationFn"),onSuccess:r(()=>{w(),a({title:"Plugin enabled",tone:"success"})},"onSuccess"),onError:r(M=>{a({title:"Failed to enable plugin",body:M.message,tone:"error"})},"onError")}),_=we({mutationFn:r(M=>El.disable(M),"mutationFn"),onSuccess:r(()=>{w(),a({title:"Plugin disabled",tone:"info"})},"onSuccess"),onError:r(M=>{a({title:"Failed to disable plugin",body:M.message,tone:"error"})},"onError")}),R=g??[],I=k.data??[],T=new Map(R.map(M=>[M.packageName,M])),E=new Map(I.map(M=>[M.packageName,M])),P=N.variables?.isLocalPath?N.error?.message??null:null,O=(0,m.useMemo)(()=>new Map(R.map(M=>[M.id,age(M)])),[R]);return v?(0,t.jsx)("div",{className:"p-4 text-sm text-muted-foreground",children:"Loading plugins..."}):y?(0,t.jsx)("div",{className:"p-4 text-sm text-destructive",children:"Failed to load plugins."}):(0,t.jsxs)("div",{className:"max-w-6xl space-y-6",children:[(0,t.jsxs)("div",{className:"flex items-center justify-between",children:[(0,t.jsxs)("div",{className:"flex items-center gap-2",children:[(0,t.jsx)(Mx,{className:"h-6 w-6 text-muted-foreground"}),(0,t.jsx)("h1",{className:"text-xl font-semibold",children:"Plugin Manager"})]}),(0,t.jsxs)(Fs,{open:l,onOpenChange:c,children:[(0,t.jsx)(Gx,{asChild:!0,children:(0,t.jsxs)($,{size:"sm",className:"gap-2",children:[(0,t.jsx)(bn,{className:"h-4 w-4"}),"Install Plugin"]})}),(0,t.jsxs)(Qs,{children:[(0,t.jsxs)(rn,{children:[(0,t.jsx)(Ks,{children:"Install Plugin"}),(0,t.jsx)(mn,{children:"Enter the npm package name of the plugin you wish to install."})]}),(0,t.jsx)("div",{className:"grid gap-4 py-4",children:(0,t.jsxs)("div",{className:"grid gap-2",children:[(0,t.jsx)($s,{htmlFor:"packageName",children:"npm Package Name"}),(0,t.jsx)(dt,{id:"packageName",placeholder:"@tickernelz/paperclip-pro-plugin-example",value:i,onChange:r(M=>o(M.target.value),"onChange")})]})}),(0,t.jsxs)(cr,{children:[(0,t.jsx)($,{variant:"outline",onClick:r(()=>c(!1),"onClick"),children:"Cancel"}),(0,t.jsx)($,{onClick:r(()=>N.mutate({packageName:i}),"onClick"),disabled:!i||N.isPending,children:N.isPending?"Installing...":"Install"})]})]})]})]}),(0,t.jsx)("div",{className:"rounded-lg border border-amber-500/30 bg-amber-500/5 px-4 py-3",children:(0,t.jsxs)("div",{className:"flex items-start gap-3",children:[(0,t.jsx)(Es,{className:"mt-0.5 h-4 w-4 shrink-0 text-amber-700"}),(0,t.jsxs)("div",{className:"space-y-1 text-sm",children:[(0,t.jsx)("p",{className:"font-medium text-foreground",children:"Plugins are alpha."}),(0,t.jsx)("p",{className:"text-muted-foreground",children:"The plugin runtime and API surface are still changing. Expect breaking changes while this feature settles."})]})]})}),(0,t.jsxs)("section",{className:"space-y-3",children:[(0,t.jsxs)("div",{className:"flex items-center gap-2",children:[(0,t.jsx)(rh,{className:"h-5 w-5 text-muted-foreground"}),(0,t.jsx)("h2",{className:"text-base font-semibold",children:"Available Plugins"}),(0,t.jsx)(ot,{variant:"outline",children:"Bundled"})]}),P&&(0,t.jsx)("div",{className:"rounded-md border border-destructive/25 bg-destructive/[0.06] px-4 py-3 text-sm text-destructive whitespace-pre-wrap break-words",children:P}),k.isLoading?(0,t.jsx)("div",{className:"text-sm text-muted-foreground",children:"Loading bundled plugins..."}):k.error?(0,t.jsx)("div",{className:"text-sm text-destructive",children:"Failed to load bundled plugins."}):I.length===0?(0,t.jsx)("div",{className:"rounded-md border border-dashed px-4 py-3 text-sm text-muted-foreground",children:"No bundled plugins were found in this checkout."}):(0,t.jsx)(sn,{className:"block py-0",children:(0,t.jsx)("ul",{className:"divide-y",children:I.map(M=>{const Q=T.get(M.packageName),L=N.isPending&&N.variables?.isLocalPath&&N.variables.packageName===M.localPath;return(0,t.jsx)("li",{children:(0,t.jsxs)("div",{className:"flex items-center gap-4 px-4 py-3",children:[(0,t.jsxs)("div",{className:"min-w-0 flex-1",children:[(0,t.jsxs)("div",{className:"flex flex-wrap items-center gap-2",children:[(0,t.jsx)("span",{className:"font-medium",children:M.displayName}),(0,t.jsx)(ot,{variant:"outline",children:M.tag==="first-party"?"First-party":"Example"}),ige({packageName:M.packageName,packagePath:M.localPath,bundledExperimental:M.experimental})&&(0,t.jsx)(oge,{}),Q?(0,t.jsx)(ot,{variant:Q.status==="ready"?"default":"secondary",className:Q.status==="ready"?"bg-green-600 hover:bg-green-700":"",children:Q.status}):(0,t.jsx)(ot,{variant:"secondary",children:"Not installed"})]}),(0,t.jsx)("p",{className:"mt-1 text-sm text-muted-foreground",children:M.description}),(0,t.jsx)("p",{className:"mt-1 text-xs text-muted-foreground",children:M.packageName}),L&&!M.hasBuiltEntrypoints&&(0,t.jsx)("p",{className:"mt-2 text-xs text-muted-foreground",children:"Building plugin..."})]}),(0,t.jsx)("div",{className:"flex items-center gap-2 shrink-0",children:Q?(0,t.jsxs)(t.Fragment,{children:[Q.status!=="ready"&&(0,t.jsx)($,{variant:"outline",size:"sm",disabled:C.isPending,onClick:r(()=>C.mutate(Q.id),"onClick"),children:"Enable"}),(0,t.jsx)($,{variant:"outline",size:"sm",asChild:!0,children:(0,t.jsx)(We,{to:`/company/settings/instance/plugins/${Q.id}`,children:Q.status==="ready"?"Open Settings":"Review"})})]}):(0,t.jsx)($,{size:"sm",disabled:L||N.isPending,onClick:r(()=>N.mutate({packageName:M.localPath,isLocalPath:!0}),"onClick"),children:L?"Installing...":"Install"})})]})},M.packageName)})})})]}),(0,t.jsxs)("section",{className:"space-y-3",children:[(0,t.jsxs)("div",{className:"flex items-center gap-2",children:[(0,t.jsx)(Mx,{className:"h-5 w-5 text-muted-foreground"}),(0,t.jsx)("h2",{className:"text-base font-semibold",children:"Installed Plugins"})]}),R.length?(0,t.jsx)(sn,{className:"block py-0",children:(0,t.jsx)("ul",{className:"divide-y",children:R.map(M=>(0,t.jsx)("li",{children:(0,t.jsxs)("div",{className:"flex items-start gap-4 px-4 py-3",children:[(0,t.jsxs)("div",{className:"min-w-0 flex-1",children:[(0,t.jsxs)("div",{className:"flex flex-wrap items-center gap-2",children:[(0,t.jsx)(We,{to:`/company/settings/instance/plugins/${M.id}`,className:"font-medium hover:underline truncate block",title:M.manifestJson.displayName??M.packageName,children:M.manifestJson.displayName??M.packageName}),E.has(M.packageName)&&(0,t.jsx)(ot,{variant:"outline",children:E.get(M.packageName)?.tag==="first-party"?"First-party":"Example"}),ige({packageName:M.packageName,packagePath:M.packagePath,manifestJson:M.manifestJson,bundledExperimental:E.get(M.packageName)?.experimental})&&(0,t.jsx)(oge,{})]}),(0,t.jsx)("div",{children:(0,t.jsxs)("p",{className:"text-xs text-muted-foreground mt-0.5 truncate",title:M.packageName,children:[M.packageName," · v",M.manifestJson.version??M.version]})}),(0,t.jsx)("p",{className:"text-sm text-muted-foreground truncate mt-0.5",title:M.manifestJson.description,children:M.manifestJson.description||"No description provided."}),M.status==="error"&&(0,t.jsx)("div",{className:"mt-3 rounded-md border border-red-500/25 bg-red-500/[0.06] px-3 py-2",children:(0,t.jsxs)("div",{className:"flex flex-wrap items-start gap-3",children:[(0,t.jsxs)("div",{className:"min-w-0 flex-1",children:[(0,t.jsxs)("div",{className:"flex items-center gap-2 text-sm font-medium text-red-700 dark:text-red-300",children:[(0,t.jsx)(Es,{className:"h-4 w-4 shrink-0"}),(0,t.jsx)("span",{children:"Plugin error"})]}),(0,t.jsx)("p",{className:"mt-1 text-sm text-red-700/90 dark:text-red-200/90 break-words",title:M.lastError??void 0,children:O.get(M.id)})]}),(0,t.jsx)($,{variant:"outline",size:"sm",className:"border-red-500/30 bg-background/60 text-red-700 hover:bg-red-500/10 hover:text-red-800 dark:text-red-200 dark:hover:text-red-100",onClick:r(()=>x(M),"onClick"),children:"View full error"})]})})]}),(0,t.jsx)("div",{className:"flex shrink-0 self-center",children:(0,t.jsxs)("div",{className:"flex flex-col items-end gap-2",children:[(0,t.jsxs)("div",{className:"flex items-center gap-2",children:[(0,t.jsx)(ot,{variant:M.status==="ready"?"default":M.status==="error"?"destructive":"secondary",className:W("shrink-0",M.status==="ready"?"bg-green-600 hover:bg-green-700":""),children:M.status}),(0,t.jsx)($,{variant:"outline",size:"icon-sm",className:"h-8 w-8",title:M.status==="ready"?"Disable":"Enable",onClick:r(()=>{M.status==="ready"?_.mutate(M.id):C.mutate(M.id)},"onClick"),disabled:C.isPending||_.isPending,children:(0,t.jsx)(bW,{className:W("h-4 w-4",M.status==="ready"?"text-green-600":"")})}),(0,t.jsx)($,{variant:"outline",size:"icon-sm",className:"h-8 w-8 text-destructive hover:text-destructive",title:"Uninstall",onClick:r(()=>{u(M.id),p(M.manifestJson.displayName??M.packageName)},"onClick"),disabled:S.isPending,children:(0,t.jsx)(ma,{className:"h-4 w-4"})})]}),(0,t.jsx)($,{variant:"outline",size:"sm",className:"mt-2 h-8",asChild:!0,children:(0,t.jsxs)(We,{to:`/company/settings/instance/plugins/${M.id}`,children:[(0,t.jsx)(Iu,{className:"h-4 w-4"}),"Configure"]})})]})})]})},M.id))})}):(0,t.jsx)(sn,{className:"bg-muted/30",children:(0,t.jsxs)(Xa,{className:"flex flex-col items-center justify-center py-10",children:[(0,t.jsx)(Mx,{className:"h-10 w-10 text-muted-foreground mb-4"}),(0,t.jsx)("p",{className:"text-sm font-medium",children:"No plugins installed"}),(0,t.jsx)("p",{className:"text-xs text-muted-foreground mt-1",children:"Install a plugin to extend functionality."})]})})]}),(0,t.jsx)(Fs,{open:d!==null,onOpenChange:r(M=>{M||u(null)},"onOpenChange"),children:(0,t.jsxs)(Qs,{children:[(0,t.jsxs)(rn,{children:[(0,t.jsx)(Ks,{children:"Uninstall Plugin"}),(0,t.jsxs)(mn,{children:["Are you sure you want to uninstall ",(0,t.jsx)("strong",{children:h}),"? This action cannot be undone."]})]}),(0,t.jsxs)(cr,{children:[(0,t.jsx)($,{variant:"outline",onClick:r(()=>u(null),"onClick"),children:"Cancel"}),(0,t.jsx)($,{variant:"destructive",disabled:S.isPending,onClick:r(()=>{d&&S.mutate(d,{onSettled:r(()=>u(null),"onSettled")})},"onClick"),children:S.isPending?"Uninstalling...":"Uninstall"})]})]})}),(0,t.jsx)(Fs,{open:f!==null,onOpenChange:r(M=>{M||x(null)},"onOpenChange"),children:(0,t.jsxs)(Qs,{className:"sm:max-w-2xl",children:[(0,t.jsxs)(rn,{children:[(0,t.jsx)(Ks,{children:"Error Details"}),(0,t.jsxs)(mn,{children:[f?.manifestJson.displayName??f?.packageName??"Plugin"," hit an error state."]})]}),(0,t.jsxs)("div",{className:"space-y-4",children:[(0,t.jsx)("div",{className:"rounded-md border border-red-500/25 bg-red-500/[0.06] px-4 py-3",children:(0,t.jsxs)("div",{className:"flex items-start gap-3",children:[(0,t.jsx)(Es,{className:"mt-0.5 h-4 w-4 shrink-0 text-red-700 dark:text-red-300"}),(0,t.jsxs)("div",{className:"space-y-1 text-sm",children:[(0,t.jsx)("p",{className:"font-medium text-red-700 dark:text-red-300",children:"What errored"}),(0,t.jsx)("p",{className:"text-red-700/90 dark:text-red-200/90 break-words",children:f?age(f):"No error summary available."})]})]})}),(0,t.jsxs)("div",{className:"space-y-2",children:[(0,t.jsx)("p",{className:"text-sm font-medium",children:"Full error output"}),(0,t.jsx)("pre",{className:"max-h-(--sz-50vh) overflow-auto rounded-md border bg-muted/40 p-3 text-xs leading-5 whitespace-pre-wrap break-words",children:f?.lastError??"No stored error message."})]})]}),(0,t.jsx)(cr,{children:(0,t.jsx)($,{variant:"outline",onClick:r(()=>x(null),"onClick"),children:"Close"})})]})})]})}r(efs,"PluginManager");function tfs(){const{selectedCompany:e,selectedCompanyId:s}=fs(),{setBreadcrumbs:n}=Vn(),{companyPrefix:a,pluginId:i}=xa(),{hideHostPaths:o}=rA(),[l,c]=(0,m.useState)("configuration"),{data:d,isLoading:u}=te({queryKey:D.plugins.detail(i),queryFn:r(()=>El.get(i),"queryFn"),enabled:!!i}),{data:h,isLoading:p}=te({queryKey:D.plugins.health(i),queryFn:r(()=>El.health(i),"queryFn"),enabled:!!i&&d?.status==="ready",refetchInterval:3e4}),{data:f}=te({queryKey:D.plugins.dashboard(i),queryFn:r(()=>El.dashboard(i),"queryFn"),enabled:!!i,refetchInterval:3e4}),{data:x}=te({queryKey:D.plugins.logs(i),queryFn:r(()=>El.logs(i,{limit:50}),"queryFn"),enabled:!!i&&d?.status==="ready",refetchInterval:3e4}),g=d?.manifestJson?.instanceConfigSchema,v=g&&g.properties&&Object.keys(g.properties).length>0,y=i&&s?D.plugins.config(i,s):["plugins",i??"__missing_plugin__","companies","__missing_company__","config"],{data:k,isLoading:w}=te({queryKey:y,queryFn:r(()=>El.getConfig(i,s),"queryFn"),enabled:!!i&&!!v&&!!s}),{slots:N}=Bd({slotTypes:["settingsPage"],companyId:s,enabled:!!s}),S=N.filter(Q=>Q.pluginId===i),C=S.length>0;if((0,m.useEffect)(()=>{n([{label:e?.name??"Organization",href:"/dashboard"},{label:"Settings",href:"/company/settings"},{label:"Plugins",href:"/company/settings/instance/plugins"},{label:d?.manifestJson?.displayName??d?.packageName??"Plugin Details"}])},[e?.name,n,a,d]),(0,m.useEffect)(()=>{c("configuration")},[i]),u)return(0,t.jsx)("div",{className:"p-4 text-sm text-muted-foreground",children:"Loading plugin details..."});if(!d)return(0,t.jsx)(In,{to:"/company/settings/instance/plugins",replace:!0});const _=d.status,R=d.status==="ready"?"default":d.status==="error"?"destructive":"secondary",I=d.manifestJson.description||"No description provided.",T=d.manifestJson.capabilities??[],E=d.manifestJson.environmentDrivers??[],P=d.manifestJson.localFolders??[],O=P.length>0&&!o,M=E.map(Q=>Q.displayName?.trim()||Q.driverKey).filter((Q,L,F)=>F.indexOf(Q)===L).join(", ");return(0,t.jsxs)("div",{className:"max-w-6xl space-y-6",children:[(0,t.jsxs)("div",{className:"flex items-center gap-4",children:[(0,t.jsx)(We,{to:"/company/settings/instance/plugins",children:(0,t.jsx)($,{variant:"outline",size:"icon",className:"h-8 w-8",children:(0,t.jsx)(wl,{className:"h-4 w-4"})})}),(0,t.jsxs)("div",{className:"flex items-center gap-2",children:[(0,t.jsx)(Mx,{className:"h-6 w-6 text-muted-foreground"}),(0,t.jsx)("h1",{className:"text-xl font-semibold",children:d.manifestJson.displayName??d.packageName}),(0,t.jsx)(ot,{variant:R,className:"ml-2",children:_}),(0,t.jsxs)(ot,{variant:"outline",className:"ml-1",children:["v",d.manifestJson.version??d.version]})]})]}),(0,t.jsxs)(Li,{value:l,onValueChange:r(Q=>c(Q),"onValueChange"),className:"space-y-6",children:[(0,t.jsx)(Yc,{align:"start",items:[{value:"configuration",label:"Configuration"},{value:"status",label:"Status"}],value:l,onValueChange:r(Q=>c(Q),"onValueChange")}),(0,t.jsx)(pa,{value:"configuration",className:"space-y-6",children:(0,t.jsxs)("div",{className:"space-y-8",children:[(0,t.jsxs)("section",{className:"space-y-5",children:[(0,t.jsx)("h2",{className:"text-base font-semibold",children:"About"}),(0,t.jsxs)("div",{className:"grid gap-8 lg:grid-cols-(--gtc-52)",children:[(0,t.jsxs)("div",{className:"space-y-2",children:[(0,t.jsx)("h3",{className:"text-sm font-medium text-muted-foreground",children:"Description"}),(0,t.jsx)("p",{className:"text-sm leading-6 text-foreground/90",children:I})]}),(0,t.jsxs)("div",{className:"space-y-4 text-sm",children:[(0,t.jsxs)("div",{className:"space-y-1.5",children:[(0,t.jsx)("h3",{className:"font-medium text-muted-foreground",children:"Author"}),(0,t.jsx)("p",{className:"text-foreground",children:d.manifestJson.author})]}),(0,t.jsxs)("div",{className:"space-y-2",children:[(0,t.jsx)("h3",{className:"font-medium text-muted-foreground",children:"Categories"}),(0,t.jsx)("div",{className:"flex flex-wrap gap-2",children:d.categories.length>0?d.categories.map(Q=>(0,t.jsx)(ot,{variant:"outline",className:"capitalize",children:Q},Q)):(0,t.jsx)("span",{className:"text-foreground",children:"None"})})]})]})]})]}),(0,t.jsx)(Wl,{}),(0,t.jsxs)("section",{className:"space-y-4",children:[(0,t.jsx)("div",{className:"space-y-1",children:(0,t.jsx)("h2",{className:"text-base font-semibold",children:"Settings"})}),O?(0,t.jsx)(sfs,{pluginId:i,companyId:s,declarations:P}):null,C?(0,t.jsx)("div",{className:"space-y-3",children:S.map(Q=>(0,t.jsx)(vm,{slot:Q,context:{companyId:s,companyPrefix:a??null},missingBehavior:"placeholder"},`${Q.pluginKey}:${Q.id}`))}):v?(0,t.jsx)(ofs,{pluginId:i,companyId:s,schema:g,initialValues:k?.configJson,isLoading:w,pluginStatus:d.status,supportsConfigTest:d.supportsConfigTest===!0}):E.length>0?(0,t.jsxs)("div",{className:"rounded-md border border-border/60 bg-muted/20 px-4 py-3 text-sm",children:[(0,t.jsx)("p",{className:"font-medium text-foreground",children:"Configure this plugin from Settings → Environments."}),(0,t.jsxs)("p",{className:"mt-1 text-muted-foreground",children:[M||"This plugin"," registers environment runtime settings there so the execution target stays instance-scoped while secret bindings still resolve through the selected organization context."]}),(0,t.jsx)("div",{className:"mt-3",children:(0,t.jsx)(We,{to:"/company/settings/instance/environments",children:(0,t.jsx)($,{variant:"outline",size:"sm",children:"Open Environments"})})})]}):O?null:(0,t.jsx)("p",{className:"text-sm text-muted-foreground",children:"This plugin does not require any settings."})]})]})}),(0,t.jsx)(pa,{value:"status",className:"space-y-6",children:(0,t.jsxs)("div",{className:"grid gap-6 xl:grid-cols-(--gtc-39)",children:[(0,t.jsxs)("div",{className:"space-y-6",children:[(0,t.jsxs)(sn,{children:[(0,t.jsxs)(mo,{children:[(0,t.jsxs)(Oo,{className:"text-base flex items-center gap-1.5",children:[(0,t.jsx)(Vm,{className:"h-4 w-4"}),"Runtime Dashboard"]}),(0,t.jsx)(Vc,{children:"Worker process, scheduled jobs, and webhook deliveries"})]}),(0,t.jsx)(Xa,{className:"space-y-6",children:f?(0,t.jsxs)(t.Fragment,{children:[(0,t.jsxs)("div",{children:[(0,t.jsxs)("h3",{className:"text-sm font-medium mb-3 flex items-center gap-1.5",children:[(0,t.jsx)(Vm,{className:"h-3.5 w-3.5 text-muted-foreground"}),"Worker Process"]}),f.worker?(0,t.jsxs)("div",{className:"grid grid-cols-2 gap-3 text-sm",children:[(0,t.jsxs)("div",{className:"flex justify-between",children:[(0,t.jsx)("span",{className:"text-muted-foreground",children:"Status"}),(0,t.jsx)(ot,{variant:f.worker.status==="running"?"default":"secondary",children:f.worker.status})]}),(0,t.jsxs)("div",{className:"flex justify-between",children:[(0,t.jsx)("span",{className:"text-muted-foreground",children:"PID"}),(0,t.jsx)("span",{className:"font-mono text-xs",children:f.worker.pid??"—"})]}),(0,t.jsxs)("div",{className:"flex justify-between",children:[(0,t.jsx)("span",{className:"text-muted-foreground",children:"Uptime"}),(0,t.jsx)("span",{className:"text-xs",children:lfs(f.worker.uptime)})]}),(0,t.jsxs)("div",{className:"flex justify-between",children:[(0,t.jsx)("span",{className:"text-muted-foreground",children:"Pending RPCs"}),(0,t.jsx)("span",{className:"text-xs",children:f.worker.pendingRequests})]}),f.worker.totalCrashes>0&&(0,t.jsxs)(t.Fragment,{children:[(0,t.jsxs)("div",{className:"flex justify-between col-span-2",children:[(0,t.jsxs)("span",{className:"text-muted-foreground flex items-center gap-1",children:[(0,t.jsx)(Es,{className:"h-3 w-3 text-amber-500"}),"Crashes"]}),(0,t.jsxs)("span",{className:"text-xs",children:[f.worker.consecutiveCrashes," consecutive / ",f.worker.totalCrashes," total"]})]}),f.worker.lastCrashAt&&(0,t.jsxs)("div",{className:"flex justify-between col-span-2",children:[(0,t.jsx)("span",{className:"text-muted-foreground",children:"Last Crash"}),(0,t.jsx)("span",{className:"text-xs",children:cfs(f.worker.lastCrashAt)})]})]})]}):(0,t.jsx)("p",{className:"text-sm text-muted-foreground italic",children:"No worker process registered."})]}),(0,t.jsx)(Wl,{}),(0,t.jsxs)("div",{children:[(0,t.jsxs)("h3",{className:"text-sm font-medium mb-3 flex items-center gap-1.5",children:[(0,t.jsx)(Fb,{className:"h-3.5 w-3.5 text-muted-foreground"}),"Recent Job Runs"]}),f.recentJobRuns.length>0?(0,t.jsx)("div",{className:"space-y-2",children:f.recentJobRuns.map(Q=>(0,t.jsxs)("div",{className:"flex items-center justify-between gap-2 rounded-md bg-muted/50 px-2 py-1.5 text-sm",children:[(0,t.jsxs)("div",{className:"flex min-w-0 items-center gap-2",children:[(0,t.jsx)(dfs,{status:Q.status}),(0,t.jsx)("span",{className:"truncate font-mono text-xs",title:Q.jobKey??Q.jobId,children:Q.jobKey??Q.jobId.slice(0,8)}),(0,t.jsx)(ot,{variant:"outline",className:"px-1 py-0 text-(length:--text-nano)",children:Q.trigger})]}),(0,t.jsxs)("div",{className:"flex shrink-0 items-center gap-2 text-xs text-muted-foreground",children:[Q.durationMs!=null?(0,t.jsx)("span",{children:cge(Q.durationMs)}):null,(0,t.jsx)("span",{title:Q.createdAt,children:dge(Q.createdAt)})]})]},Q.id))}):(0,t.jsx)("p",{className:"text-sm text-muted-foreground italic",children:"No job runs recorded yet."})]}),(0,t.jsx)(Wl,{}),(0,t.jsxs)("div",{children:[(0,t.jsxs)("h3",{className:"text-sm font-medium mb-3 flex items-center gap-1.5",children:[(0,t.jsx)(CW,{className:"h-3.5 w-3.5 text-muted-foreground"}),"Recent Webhook Deliveries"]}),f.recentWebhookDeliveries.length>0?(0,t.jsx)("div",{className:"space-y-2",children:f.recentWebhookDeliveries.map(Q=>(0,t.jsxs)("div",{className:"flex items-center justify-between gap-2 rounded-md bg-muted/50 px-2 py-1.5 text-sm",children:[(0,t.jsxs)("div",{className:"flex min-w-0 items-center gap-2",children:[(0,t.jsx)(ufs,{status:Q.status}),(0,t.jsx)("span",{className:"truncate font-mono text-xs",title:Q.webhookKey,children:Q.webhookKey})]}),(0,t.jsxs)("div",{className:"flex shrink-0 items-center gap-2 text-xs text-muted-foreground",children:[Q.durationMs!=null?(0,t.jsx)("span",{children:cge(Q.durationMs)}):null,(0,t.jsx)("span",{title:Q.createdAt,children:dge(Q.createdAt)})]})]},Q.id))}):(0,t.jsx)("p",{className:"text-sm text-muted-foreground italic",children:"No webhook deliveries recorded yet."})]}),(0,t.jsxs)("div",{className:"flex items-center gap-1.5 border-t border-border/50 pt-2 text-xs text-muted-foreground",children:[(0,t.jsx)(No,{className:"h-3 w-3"}),"Last checked: ",new Date(f.checkedAt).toLocaleTimeString()]})]}):(0,t.jsx)("p",{className:"text-sm text-muted-foreground",children:"Runtime diagnostics are unavailable right now."})})]}),x&&x.length>0?(0,t.jsxs)(sn,{children:[(0,t.jsxs)(mo,{children:[(0,t.jsxs)(Oo,{className:"text-base flex items-center gap-1.5",children:[(0,t.jsx)(fte,{className:"h-4 w-4"}),"Recent Logs"]}),(0,t.jsxs)(Vc,{children:["Last ",x.length," log entries"]})]}),(0,t.jsx)(Xa,{children:(0,t.jsx)("div",{className:"max-h-64 space-y-1 overflow-y-auto font-mono text-xs",children:x.map(Q=>(0,t.jsxs)("div",{className:`flex gap-2 py-0.5 ${Q.level==="error"?"text-destructive":Q.level==="warn"?"text-yellow-600 dark:text-yellow-400":Q.level==="debug"?"text-muted-foreground/60":"text-muted-foreground"}`,children:[(0,t.jsx)("span",{className:"shrink-0 text-muted-foreground/50",children:new Date(Q.createdAt).toLocaleTimeString()}),(0,t.jsx)(ot,{variant:"outline",className:"h-4 shrink-0 px-1 text-(length:--text-nano)",children:Q.level}),(0,t.jsx)("span",{className:"truncate",title:Q.message,children:Q.message})]},Q.id))})})]}):null]}),(0,t.jsxs)("div",{className:"space-y-6",children:[(0,t.jsxs)(sn,{children:[(0,t.jsx)(mo,{children:(0,t.jsxs)(Oo,{className:"text-base flex items-center gap-1.5",children:[(0,t.jsx)(fte,{className:"h-4 w-4"}),"Health Status"]})}),(0,t.jsx)(Xa,{children:p?(0,t.jsx)("p",{className:"text-sm text-muted-foreground",children:"Checking health..."}):h?(0,t.jsxs)("div",{className:"space-y-4 text-sm",children:[(0,t.jsxs)("div",{className:"flex items-center justify-between",children:[(0,t.jsx)("span",{className:"text-muted-foreground",children:"Overall"}),(0,t.jsx)(ot,{variant:h.healthy?"default":"destructive",children:h.status})]}),h.checks.length>0?(0,t.jsx)("div",{className:"space-y-2 border-t border-border/50 pt-2",children:h.checks.map((Q,L)=>(0,t.jsxs)("div",{className:"flex items-start justify-between gap-2",children:[(0,t.jsx)("span",{className:"truncate text-muted-foreground",title:Q.name,children:Q.name}),Q.passed?(0,t.jsx)(aKe,{className:"h-4 w-4 shrink-0 text-green-500"}):(0,t.jsx)(yd,{className:"h-4 w-4 shrink-0 text-destructive"})]},L))}):null,h.lastError?(0,t.jsx)("div",{className:"break-words rounded border border-destructive/20 bg-destructive/10 p-2 text-xs text-destructive",children:h.lastError}):null]}):(0,t.jsxs)("div",{className:"space-y-3 text-sm text-muted-foreground",children:[(0,t.jsxs)("div",{className:"flex items-center justify-between",children:[(0,t.jsx)("span",{children:"Lifecycle"}),(0,t.jsx)(ot,{variant:R,children:_})]}),(0,t.jsx)("p",{children:"Health checks run once the plugin is ready."}),d.lastError?(0,t.jsx)("div",{className:"break-words rounded border border-destructive/20 bg-destructive/10 p-2 text-xs text-destructive",children:d.lastError}):null]})})]}),(0,t.jsxs)(sn,{children:[(0,t.jsx)(mo,{children:(0,t.jsx)(Oo,{className:"text-base",children:"Details"})}),(0,t.jsxs)(Xa,{className:"space-y-3 text-sm text-muted-foreground",children:[(0,t.jsxs)("div",{className:"flex justify-between gap-3",children:[(0,t.jsx)("span",{children:"Plugin ID"}),(0,t.jsx)("span",{className:"font-mono text-xs text-right",children:d.id})]}),(0,t.jsxs)("div",{className:"flex justify-between gap-3",children:[(0,t.jsx)("span",{children:"Plugin Key"}),(0,t.jsx)("span",{className:"font-mono text-xs text-right",children:d.pluginKey})]}),(0,t.jsxs)("div",{className:"flex justify-between gap-3",children:[(0,t.jsx)("span",{children:"NPM Package"}),(0,t.jsx)("span",{className:"max-w-(--sz-170px) truncate text-right text-xs",title:d.packageName,children:d.packageName})]}),(0,t.jsxs)("div",{className:"flex justify-between gap-3",children:[(0,t.jsx)("span",{children:"Version"}),(0,t.jsxs)("span",{className:"text-right text-foreground",children:["v",d.manifestJson.version??d.version]})]})]})]}),(0,t.jsxs)(sn,{children:[(0,t.jsx)(mo,{children:(0,t.jsxs)(Oo,{className:"text-base flex items-center gap-1.5",children:[(0,t.jsx)(Tc,{className:"h-4 w-4"}),"Permissions"]})}),(0,t.jsx)(Xa,{children:T.length>0?(0,t.jsx)("ul",{className:"space-y-2 text-sm text-muted-foreground",children:T.map(Q=>(0,t.jsx)("li",{className:"rounded-md bg-muted/40 px-2.5 py-2 font-mono text-xs text-foreground/85",children:Q},Q))}):(0,t.jsx)("p",{className:"text-sm text-muted-foreground italic",children:"No special permissions requested."})})]})]})]})})]})]})}r(tfs,"PluginSettings");function sfs({pluginId:e,companyId:s,declarations:n}){const{data:a,isLoading:i,error:o}=te({queryKey:s?D.plugins.localFolders(e,s):["plugins",e,"companies","none","local-folders"],queryFn:r(()=>El.listLocalFolders(e,s),"queryFn"),enabled:!!s}),l=new Map((a?.folders??[]).map(c=>[c.folderKey,c]));return s?(0,t.jsxs)("div",{className:"space-y-3",children:[(0,t.jsxs)("div",{className:"flex items-center gap-2",children:[(0,t.jsx)(nl,{className:"h-4 w-4 text-muted-foreground"}),(0,t.jsx)("h3",{className:"text-sm font-medium",children:"Local folders"})]}),o?(0,t.jsx)("div",{className:"rounded-md border border-destructive/20 bg-destructive/10 px-3 py-2 text-sm text-destructive",children:o.message||"Failed to load local folder settings."}):null,i?(0,t.jsxs)("div",{className:"flex items-center gap-2 py-3 text-sm text-muted-foreground",children:[(0,t.jsx)(st,{className:"h-4 w-4 animate-spin"}),"Loading local folders..."]}):(0,t.jsx)("div",{className:"space-y-3",children:n.map(c=>(0,t.jsx)(nfs,{pluginId:e,companyId:s,declaration:c,status:l.get(c.folderKey)},c.folderKey))})]}):(0,t.jsx)("div",{className:"rounded-md border border-border/60 bg-muted/20 px-4 py-3 text-sm text-muted-foreground",children:"Select an organization to configure this plugin's local folders."})}r(sfs,"PluginLocalFoldersSettings");function nfs({pluginId:e,companyId:s,declaration:n,status:a}){const i=wt(),o=a?.path??"",[l,c]=(0,m.useState)(o),[d,u]=(0,m.useState)(null);(0,m.useEffect)(()=>{c(o),u(null)},[o,n.folderKey]);const h=we({mutationFn:r(v=>El.configureLocalFolder(e,s,n.folderKey,{path:v,access:n.access,requiredDirectories:n.requiredDirectories,requiredFiles:n.requiredFiles}),"mutationFn"),onSuccess:r(v=>{u({type:v.healthy?"success":"error",text:v.healthy?"Local folder saved.":"Local folder saved, but validation still needs attention."}),i.invalidateQueries({queryKey:D.plugins.localFolders(e,s)})},"onSuccess"),onError:r(v=>{u({type:"error",text:v.message||"Failed to save local folder."})},"onError")}),p=l.trim(),f=p!==o,x=a?.access??n.access??"readWrite",g=(0,m.useCallback)(()=>{if(!p){u({type:"error",text:"Local folder path is required."});return}if(!ifs(p)){u({type:"error",text:"Local folder must be a full absolute path."});return}u(null),h.mutate(p)},[h,p]);return(0,t.jsxs)("div",{className:"space-y-4 rounded-md border border-border/70 bg-background px-4 py-4",children:[(0,t.jsxs)("div",{className:"flex flex-wrap items-start justify-between gap-3",children:[(0,t.jsxs)("div",{className:"min-w-0 space-y-1",children:[(0,t.jsxs)("div",{className:"flex flex-wrap items-center gap-2",children:[(0,t.jsx)("h4",{className:"text-sm font-medium",children:n.displayName}),(0,t.jsx)(ot,{variant:"outline",className:"font-mono text-(length:--text-nano)",children:n.folderKey}),(0,t.jsx)(ot,{variant:a?.healthy?"default":"secondary",children:a?.healthy?"Healthy":"Needs attention"})]}),n.description?(0,t.jsx)("p",{className:"max-w-3xl text-sm leading-5 text-muted-foreground",children:n.description}):null]}),(0,t.jsx)(ot,{variant:x==="readWrite"?"default":"outline",children:x==="readWrite"?"Read/write":"Read only"})]}),(0,t.jsxs)("div",{className:"grid gap-3 text-sm sm:grid-cols-3",children:[(0,t.jsx)(qB,{label:"Configured",value:a?.configured?"Yes":"No",ok:!!a?.configured}),(0,t.jsx)(qB,{label:"Readable",value:a?.readable?"Yes":"No",ok:!!a?.readable}),(0,t.jsx)(qB,{label:"Writable",value:x==="read"?"Not requested":a?.writable?"Yes":"No",ok:x==="read"||!!a?.writable})]}),a?.path?(0,t.jsxs)("div",{className:"space-y-1 text-sm",children:[(0,t.jsx)("div",{className:"text-xs font-medium text-muted-foreground",children:"Configured path"}),(0,t.jsx)("div",{className:"break-all rounded-md bg-muted/60 px-2 py-1.5 font-mono text-xs text-foreground",children:a.path})]}):null,(0,t.jsxs)("div",{className:"space-y-1.5",children:[(0,t.jsx)("label",{className:"text-xs font-medium text-muted-foreground",htmlFor:`local-folder-${n.folderKey}`,children:"Local folder path"}),(0,t.jsxs)("div",{className:"flex items-center gap-2",children:[(0,t.jsx)("input",{id:`local-folder-${n.folderKey}`,className:"min-w-0 flex-1 rounded-md border border-border bg-background px-2.5 py-1.5 font-mono text-sm outline-none focus:border-foreground/40 focus:ring-2 focus:ring-ring/20",value:l,onChange:r(v=>{c(v.target.value),u(null)},"onChange"),placeholder:"/absolute/path/to/folder"}),(0,t.jsx)(nu,{className:"h-8"}),(0,t.jsxs)($,{size:"sm",onClick:g,disabled:h.isPending||!f||!s,children:[h.isPending?(0,t.jsx)(st,{className:"h-3.5 w-3.5 animate-spin"}):(0,t.jsx)(of,{className:"h-3.5 w-3.5"}),"Save"]})]})]}),(0,t.jsx)(rfs,{status:a,declaration:n}),a?.problems?.length?(0,t.jsxs)("div",{className:"space-y-2 rounded-md border border-destructive/20 bg-destructive/10 px-3 py-2 text-sm text-destructive",children:[(0,t.jsx)("div",{className:"font-medium",children:"Validation problems"}),(0,t.jsx)("ul",{className:"space-y-1",children:a.problems.map((v,y)=>(0,t.jsxs)("li",{children:[v.message,v.path?(0,t.jsxs)("span",{className:"font-mono",children:[" ",v.path]}):null]},`${v.code}:${v.path??""}:${y}`))})]}):null,d?(0,t.jsx)("div",{className:`rounded-md border px-3 py-2 text-sm ${d.type==="success"?"border-green-200 bg-green-50 text-green-700 dark:border-green-900 dark:bg-green-950/30 dark:text-green-400":"border-destructive/20 bg-destructive/10 text-destructive"}`,children:d.text}):null]})}r(nfs,"PluginLocalFolderRow");function qB({label:e,value:s,ok:n}){return(0,t.jsxs)("div",{className:"flex items-center justify-between rounded-md border border-border/60 px-2.5 py-2",children:[(0,t.jsx)("span",{className:"text-muted-foreground",children:e}),(0,t.jsx)(ot,{variant:n?"default":"secondary",children:s})]})}r(qB,"FolderStatusMetric");function rfs({status:e,declaration:s}){const n=e?.requiredDirectories??s.requiredDirectories??[],a=e?.requiredFiles??s.requiredFiles??[],i=e?.missingDirectories??n,o=e?.missingFiles??a,l=afs(e);return n.length===0&&a.length===0?null:(0,t.jsxs)("div",{className:"grid gap-3 text-sm md:grid-cols-2",children:[(0,t.jsx)(lge,{title:"Required directories",items:n,missingItems:i,missingLabel:"Missing directories",inspectionUnavailable:l}),(0,t.jsx)(lge,{title:"Required files",items:a,missingItems:o,missingLabel:"Missing files",inspectionUnavailable:l})]})}r(rfs,"FolderRequirements");function afs(e){return!e?.configured||e.readable?!1:e.problems.some(s=>s.code==="missing"||s.code==="not_readable"||s.code==="not_directory")}r(afs,"isRootNotInspected");function lge({title:e,items:s,missingItems:n,missingLabel:a,inspectionUnavailable:i}){return(0,t.jsxs)("div",{className:"space-y-2 rounded-md border border-border/60 px-3 py-2",children:[(0,t.jsxs)("div",{className:"flex items-center justify-between gap-2",children:[(0,t.jsx)("span",{className:"text-xs font-medium text-muted-foreground",children:e}),i?(0,t.jsx)(ot,{variant:"secondary",className:"text-(length:--text-nano)",children:"Not inspected"}):n.length>0?(0,t.jsxs)(ot,{variant:"destructive",className:"text-(length:--text-nano)",children:[n.length," missing"]}):(0,t.jsx)(ot,{variant:"outline",className:"text-(length:--text-nano)",children:"Present"})]}),s.length>0?(0,t.jsx)("div",{className:"flex flex-wrap gap-1.5",children:s.map(o=>{const l=n.includes(o);return(0,t.jsx)("span",{className:`rounded border px-1.5 py-0.5 font-mono text-(length:--text-micro) ${i?"border-amber-300/60 bg-amber-50 text-amber-700 dark:border-amber-800/70 dark:bg-amber-950/30 dark:text-amber-300":l?"border-destructive/30 bg-destructive/10 text-destructive":"border-border bg-muted/50 text-foreground/80"}`,children:o},o)})}):(0,t.jsx)("p",{className:"text-xs text-muted-foreground",children:"None declared."}),i?(0,t.jsx)("p",{className:"text-xs text-amber-700 dark:text-amber-300",children:"Configured root was not inspected."}):n.length>0?(0,t.jsxs)("p",{className:"text-xs text-destructive",children:[a,": ",n.join(", ")]}):null]})}r(lge,"RequirementList");function ifs(e){return e.startsWith("/")||/^[A-Za-z]:[\\/]/.test(e)||e.startsWith("\\\\")}r(ifs,"isLikelyAbsolutePath");function ofs({pluginId:e,companyId:s,schema:n,initialValues:a,isLoading:i,pluginStatus:o,supportsConfigTest:l}){const c=wt(),[d,u]=(0,m.useState)(()=>({...Zp(n),...a??{}})),h=(0,m.useRef)(!1);(0,m.useEffect)(()=>{h.current=!1,u(Zp(n))},[s,e,n]),(0,m.useEffect)(()=>{a&&!h.current&&(h.current=!0,u({...Zp(n),...a}))},[a,n]);const[p,f]=(0,m.useState)({}),[x,g]=(0,m.useState)(null),[v,y]=(0,m.useState)(null),k=JSON.stringify(d)!==JSON.stringify({...Zp(n),...a??{}}),w=we({mutationFn:r(R=>{if(!s)throw new Error("Select an organization before saving plugin configuration.");return El.saveConfig(e,s,R)},"mutationFn"),onSuccess:r(()=>{g({type:"success",text:"Configuration saved."}),y(null),s&&c.invalidateQueries({queryKey:D.plugins.config(e,s)}),setTimeout(()=>g(null),3e3)},"onSuccess"),onError:r(R=>{g({type:"error",text:R.message||"Failed to save configuration."})},"onError")}),N=we({mutationFn:r(R=>{if(!s)throw new Error("Select an organization before testing plugin configuration.");return El.testConfig(e,s,R)},"mutationFn"),onSuccess:r(R=>{R.valid?y({type:"success",text:"Configuration test passed."}):y({type:"error",text:R.message||"Configuration test failed."})},"onSuccess"),onError:r(R=>{y({type:"error",text:R.message||"Configuration test failed."})},"onError")}),S=(0,m.useCallback)(R=>{u(R),f({}),g(null)},[]),C=(0,m.useCallback)(()=>{const R=bj(n,d);if(Object.keys(R).length>0){f(R);return}f({}),w.mutate(d)},[n,d,w]),_=(0,m.useCallback)(()=>{const R=bj(n,d);if(Object.keys(R).length>0){f(R);return}f({}),y(null),N.mutate(d)},[n,d,N]);return i?(0,t.jsxs)("div",{className:"flex items-center gap-2 text-sm text-muted-foreground py-4",children:[(0,t.jsx)(st,{className:"h-4 w-4 animate-spin"}),"Loading configuration..."]}):(0,t.jsxs)("div",{className:"space-y-4",children:[(0,t.jsx)(U3,{schema:n,values:d,onChange:S,errors:p,disabled:w.isPending}),x&&(0,t.jsx)("div",{className:`text-sm p-2 rounded border ${x.type==="success"?"text-green-700 bg-green-50 border-green-200 dark:text-green-400 dark:bg-green-950/30 dark:border-green-900":"text-destructive bg-destructive/10 border-destructive/20"}`,children:x.text}),v&&(0,t.jsx)("div",{className:`text-sm p-2 rounded border ${v.type==="success"?"text-green-700 bg-green-50 border-green-200 dark:text-green-400 dark:bg-green-950/30 dark:border-green-900":"text-destructive bg-destructive/10 border-destructive/20"}`,children:v.text}),(0,t.jsxs)("div",{className:"flex items-center gap-2 pt-2",children:[(0,t.jsx)($,{onClick:C,disabled:w.isPending||!k,size:"sm",children:w.isPending?(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)(st,{className:"h-3.5 w-3.5 animate-spin"}),"Saving..."]}):"Save Configuration"}),o==="ready"&&l&&(0,t.jsx)($,{variant:"outline",onClick:_,disabled:N.isPending||!s,size:"sm",children:N.isPending?(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)(st,{className:"h-3.5 w-3.5 animate-spin"}),"Testing..."]}):"Test Configuration"})]})]})}r(ofs,"PluginConfigForm");function lfs(e){if(e==null)return"—";const s=Math.floor(e/1e3);if(s<60)return`${s}s`;const n=Math.floor(s/60);if(n<60)return`${n}m ${s%60}s`;const a=Math.floor(n/60);return a<24?`${a}h ${n%60}m`:`${Math.floor(a/24)}d ${a%24}h`}r(lfs,"formatUptime");function cge(e){return e<1e3?`${e}ms`:e<6e4?`${(e/1e3).toFixed(1)}s`:`${(e/6e4).toFixed(1)}m`}r(cge,"formatDuration");function dge(e){const s=Date.now()-new Date(e).getTime();if(s<0)return"just now";const n=Math.floor(s/1e3);if(n<60)return`${n}s ago`;const a=Math.floor(n/60);if(a<60)return`${a}m ago`;const i=Math.floor(a/60);return i<24?`${i}h ago`:`${Math.floor(i/24)}d ago`}r(dge,"formatRelativeTime");function cfs(e){return new Date(e).toLocaleString()}r(cfs,"formatTimestamp");function dfs({status:e}){return(0,t.jsx)("span",{className:`inline-block h-2 w-2 rounded-full shrink-0 ${e==="success"||e==="succeeded"?"bg-green-500":e==="failed"?"bg-red-500":e==="running"?"bg-blue-500 animate-pulse":e==="cancelled"?"bg-gray-400":"bg-amber-500"}`,title:e})}r(dfs,"JobStatusDot");function ufs({status:e}){return(0,t.jsx)("span",{className:`inline-block h-2 w-2 rounded-full shrink-0 ${e==="processed"||e==="success"?"bg-green-500":e==="failed"?"bg-red-500":e==="received"?"bg-blue-500":"bg-amber-500"}`,title:e})}r(ufs,"DeliveryStatusDot");function UB({adapter:e,canRemove:s,onToggle:n,onRemove:a,onReload:i,onReinstall:o,isToggling:l,isReloading:c,isReinstalling:d,overriddenBy:u,toggleTitleEnabled:h,toggleTitleDisabled:p,disabledBadgeLabel:f}){return(0,t.jsx)("li",{children:(0,t.jsxs)("div",{className:"flex items-center gap-4 px-4 py-3",children:[(0,t.jsxs)("div",{className:"min-w-0 flex-1",children:[(0,t.jsxs)("div",{className:"flex flex-wrap items-center gap-2",children:[(0,t.jsx)("span",{className:W("font-medium",e.disabled&&"text-muted-foreground line-through"),children:e.label&&e.label!==e.type?e.label:kf(e.type)}),(0,t.jsx)(ot,{variant:"outline",children:e.source==="external"?"External":"Built-in"}),e.source==="external"&&(e.isLocalPath?(0,t.jsx)("span",{title:"Installed from local path",children:(0,t.jsx)(nl,{className:"h-4 w-4 text-amber-500"})}):(0,t.jsx)("span",{title:"Installed from npm",children:(0,t.jsx)(t0,{className:"h-4 w-4 text-red-500"})})),e.version&&(0,t.jsxs)(ot,{variant:"secondary",className:"font-mono text-(length:--text-nano)",children:["v",e.version]}),e.overriddenBuiltin&&(0,t.jsx)(ot,{variant:"secondary",className:"text-blue-600 border-blue-400",children:"Overrides built-in"}),u&&(0,t.jsxs)(ot,{variant:"secondary",className:"text-blue-600 border-blue-400",children:["Overridden by ",u]}),e.disabled&&(0,t.jsx)(ot,{variant:"secondary",className:"text-amber-600 border-amber-400",children:f??"Hidden from menus"})]}),(0,t.jsxs)("p",{className:"text-xs text-muted-foreground mt-0.5",children:[e.type,e.packageName&&e.packageName!==e.type&&(0,t.jsxs)(t.Fragment,{children:[" · ",e.packageName]})," · ",e.modelsCount," models"]})]}),(0,t.jsxs)("div",{className:"flex items-center gap-2 shrink-0",children:[o&&(0,t.jsx)($,{variant:"outline",size:"icon-sm",className:"h-8 w-8",title:"Reinstall adapter (pull latest from npm)",disabled:d,onClick:r(()=>o(e.type),"onClick"),children:(0,t.jsx)(Fi,{className:W("h-4 w-4",d&&"animate-bounce")})}),i&&(0,t.jsx)($,{variant:"outline",size:"icon-sm",className:"h-8 w-8",title:"Reload adapter (hot-swap)",disabled:c,onClick:r(()=>i(e.type),"onClick"),children:(0,t.jsx)(Ii,{className:W("h-4 w-4",c&&"animate-spin")})}),(0,t.jsx)($,{variant:"outline",size:"icon-sm",className:"h-8 w-8",title:e.disabled?h??"Show in agent menus":p??"Hide from agent menus",disabled:l,onClick:r(()=>n(e.type,!e.disabled),"onClick"),children:(0,t.jsx)(bW,{className:W("h-4 w-4",e.disabled?"text-muted-foreground":"text-green-600")})}),s&&(0,t.jsx)($,{variant:"outline",size:"icon-sm",className:"h-8 w-8 text-destructive hover:text-destructive",title:"Remove adapter",onClick:r(()=>a(e.type),"onClick"),children:(0,t.jsx)(ma,{className:"h-4 w-4"})})]})]})})}r(UB,"AdapterRow");function mfs(e){return fetch(`https://registry.npmjs.org/${encodeURIComponent(e)}/latest`,{signal:AbortSignal.timeout(5e3)}).then(s=>s.json()).then(s=>typeof s?.version=="string"?s.version:null).catch(()=>null)}r(mfs,"fetchNpmLatestVersion");function hfs({adapter:e,open:s,isReinstalling:n,onConfirm:a,onCancel:i}){const{data:o,isLoading:l}=te({queryKey:["npm-latest-version",e?.packageName],queryFn:r(()=>e?.packageName?mfs(e.packageName):null,"queryFn"),enabled:s&&!!e?.packageName,staleTime:6e4}),c=e?.version&&o&&e.version===o;return(0,t.jsx)(Fs,{open:s,onOpenChange:r(d=>{d||i()},"onOpenChange"),children:(0,t.jsxs)(Qs,{children:[(0,t.jsxs)(rn,{children:[(0,t.jsx)(Ks,{children:"Reinstall Adapter"}),(0,t.jsxs)(mn,{children:["This will pull the latest version of"," ",(0,t.jsx)("strong",{children:e?.packageName})," from npm and hot-swap the running adapter module. Existing agents will use the new version on their next run."]})]}),(0,t.jsxs)("div",{className:"rounded-md border bg-muted/50 px-4 py-3 text-sm space-y-1",children:[(0,t.jsxs)("div",{className:"flex items-center justify-between",children:[(0,t.jsx)("span",{className:"text-muted-foreground",children:"Package"}),(0,t.jsx)("span",{className:"font-mono",children:e?.packageName})]}),(0,t.jsxs)("div",{className:"flex items-center justify-between",children:[(0,t.jsx)("span",{className:"text-muted-foreground",children:"Current"}),(0,t.jsx)("span",{className:"font-mono",children:e?.version?`v${e.version}`:"unknown"})]}),(0,t.jsxs)("div",{className:"flex items-center justify-between",children:[(0,t.jsx)("span",{className:"text-muted-foreground",children:"Latest on npm"}),(0,t.jsx)("span",{className:"font-mono",children:l?"checking...":o?`v${o}`:"unavailable"})]}),c&&(0,t.jsx)("p",{className:"text-xs text-muted-foreground pt-1",children:"Already on the latest version."})]}),(0,t.jsxs)(cr,{children:[(0,t.jsx)($,{variant:"outline",onClick:i,disabled:n,children:"Cancel"}),(0,t.jsx)($,{disabled:n,onClick:a,children:n?"Reinstalling...":"Reinstall"})]})]})})}r(hfs,"ReinstallDialog");function uge(){const{selectedCompany:e}=fs(),{setBreadcrumbs:s}=Vn(),n=wt(),{pushToast:a}=Zr(),[i,o]=(0,m.useState)(""),[l,c]=(0,m.useState)(""),[d,u]=(0,m.useState)(!1),[h,p]=(0,m.useState)(!1),[f,x]=(0,m.useState)(null),[g,v]=(0,m.useState)(null);(0,m.useEffect)(()=>{s([{label:e?.name??"Organization",href:"/dashboard"},{label:"Settings",href:"/company/settings"},{label:"Adapters"}])},[e?.name,s]);const{data:y,isLoading:k}=te({queryKey:D.adapters.all,queryFn:r(()=>Oh.list(),"queryFn")}),w=r(()=>{n.invalidateQueries({queryKey:D.adapters.all})},"invalidate"),N=we({mutationFn:r(M=>Oh.install(M),"mutationFn"),onSuccess:r(M=>{w(),p(!1),o(""),c(""),u(!1),a({title:"Adapter installed",body:`Type "${M.type}" registered successfully.${M.version?` (v${M.version})`:""}`,tone:"success"})},"onSuccess"),onError:r(M=>{a({title:"Install failed",body:M.message,tone:"error"})},"onError")}),S=we({mutationFn:r(M=>Oh.remove(M),"mutationFn"),onSuccess:r(()=>{w(),a({title:"Adapter removed",tone:"success"})},"onSuccess"),onError:r(M=>{a({title:"Removal failed",body:M.message,tone:"error"})},"onError")}),C=we({mutationFn:r(({type:M,disabled:Q})=>Oh.setDisabled(M,Q),"mutationFn"),onSuccess:r(()=>{w()},"onSuccess"),onError:r(M=>{a({title:"Toggle failed",body:M.message,tone:"error"})},"onError")}),_=we({mutationFn:r(({type:M,paused:Q})=>Oh.setOverridePaused(M,Q),"mutationFn"),onSuccess:r(()=>{w()},"onSuccess"),onError:r(M=>{a({title:"Override toggle failed",body:M.message,tone:"error"})},"onError")}),R=we({mutationFn:r(M=>Oh.reload(M),"mutationFn"),onSuccess:r(M=>{w(),_z(M.type),gre(M.type),a({title:"Adapter reloaded",body:`Type "${M.type}" reloaded.${M.version?` (v${M.version})`:""}`,tone:"success"})},"onSuccess"),onError:r(M=>{a({title:"Reload failed",body:M.message,tone:"error"})},"onError")}),I=we({mutationFn:r(M=>Oh.reinstall(M),"mutationFn"),onSuccess:r(M=>{w(),_z(M.type),gre(M.type),a({title:"Adapter reinstalled",body:`Type "${M.type}" updated from npm.${M.version?` (v${M.version})`:""}`,tone:"success"})},"onSuccess"),onError:r(M=>{a({title:"Reinstall failed",body:M.message,tone:"error"})},"onError")}),T=(y??[]).filter(M=>M.source==="builtin"),E=(y??[]).filter(M=>M.source==="external"),P=(y??[]).filter(M=>M.source==="external"&&M.overriddenBuiltin).filter(M=>!T.some(Q=>Q.type===M.type)).map(M=>({type:M.type,label:kf(M.type),overriddenBy:[M.packageName,M.version?`v${M.version}`:void 0].filter(Boolean).join(" "),overridePaused:!!M.overridePaused,menuDisabled:!!M.disabled}));if(k)return(0,t.jsx)("div",{className:"p-4 text-sm text-muted-foreground",children:"Loading adapters..."});const O=N.isPending||S.isPending||C.isPending||_.isPending||R.isPending||I.isPending;return(0,t.jsxs)("div",{className:"max-w-6xl space-y-6",children:[(0,t.jsxs)("div",{className:"flex items-center justify-between",children:[(0,t.jsxs)("div",{className:"flex items-center gap-2",children:[(0,t.jsx)(Vm,{className:"h-6 w-6 text-muted-foreground"}),(0,t.jsx)("h1",{className:"text-xl font-semibold",children:"Adapters"}),(0,t.jsx)(ot,{variant:"outline",className:"text-amber-600 border-amber-400",children:"Alpha"})]}),(0,t.jsxs)(Fs,{open:h,onOpenChange:p,children:[(0,t.jsx)(Gx,{asChild:!0,children:(0,t.jsxs)($,{size:"sm",className:"gap-2",children:[(0,t.jsx)(bn,{className:"h-4 w-4"}),"Install Adapter"]})}),(0,t.jsxs)(Qs,{children:[(0,t.jsxs)(rn,{children:[(0,t.jsx)(Ks,{children:"Install External Adapter"}),(0,t.jsxs)(mn,{children:["Add an adapter from npm or a local path. The adapter package must export ",(0,t.jsx)("code",{className:"text-xs bg-muted px-1 py-0.5 rounded",children:"createServerAdapter()"}),"."]})]}),(0,t.jsxs)("div",{className:"grid gap-4 py-4",children:[(0,t.jsxs)("div",{className:"flex items-center gap-2",children:[(0,t.jsxs)("button",{type:"button",className:W("inline-flex items-center gap-1.5 rounded-md border px-3 py-1.5 text-xs transition-colors",d?"border-border text-muted-foreground hover:text-foreground hover:bg-accent/50":"border-foreground bg-accent text-foreground"),onClick:r(()=>u(!1),"onClick"),children:[(0,t.jsx)(t0,{className:"h-3.5 w-3.5"}),"npm package"]}),(0,t.jsxs)("button",{type:"button",className:W("inline-flex items-center gap-1.5 rounded-md border px-3 py-1.5 text-xs transition-colors",d?"border-foreground bg-accent text-foreground":"border-border text-muted-foreground hover:text-foreground hover:bg-accent/50"),onClick:r(()=>u(!0),"onClick"),children:[(0,t.jsx)(nl,{className:"h-3.5 w-3.5"}),"Local path"]})]}),d?(0,t.jsxs)("div",{className:"grid gap-2",children:[(0,t.jsx)($s,{htmlFor:"adapterLocalPath",children:"Path to adapter package"}),(0,t.jsxs)("div",{className:"flex gap-2",children:[(0,t.jsx)(dt,{id:"adapterLocalPath",className:"flex-1 font-mono text-xs",placeholder:"/mnt/e/Projects/my-adapter or E:\\Projects\\my-adapter",value:i,onChange:r(M=>o(M.target.value),"onChange")}),(0,t.jsx)(nu,{})]}),(0,t.jsx)("p",{className:"text-xs text-muted-foreground",children:"Accepts Linux, WSL, and Windows paths. Windows paths are auto-converted."})]}):(0,t.jsxs)(t.Fragment,{children:[(0,t.jsxs)("div",{className:"grid gap-2",children:[(0,t.jsx)($s,{htmlFor:"adapterPackageName",children:"Package Name"}),(0,t.jsx)(dt,{id:"adapterPackageName",placeholder:"my-paperclip-adapter",value:i,onChange:r(M=>o(M.target.value),"onChange")})]}),(0,t.jsxs)("div",{className:"grid gap-2",children:[(0,t.jsx)($s,{htmlFor:"adapterVersion",children:"Version (optional)"}),(0,t.jsx)(dt,{id:"adapterVersion",placeholder:"latest",value:l,onChange:r(M=>c(M.target.value),"onChange")})]})]})]}),(0,t.jsxs)(cr,{children:[(0,t.jsx)($,{variant:"outline",onClick:r(()=>p(!1),"onClick"),children:"Cancel"}),(0,t.jsx)($,{onClick:r(()=>N.mutate({packageName:i,version:l||void 0,isLocalPath:d}),"onClick"),disabled:!i||N.isPending,children:N.isPending?"Installing...":"Install"})]})]})]})]}),(0,t.jsx)("div",{className:"rounded-lg border border-amber-500/30 bg-amber-500/5 px-4 py-3",children:(0,t.jsxs)("div",{className:"flex items-start gap-3",children:[(0,t.jsx)(Es,{className:"mt-0.5 h-4 w-4 shrink-0 text-amber-700"}),(0,t.jsxs)("div",{className:"space-y-1 text-sm",children:[(0,t.jsx)("p",{className:"font-medium text-foreground",children:"External adapters are alpha."}),(0,t.jsx)("p",{className:"text-muted-foreground",children:"The adapter plugin system is under active development. APIs and storage format may change. Use the power icon to hide adapters from agent menus without removing them."})]})]})}),(0,t.jsxs)("section",{className:"space-y-3",children:[(0,t.jsxs)("div",{className:"flex items-center gap-2",children:[(0,t.jsx)(Vm,{className:"h-5 w-5 text-muted-foreground"}),(0,t.jsx)("h2",{className:"text-base font-semibold",children:"External Adapters"})]}),E.length===0?(0,t.jsx)(sn,{className:"bg-muted/30",children:(0,t.jsxs)(Xa,{className:"flex flex-col items-center justify-center py-10",children:[(0,t.jsx)(Vm,{className:"h-10 w-10 text-muted-foreground mb-4"}),(0,t.jsx)("p",{className:"text-sm font-medium",children:"No external adapters installed"}),(0,t.jsx)("p",{className:"text-xs text-muted-foreground mt-1",children:"Install an adapter package to extend model support."})]})}):(0,t.jsx)(sn,{className:"block py-0",children:(0,t.jsx)("ul",{className:"divide-y",children:E.map(M=>{const Q=M.overriddenBuiltin,L=Q&&!!M.overridePaused,F=Q?{...M,disabled:L??!1}:M;return(0,t.jsx)(UB,{adapter:F,canRemove:!0,onToggle:Q?(q,z)=>_.mutate({type:q,paused:z}):(q,z)=>C.mutate({type:q,disabled:z}),onRemove:r(q=>x(q),"onRemove"),onReload:r(q=>R.mutate(q),"onReload"),onReinstall:M.isLocalPath?void 0:q=>v(M),isToggling:Q?_.isPending:C.isPending,isReloading:R.isPending,isReinstalling:I.isPending,toggleTitleDisabled:Q?"Pause external override":void 0,toggleTitleEnabled:Q?"Resume external override":void 0,disabledBadgeLabel:Q?"Override paused":void 0},M.type)})})})]}),(0,t.jsxs)("section",{className:"space-y-3",children:[(0,t.jsxs)("div",{className:"flex items-center gap-2",children:[(0,t.jsx)(Vm,{className:"h-5 w-5 text-muted-foreground"}),(0,t.jsx)("h2",{className:"text-base font-semibold",children:"Built-in Adapters"})]}),T.length===0&&P.length===0?(0,t.jsx)("div",{className:"text-sm text-muted-foreground",children:"No built-in adapters found."}):(0,t.jsx)(sn,{className:"block py-0",children:(0,t.jsxs)("ul",{className:"divide-y",children:[T.map(M=>(0,t.jsx)(UB,{adapter:M,canRemove:!1,onToggle:r((Q,L)=>C.mutate({type:Q,disabled:L}),"onToggle"),onRemove:r(()=>{},"onRemove"),isToggling:O},M.type)),P.map(M=>(0,t.jsx)(UB,{adapter:{type:M.type,label:M.label,source:"builtin",modelsCount:0,loaded:!0,disabled:M.menuDisabled,capabilities:{supportsInstructionsBundle:!1,supportsSkills:!1,supportsLocalAgentJwt:!1,requiresMaterializedRuntimeSkills:!1,supportsAcp:!1}},canRemove:!1,onToggle:r((Q,L)=>C.mutate({type:Q,disabled:L}),"onToggle"),onRemove:r(()=>{},"onRemove"),isToggling:O,overriddenBy:M.overridePaused?void 0:M.overriddenBy},M.type))]})})]}),(0,t.jsx)(Fs,{open:f!==null,onOpenChange:r(M=>{M||x(null)},"onOpenChange"),children:(0,t.jsxs)(Qs,{children:[(0,t.jsxs)(rn,{children:[(0,t.jsx)(Ks,{children:"Remove Adapter"}),(0,t.jsxs)(mn,{children:["Are you sure you want to remove the ",(0,t.jsx)("strong",{children:f})," adapter? It will be unregistered and removed from the adapter store.",f&&y?.find(M=>M.type===f)?.packageName&&(0,t.jsx)(t.Fragment,{children:" npm packages will be cleaned up from disk."})," ","This action cannot be undone."]})]}),(0,t.jsxs)(cr,{children:[(0,t.jsx)($,{variant:"outline",onClick:r(()=>x(null),"onClick"),children:"Cancel"}),(0,t.jsx)($,{variant:"destructive",disabled:S.isPending,onClick:r(()=>{f&&S.mutate(f,{onSettled:r(()=>x(null),"onSettled")})},"onClick"),children:S.isPending?"Removing...":"Remove"})]})]})}),(0,t.jsx)(hfs,{adapter:g,open:g!==null,isReinstalling:I.isPending,onConfirm:r(()=>{g&&I.mutate(g.type,{onSettled:r(()=>v(null),"onSettled")})},"onConfirm"),onCancel:r(()=>v(null),"onCancel")})]})}r(uge,"AdapterManager");function mge(){const e=xa(),{companyPrefix:s,pluginId:n,pluginRoutePath:a}=e,i=e["*"],{companies:o,selectedCompanyId:l}=fs(),{setBreadcrumbs:c}=Vn(),d=(0,m.useMemo)(()=>{if(!s)return null;const y=s.toUpperCase();return o.find(k=>k.issuePrefix.toUpperCase()===y)??null},[o,s]),u=!!s&&!d,h=(0,m.useMemo)(()=>d?d.id:s?null:l??null,[d,s,l]),p=(0,m.useMemo)(()=>h?o.find(y=>y.id===h)?.issuePrefix??null:null,[o,h]),{data:f}=te({queryKey:D.plugins.uiContributions,queryFn:r(()=>El.listUiContributions(),"queryFn"),enabled:!!h&&(!!n||!!a)}),x=(0,m.useMemo)(()=>{if(!f)return null;if(n){const k=f.find(N=>N.pluginId===n);if(!k)return null;const w=k.slots.find(N=>N.type==="page");return w?{...w,pluginId:k.pluginId,pluginKey:k.pluginKey,pluginDisplayName:k.displayName,pluginVersion:k.version}:null}if(!a)return null;const y=f.flatMap(k=>{const w=k.slots.find(N=>N.type==="page"&&N.routePath===a);return w?[{...w,pluginId:k.pluginId,pluginKey:k.pluginKey,pluginDisplayName:k.displayName,pluginVersion:k.version}]:[]});return y.length!==1?null:y[0]??null},[n,a,f]),g=(0,m.useMemo)(()=>({companyId:h??null,companyPrefix:p}),[h,p]),v=(0,m.useMemo)(()=>{if(!a||!f)return!1;const y=f.flatMap(k=>k.slots.map(w=>({...w,pluginId:k.pluginId,pluginKey:k.pluginKey,pluginDisplayName:k.displayName,pluginVersion:k.version})));return $W(y,a)!==null},[f,a]);if((0,m.useEffect)(()=>{if(x){if(v){c([{label:pfs(x,i)}]);return}c([{label:"Plugins",href:"/company/settings/instance/plugins"},{label:x.pluginDisplayName}])}},[x,i,c,v]),!h)return u?(0,t.jsx)(mm,{scope:"invalid_company_prefix",requestedPrefix:s}):(0,t.jsx)("div",{className:"space-y-4",children:(0,t.jsx)("p",{className:"text-sm text-muted-foreground",children:"Select an organization to view this page."})});if(!f)return(0,t.jsx)("div",{className:"text-sm text-muted-foreground",children:"Loading…"});if(!n&&a&&f.filter(y=>y.slots.some(k=>k.type==="page"&&k.routePath===a)).length>1)return(0,t.jsxs)("div",{className:"rounded-md border border-destructive/30 bg-destructive/5 px-3 py-2 text-sm text-destructive",children:["Multiple plugins declare the route ",(0,t.jsx)("code",{children:a}),". Use the plugin-id route until the conflict is resolved."]});if(!x){if(a)return(0,t.jsx)(mm,{scope:"board"});const y=n?`/company/settings/instance/plugins/${n}`:"/company/settings/instance/plugins";return(0,t.jsx)(In,{to:y,replace:!0})}return(0,t.jsxs)("div",{className:"space-y-4",children:[!v&&(0,t.jsx)("div",{className:"flex items-center gap-2",children:(0,t.jsx)($,{variant:"ghost",size:"sm",asChild:!0,children:(0,t.jsxs)(We,{to:p?`/${p}/dashboard`:"/dashboard",children:[(0,t.jsx)(wl,{className:"h-4 w-4 mr-1"}),"Back"]})})}),(0,t.jsx)(vm,{slot:x,context:g,className:"min-h-(--sz-200px)",missingBehavior:"placeholder"})]})}r(mge,"PluginPage");function pfs(e,s){return ffs(s)??e.displayName??e.pluginDisplayName}r(pfs,"resolveRouteSidebarPageTitle");function ffs(e){const s=(e??"").split("/").filter(Boolean).map(xfs);return s.length===0?null:s[0]==="page"&&s.length>1?hge(s.slice(1).join("/"),{preserveCase:!0}):hge(s[0]??null)}r(ffs,"titleFromRouteSplat");function hge(e,s={}){const n=e?.trim();if(!n)return null;const a=n.split("/").filter(Boolean).at(-1)??n,i=(a.split("::").at(-1)??a).replace(/\.[^.]+$/,"").replace(/[-_]+/g," ").trim();return i?s.preserveCase?i:i.replace(/\b\w/g,o=>o.toUpperCase()):null}r(hge,"titleFromPath");function xfs(e){try{return decodeURIComponent(e)}catch{return e}}r(xfs,"decodeRouteSegment");var KB=$ze,pge=r(e=>e.status==="fail"||e.checks.some(s=>s.code==="adapter_auth_missing"),"blocking");function gfs(){const{selectedCompanyId:e}=fs(),[s]=hi();return e?(0,t.jsx)(bfs,{companyId:e,name:s.get("name")??"",adapterType:s.get("adapterType")??"",runnerProvider:s.get("runnerProvider")??"codex",createdAgentId:s.get("createdAgentId")},`${e}:${s.get("name")}:${s.get("adapterType")}:${s.get("runnerProvider")}`):(0,t.jsx)("p",{className:"text-sm text-muted-foreground",children:"Select an organization to create an agent."})}r(gfs,"NewAgentSetup");function bfs({companyId:e,name:s,adapterType:n,runnerProvider:a,createdAgentId:i}){const o=Gn(),l=wt(),{openNewIssue:c}=al(),d=Z_e(`${e}:new-agent`),u=n==="paperclip_runner",h=u&&a==="openai_dot",p=h?"openai_dot":u?a==="grok"?"grok_local":a==="claude"?"claude_local":a==="opencode"?"opencode_local":"codex_local":n,f=p==="claude_local"||p==="codex_local"||p==="grok_local"?p:null,x=p==="opencode_local"||p==="pi_local",g=eit(p),v=x||p==="hermes_local",y=v||!!hre[n],k=!h&&!["cursor_cloud","hermes_gateway"].includes(n),[w,N]=(0,m.useState)(!1),[S,C]=(0,m.useState)(""),[_,R]=(0,m.useState)(""),[I,T]=(0,m.useState)(""),[E,P]=(0,m.useState)("kimi"),[O,M]=(0,m.useState)(i?"saved":f?"connect":"runtime"),[Q,L]=(0,m.useState)(""),F=u?[]:vE(n,Q),[q,z]=(0,m.useState)(""),[K,U]=(0,m.useState)(!1),[V,ne]=(0,m.useState)(""),[Z,ie]=(0,m.useState)("openrouter"),[J,ae]=(0,m.useState)(""),[oe,G]=(0,m.useState)(null),[X,Y]=(0,m.useState)(()=>p==="opencode_local"?{provider:"openrouter",method:"api_key",mode:"responsible_user"}:void 0),[re,se]=(0,m.useState)(null),ce=X??re?.aiConnection,pe=RCe(e,ce,p),[fe,ve]=(0,m.useState)(""),[Ie,de]=(0,m.useState)(""),[xe,le]=(0,m.useState)(null),Re=te({queryKey:D.agents.detail(i??"new"),queryFn:r(()=>Nt.get(i,e),"queryFn"),enabled:!!i,retry:!1}),Le=xe??(Re.data?.companyId===e?Re.data:null),[je,_e]=(0,m.useState)(!1),[Ze,ue]=(0,m.useState)("idle"),[Fe,mt]=(0,m.useState)(null),[bt,et]=(0,m.useState)(null),qe=(0,m.useRef)(0),it=(0,m.useRef)(!1);(0,m.useEffect)(()=>()=>{qe.current++},[]);const _t=r(()=>{qe.current++,mt(null),ue("idle"),et(null)},"resetTest"),$t=r(()=>{se(null),Y(void 0),_t(),M("connect")},"editConnection"),Ot=te({queryKey:D.adapters.all,queryFn:Oh.list}),at=te({queryKey:D.agents.list(e),queryFn:r(()=>Nt.list(e),"queryFn")}),Me=te({queryKey:D.environments.list(e),queryFn:r(()=>$i.list(e),"queryFn")}),De=te({queryKey:D.instance.settings,queryFn:jr.get}),ut=te({queryKey:D.instance.experimentalSettings,queryFn:jr.getExperimental}),Pt=te({queryKey:D.instance.generalSettings,queryFn:jr.getGeneral}),Rt=te({queryKey:D.environments.capabilities(e),queryFn:r(()=>$i.capabilities(e),"queryFn")}),Qe=te({queryKey:D.agents.adapterModels(e,p,null,ce?.provider),queryFn:r(()=>Nt.adapterModels(e,p,{provider:ce?.provider}),"queryFn"),enabled:!!p&&k&&!pe,retry:!1}),Be=te({queryKey:D.secrets.list(e),queryFn:r(()=>Rr.list(e),"queryFn"),enabled:y&&n!=="cursor_cloud"}),Oe=te({queryKey:D.secrets.myUserSecrets(e),queryFn:r(()=>Rr.listMyUserSecrets(e),"queryFn"),enabled:y&&n!=="cursor_cloud",retry:!1}),Pe=NV(Pt.data?.executionMode,Me.data??[]),Ve=ut.data?.enableManagedSandboxOnly===!0;let be=null,nt=null;try{be=Pe.forced?Pe.kubernetesEnvironment?.id??null:vN({agentDefaultEnvironmentId:V||null,instanceDefaultEnvironmentId:De.data?.defaultEnvironmentId??null,localDefaultEnvironmentId:jN(Me.data??[]),managedSandboxOnly:Ve,managedSandboxEnvironmentId:yN(Me.data??[]),visibleEnvironmentIds:(Me.data??[]).map(ze=>ze.id)})}catch(ze){nt=ze instanceof Error?ze.message:"Could not resolve the environment."}const Lt=Me.data?.find(ze=>ze.id===be),Cs=typeof Lt?.config?.provider=="string"?Lt.config.provider:"",lt=Lt?.driver==="sandbox"&&Rt.data?.sandboxProviders?.[Cs]?.supportsLoginPty===!0,Os=hre[n]??g[Z]??"API_KEY",Ke=Oe.data?.find(ze=>ze.definition.key===Os&&ze.secret),ge=Be.data?.find(ze=>ze.key===Os&&ze.status==="active"),Xe=n==="cursor_cloud"?null:oe??(ge?{type:"secret_ref",secretId:ge.id,version:"latest"}:Ke?{type:"user_secret_ref",key:Os,version:"latest"}:null),xt=n==="kimi_local"&&!!(J.trim()||Xe),Ht=!!td(),ht=J_e(n,{cloud:Ht,nativeRunnerEnabled:ut.data?.enableNativeRunner===!0,openAiDotEnabled:ut.data?.enableOpenAiDot===!0,runnerProvider:a})&&Ot.data?.some(ze=>ze.type===n&&ze.loaded&&!ze.disabled&&!th(n).comingSoon),zt=!!(ht&&!nt&&!Me.isPending&&!De.isPending&&!ut.isPending&&!Pt.isPending&&!at.isPending&&!Rt.isPending&&!Me.error&&!De.error&&!ut.error&&!Pt.error&&!at.error&&!Rt.error&&(!(Ve||Pe.forced)||be)),$e=Ze==="running"||je;function he(ze=re,St=Xe){const Ut={...Ab,adapterType:n,model:Q||(p==="codex_local"?bN:""),thinkingEffort:q,dangerouslyBypassSandbox:n==="codex_local",envBindings:ze?.env??{},...u?{adapterSchemaValues:{provider:a==="claude"||a==="grok"?"acpx":a,...h?{allowUnmeteredProvider:w}:{},...a==="claude"||a==="grok"?{acpxAgent:a}:{}}}:{}},Ct=_2(n).buildAdapterConfig(Ut);return n==="omp_local"&&(delete Ct.thinkingEffort,q&&(Ct.thinking=q)),u&&Object.assign(Ct,{provider:a==="claude"||a==="grok"?"acpx":a,...a==="claude"||a==="grok"?{acpxAgent:a}:{},...Q?{model:Q}:{}}),!ce&&!ze?.aiConnection&&y&&St&&(n==="hermes_gateway"?Ct.apiKey=St:Ct.env={...Ct.env??{},[Os]:St}),n==="cursor_cloud"&&Object.assign(Ct,{repoUrl:fe.trim(),...Ie.trim()?{repoStartingRef:Ie.trim()}:{}}),n==="hermes_gateway"&&(Ct.apiBaseUrl=S.trim()),xt&&(delete Ct.model,Ct.env={...Ct.env??{},KIMI_MODEL_NAME:{type:"plain",value:_.trim()},KIMI_MODEL_PROVIDER_TYPE:{type:"plain",value:E},...I.trim()?{KIMI_MODEL_BASE_URL:{type:"plain",value:I.trim()}}:{}}),Ct}r(he,"buildConfig");function Vt(ze=re){if(h&&!w)throw new Error("Acknowledge external provider billing before creating your Dot agent.");if(x&&(!Q.trim()||!Q.includes("/")))throw new Error("Choose or enter a model in provider/model format.");if(n==="cursor_cloud"&&!/^https:\/\/github\.com\/[^/]+\/[^/]+/.test(fe.trim()))throw new Error("Enter a GitHub repository URL.");if(["cursor_cloud","hermes_gateway"].includes(n)&&!J.trim()&&!Xe)throw new Error(n==="cursor_cloud"?"Enter a Cursor API key.":`Enter ${Os} or select an organization secret.`);if(n==="hermes_gateway")try{const St=new URL(S.trim());if(!["https:","http:"].includes(St.protocol))throw new Error}catch{throw new Error("Enter the Hermes API base URL.")}if(xt&&!_.trim())throw new Error("Enter the Kimi API model name.");return he(ze)}r(Vt,"preparedConfig");function Dt(ze=re){return ce||ze?.aiConnection?{}:{...ze?.credentials,...y&&J.trim()?{[Os]:J.trim()}:{}}}r(Dt,"pendingCredentials");async function ns(ze=re){if(!zt)return!1;const St=++qe.current;ue("running"),mt(null),et(null);try{const Ut=await Vt(ze),Ct=await ECe({companyId:e,adapterType:n,providerAdapter:p,adapterConfig:Ut,testCredentials:Dt(ze),aiConnection:X??ze?.aiConnection,environmentId:be});return St!==qe.current?!1:(mt(Ct),ue(pge(Ct)?"fail":Ct.status),!pge(Ct)&&(!f||Ct.checks.some(os=>os.code.endsWith("hello_probe_passed"))))}catch(Ut){return St===qe.current&&(et(Ut instanceof Error?Ut.message:"Could not test the agent."),ue("fail")),!1}}r(ns,"runTest");async function _s(){if(it.current||i||Le||!zt||!s.trim()||Ze==="running"||Ze==="fail"||f&&!re)return;it.current=!0,_e(!0),et(null);const ze=[];let St=!1;try{const Ut=Vt(),Ct=Dt();if(Object.keys(Ct).length&&!await ns())return;for(const[qs,Rn]of Object.entries(Ct)){const Ns=await(f?UCe:Jat)(e,qs,Rn);ze.push(Ns),n==="hermes_gateway"&&qs==="API_SERVER_KEY"?Ut.apiKey=Ns.binding:Ut.env={...Ut.env??{},[qs]:Ns.binding}}const os=at.data??[],vs=os.find(qs=>qs.role==="ceo"&&qs.status!=="terminated"),Bs=await Nt.hire(e,{name:s.trim(),appearance:d.appearance,role:os.length?"general":"ceo",...vs?{reportsTo:vs.id}:{},adapterType:n,adapterConfig:Ut,defaultEnvironmentId:V||(Pe.forced||Ve?be:null),runtimeConfig:{...WAe({heartbeatEnabled:!1}),...ce?{aiConnection:ce}:{}},budgetMonthlyCents:0,...re?.storedSessionId?{storedSessionId:re.storedSessionId}:{},...re?.applyStoredClaudeLogin?{applyStoredClaudeLogin:!0}:{}});St=!0,ae(""),se(null),le(Bs.agent),d.clear(),M("saved"),o(`/agents/new?${new URLSearchParams({name:Bs.agent.name,adapterType:n,runnerProvider:a,createdAgentId:Bs.agent.id})}`,{replace:!0}),l.setQueryData(D.agents.detail(Bs.agent.id),Bs.agent),await Promise.all([l.invalidateQueries({queryKey:D.agents.list(e)}),l.invalidateQueries({queryKey:D.approvals.list(e)})])}catch(Ut){et(Ut instanceof Error?Ut.message:"Could not create the agent.")}finally{if(!St)try{await Promise.all(ze.map(Ut=>Ut.remove()))}catch{et(Ut=>`${Ut?`${Ut} `:""}Could not remove an unused setup credential. Remove it from Secrets before retrying.`)}l.invalidateQueries({queryKey:D.secrets.myUserSecrets(e)}),l.invalidateQueries({queryKey:D.secrets.list(e)}),it.current=!1,_e(!1)}}if(r(_s,"finish"),i&&!Le)return(0,t.jsx)("p",{role:Re.error?"alert":"status",className:"text-sm text-muted-foreground",children:Re.error?"Could not load the created agent. Return to Agents to view it.":"Loading your agent…"});if(!s||!n)return(0,t.jsx)(X_e,{open:!0,initialAdapter:n,onClose:r(()=>o("/agents/all"),"onClose"),onContinue:r(ze=>o(`/agents/new?${new URLSearchParams(ze)}`,{replace:!0}),"onContinue")});const cn=[...f?["connect"]:[],"runtime","saved"],mr={connect:"Connect",runtime:"Configure",saved:"Confirmation"},pn=Le?.defaultEnvironmentId?Me.data?.find(ze=>ze.id===Le.defaultEnvironmentId):Lt,Bt=Le?.adapterConfig?.env?.KIMI_MODEL_NAME,Ls=Le?.adapterConfig?.model||(typeof Bt=="string"?Bt:Bt?.value)||Q||"Default",Ee=n==="cursor_cloud"?"Cursor Cloud":n==="hermes_gateway"?"Hermes Gateway":pn?wN(pn):"Local machine",jt=Ot.error??Me.error??De.error??ut.error??Pt.error??at.error??Rt.error;return(0,t.jsx)(yCe,{reducedMotion:"user",children:(0,t.jsxs)("div",{className:"mx-auto flex max-w-5xl flex-col gap-8 py-6",children:[(0,t.jsxs)("header",{className:"flex items-center gap-4",children:[(0,t.jsx)(NN,{appearance:Le?.appearance??d.appearance,size:256,className:"size-48",trackingScope:"page",state:Le||Ze==="pass"?"success":Ze==="running"?"loading":"sleepy",muted:!Le&&Ze!=="pass"}),(0,t.jsxs)("div",{className:"space-y-2",children:[(0,t.jsx)("h1",{className:"text-2xl font-semibold tracking-tight",children:s}),(0,t.jsxs)("div",{className:"flex items-center gap-2 text-sm text-muted-foreground",children:[(0,t.jsx)(q0,{type:p}),(0,t.jsx)("span",{children:th(p).label}),u&&!h&&(0,t.jsxs)("span",{children:["·"," ",a==="codex"?"Native app server runner":"Paperclip Runner"]})]})]})]}),nt&&!Me.isPending&&(0,t.jsx)("p",{role:"alert",className:"text-sm text-destructive",children:nt}),jt&&(0,t.jsx)("p",{role:"alert",className:"text-sm text-destructive",children:jt.message}),Ot.data&&!ht&&(0,t.jsx)("p",{role:"alert",className:"text-sm text-destructive",children:"This adapter is unavailable. Choose an enabled adapter."}),(Ve||Pe.forced)&&!Me.isPending&&!be&&(0,t.jsx)("p",{role:"alert",className:"text-sm text-destructive",children:"No managed environment is available. Configure an environment before continuing."}),(0,t.jsxs)("div",{className:"flex flex-col gap-8 md:flex-row",children:[(0,t.jsx)("nav",{"aria-label":"Agent setup steps",className:"shrink-0 md:w-44",children:(0,t.jsx)("ol",{className:"flex flex-wrap gap-2 md:flex-col",children:cn.map((ze,St)=>(0,t.jsx)("li",{children:(0,t.jsxs)("button",{type:"button","aria-current":ze===O?"step":void 0,disabled:$e||!!Le||ze==="saved",onClick:r(()=>ze==="connect"&&O!=="connect"?$t():M(ze),"onClick"),className:W("flex w-full items-center gap-3 rounded-md px-3 py-3 text-left text-sm",ze===O?"bg-accent font-medium":"text-muted-foreground"),children:[(0,t.jsx)("span",{className:W("flex size-6 shrink-0 items-center justify-center rounded-full border text-xs",ze===O?"border-foreground bg-foreground text-background":"border-border"),children:St+1}),mr[ze]]})},ze))})}),(0,t.jsx)("div",{className:"min-w-0 flex-1",children:(0,t.jsx)(S2,{mode:"wait",initial:!1,children:(0,t.jsx)(Rl.div,{...wit,children:O==="connect"&&f?(0,t.jsxs)(Lyt,{className:"mx-auto",children:[(0,t.jsx)("div",{className:"mb-8",children:(0,t.jsx)(HAe,{title:"Connect a model",center:!0})}),zt?(0,t.jsx)(s5e,{companyId:e,adapterType:f,environmentId:be,canLogin:lt,localEnvironment:Lt?.driver==="local",advancedConnection:{value:ce,content:(0,t.jsx)(pz,{companyId:e,agentName:s,adapterType:p,model:Q,environmentId:be??void 0,value:ce,preferAdvanced:!0,onChange:r(ze=>{ze.mode!=="router"&&(se(null),Y(ze),_t())},"onChange")})},onBack:r(()=>o("/agents/all"),"onBack"),onDraftChanged:r(()=>{se(null),Y(void 0),_t()},"onDraftChanged"),testConnection:ns,testError:bt??(Fe?.checks.find(ze=>ze.level==="error")??Fe?.checks.find(ze=>ze.code.includes("hello_probe")&&ze.level==="warn"))?.message,onConnected:r(ze=>{se(ze),Y(void 0),_t(),M("runtime")},"onConnected")},be??"local"):(0,t.jsx)("p",{role:"status",className:"text-sm text-muted-foreground",children:"Loading connection settings…"})]}):O==="saved"&&Le?(0,t.jsxs)("div",{className:"space-y-6",children:[(0,t.jsxs)("div",{className:"space-y-6 rounded-lg border border-border p-6",children:[(0,t.jsxs)("h2",{className:"flex items-center gap-3 text-lg font-semibold",children:[(0,t.jsx)(ms,{className:"size-5"}),Le.status==="pending_approval"?"Agent submitted for approval":h?"Your Dot agent has been created":"Your agent is ready"]}),(0,t.jsxs)("dl",{className:"grid grid-cols-2 gap-4 text-sm",children:[(0,t.jsx)("dt",{className:"text-muted-foreground",children:"Adapter"}),(0,t.jsx)("dd",{children:th(h?"openai_dot":n).label}),k&&(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)("dt",{className:"text-muted-foreground",children:"Model"}),(0,t.jsx)("dd",{className:"break-all",children:String(Ls)})]}),(0,t.jsx)("dt",{className:"text-muted-foreground",children:"Environment"}),(0,t.jsx)("dd",{children:Ee})]}),(0,t.jsx)("p",{className:"text-sm text-muted-foreground",children:Le.status==="pending_approval"?"An organization administrator must approve this agent before it can work.":h?"Pair your Dot and test event delivery in configuration before assigning work.":"Assign a task when you’re ready for this agent to work."})]}),(0,t.jsxs)("div",{className:"flex flex-wrap justify-between gap-3",children:[(0,t.jsxs)($,{variant:"outline",onClick:r(()=>o(h?"/agents/all":`${om(Le)}/runtime`),"onClick"),children:[(0,t.jsx)(jW,{className:"size-4"}),h?"Back to Agents":"Edit configuration"]}),(0,t.jsxs)($,{disabled:Le.status==="pending_approval",onClick:r(()=>h?o(`${om(Le)}/runtime`):c({assigneeAgentId:Le.id,status:"todo"}),"onClick"),children:[h?"Pair Dot":`Assign ${Le.name} a Task`,(0,t.jsx)(pl,{className:"size-4"})]})]})]}):(0,t.jsxs)("form",{className:"space-y-8",onSubmit:r(ze=>{ze.preventDefault(),_s()},"onSubmit"),children:[(0,t.jsx)("h2",{className:"text-xl font-semibold",children:"Configure your agent"}),(0,t.jsxs)("fieldset",{disabled:$e,className:"space-y-8",children:[(0,t.jsxs)("section",{className:"space-y-5",children:[h&&(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)("p",{className:"text-sm text-muted-foreground",children:"Create this agent, then copy its pairing prompt to your Dot."}),ut.data?.enablePublicMcp!==!0&&(0,t.jsx)("p",{className:"text-sm text-muted-foreground",children:"Enable Assistant connections (MCP) in Experimental settings before pairing."}),(0,t.jsx)(yl,{label:"Allow externally billed provider",hint:"Dot does not report token usage or cost. Paperclip cannot enforce a provider spend ceiling; known company and agent budget limits still apply.",checked:w,onChange:r(ze=>{N(ze),_t()},"onChange")})]}),!f&&rV(p)&&(0,t.jsx)(pz,{companyId:e,agentName:s,adapterType:p,model:Q,environmentId:be??void 0,value:ce,onChange:r(ze=>{ze.mode!=="router"&&Y(ze),_t()},"onChange")}),(pe?pe.error:Qe.error)&&(0,t.jsx)("p",{role:"alert",className:"text-sm text-destructive",children:"Could not load models. Retry or enter a model ID manually."}),(k&&!xt||F.length>0)&&(0,t.jsxs)("div",{className:"grid items-start gap-5 sm:grid-cols-2",children:[k&&!xt&&(0,t.jsx)(CV,{models:pe?.models??Qe.data??[],onRefreshModels:pe?.refreshModels,refreshingModels:pe?.refreshing,value:Q,onChange:r(ze=>{L(pe?.resolveModel(ze)??ze),(n==="omp_local"?!hM(q,ze,(Qe.data??[]).map(Ut=>Ik(Ut,!1))):q&&!vE(n,ze).includes(q))&&z("");const St=ze.split("/")[0];x&&qCe[St]&&St!==Z&&(ie(St),ae(""),G(null)),_t()},"onChange"),open:K,onOpenChange:U,allowDefault:!x,required:x,creatable:!0,groupByProvider:x&&!pe,preserveOrder:!!pe||lV(p),effort:n==="omp_local"?{value:q||null,onChange:r(ze=>{z(ze??""),_t()},"onChange")}:void 0}),F.length>0&&n!=="omp_local"&&(0,t.jsx)(Ss,{label:"Thinking effort",children:(0,t.jsxs)(eW,{"aria-label":"Thinking effort",value:q,onChange:r(ze=>{z(ze.target.value),_t()},"onChange"),children:[(0,t.jsx)("option",{value:"",children:"Auto"}),F.map(ze=>(0,t.jsx)("option",{value:ze,children:ze},ze))]})})]}),!ce&&pre[n]&&(0,t.jsx)("p",{className:"text-sm text-muted-foreground",children:pre[n]}),y&&!ce&&(0,t.jsxs)("div",{className:"grid gap-5 sm:grid-cols-2",children:[v&&(0,t.jsx)(Ss,{label:"API key provider",children:(0,t.jsx)("select",{"aria-label":"API key provider",className:KB,value:Z,onChange:r(ze=>{ie(ze.target.value),L(""),ae(""),G(null),_t()},"onChange"),children:Object.keys(g).map(ze=>(0,t.jsx)("option",{value:ze,children:ze==="openrouter"?"OpenRouter":ze==="openai"?"OpenAI":ze==="anthropic"?"Anthropic":{google:"Google",xai:"xAI",groq:"Groq",opencode:"OpenCode"}[ze]??ze},ze))})}),(0,t.jsx)("div",{className:n==="cursor_cloud"?"sm:col-span-2":void 0,children:(0,t.jsx)(Ss,{label:Os,children:(0,t.jsxs)("div",{className:"flex items-center gap-3",children:[(0,t.jsx)(dt,{"aria-label":Os,type:"password",autoComplete:"off",value:J,onChange:r(ze=>{ae(ze.target.value),G(null),_t()},"onChange"),placeholder:Xe?"Using saved key":["cursor_cloud","hermes_gateway"].includes(n)?"Required":"Optional if already configured"}),n==="cursor_cloud"&&(0,t.jsx)("a",{href:"https://cursor.com/dashboard/api?section=user-keys#user-api-keys",target:"_blank",rel:"noopener noreferrer",className:"shrink-0 text-xs text-muted-foreground underline underline-offset-4 hover:text-foreground",children:"get api key"})]})})}),n!=="cursor_cloud"&&(0,t.jsx)("div",{className:v?"sm:col-span-2":void 0,children:(0,t.jsx)(Ss,{label:"Or use an organization secret",children:(0,t.jsx)(vV,{secretId:Xe&&typeof Xe=="object"&&Xe.type==="secret_ref"?Xe.secretId:"",secrets:Be.data??[],disabled:$e,onSelect:r(ze=>{G({type:"secret_ref",secretId:ze,version:"latest"}),ae(""),_t()},"onSelect")})})}),(0,t.jsxs)("p",{className:"text-xs text-muted-foreground sm:col-span-2",children:["New keys are saved as organization secrets when you finish setup.",x&&` Use a ${Z}/model ID.`]})]}),n==="hermes_gateway"&&(0,t.jsx)(Ss,{label:"Hermes API base URL",children:(0,t.jsx)(dt,{"aria-label":"Hermes API base URL",value:S,onChange:r(ze=>{C(ze.target.value),_t()},"onChange"),placeholder:"https://hermes.example.com"})}),xt&&(0,t.jsxs)("div",{className:"grid gap-5 sm:grid-cols-2",children:[(0,t.jsx)(Ss,{label:"Kimi API model name",children:(0,t.jsx)(dt,{"aria-label":"Kimi API model name",value:_,onChange:r(ze=>{R(ze.target.value),_t()},"onChange"),placeholder:"kimi-for-coding"})}),(0,t.jsx)(Ss,{label:"Kimi API protocol",children:(0,t.jsx)("select",{"aria-label":"Kimi API protocol",className:KB,value:E,onChange:r(ze=>{P(ze.target.value),_t()},"onChange"),children:["kimi","anthropic","openai"].map(ze=>(0,t.jsx)("option",{children:ze},ze))})}),(0,t.jsx)(Ss,{label:"Kimi API base URL",hint:"Optional override for your provider endpoint.",children:(0,t.jsx)(dt,{"aria-label":"Kimi API base URL",value:I,onChange:r(ze=>{T(ze.target.value),_t()},"onChange"),placeholder:"Provider default"})})]}),n==="cursor_cloud"&&(0,t.jsxs)("div",{className:"grid gap-5 sm:grid-cols-2",children:[(0,t.jsx)(Ss,{label:"GitHub repository",children:(0,t.jsx)(dt,{"aria-label":"GitHub repository",value:fe,onChange:r(ze=>{ve(ze.target.value),_t()},"onChange"),placeholder:"https://github.com/your-org/repo"})}),(0,t.jsx)(Ss,{label:"Branch",children:(0,t.jsx)(dt,{"aria-label":"Branch",placeholder:"Repository default",value:Ie,onChange:r(ze=>{de(ze.target.value),_t()},"onChange")})})]})]}),!["cursor_cloud","hermes_gateway"].includes(n)&&(0,t.jsxs)("section",{className:"space-y-5",children:[(0,t.jsx)("h3",{className:"text-sm font-semibold",children:"Environment"}),(0,t.jsxs)("select",{"aria-label":"Environment",className:KB,value:V,disabled:Pe.forced,onChange:r(ze=>{ne(ze.target.value),se(null),_t(),f&&M("connect")},"onChange"),children:[(0,t.jsxs)("option",{value:"",children:["Default: ",Ee]}),(Me.data??[]).filter(ze=>ze.status==="active"&&(!Ve||ze.driver!=="local")).map(ze=>(0,t.jsx)("option",{value:ze.id,children:wN(ze)},ze.id))]})]})]}),(0,t.jsx)(KCe,{variant:h?"prerequisites":"connection",state:Ze,result:Fe,error:bt,disabled:!zt||$e||!!(f&&!re),onTest:r(()=>{ns()},"onTest")}),bt&&Ze!=="fail"&&(0,t.jsx)("p",{role:"alert",className:"text-sm text-destructive",children:bt}),(0,t.jsxs)("div",{className:"flex justify-between border-t border-border py-5",children:[f?(0,t.jsxs)($,{type:"button",variant:"ghost",disabled:$e,onClick:$t,children:[(0,t.jsx)(wl,{className:"size-4"}),"Connection"]}):(0,t.jsx)("span",{}),f&&!re?(0,t.jsxs)($,{type:"button",disabled:!zt||$e,onClick:r(()=>M("connect"),"onClick"),children:["Connect model",(0,t.jsx)(pl,{className:"size-4"})]}):(0,t.jsxs)($,{type:"submit",disabled:!zt||$e||Ze==="fail"||!!(f&&!re),children:[je?"Creating…":"Finish setup",(0,t.jsx)(ms,{className:"size-4"})]})]})]})},O)})})]})]})})}r(bfs,"Setup");function vfs(){const{setBreadcrumbs:e}=Vn();return(0,m.useEffect)(()=>{e([{label:"Agents",href:"/agents"},{label:"New agent"}])},[e]),(0,t.jsx)(gfs,{})}r(vfs,"NewAgent");var uL="paperclip:pending-invite-token";function UZ(){return typeof window<"u"&&typeof window.localStorage<"u"}r(UZ,"canUseStorage");function fge(e){const s=e.trim();if(!(!s||!UZ()))try{window.localStorage.setItem(uL,s)}catch{}}r(fge,"rememberPendingInviteToken");function OT(e){if(UZ())try{const s=window.localStorage.getItem(uL);if(e&&s!==e.trim())return;window.localStorage.removeItem(uL)}catch{}}r(OT,"clearPendingInviteToken");function yfs(){if(!UZ())return null;try{const e=window.localStorage.getItem(uL)?.trim();return e?`/invite/${e}`:null}catch{return null}}r(yfs,"getRememberedInvitePath");var xge=[" ",".","·","▪","▫","○"],jfs=1e3/24,BT=[[" ╭────╮ "," ╭╯╭──╮│ "," │ │ ││ "," │ │ ││ "," │ │ ││ "," │ │ ││ "," │ ╰──╯│ "," ╰─────╯ "],[" ╭─────╮ "," │╭──╮╰╮ "," ││ │ │ "," ││ │ │ "," ││ │ │ "," ││ │ │ "," │╰──╯ │ "," ╰────╯ "]];function gge(e){const s=document.createElement("span");s.textContent="M",s.style.cssText="position:absolute;visibility:hidden;white-space:pre;font-size:11px;font-family:monospace;line-height:1;",e.appendChild(s);const n=s.getBoundingClientRect();return e.removeChild(s),{w:n.width,h:n.height}}r(gge,"measureChar");function wfs(e){let s=0;for(const n of e)s=Math.max(s,n.length);return{width:s,height:e.length}}r(wfs,"spriteSize");function kfs(){const e=(0,m.useRef)(null),s=(0,m.useRef)(null);return(0,m.useEffect)(()=>{if(!e.current)return;const n=e.current,a=window.matchMedia("(prefers-reduced-motion: reduce)");let i=document.visibilityState!=="hidden",o=!1,l=0,c=0,d=0,u=0,h=7,p=11,f=new Float32Array(0),x=new Float32Array(0),g=new Float32Array(0),v=new Uint16Array(0),y=[],k="";function w(M){const Q=Math.floor(Math.max(0,Math.min(.999,M))*xge.length);return xge[Q]??" "}r(w,"toGlyph");function N(){const M=Math.max(0,Math.ceil(n.clientWidth/Math.max(1,h))),Q=Math.max(0,Math.ceil(n.clientHeight/Math.max(1,p)));if(M===d&&Q===u)return;d=M,u=Q;const L=d*u;f=new Float32Array(L),x=new Float32Array(d),g=new Float32Array(u),v=new Uint16Array(L),y=y.filter(F=>F.x>-F.width-2&&F.x<d+2&&F.y>-F.height-2&&F.y<u+2),k=""}r(N,"rebuildGrid");function S(){if(d<=0||u<=0){n.textContent="";return}const M=Array.from({length:u},()=>Array.from({length:d},()=>" "));for(let q=0;q<u;q++)for(let z=0;z<d;z++){const K=(Math.sin(z*.11+q*.04)+Math.cos(q*.08-z*.02))*.18+.22;M[q][z]=w(K)}const Q=18,L=13;for(let q=1;q<u-9;q+=L){const z=Math.floor(q/L)%2===0?2:10;for(let K=z;K<d-10;K+=Q){const U=BT[(K+q)%BT.length];for(let V=0;V<U.length;V++){const ne=U[V];for(let Z=0;Z<ne.length;Z++){const ie=ne[Z]??" ";if(ie===" ")continue;const J=q+V,ae=K+Z;J<0||J>=u||ae<0||ae>=d||(M[J][ae]=ie)}}}}const F=M.map(q=>q.join("")).join(`
705
705
  `);n.textContent=F,k=F}r(S,"drawStaticFrame");function C(){const M=BT[Math.floor(Math.random()*BT.length)],Q=wfs(M),L=Math.random();let F=0,q=0,z=0,K=0;L<.68?(F=Math.random()<.5?-Q.width-1:d+1,q=Math.random()*Math.max(1,u-Q.height),z=F<0?.04+Math.random()*.05:-(.04+Math.random()*.05),K=(Math.random()-.5)*.014):(F=Math.random()*Math.max(1,d-Q.width),q=Math.random()<.5?-Q.height-1:u+1,z=(Math.random()-.5)*.014,K=q<0?.028+Math.random()*.034:-(.028+Math.random()*.034)),y.push({x:F,y:q,vx:z,vy:K,life:0,maxLife:260+Math.random()*220,drift:(Math.random()-.5)*1.2,sprite:M,width:Q.width,height:Q.height})}r(C,"spawnClip");function _(M,Q){const L=Math.round(M.x),F=Math.round(M.y);for(let q=0;q<M.sprite.length;q++){const z=M.sprite[q],K=F+q;if(!(K<0||K>=u))for(let U=0;U<z.length;U++){const V=z[U]??" ";if(V===" ")continue;const ne=L+U;if(ne<0||ne>=d)continue;const Z=K*d+ne,ie=V==="│"||V==="─"?.8:.92;f[Z]=Math.max(f[Z]??0,Q*ie),v[Z]=V.charCodeAt(0)}}}r(_,"stampClip");function R(M){if(!o||(s.current=requestAnimationFrame(R),M-l<jfs||d<=0||u<=0))return;const Q=Math.min(2,l===0?1:(M-l)/16.6667);l=M,c+=Q;const L=d*u,F=Math.max(3,Math.floor(L/2200));for(;y.length<F;)C();for(let z=0;z<f.length;z++)f[z]*=.92;v.fill(0);for(let z=y.length-1;z>=0;z--){const K=y[z];K.life+=Q;const U=Math.sin((K.y+K.drift+c*.12)*.09)*.0018,V=Math.cos((K.x-K.drift-c*.09)*.08)*.0014;if(K.vx=(K.vx+U)*.998,K.vy=(K.vy+V)*.998,K.x+=K.vx*Q,K.y+=K.vy*Q,K.life>=K.maxLife||K.x<-K.width-2||K.x>d+2||K.y<-K.height-2||K.y>u+2){y.splice(z,1);continue}const ne=K.life/K.maxLife;_(K,ne<.12?ne/.12:ne>.88?(1-ne)/.12:1)}for(let z=0;z<d;z++)x[z]=Math.sin(z*.08+c*.06);for(let z=0;z<u;z++)g[z]=Math.cos(z*.1-c*.05);let q="";for(let z=0;z<u;z++){for(let K=0;K<d;K++){const U=z*d+K,V=v[U];if(V>0){q+=String.fromCharCode(V);continue}const ne=(x[K]+g[z])*.08+.1,Z=Math.max(f[U]??0,ne*.45);q+=w(Z)}z<u-1&&(q+=`
706
- `)}q!==k&&(n.textContent=q,k=q)}r(R,"step");function I(){const M=d>0&&u>0;if(a.matches){o&&(o=!1,s.current!==null&&cancelAnimationFrame(s.current),s.current=null),M&&S();return}if(!i||!M){o&&(o=!1,s.current!==null&&cancelAnimationFrame(s.current),s.current=null);return}o||(o=!0,l=0,s.current=requestAnimationFrame(R))}r(I,"syncLoop");const T=new ResizeObserver(()=>{const M=gge(n);h=M.w,p=M.h,N(),I()});T.observe(n);const E=r(()=>{i=document.visibilityState!=="hidden",I()},"onVisibilityChange");document.addEventListener("visibilitychange",E);const P=r(()=>{I()},"onMotionChange");a.addEventListener("change",P);const O=gge(n);return h=O.w,p=O.h,N(),I(),()=>{o=!1,s.current!==null&&cancelAnimationFrame(s.current),T.disconnect(),document.removeEventListener("visibilitychange",E),a.removeEventListener("change",P)}},[]),(0,t.jsx)("pre",{ref:e,className:"w-full h-full m-0 p-0 overflow-hidden text-muted-foreground/60 select-none leading-none",style:{fontSize:"var(--text-micro)",fontFamily:"monospace"},"aria-hidden":"true"})}r(kfs,"AsciiArtAnimation");function Nfs({decorative:e=!1,title:s="Paperclip",className:n,...a}){return(0,t.jsxs)("svg",{...a,className:n,viewBox:"22.5 22.5 121 27",fill:"currentColor",role:e?void 0:"img","aria-hidden":e?!0:void 0,"aria-label":e?void 0:s,focusable:"false",children:[(0,t.jsx)("path",{d:"M131.15 48.4902V31.9902H133.922V33.9775H134.094C134.237 33.6911 134.441 33.3831 134.706 33.0537C134.971 32.7171 135.329 32.4307 135.78 32.1943C136.239 31.958 136.822 31.8398 137.531 31.8398C138.455 31.8398 139.289 32.0762 140.034 32.5488C140.779 33.0215 141.37 33.7161 141.807 34.6328C142.251 35.5495 142.473 36.6774 142.473 38.0166C142.473 39.3343 142.258 40.4551 141.828 41.3789C141.398 42.3027 140.808 43.0081 140.056 43.4951C139.311 43.9749 138.466 44.2148 137.521 44.2148C136.84 44.2148 136.271 44.1003 135.812 43.8711C135.361 43.6348 134.996 43.3555 134.717 43.0332C134.445 42.7038 134.237 42.3923 134.094 42.0986H133.976V48.4902H131.15ZM136.747 41.8945C137.37 41.8945 137.889 41.7262 138.305 41.3896C138.727 41.0531 139.046 40.5911 139.261 40.0039C139.476 39.4167 139.583 38.7507 139.583 38.0059C139.583 37.2611 139.476 36.5986 139.261 36.0186C139.046 35.4385 138.731 34.9837 138.315 34.6543C137.9 34.3249 137.377 34.1602 136.747 34.1602C136.138 34.1602 135.623 34.3177 135.2 34.6328C134.785 34.9479 134.466 35.3955 134.244 35.9756C134.029 36.5485 133.922 37.2253 133.922 38.0059C133.922 38.7793 134.029 39.4596 134.244 40.0469C134.466 40.627 134.788 41.0817 135.211 41.4111C135.633 41.7334 136.146 41.8945 136.747 41.8945Z"}),(0,t.jsx)("path",{d:"M126.451 44V31.9902H129.276V44H126.451ZM127.869 30.3037C127.417 30.3037 127.031 30.1533 126.708 29.8525C126.386 29.5518 126.225 29.1901 126.225 28.7676C126.225 28.3379 126.386 27.9727 126.708 27.6719C127.031 27.3711 127.417 27.2207 127.869 27.2207C128.313 27.2207 128.696 27.3711 129.018 27.6719C129.34 27.9727 129.501 28.3343 129.501 28.7568C129.501 29.1865 129.34 29.5518 129.018 29.8525C128.696 30.1533 128.313 30.3037 127.869 30.3037Z"}),(0,t.jsx)("path",{d:"M124.576 27.9941V44H121.75V27.9941H124.576Z"}),(0,t.jsx)("path",{d:"M115.3 44.2363C114.104 44.2363 113.076 43.9749 112.217 43.4521C111.357 42.9222 110.699 42.1917 110.24 41.2607C109.782 40.3298 109.553 39.2591 109.553 38.0488C109.553 36.8242 109.785 35.7464 110.251 34.8154C110.716 33.8844 111.379 33.1576 112.238 32.6348C113.098 32.1048 114.111 31.8398 115.278 31.8398C116.259 31.8398 117.126 32.0189 117.878 32.377C118.63 32.735 119.228 33.2399 119.672 33.8916C120.123 34.5361 120.381 35.2917 120.445 36.1582H117.738C117.667 35.7715 117.527 35.4242 117.319 35.1162C117.112 34.8083 116.84 34.5648 116.503 34.3857C116.174 34.2067 115.78 34.1172 115.321 34.1172C114.741 34.1172 114.233 34.2747 113.796 34.5898C113.366 34.8978 113.03 35.3418 112.786 35.9219C112.543 36.502 112.421 37.1966 112.421 38.0059C112.421 38.8223 112.539 39.5277 112.775 40.1221C113.012 40.7093 113.348 41.1641 113.785 41.4863C114.222 41.8014 114.734 41.959 115.321 41.959C115.944 41.959 116.471 41.7764 116.9 41.4111C117.337 41.0459 117.617 40.541 117.738 39.8965H120.445C120.381 40.7487 120.13 41.5007 119.693 42.1523C119.257 42.804 118.666 43.3161 117.921 43.6885C117.176 44.0537 116.302 44.2363 115.3 44.2363Z"}),(0,t.jsx)("path",{d:"M102.876 44V31.9902H105.615V34.0098H105.744C105.959 33.3079 106.335 32.7708 106.872 32.3984C107.409 32.0189 108.021 31.8291 108.709 31.8291C108.859 31.8291 109.031 31.8363 109.225 31.8506C109.425 31.8649 109.59 31.8828 109.719 31.9043V34.5039C109.597 34.4609 109.407 34.4251 109.149 34.3965C108.892 34.3678 108.645 34.3535 108.408 34.3535C107.885 34.3535 107.42 34.4645 107.012 34.6865C106.604 34.9085 106.281 35.2129 106.045 35.5996C105.816 35.9863 105.701 36.4375 105.701 36.9531V44H102.876Z"}),(0,t.jsx)("path",{d:"M96.2319 44.2363C95.0288 44.2363 93.9904 43.9857 93.1167 43.4844C92.243 42.9759 91.5698 42.2598 91.0972 41.3359C90.6317 40.4121 90.3989 39.3236 90.3989 38.0703C90.3989 36.8314 90.6317 35.7464 91.0972 34.8154C91.5627 33.8773 92.2179 33.1468 93.063 32.624C93.908 32.1012 94.9035 31.8398 96.0493 31.8398C96.7869 31.8398 97.4852 31.958 98.144 32.1943C98.8101 32.4307 99.3973 32.7959 99.9058 33.29C100.421 33.7842 100.826 34.4144 101.12 35.1807C101.413 35.9398 101.56 36.8457 101.56 37.8984V38.7793H91.7202V36.8779H100.153L98.8315 37.4365C98.8315 36.7562 98.7277 36.1654 98.52 35.6641C98.3123 35.1556 98.0044 34.7581 97.5962 34.4717C97.188 34.1852 96.6795 34.042 96.0708 34.042C95.4621 34.042 94.9429 34.1852 94.5132 34.4717C94.0835 34.7581 93.7576 35.1449 93.5356 35.6318C93.3136 36.1117 93.2026 36.6488 93.2026 37.2432V38.5645C93.2026 39.2949 93.328 39.9215 93.5786 40.4443C93.8364 40.96 94.1945 41.3538 94.6528 41.626C95.1183 41.8981 95.659 42.0342 96.2749 42.0342C96.6759 42.0342 97.0412 41.9769 97.3706 41.8623C97.7072 41.7477 97.9937 41.5758 98.23 41.3467C98.4735 41.1104 98.6597 40.8203 98.7886 40.4766L101.431 40.7881C101.259 41.4827 100.941 42.0915 100.475 42.6143C100.017 43.1299 99.4259 43.5309 98.7026 43.8174C97.9865 44.0967 97.1629 44.2363 96.2319 44.2363Z"}),(0,t.jsx)("path",{d:"M78.2437 48.4902V31.9902H81.0151V33.9775H81.187C81.3302 33.6911 81.5343 33.3831 81.7993 33.0537C82.0643 32.7171 82.4224 32.4307 82.8735 32.1943C83.3319 31.958 83.9155 31.8398 84.6245 31.8398C85.5483 31.8398 86.3826 32.0762 87.1274 32.5488C87.8722 33.0215 88.4631 33.7161 88.8999 34.6328C89.3439 35.5495 89.5659 36.6774 89.5659 38.0166C89.5659 39.3343 89.3511 40.4551 88.9214 41.3789C88.4917 42.3027 87.9009 43.0081 87.1489 43.4951C86.4041 43.9749 85.5591 44.2148 84.6138 44.2148C83.9334 44.2148 83.3641 44.1003 82.9058 43.8711C82.4546 43.6348 82.0894 43.3555 81.8101 43.0332C81.5379 42.7038 81.3302 42.3923 81.187 42.0986H81.0688V48.4902H78.2437ZM83.8403 41.8945C84.4634 41.8945 84.9826 41.7262 85.3979 41.3896C85.8205 41.0531 86.1392 40.5911 86.354 40.0039C86.5688 39.4167 86.6763 38.7507 86.6763 38.0059C86.6763 37.2611 86.5688 36.5986 86.354 36.0186C86.1392 35.4385 85.8241 34.9837 85.4087 34.6543C84.9933 34.3249 84.4705 34.1602 83.8403 34.1602C83.2316 34.1602 82.716 34.3177 82.2935 34.6328C81.8781 34.9479 81.5594 35.3955 81.3374 35.9756C81.1226 36.5485 81.0151 37.2253 81.0151 38.0059C81.0151 38.7793 81.1226 39.4596 81.3374 40.0469C81.5594 40.627 81.8817 41.0817 82.3042 41.4111C82.7267 41.7334 83.2388 41.8945 83.8403 41.8945Z"}),(0,t.jsx)("path",{d:"M70.042 44.2471C69.2757 44.2471 68.5882 44.111 67.9795 43.8389C67.3708 43.5596 66.891 43.1514 66.54 42.6143C66.1891 42.0771 66.0137 41.4147 66.0137 40.627C66.0137 39.9538 66.139 39.3952 66.3896 38.9512C66.6403 38.5072 66.9805 38.1527 67.4102 37.8877C67.847 37.6227 68.3376 37.4222 68.8818 37.2861C69.4261 37.1429 69.9883 37.0426 70.5684 36.9854C71.2773 36.9066 71.8503 36.8385 72.2871 36.7812C72.724 36.724 73.0391 36.6309 73.2324 36.502C73.4329 36.373 73.5332 36.1725 73.5332 35.9004V35.8467C73.5332 35.2666 73.3613 34.8154 73.0176 34.4932C72.6738 34.1709 72.1725 34.0098 71.5137 34.0098C70.819 34.0098 70.2676 34.1602 69.8594 34.4609C69.4583 34.7617 69.1862 35.1162 69.043 35.5244L66.4111 35.1484C66.6188 34.418 66.9626 33.8092 67.4424 33.3223C67.9222 32.8281 68.5059 32.4593 69.1934 32.2158C69.888 31.9652 70.6543 31.8398 71.4922 31.8398C72.0651 31.8398 72.638 31.9079 73.2109 32.0439C73.7839 32.1729 74.3102 32.3949 74.79 32.71C75.2699 33.0251 75.653 33.4476 75.9395 33.9775C76.2259 34.5075 76.3691 35.1699 76.3691 35.9648V44H73.6514V42.3457H73.5654C73.3936 42.6751 73.1501 42.9867 72.835 43.2803C72.527 43.5667 72.1403 43.7995 71.6748 43.9785C71.2165 44.1576 70.6722 44.2471 70.042 44.2471ZM70.7617 42.1631C71.3346 42.1631 71.8288 42.0521 72.2441 41.8301C72.6595 41.6009 72.9818 41.3001 73.2109 40.9277C73.4401 40.5482 73.5547 40.1364 73.5547 39.6924V38.2852C73.4616 38.3568 73.3112 38.4248 73.1035 38.4893C72.8958 38.5465 72.6595 38.6003 72.3945 38.6504C72.1296 38.7005 71.8682 38.7435 71.6104 38.7793C71.3597 38.8151 71.1413 38.8438 70.9551 38.8652C70.5326 38.9225 70.153 39.0192 69.8164 39.1553C69.487 39.2842 69.2256 39.4632 69.0322 39.6924C68.8389 39.9215 68.7422 40.2188 68.7422 40.584C68.7422 41.1068 68.932 41.5007 69.3115 41.7656C69.6911 42.0306 70.1745 42.1631 70.7617 42.1631Z"}),(0,t.jsx)("path",{d:"M53.7939 44V27.9941H59.7988C61.0306 27.9941 62.0618 28.2233 62.8926 28.6816C63.7305 29.14 64.3643 29.7702 64.7939 30.5723C65.2236 31.3743 65.4385 32.2839 65.4385 33.3008C65.4385 34.3249 65.2201 35.238 64.7832 36.04C64.3535 36.835 63.7161 37.4616 62.8711 37.9199C62.026 38.3711 60.9876 38.5967 59.7559 38.5967H55.7812V36.2119H59.3584C60.0817 36.2119 60.6725 36.0902 61.1309 35.8467C61.5964 35.596 61.9365 35.2523 62.1514 34.8154C62.3734 34.3714 62.4844 33.8665 62.4844 33.3008C62.4844 32.7279 62.3734 32.2266 62.1514 31.7969C61.9365 31.36 61.5964 31.0234 61.1309 30.7871C60.6725 30.5436 60.0781 30.4219 59.3477 30.4219H56.6943V44H53.7939Z"}),(0,t.jsx)("path",{d:"M46.2611 33.6556L34.7307 44.6408C32.7445 46.5331 29.5205 46.5323 27.5303 44.6361C25.5404 42.74 25.54 39.669 27.5261 37.7768L39.0565 26.7916C40.2474 25.657 42.1811 25.6567 43.3752 26.7943C44.5693 27.9319 44.5689 29.7742 43.378 30.9088L31.849 41.8954C31.4528 42.2728 30.8077 42.273 30.4092 41.8933C30.011 41.5136 30.0117 40.8996 30.4078 40.5223L41.9382 29.5371C42.336 29.1581 42.336 28.5437 41.9382 28.1647C41.5404 27.786 40.8954 27.7858 40.4977 28.1647L28.9673 39.1499C27.7742 40.2866 27.7764 42.1295 28.9687 43.2657C30.1613 44.402 32.0963 44.4046 33.2895 43.2678L44.8192 32.2805C46.8068 30.3865 46.8038 27.3159 44.8157 25.4219C42.8275 23.5277 39.6039 23.5253 37.616 25.4192L26.0856 36.4044C23.3024 39.056 23.3058 43.3558 26.0898 46.0085C28.8741 48.6612 33.388 48.6649 36.1712 46.0132L47.7017 35.028C48.0994 34.649 48.0994 34.0346 47.7017 33.6556C47.3039 33.2766 46.6589 33.2766 46.2611 33.6556Z"})]})}r(Nfs,"PaperclipLockup");function Sfs(){const e=wt(),s=Gn(),[n]=hi(),[a,i]=(0,m.useState)("sign_in"),[o,l]=(0,m.useState)(""),[c,d]=(0,m.useState)(""),[u,h]=(0,m.useState)(""),[p,f]=(0,m.useState)(null),x="auth-error",g=(0,m.useMemo)(()=>M5e(n.get("next")||yfs()||"/"),[n]),v=te({queryKey:D.health,queryFn:r(()=>Lu.get(),"queryFn"),retry:!1}),{data:y,isLoading:k,error:w}=te({queryKey:D.auth.session,queryFn:r(()=>Pa.getSession(),"queryFn"),retry:!1});(0,m.useEffect)(()=>{y&&(mG(),s(g,{replace:!0}))},[y,s,g]);const N=we({mutationFn:r(async()=>{if(a==="sign_in"){await Pa.signInEmail({email:c.trim(),password:u});return}await Pa.signUpEmail({name:o.trim(),email:c.trim(),password:u})},"mutationFn"),onSuccess:r(async()=>{f(null),await e.invalidateQueries({queryKey:D.auth.session}),await e.invalidateQueries({queryKey:D.health}),await e.resetQueries({queryKey:D.companies.all}),s(g,{replace:!0})},"onSuccess"),onError:r(C=>{f(C instanceof Error?C.message:"Authentication failed")},"onError")}),S=c.trim().length>0&&u.trim().length>0&&(a==="sign_in"||o.trim().length>0&&u.trim().length>=8);return v.isLoading||k||y?(0,t.jsx)("div",{className:"fixed inset-0 flex items-center justify-center",children:(0,t.jsx)(ch,{className:"min-h-0"})}):v.error||w?(0,t.jsx)("p",{role:"alert",className:"p-6 text-sm text-destructive",children:"Unable to check sign-in. Refresh and try again."}):v.data?.cloud?(0,t.jsx)(hG,{cloud:v.data.cloud,returnTo:g}):(0,t.jsxs)("div",{className:"fixed inset-0 flex bg-background",children:[(0,t.jsx)("div",{className:"absolute top-4 right-4 z-10",children:(0,t.jsx)(Ek,{})}),(0,t.jsx)("div",{className:"w-full md:w-1/2 flex flex-col overflow-y-auto",children:(0,t.jsxs)("div",{className:"w-full max-w-md mx-auto my-auto px-8 py-12",children:[(0,t.jsx)("div",{className:"mb-8",children:(0,t.jsx)(Nfs,{className:"h-5 w-auto"})}),(0,t.jsx)("h1",{className:"text-xl font-semibold",children:a==="sign_in"?"Sign in to Paperclip":"Create your Paperclip account"}),(0,t.jsx)("p",{className:"mt-1 text-sm text-muted-foreground",children:a==="sign_in"?"Use your email and password to access this instance.":"Create an account for this instance. Email confirmation is not required in v1."}),(0,t.jsxs)("form",{className:"mt-6 space-y-4",method:"post",action:a==="sign_up"?"/api/auth/sign-up/email":"/api/auth/sign-in/email",onSubmit:r(C=>{if(C.preventDefault(),!N.isPending){if(!S){f("Please fill in all required fields.");return}N.mutate()}},"onSubmit"),children:[a==="sign_up"&&(0,t.jsxs)("div",{children:[(0,t.jsx)("label",{htmlFor:"name",className:"text-xs text-muted-foreground mb-1 block",children:"Name"}),(0,t.jsx)("input",{id:"name",name:"name",className:"w-full rounded-md border border-border bg-transparent px-3 py-2 text-sm outline-none focus:ring-1 focus:ring-ring placeholder:text-muted-foreground/50",value:o,onChange:r(C=>l(C.target.value),"onChange"),autoComplete:"name",required:!0,"aria-required":"true","aria-invalid":p?!0:void 0,"aria-describedby":p?x:void 0,autoFocus:!0})]}),(0,t.jsxs)("div",{children:[(0,t.jsx)("label",{htmlFor:"email",className:"text-xs text-muted-foreground mb-1 block",children:"Email"}),(0,t.jsx)("input",{id:"email",name:"email",className:"w-full rounded-md border border-border bg-transparent px-3 py-2 text-sm outline-none focus:ring-1 focus:ring-ring placeholder:text-muted-foreground/50",type:"email",value:c,onChange:r(C=>d(C.target.value),"onChange"),autoComplete:"username",required:!0,"aria-required":"true","aria-invalid":p?!0:void 0,"aria-describedby":p?x:void 0,autoFocus:a==="sign_in"})]}),(0,t.jsxs)("div",{children:[(0,t.jsx)("label",{htmlFor:"password",className:"text-xs text-muted-foreground mb-1 block",children:"Password"}),(0,t.jsx)("input",{id:"password",name:"password",className:"w-full rounded-md border border-border bg-transparent px-3 py-2 text-sm outline-none focus:ring-1 focus:ring-ring placeholder:text-muted-foreground/50",type:"password",value:u,onChange:r(C=>h(C.target.value),"onChange"),autoComplete:a==="sign_in"?"current-password":"new-password",required:!0,"aria-required":"true","aria-invalid":p?!0:void 0,"aria-describedby":p?x:void 0})]}),p&&(0,t.jsx)("p",{id:x,role:"alert",className:"text-xs text-destructive",children:p}),(0,t.jsx)($,{type:"submit",disabled:N.isPending,"aria-disabled":!S||N.isPending,className:`w-full ${!S&&!N.isPending?"opacity-50":""}`,children:N.isPending?"Working…":a==="sign_in"?"Sign In":"Create Account"})]}),(0,t.jsxs)("div",{className:"mt-5 text-sm text-muted-foreground",children:[a==="sign_in"?"Need an account?":"Already have an account?"," ",(0,t.jsx)("button",{type:"button",className:"font-medium text-foreground underline underline-offset-2",onClick:r(()=>{f(null),i(a==="sign_in"?"sign_up":"sign_in")},"onClick"),children:a==="sign_in"?"Create one":"Sign in"})]})]})}),(0,t.jsx)("div",{className:"hidden md:block w-1/2 overflow-hidden",children:(0,t.jsx)(kfs,{})})]})}r(Sfs,"AuthPage");function Cfs(){const e=wt(),s=xa(),[n]=hi(),a=(s.token??"").trim(),i=(n.get("code")??"").trim(),o=(0,m.useMemo)(()=>`/board-claim/${encodeURIComponent(a)}${i?`?code=${encodeURIComponent(i)}`:""}`,[a,i]),l=te({queryKey:D.auth.session,queryFn:r(()=>Pa.getSession(),"queryFn"),retry:!1}),c=te({queryKey:["board-claim",a,i],queryFn:r(()=>or.getBoardClaimStatus(a,i),"queryFn"),enabled:a.length>0&&i.length>0,retry:!1}),d=we({mutationFn:r(()=>or.claimBoard(a,i),"mutationFn"),onSuccess:r(async()=>{await e.invalidateQueries({queryKey:D.auth.session}),await e.invalidateQueries({queryKey:D.health}),await e.invalidateQueries({queryKey:D.companies.all}),await e.invalidateQueries({queryKey:D.companies.stats}),await c.refetch()},"onSuccess")});if(!a||!i)return(0,t.jsx)("div",{className:"mx-auto max-w-xl py-10 text-sm text-destructive",children:"Invalid board claim URL."});if(c.isLoading||l.isLoading)return(0,t.jsx)("div",{className:"mx-auto max-w-xl py-10 text-sm text-muted-foreground",children:"Loading claim challenge..."});if(c.error)return(0,t.jsx)("div",{className:"mx-auto max-w-xl py-10",children:(0,t.jsxs)(sn,{className:"block p-6",children:[(0,t.jsx)("h1",{className:"text-lg font-semibold",children:"Claim challenge unavailable"}),(0,t.jsx)("p",{className:"mt-2 text-sm text-muted-foreground",children:c.error instanceof Error?c.error.message:"Challenge is invalid or expired."})]})});const u=c.data;return u?u.status==="claimed"?(0,t.jsx)("div",{className:"mx-auto max-w-xl py-10",children:(0,t.jsxs)(sn,{className:"block p-6",children:[(0,t.jsx)("h1",{className:"text-lg font-semibold",children:"Board ownership claimed"}),(0,t.jsx)("p",{className:"mt-2 text-sm text-muted-foreground",children:"This instance is now linked to your authenticated user."}),(0,t.jsx)($,{asChild:!0,className:"mt-4",children:(0,t.jsx)(We,{to:"/",children:"Open board"})})]})}):l.data?(0,t.jsx)("div",{className:"mx-auto max-w-xl py-10",children:(0,t.jsxs)(sn,{className:"block p-6",children:[(0,t.jsx)("h1",{className:"text-xl font-semibold",children:"Claim Board ownership"}),(0,t.jsx)("p",{className:"mt-2 text-sm text-muted-foreground",children:"This will promote your user to instance admin and migrate organization ownership access from local trusted mode."}),d.error&&(0,t.jsx)("p",{className:"mt-3 text-sm text-destructive",children:d.error instanceof Error?d.error.message:"Failed to claim board ownership"}),(0,t.jsx)($,{className:"mt-5",onClick:r(()=>d.mutate(),"onClick"),disabled:d.isPending,children:d.isPending?"Claiming…":"Claim ownership"})]})}):(0,t.jsx)("div",{className:"mx-auto max-w-xl py-10",children:(0,t.jsxs)(sn,{className:"block p-6",children:[(0,t.jsx)("h1",{className:"text-lg font-semibold",children:"Sign in required"}),(0,t.jsx)("p",{className:"mt-2 text-sm text-muted-foreground",children:"Sign in or create an account, then return to this page to claim Board ownership."}),(0,t.jsx)($,{asChild:!0,className:"mt-4",children:(0,t.jsx)(We,{to:`/auth?next=${encodeURIComponent(o)}`,children:"Sign in / Create account"})})]})}):(0,t.jsx)("div",{className:"mx-auto max-w-xl py-10 text-sm text-destructive",children:"Claim challenge unavailable."})}r(Cfs,"BoardClaimPage");function bge({origin:e}){const[s,n]=(0,m.useState)(!1);let a;try{const i=new URL(e);i.origin==="https://claude.ai"?a="/brands/claude-color.svg":["https://chatgpt.com","https://chat.openai.com","https://openai.com"].includes(i.origin)&&(a="/brands/codex-color.svg")}catch{}return(0,t.jsxs)("div",{className:"flex items-center gap-2 text-sm text-muted-foreground",children:[a&&!s?(0,t.jsx)("img",{src:a,alt:"",className:"size-4 shrink-0 object-contain",referrerPolicy:"no-referrer",crossOrigin:"anonymous",onError:r(()=>n(!0),"onError")}):(0,t.jsx)(wm,{className:"size-4 shrink-0","aria-hidden":"true"}),(0,t.jsx)("bdi",{className:"min-w-0 break-all",children:e})]})}r(bge,"ClientOrigin");function vge({agentPairingOnly:e=!1}={}){const{id:s=""}=xa();return(0,t.jsx)(R9e,{id:s,agentPairingOnly:e},s)}r(vge,"McpConnectPage");function _fs({initialCode:e}={}){const[s,n]=(0,m.useState)(e??new URLSearchParams(window.location.search).get("user_code")??""),[a,i]=(0,m.useState)(s);return a?(0,t.jsx)(R9e,{id:a,device:!0,onEditCode:r(()=>i(""),"onEditCode")},a):(0,t.jsx)("div",{className:"mx-auto max-w-xl py-10",children:(0,t.jsxs)(sn,{className:"space-y-4 p-6",children:[(0,t.jsxs)("div",{className:"flex items-center gap-3",children:[(0,t.jsx)(kl,{className:"size-8 shrink-0"}),(0,t.jsx)("h1",{className:"min-w-0 text-xl font-semibold",children:"Connect your assistant to Paperclip"})]}),(0,t.jsxs)("form",{className:"space-y-4",onSubmit:r(o=>{o.preventDefault(),i(s.trim())},"onSubmit"),children:[(0,t.jsx)("label",{htmlFor:"device-code",className:"text-sm",children:"Enter the code shown by your assistant"}),(0,t.jsx)(dt,{id:"device-code",autoComplete:"off",value:s,onChange:r(o=>n(o.target.value),"onChange"),required:!0,maxLength:12}),(0,t.jsx)("div",{className:"flex justify-end",children:(0,t.jsx)($,{type:"submit",children:"Continue"})})]})]})})}r(_fs,"McpDevicePage");function R9e({id:e,device:s=!1,agentPairingOnly:n=!1,onEditCode:a}){const i=n?"/dot-mcp/requests":"/mcp/requests",[o,l]=(0,m.useState)(""),[c,d]=(0,m.useState)(""),[u,h]=(0,m.useState)(null),[p,f]=(0,m.useState)(""),[x,g]=(0,m.useState)(!0),[v,y]=(0,m.useState)(null),k=te({queryKey:[s?"mcp-device":n?"dot-mcp-request":"mcp-request",e],queryFn:r(()=>ke.get(s?`/mcp/device?user_code=${encodeURIComponent(e)}`:`${i}/${encodeURIComponent(e)}`),"queryFn"),retry:!1}),w=k.data;(0,m.useEffect)(()=>{if(h(null),f(""),!w?.agentConnection||s||!/^[A-Za-z0-9_-]{32}$/.test(c.trim()))return;let Q=!0;return ke.post(`${i}/${encodeURIComponent(e)}/dot-pairing/preview`,{pairingCode:c.trim()}).then(L=>{Q&&h(L)}).catch(L=>{Q&&f(L instanceof Error?L.message:"Unable to verify this pairing code.")}),()=>{Q=!1}},[e,s,i,w?.agentConnection,c]);const N=w?.requestedCompanyId??(o||w?.companies[0]?.id||"");(0,m.useEffect)(()=>{!o&&!w?.requestedCompanyId&&w?.companies[0]&&l(w.companies[0].id)},[o,w]);const S=w?.clientName.trim(),C=S&&!/^(assistant|mcp client)$/i.test(S)?S:"your assistant",_=w?.clientOrigin||w?.redirectOrigin,R=w?.companies.find(Q=>Q.id===N),I=!!(!w?.agentConnection&&R?.canWrite&&x),T=!!(w?.requestedWrite&&I),E=!!(w?.requestedConfigure&&I),P=we({mutationFn:r(Q=>ke.post(s?"/mcp/device/consent":`/mcp/requests/${encodeURIComponent(e)}/consent`,{decision:Q,companyId:N||void 0,allowWrites:Q==="approve"&&T,allowConfiguration:Q==="approve"&&E,...s?{userCode:e}:{}}),"mutationFn"),onSuccess:r(({redirectUrl:Q,status:L})=>{s&&L?y(L):Q&&window.location.assign(Q)},"onSuccess")}),O=we({mutationFn:r(()=>ke.post(`${i}/${encodeURIComponent(e)}/dot-pairing`,{pairingCode:c.trim()}),"mutationFn"),onSuccess:r(({redirectUrl:Q})=>{d(""),window.location.assign(Q)},"onSuccess")});if(v)return(0,t.jsx)("div",{className:"mx-auto max-w-xl py-10",children:(0,t.jsxs)(sn,{className:"block space-y-4 p-6",children:[(0,t.jsx)(kl,{className:"size-8"}),(0,t.jsx)("h1",{className:"text-xl font-semibold",children:v==="approved"?"Access approved":"Connection declined"}),(0,t.jsx)("p",{className:"text-sm",children:v==="approved"?"Return to your assistant. It will finish connecting automatically.":"No access was granted. You can start a new connection from your assistant."}),(0,t.jsx)($,{variant:"outline",asChild:!0,children:(0,t.jsx)(We,{to:"/",children:"Back to Paperclip"})})]})});const M=s?`/mcp-device?user_code=${encodeURIComponent(e)}`:`${n?"/dot-connect":"/mcp-connect"}/${e}`;return(0,t.jsx)("div",{className:"mx-auto max-w-xl py-10",children:(0,t.jsxs)(sn,{className:"block space-y-4 p-6",children:[(0,t.jsxs)("div",{className:"flex items-center gap-3",children:[(0,t.jsx)(kl,{className:"size-8 shrink-0 text-foreground",role:"img","aria-label":"Paperclip"}),(0,t.jsxs)("h1",{className:"min-w-0 break-words text-xl font-semibold",children:["Connect ",(0,t.jsx)("bdi",{children:C})," to Paperclip"]})]}),_&&(0,t.jsx)(bge,{origin:_},_),!s&&w?.redirectOrigin&&w.redirectOrigin!==_&&(0,t.jsx)(bge,{origin:w.redirectOrigin},w.redirectOrigin),s&&(0,t.jsxs)("p",{className:"text-sm",children:["Confirm this matches the code shown by your assistant: ",(0,t.jsx)("strong",{className:"font-mono",children:e.toUpperCase()})]}),k.isPending&&(0,t.jsx)("p",{className:"text-sm text-muted-foreground",children:"Loading connection request…"}),k.error&&(0,t.jsxs)("p",{className:"text-sm text-destructive",children:[k.error.message," Start a new connection from your assistant."]}),s&&k.error&&(0,t.jsx)($,{variant:"outline",onClick:a,children:"Enter a different code"}),w?.agentConnection&&!s&&(0,t.jsxs)("form",{className:"space-y-3",onSubmit:r(Q=>{Q.preventDefault(),O.mutate()},"onSubmit"),children:[(0,t.jsx)("p",{className:"text-sm",children:"Enter the one-use code from your Dot setup prompt to review this agent’s access. Access is granted when you click “Connect Dot with pairing code”."}),(0,t.jsx)("label",{htmlFor:"dot-pairing-code",className:"text-sm",children:"Pairing code"}),(0,t.jsx)(dt,{id:"dot-pairing-code",type:"password",autoComplete:"off",value:c,onChange:r(Q=>{h(null),f(""),d(Q.target.value)},"onChange"),required:!0,maxLength:32}),u&&(0,t.jsxs)("dl",{className:"space-y-2 rounded-md border border-border p-3 text-sm",children:[(0,t.jsxs)("div",{children:[(0,t.jsx)("dt",{className:"text-muted-foreground",children:"Company"}),(0,t.jsxs)("dd",{children:[u.company.name," ",(0,t.jsxs)("span",{className:"text-xs text-muted-foreground",children:["(",u.company.id,")"]})]})]}),(0,t.jsxs)("div",{children:[(0,t.jsx)("dt",{className:"text-muted-foreground",children:"Agent"}),(0,t.jsxs)("dd",{children:[u.agent.name," ",(0,t.jsxs)("span",{className:"text-xs text-muted-foreground",children:["(",u.agent.id,")"]})]})]}),(0,t.jsxs)("div",{children:[(0,t.jsx)("dt",{className:"text-muted-foreground",children:"Permissions"}),(0,t.jsx)("dd",{children:u.permissions})]}),(0,t.jsxs)("div",{children:[(0,t.jsx)("dt",{className:"text-muted-foreground",children:"Access duration"}),(0,t.jsx)("dd",{children:u.accessDuration})]})]}),p&&(0,t.jsx)("p",{role:"alert",className:"text-sm text-destructive",children:p}),O.error&&(0,t.jsx)("p",{role:"alert",className:"text-sm text-destructive",children:O.error.message}),(0,t.jsx)("div",{className:"flex justify-end",children:(0,t.jsx)($,{type:"submit",disabled:!u||!/^[A-Za-z0-9_-]{32}$/.test(c.trim())||O.isPending,children:O.isPending?"Connecting…":"Connect Dot with pairing code"})})]}),w&&(0,t.jsx)(t.Fragment,{children:w.requiresSignIn?(0,t.jsx)($,{asChild:!0,children:(0,t.jsx)(We,{to:`/auth?next=${encodeURIComponent(M)}`,children:"Sign in / Create account"})}):(0,t.jsxs)(t.Fragment,{children:[w.requestedCompanyId?(0,t.jsxs)("div",{className:"flex items-center gap-4 rounded-md border border-border p-4",children:[R&&(0,t.jsx)(Zx,{companyName:R.name,logoUrl:R.logoUrl,className:"size-14 shrink-0 rounded-lg text-xl"}),(0,t.jsxs)("div",{className:"min-w-0 space-y-1",children:[(0,t.jsx)("p",{className:"text-xs text-muted-foreground",children:"Organization"}),R?(0,t.jsx)("p",{className:"break-words text-lg font-semibold",children:R.name}):(0,t.jsx)("p",{className:"text-sm text-destructive",children:"The selected organization is no longer available to this account. Cancel and reconnect from your assistant to choose an organization you can access."})]})]}):(0,t.jsxs)("fieldset",{className:"space-y-2",disabled:P.isPending,children:[(0,t.jsx)("legend",{className:"mb-2 text-sm font-medium",children:"Organization"}),w.companies.map(Q=>(0,t.jsxs)("label",{className:"flex items-center gap-3 rounded-md border border-border p-3 text-sm",children:[(0,t.jsx)("input",{type:"radio",name:"company","aria-label":Q.name,value:Q.id,checked:N===Q.id,onChange:r(()=>l(Q.id),"onChange")}),(0,t.jsx)(Zx,{companyName:Q.name,logoUrl:Q.logoUrl,className:"size-12 shrink-0 rounded-lg"}),(0,t.jsx)("span",{className:"min-w-0 break-words font-medium",children:Q.name})]},Q.id)),!w.companies.length&&(0,t.jsx)("p",{className:"text-sm text-muted-foreground",children:"This account has no available organizations. Ask an organization owner to add you, then reconnect from your assistant."})]}),(0,t.jsx)("p",{className:"text-sm",children:w.agentConnection?"Connect Dot as a Paperclip agent. Pair it with an agent after connecting; assigned work uses that agent’s permissions.":"Read all of your Paperclip data"}),(w.requestedWrite||w.requestedConfigure)&&!w.agentConnection&&(0,t.jsxs)("label",{htmlFor:"mcp-allow-writes",className:"flex items-start gap-3 text-sm leading-6",children:[(0,t.jsx)("span",{className:"flex h-6 shrink-0 items-center",children:(0,t.jsx)(ei,{id:"mcp-allow-writes",checked:I,disabled:!R?.canWrite||P.isPending,onCheckedChange:r(Q=>g(Q===!0),"onCheckedChange")})}),(0,t.jsx)("span",{children:"Write all of your Paperclip data"})]}),R&&!R.canWrite&&(0,t.jsx)("p",{className:"text-sm text-muted-foreground",children:"Your role in this organization is read-only."}),P.error&&(0,t.jsx)("p",{className:"text-sm text-destructive",children:P.error.message}),(0,t.jsxs)("div",{className:"flex items-center justify-between gap-3",children:[(0,t.jsx)($,{variant:"outline",disabled:P.isPending,onClick:r(()=>P.mutate("deny"),"onClick"),children:"Cancel"}),(0,t.jsx)($,{className:"h-auto min-h-10 min-w-0 shrink whitespace-normal",disabled:!R||w.agentConnection&&!R.canWrite||P.isPending,onClick:r(()=>P.mutate("approve"),"onClick"),children:P.isPending?"Connecting…":w.agentConnection?"Connect Dot agent":"Connect organization"})]})]})})]})})}r(R9e,"McpConnectRequest");function Afs(){const e=wt(),s=te({queryKey:["mcp-connections"],queryFn:r(()=>ke.get("/mcp/connections"),"queryFn"),retry:!1}),n=s.data?.filter(i=>!i.revokedAt),a=we({mutationFn:r(i=>ke.delete(`/mcp/connections/${i}`),"mutationFn"),onSuccess:r((i,o)=>(e.setQueryData(["mcp-connections"],l=>l?.filter(c=>c.id!==o)),e.invalidateQueries({queryKey:["mcp-connections"]})),"onSuccess")});return(0,t.jsxs)("div",{className:"mx-auto max-w-xl space-y-4 py-10",children:[(0,t.jsx)("h1",{className:"text-xl font-semibold",children:"Assistant connections"}),(0,t.jsx)("p",{className:"text-sm text-muted-foreground",children:"Revoking a connection stops its future tool calls. Work already delegated continues under your organization’s normal controls."}),s.isPending&&(0,t.jsx)("p",{className:"text-sm",children:"Loading connections…"}),(s.error||a.error)&&(0,t.jsx)("p",{className:"text-sm text-destructive",children:(s.error??a.error)?.message}),n?.length===0&&(0,t.jsx)("p",{className:"text-sm",children:"No assistant connections."}),n?.map(i=>(0,t.jsxs)(sn,{className:"block space-y-2 p-4",children:[(0,t.jsx)("h2",{className:"font-medium",children:(0,t.jsx)(yo,{name:Z8(i),avatarUrl:i.user?.image,initials:iv(i.user?.name??"You")})}),(0,t.jsxs)("p",{className:"text-sm text-muted-foreground",children:["Organization: ",i.companyName]}),(0,t.jsx)("p",{className:"text-sm",children:i.scopes.includes("paperclip:agent")?"Dot agent connection":i.scopes.includes("paperclip:write")?"Read and edit work":"Read only"}),i.scopes.includes("paperclip:configure")&&(0,t.jsx)("p",{className:"text-sm",children:"Configure agents, projects and skills"}),(0,t.jsx)($,{variant:"outline",disabled:a.isPending,onClick:r(()=>a.mutate(i.id),"onClick"),children:"Revoke connection"})]},i.id)),(0,t.jsx)(We,{className:"text-sm underline",to:"/",children:"Back to Paperclip"})]})}r(Afs,"AssistantConnectionsPage");function Ifs(){const e=wt(),s=xa(),[n]=hi(),a=(s.id??"").trim(),i=(n.get("token")??"").trim(),o=(0,m.useMemo)(()=>`/cli-auth/${encodeURIComponent(a)}${i?`?token=${encodeURIComponent(i)}`:""}`,[a,i]),l=te({queryKey:D.auth.session,queryFn:r(()=>Pa.getSession(),"queryFn"),retry:!1}),c=te({queryKey:["cli-auth-challenge",a,i],queryFn:r(()=>or.getCliAuthChallenge(a,i),"queryFn"),enabled:a.length>0&&i.length>0,retry:!1}),d=we({mutationFn:r(()=>or.approveCliAuthChallenge(a,i),"mutationFn"),onSuccess:r(async()=>{await e.invalidateQueries({queryKey:D.auth.session}),await c.refetch()},"onSuccess")}),u=we({mutationFn:r(()=>or.cancelCliAuthChallenge(a,i),"mutationFn"),onSuccess:r(async()=>{await c.refetch()},"onSuccess")});if(!a||!i)return(0,t.jsx)("div",{className:"mx-auto max-w-xl py-10 text-sm text-destructive",children:"Invalid CLI auth URL."});if(l.isLoading||c.isLoading)return(0,t.jsx)("div",{className:"mx-auto max-w-xl py-10 text-sm text-muted-foreground",children:"Loading CLI auth challenge..."});if(c.error)return(0,t.jsx)("div",{className:"mx-auto max-w-xl py-10",children:(0,t.jsxs)(sn,{className:"block p-6",children:[(0,t.jsx)("h1",{className:"text-lg font-semibold",children:"CLI auth challenge unavailable"}),(0,t.jsx)("p",{className:"mt-2 text-sm text-muted-foreground",children:c.error instanceof Error?c.error.message:"Challenge is invalid or expired."})]})});const h=c.data;return h?h.status==="approved"?(0,t.jsx)("div",{className:"mx-auto max-w-xl py-10",children:(0,t.jsxs)(sn,{className:"block p-6",children:[(0,t.jsx)("h1",{className:"text-xl font-semibold",children:"CLI access approved"}),(0,t.jsx)("p",{className:"mt-2 text-sm text-muted-foreground",children:"The Paperclip CLI can now finish authentication on the requesting machine."}),(0,t.jsxs)("p",{className:"mt-4 text-sm text-muted-foreground",children:["Command: ",(0,t.jsx)("span",{className:"font-mono text-foreground",children:h.command})]})]})}):h.status==="cancelled"||h.status==="expired"?(0,t.jsx)("div",{className:"mx-auto max-w-xl py-10",children:(0,t.jsxs)(sn,{className:"block p-6",children:[(0,t.jsx)("h1",{className:"text-xl font-semibold",children:h.status==="expired"?"CLI auth challenge expired":"CLI auth challenge cancelled"}),(0,t.jsx)("p",{className:"mt-2 text-sm text-muted-foreground",children:"Start the CLI auth flow again from your terminal to generate a new approval request."})]})}):h.requiresSignIn||!l.data?(0,t.jsx)("div",{className:"mx-auto max-w-xl py-10",children:(0,t.jsxs)(sn,{className:"block p-6",children:[(0,t.jsx)("h1",{className:"text-xl font-semibold",children:"Sign in required"}),(0,t.jsx)("p",{className:"mt-2 text-sm text-muted-foreground",children:"Sign in or create an account, then return to this page to approve the CLI access request."}),(0,t.jsx)($,{asChild:!0,className:"mt-4",children:(0,t.jsx)(We,{to:`/auth?next=${encodeURIComponent(o)}`,children:"Sign in / Create account"})})]})}):(0,t.jsx)("div",{className:"mx-auto max-w-xl py-10",children:(0,t.jsxs)(sn,{className:"block p-6",children:[(0,t.jsx)("h1",{className:"text-xl font-semibold",children:"Approve Paperclip CLI access"}),(0,t.jsx)("p",{className:"mt-2 text-sm text-muted-foreground",children:"A local Paperclip CLI process is requesting board access to this instance."}),(0,t.jsxs)("div",{className:"mt-5 space-y-3 text-sm",children:[(0,t.jsxs)("div",{children:[(0,t.jsx)("div",{className:"text-muted-foreground",children:"Command"}),(0,t.jsx)("div",{className:"font-mono text-foreground",children:h.command})]}),(0,t.jsxs)("div",{children:[(0,t.jsx)("div",{className:"text-muted-foreground",children:"Client"}),(0,t.jsx)("div",{className:"text-foreground",children:h.clientName??"paperclip-pro cli"})]}),(0,t.jsxs)("div",{children:[(0,t.jsx)("div",{className:"text-muted-foreground",children:"Requested access"}),(0,t.jsx)("div",{className:"text-foreground",children:h.requestedAccess==="instance_admin_required"?"Instance admin":"Board"})]}),h.requestedCompanyName&&(0,t.jsxs)("div",{children:[(0,t.jsx)("div",{className:"text-muted-foreground",children:"Requested organization"}),(0,t.jsx)("div",{className:"text-foreground",children:h.requestedCompanyName})]})]}),(d.error||u.error)&&(0,t.jsx)("p",{className:"mt-4 text-sm text-destructive",children:(d.error??u.error)instanceof Error?(d.error??u.error).message:"Failed to update CLI auth challenge"}),!h.canApprove&&(0,t.jsx)("p",{className:"mt-4 text-sm text-destructive",children:"This challenge requires instance-admin access. Sign in with an instance admin account to approve it."}),(0,t.jsxs)("div",{className:"mt-5 flex gap-3",children:[(0,t.jsx)($,{onClick:r(()=>d.mutate(),"onClick"),disabled:!h.canApprove||d.isPending||u.isPending,children:d.isPending?"Approving...":"Approve CLI access"}),(0,t.jsx)($,{type:"button",variant:"outline",onClick:r(()=>u.mutate(),"onClick"),disabled:d.isPending||u.isPending,children:u.isPending?"Cancelling...":"Cancel"})]})]})}):(0,t.jsx)("div",{className:"mx-auto max-w-xl py-10 text-sm text-destructive",children:"CLI auth challenge unavailable."})}r(Ifs,"CliAuthPage");var Tfs=pOe.filter(e=>e!=="paperclip_runner"),yge=new Set(["claude_local","codex_local","gemini_local","kimi_local","opencode_local","pi_local","cursor"]);function Rfs(e,s){let n=e;for(const a of s){if(!n||typeof n!="object")return null;n=n[a]}return typeof n=="string"&&n.trim().length>0?n:null}r(Rfs,"readNestedString");var E1="w-full border border-zinc-800 bg-zinc-950 px-3 py-2 text-sm text-zinc-100 outline-none focus:border-zinc-500",jge="border border-zinc-800 bg-zinc-950/95 p-6",wge="flex-1 border px-3 py-2 text-sm transition-colors";function Efs(e){return e?e.charAt(0).toUpperCase()+e.slice(1):null}r(Efs,"formatHumanRole");function E9e(e){if(!e||typeof e!="object")return null;const s=e.code;return typeof s=="string"&&s.trim().length>0?s:null}r(E9e,"getAuthErrorCode");function Lfs(e){if(!(e instanceof Error))return null;const s=e.message.trim();return s.length>0?s:null}r(Lfs,"getAuthErrorMessage");function Mfs(e,s,n){const a=E9e(e),i=Lfs(e),o=n.trim().length>0?n.trim():"that email";return a==="USER_ALREADY_EXISTS_USE_ANOTHER_EMAIL"?{tone:"info",message:`An account already exists for ${o}. Sign in below to continue with this invite.`}:a==="INVALID_EMAIL_OR_PASSWORD"?{tone:"error",message:"That email and password did not match an existing Paperclip account. Check both fields, or create an account first if you are new here."}:s==="sign_in"&&i==="Request failed: 401"?{tone:"error",message:"That email and password did not match an existing Paperclip account. Check both fields, or create an account first if you are new here."}:s==="sign_up"&&i==="Request failed: 422"?{tone:"info",message:`An account may already exist for ${o}. Try signing in instead.`}:{tone:"error",message:i??"Authentication failed"}}r(Mfs,"mapInviteAuthFeedback");function kge(e){return!!(e&&typeof e=="object"&&"bootstrapAccepted"in e)}r(kge,"isBootstrapAcceptancePayload");function Pfs(e,s){return!e||typeof e!="object"||s?!1:e.status==="approved"}r(Pfs,"isApprovedHumanJoinPayload");function yQ({companyDisplayName:e,companyLogoUrl:s,className:n}){return(0,t.jsx)(Zx,{companyName:e,logoUrl:s,logoFit:"contain",className:n})}r(yQ,"InviteCompanyLogo");function Nge({companyDisplayName:e,companyLogoUrl:s,invitedByUserName:n,claimSecret:a=null,claimApiKeyPath:i=null,onboardingTextUrl:o=null}){return(0,t.jsx)("div",{className:"min-h-screen bg-zinc-950 px-6 py-12 text-zinc-100",children:(0,t.jsxs)("div",{className:"mx-auto max-w-md border border-zinc-800 bg-zinc-950 p-6","data-testid":"invite-pending-approval",children:[(0,t.jsxs)("div",{className:"flex items-center gap-3",children:[(0,t.jsx)(yQ,{companyDisplayName:e,companyLogoUrl:s,className:"h-12 w-12 border border-zinc-800 rounded-none"}),(0,t.jsxs)("h1",{className:"text-lg font-semibold",children:["Request to join ",e]})]}),(0,t.jsxs)("div",{className:"mt-4 space-y-3",children:[(0,t.jsxs)("p",{className:"text-sm text-zinc-400",children:["Your request is still awaiting approval. ",n??"An organization admin"," must approve your request to join."]}),(0,t.jsxs)("div",{className:"border border-zinc-800 p-3",children:[(0,t.jsx)("p",{className:"text-xs text-zinc-500 mb-1",children:"Approval page"}),(0,t.jsx)("p",{className:"text-sm text-zinc-200",children:"Settings → Members"})]}),(0,t.jsxs)("p",{className:"text-sm text-zinc-400",children:["Ask them to visit ",(0,t.jsx)("span",{className:"text-zinc-200",children:"Settings → Members"})," to approve your request."]}),(0,t.jsx)("p",{className:"text-xs text-zinc-500",children:"Refresh this page after you've been approved — you'll be redirected automatically."})]}),a&&i?(0,t.jsxs)("div",{className:"mt-4 space-y-1 border border-zinc-800 p-3 text-xs text-zinc-400",children:[(0,t.jsx)("div",{className:"text-zinc-200",children:"Claim secret"}),(0,t.jsx)("div",{className:"font-mono break-all",children:a}),(0,t.jsxs)("div",{className:"font-mono break-all",children:["POST ",i]})]}):null,o?(0,t.jsxs)("div",{className:"mt-4 text-xs text-zinc-400",children:["Onboarding: ",(0,t.jsx)("span",{className:"font-mono break-all",children:o})]}):null]})})}r(Nge,"AwaitingJoinApprovalPanel");function Dfs(){const e=wt(),s=Gn(),{setSelectedCompanyId:n}=fs(),a=(xa().token??"").trim(),[i,o]=(0,m.useState)("sign_up"),[l,c]=(0,m.useState)(""),[d,u]=(0,m.useState)(""),[h,p]=(0,m.useState)(""),[f,x]=(0,m.useState)(""),[g,v]=(0,m.useState)("claude_local"),[y,k]=(0,m.useState)(""),[w,N]=(0,m.useState)(null),[S,C]=(0,m.useState)(null),[_,R]=(0,m.useState)(null),[I,T]=(0,m.useState)(!1),E="invite-auth-error",P=te({queryKey:D.health,queryFn:r(()=>Lu.get(),"queryFn"),retry:!1}),O=te({queryKey:D.auth.session,queryFn:r(()=>Pa.getSession(),"queryFn"),retry:!1}),M=te({queryKey:D.access.invite(a),queryFn:r(()=>or.getInvite(a),"queryFn"),enabled:a.length>0,retry:!1}),Q=LQ({enabled:!!O.data&&!!M.data?.companyId,staleTime:0}),L=P.data?.deploymentMode!=="local_trusted"?Q.isFetchedAfterMount:!0,F=L?Q.data?.companies??[]:[];(0,m.useEffect)(()=>{a&&fge(a)},[a]),(0,m.useEffect)(()=>{T(!1)},[a]),(0,m.useEffect)(()=>{if(!L)return;const ve=Q.data?.companies;!ve||!M.data?.companyId||ve.some(Ie=>Ie.id===M.data.companyId)&&OT(a)},[Q.data,M.data,L,a]);const q=M.data,z=!!O.data&&!!q?.companyId&&!L,K=!!q?.companyId&&F.some(ve=>ve.id===q?.companyId),U=q?.companyName?.trim()||"this Paperclip company",V=q?.companyLogoUrl?.trim()||null,ne=q?.invitedByUserName?.trim()||null,Z=q?.inviteMessage?.trim()||null,ie=Efs(q?.humanRole),J=q?.joinRequestStatus??null,ae=q?.joinRequestType??null,oe=ae==="human"&&(J==="pending_approval"||J==="approved"),G=P.data?.deploymentMode==="authenticated"&&!O.data&&q?.allowedJoinTypes!=="agent",X=q?.inviteType!=="bootstrap_ceo"&&q?.allowedJoinTypes==="agent",Y=!!O.data&&!X&&q?.inviteType!=="bootstrap_ceo"&&(!J||oe)&&!z&&!K&&!w&&S===null,re=O.data?.user.name?.trim()||O.data?.user.email?.trim()||"this account",se=d.trim().length>0&&h.trim().length>0&&(i==="sign_in"||l.trim().length>0&&h.trim().length>=8),ce=we({mutationFn:r(async()=>{if(!q)throw new Error("Invite not found");if(z)throw new Error("Checking your organization access. Try again in a moment.");if(K)throw new Error("This account already belongs to the organization.");return q.inviteType==="bootstrap_ceo"||q.allowedJoinTypes!=="agent"?or.acceptInvite(a,{requestType:"human"}):or.acceptInvite(a,{requestType:"agent",agentName:f.trim(),adapterType:g,capabilities:y.trim()||null})},"mutationFn"),onSuccess:r(async ve=>{C(null),OT(a);const Ie=kge(ve);N({kind:Ie?"bootstrap":"join",payload:ve}),await e.invalidateQueries({queryKey:D.auth.session}),await e.invalidateQueries({queryKey:D.access.currentBoardAccess}),await e.invalidateQueries({queryKey:D.companies.all}),q?.companyId&&Pfs(ve,X)&&(n(q.companyId,{source:"manual"}),s("/",{replace:!0}))},"onSuccess"),onError:r(ve=>{C(ve instanceof Error?ve.message:"Failed to accept invite")},"onError")});(0,m.useEffect)(()=>{!Y||I||ce.isPending||(T(!0),C(null),ce.mutate())},[ce,I,Y]);const pe=we({mutationFn:r(async()=>{if(i==="sign_in"){await Pa.signInEmail({email:d.trim(),password:h});return}await Pa.signUpEmail({name:l.trim(),email:d.trim(),password:h})},"mutationFn"),onSuccess:r(async()=>{R(null),fge(a),await e.invalidateQueries({queryKey:D.auth.session}),await e.invalidateQueries({queryKey:D.health}),await e.invalidateQueries({queryKey:D.access.currentBoardAccess});const{companies:ve}=await HOe(e);if(q?.companyId&&ve.some(Ie=>Ie.id===q.companyId)){OT(a),n(q.companyId,{source:"manual"}),s("/",{replace:!0});return}if(!(!q||q.inviteType!=="bootstrap_ceo"))try{kge(await ce.mutateAsync())&&s("/",{replace:!0})}catch{return}},"onSuccess"),onError:r(ve=>{const Ie=Mfs(ve,i,d);E9e(ve)==="USER_ALREADY_EXISTS_USE_ANOTHER_EMAIL"&&(o("sign_in"),p("")),R(Ie)},"onError")}),fe=(0,m.useMemo)(()=>q?K?"Open organization":q.inviteType==="bootstrap_ceo"?"Accept invite":X?"Submit request":O.data?"Accept invite":"Continue":"Continue",[q,K,O.data,X]);if(!a)return(0,t.jsx)("div",{className:"mx-auto max-w-xl py-10 text-sm text-destructive",children:"Invalid invite token."});if(M.isLoading||P.isLoading||O.isLoading)return(0,t.jsx)("div",{className:"mx-auto max-w-xl py-10 text-sm text-muted-foreground",children:"Loading invite..."});if(z)return(0,t.jsx)("div",{className:"mx-auto max-w-xl py-10 text-sm text-muted-foreground",children:"Checking your access..."});if(M.error||!q)return(0,t.jsx)("div",{className:"mx-auto max-w-xl py-10",children:(0,t.jsxs)("div",{className:"border border-border bg-card p-6","data-testid":"invite-error",children:[(0,t.jsx)("h1",{className:"text-lg font-semibold",children:"Invite not available"}),(0,t.jsx)("p",{className:"mt-2 text-sm text-muted-foreground",children:"This invite may be expired, revoked, or already used."})]})});if(J==="approved"&&ae==="human"&&K)return(0,t.jsx)("div",{className:"mx-auto max-w-xl py-10 text-sm text-muted-foreground",children:"Opening organization..."});if(J==="pending_approval"&&!oe)return(0,t.jsx)(Nge,{companyDisplayName:U,companyLogoUrl:V,invitedByUserName:ne});if(J&&!oe)return(0,t.jsx)("div",{className:"mx-auto max-w-xl py-10",children:(0,t.jsxs)("div",{className:"border border-border bg-card p-6","data-testid":"invite-error",children:[(0,t.jsx)("h1",{className:"text-lg font-semibold",children:"Invite not available"}),(0,t.jsx)("p",{className:"mt-2 text-sm text-muted-foreground",children:J==="rejected"?"This join request was not approved.":"This invite has already been used."})]})});if(w?.kind==="bootstrap")return(0,t.jsx)("div",{className:"min-h-screen bg-zinc-950 px-6 py-12 text-zinc-100",children:(0,t.jsxs)("div",{className:"mx-auto max-w-md border border-zinc-800 bg-zinc-950 p-6",children:[(0,t.jsx)("h1",{className:"text-lg font-semibold",children:"Bootstrap complete"}),(0,t.jsx)("div",{className:"mt-4",children:(0,t.jsx)($,{asChild:!0,className:"rounded-none",children:(0,t.jsx)(We,{to:"/",children:"Open board"})})})]})});if(w?.kind==="join"){const ve=w.payload,Ie=typeof ve.claimSecret=="string"?ve.claimSecret:null,de=typeof ve.claimApiKeyPath=="string"?ve.claimApiKeyPath:null,xe=Rfs(ve.onboarding,["textInstructions","url"]);return!X&&ve.status==="approved"?(0,t.jsx)("div",{className:"min-h-screen bg-zinc-950 px-6 py-12 text-zinc-100",children:(0,t.jsxs)("div",{className:"mx-auto max-w-md border border-zinc-800 bg-zinc-950 p-6",children:[(0,t.jsxs)("div",{className:"flex items-center gap-3",children:[(0,t.jsx)(yQ,{companyDisplayName:U,companyLogoUrl:V,className:"h-12 w-12 border border-zinc-800 rounded-none"}),(0,t.jsx)("h1",{className:"text-lg font-semibold",children:"You joined the organization"})]}),(0,t.jsx)("div",{className:"mt-4",children:(0,t.jsx)($,{asChild:!0,className:"w-full rounded-none",children:(0,t.jsx)(We,{to:"/",children:"Open board"})})})]})}):(0,t.jsx)(Nge,{companyDisplayName:U,companyLogoUrl:V,invitedByUserName:ne,claimSecret:Ie,claimApiKeyPath:de,onboardingTextUrl:xe})}return(0,t.jsx)("div",{className:"min-h-screen bg-zinc-950 px-6 py-12 text-zinc-100",children:(0,t.jsx)("div",{className:"mx-auto max-w-5xl",children:(0,t.jsxs)("div",{className:"grid gap-6 lg:grid-cols-(--gtc-36)",children:[(0,t.jsxs)("section",{className:`${jge} space-y-6`,children:[(0,t.jsxs)("div",{className:"flex items-start gap-4",children:[(0,t.jsx)(yQ,{companyDisplayName:U,companyLogoUrl:V,className:"h-16 w-16 rounded-none border border-zinc-800"}),(0,t.jsxs)("div",{className:"min-w-0",children:[(0,t.jsx)("p",{className:"text-xs uppercase tracking-(--tracking-caps) text-zinc-500",children:"You've been invited to join Paperclip"}),(0,t.jsx)("h1",{className:"mt-2 text-2xl font-semibold",children:q.inviteType==="bootstrap_ceo"?"Set up Paperclip":`Join ${U}`}),(0,t.jsx)("p",{className:"mt-2 max-w-2xl text-sm leading-6 text-zinc-300",children:X?"Review the invite details, then submit the agent information below to start the join request.":G?"Create your Paperclip account first. If you already have one, switch to sign in and continue the invite with the same email.":"Your account is ready. Review the invite details, then accept it to continue."})]})]}),(0,t.jsxs)("div",{className:"grid gap-3 sm:grid-cols-2",children:[(0,t.jsxs)("div",{className:"border border-zinc-800 p-3",children:[(0,t.jsx)("div",{className:"text-xs uppercase tracking-(--tracking-caps) text-zinc-500",children:"Organization"}),(0,t.jsx)("div",{className:"mt-1 text-sm text-zinc-100",children:U})]}),(0,t.jsxs)("div",{className:"border border-zinc-800 p-3",children:[(0,t.jsx)("div",{className:"text-xs uppercase tracking-(--tracking-caps) text-zinc-500",children:"Invited by"}),(0,t.jsx)("div",{className:"mt-1 text-sm text-zinc-100",children:ne??"Paperclip board"})]}),(0,t.jsxs)("div",{className:"border border-zinc-800 p-3",children:[(0,t.jsx)("div",{className:"text-xs uppercase tracking-(--tracking-caps) text-zinc-500",children:"Requested access"}),(0,t.jsx)("div",{className:"mt-1 text-sm text-zinc-100",children:X?"Agent join request":ie??"Organization access"})]}),(0,t.jsxs)("div",{className:"border border-zinc-800 p-3",children:[(0,t.jsx)("div",{className:"text-xs uppercase tracking-(--tracking-caps) text-zinc-500",children:"Invite expires"}),(0,t.jsx)("div",{className:"mt-1 text-sm text-zinc-100",children:Zd(q.expiresAt)})]})]}),Z?(0,t.jsxs)("div",{className:"border border-amber-500/40 bg-amber-500/10 p-4",children:[(0,t.jsx)("div",{className:"text-xs uppercase tracking-(--tracking-caps) text-amber-200/80",children:"Message from inviter"}),(0,t.jsx)("p",{className:"mt-2 text-sm leading-6 text-amber-50",children:Z})]}):null,O.data?(0,t.jsxs)("div",{className:"border border-emerald-500/40 bg-emerald-500/10 p-4 text-sm text-emerald-50",children:["Signed in as ",(0,t.jsx)("span",{className:"font-medium",children:re}),"."]}):null]}),(0,t.jsx)("section",{className:`${jge} h-fit`,children:X?(0,t.jsxs)("div",{className:"space-y-4",children:[(0,t.jsxs)("div",{children:[(0,t.jsx)("h2",{className:"text-lg font-semibold",children:"Submit agent details"}),(0,t.jsxs)("p",{className:"mt-1 text-sm text-zinc-400",children:["This invite will create an approval request for a new agent in ",U,"."]})]}),(0,t.jsxs)("label",{className:"block text-sm",children:[(0,t.jsx)("span",{className:"mb-1 block text-zinc-400",children:"Agent name"}),(0,t.jsx)("input",{className:E1,value:f,onChange:r(ve=>x(ve.target.value),"onChange")})]}),(0,t.jsxs)("label",{className:"block text-sm",children:[(0,t.jsx)("span",{className:"mb-1 block text-zinc-400",children:"Adapter type"}),(0,t.jsx)("select",{className:E1,value:g,onChange:r(ve=>v(ve.target.value),"onChange"),children:Tfs.map(ve=>(0,t.jsxs)("option",{value:ve,disabled:!yge.has(ve),children:[kf(ve),yge.has(ve)?"":" (Coming soon)"]},ve))})]}),(0,t.jsxs)("label",{className:"block text-sm",children:[(0,t.jsx)("span",{className:"mb-1 block text-zinc-400",children:"Capabilities"}),(0,t.jsx)("textarea",{className:E1,rows:4,value:y,onChange:r(ve=>k(ve.target.value),"onChange")})]}),S?(0,t.jsx)("p",{className:"text-xs text-red-400",children:S}):null,(0,t.jsx)($,{className:"w-full rounded-none",disabled:ce.isPending||f.trim().length===0,onClick:r(()=>ce.mutate(),"onClick"),children:ce.isPending?"Working...":fe})]}):G?(0,t.jsxs)("div",{className:"space-y-5",children:[(0,t.jsxs)("div",{children:[(0,t.jsx)("h2",{className:"text-lg font-semibold",children:i==="sign_up"?"Create your account":"Sign in to continue"}),(0,t.jsx)("p",{className:"mt-1 text-sm text-zinc-400",children:i==="sign_up"?`Start with a Paperclip account. After that, you'll come right back here to accept the invite for ${U}.`:"Use the Paperclip account that already matches this invite. If you do not have one yet, switch back to create account."})]}),(0,t.jsxs)("div",{className:"flex gap-2",children:[(0,t.jsx)("button",{type:"button",className:`${wge} ${i==="sign_up"?"border-zinc-100 bg-zinc-100 text-zinc-950":"border-zinc-800 text-zinc-300 hover:border-zinc-600"}`,onClick:r(()=>{R(null),o("sign_up")},"onClick"),children:"Create account"}),(0,t.jsx)("button",{type:"button",className:`${wge} ${i==="sign_in"?"border-zinc-100 bg-zinc-100 text-zinc-950":"border-zinc-800 text-zinc-300 hover:border-zinc-600"}`,onClick:r(()=>{R(null),o("sign_in")},"onClick"),children:"I already have an account"})]}),(0,t.jsxs)("form",{className:"space-y-4",method:"post",action:i==="sign_up"?"/api/auth/sign-up/email":"/api/auth/sign-in/email",onSubmit:r(ve=>{if(ve.preventDefault(),!pe.isPending){if(!se){R({tone:"error",message:"Please fill in all required fields."});return}pe.mutate()}},"onSubmit"),"data-testid":"invite-inline-auth",children:[i==="sign_up"?(0,t.jsxs)("label",{className:"block text-sm",htmlFor:"invite-name",children:[(0,t.jsx)("span",{className:"mb-1 block text-zinc-400",children:"Name"}),(0,t.jsx)("input",{id:"invite-name",name:"name",className:E1,value:l,onChange:r(ve=>{c(ve.target.value),R(null)},"onChange"),autoComplete:"name",required:!0,"aria-required":"true","aria-invalid":_?.tone==="error"?!0:void 0,"aria-describedby":_?E:void 0,autoFocus:!0})]}):null,(0,t.jsxs)("label",{className:"block text-sm",htmlFor:"invite-email",children:[(0,t.jsx)("span",{className:"mb-1 block text-zinc-400",children:"Email"}),(0,t.jsx)("input",{id:"invite-email",name:"email",type:"email",className:E1,value:d,onChange:r(ve=>{u(ve.target.value),R(null)},"onChange"),autoComplete:"username",required:!0,"aria-required":"true","aria-invalid":_?.tone==="error"?!0:void 0,"aria-describedby":_?E:void 0,autoFocus:i==="sign_in"})]}),(0,t.jsxs)("label",{className:"block text-sm",htmlFor:"invite-password",children:[(0,t.jsx)("span",{className:"mb-1 block text-zinc-400",children:"Password"}),(0,t.jsx)("input",{id:"invite-password",name:"password",type:"password",className:E1,value:h,onChange:r(ve=>{p(ve.target.value),R(null)},"onChange"),autoComplete:i==="sign_in"?"current-password":"new-password",required:!0,"aria-required":"true","aria-invalid":_?.tone==="error"?!0:void 0,"aria-describedby":_?E:void 0})]}),_?(0,t.jsx)("p",{id:E,role:"alert",className:`text-xs ${_.tone==="info"?"text-amber-300":"text-red-400"}`,children:_.message}):null,(0,t.jsx)($,{type:"submit",className:"w-full rounded-none",disabled:pe.isPending,"aria-disabled":!se||pe.isPending,children:pe.isPending?"Working...":i==="sign_in"?"Sign in and continue":"Create account and continue"})]}),(0,t.jsx)("p",{className:"text-xs leading-5 text-zinc-500",children:i==="sign_up"?"Already signed up before? Use the existing-account option instead so the invite lands on the right Paperclip user.":"No account yet? Switch back to create account so you can accept the invite with a new login."})]}):(0,t.jsxs)("div",{className:"space-y-4",children:[(0,t.jsxs)("div",{children:[(0,t.jsx)("h2",{className:"text-lg font-semibold",children:K?"Already in this organization":Y?"Completing organization access":q.inviteType==="bootstrap_ceo"?"Accept bootstrap invite":"Accept organization invite"}),(0,t.jsx)("p",{className:"mt-1 text-sm text-zinc-400",children:Y?`Granting your access to ${U}.`:K?`This account already belongs to ${U}.`:`This will ${q.inviteType==="bootstrap_ceo"?"finish setting up Paperclip":`grant or complete your access to ${U}`}.`})]}),S?(0,t.jsx)("p",{className:"text-xs text-red-400",children:S}):null,Y?(0,t.jsx)("div",{className:"text-sm text-zinc-400",children:ce.isPending?"Submitting request...":"Finishing sign-in..."}):(0,t.jsx)($,{className:"w-full rounded-none",disabled:ce.isPending,onClick:r(()=>{if(K&&q.companyId){OT(a),n(q.companyId,{source:"manual"}),s("/",{replace:!0});return}ce.mutate()},"onClick"),children:ce.isPending?"Working...":fe})]})})]})})})}r(Dfs,"InviteLandingPage");var $fs=15e3,Ofs={parent:"Parent task",child:"Sub-task",blocked_by:"Blocked by",blocks:"Blocks"};function Bfs(){(0,m.useEffect)(()=>{const e=document.createElement("meta");return e.name="robots",e.content="noindex",document.head.appendChild(e),()=>e.remove()},[])}r(Bfs,"useNoIndexMeta");function jQ(e,s){const n=`/s/${encodeURIComponent(e)}`;return s?`${n}/issues/${encodeURIComponent(s)}`:n}r(jQ,"sharePath");var Ffs=/^(?:https?:\/\/[^/]+)?\/api\/attachments\/([^/?#]+)\/content(?:[?#].*)?$/i;function zfs(e,s){const n=Ffs.exec(s.trim());return n?`/api/public/share/${encodeURIComponent(e)}/attachments/${n[1]}/content`:null}r(zfs,"publicShareImageSrc");function pC({title:e,children:s}){return(0,t.jsxs)("section",{className:"space-y-3",children:[(0,t.jsx)("h2",{className:"text-sm font-semibold text-muted-foreground",children:e}),s]})}r(pC,"Section");function wQ({actor:e}){return(0,t.jsx)(yo,{name:e.name,avatarUrl:e.iconUrl,size:"sm"})}r(wQ,"ActorIdentity");function kQ({value:e}){return(0,t.jsx)("time",{dateTime:e,title:yr(e),className:"text-xs text-muted-foreground",children:gr(e)})}r(kQ,"Timestamp");function qfs({agentName:e}){return(0,t.jsxs)("span",{"data-testid":"public-share-run-pill",className:"inline-flex items-center gap-1.5 rounded-full border border-border px-3 py-1 text-xs text-foreground",children:[(0,t.jsx)("span",{className:"h-2 w-2 animate-pulse rounded-full bg-(--status-agent-running)","aria-hidden":!0}),e," is working…"]})}r(qfs,"ActiveRunPill");function L9e({attachments:e}){return(0,t.jsx)(mH,{children:e.map(s=>{const n=l2e({name:s.filename,url:s.url,contentType:s.contentType,byteSize:s.byteSize}),a=n.icon,i=hH(s.byteSize);return(0,t.jsxs)(oH,{size:"sm",children:[(0,t.jsx)(lH,{children:(0,t.jsx)(a,{"aria-hidden":!0})}),(0,t.jsxs)(cH,{children:[(0,t.jsx)(dH,{className:"max-w-48",children:s.filename}),(0,t.jsx)(uH,{className:"max-w-48",children:i?`${n.label} · ${i}`:n.label})]}),(0,t.jsx)(r2e,{"aria-label":`Download ${s.filename}`,render:(0,t.jsx)("a",{href:s.url,download:s.filename,rel:"noreferrer"})})]},s.id)})})}r(L9e,"AttachmentList");function Ufs({related:e,token:s,isSharedRoot:n}){const a=e.identifier?`${e.identifier} · ${e.title}`:e.title,i=(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)(ro,{status:e.status,size:"sm"}),(0,t.jsx)("span",{className:"min-w-0 truncate",children:a})]});return(0,t.jsxs)("li",{className:"flex items-center gap-2 text-sm",children:[(0,t.jsx)("span",{className:"w-20 shrink-0 text-xs text-muted-foreground",children:Ofs[e.relation]}),e.navigable?(0,t.jsx)(Md,{to:n?jQ(s,e.id):jQ(s),className:"flex min-w-0 items-center gap-2 text-foreground underline-offset-2 hover:underline",children:i}):(0,t.jsx)("span",{className:"flex min-w-0 items-center gap-2 text-muted-foreground",children:i})]})}r(Ufs,"RelatedIssueRow");function Kfs({comment:e,resolveImageSrc:s}){return e.kind==="redacted"?(0,t.jsxs)("li",{"data-testid":"public-share-redacted-comment",className:"flex flex-wrap items-center gap-2 rounded-lg border border-dashed border-border px-3 py-2",children:[(0,t.jsx)(wQ,{actor:e.author}),(0,t.jsx)(kQ,{value:e.createdAt}),(0,t.jsx)("span",{className:"text-xs italic text-muted-foreground",children:"Internal update"})]}):(0,t.jsxs)("li",{className:"space-y-2 rounded-lg border border-border bg-card px-3 py-3",children:[(0,t.jsxs)("div",{className:"flex flex-wrap items-center gap-2",children:[(0,t.jsx)(wQ,{actor:e.author}),(0,t.jsx)(kQ,{value:e.createdAt})]}),(0,t.jsx)(An,{className:"text-sm",softBreaks:!0,linkIssueReferences:!1,resolveImageSrc:s,children:e.body}),e.attachments.length>0?(0,t.jsx)(L9e,{attachments:e.attachments}):null]})}r(Kfs,"TimelineEntry");function Qfs({document:e,resolveImageSrc:s}){return(0,t.jsxs)("details",{className:"group rounded-lg border border-border bg-card",children:[(0,t.jsxs)("summary",{className:"flex cursor-pointer items-center gap-2 px-3 py-2 text-sm",children:[(0,t.jsx)(Za,{className:"h-4 w-4 shrink-0 text-muted-foreground","aria-hidden":!0}),(0,t.jsx)("span",{className:"min-w-0 flex-1 truncate font-medium",children:e.title??e.key}),(0,t.jsx)(kQ,{value:e.updatedAt})]}),(0,t.jsxs)("div",{className:"space-y-3 border-t border-border px-3 py-3",children:[(0,t.jsxs)("a",{href:e.pdfUrl,download:!0,rel:"noreferrer",className:"inline-flex items-center gap-1.5 text-xs text-muted-foreground hover:text-foreground",children:[(0,t.jsx)(Fi,{className:"h-3.5 w-3.5","aria-hidden":!0}),"Download PDF"]}),(0,t.jsx)(An,{className:"text-sm",linkIssueReferences:!1,resolveImageSrc:s,children:e.body})]})]})}r(Qfs,"DocumentCard");function Wfs({product:e}){return(0,t.jsxs)("li",{className:"flex flex-wrap items-center gap-x-3 gap-y-1 rounded-lg border border-border bg-card px-3 py-2 text-sm",children:[(0,t.jsx)("span",{className:"min-w-0 flex-1 truncate font-medium",children:e.title}),(0,t.jsxs)("span",{className:"text-xs text-muted-foreground",children:[e.type.replace(/_/g," ")," · ",e.status.replace(/_/g," ")]}),e.url?(0,t.jsxs)("a",{href:e.url,target:"_blank",rel:"noopener noreferrer",className:"inline-flex items-center gap-1 text-xs text-muted-foreground hover:text-foreground",children:[(0,t.jsx)($n,{className:"h-3.5 w-3.5","aria-hidden":!0}),"Open"]}):null,e.downloadUrl?(0,t.jsxs)("a",{href:e.downloadUrl,download:!0,rel:"noreferrer",className:"inline-flex items-center gap-1 text-xs text-muted-foreground hover:text-foreground",children:[(0,t.jsx)(Fi,{className:"h-3.5 w-3.5","aria-hidden":!0}),"Download"]}):null]})}r(Wfs,"WorkProductRow");function Sge({title:e,body:s,action:n}){return(0,t.jsx)("div",{className:"flex h-dvh overflow-y-auto bg-background px-4 text-foreground",children:(0,t.jsxs)("div",{className:"m-auto w-full max-w-sm space-y-2 rounded-lg border border-border bg-card p-6 text-center",children:[(0,t.jsx)("h1",{className:"text-lg font-semibold",children:e}),(0,t.jsx)("p",{className:"text-sm text-muted-foreground",children:s}),n]})})}r(Sge,"CenteredNotice");function Hfs({view:e,token:s}){const{company:n,issue:a}=e,i=(0,m.useCallback)(o=>zfs(s,o),[s]);return(0,t.jsxs)("div",{className:"h-dvh overflow-y-auto bg-background text-foreground",children:[(0,t.jsx)("header",{className:"border-b border-border",children:(0,t.jsxs)("div",{className:"mx-auto flex max-w-3xl items-center gap-3 px-4 py-3",children:[(0,t.jsx)(Zx,{companyName:n.name,logoUrl:n.logoUrl,logoFit:"contain",className:"h-8 w-8 shrink-0 rounded-md"}),(0,t.jsx)("span",{className:"min-w-0 truncate text-sm font-medium",children:n.name}),(0,t.jsx)("span",{className:"ml-auto shrink-0 text-xs text-muted-foreground",children:"Read-only view"})]})}),(0,t.jsxs)("main",{className:"mx-auto max-w-3xl space-y-8 px-4 py-5",children:[e.isSharedRoot?null:(0,t.jsxs)(Md,{to:jQ(s),className:"inline-flex items-center gap-1.5 text-sm text-muted-foreground hover:text-foreground",children:[(0,t.jsx)(wl,{className:"h-4 w-4","aria-hidden":!0}),"Back to main task"]}),(0,t.jsxs)("section",{className:"space-y-3",children:[(0,t.jsxs)("div",{className:"flex flex-wrap items-center gap-x-2 text-xs text-muted-foreground",children:[a.identifier?(0,t.jsx)("span",{children:a.identifier}):null,a.projectName?(0,t.jsx)("span",{children:a.projectName}):null]}),(0,t.jsx)("h1",{className:"break-words text-xl font-semibold",children:a.title}),(0,t.jsxs)("div",{className:"flex flex-wrap items-center gap-3",children:[(0,t.jsx)(A0,{status:a.status}),(0,t.jsx)(ive,{priority:a.priority,showLabel:!0}),a.assignee?(0,t.jsx)(wQ,{actor:a.assignee}):null,e.activeRun?(0,t.jsx)(qfs,{agentName:e.activeRun.agentName}):null]}),(0,t.jsxs)("p",{className:"text-xs text-muted-foreground",children:["Created ",yr(a.createdAt)," · Updated ",gr(a.updatedAt),a.completedAt?` · Completed ${yr(a.completedAt)}`:""]})]}),a.description?(0,t.jsx)(An,{className:"text-sm",softBreaks:!0,linkIssueReferences:!1,resolveImageSrc:i,children:a.description}):null,e.related.length>0?(0,t.jsx)(pC,{title:"Related tasks",children:(0,t.jsx)("ul",{className:"space-y-2",children:e.related.map(o=>(0,t.jsx)(Ufs,{related:o,token:s,isSharedRoot:e.isSharedRoot},`${o.relation}:${o.id}`))})}):null,e.documents.length>0?(0,t.jsx)(pC,{title:"Documents",children:(0,t.jsx)("div",{className:"space-y-2",children:e.documents.map(o=>(0,t.jsx)(Qfs,{document:o,resolveImageSrc:i},o.key))})}):null,e.attachments.length>0?(0,t.jsx)(pC,{title:"Attachments",children:(0,t.jsx)(L9e,{attachments:e.attachments})}):null,e.workProducts.length>0?(0,t.jsx)(pC,{title:"Work products",children:(0,t.jsx)("ul",{className:"space-y-2",children:e.workProducts.map(o=>(0,t.jsx)(Wfs,{product:o},o.id))})}):null,(0,t.jsx)(pC,{title:"Activity",children:e.comments.length>0?(0,t.jsx)("ol",{className:"space-y-3",children:e.comments.map(o=>(0,t.jsx)(Kfs,{comment:o,resolveImageSrc:i},o.id))}):(0,t.jsx)("p",{className:"text-sm text-muted-foreground",children:"No updates yet."})})]})]})}r(Hfs,"PublicIssueShareContent");function Cge(){const{token:e="",issueId:s}=xa();Bfs();const n=tUe.test(e),a=te({queryKey:D.publicShare.view(e,s??null),queryFn:r(()=>s?Gk.getPublicShareIssue(e,s):Gk.getPublicShare(e),"queryFn"),enabled:n,retry:!1,refetchOnWindowFocus:!0,refetchInterval:r(i=>i.state.data?.activeRun?$fs:!1,"refetchInterval")});return!n||a.data===null?(0,t.jsx)(Sge,{title:"This link is not available",body:"It may have been revoked, or the address is incomplete."}):a.data?(0,t.jsx)(Hfs,{view:a.data,token:e}):a.isError?(0,t.jsx)(Sge,{title:"Couldn't load this page",body:"Check your connection and try again.",action:(0,t.jsx)($,{variant:"outline",size:"sm",className:"mt-2",onClick:r(()=>{a.refetch()},"onClick"),children:"Try again"})}):(0,t.jsx)("div",{className:"h-dvh overflow-y-auto px-4 py-6","aria-busy":"true",children:(0,t.jsxs)("div",{className:"mx-auto max-w-3xl space-y-4",children:[(0,t.jsx)(yn,{className:"h-6 w-1/2"}),(0,t.jsx)(yn,{className:"h-4 w-1/3"}),(0,t.jsx)(yn,{className:"h-24 w-full"})]})})}r(Cge,"PublicIssueSharePage");function Vfs(){const{selectedCompany:e,selectedCompanyId:s}=fs(),{setBreadcrumbs:n}=Vn(),{pushToast:a}=Ti(),i=wt(),[o,l]=(0,m.useState)("pending_approval"),[c,d]=(0,m.useState)("all");(0,m.useEffect)(()=>{n([{label:e?.name??"Organization",href:"/dashboard"},{label:"Inbox",href:"/inbox"},{label:"Join Requests"}])},[e?.name,n]);const u=te({queryKey:D.access.joinRequests(s??"",`${o}:${c}`),queryFn:r(()=>or.listJoinRequests(s,o,c==="all"?void 0:c),"queryFn"),enabled:!!s}),h=we({mutationFn:r(f=>or.approveJoinRequest(s,f),"mutationFn"),onSuccess:r(async()=>{await i.invalidateQueries({queryKey:D.access.joinRequests(s,`${o}:${c}`)}),await i.invalidateQueries({queryKey:D.access.companyMembers(s)}),await i.invalidateQueries({queryKey:D.access.companyUserDirectory(s)}),a({title:"Join request approved",tone:"success"})},"onSuccess")}),p=we({mutationFn:r(f=>or.rejectJoinRequest(s,f),"mutationFn"),onSuccess:r(async()=>{await i.invalidateQueries({queryKey:D.access.joinRequests(s,`${o}:${c}`)}),a({title:"Join request rejected",tone:"success"})},"onSuccess")});if(!s)return(0,t.jsx)("div",{className:"text-sm text-muted-foreground",children:"Select an organization to review join requests."});if(u.isLoading)return(0,t.jsx)("div",{className:"text-sm text-muted-foreground",children:"Loading join requests…"});if(u.error){const f=u.error instanceof nn&&u.error.status===403?"You do not have permission to review join requests for this organization.":u.error instanceof Error?u.error.message:"Failed to load join requests.";return(0,t.jsx)("div",{className:"text-sm text-destructive",children:f})}return(0,t.jsxs)("div",{className:"max-w-6xl space-y-6",children:[(0,t.jsxs)("div",{className:"space-y-3",children:[(0,t.jsxs)("div",{className:"flex items-center gap-2",children:[(0,t.jsx)(XKe,{className:"h-5 w-5 text-muted-foreground"}),(0,t.jsx)("h1",{className:"text-lg font-semibold",children:"Join Request Queue"})]}),(0,t.jsx)("p",{className:"max-w-3xl text-sm text-muted-foreground",children:"Review human and agent join requests outside the mixed inbox feed. This queue uses the same approval mutations as the inline inbox cards."})]}),(0,t.jsxs)(sn,{className:"flex-row flex-wrap gap-3 p-4",children:[(0,t.jsxs)("label",{className:"space-y-2 text-sm",children:[(0,t.jsx)("span",{className:"font-medium",children:"Status"}),(0,t.jsxs)("select",{className:"rounded-md border border-border bg-background px-3 py-2",value:o,onChange:r(f=>l(f.target.value),"onChange"),children:[(0,t.jsx)("option",{value:"pending_approval",children:"Pending approval"}),(0,t.jsx)("option",{value:"approved",children:"Approved"}),(0,t.jsx)("option",{value:"rejected",children:"Rejected"})]})]}),(0,t.jsxs)("label",{className:"space-y-2 text-sm",children:[(0,t.jsx)("span",{className:"font-medium",children:"Request type"}),(0,t.jsxs)("select",{className:"rounded-md border border-border bg-background px-3 py-2",value:c,onChange:r(f=>d(f.target.value),"onChange"),children:[(0,t.jsx)("option",{value:"all",children:"All"}),(0,t.jsx)("option",{value:"human",children:"Human"}),(0,t.jsx)("option",{value:"agent",children:"Agent"})]})]})]}),(0,t.jsx)("div",{className:"space-y-4",children:(u.data??[]).length===0?(0,t.jsx)("div",{className:"rounded-xl border border-dashed border-border px-4 py-8 text-sm text-muted-foreground",children:"No join requests match the current filters."}):u.data.map(f=>(0,t.jsxs)(sn,{className:"block p-4",children:[(0,t.jsxs)("div",{className:"flex flex-wrap items-start justify-between gap-4",children:[(0,t.jsxs)("div",{className:"space-y-2",children:[(0,t.jsxs)("div",{className:"flex flex-wrap items-center gap-2",children:[(0,t.jsx)(ot,{variant:f.status==="pending_approval"?"secondary":f.status==="approved"?"outline":"destructive",children:f.status.replace("_"," ")}),(0,t.jsx)(ot,{variant:"outline",children:f.requestType}),f.adapterType?(0,t.jsx)(ot,{variant:"outline",children:f.adapterType}):null]}),(0,t.jsxs)("div",{children:[(0,t.jsx)("div",{className:"text-base font-medium",children:f.requestType==="human"?f.requesterUser?.name||f.requestEmailSnapshot||f.requestingUserId||"Unknown human requester":f.agentName||"Unknown agent requester"}),(0,t.jsx)("div",{className:"text-sm text-muted-foreground",children:f.requestType==="human"?f.requesterUser?.email||f.requestEmailSnapshot||f.requestingUserId:f.capabilities||f.requestIp})]})]}),f.status==="pending_approval"?(0,t.jsxs)("div",{className:"flex gap-2",children:[(0,t.jsx)($,{variant:"outline",onClick:r(()=>p.mutate(f.id),"onClick"),disabled:p.isPending,children:"Reject"}),(0,t.jsx)($,{onClick:r(()=>h.mutate(f.id),"onClick"),disabled:h.isPending,children:"Approve"})]}):null]}),(0,t.jsxs)("div",{className:"mt-4 grid gap-3 text-sm text-muted-foreground md:grid-cols-2",children:[(0,t.jsxs)("div",{className:"rounded-lg border border-border bg-background px-3 py-2",children:[(0,t.jsx)("div",{className:"text-xs font-medium uppercase tracking-wide",children:"Invite context"}),(0,t.jsx)("div",{className:"mt-2",children:f.invite?`${f.invite.allowedJoinTypes} join invite${f.invite.humanRole?` • default role ${f.invite.humanRole}`:""}`:"Invite metadata unavailable"}),f.invite?.inviteMessage?(0,t.jsx)("div",{className:"mt-2 text-foreground",children:f.invite.inviteMessage}):null]}),(0,t.jsxs)("div",{className:"rounded-lg border border-border bg-background px-3 py-2",children:[(0,t.jsx)("div",{className:"text-xs font-medium uppercase tracking-wide",children:"Request details"}),(0,t.jsxs)("div",{className:"mt-2",children:["Submitted ",new Date(f.createdAt).toLocaleString()]}),(0,t.jsxs)("div",{children:["Source IP ",f.requestIp]}),f.requestType==="agent"&&f.capabilities?(0,t.jsx)("div",{children:f.capabilities}):null]})]})]},f.id))})]})}r(Vfs,"JoinRequestQueue");var Gfs=(0,m.lazy)(()=>bd(()=>import("./CompanyExport-s-XLEAp4.js").then(e=>({default:e.CompanyExport})),__vite__mapDeps([6,5,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25]))),Yfs=(0,m.lazy)(()=>bd(()=>import("./Agents.production-CYv4yLRB.js").then(e=>({default:e.Agents})),__vite__mapDeps([26,5,7,9,8,27,28,29,30,31,15,32,33,34,35,36,19,37,23,24,25]))),Zfs=(0,m.lazy)(()=>bd(()=>import("./Routines.production-BIUgcKXN.js").then(e=>({default:e.Routines})),__vite__mapDeps([38,5,7,8,9,39,28,40,33,16,17,21,41,14,15,27,29,30,31,42,43,44,45,46,10,11,12,34,47,48,49,35,50,51,20,36,52,53,54,37,55,23,24,25,32,22,19]))),_ge=(0,m.lazy)(()=>bd(()=>import("./RoutineDetail.production-DdnWpLkf.js").then(e=>({default:e.RoutineDetail})),__vite__mapDeps([56,5,7,8,9,39,28,40,33,16,17,21,41,14,15,27,29,30,31,42,43,44,45,46,10,11,12,34,47,48,49,35,50,51,20,36,52,53,54,37,55,23,24,25,57,58,22,19]))),Jfs=(0,m.lazy)(()=>bd(()=>import("./CompanySkills.production-DxzVSVNR.js").then(e=>({default:e.CompanySkills})),__vite__mapDeps([59,5,7,8,9,27,28,29,30,31,15,42,16,40,33,17,21,44,14,45,46,32,10,11,12,60,58,52,25,48,18,13,19,61,49,22,23,24]))),Xfs=(0,m.lazy)(()=>bd(()=>import("./CompanyActivity.production-C2uGYQY6.js").then(e=>({default:e.CompanyActivity})),__vite__mapDeps([62,5,7,8,9,31,15,32,33,47,45,30,16,48,22,19,52,53,54,55,23]))),exs=(0,m.lazy)(()=>bd(()=>import("./Terminal-DGY5mL23.js").then(e=>({default:e.Terminal})),__vite__mapDeps([63,5,7,8,9,40,33,28,16,17,21,43,52,53,37]))),txs=(0,m.lazy)(()=>bd(()=>import("./OrgChart.production-BUtz4rsX.js").then(e=>({default:e.OrgChart})),__vite__mapDeps([64,5,7,8,9,31,15,50,51,19,55,23,24,25])));function Xg({children:e}){return(0,t.jsx)(m.Suspense,{fallback:(0,t.jsx)(ch,{}),children:e})}r(Xg,"ProductionSurface");function sxs(e,s){const n=e&&s;return(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)(rt,{index:!0,element:(0,t.jsx)(In,{to:"dashboard",replace:!0})}),(0,t.jsx)(rt,{path:"dashboard",element:(0,t.jsx)(fAt,{})}),(0,t.jsx)(rt,{path:"dashboard/live",element:(0,t.jsx)(xAt,{})}),(0,t.jsx)(rt,{path:"timeline",element:e?(0,t.jsx)(_p,{to:"/activity/timeline"}):(0,t.jsx)(l6e,{})}),(0,t.jsx)(rt,{path:"onboarding",element:(0,t.jsx)(D9e,{})}),(0,t.jsx)(rt,{path:"companies",element:(0,t.jsx)(sIt,{})}),(0,t.jsx)(rt,{path:"company/settings",element:(0,t.jsx)(Iss,{})}),(0,t.jsx)(rt,{path:"company/settings/connections",element:(0,t.jsx)(Ess,{})}),(0,t.jsx)(rt,{path:"company/settings/environments",element:(0,t.jsx)(In,{to:"/company/settings/instance/environments",replace:!0})}),(0,t.jsx)(rt,{path:"company/settings/cloud-upstream",element:(0,t.jsx)(In,{to:"/company/export",replace:!0})}),(0,t.jsxs)(rt,{element:(0,t.jsx)(y0,{pageKey:"company.members"}),children:[(0,t.jsx)(rt,{path:"company/settings/members",element:(0,t.jsx)(jns,{})}),(0,t.jsx)(rt,{path:"company/settings/access",element:(0,t.jsx)(wns,{})})]}),(0,t.jsx)(rt,{element:(0,t.jsx)(y0,{pageKey:"company.invites"}),children:(0,t.jsx)(rt,{path:"company/settings/invites",element:(0,t.jsx)(In,{to:"/company/settings/members?tab=invites",replace:!0})})}),(0,t.jsx)(rt,{element:(0,t.jsx)(y0,{pageKey:"company.export"}),children:(0,t.jsx)(rt,{path:"company/export/*",element:(0,t.jsx)(m.Suspense,{fallback:(0,t.jsx)(ch,{}),children:(0,t.jsx)(Gfs,{})})})}),(0,t.jsx)(rt,{element:(0,t.jsx)(hgt,{}),children:(0,t.jsx)(rt,{element:(0,t.jsx)(y0,{pageKey:"company.import"}),children:(0,t.jsx)(rt,{path:"company/import",element:(0,t.jsx)(Q0s,{})})})}),(0,t.jsx)(rt,{element:(0,t.jsx)(y0,{pageKey:"company.secrets"}),children:(0,t.jsx)(rt,{path:"company/settings/secrets",element:(0,t.jsx)(Fhs,{})})}),(0,t.jsx)(rt,{path:"company/settings/tools",element:(0,t.jsx)(Tge,{})}),(0,t.jsx)(rt,{path:"company/settings/tools/:tab",element:(0,t.jsx)(Tge,{})}),(0,t.jsx)(rt,{path:"tools",element:(0,t.jsx)(Rge,{})}),(0,t.jsx)(rt,{path:"tools/:tab",element:(0,t.jsx)(Rge,{})}),(0,t.jsx)(rt,{path:"apps",element:(0,t.jsx)(gas,{})}),(0,t.jsx)(rt,{path:"apps/assistant-connection",element:(0,t.jsx)(Xrs,{})}),(0,t.jsx)(rt,{path:"apps/browse",element:(0,t.jsx)(In,{to:"/apps",replace:!0})}),(0,t.jsx)(rt,{path:"apps/connections",element:(0,t.jsx)(In,{to:"/apps",replace:!0})}),(0,t.jsx)(rt,{path:"apps/byo",element:(0,t.jsx)(nPe,{byoOnly:!0})}),(0,t.jsx)(rt,{path:"apps/vercel-connect",element:(0,t.jsx)(Age,{credentialSource:"vercel_connect"})}),(0,t.jsx)(rt,{path:"apps/connect",element:(0,t.jsx)(Age,{})}),(0,t.jsx)(rt,{path:"apps/chat/connect",element:(0,t.jsx)(wT,{children:(0,t.jsx)(His,{})})}),(0,t.jsx)(rt,{path:"apps/chat/:endpointId",element:(0,t.jsx)(wT,{children:(0,t.jsx)(In,{to:"settings",replace:!0})})}),(0,t.jsx)(rt,{path:"apps/chat/:endpointId/reviews/:reviewId",element:(0,t.jsx)(wT,{children:(0,t.jsx)(Nfe,{})})}),(0,t.jsx)(rt,{path:"apps/chat/:endpointId/:tab",element:(0,t.jsx)(wT,{children:(0,t.jsx)(Nfe,{})})}),(0,t.jsx)(rt,{path:"apps/connect/:appKey",element:(0,t.jsx)(In,{to:"/apps",replace:!0})}),(0,t.jsx)(rt,{path:"apps/connect/:appKey/:stage",element:(0,t.jsx)(In,{to:"/apps",replace:!0})}),(0,t.jsx)(rt,{path:"apps/review",element:(0,t.jsx)(Els,{})}),(0,t.jsx)(rt,{path:"apps/attention",element:(0,t.jsx)(In,{to:"/apps",replace:!0})}),(0,t.jsx)(rt,{path:"apps/gateways",element:(0,t.jsx)(Ife,{})}),(0,t.jsx)(rt,{path:"apps/gateways/:gatewayId",element:(0,t.jsx)(In,{to:"overview",replace:!0})}),(0,t.jsx)(rt,{path:"apps/gateways/:gatewayId/:tab",element:(0,t.jsx)(lcs,{})}),(0,t.jsx)(rt,{path:"apps/advanced",element:(0,t.jsx)(Kpe,{})}),(0,t.jsx)(rt,{path:"apps/advanced/gateways",element:(0,t.jsx)(Ife,{})}),(0,t.jsx)(rt,{path:"apps/advanced/profiles/new",element:(0,t.jsx)(Gpe,{mode:"new"})}),(0,t.jsx)(rt,{path:"apps/advanced/profiles/:profileId/edit",element:(0,t.jsx)(Gpe,{mode:"edit"})}),(0,t.jsx)(rt,{path:"apps/advanced/profiles/:profileId",element:(0,t.jsx)(zrs,{})}),(0,t.jsx)(rt,{path:"apps/advanced/audit",element:(0,t.jsx)(In,{to:"/apps",replace:!0})}),(0,t.jsx)(rt,{path:"apps/advanced/run-your-own",element:(0,t.jsx)(In,{to:"/apps",replace:!0})}),(0,t.jsx)(rt,{path:"apps/advanced/:tab",element:(0,t.jsx)(Kpe,{})}),(0,t.jsx)(rt,{path:"apps/app/:applicationId",element:(0,t.jsx)(Cfe,{})}),(0,t.jsx)(rt,{path:"apps/app/:applicationId/:tab",element:(0,t.jsx)(Cfe,{})}),(0,t.jsx)(rt,{path:"apps/:connectionId",element:(0,t.jsx)(In,{to:"permissions",replace:!0})}),(0,t.jsx)(rt,{path:"apps/:connectionId/:tab",element:(0,t.jsx)(pis,{})}),(0,t.jsx)(rt,{path:"company/settings/instance",element:(0,t.jsx)(In,{to:"/company/settings",replace:!0})}),(0,t.jsx)(rt,{element:(0,t.jsx)(y0,{pageKey:"instance.profile"}),children:(0,t.jsx)(rt,{path:"company/settings/instance/profile",element:(0,t.jsx)(Jps,{})})}),(0,t.jsx)(rt,{path:"company/settings/instance/general",element:(0,t.jsx)(In,{to:"/company/settings",replace:!0})}),(0,t.jsx)(rt,{path:"company/settings/instance/heartbeats",element:(0,t.jsx)(In,{to:"/company/settings",replace:!0})}),(0,t.jsxs)(rt,{element:(0,t.jsx)(y0,{pageKey:"instance.environments"}),children:[(0,t.jsx)(rt,{path:"company/settings/instance/environments",element:(0,t.jsx)(iB,{})}),(0,t.jsx)(rt,{path:"company/settings/instance/environments/new",element:(0,t.jsx)(iB,{mode:"create"})}),(0,t.jsx)(rt,{path:"company/settings/instance/environments/:environmentId/edit",element:(0,t.jsx)(iB,{mode:"edit"})})]}),(0,t.jsx)(rt,{element:(0,t.jsx)(y0,{pageKey:"instance.access"}),children:(0,t.jsx)(rt,{path:"company/settings/instance/access",element:(0,t.jsx)(Kps,{})})}),(0,t.jsx)(rt,{element:(0,t.jsx)(y0,{pageKey:"instance.experimental"}),children:(0,t.jsx)(rt,{path:"company/settings/instance/experimental",element:(0,t.jsx)(Ups,{})})}),(0,t.jsxs)(rt,{element:(0,t.jsx)(y0,{pageKey:"instance.plugins"}),children:[(0,t.jsx)(rt,{path:"company/settings/instance/plugins",element:(0,t.jsx)(efs,{})}),(0,t.jsx)(rt,{path:"company/settings/instance/plugins/:pluginId",element:(0,t.jsx)(tfs,{})})]}),(0,t.jsx)(rt,{element:(0,t.jsx)(y0,{pageKey:"instance.adapters"}),children:(0,t.jsx)(rt,{path:"company/settings/instance/adapters",element:(0,t.jsx)(uge,{})})}),(0,t.jsx)(rt,{path:"company/settings/:settingsRoutePath/*",element:(0,t.jsx)(pns,{})}),(0,t.jsx)(rt,{path:"skills/sources",element:(0,t.jsx)(txe,{})}),(0,t.jsx)(rt,{path:"skills/sources/:sourceId",element:(0,t.jsx)(txe,{})}),(0,t.jsx)(rt,{path:"skills/studio",element:(0,t.jsx)(EB,{})}),(0,t.jsx)(rt,{path:"skills/studio/new",element:(0,t.jsx)(EB,{})}),(0,t.jsx)(rt,{path:"skills/studio/:skillId",element:(0,t.jsx)(EB,{})}),(0,t.jsx)(rt,{path:"skills/:skillId/studio",element:(0,t.jsx)(M9e,{})}),(0,t.jsx)(rt,{path:"skills/*",element:e?(0,t.jsx)(kds,{}):(0,t.jsx)(Xg,{children:(0,t.jsx)(Jfs,{})})}),(0,t.jsx)(rt,{path:"settings",element:(0,t.jsx)(Ry,{})}),(0,t.jsx)(rt,{path:"settings/*",element:(0,t.jsx)(Ry,{})}),(0,t.jsx)(rt,{path:"plugins/:pluginId",element:(0,t.jsx)(mge,{})}),(0,t.jsx)(rt,{path:"org",element:e?(0,t.jsx)(In,{to:"/agents/all",replace:!0}):(0,t.jsx)(Xg,{children:(0,t.jsx)(txs,{})})}),(0,t.jsx)(rt,{path:"agents",element:(0,t.jsx)(In,{to:"/agents/all",replace:!0})}),sY.map(a=>(0,t.jsx)(rt,{path:`agents/${a}`,element:e?(0,t.jsx)(YIt,{}):(0,t.jsx)(Xg,{children:(0,t.jsx)(Yfs,{})})},a)),(0,t.jsx)(rt,{path:"agents/new",element:(0,t.jsx)(vfs,{})}),(0,t.jsx)(rt,{path:"agents/:agentId",element:(0,t.jsx)(N$,{})}),(0,t.jsx)(rt,{path:"agents/:agentId/:tab",element:(0,t.jsx)(N$,{})}),(0,t.jsx)(rt,{path:"agents/:agentId/runs/:runId",element:(0,t.jsx)(N$,{})}),(0,t.jsx)(rt,{path:"projects",element:(0,t.jsx)(gRt,{})}),(0,t.jsx)(rt,{path:"projects/:projectId",element:(0,t.jsx)(Hv,{})}),(0,t.jsx)(rt,{path:"projects/:projectId/overview",element:(0,t.jsx)(Hv,{})}),(0,t.jsx)(rt,{path:"projects/:projectId/issues",element:(0,t.jsx)(Hv,{})}),(0,t.jsx)(rt,{path:"projects/:projectId/issues/:filter",element:(0,t.jsx)(Hv,{})}),(0,t.jsx)(rt,{element:(0,t.jsx)(_D,{}),children:(0,t.jsx)(rt,{path:"projects/:projectId/workspaces/:workspaceId",element:(0,t.jsx)(pLt,{})})}),(0,t.jsx)(rt,{path:"projects/:projectId/workspaces",element:(0,t.jsx)(Hv,{})}),(0,t.jsx)(rt,{path:"projects/:projectId/configuration",element:(0,t.jsx)(Hv,{})}),(0,t.jsx)(rt,{path:"projects/:projectId/budget",element:(0,t.jsx)(Hv,{})}),(0,t.jsx)(rt,{element:(0,t.jsx)(_D,{}),children:(0,t.jsx)(rt,{path:"workspaces",element:(0,t.jsx)(gLt,{})})}),(0,t.jsx)(rt,{path:"terminal",element:(0,t.jsx)(Xg,{children:(0,t.jsx)(exs,{})})}),(0,t.jsx)(rt,{path:"issues",element:(0,t.jsx)(zMt,{})}),(0,t.jsx)(rt,{path:"tasks",element:(0,t.jsx)(In,{to:"/issues",replace:!0})}),(0,t.jsx)(rt,{path:"search",element:(0,t.jsx)(o7t,{})}),n?(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)(rt,{path:"issues/all",element:(0,t.jsx)(Lh,{view:"all"})}),(0,t.jsx)(rt,{path:"issues/active",element:(0,t.jsx)(Lh,{view:"active"})}),(0,t.jsx)(rt,{path:"issues/backlog",element:(0,t.jsx)(Lh,{view:"backlog"})}),(0,t.jsx)(rt,{path:"issues/done",element:(0,t.jsx)(Lh,{view:"done"})}),(0,t.jsx)(rt,{path:"issues/recent",element:(0,t.jsx)(Lh,{view:"recent"})})]}):(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)(rt,{path:"issues/all",element:(0,t.jsx)(In,{to:"/issues",replace:!0})}),(0,t.jsx)(rt,{path:"issues/active",element:(0,t.jsx)(In,{to:"/issues",replace:!0})}),(0,t.jsx)(rt,{path:"issues/backlog",element:(0,t.jsx)(In,{to:"/issues",replace:!0})}),(0,t.jsx)(rt,{path:"issues/done",element:(0,t.jsx)(In,{to:"/issues",replace:!0})}),(0,t.jsx)(rt,{path:"issues/recent",element:(0,t.jsx)(In,{to:"/issues",replace:!0})})]}),(0,t.jsx)(rt,{path:"chats",element:(0,t.jsx)(bUt,{})}),(0,t.jsx)(rt,{path:"chats/:agentRef",element:(0,t.jsx)(yUt,{})}),(0,t.jsx)(rt,{path:"issues/:issueId",element:(0,t.jsx)(hUt,{})}),null,(0,t.jsx)(rt,{path:"routines",element:e?(0,t.jsx)(XUt,{}):(0,t.jsx)(Xg,{children:(0,t.jsx)(Zfs,{})})}),(0,t.jsx)(rt,{path:"cases",element:(0,t.jsx)(lie,{children:(0,t.jsx)(Lgt,{})})}),(0,t.jsx)(rt,{path:"cases/:caseIdentifier",element:(0,t.jsx)(lie,{children:(0,t.jsx)(byt,{})})}),(0,t.jsx)(rt,{path:"pixels-office",element:(0,t.jsx)(mgt,{children:(0,t.jsx)(TZt,{})})}),(0,t.jsx)(rt,{path:"status",element:(0,t.jsx)(cie,{children:(0,t.jsx)($he,{})})}),(0,t.jsx)(rt,{path:"status/:cardId",element:(0,t.jsx)(cie,{children:(0,t.jsx)($he,{})})}),(0,t.jsx)(rt,{path:"status-cards",element:(0,t.jsx)(Ege,{})}),(0,t.jsx)(rt,{path:"status-cards/:cardId",element:(0,t.jsx)(Ege,{})}),(0,t.jsx)(rt,{path:"review-queue",element:(0,t.jsx)(Qg,{children:(0,t.jsx)(gWt,{})})}),(0,t.jsx)(rt,{path:"learnings",element:(0,t.jsx)(Qg,{children:(0,t.jsx)(vWt,{})})}),(0,t.jsx)(rt,{path:"pipelines",element:(0,t.jsx)(Qg,{children:(0,t.jsx)(LO,{})})}),(0,t.jsx)(rt,{path:"pipelines/:pipelineId",element:(0,t.jsx)(Qg,{children:(0,t.jsx)(LO,{})})}),(0,t.jsx)(rt,{path:"pipelines/:pipelineId/add",element:(0,t.jsx)(Qg,{children:(0,t.jsx)(LO,{})})}),(0,t.jsx)(rt,{path:"pipelines/:pipelineId/settings",element:(0,t.jsx)(Qg,{children:(0,t.jsx)(mHt,{})})}),(0,t.jsx)(rt,{path:"pipelines/:pipelineId/items/:caseId",element:(0,t.jsx)(Qg,{children:(0,t.jsx)($Qt,{})})}),(0,t.jsx)(rt,{path:"pipelines/:pipelineId/cases/:caseId",element:(0,t.jsx)(Qg,{children:(0,t.jsx)(MQt,{})})}),(0,t.jsx)(rt,{path:"routines/:routineId",element:e?(0,t.jsx)(B0e,{}):(0,t.jsx)(Xg,{children:(0,t.jsx)(_ge,{})})}),(0,t.jsx)(rt,{path:"routines/:routineId/:section",element:e?(0,t.jsx)(B0e,{}):(0,t.jsx)(Xg,{children:(0,t.jsx)(_ge,{})})}),(0,t.jsx)(rt,{element:(0,t.jsx)(_D,{}),children:(0,t.jsxs)(rt,{element:(0,t.jsx)(fgt,{}),children:[(0,t.jsx)(rt,{path:"execution-workspaces/:workspaceId",element:(0,t.jsx)(k1,{})}),(0,t.jsx)(rt,{path:"execution-workspaces/:workspaceId/services",element:(0,t.jsx)(k1,{})}),(0,t.jsx)(rt,{path:"execution-workspaces/:workspaceId/configuration",element:(0,t.jsx)(k1,{})}),(0,t.jsx)(rt,{path:"execution-workspaces/:workspaceId/runtime-logs",element:(0,t.jsx)(k1,{})}),(0,t.jsx)(rt,{path:"execution-workspaces/:workspaceId/issues",element:(0,t.jsx)(k1,{})}),(0,t.jsx)(rt,{path:"execution-workspaces/:workspaceId/routines",element:(0,t.jsx)(k1,{})})]})}),(0,t.jsx)(rt,{path:"goals",element:(0,t.jsx)(AXt,{})}),(0,t.jsx)(rt,{path:"goals/:goalId",element:(0,t.jsx)(BXt,{})}),(0,t.jsx)(rt,{path:"artifacts",element:(0,t.jsx)(U0e,{})}),(0,t.jsx)(rt,{path:"approvals",element:(0,t.jsx)(In,{to:"/approvals/pending",replace:!0})}),(0,t.jsx)(rt,{path:"approvals/pending",element:(0,t.jsx)(Q0e,{})}),(0,t.jsx)(rt,{path:"approvals/all",element:(0,t.jsx)(Q0e,{})}),(0,t.jsx)(rt,{path:"approvals/:approvalId",element:(0,t.jsx)(FXt,{})}),(0,t.jsx)(rt,{path:"activity",element:e?(0,t.jsx)(Des,{}):(0,t.jsx)(Xg,{children:(0,t.jsx)(Xfs,{})})}),e?(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)(rt,{path:"activity/runs",element:(0,t.jsx)(qC,{section:"runs"})}),(0,t.jsx)(rt,{path:"activity/costs",element:(0,t.jsx)(qC,{section:"costs"})}),(0,t.jsx)(rt,{path:"activity/budgets",element:(0,t.jsx)(qC,{section:"budgets"})}),(0,t.jsx)(rt,{path:"activity/timeline",element:(0,t.jsx)(qC,{section:"timeline"})}),(0,t.jsx)(rt,{path:"audit",element:(0,t.jsx)(_p,{to:"/activity",forceAgentMode:!0})}),(0,t.jsx)(rt,{path:"audit/activity",element:(0,t.jsx)(_p,{to:"/activity"})}),(0,t.jsx)(rt,{path:"audit/runs",element:(0,t.jsx)(_p,{to:"/activity/runs"})}),(0,t.jsx)(rt,{path:"audit/costs",element:(0,t.jsx)(_p,{to:"/activity/costs"})}),(0,t.jsx)(rt,{path:"audit/budgets",element:(0,t.jsx)(_p,{to:"/activity/budgets"})}),(0,t.jsx)(rt,{path:"audit/timeline",element:(0,t.jsx)(_p,{to:"/activity/timeline"})}),(0,t.jsx)(rt,{path:"runs",element:(0,t.jsx)(_p,{to:"/activity/runs"})}),(0,t.jsx)(rt,{path:"costs",element:(0,t.jsx)(_p,{to:"/activity/costs"})}),(0,t.jsx)(rt,{path:"budgets",element:(0,t.jsx)(_p,{to:"/activity/budgets"})})]}):(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)(rt,{path:"costs",element:(0,t.jsx)(zK,{})}),(0,t.jsx)(rt,{path:"audit",element:(0,t.jsx)(In,{to:"/activity?mode=agents",replace:!0})})]}),(0,t.jsxs)(rt,{element:(0,t.jsx)(xpt,{}),children:[(0,t.jsx)(rt,{path:"board-chat",element:(0,t.jsx)(sss,{})}),(0,t.jsx)(rt,{path:"artifacts",element:(0,t.jsx)(U0e,{})})]}),null,(0,t.jsx)(rt,{path:"decisions",element:(0,t.jsx)(_ts,{})}),(0,t.jsx)(rt,{path:"decisions/queues/:key",element:(0,t.jsx)(Rts,{})}),n?(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)(rt,{path:"inbox",element:(0,t.jsx)(Ige,{})}),(0,t.jsx)(rt,{path:"inbox/mine",element:(0,t.jsx)(Lh,{view:"mine"})}),(0,t.jsx)(rt,{path:"inbox/recent",element:(0,t.jsx)(Lh,{view:"recent"})}),(0,t.jsx)(rt,{path:"inbox/unread",element:(0,t.jsx)(Lh,{view:"unread"})}),(0,t.jsx)(rt,{path:"inbox/blocked",element:(0,t.jsx)(Lh,{view:"blocked"})}),(0,t.jsx)(rt,{path:"inbox/all",element:(0,t.jsx)(Lh,{view:"everything"})}),(0,t.jsx)(rt,{path:"inbox/new",element:(0,t.jsx)(Lh,{view:"mine"})})]}):(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)(rt,{path:"inbox",element:(0,t.jsx)(Ige,{})}),(0,t.jsx)(rt,{path:"inbox/mine",element:(0,t.jsx)(q1,{})}),(0,t.jsx)(rt,{path:"inbox/recent",element:(0,t.jsx)(q1,{})}),(0,t.jsx)(rt,{path:"inbox/unread",element:(0,t.jsx)(q1,{})}),(0,t.jsx)(rt,{path:"inbox/blocked",element:(0,t.jsx)(q1,{})}),(0,t.jsx)(rt,{path:"inbox/all",element:(0,t.jsx)(q1,{})}),(0,t.jsx)(rt,{path:"inbox/new",element:(0,t.jsx)(In,{to:"/inbox/mine",replace:!0})})]}),(0,t.jsx)(rt,{path:"inbox/requests",element:(0,t.jsx)(Vfs,{})}),(0,t.jsx)(rt,{path:"u/:userSlug",element:(0,t.jsx)(sXt,{})}),(0,t.jsx)(rt,{path:"design-guide",element:(0,t.jsx)(Bps,{})}),(0,t.jsx)(rt,{path:"instance/settings/adapters",element:(0,t.jsx)(uge,{})}),(0,t.jsx)(rt,{path:":pluginRoutePath/*",element:(0,t.jsx)(mge,{})}),(0,t.jsx)(rt,{path:"*",element:(0,t.jsx)(mm,{scope:"board"})})]})}r(sxs,"boardRoutes");function Age({credentialSource:e="paperclip_vault"}={}){const s=la(),n=new URLSearchParams(s.search),{enabled:a,githubEnabled:i}=sw();return ymt(n,{chatConnectorsEnabled:a,githubReviewBotsEnabled:i})?(0,t.jsx)(nPe,{credentialSource:e}):(0,t.jsx)(In,{to:"/apps",replace:!0})}r(Age,"AppsConnectEntryRoute");function Ige(){const{enabled:e}=Ec(),{enabled:s}=F3();return e&&s?(0,t.jsx)(Lh,{view:mBe(Gee())}):(0,t.jsx)(In,{to:`/inbox/${Gee()}`,replace:!0})}r(Ige,"InboxRootRedirect");function Lh({view:e}){const s=la(),n=new URLSearchParams(s.search);return n.set(qT,e),(0,t.jsx)(In,{to:`/issues?${n.toString()}${s.hash}`,replace:!0})}r(Lh,"TaskViewRedirect");function M9e(){const e=la(),{companies:s,selectedCompany:n,loading:a}=fs(),{companyPrefix:i,skillId:o}=xa();if(a)return null;const l=(i?s.find(c=>c.issuePrefix.toUpperCase()===i.toUpperCase()):null)??n??s[0]??null;return!l||!o?(0,t.jsx)(In,{to:"/skills/studio",replace:!0}):(0,t.jsx)(In,{to:`/${l.issuePrefix}/skills/studio/${encodeURIComponent(o)}${e.search}${e.hash}`,replace:!0})}r(M9e,"LegacySkillStudioRedirect");function Ry(){const e=la(),{companies:s,selectedCompany:n,loading:a}=fs(),{companyPrefix:i}=xa(),{hidden:o}=Eu();if(a)return(0,t.jsx)(ch,{});const l=(i?s.find(d=>d.issuePrefix.toUpperCase()===i.toUpperCase()):null)??n??s[0]??null;if(!l)return RV({pathname:e.pathname,hasCompanies:!1})?(0,t.jsx)(In,{to:"/onboarding",replace:!0}):(0,t.jsx)(KZ,{});const c=wVe(Dke(`${e.pathname}${e.search}${e.hash}`),o);return(0,t.jsx)(In,{to:`/${l.issuePrefix}${c}`,replace:!0})}r(Ry,"LegacySettingsRedirect");function Tge(){const{tab:e}=xa();return(0,t.jsx)(In,{to:P9e(e),replace:!0})}r(Tge,"LegacyToolsSettingsRedirect");function Rge(){const{tab:e}=xa();return(0,t.jsx)(In,{to:P9e(e),replace:!0})}r(Rge,"LegacyToolsRedirect");function P9e(e){return e?e==="applications"||e==="connections"||e==="overview"||e==="examples"||e==="runtime"||e==="audit"?"/apps":e==="policies"?"/apps/advanced/profiles":`/apps/advanced/${e}`:"/apps/advanced/profiles"}r(P9e,"legacyToolsRedirectTarget");function D9e(){const{companies:e}=fs(),{openOnboarding:s}=al(),{t:n}=lke(),a=td(),i=L5e(a?.cloudBaseUrl??null),{onboardingOpen:o,onboardingRouteDismissed:l}=AL(),{companyPrefix:c}=xa(),d=c?e.find(p=>p.issuePrefix.toUpperCase()===c.toUpperCase())??null:null;if(Aht({onboardingOpen:o,routeDismissed:l}))return null;const u=d?`Add another agent to ${d.name}`:e.length>0?"Create another organization":"Create your first organization",h=d?"Run onboarding again to add an agent and a starter task for this organization.":e.length>0?"Run onboarding again to create another organization and seed its first agent.":"Get started by creating an organization and your first agent.";return(0,t.jsx)("div",{className:"mx-auto max-w-xl py-10",children:(0,t.jsxs)("div",{className:"rounded-lg border border-border bg-card p-6",children:[(0,t.jsx)("h1",{className:"text-xl font-semibold",children:u}),(0,t.jsx)("p",{className:"mt-2 text-sm text-muted-foreground",children:h}),(0,t.jsx)("div",{className:"mt-4",children:!d&&a&&!i?(0,t.jsx)("p",{className:"text-sm text-muted-foreground",children:n("app.cloudCreateUnavailable",{defaultValue:"Organizations are created in Paperclip Cloud. This instance can't reach it right now — try again from your Cloud portfolio."})}):(0,t.jsx)($,{onClick:r(()=>d?s({initialStep:IE(),companyId:d.id}):a&&i?lh(i):s(),"onClick"),children:d?"Add Agent":"Start Onboarding"})})]})})}r(D9e,"OnboardingRoutePage");function nxs(){const{companies:e,selectedCompany:s,loading:n}=fs(),a=la();if(n)return(0,t.jsx)(ch,{});const i=s??e[0]??null;return i?(0,t.jsx)(In,{to:`/${i.issuePrefix}/dashboard`,replace:!0}):RV({pathname:a.pathname,hasCompanies:!1})?(0,t.jsx)(In,{to:"/onboarding",replace:!0}):(0,t.jsx)(KZ,{})}r(nxs,"CompanyRootRedirect");function Ege(){const{cardId:e}=xa(),s=IBe(),n=s?`/${s}`:"";return(0,t.jsx)(In,{to:`${n}/status${e?`/${e}`:""}`,replace:!0})}r(Ege,"StatusCardsLegacyRedirect");function _p({to:e,forceAgentMode:s=!1}){const n=la(),a=new URLSearchParams(n.search);s&&a.set("mode","agents");const i=a.toString();return(0,t.jsx)(In,{to:`${e}${i?`?${i}`:""}${n.hash}`,replace:!0})}r(_p,"AuditCompatibilityRedirect");function ya(){const e=la(),{companies:s,selectedCompany:n,loading:a}=fs();if(a)return(0,t.jsx)(ch,{});const i=n??s[0]??null;return i?(0,t.jsx)(In,{to:`/${i.issuePrefix}${e.pathname}${e.search}${e.hash}`,replace:!0}):RV({pathname:e.pathname,hasCompanies:!1})?(0,t.jsx)(In,{to:"/onboarding",replace:!0}):(0,t.jsx)(KZ,{})}r(ya,"UnprefixedBoardRedirect");function KZ(){const{openOnboarding:e}=al(),{t:s}=lke(),n=td(),a=L5e(n?.cloudBaseUrl??null);return(0,t.jsx)("div",{className:"mx-auto max-w-xl py-10",children:(0,t.jsxs)("div",{className:"rounded-lg border border-border bg-card p-6",children:[(0,t.jsx)("h1",{className:"text-xl font-semibold",children:s("app.noCompanies.title",{defaultValue:"Create your first organization"})}),(0,t.jsx)("p",{className:"mt-2 text-sm text-muted-foreground",children:s("app.noCompanies.description",{defaultValue:"Get started by creating an organization."})}),(0,t.jsx)("div",{className:"mt-4",children:n&&!a?(0,t.jsx)("p",{className:"text-sm text-muted-foreground",children:s("app.cloudCreateUnavailable",{defaultValue:"Organizations are created in Paperclip Cloud. This instance can't reach it right now — try again from your Cloud portfolio."})}):(0,t.jsx)($,{onClick:r(()=>n&&a?lh(a):e(),"onClick"),children:s("app.noCompanies.newCompany",{defaultValue:"New Organization"})})})]})})}r(KZ,"NoCompaniesStartPage");function rxs(){const{enabled:e,loaded:s}=Ec(),{enabled:n}=F3();return(0,t.jsxs)(t.Fragment,{children:[(0,t.jsxs)(hBe,{children:[(0,t.jsx)(rt,{path:"oauth-handoff",element:(0,t.jsx)(Fls,{})}),(0,t.jsx)(rt,{path:"auth",element:(0,t.jsx)(Sfs,{})}),(0,t.jsx)(rt,{path:"board-claim/:token",element:(0,t.jsx)(Cfs,{})}),(0,t.jsx)(rt,{path:"mcp-connect/:id",element:(0,t.jsx)(vge,{})}),(0,t.jsx)(rt,{path:"dot-connect/:id",element:(0,t.jsx)(vge,{agentPairingOnly:!0})}),(0,t.jsx)(rt,{path:"mcp-device",element:(0,t.jsx)(_fs,{})}),(0,t.jsx)(rt,{path:"assistant-connections",element:(0,t.jsx)(Afs,{})}),(0,t.jsx)(rt,{path:"cli-auth/:id",element:(0,t.jsx)(Ifs,{})}),(0,t.jsx)(rt,{path:"invite/:token",element:(0,t.jsx)(Dfs,{})}),(0,t.jsx)(rt,{path:"s/:token",element:(0,t.jsx)(Cge,{})}),(0,t.jsx)(rt,{path:"s/:token/issues/:issueId",element:(0,t.jsx)(Cge,{})}),(0,t.jsx)(rt,{element:s?(0,t.jsx)(roe,{allowMembershipRequest:!0}):(0,t.jsx)(ch,{}),children:(0,t.jsx)(rt,{path:"chat-identity/confirm",element:(0,t.jsx)(Tls,{})})}),(0,t.jsx)(rt,{path:"tests/perf/long-thread",element:(0,t.jsx)(RUt,{})}),(0,t.jsx)(rt,{path:"ux-lab/bootstrap-setup",element:(0,t.jsx)(dns,{})}),(0,t.jsx)(rt,{path:"ux-lab/responsible-user-denial",element:(0,t.jsx)(uns,{})}),(0,t.jsx)(rt,{path:"ux-lab/cross-issue-collaboration",element:(0,t.jsx)(hns,{})}),(0,t.jsxs)(rt,{element:s?(0,t.jsx)(roe,{}):(0,t.jsx)(ch,{}),children:[(0,t.jsx)(rt,{index:!0,element:(0,t.jsx)(nxs,{})}),(0,t.jsx)(rt,{path:"onboarding",element:(0,t.jsx)(D9e,{})}),(0,t.jsx)(rt,{path:"instance",element:(0,t.jsx)(Ry,{})}),(0,t.jsx)(rt,{path:"instance/settings",element:(0,t.jsx)(Ry,{})}),(0,t.jsx)(rt,{path:"instance/settings/*",element:(0,t.jsx)(Ry,{})}),(0,t.jsx)(rt,{path:"companies",element:(0,t.jsx)(ya,{})}),(0,t.jsx)(rt,{path:"dashboard",element:(0,t.jsx)(ya,{})}),(0,t.jsx)(rt,{path:"inbox/*",element:(0,t.jsx)(ya,{})}),(0,t.jsx)(rt,{path:"issues",element:(0,t.jsx)(ya,{})}),(0,t.jsx)(rt,{path:"tasks",element:(0,t.jsx)(ya,{})}),(0,t.jsx)(rt,{path:"issues/:issueId",element:(0,t.jsx)(ya,{})}),(0,t.jsx)(rt,{path:"routines",element:(0,t.jsx)(ya,{})}),(0,t.jsx)(rt,{path:"routines/:routineId",element:(0,t.jsx)(ya,{})}),(0,t.jsx)(rt,{path:"review-queue",element:(0,t.jsx)(ya,{})}),(0,t.jsx)(rt,{path:"learnings",element:(0,t.jsx)(ya,{})}),(0,t.jsx)(rt,{path:"cases",element:(0,t.jsx)(ya,{})}),(0,t.jsx)(rt,{path:"cases/:caseIdentifier",element:(0,t.jsx)(ya,{})}),(0,t.jsx)(rt,{path:"pixels-office",element:(0,t.jsx)(ya,{})}),(0,t.jsx)(rt,{path:"status",element:(0,t.jsx)(ya,{})}),(0,t.jsx)(rt,{path:"status/:cardId",element:(0,t.jsx)(ya,{})}),(0,t.jsx)(rt,{path:"status-cards",element:(0,t.jsx)(ya,{})}),(0,t.jsx)(rt,{path:"status-cards/:cardId",element:(0,t.jsx)(ya,{})}),(0,t.jsx)(rt,{path:"pipelines",element:(0,t.jsx)(ya,{})}),(0,t.jsx)(rt,{path:"pipelines/:pipelineId",element:(0,t.jsx)(ya,{})}),(0,t.jsx)(rt,{path:"pipelines/:pipelineId/add",element:(0,t.jsx)(ya,{})}),(0,t.jsx)(rt,{path:"pipelines/:pipelineId/settings",element:(0,t.jsx)(ya,{})}),(0,t.jsx)(rt,{path:"pipelines/:pipelineId/items/:caseId",element:(0,t.jsx)(ya,{})}),(0,t.jsx)(rt,{path:"pipelines/:pipelineId/cases/:caseId",element:(0,t.jsx)(ya,{})}),(0,t.jsx)(rt,{path:"artifacts",element:(0,t.jsx)(ya,{})}),(0,t.jsx)(rt,{path:"audit",element:(0,t.jsx)(ya,{})}),e?(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)(rt,{path:"audit/*",element:(0,t.jsx)(ya,{})}),(0,t.jsx)(rt,{path:"activity",element:(0,t.jsx)(ya,{})}),(0,t.jsx)(rt,{path:"activity/*",element:(0,t.jsx)(ya,{})}),(0,t.jsx)(rt,{path:"runs",element:(0,t.jsx)(ya,{})}),(0,t.jsx)(rt,{path:"costs",element:(0,t.jsx)(ya,{})}),(0,t.jsx)(rt,{path:"budgets",element:(0,t.jsx)(ya,{})})]}):null,(0,t.jsx)(rt,{path:"decisions",element:(0,t.jsx)(ya,{})}),(0,t.jsx)(rt,{path:"u/:userSlug",element:(0,t.jsx)(ya,{})}),(0,t.jsx)(rt,{path:"skills/studio",element:(0,t.jsx)(ya,{})}),(0,t.jsx)(rt,{path:"skills/studio/new",element:(0,t.jsx)(ya,{})}),(0,t.jsx)(rt,{path:"skills/studio/:skillId",element:(0,t.jsx)(ya,{})}),(0,t.jsx)(rt,{path:"skills/:skillId/studio",element:(0,t.jsx)(M9e,{})}),(0,t.jsx)(rt,{path:"skills/*",element:(0,t.jsx)(ya,{})}),(0,t.jsx)(rt,{path:"settings",element:(0,t.jsx)(Ry,{})}),(0,t.jsx)(rt,{path:"settings/*",element:(0,t.jsx)(Ry,{})}),(0,t.jsx)(rt,{path:"agents",element:(0,t.jsx)(ya,{})}),sY.map(a=>(0,t.jsx)(rt,{path:`agents/${a}`,element:(0,t.jsx)(ya,{})},a)),(0,t.jsx)(rt,{path:"agents/new",element:(0,t.jsx)(ya,{})}),(0,t.jsx)(rt,{path:"agents/:agentId",element:(0,t.jsx)(ya,{})}),(0,t.jsx)(rt,{path:"agents/:agentId/:tab",element:(0,t.jsx)(ya,{})}),(0,t.jsx)(rt,{path:"agents/:agentId/runs/:runId",element:(0,t.jsx)(ya,{})}),(0,t.jsx)(rt,{path:"projects",element:(0,t.jsx)(ya,{})}),(0,t.jsx)(rt,{path:"projects/:projectId",element:(0,t.jsx)(ya,{})}),(0,t.jsx)(rt,{path:"projects/:projectId/overview",element:(0,t.jsx)(ya,{})}),(0,t.jsx)(rt,{path:"projects/:projectId/issues",element:(0,t.jsx)(ya,{})}),(0,t.jsx)(rt,{path:"projects/:projectId/issues/:filter",element:(0,t.jsx)(ya,{})}),(0,t.jsx)(rt,{path:"projects/:projectId/workspaces",element:(0,t.jsx)(ya,{})}),(0,t.jsx)(rt,{path:"projects/:projectId/workspaces/:workspaceId",element:(0,t.jsx)(ya,{})}),(0,t.jsx)(rt,{path:"projects/:projectId/configuration",element:(0,t.jsx)(ya,{})}),(0,t.jsx)(rt,{path:"workspaces",element:(0,t.jsx)(ya,{})}),(0,t.jsx)(rt,{path:"terminal",element:(0,t.jsx)(ya,{})}),(0,t.jsx)(rt,{path:"execution-workspaces/:workspaceId",element:(0,t.jsx)(e1,{})}),(0,t.jsx)(rt,{path:"execution-workspaces/:workspaceId/services",element:(0,t.jsx)(e1,{})}),(0,t.jsx)(rt,{path:"execution-workspaces/:workspaceId/configuration",element:(0,t.jsx)(e1,{})}),(0,t.jsx)(rt,{path:"execution-workspaces/:workspaceId/runtime-logs",element:(0,t.jsx)(e1,{})}),(0,t.jsx)(rt,{path:"execution-workspaces/:workspaceId/issues",element:(0,t.jsx)(e1,{})}),(0,t.jsx)(rt,{path:"execution-workspaces/:workspaceId/routines",element:(0,t.jsx)(e1,{})}),(0,t.jsx)(rt,{path:":companyPrefix",element:e?(0,t.jsx)(M0t,{}):(0,t.jsx)(hpt,{}),children:sxs(e,n)}),(0,t.jsx)(rt,{path:"*",element:(0,t.jsx)(mm,{scope:"global"})})]})]}),(0,t.jsx)(ijt,{}),(0,t.jsx)(p0t,{})]})}r(rxs,"App");var axs=class extends m.Component{static{r(this,"AppErrorBoundary")}state={error:null};static getDerivedStateFromError(e){return{error:e instanceof Error?e:new Error(String(e))}}componentDidCatch(e,s){LV(e,{boundary:"app",componentStack:s.componentStack})}render(){const{error:e}=this.state;return e?(0,t.jsxs)("div",{className:"mx-auto flex min-h-screen max-w-2xl flex-col justify-center space-y-4 px-4 py-10",children:[(0,t.jsxs)("div",{children:[(0,t.jsx)("h1",{className:"text-lg font-semibold",children:"Paperclip hit an error"}),(0,t.jsx)("p",{className:"mt-1 text-sm text-muted-foreground",children:"Something went wrong while running the app. Reloading usually fixes this."})]}),(0,t.jsx)("pre",{className:"overflow-auto rounded-md border border-destructive/30 bg-destructive/10 px-3 py-2 text-xs text-destructive whitespace-pre-wrap",children:e.message}),(0,t.jsx)("div",{children:(0,t.jsx)("button",{type:"button",className:"inline-flex items-center rounded-md border border-input bg-background px-3 py-1.5 text-sm font-medium shadow-sm hover:bg-accent hover:text-accent-foreground",onClick:r(()=>window.location.reload(),"onClick"),children:"Reload page"})})]}):this.props.children}};function ixs(){const{data:e}=te({queryKey:D.auth.session,queryFn:r(()=>Pa.getSession(),"queryFn"),retry:!1}),s=e?.sentryDsn,n=e?.sentryEnvironment??void 0;return(0,m.useEffect)(()=>{if(s)return Wht(s,n),()=>{Hht()}},[s,n]),null}r(ixs,"SentryGate");function oxs(e){let s=ag();Lce(s),pU(s,e.userId);const n=ARe(()=>{const o=ag();o!==s&&(s=o,Lce(o),pU(o,e.userId))}),a=typeof navigator<"u"&&"serviceWorker"in navigator?navigator.serviceWorker:null,i=r(o=>{const l=DEt(o.data);l&&(l.type==="navigate"?e.navigate(l.url):MEt(l.notification))},"onMessage");return a?.addEventListener("message",i),a?.startMessages(),()=>{n(),a?.removeEventListener("message",i)}}r(oxs,"startNotificationRuntime");function lxs(){const e=Gn(),s=(0,m.useRef)(e),{data:n}=te({queryKey:D.auth.session,queryFn:r(()=>Pa.getSession(),"queryFn"),retry:!1}),a=n?.user?.id??n?.session?.userId??null;return(0,m.useEffect)(()=>{s.current=e},[e]),(0,m.useEffect)(()=>{if(a)return oxs({userId:a,navigate:r(i=>s.current(i),"navigate")})},[a]),null}r(lxs,"NotificationRuntime");var $9e={get:r(e=>ke.get(`/companies/${e}/primary-agent/me`),"get"),set:r((e,s)=>ke.put(`/companies/${e}/primary-agent/me`,s),"set")};function cxs(e){const s=te({queryKey:D.auth.session,queryFn:r(()=>Pa.getSession(),"queryFn")}),n=s.data?.user?.id??s.data?.session?.userId??"local-board",a=te({queryKey:D.primaryAgent.mine(e??"__none__",n),queryFn:r(()=>$9e.get(e),"queryFn"),enabled:!!e&&s.isSuccess});return{...a,userId:n,loading:!!e&&(s.isPending||a.isPending&&!s.error),error:s.error??a.error,retry:r(()=>s.isError?s.refetch():a.refetch(),"retry")}}r(cxs,"usePrimaryAgent");function dxs({children:e}){const{selectedCompanyId:s}=fs(),n=cxs(s),a=wt(),{pushToast:i}=Zr(),o=(0,m.useRef)({companyId:s,userId:n.userId});o.current={companyId:s,userId:n.userId};const l=r(f=>D.primaryAgent.mine(f.companyId,f.userId),"keyFor"),c=r(f=>f.companyId===o.current.companyId&&f.userId===o.current.userId,"isCurrentScope"),d=te({queryKey:D.agents.list(s),queryFn:r(()=>Nt.list(s),"queryFn"),enabled:!!s}),u=we({mutationFn:r(f=>$9e.set(f.companyId,{primaryAgentId:f.agentId}),"mutationFn"),onMutate:r(async f=>{const x=l(f);await a.cancelQueries({queryKey:x});const g=a.getQueryData(x);return a.setQueryData(x,{companyId:f.companyId,userId:f.userId,primaryAgentId:f.agentId,initialized:!0}),{previous:g}},"onMutate"),onError:r((f,x,g)=>{a.setQueryData(l(x),g?.previous),c(x)&&i({title:"Couldn't change your primary agent.",body:f.message,tone:"error",action:{label:"Retry",onClick:r(()=>{c(x)&&u.mutate(x)},"onClick")}})},"onError"),onSuccess:r((f,x)=>a.setQueryData(l(x),f),"onSuccess"),onSettled:r((f,x,g)=>{a.invalidateQueries({queryKey:l(g)}),a.invalidateQueries({queryKey:D.resourceMemberships.mine(g.companyId)})},"onSettled")}),h=d.data?.find(f=>f.id===n.data?.primaryAgentId&&f.status!=="terminated")??null,p=n.error??d.error;return(0,t.jsx)(THe,{value:s?{companyId:s,primaryAgentId:h?.id??null,primaryAgent:h,loading:n.loading||d.isPending,error:p?.message,onRetry:r(()=>{n.retry(),d.refetch()},"onRetry"),pendingAgentId:u.isPending&&c(u.variables)?u.variables.agentId:null,onChange:r(f=>u.mutate({companyId:s,userId:n.userId,agentId:f}),"onChange")}:null,children:e})}r(dxs,"PrimaryAgentProvider");function uxs(e){return{id:e.key,title:e.title,status:e.status,projectId:e.projectId??null,assigneeAgentId:e.assigneeAgentId??null,lastRun:e.lastRunAt||e.lastRunStatus?{triggeredAt:e.lastRunAt??null,status:e.lastRunStatus??null}:null}}r(uxs,"managedRoutineToRow");function mxs({routines:e,agents:s=[],projects:n=[],pluginDisplayName:a=null,emptyMessage:i="No managed routines.",runningRoutineKey:o=null,statusMutationRoutineKey:l=null,reconcilingRoutineKey:c=null,resettingRoutineKey:d=null,onRunNow:u,onToggleEnabled:h,onReconcile:p,onReset:f}){const x=new Map(s.map(v=>[v.id,v])),g=new Map(n.map(v=>[v.id,{name:v.name,color:v.color}]));return e.length===0?(0,t.jsx)("div",{className:"rounded-lg border border-border px-3 py-8 text-center text-sm text-muted-foreground",children:i}):(0,t.jsx)("div",{className:"rounded-lg border border-border",children:e.map(v=>{const y=uxs(v),k=v.href??(v.routineId?`/routines/${v.routineId}`:"/routines"),w=v.missingRefs??[],N=!!(v.routineId&&v.resourceKey&&w.length===0),S=v.managedByPluginDisplayName??a,C=!!(p||f);return(0,t.jsxs)("div",{className:"last:[&_a]:border-b-0",children:[(0,t.jsx)(TLe,{routine:y,projectById:g,agentById:x,runningRoutineId:o,statusMutationRoutineId:l,href:k,configureLabel:"Configure",managedByLabel:S?`Managed by ${S}`:null,runNowButton:!0,hideArchiveAction:!0,disableRunNow:!N,disableToggle:!N,secondaryDetails:(0,t.jsxs)("span",{className:"flex flex-wrap items-center gap-x-3 gap-y-1",children:[v.resourceKey?(0,t.jsx)("span",{children:v.resourceKey}):null,v.cronExpression?(0,t.jsxs)("span",{children:["Schedule ",v.cronExpression]}):null]}),onRunNow:r(()=>u?.(v),"onRunNow"),onToggleEnabled:r(()=>h?.(v,y.status==="active"),"onToggleEnabled")}),C?(0,t.jsxs)("div",{className:"flex flex-wrap items-center justify-between gap-2 border-b border-border px-3 pb-3 text-xs text-muted-foreground last:border-b-0",onClick:r(_=>{_.preventDefault(),_.stopPropagation()},"onClick"),children:[(0,t.jsx)("span",{children:w.length?`Missing ${w.map(_=>`${_.resourceKind}:${_.resourceKey}`).join(", ")}`:"Routine defaults can be repaired."}),(0,t.jsxs)("span",{className:"flex items-center gap-2",children:[p?(0,t.jsx)($,{size:"sm",variant:"ghost",disabled:c===v.key,onClick:r(()=>p(v),"onClick"),children:c===v.key?"Reconciling...":"Reconcile"}):null,f?(0,t.jsx)($,{size:"sm",variant:"ghost",disabled:d===v.key,onClick:r(()=>f(v),"onClick"),children:d===v.key?"Resetting...":"Reset"}):null]})]}):null]},v.key)})})}r(mxs,"ManagedRoutinesList");function Lge(e){return new Set(e??[])}r(Lge,"toPathSet");function hxs({expandedPaths:e,checkedPaths:s,selectedFile:n=null,showCheckboxes:a=!1,onToggleDir:i,onSelectFile:o,...l}){return(0,m.createElement)(fw,{...l,selectedFile:n,expandedDirs:Lge(e),checkedFiles:s?Lge(s):void 0,showCheckboxes:a,onToggleDir:i??(()=>{}),onSelectFile:o??(()=>{})})}r(hxs,"PluginSdkFileTree");function pxs(e){const[s,n]=(0,m.useState)(null);return(0,m.useEffect)(()=>{let a=!1;return bd(()=>import("./MarkdownEditor-CNWCu03H.js").then(i=>i.n).then(i=>{a||n(()=>i.MarkdownEditor)}),__vite__mapDeps([44,5,7,9,14,15,33,28,31,45,30,29,21,46])),()=>{a=!0}},[]),s?(0,m.createElement)(s,e):(0,m.createElement)("textarea",{className:e.className,value:e.value,placeholder:e.placeholder,readOnly:e.readOnly,onBlur:e.onBlur,onChange:r(a=>e.onChange(a.currentTarget.value),"onChange")})}r(pxs,"PluginSdkMarkdownEditor");function fxs(e){return Object.fromEntries(Object.entries(e).filter(([,s])=>s!=null&&s!==""&&s!==!1))}r(fxs,"compactIssueFilters");function xxs({companyId:e,projectId:s=null,filters:n,viewStateKey:a="paperclip:plugin-issues-view",initialSearch:i,createIssueLabel:o,searchWithinLoadedIssues:l=!0}){const c=wt(),d=(0,m.useMemo)(()=>fxs({...n??{},projectId:n?.projectId??s??void 0}),[n,s]),u=d.originKindPrefix??null,h=d.projectId??s??null,p=(0,m.useMemo)(()=>["plugins","sdk-ui","issues-list",e??"__no-company__",d],[e,d]),{data:f}=te({queryKey:D.agents.list(e??"__no-company__"),queryFn:r(()=>Nt.list(e),"queryFn"),enabled:!!e}),{data:x}=te({queryKey:D.projects.list(e??"__no-company__",{includeArchived:!0}),queryFn:r(()=>aa.list(e,{includeArchived:!0}),"queryFn"),enabled:!!e}),g=D.liveRuns(e??"__no-company__"),v=jo({companyId:e,resourceKey:"live-runs",queryKey:g,enabled:!!e,refetchInterval:!1,leaderOnly:!0}),{data:y,dataUpdatedAt:k}=te({queryKey:g,queryFn:r(()=>ea.liveRunsForCompany(e),"queryFn"),enabled:v.enabled,refetchInterval:v.refetchInterval});wo(v,y,k);const{data:w,isLoading:N,error:S}=te({queryKey:p,queryFn:r(()=>yt.list(e,d),"queryFn"),enabled:!!e}),C=(0,m.useMemo)(()=>dg(y,w),[w,y]),_=we({mutationFn:r(({id:R,data:I})=>yt.update(R,I),"mutationFn"),onSuccess:r(()=>{e&&(c.invalidateQueries({queryKey:["plugins","sdk-ui","issues-list",e]}),c.invalidateQueries({queryKey:D.issues.list(e)}),h&&(c.invalidateQueries({queryKey:D.issues.listByProject(e,h)}),u&&c.invalidateQueries({queryKey:D.issues.listPluginOperationsByProject(e,h,u)})))},"onSuccess")});return e?(0,m.createElement)(Vx,{issues:w??[],isLoading:N,error:S,agents:f,projects:x,liveIssueIds:C,projectId:h??void 0,viewStateKey:a,initialSearch:i,createIssueLabel:o,searchWithinLoadedIssues:l,onUpdateIssue:r((R,I)=>_.mutate({id:R,data:I}),"onUpdateIssue")}):(0,m.createElement)("div",{className:"text-sm text-muted-foreground"},"Select an organization to view tasks.")}r(xxs,"PluginSdkIssuesList");function gxs({companyId:e,value:s,onChange:n,placeholder:a="Responsible",noneLabel:i="No responsible",searchPlaceholder:o="Search responsible...",emptyMessage:l="No responsible found.",includeUsers:c=!0,includeTerminatedAgents:d=!1,className:u,onConfirm:h}){const p=DW(),f=e??p.companyId??null,{data:x}=te({queryKey:D.auth.session,queryFn:r(()=>Pa.getSession(),"queryFn"),enabled:c}),g=x?.user?.id??x?.session?.userId??null,{data:v}=te({queryKey:D.agents.list(f??"__no-company__"),queryFn:r(()=>Nt.list(f),"queryFn"),enabled:!!f}),{data:y}=te({queryKey:D.access.companyUserDirectory(f??"__no-company__"),queryFn:r(()=>or.listUserDirectory(f),"queryFn"),enabled:!!f&&c}),k=(0,m.useMemo)(()=>sF(),[]),w=(0,m.useMemo)(()=>k.map(R=>R.startsWith("agent:")?R.slice(6):null).filter(R=>!!R),[k]),N=(0,m.useMemo)(()=>uj((v??[]).filter(R=>d||R.status!=="terminated"),w),[v,d,w]),S=(0,m.useMemo)(()=>[...c?uve(g):[],...c?m2(y?.users,{excludeUserIds:[g]}):[],...N.map(R=>({id:Fh({assigneeAgentId:R.id}),label:R.name,searchText:`${R.name} ${R.role} ${R.title??""}`}))],[y?.users,g,c,N]),C=Qy(s),_=C.assigneeAgentId?N.find(R=>R.id===C.assigneeAgentId):null;return(0,m.createElement)(cm,{value:s,options:S,recentOptionIds:k,placeholder:a,noneLabel:i,searchPlaceholder:o,emptyMessage:l,className:u,onConfirm:h,onChange:r(R=>{const I=Qy(R);I.assigneeAgentId&&mj(I.assigneeAgentId),I.assigneeUserId&&$_(I.assigneeUserId),n(R,I)},"onChange"),renderTriggerValue:r(R=>R?_?(0,m.createElement)(mL,null,(0,m.createElement)(TE,{icon:_.icon,className:"h-3.5 w-3.5 shrink-0 text-muted-foreground"}),(0,m.createElement)("span",{className:"truncate"},R.label)):(0,m.createElement)("span",{className:"truncate"},R.label):(0,m.createElement)("span",{className:"text-muted-foreground"},a),"renderTriggerValue"),renderOption:r(R=>{if(!R.id)return(0,m.createElement)("span",{className:"truncate"},R.label);const I=Qy(R.id),T=I.assigneeAgentId?N.find(E=>E.id===I.assigneeAgentId):null;return(0,m.createElement)(mL,null,T?(0,m.createElement)(TE,{icon:T.icon,className:"h-3.5 w-3.5 shrink-0 text-muted-foreground"}):(0,m.createElement)(gd,{className:"h-3.5 w-3.5 shrink-0 text-muted-foreground"}),(0,m.createElement)("span",{className:"truncate"},R.label))},"renderOption")})}r(gxs,"PluginSdkAssigneePicker");function bxs({companyId:e,value:s,onChange:n,placeholder:a="Project",noneLabel:i="No project",searchPlaceholder:o="Search projects...",emptyMessage:l="No projects found.",includeArchived:c=!1,className:d,onConfirm:u}){const h=DW(),p=e??h.companyId??null,{data:f}=te({queryKey:D.auth.session,queryFn:r(()=>Pa.getSession(),"queryFn")}),x=f?.user?.id??f?.session?.userId??null,{data:g}=te({queryKey:D.projects.list(p??"__no-company__",{includeArchived:c}),queryFn:r(()=>aa.list(p,{includeArchived:c}),"queryFn"),enabled:!!p}),v=(0,m.useMemo)(()=>(g??[]).filter(S=>c||!S.archivedAt),[c,g]),{orderedProjects:y}=Zj({projects:v,companyId:p,userId:x}),k=(0,m.useMemo)(()=>hj(),[]),w=(0,m.useMemo)(()=>y.map(S=>({id:S.id,label:S.name,searchText:S.description??""})),[y]),N=y.find(S=>S.id===s)??null;return(0,m.createElement)(cm,{value:s,options:w,recentOptionIds:k,placeholder:a,noneLabel:i,searchPlaceholder:o,emptyMessage:l,className:d,onConfirm:u,onChange:r(S=>{S&&Ob(S),n(S)},"onChange"),renderTriggerValue:r(S=>!S||!N?(0,m.createElement)("span",{className:"text-muted-foreground"},a):(0,m.createElement)(mL,null,(0,m.createElement)("span",{className:"h-3.5 w-3.5 shrink-0 rounded-sm",style:{backgroundColor:N.color??"#6366f1"}}),(0,m.createElement)("span",{className:"truncate"},S.label)),"renderTriggerValue"),renderOption:r(S=>{if(!S.id)return(0,m.createElement)("span",{className:"truncate"},S.label);const C=y.find(_=>_.id===S.id);return(0,m.createElement)(mL,null,(0,m.createElement)("span",{className:"h-3.5 w-3.5 shrink-0 rounded-sm",style:{backgroundColor:C?.color??"#6366f1"}}),(0,m.createElement)("span",{className:"truncate"},S.label))},"renderOption")})}r(bxs,"PluginSdkProjectPicker");function mL({children:e}){return(0,m.createElement)("span",{className:"contents"},e)}r(mL,"FragmentSafe");function vxs({label:e,status:s}){const n={ok:"border-emerald-300 bg-emerald-50 text-emerald-700",warning:"border-amber-300 bg-amber-50 text-amber-800",error:"border-red-300 bg-red-50 text-red-700",info:"border-slate-300 bg-slate-50 text-slate-700",pending:"border-slate-300 bg-slate-50 text-slate-600"}[s];return(0,m.createElement)("span",{className:`inline-flex w-fit items-center rounded-full border px-2 py-0.5 text-xs font-medium ${n}`},e)}r(vxs,"PluginSdkStatusBadge");function yxs({columns:e,rows:s,loading:n,emptyMessage:a="No rows."}){if(n)return(0,m.createElement)("div",{className:"text-sm text-muted-foreground"},"Loading...");if(!s.length)return(0,m.createElement)("div",{className:"text-sm text-muted-foreground"},a);const i=e.map(o=>o.width??"minmax(0, 1fr)").join(" ");return(0,m.createElement)("div",{className:"overflow-hidden rounded-md border"},(0,m.createElement)("div",{className:"hidden border-b bg-muted/35 px-3 py-2 text-xs font-medium uppercase tracking-wide text-muted-foreground md:grid md:[grid-template-columns:var(--plugin-grid-cols)]",style:{"--plugin-grid-cols":i}},e.map(o=>(0,m.createElement)("div",{key:o.key},o.header))),(0,m.createElement)("div",{className:"divide-y"},s.map((o,l)=>(0,m.createElement)("div",{key:String(o.id??l),className:"grid gap-2 px-3 py-3 md:items-center md:[grid-template-columns:var(--plugin-grid-cols)]",style:{"--plugin-grid-cols":i}},e.map(c=>(0,m.createElement)("div",{key:c.key,className:"min-w-0 text-sm"},(0,m.createElement)("div",{className:"mb-1 text-[11px] font-medium uppercase tracking-wide text-muted-foreground md:hidden"},c.header),c.render?c.render(o[c.key],o):String(o[c.key]??"")))))))}r(yxs,"PluginSdkDataTable");function jxs({pairs:e}){return(0,m.createElement)("dl",{className:"grid gap-x-4 gap-y-1 text-sm sm:grid-cols-[max-content_minmax(0,1fr)]"},e.flatMap(s=>[(0,m.createElement)("dt",{key:`${s.label}:label`,className:"text-muted-foreground"},s.label),(0,m.createElement)("dd",{key:`${s.label}:value`,className:"min-w-0"},s.value)]))}r(jxs,"PluginSdkKeyValueList");function wxs({label:e,value:s,unit:n}){return(0,m.createElement)("div",{className:"rounded-md border bg-card p-3"},(0,m.createElement)("div",{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground"},e),(0,m.createElement)("div",{className:"mt-1 text-lg font-semibold"},`${s}${n??""}`))}r(wxs,"PluginSdkMetricCard");function kxs({data:e}){return(0,m.createElement)("pre",{className:"max-h-80 overflow-auto rounded-md border bg-muted/30 p-2 text-xs"},JSON.stringify(e,null,2))}r(kxs,"PluginSdkJsonTree");function Nxs({label:e="Loading"}){return(0,m.createElement)("span",{className:"inline-block h-3.5 w-3.5 animate-spin rounded-full border-2 border-muted-foreground/30 border-t-foreground align-middle",role:"status","aria-label":e})}r(Nxs,"PluginSdkSpinner");var Sxs=class extends m.Component{static{r(this,"PluginSdkErrorBoundary")}state={hasError:!1};static getDerivedStateFromError(){return{hasError:!0}}render(){return this.state.hasError?this.props.fallback??(0,m.createElement)("div",{className:"rounded-md border border-destructive/30 p-3 text-sm text-destructive"},"Plugin UI failed to render."):this.props.children}};function Cxs(e,s){globalThis.__paperclipPluginBridge__={react:e,reactJsxRuntime:t,reactDom:s,sdkUi:{usePluginData:RVe,usePluginAction:EVe,useHostContext:DW,useHostLocation:MVe,useHostNavigation:LVe,usePluginStream:DVe,usePluginToast:PVe,copyTextToClipboard:wa,MarkdownBlock:r(({content:n,className:a,enableWikiLinks:i,wikiLinkRoot:o,resolveWikiLinkHref:l})=>(0,m.createElement)(An,{className:a,softBreaks:!1,enableWikiLinks:i,wikiLinkRoot:o,resolveWikiLinkHref:l,children:n}),"MarkdownBlock"),MetricCard:wxs,StatusBadge:vxs,DataTable:yxs,KeyValueList:jxs,JsonTree:kxs,Spinner:Nxs,ErrorBoundary:Sxs,MarkdownEditor:pxs,FileTree:hxs,IssuesList:xxs,AssigneePicker:gxs,ProjectPicker:bxs,ManagedRoutinesList:mxs}}}r(Cxs,"initPluginBridge");var _xs=1e4;function Axs(e=_xs){if(typeof performance>"u"||typeof performance.clearMeasures!="function")return()=>{};const n=setInterval(r(()=>{globalThis.__paperclipKeepPerfMeasures||performance.clearMeasures()},"reap"),e);return()=>clearInterval(n)}r(Axs,"startPerfMeasureReaper");var Ixs=Fj((e=>{function s(F,q){var z=F.length;F.push(q);e:for(;0<z;){var K=z-1>>>1,U=F[K];if(0<i(U,q))F[K]=q,F[z]=U,z=K;else break e}}r(s,"push");function n(F){return F.length===0?null:F[0]}r(n,"peek");function a(F){if(F.length===0)return null;var q=F[0],z=F.pop();if(z!==q){F[0]=z;e:for(var K=0,U=F.length,V=U>>>1;K<V;){var ne=2*(K+1)-1,Z=F[ne],ie=ne+1,J=F[ie];if(0>i(Z,z))ie<U&&0>i(J,Z)?(F[K]=J,F[ie]=z,K=ie):(F[K]=Z,F[ne]=z,K=ne);else if(ie<U&&0>i(J,z))F[K]=J,F[ie]=z,K=ie;else break e}}return q}r(a,"pop");function i(F,q){var z=F.sortIndex-q.sortIndex;return z!==0?z:F.id-q.id}if(r(i,"compare"),e.unstable_now=void 0,typeof performance=="object"&&typeof performance.now=="function"){var o=performance;e.unstable_now=function(){return o.now()}}else{var l=Date,c=l.now();e.unstable_now=function(){return l.now()-c}}var d=[],u=[],h=1,p=null,f=3,x=!1,g=!1,v=!1,y=!1,k=typeof setTimeout=="function"?setTimeout:null,w=typeof clearTimeout=="function"?clearTimeout:null,N=typeof setImmediate<"u"?setImmediate:null;function S(F){for(var q=n(u);q!==null;){if(q.callback===null)a(u);else if(q.startTime<=F)a(u),q.sortIndex=q.expirationTime,s(d,q);else break;q=n(u)}}r(S,"advanceTimers");function C(F){if(v=!1,S(F),!g)if(n(d)!==null)g=!0,_||(_=!0,O());else{var q=n(u);q!==null&&L(C,q.startTime-F)}}r(C,"handleTimeout");var _=!1,R=-1,I=5,T=-1;function E(){return y?!0:!(e.unstable_now()-T<I)}r(E,"shouldYieldToHost");function P(){if(y=!1,_){var F=e.unstable_now();T=F;var q=!0;try{e:{g=!1,v&&(v=!1,w(R),R=-1),x=!0;var z=f;try{t:{for(S(F),p=n(d);p!==null&&!(p.expirationTime>F&&E());){var K=p.callback;if(typeof K=="function"){p.callback=null,f=p.priorityLevel;var U=K(p.expirationTime<=F);if(F=e.unstable_now(),typeof U=="function"){p.callback=U,S(F),q=!0;break t}p===n(d)&&a(d),S(F)}else a(d);p=n(d)}if(p!==null)q=!0;else{var V=n(u);V!==null&&L(C,V.startTime-F),q=!1}}break e}finally{p=null,f=z,x=!1}q=void 0}}finally{q?O():_=!1}}}r(P,"performWorkUntilDeadline");var O;if(typeof N=="function")O=r(function(){N(P)},"schedulePerformWorkUntilDeadline");else if(typeof MessageChannel<"u"){var M=new MessageChannel,Q=M.port2;M.port1.onmessage=P,O=r(function(){Q.postMessage(null)},"schedulePerformWorkUntilDeadline")}else O=r(function(){k(P,0)},"schedulePerformWorkUntilDeadline");function L(F,q){R=k(function(){F(e.unstable_now())},q)}r(L,"requestHostTimeout"),e.unstable_IdlePriority=5,e.unstable_ImmediatePriority=1,e.unstable_LowPriority=4,e.unstable_NormalPriority=3,e.unstable_Profiling=null,e.unstable_UserBlockingPriority=2,e.unstable_cancelCallback=function(F){F.callback=null},e.unstable_forceFrameRate=function(F){0>F||125<F||(I=0<F?Math.floor(1e3/F):5)},e.unstable_getCurrentPriorityLevel=function(){return f},e.unstable_next=function(F){switch(f){case 1:case 2:case 3:var q=3;break;default:q=f}var z=f;f=q;try{return F()}finally{f=z}},e.unstable_requestPaint=function(){y=!0},e.unstable_runWithPriority=function(F,q){switch(F){case 1:case 2:case 3:case 4:case 5:break;default:F=3}var z=f;f=F;try{return q()}finally{f=z}},e.unstable_scheduleCallback=function(F,q,z){var K=e.unstable_now();switch(typeof z=="object"&&z!==null?(z=z.delay,z=typeof z=="number"&&0<z?K+z:K):z=K,F){case 1:var U=-1;break;case 2:U=250;break;case 5:U=1073741823;break;case 4:U=1e4;break;default:U=5e3}return U=z+U,F={id:h++,callback:q,priorityLevel:F,startTime:z,expirationTime:U,sortIndex:-1},z>K?(F.sortIndex=z,s(u,F),n(d)===null&&F===n(u)&&(v?(w(R),R=-1):v=!0,L(C,z-K))):(F.sortIndex=U,s(d,F),g||x||(g=!0,_||(_=!0,O()))),F},e.unstable_shouldYield=E,e.unstable_wrapCallback=function(F){var q=f;return function(){var z=f;f=q;try{return F.apply(this,arguments)}finally{f=z}}}})),Txs=Fj(((e,s)=>{s.exports=Ixs()})),Rxs=Fj((e=>{var s=Txs(),n=CQ(),a=Vge();function i(b){var j="https://react.dev/errors/"+b;if(1<arguments.length){j+="?args[]="+encodeURIComponent(arguments[1]);for(var A=2;A<arguments.length;A++)j+="&args[]="+encodeURIComponent(arguments[A])}return"Minified React error #"+b+"; visit "+j+" for the full message or use the non-minified dev environment for full errors and additional helpful warnings."}r(i,"formatProdErrorMessage");function o(b){return!(!b||b.nodeType!==1&&b.nodeType!==9&&b.nodeType!==11)}r(o,"isValidContainer");function l(b){var j=b,A=b;if(b.alternate)for(;j.return;)j=j.return;else{b=j;do j=b,(j.flags&4098)!==0&&(A=j.return),b=j.return;while(b)}return j.tag===3?A:null}r(l,"getNearestMountedFiber");function c(b){if(b.tag===13){var j=b.memoizedState;if(j===null&&(b=b.alternate,b!==null&&(j=b.memoizedState)),j!==null)return j.dehydrated}return null}r(c,"getSuspenseInstanceFromFiber");function d(b){if(b.tag===31){var j=b.memoizedState;if(j===null&&(b=b.alternate,b!==null&&(j=b.memoizedState)),j!==null)return j.dehydrated}return null}r(d,"getActivityInstanceFromFiber");function u(b){if(l(b)!==b)throw Error(i(188))}r(u,"assertIsMounted");function h(b){var j=b.alternate;if(!j){if(j=l(b),j===null)throw Error(i(188));return j!==b?null:b}for(var A=b,B=j;;){var H=A.return;if(H===null)break;var ee=H.alternate;if(ee===null){if(B=H.return,B!==null){A=B;continue}break}if(H.child===ee.child){for(ee=H.child;ee;){if(ee===A)return u(H),b;if(ee===B)return u(H),j;ee=ee.sibling}throw Error(i(188))}if(A.return!==B.return)A=H,B=ee;else{for(var Ne=!1,He=H.child;He;){if(He===A){Ne=!0,A=H,B=ee;break}if(He===B){Ne=!0,B=H,A=ee;break}He=He.sibling}if(!Ne){for(He=ee.child;He;){if(He===A){Ne=!0,A=ee,B=H;break}if(He===B){Ne=!0,B=ee,A=H;break}He=He.sibling}if(!Ne)throw Error(i(189))}}if(A.alternate!==B)throw Error(i(190))}if(A.tag!==3)throw Error(i(188));return A.stateNode.current===A?b:j}r(h,"findCurrentFiberUsingSlowPath");function p(b){var j=b.tag;if(j===5||j===26||j===27||j===6)return b;for(b=b.child;b!==null;){if(j=p(b),j!==null)return j;b=b.sibling}return null}r(p,"findCurrentHostFiberImpl");var f=Object.assign,x=Symbol.for("react.element"),g=Symbol.for("react.transitional.element"),v=Symbol.for("react.portal"),y=Symbol.for("react.fragment"),k=Symbol.for("react.strict_mode"),w=Symbol.for("react.profiler"),N=Symbol.for("react.consumer"),S=Symbol.for("react.context"),C=Symbol.for("react.forward_ref"),_=Symbol.for("react.suspense"),R=Symbol.for("react.suspense_list"),I=Symbol.for("react.memo"),T=Symbol.for("react.lazy"),E=Symbol.for("react.activity"),P=Symbol.for("react.memo_cache_sentinel"),O=Symbol.iterator;function M(b){return b===null||typeof b!="object"?null:(b=O&&b[O]||b["@@iterator"],typeof b=="function"?b:null)}r(M,"getIteratorFn");var Q=Symbol.for("react.client.reference");function L(b){if(b==null)return null;if(typeof b=="function")return b.$$typeof===Q?null:b.displayName||b.name||null;if(typeof b=="string")return b;switch(b){case y:return"Fragment";case w:return"Profiler";case k:return"StrictMode";case _:return"Suspense";case R:return"SuspenseList";case E:return"Activity"}if(typeof b=="object")switch(b.$$typeof){case v:return"Portal";case S:return b.displayName||"Context";case N:return(b._context.displayName||"Context")+".Consumer";case C:var j=b.render;return b=b.displayName,b||(b=j.displayName||j.name||"",b=b!==""?"ForwardRef("+b+")":"ForwardRef"),b;case I:return j=b.displayName||null,j!==null?j:L(b.type)||"Memo";case T:j=b._payload,b=b._init;try{return L(b(j))}catch{}}return null}r(L,"getComponentNameFromType");var F=Array.isArray,q=n.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE,z=a.__DOM_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE,K={pending:!1,data:null,method:null,action:null},U=[],V=-1;function ne(b){return{current:b}}r(ne,"createCursor");function Z(b){0>V||(b.current=U[V],U[V]=null,V--)}r(Z,"pop");function ie(b,j){V++,U[V]=b.current,b.current=j}r(ie,"push");var J=ne(null),ae=ne(null),oe=ne(null),G=ne(null);function X(b,j){switch(ie(oe,j),ie(ae,b),ie(J,null),j.nodeType){case 9:case 11:b=(b=j.documentElement)&&(b=b.namespaceURI)?HX(b):0;break;default:if(b=j.tagName,j=j.namespaceURI)j=HX(j),b=VX(j,b);else switch(b){case"svg":b=1;break;case"math":b=2;break;default:b=0}}Z(J),ie(J,b)}r(X,"pushHostContainer");function Y(){Z(J),Z(ae),Z(oe)}r(Y,"popHostContainer");function re(b){b.memoizedState!==null&&ie(G,b);var j=J.current,A=VX(j,b.type);j!==A&&(ie(ae,b),ie(J,A))}r(re,"pushHostContext");function se(b){ae.current===b&&(Z(J),Z(ae)),G.current===b&&(Z(G),xS._currentValue=K)}r(se,"popHostContext");var ce,pe;function fe(b){if(ce===void 0)try{throw Error()}catch(A){var j=A.stack.trim().match(/\n( *(at )?)/);ce=j&&j[1]||"",pe=-1<A.stack.indexOf(`
706
+ `)}q!==k&&(n.textContent=q,k=q)}r(R,"step");function I(){const M=d>0&&u>0;if(a.matches){o&&(o=!1,s.current!==null&&cancelAnimationFrame(s.current),s.current=null),M&&S();return}if(!i||!M){o&&(o=!1,s.current!==null&&cancelAnimationFrame(s.current),s.current=null);return}o||(o=!0,l=0,s.current=requestAnimationFrame(R))}r(I,"syncLoop");const T=new ResizeObserver(()=>{const M=gge(n);h=M.w,p=M.h,N(),I()});T.observe(n);const E=r(()=>{i=document.visibilityState!=="hidden",I()},"onVisibilityChange");document.addEventListener("visibilitychange",E);const P=r(()=>{I()},"onMotionChange");a.addEventListener("change",P);const O=gge(n);return h=O.w,p=O.h,N(),I(),()=>{o=!1,s.current!==null&&cancelAnimationFrame(s.current),T.disconnect(),document.removeEventListener("visibilitychange",E),a.removeEventListener("change",P)}},[]),(0,t.jsx)("pre",{ref:e,className:"w-full h-full m-0 p-0 overflow-hidden text-muted-foreground/60 select-none leading-none",style:{fontSize:"var(--text-micro)",fontFamily:"monospace"},"aria-hidden":"true"})}r(kfs,"AsciiArtAnimation");function Nfs({decorative:e=!1,title:s="Paperclip",className:n,...a}){return(0,t.jsxs)("svg",{...a,className:n,viewBox:"22.5 22.5 121 27",fill:"currentColor",role:e?void 0:"img","aria-hidden":e?!0:void 0,"aria-label":e?void 0:s,focusable:"false",children:[(0,t.jsx)("path",{d:"M131.15 48.4902V31.9902H133.922V33.9775H134.094C134.237 33.6911 134.441 33.3831 134.706 33.0537C134.971 32.7171 135.329 32.4307 135.78 32.1943C136.239 31.958 136.822 31.8398 137.531 31.8398C138.455 31.8398 139.289 32.0762 140.034 32.5488C140.779 33.0215 141.37 33.7161 141.807 34.6328C142.251 35.5495 142.473 36.6774 142.473 38.0166C142.473 39.3343 142.258 40.4551 141.828 41.3789C141.398 42.3027 140.808 43.0081 140.056 43.4951C139.311 43.9749 138.466 44.2148 137.521 44.2148C136.84 44.2148 136.271 44.1003 135.812 43.8711C135.361 43.6348 134.996 43.3555 134.717 43.0332C134.445 42.7038 134.237 42.3923 134.094 42.0986H133.976V48.4902H131.15ZM136.747 41.8945C137.37 41.8945 137.889 41.7262 138.305 41.3896C138.727 41.0531 139.046 40.5911 139.261 40.0039C139.476 39.4167 139.583 38.7507 139.583 38.0059C139.583 37.2611 139.476 36.5986 139.261 36.0186C139.046 35.4385 138.731 34.9837 138.315 34.6543C137.9 34.3249 137.377 34.1602 136.747 34.1602C136.138 34.1602 135.623 34.3177 135.2 34.6328C134.785 34.9479 134.466 35.3955 134.244 35.9756C134.029 36.5485 133.922 37.2253 133.922 38.0059C133.922 38.7793 134.029 39.4596 134.244 40.0469C134.466 40.627 134.788 41.0817 135.211 41.4111C135.633 41.7334 136.146 41.8945 136.747 41.8945Z"}),(0,t.jsx)("path",{d:"M126.451 44V31.9902H129.276V44H126.451ZM127.869 30.3037C127.417 30.3037 127.031 30.1533 126.708 29.8525C126.386 29.5518 126.225 29.1901 126.225 28.7676C126.225 28.3379 126.386 27.9727 126.708 27.6719C127.031 27.3711 127.417 27.2207 127.869 27.2207C128.313 27.2207 128.696 27.3711 129.018 27.6719C129.34 27.9727 129.501 28.3343 129.501 28.7568C129.501 29.1865 129.34 29.5518 129.018 29.8525C128.696 30.1533 128.313 30.3037 127.869 30.3037Z"}),(0,t.jsx)("path",{d:"M124.576 27.9941V44H121.75V27.9941H124.576Z"}),(0,t.jsx)("path",{d:"M115.3 44.2363C114.104 44.2363 113.076 43.9749 112.217 43.4521C111.357 42.9222 110.699 42.1917 110.24 41.2607C109.782 40.3298 109.553 39.2591 109.553 38.0488C109.553 36.8242 109.785 35.7464 110.251 34.8154C110.716 33.8844 111.379 33.1576 112.238 32.6348C113.098 32.1048 114.111 31.8398 115.278 31.8398C116.259 31.8398 117.126 32.0189 117.878 32.377C118.63 32.735 119.228 33.2399 119.672 33.8916C120.123 34.5361 120.381 35.2917 120.445 36.1582H117.738C117.667 35.7715 117.527 35.4242 117.319 35.1162C117.112 34.8083 116.84 34.5648 116.503 34.3857C116.174 34.2067 115.78 34.1172 115.321 34.1172C114.741 34.1172 114.233 34.2747 113.796 34.5898C113.366 34.8978 113.03 35.3418 112.786 35.9219C112.543 36.502 112.421 37.1966 112.421 38.0059C112.421 38.8223 112.539 39.5277 112.775 40.1221C113.012 40.7093 113.348 41.1641 113.785 41.4863C114.222 41.8014 114.734 41.959 115.321 41.959C115.944 41.959 116.471 41.7764 116.9 41.4111C117.337 41.0459 117.617 40.541 117.738 39.8965H120.445C120.381 40.7487 120.13 41.5007 119.693 42.1523C119.257 42.804 118.666 43.3161 117.921 43.6885C117.176 44.0537 116.302 44.2363 115.3 44.2363Z"}),(0,t.jsx)("path",{d:"M102.876 44V31.9902H105.615V34.0098H105.744C105.959 33.3079 106.335 32.7708 106.872 32.3984C107.409 32.0189 108.021 31.8291 108.709 31.8291C108.859 31.8291 109.031 31.8363 109.225 31.8506C109.425 31.8649 109.59 31.8828 109.719 31.9043V34.5039C109.597 34.4609 109.407 34.4251 109.149 34.3965C108.892 34.3678 108.645 34.3535 108.408 34.3535C107.885 34.3535 107.42 34.4645 107.012 34.6865C106.604 34.9085 106.281 35.2129 106.045 35.5996C105.816 35.9863 105.701 36.4375 105.701 36.9531V44H102.876Z"}),(0,t.jsx)("path",{d:"M96.2319 44.2363C95.0288 44.2363 93.9904 43.9857 93.1167 43.4844C92.243 42.9759 91.5698 42.2598 91.0972 41.3359C90.6317 40.4121 90.3989 39.3236 90.3989 38.0703C90.3989 36.8314 90.6317 35.7464 91.0972 34.8154C91.5627 33.8773 92.2179 33.1468 93.063 32.624C93.908 32.1012 94.9035 31.8398 96.0493 31.8398C96.7869 31.8398 97.4852 31.958 98.144 32.1943C98.8101 32.4307 99.3973 32.7959 99.9058 33.29C100.421 33.7842 100.826 34.4144 101.12 35.1807C101.413 35.9398 101.56 36.8457 101.56 37.8984V38.7793H91.7202V36.8779H100.153L98.8315 37.4365C98.8315 36.7562 98.7277 36.1654 98.52 35.6641C98.3123 35.1556 98.0044 34.7581 97.5962 34.4717C97.188 34.1852 96.6795 34.042 96.0708 34.042C95.4621 34.042 94.9429 34.1852 94.5132 34.4717C94.0835 34.7581 93.7576 35.1449 93.5356 35.6318C93.3136 36.1117 93.2026 36.6488 93.2026 37.2432V38.5645C93.2026 39.2949 93.328 39.9215 93.5786 40.4443C93.8364 40.96 94.1945 41.3538 94.6528 41.626C95.1183 41.8981 95.659 42.0342 96.2749 42.0342C96.6759 42.0342 97.0412 41.9769 97.3706 41.8623C97.7072 41.7477 97.9937 41.5758 98.23 41.3467C98.4735 41.1104 98.6597 40.8203 98.7886 40.4766L101.431 40.7881C101.259 41.4827 100.941 42.0915 100.475 42.6143C100.017 43.1299 99.4259 43.5309 98.7026 43.8174C97.9865 44.0967 97.1629 44.2363 96.2319 44.2363Z"}),(0,t.jsx)("path",{d:"M78.2437 48.4902V31.9902H81.0151V33.9775H81.187C81.3302 33.6911 81.5343 33.3831 81.7993 33.0537C82.0643 32.7171 82.4224 32.4307 82.8735 32.1943C83.3319 31.958 83.9155 31.8398 84.6245 31.8398C85.5483 31.8398 86.3826 32.0762 87.1274 32.5488C87.8722 33.0215 88.4631 33.7161 88.8999 34.6328C89.3439 35.5495 89.5659 36.6774 89.5659 38.0166C89.5659 39.3343 89.3511 40.4551 88.9214 41.3789C88.4917 42.3027 87.9009 43.0081 87.1489 43.4951C86.4041 43.9749 85.5591 44.2148 84.6138 44.2148C83.9334 44.2148 83.3641 44.1003 82.9058 43.8711C82.4546 43.6348 82.0894 43.3555 81.8101 43.0332C81.5379 42.7038 81.3302 42.3923 81.187 42.0986H81.0688V48.4902H78.2437ZM83.8403 41.8945C84.4634 41.8945 84.9826 41.7262 85.3979 41.3896C85.8205 41.0531 86.1392 40.5911 86.354 40.0039C86.5688 39.4167 86.6763 38.7507 86.6763 38.0059C86.6763 37.2611 86.5688 36.5986 86.354 36.0186C86.1392 35.4385 85.8241 34.9837 85.4087 34.6543C84.9933 34.3249 84.4705 34.1602 83.8403 34.1602C83.2316 34.1602 82.716 34.3177 82.2935 34.6328C81.8781 34.9479 81.5594 35.3955 81.3374 35.9756C81.1226 36.5485 81.0151 37.2253 81.0151 38.0059C81.0151 38.7793 81.1226 39.4596 81.3374 40.0469C81.5594 40.627 81.8817 41.0817 82.3042 41.4111C82.7267 41.7334 83.2388 41.8945 83.8403 41.8945Z"}),(0,t.jsx)("path",{d:"M70.042 44.2471C69.2757 44.2471 68.5882 44.111 67.9795 43.8389C67.3708 43.5596 66.891 43.1514 66.54 42.6143C66.1891 42.0771 66.0137 41.4147 66.0137 40.627C66.0137 39.9538 66.139 39.3952 66.3896 38.9512C66.6403 38.5072 66.9805 38.1527 67.4102 37.8877C67.847 37.6227 68.3376 37.4222 68.8818 37.2861C69.4261 37.1429 69.9883 37.0426 70.5684 36.9854C71.2773 36.9066 71.8503 36.8385 72.2871 36.7812C72.724 36.724 73.0391 36.6309 73.2324 36.502C73.4329 36.373 73.5332 36.1725 73.5332 35.9004V35.8467C73.5332 35.2666 73.3613 34.8154 73.0176 34.4932C72.6738 34.1709 72.1725 34.0098 71.5137 34.0098C70.819 34.0098 70.2676 34.1602 69.8594 34.4609C69.4583 34.7617 69.1862 35.1162 69.043 35.5244L66.4111 35.1484C66.6188 34.418 66.9626 33.8092 67.4424 33.3223C67.9222 32.8281 68.5059 32.4593 69.1934 32.2158C69.888 31.9652 70.6543 31.8398 71.4922 31.8398C72.0651 31.8398 72.638 31.9079 73.2109 32.0439C73.7839 32.1729 74.3102 32.3949 74.79 32.71C75.2699 33.0251 75.653 33.4476 75.9395 33.9775C76.2259 34.5075 76.3691 35.1699 76.3691 35.9648V44H73.6514V42.3457H73.5654C73.3936 42.6751 73.1501 42.9867 72.835 43.2803C72.527 43.5667 72.1403 43.7995 71.6748 43.9785C71.2165 44.1576 70.6722 44.2471 70.042 44.2471ZM70.7617 42.1631C71.3346 42.1631 71.8288 42.0521 72.2441 41.8301C72.6595 41.6009 72.9818 41.3001 73.2109 40.9277C73.4401 40.5482 73.5547 40.1364 73.5547 39.6924V38.2852C73.4616 38.3568 73.3112 38.4248 73.1035 38.4893C72.8958 38.5465 72.6595 38.6003 72.3945 38.6504C72.1296 38.7005 71.8682 38.7435 71.6104 38.7793C71.3597 38.8151 71.1413 38.8438 70.9551 38.8652C70.5326 38.9225 70.153 39.0192 69.8164 39.1553C69.487 39.2842 69.2256 39.4632 69.0322 39.6924C68.8389 39.9215 68.7422 40.2188 68.7422 40.584C68.7422 41.1068 68.932 41.5007 69.3115 41.7656C69.6911 42.0306 70.1745 42.1631 70.7617 42.1631Z"}),(0,t.jsx)("path",{d:"M53.7939 44V27.9941H59.7988C61.0306 27.9941 62.0618 28.2233 62.8926 28.6816C63.7305 29.14 64.3643 29.7702 64.7939 30.5723C65.2236 31.3743 65.4385 32.2839 65.4385 33.3008C65.4385 34.3249 65.2201 35.238 64.7832 36.04C64.3535 36.835 63.7161 37.4616 62.8711 37.9199C62.026 38.3711 60.9876 38.5967 59.7559 38.5967H55.7812V36.2119H59.3584C60.0817 36.2119 60.6725 36.0902 61.1309 35.8467C61.5964 35.596 61.9365 35.2523 62.1514 34.8154C62.3734 34.3714 62.4844 33.8665 62.4844 33.3008C62.4844 32.7279 62.3734 32.2266 62.1514 31.7969C61.9365 31.36 61.5964 31.0234 61.1309 30.7871C60.6725 30.5436 60.0781 30.4219 59.3477 30.4219H56.6943V44H53.7939Z"}),(0,t.jsx)("path",{d:"M46.2611 33.6556L34.7307 44.6408C32.7445 46.5331 29.5205 46.5323 27.5303 44.6361C25.5404 42.74 25.54 39.669 27.5261 37.7768L39.0565 26.7916C40.2474 25.657 42.1811 25.6567 43.3752 26.7943C44.5693 27.9319 44.5689 29.7742 43.378 30.9088L31.849 41.8954C31.4528 42.2728 30.8077 42.273 30.4092 41.8933C30.011 41.5136 30.0117 40.8996 30.4078 40.5223L41.9382 29.5371C42.336 29.1581 42.336 28.5437 41.9382 28.1647C41.5404 27.786 40.8954 27.7858 40.4977 28.1647L28.9673 39.1499C27.7742 40.2866 27.7764 42.1295 28.9687 43.2657C30.1613 44.402 32.0963 44.4046 33.2895 43.2678L44.8192 32.2805C46.8068 30.3865 46.8038 27.3159 44.8157 25.4219C42.8275 23.5277 39.6039 23.5253 37.616 25.4192L26.0856 36.4044C23.3024 39.056 23.3058 43.3558 26.0898 46.0085C28.8741 48.6612 33.388 48.6649 36.1712 46.0132L47.7017 35.028C48.0994 34.649 48.0994 34.0346 47.7017 33.6556C47.3039 33.2766 46.6589 33.2766 46.2611 33.6556Z"})]})}r(Nfs,"PaperclipLockup");function Sfs(){const e=wt(),s=Gn(),[n]=hi(),[a,i]=(0,m.useState)("sign_in"),[o,l]=(0,m.useState)(""),[c,d]=(0,m.useState)(""),[u,h]=(0,m.useState)(""),[p,f]=(0,m.useState)(null),x="auth-error",g=(0,m.useMemo)(()=>M5e(n.get("next")||yfs()||"/"),[n]),v=te({queryKey:D.health,queryFn:r(()=>Lu.get(),"queryFn"),retry:!1}),{data:y,isLoading:k,error:w}=te({queryKey:D.auth.session,queryFn:r(()=>Pa.getSession(),"queryFn"),retry:!1});(0,m.useEffect)(()=>{y&&(mG(),s(g,{replace:!0}))},[y,s,g]);const N=we({mutationFn:r(async()=>{if(a==="sign_in"){await Pa.signInEmail({email:c.trim(),password:u});return}await Pa.signUpEmail({name:o.trim(),email:c.trim(),password:u})},"mutationFn"),onSuccess:r(async()=>{f(null),await e.invalidateQueries({queryKey:D.auth.session}),await e.invalidateQueries({queryKey:D.health}),await e.resetQueries({queryKey:D.companies.all}),s(g,{replace:!0})},"onSuccess"),onError:r(C=>{f(C instanceof Error?C.message:"Authentication failed")},"onError")}),S=c.trim().length>0&&u.trim().length>0&&(a==="sign_in"||o.trim().length>0&&u.trim().length>=8);return v.isLoading||k||y?(0,t.jsx)("div",{className:"fixed inset-0 flex items-center justify-center",children:(0,t.jsx)(ch,{className:"min-h-0"})}):v.error||w?(0,t.jsx)("p",{role:"alert",className:"p-6 text-sm text-destructive",children:"Unable to check sign-in. Refresh and try again."}):v.data?.cloud?(0,t.jsx)(hG,{cloud:v.data.cloud,returnTo:g}):(0,t.jsxs)("div",{className:"fixed inset-0 flex bg-background",children:[(0,t.jsx)("div",{className:"absolute top-4 right-4 z-10",children:(0,t.jsx)(Ek,{})}),(0,t.jsx)("div",{className:"w-full md:w-1/2 flex flex-col overflow-y-auto",children:(0,t.jsxs)("div",{className:"w-full max-w-md mx-auto my-auto px-8 py-12",children:[(0,t.jsx)("div",{className:"mb-8",children:(0,t.jsx)(Nfs,{className:"h-5 w-auto"})}),(0,t.jsx)("h1",{className:"text-xl font-semibold",children:a==="sign_in"?"Sign in to Paperclip":"Create your Paperclip account"}),(0,t.jsx)("p",{className:"mt-1 text-sm text-muted-foreground",children:a==="sign_in"?"Use your email and password to access this instance.":"Create an account for this instance. Email confirmation is not required in v1."}),(0,t.jsxs)("form",{className:"mt-6 space-y-4",method:"post",action:a==="sign_up"?"/api/auth/sign-up/email":"/api/auth/sign-in/email",onSubmit:r(C=>{if(C.preventDefault(),!N.isPending){if(!S){f("Please fill in all required fields.");return}N.mutate()}},"onSubmit"),children:[a==="sign_up"&&(0,t.jsxs)("div",{children:[(0,t.jsx)("label",{htmlFor:"name",className:"text-xs text-muted-foreground mb-1 block",children:"Name"}),(0,t.jsx)("input",{id:"name",name:"name",className:"w-full rounded-md border border-border bg-transparent px-3 py-2 text-sm outline-none focus:ring-1 focus:ring-ring placeholder:text-muted-foreground/50",value:o,onChange:r(C=>l(C.target.value),"onChange"),autoComplete:"name",required:!0,"aria-required":"true","aria-invalid":p?!0:void 0,"aria-describedby":p?x:void 0,autoFocus:!0})]}),(0,t.jsxs)("div",{children:[(0,t.jsx)("label",{htmlFor:"email",className:"text-xs text-muted-foreground mb-1 block",children:"Email"}),(0,t.jsx)("input",{id:"email",name:"email",className:"w-full rounded-md border border-border bg-transparent px-3 py-2 text-sm outline-none focus:ring-1 focus:ring-ring placeholder:text-muted-foreground/50",type:"email",value:c,onChange:r(C=>d(C.target.value),"onChange"),autoComplete:"username",required:!0,"aria-required":"true","aria-invalid":p?!0:void 0,"aria-describedby":p?x:void 0,autoFocus:a==="sign_in"})]}),(0,t.jsxs)("div",{children:[(0,t.jsx)("label",{htmlFor:"password",className:"text-xs text-muted-foreground mb-1 block",children:"Password"}),(0,t.jsx)("input",{id:"password",name:"password",className:"w-full rounded-md border border-border bg-transparent px-3 py-2 text-sm outline-none focus:ring-1 focus:ring-ring placeholder:text-muted-foreground/50",type:"password",value:u,onChange:r(C=>h(C.target.value),"onChange"),autoComplete:a==="sign_in"?"current-password":"new-password",required:!0,"aria-required":"true","aria-invalid":p?!0:void 0,"aria-describedby":p?x:void 0})]}),p&&(0,t.jsx)("p",{id:x,role:"alert",className:"text-xs text-destructive",children:p}),(0,t.jsx)($,{type:"submit",disabled:N.isPending,"aria-disabled":!S||N.isPending,className:`w-full ${!S&&!N.isPending?"opacity-50":""}`,children:N.isPending?"Working…":a==="sign_in"?"Sign In":"Create Account"})]}),(0,t.jsxs)("div",{className:"mt-5 text-sm text-muted-foreground",children:[a==="sign_in"?"Need an account?":"Already have an account?"," ",(0,t.jsx)("button",{type:"button",className:"font-medium text-foreground underline underline-offset-2",onClick:r(()=>{f(null),i(a==="sign_in"?"sign_up":"sign_in")},"onClick"),children:a==="sign_in"?"Create one":"Sign in"})]})]})}),(0,t.jsx)("div",{className:"hidden md:block w-1/2 overflow-hidden",children:(0,t.jsx)(kfs,{})})]})}r(Sfs,"AuthPage");function Cfs(){const e=wt(),s=xa(),[n]=hi(),a=(s.token??"").trim(),i=(n.get("code")??"").trim(),o=(0,m.useMemo)(()=>`/board-claim/${encodeURIComponent(a)}${i?`?code=${encodeURIComponent(i)}`:""}`,[a,i]),l=te({queryKey:D.auth.session,queryFn:r(()=>Pa.getSession(),"queryFn"),retry:!1}),c=te({queryKey:["board-claim",a,i],queryFn:r(()=>or.getBoardClaimStatus(a,i),"queryFn"),enabled:a.length>0&&i.length>0,retry:!1}),d=we({mutationFn:r(()=>or.claimBoard(a,i),"mutationFn"),onSuccess:r(async()=>{await e.invalidateQueries({queryKey:D.auth.session}),await e.invalidateQueries({queryKey:D.health}),await e.invalidateQueries({queryKey:D.companies.all}),await e.invalidateQueries({queryKey:D.companies.stats}),await c.refetch()},"onSuccess")});if(!a||!i)return(0,t.jsx)("div",{className:"mx-auto max-w-xl py-10 text-sm text-destructive",children:"Invalid board claim URL."});if(c.isLoading||l.isLoading)return(0,t.jsx)("div",{className:"mx-auto max-w-xl py-10 text-sm text-muted-foreground",children:"Loading claim challenge..."});if(c.error)return(0,t.jsx)("div",{className:"mx-auto max-w-xl py-10",children:(0,t.jsxs)(sn,{className:"block p-6",children:[(0,t.jsx)("h1",{className:"text-lg font-semibold",children:"Claim challenge unavailable"}),(0,t.jsx)("p",{className:"mt-2 text-sm text-muted-foreground",children:c.error instanceof Error?c.error.message:"Challenge is invalid or expired."})]})});const u=c.data;return u?u.status==="claimed"?(0,t.jsx)("div",{className:"mx-auto max-w-xl py-10",children:(0,t.jsxs)(sn,{className:"block p-6",children:[(0,t.jsx)("h1",{className:"text-lg font-semibold",children:"Board ownership claimed"}),(0,t.jsx)("p",{className:"mt-2 text-sm text-muted-foreground",children:"This instance is now linked to your authenticated user."}),(0,t.jsx)($,{asChild:!0,className:"mt-4",children:(0,t.jsx)(We,{to:"/",children:"Open board"})})]})}):l.data?(0,t.jsx)("div",{className:"mx-auto max-w-xl py-10",children:(0,t.jsxs)(sn,{className:"block p-6",children:[(0,t.jsx)("h1",{className:"text-xl font-semibold",children:"Claim Board ownership"}),(0,t.jsx)("p",{className:"mt-2 text-sm text-muted-foreground",children:"This will promote your user to instance admin and migrate organization ownership access from local trusted mode."}),d.error&&(0,t.jsx)("p",{className:"mt-3 text-sm text-destructive",children:d.error instanceof Error?d.error.message:"Failed to claim board ownership"}),(0,t.jsx)($,{className:"mt-5",onClick:r(()=>d.mutate(),"onClick"),disabled:d.isPending,children:d.isPending?"Claiming…":"Claim ownership"})]})}):(0,t.jsx)("div",{className:"mx-auto max-w-xl py-10",children:(0,t.jsxs)(sn,{className:"block p-6",children:[(0,t.jsx)("h1",{className:"text-lg font-semibold",children:"Sign in required"}),(0,t.jsx)("p",{className:"mt-2 text-sm text-muted-foreground",children:"Sign in or create an account, then return to this page to claim Board ownership."}),(0,t.jsx)($,{asChild:!0,className:"mt-4",children:(0,t.jsx)(We,{to:`/auth?next=${encodeURIComponent(o)}`,children:"Sign in / Create account"})})]})}):(0,t.jsx)("div",{className:"mx-auto max-w-xl py-10 text-sm text-destructive",children:"Claim challenge unavailable."})}r(Cfs,"BoardClaimPage");function bge({origin:e}){const[s,n]=(0,m.useState)(!1);let a;try{const i=new URL(e);i.origin==="https://claude.ai"?a="/brands/claude-color.svg":["https://chatgpt.com","https://chat.openai.com","https://openai.com"].includes(i.origin)&&(a="/brands/codex-color.svg")}catch{}return(0,t.jsxs)("div",{className:"flex items-center gap-2 text-sm text-muted-foreground",children:[a&&!s?(0,t.jsx)("img",{src:a,alt:"",className:"size-4 shrink-0 object-contain",referrerPolicy:"no-referrer",crossOrigin:"anonymous",onError:r(()=>n(!0),"onError")}):(0,t.jsx)(wm,{className:"size-4 shrink-0","aria-hidden":"true"}),(0,t.jsx)("bdi",{className:"min-w-0 break-all",children:e})]})}r(bge,"ClientOrigin");function vge({agentPairingOnly:e=!1}={}){const{id:s=""}=xa();return(0,t.jsx)(R9e,{id:s,agentPairingOnly:e},s)}r(vge,"McpConnectPage");function _fs({initialCode:e}={}){const[s,n]=(0,m.useState)(e??new URLSearchParams(window.location.search).get("user_code")??""),[a,i]=(0,m.useState)(s);return a?(0,t.jsx)(R9e,{id:a,device:!0,onEditCode:r(()=>i(""),"onEditCode")},a):(0,t.jsx)("div",{className:"mx-auto max-w-xl py-10",children:(0,t.jsxs)(sn,{className:"space-y-4 p-6",children:[(0,t.jsxs)("div",{className:"flex items-center gap-3",children:[(0,t.jsx)(kl,{className:"size-8 shrink-0"}),(0,t.jsx)("h1",{className:"min-w-0 text-xl font-semibold",children:"Connect your assistant to Paperclip"})]}),(0,t.jsxs)("form",{className:"space-y-4",onSubmit:r(o=>{o.preventDefault(),i(s.trim())},"onSubmit"),children:[(0,t.jsx)("label",{htmlFor:"device-code",className:"text-sm",children:"Enter the code shown by your assistant"}),(0,t.jsx)(dt,{id:"device-code",autoComplete:"off",value:s,onChange:r(o=>n(o.target.value),"onChange"),required:!0,maxLength:12}),(0,t.jsx)("div",{className:"flex justify-end",children:(0,t.jsx)($,{type:"submit",children:"Continue"})})]})]})})}r(_fs,"McpDevicePage");function R9e({id:e,device:s=!1,agentPairingOnly:n=!1,onEditCode:a}){const i=n?"/dot-mcp/requests":"/mcp/requests",[o,l]=(0,m.useState)(""),[c,d]=(0,m.useState)(""),[u,h]=(0,m.useState)(null),[p,f]=(0,m.useState)(""),[x,g]=(0,m.useState)(!0),[v,y]=(0,m.useState)(null),k=te({queryKey:[s?"mcp-device":n?"dot-mcp-request":"mcp-request",e],queryFn:r(()=>ke.get(s?`/mcp/device?user_code=${encodeURIComponent(e)}`:`${i}/${encodeURIComponent(e)}`),"queryFn"),retry:!1}),w=k.data;(0,m.useEffect)(()=>{if(h(null),f(""),!w?.agentConnection||s||!/^[A-Za-z0-9_-]{32}$/.test(c.trim()))return;let Q=!0;return ke.post(`${i}/${encodeURIComponent(e)}/dot-pairing/preview`,{pairingCode:c.trim()}).then(L=>{Q&&h(L)}).catch(L=>{Q&&f(L instanceof Error?L.message:"Unable to verify this pairing code.")}),()=>{Q=!1}},[e,s,i,w?.agentConnection,c]);const N=w?.requestedCompanyId??(o||w?.companies[0]?.id||"");(0,m.useEffect)(()=>{!o&&!w?.requestedCompanyId&&w?.companies[0]&&l(w.companies[0].id)},[o,w]);const S=w?.clientName.trim(),C=S&&!/^(assistant|mcp client)$/i.test(S)?S:"your assistant",_=w?.clientOrigin||w?.redirectOrigin,R=w?.companies.find(Q=>Q.id===N),I=!!(!w?.agentConnection&&R?.canWrite&&x),T=!!(w?.requestedWrite&&I),E=!!(w?.requestedConfigure&&I),P=we({mutationFn:r(Q=>ke.post(s?"/mcp/device/consent":`/mcp/requests/${encodeURIComponent(e)}/consent`,{decision:Q,companyId:N||void 0,allowWrites:Q==="approve"&&T,allowConfiguration:Q==="approve"&&E,...s?{userCode:e}:{}}),"mutationFn"),onSuccess:r(({redirectUrl:Q,status:L})=>{s&&L?y(L):Q&&window.location.assign(Q)},"onSuccess")}),O=we({mutationFn:r(()=>ke.post(`${i}/${encodeURIComponent(e)}/dot-pairing`,{pairingCode:c.trim()}),"mutationFn"),onSuccess:r(({redirectUrl:Q})=>{d(""),window.location.assign(Q)},"onSuccess")});if(v)return(0,t.jsx)("div",{className:"mx-auto max-w-xl py-10",children:(0,t.jsxs)(sn,{className:"block space-y-4 p-6",children:[(0,t.jsx)(kl,{className:"size-8"}),(0,t.jsx)("h1",{className:"text-xl font-semibold",children:v==="approved"?"Access approved":"Connection declined"}),(0,t.jsx)("p",{className:"text-sm",children:v==="approved"?"Return to your assistant. It will finish connecting automatically.":"No access was granted. You can start a new connection from your assistant."}),(0,t.jsx)($,{variant:"outline",asChild:!0,children:(0,t.jsx)(We,{to:"/",children:"Back to Paperclip"})})]})});const M=s?`/mcp-device?user_code=${encodeURIComponent(e)}`:`${n?"/dot-connect":"/mcp-connect"}/${e}`;return(0,t.jsx)("div",{className:"mx-auto max-w-xl py-10",children:(0,t.jsxs)(sn,{className:"block space-y-4 p-6",children:[(0,t.jsxs)("div",{className:"flex items-center gap-3",children:[(0,t.jsx)(kl,{className:"size-8 shrink-0 text-foreground",role:"img","aria-label":"Paperclip"}),(0,t.jsxs)("h1",{className:"min-w-0 break-words text-xl font-semibold",children:["Connect ",(0,t.jsx)("bdi",{children:C})," to Paperclip"]})]}),_&&(0,t.jsx)(bge,{origin:_},_),!s&&w?.redirectOrigin&&w.redirectOrigin!==_&&(0,t.jsx)(bge,{origin:w.redirectOrigin},w.redirectOrigin),s&&(0,t.jsxs)("p",{className:"text-sm",children:["Confirm this matches the code shown by your assistant: ",(0,t.jsx)("strong",{className:"font-mono",children:e.toUpperCase()})]}),k.isPending&&(0,t.jsx)("p",{className:"text-sm text-muted-foreground",children:"Loading connection request…"}),k.error&&(0,t.jsxs)("p",{className:"text-sm text-destructive",children:[k.error.message," Start a new connection from your assistant."]}),s&&k.error&&(0,t.jsx)($,{variant:"outline",onClick:a,children:"Enter a different code"}),w?.agentConnection&&!s&&(0,t.jsxs)("form",{className:"space-y-3",onSubmit:r(Q=>{Q.preventDefault(),O.mutate()},"onSubmit"),children:[(0,t.jsx)("p",{className:"text-sm",children:"Enter the one-use code from your Dot setup prompt to review this agent’s access. Access is granted when you click “Connect Dot with pairing code”."}),(0,t.jsx)("label",{htmlFor:"dot-pairing-code",className:"text-sm",children:"Pairing code"}),(0,t.jsx)(dt,{id:"dot-pairing-code",type:"password",autoComplete:"off",value:c,onChange:r(Q=>{h(null),f(""),d(Q.target.value)},"onChange"),required:!0,maxLength:32}),u&&(0,t.jsxs)("dl",{className:"space-y-2 rounded-md border border-border p-3 text-sm",children:[(0,t.jsxs)("div",{children:[(0,t.jsx)("dt",{className:"text-muted-foreground",children:"Company"}),(0,t.jsxs)("dd",{children:[u.company.name," ",(0,t.jsxs)("span",{className:"text-xs text-muted-foreground",children:["(",u.company.id,")"]})]})]}),(0,t.jsxs)("div",{children:[(0,t.jsx)("dt",{className:"text-muted-foreground",children:"Agent"}),(0,t.jsxs)("dd",{children:[u.agent.name," ",(0,t.jsxs)("span",{className:"text-xs text-muted-foreground",children:["(",u.agent.id,")"]})]})]}),(0,t.jsxs)("div",{children:[(0,t.jsx)("dt",{className:"text-muted-foreground",children:"Permissions"}),(0,t.jsx)("dd",{children:u.permissions})]}),(0,t.jsxs)("div",{children:[(0,t.jsx)("dt",{className:"text-muted-foreground",children:"Access duration"}),(0,t.jsx)("dd",{children:u.accessDuration})]})]}),p&&(0,t.jsx)("p",{role:"alert",className:"text-sm text-destructive",children:p}),O.error&&(0,t.jsx)("p",{role:"alert",className:"text-sm text-destructive",children:O.error.message}),(0,t.jsx)("div",{className:"flex justify-end",children:(0,t.jsx)($,{type:"submit",disabled:!u||!/^[A-Za-z0-9_-]{32}$/.test(c.trim())||O.isPending,children:O.isPending?"Connecting…":"Connect Dot with pairing code"})})]}),w&&(0,t.jsx)(t.Fragment,{children:w.requiresSignIn?(0,t.jsx)($,{asChild:!0,children:(0,t.jsx)(We,{to:`/auth?next=${encodeURIComponent(M)}`,children:"Sign in / Create account"})}):(0,t.jsxs)(t.Fragment,{children:[w.requestedCompanyId?(0,t.jsxs)("div",{className:"flex items-center gap-4 rounded-md border border-border p-4",children:[R&&(0,t.jsx)(Zx,{companyName:R.name,logoUrl:R.logoUrl,className:"size-14 shrink-0 rounded-lg text-xl"}),(0,t.jsxs)("div",{className:"min-w-0 space-y-1",children:[(0,t.jsx)("p",{className:"text-xs text-muted-foreground",children:"Organization"}),R?(0,t.jsx)("p",{className:"break-words text-lg font-semibold",children:R.name}):(0,t.jsx)("p",{className:"text-sm text-destructive",children:"The selected organization is no longer available to this account. Cancel and reconnect from your assistant to choose an organization you can access."})]})]}):(0,t.jsxs)("fieldset",{className:"space-y-2",disabled:P.isPending,children:[(0,t.jsx)("legend",{className:"mb-2 text-sm font-medium",children:"Organization"}),w.companies.map(Q=>(0,t.jsxs)("label",{className:"flex items-center gap-3 rounded-md border border-border p-3 text-sm",children:[(0,t.jsx)("input",{type:"radio",name:"company","aria-label":Q.name,value:Q.id,checked:N===Q.id,onChange:r(()=>l(Q.id),"onChange")}),(0,t.jsx)(Zx,{companyName:Q.name,logoUrl:Q.logoUrl,className:"size-12 shrink-0 rounded-lg"}),(0,t.jsx)("span",{className:"min-w-0 break-words font-medium",children:Q.name})]},Q.id)),!w.companies.length&&(0,t.jsx)("p",{className:"text-sm text-muted-foreground",children:"This account has no available organizations. Ask an organization owner to add you, then reconnect from your assistant."})]}),(0,t.jsx)("p",{className:"text-sm",children:w.agentConnection?"Connect Dot as a Paperclip agent. Pair it with an agent after connecting; assigned work uses that agent’s permissions.":"Read all of your Paperclip data"}),(w.requestedWrite||w.requestedConfigure)&&!w.agentConnection&&(0,t.jsxs)("label",{htmlFor:"mcp-allow-writes",className:"flex items-start gap-3 text-sm leading-6",children:[(0,t.jsx)("span",{className:"flex h-6 shrink-0 items-center",children:(0,t.jsx)(ei,{id:"mcp-allow-writes",checked:I,disabled:!R?.canWrite||P.isPending,onCheckedChange:r(Q=>g(Q===!0),"onCheckedChange")})}),(0,t.jsx)("span",{children:"Write all of your Paperclip data"})]}),R&&!R.canWrite&&(0,t.jsx)("p",{className:"text-sm text-muted-foreground",children:"Your role in this organization is read-only."}),P.error&&(0,t.jsx)("p",{className:"text-sm text-destructive",children:P.error.message}),(0,t.jsxs)("div",{className:"flex items-center justify-between gap-3",children:[(0,t.jsx)($,{variant:"outline",disabled:P.isPending,onClick:r(()=>P.mutate("deny"),"onClick"),children:"Cancel"}),(0,t.jsx)($,{className:"h-auto min-h-10 min-w-0 shrink whitespace-normal",disabled:!R||w.agentConnection&&!R.canWrite||P.isPending,onClick:r(()=>P.mutate("approve"),"onClick"),children:P.isPending?"Connecting…":w.agentConnection?"Connect Dot agent":"Connect organization"})]})]})})]})})}r(R9e,"McpConnectRequest");function Afs(){const e=wt(),s=te({queryKey:["mcp-connections"],queryFn:r(()=>ke.get("/mcp/connections"),"queryFn"),retry:!1}),n=s.data?.filter(i=>!i.revokedAt),a=we({mutationFn:r(i=>ke.delete(`/mcp/connections/${i}`),"mutationFn"),onSuccess:r((i,o)=>(e.setQueryData(["mcp-connections"],l=>l?.filter(c=>c.id!==o)),e.invalidateQueries({queryKey:["mcp-connections"]})),"onSuccess")});return(0,t.jsxs)("div",{className:"mx-auto max-w-xl space-y-4 py-10",children:[(0,t.jsx)("h1",{className:"text-xl font-semibold",children:"Assistant connections"}),(0,t.jsx)("p",{className:"text-sm text-muted-foreground",children:"Revoking a connection stops its future tool calls. Work already delegated continues under your organization’s normal controls."}),s.isPending&&(0,t.jsx)("p",{className:"text-sm",children:"Loading connections…"}),(s.error||a.error)&&(0,t.jsx)("p",{className:"text-sm text-destructive",children:(s.error??a.error)?.message}),n?.length===0&&(0,t.jsx)("p",{className:"text-sm",children:"No assistant connections."}),n?.map(i=>(0,t.jsxs)(sn,{className:"block space-y-2 p-4",children:[(0,t.jsx)("h2",{className:"font-medium",children:(0,t.jsx)(yo,{name:Z8(i),avatarUrl:i.user?.image,initials:iv(i.user?.name??"You")})}),(0,t.jsxs)("p",{className:"text-sm text-muted-foreground",children:["Organization: ",i.companyName]}),(0,t.jsx)("p",{className:"text-sm",children:i.scopes.includes("paperclip:agent")?"Dot agent connection":i.scopes.includes("paperclip:write")?"Read and edit work":"Read only"}),i.scopes.includes("paperclip:configure")&&(0,t.jsx)("p",{className:"text-sm",children:"Configure agents, projects and skills"}),(0,t.jsx)($,{variant:"outline",disabled:a.isPending,onClick:r(()=>a.mutate(i.id),"onClick"),children:"Revoke connection"})]},i.id)),(0,t.jsx)(We,{className:"text-sm underline",to:"/",children:"Back to Paperclip"})]})}r(Afs,"AssistantConnectionsPage");function Ifs(){const e=wt(),s=xa(),[n]=hi(),a=(s.id??"").trim(),i=(n.get("token")??"").trim(),o=(0,m.useMemo)(()=>`/cli-auth/${encodeURIComponent(a)}${i?`?token=${encodeURIComponent(i)}`:""}`,[a,i]),l=te({queryKey:D.auth.session,queryFn:r(()=>Pa.getSession(),"queryFn"),retry:!1}),c=te({queryKey:["cli-auth-challenge",a,i],queryFn:r(()=>or.getCliAuthChallenge(a,i),"queryFn"),enabled:a.length>0&&i.length>0,retry:!1}),d=we({mutationFn:r(()=>or.approveCliAuthChallenge(a,i),"mutationFn"),onSuccess:r(async()=>{await e.invalidateQueries({queryKey:D.auth.session}),await c.refetch()},"onSuccess")}),u=we({mutationFn:r(()=>or.cancelCliAuthChallenge(a,i),"mutationFn"),onSuccess:r(async()=>{await c.refetch()},"onSuccess")});if(!a||!i)return(0,t.jsx)("div",{className:"mx-auto max-w-xl py-10 text-sm text-destructive",children:"Invalid CLI auth URL."});if(l.isLoading||c.isLoading)return(0,t.jsx)("div",{className:"mx-auto max-w-xl py-10 text-sm text-muted-foreground",children:"Loading CLI auth challenge..."});if(c.error)return(0,t.jsx)("div",{className:"mx-auto max-w-xl py-10",children:(0,t.jsxs)(sn,{className:"block p-6",children:[(0,t.jsx)("h1",{className:"text-lg font-semibold",children:"CLI auth challenge unavailable"}),(0,t.jsx)("p",{className:"mt-2 text-sm text-muted-foreground",children:c.error instanceof Error?c.error.message:"Challenge is invalid or expired."})]})});const h=c.data;return h?h.status==="approved"?(0,t.jsx)("div",{className:"mx-auto max-w-xl py-10",children:(0,t.jsxs)(sn,{className:"block p-6",children:[(0,t.jsx)("h1",{className:"text-xl font-semibold",children:"CLI access approved"}),(0,t.jsx)("p",{className:"mt-2 text-sm text-muted-foreground",children:"The Paperclip CLI can now finish authentication on the requesting machine."}),(0,t.jsxs)("p",{className:"mt-4 text-sm text-muted-foreground",children:["Command: ",(0,t.jsx)("span",{className:"font-mono text-foreground",children:h.command})]})]})}):h.status==="cancelled"||h.status==="expired"?(0,t.jsx)("div",{className:"mx-auto max-w-xl py-10",children:(0,t.jsxs)(sn,{className:"block p-6",children:[(0,t.jsx)("h1",{className:"text-xl font-semibold",children:h.status==="expired"?"CLI auth challenge expired":"CLI auth challenge cancelled"}),(0,t.jsx)("p",{className:"mt-2 text-sm text-muted-foreground",children:"Start the CLI auth flow again from your terminal to generate a new approval request."})]})}):h.requiresSignIn||!l.data?(0,t.jsx)("div",{className:"mx-auto max-w-xl py-10",children:(0,t.jsxs)(sn,{className:"block p-6",children:[(0,t.jsx)("h1",{className:"text-xl font-semibold",children:"Sign in required"}),(0,t.jsx)("p",{className:"mt-2 text-sm text-muted-foreground",children:"Sign in or create an account, then return to this page to approve the CLI access request."}),(0,t.jsx)($,{asChild:!0,className:"mt-4",children:(0,t.jsx)(We,{to:`/auth?next=${encodeURIComponent(o)}`,children:"Sign in / Create account"})})]})}):(0,t.jsx)("div",{className:"mx-auto max-w-xl py-10",children:(0,t.jsxs)(sn,{className:"block p-6",children:[(0,t.jsx)("h1",{className:"text-xl font-semibold",children:"Approve Paperclip CLI access"}),(0,t.jsx)("p",{className:"mt-2 text-sm text-muted-foreground",children:"A local Paperclip CLI process is requesting board access to this instance."}),(0,t.jsxs)("div",{className:"mt-5 space-y-3 text-sm",children:[(0,t.jsxs)("div",{children:[(0,t.jsx)("div",{className:"text-muted-foreground",children:"Command"}),(0,t.jsx)("div",{className:"font-mono text-foreground",children:h.command})]}),(0,t.jsxs)("div",{children:[(0,t.jsx)("div",{className:"text-muted-foreground",children:"Client"}),(0,t.jsx)("div",{className:"text-foreground",children:h.clientName??"paperclip-pro cli"})]}),(0,t.jsxs)("div",{children:[(0,t.jsx)("div",{className:"text-muted-foreground",children:"Requested access"}),(0,t.jsx)("div",{className:"text-foreground",children:h.requestedAccess==="instance_admin_required"?"Instance admin":"Board"})]}),h.requestedCompanyName&&(0,t.jsxs)("div",{children:[(0,t.jsx)("div",{className:"text-muted-foreground",children:"Requested organization"}),(0,t.jsx)("div",{className:"text-foreground",children:h.requestedCompanyName})]})]}),(d.error||u.error)&&(0,t.jsx)("p",{className:"mt-4 text-sm text-destructive",children:(d.error??u.error)instanceof Error?(d.error??u.error).message:"Failed to update CLI auth challenge"}),!h.canApprove&&(0,t.jsx)("p",{className:"mt-4 text-sm text-destructive",children:"This challenge requires instance-admin access. Sign in with an instance admin account to approve it."}),(0,t.jsxs)("div",{className:"mt-5 flex gap-3",children:[(0,t.jsx)($,{onClick:r(()=>d.mutate(),"onClick"),disabled:!h.canApprove||d.isPending||u.isPending,children:d.isPending?"Approving...":"Approve CLI access"}),(0,t.jsx)($,{type:"button",variant:"outline",onClick:r(()=>u.mutate(),"onClick"),disabled:d.isPending||u.isPending,children:u.isPending?"Cancelling...":"Cancel"})]})]})}):(0,t.jsx)("div",{className:"mx-auto max-w-xl py-10 text-sm text-destructive",children:"CLI auth challenge unavailable."})}r(Ifs,"CliAuthPage");var Tfs=pOe.filter(e=>e!=="paperclip_runner"),yge=new Set(["claude_local","codex_local","gemini_local","kimi_local","opencode_local","pi_local","cursor"]);function Rfs(e,s){let n=e;for(const a of s){if(!n||typeof n!="object")return null;n=n[a]}return typeof n=="string"&&n.trim().length>0?n:null}r(Rfs,"readNestedString");var E1="w-full border border-zinc-800 bg-zinc-950 px-3 py-2 text-sm text-zinc-100 outline-none focus:border-zinc-500",jge="border border-zinc-800 bg-zinc-950/95 p-6",wge="flex-1 border px-3 py-2 text-sm transition-colors";function Efs(e){return e?e.charAt(0).toUpperCase()+e.slice(1):null}r(Efs,"formatHumanRole");function E9e(e){if(!e||typeof e!="object")return null;const s=e.code;return typeof s=="string"&&s.trim().length>0?s:null}r(E9e,"getAuthErrorCode");function Lfs(e){if(!(e instanceof Error))return null;const s=e.message.trim();return s.length>0?s:null}r(Lfs,"getAuthErrorMessage");function Mfs(e,s,n){const a=E9e(e),i=Lfs(e),o=n.trim().length>0?n.trim():"that email";return a==="USER_ALREADY_EXISTS_USE_ANOTHER_EMAIL"?{tone:"info",message:`An account already exists for ${o}. Sign in below to continue with this invite.`}:a==="INVALID_EMAIL_OR_PASSWORD"?{tone:"error",message:"That email and password did not match an existing Paperclip account. Check both fields, or create an account first if you are new here."}:s==="sign_in"&&i==="Request failed: 401"?{tone:"error",message:"That email and password did not match an existing Paperclip account. Check both fields, or create an account first if you are new here."}:s==="sign_up"&&i==="Request failed: 422"?{tone:"info",message:`An account may already exist for ${o}. Try signing in instead.`}:{tone:"error",message:i??"Authentication failed"}}r(Mfs,"mapInviteAuthFeedback");function kge(e){return!!(e&&typeof e=="object"&&"bootstrapAccepted"in e)}r(kge,"isBootstrapAcceptancePayload");function Pfs(e,s){return!e||typeof e!="object"||s?!1:e.status==="approved"}r(Pfs,"isApprovedHumanJoinPayload");function yQ({companyDisplayName:e,companyLogoUrl:s,className:n}){return(0,t.jsx)(Zx,{companyName:e,logoUrl:s,logoFit:"contain",className:n})}r(yQ,"InviteCompanyLogo");function Nge({companyDisplayName:e,companyLogoUrl:s,invitedByUserName:n,claimSecret:a=null,claimApiKeyPath:i=null,onboardingTextUrl:o=null}){return(0,t.jsx)("div",{className:"min-h-screen bg-zinc-950 px-6 py-12 text-zinc-100",children:(0,t.jsxs)("div",{className:"mx-auto max-w-md border border-zinc-800 bg-zinc-950 p-6","data-testid":"invite-pending-approval",children:[(0,t.jsxs)("div",{className:"flex items-center gap-3",children:[(0,t.jsx)(yQ,{companyDisplayName:e,companyLogoUrl:s,className:"h-12 w-12 border border-zinc-800 rounded-none"}),(0,t.jsxs)("h1",{className:"text-lg font-semibold",children:["Request to join ",e]})]}),(0,t.jsxs)("div",{className:"mt-4 space-y-3",children:[(0,t.jsxs)("p",{className:"text-sm text-zinc-400",children:["Your request is still awaiting approval. ",n??"An organization admin"," must approve your request to join."]}),(0,t.jsxs)("div",{className:"border border-zinc-800 p-3",children:[(0,t.jsx)("p",{className:"text-xs text-zinc-500 mb-1",children:"Approval page"}),(0,t.jsx)("p",{className:"text-sm text-zinc-200",children:"Settings → Members"})]}),(0,t.jsxs)("p",{className:"text-sm text-zinc-400",children:["Ask them to visit ",(0,t.jsx)("span",{className:"text-zinc-200",children:"Settings → Members"})," to approve your request."]}),(0,t.jsx)("p",{className:"text-xs text-zinc-500",children:"Refresh this page after you've been approved — you'll be redirected automatically."})]}),a&&i?(0,t.jsxs)("div",{className:"mt-4 space-y-1 border border-zinc-800 p-3 text-xs text-zinc-400",children:[(0,t.jsx)("div",{className:"text-zinc-200",children:"Claim secret"}),(0,t.jsx)("div",{className:"font-mono break-all",children:a}),(0,t.jsxs)("div",{className:"font-mono break-all",children:["POST ",i]})]}):null,o?(0,t.jsxs)("div",{className:"mt-4 text-xs text-zinc-400",children:["Onboarding: ",(0,t.jsx)("span",{className:"font-mono break-all",children:o})]}):null]})})}r(Nge,"AwaitingJoinApprovalPanel");function Dfs(){const e=wt(),s=Gn(),{setSelectedCompanyId:n}=fs(),a=(xa().token??"").trim(),[i,o]=(0,m.useState)("sign_up"),[l,c]=(0,m.useState)(""),[d,u]=(0,m.useState)(""),[h,p]=(0,m.useState)(""),[f,x]=(0,m.useState)(""),[g,v]=(0,m.useState)("claude_local"),[y,k]=(0,m.useState)(""),[w,N]=(0,m.useState)(null),[S,C]=(0,m.useState)(null),[_,R]=(0,m.useState)(null),[I,T]=(0,m.useState)(!1),E="invite-auth-error",P=te({queryKey:D.health,queryFn:r(()=>Lu.get(),"queryFn"),retry:!1}),O=te({queryKey:D.auth.session,queryFn:r(()=>Pa.getSession(),"queryFn"),retry:!1}),M=te({queryKey:D.access.invite(a),queryFn:r(()=>or.getInvite(a),"queryFn"),enabled:a.length>0,retry:!1}),Q=LQ({enabled:!!O.data&&!!M.data?.companyId,staleTime:0}),L=P.data?.deploymentMode!=="local_trusted"?Q.isFetchedAfterMount:!0,F=L?Q.data?.companies??[]:[];(0,m.useEffect)(()=>{a&&fge(a)},[a]),(0,m.useEffect)(()=>{T(!1)},[a]),(0,m.useEffect)(()=>{if(!L)return;const ve=Q.data?.companies;!ve||!M.data?.companyId||ve.some(Ie=>Ie.id===M.data.companyId)&&OT(a)},[Q.data,M.data,L,a]);const q=M.data,z=!!O.data&&!!q?.companyId&&!L,K=!!q?.companyId&&F.some(ve=>ve.id===q?.companyId),U=q?.companyName?.trim()||"this Paperclip company",V=q?.companyLogoUrl?.trim()||null,ne=q?.invitedByUserName?.trim()||null,Z=q?.inviteMessage?.trim()||null,ie=Efs(q?.humanRole),J=q?.joinRequestStatus??null,ae=q?.joinRequestType??null,oe=ae==="human"&&(J==="pending_approval"||J==="approved"),G=P.data?.deploymentMode==="authenticated"&&!O.data&&q?.allowedJoinTypes!=="agent",X=q?.inviteType!=="bootstrap_ceo"&&q?.allowedJoinTypes==="agent",Y=!!O.data&&!X&&q?.inviteType!=="bootstrap_ceo"&&(!J||oe)&&!z&&!K&&!w&&S===null,re=O.data?.user.name?.trim()||O.data?.user.email?.trim()||"this account",se=d.trim().length>0&&h.trim().length>0&&(i==="sign_in"||l.trim().length>0&&h.trim().length>=8),ce=we({mutationFn:r(async()=>{if(!q)throw new Error("Invite not found");if(z)throw new Error("Checking your organization access. Try again in a moment.");if(K)throw new Error("This account already belongs to the organization.");return q.inviteType==="bootstrap_ceo"||q.allowedJoinTypes!=="agent"?or.acceptInvite(a,{requestType:"human"}):or.acceptInvite(a,{requestType:"agent",agentName:f.trim(),adapterType:g,capabilities:y.trim()||null})},"mutationFn"),onSuccess:r(async ve=>{C(null),OT(a);const Ie=kge(ve);N({kind:Ie?"bootstrap":"join",payload:ve}),await e.invalidateQueries({queryKey:D.auth.session}),await e.invalidateQueries({queryKey:D.access.currentBoardAccess}),await e.invalidateQueries({queryKey:D.companies.all}),q?.companyId&&Pfs(ve,X)&&(n(q.companyId,{source:"manual"}),s("/",{replace:!0}))},"onSuccess"),onError:r(ve=>{C(ve instanceof Error?ve.message:"Failed to accept invite")},"onError")});(0,m.useEffect)(()=>{!Y||I||ce.isPending||(T(!0),C(null),ce.mutate())},[ce,I,Y]);const pe=we({mutationFn:r(async()=>{if(i==="sign_in"){await Pa.signInEmail({email:d.trim(),password:h});return}await Pa.signUpEmail({name:l.trim(),email:d.trim(),password:h})},"mutationFn"),onSuccess:r(async()=>{R(null),fge(a),await e.invalidateQueries({queryKey:D.auth.session}),await e.invalidateQueries({queryKey:D.health}),await e.invalidateQueries({queryKey:D.access.currentBoardAccess});const{companies:ve}=await HOe(e);if(q?.companyId&&ve.some(Ie=>Ie.id===q.companyId)){OT(a),n(q.companyId,{source:"manual"}),s("/",{replace:!0});return}if(!(!q||q.inviteType!=="bootstrap_ceo"))try{kge(await ce.mutateAsync())&&s("/",{replace:!0})}catch{return}},"onSuccess"),onError:r(ve=>{const Ie=Mfs(ve,i,d);E9e(ve)==="USER_ALREADY_EXISTS_USE_ANOTHER_EMAIL"&&(o("sign_in"),p("")),R(Ie)},"onError")}),fe=(0,m.useMemo)(()=>q?K?"Open organization":q.inviteType==="bootstrap_ceo"?"Accept invite":X?"Submit request":O.data?"Accept invite":"Continue":"Continue",[q,K,O.data,X]);if(!a)return(0,t.jsx)("div",{className:"mx-auto max-w-xl py-10 text-sm text-destructive",children:"Invalid invite token."});if(M.isLoading||P.isLoading||O.isLoading)return(0,t.jsx)("div",{className:"mx-auto max-w-xl py-10 text-sm text-muted-foreground",children:"Loading invite..."});if(z)return(0,t.jsx)("div",{className:"mx-auto max-w-xl py-10 text-sm text-muted-foreground",children:"Checking your access..."});if(M.error||!q)return(0,t.jsx)("div",{className:"mx-auto max-w-xl py-10",children:(0,t.jsxs)("div",{className:"border border-border bg-card p-6","data-testid":"invite-error",children:[(0,t.jsx)("h1",{className:"text-lg font-semibold",children:"Invite not available"}),(0,t.jsx)("p",{className:"mt-2 text-sm text-muted-foreground",children:"This invite may be expired, revoked, or already used."})]})});if(J==="approved"&&ae==="human"&&K)return(0,t.jsx)("div",{className:"mx-auto max-w-xl py-10 text-sm text-muted-foreground",children:"Opening organization..."});if(J==="pending_approval"&&!oe)return(0,t.jsx)(Nge,{companyDisplayName:U,companyLogoUrl:V,invitedByUserName:ne});if(J&&!oe)return(0,t.jsx)("div",{className:"mx-auto max-w-xl py-10",children:(0,t.jsxs)("div",{className:"border border-border bg-card p-6","data-testid":"invite-error",children:[(0,t.jsx)("h1",{className:"text-lg font-semibold",children:"Invite not available"}),(0,t.jsx)("p",{className:"mt-2 text-sm text-muted-foreground",children:J==="rejected"?"This join request was not approved.":"This invite has already been used."})]})});if(w?.kind==="bootstrap")return(0,t.jsx)("div",{className:"min-h-screen bg-zinc-950 px-6 py-12 text-zinc-100",children:(0,t.jsxs)("div",{className:"mx-auto max-w-md border border-zinc-800 bg-zinc-950 p-6",children:[(0,t.jsx)("h1",{className:"text-lg font-semibold",children:"Bootstrap complete"}),(0,t.jsx)("div",{className:"mt-4",children:(0,t.jsx)($,{asChild:!0,className:"rounded-none",children:(0,t.jsx)(We,{to:"/",children:"Open board"})})})]})});if(w?.kind==="join"){const ve=w.payload,Ie=typeof ve.claimSecret=="string"?ve.claimSecret:null,de=typeof ve.claimApiKeyPath=="string"?ve.claimApiKeyPath:null,xe=Rfs(ve.onboarding,["textInstructions","url"]);return!X&&ve.status==="approved"?(0,t.jsx)("div",{className:"min-h-screen bg-zinc-950 px-6 py-12 text-zinc-100",children:(0,t.jsxs)("div",{className:"mx-auto max-w-md border border-zinc-800 bg-zinc-950 p-6",children:[(0,t.jsxs)("div",{className:"flex items-center gap-3",children:[(0,t.jsx)(yQ,{companyDisplayName:U,companyLogoUrl:V,className:"h-12 w-12 border border-zinc-800 rounded-none"}),(0,t.jsx)("h1",{className:"text-lg font-semibold",children:"You joined the organization"})]}),(0,t.jsx)("div",{className:"mt-4",children:(0,t.jsx)($,{asChild:!0,className:"w-full rounded-none",children:(0,t.jsx)(We,{to:"/",children:"Open board"})})})]})}):(0,t.jsx)(Nge,{companyDisplayName:U,companyLogoUrl:V,invitedByUserName:ne,claimSecret:Ie,claimApiKeyPath:de,onboardingTextUrl:xe})}return(0,t.jsx)("div",{className:"min-h-screen bg-zinc-950 px-6 py-12 text-zinc-100",children:(0,t.jsx)("div",{className:"mx-auto max-w-5xl",children:(0,t.jsxs)("div",{className:"grid gap-6 lg:grid-cols-(--gtc-36)",children:[(0,t.jsxs)("section",{className:`${jge} space-y-6`,children:[(0,t.jsxs)("div",{className:"flex items-start gap-4",children:[(0,t.jsx)(yQ,{companyDisplayName:U,companyLogoUrl:V,className:"h-16 w-16 rounded-none border border-zinc-800"}),(0,t.jsxs)("div",{className:"min-w-0",children:[(0,t.jsx)("p",{className:"text-xs uppercase tracking-(--tracking-caps) text-zinc-500",children:"You've been invited to join Paperclip"}),(0,t.jsx)("h1",{className:"mt-2 text-2xl font-semibold",children:q.inviteType==="bootstrap_ceo"?"Set up Paperclip":`Join ${U}`}),(0,t.jsx)("p",{className:"mt-2 max-w-2xl text-sm leading-6 text-zinc-300",children:X?"Review the invite details, then submit the agent information below to start the join request.":G?"Create your Paperclip account first. If you already have one, switch to sign in and continue the invite with the same email.":"Your account is ready. Review the invite details, then accept it to continue."})]})]}),(0,t.jsxs)("div",{className:"grid gap-3 sm:grid-cols-2",children:[(0,t.jsxs)("div",{className:"border border-zinc-800 p-3",children:[(0,t.jsx)("div",{className:"text-xs uppercase tracking-(--tracking-caps) text-zinc-500",children:"Organization"}),(0,t.jsx)("div",{className:"mt-1 text-sm text-zinc-100",children:U})]}),(0,t.jsxs)("div",{className:"border border-zinc-800 p-3",children:[(0,t.jsx)("div",{className:"text-xs uppercase tracking-(--tracking-caps) text-zinc-500",children:"Invited by"}),(0,t.jsx)("div",{className:"mt-1 text-sm text-zinc-100",children:ne??"Paperclip board"})]}),(0,t.jsxs)("div",{className:"border border-zinc-800 p-3",children:[(0,t.jsx)("div",{className:"text-xs uppercase tracking-(--tracking-caps) text-zinc-500",children:"Requested access"}),(0,t.jsx)("div",{className:"mt-1 text-sm text-zinc-100",children:X?"Agent join request":ie??"Organization access"})]}),(0,t.jsxs)("div",{className:"border border-zinc-800 p-3",children:[(0,t.jsx)("div",{className:"text-xs uppercase tracking-(--tracking-caps) text-zinc-500",children:"Invite expires"}),(0,t.jsx)("div",{className:"mt-1 text-sm text-zinc-100",children:Zd(q.expiresAt)})]})]}),Z?(0,t.jsxs)("div",{className:"border border-amber-500/40 bg-amber-500/10 p-4",children:[(0,t.jsx)("div",{className:"text-xs uppercase tracking-(--tracking-caps) text-amber-200/80",children:"Message from inviter"}),(0,t.jsx)("p",{className:"mt-2 text-sm leading-6 text-amber-50",children:Z})]}):null,O.data?(0,t.jsxs)("div",{className:"border border-emerald-500/40 bg-emerald-500/10 p-4 text-sm text-emerald-50",children:["Signed in as ",(0,t.jsx)("span",{className:"font-medium",children:re}),"."]}):null]}),(0,t.jsx)("section",{className:`${jge} h-fit`,children:X?(0,t.jsxs)("div",{className:"space-y-4",children:[(0,t.jsxs)("div",{children:[(0,t.jsx)("h2",{className:"text-lg font-semibold",children:"Submit agent details"}),(0,t.jsxs)("p",{className:"mt-1 text-sm text-zinc-400",children:["This invite will create an approval request for a new agent in ",U,"."]})]}),(0,t.jsxs)("label",{className:"block text-sm",children:[(0,t.jsx)("span",{className:"mb-1 block text-zinc-400",children:"Agent name"}),(0,t.jsx)("input",{className:E1,value:f,onChange:r(ve=>x(ve.target.value),"onChange")})]}),(0,t.jsxs)("label",{className:"block text-sm",children:[(0,t.jsx)("span",{className:"mb-1 block text-zinc-400",children:"Adapter type"}),(0,t.jsx)("select",{className:E1,value:g,onChange:r(ve=>v(ve.target.value),"onChange"),children:Tfs.map(ve=>(0,t.jsxs)("option",{value:ve,disabled:!yge.has(ve),children:[kf(ve),yge.has(ve)?"":" (Coming soon)"]},ve))})]}),(0,t.jsxs)("label",{className:"block text-sm",children:[(0,t.jsx)("span",{className:"mb-1 block text-zinc-400",children:"Capabilities"}),(0,t.jsx)("textarea",{className:E1,rows:4,value:y,onChange:r(ve=>k(ve.target.value),"onChange")})]}),S?(0,t.jsx)("p",{className:"text-xs text-red-400",children:S}):null,(0,t.jsx)($,{className:"w-full rounded-none",disabled:ce.isPending||f.trim().length===0,onClick:r(()=>ce.mutate(),"onClick"),children:ce.isPending?"Working...":fe})]}):G?(0,t.jsxs)("div",{className:"space-y-5",children:[(0,t.jsxs)("div",{children:[(0,t.jsx)("h2",{className:"text-lg font-semibold",children:i==="sign_up"?"Create your account":"Sign in to continue"}),(0,t.jsx)("p",{className:"mt-1 text-sm text-zinc-400",children:i==="sign_up"?`Start with a Paperclip account. After that, you'll come right back here to accept the invite for ${U}.`:"Use the Paperclip account that already matches this invite. If you do not have one yet, switch back to create account."})]}),(0,t.jsxs)("div",{className:"flex gap-2",children:[(0,t.jsx)("button",{type:"button",className:`${wge} ${i==="sign_up"?"border-zinc-100 bg-zinc-100 text-zinc-950":"border-zinc-800 text-zinc-300 hover:border-zinc-600"}`,onClick:r(()=>{R(null),o("sign_up")},"onClick"),children:"Create account"}),(0,t.jsx)("button",{type:"button",className:`${wge} ${i==="sign_in"?"border-zinc-100 bg-zinc-100 text-zinc-950":"border-zinc-800 text-zinc-300 hover:border-zinc-600"}`,onClick:r(()=>{R(null),o("sign_in")},"onClick"),children:"I already have an account"})]}),(0,t.jsxs)("form",{className:"space-y-4",method:"post",action:i==="sign_up"?"/api/auth/sign-up/email":"/api/auth/sign-in/email",onSubmit:r(ve=>{if(ve.preventDefault(),!pe.isPending){if(!se){R({tone:"error",message:"Please fill in all required fields."});return}pe.mutate()}},"onSubmit"),"data-testid":"invite-inline-auth",children:[i==="sign_up"?(0,t.jsxs)("label",{className:"block text-sm",htmlFor:"invite-name",children:[(0,t.jsx)("span",{className:"mb-1 block text-zinc-400",children:"Name"}),(0,t.jsx)("input",{id:"invite-name",name:"name",className:E1,value:l,onChange:r(ve=>{c(ve.target.value),R(null)},"onChange"),autoComplete:"name",required:!0,"aria-required":"true","aria-invalid":_?.tone==="error"?!0:void 0,"aria-describedby":_?E:void 0,autoFocus:!0})]}):null,(0,t.jsxs)("label",{className:"block text-sm",htmlFor:"invite-email",children:[(0,t.jsx)("span",{className:"mb-1 block text-zinc-400",children:"Email"}),(0,t.jsx)("input",{id:"invite-email",name:"email",type:"email",className:E1,value:d,onChange:r(ve=>{u(ve.target.value),R(null)},"onChange"),autoComplete:"username",required:!0,"aria-required":"true","aria-invalid":_?.tone==="error"?!0:void 0,"aria-describedby":_?E:void 0,autoFocus:i==="sign_in"})]}),(0,t.jsxs)("label",{className:"block text-sm",htmlFor:"invite-password",children:[(0,t.jsx)("span",{className:"mb-1 block text-zinc-400",children:"Password"}),(0,t.jsx)("input",{id:"invite-password",name:"password",type:"password",className:E1,value:h,onChange:r(ve=>{p(ve.target.value),R(null)},"onChange"),autoComplete:i==="sign_in"?"current-password":"new-password",required:!0,"aria-required":"true","aria-invalid":_?.tone==="error"?!0:void 0,"aria-describedby":_?E:void 0})]}),_?(0,t.jsx)("p",{id:E,role:"alert",className:`text-xs ${_.tone==="info"?"text-amber-300":"text-red-400"}`,children:_.message}):null,(0,t.jsx)($,{type:"submit",className:"w-full rounded-none",disabled:pe.isPending,"aria-disabled":!se||pe.isPending,children:pe.isPending?"Working...":i==="sign_in"?"Sign in and continue":"Create account and continue"})]}),(0,t.jsx)("p",{className:"text-xs leading-5 text-zinc-500",children:i==="sign_up"?"Already signed up before? Use the existing-account option instead so the invite lands on the right Paperclip user.":"No account yet? Switch back to create account so you can accept the invite with a new login."})]}):(0,t.jsxs)("div",{className:"space-y-4",children:[(0,t.jsxs)("div",{children:[(0,t.jsx)("h2",{className:"text-lg font-semibold",children:K?"Already in this organization":Y?"Completing organization access":q.inviteType==="bootstrap_ceo"?"Accept bootstrap invite":"Accept organization invite"}),(0,t.jsx)("p",{className:"mt-1 text-sm text-zinc-400",children:Y?`Granting your access to ${U}.`:K?`This account already belongs to ${U}.`:`This will ${q.inviteType==="bootstrap_ceo"?"finish setting up Paperclip":`grant or complete your access to ${U}`}.`})]}),S?(0,t.jsx)("p",{className:"text-xs text-red-400",children:S}):null,Y?(0,t.jsx)("div",{className:"text-sm text-zinc-400",children:ce.isPending?"Submitting request...":"Finishing sign-in..."}):(0,t.jsx)($,{className:"w-full rounded-none",disabled:ce.isPending,onClick:r(()=>{if(K&&q.companyId){OT(a),n(q.companyId,{source:"manual"}),s("/",{replace:!0});return}ce.mutate()},"onClick"),children:ce.isPending?"Working...":fe})]})})]})})})}r(Dfs,"InviteLandingPage");var $fs=15e3,Ofs={parent:"Parent task",child:"Sub-task",blocked_by:"Blocked by",blocks:"Blocks"};function Bfs(){(0,m.useEffect)(()=>{const e=document.createElement("meta");return e.name="robots",e.content="noindex",document.head.appendChild(e),()=>e.remove()},[])}r(Bfs,"useNoIndexMeta");function jQ(e,s){const n=`/s/${encodeURIComponent(e)}`;return s?`${n}/issues/${encodeURIComponent(s)}`:n}r(jQ,"sharePath");var Ffs=/^(?:https?:\/\/[^/]+)?\/api\/attachments\/([^/?#]+)\/content(?:[?#].*)?$/i;function zfs(e,s){const n=Ffs.exec(s.trim());return n?`/api/public/share/${encodeURIComponent(e)}/attachments/${n[1]}/content`:null}r(zfs,"publicShareImageSrc");function pC({title:e,children:s}){return(0,t.jsxs)("section",{className:"space-y-3",children:[(0,t.jsx)("h2",{className:"text-sm font-semibold text-muted-foreground",children:e}),s]})}r(pC,"Section");function wQ({actor:e}){return(0,t.jsx)(yo,{name:e.name,avatarUrl:e.iconUrl,size:"sm"})}r(wQ,"ActorIdentity");function kQ({value:e}){return(0,t.jsx)("time",{dateTime:e,title:yr(e),className:"text-xs text-muted-foreground",children:gr(e)})}r(kQ,"Timestamp");function qfs({agentName:e}){return(0,t.jsxs)("span",{"data-testid":"public-share-run-pill",className:"inline-flex items-center gap-1.5 rounded-full border border-border px-3 py-1 text-xs text-foreground",children:[(0,t.jsx)("span",{className:"h-2 w-2 animate-pulse rounded-full bg-(--status-agent-running)","aria-hidden":!0}),e," is working…"]})}r(qfs,"ActiveRunPill");function L9e({attachments:e}){return(0,t.jsx)(mH,{children:e.map(s=>{const n=l2e({name:s.filename,url:s.url,contentType:s.contentType,byteSize:s.byteSize}),a=n.icon,i=hH(s.byteSize);return(0,t.jsxs)(oH,{size:"sm",children:[(0,t.jsx)(lH,{children:(0,t.jsx)(a,{"aria-hidden":!0})}),(0,t.jsxs)(cH,{children:[(0,t.jsx)(dH,{className:"max-w-48",children:s.filename}),(0,t.jsx)(uH,{className:"max-w-48",children:i?`${n.label} · ${i}`:n.label})]}),(0,t.jsx)(r2e,{"aria-label":`Download ${s.filename}`,render:(0,t.jsx)("a",{href:s.url,download:s.filename,rel:"noreferrer"})})]},s.id)})})}r(L9e,"AttachmentList");function Ufs({related:e,token:s,isSharedRoot:n}){const a=e.identifier?`${e.identifier} · ${e.title}`:e.title,i=(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)(ro,{status:e.status,size:"sm"}),(0,t.jsx)("span",{className:"min-w-0 truncate",children:a})]});return(0,t.jsxs)("li",{className:"flex items-center gap-2 text-sm",children:[(0,t.jsx)("span",{className:"w-20 shrink-0 text-xs text-muted-foreground",children:Ofs[e.relation]}),e.navigable?(0,t.jsx)(Md,{to:n?jQ(s,e.id):jQ(s),className:"flex min-w-0 items-center gap-2 text-foreground underline-offset-2 hover:underline",children:i}):(0,t.jsx)("span",{className:"flex min-w-0 items-center gap-2 text-muted-foreground",children:i})]})}r(Ufs,"RelatedIssueRow");function Kfs({comment:e,resolveImageSrc:s}){return e.kind==="redacted"?(0,t.jsxs)("li",{"data-testid":"public-share-redacted-comment",className:"flex flex-wrap items-center gap-2 rounded-lg border border-dashed border-border px-3 py-2",children:[(0,t.jsx)(wQ,{actor:e.author}),(0,t.jsx)(kQ,{value:e.createdAt}),(0,t.jsx)("span",{className:"text-xs italic text-muted-foreground",children:"Internal update"})]}):(0,t.jsxs)("li",{className:"space-y-2 rounded-lg border border-border bg-card px-3 py-3",children:[(0,t.jsxs)("div",{className:"flex flex-wrap items-center gap-2",children:[(0,t.jsx)(wQ,{actor:e.author}),(0,t.jsx)(kQ,{value:e.createdAt})]}),(0,t.jsx)(An,{className:"text-sm",softBreaks:!0,linkIssueReferences:!1,resolveImageSrc:s,children:e.body}),e.attachments.length>0?(0,t.jsx)(L9e,{attachments:e.attachments}):null]})}r(Kfs,"TimelineEntry");function Qfs({document:e,resolveImageSrc:s}){return(0,t.jsxs)("details",{className:"group rounded-lg border border-border bg-card",children:[(0,t.jsxs)("summary",{className:"flex cursor-pointer items-center gap-2 px-3 py-2 text-sm",children:[(0,t.jsx)(Za,{className:"h-4 w-4 shrink-0 text-muted-foreground","aria-hidden":!0}),(0,t.jsx)("span",{className:"min-w-0 flex-1 truncate font-medium",children:e.title??e.key}),(0,t.jsx)(kQ,{value:e.updatedAt})]}),(0,t.jsxs)("div",{className:"space-y-3 border-t border-border px-3 py-3",children:[(0,t.jsxs)("a",{href:e.pdfUrl,download:!0,rel:"noreferrer",className:"inline-flex items-center gap-1.5 text-xs text-muted-foreground hover:text-foreground",children:[(0,t.jsx)(Fi,{className:"h-3.5 w-3.5","aria-hidden":!0}),"Download PDF"]}),(0,t.jsx)(An,{className:"text-sm",linkIssueReferences:!1,resolveImageSrc:s,children:e.body})]})]})}r(Qfs,"DocumentCard");function Wfs({product:e}){return(0,t.jsxs)("li",{className:"flex flex-wrap items-center gap-x-3 gap-y-1 rounded-lg border border-border bg-card px-3 py-2 text-sm",children:[(0,t.jsx)("span",{className:"min-w-0 flex-1 truncate font-medium",children:e.title}),(0,t.jsxs)("span",{className:"text-xs text-muted-foreground",children:[e.type.replace(/_/g," ")," · ",e.status.replace(/_/g," ")]}),e.url?(0,t.jsxs)("a",{href:e.url,target:"_blank",rel:"noopener noreferrer",className:"inline-flex items-center gap-1 text-xs text-muted-foreground hover:text-foreground",children:[(0,t.jsx)($n,{className:"h-3.5 w-3.5","aria-hidden":!0}),"Open"]}):null,e.downloadUrl?(0,t.jsxs)("a",{href:e.downloadUrl,download:!0,rel:"noreferrer",className:"inline-flex items-center gap-1 text-xs text-muted-foreground hover:text-foreground",children:[(0,t.jsx)(Fi,{className:"h-3.5 w-3.5","aria-hidden":!0}),"Download"]}):null]})}r(Wfs,"WorkProductRow");function Sge({title:e,body:s,action:n}){return(0,t.jsx)("div",{className:"flex h-dvh overflow-y-auto bg-background px-4 text-foreground",children:(0,t.jsxs)("div",{className:"m-auto w-full max-w-sm space-y-2 rounded-lg border border-border bg-card p-6 text-center",children:[(0,t.jsx)("h1",{className:"text-lg font-semibold",children:e}),(0,t.jsx)("p",{className:"text-sm text-muted-foreground",children:s}),n]})})}r(Sge,"CenteredNotice");function Hfs({view:e,token:s}){const{company:n,issue:a}=e,i=(0,m.useCallback)(o=>zfs(s,o),[s]);return(0,t.jsxs)("div",{className:"h-dvh overflow-y-auto bg-background text-foreground",children:[(0,t.jsx)("header",{className:"border-b border-border",children:(0,t.jsxs)("div",{className:"mx-auto flex max-w-3xl items-center gap-3 px-4 py-3",children:[(0,t.jsx)(Zx,{companyName:n.name,logoUrl:n.logoUrl,logoFit:"contain",className:"h-8 w-8 shrink-0 rounded-md"}),(0,t.jsx)("span",{className:"min-w-0 truncate text-sm font-medium",children:n.name}),(0,t.jsx)("span",{className:"ml-auto shrink-0 text-xs text-muted-foreground",children:"Read-only view"})]})}),(0,t.jsxs)("main",{className:"mx-auto max-w-3xl space-y-8 px-4 py-5",children:[e.isSharedRoot?null:(0,t.jsxs)(Md,{to:jQ(s),className:"inline-flex items-center gap-1.5 text-sm text-muted-foreground hover:text-foreground",children:[(0,t.jsx)(wl,{className:"h-4 w-4","aria-hidden":!0}),"Back to main task"]}),(0,t.jsxs)("section",{className:"space-y-3",children:[(0,t.jsxs)("div",{className:"flex flex-wrap items-center gap-x-2 text-xs text-muted-foreground",children:[a.identifier?(0,t.jsx)("span",{children:a.identifier}):null,a.projectName?(0,t.jsx)("span",{children:a.projectName}):null]}),(0,t.jsx)("h1",{className:"break-words text-xl font-semibold",children:a.title}),(0,t.jsxs)("div",{className:"flex flex-wrap items-center gap-3",children:[(0,t.jsx)(A0,{status:a.status}),(0,t.jsx)(ive,{priority:a.priority,showLabel:!0}),a.assignee?(0,t.jsx)(wQ,{actor:a.assignee}):null,e.activeRun?(0,t.jsx)(qfs,{agentName:e.activeRun.agentName}):null]}),(0,t.jsxs)("p",{className:"text-xs text-muted-foreground",children:["Created ",yr(a.createdAt)," · Updated ",gr(a.updatedAt),a.completedAt?` · Completed ${yr(a.completedAt)}`:""]})]}),a.description?(0,t.jsx)(An,{className:"text-sm",softBreaks:!0,linkIssueReferences:!1,resolveImageSrc:i,children:a.description}):null,e.related.length>0?(0,t.jsx)(pC,{title:"Related tasks",children:(0,t.jsx)("ul",{className:"space-y-2",children:e.related.map(o=>(0,t.jsx)(Ufs,{related:o,token:s,isSharedRoot:e.isSharedRoot},`${o.relation}:${o.id}`))})}):null,e.documents.length>0?(0,t.jsx)(pC,{title:"Documents",children:(0,t.jsx)("div",{className:"space-y-2",children:e.documents.map(o=>(0,t.jsx)(Qfs,{document:o,resolveImageSrc:i},o.key))})}):null,e.attachments.length>0?(0,t.jsx)(pC,{title:"Attachments",children:(0,t.jsx)(L9e,{attachments:e.attachments})}):null,e.workProducts.length>0?(0,t.jsx)(pC,{title:"Work products",children:(0,t.jsx)("ul",{className:"space-y-2",children:e.workProducts.map(o=>(0,t.jsx)(Wfs,{product:o},o.id))})}):null,(0,t.jsx)(pC,{title:"Activity",children:e.comments.length>0?(0,t.jsx)("ol",{className:"space-y-3",children:e.comments.map(o=>(0,t.jsx)(Kfs,{comment:o,resolveImageSrc:i},o.id))}):(0,t.jsx)("p",{className:"text-sm text-muted-foreground",children:"No updates yet."})})]})]})}r(Hfs,"PublicIssueShareContent");function Cge(){const{token:e="",issueId:s}=xa();Bfs();const n=tUe.test(e),a=te({queryKey:D.publicShare.view(e,s??null),queryFn:r(()=>s?Gk.getPublicShareIssue(e,s):Gk.getPublicShare(e),"queryFn"),enabled:n,retry:!1,refetchOnWindowFocus:!0,refetchInterval:r(i=>i.state.data?.activeRun?$fs:!1,"refetchInterval")});return!n||a.data===null?(0,t.jsx)(Sge,{title:"This link is not available",body:"It may have been revoked, or the address is incomplete."}):a.data?(0,t.jsx)(Hfs,{view:a.data,token:e}):a.isError?(0,t.jsx)(Sge,{title:"Couldn't load this page",body:"Check your connection and try again.",action:(0,t.jsx)($,{variant:"outline",size:"sm",className:"mt-2",onClick:r(()=>{a.refetch()},"onClick"),children:"Try again"})}):(0,t.jsx)("div",{className:"h-dvh overflow-y-auto px-4 py-6","aria-busy":"true",children:(0,t.jsxs)("div",{className:"mx-auto max-w-3xl space-y-4",children:[(0,t.jsx)(yn,{className:"h-6 w-1/2"}),(0,t.jsx)(yn,{className:"h-4 w-1/3"}),(0,t.jsx)(yn,{className:"h-24 w-full"})]})})}r(Cge,"PublicIssueSharePage");function Vfs(){const{selectedCompany:e,selectedCompanyId:s}=fs(),{setBreadcrumbs:n}=Vn(),{pushToast:a}=Ti(),i=wt(),[o,l]=(0,m.useState)("pending_approval"),[c,d]=(0,m.useState)("all");(0,m.useEffect)(()=>{n([{label:e?.name??"Organization",href:"/dashboard"},{label:"Inbox",href:"/inbox"},{label:"Join Requests"}])},[e?.name,n]);const u=te({queryKey:D.access.joinRequests(s??"",`${o}:${c}`),queryFn:r(()=>or.listJoinRequests(s,o,c==="all"?void 0:c),"queryFn"),enabled:!!s}),h=we({mutationFn:r(f=>or.approveJoinRequest(s,f),"mutationFn"),onSuccess:r(async()=>{await i.invalidateQueries({queryKey:D.access.joinRequests(s,`${o}:${c}`)}),await i.invalidateQueries({queryKey:D.access.companyMembers(s)}),await i.invalidateQueries({queryKey:D.access.companyUserDirectory(s)}),a({title:"Join request approved",tone:"success"})},"onSuccess")}),p=we({mutationFn:r(f=>or.rejectJoinRequest(s,f),"mutationFn"),onSuccess:r(async()=>{await i.invalidateQueries({queryKey:D.access.joinRequests(s,`${o}:${c}`)}),a({title:"Join request rejected",tone:"success"})},"onSuccess")});if(!s)return(0,t.jsx)("div",{className:"text-sm text-muted-foreground",children:"Select an organization to review join requests."});if(u.isLoading)return(0,t.jsx)("div",{className:"text-sm text-muted-foreground",children:"Loading join requests…"});if(u.error){const f=u.error instanceof nn&&u.error.status===403?"You do not have permission to review join requests for this organization.":u.error instanceof Error?u.error.message:"Failed to load join requests.";return(0,t.jsx)("div",{className:"text-sm text-destructive",children:f})}return(0,t.jsxs)("div",{className:"max-w-6xl space-y-6",children:[(0,t.jsxs)("div",{className:"space-y-3",children:[(0,t.jsxs)("div",{className:"flex items-center gap-2",children:[(0,t.jsx)(XKe,{className:"h-5 w-5 text-muted-foreground"}),(0,t.jsx)("h1",{className:"text-lg font-semibold",children:"Join Request Queue"})]}),(0,t.jsx)("p",{className:"max-w-3xl text-sm text-muted-foreground",children:"Review human and agent join requests outside the mixed inbox feed. This queue uses the same approval mutations as the inline inbox cards."})]}),(0,t.jsxs)(sn,{className:"flex-row flex-wrap gap-3 p-4",children:[(0,t.jsxs)("label",{className:"space-y-2 text-sm",children:[(0,t.jsx)("span",{className:"font-medium",children:"Status"}),(0,t.jsxs)("select",{className:"rounded-md border border-border bg-background px-3 py-2",value:o,onChange:r(f=>l(f.target.value),"onChange"),children:[(0,t.jsx)("option",{value:"pending_approval",children:"Pending approval"}),(0,t.jsx)("option",{value:"approved",children:"Approved"}),(0,t.jsx)("option",{value:"rejected",children:"Rejected"})]})]}),(0,t.jsxs)("label",{className:"space-y-2 text-sm",children:[(0,t.jsx)("span",{className:"font-medium",children:"Request type"}),(0,t.jsxs)("select",{className:"rounded-md border border-border bg-background px-3 py-2",value:c,onChange:r(f=>d(f.target.value),"onChange"),children:[(0,t.jsx)("option",{value:"all",children:"All"}),(0,t.jsx)("option",{value:"human",children:"Human"}),(0,t.jsx)("option",{value:"agent",children:"Agent"})]})]})]}),(0,t.jsx)("div",{className:"space-y-4",children:(u.data??[]).length===0?(0,t.jsx)("div",{className:"rounded-xl border border-dashed border-border px-4 py-8 text-sm text-muted-foreground",children:"No join requests match the current filters."}):u.data.map(f=>(0,t.jsxs)(sn,{className:"block p-4",children:[(0,t.jsxs)("div",{className:"flex flex-wrap items-start justify-between gap-4",children:[(0,t.jsxs)("div",{className:"space-y-2",children:[(0,t.jsxs)("div",{className:"flex flex-wrap items-center gap-2",children:[(0,t.jsx)(ot,{variant:f.status==="pending_approval"?"secondary":f.status==="approved"?"outline":"destructive",children:f.status.replace("_"," ")}),(0,t.jsx)(ot,{variant:"outline",children:f.requestType}),f.adapterType?(0,t.jsx)(ot,{variant:"outline",children:f.adapterType}):null]}),(0,t.jsxs)("div",{children:[(0,t.jsx)("div",{className:"text-base font-medium",children:f.requestType==="human"?f.requesterUser?.name||f.requestEmailSnapshot||f.requestingUserId||"Unknown human requester":f.agentName||"Unknown agent requester"}),(0,t.jsx)("div",{className:"text-sm text-muted-foreground",children:f.requestType==="human"?f.requesterUser?.email||f.requestEmailSnapshot||f.requestingUserId:f.capabilities||f.requestIp})]})]}),f.status==="pending_approval"?(0,t.jsxs)("div",{className:"flex gap-2",children:[(0,t.jsx)($,{variant:"outline",onClick:r(()=>p.mutate(f.id),"onClick"),disabled:p.isPending,children:"Reject"}),(0,t.jsx)($,{onClick:r(()=>h.mutate(f.id),"onClick"),disabled:h.isPending,children:"Approve"})]}):null]}),(0,t.jsxs)("div",{className:"mt-4 grid gap-3 text-sm text-muted-foreground md:grid-cols-2",children:[(0,t.jsxs)("div",{className:"rounded-lg border border-border bg-background px-3 py-2",children:[(0,t.jsx)("div",{className:"text-xs font-medium uppercase tracking-wide",children:"Invite context"}),(0,t.jsx)("div",{className:"mt-2",children:f.invite?`${f.invite.allowedJoinTypes} join invite${f.invite.humanRole?` • default role ${f.invite.humanRole}`:""}`:"Invite metadata unavailable"}),f.invite?.inviteMessage?(0,t.jsx)("div",{className:"mt-2 text-foreground",children:f.invite.inviteMessage}):null]}),(0,t.jsxs)("div",{className:"rounded-lg border border-border bg-background px-3 py-2",children:[(0,t.jsx)("div",{className:"text-xs font-medium uppercase tracking-wide",children:"Request details"}),(0,t.jsxs)("div",{className:"mt-2",children:["Submitted ",new Date(f.createdAt).toLocaleString()]}),(0,t.jsxs)("div",{children:["Source IP ",f.requestIp]}),f.requestType==="agent"&&f.capabilities?(0,t.jsx)("div",{children:f.capabilities}):null]})]})]},f.id))})]})}r(Vfs,"JoinRequestQueue");var Gfs=(0,m.lazy)(()=>bd(()=>import("./CompanyExport-kpky2xuC.js").then(e=>({default:e.CompanyExport})),__vite__mapDeps([6,5,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25]))),Yfs=(0,m.lazy)(()=>bd(()=>import("./Agents.production-DbtoAoUQ.js").then(e=>({default:e.Agents})),__vite__mapDeps([26,5,7,9,8,27,28,29,30,31,15,32,33,34,35,36,19,37,23,24,25]))),Zfs=(0,m.lazy)(()=>bd(()=>import("./Routines.production-CWKuR092.js").then(e=>({default:e.Routines})),__vite__mapDeps([38,5,7,8,9,39,28,40,33,16,17,21,41,14,15,27,29,30,31,42,43,44,45,46,10,11,12,34,47,48,49,35,50,51,20,36,52,53,54,37,55,23,24,25,32,22,19]))),_ge=(0,m.lazy)(()=>bd(()=>import("./RoutineDetail.production-B1919-qY.js").then(e=>({default:e.RoutineDetail})),__vite__mapDeps([56,5,7,8,9,39,28,40,33,16,17,21,41,14,15,27,29,30,31,42,43,44,45,46,10,11,12,34,47,48,49,35,50,51,20,36,52,53,54,37,55,23,24,25,57,58,22,19]))),Jfs=(0,m.lazy)(()=>bd(()=>import("./CompanySkills.production-BuVkNosy.js").then(e=>({default:e.CompanySkills})),__vite__mapDeps([59,5,7,8,9,27,28,29,30,31,15,42,16,40,33,17,21,44,14,45,46,32,10,11,12,60,58,52,25,48,18,13,19,61,49,22,23,24]))),Xfs=(0,m.lazy)(()=>bd(()=>import("./CompanyActivity.production-Bx3wHHDp.js").then(e=>({default:e.CompanyActivity})),__vite__mapDeps([62,5,7,8,9,31,15,32,33,47,45,30,16,48,22,19,52,53,54,55,23]))),exs=(0,m.lazy)(()=>bd(()=>import("./Terminal-BTETQQTg.js").then(e=>({default:e.Terminal})),__vite__mapDeps([63,5,7,8,9,40,33,28,16,17,21,43,52,53,37]))),txs=(0,m.lazy)(()=>bd(()=>import("./OrgChart.production-D-XB4GXh.js").then(e=>({default:e.OrgChart})),__vite__mapDeps([64,5,7,8,9,31,15,50,51,19,55,23,24,25])));function Xg({children:e}){return(0,t.jsx)(m.Suspense,{fallback:(0,t.jsx)(ch,{}),children:e})}r(Xg,"ProductionSurface");function sxs(e,s){const n=e&&s;return(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)(rt,{index:!0,element:(0,t.jsx)(In,{to:"dashboard",replace:!0})}),(0,t.jsx)(rt,{path:"dashboard",element:(0,t.jsx)(fAt,{})}),(0,t.jsx)(rt,{path:"dashboard/live",element:(0,t.jsx)(xAt,{})}),(0,t.jsx)(rt,{path:"timeline",element:e?(0,t.jsx)(_p,{to:"/activity/timeline"}):(0,t.jsx)(l6e,{})}),(0,t.jsx)(rt,{path:"onboarding",element:(0,t.jsx)(D9e,{})}),(0,t.jsx)(rt,{path:"companies",element:(0,t.jsx)(sIt,{})}),(0,t.jsx)(rt,{path:"company/settings",element:(0,t.jsx)(Iss,{})}),(0,t.jsx)(rt,{path:"company/settings/connections",element:(0,t.jsx)(Ess,{})}),(0,t.jsx)(rt,{path:"company/settings/environments",element:(0,t.jsx)(In,{to:"/company/settings/instance/environments",replace:!0})}),(0,t.jsx)(rt,{path:"company/settings/cloud-upstream",element:(0,t.jsx)(In,{to:"/company/export",replace:!0})}),(0,t.jsxs)(rt,{element:(0,t.jsx)(y0,{pageKey:"company.members"}),children:[(0,t.jsx)(rt,{path:"company/settings/members",element:(0,t.jsx)(jns,{})}),(0,t.jsx)(rt,{path:"company/settings/access",element:(0,t.jsx)(wns,{})})]}),(0,t.jsx)(rt,{element:(0,t.jsx)(y0,{pageKey:"company.invites"}),children:(0,t.jsx)(rt,{path:"company/settings/invites",element:(0,t.jsx)(In,{to:"/company/settings/members?tab=invites",replace:!0})})}),(0,t.jsx)(rt,{element:(0,t.jsx)(y0,{pageKey:"company.export"}),children:(0,t.jsx)(rt,{path:"company/export/*",element:(0,t.jsx)(m.Suspense,{fallback:(0,t.jsx)(ch,{}),children:(0,t.jsx)(Gfs,{})})})}),(0,t.jsx)(rt,{element:(0,t.jsx)(hgt,{}),children:(0,t.jsx)(rt,{element:(0,t.jsx)(y0,{pageKey:"company.import"}),children:(0,t.jsx)(rt,{path:"company/import",element:(0,t.jsx)(Q0s,{})})})}),(0,t.jsx)(rt,{element:(0,t.jsx)(y0,{pageKey:"company.secrets"}),children:(0,t.jsx)(rt,{path:"company/settings/secrets",element:(0,t.jsx)(Fhs,{})})}),(0,t.jsx)(rt,{path:"company/settings/tools",element:(0,t.jsx)(Tge,{})}),(0,t.jsx)(rt,{path:"company/settings/tools/:tab",element:(0,t.jsx)(Tge,{})}),(0,t.jsx)(rt,{path:"tools",element:(0,t.jsx)(Rge,{})}),(0,t.jsx)(rt,{path:"tools/:tab",element:(0,t.jsx)(Rge,{})}),(0,t.jsx)(rt,{path:"apps",element:(0,t.jsx)(gas,{})}),(0,t.jsx)(rt,{path:"apps/assistant-connection",element:(0,t.jsx)(Xrs,{})}),(0,t.jsx)(rt,{path:"apps/browse",element:(0,t.jsx)(In,{to:"/apps",replace:!0})}),(0,t.jsx)(rt,{path:"apps/connections",element:(0,t.jsx)(In,{to:"/apps",replace:!0})}),(0,t.jsx)(rt,{path:"apps/byo",element:(0,t.jsx)(nPe,{byoOnly:!0})}),(0,t.jsx)(rt,{path:"apps/vercel-connect",element:(0,t.jsx)(Age,{credentialSource:"vercel_connect"})}),(0,t.jsx)(rt,{path:"apps/connect",element:(0,t.jsx)(Age,{})}),(0,t.jsx)(rt,{path:"apps/chat/connect",element:(0,t.jsx)(wT,{children:(0,t.jsx)(His,{})})}),(0,t.jsx)(rt,{path:"apps/chat/:endpointId",element:(0,t.jsx)(wT,{children:(0,t.jsx)(In,{to:"settings",replace:!0})})}),(0,t.jsx)(rt,{path:"apps/chat/:endpointId/reviews/:reviewId",element:(0,t.jsx)(wT,{children:(0,t.jsx)(Nfe,{})})}),(0,t.jsx)(rt,{path:"apps/chat/:endpointId/:tab",element:(0,t.jsx)(wT,{children:(0,t.jsx)(Nfe,{})})}),(0,t.jsx)(rt,{path:"apps/connect/:appKey",element:(0,t.jsx)(In,{to:"/apps",replace:!0})}),(0,t.jsx)(rt,{path:"apps/connect/:appKey/:stage",element:(0,t.jsx)(In,{to:"/apps",replace:!0})}),(0,t.jsx)(rt,{path:"apps/review",element:(0,t.jsx)(Els,{})}),(0,t.jsx)(rt,{path:"apps/attention",element:(0,t.jsx)(In,{to:"/apps",replace:!0})}),(0,t.jsx)(rt,{path:"apps/gateways",element:(0,t.jsx)(Ife,{})}),(0,t.jsx)(rt,{path:"apps/gateways/:gatewayId",element:(0,t.jsx)(In,{to:"overview",replace:!0})}),(0,t.jsx)(rt,{path:"apps/gateways/:gatewayId/:tab",element:(0,t.jsx)(lcs,{})}),(0,t.jsx)(rt,{path:"apps/advanced",element:(0,t.jsx)(Kpe,{})}),(0,t.jsx)(rt,{path:"apps/advanced/gateways",element:(0,t.jsx)(Ife,{})}),(0,t.jsx)(rt,{path:"apps/advanced/profiles/new",element:(0,t.jsx)(Gpe,{mode:"new"})}),(0,t.jsx)(rt,{path:"apps/advanced/profiles/:profileId/edit",element:(0,t.jsx)(Gpe,{mode:"edit"})}),(0,t.jsx)(rt,{path:"apps/advanced/profiles/:profileId",element:(0,t.jsx)(zrs,{})}),(0,t.jsx)(rt,{path:"apps/advanced/audit",element:(0,t.jsx)(In,{to:"/apps",replace:!0})}),(0,t.jsx)(rt,{path:"apps/advanced/run-your-own",element:(0,t.jsx)(In,{to:"/apps",replace:!0})}),(0,t.jsx)(rt,{path:"apps/advanced/:tab",element:(0,t.jsx)(Kpe,{})}),(0,t.jsx)(rt,{path:"apps/app/:applicationId",element:(0,t.jsx)(Cfe,{})}),(0,t.jsx)(rt,{path:"apps/app/:applicationId/:tab",element:(0,t.jsx)(Cfe,{})}),(0,t.jsx)(rt,{path:"apps/:connectionId",element:(0,t.jsx)(In,{to:"permissions",replace:!0})}),(0,t.jsx)(rt,{path:"apps/:connectionId/:tab",element:(0,t.jsx)(pis,{})}),(0,t.jsx)(rt,{path:"company/settings/instance",element:(0,t.jsx)(In,{to:"/company/settings",replace:!0})}),(0,t.jsx)(rt,{element:(0,t.jsx)(y0,{pageKey:"instance.profile"}),children:(0,t.jsx)(rt,{path:"company/settings/instance/profile",element:(0,t.jsx)(Jps,{})})}),(0,t.jsx)(rt,{path:"company/settings/instance/general",element:(0,t.jsx)(In,{to:"/company/settings",replace:!0})}),(0,t.jsx)(rt,{path:"company/settings/instance/heartbeats",element:(0,t.jsx)(In,{to:"/company/settings",replace:!0})}),(0,t.jsxs)(rt,{element:(0,t.jsx)(y0,{pageKey:"instance.environments"}),children:[(0,t.jsx)(rt,{path:"company/settings/instance/environments",element:(0,t.jsx)(iB,{})}),(0,t.jsx)(rt,{path:"company/settings/instance/environments/new",element:(0,t.jsx)(iB,{mode:"create"})}),(0,t.jsx)(rt,{path:"company/settings/instance/environments/:environmentId/edit",element:(0,t.jsx)(iB,{mode:"edit"})})]}),(0,t.jsx)(rt,{element:(0,t.jsx)(y0,{pageKey:"instance.access"}),children:(0,t.jsx)(rt,{path:"company/settings/instance/access",element:(0,t.jsx)(Kps,{})})}),(0,t.jsx)(rt,{element:(0,t.jsx)(y0,{pageKey:"instance.experimental"}),children:(0,t.jsx)(rt,{path:"company/settings/instance/experimental",element:(0,t.jsx)(Ups,{})})}),(0,t.jsxs)(rt,{element:(0,t.jsx)(y0,{pageKey:"instance.plugins"}),children:[(0,t.jsx)(rt,{path:"company/settings/instance/plugins",element:(0,t.jsx)(efs,{})}),(0,t.jsx)(rt,{path:"company/settings/instance/plugins/:pluginId",element:(0,t.jsx)(tfs,{})})]}),(0,t.jsx)(rt,{element:(0,t.jsx)(y0,{pageKey:"instance.adapters"}),children:(0,t.jsx)(rt,{path:"company/settings/instance/adapters",element:(0,t.jsx)(uge,{})})}),(0,t.jsx)(rt,{path:"company/settings/:settingsRoutePath/*",element:(0,t.jsx)(pns,{})}),(0,t.jsx)(rt,{path:"skills/sources",element:(0,t.jsx)(txe,{})}),(0,t.jsx)(rt,{path:"skills/sources/:sourceId",element:(0,t.jsx)(txe,{})}),(0,t.jsx)(rt,{path:"skills/studio",element:(0,t.jsx)(EB,{})}),(0,t.jsx)(rt,{path:"skills/studio/new",element:(0,t.jsx)(EB,{})}),(0,t.jsx)(rt,{path:"skills/studio/:skillId",element:(0,t.jsx)(EB,{})}),(0,t.jsx)(rt,{path:"skills/:skillId/studio",element:(0,t.jsx)(M9e,{})}),(0,t.jsx)(rt,{path:"skills/*",element:e?(0,t.jsx)(kds,{}):(0,t.jsx)(Xg,{children:(0,t.jsx)(Jfs,{})})}),(0,t.jsx)(rt,{path:"settings",element:(0,t.jsx)(Ry,{})}),(0,t.jsx)(rt,{path:"settings/*",element:(0,t.jsx)(Ry,{})}),(0,t.jsx)(rt,{path:"plugins/:pluginId",element:(0,t.jsx)(mge,{})}),(0,t.jsx)(rt,{path:"org",element:e?(0,t.jsx)(In,{to:"/agents/all",replace:!0}):(0,t.jsx)(Xg,{children:(0,t.jsx)(txs,{})})}),(0,t.jsx)(rt,{path:"agents",element:(0,t.jsx)(In,{to:"/agents/all",replace:!0})}),sY.map(a=>(0,t.jsx)(rt,{path:`agents/${a}`,element:e?(0,t.jsx)(YIt,{}):(0,t.jsx)(Xg,{children:(0,t.jsx)(Yfs,{})})},a)),(0,t.jsx)(rt,{path:"agents/new",element:(0,t.jsx)(vfs,{})}),(0,t.jsx)(rt,{path:"agents/:agentId",element:(0,t.jsx)(N$,{})}),(0,t.jsx)(rt,{path:"agents/:agentId/:tab",element:(0,t.jsx)(N$,{})}),(0,t.jsx)(rt,{path:"agents/:agentId/runs/:runId",element:(0,t.jsx)(N$,{})}),(0,t.jsx)(rt,{path:"projects",element:(0,t.jsx)(gRt,{})}),(0,t.jsx)(rt,{path:"projects/:projectId",element:(0,t.jsx)(Hv,{})}),(0,t.jsx)(rt,{path:"projects/:projectId/overview",element:(0,t.jsx)(Hv,{})}),(0,t.jsx)(rt,{path:"projects/:projectId/issues",element:(0,t.jsx)(Hv,{})}),(0,t.jsx)(rt,{path:"projects/:projectId/issues/:filter",element:(0,t.jsx)(Hv,{})}),(0,t.jsx)(rt,{element:(0,t.jsx)(_D,{}),children:(0,t.jsx)(rt,{path:"projects/:projectId/workspaces/:workspaceId",element:(0,t.jsx)(pLt,{})})}),(0,t.jsx)(rt,{path:"projects/:projectId/workspaces",element:(0,t.jsx)(Hv,{})}),(0,t.jsx)(rt,{path:"projects/:projectId/configuration",element:(0,t.jsx)(Hv,{})}),(0,t.jsx)(rt,{path:"projects/:projectId/budget",element:(0,t.jsx)(Hv,{})}),(0,t.jsx)(rt,{element:(0,t.jsx)(_D,{}),children:(0,t.jsx)(rt,{path:"workspaces",element:(0,t.jsx)(gLt,{})})}),(0,t.jsx)(rt,{path:"terminal",element:(0,t.jsx)(Xg,{children:(0,t.jsx)(exs,{})})}),(0,t.jsx)(rt,{path:"issues",element:(0,t.jsx)(zMt,{})}),(0,t.jsx)(rt,{path:"tasks",element:(0,t.jsx)(In,{to:"/issues",replace:!0})}),(0,t.jsx)(rt,{path:"search",element:(0,t.jsx)(o7t,{})}),n?(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)(rt,{path:"issues/all",element:(0,t.jsx)(Lh,{view:"all"})}),(0,t.jsx)(rt,{path:"issues/active",element:(0,t.jsx)(Lh,{view:"active"})}),(0,t.jsx)(rt,{path:"issues/backlog",element:(0,t.jsx)(Lh,{view:"backlog"})}),(0,t.jsx)(rt,{path:"issues/done",element:(0,t.jsx)(Lh,{view:"done"})}),(0,t.jsx)(rt,{path:"issues/recent",element:(0,t.jsx)(Lh,{view:"recent"})})]}):(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)(rt,{path:"issues/all",element:(0,t.jsx)(In,{to:"/issues",replace:!0})}),(0,t.jsx)(rt,{path:"issues/active",element:(0,t.jsx)(In,{to:"/issues",replace:!0})}),(0,t.jsx)(rt,{path:"issues/backlog",element:(0,t.jsx)(In,{to:"/issues",replace:!0})}),(0,t.jsx)(rt,{path:"issues/done",element:(0,t.jsx)(In,{to:"/issues",replace:!0})}),(0,t.jsx)(rt,{path:"issues/recent",element:(0,t.jsx)(In,{to:"/issues",replace:!0})})]}),(0,t.jsx)(rt,{path:"chats",element:(0,t.jsx)(bUt,{})}),(0,t.jsx)(rt,{path:"chats/:agentRef",element:(0,t.jsx)(yUt,{})}),(0,t.jsx)(rt,{path:"issues/:issueId",element:(0,t.jsx)(hUt,{})}),null,(0,t.jsx)(rt,{path:"routines",element:e?(0,t.jsx)(XUt,{}):(0,t.jsx)(Xg,{children:(0,t.jsx)(Zfs,{})})}),(0,t.jsx)(rt,{path:"cases",element:(0,t.jsx)(lie,{children:(0,t.jsx)(Lgt,{})})}),(0,t.jsx)(rt,{path:"cases/:caseIdentifier",element:(0,t.jsx)(lie,{children:(0,t.jsx)(byt,{})})}),(0,t.jsx)(rt,{path:"pixels-office",element:(0,t.jsx)(mgt,{children:(0,t.jsx)(TZt,{})})}),(0,t.jsx)(rt,{path:"status",element:(0,t.jsx)(cie,{children:(0,t.jsx)($he,{})})}),(0,t.jsx)(rt,{path:"status/:cardId",element:(0,t.jsx)(cie,{children:(0,t.jsx)($he,{})})}),(0,t.jsx)(rt,{path:"status-cards",element:(0,t.jsx)(Ege,{})}),(0,t.jsx)(rt,{path:"status-cards/:cardId",element:(0,t.jsx)(Ege,{})}),(0,t.jsx)(rt,{path:"review-queue",element:(0,t.jsx)(Qg,{children:(0,t.jsx)(gWt,{})})}),(0,t.jsx)(rt,{path:"learnings",element:(0,t.jsx)(Qg,{children:(0,t.jsx)(vWt,{})})}),(0,t.jsx)(rt,{path:"pipelines",element:(0,t.jsx)(Qg,{children:(0,t.jsx)(LO,{})})}),(0,t.jsx)(rt,{path:"pipelines/:pipelineId",element:(0,t.jsx)(Qg,{children:(0,t.jsx)(LO,{})})}),(0,t.jsx)(rt,{path:"pipelines/:pipelineId/add",element:(0,t.jsx)(Qg,{children:(0,t.jsx)(LO,{})})}),(0,t.jsx)(rt,{path:"pipelines/:pipelineId/settings",element:(0,t.jsx)(Qg,{children:(0,t.jsx)(mHt,{})})}),(0,t.jsx)(rt,{path:"pipelines/:pipelineId/items/:caseId",element:(0,t.jsx)(Qg,{children:(0,t.jsx)($Qt,{})})}),(0,t.jsx)(rt,{path:"pipelines/:pipelineId/cases/:caseId",element:(0,t.jsx)(Qg,{children:(0,t.jsx)(MQt,{})})}),(0,t.jsx)(rt,{path:"routines/:routineId",element:e?(0,t.jsx)(B0e,{}):(0,t.jsx)(Xg,{children:(0,t.jsx)(_ge,{})})}),(0,t.jsx)(rt,{path:"routines/:routineId/:section",element:e?(0,t.jsx)(B0e,{}):(0,t.jsx)(Xg,{children:(0,t.jsx)(_ge,{})})}),(0,t.jsx)(rt,{element:(0,t.jsx)(_D,{}),children:(0,t.jsxs)(rt,{element:(0,t.jsx)(fgt,{}),children:[(0,t.jsx)(rt,{path:"execution-workspaces/:workspaceId",element:(0,t.jsx)(k1,{})}),(0,t.jsx)(rt,{path:"execution-workspaces/:workspaceId/services",element:(0,t.jsx)(k1,{})}),(0,t.jsx)(rt,{path:"execution-workspaces/:workspaceId/configuration",element:(0,t.jsx)(k1,{})}),(0,t.jsx)(rt,{path:"execution-workspaces/:workspaceId/runtime-logs",element:(0,t.jsx)(k1,{})}),(0,t.jsx)(rt,{path:"execution-workspaces/:workspaceId/issues",element:(0,t.jsx)(k1,{})}),(0,t.jsx)(rt,{path:"execution-workspaces/:workspaceId/routines",element:(0,t.jsx)(k1,{})})]})}),(0,t.jsx)(rt,{path:"goals",element:(0,t.jsx)(AXt,{})}),(0,t.jsx)(rt,{path:"goals/:goalId",element:(0,t.jsx)(BXt,{})}),(0,t.jsx)(rt,{path:"artifacts",element:(0,t.jsx)(U0e,{})}),(0,t.jsx)(rt,{path:"approvals",element:(0,t.jsx)(In,{to:"/approvals/pending",replace:!0})}),(0,t.jsx)(rt,{path:"approvals/pending",element:(0,t.jsx)(Q0e,{})}),(0,t.jsx)(rt,{path:"approvals/all",element:(0,t.jsx)(Q0e,{})}),(0,t.jsx)(rt,{path:"approvals/:approvalId",element:(0,t.jsx)(FXt,{})}),(0,t.jsx)(rt,{path:"activity",element:e?(0,t.jsx)(Des,{}):(0,t.jsx)(Xg,{children:(0,t.jsx)(Xfs,{})})}),e?(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)(rt,{path:"activity/runs",element:(0,t.jsx)(qC,{section:"runs"})}),(0,t.jsx)(rt,{path:"activity/costs",element:(0,t.jsx)(qC,{section:"costs"})}),(0,t.jsx)(rt,{path:"activity/budgets",element:(0,t.jsx)(qC,{section:"budgets"})}),(0,t.jsx)(rt,{path:"activity/timeline",element:(0,t.jsx)(qC,{section:"timeline"})}),(0,t.jsx)(rt,{path:"audit",element:(0,t.jsx)(_p,{to:"/activity",forceAgentMode:!0})}),(0,t.jsx)(rt,{path:"audit/activity",element:(0,t.jsx)(_p,{to:"/activity"})}),(0,t.jsx)(rt,{path:"audit/runs",element:(0,t.jsx)(_p,{to:"/activity/runs"})}),(0,t.jsx)(rt,{path:"audit/costs",element:(0,t.jsx)(_p,{to:"/activity/costs"})}),(0,t.jsx)(rt,{path:"audit/budgets",element:(0,t.jsx)(_p,{to:"/activity/budgets"})}),(0,t.jsx)(rt,{path:"audit/timeline",element:(0,t.jsx)(_p,{to:"/activity/timeline"})}),(0,t.jsx)(rt,{path:"runs",element:(0,t.jsx)(_p,{to:"/activity/runs"})}),(0,t.jsx)(rt,{path:"costs",element:(0,t.jsx)(_p,{to:"/activity/costs"})}),(0,t.jsx)(rt,{path:"budgets",element:(0,t.jsx)(_p,{to:"/activity/budgets"})})]}):(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)(rt,{path:"costs",element:(0,t.jsx)(zK,{})}),(0,t.jsx)(rt,{path:"audit",element:(0,t.jsx)(In,{to:"/activity?mode=agents",replace:!0})})]}),(0,t.jsxs)(rt,{element:(0,t.jsx)(xpt,{}),children:[(0,t.jsx)(rt,{path:"board-chat",element:(0,t.jsx)(sss,{})}),(0,t.jsx)(rt,{path:"artifacts",element:(0,t.jsx)(U0e,{})})]}),null,(0,t.jsx)(rt,{path:"decisions",element:(0,t.jsx)(_ts,{})}),(0,t.jsx)(rt,{path:"decisions/queues/:key",element:(0,t.jsx)(Rts,{})}),n?(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)(rt,{path:"inbox",element:(0,t.jsx)(Ige,{})}),(0,t.jsx)(rt,{path:"inbox/mine",element:(0,t.jsx)(Lh,{view:"mine"})}),(0,t.jsx)(rt,{path:"inbox/recent",element:(0,t.jsx)(Lh,{view:"recent"})}),(0,t.jsx)(rt,{path:"inbox/unread",element:(0,t.jsx)(Lh,{view:"unread"})}),(0,t.jsx)(rt,{path:"inbox/blocked",element:(0,t.jsx)(Lh,{view:"blocked"})}),(0,t.jsx)(rt,{path:"inbox/all",element:(0,t.jsx)(Lh,{view:"everything"})}),(0,t.jsx)(rt,{path:"inbox/new",element:(0,t.jsx)(Lh,{view:"mine"})})]}):(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)(rt,{path:"inbox",element:(0,t.jsx)(Ige,{})}),(0,t.jsx)(rt,{path:"inbox/mine",element:(0,t.jsx)(q1,{})}),(0,t.jsx)(rt,{path:"inbox/recent",element:(0,t.jsx)(q1,{})}),(0,t.jsx)(rt,{path:"inbox/unread",element:(0,t.jsx)(q1,{})}),(0,t.jsx)(rt,{path:"inbox/blocked",element:(0,t.jsx)(q1,{})}),(0,t.jsx)(rt,{path:"inbox/all",element:(0,t.jsx)(q1,{})}),(0,t.jsx)(rt,{path:"inbox/new",element:(0,t.jsx)(In,{to:"/inbox/mine",replace:!0})})]}),(0,t.jsx)(rt,{path:"inbox/requests",element:(0,t.jsx)(Vfs,{})}),(0,t.jsx)(rt,{path:"u/:userSlug",element:(0,t.jsx)(sXt,{})}),(0,t.jsx)(rt,{path:"design-guide",element:(0,t.jsx)(Bps,{})}),(0,t.jsx)(rt,{path:"instance/settings/adapters",element:(0,t.jsx)(uge,{})}),(0,t.jsx)(rt,{path:":pluginRoutePath/*",element:(0,t.jsx)(mge,{})}),(0,t.jsx)(rt,{path:"*",element:(0,t.jsx)(mm,{scope:"board"})})]})}r(sxs,"boardRoutes");function Age({credentialSource:e="paperclip_vault"}={}){const s=la(),n=new URLSearchParams(s.search),{enabled:a,githubEnabled:i}=sw();return ymt(n,{chatConnectorsEnabled:a,githubReviewBotsEnabled:i})?(0,t.jsx)(nPe,{credentialSource:e}):(0,t.jsx)(In,{to:"/apps",replace:!0})}r(Age,"AppsConnectEntryRoute");function Ige(){const{enabled:e}=Ec(),{enabled:s}=F3();return e&&s?(0,t.jsx)(Lh,{view:mBe(Gee())}):(0,t.jsx)(In,{to:`/inbox/${Gee()}`,replace:!0})}r(Ige,"InboxRootRedirect");function Lh({view:e}){const s=la(),n=new URLSearchParams(s.search);return n.set(qT,e),(0,t.jsx)(In,{to:`/issues?${n.toString()}${s.hash}`,replace:!0})}r(Lh,"TaskViewRedirect");function M9e(){const e=la(),{companies:s,selectedCompany:n,loading:a}=fs(),{companyPrefix:i,skillId:o}=xa();if(a)return null;const l=(i?s.find(c=>c.issuePrefix.toUpperCase()===i.toUpperCase()):null)??n??s[0]??null;return!l||!o?(0,t.jsx)(In,{to:"/skills/studio",replace:!0}):(0,t.jsx)(In,{to:`/${l.issuePrefix}/skills/studio/${encodeURIComponent(o)}${e.search}${e.hash}`,replace:!0})}r(M9e,"LegacySkillStudioRedirect");function Ry(){const e=la(),{companies:s,selectedCompany:n,loading:a}=fs(),{companyPrefix:i}=xa(),{hidden:o}=Eu();if(a)return(0,t.jsx)(ch,{});const l=(i?s.find(d=>d.issuePrefix.toUpperCase()===i.toUpperCase()):null)??n??s[0]??null;if(!l)return RV({pathname:e.pathname,hasCompanies:!1})?(0,t.jsx)(In,{to:"/onboarding",replace:!0}):(0,t.jsx)(KZ,{});const c=wVe(Dke(`${e.pathname}${e.search}${e.hash}`),o);return(0,t.jsx)(In,{to:`/${l.issuePrefix}${c}`,replace:!0})}r(Ry,"LegacySettingsRedirect");function Tge(){const{tab:e}=xa();return(0,t.jsx)(In,{to:P9e(e),replace:!0})}r(Tge,"LegacyToolsSettingsRedirect");function Rge(){const{tab:e}=xa();return(0,t.jsx)(In,{to:P9e(e),replace:!0})}r(Rge,"LegacyToolsRedirect");function P9e(e){return e?e==="applications"||e==="connections"||e==="overview"||e==="examples"||e==="runtime"||e==="audit"?"/apps":e==="policies"?"/apps/advanced/profiles":`/apps/advanced/${e}`:"/apps/advanced/profiles"}r(P9e,"legacyToolsRedirectTarget");function D9e(){const{companies:e}=fs(),{openOnboarding:s}=al(),{t:n}=lke(),a=td(),i=L5e(a?.cloudBaseUrl??null),{onboardingOpen:o,onboardingRouteDismissed:l}=AL(),{companyPrefix:c}=xa(),d=c?e.find(p=>p.issuePrefix.toUpperCase()===c.toUpperCase())??null:null;if(Aht({onboardingOpen:o,routeDismissed:l}))return null;const u=d?`Add another agent to ${d.name}`:e.length>0?"Create another organization":"Create your first organization",h=d?"Run onboarding again to add an agent and a starter task for this organization.":e.length>0?"Run onboarding again to create another organization and seed its first agent.":"Get started by creating an organization and your first agent.";return(0,t.jsx)("div",{className:"mx-auto max-w-xl py-10",children:(0,t.jsxs)("div",{className:"rounded-lg border border-border bg-card p-6",children:[(0,t.jsx)("h1",{className:"text-xl font-semibold",children:u}),(0,t.jsx)("p",{className:"mt-2 text-sm text-muted-foreground",children:h}),(0,t.jsx)("div",{className:"mt-4",children:!d&&a&&!i?(0,t.jsx)("p",{className:"text-sm text-muted-foreground",children:n("app.cloudCreateUnavailable",{defaultValue:"Organizations are created in Paperclip Cloud. This instance can't reach it right now — try again from your Cloud portfolio."})}):(0,t.jsx)($,{onClick:r(()=>d?s({initialStep:IE(),companyId:d.id}):a&&i?lh(i):s(),"onClick"),children:d?"Add Agent":"Start Onboarding"})})]})})}r(D9e,"OnboardingRoutePage");function nxs(){const{companies:e,selectedCompany:s,loading:n}=fs(),a=la();if(n)return(0,t.jsx)(ch,{});const i=s??e[0]??null;return i?(0,t.jsx)(In,{to:`/${i.issuePrefix}/dashboard`,replace:!0}):RV({pathname:a.pathname,hasCompanies:!1})?(0,t.jsx)(In,{to:"/onboarding",replace:!0}):(0,t.jsx)(KZ,{})}r(nxs,"CompanyRootRedirect");function Ege(){const{cardId:e}=xa(),s=IBe(),n=s?`/${s}`:"";return(0,t.jsx)(In,{to:`${n}/status${e?`/${e}`:""}`,replace:!0})}r(Ege,"StatusCardsLegacyRedirect");function _p({to:e,forceAgentMode:s=!1}){const n=la(),a=new URLSearchParams(n.search);s&&a.set("mode","agents");const i=a.toString();return(0,t.jsx)(In,{to:`${e}${i?`?${i}`:""}${n.hash}`,replace:!0})}r(_p,"AuditCompatibilityRedirect");function ya(){const e=la(),{companies:s,selectedCompany:n,loading:a}=fs();if(a)return(0,t.jsx)(ch,{});const i=n??s[0]??null;return i?(0,t.jsx)(In,{to:`/${i.issuePrefix}${e.pathname}${e.search}${e.hash}`,replace:!0}):RV({pathname:e.pathname,hasCompanies:!1})?(0,t.jsx)(In,{to:"/onboarding",replace:!0}):(0,t.jsx)(KZ,{})}r(ya,"UnprefixedBoardRedirect");function KZ(){const{openOnboarding:e}=al(),{t:s}=lke(),n=td(),a=L5e(n?.cloudBaseUrl??null);return(0,t.jsx)("div",{className:"mx-auto max-w-xl py-10",children:(0,t.jsxs)("div",{className:"rounded-lg border border-border bg-card p-6",children:[(0,t.jsx)("h1",{className:"text-xl font-semibold",children:s("app.noCompanies.title",{defaultValue:"Create your first organization"})}),(0,t.jsx)("p",{className:"mt-2 text-sm text-muted-foreground",children:s("app.noCompanies.description",{defaultValue:"Get started by creating an organization."})}),(0,t.jsx)("div",{className:"mt-4",children:n&&!a?(0,t.jsx)("p",{className:"text-sm text-muted-foreground",children:s("app.cloudCreateUnavailable",{defaultValue:"Organizations are created in Paperclip Cloud. This instance can't reach it right now — try again from your Cloud portfolio."})}):(0,t.jsx)($,{onClick:r(()=>n&&a?lh(a):e(),"onClick"),children:s("app.noCompanies.newCompany",{defaultValue:"New Organization"})})})]})})}r(KZ,"NoCompaniesStartPage");function rxs(){const{enabled:e,loaded:s}=Ec(),{enabled:n}=F3();return(0,t.jsxs)(t.Fragment,{children:[(0,t.jsxs)(hBe,{children:[(0,t.jsx)(rt,{path:"oauth-handoff",element:(0,t.jsx)(Fls,{})}),(0,t.jsx)(rt,{path:"auth",element:(0,t.jsx)(Sfs,{})}),(0,t.jsx)(rt,{path:"board-claim/:token",element:(0,t.jsx)(Cfs,{})}),(0,t.jsx)(rt,{path:"mcp-connect/:id",element:(0,t.jsx)(vge,{})}),(0,t.jsx)(rt,{path:"dot-connect/:id",element:(0,t.jsx)(vge,{agentPairingOnly:!0})}),(0,t.jsx)(rt,{path:"mcp-device",element:(0,t.jsx)(_fs,{})}),(0,t.jsx)(rt,{path:"assistant-connections",element:(0,t.jsx)(Afs,{})}),(0,t.jsx)(rt,{path:"cli-auth/:id",element:(0,t.jsx)(Ifs,{})}),(0,t.jsx)(rt,{path:"invite/:token",element:(0,t.jsx)(Dfs,{})}),(0,t.jsx)(rt,{path:"s/:token",element:(0,t.jsx)(Cge,{})}),(0,t.jsx)(rt,{path:"s/:token/issues/:issueId",element:(0,t.jsx)(Cge,{})}),(0,t.jsx)(rt,{element:s?(0,t.jsx)(roe,{allowMembershipRequest:!0}):(0,t.jsx)(ch,{}),children:(0,t.jsx)(rt,{path:"chat-identity/confirm",element:(0,t.jsx)(Tls,{})})}),(0,t.jsx)(rt,{path:"tests/perf/long-thread",element:(0,t.jsx)(RUt,{})}),(0,t.jsx)(rt,{path:"ux-lab/bootstrap-setup",element:(0,t.jsx)(dns,{})}),(0,t.jsx)(rt,{path:"ux-lab/responsible-user-denial",element:(0,t.jsx)(uns,{})}),(0,t.jsx)(rt,{path:"ux-lab/cross-issue-collaboration",element:(0,t.jsx)(hns,{})}),(0,t.jsxs)(rt,{element:s?(0,t.jsx)(roe,{}):(0,t.jsx)(ch,{}),children:[(0,t.jsx)(rt,{index:!0,element:(0,t.jsx)(nxs,{})}),(0,t.jsx)(rt,{path:"onboarding",element:(0,t.jsx)(D9e,{})}),(0,t.jsx)(rt,{path:"instance",element:(0,t.jsx)(Ry,{})}),(0,t.jsx)(rt,{path:"instance/settings",element:(0,t.jsx)(Ry,{})}),(0,t.jsx)(rt,{path:"instance/settings/*",element:(0,t.jsx)(Ry,{})}),(0,t.jsx)(rt,{path:"companies",element:(0,t.jsx)(ya,{})}),(0,t.jsx)(rt,{path:"dashboard",element:(0,t.jsx)(ya,{})}),(0,t.jsx)(rt,{path:"inbox/*",element:(0,t.jsx)(ya,{})}),(0,t.jsx)(rt,{path:"issues",element:(0,t.jsx)(ya,{})}),(0,t.jsx)(rt,{path:"tasks",element:(0,t.jsx)(ya,{})}),(0,t.jsx)(rt,{path:"issues/:issueId",element:(0,t.jsx)(ya,{})}),(0,t.jsx)(rt,{path:"routines",element:(0,t.jsx)(ya,{})}),(0,t.jsx)(rt,{path:"routines/:routineId",element:(0,t.jsx)(ya,{})}),(0,t.jsx)(rt,{path:"review-queue",element:(0,t.jsx)(ya,{})}),(0,t.jsx)(rt,{path:"learnings",element:(0,t.jsx)(ya,{})}),(0,t.jsx)(rt,{path:"cases",element:(0,t.jsx)(ya,{})}),(0,t.jsx)(rt,{path:"cases/:caseIdentifier",element:(0,t.jsx)(ya,{})}),(0,t.jsx)(rt,{path:"pixels-office",element:(0,t.jsx)(ya,{})}),(0,t.jsx)(rt,{path:"status",element:(0,t.jsx)(ya,{})}),(0,t.jsx)(rt,{path:"status/:cardId",element:(0,t.jsx)(ya,{})}),(0,t.jsx)(rt,{path:"status-cards",element:(0,t.jsx)(ya,{})}),(0,t.jsx)(rt,{path:"status-cards/:cardId",element:(0,t.jsx)(ya,{})}),(0,t.jsx)(rt,{path:"pipelines",element:(0,t.jsx)(ya,{})}),(0,t.jsx)(rt,{path:"pipelines/:pipelineId",element:(0,t.jsx)(ya,{})}),(0,t.jsx)(rt,{path:"pipelines/:pipelineId/add",element:(0,t.jsx)(ya,{})}),(0,t.jsx)(rt,{path:"pipelines/:pipelineId/settings",element:(0,t.jsx)(ya,{})}),(0,t.jsx)(rt,{path:"pipelines/:pipelineId/items/:caseId",element:(0,t.jsx)(ya,{})}),(0,t.jsx)(rt,{path:"pipelines/:pipelineId/cases/:caseId",element:(0,t.jsx)(ya,{})}),(0,t.jsx)(rt,{path:"artifacts",element:(0,t.jsx)(ya,{})}),(0,t.jsx)(rt,{path:"audit",element:(0,t.jsx)(ya,{})}),e?(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)(rt,{path:"audit/*",element:(0,t.jsx)(ya,{})}),(0,t.jsx)(rt,{path:"activity",element:(0,t.jsx)(ya,{})}),(0,t.jsx)(rt,{path:"activity/*",element:(0,t.jsx)(ya,{})}),(0,t.jsx)(rt,{path:"runs",element:(0,t.jsx)(ya,{})}),(0,t.jsx)(rt,{path:"costs",element:(0,t.jsx)(ya,{})}),(0,t.jsx)(rt,{path:"budgets",element:(0,t.jsx)(ya,{})})]}):null,(0,t.jsx)(rt,{path:"decisions",element:(0,t.jsx)(ya,{})}),(0,t.jsx)(rt,{path:"u/:userSlug",element:(0,t.jsx)(ya,{})}),(0,t.jsx)(rt,{path:"skills/studio",element:(0,t.jsx)(ya,{})}),(0,t.jsx)(rt,{path:"skills/studio/new",element:(0,t.jsx)(ya,{})}),(0,t.jsx)(rt,{path:"skills/studio/:skillId",element:(0,t.jsx)(ya,{})}),(0,t.jsx)(rt,{path:"skills/:skillId/studio",element:(0,t.jsx)(M9e,{})}),(0,t.jsx)(rt,{path:"skills/*",element:(0,t.jsx)(ya,{})}),(0,t.jsx)(rt,{path:"settings",element:(0,t.jsx)(Ry,{})}),(0,t.jsx)(rt,{path:"settings/*",element:(0,t.jsx)(Ry,{})}),(0,t.jsx)(rt,{path:"agents",element:(0,t.jsx)(ya,{})}),sY.map(a=>(0,t.jsx)(rt,{path:`agents/${a}`,element:(0,t.jsx)(ya,{})},a)),(0,t.jsx)(rt,{path:"agents/new",element:(0,t.jsx)(ya,{})}),(0,t.jsx)(rt,{path:"agents/:agentId",element:(0,t.jsx)(ya,{})}),(0,t.jsx)(rt,{path:"agents/:agentId/:tab",element:(0,t.jsx)(ya,{})}),(0,t.jsx)(rt,{path:"agents/:agentId/runs/:runId",element:(0,t.jsx)(ya,{})}),(0,t.jsx)(rt,{path:"projects",element:(0,t.jsx)(ya,{})}),(0,t.jsx)(rt,{path:"projects/:projectId",element:(0,t.jsx)(ya,{})}),(0,t.jsx)(rt,{path:"projects/:projectId/overview",element:(0,t.jsx)(ya,{})}),(0,t.jsx)(rt,{path:"projects/:projectId/issues",element:(0,t.jsx)(ya,{})}),(0,t.jsx)(rt,{path:"projects/:projectId/issues/:filter",element:(0,t.jsx)(ya,{})}),(0,t.jsx)(rt,{path:"projects/:projectId/workspaces",element:(0,t.jsx)(ya,{})}),(0,t.jsx)(rt,{path:"projects/:projectId/workspaces/:workspaceId",element:(0,t.jsx)(ya,{})}),(0,t.jsx)(rt,{path:"projects/:projectId/configuration",element:(0,t.jsx)(ya,{})}),(0,t.jsx)(rt,{path:"workspaces",element:(0,t.jsx)(ya,{})}),(0,t.jsx)(rt,{path:"terminal",element:(0,t.jsx)(ya,{})}),(0,t.jsx)(rt,{path:"execution-workspaces/:workspaceId",element:(0,t.jsx)(e1,{})}),(0,t.jsx)(rt,{path:"execution-workspaces/:workspaceId/services",element:(0,t.jsx)(e1,{})}),(0,t.jsx)(rt,{path:"execution-workspaces/:workspaceId/configuration",element:(0,t.jsx)(e1,{})}),(0,t.jsx)(rt,{path:"execution-workspaces/:workspaceId/runtime-logs",element:(0,t.jsx)(e1,{})}),(0,t.jsx)(rt,{path:"execution-workspaces/:workspaceId/issues",element:(0,t.jsx)(e1,{})}),(0,t.jsx)(rt,{path:"execution-workspaces/:workspaceId/routines",element:(0,t.jsx)(e1,{})}),(0,t.jsx)(rt,{path:":companyPrefix",element:e?(0,t.jsx)(M0t,{}):(0,t.jsx)(hpt,{}),children:sxs(e,n)}),(0,t.jsx)(rt,{path:"*",element:(0,t.jsx)(mm,{scope:"global"})})]})]}),(0,t.jsx)(ijt,{}),(0,t.jsx)(p0t,{})]})}r(rxs,"App");var axs=class extends m.Component{static{r(this,"AppErrorBoundary")}state={error:null};static getDerivedStateFromError(e){return{error:e instanceof Error?e:new Error(String(e))}}componentDidCatch(e,s){LV(e,{boundary:"app",componentStack:s.componentStack})}render(){const{error:e}=this.state;return e?(0,t.jsxs)("div",{className:"mx-auto flex min-h-screen max-w-2xl flex-col justify-center space-y-4 px-4 py-10",children:[(0,t.jsxs)("div",{children:[(0,t.jsx)("h1",{className:"text-lg font-semibold",children:"Paperclip hit an error"}),(0,t.jsx)("p",{className:"mt-1 text-sm text-muted-foreground",children:"Something went wrong while running the app. Reloading usually fixes this."})]}),(0,t.jsx)("pre",{className:"overflow-auto rounded-md border border-destructive/30 bg-destructive/10 px-3 py-2 text-xs text-destructive whitespace-pre-wrap",children:e.message}),(0,t.jsx)("div",{children:(0,t.jsx)("button",{type:"button",className:"inline-flex items-center rounded-md border border-input bg-background px-3 py-1.5 text-sm font-medium shadow-sm hover:bg-accent hover:text-accent-foreground",onClick:r(()=>window.location.reload(),"onClick"),children:"Reload page"})})]}):this.props.children}};function ixs(){const{data:e}=te({queryKey:D.auth.session,queryFn:r(()=>Pa.getSession(),"queryFn"),retry:!1}),s=e?.sentryDsn,n=e?.sentryEnvironment??void 0;return(0,m.useEffect)(()=>{if(s)return Wht(s,n),()=>{Hht()}},[s,n]),null}r(ixs,"SentryGate");function oxs(e){let s=ag();Lce(s),pU(s,e.userId);const n=ARe(()=>{const o=ag();o!==s&&(s=o,Lce(o),pU(o,e.userId))}),a=typeof navigator<"u"&&"serviceWorker"in navigator?navigator.serviceWorker:null,i=r(o=>{const l=DEt(o.data);l&&(l.type==="navigate"?e.navigate(l.url):MEt(l.notification))},"onMessage");return a?.addEventListener("message",i),a?.startMessages(),()=>{n(),a?.removeEventListener("message",i)}}r(oxs,"startNotificationRuntime");function lxs(){const e=Gn(),s=(0,m.useRef)(e),{data:n}=te({queryKey:D.auth.session,queryFn:r(()=>Pa.getSession(),"queryFn"),retry:!1}),a=n?.user?.id??n?.session?.userId??null;return(0,m.useEffect)(()=>{s.current=e},[e]),(0,m.useEffect)(()=>{if(a)return oxs({userId:a,navigate:r(i=>s.current(i),"navigate")})},[a]),null}r(lxs,"NotificationRuntime");var $9e={get:r(e=>ke.get(`/companies/${e}/primary-agent/me`),"get"),set:r((e,s)=>ke.put(`/companies/${e}/primary-agent/me`,s),"set")};function cxs(e){const s=te({queryKey:D.auth.session,queryFn:r(()=>Pa.getSession(),"queryFn")}),n=s.data?.user?.id??s.data?.session?.userId??"local-board",a=te({queryKey:D.primaryAgent.mine(e??"__none__",n),queryFn:r(()=>$9e.get(e),"queryFn"),enabled:!!e&&s.isSuccess});return{...a,userId:n,loading:!!e&&(s.isPending||a.isPending&&!s.error),error:s.error??a.error,retry:r(()=>s.isError?s.refetch():a.refetch(),"retry")}}r(cxs,"usePrimaryAgent");function dxs({children:e}){const{selectedCompanyId:s}=fs(),n=cxs(s),a=wt(),{pushToast:i}=Zr(),o=(0,m.useRef)({companyId:s,userId:n.userId});o.current={companyId:s,userId:n.userId};const l=r(f=>D.primaryAgent.mine(f.companyId,f.userId),"keyFor"),c=r(f=>f.companyId===o.current.companyId&&f.userId===o.current.userId,"isCurrentScope"),d=te({queryKey:D.agents.list(s),queryFn:r(()=>Nt.list(s),"queryFn"),enabled:!!s}),u=we({mutationFn:r(f=>$9e.set(f.companyId,{primaryAgentId:f.agentId}),"mutationFn"),onMutate:r(async f=>{const x=l(f);await a.cancelQueries({queryKey:x});const g=a.getQueryData(x);return a.setQueryData(x,{companyId:f.companyId,userId:f.userId,primaryAgentId:f.agentId,initialized:!0}),{previous:g}},"onMutate"),onError:r((f,x,g)=>{a.setQueryData(l(x),g?.previous),c(x)&&i({title:"Couldn't change your primary agent.",body:f.message,tone:"error",action:{label:"Retry",onClick:r(()=>{c(x)&&u.mutate(x)},"onClick")}})},"onError"),onSuccess:r((f,x)=>a.setQueryData(l(x),f),"onSuccess"),onSettled:r((f,x,g)=>{a.invalidateQueries({queryKey:l(g)}),a.invalidateQueries({queryKey:D.resourceMemberships.mine(g.companyId)})},"onSettled")}),h=d.data?.find(f=>f.id===n.data?.primaryAgentId&&f.status!=="terminated")??null,p=n.error??d.error;return(0,t.jsx)(THe,{value:s?{companyId:s,primaryAgentId:h?.id??null,primaryAgent:h,loading:n.loading||d.isPending,error:p?.message,onRetry:r(()=>{n.retry(),d.refetch()},"onRetry"),pendingAgentId:u.isPending&&c(u.variables)?u.variables.agentId:null,onChange:r(f=>u.mutate({companyId:s,userId:n.userId,agentId:f}),"onChange")}:null,children:e})}r(dxs,"PrimaryAgentProvider");function uxs(e){return{id:e.key,title:e.title,status:e.status,projectId:e.projectId??null,assigneeAgentId:e.assigneeAgentId??null,lastRun:e.lastRunAt||e.lastRunStatus?{triggeredAt:e.lastRunAt??null,status:e.lastRunStatus??null}:null}}r(uxs,"managedRoutineToRow");function mxs({routines:e,agents:s=[],projects:n=[],pluginDisplayName:a=null,emptyMessage:i="No managed routines.",runningRoutineKey:o=null,statusMutationRoutineKey:l=null,reconcilingRoutineKey:c=null,resettingRoutineKey:d=null,onRunNow:u,onToggleEnabled:h,onReconcile:p,onReset:f}){const x=new Map(s.map(v=>[v.id,v])),g=new Map(n.map(v=>[v.id,{name:v.name,color:v.color}]));return e.length===0?(0,t.jsx)("div",{className:"rounded-lg border border-border px-3 py-8 text-center text-sm text-muted-foreground",children:i}):(0,t.jsx)("div",{className:"rounded-lg border border-border",children:e.map(v=>{const y=uxs(v),k=v.href??(v.routineId?`/routines/${v.routineId}`:"/routines"),w=v.missingRefs??[],N=!!(v.routineId&&v.resourceKey&&w.length===0),S=v.managedByPluginDisplayName??a,C=!!(p||f);return(0,t.jsxs)("div",{className:"last:[&_a]:border-b-0",children:[(0,t.jsx)(TLe,{routine:y,projectById:g,agentById:x,runningRoutineId:o,statusMutationRoutineId:l,href:k,configureLabel:"Configure",managedByLabel:S?`Managed by ${S}`:null,runNowButton:!0,hideArchiveAction:!0,disableRunNow:!N,disableToggle:!N,secondaryDetails:(0,t.jsxs)("span",{className:"flex flex-wrap items-center gap-x-3 gap-y-1",children:[v.resourceKey?(0,t.jsx)("span",{children:v.resourceKey}):null,v.cronExpression?(0,t.jsxs)("span",{children:["Schedule ",v.cronExpression]}):null]}),onRunNow:r(()=>u?.(v),"onRunNow"),onToggleEnabled:r(()=>h?.(v,y.status==="active"),"onToggleEnabled")}),C?(0,t.jsxs)("div",{className:"flex flex-wrap items-center justify-between gap-2 border-b border-border px-3 pb-3 text-xs text-muted-foreground last:border-b-0",onClick:r(_=>{_.preventDefault(),_.stopPropagation()},"onClick"),children:[(0,t.jsx)("span",{children:w.length?`Missing ${w.map(_=>`${_.resourceKind}:${_.resourceKey}`).join(", ")}`:"Routine defaults can be repaired."}),(0,t.jsxs)("span",{className:"flex items-center gap-2",children:[p?(0,t.jsx)($,{size:"sm",variant:"ghost",disabled:c===v.key,onClick:r(()=>p(v),"onClick"),children:c===v.key?"Reconciling...":"Reconcile"}):null,f?(0,t.jsx)($,{size:"sm",variant:"ghost",disabled:d===v.key,onClick:r(()=>f(v),"onClick"),children:d===v.key?"Resetting...":"Reset"}):null]})]}):null]},v.key)})})}r(mxs,"ManagedRoutinesList");function Lge(e){return new Set(e??[])}r(Lge,"toPathSet");function hxs({expandedPaths:e,checkedPaths:s,selectedFile:n=null,showCheckboxes:a=!1,onToggleDir:i,onSelectFile:o,...l}){return(0,m.createElement)(fw,{...l,selectedFile:n,expandedDirs:Lge(e),checkedFiles:s?Lge(s):void 0,showCheckboxes:a,onToggleDir:i??(()=>{}),onSelectFile:o??(()=>{})})}r(hxs,"PluginSdkFileTree");function pxs(e){const[s,n]=(0,m.useState)(null);return(0,m.useEffect)(()=>{let a=!1;return bd(()=>import("./MarkdownEditor-B01YT6TZ.js").then(i=>i.n).then(i=>{a||n(()=>i.MarkdownEditor)}),__vite__mapDeps([44,5,7,9,14,15,33,28,31,45,30,29,21,46])),()=>{a=!0}},[]),s?(0,m.createElement)(s,e):(0,m.createElement)("textarea",{className:e.className,value:e.value,placeholder:e.placeholder,readOnly:e.readOnly,onBlur:e.onBlur,onChange:r(a=>e.onChange(a.currentTarget.value),"onChange")})}r(pxs,"PluginSdkMarkdownEditor");function fxs(e){return Object.fromEntries(Object.entries(e).filter(([,s])=>s!=null&&s!==""&&s!==!1))}r(fxs,"compactIssueFilters");function xxs({companyId:e,projectId:s=null,filters:n,viewStateKey:a="paperclip:plugin-issues-view",initialSearch:i,createIssueLabel:o,searchWithinLoadedIssues:l=!0}){const c=wt(),d=(0,m.useMemo)(()=>fxs({...n??{},projectId:n?.projectId??s??void 0}),[n,s]),u=d.originKindPrefix??null,h=d.projectId??s??null,p=(0,m.useMemo)(()=>["plugins","sdk-ui","issues-list",e??"__no-company__",d],[e,d]),{data:f}=te({queryKey:D.agents.list(e??"__no-company__"),queryFn:r(()=>Nt.list(e),"queryFn"),enabled:!!e}),{data:x}=te({queryKey:D.projects.list(e??"__no-company__",{includeArchived:!0}),queryFn:r(()=>aa.list(e,{includeArchived:!0}),"queryFn"),enabled:!!e}),g=D.liveRuns(e??"__no-company__"),v=jo({companyId:e,resourceKey:"live-runs",queryKey:g,enabled:!!e,refetchInterval:!1,leaderOnly:!0}),{data:y,dataUpdatedAt:k}=te({queryKey:g,queryFn:r(()=>ea.liveRunsForCompany(e),"queryFn"),enabled:v.enabled,refetchInterval:v.refetchInterval});wo(v,y,k);const{data:w,isLoading:N,error:S}=te({queryKey:p,queryFn:r(()=>yt.list(e,d),"queryFn"),enabled:!!e}),C=(0,m.useMemo)(()=>dg(y,w),[w,y]),_=we({mutationFn:r(({id:R,data:I})=>yt.update(R,I),"mutationFn"),onSuccess:r(()=>{e&&(c.invalidateQueries({queryKey:["plugins","sdk-ui","issues-list",e]}),c.invalidateQueries({queryKey:D.issues.list(e)}),h&&(c.invalidateQueries({queryKey:D.issues.listByProject(e,h)}),u&&c.invalidateQueries({queryKey:D.issues.listPluginOperationsByProject(e,h,u)})))},"onSuccess")});return e?(0,m.createElement)(Vx,{issues:w??[],isLoading:N,error:S,agents:f,projects:x,liveIssueIds:C,projectId:h??void 0,viewStateKey:a,initialSearch:i,createIssueLabel:o,searchWithinLoadedIssues:l,onUpdateIssue:r((R,I)=>_.mutate({id:R,data:I}),"onUpdateIssue")}):(0,m.createElement)("div",{className:"text-sm text-muted-foreground"},"Select an organization to view tasks.")}r(xxs,"PluginSdkIssuesList");function gxs({companyId:e,value:s,onChange:n,placeholder:a="Responsible",noneLabel:i="No responsible",searchPlaceholder:o="Search responsible...",emptyMessage:l="No responsible found.",includeUsers:c=!0,includeTerminatedAgents:d=!1,className:u,onConfirm:h}){const p=DW(),f=e??p.companyId??null,{data:x}=te({queryKey:D.auth.session,queryFn:r(()=>Pa.getSession(),"queryFn"),enabled:c}),g=x?.user?.id??x?.session?.userId??null,{data:v}=te({queryKey:D.agents.list(f??"__no-company__"),queryFn:r(()=>Nt.list(f),"queryFn"),enabled:!!f}),{data:y}=te({queryKey:D.access.companyUserDirectory(f??"__no-company__"),queryFn:r(()=>or.listUserDirectory(f),"queryFn"),enabled:!!f&&c}),k=(0,m.useMemo)(()=>sF(),[]),w=(0,m.useMemo)(()=>k.map(R=>R.startsWith("agent:")?R.slice(6):null).filter(R=>!!R),[k]),N=(0,m.useMemo)(()=>uj((v??[]).filter(R=>d||R.status!=="terminated"),w),[v,d,w]),S=(0,m.useMemo)(()=>[...c?uve(g):[],...c?m2(y?.users,{excludeUserIds:[g]}):[],...N.map(R=>({id:Fh({assigneeAgentId:R.id}),label:R.name,searchText:`${R.name} ${R.role} ${R.title??""}`}))],[y?.users,g,c,N]),C=Qy(s),_=C.assigneeAgentId?N.find(R=>R.id===C.assigneeAgentId):null;return(0,m.createElement)(cm,{value:s,options:S,recentOptionIds:k,placeholder:a,noneLabel:i,searchPlaceholder:o,emptyMessage:l,className:u,onConfirm:h,onChange:r(R=>{const I=Qy(R);I.assigneeAgentId&&mj(I.assigneeAgentId),I.assigneeUserId&&$_(I.assigneeUserId),n(R,I)},"onChange"),renderTriggerValue:r(R=>R?_?(0,m.createElement)(mL,null,(0,m.createElement)(TE,{icon:_.icon,className:"h-3.5 w-3.5 shrink-0 text-muted-foreground"}),(0,m.createElement)("span",{className:"truncate"},R.label)):(0,m.createElement)("span",{className:"truncate"},R.label):(0,m.createElement)("span",{className:"text-muted-foreground"},a),"renderTriggerValue"),renderOption:r(R=>{if(!R.id)return(0,m.createElement)("span",{className:"truncate"},R.label);const I=Qy(R.id),T=I.assigneeAgentId?N.find(E=>E.id===I.assigneeAgentId):null;return(0,m.createElement)(mL,null,T?(0,m.createElement)(TE,{icon:T.icon,className:"h-3.5 w-3.5 shrink-0 text-muted-foreground"}):(0,m.createElement)(gd,{className:"h-3.5 w-3.5 shrink-0 text-muted-foreground"}),(0,m.createElement)("span",{className:"truncate"},R.label))},"renderOption")})}r(gxs,"PluginSdkAssigneePicker");function bxs({companyId:e,value:s,onChange:n,placeholder:a="Project",noneLabel:i="No project",searchPlaceholder:o="Search projects...",emptyMessage:l="No projects found.",includeArchived:c=!1,className:d,onConfirm:u}){const h=DW(),p=e??h.companyId??null,{data:f}=te({queryKey:D.auth.session,queryFn:r(()=>Pa.getSession(),"queryFn")}),x=f?.user?.id??f?.session?.userId??null,{data:g}=te({queryKey:D.projects.list(p??"__no-company__",{includeArchived:c}),queryFn:r(()=>aa.list(p,{includeArchived:c}),"queryFn"),enabled:!!p}),v=(0,m.useMemo)(()=>(g??[]).filter(S=>c||!S.archivedAt),[c,g]),{orderedProjects:y}=Zj({projects:v,companyId:p,userId:x}),k=(0,m.useMemo)(()=>hj(),[]),w=(0,m.useMemo)(()=>y.map(S=>({id:S.id,label:S.name,searchText:S.description??""})),[y]),N=y.find(S=>S.id===s)??null;return(0,m.createElement)(cm,{value:s,options:w,recentOptionIds:k,placeholder:a,noneLabel:i,searchPlaceholder:o,emptyMessage:l,className:d,onConfirm:u,onChange:r(S=>{S&&Ob(S),n(S)},"onChange"),renderTriggerValue:r(S=>!S||!N?(0,m.createElement)("span",{className:"text-muted-foreground"},a):(0,m.createElement)(mL,null,(0,m.createElement)("span",{className:"h-3.5 w-3.5 shrink-0 rounded-sm",style:{backgroundColor:N.color??"#6366f1"}}),(0,m.createElement)("span",{className:"truncate"},S.label)),"renderTriggerValue"),renderOption:r(S=>{if(!S.id)return(0,m.createElement)("span",{className:"truncate"},S.label);const C=y.find(_=>_.id===S.id);return(0,m.createElement)(mL,null,(0,m.createElement)("span",{className:"h-3.5 w-3.5 shrink-0 rounded-sm",style:{backgroundColor:C?.color??"#6366f1"}}),(0,m.createElement)("span",{className:"truncate"},S.label))},"renderOption")})}r(bxs,"PluginSdkProjectPicker");function mL({children:e}){return(0,m.createElement)("span",{className:"contents"},e)}r(mL,"FragmentSafe");function vxs({label:e,status:s}){const n={ok:"border-emerald-300 bg-emerald-50 text-emerald-700",warning:"border-amber-300 bg-amber-50 text-amber-800",error:"border-red-300 bg-red-50 text-red-700",info:"border-slate-300 bg-slate-50 text-slate-700",pending:"border-slate-300 bg-slate-50 text-slate-600"}[s];return(0,m.createElement)("span",{className:`inline-flex w-fit items-center rounded-full border px-2 py-0.5 text-xs font-medium ${n}`},e)}r(vxs,"PluginSdkStatusBadge");function yxs({columns:e,rows:s,loading:n,emptyMessage:a="No rows."}){if(n)return(0,m.createElement)("div",{className:"text-sm text-muted-foreground"},"Loading...");if(!s.length)return(0,m.createElement)("div",{className:"text-sm text-muted-foreground"},a);const i=e.map(o=>o.width??"minmax(0, 1fr)").join(" ");return(0,m.createElement)("div",{className:"overflow-hidden rounded-md border"},(0,m.createElement)("div",{className:"hidden border-b bg-muted/35 px-3 py-2 text-xs font-medium uppercase tracking-wide text-muted-foreground md:grid md:[grid-template-columns:var(--plugin-grid-cols)]",style:{"--plugin-grid-cols":i}},e.map(o=>(0,m.createElement)("div",{key:o.key},o.header))),(0,m.createElement)("div",{className:"divide-y"},s.map((o,l)=>(0,m.createElement)("div",{key:String(o.id??l),className:"grid gap-2 px-3 py-3 md:items-center md:[grid-template-columns:var(--plugin-grid-cols)]",style:{"--plugin-grid-cols":i}},e.map(c=>(0,m.createElement)("div",{key:c.key,className:"min-w-0 text-sm"},(0,m.createElement)("div",{className:"mb-1 text-[11px] font-medium uppercase tracking-wide text-muted-foreground md:hidden"},c.header),c.render?c.render(o[c.key],o):String(o[c.key]??"")))))))}r(yxs,"PluginSdkDataTable");function jxs({pairs:e}){return(0,m.createElement)("dl",{className:"grid gap-x-4 gap-y-1 text-sm sm:grid-cols-[max-content_minmax(0,1fr)]"},e.flatMap(s=>[(0,m.createElement)("dt",{key:`${s.label}:label`,className:"text-muted-foreground"},s.label),(0,m.createElement)("dd",{key:`${s.label}:value`,className:"min-w-0"},s.value)]))}r(jxs,"PluginSdkKeyValueList");function wxs({label:e,value:s,unit:n}){return(0,m.createElement)("div",{className:"rounded-md border bg-card p-3"},(0,m.createElement)("div",{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground"},e),(0,m.createElement)("div",{className:"mt-1 text-lg font-semibold"},`${s}${n??""}`))}r(wxs,"PluginSdkMetricCard");function kxs({data:e}){return(0,m.createElement)("pre",{className:"max-h-80 overflow-auto rounded-md border bg-muted/30 p-2 text-xs"},JSON.stringify(e,null,2))}r(kxs,"PluginSdkJsonTree");function Nxs({label:e="Loading"}){return(0,m.createElement)("span",{className:"inline-block h-3.5 w-3.5 animate-spin rounded-full border-2 border-muted-foreground/30 border-t-foreground align-middle",role:"status","aria-label":e})}r(Nxs,"PluginSdkSpinner");var Sxs=class extends m.Component{static{r(this,"PluginSdkErrorBoundary")}state={hasError:!1};static getDerivedStateFromError(){return{hasError:!0}}render(){return this.state.hasError?this.props.fallback??(0,m.createElement)("div",{className:"rounded-md border border-destructive/30 p-3 text-sm text-destructive"},"Plugin UI failed to render."):this.props.children}};function Cxs(e,s){globalThis.__paperclipPluginBridge__={react:e,reactJsxRuntime:t,reactDom:s,sdkUi:{usePluginData:RVe,usePluginAction:EVe,useHostContext:DW,useHostLocation:MVe,useHostNavigation:LVe,usePluginStream:DVe,usePluginToast:PVe,copyTextToClipboard:wa,MarkdownBlock:r(({content:n,className:a,enableWikiLinks:i,wikiLinkRoot:o,resolveWikiLinkHref:l})=>(0,m.createElement)(An,{className:a,softBreaks:!1,enableWikiLinks:i,wikiLinkRoot:o,resolveWikiLinkHref:l,children:n}),"MarkdownBlock"),MetricCard:wxs,StatusBadge:vxs,DataTable:yxs,KeyValueList:jxs,JsonTree:kxs,Spinner:Nxs,ErrorBoundary:Sxs,MarkdownEditor:pxs,FileTree:hxs,IssuesList:xxs,AssigneePicker:gxs,ProjectPicker:bxs,ManagedRoutinesList:mxs}}}r(Cxs,"initPluginBridge");var _xs=1e4;function Axs(e=_xs){if(typeof performance>"u"||typeof performance.clearMeasures!="function")return()=>{};const n=setInterval(r(()=>{globalThis.__paperclipKeepPerfMeasures||performance.clearMeasures()},"reap"),e);return()=>clearInterval(n)}r(Axs,"startPerfMeasureReaper");var Ixs=Fj((e=>{function s(F,q){var z=F.length;F.push(q);e:for(;0<z;){var K=z-1>>>1,U=F[K];if(0<i(U,q))F[K]=q,F[z]=U,z=K;else break e}}r(s,"push");function n(F){return F.length===0?null:F[0]}r(n,"peek");function a(F){if(F.length===0)return null;var q=F[0],z=F.pop();if(z!==q){F[0]=z;e:for(var K=0,U=F.length,V=U>>>1;K<V;){var ne=2*(K+1)-1,Z=F[ne],ie=ne+1,J=F[ie];if(0>i(Z,z))ie<U&&0>i(J,Z)?(F[K]=J,F[ie]=z,K=ie):(F[K]=Z,F[ne]=z,K=ne);else if(ie<U&&0>i(J,z))F[K]=J,F[ie]=z,K=ie;else break e}}return q}r(a,"pop");function i(F,q){var z=F.sortIndex-q.sortIndex;return z!==0?z:F.id-q.id}if(r(i,"compare"),e.unstable_now=void 0,typeof performance=="object"&&typeof performance.now=="function"){var o=performance;e.unstable_now=function(){return o.now()}}else{var l=Date,c=l.now();e.unstable_now=function(){return l.now()-c}}var d=[],u=[],h=1,p=null,f=3,x=!1,g=!1,v=!1,y=!1,k=typeof setTimeout=="function"?setTimeout:null,w=typeof clearTimeout=="function"?clearTimeout:null,N=typeof setImmediate<"u"?setImmediate:null;function S(F){for(var q=n(u);q!==null;){if(q.callback===null)a(u);else if(q.startTime<=F)a(u),q.sortIndex=q.expirationTime,s(d,q);else break;q=n(u)}}r(S,"advanceTimers");function C(F){if(v=!1,S(F),!g)if(n(d)!==null)g=!0,_||(_=!0,O());else{var q=n(u);q!==null&&L(C,q.startTime-F)}}r(C,"handleTimeout");var _=!1,R=-1,I=5,T=-1;function E(){return y?!0:!(e.unstable_now()-T<I)}r(E,"shouldYieldToHost");function P(){if(y=!1,_){var F=e.unstable_now();T=F;var q=!0;try{e:{g=!1,v&&(v=!1,w(R),R=-1),x=!0;var z=f;try{t:{for(S(F),p=n(d);p!==null&&!(p.expirationTime>F&&E());){var K=p.callback;if(typeof K=="function"){p.callback=null,f=p.priorityLevel;var U=K(p.expirationTime<=F);if(F=e.unstable_now(),typeof U=="function"){p.callback=U,S(F),q=!0;break t}p===n(d)&&a(d),S(F)}else a(d);p=n(d)}if(p!==null)q=!0;else{var V=n(u);V!==null&&L(C,V.startTime-F),q=!1}}break e}finally{p=null,f=z,x=!1}q=void 0}}finally{q?O():_=!1}}}r(P,"performWorkUntilDeadline");var O;if(typeof N=="function")O=r(function(){N(P)},"schedulePerformWorkUntilDeadline");else if(typeof MessageChannel<"u"){var M=new MessageChannel,Q=M.port2;M.port1.onmessage=P,O=r(function(){Q.postMessage(null)},"schedulePerformWorkUntilDeadline")}else O=r(function(){k(P,0)},"schedulePerformWorkUntilDeadline");function L(F,q){R=k(function(){F(e.unstable_now())},q)}r(L,"requestHostTimeout"),e.unstable_IdlePriority=5,e.unstable_ImmediatePriority=1,e.unstable_LowPriority=4,e.unstable_NormalPriority=3,e.unstable_Profiling=null,e.unstable_UserBlockingPriority=2,e.unstable_cancelCallback=function(F){F.callback=null},e.unstable_forceFrameRate=function(F){0>F||125<F||(I=0<F?Math.floor(1e3/F):5)},e.unstable_getCurrentPriorityLevel=function(){return f},e.unstable_next=function(F){switch(f){case 1:case 2:case 3:var q=3;break;default:q=f}var z=f;f=q;try{return F()}finally{f=z}},e.unstable_requestPaint=function(){y=!0},e.unstable_runWithPriority=function(F,q){switch(F){case 1:case 2:case 3:case 4:case 5:break;default:F=3}var z=f;f=F;try{return q()}finally{f=z}},e.unstable_scheduleCallback=function(F,q,z){var K=e.unstable_now();switch(typeof z=="object"&&z!==null?(z=z.delay,z=typeof z=="number"&&0<z?K+z:K):z=K,F){case 1:var U=-1;break;case 2:U=250;break;case 5:U=1073741823;break;case 4:U=1e4;break;default:U=5e3}return U=z+U,F={id:h++,callback:q,priorityLevel:F,startTime:z,expirationTime:U,sortIndex:-1},z>K?(F.sortIndex=z,s(u,F),n(d)===null&&F===n(u)&&(v?(w(R),R=-1):v=!0,L(C,z-K))):(F.sortIndex=U,s(d,F),g||x||(g=!0,_||(_=!0,O()))),F},e.unstable_shouldYield=E,e.unstable_wrapCallback=function(F){var q=f;return function(){var z=f;f=q;try{return F.apply(this,arguments)}finally{f=z}}}})),Txs=Fj(((e,s)=>{s.exports=Ixs()})),Rxs=Fj((e=>{var s=Txs(),n=CQ(),a=Vge();function i(b){var j="https://react.dev/errors/"+b;if(1<arguments.length){j+="?args[]="+encodeURIComponent(arguments[1]);for(var A=2;A<arguments.length;A++)j+="&args[]="+encodeURIComponent(arguments[A])}return"Minified React error #"+b+"; visit "+j+" for the full message or use the non-minified dev environment for full errors and additional helpful warnings."}r(i,"formatProdErrorMessage");function o(b){return!(!b||b.nodeType!==1&&b.nodeType!==9&&b.nodeType!==11)}r(o,"isValidContainer");function l(b){var j=b,A=b;if(b.alternate)for(;j.return;)j=j.return;else{b=j;do j=b,(j.flags&4098)!==0&&(A=j.return),b=j.return;while(b)}return j.tag===3?A:null}r(l,"getNearestMountedFiber");function c(b){if(b.tag===13){var j=b.memoizedState;if(j===null&&(b=b.alternate,b!==null&&(j=b.memoizedState)),j!==null)return j.dehydrated}return null}r(c,"getSuspenseInstanceFromFiber");function d(b){if(b.tag===31){var j=b.memoizedState;if(j===null&&(b=b.alternate,b!==null&&(j=b.memoizedState)),j!==null)return j.dehydrated}return null}r(d,"getActivityInstanceFromFiber");function u(b){if(l(b)!==b)throw Error(i(188))}r(u,"assertIsMounted");function h(b){var j=b.alternate;if(!j){if(j=l(b),j===null)throw Error(i(188));return j!==b?null:b}for(var A=b,B=j;;){var H=A.return;if(H===null)break;var ee=H.alternate;if(ee===null){if(B=H.return,B!==null){A=B;continue}break}if(H.child===ee.child){for(ee=H.child;ee;){if(ee===A)return u(H),b;if(ee===B)return u(H),j;ee=ee.sibling}throw Error(i(188))}if(A.return!==B.return)A=H,B=ee;else{for(var Ne=!1,He=H.child;He;){if(He===A){Ne=!0,A=H,B=ee;break}if(He===B){Ne=!0,B=H,A=ee;break}He=He.sibling}if(!Ne){for(He=ee.child;He;){if(He===A){Ne=!0,A=ee,B=H;break}if(He===B){Ne=!0,B=ee,A=H;break}He=He.sibling}if(!Ne)throw Error(i(189))}}if(A.alternate!==B)throw Error(i(190))}if(A.tag!==3)throw Error(i(188));return A.stateNode.current===A?b:j}r(h,"findCurrentFiberUsingSlowPath");function p(b){var j=b.tag;if(j===5||j===26||j===27||j===6)return b;for(b=b.child;b!==null;){if(j=p(b),j!==null)return j;b=b.sibling}return null}r(p,"findCurrentHostFiberImpl");var f=Object.assign,x=Symbol.for("react.element"),g=Symbol.for("react.transitional.element"),v=Symbol.for("react.portal"),y=Symbol.for("react.fragment"),k=Symbol.for("react.strict_mode"),w=Symbol.for("react.profiler"),N=Symbol.for("react.consumer"),S=Symbol.for("react.context"),C=Symbol.for("react.forward_ref"),_=Symbol.for("react.suspense"),R=Symbol.for("react.suspense_list"),I=Symbol.for("react.memo"),T=Symbol.for("react.lazy"),E=Symbol.for("react.activity"),P=Symbol.for("react.memo_cache_sentinel"),O=Symbol.iterator;function M(b){return b===null||typeof b!="object"?null:(b=O&&b[O]||b["@@iterator"],typeof b=="function"?b:null)}r(M,"getIteratorFn");var Q=Symbol.for("react.client.reference");function L(b){if(b==null)return null;if(typeof b=="function")return b.$$typeof===Q?null:b.displayName||b.name||null;if(typeof b=="string")return b;switch(b){case y:return"Fragment";case w:return"Profiler";case k:return"StrictMode";case _:return"Suspense";case R:return"SuspenseList";case E:return"Activity"}if(typeof b=="object")switch(b.$$typeof){case v:return"Portal";case S:return b.displayName||"Context";case N:return(b._context.displayName||"Context")+".Consumer";case C:var j=b.render;return b=b.displayName,b||(b=j.displayName||j.name||"",b=b!==""?"ForwardRef("+b+")":"ForwardRef"),b;case I:return j=b.displayName||null,j!==null?j:L(b.type)||"Memo";case T:j=b._payload,b=b._init;try{return L(b(j))}catch{}}return null}r(L,"getComponentNameFromType");var F=Array.isArray,q=n.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE,z=a.__DOM_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE,K={pending:!1,data:null,method:null,action:null},U=[],V=-1;function ne(b){return{current:b}}r(ne,"createCursor");function Z(b){0>V||(b.current=U[V],U[V]=null,V--)}r(Z,"pop");function ie(b,j){V++,U[V]=b.current,b.current=j}r(ie,"push");var J=ne(null),ae=ne(null),oe=ne(null),G=ne(null);function X(b,j){switch(ie(oe,j),ie(ae,b),ie(J,null),j.nodeType){case 9:case 11:b=(b=j.documentElement)&&(b=b.namespaceURI)?HX(b):0;break;default:if(b=j.tagName,j=j.namespaceURI)j=HX(j),b=VX(j,b);else switch(b){case"svg":b=1;break;case"math":b=2;break;default:b=0}}Z(J),ie(J,b)}r(X,"pushHostContainer");function Y(){Z(J),Z(ae),Z(oe)}r(Y,"popHostContainer");function re(b){b.memoizedState!==null&&ie(G,b);var j=J.current,A=VX(j,b.type);j!==A&&(ie(ae,b),ie(J,A))}r(re,"pushHostContext");function se(b){ae.current===b&&(Z(J),Z(ae)),G.current===b&&(Z(G),xS._currentValue=K)}r(se,"popHostContext");var ce,pe;function fe(b){if(ce===void 0)try{throw Error()}catch(A){var j=A.stack.trim().match(/\n( *(at )?)/);ce=j&&j[1]||"",pe=-1<A.stack.indexOf(`
707
707
  at`)?" (<anonymous>)":-1<A.stack.indexOf("@")?"@unknown:0:0":""}return`
708
708
  `+ce+b+pe}r(fe,"describeBuiltInComponentFrame");var ve=!1;function Ie(b,j){if(!b||ve)return"";ve=!0;var A=Error.prepareStackTrace;Error.prepareStackTrace=void 0;try{var B={DetermineComponentFrameRoot:r(function(){try{if(j){var Us=r(function(){throw Error()},"Fake");if(Object.defineProperty(Us.prototype,"props",{set:r(function(){throw Error()},"set")}),typeof Reflect=="object"&&Reflect.construct){try{Reflect.construct(Us,[])}catch(gs){var cs=gs}Reflect.construct(b,[],Us)}else{try{Us.call()}catch(gs){cs=gs}b.call(Us.prototype)}}else{try{throw Error()}catch(gs){cs=gs}(Us=b())&&typeof Us.catch=="function"&&Us.catch(function(){})}}catch(gs){if(gs&&cs&&typeof gs.stack=="string")return[gs.stack,cs.stack]}return[null,null]},"DetermineComponentFrameRoot")};B.DetermineComponentFrameRoot.displayName="DetermineComponentFrameRoot";var H=Object.getOwnPropertyDescriptor(B.DetermineComponentFrameRoot,"name");H&&H.configurable&&Object.defineProperty(B.DetermineComponentFrameRoot,"name",{value:"DetermineComponentFrameRoot"});var ee=B.DetermineComponentFrameRoot(),Ne=ee[0],He=ee[1];if(Ne&&He){var vt=Ne.split(`
709
709
  `),is=He.split(`