@tickernelz/paperclip-pro-ui 2026.1016.1 → 2026.1016.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.
@@ -1,4 +1,4 @@
1
- const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/runtime-IAg0vdY9.js","assets/model-DL5biheO.js","assets/definition-CAnOpilv.js","assets/character-CguPM7IG.js","assets/prod-COP_vZWu.js","assets/rolldown-runtime-ZpX3ckPj.js","assets/CompanyExport-01FumBlx.js","assets/agent-avatar-url-BnmqahQ7.js","assets/BreadcrumbContext-Bxr1TyKN.js","assets/preload-helper-CceJXRIF.js","assets/mention-chips-ClRmijVb.js","assets/StatusIcon-YdJnE47W.js","assets/clipboard-CTmezHYG.js","assets/badge-D5aOL1Ll.js","assets/ToastContext-Dh8dPdr5.js","assets/MarkdownBody-B5ygzgk6.js","assets/check-BiXfODpl.js","assets/external-link-LnxJtUIq.js","assets/rotate-ccw-2WnWy1fs.js","assets/EmptyState-DliXLd04.js","assets/PageSkeleton-BZF4K6Hf.js","assets/skeleton-DCrngTtF.js","assets/Agents.production-_5ubl1b-.js","assets/alert-dialog-BxpRolrb.js","assets/dist-CvM0_U_m.js","assets/dist-BrRwU9U9.js","assets/AgentAvatar-DZh8tNnK.js","assets/tabs-BfOtoFWj.js","assets/bot-DpNd1tv2.js","assets/heartbeats-Dae6h2SU.js","assets/environments-Bj-4l7Ol.js","assets/Routines.production-DvkQeN0E.js","assets/label-YjU0jMtG.js","assets/checkbox-5wFlZdZn.js","assets/RoutineRunVariablesDialog-DE5hp-_u.js","assets/MarkdownEditor-D7suACD6.js","assets/dist-CMegW-DS.js","assets/dist-BhxPxuMy.js","assets/select-DRgGQ-iP.js","assets/sheet-CACWxbsc.js","assets/useHiddenSettings-Dz7GWNDr.js","assets/health-D8T5Zr74.js","assets/input-CtLHwxEw.js","assets/company-members-Dd6xBf6K.js","assets/card-PCL2aF_L.js","assets/RoutineDetail.production-BU1uce8a.js","assets/arrow-right-bnOoaiPg.js","assets/use-copy-action-qHyHFl14.js","assets/CompanySkills.production-CLJPeNSr.js","assets/use-adapter-capabilities-JhD0-FlQ.js","assets/file-text-Ba5Wddur.js","assets/CompanyActivity.production-BDDgz0sR.js","assets/OrgChart.production-B_zvlsnl.js"])))=>i.map(i=>d[i]);
1
+ const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/runtime-IAg0vdY9.js","assets/model-DL5biheO.js","assets/definition-CjvFnh6k.js","assets/character-CguPM7IG.js","assets/prod-COP_vZWu.js","assets/rolldown-runtime-ZpX3ckPj.js","assets/CompanyExport-CsJNakda.js","assets/agent-avatar-url-BnmqahQ7.js","assets/BreadcrumbContext-Bxr1TyKN.js","assets/preload-helper-CceJXRIF.js","assets/mention-chips-ClRmijVb.js","assets/StatusIcon-YdJnE47W.js","assets/clipboard-CTmezHYG.js","assets/badge-D5aOL1Ll.js","assets/ToastContext-Dh8dPdr5.js","assets/MarkdownBody-B5ygzgk6.js","assets/check-BiXfODpl.js","assets/external-link-LnxJtUIq.js","assets/rotate-ccw-2WnWy1fs.js","assets/EmptyState-DliXLd04.js","assets/PageSkeleton-BZF4K6Hf.js","assets/skeleton-DCrngTtF.js","assets/Agents.production-CVULb5cR.js","assets/alert-dialog-BxpRolrb.js","assets/dist-CvM0_U_m.js","assets/dist-BrRwU9U9.js","assets/AgentAvatar-DZh8tNnK.js","assets/tabs-BfOtoFWj.js","assets/bot-DpNd1tv2.js","assets/heartbeats-Dae6h2SU.js","assets/environments-Bj-4l7Ol.js","assets/Routines.production-CDaXZ2Kc.js","assets/label-YjU0jMtG.js","assets/checkbox-5wFlZdZn.js","assets/RoutineRunVariablesDialog-DE5hp-_u.js","assets/MarkdownEditor-D7suACD6.js","assets/dist-CMegW-DS.js","assets/dist-BhxPxuMy.js","assets/select-DRgGQ-iP.js","assets/sheet-CACWxbsc.js","assets/useHiddenSettings-Dz7GWNDr.js","assets/health-D8T5Zr74.js","assets/input-CtLHwxEw.js","assets/company-members-Dd6xBf6K.js","assets/card-PCL2aF_L.js","assets/RoutineDetail.production-C03tDWie.js","assets/arrow-right-bnOoaiPg.js","assets/use-copy-action-qHyHFl14.js","assets/CompanySkills.production-CXPBOlb3.js","assets/use-adapter-capabilities-JhD0-FlQ.js","assets/file-text-Ba5Wddur.js","assets/CompanyActivity.production-Wked11oO.js","assets/OrgChart.production-BjDW9Rac.js"])))=>i.map(i=>d[i]);
2
2
  var eFe=Object.defineProperty;var r=(e,s)=>eFe(e,"name",{value:s,configurable:!0});import{i as v4,n as tFe,t as fj}from"./rolldown-runtime-ZpX3ckPj.js";import{$ as Fq,$n as lge,$r as sFe,$t as cge,A as gy,Ai as w5,An as nFe,Ar as rFe,At as hA,B as Qu,Ba as dge,Bi as aFe,Bn as iFe,Br as uge,Bt as RC,Ci as Bq,Cn as N5,Cr as kk,Ct as Ma,D as y4,Da as jZ,Di as oFe,Dn as lFe,Dr as cFe,Dt as dFe,Ei as C9,En as uFe,Er as mge,Et as mFe,Fi as hFe,Fn as pFe,Fr as hge,Ft as fFe,G as V,Gi as Ce,Gn as xFe,Gr as Ly,Gt as gFe,H as wZ,Hi as bFe,Hn as vFe,Hr as pS,Ht as pge,Ia as pA,Ii as X$,In as fge,Ir as yFe,J as Jr,Ji as jFe,Jn as wFe,Jr as xge,Jt as gge,K as NFe,Ki as kFe,Kn as SFe,Kr as _9,Kt as CFe,L as fS,La as _Fe,Li as DN,Ln as IFe,Lr as LN,Lt as NZ,M as fA,Mi as AFe,Mn as TFe,Mr as RFe,Mt as EFe,Ni as k5,Nn as PFe,Nr as MFe,Oi as DFe,On as LFe,Or as Pb,Ot as kZ,P as $Fe,Pi as OFe,Pn as FFe,Pr as BFe,Pt as zFe,Q as qFe,Qi as S5,Qn as bge,Qr as vge,Qt as xA,R as xj,Ra as Nt,Ri as SZ,Rn as I9,Rr as UFe,Rt as CZ,Si as KFe,Sn as WFe,Sr as A9,St as D,T as Hv,Ti as VFe,Tn as HFe,Tr as zq,Tt as _Z,U as IZ,Ui as Bl,Un as QFe,Ur as yge,Ut as GFe,V as YFe,Va as T9,Vi as R9,Vn as JFe,Vr as C5,Vt as jge,W as E9,Wi as mn,Wn as XFe,Wr as wge,Wt as Nge,X as qd,Xi as mv,Xn as ZFe,Xr as kge,Xt as AZ,Y as Sge,Yn as Cge,Yr as Tf,Yt as wg,Z as br,Zi as eBe,Zn as tBe,Zr as TZ,Zt as sBe,_i as gA,_n as nBe,_r as rBe,_t as aBe,aa as te,ai as iBe,an as _ge,ar as oBe,at as Ng,bi as RZ,bn as qq,br as lBe,bt as mx,ci as j4,cn as EZ,cr as PZ,ct as em,di as Ige,dn as P9,dr as cBe,dt as Age,ea as dBe,ei as Tge,en as MZ,er as uBe,et as Wi,fi as mBe,fn as DZ,fr as Rge,ft as Ege,ga as hBe,gi as pBe,gn as fBe,gr as xBe,gt as Pge,hi as gBe,hn as w4,hr as Mge,ht as ps,ia as ye,ii as Z$,in as B_,ir as LZ,it as _5,j as bBe,ji as $Z,jn as Dge,jr as vBe,jt as Bf,k as yBe,kn as jBe,kr as wBe,kt as zf,li as NBe,ln as kBe,lr as Uq,lt as M9,mi as SBe,mn as Lge,mr as I5,mt as CBe,n as qt,na as Mb,ni as _Be,nn as $h,nr as IBe,nt as Rm,oa as ABe,oi as TBe,on as D9,or as n_,ot as z_,pi as RBe,pn as EBe,pr as PBe,q as $ge,qi as OZ,qn as Oge,qr as MBe,qt as DBe,ra as LBe,ri as $Be,rn as Pm,rr as OBe,rt as ja,si as FBe,sn as q_,sr as KE,st as r_,t as vc,ta as Sk,ti as FZ,tn as BBe,tr as zBe,tt as qBe,ui as N4,un as xS,ur as Kq,ut as gr,va as UBe,vi as Fge,vn as WE,vr as BZ,vt as KBe,wi as Bge,wn as WBe,wr as VBe,wt as zge,xi as A5,xn as qge,xr as HBe,xt as L9,ya as QBe,yi as Uge,yn as Db,yr as zZ,yt as GBe,z as Kl,za as YBe,zi as Kge,zn as qZ,zr as gp,zt as Wge}from"./agent-avatar-url-BnmqahQ7.js";import{t as Id}from"./preload-helper-CceJXRIF.js";import{$ as JBe,$t as UZ,An as ao,At as Gf,B as Vge,Bn as fa,Bt as ur,C as XBe,Cn as VE,Ct as Fl,D as ZBe,Dn as eze,Dt as T5,E as bA,En as tze,Et as Mm,Fn as sze,Ft as by,Gt as Nr,H as nze,Ht as rr,I as Wq,In as rze,It as ug,J as aze,Jt as R5,K as Vq,Ln as oa,Lt as U_,M as z0,Mn as Nd,Mt as Wu,N as ize,Nn as Lb,Nt as k4,On as Hge,Ot as Qge,Pn as nt,Pt as ha,Q as Yf,Qt as oze,R as lze,Rn as Gge,Rt as Dm,S as cze,Sn as dze,St as uze,T as mze,Tn as hze,Tt as S4,Ut as pze,Vn as hi,Vt as Hq,Wt as fze,X as E5,Xt as KZ,Yt as Yge,Z as Jf,Zt as xze,_ as gze,_n as eO,_t as vA,a as HE,an as WZ,at as bze,b as Jge,bn as kg,bt as Xge,c as $b,cn as vze,ct as bn,d as gS,dn as P5,dt as $9,en as yze,et as Pp,f as Gn,fn as M5,ft as No,g as O9,gn as jze,gt as w1,h as wze,hn as VZ,ht as Ud,i as $,in as vT,it as na,j as Nze,jn as kze,jt as gj,k as Sze,kn as Cze,kt as Zge,l as An,ln as sN,lt as qh,mn as ul,mt as Wl,n as Hn,nn as e0e,nt as Mp,o as F9,on as t0e,ot as _ze,pn as bS,pt as yA,qt as Ize,r as Ct,rn as Aze,rt as jA,s as We,sn as Tze,st as mg,t as Rze,tn as Eze,tt as Dp,u as Pze,un as yt,ut as Sp,v as $y,vn as HZ,vt as lm,w as Wm,wn as Mze,wt as wA,x as Dze,xn as Lze,xt as ql,y as C4,yn as Sg,yt as Xi,zn as _4,zt as $ze}from"./BreadcrumbContext-Bxr1TyKN.js";import{C as B9,S as I4,T as vS,_ as Oze,a as Fze,b as Dl,c as ri,d as yS,f as zu,g as Qx,h as jS,l as NA,m as Xo,n as Bg,o as A4,p as wS,r as Bze,s as zze,t as $s,u as qze,v as el,w as kA,x as mo,y as tl}from"./label-YjU0jMtG.js";import{$ as Uze,$n as s0e,$t as Kze,A as z9,An as QZ,Ar as NS,At as Wze,B as Vze,Bn as D5,Br as T4,Bt as Hze,C as Qze,Cn as $N,Cr as n0e,Ct as Qq,D as Gq,Dn as r0e,Dr as SA,Dt as a0e,E as i0e,En as ON,Er as o0e,Et as Gze,Fn as GZ,Fr as l0e,Ft as Oy,G as kS,Gn as Yze,Gt as SS,H as c0e,Hn as L5,Ht as Gx,In as YZ,Ir as Jze,It as Fy,J as Xze,Jn as $5,Jt as Zze,K as bj,Kn as eqe,Kt as tqe,L as d0e,Ln as u0e,Lr as sqe,Lt as K_,M as nqe,Mn as rqe,Mr as JZ,Mt as gb,N as aqe,Nn as m0e,Nr as Gu,Nt as CA,O as iqe,On as O5,Or as oqe,Ot as lqe,P as cqe,Pn as h0e,Pr as zg,Pt as Yq,Q as dqe,Qn as p0e,Qt as XZ,R as uqe,Rn as q9,Rr as Lp,Rt as mqe,S as hqe,Sn as ag,Sr as pqe,St as Jq,T as F5,Tn as W_,Tr as U9,Tt as fqe,U as bb,Un as B5,Ut as f0e,V as qg,Vn as x0e,Vr as tm,Vt as FN,W as Xq,Wn as xqe,Wt as bc,X as gqe,Xn as ZZ,Xt as BN,Y as g0e,Yn as b0e,Yt as bqe,Z as vqe,Zn as v0e,Zt as yqe,_ as jqe,_n as y0e,_r as wqe,_t as _A,a as Nqe,an as kqe,ar as j0e,at as Sqe,b as w0e,bn as z5,br as IA,bt as N0e,c as eee,cn as Ck,cr as k0e,ct as S0e,d as C0e,dr as Cqe,dt as _qe,en as Iqe,er as Ih,et as Aqe,f as _0e,fn as zN,fr as I0e,ft as K9,g as q5,gn as Tqe,gr as R4,gt as $p,h as A0e,hn as T0e,hr as CS,ht as Rqe,i as Eqe,in as W9,ir as vy,it as Pqe,j as Mqe,jn as tee,jr as _S,jt as By,k as Dqe,kn as U5,kr as Xf,kt as Lqe,l as tO,ln as $qe,lr as K5,lt as see,m as R0e,mn as E0e,mr as Oqe,mt as vj,n as Fqe,nn as Bqe,nr as Bm,nt as zqe,o as qqe,on as Ac,or as _k,ot as P0e,p as V_,pn as Uqe,pr as Kqe,pt as M0e,q as Wqe,qn as D0e,qt as Vqe,r as Cg,rn as nee,rr as Zq,rt as L0e,s as Hqe,sn as $0e,sr as V9,st as W5,t as H9,tn as H_,tr as O0e,tt as Qqe,u as Gqe,un as Yqe,ur as Jqe,ut as F0e,v as Xqe,vn as B0e,vr as z0e,vt as Zqe,w as Q9,wn as q0e,wr as G9,wt as Yu,x as sO,xn as U0e,xr as IS,xt as K0e,y as ree,yn as W0e,yr as AS,yt as e6e,z as t6e,zn as V0e,zr as Q_,zt as s6e}from"./RoutineRunVariablesDialog-DE5hp-_u.js";import{Z as zn,a as n6e,at as r6e,et as H0e,o as a6e,ot as i6e,s as o6e}from"./mention-chips-ClRmijVb.js";import{i as l6e}from"./dist-BrRwU9U9.js";import{d as c6e,f as d6e,l as u6e,s as m6e}from"./dist-CvM0_U_m.js";import{a as wc,c as Nc,d as On,f as Wc,i as kc,l as AA,m as Rs,n as Vc,o as Sc,p as Fn,r as Cc,s as _c,t as Ic,u as Bn}from"./alert-dialog-BxpRolrb.js";import{a as bo,c as h6e,i as Ob,l as Hc,n as p6e,o as vo,r as yo,s as Q0e,t as or}from"./AgentAvatar-DZh8tNnK.js";import{C as Y9,D as Wd,E as Ai,O as _i,S as J9,T as da,_ as sb,a as Ws,b as f6e,c as on,d as _g,f as Zr,g as Fb,h as ds,i as x6e,l as g6e,m as ea,n as Qn,o as hn,p as X9,r as zs,s as dr,t as Za,u as Vs,v as Ah,w as ta,x as Z9,y as ni}from"./checkbox-5wFlZdZn.js";import{g as b6e}from"./dist-CMegW-DS.js";import{a as eW,c as ia,d as cd,f as G0e,h as v6e,i as y6e,l as Ni,m as vb,o as j6e,p as Ug,r as w6e,s as Y0e,t as Qc,u as sm}from"./MarkdownEditor-D7suACD6.js";import{i as Ea,n as ma,r as dd,t as Pi}from"./tabs-BfOtoFWj.js";import{_ as Ik,a as tW,b as ud,c as J0e,d as V5,f as X0e,h as ra,i as Z0e,l as ebe,p as tc,t as no,u as tbe,v as sW,x as Vu,y as N6e}from"./StatusIcon-YdJnE47W.js";import{a as pa,c as Uh,i as TA,l as Vm,n as Sh,o as Fi,r as yj,s as Pl,t as jj,u as jl}from"./use-adapter-capabilities-JhD0-FlQ.js";import{t as ml}from"./arrow-right-bnOoaiPg.js";import{t as ro}from"./bot-DpNd1tv2.js";import{t as us}from"./check-BiXfODpl.js";import{a as Qr,i as Ti,n as Td,o as k6e,r as S6e,s as nn,t as C6e}from"./ToastContext-Dh8dPdr5.js";import{a as wr,i as sl,n as nW,o as ko,r as Si,s as Pn,t as Ia}from"./clipboard-CTmezHYG.js";import{a as dn,c as wa,d as _6e,f as Bb,i as I6e,l as Na,n as ka,o as A6e,r as Sa,s as sbe,t as nbe,u as T6e}from"./select-DRgGQ-iP.js";import{i as Ji,n as rW,r as qf,t as Op}from"./use-copy-action-qHyHFl14.js";import{n as yc,t as $n}from"./external-link-LnxJtUIq.js";import{C as R6e,E as Wh,S as yb,T as E6e,_ as P6e,a as M6e,b as D6e,c as L6e,d as rbe,f as $6e,g as aee,h as O6e,i as F6e,l as B6e,m as abe,n as aW,o as ibe,p as obe,r as z6e,s as q6e,t as In,u as U6e,v as Uf,w as K6e,x as zy,y as W6e}from"./MarkdownBody-B5ygzgk6.js";import{t as Ya}from"./file-text-Ba5Wddur.js";import{a as lbe,c as cbe,d as E4,i as G_,l as Vd,n as V6e,o as Fp,r as Vh,s as Hm,t as Hh,u as sc}from"./sheet-CACWxbsc.js";import{a as P4,i as rl,n as H6e,o as dbe,r as RA,t as Xr}from"./heartbeats-Dae6h2SU.js";import{n as Q6e,r as tt,t as ot}from"./badge-D5aOL1Ll.js";import{n as EA,t as vu}from"./useHiddenSettings-Dz7GWNDr.js";import{t as Ii}from"./rotate-ccw-2WnWy1fs.js";import{i as qa,n as vr,r as G6e,t as $i}from"./environments-Bj-4l7Ol.js";import{t as ut}from"./input-CtLHwxEw.js";import{a as Zf,i as PA,n as MA,o as lr,r as Kg,t as TS}from"./company-members-Dd6xBf6K.js";import{t as yu}from"./health-D8T5Zr74.js";import{t as yn}from"./skeleton-DCrngTtF.js";import{a as Y6e,i as qc,n as J6e,o as uo,r as Xa,s as Oo,t as sn}from"./card-PCL2aF_L.js";import{t as Vn}from"./EmptyState-DliXLd04.js";import{t as Pa}from"./PageSkeleton-BZF4K6Hf.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 X6e=class extends hBe{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:UBe(s,n.data),hasPreviousPage:QBe(s,n.data),isFetchNextPageError:u,isFetchingNextPage:h,isFetchPreviousPageError:p,isFetchingPreviousPage:f,isRefetchError:c&&!u&&!p,isRefetching:o&&!h&&!f}}};function Wg(e,s){return ABe(e,X6e,s)}r(Wg,"useInfiniteQuery");var Z6e="adapter_auth_missing",eUe="document",tUe=80,sUe={markdown:"md",html:"html",json:"json",text:"txt"};function nUe(e){return e.normalize("NFKD").replace(/[\u0300-\u036f]/g,"").toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,tUe).replace(/-+$/g,"")||eUe}r(nUe,"documentExportSlug");function rUe(e){return sUe[(e??"").trim().toLowerCase()]??"md"}r(rUe,"documentExportExtension");function iee(e,s){const n=s.replace(/^\.+/,"").toLowerCase()||"md";return`${nUe(e)}.${n}`}r(iee,"documentExportFileName");function e6(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(e6,"decisionEffectTargetIssueIds");var aUe=new Set(["terminated","pending_approval","paused"]),iUe=new Set(["active","idle","running","error"]);function oUe(e){return iUe.has(e)&&!aUe.has(e)}r(oUe,"isAgentStatusInvokable");function EC(e){return e==="done"||e==="cancelled"}r(EC,"isPipelineTerminalStageKind");function ube(e){const s={};for(const n of e)(s[n.stageId]??=[]).push(n);return s}r(ube,"groupWarningsByStage");function mbe(e){return e==="RESPONSIBLE_USER_UNAUTHORIZED"||e==="RESPONSIBLE_USER_UNAVAILABLE"}r(mbe,"isResponsibleUserDenialCode");function DA(e){const s=e?.trim();return s&&s.length>0?s:"the responsible user"}r(DA,"responsibleUserLabel");function t6(e,s={}){const n=DA(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(t6,"describeResponsibleUserDenial");var lUe=["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 cUe(e){const s=e?.trim();return s&&s.length>0?s:"this task"}r(cUe,"issueLabel$2");function dUe(e){const s=e?.trim();return s&&s.length>0?s:"the current assignee"}r(dUe,"assigneeLabel");function uUe(e){const s=e?.trim();return s&&s.length>0?s:"this agent"}r(uUe,"actorLabel$1");var mUe="create a child issue with the request in its description (issue creation is a separate, open write path) and let its assignee act";function hUe(e,s={}){const n=cUe(s.issueIdentifier),a=uUe(s.actorLabel),i=dUe(s.assigneeLabel),o=DA(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 ${mUe}.`};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=t6("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=t6("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(hUe,"describeIssueWriteDenial");function hbe(e){return(typeof e=="string"?e:e?.name??"").trim()}r(hbe,"rawNameOf");function pbe(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(pbe,"looksLikeNetworkAddress");function s6(e){return e.split(/[\s._-]+/).filter(Boolean).map(s=>s.charAt(0).toUpperCase()+s.slice(1).toLowerCase()).join(" ")}r(s6,"titleCaseIdentifier");function pUe(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,""),s6(n)||"Custom app"}r(pUe,"pluginPackageLabel");function ex(e,s={}){const n=s.title?.trim();if(n)return n;const a=hbe(e);if(!a||pbe(a))return"Custom app";const i=pUe(a);if(i)return i;if(a.includes(":")&&!a.includes("://")){const o=a.slice(a.lastIndexOf(":")+1).trim();if(o)return s6(o)}return/\s/.test(a)||/[A-Z]/.test(a)?a:/[._-]/.test(a)?s6(a):a}r(ex,"humanizeConnectionDisplayName");function oee(e){const s=hbe(e);return s&&pbe(s)?`hosted at ${s}`:null}r(oee,"connectionDisplaySecondaryHint");var lee=`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>
@@ -327,7 +327,7 @@ self.onmessage = function (e) {
327
327
  }
328
328
 
329
329
  };
330
- `;function Oot(){const e=new Blob([$ot],{type:"application/javascript"}),s=URL.createObjectURL(e);try{return new Worker(s)}finally{URL.revokeObjectURL(s)}}r(Oot,"createSandboxedWorker");var vU=new Map,DP=new Map,h3=new Set,p3=new Map,K1e=null;function Fot(e){K1e=e}r(Fot,"setDynamicParserResultNotifier");function W1e(e,s){e.worker.postMessage(s)}r(W1e,"sendToWorker");function Bot(e){return e.nextId++}r(Bot,"nextRequestId");function zot(e,s){return`${s}\0${e}`}r(zot,"lineCacheKey");function qot(){K1e?.()}r(qot,"notifyResultReady");function Uot(e,s,n){return new Promise(a=>{const i=Bot(e);e.pendingResolves.set(i,a),W1e(e,{type:"parse",id:i,line:s,ts:n})})}r(Uot,"parseLineAsync");function T1(e){for(const s of e.pendingResolves.values())s([]);e.pendingResolves.clear()}r(T1,"drainPendingRequests");function Kot(e){return new Promise((s,n)=>{const a=Oot(),i={worker:a,ready:!1,nextId:1,pendingResolves:new Map},o=setTimeout(()=>{T1(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"&&T1(i)},s(i);return}if(c.type==="error"){clearTimeout(o),T1(i),a.terminate(),n(new Error(c.message));return}},a.onerror=l=>{clearTimeout(o),T1(i),a.terminate(),n(new Error(`Worker error: ${l.message}`))},W1e(i,{type:"init",source:e})})}r(Kot,"initSandboxedWorker");function Wot(e){const s=new Map,n=new Set;return{parseStdoutLine:r((i,o)=>{const l=zot(i,o),c=s.get(l);return c?c.slice():(n.has(l)||(n.add(l),Uot(e,i,o).then(d=>{n.delete(l),s.set(l,d),qot()})),[])},"parseStdoutLine")}}r(Wot,"buildParserModule");async function yU(e){const s=DP.get(e);if(s)return s;if(h3.has(e))return null;const n=p3.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 h3.add(e),null;const o=await Kot(await i.text());vU.set(e,o);const l=Wot(o);return DP.set(e,l),l}catch{return h3.add(e),null}finally{p3.delete(e)}})();return p3.set(e,a),a}r(yU,"loadDynamicParser");function jU(e){const s=DP.has(e);DP.delete(e),h3.delete(e),p3.delete(e);const n=vU.get(e);return n&&(T1(n),n.worker.terminate(),vU.delete(e)),s}r(jU,"invalidateDynamicParser");var f3=[],_D=new Map,wU=new Set,V1e=new Map,nF=new Set,LT=new Map,NU=new Set;function H1e(e){return NU.add(e),()=>NU.delete(e)}r(H1e,"onAdapterChange");function Q1e(){for(const e of NU)e()}r(Q1e,"notifyAdapterChange");Fot(Q1e);function Vot(){for(const e of[_rt,Urt,cat,fat,Oat,Jat,cit,bit,Ait,Fit,cot,sot,Iat,Sot,MP,Lot])wU.add(e.type),V1e.set(e.type,e),Yv(e)}r(Vot,"registerBuiltInUIAdapters");function Yv(e){const s=f3.findIndex(n=>n.type===e.type);s>=0?f3.splice(s,1,e):f3.push(e),_D.set(e.type,e),Q1e()}r(Yv,"registerUIAdapter");function G1e(e){return _D.get(e)??null}r(G1e,"findUIAdapter");Vot();function KS(e){const s=_D.get(e);if(!s){let n=!1;return{type:e,label:e,parseStdoutLine:r((a,i)=>(n||(n=!0,yU(e).then(o=>{o&&Yv({type:e,label:e,parseStdoutLine:o.parseStdoutLine,createStdoutParser:o.createStdoutParser,ConfigFields:Gy,buildAdapterConfig:Yy})})),MP.parseStdoutLine(a,i)),"parseStdoutLine"),ConfigFields:Gy,buildAdapterConfig:Yy}}return s}r(KS,"getUIAdapter");function Hot(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 wU){const i=V1e.get(a);if(!i)continue;const o=n.has(a),l=s.has(a),c=nF.has(a);if(o&&l&&!c){nF.add(a);const d=(LT.get(a)??0)+1;LT.set(a,d);let u=!1;const h=i.parseStdoutLine,p=e.find(f=>f.type===a)?.label??a;Yv({type:a,label:p,parseStdoutLine:r((f,x)=>(u||(u=!0,yU(a).then(b=>{b&&LT.get(a)===d&&Yv({type:a,label:p,parseStdoutLine:b.parseStdoutLine,createStdoutParser:b.createStdoutParser,ConfigFields:i.ConfigFields,buildAdapterConfig:i.buildAdapterConfig})})),h(f,x)),"parseStdoutLine"),ConfigFields:i.ConfigFields,buildAdapterConfig:i.buildAdapterConfig})}else(!o||!l)&&c&&(nF.delete(a),LT.delete(a),jU(a),Yv(i))}for(const{type:a,label:i}of e){if(wU.has(a))continue;const o=_D.get(a);if(o&&o!==MP)continue;let l=!1;const c=o?.parseStdoutLine??MP.parseStdoutLine;Yv({type:a,label:i,parseStdoutLine:r((d,u)=>(l||(l=!0,yU(a).then(h=>{h&&Yv({type:a,label:i,parseStdoutLine:h.parseStdoutLine,createStdoutParser:h.createStdoutParser,ConfigFields:o?.ConfigFields??Gy,buildAdapterConfig:o?.buildAdapterConfig??Yy})})),c(d,u)),"parseStdoutLine"),ConfigFields:o?.ConfigFields??Gy,buildAdapterConfig:o?.buildAdapterConfig??Yy})}}r(Hot,"syncExternalAdapters");function vH(){return[...f3]}r(vH,"listUIAdapters");function kU(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(kU,"resolveStdoutParser");function Y1e(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(Y1e,"appendTranscriptEntry");function Qot(e,s){for(const n of s)Y1e(e,n)}r(Qot,"appendTranscriptEntries");function Got(e,s=160){return e.length<=s?e:`${e.slice(0,s-3)}...`}r(Got,"truncateTranscriptLine");function Yot(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(Yot,"formatTranscriptParserError");function Jot(e,s,n,a){const i=Yot(n)||"unknown parser error",o=Got(e);return{kind:"result",ts:s,text:Tm(`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(Jot,"createTranscriptParseErrorEntry");function yH(e){const{entries:s,line:n,ts:a,parseLine:i,reset:o,redactionOptions:l}=e;try{Qot(s,i(n,a).map(c=>Ust(c,l)))}catch(c){o?.(),Y1e(s,Jot(n,a,c,l))}}r(yH,"appendParsedTranscriptLine");function J1e(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:Tm(u.chunk,l)});continue}if(u.stream==="system"){s.push({kind:"system",ts:u.ts,text:Tm(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&&yH({entries:s,line:f,ts:u.ts,parseLine:i,reset:o,redactionOptions:l})}}return c}r(J1e,"foldTranscriptChunks");function X1e(e,s,n){const a=[],i={enabled:n?.censorUsernameInLogs??!1},{parseLine:o,reset:l}=kU(s),c=J1e({entries:a,chunks:e,from:0,stdoutBuffer:"",parseLine:o,reset:l,redactionOptions:i}).trim();return c&&yH({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(X1e,"buildTranscript");var Fne=[];function Xot(e,s){const n={enabled:s?.censorUsernameInLogs??!1},a=typeof e!="function"&&typeof e.createStdoutParser=="function";let i=kU(e),o=[],l="",c=Fne,d=[];const u=r(()=>{i=kU(e),o=[],l="",c=Fne},"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 X1e(f,e,s);const b=o.slice(),v=b.length-1;return v>=0&&(b[v]={...b[v]}),x&&yH({entries:b,line:x,ts:f.length>0?f[f.length-1].ts:new Date().toISOString(),parseLine:i.parseLine,reset:i.reset,redactionOptions:n}),b},"publish");return{update(f){return f===c||(h(f)||u(),l=J1e({entries:o,chunks:f,from:c.length,stdoutBuffer:l,parseLine:i.parseLine,reset:i.reset,redactionOptions:n}),c=f,d=p(f)),d}}}r(Xot,"createIncrementalTranscript");function Zot({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(b=>b.status!=="terminated"&&!u.has(b.id)),p=s?e.find(b=>b.id===s):null,f=p?.status==="terminated",x=!!(s&&!p);return(0,t.jsxs)(ur,{open:c,onOpenChange:d,children:[(0,t.jsx)(Nr,{asChild:!0,children:(0,t.jsx)("button",{type:"button",className:V("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)(cd,{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)(or,{agent:p,size:16,className:"h-3 w-3 shrink-0 text-muted-foreground"}),(0,t.jsx)("span",{className:V("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)(cd,{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)(rr,{className:"w-48 p-1",align:"start",children:[(0,t.jsx)("button",{type:"button",className:V("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)(or,{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(b=>(0,t.jsxs)("button",{type:"button",className:V("flex items-center gap-2 w-full min-w-0 px-2 py-1.5 text-xs rounded hover:bg-accent/50 overflow-hidden",b.id===s&&"bg-accent"),onClick:r(()=>{n(b.id),d(!1)},"onClick"),children:[(0,t.jsx)(or,{agent:b,size:16,className:"shrink-0 h-3 w-3 text-muted-foreground"}),(0,t.jsx)("span",{className:"min-w-0 truncate",children:b.name}),(0,t.jsx)("span",{className:"text-muted-foreground ml-auto shrink-0",children:cH[b.role]??b.role})]},b.id))]})]})}r(Zot,"ReportsToPicker");var elt="__secret_folder__:";function tlt(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(tlt,"statusBadge");function Z1e(e){return e.split("/").filter(s=>s.length>0)}r(Z1e,"splitSecretPath$1");function x3(e){return e.join("/")}r(x3,"pathKey$1");function FC(e){return e.length>0?`/${e.join("/")}`:"/"}r(FC,"pathLabel");function slt(e,s){return e.length<s.length?!1:s.every((n,a)=>e[a]===n)}r(slt,"pathStartsWith");function Bne(e){return`${elt}${x3(e)}`}r(Bne,"folderValue");function nlt(e,s,n){const a=s.length,i=new Map,o=[];for(const c of e){const d=Z1e(c.name);if(slt(d,s)){if(d.length>a+1){const u=d.slice(0,a+1),h=x3(u);if(!i.has(h)){const p=u[u.length-1]??"/",f=FC(u);i.set(h,{key:`folder-${h||"root"}`,value:Bne(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-${x3(s)}`,value:Bne(c),label:"Up one folder",title:FC(c),searchText:FC(c),kind:"back",folderPath:x3(c),pathHint:FC(c)})}return l.push(...i.values(),...o),{id:"browse-secrets",label:s.length>0?FC(s):"Browse secrets",options:l}}r(nlt,"buildFolderGroup");function jH({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(j=>j.id===e)??null,[s,e]),p=!!e&&!h,f=(0,m.useMemo)(()=>d?d.split("/"):[],[d]),x=(0,m.useMemo)(()=>s.some(j=>Z1e(j.name).length>1),[s]),b=(0,m.useMemo)(()=>{const j=[];p&&j.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 N=(n??[]).filter(w=>w.status==="active"&&w.id!==e);return N.length>0&&j.push({id:"recently-used",label:"Recently used",options:N.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"}))}),j.push({id:"all-secrets",label:N.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}))}),j},[p,n,e,s]),v=(0,m.useCallback)((j,N)=>{if(!x||Bze(j))return N;const w=nlt(s,f,e),k=N.filter(S=>S.id==="current-missing"||S.id==="recently-used");return w.options.length>0?[...k,w]:k},[f,x,e,s]);return(0,t.jsx)(Bg,{value:e||"",groups:b,onValueChange:r((j,N)=>{if(N.folderPath!==void 0)return u(N.folderPath),!1;u(""),i(j)},"onValueChange"),deriveGroups:v,disabled:a,disablePortal:c,placeholder:"Select secret…",searchPlaceholder:"Search secrets…",emptyMessage:"No matching secrets",triggerClassName:V("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(j=>{if(!j)return(0,t.jsx)("span",{className:"text-muted-foreground",children:"Select secret…"});if(j.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:j.label})]});const N=j.status&&j.status!=="active";return(0,t.jsxs)("span",{className:"flex w-full min-w-0 items-center gap-1.5",title:j.title,children:[(0,t.jsx)(Si,{className:V("size-3.5 shrink-0",N?"text-amber-600":"text-muted-foreground")}),(0,t.jsx)("span",{className:"min-w-0 flex-1 truncate",children:j.label}),N?(0,t.jsxs)("span",{className:"text-amber-600",children:["(",j.status,")"]}):null]})},"renderValue"),renderOption:r((j,{selected:N})=>{if(j.kind==="folder"||j.kind==="back"){const w=j.kind==="back"?PKe:ql;return(0,t.jsxs)("span",{className:"flex min-w-0 flex-1 items-center gap-1.5",title:j.title??j.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:V("truncate text-sm",N&&"font-medium"),children:j.label}),j.pathHint?(0,t.jsx)("span",{className:"truncate font-mono text-(length:--text-micro) text-muted-foreground",children:j.pathHint}):null]})]})}return(0,t.jsxs)("span",{className:V("flex min-w-0 flex-1 items-center gap-1.5",j.disabled&&"opacity-60"),title:j.title??j.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:V("min-w-0 truncate font-mono text-sm",N&&"font-medium"),children:j.label}),j.pathHint&&j.pathHint!==j.label?(0,t.jsx)("span",{className:"truncate font-mono text-(length:--text-micro) text-muted-foreground",children:j.pathHint}):null]}),tlt(j.status)]})},"renderOption"),createItem:o?{render:r(j=>(0,t.jsxs)("span",{className:"flex items-center gap-1.5 text-sm",children:[(0,t.jsx)(bn,{className:"size-3.5 shrink-0"}),j.trim()?(0,t.jsxs)("span",{children:["Create secret ",(0,t.jsxs)("span",{className:"font-mono",children:["“",j.trim(),"”"]}),"…"]}):(0,t.jsx)("span",{children:"Create new secret…"})]}),"render"),onSelect:r(j=>o(j),"onSelect")}:void 0})}r(jH,"SecretPicker");var rlt=/^[a-z][a-z0-9_]*$/,zne="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 e_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),[b,v]=(0,m.useState)(null),[j,N]=(0,m.useState)(!1),w=l.trim(),k=w?rlt.test(w)?a?.some(A=>A.toLowerCase()===w)?"A secret with this name already exists":null:"Use lowercase letters, digits and _":j?"Name is required":null,S=d.length===0&&j?"Value is required":null,C=!f&&w.length>0&&d.length>0&&!k;async function _(){if(N(!0),!!C){x(!0),v(null);try{await o(w,d)}catch(A){v(A instanceof Error?A.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)(fze,{className:"text-sm font-medium",children:e==="create"?"Create secret":"Store value as secret"}),e==="store"?(0,t.jsxs)(pze,{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:V(zne,k&&"border-destructive focus-visible:ring-destructive/40"),value:l,autoFocus:!0,spellCheck:!1,placeholder:"secret_name","aria-label":"Secret name","aria-invalid":k?!0:void 0,onChange:r(A=>c(A.target.value),"onChange"),onBlur:r(()=>N(!0),"onBlur"),onKeyDown:r(A=>{A.key==="Enter"&&(A.preventDefault(),_())},"onKeyDown")}),k?(0,t.jsx)("span",{className:"block text-(length:--text-micro) text-destructive",children:k}):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:V(zne,"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"?A=>u(A.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(A=>!A),"onClick"),children:h?(0,t.jsx)(Qm,{className:"h-3.5 w-3.5"}):(0,t.jsx)(Wd,{className:"h-3.5 w-3.5"})})]}),S?(0,t.jsx)("span",{className:"block text-(length:--text-micro) text-destructive",children:S}):null]}),b?(0,t.jsx)("p",{className:"text-(length:--text-micro) text-destructive",children:b}):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)(tt,{className:"h-3.5 w-3.5 animate-spin"}):null,R]})]})]})}r(e_e,"SecretPopoverForm");function t_e(e){return(0,t.jsx)(e_e,{mode:"create",...e})}r(t_e,"CreateSecretPopover");function alt(e){return(0,t.jsx)(e_e,{mode:"store",...e})}r(alt,"ConvertToSecretPopover");var ilt=/(api[-_]?key|access[-_]?token|auth(?:_?token)?|authorization|bearer|secret|passwd|password|credential|jwt|private[-_]?key|cookie|connectionstring)/i,olt=[/^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 llt(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(llt,"looksHighEntropy");function clt(e,s){return s?ilt.test(e)||olt.some(n=>n.test(s))?!0:llt(s):!1}r(clt,"isSensitiveEnv");var qne=0;function dlt(){return qne+=1,`env-row-${qne}`}r(dlt,"nextRowId");function Zx(e="text"){return{id:dlt(),name:"",source:e,textValue:"",secretId:"",userSecretKey:"",required:!0,version:"latest"}}r(Zx,"emptyRow");function ult(e){return typeof e=="object"&&e!==null&&"type"in e&&e.type==="secret_ref"}r(ult,"isSecretRef");function mlt(e){return typeof e=="object"&&e!==null&&"type"in e&&e.type==="plain"}r(mlt,"isPlainObj");function hlt(e){return typeof e=="object"&&e!==null&&"type"in e&&e.type==="user_secret_ref"}r(hlt,"isUserSecretRef");function rF(e){return!e||typeof e!="object"?[]:Object.entries(e).map(([s,n])=>{if(typeof n=="string")return{...Zx(),name:s,textValue:n};if(ult(n)){const a=typeof n.version=="number"?n.version:"latest";return{...Zx(),name:s,source:"secret",secretId:typeof n.secretId=="string"?n.secretId:"",version:a}}if(hlt(n)){const a=typeof n.version=="number"?n.version:"latest";return{...Zx(),name:s,source:"user_secret",userSecretKey:typeof n.key=="string"?n.key:"",required:n.required!==!1,version:a}}return mlt(n)?{...Zx(),name:s,source:"text",textValue:typeof n.value=="string"?n.value:""}:{...Zx(),name:s}})}r(rF,"rowsFromValue");function g3(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(g3,"valueFromRows");var Une="CLAUDE_CODE_OAUTH_TOKEN";function kN(){return g3([{...Zx("user_secret"),name:"CLAUDE_CODE_OAUTH_TOKEN",userSecretKey:"CLAUDE_CODE_OAUTH_TOKEN",required:!0,version:"latest"}])??{}}r(kN,"buildFixedClaudeOAuthBinding");var plt=/^[A-Za-z_][A-Za-z0-9_]*$/;function flt(e,s,n){const a=e.trim();if(!a)return null;if(!plt.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(flt,"validateName");function xlt(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(xlt,"computeDuplicateNames");function glt(e,s){return s===e.source?{kind:"noop"}:s==="secret"?e.textValue.trim()?{kind:"open-store",name:LP(e.name)||"secret",value:e.textValue}:{kind:"to-secret"}:{kind:"to-text",undoFrom:e.secretId?{...e}:null}}r(glt,"planSourceSwitch");function s_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(s_e,"computeRowHealth");function n_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(n_e,"computeUserSecretRowHealth");function LP(e){return e.trim().toLowerCase().replace(/[^a-z0-9_]+/g,"_").replace(/^_+|_+$/g,"").slice(0,64)}r(LP,"secretNameFromKey");function x_(e){return e.trim().toUpperCase().replace(/[^A-Z0-9_]+/g,"_").replace(/^_+|_+$/g,"").slice(0,64)}r(x_,"envKeyFromSecretName");var blt="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",Kne="min-w-0 flex-1 bg-transparent px-2 py-1.5 text-sm font-mono outline-none placeholder:text-muted-foreground/40";function vlt({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:b,onToast:v,focusRequest:j,onFocusConsumed:N}){const w=(0,m.useRef)(null),k=(0,m.useRef)(null),S=(0,m.useRef)(null),[C,_]=(0,m.useState)(null),[R,A]=(0,m.useState)(!1),[T,E]=(0,m.useState)(null),L=s_e(e,n)??n_e(e,a),O=e.source==="secret"?n.find(X=>X.id===e.secretId)??null:null,P=(a?.length??0)>0,U=e.source==="text"&&!e.sensitiveDismissed&&clt(e.name,e.textValue);(0,m.useEffect)(()=>{j&&(j==="name"?w.current?.focus():e.source==="text"?k.current?.focus():e.source==="secret"?S.current?.querySelector("[role=combobox]")?.focus():S.current?.querySelector("select,input")?.focus(),N())},[j,N,e.source]),(0,m.useEffect)(()=>{if(!T)return;const X=window.setTimeout(()=>E(null),5e3);return()=>window.clearTimeout(X)},[T]);function M(X){if(X==="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 ne=glt(e,X);switch(ne.kind){case"noop":return;case"open-store":{const{name:oe,value:G}=ne;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":ne.undoFrom&&E(ne.undoFrom),u({source:"text",secretId:"",userSecretKey:"",required:!0,version:"latest"}),window.setTimeout(()=>k.current?.focus(),0);return}}r(M,"switchSource");async function B(X,ne){const oe=await b(X,ne);u({source:"secret",secretId:oe.id,userSecretKey:"",required:!0,version:"latest",textValue:""}),v(`Secret ${oe.name} created`),_(null)}r(B,"submitSecretPopover");function q(){const X=LP(e.name)||"secret",{textValue:ne}=e;window.setTimeout(()=>_({mode:"store",name:X,value:ne}),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`,W=`${e.id}-health`,Q=d.name||d.value,re=O?Math.max(0,O.latestVersion):0,J=e.version==="latest"?"latest":`v${e.version}`,ie=e.version!=="latest";return(0,t.jsxs)("div",{className:V("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",Q&&"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:V(blt,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(X=>u({name:X.target.value}),"onChange"),onBlur:p,onPaste:r(X=>{e.name||f(X.clipboardData.getData("text"))&&X.preventDefault()},"onPaste"),onKeyDown:r(X=>{X.key==="Enter"&&(X.preventDefault(),e.source==="text"?k.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)(ur,{open:C!==null,onOpenChange:r(X=>{X||_(null)},"onOpenChange"),children:[(0,t.jsx)(Hq,{asChild:!0,children:(0,t.jsxs)("div",{ref:S,className:V("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)(Zr,{children:[(0,t.jsxs)(Bn,{children:[(0,t.jsx)(Fn,{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)(x8e,{className:"size-3.5"}):e.source==="secret"?(0,t.jsx)(Si,{className:"size-3.5"}):(0,t.jsx)(Gm,{className:"size-3.5"}),(0,t.jsx)(nn,{className:"size-3 opacity-60"})]})})}),(0,t.jsx)(On,{side:"top",children:z})]}),(0,t.jsxs)(ea,{align:"start",className:"w-56",children:[(0,t.jsxs)(ds,{className:"flex-col items-start gap-0.5",onSelect:r(()=>M("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)(ds,{className:"flex-col items-start gap-0.5",onSelect:r(()=>M("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)(ds,{className:"flex-col items-start gap-0.5",onSelect:r(()=>M("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:k,className:Kne,placeholder:"value",value:e.textValue,type:U?"password":"text",spellCheck:!1,disabled:o,"aria-label":"Variable value",onChange:r(X=>u({textValue:X.target.value}),"onChange"),onKeyDown:r(X=>{X.key==="Enter"&&s&&(X.preventDefault(),x())},"onKeyDown")}),U?(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)(jc,{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)(zn,{className:"size-3"})})]}):null]}):e.source==="secret"?(0,t.jsxs)("div",{className:"relative min-w-0 flex-1",children:[(0,t.jsx)(jH,{secretId:e.secretId,secrets:n,recentlyUsedSecrets:i,disabled:o,onSelect:r(X=>u({secretId:X,version:"latest"}),"onSelect"),onCreateNew:r(X=>_({mode:"create",name:LP(X)||X.trim(),value:""}),"onCreateNew"),triggerClassName:V("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)(ur,{open:R,onOpenChange:A,children:[(0,t.jsx)(Hq,{asChild:!0,children:(0,t.jsx)("button",{type:"button",disabled:o,onClick:r(X=>{X.preventDefault(),X.stopPropagation(),A(ne=>!ne)},"onClick"),"aria-label":"Version",className:V("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:J})}),(0,t.jsxs)(rr,{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"}),A(!1)},"onClick"),className:V("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:re},(X,ne)=>re-ne).filter(X=>X>0).map(X=>(0,t.jsxs)("button",{type:"button",role:"radio","aria-checked":e.version===X,onClick:r(()=>{u({version:X}),A(!1)},"onClick"),className:V("flex w-full items-center rounded px-2 py-1.5 text-sm hover:bg-accent",e.version===X&&"font-medium text-amber-700 dark:text-amber-400"),children:["v",X]},X))]})]}):null]}):(0,t.jsxs)("div",{className:"grid min-w-0 flex-1 grid-cols-(--gtc-13)",children:[P?(0,t.jsxs)("select",{"aria-label":"User secret",value:e.userSecretKey,disabled:o,onChange:r(X=>{const ne=X.target.value,oe=a?.find(G=>G.key===ne);u({userSecretKey:ne,...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(X=>X.key===e.userSecretKey)?(0,t.jsxs)("option",{value:e.userSecretKey,children:["Unknown (",e.userSecretKey,")"]}):null,(a??[]).map(X=>(0,t.jsxs)("option",{value:X.key,children:[X.name,X.status!=="active"?` (${X.status})`:""]},X.id))]}):(0,t.jsx)("input",{className:Kne,placeholder:"user-secret key",value:e.userSecretKey,spellCheck:!1,disabled:o,"aria-label":"User secret key",onChange:r(X=>u({userSecretKey:X.target.value}),"onChange")}),(0,t.jsxs)("select",{"aria-label":"Requirement",value:e.required?"required":"optional",disabled:o,onChange:r(X=>u({required:X.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)(rr,{align:"start",className:"w-auto p-3",onInteractOutside:r(X=>{const ne=X.detail.originalEvent.target;ne&&S.current?.contains(ne)&&X.preventDefault()},"onInteractOutside"),children:C?.mode==="store"?(0,t.jsx)(alt,{initialName:C.name,initialValue:C.value,existingSecretNames:n.map(X=>X.name),onCancel:r(()=>_(null),"onCancel"),onSubmit:B}):C?.mode==="create"?(0,t.jsx)(t_e,{initialName:C.name,initialValue:C.value,existingSecretNames:n.map(X=>X.name),onCancel:r(()=>_(null),"onCancel"),onSubmit:B}):null})]}),L?(0,t.jsx)("p",{id:W,role:"status",className:V("mt-0.5 text-(length:--text-micro)",L.level==="error"?"text-destructive":"text-amber-600 dark:text-amber-400"),children:L.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:V("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"&&!U&&(e.name.trim()||e.textValue)?(0,t.jsxs)(Zr,{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)(ea,{align:"end",children:(0,t.jsx)(ds,{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)(zn,{className:"size-4"})})]})]})}r(vlt,"EnvironmentVariableRow");var ylt=/^\s*(?:export\s+)?([A-Za-z_][A-Za-z0-9_]*)\s*=(.*)$/;function jlt(e){const s=e.indexOf(" #");return s>=0?e.slice(0,s):e}r(jlt,"stripInlineComment");function wlt(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 jlt(s).trim()}r(wlt,"unquote");function Nlt(e){const s=[];for(const n of e.split(/\r?\n/)){const a=n.trim();if(!a||a.startsWith("#"))continue;const i=ylt.exec(a);if(!i)continue;const o=i[1],l=wlt(i[2]);s.push({key:o,value:l})}return s}r(Nlt,"parseDotenv");var klt=["PAPERCLIP_"],Slt="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 SU(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(SU,"normalizedEnvEntries");function BC(e){return JSON.stringify(SU(e))}r(BC,"normalizedEnvKey");var aF=3;function iF(e){const s=e.slice(0,aF).join(", ");return e.length>aF?`${s} +${e.length-aF} more`:s}r(iF,"formatChangedNames");function Wne(e){return e.map(s=>({...s}))}r(Wne,"cloneRows");function Clt(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(Clt,"rowDirtyFields");var Jy=(0,m.forwardRef)(r(function({value:s,onChange:n,secrets:a,userSecretDefinitions:i,onCreateSecret:o,recentlyUsedSecrets:l,disabled:c,reservedPrefixes:d=klt,footerHint:u,onDirtyChange:h,hideDraftActions:p=!1},f){const x=Td(),b=(0,m.useRef)(null),[v,j]=(0,m.useState)(()=>rF(s)),N=(0,m.useRef)(v),[w,k]=(0,m.useState)(()=>Wne(v)),S=(0,m.useMemo)(()=>BC(s),[]),C=(0,m.useRef)(S),_=(0,m.useRef)(S),R=(0,m.useRef)(null),[A,T]=(0,m.useState)(S),[E,L]=(0,m.useState)(()=>new Set(rF(s).map(le=>le.name.trim()).filter(Boolean))),[O,P]=(0,m.useState)(null);(0,m.useEffect)(()=>{N.current=v},[v]);function U(le,fe=N.current){C.current=le,T(le),k(Wne(fe))}r(U,"markCommitted");function M(le){L(fe=>{const de=new Set(fe);for(const Ee of le){const Me=Ee.name.trim();Me&&de.add(Me)}return de})}r(M,"touchCommittedNames");function B(le){const fe=rF(le);return j(fe),M(fe),fe}r(B,"adoptExternalValue"),(0,m.useEffect)(()=>{const le=BC(s);if(le===_.current)return;_.current=le;const fe=BC(g3(N.current)),de=fe!==C.current,Ee=R.current===le;if(Ee&&(R.current=null),!de){U(le,B(s));return}(Ee||fe===le)&&(M(N.current),U(le))},[s]);const q=(0,m.useMemo)(()=>g3(v),[v]),z=(0,m.useMemo)(()=>BC(q),[q]),K=z!==A;(0,m.useEffect)(()=>{h?.(!c&&K)},[c,K,h]);const W=(0,m.useMemo)(()=>{const le=new Map(SU(g3(w)).map(([Me,ve])=>[Me,JSON.stringify(ve)])),fe=new Map(SU(q).map(([Me,ve])=>[Me,JSON.stringify(ve)])),de=[],Ee=[];for(const[Me,ve]of fe)le.has(Me)?le.get(Me)!==ve&&Ee.push(Me):de.push(Me);return{added:de,changed:Ee,removed:[...le.keys()].filter(Me=>!fe.has(Me))}},[w,q]),Q=(0,m.useMemo)(()=>{const le=[];return W.added.length>0&&le.push(`New: ${iF(W.added)}`),W.changed.length>0&&le.push(`Edited: ${iF(W.changed)}`),W.removed.length>0&&le.push(`Removed: ${iF(W.removed)}`),le.join(" · ")},[W]);(0,m.useEffect)(()=>{if(c||!K)return;function le(fe){fe.preventDefault(),fe.returnValue=""}return r(le,"handleBeforeUnload"),window.addEventListener("beforeunload",le),()=>window.removeEventListener("beforeunload",le)},[c,K]);const re=(0,m.useCallback)(()=>c||!K?null:(R.current=z,(0,_p.flushSync)(()=>{n(q)}),q??{}),[c,q,z,K,n]);(0,m.useImperativeHandle)(f,()=>({flushPendingDraft:re}),[re]),(0,m.useEffect)(()=>{const le=b.current?.closest("form");if(!le)return;function fe(){re()}return r(fe,"handleSubmit"),le.addEventListener("submit",fe,!0),()=>le.removeEventListener("submit",fe,!0)},[re]),(0,m.useEffect)(()=>{const le=b.current;if(!le)return;const fe=le;function de(Ee){const Me=Ee.target;if(!(Me instanceof Element)||fe.contains(Me))return;const ve=Me.closest("button");if(!ve||ve.disabled)return;const Ie=`${ve.getAttribute("aria-label")??""} ${ve.textContent??""}`;(ve.type==="submit"||/\b(save|create|update|test|import)\b/i.test(Ie))&&re()}return r(de,"handleDocumentClick"),document.addEventListener("click",de,!0),()=>document.removeEventListener("click",de,!0)},[re]);function J(le){j(le)}r(J,"updateDraft");function ie(le,fe){J(v.map(de=>de.id===le?{...de,...fe}:de))}r(ie,"patchRow");function X(le){J(v.filter(fe=>fe.id!==le))}r(X,"removeRow");function ne(){const le=Zx();j([...v,le]),P({rowId:le.id,field:"name"})}r(ne,"addRow");function oe(le){const fe=v.find(de=>de.id===le)?.name.trim();fe&&L(de=>{if(de.has(fe))return de;const Ee=new Set(de);return Ee.add(fe),Ee})}r(oe,"markTouched");function G(le,fe){const de=Nlt(le);if(de.length===0)return!1;const Ee=v.filter(Me=>Me.id!==fe).map(Me=>({...Me}));for(const{key:Me,value:ve}of de){const Ie=Ee.find(Ze=>Ze.name.trim()===Me);Ie?(Ie.name=Me,Ie.source="text",Ie.textValue=ve,Ie.secretId="",Ie.sensitiveDismissed=!1,Ie.userSecretKey="",Ie.required=!0):Ee.push({...Zx(),name:Me,textValue:ve})}return J(Ee),x?.pushToast({title:`Imported ${de.length} variable${de.length===1?"":"s"}`,tone:"success"}),!0}r(G,"bulkImport");function Z(le){const fe=v.map(Me=>({...Me})),de=fe[fe.length-1];let Ee;de&&!de.name&&!de.textValue&&!de.secretId&&!de.userSecretKey?Ee=de:(Ee=Zx(),fe.push(Ee)),Ee.source="secret",Ee.secretId=le.id,Ee.version="latest",Ee.name||(Ee.name=x_(le.name)),J(fe)}r(Z,"bindRecentSecret");function Y(){K&&(R.current=z,n(q))}r(Y,"saveDraft");function ae(){R.current=null,_.current=BC(s);const le=B(s);U(_.current,le)}r(ae,"revertDraft");const se=(0,m.useMemo)(()=>xlt(v),[v]),ce=(0,m.useMemo)(()=>v.reduce((le,fe)=>s_e(fe,a)||n_e(fe,i)?le+1:le,0),[v,a,i]),pe=(0,m.useMemo)(()=>{const le=new Set(v.filter(fe=>fe.source==="secret"&&fe.secretId).map(fe=>fe.secretId));return(l??[]).filter(fe=>fe.status==="active"&&!le.has(fe.id)).slice(0,8)},[l,v]),we=v.length>0,Se=u===void 0?Slt:u,Te=(0,m.useMemo)(()=>new Map(w.map(le=>[le.id,le])),[w]);return(0,t.jsx)(Wc,{children:(0,t.jsxs)("div",{ref:b,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,we?(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((le,fe)=>{const de=flt(le.name,se,d),Ee=E.has(le.name.trim());return(0,t.jsx)(vlt,{row:le,isLast:fe===v.length-1,secrets:a,userSecretDefinitions:i,recentlyUsedSecrets:l,disabled:c,nameIssue:de,showNameIssue:Ee,dirtyFields:Clt(le,Te.get(le.id)),onPatch:r(Me=>ie(le.id,Me),"onPatch"),onRemove:r(()=>X(le.id),"onRemove"),onNameBlur:r(()=>oe(le.id),"onNameBlur"),onNamePaste:r(Me=>G(Me,le.id),"onNamePaste"),onEnterInValueLast:ne,onCreateSecret:o,onToast:r(Me=>x?.pushToast({title:Me,tone:"success"}),"onToast"),focusRequest:O?.rowId===le.id?O.field:null,onFocusConsumed:r(()=>P(null),"onFocusConsumed")},le.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:ne,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(le=>(0,t.jsxs)("button",{type:"button",onClick:r(()=>Z(le),"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 ${le.name}`,children:["+ ",le.name]},le.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"})]}),Q?(0,t.jsx)("p",{className:"min-w-0 truncate pl-4 text-xs text-amber-950/80 dark:text-amber-100/80",title:Q,children:Q}):null]}),(0,t.jsxs)("div",{className:"flex items-center gap-2",children:[(0,t.jsxs)("button",{type:"button",onClick:ae,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)(Ii,{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)(qf,{className:"size-4"}),"Save"]})]})]}):null,Se?(0,t.jsx)("p",{className:"text-(length:--text-micro) text-muted-foreground/70",children:Se}):null,v.some(le=>le.source==="user_secret"&&le.userSecretKey)?(0,t.jsxs)("p",{className:"inline-flex items-start gap-1 text-(length:--text-micro) text-muted-foreground/70",children:[(0,t.jsx)(Gm,{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")),_lt="env.",r2="access.",CU=/^[A-Za-z_][A-Za-z0-9_]*$/;function r_e(e){return e?e.startsWith("access.")?"api":e.startsWith("env.")?"env":"config":"config"}r(r_e,"deliveryModeForConfigPath");function a_e(e){switch(e){case"env":return"Env var";case"api":return"API access";default:return"Config"}}r(a_e,"deliveryModeLabel");function Ilt(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(Ilt,"deliveryModeDescription");function i_e(e){return e?e.startsWith("access.")?e.slice(7):e.startsWith("env.")?e.slice(4):e:""}r(i_e,"aliasFromConfigPath");function Alt(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(Alt,"consumerTypeLabel");var Tlt={numeric:!0,sensitivity:"base"};function R1(e){return e.kind==="company"?e.secret.name:e.definition.name}r(R1,"getSecretPathRowName");function Kk(e){return e.split("/").filter(s=>s.length>0)}r(Kk,"splitSecretPath");function oF(e){return Kk(e).join("/")}r(oF,"normalizeSecretPath");function Vne(e,s){return s.every((n,a)=>e[a]===n)}r(Vne,"startsWithSegments");function Hne(e,s){return e.localeCompare(s,void 0,Tlt)}r(Hne,"compareNames");function Rlt(e,s){const n=Kk(s),a=e.map(c=>({row:c,name:R1(c),segments:Kk(R1(c))})),i=new Set,o=[];for(const c of a){if(!Vne(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(!Vne(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)=>Hne(c.name,d.name)),o.sort((c,d)=>Hne(R1(c),R1(d))),{folders:l,secrets:o}}r(Rlt,"buildSecretPathListing");function Elt(e){const s=Kk(e);return s.map((n,a)=>({name:n,path:s.slice(0,a+1).join("/")}))}r(Elt,"buildSecretPathBreadcrumbs");function Plt(e){return e.trim()?e.includes("/")?"Folder name cannot contain slashes.":null:"Folder name is required."}r(Plt,"validateSecretFolderSegment");function kI({name:e,basePath:s="",className:n,leafClassName:a}){const i=Kk(e),o=Kk(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:V("min-w-0 truncate",n),children:[u?(0,t.jsxs)("span",{className:"text-muted-foreground",children:[u,"/"]}):null,(0,t.jsx)("span",{className:V("font-medium text-foreground",a),children:d})]})}r(kI,"SecretPathName");function Mlt(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(Mlt,"fingerprintLabel");function o_e({fingerprint:e,length:s,className:n}){const{pushToast:a}=Qr(),i=Mlt(e,s);if(!e)return(0,t.jsxs)("span",{className:V("inline-flex items-center gap-1 font-mono",n),children:[(0,t.jsx)(l6,{className:"size-3 shrink-0"}),i]});const o=`sha256:${e}`;return(0,t.jsxs)("button",{type:"button",onClick:r(()=>{Ia(o).then(()=>a({title:"Fingerprint copied",tone:"success"})).catch(()=>a({title:"Couldn’t copy fingerprint",tone:"error"}))},"onClick"),title:`Copy full digest — ${o}`,className:V("inline-flex items-center gap-1 font-mono hover:text-foreground",n),children:[(0,t.jsx)(l6,{className:"size-3 shrink-0"}),i,(0,t.jsx)(wr,{className:"size-3 shrink-0 opacity-60"})]})}r(o_e,"FingerprintChip");function wH({justification:e,className:s}){return(0,t.jsxs)("div",{className:V("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(wH,"ProposalJustification");function SI({agent:e,className:s}){return(0,t.jsxs)("span",{className:V("inline-flex min-w-0 items-center gap-1",s),children:[(0,t.jsx)(or,{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(SI,"AgentRefChip");function NH({configPath:e}){const s=r_e(e),n=s==="env",a=s==="api";return(0,t.jsxs)(ot,{variant:"outline",className:V("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)(gwe,{className:"size-3"}):a?(0,t.jsx)(z4,{className:"size-3"}):null,a_e(s)]})}r(NH,"DeliveryBadge$1");function kH({className:e}){return(0,t.jsxs)(ot,{variant:"outline",className:V("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)(jc,{className:"size-3"})," Proposed"]})}r(kH,"ProposedBadge");function ID(e){return i_e(e.configPath)}r(ID,"bindingEnvKey");function SH(e){return e.secretProposalId?{name:e.secretProposalName??"proposed secret",pending:!0}:{name:e.secretName??"secret",pending:!1}}r(SH,"bindingSecretLabel");function Qne(e){return e instanceof mn?e.message||`Request failed: ${e.status}`:e instanceof Error?e.message:"Something went wrong. Try again."}r(Qne,"readableError");function l_e(e,s=[]){const n=Nt(),{pushToast:a}=Qr(),[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=ye({mutationFn:r(w=>{const{proposal:k}=w;if(k.kind==="secret"){const S=w.folder.trim()?`${w.folder.trim().replace(/\/+$/,"")}/${w.leaf.trim()}`:w.leaf.trim();return Rr.approveProposal(e,k.id,{overrides:{name:S,description:w.description.trim()||null,providerConfigId:w.providerConfigId||null}})}return Rr.approveProposal(e,k.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"} · ${ID(w)||"binding"}`,tone:"success"}),o(null),p(null),f()},"onSuccess"),onError:r(w=>p(Qne(w)),"onError")}),b=ye({mutationFn:r(({proposal:w,reason:k})=>Rr.rejectProposal(e,w.id,{reason:k.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(Qne(w)),"onError")}),v=(0,m.useCallback)(w=>{p(null);const k=(w.proposedName??"").split("/"),S=k.pop()??"";o({proposal:w,folder:k.join("/"),leaf:S,description:w.proposedDescription??"",providerConfigId:s.find(C=>C.provider==="local_encrypted"&&C.isDefault)?.id??"",cascade:!!w.secretProposalId})},[s]),j=(0,m.useCallback)(w=>{p(null),u(""),c(w)},[]),N=(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)(Dlt,{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)($lt,{proposal:l,reason:d,error:h,pending:b.isPending,onReasonChange:u,onCancel:r(()=>{c(null),u(""),p(null)},"onCancel"),onConfirm:r(()=>l&&b.mutate({proposal:l,reason:d}),"onConfirm")})]});return{requestApprove:v,requestReject:j,isBusy:x.isPending||b.isPending,dialogs:N}}r(l_e,"useProposalReview");function Dlt({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)(zs,{open:!!e,onOpenChange:r(p=>!p&&o(),"onOpenChange"),children:(0,t.jsx)(Ws,{className:"sm:max-w-lg",children:e?(0,t.jsxs)(t.Fragment,{children:[(0,t.jsxs)(on,{children:[(0,t.jsx)(Vs,{children:c?"Approve & create secret":"Approve binding"}),(0,t.jsx)(hn,{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)(SI,{agent:e.proposal.proposedBy,className:"font-medium text-foreground"})]}),(0,t.jsx)(wH,{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)(ut,{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)(ut,{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)(kI,{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)(ut,{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)(Llt,{draft:e,onChange:i}),s?(0,t.jsx)("p",{className:"text-xs text-destructive",role:"alert",children:s}):null,(0,t.jsxs)(dr,{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(Dlt,"ApproveDialog");function Llt({draft:e,onChange:s}){const{proposal:n}=e,a=SH(n),i=ID(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)(SI,{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)(NH,{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)(kH,{}):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)(Za,{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(Llt,"BindingApproveBody");function $lt({proposal:e,reason:s,error:n,pending:a,onReasonChange:i,onCancel:o,onConfirm:l}){const c=s.trim().length>0;return(0,t.jsx)(zs,{open:!!e,onOpenChange:r(d=>!d&&o(),"onOpenChange"),children:(0,t.jsx)(Ws,{className:"sm:max-w-md",children:e?(0,t.jsxs)(t.Fragment,{children:[(0,t.jsxs)(on,{children:[(0,t.jsx)(Vs,{children:"Reject proposal"}),(0,t.jsxs)(hn,{children:["The reason is sent back to"," ",(0,t.jsx)(SI,{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)(Qn,{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)(dr,{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($lt,"RejectDialog");function c_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)(Wc,{children:(0,t.jsxs)(Bn,{children:[(0,t.jsx)(Fn,{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(c_e,"ProposalActions");function d_e(e){return typeof e!="object"||e===null||Array.isArray(e)?null:e}r(d_e,"asRecord$16");function u_e(e){const s=d_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(u_e,"readSecretRef");function Olt(e){const s=d_e(e?.env);if(!s)return[];const n=[];for(const[a,i]of Object.entries(s)){const o=u_e(i);o&&n.push({name:a,...o})}return n}r(Olt,"parseEnvSecretRefs");function Flt(e){if(!e)return[];const s=[];for(const[n,a]of Object.entries(e)){if(!n.startsWith("access."))continue;const i=u_e(a);i&&s.push({name:n.slice(r2.length),...i})}return s}r(Flt,"parseAccessGrants");function Blt(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(Blt,"summarizeAgentBindings");var Gne=0;function m_e(){return Gne+=1,`access-row-${Gne}`}r(m_e,"nextAccessRowId");function lF(e){return e.map(s=>({id:m_e(),alias:s.name,secretId:s.secretId,version:s.version}))}r(lF,"entriesToRows");function Yne(e){const s={};for(const n of e){const a=n.alias.trim();!a||!CU.test(a)||!n.secretId||(s[a]={type:"secret_ref",secretId:n.secretId,version:n.version})}return s}r(Yne,"rowsToAccessMap");function Jne(e){return JSON.stringify(Object.keys(e).sort().map(s=>{const n=e[s];return[s,n.secretId,n.version??"latest"]}))}r(Jne,"normalizeAccessMapKey");function Xne({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)(gwe,{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)(z4,{className:"size-3"})," API access"]})}r(Xne,"DeliveryBadge");function zlt({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)(()=>Olt(e),[e]),h=(0,m.useMemo)(()=>Flt(e),[e]),p=(0,m.useMemo)(()=>Blt(u,h),[u,h]),f=(0,m.useMemo)(()=>Yne(lF(h)),[h]),x=(0,m.useMemo)(()=>Jne(f),[f]),[b,v]=(0,m.useState)(()=>lF(h)),[j,N]=(0,m.useState)(null),w=(0,m.useRef)(new Map),k=(0,m.useRef)(x),S=(0,m.useRef)(x);(0,m.useEffect)(()=>{x!==S.current&&(S.current=x,x!==k.current&&v(lF(h)))},[x,h]);const C=r(O=>s.find(P=>P.id===O)?.name??`${O.slice(0,8)}…`,"secretName");function _(O){v(O);const P=Yne(O);k.current=Jne(P),n(P)}r(_,"emit");function R(O,P){_(b.map(U=>U.id===O?{...U,...P}:U))}r(R,"patchRow");function A(O){_(b.filter(P=>P.id!==O))}r(A,"removeRow");function T(){v(O=>[...O,{id:m_e(),alias:"",secretId:"",version:"latest"}])}r(T,"addRow");const E=(0,m.useMemo)(()=>{const O=new Map;for(const P of b){const U=P.alias.trim();U&&O.set(U,(O.get(U)??0)+1)}return O},[b]),L=p.length>0;return(0,t.jsxs)("div",{className:"space-y-3",children:[L?(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)(Xne,{mode:"env"}):null,O.apiAliases.length>0?(0,t.jsx)(Xne,{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(P=>`${_lt}${P}`),...O.apiAliases.map(P=>`${r2}${P}`)].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 P=SH(O),U=ID(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)(NH,{configPath:O.configPath}),(0,t.jsx)("code",{className:"font-mono",children:U||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:P.name}),P.pending?(0,t.jsx)(kH,{}):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)(c_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)"}),b.length>0?(0,t.jsx)("div",{className:"space-y-2",children:b.map(O=>{const P=O.alias.trim(),U=!!P&&!CU.test(P),M=!!P&&(E.get(P)??0)>1,B=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)(ut,{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&&!CU.test(z)){const K=x_(z);K&&K!==z&&R(O.id,{alias:K})}},"onBlur"),placeholder:"ALIAS","aria-label":"Access alias",disabled:i,className:V("h-9 font-mono text-sm",(U||M)&&"border-destructive text-destructive")})}),(0,t.jsxs)("div",{className:"flex min-w-0 items-start gap-1.5",children:[(0,t.jsxs)(ur,{open:j?.rowId===O.id,onOpenChange:r(q=>{!q&&j?.rowId===O.id&&N(null)},"onOpenChange"),children:[(0,t.jsx)(Hq,{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)(jH,{secretId:O.secretId,secrets:s,onSelect:r(q=>R(O.id,{secretId:q,version:"latest",alias:!O.alias.trim()&&q?x_(C(q)):O.alias}),"onSelect"),onCreateNew:a?q=>{window.setTimeout(()=>{N({rowId:O.id,name:LP(q)||q.trim()})},0)}:void 0,disabled:i,triggerClassName:"h-9 min-h-9"})})}),(0,t.jsx)(rr,{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:j?.rowId===O.id&&a?(0,t.jsx)(t_e,{initialName:j.name,initialValue:"",existingSecretNames:s.map(q=>q.name),onCancel:r(()=>N(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()||x_(K.name)}),N(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||!B,"aria-label":"Version",children:[(0,t.jsx)("option",{value:"latest",children:"latest"}),B?Array.from({length:Math.max(0,B.latestVersion)},(q,z)=>{const K=B.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(()=>A(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)(da,{className:"size-3.5"})})]}),U?(0,t.jsx)("p",{className:"pl-0.5 text-(length:--text-micro) text-destructive",children:"Invalid alias — use letters, digits and _"}):M?(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:[Ilt("api")," The agent reads them by alias through ",(0,t.jsx)("code",{children:"GET /agents/me/secrets"}),"."]})]})}r(zlt,"AgentSecretAccessEditor");function qlt(e){if(typeof e!="string")return null;const s=e.trim();return s.length>0?s:null}r(qlt,"asNonEmptyString$3");function Ult(e){return qlt(e)!==null}r(Ult,"hasLegacyWorkingDirectory");function Klt(e){return e.isCreate?!1:Ult(e.adapterConfig?.cwd)}r(Klt,"shouldShowLegacyWorkingDirectoryField");var h_e=new Set;function Wlt(e){return h_e.has(e)}r(Wlt,"isAdapterTypeHidden");function Vlt(e){h_e=new Set(e)}r(Vlt,"setDisabledAdapterTypes");function Hlt(e){return!Um(e).hideFromVisualSelection}r(Hlt,"isVisualAdapterChoice");function p_e(e,s=vH()){const n=e??ax;return s.map(a=>({value:a.type,label:n(a.type),comingSoon:!!Um(a.type).comingSoon,hidden:Wlt(a.type),experimental:!!Um(a.type).experimental}))}r(p_e,"listAdapterOptions");function f_e(e={}){const s=e.enabled??!0,{data:n}=te({queryKey:D.adapters.all,queryFn:r(()=>Sh.list(),"queryFn"),enabled:s,staleTime:3e5});return n&&Hot(n.filter(a=>a.source==="external").map(a=>({type:a.type,label:a.label,disabled:a.disabled,overrideDisabled:a.overridePaused}))),(0,m.useEffect)(()=>{n&&Vlt(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(f_e,"useDisabledAdaptersSync");function Qlt(e={}){const s=e.enabled??!0,{data:n}=te({queryKey:D.adapters.all,queryFn:r(()=>Sh.list(),"queryFn"),enabled:s,staleTime:3e5});return n!==void 0}r(Qlt,"useAdapterRegistryLoaded");function $P(e){return Object.fromEntries(Object.entries(e).filter(([,s])=>s!==void 0))}r($P,"omitUndefinedEntries");function $T(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=$P(s.adapterType!==void 0?{...Object.fromEntries(SBe.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=$P({...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($T,"buildAgentUpdatePatch");var Glt="kubernetes";function Ylt(e){return e.driver!=="sandbox"?!1:e.config?.provider===Glt}r(Ylt,"isKubernetesSandboxEnvironment");function CH(e,s){return e!=="kubernetes"?{forced:!1,kubernetesEnvironment:null}:{forced:!0,kubernetesEnvironment:s.find(n=>Ylt(n))??null}}r(CH,"resolveForcedKubernetesEnvironment");var cF={identity:{},adapterConfig:{},heartbeat:{},debug:{},runtime:{}},zC={};function Jlt(e){return e==="claude_local"||e==="codex_local"||e==="paperclip_runner"||e==="opencode_local"}r(Jlt,"supportsAdapterModelRefresh");function Xlt(e,s){return o1e(e,s).model}r(Xlt,"resolvePaperclipRunnerTransitionModel");function Zne(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(Zne,"isOverlayDirty");function _U(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)=>_U(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&&_U(o,a[i]))}return!1}r(_U,"overlayValuesEqual");function Zlt(e,s){const n=r((a,i)=>Object.fromEntries(Object.entries(a).filter(([o,l])=>!(o in i)||!_U(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(Zlt,"subtractPersistedOverlay");var hh="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 ect(e){return e.split(",").map(s=>s.trim()).filter(Boolean)}r(ect,"parseCommaArgs");function tct(e){return Array.isArray(e)?e.filter(s=>typeof s=="string").join(", "):typeof e=="string"?e:""}r(tct,"formatArgList");var sct=[{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"}],nct=[{id:"",label:"Auto"},{id:"plan",label:"Plan"},{id:"ask",label:"Ask"}],rct=[{id:"",label:"Auto"},{id:"low",label:"Low"},{id:"medium",label:"Medium"},{id:"high",label:"High"}],act=[{id:"",label:"Auto"},{id:"low",label:"Low"},{id:"high",label:"High"},{id:"max",label:"Max"}],ict=2,ere=10,oct=1,x_e=300;function b3(e,s,n){return Math.max(s,Math.min(n,Math.floor(e)))}r(b3,"clampInteger");function lct(e){return b3(e,0,x_e)*1e3}r(lct,"clampDelayMsFromSeconds");function cct({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(cct,"ConfigSections");function g_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}=ps(),x=Nt(),b=(0,m.useRef)(null),v=f_e(),{data:j=[]}=te({queryKey:f?D.secrets.list(f):["secrets","none"],queryFn:r(()=>Rr.list(f),"queryFn"),enabled:!!f}),{data:N=[]}=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:k=[]}=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)(()=>k.filter(pt=>pt.kind==="binding"&&pt.target?.id===w),[k,w]),C=l_e(f,[]),{data:_}=te({queryKey:D.instance.experimentalSettings,queryFn:r(()=>vr.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]),A=_?.enableEnvironments===!0,T=_?.enableManagedSandboxOnly===!0,E=_===void 0||T,{data:L}=te({queryKey:D.instance.generalSettings,queryFn:r(()=>vr.getGeneral(),"queryFn"),retry:!1}),{data:O}=te({queryKey:D.instance.settings,queryFn:r(()=>vr.get(),"queryFn"),retry:!1}),{data:P=[]}=te({queryKey:f?D.environments.list(f):["environments","none"],queryFn:r(()=>$i.list(f),"queryFn"),enabled:!!f&&(A||L?.executionMode==="kubernetes")}),{forced:U,kubernetesEnvironment:M}=(0,m.useMemo)(()=>CH(L?.executionMode,P),[L?.executionMode,P]),B=ye({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=ye({mutationFn:r(async({file:pt,namespace:Is})=>{if(!f)throw new Error("Select an organization to upload images");return qb.uploadImage(f,pt,Is)},"mutationFn")}),[z,K]=(0,m.useState)(cF),[W,Q]=(0,m.useState)(!1),[re,J]=(0,m.useState)(0),ie=(0,m.useRef)(null),X=(0,m.useRef)(null),ne=(0,m.useRef)(!1);(0,m.useEffect)(()=>{if(!a){if(ie.current!==null&&e.agent!==ie.current&&!ne.current){const pt=X.current;X.current=null,K(Is=>pt?Zlt(Is,pt):{...cF})}ie.current=e.agent}},[a,a?void 0:e.agent]);const oe=!a&&(Zne(z)||W);function G(pt,Is,cn){const _n=z[pt];return Is in _n?_n[Is]:cn}r(G,"eff");function Z(pt,Is,cn){K(_n=>({..._n,[pt]:{..._n[pt],[Is]:cn}}))}r(Z,"mark");function Y(){return b.current?.flushPendingDraft()??null}r(Y,"flushEnvironmentDraft");const ae=(0,m.useCallback)(pt=>{a||K(Is=>{const cn={...e.agent.adapterConfig??{},...Is.adapterConfig},_n={...Is.adapterConfig};for(const[fn,Sr]of Object.entries(pt))_n[`${r2}${fn}`]=Sr;for(const fn of Object.keys(cn))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({...cF}),Q(!1),J(pt=>pt+1)},[]),ce=(0,m.useCallback)(async()=>{if(a)return;const pt=Y(),Is=pt?{...z,adapterConfig:{...z.adapterConfig,env:pt}}:z;Zne(Is)&&await e.onSave($T(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??{},we=a?{}:e.agent.runtimeConfig??{},Se=a?{}:we.heartbeat??{},Te=a?{}:we.debug??{},le=a?e.values.adapterType:z.adapterType??e.agent.adapterType,fe=jj(),de=fe(le),Ee=le==="paperclip_runner"&&(a?e.values.adapterSchemaValues?.provider:G("adapterConfig","provider",pe.provider))==="openai_dot",Me=!Ee&&(de.supportsInstructionsBundle||de.supportsSkills||de.supportsLocalAgentJwt),ve=Me&&!E&&Klt({isCreate:a,adapterConfig:pe}),Ie=(0,m.useMemo)(()=>KS(le),[le]),Ze=(0,m.useMemo)(()=>new Set(KUe(le)),[le]),ue=a?e.values:null,Be=a?pt=>e.onChange(pt):null;a&&ue.claudeStoredSessionId;const ht=r(()=>{f&&x.invalidateQueries({queryKey:D.secrets.userDefinitions(f)})},"invalidateUserSecretDefinitions"),jt=r(pt=>{if(!a||!Be)return;const Is=ue.envBindings??{};Be({envBindings:{...Is,...kN()},claudeStoredSessionId:pt}),ht()},"handleClaudeLoginStored"),Je=r(async()=>{if(a)return;const pt={...Y()??G("adapterConfig","env",pe.env??zC),...kN()},Is={...z,adapterConfig:{...z.adapterConfig,env:pt}};K(Is),await e.onSave({...$T(e.agent,Is),applyStoredClaudeLogin:!0}),ht()},"handleClaudeLoginStoredEdit"),Fe=r(async pt=>{if(a||!pt.companyIdentityDiffers)return;const Is={...Y()??G("adapterConfig","env",pe.env??zC),CODEX_HOME:{type:"secret_ref",secretId:pt.secretId,version:"latest"}},cn={...z,adapterConfig:{...z.adapterConfig,env:Is}};K(cn),X.current=cn,ne.current=!0;try{await e.onSave($T(e.agent,cn))}catch(_n){throw X.current=null,_n}finally{ne.current=!1}ht()},"handleCodexAccountBindingEdit"),it=r(()=>{if(!a||!Be)return;const pt=ue.envBindings??{};Be({envBindings:{...pt,...kN()},claudeApplyStoredLogin:!0}),ht()},"handleApplyStoredClaudeLogin"),At=r(async()=>{if(a)return;const pt={...Y()??G("adapterConfig","env",pe.env??zC),...kN()},Is={...z,adapterConfig:{...z.adapterConfig,env:pt}};K(Is),await e.onSave({...$T(e.agent,Is),applyStoredClaudeLogin:!0}),ht()},"handleApplyStoredClaudeLoginEdit"),$t=a?ue.defaultEnvironmentId??"":G("identity","defaultEnvironmentId",e.agent.defaultEnvironmentId??""),zt=(0,m.useMemo)(()=>$t?(P.find(pt=>pt.id===$t)??null)?.driver==="local"?"":$t:"",[P,$t]),at=(0,m.useMemo)(()=>P.find(pt=>pt.id===zt)??null,[zt,P]),De=(0,m.useMemo)(()=>{const pt=O?.defaultEnvironmentId??null;return pt?(P.find(Is=>Is.id===pt)??null)?.driver==="local"?"":pt:""},[P,O?.defaultEnvironmentId]),Pe=(0,m.useMemo)(()=>P.find(pt=>pt.id===De)??null,[P,De]),dt=(0,m.useMemo)(()=>{try{return Bk({agentDefaultEnvironmentId:$t||null,instanceDefaultEnvironmentId:O?.defaultEnvironmentId??null,localDefaultEnvironmentId:qk(P),managedSandboxOnly:_?.enableManagedSandboxOnly===!0,managedSandboxEnvironmentId:zk(P),visibleEnvironmentIds:P.map(pt=>pt.id)})}catch{return null}},[$t,O?.defaultEnvironmentId,P,_?.enableManagedSandboxOnly]),rt=(0,m.useMemo)(()=>P.find(pt=>pt.id===dt)??null,[P,dt]),{data:ft}=te({queryKey:f?D.environments.capabilities(f):["environment-capabilities","none"],queryFn:r(()=>$i.capabilities(f),"queryFn"),enabled:!!f&&de.login!=null});(0,m.useEffect)(()=>{!a||!Be||!U||!M||zt!==M.id&&Be({defaultEnvironmentId:M.id})},[a,Be,U,M,zt]);const kt=(0,m.useMemo)(()=>P.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"}),[P,Ze]),Ke=(0,m.useMemo)(()=>!at||kt.some(pt=>pt.id===at.id)?kt:[...kt,at],[at,kt]),$e=A&&(U||zt.length>0||kt.length>=1),ze=Pe?Uk(Pe):T?"Paperclip Computer":"Local",et=le==="paperclip_runner"?String(a?e.values.adapterSchemaValues?.provider??"codex":G("adapterConfig","provider",pe.provider==="acpx"&&pe.acpxAgent==="codex"?"codex":pe.provider??"codex")):void 0,ge=le==="opencode_local"&&Uq.safeParse(z.runtime.runtimeConfig?.aiConnection??we.aiConnection).data?.provider==="openrouter"?"openrouter":et,st=t1e(f,a?void 0:Uq.safeParse(z.runtime.runtimeConfig?.aiConnection??we.aiConnection).data,BZ(le,et,G("adapterConfig","acpxAgent",pe.acpxAgent))),Mt=f?D.agents.adapterModels(f,le,zt||null,ge):["agents","none","adapter-models",le],{data:Ss,error:lt,isLoading:Ls}=te({queryKey:Mt,queryFn:r(()=>Ct.adapterModels(f,le,{environmentId:zt||null,provider:ge}),"queryFn"),enabled:!!f&&!st}),[Ue,xe]=(0,m.useState)(null),[Ye,gt]=(0,m.useState)(!1),Ht=st?.models??Ss??n??[],mt=st?st.error:lt,Bt="command",{data:Le,refetch:he}=te({queryKey:f?D.agents.detectModel(f,le):["agents","none","detect-model",le],queryFn:r(()=>{if(!f)throw new Error("Select an organization to detect the model");return Ct.detectModel(f,le)},"queryFn"),enabled:!!(f&&Me&&le!=="opencode_local"&&le!=="paperclip_runner")}),Qt=Le?.model??null;Le?.candidates;const{data:Lt=[]}=te({queryKey:f?D.agents.list(f):["agents","none","list"],queryFn:r(()=>Ct.list(f),"queryFn"),enabled:!!(!a&&f)}),ss={companyId:f??void 0,agentId:a?void 0:e.agent.id,mode:s,isCreate:a,adapterType:le,values:a?e.values:null,set:a?pt=>e.onChange(pt):null,config:pe,eff:G,mark:Z,models:Ht,hideInstructionsFile:h||E||Ee,managedSandboxOnly:E||Ee,openAiDotEnabled:_?.enableOpenAiDot===!0},[Cs,ln]=(0,m.useState)(!1),[mr,pn]=(0,m.useState)(!1),Ot=mH(le),Es=r(pt=>(0,t.jsxs)(t.Fragment,{children:[le==="claude_local"&&(0,t.jsx)(Crt,{...ss,section:pt}),(0,t.jsx)(Ie.ConfigFields,{...ss,section:pt,hideModel:Me})]}),"renderAdapterFields"),[Re,wt]=(0,m.useState)(!1),[Oe,_t]=(0,m.useState)(!1);function Ut(pt){if(a){const cn=Ie.buildAdapterConfig(ue);return pt&&Object.assign(cn,pt),$P(cn)}const Is={...pe,...z.adapterConfig};return pt&&Object.assign(Is,pt),$P(Is)}r(Ut,"buildAdapterConfigForTest");const It=ye({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 cn=O,_n=P,fn=_?.enableManagedSandboxOnly===!0;if(!$t)try{const[an,Tr,Jn]=await Promise.all([x.ensureQueryData({queryKey:D.instance.settings,queryFn:r(()=>vr.get(),"queryFn")}),x.ensureQueryData({queryKey:D.environments.list(f),queryFn:r(()=>$i.list(f),"queryFn")}),x.ensureQueryData({queryKey:D.instance.experimentalSettings,queryFn:r(()=>vr.getExperimental(),"queryFn")})]);cn=an,_n=Tr,fn=Jn?.enableManagedSandboxOnly===!0}catch{throw new Error("Could not load environment settings to determine which environment to test in. Retry the test.")}const Sr=Bk({agentDefaultEnvironmentId:$t||null,instanceDefaultEnvironmentId:cn?.defaultEnvironmentId??null,localDefaultEnvironmentId:qk(_n),managedSandboxOnly:fn,managedSandboxEnvironmentId:zk(_n),visibleEnvironmentIds:_n.map(an=>an.id)}),aa=Ut(Is),Da=a?void 0:e.agent.id,As=a?void 0:DZ.safeParse(z.runtime.runtimeConfig?.aiConnection??e.agent.runtimeConfig.aiConnection).data;if(e.compactTestFeedback){const an=le==="paperclip_runner"?aa.provider==="codex"?"codex_local":aa.provider==="acpx"&&aa.acpxAgent==="grok"?"grok_local":aa.provider==="acpx"&&aa.acpxAgent==="claude"?"claude_local":le:le;return s1e({companyId:f,adapterType:le,providerAdapter:an,adapterConfig:aa,agentId:Da,aiConnection:As,environmentId:Sr})}return Ct.testEnvironment(f,le,{adapterConfig:aa,agentId:Da,aiConnection:As,environmentId:Sr})},"mutationFn")}),[is,bs]=(0,m.useState)(!1),[Os,qs]=(0,m.useState)(null),Rn="Test",Ns=!a&&!!e.isSaving,Yn=is||Ns||!f,Xt=(0,m.useRef)(It.reset);Xt.current=It.reset;const Hs=(0,m.useRef)(()=>{});Hs.current=()=>{if(!a||!Be)return;const pt=ue.envBindings??{},Is=ue.claudeStoredSessionId!=null||ue.claudeApplyStoredLogin===!0,cn=Une in pt;if(!Is&&!cn)return;const _n={...pt};delete _n[Une],Be({envBindings:_n,claudeStoredSessionId:null,claudeApplyStoredLogin:!1})},(0,m.useEffect)(()=>{Xt.current(),qs(null),Hs.current()},[le,dt]);const rn=de.login!=null,Et=It.data,rs=Et!=null&&fe(Et.adapterType).login!=null,Zs=Et&&rs?Et.checks.find(pt=>pt.code==="adapter_auth_missing")??null:null,gs=typeof rt?.config?.provider=="string"?rt.config.provider:null,Js=gs!=null&&ft?.sandboxProviders?.[gs]?.supportsLoginPty===!0,kn=de.login!=null,hr=(a||!(z.runtime.runtimeConfig?.aiConnection??we.aiConnection))&&rn&&rt?.driver==="sandbox"&&!!dt&&!!f&&!!Zs&&(!kn||Js),qn=(0,m.useCallback)(async()=>{if(!f)throw new Error("Select an organization to test adapter environment");bs(!0),qs(null),It.reset();try{return await It.mutateAsync()}catch(pt){throw qs(pt instanceof Error?pt.message:"Environment test failed"),pt}finally{bs(!1)}},[f,It]),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:is}),()=>{e.onTestActionStateChange?.({disabled:!0,pending:!1})}},[l,e.onTestActionStateChange,Yn,is]),(0,m.useEffect)(()=>{if(e.onTestFeedbackChange)return e.onTestFeedbackChange({errorMessage:Os??(It.error instanceof Error?It.error.message:It.error?"Environment test failed":null),result:It.data??null,login:hr&&f&&dt?{companyId:f,adapterType:le,environmentId:dt}:null}),()=>{e.onTestFeedbackChange?.({errorMessage:null,result:null,login:null})}},[e.onTestFeedbackChange,Os,It.data,It.error,hr,f,le,dt]);const pr=a?ue.model??"":G("adapterConfig","model",String(pe.model??"")),Cn=typeof pr=="string"?pr:"";async function kr(){if(f){gt(!0),xe(null);try{const pt=await Ct.adapterModels(f,le,{refresh:!0,environmentId:zt||null,provider:ge});x.setQueryData(Mt,pt)}catch(pt){xe(pt instanceof Error?pt.message:"Failed to refresh adapter models.")}finally{gt(!1)}}}r(kr,"handleRefreshModels");const Or=le==="codex_local"?"modelReasoningEffort":le==="cursor"?"mode":le==="opencode_local"?"variant":le==="grok_local"?"reasoningEffort":le==="pi_local"||le==="omp_local"?"thinking":"effort",Ur=le==="codex_local"?oH(Cn,"Auto").map(pt=>({id:pt.value,label:pt.label})):le==="cursor"?nct:le==="opencode_local"?sct:le==="kimi_local"?act:le==="pi_local"?[{id:"",label:"Auto"},...["off","minimal","low","medium","high","xhigh"].map(pt=>({id:pt,label:pt}))]:le==="claude_local"||le==="grok_local"?[{id:"",label:"Auto"},...TP(le,Cn).map(pt=>({id:pt,label:pt==="xhigh"?"X-High":pt[0].toUpperCase()+pt.slice(1)}))]:rct,xa=le==="omp_local",ar=a?xa?String(ue.adapterSchemaValues?.thinking??""):ue.thinkingEffort:le==="codex_local"?G("adapterConfig","modelReasoningEffort",String(pe.modelReasoningEffort??pe.reasoningEffort??"")):le==="cursor"?G("adapterConfig","mode",String(pe.mode??"")):le==="opencode_local"?G("adapterConfig","variant",String(pe.variant??"")):G("adapterConfig",Or,String(pe[Or]??"")),cr=le!=="gemini_local"&&le!=="cursor_cloud"&&le!=="paperclip_runner"&&!xa,bt=r(pt=>{if(a){Be(xa?{adapterSchemaValues:{...ue.adapterSchemaValues,thinking:pt??void 0}}:{thinkingEffort:pt??""});return}Z("adapterConfig",Or,pt||void 0)},"setThinkingEffort"),He=le==="codex_local"?a?!!ue.search:G("adapterConfig","search",!!pe.search):!1,Zt=(0,m.useMemo)(()=>{if(a)return{heartbeat:{enabled:ue.heartbeatEnabled,intervalSec:ue.intervalSec}};const pt={...we.heartbeat&&typeof we.heartbeat=="object"?we.heartbeat:{},...z.heartbeat};return{...we,heartbeat:pt}},[a,z.heartbeat,we,ue]),ms=IZ(Zt.heartbeat),_s=IZ(ms.maxTurnContinuation),ts=YFe(_s.enabled,!0),ws=b3(wZ(_s.maxAttempts,ict),0,ere),Nn=b3(wZ(_s.delayMs,oct*1e3)/1e3,0,x_e);function vn(pt){Z("heartbeat","maxTurnContinuation",{..._s,...pt})}r(vn,"updateMaxTurnContinuation");const Un=(0,t.jsx)(Jy,{ref:b,onDirtyChange:Q,hideDraftActions:!a&&e.hideInlineSave,value:a?ue.envBindings??zC:G("adapterConfig","env",pe.env??zC),secrets:j,userSecretDefinitions:N,onCreateSecret:r(async(pt,Is)=>await B.mutateAsync({name:pt,value:Is}),"onCreateSecret"),onChange:r(pt=>a?Be({envBindings:pt??{},envVars:""}):Z("adapterConfig","env",pt),"onChange")},re);return!a&&e.content==="secrets"?(0,t.jsxs)("div",{className:V("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:V(!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:V(i?"rounded-lg border border-border p-4":"px-4 pb-3"),children:Un})]}),(0,t.jsxs)("div",{"data-config-section":"secrets",className:V(!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:V(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)(zlt,{config:{...pe,...z.adapterConfig},secrets:j,onChange:ae,onCreateSecret:r((pt,Is)=>B.mutateAsync({name:pt,value:Is}),"onCreateSecret"),proposals:S,onApproveProposal:C.requestApprove,onRejectProposal:C.requestReject}),C.dialogs]})]})]}):(0,t.jsxs)(cct,{order:e.sectionOrder,className:V("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:V(!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:V(i?"border border-border rounded-lg p-4 space-y-3":"px-4 pb-3 space-y-3"),children:[(0,t.jsx)(ks,{label:"Name",hint:wi.name,children:(0,t.jsx)(Wa,{value:G("identity","name",e.agent.name),onCommit:r(pt=>Z("identity","name",pt),"onCommit"),immediate:!0,className:hh,placeholder:"Agent name"})}),(0,t.jsx)(ks,{label:"Title",hint:wi.title,children:(0,t.jsx)(Wa,{value:G("identity","title",e.agent.title??""),onCommit:r(pt=>Z("identity","title",pt||null),"onCommit"),immediate:!0,className:hh,placeholder:"e.g. VP of Engineering"})}),(0,t.jsx)(ks,{label:"Reports to",hint:wi.reportsTo,children:(0,t.jsx)(Zot,{agents:Lt,value:G("identity","reportsTo",e.agent.reportsTo??null),onChange:r(pt=>Z("identity","reportsTo",pt),"onChange"),excludeAgentIds:[e.agent.id],chooseLabel:"Choose manager…"})}),Me&&!e.hidePromptTemplate&&(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)(ks,{label:"Prompt Template",hint:wi.promptTemplate,children:(0,t.jsx)(Qc,{value:G("adapterConfig","promptTemplate",String(pe.promptTemplate??"")),onChange:r(pt=>Z("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."})]})]})]}),U?(0,t.jsxs)("div",{"data-config-section":"environment",className:V(!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:V(i?"border border-border rounded-lg p-4 space-y-3":"px-4 pb-3 space-y-3"),children:(0,t.jsx)(ks,{label:"Default environment",hint:"This instance runs all agents in the Kubernetes sandbox. Local execution is disabled.",children:M?(0,t.jsxs)("div",{className:V(hh,"flex items-center text-muted-foreground"),children:[M.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."})})})]}):$e?(0,t.jsxs)("div",{"data-config-section":"environment",className:V(!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:V(i?"border border-border rounded-lg p-4 space-y-3":"px-4 pb-3 space-y-3"),children:(0,t.jsx)(ks,{label:"Environment override",children:(0,t.jsx)("div",{className:"space-y-2",children:(0,t.jsxs)("select",{className:hh,value:zt,onChange:r(pt=>{const Is=pt.target.value;if(a){Be({defaultEnvironmentId:Is});return}Z("identity","defaultEnvironmentId",Is||null)},"onChange"),children:[(0,t.jsxs)("option",{value:"",children:["Default: ",ze]}),Ke.map(pt=>(0,t.jsx)("option",{value:pt.id,children:Uk(pt)},pt.id))]})})})})]}):null,(0,t.jsxs)("div",{"data-config-section":"adapter",className:V(!i&&(a?"border-t border-border":"border-b border-border")),children:[(0,t.jsxs)("div",{className:V(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:is?`${Rn}...`:Rn})]}),(0,t.jsxs)("div",{className:V(i?"border border-border rounded-lg p-4 space-y-3":"px-4 pb-3 space-y-3"),children:[o&&(0,t.jsx)(ks,{label:"Adapter type",hint:wi.adapterType,children:(0,t.jsx)(v_e,{value:Ee?"openai_dot":le,disabledTypes:R,openAiDotEnabled:_?.enableOpenAiDot===!0,onChange:r(pt=>{const Is=pt==="openai_dot",cn=Is?"paperclip_runner":pt;if(a){const{adapterType:_n,...fn}=ib,Sr={...fn,adapterType:cn};cn==="codex_local"?Sr.dangerouslyBypassSandbox=!0:cn==="gemini_local"?Sr.model="auto":cn==="kimi_local"?Sr.model="kimi-code/kimi-for-coding":cn==="cursor"?Sr.model="auto":cn==="opencode_local"?Sr.model="openai/gpt-5.2-codex":cn==="paperclip_runner"&&(Sr.model=Fk),Is&&(Sr.model="",Sr.adapterSchemaValues={provider:"openai_dot"}),Be(Sr)}else K(_n=>({..._n,adapterType:cn,adapterConfig:{model:cn==="gemini_local"?"auto":cn==="kimi_local"?"kimi-code/kimi-for-coding":cn==="opencode_local"?"openai/gpt-5.2-codex":cn==="cursor"?"auto":Is?"":cn==="paperclip_runner"?Xlt(le,pe.model):"",effort:"",modelReasoningEffort:"",variant:"",mode:"",...cn==="codex_local"?{dangerouslyBypassApprovalsAndSandbox:!0}:Is?{provider:"openai_dot",lifecycleMode:"per_turn",allowUnmeteredProvider:!1,dotAttachmentAccess:!1,dotWorkspaceAccess:!1}:cn==="paperclip_runner"?{...o1e(le,G("adapterConfig","model",pe.model))}:{}}}))},"onChange")})}),!Ee&&!a&&f&&(0,t.jsx)(lU,{companyId:f,agentId:e.agent.id,agentName:e.agent.name,adapterType:BZ(le,G("adapterConfig","provider",pe.provider),G("adapterConfig","acpxAgent",pe.acpxAgent)),routerAdapterType:le,value:DZ.safeParse(z.runtime.runtimeConfig?.aiConnection??we.aiConnection).data,model:String(G("adapterConfig","model",pe.model)??""),environmentId:zt||void 0,legacy:!0,onChange:r(pt=>Z("runtime","runtimeConfig",{...we,aiConnection:pt}),"onChange")}),d&&!e.compactTestFeedback&&(Os||It.error)&&(0,t.jsx)("div",{className:"rounded-md border border-destructive/30 bg-destructive/10 px-3 py-2 text-xs text-destructive",children:Os??(It.error instanceof Error?It.error.message:"Environment test failed")}),d&&!e.compactTestFeedback&&It.data&&(0,t.jsx)(xct,{result:It.data}),d&&hr&&(0,t.jsx)(_H,{companyId:f,adapterType:le,environmentId:dt,onStored:a?jt:Je,onApplyStored:a?it:At,onAccountBinding:a?void 0:Fe},`${le}:${dt}`),ve&&(0,t.jsx)(ks,{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)(sl,{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?Be({cwd:pt}):Z("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)(Qd,{})]})}),Es("adapter"),Me&&(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)(IH,{models:Ht,loadingModels:st?.isLoading??Ls,value:Cn,effort:xa?{value:ar||null,onChange:bt}:void 0,onChange:r(pt=>{xa&&!vD(ar,pt,Ht.map(_n=>YN(_n,!1)))&&bt(null);const Is=TP(le,pt),cn=["codex_local","claude_local","grok_local"].includes(le)&&!!ar&&!Is.includes(String(ar));if(a){Be({model:pt,...cn?{thinkingEffort:""}:{}});return}Z("adapterConfig","model",st?.resolveModel(pt)||pt||void 0),cn&&(Z("adapterConfig",Or,void 0),Z("adapterConfig","reasoningEffort",void 0))},"onChange"),open:Re,onOpenChange:wt,defaultLabel:le==="claude_local"?"Default (claude-opus-5)":void 0,allowDefault:le!=="opencode_local"&&le!=="pi_local"&&le!=="paperclip_runner",required:le==="opencode_local"||le==="pi_local",groupByProvider:!st&&(le==="opencode_local"||le==="pi_local"),preserveOrder:!!st||dH(le),creatable:!0,detectedModel:st?void 0:Qt,detectedModelCandidates:[],onDetectModel:st||le==="opencode_local"||le==="paperclip_runner"?void 0:async()=>(await he()).data?.model??null,onRefreshModels:st?st.refreshModels:Jlt(le)?kr:void 0,refreshingModels:st?.refreshing??Ye,detectModelLabel:"Detect model",emptyDetectHint:"No model detected. Select or enter one manually."}),(Ue||mt)&&(0,t.jsx)("p",{className:"text-xs text-destructive",children:Ue??(mt instanceof Error?mt.message:"Failed to load adapter models.")}),le==="opencode_local"&&!st&&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,"."]}),cr&&(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)(gct,{value:ar,options:Ur,onChange:r(pt=>a?Be({thinkingEffort:pt}):Z("adapterConfig",Or,pt||void 0),"onChange"),open:Oe,onOpenChange:_t}),le==="codex_local"&&He&&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:V(!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:V(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)(ks,{label:"Bootstrap prompt (legacy)",hint:wi.bootstrapPrompt,children:(0,t.jsx)(Qc,{value:G("adapterConfig","bootstrapPromptTemplate",String(pe.bootstrapPromptTemplate??"")),onChange:r(pt=>Z("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."})]}),Es("configuration"),(Me||le==="process"||Ot?.fields.some(pt=>mU(pt.key)==="advanced"))&&(0,t.jsx)(u3,{title:"Advanced",open:mr,onToggle:r(()=>pn(!mr),"onToggle"),children:(0,t.jsxs)("div",{className:"space-y-3",children:[Me&&(0,t.jsxs)(t.Fragment,{children:[" ",!E&&(0,t.jsx)(ks,{label:"Command",hint:wi.localCommand,children:(0,t.jsx)(Wa,{value:a?ue.command:G("adapterConfig",Bt,String(pe.command??"")),onCommit:r(pt=>a?Be({command:pt}):Z("adapterConfig",Bt,pt||null),"onCommit"),immediate:!0,className:hh,placeholder:{claude_local:"claude",codex_local:"codex",gemini_local:"gemini",kimi_local:"kimi",pi_local:"pi",cursor:"agent",opencode_local:"opencode"}[le]??le.replace(/_local$/,"")})}),(0,t.jsx)(ks,{label:"Extra args (comma-separated)",hint:wi.extraArgs,children:(0,t.jsx)(Wa,{value:a?ue.extraArgs:G("adapterConfig","extraArgs",tct(pe.extraArgs)),onCommit:r(pt=>a?Be({extraArgs:pt}):Z("adapterConfig","extraArgs",pt?.trim()?ect(pt):null),"onCommit"),className:hh,placeholder:"e.g. --verbose, --foo=bar"})})]}),Es("advanced")]})})]})]}),e.environmentVariablesPlacement!=="secrets"&&(Me||Ot?.fields.some(pt=>mU(pt.key)==="environment"))&&(0,t.jsxs)("div",{"data-config-section":"environment-variables",className:V(!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:V(i?"border border-border rounded-lg p-4 space-y-3":"px-4 pb-3 space-y-3"),children:Me?Un:Es("environment")})]}),a&&u?(0,t.jsxs)("div",{"data-config-section":"run-policy",className:V(!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)(w1,{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)(w1,{className:"h-3 w-3"})," Run Policy"]}),(0,t.jsxs)("div",{className:V(i?"border border-border rounded-lg p-4 space-y-3":"px-4 pb-3 space-y-3"),children:[(0,t.jsx)(fne,{label:"Heartbeat on interval",hint:wi.heartbeatInterval,checked:ue.heartbeatEnabled,onCheckedChange:r(pt=>Be({heartbeatEnabled:pt}),"onCheckedChange"),number:ue.intervalSec,onNumberChange:r(pt=>Be({intervalSec:pt}),"onNumberChange"),numberLabel:"sec",numberPrefix:"Run heartbeat every",numberHint:wi.intervalSec,showNumber:ue.heartbeatEnabled}),(0,t.jsx)(u3,{title:"Advanced Run Policy",open:Cs,onToggle:r(()=>ln(!Cs),"onToggle"),children:(0,t.jsx)("div",{className:"space-y-3",children:Es("runPolicy")})})]})]}):a?null:(0,t.jsxs)("div",{"data-config-section":"run-policy",className:V(!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)(w1,{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)(w1,{className:"h-3 w-3"})," Run Policy"]}),(0,t.jsxs)("div",{className:V(i?"border border-border rounded-lg overflow-hidden":""),children:[(0,t.jsx)("div",{className:V(i?"p-4 space-y-3":"px-4 pb-3 space-y-3"),children:(0,t.jsx)(fne,{label:"Heartbeat on interval",hint:wi.heartbeatInterval,checked:G("heartbeat","enabled",Se.enabled===!0),onCheckedChange:r(pt=>Z("heartbeat","enabled",pt),"onCheckedChange"),number:G("heartbeat","intervalSec",Number(Se.intervalSec??300)),onNumberChange:r(pt=>Z("heartbeat","intervalSec",pt),"onNumberChange"),numberLabel:"sec",numberPrefix:"Run heartbeat every",numberHint:wi.intervalSec,showNumber:G("heartbeat","enabled",Se.enabled===!0)})}),(0,t.jsx)(u3,{title:"Advanced Run Policy",bordered:i,open:Cs,onToggle:r(()=>ln(!Cs),"onToggle"),children:(0,t.jsxs)("div",{className:"space-y-3",children:[Es("runPolicy"),Me&&(0,t.jsx)(t.Fragment,{children:!a&&(0,t.jsxs)(t.Fragment,{children:[!Ot?.fields.some(pt=>pt.key==="timeoutSec")&&(0,t.jsx)(ks,{label:"Timeout (sec)",hint:wi.timeoutSec,children:(0,t.jsx)(zc,{value:G("adapterConfig","timeoutSec",Number(pe.timeoutSec??0)),onCommit:r(pt=>Z("adapterConfig","timeoutSec",pt),"onCommit"),immediate:!0,className:hh})}),!Ot?.fields.some(pt=>pt.key==="graceSec")&&(0,t.jsx)(ks,{label:"Interrupt grace period (sec)",hint:wi.graceSec,children:(0,t.jsx)(zc,{value:G("adapterConfig","graceSec",Number(pe.graceSec??15)),onCommit:r(pt=>Z("adapterConfig","graceSec",pt),"onCommit"),immediate:!0,className:hh})})]})}),(0,t.jsx)(vl,{label:"Wake on demand",hint:wi.wakeOnDemand,checked:G("heartbeat","wakeOnDemand",Se.wakeOnDemand!==!1),onChange:r(pt=>Z("heartbeat","wakeOnDemand",pt),"onChange")}),(0,t.jsx)(ks,{label:"Cooldown (sec)",hint:wi.cooldownSec,children:(0,t.jsx)(zc,{value:G("heartbeat","cooldownSec",Number(Se.cooldownSec??10)),onCommit:r(pt=>Z("heartbeat","cooldownSec",pt),"onCommit"),immediate:!0,className:hh})}),(0,t.jsx)(ks,{label:"Max concurrent runs",hint:wi.maxConcurrentRuns,children:(0,t.jsx)(zc,{value:G("heartbeat","maxConcurrentRuns",Number(Se.maxConcurrentRuns??20)),onCommit:r(pt=>Z("heartbeat","maxConcurrentRuns",pt),"onCommit"),immediate:!0,className:hh})}),(0,t.jsxs)("div",{className:"rounded-md border border-border/70 px-3 py-2",children:[(0,t.jsx)(vl,{label:"Continue after max-turn stop",hint:wi.maxTurnContinuationEnabled,checked:ts,onChange:r(pt=>vn({enabled:pt}),"onChange")}),ts?(0,t.jsxs)("div",{className:"mt-3 grid gap-3 sm:grid-cols-2",children:[(0,t.jsx)(ks,{label:"Continuation attempts",hint:wi.maxTurnContinuationMaxAttempts,children:(0,t.jsx)(zc,{value:ws,onCommit:r(pt=>vn({maxAttempts:b3(pt,0,ere)}),"onCommit"),immediate:!0,className:hh})}),(0,t.jsx)(ks,{label:"Continuation delay (sec)",hint:wi.maxTurnContinuationDelaySec,children:(0,t.jsx)(zc,{value:Nn,onCommit:r(pt=>vn({delayMs:lct(pt)}),"onCommit"),immediate:!0,className:hh})})]}):null]})]})})]})]}),!a&&p?(0,t.jsxs)("div",{className:V(!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)(by,{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)(by,{className:"h-3 w-3"})," Debugging"]}),(0,t.jsxs)("div",{className:V("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)(vl,{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",Te.providerTrace)==="raw",onChange:r(pt=>Z("debug","providerTrace",pt?"raw":void 0),"onChange")}),G("debug","providerTrace",Te.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)(by,{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)(p1e,{variant:Ee?"prerequisites":"connection",state:is?"running":Os||It.error?"fail":Et?.status??"idle",result:Et??null,error:Os??(It.error instanceof Error?It.error.message:null),onTest:Cr,disabled:Yn})]})}r(g_e,"AgentConfigForm");var IU=new Set(["authenticated","failed","timed_out","cancelled"]),AU=2e3;function TU({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 Ia(e),a(!0)}catch{a(!1)}i.current&&clearTimeout(i.current),i.current=setTimeout(()=>a(!1),1500)},"onClick"),children:n?(0,t.jsx)(us,{className:"size-3"}):(0,t.jsx)(wr,{className:"size-3"})})}r(TU,"AdapterLoginCopyButton");function dct({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)(us,{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)(Rs,{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(dct,"AdapterLoginTerminalState");var uct={claude_local:"Anthropic",codex_local:"OpenAI"};function b_e(e){const s=uct[e];return s?`Sign in to ${s}`:"Sign in to the environment"}r(b_e,"adapterLoginTitle");function _H(e){return jj()(e.adapterType).login?.panelMode==="submitted_browser_code"?(0,t.jsx)(fct,{...e}):(0,t.jsx)(mct,{...e})}r(_H,"AdapterLoginPanel");var dF=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 mct({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,b]=(0,m.useState)(null),[v,j]=(0,m.useState)("idle"),N=(0,m.useRef)(!1),w=ye({mutationFn:r(()=>Ct.startAdapterAuthLogin(e,s,{environmentId:n,aiConnection:c}),"mutationFn"),onSuccess:r(ne=>{N.current=!1,f(null),b(null),j("idle"),h(ne.sessionId)},"onSuccess"),onError:r(ne=>{f(ne instanceof Error?ne.message:"Could not start the login.")},"onError")}),k=(0,m.useCallback)(()=>{N.current=!1,h(null),b(null),f(null)},[]),S=ye({mutationFn:r(()=>Ct.cancelAdapterAuthLogin(e,s,u),"mutationFn"),onSuccess:k,onError:r(ne=>{f(ne instanceof Error?ne.message:"Could not cancel the login.")},"onError")}),C=te({queryKey:["adapter-login-active-session",e,s],queryFn:r(async()=>{try{const ne=await Ct.getActiveAdapterAuthLoginSession(e,s);if(!ne)return null;if(c&&ne.environmentId!==n||!!ne.aiConnection!=!!c||c&&(ne.aiConnection?.provider!==c.provider||ne.aiConnection?.method!==c.method||ne.aiConnection?.connectionId!==c.connectionId||ne.aiConnection?.ownership!==c.ownership||ne.aiConnection?.allAgents!==c.allAgents||JSON.stringify(ne.aiConnection?.agentIds)!==JSON.stringify(c.agentIds)))throw new dF(ne.sessionId);return ne}catch(ne){if(ne instanceof mn&&ne.status===404)return null;throw ne}},"queryFn"),retry:!1,gcTime:0,staleTime:0}),[_,R]=(0,m.useState)(!1),A=te({queryKey:["adapter-login-status",e,s,u],queryFn:r(()=>Ct.getAdapterAuthLoginStatus(e,s,u),"queryFn"),enabled:!!u&&!_,retry:r((ne,oe)=>oe instanceof mn&&oe.status===404?!1:ne<3,"retry"),refetchInterval:r(ne=>{const oe=ne.state.data?.status;return oe&&IU.has(oe)?!1:AU},"refetchInterval")});(0,m.useEffect)(()=>{const ne=A.data?.prompt??null;ne&&b(ne)},[A.data]);const T=A.data??w.data??null,E=T?.status??null,L=x,O=E?IU.has(E):!1,P=!!u&&!O,U=w.isPending||P||v==="saving",M=(0,m.useRef)(!1);(0,m.useEffect)(()=>{if(M.current||!C.isFetched)return;M.current=!0;const ne=C.data;ne&&(N.current=!0,f(null),b(ne.prompt??null),h(ne.sessionId))},[C.isFetched,C.data]),(0,m.useEffect)(()=>{const ne=A.error;if(!(ne instanceof mn&&ne.status===404)||!N.current||_)return;R(!0);const oe=u;(async()=>(oe&&await Ct.cancelAdapterAuthLogin(e,s,oe).catch(()=>{}),R(!1),k()))()},[A.error,_,u,e,s,k]);const B=(0,m.useRef)(!1),q=ye({mutationFn:r(async()=>{const ne=C.error;ne instanceof dF&&await Ct.cancelAdapterAuthLogin(e,s,ne.sessionId)},"mutationFn"),onSuccess:r(async()=>{B.current=!1,M.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||B.current)){if(C.isError){B.current=!0,f(C.error instanceof Error?C.error.message:"Could not check for an active login.");return}C.isSuccess&&(B.current=!0,!C.data&&z.current())}},[a,C.isSuccess,C.isError,C.data,C.error]);const K=(0,m.useRef)(!1),W=(0,m.useRef)(i);W.current=i,(0,m.useEffect)(()=>{E!=="authenticated"||K.current||(K.current=!0,W.current?.(u??void 0))},[E]);const Q=(0,m.useRef)(null),re=(0,m.useRef)(o);re.current=o;const J=A.data?.codexAccountBinding??null,ie=(0,m.useCallback)(async ne=>{const oe=re.current;if(oe){j("saving");try{await oe(ne),j("bound")}catch{j("failed")}}},[]);(0,m.useEffect)(()=>{E!=="authenticated"||!u||Q.current!==u&&(!J||!J.companyIdentityDiffers||!re.current||(Q.current=u,ie(J)))},[E,u,J,ie]);const X=(0,m.useRef)(d);if(X.current=d,(0,m.useEffect)(()=>{X.current?.(L?.url??null)},[L]),l==="onboarding"){const ne=O&&E&&E!=="authenticated";return(0,t.jsx)(gH,{loading:!L&&!p&&!ne,providerName:xH(s),authorizationUrl:L?.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 dF&&(0,t.jsx)($,{type:"button",variant:"outline",disabled:q.isPending,onClick:r(()=>q.mutate(),"onClick"),children:"Cancel previous sign-in and retry"})]}):ne?(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)(S1e,{code:L?.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:b_e(s)}),(0,t.jsxs)("div",{className:"flex items-center gap-1.5",children:[P&&(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:U,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:[P&&!L&&(0,t.jsxs)("div",{className:"flex items-center gap-2 text-(length:--text-micro) text-muted-foreground",children:[(0,t.jsx)(tt,{className:"size-3 animate-spin shrink-0"}),(0,t.jsx)("span",{children:"Preparing..."})]}),P&&L&&(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:L.code})]}),(0,t.jsx)(TU,{value:L.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:L.url})]}),(0,t.jsxs)("div",{className:"flex items-center",children:[(0,t.jsx)(TU,{value:L.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:L.url,target:"_blank",rel:"noreferrer noopener",children:(0,t.jsx)($n,{className:"size-3"})})})]})]})]}),O&&E&&(0,t.jsx)(dct,{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)(tt,{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)(us,{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)(Rs,{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(()=>{J&&ie(J)},"onClick"),children:"Retry"})]})]})]})}r(mct,"DisplayedCodeLoginPanel");var hct=new Set(["failed","timed_out","cancelled"]),tre="The login did not finish. Start the login again.",pct=9e5,sre="The login timed out. Start the login again.";function fct({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),[b,v]=(0,m.useState)(null),[j,N]=(0,m.useState)(null),[w,k]=(0,m.useState)(!1),[S,C]=(0,m.useState)(""),[_,R]=(0,m.useState)(null),[A,T]=(0,m.useState)(!1),[E,L]=(0,m.useState)(!1),[O,P]=(0,m.useState)(!1),[U,M]=(0,m.useState)(!1),B=(0,m.useRef)(!1),[q,z]=(0,m.useState)(!1),K=(0,m.useRef)(!1),W=r(()=>{v(null),N(null),k(!1),C(""),R(null),T(!1),L(!1),M(!1),P(!1),B.current=!1},"resetLocalState"),Q=te({queryKey:["claude-oauth-token-status",e],queryFn:r(async()=>{try{return await Ct.getClaudeOAuthTokenStatus(e)}catch(at){if(at instanceof mn&&at.status===404)return null;throw at}},"queryFn"),retry:r((at,De)=>De instanceof mn&&De.status===404?!1:at<2,"retry")}).data??null,re=ye({mutationFn:r(()=>Ct.startClaudeSetupTokenLogin(e,{environmentId:n,aiConnection:h,...Q&&!h?{overwrite:{expectedSecretId:Q.secretId,expectedLatestVersion:Q.latestVersion}}:{}}),"mutationFn"),onSuccess:r(at=>{K.current=!1,W(),x(at.sessionId)},"onSuccess"),onError:r(at=>{v(at instanceof Error?at.message:"Could not start the login.")},"onError")}),J=r(()=>{K.current=!1,x(null),W()},"clearActiveSession"),ie=ye({mutationFn:r(()=>Ct.cancelClaudeSetupTokenLogin(e,f),"mutationFn"),onSuccess:r(()=>{J()},"onSuccess"),onError:r(at=>{if(at instanceof mn&&at.status===404){J();return}v(at instanceof Error?at.message:"Could not cancel the login.")},"onError")}),X=(0,m.useCallback)(at=>{Ct.cancelClaudeSetupTokenLogin(e,at).catch(()=>{})},[e]),ne=te({queryKey:["claude-setup-token-active-session",e],queryFn:r(async()=>{try{const at=await Ct.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 mn&&at.status===404)return null;throw at}},"queryFn"),retry:!1,gcTime:0,staleTime:0}),[oe,G]=(0,m.useState)(!1),Z=!!f&&!E&&!U&&!oe,Y=te({queryKey:["claude-setup-token-status",e,f],queryFn:r(()=>Ct.getClaudeSetupTokenLoginStatus(e,f),"queryFn"),enabled:Z,retry:r((at,De)=>De instanceof mn&&De.status===404?!1:at<3,"retry"),refetchInterval:r(at=>{if(E||U)return!1;const De=at.state.data?.status;return De&&IU.has(De)?!1:AU},"refetchInterval")});(0,m.useEffect)(()=>{const at=Y.error;if(at instanceof mn&&at.status===404){if(K.current){if(oe)return;G(!0);const De=f;(async()=>(De&&await Ct.cancelClaudeSetupTokenLogin(e,De).catch(()=>{}),G(!1),J()))();return}M(!0)}},[Y.error,oe,f,e]);const ae=(0,m.useRef)(!1);(0,m.useEffect)(()=>{if(ae.current||!ne.isFetched)return;ae.current=!0;const at=ne.data;at&&(K.current=!0,W(),x(at.sessionId),at.prompt&&(N(at.prompt.authorizationUrl),at.prompt.transportAdvisory&&k(!0)))},[ne.isFetched,ne.data]);const se=te({queryKey:["claude-setup-token-prompt",e,f],enabled:Z&&!j,queryFn:r(async()=>{try{return await Ct.getClaudeSetupTokenLoginPrompt(e,f)}catch(at){if(at instanceof mn&&at.status===404)return null;throw at}},"queryFn"),refetchInterval:r(at=>E||at.state.data?.authorizationUrl?!1:AU,"refetchInterval")});(0,m.useEffect)(()=>{const at=se.data?.authorizationUrl??null;at&&N(at),se.data?.transportAdvisory&&k(!0)},[se.data]);const ce=ye({mutationFn:r(at=>Ct.submitClaudeSetupTokenBrowserCode(e,f,at),"mutationFn"),onError:r(at=>{v(at instanceof Error?at.message:"Could not submit the browser code.")},"onError")}),pe=ye({mutationFn:r(()=>Ct.completeClaudeSetupTokenLogin(e,f),"mutationFn"),onSuccess:r(at=>{R(at.storedSessionId),a?.(at.storedSessionId)},"onSuccess"),onError:r(()=>{T(!0)},"onError")}),we=Y.data?.status??re.data?.status??null,Se=Y.data?.expiresAt??re.data?.expiresAt??null,Te=(0,m.useRef)(pe.mutate);Te.current=pe.mutate,(0,m.useEffect)(()=>{we==="authenticated"&&!B.current&&(B.current=!0,Te.current())},[we]);const le=_!==null,fe=A||U||!!(we&&hct.has(we)),de=we==="authenticated"&&!le&&!A,Ee=!!f&&!le&&!fe&&!E,Me=re.isPending||Ee;(0,m.useEffect)(()=>{if(!Ee)return;const at=Se!==null?new Date(Se).getTime():NaN,De=Number.isFinite(at)?Math.max(0,at-Date.now()):pct,Pe=setTimeout(()=>{f&&X(f),L(!0)},De);return()=>clearTimeout(Pe)},[Ee,Se,f,X]);const ve=S.trim(),Ie=Ee&&!!j&&!de&&WFe(ve)&&!ce.isPending&&!O,Ze=(0,m.useRef)(c);Ze.current=c;const ue=(0,m.useRef)(d);ue.current=d;const Be=r(()=>{Ie&&(v(null),ce.mutate(ve),P(!0),Ze.current?.(),u!=="onboarding"&&C(""))},"handleSubmit"),ht=(0,m.useRef)(!1),jt=(0,m.useRef)(re.mutate);jt.current=re.mutate,(0,m.useEffect)(()=>{if(!(!o||ht.current)){if(ne.isError){ht.current=!0,v(ne.error instanceof Error?ne.error.message:"Could not check for an active login.");return}ne.isSuccess&&(ht.current=!0,!ne.data&&jt.current())}},[o,ne.isSuccess,ne.isError,ne.data,ne.error]);const Je=(0,m.useRef)(Be);Je.current=Be;const Fe=u==="onboarding",it=(0,m.useRef)(!1);(0,m.useEffect)(()=>{!Fe||!it.current||(it.current=!1,Ie&&Je.current())},[Fe,Ie,S]);const At=(0,m.useRef)(!1),$t=(0,m.useRef)(l);$t.current=l,(0,m.useEffect)(()=>{!le||At.current||(At.current=!0,$t.current?.(f??void 0))},[le]),(0,m.useEffect)(()=>{O&&(!b&&!fe&&!E||(P(!1),ue.current?.()))},[O,b,fe,E]);const zt=(0,m.useRef)(p);if(zt.current=p,(0,m.useEffect)(()=>{zt.current?.(j)},[j]),u==="onboarding"){const at=fe||E;return(0,t.jsxs)(gH,{loading:!j&&!b&&!at,providerName:xH(s),authorizationUrl:j??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)(Rs,{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."]}),b?(0,t.jsx)("p",{role:"alert",className:"pl-2 text-xs text-destructive",children:b}):at?(0,t.jsx)("p",{role:"alert",className:"pl-2 text-xs text-destructive",children:E&&!fe?sre:tre}):(0,t.jsx)(s2,{value:S,onChange:C,onSubmit:Be,onPaste:r(()=>{it.current=!0},"onPaste"),masked:!0,disabled:ce.isPending||de||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:b_e(s)}),(0,t.jsxs)("div",{className:"flex items-center gap-1.5",children:[Ee&&(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&&Q&&!Ee&&!le&&!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:Me,onClick:r(()=>re.mutate(),"onClick"),children:Q&&!Ee&&!le?"Sign in to replace":"Sign in"})]})]}),Q&&!Ee&&!le&&!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)(us,{className:"size-3 shrink-0"}),(0,t.jsx)("span",{children:"The saved Claude login is bound to this agent now."})]}),b&&(0,t.jsx)("div",{role:"alert",className:"text-(length:--text-micro) text-destructive",children:b}),(0,t.jsxs)("div",{role:"status","aria-live":"polite",className:"space-y-2 empty:hidden",children:[Ee&&!j&&!de&&(0,t.jsxs)("div",{className:"flex items-center gap-2 text-(length:--text-micro) text-muted-foreground",children:[(0,t.jsx)(tt,{className:"size-3 animate-spin shrink-0"}),(0,t.jsx)("span",{children:"Preparing..."})]}),Ee&&j&&!de&&(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)(Rs,{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:j})]}),(0,t.jsxs)("div",{className:"flex items-center",children:[(0,t.jsx)(TU,{value:j,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:j,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(),Be())},"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:!Ie,onClick:Be,children:"Submit"})]})]})]}),de&&(0,t.jsxs)("div",{className:"flex items-center gap-2 text-(length:--text-micro) text-muted-foreground",children:[(0,t.jsx)(tt,{className:"size-3 animate-spin shrink-0"}),(0,t.jsx)("span",{children:"Completing the login…"})]}),le&&(0,t.jsxs)("div",{className:"flex items-center gap-2 text-(length:--text-micro) text-foreground",children:[(0,t.jsx)(us,{className:"size-3 shrink-0"}),(0,t.jsx)("span",{children:"Authenticated. The environment has credentials now."})]}),fe&&(0,t.jsxs)("div",{className:"flex items-start gap-2 text-(length:--text-micro) text-destructive",children:[(0,t.jsx)(Rs,{className:"size-3 shrink-0"}),(0,t.jsx)("span",{children:tre})]}),E&&!fe&&!le&&(0,t.jsxs)("div",{className:"flex items-start gap-2 text-(length:--text-micro) text-destructive",children:[(0,t.jsx)(Rs,{className:"size-3 shrink-0"}),(0,t.jsx)("span",{children:sre})]})]})]})}r(fct,"SubmittedBrowserCodeLoginPanel");function xct({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(xct,"AdapterEnvironmentResult$1");function v_e({value:e,onChange:s,disabledTypes:n,openAiDotEnabled:a=!1}){const[i,o]=(0,m.useState)(!1),l=Um(e),c=(0,m.useMemo)(()=>[...p_e(d=>vI[d]??ax(d)),...a?[{value:"openai_dot",label:"OpenAI Dot",experimental:!0,comingSoon:!1}]:[]].filter(d=>!n.has(d.value)),[n,a]);return(0,t.jsxs)(ur,{open:i,onOpenChange:o,children:[(0,t.jsx)(Nr,{asChild:!0,children:(0,t.jsxs)("button",{type:"button","data-size":"default",className:V(_6e,"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)(Ap,{type:e,className:"size-4"})}),(0,t.jsx)("span",{className:"truncate",children:vI[e]??ax(e)}),l.experimental&&(0,t.jsx)(nre,{})]}),(0,t.jsx)(nn,{className:"size-4 opacity-50"})]})}),(0,t.jsx)(rr,{className:"w-(--radix-popover-trigger-width) p-1",align:"start",children:c.map(d=>(0,t.jsxs)("button",{type:"button",disabled:d.comingSoon,className:V("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)(Ap,{type:d.value,className:"size-4"})}),(0,t.jsx)("span",{children:d.label}),d.experimental&&(0,t.jsx)(nre,{})]}),d.comingSoon&&(0,t.jsx)("span",{className:"text-(length:--text-nano) text-muted-foreground",children:"Coming soon"})]},d.value))})]})}r(v_e,"AdapterTypeDropdown");function nre(){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(nre,"ExperimentalBadge$1");function IH({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:b,loadingModels:v,detectModelLabel:j,emptyDetectHint:N,defaultLabel:w,presentation:k="searchable",effort:S}){const[C,_]=(0,m.useState)(""),[R,A]=(0,m.useState)(!1),[T,E]=(0,m.useState)(!1),L=C.trim(),O=!!(u&&L&&!e.some(K=>K.id.toLowerCase()===L.toLowerCase())),P=(0,m.useMemo)(()=>{const K=new Set;h&&K.add(h);for(const W of p??[])W&&K.add(W);return K},[h,p]),U=(0,m.useMemo)(()=>e.filter(K=>{if(P.has(K.id))return!1;const W=EP(K.id);return sD({...YN(K,c),...W&&!K.provider?{group:W}:{}},C)}),[e,C,P,c]),M=(0,m.useMemo)(()=>new Map(e.map(K=>[K.id,YN(K,c)])),[e,c]),B=s?Hd(s,[...M.values()]):null,q=(0,m.useMemo)(()=>{if(!c&&U.some(W=>W.provider)){const W=new Map;for(const Q of U){const re=Q.provider??"other";W.set(re,[...W.get(re)??[],Q])}return Array.from(W.entries()).map(([Q,re])=>({provider:Q,entries:re}))}if(!c)return[{provider:null,entries:d?U:[...U].sort((W,Q)=>W.id.localeCompare(Q.id))}];const K=new Map;for(const W of U){const Q=EP(W.id)??"other",re=K.get(Q)??[];re.push(W),K.set(Q,re)}return Array.from(K.entries()).sort(([W],[Q])=>W.localeCompare(Q)).map(([W,Q])=>({provider:W,entries:[...Q].sort((re,J)=>re.id.localeCompare(J.id))}))},[U,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"),k==="native"){const K="__paperclip_custom_model__",W=[...new Set([s,...P])].filter(Q=>!!Q&&(!e.some(re=>re.id===Q)||P.has(Q)));return(0,t.jsxs)(ks,{label:"Model",hint:wi.model,children:[(0,t.jsxs)(nbe,{"aria-label":"Model","aria-busy":v||b,value:R?K:s,required:l&&!R,onChange:r(Q=>{const re=Q.target.value;A(re===K),re!==K&&n(re)},"onChange"),children:[(0,t.jsx)("option",{value:"",disabled:!o,children:o?w??"Default":v?"Loading models…":l?"Select model (required)":"Select model"}),W.map(Q=>(0,t.jsx)("option",{value:Q,children:e.find(re=>re.id===Q)?.label??Q},Q)),q.map(({provider:Q,entries:re})=>c?(0,t.jsx)("optgroup",{label:Q??void 0,children:re.map(J=>(0,t.jsx)("option",{value:J.id,children:J.label},J.id))},Q):re.map(J=>(0,t.jsx)("option",{value:J.id,children:J.label},J.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)(ut,{"aria-label":"Model ID",value:s,onChange:r(Q=>n(Q.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:b,onClick:r(()=>{x()},"onClick"),children:b?"Refreshing…":"Refresh models"})]})}return(0,t.jsx)(ks,{label:"Model",hint:wi.model,children:(0,t.jsxs)(ur,{open:a,onOpenChange:r(K=>{i(K),K||_("")},"onOpenChange"),children:[(0,t.jsx)(Nr,{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:[B?(0,t.jsx)(nx,{display:B,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&&Qy(S.value,s,[...M.values()])?(0,t.jsxs)("span",{className:V("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)(nn,{className:"size-4 shrink-0 text-muted-foreground"})]})}),(0,t.jsxs)(rr,{className:"w-(--radix-popover-trigger-width) p-1",align:"start",children:[S&&s&&Qy(S.value,s,[...M.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)(yD,{levels:Rg(s,[...M.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)(na,{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?US:"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?j?.replace(/^Detect\b/,"Re-detect")??"Re-detect from config":j??"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:b,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"})]}),b?"Refreshing...":"Refresh models"]}),s&&(!e.some(K=>K.id===s)||P.has(s))&&(0,t.jsxs)("button",{type:"button",className:V("flex items-center w-full px-2 py-1.5 text-sm rounded bg-accent/50"),onClick:r(()=>{i(!1)},"onClick"),children:[B?(0,t.jsx)(nx,{display:B,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:V("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 W=e.find(Q=>Q.id===K);return(0,t.jsxs)("button",{type:"button",className:V("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:W?.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:V("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(L),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:L})]}),q.map(K=>(0,t.jsxs)("div",{className:"mb-1 last:mb-0",children:[K.provider&&(0,t.jsx)(rD,{provider:K.provider,testId:`model-dropdown-group-${K.provider}`}),K.entries.map(W=>(0,t.jsxs)("button",{type:"button",className:V("flex items-center gap-2 w-full px-2 py-1.5 text-left text-sm rounded hover:bg-accent/50",W.id===s&&"bg-accent"),onClick:r(()=>{n(W.id),S&&Rg(W.id,[...M.values()]).length>0||i(!1)},"onClick"),children:[(0,t.jsx)(nD,{option:M.get(W.id)??YN(W,c)}),W.id===s?(0,t.jsx)(us,{className:"size-4 shrink-0","aria-hidden":"true"}):null]},W.id))]},K.provider??"")),U.length===0&&!O&&P.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?N??"No model detected yet. Enter a provider/model manually.":"No models found."})})]})]})]})})}r(IH,"ModelDropdown");function gct({value:e,options:s,onChange:n,open:a,onOpenChange:i}){const o=s.find(l=>l.id===e)??s[0];return(0,t.jsx)(ks,{label:"Thinking effort",hint:wi.thinkingEffort,children:(0,t.jsxs)(ur,{open:a,onOpenChange:i,children:[(0,t.jsx)(Nr,{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:V(!e&&"text-muted-foreground"),children:o?.label??"Auto"}),(0,t.jsx)(nn,{className:"h-3 w-3 text-muted-foreground"})]})}),(0,t.jsx)(rr,{className:"w-(--radix-popover-trigger-width) p-1",align:"start",children:s.map(l=>(0,t.jsxs)("button",{className:V("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(gct,"ThinkingEffortDropdown");function y_e(e){const s=`paperclip.agent-appearance.${e}`;function n(){try{const l=Lge.safeParse(JSON.parse(sessionStorage.getItem(s)??"null"));if(l.success)return l.data}catch{}const o=WE();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(y_e,"useAgentAppearanceDraft");var qC=null,OT=new Set,UC={subscribe(e){return OT.add(e),()=>{OT.delete(e)}},getSnapshot(){return qC},acquire(e){if(qC)return!1;qC=e;for(const s of OT)s();return!0},release(e){if(qC===e){qC=null;for(const s of OT)s()}}};function Wk({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)(()=>Db(s??e?.appearance,e?.id),[s,e?.appearance,e?.id]),b=(0,m.useRef)(null),v=(0,m.useRef)(null),j=(0,m.useRef)(null),N=(0,m.useRef)(Symbol("agent-character")),w=(0,m.useSyncExternalStore)(UC.subscribe,UC.getSnapshot,()=>null),[k,S]=(0,m.useState)(!1),[C,_]=(0,m.useState)(!0),[R,A]=(0,m.useState)(!1),[T,E]=(0,m.useState)(!1),L=!x.customAvatarAssetId&&k&&!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)"),P=r(()=>_(O.matches),"change");P(),O.addEventListener("change",P);const U=new IntersectionObserver(M=>S(M[0]?.isIntersecting??!1));return b.current&&U.observe(b.current),()=>{U.disconnect(),O.removeEventListener("change",P)}},[]),(0,m.useEffect)(()=>{L&&w===null&&UC.acquire(N.current),L||UC.release(N.current)},[L,w]),(0,m.useEffect)(()=>()=>UC.release(N.current),[]),(0,m.useEffect)(()=>{if(!L||w!==N.current)return;let O=!1;return E(!1),Promise.all([Id(()=>import("./runtime-IAg0vdY9.js"),__vite__mapDeps([0,1])),Id(()=>import("./definition-CAnOpilv.js"),__vite__mapDeps([2,3,1]))]).then(([P,U])=>{O||!v.current||(j.current=P.createCharacter(v.current,U.characterDefinition(x,i),{animation:U.animationId(a),trackingRegion:l?.current??b.current??void 0,followCursor:d,followRotation:u,trackingScope:c,displaySize:n,onError:r(()=>A(!0),"onError")}),E(!0))}).catch(()=>{O||A(!0)}),()=>{O=!0,j.current?.destroy(),j.current=null,E(!1)}},[L,w,l,c,n,d,u]),(0,m.useEffect)(()=>{j.current&&Id(()=>import("./definition-CAnOpilv.js").then(O=>{j.current?.setDefinition(O.characterDefinition(x,i)),j.current?.setAnimation(O.animationId(a))}),__vite__mapDeps([2,3,1]))},[x,i,a,T]),(0,t.jsxs)("span",{ref:b,role:p?"img":void 0,"aria-label":p,"aria-hidden":p?void 0:!0,className:V("relative inline-block shrink-0",p6e[n],h),children:[(0,t.jsx)(or,{agent:e,appearance:x,size:n<256?256:n,name:f,pose:a,muted:i,className:V("size-full",T&&!x.customAvatarAssetId&&"invisible")}),(0,t.jsx)("span",{ref:v,className:"absolute inset-0"})]})}r(Wk,"AgentCharacter");var bct=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?bct.has(e):!0}r(j_e,"isNewAgentAdapterAllowed");function vct(){const{selectedCompanyId:e}=ps(),{appearance:s}=y_e(`${e}:new-agent`);return(0,t.jsx)(Wk,{appearance:s,state:"sleepy",muted:!0,size:256,className:"size-48",trackingScope:"page"})}r(vct,"AgentBasicsCharacter");function w_e({open:e,onClose:s,onContinue:n,initialAdapter:a="",onInvite:i}){const o=(0,m.useId)(),l=!!Yc(),c=te({queryKey:D.instance.experimentalSettings,queryFn:vr.getExperimental,enabled:e,retry:!1}),[d,u]=(0,m.useState)(""),[h,p]=(0,m.useState)(a),[f,x]=(0,m.useState)("codex"),[b,v]=(0,m.useState)("name"),{data:j,isPending:N,error:w}=te({queryKey:D.adapters.all,queryFn:Sh.list,enabled:e}),k=(j??[]).filter(C=>C.loaded&&!C.disabled&&j_e(C.type,{cloud:l,nativeRunnerEnabled:c.data?.enableNativeRunner===!0})&&!["process","http"].includes(C.type)&&!Um(C.type).comingSoon),S=k.some(C=>C.type===h);return(0,t.jsx)(zs,{open:e,onOpenChange:r(C=>{C||s()},"onOpenChange"),children:(0,t.jsxs)(Ws,{className:V("flex max-h-(--sz-calc-18) flex-col gap-0 overflow-hidden p-0 sm:max-w-(--sz-640px)",b==="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:V(b==="name"&&"font-medium text-foreground"),children:"1. Name"}),(0,t.jsx)(Pn,{className:"size-3"}),(0,t.jsx)("span",{className:V(b==="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()&&(b==="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)(vct,{}),(0,t.jsxs)("div",{className:"space-y-2",children:[(0,t.jsx)(Vs,{className:"text-3xl font-semibold tracking-tight",children:b==="name"?"Meet your next agent":"Choose an adapter"}),(0,t.jsx)(hn,{className:"text-base",children:b==="name"?"Start with a name. Make them your own.":`How should ${d.trim()} work?`})]})]}),b==="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)(ut,{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"}),N&&(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:V("grid grid-cols-2 gap-3",k.length!==4&&"sm:grid-cols-3"),children:k.map(C=>{const _=Um(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:V("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)(Ap,{type:C.type}),(0,t.jsx)("span",{className:"text-sm font-medium",children:_.label}),h===C.type&&(0,t.jsx)(us,{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(()=>b==="name"?s():v("name"),"onClick"),children:b==="name"?"Cancel":(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)(jl,{className:"size-4"}),"Back"]})}),(0,t.jsxs)($,{type:"submit",disabled:!d.trim()||b==="adapter"&&!S,children:[b==="name"?"Choose adapter":"Configure agent",(0,t.jsx)(ml,{className:"size-4"})]})]})]})]})})}r(w_e,"AgentBasicsDialog");var yct={subscription:"Subscription",api:"API key",advanced:"Custom Gateway"};function jct({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)(qS,{initial:!1,mode:"sync",children:(0,t.jsx)(Tl.span,{className:"absolute inset-0 flex items-center justify-center whitespace-nowrap",initial:{opacity:0,y:bne},animate:{opacity:1,y:0,transition:Wnt},exit:{opacity:0,y:bne,transition:Vnt},children:yct[e]},e)})})}r(jct,"CredentialTag");function wct({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:V("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)(jct,{mode:s}):(0,t.jsx)("span",{"aria-hidden":!0,className:"h-4"})]})}r(wct,"ModelSourceTile");function N_e({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:V("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)(qS,{initial:!1,mode:"popLayout",children:u.map(h=>(0,t.jsx)(Tl.div,{layout:!0,transition:N1e,exit:{opacity:0,transition:srt},className:V("flex min-w-0",o?"w-(--sz-source-tile-two-up)":"flex-1"),children:(0,t.jsx)(wct,{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(N_e,"ModelSourceTiles");var uF={subscription:"Use subscription instead",api:"Use API key instead"},Nct=["subscription","api"],rre={subscription:"api",api:"subscription"};function k_e({mode:e,onChange:s}){return(0,t.jsx)(kct,{destination:rre[e],onClick:r(()=>s(rre[e]),"onClick"),modes:Nct})}r(k_e,"CredentialModeLink");function kct({destination:e,onClick:s,modes:n}){return(0,t.jsxs)("button",{type:"button","aria-label":uF[e],onClick:s,className:V("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:uF[a]},a)),(0,t.jsx)(qS,{initial:!1,mode:"sync",children:(0,t.jsx)(Tl.span,{className:V("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:fH},exit:{opacity:0,transition:Hnt},children:uF[e]},e)})]})}r(kct,"ModeLink");function RU({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)(jl,{className:"mr-1 size-3.5"}),"Back"]}):(0,t.jsx)("span",{}),(0,t.jsx)(Tl.div,{layout:!0,transition:Ynt,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)(Tl.span,{className:"flex items-center whitespace-nowrap",initial:{opacity:0},animate:{opacity:1},transition:Jnt,children:[d==="spinner"?(0,t.jsx)(tt,{className:"mr-1 size-4 animate-spin"}):null,c,d==="arrow"?(0,t.jsx)(ml,{className:"ml-1 size-3.5"}):null]},`${c}:${d}`)})})]})}r(RU,"FooterNav");function S_e({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:yu.get,enabled:i}),x=i&&(f.data?.localAiLoginSupported??f.data?.deploymentMode==="local_trusted"),b=(0,m.useRef)(0);(0,m.useEffect)(()=>()=>{b.current++},[]);const v=r(()=>{b.current++,U(!1),C(!1),R(null),T("preparing")},"cancel"),[j,N]=(0,m.useState)(h?.initialMethod==="api_key"?"api":h?"subscription":null),[w,k]=(0,m.useState)(!1),[S,C]=(0,m.useState)(!!(p||h)),[_,R]=(0,m.useState)(null),[A,T]=(0,m.useState)("preparing"),E=(0,m.useRef)("ready"),[L,O]=(0,m.useState)(""),[P,U]=(0,m.useState)(!1),[M,B]=(0,m.useState)(null),[q,z]=(0,m.useState)(null),K=s==="claude_local"?"Claude":s==="grok_local"?"Grok":"OpenAI",W=s==="claude_local"?"ANTHROPIC_API_KEY":s==="grok_local"?"XAI_API_KEY":"OPENAI_API_KEY",Q=s==="claude_local"?"anthropic":s==="grok_local"?"xai":"openai",re=e1e(e,W),J=h?{...re,options:[],subscriptions:[],loading:!1}:re,[ie,X]=(0,m.useState)(null),ne=J.subscriptions.length?J.subscriptions.find(Ee=>Ee.id===(ie??J.subscriptions[0]?.id)):void 0,[oe,G]=(0,m.useState)(null),Z=J.options.find(Ee=>Ee.id===(oe??J.options[0]?.id)),Y=h?{...J.storedLogin,data:void 0,isPending:!1,isError:!1}:J.storedLogin,ae=(0,m.useRef)(null),se=j??(J.subscriptions.length>0||s==="claude_local"&&!ne&&Y.data?"subscription":J.options.length?"api":"subscription"),ce=se==="api"?"api_key":"subscription",pe=h?.intent.connectionId&&(h.fixedMethod!==!1||h.initialMethod===ce),we=h?{...h.intent,connectionId:pe?h.intent.connectionId:void 0,name:pe?h.intent.name:h.nameForMethod?.(ce)??h.intent.name}:void 0,Se=bSe(e,we??{provider:Q,method:"subscription",name:`My ${K} subscription`,ownership:"personal",agentIds:[],allAgents:!0},!w&&x&&se==="subscription"&&!ne&&!Y.data),Te=te({queryKey:D.agents.authSignal(e,s,n),queryFn:r(()=>Ct.getAdapterAuthSignal(e,s,n??void 0),"queryFn"),retry:!1,enabled:!h&&!w});async function le(){if(P||h?.disabled)return;const Ee=++b.current;U(!0),B(null);try{if(h&&we){if(se==="subscription"&&!x)return;const Ie=ae.current??await(se==="api"?El.create(e,{...we,method:"api_key",apiKey:L.trim()}):Se.connect(we));ae.current=Ie,O(""),Ee===b.current&&h.onComplete({...Ie,method:se==="api"?"api_key":"subscription"});return}let Me=se==="api"?Z?Z.aiConnection?{env:{},aiConnection:Z.aiConnection}:{env:{[W]:Z.binding}}:q??{env:{},credentials:{[W]:L.trim()}}:{...ne?.aiConnection?{aiConnection:ne.aiConnection}:{},env:ne?.binding?{CODEX_HOME:ne.binding}:{},...s==="claude_local"&&!ne&&Y.data?{env:kN(),applyStoredClaudeLogin:!0}:{}};if(se==="subscription"&&x&&!ne&&!Y.data&&(ae.current??=await Se.connect(),Me={env:{},aiConnection:{provider:Q,method:"subscription",mode:"responsible_user"}}),Me.credentials&&(await El.create(e,{provider:Q,method:"api_key",name:`My ${K} API`,ownership:"personal",apiKey:Me.credentials[W],agentIds:[],allAgents:!0}),Me={env:{},aiConnection:{provider:Q,method:"api_key",mode:"responsible_user"}}),Ee!==b.current)return;se==="api"&&(O(""),Z||z(Me));const ve=await d(Me);if(Ee!==b.current)return;ve?o(Me):B("The provider did not respond. Check the connection and try again.")}catch(Me){if(Ee!==b.current)return;h&&O(""),B(Me instanceof Error?Me.message:"Could not connect to the provider.")}finally{Ee===b.current&&U(!1)}}r(le,"connect");const fe=se==="subscription"&&a&&n&&!ne&&!J.loading&&!Y.data&&(!!h||Te.data?.status!=="present"||ie===""),de=r(Ee=>{p&&Ee===(w?"advanced":se)||(l?.(),v(),k(Ee==="advanced"),C(p?!0:S),ae.current=null,Ee!=="advanced"&&N(Ee),O(""),z(null),B(null))},"switchMode");return(0,t.jsxs)("div",{className:"min-w-0 max-w-full",children:[(0,t.jsx)(N_e,{label:p?"Connection type":"Connect your model provider",sources:p?[{id:"subscription",label:K,icon:(0,t.jsx)(Ap,{type:s}),credentialMode:"subscription"},{id:"api",label:K,icon:(0,t.jsx)(Ap,{type:s}),credentialMode:"api"},{id:"advanced",label:"Advanced",icon:(0,t.jsx)(kKe,{className:"size-6 text-muted-foreground"}),credentialMode:"advanced"}]:[{id:s,label:K,icon:(0,t.jsx)(Ap,{type:s})}],mode:w?"advanced":se,selectedId:p?w?"advanced":se:S?s:null,collapsed:!p&&S,onSelect:r(Ee=>{h?.disabled||(p?de(Ee):C(!0))},"onSelect")}),!p&&(!S||h)&&!h?.fixedMethod&&(0,t.jsx)("div",{className:"-ml-3 mt-1",children:(0,t.jsx)(k_e,{mode:se,onChange:de})}),w&&p?(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)("div",{className:"pt-5",children:p.content}),(0,t.jsx)(RU,{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&&J.options.length>0&&(0,t.jsxs)("p",{className:"mt-2 text-sm text-muted-foreground",children:[J.options.length," saved API"," ",J.options.length===1?"key available":"keys available","."]}),se==="subscription"&&J.subscriptions.length>0&&(0,t.jsx)("div",{className:p?"pt-5":void 0,children:(0,t.jsx)(GN,{options:J.subscriptions,value:ne?.id??"",onChange:r(Ee=>{l?.(),X(Ee)},"onChange"),loading:!1,error:!1,kind:"subscription",disabled:P})}),(0,t.jsx)(Tl.div,{initial:!1,animate:{height:S?"auto":0,opacity:S?1:0},transition:{height:zd,opacity:ND},className:"overflow-hidden",children:S&&(0,t.jsx)("div",{className:"pt-5",children:se==="api"?(0,t.jsxs)(kD,{instruction:J.options.length?"Choose a saved API key or enter a new one":`Provide your ${K} API key to connect`,children:[(0,t.jsx)(GN,{...J,value:Z?.id??"",disabled:P,onChange:r(Ee=>{l?.(),G(Ee),O(""),z(null),B(null)},"onChange")}),!Z&&(0,t.jsx)(s2,{label:"API key",masked:!0,autoFocus:!0,value:L,placeholder:q?"Key entered. Retry the connection.":"Enter API key here",onChange:r(Ee=>{l?.(),G(""),O(Ee),z(null)},"onChange"),onSubmit:r(()=>{le()},"onSubmit"),disabled:P})]}):fe?(0,t.jsx)(_H,{companyId:e,adapterType:s,environmentId:n,chrome:"onboarding",aiConnection:we??{provider:Q,method:"subscription",name:`My ${K} subscription`,ownership:"personal",agentIds:[],allAgents:!0},autoStart:!0,onStored:r(()=>{},"onStored"),onPromptReady:r(Ee=>{R(Ee),T(Me=>Ee?Me==="preparing"?"ready":Me:"preparing")},"onPromptReady"),onCodeSubmitted:r(()=>{E.current=A==="waiting"?"waiting":"ready",T("connecting")},"onCodeSubmitted"),onSubmitFailed:r(()=>{T(Ee=>Ee==="connecting"?E.current:Ee)},"onSubmitFailed"),onConnected:r(Ee=>{if(h){if(!Ee){B("The login did not return a saved connection. Try again.");return}const ve=b.current;T("connecting"),El.loginResult(e,Ee).then(Ie=>{ve===b.current&&h.onComplete({...Ie,method:"subscription"})}).catch(()=>{ve===b.current&&(T("ready"),B("Could not retrieve the saved connection. Go back and retry."))});return}const Me={env:{},aiConnection:{provider:Q,method:"subscription",mode:"responsible_user"}};z(Me),o(Me)},"onConnected")}):ne?null:x&&!Y.data?(0,t.jsx)(bH,{adapterType:s,login:{...Se,retry:r(()=>{B(null),Se.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."}),M&&(0,t.jsx)("p",{role:"alert",className:"mt-4 text-sm text-destructive",children:u??M}),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)(RU,{onBack:r(()=>{S&&!p?v():c()},"onBack"),primaryLabel:S&&fe?A==="waiting"?"Waiting for code":A==="connecting"?"Connecting":`Sign in to ${K}`:P?"Connecting":se==="subscription"&&(Y.data||ne)?"Use saved subscription":se==="api"&&Z?"Use saved API key":"Connect",primaryDisabled:h?.disabled||!!h&&se==="subscription"&&!a&&!x||i&&f.isPending||Se.preparing||!!Se.error||se==="subscription"&&x&&!ne&&!Y.data&&Se.status!=="ready"||!h&&Te.isPending||J.loading||s==="claude_local"&&Y.isPending||!S&&!(se==="subscription"&&ne)||!!fe&&(!_||A!=="ready")||se==="api"&&!L.trim()&&!q&&!Z,loading:P,primaryIcon:S&&fe?A==="ready"?"none":"spinner":void 0,onPrimary:r(()=>{if(fe){if(!_||A!=="ready")return;window.open(_,"_blank","noreferrer,noopener"),T("waiting")}else le()},"onPrimary")})]})]})}r(S_e,"AgentProviderConnection");function CI(e){return e.provider==="openrouter"||e.provider==="google"?(0,t.jsx)(Cct,{...e}):(0,t.jsx)(Sct,{...e})}r(CI,"AiConnectionCredentialStep");function Sct({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:b,disabled:v}){const[j,N]=(0,m.useState)(o),[w,k]=(0,m.useState)(),S=Nt(),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:vr.get}),A=te({queryKey:D.instance.experimentalSettings,queryFn:vr.getExperimental}),T=te({queryKey:D.instance.generalSettings,queryFn:vr.getGeneral}),E=CH(T.data?.executionMode,C.data??[]);let L=null,O;try{L=E.forced?E.kubernetesEnvironment?.id??null:Bk({agentDefaultEnvironmentId:p??w,instanceDefaultEnvironmentId:R.data?.defaultEnvironmentId,localDefaultEnvironmentId:qk(C.data),managedSandboxOnly:A.data?.enableManagedSandboxOnly,managedSandboxEnvironmentId:zk(C.data),visibleEnvironmentIds:C.data?.map(W=>W.id)})}catch(W){O=W instanceof Error?W.message:"Could not resolve the sign-in environment."}const P=(C.data??[]).filter(W=>W.status==="active"&&(W.driver==="local"||W.driver==="sandbox"&&typeof W.config.provider=="string"&&_.data?.sandboxProviders?.[W.config.provider]?.supportsLoginPty===!0));!E.forced&&!p&&!w&&!P.some(W=>W.id===L)&&(L=P[0]?.id??null);const U=C.data?.find(W=>W.id===L),M=typeof U?.config.provider=="string"?U.config.provider:"",B=U?.driver==="sandbox"&&_.data?.sandboxProviders?.[M]?.supportsLoginPty===!0,q=[C,_,R,A,T].some(W=>W.isPending),z=O??[C,_,R,A,T].find(W=>W.error)?.error?.message,K={provider:s,method:"subscription",name:j,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)(ut,{value:j,onChange:r(W=>N(W.target.value),"onChange"),disabled:!!i})]}),!p&&!E.forced&&P.length>1&&(0,t.jsxs)(ka,{value:L??"",onValueChange:k,children:[(0,t.jsx)(wa,{"aria-label":"Sign-in environment",children:(0,t.jsx)(Na,{placeholder:"Sign-in environment"})}),(0,t.jsx)(Sa,{children:P.map(W=>(0,t.jsx)(dn,{value:W.id,children:W.name},W.id))})]}),z&&(0,t.jsx)("p",{role:"alert",className:"text-sm text-destructive",children:z}),b,q?(0,t.jsx)("p",{role:"status",className:"text-sm text-muted-foreground",children:"Preparing sign-in…"}):(0,t.jsx)(S_e,{companyId:e,adapterType:s==="anthropic"?"claude_local":s==="xai"?"grok_local":"codex_local",environmentId:L,canLogin:B,localEnvironment:U?.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||!j.trim(),onComplete:r(W=>{S.invalidateQueries({queryKey:["ai-connections",e]}),S.invalidateQueries({queryKey:["tools"]}),f(W)},"onComplete")}},L??"local")]})}r(Sct,"SubscriptionConnectionStep");function Cct({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,b]=(0,m.useState)(a),[v,j]=(0,m.useState)(""),N=Nt(),w=ye({mutationFn:r(()=>El.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(k=>{N.invalidateQueries({queryKey:["ai-connections",e]}),N.invalidateQueries({queryKey:["tools"]}),u({...k,method:"api_key"})},"onSuccess"),onSettled:r(()=>j(""),"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)(ut,{value:x,onChange:r(k=>b(k.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)(C1e,{providerName:s==="google"?"Google":"OpenRouter",value:v,onChange:j,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(Cct,"ApiKeyConnectionStep");var _ct=null;function Rj(){const e=(0,m.useContext)(pA),{data:s,isFetched:n,isError:a}=te({queryKey:D.instance.experimentalSettings,queryFn:r(()=>vr.getExperimental(),"queryFn"),enabled:e!=null},e??(_ct??=new vS));return e?{enabled:!a&&s?.enableChatConnectors===!0,githubEnabled:!a&&s?.enableGitHubReviewBots===!0,loaded:n}:{enabled:!1,githubEnabled:!1,loaded:!0}}r(Rj,"useChatConnectorsEnabled");function Mf(e,s,n){return e==="agentmail"||(e==="github"||e==="github-code-review-bot"?n:s)}r(Mf,"chatProviderVisible");var Ict=new RegExp(`\\b(${["mcp","server","profile","policy","gateway","transport","stdio","endpoint"].join("|")})s?\\b`,"gi");function C_e(e){return e.replace(Ict,"").replace(/\s{2,}/g," ").replace(/\s+([.,])/g,"$1").trim()}r(C_e,"sanitizeProsumerCopy");var Act={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."}},Tct={tagline:"Give your agents access to this app.",short:"Give your agents access to this app."};function __e(e,s){const n=Act[e];if(n)return n;if(s){const a=C_e(s);if(a)return{tagline:a,short:a}}return Tct}r(__e,"appCopyFor");function are(e,s,n){return n<=1?`Your ${e} key`:C_e(s)||`Your ${e} key`}r(are,"credentialFieldLabel");var Rct="/cloud/connections/handoff",Ect="/cloud/connections/reauth",OP="paperclip.cloud-oauth-handoff.v1",xg=class extends Error{static{r(this,"OAuthHandoffError")}code;constructor(e,s){super(e),this.code=s,this.name="OAuthHandoffError"}};function AH(e){if(e===void 0)return null;if(!e||typeof e!="object"||Array.isArray(e))throw new xg("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 xg("Paperclip Cloud returned an invalid sign-in handoff.","invalid_handoff");return{kind:"paperclip_cloud",session:s.session}}r(AH,"parseHandoff");function Pct(e,s){return e===404||s==="SESSION_NOT_AVAILABLE"?new xg("This sign-in expired. Start the connection again.","expired"):e===401||e===403?new xg("Paperclip Cloud could not authorize this connection for your account.","forbidden"):new xg("Paperclip Cloud couldn’t prepare secure sign-in. Try again.","unavailable")}r(Pct,"handoffFailure");async function Mct(e,s){const n=s.request??fetch;let a,i;for(let o=0;o<2;o+=1)try{if(a=await n(Rct,{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 xg(i instanceof Error?i.message:"Paperclip Cloud couldn’t prepare secure sign-in. Try again.","unavailable")}r(Mct,"postCloudHandoff");function Dct(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!==Ect||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(Dct,"exactReauthenticationTarget");async function Vk(e,s={}){const n=AH(e.handoff);if(!n){const l=mP(e.authorizationUrl);if(!l.ok)throw new xg(l.message,"invalid_handoff");return{kind:"authorization",url:l.url,host:l.host}}const a=await Mct(n.session,s),i=await a.json().catch(()=>null);if(!a.ok){if(i?.error==="RECENT_LOGIN_REQUIRED"){const l=Dct(i.reauthenticationUrl,n.session);if(l)return l}throw Pct(a.status,i?.error)}const o=mP(typeof i?.authorizationUrl=="string"?i.authorizationUrl:void 0);if(!o.ok)throw new xg("Paperclip Cloud returned an invalid provider sign-in address.","invalid_handoff");return{kind:"authorization",url:o.url,host:o.host}}r(Vk,"prepareOAuthNavigation");function _I(e,s=window.sessionStorage){const n=AH({kind:"paperclip_cloud",session:e});if(!n)throw new xg("Paperclip Cloud returned an invalid sign-in handoff.","invalid_handoff");const a={version:1,session:n.session,savedAt:Date.now()};s.setItem(OP,JSON.stringify(a))}r(_I,"savePendingCloudHandoff");function Lct(e=window.sessionStorage){const s=e.getItem(OP);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 AH({kind:"paperclip_cloud",session:n.session})}catch{return e.removeItem(OP),null}}r(Lct,"readPendingCloudHandoff");function ire(e=window.sessionStorage){e.removeItem(OP)}r(ire,"clearPendingCloudHandoff");function AD(e){return!!(e&&hge({...e,methods:e.methods.filter(s=>(s.purpose??"tool")!=="channel"&&s.transport!=="chat_sdk")}))}r(AD,"appSupportsToolCatalogSetup");var $ct=MFe.filter(e=>wge(e).some(s=>gp(s))).map(e=>e.slug);function Oct(e){return $ct.some(s=>s===e)}r(Oct,"isMcpDirectOAuthConnectSlug");function II(e,s){const n=new URLSearchParams({source:e});return s&&n.set("intent",s),`/apps/connect?${n.toString()}`}r(II,"appSourceConnectHref");function ore(e,s){return`/apps/connect?${new URLSearchParams({source:e,resume:s}).toString()}`}r(ore,"appSourceResumeHref");function mF(e){return e?`/apps/vercel-connect?${new URLSearchParams({source:e}).toString()}`:"/apps/vercel-connect"}r(mF,"vercelConnectSourceHref");function Fct(e){return e.serviceSlug??e.appKey??e.sourceSlug??void 0}r(Fct,"resolveAppsConnectRouteKey");function Bct(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=pS(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:Ly(a)&&(e.get("reconnect")?.trim()||e.get("resume")?.trim())?!0:a==="agentmail"||o?hge(i):AD(i)}r(Bct,"canEnterAppsConnect");var hF=" for the organization",zct=" for the company";function lre(e,s){const n=e.trim();if(s!=="organization")return n;const a=n.toLocaleLowerCase();return a.endsWith(hF)?n:a.endsWith(zct)?`${n.slice(0,n.length-16).trimEnd()}${hF}`:`${n}${hF}`}r(lre,"connectionNameForGrantKind");function qct(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(qct,"grantStatusLabel");function Uct(e){switch(e){case"active":return"connected";case"needs_reauthorization":case"expired":return"attention";case"revoked":return"inactive";default:return"missing"}}r(Uct,"grantStatusTone");function Kct(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(Kct,"grantAccountLabel");function Wct(e){return new Set((e?.members??[]).filter(s=>s.subjectType==="user").map(s=>s.subjectId))}r(Wct,"audienceUserIds");function Vct(e){return e.find(s=>s.kind==="organization"&&s.isDefault)??e.find(s=>s.kind==="organization")??null}r(Vct,"organizationGrant");function Hct(e,s){return s?e.find(n=>n.kind==="user"&&n.subjectUserId===s)??null:null}r(Hct,"personalGrantFor");function Qct(e,s){if(!s)return null;const n=e.find(a=>a.userId===s);return n&&(n.name?.trim()||n.email?.trim())||null}r(Qct,"memberLabel");var cre=0;function EU(){return cre+=1,{id:`header-${cre}`,name:"",value:""}}r(EU,"newCustomHeaderRow");function g_(e){try{return new URL(e).host||null}catch{return null}}r(g_,"endpointHost");function Gct(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(Gct,"oauthCallbackUrlForBrowser");function pF(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(pF,"defaultGenericMcpName");function dre(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(dre,"genericConnectGuidance");function I_e(e){const s=new Set;for(const n of e){const a=n.name.trim();if(!a&&!n.value.trim())continue;const i=IBe(a);if(!i.ok)return LZ(a,i.reason);const o=OBe(n.value);if(!o.ok)return LZ(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(I_e,"customHeaderError");function Yct(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(Yct,"genericConnectPayload");function Jct(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&&I_e(e.headers)===null:!0:!1}r(Jct,"canSubmitGenericConnect");function Hk(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(Hk,"installStateFrom");function A_e(e,s){return e.onAll||e.agentIds.has(s)}r(A_e,"isAgentInstalled");function T_e(e,s){return s.onAll?[{targetType:"company",targetId:e}]:[...s.agentIds].map(n=>({targetType:"agent",targetId:n}))}r(T_e,"installPayload");var Xct="Has access — tick to load its tools into this agent's context.";function R_e(e){return`paperclip.connector-enrollment-access:${e}`}r(R_e,"enrollmentAccessStorageKey");function Zct(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(Zct,"validEnrollmentAccessState");function edt(e,s,n){try{window.sessionStorage.setItem(R_e(s),JSON.stringify({...n,companyId:e}))}catch{}}r(edt,"saveEnrollmentAccessState");function tdt(e){const s=R_e(e);try{const n=window.sessionStorage.getItem(s);if(window.sessionStorage.removeItem(s),!n)return null;const a=JSON.parse(n);return Zct(a)?a:null}catch{return null}}r(tdt,"consumeEnrollmentAccessState");function ure(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(ure,"githubRecoveryUrl");function mre(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(mre,"oauthCallbackErrorMessage");var sdt={key:"setup",success:"complete"};function hre(e){return e.requestedAppKey||e.hasPrefilledLink||e.zapierSource?"key":"gallery"}r(hre,"requestedConnectionInitialStep");function ndt(e){const s=e.galleryApps.find(a=>a.slug===e.requestedAppKey);if(s)return s;if(E_e({requestedAppKey:e.requestedAppKey,resumeConnection:e.resumeConnection,resumeApplication:e.resumeApplication,completedResumeConnectionId:e.completedResumeConnectionId}))return Ly(e.requestedAppKey);if(!e.reconnectConnection)return null;const n=e.applications.find(a=>a.id===e.reconnectConnection?.applicationId);return sx(n)!==e.requestedAppKey?null:Ly(e.requestedAppKey)}r(ndt,"requestedConnectionEntry");function E_e(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&&sx(a)===s&&iu(n)===s)}r(E_e,"retainedResumeMatches");function rdt(e){return!e.reconnectConnection||!e.reconnectApplication||e.reconnectConnection.applicationId!==e.reconnectApplication.id?!1:e.requestedAppKey?sx(e.reconnectApplication)===e.requestedAppKey:e.byo&&e.applicationId===e.reconnectApplication.id}r(rdt,"retainedReconnectMatches");function adt(e){return e.credentialSource==="vercel_connect"&&!e.available&&!e.retainedReconnectMatches}r(adt,"isVercelConnectUnavailable");function idt(e){return e.available===!1&&!(e.reconnectConnectionId&&e.reconnectSourceMatches)}r(idt,"isConnectionDefinitionUnavailable");function odt(e){return!e.hasRequestedEntry||e.supportedMethodCount===0||e.unsupportedOAuth||e.vercelUnavailable||e.definitionUnavailable?e.reconnectConnectionId?"reconnect_unavailable":"fallback":"ready"}r(odt,"requestedConnectionSetupResolution");function pre(e,s,n,a){const i=sdt[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(pre,"appConnectHref");function FT(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(FT,"withConnectionIntent");var fre=["Pick app","Add your key"],xre={gallery:0,key:1},ldt={key:0},cdt=["Add MCP URL"],ddt=["Sign in"];function fF(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(fF,"defaultGrantKindFor");function udt(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(udt,"configuredAgentIdentity");function E1(e,s){const n=typeof s=="string"?s:s?.key;return e?.slug==="google-sheets"&&n==="local"}r(E1,"isGoogleSheetsRobotMethod");function KC(e){return e?Object.fromEntries([...e.tenantFields??[],...e.extensionFields??[]].filter(s=>s.defaultValue!==void 0).map(s=>[s.key,s.defaultValue])):{}}r(KC,"defaultMethodConfig");function aN(e,s){if(!e)return[];const n=a2(e);return s==="vercel_connect"?n.filter(a=>!!a.credentialSources?.vercelConnect):n}r(aN,"connectionMethodsForCredentialSource");function a2(e){return wge(e).filter(s=>(s.purpose??"tool")!=="channel")}r(a2,"availableToolConnectionMethods");function BT(e,s){const n=a2(e);return s?n.find(a=>a.key===s)??null:_9(n)}r(BT,"availableToolConnectionMethod");function XN(e){return _9(e)}r(XN,"recommendedSetupConnectionMethod");function gre(e){return XN(e?e.methods.filter(s=>(s.purpose??"tool")==="tool"&&(s.oauthStrategy==="paperclip_cloud_connector"||s.oauthStrategy==="paperclip_id_connector")):[])}r(gre,"recommendedManagedConnectorMethod");function bre(e){if(!e)return!1;const s=a2(e),n=s.length===1?s[0]:null;return!!(n&&gp(n)&&!UFe(n))}r(bre,"canUseAutomaticOAuthFastPath");function vre(e){if(!e)return null;const s=a2(e),n=s.length===1?s[0]:null;return n&&gp(n)?n:null}r(vre,"automaticOAuthMethod");function mdt(e){const s=e.metadata;if(!s)return null;const n=s.sourceTemplateKey??s.galleryKey;return typeof n=="string"?n:null}r(mdt,"appSourceSlug");function hdt(e){const s=e.config?.sourceTemplateKey??e.transportConfig.sourceTemplateKey;return typeof s=="string"?s:null}r(hdt,"connectionSourceSlug");function yre(e,s,n,a={}){if(!e)return null;const i=new Set(s.filter(o=>o.status!=="archived"&&mdt(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)||hdt(o)===e;return o.status!=="archived"&&(!a.draftOnly||o.status==="draft")&&o.authKind==="oauth"&&l})??null}r(yre,"reusableOAuthConnection");function P_e(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(P_e,"readConnectionIntentOAuthOutcome");function WS(e={}){const[s]=hi(),n=fa(),{selectedCompanyId:a}=ps(),i=CV(),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&&n_(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||n_(l)||H5(l))),h=te({queryKey:["tools","connection",d],queryFn:r(()=>es.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(H5(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"&&n_(p)&&(!f||KE(p,f))){const x=jge(p,s.get("targetToolkit"));return(0,t.jsx)(PJe,{...e,upstreamServiceName:e.upstreamServiceName??x?.name,interactionId:o,providerId:p,connection:h.data},`${o||"page"}:${p}`)}return(0,t.jsx)(pdt,{...e})}r(WS,"ConnectionSetupFlow");function pdt({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:b,aiConnection:v,requiredAiOwnership:j,onPhaseChange:N,onCancel:w,renderCredentialStep:k}={}){const S=Nt(),C=Gn(),_=(0,m.useCallback)((ct,fs)=>{o==="page"&&(fs?C(ct,fs):C(ct))},[o,C]),R=fa(),{selectedCompany:A,selectedCompanyId:T}=ps(),{enabled:E,githubEnabled:L}=Rj(),{enabled:O}=CV(),{setBreadcrumbs:P}=Hn(),{pushToast:U}=Ti(),[M]=hi(),B=d?.trim()||M.get("intent")?.trim()||null,q=R.appKey??M.get("appKey")??void 0,z=M.get("source")?.trim()||null,K=u||M.get("new")==="1",W=M.get("stage")?.trim()||null,Q=M.get("method")?.trim()||null,re=M.get("resume")?.trim()||null,J=M.get("oauth"),ie=M.get("code"),X=ure(M.get("installation_url")),ne=ure(M.get("management_url")),oe=p?.id??(M.get("reconnect")?.trim()||null),G=M.get("identity")==="user"?"user":M.get("identity")==="organization"?"organization":null,Z=i==="vercel_connect",Y=l??z,ae=i==="paperclip_vault"&&Oct(Y)?Y:null,se=Fct({serviceSlug:l,appKey:q,sourceSlug:z}),ce=(l??z??q)==="zapier",pe=ce?void 0:se,we=!!p||o==="page"&&(a||M.get("byo")==="1"),[Se]=(0,m.useState)(()=>o==="page"&&M.get("cloud_connector")==="enrolled"&&pe?tdt(pe):null),[Te]=(0,m.useState)(()=>{const ct=M.get("link")?.trim()??"";return{link:/^https?:\/\//i.test(ct)?ct:"",name:p?.name??M.get("name")?.trim()??"",applicationId:p?.applicationId??(M.get("applicationId")?.trim()||void 0)}}),[le,fe]=(0,m.useState)(()=>hre({requestedAppKey:pe,routeStage:W,resumeConnectionId:re,hasPrefilledLink:!!Te.link,zapierSource:ce})),[de,Ee]=(0,m.useState)(null),[Me,ve]=(0,m.useState)(""),[Ie,Ze]=(0,m.useState)(Te.link),[ue,Be]=(0,m.useState)(Te.name||(ce?"Zapier":"")),[ht,jt]=(0,m.useState)(!1),[Je,Fe]=(0,m.useState)(""),[it,At]=(0,m.useState)("auto"),[$t,zt]=(0,m.useState)(()=>[EU()]),[at,De]=(0,m.useState)(""),[Pe,dt]=(0,m.useState)(""),[rt,ft]=(0,m.useState)(!1),[kt,Ke]=(0,m.useState)(null),[$e,ze]=(0,m.useState)(!1),[et,ge]=(0,m.useState)({}),[st,Mt]=(0,m.useState)(""),[Ss,lt]=(0,m.useState)(""),[Ls,Ue]=(0,m.useState)(""),[xe,Ye]=(0,m.useState)(v&&v.mode!=="responsible_user"?`ai-${v.method}`:""),[gt,Ht]=(0,m.useState)(null),[mt,Bt]=(0,m.useState)({}),[Le,he]=(0,m.useState)(""),[Qt,Lt]=(0,m.useState)(null),[ss,Cs]=(0,m.useState)(null),[ln,mr]=(0,m.useState)({}),[pn,Ot]=(0,m.useState)("all"),[Es,Re]=(0,m.useState)(new Set),[wt,Oe]=(0,m.useState)(()=>new Set(Se?.agentIds??(c?[c]:[]))),[_t,Ut]=(0,m.useState)(Se?.grantKind??G??(c?"user":"organization")),[It,is]=(0,m.useState)(Se?.installChoice??(c?"specific":"all")),bs=!!(re&&(J==="failed"||J==="denied")),[Os,qs]=(0,m.useState)(bs?"error":"entry"),[Rn,Ns]=(0,m.useState)(()=>bs?mre(J,ie):null),[Yn,Xt]=(0,m.useState)(null),Hs=(0,m.useRef)(!1),rn=(0,m.useRef)(!1),Et=(0,m.useRef)(null),rs=(0,m.useRef)(null),[Zs,gs]=(0,m.useState)(null),[Js,kn]=(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),[kr,Or]=(0,m.useState)(h.length>0&&!!f),[Ur,xa]=(0,m.useState)(null),[ar,cr]=(0,m.useState)(null),[bt,He]=(0,m.useState)(null),Zt=(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]),ms=(0,m.useCallback)(ct=>{if(o!=="dialog"){Ym(ct);return}pr(ct);const fs=hr.current;if(!fs||fs.closed){qs("error"),Ns("Paperclip couldn’t open the sign-in window. Open sign-in in a new tab to continue."),N?.("needs_retry");return}fs.location.assign(ct),fs.focus()},[o,N]),_s=(0,m.useCallback)(()=>{hr.current=null,Ns(null),qs("redirecting"),N?.("authorizing")},[N]);(0,m.useEffect)(()=>{if(o!=="dialog"||Os!=="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),N?.("needs_retry"))},1e3);return()=>window.clearInterval(ct)},[o,Os,N]);const ts=(0,m.useCallback)(async ct=>{Cn.current?.abort();const fs=new AbortController;Cn.current=fs;try{const Ks=await Vk(ct,{signal:fs.signal});if(Ks.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.");_I(ct.handoff.session,Sn.sessionStorage),qs("starting")}else Xt(Ks.host),qs("redirecting");ms(Ks.url)}catch(Ks){if(fs.signal.aborted)return;qs("error"),Ns(Ks instanceof Error?Ks.message:"Paperclip couldn’t start secure sign-in. Try again."),N?.("needs_retry")}finally{Cn.current===fs&&(Cn.current=null)}},[o,N,ms]);(0,m.useEffect)(()=>()=>Cn.current?.abort(),[]),(0,m.useEffect)(()=>{if(o!=="dialog"||!B)return;const ct=r(fs=>{const Ks=P_e(fs,window.location.origin,B);if(Ks==="connected"){qs("entry"),pr(null),x?.({resolvedByCallback:!0});return}if(Ks==="declined"){qs("error"),Ns("Authorization was cancelled. You can try again."),N?.("needs_retry");return}Ks==="failed"&&(qs("error"),Ns("Authorization did not complete. Try again when you’re ready."))},"receiveOAuthOutcome");return window.addEventListener("message",ct),()=>window.removeEventListener("message",ct)},[B,o,x,b]),(0,m.useEffect)(()=>{if(o!=="dialog"||B||!qn)return;let ct=!1,fs=!1;const Ks=window.setInterval(async()=>{if(fs||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 Xn;try{Xn=new URL(Sn.location.href)}catch{return}if(!(Xn.origin!==window.location.origin||!Xn.pathname.includes(qn))){if(Xn.searchParams.has("oauth")){qr(null),qs("error"),Ns("Authorization did not complete. Finish setup in the sign-in window or try again.");return}if(Xn.searchParams.get("success")==="1"){fs=!0;try{const wn=await es.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{fs=!1}}}},1e3);return()=>{ct=!0,window.clearInterval(Ks)}},[B,qn,o,x]);const ws=r(()=>{At("auto"),zt([EU()]),De(""),dt(""),ft(!1),Ke(null),ze(!1)},"resetGenericAuthState"),Nn=r(ct=>{if(o==="page"&&!B&&i==="paperclip_vault"&&n_(ct.slug)){_(`/apps/connect?source=${ct.slug}`);return}if(ct.slug==="zapier"){Ee(null),ve(""),Ze(""),Be("Zapier"),jt(!1),Fe(""),ws(),ge({}),Cs(null),fe("key"),_(FT("/apps/connect?source=zapier",B));return}if(i==="paperclip_vault"&&bre(ct)){_(II(ct.slug,B));return}Ee(ct),ve(ct.name),Ze(""),Be(""),jt(!1),Fe(""),ws(),ge({}),Mt(""),lt(""),Ue("");const fs=XN(aN(ct,i));Ye(fs?.key??""),Bt(KC(fs)),he(""),Lt(null),Cs(null),Oe(new Set(c?[c]:[])),is(c?"specific":"all"),Ut(Ae??fF(fs,!!c)),fe("key"),_(i==="vercel_connect"?FT(mF(ct.slug),B):II(ct.slug,B))},"useMatchedGalleryEntry"),vn=r(()=>{fe("gallery"),_(FT(i==="vercel_connect"?mF():a?"/apps/byo":"/apps",B))},"backToGallery");(0,m.useEffect)(()=>{if(o==="page")return P([{label:"Connectors",href:"/apps"},{label:Z?"Vercel Connect":a?"Connect your own tool":"Connect an app"}]),()=>P([])},[a,o,P,Z]);const Un=te({queryKey:D.apps.gallery(T??"__none__"),queryFn:r(()=>es.listGallery(T),"queryFn"),select:(0,m.useCallback)(ct=>B||v?{...ct,apps:ct.apps.map(fs=>({...fs,methods:fs.methods.filter(Ks=>v?Ks.ai?.provider===v.provider&&(v.mode==="responsible_user"||Ks.ai.method===v.method):Ks.transport!=="runtime_auth")})).filter(fs=>fs.methods.length>0)}:ct,[B,v?.provider,v?.method,v?.mode]),enabled:!!T}),pt=Gct(window.location.origin,Un.data?.oauthCallbackUrl),Is=(0,m.useMemo)(()=>(Un.data?.apps??[]).filter(ct=>O||!H5(ct.slug)).filter(ct=>Mf(ct.slug,E,L)||!ct.methods.some(fs=>fs.transport==="chat_sdk")||AD(ct)),[Un.data,E,L,O]),cn=pe?Ly(pe):null,_n=cn?.methods.find(ct=>LN(ct)&&!gp(ct)),fn=!(_n&&xe===_n.key)&&!!cn?.methods.some(ct=>ct.oauthStrategy==="paperclip_cloud_connector"||ct.oauthStrategy==="paperclip_id_connector"),Sr=!!de?.methods.some(ct=>ct.oauthStrategy==="paperclip_cloud_connector"||ct.oauthStrategy==="paperclip_id_connector"),aa=de&&fn&&!Sr?gre(cn):null,[Da,As]=(0,m.useState)(null),an=te({queryKey:["cloud-connector","enrollment"],queryFn:r(()=>es.getCloudConnectorEnrollment(),"queryFn"),refetchInterval:Da?2e3:!1,enabled:!!(T&&fn&&!Sr)}),[Tr,Jn]=(0,m.useState)(null),Kn=(0,m.useCallback)(()=>{hr.current?.close(),hr.current=null,As(null)},[]),Vr=(0,m.useCallback)(()=>{!T||!pe||edt(T,pe,{grantKind:_t,installChoice:It,agentIds:It==="specific"?[...wt]:[]})},[_t,wt,It,pe,T]),Ps=(0,m.useCallback)(ct=>{const fs=mP(ct);if(!fs.ok){Kn(),Jn(fs.message);return}if(o==="dialog"){As(fs.url);const Ks=hr.current;Ks&&!Ks.closed?(Ks.location.assign(fs.url),Ks.focus()):Jn("Open authorization in a new tab to continue.");return}Ym(fs.url)},[o,Kn]);(0,m.useEffect)(()=>{!Da||an.data?.status!=="active"||(Kn(),Jn(null),Un.refetch())},[Da,an.data?.status,Un.refetch,Kn]);const jn=ye({mutationFn:r(()=>es.startCloudConnectorEnrollment(T,A?.name,pe?pre(pe,"key",i,{resumeConnectionId:re,reconnectConnectionId:oe,interactionId:B})+(o==="dialog"?"&enrollment_host=dialog":""):void 0),"mutationFn"),onSuccess:r(ct=>{if(!ct.verificationUrl){Kn(),Jn("Paperclip Cloud did not return an enrollment link. Try again.");return}Ps(ct.verificationUrl)},"onSuccess"),onError:r(ct=>{Kn(),Jn(ct instanceof Error?ct.message:"Paperclip couldn’t reach Paperclip Cloud. Try again.")},"onError")}),En=te({queryKey:D.tools.applications(T??"__none__"),queryFn:r(()=>es.listApplications(T),"queryFn"),enabled:!!T&&(!!ae||!!re||!!oe),refetchOnMount:"always"}),Fs=te({queryKey:D.tools.connections(T??"__none__"),queryFn:r(()=>es.listConnections(T),"queryFn"),enabled:!!T&&(!!ae||!!re||!!oe),refetchOnMount:"always"}),nr=(0,m.useMemo)(()=>u?null:yre(ae,En.data?.applications??[],Fs.data?.connections??[],K?{applicationId:Te.applicationId,draftOnly:!0}:{}),[En.data,Fs.data,K,ae,Te.applicationId,u]),un=(0,m.useMemo)(()=>oe?(Fs.data?.connections??[]).find(ct=>ct.id===oe)??null:null,[Fs.data,oe]),Gr=(0,m.useRef)(null);(0,m.useEffect)(()=>{if(!p||!Fs.isFetchedAfterMount||!un||Gr.current===un.id)return;const ct=un.config?.url??un.transportConfig?.url??un.transportConfig?.serverUrl??un.config?.serverUrl;typeof ct!="string"||!/^https?:\/\//i.test(ct)||(Gr.current=un.id,Ze(fs=>fs||ct))},[p,Fs.isFetchedAfterMount,un]);const _e=(0,m.useMemo)(()=>un?(En.data?.applications??[]).find(ct=>ct.id===un.applicationId)??null:null,[En.data,un]),Yt=rdt({requestedAppKey:pe,byo:we,applicationId:Te.applicationId,reconnectConnection:un,reconnectApplication:_e}),xn=(0,m.useMemo)(()=>re?(Fs.data?.connections??[]).find(ct=>ct.id===re)??null:null,[Fs.data,re]),Lr=(0,m.useMemo)(()=>xn?(En.data?.applications??[]).find(ct=>ct.id===xn.applicationId)??null:null,[En.data,xn]),ga=W==="complete"&&xn?.status==="active"?xn.id:null,Oa=pe?E_e({requestedAppKey:pe,resumeConnection:xn,resumeApplication:Lr,completedResumeConnectionId:Js??ga}):!1,hs=xn??un,Ae=hs?hs.credentialPolicy==="per_user"?"user":hs.credentialPolicy==="per_agent"?"agent":"organization":G,Vt=xn?.authKind==="oauth"?xn:nr,Jt=nr?nr.credentialPolicy==="per_user"?"user":nr.credentialPolicy==="per_agent"?"agent":"organization":null,Xs=Ae??Jt??(j==="shared"?"organization":null);(0,m.useEffect)(()=>{Xs&&Ut(Xs)},[Xs]);const gn=(0,m.useMemo)(()=>Ie&&!de?C5(Ie,Is):null,[de,Is,Ie]),_r=de?BT(de,xe||null):null,ei=_r&&gp(_r)?_r:vre(de),fr=i==="paperclip_vault"&&ei?de:null,Aa=i==="paperclip_vault"&&bre(de)?de:null,vi=!!ae&&(!En.isFetchedAfterMount||!Fs.isFetchedAfterMount),Va=r(ct=>{fe(ct),de&&_(pre(de.slug,ct,i,{connectionMethodKey:de.methods.find(fs=>fs.key===xe)?.ai?xe:void 0,resumeConnectionId:re,reconnectConnectionId:oe,interactionId:B}))},"setAppStep"),Er=xn??un??Vt,Mi=de?.agentInstructions,ir=de&&Mi?gt?.slug===de.slug?gt.value:Er?Er.agentInstructions??{...kk(Mi),enabled:!1}:kk(Mi):null,Hi=!ir||!!ir.text.trim(),al=ye({mutationFn:r(async ct=>(ir&&JSON.stringify(ir)!==JSON.stringify(ct.agentInstructions)&&await es.updateConnection(ct.id,{agentInstructions:ir}),es.startOAuth(ct.id,{asCurrentUser:ct.credentialPolicy==="per_user",...ct.credentialPolicy==="per_agent"?{asAgentId:udt(ct)??[...wt][0]}:{},...B?{interactionId:B}:{}})),"mutationFn"),onSuccess:r(ct=>{ts(ct)},"onSuccess"),onError:r(ct=>{const fs=ct instanceof mn&&ct.body&&typeof ct.body=="object"?ct.body.details:null;qs("error"),N?.("needs_retry"),Ns(fs?.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=al.mutate,Zi=(0,m.useCallback)(ct=>{N?.("authorizing"),Zt(),o==="dialog"&&!B&&qr(ct.id),So(ct)},[So,N,Zt,o,B]),be=r(async ct=>{if(c)return;const fs=T_e(T,(Xs??_t)!=="agent"&&It==="all"?{onAll:!0,agentIds:new Set}:{onAll:!1,agentIds:wt});await es.putConnectionInstalls(ct,fs)},"applyAccessInstalls"),xt=Xs??_t,cs=ye({mutationFn:r(async ct=>{const fs=ct??de;let Ks;if(fs){const Sn=Xs??_t,Xn=BT(fs,xe||null),wn=E1(fs,Xn)?D6(Le).ids:[],la=Me.trim(),Qa=lre(la||fs.name,Sn);Ks=await es.connectApp(T,{galleryKey:fs.slug,...ir?{agentInstructions:ir}:{},...xe?{connectionMethodKey:xe}:{},name:Qa,credentialSource:i,...i==="paperclip_vault"?{credentialValues:et}:{},...i==="vercel_connect"?{vercelConnect:{connector:Ls.trim()}}:{},...st.trim()?{oauthClient:{clientId:st.trim(),...Ss?{clientSecret:Ss}:{}}}:{},configValues:E1(fs,Xn)?{allowedSpreadsheetIds:wn}:Object.keys(mt).length>0?mt:void 0,applicationId:Te.applicationId,...re??Et.current?{resumeConnectionId:re??Et.current}:oe?{reconnectConnectionId:oe}:{},...Sn!=="organization"?{grantKind:Sn}:{},...Sn==="agent"?{subjectAgentId:[...wt][0]}:{}}),Et.current=null}else{const Sn=Yct({link:Ie,name:ue,authMode:it,needsKey:ht,keyValue:Je,headers:$t,oauthClientId:at,oauthClientSecret:Pe}),Xn=lre(Sn.name??pF(Ie)??"Custom app",xt);Ks=await es.connectApp(T,{...Sn,...oe?{reconnectConnectionId:oe}:{},...ce||gn?.slug==="zapier"?{galleryKey:"zapier",connectionMethodKey:"generated-url"}:{},name:Xn,applicationId:Te.applicationId,...xt!=="organization"?{grantKind:xt}:{},...xt==="agent"?{subjectAgentId:[...wt][0]}:{}})}return Ks.auth?.kind==="oauth"&&!re&&!oe&&await be(Ks.connectionId),Ks},"mutationFn"),onSuccess:r(ct=>{if(ct.auth?.kind==="oauth"){if(Cs(ct),ct.auth.manualClientRequired){Ke(dre("oauth_manual_client_required",null)),At("oauth"),ft(!0),ze(!1);return}if(o==="dialog"||B){qs("starting"),ze(!de),Zi(ct.connection);return}const Ks=ct.auth.startUrl?.trim();if(!Ks){qs("starting"),ze(!0),Zi(ct.connection);return}ze(!0),ts({authorizationUrl:Ks,handoff:ct.auth.handoff});return}Ke(null),Cs(ct);const fs={};for(const Ks of ct.actions.readOnly)fs[Ks.catalogEntryId]=!0;for(const Ks of ct.actions.canMakeChanges)fs[Ks.catalogEntryId]=!0;mr(fs),Ha.mutate({result:ct,enabled:fs})},"onSuccess"),onError:r(ct=>{const fs=ct instanceof mn&&ct.body&&typeof ct.body=="object"?ct.body.details:null;if(fr){qs("error"),N?.("needs_retry"),Ns(fs?.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(!de&&Ie){const Ks=typeof fs?.code=="string"?fs.code:null,Sn=dre(Ks,ct instanceof Error?ct.message:null);Ke(Sn),ze(!1),Sn.focus==="credentials"&&(jt(!0),ft(!0));return}U({title:"Couldn’t connect",body:ct instanceof Error?ct.message:"Please check your key and try again.",tone:"error"})},"onError")}),Wn=cs.mutate,sa=(0,m.useCallback)(ct=>{const fs=ct??de;(fs?BT(fs,xe||null):null)?.auth==="oauth"&&Zt(),Wn(ct)},[xe,de,Wn,Zt]);(0,m.useEffect)(()=>{if(!pe||Un.isLoading||!Un.data||(re||oe)&&(!Fs.isFetchedAfterMount||!En.isFetchedAfterMount))return;if(re&&W==="complete"&&xn?.status==="active"&&Js!==re&&Oa){_(`/apps/${xn.id}/permissions`,{replace:!0});return}if(re&&!Oa)return;const ct=ndt({requestedAppKey:pe,galleryApps:Un.data.apps,reconnectConnection:un,resumeConnection:xn,resumeApplication:Lr,completedResumeConnectionId:Js,applications:En.data?.applications??[]}),fs=!!ct?.methods.some(Ne=>Ne.oauthStrategy==="paperclip_cloud_connector"||Ne.oauthStrategy==="paperclip_id_connector");if(fn&&!fs&&an.isLoading)return;const Ks=aN(ct,i),Sn=v??(un?.connectionPurpose==="ai"?Kq.safeParse(un.config?.ai).data:void 0),Xn=Ks.find(Ne=>Sn?Ne.ai?.provider===Sn.provider&&(!("mode"in Sn)||Sn.mode!=="responsible_user")&&Ne.ai.method===Sn.method:Ne.key===Q)??(fn&&!fs?gre(cn):null)??XN(Ks),wn=Ks.length===1?Ks[0]:null,la=i==="paperclip_vault"&&!!vre(ct),Qa=adt({credentialSource:i,available:Un.data.credentialSources?.vercelConnect.available===!0,retainedReconnectMatches:!!(oe&&Yt)}),Qe=Ks.length===1&&wn?.auth==="oauth"&&!gp(wn)&&!LN(wn),Ft=idt({available:ct?.availability?.available,reconnectConnectionId:oe,reconnectSourceMatches:Yt}),vs=odt({reconnectConnectionId:oe,hasRequestedEntry:!!ct,supportedMethodCount:Ks.length,unsupportedOAuth:Qe,vercelUnavailable:Qa,definitionUnavailable:Ft});if(vs!=="ready"){if(Ee(null),fe("gallery"),vs==="reconnect_unavailable"&&oe){He(oe);return}_(FT(i==="vercel_connect"?mF():"/apps/connect",B),{replace:!0});return}if(He(null),!!ct){if(de?.slug!==ct.slug){Ee(ct),ve(ct.name),Ze(""),Be(""),jt(!1),Fe(""),ge({}),Mt(""),lt(""),Ue(""),Ye(Xn?.key??""),Bt(KC(Xn)),he(""),Lt(null),Cs(null);const Ne=Se?.companyId===T?Se:null;Ut(Ae??Ne?.grantKind??fF(Xn,!!c)),Oe(new Set(Ne?.agentIds??(c?[c]:[]))),is(Ne?.installChoice??(c?"specific":"all")),fe(hre({requestedAppKey:pe,routeStage:W,resumeConnectionId:re,hasPrefilledLink:!!Te.link,zapierSource:ce}))}else Sr!==fs&&(Ee(ct),Ye(Xn?.key??""),Bt(KC(Xn)));if(!(la&&(!En.isFetchedAfterMount||!Fs.isFetchedAfterMount))&&!(la&&rn.current)&&la&&(En.isError||Fs.isError)){qs("error"),Ns("Paperclip couldn’t check for an existing connection. Try again."),fe("key");return}}},[v,Q,En.isError,En.isFetchedAfterMount,En.data,Fs.isError,Fs.isFetchedAfterMount,an.data?.configured,an.isLoading,xe,i,de?.slug,Sr,Un.data,Un.isLoading,_,Ae,un,oe,Yt,xn,Lr,Oa,Js,ga,W,re,cn,pe,c,Se,W,ce]),(0,m.useEffect)(()=>{rs.current=null,gs(null)},[re]),(0,m.useEffect)(()=>{const ct=xn??un;if(!ct||!de||rs.current===ct.id)return;const fs=A9(ct),Ks=typeof fs.sourceTemplateKey=="string"?fs.sourceTemplateKey:null;if(Ks&&Ks!==de.slug)return;const Sn=typeof fs.connectionMethodKey=="string"?fs.connectionMethodKey:null,Xn=Sn?aN(de,i).find(la=>la.key===Sn)??null:null;if(ve(ct.name||de.name),Xn){Ye(Xn.key);const la=fs.methodConfig&&typeof fs.methodConfig=="object"?fs.methodConfig:{};Bt({...KC(Xn),...Object.fromEntries(Object.entries(la).filter(Qa=>typeof Qa[1]=="string"||typeof Qa[1]=="boolean"))})}const wn=fs.oauth&&typeof fs.oauth=="object"?fs.oauth:null;wn?.clientRegistrationSource==="manual"&&typeof wn.clientId=="string"&&Mt(wn.clientId),J==="failed"||J==="denied"?(qs("error"),Ns(mre(J,ie))):(qs("entry"),Ns(null)),fe("key"),rs.current=ct.id,gs(ct.id)},[i,de,ie,J,xn,un]);const Ha=ye({mutationFn:r(async ct=>{const{result:fs,enabled:Ks}=ct,Sn=Object.entries(Ks).filter(([,Qa])=>Qa).map(([Qa])=>Qa),Xn=Gke(fs,Qa=>!!Ks[Qa]),wn=It==="all"?"all_agents":{agentIds:Array.from(wt)},la=await es.finishApp(T,fs.connectionId,{enabledCatalogEntryIds:Sn,askFirstCatalogEntryIds:Xn,...ir?{agentInstructions:ir}:{},access:wn,...c?{preserveExistingAccess:!0}:{}});return await be(fs.connectionId),la},"mutationFn"),onSuccess:r(async(ct,fs)=>{re&&fs.result.connectionId===re&&kn(re),await S.invalidateQueries({queryKey:["tools"]}),await S.invalidateQueries({queryKey:D.apps.attention(T)}),Va("success"),x?.({connectionId:fs.result.connectionId})},"onSuccess"),onError:r(ct=>{Va("key"),U({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((re||oe)&&(Fs.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,fs]=await Promise.all([Fs.refetch(),En.refetch()]);!ct.isError&&!fs.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(re&&Fs.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(re&&Fs.isFetchedAfterMount&&En.isFetchedAfterMount&&xn&&!Oa)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&&Fs.isFetchedAfterMount&&En.isFetchedAfterMount&&(!un||!Yt))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:un?"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((re||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&&bt===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(re&&(!Fs.isFetchedAfterMount||Un.isLoading||!de||Zs!==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&&(!Fs.isFetchedAfterMount||!En.isFetchedAfterMount||Un.isLoading||pe&&!de))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(kr&&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)(Ub,{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=>{xa(ct),cr(null);try{await f(ct)}catch(fs){cr(fs instanceof Error?fs.message:"Couldn’t use this connection."),xa(null)}},"onSelect")}),ar?(0,t.jsx)(pa,{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=aN(de,i),ii=aa?[aa]:ci,Ua=de?xe?ii.find(ct=>ct.key===xe)??null:ii[0]??null:null,Pr=de?Ua?.auth??"none":it==="none"?"none":it==="oauth"?"oauth":"api_key",di=le==="key"?((ct,fs)=>(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)(RH,{extra:ct,forceOpen:fs,companyId:T,sentence:FP({grantKind:xt,authKind:Pr,installChoice:It,installCount:wt.size,lockedAgentId:c??null,preserveAgentAccess:!!(fr&&(Vt||un))}),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(Ks=>!!Ks),authKind:Pr,grantKinds:Xs?[Xs]:Ua?.grantKinds,grantKind:xt,setGrantKind:Ut,installChoice:It,setInstallChoice:is,installAgentIds:wt,setInstallAgentIds:Oe,lockedAgentId:c,capabilities:Un.data?.capabilities,githubIdentity:de?.slug==="github",identityLoading:!!fr&&vi,preserveAgentAccess:!!(fr&&(Vt||un)),disabled:cs.isPending||al.isPending},"connection-defaults"),de&&Mi&&ir&&(0,t.jsx)("div",{className:"mt-6",children:(0,t.jsx)(NV,{provider:de.name,template:Mi,value:ir,onChange:r(Ks=>Ht({slug:de.slug,value:Ks}),"onChange"),disabled:cs.isPending||al.isPending})}),e&&(0,t.jsx)("div",{className:"mt-6",children:e})]})):null,Bi=fr&&ei&&LN(ei)?ei:null,Co=Bi&&fr?(0,t.jsx)(DU,{entry:fr,method:Bi,callbackUrl:pt,clientId:st,onClientIdChange:Mt,clientSecret:Ss,onClientSecretChange:lt,required:!1}):null,Fa=di?.()??null,pi=Co?di?.(Co,Os==="error"||st.trim().length>0)??null:Fa,_o=!!(fr&&le==="key"&&(Aa||Os!=="entry")),Ed=!!(le==="key"&&de&&fn&&!Sr&&an.data?.configured===!0),Xc=!!(le==="key"&&de&&fn&&!Sr&&(an.isLoading||an.isError||an.data?.configured!==!0));if(_o&&fr)return(0,t.jsx)(PU,{entry:fr,resuming:!!re,phase:Os,error:Rn,recoveryActions:ie==="github_installation_required"?{installationUrl:X,managementUrl:ne}:void 0,authorizationHost:Yn,authorizationUrl:Cr,guidance:de?.slug==="railway"&&Ua?(0,t.jsxs)("div",{className:"space-y-3 text-sm text-muted-foreground",children:[(0,t.jsx)("p",{children:Ua.guidanceMd}),(0,t.jsx)("ul",{className:"list-disc space-y-2 pl-5",children:Ua.warnings?.map(ct=>(0,t.jsx)("li",{children:ct},ct))})]}):null,defaults:pi,settingsValid:n&&Hi,onOpenAuthorization:_s,onRetry:r(async()=>{const ct=!Hs.current;Hs.current=!0,Ns(null),qs("starting");const fs=ss?.connection??Vt;if(fs&&Co&&st.trim()){Et.current=fs.id,sa(fr);return}if(fs){Zi(fs);return}if(ct&&!re&&!En.isError&&!Fs.isError){sa(fr);return}rn.current=!0;try{const[Ks,Sn]=await Promise.all([En.refetch(),Fs.refetch()]);if(Ks.isError||Sn.isError){qs("error"),Ns("Paperclip couldn’t check for an existing connection. Try again.");return}const Xn=(re?(Sn.data?.connections??[]).find(wn=>wn.id===re&&wn.authKind==="oauth")??null:null)??yre(ae,Ks.data?.applications??[],Sn.data?.connections??[],K?{applicationId:Te.applicationId,draftOnly:!0}:{});Xn&&!re&&Ut(Xn.credentialPolicy==="per_user"?"user":Xn.credentialPolicy==="per_agent"?"agent":"organization"),Xn?Zi(Xn):cs.mutate(fr)}finally{rn.current=!1}},"onRetry"),onBack:r(()=>{Cn.current?.abort(),qs("entry"),Ns(null),vn()},"onBack"),onCancel:r(()=>{Cn.current?.abort(),(w??(()=>_("/apps")))()},"onCancel")});if($e&&!de&&Ie&&le==="key")return(0,t.jsx)(PU,{identity:{name:ue.trim()||g_(Ie)||"this server",unverifiedHost:g_(Ie)},steps:{labels:fre,activeIndex:xre.key},phase:Os,error:Rn,authorizationHost:Yn,authorizationUrl:Cr,defaults:Fa,onOpenAuthorization:_s,onRetry:r(()=>{Ns(null);const ct=ss?.connection;if(ct){qs("starting"),Zi(ct);return}ze(!1),qs("entry")},"onRetry"),onBack:r(()=>{Cn.current?.abort(),ze(!1),qs("entry"),Ns(null)},"onBack"),onCancel:r(()=>{Cn.current?.abort(),(w??(()=>_("/apps")))()},"onCancel")});const qe=ss?.application.name??de?.name??(ue.trim()||pF(Ie)||"this app"),Pt=Z?Is.filter(ct=>aN(ct,i).length>0):Is,Kt=ce?Un.data?.apps.find(ct=>ct.slug==="zapier")??null:null,Ds=(un?.connectionPurpose==="ai"?Kq.safeParse(un.config?.ai).data:void 0)??de?.methods.find(ct=>ct.key===xe)?.ai??(!xe&&de?.methods.every(ct=>ct.ai)?de.methods[0]?.ai:void 0),en=de?k?.({app:de,name:Me||de.name,grantKind:xt,agentIds:[...wt],allAgents:It==="all",onBack:r(()=>vn(),"onBack")})??(Ds&&T?(0,t.jsx)(t.Fragment,{children:(0,t.jsx)(CI,{defaults:un?void 0:Fa,companyId:T,provider:Ds.provider,fixedMethod:!!(v&&v.mode!=="responsible_user"),initialMethod:un?.connectionPurpose==="ai"?(un.config?.ai).method:Ds.method,connectionId:un?.connectionPurpose==="ai"?un.id:void 0,name:un?.connectionPurpose==="ai"?un.name:Me||`My ${de.name} ${Ds.method==="subscription"?"subscription":"API"}`,ownership:(un?.connectionPurpose==="ai"?un.credentialPolicy==="shared":xt==="organization")?"shared":"personal",agentIds:[...wt],allAgents:It==="all",onCancel:r(()=>w?w():_("/apps"),"onCancel"),onComplete:r(ct=>{x?.({connectionId:ct.connectionId}),x||_(`/apps/${ct.connectionId}/permissions`)},"onComplete")})}):void 0):void 0,ti=un?.connectionPurpose==="ai"?["Reconnect account"]:en!==void 0?["Connect account"]:ce?cdt:de&&ii.length>1?["Choose connection"]:de&&ii[0]?.auth==="oauth"?["Sign in"]:E1(de,xe)?["Share sheet"]:de?["Add your key"]:fre,Ta=un?.connectionPurpose==="ai"?0:(ce||de)&&le!=="gallery"&&le!=="success"?ldt[le]:le==="success"?ti.length:xre[le];return(0,t.jsxs)("div",{className:"max-w-5xl",children:[le!=="success"&&!(a&&le==="gallery")&&(0,t.jsx)(lD,{subtitle:le==="gallery"?Z?"Choose a reviewed app to connect through Vercel.":"Pick the app you want your agents to use.":ti.length<=1?void 0:`Step ${Ta+1} of ${ti.length}`,step:le,activeIndex:Ta,labels:ti,appIdentity:ce?{name:"Zapier",logoUrl:Kt?.branding.logoUrl??null,darkLogoUrl:Kt?.branding.darkLogoUrl??null}:de&&le!=="gallery"?{name:de.name,logoUrl:de.branding.logoUrl,darkLogoUrl:de.branding.darkLogoUrl??null}:void 0,unverifiedHost:!de&&!ce&&le!=="gallery"?g_(Ie):null,onCancel:w??(()=>_("/apps"))}),le==="key"&&s&&(0,t.jsx)("div",{className:"mx-auto mb-6 max-w-xl",children:s}),le==="gallery"&&(0,t.jsx)(xdt,{loading:Un.isLoading,initialLink:Ie,apps:Pt,vercelConnect:Z,vercelConnectAvailability:Un.data?.credentialSources?.vercelConnect??null,byo:we,byoOnly:a,source:M.get("source"),onPick:Nn,onUseLink:r(ct=>{const fs=C5(ct,Is);Ee(null),ve(""),Ze(ct),Be(fs?.name??pF(ct)??""),jt(!1),Fe(""),ge({}),he(""),Lt(null),Oe(new Set(c?[c]:[])),is(c?"specific":"all"),Ut(Ae??(c?"user":"organization")),fe("key")},"onUseLink")}),Ed&&de?(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:[de.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 ",de.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(()=>Ye(_n.key),"onClick"),children:["Use your own ",de.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)(tt,{className:"h-4 w-4 animate-spin"}):null,"Try again"]})]})]}):le==="key"&&de&&Xc?(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)(jb,{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 ",de.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(()=>Ye(_n.key),"onClick"),children:["Use your own ",de.name," OAuth app"]}):null,an.isError||Tr?(0,t.jsx)(pa,{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,Fa,(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:an.isLoading||jn.isPending,onClick:r(()=>{Jn(null),Zt(),Vr(),jn.mutate()},"onClick"),children:[jn.isPending?(0,t.jsx)(tt,{className:"h-4 w-4 animate-spin"}):null,an.data?.status==="pending"?"Continue":"Connect with Paperclip"]})]})]})}):le==="key"&&de&&en!==void 0?en:le==="key"&&de?(0,t.jsx)(vdt,{settingsValid:n&&Hi,entry:de,error:cs.isError?cs.error instanceof Error?cs.error.message:"Please check your key and try again.":null,values:et,onChange:ge,oauthClientId:st,onOAuthClientIdChange:Mt,oauthClientSecret:Ss,oauthCallbackUrl:pt,canReuseOAuthClientSecret:!!(hs?.config?.oauth&&hs.config.oauth.clientId===st.trim()&&hs.hasSavedOAuthClientSecret),onOAuthClientSecretChange:lt,credentialSource:i,vercelConnector:Ls,onVercelConnectorChange:Ue,vercelConnectAvailability:Un.data?.credentialSources?.vercelConnect??null,methodKey:xe,onMethodChange:r(ct=>{Ye(ct?.key??""),!Ae&&ct?.grantKinds&&!ct.grantKinds.includes(_t)&&Ut(fF(ct,!!c)),ge({}),Mt(""),lt(""),Ue(""),Bt(KC(ct))},"onMethodChange"),configValues:mt,onConfigChange:Bt,googleSheetsLinks:Le,googleSheetsError:Qt,onGoogleSheetsLinksChange:r(ct=>{he(ct),Lt(null)},"onGoogleSheetsLinksChange"),submitting:cs.isPending,renderDefaults:di??void 0,onBack:vn,onConnect:r(()=>{if(E1(de,xe)){const Ks=D6(Le);if(Ks.invalidCount>0){Lt("That doesn't look like a Google Sheets link.");return}if(Ks.ids.length===0){Lt("Paste at least one Google Sheets link.");return}}const ct=BT(de,xe||null),fs=!!(ct?.credentialFields?.length||ct?.tenantFields?.some(Ks=>!Ks.hidden)||ct?.extensionFields?.some(Ks=>!Ks.hidden));if(ct&&gp(ct)&&Vt&&!fs&&!st.trim()){Hs.current=!0,Ns(null),qs("starting"),Zi(Vt);return}ct&&gp(ct)&&(Hs.current=!0,Ns(null),qs("starting")),sa()},"onConnect")}):null,le==="key"&&!de&&!Ie&&!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"})]}),le==="key"&&!de&&Ie&&!ce&&(0,t.jsx)(gdt,{link:Ie,name:ue,needsKey:ht,keyValue:Je,onKeyChange:Fe,authMode:it,onAuthModeChange:r(ct=>{At(ct),Ke(null),ct!=="auto"&&jt(!1),ct!=="bearer"&&ct!=="auto"&&Fe("")},"onAuthModeChange"),headers:$t,onHeadersChange:r(ct=>{zt(ct),Ke(null)},"onHeadersChange"),oauthClientId:at,onOAuthClientIdChange:De,oauthClientSecret:Pe,onOAuthClientSecretChange:dt,advancedOpen:rt,onAdvancedOpenChange:ft,guidance:kt,matchedEntry:gn,onUseMatchedEntry:gn?()=>Nn(gn):void 0,submitting:cs.isPending||$e,defaults:Fa,onBack:vn,onConnect:r(()=>{Ke(null),cs.mutate(void 0)},"onConnect")}),le==="key"&&!de&&ce&&(0,t.jsx)(fdt,{link:Ie,onLinkChange:Ze,submitting:cs.isPending,defaults:Fa,onBack:vn,onConnect:r(()=>cs.mutate(void 0),"onConnect")}),le==="success"&&(0,t.jsx)(Ndt,{appName:qe,logoUrl:de?.branding.logoUrl,darkLogoUrl:de?.branding.darkLogoUrl,summary:wdt({grantKind:xt,authKind:Pr,installChoice:It,installCount:wt.size,enabledCount:Object.values(ln).filter(Boolean).length}),statedDefault:FP({grantKind:xt,authKind:Pr,installChoice:It,installCount:wt.size,lockedAgentId:c??null}),onDone:w??(()=>_(o==="page"&&ss?.connectionId?`/apps/${ss.connectionId}/permissions`:"/apps"))})]})}r(pdt,"StandardConnectionSetupFlow");function PU({entry:e,identity:s,resuming:n=!1,phase:a,error:i,recoveryActions:o,authorizationHost:l,authorizationUrl:c,steps:d={labels:ddt,activeIndex:0},guidance:u,defaults:h,onRetry:p,settingsValid:f=!0,onOpenAuthorization:x,onBack:b,onCancel:v}){const j=e?.name??s?.name??"this server",N=e?null:s?.unverifiedHost??null,w=a==="entry"?{title:n?`Finish connecting ${j}`:`Connect ${j} to Paperclip`,body:n?`Your connection is saved. Continue in ${j} to approve access; its identity and agent access will stay the same.`:`Paperclip will open ${j} so you can choose a workspace and approve access.`}:a==="starting"?{title:"Preparing secure sign-in",body:`Paperclip is creating a secure ${j} connection.`}:a==="redirecting"?{title:`Opening ${j}`,body:l?`Continue at ${l} to choose a workspace and approve access. Only approve access if you recognize that address.`:`Continue in ${j} to choose a workspace and approve access.`}:{title:`${j} 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)(lD,{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:N,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)(Pl,{className:"h-5 w-5 text-destructive"}):a==="entry"?(0,t.jsx)(No,{className:"h-5 w-5 text-muted-foreground"}):(0,t.jsx)(tt,{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}),N?(0,t.jsx)(oD,{host:N,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)(io,{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 ${j}`:`Continue to ${j}`:"Try again",a==="entry"?(0,t.jsx)(io,{className:"h-4 w-4","aria-hidden":"true"}):null]}):(0,t.jsx)($,{type:"button",disabled:!0,children:a==="redirecting"?`Opening ${j}…`:"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:b,children:"Back"})]})]})]})}r(PU,"OAuthConnectStateScreen");function fdt({link:e,onLinkChange:s,submitting:n,defaults:a,onBack:i,onConnect:o}){const l=MU(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)(ut,{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)(tt,{className:"mr-2 h-4 w-4 animate-spin"}),n?"Checking…":"Check link"]})]})]})}r(fdt,"ZapierConnectStep");function xdt({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),b=(0,m.useRef)(!1);(0,m.useEffect)(()=>{b.current||x(s)},[s]);const[v,j]=(0,m.useState)(null),N=(0,m.useRef)(null),w=(0,m.useRef)(null),k=(0,m.useRef)(!1);(0,m.useEffect)(()=>{!a||e&&!i||k.current||(i||N.current?.scrollIntoView?.({block:"center"}),w.current?.focus(),w.current?.select(),k.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=MU(f),_=C?C5(C,n):null,R=c==="zapier",A=r(()=>{const T=MU(f);if(!T){j("Paste a full http or https link.");return}j(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)(io,{className:"ml-2 h-3.5 w-3.5"})]})}):null]}),l?.available===!1?(0,t.jsx)(pa,{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)(na,{className:"pointer-events-none absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground"}),(0,t.jsx)(ut,{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=__e(T.slug,T.description),L=a2(T),O=L.length===0||L.every(U=>U.auth==="oauth"&&!gp(U)&&!LN(U)),P=T.availability?.available===!1||o&&l?.available!==!0;return(0,t.jsxs)("button",{type:"button",disabled:O||P,title:P?T.availability?.reason??l?.reason??void 0:void 0,onClick:r(()=>d(T),"onClick"),className:V("flex flex-col rounded-xl border border-border bg-card p-4 text-left transition-colors",O||P?"cursor-not-allowed opacity-60":"hover:border-foreground/30 hover:bg-accent/40"),children:[(0,t.jsx)(Vi,{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:P?(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:N,className:V("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)(Pl,{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)(Vi,{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(j(null),_.slug==="zapier"){A();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)(ut,{ref:w,type:R||_?.slug==="zapier"?"password":"url",autoComplete:"off",spellCheck:!1,"aria-label":"MCP server URL",value:f,onChange:r(T=>{b.current=!0,x(T.target.value),j(null)},"onChange"),onKeyDown:r(T=>{T.key==="Enter"&&A()},"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:A,children:"Continue"})]}),v&&(0,t.jsx)("div",{className:"text-xs text-destructive",children:v})]})]})]})}r(xdt,"GalleryStep");function MU(e){try{const s=new URL(e.trim());return s.protocol!=="http:"&&s.protocol!=="https:"?null:s.toString()}catch{return null}}r(MU,"normalizeAppLink");function gdt({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:b,guidance:v,matchedEntry:j,onUseMatchedEntry:N,submitting:w,defaults:k,onBack:S,onConnect:C}){const _=g_(e),R=o==="custom_headers"?I_e(c):null,A=Jct({link:e,name:s,authMode:o,needsKey:n,keyValue:a,headers:c,oauthClientId:u,oauthClientSecret:p}),T=o==="auto"&&n||o==="bearer",E=j?.slug==="zapier"?zge(e):e,L=r((O,P)=>{d(c.map(U=>U.id===O?{...U,...P}:U))},"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)(oD,{host:_})]}),j&&N?(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)(Vi,{name:j.name,logoUrl:j.branding.logoUrl,darkLogoUrl:j.branding.darkLogoUrl,size:24}),(0,t.jsxs)("span",{className:"truncate",children:["Paperclip has a guided setup for ",j.name,"."]})]}),(0,t.jsxs)($,{type:"button",size:"sm",variant:"outline",onClick:N,children:["Use ",j.name]})]}):null,v?(0,t.jsx)("div",{className:"mt-6",children:(0,t.jsx)(pa,{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)(ut,{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)(el,{open:x,onOpenChange:b,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)(nn,{className:V("h-4 w-4 text-muted-foreground transition-transform",x&&"rotate-180")})]}),(0,t.jsxs)(tl,{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:jre.map(O=>(0,t.jsx)(bdt,{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:jre.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)(ut,{value:O.name,onChange:r(P=>L(O.id,{name:P.target.value}),"onChange"),placeholder:"Header name","aria-label":"Header name",className:"h-10 font-mono"}),(0,t.jsx)(ut,{type:"password",autoComplete:"off",value:O.value,onChange:r(P=>L(O.id,{value:P.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(P=>P.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,EU()]),"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)(ut,{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)(ut,{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]})]})]}),k,(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||!A||!!R,children:[w&&(0,t.jsx)(tt,{className:"mr-2 h-4 w-4 animate-spin"}),w?"Checking…":"Check link"]})]})]})}r(gdt,"LinkConnectStep");var jre=[{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 bdt({label:e,selected:s,onClick:n}){return(0,t.jsx)("button",{type:"button",onClick:n,"aria-pressed":s,className:V("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(bdt,"SegmentedOption");function vdt({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:b,methodKey:v,onMethodChange:j,configValues:N,onConfigChange:w,googleSheetsLinks:k,googleSheetsError:S,onGoogleSheetsLinksChange:C,submitting:_,renderDefaults:R,onBack:A,onConnect:T}){const E=(0,m.useMemo)(()=>aN(s,p),[p,s]),L=v?E.find(Fe=>Fe.key===v)??null:XN(E),O=(0,m.useMemo)(()=>E.some(Fe=>Fe.capabilityProfile)?Array.from(E.reduce((Fe,it)=>{const At=it.capabilityProfile.key,$t=Fe.get(At);return $t?$t.methods.push(it):Fe.set(At,{key:At,label:it.capabilityProfile?.label??it.label??it.key,description:it.capabilityProfile?.description??it.whenToUse,methods:[it]}),Fe},new Map)).map(([,Fe])=>Fe):[],[E]),P=L?.capabilityProfile?.key??L?.key??"",U=O.map(Fe=>Fe.key).join("|"),[M,B]=(0,m.useState)(P||XN(E)?.capabilityProfile?.key||(O.length===1?O[0].key:""));(0,m.useEffect)(()=>{if(P){B(P);return}B(Fe=>O.some(it=>it.key===Fe)?Fe:XN(E)?.capabilityProfile?.key||(O.length===1?O[0].key:""))},[U,O,E,P]);const q=O.length>1?O.find(Fe=>Fe.key===M)?.methods??[]:E,z=(L?.credentialFields??[]).map(Fe=>({...Fe,configPath:uge(Fe,L),helpUrl:L?.consoleLinks?.keys??L?.consoleLinks?.docs??""})),K=L?.credentialSources?.vercelConnect??null,W=p==="vercel_connect",Q=W||z.every(Fe=>Fe.required===!1||(a[Fe.configPath]?.trim().length??0)>0),re=LN(L),J=re&&!gp(L),ie=W||!J||o.trim().length>0&&(!L?.oauthClientSecretRequired||u||c.trim().length>0),X=!W||f.trim().length>0,ne=L?.auth==="oauth"&&re?d:null,oe=[...L?.tenantFields??[],...L?.extensionFields??[]],G=oe.filter(Fe=>!Fe.hidden),Z=G.filter(Fe=>Fe.advanced!==!0),Y=G.filter(Fe=>Fe.advanced===!0),ae=oe.every(Fe=>{if(!Fe.required)return!0;const it=N[Fe.key];return typeof it=="boolean"||typeof it=="string"&&it.trim().length>0}),se=L?.configRequirements?.atLeastOneOf??[],ce=se.length===0||se.some(Fe=>{const it=N[Fe];return typeof it=="string"&&it.trim().length>0}),pe=(O.length<=1||!!M)&&(q.length<=1?!!L:!!v),we=s.availability?.robotEmail??null,Se=s.availability?.available===!1,Te=!W&&re&&!J,le=O.length>1||q.length>1,fe=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)(Lm,{ariaLabel:`Access level for ${s.name}`,className:"mt-2",value:M,onValueChange:r(Fe=>{const it=O.find(At=>At.key===Fe);it&&(B(Fe),j(_9(it.methods)))},"onValueChange"),options:O.map(Fe=>({value:Fe.key,title:Fe.label,description:Fe.description}))}),!M&&(0,t.jsx)("p",{className:"mt-2 text-xs text-muted-foreground",children:"Choose an access level to continue."})]}):null,de=q.find(Fe=>Fe.oauthStrategy==="paperclip_cloud_connector"),Ee=de&&q.find(Fe=>LN(Fe)&&!gp(Fe)),Me=L?.key===Ee?.key,ve=(0,m.useId)(),Ie=de&&Ee&&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":Me,"aria-controls":ve,disabled:_,onClick:r(()=>j(Me?de:Ee),"onClick"),children:Me?"Use Paperclip instead":`Use your own ${vBe(de.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)(Lm,{ariaLabel:`How to connect ${s.name}`,className:"mt-2",value:v,onValueChange:r(Fe=>{const it=q.find(At=>At.key===Fe);it&&j(it)},"onValueChange"),options:q.map(Fe=>({value:Fe.key,title:Fe.label??(Fe.auth==="oauth"?`Sign in with ${s.name}`:"Use an API key")}))}),!L&&(0,t.jsx)("p",{className:"mt-2 text-xs text-muted-foreground",children:"Choose a connection method to continue."})]}):null,Ze=Y.length>0||Te||le,ue=Me||!pe,Be=Ze?(0,t.jsxs)("div",{className:"space-y-6",children:[fe,Ie,Y.map(Fe=>(0,t.jsx)(wre,{field:Fe,value:N[Fe.key],onChange:r(it=>w({...N,[Fe.key]:it}),"onChange")},Fe.key)),Te?(0,t.jsx)(DU,{entry:s,method:L,callbackUrl:ne,clientId:o,onClientIdChange:l,clientSecret:c,onClientSecretChange:h,required:!1}):null]}):null,ht=R?.(Be,ue)??null;if(E1(s,L)){const Fe=D6(k),it=e&&!Se&&!!we&&k.trim().length>0;return(0,t.jsxs)("div",{className:"mx-auto max-w-xl",children:[(0,t.jsxs)("div",{className:"space-y-6",children:[fe,we?(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:we,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:we}),(0,t.jsx)(M_e,{value:we,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)(Qn,{value:k,onChange:r(At=>C(At.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:Fe.ids.length>0?`${Fe.ids.length} ${Fe.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})]})]}),ht,(0,t.jsxs)("div",{className:"mt-8 flex items-center justify-between",children:[(0,t.jsx)($,{variant:"ghost",onClick:A,disabled:_,children:"Back"}),(0,t.jsxs)($,{onClick:T,disabled:_||!it,children:[_&&(0,t.jsx)(tt,{className:"mr-2 h-4 w-4 animate-spin"}),_?"Checking…":"Connect"]})]})]})}const jt=L?.connectorProfile==="asana.mcp",Je=jt?null:L?.consoleLinks?.docs??s.docsUrl;return(0,t.jsxs)("div",{className:"mx-auto max-w-xl",children:[Je?(0,t.jsx)("div",{className:"mb-4 flex justify-end",children:(0,t.jsxs)("a",{href:Je,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)(io,{className:"h-3 w-3"})]})}):null,(0,t.jsxs)("div",{className:"space-y-6",children:[jt?(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,L?.capabilityProfile&&(0,t.jsxs)("p",{className:"text-sm text-muted-foreground",children:[L.capabilityProfile.label,": ",L.capabilityProfile.description]}),W&&K&&b?(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:b.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)(io,{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)(ut,{id:"vercel-connect-connector",value:f,onChange:r(Fe=>x(Fe.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)(pa,{tone:"danger",children:n})}):null,Z.map(Fe=>(0,t.jsx)(wre,{field:Fe,value:N[Fe.key],onChange:r(it=>w({...N,[Fe.key]:it}),"onChange")},Fe.key)),!W&&L?.auth==="oauth"&&J?(0,t.jsx)("div",{id:ve,role:"region","aria-label":"Your OAuth app",children:(0,t.jsx)(DU,{entry:s,method:L,callbackUrl:ne,clientId:o,onClientIdChange:l,clientSecret:c,onClientSecretChange:h,required:!0})}):null,W||!L||z.length===0?null:z.map(Fe=>(0,t.jsxs)("div",{children:[(0,t.jsx)("label",{className:"text-sm font-medium text-foreground",children:are(s.name,Fe.label,z.length)}),(0,t.jsx)(ut,{type:Fe.type==="text"&&Fe.secret===!1?"text":"password","aria-label":are(s.name,Fe.label,z.length),autoComplete:"off",value:a[Fe.configPath]??"",onChange:r(it=>i({...a,[Fe.configPath]:it.target.value}),"onChange"),placeholder:Fe.type==="text"&&Fe.secret===!1?Fe.placeholder:"••••••••••••••••",className:"mt-2 h-11 font-mono"}),Fe.helperMd&&(0,t.jsx)("p",{className:"mt-2 text-xs text-muted-foreground",children:Fe.helperMd}),Fe.helpUrl&&(0,t.jsxs)("a",{href:Fe.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)(io,{className:"h-3 w-3"})]})]},Fe.configPath))]}),ht,(0,t.jsxs)("div",{className:"mt-8 flex items-center justify-between",children:[(0,t.jsx)($,{variant:"ghost",onClick:A,disabled:_,children:"Back"}),(0,t.jsxs)($,{onClick:T,disabled:_||!e||!pe||!Q||!ie||!X||!ae||!ce,children:[_&&(0,t.jsx)(tt,{className:"mr-2 h-4 w-4 animate-spin"}),_?"Checking…":W?L?.auth==="oauth"?"Validate and continue":"Validate and connect":L?.auth==="oauth"?s.slug==="github"?"Continue to GitHub":"Continue to sign in":"Connect"]})]})]})}r(vdt,"KeyStep");function M_e({value:e,ariaLabel:s}){const{copied:n,failed:a,copy:i}=Op();return(0,t.jsxs)($,{type:"button",variant:"outline",className:"shrink-0","aria-label":s,onClick:r(()=>{i(e)},"onClick"),children:[n?(0,t.jsx)(us,{className:"mr-2 h-4 w-4"}):(0,t.jsx)(wr,{className:"mr-2 h-4 w-4"}),n?"Copied":a?"Copy failed":"Copy"]})}r(M_e,"CopyValueButton");function DU({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)(io,{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)(M_e,{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)(ut,{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)(ut,{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(DU,"OAuthClientFields");function wre({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)(ri,{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)(Qn,{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)(ut,{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(wre,"MethodConfigField");function ydt({companyId:e,...s}){const n=te({queryKey:D.agents.list(e),queryFn:r(()=>Ct.list(e),"queryFn")});return(0,t.jsx)(TH,{...s,agents:(n.data??[]).filter(a=>a.status!=="terminated"),agentsLoading:n.isLoading})}r(ydt,"AccessStep");function TH({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:b=!1,identityLoading:v=!1,preserveAgentAccess:j=!1,pending:N=!1,hideFooter:w=!1,bare:k=!1,onBack:S,onContinue:C}){const _=p?.editableAgentIds,R=_?e.filter(q=>_.includes(q.id)):e,A=p?.canSetCompanyInstall??!0,T=p?.canCreateOrganizationGrant??!0,E=n!=="none",L=a??["user","organization"],O=(!E||i==="user"||i==="agent"||T)&&(j?!0:h?d.has(h):i==="agent"?l==="specific"&&d.size===1:l==="all"?A:d.size>0),P=h?e.find(q=>q.id===h)?.name??"the requesting agent":null,U=f?"Connect GitHub as":"Which humans can use this credential?",M=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?",B=f?M:"Which agents can use this connection?";return(0,t.jsxs)("div",{className:k?"":"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:U}),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&&L.length===1?(0,t.jsxs)("div",{className:"mt-4 flex items-center gap-3 rounded-md border border-border p-4",children:[L[0]==="user"?(0,t.jsx)(Gm,{className:"h-4 w-4 shrink-0 text-muted-foreground","aria-hidden":"true"}):L[0]==="agent"?(0,t.jsx)(ro,{className:"h-4 w-4 shrink-0 text-muted-foreground","aria-hidden":"true"}):(0,t.jsx)(qN,{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:L[0]==="user"?f?"My GitHub account":"Just me":L[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:L[0]==="user"?"Agents use it only for runs where you are the responsible person.":L[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)(Lm,{ariaLabel:f?U:"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)(Gm,{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)(ro,{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)(qN,{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=>L.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:M}),j?(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)(qN,{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:P}),". 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)(Lm,{ariaLabel:B,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)(ro,{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)(jdt,{}),accessibleLabel:A?"Any agent":`Any agent. Unavailable: ${p?.companyInstallReason??"Only someone who can configure this connection can choose this."}`,tooltip:A?void 0:p?.companyInstallReason??"Only someone who can configure this connection can choose this.",disabled:!A}]}),!j&&!h&&l==="specific"?(0,t.jsx)("div",{className:"mt-3",children:(0,t.jsx)(yj,{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:N,children:"Back"}),(0,t.jsxs)($,{className:"w-full sm:w-auto",onClick:C,disabled:!O||v||N,children:[N?(0,t.jsx)(tt,{className:"h-4 w-4 animate-spin","aria-hidden":"true"}):null,x,!N&&b?(0,t.jsx)(io,{className:"h-4 w-4","aria-hidden":"true"}):null]})]})]})}r(TH,"AccessStepContent");function FP(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(FP,"connectionDefaultSummarySentence");function RH({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)(el,{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)(tl,{children:(0,t.jsxs)("div",{className:"mt-3 space-y-6",children:[i,s?(0,t.jsx)(TH,{...c,agents:s,bare:!0,hideFooter:!0,submitLabel:"",onBack:r(()=>{},"onBack"),onContinue:r(()=>{},"onContinue")}):(0,t.jsx)(ydt,{...c,companyId:e,bare:!0,hideFooter:!0,submitLabel:"",onBack:r(()=>{},"onBack"),onContinue:r(()=>{},"onContinue")})]})})]})}r(RH,"ConnectionAccessDefaults");function jdt(){return(0,t.jsxs)("span",{className:"relative block h-4 w-5","aria-hidden":"true",children:[(0,t.jsx)(ro,{className:"absolute left-0 top-0 h-3.5 w-3.5"}),(0,t.jsx)(ro,{className:"absolute bottom-0 right-0 h-3.5 w-3.5"})]})}r(jdt,"BotGroupIcon");function wdt(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(wdt,"accessSummaryLines");function Ndt({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)(us,{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)(Vi,{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(Ndt,"ConnectionSetupCompletionScreen");function D_e(){const{newProjectOpen:e,closeNewProject:s}=RA(),{selectedCompanyId:n}=ps();return n&&e?(0,t.jsx)(kdt,{companyId:n,onClose:s},n):null}r(D_e,"NewProjectDialog");function kdt({companyId:e,onClose:s}){const n=Nt(),[a,i]=(0,m.useState)(""),[o]=(0,m.useState)(()=>k5[Math.floor(Math.random()*k5.length)]),[l,c]=(0,m.useState)([]),[d,u]=(0,m.useState)(!1),h=(0,m.useRef)(null),p=ye({mutationFn:r(()=>ra.create(e,{name:a.trim(),color:o,status:"planned",repositoryIds:l.map(f=>f.id)}),"mutationFn"),onSuccess:r(f=>{gb(f.id,e),n.invalidateQueries({queryKey:D.projects.all(e)}),s()},"onSuccess")});return(0,t.jsx)(zs,{open:!0,onOpenChange:r(f=>{!f&&!p.isPending&&s()},"onOpenChange"),children:(0,t.jsx)(Ws,{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)(Vs,{className:"sr-only",children:"Connect GitHub"}),(0,t.jsx)(WS,{host:"dialog",serviceSlug:"github",forceNewConnection:!0,onCancel:r(()=>u(!1),"onCancel"),onComplete:r(()=>{n.invalidateQueries({queryKey:wV(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)(Vs,{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)(zn,{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)(Wm,{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)(Qke,{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(kdt,"NewProjectForm");var gg={list:r(e=>Ce.get(`/companies/${e}/goals`),"list"),get:r(e=>Ce.get(`/goals/${e}`),"get"),create:r((e,s)=>Ce.post(`/companies/${e}/goals`,s),"create"),update:r((e,s)=>Ce.patch(`/goals/${e}`,s),"update"),remove:r(e=>Ce.delete(`/goals/${e}`),"remove")};function L_e(e){return{"--sc":`var(${e})`}}r(L_e,"scStyle");function Sdt(e){const s=e.replace(/_/g," ");return s.charAt(0).toUpperCase()+s.slice(1)}r(Sdt,"sentenceCaseStatus");function ai({status:e,label:s}){return(0,t.jsx)("span",{className:V("inline-flex items-center rounded-full px-2.5 py-0.5 text-xs font-medium whitespace-nowrap shrink-0",Vq[e]??"bg-muted text-muted-foreground"),children:s??e.replace(/[_-]/g," ")})}r(ai,"StatusBadge$5");function $_e({status:e}){const s=Sze[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:L_e(s),children:n.replace(/_/g," ")})}r($_e,"AgentStatusBadge");function fp({status:e,externalConversationState:s}){const n=e==="in_review"&&s==="waiting"?"idle":e,a=aze[n]??"--status-task-backlog";return(0,t.jsxs)("span",{className:V("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:L_e(a),children:[(0,t.jsx)(bA,{status:n,size:"sm"}),Sdt(n)]})}r(fp,"IssueStatusBadge");var Nre={company:"Organization",team:"Team",agent:"Agent",task:"Task"};function O_e(){const{newGoalOpen:e,newGoalDefaults:s,closeNewGoal:n}=RA(),{selectedCompanyId:a,selectedCompany:i}=ps(),o=Nt(),[l,c]=(0,m.useState)(""),[d,u]=(0,m.useState)(""),[h,p]=(0,m.useState)("planned"),[f,x]=(0,m.useState)("task"),[b,v]=(0,m.useState)(""),[j,N]=(0,m.useState)(!1),[w,k]=(0,m.useState)(!1),[S,C]=(0,m.useState)(!1),[_,R]=(0,m.useState)(!1),A=(0,m.useRef)(null),T=b||s.parentId||"",{data:E}=te({queryKey:D.goals.list(a),queryFn:r(()=>gg.list(a),"queryFn"),enabled:!!a&&e}),L=ye({mutationFn:r(q=>gg.create(a,q),"mutationFn"),onSuccess:r(()=>{o.invalidateQueries({queryKey:D.goals.list(a)}),P(),n()},"onSuccess")}),O=ye({mutationFn:r(async q=>{if(!a)throw new Error("No organization selected");return qb.uploadImage(a,q,"goals/drafts")},"mutationFn")});function P(){c(""),u(""),p("planned"),x("task"),v(""),N(!1)}r(P,"reset");function U(){!a||!l.trim()||L.mutate({title:l.trim(),description:d.trim()||void 0,status:h,level:f,...T?{parentId:T}:{}})}r(U,"handleSubmit");function M(q){q.key==="Enter"&&(q.metaKey||q.ctrlKey)&&(q.preventDefault(),U())}r(M,"handleKeyDown");const B=(E??[]).find(q=>q.id===T);return(0,t.jsx)(zs,{open:e,onOpenChange:r(q=>{q||(P(),n())},"onOpenChange"),children:(0,t.jsxs)(Ws,{showCloseButton:!1,className:V("p-0 gap-0",j?"sm:max-w-2xl":"sm:max-w-lg"),onKeyDown:M,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(()=>N(!j),"onClick"),children:j?(0,t.jsx)(Fye,{className:"h-3.5 w-3.5"}):(0,t.jsx)(Nj,{className:"h-3.5 w-3.5"})}),(0,t.jsx)($,{variant:"ghost",size:"icon-xs",className:"text-muted-foreground",onClick:r(()=>{P(),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(),A.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)(Qc,{ref:A,value:d,onChange:u,placeholder:"Add description...",bordered:!1,contentClassName:V("text-sm text-muted-foreground",j?"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)(ur,{open:w,onOpenChange:k,children:[(0,t.jsx)(Nr,{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)(ai,{status:h})})}),(0,t.jsx)(rr,{className:"w-40 p-1",align:"start",children:Uge.map(q=>(0,t.jsx)("button",{className:V("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),k(!1)},"onClick"),children:q},q))})]}),(0,t.jsxs)(ur,{open:S,onOpenChange:C,children:[(0,t.jsx)(Nr,{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)(Wl,{className:"h-3 w-3 text-muted-foreground"}),Nre[f]??f]})}),(0,t.jsx)(rr,{className:"w-40 p-1",align:"start",children:Fge.map(q=>(0,t.jsx)("button",{className:V("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:Nre[q]??q},q))})]}),(0,t.jsxs)(ur,{open:_,onOpenChange:R,children:[(0,t.jsx)(Nr,{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)(Pp,{className:"h-3 w-3 text-muted-foreground"}),B?B.title:"Parent goal"]})}),(0,t.jsxs)(rr,{className:"w-48 p-1",align:"start",children:[(0,t.jsx)("button",{className:V("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:V("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()||L.isPending,onClick:U,children:L.isPending?"Creating…":s.parentId?"Create sub-goal":"Create goal"})})]})})}r(O_e,"NewGoalDialog");var xF=r((e,s)=>`/companies/${e}/agents/${s}/dot-binding`,"path"),zT={create:r(e=>Ce.post(`/companies/${e}/dot-invitations`,{}),"create"),connection:r((e,s,n)=>Ce.get(xF(e,s),{signal:n}),"connection"),pair:r((e,s,n)=>Ce.post(xF(e,s),{replaceBindingId:n}),"pair"),retry:r((e,s,n)=>Ce.post(xF(e,s)+"/event-test",{bindingId:n}),"retry")};function Cdt(e){const s=_dt(e),n=Idt(e);return`You're invited to join a Paperclip company as an agent.
330
+ `;function Oot(){const e=new Blob([$ot],{type:"application/javascript"}),s=URL.createObjectURL(e);try{return new Worker(s)}finally{URL.revokeObjectURL(s)}}r(Oot,"createSandboxedWorker");var vU=new Map,DP=new Map,h3=new Set,p3=new Map,K1e=null;function Fot(e){K1e=e}r(Fot,"setDynamicParserResultNotifier");function W1e(e,s){e.worker.postMessage(s)}r(W1e,"sendToWorker");function Bot(e){return e.nextId++}r(Bot,"nextRequestId");function zot(e,s){return`${s}\0${e}`}r(zot,"lineCacheKey");function qot(){K1e?.()}r(qot,"notifyResultReady");function Uot(e,s,n){return new Promise(a=>{const i=Bot(e);e.pendingResolves.set(i,a),W1e(e,{type:"parse",id:i,line:s,ts:n})})}r(Uot,"parseLineAsync");function T1(e){for(const s of e.pendingResolves.values())s([]);e.pendingResolves.clear()}r(T1,"drainPendingRequests");function Kot(e){return new Promise((s,n)=>{const a=Oot(),i={worker:a,ready:!1,nextId:1,pendingResolves:new Map},o=setTimeout(()=>{T1(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"&&T1(i)},s(i);return}if(c.type==="error"){clearTimeout(o),T1(i),a.terminate(),n(new Error(c.message));return}},a.onerror=l=>{clearTimeout(o),T1(i),a.terminate(),n(new Error(`Worker error: ${l.message}`))},W1e(i,{type:"init",source:e})})}r(Kot,"initSandboxedWorker");function Wot(e){const s=new Map,n=new Set;return{parseStdoutLine:r((i,o)=>{const l=zot(i,o),c=s.get(l);return c?c.slice():(n.has(l)||(n.add(l),Uot(e,i,o).then(d=>{n.delete(l),s.set(l,d),qot()})),[])},"parseStdoutLine")}}r(Wot,"buildParserModule");async function yU(e){const s=DP.get(e);if(s)return s;if(h3.has(e))return null;const n=p3.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 h3.add(e),null;const o=await Kot(await i.text());vU.set(e,o);const l=Wot(o);return DP.set(e,l),l}catch{return h3.add(e),null}finally{p3.delete(e)}})();return p3.set(e,a),a}r(yU,"loadDynamicParser");function jU(e){const s=DP.has(e);DP.delete(e),h3.delete(e),p3.delete(e);const n=vU.get(e);return n&&(T1(n),n.worker.terminate(),vU.delete(e)),s}r(jU,"invalidateDynamicParser");var f3=[],_D=new Map,wU=new Set,V1e=new Map,nF=new Set,LT=new Map,NU=new Set;function H1e(e){return NU.add(e),()=>NU.delete(e)}r(H1e,"onAdapterChange");function Q1e(){for(const e of NU)e()}r(Q1e,"notifyAdapterChange");Fot(Q1e);function Vot(){for(const e of[_rt,Urt,cat,fat,Oat,Jat,cit,bit,Ait,Fit,cot,sot,Iat,Sot,MP,Lot])wU.add(e.type),V1e.set(e.type,e),Yv(e)}r(Vot,"registerBuiltInUIAdapters");function Yv(e){const s=f3.findIndex(n=>n.type===e.type);s>=0?f3.splice(s,1,e):f3.push(e),_D.set(e.type,e),Q1e()}r(Yv,"registerUIAdapter");function G1e(e){return _D.get(e)??null}r(G1e,"findUIAdapter");Vot();function KS(e){const s=_D.get(e);if(!s){let n=!1;return{type:e,label:e,parseStdoutLine:r((a,i)=>(n||(n=!0,yU(e).then(o=>{o&&Yv({type:e,label:e,parseStdoutLine:o.parseStdoutLine,createStdoutParser:o.createStdoutParser,ConfigFields:Gy,buildAdapterConfig:Yy})})),MP.parseStdoutLine(a,i)),"parseStdoutLine"),ConfigFields:Gy,buildAdapterConfig:Yy}}return s}r(KS,"getUIAdapter");function Hot(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 wU){const i=V1e.get(a);if(!i)continue;const o=n.has(a),l=s.has(a),c=nF.has(a);if(o&&l&&!c){nF.add(a);const d=(LT.get(a)??0)+1;LT.set(a,d);let u=!1;const h=i.parseStdoutLine,p=e.find(f=>f.type===a)?.label??a;Yv({type:a,label:p,parseStdoutLine:r((f,x)=>(u||(u=!0,yU(a).then(b=>{b&&LT.get(a)===d&&Yv({type:a,label:p,parseStdoutLine:b.parseStdoutLine,createStdoutParser:b.createStdoutParser,ConfigFields:i.ConfigFields,buildAdapterConfig:i.buildAdapterConfig})})),h(f,x)),"parseStdoutLine"),ConfigFields:i.ConfigFields,buildAdapterConfig:i.buildAdapterConfig})}else(!o||!l)&&c&&(nF.delete(a),LT.delete(a),jU(a),Yv(i))}for(const{type:a,label:i}of e){if(wU.has(a))continue;const o=_D.get(a);if(o&&o!==MP)continue;let l=!1;const c=o?.parseStdoutLine??MP.parseStdoutLine;Yv({type:a,label:i,parseStdoutLine:r((d,u)=>(l||(l=!0,yU(a).then(h=>{h&&Yv({type:a,label:i,parseStdoutLine:h.parseStdoutLine,createStdoutParser:h.createStdoutParser,ConfigFields:o?.ConfigFields??Gy,buildAdapterConfig:o?.buildAdapterConfig??Yy})})),c(d,u)),"parseStdoutLine"),ConfigFields:o?.ConfigFields??Gy,buildAdapterConfig:o?.buildAdapterConfig??Yy})}}r(Hot,"syncExternalAdapters");function vH(){return[...f3]}r(vH,"listUIAdapters");function kU(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(kU,"resolveStdoutParser");function Y1e(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(Y1e,"appendTranscriptEntry");function Qot(e,s){for(const n of s)Y1e(e,n)}r(Qot,"appendTranscriptEntries");function Got(e,s=160){return e.length<=s?e:`${e.slice(0,s-3)}...`}r(Got,"truncateTranscriptLine");function Yot(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(Yot,"formatTranscriptParserError");function Jot(e,s,n,a){const i=Yot(n)||"unknown parser error",o=Got(e);return{kind:"result",ts:s,text:Tm(`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(Jot,"createTranscriptParseErrorEntry");function yH(e){const{entries:s,line:n,ts:a,parseLine:i,reset:o,redactionOptions:l}=e;try{Qot(s,i(n,a).map(c=>Ust(c,l)))}catch(c){o?.(),Y1e(s,Jot(n,a,c,l))}}r(yH,"appendParsedTranscriptLine");function J1e(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:Tm(u.chunk,l)});continue}if(u.stream==="system"){s.push({kind:"system",ts:u.ts,text:Tm(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&&yH({entries:s,line:f,ts:u.ts,parseLine:i,reset:o,redactionOptions:l})}}return c}r(J1e,"foldTranscriptChunks");function X1e(e,s,n){const a=[],i={enabled:n?.censorUsernameInLogs??!1},{parseLine:o,reset:l}=kU(s),c=J1e({entries:a,chunks:e,from:0,stdoutBuffer:"",parseLine:o,reset:l,redactionOptions:i}).trim();return c&&yH({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(X1e,"buildTranscript");var Fne=[];function Xot(e,s){const n={enabled:s?.censorUsernameInLogs??!1},a=typeof e!="function"&&typeof e.createStdoutParser=="function";let i=kU(e),o=[],l="",c=Fne,d=[];const u=r(()=>{i=kU(e),o=[],l="",c=Fne},"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 X1e(f,e,s);const b=o.slice(),v=b.length-1;return v>=0&&(b[v]={...b[v]}),x&&yH({entries:b,line:x,ts:f.length>0?f[f.length-1].ts:new Date().toISOString(),parseLine:i.parseLine,reset:i.reset,redactionOptions:n}),b},"publish");return{update(f){return f===c||(h(f)||u(),l=J1e({entries:o,chunks:f,from:c.length,stdoutBuffer:l,parseLine:i.parseLine,reset:i.reset,redactionOptions:n}),c=f,d=p(f)),d}}}r(Xot,"createIncrementalTranscript");function Zot({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(b=>b.status!=="terminated"&&!u.has(b.id)),p=s?e.find(b=>b.id===s):null,f=p?.status==="terminated",x=!!(s&&!p);return(0,t.jsxs)(ur,{open:c,onOpenChange:d,children:[(0,t.jsx)(Nr,{asChild:!0,children:(0,t.jsx)("button",{type:"button",className:V("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)(cd,{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)(or,{agent:p,size:16,className:"h-3 w-3 shrink-0 text-muted-foreground"}),(0,t.jsx)("span",{className:V("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)(cd,{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)(rr,{className:"w-48 p-1",align:"start",children:[(0,t.jsx)("button",{type:"button",className:V("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)(or,{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(b=>(0,t.jsxs)("button",{type:"button",className:V("flex items-center gap-2 w-full min-w-0 px-2 py-1.5 text-xs rounded hover:bg-accent/50 overflow-hidden",b.id===s&&"bg-accent"),onClick:r(()=>{n(b.id),d(!1)},"onClick"),children:[(0,t.jsx)(or,{agent:b,size:16,className:"shrink-0 h-3 w-3 text-muted-foreground"}),(0,t.jsx)("span",{className:"min-w-0 truncate",children:b.name}),(0,t.jsx)("span",{className:"text-muted-foreground ml-auto shrink-0",children:cH[b.role]??b.role})]},b.id))]})]})}r(Zot,"ReportsToPicker");var elt="__secret_folder__:";function tlt(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(tlt,"statusBadge");function Z1e(e){return e.split("/").filter(s=>s.length>0)}r(Z1e,"splitSecretPath$1");function x3(e){return e.join("/")}r(x3,"pathKey$1");function FC(e){return e.length>0?`/${e.join("/")}`:"/"}r(FC,"pathLabel");function slt(e,s){return e.length<s.length?!1:s.every((n,a)=>e[a]===n)}r(slt,"pathStartsWith");function Bne(e){return`${elt}${x3(e)}`}r(Bne,"folderValue");function nlt(e,s,n){const a=s.length,i=new Map,o=[];for(const c of e){const d=Z1e(c.name);if(slt(d,s)){if(d.length>a+1){const u=d.slice(0,a+1),h=x3(u);if(!i.has(h)){const p=u[u.length-1]??"/",f=FC(u);i.set(h,{key:`folder-${h||"root"}`,value:Bne(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-${x3(s)}`,value:Bne(c),label:"Up one folder",title:FC(c),searchText:FC(c),kind:"back",folderPath:x3(c),pathHint:FC(c)})}return l.push(...i.values(),...o),{id:"browse-secrets",label:s.length>0?FC(s):"Browse secrets",options:l}}r(nlt,"buildFolderGroup");function jH({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(j=>j.id===e)??null,[s,e]),p=!!e&&!h,f=(0,m.useMemo)(()=>d?d.split("/"):[],[d]),x=(0,m.useMemo)(()=>s.some(j=>Z1e(j.name).length>1),[s]),b=(0,m.useMemo)(()=>{const j=[];p&&j.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 N=(n??[]).filter(w=>w.status==="active"&&w.id!==e);return N.length>0&&j.push({id:"recently-used",label:"Recently used",options:N.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"}))}),j.push({id:"all-secrets",label:N.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}))}),j},[p,n,e,s]),v=(0,m.useCallback)((j,N)=>{if(!x||Bze(j))return N;const w=nlt(s,f,e),k=N.filter(S=>S.id==="current-missing"||S.id==="recently-used");return w.options.length>0?[...k,w]:k},[f,x,e,s]);return(0,t.jsx)(Bg,{value:e||"",groups:b,onValueChange:r((j,N)=>{if(N.folderPath!==void 0)return u(N.folderPath),!1;u(""),i(j)},"onValueChange"),deriveGroups:v,disabled:a,disablePortal:c,placeholder:"Select secret…",searchPlaceholder:"Search secrets…",emptyMessage:"No matching secrets",triggerClassName:V("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(j=>{if(!j)return(0,t.jsx)("span",{className:"text-muted-foreground",children:"Select secret…"});if(j.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:j.label})]});const N=j.status&&j.status!=="active";return(0,t.jsxs)("span",{className:"flex w-full min-w-0 items-center gap-1.5",title:j.title,children:[(0,t.jsx)(Si,{className:V("size-3.5 shrink-0",N?"text-amber-600":"text-muted-foreground")}),(0,t.jsx)("span",{className:"min-w-0 flex-1 truncate",children:j.label}),N?(0,t.jsxs)("span",{className:"text-amber-600",children:["(",j.status,")"]}):null]})},"renderValue"),renderOption:r((j,{selected:N})=>{if(j.kind==="folder"||j.kind==="back"){const w=j.kind==="back"?PKe:ql;return(0,t.jsxs)("span",{className:"flex min-w-0 flex-1 items-center gap-1.5",title:j.title??j.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:V("truncate text-sm",N&&"font-medium"),children:j.label}),j.pathHint?(0,t.jsx)("span",{className:"truncate font-mono text-(length:--text-micro) text-muted-foreground",children:j.pathHint}):null]})]})}return(0,t.jsxs)("span",{className:V("flex min-w-0 flex-1 items-center gap-1.5",j.disabled&&"opacity-60"),title:j.title??j.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:V("min-w-0 truncate font-mono text-sm",N&&"font-medium"),children:j.label}),j.pathHint&&j.pathHint!==j.label?(0,t.jsx)("span",{className:"truncate font-mono text-(length:--text-micro) text-muted-foreground",children:j.pathHint}):null]}),tlt(j.status)]})},"renderOption"),createItem:o?{render:r(j=>(0,t.jsxs)("span",{className:"flex items-center gap-1.5 text-sm",children:[(0,t.jsx)(bn,{className:"size-3.5 shrink-0"}),j.trim()?(0,t.jsxs)("span",{children:["Create secret ",(0,t.jsxs)("span",{className:"font-mono",children:["“",j.trim(),"”"]}),"…"]}):(0,t.jsx)("span",{children:"Create new secret…"})]}),"render"),onSelect:r(j=>o(j),"onSelect")}:void 0})}r(jH,"SecretPicker");var rlt=/^[a-z][a-z0-9_]*$/,zne="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 e_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),[b,v]=(0,m.useState)(null),[j,N]=(0,m.useState)(!1),w=l.trim(),k=w?rlt.test(w)?a?.some(A=>A.toLowerCase()===w)?"A secret with this name already exists":null:"Use lowercase letters, digits and _":j?"Name is required":null,S=d.length===0&&j?"Value is required":null,C=!f&&w.length>0&&d.length>0&&!k;async function _(){if(N(!0),!!C){x(!0),v(null);try{await o(w,d)}catch(A){v(A instanceof Error?A.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)(fze,{className:"text-sm font-medium",children:e==="create"?"Create secret":"Store value as secret"}),e==="store"?(0,t.jsxs)(pze,{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:V(zne,k&&"border-destructive focus-visible:ring-destructive/40"),value:l,autoFocus:!0,spellCheck:!1,placeholder:"secret_name","aria-label":"Secret name","aria-invalid":k?!0:void 0,onChange:r(A=>c(A.target.value),"onChange"),onBlur:r(()=>N(!0),"onBlur"),onKeyDown:r(A=>{A.key==="Enter"&&(A.preventDefault(),_())},"onKeyDown")}),k?(0,t.jsx)("span",{className:"block text-(length:--text-micro) text-destructive",children:k}):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:V(zne,"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"?A=>u(A.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(A=>!A),"onClick"),children:h?(0,t.jsx)(Qm,{className:"h-3.5 w-3.5"}):(0,t.jsx)(Wd,{className:"h-3.5 w-3.5"})})]}),S?(0,t.jsx)("span",{className:"block text-(length:--text-micro) text-destructive",children:S}):null]}),b?(0,t.jsx)("p",{className:"text-(length:--text-micro) text-destructive",children:b}):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)(tt,{className:"h-3.5 w-3.5 animate-spin"}):null,R]})]})]})}r(e_e,"SecretPopoverForm");function t_e(e){return(0,t.jsx)(e_e,{mode:"create",...e})}r(t_e,"CreateSecretPopover");function alt(e){return(0,t.jsx)(e_e,{mode:"store",...e})}r(alt,"ConvertToSecretPopover");var ilt=/(api[-_]?key|access[-_]?token|auth(?:_?token)?|authorization|bearer|secret|passwd|password|credential|jwt|private[-_]?key|cookie|connectionstring)/i,olt=[/^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 llt(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(llt,"looksHighEntropy");function clt(e,s){return s?ilt.test(e)||olt.some(n=>n.test(s))?!0:llt(s):!1}r(clt,"isSensitiveEnv");var qne=0;function dlt(){return qne+=1,`env-row-${qne}`}r(dlt,"nextRowId");function Zx(e="text"){return{id:dlt(),name:"",source:e,textValue:"",secretId:"",userSecretKey:"",required:!0,version:"latest"}}r(Zx,"emptyRow");function ult(e){return typeof e=="object"&&e!==null&&"type"in e&&e.type==="secret_ref"}r(ult,"isSecretRef");function mlt(e){return typeof e=="object"&&e!==null&&"type"in e&&e.type==="plain"}r(mlt,"isPlainObj");function hlt(e){return typeof e=="object"&&e!==null&&"type"in e&&e.type==="user_secret_ref"}r(hlt,"isUserSecretRef");function rF(e){return!e||typeof e!="object"?[]:Object.entries(e).map(([s,n])=>{if(typeof n=="string")return{...Zx(),name:s,textValue:n};if(ult(n)){const a=typeof n.version=="number"?n.version:"latest";return{...Zx(),name:s,source:"secret",secretId:typeof n.secretId=="string"?n.secretId:"",version:a}}if(hlt(n)){const a=typeof n.version=="number"?n.version:"latest";return{...Zx(),name:s,source:"user_secret",userSecretKey:typeof n.key=="string"?n.key:"",required:n.required!==!1,version:a}}return mlt(n)?{...Zx(),name:s,source:"text",textValue:typeof n.value=="string"?n.value:""}:{...Zx(),name:s}})}r(rF,"rowsFromValue");function g3(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(g3,"valueFromRows");var Une="CLAUDE_CODE_OAUTH_TOKEN";function kN(){return g3([{...Zx("user_secret"),name:"CLAUDE_CODE_OAUTH_TOKEN",userSecretKey:"CLAUDE_CODE_OAUTH_TOKEN",required:!0,version:"latest"}])??{}}r(kN,"buildFixedClaudeOAuthBinding");var plt=/^[A-Za-z_][A-Za-z0-9_]*$/;function flt(e,s,n){const a=e.trim();if(!a)return null;if(!plt.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(flt,"validateName");function xlt(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(xlt,"computeDuplicateNames");function glt(e,s){return s===e.source?{kind:"noop"}:s==="secret"?e.textValue.trim()?{kind:"open-store",name:LP(e.name)||"secret",value:e.textValue}:{kind:"to-secret"}:{kind:"to-text",undoFrom:e.secretId?{...e}:null}}r(glt,"planSourceSwitch");function s_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(s_e,"computeRowHealth");function n_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(n_e,"computeUserSecretRowHealth");function LP(e){return e.trim().toLowerCase().replace(/[^a-z0-9_]+/g,"_").replace(/^_+|_+$/g,"").slice(0,64)}r(LP,"secretNameFromKey");function x_(e){return e.trim().toUpperCase().replace(/[^A-Z0-9_]+/g,"_").replace(/^_+|_+$/g,"").slice(0,64)}r(x_,"envKeyFromSecretName");var blt="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",Kne="min-w-0 flex-1 bg-transparent px-2 py-1.5 text-sm font-mono outline-none placeholder:text-muted-foreground/40";function vlt({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:b,onToast:v,focusRequest:j,onFocusConsumed:N}){const w=(0,m.useRef)(null),k=(0,m.useRef)(null),S=(0,m.useRef)(null),[C,_]=(0,m.useState)(null),[R,A]=(0,m.useState)(!1),[T,E]=(0,m.useState)(null),L=s_e(e,n)??n_e(e,a),O=e.source==="secret"?n.find(X=>X.id===e.secretId)??null:null,P=(a?.length??0)>0,U=e.source==="text"&&!e.sensitiveDismissed&&clt(e.name,e.textValue);(0,m.useEffect)(()=>{j&&(j==="name"?w.current?.focus():e.source==="text"?k.current?.focus():e.source==="secret"?S.current?.querySelector("[role=combobox]")?.focus():S.current?.querySelector("select,input")?.focus(),N())},[j,N,e.source]),(0,m.useEffect)(()=>{if(!T)return;const X=window.setTimeout(()=>E(null),5e3);return()=>window.clearTimeout(X)},[T]);function M(X){if(X==="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 ne=glt(e,X);switch(ne.kind){case"noop":return;case"open-store":{const{name:oe,value:G}=ne;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":ne.undoFrom&&E(ne.undoFrom),u({source:"text",secretId:"",userSecretKey:"",required:!0,version:"latest"}),window.setTimeout(()=>k.current?.focus(),0);return}}r(M,"switchSource");async function B(X,ne){const oe=await b(X,ne);u({source:"secret",secretId:oe.id,userSecretKey:"",required:!0,version:"latest",textValue:""}),v(`Secret ${oe.name} created`),_(null)}r(B,"submitSecretPopover");function q(){const X=LP(e.name)||"secret",{textValue:ne}=e;window.setTimeout(()=>_({mode:"store",name:X,value:ne}),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`,W=`${e.id}-health`,Q=d.name||d.value,re=O?Math.max(0,O.latestVersion):0,J=e.version==="latest"?"latest":`v${e.version}`,ie=e.version!=="latest";return(0,t.jsxs)("div",{className:V("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",Q&&"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:V(blt,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(X=>u({name:X.target.value}),"onChange"),onBlur:p,onPaste:r(X=>{e.name||f(X.clipboardData.getData("text"))&&X.preventDefault()},"onPaste"),onKeyDown:r(X=>{X.key==="Enter"&&(X.preventDefault(),e.source==="text"?k.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)(ur,{open:C!==null,onOpenChange:r(X=>{X||_(null)},"onOpenChange"),children:[(0,t.jsx)(Hq,{asChild:!0,children:(0,t.jsxs)("div",{ref:S,className:V("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)(Zr,{children:[(0,t.jsxs)(Bn,{children:[(0,t.jsx)(Fn,{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)(x8e,{className:"size-3.5"}):e.source==="secret"?(0,t.jsx)(Si,{className:"size-3.5"}):(0,t.jsx)(Gm,{className:"size-3.5"}),(0,t.jsx)(nn,{className:"size-3 opacity-60"})]})})}),(0,t.jsx)(On,{side:"top",children:z})]}),(0,t.jsxs)(ea,{align:"start",className:"w-56",children:[(0,t.jsxs)(ds,{className:"flex-col items-start gap-0.5",onSelect:r(()=>M("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)(ds,{className:"flex-col items-start gap-0.5",onSelect:r(()=>M("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)(ds,{className:"flex-col items-start gap-0.5",onSelect:r(()=>M("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:k,className:Kne,placeholder:"value",value:e.textValue,type:U?"password":"text",spellCheck:!1,disabled:o,"aria-label":"Variable value",onChange:r(X=>u({textValue:X.target.value}),"onChange"),onKeyDown:r(X=>{X.key==="Enter"&&s&&(X.preventDefault(),x())},"onKeyDown")}),U?(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)(jc,{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)(zn,{className:"size-3"})})]}):null]}):e.source==="secret"?(0,t.jsxs)("div",{className:"relative min-w-0 flex-1",children:[(0,t.jsx)(jH,{secretId:e.secretId,secrets:n,recentlyUsedSecrets:i,disabled:o,onSelect:r(X=>u({secretId:X,version:"latest"}),"onSelect"),onCreateNew:r(X=>_({mode:"create",name:LP(X)||X.trim(),value:""}),"onCreateNew"),triggerClassName:V("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)(ur,{open:R,onOpenChange:A,children:[(0,t.jsx)(Hq,{asChild:!0,children:(0,t.jsx)("button",{type:"button",disabled:o,onClick:r(X=>{X.preventDefault(),X.stopPropagation(),A(ne=>!ne)},"onClick"),"aria-label":"Version",className:V("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:J})}),(0,t.jsxs)(rr,{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"}),A(!1)},"onClick"),className:V("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:re},(X,ne)=>re-ne).filter(X=>X>0).map(X=>(0,t.jsxs)("button",{type:"button",role:"radio","aria-checked":e.version===X,onClick:r(()=>{u({version:X}),A(!1)},"onClick"),className:V("flex w-full items-center rounded px-2 py-1.5 text-sm hover:bg-accent",e.version===X&&"font-medium text-amber-700 dark:text-amber-400"),children:["v",X]},X))]})]}):null]}):(0,t.jsxs)("div",{className:"grid min-w-0 flex-1 grid-cols-(--gtc-13)",children:[P?(0,t.jsxs)("select",{"aria-label":"User secret",value:e.userSecretKey,disabled:o,onChange:r(X=>{const ne=X.target.value,oe=a?.find(G=>G.key===ne);u({userSecretKey:ne,...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(X=>X.key===e.userSecretKey)?(0,t.jsxs)("option",{value:e.userSecretKey,children:["Unknown (",e.userSecretKey,")"]}):null,(a??[]).map(X=>(0,t.jsxs)("option",{value:X.key,children:[X.name,X.status!=="active"?` (${X.status})`:""]},X.id))]}):(0,t.jsx)("input",{className:Kne,placeholder:"user-secret key",value:e.userSecretKey,spellCheck:!1,disabled:o,"aria-label":"User secret key",onChange:r(X=>u({userSecretKey:X.target.value}),"onChange")}),(0,t.jsxs)("select",{"aria-label":"Requirement",value:e.required?"required":"optional",disabled:o,onChange:r(X=>u({required:X.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)(rr,{align:"start",className:"w-auto p-3",onInteractOutside:r(X=>{const ne=X.detail.originalEvent.target;ne&&S.current?.contains(ne)&&X.preventDefault()},"onInteractOutside"),children:C?.mode==="store"?(0,t.jsx)(alt,{initialName:C.name,initialValue:C.value,existingSecretNames:n.map(X=>X.name),onCancel:r(()=>_(null),"onCancel"),onSubmit:B}):C?.mode==="create"?(0,t.jsx)(t_e,{initialName:C.name,initialValue:C.value,existingSecretNames:n.map(X=>X.name),onCancel:r(()=>_(null),"onCancel"),onSubmit:B}):null})]}),L?(0,t.jsx)("p",{id:W,role:"status",className:V("mt-0.5 text-(length:--text-micro)",L.level==="error"?"text-destructive":"text-amber-600 dark:text-amber-400"),children:L.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:V("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"&&!U&&(e.name.trim()||e.textValue)?(0,t.jsxs)(Zr,{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)(ea,{align:"end",children:(0,t.jsx)(ds,{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)(zn,{className:"size-4"})})]})]})}r(vlt,"EnvironmentVariableRow");var ylt=/^\s*(?:export\s+)?([A-Za-z_][A-Za-z0-9_]*)\s*=(.*)$/;function jlt(e){const s=e.indexOf(" #");return s>=0?e.slice(0,s):e}r(jlt,"stripInlineComment");function wlt(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 jlt(s).trim()}r(wlt,"unquote");function Nlt(e){const s=[];for(const n of e.split(/\r?\n/)){const a=n.trim();if(!a||a.startsWith("#"))continue;const i=ylt.exec(a);if(!i)continue;const o=i[1],l=wlt(i[2]);s.push({key:o,value:l})}return s}r(Nlt,"parseDotenv");var klt=["PAPERCLIP_"],Slt="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 SU(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(SU,"normalizedEnvEntries");function BC(e){return JSON.stringify(SU(e))}r(BC,"normalizedEnvKey");var aF=3;function iF(e){const s=e.slice(0,aF).join(", ");return e.length>aF?`${s} +${e.length-aF} more`:s}r(iF,"formatChangedNames");function Wne(e){return e.map(s=>({...s}))}r(Wne,"cloneRows");function Clt(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(Clt,"rowDirtyFields");var Jy=(0,m.forwardRef)(r(function({value:s,onChange:n,secrets:a,userSecretDefinitions:i,onCreateSecret:o,recentlyUsedSecrets:l,disabled:c,reservedPrefixes:d=klt,footerHint:u,onDirtyChange:h,hideDraftActions:p=!1},f){const x=Td(),b=(0,m.useRef)(null),[v,j]=(0,m.useState)(()=>rF(s)),N=(0,m.useRef)(v),[w,k]=(0,m.useState)(()=>Wne(v)),S=(0,m.useMemo)(()=>BC(s),[]),C=(0,m.useRef)(S),_=(0,m.useRef)(S),R=(0,m.useRef)(null),[A,T]=(0,m.useState)(S),[E,L]=(0,m.useState)(()=>new Set(rF(s).map(le=>le.name.trim()).filter(Boolean))),[O,P]=(0,m.useState)(null);(0,m.useEffect)(()=>{N.current=v},[v]);function U(le,fe=N.current){C.current=le,T(le),k(Wne(fe))}r(U,"markCommitted");function M(le){L(fe=>{const de=new Set(fe);for(const Ee of le){const Me=Ee.name.trim();Me&&de.add(Me)}return de})}r(M,"touchCommittedNames");function B(le){const fe=rF(le);return j(fe),M(fe),fe}r(B,"adoptExternalValue"),(0,m.useEffect)(()=>{const le=BC(s);if(le===_.current)return;_.current=le;const fe=BC(g3(N.current)),de=fe!==C.current,Ee=R.current===le;if(Ee&&(R.current=null),!de){U(le,B(s));return}(Ee||fe===le)&&(M(N.current),U(le))},[s]);const q=(0,m.useMemo)(()=>g3(v),[v]),z=(0,m.useMemo)(()=>BC(q),[q]),K=z!==A;(0,m.useEffect)(()=>{h?.(!c&&K)},[c,K,h]);const W=(0,m.useMemo)(()=>{const le=new Map(SU(g3(w)).map(([Me,ve])=>[Me,JSON.stringify(ve)])),fe=new Map(SU(q).map(([Me,ve])=>[Me,JSON.stringify(ve)])),de=[],Ee=[];for(const[Me,ve]of fe)le.has(Me)?le.get(Me)!==ve&&Ee.push(Me):de.push(Me);return{added:de,changed:Ee,removed:[...le.keys()].filter(Me=>!fe.has(Me))}},[w,q]),Q=(0,m.useMemo)(()=>{const le=[];return W.added.length>0&&le.push(`New: ${iF(W.added)}`),W.changed.length>0&&le.push(`Edited: ${iF(W.changed)}`),W.removed.length>0&&le.push(`Removed: ${iF(W.removed)}`),le.join(" · ")},[W]);(0,m.useEffect)(()=>{if(c||!K)return;function le(fe){fe.preventDefault(),fe.returnValue=""}return r(le,"handleBeforeUnload"),window.addEventListener("beforeunload",le),()=>window.removeEventListener("beforeunload",le)},[c,K]);const re=(0,m.useCallback)(()=>c||!K?null:(R.current=z,(0,_p.flushSync)(()=>{n(q)}),q??{}),[c,q,z,K,n]);(0,m.useImperativeHandle)(f,()=>({flushPendingDraft:re}),[re]),(0,m.useEffect)(()=>{const le=b.current?.closest("form");if(!le)return;function fe(){re()}return r(fe,"handleSubmit"),le.addEventListener("submit",fe,!0),()=>le.removeEventListener("submit",fe,!0)},[re]),(0,m.useEffect)(()=>{const le=b.current;if(!le)return;const fe=le;function de(Ee){const Me=Ee.target;if(!(Me instanceof Element)||fe.contains(Me))return;const ve=Me.closest("button");if(!ve||ve.disabled)return;const Ie=`${ve.getAttribute("aria-label")??""} ${ve.textContent??""}`;(ve.type==="submit"||/\b(save|create|update|test|import)\b/i.test(Ie))&&re()}return r(de,"handleDocumentClick"),document.addEventListener("click",de,!0),()=>document.removeEventListener("click",de,!0)},[re]);function J(le){j(le)}r(J,"updateDraft");function ie(le,fe){J(v.map(de=>de.id===le?{...de,...fe}:de))}r(ie,"patchRow");function X(le){J(v.filter(fe=>fe.id!==le))}r(X,"removeRow");function ne(){const le=Zx();j([...v,le]),P({rowId:le.id,field:"name"})}r(ne,"addRow");function oe(le){const fe=v.find(de=>de.id===le)?.name.trim();fe&&L(de=>{if(de.has(fe))return de;const Ee=new Set(de);return Ee.add(fe),Ee})}r(oe,"markTouched");function G(le,fe){const de=Nlt(le);if(de.length===0)return!1;const Ee=v.filter(Me=>Me.id!==fe).map(Me=>({...Me}));for(const{key:Me,value:ve}of de){const Ie=Ee.find(Ze=>Ze.name.trim()===Me);Ie?(Ie.name=Me,Ie.source="text",Ie.textValue=ve,Ie.secretId="",Ie.sensitiveDismissed=!1,Ie.userSecretKey="",Ie.required=!0):Ee.push({...Zx(),name:Me,textValue:ve})}return J(Ee),x?.pushToast({title:`Imported ${de.length} variable${de.length===1?"":"s"}`,tone:"success"}),!0}r(G,"bulkImport");function Z(le){const fe=v.map(Me=>({...Me})),de=fe[fe.length-1];let Ee;de&&!de.name&&!de.textValue&&!de.secretId&&!de.userSecretKey?Ee=de:(Ee=Zx(),fe.push(Ee)),Ee.source="secret",Ee.secretId=le.id,Ee.version="latest",Ee.name||(Ee.name=x_(le.name)),J(fe)}r(Z,"bindRecentSecret");function Y(){K&&(R.current=z,n(q))}r(Y,"saveDraft");function ae(){R.current=null,_.current=BC(s);const le=B(s);U(_.current,le)}r(ae,"revertDraft");const se=(0,m.useMemo)(()=>xlt(v),[v]),ce=(0,m.useMemo)(()=>v.reduce((le,fe)=>s_e(fe,a)||n_e(fe,i)?le+1:le,0),[v,a,i]),pe=(0,m.useMemo)(()=>{const le=new Set(v.filter(fe=>fe.source==="secret"&&fe.secretId).map(fe=>fe.secretId));return(l??[]).filter(fe=>fe.status==="active"&&!le.has(fe.id)).slice(0,8)},[l,v]),we=v.length>0,Se=u===void 0?Slt:u,Te=(0,m.useMemo)(()=>new Map(w.map(le=>[le.id,le])),[w]);return(0,t.jsx)(Wc,{children:(0,t.jsxs)("div",{ref:b,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,we?(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((le,fe)=>{const de=flt(le.name,se,d),Ee=E.has(le.name.trim());return(0,t.jsx)(vlt,{row:le,isLast:fe===v.length-1,secrets:a,userSecretDefinitions:i,recentlyUsedSecrets:l,disabled:c,nameIssue:de,showNameIssue:Ee,dirtyFields:Clt(le,Te.get(le.id)),onPatch:r(Me=>ie(le.id,Me),"onPatch"),onRemove:r(()=>X(le.id),"onRemove"),onNameBlur:r(()=>oe(le.id),"onNameBlur"),onNamePaste:r(Me=>G(Me,le.id),"onNamePaste"),onEnterInValueLast:ne,onCreateSecret:o,onToast:r(Me=>x?.pushToast({title:Me,tone:"success"}),"onToast"),focusRequest:O?.rowId===le.id?O.field:null,onFocusConsumed:r(()=>P(null),"onFocusConsumed")},le.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:ne,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(le=>(0,t.jsxs)("button",{type:"button",onClick:r(()=>Z(le),"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 ${le.name}`,children:["+ ",le.name]},le.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"})]}),Q?(0,t.jsx)("p",{className:"min-w-0 truncate pl-4 text-xs text-amber-950/80 dark:text-amber-100/80",title:Q,children:Q}):null]}),(0,t.jsxs)("div",{className:"flex items-center gap-2",children:[(0,t.jsxs)("button",{type:"button",onClick:ae,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)(Ii,{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)(qf,{className:"size-4"}),"Save"]})]})]}):null,Se?(0,t.jsx)("p",{className:"text-(length:--text-micro) text-muted-foreground/70",children:Se}):null,v.some(le=>le.source==="user_secret"&&le.userSecretKey)?(0,t.jsxs)("p",{className:"inline-flex items-start gap-1 text-(length:--text-micro) text-muted-foreground/70",children:[(0,t.jsx)(Gm,{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")),_lt="env.",r2="access.",CU=/^[A-Za-z_][A-Za-z0-9_]*$/;function r_e(e){return e?e.startsWith("access.")?"api":e.startsWith("env.")?"env":"config":"config"}r(r_e,"deliveryModeForConfigPath");function a_e(e){switch(e){case"env":return"Env var";case"api":return"API access";default:return"Config"}}r(a_e,"deliveryModeLabel");function Ilt(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(Ilt,"deliveryModeDescription");function i_e(e){return e?e.startsWith("access.")?e.slice(7):e.startsWith("env.")?e.slice(4):e:""}r(i_e,"aliasFromConfigPath");function Alt(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(Alt,"consumerTypeLabel");var Tlt={numeric:!0,sensitivity:"base"};function R1(e){return e.kind==="company"?e.secret.name:e.definition.name}r(R1,"getSecretPathRowName");function Kk(e){return e.split("/").filter(s=>s.length>0)}r(Kk,"splitSecretPath");function oF(e){return Kk(e).join("/")}r(oF,"normalizeSecretPath");function Vne(e,s){return s.every((n,a)=>e[a]===n)}r(Vne,"startsWithSegments");function Hne(e,s){return e.localeCompare(s,void 0,Tlt)}r(Hne,"compareNames");function Rlt(e,s){const n=Kk(s),a=e.map(c=>({row:c,name:R1(c),segments:Kk(R1(c))})),i=new Set,o=[];for(const c of a){if(!Vne(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(!Vne(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)=>Hne(c.name,d.name)),o.sort((c,d)=>Hne(R1(c),R1(d))),{folders:l,secrets:o}}r(Rlt,"buildSecretPathListing");function Elt(e){const s=Kk(e);return s.map((n,a)=>({name:n,path:s.slice(0,a+1).join("/")}))}r(Elt,"buildSecretPathBreadcrumbs");function Plt(e){return e.trim()?e.includes("/")?"Folder name cannot contain slashes.":null:"Folder name is required."}r(Plt,"validateSecretFolderSegment");function kI({name:e,basePath:s="",className:n,leafClassName:a}){const i=Kk(e),o=Kk(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:V("min-w-0 truncate",n),children:[u?(0,t.jsxs)("span",{className:"text-muted-foreground",children:[u,"/"]}):null,(0,t.jsx)("span",{className:V("font-medium text-foreground",a),children:d})]})}r(kI,"SecretPathName");function Mlt(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(Mlt,"fingerprintLabel");function o_e({fingerprint:e,length:s,className:n}){const{pushToast:a}=Qr(),i=Mlt(e,s);if(!e)return(0,t.jsxs)("span",{className:V("inline-flex items-center gap-1 font-mono",n),children:[(0,t.jsx)(l6,{className:"size-3 shrink-0"}),i]});const o=`sha256:${e}`;return(0,t.jsxs)("button",{type:"button",onClick:r(()=>{Ia(o).then(()=>a({title:"Fingerprint copied",tone:"success"})).catch(()=>a({title:"Couldn’t copy fingerprint",tone:"error"}))},"onClick"),title:`Copy full digest — ${o}`,className:V("inline-flex items-center gap-1 font-mono hover:text-foreground",n),children:[(0,t.jsx)(l6,{className:"size-3 shrink-0"}),i,(0,t.jsx)(wr,{className:"size-3 shrink-0 opacity-60"})]})}r(o_e,"FingerprintChip");function wH({justification:e,className:s}){return(0,t.jsxs)("div",{className:V("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(wH,"ProposalJustification");function SI({agent:e,className:s}){return(0,t.jsxs)("span",{className:V("inline-flex min-w-0 items-center gap-1",s),children:[(0,t.jsx)(or,{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(SI,"AgentRefChip");function NH({configPath:e}){const s=r_e(e),n=s==="env",a=s==="api";return(0,t.jsxs)(ot,{variant:"outline",className:V("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)(gwe,{className:"size-3"}):a?(0,t.jsx)(z4,{className:"size-3"}):null,a_e(s)]})}r(NH,"DeliveryBadge$1");function kH({className:e}){return(0,t.jsxs)(ot,{variant:"outline",className:V("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)(jc,{className:"size-3"})," Proposed"]})}r(kH,"ProposedBadge");function ID(e){return i_e(e.configPath)}r(ID,"bindingEnvKey");function SH(e){return e.secretProposalId?{name:e.secretProposalName??"proposed secret",pending:!0}:{name:e.secretName??"secret",pending:!1}}r(SH,"bindingSecretLabel");function Qne(e){return e instanceof mn?e.message||`Request failed: ${e.status}`:e instanceof Error?e.message:"Something went wrong. Try again."}r(Qne,"readableError");function l_e(e,s=[]){const n=Nt(),{pushToast:a}=Qr(),[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=ye({mutationFn:r(w=>{const{proposal:k}=w;if(k.kind==="secret"){const S=w.folder.trim()?`${w.folder.trim().replace(/\/+$/,"")}/${w.leaf.trim()}`:w.leaf.trim();return Rr.approveProposal(e,k.id,{overrides:{name:S,description:w.description.trim()||null,providerConfigId:w.providerConfigId||null}})}return Rr.approveProposal(e,k.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"} · ${ID(w)||"binding"}`,tone:"success"}),o(null),p(null),f()},"onSuccess"),onError:r(w=>p(Qne(w)),"onError")}),b=ye({mutationFn:r(({proposal:w,reason:k})=>Rr.rejectProposal(e,w.id,{reason:k.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(Qne(w)),"onError")}),v=(0,m.useCallback)(w=>{p(null);const k=(w.proposedName??"").split("/"),S=k.pop()??"";o({proposal:w,folder:k.join("/"),leaf:S,description:w.proposedDescription??"",providerConfigId:s.find(C=>C.provider==="local_encrypted"&&C.isDefault)?.id??"",cascade:!!w.secretProposalId})},[s]),j=(0,m.useCallback)(w=>{p(null),u(""),c(w)},[]),N=(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)(Dlt,{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)($lt,{proposal:l,reason:d,error:h,pending:b.isPending,onReasonChange:u,onCancel:r(()=>{c(null),u(""),p(null)},"onCancel"),onConfirm:r(()=>l&&b.mutate({proposal:l,reason:d}),"onConfirm")})]});return{requestApprove:v,requestReject:j,isBusy:x.isPending||b.isPending,dialogs:N}}r(l_e,"useProposalReview");function Dlt({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)(zs,{open:!!e,onOpenChange:r(p=>!p&&o(),"onOpenChange"),children:(0,t.jsx)(Ws,{className:"sm:max-w-lg",children:e?(0,t.jsxs)(t.Fragment,{children:[(0,t.jsxs)(on,{children:[(0,t.jsx)(Vs,{children:c?"Approve & create secret":"Approve binding"}),(0,t.jsx)(hn,{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)(SI,{agent:e.proposal.proposedBy,className:"font-medium text-foreground"})]}),(0,t.jsx)(wH,{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)(ut,{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)(ut,{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)(kI,{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)(ut,{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)(Llt,{draft:e,onChange:i}),s?(0,t.jsx)("p",{className:"text-xs text-destructive",role:"alert",children:s}):null,(0,t.jsxs)(dr,{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(Dlt,"ApproveDialog");function Llt({draft:e,onChange:s}){const{proposal:n}=e,a=SH(n),i=ID(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)(SI,{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)(NH,{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)(kH,{}):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)(Za,{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(Llt,"BindingApproveBody");function $lt({proposal:e,reason:s,error:n,pending:a,onReasonChange:i,onCancel:o,onConfirm:l}){const c=s.trim().length>0;return(0,t.jsx)(zs,{open:!!e,onOpenChange:r(d=>!d&&o(),"onOpenChange"),children:(0,t.jsx)(Ws,{className:"sm:max-w-md",children:e?(0,t.jsxs)(t.Fragment,{children:[(0,t.jsxs)(on,{children:[(0,t.jsx)(Vs,{children:"Reject proposal"}),(0,t.jsxs)(hn,{children:["The reason is sent back to"," ",(0,t.jsx)(SI,{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)(Qn,{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)(dr,{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($lt,"RejectDialog");function c_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)(Wc,{children:(0,t.jsxs)(Bn,{children:[(0,t.jsx)(Fn,{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(c_e,"ProposalActions");function d_e(e){return typeof e!="object"||e===null||Array.isArray(e)?null:e}r(d_e,"asRecord$16");function u_e(e){const s=d_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(u_e,"readSecretRef");function Olt(e){const s=d_e(e?.env);if(!s)return[];const n=[];for(const[a,i]of Object.entries(s)){const o=u_e(i);o&&n.push({name:a,...o})}return n}r(Olt,"parseEnvSecretRefs");function Flt(e){if(!e)return[];const s=[];for(const[n,a]of Object.entries(e)){if(!n.startsWith("access."))continue;const i=u_e(a);i&&s.push({name:n.slice(r2.length),...i})}return s}r(Flt,"parseAccessGrants");function Blt(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(Blt,"summarizeAgentBindings");var Gne=0;function m_e(){return Gne+=1,`access-row-${Gne}`}r(m_e,"nextAccessRowId");function lF(e){return e.map(s=>({id:m_e(),alias:s.name,secretId:s.secretId,version:s.version}))}r(lF,"entriesToRows");function Yne(e){const s={};for(const n of e){const a=n.alias.trim();!a||!CU.test(a)||!n.secretId||(s[a]={type:"secret_ref",secretId:n.secretId,version:n.version})}return s}r(Yne,"rowsToAccessMap");function Jne(e){return JSON.stringify(Object.keys(e).sort().map(s=>{const n=e[s];return[s,n.secretId,n.version??"latest"]}))}r(Jne,"normalizeAccessMapKey");function Xne({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)(gwe,{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)(z4,{className:"size-3"})," API access"]})}r(Xne,"DeliveryBadge");function zlt({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)(()=>Olt(e),[e]),h=(0,m.useMemo)(()=>Flt(e),[e]),p=(0,m.useMemo)(()=>Blt(u,h),[u,h]),f=(0,m.useMemo)(()=>Yne(lF(h)),[h]),x=(0,m.useMemo)(()=>Jne(f),[f]),[b,v]=(0,m.useState)(()=>lF(h)),[j,N]=(0,m.useState)(null),w=(0,m.useRef)(new Map),k=(0,m.useRef)(x),S=(0,m.useRef)(x);(0,m.useEffect)(()=>{x!==S.current&&(S.current=x,x!==k.current&&v(lF(h)))},[x,h]);const C=r(O=>s.find(P=>P.id===O)?.name??`${O.slice(0,8)}…`,"secretName");function _(O){v(O);const P=Yne(O);k.current=Jne(P),n(P)}r(_,"emit");function R(O,P){_(b.map(U=>U.id===O?{...U,...P}:U))}r(R,"patchRow");function A(O){_(b.filter(P=>P.id!==O))}r(A,"removeRow");function T(){v(O=>[...O,{id:m_e(),alias:"",secretId:"",version:"latest"}])}r(T,"addRow");const E=(0,m.useMemo)(()=>{const O=new Map;for(const P of b){const U=P.alias.trim();U&&O.set(U,(O.get(U)??0)+1)}return O},[b]),L=p.length>0;return(0,t.jsxs)("div",{className:"space-y-3",children:[L?(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)(Xne,{mode:"env"}):null,O.apiAliases.length>0?(0,t.jsx)(Xne,{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(P=>`${_lt}${P}`),...O.apiAliases.map(P=>`${r2}${P}`)].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 P=SH(O),U=ID(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)(NH,{configPath:O.configPath}),(0,t.jsx)("code",{className:"font-mono",children:U||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:P.name}),P.pending?(0,t.jsx)(kH,{}):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)(c_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)"}),b.length>0?(0,t.jsx)("div",{className:"space-y-2",children:b.map(O=>{const P=O.alias.trim(),U=!!P&&!CU.test(P),M=!!P&&(E.get(P)??0)>1,B=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)(ut,{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&&!CU.test(z)){const K=x_(z);K&&K!==z&&R(O.id,{alias:K})}},"onBlur"),placeholder:"ALIAS","aria-label":"Access alias",disabled:i,className:V("h-9 font-mono text-sm",(U||M)&&"border-destructive text-destructive")})}),(0,t.jsxs)("div",{className:"flex min-w-0 items-start gap-1.5",children:[(0,t.jsxs)(ur,{open:j?.rowId===O.id,onOpenChange:r(q=>{!q&&j?.rowId===O.id&&N(null)},"onOpenChange"),children:[(0,t.jsx)(Hq,{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)(jH,{secretId:O.secretId,secrets:s,onSelect:r(q=>R(O.id,{secretId:q,version:"latest",alias:!O.alias.trim()&&q?x_(C(q)):O.alias}),"onSelect"),onCreateNew:a?q=>{window.setTimeout(()=>{N({rowId:O.id,name:LP(q)||q.trim()})},0)}:void 0,disabled:i,triggerClassName:"h-9 min-h-9"})})}),(0,t.jsx)(rr,{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:j?.rowId===O.id&&a?(0,t.jsx)(t_e,{initialName:j.name,initialValue:"",existingSecretNames:s.map(q=>q.name),onCancel:r(()=>N(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()||x_(K.name)}),N(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||!B,"aria-label":"Version",children:[(0,t.jsx)("option",{value:"latest",children:"latest"}),B?Array.from({length:Math.max(0,B.latestVersion)},(q,z)=>{const K=B.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(()=>A(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)(da,{className:"size-3.5"})})]}),U?(0,t.jsx)("p",{className:"pl-0.5 text-(length:--text-micro) text-destructive",children:"Invalid alias — use letters, digits and _"}):M?(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:[Ilt("api")," The agent reads them by alias through ",(0,t.jsx)("code",{children:"GET /agents/me/secrets"}),"."]})]})}r(zlt,"AgentSecretAccessEditor");function qlt(e){if(typeof e!="string")return null;const s=e.trim();return s.length>0?s:null}r(qlt,"asNonEmptyString$3");function Ult(e){return qlt(e)!==null}r(Ult,"hasLegacyWorkingDirectory");function Klt(e){return e.isCreate?!1:Ult(e.adapterConfig?.cwd)}r(Klt,"shouldShowLegacyWorkingDirectoryField");var h_e=new Set;function Wlt(e){return h_e.has(e)}r(Wlt,"isAdapterTypeHidden");function Vlt(e){h_e=new Set(e)}r(Vlt,"setDisabledAdapterTypes");function Hlt(e){return!Um(e).hideFromVisualSelection}r(Hlt,"isVisualAdapterChoice");function p_e(e,s=vH()){const n=e??ax;return s.map(a=>({value:a.type,label:n(a.type),comingSoon:!!Um(a.type).comingSoon,hidden:Wlt(a.type),experimental:!!Um(a.type).experimental}))}r(p_e,"listAdapterOptions");function f_e(e={}){const s=e.enabled??!0,{data:n}=te({queryKey:D.adapters.all,queryFn:r(()=>Sh.list(),"queryFn"),enabled:s,staleTime:3e5});return n&&Hot(n.filter(a=>a.source==="external").map(a=>({type:a.type,label:a.label,disabled:a.disabled,overrideDisabled:a.overridePaused}))),(0,m.useEffect)(()=>{n&&Vlt(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(f_e,"useDisabledAdaptersSync");function Qlt(e={}){const s=e.enabled??!0,{data:n}=te({queryKey:D.adapters.all,queryFn:r(()=>Sh.list(),"queryFn"),enabled:s,staleTime:3e5});return n!==void 0}r(Qlt,"useAdapterRegistryLoaded");function $P(e){return Object.fromEntries(Object.entries(e).filter(([,s])=>s!==void 0))}r($P,"omitUndefinedEntries");function $T(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=$P(s.adapterType!==void 0?{...Object.fromEntries(SBe.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=$P({...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($T,"buildAgentUpdatePatch");var Glt="kubernetes";function Ylt(e){return e.driver!=="sandbox"?!1:e.config?.provider===Glt}r(Ylt,"isKubernetesSandboxEnvironment");function CH(e,s){return e!=="kubernetes"?{forced:!1,kubernetesEnvironment:null}:{forced:!0,kubernetesEnvironment:s.find(n=>Ylt(n))??null}}r(CH,"resolveForcedKubernetesEnvironment");var cF={identity:{},adapterConfig:{},heartbeat:{},debug:{},runtime:{}},zC={};function Jlt(e){return e==="claude_local"||e==="codex_local"||e==="paperclip_runner"||e==="opencode_local"}r(Jlt,"supportsAdapterModelRefresh");function Xlt(e,s){return o1e(e,s).model}r(Xlt,"resolvePaperclipRunnerTransitionModel");function Zne(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(Zne,"isOverlayDirty");function _U(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)=>_U(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&&_U(o,a[i]))}return!1}r(_U,"overlayValuesEqual");function Zlt(e,s){const n=r((a,i)=>Object.fromEntries(Object.entries(a).filter(([o,l])=>!(o in i)||!_U(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(Zlt,"subtractPersistedOverlay");var hh="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 ect(e){return e.split(",").map(s=>s.trim()).filter(Boolean)}r(ect,"parseCommaArgs");function tct(e){return Array.isArray(e)?e.filter(s=>typeof s=="string").join(", "):typeof e=="string"?e:""}r(tct,"formatArgList");var sct=[{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"}],nct=[{id:"",label:"Auto"},{id:"plan",label:"Plan"},{id:"ask",label:"Ask"}],rct=[{id:"",label:"Auto"},{id:"low",label:"Low"},{id:"medium",label:"Medium"},{id:"high",label:"High"}],act=[{id:"",label:"Auto"},{id:"low",label:"Low"},{id:"high",label:"High"},{id:"max",label:"Max"}],ict=2,ere=10,oct=1,x_e=300;function b3(e,s,n){return Math.max(s,Math.min(n,Math.floor(e)))}r(b3,"clampInteger");function lct(e){return b3(e,0,x_e)*1e3}r(lct,"clampDelayMsFromSeconds");function cct({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(cct,"ConfigSections");function g_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}=ps(),x=Nt(),b=(0,m.useRef)(null),v=f_e(),{data:j=[]}=te({queryKey:f?D.secrets.list(f):["secrets","none"],queryFn:r(()=>Rr.list(f),"queryFn"),enabled:!!f}),{data:N=[]}=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:k=[]}=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)(()=>k.filter(pt=>pt.kind==="binding"&&pt.target?.id===w),[k,w]),C=l_e(f,[]),{data:_}=te({queryKey:D.instance.experimentalSettings,queryFn:r(()=>vr.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]),A=_?.enableEnvironments===!0,T=_?.enableManagedSandboxOnly===!0,E=_===void 0||T,{data:L}=te({queryKey:D.instance.generalSettings,queryFn:r(()=>vr.getGeneral(),"queryFn"),retry:!1}),{data:O}=te({queryKey:D.instance.settings,queryFn:r(()=>vr.get(),"queryFn"),retry:!1}),{data:P=[]}=te({queryKey:f?D.environments.list(f):["environments","none"],queryFn:r(()=>$i.list(f),"queryFn"),enabled:!!f&&(A||L?.executionMode==="kubernetes")}),{forced:U,kubernetesEnvironment:M}=(0,m.useMemo)(()=>CH(L?.executionMode,P),[L?.executionMode,P]),B=ye({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=ye({mutationFn:r(async({file:pt,namespace:Is})=>{if(!f)throw new Error("Select an organization to upload images");return qb.uploadImage(f,pt,Is)},"mutationFn")}),[z,K]=(0,m.useState)(cF),[W,Q]=(0,m.useState)(!1),[re,J]=(0,m.useState)(0),ie=(0,m.useRef)(null),X=(0,m.useRef)(null),ne=(0,m.useRef)(!1);(0,m.useEffect)(()=>{if(!a){if(ie.current!==null&&e.agent!==ie.current&&!ne.current){const pt=X.current;X.current=null,K(Is=>pt?Zlt(Is,pt):{...cF})}ie.current=e.agent}},[a,a?void 0:e.agent]);const oe=!a&&(Zne(z)||W);function G(pt,Is,cn){const _n=z[pt];return Is in _n?_n[Is]:cn}r(G,"eff");function Z(pt,Is,cn){K(_n=>({..._n,[pt]:{..._n[pt],[Is]:cn}}))}r(Z,"mark");function Y(){return b.current?.flushPendingDraft()??null}r(Y,"flushEnvironmentDraft");const ae=(0,m.useCallback)(pt=>{a||K(Is=>{const cn={...e.agent.adapterConfig??{},...Is.adapterConfig},_n={...Is.adapterConfig};for(const[fn,Sr]of Object.entries(pt))_n[`${r2}${fn}`]=Sr;for(const fn of Object.keys(cn))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({...cF}),Q(!1),J(pt=>pt+1)},[]),ce=(0,m.useCallback)(async()=>{if(a)return;const pt=Y(),Is=pt?{...z,adapterConfig:{...z.adapterConfig,env:pt}}:z;Zne(Is)&&await e.onSave($T(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??{},we=a?{}:e.agent.runtimeConfig??{},Se=a?{}:we.heartbeat??{},Te=a?{}:we.debug??{},le=a?e.values.adapterType:z.adapterType??e.agent.adapterType,fe=jj(),de=fe(le),Ee=le==="paperclip_runner"&&(a?e.values.adapterSchemaValues?.provider:G("adapterConfig","provider",pe.provider))==="openai_dot",Me=!Ee&&(de.supportsInstructionsBundle||de.supportsSkills||de.supportsLocalAgentJwt),ve=Me&&!E&&Klt({isCreate:a,adapterConfig:pe}),Ie=(0,m.useMemo)(()=>KS(le),[le]),Ze=(0,m.useMemo)(()=>new Set(KUe(le)),[le]),ue=a?e.values:null,Be=a?pt=>e.onChange(pt):null;a&&ue.claudeStoredSessionId;const ht=r(()=>{f&&x.invalidateQueries({queryKey:D.secrets.userDefinitions(f)})},"invalidateUserSecretDefinitions"),jt=r(pt=>{if(!a||!Be)return;const Is=ue.envBindings??{};Be({envBindings:{...Is,...kN()},claudeStoredSessionId:pt}),ht()},"handleClaudeLoginStored"),Je=r(async()=>{if(a)return;const pt={...Y()??G("adapterConfig","env",pe.env??zC),...kN()},Is={...z,adapterConfig:{...z.adapterConfig,env:pt}};K(Is),await e.onSave({...$T(e.agent,Is),applyStoredClaudeLogin:!0}),ht()},"handleClaudeLoginStoredEdit"),Fe=r(async pt=>{if(a||!pt.companyIdentityDiffers)return;const Is={...Y()??G("adapterConfig","env",pe.env??zC),CODEX_HOME:{type:"secret_ref",secretId:pt.secretId,version:"latest"}},cn={...z,adapterConfig:{...z.adapterConfig,env:Is}};K(cn),X.current=cn,ne.current=!0;try{await e.onSave($T(e.agent,cn))}catch(_n){throw X.current=null,_n}finally{ne.current=!1}ht()},"handleCodexAccountBindingEdit"),it=r(()=>{if(!a||!Be)return;const pt=ue.envBindings??{};Be({envBindings:{...pt,...kN()},claudeApplyStoredLogin:!0}),ht()},"handleApplyStoredClaudeLogin"),At=r(async()=>{if(a)return;const pt={...Y()??G("adapterConfig","env",pe.env??zC),...kN()},Is={...z,adapterConfig:{...z.adapterConfig,env:pt}};K(Is),await e.onSave({...$T(e.agent,Is),applyStoredClaudeLogin:!0}),ht()},"handleApplyStoredClaudeLoginEdit"),$t=a?ue.defaultEnvironmentId??"":G("identity","defaultEnvironmentId",e.agent.defaultEnvironmentId??""),zt=(0,m.useMemo)(()=>$t?(P.find(pt=>pt.id===$t)??null)?.driver==="local"?"":$t:"",[P,$t]),at=(0,m.useMemo)(()=>P.find(pt=>pt.id===zt)??null,[zt,P]),De=(0,m.useMemo)(()=>{const pt=O?.defaultEnvironmentId??null;return pt?(P.find(Is=>Is.id===pt)??null)?.driver==="local"?"":pt:""},[P,O?.defaultEnvironmentId]),Pe=(0,m.useMemo)(()=>P.find(pt=>pt.id===De)??null,[P,De]),dt=(0,m.useMemo)(()=>{try{return Bk({agentDefaultEnvironmentId:$t||null,instanceDefaultEnvironmentId:O?.defaultEnvironmentId??null,localDefaultEnvironmentId:qk(P),managedSandboxOnly:_?.enableManagedSandboxOnly===!0,managedSandboxEnvironmentId:zk(P),visibleEnvironmentIds:P.map(pt=>pt.id)})}catch{return null}},[$t,O?.defaultEnvironmentId,P,_?.enableManagedSandboxOnly]),rt=(0,m.useMemo)(()=>P.find(pt=>pt.id===dt)??null,[P,dt]),{data:ft}=te({queryKey:f?D.environments.capabilities(f):["environment-capabilities","none"],queryFn:r(()=>$i.capabilities(f),"queryFn"),enabled:!!f&&de.login!=null});(0,m.useEffect)(()=>{!a||!Be||!U||!M||zt!==M.id&&Be({defaultEnvironmentId:M.id})},[a,Be,U,M,zt]);const kt=(0,m.useMemo)(()=>P.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"}),[P,Ze]),Ke=(0,m.useMemo)(()=>!at||kt.some(pt=>pt.id===at.id)?kt:[...kt,at],[at,kt]),$e=A&&(U||zt.length>0||kt.length>=1),ze=Pe?Uk(Pe):T?"Paperclip Computer":"Local",et=le==="paperclip_runner"?String(a?e.values.adapterSchemaValues?.provider??"codex":G("adapterConfig","provider",pe.provider==="acpx"&&pe.acpxAgent==="codex"?"codex":pe.provider??"codex")):void 0,ge=le==="opencode_local"&&Uq.safeParse(z.runtime.runtimeConfig?.aiConnection??we.aiConnection).data?.provider==="openrouter"?"openrouter":et,st=t1e(f,a?void 0:Uq.safeParse(z.runtime.runtimeConfig?.aiConnection??we.aiConnection).data,BZ(le,et,G("adapterConfig","acpxAgent",pe.acpxAgent))),Mt=f?D.agents.adapterModels(f,le,zt||null,ge):["agents","none","adapter-models",le],{data:Ss,error:lt,isLoading:Ls}=te({queryKey:Mt,queryFn:r(()=>Ct.adapterModels(f,le,{environmentId:zt||null,provider:ge}),"queryFn"),enabled:!!f&&!st}),[Ue,xe]=(0,m.useState)(null),[Ye,gt]=(0,m.useState)(!1),Ht=st?.models??Ss??n??[],mt=st?st.error:lt,Bt="command",{data:Le,refetch:he}=te({queryKey:f?D.agents.detectModel(f,le):["agents","none","detect-model",le],queryFn:r(()=>{if(!f)throw new Error("Select an organization to detect the model");return Ct.detectModel(f,le)},"queryFn"),enabled:!!(f&&Me&&le!=="opencode_local"&&le!=="paperclip_runner")}),Qt=Le?.model??null;Le?.candidates;const{data:Lt=[]}=te({queryKey:f?D.agents.list(f):["agents","none","list"],queryFn:r(()=>Ct.list(f),"queryFn"),enabled:!!(!a&&f)}),ss={companyId:f??void 0,agentId:a?void 0:e.agent.id,mode:s,isCreate:a,adapterType:le,values:a?e.values:null,set:a?pt=>e.onChange(pt):null,config:pe,eff:G,mark:Z,models:Ht,hideInstructionsFile:h||E||Ee,managedSandboxOnly:E||Ee,openAiDotEnabled:_?.enableOpenAiDot===!0},[Cs,ln]=(0,m.useState)(!1),[mr,pn]=(0,m.useState)(!1),Ot=mH(le),Es=r(pt=>(0,t.jsxs)(t.Fragment,{children:[le==="claude_local"&&(0,t.jsx)(Crt,{...ss,section:pt}),(0,t.jsx)(Ie.ConfigFields,{...ss,section:pt,hideModel:Me})]}),"renderAdapterFields"),[Re,wt]=(0,m.useState)(!1),[Oe,_t]=(0,m.useState)(!1);function Ut(pt){if(a){const cn=Ie.buildAdapterConfig(ue);return pt&&Object.assign(cn,pt),$P(cn)}const Is={...pe,...z.adapterConfig};return pt&&Object.assign(Is,pt),$P(Is)}r(Ut,"buildAdapterConfigForTest");const It=ye({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 cn=O,_n=P,fn=_?.enableManagedSandboxOnly===!0;if(!$t)try{const[an,Tr,Jn]=await Promise.all([x.ensureQueryData({queryKey:D.instance.settings,queryFn:r(()=>vr.get(),"queryFn")}),x.ensureQueryData({queryKey:D.environments.list(f),queryFn:r(()=>$i.list(f),"queryFn")}),x.ensureQueryData({queryKey:D.instance.experimentalSettings,queryFn:r(()=>vr.getExperimental(),"queryFn")})]);cn=an,_n=Tr,fn=Jn?.enableManagedSandboxOnly===!0}catch{throw new Error("Could not load environment settings to determine which environment to test in. Retry the test.")}const Sr=Bk({agentDefaultEnvironmentId:$t||null,instanceDefaultEnvironmentId:cn?.defaultEnvironmentId??null,localDefaultEnvironmentId:qk(_n),managedSandboxOnly:fn,managedSandboxEnvironmentId:zk(_n),visibleEnvironmentIds:_n.map(an=>an.id)}),aa=Ut(Is),Da=a?void 0:e.agent.id,As=a?void 0:DZ.safeParse(z.runtime.runtimeConfig?.aiConnection??e.agent.runtimeConfig.aiConnection).data;if(e.compactTestFeedback){const an=le==="paperclip_runner"?aa.provider==="codex"?"codex_local":aa.provider==="acpx"&&aa.acpxAgent==="grok"?"grok_local":aa.provider==="acpx"&&aa.acpxAgent==="claude"?"claude_local":le:le;return s1e({companyId:f,adapterType:le,providerAdapter:an,adapterConfig:aa,agentId:Da,aiConnection:As,environmentId:Sr})}return Ct.testEnvironment(f,le,{adapterConfig:aa,agentId:Da,aiConnection:As,environmentId:Sr})},"mutationFn")}),[is,bs]=(0,m.useState)(!1),[Os,qs]=(0,m.useState)(null),Rn="Test",Ns=!a&&!!e.isSaving,Yn=is||Ns||!f,Xt=(0,m.useRef)(It.reset);Xt.current=It.reset;const Hs=(0,m.useRef)(()=>{});Hs.current=()=>{if(!a||!Be)return;const pt=ue.envBindings??{},Is=ue.claudeStoredSessionId!=null||ue.claudeApplyStoredLogin===!0,cn=Une in pt;if(!Is&&!cn)return;const _n={...pt};delete _n[Une],Be({envBindings:_n,claudeStoredSessionId:null,claudeApplyStoredLogin:!1})},(0,m.useEffect)(()=>{Xt.current(),qs(null),Hs.current()},[le,dt]);const rn=de.login!=null,Et=It.data,rs=Et!=null&&fe(Et.adapterType).login!=null,Zs=Et&&rs?Et.checks.find(pt=>pt.code==="adapter_auth_missing")??null:null,gs=typeof rt?.config?.provider=="string"?rt.config.provider:null,Js=gs!=null&&ft?.sandboxProviders?.[gs]?.supportsLoginPty===!0,kn=de.login!=null,hr=(a||!(z.runtime.runtimeConfig?.aiConnection??we.aiConnection))&&rn&&rt?.driver==="sandbox"&&!!dt&&!!f&&!!Zs&&(!kn||Js),qn=(0,m.useCallback)(async()=>{if(!f)throw new Error("Select an organization to test adapter environment");bs(!0),qs(null),It.reset();try{return await It.mutateAsync()}catch(pt){throw qs(pt instanceof Error?pt.message:"Environment test failed"),pt}finally{bs(!1)}},[f,It]),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:is}),()=>{e.onTestActionStateChange?.({disabled:!0,pending:!1})}},[l,e.onTestActionStateChange,Yn,is]),(0,m.useEffect)(()=>{if(e.onTestFeedbackChange)return e.onTestFeedbackChange({errorMessage:Os??(It.error instanceof Error?It.error.message:It.error?"Environment test failed":null),result:It.data??null,login:hr&&f&&dt?{companyId:f,adapterType:le,environmentId:dt}:null}),()=>{e.onTestFeedbackChange?.({errorMessage:null,result:null,login:null})}},[e.onTestFeedbackChange,Os,It.data,It.error,hr,f,le,dt]);const pr=a?ue.model??"":G("adapterConfig","model",String(pe.model??"")),Cn=typeof pr=="string"?pr:"";async function kr(){if(f){gt(!0),xe(null);try{const pt=await Ct.adapterModels(f,le,{refresh:!0,environmentId:zt||null,provider:ge});x.setQueryData(Mt,pt)}catch(pt){xe(pt instanceof Error?pt.message:"Failed to refresh adapter models.")}finally{gt(!1)}}}r(kr,"handleRefreshModels");const Or=le==="codex_local"?"modelReasoningEffort":le==="cursor"?"mode":le==="opencode_local"?"variant":le==="grok_local"?"reasoningEffort":le==="pi_local"||le==="omp_local"?"thinking":"effort",Ur=le==="codex_local"?oH(Cn,"Auto").map(pt=>({id:pt.value,label:pt.label})):le==="cursor"?nct:le==="opencode_local"?sct:le==="kimi_local"?act:le==="pi_local"?[{id:"",label:"Auto"},...["off","minimal","low","medium","high","xhigh"].map(pt=>({id:pt,label:pt}))]:le==="claude_local"||le==="grok_local"?[{id:"",label:"Auto"},...TP(le,Cn).map(pt=>({id:pt,label:pt==="xhigh"?"X-High":pt[0].toUpperCase()+pt.slice(1)}))]:rct,xa=le==="omp_local",ar=a?xa?String(ue.adapterSchemaValues?.thinking??""):ue.thinkingEffort:le==="codex_local"?G("adapterConfig","modelReasoningEffort",String(pe.modelReasoningEffort??pe.reasoningEffort??"")):le==="cursor"?G("adapterConfig","mode",String(pe.mode??"")):le==="opencode_local"?G("adapterConfig","variant",String(pe.variant??"")):G("adapterConfig",Or,String(pe[Or]??"")),cr=le!=="gemini_local"&&le!=="cursor_cloud"&&le!=="paperclip_runner"&&!xa,bt=r(pt=>{if(a){Be(xa?{adapterSchemaValues:{...ue.adapterSchemaValues,thinking:pt??void 0}}:{thinkingEffort:pt??""});return}Z("adapterConfig",Or,pt||void 0)},"setThinkingEffort"),He=le==="codex_local"?a?!!ue.search:G("adapterConfig","search",!!pe.search):!1,Zt=(0,m.useMemo)(()=>{if(a)return{heartbeat:{enabled:ue.heartbeatEnabled,intervalSec:ue.intervalSec}};const pt={...we.heartbeat&&typeof we.heartbeat=="object"?we.heartbeat:{},...z.heartbeat};return{...we,heartbeat:pt}},[a,z.heartbeat,we,ue]),ms=IZ(Zt.heartbeat),_s=IZ(ms.maxTurnContinuation),ts=YFe(_s.enabled,!0),ws=b3(wZ(_s.maxAttempts,ict),0,ere),Nn=b3(wZ(_s.delayMs,oct*1e3)/1e3,0,x_e);function vn(pt){Z("heartbeat","maxTurnContinuation",{..._s,...pt})}r(vn,"updateMaxTurnContinuation");const Un=(0,t.jsx)(Jy,{ref:b,onDirtyChange:Q,hideDraftActions:!a&&e.hideInlineSave,value:a?ue.envBindings??zC:G("adapterConfig","env",pe.env??zC),secrets:j,userSecretDefinitions:N,onCreateSecret:r(async(pt,Is)=>await B.mutateAsync({name:pt,value:Is}),"onCreateSecret"),onChange:r(pt=>a?Be({envBindings:pt??{},envVars:""}):Z("adapterConfig","env",pt),"onChange")},re);return!a&&e.content==="secrets"?(0,t.jsxs)("div",{className:V("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:V(!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:V(i?"rounded-lg border border-border p-4":"px-4 pb-3"),children:Un})]}),(0,t.jsxs)("div",{"data-config-section":"secrets",className:V(!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:V(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)(zlt,{config:{...pe,...z.adapterConfig},secrets:j,onChange:ae,onCreateSecret:r((pt,Is)=>B.mutateAsync({name:pt,value:Is}),"onCreateSecret"),proposals:S,onApproveProposal:C.requestApprove,onRejectProposal:C.requestReject}),C.dialogs]})]})]}):(0,t.jsxs)(cct,{order:e.sectionOrder,className:V("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:V(!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:V(i?"border border-border rounded-lg p-4 space-y-3":"px-4 pb-3 space-y-3"),children:[(0,t.jsx)(ks,{label:"Name",hint:wi.name,children:(0,t.jsx)(Wa,{value:G("identity","name",e.agent.name),onCommit:r(pt=>Z("identity","name",pt),"onCommit"),immediate:!0,className:hh,placeholder:"Agent name"})}),(0,t.jsx)(ks,{label:"Title",hint:wi.title,children:(0,t.jsx)(Wa,{value:G("identity","title",e.agent.title??""),onCommit:r(pt=>Z("identity","title",pt||null),"onCommit"),immediate:!0,className:hh,placeholder:"e.g. VP of Engineering"})}),(0,t.jsx)(ks,{label:"Reports to",hint:wi.reportsTo,children:(0,t.jsx)(Zot,{agents:Lt,value:G("identity","reportsTo",e.agent.reportsTo??null),onChange:r(pt=>Z("identity","reportsTo",pt),"onChange"),excludeAgentIds:[e.agent.id],chooseLabel:"Choose manager…"})}),Me&&!e.hidePromptTemplate&&(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)(ks,{label:"Prompt Template",hint:wi.promptTemplate,children:(0,t.jsx)(Qc,{value:G("adapterConfig","promptTemplate",String(pe.promptTemplate??"")),onChange:r(pt=>Z("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."})]})]})]}),U?(0,t.jsxs)("div",{"data-config-section":"environment",className:V(!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:V(i?"border border-border rounded-lg p-4 space-y-3":"px-4 pb-3 space-y-3"),children:(0,t.jsx)(ks,{label:"Default environment",hint:"This instance runs all agents in the Kubernetes sandbox. Local execution is disabled.",children:M?(0,t.jsxs)("div",{className:V(hh,"flex items-center text-muted-foreground"),children:[M.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."})})})]}):$e?(0,t.jsxs)("div",{"data-config-section":"environment",className:V(!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:V(i?"border border-border rounded-lg p-4 space-y-3":"px-4 pb-3 space-y-3"),children:(0,t.jsx)(ks,{label:"Environment override",children:(0,t.jsx)("div",{className:"space-y-2",children:(0,t.jsxs)("select",{className:hh,value:zt,onChange:r(pt=>{const Is=pt.target.value;if(a){Be({defaultEnvironmentId:Is});return}Z("identity","defaultEnvironmentId",Is||null)},"onChange"),children:[(0,t.jsxs)("option",{value:"",children:["Default: ",ze]}),Ke.map(pt=>(0,t.jsx)("option",{value:pt.id,children:Uk(pt)},pt.id))]})})})})]}):null,(0,t.jsxs)("div",{"data-config-section":"adapter",className:V(!i&&(a?"border-t border-border":"border-b border-border")),children:[(0,t.jsxs)("div",{className:V(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:is?`${Rn}...`:Rn})]}),(0,t.jsxs)("div",{className:V(i?"border border-border rounded-lg p-4 space-y-3":"px-4 pb-3 space-y-3"),children:[o&&(0,t.jsx)(ks,{label:"Adapter type",hint:wi.adapterType,children:(0,t.jsx)(v_e,{value:Ee?"openai_dot":le,disabledTypes:R,openAiDotEnabled:_?.enableOpenAiDot===!0,onChange:r(pt=>{const Is=pt==="openai_dot",cn=Is?"paperclip_runner":pt;if(a){const{adapterType:_n,...fn}=ib,Sr={...fn,adapterType:cn};cn==="codex_local"?Sr.dangerouslyBypassSandbox=!0:cn==="gemini_local"?Sr.model="auto":cn==="kimi_local"?Sr.model="kimi-code/kimi-for-coding":cn==="cursor"?Sr.model="auto":cn==="opencode_local"?Sr.model="openai/gpt-5.2-codex":cn==="paperclip_runner"&&(Sr.model=Fk),Is&&(Sr.model="",Sr.adapterSchemaValues={provider:"openai_dot"}),Be(Sr)}else K(_n=>({..._n,adapterType:cn,adapterConfig:{model:cn==="gemini_local"?"auto":cn==="kimi_local"?"kimi-code/kimi-for-coding":cn==="opencode_local"?"openai/gpt-5.2-codex":cn==="cursor"?"auto":Is?"":cn==="paperclip_runner"?Xlt(le,pe.model):"",effort:"",modelReasoningEffort:"",variant:"",mode:"",...cn==="codex_local"?{dangerouslyBypassApprovalsAndSandbox:!0}:Is?{provider:"openai_dot",lifecycleMode:"per_turn",allowUnmeteredProvider:!1,dotAttachmentAccess:!1,dotWorkspaceAccess:!1}:cn==="paperclip_runner"?{...o1e(le,G("adapterConfig","model",pe.model))}:{}}}))},"onChange")})}),!Ee&&!a&&f&&(0,t.jsx)(lU,{companyId:f,agentId:e.agent.id,agentName:e.agent.name,adapterType:BZ(le,G("adapterConfig","provider",pe.provider),G("adapterConfig","acpxAgent",pe.acpxAgent)),routerAdapterType:le,value:DZ.safeParse(z.runtime.runtimeConfig?.aiConnection??we.aiConnection).data,model:String(G("adapterConfig","model",pe.model)??""),environmentId:zt||void 0,legacy:!0,onChange:r(pt=>Z("runtime","runtimeConfig",{...we,aiConnection:pt}),"onChange")}),d&&!e.compactTestFeedback&&(Os||It.error)&&(0,t.jsx)("div",{className:"rounded-md border border-destructive/30 bg-destructive/10 px-3 py-2 text-xs text-destructive",children:Os??(It.error instanceof Error?It.error.message:"Environment test failed")}),d&&!e.compactTestFeedback&&It.data&&(0,t.jsx)(xct,{result:It.data}),d&&hr&&(0,t.jsx)(_H,{companyId:f,adapterType:le,environmentId:dt,onStored:a?jt:Je,onApplyStored:a?it:At,onAccountBinding:a?void 0:Fe},`${le}:${dt}`),ve&&(0,t.jsx)(ks,{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)(sl,{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?Be({cwd:pt}):Z("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)(Qd,{})]})}),Es("adapter"),Me&&(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)(IH,{models:Ht,loadingModels:st?.isLoading??Ls,value:Cn,effort:xa?{value:ar||null,onChange:bt}:void 0,onChange:r(pt=>{xa&&!vD(ar,pt,Ht.map(_n=>YN(_n,!1)))&&bt(null);const Is=TP(le,pt),cn=["codex_local","claude_local","grok_local"].includes(le)&&!!ar&&!Is.includes(String(ar));if(a){Be({model:pt,...cn?{thinkingEffort:""}:{}});return}Z("adapterConfig","model",st?.resolveModel(pt)||pt||void 0),cn&&(Z("adapterConfig",Or,void 0),Z("adapterConfig","reasoningEffort",void 0))},"onChange"),open:Re,onOpenChange:wt,defaultLabel:le==="claude_local"?"Default (claude-opus-5)":void 0,allowDefault:le!=="opencode_local"&&le!=="pi_local"&&le!=="paperclip_runner",required:le==="opencode_local"||le==="pi_local",groupByProvider:!st&&(le==="opencode_local"||le==="pi_local"),preserveOrder:!!st||dH(le),creatable:!0,detectedModel:st?void 0:Qt,detectedModelCandidates:[],onDetectModel:st||le==="opencode_local"||le==="paperclip_runner"?void 0:async()=>(await he()).data?.model??null,onRefreshModels:st?st.refreshModels:Jlt(le)?kr:void 0,refreshingModels:st?.refreshing??Ye,detectModelLabel:"Detect model",emptyDetectHint:"No model detected. Select or enter one manually."}),(Ue||mt)&&(0,t.jsx)("p",{className:"text-xs text-destructive",children:Ue??(mt instanceof Error?mt.message:"Failed to load adapter models.")}),le==="opencode_local"&&!st&&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,"."]}),cr&&(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)(gct,{value:ar,options:Ur,onChange:r(pt=>a?Be({thinkingEffort:pt}):Z("adapterConfig",Or,pt||void 0),"onChange"),open:Oe,onOpenChange:_t}),le==="codex_local"&&He&&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:V(!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:V(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)(ks,{label:"Bootstrap prompt (legacy)",hint:wi.bootstrapPrompt,children:(0,t.jsx)(Qc,{value:G("adapterConfig","bootstrapPromptTemplate",String(pe.bootstrapPromptTemplate??"")),onChange:r(pt=>Z("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."})]}),Es("configuration"),(Me||le==="process"||Ot?.fields.some(pt=>mU(pt.key)==="advanced"))&&(0,t.jsx)(u3,{title:"Advanced",open:mr,onToggle:r(()=>pn(!mr),"onToggle"),children:(0,t.jsxs)("div",{className:"space-y-3",children:[Me&&(0,t.jsxs)(t.Fragment,{children:[" ",!E&&(0,t.jsx)(ks,{label:"Command",hint:wi.localCommand,children:(0,t.jsx)(Wa,{value:a?ue.command:G("adapterConfig",Bt,String(pe.command??"")),onCommit:r(pt=>a?Be({command:pt}):Z("adapterConfig",Bt,pt||null),"onCommit"),immediate:!0,className:hh,placeholder:{claude_local:"claude",codex_local:"codex",gemini_local:"gemini",kimi_local:"kimi",pi_local:"pi",cursor:"agent",opencode_local:"opencode"}[le]??le.replace(/_local$/,"")})}),(0,t.jsx)(ks,{label:"Extra args (comma-separated)",hint:wi.extraArgs,children:(0,t.jsx)(Wa,{value:a?ue.extraArgs:G("adapterConfig","extraArgs",tct(pe.extraArgs)),onCommit:r(pt=>a?Be({extraArgs:pt}):Z("adapterConfig","extraArgs",pt?.trim()?ect(pt):null),"onCommit"),className:hh,placeholder:"e.g. --verbose, --foo=bar"})})]}),Es("advanced")]})})]})]}),e.environmentVariablesPlacement!=="secrets"&&(Me||Ot?.fields.some(pt=>mU(pt.key)==="environment"))&&(0,t.jsxs)("div",{"data-config-section":"environment-variables",className:V(!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:V(i?"border border-border rounded-lg p-4 space-y-3":"px-4 pb-3 space-y-3"),children:Me?Un:Es("environment")})]}),a&&u?(0,t.jsxs)("div",{"data-config-section":"run-policy",className:V(!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)(w1,{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)(w1,{className:"h-3 w-3"})," Run Policy"]}),(0,t.jsxs)("div",{className:V(i?"border border-border rounded-lg p-4 space-y-3":"px-4 pb-3 space-y-3"),children:[(0,t.jsx)(fne,{label:"Heartbeat on interval",hint:wi.heartbeatInterval,checked:ue.heartbeatEnabled,onCheckedChange:r(pt=>Be({heartbeatEnabled:pt}),"onCheckedChange"),number:ue.intervalSec,onNumberChange:r(pt=>Be({intervalSec:pt}),"onNumberChange"),numberLabel:"sec",numberPrefix:"Run heartbeat every",numberHint:wi.intervalSec,showNumber:ue.heartbeatEnabled}),(0,t.jsx)(u3,{title:"Advanced Run Policy",open:Cs,onToggle:r(()=>ln(!Cs),"onToggle"),children:(0,t.jsx)("div",{className:"space-y-3",children:Es("runPolicy")})})]})]}):a?null:(0,t.jsxs)("div",{"data-config-section":"run-policy",className:V(!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)(w1,{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)(w1,{className:"h-3 w-3"})," Run Policy"]}),(0,t.jsxs)("div",{className:V(i?"border border-border rounded-lg overflow-hidden":""),children:[(0,t.jsx)("div",{className:V(i?"p-4 space-y-3":"px-4 pb-3 space-y-3"),children:(0,t.jsx)(fne,{label:"Heartbeat on interval",hint:wi.heartbeatInterval,checked:G("heartbeat","enabled",Se.enabled===!0),onCheckedChange:r(pt=>Z("heartbeat","enabled",pt),"onCheckedChange"),number:G("heartbeat","intervalSec",Number(Se.intervalSec??300)),onNumberChange:r(pt=>Z("heartbeat","intervalSec",pt),"onNumberChange"),numberLabel:"sec",numberPrefix:"Run heartbeat every",numberHint:wi.intervalSec,showNumber:G("heartbeat","enabled",Se.enabled===!0)})}),(0,t.jsx)(u3,{title:"Advanced Run Policy",bordered:i,open:Cs,onToggle:r(()=>ln(!Cs),"onToggle"),children:(0,t.jsxs)("div",{className:"space-y-3",children:[Es("runPolicy"),Me&&(0,t.jsx)(t.Fragment,{children:!a&&(0,t.jsxs)(t.Fragment,{children:[!Ot?.fields.some(pt=>pt.key==="timeoutSec")&&(0,t.jsx)(ks,{label:"Timeout (sec)",hint:wi.timeoutSec,children:(0,t.jsx)(zc,{value:G("adapterConfig","timeoutSec",Number(pe.timeoutSec??0)),onCommit:r(pt=>Z("adapterConfig","timeoutSec",pt),"onCommit"),immediate:!0,className:hh})}),!Ot?.fields.some(pt=>pt.key==="graceSec")&&(0,t.jsx)(ks,{label:"Interrupt grace period (sec)",hint:wi.graceSec,children:(0,t.jsx)(zc,{value:G("adapterConfig","graceSec",Number(pe.graceSec??15)),onCommit:r(pt=>Z("adapterConfig","graceSec",pt),"onCommit"),immediate:!0,className:hh})})]})}),(0,t.jsx)(vl,{label:"Wake on demand",hint:wi.wakeOnDemand,checked:G("heartbeat","wakeOnDemand",Se.wakeOnDemand!==!1),onChange:r(pt=>Z("heartbeat","wakeOnDemand",pt),"onChange")}),(0,t.jsx)(ks,{label:"Cooldown (sec)",hint:wi.cooldownSec,children:(0,t.jsx)(zc,{value:G("heartbeat","cooldownSec",Number(Se.cooldownSec??10)),onCommit:r(pt=>Z("heartbeat","cooldownSec",pt),"onCommit"),immediate:!0,className:hh})}),(0,t.jsx)(ks,{label:"Max concurrent runs",hint:wi.maxConcurrentRuns,children:(0,t.jsx)(zc,{value:G("heartbeat","maxConcurrentRuns",Number(Se.maxConcurrentRuns??20)),onCommit:r(pt=>Z("heartbeat","maxConcurrentRuns",pt),"onCommit"),immediate:!0,className:hh})}),(0,t.jsxs)("div",{className:"rounded-md border border-border/70 px-3 py-2",children:[(0,t.jsx)(vl,{label:"Continue after max-turn stop",hint:wi.maxTurnContinuationEnabled,checked:ts,onChange:r(pt=>vn({enabled:pt}),"onChange")}),ts?(0,t.jsxs)("div",{className:"mt-3 grid gap-3 sm:grid-cols-2",children:[(0,t.jsx)(ks,{label:"Continuation attempts",hint:wi.maxTurnContinuationMaxAttempts,children:(0,t.jsx)(zc,{value:ws,onCommit:r(pt=>vn({maxAttempts:b3(pt,0,ere)}),"onCommit"),immediate:!0,className:hh})}),(0,t.jsx)(ks,{label:"Continuation delay (sec)",hint:wi.maxTurnContinuationDelaySec,children:(0,t.jsx)(zc,{value:Nn,onCommit:r(pt=>vn({delayMs:lct(pt)}),"onCommit"),immediate:!0,className:hh})})]}):null]})]})})]})]}),!a&&p?(0,t.jsxs)("div",{className:V(!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)(by,{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)(by,{className:"h-3 w-3"})," Debugging"]}),(0,t.jsxs)("div",{className:V("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)(vl,{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",Te.providerTrace)==="raw",onChange:r(pt=>Z("debug","providerTrace",pt?"raw":void 0),"onChange")}),G("debug","providerTrace",Te.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)(by,{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)(p1e,{variant:Ee?"prerequisites":"connection",state:is?"running":Os||It.error?"fail":Et?.status??"idle",result:Et??null,error:Os??(It.error instanceof Error?It.error.message:null),onTest:Cr,disabled:Yn})]})}r(g_e,"AgentConfigForm");var IU=new Set(["authenticated","failed","timed_out","cancelled"]),AU=2e3;function TU({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 Ia(e),a(!0)}catch{a(!1)}i.current&&clearTimeout(i.current),i.current=setTimeout(()=>a(!1),1500)},"onClick"),children:n?(0,t.jsx)(us,{className:"size-3"}):(0,t.jsx)(wr,{className:"size-3"})})}r(TU,"AdapterLoginCopyButton");function dct({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)(us,{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)(Rs,{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(dct,"AdapterLoginTerminalState");var uct={claude_local:"Anthropic",codex_local:"OpenAI"};function b_e(e){const s=uct[e];return s?`Sign in to ${s}`:"Sign in to the environment"}r(b_e,"adapterLoginTitle");function _H(e){return jj()(e.adapterType).login?.panelMode==="submitted_browser_code"?(0,t.jsx)(fct,{...e}):(0,t.jsx)(mct,{...e})}r(_H,"AdapterLoginPanel");var dF=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 mct({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,b]=(0,m.useState)(null),[v,j]=(0,m.useState)("idle"),N=(0,m.useRef)(!1),w=ye({mutationFn:r(()=>Ct.startAdapterAuthLogin(e,s,{environmentId:n,aiConnection:c}),"mutationFn"),onSuccess:r(ne=>{N.current=!1,f(null),b(null),j("idle"),h(ne.sessionId)},"onSuccess"),onError:r(ne=>{f(ne instanceof Error?ne.message:"Could not start the login.")},"onError")}),k=(0,m.useCallback)(()=>{N.current=!1,h(null),b(null),f(null)},[]),S=ye({mutationFn:r(()=>Ct.cancelAdapterAuthLogin(e,s,u),"mutationFn"),onSuccess:k,onError:r(ne=>{f(ne instanceof Error?ne.message:"Could not cancel the login.")},"onError")}),C=te({queryKey:["adapter-login-active-session",e,s],queryFn:r(async()=>{try{const ne=await Ct.getActiveAdapterAuthLoginSession(e,s);if(!ne)return null;if(c&&ne.environmentId!==n||!!ne.aiConnection!=!!c||c&&(ne.aiConnection?.provider!==c.provider||ne.aiConnection?.method!==c.method||ne.aiConnection?.connectionId!==c.connectionId||ne.aiConnection?.ownership!==c.ownership||ne.aiConnection?.allAgents!==c.allAgents||JSON.stringify(ne.aiConnection?.agentIds)!==JSON.stringify(c.agentIds)))throw new dF(ne.sessionId);return ne}catch(ne){if(ne instanceof mn&&ne.status===404)return null;throw ne}},"queryFn"),retry:!1,gcTime:0,staleTime:0}),[_,R]=(0,m.useState)(!1),A=te({queryKey:["adapter-login-status",e,s,u],queryFn:r(()=>Ct.getAdapterAuthLoginStatus(e,s,u),"queryFn"),enabled:!!u&&!_,retry:r((ne,oe)=>oe instanceof mn&&oe.status===404?!1:ne<3,"retry"),refetchInterval:r(ne=>{const oe=ne.state.data?.status;return oe&&IU.has(oe)?!1:AU},"refetchInterval")});(0,m.useEffect)(()=>{const ne=A.data?.prompt??null;ne&&b(ne)},[A.data]);const T=A.data??w.data??null,E=T?.status??null,L=x,O=E?IU.has(E):!1,P=!!u&&!O,U=w.isPending||P||v==="saving",M=(0,m.useRef)(!1);(0,m.useEffect)(()=>{if(M.current||!C.isFetched)return;M.current=!0;const ne=C.data;ne&&(N.current=!0,f(null),b(ne.prompt??null),h(ne.sessionId))},[C.isFetched,C.data]),(0,m.useEffect)(()=>{const ne=A.error;if(!(ne instanceof mn&&ne.status===404)||!N.current||_)return;R(!0);const oe=u;(async()=>(oe&&await Ct.cancelAdapterAuthLogin(e,s,oe).catch(()=>{}),R(!1),k()))()},[A.error,_,u,e,s,k]);const B=(0,m.useRef)(!1),q=ye({mutationFn:r(async()=>{const ne=C.error;ne instanceof dF&&await Ct.cancelAdapterAuthLogin(e,s,ne.sessionId)},"mutationFn"),onSuccess:r(async()=>{B.current=!1,M.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||B.current)){if(C.isError){B.current=!0,f(C.error instanceof Error?C.error.message:"Could not check for an active login.");return}C.isSuccess&&(B.current=!0,!C.data&&z.current())}},[a,C.isSuccess,C.isError,C.data,C.error]);const K=(0,m.useRef)(!1),W=(0,m.useRef)(i);W.current=i,(0,m.useEffect)(()=>{E!=="authenticated"||K.current||(K.current=!0,W.current?.(u??void 0))},[E]);const Q=(0,m.useRef)(null),re=(0,m.useRef)(o);re.current=o;const J=A.data?.codexAccountBinding??null,ie=(0,m.useCallback)(async ne=>{const oe=re.current;if(oe){j("saving");try{await oe(ne),j("bound")}catch{j("failed")}}},[]);(0,m.useEffect)(()=>{E!=="authenticated"||!u||Q.current!==u&&(!J||!J.companyIdentityDiffers||!re.current||(Q.current=u,ie(J)))},[E,u,J,ie]);const X=(0,m.useRef)(d);if(X.current=d,(0,m.useEffect)(()=>{X.current?.(L?.url??null)},[L]),l==="onboarding"){const ne=O&&E&&E!=="authenticated";return(0,t.jsx)(gH,{loading:!L&&!p&&!ne,providerName:xH(s),authorizationUrl:L?.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 dF&&(0,t.jsx)($,{type:"button",variant:"outline",disabled:q.isPending,onClick:r(()=>q.mutate(),"onClick"),children:"Cancel previous sign-in and retry"})]}):ne?(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)(S1e,{code:L?.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:b_e(s)}),(0,t.jsxs)("div",{className:"flex items-center gap-1.5",children:[P&&(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:U,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:[P&&!L&&(0,t.jsxs)("div",{className:"flex items-center gap-2 text-(length:--text-micro) text-muted-foreground",children:[(0,t.jsx)(tt,{className:"size-3 animate-spin shrink-0"}),(0,t.jsx)("span",{children:"Preparing..."})]}),P&&L&&(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:L.code})]}),(0,t.jsx)(TU,{value:L.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:L.url})]}),(0,t.jsxs)("div",{className:"flex items-center",children:[(0,t.jsx)(TU,{value:L.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:L.url,target:"_blank",rel:"noreferrer noopener",children:(0,t.jsx)($n,{className:"size-3"})})})]})]})]}),O&&E&&(0,t.jsx)(dct,{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)(tt,{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)(us,{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)(Rs,{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(()=>{J&&ie(J)},"onClick"),children:"Retry"})]})]})]})}r(mct,"DisplayedCodeLoginPanel");var hct=new Set(["failed","timed_out","cancelled"]),tre="The login did not finish. Start the login again.",pct=9e5,sre="The login timed out. Start the login again.";function fct({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),[b,v]=(0,m.useState)(null),[j,N]=(0,m.useState)(null),[w,k]=(0,m.useState)(!1),[S,C]=(0,m.useState)(""),[_,R]=(0,m.useState)(null),[A,T]=(0,m.useState)(!1),[E,L]=(0,m.useState)(!1),[O,P]=(0,m.useState)(!1),[U,M]=(0,m.useState)(!1),B=(0,m.useRef)(!1),[q,z]=(0,m.useState)(!1),K=(0,m.useRef)(!1),W=r(()=>{v(null),N(null),k(!1),C(""),R(null),T(!1),L(!1),M(!1),P(!1),B.current=!1},"resetLocalState"),Q=te({queryKey:["claude-oauth-token-status",e],queryFn:r(async()=>{try{return await Ct.getClaudeOAuthTokenStatus(e)}catch(at){if(at instanceof mn&&at.status===404)return null;throw at}},"queryFn"),retry:r((at,De)=>De instanceof mn&&De.status===404?!1:at<2,"retry")}).data??null,re=ye({mutationFn:r(()=>Ct.startClaudeSetupTokenLogin(e,{environmentId:n,aiConnection:h,...Q&&!h?{overwrite:{expectedSecretId:Q.secretId,expectedLatestVersion:Q.latestVersion}}:{}}),"mutationFn"),onSuccess:r(at=>{K.current=!1,W(),x(at.sessionId)},"onSuccess"),onError:r(at=>{v(at instanceof Error?at.message:"Could not start the login.")},"onError")}),J=r(()=>{K.current=!1,x(null),W()},"clearActiveSession"),ie=ye({mutationFn:r(()=>Ct.cancelClaudeSetupTokenLogin(e,f),"mutationFn"),onSuccess:r(()=>{J()},"onSuccess"),onError:r(at=>{if(at instanceof mn&&at.status===404){J();return}v(at instanceof Error?at.message:"Could not cancel the login.")},"onError")}),X=(0,m.useCallback)(at=>{Ct.cancelClaudeSetupTokenLogin(e,at).catch(()=>{})},[e]),ne=te({queryKey:["claude-setup-token-active-session",e],queryFn:r(async()=>{try{const at=await Ct.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 mn&&at.status===404)return null;throw at}},"queryFn"),retry:!1,gcTime:0,staleTime:0}),[oe,G]=(0,m.useState)(!1),Z=!!f&&!E&&!U&&!oe,Y=te({queryKey:["claude-setup-token-status",e,f],queryFn:r(()=>Ct.getClaudeSetupTokenLoginStatus(e,f),"queryFn"),enabled:Z,retry:r((at,De)=>De instanceof mn&&De.status===404?!1:at<3,"retry"),refetchInterval:r(at=>{if(E||U)return!1;const De=at.state.data?.status;return De&&IU.has(De)?!1:AU},"refetchInterval")});(0,m.useEffect)(()=>{const at=Y.error;if(at instanceof mn&&at.status===404){if(K.current){if(oe)return;G(!0);const De=f;(async()=>(De&&await Ct.cancelClaudeSetupTokenLogin(e,De).catch(()=>{}),G(!1),J()))();return}M(!0)}},[Y.error,oe,f,e]);const ae=(0,m.useRef)(!1);(0,m.useEffect)(()=>{if(ae.current||!ne.isFetched)return;ae.current=!0;const at=ne.data;at&&(K.current=!0,W(),x(at.sessionId),at.prompt&&(N(at.prompt.authorizationUrl),at.prompt.transportAdvisory&&k(!0)))},[ne.isFetched,ne.data]);const se=te({queryKey:["claude-setup-token-prompt",e,f],enabled:Z&&!j,queryFn:r(async()=>{try{return await Ct.getClaudeSetupTokenLoginPrompt(e,f)}catch(at){if(at instanceof mn&&at.status===404)return null;throw at}},"queryFn"),refetchInterval:r(at=>E||at.state.data?.authorizationUrl?!1:AU,"refetchInterval")});(0,m.useEffect)(()=>{const at=se.data?.authorizationUrl??null;at&&N(at),se.data?.transportAdvisory&&k(!0)},[se.data]);const ce=ye({mutationFn:r(at=>Ct.submitClaudeSetupTokenBrowserCode(e,f,at),"mutationFn"),onError:r(at=>{v(at instanceof Error?at.message:"Could not submit the browser code.")},"onError")}),pe=ye({mutationFn:r(()=>Ct.completeClaudeSetupTokenLogin(e,f),"mutationFn"),onSuccess:r(at=>{R(at.storedSessionId),a?.(at.storedSessionId)},"onSuccess"),onError:r(()=>{T(!0)},"onError")}),we=Y.data?.status??re.data?.status??null,Se=Y.data?.expiresAt??re.data?.expiresAt??null,Te=(0,m.useRef)(pe.mutate);Te.current=pe.mutate,(0,m.useEffect)(()=>{we==="authenticated"&&!B.current&&(B.current=!0,Te.current())},[we]);const le=_!==null,fe=A||U||!!(we&&hct.has(we)),de=we==="authenticated"&&!le&&!A,Ee=!!f&&!le&&!fe&&!E,Me=re.isPending||Ee;(0,m.useEffect)(()=>{if(!Ee)return;const at=Se!==null?new Date(Se).getTime():NaN,De=Number.isFinite(at)?Math.max(0,at-Date.now()):pct,Pe=setTimeout(()=>{f&&X(f),L(!0)},De);return()=>clearTimeout(Pe)},[Ee,Se,f,X]);const ve=S.trim(),Ie=Ee&&!!j&&!de&&WFe(ve)&&!ce.isPending&&!O,Ze=(0,m.useRef)(c);Ze.current=c;const ue=(0,m.useRef)(d);ue.current=d;const Be=r(()=>{Ie&&(v(null),ce.mutate(ve),P(!0),Ze.current?.(),u!=="onboarding"&&C(""))},"handleSubmit"),ht=(0,m.useRef)(!1),jt=(0,m.useRef)(re.mutate);jt.current=re.mutate,(0,m.useEffect)(()=>{if(!(!o||ht.current)){if(ne.isError){ht.current=!0,v(ne.error instanceof Error?ne.error.message:"Could not check for an active login.");return}ne.isSuccess&&(ht.current=!0,!ne.data&&jt.current())}},[o,ne.isSuccess,ne.isError,ne.data,ne.error]);const Je=(0,m.useRef)(Be);Je.current=Be;const Fe=u==="onboarding",it=(0,m.useRef)(!1);(0,m.useEffect)(()=>{!Fe||!it.current||(it.current=!1,Ie&&Je.current())},[Fe,Ie,S]);const At=(0,m.useRef)(!1),$t=(0,m.useRef)(l);$t.current=l,(0,m.useEffect)(()=>{!le||At.current||(At.current=!0,$t.current?.(f??void 0))},[le]),(0,m.useEffect)(()=>{O&&(!b&&!fe&&!E||(P(!1),ue.current?.()))},[O,b,fe,E]);const zt=(0,m.useRef)(p);if(zt.current=p,(0,m.useEffect)(()=>{zt.current?.(j)},[j]),u==="onboarding"){const at=fe||E;return(0,t.jsxs)(gH,{loading:!j&&!b&&!at,providerName:xH(s),authorizationUrl:j??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)(Rs,{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."]}),b?(0,t.jsx)("p",{role:"alert",className:"pl-2 text-xs text-destructive",children:b}):at?(0,t.jsx)("p",{role:"alert",className:"pl-2 text-xs text-destructive",children:E&&!fe?sre:tre}):(0,t.jsx)(s2,{value:S,onChange:C,onSubmit:Be,onPaste:r(()=>{it.current=!0},"onPaste"),masked:!0,disabled:ce.isPending||de||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:b_e(s)}),(0,t.jsxs)("div",{className:"flex items-center gap-1.5",children:[Ee&&(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&&Q&&!Ee&&!le&&!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:Me,onClick:r(()=>re.mutate(),"onClick"),children:Q&&!Ee&&!le?"Sign in to replace":"Sign in"})]})]}),Q&&!Ee&&!le&&!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)(us,{className:"size-3 shrink-0"}),(0,t.jsx)("span",{children:"The saved Claude login is bound to this agent now."})]}),b&&(0,t.jsx)("div",{role:"alert",className:"text-(length:--text-micro) text-destructive",children:b}),(0,t.jsxs)("div",{role:"status","aria-live":"polite",className:"space-y-2 empty:hidden",children:[Ee&&!j&&!de&&(0,t.jsxs)("div",{className:"flex items-center gap-2 text-(length:--text-micro) text-muted-foreground",children:[(0,t.jsx)(tt,{className:"size-3 animate-spin shrink-0"}),(0,t.jsx)("span",{children:"Preparing..."})]}),Ee&&j&&!de&&(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)(Rs,{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:j})]}),(0,t.jsxs)("div",{className:"flex items-center",children:[(0,t.jsx)(TU,{value:j,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:j,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(),Be())},"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:!Ie,onClick:Be,children:"Submit"})]})]})]}),de&&(0,t.jsxs)("div",{className:"flex items-center gap-2 text-(length:--text-micro) text-muted-foreground",children:[(0,t.jsx)(tt,{className:"size-3 animate-spin shrink-0"}),(0,t.jsx)("span",{children:"Completing the login…"})]}),le&&(0,t.jsxs)("div",{className:"flex items-center gap-2 text-(length:--text-micro) text-foreground",children:[(0,t.jsx)(us,{className:"size-3 shrink-0"}),(0,t.jsx)("span",{children:"Authenticated. The environment has credentials now."})]}),fe&&(0,t.jsxs)("div",{className:"flex items-start gap-2 text-(length:--text-micro) text-destructive",children:[(0,t.jsx)(Rs,{className:"size-3 shrink-0"}),(0,t.jsx)("span",{children:tre})]}),E&&!fe&&!le&&(0,t.jsxs)("div",{className:"flex items-start gap-2 text-(length:--text-micro) text-destructive",children:[(0,t.jsx)(Rs,{className:"size-3 shrink-0"}),(0,t.jsx)("span",{children:sre})]})]})]})}r(fct,"SubmittedBrowserCodeLoginPanel");function xct({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(xct,"AdapterEnvironmentResult$1");function v_e({value:e,onChange:s,disabledTypes:n,openAiDotEnabled:a=!1}){const[i,o]=(0,m.useState)(!1),l=Um(e),c=(0,m.useMemo)(()=>[...p_e(d=>vI[d]??ax(d)),...a?[{value:"openai_dot",label:"OpenAI Dot",experimental:!0,comingSoon:!1}]:[]].filter(d=>!n.has(d.value)),[n,a]);return(0,t.jsxs)(ur,{open:i,onOpenChange:o,children:[(0,t.jsx)(Nr,{asChild:!0,children:(0,t.jsxs)("button",{type:"button","data-size":"default",className:V(_6e,"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)(Ap,{type:e,className:"size-4"})}),(0,t.jsx)("span",{className:"truncate",children:vI[e]??ax(e)}),l.experimental&&(0,t.jsx)(nre,{})]}),(0,t.jsx)(nn,{className:"size-4 opacity-50"})]})}),(0,t.jsx)(rr,{className:"w-(--radix-popover-trigger-width) p-1",align:"start",children:c.map(d=>(0,t.jsxs)("button",{type:"button",disabled:d.comingSoon,className:V("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)(Ap,{type:d.value,className:"size-4"})}),(0,t.jsx)("span",{children:d.label}),d.experimental&&(0,t.jsx)(nre,{})]}),d.comingSoon&&(0,t.jsx)("span",{className:"text-(length:--text-nano) text-muted-foreground",children:"Coming soon"})]},d.value))})]})}r(v_e,"AdapterTypeDropdown");function nre(){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(nre,"ExperimentalBadge$1");function IH({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:b,loadingModels:v,detectModelLabel:j,emptyDetectHint:N,defaultLabel:w,presentation:k="searchable",effort:S}){const[C,_]=(0,m.useState)(""),[R,A]=(0,m.useState)(!1),[T,E]=(0,m.useState)(!1),L=C.trim(),O=!!(u&&L&&!e.some(K=>K.id.toLowerCase()===L.toLowerCase())),P=(0,m.useMemo)(()=>{const K=new Set;h&&K.add(h);for(const W of p??[])W&&K.add(W);return K},[h,p]),U=(0,m.useMemo)(()=>e.filter(K=>{if(P.has(K.id))return!1;const W=EP(K.id);return sD({...YN(K,c),...W&&!K.provider?{group:W}:{}},C)}),[e,C,P,c]),M=(0,m.useMemo)(()=>new Map(e.map(K=>[K.id,YN(K,c)])),[e,c]),B=s?Hd(s,[...M.values()]):null,q=(0,m.useMemo)(()=>{if(!c&&U.some(W=>W.provider)){const W=new Map;for(const Q of U){const re=Q.provider??"other";W.set(re,[...W.get(re)??[],Q])}return Array.from(W.entries()).map(([Q,re])=>({provider:Q,entries:re}))}if(!c)return[{provider:null,entries:d?U:[...U].sort((W,Q)=>W.id.localeCompare(Q.id))}];const K=new Map;for(const W of U){const Q=EP(W.id)??"other",re=K.get(Q)??[];re.push(W),K.set(Q,re)}return Array.from(K.entries()).sort(([W],[Q])=>W.localeCompare(Q)).map(([W,Q])=>({provider:W,entries:[...Q].sort((re,J)=>re.id.localeCompare(J.id))}))},[U,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"),k==="native"){const K="__paperclip_custom_model__",W=[...new Set([s,...P])].filter(Q=>!!Q&&(!e.some(re=>re.id===Q)||P.has(Q)));return(0,t.jsxs)(ks,{label:"Model",hint:wi.model,children:[(0,t.jsxs)(nbe,{"aria-label":"Model","aria-busy":v||b,value:R?K:s,required:l&&!R,onChange:r(Q=>{const re=Q.target.value;A(re===K),re!==K&&n(re)},"onChange"),children:[(0,t.jsx)("option",{value:"",disabled:!o,children:o?w??"Default":v?"Loading models…":l?"Select model (required)":"Select model"}),W.map(Q=>(0,t.jsx)("option",{value:Q,children:e.find(re=>re.id===Q)?.label??Q},Q)),q.map(({provider:Q,entries:re})=>c?(0,t.jsx)("optgroup",{label:Q??void 0,children:re.map(J=>(0,t.jsx)("option",{value:J.id,children:J.label},J.id))},Q):re.map(J=>(0,t.jsx)("option",{value:J.id,children:J.label},J.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)(ut,{"aria-label":"Model ID",value:s,onChange:r(Q=>n(Q.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:b,onClick:r(()=>{x()},"onClick"),children:b?"Refreshing…":"Refresh models"})]})}return(0,t.jsx)(ks,{label:"Model",hint:wi.model,children:(0,t.jsxs)(ur,{open:a,onOpenChange:r(K=>{i(K),K||_("")},"onOpenChange"),children:[(0,t.jsx)(Nr,{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:[B?(0,t.jsx)(nx,{display:B,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&&Qy(S.value,s,[...M.values()])?(0,t.jsxs)("span",{className:V("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)(nn,{className:"size-4 shrink-0 text-muted-foreground"})]})}),(0,t.jsxs)(rr,{className:"w-(--radix-popover-trigger-width) p-1",align:"start",children:[S&&s&&Qy(S.value,s,[...M.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)(yD,{levels:Rg(s,[...M.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)(na,{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?US:"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?j?.replace(/^Detect\b/,"Re-detect")??"Re-detect from config":j??"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:b,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"})]}),b?"Refreshing...":"Refresh models"]}),s&&(!e.some(K=>K.id===s)||P.has(s))&&(0,t.jsxs)("button",{type:"button",className:V("flex items-center w-full px-2 py-1.5 text-sm rounded bg-accent/50"),onClick:r(()=>{i(!1)},"onClick"),children:[B?(0,t.jsx)(nx,{display:B,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:V("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 W=e.find(Q=>Q.id===K);return(0,t.jsxs)("button",{type:"button",className:V("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:W?.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:V("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(L),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:L})]}),q.map(K=>(0,t.jsxs)("div",{className:"mb-1 last:mb-0",children:[K.provider&&(0,t.jsx)(rD,{provider:K.provider,testId:`model-dropdown-group-${K.provider}`}),K.entries.map(W=>(0,t.jsxs)("button",{type:"button",className:V("flex items-center gap-2 w-full px-2 py-1.5 text-left text-sm rounded hover:bg-accent/50",W.id===s&&"bg-accent"),onClick:r(()=>{n(W.id),S&&Rg(W.id,[...M.values()]).length>0||i(!1)},"onClick"),children:[(0,t.jsx)(nD,{option:M.get(W.id)??YN(W,c)}),W.id===s?(0,t.jsx)(us,{className:"size-4 shrink-0","aria-hidden":"true"}):null]},W.id))]},K.provider??"")),U.length===0&&!O&&P.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?N??"No model detected yet. Enter a provider/model manually.":"No models found."})})]})]})]})})}r(IH,"ModelDropdown");function gct({value:e,options:s,onChange:n,open:a,onOpenChange:i}){const o=s.find(l=>l.id===e)??s[0];return(0,t.jsx)(ks,{label:"Thinking effort",hint:wi.thinkingEffort,children:(0,t.jsxs)(ur,{open:a,onOpenChange:i,children:[(0,t.jsx)(Nr,{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:V(!e&&"text-muted-foreground"),children:o?.label??"Auto"}),(0,t.jsx)(nn,{className:"h-3 w-3 text-muted-foreground"})]})}),(0,t.jsx)(rr,{className:"w-(--radix-popover-trigger-width) p-1",align:"start",children:s.map(l=>(0,t.jsxs)("button",{className:V("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(gct,"ThinkingEffortDropdown");function y_e(e){const s=`paperclip.agent-appearance.${e}`;function n(){try{const l=Lge.safeParse(JSON.parse(sessionStorage.getItem(s)??"null"));if(l.success)return l.data}catch{}const o=WE();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(y_e,"useAgentAppearanceDraft");var qC=null,OT=new Set,UC={subscribe(e){return OT.add(e),()=>{OT.delete(e)}},getSnapshot(){return qC},acquire(e){if(qC)return!1;qC=e;for(const s of OT)s();return!0},release(e){if(qC===e){qC=null;for(const s of OT)s()}}};function Wk({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)(()=>Db(s??e?.appearance,e?.id),[s,e?.appearance,e?.id]),b=(0,m.useRef)(null),v=(0,m.useRef)(null),j=(0,m.useRef)(null),N=(0,m.useRef)(Symbol("agent-character")),w=(0,m.useSyncExternalStore)(UC.subscribe,UC.getSnapshot,()=>null),[k,S]=(0,m.useState)(!1),[C,_]=(0,m.useState)(!0),[R,A]=(0,m.useState)(!1),[T,E]=(0,m.useState)(!1),L=!x.customAvatarAssetId&&k&&!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)"),P=r(()=>_(O.matches),"change");P(),O.addEventListener("change",P);const U=new IntersectionObserver(M=>S(M[0]?.isIntersecting??!1));return b.current&&U.observe(b.current),()=>{U.disconnect(),O.removeEventListener("change",P)}},[]),(0,m.useEffect)(()=>{L&&w===null&&UC.acquire(N.current),L||UC.release(N.current)},[L,w]),(0,m.useEffect)(()=>()=>UC.release(N.current),[]),(0,m.useEffect)(()=>{if(!L||w!==N.current)return;let O=!1;return E(!1),Promise.all([Id(()=>import("./runtime-IAg0vdY9.js"),__vite__mapDeps([0,1])),Id(()=>import("./definition-CjvFnh6k.js"),__vite__mapDeps([2,3,1]))]).then(([P,U])=>{O||!v.current||(j.current=P.createCharacter(v.current,U.characterDefinition(x,i),{animation:U.animationId(a),trackingRegion:l?.current??b.current??void 0,followCursor:d,followRotation:u,trackingScope:c,displaySize:n,onError:r(()=>A(!0),"onError")}),E(!0))}).catch(()=>{O||A(!0)}),()=>{O=!0,j.current?.destroy(),j.current=null,E(!1)}},[L,w,l,c,n,d,u]),(0,m.useEffect)(()=>{j.current&&Id(()=>import("./definition-CjvFnh6k.js").then(O=>{j.current?.setDefinition(O.characterDefinition(x,i)),j.current?.setAnimation(O.animationId(a))}),__vite__mapDeps([2,3,1]))},[x,i,a,T]),(0,t.jsxs)("span",{ref:b,role:p?"img":void 0,"aria-label":p,"aria-hidden":p?void 0:!0,className:V("relative inline-block shrink-0",p6e[n],h),children:[(0,t.jsx)(or,{agent:e,appearance:x,size:n<256?256:n,name:f,pose:a,muted:i,className:V("size-full",T&&!x.customAvatarAssetId&&"invisible")}),(0,t.jsx)("span",{ref:v,className:"absolute inset-0"})]})}r(Wk,"AgentCharacter");var bct=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?bct.has(e):!0}r(j_e,"isNewAgentAdapterAllowed");function vct(){const{selectedCompanyId:e}=ps(),{appearance:s}=y_e(`${e}:new-agent`);return(0,t.jsx)(Wk,{appearance:s,state:"sleepy",muted:!0,size:256,className:"size-48",trackingScope:"page"})}r(vct,"AgentBasicsCharacter");function w_e({open:e,onClose:s,onContinue:n,initialAdapter:a="",onInvite:i}){const o=(0,m.useId)(),l=!!Yc(),c=te({queryKey:D.instance.experimentalSettings,queryFn:vr.getExperimental,enabled:e,retry:!1}),[d,u]=(0,m.useState)(""),[h,p]=(0,m.useState)(a),[f,x]=(0,m.useState)("codex"),[b,v]=(0,m.useState)("name"),{data:j,isPending:N,error:w}=te({queryKey:D.adapters.all,queryFn:Sh.list,enabled:e}),k=(j??[]).filter(C=>C.loaded&&!C.disabled&&j_e(C.type,{cloud:l,nativeRunnerEnabled:c.data?.enableNativeRunner===!0})&&!["process","http"].includes(C.type)&&!Um(C.type).comingSoon),S=k.some(C=>C.type===h);return(0,t.jsx)(zs,{open:e,onOpenChange:r(C=>{C||s()},"onOpenChange"),children:(0,t.jsxs)(Ws,{className:V("flex max-h-(--sz-calc-18) flex-col gap-0 overflow-hidden p-0 sm:max-w-(--sz-640px)",b==="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:V(b==="name"&&"font-medium text-foreground"),children:"1. Name"}),(0,t.jsx)(Pn,{className:"size-3"}),(0,t.jsx)("span",{className:V(b==="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()&&(b==="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)(vct,{}),(0,t.jsxs)("div",{className:"space-y-2",children:[(0,t.jsx)(Vs,{className:"text-3xl font-semibold tracking-tight",children:b==="name"?"Meet your next agent":"Choose an adapter"}),(0,t.jsx)(hn,{className:"text-base",children:b==="name"?"Start with a name. Make them your own.":`How should ${d.trim()} work?`})]})]}),b==="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)(ut,{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"}),N&&(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:V("grid grid-cols-2 gap-3",k.length!==4&&"sm:grid-cols-3"),children:k.map(C=>{const _=Um(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:V("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)(Ap,{type:C.type}),(0,t.jsx)("span",{className:"text-sm font-medium",children:_.label}),h===C.type&&(0,t.jsx)(us,{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(()=>b==="name"?s():v("name"),"onClick"),children:b==="name"?"Cancel":(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)(jl,{className:"size-4"}),"Back"]})}),(0,t.jsxs)($,{type:"submit",disabled:!d.trim()||b==="adapter"&&!S,children:[b==="name"?"Choose adapter":"Configure agent",(0,t.jsx)(ml,{className:"size-4"})]})]})]})]})})}r(w_e,"AgentBasicsDialog");var yct={subscription:"Subscription",api:"API key",advanced:"Custom Gateway"};function jct({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)(qS,{initial:!1,mode:"sync",children:(0,t.jsx)(Tl.span,{className:"absolute inset-0 flex items-center justify-center whitespace-nowrap",initial:{opacity:0,y:bne},animate:{opacity:1,y:0,transition:Wnt},exit:{opacity:0,y:bne,transition:Vnt},children:yct[e]},e)})})}r(jct,"CredentialTag");function wct({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:V("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)(jct,{mode:s}):(0,t.jsx)("span",{"aria-hidden":!0,className:"h-4"})]})}r(wct,"ModelSourceTile");function N_e({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:V("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)(qS,{initial:!1,mode:"popLayout",children:u.map(h=>(0,t.jsx)(Tl.div,{layout:!0,transition:N1e,exit:{opacity:0,transition:srt},className:V("flex min-w-0",o?"w-(--sz-source-tile-two-up)":"flex-1"),children:(0,t.jsx)(wct,{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(N_e,"ModelSourceTiles");var uF={subscription:"Use subscription instead",api:"Use API key instead"},Nct=["subscription","api"],rre={subscription:"api",api:"subscription"};function k_e({mode:e,onChange:s}){return(0,t.jsx)(kct,{destination:rre[e],onClick:r(()=>s(rre[e]),"onClick"),modes:Nct})}r(k_e,"CredentialModeLink");function kct({destination:e,onClick:s,modes:n}){return(0,t.jsxs)("button",{type:"button","aria-label":uF[e],onClick:s,className:V("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:uF[a]},a)),(0,t.jsx)(qS,{initial:!1,mode:"sync",children:(0,t.jsx)(Tl.span,{className:V("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:fH},exit:{opacity:0,transition:Hnt},children:uF[e]},e)})]})}r(kct,"ModeLink");function RU({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)(jl,{className:"mr-1 size-3.5"}),"Back"]}):(0,t.jsx)("span",{}),(0,t.jsx)(Tl.div,{layout:!0,transition:Ynt,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)(Tl.span,{className:"flex items-center whitespace-nowrap",initial:{opacity:0},animate:{opacity:1},transition:Jnt,children:[d==="spinner"?(0,t.jsx)(tt,{className:"mr-1 size-4 animate-spin"}):null,c,d==="arrow"?(0,t.jsx)(ml,{className:"ml-1 size-3.5"}):null]},`${c}:${d}`)})})]})}r(RU,"FooterNav");function S_e({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:yu.get,enabled:i}),x=i&&(f.data?.localAiLoginSupported??f.data?.deploymentMode==="local_trusted"),b=(0,m.useRef)(0);(0,m.useEffect)(()=>()=>{b.current++},[]);const v=r(()=>{b.current++,U(!1),C(!1),R(null),T("preparing")},"cancel"),[j,N]=(0,m.useState)(h?.initialMethod==="api_key"?"api":h?"subscription":null),[w,k]=(0,m.useState)(!1),[S,C]=(0,m.useState)(!!(p||h)),[_,R]=(0,m.useState)(null),[A,T]=(0,m.useState)("preparing"),E=(0,m.useRef)("ready"),[L,O]=(0,m.useState)(""),[P,U]=(0,m.useState)(!1),[M,B]=(0,m.useState)(null),[q,z]=(0,m.useState)(null),K=s==="claude_local"?"Claude":s==="grok_local"?"Grok":"OpenAI",W=s==="claude_local"?"ANTHROPIC_API_KEY":s==="grok_local"?"XAI_API_KEY":"OPENAI_API_KEY",Q=s==="claude_local"?"anthropic":s==="grok_local"?"xai":"openai",re=e1e(e,W),J=h?{...re,options:[],subscriptions:[],loading:!1}:re,[ie,X]=(0,m.useState)(null),ne=J.subscriptions.length?J.subscriptions.find(Ee=>Ee.id===(ie??J.subscriptions[0]?.id)):void 0,[oe,G]=(0,m.useState)(null),Z=J.options.find(Ee=>Ee.id===(oe??J.options[0]?.id)),Y=h?{...J.storedLogin,data:void 0,isPending:!1,isError:!1}:J.storedLogin,ae=(0,m.useRef)(null),se=j??(J.subscriptions.length>0||s==="claude_local"&&!ne&&Y.data?"subscription":J.options.length?"api":"subscription"),ce=se==="api"?"api_key":"subscription",pe=h?.intent.connectionId&&(h.fixedMethod!==!1||h.initialMethod===ce),we=h?{...h.intent,connectionId:pe?h.intent.connectionId:void 0,name:pe?h.intent.name:h.nameForMethod?.(ce)??h.intent.name}:void 0,Se=bSe(e,we??{provider:Q,method:"subscription",name:`My ${K} subscription`,ownership:"personal",agentIds:[],allAgents:!0},!w&&x&&se==="subscription"&&!ne&&!Y.data),Te=te({queryKey:D.agents.authSignal(e,s,n),queryFn:r(()=>Ct.getAdapterAuthSignal(e,s,n??void 0),"queryFn"),retry:!1,enabled:!h&&!w});async function le(){if(P||h?.disabled)return;const Ee=++b.current;U(!0),B(null);try{if(h&&we){if(se==="subscription"&&!x)return;const Ie=ae.current??await(se==="api"?El.create(e,{...we,method:"api_key",apiKey:L.trim()}):Se.connect(we));ae.current=Ie,O(""),Ee===b.current&&h.onComplete({...Ie,method:se==="api"?"api_key":"subscription"});return}let Me=se==="api"?Z?Z.aiConnection?{env:{},aiConnection:Z.aiConnection}:{env:{[W]:Z.binding}}:q??{env:{},credentials:{[W]:L.trim()}}:{...ne?.aiConnection?{aiConnection:ne.aiConnection}:{},env:ne?.binding?{CODEX_HOME:ne.binding}:{},...s==="claude_local"&&!ne&&Y.data?{env:kN(),applyStoredClaudeLogin:!0}:{}};if(se==="subscription"&&x&&!ne&&!Y.data&&(ae.current??=await Se.connect(),Me={env:{},aiConnection:{provider:Q,method:"subscription",mode:"responsible_user"}}),Me.credentials&&(await El.create(e,{provider:Q,method:"api_key",name:`My ${K} API`,ownership:"personal",apiKey:Me.credentials[W],agentIds:[],allAgents:!0}),Me={env:{},aiConnection:{provider:Q,method:"api_key",mode:"responsible_user"}}),Ee!==b.current)return;se==="api"&&(O(""),Z||z(Me));const ve=await d(Me);if(Ee!==b.current)return;ve?o(Me):B("The provider did not respond. Check the connection and try again.")}catch(Me){if(Ee!==b.current)return;h&&O(""),B(Me instanceof Error?Me.message:"Could not connect to the provider.")}finally{Ee===b.current&&U(!1)}}r(le,"connect");const fe=se==="subscription"&&a&&n&&!ne&&!J.loading&&!Y.data&&(!!h||Te.data?.status!=="present"||ie===""),de=r(Ee=>{p&&Ee===(w?"advanced":se)||(l?.(),v(),k(Ee==="advanced"),C(p?!0:S),ae.current=null,Ee!=="advanced"&&N(Ee),O(""),z(null),B(null))},"switchMode");return(0,t.jsxs)("div",{className:"min-w-0 max-w-full",children:[(0,t.jsx)(N_e,{label:p?"Connection type":"Connect your model provider",sources:p?[{id:"subscription",label:K,icon:(0,t.jsx)(Ap,{type:s}),credentialMode:"subscription"},{id:"api",label:K,icon:(0,t.jsx)(Ap,{type:s}),credentialMode:"api"},{id:"advanced",label:"Advanced",icon:(0,t.jsx)(kKe,{className:"size-6 text-muted-foreground"}),credentialMode:"advanced"}]:[{id:s,label:K,icon:(0,t.jsx)(Ap,{type:s})}],mode:w?"advanced":se,selectedId:p?w?"advanced":se:S?s:null,collapsed:!p&&S,onSelect:r(Ee=>{h?.disabled||(p?de(Ee):C(!0))},"onSelect")}),!p&&(!S||h)&&!h?.fixedMethod&&(0,t.jsx)("div",{className:"-ml-3 mt-1",children:(0,t.jsx)(k_e,{mode:se,onChange:de})}),w&&p?(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)("div",{className:"pt-5",children:p.content}),(0,t.jsx)(RU,{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&&J.options.length>0&&(0,t.jsxs)("p",{className:"mt-2 text-sm text-muted-foreground",children:[J.options.length," saved API"," ",J.options.length===1?"key available":"keys available","."]}),se==="subscription"&&J.subscriptions.length>0&&(0,t.jsx)("div",{className:p?"pt-5":void 0,children:(0,t.jsx)(GN,{options:J.subscriptions,value:ne?.id??"",onChange:r(Ee=>{l?.(),X(Ee)},"onChange"),loading:!1,error:!1,kind:"subscription",disabled:P})}),(0,t.jsx)(Tl.div,{initial:!1,animate:{height:S?"auto":0,opacity:S?1:0},transition:{height:zd,opacity:ND},className:"overflow-hidden",children:S&&(0,t.jsx)("div",{className:"pt-5",children:se==="api"?(0,t.jsxs)(kD,{instruction:J.options.length?"Choose a saved API key or enter a new one":`Provide your ${K} API key to connect`,children:[(0,t.jsx)(GN,{...J,value:Z?.id??"",disabled:P,onChange:r(Ee=>{l?.(),G(Ee),O(""),z(null),B(null)},"onChange")}),!Z&&(0,t.jsx)(s2,{label:"API key",masked:!0,autoFocus:!0,value:L,placeholder:q?"Key entered. Retry the connection.":"Enter API key here",onChange:r(Ee=>{l?.(),G(""),O(Ee),z(null)},"onChange"),onSubmit:r(()=>{le()},"onSubmit"),disabled:P})]}):fe?(0,t.jsx)(_H,{companyId:e,adapterType:s,environmentId:n,chrome:"onboarding",aiConnection:we??{provider:Q,method:"subscription",name:`My ${K} subscription`,ownership:"personal",agentIds:[],allAgents:!0},autoStart:!0,onStored:r(()=>{},"onStored"),onPromptReady:r(Ee=>{R(Ee),T(Me=>Ee?Me==="preparing"?"ready":Me:"preparing")},"onPromptReady"),onCodeSubmitted:r(()=>{E.current=A==="waiting"?"waiting":"ready",T("connecting")},"onCodeSubmitted"),onSubmitFailed:r(()=>{T(Ee=>Ee==="connecting"?E.current:Ee)},"onSubmitFailed"),onConnected:r(Ee=>{if(h){if(!Ee){B("The login did not return a saved connection. Try again.");return}const ve=b.current;T("connecting"),El.loginResult(e,Ee).then(Ie=>{ve===b.current&&h.onComplete({...Ie,method:"subscription"})}).catch(()=>{ve===b.current&&(T("ready"),B("Could not retrieve the saved connection. Go back and retry."))});return}const Me={env:{},aiConnection:{provider:Q,method:"subscription",mode:"responsible_user"}};z(Me),o(Me)},"onConnected")}):ne?null:x&&!Y.data?(0,t.jsx)(bH,{adapterType:s,login:{...Se,retry:r(()=>{B(null),Se.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."}),M&&(0,t.jsx)("p",{role:"alert",className:"mt-4 text-sm text-destructive",children:u??M}),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)(RU,{onBack:r(()=>{S&&!p?v():c()},"onBack"),primaryLabel:S&&fe?A==="waiting"?"Waiting for code":A==="connecting"?"Connecting":`Sign in to ${K}`:P?"Connecting":se==="subscription"&&(Y.data||ne)?"Use saved subscription":se==="api"&&Z?"Use saved API key":"Connect",primaryDisabled:h?.disabled||!!h&&se==="subscription"&&!a&&!x||i&&f.isPending||Se.preparing||!!Se.error||se==="subscription"&&x&&!ne&&!Y.data&&Se.status!=="ready"||!h&&Te.isPending||J.loading||s==="claude_local"&&Y.isPending||!S&&!(se==="subscription"&&ne)||!!fe&&(!_||A!=="ready")||se==="api"&&!L.trim()&&!q&&!Z,loading:P,primaryIcon:S&&fe?A==="ready"?"none":"spinner":void 0,onPrimary:r(()=>{if(fe){if(!_||A!=="ready")return;window.open(_,"_blank","noreferrer,noopener"),T("waiting")}else le()},"onPrimary")})]})]})}r(S_e,"AgentProviderConnection");function CI(e){return e.provider==="openrouter"||e.provider==="google"?(0,t.jsx)(Cct,{...e}):(0,t.jsx)(Sct,{...e})}r(CI,"AiConnectionCredentialStep");function Sct({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:b,disabled:v}){const[j,N]=(0,m.useState)(o),[w,k]=(0,m.useState)(),S=Nt(),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:vr.get}),A=te({queryKey:D.instance.experimentalSettings,queryFn:vr.getExperimental}),T=te({queryKey:D.instance.generalSettings,queryFn:vr.getGeneral}),E=CH(T.data?.executionMode,C.data??[]);let L=null,O;try{L=E.forced?E.kubernetesEnvironment?.id??null:Bk({agentDefaultEnvironmentId:p??w,instanceDefaultEnvironmentId:R.data?.defaultEnvironmentId,localDefaultEnvironmentId:qk(C.data),managedSandboxOnly:A.data?.enableManagedSandboxOnly,managedSandboxEnvironmentId:zk(C.data),visibleEnvironmentIds:C.data?.map(W=>W.id)})}catch(W){O=W instanceof Error?W.message:"Could not resolve the sign-in environment."}const P=(C.data??[]).filter(W=>W.status==="active"&&(W.driver==="local"||W.driver==="sandbox"&&typeof W.config.provider=="string"&&_.data?.sandboxProviders?.[W.config.provider]?.supportsLoginPty===!0));!E.forced&&!p&&!w&&!P.some(W=>W.id===L)&&(L=P[0]?.id??null);const U=C.data?.find(W=>W.id===L),M=typeof U?.config.provider=="string"?U.config.provider:"",B=U?.driver==="sandbox"&&_.data?.sandboxProviders?.[M]?.supportsLoginPty===!0,q=[C,_,R,A,T].some(W=>W.isPending),z=O??[C,_,R,A,T].find(W=>W.error)?.error?.message,K={provider:s,method:"subscription",name:j,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)(ut,{value:j,onChange:r(W=>N(W.target.value),"onChange"),disabled:!!i})]}),!p&&!E.forced&&P.length>1&&(0,t.jsxs)(ka,{value:L??"",onValueChange:k,children:[(0,t.jsx)(wa,{"aria-label":"Sign-in environment",children:(0,t.jsx)(Na,{placeholder:"Sign-in environment"})}),(0,t.jsx)(Sa,{children:P.map(W=>(0,t.jsx)(dn,{value:W.id,children:W.name},W.id))})]}),z&&(0,t.jsx)("p",{role:"alert",className:"text-sm text-destructive",children:z}),b,q?(0,t.jsx)("p",{role:"status",className:"text-sm text-muted-foreground",children:"Preparing sign-in…"}):(0,t.jsx)(S_e,{companyId:e,adapterType:s==="anthropic"?"claude_local":s==="xai"?"grok_local":"codex_local",environmentId:L,canLogin:B,localEnvironment:U?.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||!j.trim(),onComplete:r(W=>{S.invalidateQueries({queryKey:["ai-connections",e]}),S.invalidateQueries({queryKey:["tools"]}),f(W)},"onComplete")}},L??"local")]})}r(Sct,"SubscriptionConnectionStep");function Cct({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,b]=(0,m.useState)(a),[v,j]=(0,m.useState)(""),N=Nt(),w=ye({mutationFn:r(()=>El.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(k=>{N.invalidateQueries({queryKey:["ai-connections",e]}),N.invalidateQueries({queryKey:["tools"]}),u({...k,method:"api_key"})},"onSuccess"),onSettled:r(()=>j(""),"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)(ut,{value:x,onChange:r(k=>b(k.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)(C1e,{providerName:s==="google"?"Google":"OpenRouter",value:v,onChange:j,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(Cct,"ApiKeyConnectionStep");var _ct=null;function Rj(){const e=(0,m.useContext)(pA),{data:s,isFetched:n,isError:a}=te({queryKey:D.instance.experimentalSettings,queryFn:r(()=>vr.getExperimental(),"queryFn"),enabled:e!=null},e??(_ct??=new vS));return e?{enabled:!a&&s?.enableChatConnectors===!0,githubEnabled:!a&&s?.enableGitHubReviewBots===!0,loaded:n}:{enabled:!1,githubEnabled:!1,loaded:!0}}r(Rj,"useChatConnectorsEnabled");function Mf(e,s,n){return e==="agentmail"||(e==="github"||e==="github-code-review-bot"?n:s)}r(Mf,"chatProviderVisible");var Ict=new RegExp(`\\b(${["mcp","server","profile","policy","gateway","transport","stdio","endpoint"].join("|")})s?\\b`,"gi");function C_e(e){return e.replace(Ict,"").replace(/\s{2,}/g," ").replace(/\s+([.,])/g,"$1").trim()}r(C_e,"sanitizeProsumerCopy");var Act={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."}},Tct={tagline:"Give your agents access to this app.",short:"Give your agents access to this app."};function __e(e,s){const n=Act[e];if(n)return n;if(s){const a=C_e(s);if(a)return{tagline:a,short:a}}return Tct}r(__e,"appCopyFor");function are(e,s,n){return n<=1?`Your ${e} key`:C_e(s)||`Your ${e} key`}r(are,"credentialFieldLabel");var Rct="/cloud/connections/handoff",Ect="/cloud/connections/reauth",OP="paperclip.cloud-oauth-handoff.v1",xg=class extends Error{static{r(this,"OAuthHandoffError")}code;constructor(e,s){super(e),this.code=s,this.name="OAuthHandoffError"}};function AH(e){if(e===void 0)return null;if(!e||typeof e!="object"||Array.isArray(e))throw new xg("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 xg("Paperclip Cloud returned an invalid sign-in handoff.","invalid_handoff");return{kind:"paperclip_cloud",session:s.session}}r(AH,"parseHandoff");function Pct(e,s){return e===404||s==="SESSION_NOT_AVAILABLE"?new xg("This sign-in expired. Start the connection again.","expired"):e===401||e===403?new xg("Paperclip Cloud could not authorize this connection for your account.","forbidden"):new xg("Paperclip Cloud couldn’t prepare secure sign-in. Try again.","unavailable")}r(Pct,"handoffFailure");async function Mct(e,s){const n=s.request??fetch;let a,i;for(let o=0;o<2;o+=1)try{if(a=await n(Rct,{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 xg(i instanceof Error?i.message:"Paperclip Cloud couldn’t prepare secure sign-in. Try again.","unavailable")}r(Mct,"postCloudHandoff");function Dct(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!==Ect||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(Dct,"exactReauthenticationTarget");async function Vk(e,s={}){const n=AH(e.handoff);if(!n){const l=mP(e.authorizationUrl);if(!l.ok)throw new xg(l.message,"invalid_handoff");return{kind:"authorization",url:l.url,host:l.host}}const a=await Mct(n.session,s),i=await a.json().catch(()=>null);if(!a.ok){if(i?.error==="RECENT_LOGIN_REQUIRED"){const l=Dct(i.reauthenticationUrl,n.session);if(l)return l}throw Pct(a.status,i?.error)}const o=mP(typeof i?.authorizationUrl=="string"?i.authorizationUrl:void 0);if(!o.ok)throw new xg("Paperclip Cloud returned an invalid provider sign-in address.","invalid_handoff");return{kind:"authorization",url:o.url,host:o.host}}r(Vk,"prepareOAuthNavigation");function _I(e,s=window.sessionStorage){const n=AH({kind:"paperclip_cloud",session:e});if(!n)throw new xg("Paperclip Cloud returned an invalid sign-in handoff.","invalid_handoff");const a={version:1,session:n.session,savedAt:Date.now()};s.setItem(OP,JSON.stringify(a))}r(_I,"savePendingCloudHandoff");function Lct(e=window.sessionStorage){const s=e.getItem(OP);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 AH({kind:"paperclip_cloud",session:n.session})}catch{return e.removeItem(OP),null}}r(Lct,"readPendingCloudHandoff");function ire(e=window.sessionStorage){e.removeItem(OP)}r(ire,"clearPendingCloudHandoff");function AD(e){return!!(e&&hge({...e,methods:e.methods.filter(s=>(s.purpose??"tool")!=="channel"&&s.transport!=="chat_sdk")}))}r(AD,"appSupportsToolCatalogSetup");var $ct=MFe.filter(e=>wge(e).some(s=>gp(s))).map(e=>e.slug);function Oct(e){return $ct.some(s=>s===e)}r(Oct,"isMcpDirectOAuthConnectSlug");function II(e,s){const n=new URLSearchParams({source:e});return s&&n.set("intent",s),`/apps/connect?${n.toString()}`}r(II,"appSourceConnectHref");function ore(e,s){return`/apps/connect?${new URLSearchParams({source:e,resume:s}).toString()}`}r(ore,"appSourceResumeHref");function mF(e){return e?`/apps/vercel-connect?${new URLSearchParams({source:e}).toString()}`:"/apps/vercel-connect"}r(mF,"vercelConnectSourceHref");function Fct(e){return e.serviceSlug??e.appKey??e.sourceSlug??void 0}r(Fct,"resolveAppsConnectRouteKey");function Bct(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=pS(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:Ly(a)&&(e.get("reconnect")?.trim()||e.get("resume")?.trim())?!0:a==="agentmail"||o?hge(i):AD(i)}r(Bct,"canEnterAppsConnect");var hF=" for the organization",zct=" for the company";function lre(e,s){const n=e.trim();if(s!=="organization")return n;const a=n.toLocaleLowerCase();return a.endsWith(hF)?n:a.endsWith(zct)?`${n.slice(0,n.length-16).trimEnd()}${hF}`:`${n}${hF}`}r(lre,"connectionNameForGrantKind");function qct(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(qct,"grantStatusLabel");function Uct(e){switch(e){case"active":return"connected";case"needs_reauthorization":case"expired":return"attention";case"revoked":return"inactive";default:return"missing"}}r(Uct,"grantStatusTone");function Kct(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(Kct,"grantAccountLabel");function Wct(e){return new Set((e?.members??[]).filter(s=>s.subjectType==="user").map(s=>s.subjectId))}r(Wct,"audienceUserIds");function Vct(e){return e.find(s=>s.kind==="organization"&&s.isDefault)??e.find(s=>s.kind==="organization")??null}r(Vct,"organizationGrant");function Hct(e,s){return s?e.find(n=>n.kind==="user"&&n.subjectUserId===s)??null:null}r(Hct,"personalGrantFor");function Qct(e,s){if(!s)return null;const n=e.find(a=>a.userId===s);return n&&(n.name?.trim()||n.email?.trim())||null}r(Qct,"memberLabel");var cre=0;function EU(){return cre+=1,{id:`header-${cre}`,name:"",value:""}}r(EU,"newCustomHeaderRow");function g_(e){try{return new URL(e).host||null}catch{return null}}r(g_,"endpointHost");function Gct(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(Gct,"oauthCallbackUrlForBrowser");function pF(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(pF,"defaultGenericMcpName");function dre(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(dre,"genericConnectGuidance");function I_e(e){const s=new Set;for(const n of e){const a=n.name.trim();if(!a&&!n.value.trim())continue;const i=IBe(a);if(!i.ok)return LZ(a,i.reason);const o=OBe(n.value);if(!o.ok)return LZ(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(I_e,"customHeaderError");function Yct(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(Yct,"genericConnectPayload");function Jct(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&&I_e(e.headers)===null:!0:!1}r(Jct,"canSubmitGenericConnect");function Hk(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(Hk,"installStateFrom");function A_e(e,s){return e.onAll||e.agentIds.has(s)}r(A_e,"isAgentInstalled");function T_e(e,s){return s.onAll?[{targetType:"company",targetId:e}]:[...s.agentIds].map(n=>({targetType:"agent",targetId:n}))}r(T_e,"installPayload");var Xct="Has access — tick to load its tools into this agent's context.";function R_e(e){return`paperclip.connector-enrollment-access:${e}`}r(R_e,"enrollmentAccessStorageKey");function Zct(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(Zct,"validEnrollmentAccessState");function edt(e,s,n){try{window.sessionStorage.setItem(R_e(s),JSON.stringify({...n,companyId:e}))}catch{}}r(edt,"saveEnrollmentAccessState");function tdt(e){const s=R_e(e);try{const n=window.sessionStorage.getItem(s);if(window.sessionStorage.removeItem(s),!n)return null;const a=JSON.parse(n);return Zct(a)?a:null}catch{return null}}r(tdt,"consumeEnrollmentAccessState");function ure(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(ure,"githubRecoveryUrl");function mre(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(mre,"oauthCallbackErrorMessage");var sdt={key:"setup",success:"complete"};function hre(e){return e.requestedAppKey||e.hasPrefilledLink||e.zapierSource?"key":"gallery"}r(hre,"requestedConnectionInitialStep");function ndt(e){const s=e.galleryApps.find(a=>a.slug===e.requestedAppKey);if(s)return s;if(E_e({requestedAppKey:e.requestedAppKey,resumeConnection:e.resumeConnection,resumeApplication:e.resumeApplication,completedResumeConnectionId:e.completedResumeConnectionId}))return Ly(e.requestedAppKey);if(!e.reconnectConnection)return null;const n=e.applications.find(a=>a.id===e.reconnectConnection?.applicationId);return sx(n)!==e.requestedAppKey?null:Ly(e.requestedAppKey)}r(ndt,"requestedConnectionEntry");function E_e(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&&sx(a)===s&&iu(n)===s)}r(E_e,"retainedResumeMatches");function rdt(e){return!e.reconnectConnection||!e.reconnectApplication||e.reconnectConnection.applicationId!==e.reconnectApplication.id?!1:e.requestedAppKey?sx(e.reconnectApplication)===e.requestedAppKey:e.byo&&e.applicationId===e.reconnectApplication.id}r(rdt,"retainedReconnectMatches");function adt(e){return e.credentialSource==="vercel_connect"&&!e.available&&!e.retainedReconnectMatches}r(adt,"isVercelConnectUnavailable");function idt(e){return e.available===!1&&!(e.reconnectConnectionId&&e.reconnectSourceMatches)}r(idt,"isConnectionDefinitionUnavailable");function odt(e){return!e.hasRequestedEntry||e.supportedMethodCount===0||e.unsupportedOAuth||e.vercelUnavailable||e.definitionUnavailable?e.reconnectConnectionId?"reconnect_unavailable":"fallback":"ready"}r(odt,"requestedConnectionSetupResolution");function pre(e,s,n,a){const i=sdt[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(pre,"appConnectHref");function FT(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(FT,"withConnectionIntent");var fre=["Pick app","Add your key"],xre={gallery:0,key:1},ldt={key:0},cdt=["Add MCP URL"],ddt=["Sign in"];function fF(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(fF,"defaultGrantKindFor");function udt(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(udt,"configuredAgentIdentity");function E1(e,s){const n=typeof s=="string"?s:s?.key;return e?.slug==="google-sheets"&&n==="local"}r(E1,"isGoogleSheetsRobotMethod");function KC(e){return e?Object.fromEntries([...e.tenantFields??[],...e.extensionFields??[]].filter(s=>s.defaultValue!==void 0).map(s=>[s.key,s.defaultValue])):{}}r(KC,"defaultMethodConfig");function aN(e,s){if(!e)return[];const n=a2(e);return s==="vercel_connect"?n.filter(a=>!!a.credentialSources?.vercelConnect):n}r(aN,"connectionMethodsForCredentialSource");function a2(e){return wge(e).filter(s=>(s.purpose??"tool")!=="channel")}r(a2,"availableToolConnectionMethods");function BT(e,s){const n=a2(e);return s?n.find(a=>a.key===s)??null:_9(n)}r(BT,"availableToolConnectionMethod");function XN(e){return _9(e)}r(XN,"recommendedSetupConnectionMethod");function gre(e){return XN(e?e.methods.filter(s=>(s.purpose??"tool")==="tool"&&(s.oauthStrategy==="paperclip_cloud_connector"||s.oauthStrategy==="paperclip_id_connector")):[])}r(gre,"recommendedManagedConnectorMethod");function bre(e){if(!e)return!1;const s=a2(e),n=s.length===1?s[0]:null;return!!(n&&gp(n)&&!UFe(n))}r(bre,"canUseAutomaticOAuthFastPath");function vre(e){if(!e)return null;const s=a2(e),n=s.length===1?s[0]:null;return n&&gp(n)?n:null}r(vre,"automaticOAuthMethod");function mdt(e){const s=e.metadata;if(!s)return null;const n=s.sourceTemplateKey??s.galleryKey;return typeof n=="string"?n:null}r(mdt,"appSourceSlug");function hdt(e){const s=e.config?.sourceTemplateKey??e.transportConfig.sourceTemplateKey;return typeof s=="string"?s:null}r(hdt,"connectionSourceSlug");function yre(e,s,n,a={}){if(!e)return null;const i=new Set(s.filter(o=>o.status!=="archived"&&mdt(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)||hdt(o)===e;return o.status!=="archived"&&(!a.draftOnly||o.status==="draft")&&o.authKind==="oauth"&&l})??null}r(yre,"reusableOAuthConnection");function P_e(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(P_e,"readConnectionIntentOAuthOutcome");function WS(e={}){const[s]=hi(),n=fa(),{selectedCompanyId:a}=ps(),i=CV(),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&&n_(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||n_(l)||H5(l))),h=te({queryKey:["tools","connection",d],queryFn:r(()=>es.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(H5(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"&&n_(p)&&(!f||KE(p,f))){const x=jge(p,s.get("targetToolkit"));return(0,t.jsx)(PJe,{...e,upstreamServiceName:e.upstreamServiceName??x?.name,interactionId:o,providerId:p,connection:h.data},`${o||"page"}:${p}`)}return(0,t.jsx)(pdt,{...e})}r(WS,"ConnectionSetupFlow");function pdt({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:b,aiConnection:v,requiredAiOwnership:j,onPhaseChange:N,onCancel:w,renderCredentialStep:k}={}){const S=Nt(),C=Gn(),_=(0,m.useCallback)((ct,fs)=>{o==="page"&&(fs?C(ct,fs):C(ct))},[o,C]),R=fa(),{selectedCompany:A,selectedCompanyId:T}=ps(),{enabled:E,githubEnabled:L}=Rj(),{enabled:O}=CV(),{setBreadcrumbs:P}=Hn(),{pushToast:U}=Ti(),[M]=hi(),B=d?.trim()||M.get("intent")?.trim()||null,q=R.appKey??M.get("appKey")??void 0,z=M.get("source")?.trim()||null,K=u||M.get("new")==="1",W=M.get("stage")?.trim()||null,Q=M.get("method")?.trim()||null,re=M.get("resume")?.trim()||null,J=M.get("oauth"),ie=M.get("code"),X=ure(M.get("installation_url")),ne=ure(M.get("management_url")),oe=p?.id??(M.get("reconnect")?.trim()||null),G=M.get("identity")==="user"?"user":M.get("identity")==="organization"?"organization":null,Z=i==="vercel_connect",Y=l??z,ae=i==="paperclip_vault"&&Oct(Y)?Y:null,se=Fct({serviceSlug:l,appKey:q,sourceSlug:z}),ce=(l??z??q)==="zapier",pe=ce?void 0:se,we=!!p||o==="page"&&(a||M.get("byo")==="1"),[Se]=(0,m.useState)(()=>o==="page"&&M.get("cloud_connector")==="enrolled"&&pe?tdt(pe):null),[Te]=(0,m.useState)(()=>{const ct=M.get("link")?.trim()??"";return{link:/^https?:\/\//i.test(ct)?ct:"",name:p?.name??M.get("name")?.trim()??"",applicationId:p?.applicationId??(M.get("applicationId")?.trim()||void 0)}}),[le,fe]=(0,m.useState)(()=>hre({requestedAppKey:pe,routeStage:W,resumeConnectionId:re,hasPrefilledLink:!!Te.link,zapierSource:ce})),[de,Ee]=(0,m.useState)(null),[Me,ve]=(0,m.useState)(""),[Ie,Ze]=(0,m.useState)(Te.link),[ue,Be]=(0,m.useState)(Te.name||(ce?"Zapier":"")),[ht,jt]=(0,m.useState)(!1),[Je,Fe]=(0,m.useState)(""),[it,At]=(0,m.useState)("auto"),[$t,zt]=(0,m.useState)(()=>[EU()]),[at,De]=(0,m.useState)(""),[Pe,dt]=(0,m.useState)(""),[rt,ft]=(0,m.useState)(!1),[kt,Ke]=(0,m.useState)(null),[$e,ze]=(0,m.useState)(!1),[et,ge]=(0,m.useState)({}),[st,Mt]=(0,m.useState)(""),[Ss,lt]=(0,m.useState)(""),[Ls,Ue]=(0,m.useState)(""),[xe,Ye]=(0,m.useState)(v&&v.mode!=="responsible_user"?`ai-${v.method}`:""),[gt,Ht]=(0,m.useState)(null),[mt,Bt]=(0,m.useState)({}),[Le,he]=(0,m.useState)(""),[Qt,Lt]=(0,m.useState)(null),[ss,Cs]=(0,m.useState)(null),[ln,mr]=(0,m.useState)({}),[pn,Ot]=(0,m.useState)("all"),[Es,Re]=(0,m.useState)(new Set),[wt,Oe]=(0,m.useState)(()=>new Set(Se?.agentIds??(c?[c]:[]))),[_t,Ut]=(0,m.useState)(Se?.grantKind??G??(c?"user":"organization")),[It,is]=(0,m.useState)(Se?.installChoice??(c?"specific":"all")),bs=!!(re&&(J==="failed"||J==="denied")),[Os,qs]=(0,m.useState)(bs?"error":"entry"),[Rn,Ns]=(0,m.useState)(()=>bs?mre(J,ie):null),[Yn,Xt]=(0,m.useState)(null),Hs=(0,m.useRef)(!1),rn=(0,m.useRef)(!1),Et=(0,m.useRef)(null),rs=(0,m.useRef)(null),[Zs,gs]=(0,m.useState)(null),[Js,kn]=(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),[kr,Or]=(0,m.useState)(h.length>0&&!!f),[Ur,xa]=(0,m.useState)(null),[ar,cr]=(0,m.useState)(null),[bt,He]=(0,m.useState)(null),Zt=(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]),ms=(0,m.useCallback)(ct=>{if(o!=="dialog"){Ym(ct);return}pr(ct);const fs=hr.current;if(!fs||fs.closed){qs("error"),Ns("Paperclip couldn’t open the sign-in window. Open sign-in in a new tab to continue."),N?.("needs_retry");return}fs.location.assign(ct),fs.focus()},[o,N]),_s=(0,m.useCallback)(()=>{hr.current=null,Ns(null),qs("redirecting"),N?.("authorizing")},[N]);(0,m.useEffect)(()=>{if(o!=="dialog"||Os!=="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),N?.("needs_retry"))},1e3);return()=>window.clearInterval(ct)},[o,Os,N]);const ts=(0,m.useCallback)(async ct=>{Cn.current?.abort();const fs=new AbortController;Cn.current=fs;try{const Ks=await Vk(ct,{signal:fs.signal});if(Ks.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.");_I(ct.handoff.session,Sn.sessionStorage),qs("starting")}else Xt(Ks.host),qs("redirecting");ms(Ks.url)}catch(Ks){if(fs.signal.aborted)return;qs("error"),Ns(Ks instanceof Error?Ks.message:"Paperclip couldn’t start secure sign-in. Try again."),N?.("needs_retry")}finally{Cn.current===fs&&(Cn.current=null)}},[o,N,ms]);(0,m.useEffect)(()=>()=>Cn.current?.abort(),[]),(0,m.useEffect)(()=>{if(o!=="dialog"||!B)return;const ct=r(fs=>{const Ks=P_e(fs,window.location.origin,B);if(Ks==="connected"){qs("entry"),pr(null),x?.({resolvedByCallback:!0});return}if(Ks==="declined"){qs("error"),Ns("Authorization was cancelled. You can try again."),N?.("needs_retry");return}Ks==="failed"&&(qs("error"),Ns("Authorization did not complete. Try again when you’re ready."))},"receiveOAuthOutcome");return window.addEventListener("message",ct),()=>window.removeEventListener("message",ct)},[B,o,x,b]),(0,m.useEffect)(()=>{if(o!=="dialog"||B||!qn)return;let ct=!1,fs=!1;const Ks=window.setInterval(async()=>{if(fs||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 Xn;try{Xn=new URL(Sn.location.href)}catch{return}if(!(Xn.origin!==window.location.origin||!Xn.pathname.includes(qn))){if(Xn.searchParams.has("oauth")){qr(null),qs("error"),Ns("Authorization did not complete. Finish setup in the sign-in window or try again.");return}if(Xn.searchParams.get("success")==="1"){fs=!0;try{const wn=await es.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{fs=!1}}}},1e3);return()=>{ct=!0,window.clearInterval(Ks)}},[B,qn,o,x]);const ws=r(()=>{At("auto"),zt([EU()]),De(""),dt(""),ft(!1),Ke(null),ze(!1)},"resetGenericAuthState"),Nn=r(ct=>{if(o==="page"&&!B&&i==="paperclip_vault"&&n_(ct.slug)){_(`/apps/connect?source=${ct.slug}`);return}if(ct.slug==="zapier"){Ee(null),ve(""),Ze(""),Be("Zapier"),jt(!1),Fe(""),ws(),ge({}),Cs(null),fe("key"),_(FT("/apps/connect?source=zapier",B));return}if(i==="paperclip_vault"&&bre(ct)){_(II(ct.slug,B));return}Ee(ct),ve(ct.name),Ze(""),Be(""),jt(!1),Fe(""),ws(),ge({}),Mt(""),lt(""),Ue("");const fs=XN(aN(ct,i));Ye(fs?.key??""),Bt(KC(fs)),he(""),Lt(null),Cs(null),Oe(new Set(c?[c]:[])),is(c?"specific":"all"),Ut(Ae??fF(fs,!!c)),fe("key"),_(i==="vercel_connect"?FT(mF(ct.slug),B):II(ct.slug,B))},"useMatchedGalleryEntry"),vn=r(()=>{fe("gallery"),_(FT(i==="vercel_connect"?mF():a?"/apps/byo":"/apps",B))},"backToGallery");(0,m.useEffect)(()=>{if(o==="page")return P([{label:"Connectors",href:"/apps"},{label:Z?"Vercel Connect":a?"Connect your own tool":"Connect an app"}]),()=>P([])},[a,o,P,Z]);const Un=te({queryKey:D.apps.gallery(T??"__none__"),queryFn:r(()=>es.listGallery(T),"queryFn"),select:(0,m.useCallback)(ct=>B||v?{...ct,apps:ct.apps.map(fs=>({...fs,methods:fs.methods.filter(Ks=>v?Ks.ai?.provider===v.provider&&(v.mode==="responsible_user"||Ks.ai.method===v.method):Ks.transport!=="runtime_auth")})).filter(fs=>fs.methods.length>0)}:ct,[B,v?.provider,v?.method,v?.mode]),enabled:!!T}),pt=Gct(window.location.origin,Un.data?.oauthCallbackUrl),Is=(0,m.useMemo)(()=>(Un.data?.apps??[]).filter(ct=>O||!H5(ct.slug)).filter(ct=>Mf(ct.slug,E,L)||!ct.methods.some(fs=>fs.transport==="chat_sdk")||AD(ct)),[Un.data,E,L,O]),cn=pe?Ly(pe):null,_n=cn?.methods.find(ct=>LN(ct)&&!gp(ct)),fn=!(_n&&xe===_n.key)&&!!cn?.methods.some(ct=>ct.oauthStrategy==="paperclip_cloud_connector"||ct.oauthStrategy==="paperclip_id_connector"),Sr=!!de?.methods.some(ct=>ct.oauthStrategy==="paperclip_cloud_connector"||ct.oauthStrategy==="paperclip_id_connector"),aa=de&&fn&&!Sr?gre(cn):null,[Da,As]=(0,m.useState)(null),an=te({queryKey:["cloud-connector","enrollment"],queryFn:r(()=>es.getCloudConnectorEnrollment(),"queryFn"),refetchInterval:Da?2e3:!1,enabled:!!(T&&fn&&!Sr)}),[Tr,Jn]=(0,m.useState)(null),Kn=(0,m.useCallback)(()=>{hr.current?.close(),hr.current=null,As(null)},[]),Vr=(0,m.useCallback)(()=>{!T||!pe||edt(T,pe,{grantKind:_t,installChoice:It,agentIds:It==="specific"?[...wt]:[]})},[_t,wt,It,pe,T]),Ps=(0,m.useCallback)(ct=>{const fs=mP(ct);if(!fs.ok){Kn(),Jn(fs.message);return}if(o==="dialog"){As(fs.url);const Ks=hr.current;Ks&&!Ks.closed?(Ks.location.assign(fs.url),Ks.focus()):Jn("Open authorization in a new tab to continue.");return}Ym(fs.url)},[o,Kn]);(0,m.useEffect)(()=>{!Da||an.data?.status!=="active"||(Kn(),Jn(null),Un.refetch())},[Da,an.data?.status,Un.refetch,Kn]);const jn=ye({mutationFn:r(()=>es.startCloudConnectorEnrollment(T,A?.name,pe?pre(pe,"key",i,{resumeConnectionId:re,reconnectConnectionId:oe,interactionId:B})+(o==="dialog"?"&enrollment_host=dialog":""):void 0),"mutationFn"),onSuccess:r(ct=>{if(!ct.verificationUrl){Kn(),Jn("Paperclip Cloud did not return an enrollment link. Try again.");return}Ps(ct.verificationUrl)},"onSuccess"),onError:r(ct=>{Kn(),Jn(ct instanceof Error?ct.message:"Paperclip couldn’t reach Paperclip Cloud. Try again.")},"onError")}),En=te({queryKey:D.tools.applications(T??"__none__"),queryFn:r(()=>es.listApplications(T),"queryFn"),enabled:!!T&&(!!ae||!!re||!!oe),refetchOnMount:"always"}),Fs=te({queryKey:D.tools.connections(T??"__none__"),queryFn:r(()=>es.listConnections(T),"queryFn"),enabled:!!T&&(!!ae||!!re||!!oe),refetchOnMount:"always"}),nr=(0,m.useMemo)(()=>u?null:yre(ae,En.data?.applications??[],Fs.data?.connections??[],K?{applicationId:Te.applicationId,draftOnly:!0}:{}),[En.data,Fs.data,K,ae,Te.applicationId,u]),un=(0,m.useMemo)(()=>oe?(Fs.data?.connections??[]).find(ct=>ct.id===oe)??null:null,[Fs.data,oe]),Gr=(0,m.useRef)(null);(0,m.useEffect)(()=>{if(!p||!Fs.isFetchedAfterMount||!un||Gr.current===un.id)return;const ct=un.config?.url??un.transportConfig?.url??un.transportConfig?.serverUrl??un.config?.serverUrl;typeof ct!="string"||!/^https?:\/\//i.test(ct)||(Gr.current=un.id,Ze(fs=>fs||ct))},[p,Fs.isFetchedAfterMount,un]);const _e=(0,m.useMemo)(()=>un?(En.data?.applications??[]).find(ct=>ct.id===un.applicationId)??null:null,[En.data,un]),Yt=rdt({requestedAppKey:pe,byo:we,applicationId:Te.applicationId,reconnectConnection:un,reconnectApplication:_e}),xn=(0,m.useMemo)(()=>re?(Fs.data?.connections??[]).find(ct=>ct.id===re)??null:null,[Fs.data,re]),Lr=(0,m.useMemo)(()=>xn?(En.data?.applications??[]).find(ct=>ct.id===xn.applicationId)??null:null,[En.data,xn]),ga=W==="complete"&&xn?.status==="active"?xn.id:null,Oa=pe?E_e({requestedAppKey:pe,resumeConnection:xn,resumeApplication:Lr,completedResumeConnectionId:Js??ga}):!1,hs=xn??un,Ae=hs?hs.credentialPolicy==="per_user"?"user":hs.credentialPolicy==="per_agent"?"agent":"organization":G,Vt=xn?.authKind==="oauth"?xn:nr,Jt=nr?nr.credentialPolicy==="per_user"?"user":nr.credentialPolicy==="per_agent"?"agent":"organization":null,Xs=Ae??Jt??(j==="shared"?"organization":null);(0,m.useEffect)(()=>{Xs&&Ut(Xs)},[Xs]);const gn=(0,m.useMemo)(()=>Ie&&!de?C5(Ie,Is):null,[de,Is,Ie]),_r=de?BT(de,xe||null):null,ei=_r&&gp(_r)?_r:vre(de),fr=i==="paperclip_vault"&&ei?de:null,Aa=i==="paperclip_vault"&&bre(de)?de:null,vi=!!ae&&(!En.isFetchedAfterMount||!Fs.isFetchedAfterMount),Va=r(ct=>{fe(ct),de&&_(pre(de.slug,ct,i,{connectionMethodKey:de.methods.find(fs=>fs.key===xe)?.ai?xe:void 0,resumeConnectionId:re,reconnectConnectionId:oe,interactionId:B}))},"setAppStep"),Er=xn??un??Vt,Mi=de?.agentInstructions,ir=de&&Mi?gt?.slug===de.slug?gt.value:Er?Er.agentInstructions??{...kk(Mi),enabled:!1}:kk(Mi):null,Hi=!ir||!!ir.text.trim(),al=ye({mutationFn:r(async ct=>(ir&&JSON.stringify(ir)!==JSON.stringify(ct.agentInstructions)&&await es.updateConnection(ct.id,{agentInstructions:ir}),es.startOAuth(ct.id,{asCurrentUser:ct.credentialPolicy==="per_user",...ct.credentialPolicy==="per_agent"?{asAgentId:udt(ct)??[...wt][0]}:{},...B?{interactionId:B}:{}})),"mutationFn"),onSuccess:r(ct=>{ts(ct)},"onSuccess"),onError:r(ct=>{const fs=ct instanceof mn&&ct.body&&typeof ct.body=="object"?ct.body.details:null;qs("error"),N?.("needs_retry"),Ns(fs?.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=al.mutate,Zi=(0,m.useCallback)(ct=>{N?.("authorizing"),Zt(),o==="dialog"&&!B&&qr(ct.id),So(ct)},[So,N,Zt,o,B]),be=r(async ct=>{if(c)return;const fs=T_e(T,(Xs??_t)!=="agent"&&It==="all"?{onAll:!0,agentIds:new Set}:{onAll:!1,agentIds:wt});await es.putConnectionInstalls(ct,fs)},"applyAccessInstalls"),xt=Xs??_t,cs=ye({mutationFn:r(async ct=>{const fs=ct??de;let Ks;if(fs){const Sn=Xs??_t,Xn=BT(fs,xe||null),wn=E1(fs,Xn)?D6(Le).ids:[],la=Me.trim(),Qa=lre(la||fs.name,Sn);Ks=await es.connectApp(T,{galleryKey:fs.slug,...ir?{agentInstructions:ir}:{},...xe?{connectionMethodKey:xe}:{},name:Qa,credentialSource:i,...i==="paperclip_vault"?{credentialValues:et}:{},...i==="vercel_connect"?{vercelConnect:{connector:Ls.trim()}}:{},...st.trim()?{oauthClient:{clientId:st.trim(),...Ss?{clientSecret:Ss}:{}}}:{},configValues:E1(fs,Xn)?{allowedSpreadsheetIds:wn}:Object.keys(mt).length>0?mt:void 0,applicationId:Te.applicationId,...re??Et.current?{resumeConnectionId:re??Et.current}:oe?{reconnectConnectionId:oe}:{},...Sn!=="organization"?{grantKind:Sn}:{},...Sn==="agent"?{subjectAgentId:[...wt][0]}:{}}),Et.current=null}else{const Sn=Yct({link:Ie,name:ue,authMode:it,needsKey:ht,keyValue:Je,headers:$t,oauthClientId:at,oauthClientSecret:Pe}),Xn=lre(Sn.name??pF(Ie)??"Custom app",xt);Ks=await es.connectApp(T,{...Sn,...oe?{reconnectConnectionId:oe}:{},...ce||gn?.slug==="zapier"?{galleryKey:"zapier",connectionMethodKey:"generated-url"}:{},name:Xn,applicationId:Te.applicationId,...xt!=="organization"?{grantKind:xt}:{},...xt==="agent"?{subjectAgentId:[...wt][0]}:{}})}return Ks.auth?.kind==="oauth"&&!re&&!oe&&await be(Ks.connectionId),Ks},"mutationFn"),onSuccess:r(ct=>{if(ct.auth?.kind==="oauth"){if(Cs(ct),ct.auth.manualClientRequired){Ke(dre("oauth_manual_client_required",null)),At("oauth"),ft(!0),ze(!1);return}if(o==="dialog"||B){qs("starting"),ze(!de),Zi(ct.connection);return}const Ks=ct.auth.startUrl?.trim();if(!Ks){qs("starting"),ze(!0),Zi(ct.connection);return}ze(!0),ts({authorizationUrl:Ks,handoff:ct.auth.handoff});return}Ke(null),Cs(ct);const fs={};for(const Ks of ct.actions.readOnly)fs[Ks.catalogEntryId]=!0;for(const Ks of ct.actions.canMakeChanges)fs[Ks.catalogEntryId]=!0;mr(fs),Ha.mutate({result:ct,enabled:fs})},"onSuccess"),onError:r(ct=>{const fs=ct instanceof mn&&ct.body&&typeof ct.body=="object"?ct.body.details:null;if(fr){qs("error"),N?.("needs_retry"),Ns(fs?.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(!de&&Ie){const Ks=typeof fs?.code=="string"?fs.code:null,Sn=dre(Ks,ct instanceof Error?ct.message:null);Ke(Sn),ze(!1),Sn.focus==="credentials"&&(jt(!0),ft(!0));return}U({title:"Couldn’t connect",body:ct instanceof Error?ct.message:"Please check your key and try again.",tone:"error"})},"onError")}),Wn=cs.mutate,sa=(0,m.useCallback)(ct=>{const fs=ct??de;(fs?BT(fs,xe||null):null)?.auth==="oauth"&&Zt(),Wn(ct)},[xe,de,Wn,Zt]);(0,m.useEffect)(()=>{if(!pe||Un.isLoading||!Un.data||(re||oe)&&(!Fs.isFetchedAfterMount||!En.isFetchedAfterMount))return;if(re&&W==="complete"&&xn?.status==="active"&&Js!==re&&Oa){_(`/apps/${xn.id}/permissions`,{replace:!0});return}if(re&&!Oa)return;const ct=ndt({requestedAppKey:pe,galleryApps:Un.data.apps,reconnectConnection:un,resumeConnection:xn,resumeApplication:Lr,completedResumeConnectionId:Js,applications:En.data?.applications??[]}),fs=!!ct?.methods.some(Ne=>Ne.oauthStrategy==="paperclip_cloud_connector"||Ne.oauthStrategy==="paperclip_id_connector");if(fn&&!fs&&an.isLoading)return;const Ks=aN(ct,i),Sn=v??(un?.connectionPurpose==="ai"?Kq.safeParse(un.config?.ai).data:void 0),Xn=Ks.find(Ne=>Sn?Ne.ai?.provider===Sn.provider&&(!("mode"in Sn)||Sn.mode!=="responsible_user")&&Ne.ai.method===Sn.method:Ne.key===Q)??(fn&&!fs?gre(cn):null)??XN(Ks),wn=Ks.length===1?Ks[0]:null,la=i==="paperclip_vault"&&!!vre(ct),Qa=adt({credentialSource:i,available:Un.data.credentialSources?.vercelConnect.available===!0,retainedReconnectMatches:!!(oe&&Yt)}),Qe=Ks.length===1&&wn?.auth==="oauth"&&!gp(wn)&&!LN(wn),Ft=idt({available:ct?.availability?.available,reconnectConnectionId:oe,reconnectSourceMatches:Yt}),vs=odt({reconnectConnectionId:oe,hasRequestedEntry:!!ct,supportedMethodCount:Ks.length,unsupportedOAuth:Qe,vercelUnavailable:Qa,definitionUnavailable:Ft});if(vs!=="ready"){if(Ee(null),fe("gallery"),vs==="reconnect_unavailable"&&oe){He(oe);return}_(FT(i==="vercel_connect"?mF():"/apps/connect",B),{replace:!0});return}if(He(null),!!ct){if(de?.slug!==ct.slug){Ee(ct),ve(ct.name),Ze(""),Be(""),jt(!1),Fe(""),ge({}),Mt(""),lt(""),Ue(""),Ye(Xn?.key??""),Bt(KC(Xn)),he(""),Lt(null),Cs(null);const Ne=Se?.companyId===T?Se:null;Ut(Ae??Ne?.grantKind??fF(Xn,!!c)),Oe(new Set(Ne?.agentIds??(c?[c]:[]))),is(Ne?.installChoice??(c?"specific":"all")),fe(hre({requestedAppKey:pe,routeStage:W,resumeConnectionId:re,hasPrefilledLink:!!Te.link,zapierSource:ce}))}else Sr!==fs&&(Ee(ct),Ye(Xn?.key??""),Bt(KC(Xn)));if(!(la&&(!En.isFetchedAfterMount||!Fs.isFetchedAfterMount))&&!(la&&rn.current)&&la&&(En.isError||Fs.isError)){qs("error"),Ns("Paperclip couldn’t check for an existing connection. Try again."),fe("key");return}}},[v,Q,En.isError,En.isFetchedAfterMount,En.data,Fs.isError,Fs.isFetchedAfterMount,an.data?.configured,an.isLoading,xe,i,de?.slug,Sr,Un.data,Un.isLoading,_,Ae,un,oe,Yt,xn,Lr,Oa,Js,ga,W,re,cn,pe,c,Se,W,ce]),(0,m.useEffect)(()=>{rs.current=null,gs(null)},[re]),(0,m.useEffect)(()=>{const ct=xn??un;if(!ct||!de||rs.current===ct.id)return;const fs=A9(ct),Ks=typeof fs.sourceTemplateKey=="string"?fs.sourceTemplateKey:null;if(Ks&&Ks!==de.slug)return;const Sn=typeof fs.connectionMethodKey=="string"?fs.connectionMethodKey:null,Xn=Sn?aN(de,i).find(la=>la.key===Sn)??null:null;if(ve(ct.name||de.name),Xn){Ye(Xn.key);const la=fs.methodConfig&&typeof fs.methodConfig=="object"?fs.methodConfig:{};Bt({...KC(Xn),...Object.fromEntries(Object.entries(la).filter(Qa=>typeof Qa[1]=="string"||typeof Qa[1]=="boolean"))})}const wn=fs.oauth&&typeof fs.oauth=="object"?fs.oauth:null;wn?.clientRegistrationSource==="manual"&&typeof wn.clientId=="string"&&Mt(wn.clientId),J==="failed"||J==="denied"?(qs("error"),Ns(mre(J,ie))):(qs("entry"),Ns(null)),fe("key"),rs.current=ct.id,gs(ct.id)},[i,de,ie,J,xn,un]);const Ha=ye({mutationFn:r(async ct=>{const{result:fs,enabled:Ks}=ct,Sn=Object.entries(Ks).filter(([,Qa])=>Qa).map(([Qa])=>Qa),Xn=Gke(fs,Qa=>!!Ks[Qa]),wn=It==="all"?"all_agents":{agentIds:Array.from(wt)},la=await es.finishApp(T,fs.connectionId,{enabledCatalogEntryIds:Sn,askFirstCatalogEntryIds:Xn,...ir?{agentInstructions:ir}:{},access:wn,...c?{preserveExistingAccess:!0}:{}});return await be(fs.connectionId),la},"mutationFn"),onSuccess:r(async(ct,fs)=>{re&&fs.result.connectionId===re&&kn(re),await S.invalidateQueries({queryKey:["tools"]}),await S.invalidateQueries({queryKey:D.apps.attention(T)}),Va("success"),x?.({connectionId:fs.result.connectionId})},"onSuccess"),onError:r(ct=>{Va("key"),U({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((re||oe)&&(Fs.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,fs]=await Promise.all([Fs.refetch(),En.refetch()]);!ct.isError&&!fs.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(re&&Fs.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(re&&Fs.isFetchedAfterMount&&En.isFetchedAfterMount&&xn&&!Oa)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&&Fs.isFetchedAfterMount&&En.isFetchedAfterMount&&(!un||!Yt))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:un?"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((re||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&&bt===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(re&&(!Fs.isFetchedAfterMount||Un.isLoading||!de||Zs!==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&&(!Fs.isFetchedAfterMount||!En.isFetchedAfterMount||Un.isLoading||pe&&!de))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(kr&&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)(Ub,{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=>{xa(ct),cr(null);try{await f(ct)}catch(fs){cr(fs instanceof Error?fs.message:"Couldn’t use this connection."),xa(null)}},"onSelect")}),ar?(0,t.jsx)(pa,{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=aN(de,i),ii=aa?[aa]:ci,Ua=de?xe?ii.find(ct=>ct.key===xe)??null:ii[0]??null:null,Pr=de?Ua?.auth??"none":it==="none"?"none":it==="oauth"?"oauth":"api_key",di=le==="key"?((ct,fs)=>(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)(RH,{extra:ct,forceOpen:fs,companyId:T,sentence:FP({grantKind:xt,authKind:Pr,installChoice:It,installCount:wt.size,lockedAgentId:c??null,preserveAgentAccess:!!(fr&&(Vt||un))}),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(Ks=>!!Ks),authKind:Pr,grantKinds:Xs?[Xs]:Ua?.grantKinds,grantKind:xt,setGrantKind:Ut,installChoice:It,setInstallChoice:is,installAgentIds:wt,setInstallAgentIds:Oe,lockedAgentId:c,capabilities:Un.data?.capabilities,githubIdentity:de?.slug==="github",identityLoading:!!fr&&vi,preserveAgentAccess:!!(fr&&(Vt||un)),disabled:cs.isPending||al.isPending},"connection-defaults"),de&&Mi&&ir&&(0,t.jsx)("div",{className:"mt-6",children:(0,t.jsx)(NV,{provider:de.name,template:Mi,value:ir,onChange:r(Ks=>Ht({slug:de.slug,value:Ks}),"onChange"),disabled:cs.isPending||al.isPending})}),e&&(0,t.jsx)("div",{className:"mt-6",children:e})]})):null,Bi=fr&&ei&&LN(ei)?ei:null,Co=Bi&&fr?(0,t.jsx)(DU,{entry:fr,method:Bi,callbackUrl:pt,clientId:st,onClientIdChange:Mt,clientSecret:Ss,onClientSecretChange:lt,required:!1}):null,Fa=di?.()??null,pi=Co?di?.(Co,Os==="error"||st.trim().length>0)??null:Fa,_o=!!(fr&&le==="key"&&(Aa||Os!=="entry")),Ed=!!(le==="key"&&de&&fn&&!Sr&&an.data?.configured===!0),Xc=!!(le==="key"&&de&&fn&&!Sr&&(an.isLoading||an.isError||an.data?.configured!==!0));if(_o&&fr)return(0,t.jsx)(PU,{entry:fr,resuming:!!re,phase:Os,error:Rn,recoveryActions:ie==="github_installation_required"?{installationUrl:X,managementUrl:ne}:void 0,authorizationHost:Yn,authorizationUrl:Cr,guidance:de?.slug==="railway"&&Ua?(0,t.jsxs)("div",{className:"space-y-3 text-sm text-muted-foreground",children:[(0,t.jsx)("p",{children:Ua.guidanceMd}),(0,t.jsx)("ul",{className:"list-disc space-y-2 pl-5",children:Ua.warnings?.map(ct=>(0,t.jsx)("li",{children:ct},ct))})]}):null,defaults:pi,settingsValid:n&&Hi,onOpenAuthorization:_s,onRetry:r(async()=>{const ct=!Hs.current;Hs.current=!0,Ns(null),qs("starting");const fs=ss?.connection??Vt;if(fs&&Co&&st.trim()){Et.current=fs.id,sa(fr);return}if(fs){Zi(fs);return}if(ct&&!re&&!En.isError&&!Fs.isError){sa(fr);return}rn.current=!0;try{const[Ks,Sn]=await Promise.all([En.refetch(),Fs.refetch()]);if(Ks.isError||Sn.isError){qs("error"),Ns("Paperclip couldn’t check for an existing connection. Try again.");return}const Xn=(re?(Sn.data?.connections??[]).find(wn=>wn.id===re&&wn.authKind==="oauth")??null:null)??yre(ae,Ks.data?.applications??[],Sn.data?.connections??[],K?{applicationId:Te.applicationId,draftOnly:!0}:{});Xn&&!re&&Ut(Xn.credentialPolicy==="per_user"?"user":Xn.credentialPolicy==="per_agent"?"agent":"organization"),Xn?Zi(Xn):cs.mutate(fr)}finally{rn.current=!1}},"onRetry"),onBack:r(()=>{Cn.current?.abort(),qs("entry"),Ns(null),vn()},"onBack"),onCancel:r(()=>{Cn.current?.abort(),(w??(()=>_("/apps")))()},"onCancel")});if($e&&!de&&Ie&&le==="key")return(0,t.jsx)(PU,{identity:{name:ue.trim()||g_(Ie)||"this server",unverifiedHost:g_(Ie)},steps:{labels:fre,activeIndex:xre.key},phase:Os,error:Rn,authorizationHost:Yn,authorizationUrl:Cr,defaults:Fa,onOpenAuthorization:_s,onRetry:r(()=>{Ns(null);const ct=ss?.connection;if(ct){qs("starting"),Zi(ct);return}ze(!1),qs("entry")},"onRetry"),onBack:r(()=>{Cn.current?.abort(),ze(!1),qs("entry"),Ns(null)},"onBack"),onCancel:r(()=>{Cn.current?.abort(),(w??(()=>_("/apps")))()},"onCancel")});const qe=ss?.application.name??de?.name??(ue.trim()||pF(Ie)||"this app"),Pt=Z?Is.filter(ct=>aN(ct,i).length>0):Is,Kt=ce?Un.data?.apps.find(ct=>ct.slug==="zapier")??null:null,Ds=(un?.connectionPurpose==="ai"?Kq.safeParse(un.config?.ai).data:void 0)??de?.methods.find(ct=>ct.key===xe)?.ai??(!xe&&de?.methods.every(ct=>ct.ai)?de.methods[0]?.ai:void 0),en=de?k?.({app:de,name:Me||de.name,grantKind:xt,agentIds:[...wt],allAgents:It==="all",onBack:r(()=>vn(),"onBack")})??(Ds&&T?(0,t.jsx)(t.Fragment,{children:(0,t.jsx)(CI,{defaults:un?void 0:Fa,companyId:T,provider:Ds.provider,fixedMethod:!!(v&&v.mode!=="responsible_user"),initialMethod:un?.connectionPurpose==="ai"?(un.config?.ai).method:Ds.method,connectionId:un?.connectionPurpose==="ai"?un.id:void 0,name:un?.connectionPurpose==="ai"?un.name:Me||`My ${de.name} ${Ds.method==="subscription"?"subscription":"API"}`,ownership:(un?.connectionPurpose==="ai"?un.credentialPolicy==="shared":xt==="organization")?"shared":"personal",agentIds:[...wt],allAgents:It==="all",onCancel:r(()=>w?w():_("/apps"),"onCancel"),onComplete:r(ct=>{x?.({connectionId:ct.connectionId}),x||_(`/apps/${ct.connectionId}/permissions`)},"onComplete")})}):void 0):void 0,ti=un?.connectionPurpose==="ai"?["Reconnect account"]:en!==void 0?["Connect account"]:ce?cdt:de&&ii.length>1?["Choose connection"]:de&&ii[0]?.auth==="oauth"?["Sign in"]:E1(de,xe)?["Share sheet"]:de?["Add your key"]:fre,Ta=un?.connectionPurpose==="ai"?0:(ce||de)&&le!=="gallery"&&le!=="success"?ldt[le]:le==="success"?ti.length:xre[le];return(0,t.jsxs)("div",{className:"max-w-5xl",children:[le!=="success"&&!(a&&le==="gallery")&&(0,t.jsx)(lD,{subtitle:le==="gallery"?Z?"Choose a reviewed app to connect through Vercel.":"Pick the app you want your agents to use.":ti.length<=1?void 0:`Step ${Ta+1} of ${ti.length}`,step:le,activeIndex:Ta,labels:ti,appIdentity:ce?{name:"Zapier",logoUrl:Kt?.branding.logoUrl??null,darkLogoUrl:Kt?.branding.darkLogoUrl??null}:de&&le!=="gallery"?{name:de.name,logoUrl:de.branding.logoUrl,darkLogoUrl:de.branding.darkLogoUrl??null}:void 0,unverifiedHost:!de&&!ce&&le!=="gallery"?g_(Ie):null,onCancel:w??(()=>_("/apps"))}),le==="key"&&s&&(0,t.jsx)("div",{className:"mx-auto mb-6 max-w-xl",children:s}),le==="gallery"&&(0,t.jsx)(xdt,{loading:Un.isLoading,initialLink:Ie,apps:Pt,vercelConnect:Z,vercelConnectAvailability:Un.data?.credentialSources?.vercelConnect??null,byo:we,byoOnly:a,source:M.get("source"),onPick:Nn,onUseLink:r(ct=>{const fs=C5(ct,Is);Ee(null),ve(""),Ze(ct),Be(fs?.name??pF(ct)??""),jt(!1),Fe(""),ge({}),he(""),Lt(null),Oe(new Set(c?[c]:[])),is(c?"specific":"all"),Ut(Ae??(c?"user":"organization")),fe("key")},"onUseLink")}),Ed&&de?(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:[de.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 ",de.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(()=>Ye(_n.key),"onClick"),children:["Use your own ",de.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)(tt,{className:"h-4 w-4 animate-spin"}):null,"Try again"]})]})]}):le==="key"&&de&&Xc?(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)(jb,{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 ",de.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(()=>Ye(_n.key),"onClick"),children:["Use your own ",de.name," OAuth app"]}):null,an.isError||Tr?(0,t.jsx)(pa,{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,Fa,(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:an.isLoading||jn.isPending,onClick:r(()=>{Jn(null),Zt(),Vr(),jn.mutate()},"onClick"),children:[jn.isPending?(0,t.jsx)(tt,{className:"h-4 w-4 animate-spin"}):null,an.data?.status==="pending"?"Continue":"Connect with Paperclip"]})]})]})}):le==="key"&&de&&en!==void 0?en:le==="key"&&de?(0,t.jsx)(vdt,{settingsValid:n&&Hi,entry:de,error:cs.isError?cs.error instanceof Error?cs.error.message:"Please check your key and try again.":null,values:et,onChange:ge,oauthClientId:st,onOAuthClientIdChange:Mt,oauthClientSecret:Ss,oauthCallbackUrl:pt,canReuseOAuthClientSecret:!!(hs?.config?.oauth&&hs.config.oauth.clientId===st.trim()&&hs.hasSavedOAuthClientSecret),onOAuthClientSecretChange:lt,credentialSource:i,vercelConnector:Ls,onVercelConnectorChange:Ue,vercelConnectAvailability:Un.data?.credentialSources?.vercelConnect??null,methodKey:xe,onMethodChange:r(ct=>{Ye(ct?.key??""),!Ae&&ct?.grantKinds&&!ct.grantKinds.includes(_t)&&Ut(fF(ct,!!c)),ge({}),Mt(""),lt(""),Ue(""),Bt(KC(ct))},"onMethodChange"),configValues:mt,onConfigChange:Bt,googleSheetsLinks:Le,googleSheetsError:Qt,onGoogleSheetsLinksChange:r(ct=>{he(ct),Lt(null)},"onGoogleSheetsLinksChange"),submitting:cs.isPending,renderDefaults:di??void 0,onBack:vn,onConnect:r(()=>{if(E1(de,xe)){const Ks=D6(Le);if(Ks.invalidCount>0){Lt("That doesn't look like a Google Sheets link.");return}if(Ks.ids.length===0){Lt("Paste at least one Google Sheets link.");return}}const ct=BT(de,xe||null),fs=!!(ct?.credentialFields?.length||ct?.tenantFields?.some(Ks=>!Ks.hidden)||ct?.extensionFields?.some(Ks=>!Ks.hidden));if(ct&&gp(ct)&&Vt&&!fs&&!st.trim()){Hs.current=!0,Ns(null),qs("starting"),Zi(Vt);return}ct&&gp(ct)&&(Hs.current=!0,Ns(null),qs("starting")),sa()},"onConnect")}):null,le==="key"&&!de&&!Ie&&!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"})]}),le==="key"&&!de&&Ie&&!ce&&(0,t.jsx)(gdt,{link:Ie,name:ue,needsKey:ht,keyValue:Je,onKeyChange:Fe,authMode:it,onAuthModeChange:r(ct=>{At(ct),Ke(null),ct!=="auto"&&jt(!1),ct!=="bearer"&&ct!=="auto"&&Fe("")},"onAuthModeChange"),headers:$t,onHeadersChange:r(ct=>{zt(ct),Ke(null)},"onHeadersChange"),oauthClientId:at,onOAuthClientIdChange:De,oauthClientSecret:Pe,onOAuthClientSecretChange:dt,advancedOpen:rt,onAdvancedOpenChange:ft,guidance:kt,matchedEntry:gn,onUseMatchedEntry:gn?()=>Nn(gn):void 0,submitting:cs.isPending||$e,defaults:Fa,onBack:vn,onConnect:r(()=>{Ke(null),cs.mutate(void 0)},"onConnect")}),le==="key"&&!de&&ce&&(0,t.jsx)(fdt,{link:Ie,onLinkChange:Ze,submitting:cs.isPending,defaults:Fa,onBack:vn,onConnect:r(()=>cs.mutate(void 0),"onConnect")}),le==="success"&&(0,t.jsx)(Ndt,{appName:qe,logoUrl:de?.branding.logoUrl,darkLogoUrl:de?.branding.darkLogoUrl,summary:wdt({grantKind:xt,authKind:Pr,installChoice:It,installCount:wt.size,enabledCount:Object.values(ln).filter(Boolean).length}),statedDefault:FP({grantKind:xt,authKind:Pr,installChoice:It,installCount:wt.size,lockedAgentId:c??null}),onDone:w??(()=>_(o==="page"&&ss?.connectionId?`/apps/${ss.connectionId}/permissions`:"/apps"))})]})}r(pdt,"StandardConnectionSetupFlow");function PU({entry:e,identity:s,resuming:n=!1,phase:a,error:i,recoveryActions:o,authorizationHost:l,authorizationUrl:c,steps:d={labels:ddt,activeIndex:0},guidance:u,defaults:h,onRetry:p,settingsValid:f=!0,onOpenAuthorization:x,onBack:b,onCancel:v}){const j=e?.name??s?.name??"this server",N=e?null:s?.unverifiedHost??null,w=a==="entry"?{title:n?`Finish connecting ${j}`:`Connect ${j} to Paperclip`,body:n?`Your connection is saved. Continue in ${j} to approve access; its identity and agent access will stay the same.`:`Paperclip will open ${j} so you can choose a workspace and approve access.`}:a==="starting"?{title:"Preparing secure sign-in",body:`Paperclip is creating a secure ${j} connection.`}:a==="redirecting"?{title:`Opening ${j}`,body:l?`Continue at ${l} to choose a workspace and approve access. Only approve access if you recognize that address.`:`Continue in ${j} to choose a workspace and approve access.`}:{title:`${j} 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)(lD,{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:N,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)(Pl,{className:"h-5 w-5 text-destructive"}):a==="entry"?(0,t.jsx)(No,{className:"h-5 w-5 text-muted-foreground"}):(0,t.jsx)(tt,{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}),N?(0,t.jsx)(oD,{host:N,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)(io,{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 ${j}`:`Continue to ${j}`:"Try again",a==="entry"?(0,t.jsx)(io,{className:"h-4 w-4","aria-hidden":"true"}):null]}):(0,t.jsx)($,{type:"button",disabled:!0,children:a==="redirecting"?`Opening ${j}…`:"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:b,children:"Back"})]})]})]})}r(PU,"OAuthConnectStateScreen");function fdt({link:e,onLinkChange:s,submitting:n,defaults:a,onBack:i,onConnect:o}){const l=MU(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)(ut,{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)(tt,{className:"mr-2 h-4 w-4 animate-spin"}),n?"Checking…":"Check link"]})]})]})}r(fdt,"ZapierConnectStep");function xdt({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),b=(0,m.useRef)(!1);(0,m.useEffect)(()=>{b.current||x(s)},[s]);const[v,j]=(0,m.useState)(null),N=(0,m.useRef)(null),w=(0,m.useRef)(null),k=(0,m.useRef)(!1);(0,m.useEffect)(()=>{!a||e&&!i||k.current||(i||N.current?.scrollIntoView?.({block:"center"}),w.current?.focus(),w.current?.select(),k.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=MU(f),_=C?C5(C,n):null,R=c==="zapier",A=r(()=>{const T=MU(f);if(!T){j("Paste a full http or https link.");return}j(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)(io,{className:"ml-2 h-3.5 w-3.5"})]})}):null]}),l?.available===!1?(0,t.jsx)(pa,{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)(na,{className:"pointer-events-none absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground"}),(0,t.jsx)(ut,{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=__e(T.slug,T.description),L=a2(T),O=L.length===0||L.every(U=>U.auth==="oauth"&&!gp(U)&&!LN(U)),P=T.availability?.available===!1||o&&l?.available!==!0;return(0,t.jsxs)("button",{type:"button",disabled:O||P,title:P?T.availability?.reason??l?.reason??void 0:void 0,onClick:r(()=>d(T),"onClick"),className:V("flex flex-col rounded-xl border border-border bg-card p-4 text-left transition-colors",O||P?"cursor-not-allowed opacity-60":"hover:border-foreground/30 hover:bg-accent/40"),children:[(0,t.jsx)(Vi,{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:P?(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:N,className:V("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)(Pl,{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)(Vi,{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(j(null),_.slug==="zapier"){A();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)(ut,{ref:w,type:R||_?.slug==="zapier"?"password":"url",autoComplete:"off",spellCheck:!1,"aria-label":"MCP server URL",value:f,onChange:r(T=>{b.current=!0,x(T.target.value),j(null)},"onChange"),onKeyDown:r(T=>{T.key==="Enter"&&A()},"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:A,children:"Continue"})]}),v&&(0,t.jsx)("div",{className:"text-xs text-destructive",children:v})]})]})]})}r(xdt,"GalleryStep");function MU(e){try{const s=new URL(e.trim());return s.protocol!=="http:"&&s.protocol!=="https:"?null:s.toString()}catch{return null}}r(MU,"normalizeAppLink");function gdt({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:b,guidance:v,matchedEntry:j,onUseMatchedEntry:N,submitting:w,defaults:k,onBack:S,onConnect:C}){const _=g_(e),R=o==="custom_headers"?I_e(c):null,A=Jct({link:e,name:s,authMode:o,needsKey:n,keyValue:a,headers:c,oauthClientId:u,oauthClientSecret:p}),T=o==="auto"&&n||o==="bearer",E=j?.slug==="zapier"?zge(e):e,L=r((O,P)=>{d(c.map(U=>U.id===O?{...U,...P}:U))},"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)(oD,{host:_})]}),j&&N?(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)(Vi,{name:j.name,logoUrl:j.branding.logoUrl,darkLogoUrl:j.branding.darkLogoUrl,size:24}),(0,t.jsxs)("span",{className:"truncate",children:["Paperclip has a guided setup for ",j.name,"."]})]}),(0,t.jsxs)($,{type:"button",size:"sm",variant:"outline",onClick:N,children:["Use ",j.name]})]}):null,v?(0,t.jsx)("div",{className:"mt-6",children:(0,t.jsx)(pa,{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)(ut,{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)(el,{open:x,onOpenChange:b,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)(nn,{className:V("h-4 w-4 text-muted-foreground transition-transform",x&&"rotate-180")})]}),(0,t.jsxs)(tl,{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:jre.map(O=>(0,t.jsx)(bdt,{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:jre.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)(ut,{value:O.name,onChange:r(P=>L(O.id,{name:P.target.value}),"onChange"),placeholder:"Header name","aria-label":"Header name",className:"h-10 font-mono"}),(0,t.jsx)(ut,{type:"password",autoComplete:"off",value:O.value,onChange:r(P=>L(O.id,{value:P.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(P=>P.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,EU()]),"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)(ut,{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)(ut,{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]})]})]}),k,(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||!A||!!R,children:[w&&(0,t.jsx)(tt,{className:"mr-2 h-4 w-4 animate-spin"}),w?"Checking…":"Check link"]})]})]})}r(gdt,"LinkConnectStep");var jre=[{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 bdt({label:e,selected:s,onClick:n}){return(0,t.jsx)("button",{type:"button",onClick:n,"aria-pressed":s,className:V("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(bdt,"SegmentedOption");function vdt({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:b,methodKey:v,onMethodChange:j,configValues:N,onConfigChange:w,googleSheetsLinks:k,googleSheetsError:S,onGoogleSheetsLinksChange:C,submitting:_,renderDefaults:R,onBack:A,onConnect:T}){const E=(0,m.useMemo)(()=>aN(s,p),[p,s]),L=v?E.find(Fe=>Fe.key===v)??null:XN(E),O=(0,m.useMemo)(()=>E.some(Fe=>Fe.capabilityProfile)?Array.from(E.reduce((Fe,it)=>{const At=it.capabilityProfile.key,$t=Fe.get(At);return $t?$t.methods.push(it):Fe.set(At,{key:At,label:it.capabilityProfile?.label??it.label??it.key,description:it.capabilityProfile?.description??it.whenToUse,methods:[it]}),Fe},new Map)).map(([,Fe])=>Fe):[],[E]),P=L?.capabilityProfile?.key??L?.key??"",U=O.map(Fe=>Fe.key).join("|"),[M,B]=(0,m.useState)(P||XN(E)?.capabilityProfile?.key||(O.length===1?O[0].key:""));(0,m.useEffect)(()=>{if(P){B(P);return}B(Fe=>O.some(it=>it.key===Fe)?Fe:XN(E)?.capabilityProfile?.key||(O.length===1?O[0].key:""))},[U,O,E,P]);const q=O.length>1?O.find(Fe=>Fe.key===M)?.methods??[]:E,z=(L?.credentialFields??[]).map(Fe=>({...Fe,configPath:uge(Fe,L),helpUrl:L?.consoleLinks?.keys??L?.consoleLinks?.docs??""})),K=L?.credentialSources?.vercelConnect??null,W=p==="vercel_connect",Q=W||z.every(Fe=>Fe.required===!1||(a[Fe.configPath]?.trim().length??0)>0),re=LN(L),J=re&&!gp(L),ie=W||!J||o.trim().length>0&&(!L?.oauthClientSecretRequired||u||c.trim().length>0),X=!W||f.trim().length>0,ne=L?.auth==="oauth"&&re?d:null,oe=[...L?.tenantFields??[],...L?.extensionFields??[]],G=oe.filter(Fe=>!Fe.hidden),Z=G.filter(Fe=>Fe.advanced!==!0),Y=G.filter(Fe=>Fe.advanced===!0),ae=oe.every(Fe=>{if(!Fe.required)return!0;const it=N[Fe.key];return typeof it=="boolean"||typeof it=="string"&&it.trim().length>0}),se=L?.configRequirements?.atLeastOneOf??[],ce=se.length===0||se.some(Fe=>{const it=N[Fe];return typeof it=="string"&&it.trim().length>0}),pe=(O.length<=1||!!M)&&(q.length<=1?!!L:!!v),we=s.availability?.robotEmail??null,Se=s.availability?.available===!1,Te=!W&&re&&!J,le=O.length>1||q.length>1,fe=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)(Lm,{ariaLabel:`Access level for ${s.name}`,className:"mt-2",value:M,onValueChange:r(Fe=>{const it=O.find(At=>At.key===Fe);it&&(B(Fe),j(_9(it.methods)))},"onValueChange"),options:O.map(Fe=>({value:Fe.key,title:Fe.label,description:Fe.description}))}),!M&&(0,t.jsx)("p",{className:"mt-2 text-xs text-muted-foreground",children:"Choose an access level to continue."})]}):null,de=q.find(Fe=>Fe.oauthStrategy==="paperclip_cloud_connector"),Ee=de&&q.find(Fe=>LN(Fe)&&!gp(Fe)),Me=L?.key===Ee?.key,ve=(0,m.useId)(),Ie=de&&Ee&&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":Me,"aria-controls":ve,disabled:_,onClick:r(()=>j(Me?de:Ee),"onClick"),children:Me?"Use Paperclip instead":`Use your own ${vBe(de.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)(Lm,{ariaLabel:`How to connect ${s.name}`,className:"mt-2",value:v,onValueChange:r(Fe=>{const it=q.find(At=>At.key===Fe);it&&j(it)},"onValueChange"),options:q.map(Fe=>({value:Fe.key,title:Fe.label??(Fe.auth==="oauth"?`Sign in with ${s.name}`:"Use an API key")}))}),!L&&(0,t.jsx)("p",{className:"mt-2 text-xs text-muted-foreground",children:"Choose a connection method to continue."})]}):null,Ze=Y.length>0||Te||le,ue=Me||!pe,Be=Ze?(0,t.jsxs)("div",{className:"space-y-6",children:[fe,Ie,Y.map(Fe=>(0,t.jsx)(wre,{field:Fe,value:N[Fe.key],onChange:r(it=>w({...N,[Fe.key]:it}),"onChange")},Fe.key)),Te?(0,t.jsx)(DU,{entry:s,method:L,callbackUrl:ne,clientId:o,onClientIdChange:l,clientSecret:c,onClientSecretChange:h,required:!1}):null]}):null,ht=R?.(Be,ue)??null;if(E1(s,L)){const Fe=D6(k),it=e&&!Se&&!!we&&k.trim().length>0;return(0,t.jsxs)("div",{className:"mx-auto max-w-xl",children:[(0,t.jsxs)("div",{className:"space-y-6",children:[fe,we?(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:we,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:we}),(0,t.jsx)(M_e,{value:we,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)(Qn,{value:k,onChange:r(At=>C(At.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:Fe.ids.length>0?`${Fe.ids.length} ${Fe.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})]})]}),ht,(0,t.jsxs)("div",{className:"mt-8 flex items-center justify-between",children:[(0,t.jsx)($,{variant:"ghost",onClick:A,disabled:_,children:"Back"}),(0,t.jsxs)($,{onClick:T,disabled:_||!it,children:[_&&(0,t.jsx)(tt,{className:"mr-2 h-4 w-4 animate-spin"}),_?"Checking…":"Connect"]})]})]})}const jt=L?.connectorProfile==="asana.mcp",Je=jt?null:L?.consoleLinks?.docs??s.docsUrl;return(0,t.jsxs)("div",{className:"mx-auto max-w-xl",children:[Je?(0,t.jsx)("div",{className:"mb-4 flex justify-end",children:(0,t.jsxs)("a",{href:Je,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)(io,{className:"h-3 w-3"})]})}):null,(0,t.jsxs)("div",{className:"space-y-6",children:[jt?(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,L?.capabilityProfile&&(0,t.jsxs)("p",{className:"text-sm text-muted-foreground",children:[L.capabilityProfile.label,": ",L.capabilityProfile.description]}),W&&K&&b?(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:b.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)(io,{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)(ut,{id:"vercel-connect-connector",value:f,onChange:r(Fe=>x(Fe.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)(pa,{tone:"danger",children:n})}):null,Z.map(Fe=>(0,t.jsx)(wre,{field:Fe,value:N[Fe.key],onChange:r(it=>w({...N,[Fe.key]:it}),"onChange")},Fe.key)),!W&&L?.auth==="oauth"&&J?(0,t.jsx)("div",{id:ve,role:"region","aria-label":"Your OAuth app",children:(0,t.jsx)(DU,{entry:s,method:L,callbackUrl:ne,clientId:o,onClientIdChange:l,clientSecret:c,onClientSecretChange:h,required:!0})}):null,W||!L||z.length===0?null:z.map(Fe=>(0,t.jsxs)("div",{children:[(0,t.jsx)("label",{className:"text-sm font-medium text-foreground",children:are(s.name,Fe.label,z.length)}),(0,t.jsx)(ut,{type:Fe.type==="text"&&Fe.secret===!1?"text":"password","aria-label":are(s.name,Fe.label,z.length),autoComplete:"off",value:a[Fe.configPath]??"",onChange:r(it=>i({...a,[Fe.configPath]:it.target.value}),"onChange"),placeholder:Fe.type==="text"&&Fe.secret===!1?Fe.placeholder:"••••••••••••••••",className:"mt-2 h-11 font-mono"}),Fe.helperMd&&(0,t.jsx)("p",{className:"mt-2 text-xs text-muted-foreground",children:Fe.helperMd}),Fe.helpUrl&&(0,t.jsxs)("a",{href:Fe.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)(io,{className:"h-3 w-3"})]})]},Fe.configPath))]}),ht,(0,t.jsxs)("div",{className:"mt-8 flex items-center justify-between",children:[(0,t.jsx)($,{variant:"ghost",onClick:A,disabled:_,children:"Back"}),(0,t.jsxs)($,{onClick:T,disabled:_||!e||!pe||!Q||!ie||!X||!ae||!ce,children:[_&&(0,t.jsx)(tt,{className:"mr-2 h-4 w-4 animate-spin"}),_?"Checking…":W?L?.auth==="oauth"?"Validate and continue":"Validate and connect":L?.auth==="oauth"?s.slug==="github"?"Continue to GitHub":"Continue to sign in":"Connect"]})]})]})}r(vdt,"KeyStep");function M_e({value:e,ariaLabel:s}){const{copied:n,failed:a,copy:i}=Op();return(0,t.jsxs)($,{type:"button",variant:"outline",className:"shrink-0","aria-label":s,onClick:r(()=>{i(e)},"onClick"),children:[n?(0,t.jsx)(us,{className:"mr-2 h-4 w-4"}):(0,t.jsx)(wr,{className:"mr-2 h-4 w-4"}),n?"Copied":a?"Copy failed":"Copy"]})}r(M_e,"CopyValueButton");function DU({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)(io,{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)(M_e,{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)(ut,{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)(ut,{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(DU,"OAuthClientFields");function wre({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)(ri,{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)(Qn,{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)(ut,{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(wre,"MethodConfigField");function ydt({companyId:e,...s}){const n=te({queryKey:D.agents.list(e),queryFn:r(()=>Ct.list(e),"queryFn")});return(0,t.jsx)(TH,{...s,agents:(n.data??[]).filter(a=>a.status!=="terminated"),agentsLoading:n.isLoading})}r(ydt,"AccessStep");function TH({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:b=!1,identityLoading:v=!1,preserveAgentAccess:j=!1,pending:N=!1,hideFooter:w=!1,bare:k=!1,onBack:S,onContinue:C}){const _=p?.editableAgentIds,R=_?e.filter(q=>_.includes(q.id)):e,A=p?.canSetCompanyInstall??!0,T=p?.canCreateOrganizationGrant??!0,E=n!=="none",L=a??["user","organization"],O=(!E||i==="user"||i==="agent"||T)&&(j?!0:h?d.has(h):i==="agent"?l==="specific"&&d.size===1:l==="all"?A:d.size>0),P=h?e.find(q=>q.id===h)?.name??"the requesting agent":null,U=f?"Connect GitHub as":"Which humans can use this credential?",M=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?",B=f?M:"Which agents can use this connection?";return(0,t.jsxs)("div",{className:k?"":"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:U}),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&&L.length===1?(0,t.jsxs)("div",{className:"mt-4 flex items-center gap-3 rounded-md border border-border p-4",children:[L[0]==="user"?(0,t.jsx)(Gm,{className:"h-4 w-4 shrink-0 text-muted-foreground","aria-hidden":"true"}):L[0]==="agent"?(0,t.jsx)(ro,{className:"h-4 w-4 shrink-0 text-muted-foreground","aria-hidden":"true"}):(0,t.jsx)(qN,{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:L[0]==="user"?f?"My GitHub account":"Just me":L[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:L[0]==="user"?"Agents use it only for runs where you are the responsible person.":L[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)(Lm,{ariaLabel:f?U:"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)(Gm,{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)(ro,{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)(qN,{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=>L.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:M}),j?(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)(qN,{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:P}),". 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)(Lm,{ariaLabel:B,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)(ro,{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)(jdt,{}),accessibleLabel:A?"Any agent":`Any agent. Unavailable: ${p?.companyInstallReason??"Only someone who can configure this connection can choose this."}`,tooltip:A?void 0:p?.companyInstallReason??"Only someone who can configure this connection can choose this.",disabled:!A}]}),!j&&!h&&l==="specific"?(0,t.jsx)("div",{className:"mt-3",children:(0,t.jsx)(yj,{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:N,children:"Back"}),(0,t.jsxs)($,{className:"w-full sm:w-auto",onClick:C,disabled:!O||v||N,children:[N?(0,t.jsx)(tt,{className:"h-4 w-4 animate-spin","aria-hidden":"true"}):null,x,!N&&b?(0,t.jsx)(io,{className:"h-4 w-4","aria-hidden":"true"}):null]})]})]})}r(TH,"AccessStepContent");function FP(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(FP,"connectionDefaultSummarySentence");function RH({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)(el,{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)(tl,{children:(0,t.jsxs)("div",{className:"mt-3 space-y-6",children:[i,s?(0,t.jsx)(TH,{...c,agents:s,bare:!0,hideFooter:!0,submitLabel:"",onBack:r(()=>{},"onBack"),onContinue:r(()=>{},"onContinue")}):(0,t.jsx)(ydt,{...c,companyId:e,bare:!0,hideFooter:!0,submitLabel:"",onBack:r(()=>{},"onBack"),onContinue:r(()=>{},"onContinue")})]})})]})}r(RH,"ConnectionAccessDefaults");function jdt(){return(0,t.jsxs)("span",{className:"relative block h-4 w-5","aria-hidden":"true",children:[(0,t.jsx)(ro,{className:"absolute left-0 top-0 h-3.5 w-3.5"}),(0,t.jsx)(ro,{className:"absolute bottom-0 right-0 h-3.5 w-3.5"})]})}r(jdt,"BotGroupIcon");function wdt(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(wdt,"accessSummaryLines");function Ndt({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)(us,{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)(Vi,{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(Ndt,"ConnectionSetupCompletionScreen");function D_e(){const{newProjectOpen:e,closeNewProject:s}=RA(),{selectedCompanyId:n}=ps();return n&&e?(0,t.jsx)(kdt,{companyId:n,onClose:s},n):null}r(D_e,"NewProjectDialog");function kdt({companyId:e,onClose:s}){const n=Nt(),[a,i]=(0,m.useState)(""),[o]=(0,m.useState)(()=>k5[Math.floor(Math.random()*k5.length)]),[l,c]=(0,m.useState)([]),[d,u]=(0,m.useState)(!1),h=(0,m.useRef)(null),p=ye({mutationFn:r(()=>ra.create(e,{name:a.trim(),color:o,status:"planned",repositoryIds:l.map(f=>f.id)}),"mutationFn"),onSuccess:r(f=>{gb(f.id,e),n.invalidateQueries({queryKey:D.projects.all(e)}),s()},"onSuccess")});return(0,t.jsx)(zs,{open:!0,onOpenChange:r(f=>{!f&&!p.isPending&&s()},"onOpenChange"),children:(0,t.jsx)(Ws,{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)(Vs,{className:"sr-only",children:"Connect GitHub"}),(0,t.jsx)(WS,{host:"dialog",serviceSlug:"github",forceNewConnection:!0,onCancel:r(()=>u(!1),"onCancel"),onComplete:r(()=>{n.invalidateQueries({queryKey:wV(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)(Vs,{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)(zn,{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)(Wm,{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)(Qke,{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(kdt,"NewProjectForm");var gg={list:r(e=>Ce.get(`/companies/${e}/goals`),"list"),get:r(e=>Ce.get(`/goals/${e}`),"get"),create:r((e,s)=>Ce.post(`/companies/${e}/goals`,s),"create"),update:r((e,s)=>Ce.patch(`/goals/${e}`,s),"update"),remove:r(e=>Ce.delete(`/goals/${e}`),"remove")};function L_e(e){return{"--sc":`var(${e})`}}r(L_e,"scStyle");function Sdt(e){const s=e.replace(/_/g," ");return s.charAt(0).toUpperCase()+s.slice(1)}r(Sdt,"sentenceCaseStatus");function ai({status:e,label:s}){return(0,t.jsx)("span",{className:V("inline-flex items-center rounded-full px-2.5 py-0.5 text-xs font-medium whitespace-nowrap shrink-0",Vq[e]??"bg-muted text-muted-foreground"),children:s??e.replace(/[_-]/g," ")})}r(ai,"StatusBadge$5");function $_e({status:e}){const s=Sze[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:L_e(s),children:n.replace(/_/g," ")})}r($_e,"AgentStatusBadge");function fp({status:e,externalConversationState:s}){const n=e==="in_review"&&s==="waiting"?"idle":e,a=aze[n]??"--status-task-backlog";return(0,t.jsxs)("span",{className:V("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:L_e(a),children:[(0,t.jsx)(bA,{status:n,size:"sm"}),Sdt(n)]})}r(fp,"IssueStatusBadge");var Nre={company:"Organization",team:"Team",agent:"Agent",task:"Task"};function O_e(){const{newGoalOpen:e,newGoalDefaults:s,closeNewGoal:n}=RA(),{selectedCompanyId:a,selectedCompany:i}=ps(),o=Nt(),[l,c]=(0,m.useState)(""),[d,u]=(0,m.useState)(""),[h,p]=(0,m.useState)("planned"),[f,x]=(0,m.useState)("task"),[b,v]=(0,m.useState)(""),[j,N]=(0,m.useState)(!1),[w,k]=(0,m.useState)(!1),[S,C]=(0,m.useState)(!1),[_,R]=(0,m.useState)(!1),A=(0,m.useRef)(null),T=b||s.parentId||"",{data:E}=te({queryKey:D.goals.list(a),queryFn:r(()=>gg.list(a),"queryFn"),enabled:!!a&&e}),L=ye({mutationFn:r(q=>gg.create(a,q),"mutationFn"),onSuccess:r(()=>{o.invalidateQueries({queryKey:D.goals.list(a)}),P(),n()},"onSuccess")}),O=ye({mutationFn:r(async q=>{if(!a)throw new Error("No organization selected");return qb.uploadImage(a,q,"goals/drafts")},"mutationFn")});function P(){c(""),u(""),p("planned"),x("task"),v(""),N(!1)}r(P,"reset");function U(){!a||!l.trim()||L.mutate({title:l.trim(),description:d.trim()||void 0,status:h,level:f,...T?{parentId:T}:{}})}r(U,"handleSubmit");function M(q){q.key==="Enter"&&(q.metaKey||q.ctrlKey)&&(q.preventDefault(),U())}r(M,"handleKeyDown");const B=(E??[]).find(q=>q.id===T);return(0,t.jsx)(zs,{open:e,onOpenChange:r(q=>{q||(P(),n())},"onOpenChange"),children:(0,t.jsxs)(Ws,{showCloseButton:!1,className:V("p-0 gap-0",j?"sm:max-w-2xl":"sm:max-w-lg"),onKeyDown:M,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(()=>N(!j),"onClick"),children:j?(0,t.jsx)(Fye,{className:"h-3.5 w-3.5"}):(0,t.jsx)(Nj,{className:"h-3.5 w-3.5"})}),(0,t.jsx)($,{variant:"ghost",size:"icon-xs",className:"text-muted-foreground",onClick:r(()=>{P(),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(),A.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)(Qc,{ref:A,value:d,onChange:u,placeholder:"Add description...",bordered:!1,contentClassName:V("text-sm text-muted-foreground",j?"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)(ur,{open:w,onOpenChange:k,children:[(0,t.jsx)(Nr,{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)(ai,{status:h})})}),(0,t.jsx)(rr,{className:"w-40 p-1",align:"start",children:Uge.map(q=>(0,t.jsx)("button",{className:V("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),k(!1)},"onClick"),children:q},q))})]}),(0,t.jsxs)(ur,{open:S,onOpenChange:C,children:[(0,t.jsx)(Nr,{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)(Wl,{className:"h-3 w-3 text-muted-foreground"}),Nre[f]??f]})}),(0,t.jsx)(rr,{className:"w-40 p-1",align:"start",children:Fge.map(q=>(0,t.jsx)("button",{className:V("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:Nre[q]??q},q))})]}),(0,t.jsxs)(ur,{open:_,onOpenChange:R,children:[(0,t.jsx)(Nr,{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)(Pp,{className:"h-3 w-3 text-muted-foreground"}),B?B.title:"Parent goal"]})}),(0,t.jsxs)(rr,{className:"w-48 p-1",align:"start",children:[(0,t.jsx)("button",{className:V("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:V("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()||L.isPending,onClick:U,children:L.isPending?"Creating…":s.parentId?"Create sub-goal":"Create goal"})})]})})}r(O_e,"NewGoalDialog");var xF=r((e,s)=>`/companies/${e}/agents/${s}/dot-binding`,"path"),zT={create:r(e=>Ce.post(`/companies/${e}/dot-invitations`,{}),"create"),connection:r((e,s,n)=>Ce.get(xF(e,s),{signal:n}),"connection"),pair:r((e,s,n)=>Ce.post(xF(e,s),{replaceBindingId:n}),"pair"),retry:r((e,s,n)=>Ce.post(xF(e,s)+"/event-test",{bindingId:n}),"retry")};function Cdt(e){const s=_dt(e),n=Idt(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 @@ ${dFe}
379
379
  `}r(Cdt,"buildAgentOnboardingPrompt");function _dt(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(_dt,"buildCandidateOnboardingUrls");function Idt(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(Idt,"buildResolutionTestUrl");function F_e({children:e,className:s,...n}){const[a,i]=(0,m.useState)(null),o=(0,m.useRef)(null),l=nW();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 b=h?.playState==="running"?c.getBoundingClientRect().height:u;if(h?.cancel(),u=x,b===void 0||l||typeof c.animate!="function")return;const v=pH("--motion-ease-out-expo");h=c.animate([{height:`${b}px`},{height:`${x}px`}],{duration:wI("--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)(Ws,{...n,ref:i,className:V("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(F_e,"AnimatedDialogContent");var B_e=[{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 LU({onSelect:e,dotDisabledReason:s}){return(0,t.jsx)("div",{className:"grid grid-cols-2 gap-3 sm:grid-cols-3",children:B_e.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)(Ap,{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(LU,"ExternalAgentPresetPicker");var Adt=[{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 z_e({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:Adt.map((a,i)=>{const o=i<s,l=i===s&&e.problem==="event_timeout",c=i===s&&!e.problem,d=o?us:l?Ji:c?tt:Gf;return(0,t.jsxs)("li",{className:"flex items-start gap-3","aria-current":c?"step":void 0,children:[(0,t.jsx)("span",{className:V("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:V("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:V("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:V("text-sm leading-relaxed",e.problem&&e.problem!=="prompt_unavailable"?"text-destructive":"text-muted-foreground"),children:n})]})}r(z_e,"DotConnectionChecks");function Tdt({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 b=B_e.find(k=>k.id===e),v=e==="dot",j=v&&a.phase==="ready"&&!a.problem,N=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:[b&&(0,t.jsx)(Ap,{type:b.adapter,className:"size-10"}),(0,t.jsxs)("div",{className:"space-y-2",children:[(0,t.jsx)(Vs,{className:"text-xl font-semibold tracking-tight",children:b?v?j?"Your Dot is connected":"Connect your Dot":e==="hermes"?"Invite your Hermes agent":"Invite your agent":"Invite an external agent"}),(0,t.jsx)(hn,{className:"text-sm leading-relaxed",children:b?j?`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.":N?"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"})]}),b?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)(z_e,{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)(LU,{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:b?o:l,children:[b&&(0,t.jsx)(jl,{className:"size-4"}),b?"Back":"Cancel"]}),b&&(x?(0,t.jsx)($,{asChild:!0,children:(0,t.jsx)(We,{to:x,onClick:l,children:"Review approval"})}):j?(0,t.jsx)($,{onClick:l,children:"Done"}):N?(0,t.jsxs)($,{disabled:!0,"aria-live":"polite",children:[!a.problem&&(0,t.jsx)(tt,{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)(Ib,{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(Tdt,"ExternalAgentInviteContent");function Rdt({companyId:e,onClose:s,onBack:n}){const a=Nt(),{selectedCompany:i}=ps(),[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,b]=(0,m.useState)(""),v=(0,m.useRef)(!1),j=te({queryKey:D.instance.experimentalSettings,queryFn:vr.getExperimental}),N=j.isPending?"Loading available agents…":j.error?"Unable to load experimental settings. Try again after refreshing.":!j.data?.enableOpenAiDot||!j.data.enablePublicMcp?"Enable OpenAI Dot and Assistant connections (MCP) in experimental settings.":void 0,w=["dot-binding",e,c?.agent.id],k=te({queryKey:w,queryFn:r(({signal:K})=>zT.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=ye({mutationFn:r(async K=>{if(K==="dot"){const J=await zT.create(e);d(J),await a.invalidateQueries({queryKey:D.agents.list(e)});return}const W=await lr.createCompanyInvite(e,{allowedJoinTypes:"agent",humanRole:null,agentMessage:null});a.invalidateQueries({queryKey:D.access.invites(e,"all",5)});const Q=W.onboardingTextUrl??W.onboardingTextPath??`/api/invites/${W.token}/onboarding.txt`,re=await lr.getInviteOnboarding(W.token).catch(()=>null);b(Cdt({onboardingTextUrl:new URL(Q,window.location.origin).href,connectionCandidates:re?.onboarding.connectivity?.connectionCandidates??null,testResolutionUrl:re?.onboarding.connectivity?.testResolutionEndpoint?.url??null}))},"mutationFn"),gcTime:0}),C=ye({mutationFn:r(async K=>{const W=await zT.pair(e,c.agent.id,K);h(W),f(null)},"mutationFn"),onSuccess:r(()=>{a.invalidateQueries({queryKey:w})},"onSuccess"),onError:r(()=>{k.refetch()},"onError"),gcTime:0}),_=ye({mutationFn:r(()=>zT.retry(e,c.agent.id,k.data.binding.id),"mutationFn"),onSuccess:r(()=>{a.invalidateQueries({queryKey:w})},"onSuccess")}),R=k.data?.binding,A=o==="dot"&&k.data?.enabled&&!!k.data.resourceUrl&&k.data.canConfigureConnection&&(!R||R.status==="pairing")&&!u&&!k.error&&!C.isError&&!v.current&&(!p||R?.id===p);(0,m.useEffect)(()=>{A&&k.isFetchedAfterMount&&!k.isFetching&&!C.isPending&&(v.current=!0,C.mutate(R?.id))},[A,k.isFetchedAfterMount,k.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=k.data?.agentLifecycleState==="ready"&&k.data.canConfigureConnection,L=["preparing","verifying"].includes(k.data?.agentLifecycleState??"")&&k.data?.canConfigureConnection,O={phase:T?E?"ready":L?"finishing":"ready":R?.hasPendingChallenge?"testing":R?.subscriptionVerified?"subscribed":R?.connected?"connected":"waiting",problem:k.error?"offline":T&&!E&&!L?"agent_unavailable":R?.status==="pairing"&&!A&&!C.isPending&&!k.isFetching&&!C.isError&&u?.bindingId!==R.id?"prompt_unavailable":R?.challengeExpiresAt&&!R.hasPendingChallenge&&R.status!=="ready"?"event_timeout":void 0},P=(k.data?.agentStatus??c?.agent.status)==="pending_approval",U=k.data&&!k.data.canConfigureConnection&&!P,M=o==="dot"?u&&u.bindingId===R?.id&&k.data?.resourceUrl&&c?T1e({companyId:e,agentId:c.agent.id,resourceUrl:k.data.resourceUrl,...u}):"":x,B=(S.variables===o?S.error:null)??(o==="dot"?(R?.connected?null:C.error)??_.error:null),q=S.isPending||C.isPending||_.isPending||A||o==="dot"&&!!c&&(k.isPending||!M&&k.isFetching),z=r(()=>{if(U){k.refetch();return}if(k.error){k.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)(zs,{open:!0,onOpenChange:r(K=>{K||s()},"onOpenChange"),children:(0,t.jsx)(F_e,{className:"sm:max-w-(--sz-560px)",children:(0,t.jsx)(Tdt,{preset:o,prompt:M,companyName:i?.name??"your organization",connection:O,dotDisabledReason:N,busy:q,error:B?.message??(U?k.data?.agentLifecycleState==="terminated"?"This agent was terminated. Invite another agent to connect Dot.":"Resume this agent before connecting Dot.":void 0),approvalHref:P&&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"&&k.refetch()},"onCopied"),onRetry:z,onNewPrompt:r(()=>C.mutate(R?.id),"onNewPrompt")})})})}r(Rdt,"ExternalAgentInviteDialog");function q_e(){const{newAgentOpen:e,closeNewAgent:s}=RA(),{selectedCompanyId:n}=ps();return e?(0,t.jsx)(Edt,{companyId:n,onClose:s},n):null}r(q_e,"NewAgentDialog");function Edt({companyId:e,onClose:s}){const n=Gn(),[a,i]=(0,m.useState)(!1);return a&&e?(0,t.jsx)(Rdt,{companyId:e,onClose:s,onBack:r(()=>i(!1),"onBack")}):(0,t.jsx)(w_e,{open:!0,onClose:s,onInvite:e?()=>i(!0):void 0,onContinue:r(o=>{s(),n(`/agents/new?${new URLSearchParams(o)}`)},"onContinue")})}r(Edt,"NewAgentDialogContent");var Pdt=[{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 kre({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(kre,"KeyCap");function Mdt(){return(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)("div",{className:"divide-y divide-border border-t border-border",children:Pdt.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)(kre,{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)(kre,{children:"Esc"})," to close · Shortcuts are disabled in text fields"]})})]})}r(Mdt,"KeyboardShortcutsCheatsheetContent");function U_e({open:e,onOpenChange:s}){return(0,t.jsx)(zs,{open:e,onOpenChange:s,children:(0,t.jsxs)(Ws,{className:"sm:max-w-md gap-0 p-0 overflow-hidden",showCloseButton:!1,children:[(0,t.jsx)(on,{className:"px-5 pt-5 pb-3",children:(0,t.jsx)(Vs,{className:"text-base",children:"Keyboard shortcuts"})}),(0,t.jsx)(Mdt,{})]})})}r(U_e,"KeyboardShortcutsCheatsheet");var Ddt={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"},Ldt={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 $dt({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:V("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",Ddt[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)(or,{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)(Hc,{src:e.actor.image,alt:""}),(0,t.jsx)(vo,{children:Ob(e.actor.name)})]}):(0,t.jsx)("span",{className:V("mt-1 h-2 w-2 shrink-0 rounded-full",Ldt[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)(zn,{className:"h-3.5 w-3.5"})})]})})}r($dt,"AnimatedToast");function K_e(){const e=k6e(),{dismissToast:s}=Qr();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)($dt,{toast:n,onDismiss:s},n.id))})})}r(K_e,"ToastViewport");async function Sre(e,s){const n=await fetch(`/api/announcements/${e}`,{credentials:"same-origin",cache:"no-store",...s});if(!n.ok)throw new mn("Announcement request failed",n.status,null);return n}r(Sre,"request");var Cre={async current(e){const s=await(await Sre("current",{signal:e})).json();return s===null?null:gFe.parse(s)},async dismiss(e,s,n){await Sre(`${encodeURIComponent(e)}/dismiss`,{method:"POST",signal:n,headers:{"Content-Type":"application/json"},body:JSON.stringify({companyId:s})})}},$U=new Map;function EH(e){return`paperclip.announcement-dismissals.v1:${encodeURIComponent(e)}:`}r(EH,"announcementStoragePrefix");function qT(e){const s=EH(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);Nge.safeParse(o).success&&(l==="pending"||l==="synced")&&$U.set(i,l==="pending")}}catch{}for(const[a,i]of $U)a.startsWith(s)&&n.set(a.slice(s.length),i);return n}r(qT,"readAnnouncementDismissals");function gF(e,s,n){const a=`${EH(e)}${s}`;$U.set(a,n);try{return localStorage.setItem(a,n?"pending":"synced"),!0}catch{return!1}}r(gF,"saveAnnouncementDismissal");var Odt=3e3;function Fdt(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,b=EH(s);let v=null;try{v=new BroadcastChannel(b)}catch{}const j=r(()=>!d&&a.current.userId===s&&a.current.enabled,"active");async function N(T,E=!0){if(!j()||f.has(T)||!a.current.companyId)return;const L=new AbortController;f.set(T,L);const O=setTimeout(()=>L.abort(),1e4);try{await Cre.dismiss(T,a.current.companyId,L.signal),j()&&gF(s,T,!1)}catch{j()&&!x.has(T)&&(x.add(T),a.current.onSaveFailure(E))}finally{clearTimeout(O),f.delete(T)}}r(N,"sync");async function w(){for(const[T,E]of qT(s)){if(!j())return;E&&await N(T)}}r(w,"flush");function k(){u++,clearTimeout(p),h?.abort(),h=null,o(null)}r(k,"suspend");function S(){if(!j()||document.visibilityState==="hidden")return;k();const T=u,E=new AbortController;h=E;const L=r(()=>j()&&u===T&&!E.signal.aborted,"stillCurrent");let O=!1,P=!1,U=null;const M=r(()=>{!L()||!O||!P||U&&!qT(s).has(U.id)&&(!U.expiresAt||Date.parse(U.expiresAt)>Date.now())&&o({userId:s,announcement:U})},"show");p=setTimeout(()=>{O=!0,M()},Odt),w(),Cre.current(E.signal).then(B=>{U=B,P=!0,M()}).catch(()=>{})}r(S,"resume");function C(){const T=qT(s);o(E=>E?.userId===s&&T.has(E.announcement.id)?null:E)}r(C,"receive");function _(T){T.key?.startsWith(b)&&C()}r(_,"onStorage");function R(){document.visibilityState==="hidden"?k():S()}r(R,"onVisibility");function A(){w()}return r(A,"onOnline"),v&&(v.onmessage=T=>{const E=Nge.safeParse(T.data);E.success&&(qT(s).has(E.data)||gF(s,E.data,!0),C())}),l.current=T=>{if(!j())return;const E=gF(s,T,!0);o(null),u++,h?.abort();try{v?.postMessage(T)}catch{}N(T,E)},document.addEventListener("visibilitychange",R),window.addEventListener("online",A),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",A),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(Fdt,"useAnnouncement");function Bdt(e,s){const n=nW(),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="${GFe}">${p}`})}catch{}finally{clearTimeout(u)}})(),()=>{d.abort(),clearTimeout(u)}},[c,i,a]),c&&o?.key===i?o.document:null}r(Bdt,"useAnnouncementAnimation");function _re({action:e,primary:s,onClick:n}){const a=(0,t.jsxs)(t.Fragment,{children:[e.label,!s&&e.kind==="external"&&(0,t.jsx)(io,{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(_re,"Action");function v3({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=Bdt(e,a),p=!!h;return(0,t.jsxs)(sn,{role:"region","aria-labelledby":o,className:V("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)(zn,{className:"size-4","aria-hidden":"true"})}),(0,t.jsxs)("div",{className:V("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)(_re,{action:e.secondaryLink,onClick:s}),(0,t.jsx)("div",{className:"ml-auto min-w-0 max-w-full",children:(0,t.jsx)(_re,{action:e.primaryAction,primary:!0,onClick:s})})]})]})}r(v3,"AnnouncementCard");var zdt='[role="dialog"][data-state="open"], [role="alertdialog"][data-state="open"], [aria-modal="true"]:not([data-state="closed"]), dialog[open]';function qdt(e){const[s,n]=(0,m.useState)(!1);return(0,m.useEffect)(()=>{if(!e)return;const a=r(()=>n(!!document.querySelector(zdt)),"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(qdt,"useModalOpen");function Udt({health:e}){const{userId:s,settled:n}=mx(),{selectedCompanyId:a,loading:i}=ps(),{onboardingOpen:o}=P4(),l=Td(),c=S6e(),d=e?.deploymentMode==="local_trusted"?"local-board":n?s:null,{announcement:u,dismiss:h}=Fdt({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=qdt(!!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)(v3,{announcement:u,onDismiss:r(()=>h(u.id),"onDismiss")},u.id)})}r(Udt,"AnnouncementWell");function TD(e){const s=e.split("/").filter(Boolean);return s.length===1?s[0]?.toLowerCase()==="onboarding":s.length===2?s[1]?.toLowerCase()==="onboarding":!1}r(TD,"isOnboardingPath");function Kdt(e){const s=e.split("/").filter(Boolean);if(s.length===2&&s[1]?.toLowerCase()==="onboarding")return s[0]}r(Kdt,"companyPrefixFromOnboardingPath");function BP(){return 3}r(BP,"onboardingStepForCompany");function Wdt(e){const{pathname:s,companyPrefix:n,companies:a,cloudManaged:i}=e;if(!TD(s))return null;const o=r(()=>a.length===1?{initialStep:BP(),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:BP(),companyId:l.id}:i?o():{initialStep:1}}r(Wdt,"resolveRouteOnboardingOptions");function Vdt(e){return!e.agentsLoaded||e.agentsRefreshing||e.agentCount>0?!1:!TD(e.pathname)}r(Vdt,"shouldRouteAgentlessCompanyToOnboarding");function Hdt(e){return e.currentStep>1&&e.currentStep>e.entryStep}r(Hdt,"canGoBackFromOnboardingStep");function Ire(e){return e.targetStep<e.currentStep&&e.targetStep>=e.entryStep}r(Ire,"canJumpToOnboardingStep");function PH(e){return!e.hasCompanies&&!TD(e.pathname)}r(PH,"shouldRedirectCompanylessRouteToOnboarding");function Qdt(e){return e.onboardingOpen||!e.routeDismissed}r(Qdt,"isOnboardingWizardActive");function Gdt({context:e}){const{slots:s,errorMessage:n}=Rd({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)(am,{slot:a,context:e,className:"plugin-app-shell-overlay"},`${a.pluginId}:${a.pluginVersion}:${a.id}`))})}r(Gdt,"AppShellEntries");function W_e({localTrusted:e=!1}){const{userId:s,settled:n}=mx(),{selectedCompanyId:a,selectedCompany:i,loading:o}=ps(),{onboardingOpen:l,onboardingRouteDismissed:c}=P4(),{pathname:d}=oa(),u=n?s??(e?"local-board":null):null,h=l||!c&&TD(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)(Gdt,{context:p},JSON.stringify([u,a]))}r(W_e,"PluginAppShellOverlays");function V_e({visible:e}){const s=oa(),{selectedCompanyId:n}=ps(),{openNewIssue:a}=rl(),i=J4(n),{enabled:o}=_j(),{enabled:l}=QA(),c=(0,m.useMemo)(()=>!o&&!l?[{type:"link",to:"/dashboard",label:"Home",icon:c6},{type:"link",to:"/issues",label:"Tasks",icon:ha},{type:"action",label:"New Task",icon:tI,onClick:r(()=>a(),"onClick")},{type:"link",to:"/agents/all",label:"Agents",icon:Wo},{type:"link",to:"/inbox",label:"Inbox",icon:Ad,badge:i.inbox}]:[{type:"link",to:"/dashboard",label:"Home",icon:c6},...o?[{type:"link",to:"/chats",label:"Chat",icon:Z_}]:[],{type:"action",label:"New Task",icon:tI,onClick:r(()=>a(),"onClick")},{type:"link",to:"/issues",label:"Tasks",icon:ha,badge:l?i.inbox:void 0},{type:"link",to:"/agents/all",label:"Agents",icon:Wo},...l?[]:[{type:"link",to:"/inbox",label:"Inbox",icon:Ad,badge:i.inbox}]],[a,i.inbox,o,l]);return(0,t.jsx)("nav",{className:V("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:V("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)($b,{to:d.to,state:hx,className:r(({isActive:h})=>V("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:V("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(V_e,"MobileBottomNav");function SN(e){if(typeof document>"u")return null;const s=document.querySelector(`meta[name="${e}"]`)?.getAttribute("content")?.trim();return s||null}r(SN,"readMetaContent");function OU(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(OU,"normalizeHexColor");function Ydt(e){const s=OU(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(Ydt,"hexToRgb");function bF(e){const s=e/255;return s<=.03928?s/12.92:((s+.055)/1.055)**2.4}r(bF,"relativeLuminanceChannel");function Jdt(e){const{r:s,g:n,b:a}=Ydt(e),i=.2126*bF(s)+.7152*bF(n)+.0722*bF(a);return 1.05/(i+.05)>=(i+.05)/.05?a6e:n6e}r(Jdt,"pickReadableTextColor");function Xdt(){return SN("paperclip-worktree-enabled")==="true"}r(Xdt,"isWorktreeRuntime");function Zdt(){return SN("paperclip-instance-id")}r(Zdt,"getWorktreeInstanceId");function eut(){if(SN("paperclip-worktree-enabled")!=="true")return null;const e=SN("paperclip-worktree-name"),s=OU(SN("paperclip-worktree-color"));return!e||!s?null:{enabled:!0,name:e,color:s,textColor:OU(SN("paperclip-worktree-text-color"))??Jdt(s)}}r(eut,"getWorktreeUiBranding");function H_e(){const e=eut(),{copied:s,failed:n,copy:a}=Op(),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(H_e,"WorktreeBanner");var tut=3e4;function sut(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(sut,"formatRelativeTimestamp");function nut(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(nut,"describeReason");function Q_e({devServer:e}){const[s,n]=(0,m.useState)(!1);if((0,m.useEffect)(()=>{if(!s)return;const d=window.setTimeout(()=>{n(!1)},tut);return()=>window.clearTimeout(d)},[s]),!e?.enabled||!e.restartRequired)return null;const a=e,i=sut(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 yu.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)(Rs,{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:[nut(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)(p8e,{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)(Ii,{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)(Ii,{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)(Ii,{className:"h-3.5 w-3.5"}),(0,t.jsx)("span",{children:s?"Restart requested":"Restart now"})]})]})]})})}r(Q_e,"DevRestartBanner");var G_e=["standalone","fullscreen","window-controls-overlay"];function rut(e){return`(display-mode: ${e})`}r(rut,"displayModeQuery");function aut(){if(!(typeof window>"u"||typeof window.matchMedia!="function"))return window.matchMedia.bind(window)}r(aut,"defaultMatchMedia");function FU(e=aut(),s=typeof navigator>"u"?void 0:navigator.standalone){return s===!0?!0:e?G_e.some(n=>e(rut(n)).matches):!1}r(FU,"isChromelessDisplayMode");function UT({label:e,children:s,onClick:n}){return(0,t.jsxs)(Bn,{children:[(0,t.jsx)(Fn,{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(UT,"ControlButton");function iut(e=typeof window>"u"?null:window.history.state){const s=e?.idx;return typeof s=="number"&&s>0}r(iut,"hasInAppHistory");function out(){const[e,s]=(0,m.useState)(()=>typeof window<"u"?FU():!1);return(0,m.useEffect)(()=>{if(typeof window>"u")return;const n=r(()=>s(FU()),"update");if(n(),typeof window.matchMedia!="function")return;const a=G_e.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(out,"useChromeless");function BU({mobile:e,onNavigateHome:s}){const n=out(),a=Td(),i=(0,m.useCallback)(()=>{if(iut()){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 Ia(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:V("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)(UT,{label:"Back",onClick:i,children:(0,t.jsx)(jl,{className:"h-4 w-4"})}),(0,t.jsx)("div",{className:"flex-1"}),(0,t.jsx)(UT,{label:"Refresh",onClick:o,children:(0,t.jsx)(Ai,{className:"h-4 w-4"})}),(0,t.jsx)(UT,{label:"Share",onClick:l,children:(0,t.jsx)(NW,{className:"h-4 w-4"})}),(0,t.jsx)(UT,{label:"Open in Browser",onClick:c,children:(0,t.jsx)($n,{className:"h-4 w-4"})})]}):null}r(BU,"StandaloneBrowserControls");var lut=16384,cut=40;function dut(e){if(!e)return;const s=[];for(const n of e.slice(0,lut).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===cut)break}return s.length?`
381
381
  ${s.join(`
382
- `)}`:void 0}r(dut,"sanitizeComponentStack");function Y_e(){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(Y_e,"readBrowserErrorState");function uut(e){const s=dut(e.componentStack);return{tags:{react_error_boundary:e.boundary},contexts:{react:s?{componentStack:s}:{},browser_state:Y_e()}}}r(uut,"buildBrowserErrorContext");var Are=Promise.resolve();function MH(e){const s=Are.then(e);return Are=s.catch(()=>{}),s}r(MH,"enqueue");var Qk=null;function mut(e,s){return MH(async()=>{if(!Qk)try{const n=await Id(()=>import("./prod-COP_vZWu.js"),__vite__mapDeps([4,5]));n.init(put(e,s)),Qk=n}catch{}})}r(mut,"initBrowserErrorMonitoring");function hut(){return MH(async()=>{const e=Qk;if(Qk=null,!e)return;const s=e.getClient();try{e.getCurrentScope().setClient(void 0)}catch{}try{await s?.close(2e3)}catch{}})}r(hut,"teardownBrowserErrorMonitoring");function DH(e,s){let n;try{s&&(n=uut(s))}catch{}MH(async()=>{try{n?Qk?.captureException(e,n):Qk?.captureException(e)}catch{}})}r(DH,"captureBrowserException");function put(e,s){return{dsn:e,environment:s??void 0,release:"ce58dd042798cfe7367ab6f289d54f966655c4c5",tracesSampleRate:0,sendDefaultPii:!1,beforeSend:r((n,a)=>{try{if(n.contexts={...n.contexts,browser_state:n.contexts?.browser_state??Y_e()},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(put,"buildBrowserSentryInitOptions");var fut=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){DH(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 J_e({children:e}){const s=oa(),n=Gn(),a=`${s.pathname}${s.search}`;return(0,t.jsx)(fut,{resetKey:a,onReset:r(()=>n(-1),"onReset"),children:e})}r(J_e,"RouteErrorBoundary");var Tre={bot:ro,cpu:Mm,brain:ug,zap:E5,rocket:bze,code:Zge,terminal:Yf,shield:jA,eye:Wd,search:na,wrench:Jf,hammer:vA,lightbulb:yA,sparkles:Mp,star:Dp,heart:w1,flame:uze,bug:by,cog:Qge,database:wA,globe:lm,lock:No,mail:$9,"message-square":Sp,"file-code":Fl,"git-branch":Xi,package:qh,puzzle:mg,target:Pp,wand:CW,atom:$ze,"circuit-board":TKe,radar:_ze,swords:m8e,telescope:JBe,microscope:GKe,crown:S4,gem:Xge,hexagon:Ud,pentagon:ZKe,fingerprint:l6},xut="bot";function gut(e){return e&&pBe.includes(e)?Tre[e]:Tre[xut]}r(gut,"getAgentIcon");function zP({icon:e,className:s}){const n=gut(e);return(0,t.jsx)(n,{className:s})}r(zP,"AgentIcon");function X_e({open:e,onOpenChange:s,...n}){return(0,t.jsx)(zs,{open:e,onOpenChange:s,children:(0,t.jsxs)(Ws,{"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)(Vs,{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)(but,{...n,onComplete:r(()=>s(!1),"onComplete")},String(e))]})})}r(X_e,"AgentChatPicker");function but({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),[b,v]=(0,m.useState)(null);async function j(N){if(f)return;x(N.id),v(null);const w=new AbortController;u.current=w;try{await s(N,w.signal),d.current&&n()}catch(k){v(k instanceof Error?k.message:"Couldn’t open chat. Try again.")}finally{x(null)}}return r(j,"selectAgent"),(0,t.jsxs)(NA,{children:[(0,t.jsx)(wS,{"aria-label":"Search agents by name or role",placeholder:"Search by name or role…",value:h,onValueChange:p}),b&&(0,t.jsx)("p",{role:"alert",className:"px-4 py-3 text-sm text-destructive",children:b}),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)(jS,{children:[(0,t.jsx)(yS,{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)(zu,{children:e.map(N=>(0,t.jsxs)(Xo,{value:N.id,keywords:[N.name,N.title??"",N.role],onSelect:r(()=>{j(N)},"onSelect"),disabled:f!==null,className:"gap-3 px-3 py-3",children:[c?c(N):(0,t.jsx)(zP,{icon:N.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:N.name}),(0,t.jsx)("span",{className:"truncate text-xs text-muted-foreground",children:N.title??N.role})]}),l&&(0,t.jsx)("span",{className:"shrink-0 text-xs text-muted-foreground",children:l.includes(N.id)?"Open chat":"New chat"}),N.status==="paused"&&(0,t.jsx)("span",{className:"text-xs text-(--status-agent-paused)",children:"Paused"}),N.status==="terminated"&&(0,t.jsx)("span",{className:"text-xs text-muted-foreground",children:"Terminated"}),N.status==="pending_approval"&&(0,t.jsx)("span",{className:"text-xs text-muted-foreground",children:"Awaiting approval"})]},N.id))})]})]})}r(but,"AgentChatPickerResults");function y3({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:b}){const v=Gn(),[j,N]=(0,m.useState)(!1),[w,k]=(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 A(){k(""),S.current?.focus()}return r(A,"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(()=>N(!0),"onClick"),children:(0,t.jsx)(bn,{className:"size-4"})})]}),(0,t.jsxs)("div",{className:"relative",children:[(0,t.jsx)(na,{"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)(ut,{ref:S,"aria-label":"Search agents",placeholder:"Find an agent",value:w,onChange:r(T=>k(T.target.value),"onChange"),onKeyDown:r(T=>{T.key==="Escape"&&(T.stopPropagation(),k(""))},"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:A,children:(0,t.jsx)(zn,{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:b,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:Kl(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:V("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)(or,{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(()=>N(!0),"onClick"),children:"Choose an agent"}),e.length>0&&(0,t.jsx)($,{variant:"outline",size:"sm",onClick:A,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)(X_e,{agents:n,open:j,onOpenChange:N,existingChatAgentIds:s??e.map(T=>T.id),loading:o,error:l,onRetry:c,renderAgentIcon:r(T=>(0,t.jsx)(or,{agent:T,size:32}),"renderAgentIcon"),onSelect:r(async(T,E)=>{p?await p(T,E):u?await u(T,E):v(`/chats/${encodeURIComponent(Kl(T))}`),E?.aborted||k("")},"onSelect")})]})}r(y3,"AgentConversationSidebar");var qP={list:r(e=>Ce.get(`/companies/${e}/chats`),"list"),get:r((e,s)=>Ce.get(`/companies/${e}/chats/${encodeURIComponent(s)}`),"get"),ensure:r((e,s)=>Ce.post(`/companies/${e}/chats/${encodeURIComponent(s)}`,{}),"ensure")};function Z_e(){const{selectedCompanyId:e}=ps(),{enabled:s,loaded:n}=_j(),a=te({queryKey:D.auth.session,queryFn:r(()=>Ma.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(()=>Ct.list(e),"queryFn"),enabled:s&&!!e}),chats:te({queryKey:D.agentChats.list(e,i),queryFn:r(()=>qP.list(e),"queryFn"),enabled:s&&!!e&&a.isSuccess}),session:a}}r(Z_e,"useAgentChatNavigation");function eIe(e,s){const n=Nt(),a=Gn(),{isMobile:i,setSidebarOpen:o}=qa(),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 qP.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(Kl(c))}`),i&&o(!1))},[n,e,s,a,i,o])}r(eIe,"useOpenAgentChat");function vut(){const{companyId:e,userId:s,agents:n,chats:a,session:i}=Z_e(),o=eIe(e,s),l=Gn(),c=px(e),{isMobile:d,setSidebarOpen:u}=qa(),{pathname:h}=oa(),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]:[]))]:[],b=tm({queries:x.map(C=>({queryKey:D.agents.detail(C),queryFn:r(()=>Ct.get(C,e),"queryFn")}))}),v=new Map(f.map(C=>[C.id,C]));for(const C of b)C.data&&v.set(C.data.id,C.data);const j=[...v.values()].find(C=>C.id===p||C.status!=="terminated"&&encodeURIComponent(Kl(C))===p),N=(a.data??[]).flatMap(C=>{const _=C.conversationAgentId?v.get(C.conversationAgentId):void 0;return _?[_]:[]});j&&!N.some(C=>C.id===j.id)&&N.unshift(j);const w=new Set(N.map(C=>C.id)),k=f.filter(C=>!w.has(C.id)&&C.status!=="terminated"&&(!c.isSuccess||Ig(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)(y3,{agents:[...N,...k],availableAgents:f,existingChatAgentIds:N.map(C=>C.id),activeId:j?.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:b.some(C=>C.isPending),historyError:b.find(C=>C.error)?.error,onRetryHistory:r(()=>{b.filter(C=>C.isError).forEach(C=>{C.refetch()})},"onRetryHistory"),onAddChat:o,onSelect:r(C=>{l(`/chats/${encodeURIComponent(C.status==="terminated"?C.id:Kl(C))}`),d&&u(!1)},"onSelect")},`${e}:${s}`)}r(vut,"AgentConversationsSidebar");var KT=240,zU=208,qU=420,Rre=16;function UP(e){return Math.min(qU,Math.max(zU,e))}r(UP,"clampSidebarWidth$1");function Ere(e){if(typeof window>"u")return KT;try{const s=window.localStorage.getItem(e);if(!s)return KT;const n=Number.parseInt(s,10);return Number.isFinite(n)?UP(n):KT}catch{return KT}}r(Ere,"readStoredSidebarWidth$1");function Pre(e,s){if(!(typeof window>"u"))try{window.localStorage.setItem(e,String(UP(s)))}catch{}}r(Pre,"writeStoredSidebarWidth$1");function yut({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)(()=>Ere(o)),[x,b]=(0,m.useState)(!1),v=(0,m.useRef)(p),j=(0,m.useRef)(null);(0,m.useEffect)(()=>{const P=Ere(o);v.current=P,f(P)},[o]);const N=s?p:0,w=s?n?64:N:0,k=s?n&&!a?64:N:0,S=k>w,C=i&&s&&!n,_=(0,m.useMemo)(()=>({width:`${w}px`}),[w]),R=(0,m.useMemo)(()=>({width:`${k}px`}),[k]),A=(0,m.useCallback)(P=>{const U=UP(P);v.current=U,f(U),Pre(o,U)},[o]),T=(0,m.useCallback)(P=>{C&&(P.preventDefault(),P.currentTarget.setPointerCapture(P.pointerId),j.current={startX:P.clientX,startWidth:v.current},b(!0))},[C]),E=(0,m.useCallback)(P=>{if(!j.current)return;const U=UP(j.current.startWidth+P.clientX-j.current.startX);v.current=U,f(U)},[]),L=(0,m.useCallback)(()=>{j.current&&(j.current=null,b(!1),Pre(o,v.current))},[o]),O=(0,m.useCallback)(P=>{C&&(P.key==="ArrowLeft"?(P.preventDefault(),A(p-Rre)):P.key==="ArrowRight"?(P.preventDefault(),A(p+Rre)):P.key==="Home"?(P.preventDefault(),A(zU)):P.key==="End"&&(P.preventDefault(),A(qU)))},[C,A,p]);return(0,t.jsxs)("div",{className:V("relative h-full shrink-0",l),style:_,children:[(0,t.jsx)("div",{className:V("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":zU,"aria-valuemax":qU,"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:L,onPointerCancel:L,onLostPointerCapture:L,onKeyDown:O,children:(0,t.jsx)("div",{className:V("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(yut,"SidebarShell$1");function WT({children:e,className:s}){return(0,t.jsx)("div",{"data-secondary-sidebar":"",className:V("h-full w-full min-w-0 overflow-hidden",s),children:(0,t.jsx)(Fwe,{children:e})})}r(WT,"SecondarySidebar$1");var tIe={listStacks:r(()=>Ce.get("/cloud/stacks"),"listStacks")};function RD(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(RD,"cloudAppUrl");function sIe(e){return RD(e,"/stacks/new")}r(sIe,"cloudStackCreateUrl");function nIe(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(nIe,"tenantSignInReturnPath");function jut(e,s,n){const a=s?.trim();if(!a)return null;const i=RD(e,`/v1/stacks/${encodeURIComponent(a)}/entry-redirect`);if(!i)return null;const o=new URL(i);return o.searchParams.set("returnTo",nIe(n)),o.toString()}r(jut,"cloudStackEntryUrl");function rIe(e,s){const n=s?.trim();return n?RD(e,`/workspaces/${encodeURIComponent(n)}/settings?section=people`):null}r(rIe,"cloudStackInviteUrl");function wut(e){return RD(e,"/orgs?manage=1")}r(wut,"cloudPortfolioManageUrl");function aIe(){const e=Yc(),s=!!e,n=te({queryKey:D.cloud.stacks,queryFn:r(()=>tIe.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:rIe(e.cloudBaseUrl,a.stackSlug)}r(aIe,"useCloudInviteUrl");function Nut(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(Nut,"canInviteCompanyMembers");function iIe(e=!0){const s=Pge(),n=te({queryKey:D.access.currentBoardAccess,queryFn:r(()=>lr.getCurrentBoardAccess(),"queryFn"),enabled:e,retry:!1,staleTime:3e4});return e&&Nut(s?.selectedCompanyId,n.data)}r(iIe,"useCanInviteCompanyMembers");function oIe(e){const s=window.location.hostname.endsWith(".staging.paperclip.app"),{data:n,isError:a}=te({queryKey:D.stagingCommit,queryFn:r(()=>yu.get(),"queryFn"),enabled:s&&e,staleTime:0,retry:!1});return s&&!a?n?.commit??null:null}r(oIe,"useStagingCommit");function kut(e){return e?.trim().toLowerCase().replace(/['"]/g,"").replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")||null}r(kut,"slugifyUserPart");function lIe(e){const s=[e?.id,e?.name,e?.email?.split("@")[0],e?.email];for(const n of s){const a=kut(n);if(a)return`/u/${a}`}return"/u/me"}r(lIe,"userProfilePath");var Sut="Toggle the app appearance.";function ZN({className:e,variant:s="icon",onAfterToggle:n}){const{theme:a,toggleTheme:i}=E6e(),o=a==="dark",l=o?"Switch to light mode":"Switch to dark mode",c=o?Kje:Kye;function d(){i(),n?.()}return r(d,"handleClick"),s==="compact-menu-action"?(0,t.jsxs)("button",{type:"button",className:V("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:V("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:Sut})]})]}):(0,t.jsx)($,{type:"button",variant:"ghost",size:"icon-sm",onClick:d,"aria-label":l,title:l,className:V("text-muted-foreground",e),children:(0,t.jsx)(c,{})})}r(ZN,"ThemeToggle");var AI=null,cIe=!1,UU=!1,KU=new Set;function KP(){for(const e of KU)e()}r(KP,"emit");function Cut(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(Cut,"isIosSafariLike");function _ut(e=window){const s=r(a=>{a.preventDefault(),AI=a,KP()},"onPrompt"),n=r(()=>{AI=null,cIe=!0,KP()},"onInstalled");return e.addEventListener("beforeinstallprompt",s),e.addEventListener("appinstalled",n),()=>{e.removeEventListener("beforeinstallprompt",s),e.removeEventListener("appinstalled",n)}}r(_ut,"captureInstallPrompt");function Iut(){return cIe||FU()?"installed":AI?"prompt":Cut()?"ios-manual":"unavailable"}r(Iut,"installAvailability");async function Aut(){const e=AI;if(!e)return"unavailable";AI=null,KP(),await e.prompt();const{outcome:s}=await e.userChoice;return s}r(Aut,"promptInstall");function WU(e){UU!==e&&(UU=e,KP())}r(WU,"setIosInstallHelpOpen");function Tut(){return UU}r(Tut,"iosInstallHelpOpen");function Rut(){return(0,m.useSyncExternalStore)(dIe,Tut,()=>!1)}r(Rut,"useIosInstallHelpOpen");function dIe(e){return KU.add(e),()=>{KU.delete(e)}}r(dIe,"subscribe$1");function Eut(){return(0,m.useSyncExternalStore)(dIe,Iut,()=>"unavailable")}r(Eut,"useInstallAvailability");var Mre="Install app",Put="Add Paperclip to your home screen or dock.";function uIe({variant:e,onAfterAction:s}){const n=Eut();if(n==="installed"||n==="unavailable")return null;const a=r(()=>{n==="ios-manual"?WU(!0):Aut(),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)(ho,{className:"size-4"})}),(0,t.jsx)("span",{className:"min-w-0 flex-1 truncate",children:Mre})]}):(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)(ho,{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:Mre}),(0,t.jsx)("span",{className:"block text-xs text-muted-foreground",children:Put})]})]})}r(uIe,"InstallAppMenuAction");function Mut(){const e=Rut();return(0,t.jsx)(zs,{open:e,onOpenChange:WU,children:(0,t.jsxs)(Ws,{children:[(0,t.jsxs)(on,{children:[(0,t.jsx)(Vs,{children:"Install Paperclip"}),(0,t.jsx)(hn,{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)(vF,{index:1,icon:(0,t.jsx)(c8e,{className:"size-4"}),children:["Tap ",(0,t.jsx)("strong",{children:"Share"})," in the Safari toolbar."]}),(0,t.jsxs)(vF,{index:2,icon:(0,t.jsx)(u8e,{className:"size-4"}),children:["Choose ",(0,t.jsx)("strong",{children:"Add to Home Screen"}),"."]}),(0,t.jsxs)(vF,{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)(dr,{children:(0,t.jsx)($,{type:"button",onClick:r(()=>WU(!1),"onClick"),children:"Done"})})]})})}r(Mut,"IosInstallHelpDialog");function vF({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(vF,"InstallStep");function Dut(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(Dut,"formatTimestamp$2");function Lut(e){return!!e&&!Number.isNaN(new Date(e).getTime())}r(Lut,"isValidTimestamp");function $ut(e){return e?.devServer?.lastRestartAt??e?.serverInfo?.processStartedAt??null}r($ut,"restartTimestamp");function Out(e){const s=e?.serverInfo?.git;return s?.available?`${s.shortSha} · ${s.subject}`:"Commit unavailable"}r(Out,"commitLabel");function Fut(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(Fut,"localChangesLabel");function yF({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(yF,"ServerInfoRow");function mIe(){const e=te({queryKey:D.instance.experimentalSettings,queryFn:r(()=>vr.getExperimental(),"queryFn")}).data?.enableServerInfoDebugView===!0,s=te({queryKey:D.health,queryFn:r(()=>yu.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=$ut(n),l=Lut(o),c=i?"Health unavailable":a?"Loading...":Dut(o),d=i?"Health unavailable":a?"Loading...":Out(n),u=i?"Health unavailable":a?"Loading...":Fut(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)(yF,{icon:fu,label:"Last restarted",value:c,dateTime:!i&&!a&&l?o:null}),(0,t.jsx)(yF,{icon:fW,label:"Running commit",value:d}),(0,t.jsx)(yF,{icon:LKe,label:"Checkout state",value:u})]})}r(mIe,"SidebarServerInfo");var But="/company/settings/members?tab=invites",zut="https://docs.paperclip.ing/",qut="https://paperclip.ing/feedback";function Uut(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(Uut,"deriveInitials$2");function jF({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(jF,"MenuAction$1");function Dre({deploymentMode:e,open:s,onOpenChange:n,forceExpanded:a=!1}){const o=!!Yc(),{hidden:l,loaded:c}=vu(),d=aIe(),u=iIe(!o),h=o?d:u?But:null,p=c&&h!==null&&!wg(l,"company.members")&&!wg(l,"company.invites"),[f,x]=(0,m.useState)(!1),{isMobile:b,setSidebarOpen:v,collapsed:j,peeking:N}=qa(),w=j&&!N&&!a,k=s??f,S=oIe(k),C=n??x,{data:_}=te({queryKey:D.auth.session,queryFn:r(()=>Ma.getSession(),"queryFn"),retry:!1}),R=OS({onSignedOut:O}),A=_?.user.name?.trim()||"Board",T=_?.user.email?.trim()||(e==="authenticated"?"Signed in":"Local workspace board"),E=Uut(A),L=lIe(_?.user);function O(){C(!1),b&&v(!1)}r(O,"closeNavigationChrome");function P(){R.mutate()}return r(P,"handleSignOut"),(0,t.jsx)("div",{className:"bg-border/50 px-3 py-2 dark:bg-muted",children:(0,t.jsxs)("div",{className:V("flex items-center gap-0.5",!w&&"px-2"),children:[(0,t.jsxs)(ur,{open:k,onOpenChange:C,children:[(0,t.jsx)(Nr,{asChild:!0,children:(0,t.jsxs)("button",{type:"button",className:V("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)(Hc,{src:_.user.image,alt:A}):null,(0,t.jsx)(vo,{children:E})]}),(0,t.jsx)("span",{className:V("min-w-0 flex-1 truncate",w&&"block w-0 min-w-0 overflow-hidden whitespace-nowrap text-transparent select-none"),children:A})]})}),(0,t.jsxs)(rr,{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:L,"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)(Hc,{src:_.user.image,alt:A}):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:A}),(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)(jF,{label:"Settings",icon:xu,href:"/company/settings",onClick:O}),p&&h?(0,t.jsx)(jF,{label:"Invite",icon:eh,href:h,topLevel:o,onClick:O}):null,(0,t.jsx)(jF,{label:"Documentation",icon:RS,href:zut,external:!0,onClick:r(()=>C(!1),"onClick")}),(0,t.jsx)(ZN,{variant:"compact-menu-action",onAfterToggle:r(()=>C(!1),"onAfterToggle")}),(0,t.jsx)(uIe,{variant:"compact-menu-action",onAfterAction:r(()=>C(!1),"onAfterAction")}),e==="authenticated"?(0,t.jsxs)("button",{type:"button",className:V("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:P,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)(Up,{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)(mIe,{})]})]})]}),!w&&!o?(0,t.jsxs)(Bn,{children:[(0,t.jsx)(Fn,{asChild:!0,children:(0,t.jsx)("a",{href:qut,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(Dre,"SidebarAccountMenu$1");function hIe({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(b){if(b.defaultPrevented){u();return}if(o){const v=K0e({armed:l,defaultPrevented:b.defaultPrevented,key:b.key,metaKey:b.metaKey,ctrlKey:b.ctrlKey,altKey:b.altKey,target:b.target,hasOpenDialog:$p()});if(v==="arm"){h();return}if(v==="navigate_inbox"){u(),b.preventDefault(),o();return}if(v==="focus_comment"||v==="open_file_viewer"){u(),b.preventDefault();return}v==="disarm"&&u()}if(!_A(b.target)&&!$p()){if(b.key==="/"&&!b.metaKey&&!b.ctrlKey&&!b.altKey){b.preventDefault(),Rqe()||s?.();return}if(b.key==="?"&&!b.metaKey&&!b.ctrlKey&&!b.altKey){b.preventDefault(),i?.();return}b.key==="c"&&!b.metaKey&&!b.ctrlKey&&!b.altKey&&(b.preventDefault(),e?.()),b.key==="["&&!b.metaKey&&!b.ctrlKey&&(b.preventDefault(),n?.()),b.key==="]"&&!b.metaKey&&!b.ctrlKey&&(b.preventDefault(),a?.())}}r(p,"handleKeyDown");const f=r(()=>u(),"handlePointerDown"),x=r(b=>{b.target instanceof HTMLElement&&b.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(hIe,"useKeyboardShortcuts");var Kut=new Set(["auth","invite","board-claim","cli-auth","docs","s"]);function pIe(e){const s=(e.split("?")[0]??"").split("/").filter(Boolean);if(s.length===0)return!0;const[n]=s;return!Kut.has(n)}r(pIe,"isRememberableCompanyPath");function Wut(e){const s=$y(e.companyPrefix);return e.companies.find(n=>$y(n.issuePrefix)===s)??null}r(Wut,"findCompanyByPrefix");function Vut(e){const s=O9(e.pathname);return s?Wut({companies:e.companies,companyPrefix:s})?.id??null:e.fallbackCompanyId}r(Vut,"getRememberedPathOwnerCompanyId");function Hut(e){const s=e.path?C4(e.path):"/dashboard";if(!pIe(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&&$y(i[1]??"")!==$y(e.companyPrefix))return"/dashboard"}return s}r(Hut,"sanitizeRememberedPathForCompany");var fIe="paperclip.companyPaths";function xIe(){try{const e=localStorage.getItem(fIe);if(e)return JSON.parse(e)}catch{}return{}}r(xIe,"getCompanyPaths");function Qut(e,s){const n=xIe();n[e]=s,localStorage.setItem(fIe,JSON.stringify(n))}r(Qut,"saveCompanyPath");function gIe(){const{companies:e,selectedCompanyId:s,selectedCompany:n,selectionSource:a}=ps(),i=oa(),o=Gn(),l=(0,m.useRef)(s),c=(0,m.useMemo)(()=>Vut({companies:e,pathname:i.pathname,fallbackCompanyId:l.current}),[e,i.pathname]),d=i.pathname+i.search;(0,m.useEffect)(()=>{const u=c,h=C4(d);u&&pIe(h)&&Qut(u,h)},[d,c]),(0,m.useEffect)(()=>{if(s){if(l.current!==null&&s!==l.current&&a!=="route_sync"&&n){const u=xIe(),h=Hut({path:u[s],companyPrefix:n.issuePrefix});o(`/${n.issuePrefix}${h}`,{replace:!0})}l.current=s}},[n,s,a,o])}r(gIe,"useCompanyPageMemory");var Gut=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 bIe(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 Gut({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,b=d.update(p,f);b!==x&&a(b)}))},"onScroll");return window.addEventListener("scroll",h,{passive:!0}),()=>{window.removeEventListener("scroll",h),u!==null&&cancelAnimationFrame(u)}},[e,s]),n}r(bIe,"useMobileNavVisibility");function vIe(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(vIe,"resolveArchivedCompanyBounce");function Yut(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(Yut,"resolveCompanyArchiveDeparture");function yIe(e){const{selectionSource:s,selectedCompanyId:n,routeCompanyId:a}=e;return!(n===a||s==="manual"&&n)}r(yIe,"shouldSyncCompanySelectionFromRoute");function Jut(e,s){return e instanceof HTMLElement?!(s instanceof HTMLElement)||!document.contains(s)||s===document.body||s===document.documentElement?!0:!e.contains(s):!1}r(Jut,"shouldFocusMainContentAfterNavigation");function jIe(e){if(!(e instanceof HTMLElement))return()=>{};const s=window.requestAnimationFrame(()=>{Jut(e,document.activeElement)&&e.focus({preventScroll:!0})});return()=>window.cancelAnimationFrame(s)}r(jIe,"scheduleMainContentFocus");function wIe(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(wIe,"pinDocumentScrollToZero");function Zu({scope:e="global",requestedPrefix:s}){const n=oa(),{setBreadcrumbs:a}=Hn(),{companies:i,selectedCompany:o}=ps();(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)(Rs,{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)(T5,{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(Zu,"NotFoundPage");function Xut(e,s){return VNe(e,s)[0]?.toLowerCase()??null}r(Xut,"getCompanyRouteSegment$1");var Zut=new Set(["browse","connections","assistant-connection","connect","chat","vercel-connect","review","attention","gateways","advanced","app"]);function emt({sidebarSections:e}){const{sidebarOpen:s,setSidebarOpen:n,toggleSidebar:a,collapsed:i,peeking:o,setPeeking:l,isMobile:c,setForceCollapsed:d}=qa(),{openNewIssue:u,openOnboarding:h}=rl(),{togglePanelVisible:p}=fx(),f=Td()?.pushToast??null,{companies:x,loading:b,selectedCompany:v,selectedCompanyId:j,selectionSource:N,setSelectedCompanyId:w}=ps(),{companyPrefix:k,pluginRoutePath:S,agentId:C,routineId:_}=fa(),R=Gn(),A=oa(),T=_4(),{enabled:E}=Ac(),L=HNe(A.pathname,k),O=L.builtInContextualSurface==="settings",P=L.companySegments,U=L.isTaskDetail,{enabled:M}=_j(),B=M&&P[0]?.toLowerCase()==="chats",q=E&&(U||B),z=P[0]?.toLowerCase()==="tools",K=P[0]?.toLowerCase()==="apps",W=K&&P[1]&&!Zut.has(P[1].toLowerCase())?P[1]:null,Q=K&&P[1]?.toLowerCase()==="app"&&P[2]?P[2]:null,re=(0,m.useRef)(!1),J=(0,m.useRef)(null),ie=(0,m.useRef)(null),X=(0,m.useRef)(new Lwe),ne=(0,m.useRef)(A.key),oe=bIe(c&&!U,A.pathname),[G,Z]=(0,m.useState)(!1),Y=(0,m.useMemo)(()=>{if(!k)return null;const ft=k.toUpperCase();return x.find(kt=>kt.issuePrefix.toUpperCase()===ft)??null},[x,k]),ae=!!k&&!b&&x.length>0&&!Y,se=(0,m.useMemo)(()=>S?.toLowerCase()??Xut(A.pathname,k),[k,A.pathname,S]),ce=Y?.id??null,pe=Y?.issuePrefix??null,{slots:we}=Rd({slotTypes:["page","routeSidebar"],companyId:ce,enabled:!!(ce&&se)}),Se=(0,m.useMemo)(()=>OW(we,se),[se,we]),Te=(0,m.useMemo)(()=>({companyId:ce,companyPrefix:pe}),[ce,pe]),le=O?(0,t.jsx)(rQe,{}):!E&&L.builtInContextualSurface==="skills"?(0,t.jsx)(pte,{}):W?(0,t.jsx)(mte,{kind:"connection",connectionId:W}):Q?(0,t.jsx)(mte,{kind:"application",applicationId:Q}):K||z?(0,t.jsx)(mQe,{}):Se?E?(0,t.jsx)(VA,{surface:`plugin:${Se.id}`,title:Se.displayName,children:(0,t.jsx)(am,{slot:Se,context:Te,className:"min-h-0 flex-1",missingBehavior:"placeholder"})}):(0,t.jsx)(am,{slot:Se,context:Te,className:"h-full w-full",missingBehavior:"placeholder"}):null,fe=B?(0,t.jsx)(vut,{}):L.builtInContextualSurface==="agent"&&C?(0,t.jsx)(CQe,{agentRef:C}):E&&L.builtInContextualSurface==="routine"&&_?(0,t.jsx)(Q9e,{children:(0,t.jsx)(AQe,{routineId:_})}):E&&L.builtInContextualSurface==="skills"?(0,t.jsx)(pte,{}):le,de=fe!=null,Ee=E&&de&&(B||L.builtInContextualSurface==="skills"||L.builtInContextualSurface==="agent"||L.builtInContextualSurface==="routine"||K||z),Me=E&&de&&!Ee,ve=de&&(!E||Ee),Ie=!E||!de?null:Se&&!L.builtInContextualSurface?`plugin:${Se.id}`:L.builtInContextualSurface,Ze=(0,m.useRef)(null),{data:ue}=te({queryKey:D.health,queryFn:r(()=>yu.get(),"queryFn"),retry:!1,refetchInterval:r(ft=>ft.state.data?.devServer?.enabled?2e3:!1,"refetchInterval"),refetchIntervalInBackground:!1});(0,m.useLayoutEffect)(()=>(d(!E&&de),()=>d(!1)),[de,d,E]),(0,m.useEffect)(()=>{const ft=Ze.current;Ie&&k&&ft&&ft.surface!==Ie&&ft.pathname!==A.pathname&&tQe({surface:Ie,companyPrefix:k,previousPathname:ft.pathname}),Ze.current={pathname:A.pathname,surface:Ie}},[k,Ie,A.pathname]),(0,m.useEffect)(()=>{b||re.current||ue?.deploymentMode!=="authenticated"&&(ue?.cloud||x.length===0&&(re.current=!0,h()))},[x,b,h,ue?.cloud,ue?.deploymentMode]),(0,m.useEffect)(()=>{if(!k||b||x.length===0)return;if(!Y){const kt=(j?x.find(Ke=>Ke.id===j):null)??x[0]??null;kt&&j!==kt.id&&w(kt.id,{source:"route_sync"});return}if(k!==Y.issuePrefix){const kt=A.pathname.replace(/^\/[^/]+/,"");R(`/${Y.issuePrefix}${kt}${A.search}`,{replace:!0});return}const ft=vIe({matchedCompany:Y,selectedCompanyId:j,companies:x});if(ft){f?.({title:`${Y.name} is archived`,body:`Switched to ${ft.name}.`,tone:"info",dedupeKey:`archived-company-bounce:${Y.id}`}),w(ft.id,{source:"route_sync"}),R(`/${ft.issuePrefix}/dashboard`,{replace:!0});return}yIe({selectionSource:N,selectedCompanyId:j,routeCompanyId:Y.id})&&w(Y.id,{source:"route_sync"})},[k,x,b,Y,A.pathname,A.search,R,f,N,j,w]);const Be=p,ht=(0,m.useCallback)(()=>{document.dispatchEvent(new KeyboardEvent("keydown",{key:"k",metaKey:!0,bubbles:!0,cancelable:!0}))},[]),jt=(0,m.useRef)(null),Je=(0,m.useRef)(!1),Fe=(0,m.useRef)(!1),it=(0,m.useCallback)(()=>{jt.current!==null&&(window.clearTimeout(jt.current),jt.current=null)},[]),At=(0,m.useCallback)(()=>{it(),jt.current=window.setTimeout(()=>l(!0),50)},[it,l]),$t=(0,m.useCallback)(()=>{it(),l(!0)},[it,l]),zt=(0,m.useCallback)(()=>{it(),jt.current=window.setTimeout(()=>l(!1),120)},[it,l]),at=(0,m.useCallback)(()=>{Je.current=!0,i&&!Fe.current&&At()},[i,At]),De=(0,m.useCallback)(()=>{Je.current=!1,Fe.current=!1,zt()},[zt]),Pe=(0,m.useCallback)(()=>{Fe.current||$t()},[$t]),dt=(0,m.useCallback)(()=>{Je.current||zt()},[zt]);(0,m.useEffect)(()=>it,[it]);const rt=(0,m.useRef)(i);return(0,m.useEffect)(()=>{i!==rt.current&&(i?(it(),l(!1),Fe.current=Je.current):Fe.current=!1,rt.current=i)},[i,it,l]),(0,m.useEffect)(()=>{if(!o)return;const ft=r(kt=>{kt.key==="Escape"&&(it(),l(!1))},"onKeyDown");return window.addEventListener("keydown",ft),()=>window.removeEventListener("keydown",ft)},[o,it,l]),gIe(),hIe({onNewIssue:r(()=>u(),"onNewIssue"),onSearch:ht,onToggleSidebar:a,onTogglePanel:Be,onShowShortcuts:r(()=>Z(!0),"onShowShortcuts"),onGoToInbox:r(()=>R("/inbox"),"onGoToInbox")}),(0,m.useEffect)(()=>{if(!c)return;const ft=30,kt=50,Ke=75;let $e=0,ze=0;const et=r(st=>{const Mt=st.touches[0];$e=Mt.clientX,ze=Mt.clientY},"onTouchStart"),ge=r(st=>{const Mt=st.changedTouches[0],Ss=Mt.clientX-$e;if(!(Math.abs(Mt.clientY-ze)>Ke)){if(!s&&$e<ft&&Ss>kt){n(!0);return}s&&Ss<-50&&n(!1)}},"onTouchEnd");return document.addEventListener("touchstart",et,{passive:!0}),document.addEventListener("touchend",ge,{passive:!0}),()=>{document.removeEventListener("touchstart",et),document.removeEventListener("touchend",ge)}},[c,s,n]),(0,m.useEffect)(()=>{const ft=document.body.style.overflow;return document.body.style.overflow=c?"visible":"clip",()=>{document.body.style.overflow=ft}},[c]),(0,m.useEffect)(()=>{if(!c)return wIe()},[c]),(0,m.useEffect)(()=>{if(typeof document>"u")return;const ft=ie.current;return jIe(ft)},[A.pathname]),(0,m.useEffect)(()=>{const ft=ie.current;if(!ft)return;const kt=r(()=>{X.current.remember(ne.current,ft.scrollTop)},"recordScroll");return ft.addEventListener("scroll",kt,{passive:!0}),()=>ft.removeEventListener("scroll",kt)},[]),(0,m.useLayoutEffect)(()=>{const ft=ie.current,kt=Dwe({previousPathname:J.current,pathname:A.pathname,navigationType:T,state:A.state});J.current=A.pathname;const Ke=T==="POP",$e=Ke?X.current.recall(A.key):0;if(ne.current=A.key,Ke){J5(ft,$e);const ze=requestAnimationFrame(()=>J5(ft,$e));return()=>cancelAnimationFrame(ze)}kt&&$we(ft)},[A.key,A.pathname,A.state,T]),(0,t.jsx)(Pwe,{children:(0,t.jsxs)("div",{className:V("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)(H_e,{}),(0,t.jsx)(Q_e,{devServer:ue?.devServer}),(0,t.jsxs)("div",{className:V("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:V("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:de?(0,t.jsx)(WT,{children:fe}):(0,t.jsx)(lte,{children:e})})}),(0,t.jsx)(Dre,{deploymentMode:ue?.deploymentMode,forceExpanded:Me})]}):(0,t.jsxs)(yut,{open:s,collapsed:Me?!1:i,peeking:Me?!1:o,resizable:!0,onPanelMouseEnter:Me?void 0:at,onPanelMouseLeave:Me?void 0:De,onPanelFocusCapture:!Me&&i?Pe:void 0,onPanelBlurCapture:!Me&&i?dt:void 0,children:[(0,t.jsx)("div",{className:"flex flex-1 min-h-0",children:Me?(0,t.jsx)(WT,{children:fe}):(0,t.jsx)(lte,{children:e})}),(0,t.jsx)(Dre,{deploymentMode:ue?.deploymentMode,forceExpanded:Me})]}),!c&&ve&&!Ee?(0,t.jsx)(WT,{className:"w-60 shrink-0",children:fe}):null,(0,t.jsxs)("div",{className:V("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:V(!c&&q&&"hidden",c&&"sticky top-0 z-20 bg-background/95 backdrop-blur supports-[backdrop-filter]:bg-background/85"),children:[(0,t.jsx)(BU,{mobile:c,onNavigateHome:r(()=>R("/dashboard"),"onNavigateHome")}),(0,t.jsx)(xte,{}),c&&O?(0,t.jsx)("div",{className:"border-b border-border px-4 pb-3",children:(0,t.jsx)(YNe,{})}):null]}),(0,t.jsxs)("div",{className:V(c?"block":"flex flex-1 min-h-0",!c&&q&&"streamlined-task-detail-surface"),children:[!c&&Ee?(0,t.jsx)(WT,{className:"w-60 shrink-0 bg-background",children:fe}):null,(0,t.jsxs)("div",{className:V(!c&&q?"flex min-w-0 flex-1 flex-col":"contents"),children:[!c&&q?(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)(BU,{mobile:!1,onNavigateHome:r(()=>R("/dashboard"),"onNavigateHome")}),(0,t.jsx)(xte,{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:V("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:ae?(0,t.jsx)(Zu,{scope:"invalid_company_prefix",requestedPrefix:k??v?.issuePrefix}):(0,t.jsx)(J_e,{children:(0,t.jsx)(Lb,{})})})]}),(0,t.jsx)(lke,{taskDetailLayout:!c&&q})]})]})]}),c&&(0,t.jsx)(V_e,{visible:oe}),(0,t.jsx)(cke,{}),(0,t.jsx)(Hke,{}),(0,t.jsx)(D_e,{}),(0,t.jsx)(O_e,{}),(0,t.jsx)(q_e,{}),(0,t.jsx)(U_e,{open:G,onOpenChange:Z}),(0,t.jsx)(K_e,{}),(0,t.jsx)(Udt,{health:ue}),(0,t.jsx)(W_e,{localTrusted:ue?.deploymentMode==="local_trusted"})]})})}r(emt,"Layout$1");var NIe=(0,m.createContext)(!1);function tmt({children:e}){return(0,t.jsx)(NIe.Provider,{value:!0,children:e})}r(tmt,"SidebarNavExpandedProvider");function smt(){return(0,m.useContext)(NIe)}r(smt,"useSidebarNavExpanded");function Ga({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:b,trailing:v,trailingLabel:j,liveAccessory:N}){const{isMobile:w,setSidebarOpen:k,collapsed:S,peeking:C}=qa(),_=smt(),R=S&&!C&&!_,A=c!=null&&c>0,T=x!=null&&x>0,E=T?`${x} live`:A?`${c}${u?` ${u}`:""}`:f?"attention needed":void 0,L=!R||!E&&!j?void 0:`${s}${E?`, ${E}`:""}${j?`, ${j}`:""}`,O=(0,t.jsxs)($b,{to:e,state:hx,end:i,"aria-label":L,onClick:r(()=>{w&&k(!1)},"onClick"),className:r(({isActive:P})=>V("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",b??P?"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&&A&&(0,t.jsx)("span",{className:V("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?xj:V("min-w-0 flex-1 truncate",l),children:s}),!R&&v,!R&&h&&(0,t.jsx)(ot,{variant:"ghost",className:V("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||N)&&(0,t.jsxs)("span",{className:"ml-auto flex items-center gap-1.5",children:[N,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&&A&&(0,t.jsx)(ot,{variant:"ghost",className:V("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)(Bn,{children:[(0,t.jsx)(Fn,{asChild:!0,children:(0,t.jsx)("div",{children:O})}),(0,t.jsx)(On,{side:"right",children:s})]}):O}r(Ga,"SidebarNavItem");var nmt=3,Lre=12e4,rmt=[{value:"top",label:"Top"},{value:"alphabetical",label:"Alphabetical"},{value:"recent",label:"Recent"}];function Cw(e,s){const n=e[s];if(!n)return 0;const a=new Date(n).getTime();return Number.isFinite(a)?a:0}r(Cw,"agentTimestamp");function $re(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=Cw(i,"lastHeartbeatAt")-Cw(a,"lastHeartbeatAt");if(o!==0)return o;const l=Cw(i,"updatedAt")-Cw(a,"updatedAt");if(l!==0)return l;const c=Cw(i,"createdAt")-Cw(a,"createdAt");return c!==0?c:a.name.localeCompare(i.name,void 0,{sensitivity:"base"})}),n)}r($re,"sortAgents");var amt="opacity-0 transition-opacity group-hover/agent:opacity-100 group-focus-within/agent:opacity-100";function imt({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:b=!1}){const v=Kl(n),j=s?`${Qu(n)}/${s}`:Qu(n),N=`${Qu(n)}/configuration`,w=e===v,k=n.status==="paused",S=k&&n.pauseReason==="budget",C=n.orgChainHealth?.status==="invalid_org_chain",_=k?"Resume agent":"Pause agent",R=a||n.status==="pending_approval"||S||k&&C,A=a?"Updating...":S?"Budget paused":k&&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,L=(0,t.jsx)(Ga,{to:j,label:n.name,iconNode:(0,t.jsx)(or,{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:V("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)(KN,{status:p,compact:!0}):null,C?(0,t.jsx)(Rs,{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)(UA,{title:"Agent paused by budget"}):void 0});return d?L:(0,t.jsxs)("div",{className:"group/agent relative flex items-center",children:[L,f&&!i&&x?(0,t.jsx)("span",{className:"absolute right-10 top-1/2 -translate-y-1/2",children:(0,t.jsx)(Sj,{size:"row",quiet:!0,starred:!0,pending:b,resourceName:n.name,onToggle:r(()=>x(n,!1),"onToggle"),revealClassName:amt})}):null,(0,t.jsxs)(Zr,{children:[(0,t.jsx)(ta,{asChild:!0,children:(0,t.jsx)($,{variant:"ghost",size:"icon-xs",className:V("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)(ea,{align:"end",className:"w-48",children:[x?(0,t.jsxs)(t.Fragment,{children:[(0,t.jsxs)(ds,{onClick:r(()=>{b||x(n,!f)},"onClick"),disabled:b,children:[b?(0,t.jsx)(tt,{className:"size-4 motion-safe:animate-spin"}):(0,t.jsx)(Dp,{className:V("size-4",f&&"fill-amber-500 text-amber-500")}),(0,t.jsx)("span",{children:f?"Remove from starred":"Star agent"})]}),(0,t.jsx)(ni,{})]}):null,(0,t.jsx)(ds,{asChild:!0,children:(0,t.jsxs)(We,{to:N,onClick:r(()=>{i&&h(!1)},"onClick"),children:[(0,t.jsx)(sc,{className:"size-4"}),(0,t.jsx)("span",{children:"Edit agent"})]})}),(0,t.jsx)(ni,{}),(0,t.jsxs)(ds,{onClick:r(()=>{R||c(n,k?"resume":"pause")},"onClick"),disabled:R,title:S?"Agent was paused by budget limits":void 0,children:[k?(0,t.jsx)(OA,{className:"size-4"}):(0,t.jsx)(Kd,{className:"size-4"}),(0,t.jsx)("span",{children:A})]}),(0,t.jsx)(ni,{}),(0,t.jsxs)(ds,{onClick:r(()=>{o||l(n)},"onClick"),disabled:o,children:[o?(0,t.jsx)(tt,{className:"size-4 motion-safe:animate-spin"}):(0,t.jsx)(Up,{className:"size-4"}),(0,t.jsx)("span",{children:o?"Leaving...":"Leave agent"})]})]})]})]})}r(imt,"SidebarAgentItem");function omt({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=Nt(),{selectedCompanyId:u}=ps(),h=MS(u),{openNewAgent:p}=rl(),{isMobile:f,setSidebarOpen:x,collapsed:b,peeking:v}=qa(),j=b&&!v,{pushToast:N}=Qr(),w=oa(),{data:k}=te({queryKey:D.agents.list(u),queryFn:r(()=>Ct.list(u),"queryFn"),enabled:!!u}),{data:S}=te({queryKey:D.instance.experimentalSettings,queryFn:r(()=>vr.getExperimental(),"queryFn"),enabled:!!u}),C=S?.enableBuiltInAgents===!0,{data:_}=te({queryKey:D.builtInAgents.list(u),queryFn:r(()=>mp.list(u),"queryFn"),enabled:!!u&&C}),R=(0,m.useMemo)(()=>{const ve=new Map;if(!C)return ve;for(const Ie of _??[])Ie.agentId&&ve.set(Ie.agentId,Ie.status);return ve},[_,C]),{data:A}=te({queryKey:D.auth.session,queryFn:r(()=>Ma.getSession(),"queryFn")}),T=px(u),E=zb(u),L=D.liveRuns(u),O=jo({companyId:u,resourceKey:"live-runs",queryKey:L,enabled:!!u,refetchInterval:!1,leaderOnly:!0}),{data:P,dataUpdatedAt:U}=te({queryKey:L,queryFn:r(()=>Xr.liveRunsForCompany(u),"queryFn"),enabled:O.enabled,refetchInterval:O.refetchInterval});wo(O,P,U);const M=(0,m.useMemo)(()=>{const ve=new Map;for(const Ie of P??[])ve.set(Ie.agentId,(ve.get(Ie.agentId)??0)+1);return ve},[P]),B=(0,m.useMemo)(()=>{const ve=new Set;for(const[Ie,Ze]of M)Ze>0&&ve.add(Ie);return ve},[M]),q=(0,m.useMemo)(()=>(k??[]).filter(ve=>ve.status!=="terminated"&&(!T.isSuccess||Ig(T.data,"agent",ve.id)!=="left")),[k,T.data,T.isSuccess]),z=A?.user?.id??A?.session?.userId??null,K=(0,m.useMemo)(()=>u?Hwe(u,z):null,[z,u]),[W,Q]=(0,m.useState)(()=>K?WN(K):"top"),{orderedAgents:re}=Ywe({agents:q,companyId:u,userId:z}),J=(0,m.useMemo)(()=>$re(re,W),[re,W]),ie=(0,m.useMemo)(()=>new Set(J.map(ve=>ve.id)),[J]);(0,m.useEffect)(()=>{const ve=Date.now();for(const Ie of B)c.current.set(Ie,ve);for(const Ie of c.current.keys())ie.has(Ie)||c.current.delete(Ie)},[B,ie]);const X=(0,m.useMemo)(()=>{const ve=Date.now(),Ie=c.current;return J.filter(Ze=>{if((M.get(Ze.id)??0)>0)return!0;const ue=Ie.get(Ze.id);return ue!==void 0&&ve-ue<=Lre})},[M,o,J]),ne=X.length>0,oe=e?ne?X:J.slice(0,nmt):J,G=e&&J.length>0,Z=w.pathname.match(/^\/(?:[^/]+\/)?agents\/([^/]+)(?:\/([^/]+))?/),Y=Z?.[1]??null,ae=Z?.[2]??null;(0,m.useEffect)(()=>{if(!K){Q("top");return}Q(WN(K))},[K]),(0,m.useEffect)(()=>{if(!K)return;const ve=r(Ze=>{Ze.key===K&&Q(WN(K))},"onStorage"),Ie=r(Ze=>{const ue=Ze.detail;!ue||ue.storageKey!==K||Q(ue.sortMode)},"onCustomEvent");return window.addEventListener("storage",ve),window.addEventListener(rI,Ie),()=>{window.removeEventListener("storage",ve),window.removeEventListener(rI,Ie)}},[K]),(0,m.useEffect)(()=>{if(!e)return;const ve=Date.now();let Ie=null;for(const ue of J){if((M.get(ue.id)??0)>0)continue;const Be=c.current.get(ue.id);if(Be===void 0)continue;const ht=Be+Lre;ht<ve||(Ie=Ie===null?ht:Math.min(Ie,ht))}if(Ie===null)return;const Ze=window.setTimeout(()=>{l(ue=>ue+1)},Math.max(0,Ie-ve+1));return()=>{window.clearTimeout(Ze)}},[e,J,M,o]);const se=(0,m.useCallback)(ve=>{const Ie=ve==="alphabetical"||ve==="recent"?ve:"top";Q(Ie),K&&Gwe(K,Ie)},[K]),ce=ye({mutationFn:r(({agent:ve,action:Ie})=>Ie==="pause"?Ct.pause(ve.id,u??void 0):Ct.resume(ve.id,u??void 0),"mutationFn"),onMutate:r(({agent:ve})=>{i(Ie=>{const Ze=new Set(Ie);return Ze.add(ve.id),Ze})},"onMutate"),onSuccess:r(async(ve,{agent:Ie,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(Ie.id)}),d.invalidateQueries({queryKey:D.agents.detail(Kl(Ie))})]),N({title:Ze==="pause"?"Agent paused":"Agent resumed",body:Ie.name,tone:"success"})},"onSuccess"),onError:r((ve,{agent:Ie,action:Ze})=>{N({title:Ze==="pause"?"Could not pause agent":"Could not resume agent",body:ve instanceof Error?ve.message:Ie.name,tone:"error"})},"onError"),onSettled:r((ve,Ie,{agent:Ze})=>{i(ue=>{const Be=new Set(ue);return Be.delete(Ze.id),Be})},"onSettled")}),pe=(0,m.useCallback)(ve=>E.mutate({resourceType:"agent",resourceId:ve.id,resourceName:ve.name,state:"left"}),[E]),we=(0,m.useCallback)(ve=>E.isPending&&E.variables?.resourceType==="agent"&&E.variables.resourceId===ve.id,[E.isPending,E.variables]),Se=(0,m.useCallback)((ve,Ie)=>E.mutate({resourceType:"agent",resourceId:ve.id,resourceName:ve.name,starred:Ie}),[E]),Te=(0,m.useCallback)(ve=>E.isPending&&E.variables?.resourceType==="agent"&&E.variables.resourceId===ve.id&&E.variables.starred!==void 0,[E.isPending,E.variables]),le=(0,m.useMemo)(()=>new Set(H4(T.data,"agent")),[T.data]),fe=(0,m.useMemo)(()=>$re(q.filter(ve=>le.has(ve.id)),"alphabetical"),[q,le]),de=(0,m.useMemo)(()=>oe.filter(ve=>!le.has(ve.id)),[oe,le]),Ee=h&&!h.loading?q.find(ve=>ve.id===h.primaryAgentId):void 0,Me=r((ve,Ie)=>(0,t.jsx)(imt,{activeAgentId:Y,activeTab:ae,agent:ve,disabled:a.has(ve.id),isMobile:f,leaving:we(ve),onLeaveAgent:pe,onPauseResume:r((Ze,ue)=>ce.mutate({agent:Ze,action:ue}),"onPauseResume"),rail:j,runCount:M.get(ve.id)??0,setSidebarOpen:x,builtInStatus:R.get(ve.id),starred:Ie||kj(T.data,"agent",ve.id),onToggleStar:Se,starPending:Te(ve)},ve.id),"renderAgentRow");return(0,t.jsxs)(pg,{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:rmt,radioValue:W,onRadioValueChange:se},children:[[...Ee?[Ee]:[],...fe.filter(ve=>ve.id!==Ee?.id),...de.filter(ve=>ve.id!==Ee?.id)].map(ve=>Me(ve,le.has(ve.id))),G&&(()=>{const ve=(0,t.jsxs)(We,{to:"/agents/all",state:hx,"aria-label":j?"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:j?"block w-0 min-w-0 overflow-hidden whitespace-nowrap text-transparent select-none":void 0,children:"See all agents"})]});return j?(0,t.jsxs)(Bn,{children:[(0,t.jsx)(Fn,{asChild:!0,children:ve}),(0,t.jsx)(On,{side:"right",children:"See all agents"})]}):ve})()]})}r(omt,"SidebarAgents");var lmt="opacity-0 transition-opacity group-hover/starred-project:opacity-100 group-focus-within/starred-project:opacity-100";function cmt(){const{selectedCompanyId:e}=ps(),{isMobile:s,setSidebarOpen:n,collapsed:a,peeking:i}=qa(),o=a&&!i,l=oa(),{data:c}=te({queryKey:D.projects.list(e),queryFn:r(()=>ra.list(e),"queryFn"),enabled:!!e}),d=px(e),u=zb(e),h=l.pathname.match(/^\/(?:[^/]+\/)?projects\/([^/]+)/)?.[1]??null,p=(0,m.useMemo)(()=>{if(!d.isSuccess)return[];const v=new Set(H4(d.data,"project"));if(v.size===0)return[];const j=new Map((c??[]).map(N=>[N.id,N]));return Array.from(v).map(N=>j.get(N)).filter(N=>!!N).sort((N,w)=>N.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]),b=(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 j=Ng(v),N=h===j||h===v.id,w=b(v),k=w&&u.variables?.starred===!1,S=w&&u.variables?.state==="left",C=kj(d.data,"project",v.id),_=(0,t.jsxs)($b,{to:`/projects/${j}/issues`,state:hx,onClick:r(()=>{s&&n(!1)},"onClick"),className:V("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",N?"bg-accent text-foreground":"text-foreground/80 hover:bg-accent/50 hover:text-foreground"),children:[(0,t.jsx)(Wm,{color:v.color??null,icon:v.icon??null,size:"xs"}),(0,t.jsx)("span",{className:o?xj:"flex-1 truncate",children:v.name}),!o&&v.visibility==="private"?(0,t.jsx)(No,{className:"size-3.5 shrink-0 text-muted-foreground","aria-label":"Private project"}):null,!o&&v.pauseReason==="budget"?(0,t.jsx)(UA,{title:"Project paused by budget"}):null]});return(0,t.jsxs)("div",{className:"group/starred-project relative flex items-center",children:[o?(0,t.jsxs)(Bn,{children:[(0,t.jsx)(Fn,{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)(Sj,{size:"row",quiet:!0,starred:C,pending:k,resourceName:v.name,onToggle:r(()=>f(v),"onToggle"),revealClassName:lmt})}):null,!o&&s?(0,t.jsxs)(Zr,{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)(ea,{align:"end",className:"w-48",children:[(0,t.jsxs)(ds,{onClick:r(()=>{w||f(v)},"onClick"),disabled:w,children:[k?(0,t.jsx)(tt,{className:"size-4 motion-safe:animate-spin"}):(0,t.jsx)(Dp,{className:"size-4 fill-amber-500 text-amber-500"}),(0,t.jsx)("span",{children:"Remove from starred"})]}),(0,t.jsx)(ni,{}),(0,t.jsxs)(ds,{onClick:r(()=>{w||x(v)},"onClick"),disabled:w,children:[S?(0,t.jsx)(tt,{className:"size-4 motion-safe:animate-spin"}):(0,t.jsx)(Up,{className:"size-4"}),(0,t.jsx)("span",{children:"Leave project"})]})]})]}):null]},v.id)})})}r(cmt,"SidebarStarredProjects");var dmt="size-5 shrink-0 rounded-md text-(length:--text-micro)",umt="size-(--organization-popover-avatar-size) shrink-0 rounded-lg text-(length:--text-micro)",mmt="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",wF="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 kIe({company:e,inPopover:s=!1}){return(0,t.jsx)(Ag,{companyName:e.name,logoUrl:e.logoUrl,className:s?umt:dmt})}r(kIe,"WorkspaceIcon");function hmt({company:e,isEditing:s,isSelected:n,onSelect:a}){const{attributes:i,listeners:o,setActivatorNodeRef:l,setNodeRef:c,transform:d,transition:u,isDragging:h}=AS({id:e.id,disabled:!s});return(0,t.jsxs)(ds,{ref:c,style:{transform:_S.Transform.toString(d),transition:u,zIndex:h?10:void 0},onSelect:r(p=>{if(s){p.preventDefault();return}a(e)},"onSelect"),className:V(mmt,s&&"cursor-grab",h&&"opacity-80"),children:[(0,t.jsx)(kIe,{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)(O4,{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)(us,{className:"size-4 text-foreground"}):null})]})}r(hmt,"SortableCompanyItem");function pmt(e={}){return(0,t.jsx)(KNe,{...e,children:(0,t.jsx)(fmt,{...e})})}r(pmt,"SidebarCompanyMenu");function fmt({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}=ps(),{openOnboarding:p}=rl(),{isMobile:f,setSidebarOpen:x,collapsed:b,peeking:v}=qa(),j=b&&!v,N=oa(),w=Gn(),k=e??n,S=s??a,C=NS(Xf(G9,{activationConstraint:{distance:8}}),Xf(o0e,{activationConstraint:{delay:180,tolerance:6}})),_=(0,m.useMemo)(()=>l.filter(J=>J.status!=="archived"),[l]),{data:R}=te({queryKey:D.auth.session,queryFn:r(()=>Ma.getSession(),"queryFn"),retry:!1}),A=R?.user?.id??R?.session?.userId??null,{orderedCompanies:T,persistOrder:E}=UNe({companies:_,userId:A}),{hidden:L,loaded:O}=vu(),P=O&&!wg(L,"company.members")&&!wg(L,"company.invites"),U="company",M=c?.name??null,B=!!Yc(),q=OS({onSignedOut:K});function z(J){J||o(!1),S(J)}r(z,"handleOpenChange");function K(){S(!1),o(!1),f&&x(!1)}r(K,"closeNavigationChrome");function W(J){const ie=N.pathname.split("/")[1]?.toUpperCase(),X=_.some(oe=>oe.issuePrefix.toUpperCase()===ie),ne=J.id!==c?.id&&(N.pathname.startsWith("/instance/")||X);d(J.id),S(!1),f&&x(!1),ne&&w(`/${J.issuePrefix}/dashboard`)}r(W,"selectCompany");function Q(){B||(S(!1),f&&x(!1),p({initialStep:1}))}r(Q,"addCompany");const re=(0,m.useCallback)(J=>{const{active:ie,over:X}=J;if(!X||ie.id===X.id)return;const ne=T.map(Z=>Z.id),oe=ne.indexOf(ie.id),G=ne.indexOf(X.id);oe===-1||G===-1||E(R4(ne,oe,G))},[T,E]);return(0,t.jsxs)(Zr,{open:k,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":M?`Open ${M} ${U} switcher`:`Open ${U} switcher`,children:[(0,t.jsxs)("span",{className:"flex min-w-0 flex-1 items-center gap-2",children:[c?(0,t.jsx)(kIe,{company:c}):null,(0,t.jsx)("span",{className:V("min-w-0 truncate text-sm font-bold text-foreground",j&&"block w-0 min-w-0 overflow-hidden whitespace-nowrap text-transparent select-none"),title:M??void 0,children:M??`Select ${U}`})]}),!j&&(0,t.jsx)(I4,{className:"size-3.5 shrink-0 text-muted-foreground"})]})}),(0,t.jsxs)(ea,{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)(Fb,{className:"p-0 text-(length:--text-compact) font-semibold text-foreground",children:"Organizations"}),(0,t.jsx)("button",{type:"button",onClick:r(J=>{J.preventDefault(),J.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)(IS,{sensors:C,collisionDetection:SA,onDragEnd:re,children:(0,t.jsx)(CS,{items:T.map(J=>J.id),strategy:IA,children:T.map(J=>(0,t.jsx)(hmt,{company:J,isEditing:i,isSelected:J.id===c?.id,onSelect:W},J.id))})}),T.length===0?u?(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)(ds,{disabled:!0,children:"Couldn't load companies"}),(0,t.jsxs)(ds,{onSelect:r(J=>{J.preventDefault(),h()},"onSelect"),children:[(0,t.jsx)(Ai,{className:"h-4 w-4 mr-2"}),"Try again"]})]}):(0,t.jsx)(ds,{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:[!B&&(0,t.jsxs)(ds,{onClick:Q,className:wF,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"})]}),P?(0,t.jsx)(ds,{asChild:!0,disabled:i,className:wF,children:(0,t.jsxs)(We,{to:"/company/settings/invites",onClick:r(J=>{if(i){J.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)(eh,{className:"size-4"})}),(0,t.jsx)("span",{className:"min-w-0 flex-1 truncate",children:M?`Invite people to ${M}`:"Invite people"})]})}):null,R?.session?(0,t.jsxs)(ds,{className:wF,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)(Up,{className:"size-4"})}),(0,t.jsx)("span",{className:"min-w-0 flex-1 truncate",children:q.isPending?"Signing out...":"Sign out"})]}):null]})]})]})}r(fmt,"BuiltinCompanyMenu");function Ore(){const{openNewIssue:e}=rl(),[s,n]=(0,m.useState)(!0),[a,i]=(0,m.useState)(!0),{selectedCompanyId:o,selectedCompany:l}=ps(),{collapsed:c,peeking:d}=qa(),u=c&&!d,h=J4(o),{data:p,isFetched:f}=te({queryKey:D.instance.experimentalSettings,queryFn:r(()=>vr.getExperimental(),"queryFn")}),x=D.liveRuns(o),b=jo({companyId:o,resourceKey:"live-runs",queryKey:x,enabled:!!o,refetchInterval:!1,leaderOnly:!0}),{data:v,dataUpdatedAt:j}=te({queryKey:x,queryFn:r(()=>Xr.liveRunsForCompany(o),"queryFn"),enabled:b.enabled,refetchInterval:b.refetchInterval});wo(b,v,j);const N=v?.length??0,w=p?.enableIsolatedWorkspaces===!0,k=p?.enableApps===!0,S=p?.enablePipelines===!0,C=p?.enableStatusCards===!0,_=!f,R=p?.enableGoalsSidebarLink===!0,A=p?.enableDecisions===!0,{data:T}=te({queryKey:D.attention(o),queryFn:r(()=>DS.list(o),"queryFn"),enabled:!!o&&A,refetchInterval:6e4}),E=vNe(T),L=p?.enableCases===!0,O=!0,P=p?.enableConferenceRoomChat===!0,U={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)(pmt,{})}),(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 M=(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)(tI,{className:"h-4 w-4 shrink-0"}),(0,t.jsx)("span",{className:u?xj:"truncate",children:"New Task"})]});return u?(0,t.jsxs)(Bn,{children:[(0,t.jsx)(Fn,{asChild:!0,children:M}),(0,t.jsx)(On,{side:"right",children:"New Task"})]}):M})(),(0,t.jsx)(Ga,{to:"/search",label:"Search",icon:na}),(0,t.jsx)(Ga,{to:"/dashboard",label:"Dashboard",icon:hg,liveCount:N}),(0,t.jsx)(Ga,{to:"/inbox",label:"Inbox",icon:Ad,badge:h.inbox,badgeLabel:"unread",badgeTone:h.failedRuns>0?"danger":"default",alert:h.failedRuns>0}),A?(0,t.jsx)(Ga,{to:"/decisions",label:"Decisions",icon:wj,badge:E,badgeLabel:"decisions"}):null,C?(0,t.jsx)(Ga,{to:"/status",label:"Status",icon:ES,textBadge:"beta"}):null,P?(0,t.jsx)(Ga,{to:"/board-chat",label:"Conference Room",icon:Lye}):null]}),(0,t.jsxs)(pg,{label:"Work",collapsible:{open:s,onOpenChange:n},children:[(0,t.jsx)(Ga,{to:"/issues",label:"Tasks",icon:Wu}),L?(0,t.jsx)(Ga,{to:"/cases",label:"Cases",icon:Wl,textBadge:"beta"}):null,(0,t.jsx)(Ga,{to:"/routines",label:"Routines",icon:Gu}),S?(0,t.jsx)(Ga,{to:"/pipelines",label:"Pipelines",icon:Xi}):null,R?(0,t.jsx)(Ga,{to:"/goals",label:"Goals",icon:Pp}):_?(0,t.jsx)("div",{"data-testid":"sidebar-goals-placeholder",className:"h-8 pointer-coarse:h-7","aria-hidden":"true"}):null,(0,t.jsx)(Ga,{to:"/artifacts",label:"Artifacts",icon:qh}),(0,t.jsx)(Ga,{to:"/skills",label:"Skills",icon:vc}),w?(0,t.jsx)(Ga,{to:"/workspaces",label:"Workspaces",icon:Xi}):null,(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)(Ga,{to:"/projects",label:"Projects",icon:sl}),(0,t.jsx)(cmt,{})]}),(0,t.jsx)(Bp,{errorBehavior:"hidden",slotTypes:["sidebar"],context:U,className:"flex flex-col gap-0.5",itemClassName:"text-(length:--text-compact) font-medium",missingBehavior:"placeholder"}),(0,t.jsx)($S,{errorBehavior:"hidden",placementZones:["sidebar"],context:U,className:"flex flex-col gap-0.5",itemClassName:"text-(length:--text-compact) font-medium"})]}),null,(0,t.jsx)(omt,{streamlined:O}),(0,t.jsxs)(pg,{label:"Company",collapsible:{open:a,onOpenChange:i},children:[(0,t.jsx)(Ga,{to:"/org",label:"Org",icon:wb}),k?(0,t.jsx)(Ga,{to:"/apps",label:"Connectors",icon:G5}):null,(0,t.jsx)(Ga,{to:"/timeline",label:"Timeline",icon:O0}),(0,t.jsx)(Ga,{to:"/costs",label:"Costs",icon:Cp}),(0,t.jsx)(Ga,{to:"/activity",label:"Activity",icon:nc}),(0,t.jsx)(Ga,{to:"/company/settings",label:"Settings",icon:xu})]}),(0,t.jsx)(Bp,{errorBehavior:"hidden",slotTypes:["sidebarPanel"],context:U,className:"flex flex-col gap-3",itemClassName:"rounded-lg border border-border p-3",missingBehavior:"placeholder"})]})]})}r(Ore,"Sidebar");function xmt(e){const s=e.manifestJson.environmentDrivers??[];return s.length===0?!1:s.every(n=>n.kind==="sandbox_provider")}r(xmt,"isSandboxProviderOnly");function gmt(){const{selectedCompany:e,selectedCompanyId:s}=ps(),{isMobile:n,setSidebarOpen:a}=qa(),{hidden:i}=vu(),{enabled:o}=Ij(),l=r(x=>!i.has(x),"showPage"),c=l("instance.plugins"),d=!!Yc(),{slots:u}=Rd({slotTypes:["companySettingsPage"],companyId:s,enabled:!!s}),{data:h}=te({queryKey:s?D.sidebarBadges(s):["sidebar-badges","__disabled__"],queryFn:r(async()=>{try{return await KW.get(s)}catch(x){if(x instanceof mn&&(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(()=>Rl.list(),"queryFn"),enabled:c}),f=(p??[]).filter(x=>!xmt(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)(nm,{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)(Ga,{to:"/company/settings",label:"General",icon:rm,end:!0}),l("instance.profile")&&(0,t.jsx)(Ga,{to:"/company/settings/instance/profile",label:"Profile",icon:U4,end:!0}),l("company.members")&&(0,t.jsx)(Ga,{to:"/company/settings/members",label:"Members",icon:Wo,badge:h?.joinRequests??0,end:!0}),u.filter(x=>x.routePath).map(x=>(0,t.jsx)(Ga,{to:`/company/settings/${x.routePath}`,label:x.displayName,icon:mg,end:!0},`${x.pluginKey}:${x.id}`)),l("company.invites")&&(0,t.jsx)(Ga,{to:"/company/settings/invites",label:"Invites",icon:HKe,end:!0}),l("company.secrets")&&(0,t.jsx)(Ga,{to:"/company/settings/secrets",label:"Secrets",icon:Si,end:!0}),l("instance.environments")&&(0,t.jsx)(Ga,{to:"/company/settings/instance/environments",label:"Environments",icon:zye,end:!0}),o&&(0,t.jsx)(Ga,{to:"/company/settings/connections",label:"Connections",icon:Pl,end:!0}),l("instance.access")&&(0,t.jsx)(Ga,{to:"/company/settings/instance/access",label:"Access",icon:jA,end:!0}),l("instance.heartbeats")&&(0,t.jsx)(Ga,{to:"/company/settings/instance/heartbeats",label:"Heartbeats",icon:fu,end:!0}),l("company.export")&&(0,t.jsx)(Ga,{to:"/company/export",label:"Export",icon:ho}),!d&&l("company.import")&&(0,t.jsx)(Ga,{to:"/company/import",label:"Import",icon:Uy,end:!0}),l("instance.experimental")&&(0,t.jsx)(Ga,{to:"/company/settings/instance/experimental",label:"Experimental",icon:Vm}),c&&(0,t.jsx)(Ga,{to:"/company/settings/instance/plugins",label:"Plugins",icon:mg}),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)($b,{to:`${hp}/plugins/${x.id}`,state:hx,className:r(({isActive:b})=>["rounded-md px-2 py-1.5 text-xs transition-colors",b?"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)(Ga,{to:"/company/settings/instance/adapters",label:"Adapters",icon:Mm})]})})]})}r(gmt,"CompanySettingsSidebar");function bmt(){const{pathname:e}=oa(),{selectedCompany:s}=ps(),{isMobile:n,setSidebarOpen:a}=qa(),i=ZNe(),{enabled:o}=X4(),l=YW.filter(d=>!XNe(d.key)||o);if(e.endsWith("/apps/chat/connect"))return(0,t.jsx)(JNe,{NavItem:Ga});const c=e.match(/\/apps\/chat\/([^/]+)(?:\/(?:settings|access|conversations|activity|approvals|audit)|\/reviews(?:\/[^/]+)?)?\/?$/);return c?(0,t.jsx)(HW,{endpointId:c[1],NavItem:Ga}):(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)(nm,{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)(uee,{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)(Ga,{to:"/apps",label:"Browse",icon:sI,end:!0}),(0,t.jsx)(Ga,{to:"/apps/review",label:"Review",icon:PS,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)(Ga,{to:"/apps/connections",label:"Connections",icon:uee,end:!0}),l.map(d=>(0,t.jsx)(Ga,{to:nb(d.key),label:d.label,icon:d.icon,end:!0},d.key))]})]})]})}r(bmt,"AppsSidebar");function Fre(e){const{selectedCompanyId:s}=ps(),{isMobile:n,setSidebarOpen:a}=qa(),i=te({queryKey:D.tools.connection(e.kind==="connection"?e.connectionId:"__none__"),queryFn:r(()=>es.getConnection(e.kind==="connection"?e.connectionId:""),"queryFn"),enabled:e.kind==="connection"&&!!e.connectionId}),o=te({queryKey:D.tools.applications(s??"__none__"),queryFn:r(()=>es.listApplications(s),"queryFn"),enabled:e.kind==="application"&&!!s}),l=te({queryKey:D.tools.connections(s??"__none__"),queryFn:r(()=>es.listConnections(s),"queryFn"),enabled:e.kind==="application"&&!!s}),c=te({queryKey:D.apps.gallery(s??"__none__"),queryFn:r(()=>es.listGallery(s),"queryFn"),enabled:!!s}),d=te({queryKey:D.apps.attention(s??"__none__"),queryFn:r(()=>es.listAppsAttention(s),"queryFn"),enabled:!!s,refetchInterval:3e4}),u=i.data,h=e.kind==="application"?(o.data?.applications??[]).find(N=>N.id===e.applicationId):null,p=jmt(e.kind==="application"?(l.data?.connections??[]).filter(N=>N.applicationId===e.applicationId):[]),f=u?ex(u):h?.name??"App",x=ymt(c.data?.apps??[],u,h??void 0),b=u?.id??p?.id??null,v=b?d.data?.apps.find(N=>N.connection.id===b):null,j=(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)(nm,{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)(Vi,{name:f,logoUrl:HA(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:Z4.map(N=>(0,t.jsx)(Ga,{to:vmt(e,N.key),label:N.label,icon:N.icon,end:!0,badge:N.key==="review"&&j>0?j:void 0,badgeTone:"danger",badgeLabel:"needing review"},N.key))})})]})}r(Fre,"AppDetailSidebar");function vmt(e,s){return e.kind==="connection"?Em(e.connectionId,s):c_(e.applicationId,s)}r(vmt,"tabHref");function ymt(e,s,n){if(n?.applicationKey){const i=e.find(o=>fc(o)===n.applicationKey);if(i)return i}const a=(s?.name??n?.name)?.toLowerCase();return a?e.find(i=>fg(i).toLowerCase()===a)??e.find(i=>fc(i)===a)??null:null}r(ymt,"galleryEntryFor$1");function jmt(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(jmt,"latestArchivedConnection$1");function NF({identifier:e}){return e?(0,t.jsx)("span",{className:"shrink-0 font-mono text-muted-foreground",children:e}):null}r(NF,"CrumbIdentifier");function wmt({context:e}){const{slots:s}=Rd({slotTypes:["globalToolbarButton"],companyId:e.companyId}),{launchers:n}=VW({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)(Bp,{slotTypes:["globalToolbarButton"],context:e,className:"flex items-center gap-1"}):null,n.length>0?(0,t.jsx)($S,{placementZones:["globalToolbarButton"],context:e,className:"flex items-center gap-1"}):null]})}r(wmt,"GlobalToolbar");function Nmt(){const{breadcrumbs:e,mobileToolbar:s}=Hn(),{toggleSidebar:n,isMobile:a}=qa(),{selectedCompanyId:i,selectedCompany:o}=ps(),l=(0,m.useMemo)(()=>({companyId:i??null,companyPrefix:o?.issuePrefix??null}),[i,o?.issuePrefix]),c=(0,t.jsx)(wmt,{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)(_ye,{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)(NF,{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)(JW,{className:"min-w-0 overflow-hidden",children:(0,t.jsx)(XW,{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)(iP,{}),(0,t.jsx)(d_,{className:p?"min-w-0":"shrink-0",children:p||!u.href?u.leading||u.identifier?(0,t.jsxs)(cI,{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)(NF,{identifier:u.identifier}),(0,t.jsx)("span",{className:"truncate",children:u.label})]}):(0,t.jsx)(cI,{className:"truncate",children:u.label}):(0,t.jsx)(aP,{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)(NF,{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(Nmt,"BreadcrumbBar");var VT=240,VU=208,HU=420,Bre=16;function WP(e){return Math.min(HU,Math.max(VU,e))}r(WP,"clampSidebarWidth");function zre(e){if(typeof window>"u")return VT;try{const s=window.localStorage.getItem(e);if(!s)return VT;const n=Number.parseInt(s,10);return Number.isFinite(n)?WP(n):VT}catch{return VT}}r(zre,"readStoredSidebarWidth");function qre(e,s){if(!(typeof window>"u"))try{window.localStorage.setItem(e,String(WP(s)))}catch{}}r(qre,"writeStoredSidebarWidth");function kmt({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)(()=>zre(o)),[x,b]=(0,m.useState)(!1),v=(0,m.useRef)(p),j=(0,m.useRef)(null);(0,m.useEffect)(()=>{const P=zre(o);v.current=P,f(P)},[o]);const N=s?p:0,w=s?n?64:N:0,k=s?n&&!a?64:N:0,S=k>w,C=i&&s&&!n,_=(0,m.useMemo)(()=>({width:`${w}px`}),[w]),R=(0,m.useMemo)(()=>({width:`${k}px`}),[k]),A=(0,m.useCallback)(P=>{const U=WP(P);v.current=U,f(U),qre(o,U)},[o]),T=(0,m.useCallback)(P=>{C&&(P.preventDefault(),P.currentTarget.setPointerCapture(P.pointerId),j.current={startX:P.clientX,startWidth:v.current},b(!0))},[C]),E=(0,m.useCallback)(P=>{if(!j.current)return;const U=WP(j.current.startWidth+P.clientX-j.current.startX);v.current=U,f(U)},[]),L=(0,m.useCallback)(()=>{j.current&&(j.current=null,b(!1),qre(o,v.current))},[o]),O=(0,m.useCallback)(P=>{C&&(P.key==="ArrowLeft"?(P.preventDefault(),A(p-Bre)):P.key==="ArrowRight"?(P.preventDefault(),A(p+Bre)):P.key==="Home"?(P.preventDefault(),A(VU)):P.key==="End"&&(P.preventDefault(),A(HU)))},[C,A,p]);return(0,t.jsx)("div",{className:V("relative h-full shrink-0",l),style:_,children:(0,t.jsxs)("div",{className:V("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":VU,"aria-valuemax":HU,"aria-valuenow":p,tabIndex:0,className:V("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:L,onPointerCancel:L,onLostPointerCapture:L,onKeyDown:O}):null]})})}r(kmt,"SidebarShell");function Smt({children:e,className:s}){return(0,t.jsx)("div",{"data-secondary-sidebar":"",className:V("h-full w-60 shrink-0 overflow-y-auto border-r border-border bg-background",s),children:(0,t.jsx)(tmt,{children:e})})}r(Smt,"SecondarySidebar");var Cmt="/company/settings/members?tab=invites",_mt="https://docs.paperclip.ing/",Imt="https://paperclip.ing/feedback";function Amt(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(Amt,"deriveInitials$1");function Ure({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(Ure,"MenuAction");function Kre({deploymentMode:e,open:s,onOpenChange:n}){const i=!!Yc(),{hidden:o,loaded:l}=vu(),c=aIe(),d=iIe(!i),u=i?c:d?Cmt:null,h=l&&u!==null&&!wg(o,"company.members")&&!wg(o,"company.invites"),[p,f]=(0,m.useState)(!1),{isMobile:x,setSidebarOpen:b,collapsed:v,peeking:j}=qa(),N=v&&!j,w=s??p,k=oIe(w),S=n??f,{data:C}=te({queryKey:D.auth.session,queryFn:r(()=>Ma.getSession(),"queryFn"),retry:!1}),_=OS({onSignedOut:L}),R=C?.user.name?.trim()||"Board",A=C?.user.email?.trim()||(e==="authenticated"?"Signed in":"Local workspace board"),T=Amt(R),E=lIe(C?.user);function L(){S(!1),x&&b(!1)}r(L,"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:V("flex items-center gap-0.5",!N&&"px-2"),children:[(0,t.jsxs)(ur,{open:w,onOpenChange:S,children:[(0,t.jsx)(Nr,{asChild:!0,children:(0,t.jsxs)("button",{type:"button",className:V("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",N?"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)(Hc,{src:C.user.image,alt:R}):null,(0,t.jsx)(vo,{children:T})]}),(0,t.jsx)("span",{className:V("min-w-0 flex-1 truncate",N&&"block w-0 min-w-0 overflow-hidden whitespace-nowrap text-transparent select-none"),children:R})]})}),(0,t.jsxs)(rr,{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:L,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)(Hc,{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:A}),k?(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/${k}`,target:"_blank",rel:"noreferrer","aria-label":`View commit ${k} on GitHub`,title:k,children:["SHA ",k.slice(0,7)]}):null]})]}),(0,t.jsxs)("div",{className:"mt-4 space-y-1",children:[h&&u?(0,t.jsx)(Ure,{label:"Invite",description:"Invite people to your organization.",icon:eh,href:u,topLevel:i,onClick:L}):null,(0,t.jsx)(Ure,{label:"Documentation",description:"Open Paperclip docs in a new tab.",icon:RS,href:_mt,external:!0,onClick:r(()=>S(!1),"onClick")}),(0,t.jsx)(ZN,{variant:"menu-action",onAfterToggle:r(()=>S(!1),"onAfterToggle")}),(0,t.jsx)(uIe,{variant:"menu-action",onAfterAction:r(()=>S(!1),"onAfterAction")}),e==="authenticated"?(0,t.jsxs)("button",{type:"button",className:V("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)(Up,{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)(mIe,{})]})]})]})]}),!N&&!i?(0,t.jsxs)(Bn,{children:[(0,t.jsx)(Fn,{asChild:!0,children:(0,t.jsx)("a",{href:Imt,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(Kre,"SidebarAccountMenu");function Tmt(e,s){return SIe(e,s)[0]?.toLowerCase()??null}r(Tmt,"getCompanyRouteSegment");function SIe(e,s){if(!s)return[];const n=e.split("/").filter(Boolean);return n.length<2?[]:n[0]?.toUpperCase()!==s.toUpperCase()?[]:n.slice(1)}r(SIe,"getCompanyPathSegments");var Rmt=new Set(["browse","connections","connect","chat","review","attention","gateways","advanced","app"]);function Emt(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(Emt,"isSkillsStoreRoute");function Pmt(){const{sidebarOpen:e,setSidebarOpen:s,toggleSidebar:n,collapsed:a,peeking:i,setPeeking:o,isMobile:l,setForceCollapsed:c}=qa(),{openNewIssue:d,openOnboarding:u}=rl(),{togglePanelVisible:h}=fx(),p=Td()?.pushToast??null,{companies:f,loading:x,selectedCompany:b,selectedCompanyId:v,selectionSource:j,setSelectedCompanyId:N}=ps(),{companyPrefix:w,pluginRoutePath:k}=fa(),S=Gn(),C=oa(),_=_4(),R=HNe(C.pathname,w).isTaskDetail,A=["/company/settings","/company/export","/company/import"].some(jt=>C.pathname.includes(jt)),T=SIe(C.pathname,w),E=T[0]?.toLowerCase()==="tools",L=T[0]?.toLowerCase()==="apps",O=L&&T[1]&&!Rmt.has(T[1].toLowerCase())?T[1]:null,P=L&&T[1]?.toLowerCase()==="app"&&T[2]?T[2]:null,U=Emt(C.pathname,w),M=(0,m.useRef)(!1),B=(0,m.useRef)(null),q=(0,m.useRef)(null),z=(0,m.useRef)(new Lwe),K=(0,m.useRef)(C.key),W=bIe(l&&!R,C.pathname),[Q,re]=(0,m.useState)(!1),J=(0,m.useMemo)(()=>{if(!w)return null;const jt=w.toUpperCase();return f.find(Je=>Je.issuePrefix.toUpperCase()===jt)??null},[f,w]),ie=!!w&&!x&&f.length>0&&!J,X=(0,m.useMemo)(()=>k?.toLowerCase()??Tmt(C.pathname,w),[w,C.pathname,k]),ne=J?.id??null,oe=J?.issuePrefix??null,{slots:G}=Rd({slotTypes:["page","routeSidebar"],companyId:ne,enabled:!!(ne&&X)}),Z=(0,m.useMemo)(()=>OW(G,X),[X,G]),Y=(0,m.useMemo)(()=>({companyId:ne,companyPrefix:oe}),[ne,oe]),ae=A?(0,t.jsx)(gmt,{}):O?(0,t.jsx)(Fre,{kind:"connection",connectionId:O}):P?(0,t.jsx)(Fre,{kind:"application",applicationId:P}):L||E?(0,t.jsx)(bmt,{}):Z?(0,t.jsx)(am,{slot:Z,context:Y,className:"h-full w-full",missingBehavior:"placeholder"}):null,se=ae!=null,{data:ce}=te({queryKey:D.health,queryFn:r(()=>yu.get(),"queryFn"),retry:!1,refetchInterval:r(jt=>jt.state.data?.devServer?.enabled?2e3:!1,"refetchInterval"),refetchIntervalInBackground:!1}),pe=se||U;(0,m.useLayoutEffect)(()=>(c(pe),()=>c(!1)),[pe,c]),(0,m.useEffect)(()=>{x||M.current||ce?.deploymentMode!=="authenticated"&&(ce?.cloud||f.length===0&&(M.current=!0,u()))},[f,x,u,ce?.cloud,ce?.deploymentMode]),(0,m.useEffect)(()=>{if(!w||x||f.length===0)return;if(!J){const Je=(v?f.find(Fe=>Fe.id===v):null)??f[0]??null;Je&&v!==Je.id&&N(Je.id,{source:"route_sync"});return}if(w!==J.issuePrefix){const Je=C.pathname.replace(/^\/[^/]+/,"");S(`/${J.issuePrefix}${Je}${C.search}`,{replace:!0});return}const jt=vIe({matchedCompany:J,selectedCompanyId:v,companies:f});if(jt){p?.({title:`${J.name} is archived`,body:`Switched to ${jt.name}.`,tone:"info",dedupeKey:`archived-company-bounce:${J.id}`}),N(jt.id,{source:"route_sync"}),S(`/${jt.issuePrefix}/dashboard`,{replace:!0});return}yIe({selectionSource:j,selectedCompanyId:v,routeCompanyId:J.id})&&N(J.id,{source:"route_sync"})},[w,f,x,J,C.pathname,C.search,S,p,j,v,N]);const we=h,Se=(0,m.useCallback)(()=>{document.dispatchEvent(new KeyboardEvent("keydown",{key:"k",metaKey:!0,bubbles:!0,cancelable:!0}))},[]),Te=(0,m.useRef)(null),le=(0,m.useRef)(!1),fe=(0,m.useRef)(!1),de=(0,m.useCallback)(()=>{Te.current!==null&&(window.clearTimeout(Te.current),Te.current=null)},[]),Ee=(0,m.useCallback)(()=>{de(),Te.current=window.setTimeout(()=>o(!0),50)},[de,o]),Me=(0,m.useCallback)(()=>{de(),o(!0)},[de,o]),ve=(0,m.useCallback)(()=>{de(),Te.current=window.setTimeout(()=>o(!1),120)},[de,o]),Ie=(0,m.useCallback)(()=>{le.current=!0,a&&!fe.current&&Ee()},[a,Ee]),Ze=(0,m.useCallback)(()=>{le.current=!1,fe.current=!1,ve()},[ve]),ue=(0,m.useCallback)(()=>{fe.current||Me()},[Me]),Be=(0,m.useCallback)(()=>{le.current||ve()},[ve]);(0,m.useEffect)(()=>de,[de]);const ht=(0,m.useRef)(a);return(0,m.useEffect)(()=>{a!==ht.current&&(a?(de(),o(!1),fe.current=le.current):fe.current=!1,ht.current=a)},[a,de,o]),(0,m.useEffect)(()=>{if(!i)return;const jt=r(Je=>{Je.key==="Escape"&&(de(),o(!1))},"onKeyDown");return window.addEventListener("keydown",jt),()=>window.removeEventListener("keydown",jt)},[i,de,o]),gIe(),hIe({onNewIssue:r(()=>d(),"onNewIssue"),onSearch:Se,onToggleSidebar:n,onTogglePanel:we,onShowShortcuts:r(()=>re(!0),"onShowShortcuts"),onGoToInbox:r(()=>S("/inbox"),"onGoToInbox")}),(0,m.useEffect)(()=>{if(!l)return;const jt=30,Je=50,Fe=75;let it=0,At=0;const $t=r(at=>{const De=at.touches[0];it=De.clientX,At=De.clientY},"onTouchStart"),zt=r(at=>{const De=at.changedTouches[0],Pe=De.clientX-it;if(!(Math.abs(De.clientY-At)>Fe)){if(!e&&it<jt&&Pe>Je){s(!0);return}e&&Pe<-50&&s(!1)}},"onTouchEnd");return document.addEventListener("touchstart",$t,{passive:!0}),document.addEventListener("touchend",zt,{passive:!0}),()=>{document.removeEventListener("touchstart",$t),document.removeEventListener("touchend",zt)}},[l,e,s]),(0,m.useEffect)(()=>{const jt=document.body.style.overflow;return document.body.style.overflow=l?"visible":"clip",()=>{document.body.style.overflow=jt}},[l]),(0,m.useEffect)(()=>{if(!l)return wIe()},[l]),(0,m.useEffect)(()=>{if(typeof document>"u")return;const jt=q.current;return jIe(jt)},[C.pathname]),(0,m.useEffect)(()=>{const jt=q.current;if(!jt)return;const Je=r(()=>{z.current.remember(K.current,jt.scrollTop)},"recordScroll");return jt.addEventListener("scroll",Je,{passive:!0}),()=>jt.removeEventListener("scroll",Je)},[]),(0,m.useLayoutEffect)(()=>{const jt=q.current,Je=Dwe({previousPathname:B.current,pathname:C.pathname,navigationType:_,state:C.state});B.current=C.pathname;const Fe=_==="POP",it=Fe?z.current.recall(C.key):0;if(K.current=C.key,Fe){J5(jt,it);const At=requestAnimationFrame(()=>J5(jt,it));return()=>cancelAnimationFrame(At)}Je&&$we(jt)},[C.key,C.pathname,C.state,_]),(0,t.jsx)(Pwe,{children:(0,t.jsxs)("div",{className:V("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)(H_e,{}),(0,t.jsx)(Q_e,{devServer:ce?.devServer}),(0,t.jsxs)("div",{className:V("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:V("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?ae:(0,t.jsx)(Ore,{})})}),(0,t.jsx)(Kre,{deploymentMode:ce?.deploymentMode})]}):(0,t.jsxs)(kmt,{open:e,collapsed:a,peeking:i,resizable:!0,onPanelMouseEnter:Ie,onPanelMouseLeave:Ze,onPanelFocusCapture:a?ue:void 0,onPanelBlurCapture:a?Be:void 0,children:[(0,t.jsx)("div",{className:"flex flex-1 min-h-0",children:(0,t.jsx)(Ore,{})}),(0,t.jsx)(Kre,{deploymentMode:ce?.deploymentMode})]}),!l&&se?(0,t.jsx)(Smt,{children:ae}):null,(0,t.jsxs)("div",{className:V("flex min-w-0 flex-col",l?"w-full":"h-full flex-1"),children:[(0,t.jsxs)("div",{className:V(l&&"sticky top-0 z-20 bg-background/95 backdrop-blur supports-[backdrop-filter]:bg-background/85"),children:[(0,t.jsx)(BU,{mobile:l,onNavigateHome:r(()=>S("/dashboard"),"onNavigateHome")}),(0,t.jsx)(Nmt,{}),l&&A?(0,t.jsx)("div",{className:"border-b border-border px-4 pb-3",children:(0,t.jsx)(YNe,{})}):null]}),(0,t.jsxs)("div",{className:V(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:V("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)(Zu,{scope:"invalid_company_prefix",requestedPrefix:w??b?.issuePrefix}):(0,t.jsx)(J_e,{children:(0,t.jsx)(Lb,{})})}),(0,t.jsx)(lke,{})]})]})]}),l&&(0,t.jsx)(V_e,{visible:W}),(0,t.jsx)(cke,{}),(0,t.jsx)(Hke,{}),(0,t.jsx)(D_e,{}),(0,t.jsx)(O_e,{}),(0,t.jsx)(q_e,{}),(0,t.jsx)(U_e,{open:Q,onOpenChange:re}),(0,t.jsx)(K_e,{}),(0,t.jsx)(W_e,{localTrusted:ce?.deploymentMode==="local_trusted"})]})})}r(Pmt,"Layout");var Wre=null;function Mmt(){return Wre??=new vS,Wre}r(Mmt,"getDetachedClient");function Dmt(){const e=(0,m.useContext)(pA),{data:s,isFetched:n}=te({queryKey:D.instance.experimentalSettings,queryFn:r(()=>vr.getExperimental(),"queryFn"),enabled:e!=null},e??Mmt());return e?{enabled:s?.enableConferenceRoomChat===!0,loaded:n}:{enabled:!1,loaded:!0}}r(Dmt,"useConferenceRoomChatEnabled");function Lmt(){const{enabled:e,loaded:s}=Dmt();return s?e?(0,t.jsx)(Lb,{}):(0,t.jsx)(An,{to:"/dashboard",replace:!0}):null}r(Lmt,"ConferenceRoomChatGate");var $mt=["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"],Omt={"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 }"}},Cps=$mt.map(e=>Omt[e]);function CIe({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)(lm,{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(CIe,"TaskBrowserActivity");function _Ie({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)(FKe,{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(_Ie,"TaskChatProjectCreatedCard");function Fmt({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)(Jf,{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(Fmt,"TaskChatSkillCreatedCard");function Bmt(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(Bmt,"McpIcon");var zmt=new Set(["tool","tool call","tool_call","acp_tool"]);function mu(e){const s=(e??"").trim().toLowerCase().replace(/\s*\((?:pending|in[_ -]?progress|completed|failed|cancelled|canceled)\)$/,"");return!s||zmt.has(s)}r(mu,"isGenericToolName");function LH(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(LH,"mcpToolIdentity");function $H(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($H,"identifierWords");function IIe(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(IIe,"sentenceCase");function ek(e){const s=(e??"").trim();return mu(s)?"Unnamed tool":IIe($H(LH(s)?.name??s))}r(ek,"humanizeToolName");var Fd=r((e,s,n)=>({key:e,singular:s,plural:n}),"group"),qmt={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:Fd("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:Fd("task_operation","task operation","task operations")},task_create:{action:"create",running:"Creating a task",completed:"Created a task",family:"plan",group:Fd("task_operation","task operation","task operations")},task_update:{action:"update",running:"Updating a task",completed:"Updated a task",family:"plan",group:Fd("task_operation","task operation","task operations")},task_list:{action:"list",running:"Listing tasks",completed:"Listed tasks",family:"plan",group:Fd("task_operation","task operation","task operations")},task_get:{action:"read",running:"Reading a task",completed:"Read a task",family:"plan",group:Fd("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:Fd("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"}},Umt={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:[]},Kmt={read:"read",edit:"update",delete:"delete",move:"move",search:"search",list:"list",execute:"run",think:"think",fetch:"fetch",switch_mode:"switch"};function Wmt(e){return $H(e).join("_")}r(Wmt,"normalizedKey");function Vmt(e){const s=e[0];if(!s)return null;for(const[n,a]of Object.entries(Umt))if(a.includes(s))return n;return null}r(Vmt,"inferredAction");function Hmt(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(Hmt,"actionFamily");var Qmt={terminal:Yf,grep:i8e,search:na,read:RS,edit:L4,web:_Ke,plan:wj,question:yc,agent:wb,safety:Fi,image:BA,wait:fu,mcp:Bmt,other:Jf};function Gmt(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(Gmt,"actionCopy");function Ymt(e){switch(e){case"run":return Fd("command","command","commands");case"read":case"list":return Fd("read","read","reads");case"search":return Fd("search","search","searches");case"update":case"create":case"delete":case"move":return Fd("file_change","file change","file changes");case"start":case"stop":return Fd("delegation","delegation","delegations");case"wait":return Fd("wait","wait","waits");default:return Fd("tool_action","tool action","tool actions")}}r(Ymt,"defaultSummaryGroup");function Jmt(e){return e==="read"||e==="list"?Fd("paperclip_read","Paperclip read","Paperclip reads"):Fd("task_operation","task operation","task operations")}r(Jmt,"paperclipSummaryGroup");function Xy(e){const s=(e.name??"").trim(),n=LH(s),a=(e.namespace??n?.namespace??"").trim(),i=(n?"mcp":e.transport??"builtin").toLowerCase(),o=(n?.name??s).trim(),l=$H(o),c=Wmt(o),d=qmt[c],u=Kmt[(e.operation??"").trim().toLowerCase()],h=Vmt(l),p=d?.action??u??h??"other",f=d?"exact":u?"kind":h?"inferred":mu(o)?"unnamed":"fallback",x=mu(o)?"Unnamed tool":ek(o),b=/^[A-Za-z][A-Za-z0-9_.:-]*$/.test(o),v=h&&b&&l.length>1?l.slice(1):[],j=v.length?IIe(v).replace(/^./,_=>_.toLowerCase()):void 0,N=d?.running&&d.completed?{running:d.running,completed:d.completed}:p==="other"?mu(o)?{running:"Running an unnamed tool",completed:"Ran an unnamed tool"}:{running:`Running ${x}`,completed:`Ran ${x}`}:Gmt(p,d?void 0:j),w=d?.family??Hmt(p),k=i==="mcp"?"mcp":w,S=a?ek(a):i==="mcp"?"MCP":void 0,C=a.toLowerCase()==="paperclip"?Jmt(p):d?.group??Ymt(p);return{icon:Qmt[k],family:k,runningLabel:N.running,completedLabel:N.completed,failedLabel:`${N.completed} · failed`,interruptedLabel:`${N.running} · stopped`,displayName:x,sourceLabel:S,technicalName:s||void 0,confidence:f,summaryGroup:C}}r(Xy,"toolActivityPresentation");function Gk(e){const s=Xy({name:e});return{family:s.family,icon:s.icon,verbLabel:s.runningLabel}}r(Gk,"toolTaxonomy");function AIe(e){const s=(e??"").trim().toLowerCase();return s==="thinking"?ug:s==="responding"||s.startsWith("responding (")?QKe:null}r(AIe,"statusLabelIcon");var kF=["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"],SF=["Brewing","Tinkering","Distilling","Deliberating"],Vre=(()=>{const e=[],s=Math.max(kF.length,SF.length);for(let n=0;n<s;n++)n<kF.length&&e.push(kF[n]),n<SF.length&&e.push(SF[n]);return e})(),Xmt=1e4;function Zmt(e){const s=(e??"").trim().toLowerCase();return s==="running"||s==="working"}r(Zmt,"isGenericStatusLabel");function eht(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(eht,"fnv1a");function tht(e,s=0){const n=Math.floor(Math.max(0,s)/Xmt);return Vre[(eht(e)+n)%Vre.length]}r(tht,"whimsyWord");var sht=[{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}],_ps=Array.from(new Set(sht.map(e=>e.group)));function TIe(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(TIe,"parseCssTimeMs");function nht(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(nht,"elapsedLabel");function rht(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(rht,"liveElapsedLabel");function aht(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(aht,"useLiveElapsedMs");function iht(e,s){return!Number.isFinite(e)||!Number.isFinite(s)||s<=0?0:Math.max(0,Math.round(e/s)-1)}r(iht,"lineScrollOffset");function j3(e){const s=getComputedStyle(document.documentElement).getPropertyValue(e),n=TIe(s);return Number.isFinite(n)?n:0}r(j3,"motionTokenMs");function oht({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 b=parseFloat(window.getComputedStyle(p).lineHeight);o(iht(p.scrollHeight,b))},"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),j3("--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:V("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(oht,"LiveSelfTalkLine");function lht(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(j=>{j.current!=null&&(window.clearTimeout(j.current),j.current=null)},"clear"),f=r(j=>{i.current=j,a(j)},"show"),x=r(()=>{p(u),p(h),u.current=window.setTimeout(()=>{if(u.current=null,o.current!=null)return;const j=i.current;j==null||j.streaming||(f({...j,leaving:!0}),h.current=window.setTimeout(()=>{h.current=null,i.current?.leaving&&f(null)},j3("--motion-line-scroll")))},j3("--motion-interstitial-dwell"))},"scheduleLeave"),b=r((j,N)=>{p(u),p(h),c.current=Date.now(),f({text:j,streaming:N,swapKey:(i.current?.swapKey??0)+1}),N||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){b(e,!0);return}if(v.streaming){v.text!==e&&f({...v,text:e});return}if(o.current=e,d.current==null){const j=j3("--motion-interstitial-dwell"),N=Math.max(0,c.current+j-Date.now());d.current=window.setTimeout(()=>{d.current=null;const w=o.current;o.current=null,w!=null&&b(w,l.current!=null)},N)}},[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(lht,"useHeldSelfTalk");var cht={running:{Icon:tt,spin:!0,tone:"text-(--status-agent-running)"},working:{Icon:tt,spin:!0,tone:"text-(--status-agent-running)"},awaiting_approval:{Icon:PS,spin:!1,tone:"text-primary"},interrupted:{Icon:bW,spin:!1,tone:"text-destructive"},refused:{Icon:Dm,spin:!1,tone:"text-destructive"},truncated:{Icon:a8e,spin:!1,tone:"text-(--status-agent-paused)"}};function RIe({item:e,onApprovalDecision:s,chevronOpen:n,onToggle:a}){const{Icon:i,spin:o,tone:l}=cht[e.status],c=e.status==="awaiting_approval",d=e.status==="running"||e.status==="working",u=aht(e.startedAtMs,d),h=lht(d?e.selfTalk:void 0,d),p=nht(e.elapsedMs);if(d){const f=rht(u??e.elapsedMs),x=e.selfTalk!=null,b=e.toolName?Gk(e.toolName).icon:x?null:AIe(e.label),v=x||Zmt(e.label)?tht(e.id,u??e.elapsedMs??0):e.label,j=(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)(Pn,{className:V("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)"})}),b?(0,t.jsx)(b,{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)(oht,{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:j}):j]})}return(0,t.jsxs)("div",{className:V("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:V("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:V("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(RIe,"TaskChatStatusPill");var Gg=(0,m.createContext)(null);function Ej(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(Ej,"formatBytes$4");var VP=new Set(["application/octet-stream","binary/octet-stream","application/x-binary"]),dht=[".mp4",".m4v",".webm",".mov",".qt",".quicktime"],uht=[".png",".jpg",".jpeg",".gif",".webp",".avif",".bmp",".ico"],mht=new Set(["application/wasm"]),hht=new Set(["application/zip","application/x-zip","application/x-zip-compressed"]),EIe=new Set(["text/markdown","text/x-markdown","application/markdown","application/x-markdown"]),pht=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"]),fht=[".csv",".css",".graphql",".htm",".html",".js",".json",".jsx",".log",".markdown",".md",".mdx",".php",".py",".sh",".sql",".toml",".ts",".tsx",".txt",".xml",".yaml",".yml"];function i2(e){return(e??"").toLowerCase().split(";")[0]?.trim()??""}r(i2,"normalizeOutputContentType");function xht(e){const s=(e??"").trim().toLowerCase();return s?fht.some(n=>s.endsWith(n)):!1}r(xht,"hasDocumentLikeFilename");function PIe(e){return hht.has(e)||e.endsWith("+zip")}r(PIe,"isZipContentType");function ght(e){return e?!!(e.startsWith("text/")||EIe.has(e)||pht.has(e)||e.startsWith("application/")&&(e.endsWith("+json")||e.endsWith("+xml"))):!1}r(ght,"isDocumentLikeOutputContentType");function bht(e,s){const n=i2(e);return!n||ght(n)||VP.has(n)&&xht(s)?!1:n.startsWith("video/")||n.startsWith("image/")||n==="application/pdf"||mht.has(n)||PIe(n)||VP.has(n)}r(bht,"isOutputEligibleContentType");function vht(e){const s=i2(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"}:PIe(s)?{label:"ZIP",tone:"zip"}:s.startsWith("image/")?{label:"IMG",tone:"image"}:EIe.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(vht,"getOutputFileGlyph");function im(e,s){const n=i2(e);if(n.startsWith("video/"))return!0;if(!VP.has(n))return!1;const a=(s??"").trim().toLowerCase();return dht.some(i=>a.endsWith(i))}r(im,"isVideoLikeOutput");function Zy(e){const s=i2(e);return s.startsWith("image/")&&s!=="image/svg+xml"}r(Zy,"isImageContentType");function ED(e,s){const n=i2(e);if(Zy(n))return!0;if(n&&!VP.has(n))return!1;const a=(s??"").trim().toLowerCase();return uht.some(i=>a.endsWith(i))}r(ED,"isImageLikeOutput");function Hre(e){const s=new Date(e).getTime();return Number.isNaN(s)?0:s}r(Hre,"toTime");function PD(e){const s=(e??[]).filter(n=>n.type==="artifact"&&n.provider==="paperclip").flatMap(n=>{const a=mBe.safeParse(n.metadata);return a.success&&!bht(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:Hre(a.createdAt)-Hre(n.createdAt)),{items:s,primary:s[0]??null,rest:s.slice(1),count:s.length}}r(PD,"getIssueOutputs");function OH(e){return e.metadata?.originalFilename||e.title||"output"}r(OH,"outputFilename");function MIe(e){return new Set(PD(e).items.flatMap(s=>{const n=s.metadata?.attachmentId;return n?[n]:[]}))}r(MIe,"getPromotedOutputAttachmentIds");function o2(e,s){const n=e?.toLowerCase().split(";")[0].trim();return n==="text/html"||n==="application/xhtml+xml"||/\.html?$/i.test(s??"")}r(o2,"isHtmlPreview");var yht=["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 jht(e){return`<!doctype html><html><head><meta charset="utf-8"><meta http-equiv="Content-Security-Policy" content="${yht}"><meta name="referrer" content="no-referrer"></head><body>${e}</body></html>`}r(jht,"htmlPreviewDocument");function wht(e){return e.contentType.toLowerCase().split(";")[0]?.trim()??""}r(wht,"normalizedContentType");function Mg(e){return e.originalFilename??e.id}r(Mg,"attachmentFilename");function MD(e){return e.openPath??e.contentPath}r(MD,"attachmentOpenPath");function VS(e){return e.downloadPath??`${e.contentPath}?download=1`}r(VS,"attachmentDownloadPath");function DIe(e){const s=wht(e);return ED(s,e.originalFilename)&&!/^image\/hei[cf](?:-sequence)?$/.test(s)}r(DIe,"isImageAttachment$1");function LIe(e){return im(e.contentType,e.originalFilename)}r(LIe,"isVideoAttachment");function $Ie(e){return Ige(e)}r($Ie,"isMarkdownAttachment");function Pj(e){const s=e.contentType.toLowerCase().split(";")[0].trim();return Ige(e)||o2(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(Pj,"isTextAttachment");function OIe(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(OIe,"downloadBlob$1");function Nht(e,s,n){OIe(e,new Blob([s],{type:`${n};charset=utf-8`}))}r(Nht,"downloadTextFile");var CF="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 FIe({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:b}=Op(),v=(0,m.useRef)(void 0);(0,m.useEffect)(()=>()=>clearTimeout(v.current),[]);const j=(0,m.useCallback)(async(_,R)=>{c(_),p(null);try{await R(),u(_)}catch(A){u(null),p(A instanceof Error?A.message:"Export failed")}finally{c(null)}clearTimeout(v.current),v.current=setTimeout(()=>{u(null),p(null)},2e3)},[]),N=(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 N())==="failed"&&p("Copy failed")}catch(_){p(_ instanceof Error?_.message:"Copy failed")}finally{c(null)}})()},[f,N]),k=b||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:V("flex items-center gap-0.5",o),"data-testid":"document-export-actions",children:[(0,t.jsx)("button",{type:"button",className:CF,disabled:l!==null,"aria-label":"Copy full content",title:k,"data-testid":"document-export-copy",onClick:r(_=>{_.preventDefault(),_.stopPropagation(),w()},"onClick"),children:x?(0,t.jsx)(us,{"aria-hidden":"true",className:"h-3.5 w-3.5"}):(0,t.jsx)(wr,{"aria-hidden":"true",className:"h-3.5 w-3.5"})}),(0,t.jsx)("button",{type:"button",className:CF,disabled:l!==null,"aria-label":"Download source",title:S,"data-testid":"document-export-download",onClick:r(_=>{_.preventDefault(),_.stopPropagation(),j("download",async()=>{const R=rUe(a);Nht(iee(n,R),await N(),R==="md"?"text/markdown":"text/plain")})},"onClick"),children:(0,t.jsx)(ho,{"aria-hidden":"true",className:"h-3.5 w-3.5"})}),(0,t.jsx)("button",{type:"button",className:CF,disabled:l!==null,"aria-label":"Export to PDF",title:C,"data-testid":"document-export-pdf",onClick:r(_=>{_.preventDefault(),_.stopPropagation(),j("pdf",async()=>{OIe(iee(n,"pdf"),await yt.getDocumentPdf(e,s))})},"onClick"),children:(0,t.jsx)($Ke,{"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!":b?"Copy failed":d?"Downloaded!":"")})]})}r(FIe,"DocumentExportActions");function TI({children:e,className:s}){return(0,t.jsx)("div",{className:V("relative aspect-video w-full overflow-hidden bg-accent/20",s),children:e})}r(TI,"PreviewFrame");function HP({label:e}){return(0,t.jsx)(TI,{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)(wl,{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(HP,"PlaceholderPreview");function kht({artifact:e}){const[s,n]=(0,m.useState)(!1);return s||!e.contentPath?(0,t.jsx)(HP,{label:"Image"}):(0,t.jsx)(TI,{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(kht,"ImagePreview");function Sht({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)(TI,{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)(mo,{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,b=x>0?Math.min(1,x/4):.05;try{Math.abs(f.currentTime-b)>.001?(f.currentTime=b,d()):c()}catch{c()}},"loadThumbnailFrame"),h=r(p=>{(o.current||p.currentTarget.currentTime>0)&&c()},"handleLoadedData");return(0,t.jsxs)(TI,{className:"bg-black",children:[(0,t.jsx)("video",{src:e.contentPath,preload:"metadata",muted:!0,playsInline:!0,"data-frame-ready":a?"true":"false",className:V("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)(mo,{className:"h-5 w-5 translate-x-0.5 text-white","aria-hidden":"true"})})})]})}r(Sht,"VideoPreview");function Cht({artifact:e}){const s=e.previewText?.trim();return s?(0,t.jsxs)(TI,{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)(HP,{label:e.source==="document"?"Document":"Text"})}r(Cht,"TextPreview");function l2({artifact:e}){switch(e.mediaKind){case"image":return(0,t.jsx)(kht,{artifact:e},e.contentPath);case"video":return(0,t.jsx)(Sht,{artifact:e},e.contentPath);case"text":case"document":return(0,t.jsx)(Cht,{artifact:e});case"file":return(0,t.jsx)(HP,{label:"File"});default:return(0,t.jsx)(HP,{})}}r(l2,"ArtifactPreview");function Qre({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(Qre,"SecondaryAction");function _ht({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)(l2,{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)(FIe,{issueId:e.issue.id,documentKey:e.documentKey,title:e.title}):null,e.openPath?(0,t.jsx)(Qre,{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)(Qre,{href:e.downloadPath,download:!0,title:"Download file",children:(0,t.jsx)(ho,{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 ",qd(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(_ht,"ArtifactCard");function Iht(e){return e&&/^\/api\/assets\/[^/?#]+\/content$/.test(e)?e:null}r(Iht,"paperclipHumanAvatarUrl");function BIe(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(BIe,"resolveIssueChatHumanAuthor");var ec={credentials:r(e=>Ce.get(`/companies/${e}/email/connections`),"credentials"),checkAddress:r((e,s,n,a)=>Ce.post(`/companies/${e}/email/connections/${s}/check-address`,n,{signal:a}),"checkAddress"),connect:r((e,s)=>Ce.post(`/companies/${e}/email/connections`,s),"connect"),inspectSaved:r((e,s)=>Ce.post(`/companies/${e}/email/connections/${s}/inspect`,{}),"inspectSaved"),list:r(e=>Ce.get(`/companies/${e}/email/inboxes`),"list"),setup:r((e,s)=>Ce.post(`/companies/${e}/email/inboxes`,s),"setup"),inspect:r((e,s)=>Ce.post(`/companies/${e}/email/inspect`,{apiKey:s}),"inspect"),control:r((e,s)=>Ce.post(`/email/inboxes/${e}/control`,{action:s}),"control"),reconnect:r((e,s,n)=>Ce.post(`/email/inboxes/${e}/reconnect`,{apiKey:s,receiveMode:n}),"reconnect"),resolve:r((e,s,n,a)=>Ce.post(`/companies/${e}/email/deliveries/${s}/resolve`,{outcome:n,providerMessageId:a}),"resolve"),thread:r((e,s)=>Ce.get(`/companies/${e}/email/tasks/${s}`),"thread"),send:r((e,s)=>Ce.post(`/companies/${e}/email/send`,s),"send")};function zIe(e,s){return te({queryKey:["email-thread",e,s],queryFn:r(()=>ec.thread(e,s),"queryFn"),enabled:!!(e&&s)&&!s.startsWith("chat:"),refetchInterval:r(n=>n.state.data===null?!1:3e3,"refetchInterval")})}r(zIe,"useEmailThread");var qIe=(0,m.createContext)(null);function Aht({companyId:e,issueId:s,children:n}){const a=zIe(e,s);return(0,t.jsx)(qIe.Provider,{value:a.data??null,children:n})}r(Aht,"EmailThreadProvider");function UIe(e){const s=(0,m.useContext)(qIe),n=s?.messages.find(a=>a.commentId===e);return n&&s?(0,t.jsx)(KIe,{message:n,publication:s.publications.find(a=>a.providerMessageId===n.providerMessageId),issueId:s.issueId}):null}r(UIe,"useEmailComment");function KIe({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)($9,{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)(wl,{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(KIe,"EmailMessageCard");var Cy=(0,m.createContext)(null);function Mj({items:e,initialIndex:s,open:n,onOpenChange:a}){const[i,o]=(0,m.useState)(s),l=(0,m.useRef)(null),c=(0,m.useCallback)(b=>{l.current=b},[]);(0,m.useEffect)(()=>{n&&o(s)},[n,s]);const d=(0,m.useCallback)(()=>{o(b=>(b+1)%e.length)},[e.length]),u=(0,m.useCallback)(()=>{o(b=>(b-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 b=r(v=>{v.key==="ArrowRight"?d():v.key==="ArrowLeft"?u():v.key==="Escape"&&a(!1)},"handler");return window.addEventListener("keydown",b),()=>window.removeEventListener("keydown",b)},[n,d,u,a]);const h=(0,m.useCallback)(b=>{const v=b.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=Mg(p),x=im(p.contentType,p.originalFilename);return(0,t.jsx)(m6e,{open:n,onOpenChange:a,children:(0,t.jsxs)(d6e,{children:[(0,t.jsx)(c6e,{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)(u6e,{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:VS(p),download:f,className:"text-white/50 hover:text-white transition-colors",title:"Download","aria-label":`Download ${f}`,onClick:r(b=>b.stopPropagation(),"onClick"),children:(0,t.jsx)(ho,{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)(zn,{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)(nm,{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)(Pn,{className:"h-7 w-7"})})})]}),(0,t.jsx)("div",{className:"h-6 shrink-0"})]})]})})}r(Mj,"ImageGalleryModal");function fv(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:{}}r(fv,"record$6");var WIe=(0,m.createContext)(null);function VIe(e){const s=(0,m.useContext)(WIe);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(VIe,"useWorkspaceBaseRefRecovery");function Tht({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(()=>Xr.get(l),"queryFn"),enabled:!!l,staleTime:1/0,retry:!1}),d=fv(fv(c?.resultJson).configurationIncomplete);let u=null;if(o&&l&&c?.companyId===e.companyId&&fv(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(j=>j.id===e.projectWorkspaceId)??e.project?.primaryWorkspace;let x="The task’s repository";if(f?.repoUrl)try{const j=new URL(f.repoUrl);(j.protocol==="https:"||j.protocol==="http:")&&(x=`${j.hostname}${j.pathname.replace(/\.git$/,"")}`)}catch{}const b=fv(fv(e.executionWorkspaceSettings).workspaceStrategy).baseRef,v=o.status!=="active"||e.status!=="blocked"||e.assigneeAgentId!==o.returnOwnerAgentId||c.agentId!==e.assigneeAgentId||typeof b=="string"&&b.trim()&&b!==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(j=>j.status!=="done"&&j.status!=="cancelled")?"Resolve the task’s blockers before retrying.":null);u={actionId:o.id,runId:l,props:{requestedRef:p,repository:x,taskOverride:b===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 j=>{try{const N=await yt.resolveRecoveryAction(e.id,{actionId:o.id,outcome:"restored",sourceIssueStatus:"todo",workspaceBaseRef:{requestedRef:p,branch:j}});if(N.issue.status!=="todo"||N.issue.assigneeAgentId!==e.assigneeAgentId||fv(fv(N.issue.executionWorkspaceSettings).workspaceStrategy).baseRef!==j)throw new Error("The task changed while saving. Refresh to check its current state.")}finally{a()}},"onRepair")}}}return(0,t.jsx)(WIe.Provider,{value:u,children:i})}r(Tht,"WorkspaceBaseRefRecoveryProvider");var HIe={neutral:{container:"border-border bg-muted/35 dark:bg-muted/20",iconWrap:"bg-muted text-foreground/70",icon:Uh,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:Uh,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:ha,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:Rs,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:Ik,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 Rht(e){try{return new Date(e).toLocaleString(void 0,{month:"short",day:"numeric",hour:"numeric",minute:"2-digit"})}catch{return e}}r(Rht,"formatTimestamp$1");function Eht({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:V("inline-flex items-center gap-1 rounded-sm font-medium underline-offset-2 hover:underline",s.label),children:n}):(0,t.jsx)("span",{className:V("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:V("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:V("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:V("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(Eht,"MetadataRow$1");function FH({sections:e,tone:s="neutral"}){const n=HIe[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)(Eht,{row:o,tone:n},l))})]},i))})}r(FH,"SystemNoticeMetadataSections");function BH({tone:e="neutral",label:s,body:n,source:a,metadata:i,detailsDefaultOpen:o=!1,timestamp:l,className:c}){const d=HIe[e],u=d.icon,[h,p]=(0,m.useState)(o),f=(0,m.useId)(),x=!!(i&&i.length>0),b=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":b,className:V("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:V("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:V("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:b}),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:Rht(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:V("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)(nn,{className:V("h-3.5 w-3.5 transition-transform duration-150",h&&"rotate-180")})]}):null]}),x&&h?(0,t.jsx)("div",{id:f,className:V("border-t bg-background/50 dark:bg-background/30",d.divider),children:(0,t.jsx)(FH,{sections:i,tone:e})}):null]})}r(BH,"SystemNotice");function QIe({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??""),[b,v]=(0,m.useState)(!1),[j,N]=(0,m.useState)(!1),[w,k]=(0,m.useState)(null),[S,C]=(0,m.useState)(null),_=(0,m.useRef)(!1),R=f.trim().length>0&&f.trim()!==e;async function A(T){const E=T.trim();if(!(!E||E===e||c||_.current||S)){if(!uBe(E)){k("Enter a valid branch name, such as master or release/next.");return}_.current=!0,N(!0),k(null);try{await d(E),C(E)}catch(L){k(L instanceof Error?L.message:"Refresh the task to check its current state, then try again.")}finally{_.current=!1,N(!1)}}}return r(A,"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)(us,{"aria-hidden":!0,className:"mt-0.5 size-4 shrink-0 text-(--status-task-icon-done)"}):(0,t.jsx)(Rs,{"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(),A(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)(ut,{id:`${u}-branch`,autoFocus:!0,value:f,disabled:j||!!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:j,onClick:r(()=>{p(!1),k(null)},"onClick"),children:"Cancel"}):(0,t.jsx)("span",{}),(0,t.jsxs)($,{type:"submit",size:"sm",disabled:j||!R||!!c,"aria-describedby":c?`${u}-unavailable`:void 0,children:[j&&(0,t.jsx)(tt,{"aria-hidden":!0,className:"size-3.5 animate-spin motion-reduce:animate-none"}),j?"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:j||!!c,onClick:r(()=>p(!0),"onClick"),children:"Choose another branch"}),(0,t.jsxs)($,{type:"button",size:"sm",disabled:j||!!c||n===e,"aria-describedby":c?`${u}-unavailable`:void 0,onClick:r(()=>{A(n)},"onClick"),children:[j&&(0,t.jsx)(tt,{"aria-hidden":!0,className:"size-3.5 animate-spin motion-reduce:animate-none"}),j?"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":b,"aria-controls":`${u}-details`,onClick:r(()=>v(T=>!T),"onClick"),children:[b?"Hide details":"Why did this happen?",(0,t.jsx)(nn,{"aria-hidden":!0,className:V("size-3",b&&"rotate-180")})]}),b&&(0,t.jsx)("div",{id:`${u}-details`,className:"mt-2 rounded-md border border-border bg-background",children:(0,t.jsx)(FH,{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(QIe,"WorkspaceBaseRefRecoveryNotice");var zH=(0,m.createContext)(null);function Pht({value:e,children:s}){return(0,t.jsx)(zH.Provider,{value:e,children:s})}r(Pht,"DispositionRecoveryProvider");function Mht(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(Mht,"readDispositionRecoverySnapshot");function GIe(e){return Mht(e,(0,m.useContext)(zH)?.issue.activeRecoveryAction)}r(GIe,"useDispositionRecoverySnapshot");function Dht(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(Dht,"dispositionRetryUnavailableReason");function Lht(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(Lht,"descriptionFor");function qH({snapshot:e,createdAt:s,defaultExpanded:n=!1}){const a=(0,m.useContext)(zH),[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)(),b=(0,m.useId)(),v=(0,m.useId)(),j=Dht(e,a),N=!!(a&&a.issue.activeRecoveryAction?.id!==e.actionId),w=e.assigneeAgentId&&a?.agentMap?.get(e.assigneeAgentId)?.name||"the assigned agent",k=d||N?us:Rs;async function S(){if(!(!a||j||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":b,className:"flex min-w-0 gap-2.5 py-3","data-testid":"disposition-recovery-notice",children:[(0,t.jsx)(k,{"aria-hidden":"true",className:V("mt-0.5 size-4 shrink-0",d||N?"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:b,className:"break-words text-sm font-medium text-foreground",children:d?"Retry requested":N?"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}.`:Lht(e)})]}),j&&!d?(0,t.jsxs)("p",{id:v,className:"text-xs leading-relaxed text-muted-foreground",children:[!N&&(0,t.jsx)("span",{className:"font-medium text-foreground",children:"Retry unavailable. "}),j]}):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&&!N?(0,t.jsxs)($,{size:"xs",variant:"outline",disabled:l||!!j,"aria-describedby":j?v:void 0,onClick:r(()=>{S()},"onClick"),children:[l?(0,t.jsx)(tt,{"aria-hidden":"true",className:"size-3 animate-spin motion-reduce:animate-none"}):(0,t.jsx)(Ii,{"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)(nn,{"aria-hidden":"true",className:V("size-3",i&&"rotate-180")})]}),s?(0,t.jsx)("time",{dateTime:s,className:"font-mono text-xs text-muted-foreground sm:ml-auto",children:ao(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(qH,"DispositionRecoveryNotice");var $ht="System update",Oht=80;function Fht(e){const s=e.match(/Latest retry failure: `([^`]+)`/);return s?s[1]:null}r(Fht,"retryFailureCode");function Bht(e){const s=e.match(/Recovery owner: \[([^\]]+)\]\(/)?.[1]?.trim();return s&&s.length>0?s:null}r(Bht,"recoveryOwnerName");function zht(e){const s=e.split(`
382
+ `)}`:void 0}r(dut,"sanitizeComponentStack");function Y_e(){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(Y_e,"readBrowserErrorState");function uut(e){const s=dut(e.componentStack);return{tags:{react_error_boundary:e.boundary},contexts:{react:s?{componentStack:s}:{},browser_state:Y_e()}}}r(uut,"buildBrowserErrorContext");var Are=Promise.resolve();function MH(e){const s=Are.then(e);return Are=s.catch(()=>{}),s}r(MH,"enqueue");var Qk=null;function mut(e,s){return MH(async()=>{if(!Qk)try{const n=await Id(()=>import("./prod-COP_vZWu.js"),__vite__mapDeps([4,5]));n.init(put(e,s)),Qk=n}catch{}})}r(mut,"initBrowserErrorMonitoring");function hut(){return MH(async()=>{const e=Qk;if(Qk=null,!e)return;const s=e.getClient();try{e.getCurrentScope().setClient(void 0)}catch{}try{await s?.close(2e3)}catch{}})}r(hut,"teardownBrowserErrorMonitoring");function DH(e,s){let n;try{s&&(n=uut(s))}catch{}MH(async()=>{try{n?Qk?.captureException(e,n):Qk?.captureException(e)}catch{}})}r(DH,"captureBrowserException");function put(e,s){return{dsn:e,environment:s??void 0,release:"5edd4c514ff33131927ec23883e03e8c58f6b94c",tracesSampleRate:0,sendDefaultPii:!1,beforeSend:r((n,a)=>{try{if(n.contexts={...n.contexts,browser_state:n.contexts?.browser_state??Y_e()},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(put,"buildBrowserSentryInitOptions");var fut=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){DH(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 J_e({children:e}){const s=oa(),n=Gn(),a=`${s.pathname}${s.search}`;return(0,t.jsx)(fut,{resetKey:a,onReset:r(()=>n(-1),"onReset"),children:e})}r(J_e,"RouteErrorBoundary");var Tre={bot:ro,cpu:Mm,brain:ug,zap:E5,rocket:bze,code:Zge,terminal:Yf,shield:jA,eye:Wd,search:na,wrench:Jf,hammer:vA,lightbulb:yA,sparkles:Mp,star:Dp,heart:w1,flame:uze,bug:by,cog:Qge,database:wA,globe:lm,lock:No,mail:$9,"message-square":Sp,"file-code":Fl,"git-branch":Xi,package:qh,puzzle:mg,target:Pp,wand:CW,atom:$ze,"circuit-board":TKe,radar:_ze,swords:m8e,telescope:JBe,microscope:GKe,crown:S4,gem:Xge,hexagon:Ud,pentagon:ZKe,fingerprint:l6},xut="bot";function gut(e){return e&&pBe.includes(e)?Tre[e]:Tre[xut]}r(gut,"getAgentIcon");function zP({icon:e,className:s}){const n=gut(e);return(0,t.jsx)(n,{className:s})}r(zP,"AgentIcon");function X_e({open:e,onOpenChange:s,...n}){return(0,t.jsx)(zs,{open:e,onOpenChange:s,children:(0,t.jsxs)(Ws,{"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)(Vs,{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)(but,{...n,onComplete:r(()=>s(!1),"onComplete")},String(e))]})})}r(X_e,"AgentChatPicker");function but({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),[b,v]=(0,m.useState)(null);async function j(N){if(f)return;x(N.id),v(null);const w=new AbortController;u.current=w;try{await s(N,w.signal),d.current&&n()}catch(k){v(k instanceof Error?k.message:"Couldn’t open chat. Try again.")}finally{x(null)}}return r(j,"selectAgent"),(0,t.jsxs)(NA,{children:[(0,t.jsx)(wS,{"aria-label":"Search agents by name or role",placeholder:"Search by name or role…",value:h,onValueChange:p}),b&&(0,t.jsx)("p",{role:"alert",className:"px-4 py-3 text-sm text-destructive",children:b}),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)(jS,{children:[(0,t.jsx)(yS,{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)(zu,{children:e.map(N=>(0,t.jsxs)(Xo,{value:N.id,keywords:[N.name,N.title??"",N.role],onSelect:r(()=>{j(N)},"onSelect"),disabled:f!==null,className:"gap-3 px-3 py-3",children:[c?c(N):(0,t.jsx)(zP,{icon:N.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:N.name}),(0,t.jsx)("span",{className:"truncate text-xs text-muted-foreground",children:N.title??N.role})]}),l&&(0,t.jsx)("span",{className:"shrink-0 text-xs text-muted-foreground",children:l.includes(N.id)?"Open chat":"New chat"}),N.status==="paused"&&(0,t.jsx)("span",{className:"text-xs text-(--status-agent-paused)",children:"Paused"}),N.status==="terminated"&&(0,t.jsx)("span",{className:"text-xs text-muted-foreground",children:"Terminated"}),N.status==="pending_approval"&&(0,t.jsx)("span",{className:"text-xs text-muted-foreground",children:"Awaiting approval"})]},N.id))})]})]})}r(but,"AgentChatPickerResults");function y3({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:b}){const v=Gn(),[j,N]=(0,m.useState)(!1),[w,k]=(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 A(){k(""),S.current?.focus()}return r(A,"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(()=>N(!0),"onClick"),children:(0,t.jsx)(bn,{className:"size-4"})})]}),(0,t.jsxs)("div",{className:"relative",children:[(0,t.jsx)(na,{"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)(ut,{ref:S,"aria-label":"Search agents",placeholder:"Find an agent",value:w,onChange:r(T=>k(T.target.value),"onChange"),onKeyDown:r(T=>{T.key==="Escape"&&(T.stopPropagation(),k(""))},"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:A,children:(0,t.jsx)(zn,{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:b,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:Kl(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:V("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)(or,{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(()=>N(!0),"onClick"),children:"Choose an agent"}),e.length>0&&(0,t.jsx)($,{variant:"outline",size:"sm",onClick:A,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)(X_e,{agents:n,open:j,onOpenChange:N,existingChatAgentIds:s??e.map(T=>T.id),loading:o,error:l,onRetry:c,renderAgentIcon:r(T=>(0,t.jsx)(or,{agent:T,size:32}),"renderAgentIcon"),onSelect:r(async(T,E)=>{p?await p(T,E):u?await u(T,E):v(`/chats/${encodeURIComponent(Kl(T))}`),E?.aborted||k("")},"onSelect")})]})}r(y3,"AgentConversationSidebar");var qP={list:r(e=>Ce.get(`/companies/${e}/chats`),"list"),get:r((e,s)=>Ce.get(`/companies/${e}/chats/${encodeURIComponent(s)}`),"get"),ensure:r((e,s)=>Ce.post(`/companies/${e}/chats/${encodeURIComponent(s)}`,{}),"ensure")};function Z_e(){const{selectedCompanyId:e}=ps(),{enabled:s,loaded:n}=_j(),a=te({queryKey:D.auth.session,queryFn:r(()=>Ma.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(()=>Ct.list(e),"queryFn"),enabled:s&&!!e}),chats:te({queryKey:D.agentChats.list(e,i),queryFn:r(()=>qP.list(e),"queryFn"),enabled:s&&!!e&&a.isSuccess}),session:a}}r(Z_e,"useAgentChatNavigation");function eIe(e,s){const n=Nt(),a=Gn(),{isMobile:i,setSidebarOpen:o}=qa(),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 qP.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(Kl(c))}`),i&&o(!1))},[n,e,s,a,i,o])}r(eIe,"useOpenAgentChat");function vut(){const{companyId:e,userId:s,agents:n,chats:a,session:i}=Z_e(),o=eIe(e,s),l=Gn(),c=px(e),{isMobile:d,setSidebarOpen:u}=qa(),{pathname:h}=oa(),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]:[]))]:[],b=tm({queries:x.map(C=>({queryKey:D.agents.detail(C),queryFn:r(()=>Ct.get(C,e),"queryFn")}))}),v=new Map(f.map(C=>[C.id,C]));for(const C of b)C.data&&v.set(C.data.id,C.data);const j=[...v.values()].find(C=>C.id===p||C.status!=="terminated"&&encodeURIComponent(Kl(C))===p),N=(a.data??[]).flatMap(C=>{const _=C.conversationAgentId?v.get(C.conversationAgentId):void 0;return _?[_]:[]});j&&!N.some(C=>C.id===j.id)&&N.unshift(j);const w=new Set(N.map(C=>C.id)),k=f.filter(C=>!w.has(C.id)&&C.status!=="terminated"&&(!c.isSuccess||Ig(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)(y3,{agents:[...N,...k],availableAgents:f,existingChatAgentIds:N.map(C=>C.id),activeId:j?.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:b.some(C=>C.isPending),historyError:b.find(C=>C.error)?.error,onRetryHistory:r(()=>{b.filter(C=>C.isError).forEach(C=>{C.refetch()})},"onRetryHistory"),onAddChat:o,onSelect:r(C=>{l(`/chats/${encodeURIComponent(C.status==="terminated"?C.id:Kl(C))}`),d&&u(!1)},"onSelect")},`${e}:${s}`)}r(vut,"AgentConversationsSidebar");var KT=240,zU=208,qU=420,Rre=16;function UP(e){return Math.min(qU,Math.max(zU,e))}r(UP,"clampSidebarWidth$1");function Ere(e){if(typeof window>"u")return KT;try{const s=window.localStorage.getItem(e);if(!s)return KT;const n=Number.parseInt(s,10);return Number.isFinite(n)?UP(n):KT}catch{return KT}}r(Ere,"readStoredSidebarWidth$1");function Pre(e,s){if(!(typeof window>"u"))try{window.localStorage.setItem(e,String(UP(s)))}catch{}}r(Pre,"writeStoredSidebarWidth$1");function yut({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)(()=>Ere(o)),[x,b]=(0,m.useState)(!1),v=(0,m.useRef)(p),j=(0,m.useRef)(null);(0,m.useEffect)(()=>{const P=Ere(o);v.current=P,f(P)},[o]);const N=s?p:0,w=s?n?64:N:0,k=s?n&&!a?64:N:0,S=k>w,C=i&&s&&!n,_=(0,m.useMemo)(()=>({width:`${w}px`}),[w]),R=(0,m.useMemo)(()=>({width:`${k}px`}),[k]),A=(0,m.useCallback)(P=>{const U=UP(P);v.current=U,f(U),Pre(o,U)},[o]),T=(0,m.useCallback)(P=>{C&&(P.preventDefault(),P.currentTarget.setPointerCapture(P.pointerId),j.current={startX:P.clientX,startWidth:v.current},b(!0))},[C]),E=(0,m.useCallback)(P=>{if(!j.current)return;const U=UP(j.current.startWidth+P.clientX-j.current.startX);v.current=U,f(U)},[]),L=(0,m.useCallback)(()=>{j.current&&(j.current=null,b(!1),Pre(o,v.current))},[o]),O=(0,m.useCallback)(P=>{C&&(P.key==="ArrowLeft"?(P.preventDefault(),A(p-Rre)):P.key==="ArrowRight"?(P.preventDefault(),A(p+Rre)):P.key==="Home"?(P.preventDefault(),A(zU)):P.key==="End"&&(P.preventDefault(),A(qU)))},[C,A,p]);return(0,t.jsxs)("div",{className:V("relative h-full shrink-0",l),style:_,children:[(0,t.jsx)("div",{className:V("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":zU,"aria-valuemax":qU,"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:L,onPointerCancel:L,onLostPointerCapture:L,onKeyDown:O,children:(0,t.jsx)("div",{className:V("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(yut,"SidebarShell$1");function WT({children:e,className:s}){return(0,t.jsx)("div",{"data-secondary-sidebar":"",className:V("h-full w-full min-w-0 overflow-hidden",s),children:(0,t.jsx)(Fwe,{children:e})})}r(WT,"SecondarySidebar$1");var tIe={listStacks:r(()=>Ce.get("/cloud/stacks"),"listStacks")};function RD(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(RD,"cloudAppUrl");function sIe(e){return RD(e,"/stacks/new")}r(sIe,"cloudStackCreateUrl");function nIe(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(nIe,"tenantSignInReturnPath");function jut(e,s,n){const a=s?.trim();if(!a)return null;const i=RD(e,`/v1/stacks/${encodeURIComponent(a)}/entry-redirect`);if(!i)return null;const o=new URL(i);return o.searchParams.set("returnTo",nIe(n)),o.toString()}r(jut,"cloudStackEntryUrl");function rIe(e,s){const n=s?.trim();return n?RD(e,`/workspaces/${encodeURIComponent(n)}/settings?section=people`):null}r(rIe,"cloudStackInviteUrl");function wut(e){return RD(e,"/orgs?manage=1")}r(wut,"cloudPortfolioManageUrl");function aIe(){const e=Yc(),s=!!e,n=te({queryKey:D.cloud.stacks,queryFn:r(()=>tIe.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:rIe(e.cloudBaseUrl,a.stackSlug)}r(aIe,"useCloudInviteUrl");function Nut(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(Nut,"canInviteCompanyMembers");function iIe(e=!0){const s=Pge(),n=te({queryKey:D.access.currentBoardAccess,queryFn:r(()=>lr.getCurrentBoardAccess(),"queryFn"),enabled:e,retry:!1,staleTime:3e4});return e&&Nut(s?.selectedCompanyId,n.data)}r(iIe,"useCanInviteCompanyMembers");function oIe(e){const s=window.location.hostname.endsWith(".staging.paperclip.app"),{data:n,isError:a}=te({queryKey:D.stagingCommit,queryFn:r(()=>yu.get(),"queryFn"),enabled:s&&e,staleTime:0,retry:!1});return s&&!a?n?.commit??null:null}r(oIe,"useStagingCommit");function kut(e){return e?.trim().toLowerCase().replace(/['"]/g,"").replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")||null}r(kut,"slugifyUserPart");function lIe(e){const s=[e?.id,e?.name,e?.email?.split("@")[0],e?.email];for(const n of s){const a=kut(n);if(a)return`/u/${a}`}return"/u/me"}r(lIe,"userProfilePath");var Sut="Toggle the app appearance.";function ZN({className:e,variant:s="icon",onAfterToggle:n}){const{theme:a,toggleTheme:i}=E6e(),o=a==="dark",l=o?"Switch to light mode":"Switch to dark mode",c=o?Kje:Kye;function d(){i(),n?.()}return r(d,"handleClick"),s==="compact-menu-action"?(0,t.jsxs)("button",{type:"button",className:V("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:V("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:Sut})]})]}):(0,t.jsx)($,{type:"button",variant:"ghost",size:"icon-sm",onClick:d,"aria-label":l,title:l,className:V("text-muted-foreground",e),children:(0,t.jsx)(c,{})})}r(ZN,"ThemeToggle");var AI=null,cIe=!1,UU=!1,KU=new Set;function KP(){for(const e of KU)e()}r(KP,"emit");function Cut(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(Cut,"isIosSafariLike");function _ut(e=window){const s=r(a=>{a.preventDefault(),AI=a,KP()},"onPrompt"),n=r(()=>{AI=null,cIe=!0,KP()},"onInstalled");return e.addEventListener("beforeinstallprompt",s),e.addEventListener("appinstalled",n),()=>{e.removeEventListener("beforeinstallprompt",s),e.removeEventListener("appinstalled",n)}}r(_ut,"captureInstallPrompt");function Iut(){return cIe||FU()?"installed":AI?"prompt":Cut()?"ios-manual":"unavailable"}r(Iut,"installAvailability");async function Aut(){const e=AI;if(!e)return"unavailable";AI=null,KP(),await e.prompt();const{outcome:s}=await e.userChoice;return s}r(Aut,"promptInstall");function WU(e){UU!==e&&(UU=e,KP())}r(WU,"setIosInstallHelpOpen");function Tut(){return UU}r(Tut,"iosInstallHelpOpen");function Rut(){return(0,m.useSyncExternalStore)(dIe,Tut,()=>!1)}r(Rut,"useIosInstallHelpOpen");function dIe(e){return KU.add(e),()=>{KU.delete(e)}}r(dIe,"subscribe$1");function Eut(){return(0,m.useSyncExternalStore)(dIe,Iut,()=>"unavailable")}r(Eut,"useInstallAvailability");var Mre="Install app",Put="Add Paperclip to your home screen or dock.";function uIe({variant:e,onAfterAction:s}){const n=Eut();if(n==="installed"||n==="unavailable")return null;const a=r(()=>{n==="ios-manual"?WU(!0):Aut(),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)(ho,{className:"size-4"})}),(0,t.jsx)("span",{className:"min-w-0 flex-1 truncate",children:Mre})]}):(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)(ho,{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:Mre}),(0,t.jsx)("span",{className:"block text-xs text-muted-foreground",children:Put})]})]})}r(uIe,"InstallAppMenuAction");function Mut(){const e=Rut();return(0,t.jsx)(zs,{open:e,onOpenChange:WU,children:(0,t.jsxs)(Ws,{children:[(0,t.jsxs)(on,{children:[(0,t.jsx)(Vs,{children:"Install Paperclip"}),(0,t.jsx)(hn,{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)(vF,{index:1,icon:(0,t.jsx)(c8e,{className:"size-4"}),children:["Tap ",(0,t.jsx)("strong",{children:"Share"})," in the Safari toolbar."]}),(0,t.jsxs)(vF,{index:2,icon:(0,t.jsx)(u8e,{className:"size-4"}),children:["Choose ",(0,t.jsx)("strong",{children:"Add to Home Screen"}),"."]}),(0,t.jsxs)(vF,{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)(dr,{children:(0,t.jsx)($,{type:"button",onClick:r(()=>WU(!1),"onClick"),children:"Done"})})]})})}r(Mut,"IosInstallHelpDialog");function vF({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(vF,"InstallStep");function Dut(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(Dut,"formatTimestamp$2");function Lut(e){return!!e&&!Number.isNaN(new Date(e).getTime())}r(Lut,"isValidTimestamp");function $ut(e){return e?.devServer?.lastRestartAt??e?.serverInfo?.processStartedAt??null}r($ut,"restartTimestamp");function Out(e){const s=e?.serverInfo?.git;return s?.available?`${s.shortSha} · ${s.subject}`:"Commit unavailable"}r(Out,"commitLabel");function Fut(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(Fut,"localChangesLabel");function yF({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(yF,"ServerInfoRow");function mIe(){const e=te({queryKey:D.instance.experimentalSettings,queryFn:r(()=>vr.getExperimental(),"queryFn")}).data?.enableServerInfoDebugView===!0,s=te({queryKey:D.health,queryFn:r(()=>yu.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=$ut(n),l=Lut(o),c=i?"Health unavailable":a?"Loading...":Dut(o),d=i?"Health unavailable":a?"Loading...":Out(n),u=i?"Health unavailable":a?"Loading...":Fut(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)(yF,{icon:fu,label:"Last restarted",value:c,dateTime:!i&&!a&&l?o:null}),(0,t.jsx)(yF,{icon:fW,label:"Running commit",value:d}),(0,t.jsx)(yF,{icon:LKe,label:"Checkout state",value:u})]})}r(mIe,"SidebarServerInfo");var But="/company/settings/members?tab=invites",zut="https://docs.paperclip.ing/",qut="https://paperclip.ing/feedback";function Uut(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(Uut,"deriveInitials$2");function jF({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(jF,"MenuAction$1");function Dre({deploymentMode:e,open:s,onOpenChange:n,forceExpanded:a=!1}){const o=!!Yc(),{hidden:l,loaded:c}=vu(),d=aIe(),u=iIe(!o),h=o?d:u?But:null,p=c&&h!==null&&!wg(l,"company.members")&&!wg(l,"company.invites"),[f,x]=(0,m.useState)(!1),{isMobile:b,setSidebarOpen:v,collapsed:j,peeking:N}=qa(),w=j&&!N&&!a,k=s??f,S=oIe(k),C=n??x,{data:_}=te({queryKey:D.auth.session,queryFn:r(()=>Ma.getSession(),"queryFn"),retry:!1}),R=OS({onSignedOut:O}),A=_?.user.name?.trim()||"Board",T=_?.user.email?.trim()||(e==="authenticated"?"Signed in":"Local workspace board"),E=Uut(A),L=lIe(_?.user);function O(){C(!1),b&&v(!1)}r(O,"closeNavigationChrome");function P(){R.mutate()}return r(P,"handleSignOut"),(0,t.jsx)("div",{className:"bg-border/50 px-3 py-2 dark:bg-muted",children:(0,t.jsxs)("div",{className:V("flex items-center gap-0.5",!w&&"px-2"),children:[(0,t.jsxs)(ur,{open:k,onOpenChange:C,children:[(0,t.jsx)(Nr,{asChild:!0,children:(0,t.jsxs)("button",{type:"button",className:V("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)(Hc,{src:_.user.image,alt:A}):null,(0,t.jsx)(vo,{children:E})]}),(0,t.jsx)("span",{className:V("min-w-0 flex-1 truncate",w&&"block w-0 min-w-0 overflow-hidden whitespace-nowrap text-transparent select-none"),children:A})]})}),(0,t.jsxs)(rr,{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:L,"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)(Hc,{src:_.user.image,alt:A}):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:A}),(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)(jF,{label:"Settings",icon:xu,href:"/company/settings",onClick:O}),p&&h?(0,t.jsx)(jF,{label:"Invite",icon:eh,href:h,topLevel:o,onClick:O}):null,(0,t.jsx)(jF,{label:"Documentation",icon:RS,href:zut,external:!0,onClick:r(()=>C(!1),"onClick")}),(0,t.jsx)(ZN,{variant:"compact-menu-action",onAfterToggle:r(()=>C(!1),"onAfterToggle")}),(0,t.jsx)(uIe,{variant:"compact-menu-action",onAfterAction:r(()=>C(!1),"onAfterAction")}),e==="authenticated"?(0,t.jsxs)("button",{type:"button",className:V("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:P,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)(Up,{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)(mIe,{})]})]})]}),!w&&!o?(0,t.jsxs)(Bn,{children:[(0,t.jsx)(Fn,{asChild:!0,children:(0,t.jsx)("a",{href:qut,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(Dre,"SidebarAccountMenu$1");function hIe({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(b){if(b.defaultPrevented){u();return}if(o){const v=K0e({armed:l,defaultPrevented:b.defaultPrevented,key:b.key,metaKey:b.metaKey,ctrlKey:b.ctrlKey,altKey:b.altKey,target:b.target,hasOpenDialog:$p()});if(v==="arm"){h();return}if(v==="navigate_inbox"){u(),b.preventDefault(),o();return}if(v==="focus_comment"||v==="open_file_viewer"){u(),b.preventDefault();return}v==="disarm"&&u()}if(!_A(b.target)&&!$p()){if(b.key==="/"&&!b.metaKey&&!b.ctrlKey&&!b.altKey){b.preventDefault(),Rqe()||s?.();return}if(b.key==="?"&&!b.metaKey&&!b.ctrlKey&&!b.altKey){b.preventDefault(),i?.();return}b.key==="c"&&!b.metaKey&&!b.ctrlKey&&!b.altKey&&(b.preventDefault(),e?.()),b.key==="["&&!b.metaKey&&!b.ctrlKey&&(b.preventDefault(),n?.()),b.key==="]"&&!b.metaKey&&!b.ctrlKey&&(b.preventDefault(),a?.())}}r(p,"handleKeyDown");const f=r(()=>u(),"handlePointerDown"),x=r(b=>{b.target instanceof HTMLElement&&b.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(hIe,"useKeyboardShortcuts");var Kut=new Set(["auth","invite","board-claim","cli-auth","docs","s"]);function pIe(e){const s=(e.split("?")[0]??"").split("/").filter(Boolean);if(s.length===0)return!0;const[n]=s;return!Kut.has(n)}r(pIe,"isRememberableCompanyPath");function Wut(e){const s=$y(e.companyPrefix);return e.companies.find(n=>$y(n.issuePrefix)===s)??null}r(Wut,"findCompanyByPrefix");function Vut(e){const s=O9(e.pathname);return s?Wut({companies:e.companies,companyPrefix:s})?.id??null:e.fallbackCompanyId}r(Vut,"getRememberedPathOwnerCompanyId");function Hut(e){const s=e.path?C4(e.path):"/dashboard";if(!pIe(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&&$y(i[1]??"")!==$y(e.companyPrefix))return"/dashboard"}return s}r(Hut,"sanitizeRememberedPathForCompany");var fIe="paperclip.companyPaths";function xIe(){try{const e=localStorage.getItem(fIe);if(e)return JSON.parse(e)}catch{}return{}}r(xIe,"getCompanyPaths");function Qut(e,s){const n=xIe();n[e]=s,localStorage.setItem(fIe,JSON.stringify(n))}r(Qut,"saveCompanyPath");function gIe(){const{companies:e,selectedCompanyId:s,selectedCompany:n,selectionSource:a}=ps(),i=oa(),o=Gn(),l=(0,m.useRef)(s),c=(0,m.useMemo)(()=>Vut({companies:e,pathname:i.pathname,fallbackCompanyId:l.current}),[e,i.pathname]),d=i.pathname+i.search;(0,m.useEffect)(()=>{const u=c,h=C4(d);u&&pIe(h)&&Qut(u,h)},[d,c]),(0,m.useEffect)(()=>{if(s){if(l.current!==null&&s!==l.current&&a!=="route_sync"&&n){const u=xIe(),h=Hut({path:u[s],companyPrefix:n.issuePrefix});o(`/${n.issuePrefix}${h}`,{replace:!0})}l.current=s}},[n,s,a,o])}r(gIe,"useCompanyPageMemory");var Gut=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 bIe(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 Gut({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,b=d.update(p,f);b!==x&&a(b)}))},"onScroll");return window.addEventListener("scroll",h,{passive:!0}),()=>{window.removeEventListener("scroll",h),u!==null&&cancelAnimationFrame(u)}},[e,s]),n}r(bIe,"useMobileNavVisibility");function vIe(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(vIe,"resolveArchivedCompanyBounce");function Yut(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(Yut,"resolveCompanyArchiveDeparture");function yIe(e){const{selectionSource:s,selectedCompanyId:n,routeCompanyId:a}=e;return!(n===a||s==="manual"&&n)}r(yIe,"shouldSyncCompanySelectionFromRoute");function Jut(e,s){return e instanceof HTMLElement?!(s instanceof HTMLElement)||!document.contains(s)||s===document.body||s===document.documentElement?!0:!e.contains(s):!1}r(Jut,"shouldFocusMainContentAfterNavigation");function jIe(e){if(!(e instanceof HTMLElement))return()=>{};const s=window.requestAnimationFrame(()=>{Jut(e,document.activeElement)&&e.focus({preventScroll:!0})});return()=>window.cancelAnimationFrame(s)}r(jIe,"scheduleMainContentFocus");function wIe(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(wIe,"pinDocumentScrollToZero");function Zu({scope:e="global",requestedPrefix:s}){const n=oa(),{setBreadcrumbs:a}=Hn(),{companies:i,selectedCompany:o}=ps();(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)(Rs,{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)(T5,{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(Zu,"NotFoundPage");function Xut(e,s){return VNe(e,s)[0]?.toLowerCase()??null}r(Xut,"getCompanyRouteSegment$1");var Zut=new Set(["browse","connections","assistant-connection","connect","chat","vercel-connect","review","attention","gateways","advanced","app"]);function emt({sidebarSections:e}){const{sidebarOpen:s,setSidebarOpen:n,toggleSidebar:a,collapsed:i,peeking:o,setPeeking:l,isMobile:c,setForceCollapsed:d}=qa(),{openNewIssue:u,openOnboarding:h}=rl(),{togglePanelVisible:p}=fx(),f=Td()?.pushToast??null,{companies:x,loading:b,selectedCompany:v,selectedCompanyId:j,selectionSource:N,setSelectedCompanyId:w}=ps(),{companyPrefix:k,pluginRoutePath:S,agentId:C,routineId:_}=fa(),R=Gn(),A=oa(),T=_4(),{enabled:E}=Ac(),L=HNe(A.pathname,k),O=L.builtInContextualSurface==="settings",P=L.companySegments,U=L.isTaskDetail,{enabled:M}=_j(),B=M&&P[0]?.toLowerCase()==="chats",q=E&&(U||B),z=P[0]?.toLowerCase()==="tools",K=P[0]?.toLowerCase()==="apps",W=K&&P[1]&&!Zut.has(P[1].toLowerCase())?P[1]:null,Q=K&&P[1]?.toLowerCase()==="app"&&P[2]?P[2]:null,re=(0,m.useRef)(!1),J=(0,m.useRef)(null),ie=(0,m.useRef)(null),X=(0,m.useRef)(new Lwe),ne=(0,m.useRef)(A.key),oe=bIe(c&&!U,A.pathname),[G,Z]=(0,m.useState)(!1),Y=(0,m.useMemo)(()=>{if(!k)return null;const ft=k.toUpperCase();return x.find(kt=>kt.issuePrefix.toUpperCase()===ft)??null},[x,k]),ae=!!k&&!b&&x.length>0&&!Y,se=(0,m.useMemo)(()=>S?.toLowerCase()??Xut(A.pathname,k),[k,A.pathname,S]),ce=Y?.id??null,pe=Y?.issuePrefix??null,{slots:we}=Rd({slotTypes:["page","routeSidebar"],companyId:ce,enabled:!!(ce&&se)}),Se=(0,m.useMemo)(()=>OW(we,se),[se,we]),Te=(0,m.useMemo)(()=>({companyId:ce,companyPrefix:pe}),[ce,pe]),le=O?(0,t.jsx)(rQe,{}):!E&&L.builtInContextualSurface==="skills"?(0,t.jsx)(pte,{}):W?(0,t.jsx)(mte,{kind:"connection",connectionId:W}):Q?(0,t.jsx)(mte,{kind:"application",applicationId:Q}):K||z?(0,t.jsx)(mQe,{}):Se?E?(0,t.jsx)(VA,{surface:`plugin:${Se.id}`,title:Se.displayName,children:(0,t.jsx)(am,{slot:Se,context:Te,className:"min-h-0 flex-1",missingBehavior:"placeholder"})}):(0,t.jsx)(am,{slot:Se,context:Te,className:"h-full w-full",missingBehavior:"placeholder"}):null,fe=B?(0,t.jsx)(vut,{}):L.builtInContextualSurface==="agent"&&C?(0,t.jsx)(CQe,{agentRef:C}):E&&L.builtInContextualSurface==="routine"&&_?(0,t.jsx)(Q9e,{children:(0,t.jsx)(AQe,{routineId:_})}):E&&L.builtInContextualSurface==="skills"?(0,t.jsx)(pte,{}):le,de=fe!=null,Ee=E&&de&&(B||L.builtInContextualSurface==="skills"||L.builtInContextualSurface==="agent"||L.builtInContextualSurface==="routine"||K||z),Me=E&&de&&!Ee,ve=de&&(!E||Ee),Ie=!E||!de?null:Se&&!L.builtInContextualSurface?`plugin:${Se.id}`:L.builtInContextualSurface,Ze=(0,m.useRef)(null),{data:ue}=te({queryKey:D.health,queryFn:r(()=>yu.get(),"queryFn"),retry:!1,refetchInterval:r(ft=>ft.state.data?.devServer?.enabled?2e3:!1,"refetchInterval"),refetchIntervalInBackground:!1});(0,m.useLayoutEffect)(()=>(d(!E&&de),()=>d(!1)),[de,d,E]),(0,m.useEffect)(()=>{const ft=Ze.current;Ie&&k&&ft&&ft.surface!==Ie&&ft.pathname!==A.pathname&&tQe({surface:Ie,companyPrefix:k,previousPathname:ft.pathname}),Ze.current={pathname:A.pathname,surface:Ie}},[k,Ie,A.pathname]),(0,m.useEffect)(()=>{b||re.current||ue?.deploymentMode!=="authenticated"&&(ue?.cloud||x.length===0&&(re.current=!0,h()))},[x,b,h,ue?.cloud,ue?.deploymentMode]),(0,m.useEffect)(()=>{if(!k||b||x.length===0)return;if(!Y){const kt=(j?x.find(Ke=>Ke.id===j):null)??x[0]??null;kt&&j!==kt.id&&w(kt.id,{source:"route_sync"});return}if(k!==Y.issuePrefix){const kt=A.pathname.replace(/^\/[^/]+/,"");R(`/${Y.issuePrefix}${kt}${A.search}`,{replace:!0});return}const ft=vIe({matchedCompany:Y,selectedCompanyId:j,companies:x});if(ft){f?.({title:`${Y.name} is archived`,body:`Switched to ${ft.name}.`,tone:"info",dedupeKey:`archived-company-bounce:${Y.id}`}),w(ft.id,{source:"route_sync"}),R(`/${ft.issuePrefix}/dashboard`,{replace:!0});return}yIe({selectionSource:N,selectedCompanyId:j,routeCompanyId:Y.id})&&w(Y.id,{source:"route_sync"})},[k,x,b,Y,A.pathname,A.search,R,f,N,j,w]);const Be=p,ht=(0,m.useCallback)(()=>{document.dispatchEvent(new KeyboardEvent("keydown",{key:"k",metaKey:!0,bubbles:!0,cancelable:!0}))},[]),jt=(0,m.useRef)(null),Je=(0,m.useRef)(!1),Fe=(0,m.useRef)(!1),it=(0,m.useCallback)(()=>{jt.current!==null&&(window.clearTimeout(jt.current),jt.current=null)},[]),At=(0,m.useCallback)(()=>{it(),jt.current=window.setTimeout(()=>l(!0),50)},[it,l]),$t=(0,m.useCallback)(()=>{it(),l(!0)},[it,l]),zt=(0,m.useCallback)(()=>{it(),jt.current=window.setTimeout(()=>l(!1),120)},[it,l]),at=(0,m.useCallback)(()=>{Je.current=!0,i&&!Fe.current&&At()},[i,At]),De=(0,m.useCallback)(()=>{Je.current=!1,Fe.current=!1,zt()},[zt]),Pe=(0,m.useCallback)(()=>{Fe.current||$t()},[$t]),dt=(0,m.useCallback)(()=>{Je.current||zt()},[zt]);(0,m.useEffect)(()=>it,[it]);const rt=(0,m.useRef)(i);return(0,m.useEffect)(()=>{i!==rt.current&&(i?(it(),l(!1),Fe.current=Je.current):Fe.current=!1,rt.current=i)},[i,it,l]),(0,m.useEffect)(()=>{if(!o)return;const ft=r(kt=>{kt.key==="Escape"&&(it(),l(!1))},"onKeyDown");return window.addEventListener("keydown",ft),()=>window.removeEventListener("keydown",ft)},[o,it,l]),gIe(),hIe({onNewIssue:r(()=>u(),"onNewIssue"),onSearch:ht,onToggleSidebar:a,onTogglePanel:Be,onShowShortcuts:r(()=>Z(!0),"onShowShortcuts"),onGoToInbox:r(()=>R("/inbox"),"onGoToInbox")}),(0,m.useEffect)(()=>{if(!c)return;const ft=30,kt=50,Ke=75;let $e=0,ze=0;const et=r(st=>{const Mt=st.touches[0];$e=Mt.clientX,ze=Mt.clientY},"onTouchStart"),ge=r(st=>{const Mt=st.changedTouches[0],Ss=Mt.clientX-$e;if(!(Math.abs(Mt.clientY-ze)>Ke)){if(!s&&$e<ft&&Ss>kt){n(!0);return}s&&Ss<-50&&n(!1)}},"onTouchEnd");return document.addEventListener("touchstart",et,{passive:!0}),document.addEventListener("touchend",ge,{passive:!0}),()=>{document.removeEventListener("touchstart",et),document.removeEventListener("touchend",ge)}},[c,s,n]),(0,m.useEffect)(()=>{const ft=document.body.style.overflow;return document.body.style.overflow=c?"visible":"clip",()=>{document.body.style.overflow=ft}},[c]),(0,m.useEffect)(()=>{if(!c)return wIe()},[c]),(0,m.useEffect)(()=>{if(typeof document>"u")return;const ft=ie.current;return jIe(ft)},[A.pathname]),(0,m.useEffect)(()=>{const ft=ie.current;if(!ft)return;const kt=r(()=>{X.current.remember(ne.current,ft.scrollTop)},"recordScroll");return ft.addEventListener("scroll",kt,{passive:!0}),()=>ft.removeEventListener("scroll",kt)},[]),(0,m.useLayoutEffect)(()=>{const ft=ie.current,kt=Dwe({previousPathname:J.current,pathname:A.pathname,navigationType:T,state:A.state});J.current=A.pathname;const Ke=T==="POP",$e=Ke?X.current.recall(A.key):0;if(ne.current=A.key,Ke){J5(ft,$e);const ze=requestAnimationFrame(()=>J5(ft,$e));return()=>cancelAnimationFrame(ze)}kt&&$we(ft)},[A.key,A.pathname,A.state,T]),(0,t.jsx)(Pwe,{children:(0,t.jsxs)("div",{className:V("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)(H_e,{}),(0,t.jsx)(Q_e,{devServer:ue?.devServer}),(0,t.jsxs)("div",{className:V("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:V("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:de?(0,t.jsx)(WT,{children:fe}):(0,t.jsx)(lte,{children:e})})}),(0,t.jsx)(Dre,{deploymentMode:ue?.deploymentMode,forceExpanded:Me})]}):(0,t.jsxs)(yut,{open:s,collapsed:Me?!1:i,peeking:Me?!1:o,resizable:!0,onPanelMouseEnter:Me?void 0:at,onPanelMouseLeave:Me?void 0:De,onPanelFocusCapture:!Me&&i?Pe:void 0,onPanelBlurCapture:!Me&&i?dt:void 0,children:[(0,t.jsx)("div",{className:"flex flex-1 min-h-0",children:Me?(0,t.jsx)(WT,{children:fe}):(0,t.jsx)(lte,{children:e})}),(0,t.jsx)(Dre,{deploymentMode:ue?.deploymentMode,forceExpanded:Me})]}),!c&&ve&&!Ee?(0,t.jsx)(WT,{className:"w-60 shrink-0",children:fe}):null,(0,t.jsxs)("div",{className:V("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:V(!c&&q&&"hidden",c&&"sticky top-0 z-20 bg-background/95 backdrop-blur supports-[backdrop-filter]:bg-background/85"),children:[(0,t.jsx)(BU,{mobile:c,onNavigateHome:r(()=>R("/dashboard"),"onNavigateHome")}),(0,t.jsx)(xte,{}),c&&O?(0,t.jsx)("div",{className:"border-b border-border px-4 pb-3",children:(0,t.jsx)(YNe,{})}):null]}),(0,t.jsxs)("div",{className:V(c?"block":"flex flex-1 min-h-0",!c&&q&&"streamlined-task-detail-surface"),children:[!c&&Ee?(0,t.jsx)(WT,{className:"w-60 shrink-0 bg-background",children:fe}):null,(0,t.jsxs)("div",{className:V(!c&&q?"flex min-w-0 flex-1 flex-col":"contents"),children:[!c&&q?(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)(BU,{mobile:!1,onNavigateHome:r(()=>R("/dashboard"),"onNavigateHome")}),(0,t.jsx)(xte,{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:V("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:ae?(0,t.jsx)(Zu,{scope:"invalid_company_prefix",requestedPrefix:k??v?.issuePrefix}):(0,t.jsx)(J_e,{children:(0,t.jsx)(Lb,{})})})]}),(0,t.jsx)(lke,{taskDetailLayout:!c&&q})]})]})]}),c&&(0,t.jsx)(V_e,{visible:oe}),(0,t.jsx)(cke,{}),(0,t.jsx)(Hke,{}),(0,t.jsx)(D_e,{}),(0,t.jsx)(O_e,{}),(0,t.jsx)(q_e,{}),(0,t.jsx)(U_e,{open:G,onOpenChange:Z}),(0,t.jsx)(K_e,{}),(0,t.jsx)(Udt,{health:ue}),(0,t.jsx)(W_e,{localTrusted:ue?.deploymentMode==="local_trusted"})]})})}r(emt,"Layout$1");var NIe=(0,m.createContext)(!1);function tmt({children:e}){return(0,t.jsx)(NIe.Provider,{value:!0,children:e})}r(tmt,"SidebarNavExpandedProvider");function smt(){return(0,m.useContext)(NIe)}r(smt,"useSidebarNavExpanded");function Ga({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:b,trailing:v,trailingLabel:j,liveAccessory:N}){const{isMobile:w,setSidebarOpen:k,collapsed:S,peeking:C}=qa(),_=smt(),R=S&&!C&&!_,A=c!=null&&c>0,T=x!=null&&x>0,E=T?`${x} live`:A?`${c}${u?` ${u}`:""}`:f?"attention needed":void 0,L=!R||!E&&!j?void 0:`${s}${E?`, ${E}`:""}${j?`, ${j}`:""}`,O=(0,t.jsxs)($b,{to:e,state:hx,end:i,"aria-label":L,onClick:r(()=>{w&&k(!1)},"onClick"),className:r(({isActive:P})=>V("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",b??P?"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&&A&&(0,t.jsx)("span",{className:V("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?xj:V("min-w-0 flex-1 truncate",l),children:s}),!R&&v,!R&&h&&(0,t.jsx)(ot,{variant:"ghost",className:V("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||N)&&(0,t.jsxs)("span",{className:"ml-auto flex items-center gap-1.5",children:[N,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&&A&&(0,t.jsx)(ot,{variant:"ghost",className:V("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)(Bn,{children:[(0,t.jsx)(Fn,{asChild:!0,children:(0,t.jsx)("div",{children:O})}),(0,t.jsx)(On,{side:"right",children:s})]}):O}r(Ga,"SidebarNavItem");var nmt=3,Lre=12e4,rmt=[{value:"top",label:"Top"},{value:"alphabetical",label:"Alphabetical"},{value:"recent",label:"Recent"}];function Cw(e,s){const n=e[s];if(!n)return 0;const a=new Date(n).getTime();return Number.isFinite(a)?a:0}r(Cw,"agentTimestamp");function $re(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=Cw(i,"lastHeartbeatAt")-Cw(a,"lastHeartbeatAt");if(o!==0)return o;const l=Cw(i,"updatedAt")-Cw(a,"updatedAt");if(l!==0)return l;const c=Cw(i,"createdAt")-Cw(a,"createdAt");return c!==0?c:a.name.localeCompare(i.name,void 0,{sensitivity:"base"})}),n)}r($re,"sortAgents");var amt="opacity-0 transition-opacity group-hover/agent:opacity-100 group-focus-within/agent:opacity-100";function imt({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:b=!1}){const v=Kl(n),j=s?`${Qu(n)}/${s}`:Qu(n),N=`${Qu(n)}/configuration`,w=e===v,k=n.status==="paused",S=k&&n.pauseReason==="budget",C=n.orgChainHealth?.status==="invalid_org_chain",_=k?"Resume agent":"Pause agent",R=a||n.status==="pending_approval"||S||k&&C,A=a?"Updating...":S?"Budget paused":k&&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,L=(0,t.jsx)(Ga,{to:j,label:n.name,iconNode:(0,t.jsx)(or,{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:V("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)(KN,{status:p,compact:!0}):null,C?(0,t.jsx)(Rs,{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)(UA,{title:"Agent paused by budget"}):void 0});return d?L:(0,t.jsxs)("div",{className:"group/agent relative flex items-center",children:[L,f&&!i&&x?(0,t.jsx)("span",{className:"absolute right-10 top-1/2 -translate-y-1/2",children:(0,t.jsx)(Sj,{size:"row",quiet:!0,starred:!0,pending:b,resourceName:n.name,onToggle:r(()=>x(n,!1),"onToggle"),revealClassName:amt})}):null,(0,t.jsxs)(Zr,{children:[(0,t.jsx)(ta,{asChild:!0,children:(0,t.jsx)($,{variant:"ghost",size:"icon-xs",className:V("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)(ea,{align:"end",className:"w-48",children:[x?(0,t.jsxs)(t.Fragment,{children:[(0,t.jsxs)(ds,{onClick:r(()=>{b||x(n,!f)},"onClick"),disabled:b,children:[b?(0,t.jsx)(tt,{className:"size-4 motion-safe:animate-spin"}):(0,t.jsx)(Dp,{className:V("size-4",f&&"fill-amber-500 text-amber-500")}),(0,t.jsx)("span",{children:f?"Remove from starred":"Star agent"})]}),(0,t.jsx)(ni,{})]}):null,(0,t.jsx)(ds,{asChild:!0,children:(0,t.jsxs)(We,{to:N,onClick:r(()=>{i&&h(!1)},"onClick"),children:[(0,t.jsx)(sc,{className:"size-4"}),(0,t.jsx)("span",{children:"Edit agent"})]})}),(0,t.jsx)(ni,{}),(0,t.jsxs)(ds,{onClick:r(()=>{R||c(n,k?"resume":"pause")},"onClick"),disabled:R,title:S?"Agent was paused by budget limits":void 0,children:[k?(0,t.jsx)(OA,{className:"size-4"}):(0,t.jsx)(Kd,{className:"size-4"}),(0,t.jsx)("span",{children:A})]}),(0,t.jsx)(ni,{}),(0,t.jsxs)(ds,{onClick:r(()=>{o||l(n)},"onClick"),disabled:o,children:[o?(0,t.jsx)(tt,{className:"size-4 motion-safe:animate-spin"}):(0,t.jsx)(Up,{className:"size-4"}),(0,t.jsx)("span",{children:o?"Leaving...":"Leave agent"})]})]})]})]})}r(imt,"SidebarAgentItem");function omt({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=Nt(),{selectedCompanyId:u}=ps(),h=MS(u),{openNewAgent:p}=rl(),{isMobile:f,setSidebarOpen:x,collapsed:b,peeking:v}=qa(),j=b&&!v,{pushToast:N}=Qr(),w=oa(),{data:k}=te({queryKey:D.agents.list(u),queryFn:r(()=>Ct.list(u),"queryFn"),enabled:!!u}),{data:S}=te({queryKey:D.instance.experimentalSettings,queryFn:r(()=>vr.getExperimental(),"queryFn"),enabled:!!u}),C=S?.enableBuiltInAgents===!0,{data:_}=te({queryKey:D.builtInAgents.list(u),queryFn:r(()=>mp.list(u),"queryFn"),enabled:!!u&&C}),R=(0,m.useMemo)(()=>{const ve=new Map;if(!C)return ve;for(const Ie of _??[])Ie.agentId&&ve.set(Ie.agentId,Ie.status);return ve},[_,C]),{data:A}=te({queryKey:D.auth.session,queryFn:r(()=>Ma.getSession(),"queryFn")}),T=px(u),E=zb(u),L=D.liveRuns(u),O=jo({companyId:u,resourceKey:"live-runs",queryKey:L,enabled:!!u,refetchInterval:!1,leaderOnly:!0}),{data:P,dataUpdatedAt:U}=te({queryKey:L,queryFn:r(()=>Xr.liveRunsForCompany(u),"queryFn"),enabled:O.enabled,refetchInterval:O.refetchInterval});wo(O,P,U);const M=(0,m.useMemo)(()=>{const ve=new Map;for(const Ie of P??[])ve.set(Ie.agentId,(ve.get(Ie.agentId)??0)+1);return ve},[P]),B=(0,m.useMemo)(()=>{const ve=new Set;for(const[Ie,Ze]of M)Ze>0&&ve.add(Ie);return ve},[M]),q=(0,m.useMemo)(()=>(k??[]).filter(ve=>ve.status!=="terminated"&&(!T.isSuccess||Ig(T.data,"agent",ve.id)!=="left")),[k,T.data,T.isSuccess]),z=A?.user?.id??A?.session?.userId??null,K=(0,m.useMemo)(()=>u?Hwe(u,z):null,[z,u]),[W,Q]=(0,m.useState)(()=>K?WN(K):"top"),{orderedAgents:re}=Ywe({agents:q,companyId:u,userId:z}),J=(0,m.useMemo)(()=>$re(re,W),[re,W]),ie=(0,m.useMemo)(()=>new Set(J.map(ve=>ve.id)),[J]);(0,m.useEffect)(()=>{const ve=Date.now();for(const Ie of B)c.current.set(Ie,ve);for(const Ie of c.current.keys())ie.has(Ie)||c.current.delete(Ie)},[B,ie]);const X=(0,m.useMemo)(()=>{const ve=Date.now(),Ie=c.current;return J.filter(Ze=>{if((M.get(Ze.id)??0)>0)return!0;const ue=Ie.get(Ze.id);return ue!==void 0&&ve-ue<=Lre})},[M,o,J]),ne=X.length>0,oe=e?ne?X:J.slice(0,nmt):J,G=e&&J.length>0,Z=w.pathname.match(/^\/(?:[^/]+\/)?agents\/([^/]+)(?:\/([^/]+))?/),Y=Z?.[1]??null,ae=Z?.[2]??null;(0,m.useEffect)(()=>{if(!K){Q("top");return}Q(WN(K))},[K]),(0,m.useEffect)(()=>{if(!K)return;const ve=r(Ze=>{Ze.key===K&&Q(WN(K))},"onStorage"),Ie=r(Ze=>{const ue=Ze.detail;!ue||ue.storageKey!==K||Q(ue.sortMode)},"onCustomEvent");return window.addEventListener("storage",ve),window.addEventListener(rI,Ie),()=>{window.removeEventListener("storage",ve),window.removeEventListener(rI,Ie)}},[K]),(0,m.useEffect)(()=>{if(!e)return;const ve=Date.now();let Ie=null;for(const ue of J){if((M.get(ue.id)??0)>0)continue;const Be=c.current.get(ue.id);if(Be===void 0)continue;const ht=Be+Lre;ht<ve||(Ie=Ie===null?ht:Math.min(Ie,ht))}if(Ie===null)return;const Ze=window.setTimeout(()=>{l(ue=>ue+1)},Math.max(0,Ie-ve+1));return()=>{window.clearTimeout(Ze)}},[e,J,M,o]);const se=(0,m.useCallback)(ve=>{const Ie=ve==="alphabetical"||ve==="recent"?ve:"top";Q(Ie),K&&Gwe(K,Ie)},[K]),ce=ye({mutationFn:r(({agent:ve,action:Ie})=>Ie==="pause"?Ct.pause(ve.id,u??void 0):Ct.resume(ve.id,u??void 0),"mutationFn"),onMutate:r(({agent:ve})=>{i(Ie=>{const Ze=new Set(Ie);return Ze.add(ve.id),Ze})},"onMutate"),onSuccess:r(async(ve,{agent:Ie,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(Ie.id)}),d.invalidateQueries({queryKey:D.agents.detail(Kl(Ie))})]),N({title:Ze==="pause"?"Agent paused":"Agent resumed",body:Ie.name,tone:"success"})},"onSuccess"),onError:r((ve,{agent:Ie,action:Ze})=>{N({title:Ze==="pause"?"Could not pause agent":"Could not resume agent",body:ve instanceof Error?ve.message:Ie.name,tone:"error"})},"onError"),onSettled:r((ve,Ie,{agent:Ze})=>{i(ue=>{const Be=new Set(ue);return Be.delete(Ze.id),Be})},"onSettled")}),pe=(0,m.useCallback)(ve=>E.mutate({resourceType:"agent",resourceId:ve.id,resourceName:ve.name,state:"left"}),[E]),we=(0,m.useCallback)(ve=>E.isPending&&E.variables?.resourceType==="agent"&&E.variables.resourceId===ve.id,[E.isPending,E.variables]),Se=(0,m.useCallback)((ve,Ie)=>E.mutate({resourceType:"agent",resourceId:ve.id,resourceName:ve.name,starred:Ie}),[E]),Te=(0,m.useCallback)(ve=>E.isPending&&E.variables?.resourceType==="agent"&&E.variables.resourceId===ve.id&&E.variables.starred!==void 0,[E.isPending,E.variables]),le=(0,m.useMemo)(()=>new Set(H4(T.data,"agent")),[T.data]),fe=(0,m.useMemo)(()=>$re(q.filter(ve=>le.has(ve.id)),"alphabetical"),[q,le]),de=(0,m.useMemo)(()=>oe.filter(ve=>!le.has(ve.id)),[oe,le]),Ee=h&&!h.loading?q.find(ve=>ve.id===h.primaryAgentId):void 0,Me=r((ve,Ie)=>(0,t.jsx)(imt,{activeAgentId:Y,activeTab:ae,agent:ve,disabled:a.has(ve.id),isMobile:f,leaving:we(ve),onLeaveAgent:pe,onPauseResume:r((Ze,ue)=>ce.mutate({agent:Ze,action:ue}),"onPauseResume"),rail:j,runCount:M.get(ve.id)??0,setSidebarOpen:x,builtInStatus:R.get(ve.id),starred:Ie||kj(T.data,"agent",ve.id),onToggleStar:Se,starPending:Te(ve)},ve.id),"renderAgentRow");return(0,t.jsxs)(pg,{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:rmt,radioValue:W,onRadioValueChange:se},children:[[...Ee?[Ee]:[],...fe.filter(ve=>ve.id!==Ee?.id),...de.filter(ve=>ve.id!==Ee?.id)].map(ve=>Me(ve,le.has(ve.id))),G&&(()=>{const ve=(0,t.jsxs)(We,{to:"/agents/all",state:hx,"aria-label":j?"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:j?"block w-0 min-w-0 overflow-hidden whitespace-nowrap text-transparent select-none":void 0,children:"See all agents"})]});return j?(0,t.jsxs)(Bn,{children:[(0,t.jsx)(Fn,{asChild:!0,children:ve}),(0,t.jsx)(On,{side:"right",children:"See all agents"})]}):ve})()]})}r(omt,"SidebarAgents");var lmt="opacity-0 transition-opacity group-hover/starred-project:opacity-100 group-focus-within/starred-project:opacity-100";function cmt(){const{selectedCompanyId:e}=ps(),{isMobile:s,setSidebarOpen:n,collapsed:a,peeking:i}=qa(),o=a&&!i,l=oa(),{data:c}=te({queryKey:D.projects.list(e),queryFn:r(()=>ra.list(e),"queryFn"),enabled:!!e}),d=px(e),u=zb(e),h=l.pathname.match(/^\/(?:[^/]+\/)?projects\/([^/]+)/)?.[1]??null,p=(0,m.useMemo)(()=>{if(!d.isSuccess)return[];const v=new Set(H4(d.data,"project"));if(v.size===0)return[];const j=new Map((c??[]).map(N=>[N.id,N]));return Array.from(v).map(N=>j.get(N)).filter(N=>!!N).sort((N,w)=>N.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]),b=(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 j=Ng(v),N=h===j||h===v.id,w=b(v),k=w&&u.variables?.starred===!1,S=w&&u.variables?.state==="left",C=kj(d.data,"project",v.id),_=(0,t.jsxs)($b,{to:`/projects/${j}/issues`,state:hx,onClick:r(()=>{s&&n(!1)},"onClick"),className:V("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",N?"bg-accent text-foreground":"text-foreground/80 hover:bg-accent/50 hover:text-foreground"),children:[(0,t.jsx)(Wm,{color:v.color??null,icon:v.icon??null,size:"xs"}),(0,t.jsx)("span",{className:o?xj:"flex-1 truncate",children:v.name}),!o&&v.visibility==="private"?(0,t.jsx)(No,{className:"size-3.5 shrink-0 text-muted-foreground","aria-label":"Private project"}):null,!o&&v.pauseReason==="budget"?(0,t.jsx)(UA,{title:"Project paused by budget"}):null]});return(0,t.jsxs)("div",{className:"group/starred-project relative flex items-center",children:[o?(0,t.jsxs)(Bn,{children:[(0,t.jsx)(Fn,{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)(Sj,{size:"row",quiet:!0,starred:C,pending:k,resourceName:v.name,onToggle:r(()=>f(v),"onToggle"),revealClassName:lmt})}):null,!o&&s?(0,t.jsxs)(Zr,{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)(ea,{align:"end",className:"w-48",children:[(0,t.jsxs)(ds,{onClick:r(()=>{w||f(v)},"onClick"),disabled:w,children:[k?(0,t.jsx)(tt,{className:"size-4 motion-safe:animate-spin"}):(0,t.jsx)(Dp,{className:"size-4 fill-amber-500 text-amber-500"}),(0,t.jsx)("span",{children:"Remove from starred"})]}),(0,t.jsx)(ni,{}),(0,t.jsxs)(ds,{onClick:r(()=>{w||x(v)},"onClick"),disabled:w,children:[S?(0,t.jsx)(tt,{className:"size-4 motion-safe:animate-spin"}):(0,t.jsx)(Up,{className:"size-4"}),(0,t.jsx)("span",{children:"Leave project"})]})]})]}):null]},v.id)})})}r(cmt,"SidebarStarredProjects");var dmt="size-5 shrink-0 rounded-md text-(length:--text-micro)",umt="size-(--organization-popover-avatar-size) shrink-0 rounded-lg text-(length:--text-micro)",mmt="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",wF="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 kIe({company:e,inPopover:s=!1}){return(0,t.jsx)(Ag,{companyName:e.name,logoUrl:e.logoUrl,className:s?umt:dmt})}r(kIe,"WorkspaceIcon");function hmt({company:e,isEditing:s,isSelected:n,onSelect:a}){const{attributes:i,listeners:o,setActivatorNodeRef:l,setNodeRef:c,transform:d,transition:u,isDragging:h}=AS({id:e.id,disabled:!s});return(0,t.jsxs)(ds,{ref:c,style:{transform:_S.Transform.toString(d),transition:u,zIndex:h?10:void 0},onSelect:r(p=>{if(s){p.preventDefault();return}a(e)},"onSelect"),className:V(mmt,s&&"cursor-grab",h&&"opacity-80"),children:[(0,t.jsx)(kIe,{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)(O4,{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)(us,{className:"size-4 text-foreground"}):null})]})}r(hmt,"SortableCompanyItem");function pmt(e={}){return(0,t.jsx)(KNe,{...e,children:(0,t.jsx)(fmt,{...e})})}r(pmt,"SidebarCompanyMenu");function fmt({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}=ps(),{openOnboarding:p}=rl(),{isMobile:f,setSidebarOpen:x,collapsed:b,peeking:v}=qa(),j=b&&!v,N=oa(),w=Gn(),k=e??n,S=s??a,C=NS(Xf(G9,{activationConstraint:{distance:8}}),Xf(o0e,{activationConstraint:{delay:180,tolerance:6}})),_=(0,m.useMemo)(()=>l.filter(J=>J.status!=="archived"),[l]),{data:R}=te({queryKey:D.auth.session,queryFn:r(()=>Ma.getSession(),"queryFn"),retry:!1}),A=R?.user?.id??R?.session?.userId??null,{orderedCompanies:T,persistOrder:E}=UNe({companies:_,userId:A}),{hidden:L,loaded:O}=vu(),P=O&&!wg(L,"company.members")&&!wg(L,"company.invites"),U="company",M=c?.name??null,B=!!Yc(),q=OS({onSignedOut:K});function z(J){J||o(!1),S(J)}r(z,"handleOpenChange");function K(){S(!1),o(!1),f&&x(!1)}r(K,"closeNavigationChrome");function W(J){const ie=N.pathname.split("/")[1]?.toUpperCase(),X=_.some(oe=>oe.issuePrefix.toUpperCase()===ie),ne=J.id!==c?.id&&(N.pathname.startsWith("/instance/")||X);d(J.id),S(!1),f&&x(!1),ne&&w(`/${J.issuePrefix}/dashboard`)}r(W,"selectCompany");function Q(){B||(S(!1),f&&x(!1),p({initialStep:1}))}r(Q,"addCompany");const re=(0,m.useCallback)(J=>{const{active:ie,over:X}=J;if(!X||ie.id===X.id)return;const ne=T.map(Z=>Z.id),oe=ne.indexOf(ie.id),G=ne.indexOf(X.id);oe===-1||G===-1||E(R4(ne,oe,G))},[T,E]);return(0,t.jsxs)(Zr,{open:k,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":M?`Open ${M} ${U} switcher`:`Open ${U} switcher`,children:[(0,t.jsxs)("span",{className:"flex min-w-0 flex-1 items-center gap-2",children:[c?(0,t.jsx)(kIe,{company:c}):null,(0,t.jsx)("span",{className:V("min-w-0 truncate text-sm font-bold text-foreground",j&&"block w-0 min-w-0 overflow-hidden whitespace-nowrap text-transparent select-none"),title:M??void 0,children:M??`Select ${U}`})]}),!j&&(0,t.jsx)(I4,{className:"size-3.5 shrink-0 text-muted-foreground"})]})}),(0,t.jsxs)(ea,{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)(Fb,{className:"p-0 text-(length:--text-compact) font-semibold text-foreground",children:"Organizations"}),(0,t.jsx)("button",{type:"button",onClick:r(J=>{J.preventDefault(),J.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)(IS,{sensors:C,collisionDetection:SA,onDragEnd:re,children:(0,t.jsx)(CS,{items:T.map(J=>J.id),strategy:IA,children:T.map(J=>(0,t.jsx)(hmt,{company:J,isEditing:i,isSelected:J.id===c?.id,onSelect:W},J.id))})}),T.length===0?u?(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)(ds,{disabled:!0,children:"Couldn't load companies"}),(0,t.jsxs)(ds,{onSelect:r(J=>{J.preventDefault(),h()},"onSelect"),children:[(0,t.jsx)(Ai,{className:"h-4 w-4 mr-2"}),"Try again"]})]}):(0,t.jsx)(ds,{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:[!B&&(0,t.jsxs)(ds,{onClick:Q,className:wF,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"})]}),P?(0,t.jsx)(ds,{asChild:!0,disabled:i,className:wF,children:(0,t.jsxs)(We,{to:"/company/settings/invites",onClick:r(J=>{if(i){J.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)(eh,{className:"size-4"})}),(0,t.jsx)("span",{className:"min-w-0 flex-1 truncate",children:M?`Invite people to ${M}`:"Invite people"})]})}):null,R?.session?(0,t.jsxs)(ds,{className:wF,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)(Up,{className:"size-4"})}),(0,t.jsx)("span",{className:"min-w-0 flex-1 truncate",children:q.isPending?"Signing out...":"Sign out"})]}):null]})]})]})}r(fmt,"BuiltinCompanyMenu");function Ore(){const{openNewIssue:e}=rl(),[s,n]=(0,m.useState)(!0),[a,i]=(0,m.useState)(!0),{selectedCompanyId:o,selectedCompany:l}=ps(),{collapsed:c,peeking:d}=qa(),u=c&&!d,h=J4(o),{data:p,isFetched:f}=te({queryKey:D.instance.experimentalSettings,queryFn:r(()=>vr.getExperimental(),"queryFn")}),x=D.liveRuns(o),b=jo({companyId:o,resourceKey:"live-runs",queryKey:x,enabled:!!o,refetchInterval:!1,leaderOnly:!0}),{data:v,dataUpdatedAt:j}=te({queryKey:x,queryFn:r(()=>Xr.liveRunsForCompany(o),"queryFn"),enabled:b.enabled,refetchInterval:b.refetchInterval});wo(b,v,j);const N=v?.length??0,w=p?.enableIsolatedWorkspaces===!0,k=p?.enableApps===!0,S=p?.enablePipelines===!0,C=p?.enableStatusCards===!0,_=!f,R=p?.enableGoalsSidebarLink===!0,A=p?.enableDecisions===!0,{data:T}=te({queryKey:D.attention(o),queryFn:r(()=>DS.list(o),"queryFn"),enabled:!!o&&A,refetchInterval:6e4}),E=vNe(T),L=p?.enableCases===!0,O=!0,P=p?.enableConferenceRoomChat===!0,U={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)(pmt,{})}),(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 M=(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)(tI,{className:"h-4 w-4 shrink-0"}),(0,t.jsx)("span",{className:u?xj:"truncate",children:"New Task"})]});return u?(0,t.jsxs)(Bn,{children:[(0,t.jsx)(Fn,{asChild:!0,children:M}),(0,t.jsx)(On,{side:"right",children:"New Task"})]}):M})(),(0,t.jsx)(Ga,{to:"/search",label:"Search",icon:na}),(0,t.jsx)(Ga,{to:"/dashboard",label:"Dashboard",icon:hg,liveCount:N}),(0,t.jsx)(Ga,{to:"/inbox",label:"Inbox",icon:Ad,badge:h.inbox,badgeLabel:"unread",badgeTone:h.failedRuns>0?"danger":"default",alert:h.failedRuns>0}),A?(0,t.jsx)(Ga,{to:"/decisions",label:"Decisions",icon:wj,badge:E,badgeLabel:"decisions"}):null,C?(0,t.jsx)(Ga,{to:"/status",label:"Status",icon:ES,textBadge:"beta"}):null,P?(0,t.jsx)(Ga,{to:"/board-chat",label:"Conference Room",icon:Lye}):null]}),(0,t.jsxs)(pg,{label:"Work",collapsible:{open:s,onOpenChange:n},children:[(0,t.jsx)(Ga,{to:"/issues",label:"Tasks",icon:Wu}),L?(0,t.jsx)(Ga,{to:"/cases",label:"Cases",icon:Wl,textBadge:"beta"}):null,(0,t.jsx)(Ga,{to:"/routines",label:"Routines",icon:Gu}),S?(0,t.jsx)(Ga,{to:"/pipelines",label:"Pipelines",icon:Xi}):null,R?(0,t.jsx)(Ga,{to:"/goals",label:"Goals",icon:Pp}):_?(0,t.jsx)("div",{"data-testid":"sidebar-goals-placeholder",className:"h-8 pointer-coarse:h-7","aria-hidden":"true"}):null,(0,t.jsx)(Ga,{to:"/artifacts",label:"Artifacts",icon:qh}),(0,t.jsx)(Ga,{to:"/skills",label:"Skills",icon:vc}),w?(0,t.jsx)(Ga,{to:"/workspaces",label:"Workspaces",icon:Xi}):null,(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)(Ga,{to:"/projects",label:"Projects",icon:sl}),(0,t.jsx)(cmt,{})]}),(0,t.jsx)(Bp,{errorBehavior:"hidden",slotTypes:["sidebar"],context:U,className:"flex flex-col gap-0.5",itemClassName:"text-(length:--text-compact) font-medium",missingBehavior:"placeholder"}),(0,t.jsx)($S,{errorBehavior:"hidden",placementZones:["sidebar"],context:U,className:"flex flex-col gap-0.5",itemClassName:"text-(length:--text-compact) font-medium"})]}),null,(0,t.jsx)(omt,{streamlined:O}),(0,t.jsxs)(pg,{label:"Company",collapsible:{open:a,onOpenChange:i},children:[(0,t.jsx)(Ga,{to:"/org",label:"Org",icon:wb}),k?(0,t.jsx)(Ga,{to:"/apps",label:"Connectors",icon:G5}):null,(0,t.jsx)(Ga,{to:"/timeline",label:"Timeline",icon:O0}),(0,t.jsx)(Ga,{to:"/costs",label:"Costs",icon:Cp}),(0,t.jsx)(Ga,{to:"/activity",label:"Activity",icon:nc}),(0,t.jsx)(Ga,{to:"/company/settings",label:"Settings",icon:xu})]}),(0,t.jsx)(Bp,{errorBehavior:"hidden",slotTypes:["sidebarPanel"],context:U,className:"flex flex-col gap-3",itemClassName:"rounded-lg border border-border p-3",missingBehavior:"placeholder"})]})]})}r(Ore,"Sidebar");function xmt(e){const s=e.manifestJson.environmentDrivers??[];return s.length===0?!1:s.every(n=>n.kind==="sandbox_provider")}r(xmt,"isSandboxProviderOnly");function gmt(){const{selectedCompany:e,selectedCompanyId:s}=ps(),{isMobile:n,setSidebarOpen:a}=qa(),{hidden:i}=vu(),{enabled:o}=Ij(),l=r(x=>!i.has(x),"showPage"),c=l("instance.plugins"),d=!!Yc(),{slots:u}=Rd({slotTypes:["companySettingsPage"],companyId:s,enabled:!!s}),{data:h}=te({queryKey:s?D.sidebarBadges(s):["sidebar-badges","__disabled__"],queryFn:r(async()=>{try{return await KW.get(s)}catch(x){if(x instanceof mn&&(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(()=>Rl.list(),"queryFn"),enabled:c}),f=(p??[]).filter(x=>!xmt(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)(nm,{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)(Ga,{to:"/company/settings",label:"General",icon:rm,end:!0}),l("instance.profile")&&(0,t.jsx)(Ga,{to:"/company/settings/instance/profile",label:"Profile",icon:U4,end:!0}),l("company.members")&&(0,t.jsx)(Ga,{to:"/company/settings/members",label:"Members",icon:Wo,badge:h?.joinRequests??0,end:!0}),u.filter(x=>x.routePath).map(x=>(0,t.jsx)(Ga,{to:`/company/settings/${x.routePath}`,label:x.displayName,icon:mg,end:!0},`${x.pluginKey}:${x.id}`)),l("company.invites")&&(0,t.jsx)(Ga,{to:"/company/settings/invites",label:"Invites",icon:HKe,end:!0}),l("company.secrets")&&(0,t.jsx)(Ga,{to:"/company/settings/secrets",label:"Secrets",icon:Si,end:!0}),l("instance.environments")&&(0,t.jsx)(Ga,{to:"/company/settings/instance/environments",label:"Environments",icon:zye,end:!0}),o&&(0,t.jsx)(Ga,{to:"/company/settings/connections",label:"Connections",icon:Pl,end:!0}),l("instance.access")&&(0,t.jsx)(Ga,{to:"/company/settings/instance/access",label:"Access",icon:jA,end:!0}),l("instance.heartbeats")&&(0,t.jsx)(Ga,{to:"/company/settings/instance/heartbeats",label:"Heartbeats",icon:fu,end:!0}),l("company.export")&&(0,t.jsx)(Ga,{to:"/company/export",label:"Export",icon:ho}),!d&&l("company.import")&&(0,t.jsx)(Ga,{to:"/company/import",label:"Import",icon:Uy,end:!0}),l("instance.experimental")&&(0,t.jsx)(Ga,{to:"/company/settings/instance/experimental",label:"Experimental",icon:Vm}),c&&(0,t.jsx)(Ga,{to:"/company/settings/instance/plugins",label:"Plugins",icon:mg}),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)($b,{to:`${hp}/plugins/${x.id}`,state:hx,className:r(({isActive:b})=>["rounded-md px-2 py-1.5 text-xs transition-colors",b?"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)(Ga,{to:"/company/settings/instance/adapters",label:"Adapters",icon:Mm})]})})]})}r(gmt,"CompanySettingsSidebar");function bmt(){const{pathname:e}=oa(),{selectedCompany:s}=ps(),{isMobile:n,setSidebarOpen:a}=qa(),i=ZNe(),{enabled:o}=X4(),l=YW.filter(d=>!XNe(d.key)||o);if(e.endsWith("/apps/chat/connect"))return(0,t.jsx)(JNe,{NavItem:Ga});const c=e.match(/\/apps\/chat\/([^/]+)(?:\/(?:settings|access|conversations|activity|approvals|audit)|\/reviews(?:\/[^/]+)?)?\/?$/);return c?(0,t.jsx)(HW,{endpointId:c[1],NavItem:Ga}):(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)(nm,{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)(uee,{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)(Ga,{to:"/apps",label:"Browse",icon:sI,end:!0}),(0,t.jsx)(Ga,{to:"/apps/review",label:"Review",icon:PS,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)(Ga,{to:"/apps/connections",label:"Connections",icon:uee,end:!0}),l.map(d=>(0,t.jsx)(Ga,{to:nb(d.key),label:d.label,icon:d.icon,end:!0},d.key))]})]})]})}r(bmt,"AppsSidebar");function Fre(e){const{selectedCompanyId:s}=ps(),{isMobile:n,setSidebarOpen:a}=qa(),i=te({queryKey:D.tools.connection(e.kind==="connection"?e.connectionId:"__none__"),queryFn:r(()=>es.getConnection(e.kind==="connection"?e.connectionId:""),"queryFn"),enabled:e.kind==="connection"&&!!e.connectionId}),o=te({queryKey:D.tools.applications(s??"__none__"),queryFn:r(()=>es.listApplications(s),"queryFn"),enabled:e.kind==="application"&&!!s}),l=te({queryKey:D.tools.connections(s??"__none__"),queryFn:r(()=>es.listConnections(s),"queryFn"),enabled:e.kind==="application"&&!!s}),c=te({queryKey:D.apps.gallery(s??"__none__"),queryFn:r(()=>es.listGallery(s),"queryFn"),enabled:!!s}),d=te({queryKey:D.apps.attention(s??"__none__"),queryFn:r(()=>es.listAppsAttention(s),"queryFn"),enabled:!!s,refetchInterval:3e4}),u=i.data,h=e.kind==="application"?(o.data?.applications??[]).find(N=>N.id===e.applicationId):null,p=jmt(e.kind==="application"?(l.data?.connections??[]).filter(N=>N.applicationId===e.applicationId):[]),f=u?ex(u):h?.name??"App",x=ymt(c.data?.apps??[],u,h??void 0),b=u?.id??p?.id??null,v=b?d.data?.apps.find(N=>N.connection.id===b):null,j=(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)(nm,{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)(Vi,{name:f,logoUrl:HA(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:Z4.map(N=>(0,t.jsx)(Ga,{to:vmt(e,N.key),label:N.label,icon:N.icon,end:!0,badge:N.key==="review"&&j>0?j:void 0,badgeTone:"danger",badgeLabel:"needing review"},N.key))})})]})}r(Fre,"AppDetailSidebar");function vmt(e,s){return e.kind==="connection"?Em(e.connectionId,s):c_(e.applicationId,s)}r(vmt,"tabHref");function ymt(e,s,n){if(n?.applicationKey){const i=e.find(o=>fc(o)===n.applicationKey);if(i)return i}const a=(s?.name??n?.name)?.toLowerCase();return a?e.find(i=>fg(i).toLowerCase()===a)??e.find(i=>fc(i)===a)??null:null}r(ymt,"galleryEntryFor$1");function jmt(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(jmt,"latestArchivedConnection$1");function NF({identifier:e}){return e?(0,t.jsx)("span",{className:"shrink-0 font-mono text-muted-foreground",children:e}):null}r(NF,"CrumbIdentifier");function wmt({context:e}){const{slots:s}=Rd({slotTypes:["globalToolbarButton"],companyId:e.companyId}),{launchers:n}=VW({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)(Bp,{slotTypes:["globalToolbarButton"],context:e,className:"flex items-center gap-1"}):null,n.length>0?(0,t.jsx)($S,{placementZones:["globalToolbarButton"],context:e,className:"flex items-center gap-1"}):null]})}r(wmt,"GlobalToolbar");function Nmt(){const{breadcrumbs:e,mobileToolbar:s}=Hn(),{toggleSidebar:n,isMobile:a}=qa(),{selectedCompanyId:i,selectedCompany:o}=ps(),l=(0,m.useMemo)(()=>({companyId:i??null,companyPrefix:o?.issuePrefix??null}),[i,o?.issuePrefix]),c=(0,t.jsx)(wmt,{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)(_ye,{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)(NF,{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)(JW,{className:"min-w-0 overflow-hidden",children:(0,t.jsx)(XW,{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)(iP,{}),(0,t.jsx)(d_,{className:p?"min-w-0":"shrink-0",children:p||!u.href?u.leading||u.identifier?(0,t.jsxs)(cI,{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)(NF,{identifier:u.identifier}),(0,t.jsx)("span",{className:"truncate",children:u.label})]}):(0,t.jsx)(cI,{className:"truncate",children:u.label}):(0,t.jsx)(aP,{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)(NF,{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(Nmt,"BreadcrumbBar");var VT=240,VU=208,HU=420,Bre=16;function WP(e){return Math.min(HU,Math.max(VU,e))}r(WP,"clampSidebarWidth");function zre(e){if(typeof window>"u")return VT;try{const s=window.localStorage.getItem(e);if(!s)return VT;const n=Number.parseInt(s,10);return Number.isFinite(n)?WP(n):VT}catch{return VT}}r(zre,"readStoredSidebarWidth");function qre(e,s){if(!(typeof window>"u"))try{window.localStorage.setItem(e,String(WP(s)))}catch{}}r(qre,"writeStoredSidebarWidth");function kmt({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)(()=>zre(o)),[x,b]=(0,m.useState)(!1),v=(0,m.useRef)(p),j=(0,m.useRef)(null);(0,m.useEffect)(()=>{const P=zre(o);v.current=P,f(P)},[o]);const N=s?p:0,w=s?n?64:N:0,k=s?n&&!a?64:N:0,S=k>w,C=i&&s&&!n,_=(0,m.useMemo)(()=>({width:`${w}px`}),[w]),R=(0,m.useMemo)(()=>({width:`${k}px`}),[k]),A=(0,m.useCallback)(P=>{const U=WP(P);v.current=U,f(U),qre(o,U)},[o]),T=(0,m.useCallback)(P=>{C&&(P.preventDefault(),P.currentTarget.setPointerCapture(P.pointerId),j.current={startX:P.clientX,startWidth:v.current},b(!0))},[C]),E=(0,m.useCallback)(P=>{if(!j.current)return;const U=WP(j.current.startWidth+P.clientX-j.current.startX);v.current=U,f(U)},[]),L=(0,m.useCallback)(()=>{j.current&&(j.current=null,b(!1),qre(o,v.current))},[o]),O=(0,m.useCallback)(P=>{C&&(P.key==="ArrowLeft"?(P.preventDefault(),A(p-Bre)):P.key==="ArrowRight"?(P.preventDefault(),A(p+Bre)):P.key==="Home"?(P.preventDefault(),A(VU)):P.key==="End"&&(P.preventDefault(),A(HU)))},[C,A,p]);return(0,t.jsx)("div",{className:V("relative h-full shrink-0",l),style:_,children:(0,t.jsxs)("div",{className:V("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":VU,"aria-valuemax":HU,"aria-valuenow":p,tabIndex:0,className:V("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:L,onPointerCancel:L,onLostPointerCapture:L,onKeyDown:O}):null]})})}r(kmt,"SidebarShell");function Smt({children:e,className:s}){return(0,t.jsx)("div",{"data-secondary-sidebar":"",className:V("h-full w-60 shrink-0 overflow-y-auto border-r border-border bg-background",s),children:(0,t.jsx)(tmt,{children:e})})}r(Smt,"SecondarySidebar");var Cmt="/company/settings/members?tab=invites",_mt="https://docs.paperclip.ing/",Imt="https://paperclip.ing/feedback";function Amt(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(Amt,"deriveInitials$1");function Ure({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(Ure,"MenuAction");function Kre({deploymentMode:e,open:s,onOpenChange:n}){const i=!!Yc(),{hidden:o,loaded:l}=vu(),c=aIe(),d=iIe(!i),u=i?c:d?Cmt:null,h=l&&u!==null&&!wg(o,"company.members")&&!wg(o,"company.invites"),[p,f]=(0,m.useState)(!1),{isMobile:x,setSidebarOpen:b,collapsed:v,peeking:j}=qa(),N=v&&!j,w=s??p,k=oIe(w),S=n??f,{data:C}=te({queryKey:D.auth.session,queryFn:r(()=>Ma.getSession(),"queryFn"),retry:!1}),_=OS({onSignedOut:L}),R=C?.user.name?.trim()||"Board",A=C?.user.email?.trim()||(e==="authenticated"?"Signed in":"Local workspace board"),T=Amt(R),E=lIe(C?.user);function L(){S(!1),x&&b(!1)}r(L,"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:V("flex items-center gap-0.5",!N&&"px-2"),children:[(0,t.jsxs)(ur,{open:w,onOpenChange:S,children:[(0,t.jsx)(Nr,{asChild:!0,children:(0,t.jsxs)("button",{type:"button",className:V("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",N?"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)(Hc,{src:C.user.image,alt:R}):null,(0,t.jsx)(vo,{children:T})]}),(0,t.jsx)("span",{className:V("min-w-0 flex-1 truncate",N&&"block w-0 min-w-0 overflow-hidden whitespace-nowrap text-transparent select-none"),children:R})]})}),(0,t.jsxs)(rr,{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:L,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)(Hc,{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:A}),k?(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/${k}`,target:"_blank",rel:"noreferrer","aria-label":`View commit ${k} on GitHub`,title:k,children:["SHA ",k.slice(0,7)]}):null]})]}),(0,t.jsxs)("div",{className:"mt-4 space-y-1",children:[h&&u?(0,t.jsx)(Ure,{label:"Invite",description:"Invite people to your organization.",icon:eh,href:u,topLevel:i,onClick:L}):null,(0,t.jsx)(Ure,{label:"Documentation",description:"Open Paperclip docs in a new tab.",icon:RS,href:_mt,external:!0,onClick:r(()=>S(!1),"onClick")}),(0,t.jsx)(ZN,{variant:"menu-action",onAfterToggle:r(()=>S(!1),"onAfterToggle")}),(0,t.jsx)(uIe,{variant:"menu-action",onAfterAction:r(()=>S(!1),"onAfterAction")}),e==="authenticated"?(0,t.jsxs)("button",{type:"button",className:V("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)(Up,{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)(mIe,{})]})]})]})]}),!N&&!i?(0,t.jsxs)(Bn,{children:[(0,t.jsx)(Fn,{asChild:!0,children:(0,t.jsx)("a",{href:Imt,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(Kre,"SidebarAccountMenu");function Tmt(e,s){return SIe(e,s)[0]?.toLowerCase()??null}r(Tmt,"getCompanyRouteSegment");function SIe(e,s){if(!s)return[];const n=e.split("/").filter(Boolean);return n.length<2?[]:n[0]?.toUpperCase()!==s.toUpperCase()?[]:n.slice(1)}r(SIe,"getCompanyPathSegments");var Rmt=new Set(["browse","connections","connect","chat","review","attention","gateways","advanced","app"]);function Emt(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(Emt,"isSkillsStoreRoute");function Pmt(){const{sidebarOpen:e,setSidebarOpen:s,toggleSidebar:n,collapsed:a,peeking:i,setPeeking:o,isMobile:l,setForceCollapsed:c}=qa(),{openNewIssue:d,openOnboarding:u}=rl(),{togglePanelVisible:h}=fx(),p=Td()?.pushToast??null,{companies:f,loading:x,selectedCompany:b,selectedCompanyId:v,selectionSource:j,setSelectedCompanyId:N}=ps(),{companyPrefix:w,pluginRoutePath:k}=fa(),S=Gn(),C=oa(),_=_4(),R=HNe(C.pathname,w).isTaskDetail,A=["/company/settings","/company/export","/company/import"].some(jt=>C.pathname.includes(jt)),T=SIe(C.pathname,w),E=T[0]?.toLowerCase()==="tools",L=T[0]?.toLowerCase()==="apps",O=L&&T[1]&&!Rmt.has(T[1].toLowerCase())?T[1]:null,P=L&&T[1]?.toLowerCase()==="app"&&T[2]?T[2]:null,U=Emt(C.pathname,w),M=(0,m.useRef)(!1),B=(0,m.useRef)(null),q=(0,m.useRef)(null),z=(0,m.useRef)(new Lwe),K=(0,m.useRef)(C.key),W=bIe(l&&!R,C.pathname),[Q,re]=(0,m.useState)(!1),J=(0,m.useMemo)(()=>{if(!w)return null;const jt=w.toUpperCase();return f.find(Je=>Je.issuePrefix.toUpperCase()===jt)??null},[f,w]),ie=!!w&&!x&&f.length>0&&!J,X=(0,m.useMemo)(()=>k?.toLowerCase()??Tmt(C.pathname,w),[w,C.pathname,k]),ne=J?.id??null,oe=J?.issuePrefix??null,{slots:G}=Rd({slotTypes:["page","routeSidebar"],companyId:ne,enabled:!!(ne&&X)}),Z=(0,m.useMemo)(()=>OW(G,X),[X,G]),Y=(0,m.useMemo)(()=>({companyId:ne,companyPrefix:oe}),[ne,oe]),ae=A?(0,t.jsx)(gmt,{}):O?(0,t.jsx)(Fre,{kind:"connection",connectionId:O}):P?(0,t.jsx)(Fre,{kind:"application",applicationId:P}):L||E?(0,t.jsx)(bmt,{}):Z?(0,t.jsx)(am,{slot:Z,context:Y,className:"h-full w-full",missingBehavior:"placeholder"}):null,se=ae!=null,{data:ce}=te({queryKey:D.health,queryFn:r(()=>yu.get(),"queryFn"),retry:!1,refetchInterval:r(jt=>jt.state.data?.devServer?.enabled?2e3:!1,"refetchInterval"),refetchIntervalInBackground:!1}),pe=se||U;(0,m.useLayoutEffect)(()=>(c(pe),()=>c(!1)),[pe,c]),(0,m.useEffect)(()=>{x||M.current||ce?.deploymentMode!=="authenticated"&&(ce?.cloud||f.length===0&&(M.current=!0,u()))},[f,x,u,ce?.cloud,ce?.deploymentMode]),(0,m.useEffect)(()=>{if(!w||x||f.length===0)return;if(!J){const Je=(v?f.find(Fe=>Fe.id===v):null)??f[0]??null;Je&&v!==Je.id&&N(Je.id,{source:"route_sync"});return}if(w!==J.issuePrefix){const Je=C.pathname.replace(/^\/[^/]+/,"");S(`/${J.issuePrefix}${Je}${C.search}`,{replace:!0});return}const jt=vIe({matchedCompany:J,selectedCompanyId:v,companies:f});if(jt){p?.({title:`${J.name} is archived`,body:`Switched to ${jt.name}.`,tone:"info",dedupeKey:`archived-company-bounce:${J.id}`}),N(jt.id,{source:"route_sync"}),S(`/${jt.issuePrefix}/dashboard`,{replace:!0});return}yIe({selectionSource:j,selectedCompanyId:v,routeCompanyId:J.id})&&N(J.id,{source:"route_sync"})},[w,f,x,J,C.pathname,C.search,S,p,j,v,N]);const we=h,Se=(0,m.useCallback)(()=>{document.dispatchEvent(new KeyboardEvent("keydown",{key:"k",metaKey:!0,bubbles:!0,cancelable:!0}))},[]),Te=(0,m.useRef)(null),le=(0,m.useRef)(!1),fe=(0,m.useRef)(!1),de=(0,m.useCallback)(()=>{Te.current!==null&&(window.clearTimeout(Te.current),Te.current=null)},[]),Ee=(0,m.useCallback)(()=>{de(),Te.current=window.setTimeout(()=>o(!0),50)},[de,o]),Me=(0,m.useCallback)(()=>{de(),o(!0)},[de,o]),ve=(0,m.useCallback)(()=>{de(),Te.current=window.setTimeout(()=>o(!1),120)},[de,o]),Ie=(0,m.useCallback)(()=>{le.current=!0,a&&!fe.current&&Ee()},[a,Ee]),Ze=(0,m.useCallback)(()=>{le.current=!1,fe.current=!1,ve()},[ve]),ue=(0,m.useCallback)(()=>{fe.current||Me()},[Me]),Be=(0,m.useCallback)(()=>{le.current||ve()},[ve]);(0,m.useEffect)(()=>de,[de]);const ht=(0,m.useRef)(a);return(0,m.useEffect)(()=>{a!==ht.current&&(a?(de(),o(!1),fe.current=le.current):fe.current=!1,ht.current=a)},[a,de,o]),(0,m.useEffect)(()=>{if(!i)return;const jt=r(Je=>{Je.key==="Escape"&&(de(),o(!1))},"onKeyDown");return window.addEventListener("keydown",jt),()=>window.removeEventListener("keydown",jt)},[i,de,o]),gIe(),hIe({onNewIssue:r(()=>d(),"onNewIssue"),onSearch:Se,onToggleSidebar:n,onTogglePanel:we,onShowShortcuts:r(()=>re(!0),"onShowShortcuts"),onGoToInbox:r(()=>S("/inbox"),"onGoToInbox")}),(0,m.useEffect)(()=>{if(!l)return;const jt=30,Je=50,Fe=75;let it=0,At=0;const $t=r(at=>{const De=at.touches[0];it=De.clientX,At=De.clientY},"onTouchStart"),zt=r(at=>{const De=at.changedTouches[0],Pe=De.clientX-it;if(!(Math.abs(De.clientY-At)>Fe)){if(!e&&it<jt&&Pe>Je){s(!0);return}e&&Pe<-50&&s(!1)}},"onTouchEnd");return document.addEventListener("touchstart",$t,{passive:!0}),document.addEventListener("touchend",zt,{passive:!0}),()=>{document.removeEventListener("touchstart",$t),document.removeEventListener("touchend",zt)}},[l,e,s]),(0,m.useEffect)(()=>{const jt=document.body.style.overflow;return document.body.style.overflow=l?"visible":"clip",()=>{document.body.style.overflow=jt}},[l]),(0,m.useEffect)(()=>{if(!l)return wIe()},[l]),(0,m.useEffect)(()=>{if(typeof document>"u")return;const jt=q.current;return jIe(jt)},[C.pathname]),(0,m.useEffect)(()=>{const jt=q.current;if(!jt)return;const Je=r(()=>{z.current.remember(K.current,jt.scrollTop)},"recordScroll");return jt.addEventListener("scroll",Je,{passive:!0}),()=>jt.removeEventListener("scroll",Je)},[]),(0,m.useLayoutEffect)(()=>{const jt=q.current,Je=Dwe({previousPathname:B.current,pathname:C.pathname,navigationType:_,state:C.state});B.current=C.pathname;const Fe=_==="POP",it=Fe?z.current.recall(C.key):0;if(K.current=C.key,Fe){J5(jt,it);const At=requestAnimationFrame(()=>J5(jt,it));return()=>cancelAnimationFrame(At)}Je&&$we(jt)},[C.key,C.pathname,C.state,_]),(0,t.jsx)(Pwe,{children:(0,t.jsxs)("div",{className:V("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)(H_e,{}),(0,t.jsx)(Q_e,{devServer:ce?.devServer}),(0,t.jsxs)("div",{className:V("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:V("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?ae:(0,t.jsx)(Ore,{})})}),(0,t.jsx)(Kre,{deploymentMode:ce?.deploymentMode})]}):(0,t.jsxs)(kmt,{open:e,collapsed:a,peeking:i,resizable:!0,onPanelMouseEnter:Ie,onPanelMouseLeave:Ze,onPanelFocusCapture:a?ue:void 0,onPanelBlurCapture:a?Be:void 0,children:[(0,t.jsx)("div",{className:"flex flex-1 min-h-0",children:(0,t.jsx)(Ore,{})}),(0,t.jsx)(Kre,{deploymentMode:ce?.deploymentMode})]}),!l&&se?(0,t.jsx)(Smt,{children:ae}):null,(0,t.jsxs)("div",{className:V("flex min-w-0 flex-col",l?"w-full":"h-full flex-1"),children:[(0,t.jsxs)("div",{className:V(l&&"sticky top-0 z-20 bg-background/95 backdrop-blur supports-[backdrop-filter]:bg-background/85"),children:[(0,t.jsx)(BU,{mobile:l,onNavigateHome:r(()=>S("/dashboard"),"onNavigateHome")}),(0,t.jsx)(Nmt,{}),l&&A?(0,t.jsx)("div",{className:"border-b border-border px-4 pb-3",children:(0,t.jsx)(YNe,{})}):null]}),(0,t.jsxs)("div",{className:V(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:V("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)(Zu,{scope:"invalid_company_prefix",requestedPrefix:w??b?.issuePrefix}):(0,t.jsx)(J_e,{children:(0,t.jsx)(Lb,{})})}),(0,t.jsx)(lke,{})]})]})]}),l&&(0,t.jsx)(V_e,{visible:W}),(0,t.jsx)(cke,{}),(0,t.jsx)(Hke,{}),(0,t.jsx)(D_e,{}),(0,t.jsx)(O_e,{}),(0,t.jsx)(q_e,{}),(0,t.jsx)(U_e,{open:Q,onOpenChange:re}),(0,t.jsx)(K_e,{}),(0,t.jsx)(W_e,{localTrusted:ce?.deploymentMode==="local_trusted"})]})})}r(Pmt,"Layout");var Wre=null;function Mmt(){return Wre??=new vS,Wre}r(Mmt,"getDetachedClient");function Dmt(){const e=(0,m.useContext)(pA),{data:s,isFetched:n}=te({queryKey:D.instance.experimentalSettings,queryFn:r(()=>vr.getExperimental(),"queryFn"),enabled:e!=null},e??Mmt());return e?{enabled:s?.enableConferenceRoomChat===!0,loaded:n}:{enabled:!1,loaded:!0}}r(Dmt,"useConferenceRoomChatEnabled");function Lmt(){const{enabled:e,loaded:s}=Dmt();return s?e?(0,t.jsx)(Lb,{}):(0,t.jsx)(An,{to:"/dashboard",replace:!0}):null}r(Lmt,"ConferenceRoomChatGate");var $mt=["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"],Omt={"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 }"}},Cps=$mt.map(e=>Omt[e]);function CIe({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)(lm,{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(CIe,"TaskBrowserActivity");function _Ie({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)(FKe,{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(_Ie,"TaskChatProjectCreatedCard");function Fmt({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)(Jf,{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(Fmt,"TaskChatSkillCreatedCard");function Bmt(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(Bmt,"McpIcon");var zmt=new Set(["tool","tool call","tool_call","acp_tool"]);function mu(e){const s=(e??"").trim().toLowerCase().replace(/\s*\((?:pending|in[_ -]?progress|completed|failed|cancelled|canceled)\)$/,"");return!s||zmt.has(s)}r(mu,"isGenericToolName");function LH(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(LH,"mcpToolIdentity");function $H(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($H,"identifierWords");function IIe(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(IIe,"sentenceCase");function ek(e){const s=(e??"").trim();return mu(s)?"Unnamed tool":IIe($H(LH(s)?.name??s))}r(ek,"humanizeToolName");var Fd=r((e,s,n)=>({key:e,singular:s,plural:n}),"group"),qmt={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:Fd("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:Fd("task_operation","task operation","task operations")},task_create:{action:"create",running:"Creating a task",completed:"Created a task",family:"plan",group:Fd("task_operation","task operation","task operations")},task_update:{action:"update",running:"Updating a task",completed:"Updated a task",family:"plan",group:Fd("task_operation","task operation","task operations")},task_list:{action:"list",running:"Listing tasks",completed:"Listed tasks",family:"plan",group:Fd("task_operation","task operation","task operations")},task_get:{action:"read",running:"Reading a task",completed:"Read a task",family:"plan",group:Fd("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:Fd("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"}},Umt={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:[]},Kmt={read:"read",edit:"update",delete:"delete",move:"move",search:"search",list:"list",execute:"run",think:"think",fetch:"fetch",switch_mode:"switch"};function Wmt(e){return $H(e).join("_")}r(Wmt,"normalizedKey");function Vmt(e){const s=e[0];if(!s)return null;for(const[n,a]of Object.entries(Umt))if(a.includes(s))return n;return null}r(Vmt,"inferredAction");function Hmt(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(Hmt,"actionFamily");var Qmt={terminal:Yf,grep:i8e,search:na,read:RS,edit:L4,web:_Ke,plan:wj,question:yc,agent:wb,safety:Fi,image:BA,wait:fu,mcp:Bmt,other:Jf};function Gmt(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(Gmt,"actionCopy");function Ymt(e){switch(e){case"run":return Fd("command","command","commands");case"read":case"list":return Fd("read","read","reads");case"search":return Fd("search","search","searches");case"update":case"create":case"delete":case"move":return Fd("file_change","file change","file changes");case"start":case"stop":return Fd("delegation","delegation","delegations");case"wait":return Fd("wait","wait","waits");default:return Fd("tool_action","tool action","tool actions")}}r(Ymt,"defaultSummaryGroup");function Jmt(e){return e==="read"||e==="list"?Fd("paperclip_read","Paperclip read","Paperclip reads"):Fd("task_operation","task operation","task operations")}r(Jmt,"paperclipSummaryGroup");function Xy(e){const s=(e.name??"").trim(),n=LH(s),a=(e.namespace??n?.namespace??"").trim(),i=(n?"mcp":e.transport??"builtin").toLowerCase(),o=(n?.name??s).trim(),l=$H(o),c=Wmt(o),d=qmt[c],u=Kmt[(e.operation??"").trim().toLowerCase()],h=Vmt(l),p=d?.action??u??h??"other",f=d?"exact":u?"kind":h?"inferred":mu(o)?"unnamed":"fallback",x=mu(o)?"Unnamed tool":ek(o),b=/^[A-Za-z][A-Za-z0-9_.:-]*$/.test(o),v=h&&b&&l.length>1?l.slice(1):[],j=v.length?IIe(v).replace(/^./,_=>_.toLowerCase()):void 0,N=d?.running&&d.completed?{running:d.running,completed:d.completed}:p==="other"?mu(o)?{running:"Running an unnamed tool",completed:"Ran an unnamed tool"}:{running:`Running ${x}`,completed:`Ran ${x}`}:Gmt(p,d?void 0:j),w=d?.family??Hmt(p),k=i==="mcp"?"mcp":w,S=a?ek(a):i==="mcp"?"MCP":void 0,C=a.toLowerCase()==="paperclip"?Jmt(p):d?.group??Ymt(p);return{icon:Qmt[k],family:k,runningLabel:N.running,completedLabel:N.completed,failedLabel:`${N.completed} · failed`,interruptedLabel:`${N.running} · stopped`,displayName:x,sourceLabel:S,technicalName:s||void 0,confidence:f,summaryGroup:C}}r(Xy,"toolActivityPresentation");function Gk(e){const s=Xy({name:e});return{family:s.family,icon:s.icon,verbLabel:s.runningLabel}}r(Gk,"toolTaxonomy");function AIe(e){const s=(e??"").trim().toLowerCase();return s==="thinking"?ug:s==="responding"||s.startsWith("responding (")?QKe:null}r(AIe,"statusLabelIcon");var kF=["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"],SF=["Brewing","Tinkering","Distilling","Deliberating"],Vre=(()=>{const e=[],s=Math.max(kF.length,SF.length);for(let n=0;n<s;n++)n<kF.length&&e.push(kF[n]),n<SF.length&&e.push(SF[n]);return e})(),Xmt=1e4;function Zmt(e){const s=(e??"").trim().toLowerCase();return s==="running"||s==="working"}r(Zmt,"isGenericStatusLabel");function eht(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(eht,"fnv1a");function tht(e,s=0){const n=Math.floor(Math.max(0,s)/Xmt);return Vre[(eht(e)+n)%Vre.length]}r(tht,"whimsyWord");var sht=[{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}],_ps=Array.from(new Set(sht.map(e=>e.group)));function TIe(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(TIe,"parseCssTimeMs");function nht(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(nht,"elapsedLabel");function rht(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(rht,"liveElapsedLabel");function aht(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(aht,"useLiveElapsedMs");function iht(e,s){return!Number.isFinite(e)||!Number.isFinite(s)||s<=0?0:Math.max(0,Math.round(e/s)-1)}r(iht,"lineScrollOffset");function j3(e){const s=getComputedStyle(document.documentElement).getPropertyValue(e),n=TIe(s);return Number.isFinite(n)?n:0}r(j3,"motionTokenMs");function oht({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 b=parseFloat(window.getComputedStyle(p).lineHeight);o(iht(p.scrollHeight,b))},"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),j3("--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:V("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(oht,"LiveSelfTalkLine");function lht(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(j=>{j.current!=null&&(window.clearTimeout(j.current),j.current=null)},"clear"),f=r(j=>{i.current=j,a(j)},"show"),x=r(()=>{p(u),p(h),u.current=window.setTimeout(()=>{if(u.current=null,o.current!=null)return;const j=i.current;j==null||j.streaming||(f({...j,leaving:!0}),h.current=window.setTimeout(()=>{h.current=null,i.current?.leaving&&f(null)},j3("--motion-line-scroll")))},j3("--motion-interstitial-dwell"))},"scheduleLeave"),b=r((j,N)=>{p(u),p(h),c.current=Date.now(),f({text:j,streaming:N,swapKey:(i.current?.swapKey??0)+1}),N||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){b(e,!0);return}if(v.streaming){v.text!==e&&f({...v,text:e});return}if(o.current=e,d.current==null){const j=j3("--motion-interstitial-dwell"),N=Math.max(0,c.current+j-Date.now());d.current=window.setTimeout(()=>{d.current=null;const w=o.current;o.current=null,w!=null&&b(w,l.current!=null)},N)}},[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(lht,"useHeldSelfTalk");var cht={running:{Icon:tt,spin:!0,tone:"text-(--status-agent-running)"},working:{Icon:tt,spin:!0,tone:"text-(--status-agent-running)"},awaiting_approval:{Icon:PS,spin:!1,tone:"text-primary"},interrupted:{Icon:bW,spin:!1,tone:"text-destructive"},refused:{Icon:Dm,spin:!1,tone:"text-destructive"},truncated:{Icon:a8e,spin:!1,tone:"text-(--status-agent-paused)"}};function RIe({item:e,onApprovalDecision:s,chevronOpen:n,onToggle:a}){const{Icon:i,spin:o,tone:l}=cht[e.status],c=e.status==="awaiting_approval",d=e.status==="running"||e.status==="working",u=aht(e.startedAtMs,d),h=lht(d?e.selfTalk:void 0,d),p=nht(e.elapsedMs);if(d){const f=rht(u??e.elapsedMs),x=e.selfTalk!=null,b=e.toolName?Gk(e.toolName).icon:x?null:AIe(e.label),v=x||Zmt(e.label)?tht(e.id,u??e.elapsedMs??0):e.label,j=(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)(Pn,{className:V("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)"})}),b?(0,t.jsx)(b,{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)(oht,{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:j}):j]})}return(0,t.jsxs)("div",{className:V("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:V("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:V("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(RIe,"TaskChatStatusPill");var Gg=(0,m.createContext)(null);function Ej(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(Ej,"formatBytes$4");var VP=new Set(["application/octet-stream","binary/octet-stream","application/x-binary"]),dht=[".mp4",".m4v",".webm",".mov",".qt",".quicktime"],uht=[".png",".jpg",".jpeg",".gif",".webp",".avif",".bmp",".ico"],mht=new Set(["application/wasm"]),hht=new Set(["application/zip","application/x-zip","application/x-zip-compressed"]),EIe=new Set(["text/markdown","text/x-markdown","application/markdown","application/x-markdown"]),pht=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"]),fht=[".csv",".css",".graphql",".htm",".html",".js",".json",".jsx",".log",".markdown",".md",".mdx",".php",".py",".sh",".sql",".toml",".ts",".tsx",".txt",".xml",".yaml",".yml"];function i2(e){return(e??"").toLowerCase().split(";")[0]?.trim()??""}r(i2,"normalizeOutputContentType");function xht(e){const s=(e??"").trim().toLowerCase();return s?fht.some(n=>s.endsWith(n)):!1}r(xht,"hasDocumentLikeFilename");function PIe(e){return hht.has(e)||e.endsWith("+zip")}r(PIe,"isZipContentType");function ght(e){return e?!!(e.startsWith("text/")||EIe.has(e)||pht.has(e)||e.startsWith("application/")&&(e.endsWith("+json")||e.endsWith("+xml"))):!1}r(ght,"isDocumentLikeOutputContentType");function bht(e,s){const n=i2(e);return!n||ght(n)||VP.has(n)&&xht(s)?!1:n.startsWith("video/")||n.startsWith("image/")||n==="application/pdf"||mht.has(n)||PIe(n)||VP.has(n)}r(bht,"isOutputEligibleContentType");function vht(e){const s=i2(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"}:PIe(s)?{label:"ZIP",tone:"zip"}:s.startsWith("image/")?{label:"IMG",tone:"image"}:EIe.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(vht,"getOutputFileGlyph");function im(e,s){const n=i2(e);if(n.startsWith("video/"))return!0;if(!VP.has(n))return!1;const a=(s??"").trim().toLowerCase();return dht.some(i=>a.endsWith(i))}r(im,"isVideoLikeOutput");function Zy(e){const s=i2(e);return s.startsWith("image/")&&s!=="image/svg+xml"}r(Zy,"isImageContentType");function ED(e,s){const n=i2(e);if(Zy(n))return!0;if(n&&!VP.has(n))return!1;const a=(s??"").trim().toLowerCase();return uht.some(i=>a.endsWith(i))}r(ED,"isImageLikeOutput");function Hre(e){const s=new Date(e).getTime();return Number.isNaN(s)?0:s}r(Hre,"toTime");function PD(e){const s=(e??[]).filter(n=>n.type==="artifact"&&n.provider==="paperclip").flatMap(n=>{const a=mBe.safeParse(n.metadata);return a.success&&!bht(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:Hre(a.createdAt)-Hre(n.createdAt)),{items:s,primary:s[0]??null,rest:s.slice(1),count:s.length}}r(PD,"getIssueOutputs");function OH(e){return e.metadata?.originalFilename||e.title||"output"}r(OH,"outputFilename");function MIe(e){return new Set(PD(e).items.flatMap(s=>{const n=s.metadata?.attachmentId;return n?[n]:[]}))}r(MIe,"getPromotedOutputAttachmentIds");function o2(e,s){const n=e?.toLowerCase().split(";")[0].trim();return n==="text/html"||n==="application/xhtml+xml"||/\.html?$/i.test(s??"")}r(o2,"isHtmlPreview");var yht=["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 jht(e){return`<!doctype html><html><head><meta charset="utf-8"><meta http-equiv="Content-Security-Policy" content="${yht}"><meta name="referrer" content="no-referrer"></head><body>${e}</body></html>`}r(jht,"htmlPreviewDocument");function wht(e){return e.contentType.toLowerCase().split(";")[0]?.trim()??""}r(wht,"normalizedContentType");function Mg(e){return e.originalFilename??e.id}r(Mg,"attachmentFilename");function MD(e){return e.openPath??e.contentPath}r(MD,"attachmentOpenPath");function VS(e){return e.downloadPath??`${e.contentPath}?download=1`}r(VS,"attachmentDownloadPath");function DIe(e){const s=wht(e);return ED(s,e.originalFilename)&&!/^image\/hei[cf](?:-sequence)?$/.test(s)}r(DIe,"isImageAttachment$1");function LIe(e){return im(e.contentType,e.originalFilename)}r(LIe,"isVideoAttachment");function $Ie(e){return Ige(e)}r($Ie,"isMarkdownAttachment");function Pj(e){const s=e.contentType.toLowerCase().split(";")[0].trim();return Ige(e)||o2(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(Pj,"isTextAttachment");function OIe(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(OIe,"downloadBlob$1");function Nht(e,s,n){OIe(e,new Blob([s],{type:`${n};charset=utf-8`}))}r(Nht,"downloadTextFile");var CF="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 FIe({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:b}=Op(),v=(0,m.useRef)(void 0);(0,m.useEffect)(()=>()=>clearTimeout(v.current),[]);const j=(0,m.useCallback)(async(_,R)=>{c(_),p(null);try{await R(),u(_)}catch(A){u(null),p(A instanceof Error?A.message:"Export failed")}finally{c(null)}clearTimeout(v.current),v.current=setTimeout(()=>{u(null),p(null)},2e3)},[]),N=(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 N())==="failed"&&p("Copy failed")}catch(_){p(_ instanceof Error?_.message:"Copy failed")}finally{c(null)}})()},[f,N]),k=b||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:V("flex items-center gap-0.5",o),"data-testid":"document-export-actions",children:[(0,t.jsx)("button",{type:"button",className:CF,disabled:l!==null,"aria-label":"Copy full content",title:k,"data-testid":"document-export-copy",onClick:r(_=>{_.preventDefault(),_.stopPropagation(),w()},"onClick"),children:x?(0,t.jsx)(us,{"aria-hidden":"true",className:"h-3.5 w-3.5"}):(0,t.jsx)(wr,{"aria-hidden":"true",className:"h-3.5 w-3.5"})}),(0,t.jsx)("button",{type:"button",className:CF,disabled:l!==null,"aria-label":"Download source",title:S,"data-testid":"document-export-download",onClick:r(_=>{_.preventDefault(),_.stopPropagation(),j("download",async()=>{const R=rUe(a);Nht(iee(n,R),await N(),R==="md"?"text/markdown":"text/plain")})},"onClick"),children:(0,t.jsx)(ho,{"aria-hidden":"true",className:"h-3.5 w-3.5"})}),(0,t.jsx)("button",{type:"button",className:CF,disabled:l!==null,"aria-label":"Export to PDF",title:C,"data-testid":"document-export-pdf",onClick:r(_=>{_.preventDefault(),_.stopPropagation(),j("pdf",async()=>{OIe(iee(n,"pdf"),await yt.getDocumentPdf(e,s))})},"onClick"),children:(0,t.jsx)($Ke,{"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!":b?"Copy failed":d?"Downloaded!":"")})]})}r(FIe,"DocumentExportActions");function TI({children:e,className:s}){return(0,t.jsx)("div",{className:V("relative aspect-video w-full overflow-hidden bg-accent/20",s),children:e})}r(TI,"PreviewFrame");function HP({label:e}){return(0,t.jsx)(TI,{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)(wl,{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(HP,"PlaceholderPreview");function kht({artifact:e}){const[s,n]=(0,m.useState)(!1);return s||!e.contentPath?(0,t.jsx)(HP,{label:"Image"}):(0,t.jsx)(TI,{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(kht,"ImagePreview");function Sht({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)(TI,{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)(mo,{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,b=x>0?Math.min(1,x/4):.05;try{Math.abs(f.currentTime-b)>.001?(f.currentTime=b,d()):c()}catch{c()}},"loadThumbnailFrame"),h=r(p=>{(o.current||p.currentTarget.currentTime>0)&&c()},"handleLoadedData");return(0,t.jsxs)(TI,{className:"bg-black",children:[(0,t.jsx)("video",{src:e.contentPath,preload:"metadata",muted:!0,playsInline:!0,"data-frame-ready":a?"true":"false",className:V("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)(mo,{className:"h-5 w-5 translate-x-0.5 text-white","aria-hidden":"true"})})})]})}r(Sht,"VideoPreview");function Cht({artifact:e}){const s=e.previewText?.trim();return s?(0,t.jsxs)(TI,{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)(HP,{label:e.source==="document"?"Document":"Text"})}r(Cht,"TextPreview");function l2({artifact:e}){switch(e.mediaKind){case"image":return(0,t.jsx)(kht,{artifact:e},e.contentPath);case"video":return(0,t.jsx)(Sht,{artifact:e},e.contentPath);case"text":case"document":return(0,t.jsx)(Cht,{artifact:e});case"file":return(0,t.jsx)(HP,{label:"File"});default:return(0,t.jsx)(HP,{})}}r(l2,"ArtifactPreview");function Qre({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(Qre,"SecondaryAction");function _ht({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)(l2,{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)(FIe,{issueId:e.issue.id,documentKey:e.documentKey,title:e.title}):null,e.openPath?(0,t.jsx)(Qre,{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)(Qre,{href:e.downloadPath,download:!0,title:"Download file",children:(0,t.jsx)(ho,{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 ",qd(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(_ht,"ArtifactCard");function Iht(e){return e&&/^\/api\/assets\/[^/?#]+\/content$/.test(e)?e:null}r(Iht,"paperclipHumanAvatarUrl");function BIe(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(BIe,"resolveIssueChatHumanAuthor");var ec={credentials:r(e=>Ce.get(`/companies/${e}/email/connections`),"credentials"),checkAddress:r((e,s,n,a)=>Ce.post(`/companies/${e}/email/connections/${s}/check-address`,n,{signal:a}),"checkAddress"),connect:r((e,s)=>Ce.post(`/companies/${e}/email/connections`,s),"connect"),inspectSaved:r((e,s)=>Ce.post(`/companies/${e}/email/connections/${s}/inspect`,{}),"inspectSaved"),list:r(e=>Ce.get(`/companies/${e}/email/inboxes`),"list"),setup:r((e,s)=>Ce.post(`/companies/${e}/email/inboxes`,s),"setup"),inspect:r((e,s)=>Ce.post(`/companies/${e}/email/inspect`,{apiKey:s}),"inspect"),control:r((e,s)=>Ce.post(`/email/inboxes/${e}/control`,{action:s}),"control"),reconnect:r((e,s,n)=>Ce.post(`/email/inboxes/${e}/reconnect`,{apiKey:s,receiveMode:n}),"reconnect"),resolve:r((e,s,n,a)=>Ce.post(`/companies/${e}/email/deliveries/${s}/resolve`,{outcome:n,providerMessageId:a}),"resolve"),thread:r((e,s)=>Ce.get(`/companies/${e}/email/tasks/${s}`),"thread"),send:r((e,s)=>Ce.post(`/companies/${e}/email/send`,s),"send")};function zIe(e,s){return te({queryKey:["email-thread",e,s],queryFn:r(()=>ec.thread(e,s),"queryFn"),enabled:!!(e&&s)&&!s.startsWith("chat:"),refetchInterval:r(n=>n.state.data===null?!1:3e3,"refetchInterval")})}r(zIe,"useEmailThread");var qIe=(0,m.createContext)(null);function Aht({companyId:e,issueId:s,children:n}){const a=zIe(e,s);return(0,t.jsx)(qIe.Provider,{value:a.data??null,children:n})}r(Aht,"EmailThreadProvider");function UIe(e){const s=(0,m.useContext)(qIe),n=s?.messages.find(a=>a.commentId===e);return n&&s?(0,t.jsx)(KIe,{message:n,publication:s.publications.find(a=>a.providerMessageId===n.providerMessageId),issueId:s.issueId}):null}r(UIe,"useEmailComment");function KIe({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)($9,{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)(wl,{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(KIe,"EmailMessageCard");var Cy=(0,m.createContext)(null);function Mj({items:e,initialIndex:s,open:n,onOpenChange:a}){const[i,o]=(0,m.useState)(s),l=(0,m.useRef)(null),c=(0,m.useCallback)(b=>{l.current=b},[]);(0,m.useEffect)(()=>{n&&o(s)},[n,s]);const d=(0,m.useCallback)(()=>{o(b=>(b+1)%e.length)},[e.length]),u=(0,m.useCallback)(()=>{o(b=>(b-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 b=r(v=>{v.key==="ArrowRight"?d():v.key==="ArrowLeft"?u():v.key==="Escape"&&a(!1)},"handler");return window.addEventListener("keydown",b),()=>window.removeEventListener("keydown",b)},[n,d,u,a]);const h=(0,m.useCallback)(b=>{const v=b.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=Mg(p),x=im(p.contentType,p.originalFilename);return(0,t.jsx)(m6e,{open:n,onOpenChange:a,children:(0,t.jsxs)(d6e,{children:[(0,t.jsx)(c6e,{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)(u6e,{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:VS(p),download:f,className:"text-white/50 hover:text-white transition-colors",title:"Download","aria-label":`Download ${f}`,onClick:r(b=>b.stopPropagation(),"onClick"),children:(0,t.jsx)(ho,{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)(zn,{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)(nm,{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)(Pn,{className:"h-7 w-7"})})})]}),(0,t.jsx)("div",{className:"h-6 shrink-0"})]})]})})}r(Mj,"ImageGalleryModal");function fv(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:{}}r(fv,"record$6");var WIe=(0,m.createContext)(null);function VIe(e){const s=(0,m.useContext)(WIe);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(VIe,"useWorkspaceBaseRefRecovery");function Tht({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(()=>Xr.get(l),"queryFn"),enabled:!!l,staleTime:1/0,retry:!1}),d=fv(fv(c?.resultJson).configurationIncomplete);let u=null;if(o&&l&&c?.companyId===e.companyId&&fv(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(j=>j.id===e.projectWorkspaceId)??e.project?.primaryWorkspace;let x="The task’s repository";if(f?.repoUrl)try{const j=new URL(f.repoUrl);(j.protocol==="https:"||j.protocol==="http:")&&(x=`${j.hostname}${j.pathname.replace(/\.git$/,"")}`)}catch{}const b=fv(fv(e.executionWorkspaceSettings).workspaceStrategy).baseRef,v=o.status!=="active"||e.status!=="blocked"||e.assigneeAgentId!==o.returnOwnerAgentId||c.agentId!==e.assigneeAgentId||typeof b=="string"&&b.trim()&&b!==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(j=>j.status!=="done"&&j.status!=="cancelled")?"Resolve the task’s blockers before retrying.":null);u={actionId:o.id,runId:l,props:{requestedRef:p,repository:x,taskOverride:b===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 j=>{try{const N=await yt.resolveRecoveryAction(e.id,{actionId:o.id,outcome:"restored",sourceIssueStatus:"todo",workspaceBaseRef:{requestedRef:p,branch:j}});if(N.issue.status!=="todo"||N.issue.assigneeAgentId!==e.assigneeAgentId||fv(fv(N.issue.executionWorkspaceSettings).workspaceStrategy).baseRef!==j)throw new Error("The task changed while saving. Refresh to check its current state.")}finally{a()}},"onRepair")}}}return(0,t.jsx)(WIe.Provider,{value:u,children:i})}r(Tht,"WorkspaceBaseRefRecoveryProvider");var HIe={neutral:{container:"border-border bg-muted/35 dark:bg-muted/20",iconWrap:"bg-muted text-foreground/70",icon:Uh,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:Uh,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:ha,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:Rs,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:Ik,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 Rht(e){try{return new Date(e).toLocaleString(void 0,{month:"short",day:"numeric",hour:"numeric",minute:"2-digit"})}catch{return e}}r(Rht,"formatTimestamp$1");function Eht({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:V("inline-flex items-center gap-1 rounded-sm font-medium underline-offset-2 hover:underline",s.label),children:n}):(0,t.jsx)("span",{className:V("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:V("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:V("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:V("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(Eht,"MetadataRow$1");function FH({sections:e,tone:s="neutral"}){const n=HIe[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)(Eht,{row:o,tone:n},l))})]},i))})}r(FH,"SystemNoticeMetadataSections");function BH({tone:e="neutral",label:s,body:n,source:a,metadata:i,detailsDefaultOpen:o=!1,timestamp:l,className:c}){const d=HIe[e],u=d.icon,[h,p]=(0,m.useState)(o),f=(0,m.useId)(),x=!!(i&&i.length>0),b=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":b,className:V("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:V("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:V("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:b}),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:Rht(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:V("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)(nn,{className:V("h-3.5 w-3.5 transition-transform duration-150",h&&"rotate-180")})]}):null]}),x&&h?(0,t.jsx)("div",{id:f,className:V("border-t bg-background/50 dark:bg-background/30",d.divider),children:(0,t.jsx)(FH,{sections:i,tone:e})}):null]})}r(BH,"SystemNotice");function QIe({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??""),[b,v]=(0,m.useState)(!1),[j,N]=(0,m.useState)(!1),[w,k]=(0,m.useState)(null),[S,C]=(0,m.useState)(null),_=(0,m.useRef)(!1),R=f.trim().length>0&&f.trim()!==e;async function A(T){const E=T.trim();if(!(!E||E===e||c||_.current||S)){if(!uBe(E)){k("Enter a valid branch name, such as master or release/next.");return}_.current=!0,N(!0),k(null);try{await d(E),C(E)}catch(L){k(L instanceof Error?L.message:"Refresh the task to check its current state, then try again.")}finally{_.current=!1,N(!1)}}}return r(A,"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)(us,{"aria-hidden":!0,className:"mt-0.5 size-4 shrink-0 text-(--status-task-icon-done)"}):(0,t.jsx)(Rs,{"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(),A(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)(ut,{id:`${u}-branch`,autoFocus:!0,value:f,disabled:j||!!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:j,onClick:r(()=>{p(!1),k(null)},"onClick"),children:"Cancel"}):(0,t.jsx)("span",{}),(0,t.jsxs)($,{type:"submit",size:"sm",disabled:j||!R||!!c,"aria-describedby":c?`${u}-unavailable`:void 0,children:[j&&(0,t.jsx)(tt,{"aria-hidden":!0,className:"size-3.5 animate-spin motion-reduce:animate-none"}),j?"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:j||!!c,onClick:r(()=>p(!0),"onClick"),children:"Choose another branch"}),(0,t.jsxs)($,{type:"button",size:"sm",disabled:j||!!c||n===e,"aria-describedby":c?`${u}-unavailable`:void 0,onClick:r(()=>{A(n)},"onClick"),children:[j&&(0,t.jsx)(tt,{"aria-hidden":!0,className:"size-3.5 animate-spin motion-reduce:animate-none"}),j?"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":b,"aria-controls":`${u}-details`,onClick:r(()=>v(T=>!T),"onClick"),children:[b?"Hide details":"Why did this happen?",(0,t.jsx)(nn,{"aria-hidden":!0,className:V("size-3",b&&"rotate-180")})]}),b&&(0,t.jsx)("div",{id:`${u}-details`,className:"mt-2 rounded-md border border-border bg-background",children:(0,t.jsx)(FH,{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(QIe,"WorkspaceBaseRefRecoveryNotice");var zH=(0,m.createContext)(null);function Pht({value:e,children:s}){return(0,t.jsx)(zH.Provider,{value:e,children:s})}r(Pht,"DispositionRecoveryProvider");function Mht(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(Mht,"readDispositionRecoverySnapshot");function GIe(e){return Mht(e,(0,m.useContext)(zH)?.issue.activeRecoveryAction)}r(GIe,"useDispositionRecoverySnapshot");function Dht(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(Dht,"dispositionRetryUnavailableReason");function Lht(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(Lht,"descriptionFor");function qH({snapshot:e,createdAt:s,defaultExpanded:n=!1}){const a=(0,m.useContext)(zH),[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)(),b=(0,m.useId)(),v=(0,m.useId)(),j=Dht(e,a),N=!!(a&&a.issue.activeRecoveryAction?.id!==e.actionId),w=e.assigneeAgentId&&a?.agentMap?.get(e.assigneeAgentId)?.name||"the assigned agent",k=d||N?us:Rs;async function S(){if(!(!a||j||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":b,className:"flex min-w-0 gap-2.5 py-3","data-testid":"disposition-recovery-notice",children:[(0,t.jsx)(k,{"aria-hidden":"true",className:V("mt-0.5 size-4 shrink-0",d||N?"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:b,className:"break-words text-sm font-medium text-foreground",children:d?"Retry requested":N?"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}.`:Lht(e)})]}),j&&!d?(0,t.jsxs)("p",{id:v,className:"text-xs leading-relaxed text-muted-foreground",children:[!N&&(0,t.jsx)("span",{className:"font-medium text-foreground",children:"Retry unavailable. "}),j]}):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&&!N?(0,t.jsxs)($,{size:"xs",variant:"outline",disabled:l||!!j,"aria-describedby":j?v:void 0,onClick:r(()=>{S()},"onClick"),children:[l?(0,t.jsx)(tt,{"aria-hidden":"true",className:"size-3 animate-spin motion-reduce:animate-none"}):(0,t.jsx)(Ii,{"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)(nn,{"aria-hidden":"true",className:V("size-3",i&&"rotate-180")})]}),s?(0,t.jsx)("time",{dateTime:s,className:"font-mono text-xs text-muted-foreground sm:ml-auto",children:ao(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(qH,"DispositionRecoveryNotice");var $ht="System update",Oht=80;function Fht(e){const s=e.match(/Latest retry failure: `([^`]+)`/);return s?s[1]:null}r(Fht,"retryFailureCode");function Bht(e){const s=e.match(/Recovery owner: \[([^\]]+)\]\(/)?.[1]?.trim();return s&&s.length>0?s:null}r(Bht,"recoveryOwnerName");function zht(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<=Oht?a:`${a.slice(0,79).trimEnd()}…`}r(zht,"firstSentence");function qht(e){const s=e.presentation?.title?.trim(),n=e.presentation?.tone;if(s)return{title:s,tone:n??"neutral"};const a=e.body??"",i=Fht(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=Bht(a);return{title:o?`Task paused — waiting on ${o}`:"Task paused — waiting on a recovery owner",tone:n??"warning"}}return{title:$ht,tone:n??"neutral",detail:zht(a)}}r(qht,"humanizeSystemNotice");var Uht={neutral:"System notice",info:"System notice",success:"System notice",warning:"System warning",danger:"System alert"};function _w(e,s){const n=e.label?.trim();return n&&n.length>0?n:s}r(_w,"metadataRowText");function Kht(e,s){switch(e.type){case"text":return{kind:"text",label:_w(e,"Detail"),value:e.text};case"code":return{kind:"code",label:_w(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:_w(e,"Task"),identifier:n,href:`/issues/${n}`,title:e.title??void 0}:{kind:"text",label:_w(e,"Task"),value:e.title??"unknown"}}case"agent_link":{const n=e.name?.trim()||e.agentId.slice(0,8);return{kind:"agent",label:_w(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:_w(e,"Run"),runId:e.runId,href:a,status:e.title??void 0}}default:return null}}r(Kht,"mapMetadataRow");function UH(e,s={}){return!e||!Array.isArray(e.sections)?[]:e.sections.map(n=>{const a=n.rows.map(o=>Kht(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(UH,"mapCommentMetadataToSystemNoticeSections");function YIe(e,s){const n=s?.trim();return n&&n.length>0?n:Uht[e]}r(YIe,"systemNoticeLabelForTone");function Wht(e){const s=e.presentation?.tone??"neutral",n=YIe(s,e.presentation?.title),a=!!e.presentation?.detailsDefaultOpen,i=UH(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(Wht,"buildSystemNoticeProps");var Vht={neutral:Uh,info:Uh,success:ha,warning:Rs,danger:Ik},Hht={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 Qht({item:e,onTryAgainNoLiveExecutionPath:s,tryAgainNoLiveExecutionPathPending:n=!1}){const a=GIe(e.metadata),i=VIe(e.metadata),o=Kp(),[l,c]=(0,m.useState)(!!e.presentation?.detailsDefaultOpen),d=(0,m.useId)(),{title:u,tone:h,detail:p}=qht({body:e.text,presentation:e.presentation}),f=UH(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")),b=Vht[h],v=e.createdAtIso?ao(e.createdAtIso):void 0,j=!!s&&(e.presentation?.title?.trim()==="No live execution path"||e.text.toLowerCase().includes("no live execution path")),N=r(()=>{Promise.resolve().then(()=>s?.()).catch(()=>{})},"handleTryAgain");return e.author==="system"&&i?(0,t.jsx)(QIe,{...i.props},`${i.actionId}:${i.runId}`):e.author==="system"&&a?(0,t.jsx)(qH,{snapshot:a,createdAt:e.createdAtIso,defaultExpanded:e.presentation?.detailsDefaultOpen}):(0,t.jsxs)("div",{className:V("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:V("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)(b,{className:V("h-3.5 w-3.5 shrink-0",Hht[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)(nn,{className:V("tc-notice-chevron h-3.5 w-3.5 shrink-0 transition-transform",l&&"rotate-180"),"aria-hidden":!0})]}),j&&!l?(0,t.jsx)($,{type:"button",variant:"outline",size:"xs",onClick:N,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)(In,{softBreaks:!0,linkIssueReferences:!0,children:e.text})}):null,f.length>0?(0,t.jsx)("div",{className:V("bg-background/50 dark:bg-background/30",x&&"border-t border-border/70"),children:(0,t.jsx)(FH,{sections:f,tone:h})}):null,j?(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:N,disabled:n,"data-testid":"task-chat-no-live-path-try-again",children:n?"Trying again...":"Try again"})}):null]}):null]})}r(Qht,"TaskChatSystemNotice");function KH({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)(or,{agent:n,name:e,size:24})}),(0,t.jsx)("span",{className:"text-sm font-semibold text-foreground",children:e})]})}r(KH,"TaskChatAgentIdentity");function Gre(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(Gre,"galleryItemForMedia");function Yre(e){return e.filter((s,n)=>e.findIndex(a=>s.id&&a.id===s.id||a.url===s.url)===n)}r(Yre,"uniqueAttachmentRefs");function JIe(e){return UIe(e.item.id)??(0,t.jsx)(Ght,{...e})}r(JIe,"TaskChatBubble");function Ght({item:e,animateEntry:s=!0,queuedAction:n,attachedTurn:a,beforeTurn:i,hideAgentIdentity:o=!1,actions:l,attachments:c=[],onTryAgainNoLiveExecutionPath:d,tryAgainNoLiveExecutionPathPending:u}){const h=Kp(),p=(0,m.useContext)(Gg),f=(0,m.useContext)(Cy),[x,b]=(0,m.useState)(null),v=(0,m.useCallback)(M=>{f?.(M)||b(M)},[f]);if(e.interstitial)return null;if(e.author==="system")return(0,t.jsx)(Qht,{item:e,onTryAgainNoLiveExecutionPath:d,tryAgainNoLiveExecutionPathPending:u});const j=e.author==="human",N=j&&e.isCurrentUser===!0,w=j&&e.sourceChannel==="imessage-photon",{refs:k,text:S}=uYe(e.text),C=cYe(S),_=dYe(S),R=Ete(k,c),A=Ete(C,c),T=c.filter(M=>M.issueCommentId===e.id).map(M=>({id:M.id,name:M.originalFilename?.trim()||"attachment",url:M.contentPath,contentType:M.contentType,byteSize:M.byteSize,openPath:M.openPath,downloadPath:M.downloadPath})),E=Yre([...A,...R.filter(CT),...T.filter(CT)]),L=Yre([...R.filter(M=>!CT(M)),...T.filter(M=>!CT(M))]),O=[...E,...L.filter(M=>im(M.contentType,M.name))],P=x!==null&&!O.some(M=>M.url===x)?[Gre(x)]:O.map(M=>Gre(M.url,M.name,M)),U=x===null?-1:Math.max(0,O.findIndex(M=>M.url===x));return(0,t.jsxs)("div",{className:V("flex w-full flex-col gap-1",s&&"tc-enter-bubble",N?"items-end":"items-start"),children:[i?(0,t.jsx)("div",{className:"w-full pb-1",children:i}):null,j&&!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:Iht(e.authorAvatarUrl),size:"default",className:"gap-2"})}):null,!j&&e.authorName&&!o?(0,t.jsx)(KH,{agentName:e.authorName,agentIcon:e.agentIcon,agent:e.agent}):null,_.length>0?(0,t.jsx)("div",{"data-testid":j?"task-chat-human-bubble":"task-chat-agent-bubble",className:V("break-words py-2 text-sm",N?"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)(In,{className:N?"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((M,B)=>(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 ${M.name||`image ${B+1}`}`,onClick:r(()=>v(M.url),"onClick"),children:(0,t.jsx)("img",{src:M.openPath??M.url,alt:M.name,loading:"lazy",className:"h-full w-full object-cover transition-transform group-hover:scale-(--s-1_02)"})},M.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(M=>M.name||"image").join(" · ")})]}):null,L.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 · ",L.length]}),(0,t.jsx)(hV,{"data-testid":"task-chat-bubble-attachments",children:L.map(M=>{const B=Rke(M),q=B.icon,z=pV(M.byteSize),K=im(M.contentType,M.name);return(0,t.jsxs)(lV,{size:"sm",children:[(0,t.jsx)(cV,{className:K?"aspect-video group-data-[size=sm]/attachment:w-20":void 0,children:K?(0,t.jsx)(l2,{artifact:{title:M.name,contentPath:M.openPath??M.url,mediaKind:"video"}}):(0,t.jsx)(q,{"aria-hidden":!0})}),(0,t.jsxs)(dV,{children:[(0,t.jsx)(uV,{className:"max-w-48",children:M.name}),(0,t.jsx)(mV,{className:"max-w-48",children:z?`${B.label} · ${z}`:B.label})]}),(0,t.jsx)(_ke,{"aria-label":`Open ${M.name}`,onClick:K?()=>v(M.url):void 0,render:K?(0,t.jsx)("button",{type:"button"}):(0,t.jsx)("a",{href:M.openPath??M.url,onClick:r(W=>{p&&M.id&&Pj({contentType:M.contentType??"",originalFilename:M.name})&&!W.metaKey&&!W.ctrlKey&&!W.shiftKey&&!W.altKey&&(W.preventDefault(),p(M.id,M.name))},"onClick"),target:"_blank",rel:"noreferrer"})})]},M.url)})})]}):null,!j&&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((M,B)=>(0,t.jsxs)("li",{children:[(0,t.jsx)("span",{className:"font-mono text-foreground",children:M.commandOrCheck}),M.reasonCode?` · ${M.reasonCode.replaceAll("_"," ")}`:"",M.detail?(0,t.jsx)("span",{className:"block",children:M.detail}):null]},`${M.commandOrCheck}:${B}`))})]}):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&&U>=0?(0,t.jsx)(Mj,{items:P,initialIndex:U,open:!0,onOpenChange:r(M=>{M||b(null)},"onOpenChange")}):null]})}r(Ght,"TaskChatBubbleContent");function Jre(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(Jre,"turnSummaryMetrics");function Xre({item:e,renderChild:s,timestampPrefix:n,leading:a}){const i=Kp(),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)(KH,{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)(In,{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,b]=(0,m.useState)(e.settled),[v,j]=(0,m.useState)(o);o&&!v&&j(!0),e.settled!==x&&(b(e.settled),e.settled&&!v&&h(!1));const N=d.length>0,w=(e.settled||o)&&!u,k=e.summary.failed?zn:us,S=e.settled&&(!e.historical||N)?(0,t.jsxs)("button",{type:"button",onClick:r(()=>h(C=>!C),"onClick"),"aria-expanded":u,className:V("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)(k,{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&&Jre(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:Jre(e.summary)})}):null,(0,t.jsx)(Pn,{className:V("h-3 w-3 shrink-0 transition-transform",e.standaloneHeader&&"ml-auto",u?"rotate-90":null),"aria-hidden":!0})]}):o?(0,t.jsx)(RIe,{item:e.liveStatus,chevronOpen:N?u:void 0,onToggle:N?()=>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(Xre,"TaskChatTurn");var Yht={session_start:Wu,interrupted:bW,turn_boundary:Ug};function XIe({item:e,onTryAgain:s,tryAgainPending:n=!1}){const[a,i]=(0,m.useState)(!1),o=(0,m.useId)(),l=Kp(),c=e.tone==="neutral"?Hg:Yht[e.variant],d=e.variant==="interrupted"&&e.tone!=="neutral",u=e.createdAtIso?ao(e.createdAtIso):void 0,h=r(()=>{Promise.resolve().then(()=>s?.()).catch(()=>{})},"handleTryAgain");if(e.credentialAccess){const{agentName:p,credentialName:f,deniedUser:x,settingsHref:b}=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:b,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:V("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)(nn,{className:V("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:V("h-px flex-1",d?"border-t border-dashed border-destructive/50":"bg-border")}),(0,t.jsxs)("span",{className:V("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:V("h-px flex-1",d?"border-t border-dashed border-destructive/50":"bg-border")})]})}r(XIe,"TaskChatMarker");var ZIe=(0,m.createContext)(null);function WH(e,s){const n=(0,m.useContext)(ZIe),[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(WH,"useTaskChatExpansion");var Jht={pending:{Icon:tt,spin:!1,tone:"text-muted-foreground"},in_progress:{Icon:tt,spin:!0,tone:"text-(--status-agent-running)"},completed:{Icon:us,spin:!1,tone:"text-muted-foreground"},failed:{Icon:zn,spin:!1,tone:"text-destructive"},interrupted:{Icon:zn,spin:!1,tone:"text-muted-foreground"}};function eAe({item:e}){const{Icon:s,spin:n,tone:a}=Jht[e.status],i=Gk(e.rawName??e.name).icon,[o,l]=WH(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:V("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:V("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)(Fi,{className:"h-3 w-3"}):(0,t.jsx)(kW,{className:"h-3 w-3"}),e.decision]}):null,c?(0,t.jsx)(Pn,{className:V("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:V("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(eAe,"TaskChatToolCard");function VH({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)(pW,{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:V("h-full rounded-full bg-(--status-agent-running)"),style:{width:`${c}%`}})}):null]})}r(VH,"TaskChatUsageReadout");function tAe(e){const s=e.details.find(n=>n.label==="Severity")?.value;return e.status==="failed"||s==="error"?"error":s==="info"?"info":"warning"}r(tAe,"providerNoticeSeverity");function ef(e,...s){return e.details.find(n=>s.includes(n.label))?.value}r(ef,"providerDetail");function _F(e){if(!(!e||mu(e)||/^tool(?:\s+|_)call\b/i.test(e)))return e}r(_F,"meaningfulToolDetail");function Xht(e){const s=e.summary??ef(e,"Query","URL","Target","Name","Reference","Reason","Summary");switch(e.family){case"research":{const n=ef(e,"Action")?.toLowerCase();return n==="open_page"?{icon:na,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:na,runningLabel:"Searching the page",completedLabel:"Searched the page",failedLabel:"Page search failed",interruptedLabel:"Page search stopped",detail:s}:{icon:na,runningLabel:"Searching the web",completedLabel:"Searched the web",failedLabel:"Web search failed",interruptedLabel:"Web search stopped",detail:s}}case"tool_execution":{const n=ef(e,"Name"),a=ef(e,"Target"),i=ef(e,"Progress"),o=Xy({name:n,transport:ef(e,"Transport"),namespace:ef(e,"Namespace"),operation:ef(e,"Operation"),target:a,progress:i}),l=_F(e.summary)??_F(i)??_F(a),c=!!(l&&n&&ek(l)===ek(n)),d=n?LH(n)?.name??n:o.displayName,u=o.sourceLabel?`${o.sourceLabel} · ${d}`:n&&!mu(n)&&ek(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:wj,runningLabel:"Updating the plan",completedLabel:"Updated the plan",failedLabel:"Plan update failed",interruptedLabel:"Plan update stopped",detail:s};case"delegation":{const n=ef(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:ro,runningLabel:"Switching models",completedLabel:"Switched models",failedLabel:"Model switch failed",interruptedLabel:"Model switch stopped",detail:s}:{icon:ro,runningLabel:"Verifying the model",completedLabel:"Verified the model",failedLabel:"Model verification failed",interruptedLabel:"Model verification stopped",detail:s};case"context":return{icon:wA,runningLabel:"Compacting context",completedLabel:"Compacted context",failedLabel:"Context compaction failed",interruptedLabel:"Context compaction stopped",detail:s};case"artifact":return e.eventType==="artifact.viewed"?{icon:U_,runningLabel:"Viewing an artifact",completedLabel:"Viewed an artifact",failedLabel:"Couldn’t view the artifact",interruptedLabel:"Artifact view stopped",detail:s}:{icon:U_,runningLabel:"Generating an artifact",completedLabel:"Generated an artifact",failedLabel:"Artifact generation failed",interruptedLabel:"Artifact generation stopped",detail:s};case"review":return ef(e,"State")?.toLowerCase()==="exited"?{icon:hee,runningLabel:"Leaving review mode",completedLabel:"Left review mode",failedLabel:"Couldn’t leave review mode",interruptedLabel:"Review-mode change stopped",detail:s}:{icon:hee,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:RS,runningLabel:"Checking memory",completedLabel:"Referenced memory",failedLabel:"Memory lookup failed",interruptedLabel:"Memory lookup stopped",detail:s};case"safety":return{icon:Fi,runningLabel:"Reviewing safety",completedLabel:"Reviewed safety",failedLabel:"Safety review failed",interruptedLabel:"Safety review stopped",detail:s};case"terminal":return{icon:tx,runningLabel:"Sending terminal input",completedLabel:"Sent terminal input",failedLabel:"Terminal input failed",interruptedLabel:"Terminal input stopped",detail:s};case"wait":return{icon:fu,runningLabel:"Waiting",completedLabel:"Finished waiting",failedLabel:"Wait failed",interruptedLabel:"Wait stopped",detail:s};case"provider_notice":return{icon:tAe(e)==="info"?Uh:Rs,runningLabel:"Provider notice",completedLabel:"Provider notice",failedLabel:"Provider error",interruptedLabel:"Provider notice",detail:s}}}r(Xht,"providerActivityPresentation$1");function Zht(e){const s=e.totals.files||e.files.length,n=s>0?`${s} ${s===1?"file":"files"}`:void 0;return{icon:L4,runningLabel:"Editing files",completedLabel:"Edited files",detail:n}}r(Zht,"workspaceChangePresentation");function ept(e){return{icon:Ya,runningLabel:"Referencing a file",completedLabel:"Referenced a file",detail:e.line==null?e.path:`${e.path}:${e.line}`}}r(ept,"workspaceFilePresentation");function tpt(e){return{icon:e.resourceKind==="document"?Ya:Ak,runningLabel:"Saving a resource",completedLabel:e.resourceKind==="document"?"Added a document":"Added a deliverable",detail:e.title}}r(tpt,"resourcePresentation");function sAe(e){switch(e.surface){case"provider_activity":return Xht(e);case"workspace_change":return Zht(e);case"workspace_file":return ept(e);case"resource":return tpt(e);case"runtime_request":case"run_result":case"run_terminal":return null}}r(sAe,"protocolActivityPresentation");function nAe(e){return e.surface==="provider_activity"?e.status==="running":e.surface==="workspace_change"?!e.complete:!1}r(nAe,"protocolActivityIsRunning");function spt(e,s){return e.surface!=="provider_activity"?nAe(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(spt,"protocolActivityLabel");var npt={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 rpt(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=Xy({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(b=>b.label===x)?.value,"value"),f=Xy({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=sAe(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:tAe(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":npt[u.family],u.icon,u.order)}s.size||(e.some(u=>u.kind==="thinking")?n("Thought through the task",ug):e.some(u=>u.kind==="marker")?n("Activity stopped",Kd):n("Recorded usage",pW));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:Wl}}r(rpt,"completedActivitySummary");var Zre=5,apt=8;function ipt(e,s=!1){return s&&(e==="blocked"||e==="failed")?(0,t.jsx)(Gf,{className:"h-3 w-3 text-muted-foreground","aria-hidden":!0}):e==="in_progress"?(0,t.jsx)(tt,{className:"h-3 w-3 animate-spin text-(--status-agent-running)","aria-hidden":!0}):e==="completed"?(0,t.jsx)(us,{className:"h-3 w-3 text-(--status-task-icon-done)","aria-hidden":!0}):e==="blocked"||e==="failed"?(0,t.jsx)(zn,{className:"h-3 w-3 text-destructive","aria-hidden":!0}):(0,t.jsx)(Gf,{className:"h-3 w-3 text-muted-foreground","aria-hidden":!0})}r(ipt,"stepStatusIcon");function rAe({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:V("min-w-0 break-words text-foreground",s.mono&&"font-mono"),children:s.value})]},`${s.label}:${s.value}`))})}r(rAe,"DetailList");function opt(e){try{return new URL(e).hostname.replace(/^www\./,"")}catch{return e}}r(opt,"sourceHostname");function lpt({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,Zre),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:opt(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>Zre?(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)(rAe,{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(lpt,"ResearchDetails");function cpt({item:e,neutral:s=!1}){return e.family==="research"?(0,t.jsx)(lpt,{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:ipt(n.status,s)}),(0,t.jsx)("span",{className:V("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)(rAe,{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(cpt,"ProviderDetails");function dpt({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,apt),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(dpt,"WorkspaceChangeDetails");function upt({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)(ibe,{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)(In,{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(upt,"WorkspaceFileDetails");function aAe(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)(cpt,{item:e,neutral:s}):null;case"workspace_change":return(0,t.jsx)(dpt,{item:e});case"workspace_file":return(0,t.jsx)(upt,{item:e});case"resource":case"runtime_request":case"run_result":case"run_terminal":return null}}r(aAe,"detailContent");function iAe(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(iAe,"safeActivityHref");function mpt(e){return e.surface==="resource"?!!iAe(e.href):aAe(e)!==null||e.surface==="provider_activity"&&!!e.summary?.trim()}r(mpt,"hasTaskChatProtocolActivityDetails");function hpt({item:e,neutral:s=!1}){const n=aAe(e,s);if(e.surface==="resource"){const a=iAe(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(hpt,"TaskChatProtocolActivityDetails");function oAe(e,s){if(e.kind==="tool"){const d=Xy({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:ug,label:d?"Thinking":"Thought",target:e.lines.filter(u=>u.trim()).at(-1)?.trim(),mono:!1,running:d}}if(e.kind==="protocol"){const d=sAe(e);return d?{icon:d.icon,label:spt(e,d),target:d.detail,mono:!0,running:s&&nAe(e)}:null}if(e.kind==="marker")return{icon:Kd,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:pW,label:e.label??"Token usage",target:c||e.detail,mono:!1,running:!1}}r(oAe,"presentation");function QU({item:e,active:s}){const n=oAe(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:V("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:V("truncate text-xs text-muted-foreground",n.mono&&"font-mono"),children:n.target}):null]})]})}r(QU,"ActivityContent");function ppt({item:e,active:s}){const n=ZCe(),[a,i]=(0,m.useState)({current:e,previous:null});return a.current.id!==e.id?i({current:e,previous:n?null:a.current}):a.current!==e&&i({...a,current:e}),(0,t.jsxs)("span",{className:"relative flex h-8 min-w-0 flex-1 items-center overflow-hidden","aria-live":"polite","aria-atomic":"true","data-testid":"task-chat-activity-viewport",children:[a.previous&&!n?(0,t.jsx)("span",{className:"runner-activity-roll-out absolute inset-0 flex items-center","aria-hidden":"true",onAnimationEnd:r(()=>i(o=>o.current.id===e.id?{...o,previous:null}:o),"onAnimationEnd"),children:(0,t.jsx)(QU,{item:a.previous,active:!1})},`exit-${e.id}`):null,(0,t.jsx)("span",{className:V("relative flex w-full min-w-0 items-center",a.previous&&!n&&"runner-activity-roll-in"),children:(0,t.jsx)(QU,{item:e,active:s})},e.id)]})}r(ppt,"RollingActivity");function fpt({item:e}){return e.kind==="thinking"?(0,t.jsx)(In,{softBreaks:!0,children:e.lines.join(`
384
384
  `)}):e.kind==="usage"?(0,t.jsx)(VH,{item:e}):e.kind==="protocol"?(0,t.jsx)(hpt,{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(fpt,"ActivityDetails");function xpt(e){return e.kind==="protocol"?mpt(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(xpt,"hasActivityDetails");function gpt({item:e,active:s}){const[n,a]=WH(`runner-detail:${e.id}`,!1),i=(0,m.useId)(),o=xpt(e),l=(0,t.jsx)(QU,{item:e,active:s});return(0,t.jsxs)("li",{className:"min-w-0","data-activity-item-id":e.id,children:[o?(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(()=>a(!n),"onClick"),"aria-expanded":n,"aria-controls":n?i:void 0,children:[l,(0,t.jsx)(Pn,{className:V("size-3.5 shrink-0",n&&"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:l}),o&&n?(0,t.jsx)("div",{id:i,className:"flex min-w-0 flex-col gap-2 overflow-hidden rounded-md bg-muted/40 p-3 text-xs leading-relaxed text-muted-foreground","data-testid":"task-chat-runner-activity-detail",children:(0,t.jsx)(fpt,{item:e})}):null]})}r(gpt,"ExpandedActivity");function RI({item:e,defaultExpanded:s=!1}){const[n,a]=WH(e.id,s),i=(0,m.useId)(),o=e.items.filter(h=>oAe(h,!1)!==null),l=o.at(-1),c=rpt(o),d=c.icon,u=`${o.length} ${o.length===1?"activity":"activities"}`;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-expanded":n,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)(In,{softBreaks:!0,linkIssueReferences:!0,children:e.interstitial.text})}):null,l?(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"} ${e.active?u:`${c.fullLabel.toLowerCase()} (${u})`}`,children:[e.active?n?(0,t.jsxs)("span",{className:"flex min-h-8 flex-1 items-center gap-2 text-xs",children:[(0,t.jsx)("span",{className:"flex size-5 shrink-0 items-center justify-center",children:(0,t.jsx)(nn,{className:"size-3.5","aria-hidden":"true"})}),(0,t.jsx)("span",{children:u})]}):(0,t.jsx)(ppt,{item:l,active:e.active}):(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)(d,{className:"size-3.5","aria-hidden":"true"})}),(0,t.jsx)("span",{className:"truncate",title:c.fullLabel,children:c.label})]}),(0,t.jsxs)("span",{className:"flex shrink-0 items-center gap-1 text-xs",children:[n?u:e.active?o.length:null,(0,t.jsx)(Pn,{className:V("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:o.map((h,p)=>(0,t.jsx)(gpt,{item:h,active:e.active&&p===o.length-1},h.id))}):null]}):null]})}r(RI,"TaskChatRunnerActivityGroup");var bpt=new Set(["failed","timed_out","cancelled","interrupted","succeeded"]);function _y(e){return e!=null&&bpt.has(e)}r(_y,"isTerminalRunStatus$1");function eae(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(eae,"splitTranscriptAtAnchors");function vpt(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(vpt,"flattenSelfTalk");function ypt(e){return e==="add"?"add":e==="remove"?"remove":"context"}r(ypt,"diffKind");var jpt=["file_path","path","notebook_path","command","pattern","query","url","prompt","description","skill","subject"],P1=96,wpt=/^xd:\/\/([A-Za-z0-9_]+)$/,Npt={resolve:!0,reject:!0,propose:!0,report_issue:!0};function kpt(e){if(typeof e!="string")return null;const s=wpt.exec(e.trim());return s?s[1]in Npt?null:s[1]:null}r(kpt,"xdDeviceFromPath");function Spt(e,s){if(e?.trim()!=="write"||s==null||typeof s!="object")return null;const n=s,a=kpt(n.path);return a||(typeof n.path=="string"||!("content"in n)?null:_pt(n.content))}r(Spt,"xdDeviceToolName");var Cpt=/"code"\s*:\s*"[\s\S]{0,400}?omp\./;function _pt(e){return typeof e!="string"?null:Cpt.test(e)?"fabric_exec":null}r(_pt,"fabricDeviceFromPayload");function K0(e,s){const n=e.replace(/\s+/g," ").trim();return n.length>s?`${n.slice(0,s-1)}…`:n}r(K0,"clip");function Ipt(e){if(e==null)return;if(typeof e=="string")return e.trim()?K0(e,P1):void 0;if(typeof e!="object")return K0(String(e),P1);const s=e;for(const a of jpt){const i=s[a];if(typeof i=="string"&&i.trim())return K0(i,P1)}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 K0(n.map(([a,i])=>`${a}: ${String(i)}`).join(", "),P1)}r(Ipt,"summarizeToolInput$2");function IF(e){const s=(e??"").trim();return mu(s)?"Unnamed tool":ek(s)}r(IF,"toolDisplayName");function Apt(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(Apt,"thoughtDurationLabel");function Tpt(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(Tpt,"appendThinkingText");var tae=600,b_=8192;function HT(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)?e:{}}r(HT,"objectRecord");function td(e){return typeof e=="string"&&e.trim().length>0?e.trim():void 0}r(td,"stringValue");function Rpt(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(Rpt,"scalarValue");function Ept(e){return e.replace(/([a-z0-9])([A-Z])/g,"$1 $2").replaceAll("_"," ").replace(/\b\w/g,s=>s.toUpperCase())}r(Ept,"titleCaseKey$1");function Ppt(e){const s=td(e);if(!s)return null;try{const n=new URL(s);return n.protocol==="http:"||n.protocol==="https:"?s:null}catch{return null}}r(Ppt,"safeHttpHref");var Mpt={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 lAe(e){for(const s of["planId","executionId","researchId","delegationId","routeId","verificationId","compactionId","artifactId","reviewId","hookId","citationId","waitId","noticeId"]){const n=td(e.payload[s]);if(n)return`${e.family}:${n}`}return`${e.family}:${e.eventType}:${e.ts}`}r(lAe,"providerActivityKey");function Dpt(e,s,n){const a=[];for(const h of Mpt[e.family]){const p=Rpt(e.payload[h]);p&&(e.family==="tool_execution"&&h==="name"&&mu(p)||e.family==="tool_execution"&&h==="progress"&&!GU(p)||a.push({label:Ept(h),value:K0(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=HT(h);typeof p.name=="string"&&typeof p.value=="string"&&a.push({label:K0(p.name,160),value:K0(p.value,4e3),mono:!1})}const i=e.family==="plan"&&Array.isArray(e.payload.steps)?e.payload.steps.map(HT).slice(0,256).map((h,p)=>{const f=td(h.status),x=f==="in_progress"||f==="completed"||f==="blocked"?f:"pending";return{id:td(h.stepId)??`${s}:plan-step:${p}`,label:td(h.body)??"Plan step",status:x}}):[],o=e.family==="research"&&Array.isArray(e.payload.sources)?e.payload.sources.map(HT).slice(0,64).flatMap(h=>{const p=Ppt(h.url);return p?[{label:td(h.title)??p,href:p,description:td(h.snippet)}]:[]}):[],l=e.family==="delegation"&&Array.isArray(e.payload.children)?e.payload.children.map(HT).slice(0,64).map((h,p)=>({id:td(h.childId)??`${s}:delegation:${p}`,title:td(h.role)??"Subagent",status:td(h.status)??"unknown",metadata:[td(h.model),td(h.activitySummary)].filter(Boolean).join(" · ")||void 0,summary:td(h.summary)})):[],c=e.family==="tool_execution"?td(e.payload.output):void 0,d=e.payload.outputTruncated===!0||!!(c&&c.length>b_),u=e.summary&&e.summary!==e.eventType?e.summary:td(e.payload.explanation)??td(e.payload.progress)??td(e.payload.message)??td(e.payload.summary);return{id:`${s}:provider:${lAe(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,b_):void 0,outputTruncated:d,transcriptIndex:n}}r(Dpt,"providerActivityItem");function lu(e,s){return e.details.find(n=>n.label===s)?.value}r(lu,"providerItemDetail");function GU(e){return!!(e&&!mu(e)&&!/^tool(?:\s+|_)call\b/i.test(e))}r(GU,"meaningfulProviderToolSummary");function Lpt(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=lu(s,"Name"),i=mu(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"&&!GU(l.value)&&n.has("Progress")||n.set(l.label,l);return{...s,id:e.id,summary:GU(s.summary)?s.summary:e.summary,details:[...n.values()]}}r(Lpt,"mergeProviderActivityItem");function $pt(e){if(e==null)return;const s=(typeof e=="string"?e:String(e)).trim();if(s)return s.length>tae?`${s.slice(0,tae)}
@@ -519,7 +519,7 @@ ${e.stopReason}`:""}`:e.text}r($Tt,"rawEntryContent");function OTt({entries:e,de
519
519
  "cwd": "."
520
520
  }
521
521
  ]
522
- }`})})})]})]}),(0,t.jsxs)("div",{className:"mt-5 flex flex-col items-stretch gap-3 sm:flex-row sm:flex-wrap sm:items-center",children:[(0,t.jsxs)($,{className:"w-full sm:w-auto",disabled:!L||z.isPending,onClick:X,children:[z.isPending?(0,t.jsx)(tt,{className:"mr-2 h-4 w-4 animate-spin"}):null,"Save changes"]}),(0,t.jsx)($,{variant:"outline",className:"w-full sm:w-auto",disabled:!L||z.isPending,onClick:r(()=>{f(E),b(null)},"onClick"),children:"Reset"}),x?(0,t.jsx)("p",{className:"text-sm text-destructive",children:x}):null,!x&&v?(0,t.jsx)("p",{className:"text-sm text-muted-foreground",children:v}):null,!x&&!L?(0,t.jsx)("p",{className:"text-sm text-muted-foreground",children:"No unsaved changes."}):null]})]})}),(0,t.jsxs)("div",{className:"space-y-6",children:[(0,t.jsxs)(sn,{className:"block p-5",children:[(0,t.jsxs)("div",{className:"space-y-1",children:[(0,t.jsx)("div",{className:"text-xs font-medium uppercase tracking-(--tracking-eyebrow) text-muted-foreground",children:"Workspace facts"}),(0,t.jsx)("h2",{className:"text-lg font-semibold",children:"Current state"})]}),(0,t.jsx)(Ul,{className:"my-4"}),(0,t.jsx)($w,{label:"Project",children:(0,t.jsx)(We,{to:`/projects/${T}`,className:"hover:underline",children:R.name})}),(0,t.jsx)($w,{label:"Workspace ID",children:(0,t.jsx)("span",{className:"break-all font-mono text-xs",children:A.id})}),h?null:(0,t.jsx)($w,{label:"Local path",children:(0,t.jsx)("span",{className:"break-all font-mono text-xs",children:A.cwd??"None"})}),(0,t.jsx)($w,{label:"Repo",children:A.repoUrl&&bPt(A.repoUrl)?(0,t.jsxs)("a",{href:A.repoUrl,target:"_blank",rel:"noreferrer",className:"inline-flex items-center gap-1 hover:underline",children:[A.repoUrl,(0,t.jsx)($n,{className:"h-3 w-3"})]}):A.repoUrl?(0,t.jsx)("span",{className:"break-all font-mono text-xs",children:A.repoUrl}):"None"}),(0,t.jsx)($w,{label:"Default ref",children:A.defaultRef??"None"}),(0,t.jsx)($w,{label:"Updated",children:new Date(A.updatedAt).toLocaleString()})]}),(0,t.jsxs)(sn,{className:"block p-5",children:[(0,t.jsx)("div",{className:"flex flex-col gap-3 sm:flex-row sm:items-start sm:justify-between",children:(0,t.jsxs)("div",{className:"space-y-1",children:[(0,t.jsx)("div",{className:"text-xs font-medium uppercase tracking-(--tracking-eyebrow) text-muted-foreground",children:"Workspace commands"}),(0,t.jsx)("h2",{className:"text-lg font-semibold",children:"Services and jobs"}),(0,t.jsx)("p",{className:"text-sm text-muted-foreground",children:"Long-running services stay supervised here, while one-shot jobs run on demand against this workspace. Execution workspaces inherit this config unless they override it."})]})}),(0,t.jsx)(n2e,{className:"mt-4",sections:J,isPending:W.isPending,pendingRequest:ie,serviceEmptyMessage:A.runtimeConfig?.workspaceRuntime?"No services have been started for this workspace yet.":"No workspace command config is defined for this workspace yet.",jobEmptyMessage:"No one-shot jobs are configured for this workspace yet.",disabledHint:"Project workspaces need a working directory before local commands can run, and services also need runtime config.",onAction:r(Z=>W.mutate(Z),"onAction")})]})]})]}):null,u8(k)?G?(0,t.jsx)(am,{slot:G.slot,context:{companyId:R.companyId,companyPrefix:e??null,projectId:R.id,entityId:A.id,entityType:"project_workspace"},missingBehavior:"placeholder"}):P||U?(0,t.jsx)("div",{className:"rounded-lg border border-dashed border-border bg-background px-4 py-8 text-sm text-muted-foreground",children:U||"Loading workspace plugin..."}):(0,t.jsx)(r5e,{defaultTabHref:`${r_(R,w)}?tab=configuration`,defaultTabLabel:"Back to configuration"}):null]})}r(NPt,"ProjectWorkspaceDetail");function kPt(e){return{key:e.key,kind:e.kind,workspaceId:e.workspaceId,workspaceName:e.workspaceName,cwd:e.cwd,branchName:e.branchName,lastUpdatedAt:e.lastUpdatedAt,projectWorkspaceId:e.projectWorkspaceId,executionWorkspaceId:e.executionWorkspaceId,executionWorkspaceStatus:e.executionWorkspaceStatus,serviceCount:e.serviceCount,runningServiceCount:e.runningServiceCount,primaryServiceUrl:e.primaryServiceUrl,primaryServiceUrlRunning:e.primaryServiceUrlRunning,hasRuntimeConfig:e.hasRuntimeConfig,linkedIssueCount:e.linkedIssueCount,issues:e.linkedIssues}}r(kPt,"overviewItemToSummary");function SPt(e){const s=new Map;for(const n of e){const a=s.get(n.projectId),i=kPt(n);if(a){a.summaries.push(i),i.lastUpdatedAt.getTime()>a.lastUpdatedAt.getTime()&&(a.lastUpdatedAt=i.lastUpdatedAt),a.runningServiceCount+=i.runningServiceCount;continue}s.set(n.projectId,{projectId:n.projectId,projectName:n.projectName,projectRef:Ng({id:n.projectId,name:n.projectName,urlKey:n.projectUrlKey}),summaries:[i],lastUpdatedAt:i.lastUpdatedAt,runningServiceCount:i.runningServiceCount})}return[...s.values()].sort((n,a)=>{const i=a.runningServiceCount-n.runningServiceCount;if(i!==0)return i;const o=a.lastUpdatedAt.getTime()-n.lastUpdatedAt.getTime();return o!==0?o:n.projectName.localeCompare(a.projectName)})}r(SPt,"buildProjectWorkspaceGroups");function CPt(){const{selectedCompanyId:e}=ps(),{setBreadcrumbs:s}=Hn(),n=te({queryKey:D.instance.experimentalSettings,queryFn:r(()=>vr.getExperimental(),"queryFn")}),a=n.data?.enableIsolatedWorkspaces===!0,i=Wg({queryKey:e?D.executionWorkspaces.overview(e):["execution-workspaces","__workspaces-overview__","disabled"],queryFn:r(({pageParam:p})=>bc.listOverview(e,{offset:p}),"queryFn"),initialPageParam:0,getNextPageParam:r(p=>p.nextOffset??void 0,"getNextPageParam"),enabled:!!(e&&a)});(0,m.useEffect)(()=>{s([{label:"Workspaces"}])},[s]);const o=i.data?.pages??[],l=(0,m.useMemo)(()=>o.flatMap(p=>p.items),[o]),c=(0,m.useMemo)(()=>SPt(l),[l]),d=(o[0]??null)?.total??l.length,u=i.isLoading,h=i.error;return n.isLoading?(0,t.jsx)(Pa,{variant:"detail"}):a?u?(0,t.jsx)(Pa,{variant:"list"}):h?(0,t.jsx)("p",{className:"text-sm text-destructive",children:h.message}):(0,t.jsxs)("div",{className:"space-y-6",children:[(0,t.jsx)("div",{children:(0,t.jsx)("h2",{className:"text-xl font-bold",children:"Workspaces"})}),(0,t.jsx)(vG,{companyId:e,scopeKind:"workspaces_overview",title:"Workspace summary",description:"Summarizer tracks workspace activity, live services, and follow-up needs across projects."}),c.length===0?(0,t.jsx)("p",{className:"text-sm text-muted-foreground",children:"No workspace activity yet."}):(0,t.jsxs)("div",{className:"space-y-8",children:[c.map(p=>(0,t.jsxs)("section",{className:"space-y-3",children:[(0,t.jsxs)("div",{className:"flex flex-wrap items-end justify-between gap-2",children:[(0,t.jsx)("div",{className:"min-w-0",children:(0,t.jsx)(We,{to:`/projects/${p.projectRef}/workspaces`,className:"text-base font-semibold hover:underline",children:p.projectName})}),(0,t.jsxs)("span",{className:"text-xs text-muted-foreground",children:[p.summaries.length," workspace",p.summaries.length===1?"":"s"]})]}),(0,t.jsx)(C3e,{companyId:e,projectId:p.projectId,projectRef:p.projectRef,summaries:p.summaries})]},p.projectId)),i.hasNextPage?(0,t.jsxs)("div",{className:"flex flex-wrap items-center justify-between gap-3 border-t border-border pt-4",children:[(0,t.jsxs)("p",{className:"text-sm text-muted-foreground",children:["Showing ",l.length," of ",d," workspaces."]}),(0,t.jsx)($,{type:"button",variant:"outline",size:"sm",onClick:r(()=>{i.fetchNextPage()},"onClick"),disabled:i.isFetchingNextPage,children:i.isFetchingNextPage?"Loading...":"Load more"})]}):null]})]}):(0,t.jsx)(An,{to:"/issues",replace:!0})}r(CPt,"Workspaces");var _Pt=6e4,IPt=12e4,APt=9e5,Gle={active:0,thinking:1,starting:2,quiet:3,stalled:4},i5e={starting:"loading",active:"working",thinking:"thinking",quiet:"sleepy",stalled:"confused"};function o5e(e){if(!e)return null;const s=new Date(e).getTime();return Number.isFinite(s)?s:null}r(o5e,"toMs$1");function D3(e){let s=null;for(const n of[e.lastEventAt,e.currentStatusUpdatedAt,e.outputSilence?.lastOutputAt,e.lastUsefulActionAt]){const a=o5e(n);a!==null&&(s===null||a>s)&&(s=a)}return s}r(D3,"lastLiveActivityMs");function m8(e){const s=Math.floor(e/6e4);if(s<1)return`${Math.max(0,Math.floor(e/1e3))}s`;if(s<60)return`${s}m`;const n=Math.floor(s/60),a=s%60;return a>0?`${n}h ${a}m`:`${n}h`}r(m8,"formatSilence");function TPt(e){return!!e.currentToolName&&!/^finished\b/i.test(e.currentStatusMessage??"")}r(TPt,"toolInFlight");function l5e(e,s){const n=o5e(e.startedAt);if(n===null||e.status==="queued"||e.status==="scheduled_retry")return{health:"starting",label:"Queued",silentMs:null};const a=D3(e);if(a===null&&s-n<_Pt)return{health:"starting",label:"Starting",silentMs:null};const i=Math.max(0,s-(a??n)),o=e.outputSilence?.level,l=e.outputSilence?.criticalThresholdMs||APt;return o==="critical"||o!=="snoozed"&&i>=l?{health:"stalled",label:`Stalled ${m8(i)}`,silentMs:i}:o==="suspicious"||i>=IPt?{health:"quiet",label:`Quiet ${m8(i)}`,silentMs:i}:TPt(e)?{health:"active",label:"Working",silentMs:i}:{health:"thinking",label:"Thinking",silentMs:i}}r(l5e,"classifyLiveNowHealth");function c5e(e){return e.reduce((s,n)=>Gle[n.health]>Gle[s.health]?n:s)}r(c5e,"mostSevereSignal");function RPt(e){const s={working:0,quiet:0,stalled:0};for(const n of e)n==="quiet"?s.quiet+=1:n==="stalled"?s.stalled+=1:s.working+=1;return s}r(RPt,"countLiveNowHealth");function Yle(e){const s=e.currentToolName?.trim()||null,n=(e.currentStatusMessage?.trim()||null)??(s?Gk(s).verbLabel:null);return n?{icon:s?Gk(s).icon:AIe(n)??Gd,text:n}:null}r(Yle,"describeLiveActivity");function d5e(e,s){return e instanceof Error&&e.message?e.message:s}r(d5e,"errorMessage");function EPt({companyId:e,entry:s,issue:n,loadFailed:a,ancestors:i,truncatedAncestors:o,issueLinkState:l,now:c,hiddenOnWide:d=!1}){const u=Nt(),h=(0,m.useId)(),[p,f]=(0,m.useState)(!1),[x,b]=(0,m.useState)(!1),[v,j]=(0,m.useState)(null),N=n?.identifier??s.issueId,w=n?.identifier??s.issueId.slice(0,8),k=n?.title??(a?"Task unavailable":"Loading task…"),S=n?kg(l,n):void 0,C=ul(N),_=s.runs[0],R=s.runs.map(Q=>l5e(Q,c)),A=c5e(R),T=R[0],E=s.runs.reduce((Q,re)=>(D3(re)??0)>(D3(Q)??0)?re:Q,_),L=Yle(E)??s.runs.map(Yle).find(Boolean)??null,O=D3(E),P=s.runs.find(Q=>Q.lastAssistantSnippet?.trim())?.lastAssistantSnippet?.trim()??null,U=s.runs.find(Q=>Q.nextAction?.trim())?.nextAction?.trim()??null,M=[...new Map(s.runs.slice(1).filter(Q=>Q.agentId!==_.agentId).map(Q=>[Q.agentId,Q])).values()],B=s.earliestStartedAt?Fq(Math.max(0,c-new Date(s.earliestStartedAt).getTime())):"Queued",q=`/agents/${_.agentId}/runs/${_.id}`,z=L?.icon??null,K=ye({mutationFn:r(()=>Xr.cancel(_.id),"mutationFn"),onSuccess:r(()=>{j(`Stopping ${_.agentName}'s run`),u.invalidateQueries({queryKey:D.liveRuns(e)}),u.invalidateQueries({queryKey:D.issues.liveRuns(s.issueId)}),u.invalidateQueries({queryKey:D.issues.activeRun(s.issueId)}),u.invalidateQueries({queryKey:D.issues.runs(s.issueId)})},"onSuccess")}),W=r(()=>{j(null),f(Q=>!Q)},"openComposer");return(0,t.jsxs)("li",{"data-live-now-issue-id":s.issueId,"data-live-health":A.health,className:V("live-now-card relative flex w-(--live-now-card-peek) shrink-0 snap-start flex-col overflow-hidden rounded-xl border border-border bg-card text-card-foreground sm:w-auto",d&&"sm:hidden"),children:[A.health==="active"||A.health==="starting"?(0,t.jsx)("span",{"aria-hidden":"true",className:"live-now-sweep"}):null,(0,t.jsxs)("div",{className:"flex items-start gap-3 px-3 pt-3",children:[(0,t.jsxs)("span",{className:"relative shrink-0",children:[(0,t.jsx)(or,{agent:{id:_.agentId,name:_.agentName,appearance:_.agentAppearance,avatarUrl:_.avatarUrl},size:40,pose:i5e[T.health]}),(0,t.jsx)("span",{"aria-hidden":"true",className:V("live-now-health-dot absolute right-0 bottom-0 size-2.5 rounded-full ring-2 ring-card",(A.health==="active"||A.health==="thinking")&&"live-now-breathe")})]}),(0,t.jsxs)("div",{className:"min-w-0 flex-1",children:[(0,t.jsxs)("div",{className:"flex min-w-0 items-center gap-2",children:[(0,t.jsx)("span",{title:_.agentName,className:"truncate text-sm font-semibold",children:_.agentName}),M.length>0?(0,t.jsx)("span",{className:"flex shrink-0 items-center","data-slot":"tasks-live-now-other-agents",children:M.map(Q=>(0,t.jsx)("span",{title:Q.agentName,className:"-ml-1 rounded-full bg-card ring-2 ring-card first:ml-0",children:(0,t.jsx)(or,{agent:{id:Q.agentId,name:Q.agentName,appearance:Q.agentAppearance},size:20,label:Q.agentName})},Q.agentId))}):null,(0,t.jsx)("time",{dateTime:s.earliestStartedAt??s.latestStartAt,title:"Time since the run started",className:"ml-auto shrink-0 font-mono text-xs tabular-nums text-muted-foreground",children:B})]}),(0,t.jsxs)("span",{"data-slot":"tasks-live-now-health",className:"live-now-health-pill mt-1 inline-flex max-w-full items-center gap-1.5 rounded-full px-2 py-0.5 text-xs font-medium text-foreground",children:[(0,t.jsx)("span",{"aria-hidden":"true",className:"live-now-health-dot size-1.5 shrink-0 rounded-full"}),(0,t.jsx)("span",{className:"truncate",children:A.label})]}),_.modelFallback?(0,t.jsx)(PPt,{adapterType:_.adapterType,fallback:_.modelFallback}):null]})]}),(0,t.jsxs)("div",{className:"mt-3 px-3",children:[i.length>0||o?(0,t.jsxs)("nav",{"aria-label":"Parent tasks","data-slot":"tasks-live-now-path",className:"mb-0.5 flex min-w-0 items-center gap-1 overflow-hidden whitespace-nowrap text-xs text-muted-foreground",children:[o?(0,t.jsx)("span",{"aria-hidden":"true",children:"… ›"}):null,i.map((Q,re)=>(0,t.jsxs)("span",{className:"flex min-w-0 items-center gap-1",children:[re>0?(0,t.jsx)("span",{"aria-hidden":"true",children:"›"}):null,(0,t.jsx)(We,{to:ul(Q.identifier??Q.id),title:Q.title,className:"truncate font-mono text-muted-foreground no-underline hover:text-foreground hover:underline",children:Q.identifier??Q.id.slice(0,8)})]},Q.id)),(0,t.jsx)("span",{"aria-hidden":"true",children:"›"})]}):null,(0,t.jsxs)(We,{to:C,state:S,issuePrefetch:n,disableIssueQuicklook:!0,onClickCapture:S?()=>Sg(N,S):void 0,className:"line-clamp-2 rounded-sm text-sm leading-5 font-medium text-foreground no-underline outline-none hover:underline focus-visible:ring-2 focus-visible:ring-ring",children:[(0,t.jsx)("span",{className:"mr-1.5 font-mono text-xs font-normal text-muted-foreground",children:w}),k]})]}),(0,t.jsx)("blockquote",{"data-slot":"tasks-live-now-snippet",className:"live-now-quote mx-3 mt-2.5 line-clamp-2 min-h-10 border-l-2 pl-2.5 text-sm leading-5 text-muted-foreground",children:P??(U?`Next: ${U}`:A.health==="starting"?"Warming up…":"No message yet")}),(0,t.jsxs)("div",{"data-slot":"tasks-live-now-status",className:"mx-3 mt-2 flex h-5 min-w-0 items-center gap-1.5 text-xs text-muted-foreground",children:[z?(0,t.jsx)(z,{"aria-hidden":"true",className:"size-3.5 shrink-0"}):null,(0,t.jsx)("span",{className:"min-w-0 truncate",children:L?.text??"Waiting for the first event"}),O!==null?(0,t.jsxs)("span",{className:"ml-auto shrink-0 tabular-nums",children:[m8(Math.max(0,c-O))," ago"]}):null]}),p?(0,t.jsx)(MPt,{id:h,issueId:s.issueId,agentName:_.agentName,identifier:w,onSent:r(Q=>{f(!1),j(Q)},"onSent"),onCancel:r(()=>f(!1),"onCancel")}):null,v||K.error?(0,t.jsx)("p",{role:K.error?"alert":"status",className:V("mx-3 mt-2 text-xs",K.error?"text-destructive":"text-muted-foreground"),children:K.error?d5e(K.error,"Couldn’t stop the run."):v}):null,(0,t.jsx)("div",{className:"mt-auto pt-2.5",children:(0,t.jsxs)("div",{className:"flex items-center gap-0.5 border-t border-border px-1.5 py-1.5",children:[(0,t.jsxs)(We,{to:C,state:S,disableIssueQuicklook:!0,"aria-label":`Open ${w}`,className:HE({variant:"ghost",size:"xs"}),children:[(0,t.jsx)(io,{"aria-hidden":"true"}),"Open"]}),(0,t.jsxs)(We,{to:q,"aria-label":`Run transcript for ${_.agentName}`,className:HE({variant:"ghost",size:"xs"}),children:[(0,t.jsx)(jW,{"aria-hidden":"true"}),"Run"]}),(0,t.jsxs)($,{type:"button",variant:"ghost",size:"xs","aria-expanded":p,"aria-controls":p?h:void 0,"aria-label":`Steer ${_.agentName} on ${w}`,onClick:W,children:[(0,t.jsx)(Sp,{"aria-hidden":"true"}),"Steer"]}),(0,t.jsx)(_0e,{className:"ml-auto",issueId:s.issueId,run:_,companyId:e,taskLabel:w}),(0,t.jsxs)($,{type:"button",variant:"ghost",size:"xs",className:"ml-auto text-muted-foreground hover:bg-destructive/10 hover:text-destructive focus-visible:text-destructive",disabled:K.isPending,"aria-label":`Stop ${_.agentName}'s run on ${w}`,onClick:r(()=>b(!0),"onClick"),children:[(0,t.jsx)(Hg,{"aria-hidden":"true",className:"fill-current"}),K.isPending?"Stopping…":"Stop"]})]})}),(0,t.jsx)(Ic,{open:x,onOpenChange:b,children:(0,t.jsxs)(kc,{children:[(0,t.jsxs)(_c,{children:[(0,t.jsxs)(Nc,{children:["Stop ",_.agentName,"'s run?"]}),(0,t.jsxs)(wc,{children:[w," keeps its status and comments. The agent stops mid-turn, so any unsaved work in this run is lost."]})]}),(0,t.jsxs)(Sc,{children:[(0,t.jsx)(Cc,{children:"Keep running"}),(0,t.jsx)(Vc,{className:HE({variant:"destructive"}),onClick:r(()=>{j(null),K.mutate()},"onClick"),children:"Stop run"})]})]})})]})}r(EPt,"LiveNowCard");function PPt({adapterType:e,fallback:s}){const n=mH(e)?.fields.find(a=>a.key==="model")?.options??[];return(0,t.jsxs)("span",{"data-slot":"live-now-model-fallback",title:`${s.activeModel} (primary ${s.primaryModel})`,className:"ml-1.5 mt-1 inline-flex max-w-full items-start gap-1.5 rounded-md border border-amber-500/25 bg-amber-500/10 px-2 py-1 text-left text-xs font-medium leading-snug text-amber-800 dark:text-amber-200",children:[(0,t.jsx)(Rs,{"aria-hidden":"true",className:"mt-0.5 size-3.5 shrink-0 text-amber-500 dark:text-amber-400"}),(0,t.jsxs)("span",{className:"min-w-0 whitespace-normal break-words",children:[Sb(qRt(s.activeModel,n)),(0,t.jsxs)("span",{className:"text-muted-foreground",children:[" · primary: ",s8(s.reason)]})]})]})}r(PPt,"LiveNowModelFallbackPill");function MPt({id:e,issueId:s,agentName:n,identifier:a,onSent:i,onCancel:o}){const l=Nt(),[c,d]=(0,m.useState)(""),u=`${e}-field`,h=ye({mutationFn:r(b=>yt.addComment(s,b,void 0,void 0,void 0,crypto.randomUUID(),"steer"),"mutationFn"),onSuccess:r(b=>{l.invalidateQueries({queryKey:D.issues.comments(s)}),i(eW(b)??(b?.deliveredAs==="steered"?`Steered into ${n}'s turn`:`Sent to ${n}`))},"onSuccess")}),p=c.trim(),f=r(b=>{b?.preventDefault(),!(!p||h.isPending)&&h.mutate(p)},"submit"),x=r(b=>{b.key==="Escape"?(b.preventDefault(),o()):b.key==="Enter"&&!b.shiftKey&&!b.nativeEvent.isComposing&&f(b)},"onKeyDown");return(0,t.jsxs)("form",{id:e,"data-slot":"tasks-live-now-steer",className:"mx-3 mt-3 space-y-2",onSubmit:f,children:[(0,t.jsxs)("label",{htmlFor:u,className:"sr-only",children:["Steer ",n," on ",a]}),(0,t.jsx)(Qn,{id:u,rows:2,autoFocus:!0,value:c,placeholder:`Steer ${n}…`,className:"min-h-14 resize-none text-sm",disabled:h.isPending,onChange:r(b=>d(b.target.value),"onChange"),onKeyDown:x}),h.error?(0,t.jsx)("p",{role:"alert",className:"text-xs text-destructive",children:d5e(h.error,"Couldn’t send the message.")}):null,(0,t.jsxs)("div",{className:"flex items-center justify-end gap-1.5",children:[(0,t.jsx)("span",{className:"mr-auto text-xs text-muted-foreground",children:"Enter to send · Esc to cancel"}),(0,t.jsx)($,{type:"button",variant:"ghost",size:"xs",onClick:o,children:"Cancel"}),(0,t.jsx)($,{type:"submit",size:"xs",disabled:!p||h.isPending,children:h.isPending?"Sending…":"Send"})]})]})}r(MPt,"LiveNowSteerForm");var DPt=3e4,Jle=6,LPt=5,Xle=2;function UB(e){return e.startedAt??e.createdAt}r(UB,"runStartAt");function LR(e){const s=new Date(e).getTime();return Number.isFinite(s)?s:0}r(LR,"timestampMs");function $Pt(e,s){const n=new Map;for(const i of e??[]){if(!i.issueId||!bb(i,s.get(i.issueId)))continue;const o=n.get(i.issueId);o?o.push(i):n.set(i.issueId,[i])}const a=[];for(const[i,o]of n){o.sort((c,d)=>LR(UB(d))-LR(UB(c)));const l=o.filter(c=>c.startedAt!==null);a.push({issueId:i,runs:o,latestStartAt:UB(o[0]),earliestStartedAt:l.length>0?l[l.length-1].startedAt:null})}return a.sort((i,o)=>LR(o.latestStartAt)-LR(i.latestStartAt))}r($Pt,"buildLiveNowEntries");function Zle(e,s,n){const a=[],i=new Set;let o=e?.parentId??null,l=!1;for(;o&&!i.has(o);){i.add(o);const c=s.get(o);if(!c){l=!0;break}a.push({id:c.id,identifier:c.identifier??null,title:c.title}),o=c.parentId??null}return l?n?{ancestors:[...n].reverse().map(({id:c,identifier:d,title:u})=>({id:c,identifier:d,title:u})),complete:!0}:{ancestors:a.reverse(),complete:!1}:{ancestors:a.reverse(),complete:!0}}r(Zle,"resolveLiveNowParentPath");function h8(e){return`paperclip:tasks-live-now:collapsed:${e}`}r(h8,"liveNowCollapsedStorageKey");function OPt(e){try{return window.localStorage.getItem(h8(e))==="true"}catch{return!1}}r(OPt,"readCollapsed");function FPt(e,s){try{s?window.localStorage.setItem(h8(e),"true"):window.localStorage.removeItem(h8(e))}catch{return}}r(FPt,"writeCollapsed");function BPt(e){const s=(0,m.useRef)(!1);return(0,m.useLayoutEffect)(()=>{const n=e.current;if(!n||typeof ResizeObserver>"u")return;const a=Eqe(n),i=a??window,o=r(()=>n.getBoundingClientRect().bottom-(a?a.getBoundingClientRect().top:0),"bottomBelowViewportTop");let l=o();const c=r(()=>{l=o()},"syncBottom"),d=new ResizeObserver(()=>{const u=o(),h=u-l,p=s.current;if(s.current=!1,!p&&h!==0&&l<=0){a?a.scrollTop+=h:window.scrollBy(0,h),c();return}l=u});return i.addEventListener("scroll",c,{passive:!0}),d.observe(n),()=>{d.disconnect(),i.removeEventListener("scroll",c)}},[e]),(0,m.useCallback)(()=>{s.current=!0},[])}r(BPt,"useAboveViewportResizeCompensation");function zPt({companyId:e,liveRuns:s,issues:n,issueLinkState:a}){const i=(0,m.useRef)(null),o=BPt(i),[l,c]=(0,m.useState)(()=>OPt(e)),d=(0,m.useMemo)(()=>new Map(n.map(R=>[R.id,R])),[n]),u=(0,m.useMemo)(()=>{const R=new Set;for(const A of s??[]){if(!A.issueId||R.has(A.issueId)||!bb(A))continue;const T=d.get(A.issueId);(!T||!Zle(T,d).complete)&&R.add(A.issueId)}return[...R]},[s,d]),h=tm({queries:u.map(R=>({queryKey:D.issues.detail(R),queryFn:r(()=>yt.get(R),"queryFn"),staleTime:DPt,retry:!1}))}),{detailById:p,failedIds:f}=(0,m.useMemo)(()=>{const R=new Map,A=new Set;return h.forEach((T,E)=>{const L=u[E];T.data?R.set(L,T.data):T.isError&&A.add(L)}),{detailById:R,failedIds:A}},[u,h]),x=(0,m.useMemo)(()=>{const R=new Map;for(const A of s??[]){if(!A.issueId)continue;const T=d.get(A.issueId)?.status??p.get(A.issueId)?.status;T&&R.set(A.issueId,T)}return $Pt(s,R)},[p,s,d]),b=Date.now();JD(x.length>0&&!l);const[v,j]=(0,m.useState)(!1),N=(0,m.useId)(),w=x.map(R=>{const A=d.get(R.issueId)??p.get(R.issueId)??null;return{entry:R,issue:A,signal:c5e(R.runs.map(T=>l5e(T,b))),identifier:A?.identifier??R.issueId.slice(0,8)}}).sort((R,A)=>+(A.signal.health==="stalled")-+(R.signal.health==="stalled")),k=RPt(w.map(R=>R.signal.health)),S=v?0:Math.max(0,w.length-Jle),C=qPt(w.map(R=>`${R.identifier} ${R.signal.health}`).join(`
522
+ }`})})})]})]}),(0,t.jsxs)("div",{className:"mt-5 flex flex-col items-stretch gap-3 sm:flex-row sm:flex-wrap sm:items-center",children:[(0,t.jsxs)($,{className:"w-full sm:w-auto",disabled:!L||z.isPending,onClick:X,children:[z.isPending?(0,t.jsx)(tt,{className:"mr-2 h-4 w-4 animate-spin"}):null,"Save changes"]}),(0,t.jsx)($,{variant:"outline",className:"w-full sm:w-auto",disabled:!L||z.isPending,onClick:r(()=>{f(E),b(null)},"onClick"),children:"Reset"}),x?(0,t.jsx)("p",{className:"text-sm text-destructive",children:x}):null,!x&&v?(0,t.jsx)("p",{className:"text-sm text-muted-foreground",children:v}):null,!x&&!L?(0,t.jsx)("p",{className:"text-sm text-muted-foreground",children:"No unsaved changes."}):null]})]})}),(0,t.jsxs)("div",{className:"space-y-6",children:[(0,t.jsxs)(sn,{className:"block p-5",children:[(0,t.jsxs)("div",{className:"space-y-1",children:[(0,t.jsx)("div",{className:"text-xs font-medium uppercase tracking-(--tracking-eyebrow) text-muted-foreground",children:"Workspace facts"}),(0,t.jsx)("h2",{className:"text-lg font-semibold",children:"Current state"})]}),(0,t.jsx)(Ul,{className:"my-4"}),(0,t.jsx)($w,{label:"Project",children:(0,t.jsx)(We,{to:`/projects/${T}`,className:"hover:underline",children:R.name})}),(0,t.jsx)($w,{label:"Workspace ID",children:(0,t.jsx)("span",{className:"break-all font-mono text-xs",children:A.id})}),h?null:(0,t.jsx)($w,{label:"Local path",children:(0,t.jsx)("span",{className:"break-all font-mono text-xs",children:A.cwd??"None"})}),(0,t.jsx)($w,{label:"Repo",children:A.repoUrl&&bPt(A.repoUrl)?(0,t.jsxs)("a",{href:A.repoUrl,target:"_blank",rel:"noreferrer",className:"inline-flex items-center gap-1 hover:underline",children:[A.repoUrl,(0,t.jsx)($n,{className:"h-3 w-3"})]}):A.repoUrl?(0,t.jsx)("span",{className:"break-all font-mono text-xs",children:A.repoUrl}):"None"}),(0,t.jsx)($w,{label:"Default ref",children:A.defaultRef??"None"}),(0,t.jsx)($w,{label:"Updated",children:new Date(A.updatedAt).toLocaleString()})]}),(0,t.jsxs)(sn,{className:"block p-5",children:[(0,t.jsx)("div",{className:"flex flex-col gap-3 sm:flex-row sm:items-start sm:justify-between",children:(0,t.jsxs)("div",{className:"space-y-1",children:[(0,t.jsx)("div",{className:"text-xs font-medium uppercase tracking-(--tracking-eyebrow) text-muted-foreground",children:"Workspace commands"}),(0,t.jsx)("h2",{className:"text-lg font-semibold",children:"Services and jobs"}),(0,t.jsx)("p",{className:"text-sm text-muted-foreground",children:"Long-running services stay supervised here, while one-shot jobs run on demand against this workspace. Execution workspaces inherit this config unless they override it."})]})}),(0,t.jsx)(n2e,{className:"mt-4",sections:J,isPending:W.isPending,pendingRequest:ie,serviceEmptyMessage:A.runtimeConfig?.workspaceRuntime?"No services have been started for this workspace yet.":"No workspace command config is defined for this workspace yet.",jobEmptyMessage:"No one-shot jobs are configured for this workspace yet.",disabledHint:"Project workspaces need a working directory before local commands can run, and services also need runtime config.",onAction:r(Z=>W.mutate(Z),"onAction")})]})]})]}):null,u8(k)?G?(0,t.jsx)(am,{slot:G.slot,context:{companyId:R.companyId,companyPrefix:e??null,projectId:R.id,entityId:A.id,entityType:"project_workspace"},missingBehavior:"placeholder"}):P||U?(0,t.jsx)("div",{className:"rounded-lg border border-dashed border-border bg-background px-4 py-8 text-sm text-muted-foreground",children:U||"Loading workspace plugin..."}):(0,t.jsx)(r5e,{defaultTabHref:`${r_(R,w)}?tab=configuration`,defaultTabLabel:"Back to configuration"}):null]})}r(NPt,"ProjectWorkspaceDetail");function kPt(e){return{key:e.key,kind:e.kind,workspaceId:e.workspaceId,workspaceName:e.workspaceName,cwd:e.cwd,branchName:e.branchName,lastUpdatedAt:e.lastUpdatedAt,projectWorkspaceId:e.projectWorkspaceId,executionWorkspaceId:e.executionWorkspaceId,executionWorkspaceStatus:e.executionWorkspaceStatus,serviceCount:e.serviceCount,runningServiceCount:e.runningServiceCount,primaryServiceUrl:e.primaryServiceUrl,primaryServiceUrlRunning:e.primaryServiceUrlRunning,hasRuntimeConfig:e.hasRuntimeConfig,linkedIssueCount:e.linkedIssueCount,issues:e.linkedIssues}}r(kPt,"overviewItemToSummary");function SPt(e){const s=new Map;for(const n of e){const a=s.get(n.projectId),i=kPt(n);if(a){a.summaries.push(i),i.lastUpdatedAt.getTime()>a.lastUpdatedAt.getTime()&&(a.lastUpdatedAt=i.lastUpdatedAt),a.runningServiceCount+=i.runningServiceCount;continue}s.set(n.projectId,{projectId:n.projectId,projectName:n.projectName,projectRef:Ng({id:n.projectId,name:n.projectName,urlKey:n.projectUrlKey}),summaries:[i],lastUpdatedAt:i.lastUpdatedAt,runningServiceCount:i.runningServiceCount})}return[...s.values()].sort((n,a)=>{const i=a.runningServiceCount-n.runningServiceCount;if(i!==0)return i;const o=a.lastUpdatedAt.getTime()-n.lastUpdatedAt.getTime();return o!==0?o:n.projectName.localeCompare(a.projectName)})}r(SPt,"buildProjectWorkspaceGroups");function CPt(){const{selectedCompanyId:e}=ps(),{setBreadcrumbs:s}=Hn(),n=te({queryKey:D.instance.experimentalSettings,queryFn:r(()=>vr.getExperimental(),"queryFn")}),a=n.data?.enableIsolatedWorkspaces===!0,i=Wg({queryKey:e?D.executionWorkspaces.overview(e):["execution-workspaces","__workspaces-overview__","disabled"],queryFn:r(({pageParam:p})=>bc.listOverview(e,{offset:p}),"queryFn"),initialPageParam:0,getNextPageParam:r(p=>p.nextOffset??void 0,"getNextPageParam"),enabled:!!(e&&a)});(0,m.useEffect)(()=>{s([{label:"Workspaces"}])},[s]);const o=i.data?.pages??[],l=(0,m.useMemo)(()=>o.flatMap(p=>p.items),[o]),c=(0,m.useMemo)(()=>SPt(l),[l]),d=(o[0]??null)?.total??l.length,u=i.isLoading,h=i.error;return n.isLoading?(0,t.jsx)(Pa,{variant:"detail"}):a?u?(0,t.jsx)(Pa,{variant:"list"}):h?(0,t.jsx)("p",{className:"text-sm text-destructive",children:h.message}):(0,t.jsxs)("div",{className:"space-y-6",children:[(0,t.jsx)("div",{children:(0,t.jsx)("h2",{className:"text-xl font-bold",children:"Workspaces"})}),(0,t.jsx)(vG,{companyId:e,scopeKind:"workspaces_overview",title:"Workspace summary",description:"Summarizer tracks workspace activity, live services, and follow-up needs across projects."}),c.length===0?(0,t.jsx)("p",{className:"text-sm text-muted-foreground",children:"No workspace activity yet."}):(0,t.jsxs)("div",{className:"space-y-8",children:[c.map(p=>(0,t.jsxs)("section",{className:"space-y-3",children:[(0,t.jsxs)("div",{className:"flex flex-wrap items-end justify-between gap-2",children:[(0,t.jsx)("div",{className:"min-w-0",children:(0,t.jsx)(We,{to:`/projects/${p.projectRef}/workspaces`,className:"text-base font-semibold hover:underline",children:p.projectName})}),(0,t.jsxs)("span",{className:"text-xs text-muted-foreground",children:[p.summaries.length," workspace",p.summaries.length===1?"":"s"]})]}),(0,t.jsx)(C3e,{companyId:e,projectId:p.projectId,projectRef:p.projectRef,summaries:p.summaries})]},p.projectId)),i.hasNextPage?(0,t.jsxs)("div",{className:"flex flex-wrap items-center justify-between gap-3 border-t border-border pt-4",children:[(0,t.jsxs)("p",{className:"text-sm text-muted-foreground",children:["Showing ",l.length," of ",d," workspaces."]}),(0,t.jsx)($,{type:"button",variant:"outline",size:"sm",onClick:r(()=>{i.fetchNextPage()},"onClick"),disabled:i.isFetchingNextPage,children:i.isFetchingNextPage?"Loading...":"Load more"})]}):null]})]}):(0,t.jsx)(An,{to:"/issues",replace:!0})}r(CPt,"Workspaces");var _Pt=6e4,IPt=12e4,APt=9e5,Gle={active:0,thinking:1,starting:2,quiet:3,stalled:4},i5e={starting:"loading",active:"working",thinking:"thinking",quiet:"sleepy",stalled:"confused"};function o5e(e){if(!e)return null;const s=new Date(e).getTime();return Number.isFinite(s)?s:null}r(o5e,"toMs$1");function D3(e){let s=null;for(const n of[e.lastEventAt,e.currentStatusUpdatedAt,e.outputSilence?.lastOutputAt,e.lastUsefulActionAt]){const a=o5e(n);a!==null&&(s===null||a>s)&&(s=a)}return s}r(D3,"lastLiveActivityMs");function m8(e){const s=Math.floor(e/6e4);if(s<1)return`${Math.max(0,Math.floor(e/1e3))}s`;if(s<60)return`${s}m`;const n=Math.floor(s/60),a=s%60;return a>0?`${n}h ${a}m`:`${n}h`}r(m8,"formatSilence");function TPt(e){return!!e.currentToolName&&!/^finished\b/i.test(e.currentStatusMessage??"")}r(TPt,"toolInFlight");function l5e(e,s){const n=o5e(e.startedAt);if(n===null||e.status==="queued"||e.status==="scheduled_retry")return{health:"starting",label:"Queued",silentMs:null};const a=D3(e);if(a===null&&s-n<_Pt)return{health:"starting",label:"Starting",silentMs:null};const i=Math.max(0,s-(a??n)),o=e.outputSilence?.level,l=e.outputSilence?.criticalThresholdMs||APt;return o==="critical"||o!=="snoozed"&&i>=l?{health:"stalled",label:`Stalled ${m8(i)}`,silentMs:i}:o==="suspicious"||i>=IPt?{health:"quiet",label:`Quiet ${m8(i)}`,silentMs:i}:TPt(e)?{health:"active",label:"Working",silentMs:i}:{health:"thinking",label:"Thinking",silentMs:i}}r(l5e,"classifyLiveNowHealth");function c5e(e){return e.reduce((s,n)=>Gle[n.health]>Gle[s.health]?n:s)}r(c5e,"mostSevereSignal");function RPt(e){const s={working:0,quiet:0,stalled:0};for(const n of e)n==="quiet"?s.quiet+=1:n==="stalled"?s.stalled+=1:s.working+=1;return s}r(RPt,"countLiveNowHealth");function Yle(e){const s=e.currentToolName?.trim()||null,n=(e.currentStatusMessage?.trim()||null)??(s?Gk(s).verbLabel:null);return n?{icon:s?Gk(s).icon:AIe(n)??Gd,text:n}:null}r(Yle,"describeLiveActivity");function d5e(e,s){return e instanceof Error&&e.message?e.message:s}r(d5e,"errorMessage");function EPt({companyId:e,entry:s,issue:n,loadFailed:a,ancestors:i,truncatedAncestors:o,issueLinkState:l,now:c,hiddenOnWide:d=!1}){const u=Nt(),h=(0,m.useId)(),[p,f]=(0,m.useState)(!1),[x,b]=(0,m.useState)(!1),[v,j]=(0,m.useState)(null),N=n?.identifier??s.issueId,w=n?.identifier??s.issueId.slice(0,8),k=n?.title??(a?"Task unavailable":"Loading task…"),S=n?kg(l,n):void 0,C=ul(N),_=s.runs[0],R=s.runs.map(Q=>l5e(Q,c)),A=c5e(R),T=R[0],E=s.runs.reduce((Q,re)=>(D3(re)??0)>(D3(Q)??0)?re:Q,_),L=Yle(E)??s.runs.map(Yle).find(Boolean)??null,O=D3(E),P=s.runs.find(Q=>Q.lastAssistantSnippet?.trim())?.lastAssistantSnippet?.trim()??null,U=s.runs.find(Q=>Q.nextAction?.trim())?.nextAction?.trim()??null,M=[...new Map(s.runs.slice(1).filter(Q=>Q.agentId!==_.agentId).map(Q=>[Q.agentId,Q])).values()],B=s.earliestStartedAt?Fq(Math.max(0,c-new Date(s.earliestStartedAt).getTime())):"Queued",q=`/agents/${_.agentId}/runs/${_.id}`,z=L?.icon??null,K=ye({mutationFn:r(()=>Xr.cancel(_.id),"mutationFn"),onSuccess:r(()=>{j(`Stopping ${_.agentName}'s run`),u.invalidateQueries({queryKey:D.liveRuns(e)}),u.invalidateQueries({queryKey:D.issues.liveRuns(s.issueId)}),u.invalidateQueries({queryKey:D.issues.activeRun(s.issueId)}),u.invalidateQueries({queryKey:D.issues.runs(s.issueId)})},"onSuccess")}),W=r(()=>{j(null),f(Q=>!Q)},"openComposer");return(0,t.jsxs)("li",{"data-live-now-issue-id":s.issueId,"data-live-health":A.health,className:V("live-now-card relative flex w-(--live-now-card-peek) shrink-0 snap-start flex-col overflow-hidden rounded-xl border border-border bg-card text-card-foreground sm:w-auto",d&&"sm:hidden"),children:[A.health==="active"||A.health==="starting"?(0,t.jsx)("span",{"aria-hidden":"true",className:"live-now-sweep"}):null,(0,t.jsxs)("div",{className:"flex items-start gap-3 px-3 pt-3",children:[(0,t.jsxs)("span",{className:"relative shrink-0",children:[(0,t.jsx)(or,{agent:{id:_.agentId,name:_.agentName,appearance:_.agentAppearance,avatarUrl:_.avatarUrl},size:40,pose:i5e[T.health]}),(0,t.jsx)("span",{"aria-hidden":"true",className:V("live-now-health-dot absolute right-0 bottom-0 size-2.5 rounded-full ring-2 ring-card",(A.health==="active"||A.health==="thinking")&&"live-now-breathe")})]}),(0,t.jsxs)("div",{className:"min-w-0 flex-1",children:[(0,t.jsxs)("div",{className:"flex min-w-0 items-center gap-2",children:[(0,t.jsx)("span",{title:_.agentName,className:"truncate text-sm font-semibold",children:_.agentName}),M.length>0?(0,t.jsx)("span",{className:"flex shrink-0 items-center","data-slot":"tasks-live-now-other-agents",children:M.map(Q=>(0,t.jsx)("span",{title:Q.agentName,className:"-ml-1 rounded-full bg-card ring-2 ring-card first:ml-0",children:(0,t.jsx)(or,{agent:{id:Q.agentId,name:Q.agentName,appearance:Q.agentAppearance},size:20,label:Q.agentName})},Q.agentId))}):null,(0,t.jsx)("time",{dateTime:s.earliestStartedAt??s.latestStartAt,title:"Time since the run started",className:"ml-auto shrink-0 font-mono text-xs tabular-nums text-muted-foreground",children:B})]}),(0,t.jsxs)("span",{"data-slot":"tasks-live-now-health",className:"live-now-health-pill mt-1 inline-flex max-w-full items-center gap-1.5 rounded-full px-2 py-0.5 text-xs font-medium text-foreground",children:[(0,t.jsx)("span",{"aria-hidden":"true",className:"live-now-health-dot size-1.5 shrink-0 rounded-full"}),(0,t.jsx)("span",{className:"truncate",children:A.label})]}),_.modelFallback?(0,t.jsx)(PPt,{adapterType:_.adapterType,fallback:_.modelFallback}):null]})]}),(0,t.jsxs)("div",{className:"mt-3 px-3",children:[i.length>0||o?(0,t.jsxs)("nav",{"aria-label":"Parent tasks","data-slot":"tasks-live-now-path",className:"mb-0.5 flex min-w-0 items-center gap-1 overflow-hidden whitespace-nowrap text-xs text-muted-foreground",children:[o?(0,t.jsx)("span",{"aria-hidden":"true",children:"… ›"}):null,i.map((Q,re)=>(0,t.jsxs)("span",{className:"flex min-w-0 items-center gap-1",children:[re>0?(0,t.jsx)("span",{"aria-hidden":"true",children:"›"}):null,(0,t.jsx)(We,{to:ul(Q.identifier??Q.id),title:Q.title,className:"truncate font-mono text-muted-foreground no-underline hover:text-foreground hover:underline",children:Q.identifier??Q.id.slice(0,8)})]},Q.id)),(0,t.jsx)("span",{"aria-hidden":"true",children:"›"})]}):null,(0,t.jsxs)(We,{to:C,state:S,issuePrefetch:n,disableIssueQuicklook:!0,onClickCapture:S?()=>Sg(N,S):void 0,className:"line-clamp-2 rounded-sm text-sm leading-5 font-medium text-foreground no-underline outline-none hover:underline focus-visible:ring-2 focus-visible:ring-ring",children:[(0,t.jsx)("span",{className:"mr-1.5 font-mono text-xs font-normal text-muted-foreground",children:w}),k]})]}),(0,t.jsx)("blockquote",{"data-slot":"tasks-live-now-snippet",className:"live-now-quote mx-3 mt-2.5 line-clamp-2 min-h-10 border-l-2 pl-2.5 text-sm leading-5 text-muted-foreground",children:P??(U?`Next: ${U}`:A.health==="starting"?"Warming up…":"No message yet")}),(0,t.jsxs)("div",{"data-slot":"tasks-live-now-status",className:"mx-3 mt-2 flex h-5 min-w-0 items-center gap-1.5 text-xs text-muted-foreground",children:[z?(0,t.jsx)(z,{"aria-hidden":"true",className:"size-3.5 shrink-0"}):null,(0,t.jsx)("span",{className:"min-w-0 truncate",children:L?.text??"Waiting for the first event"}),O!==null?(0,t.jsxs)("span",{className:"ml-auto shrink-0 tabular-nums",children:[m8(Math.max(0,c-O))," ago"]}):null]}),p?(0,t.jsx)(MPt,{id:h,issueId:s.issueId,agentName:_.agentName,identifier:w,onSent:r(Q=>{f(!1),j(Q)},"onSent"),onCancel:r(()=>f(!1),"onCancel")}):null,v||K.error?(0,t.jsx)("p",{role:K.error?"alert":"status",className:V("mx-3 mt-2 text-xs",K.error?"text-destructive":"text-muted-foreground"),children:K.error?d5e(K.error,"Couldn’t stop the run."):v}):null,(0,t.jsx)("div",{className:"mt-auto pt-2.5",children:(0,t.jsxs)("div",{className:"flex flex-wrap items-center gap-0.5 border-t border-border px-1.5 py-1.5",children:[(0,t.jsxs)(We,{to:C,state:S,disableIssueQuicklook:!0,"aria-label":`Open ${w}`,className:HE({variant:"ghost",size:"xs"}),children:[(0,t.jsx)(io,{"aria-hidden":"true"}),"Open"]}),(0,t.jsxs)(We,{to:q,"aria-label":`Run transcript for ${_.agentName}`,className:HE({variant:"ghost",size:"xs"}),children:[(0,t.jsx)(jW,{"aria-hidden":"true"}),"Run"]}),(0,t.jsxs)($,{type:"button",variant:"ghost",size:"xs","aria-expanded":p,"aria-controls":p?h:void 0,"aria-label":`Steer ${_.agentName} on ${w}`,onClick:W,children:[(0,t.jsx)(Sp,{"aria-hidden":"true"}),"Steer"]}),(0,t.jsx)(_0e,{className:"ml-auto",issueId:s.issueId,run:_,companyId:e,taskLabel:w}),(0,t.jsxs)($,{type:"button",variant:"ghost",size:"xs",className:"ml-auto text-muted-foreground hover:bg-destructive/10 hover:text-destructive focus-visible:text-destructive",disabled:K.isPending,"aria-label":`Stop ${_.agentName}'s run on ${w}`,onClick:r(()=>b(!0),"onClick"),children:[(0,t.jsx)(Hg,{"aria-hidden":"true",className:"fill-current"}),K.isPending?"Stopping…":"Stop"]})]})}),(0,t.jsx)(Ic,{open:x,onOpenChange:b,children:(0,t.jsxs)(kc,{children:[(0,t.jsxs)(_c,{children:[(0,t.jsxs)(Nc,{children:["Stop ",_.agentName,"'s run?"]}),(0,t.jsxs)(wc,{children:[w," keeps its status and comments. The agent stops mid-turn, so any unsaved work in this run is lost."]})]}),(0,t.jsxs)(Sc,{children:[(0,t.jsx)(Cc,{children:"Keep running"}),(0,t.jsx)(Vc,{className:HE({variant:"destructive"}),onClick:r(()=>{j(null),K.mutate()},"onClick"),children:"Stop run"})]})]})})]})}r(EPt,"LiveNowCard");function PPt({adapterType:e,fallback:s}){const n=mH(e)?.fields.find(a=>a.key==="model")?.options??[];return(0,t.jsxs)("span",{"data-slot":"live-now-model-fallback",title:`${s.activeModel} (primary ${s.primaryModel})`,className:"ml-1.5 mt-1 inline-flex max-w-full items-start gap-1.5 rounded-md border border-amber-500/25 bg-amber-500/10 px-2 py-1 text-left text-xs font-medium leading-snug text-amber-800 dark:text-amber-200",children:[(0,t.jsx)(Rs,{"aria-hidden":"true",className:"mt-0.5 size-3.5 shrink-0 text-amber-500 dark:text-amber-400"}),(0,t.jsxs)("span",{className:"min-w-0 whitespace-normal break-words",children:[Sb(qRt(s.activeModel,n)),(0,t.jsxs)("span",{className:"text-muted-foreground",children:[" · primary: ",s8(s.reason)]})]})]})}r(PPt,"LiveNowModelFallbackPill");function MPt({id:e,issueId:s,agentName:n,identifier:a,onSent:i,onCancel:o}){const l=Nt(),[c,d]=(0,m.useState)(""),u=`${e}-field`,h=ye({mutationFn:r(b=>yt.addComment(s,b,void 0,void 0,void 0,crypto.randomUUID(),"steer"),"mutationFn"),onSuccess:r(b=>{l.invalidateQueries({queryKey:D.issues.comments(s)}),i(eW(b)??(b?.deliveredAs==="steered"?`Steered into ${n}'s turn`:`Sent to ${n}`))},"onSuccess")}),p=c.trim(),f=r(b=>{b?.preventDefault(),!(!p||h.isPending)&&h.mutate(p)},"submit"),x=r(b=>{b.key==="Escape"?(b.preventDefault(),o()):b.key==="Enter"&&!b.shiftKey&&!b.nativeEvent.isComposing&&f(b)},"onKeyDown");return(0,t.jsxs)("form",{id:e,"data-slot":"tasks-live-now-steer",className:"mx-3 mt-3 space-y-2",onSubmit:f,children:[(0,t.jsxs)("label",{htmlFor:u,className:"sr-only",children:["Steer ",n," on ",a]}),(0,t.jsx)(Qn,{id:u,rows:2,autoFocus:!0,value:c,placeholder:`Steer ${n}…`,className:"min-h-14 resize-none text-sm",disabled:h.isPending,onChange:r(b=>d(b.target.value),"onChange"),onKeyDown:x}),h.error?(0,t.jsx)("p",{role:"alert",className:"text-xs text-destructive",children:d5e(h.error,"Couldn’t send the message.")}):null,(0,t.jsxs)("div",{className:"flex items-center justify-end gap-1.5",children:[(0,t.jsx)("span",{className:"mr-auto text-xs text-muted-foreground",children:"Enter to send · Esc to cancel"}),(0,t.jsx)($,{type:"button",variant:"ghost",size:"xs",onClick:o,children:"Cancel"}),(0,t.jsx)($,{type:"submit",size:"xs",disabled:!p||h.isPending,children:h.isPending?"Sending…":"Send"})]})]})}r(MPt,"LiveNowSteerForm");var DPt=3e4,Jle=6,LPt=5,Xle=2;function UB(e){return e.startedAt??e.createdAt}r(UB,"runStartAt");function LR(e){const s=new Date(e).getTime();return Number.isFinite(s)?s:0}r(LR,"timestampMs");function $Pt(e,s){const n=new Map;for(const i of e??[]){if(!i.issueId||!bb(i,s.get(i.issueId)))continue;const o=n.get(i.issueId);o?o.push(i):n.set(i.issueId,[i])}const a=[];for(const[i,o]of n){o.sort((c,d)=>LR(UB(d))-LR(UB(c)));const l=o.filter(c=>c.startedAt!==null);a.push({issueId:i,runs:o,latestStartAt:UB(o[0]),earliestStartedAt:l.length>0?l[l.length-1].startedAt:null})}return a.sort((i,o)=>LR(o.latestStartAt)-LR(i.latestStartAt))}r($Pt,"buildLiveNowEntries");function Zle(e,s,n){const a=[],i=new Set;let o=e?.parentId??null,l=!1;for(;o&&!i.has(o);){i.add(o);const c=s.get(o);if(!c){l=!0;break}a.push({id:c.id,identifier:c.identifier??null,title:c.title}),o=c.parentId??null}return l?n?{ancestors:[...n].reverse().map(({id:c,identifier:d,title:u})=>({id:c,identifier:d,title:u})),complete:!0}:{ancestors:a.reverse(),complete:!1}:{ancestors:a.reverse(),complete:!0}}r(Zle,"resolveLiveNowParentPath");function h8(e){return`paperclip:tasks-live-now:collapsed:${e}`}r(h8,"liveNowCollapsedStorageKey");function OPt(e){try{return window.localStorage.getItem(h8(e))==="true"}catch{return!1}}r(OPt,"readCollapsed");function FPt(e,s){try{s?window.localStorage.setItem(h8(e),"true"):window.localStorage.removeItem(h8(e))}catch{return}}r(FPt,"writeCollapsed");function BPt(e){const s=(0,m.useRef)(!1);return(0,m.useLayoutEffect)(()=>{const n=e.current;if(!n||typeof ResizeObserver>"u")return;const a=Eqe(n),i=a??window,o=r(()=>n.getBoundingClientRect().bottom-(a?a.getBoundingClientRect().top:0),"bottomBelowViewportTop");let l=o();const c=r(()=>{l=o()},"syncBottom"),d=new ResizeObserver(()=>{const u=o(),h=u-l,p=s.current;if(s.current=!1,!p&&h!==0&&l<=0){a?a.scrollTop+=h:window.scrollBy(0,h),c();return}l=u});return i.addEventListener("scroll",c,{passive:!0}),d.observe(n),()=>{d.disconnect(),i.removeEventListener("scroll",c)}},[e]),(0,m.useCallback)(()=>{s.current=!0},[])}r(BPt,"useAboveViewportResizeCompensation");function zPt({companyId:e,liveRuns:s,issues:n,issueLinkState:a}){const i=(0,m.useRef)(null),o=BPt(i),[l,c]=(0,m.useState)(()=>OPt(e)),d=(0,m.useMemo)(()=>new Map(n.map(R=>[R.id,R])),[n]),u=(0,m.useMemo)(()=>{const R=new Set;for(const A of s??[]){if(!A.issueId||R.has(A.issueId)||!bb(A))continue;const T=d.get(A.issueId);(!T||!Zle(T,d).complete)&&R.add(A.issueId)}return[...R]},[s,d]),h=tm({queries:u.map(R=>({queryKey:D.issues.detail(R),queryFn:r(()=>yt.get(R),"queryFn"),staleTime:DPt,retry:!1}))}),{detailById:p,failedIds:f}=(0,m.useMemo)(()=>{const R=new Map,A=new Set;return h.forEach((T,E)=>{const L=u[E];T.data?R.set(L,T.data):T.isError&&A.add(L)}),{detailById:R,failedIds:A}},[u,h]),x=(0,m.useMemo)(()=>{const R=new Map;for(const A of s??[]){if(!A.issueId)continue;const T=d.get(A.issueId)?.status??p.get(A.issueId)?.status;T&&R.set(A.issueId,T)}return $Pt(s,R)},[p,s,d]),b=Date.now();JD(x.length>0&&!l);const[v,j]=(0,m.useState)(!1),N=(0,m.useId)(),w=x.map(R=>{const A=d.get(R.issueId)??p.get(R.issueId)??null;return{entry:R,issue:A,signal:c5e(R.runs.map(T=>l5e(T,b))),identifier:A?.identifier??R.issueId.slice(0,8)}}).sort((R,A)=>+(A.signal.health==="stalled")-+(R.signal.health==="stalled")),k=RPt(w.map(R=>R.signal.health)),S=v?0:Math.max(0,w.length-Jle),C=qPt(w.map(R=>`${R.identifier} ${R.signal.health}`).join(`
523
523
  `)),_=r(()=>{const R=!l;o(),c(R),FPt(e,R)},"toggle");return(0,t.jsx)("div",{ref:i,"data-slot":"tasks-live-now",children:w.length>0?(0,t.jsxs)("section",{"aria-label":"Live now",className:"pb-4",children:[(0,t.jsxs)("button",{type:"button",className:V("flex w-full min-w-0 flex-wrap items-center gap-x-2 gap-y-1 rounded-xl border py-1.5 pl-1.5 pr-3 text-left outline-none hover:bg-accent/40 focus-visible:ring-2 focus-visible:ring-ring",l?"border-border bg-card":"border-transparent"),"aria-expanded":!l,"aria-controls":l?void 0:N,onClick:_,children:[(0,t.jsx)("span",{className:"inline-flex w-4 shrink-0 items-center justify-center",children:(0,t.jsx)(Pn,{className:V("h-3.5 w-3.5 shrink-0 text-muted-foreground transition-transform",!l&&"rotate-90")})}),(0,t.jsx)(jqe,{}),(0,t.jsx)("span",{className:"shrink-0 text-sm font-semibold uppercase tracking-wide",children:"Live now"}),(0,t.jsx)("span",{"data-slot":"tasks-live-now-count",className:"text-xs tabular-nums text-muted-foreground",children:w.length}),l?(0,t.jsx)(KPt,{cards:w}):null,(0,t.jsx)(UPt,{counts:k})]}),l?null:(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)("ul",{id:N,className:"scrollbar-none mt-2 flex snap-x snap-mandatory gap-3 overflow-x-auto pb-1 sm:grid sm:grid-cols-2 sm:overflow-visible sm:pb-0 xl:grid-cols-3",children:w.map(({entry:R,issue:A},T)=>{const{ancestors:E,complete:L}=Zle(A,d,p.get(R.issueId)?.ancestors??null),O=E.slice(-3);return(0,t.jsx)(EPt,{companyId:e,entry:R,issue:A,loadFailed:f.has(R.issueId),ancestors:O,truncatedAncestors:!L||E.length>O.length,issueLinkState:a,now:b,hiddenOnWide:T>=w.length-S},R.issueId)})}),w.length>Jle?(0,t.jsx)("button",{type:"button",className:"mt-2 hidden rounded-md px-2 py-1 text-xs text-muted-foreground outline-none hover:bg-accent/40 hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring sm:inline-flex","aria-controls":N,onClick:r(()=>j(R=>!R),"onClick"),children:v?"Show fewer":`Show ${S} more`}):null]}),(0,t.jsx)("p",{role:"status","aria-live":"polite",className:"sr-only","data-slot":"tasks-live-now-announcer",children:C})]}):null})}r(zPt,"TasksLiveNowSection");function qPt(e){const s=(0,m.useRef)(null),[n,a]=(0,m.useState)("");return(0,m.useEffect)(()=>{const i=new Map;for(const c of e?e.split(`
524
524
  `):[]){const[d,u]=c.split(" ");i.set(d,u)}const o=s.current;if(s.current=i,!o)return;const l=[];for(const[c,d]of i){const u=o.get(c);!u||u===d||(d==="stalled"||d==="quiet"?l.push(`${c} is ${d}`):(u==="stalled"||u==="quiet")&&l.push(`${c} is working again`))}l.length>0&&a(l.join(". "))},[e]),n}r(qPt,"useHealthAnnouncement");function UPt({counts:e}){const s=[{health:"stalled",count:e.stalled,text:"stalled"},{health:"quiet",count:e.quiet,text:"quiet"},{health:"active",count:e.working,text:"working"}].filter(a=>a.count>0),n=s.map(a=>`${a.count} ${a.text}`).join(", ");return(0,t.jsxs)("span",{"data-slot":"tasks-live-now-summary",className:"ml-auto flex shrink-0 items-center gap-2 text-xs text-muted-foreground sm:gap-3",children:[(0,t.jsx)("span",{className:"sr-only",children:n}),s.map(a=>(0,t.jsxs)("span",{"aria-hidden":"true","data-live-health":a.health,className:V("items-center gap-1.5 tabular-nums",a.health==="active"?"hidden sm:inline-flex":"inline-flex"),children:[(0,t.jsx)("span",{"aria-hidden":"true",className:"live-now-health-dot size-1.5 rounded-full"}),a.count," ",a.text]},a.health))]})}r(UPt,"LiveNowHealthSummary");function KPt({cards:e}){const s=new Map;for(const l of e)for(const c of l.entry.runs)s.has(c.agentId)||s.set(c.agentId,{run:c,health:l.signal.health});const n=[...s.values()],a=n.slice(0,LPt),i=n.length-a.length,o=n.length-Math.min(n.length,Xle);return(0,t.jsxs)("span",{"data-slot":"tasks-live-now-avatars",className:"flex shrink-0 items-center pl-1",children:[a.map(({run:l,health:c},d)=>(0,t.jsx)("span",{title:l.agentName,className:V("-ml-1.5 inline-flex rounded-full bg-card ring-2 ring-card first:ml-0",d>=Xle&&"hidden sm:inline-flex"),children:(0,t.jsx)(or,{agent:{id:l.agentId,name:l.agentName,appearance:l.agentAppearance},size:24,pose:i5e[c]})},l.agentId)),o>0?(0,t.jsxs)("span",{"aria-hidden":"true",className:"ml-1 text-xs tabular-nums text-muted-foreground sm:hidden",children:["+",o]}):null,i>0?(0,t.jsxs)("span",{"aria-hidden":"true",className:"ml-1 hidden text-xs tabular-nums text-muted-foreground sm:inline",children:["+",i]}):null,(0,t.jsx)("span",{className:"sr-only",children:n.map(({run:l})=>l.agentName).join(", ")})]})}r(KPt,"LiveNowAvatarStrip");function WPt({value:e,onChange:s,badgeCount:n}){const a=Hge(e);return(0,t.jsxs)(Zr,{children:[(0,t.jsx)(ta,{asChild:!0,children:(0,t.jsxs)($,{size:"sm",variant:"outline",className:"h-8 gap-1.5","aria-label":`Change view — currently ${a.label}`,children:[(0,t.jsx)("span",{className:"max-w-(--sz-160px) truncate font-medium",children:a.label}),(0,t.jsx)(nn,{"aria-hidden":"true",className:"h-3.5 w-3.5 text-muted-foreground"})]})}),(0,t.jsx)(ea,{align:"start",className:"w-(--sz-260px)",children:dze.map((i,o)=>(0,t.jsxs)("div",{children:[o>0?(0,t.jsx)(ni,{}):null,(0,t.jsxs)(Fb,{className:"flex items-center justify-between gap-2",children:[(0,t.jsx)("span",{children:i.label}),o===0&&n!=null&&n>0?(0,t.jsx)("span",{className:"rounded-full bg-primary px-1.5 text-(length:--text-nano) leading-tight text-primary-foreground",children:n>99?"99+":n}):null]}),i.views.map(l=>{const c=l.key===e;return(0,t.jsxs)(ds,{onSelect:r(()=>s(l.key),"onSelect"),className:"items-start gap-2","aria-current":c?"true":void 0,children:[(0,t.jsx)(us,{"aria-hidden":"true",className:V("mt-0.5 size-3.5 shrink-0",c?"opacity-100":"opacity-0")}),(0,t.jsxs)("span",{className:"min-w-0",children:[(0,t.jsx)("span",{className:V("block truncate",c&&"font-medium"),children:l.label}),(0,t.jsx)("span",{className:"block text-(length:--text-nano) text-muted-foreground",children:l.hint})]})]},l.key)})]},i.label))})]})}r(WPt,"TaskViewsMenu");var VPt={pending_board_decision:"needs_decision",pending_user_decision:"needs_decision",missing_successful_run_disposition:"needs_decision",blocked_chain_stalled:"stalled",blocked_by_unassigned_issue:"needs_attention",blocked_by_assigned_backlog_issue:"needs_attention",blocked_by_cancelled_issue:"needs_attention",in_review_without_action_path:"needs_attention",invalid_review_participant:"needs_attention",open_recovery_issue:"recovery_required",external_owner_action:"external_wait",blocked_by_uninvokable_assignee:"owner_paused"},HPt=["needs_decision","stalled","needs_attention","recovery_required","external_wait","owner_paused"],u5e={needs_decision:"Needs decision",stalled:"Blocked chain stalled",needs_attention:"Needs attention",recovery_required:"Recovery required",external_wait:"External wait",owner_paused:"Owner paused"},QPt={pending_board_decision:"Pending board decision",pending_user_decision:"Pending user decision",missing_successful_run_disposition:"Pick disposition",blocked_chain_stalled:"Blocked chain stalled",blocked_by_unassigned_issue:"Unassigned blocker",blocked_by_assigned_backlog_issue:"Parked blocker",blocked_by_cancelled_issue:"Cancelled blocker",in_review_without_action_path:"Review without action path",invalid_review_participant:"Invalid review participant",open_recovery_issue:"Recovery in progress",external_owner_action:"External owner action",blocked_by_uninvokable_assignee:"Owner paused"},GPt={critical:0,high:1,medium:2,low:3};function m5e(e){return VPt[e]??"needs_attention"}r(m5e,"blockedReasonVariant");function YPt(e){return QPt[e]??"Stopped"}r(YPt,"blockedReasonLabel");function JPt(e){return u5e[e]}r(JPt,"blockedVariantLabel");function LM(e){return GPt[e]??9}r(LM,"blockedSeverityRank");function ece(e,s){const n=LM(e.severity)-LM(s.severity);if(n!==0)return n;const a=(e.stoppedSinceAt?new Date(e.stoppedSinceAt).getTime():Number.POSITIVE_INFINITY)-(s.stoppedSinceAt?new Date(s.stoppedSinceAt).getTime():Number.POSITIVE_INFINITY);return Number.isFinite(a)?a:0}r(ece,"compareBlockedAttention");var h5e=[["blocker_type","Blocker type"],["none","None"]],p5e=[["urgency","Most urgent"],["most_recent","Most recent"],["longest_stopped","Longest stopped"]];function XPt(e){const s=[];for(const n of e){const a=n.blockedInboxAttention;a&&s.push({issue:n,attention:a,variant:m5e(a.reason),reasonLabel:YPt(a.reason),stoppedAtMs:a.stoppedSinceAt?new Date(a.stoppedSinceAt).getTime():null})}return s}r(XPt,"buildBlockedInboxRows");function ZPt(e){if(!e)return null;const s=new Date(e).getTime();return Number.isFinite(s)?s:null}r(ZPt,"issueTimestampMs");function $R(e){return e.stoppedAtMs??ZPt(e.issue.updatedAt)??0}r($R,"blockedRowRecencyMs");function KB(e,s){const n=e.issue.title.localeCompare(s.issue.title);return n!==0?n:e.issue.id.localeCompare(s.issue.id)}r(KB,"compareBlockedRowsByTitle");function eMt(e,s,n="urgency"){if(n==="most_recent"){const o=$R(s)-$R(e);if(o!==0)return o;const l=ece(e.attention,s.attention);return l!==0?l:KB(e,s)}if(n==="longest_stopped"){const o=(e.stoppedAtMs??Number.POSITIVE_INFINITY)-(s.stoppedAtMs??Number.POSITIVE_INFINITY);if(o!==0)return o;const l=LM(e.attention.severity)-LM(s.attention.severity);return l!==0?l:KB(e,s)}const a=ece(e.attention,s.attention);if(a!==0)return a;const i=$R(s)-$R(e);return i!==0?i:KB(e,s)}r(eMt,"compareBlockedRows");function f5e(e,s="urgency"){return[...e].sort((n,a)=>eMt(n,a,s))}r(f5e,"sortBlockedInboxRows");function tMt(e,s="urgency"){const n=new Map;for(const i of e){const o=n.get(i.variant)??[];o.push(i),n.set(i.variant,o)}const a=[];for(const i of HPt){const o=n.get(i);if(!o||o.length===0)continue;const l=f5e(o,s);a.push({variant:i,label:u5e[i],rows:l})}return a}r(tMt,"groupBlockedInboxRows");function sMt(e,s){const n=s.trim().toLowerCase();return n?[e.issue.title,e.issue.identifier??"",e.attention.owner.label??"",e.attention.action.label,e.attention.action.detail??"",e.reasonLabel,e.attention.leafIssue?.identifier??"",e.attention.leafIssue?.title??"",e.attention.recoveryIssue?.identifier??"",e.attention.recoveryIssue?.title??""].join(" ").toLowerCase().includes(n):!0}r(sMt,"blockedRowMatchesSearch");function nMt(e,s=Date.now()){if(!e)return"stopped";const n=new Date(e).getTime();if(!Number.isFinite(n))return"stopped";const a=Math.max(0,Math.round((s-n)/1e3));return a<60?"stopped just now":a<3600?`stopped ${Math.floor(a/60)}m`:a<86400?`stopped ${Math.floor(a/3600)}h`:a<604800?`stopped ${Math.floor(a/86400)}d`:a<2592e3?`stopped ${Math.floor(a/604800)}w`:`stopped ${Math.floor(a/2592e3)}mo`}r(nMt,"formatStoppedAge");function tce(e){return typeof e!="number"||!Number.isFinite(e)?0:Math.max(0,Math.trunc(e))}r(tce,"normalizeLiveDescendantCount");function rMt(e){if(!e||typeof e!="object")return null;const s=e;return typeof s.state=="string"?s:null}r(rMt,"asBlockerAttention");function yG(e,s=0){return Math.max(tce(e.liveDescendantCount),tce(s))}r(yG,"resolveIssueLiveDescendantCount");function jG(e,s){const n=rMt(e.blockerAttention);if(e.status!=="blocked"||s.isLive||n?.state==="needs_attention"||n?.state==="stalled"||n?.state==="covered")return n;const a=yG(e,s.loadedSubtreeLiveCount);return a<=0?n:{state:"covered",reason:"active_child",unresolvedBlockerCount:n?.unresolvedBlockerCount??0,coveredBlockerCount:a,stalledBlockerCount:n?.stalledBlockerCount??0,attentionBlockerCount:n?.attentionBlockerCount??0,sampleBlockerIdentifier:n?.sampleBlockerIdentifier??null,sampleStalledBlockerIdentifier:n?.sampleStalledBlockerIdentifier??null}}r(jG,"resolveInboxIssueBlockerAttention");var aMt={needs_decision:"border-violet-300/70 bg-violet-50 text-violet-800 dark:border-violet-500/30 dark:bg-violet-500/10 dark:text-violet-300",recovery_required:"border-cyan-300/70 bg-cyan-50 text-cyan-800 dark:border-cyan-500/30 dark:bg-cyan-500/10 dark:text-cyan-300",stalled:"border-amber-400/70 bg-amber-100 text-amber-900 dark:border-amber-500/40 dark:bg-amber-500/15 dark:text-amber-200",needs_attention:"border-amber-300/70 bg-amber-50 text-amber-800 dark:border-amber-500/40 dark:bg-amber-500/10 dark:text-amber-300",external_wait:"border-slate-300 bg-slate-50 text-slate-700 dark:border-slate-500/30 dark:bg-slate-500/15 dark:text-slate-300",owner_paused:"border-red-300/70 bg-red-50 text-red-800 dark:border-red-500/30 dark:bg-red-500/10 dark:text-red-300"},iMt={needs_decision:ko,recovery_required:Jf,stalled:Rs,needs_attention:Rs,external_wait:cd,owner_paused:Kh},oMt={critical:"bg-red-500",high:"bg-orange-500"};function sce({reason:e,severity:s,compact:n=!1,className:a}){const i=m5e(e),o=JPt(i),l=iMt[i],c=oMt[s];return(0,t.jsxs)("span",{"data-testid":"blocked-reason-chip","data-variant":i,"data-severity":s,"aria-label":`Reason: ${o}, severity ${s}`,className:V("inline-flex shrink-0 items-center gap-1 rounded-md border px-2 py-0.5 text-(length:--text-nano) font-medium leading-tight sm:text-(length:--text-micro)",aMt[i],a),children:[c?(0,t.jsx)("span",{"aria-hidden":"true",className:V("inline-block h-1.5 w-1.5 shrink-0 rounded-full",c)}):null,n?null:(0,t.jsx)(l,{className:"h-3 w-3 shrink-0","aria-hidden":"true"}),(0,t.jsx)("span",{className:"truncate",children:o})]})}r(sce,"BlockedReasonChip");var lMt=200;function x5e({companyId:e,searchQuery:s,agentNameById:n,agents:a,userLabelById:i,issueLinkState:o,groupBy:l,sortBy:c,issueFilters:d,currentUserId:u,liveIssueIds:h,subtreeLiveCounts:p,workspaceFilterContext:f,showStatusColumn:x,showIdentifierColumn:b,showUpdatedColumn:v,presentation:j="legacy"}){const[N,w]=(0,m.useState)(()=>new Set),{data:k=[],isLoading:S,isFetching:C,error:_,refetch:R}=te({queryKey:[...D.issues.listBlockedAttention(e),"live-descendant-summary"],queryFn:r(()=>yt.list(e,{attention:"blocked",includeBlockedInboxAttention:!0,includeBlockedBy:!0,includeLiveDescendantSummary:!0,limit:lMt}),"queryFn")}),A=(0,m.useMemo)(()=>XPt(k),[k]),T=(0,m.useMemo)(()=>A.filter(U=>sMt(U,s)),[A,s]),E=(0,m.useMemo)(()=>{const U=new Set(_k(T.map(M=>M.issue),d,u,!0,h,f).map(M=>M.id));return T.filter(M=>U.has(M.issue.id))},[u,T,d,h,f]),L=(0,m.useMemo)(()=>f5e(E,c),[E,c]),O=(0,m.useMemo)(()=>tMt(E,c),[E,c]),P=r(U=>{w(M=>{const B=new Set(M);return B.has(U)?B.delete(U):B.add(U),B})},"toggleVariant");if(S)return(0,t.jsx)("div",{"data-testid":"blocked-inbox-loading",className:"space-y-3","aria-busy":"true",children:Array.from({length:3}).map((U,M)=>(0,t.jsxs)("div",{className:"space-y-1",children:[(0,t.jsx)("div",{className:"h-4 w-40 animate-pulse rounded bg-muted/70"}),Array.from({length:2}).map((B,q)=>(0,t.jsxs)("div",{className:V("flex items-center gap-3 px-3 py-2.5 sm:px-4",j==="legacy"&&"border-b border-border/60"),children:[(0,t.jsx)("div",{className:"h-3.5 w-3.5 animate-pulse rounded-full bg-muted"}),(0,t.jsx)("div",{className:"h-4 w-16 animate-pulse rounded bg-muted/70"}),(0,t.jsx)("div",{className:"h-4 w-32 animate-pulse rounded-md bg-muted/70"}),(0,t.jsx)("div",{className:"h-4 flex-1 animate-pulse rounded bg-muted/60"}),(0,t.jsx)("div",{className:"hidden h-3 w-24 animate-pulse rounded bg-muted/60 sm:block"})]},q))]},M))});if(_){const U=_ instanceof Error?_.message:"Couldn't load the Blocked tab.";return(0,t.jsx)("div",{"data-testid":"blocked-inbox-error",role:"alert",className:"flex flex-col gap-2 rounded-md border border-amber-300/70 bg-amber-50/90 p-4 text-amber-900 dark:border-amber-500/40 dark:bg-amber-500/10 dark:text-amber-200",children:(0,t.jsxs)("div",{className:"flex items-start gap-2",children:[(0,t.jsx)(Rs,{className:"mt-0.5 h-4 w-4 shrink-0","aria-hidden":"true"}),(0,t.jsxs)("div",{className:"flex-1 space-y-1",children:[(0,t.jsx)("p",{className:"text-sm font-medium",children:"Couldn't load the Blocked tab."}),(0,t.jsxs)("p",{className:"text-xs opacity-80",children:["Other Inbox tabs still work. ",U]})]}),(0,t.jsx)($,{type:"button",variant:"outline",size:"sm",className:"h-7 shrink-0 border-amber-400/70 bg-white/40 text-amber-900 hover:bg-white/70 dark:bg-amber-500/20 dark:text-amber-100",onClick:r(()=>{R()},"onClick"),disabled:C,children:C?"Trying…":"Try again"})]})})}return A.length===0?(0,t.jsxs)(sn,{"data-testid":"blocked-inbox-empty",className:"items-center gap-3 border-border/70 bg-card/40 px-6 py-10 text-center",children:[(0,t.jsx)("span",{className:"inline-flex h-10 w-10 items-center justify-center rounded-full bg-emerald-100 text-emerald-700 dark:bg-emerald-500/15 dark:text-emerald-300",children:(0,t.jsx)(ha,{className:"h-5 w-5","aria-hidden":"true"})}),(0,t.jsxs)("div",{className:"space-y-1",children:[(0,t.jsx)("p",{className:"text-sm font-medium text-foreground",children:"No work is stopped."}),(0,t.jsx)("p",{className:"text-xs text-muted-foreground",children:"Tasks that need a decision, recovery, or external action will appear here."})]})]}):O.length===0?(0,t.jsx)("div",{className:"space-y-3",children:(0,t.jsx)(sn,{"data-testid":"blocked-inbox-no-search-results",className:"block border-border/70 bg-card/40 px-4 py-6 text-center text-sm text-muted-foreground",children:"No stopped items match your search."})}):(0,t.jsx)("div",{"data-testid":"blocked-inbox",className:"space-y-3",children:(0,t.jsx)("div",{className:"overflow-hidden rounded-xl",children:l==="none"?L.map(U=>(0,t.jsx)(nce,{row:U,issueLinkState:o,agentNameById:n,agents:a,userLabelById:i,liveIssueIds:h,subtreeLiveCounts:p,showStatusColumn:x,showIdentifierColumn:b,showUpdatedColumn:v,presentation:j},U.issue.id)):O.map(U=>{const M=N.has(U.variant);return(0,t.jsxs)("div",{"data-testid":`blocked-inbox-group-${U.variant}`,children:[(0,t.jsx)("div",{className:j==="task"?"rounded-lg px-3 sm:pl-0 sm:pr-4":"px-3 sm:px-4",children:(0,t.jsx)(vj,{label:`${U.label} · ${U.rows.length}`,collapsible:!0,collapsed:M,onToggle:r(()=>P(U.variant),"onToggle")})}),!M&&(0,t.jsx)("div",{children:U.rows.map(B=>(0,t.jsx)(nce,{row:B,issueLinkState:o,agentNameById:n,agents:a,userLabelById:i,liveIssueIds:h,subtreeLiveCounts:p,showStatusColumn:x,showIdentifierColumn:b,showUpdatedColumn:v,presentation:j},B.issue.id))})]},U.variant)})})})}r(x5e,"BlockedInboxView");function cMt(e,s,n){const a=e.attention.owner;return a.label?{label:a.label,isAgent:a.type==="agent"}:a.agentId?{label:s.get(a.agentId)??null,isAgent:!0}:a.userId?{label:n?.get(a.userId)??null,isAgent:!1}:{label:null,isAgent:!1}}r(cMt,"resolveOwnerName");function nce({row:e,issueLinkState:s,agentNameById:n,agents:a,userLabelById:i,liveIssueIds:o,subtreeLiveCounts:l,showStatusColumn:c,showIdentifierColumn:d,showUpdatedColumn:u,presentation:h}){const{label:p,isAgent:f}=cMt(e,n,i),x=nMt(e.attention.stoppedSinceAt),b=jG(e.issue,{isLive:o.has(e.issue.id),loadedSubtreeLiveCount:l.get(e.issue.id)??0}),v=(0,t.jsxs)("span",{className:"flex shrink-0 items-center gap-3 text-xs",children:[(0,t.jsx)("span",{className:"hidden w-(--sz-10_5rem) shrink-0 justify-start sm:inline-flex","data-testid":"blocked-row-reason-column",children:(0,t.jsx)(sce,{reason:e.attention.reason,severity:e.attention.severity,className:"max-w-full"})}),p?(0,t.jsx)("span",{className:"hidden w-(--sz-150px) min-w-0 items-center text-muted-foreground sm:inline-flex",children:f?(0,t.jsx)(Vd,{agent:a?.find(N=>N.id===e.attention.owner.agentId)??{id:e.attention.owner.agentId??void 0,name:p},size:"xs",className:"max-w-full"}):(0,t.jsx)(yo,{name:p,size:"xs",className:"max-w-full"})}):(0,t.jsx)("span",{className:"hidden w-(--sz-150px) shrink-0 sm:inline-flex","aria-hidden":"true"}),h==="legacy"&&u?(0,t.jsx)("span",{className:"hidden w-(--sz-5_75rem) text-right text-muted-foreground sm:inline","data-testid":"blocked-row-age",children:x}):null]}),j=(0,t.jsxs)("span",{className:"flex flex-wrap items-center gap-x-1.5 gap-y-1 text-xs text-muted-foreground",children:[h==="legacy"&&(0,t.jsx)("span",{"data-testid":"blocked-row-age-mobile",children:x}),p?(0,t.jsxs)(t.Fragment,{children:[h==="legacy"&&(0,t.jsx)("span",{"aria-hidden":"true",children:"·"}),(0,t.jsx)("span",{className:V(f?"font-medium text-foreground/90":null),"data-testid":"blocked-row-owner-mobile",children:p})]}):null]});return(0,t.jsx)(bj,{issue:e.issue,issueLinkState:s,presentation:h,showDivider:h==="legacy",statusSlot:h==="task"?c?(0,t.jsx)(no,{status:e.issue.status,blockerAttention:b}):(0,t.jsx)("span",{className:"inline-flex size-4","aria-hidden":"true"}):void 0,showIdentifier:h==="task"?d:void 0,desktopMetaLeading:h==="legacy"?(0,t.jsx)(dMt,{row:e,blockerAttention:b,showStatusColumn:c,showIdentifierColumn:d}):void 0,mobileLeading:(0,t.jsx)("span",{className:"flex shrink-0 items-center gap-1.5 pt-px",children:(0,t.jsx)(no,{status:e.issue.status,blockerAttention:b})}),titleSuffix:(0,t.jsx)(sce,{reason:e.attention.reason,severity:e.attention.severity,className:"ml-2 max-w-(--sz-12rem) align-middle sm:hidden"}),mobileMeta:j,mobileTitleMeta:h==="task"?(0,t.jsx)("span",{"data-testid":"blocked-row-age-mobile",children:x}):void 0,desktopTrailing:v,trailingMeta:h==="task"&&u?x:null})}r(nce,"BlockedInboxRow");function dMt({row:e,blockerAttention:s,showStatusColumn:n,showIdentifierColumn:a}){const i=e.issue.identifier??e.issue.id.slice(0,8);return(0,t.jsxs)("span",{className:"hidden shrink-0 items-center gap-2 sm:inline-flex",children:[n?(0,t.jsx)(no,{status:e.issue.status,blockerAttention:s}):null,a?(0,t.jsx)("span",{className:"font-mono text-xs text-muted-foreground",children:i}):null]})}r(dMt,"BlockedRowDesktopMeta");var uMt=.32,mMt=.88,hMt=140;function If({children:e,onArchive:s,disabled:n=!1,selected:a=!1,className:i}){const o=(0,m.useRef)(null),l=(0,m.useRef)(null),c=(0,m.useRef)(0),d=(0,m.useRef)(null),u=(0,m.useRef)(null),h=(0,m.useRef)(!1),p=(0,m.useRef)(0),[f,x]=(0,m.useState)(0),[b,v]=(0,m.useState)(!1),[j,N]=(0,m.useState)(!1),[w,k]=(0,m.useState)(null);(0,m.useEffect)(()=>()=>{d.current!==null&&window.clearTimeout(d.current),u.current!==null&&window.clearTimeout(u.current),d.current=null,u.current=null,l.current=null,h.current=!1},[]);const S=r(()=>{d.current!==null&&(window.clearTimeout(d.current),d.current=null)},"clearArchiveTimeout"),C=r(()=>{u.current!==null&&(window.clearTimeout(u.current),u.current=null)},"clearClickSuppressionTimeout"),_=r(()=>{C(),h.current=!1},"clearClickSuppression"),R=r(()=>{C(),u.current=window.setTimeout(()=>{h.current=!1,u.current=null},350)},"releaseClickSuppressionSoon"),A=r(()=>{l.current=null,p.current=0,v(!1),N(!1),k(null),x(0)},"reset"),T=r(()=>{S();const M=o.current;if(!M){s();return}l.current=null,v(!1),k(M.offsetHeight);const B=-Math.max(c.current,M.offsetWidth);p.current=B,x(B),window.requestAnimationFrame(()=>{window.requestAnimationFrame(()=>{N(!0)})}),d.current=window.setTimeout(()=>{d.current=null,s()},hMt)},"commitArchive"),E=r(M=>{if(n||j||d.current!==null||M.touches.length!==1)return;S(),_();const B=M.touches[0],q=o.current;c.current=q?.offsetWidth??0,k(q?.offsetHeight??null),N(!1),h.current=!1,l.current={x:B.clientX,y:B.clientY}},"handleTouchStart"),L=r(M=>{if(n||j)return;const B=l.current;if(!B||M.touches.length!==1)return;const q=M.touches[0],z=q.clientX-B.x,K=q.clientY-B.y;if(!b){if(Math.abs(z)<6)return;if(Math.abs(K)>Math.abs(z)){l.current=null;return}h.current=!0}if(z>=0){M.preventDefault(),v(!0),p.current=0,x(0);return}const W=c.current>0?c.current*mMt:Number.POSITIVE_INFINITY;M.preventDefault(),v(!0);const Q=Math.max(z,-W);p.current=Q,x(Q)},"handleTouchMove"),O=r(()=>{if(!(n||j||d.current!==null)){if(c.current>0&&Math.abs(p.current)>=c.current*uMt){R(),T();return}b&&R(),A()}},"handleTouchEnd"),P=r(()=>{n||j||d.current!==null||(_(),A())},"handleTouchCancel"),U=c.current>0?Math.min(Math.abs(f)/c.current,1):0;return(0,t.jsxs)("div",{ref:o,className:V("relative overflow-hidden touch-pan-y",i),style:{height:w===null?void 0:j?0:w,opacity:j?0:1,transition:j?"height 200ms ease, opacity 200ms ease":void 0},onTouchStart:E,onTouchMove:L,onTouchEnd:O,onTouchCancel:P,onClickCapture:r(M=>{h.current&&(M.preventDefault(),M.stopPropagation(),_())},"onClickCapture"),children:[(0,t.jsx)("div",{"aria-hidden":"true",className:"pointer-events-none absolute inset-0 flex items-center justify-end rounded-lg bg-emerald-600 px-4 text-white",style:{opacity:U},children:(0,t.jsxs)("span",{className:"inline-flex items-center gap-2 text-sm font-medium",children:[(0,t.jsx)(Vu,{className:"h-4 w-4"}),"Archive"]})}),(0,t.jsx)("div",{"data-inbox-row-surface":!0,className:V("relative will-change-transform",a?"rounded-lg bg-accent/50":"bg-background"),style:{transform:`translate3d(${f}px, 0, 0)`,transition:b?"none":"transform 180ms ease-out"},children:e})]})}r(If,"SwipeToArchive");var g5e={hire_agent:"Hire Agent",approve_ceo_strategy:"CEO Strategy",budget_override_required:"Budget Override",request_board_approval:"Board Approval"};function dN(...e){for(const s of e)if(typeof s=="string"&&s.trim().length>0)return s.trim();return null}r(dN,"firstNonEmptyString");function b5e(e){return dN(e?.title,e?.name,e?.summary,e?.recommendedAction)}r(b5e,"approvalSubject");function b2(e,s){const n=g5e[e]??e,a=b5e(s);return a?`${n}: ${a}`:n}r(b2,"approvalLabel");var dL={hire_agent:eh,approve_ceo_strategy:yA,budget_override_required:jc,request_board_approval:Fi},uL=Fi;function Ay({label:e,value:s}){return s?(0,t.jsxs)("div",{className:"flex items-center gap-2",children:[(0,t.jsx)("span",{className:"text-muted-foreground w-20 sm:w-24 shrink-0 text-xs",children:e}),(0,t.jsx)("span",{children:String(s)})]}):null}r(Ay,"PayloadField");function pMt({values:e}){if(!Array.isArray(e))return null;const s=e.filter(n=>typeof n=="string").map(n=>n.trim()).filter(Boolean);return s.length===0?null:(0,t.jsxs)("div",{className:"flex items-start gap-2",children:[(0,t.jsx)("span",{className:"text-muted-foreground w-20 sm:w-24 shrink-0 text-xs pt-0.5",children:"Skills"}),(0,t.jsx)("div",{className:"flex flex-wrap gap-1.5",children:s.map(n=>(0,t.jsx)("span",{className:"rounded bg-muted px-1.5 py-0.5 font-mono text-(length:--text-micro) text-muted-foreground",children:n},n))})]})}r(pMt,"SkillList");function fMt({payload:e}){return(0,t.jsxs)("div",{className:"mt-3 space-y-1.5 text-sm",children:[(0,t.jsxs)("div",{className:"flex items-center gap-2",children:[(0,t.jsx)("span",{className:"text-muted-foreground w-20 sm:w-24 shrink-0 text-xs",children:"Name"}),(0,t.jsx)("span",{className:"font-medium",children:String(e.name??"—")})]}),(0,t.jsx)(Ay,{label:"Role",value:e.role}),(0,t.jsx)(Ay,{label:"Title",value:e.title}),(0,t.jsx)(Ay,{label:"Icon",value:e.icon}),!!e.capabilities&&(0,t.jsxs)("div",{className:"flex items-start gap-2",children:[(0,t.jsx)("span",{className:"text-muted-foreground w-20 sm:w-24 shrink-0 text-xs pt-0.5",children:"Capabilities"}),(0,t.jsx)("span",{className:"text-muted-foreground",children:String(e.capabilities)})]}),!!e.adapterType&&(0,t.jsxs)("div",{className:"flex items-center gap-2",children:[(0,t.jsx)("span",{className:"text-muted-foreground w-20 sm:w-24 shrink-0 text-xs",children:"Adapter"}),(0,t.jsx)("span",{className:"font-mono text-xs bg-muted px-1.5 py-0.5 rounded",children:String(e.adapterType)})]}),(0,t.jsx)(pMt,{values:e.desiredSkills})]})}r(fMt,"HireAgentPayload");function xMt({payload:e}){const s=e.plan??e.description??e.strategy??e.text;return(0,t.jsxs)("div",{className:"mt-3 space-y-1.5 text-sm",children:[(0,t.jsx)(Ay,{label:"Title",value:e.title}),!!s&&(0,t.jsx)("div",{className:"mt-2 rounded-md bg-muted/40 px-3 py-2 text-sm text-muted-foreground whitespace-pre-wrap font-mono text-xs max-h-48 overflow-y-auto",children:String(s)}),!s&&(0,t.jsx)("pre",{className:"mt-2 rounded-md bg-muted/40 px-3 py-2 text-xs text-muted-foreground overflow-x-auto max-h-48",children:JSON.stringify(e,null,2)})]})}r(xMt,"CeoStrategyPayload");function gMt({payload:e}){const s=typeof e.budgetAmount=="number"?e.budgetAmount:null,n=typeof e.observedAmount=="number"?e.observedAmount:null;return(0,t.jsxs)("div",{className:"mt-3 space-y-1.5 text-sm",children:[(0,t.jsx)(Ay,{label:"Scope",value:e.scopeName??e.scopeType}),(0,t.jsx)(Ay,{label:"Window",value:e.windowKind}),(0,t.jsx)(Ay,{label:"Metric",value:e.metric}),s!==null||n!==null?(0,t.jsxs)("div",{className:"rounded-md bg-muted/40 px-3 py-2 text-xs text-muted-foreground",children:["Limit ",s!==null?Jr(s):"—"," · Observed ",n!==null?Jr(n):"—"]}):null,!!e.guidance&&(0,t.jsx)("p",{className:"text-muted-foreground",children:String(e.guidance)})]})}r(gMt,"BudgetOverridePayload");function bMt({payload:e,hideTitle:s=!1}){const n=s?{...e,title:void 0}:e;return(0,t.jsx)(yMt,{payload:n})}r(bMt,"BoardApprovalPayload");function vMt(e){return e.replace(/^(?:[-*•]|\d+[.)])\s+/,"")}r(vMt,"stripLeadingListMarker");function yMt({payload:e}){const s=Array.isArray(e.risks)?e.risks.filter(c=>typeof c=="string").map(c=>vMt(c.trim())).filter(Boolean):[],n=dN(e.title),a=dN(e.summary),i=dN(e.recommendedAction),o=dN(e.nextActionOnApproval),l=dN(e.proposedComment);return(0,t.jsxs)("div",{className:"mt-4 space-y-3.5 text-sm",children:[n&&(0,t.jsxs)("div",{className:"space-y-1",children:[(0,t.jsx)("p",{className:"text-(length:--text-micro) font-medium uppercase tracking-(--tracking-label) text-muted-foreground",children:"Title"}),(0,t.jsx)("p",{className:"font-medium leading-6 text-foreground",children:n})]}),a&&(0,t.jsxs)("div",{className:"space-y-1",children:[(0,t.jsx)("p",{className:"text-(length:--text-micro) font-medium uppercase tracking-(--tracking-label) text-muted-foreground",children:"Summary"}),(0,t.jsx)(In,{className:"leading-6 text-foreground/90",children:a})]}),i&&(0,t.jsxs)("div",{className:"rounded-lg border border-amber-500/20 bg-amber-500/10 px-3.5 py-3",children:[(0,t.jsx)("p",{className:"text-(length:--text-micro) font-medium uppercase tracking-(--tracking-label) text-amber-700 dark:text-amber-300",children:"Recommended action"}),(0,t.jsx)(In,{className:"mt-1 leading-6 text-foreground",children:i})]}),o&&(0,t.jsxs)("div",{className:"rounded-lg border border-border/60 bg-background/60 px-3.5 py-3",children:[(0,t.jsx)("p",{className:"text-(length:--text-micro) font-medium uppercase tracking-(--tracking-label) text-muted-foreground",children:"On approval"}),(0,t.jsx)(In,{className:"mt-1 leading-6 text-foreground",children:o})]}),s.length>0&&(0,t.jsxs)("div",{className:"space-y-1.5",children:[(0,t.jsx)("p",{className:"text-(length:--text-micro) font-medium uppercase tracking-(--tracking-label) text-muted-foreground",children:"Risks"}),(0,t.jsx)("ul",{className:"space-y-1 text-sm text-muted-foreground",children:s.map((c,d)=>(0,t.jsxs)("li",{className:"flex items-start gap-2",children:[(0,t.jsx)("span",{className:"mt-2 h-1.5 w-1.5 shrink-0 rounded-full bg-muted-foreground/60"}),(0,t.jsx)(In,{className:"leading-6",children:c})]},`${d}-${c}`))})]}),l&&(0,t.jsxs)("div",{className:"space-y-1.5",children:[(0,t.jsx)("p",{className:"text-(length:--text-micro) font-medium uppercase tracking-(--tracking-label) text-muted-foreground",children:"Proposed comment"}),(0,t.jsx)("pre",{className:"max-h-48 overflow-auto rounded-lg border border-border/60 bg-muted/50 px-3.5 py-3 font-mono text-xs leading-5 text-muted-foreground whitespace-pre-wrap",children:l})]})]})}r(yMt,"BoardApprovalPayloadContent");function v5e({type:e,payload:s,hidePrimaryTitle:n=!1}){return e==="hire_agent"?(0,t.jsx)(fMt,{payload:s}):e==="budget_override_required"?(0,t.jsx)(gMt,{payload:s}):e==="request_board_approval"?(0,t.jsx)(bMt,{payload:s,hideTitle:n}):(0,t.jsx)(xMt,{payload:s})}r(v5e,"ApprovalPayloadRenderer");var jMt=15e4,wMt=3e4;function rce(){return typeof document>"u"||document.visibilityState==="visible"}r(rce,"isDocumentVisible");function y5e({viewIdentity:e,onCommit:s,idleCommitMs:n=jMt,hiddenCommitMs:a=wMt}){const i=(0,m.useRef)(s),o=(0,m.useRef)(null),l=(0,m.useRef)(null),c=(0,m.useRef)(!1),d=(0,m.useRef)(e);(0,m.useEffect)(()=>{i.current=s},[s]);const u=(0,m.useCallback)(()=>{o.current!==null&&(clearTimeout(o.current),o.current=null)},[]),h=(0,m.useCallback)(()=>{if(u(),!rce())return;const x=r(()=>{o.current=setTimeout(()=>{o.current=null,rce()&&(i.current("idle"),x())},n)},"armIdleTimer");x()},[u,n]),p=(0,m.useCallback)(()=>{h()},[h]),f=(0,m.useCallback)(()=>{i.current("manual-refresh"),h()},[h]);return(0,m.useEffect)(()=>(c.current?d.current!==e&&i.current("view-identity-change"):(c.current=!0,i.current("mount")),d.current=e,h(),u),[u,h,e]),(0,m.useEffect)(()=>{if(typeof document>"u")return;document.visibilityState!=="visible"&&(l.current=Date.now(),u());const x=r(()=>{if(document.visibilityState!=="visible"){l.current=Date.now(),u();return}const b=l.current;l.current=null,b!==null&&Date.now()-b>=a&&i.current("visibility"),h()},"handleVisibilityChange");return document.addEventListener("visibilitychange",x),()=>document.removeEventListener("visibilitychange",x)},[u,a,h]),{noteInteraction:p,commitManualRefresh:f}}r(y5e,"useInboxSortAttention");function p8(e){return e.kind==="issue"?e.issue.id:ag(e)}r(p8,"inboxOrderRowKey");function ace(e){return Array.from(e,s=>({key:s,missingSince:null}))}r(ace,"captureKeys");function j5e(e){return{key:e.key,missingSince:null,rows:ace(e.displayItems.map(p8)),childrenByIssueId:new Map(Array.from(e.childrenByIssueId,([s,n])=>[s,ace(n.map(a=>a.id))]))}}r(j5e,"captureSection");function w5e(e){return{sections:e.map(j5e)}}r(w5e,"captureInboxOrderPin");function NMt(e,s,n){let a=0;for(let i=0;i<e.length;i+=1){if(a===n)return i;s.has(e[i].key)&&(a+=1)}return e.length}r(NMt,"insertionIndexForVisiblePosition");function wG(e,s,n){const a=new Set(s),i=e.flatMap(c=>{if(a.has(c.key))return c.missingSince===null||n-c.missingSince<5e3?[{key:c.key,missingSince:null}]:[];const d=c.missingSince??n;return n-d<5e3?[{key:c.key,missingSince:d}]:[]}),o=new Set(i.map(c=>c.key)),l=new Set(i.filter(c=>c.missingSince===null).map(c=>c.key));return s.forEach((c,d)=>{if(o.has(c))return;const u=NMt(i,l,d);i.splice(u,0,{key:c,missingSince:null}),l.add(c)}),{entries:i,retainedPinnedKeys:o,visibleKeys:i.filter(c=>c.missingSince===null).map(c=>c.key)}}r(wG,"reconcileKeys");function kMt(e,s,n){const a=new Set([...e.keys(),...s.keys()]),i=new Map,o=new Map;for(const l of a){const c=s.get(l)??[],d=new Map(c.map(h=>[h.id,h])),u=wG(e.get(l)??[],c.map(h=>h.id),n);u.entries.length>0&&i.set(l,u.entries),s.has(l)&&o.set(l,u.visibleKeys.flatMap(h=>{const p=d.get(h);return p?[p]:[]}))}return{pin:i,display:o}}r(kMt,"reconcileChildren");function SMt(e,s,n){if(!e)return{pin:j5e(s),display:s};const a=new Map(s.displayItems.map(l=>[p8(l),l])),i=wG(e.rows,s.displayItems.map(p8),n),o=kMt(e.childrenByIssueId,s.childrenByIssueId,n);return{pin:{key:s.key,missingSince:null,rows:i.entries,childrenByIssueId:o.pin},display:{...s,displayItems:i.visibleKeys.flatMap(l=>{const c=a.get(l);return c?[c]:[]}),childrenByIssueId:o.display}}}r(SMt,"reconcileSection");function N5e(e,s,n){const a=new Map(s.map(d=>[d.key,d])),i=wG(e.sections,s.map(d=>d.key),n),o=new Map(e.sections.map(d=>[d.key,d])),l=new Map;for(const d of s)l.set(d.key,SMt(i.retainedPinnedKeys.has(d.key)?o.get(d.key):void 0,d,n));const c=i.entries.flatMap(d=>{const u=l.get(d.key);if(u)return[{...u.pin,missingSince:d.missingSince}];const h=o.get(d.key);return h?[{...h,missingSince:d.missingSince}]:[]});return{sections:i.visibleKeys.flatMap(d=>{const u=a.get(d);return u?[l.get(d)?.display??u]:[]}),pin:{sections:c}}}r(N5e,"reconcileInboxOrderPin");var ice=200,C0=500,OR=3e4,FR=r(e=>e?e.type==="top"?`top:${e.itemKey}`:e.type==="child"?`child:${e.issueId}`:`group:${e.groupKey}`:null,"navEntryKey$1");function oce(e){return e?e.split(`
525
525
  `).map(s=>s.trim()).find(Boolean)??null:null}r(oce,"firstNonEmptyLine$2");function k5e(e){return oce(e.error)??oce(e.stderrExcerpt)??"Run exited with an error."}r(k5e,"runFailureMessage$1");function CMt(e){return e.replaceAll("_"," ")}r(CMt,"approvalStatusLabel$1");function S5e(e){const s=e.contextSnapshot;if(!s)return null;const n=s.issueId;if(typeof n=="string"&&n.length>0)return n;const a=s.taskId;return typeof a=="string"&&a.length>0?a:null}r(S5e,"readIssueIdFromRun$1");function BR(e){const s=e?.trim();return s||null}r(BR,"nonEmptyLabel$1");function _Mt(e){if(e.requestType!=="human")return`Agent join request${e.agentName?`: ${e.agentName}`:""}`;const s=BR(e.requesterUser?.name),n=BR(e.requesterUser?.email)??BR(e.requestEmailSnapshot),a=BR(e.requestingUserId);return s&&n?`${s} (${n})`:n||s||a||"Human join request"}r(_Mt,"formatJoinRequestInboxLabel$1");function JC({selected:e,children:s}){return(0,t.jsx)("div",{className:V(e&&"rounded-lg bg-accent/50"),children:s})}r(JC,"InboxRowSurface$1");function IMt({run:e,issueById:s,agentName:n,issueLinkState:a,onDismiss:i,onRetry:o,isRetrying:l,unreadState:c=null,onMarkRead:d,onArchive:u,archiveDisabled:h,selected:p=!1,className:f}){const x=S5e(e),b=x?s.get(x)??null:null,v=k5e(e),j=c!==null,N=c==="visible"||c==="fading";return(0,t.jsxs)("div",{className:V("group border-b border-border px-2 py-2.5 last:border-b-0 sm:px-1 sm:pr-3 sm:py-2",f),children:[(0,t.jsxs)("div",{className:"flex items-start gap-2 sm:items-center",children:[j?(0,t.jsx)("span",{className:"hidden sm:inline-flex h-4 w-4 shrink-0 items-center justify-center self-center",children:N?(0,t.jsx)("button",{type:"button",onClick:d,className:V("inline-flex h-4 w-4 items-center justify-center rounded-full transition-colors","hover:bg-(--status-task-in_progress)/20"),"aria-label":"Mark as read",children:(0,t.jsx)("span",{className:V("block h-2 w-2 rounded-full transition-opacity duration-300","bg-(--status-task-in_progress)",c==="fading"?"opacity-0":"opacity-100")})}):(0,t.jsx)("span",{className:"inline-flex h-4 w-4","aria-hidden":"true"})}):null,(0,t.jsxs)(We,{to:`/agents/${e.agentId}/runs/${e.id}`,className:V("flex min-w-0 flex-1 items-start gap-2 no-underline text-inherit transition-colors",p?"hover:bg-transparent":"hover:bg-accent/50"),children:[!j&&(0,t.jsx)("span",{className:"hidden h-2 w-2 shrink-0 sm:inline-flex","aria-hidden":"true"}),(0,t.jsx)("span",{className:"hidden h-3.5 w-3.5 shrink-0 sm:inline-flex","aria-hidden":"true"}),(0,t.jsx)("span",{className:"mt-0.5 shrink-0 rounded-md bg-red-500/20 p-1.5 sm:mt-0",children:(0,t.jsx)(ud,{className:"h-4 w-4 text-red-600 dark:text-red-400"})}),(0,t.jsxs)("span",{className:"min-w-0 flex-1",children:[(0,t.jsx)("span",{className:"line-clamp-2 text-sm font-medium sm:truncate sm:line-clamp-none",children:b?(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)("span",{className:"font-mono text-muted-foreground mr-1.5",children:b.identifier??b.id.slice(0,8)}),b.title]}):(0,t.jsxs)(t.Fragment,{children:["Failed run",n?` — ${n}`:""]})}),(0,t.jsxs)("span",{className:"mt-1 flex flex-wrap items-center gap-x-2 gap-y-1 text-xs text-muted-foreground",children:[(0,t.jsx)(ai,{status:e.status}),n&&b?(0,t.jsx)("span",{children:n}):null,(0,t.jsx)("span",{className:"truncate max-w-(--sz-300px)",children:v}),(0,t.jsx)("span",{children:ao(e.createdAt)})]})]})]}),(0,t.jsxs)("div",{className:"hidden shrink-0 items-center gap-2 sm:flex",children:[u?(0,t.jsx)(kS,{onArchive:u,disabled:h}):null,(0,t.jsxs)($,{type:"button",variant:"outline",size:"sm",className:"h-8 shrink-0 px-2.5",onClick:o,disabled:l,children:[(0,t.jsx)(Ii,{className:"mr-1.5 h-3.5 w-3.5"}),l?"Retrying…":"Retry"]}),!j&&(0,t.jsx)("button",{type:"button",onClick:i,className:"rounded-md p-1 text-muted-foreground opacity-0 transition-opacity hover:bg-accent hover:text-foreground group-hover:opacity-100","aria-label":"Dismiss",children:(0,t.jsx)(zn,{className:"h-4 w-4"})})]})]}),(0,t.jsxs)("div",{className:"mt-3 flex gap-2 sm:hidden",children:[(0,t.jsxs)($,{type:"button",variant:"outline",size:"sm",className:"h-8 shrink-0 px-2.5",onClick:o,disabled:l,children:[(0,t.jsx)(Ii,{className:"mr-1.5 h-3.5 w-3.5"}),l?"Retrying…":"Retry"]}),!j&&(0,t.jsx)("button",{type:"button",onClick:i,className:"rounded-md p-1 text-muted-foreground hover:bg-accent hover:text-foreground","aria-label":"Dismiss",children:(0,t.jsx)(zn,{className:"h-4 w-4"})})]})]})}r(IMt,"FailedRunInboxRow$1");function AMt({approval:e,requesterName:s,onApprove:n,onReject:a,isPending:i,unreadState:o=null,onMarkRead:l,onArchive:c,archiveDisabled:d,selected:u=!1,className:h}){const p=dL[e.type]??uL,f=b2(e.type,e.payload),x=e.type!=="budget_override_required"&&$0e.has(e.status),b=o!==null,v=o==="visible"||o==="fading";return(0,t.jsxs)("div",{className:V("group border-b border-border px-2 py-2.5 last:border-b-0 sm:px-1 sm:pr-3 sm:py-2",h),children:[(0,t.jsxs)("div",{className:"flex items-start gap-2 sm:items-center",children:[b?(0,t.jsx)("span",{className:"hidden sm:inline-flex h-4 w-4 shrink-0 items-center justify-center self-center",children:v?(0,t.jsx)("button",{type:"button",onClick:l,className:V("inline-flex h-4 w-4 items-center justify-center rounded-full transition-colors","hover:bg-(--status-task-in_progress)/20"),"aria-label":"Mark as read",children:(0,t.jsx)("span",{className:V("block h-2 w-2 rounded-full transition-opacity duration-300","bg-(--status-task-in_progress)",o==="fading"?"opacity-0":"opacity-100")})}):(0,t.jsx)("span",{className:"inline-flex h-4 w-4","aria-hidden":"true"})}):null,(0,t.jsxs)(We,{to:`/approvals/${e.id}`,className:V("flex min-w-0 flex-1 items-start gap-2 no-underline text-inherit transition-colors",u?"hover:bg-transparent":"hover:bg-accent/50"),children:[!b&&(0,t.jsx)("span",{className:"hidden h-2 w-2 shrink-0 sm:inline-flex","aria-hidden":"true"}),(0,t.jsx)("span",{className:"hidden h-3.5 w-3.5 shrink-0 sm:inline-flex","aria-hidden":"true"}),(0,t.jsx)("span",{className:"mt-0.5 shrink-0 rounded-md bg-muted p-1.5 sm:mt-0",children:(0,t.jsx)(p,{className:"h-4 w-4 text-muted-foreground"})}),(0,t.jsxs)("span",{className:"min-w-0 flex-1",children:[(0,t.jsx)("span",{className:"line-clamp-2 text-sm font-medium sm:truncate sm:line-clamp-none",children:f}),(0,t.jsxs)("span",{className:"mt-1 flex flex-wrap items-center gap-x-2 gap-y-1 text-xs text-muted-foreground",children:[(0,t.jsx)("span",{className:"capitalize",children:CMt(e.status)}),s?(0,t.jsxs)("span",{children:["requested by ",s]}):null,(0,t.jsxs)("span",{children:["updated ",ao(e.updatedAt)]})]})]})]}),c||x?(0,t.jsxs)("div",{className:"hidden shrink-0 items-center gap-2 sm:flex",children:[c?(0,t.jsx)(kS,{onArchive:c,disabled:d}):null,x?(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)($,{size:"sm",className:"h-8 bg-(--status-task-icon-done) px-3 text-white hover:bg-(--status-task-done)",onClick:n,disabled:i,children:"Approve"}),(0,t.jsx)($,{variant:"destructive",size:"sm",className:"h-8 px-3",onClick:a,disabled:i,children:"Reject"})]}):null]}):null]}),x?(0,t.jsxs)("div",{className:"mt-3 flex gap-2 sm:hidden",children:[(0,t.jsx)($,{size:"sm",className:"h-8 bg-(--status-task-icon-done) px-3 text-white hover:bg-(--status-task-done)",onClick:n,disabled:i,children:"Approve"}),(0,t.jsx)($,{variant:"destructive",size:"sm",className:"h-8 px-3",onClick:a,disabled:i,children:"Reject"})]}):null]})}r(AMt,"ApprovalInboxRow$1");function TMt({joinRequest:e,onApprove:s,onReject:n,isPending:a,unreadState:i=null,onMarkRead:o,onArchive:l,archiveDisabled:c,selected:d=!1,className:u}){const h=_Mt(e),p=i!==null,f=i==="visible"||i==="fading";return(0,t.jsxs)("div",{className:V("group border-b border-border px-2 py-2.5 last:border-b-0 sm:px-1 sm:pr-3 sm:py-2",u),children:[(0,t.jsxs)("div",{className:"flex items-start gap-2 sm:items-center",children:[p?(0,t.jsx)("span",{className:"hidden sm:inline-flex h-4 w-4 shrink-0 items-center justify-center self-center",children:f?(0,t.jsx)("button",{type:"button",onClick:o,className:V("inline-flex h-4 w-4 items-center justify-center rounded-full transition-colors","hover:bg-(--status-task-in_progress)/20"),"aria-label":"Mark as read",children:(0,t.jsx)("span",{className:V("block h-2 w-2 rounded-full transition-opacity duration-300","bg-(--status-task-in_progress)",i==="fading"?"opacity-0":"opacity-100")})}):(0,t.jsx)("span",{className:"inline-flex h-4 w-4","aria-hidden":"true"})}):null,(0,t.jsxs)("div",{className:"flex min-w-0 flex-1 items-start gap-2",children:[!p&&(0,t.jsx)("span",{className:"hidden h-2 w-2 shrink-0 sm:inline-flex","aria-hidden":"true"}),(0,t.jsx)("span",{className:"hidden h-3.5 w-3.5 shrink-0 sm:inline-flex","aria-hidden":"true"}),(0,t.jsx)("span",{className:"mt-0.5 shrink-0 rounded-md bg-muted p-1.5 sm:mt-0",children:(0,t.jsx)(eh,{className:"h-4 w-4 text-muted-foreground"})}),(0,t.jsxs)("span",{className:"min-w-0 flex-1",children:[(0,t.jsx)("span",{className:"line-clamp-2 text-sm font-medium sm:truncate sm:line-clamp-none",children:h}),(0,t.jsxs)("span",{className:"mt-1 flex flex-wrap items-center gap-x-2 gap-y-1 text-xs text-muted-foreground",children:[(0,t.jsxs)("span",{children:["requested ",ao(e.createdAt)," from IP ",e.requestIp]}),e.adapterType&&(0,t.jsxs)("span",{children:["adapter: ",e.adapterType]})]})]})]}),(0,t.jsxs)("div",{className:"hidden shrink-0 items-center gap-2 sm:flex",children:[l?(0,t.jsx)(kS,{onArchive:l,disabled:c}):null,(0,t.jsx)($,{size:"sm",className:"h-8 bg-(--status-task-icon-done) px-3 text-white hover:bg-(--status-task-done)",onClick:s,disabled:a,children:"Approve"}),(0,t.jsx)($,{variant:"destructive",size:"sm",className:"h-8 px-3",onClick:n,disabled:a,children:"Reject"})]})]}),(0,t.jsxs)("div",{className:"mt-3 flex gap-2 sm:hidden",children:[(0,t.jsx)($,{size:"sm",className:"h-8 bg-(--status-task-icon-done) px-3 text-white hover:bg-(--status-task-done)",onClick:s,disabled:a,children:"Approve"}),(0,t.jsx)($,{variant:"destructive",size:"sm",className:"h-8 px-3",onClick:n,disabled:a,children:"Reject"})]})]})}r(TMt,"JoinRequestInboxRow$1");function RMt(){const{selectedCompanyId:e}=ps(),{setBreadcrumbs:s}=Hn(),{openNewIssue:n}=rl(),{isMobile:a}=qa(),i=Gn(),{pushToast:o}=Qr(),l=oa(),c=Nt(),[d,u]=(0,m.useState)(null),{data:h}=te({queryKey:D.instance.experimentalSettings,queryFn:r(()=>vr.getExperimental(),"queryFn"),retry:!1}),p=h!==void 0,[f,x]=(0,m.useState)(""),b=f.trim(),[v,j]=(0,m.useState)(()=>tee(e)),[N,w]=(0,m.useState)(()=>h0e()),[k,S]=(0,m.useState)("none"),[C,_]=(0,m.useState)("most_recent"),[R,A]=(0,m.useState)(rqe),{dismissed:T,dismiss:E}=WW(),{dismissedAtByKey:L,dismiss:O}=WA(e),{readItems:P,markRead:U,markUnread:M}=ONe(),{allCategoryFilter:B,allApprovalFilter:q,issueFilters:z}=v,K=l.pathname.split("/").pop()??"mine",W=K==="mine"||K==="recent"||K==="all"||K==="unread"||K==="blocked"?K:"mine",Q=r0e(W),re=(0,m.useMemo)(()=>bS("Inbox",`${l.pathname}${l.search}${l.hash}`,"inbox"),[l.pathname,l.search,l.hash]),{data:J}=te({queryKey:D.auth.session,queryFn:r(()=>Ma.getSession(),"queryFn")}),{data:ie}=te({queryKey:D.agents.list(e),queryFn:r(()=>Ct.list(e),"queryFn"),enabled:!!e}),{data:X}=te({queryKey:D.projects.list(e,{includeArchived:!0}),queryFn:r(()=>ra.list(e,{includeArchived:!0}),"queryFn"),enabled:!!e}),{data:ne}=te({queryKey:D.issues.labels(e),queryFn:r(()=>yt.listLabels(e),"queryFn"),enabled:!!e}),oe=h?.enableIsolatedWorkspaces===!0,G=h?.enableExternalObjects===!0,{data:Z=[]}=te({queryKey:e?D.executionWorkspaces.summaryList(e):["execution-workspaces","__disabled__"],queryFn:r(()=>bc.listSummaries(e),"queryFn"),enabled:!!e&&oe});(0,m.useEffect)(()=>{s([{label:"Inbox"}])},[s]),(0,m.useEffect)(()=>{b0e(W),_r(-1),x("")},[W]);const Y=(0,m.useRef)(e);(0,m.useEffect)(()=>{Y.current!==e&&(Y.current=e,j(tee(e)),Ur(O5(e)),kr(U5(e)))},[e]);const{data:ae,isLoading:se,error:ce}=te({queryKey:D.approvals.list(e),queryFn:r(()=>Uo.list(e),"queryFn"),enabled:!!e}),{data:pe=[],isLoading:we}=te({queryKey:D.access.joinRequests(e),queryFn:r(async()=>{try{return await lr.listJoinRequests(e,"pending_approval")}catch(qe){if(qe instanceof mn&&(qe.status===403||qe.status===401))return[];throw qe}},"queryFn"),enabled:!!e,retry:!1}),Se=D.dashboard(e),Te=jo({companyId:e,resourceKey:"dashboard",queryKey:Se,enabled:!!e}),{data:le,isLoading:fe,dataUpdatedAt:de}=te({queryKey:Se,queryFn:r(()=>LS.summary(e),"queryFn"),enabled:!!e});wo(Te,le,de);const Ee=[...D.issues.list(e),"compact","with-routine-executions","live-descendant-summary",C0],Me=jo({companyId:e,resourceKey:"inbox:issues",queryKey:Ee,enabled:!!e}),{data:ve,isLoading:Ie,dataUpdatedAt:Ze}=te({queryKey:Ee,queryFn:r(()=>yt.listCompact(e,{includeRoutineExecutions:!0,includeLiveDescendantSummary:!0,limit:C0}).then(qe=>qe),"queryFn"),enabled:!!e,refetchOnWindowFocus:!1,staleTime:OR});wo(Me,ve,Ze);const{data:ue=[],isLoading:Be,dataUpdatedAt:ht}=te({queryKey:[...D.issues.listMineByMe(e),"compact","with-routine-executions","live-descendant-summary",C0],queryFn:r(()=>yt.listCompact(e,{touchedByUserId:"me",inboxArchivedByUserId:"me",status:A5,includeRoutineExecutions:!0,includeLiveDescendantSummary:!0,limit:C0}).then(qe=>qe),"queryFn"),enabled:!!e,refetchOnWindowFocus:!1,staleTime:OR}),jt=[...D.issues.listMineByMe(e),"compact","with-routine-executions","live-descendant-summary",C0],Je=jo({companyId:e,resourceKey:"inbox:mine-issues",queryKey:jt,enabled:!!e});wo(Je,ue,ht);const{data:Fe=[],isLoading:it,dataUpdatedAt:At}=te({queryKey:[...D.issues.listTouchedByMe(e),"compact","with-routine-executions","live-descendant-summary",C0],queryFn:r(()=>yt.listCompact(e,{touchedByUserId:"me",status:A5,includeRoutineExecutions:!0,includeLiveDescendantSummary:!0,limit:C0}).then(qe=>qe),"queryFn"),enabled:!!e,refetchOnWindowFocus:!1,staleTime:OR}),$t=[...D.issues.listTouchedByMe(e),"compact","with-routine-executions","live-descendant-summary",C0],zt=jo({companyId:e,resourceKey:"inbox:touched-issues",queryKey:$t,enabled:!!e});wo(zt,Fe,At);const{data:at,isLoading:De}=te({queryKey:[...D.heartbeats(e),"limit",ice],queryFn:r(()=>Xr.list(e,void 0,ice,{summary:!0}),"queryFn"),enabled:!!e,refetchOnWindowFocus:!1,staleTime:OR}),Pe=D.liveRuns(e),dt=jo({companyId:e,resourceKey:"live-runs",queryKey:Pe,enabled:!!e,refetchInterval:!1,leaderOnly:!0}),{data:rt,dataUpdatedAt:ft}=te({queryKey:Pe,queryFn:r(()=>Xr.liveRunsForCompany(e),"queryFn"),enabled:dt.enabled,refetchInterval:dt.refetchInterval});wo(dt,rt,ft);const{data:kt}=te({queryKey:D.access.companyUserDirectory(e),queryFn:r(()=>lr.listUserDirectory(e),"queryFn"),enabled:!!e}),Ke=J?.user.id??J?.session.userId??null,[$e,ze]=(0,m.useState)(new Set),[et,ge]=(0,m.useState)([]),[st,Mt]=(0,m.useState)(new Set),Ss=EW(e),lt=(0,m.useMemo)(()=>{const qe=new Set(Ss);for(const Pt of et)qe.add(Pt);for(const Pt of $e)qe.add(Pt);for(const Pt of st)qe.delete(Pt);return qe},[$e,Ss,et,st]),Ls=(0,m.useMemo)(()=>MA(kt?.users),[kt?.users]),Ue=(0,m.useMemo)(()=>Kg(kt?.users),[kt?.users]),xe=(0,m.useMemo)(()=>W_(ue).filter(qe=>!lt.has(qe.id)),[lt,ue]),Ye=(0,m.useMemo)(()=>W_(Fe).filter(qe=>!lt.has(qe.id)),[lt,Fe]),gt=!!e&&b.length>0,{data:Ht=[]}=te({queryKey:[...D.issues.search(e,b,void 0,25),"compact","inbox-supplement","live-descendant-summary"],queryFn:r(()=>yt.listCompact(e,{q:b,limit:25,includeRoutineExecutions:!0,includeLiveDescendantSummary:!0}).then(qe=>qe),"queryFn"),enabled:gt,placeholderData:r(qe=>qe,"placeholderData")}),mt=(0,m.useMemo)(()=>qg(rt,[...ve??[],...ue,...Fe,...Ht]),[ve,rt,ue,Ht,Fe]),Bt=(0,m.useMemo)(()=>{const qe=new Set;for(const Pt of xe)qe.add(Pt.id);for(const Pt of Ye)qe.add(Pt.id);for(const Pt of Ht)qe.add(Pt.id);return[...qe]},[xe,Ht,Ye]),{summaries:Le,isLoading:he,isReady:Qt}=I0e(e,Bt),Lt=(0,m.useMemo)(()=>({externalObjectSummaryByIssueId:Le,externalObjectSummariesReady:Qt&&!he}),[he,Qt,Le]),ss=(0,m.useMemo)(()=>_k(xe,z,Ke,!0,mt,Lt),[xe,z,Ke,mt,Lt]),Cs=(0,m.useMemo)(()=>_k(Ye,z,Ke,!0,mt,Lt),[Ye,z,Ke,mt,Lt]),ln=(0,m.useMemo)(()=>Cs.filter(qe=>qe.isUnreadForMe),[Cs]),mr=(0,m.useMemo)(()=>{const qe=new Map,Pt=[...xe,...Ye];Ke&&qe.set(`user:${Ke}`,{id:`user:${Ke}`,label:Ke==="local-board"?"Board":"Me",kind:"user",searchText:Ke==="local-board"?"board me human local-board":`me board human ${Ke}`});for(const Ds of Pt)if(Ds.createdByUserId){const en=`user:${Ds.createdByUserId}`;qe.has(en)||qe.set(en,{id:en,label:Bm(Ds.createdByUserId,Ke)??Ds.createdByUserId.slice(0,5),kind:"user",searchText:`${Ds.createdByUserId} board user human`})}const Kt=new Set;for(const Ds of ie??[]){Kt.add(Ds.id);const en=`agent:${Ds.id}`;qe.has(en)||qe.set(en,{id:en,label:Ds.name,kind:"agent",searchText:`${Ds.name} ${Ds.id} agent`})}for(const Ds of Pt)if(Ds.createdByAgentId&&!Kt.has(Ds.createdByAgentId)){const en=`agent:${Ds.createdByAgentId}`;qe.has(en)||qe.set(en,{id:en,label:Ds.createdByAgentId.slice(0,8),kind:"agent",searchText:`${Ds.createdByAgentId} agent`})}return[...qe.values()].sort((Ds,en)=>Ds.kind!==en.kind?Ds.kind==="user"?-1:1:Ds.label.localeCompare(en.label))},[ie,Ke,xe,Ye]),pn=(0,m.useMemo)(()=>W==="mine"?ss:W==="unread"?ln:Cs,[W,ss,Cs,ln]),Ot=(0,m.useMemo)(()=>{const qe=new Map;for(const Pt of ie??[])qe.set(Pt.id,Pt.name);return qe},[ie]),Es=(0,m.useMemo)(()=>{const qe=new Map;for(const Pt of ve??[])qe.set(Pt.id,Pt);return qe},[ve]),Re=(0,m.useMemo)(()=>{const qe=new Map;for(const Pt of X??[])qe.set(Pt.id,{name:Pt.name,color:Pt.color});return qe},[X]),wt=(0,m.useMemo)(()=>{const qe=new Map;for(const Pt of X??[])for(const Kt of Pt.workspaces??[])qe.set(Kt.id,{name:Kt.name,projectId:Pt.id});return qe},[X]),Oe=(0,m.useMemo)(()=>{const qe=new Map;for(const Pt of X??[]){const Kt=Pt.executionWorkspacePolicy?.defaultProjectWorkspaceId??Pt.primaryWorkspace?.id??null;Kt&&qe.set(Pt.id,Kt)}return qe},[X]),_t=(0,m.useMemo)(()=>{const qe=new Map;for(const Pt of Z){const Kt=Pt.projectWorkspaceId?wt.get(Pt.projectWorkspaceId)??null:null;qe.set(Pt.id,{name:Pt.name,mode:Pt.mode,projectWorkspaceId:Pt.projectWorkspaceId??null,projectId:Kt?.projectId??null})}return qe},[Z,wt]),Ut=(0,m.useMemo)(()=>({agentById:Ot,executionWorkspaceById:_t,projectWorkspaceById:wt,defaultProjectWorkspaceIdByProjectId:Oe,projectById:Re,userLabelById:Ls,currentUserId:Ke}),[Ot,Ls,Ke,Oe,_t,Re,wt]),It=(0,m.useMemo)(()=>new Set(R),[R]),is=(0,m.useMemo)(()=>W0e(oe),[oe]),bs=(0,m.useMemo)(()=>new Set(is),[is]),Os=(0,m.useMemo)(()=>w0e.filter(qe=>It.has(qe)&&bs.has(qe)),[bs,It]),qs=(0,m.useMemo)(()=>q0e(at??[]).filter(qe=>!ON(L,`run:${qe.id}`,qe.createdAt)),[at,L]),Rn=(0,m.useMemo)(()=>{let qe=y0e(ae??[],W,q,Ke);return W==="mine"&&(qe=qe.filter(Pt=>!ON(L,`approval:${Pt.id}`,Pt.updatedAt))),qe},[ae,W,q,Ke,L]),Ns=B==="everything"||B==="join_requests",Yn=B==="everything"||B==="issues_i_touched",Xt=B==="everything"||B==="approvals",Hs=B==="everything"||B==="failed_runs",rn=B==="everything"||B==="alerts",Et=(0,m.useMemo)(()=>W==="all"&&!Hs?[]:W==="mine"?qs.filter(qe=>gbe(qe,Ke)):qs,[qs,W,Hs,Ke]),rs=(0,m.useMemo)(()=>W==="all"&&!Ns?[]:W==="mine"?pe.filter(qe=>!ON(L,`join:${qe.id}`,qe.updatedAt??qe.createdAt)):pe,[pe,W,Ns,L]),Zs=(0,m.useMemo)(()=>$N({issues:W==="all"&&!Yn?[]:pn,approvals:W==="all"&&!Xt?[]:Rn,failedRuns:Et,joinRequests:rs}),[Rn,pn,Xt,Yn,W,Et,rs]),gs=(0,m.useMemo)(()=>{const qe=b.toLowerCase();return qe?Zs.filter(Pt=>{if(Pt.kind==="issue")return u0e(Pt.issue,qe,{isolatedWorkspacesEnabled:oe,executionWorkspaceById:_t,projectWorkspaceById:wt,defaultProjectWorkspaceIdByProjectId:Oe});if(Pt.kind==="approval"){const Kt=Pt.approval;return!!(b2(Kt.type,Kt.payload).toLowerCase().includes(qe)||Kt.type.toLowerCase().includes(qe))}if(Pt.kind==="failed_run"){const Kt=Pt.run;if(Ot.get(Kt.agentId)?.toLowerCase().includes(qe)||k5e(Kt).toLowerCase().includes(qe))return!0;const Ds=S5e(Kt);if(Ds){const en=Es.get(Ds);if(en?.title.toLowerCase().includes(qe)||en?.identifier?.toLowerCase().includes(qe))return!0}return!1}if(Pt.kind==="join_request"){const Kt=Pt.joinRequest;return!!(Kt.agentName?.toLowerCase().includes(qe)||Kt.capabilities?.toLowerCase().includes(qe))}return!1}):Zs},[Zs,Ot,Oe,_t,Es,oe,b,wt]),Js=(0,m.useMemo)(()=>W==="mine"?B0e({visibleIssues:ss,searchableIssues:Cs,query:b,isolatedWorkspacesEnabled:oe,executionWorkspaceById:_t,projectWorkspaceById:wt,defaultProjectWorkspaceIdByProjectId:Oe}):[],[Oe,_t,oe,b,wt,W,ss,Cs]),kn=(0,m.useMemo)(()=>U0e({query:b,filteredWorkItems:gs,archivedSearchIssues:Js,remoteIssues:Ht,issueFilters:z,currentUserId:Ke,enableRoutineVisibilityFilter:!0,liveIssueIds:mt,issueFilterContext:Lt}),[Js,Ke,gs,Lt,z,mt,b,Ht]),hr=(0,m.useMemo)(()=>new Set([...Js.map(qe=>qe.id),...kn.map(qe=>qe.id)]),[Js,kn]),[qn,qr]=(0,m.useState)(()=>m0e()),Cr=V0e(qn,a);(0,m.useEffect)(()=>{v0e(N,oe,p)&&(w("none"),$5("none"))},[p,N,oe]);const pr=(0,m.useCallback)(()=>{qr(qe=>{const Pt=!qe;return D0e(Pt),Pt})},[]),[Cn,kr]=(0,m.useState)(()=>U5(e)),[Or,Ur]=(0,m.useState)(()=>O5(e)),xa=(0,m.useCallback)(qe=>{Ur(Pt=>{const Kt=new Set(Pt);return Kt.has(qe)?Kt.delete(qe):Kt.add(qe),L5(e,Kt),Kt})},[e]),ar=(0,m.useCallback)((qe,Pt)=>{Ur(Kt=>{if(Pt?Kt.has(qe):!Kt.has(qe))return Kt;const Ds=new Set(Kt);return Pt?Ds.add(qe):Ds.delete(qe),L5(e,Ds),Ds})},[e]),cr=(0,m.useMemo)(()=>[...zN(gs,N,Ut,{nestingEnabled:Cr}),...zN($N({issues:Js,approvals:[]}),N,Ut,{keyPrefix:"archived-search:",searchSection:"archived",nestingEnabled:Cr}),...zN($N({issues:kn,approvals:[]}),N,Ut,{keyPrefix:"other-search:",searchSection:"other",nestingEnabled:Cr})],[Js,gs,N,Ut,kn,Cr]),bt=(0,m.useRef)({sections:[]}),[He,Zt]=(0,m.useState)(0),ms=(0,m.useRef)(!1),_s=(0,m.useCallback)(()=>{ms.current=!0,Zt(qe=>qe+1)},[]),ts=(0,m.useMemo)(()=>JSON.stringify([e,W,N,Cr,b,B,q,z]),[q,B,N,z,Cr,b,e,W]),ws=(0,m.useRef)(ts);ws.current!==ts&&(ws.current=ts,ms.current=!0);const Nn=(0,m.useMemo)(()=>{const qe=Date.now();if(ms.current)return ms.current=!1,bt.current=w5e(cr),cr;const{sections:Pt,pin:Kt}=N5e(bt.current,cr,qe);return bt.current=Kt,Pt},[cr,ts,He]),vn=y5e({viewIdentity:ts,onCommit:_s}).noteInteraction,Un=(0,m.useCallback)(qe=>{const Pt=E0e(qe.key,N,qe.displayItems,Ut);Pt&&n(Pt)},[N,Ut,n]),pt=(0,m.useMemo)(()=>Nn.reduce((qe,Pt)=>qe+Pt.displayItems.length,0),[Nn]),Is=(0,m.useCallback)(qe=>{kr(Pt=>{const Kt=new Set(Pt);return Kt.has(qe)?Kt.delete(qe):Kt.add(qe),B5(e,Kt),Kt})},[e]),cn=(0,m.useCallback)((qe,Pt)=>{kr(Kt=>{if(Kt.has(qe)===Pt)return Kt;const Ds=new Set(Kt);return Pt?Ds.add(qe):Ds.delete(qe),B5(e,Ds),Ds})},[e]),_n=(0,m.useMemo)(()=>T0e(Nn,Or,Cn),[Or,Cn,Nn]),fn=(0,m.useRef)(_n);fn.current=_n;const Sr=(0,m.useMemo)(()=>{const qe=[],Pt=new Set,Kt=r(Ds=>{Pt.has(Ds.id)||(Pt.add(Ds.id),qe.push({id:Ds.id,parentId:Ds.parentId}))},"pushIssue");for(const Ds of Nn){for(const en of Ds.displayItems)en.kind==="issue"&&Kt(en.issue);for(const en of Ds.childrenByIssueId.values())for(const ti of en)Kt(ti)}return c0e(qe,mt)},[Nn,mt]),aa=(0,m.useMemo)(()=>{const qe=new Map;return _n.forEach((Pt,Kt)=>{Pt.type==="top"&&qe.set(Pt.itemKey,Kt)}),qe},[_n]),Da=(0,m.useMemo)(()=>{const qe=new Map;return _n.forEach((Pt,Kt)=>{Pt.type==="child"&&qe.set(Pt.issueId,Kt)}),qe},[_n]),As=(0,m.useMemo)(()=>{const qe=new Map;return _n.forEach((Pt,Kt)=>{Pt.type==="group"&&qe.set(Pt.groupKey,Kt)}),qe},[_n]),an=r(qe=>qe?Ot.get(qe)??null:null,"agentName"),Tr=(0,m.useCallback)(qe=>{const Pt=q9(qe);A(Pt),eqe(Pt)},[]),Jn=(0,m.useCallback)((qe,Pt)=>{if(Pt){Tr([...R,qe]);return}Tr(R.filter(Kt=>Kt!==qe))},[Tr,R]),Kn=(0,m.useCallback)(qe=>{j(Pt=>{const Kt=qe(Pt);return Yze(e,Kt),Kt})},[e]),Vr=(0,m.useCallback)(qe=>{Kn(Pt=>({...Pt,issueFilters:{...Pt.issueFilters,...qe}}))},[Kn]);(0,m.useEffect)(()=>{!p||G||z.externalObjectStatuses.length===0||Vr({externalObjectStatuses:[]})},[p,G,z.externalObjectStatuses.length,Vr]);const Ps=(0,m.useCallback)(qe=>{Kn(Pt=>({...Pt,allCategoryFilter:qe}))},[Kn]),jn=(0,m.useCallback)(qe=>{Kn(Pt=>({...Pt,allApprovalFilter:qe}))},[Kn]),En=(0,m.useCallback)(qe=>{w(qe),$5(qe)},[]),Fs=ye({mutationFn:r(qe=>Uo.approve(qe),"mutationFn"),onSuccess:r((qe,Pt)=>{u(null),c.invalidateQueries({queryKey:D.approvals.list(e)}),i(`/approvals/${Pt}?resolved=approved`)},"onSuccess"),onError:r(qe=>{u(qe instanceof Error?qe.message:"Failed to approve")},"onError")}),nr=ye({mutationFn:r(qe=>Uo.reject(qe),"mutationFn"),onSuccess:r(()=>{u(null),c.invalidateQueries({queryKey:D.approvals.list(e)})},"onSuccess"),onError:r(qe=>{u(qe instanceof Error?qe.message:"Failed to reject")},"onError")}),un=ye({mutationFn:r(qe=>lr.approveJoinRequest(e,qe.id),"mutationFn"),onSuccess:r(()=>{u(null),c.invalidateQueries({queryKey:D.access.joinRequests(e)}),c.invalidateQueries({queryKey:D.sidebarBadges(e)}),c.invalidateQueries({queryKey:D.agents.list(e)}),c.invalidateQueries({queryKey:D.companies.all})},"onSuccess"),onError:r(qe=>{u(qe instanceof Error?qe.message:"Failed to approve join request")},"onError")}),Gr=ye({mutationFn:r(qe=>lr.rejectJoinRequest(e,qe.id),"mutationFn"),onSuccess:r(()=>{u(null),c.invalidateQueries({queryKey:D.access.joinRequests(e)}),c.invalidateQueries({queryKey:D.sidebarBadges(e)})},"onSuccess"),onError:r(qe=>{u(qe instanceof Error?qe.message:"Failed to reject join request")},"onError")}),[_e,Yt]=(0,m.useState)(new Set),xn=ye({mutationFn:r(async qe=>({newRun:await Ct.retryFailedRun(qe.agentId,qe.id,qe.companyId),originalRun:qe}),"mutationFn"),onMutate:r(qe=>{Yt(Pt=>new Set(Pt).add(qe.id))},"onMutate"),onSuccess:r(({newRun:qe,originalRun:Pt})=>{c.invalidateQueries({queryKey:D.heartbeats(Pt.companyId)}),c.invalidateQueries({queryKey:D.heartbeats(Pt.companyId,Pt.agentId)}),qe.runId?i(`/agents/${Pt.agentId}/runs/${qe.runId}`):qe.issueId&&i(`/issues/${qe.issueId}`)},"onSuccess"),onError:r(qe=>{o({title:"Run retry failed",body:qe instanceof Error?qe.message:"Unable to retry run",tone:"error"})},"onError"),onSettled:r((qe,Pt,Kt)=>{Kt&&Yt(Ds=>{const en=new Set(Ds);return en.delete(Kt.id),en})},"onSettled")}),[Lr,ga]=(0,m.useState)(new Set),[Oa,hs]=(0,m.useState)(!1),[Ae,Vt]=(0,m.useState)(new Set),[Jt,Xs]=(0,m.useState)(new Set),[gn,_r]=(0,m.useState)(-1),ei=(0,m.useRef)(null),fr=(0,m.useRef)(!0);(0,m.useEffect)(()=>{const qe=r(()=>{fr.current=!0},"handlePointerMove");return window.addEventListener("mousemove",qe,{passive:!0}),()=>window.removeEventListener("mousemove",qe)},[]);const Aa=(0,m.useRef)(null),vi=(0,m.useRef)(null),Va=(0,m.useCallback)(qe=>{fr.current&&(vn(),Aa.current=qe,vi.current=FR(fn.current[qe]),_r(Pt=>Pt<0?Pt:-1))},[vn]),Er=r(()=>{e&&Wy(c,e)},"invalidateInboxIssueQueryCaches"),Mi=ye({mutationFn:r(qe=>yt.archiveFromInbox(qe),"mutationFn"),onMutate:r(async qe=>{if(vn(),u(null),ze(Kt=>new Set(Kt).add(qe)),!e)return{previousData:[]};Rk(e,qe),await X5(c,e);const Pt=PW(c,e);return l_(c,e,qe),{companyId:e,previousData:Pt}},"onMutate"),onError:r((qe,Pt,Kt)=>{u(qe instanceof Error?qe.message:"Failed to archive task"),Kt?.companyId&&kb(Kt.companyId,Pt),ze(Ds=>{const en=new Set(Ds);return en.delete(Pt),en}),Kt?.previousData&&Z5(c,Kt.previousData,Pt)},"onError"),onSettled:r(async(qe,Pt,Kt,Ds)=>{ze(en=>{const ti=new Set(en);return ti.delete(Kt),ti}),Ds?.companyId&&(Pt||Ek(Ds.companyId,Kt),await Wy(c,Ds.companyId),Pt||MW(c,Ds.companyId,Kt)!=="unknown"&&RW(Ds.companyId,Kt))},"onSettled"),onSuccess:r((qe,Pt)=>{ge(Kt=>[...Kt.filter(Ds=>Ds!==Pt),Pt])},"onSuccess")}),ir=ye({mutationFn:r(qe=>yt.unarchiveFromInbox(qe),"mutationFn"),onMutate:r(qe=>(u(null),Mt(Pt=>new Set(Pt).add(qe)),e&&kb(e,qe),{companyId:e}),"onMutate"),onError:r((qe,Pt,Kt)=>{u(qe instanceof Error?qe.message:"Failed to undo inbox archive"),Kt?.companyId&&(Rk(Kt.companyId,Pt),Ek(Kt.companyId,Pt))},"onError"),onSuccess:r((qe,Pt)=>{ge(Kt=>Kt.filter(Ds=>Ds!==Pt))},"onSuccess"),onSettled:r((qe,Pt,Kt)=>{Mt(Ds=>{const en=new Set(Ds);return en.delete(Kt),en}),Er()},"onSettled")}),Hi=ye({mutationFn:r(qe=>yt.markRead(qe),"mutationFn"),onMutate:r(qe=>{ga(Pt=>new Set(Pt).add(qe))},"onMutate"),onSuccess:r(()=>{Er()},"onSuccess"),onSettled:r((qe,Pt,Kt)=>{setTimeout(()=>{ga(Ds=>{const en=new Set(Ds);return en.delete(Kt),en})},300)},"onSettled")}),al=ye({mutationFn:r(async qe=>{await Promise.all(qe.map(Pt=>yt.markRead(Pt)))},"mutationFn"),onMutate:r(qe=>{ga(Pt=>{const Kt=new Set(Pt);for(const Ds of qe)Kt.add(Ds);return Kt})},"onMutate"),onSuccess:r(()=>{Er()},"onSuccess"),onSettled:r((qe,Pt,Kt)=>{setTimeout(()=>{ga(Ds=>{const en=new Set(Ds);for(const ti of Kt)en.delete(ti);return en})},300)},"onSettled")}),So=ye({mutationFn:r(qe=>yt.markUnread(qe),"mutationFn"),onSuccess:r(()=>{Er()},"onSuccess")}),Zi=(0,m.useCallback)(qe=>{Vt(Pt=>new Set(Pt).add(qe)),U(qe),setTimeout(()=>{Vt(Pt=>{const Kt=new Set(Pt);return Kt.delete(qe),Kt})},300)},[U]),be=(0,m.useCallback)(qe=>{vn(),Xs(Pt=>new Set(Pt).add(qe)),setTimeout(()=>{qe.startsWith("alert:")?E(qe):O(qe),Xs(Pt=>{const Kt=new Set(Pt);return Kt.delete(qe),Kt})},200)},[E,O,vn]),xt=r(qe=>{if(!Q)return null;const Pt=P.has(qe);return Ae.has(qe)?"fading":Pt?"hidden":"visible"},"nonIssueUnreadState"),cs=(0,m.useRef)(null);(0,m.useEffect)(()=>{const qe=vi.current,Pt=qe===null?-1:_n.findIndex(Kt=>FR(Kt)===qe);Aa.current=Pt>=0?Pt:null,Pt<0&&(vi.current=null),_r(Kt=>{if(Kt<0)return D5(Kt,_n.length);const Ds=cs.current,en=Ds===null?-1:_n.findIndex(ti=>FR(ti)===Ds);return en>=0?en:D5(Kt,_n.length)})},[_n]),(0,m.useEffect)(()=>{cs.current=gn>=0?FR(_n[gn]):null},[_n,gn]),(0,m.useEffect)(()=>{ge(qe=>qe.filter(Pt=>Ss.has(Pt)||st.has(Pt)))},[Ss,st]),(0,m.useEffect)(()=>{ge([]),Mt(new Set)},[e]);const Wn=(0,m.useRef)({workItems:Nn,flatNavItems:_n,selectedIndex:gn,canArchive:Q,nonInboxSearchIssueIds:hr,archivingIssueIds:$e,undoableArchiveIssueIds:et,unarchivingIssueIds:st,archivingNonIssueIds:Jt,fadingOutIssues:Lr,readItems:P});Wn.current={workItems:Nn,flatNavItems:_n,selectedIndex:gn,canArchive:Q,nonInboxSearchIssueIds:hr,archivingIssueIds:$e,undoableArchiveIssueIds:et,unarchivingIssueIds:st,archivingNonIssueIds:Jt,fadingOutIssues:Lr,readItems:P};const sa=(0,m.useRef)({archiveIssue:r(qe=>Mi.mutate(qe),"archiveIssue"),undoArchiveIssue:r(qe=>ir.mutate(qe),"undoArchiveIssue"),archiveNonIssue:be,markRead:r(qe=>Hi.mutate(qe),"markRead"),markUnreadIssue:r(qe=>So.mutate(qe),"markUnreadIssue"),markNonIssueRead:Zi,markNonIssueUnread:M,setGroupCollapsed:ar,setInboxParentCollapsed:cn,navigate:i});if(sa.current={archiveIssue:r(qe=>Mi.mutate(qe),"archiveIssue"),undoArchiveIssue:r(qe=>ir.mutate(qe),"undoArchiveIssue"),archiveNonIssue:be,markRead:r(qe=>Hi.mutate(qe),"markRead"),markUnreadIssue:r(qe=>So.mutate(qe),"markUnreadIssue"),markNonIssueRead:Zi,markNonIssueUnread:M,setGroupCollapsed:ar,setInboxParentCollapsed:cn,navigate:i},(0,m.useEffect)(()=>{const qe=r(Pt=>{if(Pt.defaultPrevented)return;const Kt=Pt.target;if(!(Kt instanceof HTMLElement)||_A(Kt)||$p(document)||Pt.metaKey||Pt.ctrlKey||Pt.altKey)return;const Ds=Wn.current,en=sa.current;if((Ds.canArchive?N0e({hasUndoableArchive:Ds.undoableArchiveIssueIds.length>0,defaultPrevented:Pt.defaultPrevented,key:Pt.key,metaKey:Pt.metaKey,ctrlKey:Pt.ctrlKey,altKey:Pt.altKey,target:Kt,hasOpenDialog:$p(document)}):"none")==="undo_archive"){const Xn=Ds.undoableArchiveIssueIds[Ds.undoableArchiveIssueIds.length-1];if(!Xn||Ds.unarchivingIssueIds.has(Xn))return;Pt.preventDefault(),en.undoArchiveIssue(Xn);return}const ti=Ds.flatNavItems,Ta=ti.length;if(Ta===0)return;vn();const ct=r(Xn=>{const wn=ti[Xn];return wn?wn.type==="child"?{issue:wn.issue}:wn.type==="top"?{item:wn.item}:{}:{}},"resolveNavEntry"),fs=Aa.current,Ks=fs!=null&&fs>=0&&fs<Ta?fs:-1,Sn=fr.current&&Ks>=0?Ks:Ds.selectedIndex;switch(Pt.key){case"j":case"ArrowDown":Pt.preventDefault(),fr.current=!1,_r(z5(Sn,Ta,"next"));break;case"k":case"ArrowUp":Pt.preventDefault(),fr.current=!1,_r(z5(Sn,Ta,"previous"));break;case"ArrowLeft":case"ArrowRight":{if(Sn<0||Sn>=Ta)return;const Xn=ti[Sn];if(!Xn)return;if(Xn.type==="group"){Pt.preventDefault(),fr.current=!1,_r(Sn),en.setGroupCollapsed(Xn.groupKey,Pt.key==="ArrowLeft");break}const{issue:wn,item:la}=ct(Sn),Qa=wn??(la?.kind==="issue"?la.issue:null);if(!Qa||!Ds.workItems.some(Qe=>(Qe.childrenByIssueId.get(Qa.id)?.length??0)>0))return;Pt.preventDefault(),fr.current=!1,_r(Sn),en.setInboxParentCollapsed(Qa.id,Pt.key==="ArrowLeft");break}case"a":case"y":{if(!Ds.canArchive||Sn<0||Sn>=Ta)return;Pt.preventDefault();const{issue:Xn,item:wn}=ct(Sn);if(Xn)!Ds.nonInboxSearchIssueIds.has(Xn.id)&&!Ds.archivingIssueIds.has(Xn.id)&&en.archiveIssue(Xn.id);else if(wn)if(wn.kind==="issue")!Ds.nonInboxSearchIssueIds.has(wn.issue.id)&&!Ds.archivingIssueIds.has(wn.issue.id)&&en.archiveIssue(wn.issue.id);else{const la=ag(wn);Ds.archivingNonIssueIds.has(la)||en.archiveNonIssue(la)}break}case"U":{if(!Ds.canArchive||Sn<0||Sn>=Ta)return;Pt.preventDefault();const{issue:Xn,item:wn}=ct(Sn);Xn?en.markUnreadIssue(Xn.id):wn&&(wn.kind==="issue"?en.markUnreadIssue(wn.issue.id):en.markNonIssueUnread(ag(wn)));break}case"r":{if(!Ds.canArchive||Sn<0||Sn>=Ta)return;Pt.preventDefault();const{issue:Xn,item:wn}=ct(Sn);if(Xn)Xn.isUnreadForMe&&!Ds.fadingOutIssues.has(Xn.id)&&en.markRead(Xn.id);else if(wn)if(wn.kind==="issue")wn.issue.isUnreadForMe&&!Ds.fadingOutIssues.has(wn.issue.id)&&en.markRead(wn.issue.id);else{const la=ag(wn);Ds.readItems.has(la)||en.markNonIssueRead(la)}break}case"Enter":{if(Sn<0||Sn>=Ta)return;Pt.preventDefault();const{issue:Xn,item:wn}=ct(Sn);if(Xn){const la=Xn.identifier??Xn.id,Qa=M5(kg(re,Xn));Sg(la,Qa),R5(c,la,{issue:Xn}),en.navigate(ul(la),{state:Qa})}else if(wn)if(wn.kind==="issue"){const la=wn.issue.identifier??wn.issue.id,Qa=M5(kg(re,wn.issue));Sg(la,Qa),R5(c,la,{issue:wn.issue}),en.navigate(ul(la),{state:Qa})}else wn.kind==="approval"?en.navigate(`/approvals/${wn.approval.id}`):wn.kind==="failed_run"&&en.navigate(`/agents/${wn.run.agentId}/runs/${wn.run.id}`);break}default:return}},"handleKeyDown");return window.addEventListener("keydown",qe),()=>window.removeEventListener("keydown",qe)},[re,vn]),(0,m.useEffect)(()=>{if(gn<0||!ei.current)return;const qe=ei.current.querySelectorAll("[data-inbox-item]")[gn];qe&&qe.scrollIntoView({block:"nearest"})},[gn]),!e)return(0,t.jsx)(Vn,{icon:Ad,message:"Select a company to view inbox."});const Ha=qs.length>0,ci=p0e(W)&&rn,ii=ci&&!!le&&le.agents.error>0&&!Ha&&!T.has("alert:agent-errors"),Ua=ci&&!!le&&le.costs.monthBudgetCents>0&&le.costs.monthUtilizationPercent>=80&&!T.has("alert:budget"),Pr=ii||Ua,di=pt>0,Bi=s0e({tab:W,hasItems:Pr,showOnMine:!1,showOnRecent:!1,showOnUnread:!1,showOnAll:Pr}),Co=[Bi?"alerts":null,di?"work_items":null].filter(qe=>qe!==null),Fa=!we&&!se&&!fe&&!Ie&&!Be&&!it&&!De,pi=r(qe=>Co.indexOf(qe)>0,"showSeparatorBefore"),_o=(W==="mine"?ss:ln).filter(qe=>qe.isUnreadForMe&&!Lr.has(qe.id)&&!$e.has(qe.id)).map(qe=>qe.id),Ed=_o.length>0,Xc=V9(z,!0);return(0,t.jsxs)("div",{className:"space-y-6",children:[(0,t.jsxs)("div",{className:"space-y-2",children:[(0,t.jsxs)("div",{className:"relative sm:hidden",children:[(0,t.jsx)(na,{className:"pointer-events-none absolute left-2.5 top-1/2 h-3.5 w-3.5 -translate-y-1/2 text-muted-foreground"}),(0,t.jsx)(ut,{type:"search",placeholder:"Search inbox…",value:f,onChange:r(qe=>x(qe.target.value),"onChange"),onKeyDown:r(qe=>{if(Jq({key:qe.key,isComposing:qe.nativeEvent.isComposing})){qe.currentTarget.blur();return}Qq({key:qe.key,isComposing:qe.nativeEvent.isComposing,currentValue:qe.currentTarget.value})&&qe.currentTarget.blur()},"onKeyDown"),className:"h-8 w-full pl-8 text-xs","data-page-search-target":"true"})]}),(0,t.jsxs)("div",{className:"flex flex-wrap items-center justify-between gap-2",children:[(0,t.jsx)(Pi,{value:W,onValueChange:r(qe=>i(`/inbox/${qe}`),"onValueChange"),children:(0,t.jsx)(Kc,{items:[{value:"mine",label:"Mine"},{value:"recent",label:"Recent"},{value:"unread",label:"Unread"},{value:"blocked",label:"Blocked"},{value:"all",label:"All"}]})}),(0,t.jsxs)("div",{className:"flex items-center gap-2",children:[(0,t.jsxs)("div",{className:"relative hidden sm:block",children:[(0,t.jsx)(na,{className:"pointer-events-none absolute left-2.5 top-1/2 h-3.5 w-3.5 -translate-y-1/2 text-muted-foreground"}),(0,t.jsx)(ut,{type:"search",placeholder:"Search inbox…",value:f,onChange:r(qe=>x(qe.target.value),"onChange"),onKeyDown:r(qe=>{if(Jq({key:qe.key,isComposing:qe.nativeEvent.isComposing})){qe.currentTarget.blur();return}Qq({key:qe.key,isComposing:qe.nativeEvent.isComposing,currentValue:qe.currentTarget.value})&&qe.currentTarget.blur()},"onKeyDown"),className:"h-8 w-(--sz-220px) pl-8 text-xs","data-page-search-target":"true"})]}),W==="blocked"?(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)(V_,{presentation:"legacy",state:z,onChange:Vr,activeFilterCount:Xc,agents:ie,creators:mr,projects:X?.map(qe=>({id:qe.id,name:qe.name})),labels:ne?.map(qe=>({id:qe.id,name:qe.name,color:qe.color})),currentUserId:Ke,enableExternalObjectFilters:G,enableRoutineVisibilityFilter:!0,buttonVariant:"outline",iconOnly:!0}),(0,t.jsxs)(ur,{children:[(0,t.jsx)(Nr,{asChild:!0,children:(0,t.jsx)($,{type:"button",variant:"outline",size:"icon",className:V("h-8 w-8 shrink-0",k!=="none"&&"bg-accent"),title:"Group",children:(0,t.jsx)(Wl,{className:"h-3.5 w-3.5"})})}),(0,t.jsx)(rr,{align:"end",className:"w-44 p-0",children:(0,t.jsx)("div",{className:"space-y-0.5 p-2",children:h5e.map(([qe,Pt])=>(0,t.jsxs)("button",{type:"button",className:V("flex w-full items-center justify-between rounded-sm px-2 py-1.5 text-sm",k===qe?"bg-accent/50 text-foreground":"text-muted-foreground hover:bg-accent/50"),onClick:r(()=>S(qe),"onClick"),children:[(0,t.jsx)("span",{children:Pt}),k===qe?(0,t.jsx)(us,{className:"h-3.5 w-3.5"}):null]},qe))})})]}),(0,t.jsx)(q5,{availableColumns:is,visibleColumnSet:It,onToggleColumn:Jn,onResetColumns:r(()=>Tr(Ck),"onResetColumns"),title:"Choose which inbox columns stay visible",iconOnly:!0}),(0,t.jsxs)(ur,{children:[(0,t.jsx)(Nr,{asChild:!0,children:(0,t.jsx)($,{type:"button",variant:"outline",size:"icon",className:"h-8 w-8 shrink-0",title:"Sort",children:(0,t.jsx)(Lp,{className:"h-3.5 w-3.5"})})}),(0,t.jsx)(rr,{align:"end",className:"w-48 p-0",children:(0,t.jsx)("div",{className:"space-y-0.5 p-2",children:p5e.map(([qe,Pt])=>(0,t.jsxs)("button",{type:"button",className:V("flex w-full items-center justify-between rounded-sm px-2 py-1.5 text-sm",C===qe?"bg-accent/50 text-foreground":"text-muted-foreground hover:bg-accent/50"),onClick:r(()=>_(qe),"onClick"),children:[(0,t.jsx)("span",{children:Pt}),C===qe?(0,t.jsx)(us,{className:"h-3.5 w-3.5"}):null]},qe))})})]})]}):W!=="blocked"?(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)($,{type:"button",variant:"outline",size:"icon",className:V("hidden h-8 w-8 shrink-0 sm:inline-flex",Cr&&"bg-accent"),onClick:pr,title:Cr?"Disable parent-child nesting":"Enable parent-child nesting",children:(0,t.jsx)(zg,{className:"h-3.5 w-3.5"})}),(0,t.jsx)(V_,{presentation:"legacy",state:z,onChange:Vr,activeFilterCount:Xc,agents:ie,creators:mr,projects:X?.map(qe=>({id:qe.id,name:qe.name})),labels:ne?.map(qe=>({id:qe.id,name:qe.name,color:qe.color})),currentUserId:Ke,enableExternalObjectFilters:G,enableRoutineVisibilityFilter:!0,buttonVariant:"outline",iconOnly:!0}),(0,t.jsxs)(ur,{children:[(0,t.jsx)(Nr,{asChild:!0,children:(0,t.jsx)($,{type:"button",variant:"outline",size:"icon",className:V("h-8 w-8 shrink-0",N!=="none"&&"bg-accent"),title:"Group",children:(0,t.jsx)(Wl,{className:"h-3.5 w-3.5"})})}),(0,t.jsx)(rr,{align:"end",className:"w-40 p-2",children:(0,t.jsx)("div",{className:"space-y-0.5",children:[["none","None"],["type","Type"],["assignee","Responsible"],["project","Project"],...oe?[["workspace","Workspace"]]:[]].map(([qe,Pt])=>(0,t.jsxs)("button",{type:"button",className:V("flex w-full items-center justify-between rounded-sm px-2 py-1.5 text-sm",N===qe?"bg-accent/50 text-foreground":"text-muted-foreground hover:bg-accent/50"),onClick:r(()=>En(qe),"onClick"),children:[(0,t.jsx)("span",{children:Pt}),N===qe?(0,t.jsx)(us,{className:"h-3.5 w-3.5"}):null]},qe))})})]}),(0,t.jsx)(q5,{availableColumns:is,visibleColumnSet:It,onToggleColumn:Jn,onResetColumns:r(()=>Tr(Ck),"onResetColumns"),title:"Choose which inbox columns stay visible",iconOnly:!0}),Ed&&(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)($,{type:"button",variant:"outline",size:"sm",className:"h-8 shrink-0",onClick:r(()=>hs(!0),"onClick"),disabled:al.isPending,children:al.isPending?"Marking…":"Mark all as read"}),(0,t.jsx)(zs,{open:Oa,onOpenChange:hs,children:(0,t.jsxs)(Ws,{className:"sm:max-w-md",children:[(0,t.jsxs)(on,{children:[(0,t.jsx)(Vs,{children:"Mark all as read?"}),(0,t.jsxs)(hn,{children:["This will mark ",_o.length," unread ",_o.length===1?"item":"items"," as read."]})]}),(0,t.jsxs)(dr,{children:[(0,t.jsx)($,{variant:"outline",onClick:r(()=>hs(!1),"onClick"),children:"Cancel"}),(0,t.jsx)($,{onClick:r(()=>{hs(!1),al.mutate(_o)},"onClick"),children:"Mark all as read"})]})]})})]})]}):null]})]})]}),W==="all"&&(0,t.jsxs)("div",{className:"flex flex-wrap items-center gap-2",children:[(0,t.jsxs)(ka,{value:B,onValueChange:r(qe=>Ps(qe),"onValueChange"),children:[(0,t.jsx)(wa,{className:"h-8 w-(--sz-170px) text-xs",children:(0,t.jsx)(Na,{placeholder:"Category"})}),(0,t.jsxs)(Sa,{children:[(0,t.jsx)(dn,{value:"everything",children:"All categories"}),(0,t.jsx)(dn,{value:"issues_i_touched",children:"My recent tasks"}),(0,t.jsx)(dn,{value:"join_requests",children:"Join requests"}),(0,t.jsx)(dn,{value:"approvals",children:"Approvals"}),(0,t.jsx)(dn,{value:"failed_runs",children:"Failed runs"}),(0,t.jsx)(dn,{value:"alerts",children:"Alerts"})]})]}),Xt&&(0,t.jsxs)(ka,{value:q,onValueChange:r(qe=>jn(qe),"onValueChange"),children:[(0,t.jsx)(wa,{className:"h-8 w-(--sz-170px) text-xs",children:(0,t.jsx)(Na,{placeholder:"Approval status"})}),(0,t.jsxs)(Sa,{children:[(0,t.jsx)(dn,{value:"all",children:"All approval statuses"}),(0,t.jsx)(dn,{value:"actionable",children:"Needs action"}),(0,t.jsx)(dn,{value:"resolved",children:"Resolved"})]})]})]}),ce&&(0,t.jsx)("p",{className:"text-sm text-destructive",children:ce.message}),d&&(0,t.jsx)("p",{className:"text-sm text-destructive",children:d}),W==="blocked"?(0,t.jsx)(x5e,{presentation:"legacy",companyId:e,searchQuery:f,agentNameById:Ot,userLabelById:Ls,issueLinkState:re,groupBy:k,sortBy:C,issueFilters:z,currentUserId:Ke,liveIssueIds:mt,subtreeLiveCounts:Sr,workspaceFilterContext:Ut,showStatusColumn:It.has("status")&&bs.has("status"),showIdentifierColumn:It.has("id")&&bs.has("id"),showUpdatedColumn:It.has("updated")&&bs.has("updated")}):null,W!=="blocked"&&!Fa&&Co.length===0&&(0,t.jsx)(Pa,{variant:"inbox"}),W!=="blocked"&&Fa&&Co.length===0&&(0,t.jsx)(Vn,{icon:f.trim()?na:Ad,message:f.trim()?"No inbox items match your search.":W==="mine"?"Inbox zero.":W==="unread"?"No new inbox items.":W==="recent"?"No recent inbox items.":"No inbox items match these filters."}),W!=="blocked"&&di&&(0,t.jsxs)(t.Fragment,{children:[pi("work_items")&&(0,t.jsx)(Ul,{}),(0,t.jsx)("div",{children:(0,t.jsx)("div",{ref:ei,className:"overflow-hidden",onPointerDownCapture:vn,onWheelCapture:vn,children:(()=>{const qe=r(({issue:Kt,depth:Ds,selected:en,hasChildren:ti=!1,isExpanded:Ta=!1,childCount:ct=0,collapseParentId:fs=null,allowArchive:Ks=Q})=>{const Sn=Kt.isUnreadForMe&&!Lr.has(Kt.id),Xn=Lr.has(Kt.id),wn=$e.has(Kt.id),la=Kt.projectId?Re.get(Kt.projectId)??null:null,Qa=Kt.assigneeUserId?Ue.get(Kt.assigneeUserId)??null:null,Qe=T4(Kt),Ft=Qe?.kind==="user"?Qe.id:null,vs=Qe?.kind==="user"?Qe.viaAgentId??null:null,Ne=mt.has(Kt.id),Ge=Sr.get(Kt.id)??0,Dt=yG(Kt,Ge),Tt=jG(Kt,{isLive:Ne,loadedSubtreeLiveCount:Ge}),Qs=It.has("status")&&bs.has("status"),Ir=!(Qs&&Kt.status==="blocked"&&Tt?.state==="covered"),ys=(0,t.jsx)(no,{status:Kt.status,externalConversationState:Kt.externalConversationState,blockerAttention:Tt,size:"md"});return(0,t.jsx)(bj,{issue:Kt,issueLinkState:re,treeGuides:Ds,selected:en,className:wn?"pointer-events-none -translate-x-4 scale-(--s-0_98) opacity-0 transition-all duration-200 ease-out":"transition-all duration-200 ease-out",desktopMetaLeading:(0,t.jsxs)(t.Fragment,{children:[Cr?Ds===0&&ti&&fs?(0,t.jsx)("button",{type:"button","data-slot":"icon-button",className:"hidden w-4 shrink-0 items-center justify-center sm:inline-flex",onClick:r(Ar=>{Ar.preventDefault(),Ar.stopPropagation(),Is(fs)},"onClick"),children:(0,t.jsx)(Pn,{className:V("h-3.5 w-3.5 transition-transform",Ta&&"rotate-90")})}):(0,t.jsx)("span",{className:"hidden w-4 shrink-0 sm:block"}):null,(0,t.jsx)(R0e,{issue:Kt,isLive:Ne,subtreeLiveCount:Dt,showSubtreeLiveChip:Ir,showStatus:Qs,showIdentifier:It.has("id")&&bs.has("id"),statusSlot:ys})]}),titleSuffix:ti&&!Ta&&Ds===0?(0,t.jsxs)("span",{className:"ml-1.5 text-xs text-muted-foreground",children:["(",ct," sub-task",ct!==1?"s":"",")"]}):void 0,mobileMeta:Xqe(Kt).toLowerCase(),mobileLeading:Ds===0&&ti&&fs?(0,t.jsx)("button",{type:"button","data-slot":"icon-button",onClick:r(Ar=>{Ar.preventDefault(),Ar.stopPropagation(),Is(fs)},"onClick"),children:(0,t.jsx)(Pn,{className:V("h-3.5 w-3.5 transition-transform",Ta&&"rotate-90")})}):(0,t.jsx)(no,{status:Kt.status,externalConversationState:Kt.externalConversationState,blockerAttention:Tt,size:"md"}),unreadState:Sn?"visible":Xn?"fading":"hidden",onMarkRead:r(()=>Hi.mutate(Kt.id),"onMarkRead"),onArchive:Ks?()=>Mi.mutate(Kt.id):void 0,archiveDisabled:wn,desktopTrailing:Os.length>0?(0,t.jsx)(A0e,{issue:Kt,columns:Os,projectName:la?.name??null,projectColor:la?.color??null,workspaceName:x0e(Kt,{executionWorkspaceById:_t,projectWorkspaceById:wt,defaultProjectWorkspaceIdByProjectId:Oe}),assigneeName:an(Kt.assigneeAgentId),assigneeAgent:ie?.find(Ar=>Ar.id===Kt.assigneeAgentId),creatorAgent:ie?.find(Ar=>Ar.id===Kt.createdByAgentId),assigneeUserName:Bm(Kt.assigneeUserId,Ke,Ls)??Qa?.label??null,assigneeUserAvatarUrl:Qa?.image??null,creatorAgentName:an(Kt.createdByAgentId),creatorUserName:Ft?Ue.get(Ft)?.label??null:null,creatorUserAvatarUrl:Ft?Ue.get(Ft)?.image??null:null,viaAgentName:vs?an(vs):null,currentUserId:Ke,parentIdentifier:Kt.parentId?Es.get(Kt.parentId)?.identifier??null:null,parentTitle:Kt.parentId?Es.get(Kt.parentId)?.title??null:null}):void 0},`issue:${Kt.id}`)},"renderInboxIssue");let Pt=Number.POSITIVE_INFINITY;return Nn.flatMap((Kt,Ds)=>{const en=[],ti=Or.has(Kt.key);if(Kt.searchSection!=="none"&&Kt.searchSection!==Nn[Ds-1]?.searchSection&&en.push((0,t.jsxs)("div",{className:"flex items-center gap-3 border-y border-border/70 bg-muted/30 px-4 py-2",children:[(0,t.jsx)("div",{className:"h-px flex-1 bg-border/80"}),(0,t.jsx)("span",{className:"shrink-0 text-(length:--text-micro) font-semibold uppercase tracking-wide text-muted-foreground",children:Kt.searchSection==="archived"?"Archived":"Other results"}),(0,t.jsx)("div",{className:"h-px flex-1 bg-border/80"})]},`${Kt.searchSection}-search-divider`)),Kt.label){const Ta=As.get(Kt.key)??-1,ct=Ta>=0&&gn===Ta,fs=Kt.displayItems.some(Ks=>Ks.kind==="issue");en.push((0,t.jsx)("div",{"data-inbox-item":!0,className:V(Ds>0&&"pt-2"),onClick:r(()=>{Ta>=0&&_r(Ta)},"onClick"),onMouseEnter:r(()=>{Ta>=0&&Va(Ta)},"onMouseEnter"),children:(0,t.jsx)("div",{className:V("rounded-lg px-3 sm:pl-0 sm:pr-4",ct?"bg-accent/50":"hover:bg-accent/50"),children:(0,t.jsx)(vj,{label:Kt.label,collapsible:!0,collapsed:ti,onToggle:r(()=>xa(Kt.key),"onToggle"),trailing:fs?(0,t.jsx)($,{variant:"ghost",size:"icon-xs",className:"-mr-2 text-muted-foreground",title:`New task in ${Kt.label}`,"aria-label":`New task in ${Kt.label}`,onClick:r(Ks=>{Ks.stopPropagation(),Un(Kt)},"onClick"),children:(0,t.jsx)(bn,{className:"h-3 w-3"})}):null})})},`group-${Kt.key}`))}if(ti)return en;for(let Ta=0;Ta<Kt.displayItems.length;Ta+=1){const ct=Kt.displayItems[Ta],fs=aa.get(`${Kt.key}:${ag(ct)}`)??0,Ks=r((Dt,Tt,Qs)=>(0,t.jsx)("div",{"data-inbox-item":!0,className:"relative",onClick:r(()=>_r(fs),"onClick"),onMouseEnter:r(()=>Va(fs),"onMouseEnter"),children:Qs},`sel-${Dt}`),"wrapItem"),Sn=Date.now()-864e5,Xn=N==="none"&&ct.timestamp>0&&ct.timestamp<Sn&&Pt>=Sn;Pt=ct.timestamp>0?ct.timestamp:Pt,Xn&&en.push((0,t.jsxs)("div",{className:"my-2 flex items-center gap-3 px-4",children:[(0,t.jsx)("div",{className:"flex-1 border-t border-zinc-600"}),(0,t.jsx)("span",{className:"shrink-0 text-(length:--text-micro) font-medium uppercase tracking-wider text-zinc-500",children:"Earlier"})]},`today-divider-${Kt.key}-${Ta}`));const wn=gn===fs;if(ct.kind==="approval"){const Dt=`approval:${ct.approval.id}`,Tt=Jt.has(Dt),Qs=(0,t.jsx)(AMt,{approval:ct.approval,selected:wn,requesterName:an(ct.approval.requestedByAgentId),onApprove:r(()=>Fs.mutate(ct.approval.id),"onApprove"),onReject:r(()=>nr.mutate(ct.approval.id),"onReject"),isPending:Fs.isPending||nr.isPending,unreadState:xt(Dt),onMarkRead:r(()=>Zi(Dt),"onMarkRead"),onArchive:Q?()=>be(Dt):void 0,archiveDisabled:Tt,className:Tt?"pointer-events-none -translate-x-4 scale-(--s-0_98) opacity-0 transition-all duration-200 ease-out":"transition-all duration-200 ease-out"},Dt);en.push(Ks(Dt,wn,Q?(0,t.jsx)(If,{selected:wn,disabled:Tt,onArchive:r(()=>be(Dt),"onArchive"),children:Qs},Dt):(0,t.jsx)(JC,{selected:wn,children:Qs})));continue}if(ct.kind==="failed_run"){const Dt=`run:${ct.run.id}`,Tt=Jt.has(Dt),Qs=(0,t.jsx)(IMt,{run:ct.run,selected:wn,issueById:Es,agentName:an(ct.run.agentId),issueLinkState:re,onDismiss:r(()=>O(Dt),"onDismiss"),onRetry:r(()=>xn.mutate(ct.run),"onRetry"),isRetrying:_e.has(ct.run.id),unreadState:xt(Dt),onMarkRead:r(()=>Zi(Dt),"onMarkRead"),onArchive:Q?()=>be(Dt):void 0,archiveDisabled:Tt,className:Tt?"pointer-events-none -translate-x-4 scale-(--s-0_98) opacity-0 transition-all duration-200 ease-out":"transition-all duration-200 ease-out"},Dt);en.push(Ks(Dt,wn,Q?(0,t.jsx)(If,{selected:wn,disabled:Tt,onArchive:r(()=>be(Dt),"onArchive"),children:Qs},Dt):(0,t.jsx)(JC,{selected:wn,children:Qs})));continue}if(ct.kind==="join_request"){const Dt=`join:${ct.joinRequest.id}`,Tt=Jt.has(Dt),Qs=(0,t.jsx)(TMt,{joinRequest:ct.joinRequest,selected:wn,onApprove:r(()=>un.mutate(ct.joinRequest),"onApprove"),onReject:r(()=>Gr.mutate(ct.joinRequest),"onReject"),isPending:un.isPending||Gr.isPending,unreadState:xt(Dt),onMarkRead:r(()=>Zi(Dt),"onMarkRead"),onArchive:Q?()=>be(Dt):void 0,archiveDisabled:Tt,className:Tt?"pointer-events-none -translate-x-4 scale-(--s-0_98) opacity-0 transition-all duration-200 ease-out":"transition-all duration-200 ease-out"},Dt);en.push(Ks(Dt,wn,Q?(0,t.jsx)(If,{selected:wn,disabled:Tt,onArchive:r(()=>be(Dt),"onArchive"),children:Qs},Dt):(0,t.jsx)(JC,{selected:wn,children:Qs})));continue}const la=ct.issue,Qa=Kt.childrenByIssueId.get(la.id)??[],Qe=Qa.length>0,Ft=Qe&&!Cn.has(la.id),vs=Q&&Kt.searchSection==="none",Ne=r((Dt,Tt,Qs)=>Dt.flatMap(Ir=>{if(Qs.has(Ir.id))return[];const ys=new Set(Qs);ys.add(Ir.id);const Ar=Da.get(Ir.id)??-1,os=gn===Ar,zi=Kt.childrenByIssueId.get(Ir.id)??[],Fr=zi.length>0,Kr=Fr&&!Cn.has(Ir.id),er=qe({issue:Ir,depth:Tt,selected:os,hasChildren:Fr,isExpanded:Kr,childCount:zi.length,collapseParentId:Ir.id,allowArchive:vs}),Mr=$e.has(Ir.id),Ja=(0,t.jsx)("div",{"data-inbox-item":!0,className:"relative",onClick:r(()=>{Ar>=0&&_r(Ar)},"onClick"),onMouseEnter:r(()=>{Ar>=0&&Va(Ar)},"onMouseEnter"),children:vs?(0,t.jsx)(If,{selected:os,disabled:Mr,onArchive:r(()=>Mi.mutate(Ir.id),"onArchive"),children:er},`issue:${Ir.id}`):(0,t.jsx)(JC,{selected:os,children:er})},`sel-issue:${Ir.id}`);return Kr?[Ja,...Ne(zi,Tt+1,ys)]:[Ja]}),"renderChildIssueRows"),Ge=qe({issue:la,depth:0,selected:wn,hasChildren:Qe,isExpanded:Ft,childCount:Qa.length,collapseParentId:la.id,allowArchive:vs});en.push(Ks(`issue:${la.id}`,wn,vs?(0,t.jsx)(If,{selected:wn,disabled:$e.has(la.id),onArchive:r(()=>Mi.mutate(la.id),"onArchive"),children:Ge},`issue:${la.id}`):(0,t.jsx)(JC,{selected:wn,children:Ge}))),Ft&&en.push(...Ne(Qa,1,new Set([la.id])))}return en})})()})})]}),Bi&&(0,t.jsxs)(t.Fragment,{children:[pi("alerts")&&(0,t.jsx)(Ul,{}),(0,t.jsxs)("div",{children:[(0,t.jsx)("h3",{className:"mb-3 text-sm font-semibold uppercase tracking-wide text-muted-foreground",children:"Alerts"}),(0,t.jsxs)("div",{className:"divide-y divide-border border border-border",children:[ii&&(0,t.jsxs)("div",{className:"group/alert relative flex items-center gap-3 px-4 py-3 transition-colors hover:bg-accent/50",children:[(0,t.jsxs)(We,{to:"/agents",className:"flex flex-1 cursor-pointer items-center gap-3 no-underline text-inherit",children:[(0,t.jsx)(Rs,{className:"h-4 w-4 shrink-0 text-red-600 dark:text-red-400"}),(0,t.jsxs)("span",{className:"text-sm",children:[(0,t.jsx)("span",{className:"font-medium",children:le.agents.error})," ",le.agents.error===1?"agent has":"agents have"," errors"]})]}),(0,t.jsx)("button",{type:"button",onClick:r(()=>E("alert:agent-errors"),"onClick"),className:"rounded-md p-1 text-muted-foreground opacity-0 transition-opacity hover:bg-accent hover:text-foreground group-hover/alert:opacity-100","aria-label":"Dismiss",children:(0,t.jsx)(zn,{className:"h-3.5 w-3.5"})})]}),Ua&&(0,t.jsxs)("div",{className:"group/alert relative flex items-center gap-3 px-4 py-3 transition-colors hover:bg-accent/50",children:[(0,t.jsxs)(We,{to:"/costs",className:"flex flex-1 cursor-pointer items-center gap-3 no-underline text-inherit",children:[(0,t.jsx)(Rs,{className:"h-4 w-4 shrink-0 text-yellow-400"}),(0,t.jsxs)("span",{className:"text-sm",children:["Budget at"," ",(0,t.jsxs)("span",{className:"font-medium",children:[le.costs.monthUtilizationPercent,"%"]})," ","utilization this month"]})]}),(0,t.jsx)("button",{type:"button",onClick:r(()=>E("alert:budget"),"onClick"),className:"rounded-md p-1 text-muted-foreground opacity-0 transition-opacity hover:bg-accent hover:text-foreground group-hover/alert:opacity-100","aria-label":"Dismiss",children:(0,t.jsx)(zn,{className:"h-3.5 w-3.5"})})]})]})]})]})]})}r(RMt,"Inbox$1");var lce=200,_0=500,zR=3e4,EMt="inbox",PMt={allCategoryFilter:"everything",allApprovalFilter:"all",issueFilters:{...k0e},showDateGroupSeparators:!0};function MMt(e){const s=e&&typeof e=="object"?e:{},n=s.allCategoryFilter,a=s.allApprovalFilter;return{allCategoryFilter:n==="issues_i_touched"||n==="join_requests"||n==="approvals"||n==="failed_runs"||n==="alerts"?n:"everything",allApprovalFilter:a==="actionable"||a==="resolved"?a:"all",issueFilters:{...Jqe(s.issueFilters),workspaces:[]},showDateGroupSeparators:s.showDateGroupSeparators!==!1}}r(MMt,"normalizeInboxCollectionViewState");function f8(e){return{companyId:e??"__unscoped__",collectionKey:EMt,legacyViewStorageKey:e?`${$qe}:${e}`:void 0,legacyColumnsStorageKey:Yqe}}r(f8,"inboxCollectionPreferenceLocation");function WB(e){return Hqe({...f8(e),defaultViewState:PMt,defaultColumns:Ck,normalizeViewState:MMt,normalizeColumns:r(s=>Array.isArray(s)?q9(s):Ck,"normalizeColumns")})}r(WB,"loadInboxCollectionPreferences");var qR=r(e=>e?e.type==="top"?`top:${e.itemKey}`:e.type==="child"?`child:${e.issueId}`:`group:${e.groupKey}`:null,"navEntryKey");function cce(e){return e?e.split(`
@@ -665,7 +665,7 @@ Last resolved: user values resolve per member`;return(0,t.jsxs)("div",{role:"row
665
665
 
666
666
  Review the **original** file.`,markdown:!0,downloadUrl:"data:text/markdown,%23%20Project%20notes"}),(0,t.jsx)(b8,{title:"notes.txt",text:"Plain text stays literal: <example>",markdown:!1,downloadUrl:"data:text/plain,Plain%20text"})]})]}),(0,t.jsxs)(yr,{title:"Connection recovery",children:[(0,t.jsx)(tr,{title:"Waiting for server",children:(0,t.jsx)(C3,{temporary:!0,retrying:!1,onRetry:r(()=>{},"onRetry")})}),(0,t.jsx)(tr,{title:"Checking connection",children:(0,t.jsx)(C3,{temporary:!0,retrying:!0,onRetry:r(()=>{},"onRetry")})}),(0,t.jsx)(tr,{title:"Access check failed",children:(0,t.jsx)(C3,{temporary:!1,retrying:!1,onRetry:r(()=>{},"onRetry")})})]}),(0,t.jsxs)(yr,{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)(mPe,{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)(yr,{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)(CIe,{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)(yr,{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)(ZU,{id:"design-image",title:"Launch artwork",contentPath:"/announcement-preview.svg",contentType:"image/svg+xml",originalFilename:"launch.svg",detail:"Image"}),(0,t.jsx)(ZU,{id:"design-video",title:"Video preview unavailable",contentPath:"",contentType:"video/mp4",originalFilename:"preview.mp4",detail:"Video"})]})]}),(0,t.jsx)(yr,{title:"AI Connections",children:(0,t.jsx)(uds,{})}),(0,t.jsxs)(yr,{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)(KN,{status:"needs_setup"}),(0,t.jsx)(KN,{status:"pending_approval"}),(0,t.jsx)(KN,{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(Jds,"DesignGuide");function Xds(){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)($Le,{candidates:e,selected:s,excludedFolders:a,onChange:r((o,l)=>{n(o),i(l)},"onChange")})}r(Xds,"SkillSourceTreeShowcase");function Zds(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(Zds,"resolveWorktreeRunExecutionDisplayState");function eus(e){const s=new Date(e);return Number.isNaN(s.getTime())?e:s.toLocaleString(void 0,{dateStyle:"medium",timeStyle:"short"})}r(eus,"formatActivationTimestamp");function T$e(){return(0,t.jsxs)(ot,{variant:"outline",className:"text-muted-foreground",children:[(0,t.jsx)(No,{"aria-hidden":"true"}),"Managed by Paperclip Cloud"]})}r(T$e,"ManagedByCloudBadge");function Yi({title:e,description:s,footnote:n,checked:a,onCheckedChange:i,disabled:o,settingKey:l,managed:c,ariaLabel:d}){const{hidden:u}=vu(),h=c?.managed===!0;return u.has(gge(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)(T$e,{}):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)(ri,{checked:a,onCheckedChange:r(p=>{h||i(p)},"onCheckedChange"),disabled:o||h,"aria-label":d})]})})}r(Yi,"ExperimentalToggleCard");function tus(){const{setBreadcrumbs:e}=Hn(),s=Nt(),{hidden:n}=vu(),[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(()=>vr.getExperimental(),"queryFn")}),l=ye({mutationFn:r(async G=>vr.updateExperimental(G),"mutationFn"),onMutate:r(async G=>{await s.cancelQueries({queryKey:D.instance.experimentalSettings});const Z=s.getQueryData(D.instance.experimentalSettings);return Z&&s.setQueryData(D.instance.experimentalSettings,{...Z,...G}),{previousSettings:Z}},"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,Z,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=Xdt(),d=o.data?.managedKeys??{},u=o.data?.enableWorktreeRunExecution===!0,h=d.enableWorktreeRunExecution?.managed===!0,p=Zds(o.data,Zdt()),f=o.data?.enableEnvironments===!0,x=o.data?.enableNativeRunner===!0,b=o.data?.enableChatConnectors===!0,v=o.data?.enableManagedSandboxOnly===!0,j=o.data?.enableIsolatedWorkspaces===!0,N=o.data?.enableIsolatedWorkspacesByDefault===!0,w=o.data?.enableStreamlinedUi!==!1;o.data?.enableConferenceRoomChat;const k=o.data?.enableClassicTaskInterface===!0,S=o.data?.enableIssuePlanDecompositions===!0,C=o.data?.enableExperimentalFileViewer===!0,_=o.data?.enableExternalObjects===!0,R=o.data?.enableBuiltInAgents===!0,A=o.data?.enableBetaSkills===!0,T=o.data?.enableSummaries===!0,E=o.data?.enableStatusCards===!0,L=d.enableSummaries?.managed===!0,O=d.enableStatusCards?.managed===!0,P=L&&!T,U=O&&E,M=o.data?.enableDecisions===!0,B=o.data?.enableGoalsSidebarLink===!0,q=o.data?.enableCases===!0,z=o.data?.enableServerInfoDebugView===!0,K=o.data?.enablePaperclipDeveloperMode===!0,W=o.data?.enableSimplifiedEnglishInteractions===!0,Q=o.data?.enableFirstTaskPlanProposal===!0,re=o.data?.enableSmokeLab===!0,J=o.data?.autoRestartDevServerWhenIdle===!0,ie=r(G=>!n.has(gge(G)),"isVisible"),X=c&&ie("enableWorktreeRunExecution"),ne=X||["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)(Vm,{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)(Rs,{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)(Yi,{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)(Yi,{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)(Yi,{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:A,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)(Yi,{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)(Yi,{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)(Yi,{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:b,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)(Yi,{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)(Yi,{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:M,onCheckedChange:r(G=>l.mutate({enableDecisions:G}),"onCheckedChange"),disabled:l.isPending,settingKey:"enableDecisions",managed:d.enableDecisions,ariaLabel:"Toggle decisions experimental setting"}),(0,t.jsx)(Yi,{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)(Yi,{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)(Yi,{title:"Enable Isolated Workspaces",description:"Show execution workspace controls in project configuration and allow isolated workspace behavior for new and existing task runs.",checked:j,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)(Yi,{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)(Yi,{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)(Yi,{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:Q,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)(Yi,{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)(Yi,{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)(Yi,{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)(Yi,{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)(Yi,{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)(Yi,{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:W,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)(Yi,{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||P,settingKey:"enableStatusCards",managed:d.enableStatusCards,ariaLabel:"Toggle status cards experimental setting"}),(0,t.jsx)(Yi,{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)(Yi,{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||U,settingKey:"enableSummaries",managed:d.enableSummaries,ariaLabel:"Toggle summaries experimental setting"}),j&&(0,t.jsx)(Yi,{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:N,onCheckedChange:r(G=>l.mutate({enableIsolatedWorkspacesByDefault:G}),"onCheckedChange"),disabled:l.isPending,settingKey:"enableIsolatedWorkspacesByDefault",managed:d.enableIsolatedWorkspacesByDefault,ariaLabel:"Toggle isolated workspaces by default experimental setting"})]}),ne?(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)(Yi,{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:J,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)(Yi,{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)(Yi,{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"}),X?(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)(T$e,{}):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)(ri,{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)(mo,{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:eus(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)(Rs,{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)(Yi,{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)(Yi,{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:re,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)(Yi,{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)(Yi,{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:k,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)(Yi,{title:"Goals Sidebar Link",description:"Restore the Goals item in the main sidebar while the goals surface is being evaluated.",checked:B,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(tus,"InstanceExperimentalSettings");function sus(){const{userId:e,settled:s}=mx(),{setBreadcrumbs:n}=Hn(),{pushToast:a}=Ti(),i=Nt(),[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(()=>lr.searchAdminUsers(o),"queryFn")}),f=te({...aBe(e),enabled:s&&p.isSuccess}),x=f.data??[],b=(0,m.useMemo)(()=>p.data?.find(w=>w.id===c)??null,[c,p.data]),v=te({queryKey:D.access.userCompanyAccess(c??""),queryFn:r(()=>lr.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 j=ye({mutationFn:r(()=>lr.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")}),N=ye({mutationFn:r(async w=>{if(!c)throw new Error("No user selected");return w?lr.promoteInstanceAdmin(c):lr.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 mn&&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)(jA,{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)(Fi,{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:b?.name||b?.email||c}),(0,t.jsx)("div",{className:"text-sm text-muted-foreground",children:b?.email||c})]}),(0,t.jsx)($,{variant:b?.isInstanceAdmin?"outline":"default",onClick:r(()=>N.mutate(!(b?.isInstanceAdmin??!1)),"onClick"),disabled:N.isPending,children:b?.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)(Za,{checked:u.has(w.id),onCheckedChange:r(k=>{h(S=>{const C=new Set(S);return k?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(()=>j.mutate(),"onClick"),disabled:j.isPending,children:j.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(sus,"InstanceAccess");var Rxe={getMine:r(e=>Ce.get(`/companies/${e}/users/me/inbox-agent-policy`),"getMine"),updateMine:r((e,s)=>Ce.put(`/companies/${e}/users/me/inbox-agent-policy`,s),"updateMine")},nus=[{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 zE(e,s){return`${e}:${[...s].sort().join(",")}`}r(zE,"policyKey");function rus({companyId:e}){const s=Nt(),[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(()=>Rxe.getMine(e),"queryFn"),enabled:!!e}),l=o.data,c=te({queryKey:e?D.agents.list(e):["agents","none"],queryFn:r(()=>Ct.list(e),"queryFn"),enabled:!!e}),d=(0,m.useMemo)(()=>(c.data??[]).filter(Zf),[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=zE(l.mode,l.allowedAgentIds);a(b=>b===null||zE(b.mode,b.allowedAgentIds)===i.current?{mode:l.mode,allowedAgentIds:l.allowedAgentIds}:b),i.current=x},[l]);const p=ye({mutationFn:r(x=>Rxe.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&&zE(n.mode,n.allowedAgentIds)!==zE(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)(Ad,{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)(Lm,{ariaLabel:"Inbox agent archiving policy",value:n.mode,onValueChange:r(x=>a(b=>b&&{...b,mode:x}),"onValueChange"),options:nus,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)(yj,{agents:u,selectedAgentIds:h,onChange:r(x=>a(b=>b&&{...b,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)(tt,{className:"size-4 animate-spin"}):(0,t.jsx)(qf,{className:"size-4"}),p.isPending?"Saving…":"Save"]})]})]})}r(rus,"InboxAgentPolicyControl");var aus={granted:"Allowed",denied:"Blocked in browser settings",default:"Not requested yet",unsupported:"Not supported in this browser"},Exe={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 ius(){const[e,s]=(0,m.useState)({});return(0,m.useEffect)(()=>{let n=!1;const a=r(()=>{Promise.all(xA.map(async o=>[o,(await D3e(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=P3e(a);return()=>{n=!0,i()}},[]),e}r(ius,"useCustomSoundNames");function ous({kind:e,customName:s,disabled:n,onError:a}){const i=V3e(),o=i.kinds[e],l=(0,m.useId)(),[c,d]=(0,m.useState)(!1),u=S3t[e];async function h(x){const b=R3e(x);if(!b.ok){a(`${u}: ${b.error}`);return}d(!0);try{await w3t(e,x),MR(e,{soundId:Ile}),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 N3t(e),$g().kinds[e].soundId==="custom"&&MR(e,{soundId:TM[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)(ri,{checked:o.enabled,onCheckedChange:r(x=>MR(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)(ka,{value:o.soundId,onValueChange:r(x=>MR(e,{soundId:x}),"onValueChange"),disabled:f,children:[(0,t.jsx)(wa,{className:"min-w-0 flex-1 sm:w-(--sz-170px) sm:flex-none","aria-label":`${u} sound`,children:(0,t.jsx)(Na,{})}),(0,t.jsxs)(Sa,{children:[L3e.map(x=>(0,t.jsx)(dn,{value:x.id,children:x.label},x.id)),s?(0,t.jsxs)(dn,{value:Ile,children:["Custom: ",s]}):null,(0,t.jsx)(dn,{value:k3t,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(()=>{z3e(e,o.soundId,i.volume)},"onClick"),children:(0,t.jsx)(mo,{})}),(0,t.jsx)("input",{id:l,type:"file",accept:"audio/*",className:"sr-only",disabled:f||c,onChange:r(x=>{const b=x.target.files?.[0];x.target.value="",b&&h(b)},"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)(tt,{className:"animate-spin"}):(0,t.jsx)(Uy,{}),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)(da,{})}):null]})]})}r(ous,"KindRow");function lus({userId:e}){const s=V3e(),n=L3t(),a=ius(),[i,o]=(0,m.useState)(()=>I_()),[l,c]=(0,m.useState)(null),[d,u]=(0,m.useState)(null),[h,p]=(0,m.useState)(!1),f=I3e(),x=n.status==="active",b=(0,m.useCallback)(()=>{e&&c8($g(),e)},[e]);async function v(){const S=await d3t();return o(S),S==="granted"&&b(),S}r(v,"askPermission");async function j(S){M3(C=>({...C,enabled:S})),S&&I_()==="default"&&await v()}r(j,"setEnabled");async function N(S){M3(C=>({...C,pushEnabled:S})),S&&I_()==="default"&&await v()}r(N,"setPushEnabled");async function w(){p(!0),c(null),u(null);try{const S=await EM.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 k=!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)(jKe,{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)(ri,{checked:s.enabled,onCheckedChange:r(S=>{j(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:aus[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?Exe[n.status]:Exe.unsupported,n.error?`: ${n.error}`:""]})]}),(0,t.jsx)(ri,{checked:s.pushEnabled,onCheckedChange:r(S=>{N(S)},"onCheckedChange"),disabled:k||!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,u3t()?(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:k,onChange:r(S=>M3(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:xA.map(S=>(0,t.jsx)(ous,{kind:S,customName:a[S],disabled:k,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||k,children:[h?(0,t.jsx)(tt,{className:"animate-spin"}):(0,t.jsx)(zA,{}),"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(lus,"NotificationSettingsSection");function cus(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(cus,"deriveInitials");function dus(){const{setBreadcrumbs:e}=Hn(),{selectedCompanyId:s,selectedCompany:n}=ps(),a=Nt(),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(()=>Ma.getSession(),"queryFn"),retry:!1});(0,m.useEffect)(()=>{e([{label:"Settings",href:"/company/settings"},{label:"Profile"}])},[e]),(0,m.useEffect)(()=>{const A=f.data;A&&(c(A.user.name??""),u(A.user.image??""))},[f.data]);function x(A){a.setQueryData(D.auth.session,T=>T&&{...T,user:{...T.user,...A}})}r(x,"syncSessionProfile");async function b(A){const T=await Ma.updateProfile(A);return x(T),T}r(b,"persistProfile");function v(){return l.trim()||f.data?.user.name||"Board"}r(v,"resolveProfileName");const j=ye({mutationFn:r(A=>b(A),"mutationFn"),onSuccess:r(A=>{p(null),c(A.name??""),u(A.image??"")},"onSuccess"),onError:r(A=>{p(A instanceof Error?A.message:"Failed to update profile.")},"onError")}),N=ye({mutationFn:r(async A=>{if(!s)throw new Error("Select an organization before uploading a profile avatar.");const T=await qb.uploadImage(s,A,`profiles/${f.data?.user.id??"board-user"}`);return b({name:v(),image:T.contentPath})},"mutationFn"),onSuccess:r(A=>{p(null),c(A.name??""),u(A.image??"")},"onSuccess"),onError:r(A=>{p(A instanceof Error?A.message:"Failed to upload avatar.")},"onError")}),w=ye({mutationFn:r(()=>b({name:v(),image:null}),"mutationFn"),onSuccess:r(A=>{p(null),c(A.name??""),u(A.image??"")},"onSuccess"),onError:r(A=>{p(A instanceof Error?A.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 k=l.trim()||f.data.user.name||"Board",S=d.trim()||null,C=cus(k),_=j.isPending||N.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)(U4,{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(A=>{const T=A.target.files?.[0];T&&(N.mutate(T),A.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:N.isPending?(0,t.jsx)(tt,{className:"size-4 animate-spin"}):(0,t.jsx)(mee,{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)(Hc,{src:S,alt:k}):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:[N.isPending?(0,t.jsx)(tt,{className:"size-4 animate-spin"}):(0,t.jsx)(mee,{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)(tt,{className:"size-4 animate-spin"}):(0,t.jsx)(da,{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:k}),(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(A=>{A.preventDefault(),j.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)(ut,{id:"profile-name",value:l,onChange:r(A=>c(A.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)(ut,{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:[j.isPending?(0,t.jsx)(tt,{className:"size-4 animate-spin"}):(0,t.jsx)(qf,{className:"size-4"}),j.isPending?"Saving...":"Save profile"]})})]}),(0,t.jsx)(rus,{companyId:s}),(0,t.jsx)(lus,{userId:f.data.user.id??null})]})]})}r(dus,"ProfileSettings");function uus(e){return e?e.split(/\r?\n/).map(s=>s.trim()).find(Boolean)??null:null}r(uus,"firstNonEmptyLine");function Pxe(e){return uus(e.lastError)??"Plugin entered an error state without a stored error message."}r(Pxe,"getPluginErrorSummary");function Mxe(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(Mxe,"isExperimentalPluginIdentity");function Dxe(){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(Dxe,"ExperimentalBadge");function mus(){const{selectedCompany:e}=ps(),{setBreadcrumbs:s}=Hn(),n=Nt(),{pushToast:a}=Qr(),[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:b,isLoading:v,error:j}=te({queryKey:D.plugins.all,queryFn:r(()=>Rl.list(),"queryFn")}),N=te({queryKey:D.plugins.examples,queryFn:r(()=>Rl.listBundled(),"queryFn")}),w=r(()=>{n.invalidateQueries({queryKey:D.plugins.all}),n.invalidateQueries({queryKey:D.plugins.examples}),n.invalidateQueries({queryKey:D.plugins.uiContributions})},"invalidatePluginQueries"),k=ye({mutationFn:r(P=>Rl.install(P),"mutationFn"),onSuccess:r(()=>{w(),c(!1),o(""),a({title:"Plugin installed successfully",tone:"success"})},"onSuccess"),onError:r(P=>{a({title:"Failed to install plugin",body:P.message,tone:"error"})},"onError")}),S=ye({mutationFn:r(P=>Rl.uninstall(P),"mutationFn"),onSuccess:r(()=>{w(),a({title:"Plugin uninstalled successfully",tone:"success"})},"onSuccess"),onError:r(P=>{a({title:"Failed to uninstall plugin",body:P.message,tone:"error"})},"onError")}),C=ye({mutationFn:r(P=>Rl.enable(P),"mutationFn"),onSuccess:r(()=>{w(),a({title:"Plugin enabled",tone:"success"})},"onSuccess"),onError:r(P=>{a({title:"Failed to enable plugin",body:P.message,tone:"error"})},"onError")}),_=ye({mutationFn:r(P=>Rl.disable(P),"mutationFn"),onSuccess:r(()=>{w(),a({title:"Plugin disabled",tone:"info"})},"onSuccess"),onError:r(P=>{a({title:"Failed to disable plugin",body:P.message,tone:"error"})},"onError")}),R=b??[],A=N.data??[],T=new Map(R.map(P=>[P.packageName,P])),E=new Map(A.map(P=>[P.packageName,P])),L=k.variables?.isLocalPath?k.error?.message??null:null,O=(0,m.useMemo)(()=>new Map(R.map(P=>[P.id,Pxe(P)])),[R]);return v?(0,t.jsx)("div",{className:"p-4 text-sm text-muted-foreground",children:"Loading plugins..."}):j?(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)(mg,{className:"h-6 w-6 text-muted-foreground"}),(0,t.jsx)("h1",{className:"text-xl font-semibold",children:"Plugin Manager"})]}),(0,t.jsxs)(zs,{open:l,onOpenChange:c,children:[(0,t.jsx)(_g,{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)(Ws,{children:[(0,t.jsxs)(on,{children:[(0,t.jsx)(Vs,{children:"Install Plugin"}),(0,t.jsx)(hn,{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)(ut,{id:"packageName",placeholder:"@tickernelz/paperclip-pro-plugin-example",value:i,onChange:r(P=>o(P.target.value),"onChange")})]})}),(0,t.jsxs)(dr,{children:[(0,t.jsx)($,{variant:"outline",onClick:r(()=>c(!1),"onClick"),children:"Cancel"}),(0,t.jsx)($,{onClick:r(()=>k.mutate({packageName:i}),"onClick"),disabled:!i||k.isPending,children:k.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)(Rs,{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)(Vm,{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"})]}),L&&(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:L}),N.isLoading?(0,t.jsx)("div",{className:"text-sm text-muted-foreground",children:"Loading bundled plugins..."}):N.error?(0,t.jsx)("div",{className:"text-sm text-destructive",children:"Failed to load bundled plugins."}):A.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:A.map(P=>{const U=T.get(P.packageName),M=k.isPending&&k.variables?.isLocalPath&&k.variables.packageName===P.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:P.displayName}),(0,t.jsx)(ot,{variant:"outline",children:P.tag==="first-party"?"First-party":"Example"}),Mxe({packageName:P.packageName,packagePath:P.localPath,bundledExperimental:P.experimental})&&(0,t.jsx)(Dxe,{}),U?(0,t.jsx)(ot,{variant:U.status==="ready"?"default":"secondary",className:U.status==="ready"?"bg-green-600 hover:bg-green-700":"",children:U.status}):(0,t.jsx)(ot,{variant:"secondary",children:"Not installed"})]}),(0,t.jsx)("p",{className:"mt-1 text-sm text-muted-foreground",children:P.description}),(0,t.jsx)("p",{className:"mt-1 text-xs text-muted-foreground",children:P.packageName}),M&&!P.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:U?(0,t.jsxs)(t.Fragment,{children:[U.status!=="ready"&&(0,t.jsx)($,{variant:"outline",size:"sm",disabled:C.isPending,onClick:r(()=>C.mutate(U.id),"onClick"),children:"Enable"}),(0,t.jsx)($,{variant:"outline",size:"sm",asChild:!0,children:(0,t.jsx)(We,{to:`/company/settings/instance/plugins/${U.id}`,children:U.status==="ready"?"Open Settings":"Review"})})]}):(0,t.jsx)($,{size:"sm",disabled:M||k.isPending,onClick:r(()=>k.mutate({packageName:P.localPath,isLocalPath:!0}),"onClick"),children:M?"Installing...":"Install"})})]})},P.packageName)})})})]}),(0,t.jsxs)("section",{className:"space-y-3",children:[(0,t.jsxs)("div",{className:"flex items-center gap-2",children:[(0,t.jsx)(mg,{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(P=>(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/${P.id}`,className:"font-medium hover:underline truncate block",title:P.manifestJson.displayName??P.packageName,children:P.manifestJson.displayName??P.packageName}),E.has(P.packageName)&&(0,t.jsx)(ot,{variant:"outline",children:E.get(P.packageName)?.tag==="first-party"?"First-party":"Example"}),Mxe({packageName:P.packageName,packagePath:P.packagePath,manifestJson:P.manifestJson,bundledExperimental:E.get(P.packageName)?.experimental})&&(0,t.jsx)(Dxe,{})]}),(0,t.jsx)("div",{children:(0,t.jsxs)("p",{className:"text-xs text-muted-foreground mt-0.5 truncate",title:P.packageName,children:[P.packageName," · v",P.manifestJson.version??P.version]})}),(0,t.jsx)("p",{className:"text-sm text-muted-foreground truncate mt-0.5",title:P.manifestJson.description,children:P.manifestJson.description||"No description provided."}),P.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)(Rs,{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:P.lastError??void 0,children:O.get(P.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(P),"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:P.status==="ready"?"default":P.status==="error"?"destructive":"secondary",className:V("shrink-0",P.status==="ready"?"bg-green-600 hover:bg-green-700":""),children:P.status}),(0,t.jsx)($,{variant:"outline",size:"icon-sm",className:"h-8 w-8",title:P.status==="ready"?"Disable":"Enable",onClick:r(()=>{P.status==="ready"?_.mutate(P.id):C.mutate(P.id)},"onClick"),disabled:C.isPending||_.isPending,children:(0,t.jsx)(vW,{className:V("h-4 w-4",P.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(P.id),p(P.manifestJson.displayName??P.packageName)},"onClick"),disabled:S.isPending,children:(0,t.jsx)(da,{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/${P.id}`,children:[(0,t.jsx)(xu,{className:"h-4 w-4"}),"Configure"]})})]})})]})},P.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)(mg,{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)(zs,{open:d!==null,onOpenChange:r(P=>{P||u(null)},"onOpenChange"),children:(0,t.jsxs)(Ws,{children:[(0,t.jsxs)(on,{children:[(0,t.jsx)(Vs,{children:"Uninstall Plugin"}),(0,t.jsxs)(hn,{children:["Are you sure you want to uninstall ",(0,t.jsx)("strong",{children:h}),"? This action cannot be undone."]})]}),(0,t.jsxs)(dr,{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)(zs,{open:f!==null,onOpenChange:r(P=>{P||x(null)},"onOpenChange"),children:(0,t.jsxs)(Ws,{className:"sm:max-w-2xl",children:[(0,t.jsxs)(on,{children:[(0,t.jsx)(Vs,{children:"Error Details"}),(0,t.jsxs)(hn,{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)(Rs,{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?Pxe(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)(dr,{children:(0,t.jsx)($,{variant:"outline",onClick:r(()=>x(null),"onClick"),children:"Close"})})]})})]})}r(mus,"PluginManager");function hus(){const{selectedCompany:e,selectedCompanyId:s}=ps(),{setBreadcrumbs:n}=Hn(),{companyPrefix:a,pluginId:i}=fa(),{hideHostPaths:o}=m2(),[l,c]=(0,m.useState)("configuration"),{data:d,isLoading:u}=te({queryKey:D.plugins.detail(i),queryFn:r(()=>Rl.get(i),"queryFn"),enabled:!!i}),{data:h,isLoading:p}=te({queryKey:D.plugins.health(i),queryFn:r(()=>Rl.health(i),"queryFn"),enabled:!!i&&d?.status==="ready",refetchInterval:3e4}),{data:f}=te({queryKey:D.plugins.dashboard(i),queryFn:r(()=>Rl.dashboard(i),"queryFn"),enabled:!!i,refetchInterval:3e4}),{data:x}=te({queryKey:D.plugins.logs(i),queryFn:r(()=>Rl.logs(i,{limit:50}),"queryFn"),enabled:!!i&&d?.status==="ready",refetchInterval:3e4}),b=d?.manifestJson?.instanceConfigSchema,v=b&&b.properties&&Object.keys(b.properties).length>0,j=i&&s?D.plugins.config(i,s):["plugins",i??"__missing_plugin__","companies","__missing_company__","config"],{data:N,isLoading:w}=te({queryKey:j,queryFn:r(()=>Rl.getConfig(i,s),"queryFn"),enabled:!!i&&!!v&&!!s}),{slots:k}=Rd({slotTypes:["settingsPage"],companyId:s,enabled:!!s}),S=k.filter(U=>U.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)(An,{to:"/company/settings/instance/plugins",replace:!0});const _=d.status,R=d.status==="ready"?"default":d.status==="error"?"destructive":"secondary",A=d.manifestJson.description||"No description provided.",T=d.manifestJson.capabilities??[],E=d.manifestJson.environmentDrivers??[],L=d.manifestJson.localFolders??[],O=L.length>0&&!o,P=E.map(U=>U.displayName?.trim()||U.driverKey).filter((U,M,B)=>B.indexOf(U)===M).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)(jl,{className:"h-4 w-4"})})}),(0,t.jsxs)("div",{className:"flex items-center gap-2",children:[(0,t.jsx)(mg,{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)(Pi,{value:l,onValueChange:r(U=>c(U),"onValueChange"),className:"space-y-6",children:[(0,t.jsx)(Kc,{align:"start",items:[{value:"configuration",label:"Configuration"},{value:"status",label:"Status"}],value:l,onValueChange:r(U=>c(U),"onValueChange")}),(0,t.jsx)(ma,{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:A})]}),(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(U=>(0,t.jsx)(ot,{variant:"outline",className:"capitalize",children:U},U)):(0,t.jsx)("span",{className:"text-foreground",children:"None"})})]})]})]})]}),(0,t.jsx)(Ul,{}),(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)(pus,{pluginId:i,companyId:s,declarations:L}):null,C?(0,t.jsx)("div",{className:"space-y-3",children:S.map(U=>(0,t.jsx)(am,{slot:U,context:{companyId:s,companyPrefix:a??null},missingBehavior:"placeholder"},`${U.pluginKey}:${U.id}`))}):v?(0,t.jsx)(vus,{pluginId:i,companyId:s,schema:b,initialValues:N?.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:[P||"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)(ma,{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)(uo,{children:[(0,t.jsxs)(Oo,{className:"text-base flex items-center gap-1.5",children:[(0,t.jsx)(Mm,{className:"h-4 w-4"}),"Runtime Dashboard"]}),(0,t.jsx)(qc,{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)(Mm,{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:yus(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)(Rs,{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:jus(f.worker.lastCrashAt)})]})]})]}):(0,t.jsx)("p",{className:"text-sm text-muted-foreground italic",children:"No worker process registered."})]}),(0,t.jsx)(Ul,{}),(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)(vb,{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(U=>(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)(wus,{status:U.status}),(0,t.jsx)("span",{className:"truncate font-mono text-xs",title:U.jobKey??U.jobId,children:U.jobKey??U.jobId.slice(0,8)}),(0,t.jsx)(ot,{variant:"outline",className:"px-1 py-0 text-(length:--text-nano)",children:U.trigger})]}),(0,t.jsxs)("div",{className:"flex shrink-0 items-center gap-2 text-xs text-muted-foreground",children:[U.durationMs!=null?(0,t.jsx)("span",{children:$xe(U.durationMs)}):null,(0,t.jsx)("span",{title:U.createdAt,children:Oxe(U.createdAt)})]})]},U.id))}):(0,t.jsx)("p",{className:"text-sm text-muted-foreground italic",children:"No job runs recorded yet."})]}),(0,t.jsx)(Ul,{}),(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)(_W,{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(U=>(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)(Nus,{status:U.status}),(0,t.jsx)("span",{className:"truncate font-mono text-xs",title:U.webhookKey,children:U.webhookKey})]}),(0,t.jsxs)("div",{className:"flex shrink-0 items-center gap-2 text-xs text-muted-foreground",children:[U.durationMs!=null?(0,t.jsx)("span",{children:$xe(U.durationMs)}):null,(0,t.jsx)("span",{title:U.createdAt,children:Oxe(U.createdAt)})]})]},U.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)(ko,{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)(uo,{children:[(0,t.jsxs)(Oo,{className:"text-base flex items-center gap-1.5",children:[(0,t.jsx)(fee,{className:"h-4 w-4"}),"Recent Logs"]}),(0,t.jsxs)(qc,{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(U=>(0,t.jsxs)("div",{className:`flex gap-2 py-0.5 ${U.level==="error"?"text-destructive":U.level==="warn"?"text-yellow-600 dark:text-yellow-400":U.level==="debug"?"text-muted-foreground/60":"text-muted-foreground"}`,children:[(0,t.jsx)("span",{className:"shrink-0 text-muted-foreground/50",children:new Date(U.createdAt).toLocaleTimeString()}),(0,t.jsx)(ot,{variant:"outline",className:"h-4 shrink-0 px-1 text-(length:--text-nano)",children:U.level}),(0,t.jsx)("span",{className:"truncate",title:U.message,children:U.message})]},U.id))})})]}):null]}),(0,t.jsxs)("div",{className:"space-y-6",children:[(0,t.jsxs)(sn,{children:[(0,t.jsx)(uo,{children:(0,t.jsxs)(Oo,{className:"text-base flex items-center gap-1.5",children:[(0,t.jsx)(fee,{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((U,M)=>(0,t.jsxs)("div",{className:"flex items-start justify-between gap-2",children:[(0,t.jsx)("span",{className:"truncate text-muted-foreground",title:U.name,children:U.name}),U.passed?(0,t.jsx)(IKe,{className:"h-4 w-4 shrink-0 text-green-500"}):(0,t.jsx)(ud,{className:"h-4 w-4 shrink-0 text-destructive"})]},M))}):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)(uo,{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)(uo,{children:(0,t.jsxs)(Oo,{className:"text-base flex items-center gap-1.5",children:[(0,t.jsx)(jc,{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(U=>(0,t.jsx)("li",{className:"rounded-md bg-muted/40 px-2.5 py-2 font-mono text-xs text-foreground/85",children:U},U))}):(0,t.jsx)("p",{className:"text-sm text-muted-foreground italic",children:"No special permissions requested."})})]})]})]})})]})]})}r(hus,"PluginSettings");function pus({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(()=>Rl.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)(sl,{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)(tt,{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)(fus,{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(pus,"PluginLocalFoldersSettings");function fus({pluginId:e,companyId:s,declaration:n,status:a}){const i=Nt(),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=ye({mutationFn:r(v=>Rl.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",b=(0,m.useCallback)(()=>{if(!p){u({type:"error",text:"Local folder path is required."});return}if(!bus(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)(Lq,{label:"Configured",value:a?.configured?"Yes":"No",ok:!!a?.configured}),(0,t.jsx)(Lq,{label:"Readable",value:a?.readable?"Yes":"No",ok:!!a?.readable}),(0,t.jsx)(Lq,{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)(Qd,{className:"h-8"}),(0,t.jsxs)($,{size:"sm",onClick:b,disabled:h.isPending||!f||!s,children:[h.isPending?(0,t.jsx)(tt,{className:"h-3.5 w-3.5 animate-spin"}):(0,t.jsx)(qf,{className:"h-3.5 w-3.5"}),"Save"]})]})]}),(0,t.jsx)(xus,{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,j)=>(0,t.jsxs)("li",{children:[v.message,v.path?(0,t.jsxs)("span",{className:"font-mono",children:[" ",v.path]}):null]},`${v.code}:${v.path??""}:${j}`))})]}):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(fus,"PluginLocalFolderRow");function Lq({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(Lq,"FolderStatusMetric");function xus({status:e,declaration:s}){const n=e?.requiredDirectories??s.requiredDirectories??[],a=e?.requiredFiles??s.requiredFiles??[],i=e?.missingDirectories??n,o=e?.missingFiles??a,l=gus(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)(Lxe,{title:"Required directories",items:n,missingItems:i,missingLabel:"Missing directories",inspectionUnavailable:l}),(0,t.jsx)(Lxe,{title:"Required files",items:a,missingItems:o,missingLabel:"Missing files",inspectionUnavailable:l})]})}r(xus,"FolderRequirements");function gus(e){return!e?.configured||e.readable?!1:e.problems.some(s=>s.code==="missing"||s.code==="not_readable"||s.code==="not_directory")}r(gus,"isRootNotInspected");function Lxe({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(Lxe,"RequirementList");function bus(e){return e.startsWith("/")||/^[A-Za-z]:[\\/]/.test(e)||e.startsWith("\\\\")}r(bus,"isLikelyAbsolutePath");function vus({pluginId:e,companyId:s,schema:n,initialValues:a,isLoading:i,pluginStatus:o,supportsConfigTest:l}){const c=Nt(),[d,u]=(0,m.useState)(()=>({...Pf(n),...a??{}})),h=(0,m.useRef)(!1);(0,m.useEffect)(()=>{h.current=!1,u(Pf(n))},[s,e,n]),(0,m.useEffect)(()=>{a&&!h.current&&(h.current=!0,u({...Pf(n),...a}))},[a,n]);const[p,f]=(0,m.useState)({}),[x,b]=(0,m.useState)(null),[v,j]=(0,m.useState)(null),N=JSON.stringify(d)!==JSON.stringify({...Pf(n),...a??{}}),w=ye({mutationFn:r(R=>{if(!s)throw new Error("Select an organization before saving plugin configuration.");return Rl.saveConfig(e,s,R)},"mutationFn"),onSuccess:r(()=>{b({type:"success",text:"Configuration saved."}),j(null),s&&c.invalidateQueries({queryKey:D.plugins.config(e,s)}),setTimeout(()=>b(null),3e3)},"onSuccess"),onError:r(R=>{b({type:"error",text:R.message||"Failed to save configuration."})},"onError")}),k=ye({mutationFn:r(R=>{if(!s)throw new Error("Select an organization before testing plugin configuration.");return Rl.testConfig(e,s,R)},"mutationFn"),onSuccess:r(R=>{R.valid?j({type:"success",text:"Configuration test passed."}):j({type:"error",text:R.message||"Configuration test failed."})},"onSuccess"),onError:r(R=>{j({type:"error",text:R.message||"Configuration test failed."})},"onError")}),S=(0,m.useCallback)(R=>{u(R),f({}),b(null)},[]),C=(0,m.useCallback)(()=>{const R=Vy(n,d);if(Object.keys(R).length>0){f(R);return}f({}),w.mutate(d)},[n,d,w]),_=(0,m.useCallback)(()=>{const R=Vy(n,d);if(Object.keys(R).length>0){f(R);return}f({}),j(null),k.mutate(d)},[n,d,k]);return i?(0,t.jsxs)("div",{className:"flex items-center gap-2 text-sm text-muted-foreground py-4",children:[(0,t.jsx)(tt,{className:"h-4 w-4 animate-spin"}),"Loading configuration..."]}):(0,t.jsxs)("div",{className:"space-y-4",children:[(0,t.jsx)(JA,{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||!N,size:"sm",children:w.isPending?(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)(tt,{className:"h-3.5 w-3.5 animate-spin"}),"Saving..."]}):"Save Configuration"}),o==="ready"&&l&&(0,t.jsx)($,{variant:"outline",onClick:_,disabled:k.isPending||!s,size:"sm",children:k.isPending?(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)(tt,{className:"h-3.5 w-3.5 animate-spin"}),"Testing..."]}):"Test Configuration"})]})]})}r(vus,"PluginConfigForm");function yus(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(yus,"formatUptime");function $xe(e){return e<1e3?`${e}ms`:e<6e4?`${(e/1e3).toFixed(1)}s`:`${(e/6e4).toFixed(1)}m`}r($xe,"formatDuration");function Oxe(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(Oxe,"formatRelativeTime");function jus(e){return new Date(e).toLocaleString()}r(jus,"formatTimestamp");function wus({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(wus,"JobStatusDot");function Nus({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(Nus,"DeliveryStatusDot");function $q({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:V("font-medium",e.disabled&&"text-muted-foreground line-through"),children:e.label&&e.label!==e.type?e.label:ax(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)(sl,{className:"h-4 w-4 text-amber-500"})}):(0,t.jsx)("span",{title:"Installed from npm",children:(0,t.jsx)(qh,{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)(ho,{className:V("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)(Ai,{className:V("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)(vW,{className:V("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)(da,{className:"h-4 w-4"})})]})]})})}r($q,"AdapterRow");function kus(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(kus,"fetchNpmLatestVersion");function Sus({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?kus(e.packageName):null,"queryFn"),enabled:s&&!!e?.packageName,staleTime:6e4}),c=e?.version&&o&&e.version===o;return(0,t.jsx)(zs,{open:s,onOpenChange:r(d=>{d||i()},"onOpenChange"),children:(0,t.jsxs)(Ws,{children:[(0,t.jsxs)(on,{children:[(0,t.jsx)(Vs,{children:"Reinstall Adapter"}),(0,t.jsxs)(hn,{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)(dr,{children:[(0,t.jsx)($,{variant:"outline",onClick:i,disabled:n,children:"Cancel"}),(0,t.jsx)($,{disabled:n,onClick:a,children:n?"Reinstalling...":"Reinstall"})]})]})})}r(Sus,"ReinstallDialog");function Fxe(){const{selectedCompany:e}=ps(),{setBreadcrumbs:s}=Hn(),n=Nt(),{pushToast:a}=Qr(),[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),[b,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:j,isLoading:N}=te({queryKey:D.adapters.all,queryFn:r(()=>Sh.list(),"queryFn")}),w=r(()=>{n.invalidateQueries({queryKey:D.adapters.all})},"invalidate"),k=ye({mutationFn:r(P=>Sh.install(P),"mutationFn"),onSuccess:r(P=>{w(),p(!1),o(""),c(""),u(!1),a({title:"Adapter installed",body:`Type "${P.type}" registered successfully.${P.version?` (v${P.version})`:""}`,tone:"success"})},"onSuccess"),onError:r(P=>{a({title:"Install failed",body:P.message,tone:"error"})},"onError")}),S=ye({mutationFn:r(P=>Sh.remove(P),"mutationFn"),onSuccess:r(()=>{w(),a({title:"Adapter removed",tone:"success"})},"onSuccess"),onError:r(P=>{a({title:"Removal failed",body:P.message,tone:"error"})},"onError")}),C=ye({mutationFn:r(({type:P,disabled:U})=>Sh.setDisabled(P,U),"mutationFn"),onSuccess:r(()=>{w()},"onSuccess"),onError:r(P=>{a({title:"Toggle failed",body:P.message,tone:"error"})},"onError")}),_=ye({mutationFn:r(({type:P,paused:U})=>Sh.setOverridePaused(P,U),"mutationFn"),onSuccess:r(()=>{w()},"onSuccess"),onError:r(P=>{a({title:"Override toggle failed",body:P.message,tone:"error"})},"onError")}),R=ye({mutationFn:r(P=>Sh.reload(P),"mutationFn"),onSuccess:r(P=>{w(),jU(P.type),gne(P.type),a({title:"Adapter reloaded",body:`Type "${P.type}" reloaded.${P.version?` (v${P.version})`:""}`,tone:"success"})},"onSuccess"),onError:r(P=>{a({title:"Reload failed",body:P.message,tone:"error"})},"onError")}),A=ye({mutationFn:r(P=>Sh.reinstall(P),"mutationFn"),onSuccess:r(P=>{w(),jU(P.type),gne(P.type),a({title:"Adapter reinstalled",body:`Type "${P.type}" updated from npm.${P.version?` (v${P.version})`:""}`,tone:"success"})},"onSuccess"),onError:r(P=>{a({title:"Reinstall failed",body:P.message,tone:"error"})},"onError")}),T=(j??[]).filter(P=>P.source==="builtin"),E=(j??[]).filter(P=>P.source==="external"),L=(j??[]).filter(P=>P.source==="external"&&P.overriddenBuiltin).filter(P=>!T.some(U=>U.type===P.type)).map(P=>({type:P.type,label:ax(P.type),overriddenBy:[P.packageName,P.version?`v${P.version}`:void 0].filter(Boolean).join(" "),overridePaused:!!P.overridePaused,menuDisabled:!!P.disabled}));if(N)return(0,t.jsx)("div",{className:"p-4 text-sm text-muted-foreground",children:"Loading adapters..."});const O=k.isPending||S.isPending||C.isPending||_.isPending||R.isPending||A.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)(Mm,{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)(zs,{open:h,onOpenChange:p,children:[(0,t.jsx)(_g,{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)(Ws,{children:[(0,t.jsxs)(on,{children:[(0,t.jsx)(Vs,{children:"Install External Adapter"}),(0,t.jsxs)(hn,{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:V("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)(qh,{className:"h-3.5 w-3.5"}),"npm package"]}),(0,t.jsxs)("button",{type:"button",className:V("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)(sl,{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)(ut,{id:"adapterLocalPath",className:"flex-1 font-mono text-xs",placeholder:"/mnt/e/Projects/my-adapter or E:\\Projects\\my-adapter",value:i,onChange:r(P=>o(P.target.value),"onChange")}),(0,t.jsx)(Qd,{})]}),(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)(ut,{id:"adapterPackageName",placeholder:"my-paperclip-adapter",value:i,onChange:r(P=>o(P.target.value),"onChange")})]}),(0,t.jsxs)("div",{className:"grid gap-2",children:[(0,t.jsx)($s,{htmlFor:"adapterVersion",children:"Version (optional)"}),(0,t.jsx)(ut,{id:"adapterVersion",placeholder:"latest",value:l,onChange:r(P=>c(P.target.value),"onChange")})]})]})]}),(0,t.jsxs)(dr,{children:[(0,t.jsx)($,{variant:"outline",onClick:r(()=>p(!1),"onClick"),children:"Cancel"}),(0,t.jsx)($,{onClick:r(()=>k.mutate({packageName:i,version:l||void 0,isLocalPath:d}),"onClick"),disabled:!i||k.isPending,children:k.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)(Rs,{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)(Mm,{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)(Mm,{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(P=>{const U=P.overriddenBuiltin,M=U&&!!P.overridePaused,B=U?{...P,disabled:M??!1}:P;return(0,t.jsx)($q,{adapter:B,canRemove:!0,onToggle:U?(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:P.isLocalPath?void 0:q=>v(P),isToggling:U?_.isPending:C.isPending,isReloading:R.isPending,isReinstalling:A.isPending,toggleTitleDisabled:U?"Pause external override":void 0,toggleTitleEnabled:U?"Resume external override":void 0,disabledBadgeLabel:U?"Override paused":void 0},P.type)})})})]}),(0,t.jsxs)("section",{className:"space-y-3",children:[(0,t.jsxs)("div",{className:"flex items-center gap-2",children:[(0,t.jsx)(Mm,{className:"h-5 w-5 text-muted-foreground"}),(0,t.jsx)("h2",{className:"text-base font-semibold",children:"Built-in Adapters"})]}),T.length===0&&L.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(P=>(0,t.jsx)($q,{adapter:P,canRemove:!1,onToggle:r((U,M)=>C.mutate({type:U,disabled:M}),"onToggle"),onRemove:r(()=>{},"onRemove"),isToggling:O},P.type)),L.map(P=>(0,t.jsx)($q,{adapter:{type:P.type,label:P.label,source:"builtin",modelsCount:0,loaded:!0,disabled:P.menuDisabled,capabilities:{supportsInstructionsBundle:!1,supportsSkills:!1,supportsLocalAgentJwt:!1,requiresMaterializedRuntimeSkills:!1,supportsAcp:!1}},canRemove:!1,onToggle:r((U,M)=>C.mutate({type:U,disabled:M}),"onToggle"),onRemove:r(()=>{},"onRemove"),isToggling:O,overriddenBy:P.overridePaused?void 0:P.overriddenBy},P.type))]})})]}),(0,t.jsx)(zs,{open:f!==null,onOpenChange:r(P=>{P||x(null)},"onOpenChange"),children:(0,t.jsxs)(Ws,{children:[(0,t.jsxs)(on,{children:[(0,t.jsx)(Vs,{children:"Remove Adapter"}),(0,t.jsxs)(hn,{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&&j?.find(P=>P.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)(dr,{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)(Sus,{adapter:b,open:b!==null,isReinstalling:A.isPending,onConfirm:r(()=>{b&&A.mutate(b.type,{onSettled:r(()=>v(null),"onSettled")})},"onConfirm"),onCancel:r(()=>v(null),"onCancel")})]})}r(Fxe,"AdapterManager");function Bxe(){const e=fa(),{companyPrefix:s,pluginId:n,pluginRoutePath:a}=e,i=e["*"],{companies:o,selectedCompanyId:l}=ps(),{setBreadcrumbs:c}=Hn(),d=(0,m.useMemo)(()=>{if(!s)return null;const j=s.toUpperCase();return o.find(N=>N.issuePrefix.toUpperCase()===j)??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(j=>j.id===h)?.issuePrefix??null:null,[o,h]),{data:f}=te({queryKey:D.plugins.uiContributions,queryFn:r(()=>Rl.listUiContributions(),"queryFn"),enabled:!!h&&(!!n||!!a)}),x=(0,m.useMemo)(()=>{if(!f)return null;if(n){const N=f.find(k=>k.pluginId===n);if(!N)return null;const w=N.slots.find(k=>k.type==="page");return w?{...w,pluginId:N.pluginId,pluginKey:N.pluginKey,pluginDisplayName:N.displayName,pluginVersion:N.version}:null}if(!a)return null;const j=f.flatMap(N=>{const w=N.slots.find(k=>k.type==="page"&&k.routePath===a);return w?[{...w,pluginId:N.pluginId,pluginKey:N.pluginKey,pluginDisplayName:N.displayName,pluginVersion:N.version}]:[]});return j.length!==1?null:j[0]??null},[n,a,f]),b=(0,m.useMemo)(()=>({companyId:h??null,companyPrefix:p}),[h,p]),v=(0,m.useMemo)(()=>{if(!a||!f)return!1;const j=f.flatMap(N=>N.slots.map(w=>({...w,pluginId:N.pluginId,pluginKey:N.pluginKey,pluginDisplayName:N.displayName,pluginVersion:N.version})));return OW(j,a)!==null},[f,a]);if((0,m.useEffect)(()=>{if(x){if(v){c([{label:Cus(x,i)}]);return}c([{label:"Plugins",href:"/company/settings/instance/plugins"},{label:x.pluginDisplayName}])}},[x,i,c,v]),!h)return u?(0,t.jsx)(Zu,{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(j=>j.slots.some(N=>N.type==="page"&&N.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)(Zu,{scope:"board"});const j=n?`/company/settings/instance/plugins/${n}`:"/company/settings/instance/plugins";return(0,t.jsx)(An,{to:j,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)(jl,{className:"h-4 w-4 mr-1"}),"Back"]})})}),(0,t.jsx)(am,{slot:x,context:b,className:"min-h-(--sz-200px)",missingBehavior:"placeholder"})]})}r(Bxe,"PluginPage");function Cus(e,s){return _us(s)??e.displayName??e.pluginDisplayName}r(Cus,"resolveRouteSidebarPageTitle");function _us(e){const s=(e??"").split("/").filter(Boolean).map(Ius);return s.length===0?null:s[0]==="page"&&s.length>1?zxe(s.slice(1).join("/"),{preserveCase:!0}):zxe(s[0]??null)}r(_us,"titleFromRouteSplat");function zxe(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(zxe,"titleFromPath");function Ius(e){try{return decodeURIComponent(e)}catch{return e}}r(Ius,"decodeRouteSegment");var Oq=T6e,qxe=r(e=>e.status==="fail"||e.checks.some(s=>s.code==="adapter_auth_missing"),"blocking");function Aus(){const{selectedCompanyId:e}=ps(),[s]=hi();return e?(0,t.jsx)(Tus,{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(Aus,"NewAgentSetup");function Tus({companyId:e,name:s,adapterType:n,runnerProvider:a,createdAgentId:i}){const o=Gn(),l=Nt(),{openNewIssue:c}=rl(),d=y_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",b=jnt(p),v=x||p==="hermes_local",j=v||!!hne[n],N=!h&&!["cursor_cloud","hermes_gateway"].includes(n),[w,k]=(0,m.useState)(!1),[S,C]=(0,m.useState)(""),[_,R]=(0,m.useState)(""),[A,T]=(0,m.useState)(""),[E,L]=(0,m.useState)("kimi"),[O,P]=(0,m.useState)(i?"saved":f?"connect":"runtime"),[U,M]=(0,m.useState)(""),B=u?[]:TP(n,U),[q,z]=(0,m.useState)(""),[K,W]=(0,m.useState)(!1),[Q,re]=(0,m.useState)(""),[J,ie]=(0,m.useState)("openrouter"),[X,ne]=(0,m.useState)(""),[oe,G]=(0,m.useState)(null),[Z,Y]=(0,m.useState)(()=>p==="opencode_local"?{provider:"openrouter",method:"api_key",mode:"responsible_user"}:void 0),[ae,se]=(0,m.useState)(null),ce=Z??ae?.aiConnection,pe=t1e(e,ce,p),[we,Se]=(0,m.useState)(""),[Te,le]=(0,m.useState)(""),[fe,de]=(0,m.useState)(null),Ee=te({queryKey:D.agents.detail(i??"new"),queryFn:r(()=>Ct.get(i,e),"queryFn"),enabled:!!i,retry:!1}),Me=fe??(Ee.data?.companyId===e?Ee.data:null),[ve,Ie]=(0,m.useState)(!1),[Ze,ue]=(0,m.useState)("idle"),[Be,ht]=(0,m.useState)(null),[jt,Je]=(0,m.useState)(null),Fe=(0,m.useRef)(0),it=(0,m.useRef)(!1);(0,m.useEffect)(()=>()=>{Fe.current++},[]);const At=r(()=>{Fe.current++,ht(null),ue("idle"),Je(null)},"resetTest"),$t=r(()=>{se(null),Y(void 0),At(),P("connect")},"editConnection"),zt=te({queryKey:D.adapters.all,queryFn:Sh.list}),at=te({queryKey:D.agents.list(e),queryFn:r(()=>Ct.list(e),"queryFn")}),De=te({queryKey:D.environments.list(e),queryFn:r(()=>$i.list(e),"queryFn")}),Pe=te({queryKey:D.instance.settings,queryFn:vr.get}),dt=te({queryKey:D.instance.experimentalSettings,queryFn:vr.getExperimental}),rt=te({queryKey:D.instance.generalSettings,queryFn:vr.getGeneral}),ft=te({queryKey:D.environments.capabilities(e),queryFn:r(()=>$i.capabilities(e),"queryFn")}),kt=te({queryKey:D.agents.adapterModels(e,p,null,ce?.provider),queryFn:r(()=>Ct.adapterModels(e,p,{provider:ce?.provider}),"queryFn"),enabled:!!p&&N&&!pe,retry:!1}),Ke=te({queryKey:D.secrets.list(e),queryFn:r(()=>Rr.list(e),"queryFn"),enabled:j&&n!=="cursor_cloud"}),$e=te({queryKey:D.secrets.myUserSecrets(e),queryFn:r(()=>Rr.listMyUserSecrets(e),"queryFn"),enabled:j&&n!=="cursor_cloud",retry:!1}),ze=CH(rt.data?.executionMode,De.data??[]),et=dt.data?.enableManagedSandboxOnly===!0;let ge=null,st=null;try{ge=ze.forced?ze.kubernetesEnvironment?.id??null:Bk({agentDefaultEnvironmentId:Q||null,instanceDefaultEnvironmentId:Pe.data?.defaultEnvironmentId??null,localDefaultEnvironmentId:qk(De.data??[]),managedSandboxOnly:et,managedSandboxEnvironmentId:zk(De.data??[]),visibleEnvironmentIds:(De.data??[]).map(Oe=>Oe.id)})}catch(Oe){st=Oe instanceof Error?Oe.message:"Could not resolve the environment."}const Mt=De.data?.find(Oe=>Oe.id===ge),Ss=typeof Mt?.config?.provider=="string"?Mt.config.provider:"",lt=Mt?.driver==="sandbox"&&ft.data?.sandboxProviders?.[Ss]?.supportsLoginPty===!0,Ls=hne[n]??b[J]??"API_KEY",Ue=$e.data?.find(Oe=>Oe.definition.key===Ls&&Oe.secret),xe=Ke.data?.find(Oe=>Oe.key===Ls&&Oe.status==="active"),Ye=n==="cursor_cloud"?null:oe??(xe?{type:"secret_ref",secretId:xe.id,version:"latest"}:Ue?{type:"user_secret_ref",key:Ls,version:"latest"}:null),gt=n==="kimi_local"&&!!(X.trim()||Ye),Ht=!!Yc(),mt=j_e(n,{cloud:Ht,nativeRunnerEnabled:dt.data?.enableNativeRunner===!0,openAiDotEnabled:dt.data?.enableOpenAiDot===!0,runnerProvider:a})&&zt.data?.some(Oe=>Oe.type===n&&Oe.loaded&&!Oe.disabled&&!Um(n).comingSoon),Bt=!!(mt&&!st&&!De.isPending&&!Pe.isPending&&!dt.isPending&&!rt.isPending&&!at.isPending&&!ft.isPending&&!De.error&&!Pe.error&&!dt.error&&!rt.error&&!at.error&&!ft.error&&(!(et||ze.forced)||ge)),Le=Ze==="running"||ve;function he(Oe=ae,_t=Ye){const Ut={...ib,adapterType:n,model:U||(p==="codex_local"?Fk:""),thinkingEffort:q,dangerouslyBypassSandbox:n==="codex_local",envBindings:Oe?.env??{},...u?{adapterSchemaValues:{provider:a==="claude"||a==="grok"?"acpx":a,...h?{allowUnmeteredProvider:w}:{},...a==="claude"||a==="grok"?{acpxAgent:a}:{}}}:{}},It=KS(n).buildAdapterConfig(Ut);return n==="omp_local"&&(delete It.thinkingEffort,q&&(It.thinking=q)),u&&Object.assign(It,{provider:a==="claude"||a==="grok"?"acpx":a,...a==="claude"||a==="grok"?{acpxAgent:a}:{},...U?{model:U}:{}}),!ce&&!Oe?.aiConnection&&j&&_t&&(n==="hermes_gateway"?It.apiKey=_t:It.env={...It.env??{},[Ls]:_t}),n==="cursor_cloud"&&Object.assign(It,{repoUrl:we.trim(),...Te.trim()?{repoStartingRef:Te.trim()}:{}}),n==="hermes_gateway"&&(It.apiBaseUrl=S.trim()),gt&&(delete It.model,It.env={...It.env??{},KIMI_MODEL_NAME:{type:"plain",value:_.trim()},KIMI_MODEL_PROVIDER_TYPE:{type:"plain",value:E},...A.trim()?{KIMI_MODEL_BASE_URL:{type:"plain",value:A.trim()}}:{}}),It}r(he,"buildConfig");function Qt(Oe=ae){if(h&&!w)throw new Error("Acknowledge external provider billing before creating your Dot agent.");if(x&&(!U.trim()||!U.includes("/")))throw new Error("Choose or enter a model in provider/model format.");if(n==="cursor_cloud"&&!/^https:\/\/github\.com\/[^/]+\/[^/]+/.test(we.trim()))throw new Error("Enter a GitHub repository URL.");if(["cursor_cloud","hermes_gateway"].includes(n)&&!X.trim()&&!Ye)throw new Error(n==="cursor_cloud"?"Enter a Cursor API key.":`Enter ${Ls} or select an organization secret.`);if(n==="hermes_gateway")try{const _t=new URL(S.trim());if(!["https:","http:"].includes(_t.protocol))throw new Error}catch{throw new Error("Enter the Hermes API base URL.")}if(gt&&!_.trim())throw new Error("Enter the Kimi API model name.");return he(Oe)}r(Qt,"preparedConfig");function Lt(Oe=ae){return ce||Oe?.aiConnection?{}:{...Oe?.credentials,...j&&X.trim()?{[Ls]:X.trim()}:{}}}r(Lt,"pendingCredentials");async function ss(Oe=ae){if(!Bt)return!1;const _t=++Fe.current;ue("running"),ht(null),Je(null);try{const Ut=await Qt(Oe),It=await s1e({companyId:e,adapterType:n,providerAdapter:p,adapterConfig:Ut,testCredentials:Lt(Oe),aiConnection:Z??Oe?.aiConnection,environmentId:ge});return _t!==Fe.current?!1:(ht(It),ue(qxe(It)?"fail":It.status),!qxe(It)&&(!f||It.checks.some(is=>is.code.endsWith("hello_probe_passed"))))}catch(Ut){return _t===Fe.current&&(Je(Ut instanceof Error?Ut.message:"Could not test the agent."),ue("fail")),!1}}r(ss,"runTest");async function Cs(){if(it.current||i||Me||!Bt||!s.trim()||Ze==="running"||Ze==="fail"||f&&!ae)return;it.current=!0,Ie(!0),Je(null);const Oe=[];let _t=!1;try{const Ut=Qt(),It=Lt();if(Object.keys(It).length&&!await ss())return;for(const[qs,Rn]of Object.entries(It)){const Ns=await(f?h1e:vnt)(e,qs,Rn);Oe.push(Ns),n==="hermes_gateway"&&qs==="API_SERVER_KEY"?Ut.apiKey=Ns.binding:Ut.env={...Ut.env??{},[qs]:Ns.binding}}const is=at.data??[],bs=is.find(qs=>qs.role==="ceo"&&qs.status!=="terminated"),Os=await Ct.hire(e,{name:s.trim(),appearance:d.appearance,role:is.length?"general":"ceo",...bs?{reportsTo:bs.id}:{},adapterType:n,adapterConfig:Ut,defaultEnvironmentId:Q||(ze.forced||et?ge:null),runtimeConfig:{...h2e({heartbeatEnabled:!1}),...ce?{aiConnection:ce}:{}},budgetMonthlyCents:0,...ae?.storedSessionId?{storedSessionId:ae.storedSessionId}:{},...ae?.applyStoredClaudeLogin?{applyStoredClaudeLogin:!0}:{}});_t=!0,ne(""),se(null),de(Os.agent),d.clear(),P("saved"),o(`/agents/new?${new URLSearchParams({name:Os.agent.name,adapterType:n,runnerProvider:a,createdAgentId:Os.agent.id})}`,{replace:!0}),l.setQueryData(D.agents.detail(Os.agent.id),Os.agent),await Promise.all([l.invalidateQueries({queryKey:D.agents.list(e)}),l.invalidateQueries({queryKey:D.approvals.list(e)})])}catch(Ut){Je(Ut instanceof Error?Ut.message:"Could not create the agent.")}finally{if(!_t)try{await Promise.all(Oe.map(Ut=>Ut.remove()))}catch{Je(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,Ie(!1)}}if(r(Cs,"finish"),i&&!Me)return(0,t.jsx)("p",{role:Ee.error?"alert":"status",className:"text-sm text-muted-foreground",children:Ee.error?"Could not load the created agent. Return to Agents to view it.":"Loading your agent…"});if(!s||!n)return(0,t.jsx)(w_e,{open:!0,initialAdapter:n,onClose:r(()=>o("/agents/all"),"onClose"),onContinue:r(Oe=>o(`/agents/new?${new URLSearchParams(Oe)}`,{replace:!0}),"onContinue")});const ln=[...f?["connect"]:[],"runtime","saved"],mr={connect:"Connect",runtime:"Configure",saved:"Confirmation"},pn=Me?.defaultEnvironmentId?De.data?.find(Oe=>Oe.id===Me.defaultEnvironmentId):Mt,Ot=Me?.adapterConfig?.env?.KIMI_MODEL_NAME,Es=Me?.adapterConfig?.model||(typeof Ot=="string"?Ot:Ot?.value)||U||"Default",Re=n==="cursor_cloud"?"Cursor Cloud":n==="hermes_gateway"?"Hermes Gateway":pn?Uk(pn):"Local machine",wt=zt.error??De.error??Pe.error??dt.error??rt.error??at.error??ft.error;return(0,t.jsx)(UCe,{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)(Wk,{appearance:Me?.appearance??d.appearance,size:256,className:"size-48",trackingScope:"page",state:Me||Ze==="pass"?"success":Ze==="running"?"loading":"sleepy",muted:!Me&&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)(Ap,{type:p}),(0,t.jsx)("span",{children:Um(p).label}),u&&!h&&(0,t.jsxs)("span",{children:["·"," ",a==="codex"?"Native app server runner":"Paperclip Runner"]})]})]})]}),st&&!De.isPending&&(0,t.jsx)("p",{role:"alert",className:"text-sm text-destructive",children:st}),wt&&(0,t.jsx)("p",{role:"alert",className:"text-sm text-destructive",children:wt.message}),zt.data&&!mt&&(0,t.jsx)("p",{role:"alert",className:"text-sm text-destructive",children:"This adapter is unavailable. Choose an enabled adapter."}),(et||ze.forced)&&!De.isPending&&!ge&&(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:ln.map((Oe,_t)=>(0,t.jsx)("li",{children:(0,t.jsxs)("button",{type:"button","aria-current":Oe===O?"step":void 0,disabled:Le||!!Me||Oe==="saved",onClick:r(()=>Oe==="connect"&&O!=="connect"?$t():P(Oe),"onClick"),className:V("flex w-full items-center gap-3 rounded-md px-3 py-3 text-left text-sm",Oe===O?"bg-accent font-medium":"text-muted-foreground"),children:[(0,t.jsx)("span",{className:V("flex size-6 shrink-0 items-center justify-center rounded-full border text-xs",Oe===O?"border-foreground bg-foreground text-background":"border-border"),children:_t+1}),mr[Oe]]})},Oe))})}),(0,t.jsx)("div",{className:"min-w-0 flex-1",children:(0,t.jsx)(qS,{mode:"wait",initial:!1,children:(0,t.jsx)(Tl.div,{...Unt,children:O==="connect"&&f?(0,t.jsxs)(Q0t,{className:"mx-auto",children:[(0,t.jsx)("div",{className:"mb-8",children:(0,t.jsx)(p2e,{title:"Connect a model",center:!0})}),Bt?(0,t.jsx)(S_e,{companyId:e,adapterType:f,environmentId:ge,canLogin:lt,localEnvironment:Mt?.driver==="local",advancedConnection:{value:ce,content:(0,t.jsx)(lU,{companyId:e,agentName:s,adapterType:p,model:U,environmentId:ge??void 0,value:ce,preferAdvanced:!0,onChange:r(Oe=>{Oe.mode!=="router"&&(se(null),Y(Oe),At())},"onChange")})},onBack:r(()=>o("/agents/all"),"onBack"),onDraftChanged:r(()=>{se(null),Y(void 0),At()},"onDraftChanged"),testConnection:ss,testError:jt??(Be?.checks.find(Oe=>Oe.level==="error")??Be?.checks.find(Oe=>Oe.code.includes("hello_probe")&&Oe.level==="warn"))?.message,onConnected:r(Oe=>{se(Oe),Y(void 0),At(),P("runtime")},"onConnected")},ge??"local"):(0,t.jsx)("p",{role:"status",className:"text-sm text-muted-foreground",children:"Loading connection settings…"})]}):O==="saved"&&Me?(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)(us,{className:"size-5"}),Me.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:Um(h?"openai_dot":n).label}),N&&(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(Es)})]}),(0,t.jsx)("dt",{className:"text-muted-foreground",children:"Environment"}),(0,t.jsx)("dd",{children:Re})]}),(0,t.jsx)("p",{className:"text-sm text-muted-foreground",children:Me.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":`${Qu(Me)}/runtime`),"onClick"),children:[(0,t.jsx)(wW,{className:"size-4"}),h?"Back to Agents":"Edit configuration"]}),(0,t.jsxs)($,{disabled:Me.status==="pending_approval",onClick:r(()=>h?o(`${Qu(Me)}/runtime`):c({assigneeAgentId:Me.id,status:"todo"}),"onClick"),children:[h?"Pair Dot":`Assign ${Me.name} a Task`,(0,t.jsx)(ml,{className:"size-4"})]})]})]}):(0,t.jsxs)("form",{className:"space-y-8",onSubmit:r(Oe=>{Oe.preventDefault(),Cs()},"onSubmit"),children:[(0,t.jsx)("h2",{className:"text-xl font-semibold",children:"Configure your agent"}),(0,t.jsxs)("fieldset",{disabled:Le,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."}),dt.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)(vl,{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(Oe=>{k(Oe),At()},"onChange")})]}),!f&&aH(p)&&(0,t.jsx)(lU,{companyId:e,agentName:s,adapterType:p,model:U,environmentId:ge??void 0,value:ce,onChange:r(Oe=>{Oe.mode!=="router"&&Y(Oe),At()},"onChange")}),(pe?pe.error:kt.error)&&(0,t.jsx)("p",{role:"alert",className:"text-sm text-destructive",children:"Could not load models. Retry or enter a model ID manually."}),(N&&!gt||B.length>0)&&(0,t.jsxs)("div",{className:"grid items-start gap-5 sm:grid-cols-2",children:[N&&!gt&&(0,t.jsx)(IH,{models:pe?.models??kt.data??[],onRefreshModels:pe?.refreshModels,refreshingModels:pe?.refreshing,value:U,onChange:r(Oe=>{M(pe?.resolveModel(Oe)??Oe),(n==="omp_local"?!vD(q,Oe,(kt.data??[]).map(Ut=>YN(Ut,!1))):q&&!TP(n,Oe).includes(q))&&z("");const _t=Oe.split("/")[0];x&&m1e[_t]&&_t!==J&&(ie(_t),ne(""),G(null)),At()},"onChange"),open:K,onOpenChange:W,allowDefault:!x,required:x,creatable:!0,groupByProvider:x&&!pe,preserveOrder:!!pe||dH(p),effort:n==="omp_local"?{value:q||null,onChange:r(Oe=>{z(Oe??""),At()},"onChange")}:void 0}),B.length>0&&n!=="omp_local"&&(0,t.jsx)(ks,{label:"Thinking effort",children:(0,t.jsxs)(nbe,{"aria-label":"Thinking effort",value:q,onChange:r(Oe=>{z(Oe.target.value),At()},"onChange"),children:[(0,t.jsx)("option",{value:"",children:"Auto"}),B.map(Oe=>(0,t.jsx)("option",{value:Oe,children:Oe},Oe))]})})]}),!ce&&pne[n]&&(0,t.jsx)("p",{className:"text-sm text-muted-foreground",children:pne[n]}),j&&!ce&&(0,t.jsxs)("div",{className:"grid gap-5 sm:grid-cols-2",children:[v&&(0,t.jsx)(ks,{label:"API key provider",children:(0,t.jsx)("select",{"aria-label":"API key provider",className:Oq,value:J,onChange:r(Oe=>{ie(Oe.target.value),M(""),ne(""),G(null),At()},"onChange"),children:Object.keys(b).map(Oe=>(0,t.jsx)("option",{value:Oe,children:Oe==="openrouter"?"OpenRouter":Oe==="openai"?"OpenAI":Oe==="anthropic"?"Anthropic":{google:"Google",xai:"xAI",groq:"Groq",opencode:"OpenCode"}[Oe]??Oe},Oe))})}),(0,t.jsx)("div",{className:n==="cursor_cloud"?"sm:col-span-2":void 0,children:(0,t.jsx)(ks,{label:Ls,children:(0,t.jsxs)("div",{className:"flex items-center gap-3",children:[(0,t.jsx)(ut,{"aria-label":Ls,type:"password",autoComplete:"off",value:X,onChange:r(Oe=>{ne(Oe.target.value),G(null),At()},"onChange"),placeholder:Ye?"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)(ks,{label:"Or use an organization secret",children:(0,t.jsx)(jH,{secretId:Ye&&typeof Ye=="object"&&Ye.type==="secret_ref"?Ye.secretId:"",secrets:Ke.data??[],disabled:Le,onSelect:r(Oe=>{G({type:"secret_ref",secretId:Oe,version:"latest"}),ne(""),At()},"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 ${J}/model ID.`]})]}),n==="hermes_gateway"&&(0,t.jsx)(ks,{label:"Hermes API base URL",children:(0,t.jsx)(ut,{"aria-label":"Hermes API base URL",value:S,onChange:r(Oe=>{C(Oe.target.value),At()},"onChange"),placeholder:"https://hermes.example.com"})}),gt&&(0,t.jsxs)("div",{className:"grid gap-5 sm:grid-cols-2",children:[(0,t.jsx)(ks,{label:"Kimi API model name",children:(0,t.jsx)(ut,{"aria-label":"Kimi API model name",value:_,onChange:r(Oe=>{R(Oe.target.value),At()},"onChange"),placeholder:"kimi-for-coding"})}),(0,t.jsx)(ks,{label:"Kimi API protocol",children:(0,t.jsx)("select",{"aria-label":"Kimi API protocol",className:Oq,value:E,onChange:r(Oe=>{L(Oe.target.value),At()},"onChange"),children:["kimi","anthropic","openai"].map(Oe=>(0,t.jsx)("option",{children:Oe},Oe))})}),(0,t.jsx)(ks,{label:"Kimi API base URL",hint:"Optional override for your provider endpoint.",children:(0,t.jsx)(ut,{"aria-label":"Kimi API base URL",value:A,onChange:r(Oe=>{T(Oe.target.value),At()},"onChange"),placeholder:"Provider default"})})]}),n==="cursor_cloud"&&(0,t.jsxs)("div",{className:"grid gap-5 sm:grid-cols-2",children:[(0,t.jsx)(ks,{label:"GitHub repository",children:(0,t.jsx)(ut,{"aria-label":"GitHub repository",value:we,onChange:r(Oe=>{Se(Oe.target.value),At()},"onChange"),placeholder:"https://github.com/your-org/repo"})}),(0,t.jsx)(ks,{label:"Branch",children:(0,t.jsx)(ut,{"aria-label":"Branch",placeholder:"Repository default",value:Te,onChange:r(Oe=>{le(Oe.target.value),At()},"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:Oq,value:Q,disabled:ze.forced,onChange:r(Oe=>{re(Oe.target.value),se(null),At(),f&&P("connect")},"onChange"),children:[(0,t.jsxs)("option",{value:"",children:["Default: ",Re]}),(De.data??[]).filter(Oe=>Oe.status==="active"&&(!et||Oe.driver!=="local")).map(Oe=>(0,t.jsx)("option",{value:Oe.id,children:Uk(Oe)},Oe.id))]})]})]}),(0,t.jsx)(p1e,{variant:h?"prerequisites":"connection",state:Ze,result:Be,error:jt,disabled:!Bt||Le||!!(f&&!ae),onTest:r(()=>{ss()},"onTest")}),jt&&Ze!=="fail"&&(0,t.jsx)("p",{role:"alert",className:"text-sm text-destructive",children:jt}),(0,t.jsxs)("div",{className:"flex justify-between border-t border-border py-5",children:[f?(0,t.jsxs)($,{type:"button",variant:"ghost",disabled:Le,onClick:$t,children:[(0,t.jsx)(jl,{className:"size-4"}),"Connection"]}):(0,t.jsx)("span",{}),f&&!ae?(0,t.jsxs)($,{type:"button",disabled:!Bt||Le,onClick:r(()=>P("connect"),"onClick"),children:["Connect model",(0,t.jsx)(ml,{className:"size-4"})]}):(0,t.jsxs)($,{type:"submit",disabled:!Bt||Le||Ze==="fail"||!!(f&&!ae),children:[ve?"Creating…":"Finish setup",(0,t.jsx)(us,{className:"size-4"})]})]})]})},O)})})]})]})})}r(Tus,"Setup");function Rus(){const{setBreadcrumbs:e}=Hn();return(0,m.useEffect)(()=>{e([{label:"Agents",href:"/agents"},{label:"New agent"}])},[e]),(0,t.jsx)(Aus,{})}r(Rus,"NewAgent");var g4="paperclip:pending-invite-token";function UY(){return typeof window<"u"&&typeof window.localStorage<"u"}r(UY,"canUseStorage");function Uxe(e){const s=e.trim();if(!(!s||!UY()))try{window.localStorage.setItem(g4,s)}catch{}}r(Uxe,"rememberPendingInviteToken");function qE(e){if(UY())try{const s=window.localStorage.getItem(g4);if(e&&s!==e.trim())return;window.localStorage.removeItem(g4)}catch{}}r(qE,"clearPendingInviteToken");function Eus(){if(!UY())return null;try{const e=window.localStorage.getItem(g4)?.trim();return e?`/invite/${e}`:null}catch{return null}}r(Eus,"getRememberedInvitePath");var Kxe=[" ",".","·","▪","▫","○"],Pus=1e3/24,UE=[[" ╭────╮ "," ╭╯╭──╮│ "," │ │ ││ "," │ │ ││ "," │ │ ││ "," │ │ ││ "," │ ╰──╯│ "," ╰─────╯ "],[" ╭─────╮ "," │╭──╮╰╮ "," ││ │ │ "," ││ │ │ "," ││ │ │ "," ││ │ │ "," │╰──╯ │ "," ╰────╯ "]];function Wxe(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(Wxe,"measureChar");function Mus(e){let s=0;for(const n of e)s=Math.max(s,n.length);return{width:s,height:e.length}}r(Mus,"spriteSize");function Dus(){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),b=new Float32Array(0),v=new Uint16Array(0),j=[],N="";function w(P){const U=Math.floor(Math.max(0,Math.min(.999,P))*Kxe.length);return Kxe[U]??" "}r(w,"toGlyph");function k(){const P=Math.max(0,Math.ceil(n.clientWidth/Math.max(1,h))),U=Math.max(0,Math.ceil(n.clientHeight/Math.max(1,p)));if(P===d&&U===u)return;d=P,u=U;const M=d*u;f=new Float32Array(M),x=new Float32Array(d),b=new Float32Array(u),v=new Uint16Array(M),j=j.filter(B=>B.x>-B.width-2&&B.x<d+2&&B.y>-B.height-2&&B.y<u+2),N=""}r(k,"rebuildGrid");function S(){if(d<=0||u<=0){n.textContent="";return}const P=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;P[q][z]=w(K)}const U=18,M=13;for(let q=1;q<u-9;q+=M){const z=Math.floor(q/M)%2===0?2:10;for(let K=z;K<d-10;K+=U){const W=UE[(K+q)%UE.length];for(let Q=0;Q<W.length;Q++){const re=W[Q];for(let J=0;J<re.length;J++){const ie=re[J]??" ";if(ie===" ")continue;const X=q+Q,ne=K+J;X<0||X>=u||ne<0||ne>=d||(P[X][ne]=ie)}}}}const B=P.map(q=>q.join("")).join(`
667
667
  `);n.textContent=B,N=B}r(S,"drawStaticFrame");function C(){const P=UE[Math.floor(Math.random()*UE.length)],U=Mus(P),M=Math.random();let B=0,q=0,z=0,K=0;M<.68?(B=Math.random()<.5?-U.width-1:d+1,q=Math.random()*Math.max(1,u-U.height),z=B<0?.04+Math.random()*.05:-(.04+Math.random()*.05),K=(Math.random()-.5)*.014):(B=Math.random()*Math.max(1,d-U.width),q=Math.random()<.5?-U.height-1:u+1,z=(Math.random()-.5)*.014,K=q<0?.028+Math.random()*.034:-(.028+Math.random()*.034)),j.push({x:B,y:q,vx:z,vy:K,life:0,maxLife:260+Math.random()*220,drift:(Math.random()-.5)*1.2,sprite:P,width:U.width,height:U.height})}r(C,"spawnClip");function _(P,U){const M=Math.round(P.x),B=Math.round(P.y);for(let q=0;q<P.sprite.length;q++){const z=P.sprite[q],K=B+q;if(!(K<0||K>=u))for(let W=0;W<z.length;W++){const Q=z[W]??" ";if(Q===" ")continue;const re=M+W;if(re<0||re>=d)continue;const J=K*d+re,ie=Q==="│"||Q==="─"?.8:.92;f[J]=Math.max(f[J]??0,U*ie),v[J]=Q.charCodeAt(0)}}}r(_,"stampClip");function R(P){if(!o||(s.current=requestAnimationFrame(R),P-l<Pus||d<=0||u<=0))return;const U=Math.min(2,l===0?1:(P-l)/16.6667);l=P,c+=U;const M=d*u,B=Math.max(3,Math.floor(M/2200));for(;j.length<B;)C();for(let z=0;z<f.length;z++)f[z]*=.92;v.fill(0);for(let z=j.length-1;z>=0;z--){const K=j[z];K.life+=U;const W=Math.sin((K.y+K.drift+c*.12)*.09)*.0018,Q=Math.cos((K.x-K.drift-c*.09)*.08)*.0014;if(K.vx=(K.vx+W)*.998,K.vy=(K.vy+Q)*.998,K.x+=K.vx*U,K.y+=K.vy*U,K.life>=K.maxLife||K.x<-K.width-2||K.x>d+2||K.y<-K.height-2||K.y>u+2){j.splice(z,1);continue}const re=K.life/K.maxLife;_(K,re<.12?re/.12:re>.88?(1-re)/.12:1)}for(let z=0;z<d;z++)x[z]=Math.sin(z*.08+c*.06);for(let z=0;z<u;z++)b[z]=Math.cos(z*.1-c*.05);let q="";for(let z=0;z<u;z++){for(let K=0;K<d;K++){const W=z*d+K,Q=v[W];if(Q>0){q+=String.fromCharCode(Q);continue}const re=(x[K]+b[z])*.08+.1,J=Math.max(f[W]??0,re*.45);q+=w(J)}z<u-1&&(q+=`
668
- `)}q!==N&&(n.textContent=q,N=q)}r(R,"step");function A(){const P=d>0&&u>0;if(a.matches){o&&(o=!1,s.current!==null&&cancelAnimationFrame(s.current),s.current=null),P&&S();return}if(!i||!P){o&&(o=!1,s.current!==null&&cancelAnimationFrame(s.current),s.current=null);return}o||(o=!0,l=0,s.current=requestAnimationFrame(R))}r(A,"syncLoop");const T=new ResizeObserver(()=>{const P=Wxe(n);h=P.w,p=P.h,k(),A()});T.observe(n);const E=r(()=>{i=document.visibilityState!=="hidden",A()},"onVisibilityChange");document.addEventListener("visibilitychange",E);const L=r(()=>{A()},"onMotionChange");a.addEventListener("change",L);const O=Wxe(n);return h=O.w,p=O.h,k(),A(),()=>{o=!1,s.current!==null&&cancelAnimationFrame(s.current),T.disconnect(),document.removeEventListener("visibilitychange",E),a.removeEventListener("change",L)}},[]),(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(Dus,"AsciiArtAnimation");function Lus({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(Lus,"PaperclipLockup");function $us(){const e=Nt(),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",b=(0,m.useMemo)(()=>nIe(n.get("next")||Eus()||"/"),[n]),v=te({queryKey:D.health,queryFn:r(()=>yu.get(),"queryFn"),retry:!1}),{data:j,isLoading:N,error:w}=te({queryKey:D.auth.session,queryFn:r(()=>Ma.getSession(),"queryFn"),retry:!1});(0,m.useEffect)(()=>{j&&(pQ(),s(b,{replace:!0}))},[j,s,b]);const k=ye({mutationFn:r(async()=>{if(a==="sign_in"){await Ma.signInEmail({email:c.trim(),password:u});return}await Ma.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(b,{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||N||j?(0,t.jsx)("div",{className:"fixed inset-0 flex items-center justify-center",children:(0,t.jsx)(Jm,{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)(fQ,{cloud:v.data.cloud,returnTo:b}):(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)(ZN,{})}),(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)(Lus,{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(),!k.isPending){if(!S){f("Please fill in all required fields.");return}k.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:k.isPending,"aria-disabled":!S||k.isPending,className:`w-full ${!S&&!k.isPending?"opacity-50":""}`,children:k.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)(Dus,{})})]})}r($us,"AuthPage");function Ous(){const e=Nt(),s=fa(),[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(()=>Ma.getSession(),"queryFn"),retry:!1}),c=te({queryKey:["board-claim",a,i],queryFn:r(()=>lr.getBoardClaimStatus(a,i),"queryFn"),enabled:a.length>0&&i.length>0,retry:!1}),d=ye({mutationFn:r(()=>lr.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(Ous,"BoardClaimPage");function Vxe({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)(lm,{className:"size-4 shrink-0","aria-hidden":"true"}),(0,t.jsx)("bdi",{className:"min-w-0 break-all",children:e})]})}r(Vxe,"ClientOrigin");function Hxe({agentPairingOnly:e=!1}={}){const{id:s=""}=fa();return(0,t.jsx)(R$e,{id:s,agentPairingOnly:e},s)}r(Hxe,"McpConnectPage");function Fus({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)(R$e,{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)(wl,{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)(ut,{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(Fus,"McpDevicePage");function R$e({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,b]=(0,m.useState)(!0),[v,j]=(0,m.useState)(null),N=te({queryKey:[s?"mcp-device":n?"dot-mcp-request":"mcp-request",e],queryFn:r(()=>Ce.get(s?`/mcp/device?user_code=${encodeURIComponent(e)}`:`${i}/${encodeURIComponent(e)}`),"queryFn"),retry:!1}),w=N.data;(0,m.useEffect)(()=>{if(h(null),f(""),!w?.agentConnection||s||!/^[A-Za-z0-9_-]{32}$/.test(c.trim()))return;let U=!0;return Ce.post(`${i}/${encodeURIComponent(e)}/dot-pairing/preview`,{pairingCode:c.trim()}).then(M=>{U&&h(M)}).catch(M=>{U&&f(M instanceof Error?M.message:"Unable to verify this pairing code.")}),()=>{U=!1}},[e,s,i,w?.agentConnection,c]);const k=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(U=>U.id===k),A=!!(!w?.agentConnection&&R?.canWrite&&x),T=!!(w?.requestedWrite&&A),E=!!(w?.requestedConfigure&&A),L=ye({mutationFn:r(U=>Ce.post(s?"/mcp/device/consent":`/mcp/requests/${encodeURIComponent(e)}/consent`,{decision:U,companyId:k||void 0,allowWrites:U==="approve"&&T,allowConfiguration:U==="approve"&&E,...s?{userCode:e}:{}}),"mutationFn"),onSuccess:r(({redirectUrl:U,status:M})=>{s&&M?j(M):U&&window.location.assign(U)},"onSuccess")}),O=ye({mutationFn:r(()=>Ce.post(`${i}/${encodeURIComponent(e)}/dot-pairing`,{pairingCode:c.trim()}),"mutationFn"),onSuccess:r(({redirectUrl:U})=>{d(""),window.location.assign(U)},"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)(wl,{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 P=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)(wl,{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)(Vxe,{origin:_},_),!s&&w?.redirectOrigin&&w.redirectOrigin!==_&&(0,t.jsx)(Vxe,{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()})]}),N.isPending&&(0,t.jsx)("p",{className:"text-sm text-muted-foreground",children:"Loading connection request…"}),N.error&&(0,t.jsxs)("p",{className:"text-sm text-destructive",children:[N.error.message," Start a new connection from your assistant."]}),s&&N.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(U=>{U.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)(ut,{id:"dot-pairing-code",type:"password",autoComplete:"off",value:c,onChange:r(U=>{h(null),f(""),d(U.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(P)}`,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)(Ag,{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:L.isPending,children:[(0,t.jsx)("legend",{className:"mb-2 text-sm font-medium",children:"Organization"}),w.companies.map(U=>(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":U.name,value:U.id,checked:k===U.id,onChange:r(()=>l(U.id),"onChange")}),(0,t.jsx)(Ag,{companyName:U.name,logoUrl:U.logoUrl,className:"size-12 shrink-0 rounded-lg"}),(0,t.jsx)("span",{className:"min-w-0 break-words font-medium",children:U.name})]},U.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)(Za,{id:"mcp-allow-writes",checked:A,disabled:!R?.canWrite||L.isPending,onCheckedChange:r(U=>b(U===!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."}),L.error&&(0,t.jsx)("p",{className:"text-sm text-destructive",children:L.error.message}),(0,t.jsxs)("div",{className:"flex items-center justify-between gap-3",children:[(0,t.jsx)($,{variant:"outline",disabled:L.isPending,onClick:r(()=>L.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||L.isPending,onClick:r(()=>L.mutate("approve"),"onClick"),children:L.isPending?"Connecting…":w.agentConnection?"Connect Dot agent":"Connect organization"})]})]})})]})})}r(R$e,"McpConnectRequest");function Bus(){const e=Nt(),s=te({queryKey:["mcp-connections"],queryFn:r(()=>Ce.get("/mcp/connections"),"queryFn"),retry:!1}),n=s.data?.filter(i=>!i.revokedAt),a=ye({mutationFn:r(i=>Ce.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:r4(i),avatarUrl:i.user?.image,initials:Ob(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(Bus,"AssistantConnectionsPage");function zus(){const e=Nt(),s=fa(),[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(()=>Ma.getSession(),"queryFn"),retry:!1}),c=te({queryKey:["cli-auth-challenge",a,i],queryFn:r(()=>lr.getCliAuthChallenge(a,i),"queryFn"),enabled:a.length>0&&i.length>0,retry:!1}),d=ye({mutationFn:r(()=>lr.approveCliAuthChallenge(a,i),"mutationFn"),onSuccess:r(async()=>{await e.invalidateQueries({queryKey:D.auth.session}),await c.refetch()},"onSuccess")}),u=ye({mutationFn:r(()=>lr.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(zus,"CliAuthPage");var qus=gBe.filter(e=>e!=="paperclip_runner"),Qxe=new Set(["claude_local","codex_local","gemini_local","kimi_local","opencode_local","pi_local","cursor"]);function Uus(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(Uus,"readNestedString");var tN="w-full border border-zinc-800 bg-zinc-950 px-3 py-2 text-sm text-zinc-100 outline-none focus:border-zinc-500",Gxe="border border-zinc-800 bg-zinc-950/95 p-6",Yxe="flex-1 border px-3 py-2 text-sm transition-colors";function Kus(e){return e?e.charAt(0).toUpperCase()+e.slice(1):null}r(Kus,"formatHumanRole");function E$e(e){if(!e||typeof e!="object")return null;const s=e.code;return typeof s=="string"&&s.trim().length>0?s:null}r(E$e,"getAuthErrorCode");function Wus(e){if(!(e instanceof Error))return null;const s=e.message.trim();return s.length>0?s:null}r(Wus,"getAuthErrorMessage");function Vus(e,s,n){const a=E$e(e),i=Wus(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(Vus,"mapInviteAuthFeedback");function Jxe(e){return!!(e&&typeof e=="object"&&"bootstrapAccepted"in e)}r(Jxe,"isBootstrapAcceptancePayload");function Hus(e,s){return!e||typeof e!="object"||s?!1:e.status==="approved"}r(Hus,"isApprovedHumanJoinPayload");function w9({companyDisplayName:e,companyLogoUrl:s,className:n}){return(0,t.jsx)(Ag,{companyName:e,logoUrl:s,logoFit:"contain",className:n})}r(w9,"InviteCompanyLogo");function Xxe({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)(w9,{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(Xxe,"AwaitingJoinApprovalPanel");function Qus(){const e=Nt(),s=Gn(),{setSelectedCompanyId:n}=ps(),a=(fa().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)(""),[b,v]=(0,m.useState)("claude_local"),[j,N]=(0,m.useState)(""),[w,k]=(0,m.useState)(null),[S,C]=(0,m.useState)(null),[_,R]=(0,m.useState)(null),[A,T]=(0,m.useState)(!1),E="invite-auth-error",L=te({queryKey:D.health,queryFn:r(()=>yu.get(),"queryFn"),retry:!1}),O=te({queryKey:D.auth.session,queryFn:r(()=>Ma.getSession(),"queryFn"),retry:!1}),P=te({queryKey:D.access.invite(a),queryFn:r(()=>lr.getInvite(a),"queryFn"),enabled:a.length>0,retry:!1}),U=L9({enabled:!!O.data&&!!P.data?.companyId,staleTime:0}),M=L.data?.deploymentMode!=="local_trusted"?U.isFetchedAfterMount:!0,B=M?U.data?.companies??[]:[];(0,m.useEffect)(()=>{a&&Uxe(a)},[a]),(0,m.useEffect)(()=>{T(!1)},[a]),(0,m.useEffect)(()=>{if(!M)return;const Se=U.data?.companies;!Se||!P.data?.companyId||Se.some(Te=>Te.id===P.data.companyId)&&qE(a)},[U.data,P.data,M,a]);const q=P.data,z=!!O.data&&!!q?.companyId&&!M,K=!!q?.companyId&&B.some(Se=>Se.id===q?.companyId),W=q?.companyName?.trim()||"this Paperclip company",Q=q?.companyLogoUrl?.trim()||null,re=q?.invitedByUserName?.trim()||null,J=q?.inviteMessage?.trim()||null,ie=Kus(q?.humanRole),X=q?.joinRequestStatus??null,ne=q?.joinRequestType??null,oe=ne==="human"&&(X==="pending_approval"||X==="approved"),G=L.data?.deploymentMode==="authenticated"&&!O.data&&q?.allowedJoinTypes!=="agent",Z=q?.inviteType!=="bootstrap_ceo"&&q?.allowedJoinTypes==="agent",Y=!!O.data&&!Z&&q?.inviteType!=="bootstrap_ceo"&&(!X||oe)&&!z&&!K&&!w&&S===null,ae=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=ye({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"?lr.acceptInvite(a,{requestType:"human"}):lr.acceptInvite(a,{requestType:"agent",agentName:f.trim(),adapterType:b,capabilities:j.trim()||null})},"mutationFn"),onSuccess:r(async Se=>{C(null),qE(a);const Te=Jxe(Se);k({kind:Te?"bootstrap":"join",payload:Se}),await e.invalidateQueries({queryKey:D.auth.session}),await e.invalidateQueries({queryKey:D.access.currentBoardAccess}),await e.invalidateQueries({queryKey:D.companies.all}),q?.companyId&&Hus(Se,Z)&&(n(q.companyId,{source:"manual"}),s("/",{replace:!0}))},"onSuccess"),onError:r(Se=>{C(Se instanceof Error?Se.message:"Failed to accept invite")},"onError")});(0,m.useEffect)(()=>{!Y||A||ce.isPending||(T(!0),C(null),ce.mutate())},[ce,A,Y]);const pe=ye({mutationFn:r(async()=>{if(i==="sign_in"){await Ma.signInEmail({email:d.trim(),password:h});return}await Ma.signUpEmail({name:l.trim(),email:d.trim(),password:h})},"mutationFn"),onSuccess:r(async()=>{R(null),Uxe(a),await e.invalidateQueries({queryKey:D.auth.session}),await e.invalidateQueries({queryKey:D.health}),await e.invalidateQueries({queryKey:D.access.currentBoardAccess});const{companies:Se}=await KBe(e);if(q?.companyId&&Se.some(Te=>Te.id===q.companyId)){qE(a),n(q.companyId,{source:"manual"}),s("/",{replace:!0});return}if(!(!q||q.inviteType!=="bootstrap_ceo"))try{Jxe(await ce.mutateAsync())&&s("/",{replace:!0})}catch{return}},"onSuccess"),onError:r(Se=>{const Te=Vus(Se,i,d);E$e(Se)==="USER_ALREADY_EXISTS_USE_ANOTHER_EMAIL"&&(o("sign_in"),p("")),R(Te)},"onError")}),we=(0,m.useMemo)(()=>q?K?"Open organization":q.inviteType==="bootstrap_ceo"?"Accept invite":Z?"Submit request":O.data?"Accept invite":"Continue":"Continue",[q,K,O.data,Z]);if(!a)return(0,t.jsx)("div",{className:"mx-auto max-w-xl py-10 text-sm text-destructive",children:"Invalid invite token."});if(P.isLoading||L.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(P.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(X==="approved"&&ne==="human"&&K)return(0,t.jsx)("div",{className:"mx-auto max-w-xl py-10 text-sm text-muted-foreground",children:"Opening organization..."});if(X==="pending_approval"&&!oe)return(0,t.jsx)(Xxe,{companyDisplayName:W,companyLogoUrl:Q,invitedByUserName:re});if(X&&!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:X==="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 Se=w.payload,Te=typeof Se.claimSecret=="string"?Se.claimSecret:null,le=typeof Se.claimApiKeyPath=="string"?Se.claimApiKeyPath:null,fe=Uus(Se.onboarding,["textInstructions","url"]);return!Z&&Se.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)(w9,{companyDisplayName:W,companyLogoUrl:Q,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)(Xxe,{companyDisplayName:W,companyLogoUrl:Q,invitedByUserName:re,claimSecret:Te,claimApiKeyPath:le,onboardingTextUrl:fe})}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:`${Gxe} space-y-6`,children:[(0,t.jsxs)("div",{className:"flex items-start gap-4",children:[(0,t.jsx)(w9,{companyDisplayName:W,companyLogoUrl:Q,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 ${W}`}),(0,t.jsx)("p",{className:"mt-2 max-w-2xl text-sm leading-6 text-zinc-300",children:Z?"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:W})]}),(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:re??"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:Z?"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:qd(q.expiresAt)})]})]}),J?(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:J})]}):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:ae}),"."]}):null]}),(0,t.jsx)("section",{className:`${Gxe} h-fit`,children:Z?(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 ",W,"."]})]}),(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:tN,value:f,onChange:r(Se=>x(Se.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:tN,value:b,onChange:r(Se=>v(Se.target.value),"onChange"),children:qus.map(Se=>(0,t.jsxs)("option",{value:Se,disabled:!Qxe.has(Se),children:[ax(Se),Qxe.has(Se)?"":" (Coming soon)"]},Se))})]}),(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:tN,rows:4,value:j,onChange:r(Se=>N(Se.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...":we})]}):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 ${W}.`:"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:`${Yxe} ${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:`${Yxe} ${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(Se=>{if(Se.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:tN,value:l,onChange:r(Se=>{c(Se.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:tN,value:d,onChange:r(Se=>{u(Se.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:tN,value:h,onChange:r(Se=>{p(Se.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 ${W}.`:K?`This account already belongs to ${W}.`:`This will ${q.inviteType==="bootstrap_ceo"?"finish setting up Paperclip":`grant or complete your access to ${W}`}.`})]}),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){qE(a),n(q.companyId,{source:"manual"}),s("/",{replace:!0});return}ce.mutate()},"onClick"),children:ce.isPending?"Working...":we})]})})]})})})}r(Qus,"InviteLandingPage");var Gus=15e3,Yus={parent:"Parent task",child:"Sub-task",blocked_by:"Blocked by",blocks:"Blocks"};function Jus(){(0,m.useEffect)(()=>{const e=document.createElement("meta");return e.name="robots",e.content="noindex",document.head.appendChild(e),()=>e.remove()},[])}r(Jus,"useNoIndexMeta");function N9(e,s){const n=`/s/${encodeURIComponent(e)}`;return s?`${n}/issues/${encodeURIComponent(s)}`:n}r(N9,"sharePath");var Xus=/^(?:https?:\/\/[^/]+)?\/api\/attachments\/([^/?#]+)\/content(?:[?#].*)?$/i;function Zus(e,s){const n=Xus.exec(s.trim());return n?`/api/public/share/${encodeURIComponent(e)}/attachments/${n[1]}/content`:null}r(Zus,"publicShareImageSrc");function j1({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(j1,"Section");function k9({actor:e}){return(0,t.jsx)(yo,{name:e.name,avatarUrl:e.iconUrl,size:"sm"})}r(k9,"ActorIdentity");function S9({value:e}){return(0,t.jsx)("time",{dateTime:e,title:br(e),className:"text-xs text-muted-foreground",children:gr(e)})}r(S9,"Timestamp");function ems({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(ems,"ActiveRunPill");function P$e({attachments:e}){return(0,t.jsx)(hV,{children:e.map(s=>{const n=Rke({name:s.filename,url:s.url,contentType:s.contentType,byteSize:s.byteSize}),a=n.icon,i=pV(s.byteSize);return(0,t.jsxs)(lV,{size:"sm",children:[(0,t.jsx)(cV,{children:(0,t.jsx)(a,{"aria-hidden":!0})}),(0,t.jsxs)(dV,{children:[(0,t.jsx)(uV,{className:"max-w-48",children:s.filename}),(0,t.jsx)(mV,{className:"max-w-48",children:i?`${n.label} · ${i}`:n.label})]}),(0,t.jsx)(_ke,{"aria-label":`Download ${s.filename}`,render:(0,t.jsx)("a",{href:s.url,download:s.filename,rel:"noreferrer"})})]},s.id)})})}r(P$e,"AttachmentList");function tms({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)(no,{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:Yus[e.relation]}),e.navigable?(0,t.jsx)(Nd,{to:n?N9(s,e.id):N9(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(tms,"RelatedIssueRow");function sms({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)(k9,{actor:e.author}),(0,t.jsx)(S9,{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)(k9,{actor:e.author}),(0,t.jsx)(S9,{value:e.createdAt})]}),(0,t.jsx)(In,{className:"text-sm",softBreaks:!0,linkIssueReferences:!1,resolveImageSrc:s,children:e.body}),e.attachments.length>0?(0,t.jsx)(P$e,{attachments:e.attachments}):null]})}r(sms,"TimelineEntry");function nms({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)(Ya,{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)(S9,{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)(ho,{className:"h-3.5 w-3.5","aria-hidden":!0}),"Download PDF"]}),(0,t.jsx)(In,{className:"text-sm",linkIssueReferences:!1,resolveImageSrc:s,children:e.body})]})]})}r(nms,"DocumentCard");function rms({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)(ho,{className:"h-3.5 w-3.5","aria-hidden":!0}),"Download"]}):null]})}r(rms,"WorkProductRow");function Zxe({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(Zxe,"CenteredNotice");function ams({view:e,token:s}){const{company:n,issue:a}=e,i=(0,m.useCallback)(o=>Zus(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)(Ag,{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)(Nd,{to:N9(s),className:"inline-flex items-center gap-1.5 text-sm text-muted-foreground hover:text-foreground",children:[(0,t.jsx)(jl,{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)(fp,{status:a.status}),(0,t.jsx)(P0e,{priority:a.priority,showLabel:!0}),a.assignee?(0,t.jsx)(k9,{actor:a.assignee}):null,e.activeRun?(0,t.jsx)(ems,{agentName:e.activeRun.agentName}):null]}),(0,t.jsxs)("p",{className:"text-xs text-muted-foreground",children:["Created ",br(a.createdAt)," · Updated ",gr(a.updatedAt),a.completedAt?` · Completed ${br(a.completedAt)}`:""]})]}),a.description?(0,t.jsx)(In,{className:"text-sm",softBreaks:!0,linkIssueReferences:!1,resolveImageSrc:i,children:a.description}):null,e.related.length>0?(0,t.jsx)(j1,{title:"Related tasks",children:(0,t.jsx)("ul",{className:"space-y-2",children:e.related.map(o=>(0,t.jsx)(tms,{related:o,token:s,isSharedRoot:e.isSharedRoot},`${o.relation}:${o.id}`))})}):null,e.documents.length>0?(0,t.jsx)(j1,{title:"Documents",children:(0,t.jsx)("div",{className:"space-y-2",children:e.documents.map(o=>(0,t.jsx)(nms,{document:o,resolveImageSrc:i},o.key))})}):null,e.attachments.length>0?(0,t.jsx)(j1,{title:"Attachments",children:(0,t.jsx)(P$e,{attachments:e.attachments})}):null,e.workProducts.length>0?(0,t.jsx)(j1,{title:"Work products",children:(0,t.jsx)("ul",{className:"space-y-2",children:e.workProducts.map(o=>(0,t.jsx)(rms,{product:o},o.id))})}):null,(0,t.jsx)(j1,{title:"Activity",children:e.comments.length>0?(0,t.jsx)("ol",{className:"space-y-3",children:e.comments.map(o=>(0,t.jsx)(sms,{comment:o,resolveImageSrc:i},o.id))}):(0,t.jsx)("p",{className:"text-sm text-muted-foreground",children:"No updates yet."})})]})]})}r(ams,"PublicIssueShareContent");function ege(){const{token:e="",issueId:s}=fa();Jus();const n=WUe.test(e),a=te({queryKey:D.publicShare.view(e,s??null),queryFn:r(()=>s?xk.getPublicShareIssue(e,s):xk.getPublicShare(e),"queryFn"),enabled:n,retry:!1,refetchOnWindowFocus:!0,refetchInterval:r(i=>i.state.data?.activeRun?Gus:!1,"refetchInterval")});return!n||a.data===null?(0,t.jsx)(Zxe,{title:"This link is not available",body:"It may have been revoked, or the address is incomplete."}):a.data?(0,t.jsx)(ams,{view:a.data,token:e}):a.isError?(0,t.jsx)(Zxe,{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(ege,"PublicIssueSharePage");function ims(){const{selectedCompany:e,selectedCompanyId:s}=ps(),{setBreadcrumbs:n}=Hn(),{pushToast:a}=Ti(),i=Nt(),[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(()=>lr.listJoinRequests(s,o,c==="all"?void 0:c),"queryFn"),enabled:!!s}),h=ye({mutationFn:r(f=>lr.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=ye({mutationFn:r(f=>lr.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 mn&&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)(j8e,{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(ims,"JoinRequestQueue");var oms=(0,m.lazy)(()=>Id(()=>import("./CompanyExport-01FumBlx.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]))),lms=(0,m.lazy)(()=>Id(()=>import("./Agents.production-_5ubl1b-.js").then(e=>({default:e.Agents})),__vite__mapDeps([22,5,7,9,8,23,24,25,26,27,28,29,30,19,20,21]))),cms=(0,m.lazy)(()=>Id(()=>import("./Routines.production-DvkQeN0E.js").then(e=>({default:e.Routines})),__vite__mapDeps([31,5,7,8,9,32,10,24,25,33,16,12,34,23,26,35,36,37,11,13,28,38,14,39,29,40,41,18,30,42,43,44,19,20,21,27]))),tge=(0,m.lazy)(()=>Id(()=>import("./RoutineDetail.production-BU1uce8a.js").then(e=>({default:e.RoutineDetail})),__vite__mapDeps([45,5,7,8,9,32,10,24,25,33,16,12,34,23,26,35,36,37,11,13,28,38,14,39,29,40,41,18,30,42,43,44,19,20,21,46,47]))),dms=(0,m.lazy)(()=>Id(()=>import("./CompanySkills.production-CLJPeNSr.js").then(e=>({default:e.CompanySkills})),__vite__mapDeps([48,5,7,8,9,10,23,24,25,26,33,16,12,35,36,37,27,11,13,49,47,14,42,21,17,15,50,39,19,20]))),ums=(0,m.lazy)(()=>Id(()=>import("./CompanyActivity.production-BDDgz0sR.js").then(e=>({default:e.CompanyActivity})),__vite__mapDeps([51,5,7,8,9,26,27,25,14,38,36,16,42,43,44,19]))),mms=(0,m.lazy)(()=>Id(()=>import("./OrgChart.production-B_zvlsnl.js").then(e=>({default:e.OrgChart})),__vite__mapDeps([52,5,7,8,9,26,40,41,44,19,20,21])));function Ov({children:e}){return(0,t.jsx)(m.Suspense,{fallback:(0,t.jsx)(Jm,{}),children:e})}r(Ov,"ProductionSurface");function hms(e,s){const n=e&&s;return(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)(nt,{index:!0,element:(0,t.jsx)(An,{to:"dashboard",replace:!0})}),(0,t.jsx)(nt,{path:"dashboard",element:(0,t.jsx)(TIt,{})}),(0,t.jsx)(nt,{path:"dashboard/live",element:(0,t.jsx)(RIt,{})}),(0,t.jsx)(nt,{path:"timeline",element:e?(0,t.jsx)(cf,{to:"/activity/timeline"}):(0,t.jsx)(AEe,{})}),(0,t.jsx)(nt,{path:"onboarding",element:(0,t.jsx)(L$e,{})}),(0,t.jsx)(nt,{path:"companies",element:(0,t.jsx)(gAt,{})}),(0,t.jsx)(nt,{path:"company/settings",element:(0,t.jsx)(EQt,{})}),(0,t.jsx)(nt,{path:"company/settings/connections",element:(0,t.jsx)(DQt,{})}),(0,t.jsx)(nt,{path:"company/settings/environments",element:(0,t.jsx)(An,{to:"/company/settings/instance/environments",replace:!0})}),(0,t.jsx)(nt,{path:"company/settings/cloud-upstream",element:(0,t.jsx)(An,{to:"/company/export",replace:!0})}),(0,t.jsxs)(nt,{element:(0,t.jsx)(op,{pageKey:"company.members"}),children:[(0,t.jsx)(nt,{path:"company/settings/members",element:(0,t.jsx)(nZt,{})}),(0,t.jsx)(nt,{path:"company/settings/access",element:(0,t.jsx)(rZt,{})})]}),(0,t.jsx)(nt,{element:(0,t.jsx)(op,{pageKey:"company.invites"}),children:(0,t.jsx)(nt,{path:"company/settings/invites",element:(0,t.jsx)(An,{to:"/company/settings/members?tab=invites",replace:!0})})}),(0,t.jsx)(nt,{element:(0,t.jsx)(op,{pageKey:"company.export"}),children:(0,t.jsx)(nt,{path:"company/export/*",element:(0,t.jsx)(m.Suspense,{fallback:(0,t.jsx)(Jm,{}),children:(0,t.jsx)(oms,{})})})}),(0,t.jsx)(nt,{element:(0,t.jsx)(Ift,{}),children:(0,t.jsx)(nt,{element:(0,t.jsx)(op,{pageKey:"company.import"}),children:(0,t.jsx)(nt,{path:"company/import",element:(0,t.jsx)(nds,{})})})}),(0,t.jsx)(nt,{element:(0,t.jsx)(op,{pageKey:"company.secrets"}),children:(0,t.jsx)(nt,{path:"company/settings/secrets",element:(0,t.jsx)(Xls,{})})}),(0,t.jsx)(nt,{path:"company/settings/tools",element:(0,t.jsx)(rge,{})}),(0,t.jsx)(nt,{path:"company/settings/tools/:tab",element:(0,t.jsx)(rge,{})}),(0,t.jsx)(nt,{path:"tools",element:(0,t.jsx)(age,{})}),(0,t.jsx)(nt,{path:"tools/:tab",element:(0,t.jsx)(age,{})}),(0,t.jsx)(nt,{path:"apps",element:(0,t.jsx)(Zes,{})}),(0,t.jsx)(nt,{path:"apps/assistant-connection",element:(0,t.jsx)(Des,{})}),(0,t.jsx)(nt,{path:"apps/browse",element:(0,t.jsx)(An,{to:"/apps",replace:!0})}),(0,t.jsx)(nt,{path:"apps/connections",element:(0,t.jsx)(An,{to:"/apps",replace:!0})}),(0,t.jsx)(nt,{path:"apps/byo",element:(0,t.jsx)(nLe,{byoOnly:!0})}),(0,t.jsx)(nt,{path:"apps/vercel-connect",element:(0,t.jsx)(sge,{credentialSource:"vercel_connect"})}),(0,t.jsx)(nt,{path:"apps/connect",element:(0,t.jsx)(sge,{})}),(0,t.jsx)(nt,{path:"apps/chat/connect",element:(0,t.jsx)(CE,{children:(0,t.jsx)(ass,{})})}),(0,t.jsx)(nt,{path:"apps/chat/:endpointId",element:(0,t.jsx)(CE,{children:(0,t.jsx)(An,{to:"settings",replace:!0})})}),(0,t.jsx)(nt,{path:"apps/chat/:endpointId/reviews/:reviewId",element:(0,t.jsx)(CE,{children:(0,t.jsx)(Xpe,{})})}),(0,t.jsx)(nt,{path:"apps/chat/:endpointId/:tab",element:(0,t.jsx)(CE,{children:(0,t.jsx)(Xpe,{})})}),(0,t.jsx)(nt,{path:"apps/connect/:appKey",element:(0,t.jsx)(An,{to:"/apps",replace:!0})}),(0,t.jsx)(nt,{path:"apps/connect/:appKey/:stage",element:(0,t.jsx)(An,{to:"/apps",replace:!0})}),(0,t.jsx)(nt,{path:"apps/review",element:(0,t.jsx)(Kns,{})}),(0,t.jsx)(nt,{path:"apps/attention",element:(0,t.jsx)(An,{to:"/apps",replace:!0})}),(0,t.jsx)(nt,{path:"apps/gateways",element:(0,t.jsx)(nfe,{})}),(0,t.jsx)(nt,{path:"apps/gateways/:gatewayId",element:(0,t.jsx)(An,{to:"overview",replace:!0})}),(0,t.jsx)(nt,{path:"apps/gateways/:gatewayId/:tab",element:(0,t.jsx)(yrs,{})}),(0,t.jsx)(nt,{path:"apps/advanced",element:(0,t.jsx)(Npe,{})}),(0,t.jsx)(nt,{path:"apps/advanced/gateways",element:(0,t.jsx)(nfe,{})}),(0,t.jsx)(nt,{path:"apps/advanced/profiles/new",element:(0,t.jsx)(Ipe,{mode:"new"})}),(0,t.jsx)(nt,{path:"apps/advanced/profiles/:profileId/edit",element:(0,t.jsx)(Ipe,{mode:"edit"})}),(0,t.jsx)(nt,{path:"apps/advanced/profiles/:profileId",element:(0,t.jsx)(Nes,{})}),(0,t.jsx)(nt,{path:"apps/advanced/audit",element:(0,t.jsx)(An,{to:"/apps",replace:!0})}),(0,t.jsx)(nt,{path:"apps/advanced/run-your-own",element:(0,t.jsx)(An,{to:"/apps",replace:!0})}),(0,t.jsx)(nt,{path:"apps/advanced/:tab",element:(0,t.jsx)(Npe,{})}),(0,t.jsx)(nt,{path:"apps/app/:applicationId",element:(0,t.jsx)(efe,{})}),(0,t.jsx)(nt,{path:"apps/app/:applicationId/:tab",element:(0,t.jsx)(efe,{})}),(0,t.jsx)(nt,{path:"apps/:connectionId",element:(0,t.jsx)(An,{to:"permissions",replace:!0})}),(0,t.jsx)(nt,{path:"apps/:connectionId/:tab",element:(0,t.jsx)(Cts,{})}),(0,t.jsx)(nt,{path:"company/settings/instance",element:(0,t.jsx)(An,{to:"/company/settings",replace:!0})}),(0,t.jsx)(nt,{element:(0,t.jsx)(op,{pageKey:"instance.profile"}),children:(0,t.jsx)(nt,{path:"company/settings/instance/profile",element:(0,t.jsx)(dus,{})})}),(0,t.jsx)(nt,{path:"company/settings/instance/general",element:(0,t.jsx)(An,{to:"/company/settings",replace:!0})}),(0,t.jsx)(nt,{path:"company/settings/instance/heartbeats",element:(0,t.jsx)(An,{to:"/company/settings",replace:!0})}),(0,t.jsxs)(nt,{element:(0,t.jsx)(op,{pageKey:"instance.environments"}),children:[(0,t.jsx)(nt,{path:"company/settings/instance/environments",element:(0,t.jsx)(sq,{})}),(0,t.jsx)(nt,{path:"company/settings/instance/environments/new",element:(0,t.jsx)(sq,{mode:"create"})}),(0,t.jsx)(nt,{path:"company/settings/instance/environments/:environmentId/edit",element:(0,t.jsx)(sq,{mode:"edit"})})]}),(0,t.jsx)(nt,{element:(0,t.jsx)(op,{pageKey:"instance.access"}),children:(0,t.jsx)(nt,{path:"company/settings/instance/access",element:(0,t.jsx)(sus,{})})}),(0,t.jsx)(nt,{element:(0,t.jsx)(op,{pageKey:"instance.experimental"}),children:(0,t.jsx)(nt,{path:"company/settings/instance/experimental",element:(0,t.jsx)(tus,{})})}),(0,t.jsxs)(nt,{element:(0,t.jsx)(op,{pageKey:"instance.plugins"}),children:[(0,t.jsx)(nt,{path:"company/settings/instance/plugins",element:(0,t.jsx)(mus,{})}),(0,t.jsx)(nt,{path:"company/settings/instance/plugins/:pluginId",element:(0,t.jsx)(hus,{})})]}),(0,t.jsx)(nt,{element:(0,t.jsx)(op,{pageKey:"instance.adapters"}),children:(0,t.jsx)(nt,{path:"company/settings/instance/adapters",element:(0,t.jsx)(Fxe,{})})}),(0,t.jsx)(nt,{path:"company/settings/:settingsRoutePath/*",element:(0,t.jsx)(YXt,{})}),(0,t.jsx)(nt,{path:"skills/sources",element:(0,t.jsx)(Afe,{})}),(0,t.jsx)(nt,{path:"skills/sources/:sourceId",element:(0,t.jsx)(Afe,{})}),(0,t.jsx)(nt,{path:"skills/studio",element:(0,t.jsx)(Cq,{})}),(0,t.jsx)(nt,{path:"skills/studio/new",element:(0,t.jsx)(Cq,{})}),(0,t.jsx)(nt,{path:"skills/studio/:skillId",element:(0,t.jsx)(Cq,{})}),(0,t.jsx)(nt,{path:"skills/:skillId/studio",element:(0,t.jsx)(M$e,{})}),(0,t.jsx)(nt,{path:"skills/*",element:e?(0,t.jsx)(Das,{}):(0,t.jsx)(Ov,{children:(0,t.jsx)(dms,{})})}),(0,t.jsx)(nt,{path:"settings",element:(0,t.jsx)(ay,{})}),(0,t.jsx)(nt,{path:"settings/*",element:(0,t.jsx)(ay,{})}),(0,t.jsx)(nt,{path:"plugins/:pluginId",element:(0,t.jsx)(Bxe,{})}),(0,t.jsx)(nt,{path:"org",element:e?(0,t.jsx)(An,{to:"/agents/all",replace:!0}):(0,t.jsx)(Ov,{children:(0,t.jsx)(mms,{})})}),(0,t.jsx)(nt,{path:"agents",element:(0,t.jsx)(An,{to:"/agents/all",replace:!0})}),rG.map(a=>(0,t.jsx)(nt,{path:`agents/${a}`,element:e?(0,t.jsx)(a2t,{}):(0,t.jsx)(Ov,{children:(0,t.jsx)(lms,{})})},a)),(0,t.jsx)(nt,{path:"agents/new",element:(0,t.jsx)(Rus,{})}),(0,t.jsx)(nt,{path:"agents/:agentId",element:(0,t.jsx)(AB,{})}),(0,t.jsx)(nt,{path:"agents/:agentId/:tab",element:(0,t.jsx)(AB,{})}),(0,t.jsx)(nt,{path:"agents/:agentId/runs/:runId",element:(0,t.jsx)(AB,{})}),(0,t.jsx)(nt,{path:"projects",element:(0,t.jsx)(CEt,{})}),(0,t.jsx)(nt,{path:"projects/:projectId",element:(0,t.jsx)(Sv,{})}),(0,t.jsx)(nt,{path:"projects/:projectId/overview",element:(0,t.jsx)(Sv,{})}),(0,t.jsx)(nt,{path:"projects/:projectId/issues",element:(0,t.jsx)(Sv,{})}),(0,t.jsx)(nt,{path:"projects/:projectId/issues/:filter",element:(0,t.jsx)(Sv,{})}),(0,t.jsx)(nt,{element:(0,t.jsx)(EF,{}),children:(0,t.jsx)(nt,{path:"projects/:projectId/workspaces/:workspaceId",element:(0,t.jsx)(NPt,{})})}),(0,t.jsx)(nt,{path:"projects/:projectId/workspaces",element:(0,t.jsx)(Sv,{})}),(0,t.jsx)(nt,{path:"projects/:projectId/configuration",element:(0,t.jsx)(Sv,{})}),(0,t.jsx)(nt,{path:"projects/:projectId/budget",element:(0,t.jsx)(Sv,{})}),(0,t.jsx)(nt,{element:(0,t.jsx)(EF,{}),children:(0,t.jsx)(nt,{path:"workspaces",element:(0,t.jsx)(CPt,{})})}),(0,t.jsx)(nt,{path:"issues",element:(0,t.jsx)(YMt,{})}),(0,t.jsx)(nt,{path:"tasks",element:(0,t.jsx)(An,{to:"/issues",replace:!0})}),(0,t.jsx)(nt,{path:"search",element:(0,t.jsx)(x4t,{})}),n?(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)(nt,{path:"issues/all",element:(0,t.jsx)(jh,{view:"all"})}),(0,t.jsx)(nt,{path:"issues/active",element:(0,t.jsx)(jh,{view:"active"})}),(0,t.jsx)(nt,{path:"issues/backlog",element:(0,t.jsx)(jh,{view:"backlog"})}),(0,t.jsx)(nt,{path:"issues/done",element:(0,t.jsx)(jh,{view:"done"})}),(0,t.jsx)(nt,{path:"issues/recent",element:(0,t.jsx)(jh,{view:"recent"})})]}):(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)(nt,{path:"issues/all",element:(0,t.jsx)(An,{to:"/issues",replace:!0})}),(0,t.jsx)(nt,{path:"issues/active",element:(0,t.jsx)(An,{to:"/issues",replace:!0})}),(0,t.jsx)(nt,{path:"issues/backlog",element:(0,t.jsx)(An,{to:"/issues",replace:!0})}),(0,t.jsx)(nt,{path:"issues/done",element:(0,t.jsx)(An,{to:"/issues",replace:!0})}),(0,t.jsx)(nt,{path:"issues/recent",element:(0,t.jsx)(An,{to:"/issues",replace:!0})})]}),(0,t.jsx)(nt,{path:"chats",element:(0,t.jsx)(jFt,{})}),(0,t.jsx)(nt,{path:"chats/:agentRef",element:(0,t.jsx)(NFt,{})}),(0,t.jsx)(nt,{path:"issues/:issueId",element:(0,t.jsx)(xFt,{})}),null,(0,t.jsx)(nt,{path:"routines",element:e?(0,t.jsx)(sBt,{}):(0,t.jsx)(Ov,{children:(0,t.jsx)(cms,{})})}),(0,t.jsx)(nt,{path:"cases",element:(0,t.jsx)(lae,{children:(0,t.jsx)(Qft,{})})}),(0,t.jsx)(nt,{path:"cases/:caseIdentifier",element:(0,t.jsx)(lae,{children:(0,t.jsx)(P0t,{})})}),(0,t.jsx)(nt,{path:"pixels-office",element:(0,t.jsx)(_ft,{children:(0,t.jsx)(P7t,{})})}),(0,t.jsx)(nt,{path:"status",element:(0,t.jsx)(cae,{children:(0,t.jsx)(bue,{})})}),(0,t.jsx)(nt,{path:"status/:cardId",element:(0,t.jsx)(cae,{children:(0,t.jsx)(bue,{})})}),(0,t.jsx)(nt,{path:"status-cards",element:(0,t.jsx)(ige,{})}),(0,t.jsx)(nt,{path:"status-cards/:cardId",element:(0,t.jsx)(ige,{})}),(0,t.jsx)(nt,{path:"review-queue",element:(0,t.jsx)(k0,{children:(0,t.jsx)(yqt,{})})}),(0,t.jsx)(nt,{path:"learnings",element:(0,t.jsx)(k0,{children:(0,t.jsx)(wqt,{})})}),(0,t.jsx)(nt,{path:"pipelines",element:(0,t.jsx)(k0,{children:(0,t.jsx)(xz,{})})}),(0,t.jsx)(nt,{path:"pipelines/:pipelineId",element:(0,t.jsx)(k0,{children:(0,t.jsx)(xz,{})})}),(0,t.jsx)(nt,{path:"pipelines/:pipelineId/add",element:(0,t.jsx)(k0,{children:(0,t.jsx)(xz,{})})}),(0,t.jsx)(nt,{path:"pipelines/:pipelineId/settings",element:(0,t.jsx)(k0,{children:(0,t.jsx)(f6t,{})})}),(0,t.jsx)(nt,{path:"pipelines/:pipelineId/items/:caseId",element:(0,t.jsx)(k0,{children:(0,t.jsx)(Bzt,{})})}),(0,t.jsx)(nt,{path:"pipelines/:pipelineId/cases/:caseId",element:(0,t.jsx)(k0,{children:(0,t.jsx)($zt,{})})}),(0,t.jsx)(nt,{path:"routines/:routineId",element:e?(0,t.jsx)(yme,{}):(0,t.jsx)(Ov,{children:(0,t.jsx)(tge,{})})}),(0,t.jsx)(nt,{path:"routines/:routineId/:section",element:e?(0,t.jsx)(yme,{}):(0,t.jsx)(Ov,{children:(0,t.jsx)(tge,{})})}),(0,t.jsx)(nt,{element:(0,t.jsx)(EF,{}),children:(0,t.jsxs)(nt,{element:(0,t.jsx)(Tft,{}),children:[(0,t.jsx)(nt,{path:"execution-workspaces/:workspaceId",element:(0,t.jsx)(Qw,{})}),(0,t.jsx)(nt,{path:"execution-workspaces/:workspaceId/services",element:(0,t.jsx)(Qw,{})}),(0,t.jsx)(nt,{path:"execution-workspaces/:workspaceId/configuration",element:(0,t.jsx)(Qw,{})}),(0,t.jsx)(nt,{path:"execution-workspaces/:workspaceId/runtime-logs",element:(0,t.jsx)(Qw,{})}),(0,t.jsx)(nt,{path:"execution-workspaces/:workspaceId/issues",element:(0,t.jsx)(Qw,{})}),(0,t.jsx)(nt,{path:"execution-workspaces/:workspaceId/routines",element:(0,t.jsx)(Qw,{})})]})}),(0,t.jsx)(nt,{path:"goals",element:(0,t.jsx)(RWt,{})}),(0,t.jsx)(nt,{path:"goals/:goalId",element:(0,t.jsx)(qWt,{})}),(0,t.jsx)(nt,{path:"artifacts",element:(0,t.jsx)(kme,{})}),(0,t.jsx)(nt,{path:"approvals",element:(0,t.jsx)(An,{to:"/approvals/pending",replace:!0})}),(0,t.jsx)(nt,{path:"approvals/pending",element:(0,t.jsx)(Cme,{})}),(0,t.jsx)(nt,{path:"approvals/all",element:(0,t.jsx)(Cme,{})}),(0,t.jsx)(nt,{path:"approvals/:approvalId",element:(0,t.jsx)(UWt,{})}),(0,t.jsx)(nt,{path:"activity",element:e?(0,t.jsx)(FVt,{}):(0,t.jsx)(Ov,{children:(0,t.jsx)(ums,{})})}),e?(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)(nt,{path:"activity/runs",element:(0,t.jsx)(U1,{section:"runs"})}),(0,t.jsx)(nt,{path:"activity/costs",element:(0,t.jsx)(U1,{section:"costs"})}),(0,t.jsx)(nt,{path:"activity/budgets",element:(0,t.jsx)(U1,{section:"budgets"})}),(0,t.jsx)(nt,{path:"activity/timeline",element:(0,t.jsx)(U1,{section:"timeline"})}),(0,t.jsx)(nt,{path:"audit",element:(0,t.jsx)(cf,{to:"/activity",forceAgentMode:!0})}),(0,t.jsx)(nt,{path:"audit/activity",element:(0,t.jsx)(cf,{to:"/activity"})}),(0,t.jsx)(nt,{path:"audit/runs",element:(0,t.jsx)(cf,{to:"/activity/runs"})}),(0,t.jsx)(nt,{path:"audit/costs",element:(0,t.jsx)(cf,{to:"/activity/costs"})}),(0,t.jsx)(nt,{path:"audit/budgets",element:(0,t.jsx)(cf,{to:"/activity/budgets"})}),(0,t.jsx)(nt,{path:"audit/timeline",element:(0,t.jsx)(cf,{to:"/activity/timeline"})}),(0,t.jsx)(nt,{path:"runs",element:(0,t.jsx)(cf,{to:"/activity/runs"})}),(0,t.jsx)(nt,{path:"costs",element:(0,t.jsx)(cf,{to:"/activity/costs"})}),(0,t.jsx)(nt,{path:"budgets",element:(0,t.jsx)(cf,{to:"/activity/budgets"})})]}):(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)(nt,{path:"costs",element:(0,t.jsx)(r7,{})}),(0,t.jsx)(nt,{path:"audit",element:(0,t.jsx)(An,{to:"/activity?mode=agents",replace:!0})})]}),(0,t.jsxs)(nt,{element:(0,t.jsx)(Lmt,{}),children:[(0,t.jsx)(nt,{path:"board-chat",element:(0,t.jsx)(aQt,{})}),(0,t.jsx)(nt,{path:"artifacts",element:(0,t.jsx)(kme,{})})]}),null,(0,t.jsx)(nt,{path:"decisions",element:(0,t.jsx)(THt,{})}),(0,t.jsx)(nt,{path:"decisions/queues/:key",element:(0,t.jsx)(MHt,{})}),n?(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)(nt,{path:"inbox",element:(0,t.jsx)(nge,{})}),(0,t.jsx)(nt,{path:"inbox/mine",element:(0,t.jsx)(jh,{view:"mine"})}),(0,t.jsx)(nt,{path:"inbox/recent",element:(0,t.jsx)(jh,{view:"recent"})}),(0,t.jsx)(nt,{path:"inbox/unread",element:(0,t.jsx)(jh,{view:"unread"})}),(0,t.jsx)(nt,{path:"inbox/blocked",element:(0,t.jsx)(jh,{view:"blocked"})}),(0,t.jsx)(nt,{path:"inbox/all",element:(0,t.jsx)(jh,{view:"everything"})}),(0,t.jsx)(nt,{path:"inbox/new",element:(0,t.jsx)(jh,{view:"mine"})})]}):(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)(nt,{path:"inbox",element:(0,t.jsx)(nge,{})}),(0,t.jsx)(nt,{path:"inbox/mine",element:(0,t.jsx)(uN,{})}),(0,t.jsx)(nt,{path:"inbox/recent",element:(0,t.jsx)(uN,{})}),(0,t.jsx)(nt,{path:"inbox/unread",element:(0,t.jsx)(uN,{})}),(0,t.jsx)(nt,{path:"inbox/blocked",element:(0,t.jsx)(uN,{})}),(0,t.jsx)(nt,{path:"inbox/all",element:(0,t.jsx)(uN,{})}),(0,t.jsx)(nt,{path:"inbox/new",element:(0,t.jsx)(An,{to:"/inbox/mine",replace:!0})})]}),(0,t.jsx)(nt,{path:"inbox/requests",element:(0,t.jsx)(ims,{})}),(0,t.jsx)(nt,{path:"u/:userSlug",element:(0,t.jsx)(aWt,{})}),(0,t.jsx)(nt,{path:"design-guide",element:(0,t.jsx)(Jds,{})}),(0,t.jsx)(nt,{path:"instance/settings/adapters",element:(0,t.jsx)(Fxe,{})}),(0,t.jsx)(nt,{path:":pluginRoutePath/*",element:(0,t.jsx)(Bxe,{})}),(0,t.jsx)(nt,{path:"*",element:(0,t.jsx)(Zu,{scope:"board"})})]})}r(hms,"boardRoutes");function sge({credentialSource:e="paperclip_vault"}={}){const s=oa(),n=new URLSearchParams(s.search),{enabled:a,githubEnabled:i}=Rj();return Bct(n,{chatConnectorsEnabled:a,githubReviewBotsEnabled:i})?(0,t.jsx)(nLe,{credentialSource:e}):(0,t.jsx)(An,{to:"/apps",replace:!0})}r(sge,"AppsConnectEntryRoute");function nge(){const{enabled:e}=Ac(),{enabled:s}=QA();return e&&s?(0,t.jsx)(jh,{view:Cze(GZ())}):(0,t.jsx)(An,{to:`/inbox/${GZ()}`,replace:!0})}r(nge,"InboxRootRedirect");function jh({view:e}){const s=oa(),n=new URLSearchParams(s.search);return n.set(VE,e),(0,t.jsx)(An,{to:`/issues?${n.toString()}${s.hash}`,replace:!0})}r(jh,"TaskViewRedirect");function M$e(){const e=oa(),{companies:s,selectedCompany:n,loading:a}=ps(),{companyPrefix:i,skillId:o}=fa();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)(An,{to:"/skills/studio",replace:!0}):(0,t.jsx)(An,{to:`/${l.issuePrefix}/skills/studio/${encodeURIComponent(o)}${e.search}${e.hash}`,replace:!0})}r(M$e,"LegacySkillStudioRedirect");function ay(){const e=oa(),{companies:s,selectedCompany:n,loading:a}=ps(),{companyPrefix:i}=fa(),{hidden:o}=vu();if(a)return(0,t.jsx)(Jm,{});const l=(i?s.find(d=>d.issuePrefix.toUpperCase()===i.toUpperCase()):null)??n??s[0]??null;if(!l)return PH({pathname:e.pathname,hasCompanies:!1})?(0,t.jsx)(An,{to:"/onboarding",replace:!0}):(0,t.jsx)(KY,{});const c=KWe(aNe(`${e.pathname}${e.search}${e.hash}`),o);return(0,t.jsx)(An,{to:`/${l.issuePrefix}${c}`,replace:!0})}r(ay,"LegacySettingsRedirect");function rge(){const{tab:e}=fa();return(0,t.jsx)(An,{to:D$e(e),replace:!0})}r(rge,"LegacyToolsSettingsRedirect");function age(){const{tab:e}=fa();return(0,t.jsx)(An,{to:D$e(e),replace:!0})}r(age,"LegacyToolsRedirect");function D$e(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(D$e,"legacyToolsRedirectTarget");function L$e(){const{companies:e}=ps(),{openOnboarding:s}=rl(),{t:n}=Rwe(),a=Yc(),i=sIe(a?.cloudBaseUrl??null),{onboardingOpen:o,onboardingRouteDismissed:l}=P4(),{companyPrefix:c}=fa(),d=c?e.find(p=>p.issuePrefix.toUpperCase()===c.toUpperCase())??null:null;if(Qdt({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:BP(),companyId:d.id}):a&&i?Ym(i):s(),"onClick"),children:d?"Add Agent":"Start Onboarding"})})]})})}r(L$e,"OnboardingRoutePage");function pms(){const{companies:e,selectedCompany:s,loading:n}=ps(),a=oa();if(n)return(0,t.jsx)(Jm,{});const i=s??e[0]??null;return i?(0,t.jsx)(An,{to:`/${i.issuePrefix}/dashboard`,replace:!0}):PH({pathname:a.pathname,hasCompanies:!1})?(0,t.jsx)(An,{to:"/onboarding",replace:!0}):(0,t.jsx)(KY,{})}r(pms,"CompanyRootRedirect");function ige(){const{cardId:e}=fa(),s=Pze(),n=s?`/${s}`:"";return(0,t.jsx)(An,{to:`${n}/status${e?`/${e}`:""}`,replace:!0})}r(ige,"StatusCardsLegacyRedirect");function cf({to:e,forceAgentMode:s=!1}){const n=oa(),a=new URLSearchParams(n.search);s&&a.set("mode","agents");const i=a.toString();return(0,t.jsx)(An,{to:`${e}${i?`?${i}`:""}${n.hash}`,replace:!0})}r(cf,"AuditCompatibilityRedirect");function ya(){const e=oa(),{companies:s,selectedCompany:n,loading:a}=ps();if(a)return(0,t.jsx)(Jm,{});const i=n??s[0]??null;return i?(0,t.jsx)(An,{to:`/${i.issuePrefix}${e.pathname}${e.search}${e.hash}`,replace:!0}):PH({pathname:e.pathname,hasCompanies:!1})?(0,t.jsx)(An,{to:"/onboarding",replace:!0}):(0,t.jsx)(KY,{})}r(ya,"UnprefixedBoardRedirect");function KY(){const{openOnboarding:e}=rl(),{t:s}=Rwe(),n=Yc(),a=sIe(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?Ym(a):e(),"onClick"),children:s("app.noCompanies.newCompany",{defaultValue:"New Organization"})})})]})})}r(KY,"NoCompaniesStartPage");function fms(){const{enabled:e,loaded:s}=Ac(),{enabled:n}=QA();return(0,t.jsxs)(t.Fragment,{children:[(0,t.jsxs)(sze,{children:[(0,t.jsx)(nt,{path:"oauth-handoff",element:(0,t.jsx)(Xns,{})}),(0,t.jsx)(nt,{path:"auth",element:(0,t.jsx)($us,{})}),(0,t.jsx)(nt,{path:"board-claim/:token",element:(0,t.jsx)(Ous,{})}),(0,t.jsx)(nt,{path:"mcp-connect/:id",element:(0,t.jsx)(Hxe,{})}),(0,t.jsx)(nt,{path:"dot-connect/:id",element:(0,t.jsx)(Hxe,{agentPairingOnly:!0})}),(0,t.jsx)(nt,{path:"mcp-device",element:(0,t.jsx)(Fus,{})}),(0,t.jsx)(nt,{path:"assistant-connections",element:(0,t.jsx)(Bus,{})}),(0,t.jsx)(nt,{path:"cli-auth/:id",element:(0,t.jsx)(zus,{})}),(0,t.jsx)(nt,{path:"invite/:token",element:(0,t.jsx)(Qus,{})}),(0,t.jsx)(nt,{path:"s/:token",element:(0,t.jsx)(ege,{})}),(0,t.jsx)(nt,{path:"s/:token/issues/:issueId",element:(0,t.jsx)(ege,{})}),(0,t.jsx)(nt,{element:s?(0,t.jsx)(rie,{allowMembershipRequest:!0}):(0,t.jsx)(Jm,{}),children:(0,t.jsx)(nt,{path:"chat-identity/confirm",element:(0,t.jsx)(qns,{})})}),(0,t.jsx)(nt,{path:"tests/perf/long-thread",element:(0,t.jsx)(MFt,{})}),(0,t.jsx)(nt,{path:"ux-lab/bootstrap-setup",element:(0,t.jsx)(VXt,{})}),(0,t.jsx)(nt,{path:"ux-lab/responsible-user-denial",element:(0,t.jsx)(HXt,{})}),(0,t.jsx)(nt,{path:"ux-lab/cross-issue-collaboration",element:(0,t.jsx)(GXt,{})}),(0,t.jsxs)(nt,{element:s?(0,t.jsx)(rie,{}):(0,t.jsx)(Jm,{}),children:[(0,t.jsx)(nt,{index:!0,element:(0,t.jsx)(pms,{})}),(0,t.jsx)(nt,{path:"onboarding",element:(0,t.jsx)(L$e,{})}),(0,t.jsx)(nt,{path:"instance",element:(0,t.jsx)(ay,{})}),(0,t.jsx)(nt,{path:"instance/settings",element:(0,t.jsx)(ay,{})}),(0,t.jsx)(nt,{path:"instance/settings/*",element:(0,t.jsx)(ay,{})}),(0,t.jsx)(nt,{path:"companies",element:(0,t.jsx)(ya,{})}),(0,t.jsx)(nt,{path:"dashboard",element:(0,t.jsx)(ya,{})}),(0,t.jsx)(nt,{path:"inbox/*",element:(0,t.jsx)(ya,{})}),(0,t.jsx)(nt,{path:"issues",element:(0,t.jsx)(ya,{})}),(0,t.jsx)(nt,{path:"tasks",element:(0,t.jsx)(ya,{})}),(0,t.jsx)(nt,{path:"issues/:issueId",element:(0,t.jsx)(ya,{})}),(0,t.jsx)(nt,{path:"routines",element:(0,t.jsx)(ya,{})}),(0,t.jsx)(nt,{path:"routines/:routineId",element:(0,t.jsx)(ya,{})}),(0,t.jsx)(nt,{path:"review-queue",element:(0,t.jsx)(ya,{})}),(0,t.jsx)(nt,{path:"learnings",element:(0,t.jsx)(ya,{})}),(0,t.jsx)(nt,{path:"cases",element:(0,t.jsx)(ya,{})}),(0,t.jsx)(nt,{path:"cases/:caseIdentifier",element:(0,t.jsx)(ya,{})}),(0,t.jsx)(nt,{path:"pixels-office",element:(0,t.jsx)(ya,{})}),(0,t.jsx)(nt,{path:"status",element:(0,t.jsx)(ya,{})}),(0,t.jsx)(nt,{path:"status/:cardId",element:(0,t.jsx)(ya,{})}),(0,t.jsx)(nt,{path:"status-cards",element:(0,t.jsx)(ya,{})}),(0,t.jsx)(nt,{path:"status-cards/:cardId",element:(0,t.jsx)(ya,{})}),(0,t.jsx)(nt,{path:"pipelines",element:(0,t.jsx)(ya,{})}),(0,t.jsx)(nt,{path:"pipelines/:pipelineId",element:(0,t.jsx)(ya,{})}),(0,t.jsx)(nt,{path:"pipelines/:pipelineId/add",element:(0,t.jsx)(ya,{})}),(0,t.jsx)(nt,{path:"pipelines/:pipelineId/settings",element:(0,t.jsx)(ya,{})}),(0,t.jsx)(nt,{path:"pipelines/:pipelineId/items/:caseId",element:(0,t.jsx)(ya,{})}),(0,t.jsx)(nt,{path:"pipelines/:pipelineId/cases/:caseId",element:(0,t.jsx)(ya,{})}),(0,t.jsx)(nt,{path:"artifacts",element:(0,t.jsx)(ya,{})}),(0,t.jsx)(nt,{path:"audit",element:(0,t.jsx)(ya,{})}),e?(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)(nt,{path:"audit/*",element:(0,t.jsx)(ya,{})}),(0,t.jsx)(nt,{path:"activity",element:(0,t.jsx)(ya,{})}),(0,t.jsx)(nt,{path:"activity/*",element:(0,t.jsx)(ya,{})}),(0,t.jsx)(nt,{path:"runs",element:(0,t.jsx)(ya,{})}),(0,t.jsx)(nt,{path:"costs",element:(0,t.jsx)(ya,{})}),(0,t.jsx)(nt,{path:"budgets",element:(0,t.jsx)(ya,{})})]}):null,(0,t.jsx)(nt,{path:"decisions",element:(0,t.jsx)(ya,{})}),(0,t.jsx)(nt,{path:"u/:userSlug",element:(0,t.jsx)(ya,{})}),(0,t.jsx)(nt,{path:"skills/studio",element:(0,t.jsx)(ya,{})}),(0,t.jsx)(nt,{path:"skills/studio/new",element:(0,t.jsx)(ya,{})}),(0,t.jsx)(nt,{path:"skills/studio/:skillId",element:(0,t.jsx)(ya,{})}),(0,t.jsx)(nt,{path:"skills/:skillId/studio",element:(0,t.jsx)(M$e,{})}),(0,t.jsx)(nt,{path:"skills/*",element:(0,t.jsx)(ya,{})}),(0,t.jsx)(nt,{path:"settings",element:(0,t.jsx)(ay,{})}),(0,t.jsx)(nt,{path:"settings/*",element:(0,t.jsx)(ay,{})}),(0,t.jsx)(nt,{path:"agents",element:(0,t.jsx)(ya,{})}),rG.map(a=>(0,t.jsx)(nt,{path:`agents/${a}`,element:(0,t.jsx)(ya,{})},a)),(0,t.jsx)(nt,{path:"agents/new",element:(0,t.jsx)(ya,{})}),(0,t.jsx)(nt,{path:"agents/:agentId",element:(0,t.jsx)(ya,{})}),(0,t.jsx)(nt,{path:"agents/:agentId/:tab",element:(0,t.jsx)(ya,{})}),(0,t.jsx)(nt,{path:"agents/:agentId/runs/:runId",element:(0,t.jsx)(ya,{})}),(0,t.jsx)(nt,{path:"projects",element:(0,t.jsx)(ya,{})}),(0,t.jsx)(nt,{path:"projects/:projectId",element:(0,t.jsx)(ya,{})}),(0,t.jsx)(nt,{path:"projects/:projectId/overview",element:(0,t.jsx)(ya,{})}),(0,t.jsx)(nt,{path:"projects/:projectId/issues",element:(0,t.jsx)(ya,{})}),(0,t.jsx)(nt,{path:"projects/:projectId/issues/:filter",element:(0,t.jsx)(ya,{})}),(0,t.jsx)(nt,{path:"projects/:projectId/workspaces",element:(0,t.jsx)(ya,{})}),(0,t.jsx)(nt,{path:"projects/:projectId/workspaces/:workspaceId",element:(0,t.jsx)(ya,{})}),(0,t.jsx)(nt,{path:"projects/:projectId/configuration",element:(0,t.jsx)(ya,{})}),(0,t.jsx)(nt,{path:"workspaces",element:(0,t.jsx)(ya,{})}),(0,t.jsx)(nt,{path:"execution-workspaces/:workspaceId",element:(0,t.jsx)(Aw,{})}),(0,t.jsx)(nt,{path:"execution-workspaces/:workspaceId/services",element:(0,t.jsx)(Aw,{})}),(0,t.jsx)(nt,{path:"execution-workspaces/:workspaceId/configuration",element:(0,t.jsx)(Aw,{})}),(0,t.jsx)(nt,{path:"execution-workspaces/:workspaceId/runtime-logs",element:(0,t.jsx)(Aw,{})}),(0,t.jsx)(nt,{path:"execution-workspaces/:workspaceId/issues",element:(0,t.jsx)(Aw,{})}),(0,t.jsx)(nt,{path:"execution-workspaces/:workspaceId/routines",element:(0,t.jsx)(Aw,{})}),(0,t.jsx)(nt,{path:":companyPrefix",element:e?(0,t.jsx)(emt,{}):(0,t.jsx)(Pmt,{}),children:hms(e,n)}),(0,t.jsx)(nt,{path:"*",element:(0,t.jsx)(Zu,{scope:"global"})})]})]}),(0,t.jsx)(jbt,{}),(0,t.jsx)(Mut,{})]})}r(fms,"App");var xms=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){DH(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 gms(){const{data:e}=te({queryKey:D.auth.session,queryFn:r(()=>Ma.getSession(),"queryFn"),retry:!1}),s=e?.sentryDsn,n=e?.sentryEnvironment??void 0;return(0,m.useEffect)(()=>{if(s)return mut(s,n),()=>{hut()}},[s,n]),null}r(gms,"SentryGate");function bms(e){let s=$g();Ele(s),c8(s,e.userId);const n=W3e(()=>{const o=$g();o!==s&&(s=o,Ele(o),c8(o,e.userId))}),a=typeof navigator<"u"&&"serviceWorker"in navigator?navigator.serviceWorker:null,i=r(o=>{const l=W3t(o.data);l&&(l.type==="navigate"?e.navigate(l.url):U3t(l.notification))},"onMessage");return a?.addEventListener("message",i),a?.startMessages(),()=>{n(),a?.removeEventListener("message",i)}}r(bms,"startNotificationRuntime");function vms(){const e=Gn(),s=(0,m.useRef)(e),{data:n}=te({queryKey:D.auth.session,queryFn:r(()=>Ma.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 bms({userId:a,navigate:r(i=>s.current(i),"navigate")})},[a]),null}r(vms,"NotificationRuntime");var $$e={get:r(e=>Ce.get(`/companies/${e}/primary-agent/me`),"get"),set:r((e,s)=>Ce.put(`/companies/${e}/primary-agent/me`,s),"set")};function yms(e){const s=te({queryKey:D.auth.session,queryFn:r(()=>Ma.getSession(),"queryFn")}),n=s.data?.user?.id??s.data?.session?.userId??"local-board",a=te({queryKey:D.primaryAgent.mine(e??"__none__",n),queryFn:r(()=>$$e.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(yms,"usePrimaryAgent");function jms({children:e}){const{selectedCompanyId:s}=ps(),n=yms(s),a=Nt(),{pushToast:i}=Qr(),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(()=>Ct.list(s),"queryFn"),enabled:!!s}),u=ye({mutationFn:r(f=>$$e.set(f.companyId,{primaryAgentId:f.agentId}),"mutationFn"),onMutate:r(async f=>{const x=l(f);await a.cancelQueries({queryKey:x});const b=a.getQueryData(x);return a.setQueryData(x,{companyId:f.companyId,userId:f.userId,primaryAgentId:f.agentId,initialized:!0}),{previous:b}},"onMutate"),onError:r((f,x,b)=>{a.setQueryData(l(x),b?.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,b)=>{a.invalidateQueries({queryKey:l(b)}),a.invalidateQueries({queryKey:D.resourceMemberships.mine(b.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)(X9e,{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(jms,"PrimaryAgentProvider");function wms(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(wms,"managedRoutineToRow");function Nms({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])),b=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 j=wms(v),N=v.href??(v.routineId?`/routines/${v.routineId}`:"/routines"),w=v.missingRefs??[],k=!!(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)(MPe,{routine:j,projectById:b,agentById:x,runningRoutineId:o,statusMutationRoutineId:l,href:N,configureLabel:"Configure",managedByLabel:S?`Managed by ${S}`:null,runNowButton:!0,hideArchiveAction:!0,disableRunNow:!k,disableToggle:!k,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,j.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(Nms,"ManagedRoutinesList");function oge(e){return new Set(e??[])}r(oge,"toPathSet");function kms({expandedPaths:e,checkedPaths:s,selectedFile:n=null,showCheckboxes:a=!1,onToggleDir:i,onSelectFile:o,...l}){return(0,m.createElement)(Kj,{...l,selectedFile:n,expandedDirs:oge(e),checkedFiles:s?oge(s):void 0,showCheckboxes:a,onToggleDir:i??(()=>{}),onSelectFile:o??(()=>{})})}r(kms,"PluginSdkFileTree");function Sms(e){const[s,n]=(0,m.useState)(null);return(0,m.useEffect)(()=>{let a=!1;return Id(()=>import("./MarkdownEditor-D7suACD6.js").then(i=>i.n).then(i=>{a||n(()=>i.MarkdownEditor)}),__vite__mapDeps([35,5,7,9,10,25,24,26,36,37])),()=>{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(Sms,"PluginSdkMarkdownEditor");function Cms(e){return Object.fromEntries(Object.entries(e).filter(([,s])=>s!=null&&s!==""&&s!==!1))}r(Cms,"compactIssueFilters");function _ms({companyId:e,projectId:s=null,filters:n,viewStateKey:a="paperclip:plugin-issues-view",initialSearch:i,createIssueLabel:o,searchWithinLoadedIssues:l=!0}){const c=Nt(),d=(0,m.useMemo)(()=>Cms({...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(()=>Ct.list(e),"queryFn"),enabled:!!e}),{data:x}=te({queryKey:D.projects.list(e??"__no-company__",{includeArchived:!0}),queryFn:r(()=>ra.list(e,{includeArchived:!0}),"queryFn"),enabled:!!e}),b=D.liveRuns(e??"__no-company__"),v=jo({companyId:e,resourceKey:"live-runs",queryKey:b,enabled:!!e,refetchInterval:!1,leaderOnly:!0}),{data:j,dataUpdatedAt:N}=te({queryKey:b,queryFn:r(()=>Xr.liveRunsForCompany(e),"queryFn"),enabled:v.enabled,refetchInterval:v.refetchInterval});wo(v,j,N);const{data:w,isLoading:k,error:S}=te({queryKey:p,queryFn:r(()=>yt.list(e,d),"queryFn"),enabled:!!e}),C=(0,m.useMemo)(()=>qg(j,w),[w,j]),_=ye({mutationFn:r(({id:R,data:A})=>yt.update(R,A),"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)(Cg,{issues:w??[],isLoading:k,error:S,agents:f,projects:x,liveIssueIds:C,projectId:h??void 0,viewStateKey:a,initialSearch:i,createIssueLabel:o,searchWithinLoadedIssues:l,onUpdateIssue:r((R,A)=>_.mutate({id:R,data:A}),"onUpdateIssue")}):(0,m.createElement)("div",{className:"text-sm text-muted-foreground"},"Select an organization to view tasks.")}r(_ms,"PluginSdkIssuesList");function Ims({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=$W(),f=e??p.companyId??null,{data:x}=te({queryKey:D.auth.session,queryFn:r(()=>Ma.getSession(),"queryFn"),enabled:c}),b=x?.user?.id??x?.session?.userId??null,{data:v}=te({queryKey:D.agents.list(f??"__no-company__"),queryFn:r(()=>Ct.list(f),"queryFn"),enabled:!!f}),{data:j}=te({queryKey:D.access.companyUserDirectory(f??"__no-company__"),queryFn:r(()=>lr.listUserDirectory(f),"queryFn"),enabled:!!f&&c}),N=(0,m.useMemo)(()=>Yq(),[]),w=(0,m.useMemo)(()=>N.map(R=>R.startsWith("agent:")?R.slice(6):null).filter(R=>!!R),[N]),k=(0,m.useMemo)(()=>Oy((v??[]).filter(R=>d||R.status!=="terminated"),w),[v,d,w]),S=(0,m.useMemo)(()=>[...c?O0e(b):[],...c?TS(j?.users,{excludeUserIds:[b]}):[],...k.map(R=>({id:Ih({assigneeAgentId:R.id}),label:R.name,searchText:`${R.name} ${R.role} ${R.title??""}`}))],[j?.users,b,c,k]),C=vy(s),_=C.assigneeAgentId?k.find(R=>R.id===C.assigneeAgentId):null;return(0,m.createElement)(Yu,{value:s,options:S,recentOptionIds:N,placeholder:a,noneLabel:i,searchPlaceholder:o,emptyMessage:l,className:u,onConfirm:h,onChange:r(R=>{const A=vy(R);A.assigneeAgentId&&Fy(A.assigneeAgentId),A.assigneeUserId&&K_(A.assigneeUserId),n(R,A)},"onChange"),renderTriggerValue:r(R=>R?_?(0,m.createElement)(b4,null,(0,m.createElement)(zP,{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 A=vy(R.id),T=A.assigneeAgentId?k.find(E=>E.id===A.assigneeAgentId):null;return(0,m.createElement)(b4,null,T?(0,m.createElement)(zP,{icon:T.icon,className:"h-3.5 w-3.5 shrink-0 text-muted-foreground"}):(0,m.createElement)(cd,{className:"h-3.5 w-3.5 shrink-0 text-muted-foreground"}),(0,m.createElement)("span",{className:"truncate"},R.label))},"renderOption")})}r(Ims,"PluginSdkAssigneePicker");function Ams({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=$W(),p=e??h.companyId??null,{data:f}=te({queryKey:D.auth.session,queryFn:r(()=>Ma.getSession(),"queryFn")}),x=f?.user?.id??f?.session?.userId??null,{data:b}=te({queryKey:D.projects.list(p??"__no-company__",{includeArchived:c}),queryFn:r(()=>ra.list(p,{includeArchived:c}),"queryFn"),enabled:!!p}),v=(0,m.useMemo)(()=>(b??[]).filter(S=>c||!S.archivedAt),[c,b]),{orderedProjects:j}=Cj({projects:v,companyId:p,userId:x}),N=(0,m.useMemo)(()=>By(),[]),w=(0,m.useMemo)(()=>j.map(S=>({id:S.id,label:S.name,searchText:S.description??""})),[j]),k=j.find(S=>S.id===s)??null;return(0,m.createElement)(Yu,{value:s,options:w,recentOptionIds:N,placeholder:a,noneLabel:i,searchPlaceholder:o,emptyMessage:l,className:d,onConfirm:u,onChange:r(S=>{S&&gb(S),n(S)},"onChange"),renderTriggerValue:r(S=>!S||!k?(0,m.createElement)("span",{className:"text-muted-foreground"},a):(0,m.createElement)(b4,null,(0,m.createElement)("span",{className:"h-3.5 w-3.5 shrink-0 rounded-sm",style:{backgroundColor:k.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=j.find(_=>_.id===S.id);return(0,m.createElement)(b4,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(Ams,"PluginSdkProjectPicker");function b4({children:e}){return(0,m.createElement)("span",{className:"contents"},e)}r(b4,"FragmentSafe");function Tms({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(Tms,"PluginSdkStatusBadge");function Rms({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(Rms,"PluginSdkDataTable");function Ems({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(Ems,"PluginSdkKeyValueList");function Pms({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(Pms,"PluginSdkMetricCard");function Mms({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(Mms,"PluginSdkJsonTree");function Dms({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(Dms,"PluginSdkSpinner");var Lms=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 $ms(e,s){globalThis.__paperclipPluginBridge__={react:e,reactJsxRuntime:t,reactDom:s,sdkUi:{usePluginData:ZWe,usePluginAction:eVe,useHostContext:$W,useHostLocation:sVe,useHostNavigation:tVe,usePluginStream:rVe,usePluginToast:nVe,copyTextToClipboard:Ia,MarkdownBlock:r(({content:n,className:a,enableWikiLinks:i,wikiLinkRoot:o,resolveWikiLinkHref:l})=>(0,m.createElement)(In,{className:a,softBreaks:!1,enableWikiLinks:i,wikiLinkRoot:o,resolveWikiLinkHref:l,children:n}),"MarkdownBlock"),MetricCard:Pms,StatusBadge:Tms,DataTable:Rms,KeyValueList:Ems,JsonTree:Mms,Spinner:Dms,ErrorBoundary:Lms,MarkdownEditor:Sms,FileTree:kms,IssuesList:_ms,AssigneePicker:Ims,ProjectPicker:Ams,ManagedRoutinesList:Nms}}}r($ms,"initPluginBridge");var Oms=1e4;function Fms(e=Oms){if(typeof performance>"u"||typeof performance.clearMeasures!="function")return()=>{};const n=setInterval(r(()=>{globalThis.__paperclipKeepPerfMeasures||performance.clearMeasures()},"reap"),e);return()=>clearInterval(n)}r(Fms,"startPerfMeasureReaper");var Bms=fj((e=>{function s(B,q){var z=B.length;B.push(q);e:for(;0<z;){var K=z-1>>>1,W=B[K];if(0<i(W,q))B[K]=q,B[z]=W,z=K;else break e}}r(s,"push");function n(B){return B.length===0?null:B[0]}r(n,"peek");function a(B){if(B.length===0)return null;var q=B[0],z=B.pop();if(z!==q){B[0]=z;e:for(var K=0,W=B.length,Q=W>>>1;K<Q;){var re=2*(K+1)-1,J=B[re],ie=re+1,X=B[ie];if(0>i(J,z))ie<W&&0>i(X,J)?(B[K]=X,B[ie]=z,K=ie):(B[K]=J,B[re]=z,K=re);else if(ie<W&&0>i(X,z))B[K]=X,B[ie]=z,K=ie;else break e}}return q}r(a,"pop");function i(B,q){var z=B.sortIndex-q.sortIndex;return z!==0?z:B.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,b=!1,v=!1,j=!1,N=typeof setTimeout=="function"?setTimeout:null,w=typeof clearTimeout=="function"?clearTimeout:null,k=typeof setImmediate<"u"?setImmediate:null;function S(B){for(var q=n(u);q!==null;){if(q.callback===null)a(u);else if(q.startTime<=B)a(u),q.sortIndex=q.expirationTime,s(d,q);else break;q=n(u)}}r(S,"advanceTimers");function C(B){if(v=!1,S(B),!b)if(n(d)!==null)b=!0,_||(_=!0,O());else{var q=n(u);q!==null&&M(C,q.startTime-B)}}r(C,"handleTimeout");var _=!1,R=-1,A=5,T=-1;function E(){return j?!0:!(e.unstable_now()-T<A)}r(E,"shouldYieldToHost");function L(){if(j=!1,_){var B=e.unstable_now();T=B;var q=!0;try{e:{b=!1,v&&(v=!1,w(R),R=-1),x=!0;var z=f;try{t:{for(S(B),p=n(d);p!==null&&!(p.expirationTime>B&&E());){var K=p.callback;if(typeof K=="function"){p.callback=null,f=p.priorityLevel;var W=K(p.expirationTime<=B);if(B=e.unstable_now(),typeof W=="function"){p.callback=W,S(B),q=!0;break t}p===n(d)&&a(d),S(B)}else a(d);p=n(d)}if(p!==null)q=!0;else{var Q=n(u);Q!==null&&M(C,Q.startTime-B),q=!1}}break e}finally{p=null,f=z,x=!1}q=void 0}}finally{q?O():_=!1}}}r(L,"performWorkUntilDeadline");var O;if(typeof k=="function")O=r(function(){k(L)},"schedulePerformWorkUntilDeadline");else if(typeof MessageChannel<"u"){var P=new MessageChannel,U=P.port2;P.port1.onmessage=L,O=r(function(){U.postMessage(null)},"schedulePerformWorkUntilDeadline")}else O=r(function(){N(L,0)},"schedulePerformWorkUntilDeadline");function M(B,q){R=N(function(){B(e.unstable_now())},q)}r(M,"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(B){B.callback=null},e.unstable_forceFrameRate=function(B){0>B||125<B||(A=0<B?Math.floor(1e3/B):5)},e.unstable_getCurrentPriorityLevel=function(){return f},e.unstable_next=function(B){switch(f){case 1:case 2:case 3:var q=3;break;default:q=f}var z=f;f=q;try{return B()}finally{f=z}},e.unstable_requestPaint=function(){j=!0},e.unstable_runWithPriority=function(B,q){switch(B){case 1:case 2:case 3:case 4:case 5:break;default:B=3}var z=f;f=B;try{return q()}finally{f=z}},e.unstable_scheduleCallback=function(B,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,B){case 1:var W=-1;break;case 2:W=250;break;case 5:W=1073741823;break;case 4:W=1e4;break;default:W=5e3}return W=z+W,B={id:h++,callback:q,priorityLevel:B,startTime:z,expirationTime:W,sortIndex:-1},z>K?(B.sortIndex=z,s(u,B),n(d)===null&&B===n(u)&&(v?(w(R),R=-1):v=!0,M(C,z-K))):(B.sortIndex=W,s(d,B),b||x||(b=!0,_||(_=!0,O()))),B},e.unstable_shouldYield=E,e.unstable_wrapCallback=function(B){var q=f;return function(){var z=f;f=q;try{return B.apply(this,arguments)}finally{f=z}}}})),zms=fj(((e,s)=>{s.exports=Bms()})),qms=fj((e=>{var s=zms(),n=T9(),a=dge();function i(g){var y="https://react.dev/errors/"+g;if(1<arguments.length){y+="?args[]="+encodeURIComponent(arguments[1]);for(var I=2;I<arguments.length;I++)y+="&args[]="+encodeURIComponent(arguments[I])}return"Minified React error #"+g+"; visit "+y+" for the full message or use the non-minified dev environment for full errors and additional helpful warnings."}r(i,"formatProdErrorMessage");function o(g){return!(!g||g.nodeType!==1&&g.nodeType!==9&&g.nodeType!==11)}r(o,"isValidContainer");function l(g){var y=g,I=g;if(g.alternate)for(;y.return;)y=y.return;else{g=y;do y=g,(y.flags&4098)!==0&&(I=y.return),g=y.return;while(g)}return y.tag===3?I:null}r(l,"getNearestMountedFiber");function c(g){if(g.tag===13){var y=g.memoizedState;if(y===null&&(g=g.alternate,g!==null&&(y=g.memoizedState)),y!==null)return y.dehydrated}return null}r(c,"getSuspenseInstanceFromFiber");function d(g){if(g.tag===31){var y=g.memoizedState;if(y===null&&(g=g.alternate,g!==null&&(y=g.memoizedState)),y!==null)return y.dehydrated}return null}r(d,"getActivityInstanceFromFiber");function u(g){if(l(g)!==g)throw Error(i(188))}r(u,"assertIsMounted");function h(g){var y=g.alternate;if(!y){if(y=l(g),y===null)throw Error(i(188));return y!==g?null:g}for(var I=g,F=y;;){var H=I.return;if(H===null)break;var ee=H.alternate;if(ee===null){if(F=H.return,F!==null){I=F;continue}break}if(H.child===ee.child){for(ee=H.child;ee;){if(ee===I)return u(H),g;if(ee===F)return u(H),y;ee=ee.sibling}throw Error(i(188))}if(I.return!==F.return)I=H,F=ee;else{for(var je=!1,Ve=H.child;Ve;){if(Ve===I){je=!0,I=H,F=ee;break}if(Ve===F){je=!0,F=H,I=ee;break}Ve=Ve.sibling}if(!je){for(Ve=ee.child;Ve;){if(Ve===I){je=!0,I=ee,F=H;break}if(Ve===F){je=!0,F=ee,I=H;break}Ve=Ve.sibling}if(!je)throw Error(i(189))}}if(I.alternate!==F)throw Error(i(190))}if(I.tag!==3)throw Error(i(188));return I.stateNode.current===I?g:y}r(h,"findCurrentFiberUsingSlowPath");function p(g){var y=g.tag;if(y===5||y===26||y===27||y===6)return g;for(g=g.child;g!==null;){if(y=p(g),y!==null)return y;g=g.sibling}return null}r(p,"findCurrentHostFiberImpl");var f=Object.assign,x=Symbol.for("react.element"),b=Symbol.for("react.transitional.element"),v=Symbol.for("react.portal"),j=Symbol.for("react.fragment"),N=Symbol.for("react.strict_mode"),w=Symbol.for("react.profiler"),k=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"),A=Symbol.for("react.memo"),T=Symbol.for("react.lazy"),E=Symbol.for("react.activity"),L=Symbol.for("react.memo_cache_sentinel"),O=Symbol.iterator;function P(g){return g===null||typeof g!="object"?null:(g=O&&g[O]||g["@@iterator"],typeof g=="function"?g:null)}r(P,"getIteratorFn");var U=Symbol.for("react.client.reference");function M(g){if(g==null)return null;if(typeof g=="function")return g.$$typeof===U?null:g.displayName||g.name||null;if(typeof g=="string")return g;switch(g){case j:return"Fragment";case w:return"Profiler";case N:return"StrictMode";case _:return"Suspense";case R:return"SuspenseList";case E:return"Activity"}if(typeof g=="object")switch(g.$$typeof){case v:return"Portal";case S:return g.displayName||"Context";case k:return(g._context.displayName||"Context")+".Consumer";case C:var y=g.render;return g=g.displayName,g||(g=y.displayName||y.name||"",g=g!==""?"ForwardRef("+g+")":"ForwardRef"),g;case A:return y=g.displayName||null,y!==null?y:M(g.type)||"Memo";case T:y=g._payload,g=g._init;try{return M(g(y))}catch{}}return null}r(M,"getComponentNameFromType");var B=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},W=[],Q=-1;function re(g){return{current:g}}r(re,"createCursor");function J(g){0>Q||(g.current=W[Q],W[Q]=null,Q--)}r(J,"pop");function ie(g,y){Q++,W[Q]=g.current,g.current=y}r(ie,"push");var X=re(null),ne=re(null),oe=re(null),G=re(null);function Z(g,y){switch(ie(oe,y),ie(ne,g),ie(X,null),y.nodeType){case 9:case 11:g=(g=y.documentElement)&&(g=g.namespaceURI)?HX(g):0;break;default:if(g=y.tagName,y=y.namespaceURI)y=HX(y),g=QX(y,g);else switch(g){case"svg":g=1;break;case"math":g=2;break;default:g=0}}J(X),ie(X,g)}r(Z,"pushHostContainer");function Y(){J(X),J(ne),J(oe)}r(Y,"popHostContainer");function ae(g){g.memoizedState!==null&&ie(G,g);var y=X.current,I=QX(y,g.type);y!==I&&(ie(ne,g),ie(X,I))}r(ae,"pushHostContext");function se(g){ne.current===g&&(J(X),J(ne)),G.current===g&&(J(G),_C._currentValue=K)}r(se,"popHostContext");var ce,pe;function we(g){if(ce===void 0)try{throw Error()}catch(I){var y=I.stack.trim().match(/\n( *(at )?)/);ce=y&&y[1]||"",pe=-1<I.stack.indexOf(`
668
+ `)}q!==N&&(n.textContent=q,N=q)}r(R,"step");function A(){const P=d>0&&u>0;if(a.matches){o&&(o=!1,s.current!==null&&cancelAnimationFrame(s.current),s.current=null),P&&S();return}if(!i||!P){o&&(o=!1,s.current!==null&&cancelAnimationFrame(s.current),s.current=null);return}o||(o=!0,l=0,s.current=requestAnimationFrame(R))}r(A,"syncLoop");const T=new ResizeObserver(()=>{const P=Wxe(n);h=P.w,p=P.h,k(),A()});T.observe(n);const E=r(()=>{i=document.visibilityState!=="hidden",A()},"onVisibilityChange");document.addEventListener("visibilitychange",E);const L=r(()=>{A()},"onMotionChange");a.addEventListener("change",L);const O=Wxe(n);return h=O.w,p=O.h,k(),A(),()=>{o=!1,s.current!==null&&cancelAnimationFrame(s.current),T.disconnect(),document.removeEventListener("visibilitychange",E),a.removeEventListener("change",L)}},[]),(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(Dus,"AsciiArtAnimation");function Lus({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(Lus,"PaperclipLockup");function $us(){const e=Nt(),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",b=(0,m.useMemo)(()=>nIe(n.get("next")||Eus()||"/"),[n]),v=te({queryKey:D.health,queryFn:r(()=>yu.get(),"queryFn"),retry:!1}),{data:j,isLoading:N,error:w}=te({queryKey:D.auth.session,queryFn:r(()=>Ma.getSession(),"queryFn"),retry:!1});(0,m.useEffect)(()=>{j&&(pQ(),s(b,{replace:!0}))},[j,s,b]);const k=ye({mutationFn:r(async()=>{if(a==="sign_in"){await Ma.signInEmail({email:c.trim(),password:u});return}await Ma.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(b,{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||N||j?(0,t.jsx)("div",{className:"fixed inset-0 flex items-center justify-center",children:(0,t.jsx)(Jm,{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)(fQ,{cloud:v.data.cloud,returnTo:b}):(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)(ZN,{})}),(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)(Lus,{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(),!k.isPending){if(!S){f("Please fill in all required fields.");return}k.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:k.isPending,"aria-disabled":!S||k.isPending,className:`w-full ${!S&&!k.isPending?"opacity-50":""}`,children:k.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)(Dus,{})})]})}r($us,"AuthPage");function Ous(){const e=Nt(),s=fa(),[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(()=>Ma.getSession(),"queryFn"),retry:!1}),c=te({queryKey:["board-claim",a,i],queryFn:r(()=>lr.getBoardClaimStatus(a,i),"queryFn"),enabled:a.length>0&&i.length>0,retry:!1}),d=ye({mutationFn:r(()=>lr.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(Ous,"BoardClaimPage");function Vxe({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)(lm,{className:"size-4 shrink-0","aria-hidden":"true"}),(0,t.jsx)("bdi",{className:"min-w-0 break-all",children:e})]})}r(Vxe,"ClientOrigin");function Hxe({agentPairingOnly:e=!1}={}){const{id:s=""}=fa();return(0,t.jsx)(R$e,{id:s,agentPairingOnly:e},s)}r(Hxe,"McpConnectPage");function Fus({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)(R$e,{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)(wl,{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)(ut,{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(Fus,"McpDevicePage");function R$e({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,b]=(0,m.useState)(!0),[v,j]=(0,m.useState)(null),N=te({queryKey:[s?"mcp-device":n?"dot-mcp-request":"mcp-request",e],queryFn:r(()=>Ce.get(s?`/mcp/device?user_code=${encodeURIComponent(e)}`:`${i}/${encodeURIComponent(e)}`),"queryFn"),retry:!1}),w=N.data;(0,m.useEffect)(()=>{if(h(null),f(""),!w?.agentConnection||s||!/^[A-Za-z0-9_-]{32}$/.test(c.trim()))return;let U=!0;return Ce.post(`${i}/${encodeURIComponent(e)}/dot-pairing/preview`,{pairingCode:c.trim()}).then(M=>{U&&h(M)}).catch(M=>{U&&f(M instanceof Error?M.message:"Unable to verify this pairing code.")}),()=>{U=!1}},[e,s,i,w?.agentConnection,c]);const k=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(U=>U.id===k),A=!!(!w?.agentConnection&&R?.canWrite&&x),T=!!(w?.requestedWrite&&A),E=!!(w?.requestedConfigure&&A),L=ye({mutationFn:r(U=>Ce.post(s?"/mcp/device/consent":`/mcp/requests/${encodeURIComponent(e)}/consent`,{decision:U,companyId:k||void 0,allowWrites:U==="approve"&&T,allowConfiguration:U==="approve"&&E,...s?{userCode:e}:{}}),"mutationFn"),onSuccess:r(({redirectUrl:U,status:M})=>{s&&M?j(M):U&&window.location.assign(U)},"onSuccess")}),O=ye({mutationFn:r(()=>Ce.post(`${i}/${encodeURIComponent(e)}/dot-pairing`,{pairingCode:c.trim()}),"mutationFn"),onSuccess:r(({redirectUrl:U})=>{d(""),window.location.assign(U)},"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)(wl,{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 P=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)(wl,{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)(Vxe,{origin:_},_),!s&&w?.redirectOrigin&&w.redirectOrigin!==_&&(0,t.jsx)(Vxe,{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()})]}),N.isPending&&(0,t.jsx)("p",{className:"text-sm text-muted-foreground",children:"Loading connection request…"}),N.error&&(0,t.jsxs)("p",{className:"text-sm text-destructive",children:[N.error.message," Start a new connection from your assistant."]}),s&&N.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(U=>{U.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)(ut,{id:"dot-pairing-code",type:"password",autoComplete:"off",value:c,onChange:r(U=>{h(null),f(""),d(U.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(P)}`,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)(Ag,{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:L.isPending,children:[(0,t.jsx)("legend",{className:"mb-2 text-sm font-medium",children:"Organization"}),w.companies.map(U=>(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":U.name,value:U.id,checked:k===U.id,onChange:r(()=>l(U.id),"onChange")}),(0,t.jsx)(Ag,{companyName:U.name,logoUrl:U.logoUrl,className:"size-12 shrink-0 rounded-lg"}),(0,t.jsx)("span",{className:"min-w-0 break-words font-medium",children:U.name})]},U.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)(Za,{id:"mcp-allow-writes",checked:A,disabled:!R?.canWrite||L.isPending,onCheckedChange:r(U=>b(U===!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."}),L.error&&(0,t.jsx)("p",{className:"text-sm text-destructive",children:L.error.message}),(0,t.jsxs)("div",{className:"flex items-center justify-between gap-3",children:[(0,t.jsx)($,{variant:"outline",disabled:L.isPending,onClick:r(()=>L.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||L.isPending,onClick:r(()=>L.mutate("approve"),"onClick"),children:L.isPending?"Connecting…":w.agentConnection?"Connect Dot agent":"Connect organization"})]})]})})]})})}r(R$e,"McpConnectRequest");function Bus(){const e=Nt(),s=te({queryKey:["mcp-connections"],queryFn:r(()=>Ce.get("/mcp/connections"),"queryFn"),retry:!1}),n=s.data?.filter(i=>!i.revokedAt),a=ye({mutationFn:r(i=>Ce.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:r4(i),avatarUrl:i.user?.image,initials:Ob(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(Bus,"AssistantConnectionsPage");function zus(){const e=Nt(),s=fa(),[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(()=>Ma.getSession(),"queryFn"),retry:!1}),c=te({queryKey:["cli-auth-challenge",a,i],queryFn:r(()=>lr.getCliAuthChallenge(a,i),"queryFn"),enabled:a.length>0&&i.length>0,retry:!1}),d=ye({mutationFn:r(()=>lr.approveCliAuthChallenge(a,i),"mutationFn"),onSuccess:r(async()=>{await e.invalidateQueries({queryKey:D.auth.session}),await c.refetch()},"onSuccess")}),u=ye({mutationFn:r(()=>lr.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(zus,"CliAuthPage");var qus=gBe.filter(e=>e!=="paperclip_runner"),Qxe=new Set(["claude_local","codex_local","gemini_local","kimi_local","opencode_local","pi_local","cursor"]);function Uus(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(Uus,"readNestedString");var tN="w-full border border-zinc-800 bg-zinc-950 px-3 py-2 text-sm text-zinc-100 outline-none focus:border-zinc-500",Gxe="border border-zinc-800 bg-zinc-950/95 p-6",Yxe="flex-1 border px-3 py-2 text-sm transition-colors";function Kus(e){return e?e.charAt(0).toUpperCase()+e.slice(1):null}r(Kus,"formatHumanRole");function E$e(e){if(!e||typeof e!="object")return null;const s=e.code;return typeof s=="string"&&s.trim().length>0?s:null}r(E$e,"getAuthErrorCode");function Wus(e){if(!(e instanceof Error))return null;const s=e.message.trim();return s.length>0?s:null}r(Wus,"getAuthErrorMessage");function Vus(e,s,n){const a=E$e(e),i=Wus(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(Vus,"mapInviteAuthFeedback");function Jxe(e){return!!(e&&typeof e=="object"&&"bootstrapAccepted"in e)}r(Jxe,"isBootstrapAcceptancePayload");function Hus(e,s){return!e||typeof e!="object"||s?!1:e.status==="approved"}r(Hus,"isApprovedHumanJoinPayload");function w9({companyDisplayName:e,companyLogoUrl:s,className:n}){return(0,t.jsx)(Ag,{companyName:e,logoUrl:s,logoFit:"contain",className:n})}r(w9,"InviteCompanyLogo");function Xxe({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)(w9,{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(Xxe,"AwaitingJoinApprovalPanel");function Qus(){const e=Nt(),s=Gn(),{setSelectedCompanyId:n}=ps(),a=(fa().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)(""),[b,v]=(0,m.useState)("claude_local"),[j,N]=(0,m.useState)(""),[w,k]=(0,m.useState)(null),[S,C]=(0,m.useState)(null),[_,R]=(0,m.useState)(null),[A,T]=(0,m.useState)(!1),E="invite-auth-error",L=te({queryKey:D.health,queryFn:r(()=>yu.get(),"queryFn"),retry:!1}),O=te({queryKey:D.auth.session,queryFn:r(()=>Ma.getSession(),"queryFn"),retry:!1}),P=te({queryKey:D.access.invite(a),queryFn:r(()=>lr.getInvite(a),"queryFn"),enabled:a.length>0,retry:!1}),U=L9({enabled:!!O.data&&!!P.data?.companyId,staleTime:0}),M=L.data?.deploymentMode!=="local_trusted"?U.isFetchedAfterMount:!0,B=M?U.data?.companies??[]:[];(0,m.useEffect)(()=>{a&&Uxe(a)},[a]),(0,m.useEffect)(()=>{T(!1)},[a]),(0,m.useEffect)(()=>{if(!M)return;const Se=U.data?.companies;!Se||!P.data?.companyId||Se.some(Te=>Te.id===P.data.companyId)&&qE(a)},[U.data,P.data,M,a]);const q=P.data,z=!!O.data&&!!q?.companyId&&!M,K=!!q?.companyId&&B.some(Se=>Se.id===q?.companyId),W=q?.companyName?.trim()||"this Paperclip company",Q=q?.companyLogoUrl?.trim()||null,re=q?.invitedByUserName?.trim()||null,J=q?.inviteMessage?.trim()||null,ie=Kus(q?.humanRole),X=q?.joinRequestStatus??null,ne=q?.joinRequestType??null,oe=ne==="human"&&(X==="pending_approval"||X==="approved"),G=L.data?.deploymentMode==="authenticated"&&!O.data&&q?.allowedJoinTypes!=="agent",Z=q?.inviteType!=="bootstrap_ceo"&&q?.allowedJoinTypes==="agent",Y=!!O.data&&!Z&&q?.inviteType!=="bootstrap_ceo"&&(!X||oe)&&!z&&!K&&!w&&S===null,ae=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=ye({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"?lr.acceptInvite(a,{requestType:"human"}):lr.acceptInvite(a,{requestType:"agent",agentName:f.trim(),adapterType:b,capabilities:j.trim()||null})},"mutationFn"),onSuccess:r(async Se=>{C(null),qE(a);const Te=Jxe(Se);k({kind:Te?"bootstrap":"join",payload:Se}),await e.invalidateQueries({queryKey:D.auth.session}),await e.invalidateQueries({queryKey:D.access.currentBoardAccess}),await e.invalidateQueries({queryKey:D.companies.all}),q?.companyId&&Hus(Se,Z)&&(n(q.companyId,{source:"manual"}),s("/",{replace:!0}))},"onSuccess"),onError:r(Se=>{C(Se instanceof Error?Se.message:"Failed to accept invite")},"onError")});(0,m.useEffect)(()=>{!Y||A||ce.isPending||(T(!0),C(null),ce.mutate())},[ce,A,Y]);const pe=ye({mutationFn:r(async()=>{if(i==="sign_in"){await Ma.signInEmail({email:d.trim(),password:h});return}await Ma.signUpEmail({name:l.trim(),email:d.trim(),password:h})},"mutationFn"),onSuccess:r(async()=>{R(null),Uxe(a),await e.invalidateQueries({queryKey:D.auth.session}),await e.invalidateQueries({queryKey:D.health}),await e.invalidateQueries({queryKey:D.access.currentBoardAccess});const{companies:Se}=await KBe(e);if(q?.companyId&&Se.some(Te=>Te.id===q.companyId)){qE(a),n(q.companyId,{source:"manual"}),s("/",{replace:!0});return}if(!(!q||q.inviteType!=="bootstrap_ceo"))try{Jxe(await ce.mutateAsync())&&s("/",{replace:!0})}catch{return}},"onSuccess"),onError:r(Se=>{const Te=Vus(Se,i,d);E$e(Se)==="USER_ALREADY_EXISTS_USE_ANOTHER_EMAIL"&&(o("sign_in"),p("")),R(Te)},"onError")}),we=(0,m.useMemo)(()=>q?K?"Open organization":q.inviteType==="bootstrap_ceo"?"Accept invite":Z?"Submit request":O.data?"Accept invite":"Continue":"Continue",[q,K,O.data,Z]);if(!a)return(0,t.jsx)("div",{className:"mx-auto max-w-xl py-10 text-sm text-destructive",children:"Invalid invite token."});if(P.isLoading||L.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(P.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(X==="approved"&&ne==="human"&&K)return(0,t.jsx)("div",{className:"mx-auto max-w-xl py-10 text-sm text-muted-foreground",children:"Opening organization..."});if(X==="pending_approval"&&!oe)return(0,t.jsx)(Xxe,{companyDisplayName:W,companyLogoUrl:Q,invitedByUserName:re});if(X&&!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:X==="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 Se=w.payload,Te=typeof Se.claimSecret=="string"?Se.claimSecret:null,le=typeof Se.claimApiKeyPath=="string"?Se.claimApiKeyPath:null,fe=Uus(Se.onboarding,["textInstructions","url"]);return!Z&&Se.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)(w9,{companyDisplayName:W,companyLogoUrl:Q,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)(Xxe,{companyDisplayName:W,companyLogoUrl:Q,invitedByUserName:re,claimSecret:Te,claimApiKeyPath:le,onboardingTextUrl:fe})}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:`${Gxe} space-y-6`,children:[(0,t.jsxs)("div",{className:"flex items-start gap-4",children:[(0,t.jsx)(w9,{companyDisplayName:W,companyLogoUrl:Q,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 ${W}`}),(0,t.jsx)("p",{className:"mt-2 max-w-2xl text-sm leading-6 text-zinc-300",children:Z?"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:W})]}),(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:re??"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:Z?"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:qd(q.expiresAt)})]})]}),J?(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:J})]}):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:ae}),"."]}):null]}),(0,t.jsx)("section",{className:`${Gxe} h-fit`,children:Z?(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 ",W,"."]})]}),(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:tN,value:f,onChange:r(Se=>x(Se.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:tN,value:b,onChange:r(Se=>v(Se.target.value),"onChange"),children:qus.map(Se=>(0,t.jsxs)("option",{value:Se,disabled:!Qxe.has(Se),children:[ax(Se),Qxe.has(Se)?"":" (Coming soon)"]},Se))})]}),(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:tN,rows:4,value:j,onChange:r(Se=>N(Se.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...":we})]}):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 ${W}.`:"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:`${Yxe} ${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:`${Yxe} ${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(Se=>{if(Se.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:tN,value:l,onChange:r(Se=>{c(Se.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:tN,value:d,onChange:r(Se=>{u(Se.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:tN,value:h,onChange:r(Se=>{p(Se.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 ${W}.`:K?`This account already belongs to ${W}.`:`This will ${q.inviteType==="bootstrap_ceo"?"finish setting up Paperclip":`grant or complete your access to ${W}`}.`})]}),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){qE(a),n(q.companyId,{source:"manual"}),s("/",{replace:!0});return}ce.mutate()},"onClick"),children:ce.isPending?"Working...":we})]})})]})})})}r(Qus,"InviteLandingPage");var Gus=15e3,Yus={parent:"Parent task",child:"Sub-task",blocked_by:"Blocked by",blocks:"Blocks"};function Jus(){(0,m.useEffect)(()=>{const e=document.createElement("meta");return e.name="robots",e.content="noindex",document.head.appendChild(e),()=>e.remove()},[])}r(Jus,"useNoIndexMeta");function N9(e,s){const n=`/s/${encodeURIComponent(e)}`;return s?`${n}/issues/${encodeURIComponent(s)}`:n}r(N9,"sharePath");var Xus=/^(?:https?:\/\/[^/]+)?\/api\/attachments\/([^/?#]+)\/content(?:[?#].*)?$/i;function Zus(e,s){const n=Xus.exec(s.trim());return n?`/api/public/share/${encodeURIComponent(e)}/attachments/${n[1]}/content`:null}r(Zus,"publicShareImageSrc");function j1({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(j1,"Section");function k9({actor:e}){return(0,t.jsx)(yo,{name:e.name,avatarUrl:e.iconUrl,size:"sm"})}r(k9,"ActorIdentity");function S9({value:e}){return(0,t.jsx)("time",{dateTime:e,title:br(e),className:"text-xs text-muted-foreground",children:gr(e)})}r(S9,"Timestamp");function ems({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(ems,"ActiveRunPill");function P$e({attachments:e}){return(0,t.jsx)(hV,{children:e.map(s=>{const n=Rke({name:s.filename,url:s.url,contentType:s.contentType,byteSize:s.byteSize}),a=n.icon,i=pV(s.byteSize);return(0,t.jsxs)(lV,{size:"sm",children:[(0,t.jsx)(cV,{children:(0,t.jsx)(a,{"aria-hidden":!0})}),(0,t.jsxs)(dV,{children:[(0,t.jsx)(uV,{className:"max-w-48",children:s.filename}),(0,t.jsx)(mV,{className:"max-w-48",children:i?`${n.label} · ${i}`:n.label})]}),(0,t.jsx)(_ke,{"aria-label":`Download ${s.filename}`,render:(0,t.jsx)("a",{href:s.url,download:s.filename,rel:"noreferrer"})})]},s.id)})})}r(P$e,"AttachmentList");function tms({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)(no,{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:Yus[e.relation]}),e.navigable?(0,t.jsx)(Nd,{to:n?N9(s,e.id):N9(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(tms,"RelatedIssueRow");function sms({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)(k9,{actor:e.author}),(0,t.jsx)(S9,{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)(k9,{actor:e.author}),(0,t.jsx)(S9,{value:e.createdAt})]}),(0,t.jsx)(In,{className:"text-sm",softBreaks:!0,linkIssueReferences:!1,resolveImageSrc:s,children:e.body}),e.attachments.length>0?(0,t.jsx)(P$e,{attachments:e.attachments}):null]})}r(sms,"TimelineEntry");function nms({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)(Ya,{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)(S9,{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)(ho,{className:"h-3.5 w-3.5","aria-hidden":!0}),"Download PDF"]}),(0,t.jsx)(In,{className:"text-sm",linkIssueReferences:!1,resolveImageSrc:s,children:e.body})]})]})}r(nms,"DocumentCard");function rms({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)(ho,{className:"h-3.5 w-3.5","aria-hidden":!0}),"Download"]}):null]})}r(rms,"WorkProductRow");function Zxe({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(Zxe,"CenteredNotice");function ams({view:e,token:s}){const{company:n,issue:a}=e,i=(0,m.useCallback)(o=>Zus(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)(Ag,{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)(Nd,{to:N9(s),className:"inline-flex items-center gap-1.5 text-sm text-muted-foreground hover:text-foreground",children:[(0,t.jsx)(jl,{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)(fp,{status:a.status}),(0,t.jsx)(P0e,{priority:a.priority,showLabel:!0}),a.assignee?(0,t.jsx)(k9,{actor:a.assignee}):null,e.activeRun?(0,t.jsx)(ems,{agentName:e.activeRun.agentName}):null]}),(0,t.jsxs)("p",{className:"text-xs text-muted-foreground",children:["Created ",br(a.createdAt)," · Updated ",gr(a.updatedAt),a.completedAt?` · Completed ${br(a.completedAt)}`:""]})]}),a.description?(0,t.jsx)(In,{className:"text-sm",softBreaks:!0,linkIssueReferences:!1,resolveImageSrc:i,children:a.description}):null,e.related.length>0?(0,t.jsx)(j1,{title:"Related tasks",children:(0,t.jsx)("ul",{className:"space-y-2",children:e.related.map(o=>(0,t.jsx)(tms,{related:o,token:s,isSharedRoot:e.isSharedRoot},`${o.relation}:${o.id}`))})}):null,e.documents.length>0?(0,t.jsx)(j1,{title:"Documents",children:(0,t.jsx)("div",{className:"space-y-2",children:e.documents.map(o=>(0,t.jsx)(nms,{document:o,resolveImageSrc:i},o.key))})}):null,e.attachments.length>0?(0,t.jsx)(j1,{title:"Attachments",children:(0,t.jsx)(P$e,{attachments:e.attachments})}):null,e.workProducts.length>0?(0,t.jsx)(j1,{title:"Work products",children:(0,t.jsx)("ul",{className:"space-y-2",children:e.workProducts.map(o=>(0,t.jsx)(rms,{product:o},o.id))})}):null,(0,t.jsx)(j1,{title:"Activity",children:e.comments.length>0?(0,t.jsx)("ol",{className:"space-y-3",children:e.comments.map(o=>(0,t.jsx)(sms,{comment:o,resolveImageSrc:i},o.id))}):(0,t.jsx)("p",{className:"text-sm text-muted-foreground",children:"No updates yet."})})]})]})}r(ams,"PublicIssueShareContent");function ege(){const{token:e="",issueId:s}=fa();Jus();const n=WUe.test(e),a=te({queryKey:D.publicShare.view(e,s??null),queryFn:r(()=>s?xk.getPublicShareIssue(e,s):xk.getPublicShare(e),"queryFn"),enabled:n,retry:!1,refetchOnWindowFocus:!0,refetchInterval:r(i=>i.state.data?.activeRun?Gus:!1,"refetchInterval")});return!n||a.data===null?(0,t.jsx)(Zxe,{title:"This link is not available",body:"It may have been revoked, or the address is incomplete."}):a.data?(0,t.jsx)(ams,{view:a.data,token:e}):a.isError?(0,t.jsx)(Zxe,{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(ege,"PublicIssueSharePage");function ims(){const{selectedCompany:e,selectedCompanyId:s}=ps(),{setBreadcrumbs:n}=Hn(),{pushToast:a}=Ti(),i=Nt(),[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(()=>lr.listJoinRequests(s,o,c==="all"?void 0:c),"queryFn"),enabled:!!s}),h=ye({mutationFn:r(f=>lr.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=ye({mutationFn:r(f=>lr.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 mn&&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)(j8e,{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(ims,"JoinRequestQueue");var oms=(0,m.lazy)(()=>Id(()=>import("./CompanyExport-CsJNakda.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]))),lms=(0,m.lazy)(()=>Id(()=>import("./Agents.production-CVULb5cR.js").then(e=>({default:e.Agents})),__vite__mapDeps([22,5,7,9,8,23,24,25,26,27,28,29,30,19,20,21]))),cms=(0,m.lazy)(()=>Id(()=>import("./Routines.production-CDaXZ2Kc.js").then(e=>({default:e.Routines})),__vite__mapDeps([31,5,7,8,9,32,10,24,25,33,16,12,34,23,26,35,36,37,11,13,28,38,14,39,29,40,41,18,30,42,43,44,19,20,21,27]))),tge=(0,m.lazy)(()=>Id(()=>import("./RoutineDetail.production-C03tDWie.js").then(e=>({default:e.RoutineDetail})),__vite__mapDeps([45,5,7,8,9,32,10,24,25,33,16,12,34,23,26,35,36,37,11,13,28,38,14,39,29,40,41,18,30,42,43,44,19,20,21,46,47]))),dms=(0,m.lazy)(()=>Id(()=>import("./CompanySkills.production-CXPBOlb3.js").then(e=>({default:e.CompanySkills})),__vite__mapDeps([48,5,7,8,9,10,23,24,25,26,33,16,12,35,36,37,27,11,13,49,47,14,42,21,17,15,50,39,19,20]))),ums=(0,m.lazy)(()=>Id(()=>import("./CompanyActivity.production-Wked11oO.js").then(e=>({default:e.CompanyActivity})),__vite__mapDeps([51,5,7,8,9,26,27,25,14,38,36,16,42,43,44,19]))),mms=(0,m.lazy)(()=>Id(()=>import("./OrgChart.production-BjDW9Rac.js").then(e=>({default:e.OrgChart})),__vite__mapDeps([52,5,7,8,9,26,40,41,44,19,20,21])));function Ov({children:e}){return(0,t.jsx)(m.Suspense,{fallback:(0,t.jsx)(Jm,{}),children:e})}r(Ov,"ProductionSurface");function hms(e,s){const n=e&&s;return(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)(nt,{index:!0,element:(0,t.jsx)(An,{to:"dashboard",replace:!0})}),(0,t.jsx)(nt,{path:"dashboard",element:(0,t.jsx)(TIt,{})}),(0,t.jsx)(nt,{path:"dashboard/live",element:(0,t.jsx)(RIt,{})}),(0,t.jsx)(nt,{path:"timeline",element:e?(0,t.jsx)(cf,{to:"/activity/timeline"}):(0,t.jsx)(AEe,{})}),(0,t.jsx)(nt,{path:"onboarding",element:(0,t.jsx)(L$e,{})}),(0,t.jsx)(nt,{path:"companies",element:(0,t.jsx)(gAt,{})}),(0,t.jsx)(nt,{path:"company/settings",element:(0,t.jsx)(EQt,{})}),(0,t.jsx)(nt,{path:"company/settings/connections",element:(0,t.jsx)(DQt,{})}),(0,t.jsx)(nt,{path:"company/settings/environments",element:(0,t.jsx)(An,{to:"/company/settings/instance/environments",replace:!0})}),(0,t.jsx)(nt,{path:"company/settings/cloud-upstream",element:(0,t.jsx)(An,{to:"/company/export",replace:!0})}),(0,t.jsxs)(nt,{element:(0,t.jsx)(op,{pageKey:"company.members"}),children:[(0,t.jsx)(nt,{path:"company/settings/members",element:(0,t.jsx)(nZt,{})}),(0,t.jsx)(nt,{path:"company/settings/access",element:(0,t.jsx)(rZt,{})})]}),(0,t.jsx)(nt,{element:(0,t.jsx)(op,{pageKey:"company.invites"}),children:(0,t.jsx)(nt,{path:"company/settings/invites",element:(0,t.jsx)(An,{to:"/company/settings/members?tab=invites",replace:!0})})}),(0,t.jsx)(nt,{element:(0,t.jsx)(op,{pageKey:"company.export"}),children:(0,t.jsx)(nt,{path:"company/export/*",element:(0,t.jsx)(m.Suspense,{fallback:(0,t.jsx)(Jm,{}),children:(0,t.jsx)(oms,{})})})}),(0,t.jsx)(nt,{element:(0,t.jsx)(Ift,{}),children:(0,t.jsx)(nt,{element:(0,t.jsx)(op,{pageKey:"company.import"}),children:(0,t.jsx)(nt,{path:"company/import",element:(0,t.jsx)(nds,{})})})}),(0,t.jsx)(nt,{element:(0,t.jsx)(op,{pageKey:"company.secrets"}),children:(0,t.jsx)(nt,{path:"company/settings/secrets",element:(0,t.jsx)(Xls,{})})}),(0,t.jsx)(nt,{path:"company/settings/tools",element:(0,t.jsx)(rge,{})}),(0,t.jsx)(nt,{path:"company/settings/tools/:tab",element:(0,t.jsx)(rge,{})}),(0,t.jsx)(nt,{path:"tools",element:(0,t.jsx)(age,{})}),(0,t.jsx)(nt,{path:"tools/:tab",element:(0,t.jsx)(age,{})}),(0,t.jsx)(nt,{path:"apps",element:(0,t.jsx)(Zes,{})}),(0,t.jsx)(nt,{path:"apps/assistant-connection",element:(0,t.jsx)(Des,{})}),(0,t.jsx)(nt,{path:"apps/browse",element:(0,t.jsx)(An,{to:"/apps",replace:!0})}),(0,t.jsx)(nt,{path:"apps/connections",element:(0,t.jsx)(An,{to:"/apps",replace:!0})}),(0,t.jsx)(nt,{path:"apps/byo",element:(0,t.jsx)(nLe,{byoOnly:!0})}),(0,t.jsx)(nt,{path:"apps/vercel-connect",element:(0,t.jsx)(sge,{credentialSource:"vercel_connect"})}),(0,t.jsx)(nt,{path:"apps/connect",element:(0,t.jsx)(sge,{})}),(0,t.jsx)(nt,{path:"apps/chat/connect",element:(0,t.jsx)(CE,{children:(0,t.jsx)(ass,{})})}),(0,t.jsx)(nt,{path:"apps/chat/:endpointId",element:(0,t.jsx)(CE,{children:(0,t.jsx)(An,{to:"settings",replace:!0})})}),(0,t.jsx)(nt,{path:"apps/chat/:endpointId/reviews/:reviewId",element:(0,t.jsx)(CE,{children:(0,t.jsx)(Xpe,{})})}),(0,t.jsx)(nt,{path:"apps/chat/:endpointId/:tab",element:(0,t.jsx)(CE,{children:(0,t.jsx)(Xpe,{})})}),(0,t.jsx)(nt,{path:"apps/connect/:appKey",element:(0,t.jsx)(An,{to:"/apps",replace:!0})}),(0,t.jsx)(nt,{path:"apps/connect/:appKey/:stage",element:(0,t.jsx)(An,{to:"/apps",replace:!0})}),(0,t.jsx)(nt,{path:"apps/review",element:(0,t.jsx)(Kns,{})}),(0,t.jsx)(nt,{path:"apps/attention",element:(0,t.jsx)(An,{to:"/apps",replace:!0})}),(0,t.jsx)(nt,{path:"apps/gateways",element:(0,t.jsx)(nfe,{})}),(0,t.jsx)(nt,{path:"apps/gateways/:gatewayId",element:(0,t.jsx)(An,{to:"overview",replace:!0})}),(0,t.jsx)(nt,{path:"apps/gateways/:gatewayId/:tab",element:(0,t.jsx)(yrs,{})}),(0,t.jsx)(nt,{path:"apps/advanced",element:(0,t.jsx)(Npe,{})}),(0,t.jsx)(nt,{path:"apps/advanced/gateways",element:(0,t.jsx)(nfe,{})}),(0,t.jsx)(nt,{path:"apps/advanced/profiles/new",element:(0,t.jsx)(Ipe,{mode:"new"})}),(0,t.jsx)(nt,{path:"apps/advanced/profiles/:profileId/edit",element:(0,t.jsx)(Ipe,{mode:"edit"})}),(0,t.jsx)(nt,{path:"apps/advanced/profiles/:profileId",element:(0,t.jsx)(Nes,{})}),(0,t.jsx)(nt,{path:"apps/advanced/audit",element:(0,t.jsx)(An,{to:"/apps",replace:!0})}),(0,t.jsx)(nt,{path:"apps/advanced/run-your-own",element:(0,t.jsx)(An,{to:"/apps",replace:!0})}),(0,t.jsx)(nt,{path:"apps/advanced/:tab",element:(0,t.jsx)(Npe,{})}),(0,t.jsx)(nt,{path:"apps/app/:applicationId",element:(0,t.jsx)(efe,{})}),(0,t.jsx)(nt,{path:"apps/app/:applicationId/:tab",element:(0,t.jsx)(efe,{})}),(0,t.jsx)(nt,{path:"apps/:connectionId",element:(0,t.jsx)(An,{to:"permissions",replace:!0})}),(0,t.jsx)(nt,{path:"apps/:connectionId/:tab",element:(0,t.jsx)(Cts,{})}),(0,t.jsx)(nt,{path:"company/settings/instance",element:(0,t.jsx)(An,{to:"/company/settings",replace:!0})}),(0,t.jsx)(nt,{element:(0,t.jsx)(op,{pageKey:"instance.profile"}),children:(0,t.jsx)(nt,{path:"company/settings/instance/profile",element:(0,t.jsx)(dus,{})})}),(0,t.jsx)(nt,{path:"company/settings/instance/general",element:(0,t.jsx)(An,{to:"/company/settings",replace:!0})}),(0,t.jsx)(nt,{path:"company/settings/instance/heartbeats",element:(0,t.jsx)(An,{to:"/company/settings",replace:!0})}),(0,t.jsxs)(nt,{element:(0,t.jsx)(op,{pageKey:"instance.environments"}),children:[(0,t.jsx)(nt,{path:"company/settings/instance/environments",element:(0,t.jsx)(sq,{})}),(0,t.jsx)(nt,{path:"company/settings/instance/environments/new",element:(0,t.jsx)(sq,{mode:"create"})}),(0,t.jsx)(nt,{path:"company/settings/instance/environments/:environmentId/edit",element:(0,t.jsx)(sq,{mode:"edit"})})]}),(0,t.jsx)(nt,{element:(0,t.jsx)(op,{pageKey:"instance.access"}),children:(0,t.jsx)(nt,{path:"company/settings/instance/access",element:(0,t.jsx)(sus,{})})}),(0,t.jsx)(nt,{element:(0,t.jsx)(op,{pageKey:"instance.experimental"}),children:(0,t.jsx)(nt,{path:"company/settings/instance/experimental",element:(0,t.jsx)(tus,{})})}),(0,t.jsxs)(nt,{element:(0,t.jsx)(op,{pageKey:"instance.plugins"}),children:[(0,t.jsx)(nt,{path:"company/settings/instance/plugins",element:(0,t.jsx)(mus,{})}),(0,t.jsx)(nt,{path:"company/settings/instance/plugins/:pluginId",element:(0,t.jsx)(hus,{})})]}),(0,t.jsx)(nt,{element:(0,t.jsx)(op,{pageKey:"instance.adapters"}),children:(0,t.jsx)(nt,{path:"company/settings/instance/adapters",element:(0,t.jsx)(Fxe,{})})}),(0,t.jsx)(nt,{path:"company/settings/:settingsRoutePath/*",element:(0,t.jsx)(YXt,{})}),(0,t.jsx)(nt,{path:"skills/sources",element:(0,t.jsx)(Afe,{})}),(0,t.jsx)(nt,{path:"skills/sources/:sourceId",element:(0,t.jsx)(Afe,{})}),(0,t.jsx)(nt,{path:"skills/studio",element:(0,t.jsx)(Cq,{})}),(0,t.jsx)(nt,{path:"skills/studio/new",element:(0,t.jsx)(Cq,{})}),(0,t.jsx)(nt,{path:"skills/studio/:skillId",element:(0,t.jsx)(Cq,{})}),(0,t.jsx)(nt,{path:"skills/:skillId/studio",element:(0,t.jsx)(M$e,{})}),(0,t.jsx)(nt,{path:"skills/*",element:e?(0,t.jsx)(Das,{}):(0,t.jsx)(Ov,{children:(0,t.jsx)(dms,{})})}),(0,t.jsx)(nt,{path:"settings",element:(0,t.jsx)(ay,{})}),(0,t.jsx)(nt,{path:"settings/*",element:(0,t.jsx)(ay,{})}),(0,t.jsx)(nt,{path:"plugins/:pluginId",element:(0,t.jsx)(Bxe,{})}),(0,t.jsx)(nt,{path:"org",element:e?(0,t.jsx)(An,{to:"/agents/all",replace:!0}):(0,t.jsx)(Ov,{children:(0,t.jsx)(mms,{})})}),(0,t.jsx)(nt,{path:"agents",element:(0,t.jsx)(An,{to:"/agents/all",replace:!0})}),rG.map(a=>(0,t.jsx)(nt,{path:`agents/${a}`,element:e?(0,t.jsx)(a2t,{}):(0,t.jsx)(Ov,{children:(0,t.jsx)(lms,{})})},a)),(0,t.jsx)(nt,{path:"agents/new",element:(0,t.jsx)(Rus,{})}),(0,t.jsx)(nt,{path:"agents/:agentId",element:(0,t.jsx)(AB,{})}),(0,t.jsx)(nt,{path:"agents/:agentId/:tab",element:(0,t.jsx)(AB,{})}),(0,t.jsx)(nt,{path:"agents/:agentId/runs/:runId",element:(0,t.jsx)(AB,{})}),(0,t.jsx)(nt,{path:"projects",element:(0,t.jsx)(CEt,{})}),(0,t.jsx)(nt,{path:"projects/:projectId",element:(0,t.jsx)(Sv,{})}),(0,t.jsx)(nt,{path:"projects/:projectId/overview",element:(0,t.jsx)(Sv,{})}),(0,t.jsx)(nt,{path:"projects/:projectId/issues",element:(0,t.jsx)(Sv,{})}),(0,t.jsx)(nt,{path:"projects/:projectId/issues/:filter",element:(0,t.jsx)(Sv,{})}),(0,t.jsx)(nt,{element:(0,t.jsx)(EF,{}),children:(0,t.jsx)(nt,{path:"projects/:projectId/workspaces/:workspaceId",element:(0,t.jsx)(NPt,{})})}),(0,t.jsx)(nt,{path:"projects/:projectId/workspaces",element:(0,t.jsx)(Sv,{})}),(0,t.jsx)(nt,{path:"projects/:projectId/configuration",element:(0,t.jsx)(Sv,{})}),(0,t.jsx)(nt,{path:"projects/:projectId/budget",element:(0,t.jsx)(Sv,{})}),(0,t.jsx)(nt,{element:(0,t.jsx)(EF,{}),children:(0,t.jsx)(nt,{path:"workspaces",element:(0,t.jsx)(CPt,{})})}),(0,t.jsx)(nt,{path:"issues",element:(0,t.jsx)(YMt,{})}),(0,t.jsx)(nt,{path:"tasks",element:(0,t.jsx)(An,{to:"/issues",replace:!0})}),(0,t.jsx)(nt,{path:"search",element:(0,t.jsx)(x4t,{})}),n?(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)(nt,{path:"issues/all",element:(0,t.jsx)(jh,{view:"all"})}),(0,t.jsx)(nt,{path:"issues/active",element:(0,t.jsx)(jh,{view:"active"})}),(0,t.jsx)(nt,{path:"issues/backlog",element:(0,t.jsx)(jh,{view:"backlog"})}),(0,t.jsx)(nt,{path:"issues/done",element:(0,t.jsx)(jh,{view:"done"})}),(0,t.jsx)(nt,{path:"issues/recent",element:(0,t.jsx)(jh,{view:"recent"})})]}):(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)(nt,{path:"issues/all",element:(0,t.jsx)(An,{to:"/issues",replace:!0})}),(0,t.jsx)(nt,{path:"issues/active",element:(0,t.jsx)(An,{to:"/issues",replace:!0})}),(0,t.jsx)(nt,{path:"issues/backlog",element:(0,t.jsx)(An,{to:"/issues",replace:!0})}),(0,t.jsx)(nt,{path:"issues/done",element:(0,t.jsx)(An,{to:"/issues",replace:!0})}),(0,t.jsx)(nt,{path:"issues/recent",element:(0,t.jsx)(An,{to:"/issues",replace:!0})})]}),(0,t.jsx)(nt,{path:"chats",element:(0,t.jsx)(jFt,{})}),(0,t.jsx)(nt,{path:"chats/:agentRef",element:(0,t.jsx)(NFt,{})}),(0,t.jsx)(nt,{path:"issues/:issueId",element:(0,t.jsx)(xFt,{})}),null,(0,t.jsx)(nt,{path:"routines",element:e?(0,t.jsx)(sBt,{}):(0,t.jsx)(Ov,{children:(0,t.jsx)(cms,{})})}),(0,t.jsx)(nt,{path:"cases",element:(0,t.jsx)(lae,{children:(0,t.jsx)(Qft,{})})}),(0,t.jsx)(nt,{path:"cases/:caseIdentifier",element:(0,t.jsx)(lae,{children:(0,t.jsx)(P0t,{})})}),(0,t.jsx)(nt,{path:"pixels-office",element:(0,t.jsx)(_ft,{children:(0,t.jsx)(P7t,{})})}),(0,t.jsx)(nt,{path:"status",element:(0,t.jsx)(cae,{children:(0,t.jsx)(bue,{})})}),(0,t.jsx)(nt,{path:"status/:cardId",element:(0,t.jsx)(cae,{children:(0,t.jsx)(bue,{})})}),(0,t.jsx)(nt,{path:"status-cards",element:(0,t.jsx)(ige,{})}),(0,t.jsx)(nt,{path:"status-cards/:cardId",element:(0,t.jsx)(ige,{})}),(0,t.jsx)(nt,{path:"review-queue",element:(0,t.jsx)(k0,{children:(0,t.jsx)(yqt,{})})}),(0,t.jsx)(nt,{path:"learnings",element:(0,t.jsx)(k0,{children:(0,t.jsx)(wqt,{})})}),(0,t.jsx)(nt,{path:"pipelines",element:(0,t.jsx)(k0,{children:(0,t.jsx)(xz,{})})}),(0,t.jsx)(nt,{path:"pipelines/:pipelineId",element:(0,t.jsx)(k0,{children:(0,t.jsx)(xz,{})})}),(0,t.jsx)(nt,{path:"pipelines/:pipelineId/add",element:(0,t.jsx)(k0,{children:(0,t.jsx)(xz,{})})}),(0,t.jsx)(nt,{path:"pipelines/:pipelineId/settings",element:(0,t.jsx)(k0,{children:(0,t.jsx)(f6t,{})})}),(0,t.jsx)(nt,{path:"pipelines/:pipelineId/items/:caseId",element:(0,t.jsx)(k0,{children:(0,t.jsx)(Bzt,{})})}),(0,t.jsx)(nt,{path:"pipelines/:pipelineId/cases/:caseId",element:(0,t.jsx)(k0,{children:(0,t.jsx)($zt,{})})}),(0,t.jsx)(nt,{path:"routines/:routineId",element:e?(0,t.jsx)(yme,{}):(0,t.jsx)(Ov,{children:(0,t.jsx)(tge,{})})}),(0,t.jsx)(nt,{path:"routines/:routineId/:section",element:e?(0,t.jsx)(yme,{}):(0,t.jsx)(Ov,{children:(0,t.jsx)(tge,{})})}),(0,t.jsx)(nt,{element:(0,t.jsx)(EF,{}),children:(0,t.jsxs)(nt,{element:(0,t.jsx)(Tft,{}),children:[(0,t.jsx)(nt,{path:"execution-workspaces/:workspaceId",element:(0,t.jsx)(Qw,{})}),(0,t.jsx)(nt,{path:"execution-workspaces/:workspaceId/services",element:(0,t.jsx)(Qw,{})}),(0,t.jsx)(nt,{path:"execution-workspaces/:workspaceId/configuration",element:(0,t.jsx)(Qw,{})}),(0,t.jsx)(nt,{path:"execution-workspaces/:workspaceId/runtime-logs",element:(0,t.jsx)(Qw,{})}),(0,t.jsx)(nt,{path:"execution-workspaces/:workspaceId/issues",element:(0,t.jsx)(Qw,{})}),(0,t.jsx)(nt,{path:"execution-workspaces/:workspaceId/routines",element:(0,t.jsx)(Qw,{})})]})}),(0,t.jsx)(nt,{path:"goals",element:(0,t.jsx)(RWt,{})}),(0,t.jsx)(nt,{path:"goals/:goalId",element:(0,t.jsx)(qWt,{})}),(0,t.jsx)(nt,{path:"artifacts",element:(0,t.jsx)(kme,{})}),(0,t.jsx)(nt,{path:"approvals",element:(0,t.jsx)(An,{to:"/approvals/pending",replace:!0})}),(0,t.jsx)(nt,{path:"approvals/pending",element:(0,t.jsx)(Cme,{})}),(0,t.jsx)(nt,{path:"approvals/all",element:(0,t.jsx)(Cme,{})}),(0,t.jsx)(nt,{path:"approvals/:approvalId",element:(0,t.jsx)(UWt,{})}),(0,t.jsx)(nt,{path:"activity",element:e?(0,t.jsx)(FVt,{}):(0,t.jsx)(Ov,{children:(0,t.jsx)(ums,{})})}),e?(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)(nt,{path:"activity/runs",element:(0,t.jsx)(U1,{section:"runs"})}),(0,t.jsx)(nt,{path:"activity/costs",element:(0,t.jsx)(U1,{section:"costs"})}),(0,t.jsx)(nt,{path:"activity/budgets",element:(0,t.jsx)(U1,{section:"budgets"})}),(0,t.jsx)(nt,{path:"activity/timeline",element:(0,t.jsx)(U1,{section:"timeline"})}),(0,t.jsx)(nt,{path:"audit",element:(0,t.jsx)(cf,{to:"/activity",forceAgentMode:!0})}),(0,t.jsx)(nt,{path:"audit/activity",element:(0,t.jsx)(cf,{to:"/activity"})}),(0,t.jsx)(nt,{path:"audit/runs",element:(0,t.jsx)(cf,{to:"/activity/runs"})}),(0,t.jsx)(nt,{path:"audit/costs",element:(0,t.jsx)(cf,{to:"/activity/costs"})}),(0,t.jsx)(nt,{path:"audit/budgets",element:(0,t.jsx)(cf,{to:"/activity/budgets"})}),(0,t.jsx)(nt,{path:"audit/timeline",element:(0,t.jsx)(cf,{to:"/activity/timeline"})}),(0,t.jsx)(nt,{path:"runs",element:(0,t.jsx)(cf,{to:"/activity/runs"})}),(0,t.jsx)(nt,{path:"costs",element:(0,t.jsx)(cf,{to:"/activity/costs"})}),(0,t.jsx)(nt,{path:"budgets",element:(0,t.jsx)(cf,{to:"/activity/budgets"})})]}):(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)(nt,{path:"costs",element:(0,t.jsx)(r7,{})}),(0,t.jsx)(nt,{path:"audit",element:(0,t.jsx)(An,{to:"/activity?mode=agents",replace:!0})})]}),(0,t.jsxs)(nt,{element:(0,t.jsx)(Lmt,{}),children:[(0,t.jsx)(nt,{path:"board-chat",element:(0,t.jsx)(aQt,{})}),(0,t.jsx)(nt,{path:"artifacts",element:(0,t.jsx)(kme,{})})]}),null,(0,t.jsx)(nt,{path:"decisions",element:(0,t.jsx)(THt,{})}),(0,t.jsx)(nt,{path:"decisions/queues/:key",element:(0,t.jsx)(MHt,{})}),n?(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)(nt,{path:"inbox",element:(0,t.jsx)(nge,{})}),(0,t.jsx)(nt,{path:"inbox/mine",element:(0,t.jsx)(jh,{view:"mine"})}),(0,t.jsx)(nt,{path:"inbox/recent",element:(0,t.jsx)(jh,{view:"recent"})}),(0,t.jsx)(nt,{path:"inbox/unread",element:(0,t.jsx)(jh,{view:"unread"})}),(0,t.jsx)(nt,{path:"inbox/blocked",element:(0,t.jsx)(jh,{view:"blocked"})}),(0,t.jsx)(nt,{path:"inbox/all",element:(0,t.jsx)(jh,{view:"everything"})}),(0,t.jsx)(nt,{path:"inbox/new",element:(0,t.jsx)(jh,{view:"mine"})})]}):(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)(nt,{path:"inbox",element:(0,t.jsx)(nge,{})}),(0,t.jsx)(nt,{path:"inbox/mine",element:(0,t.jsx)(uN,{})}),(0,t.jsx)(nt,{path:"inbox/recent",element:(0,t.jsx)(uN,{})}),(0,t.jsx)(nt,{path:"inbox/unread",element:(0,t.jsx)(uN,{})}),(0,t.jsx)(nt,{path:"inbox/blocked",element:(0,t.jsx)(uN,{})}),(0,t.jsx)(nt,{path:"inbox/all",element:(0,t.jsx)(uN,{})}),(0,t.jsx)(nt,{path:"inbox/new",element:(0,t.jsx)(An,{to:"/inbox/mine",replace:!0})})]}),(0,t.jsx)(nt,{path:"inbox/requests",element:(0,t.jsx)(ims,{})}),(0,t.jsx)(nt,{path:"u/:userSlug",element:(0,t.jsx)(aWt,{})}),(0,t.jsx)(nt,{path:"design-guide",element:(0,t.jsx)(Jds,{})}),(0,t.jsx)(nt,{path:"instance/settings/adapters",element:(0,t.jsx)(Fxe,{})}),(0,t.jsx)(nt,{path:":pluginRoutePath/*",element:(0,t.jsx)(Bxe,{})}),(0,t.jsx)(nt,{path:"*",element:(0,t.jsx)(Zu,{scope:"board"})})]})}r(hms,"boardRoutes");function sge({credentialSource:e="paperclip_vault"}={}){const s=oa(),n=new URLSearchParams(s.search),{enabled:a,githubEnabled:i}=Rj();return Bct(n,{chatConnectorsEnabled:a,githubReviewBotsEnabled:i})?(0,t.jsx)(nLe,{credentialSource:e}):(0,t.jsx)(An,{to:"/apps",replace:!0})}r(sge,"AppsConnectEntryRoute");function nge(){const{enabled:e}=Ac(),{enabled:s}=QA();return e&&s?(0,t.jsx)(jh,{view:Cze(GZ())}):(0,t.jsx)(An,{to:`/inbox/${GZ()}`,replace:!0})}r(nge,"InboxRootRedirect");function jh({view:e}){const s=oa(),n=new URLSearchParams(s.search);return n.set(VE,e),(0,t.jsx)(An,{to:`/issues?${n.toString()}${s.hash}`,replace:!0})}r(jh,"TaskViewRedirect");function M$e(){const e=oa(),{companies:s,selectedCompany:n,loading:a}=ps(),{companyPrefix:i,skillId:o}=fa();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)(An,{to:"/skills/studio",replace:!0}):(0,t.jsx)(An,{to:`/${l.issuePrefix}/skills/studio/${encodeURIComponent(o)}${e.search}${e.hash}`,replace:!0})}r(M$e,"LegacySkillStudioRedirect");function ay(){const e=oa(),{companies:s,selectedCompany:n,loading:a}=ps(),{companyPrefix:i}=fa(),{hidden:o}=vu();if(a)return(0,t.jsx)(Jm,{});const l=(i?s.find(d=>d.issuePrefix.toUpperCase()===i.toUpperCase()):null)??n??s[0]??null;if(!l)return PH({pathname:e.pathname,hasCompanies:!1})?(0,t.jsx)(An,{to:"/onboarding",replace:!0}):(0,t.jsx)(KY,{});const c=KWe(aNe(`${e.pathname}${e.search}${e.hash}`),o);return(0,t.jsx)(An,{to:`/${l.issuePrefix}${c}`,replace:!0})}r(ay,"LegacySettingsRedirect");function rge(){const{tab:e}=fa();return(0,t.jsx)(An,{to:D$e(e),replace:!0})}r(rge,"LegacyToolsSettingsRedirect");function age(){const{tab:e}=fa();return(0,t.jsx)(An,{to:D$e(e),replace:!0})}r(age,"LegacyToolsRedirect");function D$e(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(D$e,"legacyToolsRedirectTarget");function L$e(){const{companies:e}=ps(),{openOnboarding:s}=rl(),{t:n}=Rwe(),a=Yc(),i=sIe(a?.cloudBaseUrl??null),{onboardingOpen:o,onboardingRouteDismissed:l}=P4(),{companyPrefix:c}=fa(),d=c?e.find(p=>p.issuePrefix.toUpperCase()===c.toUpperCase())??null:null;if(Qdt({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:BP(),companyId:d.id}):a&&i?Ym(i):s(),"onClick"),children:d?"Add Agent":"Start Onboarding"})})]})})}r(L$e,"OnboardingRoutePage");function pms(){const{companies:e,selectedCompany:s,loading:n}=ps(),a=oa();if(n)return(0,t.jsx)(Jm,{});const i=s??e[0]??null;return i?(0,t.jsx)(An,{to:`/${i.issuePrefix}/dashboard`,replace:!0}):PH({pathname:a.pathname,hasCompanies:!1})?(0,t.jsx)(An,{to:"/onboarding",replace:!0}):(0,t.jsx)(KY,{})}r(pms,"CompanyRootRedirect");function ige(){const{cardId:e}=fa(),s=Pze(),n=s?`/${s}`:"";return(0,t.jsx)(An,{to:`${n}/status${e?`/${e}`:""}`,replace:!0})}r(ige,"StatusCardsLegacyRedirect");function cf({to:e,forceAgentMode:s=!1}){const n=oa(),a=new URLSearchParams(n.search);s&&a.set("mode","agents");const i=a.toString();return(0,t.jsx)(An,{to:`${e}${i?`?${i}`:""}${n.hash}`,replace:!0})}r(cf,"AuditCompatibilityRedirect");function ya(){const e=oa(),{companies:s,selectedCompany:n,loading:a}=ps();if(a)return(0,t.jsx)(Jm,{});const i=n??s[0]??null;return i?(0,t.jsx)(An,{to:`/${i.issuePrefix}${e.pathname}${e.search}${e.hash}`,replace:!0}):PH({pathname:e.pathname,hasCompanies:!1})?(0,t.jsx)(An,{to:"/onboarding",replace:!0}):(0,t.jsx)(KY,{})}r(ya,"UnprefixedBoardRedirect");function KY(){const{openOnboarding:e}=rl(),{t:s}=Rwe(),n=Yc(),a=sIe(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?Ym(a):e(),"onClick"),children:s("app.noCompanies.newCompany",{defaultValue:"New Organization"})})})]})})}r(KY,"NoCompaniesStartPage");function fms(){const{enabled:e,loaded:s}=Ac(),{enabled:n}=QA();return(0,t.jsxs)(t.Fragment,{children:[(0,t.jsxs)(sze,{children:[(0,t.jsx)(nt,{path:"oauth-handoff",element:(0,t.jsx)(Xns,{})}),(0,t.jsx)(nt,{path:"auth",element:(0,t.jsx)($us,{})}),(0,t.jsx)(nt,{path:"board-claim/:token",element:(0,t.jsx)(Ous,{})}),(0,t.jsx)(nt,{path:"mcp-connect/:id",element:(0,t.jsx)(Hxe,{})}),(0,t.jsx)(nt,{path:"dot-connect/:id",element:(0,t.jsx)(Hxe,{agentPairingOnly:!0})}),(0,t.jsx)(nt,{path:"mcp-device",element:(0,t.jsx)(Fus,{})}),(0,t.jsx)(nt,{path:"assistant-connections",element:(0,t.jsx)(Bus,{})}),(0,t.jsx)(nt,{path:"cli-auth/:id",element:(0,t.jsx)(zus,{})}),(0,t.jsx)(nt,{path:"invite/:token",element:(0,t.jsx)(Qus,{})}),(0,t.jsx)(nt,{path:"s/:token",element:(0,t.jsx)(ege,{})}),(0,t.jsx)(nt,{path:"s/:token/issues/:issueId",element:(0,t.jsx)(ege,{})}),(0,t.jsx)(nt,{element:s?(0,t.jsx)(rie,{allowMembershipRequest:!0}):(0,t.jsx)(Jm,{}),children:(0,t.jsx)(nt,{path:"chat-identity/confirm",element:(0,t.jsx)(qns,{})})}),(0,t.jsx)(nt,{path:"tests/perf/long-thread",element:(0,t.jsx)(MFt,{})}),(0,t.jsx)(nt,{path:"ux-lab/bootstrap-setup",element:(0,t.jsx)(VXt,{})}),(0,t.jsx)(nt,{path:"ux-lab/responsible-user-denial",element:(0,t.jsx)(HXt,{})}),(0,t.jsx)(nt,{path:"ux-lab/cross-issue-collaboration",element:(0,t.jsx)(GXt,{})}),(0,t.jsxs)(nt,{element:s?(0,t.jsx)(rie,{}):(0,t.jsx)(Jm,{}),children:[(0,t.jsx)(nt,{index:!0,element:(0,t.jsx)(pms,{})}),(0,t.jsx)(nt,{path:"onboarding",element:(0,t.jsx)(L$e,{})}),(0,t.jsx)(nt,{path:"instance",element:(0,t.jsx)(ay,{})}),(0,t.jsx)(nt,{path:"instance/settings",element:(0,t.jsx)(ay,{})}),(0,t.jsx)(nt,{path:"instance/settings/*",element:(0,t.jsx)(ay,{})}),(0,t.jsx)(nt,{path:"companies",element:(0,t.jsx)(ya,{})}),(0,t.jsx)(nt,{path:"dashboard",element:(0,t.jsx)(ya,{})}),(0,t.jsx)(nt,{path:"inbox/*",element:(0,t.jsx)(ya,{})}),(0,t.jsx)(nt,{path:"issues",element:(0,t.jsx)(ya,{})}),(0,t.jsx)(nt,{path:"tasks",element:(0,t.jsx)(ya,{})}),(0,t.jsx)(nt,{path:"issues/:issueId",element:(0,t.jsx)(ya,{})}),(0,t.jsx)(nt,{path:"routines",element:(0,t.jsx)(ya,{})}),(0,t.jsx)(nt,{path:"routines/:routineId",element:(0,t.jsx)(ya,{})}),(0,t.jsx)(nt,{path:"review-queue",element:(0,t.jsx)(ya,{})}),(0,t.jsx)(nt,{path:"learnings",element:(0,t.jsx)(ya,{})}),(0,t.jsx)(nt,{path:"cases",element:(0,t.jsx)(ya,{})}),(0,t.jsx)(nt,{path:"cases/:caseIdentifier",element:(0,t.jsx)(ya,{})}),(0,t.jsx)(nt,{path:"pixels-office",element:(0,t.jsx)(ya,{})}),(0,t.jsx)(nt,{path:"status",element:(0,t.jsx)(ya,{})}),(0,t.jsx)(nt,{path:"status/:cardId",element:(0,t.jsx)(ya,{})}),(0,t.jsx)(nt,{path:"status-cards",element:(0,t.jsx)(ya,{})}),(0,t.jsx)(nt,{path:"status-cards/:cardId",element:(0,t.jsx)(ya,{})}),(0,t.jsx)(nt,{path:"pipelines",element:(0,t.jsx)(ya,{})}),(0,t.jsx)(nt,{path:"pipelines/:pipelineId",element:(0,t.jsx)(ya,{})}),(0,t.jsx)(nt,{path:"pipelines/:pipelineId/add",element:(0,t.jsx)(ya,{})}),(0,t.jsx)(nt,{path:"pipelines/:pipelineId/settings",element:(0,t.jsx)(ya,{})}),(0,t.jsx)(nt,{path:"pipelines/:pipelineId/items/:caseId",element:(0,t.jsx)(ya,{})}),(0,t.jsx)(nt,{path:"pipelines/:pipelineId/cases/:caseId",element:(0,t.jsx)(ya,{})}),(0,t.jsx)(nt,{path:"artifacts",element:(0,t.jsx)(ya,{})}),(0,t.jsx)(nt,{path:"audit",element:(0,t.jsx)(ya,{})}),e?(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)(nt,{path:"audit/*",element:(0,t.jsx)(ya,{})}),(0,t.jsx)(nt,{path:"activity",element:(0,t.jsx)(ya,{})}),(0,t.jsx)(nt,{path:"activity/*",element:(0,t.jsx)(ya,{})}),(0,t.jsx)(nt,{path:"runs",element:(0,t.jsx)(ya,{})}),(0,t.jsx)(nt,{path:"costs",element:(0,t.jsx)(ya,{})}),(0,t.jsx)(nt,{path:"budgets",element:(0,t.jsx)(ya,{})})]}):null,(0,t.jsx)(nt,{path:"decisions",element:(0,t.jsx)(ya,{})}),(0,t.jsx)(nt,{path:"u/:userSlug",element:(0,t.jsx)(ya,{})}),(0,t.jsx)(nt,{path:"skills/studio",element:(0,t.jsx)(ya,{})}),(0,t.jsx)(nt,{path:"skills/studio/new",element:(0,t.jsx)(ya,{})}),(0,t.jsx)(nt,{path:"skills/studio/:skillId",element:(0,t.jsx)(ya,{})}),(0,t.jsx)(nt,{path:"skills/:skillId/studio",element:(0,t.jsx)(M$e,{})}),(0,t.jsx)(nt,{path:"skills/*",element:(0,t.jsx)(ya,{})}),(0,t.jsx)(nt,{path:"settings",element:(0,t.jsx)(ay,{})}),(0,t.jsx)(nt,{path:"settings/*",element:(0,t.jsx)(ay,{})}),(0,t.jsx)(nt,{path:"agents",element:(0,t.jsx)(ya,{})}),rG.map(a=>(0,t.jsx)(nt,{path:`agents/${a}`,element:(0,t.jsx)(ya,{})},a)),(0,t.jsx)(nt,{path:"agents/new",element:(0,t.jsx)(ya,{})}),(0,t.jsx)(nt,{path:"agents/:agentId",element:(0,t.jsx)(ya,{})}),(0,t.jsx)(nt,{path:"agents/:agentId/:tab",element:(0,t.jsx)(ya,{})}),(0,t.jsx)(nt,{path:"agents/:agentId/runs/:runId",element:(0,t.jsx)(ya,{})}),(0,t.jsx)(nt,{path:"projects",element:(0,t.jsx)(ya,{})}),(0,t.jsx)(nt,{path:"projects/:projectId",element:(0,t.jsx)(ya,{})}),(0,t.jsx)(nt,{path:"projects/:projectId/overview",element:(0,t.jsx)(ya,{})}),(0,t.jsx)(nt,{path:"projects/:projectId/issues",element:(0,t.jsx)(ya,{})}),(0,t.jsx)(nt,{path:"projects/:projectId/issues/:filter",element:(0,t.jsx)(ya,{})}),(0,t.jsx)(nt,{path:"projects/:projectId/workspaces",element:(0,t.jsx)(ya,{})}),(0,t.jsx)(nt,{path:"projects/:projectId/workspaces/:workspaceId",element:(0,t.jsx)(ya,{})}),(0,t.jsx)(nt,{path:"projects/:projectId/configuration",element:(0,t.jsx)(ya,{})}),(0,t.jsx)(nt,{path:"workspaces",element:(0,t.jsx)(ya,{})}),(0,t.jsx)(nt,{path:"execution-workspaces/:workspaceId",element:(0,t.jsx)(Aw,{})}),(0,t.jsx)(nt,{path:"execution-workspaces/:workspaceId/services",element:(0,t.jsx)(Aw,{})}),(0,t.jsx)(nt,{path:"execution-workspaces/:workspaceId/configuration",element:(0,t.jsx)(Aw,{})}),(0,t.jsx)(nt,{path:"execution-workspaces/:workspaceId/runtime-logs",element:(0,t.jsx)(Aw,{})}),(0,t.jsx)(nt,{path:"execution-workspaces/:workspaceId/issues",element:(0,t.jsx)(Aw,{})}),(0,t.jsx)(nt,{path:"execution-workspaces/:workspaceId/routines",element:(0,t.jsx)(Aw,{})}),(0,t.jsx)(nt,{path:":companyPrefix",element:e?(0,t.jsx)(emt,{}):(0,t.jsx)(Pmt,{}),children:hms(e,n)}),(0,t.jsx)(nt,{path:"*",element:(0,t.jsx)(Zu,{scope:"global"})})]})]}),(0,t.jsx)(jbt,{}),(0,t.jsx)(Mut,{})]})}r(fms,"App");var xms=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){DH(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 gms(){const{data:e}=te({queryKey:D.auth.session,queryFn:r(()=>Ma.getSession(),"queryFn"),retry:!1}),s=e?.sentryDsn,n=e?.sentryEnvironment??void 0;return(0,m.useEffect)(()=>{if(s)return mut(s,n),()=>{hut()}},[s,n]),null}r(gms,"SentryGate");function bms(e){let s=$g();Ele(s),c8(s,e.userId);const n=W3e(()=>{const o=$g();o!==s&&(s=o,Ele(o),c8(o,e.userId))}),a=typeof navigator<"u"&&"serviceWorker"in navigator?navigator.serviceWorker:null,i=r(o=>{const l=W3t(o.data);l&&(l.type==="navigate"?e.navigate(l.url):U3t(l.notification))},"onMessage");return a?.addEventListener("message",i),a?.startMessages(),()=>{n(),a?.removeEventListener("message",i)}}r(bms,"startNotificationRuntime");function vms(){const e=Gn(),s=(0,m.useRef)(e),{data:n}=te({queryKey:D.auth.session,queryFn:r(()=>Ma.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 bms({userId:a,navigate:r(i=>s.current(i),"navigate")})},[a]),null}r(vms,"NotificationRuntime");var $$e={get:r(e=>Ce.get(`/companies/${e}/primary-agent/me`),"get"),set:r((e,s)=>Ce.put(`/companies/${e}/primary-agent/me`,s),"set")};function yms(e){const s=te({queryKey:D.auth.session,queryFn:r(()=>Ma.getSession(),"queryFn")}),n=s.data?.user?.id??s.data?.session?.userId??"local-board",a=te({queryKey:D.primaryAgent.mine(e??"__none__",n),queryFn:r(()=>$$e.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(yms,"usePrimaryAgent");function jms({children:e}){const{selectedCompanyId:s}=ps(),n=yms(s),a=Nt(),{pushToast:i}=Qr(),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(()=>Ct.list(s),"queryFn"),enabled:!!s}),u=ye({mutationFn:r(f=>$$e.set(f.companyId,{primaryAgentId:f.agentId}),"mutationFn"),onMutate:r(async f=>{const x=l(f);await a.cancelQueries({queryKey:x});const b=a.getQueryData(x);return a.setQueryData(x,{companyId:f.companyId,userId:f.userId,primaryAgentId:f.agentId,initialized:!0}),{previous:b}},"onMutate"),onError:r((f,x,b)=>{a.setQueryData(l(x),b?.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,b)=>{a.invalidateQueries({queryKey:l(b)}),a.invalidateQueries({queryKey:D.resourceMemberships.mine(b.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)(X9e,{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(jms,"PrimaryAgentProvider");function wms(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(wms,"managedRoutineToRow");function Nms({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])),b=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 j=wms(v),N=v.href??(v.routineId?`/routines/${v.routineId}`:"/routines"),w=v.missingRefs??[],k=!!(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)(MPe,{routine:j,projectById:b,agentById:x,runningRoutineId:o,statusMutationRoutineId:l,href:N,configureLabel:"Configure",managedByLabel:S?`Managed by ${S}`:null,runNowButton:!0,hideArchiveAction:!0,disableRunNow:!k,disableToggle:!k,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,j.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(Nms,"ManagedRoutinesList");function oge(e){return new Set(e??[])}r(oge,"toPathSet");function kms({expandedPaths:e,checkedPaths:s,selectedFile:n=null,showCheckboxes:a=!1,onToggleDir:i,onSelectFile:o,...l}){return(0,m.createElement)(Kj,{...l,selectedFile:n,expandedDirs:oge(e),checkedFiles:s?oge(s):void 0,showCheckboxes:a,onToggleDir:i??(()=>{}),onSelectFile:o??(()=>{})})}r(kms,"PluginSdkFileTree");function Sms(e){const[s,n]=(0,m.useState)(null);return(0,m.useEffect)(()=>{let a=!1;return Id(()=>import("./MarkdownEditor-D7suACD6.js").then(i=>i.n).then(i=>{a||n(()=>i.MarkdownEditor)}),__vite__mapDeps([35,5,7,9,10,25,24,26,36,37])),()=>{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(Sms,"PluginSdkMarkdownEditor");function Cms(e){return Object.fromEntries(Object.entries(e).filter(([,s])=>s!=null&&s!==""&&s!==!1))}r(Cms,"compactIssueFilters");function _ms({companyId:e,projectId:s=null,filters:n,viewStateKey:a="paperclip:plugin-issues-view",initialSearch:i,createIssueLabel:o,searchWithinLoadedIssues:l=!0}){const c=Nt(),d=(0,m.useMemo)(()=>Cms({...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(()=>Ct.list(e),"queryFn"),enabled:!!e}),{data:x}=te({queryKey:D.projects.list(e??"__no-company__",{includeArchived:!0}),queryFn:r(()=>ra.list(e,{includeArchived:!0}),"queryFn"),enabled:!!e}),b=D.liveRuns(e??"__no-company__"),v=jo({companyId:e,resourceKey:"live-runs",queryKey:b,enabled:!!e,refetchInterval:!1,leaderOnly:!0}),{data:j,dataUpdatedAt:N}=te({queryKey:b,queryFn:r(()=>Xr.liveRunsForCompany(e),"queryFn"),enabled:v.enabled,refetchInterval:v.refetchInterval});wo(v,j,N);const{data:w,isLoading:k,error:S}=te({queryKey:p,queryFn:r(()=>yt.list(e,d),"queryFn"),enabled:!!e}),C=(0,m.useMemo)(()=>qg(j,w),[w,j]),_=ye({mutationFn:r(({id:R,data:A})=>yt.update(R,A),"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)(Cg,{issues:w??[],isLoading:k,error:S,agents:f,projects:x,liveIssueIds:C,projectId:h??void 0,viewStateKey:a,initialSearch:i,createIssueLabel:o,searchWithinLoadedIssues:l,onUpdateIssue:r((R,A)=>_.mutate({id:R,data:A}),"onUpdateIssue")}):(0,m.createElement)("div",{className:"text-sm text-muted-foreground"},"Select an organization to view tasks.")}r(_ms,"PluginSdkIssuesList");function Ims({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=$W(),f=e??p.companyId??null,{data:x}=te({queryKey:D.auth.session,queryFn:r(()=>Ma.getSession(),"queryFn"),enabled:c}),b=x?.user?.id??x?.session?.userId??null,{data:v}=te({queryKey:D.agents.list(f??"__no-company__"),queryFn:r(()=>Ct.list(f),"queryFn"),enabled:!!f}),{data:j}=te({queryKey:D.access.companyUserDirectory(f??"__no-company__"),queryFn:r(()=>lr.listUserDirectory(f),"queryFn"),enabled:!!f&&c}),N=(0,m.useMemo)(()=>Yq(),[]),w=(0,m.useMemo)(()=>N.map(R=>R.startsWith("agent:")?R.slice(6):null).filter(R=>!!R),[N]),k=(0,m.useMemo)(()=>Oy((v??[]).filter(R=>d||R.status!=="terminated"),w),[v,d,w]),S=(0,m.useMemo)(()=>[...c?O0e(b):[],...c?TS(j?.users,{excludeUserIds:[b]}):[],...k.map(R=>({id:Ih({assigneeAgentId:R.id}),label:R.name,searchText:`${R.name} ${R.role} ${R.title??""}`}))],[j?.users,b,c,k]),C=vy(s),_=C.assigneeAgentId?k.find(R=>R.id===C.assigneeAgentId):null;return(0,m.createElement)(Yu,{value:s,options:S,recentOptionIds:N,placeholder:a,noneLabel:i,searchPlaceholder:o,emptyMessage:l,className:u,onConfirm:h,onChange:r(R=>{const A=vy(R);A.assigneeAgentId&&Fy(A.assigneeAgentId),A.assigneeUserId&&K_(A.assigneeUserId),n(R,A)},"onChange"),renderTriggerValue:r(R=>R?_?(0,m.createElement)(b4,null,(0,m.createElement)(zP,{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 A=vy(R.id),T=A.assigneeAgentId?k.find(E=>E.id===A.assigneeAgentId):null;return(0,m.createElement)(b4,null,T?(0,m.createElement)(zP,{icon:T.icon,className:"h-3.5 w-3.5 shrink-0 text-muted-foreground"}):(0,m.createElement)(cd,{className:"h-3.5 w-3.5 shrink-0 text-muted-foreground"}),(0,m.createElement)("span",{className:"truncate"},R.label))},"renderOption")})}r(Ims,"PluginSdkAssigneePicker");function Ams({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=$W(),p=e??h.companyId??null,{data:f}=te({queryKey:D.auth.session,queryFn:r(()=>Ma.getSession(),"queryFn")}),x=f?.user?.id??f?.session?.userId??null,{data:b}=te({queryKey:D.projects.list(p??"__no-company__",{includeArchived:c}),queryFn:r(()=>ra.list(p,{includeArchived:c}),"queryFn"),enabled:!!p}),v=(0,m.useMemo)(()=>(b??[]).filter(S=>c||!S.archivedAt),[c,b]),{orderedProjects:j}=Cj({projects:v,companyId:p,userId:x}),N=(0,m.useMemo)(()=>By(),[]),w=(0,m.useMemo)(()=>j.map(S=>({id:S.id,label:S.name,searchText:S.description??""})),[j]),k=j.find(S=>S.id===s)??null;return(0,m.createElement)(Yu,{value:s,options:w,recentOptionIds:N,placeholder:a,noneLabel:i,searchPlaceholder:o,emptyMessage:l,className:d,onConfirm:u,onChange:r(S=>{S&&gb(S),n(S)},"onChange"),renderTriggerValue:r(S=>!S||!k?(0,m.createElement)("span",{className:"text-muted-foreground"},a):(0,m.createElement)(b4,null,(0,m.createElement)("span",{className:"h-3.5 w-3.5 shrink-0 rounded-sm",style:{backgroundColor:k.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=j.find(_=>_.id===S.id);return(0,m.createElement)(b4,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(Ams,"PluginSdkProjectPicker");function b4({children:e}){return(0,m.createElement)("span",{className:"contents"},e)}r(b4,"FragmentSafe");function Tms({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(Tms,"PluginSdkStatusBadge");function Rms({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(Rms,"PluginSdkDataTable");function Ems({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(Ems,"PluginSdkKeyValueList");function Pms({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(Pms,"PluginSdkMetricCard");function Mms({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(Mms,"PluginSdkJsonTree");function Dms({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(Dms,"PluginSdkSpinner");var Lms=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 $ms(e,s){globalThis.__paperclipPluginBridge__={react:e,reactJsxRuntime:t,reactDom:s,sdkUi:{usePluginData:ZWe,usePluginAction:eVe,useHostContext:$W,useHostLocation:sVe,useHostNavigation:tVe,usePluginStream:rVe,usePluginToast:nVe,copyTextToClipboard:Ia,MarkdownBlock:r(({content:n,className:a,enableWikiLinks:i,wikiLinkRoot:o,resolveWikiLinkHref:l})=>(0,m.createElement)(In,{className:a,softBreaks:!1,enableWikiLinks:i,wikiLinkRoot:o,resolveWikiLinkHref:l,children:n}),"MarkdownBlock"),MetricCard:Pms,StatusBadge:Tms,DataTable:Rms,KeyValueList:Ems,JsonTree:Mms,Spinner:Dms,ErrorBoundary:Lms,MarkdownEditor:Sms,FileTree:kms,IssuesList:_ms,AssigneePicker:Ims,ProjectPicker:Ams,ManagedRoutinesList:Nms}}}r($ms,"initPluginBridge");var Oms=1e4;function Fms(e=Oms){if(typeof performance>"u"||typeof performance.clearMeasures!="function")return()=>{};const n=setInterval(r(()=>{globalThis.__paperclipKeepPerfMeasures||performance.clearMeasures()},"reap"),e);return()=>clearInterval(n)}r(Fms,"startPerfMeasureReaper");var Bms=fj((e=>{function s(B,q){var z=B.length;B.push(q);e:for(;0<z;){var K=z-1>>>1,W=B[K];if(0<i(W,q))B[K]=q,B[z]=W,z=K;else break e}}r(s,"push");function n(B){return B.length===0?null:B[0]}r(n,"peek");function a(B){if(B.length===0)return null;var q=B[0],z=B.pop();if(z!==q){B[0]=z;e:for(var K=0,W=B.length,Q=W>>>1;K<Q;){var re=2*(K+1)-1,J=B[re],ie=re+1,X=B[ie];if(0>i(J,z))ie<W&&0>i(X,J)?(B[K]=X,B[ie]=z,K=ie):(B[K]=J,B[re]=z,K=re);else if(ie<W&&0>i(X,z))B[K]=X,B[ie]=z,K=ie;else break e}}return q}r(a,"pop");function i(B,q){var z=B.sortIndex-q.sortIndex;return z!==0?z:B.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,b=!1,v=!1,j=!1,N=typeof setTimeout=="function"?setTimeout:null,w=typeof clearTimeout=="function"?clearTimeout:null,k=typeof setImmediate<"u"?setImmediate:null;function S(B){for(var q=n(u);q!==null;){if(q.callback===null)a(u);else if(q.startTime<=B)a(u),q.sortIndex=q.expirationTime,s(d,q);else break;q=n(u)}}r(S,"advanceTimers");function C(B){if(v=!1,S(B),!b)if(n(d)!==null)b=!0,_||(_=!0,O());else{var q=n(u);q!==null&&M(C,q.startTime-B)}}r(C,"handleTimeout");var _=!1,R=-1,A=5,T=-1;function E(){return j?!0:!(e.unstable_now()-T<A)}r(E,"shouldYieldToHost");function L(){if(j=!1,_){var B=e.unstable_now();T=B;var q=!0;try{e:{b=!1,v&&(v=!1,w(R),R=-1),x=!0;var z=f;try{t:{for(S(B),p=n(d);p!==null&&!(p.expirationTime>B&&E());){var K=p.callback;if(typeof K=="function"){p.callback=null,f=p.priorityLevel;var W=K(p.expirationTime<=B);if(B=e.unstable_now(),typeof W=="function"){p.callback=W,S(B),q=!0;break t}p===n(d)&&a(d),S(B)}else a(d);p=n(d)}if(p!==null)q=!0;else{var Q=n(u);Q!==null&&M(C,Q.startTime-B),q=!1}}break e}finally{p=null,f=z,x=!1}q=void 0}}finally{q?O():_=!1}}}r(L,"performWorkUntilDeadline");var O;if(typeof k=="function")O=r(function(){k(L)},"schedulePerformWorkUntilDeadline");else if(typeof MessageChannel<"u"){var P=new MessageChannel,U=P.port2;P.port1.onmessage=L,O=r(function(){U.postMessage(null)},"schedulePerformWorkUntilDeadline")}else O=r(function(){N(L,0)},"schedulePerformWorkUntilDeadline");function M(B,q){R=N(function(){B(e.unstable_now())},q)}r(M,"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(B){B.callback=null},e.unstable_forceFrameRate=function(B){0>B||125<B||(A=0<B?Math.floor(1e3/B):5)},e.unstable_getCurrentPriorityLevel=function(){return f},e.unstable_next=function(B){switch(f){case 1:case 2:case 3:var q=3;break;default:q=f}var z=f;f=q;try{return B()}finally{f=z}},e.unstable_requestPaint=function(){j=!0},e.unstable_runWithPriority=function(B,q){switch(B){case 1:case 2:case 3:case 4:case 5:break;default:B=3}var z=f;f=B;try{return q()}finally{f=z}},e.unstable_scheduleCallback=function(B,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,B){case 1:var W=-1;break;case 2:W=250;break;case 5:W=1073741823;break;case 4:W=1e4;break;default:W=5e3}return W=z+W,B={id:h++,callback:q,priorityLevel:B,startTime:z,expirationTime:W,sortIndex:-1},z>K?(B.sortIndex=z,s(u,B),n(d)===null&&B===n(u)&&(v?(w(R),R=-1):v=!0,M(C,z-K))):(B.sortIndex=W,s(d,B),b||x||(b=!0,_||(_=!0,O()))),B},e.unstable_shouldYield=E,e.unstable_wrapCallback=function(B){var q=f;return function(){var z=f;f=q;try{return B.apply(this,arguments)}finally{f=z}}}})),zms=fj(((e,s)=>{s.exports=Bms()})),qms=fj((e=>{var s=zms(),n=T9(),a=dge();function i(g){var y="https://react.dev/errors/"+g;if(1<arguments.length){y+="?args[]="+encodeURIComponent(arguments[1]);for(var I=2;I<arguments.length;I++)y+="&args[]="+encodeURIComponent(arguments[I])}return"Minified React error #"+g+"; visit "+y+" for the full message or use the non-minified dev environment for full errors and additional helpful warnings."}r(i,"formatProdErrorMessage");function o(g){return!(!g||g.nodeType!==1&&g.nodeType!==9&&g.nodeType!==11)}r(o,"isValidContainer");function l(g){var y=g,I=g;if(g.alternate)for(;y.return;)y=y.return;else{g=y;do y=g,(y.flags&4098)!==0&&(I=y.return),g=y.return;while(g)}return y.tag===3?I:null}r(l,"getNearestMountedFiber");function c(g){if(g.tag===13){var y=g.memoizedState;if(y===null&&(g=g.alternate,g!==null&&(y=g.memoizedState)),y!==null)return y.dehydrated}return null}r(c,"getSuspenseInstanceFromFiber");function d(g){if(g.tag===31){var y=g.memoizedState;if(y===null&&(g=g.alternate,g!==null&&(y=g.memoizedState)),y!==null)return y.dehydrated}return null}r(d,"getActivityInstanceFromFiber");function u(g){if(l(g)!==g)throw Error(i(188))}r(u,"assertIsMounted");function h(g){var y=g.alternate;if(!y){if(y=l(g),y===null)throw Error(i(188));return y!==g?null:g}for(var I=g,F=y;;){var H=I.return;if(H===null)break;var ee=H.alternate;if(ee===null){if(F=H.return,F!==null){I=F;continue}break}if(H.child===ee.child){for(ee=H.child;ee;){if(ee===I)return u(H),g;if(ee===F)return u(H),y;ee=ee.sibling}throw Error(i(188))}if(I.return!==F.return)I=H,F=ee;else{for(var je=!1,Ve=H.child;Ve;){if(Ve===I){je=!0,I=H,F=ee;break}if(Ve===F){je=!0,F=H,I=ee;break}Ve=Ve.sibling}if(!je){for(Ve=ee.child;Ve;){if(Ve===I){je=!0,I=ee,F=H;break}if(Ve===F){je=!0,F=ee,I=H;break}Ve=Ve.sibling}if(!je)throw Error(i(189))}}if(I.alternate!==F)throw Error(i(190))}if(I.tag!==3)throw Error(i(188));return I.stateNode.current===I?g:y}r(h,"findCurrentFiberUsingSlowPath");function p(g){var y=g.tag;if(y===5||y===26||y===27||y===6)return g;for(g=g.child;g!==null;){if(y=p(g),y!==null)return y;g=g.sibling}return null}r(p,"findCurrentHostFiberImpl");var f=Object.assign,x=Symbol.for("react.element"),b=Symbol.for("react.transitional.element"),v=Symbol.for("react.portal"),j=Symbol.for("react.fragment"),N=Symbol.for("react.strict_mode"),w=Symbol.for("react.profiler"),k=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"),A=Symbol.for("react.memo"),T=Symbol.for("react.lazy"),E=Symbol.for("react.activity"),L=Symbol.for("react.memo_cache_sentinel"),O=Symbol.iterator;function P(g){return g===null||typeof g!="object"?null:(g=O&&g[O]||g["@@iterator"],typeof g=="function"?g:null)}r(P,"getIteratorFn");var U=Symbol.for("react.client.reference");function M(g){if(g==null)return null;if(typeof g=="function")return g.$$typeof===U?null:g.displayName||g.name||null;if(typeof g=="string")return g;switch(g){case j:return"Fragment";case w:return"Profiler";case N:return"StrictMode";case _:return"Suspense";case R:return"SuspenseList";case E:return"Activity"}if(typeof g=="object")switch(g.$$typeof){case v:return"Portal";case S:return g.displayName||"Context";case k:return(g._context.displayName||"Context")+".Consumer";case C:var y=g.render;return g=g.displayName,g||(g=y.displayName||y.name||"",g=g!==""?"ForwardRef("+g+")":"ForwardRef"),g;case A:return y=g.displayName||null,y!==null?y:M(g.type)||"Memo";case T:y=g._payload,g=g._init;try{return M(g(y))}catch{}}return null}r(M,"getComponentNameFromType");var B=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},W=[],Q=-1;function re(g){return{current:g}}r(re,"createCursor");function J(g){0>Q||(g.current=W[Q],W[Q]=null,Q--)}r(J,"pop");function ie(g,y){Q++,W[Q]=g.current,g.current=y}r(ie,"push");var X=re(null),ne=re(null),oe=re(null),G=re(null);function Z(g,y){switch(ie(oe,y),ie(ne,g),ie(X,null),y.nodeType){case 9:case 11:g=(g=y.documentElement)&&(g=g.namespaceURI)?HX(g):0;break;default:if(g=y.tagName,y=y.namespaceURI)y=HX(y),g=QX(y,g);else switch(g){case"svg":g=1;break;case"math":g=2;break;default:g=0}}J(X),ie(X,g)}r(Z,"pushHostContainer");function Y(){J(X),J(ne),J(oe)}r(Y,"popHostContainer");function ae(g){g.memoizedState!==null&&ie(G,g);var y=X.current,I=QX(y,g.type);y!==I&&(ie(ne,g),ie(X,I))}r(ae,"pushHostContext");function se(g){ne.current===g&&(J(X),J(ne)),G.current===g&&(J(G),_C._currentValue=K)}r(se,"popHostContext");var ce,pe;function we(g){if(ce===void 0)try{throw Error()}catch(I){var y=I.stack.trim().match(/\n( *(at )?)/);ce=y&&y[1]||"",pe=-1<I.stack.indexOf(`
669
669
  at`)?" (<anonymous>)":-1<I.stack.indexOf("@")?"@unknown:0:0":""}return`
670
670
  `+ce+g+pe}r(we,"describeBuiltInComponentFrame");var Se=!1;function Te(g,y){if(!g||Se)return"";Se=!0;var I=Error.prepareStackTrace;Error.prepareStackTrace=void 0;try{var F={DetermineComponentFrameRoot:r(function(){try{if(y){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(xs){var ls=xs}Reflect.construct(g,[],Us)}else{try{Us.call()}catch(xs){ls=xs}g.call(Us.prototype)}}else{try{throw Error()}catch(xs){ls=xs}(Us=g())&&typeof Us.catch=="function"&&Us.catch(function(){})}}catch(xs){if(xs&&ls&&typeof xs.stack=="string")return[xs.stack,ls.stack]}return[null,null]},"DetermineComponentFrameRoot")};F.DetermineComponentFrameRoot.displayName="DetermineComponentFrameRoot";var H=Object.getOwnPropertyDescriptor(F.DetermineComponentFrameRoot,"name");H&&H.configurable&&Object.defineProperty(F.DetermineComponentFrameRoot,"name",{value:"DetermineComponentFrameRoot"});var ee=F.DetermineComponentFrameRoot(),je=ee[0],Ve=ee[1];if(je&&Ve){var vt=je.split(`
671
671
  `),as=Ve.split(`