@tickernelz/paperclip-pro-ui 2026.1008.3 → 2026.1008.5

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-DWnXCBun.js","assets/character-CguPM7IG.js","assets/prod-COP_vZWu.js","assets/rolldown-runtime-ZpX3ckPj.js","assets/CompanyExport-DZXwSqbC.js","assets/agent-avatar-url-Cv0eH_gk.js","assets/router-C-8KEGbX.js","assets/preload-helper-CceJXRIF.js","assets/boxes-DN6zNhxD.js","assets/agents-BCsEXmmg.js","assets/EmptyState-CkTgLu0M.js","assets/button-Bs_hqIdB.js","assets/mention-chips-BfQmC5ut.js","assets/StatusIcon-DMWo0jee.js","assets/clipboard-AVa8mWpe.js","assets/loader-circle-Ccn7cIQz.js","assets/octagon-alert-CvqN8YxN.js","assets/MarkdownBody-DVrC75-l.js","assets/check-Wdx0oVFt.js","assets/external-link-C0kSD4FX.js","assets/rotate-ccw-BFBwEreq.js","assets/PageSkeleton-BaA5fPnJ.js","assets/skeleton-CT2up2kA.js","assets/Agents.production-DC72vjFS.js","assets/AgentAvatar-BmM_AHw4.js","assets/tabs-DpWk-7C2.js","assets/dist-CMaDTo1K.js","assets/bot-B7BKrriZ.js","assets/heartbeats-DC1Jg5wJ.js","assets/triangle-alert-Bu0jhxoE.js","assets/SidebarContext-CkAM3N-1.js","assets/environments-C34o7Amp.js","assets/Routines.production-DQbPhKWQ.js","assets/RoutineRunVariablesDialog-jpQtDrRe.js","assets/MarkdownEditor-DIHDyI6k.js","assets/dist-DCMmOKhY.js","assets/dist-DCJXgQu0.js","assets/sheet-BAKlmZaz.js","assets/checkbox-BXdCzpwP.js","assets/chevron-right-H1hxuQcL.js","assets/label-FDocpxbC.js","assets/select-Bk63MRJ7.js","assets/chevron-down-_ZjvalUC.js","assets/useHiddenSettings-e3P22afn.js","assets/health-DOk361OT.js","assets/badge-CBYpD1kE.js","assets/input-DWX5pycC.js","assets/company-members-D5TY0Q5y.js","assets/AgentIdentity-yWgBWli2.js","assets/card-q2lFI4Jb.js","assets/RoutineDetail.production-f4dz9CbP.js","assets/save-CuFXd8QN.js","assets/CompanySkills.production-Ctn-8voB.js","assets/use-adapter-capabilities-JfIn6NXs.js","assets/file-text-D75dT7T5.js","assets/CompanyActivity.production-Clf5BH9f.js","assets/Costs.production-C3x7Atp8.js","assets/OrgChart.production-DbBXNgXD.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-DZvn-O-F.js","assets/character-CguPM7IG.js","assets/prod-COP_vZWu.js","assets/rolldown-runtime-ZpX3ckPj.js","assets/CompanyExport-Csbe_I4o.js","assets/agent-avatar-url-Cv0eH_gk.js","assets/router-C-8KEGbX.js","assets/preload-helper-CceJXRIF.js","assets/boxes-DN6zNhxD.js","assets/agents-BCsEXmmg.js","assets/EmptyState-CkTgLu0M.js","assets/button-Bs_hqIdB.js","assets/mention-chips-BfQmC5ut.js","assets/StatusIcon-DMWo0jee.js","assets/clipboard-AVa8mWpe.js","assets/loader-circle-Ccn7cIQz.js","assets/octagon-alert-CvqN8YxN.js","assets/MarkdownBody-DVrC75-l.js","assets/check-Wdx0oVFt.js","assets/external-link-C0kSD4FX.js","assets/rotate-ccw-BFBwEreq.js","assets/PageSkeleton-BaA5fPnJ.js","assets/skeleton-CT2up2kA.js","assets/Agents.production-koHgVDEu.js","assets/AgentAvatar-BmM_AHw4.js","assets/tabs-DpWk-7C2.js","assets/dist-CMaDTo1K.js","assets/bot-B7BKrriZ.js","assets/heartbeats-DC1Jg5wJ.js","assets/triangle-alert-Bu0jhxoE.js","assets/SidebarContext-CkAM3N-1.js","assets/environments-C34o7Amp.js","assets/Routines.production-CCosQxj4.js","assets/RoutineRunVariablesDialog-jpQtDrRe.js","assets/MarkdownEditor-DIHDyI6k.js","assets/dist-DCMmOKhY.js","assets/dist-DCJXgQu0.js","assets/sheet-BAKlmZaz.js","assets/checkbox-BXdCzpwP.js","assets/chevron-right-H1hxuQcL.js","assets/label-FDocpxbC.js","assets/select-Bk63MRJ7.js","assets/chevron-down-_ZjvalUC.js","assets/useHiddenSettings-e3P22afn.js","assets/health-DOk361OT.js","assets/badge-CBYpD1kE.js","assets/input-DWX5pycC.js","assets/company-members-D5TY0Q5y.js","assets/AgentIdentity-yWgBWli2.js","assets/card-q2lFI4Jb.js","assets/RoutineDetail.production-tvnkma9I.js","assets/save-CuFXd8QN.js","assets/CompanySkills.production-Dfki-nUi.js","assets/use-adapter-capabilities-JfIn6NXs.js","assets/file-text-D75dT7T5.js","assets/CompanyActivity.production-B7l2pgBy.js","assets/Costs.production-CBHHLCW0.js","assets/OrgChart.production-DzZWjZTS.js"])))=>i.map(i=>d[i]);
2
2
  var FDe=Object.defineProperty;var r=(e,s)=>FDe(e,"name",{value:s,configurable:!0});import{i as aM,n as BDe,t as Fy}from"./rolldown-runtime-ZpX3ckPj.js";import{$ as _pe,$n as Ipe,$r as lb,$t as zDe,A as Bi,An as qDe,Ar as g3,At as UDe,B as cr,Bn as rp,Br as $l,Bt as KDe,C as WDe,Cn as Y8,Cr as fz,Ct as VDe,D as Ad,Dn as Ape,Dr as HDe,Dt as GDe,E as Tpe,En as xz,Er as J8,Et as yJ,F as lg,Fi as QDe,Fn as YDe,Fr as JDe,Ft as b3,G as XDe,Gn as Rpe,Gr as ZDe,Gt as eLe,Hn as v3,Hr as Te,Ht as Epe,I as n_,Ii as Ppe,In as Mpe,Ir as ML,It as tLe,J as sLe,Jn as nLe,Jr as rLe,Jt as aLe,K as iLe,Kn as NI,Kt as oLe,L as v1,Li as X8,Ln as lLe,Lr as sk,Lt as cLe,M as gh,Mi as SI,Mn as dLe,Mr as uLe,Mt as VR,N as Va,Ni as mLe,Nn as hLe,Nr as y3,Nt as AN,O as Rr,On as pLe,Or as fLe,Ot as Dpe,P as j3,Pi as Dt,Pn as xLe,Pr as gLe,Pt as bLe,Q as Oa,Qn as jJ,Qr as Uk,Qt as vLe,R as Rm,Rn as nk,Rr as wJ,Rt as yLe,S as W,Sn as jLe,Sr as w3,St as wLe,T as ta,Tn as kLe,Tr as NLe,Tt as Z8,U as SLe,Un as TN,Ur as CLe,Ut as _Le,V as Lpe,Vn as $pe,Vr as dn,Vt as ILe,W as ps,Wn as Ope,Wr as kJ,Wt as ALe,X as e7,Xn as xf,Xt as NJ,Y as Vf,Yn as Fpe,Yr as k3,Yt as TLe,Z as P,Zn as Bpe,Zr as RLe,Zt as ELe,_ as Cm,_n as zpe,_r as PLe,_t as SJ,an as MLe,ar as DL,at as CJ,b as _J,bn as IJ,br as qpe,bt as Upe,c as DLe,cn as LLe,cr as $Le,ct as Kpe,d as OLe,dn as FLe,dr as iM,dt as BLe,ei as zLe,en as qLe,er as ULe,et as kf,fn as KLe,fr as Wpe,ft as Vpe,g as Xl,gi as WLe,gn as HR,gr as VLe,gt as cg,h as By,hi as HLe,hn as y1,hr as GLe,ht as Hpe,i as oM,in as Gpe,ir as QLe,it as AJ,j as YLe,jn as JLe,jr as TJ,jt as XLe,k as gz,kn as cb,kt as t7,l as CI,ln as Qpe,lr as lM,lt as Ype,m as RN,mn as ZLe,mr as e$e,mt as t$e,n as bv,ni as Z,nn as s$e,nr as RJ,nt as Nf,o as n$e,on as Jpe,or as r$e,ot as Xpe,pi as a$e,pn as EJ,pr as i$e,pt as o$e,q as l$e,qn as s7,qr as qb,qt as Zpe,ri as c$e,rn as d$e,rr as u$e,s as zv,sn as m$e,sr as h$e,st as VS,t as Ft,ti as je,tn as p$e,tr as efe,tt as _I,un as tfe,ur as f$e,ut as x$e,v as g$e,vn as PJ,vr as II,vt as b$e,w as sfe,wn as Kk,wr as nfe,wt as EN,x as n7,xn as v$e,xr as MJ,xt as DJ,y as LJ,yn as rfe,yr as afe,yt as AI,z as r7,zn as y$e,zr as ife,zt as j$e}from"./agent-avatar-url-Cv0eH_gk.js";import{t as Jc}from"./preload-helper-CceJXRIF.js";import{$ as w$e,A as Yx,At as ofe,B as Ll,Bt as lfe,C as vp,Ct as k$e,D as N$e,Dt as S$e,E as C$e,Et as _$e,F as Td,Ft as db,G as Jx,H as cfe,Ht as va,I as cM,It as nt,K as r_,L as Ap,Lt as I$e,M as pd,Mt as ro,N as TI,Nt as A$e,O as Xx,Ot as T$e,P as zl,Pt as ld,Q as $J,R as io,Rt as R$e,S as E$e,St as dg,T as RI,Tt as GR,U as N3,Ut as fi,V as EI,Vt as dM,W as dfe,X as S3,Y as P$e,Z as ufe,_ as M$e,_t as OJ,a as PN,at as D$e,b as C3,bt as FJ,ct as mfe,d as L$e,dt as Cw,et as $$e,f as ly,ft as Ct,g as O$e,gt as hl,h as F$e,ht as MN,i as B$e,it as hfe,j as a7,jt as z$e,k as Th,kt as q$e,l as U$e,lt as K$e,m as pfe,mt as _3,n as ub,nt as W$e,o as Mn,ot as _2,p as uM,pt as I3,q as V$e,r as kn,rt as H$e,st as BJ,t as Ke,tt as zJ,u as i7,ut as G$e,v as Em,vt as Q$e,w as yp,wt as Y$e,x as Ef,xt as H0,y as J$e,yt as LL,z as X$e,zt as na}from"./router-C-8KEGbX.js";import{$ as Z$e,$n as xh,$t as eOe,A as tOe,An as qJ,Ar as DN,At as cy,B as Ng,Bn as ffe,Br as sOe,Bt as rk,C as o7,Cn as xfe,Cr as l7,Ct as Au,D as nOe,Dn as A3,Dr as rOe,Dt as aOe,E as bz,En as gfe,Er as PI,Et as bfe,Fn as UJ,Fr as Tu,Ft as dy,G as zy,Gn as iOe,Gr as mM,Gt as oOe,H as G0,Hn as T3,Hr as jp,Ht as vfe,I as yfe,In as jfe,Ir as Sg,It as a_,J as wfe,Jn as kfe,Jt as lOe,K as cOe,Kn as Nfe,Kr as Rh,Kt as dOe,L as uOe,Ln as c7,Lr as mOe,Lt as hOe,M as pOe,Mn as Sfe,Mr as xl,Mt as MI,N as fOe,Nn as Cfe,Nr as ec,Nt as vz,O as xOe,On as R3,Or as Pf,Ot as _fe,Pn as KJ,Pr as WJ,Pt as uy,Q as gOe,Qn as Ife,Qt as bOe,R as vOe,Rn as Afe,Rr as Tfe,Rt as yOe,S as jOe,Sn as ak,Sr as Rfe,St as yz,T as Efe,Tn as ik,Tr as Pfe,Tt as wOe,U as jz,Un as kOe,Ur as hM,Ut as fc,V as Mfe,Vn as E3,Vr as Dfe,Vt as Mx,W as LN,Wn as NOe,Wr as P3,Wt as $N,X as SOe,Xn as Lfe,Xt as COe,Y as _Oe,Yn as VJ,Yt as ok,Z as IOe,Zn as $fe,Zt as HJ,_ as AOe,_n as Ofe,_r as Ffe,_t as TOe,a as ROe,an as yc,ar as Wk,at as Bfe,b as $L,bn as zfe,br as ON,bt as qfe,c as GJ,cn as EOe,cr as M3,ct as QJ,d as Ufe,dn as lk,dr as Kfe,dt as d7,en as i_,er as Wfe,et as POe,f as o_,fn as MOe,fr as DOe,ft as Vfe,g as Hfe,gn as Gfe,gr as LOe,gt as DI,h as D3,hn as $Oe,hr as pM,ht as wp,i as OOe,in as FOe,ir as Qfe,it as BOe,j as zOe,jn as qOe,jr as gl,jt as Q0,k as u7,kn as YJ,kr as FN,kt as UOe,l as OL,ln as KOe,lr as WOe,lt as Yfe,m as Jfe,mn as Xfe,mr as BN,mt as VOe,n as HOe,nn as JJ,nr as wz,nt as Zfe,o as GOe,on as exe,or as m7,ot as kz,p as txe,pn as sxe,pr as QOe,pt as qy,q as YOe,qn as L3,qr as zN,qt as JOe,r as ug,rn as h7,rr as qv,rt as XOe,s as ZOe,sn as Vk,sr as nxe,st as rxe,t as p7,tn as eFe,tr as _m,tt as tFe,u as sFe,ur as nFe,ut as rFe,v as XJ,vn as axe,vr as qN,vt as aFe,w as $3,wn as l_,wr as f7,wt as iFe,x as oFe,xn as Wx,xr as lFe,xt as Nz,y as ixe,yn as O3,yr as LI,yt as oxe,z as cFe,zn as F3,zr as dFe,zt as uFe}from"./RoutineRunVariablesDialog-jpQtDrRe.js";import{$ as lxe,Z as Fn,a as mFe,at as hFe,it as pFe,o as fFe,s as xFe}from"./mention-chips-BfQmC5ut.js";import{g as gFe}from"./dist-DCMmOKhY.js";import{i as bFe}from"./dist-CMaDTo1K.js";import{t as xc}from"./boxes-DN6zNhxD.js";import{D as vFe,E as yFe,S as jFe,a as cxe,c as Yr,d as Qc,f as dxe,i as wFe,l as vi,m as Y0,o as kFe,p as Cg,r as NFe,s as uxe,t as fd,u as Mu,w as SFe,x as CFe}from"./MarkdownEditor-DIHDyI6k.js";import{_ as x7,a as mxe,b as fM,c as hxe,d as Du,f as Lu,g as $u,h as Ou,i as c_,l as Fu,m as Bu,n as _Fe,o as kp,p as zu,r as Mh,s as Pm,t as Dh,u as qu,v as _i,y as gc}from"./sheet-BAKlmZaz.js";import{a as Mo,c as IFe,i as xM,l as xd,n as AFe,o as Do,r as Hl,s as pxe,t as kr}from"./AgentAvatar-BmM_AHw4.js";import{A as Pd,C as ni,D as g7,E as b7,O as Jr,S as bh,T as v7,_ as y7,a as Js,b as mb,c as hn,d as Uy,f as zn,g as Xr,h as qn,i as TFe,j as Ri,k as la,l as RFe,m as Md,n as Tn,o as jn,p as Un,r as Qs,s as hr,t as pi,u as Xs,v as Zr,w as EFe,x as D0,y as ls}from"./checkbox-BXdCzpwP.js";import{_ as PFe,c as ci,d as UN,f as ju,g as Dx,h as KN,i as MFe,l as $I,m as Ko,n as Ky,o as gM,p as WN,s as DFe,t as Gs,u as LFe,v as oo,y as bM}from"./label-FDocpxbC.js";import{i as za,n as ba,r as md,t as Ti}from"./tabs-DpWk-7C2.js";import{a as OC,c as ym,d as gr,f as Sz,g as Sr,h as $Fe,i as oa,l as fxe,m as OFe,n as mg,o as xxe,p as dr,r as Np,s as Jl,t as $t,u as Uv}from"./agents-BCsEXmmg.js";import{S as Su,a as gxe,b as ho,d as bxe,f as B3,g as pa,l as vxe,m as Yl,n as yxe,o as jxe,p as wxe,t as Xi,u as FFe,v as kxe,x as Ec,y as BFe}from"./StatusIcon-DMWo0jee.js";import{a as Tl,i as Mf,n as uh,r as ha,t as Wy}from"./use-adapter-capabilities-JfIn6NXs.js";import{a as Vy,c as jm,i as OI,n as zFe,o as Cu,r as Bn,s as vM,t as On}from"./EmptyState-CkTgLu0M.js";import{t as so}from"./bot-B7BKrriZ.js";import{t as gs}from"./check-Wdx0oVFt.js";import{t as nn}from"./chevron-down-_ZjvalUC.js";import{t as Rn}from"./chevron-right-H1hxuQcL.js";import{a as qFe,c as Ma,i as Nn,l as hb,n as Da,o as Nxe,r as UFe,s as La,t as $a}from"./select-Bk63MRJ7.js";import{n as Pc,r as Zi,t as Sf}from"./save-CuFXd8QN.js";import{A as hg,C as Cz,D as KFe,_ as Sxe,c as WFe,h as VFe,i as HFe,j as ca,k as yn,l as v0,n as GFe,o as QFe,p as _z,r as j7,t as L,u as YFe,y as JFe}from"./button-Bs_hqIdB.js";import{i as Ir,n as Si,r as Ho,t as fa}from"./clipboard-AVa8mWpe.js";import{t as Vn}from"./external-link-C0kSD4FX.js";import{C as Lh,S as XFe,_ as ZFe,a as eBe,b as tBe,c as sBe,d as Cxe,f as nBe,g as ZJ,h as rBe,i as aBe,l as iBe,m as _xe,n as Ixe,o as Axe,p as Txe,r as oBe,s as lBe,t as Sn,u as cBe,v as Cf,x as dBe,y as uBe}from"./MarkdownBody-DVrC75-l.js";import{t as Ha}from"./file-text-D75dT7T5.js";import{a as yM,i as Qo,n as mBe,o as Rxe,r as FI,t as sa}from"./heartbeats-DC1Jg5wJ.js";import{t as rt}from"./loader-circle-Ccn7cIQz.js";import{n as BI,t as eu}from"./useHiddenSettings-e3P22afn.js";import{t as Hk}from"./octagon-alert-CvqN8YxN.js";import{t as Ci}from"./rotate-ccw-BFBwEreq.js";import{t as Es}from"./triangle-alert-Bu0jhxoE.js";import{n as qa,t as hBe}from"./SidebarContext-CkAM3N-1.js";import{n as pBe,t as ct}from"./badge-CBYpD1kE.js";import{n as Nr,t as Pi}from"./environments-C34o7Amp.js";import{t as ht}from"./input-DWX5pycC.js";import{a as Df,i as zI,n as qI,o as pr,r as _g,t as VN}from"./company-members-D5TY0Q5y.js";import{t as tu}from"./health-DOk361OT.js";import{t as vn}from"./skeleton-CT2up2kA.js";import{t as gd}from"./AgentIdentity-yWgBWli2.js";import{a as fBe,i as Fl,n as xBe,o as no,r as Xa,s as ko,t as rn}from"./card-q2lFI4Jb.js";import{t as Ra}from"./PageSkeleton-BaA5fPnJ.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 gBe=class extends a$e{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:HLe(s,n.data),hasPreviousPage:WLe(s,n.data),isFetchNextPageError:u,isFetchingNextPage:h,isFetchPreviousPageError:p,isFetchingPreviousPage:f,isRefetchError:c&&!u&&!p,isRefetching:o&&!h&&!f}}};function pb(e,s){return c$e(e,gBe,s)}r(pb,"useInfiniteQuery");var bBe="adapter_auth_missing",vBe="document",yBe=80,jBe={markdown:"md",html:"html",json:"json",text:"txt"};function wBe(e){return e.normalize("NFKD").replace(/[\u0300-\u036f]/g,"").toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,yBe).replace(/-+$/g,"")||vBe}r(wBe,"documentExportSlug");function kBe(e){return jBe[(e??"").trim().toLowerCase()]??"md"}r(kBe,"documentExportExtension");function eX(e,s){const n=s.replace(/^\.+/,"").toLowerCase()||"md";return`${wBe(e)}.${n}`}r(eX,"documentExportFileName");function Iz(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(Iz,"decisionEffectTargetIssueIds");var NBe=new Set(["terminated","pending_approval","paused"]),SBe=new Set(["active","idle","running","error"]);function CBe(e){return SBe.has(e)&&!NBe.has(e)}r(CBe,"isAgentStatusInvokable");function HS(e){return e==="done"||e==="cancelled"}r(HS,"isPipelineTerminalStageKind");function Exe(e){const s={};for(const n of e)(s[n.stageId]??=[]).push(n);return s}r(Exe,"groupWarningsByStage");function Pxe(e){return e==="RESPONSIBLE_USER_UNAUTHORIZED"||e==="RESPONSIBLE_USER_UNAVAILABLE"}r(Pxe,"isResponsibleUserDenialCode");function UI(e){const s=e?.trim();return s&&s.length>0?s:"the responsible user"}r(UI,"responsibleUserLabel");function Az(e,s={}){const n=UI(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(Az,"describeResponsibleUserDenial");var _Be=["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 IBe(e){const s=e?.trim();return s&&s.length>0?s:"this task"}r(IBe,"issueLabel$2");function ABe(e){const s=e?.trim();return s&&s.length>0?s:"the current assignee"}r(ABe,"assigneeLabel");function TBe(e){const s=e?.trim();return s&&s.length>0?s:"this agent"}r(TBe,"actorLabel$1");var RBe="create a child issue with the request in its description (issue creation is a separate, open write path) and let its assignee act";function EBe(e,s={}){const n=IBe(s.issueIdentifier),a=TBe(s.actorLabel),i=ABe(s.assigneeLabel),o=UI(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 ${RBe}.`};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=Az("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=Az("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(EBe,"describeIssueWriteDenial");function Mxe(e){return(typeof e=="string"?e:e?.name??"").trim()}r(Mxe,"rawNameOf");function Dxe(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(Dxe,"looksLikeNetworkAddress");function Tz(e){return e.split(/[\s._-]+/).filter(Boolean).map(s=>s.charAt(0).toUpperCase()+s.slice(1).toLowerCase()).join(" ")}r(Tz,"titleCaseIdentifier");function PBe(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,""),Tz(n)||"Custom app"}r(PBe,"pluginPackageLabel");function Lf(e,s={}){const n=s.title?.trim();if(n)return n;const a=Mxe(e);if(!a||Dxe(a))return"Custom app";const i=PBe(a);if(i)return i;if(a.includes(":")&&!a.includes("://")){const o=a.slice(a.lastIndexOf(":")+1).trim();if(o)return Tz(o)}return/\s/.test(a)||/[A-Z]/.test(a)?a:/[._-]/.test(a)?Tz(a):a}r(Lf,"humanizeConnectionDisplayName");function tX(e){const s=Mxe(e);return s&&Dxe(s)?`hosted at ${s}`:null}r(tX,"connectionDisplaySecondaryHint");var sX=`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>
@@ -303,7 +303,7 @@ self.onmessage = function (e) {
303
303
  }
304
304
 
305
305
  };
306
- `;function Hnt(){const e=new Blob([Vnt],{type:"application/javascript"}),s=URL.createObjectURL(e);try{return new Worker(s)}finally{URL.revokeObjectURL(s)}}r(Hnt,"createSandboxedWorker");var Gq=new Map,T5=new Map,pE=new Set,fE=new Map,oSe=null;function Gnt(e){oSe=e}r(Gnt,"setDynamicParserResultNotifier");function lSe(e,s){e.worker.postMessage(s)}r(lSe,"sendToWorker");function Qnt(e){return e.nextId++}r(Qnt,"nextRequestId");function Ynt(e,s){return`${s}\0${e}`}r(Ynt,"lineCacheKey");function Jnt(){oSe?.()}r(Jnt,"notifyResultReady");function Xnt(e,s,n){return new Promise(a=>{const i=Qnt(e);e.pendingResolves.set(i,a),lSe(e,{type:"parse",id:i,line:s,ts:n})})}r(Xnt,"parseLineAsync");function VC(e){for(const s of e.pendingResolves.values())s([]);e.pendingResolves.clear()}r(VC,"drainPendingRequests");function Znt(e){return new Promise((s,n)=>{const a=Hnt(),i={worker:a,ready:!1,nextId:1,pendingResolves:new Map},o=setTimeout(()=>{VC(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"&&VC(i)},s(i);return}if(c.type==="error"){clearTimeout(o),VC(i),a.terminate(),n(new Error(c.message));return}},a.onerror=l=>{clearTimeout(o),VC(i),a.terminate(),n(new Error(`Worker error: ${l.message}`))},lSe(i,{type:"init",source:e})})}r(Znt,"initSandboxedWorker");function ert(e){const s=new Map,n=new Set;return{parseStdoutLine:r((i,o)=>{const l=Ynt(i,o),c=s.get(l);return c?c.slice():(n.has(l)||(n.add(l),Xnt(e,i,o).then(d=>{n.delete(l),s.set(l,d),Jnt()})),[])},"parseStdoutLine")}}r(ert,"buildParserModule");async function Qq(e){const s=T5.get(e);if(s)return s;if(pE.has(e))return null;const n=fE.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 pE.add(e),null;const o=await Znt(await i.text());Gq.set(e,o);const l=ert(o);return T5.set(e,l),l}catch{return pE.add(e),null}finally{fE.delete(e)}})();return fE.set(e,a),a}r(Qq,"loadDynamicParser");function Yq(e){const s=T5.has(e);T5.delete(e),pE.delete(e),fE.delete(e);const n=Gq.get(e);return n&&(VC(n),n.worker.terminate(),Gq.delete(e)),s}r(Yq,"invalidateDynamicParser");var xE=[],i4=new Map,Jq=new Set,cSe=new Map,$$=new Set,K2=new Map,Xq=new Set;function dSe(e){return Xq.add(e),()=>Xq.delete(e)}r(dSe,"onAdapterChange");function uSe(){for(const e of Xq)e()}r(uSe,"notifyAdapterChange");Gnt(uSe);function trt(){for(const e of[Bet,Zet,btt,Ntt,Htt,ist,bst,_st,Ost,Gst,bnt,unt,$tt,Mnt,A5,Wnt])Jq.add(e.type),cSe.set(e.type,e),jv(e)}r(trt,"registerBuiltInUIAdapters");function jv(e){const s=xE.findIndex(n=>n.type===e.type);s>=0?xE.splice(s,1,e):xE.push(e),i4.set(e.type,e),uSe()}r(jv,"registerUIAdapter");function mSe(e){return i4.get(e)??null}r(mSe,"findUIAdapter");trt();function aS(e){const s=i4.get(e);if(!s){let n=!1;return{type:e,label:e,parseStdoutLine:r((a,i)=>(n||(n=!0,Qq(e).then(o=>{o&&jv({type:e,label:e,parseStdoutLine:o.parseStdoutLine,createStdoutParser:o.createStdoutParser,ConfigFields:yy,buildAdapterConfig:aN})})),A5.parseStdoutLine(a,i)),"parseStdoutLine"),ConfigFields:yy,buildAdapterConfig:aN}}return s}r(aS,"getUIAdapter");function srt(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 Jq){const i=cSe.get(a);if(!i)continue;const o=n.has(a),l=s.has(a),c=$$.has(a);if(o&&l&&!c){$$.add(a);const d=(K2.get(a)??0)+1;K2.set(a,d);let u=!1;const h=i.parseStdoutLine,p=e.find(f=>f.type===a)?.label??a;jv({type:a,label:p,parseStdoutLine:r((f,x)=>(u||(u=!0,Qq(a).then(b=>{b&&K2.get(a)===d&&jv({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&&($$.delete(a),K2.delete(a),Yq(a),jv(i))}for(const{type:a,label:i}of e){if(Jq.has(a))continue;const o=i4.get(a);if(o&&o!==A5)continue;let l=!1;const c=o?.parseStdoutLine??A5.parseStdoutLine;jv({type:a,label:i,parseStdoutLine:r((d,u)=>(l||(l=!0,Qq(a).then(h=>{h&&jv({type:a,label:i,parseStdoutLine:h.parseStdoutLine,createStdoutParser:h.createStdoutParser,ConfigFields:o?.ConfigFields??yy,buildAdapterConfig:o?.buildAdapterConfig??aN})})),c(d,u)),"parseStdoutLine"),ConfigFields:o?.ConfigFields??yy,buildAdapterConfig:o?.buildAdapterConfig??aN})}}r(srt,"syncExternalAdapters");function IW(){return[...xE]}r(IW,"listUIAdapters");function Zq(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(Zq,"resolveStdoutParser");function hSe(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(hSe,"appendTranscriptEntry");function nrt(e,s){for(const n of s)hSe(e,n)}r(nrt,"appendTranscriptEntries");function rrt(e,s=160){return e.length<=s?e:`${e.slice(0,s-3)}...`}r(rrt,"truncateTranscriptLine");function art(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(art,"formatTranscriptParserError");function irt(e,s,n,a){const i=art(n)||"unknown parser error",o=rrt(e);return{kind:"result",ts:s,text:bm(`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(irt,"createTranscriptParseErrorEntry");function AW(e){const{entries:s,line:n,ts:a,parseLine:i,reset:o,redactionOptions:l}=e;try{nrt(s,i(n,a).map(c=>aZe(c,l)))}catch(c){o?.(),hSe(s,irt(n,a,c,l))}}r(AW,"appendParsedTranscriptLine");function pSe(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:bm(u.chunk,l)});continue}if(u.stream==="system"){s.push({kind:"system",ts:u.ts,text:bm(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&&AW({entries:s,line:f,ts:u.ts,parseLine:i,reset:o,redactionOptions:l})}}return c}r(pSe,"foldTranscriptChunks");function fSe(e,s,n){const a=[],i={enabled:n?.censorUsernameInLogs??!1},{parseLine:o,reset:l}=Zq(s),c=pSe({entries:a,chunks:e,from:0,stdoutBuffer:"",parseLine:o,reset:l,redactionOptions:i}).trim();return c&&AW({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(fSe,"buildTranscript");var Tte=[];function ort(e,s){const n={enabled:s?.censorUsernameInLogs??!1},a=typeof e!="function"&&typeof e.createStdoutParser=="function";let i=Zq(e),o=[],l="",c=Tte,d=[];const u=r(()=>{i=Zq(e),o=[],l="",c=Tte},"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 fSe(f,e,s);const b=o.slice(),v=b.length-1;return v>=0&&(b[v]={...b[v]}),x&&AW({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=pSe({entries:o,chunks:f,from:c.length,stdoutBuffer:l,parseLine:i.parseLine,reset:i.reset,redactionOptions:n}),c=f,d=p(f)),d}}}r(ort,"createIncrementalTranscript");function lrt({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)(gr,{open:c,onOpenChange:d,children:[(0,t.jsx)(Sr,{asChild:!0,children:(0,t.jsx)("button",{type:"button",className:W("inline-flex max-w-full min-w-0 items-center gap-1.5 overflow-hidden rounded-md border border-border px-2 py-1 text-xs hover:bg-accent/50 transition-colors",f&&"border-amber-600/45 bg-amber-500/5",a&&"opacity-60 cursor-not-allowed"),disabled:a,children:x?(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)(Qc,{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)(kr,{agent:p,size:16,className:"h-3 w-3 shrink-0 text-muted-foreground"}),(0,t.jsx)("span",{className:W("min-w-0 truncate",f&&"text-amber-900 dark:text-amber-200"),children:`Reports to ${p.name}${f?" (terminated)":""}`})]}):(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)(Qc,{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)(dr,{className:"w-48 p-1",align:"start",children:[(0,t.jsx)("button",{type:"button",className:W("flex items-center gap-2 w-full px-2 py-1.5 text-xs rounded hover:bg-accent/50",s===null&&"bg-accent"),onClick:r(()=>{n(null),d(!1)},"onClick"),children:"No manager"}),f&&(0,t.jsxs)("div",{className:"flex min-w-0 items-center gap-2 overflow-hidden px-2 py-1.5 text-xs text-muted-foreground border-b border-border mb-0.5",children:[(0,t.jsx)(kr,{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:W("flex items-center gap-2 w-full min-w-0 px-2 py-1.5 text-xs rounded hover:bg-accent/50 overflow-hidden",b.id===s&&"bg-accent"),onClick:r(()=>{n(b.id),d(!1)},"onClick"),children:[(0,t.jsx)(kr,{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:kW[b.role]??b.role})]},b.id))]})]})}r(lrt,"ReportsToPicker");var crt="__secret_folder__:";function drt(e){return!e||e==="active"?null:(0,t.jsx)(ct,{variant:"outline",className:"ml-auto text-(length:--text-nano) font-normal text-muted-foreground",children:e})}r(drt,"statusBadge");function xSe(e){return e.split("/").filter(s=>s.length>0)}r(xSe,"splitSecretPath$1");function gE(e){return e.join("/")}r(gE,"pathKey$1");function eC(e){return e.length>0?`/${e.join("/")}`:"/"}r(eC,"pathLabel");function urt(e,s){return e.length<s.length?!1:s.every((n,a)=>e[a]===n)}r(urt,"pathStartsWith");function Rte(e){return`${crt}${gE(e)}`}r(Rte,"folderValue");function mrt(e,s,n){const a=s.length,i=new Map,o=[];for(const c of e){const d=xSe(c.name);if(urt(d,s)){if(d.length>a+1){const u=d.slice(0,a+1),h=gE(u);if(!i.has(h)){const p=u[u.length-1]??"/",f=eC(u);i.set(h,{key:`folder-${h||"root"}`,value:Rte(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-${gE(s)}`,value:Rte(c),label:"Up one folder",title:eC(c),searchText:eC(c),kind:"back",folderPath:gE(c),pathHint:eC(c)})}return l.push(...i.values(),...o),{id:"browse-secrets",label:s.length>0?eC(s):"Browse secrets",options:l}}r(mrt,"buildFolderGroup");function TW({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=>xSe(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||MFe(j))return N;const w=mrt(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)(Ky,{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:W("h-(--sz-34px) min-h-(--sz-34px) font-mono text-sm",p&&"border-destructive text-destructive",h&&h.status!=="active"&&"border-amber-500/60",l),renderValue:r(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:W("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"?Yze:Jl;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:W("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:W("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:W("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]}),drt(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)(yn,{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(TW,"SecretPicker");var hrt=/^[a-z][a-z0-9_]*$/,Ete="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 gSe({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?hrt.test(w)?a?.some(T=>T.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 I(){if(N(!0),!!C){x(!0),v(null);try{await o(w,d)}catch(T){v(T instanceof Error?T.message:"Failed to create secret"),x(!1)}}}r(I,"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)($Fe,{className:"text-sm font-medium",children:e==="create"?"Create secret":"Store value as secret"}),e==="store"?(0,t.jsxs)(OFe,{className:"text-(length:--text-micro) text-muted-foreground",children:["Moves the typed value into an encrypted organization secret and binds"," ",(0,t.jsx)("span",{className:"font-mono",children:s||"this variable"})," to it."]}):null]}),(0,t.jsxs)("label",{className:"block space-y-1",children:[(0,t.jsx)("span",{className:"text-(length:--text-micro) font-medium text-muted-foreground",children:"Name"}),(0,t.jsx)("input",{className:W(Ete,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(T=>c(T.target.value),"onChange"),onBlur:r(()=>N(!0),"onBlur"),onKeyDown:r(T=>{T.key==="Enter"&&(T.preventDefault(),I())},"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:W(Ete,"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"?T=>u(T.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(T=>!T),"onClick"),children:h?(0,t.jsx)(Mm,{className:"h-3.5 w-3.5"}):(0,t.jsx)(Pd,{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)(L,{type:"button",variant:"ghost",size:"sm",onClick:i,disabled:f,children:"Cancel"}),(0,t.jsxs)(L,{type:"button",size:"sm",onClick:r(()=>{I()},"onClick"),disabled:!C,children:[f?(0,t.jsx)(rt,{className:"h-3.5 w-3.5 animate-spin"}):null,R]})]})]})}r(gSe,"SecretPopoverForm");function bSe(e){return(0,t.jsx)(gSe,{mode:"create",...e})}r(bSe,"CreateSecretPopover");function prt(e){return(0,t.jsx)(gSe,{mode:"store",...e})}r(prt,"ConvertToSecretPopover");var frt=/(api[-_]?key|access[-_]?token|auth(?:_?token)?|authorization|bearer|secret|passwd|password|credential|jwt|private[-_]?key|cookie|connectionstring)/i,xrt=[/^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 grt(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(grt,"looksHighEntropy");function brt(e,s){return s?frt.test(e)||xrt.some(n=>n.test(s))?!0:grt(s):!1}r(brt,"isSensitiveEnv");var Pte=0;function vrt(){return Pte+=1,`env-row-${Pte}`}r(vrt,"nextRowId");function Fx(e="text"){return{id:vrt(),name:"",source:e,textValue:"",secretId:"",userSecretKey:"",required:!0,version:"latest"}}r(Fx,"emptyRow");function yrt(e){return typeof e=="object"&&e!==null&&"type"in e&&e.type==="secret_ref"}r(yrt,"isSecretRef");function jrt(e){return typeof e=="object"&&e!==null&&"type"in e&&e.type==="plain"}r(jrt,"isPlainObj");function wrt(e){return typeof e=="object"&&e!==null&&"type"in e&&e.type==="user_secret_ref"}r(wrt,"isUserSecretRef");function O$(e){return!e||typeof e!="object"?[]:Object.entries(e).map(([s,n])=>{if(typeof n=="string")return{...Fx(),name:s,textValue:n};if(yrt(n)){const a=typeof n.version=="number"?n.version:"latest";return{...Fx(),name:s,source:"secret",secretId:typeof n.secretId=="string"?n.secretId:"",version:a}}if(wrt(n)){const a=typeof n.version=="number"?n.version:"latest";return{...Fx(),name:s,source:"user_secret",userSecretKey:typeof n.key=="string"?n.key:"",required:n.required!==!1,version:a}}return jrt(n)?{...Fx(),name:s,source:"text",textValue:typeof n.value=="string"?n.value:""}:{...Fx(),name:s}})}r(O$,"rowsFromValue");function bE(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(bE,"valueFromRows");var Mte="CLAUDE_CODE_OAUTH_TOKEN";function Vw(){return bE([{...Fx("user_secret"),name:"CLAUDE_CODE_OAUTH_TOKEN",userSecretKey:"CLAUDE_CODE_OAUTH_TOKEN",required:!0,version:"latest"}])??{}}r(Vw,"buildFixedClaudeOAuthBinding");var krt=/^[A-Za-z_][A-Za-z0-9_]*$/;function Nrt(e,s,n){const a=e.trim();if(!a)return null;if(!krt.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(Nrt,"validateName");function Srt(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(Srt,"computeDuplicateNames");function Crt(e,s){return s===e.source?{kind:"noop"}:s==="secret"?e.textValue.trim()?{kind:"open-store",name:R5(e.name)||"secret",value:e.textValue}:{kind:"to-secret"}:{kind:"to-text",undoFrom:e.secretId?{...e}:null}}r(Crt,"planSourceSwitch");function vSe(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(vSe,"computeRowHealth");function ySe(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(ySe,"computeUserSecretRowHealth");function R5(e){return e.trim().toLowerCase().replace(/[^a-z0-9_]+/g,"_").replace(/^_+|_+$/g,"").slice(0,64)}r(R5,"secretNameFromKey");function P1(e){return e.trim().toUpperCase().replace(/[^A-Z0-9_]+/g,"_").replace(/^_+|_+$/g,"").slice(0,64)}r(P1,"envKeyFromSecretName");var _rt="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",Dte="min-w-0 flex-1 bg-transparent px-2 py-1.5 text-sm font-mono outline-none placeholder:text-muted-foreground/40";function Irt({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,I]=(0,m.useState)(null),[R,T]=(0,m.useState)(!1),[A,D]=(0,m.useState)(null),M=vSe(e,n)??ySe(e,a),B=e.source==="secret"?n.find(X=>X.id===e.secretId)??null:null,E=(a?.length??0)>0,z=e.source==="text"&&!e.sensitiveDismissed&&brt(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(!A)return;const X=window.setTimeout(()=>D(null),5e3);return()=>window.clearTimeout(X)},[A]);function $(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 re=Crt(e,X);switch(re.kind){case"noop":return;case"open-store":{const{name:oe,value:G}=re;window.setTimeout(()=>I({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":re.undoFrom&&D(re.undoFrom),u({source:"text",secretId:"",userSecretKey:"",required:!0,version:"latest"}),window.setTimeout(()=>k.current?.focus(),0);return}}r($,"switchSource");async function q(X,re){const oe=await b(X,re);u({source:"secret",secretId:oe.id,userSecretKey:"",required:!0,version:"latest",textValue:""}),v(`Secret ${oe.name} created`),I(null)}r(q,"submitSecretPopover");function U(){const X=R5(e.name)||"secret",{textValue:re}=e;window.setTimeout(()=>I({mode:"store",name:X,value:re}),0)}r(U,"openStoreAsSecret");const O=e.source==="text"?"Text value":e.source==="secret"?"Organization secret reference":"User secret reference",K=`${e.id}-name-error`,H=`${e.id}-health`,ee=d.name||d.value,se=B?Math.max(0,B.latestVersion):0,ne=e.version==="latest"?"latest":`v${e.version}`,fe=e.version!=="latest";return(0,t.jsxs)("div",{className:W("group/row grid grid-cols-(--gtc-13) items-start gap-x-1.5 gap-y-1 rounded-md px-1 py-1","@[40rem]/env:grid-cols-(--gtc-14) @[40rem]/env:items-center",ee&&"bg-amber-500/[0.06] ring-1 ring-amber-500/20"),children:[(0,t.jsx)("div",{className:"col-start-1 row-start-1 min-w-0 @[40rem]/env:row-start-1 @[40rem]/env:self-start",children:(0,t.jsx)("input",{ref:w,className:W(_rt,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)(gr,{open:C!==null,onOpenChange:r(X=>{X||I(null)},"onOpenChange"),children:[(0,t.jsx)(Sz,{asChild:!0,children:(0,t.jsxs)("div",{ref:S,className:W("relative flex items-stretch overflow-hidden rounded-md border border-border bg-transparent focus-within:ring-2 focus-within:ring-ring/40",d.value&&"border-amber-500/70 bg-amber-500/10 focus-within:ring-amber-500/40",o&&"opacity-60"),children:[(0,t.jsxs)(Xr,{children:[(0,t.jsxs)(zn,{children:[(0,t.jsx)(qn,{asChild:!0,children:(0,t.jsx)(Jr,{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)(Rqe,{className:"size-3.5"}):e.source==="secret"?(0,t.jsx)(Si,{className:"size-3.5"}):(0,t.jsx)(Ph,{className:"size-3.5"}),(0,t.jsx)(nn,{className:"size-3 opacity-60"})]})})}),(0,t.jsx)(Un,{side:"top",children:O})]}),(0,t.jsxs)(Zr,{align:"start",className:"w-56",children:[(0,t.jsxs)(ls,{className:"flex-col items-start gap-0.5",onSelect:r(()=>$("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)(ls,{className:"flex-col items-start gap-0.5",onSelect:r(()=>$("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)(ls,{className:"flex-col items-start gap-0.5",onSelect:r(()=>$("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:Dte,placeholder:"value",value:e.textValue,type:z?"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")}),z?(0,t.jsxs)("div",{className:"flex shrink-0 items-stretch border-l border-border",children:[(0,t.jsxs)("button",{type:"button",onClick:U,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)(bc,{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)(Fn,{className:"size-3"})})]}):null]}):e.source==="secret"?(0,t.jsxs)("div",{className:"relative min-w-0 flex-1",children:[(0,t.jsx)(TW,{secretId:e.secretId,secrets:n,recentlyUsedSecrets:i,disabled:o,onSelect:r(X=>u({secretId:X,version:"latest"}),"onSelect"),onCreateNew:r(X=>I({mode:"create",name:R5(X)||X.trim(),value:""}),"onCreateNew"),triggerClassName:W("rounded-none border-0 bg-transparent shadow-none focus-visible:ring-0",B&&B.status==="active"&&"pr-24 has-[>svg]:!pr-24")}),B&&B.status==="active"?(0,t.jsxs)(gr,{open:R,onOpenChange:T,children:[(0,t.jsx)(Sz,{asChild:!0,children:(0,t.jsx)("button",{type:"button",disabled:o,onClick:r(X=>{X.preventDefault(),X.stopPropagation(),T(re=>!re)},"onClick"),"aria-label":"Version",className:W("absolute right-8 top-1/2 z-10 -translate-y-1/2 rounded px-1.5 py-0.5 text-(length:--text-nano) font-medium",fe?"bg-amber-500/15 text-amber-700 dark:text-amber-400":"text-muted-foreground hover:bg-accent"),children:ne})}),(0,t.jsxs)(dr,{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"}),T(!1)},"onClick"),className:W("flex w-full items-center justify-between rounded px-2 py-1.5 text-sm hover:bg-accent",e.version==="latest"&&"font-medium"),children:["latest ",(0,t.jsx)("span",{className:"text-(length:--text-micro) text-muted-foreground",children:"(recommended)"})]}),Array.from({length:se},(X,re)=>se-re).filter(X=>X>0).map(X=>(0,t.jsxs)("button",{type:"button",role:"radio","aria-checked":e.version===X,onClick:r(()=>{u({version:X}),T(!1)},"onClick"),className:W("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:[E?(0,t.jsxs)("select",{"aria-label":"User secret",value:e.userSecretKey,disabled:o,onChange:r(X=>{const re=X.target.value,oe=a?.find(G=>G.key===re);u({userSecretKey:re,...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:Dte,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)(dr,{align:"start",className:"w-auto p-3",onInteractOutside:r(X=>{const re=X.detail.originalEvent.target;re&&S.current?.contains(re)&&X.preventDefault()},"onInteractOutside"),children:C?.mode==="store"?(0,t.jsx)(prt,{initialName:C.name,initialValue:C.value,existingSecretNames:n.map(X=>X.name),onCancel:r(()=>I(null),"onCancel"),onSubmit:q}):C?.mode==="create"?(0,t.jsx)(bSe,{initialName:C.name,initialValue:C.value,existingSecretNames:n.map(X=>X.name),onCancel:r(()=>I(null),"onCancel"),onSubmit:q}):null})]}),M?(0,t.jsx)("p",{id:H,role:"status",className:W("mt-0.5 text-(length:--text-micro)",M.level==="error"?"text-destructive":"text-amber-600 dark:text-amber-400"),children:M.message}):null,A?(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:A.secretId,version:A.version,textValue:""}),D(null)},"onClick"),children:"Undo"})]}):null]}),c&&l?(0,t.jsx)("p",{id:K,className:W("col-span-2 col-start-1 row-start-3 min-w-0 text-(length:--text-micro) @[40rem]/env:col-span-2 @[40rem]/env:row-start-2",l.level==="error"?"text-destructive":"text-amber-600 dark:text-amber-400"),children:l.message}):null,(0,t.jsxs)("div",{className:"col-start-2 row-start-1 flex items-center justify-end gap-0.5 self-start @[40rem]/env:col-start-3 @[40rem]/env:self-center",children:[e.source==="text"&&!z&&(e.name.trim()||e.textValue)?(0,t.jsxs)(Xr,{children:[(0,t.jsx)(Jr,{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)(Ri,{className:"size-4"})})}),(0,t.jsx)(Zr,{align:"end",children:(0,t.jsx)(ls,{onSelect:r(()=>{window.setTimeout(U,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)(Fn,{className:"size-4"})})]})]})}r(Irt,"EnvironmentVariableRow");var Art=/^\s*(?:export\s+)?([A-Za-z_][A-Za-z0-9_]*)\s*=(.*)$/;function Trt(e){const s=e.indexOf(" #");return s>=0?e.slice(0,s):e}r(Trt,"stripInlineComment");function Rrt(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 Trt(s).trim()}r(Rrt,"unquote");function Ert(e){const s=[];for(const n of e.split(/\r?\n/)){const a=n.trim();if(!a||a.startsWith("#"))continue;const i=Art.exec(a);if(!i)continue;const o=i[1],l=Rrt(i[2]);s.push({key:o,value:l})}return s}r(Ert,"parseDotenv");var Prt=["PAPERCLIP_"],Mrt="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 e6(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(e6,"normalizedEnvEntries");function tC(e){return JSON.stringify(e6(e))}r(tC,"normalizedEnvKey");var F$=3;function B$(e){const s=e.slice(0,F$).join(", ");return e.length>F$?`${s} +${e.length-F$} more`:s}r(B$,"formatChangedNames");function Lte(e){return e.map(s=>({...s}))}r(Lte,"cloneRows");function Drt(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(Drt,"rowDirtyFields");var jy=(0,m.forwardRef)(r(function({value:s,onChange:n,secrets:a,userSecretDefinitions:i,onCreateSecret:o,recentlyUsedSecrets:l,disabled:c,reservedPrefixes:d=Prt,footerHint:u,onDirtyChange:h,hideDraftActions:p=!1},f){const x=Xc(),b=(0,m.useRef)(null),[v,j]=(0,m.useState)(()=>O$(s)),N=(0,m.useRef)(v),[w,k]=(0,m.useState)(()=>Lte(v)),S=(0,m.useMemo)(()=>tC(s),[]),C=(0,m.useRef)(S),I=(0,m.useRef)(S),R=(0,m.useRef)(null),[T,A]=(0,m.useState)(S),[D,M]=(0,m.useState)(()=>new Set(O$(s).map(ie=>ie.name.trim()).filter(Boolean))),[B,E]=(0,m.useState)(null);(0,m.useEffect)(()=>{N.current=v},[v]);function z(ie,ue=N.current){C.current=ie,A(ie),k(Lte(ue))}r(z,"markCommitted");function $(ie){M(ue=>{const ke=new Set(ue);for(const be of ie){const Ie=be.name.trim();Ie&&ke.add(Ie)}return ke})}r($,"touchCommittedNames");function q(ie){const ue=O$(ie);return j(ue),$(ue),ue}r(q,"adoptExternalValue"),(0,m.useEffect)(()=>{const ie=tC(s);if(ie===I.current)return;I.current=ie;const ue=tC(bE(N.current)),ke=ue!==C.current,be=R.current===ie;if(be&&(R.current=null),!ke){z(ie,q(s));return}(be||ue===ie)&&($(N.current),z(ie))},[s]);const U=(0,m.useMemo)(()=>bE(v),[v]),O=(0,m.useMemo)(()=>tC(U),[U]),K=O!==T;(0,m.useEffect)(()=>{h?.(!c&&K)},[c,K,h]);const H=(0,m.useMemo)(()=>{const ie=new Map(e6(bE(w)).map(([Ie,Ue])=>[Ie,JSON.stringify(Ue)])),ue=new Map(e6(U).map(([Ie,Ue])=>[Ie,JSON.stringify(Ue)])),ke=[],be=[];for(const[Ie,Ue]of ue)ie.has(Ie)?ie.get(Ie)!==Ue&&be.push(Ie):ke.push(Ie);return{added:ke,changed:be,removed:[...ie.keys()].filter(Ie=>!ue.has(Ie))}},[w,U]),ee=(0,m.useMemo)(()=>{const ie=[];return H.added.length>0&&ie.push(`New: ${B$(H.added)}`),H.changed.length>0&&ie.push(`Edited: ${B$(H.changed)}`),H.removed.length>0&&ie.push(`Removed: ${B$(H.removed)}`),ie.join(" · ")},[H]);(0,m.useEffect)(()=>{if(c||!K)return;function ie(ue){ue.preventDefault(),ue.returnValue=""}return r(ie,"handleBeforeUnload"),window.addEventListener("beforeunload",ie),()=>window.removeEventListener("beforeunload",ie)},[c,K]);const se=(0,m.useCallback)(()=>c||!K?null:(R.current=O,(0,hp.flushSync)(()=>{n(U)}),U??{}),[c,U,O,K,n]);(0,m.useImperativeHandle)(f,()=>({flushPendingDraft:se}),[se]),(0,m.useEffect)(()=>{const ie=b.current?.closest("form");if(!ie)return;function ue(){se()}return r(ue,"handleSubmit"),ie.addEventListener("submit",ue,!0),()=>ie.removeEventListener("submit",ue,!0)},[se]),(0,m.useEffect)(()=>{const ie=b.current;if(!ie)return;const ue=ie;function ke(be){const Ie=be.target;if(!(Ie instanceof Element)||ue.contains(Ie))return;const Ue=Ie.closest("button");if(!Ue||Ue.disabled)return;const at=`${Ue.getAttribute("aria-label")??""} ${Ue.textContent??""}`;(Ue.type==="submit"||/\b(save|create|update|test|import)\b/i.test(at))&&se()}return r(ke,"handleDocumentClick"),document.addEventListener("click",ke,!0),()=>document.removeEventListener("click",ke,!0)},[se]);function ne(ie){j(ie)}r(ne,"updateDraft");function fe(ie,ue){ne(v.map(ke=>ke.id===ie?{...ke,...ue}:ke))}r(fe,"patchRow");function X(ie){ne(v.filter(ue=>ue.id!==ie))}r(X,"removeRow");function re(){const ie=Fx();j([...v,ie]),E({rowId:ie.id,field:"name"})}r(re,"addRow");function oe(ie){const ue=v.find(ke=>ke.id===ie)?.name.trim();ue&&M(ke=>{if(ke.has(ue))return ke;const be=new Set(ke);return be.add(ue),be})}r(oe,"markTouched");function G(ie,ue){const ke=Ert(ie);if(ke.length===0)return!1;const be=v.filter(Ie=>Ie.id!==ue).map(Ie=>({...Ie}));for(const{key:Ie,value:Ue}of ke){const at=be.find(dt=>dt.name.trim()===Ie);at?(at.name=Ie,at.source="text",at.textValue=Ue,at.secretId="",at.sensitiveDismissed=!1,at.userSecretKey="",at.required=!0):be.push({...Fx(),name:Ie,textValue:Ue})}return ne(be),x?.pushToast({title:`Imported ${ke.length} variable${ke.length===1?"":"s"}`,tone:"success"}),!0}r(G,"bulkImport");function Y(ie){const ue=v.map(Ie=>({...Ie})),ke=ue[ue.length-1];let be;ke&&!ke.name&&!ke.textValue&&!ke.secretId&&!ke.userSecretKey?be=ke:(be=Fx(),ue.push(be)),be.source="secret",be.secretId=ie.id,be.version="latest",be.name||(be.name=P1(ie.name)),ne(ue)}r(Y,"bindRecentSecret");function Q(){K&&(R.current=O,n(U))}r(Q,"saveDraft");function te(){R.current=null,I.current=tC(s);const ie=q(s);z(I.current,ie)}r(te,"revertDraft");const ae=(0,m.useMemo)(()=>Srt(v),[v]),le=(0,m.useMemo)(()=>v.reduce((ie,ue)=>vSe(ue,a)||ySe(ue,i)?ie+1:ie,0),[v,a,i]),he=(0,m.useMemo)(()=>{const ie=new Set(v.filter(ue=>ue.source==="secret"&&ue.secretId).map(ue=>ue.secretId));return(l??[]).filter(ue=>ue.status==="active"&&!ie.has(ue.id)).slice(0,8)},[l,v]),ce=v.length>0,ge=u===void 0?Mrt:u,me=(0,m.useMemo)(()=>new Map(w.map(ie=>[ie.id,ie])),[w]);return(0,t.jsx)(Md,{children:(0,t.jsxs)("div",{ref:b,className:"@container/env space-y-2",children:[le>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)(Zi,{className:"size-3.5"}),le," bindings need attention"]}):null,ce?(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((ie,ue)=>{const ke=Nrt(ie.name,ae,d),be=D.has(ie.name.trim());return(0,t.jsx)(Irt,{row:ie,isLast:ue===v.length-1,secrets:a,userSecretDefinitions:i,recentlyUsedSecrets:l,disabled:c,nameIssue:ke,showNameIssue:be,dirtyFields:Drt(ie,me.get(ie.id)),onPatch:r(Ie=>fe(ie.id,Ie),"onPatch"),onRemove:r(()=>X(ie.id),"onRemove"),onNameBlur:r(()=>oe(ie.id),"onNameBlur"),onNamePaste:r(Ie=>G(Ie,ie.id),"onNamePaste"),onEnterInValueLast:re,onCreateSecret:o,onToast:r(Ie=>x?.pushToast({title:Ie,tone:"success"}),"onToast"),focusRequest:B?.rowId===ie.id?B.field:null,onFocusConsumed:r(()=>E(null),"onFocusConsumed")},ie.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:re,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)(yn,{className:"size-3.5"}),"Add variable"]}),he.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:"]}),he.map(ie=>(0,t.jsxs)("button",{type:"button",onClick:r(()=>Y(ie),"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 ${ie.name}`,children:["+ ",ie.name]},ie.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"})]}),ee?(0,t.jsx)("p",{className:"min-w-0 truncate pl-4 text-xs text-amber-950/80 dark:text-amber-100/80",title:ee,children:ee}):null]}),(0,t.jsxs)("div",{className:"flex items-center gap-2",children:[(0,t.jsxs)("button",{type:"button",onClick:te,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)(Ci,{className:"size-4"}),"Revert"]}),(0,t.jsxs)("button",{type:"button",onClick:Q,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)(Sf,{className:"size-4"}),"Save"]})]})]}):null,ge?(0,t.jsx)("p",{className:"text-(length:--text-micro) text-muted-foreground/70",children:ge}):null,v.some(ie=>ie.source==="user_secret"&&ie.userSecretKey)?(0,t.jsxs)("p",{className:"inline-flex items-start gap-1 text-(length:--text-micro) text-muted-foreground/70",children:[(0,t.jsx)(Ph,{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")),Lrt="env.",mA="access.",t6=/^[A-Za-z_][A-Za-z0-9_]*$/;function jSe(e){return e?e.startsWith("access.")?"api":e.startsWith("env.")?"env":"config":"config"}r(jSe,"deliveryModeForConfigPath");function wSe(e){switch(e){case"env":return"Env var";case"api":return"API access";default:return"Config"}}r(wSe,"deliveryModeLabel");function $rt(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($rt,"deliveryModeDescription");function kSe(e){return e?e.startsWith("access.")?e.slice(7):e.startsWith("env.")?e.slice(4):e:""}r(kSe,"aliasFromConfigPath");function Ort(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(Ort,"consumerTypeLabel");var Frt={numeric:!0,sensitivity:"base"};function HC(e){return e.kind==="company"?e.secret.name:e.definition.name}r(HC,"getSecretPathRowName");function cN(e){return e.split("/").filter(s=>s.length>0)}r(cN,"splitSecretPath");function z$(e){return cN(e).join("/")}r(z$,"normalizeSecretPath");function $te(e,s){return s.every((n,a)=>e[a]===n)}r($te,"startsWithSegments");function Ote(e,s){return e.localeCompare(s,void 0,Frt)}r(Ote,"compareNames");function Brt(e,s){const n=cN(s),a=e.map(c=>({row:c,name:HC(c),segments:cN(HC(c))})),i=new Set,o=[];for(const c of a){if(!$te(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(!$te(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)=>Ote(c.name,d.name)),o.sort((c,d)=>Ote(HC(c),HC(d))),{folders:l,secrets:o}}r(Brt,"buildSecretPathListing");function zrt(e){const s=cN(e);return s.map((n,a)=>({name:n,path:s.slice(0,a+1).join("/")}))}r(zrt,"buildSecretPathBreadcrumbs");function qrt(e){return e.trim()?e.includes("/")?"Folder name cannot contain slashes.":null:"Folder name is required."}r(qrt,"validateSecretFolderSegment");function $_({name:e,basePath:s="",className:n,leafClassName:a}){const i=cN(e),o=cN(s),l=o.length>0&&o.every((h,p)=>i[p]===h)&&i.length>o.length?i.slice(o.length):i,c=l.length>0?l:[e],d=c[c.length-1],u=c.slice(0,-1).join("/");return(0,t.jsxs)("span",{className:W("min-w-0 truncate",n),children:[u?(0,t.jsxs)("span",{className:"text-muted-foreground",children:[u,"/"]}):null,(0,t.jsx)("span",{className:W("font-medium text-foreground",a),children:d})]})}r($_,"SecretPathName");function Urt(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(Urt,"fingerprintLabel");function NSe({fingerprint:e,length:s,className:n}){const{pushToast:a}=da(),i=Urt(e,s);if(!e)return(0,t.jsxs)("span",{className:W("inline-flex items-center gap-1 font-mono",n),children:[(0,t.jsx)(Lz,{className:"size-3 shrink-0"}),i]});const o=`sha256:${e}`;return(0,t.jsxs)("button",{type:"button",onClick:r(()=>{fa(o).then(()=>a({title:"Fingerprint copied",tone:"success"})).catch(()=>a({title:"Couldn’t copy fingerprint",tone:"error"}))},"onClick"),title:`Copy full digest — ${o}`,className:W("inline-flex items-center gap-1 font-mono hover:text-foreground",n),children:[(0,t.jsx)(Lz,{className:"size-3 shrink-0"}),i,(0,t.jsx)(Ir,{className:"size-3 shrink-0 opacity-60"})]})}r(NSe,"FingerprintChip");function RW({justification:e,className:s}){return(0,t.jsxs)("div",{className:W("space-y-0.5",s),children:[(0,t.jsx)("p",{className:"text-(length:--text-micro) text-muted-foreground",children:"Reason given by the agent"}),(0,t.jsxs)("p",{className:"whitespace-pre-wrap break-words text-xs text-foreground/80",children:["“",e,"”"]})]})}r(RW,"ProposalJustification");function O_({agent:e,className:s}){return(0,t.jsxs)("span",{className:W("inline-flex min-w-0 items-center gap-1",s),children:[(0,t.jsx)(kr,{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(O_,"AgentRefChip");function EW({configPath:e}){const s=jSe(e),n=s==="env",a=s==="api";return(0,t.jsxs)(ct,{variant:"outline",className:W("h-5 gap-1 px-1.5 text-(length:--text-nano) font-normal",n&&"border-sky-500/30 bg-sky-500/10 text-sky-700 dark:text-sky-300",a&&"border-violet-500/30 bg-violet-500/10 text-violet-700 dark:text-violet-300",!n&&!a&&"border-border bg-muted/40 text-muted-foreground"),children:[n?(0,t.jsx)(Bve,{className:"size-3"}):a?(0,t.jsx)(_M,{className:"size-3"}):null,wSe(s)]})}r(EW,"DeliveryBadge$1");function PW({className:e}){return(0,t.jsxs)(ct,{variant:"outline",className:W("h-5 gap-1 px-1.5 text-(length:--text-nano) font-medium","border-amber-500/40 bg-amber-500/10 text-amber-700 dark:text-amber-300",e),children:[(0,t.jsx)(bc,{className:"size-3"})," Proposed"]})}r(PW,"ProposedBadge");function o4(e){return kSe(e.configPath)}r(o4,"bindingEnvKey");function MW(e){return e.secretProposalId?{name:e.secretProposalName??"proposed secret",pending:!0}:{name:e.secretName??"secret",pending:!1}}r(MW,"bindingSecretLabel");function Fte(e){return e instanceof dn?e.message||`Request failed: ${e.status}`:e instanceof Error?e.message:"Something went wrong. Try again."}r(Fte,"readableError");function SSe(e,s=[]){const n=Dt(),{pushToast:a}=da(),[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:P.secrets.list(e)}))},[e,n]),x=je({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 vr.approveProposal(e,k.id,{overrides:{name:S,description:w.description.trim()||null,providerConfigId:w.providerConfigId||null}})}return vr.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"} · ${o4(w)||"binding"}`,tone:"success"}),o(null),p(null),f()},"onSuccess"),onError:r(w=>p(Fte(w)),"onError")}),b=je({mutationFn:r(({proposal:w,reason:k})=>vr.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(Fte(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)(Krt,{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)(Vrt,{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(SSe,"useProposalReview");function Krt({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)(Qs,{open:!!e,onOpenChange:r(p=>!p&&o(),"onOpenChange"),children:(0,t.jsx)(Js,{className:"sm:max-w-lg",children:e?(0,t.jsxs)(t.Fragment,{children:[(0,t.jsxs)(hn,{children:[(0,t.jsx)(Xs,{children:c?"Approve & create secret":"Approve binding"}),(0,t.jsx)(jn,{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)(O_,{agent:e.proposal.proposedBy,className:"font-medium text-foreground"})]}),(0,t.jsx)(RW,{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)(Gs,{htmlFor:"approve-folder",children:"Folder"}),(0,t.jsx)(ht,{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)(Gs,{htmlFor:"approve-name",children:"Name"}),(0,t.jsx)(ht,{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)($_,{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)(Gs,{htmlFor:"approve-description",children:"Description"}),(0,t.jsx)(ht,{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)(Gs,{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)(NSe,{fingerprint:e.proposal.valueFingerprintSha256,length:e.proposal.valueLength})})]}):(0,t.jsx)(Wrt,{draft:e,onChange:i}),s?(0,t.jsx)("p",{className:"text-xs text-destructive",role:"alert",children:s}):null,(0,t.jsxs)(hr,{children:[(0,t.jsx)(L,{variant:"ghost",onClick:o,disabled:n,children:"Cancel"}),(0,t.jsx)(L,{onClick:l,disabled:n||!h,children:n?"Approving…":c?"Approve & create":e.cascade?"Approve secret & bind":"Approve binding"})]})]}):null})})}r(Krt,"ApproveDialog");function Wrt({draft:e,onChange:s}){const{proposal:n}=e,a=MW(n),i=o4(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)(O_,{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)(EW,{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)(PW,{}):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)(pi,{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(Wrt,"BindingApproveBody");function Vrt({proposal:e,reason:s,error:n,pending:a,onReasonChange:i,onCancel:o,onConfirm:l}){const c=s.trim().length>0;return(0,t.jsx)(Qs,{open:!!e,onOpenChange:r(d=>!d&&o(),"onOpenChange"),children:(0,t.jsx)(Js,{className:"sm:max-w-md",children:e?(0,t.jsxs)(t.Fragment,{children:[(0,t.jsxs)(hn,{children:[(0,t.jsx)(Xs,{children:"Reject proposal"}),(0,t.jsxs)(jn,{children:["The reason is sent back to"," ",(0,t.jsx)(O_,{agent:e.proposedBy,className:"text-foreground"}),". Dependent bindings are rejected too."]})]}),(0,t.jsxs)("div",{className:"space-y-1",children:[(0,t.jsx)(Gs,{htmlFor:"reject-reason",children:"Reason"}),(0,t.jsx)(Tn,{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)(hr,{children:[(0,t.jsx)(L,{variant:"ghost",onClick:o,disabled:a,children:"Cancel"}),(0,t.jsx)(L,{variant:"destructive",onClick:l,disabled:a||!c,children:a?"Rejecting…":"Reject"})]})]}):null})})}r(Vrt,"RejectDialog");function CSe({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)(L,{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)(Md,{children:(0,t.jsxs)(zn,{children:[(0,t.jsx)(qn,{asChild:!0,children:(0,t.jsx)("span",{tabIndex:0,children:c})}),(0,t.jsx)(Un,{className:"max-w-72",children:e.approveBlockReason??"You don’t have permission to approve this."})]})}):c,(0,t.jsx)(L,{size:"sm",variant:"outline",className:l,disabled:a,onClick:r(()=>n(e),"onClick"),children:"Reject"})]})}r(CSe,"ProposalActions");function _Se(e){return typeof e!="object"||e===null||Array.isArray(e)?null:e}r(_Se,"asRecord$16");function ISe(e){const s=_Se(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(ISe,"readSecretRef");function Hrt(e){const s=_Se(e?.env);if(!s)return[];const n=[];for(const[a,i]of Object.entries(s)){const o=ISe(i);o&&n.push({name:a,...o})}return n}r(Hrt,"parseEnvSecretRefs");function Grt(e){if(!e)return[];const s=[];for(const[n,a]of Object.entries(e)){if(!n.startsWith("access."))continue;const i=ISe(a);i&&s.push({name:n.slice(mA.length),...i})}return s}r(Grt,"parseAccessGrants");function Qrt(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(Qrt,"summarizeAgentBindings");var Bte=0;function ASe(){return Bte+=1,`access-row-${Bte}`}r(ASe,"nextAccessRowId");function q$(e){return e.map(s=>({id:ASe(),alias:s.name,secretId:s.secretId,version:s.version}))}r(q$,"entriesToRows");function zte(e){const s={};for(const n of e){const a=n.alias.trim();!a||!t6.test(a)||!n.secretId||(s[a]={type:"secret_ref",secretId:n.secretId,version:n.version})}return s}r(zte,"rowsToAccessMap");function qte(e){return JSON.stringify(Object.keys(e).sort().map(s=>{const n=e[s];return[s,n.secretId,n.version??"latest"]}))}r(qte,"normalizeAccessMapKey");function Ute({mode:e}){return e==="env"?(0,t.jsxs)(ct,{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)(Bve,{className:"size-3"})," Env var"]}):(0,t.jsxs)(ct,{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)(_M,{className:"size-3"})," API access"]})}r(Ute,"DeliveryBadge");function Yrt({config:e,secrets:s,onChange:n,onCreateSecret:a,disabled:i,proposals:o,onApproveProposal:l,onRejectProposal:c}){const d=(0,m.useMemo)(()=>(o??[]).filter(B=>B.kind==="binding"),[o]),u=(0,m.useMemo)(()=>Hrt(e),[e]),h=(0,m.useMemo)(()=>Grt(e),[e]),p=(0,m.useMemo)(()=>Qrt(u,h),[u,h]),f=(0,m.useMemo)(()=>zte(q$(h)),[h]),x=(0,m.useMemo)(()=>qte(f),[f]),[b,v]=(0,m.useState)(()=>q$(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(q$(h)))},[x,h]);const C=r(B=>s.find(E=>E.id===B)?.name??`${B.slice(0,8)}…`,"secretName");function I(B){v(B);const E=zte(B);k.current=qte(E),n(E)}r(I,"emit");function R(B,E){I(b.map(z=>z.id===B?{...z,...E}:z))}r(R,"patchRow");function T(B){I(b.filter(E=>E.id!==B))}r(T,"removeRow");function A(){v(B=>[...B,{id:ASe(),alias:"",secretId:"",version:"latest"}])}r(A,"addRow");const D=(0,m.useMemo)(()=>{const B=new Map;for(const E of b){const z=E.alias.trim();z&&B.set(z,(B.get(z)??0)+1)}return B},[b]),M=p.length>0;return(0,t.jsxs)("div",{className:"space-y-3",children:[M?(0,t.jsx)("div",{className:"space-y-1.5",children:p.map(B=>(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(B.secretId)}),B.envKeys.length>0?(0,t.jsx)(Ute,{mode:"env"}):null,B.apiAliases.length>0?(0,t.jsx)(Ute,{mode:"api"}):null,(0,t.jsx)("span",{className:"min-w-0 truncate font-mono text-(length:--text-micro) text-muted-foreground",children:[...B.envKeys.map(E=>`${Lrt}${E}`),...B.apiAliases.map(E=>`${mA}${E}`)].join(" · ")})]},B.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(B=>{const E=MW(B),z=o4(B);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)(EW,{configPath:B.configPath}),(0,t.jsx)("code",{className:"font-mono",children:z||B.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:E.name}),E.pending?(0,t.jsx)(PW,{}):null]}),(0,t.jsxs)("p",{className:"flex flex-wrap items-center gap-1 text-muted-foreground",children:[(0,t.jsxs)("span",{children:["proposed by ",B.proposedBy.name]}),(0,t.jsx)("span",{"aria-hidden":"true",children:"·"}),(0,t.jsxs)("span",{className:"truncate italic",children:["“",B.justification,"”"]})]})]}),(0,t.jsx)(CSe,{proposal:B,onApprove:l,onReject:c,disabled:i,size:"xs"})]},B.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(B=>{const E=B.alias.trim(),z=!!E&&!t6.test(E),$=!!E&&(D.get(E)??0)>1,q=s.find(U=>U.id===B.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)(ht,{value:B.alias,onChange:r(U=>R(B.id,{alias:U.target.value}),"onChange"),onBlur:r(U=>{const O=U.target.value.trim();if(O&&!t6.test(O)){const K=P1(O);K&&K!==O&&R(B.id,{alias:K})}},"onBlur"),placeholder:"ALIAS","aria-label":"Access alias",disabled:i,className:W("h-9 font-mono text-sm",(z||$)&&"border-destructive text-destructive")})}),(0,t.jsxs)("div",{className:"flex min-w-0 items-start gap-1.5",children:[(0,t.jsxs)(gr,{open:j?.rowId===B.id,onOpenChange:r(U=>{!U&&j?.rowId===B.id&&N(null)},"onOpenChange"),children:[(0,t.jsx)(Sz,{asChild:!0,children:(0,t.jsx)("div",{ref:r(U=>{U?w.current.set(B.id,U):w.current.delete(B.id)},"ref"),className:"min-w-0 flex-1",children:(0,t.jsx)(TW,{secretId:B.secretId,secrets:s,onSelect:r(U=>R(B.id,{secretId:U,version:"latest",alias:!B.alias.trim()&&U?P1(C(U)):B.alias}),"onSelect"),onCreateNew:a?U=>{window.setTimeout(()=>{N({rowId:B.id,name:R5(U)||U.trim()})},0)}:void 0,disabled:i,triggerClassName:"h-9 min-h-9"})})}),(0,t.jsx)(dr,{align:"start",className:"w-auto p-3",onInteractOutside:r(U=>{const O=U.detail.originalEvent.target;O&&w.current.get(B.id)?.contains(O)&&U.preventDefault()},"onInteractOutside"),children:j?.rowId===B.id&&a?(0,t.jsx)(bSe,{initialName:j.name,initialValue:"",existingSecretNames:s.map(U=>U.name),onCancel:r(()=>N(null),"onCancel"),onSubmit:r(async(U,O)=>{const K=await a(U,O);R(B.id,{secretId:K.id,version:"latest",alias:B.alias.trim()||P1(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:B.version===void 0?"latest":String(B.version),onChange:r(U=>{const O=U.target.value;R(B.id,{version:O==="latest"?"latest":Number.parseInt(O,10)})},"onChange"),disabled:i||!q,"aria-label":"Version",children:[(0,t.jsx)("option",{value:"latest",children:"latest"}),q?Array.from({length:Math.max(0,q.latestVersion)},(U,O)=>{const K=q.latestVersion-O;return K<=0?null:(0,t.jsxs)("option",{value:K,children:["v",K]},K)}):null]})]}),(0,t.jsx)("button",{type:"button",onClick:r(()=>T(B.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)(la,{className:"size-3.5"})})]}),z?(0,t.jsx)("p",{className:"pl-0.5 text-(length:--text-micro) text-destructive",children:"Invalid alias — use letters, digits and _"}):$?(0,t.jsx)("p",{className:"pl-0.5 text-(length:--text-micro) text-destructive",children:"Duplicate alias"}):null]},B.id)})}):null,(0,t.jsxs)("button",{type:"button",onClick:A,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)(yn,{className:"size-3.5"}),"Add API access"]})]}),(0,t.jsxs)("p",{className:"text-(length:--text-micro) text-muted-foreground/70",children:[$rt("api")," The agent reads them by alias through ",(0,t.jsx)("code",{children:"GET /agents/me/secrets"}),"."]})]})}r(Yrt,"AgentSecretAccessEditor");function Jrt(e){if(typeof e!="string")return null;const s=e.trim();return s.length>0?s:null}r(Jrt,"asNonEmptyString$3");function Xrt(e){return Jrt(e)!==null}r(Xrt,"hasLegacyWorkingDirectory");function Zrt(e){return e.isCreate?!1:Xrt(e.adapterConfig?.cwd)}r(Zrt,"shouldShowLegacyWorkingDirectoryField");var TSe=new Set;function eat(e){return TSe.has(e)}r(eat,"isAdapterTypeHidden");function tat(e){TSe=new Set(e)}r(tat,"setDisabledAdapterTypes");function sat(e){return!Ch(e).hideFromVisualSelection}r(sat,"isVisualAdapterChoice");function RSe(e,s=IW()){const n=e??Ff;return s.map(a=>({value:a.type,label:n(a.type),comingSoon:!!Ch(a.type).comingSoon,hidden:eat(a.type),experimental:!!Ch(a.type).experimental}))}r(RSe,"listAdapterOptions");function ESe(e={}){const s=e.enabled??!0,{data:n}=Z({queryKey:P.adapters.all,queryFn:r(()=>uh.list(),"queryFn"),enabled:s,staleTime:3e5});return n&&srt(n.filter(a=>a.source==="external").map(a=>({type:a.type,label:a.label,disabled:a.disabled,overrideDisabled:a.overridePaused}))),(0,m.useEffect)(()=>{n&&tat(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(ESe,"useDisabledAdaptersSync");function nat(e={}){const s=e.enabled??!0,{data:n}=Z({queryKey:P.adapters.all,queryFn:r(()=>uh.list(),"queryFn"),enabled:s,staleTime:3e5});return n!==void 0}r(nat,"useAdapterRegistryLoaded");function E5(e){return Object.fromEntries(Object.entries(e).filter(([,s])=>s!==void 0))}r(E5,"omitUndefinedEntries");function W2(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=E5(s.adapterType!==void 0?{...Object.fromEntries(GLe.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=E5({...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(W2,"buildAgentUpdatePatch");var rat="kubernetes";function aat(e){return e.driver!=="sandbox"?!1:e.config?.provider===rat}r(aat,"isKubernetesSandboxEnvironment");function DW(e,s){return e!=="kubernetes"?{forced:!1,kubernetesEnvironment:null}:{forced:!0,kubernetesEnvironment:s.find(n=>aat(n))??null}}r(DW,"resolveForcedKubernetesEnvironment");var U$={identity:{},adapterConfig:{},heartbeat:{},debug:{},runtime:{}},sC={};function iat(e){return e==="claude_local"||e==="codex_local"||e==="paperclip_runner"||e==="opencode_local"}r(iat,"supportsAdapterModelRefresh");function oat(e,s){return CNe(e,s).model}r(oat,"resolvePaperclipRunnerTransitionModel");function Kte(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(Kte,"isOverlayDirty");function s6(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)=>s6(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&&s6(o,a[i]))}return!1}r(s6,"overlayValuesEqual");function lat(e,s){const n=r((a,i)=>Object.fromEntries(Object.entries(a).filter(([o,l])=>!(o in i)||!s6(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(lat,"subtractPersistedOverlay");var Zm="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 cat(e){return e.split(",").map(s=>s.trim()).filter(Boolean)}r(cat,"parseCommaArgs");function dat(e){return Array.isArray(e)?e.filter(s=>typeof s=="string").join(", "):typeof e=="string"?e:""}r(dat,"formatArgList");var uat=[{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"}],mat=[{id:"",label:"Auto"},{id:"plan",label:"Plan"},{id:"ask",label:"Ask"}],hat=[{id:"",label:"Auto"},{id:"low",label:"Low"},{id:"medium",label:"Medium"},{id:"high",label:"High"}],pat=[{id:"",label:"Auto"},{id:"low",label:"Low"},{id:"high",label:"High"},{id:"max",label:"Max"}],fat=2,Wte=10,xat=1,PSe=300;function vE(e,s,n){return Math.max(s,Math.min(n,Math.floor(e)))}r(vE,"clampInteger");function gat(e){return vE(e,0,PSe)*1e3}r(gat,"clampDelayMsFromSeconds");function bat({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(bat,"ConfigSections");function MSe(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=Dt(),b=(0,m.useRef)(null),v=ESe(),{data:j=[]}=Z({queryKey:f?P.secrets.list(f):["secrets","none"],queryFn:r(()=>vr.list(f),"queryFn"),enabled:!!f}),{data:N=[]}=Z({queryKey:f?P.secrets.userDefinitions(f):["user-secret-definitions","none"],queryFn:r(()=>vr.listUserSecretDefinitions(f),"queryFn"),enabled:!!f,retry:!1}),w=a?null:e.agent.id,{data:k=[]}=Z({queryKey:f?P.secrets.proposals(f,"pending"):["secret-proposals","none"],queryFn:r(()=>vr.listProposals(f,"pending"),"queryFn"),enabled:!!f&&!a,retry:!1}),S=(0,m.useMemo)(()=>k.filter(Ze=>Ze.kind==="binding"&&Ze.target?.id===w),[k,w]),C=SSe(f,[]),{data:I}=Z({queryKey:P.instance.experimentalSettings,queryFn:r(()=>Nr.getExperimental(),"queryFn"),retry:!1}),R=(0,m.useMemo)(()=>{const Ze=new Set(v);return I?.enableNativeRunner!==!0&&Ze.add("paperclip_runner"),Ze},[v,I?.enableNativeRunner]),T=I?.enableEnvironments===!0,A=I?.enableManagedSandboxOnly===!0,D=I===void 0||A,{data:M}=Z({queryKey:P.instance.generalSettings,queryFn:r(()=>Nr.getGeneral(),"queryFn"),retry:!1}),{data:B}=Z({queryKey:P.instance.settings,queryFn:r(()=>Nr.get(),"queryFn"),retry:!1}),{data:E=[]}=Z({queryKey:f?P.environments.list(f):["environments","none"],queryFn:r(()=>Pi.list(f),"queryFn"),enabled:!!f&&(T||M?.executionMode==="kubernetes")}),{forced:z,kubernetesEnvironment:$}=(0,m.useMemo)(()=>DW(M?.executionMode,E),[M?.executionMode,E]),q=je({mutationFn:r(Ze=>{if(!f)throw new Error("Select an organization to create secrets");return vr.create(f,Ze)},"mutationFn"),onSuccess:r(()=>{f&&x.invalidateQueries({queryKey:P.secrets.list(f)})},"onSuccess")}),U=je({mutationFn:r(async({file:Ze,namespace:At})=>{if(!f)throw new Error("Select an organization to upload images");return bb.uploadImage(f,Ze,At)},"mutationFn")}),[O,K]=(0,m.useState)(U$),[H,ee]=(0,m.useState)(!1),[se,ne]=(0,m.useState)(0),fe=(0,m.useRef)(null),X=(0,m.useRef)(null),re=(0,m.useRef)(!1);(0,m.useEffect)(()=>{if(!a){if(fe.current!==null&&e.agent!==fe.current&&!re.current){const Ze=X.current;X.current=null,K(At=>Ze?lat(At,Ze):{...U$})}fe.current=e.agent}},[a,a?void 0:e.agent]);const oe=!a&&(Kte(O)||H);function G(Ze,At,fs){const Ks=O[Ze];return At in Ks?Ks[At]:fs}r(G,"eff");function Y(Ze,At,fs){K(Ks=>({...Ks,[Ze]:{...Ks[Ze],[At]:fs}}))}r(Y,"mark");function Q(){return b.current?.flushPendingDraft()??null}r(Q,"flushEnvironmentDraft");const te=(0,m.useCallback)(Ze=>{a||K(At=>{const fs={...e.agent.adapterConfig??{},...At.adapterConfig},Ks={...At.adapterConfig};for(const[Ln,Cr]of Object.entries(Ze))Ks[`${mA}${Ln}`]=Cr;for(const Ln of Object.keys(fs))Ln.startsWith("access.")&&(Ln.slice(7)in Ze||(Ks[Ln]=void 0));return{...At,adapterConfig:Ks}})},[a,a?void 0:e.agent]),ae=(0,m.useCallback)(()=>{K({...U$}),ee(!1),ne(Ze=>Ze+1)},[]),le=(0,m.useCallback)(async()=>{if(a)return;const Ze=Q(),At=Ze?{...O,adapterConfig:{...O.adapterConfig,env:Ze}}:O;Kte(At)&&await e.onSave(W2(e.agent,At))},[a,oe,O,e]);(0,m.useEffect)(()=>{a||(e.onDirtyChange?.(oe),e.onSaveActionChange?.(le),e.onCancelActionChange?.(ae))},[a,oe,e.onDirtyChange,e.onSaveActionChange,e.onCancelActionChange,le,ae]),(0,m.useEffect)(()=>{if(!a)return()=>{e.onSaveActionChange?.(null),e.onCancelActionChange?.(null),e.onDirtyChange?.(!1)}},[a,e.onDirtyChange,e.onSaveActionChange,e.onCancelActionChange]);const he=a?{}:e.agent.adapterConfig??{},ce=a?{}:e.agent.runtimeConfig??{},ge=a?{}:ce.heartbeat??{},me=a?{}:ce.debug??{},ie=a?e.values.adapterType:O.adapterType??e.agent.adapterType,ue=Wy(),ke=ue(ie),be=ke.supportsInstructionsBundle||ke.supportsSkills||ke.supportsLocalAgentJwt,Ie=be&&!D&&Zrt({isCreate:a,adapterConfig:he}),Ue=(0,m.useMemo)(()=>aS(ie),[ie]),at=(0,m.useMemo)(()=>new Set(cze(ie)),[ie]),dt=a?e.values:null,de=a?Ze=>e.onChange(Ze):null;a&&dt.claudeStoredSessionId;const Be=r(()=>{f&&x.invalidateQueries({queryKey:P.secrets.userDefinitions(f)})},"invalidateUserSecretDefinitions"),pt=r(Ze=>{if(!a||!de)return;const At=dt.envBindings??{};de({envBindings:{...At,...Vw()},claudeStoredSessionId:Ze}),Be()},"handleClaudeLoginStored"),vt=r(async()=>{if(a)return;const Ze={...Q()??G("adapterConfig","env",he.env??sC),...Vw()},At={...O,adapterConfig:{...O.adapterConfig,env:Ze}};K(At),await e.onSave({...W2(e.agent,At),applyStoredClaudeLogin:!0}),Be()},"handleClaudeLoginStoredEdit"),Le=r(async Ze=>{if(a||!Ze.companyIdentityDiffers)return;const At={...Q()??G("adapterConfig","env",he.env??sC),CODEX_HOME:{type:"secret_ref",secretId:Ze.secretId,version:"latest"}},fs={...O,adapterConfig:{...O.adapterConfig,env:At}};K(fs),X.current=fs,re.current=!0;try{await e.onSave(W2(e.agent,fs))}catch(Ks){throw X.current=null,Ks}finally{re.current=!1}Be()},"handleCodexAccountBindingEdit"),Qe=r(()=>{if(!a||!de)return;const Ze=dt.envBindings??{};de({envBindings:{...Ze,...Vw()},claudeApplyStoredLogin:!0}),Be()},"handleApplyStoredClaudeLogin"),ut=r(async()=>{if(a)return;const Ze={...Q()??G("adapterConfig","env",he.env??sC),...Vw()},At={...O,adapterConfig:{...O.adapterConfig,env:Ze}};K(At),await e.onSave({...W2(e.agent,At),applyStoredClaudeLogin:!0}),Be()},"handleApplyStoredClaudeLoginEdit"),Ye=a?dt.defaultEnvironmentId??"":G("identity","defaultEnvironmentId",e.agent.defaultEnvironmentId??""),it=(0,m.useMemo)(()=>Ye?(E.find(Ze=>Ze.id===Ye)??null)?.driver==="local"?"":Ye:"",[E,Ye]),kt=(0,m.useMemo)(()=>E.find(Ze=>Ze.id===it)??null,[it,E]),tt=(0,m.useMemo)(()=>{const Ze=B?.defaultEnvironmentId??null;return Ze?(E.find(At=>At.id===Ze)??null)?.driver==="local"?"":Ze:""},[E,B?.defaultEnvironmentId]),Pe=(0,m.useMemo)(()=>E.find(Ze=>Ze.id===tt)??null,[E,tt]),Ce=(0,m.useMemo)(()=>{try{return iN({agentDefaultEnvironmentId:Ye||null,instanceDefaultEnvironmentId:B?.defaultEnvironmentId??null,localDefaultEnvironmentId:lN(E),managedSandboxOnly:I?.enableManagedSandboxOnly===!0,managedSandboxEnvironmentId:oN(E),visibleEnvironmentIds:E.map(Ze=>Ze.id)})}catch{return null}},[Ye,B?.defaultEnvironmentId,E,I?.enableManagedSandboxOnly]),He=(0,m.useMemo)(()=>E.find(Ze=>Ze.id===Ce)??null,[E,Ce]),{data:Je}=Z({queryKey:f?P.environments.capabilities(f):["environment-capabilities","none"],queryFn:r(()=>Pi.capabilities(f),"queryFn"),enabled:!!f&&ke.login!=null});(0,m.useEffect)(()=>{!a||!de||!z||!$||it!==$.id&&de({defaultEnvironmentId:$.id})},[a,de,z,$,it]);const lt=(0,m.useMemo)(()=>E.filter(Ze=>{if(!at.has(Ze.driver)||Ze.driver==="local")return!1;if(Ze.driver!=="sandbox")return!0;const At=typeof Ze.config?.provider=="string"?Ze.config.provider:null;return At!==null&&At!=="fake"}),[E,at]),Ee=(0,m.useMemo)(()=>!kt||lt.some(Ze=>Ze.id===kt.id)?lt:[...lt,kt],[kt,lt]),Xe=T&&(z||it.length>0||lt.length>=1),Ae=Pe?Qv(Pe):A?"Paperclip Computer":"Local",De=ie==="paperclip_runner"?String(a?e.values.adapterSchemaValues?.provider??"codex":G("adapterConfig","provider",he.provider==="acpx"&&he.acpxAgent==="codex"?"codex":he.provider??"codex")):void 0,_t=ie==="opencode_local"&&zpe.safeParse(O.runtime.runtimeConfig?.aiConnection??ce.aiConnection).data?.provider==="openrouter"?"openrouter":De,ye=f?P.agents.adapterModels(f,ie,it||null,_t):["agents","none","adapter-models",ie],{data:gt,error:We}=Z({queryKey:ye,queryFn:r(()=>$t.adapterModels(f,ie,{environmentId:it||null,provider:_t}),"queryFn"),enabled:!!f}),[Ot,zt]=(0,m.useState)(null),[Cs,ze]=(0,m.useState)(!1),ft=gt??n??[],Ut="command",{data:Ns,refetch:Is}=Z({queryKey:f?P.agents.detectModel(f,ie):["agents","none","detect-model",ie],queryFn:r(()=>{if(!f)throw new Error("Select an organization to detect the model");return $t.detectModel(f,ie)},"queryFn"),enabled:!!(f&&be&&ie!=="opencode_local"&&ie!=="paperclip_runner")}),St=Ns?.model??null;Ns?.candidates;const{data:ds=[]}=Z({queryKey:f?P.agents.list(f):["agents","none","list"],queryFn:r(()=>$t.list(f),"queryFn"),enabled:!!(!a&&f)}),$e={mode:s,isCreate:a,adapterType:ie,values:a?e.values:null,set:a?Ze=>e.onChange(Ze):null,config:he,eff:G,mark:Y,models:ft,hideInstructionsFile:h||D,managedSandboxOnly:D},[xe,Qt]=(0,m.useState)(!1),[Mt,rs]=(0,m.useState)(!1),ws=ONe(ie),Bs=r(Ze=>(0,t.jsxs)(t.Fragment,{children:[ie==="claude_local"&&(0,t.jsx)(Fet,{...$e,section:Ze}),(0,t.jsx)(Ue.ConfigFields,{...$e,section:Ze,hideModel:be})]}),"renderAdapterFields"),[er,Fe]=(0,m.useState)(!1),[st,xt]=(0,m.useState)(!1);function Oe(Ze){if(a){const fs=Ue.buildAdapterConfig(dt);return Ze&&Object.assign(fs,Ze),E5(fs)}const At={...he,...O.adapterConfig};return Ze&&Object.assign(At,Ze),E5(At)}r(Oe,"buildAdapterConfigForTest");const Bt=je({mutationFn:r(async()=>{if(!f)throw new Error("Select an organization to test adapter environment");const Ze=Q(),At=Ze?{env:Ze}:void 0;let fs=B,Ks=E,Ln=I?.enableManagedSandboxOnly===!0;if(!Ye)try{const[_r,yr,sr]=await Promise.all([x.ensureQueryData({queryKey:P.instance.settings,queryFn:r(()=>Nr.get(),"queryFn")}),x.ensureQueryData({queryKey:P.environments.list(f),queryFn:r(()=>Pi.list(f),"queryFn")}),x.ensureQueryData({queryKey:P.instance.experimentalSettings,queryFn:r(()=>Nr.getExperimental(),"queryFn")})]);fs=_r,Ks=yr,Ln=sr?.enableManagedSandboxOnly===!0}catch{throw new Error("Could not load environment settings to determine which environment to test in. Retry the test.")}const Cr=iN({agentDefaultEnvironmentId:Ye||null,instanceDefaultEnvironmentId:fs?.defaultEnvironmentId??null,localDefaultEnvironmentId:lN(Ks),managedSandboxOnly:Ln,managedSandboxEnvironmentId:oN(Ks),visibleEnvironmentIds:Ks.map(_r=>_r.id)}),Vr=Oe(At),Pr=a?void 0:e.agent.id,Ar=a?void 0:yJ.safeParse(O.runtime.runtimeConfig?.aiConnection??e.agent.runtimeConfig.aiConnection).data;if(e.compactTestFeedback){const _r=ie==="paperclip_runner"?Vr.provider==="codex"?"codex_local":Vr.provider==="acpx"&&Vr.acpxAgent==="grok"?"grok_local":Vr.provider==="acpx"&&Vr.acpxAgent==="claude"?"claude_local":ie:ie;return jNe({companyId:f,adapterType:ie,providerAdapter:_r,adapterConfig:Vr,agentId:Pr,aiConnection:Ar,environmentId:Cr})}return $t.testEnvironment(f,ie,{adapterConfig:Vr,agentId:Pr,aiConnection:Ar,environmentId:Cr})},"mutationFn")}),[wt,Xt]=(0,m.useState)(!1),[Yt,hs]=(0,m.useState)(null),Ts="Test",as=!a&&!!e.isSaving,Zn=wt||as||!f,en=(0,m.useRef)(Bt.reset);en.current=Bt.reset;const nr=(0,m.useRef)(()=>{});nr.current=()=>{if(!a||!de)return;const Ze=dt.envBindings??{},At=dt.claudeStoredSessionId!=null||dt.claudeApplyStoredLogin===!0,fs=Mte in Ze;if(!At&&!fs)return;const Ks={...Ze};delete Ks[Mte],de({envBindings:Ks,claudeStoredSessionId:null,claudeApplyStoredLogin:!1})},(0,m.useEffect)(()=>{en.current(),hs(null),nr.current()},[ie,Ce]);const tn=ke.login!=null,xn=Bt.data,Ht=xn!=null&&ue(xn.adapterType).login!=null,qs=xn&&Ht?xn.checks.find(Ze=>Ze.code==="adapter_auth_missing")??null:null,Vs=typeof He?.config?.provider=="string"?He.config.provider:null,Lt=Vs!=null&&Je?.sandboxProviders?.[Vs]?.supportsLoginPty===!0,is=ke.login!=null,Ms=(a||!(O.runtime.runtimeConfig?.aiConnection??ce.aiConnection))&&tn&&He?.driver==="sandbox"&&!!Ce&&!!f&&!!qs&&(!is||Lt),bs=(0,m.useCallback)(async()=>{if(!f)throw new Error("Select an organization to test adapter environment");Xt(!0),hs(null),Bt.reset();try{return await Bt.mutateAsync()}catch(Ze){throw hs(Ze instanceof Error?Ze.message:"Environment test failed"),Ze}finally{Xt(!1)}},[f,Bt]),gn=(0,m.useRef)(()=>{});(0,m.useEffect)(()=>{gn.current=()=>{Zn||bs().catch(()=>{})}},[bs,Zn]);const Pn=(0,m.useCallback)(()=>{gn.current()},[]);(0,m.useEffect)(()=>{if(!(!l||!e.onTestActionChange))return e.onTestActionChange(Pn),()=>{e.onTestActionChange?.(null)}},[l,e.onTestActionChange,Pn]),(0,m.useEffect)(()=>{if(!(!l||!e.onTestActionStateChange))return e.onTestActionStateChange({disabled:Zn,pending:wt}),()=>{e.onTestActionStateChange?.({disabled:!0,pending:!1})}},[l,e.onTestActionStateChange,Zn,wt]),(0,m.useEffect)(()=>{if(e.onTestFeedbackChange)return e.onTestFeedbackChange({errorMessage:Yt??(Bt.error instanceof Error?Bt.error.message:Bt.error?"Environment test failed":null),result:Bt.data??null,login:Ms&&f&&Ce?{companyId:f,adapterType:ie,environmentId:Ce}:null}),()=>{e.onTestFeedbackChange?.({errorMessage:null,result:null,login:null})}},[e.onTestFeedbackChange,Yt,Bt.data,Bt.error,Ms,f,ie,Ce]);const $r=a?dt.model??"":G("adapterConfig","model",String(he.model??"")),mt=typeof $r=="string"?$r:"";async function vs(){if(f){ze(!0),zt(null);try{const Ze=await $t.adapterModels(f,ie,{refresh:!0,environmentId:it||null,provider:_t});x.setQueryData(ye,Ze)}catch(Ze){zt(Ze instanceof Error?Ze.message:"Failed to refresh adapter models.")}finally{ze(!1)}}}r(vs,"handleRefreshModels");const Fs=ie==="codex_local"?"modelReasoningEffort":ie==="cursor"?"mode":ie==="opencode_local"?"variant":ie==="grok_local"?"reasoningEffort":ie==="pi_local"?"thinking":"effort",Hs=ie==="codex_local"?jW(mt,"Auto").map(Ze=>({id:Ze.value,label:Ze.label})):ie==="cursor"?mat:ie==="opencode_local"?uat:ie==="kimi_local"?pat:ie==="pi_local"?[{id:"",label:"Auto"},...["off","minimal","low","medium","high","xhigh"].map(Ze=>({id:Ze,label:Ze}))]:ie==="claude_local"||ie==="grok_local"?[{id:"",label:"Auto"},...S5(ie,mt).map(Ze=>({id:Ze,label:Ze==="xhigh"?"X-High":Ze[0].toUpperCase()+Ze.slice(1)}))]:hat,zs=a?dt.thinkingEffort:ie==="codex_local"?G("adapterConfig","modelReasoningEffort",String(he.modelReasoningEffort??he.reasoningEffort??"")):ie==="cursor"?G("adapterConfig","mode",String(he.mode??"")):ie==="opencode_local"?G("adapterConfig","variant",String(he.variant??"")):G("adapterConfig",Fs,String(he[Fs]??"")),Us=ie!=="gemini_local"&&ie!=="cursor_cloud"&&ie!=="paperclip_runner",ur=ie==="codex_local"?a?!!dt.search:G("adapterConfig","search",!!he.search):!1,Dn=(0,m.useMemo)(()=>{if(a)return{heartbeat:{enabled:dt.heartbeatEnabled,intervalSec:dt.intervalSec}};const Ze={...ce.heartbeat&&typeof ce.heartbeat=="object"?ce.heartbeat:{},...O.heartbeat};return{...ce,heartbeat:Ze}},[a,O.heartbeat,ce,dt]),Er=_J(Dn.heartbeat),Jn=_J(Er.maxTurnContinuation),tr=g$e(Jn.enabled,!0),pn=vE(LJ(Jn.maxAttempts,fat),0,Wte),yt=vE(LJ(Jn.delayMs,xat*1e3)/1e3,0,PSe);function Ps(Ze){Y("heartbeat","maxTurnContinuation",{...Jn,...Ze})}r(Ps,"updateMaxTurnContinuation");const Zs=(0,t.jsx)(jy,{ref:b,onDirtyChange:ee,hideDraftActions:!a&&e.hideInlineSave,value:a?dt.envBindings??sC:G("adapterConfig","env",he.env??sC),secrets:j,userSecretDefinitions:N,onCreateSecret:r(async(Ze,At)=>await q.mutateAsync({name:Ze,value:At}),"onCreateSecret"),onChange:r(Ze=>a?de({envBindings:Ze??{},envVars:""}):Y("adapterConfig","env",Ze),"onChange")},se);return!a&&e.content==="secrets"?(0,t.jsxs)("div",{className:W("relative",i&&"space-y-6"),children:[oe&&!e.hideInlineSave&&(0,t.jsx)("div",{className:"sticky top-0 z-10 flex items-center justify-end border-b border-primary/20 bg-background/90 px-4 py-2 backdrop-blur-sm",children:(0,t.jsxs)("div",{className:"flex items-center gap-3",children:[(0,t.jsx)("span",{className:"text-xs text-muted-foreground",children:"Unsaved changes"}),(0,t.jsx)(L,{size:"sm",onClick:le,disabled:e.isSaving,children:e.isSaving?"Saving...":"Save"})]})}),e.environmentVariablesPlacement==="secrets"&&(0,t.jsxs)("div",{"data-config-section":"environment-variables",className:W(!i&&"border-b border-border"),children:[i?(0,t.jsx)("h3",{className:"mb-3 text-sm font-medium",children:"Environment variables"}):(0,t.jsx)("div",{className:"px-4 py-2 text-xs font-medium text-muted-foreground",children:"Environment variables"}),(0,t.jsx)("div",{className:W(i?"rounded-lg border border-border p-4":"px-4 pb-3"),children:Zs})]}),(0,t.jsxs)("div",{"data-config-section":"secrets",className:W(!i&&"border-b border-border"),children:[i?(0,t.jsx)("h3",{className:"mb-3 text-sm font-medium",children:"Secret access"}):(0,t.jsx)("div",{className:"px-4 py-2 text-xs font-medium text-muted-foreground",children:"Secret access"}),(0,t.jsxs)("div",{className:W(i?"space-y-3 rounded-lg border border-border p-4":"space-y-3 px-4 pb-3"),children:[(0,t.jsx)("p",{className:"text-xs text-muted-foreground",children:Ni.secretAccess}),(0,t.jsx)(Yrt,{config:{...he,...O.adapterConfig},secrets:j,onChange:te,onCreateSecret:r((Ze,At)=>q.mutateAsync({name:Ze,value:At}),"onCreateSecret"),proposals:S,onApproveProposal:C.requestApprove,onRejectProposal:C.requestReject}),C.dialogs]})]})]}):(0,t.jsxs)(bat,{order:e.sectionOrder,className:W("relative",i&&"space-y-6"),children:[oe&&!e.hideInlineSave&&(0,t.jsx)("div",{className:"sticky top-0 z-10 flex items-center justify-end px-4 py-2 bg-background/90 backdrop-blur-sm border-b border-primary/20",children:(0,t.jsxs)("div",{className:"flex items-center gap-3",children:[(0,t.jsx)("span",{className:"text-xs text-muted-foreground",children:"Unsaved changes"}),(0,t.jsx)(L,{size:"sm",onClick:le,disabled:!a&&e.isSaving,children:!a&&e.isSaving?"Saving...":"Save"})]})}),!a&&(0,t.jsxs)("div",{"data-config-section":"identity",className:W(!i&&"border-b border-border"),children:[i?(0,t.jsx)("h3",{className:"text-sm font-medium mb-3",children:e.sectionTitles?.identity??"Identity"}):(0,t.jsx)("div",{className:"px-4 py-2 text-xs font-medium text-muted-foreground",children:"Identity"}),(0,t.jsxs)("div",{className:W(i?"border border-border rounded-lg p-4 space-y-3":"px-4 pb-3 space-y-3"),children:[(0,t.jsx)(Ss,{label:"Name",hint:Ni.name,children:(0,t.jsx)(Ka,{value:G("identity","name",e.agent.name),onCommit:r(Ze=>Y("identity","name",Ze),"onCommit"),immediate:!0,className:Zm,placeholder:"Agent name"})}),(0,t.jsx)(Ss,{label:"Title",hint:Ni.title,children:(0,t.jsx)(Ka,{value:G("identity","title",e.agent.title??""),onCommit:r(Ze=>Y("identity","title",Ze||null),"onCommit"),immediate:!0,className:Zm,placeholder:"e.g. VP of Engineering"})}),(0,t.jsx)(Ss,{label:"Reports to",hint:Ni.reportsTo,children:(0,t.jsx)(lrt,{agents:ds,value:G("identity","reportsTo",e.agent.reportsTo??null),onChange:r(Ze=>Y("identity","reportsTo",Ze),"onChange"),excludeAgentIds:[e.agent.id],chooseLabel:"Choose manager…"})}),be&&!e.hidePromptTemplate&&(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)(Ss,{label:"Prompt Template",hint:Ni.promptTemplate,children:(0,t.jsx)(fd,{value:G("adapterConfig","promptTemplate",String(he.promptTemplate??"")),onChange:r(Ze=>Y("adapterConfig","promptTemplate",Ze??""),"onChange"),placeholder:"You are agent {{ agent.name }}. Your role is {{ agent.role }}...",contentClassName:"min-h-(--sz-88px) text-sm font-mono",imageUploadHandler:r(async Ze=>{const At=`agents/${e.agent.id}/prompt-template`;return(await U.mutateAsync({file:Ze,namespace:At})).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."})]})]})]}),z?(0,t.jsxs)("div",{"data-config-section":"environment",className:W(!i&&(a?"border-t border-border":"border-b border-border")),children:[i?(0,t.jsx)("h3",{className:"text-sm font-medium mb-3",children:"Environment"}):(0,t.jsx)("div",{className:"px-4 py-2 text-xs font-medium text-muted-foreground",children:"Environment"}),(0,t.jsx)("div",{className:W(i?"border border-border rounded-lg p-4 space-y-3":"px-4 pb-3 space-y-3"),children:(0,t.jsx)(Ss,{label:"Default environment",hint:"This instance runs all agents in the Kubernetes sandbox. Local execution is disabled.",children:$?(0,t.jsxs)("div",{className:W(Zm,"flex items-center text-muted-foreground"),children:[$.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."})})})]}):Xe?(0,t.jsxs)("div",{"data-config-section":"environment",className:W(!i&&(a?"border-t border-border":"border-b border-border")),children:[i?(0,t.jsx)("h3",{className:"text-sm font-medium mb-3",children:"Environment"}):(0,t.jsx)("div",{className:"px-4 py-2 text-xs font-medium text-muted-foreground",children:"Environment"}),(0,t.jsx)("div",{className:W(i?"border border-border rounded-lg p-4 space-y-3":"px-4 pb-3 space-y-3"),children:(0,t.jsx)(Ss,{label:"Environment override",children:(0,t.jsx)("div",{className:"space-y-2",children:(0,t.jsxs)("select",{className:Zm,value:it,onChange:r(Ze=>{const At=Ze.target.value;if(a){de({defaultEnvironmentId:At});return}Y("identity","defaultEnvironmentId",At||null)},"onChange"),children:[(0,t.jsxs)("option",{value:"",children:["Default: ",Ae]}),Ee.map(Ze=>(0,t.jsx)("option",{value:Ze.id,children:Qv(Ze)},Ze.id))]})})})})]}):null,(0,t.jsxs)("div",{"data-config-section":"adapter",className:W(!i&&(a?"border-t border-border":"border-b border-border")),children:[(0,t.jsxs)("div",{className:W(i?"flex items-center justify-between mb-3":"px-4 py-2 flex items-center justify-between gap-2"),children:[i?(0,t.jsx)("h3",{className:"text-sm font-medium",children:e.sectionTitles?.adapter??"Adapter"}):(0,t.jsx)("span",{className:"text-xs font-medium text-muted-foreground",children:"Adapter"}),c&&(0,t.jsx)(L,{type:"button",variant:"outline",size:"sm",className:"h-7 px-2.5 text-xs",onClick:Pn,disabled:Zn,children:wt?`${Ts}...`:Ts})]}),(0,t.jsxs)("div",{className:W(i?"border border-border rounded-lg p-4 space-y-3":"px-4 pb-3 space-y-3"),children:[o&&(0,t.jsx)(Ss,{label:"Adapter type",hint:Ni.adapterType,children:(0,t.jsx)(LSe,{value:ie,disabledTypes:R,onChange:r(Ze=>{if(a){const{adapterType:At,...fs}=nb,Ks={...fs,adapterType:Ze};Ze==="codex_local"?Ks.dangerouslyBypassSandbox=!0:Ze==="gemini_local"?Ks.model="auto":Ze==="kimi_local"?Ks.model="kimi-code/kimi-for-coding":Ze==="cursor"?Ks.model="auto":Ze==="opencode_local"?Ks.model="openai/gpt-5.2-codex":Ze==="paperclip_runner"&&(Ks.model=nN),de(Ks)}else K(At=>({...At,adapterType:Ze,adapterConfig:{model:Ze==="gemini_local"?"auto":Ze==="kimi_local"?"kimi-code/kimi-for-coding":Ze==="opencode_local"?"openai/gpt-5.2-codex":Ze==="cursor"?"auto":Ze==="paperclip_runner"?oat(ie,he.model):"",effort:"",modelReasoningEffort:"",variant:"",mode:"",...Ze==="codex_local"?{dangerouslyBypassApprovalsAndSandbox:!0}:Ze==="paperclip_runner"?{...CNe(ie,G("adapterConfig","model",he.model))}:{}}}))},"onChange")})}),!a&&f&&(0,t.jsx)(yNe,{companyId:f,agentId:e.agent.id,agentName:e.agent.name,adapterType:ie==="paperclip_runner"?G("adapterConfig","provider",he.provider)==="codex"?"codex_local":G("adapterConfig","provider",he.provider)==="opencode"?"opencode_local":G("adapterConfig","provider",he.provider)==="acpx"&&G("adapterConfig","acpxAgent",he.acpxAgent)==="grok"?"grok_local":G("adapterConfig","provider",he.provider)==="acpx"&&G("adapterConfig","acpxAgent",he.acpxAgent)==="claude"?"claude_local":ie:ie,routerAdapterType:ie,value:yJ.safeParse(O.runtime.runtimeConfig?.aiConnection??ce.aiConnection).data,model:String(G("adapterConfig","model",he.model)??""),environmentId:it||void 0,legacy:!0,onChange:r(Ze=>Y("runtime","runtimeConfig",{...ce,aiConnection:Ze}),"onChange")}),d&&!e.compactTestFeedback&&(Yt||Bt.error)&&(0,t.jsx)("div",{className:"rounded-md border border-destructive/30 bg-destructive/10 px-3 py-2 text-xs text-destructive",children:Yt??(Bt.error instanceof Error?Bt.error.message:"Environment test failed")}),d&&!e.compactTestFeedback&&Bt.data&&(0,t.jsx)(Sat,{result:Bt.data}),d&&Ms&&(0,t.jsx)(LW,{companyId:f,adapterType:ie,environmentId:Ce,onStored:a?pt:vt,onApplyStored:a?Qe:ut,onAccountBinding:a?void 0:Le},`${ie}:${Ce}`),Ie&&(0,t.jsx)(Ss,{label:"Working directory (deprecated)",hint:Ni.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)(Ho,{className:"h-3.5 w-3.5 text-muted-foreground shrink-0"}),(0,t.jsx)(Ka,{value:a?dt.cwd:G("adapterConfig","cwd",String(he.cwd??"")),onCommit:r(Ze=>a?de({cwd:Ze}):Y("adapterConfig","cwd",Ze||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)(Dd,{})]})}),Bs("adapter"),be&&(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)($W,{models:ft,value:mt,onChange:r(Ze=>{const At=S5(ie,Ze),fs=["codex_local","claude_local","grok_local"].includes(ie)&&!!zs&&!At.includes(String(zs));if(a){de({model:Ze,...fs?{thinkingEffort:""}:{}});return}Y("adapterConfig","model",Ze||void 0),fs&&(Y("adapterConfig",Fs,void 0),Y("adapterConfig","reasoningEffort",void 0))},"onChange"),open:er,onOpenChange:Fe,defaultLabel:ie==="claude_local"?"Default (claude-opus-5)":void 0,allowDefault:ie!=="opencode_local"&&ie!=="pi_local"&&ie!=="paperclip_runner",required:ie==="opencode_local"||ie==="pi_local",groupByProvider:ie==="opencode_local"||ie==="pi_local",preserveOrder:_W(ie),creatable:!0,detectedModel:St,detectedModelCandidates:[],onDetectModel:ie==="opencode_local"||ie==="paperclip_runner"?void 0:async()=>(await Is()).data?.model??null,onRefreshModels:iat(ie)?vs:void 0,refreshingModels:Cs,detectModelLabel:"Detect model",emptyDetectHint:"No model detected. Select or enter one manually."}),(Ot||We)&&(0,t.jsx)("p",{className:"text-xs text-destructive",children:Ot??(We instanceof Error?We.message:"Failed to load adapter models.")}),ie==="opencode_local"&&kt&&kt.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 ",kt.name,"."]}),Us&&(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)(Cat,{value:zs,options:Hs,onChange:r(Ze=>a?de({thinkingEffort:Ze}):Y("adapterConfig",Fs,Ze||void 0),"onChange"),open:st,onOpenChange:xt}),ie==="codex_local"&&ur&&zs==="minimal"&&(0,t.jsx)("p",{className:"text-xs text-amber-400",children:"Codex may reject `minimal` thinking when search is enabled."})]})]})]})]}),(0,t.jsxs)("div",{"data-config-section":"configuration",className:W(!i&&"border-b border-border"),children:[i?(0,t.jsx)("h3",{className:"text-sm font-medium mb-3",children:"Configuration"}):(0,t.jsx)("div",{className:"px-4 py-2 text-xs font-medium text-muted-foreground",children:"Configuration"}),(0,t.jsxs)("div",{className:W(i?"border border-border rounded-lg p-4 space-y-3":"px-4 pb-3 space-y-3"),children:[!a&&typeof he.bootstrapPromptTemplate=="string"&&he.bootstrapPromptTemplate&&(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)(Ss,{label:"Bootstrap prompt (legacy)",hint:Ni.bootstrapPrompt,children:(0,t.jsx)(fd,{value:G("adapterConfig","bootstrapPromptTemplate",String(he.bootstrapPromptTemplate??"")),onChange:r(Ze=>Y("adapterConfig","bootstrapPromptTemplate",Ze||void 0),"onChange"),placeholder:"Optional initial setup prompt for the first run",contentClassName:"min-h-(--sz-44px) text-sm font-mono",imageUploadHandler:r(async Ze=>{const At=`agents/${e.agent.id}/bootstrap-prompt`;return(await U.mutateAsync({file:Ze,namespace:At})).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."})]}),Bs("configuration"),(be||ie==="process"||ws?.fields.some(Ze=>Fq(Ze.key)==="advanced"))&&(0,t.jsx)(mE,{title:"Advanced",open:Mt,onToggle:r(()=>rs(!Mt),"onToggle"),children:(0,t.jsxs)("div",{className:"space-y-3",children:[be&&(0,t.jsxs)(t.Fragment,{children:[" ",!D&&(0,t.jsx)(Ss,{label:"Command",hint:Ni.localCommand,children:(0,t.jsx)(Ka,{value:a?dt.command:G("adapterConfig",Ut,String(he.command??"")),onCommit:r(Ze=>a?de({command:Ze}):Y("adapterConfig",Ut,Ze||null),"onCommit"),immediate:!0,className:Zm,placeholder:{claude_local:"claude",codex_local:"codex",gemini_local:"gemini",kimi_local:"kimi",pi_local:"pi",cursor:"agent",opencode_local:"opencode"}[ie]??ie.replace(/_local$/,"")})}),(0,t.jsx)(Ss,{label:"Extra args (comma-separated)",hint:Ni.extraArgs,children:(0,t.jsx)(Ka,{value:a?dt.extraArgs:G("adapterConfig","extraArgs",dat(he.extraArgs)),onCommit:r(Ze=>a?de({extraArgs:Ze}):Y("adapterConfig","extraArgs",Ze?.trim()?cat(Ze):null),"onCommit"),className:Zm,placeholder:"e.g. --verbose, --foo=bar"})})]}),Bs("advanced")]})})]})]}),e.environmentVariablesPlacement!=="secrets"&&(be||ws?.fields.some(Ze=>Fq(Ze.key)==="environment"))&&(0,t.jsxs)("div",{"data-config-section":"environment-variables",className:W(!i&&"border-b border-border"),children:[i?(0,t.jsx)("h3",{className:"text-sm font-medium mb-3",children:"Environment variables"}):(0,t.jsx)("div",{className:"px-4 py-2 text-xs font-medium text-muted-foreground",children:"Environment variables"}),(0,t.jsx)("div",{className:W(i?"border border-border rounded-lg p-4 space-y-3":"px-4 pb-3 space-y-3"),children:be?Zs:Bs("environment")})]}),a&&u?(0,t.jsxs)("div",{"data-config-section":"run-policy",className:W(!i&&"border-b border-border"),children:[i?(0,t.jsxs)("h3",{className:"text-sm font-medium flex items-center gap-2 mb-3",children:[(0,t.jsx)(OC,{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)(OC,{className:"h-3 w-3"})," Run Policy"]}),(0,t.jsxs)("div",{className:W(i?"border border-border rounded-lg p-4 space-y-3":"px-4 pb-3 space-y-3"),children:[(0,t.jsx)(ote,{label:"Heartbeat on interval",hint:Ni.heartbeatInterval,checked:dt.heartbeatEnabled,onCheckedChange:r(Ze=>de({heartbeatEnabled:Ze}),"onCheckedChange"),number:dt.intervalSec,onNumberChange:r(Ze=>de({intervalSec:Ze}),"onNumberChange"),numberLabel:"sec",numberPrefix:"Run heartbeat every",numberHint:Ni.intervalSec,showNumber:dt.heartbeatEnabled}),(0,t.jsx)(mE,{title:"Advanced Run Policy",open:xe,onToggle:r(()=>Qt(!xe),"onToggle"),children:(0,t.jsx)("div",{className:"space-y-3",children:Bs("runPolicy")})})]})]}):a?null:(0,t.jsxs)("div",{"data-config-section":"run-policy",className:W(!i&&"border-b border-border"),children:[i?(0,t.jsxs)("h3",{className:"text-sm font-medium flex items-center gap-2 mb-3",children:[(0,t.jsx)(OC,{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)(OC,{className:"h-3 w-3"})," Run Policy"]}),(0,t.jsxs)("div",{className:W(i?"border border-border rounded-lg overflow-hidden":""),children:[(0,t.jsx)("div",{className:W(i?"p-4 space-y-3":"px-4 pb-3 space-y-3"),children:(0,t.jsx)(ote,{label:"Heartbeat on interval",hint:Ni.heartbeatInterval,checked:G("heartbeat","enabled",ge.enabled===!0),onCheckedChange:r(Ze=>Y("heartbeat","enabled",Ze),"onCheckedChange"),number:G("heartbeat","intervalSec",Number(ge.intervalSec??300)),onNumberChange:r(Ze=>Y("heartbeat","intervalSec",Ze),"onNumberChange"),numberLabel:"sec",numberPrefix:"Run heartbeat every",numberHint:Ni.intervalSec,showNumber:G("heartbeat","enabled",ge.enabled===!0)})}),(0,t.jsx)(mE,{title:"Advanced Run Policy",bordered:i,open:xe,onToggle:r(()=>Qt(!xe),"onToggle"),children:(0,t.jsxs)("div",{className:"space-y-3",children:[Bs("runPolicy"),be&&(0,t.jsx)(t.Fragment,{children:!a&&(0,t.jsxs)(t.Fragment,{children:[!ws?.fields.some(Ze=>Ze.key==="timeoutSec")&&(0,t.jsx)(Ss,{label:"Timeout (sec)",hint:Ni.timeoutSec,children:(0,t.jsx)(Rc,{value:G("adapterConfig","timeoutSec",Number(he.timeoutSec??0)),onCommit:r(Ze=>Y("adapterConfig","timeoutSec",Ze),"onCommit"),immediate:!0,className:Zm})}),!ws?.fields.some(Ze=>Ze.key==="graceSec")&&(0,t.jsx)(Ss,{label:"Interrupt grace period (sec)",hint:Ni.graceSec,children:(0,t.jsx)(Rc,{value:G("adapterConfig","graceSec",Number(he.graceSec??15)),onCommit:r(Ze=>Y("adapterConfig","graceSec",Ze),"onCommit"),immediate:!0,className:Zm})})]})}),(0,t.jsx)(_d,{label:"Wake on demand",hint:Ni.wakeOnDemand,checked:G("heartbeat","wakeOnDemand",ge.wakeOnDemand!==!1),onChange:r(Ze=>Y("heartbeat","wakeOnDemand",Ze),"onChange")}),(0,t.jsx)(Ss,{label:"Cooldown (sec)",hint:Ni.cooldownSec,children:(0,t.jsx)(Rc,{value:G("heartbeat","cooldownSec",Number(ge.cooldownSec??10)),onCommit:r(Ze=>Y("heartbeat","cooldownSec",Ze),"onCommit"),immediate:!0,className:Zm})}),(0,t.jsx)(Ss,{label:"Max concurrent runs",hint:Ni.maxConcurrentRuns,children:(0,t.jsx)(Rc,{value:G("heartbeat","maxConcurrentRuns",Number(ge.maxConcurrentRuns??20)),onCommit:r(Ze=>Y("heartbeat","maxConcurrentRuns",Ze),"onCommit"),immediate:!0,className:Zm})}),(0,t.jsxs)("div",{className:"rounded-md border border-border/70 px-3 py-2",children:[(0,t.jsx)(_d,{label:"Continue after max-turn stop",hint:Ni.maxTurnContinuationEnabled,checked:tr,onChange:r(Ze=>Ps({enabled:Ze}),"onChange")}),tr?(0,t.jsxs)("div",{className:"mt-3 grid gap-3 sm:grid-cols-2",children:[(0,t.jsx)(Ss,{label:"Continuation attempts",hint:Ni.maxTurnContinuationMaxAttempts,children:(0,t.jsx)(Rc,{value:pn,onCommit:r(Ze=>Ps({maxAttempts:vE(Ze,0,Wte)}),"onCommit"),immediate:!0,className:Zm})}),(0,t.jsx)(Ss,{label:"Continuation delay (sec)",hint:Ni.maxTurnContinuationDelaySec,children:(0,t.jsx)(Rc,{value:yt,onCommit:r(Ze=>Ps({delayMs:gat(Ze)}),"onCommit"),immediate:!0,className:Zm})})]}):null]})]})})]})]}),!a&&p?(0,t.jsxs)("div",{className:W(!i&&"border-b border-border"),children:[i?(0,t.jsxs)("h3",{className:"mb-3 flex items-center gap-2 text-sm font-medium",children:[(0,t.jsx)(Uv,{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)(Uv,{className:"h-3 w-3"})," Debugging"]}),(0,t.jsxs)("div",{className:W("border-border bg-accent/30",i?"rounded-lg border p-4":"mx-4 mb-4 rounded-md border px-3 py-3"),children:[(0,t.jsx)(_d,{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",me.providerTrace)==="raw",onChange:r(Ze=>Y("debug","providerTrace",Ze?"raw":void 0),"onChange")}),G("debug","providerTrace",me.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)(Uv,{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)(PNe,{state:wt?"running":Yt||Bt.error?"fail":xn?.status??"idle",result:xn??null,error:Yt??(Bt.error instanceof Error?Bt.error.message:null),onTest:Pn,disabled:Zn})]})}r(MSe,"AgentConfigForm");var n6=new Set(["authenticated","failed","timed_out","cancelled"]),r6=2e3;function a6({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)(L,{type:"button",variant:"ghost",size:"icon-xs","aria-label":s,title:s,className:"text-muted-foreground hover:text-foreground",onClick:r(async()=>{try{await fa(e),a(!0)}catch{a(!1)}i.current&&clearTimeout(i.current),i.current=setTimeout(()=>a(!1),1500)},"onClick"),children:n?(0,t.jsx)(gs,{className:"size-3"}):(0,t.jsx)(Ir,{className:"size-3"})})}r(a6,"AdapterLoginCopyButton");function vat({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)(gs,{className:"size-3 shrink-0"}),(0,t.jsx)("span",{children:"Authenticated. The environment has credentials now."})]}):(0,t.jsxs)("div",{className:"flex items-start gap-2 text-(length:--text-micro) text-destructive",children:[(0,t.jsx)(Es,{className:"size-3 shrink-0"}),(0,t.jsxs)("span",{children:[e==="timed_out"?"Login timed out":e==="cancelled"?"Login cancelled":"Login failed",s?`: ${s}`:"."]})]})}r(vat,"AdapterLoginTerminalState");var yat={claude_local:"Anthropic",codex_local:"OpenAI"};function DSe(e){const s=yat[e];return s?`Sign in to ${s}`:"Sign in to the environment"}r(DSe,"adapterLoginTitle");function LW(e){return Wy()(e.adapterType).login?.panelMode==="submitted_browser_code"?(0,t.jsx)(Nat,{...e}):(0,t.jsx)(jat,{...e})}r(LW,"AdapterLoginPanel");var K$=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 jat({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=je({mutationFn:r(()=>$t.startAdapterAuthLogin(e,s,{environmentId:n,aiConnection:c}),"mutationFn"),onSuccess:r(re=>{N.current=!1,f(null),b(null),j("idle"),h(re.sessionId)},"onSuccess"),onError:r(re=>{f(re instanceof Error?re.message:"Could not start the login.")},"onError")}),k=(0,m.useCallback)(()=>{N.current=!1,h(null),b(null),f(null)},[]),S=je({mutationFn:r(()=>$t.cancelAdapterAuthLogin(e,s,u),"mutationFn"),onSuccess:k,onError:r(re=>{f(re instanceof Error?re.message:"Could not cancel the login.")},"onError")}),C=Z({queryKey:["adapter-login-active-session",e,s],queryFn:r(async()=>{try{const re=await $t.getActiveAdapterAuthLoginSession(e,s);if(!re)return null;if(c&&re.environmentId!==n||!!re.aiConnection!=!!c||c&&(re.aiConnection?.provider!==c.provider||re.aiConnection?.method!==c.method||re.aiConnection?.connectionId!==c.connectionId||re.aiConnection?.ownership!==c.ownership||re.aiConnection?.allAgents!==c.allAgents||JSON.stringify(re.aiConnection?.agentIds)!==JSON.stringify(c.agentIds)))throw new K$(re.sessionId);return re}catch(re){if(re instanceof dn&&re.status===404)return null;throw re}},"queryFn"),retry:!1,gcTime:0,staleTime:0}),[I,R]=(0,m.useState)(!1),T=Z({queryKey:["adapter-login-status",e,s,u],queryFn:r(()=>$t.getAdapterAuthLoginStatus(e,s,u),"queryFn"),enabled:!!u&&!I,retry:r((re,oe)=>oe instanceof dn&&oe.status===404?!1:re<3,"retry"),refetchInterval:r(re=>{const oe=re.state.data?.status;return oe&&n6.has(oe)?!1:r6},"refetchInterval")});(0,m.useEffect)(()=>{const re=T.data?.prompt??null;re&&b(re)},[T.data]);const A=T.data??w.data??null,D=A?.status??null,M=x,B=D?n6.has(D):!1,E=!!u&&!B,z=w.isPending||E||v==="saving",$=(0,m.useRef)(!1);(0,m.useEffect)(()=>{if($.current||!C.isFetched)return;$.current=!0;const re=C.data;re&&(N.current=!0,f(null),b(re.prompt??null),h(re.sessionId))},[C.isFetched,C.data]),(0,m.useEffect)(()=>{const re=T.error;if(!(re instanceof dn&&re.status===404)||!N.current||I)return;R(!0);const oe=u;(async()=>(oe&&await $t.cancelAdapterAuthLogin(e,s,oe).catch(()=>{}),R(!1),k()))()},[T.error,I,u,e,s,k]);const q=(0,m.useRef)(!1),U=je({mutationFn:r(async()=>{const re=C.error;re instanceof K$&&await $t.cancelAdapterAuthLogin(e,s,re.sessionId)},"mutationFn"),onSuccess:r(async()=>{q.current=!1,$.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")}),O=(0,m.useRef)(w.mutate);O.current=w.mutate,(0,m.useEffect)(()=>{if(!(!a||q.current)){if(C.isError){q.current=!0,f(C.error instanceof Error?C.error.message:"Could not check for an active login.");return}C.isSuccess&&(q.current=!0,!C.data&&O.current())}},[a,C.isSuccess,C.isError,C.data,C.error]);const K=(0,m.useRef)(!1),H=(0,m.useRef)(i);H.current=i,(0,m.useEffect)(()=>{D!=="authenticated"||K.current||(K.current=!0,H.current?.(u??void 0))},[D]);const ee=(0,m.useRef)(null),se=(0,m.useRef)(o);se.current=o;const ne=T.data?.codexAccountBinding??null,fe=(0,m.useCallback)(async re=>{const oe=se.current;if(oe){j("saving");try{await oe(re),j("bound")}catch{j("failed")}}},[]);(0,m.useEffect)(()=>{D!=="authenticated"||!u||ee.current!==u&&(!ne||!ne.companyIdentityDiffers||!se.current||(ee.current=u,fe(ne)))},[D,u,ne,fe]);const X=(0,m.useRef)(d);if(X.current=d,(0,m.useEffect)(()=>{X.current?.(M?.url??null)},[M]),l==="onboarding"){const re=B&&D&&D!=="authenticated";return(0,t.jsx)(UNe,{loading:!M&&!p&&!re,providerName:zNe(s),authorizationUrl:M?.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 K$&&(0,t.jsx)(L,{type:"button",variant:"outline",disabled:U.isPending,onClick:r(()=>U.mutate(),"onClick"),children:"Cancel previous sign-in and retry"})]}):re?(0,t.jsx)("p",{role:"alert",className:"pl-2 text-xs text-destructive",children:D==="timed_out"?"The login timed out. Start it again.":D==="cancelled"?"The login was cancelled.":"The login did not finish. Start it again."}):(0,t.jsx)(get,{code:M?.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:DSe(s)}),(0,t.jsxs)("div",{className:"flex items-center gap-1.5",children:[E&&(0,t.jsx)(L,{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)(L,{type:"button",variant:"outline",size:"sm",className:"h-7 px-2.5 text-xs",disabled:z,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:[E&&!M&&(0,t.jsxs)("div",{className:"flex items-center gap-2 text-(length:--text-micro) text-muted-foreground",children:[(0,t.jsx)(rt,{className:"size-3 animate-spin shrink-0"}),(0,t.jsx)("span",{children:"Preparing..."})]}),E&&M&&(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:M.code})]}),(0,t.jsx)(a6,{value:M.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:M.url})]}),(0,t.jsxs)("div",{className:"flex items-center",children:[(0,t.jsx)(a6,{value:M.url,label:"Copy URL"}),(0,t.jsx)(L,{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:M.url,target:"_blank",rel:"noreferrer noopener",children:(0,t.jsx)(Vn,{className:"size-3"})})})]})]})]}),B&&D&&(0,t.jsx)(vat,{status:D,message:A?.failure?.message??null}),D==="authenticated"&&v==="saving"&&(0,t.jsxs)("div",{className:"flex items-center gap-2 text-(length:--text-micro) text-muted-foreground",children:[(0,t.jsx)(rt,{className:"size-3 animate-spin shrink-0"}),(0,t.jsx)("span",{children:"Binding this agent to the signed-in account..."})]}),D==="authenticated"&&v==="bound"&&(0,t.jsxs)("div",{className:"flex items-center gap-2 text-(length:--text-micro) text-foreground",children:[(0,t.jsx)(gs,{className:"size-3 shrink-0"}),(0,t.jsx)("span",{children:"Agent bound to the signed-in account."})]}),D==="authenticated"&&v==="failed"&&(0,t.jsxs)("div",{className:"flex items-center gap-2 text-(length:--text-micro)",children:[(0,t.jsx)(Es,{className:"size-3 shrink-0 text-destructive"}),(0,t.jsx)("span",{className:"text-destructive",children:"Could not bind this agent to the signed-in account."}),(0,t.jsx)(L,{type:"button",variant:"outline",size:"sm",className:"h-6 px-2 text-xs",onClick:r(()=>{ne&&fe(ne)},"onClick"),children:"Retry"})]})]})]})}r(jat,"DisplayedCodeLoginPanel");var wat=new Set(["failed","timed_out","cancelled"]),Vte="The login did not finish. Start the login again.",kat=9e5,Hte="The login timed out. Start the login again.";function Nat({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)(""),[I,R]=(0,m.useState)(null),[T,A]=(0,m.useState)(!1),[D,M]=(0,m.useState)(!1),[B,E]=(0,m.useState)(!1),[z,$]=(0,m.useState)(!1),q=(0,m.useRef)(!1),[U,O]=(0,m.useState)(!1),K=(0,m.useRef)(!1),H=r(()=>{v(null),N(null),k(!1),C(""),R(null),A(!1),M(!1),$(!1),E(!1),q.current=!1},"resetLocalState"),ee=Z({queryKey:["claude-oauth-token-status",e],queryFn:r(async()=>{try{return await $t.getClaudeOAuthTokenStatus(e)}catch(tt){if(tt instanceof dn&&tt.status===404)return null;throw tt}},"queryFn"),retry:r((tt,Pe)=>Pe instanceof dn&&Pe.status===404?!1:tt<2,"retry")}).data??null,se=je({mutationFn:r(()=>$t.startClaudeSetupTokenLogin(e,{environmentId:n,aiConnection:h,...ee&&!h?{overwrite:{expectedSecretId:ee.secretId,expectedLatestVersion:ee.latestVersion}}:{}}),"mutationFn"),onSuccess:r(tt=>{K.current=!1,H(),x(tt.sessionId)},"onSuccess"),onError:r(tt=>{v(tt instanceof Error?tt.message:"Could not start the login.")},"onError")}),ne=r(()=>{K.current=!1,x(null),H()},"clearActiveSession"),fe=je({mutationFn:r(()=>$t.cancelClaudeSetupTokenLogin(e,f),"mutationFn"),onSuccess:r(()=>{ne()},"onSuccess"),onError:r(tt=>{if(tt instanceof dn&&tt.status===404){ne();return}v(tt instanceof Error?tt.message:"Could not cancel the login.")},"onError")}),X=(0,m.useCallback)(tt=>{$t.cancelClaudeSetupTokenLogin(e,tt).catch(()=>{})},[e]),re=Z({queryKey:["claude-setup-token-active-session",e],queryFn:r(async()=>{try{const tt=await $t.getActiveClaudeSetupTokenLoginSession(e);if(!tt)return null;if(h&&tt.environmentId!==n||!!tt.aiConnection!=!!h||h&&(tt.aiConnection?.provider!==h.provider||tt.aiConnection?.method!==h.method||tt.aiConnection?.connectionId!==h.connectionId||tt.aiConnection?.ownership!==h.ownership||tt.aiConnection?.allAgents!==h.allAgents||JSON.stringify(tt.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 tt}catch(tt){if(tt instanceof dn&&tt.status===404)return null;throw tt}},"queryFn"),retry:!1,gcTime:0,staleTime:0}),[oe,G]=(0,m.useState)(!1),Y=!!f&&!D&&!z&&!oe,Q=Z({queryKey:["claude-setup-token-status",e,f],queryFn:r(()=>$t.getClaudeSetupTokenLoginStatus(e,f),"queryFn"),enabled:Y,retry:r((tt,Pe)=>Pe instanceof dn&&Pe.status===404?!1:tt<3,"retry"),refetchInterval:r(tt=>{if(D||z)return!1;const Pe=tt.state.data?.status;return Pe&&n6.has(Pe)?!1:r6},"refetchInterval")});(0,m.useEffect)(()=>{const tt=Q.error;if(tt instanceof dn&&tt.status===404){if(K.current){if(oe)return;G(!0);const Pe=f;(async()=>(Pe&&await $t.cancelClaudeSetupTokenLogin(e,Pe).catch(()=>{}),G(!1),ne()))();return}$(!0)}},[Q.error,oe,f,e]);const te=(0,m.useRef)(!1);(0,m.useEffect)(()=>{if(te.current||!re.isFetched)return;te.current=!0;const tt=re.data;tt&&(K.current=!0,H(),x(tt.sessionId),tt.prompt&&(N(tt.prompt.authorizationUrl),tt.prompt.transportAdvisory&&k(!0)))},[re.isFetched,re.data]);const ae=Z({queryKey:["claude-setup-token-prompt",e,f],enabled:Y&&!j,queryFn:r(async()=>{try{return await $t.getClaudeSetupTokenLoginPrompt(e,f)}catch(tt){if(tt instanceof dn&&tt.status===404)return null;throw tt}},"queryFn"),refetchInterval:r(tt=>D||tt.state.data?.authorizationUrl?!1:r6,"refetchInterval")});(0,m.useEffect)(()=>{const tt=ae.data?.authorizationUrl??null;tt&&N(tt),ae.data?.transportAdvisory&&k(!0)},[ae.data]);const le=je({mutationFn:r(tt=>$t.submitClaudeSetupTokenBrowserCode(e,f,tt),"mutationFn"),onError:r(tt=>{v(tt instanceof Error?tt.message:"Could not submit the browser code.")},"onError")}),he=je({mutationFn:r(()=>$t.completeClaudeSetupTokenLogin(e,f),"mutationFn"),onSuccess:r(tt=>{R(tt.storedSessionId),a?.(tt.storedSessionId)},"onSuccess"),onError:r(()=>{A(!0)},"onError")}),ce=Q.data?.status??se.data?.status??null,ge=Q.data?.expiresAt??se.data?.expiresAt??null,me=(0,m.useRef)(he.mutate);me.current=he.mutate,(0,m.useEffect)(()=>{ce==="authenticated"&&!q.current&&(q.current=!0,me.current())},[ce]);const ie=I!==null,ue=T||z||!!(ce&&wat.has(ce)),ke=ce==="authenticated"&&!ie&&!T,be=!!f&&!ie&&!ue&&!D,Ie=se.isPending||be;(0,m.useEffect)(()=>{if(!be)return;const tt=ge!==null?new Date(ge).getTime():NaN,Pe=Number.isFinite(tt)?Math.max(0,tt-Date.now()):kat,Ce=setTimeout(()=>{f&&X(f),M(!0)},Pe);return()=>clearTimeout(Ce)},[be,ge,f,X]);const Ue=S.trim(),at=be&&!!j&&!ke&&bLe(Ue)&&!le.isPending&&!B,dt=(0,m.useRef)(c);dt.current=c;const de=(0,m.useRef)(d);de.current=d;const Be=r(()=>{at&&(v(null),le.mutate(Ue),E(!0),dt.current?.(),u!=="onboarding"&&C(""))},"handleSubmit"),pt=(0,m.useRef)(!1),vt=(0,m.useRef)(se.mutate);vt.current=se.mutate,(0,m.useEffect)(()=>{if(!(!o||pt.current)){if(re.isError){pt.current=!0,v(re.error instanceof Error?re.error.message:"Could not check for an active login.");return}re.isSuccess&&(pt.current=!0,!re.data&&vt.current())}},[o,re.isSuccess,re.isError,re.data,re.error]);const Le=(0,m.useRef)(Be);Le.current=Be;const Qe=u==="onboarding",ut=(0,m.useRef)(!1);(0,m.useEffect)(()=>{!Qe||!ut.current||(ut.current=!1,at&&Le.current())},[Qe,at,S]);const Ye=(0,m.useRef)(!1),it=(0,m.useRef)(l);it.current=l,(0,m.useEffect)(()=>{!ie||Ye.current||(Ye.current=!0,it.current?.(f??void 0))},[ie]),(0,m.useEffect)(()=>{B&&(!b&&!ue&&!D||(E(!1),de.current?.()))},[B,b,ue,D]);const kt=(0,m.useRef)(p);if(kt.current=p,(0,m.useEffect)(()=>{kt.current?.(j)},[j]),u==="onboarding"){const tt=ue||D;return(0,t.jsxs)(UNe,{loading:!j&&!b&&!tt,providerName:zNe(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)(Es,{className:"mt-0.5 size-3 shrink-0"}),"This connection is not encrypted. The login code travels in clear text on this network. Continue only on a network you trust."]}),b?(0,t.jsx)("p",{role:"alert",className:"pl-2 text-xs text-destructive",children:b}):tt?(0,t.jsx)("p",{role:"alert",className:"pl-2 text-xs text-destructive",children:D&&!ue?Hte:Vte}):(0,t.jsx)(n4,{value:S,onChange:C,onSubmit:Be,onPaste:r(()=>{ut.current=!0},"onPaste"),masked:!0,disabled:le.isPending||ke||B})]})}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:DSe(s)}),(0,t.jsxs)("div",{className:"flex items-center gap-1.5",children:[be&&(0,t.jsx)(L,{type:"button",variant:"ghost",size:"sm",className:"h-7 px-2.5 text-xs text-muted-foreground hover:text-foreground",disabled:fe.isPending,onClick:r(()=>fe.mutate(),"onClick"),children:"Cancel"}),i&&ee&&!be&&!ie&&!U&&(0,t.jsx)(L,{type:"button",variant:"default",size:"sm",className:"h-7 px-2.5 text-xs",onClick:r(()=>{i(),O(!0)},"onClick"),children:"Use saved login"}),(0,t.jsx)(L,{type:"button",variant:"outline",size:"sm",className:"h-7 px-2.5 text-xs",disabled:Ie,onClick:r(()=>se.mutate(),"onClick"),children:ee&&!be&&!ie?"Sign in to replace":"Sign in"})]})]}),ee&&!be&&!ie&&!U&&(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."}),U&&(0,t.jsxs)("div",{className:"flex items-center gap-2 text-(length:--text-micro) text-foreground",children:[(0,t.jsx)(gs,{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:[be&&!j&&!ke&&(0,t.jsxs)("div",{className:"flex items-center gap-2 text-(length:--text-micro) text-muted-foreground",children:[(0,t.jsx)(rt,{className:"size-3 animate-spin shrink-0"}),(0,t.jsx)("span",{children:"Preparing..."})]}),be&&j&&!ke&&(0,t.jsxs)("div",{className:"space-y-2",children:[w&&(0,t.jsxs)("div",{className:"flex items-start gap-2 rounded-md border border-amber-300 bg-amber-50 px-2 py-1.5 text-(length:--text-micro) text-amber-800 dark:border-amber-500/40 dark:bg-amber-500/10 dark:text-amber-200",children:[(0,t.jsx)(Es,{className:"size-3 shrink-0 mt-0.5"}),(0,t.jsx)("span",{children:"This connection is not encrypted. The login code travels in clear text on this network. Continue only on a network you trust."})]}),(0,t.jsx)("div",{className:"text-(length:--text-micro) text-muted-foreground",children:"Open the authorization page, then enter the browser code it shows."}),(0,t.jsxs)("div",{className:"flex items-center justify-between gap-2",children:[(0,t.jsxs)("div",{className:"min-w-0",children:[(0,t.jsx)("div",{className:"text-(length:--text-micro) uppercase tracking-wide text-muted-foreground",children:"1. Authorization URL"}),(0,t.jsx)("span",{className:"font-mono text-xs text-foreground break-all",children:j})]}),(0,t.jsxs)("div",{className:"flex items-center",children:[(0,t.jsx)(a6,{value:j,label:"Copy URL"}),(0,t.jsx)(L,{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)(Vn,{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(tt=>C(tt.target.value),"onChange"),onKeyDown:r(tt=>{tt.key==="Enter"&&(tt.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)(L,{type:"button",variant:"outline",size:"sm",className:"h-7 px-2.5 text-xs",disabled:!at,onClick:Be,children:"Submit"})]})]})]}),ke&&(0,t.jsxs)("div",{className:"flex items-center gap-2 text-(length:--text-micro) text-muted-foreground",children:[(0,t.jsx)(rt,{className:"size-3 animate-spin shrink-0"}),(0,t.jsx)("span",{children:"Completing the login…"})]}),ie&&(0,t.jsxs)("div",{className:"flex items-center gap-2 text-(length:--text-micro) text-foreground",children:[(0,t.jsx)(gs,{className:"size-3 shrink-0"}),(0,t.jsx)("span",{children:"Authenticated. The environment has credentials now."})]}),ue&&(0,t.jsxs)("div",{className:"flex items-start gap-2 text-(length:--text-micro) text-destructive",children:[(0,t.jsx)(Es,{className:"size-3 shrink-0"}),(0,t.jsx)("span",{children:Vte})]}),D&&!ue&&!ie&&(0,t.jsxs)("div",{className:"flex items-start gap-2 text-(length:--text-micro) text-destructive",children:[(0,t.jsx)(Es,{className:"size-3 shrink-0"}),(0,t.jsx)("span",{children:Hte})]})]})]})}r(Nat,"SubmittedBrowserCodeLoginPanel");function Sat({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(Sat,"AdapterEnvironmentResult$1");function LSe({value:e,onChange:s,disabledTypes:n}){const[a,i]=(0,m.useState)(!1),o=Ch(e),l=(0,m.useMemo)(()=>RSe(c=>rN[c]??Ff(c)).filter(c=>!n.has(c.value)),[n]);return(0,t.jsxs)(gr,{open:a,onOpenChange:i,children:[(0,t.jsx)(Sr,{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.jsxs)("span",{className:"inline-flex min-w-0 items-center gap-1.5",children:[e==="opencode_local"?(0,t.jsx)(Bq,{className:"h-3.5 w-3.5"}):null,(0,t.jsx)("span",{className:"truncate",children:rN[e]??Ff(e)}),o.experimental&&(0,t.jsx)(Gte,{})]}),(0,t.jsx)(nn,{className:"h-3 w-3 text-muted-foreground"})]})}),(0,t.jsx)(dr,{className:"w-(--radix-popover-trigger-width) p-1",align:"start",children:l.map(c=>(0,t.jsxs)("button",{disabled:c.comingSoon,className:W("flex items-center justify-between w-full px-2 py-1.5 text-sm rounded",c.comingSoon?"opacity-40 cursor-not-allowed":"hover:bg-accent/50",c.value===e&&!c.comingSoon&&"bg-accent"),onClick:r(()=>{c.comingSoon||(s(c.value),i(!1))},"onClick"),children:[(0,t.jsxs)("span",{className:"inline-flex items-center gap-1.5",children:[c.value==="opencode_local"?(0,t.jsx)(Bq,{className:"h-3.5 w-3.5"}):null,(0,t.jsx)("span",{children:c.label}),c.experimental&&(0,t.jsx)(Gte,{})]}),c.comingSoon&&(0,t.jsx)("span",{className:"text-(length:--text-nano) text-muted-foreground",children:"Coming soon"})]},c.value))})]})}r(LSe,"AdapterTypeDropdown");function Gte(){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(Gte,"ExperimentalBadge$1");function $W({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,detectModelLabel:v,emptyDetectHint:j,defaultLabel:N}){const[w,k]=(0,m.useState)(""),[S,C]=(0,m.useState)(!1),I=e.find(E=>E.id===s),R=w.trim(),T=!!(u&&R&&!e.some(E=>E.id.toLowerCase()===R.toLowerCase())),A=(0,m.useMemo)(()=>{const E=new Set;h&&E.add(h);for(const z of p??[])z&&E.add(z);return E},[h,p]),D=(0,m.useMemo)(()=>e.filter(E=>{if(A.has(E.id))return!1;if(!w.trim())return!0;const z=w.toLowerCase(),$=qq(E.id)??"";return E.id.toLowerCase().includes(z)||E.label.toLowerCase().includes(z)||$.toLowerCase().includes(z)}),[e,w,A]),M=(0,m.useMemo)(()=>{if(!c)return[{provider:"models",entries:d?D:[...D].sort((z,$)=>z.id.localeCompare($.id))}];const E=new Map;for(const z of D){const $=qq(z.id)??"other",q=E.get($)??[];q.push(z),E.set($,q)}return Array.from(E.entries()).sort(([z],[$])=>z.localeCompare($)).map(([z,$])=>({provider:z,entries:[...$].sort((q,U)=>q.id.localeCompare(U.id))}))},[D,c,d]);async function B(){if(f){C(!0);try{const E=await f();E&&(n(E),i(!1),k(""))}finally{C(!1)}}}return r(B,"handleDetectModel"),(0,t.jsx)(Ss,{label:"Model",hint:Ni.model,children:(0,t.jsxs)(gr,{open:a,onOpenChange:r(E=>{i(E),E||k("")},"onOpenChange"),children:[(0,t.jsx)(Sr,{asChild:!0,children:(0,t.jsxs)("button",{type:"button",className:"inline-flex items-center gap-1.5 rounded-md border border-border px-2.5 py-1.5 text-sm hover:bg-accent/50 transition-colors w-full justify-between",children:[(0,t.jsx)("span",{className:W(!s&&"text-muted-foreground"),children:I?I.label:s||(o?N??"Default":l?"Select model (required)":"Select model")}),(0,t.jsx)(nn,{className:"h-3 w-3 text-muted-foreground"})]})}),(0,t.jsxs)(dr,{className:"w-(--radix-popover-trigger-width) p-1",align:"start",children:[(0,t.jsxs)("div",{className:"relative mb-1",children:[(0,t.jsx)("input",{className:"w-full px-2 py-1.5 pr-6 text-xs bg-transparent outline-none border-b border-border placeholder:text-muted-foreground/50",placeholder:u?"Search models... (type to create)":"Search models...",value:w,onChange:r(E=>k(E.target.value),"onChange"),autoFocus:!0}),w&&(0,t.jsx)("button",{type:"button",className:"absolute right-1.5 top-1/2 -translate-y-1/2 text-muted-foreground hover:text-foreground",onClick:r(()=>k(""),"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&&!w.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(()=>{B()},"onClick"),disabled:S,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"})]}),S?"Detecting...":h?v?.replace(/^Detect\b/,"Re-detect")??"Re-detect from config":v??"Detect from config"]}),x&&!w.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(E=>E.id===s)||A.has(s))&&(0,t.jsxs)("button",{type:"button",className:W("flex items-center w-full px-2 py-1.5 text-sm rounded bg-accent/50"),onClick:r(()=>{i(!1)},"onClick"),children:[(0,t.jsx)("span",{className:"block w-full text-left truncate font-mono text-xs",title:s,children:e.find(E=>E.id===s)?.label??s}),(0,t.jsx)(ct,{variant:"outline",className:"ml-auto text-(length:--text-nano) px-1.5 bg-green-500/15 text-green-400 border-green-500/20",children:"current"})]}),h&&h!==s&&(0,t.jsxs)("button",{type:"button",className:W("flex items-center w-full px-2 py-1.5 text-sm rounded hover:bg-accent/50"),onClick:r(()=>{n(h),i(!1)},"onClick"),children:[(0,t.jsx)("span",{className:"block w-full text-left truncate font-mono text-xs",title:h,children:e.find(E=>E.id===h)?.label??h}),(0,t.jsx)(ct,{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(E=>E&&E!==h&&E!==s).map(E=>{const z=e.find($=>$.id===E);return(0,t.jsxs)("button",{type:"button",className:W("flex items-center w-full px-2 py-1.5 text-sm rounded hover:bg-accent/50"),onClick:r(()=>{n(E),i(!1)},"onClick"),children:[(0,t.jsx)("span",{className:"block w-full text-left truncate font-mono text-xs",title:E,children:z?.label??E}),(0,t.jsx)(ct,{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-${E}`)}),(0,t.jsxs)("div",{className:"max-h-(--sz-240px) overflow-y-auto",children:[o&&(0,t.jsx)("button",{type:"button",className:W("flex items-center gap-2 w-full px-2 py-1.5 text-sm rounded hover:bg-accent/50",!s&&"bg-accent"),onClick:r(()=>{n(""),i(!1)},"onClick"),children:"Default"}),T&&(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(R),i(!1),k("")},"onClick"),children:[(0,t.jsx)("span",{children:"Use manual model"}),(0,t.jsx)("span",{className:"text-xs font-mono text-muted-foreground",children:R})]}),M.map(E=>(0,t.jsxs)("div",{className:"mb-1 last:mb-0",children:[c&&(0,t.jsxs)("div",{className:"px-2 py-1 text-(length:--text-nano) uppercase tracking-wide text-muted-foreground",children:[E.provider," (",E.entries.length,")"]}),E.entries.map(z=>(0,t.jsx)("button",{type:"button",className:W("flex items-center w-full px-2 py-1.5 text-sm rounded hover:bg-accent/50",z.id===s&&"bg-accent"),onClick:r(()=>{n(z.id),i(!1)},"onClick"),children:(0,t.jsx)("span",{className:"block w-full text-left truncate",title:z.id,children:c?jet(z.id):z.label})},z.id))]},E.provider)),D.length===0&&!T&&A.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:f?j??"No model detected yet. Enter a provider/model manually.":"No models found."})})]})]})]})})}r($W,"ModelDropdown");function Cat({value:e,options:s,onChange:n,open:a,onOpenChange:i}){const o=s.find(l=>l.id===e)??s[0];return(0,t.jsx)(Ss,{label:"Thinking effort",hint:Ni.thinkingEffort,children:(0,t.jsxs)(gr,{open:a,onOpenChange:i,children:[(0,t.jsx)(Sr,{asChild:!0,children:(0,t.jsxs)("button",{className:"inline-flex items-center gap-1.5 rounded-md border border-border px-2.5 py-1.5 text-sm hover:bg-accent/50 transition-colors w-full justify-between",children:[(0,t.jsx)("span",{className:W(!e&&"text-muted-foreground"),children:o?.label??"Auto"}),(0,t.jsx)(nn,{className:"h-3 w-3 text-muted-foreground"})]})}),(0,t.jsx)(dr,{className:"w-(--radix-popover-trigger-width) p-1",align:"start",children:s.map(l=>(0,t.jsxs)("button",{className:W("flex items-center justify-between w-full px-2 py-1.5 text-sm rounded hover:bg-accent/50",l.id===e&&"bg-accent"),onClick:r(()=>{n(l.id),i(!1)},"onClick"),children:[(0,t.jsx)("span",{children:l.label}),l.id?(0,t.jsx)("span",{className:"text-xs text-muted-foreground font-mono",children:l.id}):null]},l.id||"auto"))})]})})}r(Cat,"ThinkingEffortDropdown");function $Se(e){const s=`paperclip.agent-appearance.${e}`;function n(){try{const l=Dpe.safeParse(JSON.parse(sessionStorage.getItem(s)??"null"));if(l.success)return l.data}catch{}const o=VR();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($Se,"useAgentAppearanceDraft");var nC=null,V2=new Set,rC={subscribe(e){return V2.add(e),()=>{V2.delete(e)}},getSnapshot(){return nC},acquire(e){if(nC)return!1;nC=e;for(const s of V2)s();return!0},release(e){if(nC===e){nC=null;for(const s of V2)s()}}};function F_({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)(()=>AN(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)(rC.subscribe,rC.getSnapshot,()=>null),[k,S]=(0,m.useState)(!1),[C,I]=(0,m.useState)(!0),[R,T]=(0,m.useState)(!1),[A,D]=(0,m.useState)(!1),M=k&&!C&&!R&&o==="auto"&&a!=="rest";return(0,m.useEffect)(()=>{if(typeof matchMedia!="function"||typeof IntersectionObserver!="function")return;const B=matchMedia("(prefers-reduced-motion: reduce)"),E=r(()=>I(B.matches),"change");E(),B.addEventListener("change",E);const z=new IntersectionObserver($=>S($[0]?.isIntersecting??!1));return b.current&&z.observe(b.current),()=>{z.disconnect(),B.removeEventListener("change",E)}},[]),(0,m.useEffect)(()=>{M&&w===null&&rC.acquire(N.current),M||rC.release(N.current)},[M,w]),(0,m.useEffect)(()=>()=>rC.release(N.current),[]),(0,m.useEffect)(()=>{if(!M||w!==N.current)return;let B=!1;return D(!1),Promise.all([Jc(()=>import("./runtime-IAg0vdY9.js"),__vite__mapDeps([0,1])),Jc(()=>import("./definition-DWnXCBun.js"),__vite__mapDeps([2,3,1]))]).then(([E,z])=>{B||!v.current||(j.current=E.createCharacter(v.current,z.characterDefinition(x,i),{animation:z.animationId(a),trackingRegion:l?.current??b.current??void 0,followCursor:d,followRotation:u,trackingScope:c,displaySize:n,onError:r(()=>T(!0),"onError")}),D(!0))}).catch(()=>{B||T(!0)}),()=>{B=!0,j.current?.destroy(),j.current=null,D(!1)}},[M,w,l,c,n,d,u]),(0,m.useEffect)(()=>{j.current&&Jc(()=>import("./definition-DWnXCBun.js").then(B=>{j.current?.setDefinition(B.characterDefinition(x,i)),j.current?.setAnimation(B.animationId(a))}),__vite__mapDeps([2,3,1]))},[x,i,a,A]),(0,t.jsxs)("span",{ref:b,role:p?"img":void 0,"aria-label":p,"aria-hidden":p?void 0:!0,className:W("relative inline-block shrink-0",AFe[n],h),children:[(0,t.jsx)(kr,{agent:e,appearance:x,size:n<256?256:n,name:f,pose:a,muted:i,className:W("size-full",A&&"invisible")}),(0,t.jsx)("span",{ref:v,className:"absolute inset-0"})]})}r(F_,"AgentCharacter");var _at=new Set(["claude_local","codex_local","opencode_local","grok_local"]);function OSe(e,{cloud:s,nativeRunnerEnabled:n}){return e==="paperclip_runner"?n:s?_at.has(e):!0}r(OSe,"isNewAgentAdapterAllowed");var Iat={claude_local:{src:"/brands/claude-color.svg"},codex_local:{src:"/brands/codex-color.svg"},gemini_local:{src:"/brands/adapters/gemini-color.svg"},kimi_local:{src:"/brands/adapters/kimi-color-light.svg",dark:"/brands/adapters/kimi-color.svg"},...Object.fromEntries([["cursor","cursor"],["cursor_cloud","cursor"],["grok_local","grok"],["hermes_local","hermesagent"],["hermes_gateway","hermesagent"],["pi_local","pi"]].map(([e,s])=>[e,{src:`/brands/adapters/${s}.svg`,dark:`/brands/adapters/${s}-dark.svg`}]))};function OW({type:e,className:s="size-6"}){const n=Ch(e).icon,a=Iat[e];return a?(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)("img",{src:a.src,className:W("shrink-0 object-contain",a.dark&&"dark:hidden",s),alt:""}),a.dark&&(0,t.jsx)("img",{src:a.dark,className:W("hidden shrink-0 object-contain dark:block",s),alt:""})]}):(0,t.jsx)(n,{className:s})}r(OW,"AdapterMark");function Aat(){const{selectedCompanyId:e}=ps(),{appearance:s}=$Se(`${e}:new-agent`);return(0,t.jsx)(F_,{appearance:s,state:"sleepy",muted:!0,size:256,className:"size-48",trackingScope:"page"})}r(Aat,"AgentBasicsCharacter");function FSe({open:e,onClose:s,onContinue:n,initialAdapter:a="",onInvite:i}){const o=(0,m.useId)(),l=!!$c(),c=Z({queryKey:P.instance.experimentalSettings,queryFn:Nr.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}=Z({queryKey:P.adapters.all,queryFn:uh.list,enabled:e}),k=(j??[]).filter(C=>C.loaded&&!C.disabled&&OSe(C.type,{cloud:l,nativeRunnerEnabled:c.data?.enableNativeRunner===!0})&&!["process","http"].includes(C.type)&&!Ch(C.type).comingSoon),S=k.some(C=>C.type===h);return(0,t.jsx)(Qs,{open:e,onOpenChange:r(C=>{C||s()},"onOpenChange"),children:(0,t.jsxs)(Js,{className:W("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:W(b==="name"&&"font-medium text-foreground"),children:"1. Name"}),(0,t.jsx)(Rn,{className:"size-3"}),(0,t.jsx)("span",{className:W(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,runnerProvider: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)(Aat,{}),(0,t.jsxs)("div",{className:"space-y-2",children:[(0,t.jsx)(Xs,{className:"text-3xl font-semibold tracking-tight",children:b==="name"?"Meet your next agent":"Choose an adapter"}),(0,t.jsx)(jn,{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)(ht,{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)(L,{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:W("grid grid-cols-2 gap-3",k.length!==4&&"sm:grid-cols-3"),children:k.map(C=>{const I=Ch(C.type);return(0,t.jsxs)("label",{className:"relative cursor-pointer",children:[(0,t.jsx)("input",{type:"radio",name:"new-agent-adapter",value:C.type,checked:h===C.type,onChange:r(()=>p(C.type),"onChange"),className:"peer sr-only"}),(0,t.jsxs)("span",{className:W("flex h-full flex-col items-center gap-2 rounded-lg border px-3 py-4 text-center peer-focus-visible:ring-2 peer-focus-visible:ring-ring hover:bg-accent/40",h===C.type?"border-foreground/40 bg-accent":"border-border bg-card"),children:[(0,t.jsx)(OW,{type:C.type}),(0,t.jsx)("span",{className:"text-sm font-medium",children:I.label}),h===C.type&&(0,t.jsx)(gs,{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)(L,{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)(Tl,{className:"size-4"}),"Back"]})}),(0,t.jsxs)(L,{type:"submit",disabled:!d.trim()||b==="adapter"&&!S,children:[b==="name"?"Choose adapter":"Configure agent",(0,t.jsx)(pl,{className:"size-4"})]})]})]})]})})}r(FSe,"AgentBasicsDialog");var Tat={subscription:"Subscription",api:"API"};function Rat({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)(rS,{initial:!1,mode:"sync",children:(0,t.jsx)(Il.span,{className:"absolute inset-0 flex items-center justify-center whitespace-nowrap",initial:{opacity:0,y:dte},animate:{opacity:1,y:0,transition:ZZe},exit:{opacity:0,y:dte,transition:eet},children:Tat[e]},e)})})}r(Rat,"CredentialTag");function Eat({source:e,mode:s,selected:n,onSelect:a,buttonRef:i,settling:o}){return(0,t.jsxs)("button",{ref:i,type:"button",role:"radio","aria-checked":n,onClick:a,className:W("flex min-w-0 flex-1 cursor-pointer flex-col items-center gap-1.5 self-stretch rounded-md border p-3","transition-(--tp-border-color-background-color) ease-(--motion-ease-standard)",o?"duration-(--motion-duration-slow)":"duration-(--motion-duration-fast)","outline-none focus-visible:ring-ring/50 focus-visible:ring-(length:--rad-3)",n?"border-foreground/40 bg-accent":"border-border bg-card hover:bg-accent/40"),children:[(0,t.jsx)("span",{className:"flex size-(--sz-30px) shrink-0 items-center justify-center",children:e.icon}),(0,t.jsx)("span",{className:"text-(length:--text-compact) font-medium text-foreground",children:e.label}),(0,t.jsx)(Rat,{mode:s})]})}r(Eat,"ModelSourceTile");function BSe({sources:e,mode:s,selectedId:n,onSelect:a,label:i,collapsed:o=!1,settling:l=!1}){const c=(0,m.useRef)(new Map),d=r(h=>{if(e.length===0)return;const p=e.findIndex(x=>x.id===n),f=e[((p===-1?h>0?-1:0:p)+h+e.length)%e.length];a(f.id),c.current.get(f.id)?.focus()},"moveSelection"),u=o?e.filter(h=>h.id===n):e;return(0,t.jsx)("div",{role:"radiogroup","aria-label":i,className:W("flex items-start gap-3",o&&"justify-center"),onKeyDown:r(h=>{o||(h.key==="ArrowRight"||h.key==="ArrowDown"?(h.preventDefault(),d(1)):(h.key==="ArrowLeft"||h.key==="ArrowUp")&&(h.preventDefault(),d(-1)))},"onKeyDown"),children:(0,t.jsx)(rS,{initial:!1,mode:"popLayout",children:u.map(h=>(0,t.jsx)(Il.div,{layout:!0,transition:BNe,exit:{opacity:0,transition:uet},className:W("flex min-w-0",o?"w-(--sz-source-tile-two-up)":"flex-1"),children:(0,t.jsx)(Eat,{source:h,mode:s,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(BSe,"ModelSourceTiles");var W$={subscription:"Use API key instead",api:"Use subscription instead"},Pat={subscription:"api",api:"subscription"};function zSe({mode:e,onChange:s}){return(0,t.jsxs)("button",{type:"button",onClick:r(()=>s(Pat[e]),"onClick"),className:W("group grid cursor-pointer px-3 py-2 text-left text-sm font-medium","rounded-md outline-none focus-visible:ring-ring/50 focus-visible:ring-(length:--rad-3)"),children:[Object.keys(W$).map(n=>(0,t.jsx)("span",{"aria-hidden":!0,className:"invisible col-start-1 row-start-1 whitespace-nowrap",children:W$[n]},n)),(0,t.jsx)(rS,{initial:!1,mode:"sync",children:(0,t.jsx)(Il.span,{className:W("col-start-1 row-start-1 justify-self-start whitespace-nowrap","underline decoration-muted-foreground/40 underline-offset-4","text-muted-foreground transition-colors","group-hover:text-foreground group-hover:decoration-foreground/40"),initial:{opacity:0},animate:{opacity:1,transition:SW},exit:{opacity:0,transition:tet},children:W$[e]},e)})]})}r(zSe,"CredentialModeLink");function qSe({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)(L,{variant:"ghost",size:"lg",className:"rounded-full has-[>svg]:pl-4 has-[>svg]:pr-5",onClick:e,disabled:a,children:[(0,t.jsx)(Tl,{className:"mr-1 size-3.5"}),"Back"]}):(0,t.jsx)("span",{}),(0,t.jsx)(Il.div,{layout:!0,transition:ret,className:"min-w-0",children:(0,t.jsx)(L,{size:"lg",className:"w-full rounded-full px-6",onClick:l,disabled:n||a,children:(0,t.jsxs)(Il.span,{className:"flex items-center whitespace-nowrap",initial:{opacity:0},animate:{opacity:1},transition:aet,children:[d==="spinner"?(0,t.jsx)(rt,{className:"mr-1 size-4 animate-spin"}):null,c,d==="arrow"?(0,t.jsx)(pl,{className:"ml-1 size-3.5"}):null]},`${c}:${d}`)})})]})}r(qSe,"FooterNav");function USe({companyId:e,adapterType:s,environmentId:n,canLogin:a,localEnvironment:i=!1,onConnected:o,onBack:l,testConnection:c,testError:d,managedAccount:u}){const h=Z({queryKey:P.health,queryFn:tu.get,enabled:i}),p=i&&(h.data?.localAiLoginSupported??h.data?.deploymentMode==="local_trusted"),f=(0,m.useRef)(0);(0,m.useEffect)(()=>()=>{f.current++},[]);const x=r(()=>{f.current++,D(!1),N(!1),k(null),C("preparing")},"cancel"),[b,v]=(0,m.useState)(u?.initialMethod==="api_key"?"api":u?"subscription":null),[j,N]=(0,m.useState)(!1),[w,k]=(0,m.useState)(null),[S,C]=(0,m.useState)("preparing"),I=(0,m.useRef)("ready"),[R,T]=(0,m.useState)(""),[A,D]=(0,m.useState)(!1),[M,B]=(0,m.useState)(null),[E,z]=(0,m.useState)(null),$=s==="claude_local"?"Claude":s==="grok_local"?"Grok":"OpenAI",q=s==="claude_local"?"ANTHROPIC_API_KEY":s==="grok_local"?"XAI_API_KEY":"OPENAI_API_KEY",U=s==="claude_local"?"anthropic":s==="grok_local"?"xai":"openai",O=gNe(e,q),K=u?{...O,options:[],subscriptions:[],loading:!1}:O,[H,ee]=(0,m.useState)(null),se=K.subscriptions.length?K.subscriptions.find(ge=>ge.id===(H??K.subscriptions[0]?.id)):void 0,[ne,fe]=(0,m.useState)(null),X=K.options.find(ge=>ge.id===(ne??K.options[0]?.id)),re=u?{...K.storedLogin,data:void 0,isPending:!1,isError:!1}:K.storedLogin,oe=(0,m.useRef)(null),G=b??(K.subscriptions.length>0||s==="claude_local"&&!se&&re.data?"subscription":K.options.length?"api":"subscription"),Y=G==="api"?"api_key":"subscription",Q=u?.intent.connectionId&&(u.fixedMethod!==!1||u.initialMethod===Y),te=u?{...u.intent,connectionId:Q?u.intent.connectionId:void 0,name:Q?u.intent.name:u.nameForMethod?.(Y)??u.intent.name}:void 0,ae=Dwe(e,te??{provider:U,method:"subscription",name:`My ${$} subscription`,ownership:"personal",agentIds:[],allAgents:!0},p&&G==="subscription"&&!se&&!re.data,{allowHostClaude:h.data?.deploymentMode==="local_trusted"}),le=Z({queryKey:P.agents.authSignal(e,s,n),queryFn:r(()=>$t.getAdapterAuthSignal(e,s,n??void 0),"queryFn"),retry:!1,enabled:!u});async function he(){if(A||u?.disabled)return;const ge=++f.current;D(!0),B(null);try{if(u&&te){if(G==="subscription"&&!p)return;const ue=oe.current??await(G==="api"?Yc.create(e,{...te,method:"api_key",apiKey:R.trim()}):ae.connect(te));oe.current=ue,T(""),ge===f.current&&u.onComplete({...ue,method:G==="api"?"api_key":"subscription"});return}let me=G==="api"?X?X.aiConnection?{env:{},aiConnection:X.aiConnection}:{env:{[q]:X.binding}}:E??{env:{},credentials:{[q]:R.trim()}}:{...se?.aiConnection?{aiConnection:se.aiConnection}:{},env:se?.binding?{CODEX_HOME:se.binding}:{},...s==="claude_local"&&!se&&re.data?{env:Vw(),applyStoredClaudeLogin:!0}:{}};if(G==="subscription"&&p&&!se&&!re.data&&(oe.current??=await ae.connect(),me={env:{},aiConnection:{provider:U,method:"subscription",mode:"responsible_user"}}),me.credentials&&(await Yc.create(e,{provider:U,method:"api_key",name:`My ${$} API`,ownership:"personal",apiKey:me.credentials[q],agentIds:[],allAgents:!0}),me={env:{},aiConnection:{provider:U,method:"api_key",mode:"responsible_user"}}),ge!==f.current)return;G==="api"&&(T(""),X||z(me));const ie=await c(me);if(ge!==f.current)return;ie?o(me):B("The provider did not respond. Check the connection and try again.")}catch(me){if(ge!==f.current)return;u&&T(""),B(me instanceof Error?me.message:"Could not connect to the provider.")}finally{ge===f.current&&D(!1)}}r(he,"connect");const ce=G==="subscription"&&a&&n&&!se&&!K.loading&&!re.data&&(!!u||le.data?.status!=="present"||H==="");return(0,t.jsxs)("div",{className:"min-w-0 max-w-full",children:[(0,t.jsx)(BSe,{label:"Connect your model provider",sources:[{id:s,label:$,icon:(0,t.jsx)(OW,{type:s})}],mode:G,selectedId:j?s:null,collapsed:j,onSelect:r(()=>{u?.disabled||N(!0)},"onSelect")}),(!j||u)&&!u?.fixedMethod&&(0,t.jsx)("div",{className:"-ml-3 mt-1",children:(0,t.jsx)(zSe,{mode:G,onChange:r(ge=>{x(),N(j),oe.current=null,v(ge),T(""),z(null),B(null)},"onChange")})}),!j&&K.options.length>0&&(0,t.jsxs)("p",{className:"mt-2 text-sm text-muted-foreground",children:[K.options.length," saved API"," ",K.options.length===1?"key available":"keys available","."]}),G==="subscription"&&K.subscriptions.length>0&&(0,t.jsx)(gk,{options:K.subscriptions,value:se?.id??"",onChange:ee,loading:!1,error:!1,kind:"subscription",disabled:A}),(0,t.jsx)(Il.div,{initial:!1,animate:{height:j?"auto":0,opacity:j?1:0},transition:{height:Id,opacity:t4},className:"overflow-hidden",children:j&&(0,t.jsx)("div",{className:"pt-5",children:G==="api"?(0,t.jsxs)(s4,{instruction:K.options.length?"Choose a saved API key or enter a new one":`Provide your ${$} API key to connect`,children:[(0,t.jsx)(gk,{...K,value:X?.id??"",disabled:A,onChange:r(ge=>{fe(ge),T(""),z(null),B(null)},"onChange")}),!X&&(0,t.jsx)(n4,{label:"API key",masked:!0,autoFocus:!0,value:R,placeholder:E?"Key entered. Retry the connection.":"Enter API key here",onChange:r(ge=>{fe(""),T(ge),z(null)},"onChange"),onSubmit:r(()=>{he()},"onSubmit"),disabled:A})]}):ce?(0,t.jsx)(LW,{companyId:e,adapterType:s,environmentId:n,chrome:"onboarding",aiConnection:te??{provider:U,method:"subscription",name:`My ${$} subscription`,ownership:"personal",agentIds:[],allAgents:!0},autoStart:!0,onStored:r(()=>{},"onStored"),onPromptReady:r(ge=>{k(ge),C(me=>ge?me==="preparing"?"ready":me:"preparing")},"onPromptReady"),onCodeSubmitted:r(()=>{I.current=S==="waiting"?"waiting":"ready",C("connecting")},"onCodeSubmitted"),onSubmitFailed:r(()=>{C(ge=>ge==="connecting"?I.current:ge)},"onSubmitFailed"),onConnected:r(ge=>{if(u){if(!ge){B("The login did not return a saved connection. Try again.");return}const ie=f.current;C("connecting"),Yc.loginResult(e,ge).then(ue=>{ie===f.current&&u.onComplete({...ue,method:"subscription"})}).catch(()=>{ie===f.current&&(C("ready"),B("Could not retrieve the saved connection. Go back and retry."))});return}const me={env:{},aiConnection:{provider:U,method:"subscription",mode:"responsible_user"}};z(me),o(me)},"onConnected")}):se?null:p&&!re.data?(0,t.jsx)(CW,{adapterType:s,login:{...ae,retry:r(()=>{B(null),ae.retry()},"retry")}}):(0,t.jsx)("p",{className:"text-sm text-muted-foreground",children:re.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."})})}),G==="subscription"&&re.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:d??M}),i&&h.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)(qSe,{onBack:r(()=>{j?x():l()},"onBack"),primaryLabel:j&&ce?S==="waiting"?"Waiting for code":S==="connecting"?"Connecting":`Sign in to ${$}`:A?"Connecting":G==="subscription"&&(re.data||se)?"Use saved subscription":G==="api"&&X?"Use saved API key":"Connect",primaryDisabled:u?.disabled||!!u&&G==="subscription"&&!a&&!p||i&&h.isPending||ae.preparing||!!ae.error||!u&&le.isPending||K.loading||s==="claude_local"&&re.isPending||!j&&!(G==="subscription"&&se)||!!ce&&(!w||S!=="ready")||G==="api"&&!R.trim()&&!E&&!X,loading:A,primaryIcon:j&&ce?S==="ready"?"none":"spinner":void 0,onPrimary:r(()=>{if(ce){if(!w||S!=="ready")return;window.open(w,"_blank","noreferrer,noopener"),C("waiting")}else he()},"onPrimary")})]})}r(USe,"AgentProviderConnection");function P5(e){return e.provider==="openrouter"?(0,t.jsx)(Dat,{...e}):(0,t.jsx)(Mat,{...e})}r(P5,"AiConnectionCredentialStep");function Mat({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}){const[b,v]=(0,m.useState)(o),[j,N]=(0,m.useState)(),w=Dt(),k=Z({queryKey:P.environments.list(e),queryFn:r(()=>Pi.list(e),"queryFn")}),S=Z({queryKey:P.environments.capabilities(e),queryFn:r(()=>Pi.capabilities(e),"queryFn")}),C=Z({queryKey:P.instance.settings,queryFn:Nr.get}),I=Z({queryKey:P.instance.experimentalSettings,queryFn:Nr.getExperimental}),R=Z({queryKey:P.instance.generalSettings,queryFn:Nr.getGeneral}),T=DW(R.data?.executionMode,k.data??[]);let A=null,D;try{A=T.forced?T.kubernetesEnvironment?.id??null:iN({agentDefaultEnvironmentId:p??j,instanceDefaultEnvironmentId:C.data?.defaultEnvironmentId,localDefaultEnvironmentId:lN(k.data),managedSandboxOnly:I.data?.enableManagedSandboxOnly,managedSandboxEnvironmentId:oN(k.data),visibleEnvironmentIds:k.data?.map(O=>O.id)})}catch(O){D=O instanceof Error?O.message:"Could not resolve the sign-in environment."}const M=(k.data??[]).filter(O=>O.status==="active"&&(O.driver==="local"||O.driver==="sandbox"&&typeof O.config.provider=="string"&&S.data?.sandboxProviders?.[O.config.provider]?.supportsLoginPty===!0));!T.forced&&!p&&!j&&!M.some(O=>O.id===A)&&(A=M[0]?.id??null);const B=k.data?.find(O=>O.id===A),E=typeof B?.config.provider=="string"?B.config.provider:"",z=B?.driver==="sandbox"&&S.data?.sandboxProviders?.[E]?.supportsLoginPty===!0,$=[k,S,C,I,R].some(O=>O.isPending),q=D??[k,S,C,I,R].find(O=>O.error)?.error?.message,U={provider:s,method:"subscription",name:b,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)(ht,{value:b,onChange:r(O=>v(O.target.value),"onChange"),disabled:!!i})]}),!p&&!T.forced&&M.length>1&&(0,t.jsxs)($a,{value:A??"",onValueChange:N,children:[(0,t.jsx)(La,{"aria-label":"Sign-in environment",children:(0,t.jsx)(Ma,{placeholder:"Sign-in environment"})}),(0,t.jsx)(Da,{children:M.map(O=>(0,t.jsx)(Nn,{value:O.id,children:O.name},O.id))})]}),q&&(0,t.jsx)("p",{role:"alert",className:"text-sm text-destructive",children:q}),$?(0,t.jsx)("p",{role:"status",className:"text-sm text-muted-foreground",children:"Preparing sign-in…"}):(0,t.jsx)(USe,{companyId:e,adapterType:s==="anthropic"?"claude_local":s==="xai"?"grok_local":"codex_local",environmentId:A,canLogin:z,localEnvironment:B?.driver==="local",onBack:x,onConnected:r(()=>{},"onConnected"),testConnection:r(async()=>!1,"testConnection"),managedAccount:{intent:U,nameForMethod:c,initialMethod:n,fixedMethod:a??!!i,disabled:$||!!q||!b.trim(),onComplete:r(O=>{w.invalidateQueries({queryKey:["ai-connections",e]}),f(O)},"onComplete")}},A??"local")]})}r(Mat,"SubscriptionConnectionStep");function Dat({companyId:e,provider:s,connectionId:n,name:a,hideName:i,nameForMethod:o,ownership:l,agentIds:c,allAgents:d,onComplete:u,onCancel:h}){const[p,f]=(0,m.useState)(a),[x,b]=(0,m.useState)(""),v=Dt(),j=je({mutationFn:r(()=>Yc.create(e,{provider:s,method:"api_key",name:n?p:o?.("api_key")??p,ownership:l,agentIds:c,allAgents:d,connectionId:n,apiKey:x}),"mutationFn"),onSuccess:r(N=>{v.invalidateQueries({queryKey:["ai-connections",e]}),u({...N,method:"api_key"})},"onSuccess"),onSettled:r(()=>b(""),"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)(ht,{value:p,onChange:r(N=>f(N.target.value),"onChange"),disabled:!!n})]}),j.error&&(0,t.jsx)("p",{role:"alert",className:"text-sm text-destructive",children:j.error.message}),(0,t.jsx)(KNe,{providerName:"OpenRouter",value:x,onChange:b,onSubmit:r(()=>j.mutate(),"onSubmit"),disabled:j.isPending,placeholder:"Enter API key here",autoFocus:!0}),(0,t.jsxs)("div",{className:"flex justify-between gap-2",children:[(0,t.jsx)(L,{variant:"ghost",onClick:h,children:"Cancel"}),(0,t.jsx)(L,{disabled:!p.trim()||!x.trim()||j.isPending,onClick:r(()=>j.mutate(),"onClick"),children:j.isPending?"Connecting…":"Connect"})]})]})}r(Dat,"ApiKeyConnectionStep");var Lat=null;function iS(){const e=(0,m.useContext)(SI),{data:s,isFetched:n,isError:a}=Z({queryKey:P.instance.experimentalSettings,queryFn:r(()=>Nr.getExperimental(),"queryFn"),enabled:e!=null},e??(Lat??=new zN));return e?{enabled:!a&&s?.enableChatConnectors===!0,loaded:n}:{enabled:!1,loaded:!0}}r(iS,"useChatConnectorsEnabled");var $at=new RegExp(`\\b(${["mcp","server","profile","policy","gateway","transport","stdio","endpoint"].join("|")})s?\\b`,"gi");function KSe(e){return e.replace($at,"").replace(/\s{2,}/g," ").replace(/\s+([.,])/g,"$1").trim()}r(KSe,"sanitizeProsumerCopy");var Oat={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."},neon:{tagline:"Manage Postgres projects, branches, and queries.",short:"Sign in with Neon. Project pinning and read-only mode are optional."},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."}},Fat={tagline:"Give your agents access to this app.",short:"Give your agents access to this app."};function WSe(e,s){const n=Oat[e];if(n)return n;if(s){const a=KSe(s);if(a)return{tagline:a,short:a}}return Fat}r(WSe,"appCopyFor");function Qte(e,s,n){return n<=1?`Your ${e} key`:KSe(s)||`Your ${e} key`}r(Qte,"credentialFieldLabel");var Bat=1500;function Cp(e=Bat){const[s,n]=(0,m.useState)("idle"),a=(0,m.useRef)(null),i=(0,m.useRef)(0);(0,m.useEffect)(()=>()=>{a.current!==null&&window.clearTimeout(a.current)},[]);const o=(0,m.useCallback)(async l=>{const c=++i.current;let d="copied";try{await fa(l)}catch{d="failed"}return i.current!==c||(n(d),a.current!==null&&window.clearTimeout(a.current),a.current=window.setTimeout(()=>{i.current===c&&(n("idle"),a.current=null)},e)),d},[e]);return{status:s,copied:s==="copied",failed:s==="failed",copy:o}}r(Cp,"useCopyAction");function FW(){const e=Xc()?.pushToast;return(0,m.useCallback)(async(s,n="Copied")=>{try{return await fa(s),e?.({title:n,tone:"success",dedupeKey:`copy:${n}`}),!0}catch{return e?.({title:"Couldn’t copy to clipboard",body:"Select and copy the value manually.",tone:"error",dedupeKey:"copy-failed"}),!1}},[e])}r(FW,"useCopyToast");var zat="/cloud/connections/handoff",qat="/cloud/connections/reauth",M5="paperclip.cloud-oauth-handoff.v1",sg=class extends Error{static{r(this,"OAuthHandoffError")}code;constructor(e,s){super(e),this.code=s,this.name="OAuthHandoffError"}};function BW(e){if(e===void 0)return null;if(!e||typeof e!="object"||Array.isArray(e))throw new sg("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 sg("Paperclip Cloud returned an invalid sign-in handoff.","invalid_handoff");return{kind:"paperclip_cloud",session:s.session}}r(BW,"parseHandoff");function Uat(e,s){return e===404||s==="SESSION_NOT_AVAILABLE"?new sg("This sign-in expired. Start the connection again.","expired"):e===401||e===403?new sg("Paperclip Cloud could not authorize this connection for your account.","forbidden"):new sg("Paperclip Cloud couldn’t prepare secure sign-in. Try again.","unavailable")}r(Uat,"handoffFailure");async function Kat(e,s){const n=s.request??fetch;let a,i;for(let o=0;o<2;o+=1)try{if(a=await n(zat,{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 sg(i instanceof Error?i.message:"Paperclip Cloud couldn’t prepare secure sign-in. Try again.","unavailable")}r(Kat,"postCloudHandoff");function Wat(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!==qat||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(Wat,"exactReauthenticationTarget");async function dN(e,s={}){const n=BW(e.handoff);if(!n){const l=o5(e.authorizationUrl);if(!l.ok)throw new sg(l.message,"invalid_handoff");return{kind:"authorization",url:l.url,host:l.host}}const a=await Kat(n.session,s),i=await a.json().catch(()=>null);if(!a.ok){if(i?.error==="RECENT_LOGIN_REQUIRED"){const l=Wat(i.reauthenticationUrl,n.session);if(l)return l}throw Uat(a.status,i?.error)}const o=o5(typeof i?.authorizationUrl=="string"?i.authorizationUrl:void 0);if(!o.ok)throw new sg("Paperclip Cloud returned an invalid provider sign-in address.","invalid_handoff");return{kind:"authorization",url:o.url,host:o.host}}r(dN,"prepareOAuthNavigation");function B_(e,s=window.sessionStorage){const n=BW({kind:"paperclip_cloud",session:e});if(!n)throw new sg("Paperclip Cloud returned an invalid sign-in handoff.","invalid_handoff");const a={version:1,session:n.session,savedAt:Date.now()};s.setItem(M5,JSON.stringify(a))}r(B_,"savePendingCloudHandoff");function Vat(e=window.sessionStorage){const s=e.getItem(M5);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 BW({kind:"paperclip_cloud",session:n.session})}catch{return e.removeItem(M5),null}}r(Vat,"readPendingCloudHandoff");function Yte(e=window.sessionStorage){e.removeItem(M5)}r(Yte,"clearPendingCloudHandoff");function l4(e){return!!(e&&Mpe({...e,methods:e.methods.filter(s=>(s.purpose??"tool")!=="channel"&&s.transport!=="chat_sdk")}))}r(l4,"appSupportsToolCatalogSetup");var Hat=xLe.filter(e=>Rpe(e).some(s=>rp(s))).map(e=>e.slug);function Gat(e){return Hat.some(s=>s===e)}r(Gat,"isMcpDirectOAuthConnectSlug");function z_(e,s){const n=new URLSearchParams({source:e});return s&&n.set("intent",s),`/apps/connect?${n.toString()}`}r(z_,"appSourceConnectHref");function Qat(e,s){return`/apps/connect?${new URLSearchParams({source:e,resume:s}).toString()}`}r(Qat,"appSourceResumeHref");function V$(e){return e?`/apps/vercel-connect?${new URLSearchParams({source:e}).toString()}`:"/apps/vercel-connect"}r(V$,"vercelConnectSourceHref");function Yat(e){return e.serviceSlug??e.appKey??e.sourceSlug??void 0}r(Yat,"resolveAppsConnectRouteKey");function Jat(e,{chatConnectorsEnabled:s=!1}={}){if(e.get("byo")==="1")return!!(e.get("reconnect")?.trim()&&e.get("applicationId")?.trim()&&e.get("link")?.trim());const n=e.get("source")??"";if(/^ai-router-(?:[a-f0-9]{2})+$/.test(n))return!0;const a=TN(n);return!s&&a?.methods.some(i=>i.transport==="chat_sdk")&&!a.methods.some(i=>(i.purpose??"tool")!=="channel"&&i.transport!=="chat_sdk")?!1:NI(n)&&e.get("reconnect")?.trim()?!0:n==="agentmail"||s?Mpe(a):l4(a)}r(Jat,"canEnterAppsConnect");var H$=" for the organization",Xat=" for the company";function Jte(e,s){const n=e.trim();if(s!=="organization")return n;const a=n.toLocaleLowerCase();return a.endsWith(H$)?n:a.endsWith(Xat)?`${n.slice(0,n.length-16).trimEnd()}${H$}`:`${n}${H$}`}r(Jte,"connectionNameForGrantKind");function Zat(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(Zat,"grantStatusLabel");function eit(e){switch(e){case"active":return"connected";case"needs_reauthorization":case"expired":return"attention";case"revoked":return"inactive";default:return"missing"}}r(eit,"grantStatusTone");function tit(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(tit,"grantAccountLabel");function sit(e){return new Set((e?.members??[]).filter(s=>s.subjectType==="user").map(s=>s.subjectId))}r(sit,"audienceUserIds");function nit(e){return e.find(s=>s.kind==="organization"&&s.isDefault)??e.find(s=>s.kind==="organization")??null}r(nit,"organizationGrant");function rit(e,s){return s?e.find(n=>n.kind==="user"&&n.subjectUserId===s)??null:null}r(rit,"personalGrantFor");function ait(e,s){if(!s)return null;const n=e.find(a=>a.userId===s);return n&&(n.name?.trim()||n.email?.trim())||null}r(ait,"memberLabel");var Xte=0;function i6(){return Xte+=1,{id:`header-${Xte}`,name:"",value:""}}r(i6,"newCustomHeaderRow");function M1(e){try{return new URL(e).host||null}catch{return null}}r(M1,"endpointHost");function VSe(e=window.location.origin){const s=new URL("/api/tools/oauth/callback",e),n=s.hostname.toLowerCase().replace(/^\[|\]$/g,"");return s.protocol==="http:"&&(n==="127.0.0.1"||n==="::1")&&(s.hostname="localhost"),s.toString()}r(VSe,"oauthCallbackUrlForBrowser");function G$(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(G$,"defaultGenericMcpName");function Zte(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(Zte,"genericConnectGuidance");function HSe(e){const s=new Set;for(const n of e){const a=n.name.trim();if(!a&&!n.value.trim())continue;const i=FLe(a);if(!i.ok)return EJ(a,i.reason);const o=KLe(n.value);if(!o.ok)return EJ(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(HSe,"customHeaderError");function iit(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(iit,"genericConnectPayload");function oit(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&&HSe(e.headers)===null:!0:!1}r(oit,"canSubmitGenericConnect");function uN(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(uN,"installStateFrom");function GSe(e,s){return e.onAll||e.agentIds.has(s)}r(GSe,"isAgentInstalled");function QSe(e,s){return s.onAll?[{targetType:"company",targetId:e}]:[...s.agentIds].map(n=>({targetType:"agent",targetId:n}))}r(QSe,"installPayload");var lit="Has access — tick to load its tools into this agent's context.";function YSe(e){return`paperclip.connector-enrollment-access:${e}`}r(YSe,"enrollmentAccessStorageKey");function cit(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(cit,"validEnrollmentAccessState");function dit(e,s,n){try{window.sessionStorage.setItem(YSe(s),JSON.stringify({...n,companyId:e}))}catch{}}r(dit,"saveEnrollmentAccessState");function uit(e){const s=YSe(e);try{const n=window.sessionStorage.getItem(s);if(window.sessionStorage.removeItem(s),!n)return null;const a=JSON.parse(n);return cit(a)?a:null}catch{return null}}r(uit,"consumeEnrollmentAccessState");function ese(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(ese,"githubRecoveryUrl");function tse(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(tse,"oauthCallbackErrorMessage");var mit={key:"setup",success:"complete"};function sse(e){return e.requestedAppKey||e.hasPrefilledLink||e.zapierSource?"key":"gallery"}r(sse,"requestedConnectionInitialStep");function hit(e){const s=e.galleryApps.find(a=>a.slug===e.requestedAppKey);if(s)return s;if(!e.reconnectConnection)return null;const n=e.applications.find(a=>a.id===e.reconnectConnection?.applicationId);return fg(n)!==e.requestedAppKey?null:NI(e.requestedAppKey)}r(hit,"requestedConnectionEntry");function pit(e){return!e.reconnectConnection||!e.reconnectApplication||e.reconnectConnection.applicationId!==e.reconnectApplication.id?!1:e.requestedAppKey?fg(e.reconnectApplication)===e.requestedAppKey:e.byo&&e.applicationId===e.reconnectApplication.id}r(pit,"retainedReconnectMatches");function fit(e){return e.credentialSource==="vercel_connect"&&!e.available&&!e.retainedReconnectMatches}r(fit,"isVercelConnectUnavailable");function xit(e){return e.available===!1&&!(e.reconnectConnectionId&&e.reconnectSourceMatches)}r(xit,"isConnectionDefinitionUnavailable");function git(e){return!e.hasRequestedEntry||e.supportedMethodCount===0||e.unsupportedOAuth||e.vercelUnavailable||e.definitionUnavailable?e.reconnectConnectionId?"reconnect_unavailable":"fallback":"ready"}r(git,"requestedConnectionSetupResolution");function nse(e,s,n,a){const i=mit[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(nse,"appConnectHref");function H2(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(H2,"withConnectionIntent");var rse=["Pick app","Add your key"],ase={gallery:0,key:1},bit={key:0},vit=["Add MCP URL"],yit=["Sign in"];function Q$(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(Q$,"defaultGrantKindFor");function jit(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(jit,"configuredAgentIdentity");function GC(e,s){const n=typeof s=="string"?s:s?.key;return e?.slug==="google-sheets"&&n==="local"}r(GC,"isGoogleSheetsRobotMethod");function aC(e){return e?Object.fromEntries([...e.tenantFields??[],...e.extensionFields??[]].filter(s=>s.defaultValue!==void 0).map(s=>[s.key,s.defaultValue])):{}}r(aC,"defaultMethodConfig");function Aw(e,s){if(!e)return[];const n=hA(e);return s==="vercel_connect"?n.filter(a=>!!a.credentialSources?.vercelConnect):n}r(Aw,"connectionMethodsForCredentialSource");function hA(e){return Rpe(e).filter(s=>(s.purpose??"tool")!=="channel")}r(hA,"availableToolConnectionMethods");function G2(e,s){const n=hA(e);return s?n.find(a=>a.key===s)??null:s7(n)}r(G2,"availableToolConnectionMethod");function vk(e){return s7(e)}r(vk,"recommendedSetupConnectionMethod");function ise(e){return vk(e?e.methods.filter(s=>(s.purpose??"tool")==="tool"&&(s.oauthStrategy==="paperclip_cloud_connector"||s.oauthStrategy==="paperclip_id_connector")):[])}r(ise,"recommendedManagedConnectorMethod");function ose(e){if(!e)return!1;const s=hA(e),n=s.length===1?s[0]:null;return!!(n&&rp(n)&&!y$e(n))}r(ose,"canUseAutomaticOAuthFastPath");function lse(e){if(!e)return null;const s=hA(e),n=s.length===1?s[0]:null;return n&&rp(n)?n:null}r(lse,"automaticOAuthMethod");function wit(e){const s=e.metadata;if(!s)return null;const n=s.sourceTemplateKey??s.galleryKey;return typeof n=="string"?n:null}r(wit,"appSourceSlug");function kit(e){const s=e.config?.sourceTemplateKey??e.transportConfig.sourceTemplateKey;return typeof s=="string"?s:null}r(kit,"connectionSourceSlug");function cse(e,s,n,a={}){if(!e)return null;const i=new Set(s.filter(o=>o.status!=="archived"&&wit(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)||kit(o)===e;return o.status!=="archived"&&(!a.draftOnly||o.status==="draft")&&o.authKind==="oauth"&&l})??null}r(cse,"reusableOAuthConnection");function JSe(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(JSe,"readConnectionIntentOAuthOutcome");function c4(e={}){const[s]=fi(),n=va(),{selectedCompanyId:a}=ps(),i=q9(),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&&y1(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||y1(l)||z3(l))),h=Z({queryKey:["tools","connection",d],queryFn:r(()=>Zt.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)(L,{variant:"outline",onClick:r(()=>{h.refetch()},"onClick"),children:"Try again"})]});if(z3(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"&&y1(p)&&(!f||HR(p,f))){const x=Kpe(p,s.get("targetToolkit"));return(0,t.jsx)(XHe,{...e,upstreamServiceName:e.upstreamServiceName??x?.name,interactionId:o,providerId:p,connection:h.data},`${o||"page"}:${p}`)}return(0,t.jsx)(Nit,{...e})}r(c4,"ConnectionSetupFlow");function Nit({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,onPhaseChange:j,onCancel:N,renderCredentialStep:w}={}){const k=Dt(),S=Mn(),C=(0,m.useCallback)((bt,_e)=>{o==="page"&&(_e?S(bt,_e):S(bt))},[o,S]),I=va(),{selectedCompany:R,selectedCompanyId:T}=ps(),{enabled:A}=iS(),{enabled:D}=q9(),{setBreadcrumbs:M}=Bn(),{pushToast:B}=xi(),[E]=fi(),z=d?.trim()||E.get("intent")?.trim()||null,$=I.appKey??E.get("appKey")??void 0,q=E.get("source")?.trim()||null,U=u||E.get("new")==="1",O=E.get("stage")?.trim()||null,K=E.get("method")?.trim()||null,H=E.get("resume")?.trim()||null,ee=E.get("oauth"),se=E.get("code"),ne=ese(E.get("installation_url")),fe=ese(E.get("management_url")),X=p?.id??(E.get("reconnect")?.trim()||null),re=E.get("identity")==="user"?"user":E.get("identity")==="organization"?"organization":null,oe=i==="vercel_connect",G=l??q,Y=i==="paperclip_vault"&&Gat(G)?G:null,Q=Yat({serviceSlug:l,appKey:$,sourceSlug:q}),te=(l??q??$)==="zapier",ae=te?void 0:Q,le=!!p||o==="page"&&(a||E.get("byo")==="1"),[he]=(0,m.useState)(()=>o==="page"&&E.get("cloud_connector")==="enrolled"&&ae?uit(ae):null),[ce]=(0,m.useState)(()=>{const bt=E.get("link")?.trim()??"";return{link:/^https?:\/\//i.test(bt)?bt:"",name:p?.name??E.get("name")?.trim()??"",applicationId:p?.applicationId??(E.get("applicationId")?.trim()||void 0)}}),[ge,me]=(0,m.useState)(()=>sse({requestedAppKey:ae,routeStage:O,resumeConnectionId:H,hasPrefilledLink:!!ce.link,zapierSource:te})),[ie,ue]=(0,m.useState)(null),[ke,be]=(0,m.useState)(""),[Ie,Ue]=(0,m.useState)(ce.link),[at,dt]=(0,m.useState)(ce.name||(te?"Zapier":"")),[de,Be]=(0,m.useState)(!1),[pt,vt]=(0,m.useState)(""),[Le,Qe]=(0,m.useState)("auto"),[ut,Ye]=(0,m.useState)(()=>[i6()]),[it,kt]=(0,m.useState)(""),[tt,Pe]=(0,m.useState)(""),[Ce,He]=(0,m.useState)(!1),[Je,lt]=(0,m.useState)(null),[Ee,Xe]=(0,m.useState)(!1),[Ae,De]=(0,m.useState)({}),[_t,ye]=(0,m.useState)(""),[gt,We]=(0,m.useState)(""),[Ot,zt]=(0,m.useState)(""),[Cs,ze]=(0,m.useState)(v&&v.mode!=="responsible_user"?`ai-${v.method}`:""),[ft,Ut]=(0,m.useState)(null),[Ns,Is]=(0,m.useState)({}),[St,ds]=(0,m.useState)(""),[$e,xe]=(0,m.useState)(null),[Qt,Mt]=(0,m.useState)(null),[rs,ws]=(0,m.useState)({}),[Bs,er]=(0,m.useState)("all"),[Fe,st]=(0,m.useState)(new Set),[xt,Oe]=(0,m.useState)(()=>new Set(he?.agentIds??(c?[c]:[]))),[Bt,wt]=(0,m.useState)(he?.grantKind??re??(c?"user":"organization")),[Xt,Yt]=(0,m.useState)(he?.installChoice??(c?"specific":"all")),hs=!!(H&&(ee==="failed"||ee==="denied")),[Ts,as]=(0,m.useState)(hs?"error":"entry"),[Zn,en]=(0,m.useState)(()=>hs?tse(ee,se):null),[nr,tn]=(0,m.useState)(null),xn=(0,m.useRef)(!1),Ht=(0,m.useRef)(!1),qs=(0,m.useRef)(null),Vs=(0,m.useRef)(null),[Lt,is]=(0,m.useState)(null),Ms=(0,m.useRef)(null),[bs,gn]=(0,m.useState)(null),[Pn,$r]=(0,m.useState)(null),mt=(0,m.useRef)(null),[vs,Fs]=(0,m.useState)(h.length>0&&!!f),[Hs,zs]=(0,m.useState)(null),[Us,ur]=(0,m.useState)(null),[Dn,Er]=(0,m.useState)(null),Jn=(0,m.useCallback)(()=>{o!=="dialog"||Ms.current?.closed===!1||(Ms.current=window.open("about:blank","paperclip-connection-oauth","popup,width=720,height=760,resizable=yes,scrollbars=yes"))},[o]),tr=(0,m.useCallback)(bt=>{if(o!=="dialog"){Lm(bt);return}$r(bt);const _e=Ms.current;if(!_e||_e.closed){as("error"),en("Paperclip couldn’t open the sign-in window. Open sign-in in a new tab to continue."),j?.("needs_retry");return}_e.location.assign(bt),_e.focus()},[o,j]),pn=(0,m.useCallback)(()=>{Ms.current=null,en(null),as("redirecting"),j?.("authorizing")},[j]);(0,m.useEffect)(()=>{if(o!=="dialog"||Ts!=="redirecting")return;const bt=window.setInterval(()=>{Ms.current?.closed&&(as("error"),en("The sign-in window closed. If authorization did not finish, try again."),$r(null),j?.("needs_retry"))},1e3);return()=>window.clearInterval(bt)},[o,Ts,j]);const yt=(0,m.useCallback)(async bt=>{mt.current?.abort();const _e=new AbortController;mt.current=_e;try{const ot=await dN(bt,{signal:_e.signal});if(ot.kind==="reauthentication"){const Nt=o==="dialog"?Ms.current:window;if(!Nt||Nt.closed||!bt.handoff)throw new Error("Paperclip couldn’t preserve this sign-in while refreshing your account.");B_(bt.handoff.session,Nt.sessionStorage),as("starting")}else tn(ot.host),as("redirecting");tr(ot.url)}catch(ot){if(_e.signal.aborted)return;as("error"),en(ot instanceof Error?ot.message:"Paperclip couldn’t start secure sign-in. Try again."),j?.("needs_retry")}finally{mt.current===_e&&(mt.current=null)}},[o,j,tr]);(0,m.useEffect)(()=>()=>mt.current?.abort(),[]),(0,m.useEffect)(()=>{if(o!=="dialog"||!z)return;const bt=r(_e=>{const ot=JSe(_e,window.location.origin,z);if(ot==="connected"){as("entry"),$r(null),x?.({resolvedByCallback:!0});return}if(ot==="declined"){as("error"),en("Authorization was cancelled. You can try again."),j?.("needs_retry");return}ot==="failed"&&(as("error"),en("Authorization did not complete. Try again when you’re ready."))},"receiveOAuthOutcome");return window.addEventListener("message",bt),()=>window.removeEventListener("message",bt)},[z,o,x,b]),(0,m.useEffect)(()=>{if(o!=="dialog"||z||!bs)return;let bt=!1,_e=!1;const ot=window.setInterval(async()=>{if(_e||bt)return;const Nt=Ms.current;if(!Nt||Nt.closed){gn(null),as("error"),en("The sign-in window closed. Try again to finish connecting GitHub.");return}let us;try{us=new URL(Nt.location.href)}catch{return}if(!(us.origin!==window.location.origin||!us.pathname.includes(bs))){if(us.searchParams.has("oauth")){gn(null),as("error"),en("Authorization did not complete. Finish setup in the sign-in window or try again.");return}if(us.searchParams.get("success")==="1"){_e=!0;try{const Ls=await Zt.getConnection(bs);!bt&&Ls.status==="active"&&(gn(null),Nt.close(),x?.({connectionId:Ls.id}))}catch{bt||(gn(null),as("error"),en("Could not confirm the connection. Try again."))}finally{_e=!1}}}},1e3);return()=>{bt=!0,window.clearInterval(ot)}},[z,bs,o,x]);const Ps=r(()=>{Qe("auto"),Ye([i6()]),kt(""),Pe(""),He(!1),lt(null),Xe(!1)},"resetGenericAuthState"),Zs=r(bt=>{if(o==="page"&&!z&&i==="paperclip_vault"&&y1(bt.slug)){C(`/apps/connect?source=${bt.slug}`);return}if(bt.slug==="zapier"){ue(null),be(""),Ue(""),dt("Zapier"),Be(!1),vt(""),Ps(),De({}),Mt(null),me("key"),C(H2("/apps/connect?source=zapier",z));return}if(i==="paperclip_vault"&&ose(bt)){C(z_(bt.slug,z));return}ue(bt),be(bt.name),Ue(""),dt(""),Be(!1),vt(""),Ps(),De({}),ye(""),We(""),zt("");const _e=vk(Aw(bt,i));ze(_e?.key??""),Is(aC(_e)),ds(""),xe(null),Mt(null),Oe(new Set(c?[c]:[])),Yt(c?"specific":"all"),wt(Br??Q$(_e,!!c)),me("key"),C(i==="vercel_connect"?H2(V$(bt.slug),z):z_(bt.slug,z))},"useMatchedGalleryEntry"),Ze=r(()=>{me("gallery"),C(H2(i==="vercel_connect"?V$():a?"/apps/byo":"/apps",z))},"backToGallery");(0,m.useEffect)(()=>{if(o==="page")return M([{label:"Connectors",href:"/apps"},{label:oe?"Vercel Connect":a?"Connect your own tool":"Connect an app"}]),()=>M([])},[a,o,M,oe]);const At=Z({queryKey:P.apps.gallery(T??"__none__"),queryFn:r(()=>Zt.listGallery(T),"queryFn"),select:(0,m.useCallback)(bt=>z?{...bt,apps:bt.apps.map(_e=>({..._e,methods:_e.methods.filter(ot=>v?ot.ai?.provider===v.provider&&(v.mode==="responsible_user"||ot.ai.method===v.method):ot.transport!=="runtime_auth")})).filter(_e=>_e.methods.length>0)}:bt,[z,v?.provider,v?.method,v?.mode]),enabled:!!T}),fs=(0,m.useMemo)(()=>(At.data?.apps??[]).filter(bt=>D||!z3(bt.slug)).filter(bt=>bt.slug==="agentmail"||A||!bt.methods.some(_e=>_e.transport==="chat_sdk")||l4(bt)),[At.data,A,D]),Ks=ae?NI(ae):null,Ln=Ks?.methods.find(bt=>nk(bt)&&!rp(bt)),Cr=!(Ln&&Cs===Ln.key)&&!!Ks?.methods.some(bt=>bt.oauthStrategy==="paperclip_cloud_connector"||bt.oauthStrategy==="paperclip_id_connector"),Vr=!!ie?.methods.some(bt=>bt.oauthStrategy==="paperclip_cloud_connector"||bt.oauthStrategy==="paperclip_id_connector"),Pr=ie&&Cr&&!Vr?ise(Ks):null,[Ar,_r]=(0,m.useState)(null),yr=Z({queryKey:["cloud-connector","enrollment"],queryFn:r(()=>Zt.getCloudConnectorEnrollment(),"queryFn"),refetchInterval:Ar?2e3:!1,enabled:!!(T&&Cr&&!Vr)}),[sr,Ga]=(0,m.useState)(null),ka=(0,m.useCallback)(()=>{Ms.current?.close(),Ms.current=null,_r(null)},[]),Ds=(0,m.useCallback)(()=>{!T||!ae||dit(T,ae,{grantKind:Bt,installChoice:Xt,agentIds:Xt==="specific"?[...xt]:[]})},[Bt,xt,Xt,ae,T]),$n=(0,m.useCallback)(bt=>{const _e=o5(bt);if(!_e.ok){ka(),Ga(_e.message);return}if(o==="dialog"){_r(_e.url);const ot=Ms.current;ot&&!ot.closed?(ot.location.assign(_e.url),ot.focus()):Ga("Open authorization in a new tab to continue.");return}Lm(_e.url)},[o,ka]);(0,m.useEffect)(()=>{!Ar||yr.data?.status!=="active"||(ka(),Ga(null),At.refetch())},[Ar,yr.data?.status,At.refetch,ka]);const mr=je({mutationFn:r(()=>Zt.startCloudConnectorEnrollment(T,R?.name,ae?nse(ae,"key",i,{resumeConnectionId:H,reconnectConnectionId:X,interactionId:z})+(o==="dialog"?"&enrollment_host=dialog":""):void 0),"mutationFn"),onSuccess:r(bt=>{if(!bt.verificationUrl){ka(),Ga("Paperclip Cloud did not return an enrollment link. Try again.");return}$n(bt.verificationUrl)},"onSuccess"),onError:r(bt=>{ka(),Ga(bt instanceof Error?bt.message:"Paperclip couldn’t reach Paperclip Cloud. Try again.")},"onError")}),Cn=Z({queryKey:P.tools.applications(T??"__none__"),queryFn:r(()=>Zt.listApplications(T),"queryFn"),enabled:!!T&&(!!Y||!!H||!!X),refetchOnMount:"always"}),on=Z({queryKey:P.tools.connections(T??"__none__"),queryFn:r(()=>Zt.listConnections(T),"queryFn"),enabled:!!T&&(!!Y||!!H||!!X),refetchOnMount:"always"}),Hr=(0,m.useMemo)(()=>u?null:cse(Y,Cn.data?.applications??[],on.data?.connections??[],U?{applicationId:ce.applicationId,draftOnly:!0}:{}),[Cn.data,on.data,U,Y,ce.applicationId,u]),ss=(0,m.useMemo)(()=>X?(on.data?.connections??[]).find(bt=>bt.id===X)??null:null,[on.data,X]),Hn=(0,m.useRef)(null);(0,m.useEffect)(()=>{if(!p||!on.isFetchedAfterMount||!ss||Hn.current===ss.id)return;const bt=ss.config?.url??ss.transportConfig?.url??ss.transportConfig?.serverUrl??ss.config?.serverUrl;typeof bt!="string"||!/^https?:\/\//i.test(bt)||(Hn.current=ss.id,Ue(_e=>_e||bt))},[p,on.isFetchedAfterMount,ss]);const Gn=(0,m.useMemo)(()=>ss?(Cn.data?.applications??[]).find(bt=>bt.id===ss.applicationId)??null:null,[Cn.data,ss]),un=pit({requestedAppKey:ae,byo:le,applicationId:ce.applicationId,reconnectConnection:ss,reconnectApplication:Gn}),Kn=(0,m.useMemo)(()=>H?(on.data?.connections??[]).find(bt=>bt.id===H)??null:null,[on.data,H]),Lr=Kn??ss,Br=Lr?Lr.credentialPolicy==="per_user"?"user":Lr.credentialPolicy==="per_agent"?"agent":"organization":re,Se=Kn?.authKind==="oauth"?Kn:Hr,Jt=Hr?Hr.credentialPolicy==="per_user"?"user":Hr.credentialPolicy==="per_agent"?"agent":"organization":null,ln=Br??Jt;(0,m.useEffect)(()=>{ln&&wt(ln)},[ln]);const rr=(0,m.useMemo)(()=>Ie&&!ie?v3(Ie,fs):null,[ie,fs,Ie]),ra=ie?G2(ie,Cs||null):null,Ea=ra&&rp(ra)?ra:lse(ie),os=i==="paperclip_vault"&&Ea?ie:null,Re=i==="paperclip_vault"&&ose(ie)?ie:null,Kt=!!Y&&(!Cn.isFetchedAfterMount||!on.isFetchedAfterMount),Vt=r(bt=>{me(bt),ie&&C(nse(ie.slug,bt,i,{connectionMethodKey:ie.methods.find(_e=>_e.key===Cs)?.ai?Cs:void 0,resumeConnectionId:H,reconnectConnectionId:X,interactionId:z}))},"setAppStep"),fn=Kn??ss??Se,an=ie?.agentInstructions,ar=ie&&an?ft?.slug===ie.slug?ft.value:fn?fn.agentInstructions??{...Kk(an),enabled:!1}:Kk(an):null,Mr=!ar||!!ar.text.trim(),qt=je({mutationFn:r(async bt=>(ar&&JSON.stringify(ar)!==JSON.stringify(bt.agentInstructions)&&await Zt.updateConnection(bt.id,{agentInstructions:ar}),Zt.startOAuth(bt.id,{asCurrentUser:bt.credentialPolicy==="per_user",...bt.credentialPolicy==="per_agent"?{asAgentId:jit(bt)??[...xt][0]}:{},...z?{interactionId:z}:{}})),"mutationFn"),onSuccess:r(bt=>{yt(bt)},"onSuccess"),onError:r(bt=>{const _e=bt instanceof dn&&bt.body&&typeof bt.body=="object"?bt.body.details:null;as("error"),j?.("needs_retry"),en(_e?.code==="invalid_grant"?"Your authorization expired or was revoked. Reconnect to continue.":bt instanceof Error?bt.message:"Paperclip couldn’t start secure sign-in. Try again.")},"onError")}),cs=qt.mutate,_n=(0,m.useCallback)(bt=>{j?.("authorizing"),Jn(),o==="dialog"&&!z&&gn(bt.id),cs(bt)},[cs,j,Jn,o,z]),jr=r(async bt=>{if(c)return;const _e=QSe(T,(ln??Bt)!=="agent"&&Xt==="all"?{onAll:!0,agentIds:new Set}:{onAll:!1,agentIds:xt});await Zt.putConnectionInstalls(bt,_e)},"applyAccessInstalls"),wn=ln??Bt,ya=je({mutationFn:r(async bt=>{const _e=bt??ie;let ot;if(_e){const Nt=ln??Bt,us=G2(_e,Cs||null),Ls=GC(_e,us)?dq(St).ids:[],Na=ke.trim(),ea=Jte(Na||_e.name,Nt);ot=await Zt.connectApp(T,{galleryKey:_e.slug,...ar?{agentInstructions:ar}:{},...Cs?{connectionMethodKey:Cs}:{},name:ea,credentialSource:i,...i==="paperclip_vault"?{credentialValues:Ae}:{},...i==="vercel_connect"?{vercelConnect:{connector:Ot.trim()}}:{},..._t.trim()?{oauthClient:{clientId:_t.trim(),...gt?{clientSecret:gt}:{}}}:{},configValues:GC(_e,us)?{allowedSpreadsheetIds:Ls}:Object.keys(Ns).length>0?Ns:void 0,applicationId:ce.applicationId,...H??qs.current?{resumeConnectionId:H??qs.current}:X?{reconnectConnectionId:X}:{},...Nt!=="organization"?{grantKind:Nt}:{},...Nt==="agent"?{subjectAgentId:[...xt][0]}:{}}),qs.current=null}else{const Nt=iit({link:Ie,name:at,authMode:Le,needsKey:de,keyValue:pt,headers:ut,oauthClientId:it,oauthClientSecret:tt}),us=Jte(Nt.name??G$(Ie)??"Custom app",wn);ot=await Zt.connectApp(T,{...Nt,...X?{reconnectConnectionId:X}:{},...te||rr?.slug==="zapier"?{galleryKey:"zapier",connectionMethodKey:"generated-url"}:{},name:us,applicationId:ce.applicationId,...wn!=="organization"?{grantKind:wn}:{},...wn==="agent"?{subjectAgentId:[...xt][0]}:{}})}return ot.auth?.kind==="oauth"&&!H&&!X&&await jr(ot.connectionId),ot},"mutationFn"),onSuccess:r(bt=>{if(bt.auth?.kind==="oauth"){if(Mt(bt),bt.auth.manualClientRequired){lt(Zte("oauth_manual_client_required",null)),Qe("oauth"),He(!0),Xe(!1);return}if(o==="dialog"||z){as("starting"),Xe(!ie),_n(bt.connection);return}const ot=bt.auth.startUrl?.trim();if(!ot){as("starting"),Xe(!0),_n(bt.connection);return}Xe(!0),yt({authorizationUrl:ot,handoff:bt.auth.handoff});return}lt(null),Mt(bt);const _e={};for(const ot of bt.actions.readOnly)_e[ot.catalogEntryId]=!0;for(const ot of bt.actions.canMakeChanges)_e[ot.catalogEntryId]=!0;ws(_e),eo.mutate({result:bt,enabled:_e})},"onSuccess"),onError:r(bt=>{const _e=bt instanceof dn&&bt.body&&typeof bt.body=="object"?bt.body.details:null;if(os){as("error"),j?.("needs_retry"),en(_e?.code==="invalid_grant"?"Your authorization expired or was revoked. Reconnect to continue.":bt instanceof Error?bt.message:"Paperclip couldn’t start secure sign-in. Try again.");return}if(!ie&&Ie){const ot=typeof _e?.code=="string"?_e.code:null,Nt=Zte(ot,bt instanceof Error?bt.message:null);lt(Nt),Xe(!1),Nt.focus==="credentials"&&(Be(!0),He(!0));return}B({title:"Couldn’t connect",body:bt instanceof Error?bt.message:"Please check your key and try again.",tone:"error"})},"onError")}),br=ya.mutate,Wi=(0,m.useCallback)(bt=>{const _e=bt??ie;(_e?G2(_e,Cs||null):null)?.auth==="oauth"&&Jn(),br(bt)},[Cs,ie,br,Jn]);(0,m.useEffect)(()=>{if(!ae||At.isLoading||!At.data||X&&(!on.isFetchedAfterMount||!Cn.isFetchedAfterMount))return;const bt=hit({requestedAppKey:ae,galleryApps:At.data.apps,reconnectConnection:ss,applications:Cn.data?.applications??[]}),_e=!!bt?.methods.some(ir=>ir.oauthStrategy==="paperclip_cloud_connector"||ir.oauthStrategy==="paperclip_id_connector");if(Cr&&!_e&&yr.isLoading)return;const ot=Aw(bt,i),Nt=v??(ss?.connectionPurpose==="ai"?PJ.safeParse(ss.config?.ai).data:void 0),us=ot.find(ir=>Nt?ir.ai?.provider===Nt.provider&&(!("mode"in Nt)||Nt.mode!=="responsible_user")&&ir.ai.method===Nt.method:ir.key===K)??(Cr&&!_e?ise(Ks):null)??vk(ot),Ls=ot.length===1?ot[0]:null,Na=i==="paperclip_vault"&&!!lse(bt),ea=fit({credentialSource:i,available:At.data.credentialSources?.vercelConnect.available===!0,retainedReconnectMatches:!!(X&&un)}),zr=ot.length===1&&Ls?.auth==="oauth"&&!rp(Ls)&&!nk(Ls),Sa=xit({available:bt?.availability?.available,reconnectConnectionId:X,reconnectSourceMatches:un}),Ei=git({reconnectConnectionId:X,hasRequestedEntry:!!bt,supportedMethodCount:ot.length,unsupportedOAuth:zr,vercelUnavailable:ea,definitionUnavailable:Sa});if(Ei!=="ready"){if(ue(null),me("gallery"),Ei==="reconnect_unavailable"&&X){Er(X);return}C(H2(i==="vercel_connect"?V$():"/apps/connect",z),{replace:!0});return}if(Er(null),!!bt){if(ie?.slug!==bt.slug){ue(bt),be(bt.name),Ue(""),dt(""),Be(!1),vt(""),De({}),ye(""),We(""),zt(""),ze(us?.key??""),Is(aC(us)),ds(""),xe(null),Mt(null);const ir=he?.companyId===T?he:null;wt(Br??ir?.grantKind??Q$(us,!!c)),Oe(new Set(ir?.agentIds??(c?[c]:[]))),Yt(ir?.installChoice??(c?"specific":"all")),me(sse({requestedAppKey:ae,routeStage:O,resumeConnectionId:H,hasPrefilledLink:!!ce.link,zapierSource:te}))}else Vr!==_e&&(ue(bt),ze(us?.key??""),Is(aC(us)));if(!(Na&&(!Cn.isFetchedAfterMount||!on.isFetchedAfterMount))&&!(Na&&Ht.current)&&Na&&(Cn.isError||on.isError)){as("error"),en("Paperclip couldn’t check for an existing connection. Try again."),me("key");return}}},[v,K,Cn.isError,Cn.isFetchedAfterMount,Cn.data,on.isError,on.isFetchedAfterMount,yr.data?.configured,yr.isLoading,Cs,i,ie?.slug,Vr,At.data,At.isLoading,C,Br,ss,X,un,H,Ks,ae,c,he,O,te]),(0,m.useEffect)(()=>{Vs.current=null,is(null)},[H]),(0,m.useEffect)(()=>{const bt=Kn??ss;if(!bt||!ie||Vs.current===bt.id)return;const _e=Y8(bt),ot=typeof _e.sourceTemplateKey=="string"?_e.sourceTemplateKey:null;if(ot&&ot!==ie.slug)return;const Nt=typeof _e.connectionMethodKey=="string"?_e.connectionMethodKey:null,us=Nt?Aw(ie,i).find(Na=>Na.key===Nt)??null:null;if(be(bt.name||ie.name),us){ze(us.key);const Na=_e.methodConfig&&typeof _e.methodConfig=="object"?_e.methodConfig:{};Is({...aC(us),...Object.fromEntries(Object.entries(Na).filter(ea=>typeof ea[1]=="string"||typeof ea[1]=="boolean"))})}const Ls=_e.oauth&&typeof _e.oauth=="object"?_e.oauth:null;Ls?.clientRegistrationSource==="manual"&&typeof Ls.clientId=="string"&&ye(Ls.clientId),ee==="failed"||ee==="denied"?(as("error"),en(tse(ee,se))):(as("entry"),en(null)),me("key"),Vs.current=bt.id,is(bt.id)},[i,ie,se,ee,Kn,ss]);const eo=je({mutationFn:r(async bt=>{const{result:_e,enabled:ot}=bt,Nt=Object.entries(ot).filter(([,ea])=>ea).map(([ea])=>ea),us=mwe(_e,ea=>!!ot[ea]),Ls=Xt==="all"?"all_agents":{agentIds:Array.from(xt)},Na=await Zt.finishApp(T,_e.connectionId,{enabledCatalogEntryIds:Nt,askFirstCatalogEntryIds:us,...ar?{agentInstructions:ar}:{},access:Ls,...c?{preserveExistingAccess:!0}:{}});return await jr(_e.connectionId),Na},"mutationFn"),onSuccess:r(async(bt,_e)=>{await k.invalidateQueries({queryKey:["tools"]}),await k.invalidateQueries({queryKey:P.apps.attention(T)}),Vt("success"),x?.({connectionId:_e.result.connectionId})},"onSuccess"),onError:r(bt=>{Vt("key"),B({title:"Couldn’t finish setup",body:bt instanceof Error?bt.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((H||X)&&(on.isError||Cn.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)(L,{type:"button",onClick:r(async()=>{const[bt,_e]=await Promise.all([on.refetch(),Cn.refetch()]);!bt.isError&&!_e.isError&&(en(null),as("entry"))},"onClick"),children:"Try again"}),(0,t.jsx)(L,{type:"button",variant:"outline",onClick:r(()=>C("/apps"),"onClick"),children:"Back to apps"})]})]});if(H&&on.isFetchedAfterMount&&!Kn)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)(L,{type:"button",variant:"outline",className:"mt-5",onClick:r(()=>C("/apps"),"onClick"),children:"Back to apps"})]});if(X&&on.isFetchedAfterMount&&Cn.isFetchedAfterMount&&(!ss||!un))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:ss?"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)(L,{type:"button",variant:"outline",className:"mt-5",onClick:r(()=>C("/apps"),"onClick"),children:"Back to apps"})]});if((H||X)&&At.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)(L,{type:"button",onClick:r(()=>{At.refetch()},"onClick"),children:"Try again"}),(0,t.jsx)(L,{type:"button",variant:"outline",onClick:r(()=>C("/apps"),"onClick"),children:"Back to apps"})]})]});if(X&&Dn===X)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)(L,{type:"button",variant:"outline",className:"mt-5",onClick:r(()=>C("/apps"),"onClick"),children:"Back to apps"})]});if(H&&(!on.isFetchedAfterMount||At.isLoading||!ie||Lt!==Kn?.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)(vn,{className:"h-8 w-48"}),(0,t.jsx)(vn,{className:"h-40 w-full rounded-xl"})]});if(X&&(!on.isFetchedAfterMount||!Cn.isFetchedAfterMount||At.isLoading||ae&&!ie))return(0,t.jsxs)("div",{className:"mx-auto max-w-xl space-y-4","aria-label":"Loading retained connection setup",children:[(0,t.jsx)(vn,{className:"h-8 w-48"}),(0,t.jsx)(vn,{className:"h-40 w-full rounded-xl"})]});if(vs&&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 ",ae?"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)(F9,{choices:h.map(bt=>({id:bt.id,name:bt.name,description:bt.status==="active"&&bt.enabled?"Ready to use":"Setup needs attention"})),pendingId:Hs,onSelect:r(async bt=>{zs(bt),ur(null);try{await f(bt)}catch(_e){ur(_e instanceof Error?_e.message:"Couldn’t use this connection."),zs(null)}},"onSelect")}),Us?(0,t.jsx)(ha,{tone:"danger",className:"mt-4",children:Us}):null,(0,t.jsxs)("div",{className:"mt-5 flex flex-wrap gap-2",children:[(0,t.jsx)(L,{type:"button",variant:"outline",onClick:r(()=>Fs(!1),"onClick"),children:p?"Review connection setup":"Connect new"}),N?(0,t.jsx)(L,{type:"button",variant:"ghost",onClick:N,children:"Cancel"}):null]})]});const _o=Aw(ie,i),Vi=Pr?[Pr]:_o,Me=ie?Cs?Vi.find(bt=>bt.key===Cs)??null:Vi[0]??null:null,ys=ie?Me?.auth??"none":Le==="none"?"none":Le==="oauth"?"oauth":"api_key",cn=ge==="key"?((bt,_e)=>(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)(ZSe,{extra:bt,forceOpen:_e,companyId:T,sentence:d6({grantKind:wn,authKind:ys,installChoice:Xt,installCount:xt.size,lockedAgentId:c??null,preserveAgentAccess:!!(os&&(Se||ss))}),notice:[At.data?.capabilities?.canCreateOrganizationGrant===!1?At.data.capabilities.organizationGrantReason??"Only a connection manager can share this credential with the organization.":null,At.data?.capabilities?.canSetCompanyInstall===!1?At.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(ot=>!!ot),authKind:ys,grantKinds:ln?[ln]:Me?.grantKinds,grantKind:wn,setGrantKind:wt,installChoice:Xt,setInstallChoice:Yt,installAgentIds:xt,setInstallAgentIds:Oe,lockedAgentId:c,capabilities:At.data?.capabilities,githubIdentity:ie?.slug==="github",identityLoading:!!os&&Kt,preserveAgentAccess:!!(os&&(Se||ss)),disabled:ya.isPending||qt.isPending},"connection-defaults"),ie&&an&&ar&&(0,t.jsx)("div",{className:"mt-6",children:(0,t.jsx)(O9,{provider:ie.name,template:an,value:ar,onChange:r(ot=>Ut({slug:ie.slug,value:ot}),"onChange"),disabled:ya.isPending||qt.isPending})}),e&&(0,t.jsx)("div",{className:"mt-6",children:e})]})):null,aa=os&&Ea&&nk(Ea)?Ea:null,Wa=aa&&os?(0,t.jsx)(c6,{entry:os,method:aa,callbackUrl:VSe(),clientId:_t,onClientIdChange:ye,clientSecret:gt,onClientSecretChange:We,required:!1}):null,Za=cn?.()??null,Li=Wa?cn?.(Wa,Ts==="error"||_t.trim().length>0)??null:Za,Fa=!!(os&&ge==="key"&&(Re||Ts!=="entry")),Yo=!!(ge==="key"&&ie&&Cr&&!Vr&&yr.data?.configured===!0),ja=!!(ge==="key"&&ie&&Cr&&!Vr&&(yr.isLoading||yr.isError||yr.data?.configured!==!0));if(Fa&&os)return(0,t.jsx)(o6,{entry:os,resuming:!!H,phase:Ts,error:Zn,recoveryActions:se==="github_installation_required"?{installationUrl:ne,managementUrl:fe}:void 0,authorizationHost:nr,authorizationUrl:Pn,guidance:ie?.slug==="railway"&&Me?(0,t.jsxs)("div",{className:"space-y-3 text-sm text-muted-foreground",children:[(0,t.jsx)("p",{children:Me.guidanceMd}),(0,t.jsx)("ul",{className:"list-disc space-y-2 pl-5",children:Me.warnings?.map(bt=>(0,t.jsx)("li",{children:bt},bt))})]}):null,defaults:Li,settingsValid:n&&Mr,onOpenAuthorization:pn,onRetry:r(async()=>{const bt=!xn.current;xn.current=!0,en(null),as("starting");const _e=Qt?.connection??Se;if(_e&&Wa&&_t.trim()){qs.current=_e.id,Wi(os);return}if(_e){_n(_e);return}if(bt&&!H&&!Cn.isError&&!on.isError){Wi(os);return}Ht.current=!0;try{const[ot,Nt]=await Promise.all([Cn.refetch(),on.refetch()]);if(ot.isError||Nt.isError){as("error"),en("Paperclip couldn’t check for an existing connection. Try again.");return}const us=(H?(Nt.data?.connections??[]).find(Ls=>Ls.id===H&&Ls.authKind==="oauth")??null:null)??cse(Y,ot.data?.applications??[],Nt.data?.connections??[],U?{applicationId:ce.applicationId,draftOnly:!0}:{});us&&!H&&wt(us.credentialPolicy==="per_user"?"user":us.credentialPolicy==="per_agent"?"agent":"organization"),us?_n(us):ya.mutate(os)}finally{Ht.current=!1}},"onRetry"),onBack:r(()=>{mt.current?.abort(),as("entry"),en(null),Ze()},"onBack"),onCancel:r(()=>{mt.current?.abort(),(N??(()=>C("/apps")))()},"onCancel")});if(Ee&&!ie&&Ie&&ge==="key")return(0,t.jsx)(o6,{identity:{name:at.trim()||M1(Ie)||"this server",unverifiedHost:M1(Ie)},steps:{labels:rse,activeIndex:ase.key},phase:Ts,error:Zn,authorizationHost:nr,authorizationUrl:Pn,defaults:Za,onOpenAuthorization:pn,onRetry:r(()=>{en(null);const bt=Qt?.connection;if(bt){as("starting"),_n(bt);return}Xe(!1),as("entry")},"onRetry"),onBack:r(()=>{mt.current?.abort(),Xe(!1),as("entry"),en(null)},"onBack"),onCancel:r(()=>{mt.current?.abort(),(N??(()=>C("/apps")))()},"onCancel")});const Hi=Qt?.application.name??ie?.name??(at.trim()||G$(Ie)||"this app"),Oo=oe?fs.filter(bt=>Aw(bt,i).length>0):fs,Jo=te?At.data?.apps.find(bt=>bt.slug==="zapier")??null:null,Fo=(ss?.connectionPurpose==="ai"?PJ.safeParse(ss.config?.ai).data:void 0)??ie?.methods.find(bt=>bt.key===Cs)?.ai??(!Cs&&ie?.methods.every(bt=>bt.ai)?ie.methods[0]?.ai:void 0),Gi=ie?w?.({app:ie,name:ke||ie.name,grantKind:wn,agentIds:[...xt],allAgents:Xt==="all",onBack:r(()=>Ze(),"onBack")})??(Fo&&T?(0,t.jsx)(t.Fragment,{children:(0,t.jsx)(P5,{companyId:T,provider:Fo.provider,fixedMethod:!!(v&&v.mode!=="responsible_user"),initialMethod:ss?.connectionPurpose==="ai"?(ss.config?.ai).method:Fo.method,connectionId:ss?.connectionPurpose==="ai"?ss.id:void 0,name:ss?.connectionPurpose==="ai"?ss.name:ke||`My ${ie.name} ${Fo.method==="subscription"?"subscription":"API"}`,ownership:(ss?.connectionPurpose==="ai"?ss.credentialPolicy==="shared":wn==="organization")?"shared":"personal",agentIds:[...xt],allAgents:Xt==="all",onCancel:r(()=>N?N():C("/apps"),"onCancel"),onComplete:r(bt=>{x?.({connectionId:bt.connectionId}),x||C(`/apps/${bt.connectionId}/permissions`)},"onComplete")})}):void 0):void 0,Xo=ss?.connectionPurpose==="ai"?["Reconnect account"]:Gi!==void 0?["Connect account"]:te?vit:ie&&Vi.length>1?["Choose connection"]:ie&&Vi[0]?.auth==="oauth"?["Sign in"]:GC(ie,Cs)?["Share sheet"]:ie?["Add your key"]:rse,Fc=ss?.connectionPurpose==="ai"?0:(te||ie)&&ge!=="gallery"&&ge!=="success"?bit[ge]:ge==="success"?Xo.length:ase[ge];return(0,t.jsxs)("div",{className:"max-w-5xl",children:[ge!=="success"&&!(a&&ge==="gallery")&&(0,t.jsx)(WM,{subtitle:ge==="gallery"?oe?"Choose a reviewed app to connect through Vercel.":"Pick the app you want your agents to use.":Xo.length<=1?void 0:`Step ${Fc+1} of ${Xo.length}`,step:ge,activeIndex:Fc,labels:Xo,appIdentity:te?{name:"Zapier",logoUrl:Jo?.branding.logoUrl??null,darkLogoUrl:Jo?.branding.darkLogoUrl??null}:ie&&ge!=="gallery"?{name:ie.name,logoUrl:ie.branding.logoUrl,darkLogoUrl:ie.branding.darkLogoUrl??null}:void 0,unverifiedHost:!ie&&!te&&ge!=="gallery"?M1(Ie):null,onCancel:N??(()=>C("/apps"))}),ge==="key"&&s&&(0,t.jsx)("div",{className:"mx-auto mb-6 max-w-xl",children:s}),ge==="gallery"&&(0,t.jsx)(Cit,{loading:At.isLoading,initialLink:Ie,apps:Oo,vercelConnect:oe,vercelConnectAvailability:At.data?.credentialSources?.vercelConnect??null,byo:le,byoOnly:a,source:E.get("source"),onPick:Zs,onUseLink:r(bt=>{const _e=v3(bt,fs);ue(null),be(""),Ue(bt),dt(_e?.name??G$(bt)??""),Be(!1),vt(""),De({}),ds(""),xe(null),Oe(new Set(c?[c]:[])),Yt(c?"specific":"all"),wt(Br??(c?"user":"organization")),me("key")},"onUseLink")}),Yo&&ie?(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:[ie.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 ",ie.name," sign-in is not currently available. Try again shortly or contact your instance administrator."]}),Ln?(0,t.jsxs)(L,{type:"button",variant:"link",className:"mt-4 h-auto p-0 text-xs",onClick:r(()=>ze(Ln.key),"onClick"),children:["Use your own ",ie.name," OAuth app"]}):null,(0,t.jsxs)("div",{className:"mt-6 flex items-center justify-between gap-3",children:[(0,t.jsx)(L,{type:"button",variant:"ghost",onClick:Ze,children:"Back"}),(0,t.jsxs)(L,{type:"button",disabled:At.isFetching,onClick:r(()=>{At.refetch()},"onClick"),children:[At.isFetching?(0,t.jsx)(rt,{className:"h-4 w-4 animate-spin"}):null,"Try again"]})]})]}):ge==="key"&&ie&&ja?(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)(J0,{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 ",ie.name," (you only need to do this once)."]})]})]}),Ln?(0,t.jsxs)(L,{type:"button",variant:"link",className:"mt-4 h-auto p-0 text-xs",onClick:r(()=>ze(Ln.key),"onClick"),children:["Use your own ",ie.name," OAuth app"]}):null,yr.isError||sr?(0,t.jsx)(ha,{tone:"danger",className:"mt-4",children:sr??"Paperclip couldn’t check Cloud registration. Try again."}):null,Ar?(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:Ar,target:"_blank",rel:"noopener noreferrer",children:"Open authorization in a new tab"})]}):null,Za,(0,t.jsxs)("div",{className:"mt-6 flex items-center justify-between gap-3",children:[(0,t.jsx)(L,{type:"button",variant:"ghost",onClick:Ze,children:"Back"}),(0,t.jsxs)(L,{type:"button",disabled:yr.isLoading||mr.isPending,onClick:r(()=>{Ga(null),Jn(),Ds(),mr.mutate()},"onClick"),children:[mr.isPending?(0,t.jsx)(rt,{className:"h-4 w-4 animate-spin"}):null,yr.data?.status==="pending"?"Continue":"Connect with Paperclip"]})]})]})}):ge==="key"&&ie&&Gi!==void 0?Gi:ge==="key"&&ie?(0,t.jsx)(Ait,{settingsValid:n&&Mr,entry:ie,error:ya.isError?ya.error instanceof Error?ya.error.message:"Please check your key and try again.":null,values:Ae,onChange:De,oauthClientId:_t,onOAuthClientIdChange:ye,oauthClientSecret:gt,canReuseOAuthClientSecret:!!(Lr?.config?.oauth&&Lr.config.oauth.clientId===_t.trim()&&Lr.hasSavedOAuthClientSecret),onOAuthClientSecretChange:We,credentialSource:i,vercelConnector:Ot,onVercelConnectorChange:zt,vercelConnectAvailability:At.data?.credentialSources?.vercelConnect??null,methodKey:Cs,onMethodChange:r(bt=>{ze(bt?.key??""),!Br&&bt?.grantKinds&&!bt.grantKinds.includes(Bt)&&wt(Q$(bt,!!c)),De({}),ye(""),We(""),zt(""),Is(aC(bt))},"onMethodChange"),configValues:Ns,onConfigChange:Is,googleSheetsLinks:St,googleSheetsError:$e,onGoogleSheetsLinksChange:r(bt=>{ds(bt),xe(null)},"onGoogleSheetsLinksChange"),submitting:ya.isPending,renderDefaults:cn??void 0,onBack:Ze,onConnect:r(()=>{if(GC(ie,Cs)){const ot=dq(St);if(ot.invalidCount>0){xe("That doesn't look like a Google Sheets link.");return}if(ot.ids.length===0){xe("Paste at least one Google Sheets link.");return}}const bt=G2(ie,Cs||null),_e=!!(bt?.credentialFields?.length||bt?.tenantFields?.some(ot=>!ot.hidden)||bt?.extensionFields?.some(ot=>!ot.hidden));if(bt&&rp(bt)&&Se&&!_e&&!_t.trim()){xn.current=!0,en(null),as("starting"),_n(Se);return}bt&&rp(bt)&&(xn.current=!0,en(null),as("starting")),Wi()},"onConnect")}):null,ge==="key"&&!ie&&!Ie&&!te&&ae&&(0,t.jsxs)("div",{className:"mx-auto max-w-xl","aria-busy":"true","aria-label":`Loading ${ae} setup`,children:[(0,t.jsx)(vn,{className:"h-6 w-2/3 rounded-md"}),(0,t.jsx)(vn,{className:"mt-3 h-4 w-full rounded-md"}),(0,t.jsx)(vn,{className:"mt-8 h-11 w-40 rounded-md"})]}),ge==="key"&&!ie&&Ie&&!te&&(0,t.jsx)(_it,{link:Ie,name:at,needsKey:de,keyValue:pt,onKeyChange:vt,authMode:Le,onAuthModeChange:r(bt=>{Qe(bt),lt(null),bt!=="auto"&&Be(!1),bt!=="bearer"&&bt!=="auto"&&vt("")},"onAuthModeChange"),headers:ut,onHeadersChange:r(bt=>{Ye(bt),lt(null)},"onHeadersChange"),oauthClientId:it,onOAuthClientIdChange:kt,oauthClientSecret:tt,onOAuthClientSecretChange:Pe,advancedOpen:Ce,onAdvancedOpenChange:He,guidance:Je,matchedEntry:rr,onUseMatchedEntry:rr?()=>Zs(rr):void 0,submitting:ya.isPending||Ee,defaults:Za,onBack:Ze,onConnect:r(()=>{lt(null),ya.mutate(void 0)},"onConnect")}),ge==="key"&&!ie&&te&&(0,t.jsx)(Sit,{link:Ie,onLinkChange:Ue,submitting:ya.isPending,defaults:Za,onBack:Ze,onConnect:r(()=>ya.mutate(void 0),"onConnect")}),ge==="success"&&(0,t.jsx)(Pit,{appName:Hi,logoUrl:ie?.branding.logoUrl,darkLogoUrl:ie?.branding.darkLogoUrl,summary:Eit({grantKind:wn,authKind:ys,installChoice:Xt,installCount:xt.size,enabledCount:Object.values(rs).filter(Boolean).length}),statedDefault:d6({grantKind:wn,authKind:ys,installChoice:Xt,installCount:xt.size,lockedAgentId:c??null}),onDone:N??(()=>C("/apps"))})]})}r(Nit,"StandardConnectionSetupFlow");function o6({entry:e,identity:s,resuming:n=!1,phase:a,error:i,recoveryActions:o,authorizationHost:l,authorizationUrl:c,steps:d={labels:yit,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)(WM,{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)(vc,{className:"h-5 w-5 text-destructive"}):a==="entry"?(0,t.jsx)(pd,{className:"h-5 w-5 text-muted-foreground"}):(0,t.jsx)(rt,{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)(KM,{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)(L,{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)(ao,{className:"ml-1.5 h-3.5 w-3.5"})]})}):null,o.managementUrl?(0,t.jsx)(L,{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)(L,{type:"button",onClick:p,disabled:!f,children:[a==="entry"?n?`Finish with ${j}`:`Continue to ${j}`:"Try again",a==="entry"?(0,t.jsx)(ao,{className:"h-4 w-4","aria-hidden":"true"}):null]}):(0,t.jsx)(L,{type:"button",disabled:!0,children:a==="redirecting"?`Opening ${j}…`:"Preparing…"}),c?(0,t.jsx)(L,{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)(L,{type:"button",variant:"ghost",onClick:b,children:"Back"})]})]})]})}r(o6,"OAuthConnectStateScreen");function Sit({link:e,onLinkChange:s,submitting:n,defaults:a,onBack:i,onConnect:o}){const l=l6(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)(ht,{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)(L,{variant:"ghost",onClick:i,disabled:n,children:"Back"}),(0,t.jsxs)(L,{onClick:o,disabled:n||!d,children:[n&&(0,t.jsx)(rt,{className:"mr-2 h-4 w-4 animate-spin"}),n?"Checking…":"Check link"]})]})]})}r(Sit,"ZapierConnectStep");function Cit({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 A=h.trim().toLowerCase();return n.filter(D=>!A||D.name.toLowerCase().includes(A))},[n,h]),C=l6(f),I=C?v3(C,n):null,R=c==="zapier",T=r(()=>{const A=l6(f);if(!A){j("Paste a full http or https link.");return}j(null),u(A)},"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((A,D)=>(0,t.jsx)(vn,{className:"h-32 w-full rounded-xl"},D))}):(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)(L,{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)(ao,{className:"ml-2 h-3.5 w-3.5"})]})}):null]}),l?.available===!1?(0,t.jsx)(ha,{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)(oa,{className:"pointer-events-none absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground"}),(0,t.jsx)(ht,{value:h,onChange:r(A=>p(A.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(A=>{const D=WSe(A.slug,A.description),M=hA(A),B=M.length===0||M.every(z=>z.auth==="oauth"&&!rp(z)&&!nk(z)),E=A.availability?.available===!1||o&&l?.available!==!0;return(0,t.jsxs)("button",{type:"button",disabled:B||E,title:E?A.availability?.reason??l?.reason??void 0:void 0,onClick:r(()=>d(A),"onClick"),className:W("flex flex-col rounded-xl border border-border bg-card p-4 text-left transition-colors",B||E?"cursor-not-allowed opacity-60":"hover:border-foreground/30 hover:bg-accent/40"),children:[(0,t.jsx)(al,{name:A.name,logoUrl:A.branding.logoUrl,darkLogoUrl:A.branding.darkLogoUrl,size:36}),(0,t.jsx)("div",{className:"mt-3 text-sm font-bold text-foreground",children:A.name}),(0,t.jsx)("div",{className:"mt-1 line-clamp-2 text-xs text-muted-foreground",children:D.tagline}),(0,t.jsx)("div",{className:"mt-3 text-xs font-semibold text-foreground",children:E?(0,t.jsx)("span",{className:"text-muted-foreground",children:A.availability?.reason??l?.reason??"Unavailable on this instance."}):B?(0,t.jsx)("span",{className:"text-muted-foreground",children:"Unavailable"}):(0,t.jsx)("span",{children:"Connect →"})})]},A.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:W("grid gap-4 border-t border-border pt-5 md:grid-cols-(--gtc-13)",a&&"-mx-3 rounded-xl border border-primary/40 bg-primary/[0.04] px-3 pb-4 md:mx-0"),children:[(0,t.jsxs)("div",{children:[(0,t.jsxs)("div",{className:"flex items-center gap-2 text-sm font-semibold text-foreground",children:[(0,t.jsx)(vc,{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"}),"."]}),I&&(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)(al,{name:I.name,logoUrl:I.branding.logoUrl,darkLogoUrl:I.branding.darkLogoUrl,size:24}),(0,t.jsxs)("span",{className:"truncate",children:["This looks like ",I.name,"."]})]}),(0,t.jsx)(L,{type:"button",size:"sm",variant:"outline",disabled:I.availability?.available===!1,onClick:r(()=>{if(j(null),I.slug==="zapier"){T();return}d(I)},"onClick"),children:I.availability?.available===!1?"Not available":I.slug==="zapier"?"Continue":`Use ${I.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)(ht,{ref:w,type:R||I?.slug==="zapier"?"password":"url",autoComplete:"off",spellCheck:!1,"aria-label":"MCP server URL",value:f,onChange:r(A=>{b.current=!0,x(A.target.value),j(null)},"onChange"),onKeyDown:r(A=>{A.key==="Enter"&&T()},"onKeyDown"),placeholder:R?"https://mcp.zapier.com/api/v1/connect?token=…":"https://example.com/actions",className:"h-10"}),(0,t.jsx)(L,{type:"button",variant:"outline",onClick:T,children:"Continue"})]}),v&&(0,t.jsx)("div",{className:"text-xs text-destructive",children:v})]})]})]})}r(Cit,"GalleryStep");function l6(e){try{const s=new URL(e.trim());return s.protocol!=="http:"&&s.protocol!=="https:"?null:s.toString()}catch{return null}}r(l6,"normalizeAppLink");function _it({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 I=M1(e),R=o==="custom_headers"?HSe(c):null,T=oit({link:e,name:s,authMode:o,needsKey:n,keyValue:a,headers:c,oauthClientId:u,oauthClientSecret:p}),A=o==="auto"&&n||o==="bearer",D=j?.slug==="zapier"?_pe(e):e,M=r((B,E)=>{d(c.map(z=>z.id===B?{...z,...E}:z))},"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:D,children:D}),(0,t.jsx)(KM,{host:I})]}),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)(al,{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)(L,{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)(ha,{tone:"warning",title:v.title,children:v.body})}):null,(0,t.jsxs)("div",{className:"mt-6 space-y-6",children:[A?(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)(ht,{id:"generic-mcp-key",type:"password",autoComplete:"off",value:a,onChange:r(B=>i(B.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)(gl,{open:x,onOpenChange:b,children:[(0,t.jsxs)(ec,{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:W("h-4 w-4 text-muted-foreground transition-transform",x&&"rotate-180")})]}),(0,t.jsxs)(xl,{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:dse.map(B=>(0,t.jsx)(Iit,{label:B.label,selected:o===B.mode,onClick:r(()=>l(B.mode),"onClick")},B.mode))}),(0,t.jsx)("p",{className:"text-xs text-muted-foreground",children:dse.find(B=>B.mode===o)?.hint}),o==="custom_headers"?(0,t.jsxs)("div",{className:"space-y-3",children:[c.map(B=>(0,t.jsxs)("div",{className:"flex items-start gap-2",children:[(0,t.jsx)(ht,{value:B.name,onChange:r(E=>M(B.id,{name:E.target.value}),"onChange"),placeholder:"Header name","aria-label":"Header name",className:"h-10 font-mono"}),(0,t.jsx)(ht,{type:"password",autoComplete:"off",value:B.value,onChange:r(E=>M(B.id,{value:E.target.value}),"onChange"),placeholder:"Value","aria-label":B.name.trim()?`Value for ${B.name.trim()}`:"Header value",className:"h-10 font-mono"}),(0,t.jsx)(L,{type:"button",variant:"ghost",size:"sm",className:"h-10 shrink-0",onClick:r(()=>d(c.filter(E=>E.id!==B.id)),"onClick"),disabled:c.length===1,children:"Remove"})]},B.id)),(0,t.jsx)(L,{type:"button",variant:"outline",size:"sm",onClick:r(()=>d([...c,i6()]),"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)(ht,{id:"generic-mcp-client-id",value:u,onChange:r(B=>h(B.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)(ht,{id:"generic-mcp-client-secret",type:"password",autoComplete:"off",value:p,onChange:r(B=>f(B.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)(L,{variant:"ghost",onClick:S,disabled:w,children:"Back"}),(0,t.jsxs)(L,{onClick:C,disabled:w||!T||!!R,children:[w&&(0,t.jsx)(rt,{className:"mr-2 h-4 w-4 animate-spin"}),w?"Checking…":"Check link"]})]})]})}r(_it,"LinkConnectStep");var dse=[{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 Iit({label:e,selected:s,onClick:n}){return(0,t.jsx)("button",{type:"button",onClick:n,"aria-pressed":s,className:W("min-w-(--sz-64px) rounded-md px-4 py-1.5 text-sm font-medium transition-colors",s?"bg-background text-foreground shadow-sm":"text-muted-foreground hover:text-foreground"),children:e})}r(Iit,"SegmentedOption");function Ait({settingsValid:e=!0,entry:s,error:n,values:a,onChange:i,oauthClientId:o,onOAuthClientIdChange:l,oauthClientSecret:c,canReuseOAuthClientSecret:d,onOAuthClientSecretChange:u,credentialSource:h,vercelConnector:p,onVercelConnectorChange:f,vercelConnectAvailability:x,methodKey:b,onMethodChange:v,configValues:j,onConfigChange:N,googleSheetsLinks:w,googleSheetsError:k,onGoogleSheetsLinksChange:S,submitting:C,renderDefaults:I,onBack:R,onConnect:T}){const A=(0,m.useMemo)(()=>Aw(s,h),[h,s]),D=b?A.find(Le=>Le.key===b)??null:vk(A),M=(0,m.useMemo)(()=>A.some(Le=>Le.capabilityProfile)?Array.from(A.reduce((Le,Qe)=>{const ut=Qe.capabilityProfile.key,Ye=Le.get(ut);return Ye?Ye.methods.push(Qe):Le.set(ut,{key:ut,label:Qe.capabilityProfile?.label??Qe.label??Qe.key,description:Qe.capabilityProfile?.description??Qe.whenToUse,methods:[Qe]}),Le},new Map)).map(([,Le])=>Le):[],[A]),B=D?.capabilityProfile?.key??D?.key??"",E=M.map(Le=>Le.key).join("|"),[z,$]=(0,m.useState)(B||vk(A)?.capabilityProfile?.key||(M.length===1?M[0].key:""));(0,m.useEffect)(()=>{if(B){$(B);return}$(Le=>M.some(Qe=>Qe.key===Le)?Le:vk(A)?.capabilityProfile?.key||(M.length===1?M[0].key:""))},[E,M,A,B]);const q=M.length>1?M.find(Le=>Le.key===z)?.methods??[]:A,U=(D?.credentialFields??[]).map(Le=>({...Le,configPath:$pe(Le,D),helpUrl:D?.consoleLinks?.keys??D?.consoleLinks?.docs??""})),O=D?.credentialSources?.vercelConnect??null,K=h==="vercel_connect",H=K||U.every(Le=>Le.required===!1||(a[Le.configPath]?.trim().length??0)>0),ee=nk(D),se=ee&&!rp(D),ne=K||!se||o.trim().length>0&&(!D?.oauthClientSecretRequired||d||c.trim().length>0),fe=!K||p.trim().length>0,X=D?.auth==="oauth"&&ee?VSe():null,re=[...D?.tenantFields??[],...D?.extensionFields??[]],oe=re.filter(Le=>!Le.hidden),G=oe.filter(Le=>Le.advanced!==!0),Y=oe.filter(Le=>Le.advanced===!0),Q=re.every(Le=>{if(!Le.required)return!0;const Qe=j[Le.key];return typeof Qe=="boolean"||typeof Qe=="string"&&Qe.trim().length>0}),te=D?.configRequirements?.atLeastOneOf??[],ae=te.length===0||te.some(Le=>{const Qe=j[Le];return typeof Qe=="string"&&Qe.trim().length>0}),le=(M.length<=1||!!z)&&(q.length<=1?!!D:!!b),he=s.availability?.robotEmail??null,ce=s.availability?.available===!1,ge=!K&&ee&&!se,me=M.length>1||q.length>1,ie=M.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)(wm,{ariaLabel:`Access level for ${s.name}`,className:"mt-2",value:z,onValueChange:r(Le=>{const Qe=M.find(ut=>ut.key===Le);Qe&&($(Le),v(s7(Qe.methods)))},"onValueChange"),options:M.map(Le=>({value:Le.key,title:Le.label,description:Le.description}))}),!z&&(0,t.jsx)("p",{className:"mt-2 text-xs text-muted-foreground",children:"Choose an access level to continue."})]}):null,ue=q.find(Le=>Le.oauthStrategy==="paperclip_cloud_connector"),ke=ue&&q.find(Le=>nk(Le)&&!rp(Le)),be=D?.key===ke?.key,Ie=(0,m.useId)(),Ue=ue&&ke&&q.length===2?(0,t.jsx)(L,{type:"button",variant:"link",className:"h-auto p-0 text-xs text-muted-foreground underline underline-offset-2 hover:text-foreground","aria-expanded":be,"aria-controls":Ie,disabled:C,onClick:r(()=>v(be?ue:ke),"onClick"),children:be?"Use Paperclip instead":`Use your own ${dLe(ue.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)(wm,{ariaLabel:`How to connect ${s.name}`,className:"mt-2",value:b,onValueChange:r(Le=>{const Qe=q.find(ut=>ut.key===Le);Qe&&v(Qe)},"onValueChange"),options:q.map(Le=>({value:Le.key,title:Le.label??(Le.auth==="oauth"?`Sign in with ${s.name}`:"Use an API key")}))}),!D&&(0,t.jsx)("p",{className:"mt-2 text-xs text-muted-foreground",children:"Choose a connection method to continue."})]}):null,at=Y.length>0||ge||me,dt=be||!le,de=at?(0,t.jsxs)("div",{className:"space-y-6",children:[ie,Ue,Y.map(Le=>(0,t.jsx)(use,{field:Le,value:j[Le.key],onChange:r(Qe=>N({...j,[Le.key]:Qe}),"onChange")},Le.key)),ge?(0,t.jsx)(c6,{entry:s,method:D,callbackUrl:X,clientId:o,onClientIdChange:l,clientSecret:c,onClientSecretChange:u,required:!1}):null]}):null,Be=I?.(de,dt)??null;if(GC(s,D)){const Le=dq(w),Qe=e&&!ce&&!!he&&w.trim().length>0;return(0,t.jsxs)("div",{className:"mx-auto max-w-xl",children:[(0,t.jsxs)("div",{className:"space-y-6",children:[ie,he?(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:he,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:he}),(0,t.jsx)(XSe,{value:he,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)(Tn,{value:w,onChange:r(ut=>S(ut.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:Le.ids.length>0?`${Le.ids.length} ${Le.ids.length===1?"sheet":"sheets"} ready to connect.`:"Paste one link per line. Both .../edit and .../edit#gid=... links work."}),k&&(0,t.jsx)("div",{className:"mt-2 text-xs text-destructive",children:k})]})]}),Be,(0,t.jsxs)("div",{className:"mt-8 flex items-center justify-between",children:[(0,t.jsx)(L,{variant:"ghost",onClick:R,disabled:C,children:"Back"}),(0,t.jsxs)(L,{onClick:T,disabled:C||!Qe,children:[C&&(0,t.jsx)(rt,{className:"mr-2 h-4 w-4 animate-spin"}),C?"Checking…":"Connect"]})]})]})}const pt=D?.connectorProfile==="asana.mcp",vt=pt?null:D?.consoleLinks?.docs??s.docsUrl;return(0,t.jsxs)("div",{className:"mx-auto max-w-xl",children:[vt?(0,t.jsx)("div",{className:"mb-4 flex justify-end",children:(0,t.jsxs)("a",{href:vt,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)(ao,{className:"h-3 w-3"})]})}):null,(0,t.jsxs)("div",{className:"space-y-6",children:[pt?(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,D?.capabilityProfile&&(0,t.jsxs)("p",{className:"text-sm text-muted-foreground",children:[D.capabilityProfile.label,": ",D.capabilityProfile.description]}),K&&O&&x?(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:x.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)(ao,{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)(ht,{id:"vercel-connect-connector",value:p,onChange:r(Le=>f(Le.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)(ha,{tone:"danger",children:n})}):null,G.map(Le=>(0,t.jsx)(use,{field:Le,value:j[Le.key],onChange:r(Qe=>N({...j,[Le.key]:Qe}),"onChange")},Le.key)),!K&&D?.auth==="oauth"&&se?(0,t.jsx)("div",{id:Ie,role:"region","aria-label":"Your OAuth app",children:(0,t.jsx)(c6,{entry:s,method:D,callbackUrl:X,clientId:o,onClientIdChange:l,clientSecret:c,onClientSecretChange:u,required:!0})}):null,K||!D||U.length===0?null:U.map(Le=>(0,t.jsxs)("div",{children:[(0,t.jsx)("label",{className:"text-sm font-medium text-foreground",children:Qte(s.name,Le.label,U.length)}),(0,t.jsx)(ht,{type:Le.type==="text"&&Le.secret===!1?"text":"password","aria-label":Qte(s.name,Le.label,U.length),autoComplete:"off",value:a[Le.configPath]??"",onChange:r(Qe=>i({...a,[Le.configPath]:Qe.target.value}),"onChange"),placeholder:Le.type==="text"&&Le.secret===!1?Le.placeholder:"••••••••••••••••",className:"mt-2 h-11 font-mono"}),Le.helperMd&&(0,t.jsx)("p",{className:"mt-2 text-xs text-muted-foreground",children:Le.helperMd}),Le.helpUrl&&(0,t.jsxs)("a",{href:Le.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)(ao,{className:"h-3 w-3"})]})]},Le.configPath))]}),Be,(0,t.jsxs)("div",{className:"mt-8 flex items-center justify-between",children:[(0,t.jsx)(L,{variant:"ghost",onClick:R,disabled:C,children:"Back"}),(0,t.jsxs)(L,{onClick:T,disabled:C||!e||!le||!H||!ne||!fe||!Q||!ae,children:[C&&(0,t.jsx)(rt,{className:"mr-2 h-4 w-4 animate-spin"}),C?"Checking…":K?D?.auth==="oauth"?"Validate and continue":"Validate and connect":D?.auth==="oauth"?s.slug==="github"?"Continue to GitHub":"Continue to sign in":"Connect"]})]})]})}r(Ait,"KeyStep");function XSe({value:e,ariaLabel:s}){const{copied:n,failed:a,copy:i}=Cp();return(0,t.jsxs)(L,{type:"button",variant:"outline",className:"shrink-0","aria-label":s,onClick:r(()=>{i(e)},"onClick"),children:[n?(0,t.jsx)(gs,{className:"mr-2 h-4 w-4"}):(0,t.jsx)(Ir,{className:"mr-2 h-4 w-4"}),n?"Copied":a?"Copy failed":"Copy"]})}r(XSe,"CopyValueButton");function c6({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)(ao,{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)(XSe,{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)(ht,{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)(ht,{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(c6,"OAuthClientFields");function use({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)(ci,{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)(Tn,{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)(ht,{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(use,"MethodConfigField");function Tit({companyId:e,...s}){const n=Z({queryKey:P.agents.list(e),queryFn:r(()=>$t.list(e),"queryFn")});return(0,t.jsx)(zW,{...s,agents:(n.data??[]).filter(a=>a.status!=="terminated"),agentsLoading:n.isLoading})}r(Tit,"AccessStep");function zW({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 I=p?.editableAgentIds,R=I?e.filter(U=>I.includes(U.id)):e,T=p?.canSetCompanyInstall??!0,A=p?.canCreateOrganizationGrant??!0,D=n!=="none",M=a??["user","organization"],B=(!D||i==="user"||i==="agent"||A)&&(j?!0:h?d.has(h):i==="agent"?l==="specific"&&d.size===1:l==="all"?T:d.size>0),E=h?e.find(U=>U.id===h)?.name??"the requesting agent":null,z=f?"Connect GitHub as":"Which humans can use this credential?",$=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?",q=f?$:"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:z}),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)(vn,{className:"h-20 w-full rounded-md"}),(0,t.jsx)(vn,{className:"h-20 w-full rounded-md"})]}):D&&M.length===1?(0,t.jsxs)("div",{className:"mt-4 flex items-center gap-3 rounded-md border border-border p-4",children:[M[0]==="user"?(0,t.jsx)(Ph,{className:"h-4 w-4 shrink-0 text-muted-foreground","aria-hidden":"true"}):M[0]==="agent"?(0,t.jsx)(so,{className:"h-4 w-4 shrink-0 text-muted-foreground","aria-hidden":"true"}):(0,t.jsx)(ck,{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:M[0]==="user"?f?"My GitHub account":"Just me":M[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:M[0]==="user"?"Agents use it only for runs where you are the responsible person.":M[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]})]}):D?(0,t.jsx)(wm,{ariaLabel:f?z:"Which humans can use this credential?",className:"mt-4 sm:grid-cols-2",value:i,onValueChange:r(U=>{const O=U;o(O),O==="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)(Ph,{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)(so,{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)(ck,{className:"h-4 w-4","aria-hidden":"true"}),accessibleLabel:A?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:A?void 0:p?.organizationGrantReason??"Only a connection manager can share this credential with the organization.",disabled:!A}].filter(U=>M.includes(U.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:$}),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)(ck,{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:E}),". 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)(wm,{ariaLabel:q,className:"mt-4 sm:grid-cols-2",value:l,onValueChange:r(U=>c(U),"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)(so,{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)(Rit,{}),accessibleLabel:T?"Any agent":`Any agent. Unavailable: ${p?.companyInstallReason??"Only someone who can configure this connection can choose this."}`,tooltip:T?void 0:p?.companyInstallReason??"Only someone who can configure this connection can choose this.",disabled:!T}]}),!j&&!h&&l==="specific"?(0,t.jsx)("div",{className:"mt-3",children:(0,t.jsx)(Zy,{agents:R,selectedAgentIds:d,onChange:r(U=>u(i==="agent"&&U.size>1?new Set([[...U].at(-1)]):U),"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)(L,{variant:"ghost",className:"w-full sm:w-auto",onClick:S,disabled:N,children:"Back"}),(0,t.jsxs)(L,{className:"w-full sm:w-auto",onClick:C,disabled:!B||v||N,children:[N?(0,t.jsx)(rt,{className:"h-4 w-4 animate-spin","aria-hidden":"true"}):null,x,!N&&b?(0,t.jsx)(ao,{className:"h-4 w-4","aria-hidden":"true"}):null]})]})]})}r(zW,"AccessStepContent");function d6(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(d6,"connectionDefaultSummarySentence");function ZSe({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)(gl,{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)(ec,{asChild:!0,children:(0,t.jsx)(L,{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)(xl,{children:(0,t.jsxs)("div",{className:"mt-3 space-y-6",children:[i,s?(0,t.jsx)(zW,{...c,agents:s,bare:!0,hideFooter:!0,submitLabel:"",onBack:r(()=>{},"onBack"),onContinue:r(()=>{},"onContinue")}):(0,t.jsx)(Tit,{...c,companyId:e,bare:!0,hideFooter:!0,submitLabel:"",onBack:r(()=>{},"onBack"),onContinue:r(()=>{},"onContinue")})]})})]})}r(ZSe,"ConnectionAccessDefaults");function Rit(){return(0,t.jsxs)("span",{className:"relative block h-4 w-5","aria-hidden":"true",children:[(0,t.jsx)(so,{className:"absolute left-0 top-0 h-3.5 w-3.5"}),(0,t.jsx)(so,{className:"absolute bottom-0 right-0 h-3.5 w-3.5"})]})}r(Rit,"BotGroupIcon");function Eit(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(Eit,"accessSummaryLines");function Pit({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)(gs,{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)(al,{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)(L,{size:"lg",className:"px-10",onClick:o,children:"View connection"})})]})}r(Pit,"ConnectionSetupCompletionScreen");function eCe(){const{newProjectOpen:e,closeNewProject:s}=FI(),{selectedCompanyId:n}=ps();return n&&e?(0,t.jsx)(Mit,{companyId:n,onClose:s},n):null}r(eCe,"NewProjectDialog");function Mit({companyId:e,onClose:s}){const n=Dt(),[a,i]=(0,m.useState)(""),[o]=(0,m.useState)(()=>y3[Math.floor(Math.random()*y3.length)]),[l,c]=(0,m.useState)([]),[d,u]=(0,m.useState)(!1),h=(0,m.useRef)(null),p=je({mutationFn:r(()=>pa.create(e,{name:a.trim(),color:o,status:"planned",repositoryIds:l.map(f=>f.id)}),"mutationFn"),onSuccess:r(f=>{Q0(f.id,e),n.invalidateQueries({queryKey:P.projects.all(e)}),s()},"onSuccess")});return(0,t.jsx)(Qs,{open:!0,onOpenChange:r(f=>{!f&&!p.isPending&&s()},"onOpenChange"),children:(0,t.jsx)(Js,{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)(Xs,{className:"sr-only",children:"Connect GitHub"}),(0,t.jsx)(c4,{host:"dialog",serviceSlug:"github",forceNewConnection:!0,onCancel:r(()=>u(!1),"onCancel"),onComplete:r(()=>{n.invalidateQueries({queryKey:$9(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)(Xs,{className:"text-lg font-semibold",children:"Create project"}),(0,t.jsx)(L,{type:"button",variant:"ghost",size:"icon-sm",disabled:p.isPending,"aria-label":"Close new project",onClick:s,children:(0,t.jsx)(Fn,{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)(Em,{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)(uwe,{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)(L,{type:"button",variant:"ghost",disabled:p.isPending,onClick:s,children:"Cancel"}),(0,t.jsx)(L,{type:"submit",disabled:!a.trim()||p.isPending,children:p.isPending?"Creating…":"Create project"})]})]})})})}r(Mit,"NewProjectForm");var ng={list:r(e=>Te.get(`/companies/${e}/goals`),"list"),get:r(e=>Te.get(`/goals/${e}`),"get"),create:r((e,s)=>Te.post(`/companies/${e}/goals`,s),"create"),update:r((e,s)=>Te.patch(`/goals/${e}`,s),"update"),remove:r(e=>Te.delete(`/goals/${e}`),"remove")};function tCe(e){return{"--sc":`var(${e})`}}r(tCe,"scStyle");function Dit(e){const s=e.replace(/_/g," ");return s.charAt(0).toUpperCase()+s.slice(1)}r(Dit,"sentenceCaseStatus");function ri({status:e,label:s}){return(0,t.jsx)("span",{className:W("inline-flex items-center rounded-full px-2.5 py-0.5 text-xs font-medium whitespace-nowrap shrink-0",Cz[e]??"bg-muted text-muted-foreground"),children:s??e.replace(/[_-]/g," ")})}r(ri,"StatusBadge$5");function sCe({status:e}){const s=QFe[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:tCe(s),children:n.replace(/_/g," ")})}r(sCe,"AgentStatusBadge");function sp({status:e,externalConversationState:s}){const n=e==="in_review"&&s==="waiting"?"idle":e,a=KFe[n]??"--status-task-backlog";return(0,t.jsxs)("span",{className:W("status-chip inline-flex items-center gap-1.5 rounded-full border px-3 py-1 text-xs font-normal leading-none whitespace-nowrap shrink-0",n==="cancelled"&&"line-through"),style:tCe(a),children:[(0,t.jsx)(OI,{status:n,size:"sm"}),Dit(n)]})}r(sp,"IssueStatusBadge");var mse={company:"Organization",team:"Team",agent:"Agent",task:"Task"};function nCe(){const{newGoalOpen:e,newGoalDefaults:s,closeNewGoal:n}=FI(),{selectedCompanyId:a,selectedCompany:i}=ps(),o=Dt(),[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),[I,R]=(0,m.useState)(!1),T=(0,m.useRef)(null),A=b||s.parentId||"",{data:D}=Z({queryKey:P.goals.list(a),queryFn:r(()=>ng.list(a),"queryFn"),enabled:!!a&&e}),M=je({mutationFn:r(U=>ng.create(a,U),"mutationFn"),onSuccess:r(()=>{o.invalidateQueries({queryKey:P.goals.list(a)}),E(),n()},"onSuccess")}),B=je({mutationFn:r(async U=>{if(!a)throw new Error("No organization selected");return bb.uploadImage(a,U,"goals/drafts")},"mutationFn")});function E(){c(""),u(""),p("planned"),x("task"),v(""),N(!1)}r(E,"reset");function z(){!a||!l.trim()||M.mutate({title:l.trim(),description:d.trim()||void 0,status:h,level:f,...A?{parentId:A}:{}})}r(z,"handleSubmit");function $(U){U.key==="Enter"&&(U.metaKey||U.ctrlKey)&&(U.preventDefault(),z())}r($,"handleKeyDown");const q=(D??[]).find(U=>U.id===A);return(0,t.jsx)(Qs,{open:e,onOpenChange:r(U=>{U||(E(),n())},"onOpenChange"),children:(0,t.jsxs)(Js,{showCloseButton:!1,className:W("p-0 gap-0",j?"sm:max-w-2xl":"sm:max-w-lg"),onKeyDown:$,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)(L,{variant:"ghost",size:"icon-xs",className:"text-muted-foreground",onClick:r(()=>N(!j),"onClick"),children:j?(0,t.jsx)(obe,{className:"h-3.5 w-3.5"}):(0,t.jsx)(Gy,{className:"h-3.5 w-3.5"})}),(0,t.jsx)(L,{variant:"ghost",size:"icon-xs",className:"text-muted-foreground",onClick:r(()=>{E(),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(U=>c(U.target.value),"onChange"),onKeyDown:r(U=>{U.key==="Tab"&&!U.shiftKey&&(U.preventDefault(),T.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)(fd,{ref:T,value:d,onChange:u,placeholder:"Add description...",bordered:!1,contentClassName:W("text-sm text-muted-foreground",j?"min-h-(--sz-220px)":"min-h-(--sz-120px)"),imageUploadHandler:r(async U=>(await B.mutateAsync(U)).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)(gr,{open:w,onOpenChange:k,children:[(0,t.jsx)(Sr,{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)(ri,{status:h})})}),(0,t.jsx)(dr,{className:"w-40 p-1",align:"start",children:qpe.map(U=>(0,t.jsx)("button",{className:W("flex items-center gap-2 w-full px-2 py-1.5 text-xs rounded hover:bg-accent/50 capitalize",U===h&&"bg-accent"),onClick:r(()=>{p(U),k(!1)},"onClick"),children:U},U))})]}),(0,t.jsxs)(gr,{open:S,onOpenChange:C,children:[(0,t.jsx)(Sr,{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)(zl,{className:"h-3 w-3 text-muted-foreground"}),mse[f]??f]})}),(0,t.jsx)(dr,{className:"w-40 p-1",align:"start",children:afe.map(U=>(0,t.jsx)("button",{className:W("flex items-center gap-2 w-full px-2 py-1.5 text-xs rounded hover:bg-accent/50",U===f&&"bg-accent"),onClick:r(()=>{x(U),C(!1)},"onClick"),children:mse[U]??U},U))})]}),(0,t.jsxs)(gr,{open:I,onOpenChange:R,children:[(0,t.jsx)(Sr,{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)(vp,{className:"h-3 w-3 text-muted-foreground"}),q?q.title:"Parent goal"]})}),(0,t.jsxs)(dr,{className:"w-48 p-1",align:"start",children:[(0,t.jsx)("button",{className:W("flex items-center gap-2 w-full px-2 py-1.5 text-xs rounded hover:bg-accent/50",!A&&"bg-accent"),onClick:r(()=>{v(""),R(!1)},"onClick"),children:"No parent"}),(D??[]).map(U=>(0,t.jsx)("button",{className:W("flex items-center gap-2 w-full px-2 py-1.5 text-xs rounded hover:bg-accent/50 truncate",U.id===A&&"bg-accent"),onClick:r(()=>{v(U.id),R(!1)},"onClick"),children:U.title},U.id))]})]})]}),(0,t.jsx)("div",{className:"flex items-center justify-end px-4 py-2.5 border-t border-border",children:(0,t.jsx)(L,{size:"sm",disabled:!l.trim()||M.isPending,onClick:z,children:M.isPending?"Creating…":s.parentId?"Create sub-goal":"Create goal"})})]})})}r(nCe,"NewGoalDialog");function Lit(e){const s=$it(e),n=Oit(e);return`You're invited to join a Paperclip company as an agent.
306
+ `;function Hnt(){const e=new Blob([Vnt],{type:"application/javascript"}),s=URL.createObjectURL(e);try{return new Worker(s)}finally{URL.revokeObjectURL(s)}}r(Hnt,"createSandboxedWorker");var Gq=new Map,T5=new Map,pE=new Set,fE=new Map,oSe=null;function Gnt(e){oSe=e}r(Gnt,"setDynamicParserResultNotifier");function lSe(e,s){e.worker.postMessage(s)}r(lSe,"sendToWorker");function Qnt(e){return e.nextId++}r(Qnt,"nextRequestId");function Ynt(e,s){return`${s}\0${e}`}r(Ynt,"lineCacheKey");function Jnt(){oSe?.()}r(Jnt,"notifyResultReady");function Xnt(e,s,n){return new Promise(a=>{const i=Qnt(e);e.pendingResolves.set(i,a),lSe(e,{type:"parse",id:i,line:s,ts:n})})}r(Xnt,"parseLineAsync");function VC(e){for(const s of e.pendingResolves.values())s([]);e.pendingResolves.clear()}r(VC,"drainPendingRequests");function Znt(e){return new Promise((s,n)=>{const a=Hnt(),i={worker:a,ready:!1,nextId:1,pendingResolves:new Map},o=setTimeout(()=>{VC(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"&&VC(i)},s(i);return}if(c.type==="error"){clearTimeout(o),VC(i),a.terminate(),n(new Error(c.message));return}},a.onerror=l=>{clearTimeout(o),VC(i),a.terminate(),n(new Error(`Worker error: ${l.message}`))},lSe(i,{type:"init",source:e})})}r(Znt,"initSandboxedWorker");function ert(e){const s=new Map,n=new Set;return{parseStdoutLine:r((i,o)=>{const l=Ynt(i,o),c=s.get(l);return c?c.slice():(n.has(l)||(n.add(l),Xnt(e,i,o).then(d=>{n.delete(l),s.set(l,d),Jnt()})),[])},"parseStdoutLine")}}r(ert,"buildParserModule");async function Qq(e){const s=T5.get(e);if(s)return s;if(pE.has(e))return null;const n=fE.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 pE.add(e),null;const o=await Znt(await i.text());Gq.set(e,o);const l=ert(o);return T5.set(e,l),l}catch{return pE.add(e),null}finally{fE.delete(e)}})();return fE.set(e,a),a}r(Qq,"loadDynamicParser");function Yq(e){const s=T5.has(e);T5.delete(e),pE.delete(e),fE.delete(e);const n=Gq.get(e);return n&&(VC(n),n.worker.terminate(),Gq.delete(e)),s}r(Yq,"invalidateDynamicParser");var xE=[],i4=new Map,Jq=new Set,cSe=new Map,$$=new Set,K2=new Map,Xq=new Set;function dSe(e){return Xq.add(e),()=>Xq.delete(e)}r(dSe,"onAdapterChange");function uSe(){for(const e of Xq)e()}r(uSe,"notifyAdapterChange");Gnt(uSe);function trt(){for(const e of[Bet,Zet,btt,Ntt,Htt,ist,bst,_st,Ost,Gst,bnt,unt,$tt,Mnt,A5,Wnt])Jq.add(e.type),cSe.set(e.type,e),jv(e)}r(trt,"registerBuiltInUIAdapters");function jv(e){const s=xE.findIndex(n=>n.type===e.type);s>=0?xE.splice(s,1,e):xE.push(e),i4.set(e.type,e),uSe()}r(jv,"registerUIAdapter");function mSe(e){return i4.get(e)??null}r(mSe,"findUIAdapter");trt();function aS(e){const s=i4.get(e);if(!s){let n=!1;return{type:e,label:e,parseStdoutLine:r((a,i)=>(n||(n=!0,Qq(e).then(o=>{o&&jv({type:e,label:e,parseStdoutLine:o.parseStdoutLine,createStdoutParser:o.createStdoutParser,ConfigFields:yy,buildAdapterConfig:aN})})),A5.parseStdoutLine(a,i)),"parseStdoutLine"),ConfigFields:yy,buildAdapterConfig:aN}}return s}r(aS,"getUIAdapter");function srt(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 Jq){const i=cSe.get(a);if(!i)continue;const o=n.has(a),l=s.has(a),c=$$.has(a);if(o&&l&&!c){$$.add(a);const d=(K2.get(a)??0)+1;K2.set(a,d);let u=!1;const h=i.parseStdoutLine,p=e.find(f=>f.type===a)?.label??a;jv({type:a,label:p,parseStdoutLine:r((f,x)=>(u||(u=!0,Qq(a).then(b=>{b&&K2.get(a)===d&&jv({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&&($$.delete(a),K2.delete(a),Yq(a),jv(i))}for(const{type:a,label:i}of e){if(Jq.has(a))continue;const o=i4.get(a);if(o&&o!==A5)continue;let l=!1;const c=o?.parseStdoutLine??A5.parseStdoutLine;jv({type:a,label:i,parseStdoutLine:r((d,u)=>(l||(l=!0,Qq(a).then(h=>{h&&jv({type:a,label:i,parseStdoutLine:h.parseStdoutLine,createStdoutParser:h.createStdoutParser,ConfigFields:o?.ConfigFields??yy,buildAdapterConfig:o?.buildAdapterConfig??aN})})),c(d,u)),"parseStdoutLine"),ConfigFields:o?.ConfigFields??yy,buildAdapterConfig:o?.buildAdapterConfig??aN})}}r(srt,"syncExternalAdapters");function IW(){return[...xE]}r(IW,"listUIAdapters");function Zq(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(Zq,"resolveStdoutParser");function hSe(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(hSe,"appendTranscriptEntry");function nrt(e,s){for(const n of s)hSe(e,n)}r(nrt,"appendTranscriptEntries");function rrt(e,s=160){return e.length<=s?e:`${e.slice(0,s-3)}...`}r(rrt,"truncateTranscriptLine");function art(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(art,"formatTranscriptParserError");function irt(e,s,n,a){const i=art(n)||"unknown parser error",o=rrt(e);return{kind:"result",ts:s,text:bm(`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(irt,"createTranscriptParseErrorEntry");function AW(e){const{entries:s,line:n,ts:a,parseLine:i,reset:o,redactionOptions:l}=e;try{nrt(s,i(n,a).map(c=>aZe(c,l)))}catch(c){o?.(),hSe(s,irt(n,a,c,l))}}r(AW,"appendParsedTranscriptLine");function pSe(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:bm(u.chunk,l)});continue}if(u.stream==="system"){s.push({kind:"system",ts:u.ts,text:bm(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&&AW({entries:s,line:f,ts:u.ts,parseLine:i,reset:o,redactionOptions:l})}}return c}r(pSe,"foldTranscriptChunks");function fSe(e,s,n){const a=[],i={enabled:n?.censorUsernameInLogs??!1},{parseLine:o,reset:l}=Zq(s),c=pSe({entries:a,chunks:e,from:0,stdoutBuffer:"",parseLine:o,reset:l,redactionOptions:i}).trim();return c&&AW({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(fSe,"buildTranscript");var Tte=[];function ort(e,s){const n={enabled:s?.censorUsernameInLogs??!1},a=typeof e!="function"&&typeof e.createStdoutParser=="function";let i=Zq(e),o=[],l="",c=Tte,d=[];const u=r(()=>{i=Zq(e),o=[],l="",c=Tte},"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 fSe(f,e,s);const b=o.slice(),v=b.length-1;return v>=0&&(b[v]={...b[v]}),x&&AW({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=pSe({entries:o,chunks:f,from:c.length,stdoutBuffer:l,parseLine:i.parseLine,reset:i.reset,redactionOptions:n}),c=f,d=p(f)),d}}}r(ort,"createIncrementalTranscript");function lrt({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)(gr,{open:c,onOpenChange:d,children:[(0,t.jsx)(Sr,{asChild:!0,children:(0,t.jsx)("button",{type:"button",className:W("inline-flex max-w-full min-w-0 items-center gap-1.5 overflow-hidden rounded-md border border-border px-2 py-1 text-xs hover:bg-accent/50 transition-colors",f&&"border-amber-600/45 bg-amber-500/5",a&&"opacity-60 cursor-not-allowed"),disabled:a,children:x?(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)(Qc,{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)(kr,{agent:p,size:16,className:"h-3 w-3 shrink-0 text-muted-foreground"}),(0,t.jsx)("span",{className:W("min-w-0 truncate",f&&"text-amber-900 dark:text-amber-200"),children:`Reports to ${p.name}${f?" (terminated)":""}`})]}):(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)(Qc,{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)(dr,{className:"w-48 p-1",align:"start",children:[(0,t.jsx)("button",{type:"button",className:W("flex items-center gap-2 w-full px-2 py-1.5 text-xs rounded hover:bg-accent/50",s===null&&"bg-accent"),onClick:r(()=>{n(null),d(!1)},"onClick"),children:"No manager"}),f&&(0,t.jsxs)("div",{className:"flex min-w-0 items-center gap-2 overflow-hidden px-2 py-1.5 text-xs text-muted-foreground border-b border-border mb-0.5",children:[(0,t.jsx)(kr,{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:W("flex items-center gap-2 w-full min-w-0 px-2 py-1.5 text-xs rounded hover:bg-accent/50 overflow-hidden",b.id===s&&"bg-accent"),onClick:r(()=>{n(b.id),d(!1)},"onClick"),children:[(0,t.jsx)(kr,{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:kW[b.role]??b.role})]},b.id))]})]})}r(lrt,"ReportsToPicker");var crt="__secret_folder__:";function drt(e){return!e||e==="active"?null:(0,t.jsx)(ct,{variant:"outline",className:"ml-auto text-(length:--text-nano) font-normal text-muted-foreground",children:e})}r(drt,"statusBadge");function xSe(e){return e.split("/").filter(s=>s.length>0)}r(xSe,"splitSecretPath$1");function gE(e){return e.join("/")}r(gE,"pathKey$1");function eC(e){return e.length>0?`/${e.join("/")}`:"/"}r(eC,"pathLabel");function urt(e,s){return e.length<s.length?!1:s.every((n,a)=>e[a]===n)}r(urt,"pathStartsWith");function Rte(e){return`${crt}${gE(e)}`}r(Rte,"folderValue");function mrt(e,s,n){const a=s.length,i=new Map,o=[];for(const c of e){const d=xSe(c.name);if(urt(d,s)){if(d.length>a+1){const u=d.slice(0,a+1),h=gE(u);if(!i.has(h)){const p=u[u.length-1]??"/",f=eC(u);i.set(h,{key:`folder-${h||"root"}`,value:Rte(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-${gE(s)}`,value:Rte(c),label:"Up one folder",title:eC(c),searchText:eC(c),kind:"back",folderPath:gE(c),pathHint:eC(c)})}return l.push(...i.values(),...o),{id:"browse-secrets",label:s.length>0?eC(s):"Browse secrets",options:l}}r(mrt,"buildFolderGroup");function TW({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=>xSe(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||MFe(j))return N;const w=mrt(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)(Ky,{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:W("h-(--sz-34px) min-h-(--sz-34px) font-mono text-sm",p&&"border-destructive text-destructive",h&&h.status!=="active"&&"border-amber-500/60",l),renderValue:r(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:W("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"?Yze:Jl;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:W("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:W("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:W("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]}),drt(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)(yn,{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(TW,"SecretPicker");var hrt=/^[a-z][a-z0-9_]*$/,Ete="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 gSe({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?hrt.test(w)?a?.some(T=>T.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 I(){if(N(!0),!!C){x(!0),v(null);try{await o(w,d)}catch(T){v(T instanceof Error?T.message:"Failed to create secret"),x(!1)}}}r(I,"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)($Fe,{className:"text-sm font-medium",children:e==="create"?"Create secret":"Store value as secret"}),e==="store"?(0,t.jsxs)(OFe,{className:"text-(length:--text-micro) text-muted-foreground",children:["Moves the typed value into an encrypted organization secret and binds"," ",(0,t.jsx)("span",{className:"font-mono",children:s||"this variable"})," to it."]}):null]}),(0,t.jsxs)("label",{className:"block space-y-1",children:[(0,t.jsx)("span",{className:"text-(length:--text-micro) font-medium text-muted-foreground",children:"Name"}),(0,t.jsx)("input",{className:W(Ete,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(T=>c(T.target.value),"onChange"),onBlur:r(()=>N(!0),"onBlur"),onKeyDown:r(T=>{T.key==="Enter"&&(T.preventDefault(),I())},"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:W(Ete,"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"?T=>u(T.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(T=>!T),"onClick"),children:h?(0,t.jsx)(Mm,{className:"h-3.5 w-3.5"}):(0,t.jsx)(Pd,{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)(L,{type:"button",variant:"ghost",size:"sm",onClick:i,disabled:f,children:"Cancel"}),(0,t.jsxs)(L,{type:"button",size:"sm",onClick:r(()=>{I()},"onClick"),disabled:!C,children:[f?(0,t.jsx)(rt,{className:"h-3.5 w-3.5 animate-spin"}):null,R]})]})]})}r(gSe,"SecretPopoverForm");function bSe(e){return(0,t.jsx)(gSe,{mode:"create",...e})}r(bSe,"CreateSecretPopover");function prt(e){return(0,t.jsx)(gSe,{mode:"store",...e})}r(prt,"ConvertToSecretPopover");var frt=/(api[-_]?key|access[-_]?token|auth(?:_?token)?|authorization|bearer|secret|passwd|password|credential|jwt|private[-_]?key|cookie|connectionstring)/i,xrt=[/^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 grt(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(grt,"looksHighEntropy");function brt(e,s){return s?frt.test(e)||xrt.some(n=>n.test(s))?!0:grt(s):!1}r(brt,"isSensitiveEnv");var Pte=0;function vrt(){return Pte+=1,`env-row-${Pte}`}r(vrt,"nextRowId");function Fx(e="text"){return{id:vrt(),name:"",source:e,textValue:"",secretId:"",userSecretKey:"",required:!0,version:"latest"}}r(Fx,"emptyRow");function yrt(e){return typeof e=="object"&&e!==null&&"type"in e&&e.type==="secret_ref"}r(yrt,"isSecretRef");function jrt(e){return typeof e=="object"&&e!==null&&"type"in e&&e.type==="plain"}r(jrt,"isPlainObj");function wrt(e){return typeof e=="object"&&e!==null&&"type"in e&&e.type==="user_secret_ref"}r(wrt,"isUserSecretRef");function O$(e){return!e||typeof e!="object"?[]:Object.entries(e).map(([s,n])=>{if(typeof n=="string")return{...Fx(),name:s,textValue:n};if(yrt(n)){const a=typeof n.version=="number"?n.version:"latest";return{...Fx(),name:s,source:"secret",secretId:typeof n.secretId=="string"?n.secretId:"",version:a}}if(wrt(n)){const a=typeof n.version=="number"?n.version:"latest";return{...Fx(),name:s,source:"user_secret",userSecretKey:typeof n.key=="string"?n.key:"",required:n.required!==!1,version:a}}return jrt(n)?{...Fx(),name:s,source:"text",textValue:typeof n.value=="string"?n.value:""}:{...Fx(),name:s}})}r(O$,"rowsFromValue");function bE(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(bE,"valueFromRows");var Mte="CLAUDE_CODE_OAUTH_TOKEN";function Vw(){return bE([{...Fx("user_secret"),name:"CLAUDE_CODE_OAUTH_TOKEN",userSecretKey:"CLAUDE_CODE_OAUTH_TOKEN",required:!0,version:"latest"}])??{}}r(Vw,"buildFixedClaudeOAuthBinding");var krt=/^[A-Za-z_][A-Za-z0-9_]*$/;function Nrt(e,s,n){const a=e.trim();if(!a)return null;if(!krt.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(Nrt,"validateName");function Srt(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(Srt,"computeDuplicateNames");function Crt(e,s){return s===e.source?{kind:"noop"}:s==="secret"?e.textValue.trim()?{kind:"open-store",name:R5(e.name)||"secret",value:e.textValue}:{kind:"to-secret"}:{kind:"to-text",undoFrom:e.secretId?{...e}:null}}r(Crt,"planSourceSwitch");function vSe(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(vSe,"computeRowHealth");function ySe(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(ySe,"computeUserSecretRowHealth");function R5(e){return e.trim().toLowerCase().replace(/[^a-z0-9_]+/g,"_").replace(/^_+|_+$/g,"").slice(0,64)}r(R5,"secretNameFromKey");function P1(e){return e.trim().toUpperCase().replace(/[^A-Z0-9_]+/g,"_").replace(/^_+|_+$/g,"").slice(0,64)}r(P1,"envKeyFromSecretName");var _rt="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",Dte="min-w-0 flex-1 bg-transparent px-2 py-1.5 text-sm font-mono outline-none placeholder:text-muted-foreground/40";function Irt({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,I]=(0,m.useState)(null),[R,T]=(0,m.useState)(!1),[A,D]=(0,m.useState)(null),M=vSe(e,n)??ySe(e,a),B=e.source==="secret"?n.find(X=>X.id===e.secretId)??null:null,E=(a?.length??0)>0,z=e.source==="text"&&!e.sensitiveDismissed&&brt(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(!A)return;const X=window.setTimeout(()=>D(null),5e3);return()=>window.clearTimeout(X)},[A]);function $(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 re=Crt(e,X);switch(re.kind){case"noop":return;case"open-store":{const{name:oe,value:G}=re;window.setTimeout(()=>I({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":re.undoFrom&&D(re.undoFrom),u({source:"text",secretId:"",userSecretKey:"",required:!0,version:"latest"}),window.setTimeout(()=>k.current?.focus(),0);return}}r($,"switchSource");async function q(X,re){const oe=await b(X,re);u({source:"secret",secretId:oe.id,userSecretKey:"",required:!0,version:"latest",textValue:""}),v(`Secret ${oe.name} created`),I(null)}r(q,"submitSecretPopover");function U(){const X=R5(e.name)||"secret",{textValue:re}=e;window.setTimeout(()=>I({mode:"store",name:X,value:re}),0)}r(U,"openStoreAsSecret");const O=e.source==="text"?"Text value":e.source==="secret"?"Organization secret reference":"User secret reference",K=`${e.id}-name-error`,H=`${e.id}-health`,ee=d.name||d.value,se=B?Math.max(0,B.latestVersion):0,ne=e.version==="latest"?"latest":`v${e.version}`,fe=e.version!=="latest";return(0,t.jsxs)("div",{className:W("group/row grid grid-cols-(--gtc-13) items-start gap-x-1.5 gap-y-1 rounded-md px-1 py-1","@[40rem]/env:grid-cols-(--gtc-14) @[40rem]/env:items-center",ee&&"bg-amber-500/[0.06] ring-1 ring-amber-500/20"),children:[(0,t.jsx)("div",{className:"col-start-1 row-start-1 min-w-0 @[40rem]/env:row-start-1 @[40rem]/env:self-start",children:(0,t.jsx)("input",{ref:w,className:W(_rt,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)(gr,{open:C!==null,onOpenChange:r(X=>{X||I(null)},"onOpenChange"),children:[(0,t.jsx)(Sz,{asChild:!0,children:(0,t.jsxs)("div",{ref:S,className:W("relative flex items-stretch overflow-hidden rounded-md border border-border bg-transparent focus-within:ring-2 focus-within:ring-ring/40",d.value&&"border-amber-500/70 bg-amber-500/10 focus-within:ring-amber-500/40",o&&"opacity-60"),children:[(0,t.jsxs)(Xr,{children:[(0,t.jsxs)(zn,{children:[(0,t.jsx)(qn,{asChild:!0,children:(0,t.jsx)(Jr,{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)(Rqe,{className:"size-3.5"}):e.source==="secret"?(0,t.jsx)(Si,{className:"size-3.5"}):(0,t.jsx)(Ph,{className:"size-3.5"}),(0,t.jsx)(nn,{className:"size-3 opacity-60"})]})})}),(0,t.jsx)(Un,{side:"top",children:O})]}),(0,t.jsxs)(Zr,{align:"start",className:"w-56",children:[(0,t.jsxs)(ls,{className:"flex-col items-start gap-0.5",onSelect:r(()=>$("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)(ls,{className:"flex-col items-start gap-0.5",onSelect:r(()=>$("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)(ls,{className:"flex-col items-start gap-0.5",onSelect:r(()=>$("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:Dte,placeholder:"value",value:e.textValue,type:z?"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")}),z?(0,t.jsxs)("div",{className:"flex shrink-0 items-stretch border-l border-border",children:[(0,t.jsxs)("button",{type:"button",onClick:U,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)(bc,{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)(Fn,{className:"size-3"})})]}):null]}):e.source==="secret"?(0,t.jsxs)("div",{className:"relative min-w-0 flex-1",children:[(0,t.jsx)(TW,{secretId:e.secretId,secrets:n,recentlyUsedSecrets:i,disabled:o,onSelect:r(X=>u({secretId:X,version:"latest"}),"onSelect"),onCreateNew:r(X=>I({mode:"create",name:R5(X)||X.trim(),value:""}),"onCreateNew"),triggerClassName:W("rounded-none border-0 bg-transparent shadow-none focus-visible:ring-0",B&&B.status==="active"&&"pr-24 has-[>svg]:!pr-24")}),B&&B.status==="active"?(0,t.jsxs)(gr,{open:R,onOpenChange:T,children:[(0,t.jsx)(Sz,{asChild:!0,children:(0,t.jsx)("button",{type:"button",disabled:o,onClick:r(X=>{X.preventDefault(),X.stopPropagation(),T(re=>!re)},"onClick"),"aria-label":"Version",className:W("absolute right-8 top-1/2 z-10 -translate-y-1/2 rounded px-1.5 py-0.5 text-(length:--text-nano) font-medium",fe?"bg-amber-500/15 text-amber-700 dark:text-amber-400":"text-muted-foreground hover:bg-accent"),children:ne})}),(0,t.jsxs)(dr,{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"}),T(!1)},"onClick"),className:W("flex w-full items-center justify-between rounded px-2 py-1.5 text-sm hover:bg-accent",e.version==="latest"&&"font-medium"),children:["latest ",(0,t.jsx)("span",{className:"text-(length:--text-micro) text-muted-foreground",children:"(recommended)"})]}),Array.from({length:se},(X,re)=>se-re).filter(X=>X>0).map(X=>(0,t.jsxs)("button",{type:"button",role:"radio","aria-checked":e.version===X,onClick:r(()=>{u({version:X}),T(!1)},"onClick"),className:W("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:[E?(0,t.jsxs)("select",{"aria-label":"User secret",value:e.userSecretKey,disabled:o,onChange:r(X=>{const re=X.target.value,oe=a?.find(G=>G.key===re);u({userSecretKey:re,...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:Dte,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)(dr,{align:"start",className:"w-auto p-3",onInteractOutside:r(X=>{const re=X.detail.originalEvent.target;re&&S.current?.contains(re)&&X.preventDefault()},"onInteractOutside"),children:C?.mode==="store"?(0,t.jsx)(prt,{initialName:C.name,initialValue:C.value,existingSecretNames:n.map(X=>X.name),onCancel:r(()=>I(null),"onCancel"),onSubmit:q}):C?.mode==="create"?(0,t.jsx)(bSe,{initialName:C.name,initialValue:C.value,existingSecretNames:n.map(X=>X.name),onCancel:r(()=>I(null),"onCancel"),onSubmit:q}):null})]}),M?(0,t.jsx)("p",{id:H,role:"status",className:W("mt-0.5 text-(length:--text-micro)",M.level==="error"?"text-destructive":"text-amber-600 dark:text-amber-400"),children:M.message}):null,A?(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:A.secretId,version:A.version,textValue:""}),D(null)},"onClick"),children:"Undo"})]}):null]}),c&&l?(0,t.jsx)("p",{id:K,className:W("col-span-2 col-start-1 row-start-3 min-w-0 text-(length:--text-micro) @[40rem]/env:col-span-2 @[40rem]/env:row-start-2",l.level==="error"?"text-destructive":"text-amber-600 dark:text-amber-400"),children:l.message}):null,(0,t.jsxs)("div",{className:"col-start-2 row-start-1 flex items-center justify-end gap-0.5 self-start @[40rem]/env:col-start-3 @[40rem]/env:self-center",children:[e.source==="text"&&!z&&(e.name.trim()||e.textValue)?(0,t.jsxs)(Xr,{children:[(0,t.jsx)(Jr,{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)(Ri,{className:"size-4"})})}),(0,t.jsx)(Zr,{align:"end",children:(0,t.jsx)(ls,{onSelect:r(()=>{window.setTimeout(U,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)(Fn,{className:"size-4"})})]})]})}r(Irt,"EnvironmentVariableRow");var Art=/^\s*(?:export\s+)?([A-Za-z_][A-Za-z0-9_]*)\s*=(.*)$/;function Trt(e){const s=e.indexOf(" #");return s>=0?e.slice(0,s):e}r(Trt,"stripInlineComment");function Rrt(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 Trt(s).trim()}r(Rrt,"unquote");function Ert(e){const s=[];for(const n of e.split(/\r?\n/)){const a=n.trim();if(!a||a.startsWith("#"))continue;const i=Art.exec(a);if(!i)continue;const o=i[1],l=Rrt(i[2]);s.push({key:o,value:l})}return s}r(Ert,"parseDotenv");var Prt=["PAPERCLIP_"],Mrt="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 e6(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(e6,"normalizedEnvEntries");function tC(e){return JSON.stringify(e6(e))}r(tC,"normalizedEnvKey");var F$=3;function B$(e){const s=e.slice(0,F$).join(", ");return e.length>F$?`${s} +${e.length-F$} more`:s}r(B$,"formatChangedNames");function Lte(e){return e.map(s=>({...s}))}r(Lte,"cloneRows");function Drt(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(Drt,"rowDirtyFields");var jy=(0,m.forwardRef)(r(function({value:s,onChange:n,secrets:a,userSecretDefinitions:i,onCreateSecret:o,recentlyUsedSecrets:l,disabled:c,reservedPrefixes:d=Prt,footerHint:u,onDirtyChange:h,hideDraftActions:p=!1},f){const x=Xc(),b=(0,m.useRef)(null),[v,j]=(0,m.useState)(()=>O$(s)),N=(0,m.useRef)(v),[w,k]=(0,m.useState)(()=>Lte(v)),S=(0,m.useMemo)(()=>tC(s),[]),C=(0,m.useRef)(S),I=(0,m.useRef)(S),R=(0,m.useRef)(null),[T,A]=(0,m.useState)(S),[D,M]=(0,m.useState)(()=>new Set(O$(s).map(ie=>ie.name.trim()).filter(Boolean))),[B,E]=(0,m.useState)(null);(0,m.useEffect)(()=>{N.current=v},[v]);function z(ie,ue=N.current){C.current=ie,A(ie),k(Lte(ue))}r(z,"markCommitted");function $(ie){M(ue=>{const ke=new Set(ue);for(const be of ie){const Ie=be.name.trim();Ie&&ke.add(Ie)}return ke})}r($,"touchCommittedNames");function q(ie){const ue=O$(ie);return j(ue),$(ue),ue}r(q,"adoptExternalValue"),(0,m.useEffect)(()=>{const ie=tC(s);if(ie===I.current)return;I.current=ie;const ue=tC(bE(N.current)),ke=ue!==C.current,be=R.current===ie;if(be&&(R.current=null),!ke){z(ie,q(s));return}(be||ue===ie)&&($(N.current),z(ie))},[s]);const U=(0,m.useMemo)(()=>bE(v),[v]),O=(0,m.useMemo)(()=>tC(U),[U]),K=O!==T;(0,m.useEffect)(()=>{h?.(!c&&K)},[c,K,h]);const H=(0,m.useMemo)(()=>{const ie=new Map(e6(bE(w)).map(([Ie,Ue])=>[Ie,JSON.stringify(Ue)])),ue=new Map(e6(U).map(([Ie,Ue])=>[Ie,JSON.stringify(Ue)])),ke=[],be=[];for(const[Ie,Ue]of ue)ie.has(Ie)?ie.get(Ie)!==Ue&&be.push(Ie):ke.push(Ie);return{added:ke,changed:be,removed:[...ie.keys()].filter(Ie=>!ue.has(Ie))}},[w,U]),ee=(0,m.useMemo)(()=>{const ie=[];return H.added.length>0&&ie.push(`New: ${B$(H.added)}`),H.changed.length>0&&ie.push(`Edited: ${B$(H.changed)}`),H.removed.length>0&&ie.push(`Removed: ${B$(H.removed)}`),ie.join(" · ")},[H]);(0,m.useEffect)(()=>{if(c||!K)return;function ie(ue){ue.preventDefault(),ue.returnValue=""}return r(ie,"handleBeforeUnload"),window.addEventListener("beforeunload",ie),()=>window.removeEventListener("beforeunload",ie)},[c,K]);const se=(0,m.useCallback)(()=>c||!K?null:(R.current=O,(0,hp.flushSync)(()=>{n(U)}),U??{}),[c,U,O,K,n]);(0,m.useImperativeHandle)(f,()=>({flushPendingDraft:se}),[se]),(0,m.useEffect)(()=>{const ie=b.current?.closest("form");if(!ie)return;function ue(){se()}return r(ue,"handleSubmit"),ie.addEventListener("submit",ue,!0),()=>ie.removeEventListener("submit",ue,!0)},[se]),(0,m.useEffect)(()=>{const ie=b.current;if(!ie)return;const ue=ie;function ke(be){const Ie=be.target;if(!(Ie instanceof Element)||ue.contains(Ie))return;const Ue=Ie.closest("button");if(!Ue||Ue.disabled)return;const at=`${Ue.getAttribute("aria-label")??""} ${Ue.textContent??""}`;(Ue.type==="submit"||/\b(save|create|update|test|import)\b/i.test(at))&&se()}return r(ke,"handleDocumentClick"),document.addEventListener("click",ke,!0),()=>document.removeEventListener("click",ke,!0)},[se]);function ne(ie){j(ie)}r(ne,"updateDraft");function fe(ie,ue){ne(v.map(ke=>ke.id===ie?{...ke,...ue}:ke))}r(fe,"patchRow");function X(ie){ne(v.filter(ue=>ue.id!==ie))}r(X,"removeRow");function re(){const ie=Fx();j([...v,ie]),E({rowId:ie.id,field:"name"})}r(re,"addRow");function oe(ie){const ue=v.find(ke=>ke.id===ie)?.name.trim();ue&&M(ke=>{if(ke.has(ue))return ke;const be=new Set(ke);return be.add(ue),be})}r(oe,"markTouched");function G(ie,ue){const ke=Ert(ie);if(ke.length===0)return!1;const be=v.filter(Ie=>Ie.id!==ue).map(Ie=>({...Ie}));for(const{key:Ie,value:Ue}of ke){const at=be.find(dt=>dt.name.trim()===Ie);at?(at.name=Ie,at.source="text",at.textValue=Ue,at.secretId="",at.sensitiveDismissed=!1,at.userSecretKey="",at.required=!0):be.push({...Fx(),name:Ie,textValue:Ue})}return ne(be),x?.pushToast({title:`Imported ${ke.length} variable${ke.length===1?"":"s"}`,tone:"success"}),!0}r(G,"bulkImport");function Y(ie){const ue=v.map(Ie=>({...Ie})),ke=ue[ue.length-1];let be;ke&&!ke.name&&!ke.textValue&&!ke.secretId&&!ke.userSecretKey?be=ke:(be=Fx(),ue.push(be)),be.source="secret",be.secretId=ie.id,be.version="latest",be.name||(be.name=P1(ie.name)),ne(ue)}r(Y,"bindRecentSecret");function Q(){K&&(R.current=O,n(U))}r(Q,"saveDraft");function te(){R.current=null,I.current=tC(s);const ie=q(s);z(I.current,ie)}r(te,"revertDraft");const ae=(0,m.useMemo)(()=>Srt(v),[v]),le=(0,m.useMemo)(()=>v.reduce((ie,ue)=>vSe(ue,a)||ySe(ue,i)?ie+1:ie,0),[v,a,i]),he=(0,m.useMemo)(()=>{const ie=new Set(v.filter(ue=>ue.source==="secret"&&ue.secretId).map(ue=>ue.secretId));return(l??[]).filter(ue=>ue.status==="active"&&!ie.has(ue.id)).slice(0,8)},[l,v]),ce=v.length>0,ge=u===void 0?Mrt:u,me=(0,m.useMemo)(()=>new Map(w.map(ie=>[ie.id,ie])),[w]);return(0,t.jsx)(Md,{children:(0,t.jsxs)("div",{ref:b,className:"@container/env space-y-2",children:[le>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)(Zi,{className:"size-3.5"}),le," bindings need attention"]}):null,ce?(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((ie,ue)=>{const ke=Nrt(ie.name,ae,d),be=D.has(ie.name.trim());return(0,t.jsx)(Irt,{row:ie,isLast:ue===v.length-1,secrets:a,userSecretDefinitions:i,recentlyUsedSecrets:l,disabled:c,nameIssue:ke,showNameIssue:be,dirtyFields:Drt(ie,me.get(ie.id)),onPatch:r(Ie=>fe(ie.id,Ie),"onPatch"),onRemove:r(()=>X(ie.id),"onRemove"),onNameBlur:r(()=>oe(ie.id),"onNameBlur"),onNamePaste:r(Ie=>G(Ie,ie.id),"onNamePaste"),onEnterInValueLast:re,onCreateSecret:o,onToast:r(Ie=>x?.pushToast({title:Ie,tone:"success"}),"onToast"),focusRequest:B?.rowId===ie.id?B.field:null,onFocusConsumed:r(()=>E(null),"onFocusConsumed")},ie.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:re,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)(yn,{className:"size-3.5"}),"Add variable"]}),he.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:"]}),he.map(ie=>(0,t.jsxs)("button",{type:"button",onClick:r(()=>Y(ie),"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 ${ie.name}`,children:["+ ",ie.name]},ie.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"})]}),ee?(0,t.jsx)("p",{className:"min-w-0 truncate pl-4 text-xs text-amber-950/80 dark:text-amber-100/80",title:ee,children:ee}):null]}),(0,t.jsxs)("div",{className:"flex items-center gap-2",children:[(0,t.jsxs)("button",{type:"button",onClick:te,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)(Ci,{className:"size-4"}),"Revert"]}),(0,t.jsxs)("button",{type:"button",onClick:Q,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)(Sf,{className:"size-4"}),"Save"]})]})]}):null,ge?(0,t.jsx)("p",{className:"text-(length:--text-micro) text-muted-foreground/70",children:ge}):null,v.some(ie=>ie.source==="user_secret"&&ie.userSecretKey)?(0,t.jsxs)("p",{className:"inline-flex items-start gap-1 text-(length:--text-micro) text-muted-foreground/70",children:[(0,t.jsx)(Ph,{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")),Lrt="env.",mA="access.",t6=/^[A-Za-z_][A-Za-z0-9_]*$/;function jSe(e){return e?e.startsWith("access.")?"api":e.startsWith("env.")?"env":"config":"config"}r(jSe,"deliveryModeForConfigPath");function wSe(e){switch(e){case"env":return"Env var";case"api":return"API access";default:return"Config"}}r(wSe,"deliveryModeLabel");function $rt(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($rt,"deliveryModeDescription");function kSe(e){return e?e.startsWith("access.")?e.slice(7):e.startsWith("env.")?e.slice(4):e:""}r(kSe,"aliasFromConfigPath");function Ort(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(Ort,"consumerTypeLabel");var Frt={numeric:!0,sensitivity:"base"};function HC(e){return e.kind==="company"?e.secret.name:e.definition.name}r(HC,"getSecretPathRowName");function cN(e){return e.split("/").filter(s=>s.length>0)}r(cN,"splitSecretPath");function z$(e){return cN(e).join("/")}r(z$,"normalizeSecretPath");function $te(e,s){return s.every((n,a)=>e[a]===n)}r($te,"startsWithSegments");function Ote(e,s){return e.localeCompare(s,void 0,Frt)}r(Ote,"compareNames");function Brt(e,s){const n=cN(s),a=e.map(c=>({row:c,name:HC(c),segments:cN(HC(c))})),i=new Set,o=[];for(const c of a){if(!$te(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(!$te(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)=>Ote(c.name,d.name)),o.sort((c,d)=>Ote(HC(c),HC(d))),{folders:l,secrets:o}}r(Brt,"buildSecretPathListing");function zrt(e){const s=cN(e);return s.map((n,a)=>({name:n,path:s.slice(0,a+1).join("/")}))}r(zrt,"buildSecretPathBreadcrumbs");function qrt(e){return e.trim()?e.includes("/")?"Folder name cannot contain slashes.":null:"Folder name is required."}r(qrt,"validateSecretFolderSegment");function $_({name:e,basePath:s="",className:n,leafClassName:a}){const i=cN(e),o=cN(s),l=o.length>0&&o.every((h,p)=>i[p]===h)&&i.length>o.length?i.slice(o.length):i,c=l.length>0?l:[e],d=c[c.length-1],u=c.slice(0,-1).join("/");return(0,t.jsxs)("span",{className:W("min-w-0 truncate",n),children:[u?(0,t.jsxs)("span",{className:"text-muted-foreground",children:[u,"/"]}):null,(0,t.jsx)("span",{className:W("font-medium text-foreground",a),children:d})]})}r($_,"SecretPathName");function Urt(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(Urt,"fingerprintLabel");function NSe({fingerprint:e,length:s,className:n}){const{pushToast:a}=da(),i=Urt(e,s);if(!e)return(0,t.jsxs)("span",{className:W("inline-flex items-center gap-1 font-mono",n),children:[(0,t.jsx)(Lz,{className:"size-3 shrink-0"}),i]});const o=`sha256:${e}`;return(0,t.jsxs)("button",{type:"button",onClick:r(()=>{fa(o).then(()=>a({title:"Fingerprint copied",tone:"success"})).catch(()=>a({title:"Couldn’t copy fingerprint",tone:"error"}))},"onClick"),title:`Copy full digest — ${o}`,className:W("inline-flex items-center gap-1 font-mono hover:text-foreground",n),children:[(0,t.jsx)(Lz,{className:"size-3 shrink-0"}),i,(0,t.jsx)(Ir,{className:"size-3 shrink-0 opacity-60"})]})}r(NSe,"FingerprintChip");function RW({justification:e,className:s}){return(0,t.jsxs)("div",{className:W("space-y-0.5",s),children:[(0,t.jsx)("p",{className:"text-(length:--text-micro) text-muted-foreground",children:"Reason given by the agent"}),(0,t.jsxs)("p",{className:"whitespace-pre-wrap break-words text-xs text-foreground/80",children:["“",e,"”"]})]})}r(RW,"ProposalJustification");function O_({agent:e,className:s}){return(0,t.jsxs)("span",{className:W("inline-flex min-w-0 items-center gap-1",s),children:[(0,t.jsx)(kr,{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(O_,"AgentRefChip");function EW({configPath:e}){const s=jSe(e),n=s==="env",a=s==="api";return(0,t.jsxs)(ct,{variant:"outline",className:W("h-5 gap-1 px-1.5 text-(length:--text-nano) font-normal",n&&"border-sky-500/30 bg-sky-500/10 text-sky-700 dark:text-sky-300",a&&"border-violet-500/30 bg-violet-500/10 text-violet-700 dark:text-violet-300",!n&&!a&&"border-border bg-muted/40 text-muted-foreground"),children:[n?(0,t.jsx)(Bve,{className:"size-3"}):a?(0,t.jsx)(_M,{className:"size-3"}):null,wSe(s)]})}r(EW,"DeliveryBadge$1");function PW({className:e}){return(0,t.jsxs)(ct,{variant:"outline",className:W("h-5 gap-1 px-1.5 text-(length:--text-nano) font-medium","border-amber-500/40 bg-amber-500/10 text-amber-700 dark:text-amber-300",e),children:[(0,t.jsx)(bc,{className:"size-3"})," Proposed"]})}r(PW,"ProposedBadge");function o4(e){return kSe(e.configPath)}r(o4,"bindingEnvKey");function MW(e){return e.secretProposalId?{name:e.secretProposalName??"proposed secret",pending:!0}:{name:e.secretName??"secret",pending:!1}}r(MW,"bindingSecretLabel");function Fte(e){return e instanceof dn?e.message||`Request failed: ${e.status}`:e instanceof Error?e.message:"Something went wrong. Try again."}r(Fte,"readableError");function SSe(e,s=[]){const n=Dt(),{pushToast:a}=da(),[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:P.secrets.list(e)}))},[e,n]),x=je({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 vr.approveProposal(e,k.id,{overrides:{name:S,description:w.description.trim()||null,providerConfigId:w.providerConfigId||null}})}return vr.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"} · ${o4(w)||"binding"}`,tone:"success"}),o(null),p(null),f()},"onSuccess"),onError:r(w=>p(Fte(w)),"onError")}),b=je({mutationFn:r(({proposal:w,reason:k})=>vr.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(Fte(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)(Krt,{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)(Vrt,{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(SSe,"useProposalReview");function Krt({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)(Qs,{open:!!e,onOpenChange:r(p=>!p&&o(),"onOpenChange"),children:(0,t.jsx)(Js,{className:"sm:max-w-lg",children:e?(0,t.jsxs)(t.Fragment,{children:[(0,t.jsxs)(hn,{children:[(0,t.jsx)(Xs,{children:c?"Approve & create secret":"Approve binding"}),(0,t.jsx)(jn,{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)(O_,{agent:e.proposal.proposedBy,className:"font-medium text-foreground"})]}),(0,t.jsx)(RW,{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)(Gs,{htmlFor:"approve-folder",children:"Folder"}),(0,t.jsx)(ht,{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)(Gs,{htmlFor:"approve-name",children:"Name"}),(0,t.jsx)(ht,{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)($_,{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)(Gs,{htmlFor:"approve-description",children:"Description"}),(0,t.jsx)(ht,{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)(Gs,{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)(NSe,{fingerprint:e.proposal.valueFingerprintSha256,length:e.proposal.valueLength})})]}):(0,t.jsx)(Wrt,{draft:e,onChange:i}),s?(0,t.jsx)("p",{className:"text-xs text-destructive",role:"alert",children:s}):null,(0,t.jsxs)(hr,{children:[(0,t.jsx)(L,{variant:"ghost",onClick:o,disabled:n,children:"Cancel"}),(0,t.jsx)(L,{onClick:l,disabled:n||!h,children:n?"Approving…":c?"Approve & create":e.cascade?"Approve secret & bind":"Approve binding"})]})]}):null})})}r(Krt,"ApproveDialog");function Wrt({draft:e,onChange:s}){const{proposal:n}=e,a=MW(n),i=o4(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)(O_,{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)(EW,{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)(PW,{}):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)(pi,{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(Wrt,"BindingApproveBody");function Vrt({proposal:e,reason:s,error:n,pending:a,onReasonChange:i,onCancel:o,onConfirm:l}){const c=s.trim().length>0;return(0,t.jsx)(Qs,{open:!!e,onOpenChange:r(d=>!d&&o(),"onOpenChange"),children:(0,t.jsx)(Js,{className:"sm:max-w-md",children:e?(0,t.jsxs)(t.Fragment,{children:[(0,t.jsxs)(hn,{children:[(0,t.jsx)(Xs,{children:"Reject proposal"}),(0,t.jsxs)(jn,{children:["The reason is sent back to"," ",(0,t.jsx)(O_,{agent:e.proposedBy,className:"text-foreground"}),". Dependent bindings are rejected too."]})]}),(0,t.jsxs)("div",{className:"space-y-1",children:[(0,t.jsx)(Gs,{htmlFor:"reject-reason",children:"Reason"}),(0,t.jsx)(Tn,{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)(hr,{children:[(0,t.jsx)(L,{variant:"ghost",onClick:o,disabled:a,children:"Cancel"}),(0,t.jsx)(L,{variant:"destructive",onClick:l,disabled:a||!c,children:a?"Rejecting…":"Reject"})]})]}):null})})}r(Vrt,"RejectDialog");function CSe({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)(L,{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)(Md,{children:(0,t.jsxs)(zn,{children:[(0,t.jsx)(qn,{asChild:!0,children:(0,t.jsx)("span",{tabIndex:0,children:c})}),(0,t.jsx)(Un,{className:"max-w-72",children:e.approveBlockReason??"You don’t have permission to approve this."})]})}):c,(0,t.jsx)(L,{size:"sm",variant:"outline",className:l,disabled:a,onClick:r(()=>n(e),"onClick"),children:"Reject"})]})}r(CSe,"ProposalActions");function _Se(e){return typeof e!="object"||e===null||Array.isArray(e)?null:e}r(_Se,"asRecord$16");function ISe(e){const s=_Se(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(ISe,"readSecretRef");function Hrt(e){const s=_Se(e?.env);if(!s)return[];const n=[];for(const[a,i]of Object.entries(s)){const o=ISe(i);o&&n.push({name:a,...o})}return n}r(Hrt,"parseEnvSecretRefs");function Grt(e){if(!e)return[];const s=[];for(const[n,a]of Object.entries(e)){if(!n.startsWith("access."))continue;const i=ISe(a);i&&s.push({name:n.slice(mA.length),...i})}return s}r(Grt,"parseAccessGrants");function Qrt(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(Qrt,"summarizeAgentBindings");var Bte=0;function ASe(){return Bte+=1,`access-row-${Bte}`}r(ASe,"nextAccessRowId");function q$(e){return e.map(s=>({id:ASe(),alias:s.name,secretId:s.secretId,version:s.version}))}r(q$,"entriesToRows");function zte(e){const s={};for(const n of e){const a=n.alias.trim();!a||!t6.test(a)||!n.secretId||(s[a]={type:"secret_ref",secretId:n.secretId,version:n.version})}return s}r(zte,"rowsToAccessMap");function qte(e){return JSON.stringify(Object.keys(e).sort().map(s=>{const n=e[s];return[s,n.secretId,n.version??"latest"]}))}r(qte,"normalizeAccessMapKey");function Ute({mode:e}){return e==="env"?(0,t.jsxs)(ct,{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)(Bve,{className:"size-3"})," Env var"]}):(0,t.jsxs)(ct,{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)(_M,{className:"size-3"})," API access"]})}r(Ute,"DeliveryBadge");function Yrt({config:e,secrets:s,onChange:n,onCreateSecret:a,disabled:i,proposals:o,onApproveProposal:l,onRejectProposal:c}){const d=(0,m.useMemo)(()=>(o??[]).filter(B=>B.kind==="binding"),[o]),u=(0,m.useMemo)(()=>Hrt(e),[e]),h=(0,m.useMemo)(()=>Grt(e),[e]),p=(0,m.useMemo)(()=>Qrt(u,h),[u,h]),f=(0,m.useMemo)(()=>zte(q$(h)),[h]),x=(0,m.useMemo)(()=>qte(f),[f]),[b,v]=(0,m.useState)(()=>q$(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(q$(h)))},[x,h]);const C=r(B=>s.find(E=>E.id===B)?.name??`${B.slice(0,8)}…`,"secretName");function I(B){v(B);const E=zte(B);k.current=qte(E),n(E)}r(I,"emit");function R(B,E){I(b.map(z=>z.id===B?{...z,...E}:z))}r(R,"patchRow");function T(B){I(b.filter(E=>E.id!==B))}r(T,"removeRow");function A(){v(B=>[...B,{id:ASe(),alias:"",secretId:"",version:"latest"}])}r(A,"addRow");const D=(0,m.useMemo)(()=>{const B=new Map;for(const E of b){const z=E.alias.trim();z&&B.set(z,(B.get(z)??0)+1)}return B},[b]),M=p.length>0;return(0,t.jsxs)("div",{className:"space-y-3",children:[M?(0,t.jsx)("div",{className:"space-y-1.5",children:p.map(B=>(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(B.secretId)}),B.envKeys.length>0?(0,t.jsx)(Ute,{mode:"env"}):null,B.apiAliases.length>0?(0,t.jsx)(Ute,{mode:"api"}):null,(0,t.jsx)("span",{className:"min-w-0 truncate font-mono text-(length:--text-micro) text-muted-foreground",children:[...B.envKeys.map(E=>`${Lrt}${E}`),...B.apiAliases.map(E=>`${mA}${E}`)].join(" · ")})]},B.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(B=>{const E=MW(B),z=o4(B);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)(EW,{configPath:B.configPath}),(0,t.jsx)("code",{className:"font-mono",children:z||B.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:E.name}),E.pending?(0,t.jsx)(PW,{}):null]}),(0,t.jsxs)("p",{className:"flex flex-wrap items-center gap-1 text-muted-foreground",children:[(0,t.jsxs)("span",{children:["proposed by ",B.proposedBy.name]}),(0,t.jsx)("span",{"aria-hidden":"true",children:"·"}),(0,t.jsxs)("span",{className:"truncate italic",children:["“",B.justification,"”"]})]})]}),(0,t.jsx)(CSe,{proposal:B,onApprove:l,onReject:c,disabled:i,size:"xs"})]},B.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(B=>{const E=B.alias.trim(),z=!!E&&!t6.test(E),$=!!E&&(D.get(E)??0)>1,q=s.find(U=>U.id===B.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)(ht,{value:B.alias,onChange:r(U=>R(B.id,{alias:U.target.value}),"onChange"),onBlur:r(U=>{const O=U.target.value.trim();if(O&&!t6.test(O)){const K=P1(O);K&&K!==O&&R(B.id,{alias:K})}},"onBlur"),placeholder:"ALIAS","aria-label":"Access alias",disabled:i,className:W("h-9 font-mono text-sm",(z||$)&&"border-destructive text-destructive")})}),(0,t.jsxs)("div",{className:"flex min-w-0 items-start gap-1.5",children:[(0,t.jsxs)(gr,{open:j?.rowId===B.id,onOpenChange:r(U=>{!U&&j?.rowId===B.id&&N(null)},"onOpenChange"),children:[(0,t.jsx)(Sz,{asChild:!0,children:(0,t.jsx)("div",{ref:r(U=>{U?w.current.set(B.id,U):w.current.delete(B.id)},"ref"),className:"min-w-0 flex-1",children:(0,t.jsx)(TW,{secretId:B.secretId,secrets:s,onSelect:r(U=>R(B.id,{secretId:U,version:"latest",alias:!B.alias.trim()&&U?P1(C(U)):B.alias}),"onSelect"),onCreateNew:a?U=>{window.setTimeout(()=>{N({rowId:B.id,name:R5(U)||U.trim()})},0)}:void 0,disabled:i,triggerClassName:"h-9 min-h-9"})})}),(0,t.jsx)(dr,{align:"start",className:"w-auto p-3",onInteractOutside:r(U=>{const O=U.detail.originalEvent.target;O&&w.current.get(B.id)?.contains(O)&&U.preventDefault()},"onInteractOutside"),children:j?.rowId===B.id&&a?(0,t.jsx)(bSe,{initialName:j.name,initialValue:"",existingSecretNames:s.map(U=>U.name),onCancel:r(()=>N(null),"onCancel"),onSubmit:r(async(U,O)=>{const K=await a(U,O);R(B.id,{secretId:K.id,version:"latest",alias:B.alias.trim()||P1(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:B.version===void 0?"latest":String(B.version),onChange:r(U=>{const O=U.target.value;R(B.id,{version:O==="latest"?"latest":Number.parseInt(O,10)})},"onChange"),disabled:i||!q,"aria-label":"Version",children:[(0,t.jsx)("option",{value:"latest",children:"latest"}),q?Array.from({length:Math.max(0,q.latestVersion)},(U,O)=>{const K=q.latestVersion-O;return K<=0?null:(0,t.jsxs)("option",{value:K,children:["v",K]},K)}):null]})]}),(0,t.jsx)("button",{type:"button",onClick:r(()=>T(B.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)(la,{className:"size-3.5"})})]}),z?(0,t.jsx)("p",{className:"pl-0.5 text-(length:--text-micro) text-destructive",children:"Invalid alias — use letters, digits and _"}):$?(0,t.jsx)("p",{className:"pl-0.5 text-(length:--text-micro) text-destructive",children:"Duplicate alias"}):null]},B.id)})}):null,(0,t.jsxs)("button",{type:"button",onClick:A,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)(yn,{className:"size-3.5"}),"Add API access"]})]}),(0,t.jsxs)("p",{className:"text-(length:--text-micro) text-muted-foreground/70",children:[$rt("api")," The agent reads them by alias through ",(0,t.jsx)("code",{children:"GET /agents/me/secrets"}),"."]})]})}r(Yrt,"AgentSecretAccessEditor");function Jrt(e){if(typeof e!="string")return null;const s=e.trim();return s.length>0?s:null}r(Jrt,"asNonEmptyString$3");function Xrt(e){return Jrt(e)!==null}r(Xrt,"hasLegacyWorkingDirectory");function Zrt(e){return e.isCreate?!1:Xrt(e.adapterConfig?.cwd)}r(Zrt,"shouldShowLegacyWorkingDirectoryField");var TSe=new Set;function eat(e){return TSe.has(e)}r(eat,"isAdapterTypeHidden");function tat(e){TSe=new Set(e)}r(tat,"setDisabledAdapterTypes");function sat(e){return!Ch(e).hideFromVisualSelection}r(sat,"isVisualAdapterChoice");function RSe(e,s=IW()){const n=e??Ff;return s.map(a=>({value:a.type,label:n(a.type),comingSoon:!!Ch(a.type).comingSoon,hidden:eat(a.type),experimental:!!Ch(a.type).experimental}))}r(RSe,"listAdapterOptions");function ESe(e={}){const s=e.enabled??!0,{data:n}=Z({queryKey:P.adapters.all,queryFn:r(()=>uh.list(),"queryFn"),enabled:s,staleTime:3e5});return n&&srt(n.filter(a=>a.source==="external").map(a=>({type:a.type,label:a.label,disabled:a.disabled,overrideDisabled:a.overridePaused}))),(0,m.useEffect)(()=>{n&&tat(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(ESe,"useDisabledAdaptersSync");function nat(e={}){const s=e.enabled??!0,{data:n}=Z({queryKey:P.adapters.all,queryFn:r(()=>uh.list(),"queryFn"),enabled:s,staleTime:3e5});return n!==void 0}r(nat,"useAdapterRegistryLoaded");function E5(e){return Object.fromEntries(Object.entries(e).filter(([,s])=>s!==void 0))}r(E5,"omitUndefinedEntries");function W2(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=E5(s.adapterType!==void 0?{...Object.fromEntries(GLe.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=E5({...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(W2,"buildAgentUpdatePatch");var rat="kubernetes";function aat(e){return e.driver!=="sandbox"?!1:e.config?.provider===rat}r(aat,"isKubernetesSandboxEnvironment");function DW(e,s){return e!=="kubernetes"?{forced:!1,kubernetesEnvironment:null}:{forced:!0,kubernetesEnvironment:s.find(n=>aat(n))??null}}r(DW,"resolveForcedKubernetesEnvironment");var U$={identity:{},adapterConfig:{},heartbeat:{},debug:{},runtime:{}},sC={};function iat(e){return e==="claude_local"||e==="codex_local"||e==="paperclip_runner"||e==="opencode_local"}r(iat,"supportsAdapterModelRefresh");function oat(e,s){return CNe(e,s).model}r(oat,"resolvePaperclipRunnerTransitionModel");function Kte(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(Kte,"isOverlayDirty");function s6(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)=>s6(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&&s6(o,a[i]))}return!1}r(s6,"overlayValuesEqual");function lat(e,s){const n=r((a,i)=>Object.fromEntries(Object.entries(a).filter(([o,l])=>!(o in i)||!s6(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(lat,"subtractPersistedOverlay");var Zm="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 cat(e){return e.split(",").map(s=>s.trim()).filter(Boolean)}r(cat,"parseCommaArgs");function dat(e){return Array.isArray(e)?e.filter(s=>typeof s=="string").join(", "):typeof e=="string"?e:""}r(dat,"formatArgList");var uat=[{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"}],mat=[{id:"",label:"Auto"},{id:"plan",label:"Plan"},{id:"ask",label:"Ask"}],hat=[{id:"",label:"Auto"},{id:"low",label:"Low"},{id:"medium",label:"Medium"},{id:"high",label:"High"}],pat=[{id:"",label:"Auto"},{id:"low",label:"Low"},{id:"high",label:"High"},{id:"max",label:"Max"}],fat=2,Wte=10,xat=1,PSe=300;function vE(e,s,n){return Math.max(s,Math.min(n,Math.floor(e)))}r(vE,"clampInteger");function gat(e){return vE(e,0,PSe)*1e3}r(gat,"clampDelayMsFromSeconds");function bat({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(bat,"ConfigSections");function MSe(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=Dt(),b=(0,m.useRef)(null),v=ESe(),{data:j=[]}=Z({queryKey:f?P.secrets.list(f):["secrets","none"],queryFn:r(()=>vr.list(f),"queryFn"),enabled:!!f}),{data:N=[]}=Z({queryKey:f?P.secrets.userDefinitions(f):["user-secret-definitions","none"],queryFn:r(()=>vr.listUserSecretDefinitions(f),"queryFn"),enabled:!!f,retry:!1}),w=a?null:e.agent.id,{data:k=[]}=Z({queryKey:f?P.secrets.proposals(f,"pending"):["secret-proposals","none"],queryFn:r(()=>vr.listProposals(f,"pending"),"queryFn"),enabled:!!f&&!a,retry:!1}),S=(0,m.useMemo)(()=>k.filter(Ze=>Ze.kind==="binding"&&Ze.target?.id===w),[k,w]),C=SSe(f,[]),{data:I}=Z({queryKey:P.instance.experimentalSettings,queryFn:r(()=>Nr.getExperimental(),"queryFn"),retry:!1}),R=(0,m.useMemo)(()=>{const Ze=new Set(v);return I?.enableNativeRunner!==!0&&Ze.add("paperclip_runner"),Ze},[v,I?.enableNativeRunner]),T=I?.enableEnvironments===!0,A=I?.enableManagedSandboxOnly===!0,D=I===void 0||A,{data:M}=Z({queryKey:P.instance.generalSettings,queryFn:r(()=>Nr.getGeneral(),"queryFn"),retry:!1}),{data:B}=Z({queryKey:P.instance.settings,queryFn:r(()=>Nr.get(),"queryFn"),retry:!1}),{data:E=[]}=Z({queryKey:f?P.environments.list(f):["environments","none"],queryFn:r(()=>Pi.list(f),"queryFn"),enabled:!!f&&(T||M?.executionMode==="kubernetes")}),{forced:z,kubernetesEnvironment:$}=(0,m.useMemo)(()=>DW(M?.executionMode,E),[M?.executionMode,E]),q=je({mutationFn:r(Ze=>{if(!f)throw new Error("Select an organization to create secrets");return vr.create(f,Ze)},"mutationFn"),onSuccess:r(()=>{f&&x.invalidateQueries({queryKey:P.secrets.list(f)})},"onSuccess")}),U=je({mutationFn:r(async({file:Ze,namespace:At})=>{if(!f)throw new Error("Select an organization to upload images");return bb.uploadImage(f,Ze,At)},"mutationFn")}),[O,K]=(0,m.useState)(U$),[H,ee]=(0,m.useState)(!1),[se,ne]=(0,m.useState)(0),fe=(0,m.useRef)(null),X=(0,m.useRef)(null),re=(0,m.useRef)(!1);(0,m.useEffect)(()=>{if(!a){if(fe.current!==null&&e.agent!==fe.current&&!re.current){const Ze=X.current;X.current=null,K(At=>Ze?lat(At,Ze):{...U$})}fe.current=e.agent}},[a,a?void 0:e.agent]);const oe=!a&&(Kte(O)||H);function G(Ze,At,fs){const Ks=O[Ze];return At in Ks?Ks[At]:fs}r(G,"eff");function Y(Ze,At,fs){K(Ks=>({...Ks,[Ze]:{...Ks[Ze],[At]:fs}}))}r(Y,"mark");function Q(){return b.current?.flushPendingDraft()??null}r(Q,"flushEnvironmentDraft");const te=(0,m.useCallback)(Ze=>{a||K(At=>{const fs={...e.agent.adapterConfig??{},...At.adapterConfig},Ks={...At.adapterConfig};for(const[Ln,Cr]of Object.entries(Ze))Ks[`${mA}${Ln}`]=Cr;for(const Ln of Object.keys(fs))Ln.startsWith("access.")&&(Ln.slice(7)in Ze||(Ks[Ln]=void 0));return{...At,adapterConfig:Ks}})},[a,a?void 0:e.agent]),ae=(0,m.useCallback)(()=>{K({...U$}),ee(!1),ne(Ze=>Ze+1)},[]),le=(0,m.useCallback)(async()=>{if(a)return;const Ze=Q(),At=Ze?{...O,adapterConfig:{...O.adapterConfig,env:Ze}}:O;Kte(At)&&await e.onSave(W2(e.agent,At))},[a,oe,O,e]);(0,m.useEffect)(()=>{a||(e.onDirtyChange?.(oe),e.onSaveActionChange?.(le),e.onCancelActionChange?.(ae))},[a,oe,e.onDirtyChange,e.onSaveActionChange,e.onCancelActionChange,le,ae]),(0,m.useEffect)(()=>{if(!a)return()=>{e.onSaveActionChange?.(null),e.onCancelActionChange?.(null),e.onDirtyChange?.(!1)}},[a,e.onDirtyChange,e.onSaveActionChange,e.onCancelActionChange]);const he=a?{}:e.agent.adapterConfig??{},ce=a?{}:e.agent.runtimeConfig??{},ge=a?{}:ce.heartbeat??{},me=a?{}:ce.debug??{},ie=a?e.values.adapterType:O.adapterType??e.agent.adapterType,ue=Wy(),ke=ue(ie),be=ke.supportsInstructionsBundle||ke.supportsSkills||ke.supportsLocalAgentJwt,Ie=be&&!D&&Zrt({isCreate:a,adapterConfig:he}),Ue=(0,m.useMemo)(()=>aS(ie),[ie]),at=(0,m.useMemo)(()=>new Set(cze(ie)),[ie]),dt=a?e.values:null,de=a?Ze=>e.onChange(Ze):null;a&&dt.claudeStoredSessionId;const Be=r(()=>{f&&x.invalidateQueries({queryKey:P.secrets.userDefinitions(f)})},"invalidateUserSecretDefinitions"),pt=r(Ze=>{if(!a||!de)return;const At=dt.envBindings??{};de({envBindings:{...At,...Vw()},claudeStoredSessionId:Ze}),Be()},"handleClaudeLoginStored"),vt=r(async()=>{if(a)return;const Ze={...Q()??G("adapterConfig","env",he.env??sC),...Vw()},At={...O,adapterConfig:{...O.adapterConfig,env:Ze}};K(At),await e.onSave({...W2(e.agent,At),applyStoredClaudeLogin:!0}),Be()},"handleClaudeLoginStoredEdit"),Le=r(async Ze=>{if(a||!Ze.companyIdentityDiffers)return;const At={...Q()??G("adapterConfig","env",he.env??sC),CODEX_HOME:{type:"secret_ref",secretId:Ze.secretId,version:"latest"}},fs={...O,adapterConfig:{...O.adapterConfig,env:At}};K(fs),X.current=fs,re.current=!0;try{await e.onSave(W2(e.agent,fs))}catch(Ks){throw X.current=null,Ks}finally{re.current=!1}Be()},"handleCodexAccountBindingEdit"),Qe=r(()=>{if(!a||!de)return;const Ze=dt.envBindings??{};de({envBindings:{...Ze,...Vw()},claudeApplyStoredLogin:!0}),Be()},"handleApplyStoredClaudeLogin"),ut=r(async()=>{if(a)return;const Ze={...Q()??G("adapterConfig","env",he.env??sC),...Vw()},At={...O,adapterConfig:{...O.adapterConfig,env:Ze}};K(At),await e.onSave({...W2(e.agent,At),applyStoredClaudeLogin:!0}),Be()},"handleApplyStoredClaudeLoginEdit"),Ye=a?dt.defaultEnvironmentId??"":G("identity","defaultEnvironmentId",e.agent.defaultEnvironmentId??""),it=(0,m.useMemo)(()=>Ye?(E.find(Ze=>Ze.id===Ye)??null)?.driver==="local"?"":Ye:"",[E,Ye]),kt=(0,m.useMemo)(()=>E.find(Ze=>Ze.id===it)??null,[it,E]),tt=(0,m.useMemo)(()=>{const Ze=B?.defaultEnvironmentId??null;return Ze?(E.find(At=>At.id===Ze)??null)?.driver==="local"?"":Ze:""},[E,B?.defaultEnvironmentId]),Pe=(0,m.useMemo)(()=>E.find(Ze=>Ze.id===tt)??null,[E,tt]),Ce=(0,m.useMemo)(()=>{try{return iN({agentDefaultEnvironmentId:Ye||null,instanceDefaultEnvironmentId:B?.defaultEnvironmentId??null,localDefaultEnvironmentId:lN(E),managedSandboxOnly:I?.enableManagedSandboxOnly===!0,managedSandboxEnvironmentId:oN(E),visibleEnvironmentIds:E.map(Ze=>Ze.id)})}catch{return null}},[Ye,B?.defaultEnvironmentId,E,I?.enableManagedSandboxOnly]),He=(0,m.useMemo)(()=>E.find(Ze=>Ze.id===Ce)??null,[E,Ce]),{data:Je}=Z({queryKey:f?P.environments.capabilities(f):["environment-capabilities","none"],queryFn:r(()=>Pi.capabilities(f),"queryFn"),enabled:!!f&&ke.login!=null});(0,m.useEffect)(()=>{!a||!de||!z||!$||it!==$.id&&de({defaultEnvironmentId:$.id})},[a,de,z,$,it]);const lt=(0,m.useMemo)(()=>E.filter(Ze=>{if(!at.has(Ze.driver)||Ze.driver==="local")return!1;if(Ze.driver!=="sandbox")return!0;const At=typeof Ze.config?.provider=="string"?Ze.config.provider:null;return At!==null&&At!=="fake"}),[E,at]),Ee=(0,m.useMemo)(()=>!kt||lt.some(Ze=>Ze.id===kt.id)?lt:[...lt,kt],[kt,lt]),Xe=T&&(z||it.length>0||lt.length>=1),Ae=Pe?Qv(Pe):A?"Paperclip Computer":"Local",De=ie==="paperclip_runner"?String(a?e.values.adapterSchemaValues?.provider??"codex":G("adapterConfig","provider",he.provider==="acpx"&&he.acpxAgent==="codex"?"codex":he.provider??"codex")):void 0,_t=ie==="opencode_local"&&zpe.safeParse(O.runtime.runtimeConfig?.aiConnection??ce.aiConnection).data?.provider==="openrouter"?"openrouter":De,ye=f?P.agents.adapterModels(f,ie,it||null,_t):["agents","none","adapter-models",ie],{data:gt,error:We}=Z({queryKey:ye,queryFn:r(()=>$t.adapterModels(f,ie,{environmentId:it||null,provider:_t}),"queryFn"),enabled:!!f}),[Ot,zt]=(0,m.useState)(null),[Cs,ze]=(0,m.useState)(!1),ft=gt??n??[],Ut="command",{data:Ns,refetch:Is}=Z({queryKey:f?P.agents.detectModel(f,ie):["agents","none","detect-model",ie],queryFn:r(()=>{if(!f)throw new Error("Select an organization to detect the model");return $t.detectModel(f,ie)},"queryFn"),enabled:!!(f&&be&&ie!=="opencode_local"&&ie!=="paperclip_runner")}),St=Ns?.model??null;Ns?.candidates;const{data:ds=[]}=Z({queryKey:f?P.agents.list(f):["agents","none","list"],queryFn:r(()=>$t.list(f),"queryFn"),enabled:!!(!a&&f)}),$e={mode:s,isCreate:a,adapterType:ie,values:a?e.values:null,set:a?Ze=>e.onChange(Ze):null,config:he,eff:G,mark:Y,models:ft,hideInstructionsFile:h||D,managedSandboxOnly:D},[xe,Qt]=(0,m.useState)(!1),[Mt,rs]=(0,m.useState)(!1),ws=ONe(ie),Bs=r(Ze=>(0,t.jsxs)(t.Fragment,{children:[ie==="claude_local"&&(0,t.jsx)(Fet,{...$e,section:Ze}),(0,t.jsx)(Ue.ConfigFields,{...$e,section:Ze,hideModel:be})]}),"renderAdapterFields"),[er,Fe]=(0,m.useState)(!1),[st,xt]=(0,m.useState)(!1);function Oe(Ze){if(a){const fs=Ue.buildAdapterConfig(dt);return Ze&&Object.assign(fs,Ze),E5(fs)}const At={...he,...O.adapterConfig};return Ze&&Object.assign(At,Ze),E5(At)}r(Oe,"buildAdapterConfigForTest");const Bt=je({mutationFn:r(async()=>{if(!f)throw new Error("Select an organization to test adapter environment");const Ze=Q(),At=Ze?{env:Ze}:void 0;let fs=B,Ks=E,Ln=I?.enableManagedSandboxOnly===!0;if(!Ye)try{const[_r,yr,sr]=await Promise.all([x.ensureQueryData({queryKey:P.instance.settings,queryFn:r(()=>Nr.get(),"queryFn")}),x.ensureQueryData({queryKey:P.environments.list(f),queryFn:r(()=>Pi.list(f),"queryFn")}),x.ensureQueryData({queryKey:P.instance.experimentalSettings,queryFn:r(()=>Nr.getExperimental(),"queryFn")})]);fs=_r,Ks=yr,Ln=sr?.enableManagedSandboxOnly===!0}catch{throw new Error("Could not load environment settings to determine which environment to test in. Retry the test.")}const Cr=iN({agentDefaultEnvironmentId:Ye||null,instanceDefaultEnvironmentId:fs?.defaultEnvironmentId??null,localDefaultEnvironmentId:lN(Ks),managedSandboxOnly:Ln,managedSandboxEnvironmentId:oN(Ks),visibleEnvironmentIds:Ks.map(_r=>_r.id)}),Vr=Oe(At),Pr=a?void 0:e.agent.id,Ar=a?void 0:yJ.safeParse(O.runtime.runtimeConfig?.aiConnection??e.agent.runtimeConfig.aiConnection).data;if(e.compactTestFeedback){const _r=ie==="paperclip_runner"?Vr.provider==="codex"?"codex_local":Vr.provider==="acpx"&&Vr.acpxAgent==="grok"?"grok_local":Vr.provider==="acpx"&&Vr.acpxAgent==="claude"?"claude_local":ie:ie;return jNe({companyId:f,adapterType:ie,providerAdapter:_r,adapterConfig:Vr,agentId:Pr,aiConnection:Ar,environmentId:Cr})}return $t.testEnvironment(f,ie,{adapterConfig:Vr,agentId:Pr,aiConnection:Ar,environmentId:Cr})},"mutationFn")}),[wt,Xt]=(0,m.useState)(!1),[Yt,hs]=(0,m.useState)(null),Ts="Test",as=!a&&!!e.isSaving,Zn=wt||as||!f,en=(0,m.useRef)(Bt.reset);en.current=Bt.reset;const nr=(0,m.useRef)(()=>{});nr.current=()=>{if(!a||!de)return;const Ze=dt.envBindings??{},At=dt.claudeStoredSessionId!=null||dt.claudeApplyStoredLogin===!0,fs=Mte in Ze;if(!At&&!fs)return;const Ks={...Ze};delete Ks[Mte],de({envBindings:Ks,claudeStoredSessionId:null,claudeApplyStoredLogin:!1})},(0,m.useEffect)(()=>{en.current(),hs(null),nr.current()},[ie,Ce]);const tn=ke.login!=null,xn=Bt.data,Ht=xn!=null&&ue(xn.adapterType).login!=null,qs=xn&&Ht?xn.checks.find(Ze=>Ze.code==="adapter_auth_missing")??null:null,Vs=typeof He?.config?.provider=="string"?He.config.provider:null,Lt=Vs!=null&&Je?.sandboxProviders?.[Vs]?.supportsLoginPty===!0,is=ke.login!=null,Ms=(a||!(O.runtime.runtimeConfig?.aiConnection??ce.aiConnection))&&tn&&He?.driver==="sandbox"&&!!Ce&&!!f&&!!qs&&(!is||Lt),bs=(0,m.useCallback)(async()=>{if(!f)throw new Error("Select an organization to test adapter environment");Xt(!0),hs(null),Bt.reset();try{return await Bt.mutateAsync()}catch(Ze){throw hs(Ze instanceof Error?Ze.message:"Environment test failed"),Ze}finally{Xt(!1)}},[f,Bt]),gn=(0,m.useRef)(()=>{});(0,m.useEffect)(()=>{gn.current=()=>{Zn||bs().catch(()=>{})}},[bs,Zn]);const Pn=(0,m.useCallback)(()=>{gn.current()},[]);(0,m.useEffect)(()=>{if(!(!l||!e.onTestActionChange))return e.onTestActionChange(Pn),()=>{e.onTestActionChange?.(null)}},[l,e.onTestActionChange,Pn]),(0,m.useEffect)(()=>{if(!(!l||!e.onTestActionStateChange))return e.onTestActionStateChange({disabled:Zn,pending:wt}),()=>{e.onTestActionStateChange?.({disabled:!0,pending:!1})}},[l,e.onTestActionStateChange,Zn,wt]),(0,m.useEffect)(()=>{if(e.onTestFeedbackChange)return e.onTestFeedbackChange({errorMessage:Yt??(Bt.error instanceof Error?Bt.error.message:Bt.error?"Environment test failed":null),result:Bt.data??null,login:Ms&&f&&Ce?{companyId:f,adapterType:ie,environmentId:Ce}:null}),()=>{e.onTestFeedbackChange?.({errorMessage:null,result:null,login:null})}},[e.onTestFeedbackChange,Yt,Bt.data,Bt.error,Ms,f,ie,Ce]);const $r=a?dt.model??"":G("adapterConfig","model",String(he.model??"")),mt=typeof $r=="string"?$r:"";async function vs(){if(f){ze(!0),zt(null);try{const Ze=await $t.adapterModels(f,ie,{refresh:!0,environmentId:it||null,provider:_t});x.setQueryData(ye,Ze)}catch(Ze){zt(Ze instanceof Error?Ze.message:"Failed to refresh adapter models.")}finally{ze(!1)}}}r(vs,"handleRefreshModels");const Fs=ie==="codex_local"?"modelReasoningEffort":ie==="cursor"?"mode":ie==="opencode_local"?"variant":ie==="grok_local"?"reasoningEffort":ie==="pi_local"?"thinking":"effort",Hs=ie==="codex_local"?jW(mt,"Auto").map(Ze=>({id:Ze.value,label:Ze.label})):ie==="cursor"?mat:ie==="opencode_local"?uat:ie==="kimi_local"?pat:ie==="pi_local"?[{id:"",label:"Auto"},...["off","minimal","low","medium","high","xhigh"].map(Ze=>({id:Ze,label:Ze}))]:ie==="claude_local"||ie==="grok_local"?[{id:"",label:"Auto"},...S5(ie,mt).map(Ze=>({id:Ze,label:Ze==="xhigh"?"X-High":Ze[0].toUpperCase()+Ze.slice(1)}))]:hat,zs=a?dt.thinkingEffort:ie==="codex_local"?G("adapterConfig","modelReasoningEffort",String(he.modelReasoningEffort??he.reasoningEffort??"")):ie==="cursor"?G("adapterConfig","mode",String(he.mode??"")):ie==="opencode_local"?G("adapterConfig","variant",String(he.variant??"")):G("adapterConfig",Fs,String(he[Fs]??"")),Us=ie!=="gemini_local"&&ie!=="cursor_cloud"&&ie!=="paperclip_runner",ur=ie==="codex_local"?a?!!dt.search:G("adapterConfig","search",!!he.search):!1,Dn=(0,m.useMemo)(()=>{if(a)return{heartbeat:{enabled:dt.heartbeatEnabled,intervalSec:dt.intervalSec}};const Ze={...ce.heartbeat&&typeof ce.heartbeat=="object"?ce.heartbeat:{},...O.heartbeat};return{...ce,heartbeat:Ze}},[a,O.heartbeat,ce,dt]),Er=_J(Dn.heartbeat),Jn=_J(Er.maxTurnContinuation),tr=g$e(Jn.enabled,!0),pn=vE(LJ(Jn.maxAttempts,fat),0,Wte),yt=vE(LJ(Jn.delayMs,xat*1e3)/1e3,0,PSe);function Ps(Ze){Y("heartbeat","maxTurnContinuation",{...Jn,...Ze})}r(Ps,"updateMaxTurnContinuation");const Zs=(0,t.jsx)(jy,{ref:b,onDirtyChange:ee,hideDraftActions:!a&&e.hideInlineSave,value:a?dt.envBindings??sC:G("adapterConfig","env",he.env??sC),secrets:j,userSecretDefinitions:N,onCreateSecret:r(async(Ze,At)=>await q.mutateAsync({name:Ze,value:At}),"onCreateSecret"),onChange:r(Ze=>a?de({envBindings:Ze??{},envVars:""}):Y("adapterConfig","env",Ze),"onChange")},se);return!a&&e.content==="secrets"?(0,t.jsxs)("div",{className:W("relative",i&&"space-y-6"),children:[oe&&!e.hideInlineSave&&(0,t.jsx)("div",{className:"sticky top-0 z-10 flex items-center justify-end border-b border-primary/20 bg-background/90 px-4 py-2 backdrop-blur-sm",children:(0,t.jsxs)("div",{className:"flex items-center gap-3",children:[(0,t.jsx)("span",{className:"text-xs text-muted-foreground",children:"Unsaved changes"}),(0,t.jsx)(L,{size:"sm",onClick:le,disabled:e.isSaving,children:e.isSaving?"Saving...":"Save"})]})}),e.environmentVariablesPlacement==="secrets"&&(0,t.jsxs)("div",{"data-config-section":"environment-variables",className:W(!i&&"border-b border-border"),children:[i?(0,t.jsx)("h3",{className:"mb-3 text-sm font-medium",children:"Environment variables"}):(0,t.jsx)("div",{className:"px-4 py-2 text-xs font-medium text-muted-foreground",children:"Environment variables"}),(0,t.jsx)("div",{className:W(i?"rounded-lg border border-border p-4":"px-4 pb-3"),children:Zs})]}),(0,t.jsxs)("div",{"data-config-section":"secrets",className:W(!i&&"border-b border-border"),children:[i?(0,t.jsx)("h3",{className:"mb-3 text-sm font-medium",children:"Secret access"}):(0,t.jsx)("div",{className:"px-4 py-2 text-xs font-medium text-muted-foreground",children:"Secret access"}),(0,t.jsxs)("div",{className:W(i?"space-y-3 rounded-lg border border-border p-4":"space-y-3 px-4 pb-3"),children:[(0,t.jsx)("p",{className:"text-xs text-muted-foreground",children:Ni.secretAccess}),(0,t.jsx)(Yrt,{config:{...he,...O.adapterConfig},secrets:j,onChange:te,onCreateSecret:r((Ze,At)=>q.mutateAsync({name:Ze,value:At}),"onCreateSecret"),proposals:S,onApproveProposal:C.requestApprove,onRejectProposal:C.requestReject}),C.dialogs]})]})]}):(0,t.jsxs)(bat,{order:e.sectionOrder,className:W("relative",i&&"space-y-6"),children:[oe&&!e.hideInlineSave&&(0,t.jsx)("div",{className:"sticky top-0 z-10 flex items-center justify-end px-4 py-2 bg-background/90 backdrop-blur-sm border-b border-primary/20",children:(0,t.jsxs)("div",{className:"flex items-center gap-3",children:[(0,t.jsx)("span",{className:"text-xs text-muted-foreground",children:"Unsaved changes"}),(0,t.jsx)(L,{size:"sm",onClick:le,disabled:!a&&e.isSaving,children:!a&&e.isSaving?"Saving...":"Save"})]})}),!a&&(0,t.jsxs)("div",{"data-config-section":"identity",className:W(!i&&"border-b border-border"),children:[i?(0,t.jsx)("h3",{className:"text-sm font-medium mb-3",children:e.sectionTitles?.identity??"Identity"}):(0,t.jsx)("div",{className:"px-4 py-2 text-xs font-medium text-muted-foreground",children:"Identity"}),(0,t.jsxs)("div",{className:W(i?"border border-border rounded-lg p-4 space-y-3":"px-4 pb-3 space-y-3"),children:[(0,t.jsx)(Ss,{label:"Name",hint:Ni.name,children:(0,t.jsx)(Ka,{value:G("identity","name",e.agent.name),onCommit:r(Ze=>Y("identity","name",Ze),"onCommit"),immediate:!0,className:Zm,placeholder:"Agent name"})}),(0,t.jsx)(Ss,{label:"Title",hint:Ni.title,children:(0,t.jsx)(Ka,{value:G("identity","title",e.agent.title??""),onCommit:r(Ze=>Y("identity","title",Ze||null),"onCommit"),immediate:!0,className:Zm,placeholder:"e.g. VP of Engineering"})}),(0,t.jsx)(Ss,{label:"Reports to",hint:Ni.reportsTo,children:(0,t.jsx)(lrt,{agents:ds,value:G("identity","reportsTo",e.agent.reportsTo??null),onChange:r(Ze=>Y("identity","reportsTo",Ze),"onChange"),excludeAgentIds:[e.agent.id],chooseLabel:"Choose manager…"})}),be&&!e.hidePromptTemplate&&(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)(Ss,{label:"Prompt Template",hint:Ni.promptTemplate,children:(0,t.jsx)(fd,{value:G("adapterConfig","promptTemplate",String(he.promptTemplate??"")),onChange:r(Ze=>Y("adapterConfig","promptTemplate",Ze??""),"onChange"),placeholder:"You are agent {{ agent.name }}. Your role is {{ agent.role }}...",contentClassName:"min-h-(--sz-88px) text-sm font-mono",imageUploadHandler:r(async Ze=>{const At=`agents/${e.agent.id}/prompt-template`;return(await U.mutateAsync({file:Ze,namespace:At})).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."})]})]})]}),z?(0,t.jsxs)("div",{"data-config-section":"environment",className:W(!i&&(a?"border-t border-border":"border-b border-border")),children:[i?(0,t.jsx)("h3",{className:"text-sm font-medium mb-3",children:"Environment"}):(0,t.jsx)("div",{className:"px-4 py-2 text-xs font-medium text-muted-foreground",children:"Environment"}),(0,t.jsx)("div",{className:W(i?"border border-border rounded-lg p-4 space-y-3":"px-4 pb-3 space-y-3"),children:(0,t.jsx)(Ss,{label:"Default environment",hint:"This instance runs all agents in the Kubernetes sandbox. Local execution is disabled.",children:$?(0,t.jsxs)("div",{className:W(Zm,"flex items-center text-muted-foreground"),children:[$.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."})})})]}):Xe?(0,t.jsxs)("div",{"data-config-section":"environment",className:W(!i&&(a?"border-t border-border":"border-b border-border")),children:[i?(0,t.jsx)("h3",{className:"text-sm font-medium mb-3",children:"Environment"}):(0,t.jsx)("div",{className:"px-4 py-2 text-xs font-medium text-muted-foreground",children:"Environment"}),(0,t.jsx)("div",{className:W(i?"border border-border rounded-lg p-4 space-y-3":"px-4 pb-3 space-y-3"),children:(0,t.jsx)(Ss,{label:"Environment override",children:(0,t.jsx)("div",{className:"space-y-2",children:(0,t.jsxs)("select",{className:Zm,value:it,onChange:r(Ze=>{const At=Ze.target.value;if(a){de({defaultEnvironmentId:At});return}Y("identity","defaultEnvironmentId",At||null)},"onChange"),children:[(0,t.jsxs)("option",{value:"",children:["Default: ",Ae]}),Ee.map(Ze=>(0,t.jsx)("option",{value:Ze.id,children:Qv(Ze)},Ze.id))]})})})})]}):null,(0,t.jsxs)("div",{"data-config-section":"adapter",className:W(!i&&(a?"border-t border-border":"border-b border-border")),children:[(0,t.jsxs)("div",{className:W(i?"flex items-center justify-between mb-3":"px-4 py-2 flex items-center justify-between gap-2"),children:[i?(0,t.jsx)("h3",{className:"text-sm font-medium",children:e.sectionTitles?.adapter??"Adapter"}):(0,t.jsx)("span",{className:"text-xs font-medium text-muted-foreground",children:"Adapter"}),c&&(0,t.jsx)(L,{type:"button",variant:"outline",size:"sm",className:"h-7 px-2.5 text-xs",onClick:Pn,disabled:Zn,children:wt?`${Ts}...`:Ts})]}),(0,t.jsxs)("div",{className:W(i?"border border-border rounded-lg p-4 space-y-3":"px-4 pb-3 space-y-3"),children:[o&&(0,t.jsx)(Ss,{label:"Adapter type",hint:Ni.adapterType,children:(0,t.jsx)(LSe,{value:ie,disabledTypes:R,onChange:r(Ze=>{if(a){const{adapterType:At,...fs}=nb,Ks={...fs,adapterType:Ze};Ze==="codex_local"?Ks.dangerouslyBypassSandbox=!0:Ze==="gemini_local"?Ks.model="auto":Ze==="kimi_local"?Ks.model="kimi-code/kimi-for-coding":Ze==="cursor"?Ks.model="auto":Ze==="opencode_local"?Ks.model="openai/gpt-5.2-codex":Ze==="paperclip_runner"&&(Ks.model=nN),de(Ks)}else K(At=>({...At,adapterType:Ze,adapterConfig:{model:Ze==="gemini_local"?"auto":Ze==="kimi_local"?"kimi-code/kimi-for-coding":Ze==="opencode_local"?"openai/gpt-5.2-codex":Ze==="cursor"?"auto":Ze==="paperclip_runner"?oat(ie,he.model):"",effort:"",modelReasoningEffort:"",variant:"",mode:"",...Ze==="codex_local"?{dangerouslyBypassApprovalsAndSandbox:!0}:Ze==="paperclip_runner"?{...CNe(ie,G("adapterConfig","model",he.model))}:{}}}))},"onChange")})}),!a&&f&&(0,t.jsx)(yNe,{companyId:f,agentId:e.agent.id,agentName:e.agent.name,adapterType:ie==="paperclip_runner"?G("adapterConfig","provider",he.provider)==="codex"?"codex_local":G("adapterConfig","provider",he.provider)==="opencode"?"opencode_local":G("adapterConfig","provider",he.provider)==="acpx"&&G("adapterConfig","acpxAgent",he.acpxAgent)==="grok"?"grok_local":G("adapterConfig","provider",he.provider)==="acpx"&&G("adapterConfig","acpxAgent",he.acpxAgent)==="claude"?"claude_local":ie:ie,routerAdapterType:ie,value:yJ.safeParse(O.runtime.runtimeConfig?.aiConnection??ce.aiConnection).data,model:String(G("adapterConfig","model",he.model)??""),environmentId:it||void 0,legacy:!0,onChange:r(Ze=>Y("runtime","runtimeConfig",{...ce,aiConnection:Ze}),"onChange")}),d&&!e.compactTestFeedback&&(Yt||Bt.error)&&(0,t.jsx)("div",{className:"rounded-md border border-destructive/30 bg-destructive/10 px-3 py-2 text-xs text-destructive",children:Yt??(Bt.error instanceof Error?Bt.error.message:"Environment test failed")}),d&&!e.compactTestFeedback&&Bt.data&&(0,t.jsx)(Sat,{result:Bt.data}),d&&Ms&&(0,t.jsx)(LW,{companyId:f,adapterType:ie,environmentId:Ce,onStored:a?pt:vt,onApplyStored:a?Qe:ut,onAccountBinding:a?void 0:Le},`${ie}:${Ce}`),Ie&&(0,t.jsx)(Ss,{label:"Working directory (deprecated)",hint:Ni.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)(Ho,{className:"h-3.5 w-3.5 text-muted-foreground shrink-0"}),(0,t.jsx)(Ka,{value:a?dt.cwd:G("adapterConfig","cwd",String(he.cwd??"")),onCommit:r(Ze=>a?de({cwd:Ze}):Y("adapterConfig","cwd",Ze||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)(Dd,{})]})}),Bs("adapter"),be&&(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)($W,{models:ft,value:mt,onChange:r(Ze=>{const At=S5(ie,Ze),fs=["codex_local","claude_local","grok_local"].includes(ie)&&!!zs&&!At.includes(String(zs));if(a){de({model:Ze,...fs?{thinkingEffort:""}:{}});return}Y("adapterConfig","model",Ze||void 0),fs&&(Y("adapterConfig",Fs,void 0),Y("adapterConfig","reasoningEffort",void 0))},"onChange"),open:er,onOpenChange:Fe,defaultLabel:ie==="claude_local"?"Default (claude-opus-5)":void 0,allowDefault:ie!=="opencode_local"&&ie!=="pi_local"&&ie!=="paperclip_runner",required:ie==="opencode_local"||ie==="pi_local",groupByProvider:ie==="opencode_local"||ie==="pi_local",preserveOrder:_W(ie),creatable:!0,detectedModel:St,detectedModelCandidates:[],onDetectModel:ie==="opencode_local"||ie==="paperclip_runner"?void 0:async()=>(await Is()).data?.model??null,onRefreshModels:iat(ie)?vs:void 0,refreshingModels:Cs,detectModelLabel:"Detect model",emptyDetectHint:"No model detected. Select or enter one manually."}),(Ot||We)&&(0,t.jsx)("p",{className:"text-xs text-destructive",children:Ot??(We instanceof Error?We.message:"Failed to load adapter models.")}),ie==="opencode_local"&&kt&&kt.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 ",kt.name,"."]}),Us&&(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)(Cat,{value:zs,options:Hs,onChange:r(Ze=>a?de({thinkingEffort:Ze}):Y("adapterConfig",Fs,Ze||void 0),"onChange"),open:st,onOpenChange:xt}),ie==="codex_local"&&ur&&zs==="minimal"&&(0,t.jsx)("p",{className:"text-xs text-amber-400",children:"Codex may reject `minimal` thinking when search is enabled."})]})]})]})]}),(0,t.jsxs)("div",{"data-config-section":"configuration",className:W(!i&&"border-b border-border"),children:[i?(0,t.jsx)("h3",{className:"text-sm font-medium mb-3",children:"Configuration"}):(0,t.jsx)("div",{className:"px-4 py-2 text-xs font-medium text-muted-foreground",children:"Configuration"}),(0,t.jsxs)("div",{className:W(i?"border border-border rounded-lg p-4 space-y-3":"px-4 pb-3 space-y-3"),children:[!a&&typeof he.bootstrapPromptTemplate=="string"&&he.bootstrapPromptTemplate&&(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)(Ss,{label:"Bootstrap prompt (legacy)",hint:Ni.bootstrapPrompt,children:(0,t.jsx)(fd,{value:G("adapterConfig","bootstrapPromptTemplate",String(he.bootstrapPromptTemplate??"")),onChange:r(Ze=>Y("adapterConfig","bootstrapPromptTemplate",Ze||void 0),"onChange"),placeholder:"Optional initial setup prompt for the first run",contentClassName:"min-h-(--sz-44px) text-sm font-mono",imageUploadHandler:r(async Ze=>{const At=`agents/${e.agent.id}/bootstrap-prompt`;return(await U.mutateAsync({file:Ze,namespace:At})).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."})]}),Bs("configuration"),(be||ie==="process"||ws?.fields.some(Ze=>Fq(Ze.key)==="advanced"))&&(0,t.jsx)(mE,{title:"Advanced",open:Mt,onToggle:r(()=>rs(!Mt),"onToggle"),children:(0,t.jsxs)("div",{className:"space-y-3",children:[be&&(0,t.jsxs)(t.Fragment,{children:[" ",!D&&(0,t.jsx)(Ss,{label:"Command",hint:Ni.localCommand,children:(0,t.jsx)(Ka,{value:a?dt.command:G("adapterConfig",Ut,String(he.command??"")),onCommit:r(Ze=>a?de({command:Ze}):Y("adapterConfig",Ut,Ze||null),"onCommit"),immediate:!0,className:Zm,placeholder:{claude_local:"claude",codex_local:"codex",gemini_local:"gemini",kimi_local:"kimi",pi_local:"pi",cursor:"agent",opencode_local:"opencode"}[ie]??ie.replace(/_local$/,"")})}),(0,t.jsx)(Ss,{label:"Extra args (comma-separated)",hint:Ni.extraArgs,children:(0,t.jsx)(Ka,{value:a?dt.extraArgs:G("adapterConfig","extraArgs",dat(he.extraArgs)),onCommit:r(Ze=>a?de({extraArgs:Ze}):Y("adapterConfig","extraArgs",Ze?.trim()?cat(Ze):null),"onCommit"),className:Zm,placeholder:"e.g. --verbose, --foo=bar"})})]}),Bs("advanced")]})})]})]}),e.environmentVariablesPlacement!=="secrets"&&(be||ws?.fields.some(Ze=>Fq(Ze.key)==="environment"))&&(0,t.jsxs)("div",{"data-config-section":"environment-variables",className:W(!i&&"border-b border-border"),children:[i?(0,t.jsx)("h3",{className:"text-sm font-medium mb-3",children:"Environment variables"}):(0,t.jsx)("div",{className:"px-4 py-2 text-xs font-medium text-muted-foreground",children:"Environment variables"}),(0,t.jsx)("div",{className:W(i?"border border-border rounded-lg p-4 space-y-3":"px-4 pb-3 space-y-3"),children:be?Zs:Bs("environment")})]}),a&&u?(0,t.jsxs)("div",{"data-config-section":"run-policy",className:W(!i&&"border-b border-border"),children:[i?(0,t.jsxs)("h3",{className:"text-sm font-medium flex items-center gap-2 mb-3",children:[(0,t.jsx)(OC,{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)(OC,{className:"h-3 w-3"})," Run Policy"]}),(0,t.jsxs)("div",{className:W(i?"border border-border rounded-lg p-4 space-y-3":"px-4 pb-3 space-y-3"),children:[(0,t.jsx)(ote,{label:"Heartbeat on interval",hint:Ni.heartbeatInterval,checked:dt.heartbeatEnabled,onCheckedChange:r(Ze=>de({heartbeatEnabled:Ze}),"onCheckedChange"),number:dt.intervalSec,onNumberChange:r(Ze=>de({intervalSec:Ze}),"onNumberChange"),numberLabel:"sec",numberPrefix:"Run heartbeat every",numberHint:Ni.intervalSec,showNumber:dt.heartbeatEnabled}),(0,t.jsx)(mE,{title:"Advanced Run Policy",open:xe,onToggle:r(()=>Qt(!xe),"onToggle"),children:(0,t.jsx)("div",{className:"space-y-3",children:Bs("runPolicy")})})]})]}):a?null:(0,t.jsxs)("div",{"data-config-section":"run-policy",className:W(!i&&"border-b border-border"),children:[i?(0,t.jsxs)("h3",{className:"text-sm font-medium flex items-center gap-2 mb-3",children:[(0,t.jsx)(OC,{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)(OC,{className:"h-3 w-3"})," Run Policy"]}),(0,t.jsxs)("div",{className:W(i?"border border-border rounded-lg overflow-hidden":""),children:[(0,t.jsx)("div",{className:W(i?"p-4 space-y-3":"px-4 pb-3 space-y-3"),children:(0,t.jsx)(ote,{label:"Heartbeat on interval",hint:Ni.heartbeatInterval,checked:G("heartbeat","enabled",ge.enabled===!0),onCheckedChange:r(Ze=>Y("heartbeat","enabled",Ze),"onCheckedChange"),number:G("heartbeat","intervalSec",Number(ge.intervalSec??300)),onNumberChange:r(Ze=>Y("heartbeat","intervalSec",Ze),"onNumberChange"),numberLabel:"sec",numberPrefix:"Run heartbeat every",numberHint:Ni.intervalSec,showNumber:G("heartbeat","enabled",ge.enabled===!0)})}),(0,t.jsx)(mE,{title:"Advanced Run Policy",bordered:i,open:xe,onToggle:r(()=>Qt(!xe),"onToggle"),children:(0,t.jsxs)("div",{className:"space-y-3",children:[Bs("runPolicy"),be&&(0,t.jsx)(t.Fragment,{children:!a&&(0,t.jsxs)(t.Fragment,{children:[!ws?.fields.some(Ze=>Ze.key==="timeoutSec")&&(0,t.jsx)(Ss,{label:"Timeout (sec)",hint:Ni.timeoutSec,children:(0,t.jsx)(Rc,{value:G("adapterConfig","timeoutSec",Number(he.timeoutSec??0)),onCommit:r(Ze=>Y("adapterConfig","timeoutSec",Ze),"onCommit"),immediate:!0,className:Zm})}),!ws?.fields.some(Ze=>Ze.key==="graceSec")&&(0,t.jsx)(Ss,{label:"Interrupt grace period (sec)",hint:Ni.graceSec,children:(0,t.jsx)(Rc,{value:G("adapterConfig","graceSec",Number(he.graceSec??15)),onCommit:r(Ze=>Y("adapterConfig","graceSec",Ze),"onCommit"),immediate:!0,className:Zm})})]})}),(0,t.jsx)(_d,{label:"Wake on demand",hint:Ni.wakeOnDemand,checked:G("heartbeat","wakeOnDemand",ge.wakeOnDemand!==!1),onChange:r(Ze=>Y("heartbeat","wakeOnDemand",Ze),"onChange")}),(0,t.jsx)(Ss,{label:"Cooldown (sec)",hint:Ni.cooldownSec,children:(0,t.jsx)(Rc,{value:G("heartbeat","cooldownSec",Number(ge.cooldownSec??10)),onCommit:r(Ze=>Y("heartbeat","cooldownSec",Ze),"onCommit"),immediate:!0,className:Zm})}),(0,t.jsx)(Ss,{label:"Max concurrent runs",hint:Ni.maxConcurrentRuns,children:(0,t.jsx)(Rc,{value:G("heartbeat","maxConcurrentRuns",Number(ge.maxConcurrentRuns??20)),onCommit:r(Ze=>Y("heartbeat","maxConcurrentRuns",Ze),"onCommit"),immediate:!0,className:Zm})}),(0,t.jsxs)("div",{className:"rounded-md border border-border/70 px-3 py-2",children:[(0,t.jsx)(_d,{label:"Continue after max-turn stop",hint:Ni.maxTurnContinuationEnabled,checked:tr,onChange:r(Ze=>Ps({enabled:Ze}),"onChange")}),tr?(0,t.jsxs)("div",{className:"mt-3 grid gap-3 sm:grid-cols-2",children:[(0,t.jsx)(Ss,{label:"Continuation attempts",hint:Ni.maxTurnContinuationMaxAttempts,children:(0,t.jsx)(Rc,{value:pn,onCommit:r(Ze=>Ps({maxAttempts:vE(Ze,0,Wte)}),"onCommit"),immediate:!0,className:Zm})}),(0,t.jsx)(Ss,{label:"Continuation delay (sec)",hint:Ni.maxTurnContinuationDelaySec,children:(0,t.jsx)(Rc,{value:yt,onCommit:r(Ze=>Ps({delayMs:gat(Ze)}),"onCommit"),immediate:!0,className:Zm})})]}):null]})]})})]})]}),!a&&p?(0,t.jsxs)("div",{className:W(!i&&"border-b border-border"),children:[i?(0,t.jsxs)("h3",{className:"mb-3 flex items-center gap-2 text-sm font-medium",children:[(0,t.jsx)(Uv,{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)(Uv,{className:"h-3 w-3"})," Debugging"]}),(0,t.jsxs)("div",{className:W("border-border bg-accent/30",i?"rounded-lg border p-4":"mx-4 mb-4 rounded-md border px-3 py-3"),children:[(0,t.jsx)(_d,{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",me.providerTrace)==="raw",onChange:r(Ze=>Y("debug","providerTrace",Ze?"raw":void 0),"onChange")}),G("debug","providerTrace",me.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)(Uv,{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)(PNe,{state:wt?"running":Yt||Bt.error?"fail":xn?.status??"idle",result:xn??null,error:Yt??(Bt.error instanceof Error?Bt.error.message:null),onTest:Pn,disabled:Zn})]})}r(MSe,"AgentConfigForm");var n6=new Set(["authenticated","failed","timed_out","cancelled"]),r6=2e3;function a6({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)(L,{type:"button",variant:"ghost",size:"icon-xs","aria-label":s,title:s,className:"text-muted-foreground hover:text-foreground",onClick:r(async()=>{try{await fa(e),a(!0)}catch{a(!1)}i.current&&clearTimeout(i.current),i.current=setTimeout(()=>a(!1),1500)},"onClick"),children:n?(0,t.jsx)(gs,{className:"size-3"}):(0,t.jsx)(Ir,{className:"size-3"})})}r(a6,"AdapterLoginCopyButton");function vat({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)(gs,{className:"size-3 shrink-0"}),(0,t.jsx)("span",{children:"Authenticated. The environment has credentials now."})]}):(0,t.jsxs)("div",{className:"flex items-start gap-2 text-(length:--text-micro) text-destructive",children:[(0,t.jsx)(Es,{className:"size-3 shrink-0"}),(0,t.jsxs)("span",{children:[e==="timed_out"?"Login timed out":e==="cancelled"?"Login cancelled":"Login failed",s?`: ${s}`:"."]})]})}r(vat,"AdapterLoginTerminalState");var yat={claude_local:"Anthropic",codex_local:"OpenAI"};function DSe(e){const s=yat[e];return s?`Sign in to ${s}`:"Sign in to the environment"}r(DSe,"adapterLoginTitle");function LW(e){return Wy()(e.adapterType).login?.panelMode==="submitted_browser_code"?(0,t.jsx)(Nat,{...e}):(0,t.jsx)(jat,{...e})}r(LW,"AdapterLoginPanel");var K$=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 jat({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=je({mutationFn:r(()=>$t.startAdapterAuthLogin(e,s,{environmentId:n,aiConnection:c}),"mutationFn"),onSuccess:r(re=>{N.current=!1,f(null),b(null),j("idle"),h(re.sessionId)},"onSuccess"),onError:r(re=>{f(re instanceof Error?re.message:"Could not start the login.")},"onError")}),k=(0,m.useCallback)(()=>{N.current=!1,h(null),b(null),f(null)},[]),S=je({mutationFn:r(()=>$t.cancelAdapterAuthLogin(e,s,u),"mutationFn"),onSuccess:k,onError:r(re=>{f(re instanceof Error?re.message:"Could not cancel the login.")},"onError")}),C=Z({queryKey:["adapter-login-active-session",e,s],queryFn:r(async()=>{try{const re=await $t.getActiveAdapterAuthLoginSession(e,s);if(!re)return null;if(c&&re.environmentId!==n||!!re.aiConnection!=!!c||c&&(re.aiConnection?.provider!==c.provider||re.aiConnection?.method!==c.method||re.aiConnection?.connectionId!==c.connectionId||re.aiConnection?.ownership!==c.ownership||re.aiConnection?.allAgents!==c.allAgents||JSON.stringify(re.aiConnection?.agentIds)!==JSON.stringify(c.agentIds)))throw new K$(re.sessionId);return re}catch(re){if(re instanceof dn&&re.status===404)return null;throw re}},"queryFn"),retry:!1,gcTime:0,staleTime:0}),[I,R]=(0,m.useState)(!1),T=Z({queryKey:["adapter-login-status",e,s,u],queryFn:r(()=>$t.getAdapterAuthLoginStatus(e,s,u),"queryFn"),enabled:!!u&&!I,retry:r((re,oe)=>oe instanceof dn&&oe.status===404?!1:re<3,"retry"),refetchInterval:r(re=>{const oe=re.state.data?.status;return oe&&n6.has(oe)?!1:r6},"refetchInterval")});(0,m.useEffect)(()=>{const re=T.data?.prompt??null;re&&b(re)},[T.data]);const A=T.data??w.data??null,D=A?.status??null,M=x,B=D?n6.has(D):!1,E=!!u&&!B,z=w.isPending||E||v==="saving",$=(0,m.useRef)(!1);(0,m.useEffect)(()=>{if($.current||!C.isFetched)return;$.current=!0;const re=C.data;re&&(N.current=!0,f(null),b(re.prompt??null),h(re.sessionId))},[C.isFetched,C.data]),(0,m.useEffect)(()=>{const re=T.error;if(!(re instanceof dn&&re.status===404)||!N.current||I)return;R(!0);const oe=u;(async()=>(oe&&await $t.cancelAdapterAuthLogin(e,s,oe).catch(()=>{}),R(!1),k()))()},[T.error,I,u,e,s,k]);const q=(0,m.useRef)(!1),U=je({mutationFn:r(async()=>{const re=C.error;re instanceof K$&&await $t.cancelAdapterAuthLogin(e,s,re.sessionId)},"mutationFn"),onSuccess:r(async()=>{q.current=!1,$.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")}),O=(0,m.useRef)(w.mutate);O.current=w.mutate,(0,m.useEffect)(()=>{if(!(!a||q.current)){if(C.isError){q.current=!0,f(C.error instanceof Error?C.error.message:"Could not check for an active login.");return}C.isSuccess&&(q.current=!0,!C.data&&O.current())}},[a,C.isSuccess,C.isError,C.data,C.error]);const K=(0,m.useRef)(!1),H=(0,m.useRef)(i);H.current=i,(0,m.useEffect)(()=>{D!=="authenticated"||K.current||(K.current=!0,H.current?.(u??void 0))},[D]);const ee=(0,m.useRef)(null),se=(0,m.useRef)(o);se.current=o;const ne=T.data?.codexAccountBinding??null,fe=(0,m.useCallback)(async re=>{const oe=se.current;if(oe){j("saving");try{await oe(re),j("bound")}catch{j("failed")}}},[]);(0,m.useEffect)(()=>{D!=="authenticated"||!u||ee.current!==u&&(!ne||!ne.companyIdentityDiffers||!se.current||(ee.current=u,fe(ne)))},[D,u,ne,fe]);const X=(0,m.useRef)(d);if(X.current=d,(0,m.useEffect)(()=>{X.current?.(M?.url??null)},[M]),l==="onboarding"){const re=B&&D&&D!=="authenticated";return(0,t.jsx)(UNe,{loading:!M&&!p&&!re,providerName:zNe(s),authorizationUrl:M?.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 K$&&(0,t.jsx)(L,{type:"button",variant:"outline",disabled:U.isPending,onClick:r(()=>U.mutate(),"onClick"),children:"Cancel previous sign-in and retry"})]}):re?(0,t.jsx)("p",{role:"alert",className:"pl-2 text-xs text-destructive",children:D==="timed_out"?"The login timed out. Start it again.":D==="cancelled"?"The login was cancelled.":"The login did not finish. Start it again."}):(0,t.jsx)(get,{code:M?.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:DSe(s)}),(0,t.jsxs)("div",{className:"flex items-center gap-1.5",children:[E&&(0,t.jsx)(L,{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)(L,{type:"button",variant:"outline",size:"sm",className:"h-7 px-2.5 text-xs",disabled:z,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:[E&&!M&&(0,t.jsxs)("div",{className:"flex items-center gap-2 text-(length:--text-micro) text-muted-foreground",children:[(0,t.jsx)(rt,{className:"size-3 animate-spin shrink-0"}),(0,t.jsx)("span",{children:"Preparing..."})]}),E&&M&&(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:M.code})]}),(0,t.jsx)(a6,{value:M.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:M.url})]}),(0,t.jsxs)("div",{className:"flex items-center",children:[(0,t.jsx)(a6,{value:M.url,label:"Copy URL"}),(0,t.jsx)(L,{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:M.url,target:"_blank",rel:"noreferrer noopener",children:(0,t.jsx)(Vn,{className:"size-3"})})})]})]})]}),B&&D&&(0,t.jsx)(vat,{status:D,message:A?.failure?.message??null}),D==="authenticated"&&v==="saving"&&(0,t.jsxs)("div",{className:"flex items-center gap-2 text-(length:--text-micro) text-muted-foreground",children:[(0,t.jsx)(rt,{className:"size-3 animate-spin shrink-0"}),(0,t.jsx)("span",{children:"Binding this agent to the signed-in account..."})]}),D==="authenticated"&&v==="bound"&&(0,t.jsxs)("div",{className:"flex items-center gap-2 text-(length:--text-micro) text-foreground",children:[(0,t.jsx)(gs,{className:"size-3 shrink-0"}),(0,t.jsx)("span",{children:"Agent bound to the signed-in account."})]}),D==="authenticated"&&v==="failed"&&(0,t.jsxs)("div",{className:"flex items-center gap-2 text-(length:--text-micro)",children:[(0,t.jsx)(Es,{className:"size-3 shrink-0 text-destructive"}),(0,t.jsx)("span",{className:"text-destructive",children:"Could not bind this agent to the signed-in account."}),(0,t.jsx)(L,{type:"button",variant:"outline",size:"sm",className:"h-6 px-2 text-xs",onClick:r(()=>{ne&&fe(ne)},"onClick"),children:"Retry"})]})]})]})}r(jat,"DisplayedCodeLoginPanel");var wat=new Set(["failed","timed_out","cancelled"]),Vte="The login did not finish. Start the login again.",kat=9e5,Hte="The login timed out. Start the login again.";function Nat({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)(""),[I,R]=(0,m.useState)(null),[T,A]=(0,m.useState)(!1),[D,M]=(0,m.useState)(!1),[B,E]=(0,m.useState)(!1),[z,$]=(0,m.useState)(!1),q=(0,m.useRef)(!1),[U,O]=(0,m.useState)(!1),K=(0,m.useRef)(!1),H=r(()=>{v(null),N(null),k(!1),C(""),R(null),A(!1),M(!1),$(!1),E(!1),q.current=!1},"resetLocalState"),ee=Z({queryKey:["claude-oauth-token-status",e],queryFn:r(async()=>{try{return await $t.getClaudeOAuthTokenStatus(e)}catch(tt){if(tt instanceof dn&&tt.status===404)return null;throw tt}},"queryFn"),retry:r((tt,Pe)=>Pe instanceof dn&&Pe.status===404?!1:tt<2,"retry")}).data??null,se=je({mutationFn:r(()=>$t.startClaudeSetupTokenLogin(e,{environmentId:n,aiConnection:h,...ee&&!h?{overwrite:{expectedSecretId:ee.secretId,expectedLatestVersion:ee.latestVersion}}:{}}),"mutationFn"),onSuccess:r(tt=>{K.current=!1,H(),x(tt.sessionId)},"onSuccess"),onError:r(tt=>{v(tt instanceof Error?tt.message:"Could not start the login.")},"onError")}),ne=r(()=>{K.current=!1,x(null),H()},"clearActiveSession"),fe=je({mutationFn:r(()=>$t.cancelClaudeSetupTokenLogin(e,f),"mutationFn"),onSuccess:r(()=>{ne()},"onSuccess"),onError:r(tt=>{if(tt instanceof dn&&tt.status===404){ne();return}v(tt instanceof Error?tt.message:"Could not cancel the login.")},"onError")}),X=(0,m.useCallback)(tt=>{$t.cancelClaudeSetupTokenLogin(e,tt).catch(()=>{})},[e]),re=Z({queryKey:["claude-setup-token-active-session",e],queryFn:r(async()=>{try{const tt=await $t.getActiveClaudeSetupTokenLoginSession(e);if(!tt)return null;if(h&&tt.environmentId!==n||!!tt.aiConnection!=!!h||h&&(tt.aiConnection?.provider!==h.provider||tt.aiConnection?.method!==h.method||tt.aiConnection?.connectionId!==h.connectionId||tt.aiConnection?.ownership!==h.ownership||tt.aiConnection?.allAgents!==h.allAgents||JSON.stringify(tt.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 tt}catch(tt){if(tt instanceof dn&&tt.status===404)return null;throw tt}},"queryFn"),retry:!1,gcTime:0,staleTime:0}),[oe,G]=(0,m.useState)(!1),Y=!!f&&!D&&!z&&!oe,Q=Z({queryKey:["claude-setup-token-status",e,f],queryFn:r(()=>$t.getClaudeSetupTokenLoginStatus(e,f),"queryFn"),enabled:Y,retry:r((tt,Pe)=>Pe instanceof dn&&Pe.status===404?!1:tt<3,"retry"),refetchInterval:r(tt=>{if(D||z)return!1;const Pe=tt.state.data?.status;return Pe&&n6.has(Pe)?!1:r6},"refetchInterval")});(0,m.useEffect)(()=>{const tt=Q.error;if(tt instanceof dn&&tt.status===404){if(K.current){if(oe)return;G(!0);const Pe=f;(async()=>(Pe&&await $t.cancelClaudeSetupTokenLogin(e,Pe).catch(()=>{}),G(!1),ne()))();return}$(!0)}},[Q.error,oe,f,e]);const te=(0,m.useRef)(!1);(0,m.useEffect)(()=>{if(te.current||!re.isFetched)return;te.current=!0;const tt=re.data;tt&&(K.current=!0,H(),x(tt.sessionId),tt.prompt&&(N(tt.prompt.authorizationUrl),tt.prompt.transportAdvisory&&k(!0)))},[re.isFetched,re.data]);const ae=Z({queryKey:["claude-setup-token-prompt",e,f],enabled:Y&&!j,queryFn:r(async()=>{try{return await $t.getClaudeSetupTokenLoginPrompt(e,f)}catch(tt){if(tt instanceof dn&&tt.status===404)return null;throw tt}},"queryFn"),refetchInterval:r(tt=>D||tt.state.data?.authorizationUrl?!1:r6,"refetchInterval")});(0,m.useEffect)(()=>{const tt=ae.data?.authorizationUrl??null;tt&&N(tt),ae.data?.transportAdvisory&&k(!0)},[ae.data]);const le=je({mutationFn:r(tt=>$t.submitClaudeSetupTokenBrowserCode(e,f,tt),"mutationFn"),onError:r(tt=>{v(tt instanceof Error?tt.message:"Could not submit the browser code.")},"onError")}),he=je({mutationFn:r(()=>$t.completeClaudeSetupTokenLogin(e,f),"mutationFn"),onSuccess:r(tt=>{R(tt.storedSessionId),a?.(tt.storedSessionId)},"onSuccess"),onError:r(()=>{A(!0)},"onError")}),ce=Q.data?.status??se.data?.status??null,ge=Q.data?.expiresAt??se.data?.expiresAt??null,me=(0,m.useRef)(he.mutate);me.current=he.mutate,(0,m.useEffect)(()=>{ce==="authenticated"&&!q.current&&(q.current=!0,me.current())},[ce]);const ie=I!==null,ue=T||z||!!(ce&&wat.has(ce)),ke=ce==="authenticated"&&!ie&&!T,be=!!f&&!ie&&!ue&&!D,Ie=se.isPending||be;(0,m.useEffect)(()=>{if(!be)return;const tt=ge!==null?new Date(ge).getTime():NaN,Pe=Number.isFinite(tt)?Math.max(0,tt-Date.now()):kat,Ce=setTimeout(()=>{f&&X(f),M(!0)},Pe);return()=>clearTimeout(Ce)},[be,ge,f,X]);const Ue=S.trim(),at=be&&!!j&&!ke&&bLe(Ue)&&!le.isPending&&!B,dt=(0,m.useRef)(c);dt.current=c;const de=(0,m.useRef)(d);de.current=d;const Be=r(()=>{at&&(v(null),le.mutate(Ue),E(!0),dt.current?.(),u!=="onboarding"&&C(""))},"handleSubmit"),pt=(0,m.useRef)(!1),vt=(0,m.useRef)(se.mutate);vt.current=se.mutate,(0,m.useEffect)(()=>{if(!(!o||pt.current)){if(re.isError){pt.current=!0,v(re.error instanceof Error?re.error.message:"Could not check for an active login.");return}re.isSuccess&&(pt.current=!0,!re.data&&vt.current())}},[o,re.isSuccess,re.isError,re.data,re.error]);const Le=(0,m.useRef)(Be);Le.current=Be;const Qe=u==="onboarding",ut=(0,m.useRef)(!1);(0,m.useEffect)(()=>{!Qe||!ut.current||(ut.current=!1,at&&Le.current())},[Qe,at,S]);const Ye=(0,m.useRef)(!1),it=(0,m.useRef)(l);it.current=l,(0,m.useEffect)(()=>{!ie||Ye.current||(Ye.current=!0,it.current?.(f??void 0))},[ie]),(0,m.useEffect)(()=>{B&&(!b&&!ue&&!D||(E(!1),de.current?.()))},[B,b,ue,D]);const kt=(0,m.useRef)(p);if(kt.current=p,(0,m.useEffect)(()=>{kt.current?.(j)},[j]),u==="onboarding"){const tt=ue||D;return(0,t.jsxs)(UNe,{loading:!j&&!b&&!tt,providerName:zNe(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)(Es,{className:"mt-0.5 size-3 shrink-0"}),"This connection is not encrypted. The login code travels in clear text on this network. Continue only on a network you trust."]}),b?(0,t.jsx)("p",{role:"alert",className:"pl-2 text-xs text-destructive",children:b}):tt?(0,t.jsx)("p",{role:"alert",className:"pl-2 text-xs text-destructive",children:D&&!ue?Hte:Vte}):(0,t.jsx)(n4,{value:S,onChange:C,onSubmit:Be,onPaste:r(()=>{ut.current=!0},"onPaste"),masked:!0,disabled:le.isPending||ke||B})]})}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:DSe(s)}),(0,t.jsxs)("div",{className:"flex items-center gap-1.5",children:[be&&(0,t.jsx)(L,{type:"button",variant:"ghost",size:"sm",className:"h-7 px-2.5 text-xs text-muted-foreground hover:text-foreground",disabled:fe.isPending,onClick:r(()=>fe.mutate(),"onClick"),children:"Cancel"}),i&&ee&&!be&&!ie&&!U&&(0,t.jsx)(L,{type:"button",variant:"default",size:"sm",className:"h-7 px-2.5 text-xs",onClick:r(()=>{i(),O(!0)},"onClick"),children:"Use saved login"}),(0,t.jsx)(L,{type:"button",variant:"outline",size:"sm",className:"h-7 px-2.5 text-xs",disabled:Ie,onClick:r(()=>se.mutate(),"onClick"),children:ee&&!be&&!ie?"Sign in to replace":"Sign in"})]})]}),ee&&!be&&!ie&&!U&&(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."}),U&&(0,t.jsxs)("div",{className:"flex items-center gap-2 text-(length:--text-micro) text-foreground",children:[(0,t.jsx)(gs,{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:[be&&!j&&!ke&&(0,t.jsxs)("div",{className:"flex items-center gap-2 text-(length:--text-micro) text-muted-foreground",children:[(0,t.jsx)(rt,{className:"size-3 animate-spin shrink-0"}),(0,t.jsx)("span",{children:"Preparing..."})]}),be&&j&&!ke&&(0,t.jsxs)("div",{className:"space-y-2",children:[w&&(0,t.jsxs)("div",{className:"flex items-start gap-2 rounded-md border border-amber-300 bg-amber-50 px-2 py-1.5 text-(length:--text-micro) text-amber-800 dark:border-amber-500/40 dark:bg-amber-500/10 dark:text-amber-200",children:[(0,t.jsx)(Es,{className:"size-3 shrink-0 mt-0.5"}),(0,t.jsx)("span",{children:"This connection is not encrypted. The login code travels in clear text on this network. Continue only on a network you trust."})]}),(0,t.jsx)("div",{className:"text-(length:--text-micro) text-muted-foreground",children:"Open the authorization page, then enter the browser code it shows."}),(0,t.jsxs)("div",{className:"flex items-center justify-between gap-2",children:[(0,t.jsxs)("div",{className:"min-w-0",children:[(0,t.jsx)("div",{className:"text-(length:--text-micro) uppercase tracking-wide text-muted-foreground",children:"1. Authorization URL"}),(0,t.jsx)("span",{className:"font-mono text-xs text-foreground break-all",children:j})]}),(0,t.jsxs)("div",{className:"flex items-center",children:[(0,t.jsx)(a6,{value:j,label:"Copy URL"}),(0,t.jsx)(L,{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)(Vn,{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(tt=>C(tt.target.value),"onChange"),onKeyDown:r(tt=>{tt.key==="Enter"&&(tt.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)(L,{type:"button",variant:"outline",size:"sm",className:"h-7 px-2.5 text-xs",disabled:!at,onClick:Be,children:"Submit"})]})]})]}),ke&&(0,t.jsxs)("div",{className:"flex items-center gap-2 text-(length:--text-micro) text-muted-foreground",children:[(0,t.jsx)(rt,{className:"size-3 animate-spin shrink-0"}),(0,t.jsx)("span",{children:"Completing the login…"})]}),ie&&(0,t.jsxs)("div",{className:"flex items-center gap-2 text-(length:--text-micro) text-foreground",children:[(0,t.jsx)(gs,{className:"size-3 shrink-0"}),(0,t.jsx)("span",{children:"Authenticated. The environment has credentials now."})]}),ue&&(0,t.jsxs)("div",{className:"flex items-start gap-2 text-(length:--text-micro) text-destructive",children:[(0,t.jsx)(Es,{className:"size-3 shrink-0"}),(0,t.jsx)("span",{children:Vte})]}),D&&!ue&&!ie&&(0,t.jsxs)("div",{className:"flex items-start gap-2 text-(length:--text-micro) text-destructive",children:[(0,t.jsx)(Es,{className:"size-3 shrink-0"}),(0,t.jsx)("span",{children:Hte})]})]})]})}r(Nat,"SubmittedBrowserCodeLoginPanel");function Sat({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(Sat,"AdapterEnvironmentResult$1");function LSe({value:e,onChange:s,disabledTypes:n}){const[a,i]=(0,m.useState)(!1),o=Ch(e),l=(0,m.useMemo)(()=>RSe(c=>rN[c]??Ff(c)).filter(c=>!n.has(c.value)),[n]);return(0,t.jsxs)(gr,{open:a,onOpenChange:i,children:[(0,t.jsx)(Sr,{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.jsxs)("span",{className:"inline-flex min-w-0 items-center gap-1.5",children:[e==="opencode_local"?(0,t.jsx)(Bq,{className:"h-3.5 w-3.5"}):null,(0,t.jsx)("span",{className:"truncate",children:rN[e]??Ff(e)}),o.experimental&&(0,t.jsx)(Gte,{})]}),(0,t.jsx)(nn,{className:"h-3 w-3 text-muted-foreground"})]})}),(0,t.jsx)(dr,{className:"w-(--radix-popover-trigger-width) p-1",align:"start",children:l.map(c=>(0,t.jsxs)("button",{disabled:c.comingSoon,className:W("flex items-center justify-between w-full px-2 py-1.5 text-sm rounded",c.comingSoon?"opacity-40 cursor-not-allowed":"hover:bg-accent/50",c.value===e&&!c.comingSoon&&"bg-accent"),onClick:r(()=>{c.comingSoon||(s(c.value),i(!1))},"onClick"),children:[(0,t.jsxs)("span",{className:"inline-flex items-center gap-1.5",children:[c.value==="opencode_local"?(0,t.jsx)(Bq,{className:"h-3.5 w-3.5"}):null,(0,t.jsx)("span",{children:c.label}),c.experimental&&(0,t.jsx)(Gte,{})]}),c.comingSoon&&(0,t.jsx)("span",{className:"text-(length:--text-nano) text-muted-foreground",children:"Coming soon"})]},c.value))})]})}r(LSe,"AdapterTypeDropdown");function Gte(){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(Gte,"ExperimentalBadge$1");function $W({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,detectModelLabel:v,emptyDetectHint:j,defaultLabel:N}){const[w,k]=(0,m.useState)(""),[S,C]=(0,m.useState)(!1),I=e.find(E=>E.id===s),R=w.trim(),T=!!(u&&R&&!e.some(E=>E.id.toLowerCase()===R.toLowerCase())),A=(0,m.useMemo)(()=>{const E=new Set;h&&E.add(h);for(const z of p??[])z&&E.add(z);return E},[h,p]),D=(0,m.useMemo)(()=>e.filter(E=>{if(A.has(E.id))return!1;if(!w.trim())return!0;const z=w.toLowerCase(),$=qq(E.id)??"";return E.id.toLowerCase().includes(z)||E.label.toLowerCase().includes(z)||$.toLowerCase().includes(z)}),[e,w,A]),M=(0,m.useMemo)(()=>{if(!c)return[{provider:"models",entries:d?D:[...D].sort((z,$)=>z.id.localeCompare($.id))}];const E=new Map;for(const z of D){const $=qq(z.id)??"other",q=E.get($)??[];q.push(z),E.set($,q)}return Array.from(E.entries()).sort(([z],[$])=>z.localeCompare($)).map(([z,$])=>({provider:z,entries:[...$].sort((q,U)=>q.id.localeCompare(U.id))}))},[D,c,d]);async function B(){if(f){C(!0);try{const E=await f();E&&(n(E),i(!1),k(""))}finally{C(!1)}}}return r(B,"handleDetectModel"),(0,t.jsx)(Ss,{label:"Model",hint:Ni.model,children:(0,t.jsxs)(gr,{open:a,onOpenChange:r(E=>{i(E),E||k("")},"onOpenChange"),children:[(0,t.jsx)(Sr,{asChild:!0,children:(0,t.jsxs)("button",{type:"button",className:"inline-flex items-center gap-1.5 rounded-md border border-border px-2.5 py-1.5 text-sm hover:bg-accent/50 transition-colors w-full justify-between",children:[(0,t.jsx)("span",{className:W(!s&&"text-muted-foreground"),children:I?I.label:s||(o?N??"Default":l?"Select model (required)":"Select model")}),(0,t.jsx)(nn,{className:"h-3 w-3 text-muted-foreground"})]})}),(0,t.jsxs)(dr,{className:"w-(--radix-popover-trigger-width) p-1",align:"start",children:[(0,t.jsxs)("div",{className:"relative mb-1",children:[(0,t.jsx)("input",{className:"w-full px-2 py-1.5 pr-6 text-xs bg-transparent outline-none border-b border-border placeholder:text-muted-foreground/50",placeholder:u?"Search models... (type to create)":"Search models...",value:w,onChange:r(E=>k(E.target.value),"onChange"),autoFocus:!0}),w&&(0,t.jsx)("button",{type:"button",className:"absolute right-1.5 top-1/2 -translate-y-1/2 text-muted-foreground hover:text-foreground",onClick:r(()=>k(""),"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&&!w.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(()=>{B()},"onClick"),disabled:S,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"})]}),S?"Detecting...":h?v?.replace(/^Detect\b/,"Re-detect")??"Re-detect from config":v??"Detect from config"]}),x&&!w.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(E=>E.id===s)||A.has(s))&&(0,t.jsxs)("button",{type:"button",className:W("flex items-center w-full px-2 py-1.5 text-sm rounded bg-accent/50"),onClick:r(()=>{i(!1)},"onClick"),children:[(0,t.jsx)("span",{className:"block w-full text-left truncate font-mono text-xs",title:s,children:e.find(E=>E.id===s)?.label??s}),(0,t.jsx)(ct,{variant:"outline",className:"ml-auto text-(length:--text-nano) px-1.5 bg-green-500/15 text-green-400 border-green-500/20",children:"current"})]}),h&&h!==s&&(0,t.jsxs)("button",{type:"button",className:W("flex items-center w-full px-2 py-1.5 text-sm rounded hover:bg-accent/50"),onClick:r(()=>{n(h),i(!1)},"onClick"),children:[(0,t.jsx)("span",{className:"block w-full text-left truncate font-mono text-xs",title:h,children:e.find(E=>E.id===h)?.label??h}),(0,t.jsx)(ct,{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(E=>E&&E!==h&&E!==s).map(E=>{const z=e.find($=>$.id===E);return(0,t.jsxs)("button",{type:"button",className:W("flex items-center w-full px-2 py-1.5 text-sm rounded hover:bg-accent/50"),onClick:r(()=>{n(E),i(!1)},"onClick"),children:[(0,t.jsx)("span",{className:"block w-full text-left truncate font-mono text-xs",title:E,children:z?.label??E}),(0,t.jsx)(ct,{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-${E}`)}),(0,t.jsxs)("div",{className:"max-h-(--sz-240px) overflow-y-auto",children:[o&&(0,t.jsx)("button",{type:"button",className:W("flex items-center gap-2 w-full px-2 py-1.5 text-sm rounded hover:bg-accent/50",!s&&"bg-accent"),onClick:r(()=>{n(""),i(!1)},"onClick"),children:"Default"}),T&&(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(R),i(!1),k("")},"onClick"),children:[(0,t.jsx)("span",{children:"Use manual model"}),(0,t.jsx)("span",{className:"text-xs font-mono text-muted-foreground",children:R})]}),M.map(E=>(0,t.jsxs)("div",{className:"mb-1 last:mb-0",children:[c&&(0,t.jsxs)("div",{className:"px-2 py-1 text-(length:--text-nano) uppercase tracking-wide text-muted-foreground",children:[E.provider," (",E.entries.length,")"]}),E.entries.map(z=>(0,t.jsx)("button",{type:"button",className:W("flex items-center w-full px-2 py-1.5 text-sm rounded hover:bg-accent/50",z.id===s&&"bg-accent"),onClick:r(()=>{n(z.id),i(!1)},"onClick"),children:(0,t.jsx)("span",{className:"block w-full text-left truncate",title:z.id,children:c?jet(z.id):z.label})},z.id))]},E.provider)),D.length===0&&!T&&A.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:f?j??"No model detected yet. Enter a provider/model manually.":"No models found."})})]})]})]})})}r($W,"ModelDropdown");function Cat({value:e,options:s,onChange:n,open:a,onOpenChange:i}){const o=s.find(l=>l.id===e)??s[0];return(0,t.jsx)(Ss,{label:"Thinking effort",hint:Ni.thinkingEffort,children:(0,t.jsxs)(gr,{open:a,onOpenChange:i,children:[(0,t.jsx)(Sr,{asChild:!0,children:(0,t.jsxs)("button",{className:"inline-flex items-center gap-1.5 rounded-md border border-border px-2.5 py-1.5 text-sm hover:bg-accent/50 transition-colors w-full justify-between",children:[(0,t.jsx)("span",{className:W(!e&&"text-muted-foreground"),children:o?.label??"Auto"}),(0,t.jsx)(nn,{className:"h-3 w-3 text-muted-foreground"})]})}),(0,t.jsx)(dr,{className:"w-(--radix-popover-trigger-width) p-1",align:"start",children:s.map(l=>(0,t.jsxs)("button",{className:W("flex items-center justify-between w-full px-2 py-1.5 text-sm rounded hover:bg-accent/50",l.id===e&&"bg-accent"),onClick:r(()=>{n(l.id),i(!1)},"onClick"),children:[(0,t.jsx)("span",{children:l.label}),l.id?(0,t.jsx)("span",{className:"text-xs text-muted-foreground font-mono",children:l.id}):null]},l.id||"auto"))})]})})}r(Cat,"ThinkingEffortDropdown");function $Se(e){const s=`paperclip.agent-appearance.${e}`;function n(){try{const l=Dpe.safeParse(JSON.parse(sessionStorage.getItem(s)??"null"));if(l.success)return l.data}catch{}const o=VR();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($Se,"useAgentAppearanceDraft");var nC=null,V2=new Set,rC={subscribe(e){return V2.add(e),()=>{V2.delete(e)}},getSnapshot(){return nC},acquire(e){if(nC)return!1;nC=e;for(const s of V2)s();return!0},release(e){if(nC===e){nC=null;for(const s of V2)s()}}};function F_({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)(()=>AN(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)(rC.subscribe,rC.getSnapshot,()=>null),[k,S]=(0,m.useState)(!1),[C,I]=(0,m.useState)(!0),[R,T]=(0,m.useState)(!1),[A,D]=(0,m.useState)(!1),M=k&&!C&&!R&&o==="auto"&&a!=="rest";return(0,m.useEffect)(()=>{if(typeof matchMedia!="function"||typeof IntersectionObserver!="function")return;const B=matchMedia("(prefers-reduced-motion: reduce)"),E=r(()=>I(B.matches),"change");E(),B.addEventListener("change",E);const z=new IntersectionObserver($=>S($[0]?.isIntersecting??!1));return b.current&&z.observe(b.current),()=>{z.disconnect(),B.removeEventListener("change",E)}},[]),(0,m.useEffect)(()=>{M&&w===null&&rC.acquire(N.current),M||rC.release(N.current)},[M,w]),(0,m.useEffect)(()=>()=>rC.release(N.current),[]),(0,m.useEffect)(()=>{if(!M||w!==N.current)return;let B=!1;return D(!1),Promise.all([Jc(()=>import("./runtime-IAg0vdY9.js"),__vite__mapDeps([0,1])),Jc(()=>import("./definition-DZvn-O-F.js"),__vite__mapDeps([2,3,1]))]).then(([E,z])=>{B||!v.current||(j.current=E.createCharacter(v.current,z.characterDefinition(x,i),{animation:z.animationId(a),trackingRegion:l?.current??b.current??void 0,followCursor:d,followRotation:u,trackingScope:c,displaySize:n,onError:r(()=>T(!0),"onError")}),D(!0))}).catch(()=>{B||T(!0)}),()=>{B=!0,j.current?.destroy(),j.current=null,D(!1)}},[M,w,l,c,n,d,u]),(0,m.useEffect)(()=>{j.current&&Jc(()=>import("./definition-DZvn-O-F.js").then(B=>{j.current?.setDefinition(B.characterDefinition(x,i)),j.current?.setAnimation(B.animationId(a))}),__vite__mapDeps([2,3,1]))},[x,i,a,A]),(0,t.jsxs)("span",{ref:b,role:p?"img":void 0,"aria-label":p,"aria-hidden":p?void 0:!0,className:W("relative inline-block shrink-0",AFe[n],h),children:[(0,t.jsx)(kr,{agent:e,appearance:x,size:n<256?256:n,name:f,pose:a,muted:i,className:W("size-full",A&&"invisible")}),(0,t.jsx)("span",{ref:v,className:"absolute inset-0"})]})}r(F_,"AgentCharacter");var _at=new Set(["claude_local","codex_local","opencode_local","grok_local"]);function OSe(e,{cloud:s,nativeRunnerEnabled:n}){return e==="paperclip_runner"?n:s?_at.has(e):!0}r(OSe,"isNewAgentAdapterAllowed");var Iat={claude_local:{src:"/brands/claude-color.svg"},codex_local:{src:"/brands/codex-color.svg"},gemini_local:{src:"/brands/adapters/gemini-color.svg"},kimi_local:{src:"/brands/adapters/kimi-color-light.svg",dark:"/brands/adapters/kimi-color.svg"},...Object.fromEntries([["cursor","cursor"],["cursor_cloud","cursor"],["grok_local","grok"],["hermes_local","hermesagent"],["hermes_gateway","hermesagent"],["pi_local","pi"]].map(([e,s])=>[e,{src:`/brands/adapters/${s}.svg`,dark:`/brands/adapters/${s}-dark.svg`}]))};function OW({type:e,className:s="size-6"}){const n=Ch(e).icon,a=Iat[e];return a?(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)("img",{src:a.src,className:W("shrink-0 object-contain",a.dark&&"dark:hidden",s),alt:""}),a.dark&&(0,t.jsx)("img",{src:a.dark,className:W("hidden shrink-0 object-contain dark:block",s),alt:""})]}):(0,t.jsx)(n,{className:s})}r(OW,"AdapterMark");function Aat(){const{selectedCompanyId:e}=ps(),{appearance:s}=$Se(`${e}:new-agent`);return(0,t.jsx)(F_,{appearance:s,state:"sleepy",muted:!0,size:256,className:"size-48",trackingScope:"page"})}r(Aat,"AgentBasicsCharacter");function FSe({open:e,onClose:s,onContinue:n,initialAdapter:a="",onInvite:i}){const o=(0,m.useId)(),l=!!$c(),c=Z({queryKey:P.instance.experimentalSettings,queryFn:Nr.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}=Z({queryKey:P.adapters.all,queryFn:uh.list,enabled:e}),k=(j??[]).filter(C=>C.loaded&&!C.disabled&&OSe(C.type,{cloud:l,nativeRunnerEnabled:c.data?.enableNativeRunner===!0})&&!["process","http"].includes(C.type)&&!Ch(C.type).comingSoon),S=k.some(C=>C.type===h);return(0,t.jsx)(Qs,{open:e,onOpenChange:r(C=>{C||s()},"onOpenChange"),children:(0,t.jsxs)(Js,{className:W("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:W(b==="name"&&"font-medium text-foreground"),children:"1. Name"}),(0,t.jsx)(Rn,{className:"size-3"}),(0,t.jsx)("span",{className:W(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,runnerProvider: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)(Aat,{}),(0,t.jsxs)("div",{className:"space-y-2",children:[(0,t.jsx)(Xs,{className:"text-3xl font-semibold tracking-tight",children:b==="name"?"Meet your next agent":"Choose an adapter"}),(0,t.jsx)(jn,{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)(ht,{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)(L,{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:W("grid grid-cols-2 gap-3",k.length!==4&&"sm:grid-cols-3"),children:k.map(C=>{const I=Ch(C.type);return(0,t.jsxs)("label",{className:"relative cursor-pointer",children:[(0,t.jsx)("input",{type:"radio",name:"new-agent-adapter",value:C.type,checked:h===C.type,onChange:r(()=>p(C.type),"onChange"),className:"peer sr-only"}),(0,t.jsxs)("span",{className:W("flex h-full flex-col items-center gap-2 rounded-lg border px-3 py-4 text-center peer-focus-visible:ring-2 peer-focus-visible:ring-ring hover:bg-accent/40",h===C.type?"border-foreground/40 bg-accent":"border-border bg-card"),children:[(0,t.jsx)(OW,{type:C.type}),(0,t.jsx)("span",{className:"text-sm font-medium",children:I.label}),h===C.type&&(0,t.jsx)(gs,{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)(L,{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)(Tl,{className:"size-4"}),"Back"]})}),(0,t.jsxs)(L,{type:"submit",disabled:!d.trim()||b==="adapter"&&!S,children:[b==="name"?"Choose adapter":"Configure agent",(0,t.jsx)(pl,{className:"size-4"})]})]})]})]})})}r(FSe,"AgentBasicsDialog");var Tat={subscription:"Subscription",api:"API"};function Rat({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)(rS,{initial:!1,mode:"sync",children:(0,t.jsx)(Il.span,{className:"absolute inset-0 flex items-center justify-center whitespace-nowrap",initial:{opacity:0,y:dte},animate:{opacity:1,y:0,transition:ZZe},exit:{opacity:0,y:dte,transition:eet},children:Tat[e]},e)})})}r(Rat,"CredentialTag");function Eat({source:e,mode:s,selected:n,onSelect:a,buttonRef:i,settling:o}){return(0,t.jsxs)("button",{ref:i,type:"button",role:"radio","aria-checked":n,onClick:a,className:W("flex min-w-0 flex-1 cursor-pointer flex-col items-center gap-1.5 self-stretch rounded-md border p-3","transition-(--tp-border-color-background-color) ease-(--motion-ease-standard)",o?"duration-(--motion-duration-slow)":"duration-(--motion-duration-fast)","outline-none focus-visible:ring-ring/50 focus-visible:ring-(length:--rad-3)",n?"border-foreground/40 bg-accent":"border-border bg-card hover:bg-accent/40"),children:[(0,t.jsx)("span",{className:"flex size-(--sz-30px) shrink-0 items-center justify-center",children:e.icon}),(0,t.jsx)("span",{className:"text-(length:--text-compact) font-medium text-foreground",children:e.label}),(0,t.jsx)(Rat,{mode:s})]})}r(Eat,"ModelSourceTile");function BSe({sources:e,mode:s,selectedId:n,onSelect:a,label:i,collapsed:o=!1,settling:l=!1}){const c=(0,m.useRef)(new Map),d=r(h=>{if(e.length===0)return;const p=e.findIndex(x=>x.id===n),f=e[((p===-1?h>0?-1:0:p)+h+e.length)%e.length];a(f.id),c.current.get(f.id)?.focus()},"moveSelection"),u=o?e.filter(h=>h.id===n):e;return(0,t.jsx)("div",{role:"radiogroup","aria-label":i,className:W("flex items-start gap-3",o&&"justify-center"),onKeyDown:r(h=>{o||(h.key==="ArrowRight"||h.key==="ArrowDown"?(h.preventDefault(),d(1)):(h.key==="ArrowLeft"||h.key==="ArrowUp")&&(h.preventDefault(),d(-1)))},"onKeyDown"),children:(0,t.jsx)(rS,{initial:!1,mode:"popLayout",children:u.map(h=>(0,t.jsx)(Il.div,{layout:!0,transition:BNe,exit:{opacity:0,transition:uet},className:W("flex min-w-0",o?"w-(--sz-source-tile-two-up)":"flex-1"),children:(0,t.jsx)(Eat,{source:h,mode:s,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(BSe,"ModelSourceTiles");var W$={subscription:"Use API key instead",api:"Use subscription instead"},Pat={subscription:"api",api:"subscription"};function zSe({mode:e,onChange:s}){return(0,t.jsxs)("button",{type:"button",onClick:r(()=>s(Pat[e]),"onClick"),className:W("group grid cursor-pointer px-3 py-2 text-left text-sm font-medium","rounded-md outline-none focus-visible:ring-ring/50 focus-visible:ring-(length:--rad-3)"),children:[Object.keys(W$).map(n=>(0,t.jsx)("span",{"aria-hidden":!0,className:"invisible col-start-1 row-start-1 whitespace-nowrap",children:W$[n]},n)),(0,t.jsx)(rS,{initial:!1,mode:"sync",children:(0,t.jsx)(Il.span,{className:W("col-start-1 row-start-1 justify-self-start whitespace-nowrap","underline decoration-muted-foreground/40 underline-offset-4","text-muted-foreground transition-colors","group-hover:text-foreground group-hover:decoration-foreground/40"),initial:{opacity:0},animate:{opacity:1,transition:SW},exit:{opacity:0,transition:tet},children:W$[e]},e)})]})}r(zSe,"CredentialModeLink");function qSe({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)(L,{variant:"ghost",size:"lg",className:"rounded-full has-[>svg]:pl-4 has-[>svg]:pr-5",onClick:e,disabled:a,children:[(0,t.jsx)(Tl,{className:"mr-1 size-3.5"}),"Back"]}):(0,t.jsx)("span",{}),(0,t.jsx)(Il.div,{layout:!0,transition:ret,className:"min-w-0",children:(0,t.jsx)(L,{size:"lg",className:"w-full rounded-full px-6",onClick:l,disabled:n||a,children:(0,t.jsxs)(Il.span,{className:"flex items-center whitespace-nowrap",initial:{opacity:0},animate:{opacity:1},transition:aet,children:[d==="spinner"?(0,t.jsx)(rt,{className:"mr-1 size-4 animate-spin"}):null,c,d==="arrow"?(0,t.jsx)(pl,{className:"ml-1 size-3.5"}):null]},`${c}:${d}`)})})]})}r(qSe,"FooterNav");function USe({companyId:e,adapterType:s,environmentId:n,canLogin:a,localEnvironment:i=!1,onConnected:o,onBack:l,testConnection:c,testError:d,managedAccount:u}){const h=Z({queryKey:P.health,queryFn:tu.get,enabled:i}),p=i&&(h.data?.localAiLoginSupported??h.data?.deploymentMode==="local_trusted"),f=(0,m.useRef)(0);(0,m.useEffect)(()=>()=>{f.current++},[]);const x=r(()=>{f.current++,D(!1),N(!1),k(null),C("preparing")},"cancel"),[b,v]=(0,m.useState)(u?.initialMethod==="api_key"?"api":u?"subscription":null),[j,N]=(0,m.useState)(!1),[w,k]=(0,m.useState)(null),[S,C]=(0,m.useState)("preparing"),I=(0,m.useRef)("ready"),[R,T]=(0,m.useState)(""),[A,D]=(0,m.useState)(!1),[M,B]=(0,m.useState)(null),[E,z]=(0,m.useState)(null),$=s==="claude_local"?"Claude":s==="grok_local"?"Grok":"OpenAI",q=s==="claude_local"?"ANTHROPIC_API_KEY":s==="grok_local"?"XAI_API_KEY":"OPENAI_API_KEY",U=s==="claude_local"?"anthropic":s==="grok_local"?"xai":"openai",O=gNe(e,q),K=u?{...O,options:[],subscriptions:[],loading:!1}:O,[H,ee]=(0,m.useState)(null),se=K.subscriptions.length?K.subscriptions.find(ge=>ge.id===(H??K.subscriptions[0]?.id)):void 0,[ne,fe]=(0,m.useState)(null),X=K.options.find(ge=>ge.id===(ne??K.options[0]?.id)),re=u?{...K.storedLogin,data:void 0,isPending:!1,isError:!1}:K.storedLogin,oe=(0,m.useRef)(null),G=b??(K.subscriptions.length>0||s==="claude_local"&&!se&&re.data?"subscription":K.options.length?"api":"subscription"),Y=G==="api"?"api_key":"subscription",Q=u?.intent.connectionId&&(u.fixedMethod!==!1||u.initialMethod===Y),te=u?{...u.intent,connectionId:Q?u.intent.connectionId:void 0,name:Q?u.intent.name:u.nameForMethod?.(Y)??u.intent.name}:void 0,ae=Dwe(e,te??{provider:U,method:"subscription",name:`My ${$} subscription`,ownership:"personal",agentIds:[],allAgents:!0},p&&G==="subscription"&&!se&&!re.data,{allowHostClaude:h.data?.deploymentMode==="local_trusted"}),le=Z({queryKey:P.agents.authSignal(e,s,n),queryFn:r(()=>$t.getAdapterAuthSignal(e,s,n??void 0),"queryFn"),retry:!1,enabled:!u});async function he(){if(A||u?.disabled)return;const ge=++f.current;D(!0),B(null);try{if(u&&te){if(G==="subscription"&&!p)return;const ue=oe.current??await(G==="api"?Yc.create(e,{...te,method:"api_key",apiKey:R.trim()}):ae.connect(te));oe.current=ue,T(""),ge===f.current&&u.onComplete({...ue,method:G==="api"?"api_key":"subscription"});return}let me=G==="api"?X?X.aiConnection?{env:{},aiConnection:X.aiConnection}:{env:{[q]:X.binding}}:E??{env:{},credentials:{[q]:R.trim()}}:{...se?.aiConnection?{aiConnection:se.aiConnection}:{},env:se?.binding?{CODEX_HOME:se.binding}:{},...s==="claude_local"&&!se&&re.data?{env:Vw(),applyStoredClaudeLogin:!0}:{}};if(G==="subscription"&&p&&!se&&!re.data&&(oe.current??=await ae.connect(),me={env:{},aiConnection:{provider:U,method:"subscription",mode:"responsible_user"}}),me.credentials&&(await Yc.create(e,{provider:U,method:"api_key",name:`My ${$} API`,ownership:"personal",apiKey:me.credentials[q],agentIds:[],allAgents:!0}),me={env:{},aiConnection:{provider:U,method:"api_key",mode:"responsible_user"}}),ge!==f.current)return;G==="api"&&(T(""),X||z(me));const ie=await c(me);if(ge!==f.current)return;ie?o(me):B("The provider did not respond. Check the connection and try again.")}catch(me){if(ge!==f.current)return;u&&T(""),B(me instanceof Error?me.message:"Could not connect to the provider.")}finally{ge===f.current&&D(!1)}}r(he,"connect");const ce=G==="subscription"&&a&&n&&!se&&!K.loading&&!re.data&&(!!u||le.data?.status!=="present"||H==="");return(0,t.jsxs)("div",{className:"min-w-0 max-w-full",children:[(0,t.jsx)(BSe,{label:"Connect your model provider",sources:[{id:s,label:$,icon:(0,t.jsx)(OW,{type:s})}],mode:G,selectedId:j?s:null,collapsed:j,onSelect:r(()=>{u?.disabled||N(!0)},"onSelect")}),(!j||u)&&!u?.fixedMethod&&(0,t.jsx)("div",{className:"-ml-3 mt-1",children:(0,t.jsx)(zSe,{mode:G,onChange:r(ge=>{x(),N(j),oe.current=null,v(ge),T(""),z(null),B(null)},"onChange")})}),!j&&K.options.length>0&&(0,t.jsxs)("p",{className:"mt-2 text-sm text-muted-foreground",children:[K.options.length," saved API"," ",K.options.length===1?"key available":"keys available","."]}),G==="subscription"&&K.subscriptions.length>0&&(0,t.jsx)(gk,{options:K.subscriptions,value:se?.id??"",onChange:ee,loading:!1,error:!1,kind:"subscription",disabled:A}),(0,t.jsx)(Il.div,{initial:!1,animate:{height:j?"auto":0,opacity:j?1:0},transition:{height:Id,opacity:t4},className:"overflow-hidden",children:j&&(0,t.jsx)("div",{className:"pt-5",children:G==="api"?(0,t.jsxs)(s4,{instruction:K.options.length?"Choose a saved API key or enter a new one":`Provide your ${$} API key to connect`,children:[(0,t.jsx)(gk,{...K,value:X?.id??"",disabled:A,onChange:r(ge=>{fe(ge),T(""),z(null),B(null)},"onChange")}),!X&&(0,t.jsx)(n4,{label:"API key",masked:!0,autoFocus:!0,value:R,placeholder:E?"Key entered. Retry the connection.":"Enter API key here",onChange:r(ge=>{fe(""),T(ge),z(null)},"onChange"),onSubmit:r(()=>{he()},"onSubmit"),disabled:A})]}):ce?(0,t.jsx)(LW,{companyId:e,adapterType:s,environmentId:n,chrome:"onboarding",aiConnection:te??{provider:U,method:"subscription",name:`My ${$} subscription`,ownership:"personal",agentIds:[],allAgents:!0},autoStart:!0,onStored:r(()=>{},"onStored"),onPromptReady:r(ge=>{k(ge),C(me=>ge?me==="preparing"?"ready":me:"preparing")},"onPromptReady"),onCodeSubmitted:r(()=>{I.current=S==="waiting"?"waiting":"ready",C("connecting")},"onCodeSubmitted"),onSubmitFailed:r(()=>{C(ge=>ge==="connecting"?I.current:ge)},"onSubmitFailed"),onConnected:r(ge=>{if(u){if(!ge){B("The login did not return a saved connection. Try again.");return}const ie=f.current;C("connecting"),Yc.loginResult(e,ge).then(ue=>{ie===f.current&&u.onComplete({...ue,method:"subscription"})}).catch(()=>{ie===f.current&&(C("ready"),B("Could not retrieve the saved connection. Go back and retry."))});return}const me={env:{},aiConnection:{provider:U,method:"subscription",mode:"responsible_user"}};z(me),o(me)},"onConnected")}):se?null:p&&!re.data?(0,t.jsx)(CW,{adapterType:s,login:{...ae,retry:r(()=>{B(null),ae.retry()},"retry")}}):(0,t.jsx)("p",{className:"text-sm text-muted-foreground",children:re.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."})})}),G==="subscription"&&re.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:d??M}),i&&h.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)(qSe,{onBack:r(()=>{j?x():l()},"onBack"),primaryLabel:j&&ce?S==="waiting"?"Waiting for code":S==="connecting"?"Connecting":`Sign in to ${$}`:A?"Connecting":G==="subscription"&&(re.data||se)?"Use saved subscription":G==="api"&&X?"Use saved API key":"Connect",primaryDisabled:u?.disabled||!!u&&G==="subscription"&&!a&&!p||i&&h.isPending||ae.preparing||!!ae.error||!u&&le.isPending||K.loading||s==="claude_local"&&re.isPending||!j&&!(G==="subscription"&&se)||!!ce&&(!w||S!=="ready")||G==="api"&&!R.trim()&&!E&&!X,loading:A,primaryIcon:j&&ce?S==="ready"?"none":"spinner":void 0,onPrimary:r(()=>{if(ce){if(!w||S!=="ready")return;window.open(w,"_blank","noreferrer,noopener"),C("waiting")}else he()},"onPrimary")})]})}r(USe,"AgentProviderConnection");function P5(e){return e.provider==="openrouter"?(0,t.jsx)(Dat,{...e}):(0,t.jsx)(Mat,{...e})}r(P5,"AiConnectionCredentialStep");function Mat({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}){const[b,v]=(0,m.useState)(o),[j,N]=(0,m.useState)(),w=Dt(),k=Z({queryKey:P.environments.list(e),queryFn:r(()=>Pi.list(e),"queryFn")}),S=Z({queryKey:P.environments.capabilities(e),queryFn:r(()=>Pi.capabilities(e),"queryFn")}),C=Z({queryKey:P.instance.settings,queryFn:Nr.get}),I=Z({queryKey:P.instance.experimentalSettings,queryFn:Nr.getExperimental}),R=Z({queryKey:P.instance.generalSettings,queryFn:Nr.getGeneral}),T=DW(R.data?.executionMode,k.data??[]);let A=null,D;try{A=T.forced?T.kubernetesEnvironment?.id??null:iN({agentDefaultEnvironmentId:p??j,instanceDefaultEnvironmentId:C.data?.defaultEnvironmentId,localDefaultEnvironmentId:lN(k.data),managedSandboxOnly:I.data?.enableManagedSandboxOnly,managedSandboxEnvironmentId:oN(k.data),visibleEnvironmentIds:k.data?.map(O=>O.id)})}catch(O){D=O instanceof Error?O.message:"Could not resolve the sign-in environment."}const M=(k.data??[]).filter(O=>O.status==="active"&&(O.driver==="local"||O.driver==="sandbox"&&typeof O.config.provider=="string"&&S.data?.sandboxProviders?.[O.config.provider]?.supportsLoginPty===!0));!T.forced&&!p&&!j&&!M.some(O=>O.id===A)&&(A=M[0]?.id??null);const B=k.data?.find(O=>O.id===A),E=typeof B?.config.provider=="string"?B.config.provider:"",z=B?.driver==="sandbox"&&S.data?.sandboxProviders?.[E]?.supportsLoginPty===!0,$=[k,S,C,I,R].some(O=>O.isPending),q=D??[k,S,C,I,R].find(O=>O.error)?.error?.message,U={provider:s,method:"subscription",name:b,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)(ht,{value:b,onChange:r(O=>v(O.target.value),"onChange"),disabled:!!i})]}),!p&&!T.forced&&M.length>1&&(0,t.jsxs)($a,{value:A??"",onValueChange:N,children:[(0,t.jsx)(La,{"aria-label":"Sign-in environment",children:(0,t.jsx)(Ma,{placeholder:"Sign-in environment"})}),(0,t.jsx)(Da,{children:M.map(O=>(0,t.jsx)(Nn,{value:O.id,children:O.name},O.id))})]}),q&&(0,t.jsx)("p",{role:"alert",className:"text-sm text-destructive",children:q}),$?(0,t.jsx)("p",{role:"status",className:"text-sm text-muted-foreground",children:"Preparing sign-in…"}):(0,t.jsx)(USe,{companyId:e,adapterType:s==="anthropic"?"claude_local":s==="xai"?"grok_local":"codex_local",environmentId:A,canLogin:z,localEnvironment:B?.driver==="local",onBack:x,onConnected:r(()=>{},"onConnected"),testConnection:r(async()=>!1,"testConnection"),managedAccount:{intent:U,nameForMethod:c,initialMethod:n,fixedMethod:a??!!i,disabled:$||!!q||!b.trim(),onComplete:r(O=>{w.invalidateQueries({queryKey:["ai-connections",e]}),f(O)},"onComplete")}},A??"local")]})}r(Mat,"SubscriptionConnectionStep");function Dat({companyId:e,provider:s,connectionId:n,name:a,hideName:i,nameForMethod:o,ownership:l,agentIds:c,allAgents:d,onComplete:u,onCancel:h}){const[p,f]=(0,m.useState)(a),[x,b]=(0,m.useState)(""),v=Dt(),j=je({mutationFn:r(()=>Yc.create(e,{provider:s,method:"api_key",name:n?p:o?.("api_key")??p,ownership:l,agentIds:c,allAgents:d,connectionId:n,apiKey:x}),"mutationFn"),onSuccess:r(N=>{v.invalidateQueries({queryKey:["ai-connections",e]}),u({...N,method:"api_key"})},"onSuccess"),onSettled:r(()=>b(""),"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)(ht,{value:p,onChange:r(N=>f(N.target.value),"onChange"),disabled:!!n})]}),j.error&&(0,t.jsx)("p",{role:"alert",className:"text-sm text-destructive",children:j.error.message}),(0,t.jsx)(KNe,{providerName:"OpenRouter",value:x,onChange:b,onSubmit:r(()=>j.mutate(),"onSubmit"),disabled:j.isPending,placeholder:"Enter API key here",autoFocus:!0}),(0,t.jsxs)("div",{className:"flex justify-between gap-2",children:[(0,t.jsx)(L,{variant:"ghost",onClick:h,children:"Cancel"}),(0,t.jsx)(L,{disabled:!p.trim()||!x.trim()||j.isPending,onClick:r(()=>j.mutate(),"onClick"),children:j.isPending?"Connecting…":"Connect"})]})]})}r(Dat,"ApiKeyConnectionStep");var Lat=null;function iS(){const e=(0,m.useContext)(SI),{data:s,isFetched:n,isError:a}=Z({queryKey:P.instance.experimentalSettings,queryFn:r(()=>Nr.getExperimental(),"queryFn"),enabled:e!=null},e??(Lat??=new zN));return e?{enabled:!a&&s?.enableChatConnectors===!0,loaded:n}:{enabled:!1,loaded:!0}}r(iS,"useChatConnectorsEnabled");var $at=new RegExp(`\\b(${["mcp","server","profile","policy","gateway","transport","stdio","endpoint"].join("|")})s?\\b`,"gi");function KSe(e){return e.replace($at,"").replace(/\s{2,}/g," ").replace(/\s+([.,])/g,"$1").trim()}r(KSe,"sanitizeProsumerCopy");var Oat={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."},neon:{tagline:"Manage Postgres projects, branches, and queries.",short:"Sign in with Neon. Project pinning and read-only mode are optional."},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."}},Fat={tagline:"Give your agents access to this app.",short:"Give your agents access to this app."};function WSe(e,s){const n=Oat[e];if(n)return n;if(s){const a=KSe(s);if(a)return{tagline:a,short:a}}return Fat}r(WSe,"appCopyFor");function Qte(e,s,n){return n<=1?`Your ${e} key`:KSe(s)||`Your ${e} key`}r(Qte,"credentialFieldLabel");var Bat=1500;function Cp(e=Bat){const[s,n]=(0,m.useState)("idle"),a=(0,m.useRef)(null),i=(0,m.useRef)(0);(0,m.useEffect)(()=>()=>{a.current!==null&&window.clearTimeout(a.current)},[]);const o=(0,m.useCallback)(async l=>{const c=++i.current;let d="copied";try{await fa(l)}catch{d="failed"}return i.current!==c||(n(d),a.current!==null&&window.clearTimeout(a.current),a.current=window.setTimeout(()=>{i.current===c&&(n("idle"),a.current=null)},e)),d},[e]);return{status:s,copied:s==="copied",failed:s==="failed",copy:o}}r(Cp,"useCopyAction");function FW(){const e=Xc()?.pushToast;return(0,m.useCallback)(async(s,n="Copied")=>{try{return await fa(s),e?.({title:n,tone:"success",dedupeKey:`copy:${n}`}),!0}catch{return e?.({title:"Couldn’t copy to clipboard",body:"Select and copy the value manually.",tone:"error",dedupeKey:"copy-failed"}),!1}},[e])}r(FW,"useCopyToast");var zat="/cloud/connections/handoff",qat="/cloud/connections/reauth",M5="paperclip.cloud-oauth-handoff.v1",sg=class extends Error{static{r(this,"OAuthHandoffError")}code;constructor(e,s){super(e),this.code=s,this.name="OAuthHandoffError"}};function BW(e){if(e===void 0)return null;if(!e||typeof e!="object"||Array.isArray(e))throw new sg("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 sg("Paperclip Cloud returned an invalid sign-in handoff.","invalid_handoff");return{kind:"paperclip_cloud",session:s.session}}r(BW,"parseHandoff");function Uat(e,s){return e===404||s==="SESSION_NOT_AVAILABLE"?new sg("This sign-in expired. Start the connection again.","expired"):e===401||e===403?new sg("Paperclip Cloud could not authorize this connection for your account.","forbidden"):new sg("Paperclip Cloud couldn’t prepare secure sign-in. Try again.","unavailable")}r(Uat,"handoffFailure");async function Kat(e,s){const n=s.request??fetch;let a,i;for(let o=0;o<2;o+=1)try{if(a=await n(zat,{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 sg(i instanceof Error?i.message:"Paperclip Cloud couldn’t prepare secure sign-in. Try again.","unavailable")}r(Kat,"postCloudHandoff");function Wat(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!==qat||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(Wat,"exactReauthenticationTarget");async function dN(e,s={}){const n=BW(e.handoff);if(!n){const l=o5(e.authorizationUrl);if(!l.ok)throw new sg(l.message,"invalid_handoff");return{kind:"authorization",url:l.url,host:l.host}}const a=await Kat(n.session,s),i=await a.json().catch(()=>null);if(!a.ok){if(i?.error==="RECENT_LOGIN_REQUIRED"){const l=Wat(i.reauthenticationUrl,n.session);if(l)return l}throw Uat(a.status,i?.error)}const o=o5(typeof i?.authorizationUrl=="string"?i.authorizationUrl:void 0);if(!o.ok)throw new sg("Paperclip Cloud returned an invalid provider sign-in address.","invalid_handoff");return{kind:"authorization",url:o.url,host:o.host}}r(dN,"prepareOAuthNavigation");function B_(e,s=window.sessionStorage){const n=BW({kind:"paperclip_cloud",session:e});if(!n)throw new sg("Paperclip Cloud returned an invalid sign-in handoff.","invalid_handoff");const a={version:1,session:n.session,savedAt:Date.now()};s.setItem(M5,JSON.stringify(a))}r(B_,"savePendingCloudHandoff");function Vat(e=window.sessionStorage){const s=e.getItem(M5);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 BW({kind:"paperclip_cloud",session:n.session})}catch{return e.removeItem(M5),null}}r(Vat,"readPendingCloudHandoff");function Yte(e=window.sessionStorage){e.removeItem(M5)}r(Yte,"clearPendingCloudHandoff");function l4(e){return!!(e&&Mpe({...e,methods:e.methods.filter(s=>(s.purpose??"tool")!=="channel"&&s.transport!=="chat_sdk")}))}r(l4,"appSupportsToolCatalogSetup");var Hat=xLe.filter(e=>Rpe(e).some(s=>rp(s))).map(e=>e.slug);function Gat(e){return Hat.some(s=>s===e)}r(Gat,"isMcpDirectOAuthConnectSlug");function z_(e,s){const n=new URLSearchParams({source:e});return s&&n.set("intent",s),`/apps/connect?${n.toString()}`}r(z_,"appSourceConnectHref");function Qat(e,s){return`/apps/connect?${new URLSearchParams({source:e,resume:s}).toString()}`}r(Qat,"appSourceResumeHref");function V$(e){return e?`/apps/vercel-connect?${new URLSearchParams({source:e}).toString()}`:"/apps/vercel-connect"}r(V$,"vercelConnectSourceHref");function Yat(e){return e.serviceSlug??e.appKey??e.sourceSlug??void 0}r(Yat,"resolveAppsConnectRouteKey");function Jat(e,{chatConnectorsEnabled:s=!1}={}){if(e.get("byo")==="1")return!!(e.get("reconnect")?.trim()&&e.get("applicationId")?.trim()&&e.get("link")?.trim());const n=e.get("source")??"";if(/^ai-router-(?:[a-f0-9]{2})+$/.test(n))return!0;const a=TN(n);return!s&&a?.methods.some(i=>i.transport==="chat_sdk")&&!a.methods.some(i=>(i.purpose??"tool")!=="channel"&&i.transport!=="chat_sdk")?!1:NI(n)&&e.get("reconnect")?.trim()?!0:n==="agentmail"||s?Mpe(a):l4(a)}r(Jat,"canEnterAppsConnect");var H$=" for the organization",Xat=" for the company";function Jte(e,s){const n=e.trim();if(s!=="organization")return n;const a=n.toLocaleLowerCase();return a.endsWith(H$)?n:a.endsWith(Xat)?`${n.slice(0,n.length-16).trimEnd()}${H$}`:`${n}${H$}`}r(Jte,"connectionNameForGrantKind");function Zat(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(Zat,"grantStatusLabel");function eit(e){switch(e){case"active":return"connected";case"needs_reauthorization":case"expired":return"attention";case"revoked":return"inactive";default:return"missing"}}r(eit,"grantStatusTone");function tit(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(tit,"grantAccountLabel");function sit(e){return new Set((e?.members??[]).filter(s=>s.subjectType==="user").map(s=>s.subjectId))}r(sit,"audienceUserIds");function nit(e){return e.find(s=>s.kind==="organization"&&s.isDefault)??e.find(s=>s.kind==="organization")??null}r(nit,"organizationGrant");function rit(e,s){return s?e.find(n=>n.kind==="user"&&n.subjectUserId===s)??null:null}r(rit,"personalGrantFor");function ait(e,s){if(!s)return null;const n=e.find(a=>a.userId===s);return n&&(n.name?.trim()||n.email?.trim())||null}r(ait,"memberLabel");var Xte=0;function i6(){return Xte+=1,{id:`header-${Xte}`,name:"",value:""}}r(i6,"newCustomHeaderRow");function M1(e){try{return new URL(e).host||null}catch{return null}}r(M1,"endpointHost");function VSe(e=window.location.origin){const s=new URL("/api/tools/oauth/callback",e),n=s.hostname.toLowerCase().replace(/^\[|\]$/g,"");return s.protocol==="http:"&&(n==="127.0.0.1"||n==="::1")&&(s.hostname="localhost"),s.toString()}r(VSe,"oauthCallbackUrlForBrowser");function G$(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(G$,"defaultGenericMcpName");function Zte(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(Zte,"genericConnectGuidance");function HSe(e){const s=new Set;for(const n of e){const a=n.name.trim();if(!a&&!n.value.trim())continue;const i=FLe(a);if(!i.ok)return EJ(a,i.reason);const o=KLe(n.value);if(!o.ok)return EJ(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(HSe,"customHeaderError");function iit(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(iit,"genericConnectPayload");function oit(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&&HSe(e.headers)===null:!0:!1}r(oit,"canSubmitGenericConnect");function uN(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(uN,"installStateFrom");function GSe(e,s){return e.onAll||e.agentIds.has(s)}r(GSe,"isAgentInstalled");function QSe(e,s){return s.onAll?[{targetType:"company",targetId:e}]:[...s.agentIds].map(n=>({targetType:"agent",targetId:n}))}r(QSe,"installPayload");var lit="Has access — tick to load its tools into this agent's context.";function YSe(e){return`paperclip.connector-enrollment-access:${e}`}r(YSe,"enrollmentAccessStorageKey");function cit(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(cit,"validEnrollmentAccessState");function dit(e,s,n){try{window.sessionStorage.setItem(YSe(s),JSON.stringify({...n,companyId:e}))}catch{}}r(dit,"saveEnrollmentAccessState");function uit(e){const s=YSe(e);try{const n=window.sessionStorage.getItem(s);if(window.sessionStorage.removeItem(s),!n)return null;const a=JSON.parse(n);return cit(a)?a:null}catch{return null}}r(uit,"consumeEnrollmentAccessState");function ese(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(ese,"githubRecoveryUrl");function tse(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(tse,"oauthCallbackErrorMessage");var mit={key:"setup",success:"complete"};function sse(e){return e.requestedAppKey||e.hasPrefilledLink||e.zapierSource?"key":"gallery"}r(sse,"requestedConnectionInitialStep");function hit(e){const s=e.galleryApps.find(a=>a.slug===e.requestedAppKey);if(s)return s;if(!e.reconnectConnection)return null;const n=e.applications.find(a=>a.id===e.reconnectConnection?.applicationId);return fg(n)!==e.requestedAppKey?null:NI(e.requestedAppKey)}r(hit,"requestedConnectionEntry");function pit(e){return!e.reconnectConnection||!e.reconnectApplication||e.reconnectConnection.applicationId!==e.reconnectApplication.id?!1:e.requestedAppKey?fg(e.reconnectApplication)===e.requestedAppKey:e.byo&&e.applicationId===e.reconnectApplication.id}r(pit,"retainedReconnectMatches");function fit(e){return e.credentialSource==="vercel_connect"&&!e.available&&!e.retainedReconnectMatches}r(fit,"isVercelConnectUnavailable");function xit(e){return e.available===!1&&!(e.reconnectConnectionId&&e.reconnectSourceMatches)}r(xit,"isConnectionDefinitionUnavailable");function git(e){return!e.hasRequestedEntry||e.supportedMethodCount===0||e.unsupportedOAuth||e.vercelUnavailable||e.definitionUnavailable?e.reconnectConnectionId?"reconnect_unavailable":"fallback":"ready"}r(git,"requestedConnectionSetupResolution");function nse(e,s,n,a){const i=mit[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(nse,"appConnectHref");function H2(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(H2,"withConnectionIntent");var rse=["Pick app","Add your key"],ase={gallery:0,key:1},bit={key:0},vit=["Add MCP URL"],yit=["Sign in"];function Q$(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(Q$,"defaultGrantKindFor");function jit(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(jit,"configuredAgentIdentity");function GC(e,s){const n=typeof s=="string"?s:s?.key;return e?.slug==="google-sheets"&&n==="local"}r(GC,"isGoogleSheetsRobotMethod");function aC(e){return e?Object.fromEntries([...e.tenantFields??[],...e.extensionFields??[]].filter(s=>s.defaultValue!==void 0).map(s=>[s.key,s.defaultValue])):{}}r(aC,"defaultMethodConfig");function Aw(e,s){if(!e)return[];const n=hA(e);return s==="vercel_connect"?n.filter(a=>!!a.credentialSources?.vercelConnect):n}r(Aw,"connectionMethodsForCredentialSource");function hA(e){return Rpe(e).filter(s=>(s.purpose??"tool")!=="channel")}r(hA,"availableToolConnectionMethods");function G2(e,s){const n=hA(e);return s?n.find(a=>a.key===s)??null:s7(n)}r(G2,"availableToolConnectionMethod");function vk(e){return s7(e)}r(vk,"recommendedSetupConnectionMethod");function ise(e){return vk(e?e.methods.filter(s=>(s.purpose??"tool")==="tool"&&(s.oauthStrategy==="paperclip_cloud_connector"||s.oauthStrategy==="paperclip_id_connector")):[])}r(ise,"recommendedManagedConnectorMethod");function ose(e){if(!e)return!1;const s=hA(e),n=s.length===1?s[0]:null;return!!(n&&rp(n)&&!y$e(n))}r(ose,"canUseAutomaticOAuthFastPath");function lse(e){if(!e)return null;const s=hA(e),n=s.length===1?s[0]:null;return n&&rp(n)?n:null}r(lse,"automaticOAuthMethod");function wit(e){const s=e.metadata;if(!s)return null;const n=s.sourceTemplateKey??s.galleryKey;return typeof n=="string"?n:null}r(wit,"appSourceSlug");function kit(e){const s=e.config?.sourceTemplateKey??e.transportConfig.sourceTemplateKey;return typeof s=="string"?s:null}r(kit,"connectionSourceSlug");function cse(e,s,n,a={}){if(!e)return null;const i=new Set(s.filter(o=>o.status!=="archived"&&wit(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)||kit(o)===e;return o.status!=="archived"&&(!a.draftOnly||o.status==="draft")&&o.authKind==="oauth"&&l})??null}r(cse,"reusableOAuthConnection");function JSe(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(JSe,"readConnectionIntentOAuthOutcome");function c4(e={}){const[s]=fi(),n=va(),{selectedCompanyId:a}=ps(),i=q9(),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&&y1(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||y1(l)||z3(l))),h=Z({queryKey:["tools","connection",d],queryFn:r(()=>Zt.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)(L,{variant:"outline",onClick:r(()=>{h.refetch()},"onClick"),children:"Try again"})]});if(z3(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"&&y1(p)&&(!f||HR(p,f))){const x=Kpe(p,s.get("targetToolkit"));return(0,t.jsx)(XHe,{...e,upstreamServiceName:e.upstreamServiceName??x?.name,interactionId:o,providerId:p,connection:h.data},`${o||"page"}:${p}`)}return(0,t.jsx)(Nit,{...e})}r(c4,"ConnectionSetupFlow");function Nit({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,onPhaseChange:j,onCancel:N,renderCredentialStep:w}={}){const k=Dt(),S=Mn(),C=(0,m.useCallback)((bt,_e)=>{o==="page"&&(_e?S(bt,_e):S(bt))},[o,S]),I=va(),{selectedCompany:R,selectedCompanyId:T}=ps(),{enabled:A}=iS(),{enabled:D}=q9(),{setBreadcrumbs:M}=Bn(),{pushToast:B}=xi(),[E]=fi(),z=d?.trim()||E.get("intent")?.trim()||null,$=I.appKey??E.get("appKey")??void 0,q=E.get("source")?.trim()||null,U=u||E.get("new")==="1",O=E.get("stage")?.trim()||null,K=E.get("method")?.trim()||null,H=E.get("resume")?.trim()||null,ee=E.get("oauth"),se=E.get("code"),ne=ese(E.get("installation_url")),fe=ese(E.get("management_url")),X=p?.id??(E.get("reconnect")?.trim()||null),re=E.get("identity")==="user"?"user":E.get("identity")==="organization"?"organization":null,oe=i==="vercel_connect",G=l??q,Y=i==="paperclip_vault"&&Gat(G)?G:null,Q=Yat({serviceSlug:l,appKey:$,sourceSlug:q}),te=(l??q??$)==="zapier",ae=te?void 0:Q,le=!!p||o==="page"&&(a||E.get("byo")==="1"),[he]=(0,m.useState)(()=>o==="page"&&E.get("cloud_connector")==="enrolled"&&ae?uit(ae):null),[ce]=(0,m.useState)(()=>{const bt=E.get("link")?.trim()??"";return{link:/^https?:\/\//i.test(bt)?bt:"",name:p?.name??E.get("name")?.trim()??"",applicationId:p?.applicationId??(E.get("applicationId")?.trim()||void 0)}}),[ge,me]=(0,m.useState)(()=>sse({requestedAppKey:ae,routeStage:O,resumeConnectionId:H,hasPrefilledLink:!!ce.link,zapierSource:te})),[ie,ue]=(0,m.useState)(null),[ke,be]=(0,m.useState)(""),[Ie,Ue]=(0,m.useState)(ce.link),[at,dt]=(0,m.useState)(ce.name||(te?"Zapier":"")),[de,Be]=(0,m.useState)(!1),[pt,vt]=(0,m.useState)(""),[Le,Qe]=(0,m.useState)("auto"),[ut,Ye]=(0,m.useState)(()=>[i6()]),[it,kt]=(0,m.useState)(""),[tt,Pe]=(0,m.useState)(""),[Ce,He]=(0,m.useState)(!1),[Je,lt]=(0,m.useState)(null),[Ee,Xe]=(0,m.useState)(!1),[Ae,De]=(0,m.useState)({}),[_t,ye]=(0,m.useState)(""),[gt,We]=(0,m.useState)(""),[Ot,zt]=(0,m.useState)(""),[Cs,ze]=(0,m.useState)(v&&v.mode!=="responsible_user"?`ai-${v.method}`:""),[ft,Ut]=(0,m.useState)(null),[Ns,Is]=(0,m.useState)({}),[St,ds]=(0,m.useState)(""),[$e,xe]=(0,m.useState)(null),[Qt,Mt]=(0,m.useState)(null),[rs,ws]=(0,m.useState)({}),[Bs,er]=(0,m.useState)("all"),[Fe,st]=(0,m.useState)(new Set),[xt,Oe]=(0,m.useState)(()=>new Set(he?.agentIds??(c?[c]:[]))),[Bt,wt]=(0,m.useState)(he?.grantKind??re??(c?"user":"organization")),[Xt,Yt]=(0,m.useState)(he?.installChoice??(c?"specific":"all")),hs=!!(H&&(ee==="failed"||ee==="denied")),[Ts,as]=(0,m.useState)(hs?"error":"entry"),[Zn,en]=(0,m.useState)(()=>hs?tse(ee,se):null),[nr,tn]=(0,m.useState)(null),xn=(0,m.useRef)(!1),Ht=(0,m.useRef)(!1),qs=(0,m.useRef)(null),Vs=(0,m.useRef)(null),[Lt,is]=(0,m.useState)(null),Ms=(0,m.useRef)(null),[bs,gn]=(0,m.useState)(null),[Pn,$r]=(0,m.useState)(null),mt=(0,m.useRef)(null),[vs,Fs]=(0,m.useState)(h.length>0&&!!f),[Hs,zs]=(0,m.useState)(null),[Us,ur]=(0,m.useState)(null),[Dn,Er]=(0,m.useState)(null),Jn=(0,m.useCallback)(()=>{o!=="dialog"||Ms.current?.closed===!1||(Ms.current=window.open("about:blank","paperclip-connection-oauth","popup,width=720,height=760,resizable=yes,scrollbars=yes"))},[o]),tr=(0,m.useCallback)(bt=>{if(o!=="dialog"){Lm(bt);return}$r(bt);const _e=Ms.current;if(!_e||_e.closed){as("error"),en("Paperclip couldn’t open the sign-in window. Open sign-in in a new tab to continue."),j?.("needs_retry");return}_e.location.assign(bt),_e.focus()},[o,j]),pn=(0,m.useCallback)(()=>{Ms.current=null,en(null),as("redirecting"),j?.("authorizing")},[j]);(0,m.useEffect)(()=>{if(o!=="dialog"||Ts!=="redirecting")return;const bt=window.setInterval(()=>{Ms.current?.closed&&(as("error"),en("The sign-in window closed. If authorization did not finish, try again."),$r(null),j?.("needs_retry"))},1e3);return()=>window.clearInterval(bt)},[o,Ts,j]);const yt=(0,m.useCallback)(async bt=>{mt.current?.abort();const _e=new AbortController;mt.current=_e;try{const ot=await dN(bt,{signal:_e.signal});if(ot.kind==="reauthentication"){const Nt=o==="dialog"?Ms.current:window;if(!Nt||Nt.closed||!bt.handoff)throw new Error("Paperclip couldn’t preserve this sign-in while refreshing your account.");B_(bt.handoff.session,Nt.sessionStorage),as("starting")}else tn(ot.host),as("redirecting");tr(ot.url)}catch(ot){if(_e.signal.aborted)return;as("error"),en(ot instanceof Error?ot.message:"Paperclip couldn’t start secure sign-in. Try again."),j?.("needs_retry")}finally{mt.current===_e&&(mt.current=null)}},[o,j,tr]);(0,m.useEffect)(()=>()=>mt.current?.abort(),[]),(0,m.useEffect)(()=>{if(o!=="dialog"||!z)return;const bt=r(_e=>{const ot=JSe(_e,window.location.origin,z);if(ot==="connected"){as("entry"),$r(null),x?.({resolvedByCallback:!0});return}if(ot==="declined"){as("error"),en("Authorization was cancelled. You can try again."),j?.("needs_retry");return}ot==="failed"&&(as("error"),en("Authorization did not complete. Try again when you’re ready."))},"receiveOAuthOutcome");return window.addEventListener("message",bt),()=>window.removeEventListener("message",bt)},[z,o,x,b]),(0,m.useEffect)(()=>{if(o!=="dialog"||z||!bs)return;let bt=!1,_e=!1;const ot=window.setInterval(async()=>{if(_e||bt)return;const Nt=Ms.current;if(!Nt||Nt.closed){gn(null),as("error"),en("The sign-in window closed. Try again to finish connecting GitHub.");return}let us;try{us=new URL(Nt.location.href)}catch{return}if(!(us.origin!==window.location.origin||!us.pathname.includes(bs))){if(us.searchParams.has("oauth")){gn(null),as("error"),en("Authorization did not complete. Finish setup in the sign-in window or try again.");return}if(us.searchParams.get("success")==="1"){_e=!0;try{const Ls=await Zt.getConnection(bs);!bt&&Ls.status==="active"&&(gn(null),Nt.close(),x?.({connectionId:Ls.id}))}catch{bt||(gn(null),as("error"),en("Could not confirm the connection. Try again."))}finally{_e=!1}}}},1e3);return()=>{bt=!0,window.clearInterval(ot)}},[z,bs,o,x]);const Ps=r(()=>{Qe("auto"),Ye([i6()]),kt(""),Pe(""),He(!1),lt(null),Xe(!1)},"resetGenericAuthState"),Zs=r(bt=>{if(o==="page"&&!z&&i==="paperclip_vault"&&y1(bt.slug)){C(`/apps/connect?source=${bt.slug}`);return}if(bt.slug==="zapier"){ue(null),be(""),Ue(""),dt("Zapier"),Be(!1),vt(""),Ps(),De({}),Mt(null),me("key"),C(H2("/apps/connect?source=zapier",z));return}if(i==="paperclip_vault"&&ose(bt)){C(z_(bt.slug,z));return}ue(bt),be(bt.name),Ue(""),dt(""),Be(!1),vt(""),Ps(),De({}),ye(""),We(""),zt("");const _e=vk(Aw(bt,i));ze(_e?.key??""),Is(aC(_e)),ds(""),xe(null),Mt(null),Oe(new Set(c?[c]:[])),Yt(c?"specific":"all"),wt(Br??Q$(_e,!!c)),me("key"),C(i==="vercel_connect"?H2(V$(bt.slug),z):z_(bt.slug,z))},"useMatchedGalleryEntry"),Ze=r(()=>{me("gallery"),C(H2(i==="vercel_connect"?V$():a?"/apps/byo":"/apps",z))},"backToGallery");(0,m.useEffect)(()=>{if(o==="page")return M([{label:"Connectors",href:"/apps"},{label:oe?"Vercel Connect":a?"Connect your own tool":"Connect an app"}]),()=>M([])},[a,o,M,oe]);const At=Z({queryKey:P.apps.gallery(T??"__none__"),queryFn:r(()=>Zt.listGallery(T),"queryFn"),select:(0,m.useCallback)(bt=>z?{...bt,apps:bt.apps.map(_e=>({..._e,methods:_e.methods.filter(ot=>v?ot.ai?.provider===v.provider&&(v.mode==="responsible_user"||ot.ai.method===v.method):ot.transport!=="runtime_auth")})).filter(_e=>_e.methods.length>0)}:bt,[z,v?.provider,v?.method,v?.mode]),enabled:!!T}),fs=(0,m.useMemo)(()=>(At.data?.apps??[]).filter(bt=>D||!z3(bt.slug)).filter(bt=>bt.slug==="agentmail"||A||!bt.methods.some(_e=>_e.transport==="chat_sdk")||l4(bt)),[At.data,A,D]),Ks=ae?NI(ae):null,Ln=Ks?.methods.find(bt=>nk(bt)&&!rp(bt)),Cr=!(Ln&&Cs===Ln.key)&&!!Ks?.methods.some(bt=>bt.oauthStrategy==="paperclip_cloud_connector"||bt.oauthStrategy==="paperclip_id_connector"),Vr=!!ie?.methods.some(bt=>bt.oauthStrategy==="paperclip_cloud_connector"||bt.oauthStrategy==="paperclip_id_connector"),Pr=ie&&Cr&&!Vr?ise(Ks):null,[Ar,_r]=(0,m.useState)(null),yr=Z({queryKey:["cloud-connector","enrollment"],queryFn:r(()=>Zt.getCloudConnectorEnrollment(),"queryFn"),refetchInterval:Ar?2e3:!1,enabled:!!(T&&Cr&&!Vr)}),[sr,Ga]=(0,m.useState)(null),ka=(0,m.useCallback)(()=>{Ms.current?.close(),Ms.current=null,_r(null)},[]),Ds=(0,m.useCallback)(()=>{!T||!ae||dit(T,ae,{grantKind:Bt,installChoice:Xt,agentIds:Xt==="specific"?[...xt]:[]})},[Bt,xt,Xt,ae,T]),$n=(0,m.useCallback)(bt=>{const _e=o5(bt);if(!_e.ok){ka(),Ga(_e.message);return}if(o==="dialog"){_r(_e.url);const ot=Ms.current;ot&&!ot.closed?(ot.location.assign(_e.url),ot.focus()):Ga("Open authorization in a new tab to continue.");return}Lm(_e.url)},[o,ka]);(0,m.useEffect)(()=>{!Ar||yr.data?.status!=="active"||(ka(),Ga(null),At.refetch())},[Ar,yr.data?.status,At.refetch,ka]);const mr=je({mutationFn:r(()=>Zt.startCloudConnectorEnrollment(T,R?.name,ae?nse(ae,"key",i,{resumeConnectionId:H,reconnectConnectionId:X,interactionId:z})+(o==="dialog"?"&enrollment_host=dialog":""):void 0),"mutationFn"),onSuccess:r(bt=>{if(!bt.verificationUrl){ka(),Ga("Paperclip Cloud did not return an enrollment link. Try again.");return}$n(bt.verificationUrl)},"onSuccess"),onError:r(bt=>{ka(),Ga(bt instanceof Error?bt.message:"Paperclip couldn’t reach Paperclip Cloud. Try again.")},"onError")}),Cn=Z({queryKey:P.tools.applications(T??"__none__"),queryFn:r(()=>Zt.listApplications(T),"queryFn"),enabled:!!T&&(!!Y||!!H||!!X),refetchOnMount:"always"}),on=Z({queryKey:P.tools.connections(T??"__none__"),queryFn:r(()=>Zt.listConnections(T),"queryFn"),enabled:!!T&&(!!Y||!!H||!!X),refetchOnMount:"always"}),Hr=(0,m.useMemo)(()=>u?null:cse(Y,Cn.data?.applications??[],on.data?.connections??[],U?{applicationId:ce.applicationId,draftOnly:!0}:{}),[Cn.data,on.data,U,Y,ce.applicationId,u]),ss=(0,m.useMemo)(()=>X?(on.data?.connections??[]).find(bt=>bt.id===X)??null:null,[on.data,X]),Hn=(0,m.useRef)(null);(0,m.useEffect)(()=>{if(!p||!on.isFetchedAfterMount||!ss||Hn.current===ss.id)return;const bt=ss.config?.url??ss.transportConfig?.url??ss.transportConfig?.serverUrl??ss.config?.serverUrl;typeof bt!="string"||!/^https?:\/\//i.test(bt)||(Hn.current=ss.id,Ue(_e=>_e||bt))},[p,on.isFetchedAfterMount,ss]);const Gn=(0,m.useMemo)(()=>ss?(Cn.data?.applications??[]).find(bt=>bt.id===ss.applicationId)??null:null,[Cn.data,ss]),un=pit({requestedAppKey:ae,byo:le,applicationId:ce.applicationId,reconnectConnection:ss,reconnectApplication:Gn}),Kn=(0,m.useMemo)(()=>H?(on.data?.connections??[]).find(bt=>bt.id===H)??null:null,[on.data,H]),Lr=Kn??ss,Br=Lr?Lr.credentialPolicy==="per_user"?"user":Lr.credentialPolicy==="per_agent"?"agent":"organization":re,Se=Kn?.authKind==="oauth"?Kn:Hr,Jt=Hr?Hr.credentialPolicy==="per_user"?"user":Hr.credentialPolicy==="per_agent"?"agent":"organization":null,ln=Br??Jt;(0,m.useEffect)(()=>{ln&&wt(ln)},[ln]);const rr=(0,m.useMemo)(()=>Ie&&!ie?v3(Ie,fs):null,[ie,fs,Ie]),ra=ie?G2(ie,Cs||null):null,Ea=ra&&rp(ra)?ra:lse(ie),os=i==="paperclip_vault"&&Ea?ie:null,Re=i==="paperclip_vault"&&ose(ie)?ie:null,Kt=!!Y&&(!Cn.isFetchedAfterMount||!on.isFetchedAfterMount),Vt=r(bt=>{me(bt),ie&&C(nse(ie.slug,bt,i,{connectionMethodKey:ie.methods.find(_e=>_e.key===Cs)?.ai?Cs:void 0,resumeConnectionId:H,reconnectConnectionId:X,interactionId:z}))},"setAppStep"),fn=Kn??ss??Se,an=ie?.agentInstructions,ar=ie&&an?ft?.slug===ie.slug?ft.value:fn?fn.agentInstructions??{...Kk(an),enabled:!1}:Kk(an):null,Mr=!ar||!!ar.text.trim(),qt=je({mutationFn:r(async bt=>(ar&&JSON.stringify(ar)!==JSON.stringify(bt.agentInstructions)&&await Zt.updateConnection(bt.id,{agentInstructions:ar}),Zt.startOAuth(bt.id,{asCurrentUser:bt.credentialPolicy==="per_user",...bt.credentialPolicy==="per_agent"?{asAgentId:jit(bt)??[...xt][0]}:{},...z?{interactionId:z}:{}})),"mutationFn"),onSuccess:r(bt=>{yt(bt)},"onSuccess"),onError:r(bt=>{const _e=bt instanceof dn&&bt.body&&typeof bt.body=="object"?bt.body.details:null;as("error"),j?.("needs_retry"),en(_e?.code==="invalid_grant"?"Your authorization expired or was revoked. Reconnect to continue.":bt instanceof Error?bt.message:"Paperclip couldn’t start secure sign-in. Try again.")},"onError")}),cs=qt.mutate,_n=(0,m.useCallback)(bt=>{j?.("authorizing"),Jn(),o==="dialog"&&!z&&gn(bt.id),cs(bt)},[cs,j,Jn,o,z]),jr=r(async bt=>{if(c)return;const _e=QSe(T,(ln??Bt)!=="agent"&&Xt==="all"?{onAll:!0,agentIds:new Set}:{onAll:!1,agentIds:xt});await Zt.putConnectionInstalls(bt,_e)},"applyAccessInstalls"),wn=ln??Bt,ya=je({mutationFn:r(async bt=>{const _e=bt??ie;let ot;if(_e){const Nt=ln??Bt,us=G2(_e,Cs||null),Ls=GC(_e,us)?dq(St).ids:[],Na=ke.trim(),ea=Jte(Na||_e.name,Nt);ot=await Zt.connectApp(T,{galleryKey:_e.slug,...ar?{agentInstructions:ar}:{},...Cs?{connectionMethodKey:Cs}:{},name:ea,credentialSource:i,...i==="paperclip_vault"?{credentialValues:Ae}:{},...i==="vercel_connect"?{vercelConnect:{connector:Ot.trim()}}:{},..._t.trim()?{oauthClient:{clientId:_t.trim(),...gt?{clientSecret:gt}:{}}}:{},configValues:GC(_e,us)?{allowedSpreadsheetIds:Ls}:Object.keys(Ns).length>0?Ns:void 0,applicationId:ce.applicationId,...H??qs.current?{resumeConnectionId:H??qs.current}:X?{reconnectConnectionId:X}:{},...Nt!=="organization"?{grantKind:Nt}:{},...Nt==="agent"?{subjectAgentId:[...xt][0]}:{}}),qs.current=null}else{const Nt=iit({link:Ie,name:at,authMode:Le,needsKey:de,keyValue:pt,headers:ut,oauthClientId:it,oauthClientSecret:tt}),us=Jte(Nt.name??G$(Ie)??"Custom app",wn);ot=await Zt.connectApp(T,{...Nt,...X?{reconnectConnectionId:X}:{},...te||rr?.slug==="zapier"?{galleryKey:"zapier",connectionMethodKey:"generated-url"}:{},name:us,applicationId:ce.applicationId,...wn!=="organization"?{grantKind:wn}:{},...wn==="agent"?{subjectAgentId:[...xt][0]}:{}})}return ot.auth?.kind==="oauth"&&!H&&!X&&await jr(ot.connectionId),ot},"mutationFn"),onSuccess:r(bt=>{if(bt.auth?.kind==="oauth"){if(Mt(bt),bt.auth.manualClientRequired){lt(Zte("oauth_manual_client_required",null)),Qe("oauth"),He(!0),Xe(!1);return}if(o==="dialog"||z){as("starting"),Xe(!ie),_n(bt.connection);return}const ot=bt.auth.startUrl?.trim();if(!ot){as("starting"),Xe(!0),_n(bt.connection);return}Xe(!0),yt({authorizationUrl:ot,handoff:bt.auth.handoff});return}lt(null),Mt(bt);const _e={};for(const ot of bt.actions.readOnly)_e[ot.catalogEntryId]=!0;for(const ot of bt.actions.canMakeChanges)_e[ot.catalogEntryId]=!0;ws(_e),eo.mutate({result:bt,enabled:_e})},"onSuccess"),onError:r(bt=>{const _e=bt instanceof dn&&bt.body&&typeof bt.body=="object"?bt.body.details:null;if(os){as("error"),j?.("needs_retry"),en(_e?.code==="invalid_grant"?"Your authorization expired or was revoked. Reconnect to continue.":bt instanceof Error?bt.message:"Paperclip couldn’t start secure sign-in. Try again.");return}if(!ie&&Ie){const ot=typeof _e?.code=="string"?_e.code:null,Nt=Zte(ot,bt instanceof Error?bt.message:null);lt(Nt),Xe(!1),Nt.focus==="credentials"&&(Be(!0),He(!0));return}B({title:"Couldn’t connect",body:bt instanceof Error?bt.message:"Please check your key and try again.",tone:"error"})},"onError")}),br=ya.mutate,Wi=(0,m.useCallback)(bt=>{const _e=bt??ie;(_e?G2(_e,Cs||null):null)?.auth==="oauth"&&Jn(),br(bt)},[Cs,ie,br,Jn]);(0,m.useEffect)(()=>{if(!ae||At.isLoading||!At.data||X&&(!on.isFetchedAfterMount||!Cn.isFetchedAfterMount))return;const bt=hit({requestedAppKey:ae,galleryApps:At.data.apps,reconnectConnection:ss,applications:Cn.data?.applications??[]}),_e=!!bt?.methods.some(ir=>ir.oauthStrategy==="paperclip_cloud_connector"||ir.oauthStrategy==="paperclip_id_connector");if(Cr&&!_e&&yr.isLoading)return;const ot=Aw(bt,i),Nt=v??(ss?.connectionPurpose==="ai"?PJ.safeParse(ss.config?.ai).data:void 0),us=ot.find(ir=>Nt?ir.ai?.provider===Nt.provider&&(!("mode"in Nt)||Nt.mode!=="responsible_user")&&ir.ai.method===Nt.method:ir.key===K)??(Cr&&!_e?ise(Ks):null)??vk(ot),Ls=ot.length===1?ot[0]:null,Na=i==="paperclip_vault"&&!!lse(bt),ea=fit({credentialSource:i,available:At.data.credentialSources?.vercelConnect.available===!0,retainedReconnectMatches:!!(X&&un)}),zr=ot.length===1&&Ls?.auth==="oauth"&&!rp(Ls)&&!nk(Ls),Sa=xit({available:bt?.availability?.available,reconnectConnectionId:X,reconnectSourceMatches:un}),Ei=git({reconnectConnectionId:X,hasRequestedEntry:!!bt,supportedMethodCount:ot.length,unsupportedOAuth:zr,vercelUnavailable:ea,definitionUnavailable:Sa});if(Ei!=="ready"){if(ue(null),me("gallery"),Ei==="reconnect_unavailable"&&X){Er(X);return}C(H2(i==="vercel_connect"?V$():"/apps/connect",z),{replace:!0});return}if(Er(null),!!bt){if(ie?.slug!==bt.slug){ue(bt),be(bt.name),Ue(""),dt(""),Be(!1),vt(""),De({}),ye(""),We(""),zt(""),ze(us?.key??""),Is(aC(us)),ds(""),xe(null),Mt(null);const ir=he?.companyId===T?he:null;wt(Br??ir?.grantKind??Q$(us,!!c)),Oe(new Set(ir?.agentIds??(c?[c]:[]))),Yt(ir?.installChoice??(c?"specific":"all")),me(sse({requestedAppKey:ae,routeStage:O,resumeConnectionId:H,hasPrefilledLink:!!ce.link,zapierSource:te}))}else Vr!==_e&&(ue(bt),ze(us?.key??""),Is(aC(us)));if(!(Na&&(!Cn.isFetchedAfterMount||!on.isFetchedAfterMount))&&!(Na&&Ht.current)&&Na&&(Cn.isError||on.isError)){as("error"),en("Paperclip couldn’t check for an existing connection. Try again."),me("key");return}}},[v,K,Cn.isError,Cn.isFetchedAfterMount,Cn.data,on.isError,on.isFetchedAfterMount,yr.data?.configured,yr.isLoading,Cs,i,ie?.slug,Vr,At.data,At.isLoading,C,Br,ss,X,un,H,Ks,ae,c,he,O,te]),(0,m.useEffect)(()=>{Vs.current=null,is(null)},[H]),(0,m.useEffect)(()=>{const bt=Kn??ss;if(!bt||!ie||Vs.current===bt.id)return;const _e=Y8(bt),ot=typeof _e.sourceTemplateKey=="string"?_e.sourceTemplateKey:null;if(ot&&ot!==ie.slug)return;const Nt=typeof _e.connectionMethodKey=="string"?_e.connectionMethodKey:null,us=Nt?Aw(ie,i).find(Na=>Na.key===Nt)??null:null;if(be(bt.name||ie.name),us){ze(us.key);const Na=_e.methodConfig&&typeof _e.methodConfig=="object"?_e.methodConfig:{};Is({...aC(us),...Object.fromEntries(Object.entries(Na).filter(ea=>typeof ea[1]=="string"||typeof ea[1]=="boolean"))})}const Ls=_e.oauth&&typeof _e.oauth=="object"?_e.oauth:null;Ls?.clientRegistrationSource==="manual"&&typeof Ls.clientId=="string"&&ye(Ls.clientId),ee==="failed"||ee==="denied"?(as("error"),en(tse(ee,se))):(as("entry"),en(null)),me("key"),Vs.current=bt.id,is(bt.id)},[i,ie,se,ee,Kn,ss]);const eo=je({mutationFn:r(async bt=>{const{result:_e,enabled:ot}=bt,Nt=Object.entries(ot).filter(([,ea])=>ea).map(([ea])=>ea),us=mwe(_e,ea=>!!ot[ea]),Ls=Xt==="all"?"all_agents":{agentIds:Array.from(xt)},Na=await Zt.finishApp(T,_e.connectionId,{enabledCatalogEntryIds:Nt,askFirstCatalogEntryIds:us,...ar?{agentInstructions:ar}:{},access:Ls,...c?{preserveExistingAccess:!0}:{}});return await jr(_e.connectionId),Na},"mutationFn"),onSuccess:r(async(bt,_e)=>{await k.invalidateQueries({queryKey:["tools"]}),await k.invalidateQueries({queryKey:P.apps.attention(T)}),Vt("success"),x?.({connectionId:_e.result.connectionId})},"onSuccess"),onError:r(bt=>{Vt("key"),B({title:"Couldn’t finish setup",body:bt instanceof Error?bt.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((H||X)&&(on.isError||Cn.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)(L,{type:"button",onClick:r(async()=>{const[bt,_e]=await Promise.all([on.refetch(),Cn.refetch()]);!bt.isError&&!_e.isError&&(en(null),as("entry"))},"onClick"),children:"Try again"}),(0,t.jsx)(L,{type:"button",variant:"outline",onClick:r(()=>C("/apps"),"onClick"),children:"Back to apps"})]})]});if(H&&on.isFetchedAfterMount&&!Kn)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)(L,{type:"button",variant:"outline",className:"mt-5",onClick:r(()=>C("/apps"),"onClick"),children:"Back to apps"})]});if(X&&on.isFetchedAfterMount&&Cn.isFetchedAfterMount&&(!ss||!un))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:ss?"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)(L,{type:"button",variant:"outline",className:"mt-5",onClick:r(()=>C("/apps"),"onClick"),children:"Back to apps"})]});if((H||X)&&At.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)(L,{type:"button",onClick:r(()=>{At.refetch()},"onClick"),children:"Try again"}),(0,t.jsx)(L,{type:"button",variant:"outline",onClick:r(()=>C("/apps"),"onClick"),children:"Back to apps"})]})]});if(X&&Dn===X)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)(L,{type:"button",variant:"outline",className:"mt-5",onClick:r(()=>C("/apps"),"onClick"),children:"Back to apps"})]});if(H&&(!on.isFetchedAfterMount||At.isLoading||!ie||Lt!==Kn?.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)(vn,{className:"h-8 w-48"}),(0,t.jsx)(vn,{className:"h-40 w-full rounded-xl"})]});if(X&&(!on.isFetchedAfterMount||!Cn.isFetchedAfterMount||At.isLoading||ae&&!ie))return(0,t.jsxs)("div",{className:"mx-auto max-w-xl space-y-4","aria-label":"Loading retained connection setup",children:[(0,t.jsx)(vn,{className:"h-8 w-48"}),(0,t.jsx)(vn,{className:"h-40 w-full rounded-xl"})]});if(vs&&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 ",ae?"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)(F9,{choices:h.map(bt=>({id:bt.id,name:bt.name,description:bt.status==="active"&&bt.enabled?"Ready to use":"Setup needs attention"})),pendingId:Hs,onSelect:r(async bt=>{zs(bt),ur(null);try{await f(bt)}catch(_e){ur(_e instanceof Error?_e.message:"Couldn’t use this connection."),zs(null)}},"onSelect")}),Us?(0,t.jsx)(ha,{tone:"danger",className:"mt-4",children:Us}):null,(0,t.jsxs)("div",{className:"mt-5 flex flex-wrap gap-2",children:[(0,t.jsx)(L,{type:"button",variant:"outline",onClick:r(()=>Fs(!1),"onClick"),children:p?"Review connection setup":"Connect new"}),N?(0,t.jsx)(L,{type:"button",variant:"ghost",onClick:N,children:"Cancel"}):null]})]});const _o=Aw(ie,i),Vi=Pr?[Pr]:_o,Me=ie?Cs?Vi.find(bt=>bt.key===Cs)??null:Vi[0]??null:null,ys=ie?Me?.auth??"none":Le==="none"?"none":Le==="oauth"?"oauth":"api_key",cn=ge==="key"?((bt,_e)=>(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)(ZSe,{extra:bt,forceOpen:_e,companyId:T,sentence:d6({grantKind:wn,authKind:ys,installChoice:Xt,installCount:xt.size,lockedAgentId:c??null,preserveAgentAccess:!!(os&&(Se||ss))}),notice:[At.data?.capabilities?.canCreateOrganizationGrant===!1?At.data.capabilities.organizationGrantReason??"Only a connection manager can share this credential with the organization.":null,At.data?.capabilities?.canSetCompanyInstall===!1?At.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(ot=>!!ot),authKind:ys,grantKinds:ln?[ln]:Me?.grantKinds,grantKind:wn,setGrantKind:wt,installChoice:Xt,setInstallChoice:Yt,installAgentIds:xt,setInstallAgentIds:Oe,lockedAgentId:c,capabilities:At.data?.capabilities,githubIdentity:ie?.slug==="github",identityLoading:!!os&&Kt,preserveAgentAccess:!!(os&&(Se||ss)),disabled:ya.isPending||qt.isPending},"connection-defaults"),ie&&an&&ar&&(0,t.jsx)("div",{className:"mt-6",children:(0,t.jsx)(O9,{provider:ie.name,template:an,value:ar,onChange:r(ot=>Ut({slug:ie.slug,value:ot}),"onChange"),disabled:ya.isPending||qt.isPending})}),e&&(0,t.jsx)("div",{className:"mt-6",children:e})]})):null,aa=os&&Ea&&nk(Ea)?Ea:null,Wa=aa&&os?(0,t.jsx)(c6,{entry:os,method:aa,callbackUrl:VSe(),clientId:_t,onClientIdChange:ye,clientSecret:gt,onClientSecretChange:We,required:!1}):null,Za=cn?.()??null,Li=Wa?cn?.(Wa,Ts==="error"||_t.trim().length>0)??null:Za,Fa=!!(os&&ge==="key"&&(Re||Ts!=="entry")),Yo=!!(ge==="key"&&ie&&Cr&&!Vr&&yr.data?.configured===!0),ja=!!(ge==="key"&&ie&&Cr&&!Vr&&(yr.isLoading||yr.isError||yr.data?.configured!==!0));if(Fa&&os)return(0,t.jsx)(o6,{entry:os,resuming:!!H,phase:Ts,error:Zn,recoveryActions:se==="github_installation_required"?{installationUrl:ne,managementUrl:fe}:void 0,authorizationHost:nr,authorizationUrl:Pn,guidance:ie?.slug==="railway"&&Me?(0,t.jsxs)("div",{className:"space-y-3 text-sm text-muted-foreground",children:[(0,t.jsx)("p",{children:Me.guidanceMd}),(0,t.jsx)("ul",{className:"list-disc space-y-2 pl-5",children:Me.warnings?.map(bt=>(0,t.jsx)("li",{children:bt},bt))})]}):null,defaults:Li,settingsValid:n&&Mr,onOpenAuthorization:pn,onRetry:r(async()=>{const bt=!xn.current;xn.current=!0,en(null),as("starting");const _e=Qt?.connection??Se;if(_e&&Wa&&_t.trim()){qs.current=_e.id,Wi(os);return}if(_e){_n(_e);return}if(bt&&!H&&!Cn.isError&&!on.isError){Wi(os);return}Ht.current=!0;try{const[ot,Nt]=await Promise.all([Cn.refetch(),on.refetch()]);if(ot.isError||Nt.isError){as("error"),en("Paperclip couldn’t check for an existing connection. Try again.");return}const us=(H?(Nt.data?.connections??[]).find(Ls=>Ls.id===H&&Ls.authKind==="oauth")??null:null)??cse(Y,ot.data?.applications??[],Nt.data?.connections??[],U?{applicationId:ce.applicationId,draftOnly:!0}:{});us&&!H&&wt(us.credentialPolicy==="per_user"?"user":us.credentialPolicy==="per_agent"?"agent":"organization"),us?_n(us):ya.mutate(os)}finally{Ht.current=!1}},"onRetry"),onBack:r(()=>{mt.current?.abort(),as("entry"),en(null),Ze()},"onBack"),onCancel:r(()=>{mt.current?.abort(),(N??(()=>C("/apps")))()},"onCancel")});if(Ee&&!ie&&Ie&&ge==="key")return(0,t.jsx)(o6,{identity:{name:at.trim()||M1(Ie)||"this server",unverifiedHost:M1(Ie)},steps:{labels:rse,activeIndex:ase.key},phase:Ts,error:Zn,authorizationHost:nr,authorizationUrl:Pn,defaults:Za,onOpenAuthorization:pn,onRetry:r(()=>{en(null);const bt=Qt?.connection;if(bt){as("starting"),_n(bt);return}Xe(!1),as("entry")},"onRetry"),onBack:r(()=>{mt.current?.abort(),Xe(!1),as("entry"),en(null)},"onBack"),onCancel:r(()=>{mt.current?.abort(),(N??(()=>C("/apps")))()},"onCancel")});const Hi=Qt?.application.name??ie?.name??(at.trim()||G$(Ie)||"this app"),Oo=oe?fs.filter(bt=>Aw(bt,i).length>0):fs,Jo=te?At.data?.apps.find(bt=>bt.slug==="zapier")??null:null,Fo=(ss?.connectionPurpose==="ai"?PJ.safeParse(ss.config?.ai).data:void 0)??ie?.methods.find(bt=>bt.key===Cs)?.ai??(!Cs&&ie?.methods.every(bt=>bt.ai)?ie.methods[0]?.ai:void 0),Gi=ie?w?.({app:ie,name:ke||ie.name,grantKind:wn,agentIds:[...xt],allAgents:Xt==="all",onBack:r(()=>Ze(),"onBack")})??(Fo&&T?(0,t.jsx)(t.Fragment,{children:(0,t.jsx)(P5,{companyId:T,provider:Fo.provider,fixedMethod:!!(v&&v.mode!=="responsible_user"),initialMethod:ss?.connectionPurpose==="ai"?(ss.config?.ai).method:Fo.method,connectionId:ss?.connectionPurpose==="ai"?ss.id:void 0,name:ss?.connectionPurpose==="ai"?ss.name:ke||`My ${ie.name} ${Fo.method==="subscription"?"subscription":"API"}`,ownership:(ss?.connectionPurpose==="ai"?ss.credentialPolicy==="shared":wn==="organization")?"shared":"personal",agentIds:[...xt],allAgents:Xt==="all",onCancel:r(()=>N?N():C("/apps"),"onCancel"),onComplete:r(bt=>{x?.({connectionId:bt.connectionId}),x||C(`/apps/${bt.connectionId}/permissions`)},"onComplete")})}):void 0):void 0,Xo=ss?.connectionPurpose==="ai"?["Reconnect account"]:Gi!==void 0?["Connect account"]:te?vit:ie&&Vi.length>1?["Choose connection"]:ie&&Vi[0]?.auth==="oauth"?["Sign in"]:GC(ie,Cs)?["Share sheet"]:ie?["Add your key"]:rse,Fc=ss?.connectionPurpose==="ai"?0:(te||ie)&&ge!=="gallery"&&ge!=="success"?bit[ge]:ge==="success"?Xo.length:ase[ge];return(0,t.jsxs)("div",{className:"max-w-5xl",children:[ge!=="success"&&!(a&&ge==="gallery")&&(0,t.jsx)(WM,{subtitle:ge==="gallery"?oe?"Choose a reviewed app to connect through Vercel.":"Pick the app you want your agents to use.":Xo.length<=1?void 0:`Step ${Fc+1} of ${Xo.length}`,step:ge,activeIndex:Fc,labels:Xo,appIdentity:te?{name:"Zapier",logoUrl:Jo?.branding.logoUrl??null,darkLogoUrl:Jo?.branding.darkLogoUrl??null}:ie&&ge!=="gallery"?{name:ie.name,logoUrl:ie.branding.logoUrl,darkLogoUrl:ie.branding.darkLogoUrl??null}:void 0,unverifiedHost:!ie&&!te&&ge!=="gallery"?M1(Ie):null,onCancel:N??(()=>C("/apps"))}),ge==="key"&&s&&(0,t.jsx)("div",{className:"mx-auto mb-6 max-w-xl",children:s}),ge==="gallery"&&(0,t.jsx)(Cit,{loading:At.isLoading,initialLink:Ie,apps:Oo,vercelConnect:oe,vercelConnectAvailability:At.data?.credentialSources?.vercelConnect??null,byo:le,byoOnly:a,source:E.get("source"),onPick:Zs,onUseLink:r(bt=>{const _e=v3(bt,fs);ue(null),be(""),Ue(bt),dt(_e?.name??G$(bt)??""),Be(!1),vt(""),De({}),ds(""),xe(null),Oe(new Set(c?[c]:[])),Yt(c?"specific":"all"),wt(Br??(c?"user":"organization")),me("key")},"onUseLink")}),Yo&&ie?(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:[ie.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 ",ie.name," sign-in is not currently available. Try again shortly or contact your instance administrator."]}),Ln?(0,t.jsxs)(L,{type:"button",variant:"link",className:"mt-4 h-auto p-0 text-xs",onClick:r(()=>ze(Ln.key),"onClick"),children:["Use your own ",ie.name," OAuth app"]}):null,(0,t.jsxs)("div",{className:"mt-6 flex items-center justify-between gap-3",children:[(0,t.jsx)(L,{type:"button",variant:"ghost",onClick:Ze,children:"Back"}),(0,t.jsxs)(L,{type:"button",disabled:At.isFetching,onClick:r(()=>{At.refetch()},"onClick"),children:[At.isFetching?(0,t.jsx)(rt,{className:"h-4 w-4 animate-spin"}):null,"Try again"]})]})]}):ge==="key"&&ie&&ja?(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)(J0,{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 ",ie.name," (you only need to do this once)."]})]})]}),Ln?(0,t.jsxs)(L,{type:"button",variant:"link",className:"mt-4 h-auto p-0 text-xs",onClick:r(()=>ze(Ln.key),"onClick"),children:["Use your own ",ie.name," OAuth app"]}):null,yr.isError||sr?(0,t.jsx)(ha,{tone:"danger",className:"mt-4",children:sr??"Paperclip couldn’t check Cloud registration. Try again."}):null,Ar?(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:Ar,target:"_blank",rel:"noopener noreferrer",children:"Open authorization in a new tab"})]}):null,Za,(0,t.jsxs)("div",{className:"mt-6 flex items-center justify-between gap-3",children:[(0,t.jsx)(L,{type:"button",variant:"ghost",onClick:Ze,children:"Back"}),(0,t.jsxs)(L,{type:"button",disabled:yr.isLoading||mr.isPending,onClick:r(()=>{Ga(null),Jn(),Ds(),mr.mutate()},"onClick"),children:[mr.isPending?(0,t.jsx)(rt,{className:"h-4 w-4 animate-spin"}):null,yr.data?.status==="pending"?"Continue":"Connect with Paperclip"]})]})]})}):ge==="key"&&ie&&Gi!==void 0?Gi:ge==="key"&&ie?(0,t.jsx)(Ait,{settingsValid:n&&Mr,entry:ie,error:ya.isError?ya.error instanceof Error?ya.error.message:"Please check your key and try again.":null,values:Ae,onChange:De,oauthClientId:_t,onOAuthClientIdChange:ye,oauthClientSecret:gt,canReuseOAuthClientSecret:!!(Lr?.config?.oauth&&Lr.config.oauth.clientId===_t.trim()&&Lr.hasSavedOAuthClientSecret),onOAuthClientSecretChange:We,credentialSource:i,vercelConnector:Ot,onVercelConnectorChange:zt,vercelConnectAvailability:At.data?.credentialSources?.vercelConnect??null,methodKey:Cs,onMethodChange:r(bt=>{ze(bt?.key??""),!Br&&bt?.grantKinds&&!bt.grantKinds.includes(Bt)&&wt(Q$(bt,!!c)),De({}),ye(""),We(""),zt(""),Is(aC(bt))},"onMethodChange"),configValues:Ns,onConfigChange:Is,googleSheetsLinks:St,googleSheetsError:$e,onGoogleSheetsLinksChange:r(bt=>{ds(bt),xe(null)},"onGoogleSheetsLinksChange"),submitting:ya.isPending,renderDefaults:cn??void 0,onBack:Ze,onConnect:r(()=>{if(GC(ie,Cs)){const ot=dq(St);if(ot.invalidCount>0){xe("That doesn't look like a Google Sheets link.");return}if(ot.ids.length===0){xe("Paste at least one Google Sheets link.");return}}const bt=G2(ie,Cs||null),_e=!!(bt?.credentialFields?.length||bt?.tenantFields?.some(ot=>!ot.hidden)||bt?.extensionFields?.some(ot=>!ot.hidden));if(bt&&rp(bt)&&Se&&!_e&&!_t.trim()){xn.current=!0,en(null),as("starting"),_n(Se);return}bt&&rp(bt)&&(xn.current=!0,en(null),as("starting")),Wi()},"onConnect")}):null,ge==="key"&&!ie&&!Ie&&!te&&ae&&(0,t.jsxs)("div",{className:"mx-auto max-w-xl","aria-busy":"true","aria-label":`Loading ${ae} setup`,children:[(0,t.jsx)(vn,{className:"h-6 w-2/3 rounded-md"}),(0,t.jsx)(vn,{className:"mt-3 h-4 w-full rounded-md"}),(0,t.jsx)(vn,{className:"mt-8 h-11 w-40 rounded-md"})]}),ge==="key"&&!ie&&Ie&&!te&&(0,t.jsx)(_it,{link:Ie,name:at,needsKey:de,keyValue:pt,onKeyChange:vt,authMode:Le,onAuthModeChange:r(bt=>{Qe(bt),lt(null),bt!=="auto"&&Be(!1),bt!=="bearer"&&bt!=="auto"&&vt("")},"onAuthModeChange"),headers:ut,onHeadersChange:r(bt=>{Ye(bt),lt(null)},"onHeadersChange"),oauthClientId:it,onOAuthClientIdChange:kt,oauthClientSecret:tt,onOAuthClientSecretChange:Pe,advancedOpen:Ce,onAdvancedOpenChange:He,guidance:Je,matchedEntry:rr,onUseMatchedEntry:rr?()=>Zs(rr):void 0,submitting:ya.isPending||Ee,defaults:Za,onBack:Ze,onConnect:r(()=>{lt(null),ya.mutate(void 0)},"onConnect")}),ge==="key"&&!ie&&te&&(0,t.jsx)(Sit,{link:Ie,onLinkChange:Ue,submitting:ya.isPending,defaults:Za,onBack:Ze,onConnect:r(()=>ya.mutate(void 0),"onConnect")}),ge==="success"&&(0,t.jsx)(Pit,{appName:Hi,logoUrl:ie?.branding.logoUrl,darkLogoUrl:ie?.branding.darkLogoUrl,summary:Eit({grantKind:wn,authKind:ys,installChoice:Xt,installCount:xt.size,enabledCount:Object.values(rs).filter(Boolean).length}),statedDefault:d6({grantKind:wn,authKind:ys,installChoice:Xt,installCount:xt.size,lockedAgentId:c??null}),onDone:N??(()=>C("/apps"))})]})}r(Nit,"StandardConnectionSetupFlow");function o6({entry:e,identity:s,resuming:n=!1,phase:a,error:i,recoveryActions:o,authorizationHost:l,authorizationUrl:c,steps:d={labels:yit,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)(WM,{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)(vc,{className:"h-5 w-5 text-destructive"}):a==="entry"?(0,t.jsx)(pd,{className:"h-5 w-5 text-muted-foreground"}):(0,t.jsx)(rt,{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)(KM,{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)(L,{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)(ao,{className:"ml-1.5 h-3.5 w-3.5"})]})}):null,o.managementUrl?(0,t.jsx)(L,{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)(L,{type:"button",onClick:p,disabled:!f,children:[a==="entry"?n?`Finish with ${j}`:`Continue to ${j}`:"Try again",a==="entry"?(0,t.jsx)(ao,{className:"h-4 w-4","aria-hidden":"true"}):null]}):(0,t.jsx)(L,{type:"button",disabled:!0,children:a==="redirecting"?`Opening ${j}…`:"Preparing…"}),c?(0,t.jsx)(L,{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)(L,{type:"button",variant:"ghost",onClick:b,children:"Back"})]})]})]})}r(o6,"OAuthConnectStateScreen");function Sit({link:e,onLinkChange:s,submitting:n,defaults:a,onBack:i,onConnect:o}){const l=l6(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)(ht,{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)(L,{variant:"ghost",onClick:i,disabled:n,children:"Back"}),(0,t.jsxs)(L,{onClick:o,disabled:n||!d,children:[n&&(0,t.jsx)(rt,{className:"mr-2 h-4 w-4 animate-spin"}),n?"Checking…":"Check link"]})]})]})}r(Sit,"ZapierConnectStep");function Cit({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 A=h.trim().toLowerCase();return n.filter(D=>!A||D.name.toLowerCase().includes(A))},[n,h]),C=l6(f),I=C?v3(C,n):null,R=c==="zapier",T=r(()=>{const A=l6(f);if(!A){j("Paste a full http or https link.");return}j(null),u(A)},"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((A,D)=>(0,t.jsx)(vn,{className:"h-32 w-full rounded-xl"},D))}):(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)(L,{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)(ao,{className:"ml-2 h-3.5 w-3.5"})]})}):null]}),l?.available===!1?(0,t.jsx)(ha,{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)(oa,{className:"pointer-events-none absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground"}),(0,t.jsx)(ht,{value:h,onChange:r(A=>p(A.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(A=>{const D=WSe(A.slug,A.description),M=hA(A),B=M.length===0||M.every(z=>z.auth==="oauth"&&!rp(z)&&!nk(z)),E=A.availability?.available===!1||o&&l?.available!==!0;return(0,t.jsxs)("button",{type:"button",disabled:B||E,title:E?A.availability?.reason??l?.reason??void 0:void 0,onClick:r(()=>d(A),"onClick"),className:W("flex flex-col rounded-xl border border-border bg-card p-4 text-left transition-colors",B||E?"cursor-not-allowed opacity-60":"hover:border-foreground/30 hover:bg-accent/40"),children:[(0,t.jsx)(al,{name:A.name,logoUrl:A.branding.logoUrl,darkLogoUrl:A.branding.darkLogoUrl,size:36}),(0,t.jsx)("div",{className:"mt-3 text-sm font-bold text-foreground",children:A.name}),(0,t.jsx)("div",{className:"mt-1 line-clamp-2 text-xs text-muted-foreground",children:D.tagline}),(0,t.jsx)("div",{className:"mt-3 text-xs font-semibold text-foreground",children:E?(0,t.jsx)("span",{className:"text-muted-foreground",children:A.availability?.reason??l?.reason??"Unavailable on this instance."}):B?(0,t.jsx)("span",{className:"text-muted-foreground",children:"Unavailable"}):(0,t.jsx)("span",{children:"Connect →"})})]},A.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:W("grid gap-4 border-t border-border pt-5 md:grid-cols-(--gtc-13)",a&&"-mx-3 rounded-xl border border-primary/40 bg-primary/[0.04] px-3 pb-4 md:mx-0"),children:[(0,t.jsxs)("div",{children:[(0,t.jsxs)("div",{className:"flex items-center gap-2 text-sm font-semibold text-foreground",children:[(0,t.jsx)(vc,{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"}),"."]}),I&&(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)(al,{name:I.name,logoUrl:I.branding.logoUrl,darkLogoUrl:I.branding.darkLogoUrl,size:24}),(0,t.jsxs)("span",{className:"truncate",children:["This looks like ",I.name,"."]})]}),(0,t.jsx)(L,{type:"button",size:"sm",variant:"outline",disabled:I.availability?.available===!1,onClick:r(()=>{if(j(null),I.slug==="zapier"){T();return}d(I)},"onClick"),children:I.availability?.available===!1?"Not available":I.slug==="zapier"?"Continue":`Use ${I.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)(ht,{ref:w,type:R||I?.slug==="zapier"?"password":"url",autoComplete:"off",spellCheck:!1,"aria-label":"MCP server URL",value:f,onChange:r(A=>{b.current=!0,x(A.target.value),j(null)},"onChange"),onKeyDown:r(A=>{A.key==="Enter"&&T()},"onKeyDown"),placeholder:R?"https://mcp.zapier.com/api/v1/connect?token=…":"https://example.com/actions",className:"h-10"}),(0,t.jsx)(L,{type:"button",variant:"outline",onClick:T,children:"Continue"})]}),v&&(0,t.jsx)("div",{className:"text-xs text-destructive",children:v})]})]})]})}r(Cit,"GalleryStep");function l6(e){try{const s=new URL(e.trim());return s.protocol!=="http:"&&s.protocol!=="https:"?null:s.toString()}catch{return null}}r(l6,"normalizeAppLink");function _it({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 I=M1(e),R=o==="custom_headers"?HSe(c):null,T=oit({link:e,name:s,authMode:o,needsKey:n,keyValue:a,headers:c,oauthClientId:u,oauthClientSecret:p}),A=o==="auto"&&n||o==="bearer",D=j?.slug==="zapier"?_pe(e):e,M=r((B,E)=>{d(c.map(z=>z.id===B?{...z,...E}:z))},"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:D,children:D}),(0,t.jsx)(KM,{host:I})]}),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)(al,{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)(L,{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)(ha,{tone:"warning",title:v.title,children:v.body})}):null,(0,t.jsxs)("div",{className:"mt-6 space-y-6",children:[A?(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)(ht,{id:"generic-mcp-key",type:"password",autoComplete:"off",value:a,onChange:r(B=>i(B.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)(gl,{open:x,onOpenChange:b,children:[(0,t.jsxs)(ec,{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:W("h-4 w-4 text-muted-foreground transition-transform",x&&"rotate-180")})]}),(0,t.jsxs)(xl,{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:dse.map(B=>(0,t.jsx)(Iit,{label:B.label,selected:o===B.mode,onClick:r(()=>l(B.mode),"onClick")},B.mode))}),(0,t.jsx)("p",{className:"text-xs text-muted-foreground",children:dse.find(B=>B.mode===o)?.hint}),o==="custom_headers"?(0,t.jsxs)("div",{className:"space-y-3",children:[c.map(B=>(0,t.jsxs)("div",{className:"flex items-start gap-2",children:[(0,t.jsx)(ht,{value:B.name,onChange:r(E=>M(B.id,{name:E.target.value}),"onChange"),placeholder:"Header name","aria-label":"Header name",className:"h-10 font-mono"}),(0,t.jsx)(ht,{type:"password",autoComplete:"off",value:B.value,onChange:r(E=>M(B.id,{value:E.target.value}),"onChange"),placeholder:"Value","aria-label":B.name.trim()?`Value for ${B.name.trim()}`:"Header value",className:"h-10 font-mono"}),(0,t.jsx)(L,{type:"button",variant:"ghost",size:"sm",className:"h-10 shrink-0",onClick:r(()=>d(c.filter(E=>E.id!==B.id)),"onClick"),disabled:c.length===1,children:"Remove"})]},B.id)),(0,t.jsx)(L,{type:"button",variant:"outline",size:"sm",onClick:r(()=>d([...c,i6()]),"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)(ht,{id:"generic-mcp-client-id",value:u,onChange:r(B=>h(B.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)(ht,{id:"generic-mcp-client-secret",type:"password",autoComplete:"off",value:p,onChange:r(B=>f(B.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)(L,{variant:"ghost",onClick:S,disabled:w,children:"Back"}),(0,t.jsxs)(L,{onClick:C,disabled:w||!T||!!R,children:[w&&(0,t.jsx)(rt,{className:"mr-2 h-4 w-4 animate-spin"}),w?"Checking…":"Check link"]})]})]})}r(_it,"LinkConnectStep");var dse=[{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 Iit({label:e,selected:s,onClick:n}){return(0,t.jsx)("button",{type:"button",onClick:n,"aria-pressed":s,className:W("min-w-(--sz-64px) rounded-md px-4 py-1.5 text-sm font-medium transition-colors",s?"bg-background text-foreground shadow-sm":"text-muted-foreground hover:text-foreground"),children:e})}r(Iit,"SegmentedOption");function Ait({settingsValid:e=!0,entry:s,error:n,values:a,onChange:i,oauthClientId:o,onOAuthClientIdChange:l,oauthClientSecret:c,canReuseOAuthClientSecret:d,onOAuthClientSecretChange:u,credentialSource:h,vercelConnector:p,onVercelConnectorChange:f,vercelConnectAvailability:x,methodKey:b,onMethodChange:v,configValues:j,onConfigChange:N,googleSheetsLinks:w,googleSheetsError:k,onGoogleSheetsLinksChange:S,submitting:C,renderDefaults:I,onBack:R,onConnect:T}){const A=(0,m.useMemo)(()=>Aw(s,h),[h,s]),D=b?A.find(Le=>Le.key===b)??null:vk(A),M=(0,m.useMemo)(()=>A.some(Le=>Le.capabilityProfile)?Array.from(A.reduce((Le,Qe)=>{const ut=Qe.capabilityProfile.key,Ye=Le.get(ut);return Ye?Ye.methods.push(Qe):Le.set(ut,{key:ut,label:Qe.capabilityProfile?.label??Qe.label??Qe.key,description:Qe.capabilityProfile?.description??Qe.whenToUse,methods:[Qe]}),Le},new Map)).map(([,Le])=>Le):[],[A]),B=D?.capabilityProfile?.key??D?.key??"",E=M.map(Le=>Le.key).join("|"),[z,$]=(0,m.useState)(B||vk(A)?.capabilityProfile?.key||(M.length===1?M[0].key:""));(0,m.useEffect)(()=>{if(B){$(B);return}$(Le=>M.some(Qe=>Qe.key===Le)?Le:vk(A)?.capabilityProfile?.key||(M.length===1?M[0].key:""))},[E,M,A,B]);const q=M.length>1?M.find(Le=>Le.key===z)?.methods??[]:A,U=(D?.credentialFields??[]).map(Le=>({...Le,configPath:$pe(Le,D),helpUrl:D?.consoleLinks?.keys??D?.consoleLinks?.docs??""})),O=D?.credentialSources?.vercelConnect??null,K=h==="vercel_connect",H=K||U.every(Le=>Le.required===!1||(a[Le.configPath]?.trim().length??0)>0),ee=nk(D),se=ee&&!rp(D),ne=K||!se||o.trim().length>0&&(!D?.oauthClientSecretRequired||d||c.trim().length>0),fe=!K||p.trim().length>0,X=D?.auth==="oauth"&&ee?VSe():null,re=[...D?.tenantFields??[],...D?.extensionFields??[]],oe=re.filter(Le=>!Le.hidden),G=oe.filter(Le=>Le.advanced!==!0),Y=oe.filter(Le=>Le.advanced===!0),Q=re.every(Le=>{if(!Le.required)return!0;const Qe=j[Le.key];return typeof Qe=="boolean"||typeof Qe=="string"&&Qe.trim().length>0}),te=D?.configRequirements?.atLeastOneOf??[],ae=te.length===0||te.some(Le=>{const Qe=j[Le];return typeof Qe=="string"&&Qe.trim().length>0}),le=(M.length<=1||!!z)&&(q.length<=1?!!D:!!b),he=s.availability?.robotEmail??null,ce=s.availability?.available===!1,ge=!K&&ee&&!se,me=M.length>1||q.length>1,ie=M.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)(wm,{ariaLabel:`Access level for ${s.name}`,className:"mt-2",value:z,onValueChange:r(Le=>{const Qe=M.find(ut=>ut.key===Le);Qe&&($(Le),v(s7(Qe.methods)))},"onValueChange"),options:M.map(Le=>({value:Le.key,title:Le.label,description:Le.description}))}),!z&&(0,t.jsx)("p",{className:"mt-2 text-xs text-muted-foreground",children:"Choose an access level to continue."})]}):null,ue=q.find(Le=>Le.oauthStrategy==="paperclip_cloud_connector"),ke=ue&&q.find(Le=>nk(Le)&&!rp(Le)),be=D?.key===ke?.key,Ie=(0,m.useId)(),Ue=ue&&ke&&q.length===2?(0,t.jsx)(L,{type:"button",variant:"link",className:"h-auto p-0 text-xs text-muted-foreground underline underline-offset-2 hover:text-foreground","aria-expanded":be,"aria-controls":Ie,disabled:C,onClick:r(()=>v(be?ue:ke),"onClick"),children:be?"Use Paperclip instead":`Use your own ${dLe(ue.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)(wm,{ariaLabel:`How to connect ${s.name}`,className:"mt-2",value:b,onValueChange:r(Le=>{const Qe=q.find(ut=>ut.key===Le);Qe&&v(Qe)},"onValueChange"),options:q.map(Le=>({value:Le.key,title:Le.label??(Le.auth==="oauth"?`Sign in with ${s.name}`:"Use an API key")}))}),!D&&(0,t.jsx)("p",{className:"mt-2 text-xs text-muted-foreground",children:"Choose a connection method to continue."})]}):null,at=Y.length>0||ge||me,dt=be||!le,de=at?(0,t.jsxs)("div",{className:"space-y-6",children:[ie,Ue,Y.map(Le=>(0,t.jsx)(use,{field:Le,value:j[Le.key],onChange:r(Qe=>N({...j,[Le.key]:Qe}),"onChange")},Le.key)),ge?(0,t.jsx)(c6,{entry:s,method:D,callbackUrl:X,clientId:o,onClientIdChange:l,clientSecret:c,onClientSecretChange:u,required:!1}):null]}):null,Be=I?.(de,dt)??null;if(GC(s,D)){const Le=dq(w),Qe=e&&!ce&&!!he&&w.trim().length>0;return(0,t.jsxs)("div",{className:"mx-auto max-w-xl",children:[(0,t.jsxs)("div",{className:"space-y-6",children:[ie,he?(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:he,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:he}),(0,t.jsx)(XSe,{value:he,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)(Tn,{value:w,onChange:r(ut=>S(ut.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:Le.ids.length>0?`${Le.ids.length} ${Le.ids.length===1?"sheet":"sheets"} ready to connect.`:"Paste one link per line. Both .../edit and .../edit#gid=... links work."}),k&&(0,t.jsx)("div",{className:"mt-2 text-xs text-destructive",children:k})]})]}),Be,(0,t.jsxs)("div",{className:"mt-8 flex items-center justify-between",children:[(0,t.jsx)(L,{variant:"ghost",onClick:R,disabled:C,children:"Back"}),(0,t.jsxs)(L,{onClick:T,disabled:C||!Qe,children:[C&&(0,t.jsx)(rt,{className:"mr-2 h-4 w-4 animate-spin"}),C?"Checking…":"Connect"]})]})]})}const pt=D?.connectorProfile==="asana.mcp",vt=pt?null:D?.consoleLinks?.docs??s.docsUrl;return(0,t.jsxs)("div",{className:"mx-auto max-w-xl",children:[vt?(0,t.jsx)("div",{className:"mb-4 flex justify-end",children:(0,t.jsxs)("a",{href:vt,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)(ao,{className:"h-3 w-3"})]})}):null,(0,t.jsxs)("div",{className:"space-y-6",children:[pt?(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,D?.capabilityProfile&&(0,t.jsxs)("p",{className:"text-sm text-muted-foreground",children:[D.capabilityProfile.label,": ",D.capabilityProfile.description]}),K&&O&&x?(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:x.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)(ao,{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)(ht,{id:"vercel-connect-connector",value:p,onChange:r(Le=>f(Le.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)(ha,{tone:"danger",children:n})}):null,G.map(Le=>(0,t.jsx)(use,{field:Le,value:j[Le.key],onChange:r(Qe=>N({...j,[Le.key]:Qe}),"onChange")},Le.key)),!K&&D?.auth==="oauth"&&se?(0,t.jsx)("div",{id:Ie,role:"region","aria-label":"Your OAuth app",children:(0,t.jsx)(c6,{entry:s,method:D,callbackUrl:X,clientId:o,onClientIdChange:l,clientSecret:c,onClientSecretChange:u,required:!0})}):null,K||!D||U.length===0?null:U.map(Le=>(0,t.jsxs)("div",{children:[(0,t.jsx)("label",{className:"text-sm font-medium text-foreground",children:Qte(s.name,Le.label,U.length)}),(0,t.jsx)(ht,{type:Le.type==="text"&&Le.secret===!1?"text":"password","aria-label":Qte(s.name,Le.label,U.length),autoComplete:"off",value:a[Le.configPath]??"",onChange:r(Qe=>i({...a,[Le.configPath]:Qe.target.value}),"onChange"),placeholder:Le.type==="text"&&Le.secret===!1?Le.placeholder:"••••••••••••••••",className:"mt-2 h-11 font-mono"}),Le.helperMd&&(0,t.jsx)("p",{className:"mt-2 text-xs text-muted-foreground",children:Le.helperMd}),Le.helpUrl&&(0,t.jsxs)("a",{href:Le.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)(ao,{className:"h-3 w-3"})]})]},Le.configPath))]}),Be,(0,t.jsxs)("div",{className:"mt-8 flex items-center justify-between",children:[(0,t.jsx)(L,{variant:"ghost",onClick:R,disabled:C,children:"Back"}),(0,t.jsxs)(L,{onClick:T,disabled:C||!e||!le||!H||!ne||!fe||!Q||!ae,children:[C&&(0,t.jsx)(rt,{className:"mr-2 h-4 w-4 animate-spin"}),C?"Checking…":K?D?.auth==="oauth"?"Validate and continue":"Validate and connect":D?.auth==="oauth"?s.slug==="github"?"Continue to GitHub":"Continue to sign in":"Connect"]})]})]})}r(Ait,"KeyStep");function XSe({value:e,ariaLabel:s}){const{copied:n,failed:a,copy:i}=Cp();return(0,t.jsxs)(L,{type:"button",variant:"outline",className:"shrink-0","aria-label":s,onClick:r(()=>{i(e)},"onClick"),children:[n?(0,t.jsx)(gs,{className:"mr-2 h-4 w-4"}):(0,t.jsx)(Ir,{className:"mr-2 h-4 w-4"}),n?"Copied":a?"Copy failed":"Copy"]})}r(XSe,"CopyValueButton");function c6({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)(ao,{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)(XSe,{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)(ht,{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)(ht,{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(c6,"OAuthClientFields");function use({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)(ci,{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)(Tn,{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)(ht,{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(use,"MethodConfigField");function Tit({companyId:e,...s}){const n=Z({queryKey:P.agents.list(e),queryFn:r(()=>$t.list(e),"queryFn")});return(0,t.jsx)(zW,{...s,agents:(n.data??[]).filter(a=>a.status!=="terminated"),agentsLoading:n.isLoading})}r(Tit,"AccessStep");function zW({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 I=p?.editableAgentIds,R=I?e.filter(U=>I.includes(U.id)):e,T=p?.canSetCompanyInstall??!0,A=p?.canCreateOrganizationGrant??!0,D=n!=="none",M=a??["user","organization"],B=(!D||i==="user"||i==="agent"||A)&&(j?!0:h?d.has(h):i==="agent"?l==="specific"&&d.size===1:l==="all"?T:d.size>0),E=h?e.find(U=>U.id===h)?.name??"the requesting agent":null,z=f?"Connect GitHub as":"Which humans can use this credential?",$=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?",q=f?$:"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:z}),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)(vn,{className:"h-20 w-full rounded-md"}),(0,t.jsx)(vn,{className:"h-20 w-full rounded-md"})]}):D&&M.length===1?(0,t.jsxs)("div",{className:"mt-4 flex items-center gap-3 rounded-md border border-border p-4",children:[M[0]==="user"?(0,t.jsx)(Ph,{className:"h-4 w-4 shrink-0 text-muted-foreground","aria-hidden":"true"}):M[0]==="agent"?(0,t.jsx)(so,{className:"h-4 w-4 shrink-0 text-muted-foreground","aria-hidden":"true"}):(0,t.jsx)(ck,{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:M[0]==="user"?f?"My GitHub account":"Just me":M[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:M[0]==="user"?"Agents use it only for runs where you are the responsible person.":M[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]})]}):D?(0,t.jsx)(wm,{ariaLabel:f?z:"Which humans can use this credential?",className:"mt-4 sm:grid-cols-2",value:i,onValueChange:r(U=>{const O=U;o(O),O==="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)(Ph,{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)(so,{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)(ck,{className:"h-4 w-4","aria-hidden":"true"}),accessibleLabel:A?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:A?void 0:p?.organizationGrantReason??"Only a connection manager can share this credential with the organization.",disabled:!A}].filter(U=>M.includes(U.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:$}),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)(ck,{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:E}),". 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)(wm,{ariaLabel:q,className:"mt-4 sm:grid-cols-2",value:l,onValueChange:r(U=>c(U),"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)(so,{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)(Rit,{}),accessibleLabel:T?"Any agent":`Any agent. Unavailable: ${p?.companyInstallReason??"Only someone who can configure this connection can choose this."}`,tooltip:T?void 0:p?.companyInstallReason??"Only someone who can configure this connection can choose this.",disabled:!T}]}),!j&&!h&&l==="specific"?(0,t.jsx)("div",{className:"mt-3",children:(0,t.jsx)(Zy,{agents:R,selectedAgentIds:d,onChange:r(U=>u(i==="agent"&&U.size>1?new Set([[...U].at(-1)]):U),"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)(L,{variant:"ghost",className:"w-full sm:w-auto",onClick:S,disabled:N,children:"Back"}),(0,t.jsxs)(L,{className:"w-full sm:w-auto",onClick:C,disabled:!B||v||N,children:[N?(0,t.jsx)(rt,{className:"h-4 w-4 animate-spin","aria-hidden":"true"}):null,x,!N&&b?(0,t.jsx)(ao,{className:"h-4 w-4","aria-hidden":"true"}):null]})]})]})}r(zW,"AccessStepContent");function d6(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(d6,"connectionDefaultSummarySentence");function ZSe({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)(gl,{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)(ec,{asChild:!0,children:(0,t.jsx)(L,{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)(xl,{children:(0,t.jsxs)("div",{className:"mt-3 space-y-6",children:[i,s?(0,t.jsx)(zW,{...c,agents:s,bare:!0,hideFooter:!0,submitLabel:"",onBack:r(()=>{},"onBack"),onContinue:r(()=>{},"onContinue")}):(0,t.jsx)(Tit,{...c,companyId:e,bare:!0,hideFooter:!0,submitLabel:"",onBack:r(()=>{},"onBack"),onContinue:r(()=>{},"onContinue")})]})})]})}r(ZSe,"ConnectionAccessDefaults");function Rit(){return(0,t.jsxs)("span",{className:"relative block h-4 w-5","aria-hidden":"true",children:[(0,t.jsx)(so,{className:"absolute left-0 top-0 h-3.5 w-3.5"}),(0,t.jsx)(so,{className:"absolute bottom-0 right-0 h-3.5 w-3.5"})]})}r(Rit,"BotGroupIcon");function Eit(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(Eit,"accessSummaryLines");function Pit({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)(gs,{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)(al,{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)(L,{size:"lg",className:"px-10",onClick:o,children:"View connection"})})]})}r(Pit,"ConnectionSetupCompletionScreen");function eCe(){const{newProjectOpen:e,closeNewProject:s}=FI(),{selectedCompanyId:n}=ps();return n&&e?(0,t.jsx)(Mit,{companyId:n,onClose:s},n):null}r(eCe,"NewProjectDialog");function Mit({companyId:e,onClose:s}){const n=Dt(),[a,i]=(0,m.useState)(""),[o]=(0,m.useState)(()=>y3[Math.floor(Math.random()*y3.length)]),[l,c]=(0,m.useState)([]),[d,u]=(0,m.useState)(!1),h=(0,m.useRef)(null),p=je({mutationFn:r(()=>pa.create(e,{name:a.trim(),color:o,status:"planned",repositoryIds:l.map(f=>f.id)}),"mutationFn"),onSuccess:r(f=>{Q0(f.id,e),n.invalidateQueries({queryKey:P.projects.all(e)}),s()},"onSuccess")});return(0,t.jsx)(Qs,{open:!0,onOpenChange:r(f=>{!f&&!p.isPending&&s()},"onOpenChange"),children:(0,t.jsx)(Js,{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)(Xs,{className:"sr-only",children:"Connect GitHub"}),(0,t.jsx)(c4,{host:"dialog",serviceSlug:"github",forceNewConnection:!0,onCancel:r(()=>u(!1),"onCancel"),onComplete:r(()=>{n.invalidateQueries({queryKey:$9(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)(Xs,{className:"text-lg font-semibold",children:"Create project"}),(0,t.jsx)(L,{type:"button",variant:"ghost",size:"icon-sm",disabled:p.isPending,"aria-label":"Close new project",onClick:s,children:(0,t.jsx)(Fn,{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)(Em,{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)(uwe,{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)(L,{type:"button",variant:"ghost",disabled:p.isPending,onClick:s,children:"Cancel"}),(0,t.jsx)(L,{type:"submit",disabled:!a.trim()||p.isPending,children:p.isPending?"Creating…":"Create project"})]})]})})})}r(Mit,"NewProjectForm");var ng={list:r(e=>Te.get(`/companies/${e}/goals`),"list"),get:r(e=>Te.get(`/goals/${e}`),"get"),create:r((e,s)=>Te.post(`/companies/${e}/goals`,s),"create"),update:r((e,s)=>Te.patch(`/goals/${e}`,s),"update"),remove:r(e=>Te.delete(`/goals/${e}`),"remove")};function tCe(e){return{"--sc":`var(${e})`}}r(tCe,"scStyle");function Dit(e){const s=e.replace(/_/g," ");return s.charAt(0).toUpperCase()+s.slice(1)}r(Dit,"sentenceCaseStatus");function ri({status:e,label:s}){return(0,t.jsx)("span",{className:W("inline-flex items-center rounded-full px-2.5 py-0.5 text-xs font-medium whitespace-nowrap shrink-0",Cz[e]??"bg-muted text-muted-foreground"),children:s??e.replace(/[_-]/g," ")})}r(ri,"StatusBadge$5");function sCe({status:e}){const s=QFe[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:tCe(s),children:n.replace(/_/g," ")})}r(sCe,"AgentStatusBadge");function sp({status:e,externalConversationState:s}){const n=e==="in_review"&&s==="waiting"?"idle":e,a=KFe[n]??"--status-task-backlog";return(0,t.jsxs)("span",{className:W("status-chip inline-flex items-center gap-1.5 rounded-full border px-3 py-1 text-xs font-normal leading-none whitespace-nowrap shrink-0",n==="cancelled"&&"line-through"),style:tCe(a),children:[(0,t.jsx)(OI,{status:n,size:"sm"}),Dit(n)]})}r(sp,"IssueStatusBadge");var mse={company:"Organization",team:"Team",agent:"Agent",task:"Task"};function nCe(){const{newGoalOpen:e,newGoalDefaults:s,closeNewGoal:n}=FI(),{selectedCompanyId:a,selectedCompany:i}=ps(),o=Dt(),[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),[I,R]=(0,m.useState)(!1),T=(0,m.useRef)(null),A=b||s.parentId||"",{data:D}=Z({queryKey:P.goals.list(a),queryFn:r(()=>ng.list(a),"queryFn"),enabled:!!a&&e}),M=je({mutationFn:r(U=>ng.create(a,U),"mutationFn"),onSuccess:r(()=>{o.invalidateQueries({queryKey:P.goals.list(a)}),E(),n()},"onSuccess")}),B=je({mutationFn:r(async U=>{if(!a)throw new Error("No organization selected");return bb.uploadImage(a,U,"goals/drafts")},"mutationFn")});function E(){c(""),u(""),p("planned"),x("task"),v(""),N(!1)}r(E,"reset");function z(){!a||!l.trim()||M.mutate({title:l.trim(),description:d.trim()||void 0,status:h,level:f,...A?{parentId:A}:{}})}r(z,"handleSubmit");function $(U){U.key==="Enter"&&(U.metaKey||U.ctrlKey)&&(U.preventDefault(),z())}r($,"handleKeyDown");const q=(D??[]).find(U=>U.id===A);return(0,t.jsx)(Qs,{open:e,onOpenChange:r(U=>{U||(E(),n())},"onOpenChange"),children:(0,t.jsxs)(Js,{showCloseButton:!1,className:W("p-0 gap-0",j?"sm:max-w-2xl":"sm:max-w-lg"),onKeyDown:$,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)(L,{variant:"ghost",size:"icon-xs",className:"text-muted-foreground",onClick:r(()=>N(!j),"onClick"),children:j?(0,t.jsx)(obe,{className:"h-3.5 w-3.5"}):(0,t.jsx)(Gy,{className:"h-3.5 w-3.5"})}),(0,t.jsx)(L,{variant:"ghost",size:"icon-xs",className:"text-muted-foreground",onClick:r(()=>{E(),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(U=>c(U.target.value),"onChange"),onKeyDown:r(U=>{U.key==="Tab"&&!U.shiftKey&&(U.preventDefault(),T.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)(fd,{ref:T,value:d,onChange:u,placeholder:"Add description...",bordered:!1,contentClassName:W("text-sm text-muted-foreground",j?"min-h-(--sz-220px)":"min-h-(--sz-120px)"),imageUploadHandler:r(async U=>(await B.mutateAsync(U)).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)(gr,{open:w,onOpenChange:k,children:[(0,t.jsx)(Sr,{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)(ri,{status:h})})}),(0,t.jsx)(dr,{className:"w-40 p-1",align:"start",children:qpe.map(U=>(0,t.jsx)("button",{className:W("flex items-center gap-2 w-full px-2 py-1.5 text-xs rounded hover:bg-accent/50 capitalize",U===h&&"bg-accent"),onClick:r(()=>{p(U),k(!1)},"onClick"),children:U},U))})]}),(0,t.jsxs)(gr,{open:S,onOpenChange:C,children:[(0,t.jsx)(Sr,{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)(zl,{className:"h-3 w-3 text-muted-foreground"}),mse[f]??f]})}),(0,t.jsx)(dr,{className:"w-40 p-1",align:"start",children:afe.map(U=>(0,t.jsx)("button",{className:W("flex items-center gap-2 w-full px-2 py-1.5 text-xs rounded hover:bg-accent/50",U===f&&"bg-accent"),onClick:r(()=>{x(U),C(!1)},"onClick"),children:mse[U]??U},U))})]}),(0,t.jsxs)(gr,{open:I,onOpenChange:R,children:[(0,t.jsx)(Sr,{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)(vp,{className:"h-3 w-3 text-muted-foreground"}),q?q.title:"Parent goal"]})}),(0,t.jsxs)(dr,{className:"w-48 p-1",align:"start",children:[(0,t.jsx)("button",{className:W("flex items-center gap-2 w-full px-2 py-1.5 text-xs rounded hover:bg-accent/50",!A&&"bg-accent"),onClick:r(()=>{v(""),R(!1)},"onClick"),children:"No parent"}),(D??[]).map(U=>(0,t.jsx)("button",{className:W("flex items-center gap-2 w-full px-2 py-1.5 text-xs rounded hover:bg-accent/50 truncate",U.id===A&&"bg-accent"),onClick:r(()=>{v(U.id),R(!1)},"onClick"),children:U.title},U.id))]})]})]}),(0,t.jsx)("div",{className:"flex items-center justify-end px-4 py-2.5 border-t border-border",children:(0,t.jsx)(L,{size:"sm",disabled:!l.trim()||M.isPending,onClick:z,children:M.isPending?"Creating…":s.parentId?"Create sub-goal":"Create goal"})})]})})}r(nCe,"NewGoalDialog");function Lit(e){const s=$it(e),n=Oit(e);return`You're invited to join a Paperclip company as an agent.
307
307
 
308
308
  First, respond to your user that you understand the request and are going to onboard into Paperclip. Then work through the steps below.
309
309
 
@@ -352,7 +352,7 @@ After you have connected to Paperclip, review and follow the full onboarding ins
352
352
  `}r(Lit,"buildAgentOnboardingPrompt");function $it(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($it,"buildCandidateOnboardingUrls");function Oit(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(Oit,"buildResolutionTestUrl");var u6=[{name:"Codex",src:"/brands/codex-color.svg",className:""},{name:"ChatGPT",src:"/brands/apps/openai.svg",className:"dark:invert"},{name:"Claude",src:"/brands/claude-color.svg",className:""}];function hse({ref:e,hidden:s}){return(0,t.jsx)("span",{ref:e,className:"agent-setup-logos","data-hidden":s,"aria-hidden":"true",children:u6.map(n=>(0,t.jsx)("span",{className:"agent-setup-logo-slot",children:(0,t.jsx)("span",{className:"agent-setup-logo",children:(0,t.jsx)("img",{src:n.src,alt:"",className:W("size-5",n.className),draggable:!1})})},n.name))})}r(hse,"AgentLogos");function Y$(e){return Array.from(e?.querySelectorAll(".agent-setup-logo")??[]).map(s=>{const n=s.getBoundingClientRect(),a=getComputedStyle(s).transform,i=a&&a!=="none"?new DOMMatrixReadOnly(a):null;return{left:n.left+(n.width-s.offsetWidth)/2,top:n.top+(n.height-s.offsetHeight)/2,width:s.offsetWidth,height:s.offsetHeight,transform:`rotate(${i?Math.atan2(i.b,i.a)*180/Math.PI:0}deg)`}})}r(Y$,"readLogoPositions");function ej({prompt:e,title:s="Agent setup",description:n="Paste this into your agent to take care of setup.",label:a="Set up with an agent",variant:i="outline",side:o="top",align:l="start",className:c,initialCopyStatus:d="idle",onCopied:u}){const h=(0,m.useId)(),p=yxe(),[f,x]=(0,m.useState)(!1),[b,v]=(0,m.useState)(d),[j,N]=(0,m.useState)(null),w=(0,m.useRef)(null),k=(0,m.useRef)(null),S=(0,m.useRef)(null),C=(0,m.useRef)(null),I=(0,m.useRef)(0),R=(0,m.useRef)(!1),T=(0,m.useRef)(!1),A=(0,m.useRef)(null);(0,m.useEffect)(()=>(v("idle"),T.current=!1,R.current=!1,()=>{I.current+=1}),[e]),(0,m.useEffect)(()=>{R.current||v(d)},[e,d]),(0,m.useEffect)(()=>{if(b!=="copied")return;const B=_5("--agent-setup-copied-hold");if(B<=0)return;const E=window.setTimeout(()=>v("idle"),B);return()=>window.clearTimeout(E)},[b]),(0,m.useLayoutEffect)(()=>{if(!j)return;if(p||typeof Element.prototype.animate!="function"){N(null);return}let B,E=!1,z=[];const $=r(()=>{E||N(null)},"finish"),q=r(()=>{const U=j.toPreview?k.current:w.current;if(!U||j.toPreview&&!getComputedStyle(U).getPropertyValue("--radix-popover-content-transform-origin").trim()){B=requestAnimationFrame(q);return}const O=Y$(U),K=S.current?.querySelectorAll(".agent-setup-logo"),H=getComputedStyle(document.documentElement).getPropertyValue("--motion-ease-out-expo").trim();z=Array.from(K??[]).map((ee,se)=>ee.animate([j.origins[se],O[se]].map(({left:ne,top:fe,transform:X})=>({left:`${ne}px`,top:`${fe}px`,transform:X})),{duration:_5("--agent-setup-flight-duration"),easing:H,fill:"both"})),Promise.all(z.map(ee=>ee.finished)).then($,()=>{})},"start");return B=requestAnimationFrame(q),window.addEventListener("resize",$),document.addEventListener("scroll",$,!0),()=>{E=!0,cancelAnimationFrame(B),z.forEach(U=>U.cancel()),window.removeEventListener("resize",$),document.removeEventListener("scroll",$,!0)}},[j,p]);function D(B){const E=C.current??Y$(S.current??(f?k.current:w.current));C.current=null,N(!p&&E.length===u6.length?{origins:E,toPreview:B}:null),x(B)}r(D,"changeOpen");async function M(){if(T.current||!e.trim())return;R.current=!0,T.current=!0;const B=++I.current;v("copying");try{await fa(e),B===I.current&&(v("copied"),u?.())}catch{B===I.current&&v("failed")}finally{B===I.current&&(T.current=!1)}}return r(M,"copyPrompt"),(0,t.jsxs)(t.Fragment,{children:[(0,t.jsxs)(gr,{open:f,onOpenChange:D,children:[(0,t.jsx)(Sr,{asChild:!0,children:(0,t.jsxs)(L,{type:"button",variant:i,"aria-label":a,"data-copied":b==="copied",onClick:r(B=>{f?B.preventDefault():C.current=Y$(S.current??w.current),M()},"onClick"),className:W("agent-setup-trigger h-auto min-h-10 max-w-full gap-3 whitespace-normal text-left",i==="ghost"&&"w-full justify-start",c),children:[b==="copied"?(0,t.jsx)(gs,{className:"agent-setup-check size-4"}):(0,t.jsx)(mg,{className:"size-4 text-muted-foreground"}),(0,t.jsxs)("span",{className:"relative min-w-0",children:[(0,t.jsx)("span",{className:b==="copied"?"invisible":void 0,children:a}),b==="copied"&&(0,t.jsx)("span",{className:"agent-setup-confirmation absolute inset-0 flex items-center",children:"Copied!"})]}),(0,t.jsx)("span",{className:"agent-setup-trigger-logos",children:(0,t.jsx)(hse,{ref:w,hidden:f||!!j})})]})}),(0,t.jsxs)(dr,{side:o,align:l,collisionPadding:Tm("--agent-setup-collision-padding"),className:"agent-setup-popover flex flex-col gap-4 rounded-xl p-4","aria-labelledby":`${h}-title`,"aria-describedby":`${h}-description`,onOpenAutoFocus:r(B=>{B.preventDefault(),A.current?.focus()},"onOpenAutoFocus"),onFocusOutside:r(B=>{T.current&&B.preventDefault()},"onFocusOutside"),children:[(0,t.jsxs)("div",{className:"flex items-start gap-3",children:[(0,t.jsxs)("div",{className:"flex min-w-0 flex-1 flex-col gap-1",children:[(0,t.jsx)("h2",{id:`${h}-title`,className:"text-sm font-semibold",children:s}),(0,t.jsx)("p",{id:`${h}-description`,className:"text-sm leading-relaxed text-muted-foreground",children:n})]}),(0,t.jsx)(L,{type:"button",variant:"ghost",size:"icon-xs","aria-label":"Close agent setup",onClick:r(()=>D(!1),"onClick"),children:(0,t.jsx)(Fn,{className:"size-3.5"})})]}),(0,t.jsxs)("div",{className:"agent-setup-preview-wrap relative pt-2",children:[(0,t.jsx)("div",{className:"agent-setup-preview-logos absolute right-3 top-0 z-10",children:(0,t.jsx)(hse,{ref:k,hidden:!!j})}),b==="failed"?(0,t.jsx)(Tn,{"aria-label":"Setup prompt",readOnly:!0,value:e,onFocus:r(B=>B.currentTarget.select(),"onFocus"),className:"agent-setup-preview resize-none rounded-lg bg-muted/50 p-3 pt-5 font-mono text-xs leading-relaxed"}):(0,t.jsx)("pre",{tabIndex:0,"aria-label":"Setup prompt",className:"agent-setup-preview m-0 overflow-auto whitespace-pre-wrap break-words rounded-lg border border-border/60 bg-muted/50 p-3 pt-5 font-mono text-xs leading-relaxed text-muted-foreground",children:e})]}),(0,t.jsxs)("div",{className:"flex flex-col gap-2",children:[b==="failed"&&(0,t.jsx)("p",{role:"alert",className:"text-xs text-destructive",children:"Could not copy automatically. Select and copy the prompt above, or try again."}),(0,t.jsxs)(L,{ref:A,type:"button",variant:"cta",className:"agent-setup-copy w-full","data-copied":b==="copied","aria-disabled":b==="copying"||!e.trim(),onClick:r(()=>{e.trim()&&M()},"onClick"),children:[b==="copied"?(0,t.jsx)(gs,{className:"agent-setup-check size-4"}):(0,t.jsx)(Ir,{className:"size-4"}),b==="copied"?"Copied to clipboard":b==="copying"?"Copying…":b==="failed"?"Try copying again":"Copy prompt"]}),(0,t.jsx)("p",{className:"text-center text-xs text-muted-foreground",children:b==="copied"?"Ready to paste into your agent.":"Works with Codex, ChatGPT, Claude, and more."})]})]})]}),(0,t.jsx)("span",{role:"status",className:"sr-only",children:b==="copied"?"Setup prompt copied. Ready to paste into your agent.":""}),j&&(0,hp.createPortal)((0,t.jsx)("span",{ref:S,className:"agent-setup-flight-layer","aria-hidden":"true",children:u6.map((B,E)=>(0,t.jsx)("span",{className:"agent-setup-logo agent-setup-flying-logo",style:j.origins[E],children:(0,t.jsx)("img",{src:B.src,alt:"",className:W("size-5",B.className),draggable:!1})},B.name))}),document.body)]})}r(ej,"AgentSetupPrompt");function Fit({companyId:e,onClose:s,onBack:n}){const a=Dt(),i=(0,m.useRef)(!0);(0,m.useEffect)(()=>(i.current=!0,()=>{i.current=!1}),[]);const[o,l]=(0,m.useState)(""),[c,d]=(0,m.useState)(null),u=c?.prompt,h=je({mutationFn:r(async()=>{const p=await pr.createCompanyInvite(e,{allowedJoinTypes:"agent",humanRole:null,agentMessage:o.trim()||null});a.invalidateQueries({queryKey:P.access.invites(e,"all",5)});const f=p.onboardingTextUrl??p.onboardingTextPath??`/api/invites/${p.token}/onboarding.txt`,x=new URL(f,window.location.origin).href,b=await pr.getInviteOnboarding(p.token).catch(()=>null);return Lit({onboardingTextUrl:x,connectionCandidates:b?.onboarding.connectivity?.connectionCandidates??null,testResolutionUrl:b?.onboarding.connectivity?.testResolutionEndpoint?.url??null})},"mutationFn"),onSuccess:r(async p=>{if(!i.current)return;d({prompt:p,copyStatus:"idle"});let f="copied";try{await fa(p)}catch{f="failed"}i.current&&d(x=>x?.copyStatus==="idle"?{...x,copyStatus:f}:x)},"onSuccess")});return(0,t.jsx)(Qs,{open:!0,onOpenChange:r(p=>{p||s()},"onOpenChange"),children:(0,t.jsxs)(Js,{className:"max-h-(--sz-calc-16) overflow-y-auto sm:max-w-2xl",children:[(0,t.jsx)(Xs,{children:u?"Agent onboarding prompt":"Invite an external agent"}),(0,t.jsx)(jn,{children:u?"Send this one-time prompt to the agent that should join your organization.":"Generate a one-time onboarding prompt for an external agent. An organization admin must approve its join request before it can claim an API key."}),u?(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)(Tn,{"aria-label":"Agent onboarding prompt",readOnly:!0,value:u,className:"min-h-64 font-mono text-xs"}),c?.copyStatus==="failed"&&(0,t.jsx)("p",{role:"alert",className:"text-sm text-muted-foreground",children:"Clipboard unavailable. Copy the prompt manually from the field above, or use the button below to try again."}),(0,t.jsxs)("div",{className:"flex flex-wrap items-center justify-between gap-4",children:[(0,t.jsx)(L,{variant:"ghost",onClick:s,children:"Done"}),(0,t.jsx)(ej,{prompt:u,label:"Copy onboarding prompt",title:"Invite your agent",description:"Paste this into your external agent to request access to your organization.",initialCopyStatus:c?.copyStatus,onCopied:r(()=>d(p=>p&&{...p,copyStatus:"copied"}),"onCopied")})]})]}):(0,t.jsxs)(t.Fragment,{children:[(0,t.jsxs)("label",{className:"space-y-2 text-sm",children:[(0,t.jsx)("span",{children:"Optional message for the agent"}),(0,t.jsx)(Tn,{value:o,onChange:r(p=>l(p.target.value),"onChange"),maxLength:4e3,className:"min-h-24"})]}),h.error&&(0,t.jsx)("p",{role:"alert",className:"text-sm text-destructive",children:h.error.message}),(0,t.jsxs)("div",{className:"flex justify-between gap-4",children:[(0,t.jsx)(L,{variant:"ghost",onClick:n,children:"Back"}),(0,t.jsx)(L,{disabled:h.isPending,onClick:r(()=>h.mutate(),"onClick"),children:h.isPending?"Generating…":"Generate onboarding prompt"})]})]})]})})}r(Fit,"ExternalAgentInviteDialog");function rCe(){const{newAgentOpen:e,closeNewAgent:s}=FI(),{selectedCompanyId:n}=ps();return e?(0,t.jsx)(Bit,{companyId:n,onClose:s},n):null}r(rCe,"NewAgentDialog");function Bit({companyId:e,onClose:s}){const n=Mn(),[a,i]=(0,m.useState)(!1);return a&&e?(0,t.jsx)(Fit,{companyId:e,onClose:s,onBack:r(()=>i(!1),"onBack")}):(0,t.jsx)(FSe,{open:!0,onClose:s,onInvite:e?()=>i(!0):void 0,onContinue:r(o=>{s(),n(`/agents/new?${new URLSearchParams(o)}`)},"onContinue")})}r(Bit,"NewAgentDialogContent");var zit=[{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 pse({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(pse,"KeyCap");function qit(){return(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)("div",{className:"divide-y divide-border border-t border-border",children:zit.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)(pse,{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)(pse,{children:"Esc"})," to close · Shortcuts are disabled in text fields"]})})]})}r(qit,"KeyboardShortcutsCheatsheetContent");function aCe({open:e,onOpenChange:s}){return(0,t.jsx)(Qs,{open:e,onOpenChange:s,children:(0,t.jsxs)(Js,{className:"sm:max-w-md gap-0 p-0 overflow-hidden",showCloseButton:!1,children:[(0,t.jsx)(hn,{className:"px-5 pt-5 pb-3",children:(0,t.jsx)(Xs,{className:"text-base",children:"Keyboard shortcuts"})}),(0,t.jsx)(qit,{})]})})}r(aCe,"KeyboardShortcutsCheatsheet");var Uit={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"},Kit={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 Wit({toast:e,onDismiss:s}){const[n,a]=(0,m.useState)(!1);return(0,m.useEffect)(()=>{const i=requestAnimationFrame(()=>a(!0));return()=>cancelAnimationFrame(i)},[]),(0,t.jsx)("li",{className:W("pointer-events-auto rounded-sm border shadow-lg backdrop-blur-xl transition-(--tp-transform-opacity) duration-200 ease-out",n?"translate-y-0 opacity-100":"translate-y-3 opacity-0",Uit[e.tone]),children:(0,t.jsxs)("div",{className:"flex items-start gap-3 px-3 py-2.5",children:[(0,t.jsx)("span",{className:W("mt-1 h-2 w-2 shrink-0 rounded-full",Kit[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)(Ke,{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)(Fn,{className:"h-3.5 w-3.5"})})]})})}r(Wit,"AnimatedToast");function iCe(){const e=cye(),{dismissToast:s}=da();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)(Wit,{toast:n,onDismiss:s},n.id))})})}r(iCe,"ToastViewport");async function fse(e,s){const n=await fetch(`/api/announcements/${e}`,{credentials:"same-origin",cache:"no-store",...s});if(!n.ok)throw new dn("Announcement request failed",n.status,null);return n}r(fse,"request");var xse={async current(e){const s=await(await fse("current",{signal:e})).json();return s===null?null:o$e.parse(s)},async dismiss(e,s,n){await fse(`${encodeURIComponent(e)}/dismiss`,{method:"POST",signal:n,headers:{"Content-Type":"application/json"},body:JSON.stringify({companyId:s})})}},m6=new Map;function qW(e){return`paperclip.announcement-dismissals.v1:${encodeURIComponent(e)}:`}r(qW,"announcementStoragePrefix");function Q2(e){const s=qW(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);Vpe.safeParse(o).success&&(l==="pending"||l==="synced")&&m6.set(i,l==="pending")}}catch{}for(const[a,i]of m6)a.startsWith(s)&&n.set(a.slice(s.length),i);return n}r(Q2,"readAnnouncementDismissals");function J$(e,s,n){const a=`${qW(e)}${s}`;m6.set(a,n);try{return localStorage.setItem(a,n?"pending":"synced"),!0}catch{return!1}}r(J$,"saveAnnouncementDismissal");var Vit=3e3;function Hit(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=qW(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(A,D=!0){if(!j()||f.has(A)||!a.current.companyId)return;const M=new AbortController;f.set(A,M);const B=setTimeout(()=>M.abort(),1e4);try{await xse.dismiss(A,a.current.companyId,M.signal),j()&&J$(s,A,!1)}catch{j()&&!x.has(A)&&(x.add(A),a.current.onSaveFailure(D))}finally{clearTimeout(B),f.delete(A)}}r(N,"sync");async function w(){for(const[A,D]of Q2(s)){if(!j())return;D&&await N(A)}}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 A=u,D=new AbortController;h=D;const M=r(()=>j()&&u===A&&!D.signal.aborted,"stillCurrent");let B=!1,E=!1,z=null;const $=r(()=>{!M()||!B||!E||z&&!Q2(s).has(z.id)&&(!z.expiresAt||Date.parse(z.expiresAt)>Date.now())&&o({userId:s,announcement:z})},"show");p=setTimeout(()=>{B=!0,$()},Vit),w(),xse.current(D.signal).then(q=>{z=q,E=!0,$()}).catch(()=>{})}r(S,"resume");function C(){const A=Q2(s);o(D=>D?.userId===s&&A.has(D.announcement.id)?null:D)}r(C,"receive");function I(A){A.key?.startsWith(b)&&C()}r(I,"onStorage");function R(){document.visibilityState==="hidden"?k():S()}r(R,"onVisibility");function T(){w()}return r(T,"onOnline"),v&&(v.onmessage=A=>{const D=Vpe.safeParse(A.data);D.success&&(Q2(s).has(D.data)||J$(s,D.data,!0),C())}),l.current=A=>{if(!j())return;const D=J$(s,A,!0);o(null),u++,h?.abort();try{v?.postMessage(A)}catch{}N(A,D)},document.addEventListener("visibilitychange",R),window.addEventListener("online",T),window.addEventListener("storage",I),S(),()=>{d=!0,u++,clearTimeout(p),h?.abort();for(const A of f.values())A.abort();v?.close(),document.removeEventListener("visibilitychange",R),window.removeEventListener("online",T),window.removeEventListener("storage",I),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(Hit,"useAnnouncement");function Git(e,s){const n=yxe(),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="${BLe}">${p}`})}catch{}finally{clearTimeout(u)}})(),()=>{d.abort(),clearTimeout(u)}},[c,i,a]),c&&o?.key===i?o.document:null}r(Git,"useAnnouncementAnimation");function gse({action:e,primary:s,onClick:n}){const a=(0,t.jsxs)(t.Fragment,{children:[e.label,!s&&e.kind==="external"&&(0,t.jsx)(ao,{className:"size-3.5 shrink-0","aria-hidden":"true"})]}),i=r(o=>{o.button===1&&n()},"onAuxClick");return(0,t.jsx)(L,{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)(Ke,{to:e.path,onClick:n,onAuxClick:i,children:a})})}r(gse,"Action");function yE({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=Git(e,a),p=!!h;return(0,t.jsxs)(rn,{role:"region","aria-labelledby":o,className:W("relative w-full max-w-(--announcement-width) gap-0 overflow-hidden rounded-xl p-0 shadow-sm",i),onKeyDown:r(f=>{f.key==="Escape"&&(f.preventDefault(),f.stopPropagation(),s())},"onKeyDown"),children:[(u||h)&&(0,t.jsxs)("div",{className:"relative h-(--announcement-image-mobile-height) w-full shrink-0 overflow-hidden bg-muted md:h-(--announcement-image-height)",children:[u&&(0,t.jsx)("img",{src:d,alt:p?"":e.image.alt,referrerPolicy:"no-referrer",onError:r(()=>c(d),"onError"),className:"h-full w-full object-cover"}),p&&(0,t.jsx)("div",{role:"img","aria-label":e.animation.alt,className:"pointer-events-none absolute inset-0",children:(0,t.jsx)("iframe",{title:e.animation.alt,"aria-hidden":"true",tabIndex:-1,sandbox:"",referrerPolicy:"no-referrer",srcDoc:h,className:"h-full w-full border-0"})})]}),(0,t.jsx)(L,{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)(Fn,{className:"size-4","aria-hidden":"true"})}),(0,t.jsxs)("div",{className:W("flex flex-col gap-1 px-4 py-4",!u&&!h&&"pr-12"),children:[(0,t.jsx)("p",{className:"text-xs text-muted-foreground",children:e.eyebrow}),(0,t.jsx)("h2",{id:o,className:"break-words text-base font-semibold leading-snug",children:e.title}),(0,t.jsx)("p",{className:"break-words text-sm leading-snug text-muted-foreground",children:e.description})]}),(0,t.jsxs)("div",{className:"flex flex-wrap items-center justify-between gap-2 border-t px-3 py-2",children:[e.secondaryLink&&(0,t.jsx)(gse,{action:e.secondaryLink,onClick:s}),(0,t.jsx)("div",{className:"ml-auto min-w-0 max-w-full",children:(0,t.jsx)(gse,{action:e.primaryAction,primary:!0,onClick:s})})]})]})}r(yE,"AnnouncementCard");var Qit='[role="dialog"][data-state="open"], [role="alertdialog"][data-state="open"], [aria-modal="true"]:not([data-state="closed"]), dialog[open]';function Yit(e){const[s,n]=(0,m.useState)(!1);return(0,m.useEffect)(()=>{if(!e)return;const a=r(()=>n(!!document.querySelector(Qit)),"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(Yit,"useModalOpen");function Jit({health:e}){const{userId:s,settled:n}=Vf(),{selectedCompanyId:a,loading:i}=ps(),{onboardingOpen:o}=yM(),l=Xc(),c=wKe(),d=e?.deploymentMode==="local_trusted"?"local-board":n?s:null,{announcement:u,dismiss:h}=Hit({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=Yit(!!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)(yE,{announcement:u,onDismiss:r(()=>h(u.id),"onDismiss")},u.id)})}r(Jit,"AnnouncementWell");function d4(e){const s=e.split("/").filter(Boolean);return s.length===1?s[0]?.toLowerCase()==="onboarding":s.length===2?s[1]?.toLowerCase()==="onboarding":!1}r(d4,"isOnboardingPath");function Xit(e){const s=e.split("/").filter(Boolean);if(s.length===2&&s[1]?.toLowerCase()==="onboarding")return s[0]}r(Xit,"companyPrefixFromOnboardingPath");function D5(){return 3}r(D5,"onboardingStepForCompany");function Zit(e){const{pathname:s,companyPrefix:n,companies:a,cloudManaged:i}=e;if(!d4(s))return null;const o=r(()=>a.length===1?{initialStep:D5(),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:D5(),companyId:l.id}:i?o():{initialStep:1}}r(Zit,"resolveRouteOnboardingOptions");function eot(e){return!e.agentsLoaded||e.agentsRefreshing||e.agentCount>0?!1:!d4(e.pathname)}r(eot,"shouldRouteAgentlessCompanyToOnboarding");function tot(e){return e.currentStep>1&&e.currentStep>e.entryStep}r(tot,"canGoBackFromOnboardingStep");function bse(e){return e.targetStep<e.currentStep&&e.targetStep>=e.entryStep}r(bse,"canJumpToOnboardingStep");function UW(e){return!e.hasCompanies&&!d4(e.pathname)}r(UW,"shouldRedirectCompanylessRouteToOnboarding");function sot(e){return e.onboardingOpen||!e.routeDismissed}r(sot,"isOnboardingWizardActive");function not({context:e}){const{slots:s,errorMessage:n}=bd({slotTypes:["appShellOverlay"],companyId:e.companyId});return n||s.length===0?null:(0,t.jsx)("aside",{className:"plugin-app-shell-overlays","aria-label":"Application extensions",children:s.map(a=>(0,t.jsx)(Wu,{slot:a,context:e,className:"plugin-app-shell-overlay"},`${a.pluginId}:${a.pluginVersion}:${a.id}`))})}r(not,"AppShellEntries");function oCe({localTrusted:e=!1}){const{userId:s,settled:n}=Vf(),{selectedCompanyId:a,selectedCompany:i,loading:o}=ps(),{onboardingOpen:l,onboardingRouteDismissed:c}=yM(),{pathname:d}=na(),u=n?s??(e?"local-board":null):null,h=l||!c&&d4(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)(not,{context:p},JSON.stringify([u,a]))}r(oCe,"PluginAppShellOverlays");function lCe({visible:e}){const s=na(),{selectedCompanyId:n}=ps(),{openNewIssue:a}=Qo(),i=$M(n),{enabled:o}=Yy(),{enabled:l}=sA(),c=(0,m.useMemo)(()=>!o&&!l?[{type:"link",to:"/dashboard",label:"Home",icon:$z},{type:"link",to:"/issues",label:"Tasks",icon:ca},{type:"action",label:"New Task",icon:p_,onClick:r(()=>a(),"onClick")},{type:"link",to:"/agents/all",label:"Agents",icon:Vo},{type:"link",to:"/inbox",label:"Inbox",icon:hd,badge:i.inbox}]:[{type:"link",to:"/dashboard",label:"Home",icon:$z},...o?[{type:"link",to:"/chats",label:"Chat",icon:h_}]:[],{type:"action",label:"New Task",icon:p_,onClick:r(()=>a(),"onClick")},{type:"link",to:"/issues",label:"Tasks",icon:ca,badge:l?i.inbox:void 0},{type:"link",to:"/agents/all",label:"Agents",icon:Vo},...l?[]:[{type:"link",to:"/inbox",label:"Inbox",icon:hd,badge:i.inbox}]],[a,i.inbox,o,l]);return(0,t.jsx)("nav",{className:W("mobile-bottom-nav fixed bottom-0 left-0 right-0 z-30 bg-muted md:hidden pb-(--sz-safe-bottom)"),"data-visible":e,inert:!e,"aria-label":"Mobile navigation",children:(0,t.jsx)("div",{className:"grid h-16 px-1",style:{gridTemplateColumns:`repeat(${c.length}, minmax(0, 1fr))`},children:c.map(d=>{if(d.type==="action"){const h=d.icon,p=/\/issues\/new(?:\/|$)/.test(s.pathname);return(0,t.jsxs)("button",{type:"button",onClick:d.onClick,className:W("relative flex min-w-0 flex-col items-center justify-center gap-1 rounded-md text-(length:--text-nano) font-medium transition-colors",p?"text-foreground":"text-muted-foreground hover:text-foreground"),children:[(0,t.jsx)(h,{className:"h-(--sz-18px) w-(--sz-18px)"}),(0,t.jsx)("span",{className:"truncate",children:d.label})]},d.label)}const u=d.icon;return(0,t.jsx)(ub,{to:d.to,state:Gf,className:r(({isActive:h})=>W("relative flex min-w-0 flex-col items-center justify-center gap-1 rounded-md text-(length:--text-nano) font-medium transition-colors",h?"text-foreground":"text-muted-foreground hover:text-foreground"),"className"),children:r(({isActive:h})=>(0,t.jsxs)(t.Fragment,{children:[(0,t.jsxs)("span",{className:"relative",children:[(0,t.jsx)(u,{className:W("h-(--sz-18px) w-(--sz-18px)",h&&"stroke-(length:--sw-2_3)")}),d.badge!=null&&d.badge>0&&(0,t.jsx)(ct,{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(lCe,"MobileBottomNav");function Hw(e){if(typeof document>"u")return null;const s=document.querySelector(`meta[name="${e}"]`)?.getAttribute("content")?.trim();return s||null}r(Hw,"readMetaContent");function h6(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(h6,"normalizeHexColor");function rot(e){const s=h6(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(rot,"hexToRgb");function X$(e){const s=e/255;return s<=.03928?s/12.92:((s+.055)/1.055)**2.4}r(X$,"relativeLuminanceChannel");function aot(e){const{r:s,g:n,b:a}=rot(e),i=.2126*X$(s)+.7152*X$(n)+.0722*X$(a);return 1.05/(i+.05)>=(i+.05)/.05?fFe:mFe}r(aot,"pickReadableTextColor");function iot(){return Hw("paperclip-worktree-enabled")==="true"}r(iot,"isWorktreeRuntime");function oot(){return Hw("paperclip-instance-id")}r(oot,"getWorktreeInstanceId");function lot(){if(Hw("paperclip-worktree-enabled")!=="true")return null;const e=Hw("paperclip-worktree-name"),s=h6(Hw("paperclip-worktree-color"));return!e||!s?null:{enabled:!0,name:e,color:s,textColor:h6(Hw("paperclip-worktree-text-color"))??aot(s)}}r(lot,"getWorktreeUiBranding");function cCe(){const e=lot(),{copied:s,failed:n,copy:a}=Cp(),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(cCe,"WorktreeBanner");var cot=3e4;function dot(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(dot,"formatRelativeTimestamp");function uot(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(uot,"describeReason");function dCe({devServer:e}){const[s,n]=(0,m.useState)(!1);if((0,m.useEffect)(()=>{if(!s)return;const d=window.setTimeout(()=>{n(!1)},cot);return()=>window.clearTimeout(d)},[s]),!e?.enabled||!e.restartRequired)return null;const a=e,i=dot(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 tu.requestDevServerRestart()}catch(u){n(!1),window.alert(u instanceof Error?u.message:"Failed to request restart")}}}return r(c,"requestRestartNow"),(0,t.jsx)("div",{className:"border-b border-amber-300/60 bg-amber-50 text-amber-950 dark:border-amber-500/25 dark:bg-amber-500/10 dark:text-amber-100",children:(0,t.jsxs)("div",{className:"flex flex-col gap-3 px-3 py-2.5 md:flex-row md:items-center md:justify-between",children:[(0,t.jsxs)("div",{className:"min-w-0",children:[(0,t.jsxs)("div",{className:"flex items-center gap-2 text-xs font-semibold uppercase tracking-(--tracking-caps)",children:[(0,t.jsx)(Es,{className:"h-3.5 w-3.5 shrink-0"}),(0,t.jsx)("span",{children:"Restart Required"}),e.autoRestartEnabled?(0,t.jsx)(ct,{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:[uot(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)(Aqe,{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)(Ci,{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)(Ci,{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)(Ci,{className:"h-3.5 w-3.5"}),(0,t.jsx)("span",{children:s?"Restart requested":"Restart now"})]})]})]})})}r(dCe,"DevRestartBanner");var uCe=["standalone","fullscreen","window-controls-overlay"];function mot(e){return`(display-mode: ${e})`}r(mot,"displayModeQuery");function hot(){if(!(typeof window>"u"||typeof window.matchMedia!="function"))return window.matchMedia.bind(window)}r(hot,"defaultMatchMedia");function p6(e=hot(),s=typeof navigator>"u"?void 0:navigator.standalone){return s===!0?!0:e?uCe.some(n=>e(mot(n)).matches):!1}r(p6,"isChromelessDisplayMode");function Y2({label:e,children:s,onClick:n}){return(0,t.jsxs)(zn,{children:[(0,t.jsx)(qn,{asChild:!0,children:(0,t.jsx)(L,{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)(Un,{children:e})]})}r(Y2,"ControlButton");function pot(e=typeof window>"u"?null:window.history.state){const s=e?.idx;return typeof s=="number"&&s>0}r(pot,"hasInAppHistory");function fot(){const[e,s]=(0,m.useState)(()=>typeof window<"u"?p6():!1);return(0,m.useEffect)(()=>{if(typeof window>"u")return;const n=r(()=>s(p6()),"update");if(n(),typeof window.matchMedia!="function")return;const a=uCe.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(fot,"useChromeless");function f6({mobile:e,onNavigateHome:s}){const n=fot(),a=Xc(),i=(0,m.useCallback)(()=>{if(pot()){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 fa(d),a?.pushToast({title:"Link copied",tone:"success"})}catch(u){if(u instanceof DOMException&&u.name==="AbortError")return;a?.pushToast({title:"Share failed",body:"Try opening the page in your browser.",tone:"error"})}},[a]),c=(0,m.useCallback)(()=>{window.open(window.location.href,"_blank","noopener,noreferrer")},[]);return n?(0,t.jsxs)("div",{className:W("flex items-center gap-1",e?"h-10 border-b border-border bg-background/95 px-3 backdrop-blur supports-[backdrop-filter]:bg-background/85":"h-9 border-b border-border px-2"),children:[(0,t.jsx)(Y2,{label:"Back",onClick:i,children:(0,t.jsx)(Tl,{className:"h-4 w-4"})}),(0,t.jsx)("div",{className:"flex-1"}),(0,t.jsx)(Y2,{label:"Refresh",onClick:o,children:(0,t.jsx)(_i,{className:"h-4 w-4"})}),(0,t.jsx)(Y2,{label:"Share",onClick:l,children:(0,t.jsx)(O7,{className:"h-4 w-4"})}),(0,t.jsx)(Y2,{label:"Open in Browser",onClick:c,children:(0,t.jsx)(Vn,{className:"h-4 w-4"})})]}):null}r(f6,"StandaloneBrowserControls");var xot=16384,got=40;function bot(e){if(!e)return;const s=[];for(const n of e.slice(0,xot).split(`
353
353
  `).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===got)break}return s.length?`
354
354
  ${s.join(`
355
- `)}`:void 0}r(bot,"sanitizeComponentStack");function mCe(){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(mCe,"readBrowserErrorState");function vot(e){const s=bot(e.componentStack);return{tags:{react_error_boundary:e.boundary},contexts:{react:s?{componentStack:s}:{},browser_state:mCe()}}}r(vot,"buildBrowserErrorContext");var vse=Promise.resolve();function KW(e){const s=vse.then(e);return vse=s.catch(()=>{}),s}r(KW,"enqueue");var mN=null;function yot(e,s){return KW(async()=>{if(!mN)try{const n=await Jc(()=>import("./prod-COP_vZWu.js"),__vite__mapDeps([4,5]));n.init(wot(e,s)),mN=n}catch{}})}r(yot,"initBrowserErrorMonitoring");function jot(){return KW(async()=>{const e=mN;if(mN=null,!e)return;const s=e.getClient();try{e.getCurrentScope().setClient(void 0)}catch{}try{await s?.close(2e3)}catch{}})}r(jot,"teardownBrowserErrorMonitoring");function hCe(e,s){let n;try{s&&(n=vot(s))}catch{}KW(async()=>{try{n?mN?.captureException(e,n):mN?.captureException(e)}catch{}})}r(hCe,"captureBrowserException");function wot(e,s){return{dsn:e,environment:s??void 0,release:"2c5221118b0c598817a4f8bc423756826bc4e5ff",tracesSampleRate:0,sendDefaultPii:!1,beforeSend:r((n,a)=>{try{if(n.contexts={...n.contexts,browser_state:n.contexts?.browser_state??mCe()},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(wot,"buildBrowserSentryInitOptions");var kot=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){hCe(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)(L,{variant:"outline",size:"sm",onClick:this.props.onReset,children:"Go back"}),(0,t.jsx)(L,{size:"sm",onClick:r(()=>window.location.reload(),"onClick"),children:"Reload page"})]})]}):this.props.children}};function pCe({children:e}){const s=na(),n=Mn(),a=`${s.pathname}${s.search}`;return(0,t.jsx)(kot,{resetKey:a,onReset:r(()=>n(-1),"onReset"),children:e})}r(pCe,"RouteErrorBoundary");var yse={bot:so,cpu:ym,brain:Jx,zap:C3,rocket:C$e,code:fxe,terminal:mg,shield:RI,eye:Pd,search:oa,wrench:Ef,hammer:cM,lightbulb:TI,sparkles:Np,star:yp,heart:OC,flame:X$e,bug:Uv,cog:dfe,database:EI,globe:Ap,lock:pd,mail:a7,"message-square":Yx,"file-code":Ll,"git-branch":io,package:Th,puzzle:Xx,target:vp,wand:z7,atom:V$e,"circuit-board":Hze,radar:N$e,swords:_qe,telescope:E$e,microscope:uqe,crown:cfe,gem:xxe,hexagon:Td,pentagon:fqe,fingerprint:Lz},Not="bot";function Sot(e){return e&&PLe.includes(e)?yse[e]:yse[Not]}r(Sot,"getAgentIcon");function L5({icon:e,className:s}){const n=Sot(e);return(0,t.jsx)(n,{className:s})}r(L5,"AgentIcon");function fCe({open:e,onOpenChange:s,...n}){return(0,t.jsx)(Qs,{open:e,onOpenChange:s,children:(0,t.jsxs)(Js,{"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)(Xs,{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)(Cot,{...n,onComplete:r(()=>s(!1),"onComplete")},String(e))]})})}r(fCe,"AgentChatPicker");function Cot({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)($I,{children:[(0,t.jsx)(WN,{"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)(L,{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)(KN,{children:[(0,t.jsx)(UN,{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)(L,{variant:"ghost",size:"sm",onClick:r(()=>p(""),"onClick"),children:"Clear search"})]}):(0,t.jsx)("span",{className:"text-xs text-muted-foreground",children:"Create an agent from the Agents page to start chatting."})]})}),(0,t.jsx)(ju,{children:e.map(N=>(0,t.jsxs)(Ko,{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)(L5,{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(Cot,"AgentChatPickerResults");function jE({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=Mn(),[j,N]=(0,m.useState)(!1),[w,k]=(0,m.useState)(d),S=(0,m.useRef)(null),C=(0,m.useId)(),I=w.trim().toLocaleLowerCase(),R=e.filter(A=>`${A.name} ${A.title??""} ${A.role}`.toLocaleLowerCase().includes(I));function T(){k(""),S.current?.focus()}return r(T,"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)(L,{variant:"outline",size:"icon-sm","aria-label":"Add chat",title:"Add chat",onClick:r(()=>N(!0),"onClick"),children:(0,t.jsx)(yn,{className:"size-4"})})]}),(0,t.jsxs)("div",{className:"relative",children:[(0,t.jsx)(oa,{"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)(ht,{ref:S,"aria-label":"Search agents",placeholder:"Find an agent",value:w,onChange:r(A=>k(A.target.value),"onChange"),onKeyDown:r(A=>{A.key==="Escape"&&(A.stopPropagation(),k(""))},"onKeyDown"),className:"h-8 pl-8 pr-8 text-xs md:text-xs"}),w&&(0,t.jsx)(L,{variant:"ghost",size:"icon-xs","aria-label":"Clear search",className:"absolute right-1 top-1/2 -translate-y-1/2",onClick:T,children:(0,t.jsx)(Fn,{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:I?"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)(L,{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)(L,{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(A=>(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"})]})]},A))}):R.length?(0,t.jsx)("nav",{"aria-label":"Agent conversations",className:"flex flex-col gap-1",children:R.map(A=>(0,t.jsxs)(Ke,{to:`/chats/${encodeURIComponent(A.status==="terminated"?A.id:Xl(A))}`,"aria-current":a===A.id?"page":void 0,title:`${A.name}${A.title?` · ${A.title}`:""}`,onClick:r(D=>{u&&(D.preventDefault(),u(A))},"onClick"),className:W("flex min-w-0 items-center gap-3 rounded-md px-2 py-3 text-left transition-colors hover:bg-accent/60 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-ring",a===A.id&&"bg-accent text-accent-foreground"),children:[(0,t.jsx)(kr,{agent:A,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:A.name}),(0,t.jsx)("span",{className:"truncate text-xs text-muted-foreground",children:A.status==="terminated"?"Terminated":A.status==="paused"?"Paused":i[A.id]??A.title??"Start a conversation"})]})]},A.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)(L,{variant:"outline",size:"sm",onClick:r(()=>N(!0),"onClick"),children:"Choose an agent"}),e.length>0&&(0,t.jsx)(L,{variant:"outline",size:"sm",onClick:T,children:"Clear search"})]})]}),(0,t.jsx)("div",{className:"shrink-0 px-3 py-4",children:(0,t.jsx)(L,{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)(Vo,{className:"size-4"}),"Browse all agents"]}):(0,t.jsxs)(Ke,{to:"/agents/all",children:[(0,t.jsx)(Vo,{className:"size-4"}),"Browse all agents"]})})}),(0,t.jsx)(fCe,{agents:n,open:j,onOpenChange:N,existingChatAgentIds:s??e.map(A=>A.id),loading:o,error:l,onRetry:c,renderAgentIcon:r(A=>(0,t.jsx)(kr,{agent:A,size:32}),"renderAgentIcon"),onSelect:r(async(A,D)=>{p?await p(A,D):u?await u(A,D):v(`/chats/${encodeURIComponent(Xl(A))}`),D?.aborted||k("")},"onSelect")})]})}r(jE,"AgentConversationSidebar");var $5={list:r(e=>Te.get(`/companies/${e}/chats`),"list"),get:r((e,s)=>Te.get(`/companies/${e}/chats/${encodeURIComponent(s)}`),"get"),ensure:r((e,s)=>Te.post(`/companies/${e}/chats/${encodeURIComponent(s)}`,{}),"ensure")};function xCe(){const{selectedCompanyId:e}=ps(),{enabled:s,loaded:n}=Yy(),a=Z({queryKey:P.auth.session,queryFn:r(()=>Oa.getSession(),"queryFn")}),i=a.data?.user?.id??a.data?.session?.userId??null;return{companyId:e,userId:i,enabled:s,loaded:n,agents:Z({queryKey:P.agents.list(e),queryFn:r(()=>$t.list(e),"queryFn"),enabled:s&&!!e}),chats:Z({queryKey:P.agentChats.list(e,i),queryFn:r(()=>$5.list(e),"queryFn"),enabled:s&&!!e&&a.isSuccess}),session:a}}r(xCe,"useAgentChatNavigation");function gCe(e,s){const n=Dt(),a=Mn(),{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 $5.ensure(e,c.id);n.setQueryData(P.agentChats.detail(e,s,c.id),h),n.setQueryData(P.issues.detail(h.id),h),n.setQueryData(P.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(Xl(c))}`),i&&o(!1))},[n,e,s,a,i,o])}r(gCe,"useOpenAgentChat");function _ot(){const{companyId:e,userId:s,agents:n,chats:a,session:i}=xCe(),o=gCe(e,s),l=Mn(),c=Qf(e),{isMobile:d,setSidebarOpen:u}=qa(),{pathname:h}=na(),p=h.split("/chats/")[1]?.split("/")[0],f=n.data??[],x=n.isSuccess?[...new Set((a.data??[]).flatMap(C=>C.conversationAgentId&&!f.some(I=>I.id===C.conversationAgentId)?[C.conversationAgentId]:[]))]:[],b=Rh({queries:x.map(C=>({queryKey:P.agents.detail(C),queryFn:r(()=>$t.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(Xl(C))===p),N=(a.data??[]).flatMap(C=>{const I=C.conversationAgentId?v.get(C.conversationAgentId):void 0;return I?[I]:[]});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||$f(c.data,"agent",C.id)!=="left")).sort((C,I)=>C.name.localeCompare(I.name,void 0,{sensitivity:"base"})),S=Object.fromEntries((a.data??[]).filter(C=>C.conversationState==="active").map(C=>[C.conversationAgentId,"Working…"]));return(0,t.jsx)(jE,{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:Xl(C))}`),d&&u(!1)},"onSelect")},`${e}:${s}`)}r(_ot,"AgentConversationsSidebar");var J2=240,x6=208,g6=420,jse=16;function O5(e){return Math.min(g6,Math.max(x6,e))}r(O5,"clampSidebarWidth$1");function wse(e){if(typeof window>"u")return J2;try{const s=window.localStorage.getItem(e);if(!s)return J2;const n=Number.parseInt(s,10);return Number.isFinite(n)?O5(n):J2}catch{return J2}}r(wse,"readStoredSidebarWidth$1");function kse(e,s){if(!(typeof window>"u"))try{window.localStorage.setItem(e,String(O5(s)))}catch{}}r(kse,"writeStoredSidebarWidth$1");function Iot({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)(()=>wse(o)),[x,b]=(0,m.useState)(!1),v=(0,m.useRef)(p),j=(0,m.useRef)(null);(0,m.useEffect)(()=>{const E=wse(o);v.current=E,f(E)},[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,I=(0,m.useMemo)(()=>({width:`${w}px`}),[w]),R=(0,m.useMemo)(()=>({width:`${k}px`}),[k]),T=(0,m.useCallback)(E=>{const z=O5(E);v.current=z,f(z),kse(o,z)},[o]),A=(0,m.useCallback)(E=>{C&&(E.preventDefault(),E.currentTarget.setPointerCapture(E.pointerId),j.current={startX:E.clientX,startWidth:v.current},b(!0))},[C]),D=(0,m.useCallback)(E=>{if(!j.current)return;const z=O5(j.current.startWidth+E.clientX-j.current.startX);v.current=z,f(z)},[]),M=(0,m.useCallback)(()=>{j.current&&(j.current=null,b(!1),kse(o,v.current))},[o]),B=(0,m.useCallback)(E=>{C&&(E.key==="ArrowLeft"?(E.preventDefault(),T(p-jse)):E.key==="ArrowRight"?(E.preventDefault(),T(p+jse)):E.key==="Home"?(E.preventDefault(),T(x6)):E.key==="End"&&(E.preventDefault(),T(g6)))},[C,T,p]);return(0,t.jsxs)("div",{className:W("relative h-full shrink-0",l),style:I,children:[(0,t.jsx)("div",{className:W("absolute inset-y-0 left-0 flex flex-col overflow-hidden",S?"z-30 border-r border-border bg-background shadow-lg":"z-0"),style:R,"data-sidebar-overlay":S?"":void 0,onMouseEnter:c,onMouseLeave:d,onFocusCapture:u,onBlurCapture:h,children:e}),C?(0,t.jsx)("div",{role:"separator","aria-label":"Resize sidebar","aria-orientation":"vertical","aria-valuemin":x6,"aria-valuemax":g6,"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:A,onPointerMove:D,onPointerUp:M,onPointerCancel:M,onLostPointerCapture:M,onKeyDown:B,children:(0,t.jsx)("div",{className:W("mx-auto h-full w-0.5 transition-colors",x?"bg-ring":"bg-transparent group-hover:bg-ring group-focus-visible:bg-ring")})}):null]})}r(Iot,"SidebarShell$1");function X2({children:e,className:s}){return(0,t.jsx)("div",{"data-secondary-sidebar":"",className:W("h-full w-full min-w-0 overflow-hidden",s),children:(0,t.jsx)(oye,{children:e})})}r(X2,"SecondarySidebar$1");var bCe={listStacks:r(()=>Te.get("/cloud/stacks"),"listStacks")};function u4(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(u4,"cloudAppUrl");function vCe(e){return u4(e,"/stacks/new")}r(vCe,"cloudStackCreateUrl");function yCe(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(yCe,"tenantSignInReturnPath");function Aot(e,s,n){const a=s?.trim();if(!a)return null;const i=u4(e,`/v1/stacks/${encodeURIComponent(a)}/entry-redirect`);if(!i)return null;const o=new URL(i);return o.searchParams.set("returnTo",yCe(n)),o.toString()}r(Aot,"cloudStackEntryUrl");function jCe(e,s){const n=s?.trim();return n?u4(e,`/workspaces/${encodeURIComponent(n)}/settings?section=people`):null}r(jCe,"cloudStackInviteUrl");function Tot(e){return u4(e,"/orgs?manage=1")}r(Tot,"cloudPortfolioManageUrl");function wCe(){const e=$c(),s=!!e,n=Z({queryKey:P.cloud.stacks,queryFn:r(()=>bCe.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:jCe(e.cloudBaseUrl,a.stackSlug)}r(wCe,"useCloudInviteUrl");function Rot(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"}r(Rot,"canInviteCompanyMembers");function kCe(e=!0){const s=XDe(),n=Z({queryKey:P.access.currentBoardAccess,queryFn:r(()=>pr.getCurrentBoardAccess(),"queryFn"),enabled:e,retry:!1,staleTime:3e4});return e&&Rot(s?.selectedCompanyId,n.data)}r(kCe,"useCanInviteCompanyMembers");function NCe(e){const s=window.location.hostname.endsWith(".staging.paperclip.app"),{data:n,isError:a}=Z({queryKey:P.stagingCommit,queryFn:r(()=>tu.get(),"queryFn"),enabled:s&&e,staleTime:0,retry:!1});return s&&!a?n?.commit??null:null}r(NCe,"useStagingCommit");function Eot(e){return e?.trim().toLowerCase().replace(/['"]/g,"").replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")||null}r(Eot,"slugifyUserPart");function SCe(e){const s=[e?.id,e?.name,e?.email?.split("@")[0],e?.email];for(const n of s){const a=Eot(n);if(a)return`/u/${a}`}return"/u/me"}r(SCe,"userProfilePath");var Pot="Toggle the app appearance.";function yk({className:e,variant:s="icon",onAfterToggle:n}){const{theme:a,toggleTheme:i}=XFe(),o=a==="dark",l=o?"Switch to light mode":"Switch to dark mode",c=o?hve:mbe;function d(){i(),n?.()}return r(d,"handleClick"),s==="compact-menu-action"?(0,t.jsxs)("button",{type:"button",className:W("flex h-(--profile-popover-row-height) w-full items-center gap-(--profile-popover-row-gap) rounded-lg px-2.5 text-left text-(length:--text-compact) font-medium leading-(--profile-popover-label-line-height) text-foreground transition-colors hover:bg-accent",e),onClick:d,"aria-label":l,children:[(0,t.jsx)("span",{className:"flex size-5 shrink-0 items-center justify-center text-muted-foreground",children:(0,t.jsx)(c,{className:"size-4"})}),(0,t.jsx)("span",{className:"min-w-0 flex-1 truncate",children:l})]}):s==="menu-action"?(0,t.jsxs)("button",{type:"button",className:W("flex w-full items-start gap-3 rounded-xl px-3 py-3 text-left transition-colors hover:bg-accent/60",e),onClick:d,"aria-label":l,children:[(0,t.jsx)("span",{className:"mt-0.5 rounded-lg border border-border bg-background/70 p-2 text-muted-foreground",children:(0,t.jsx)(c,{className:"size-4"})}),(0,t.jsxs)("span",{className:"min-w-0 flex-1",children:[(0,t.jsx)("span",{className:"block text-sm font-medium text-foreground",children:l}),(0,t.jsx)("span",{className:"block text-xs text-muted-foreground",children:Pot})]})]}):(0,t.jsx)(L,{type:"button",variant:"ghost",size:"icon-sm",onClick:d,"aria-label":l,title:l,className:W("text-muted-foreground",e),children:(0,t.jsx)(c,{})})}r(yk,"ThemeToggle");var q_=null,CCe=!1,b6=!1,v6=new Set;function F5(){for(const e of v6)e()}r(F5,"emit");function Mot(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(Mot,"isIosSafariLike");function Dot(e=window){const s=r(a=>{a.preventDefault(),q_=a,F5()},"onPrompt"),n=r(()=>{q_=null,CCe=!0,F5()},"onInstalled");return e.addEventListener("beforeinstallprompt",s),e.addEventListener("appinstalled",n),()=>{e.removeEventListener("beforeinstallprompt",s),e.removeEventListener("appinstalled",n)}}r(Dot,"captureInstallPrompt");function Lot(){return CCe||p6()?"installed":q_?"prompt":Mot()?"ios-manual":"unavailable"}r(Lot,"installAvailability");async function $ot(){const e=q_;if(!e)return"unavailable";q_=null,F5(),await e.prompt();const{outcome:s}=await e.userChoice;return s}r($ot,"promptInstall");function y6(e){b6!==e&&(b6=e,F5())}r(y6,"setIosInstallHelpOpen");function Oot(){return b6}r(Oot,"iosInstallHelpOpen");function Fot(){return(0,m.useSyncExternalStore)(_Ce,Oot,()=>!1)}r(Fot,"useIosInstallHelpOpen");function _Ce(e){return v6.add(e),()=>{v6.delete(e)}}r(_Ce,"subscribe$1");function Bot(){return(0,m.useSyncExternalStore)(_Ce,Lot,()=>"unavailable")}r(Bot,"useInstallAvailability");var Nse="Install app",zot="Add Paperclip to your home screen or dock.";function ICe({variant:e,onAfterAction:s}){const n=Bot();if(n==="installed"||n==="unavailable")return null;const a=r(()=>{n==="ios-manual"?y6(!0):$ot(),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)(po,{className:"size-4"})}),(0,t.jsx)("span",{className:"min-w-0 flex-1 truncate",children:Nse})]}):(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)(po,{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:Nse}),(0,t.jsx)("span",{className:"block text-xs text-muted-foreground",children:zot})]})]})}r(ICe,"InstallAppMenuAction");function qot(){const e=Fot();return(0,t.jsx)(Qs,{open:e,onOpenChange:y6,children:(0,t.jsxs)(Js,{children:[(0,t.jsxs)(hn,{children:[(0,t.jsx)(Xs,{children:"Install Paperclip"}),(0,t.jsx)(jn,{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)(Z$,{index:1,icon:(0,t.jsx)(Nqe,{className:"size-4"}),children:["Tap ",(0,t.jsx)("strong",{children:"Share"})," in the Safari toolbar."]}),(0,t.jsxs)(Z$,{index:2,icon:(0,t.jsx)(Cqe,{className:"size-4"}),children:["Choose ",(0,t.jsx)("strong",{children:"Add to Home Screen"}),"."]}),(0,t.jsxs)(Z$,{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)(hr,{children:(0,t.jsx)(L,{type:"button",onClick:r(()=>y6(!1),"onClick"),children:"Done"})})]})})}r(qot,"IosInstallHelpDialog");function Z$({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(Z$,"InstallStep");function Uot(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(Uot,"formatTimestamp$2");function Kot(e){return!!e&&!Number.isNaN(new Date(e).getTime())}r(Kot,"isValidTimestamp");function Wot(e){return e?.devServer?.lastRestartAt??e?.serverInfo?.processStartedAt??null}r(Wot,"restartTimestamp");function Vot(e){const s=e?.serverInfo?.git;return s?.available?`${s.shortSha} · ${s.subject}`:"Commit unavailable"}r(Vot,"commitLabel");function Hot(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(Hot,"localChangesLabel");function eO({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(eO,"ServerInfoRow");function ACe(){const e=Z({queryKey:P.instance.experimentalSettings,queryFn:r(()=>Nr.getExperimental(),"queryFn")}).data?.enableServerInfoDebugView===!0,s=Z({queryKey:P.health,queryFn:r(()=>tu.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=Wot(n),l=Kot(o),c=i?"Health unavailable":a?"Loading...":Uot(o),d=i?"Health unavailable":a?"Loading...":Vot(n),u=i?"Health unavailable":a?"Loading...":Hot(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)(eO,{icon:Yd,label:"Last restarted",value:c,dateTime:!i&&!a&&l?o:null}),(0,t.jsx)(eO,{icon:T7,label:"Running commit",value:d}),(0,t.jsx)(eO,{icon:Zze,label:"Checkout state",value:u})]})}r(ACe,"SidebarServerInfo");var Got="/company/settings/members?tab=invites",Qot="https://docs.paperclip.ing/",Yot="https://paperclip.ing/feedback";function Jot(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(Jot,"deriveInitials$2");function tO({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)(Ke,{to:a,className:l,onClick:n,children:c}):(0,t.jsx)("button",{type:"button",className:l,onClick:n,children:c})}r(tO,"MenuAction$1");function Sse({deploymentMode:e,open:s,onOpenChange:n,forceExpanded:a=!1}){const o=!!$c(),{hidden:l,loaded:c}=eu(),d=wCe(),u=kCe(!o),h=o?d:u?Got:null,p=c&&h!==null&&!cg(l,"company.members")&&!cg(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=NCe(k),C=n??x,{data:I}=Z({queryKey:P.auth.session,queryFn:r(()=>Oa.getSession(),"queryFn"),retry:!1}),R=ZN({onSignedOut:B}),T=I?.user.name?.trim()||"Board",A=I?.user.email?.trim()||(e==="authenticated"?"Signed in":"Local workspace board"),D=Jot(T),M=SCe(I?.user);function B(){C(!1),b&&v(!1)}r(B,"closeNavigationChrome");function E(){R.mutate()}return r(E,"handleSignOut"),(0,t.jsx)("div",{className:"bg-border/50 px-3 py-2 dark:bg-muted",children:(0,t.jsxs)("div",{className:W("flex items-center gap-0.5",!w&&"px-2"),children:[(0,t.jsxs)(gr,{open:k,onOpenChange:C,children:[(0,t.jsx)(Sr,{asChild:!0,children:(0,t.jsxs)("button",{type:"button",className:W("flex min-w-0 items-center gap-2.5 rounded-lg text-left text-(length:--text-compact) font-medium text-foreground/80 transition-colors hover:bg-sidebar-accent hover:text-sidebar-accent-foreground",w?"w-full px-3 py-2":"flex-1 px-2 py-1.5"),"aria-label":"Open account menu",children:[(0,t.jsxs)(Mo,{size:"sm",children:[I?.user.image?(0,t.jsx)(xd,{src:I.user.image,alt:T}):null,(0,t.jsx)(Do,{children:D})]}),(0,t.jsx)("span",{className:W("min-w-0 flex-1 truncate",w&&"block w-0 min-w-0 overflow-hidden whitespace-nowrap text-transparent select-none"),children:T})]})}),(0,t.jsxs)(dr,{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)(Ke,{to:M,"aria-label":"View profile",onClick:B,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)(Mo,{className:"pointer-events-none relative size-9",children:[I?.user.image?(0,t.jsx)(xd,{src:I.user.image,alt:T}):null,(0,t.jsx)(Do,{className:"text-xs text-foreground",children:D})]}),(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:T}),(0,t.jsx)("p",{className:"truncate text-(length:--text-micro) leading-(--profile-popover-meta-line-height) text-muted-foreground",children:A}),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)(tO,{label:"Settings",icon:Jd,href:"/company/settings",onClick:B}),p&&h?(0,t.jsx)(tO,{label:"Invite",icon:Hf,href:h,topLevel:o,onClick:B}):null,(0,t.jsx)(tO,{label:"Documentation",icon:HN,href:Qot,external:!0,onClick:r(()=>C(!1),"onClick")}),(0,t.jsx)(yk,{variant:"compact-menu-action",onAfterToggle:r(()=>C(!1),"onAfterToggle")}),(0,t.jsx)(ICe,{variant:"compact-menu-action",onAfterAction:r(()=>C(!1),"onAfterAction")}),e==="authenticated"?(0,t.jsxs)("button",{type:"button",className:W("flex h-(--profile-popover-row-height) w-full items-center gap-(--profile-popover-row-gap) rounded-lg px-2.5 text-left text-(length:--text-compact) font-medium leading-(--profile-popover-label-line-height) text-foreground transition-colors hover:bg-destructive/10",R.isPending&&"cursor-not-allowed opacity-60"),onClick:E,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)(Tp,{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)(ACe,{})]})]})]}),!w&&!o?(0,t.jsxs)(zn,{children:[(0,t.jsx)(qn,{asChild:!0,children:(0,t.jsx)("a",{href:Yot,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)(Cg,{className:"h-4 w-4","aria-hidden":"true"})})}),(0,t.jsx)(Un,{side:"top",children:"Share feedback"})]}):null]})})}r(Sse,"SidebarAccountMenu$1");function TCe({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=qfe({armed:l,defaultPrevented:b.defaultPrevented,key:b.key,metaKey:b.metaKey,ctrlKey:b.ctrlKey,altKey:b.altKey,target:b.target,hasOpenDialog:wp()});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(!DI(b.target)&&!wp()){if(b.key==="/"&&!b.metaKey&&!b.ctrlKey&&!b.altKey){b.preventDefault(),VOe()||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(TCe,"useKeyboardShortcuts");var Xot=new Set(["auth","invite","board-claim","cli-auth","docs","s"]);function RCe(e){const s=(e.split("?")[0]??"").split("/").filter(Boolean);if(s.length===0)return!0;const[n]=s;return!Xot.has(n)}r(RCe,"isRememberableCompanyPath");function Zot(e){const s=ly(e.companyPrefix);return e.companies.find(n=>ly(n.issuePrefix)===s)??null}r(Zot,"findCompanyByPrefix");function elt(e){const s=i7(e.pathname);return s?Zot({companies:e.companies,companyPrefix:s})?.id??null:e.fallbackCompanyId}r(elt,"getRememberedPathOwnerCompanyId");function tlt(e){const s=e.path?uM(e.path):"/dashboard";if(!RCe(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&&ly(i[1]??"")!==ly(e.companyPrefix))return"/dashboard"}return s}r(tlt,"sanitizeRememberedPathForCompany");var ECe="paperclip.companyPaths";function PCe(){try{const e=localStorage.getItem(ECe);if(e)return JSON.parse(e)}catch{}return{}}r(PCe,"getCompanyPaths");function slt(e,s){const n=PCe();n[e]=s,localStorage.setItem(ECe,JSON.stringify(n))}r(slt,"saveCompanyPath");function MCe(){const{companies:e,selectedCompanyId:s,selectedCompany:n,selectionSource:a}=ps(),i=na(),o=Mn(),l=(0,m.useRef)(s),c=(0,m.useMemo)(()=>elt({companies:e,pathname:i.pathname,fallbackCompanyId:l.current}),[e,i.pathname]),d=i.pathname+i.search;(0,m.useEffect)(()=>{const u=c,h=uM(d);u&&RCe(h)&&slt(u,h)},[d,c]),(0,m.useEffect)(()=>{if(s){if(l.current!==null&&s!==l.current&&a!=="route_sync"&&n){const u=PCe(),h=tlt({path:u[s],companyPrefix:n.issuePrefix});o(`/${n.issuePrefix}${h}`,{replace:!0})}l.current=s}},[n,s,a,o])}r(MCe,"useCompanyPageMemory");var nlt=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 DCe(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 nlt({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(DCe,"useMobileNavVisibility");function LCe(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(LCe,"resolveArchivedCompanyBounce");function rlt(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(rlt,"resolveCompanyArchiveDeparture");function $Ce(e){const{selectionSource:s,selectedCompanyId:n,routeCompanyId:a}=e;return!(n===a||s==="manual"&&n)}r($Ce,"shouldSyncCompanySelectionFromRoute");function alt(e,s){return e instanceof HTMLElement?!(s instanceof HTMLElement)||!document.contains(s)||s===document.body||s===document.documentElement?!0:!e.contains(s):!1}r(alt,"shouldFocusMainContentAfterNavigation");function OCe(e){if(!(e instanceof HTMLElement))return()=>{};const s=window.requestAnimationFrame(()=>{alt(e,document.activeElement)&&e.focus({preventScroll:!0})});return()=>window.cancelAnimationFrame(s)}r(OCe,"scheduleMainContentFocus");function FCe(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(FCe,"pinDocumentScrollToZero");function Pu({scope:e="global",requestedPrefix:s}){const n=na(),{setBreadcrumbs:a}=Bn(),{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)(rn,{className:"block p-6",children:[(0,t.jsxs)("div",{className:"flex items-center gap-3",children:[(0,t.jsx)("div",{className:"rounded-md border border-destructive/20 bg-destructive/10 p-2",children:(0,t.jsx)(Es,{className:"h-5 w-5 text-destructive"})}),(0,t.jsxs)("div",{children:[(0,t.jsx)("h1",{className:"text-xl font-semibold",children:h}),(0,t.jsx)("p",{className:"text-sm text-muted-foreground",children:p})]})]}),(0,t.jsxs)("div",{className:"mt-4 rounded-md border border-border bg-muted/20 px-3 py-2 text-xs text-muted-foreground",children:["Requested path: ",(0,t.jsx)("code",{className:"font-mono",children:d})]}),(0,t.jsxs)("div",{className:"mt-5 flex flex-wrap gap-2",children:[(0,t.jsx)(L,{asChild:!0,children:(0,t.jsxs)(Ke,{to:c,children:[(0,t.jsx)(N3,{className:"mr-1.5 h-4 w-4"}),"Open dashboard"]})}),(0,t.jsx)(L,{variant:"outline",asChild:!0,children:(0,t.jsx)(Ke,{to:"/",children:"Go home"})})]})]})})}r(Pu,"NotFoundPage");function ilt(e,s){return hje(e,s)[0]?.toLowerCase()??null}r(ilt,"getCompanyRouteSegment$1");var olt=new Set(["browse","connections","connect","chat","vercel-connect","review","attention","gateways","advanced","app"]);function llt({sidebarSections:e}){const{sidebarOpen:s,setSidebarOpen:n,toggleSidebar:a,collapsed:i,peeking:o,setPeeking:l,isMobile:c,setForceCollapsed:d}=qa(),{openNewIssue:u,openOnboarding:h}=Qo(),{togglePanelVisible:p}=Yf(),f=Xc()?.pushToast??null,{companies:x,loading:b,selectedCompany:v,selectedCompanyId:j,selectionSource:N,setSelectedCompanyId:w}=ps(),{companyPrefix:k,pluginRoutePath:S,agentId:C,routineId:I}=va(),R=Mn(),T=na(),A=dM(),{enabled:D}=yc(),M=pje(T.pathname,k),B=M.builtInContextualSurface==="settings",E=M.companySegments,z=M.isTaskDetail,{enabled:$}=Yy(),q=$&&E[0]?.toLowerCase()==="chats",U=D&&(z||q),O=E[0]?.toLowerCase()==="tools",K=E[0]?.toLowerCase()==="apps",H=K&&E[1]&&!olt.has(E[1].toLowerCase())?E[1]:null,ee=K&&E[1]?.toLowerCase()==="app"&&E[2]?E[2]:null,se=(0,m.useRef)(!1),ne=(0,m.useRef)(null),fe=(0,m.useRef)(null),X=(0,m.useRef)(new rye),re=(0,m.useRef)(T.key),oe=DCe(c&&!z,T.pathname),[G,Y]=(0,m.useState)(!1),Q=(0,m.useMemo)(()=>{if(!k)return null;const lt=k.toUpperCase();return x.find(Ee=>Ee.issuePrefix.toUpperCase()===lt)??null},[x,k]),te=!!k&&!b&&x.length>0&&!Q,ae=(0,m.useMemo)(()=>S?.toLowerCase()??ilt(T.pathname,k),[k,T.pathname,S]),le=Q?.id??null,he=Q?.issuePrefix??null,{slots:ce}=bd({slotTypes:["page","routeSidebar"],companyId:le,enabled:!!(le&&ae)}),ge=(0,m.useMemo)(()=>s9(ce,ae),[ae,ce]),me=(0,m.useMemo)(()=>({companyId:le,companyPrefix:he}),[le,he]),ie=B?(0,t.jsx)(I9e,{}):!D&&M.builtInContextualSurface==="skills"?(0,t.jsx)(oZ,{}):H?(0,t.jsx)(aZ,{kind:"connection",connectionId:H}):ee?(0,t.jsx)(aZ,{kind:"application",applicationId:ee}):K||O?(0,t.jsx)(L9e,{}):ge?D?(0,t.jsx)(eA,{surface:`plugin:${ge.id}`,title:ge.displayName,children:(0,t.jsx)(Wu,{slot:ge,context:me,className:"min-h-0 flex-1",missingBehavior:"placeholder"})}):(0,t.jsx)(Wu,{slot:ge,context:me,className:"h-full w-full",missingBehavior:"placeholder"}):null,ue=q?(0,t.jsx)(_ot,{}):M.builtInContextualSurface==="agent"&&C?(0,t.jsx)(Y9e,{agentRef:C}):D&&M.builtInContextualSurface==="routine"&&I?(0,t.jsx)(cKe,{children:(0,t.jsx)(Z9e,{routineId:I})}):D&&M.builtInContextualSurface==="skills"?(0,t.jsx)(oZ,{}):ie,ke=ue!=null,be=D&&ke&&(q||M.builtInContextualSurface==="skills"||M.builtInContextualSurface==="agent"||M.builtInContextualSurface==="routine"||K||O),Ie=D&&ke&&!be,Ue=ke&&(!D||be),at=!D||!ke?null:ge&&!M.builtInContextualSurface?`plugin:${ge.id}`:M.builtInContextualSurface,dt=(0,m.useRef)(null),{data:de}=Z({queryKey:P.health,queryFn:r(()=>tu.get(),"queryFn"),retry:!1,refetchInterval:r(lt=>lt.state.data?.devServer?.enabled?2e3:!1,"refetchInterval"),refetchIntervalInBackground:!1});(0,m.useLayoutEffect)(()=>(d(!D&&ke),()=>d(!1)),[ke,d,D]),(0,m.useEffect)(()=>{const lt=dt.current;at&&k&&lt&&lt.surface!==at&&lt.pathname!==T.pathname&&S9e({surface:at,companyPrefix:k,previousPathname:lt.pathname}),dt.current={pathname:T.pathname,surface:at}},[k,at,T.pathname]),(0,m.useEffect)(()=>{b||se.current||de?.deploymentMode!=="authenticated"&&(de?.cloud||x.length===0&&(se.current=!0,h()))},[x,b,h,de?.cloud,de?.deploymentMode]),(0,m.useEffect)(()=>{if(!k||b||x.length===0)return;if(!Q){const Ee=(j?x.find(Xe=>Xe.id===j):null)??x[0]??null;Ee&&j!==Ee.id&&w(Ee.id,{source:"route_sync"});return}if(k!==Q.issuePrefix){const Ee=T.pathname.replace(/^\/[^/]+/,"");R(`/${Q.issuePrefix}${Ee}${T.search}`,{replace:!0});return}const lt=LCe({matchedCompany:Q,selectedCompanyId:j,companies:x});if(lt){f?.({title:`${Q.name} is archived`,body:`Switched to ${lt.name}.`,tone:"info",dedupeKey:`archived-company-bounce:${Q.id}`}),w(lt.id,{source:"route_sync"}),R(`/${lt.issuePrefix}/dashboard`,{replace:!0});return}$Ce({selectionSource:N,selectedCompanyId:j,routeCompanyId:Q.id})&&w(Q.id,{source:"route_sync"})},[k,x,b,Q,T.pathname,T.search,R,f,N,j,w]);const Be=p,pt=(0,m.useCallback)(()=>{document.dispatchEvent(new KeyboardEvent("keydown",{key:"k",metaKey:!0,bubbles:!0,cancelable:!0}))},[]),vt=(0,m.useRef)(null),Le=(0,m.useRef)(!1),Qe=(0,m.useRef)(!1),ut=(0,m.useCallback)(()=>{vt.current!==null&&(window.clearTimeout(vt.current),vt.current=null)},[]),Ye=(0,m.useCallback)(()=>{ut(),vt.current=window.setTimeout(()=>l(!0),50)},[ut,l]),it=(0,m.useCallback)(()=>{ut(),l(!0)},[ut,l]),kt=(0,m.useCallback)(()=>{ut(),vt.current=window.setTimeout(()=>l(!1),120)},[ut,l]),tt=(0,m.useCallback)(()=>{Le.current=!0,i&&!Qe.current&&Ye()},[i,Ye]),Pe=(0,m.useCallback)(()=>{Le.current=!1,Qe.current=!1,kt()},[kt]),Ce=(0,m.useCallback)(()=>{Qe.current||it()},[it]),He=(0,m.useCallback)(()=>{Le.current||kt()},[kt]);(0,m.useEffect)(()=>ut,[ut]);const Je=(0,m.useRef)(i);return(0,m.useEffect)(()=>{i!==Je.current&&(i?(ut(),l(!1),Qe.current=Le.current):Qe.current=!1,Je.current=i)},[i,ut,l]),(0,m.useEffect)(()=>{if(!o)return;const lt=r(Ee=>{Ee.key==="Escape"&&(ut(),l(!1))},"onKeyDown");return window.addEventListener("keydown",lt),()=>window.removeEventListener("keydown",lt)},[o,ut,l]),MCe(),TCe({onNewIssue:r(()=>u(),"onNewIssue"),onSearch:pt,onToggleSidebar:a,onTogglePanel:Be,onShowShortcuts:r(()=>Y(!0),"onShowShortcuts"),onGoToInbox:r(()=>R("/inbox"),"onGoToInbox")}),(0,m.useEffect)(()=>{if(!c)return;const lt=30,Ee=50,Xe=75;let Ae=0,De=0;const _t=r(gt=>{const We=gt.touches[0];Ae=We.clientX,De=We.clientY},"onTouchStart"),ye=r(gt=>{const We=gt.changedTouches[0],Ot=We.clientX-Ae;if(!(Math.abs(We.clientY-De)>Xe)){if(!s&&Ae<lt&&Ot>Ee){n(!0);return}s&&Ot<-50&&n(!1)}},"onTouchEnd");return document.addEventListener("touchstart",_t,{passive:!0}),document.addEventListener("touchend",ye,{passive:!0}),()=>{document.removeEventListener("touchstart",_t),document.removeEventListener("touchend",ye)}},[c,s,n]),(0,m.useEffect)(()=>{const lt=document.body.style.overflow;return document.body.style.overflow=c?"visible":"clip",()=>{document.body.style.overflow=lt}},[c]),(0,m.useEffect)(()=>{if(!c)return FCe()},[c]),(0,m.useEffect)(()=>{if(typeof document>"u")return;const lt=fe.current;return OCe(lt)},[T.pathname]),(0,m.useEffect)(()=>{const lt=fe.current;if(!lt)return;const Ee=r(()=>{X.current.remember(re.current,lt.scrollTop)},"recordScroll");return lt.addEventListener("scroll",Ee,{passive:!0}),()=>lt.removeEventListener("scroll",Ee)},[]),(0,m.useLayoutEffect)(()=>{const lt=fe.current,Ee=nye({previousPathname:ne.current,pathname:T.pathname,navigationType:A,state:T.state});ne.current=T.pathname;const Xe=A==="POP",Ae=Xe?X.current.recall(T.key):0;if(re.current=T.key,Xe){V3(lt,Ae);const De=requestAnimationFrame(()=>V3(lt,Ae));return()=>cancelAnimationFrame(De)}Ee&&aye(lt)},[T.key,T.pathname,T.state,A]),(0,t.jsx)(sye,{children:(0,t.jsxs)("div",{className:W("bg-background text-foreground pt-(--sz-safe-top)",c?"min-h-dvh overflow-x-clip":"flex h-dvh flex-col overflow-clip"),children:[(0,t.jsx)("a",{href:"#main-content",className:"sr-only focus:not-sr-only focus:fixed focus:left-3 focus:top-3 focus:z-(--z-200) focus:rounded-md focus:bg-background focus:px-3 focus:py-2 focus:text-sm focus:font-medium focus:shadow-lg focus:outline-none focus-visible:ring-2 focus-visible:ring-ring",children:"Skip to Main Content"}),(0,t.jsx)(cCe,{}),(0,t.jsx)(dCe,{devServer:de?.devServer}),(0,t.jsxs)("div",{className:W("min-h-0 flex-1",c?"w-full":"flex overflow-clip"),children:[c&&s&&(0,t.jsx)("button",{type:"button",className:"fixed inset-0 z-40 bg-black/50",onClick:r(()=>n(!1),"onClick"),"aria-label":"Close sidebar"}),c?(0,t.jsxs)("div",{className:W("fixed inset-y-0 left-0 z-50 flex flex-col overflow-hidden pt-(--sz-safe-top) transition-transform duration-100 ease-out",s?"translate-x-0":"-translate-x-full"),children:[(0,t.jsx)("div",{className:"flex flex-1 min-h-0 overflow-hidden",children:(0,t.jsx)("div",{className:"w-60 shrink-0 overflow-hidden",children:ke?(0,t.jsx)(X2,{children:ue}):(0,t.jsx)(tZ,{children:e})})}),(0,t.jsx)(Sse,{deploymentMode:de?.deploymentMode,forceExpanded:Ie})]}):(0,t.jsxs)(Iot,{open:s,collapsed:Ie?!1:i,peeking:Ie?!1:o,resizable:!0,onPanelMouseEnter:Ie?void 0:tt,onPanelMouseLeave:Ie?void 0:Pe,onPanelFocusCapture:!Ie&&i?Ce:void 0,onPanelBlurCapture:!Ie&&i?He:void 0,children:[(0,t.jsx)("div",{className:"flex flex-1 min-h-0",children:Ie?(0,t.jsx)(X2,{children:ue}):(0,t.jsx)(tZ,{children:e})}),(0,t.jsx)(Sse,{deploymentMode:de?.deploymentMode,forceExpanded:Ie})]}),!c&&Ue&&!be?(0,t.jsx)(X2,{className:"w-60 shrink-0",children:ue}):null,(0,t.jsxs)("div",{className:W("flex min-w-0 flex-col",c?"w-full":"h-full flex-1"),children:[(0,t.jsxs)("div",{"data-slot":c?"mobile-topbar":void 0,className:W(!c&&U&&"hidden",c&&"sticky top-0 z-20 bg-background/95 backdrop-blur supports-[backdrop-filter]:bg-background/85"),children:[(0,t.jsx)(f6,{mobile:c,onNavigateHome:r(()=>R("/dashboard"),"onNavigateHome")}),(0,t.jsx)(cZ,{}),c&&B?(0,t.jsx)("div",{className:"border-b border-border px-4 pb-3",children:(0,t.jsx)(gje,{})}):null]}),(0,t.jsxs)("div",{className:W(c?"block":"flex flex-1 min-h-0",!c&&U&&"streamlined-task-detail-surface"),children:[!c&&be?(0,t.jsx)(X2,{className:"w-60 shrink-0 bg-background",children:ue}):null,(0,t.jsxs)("div",{className:W(!c&&U?"flex min-w-0 flex-1 flex-col":"contents"),children:[!c&&U?(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)(f6,{mobile:!1,onNavigateHome:r(()=>R("/dashboard"),"onNavigateHome")}),(0,t.jsx)(cZ,{taskDetailLayout:!0})]}):null,(0,t.jsx)("main",{id:"main-content",ref:fe,tabIndex:-1,style:c?{"--tc-composer-bottom":"var(--sz-calc-14)"}:void 0,className:W("flex-1 p-4 outline-none md:p-6",!c&&U&&"pt-0 md:pt-0",c?"overflow-visible pb-(--sz-calc-14)":"overflow-auto [scrollbar-gutter:stable]"),children:te?(0,t.jsx)(Pu,{scope:"invalid_company_prefix",requestedPrefix:k??v?.issuePrefix}):(0,t.jsx)(pCe,{children:(0,t.jsx)(db,{})})})]}),(0,t.jsx)(Aje,{taskDetailLayout:!c&&U})]})]})]}),c&&(0,t.jsx)(lCe,{visible:oe}),(0,t.jsx)(Tje,{}),(0,t.jsx)(dwe,{}),(0,t.jsx)(eCe,{}),(0,t.jsx)(nCe,{}),(0,t.jsx)(rCe,{}),(0,t.jsx)(aCe,{open:G,onOpenChange:Y}),(0,t.jsx)(iCe,{}),(0,t.jsx)(Jit,{health:de}),(0,t.jsx)(oCe,{localTrusted:de?.deploymentMode==="local_trusted"})]})})}r(llt,"Layout$1");var BCe=(0,m.createContext)(!1);function clt({children:e}){return(0,t.jsx)(BCe.Provider,{value:!0,children:e})}r(clt,"SidebarNavExpandedProvider");function dlt(){return(0,m.useContext)(BCe)}r(dlt,"useSidebarNavExpanded");function si({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(),I=dlt(),R=S&&!C&&!I,T=c!=null&&c>0,A=x!=null&&x>0,D=A?`${x} live`:T?`${c}${u?` ${u}`:""}`:f?"attention needed":void 0,M=!R||!D&&!j?void 0:`${s}${D?`, ${D}`:""}${j?`, ${j}`:""}`,B=(0,t.jsxs)(ub,{to:e,state:Gf,end:i,"aria-label":M,onClick:r(()=>{w&&k(!1)},"onClick"),className:r(({isActive:E})=>W("flex items-center gap-2.5 mx-2 rounded-lg px-2 py-1.5 pointer-coarse:py-1 text-(length:--text-compact) font-medium transition-colors",b??E?"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&&A&&(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&&!A&&T&&(0,t.jsx)("span",{className:W("absolute -right-0.5 -top-0.5 h-2 w-2 rounded-full shadow-(--shadow-extract-12)",d==="danger"?"bg-red-600":d==="warning"?"bg-amber-500":"bg-primary"),"aria-hidden":"true"})]}),(0,t.jsx)("span",{className:R?By:W("min-w-0 flex-1 truncate",l),children:s}),!R&&v,!R&&h&&(0,t.jsx)(ct,{variant:"ghost",className:W("ml-auto px-1.5 text-(length:--text-nano) leading-none",p==="amber"?"bg-amber-100 text-amber-800 dark:bg-amber-900/30 dark:text-amber-400":"bg-muted text-muted-foreground"),children:h}),!R&&(A||N)&&(0,t.jsxs)("span",{className:"ml-auto flex items-center gap-1.5",children:[N,A&&(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&&T&&(0,t.jsx)(ct,{variant:"ghost",className:W("ml-auto px-1.5 leading-none",d==="danger"?"bg-red-600/90 text-red-50":d==="warning"?"bg-amber-500/90 text-amber-50":"bg-primary text-primary-foreground"),children:c})]});return R?(0,t.jsxs)(zn,{children:[(0,t.jsx)(qn,{asChild:!0,children:(0,t.jsx)("div",{children:B})}),(0,t.jsx)(Un,{side:"right",children:s})]}):B}r(si,"SidebarNavItem");var ult=3,Cse=12e4,mlt=[{value:"top",label:"Top"},{value:"alphabetical",label:"Alphabetical"},{value:"recent",label:"Recent"}];function Yj(e,s){const n=e[s];if(!n)return 0;const a=new Date(n).getTime();return Number.isFinite(a)?a:0}r(Yj,"agentTimestamp");function _se(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=Yj(i,"lastHeartbeatAt")-Yj(a,"lastHeartbeatAt");if(o!==0)return o;const l=Yj(i,"updatedAt")-Yj(a,"updatedAt");if(l!==0)return l;const c=Yj(i,"createdAt")-Yj(a,"createdAt");return c!==0?c:a.name.localeCompare(i.name,void 0,{sensitivity:"base"})}),n)}r(_se,"sortAgents");var hlt="opacity-0 transition-opacity group-hover/agent:opacity-100 group-focus-within/agent:opacity-100";function plt({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=Xl(n),j=s?`${Cm(n)}/${s}`:Cm(n),N=`${Cm(n)}/configuration`,w=e===v,k=n.status==="paused",S=k&&n.pauseReason==="budget",C=n.orgChainHealth?.status==="invalid_org_chain",I=k?"Resume agent":"Pause agent",R=a||n.status==="pending_approval"||S||k&&C,T=a?"Updating...":S?"Budget paused":k&&C?"Invalid org chain":I,A=p==="needs_setup"||p==="pending_approval",D=[A?`Built-in agent ${p.replace(/_/g," ")}`:null,C?"Invalid reporting chain":null].filter(Boolean).join(", ")||void 0,M=(0,t.jsx)(si,{to:j,label:n.name,iconNode:(0,t.jsx)(kr,{agent:n,size:16,className:"shrink-0 h-4 w-4"}),active:w,liveCount:u,labelClassName:A?"min-w-(--sz-4_5rem) flex-initial":void 0,className:W("min-w-0 flex-1",f&&!i?"pr-14":"pr-8"),trailing:A||C?(0,t.jsxs)("span",{className:"ml-1 flex shrink-0 items-center gap-1",children:[A?(0,t.jsx)(uk,{status:p,compact:!0}):null,C?(0,t.jsx)(Es,{className:"h-3.5 w-3.5 shrink-0 text-amber-500","aria-label":"Invalid reporting chain"}):null]}):void 0,trailingLabel:D,liveAccessory:n.pauseReason==="budget"?(0,t.jsx)(JI,{title:"Agent paused by budget"}):void 0});return d?M:(0,t.jsxs)("div",{className:"group/agent relative flex items-center",children:[M,f&&!i&&x?(0,t.jsx)("span",{className:"absolute right-10 top-1/2 -translate-y-1/2",children:(0,t.jsx)(gb,{size:"row",quiet:!0,starred:!0,pending:b,resourceName:n.name,onToggle:r(()=>x(n,!1),"onToggle"),revealClassName:hlt})}):null,(0,t.jsxs)(Xr,{children:[(0,t.jsx)(Jr,{asChild:!0,children:(0,t.jsx)(L,{variant:"ghost",size:"icon-xs",className:W("absolute right-3 top-1/2 h-6 w-6 -translate-y-1/2 transition-opacity data-[state=open]:pointer-events-auto data-[state=open]:opacity-100",i?"opacity-100":"pointer-events-none opacity-0 group-hover/agent:pointer-events-auto group-hover/agent:opacity-100 group-focus-within/agent:pointer-events-auto group-focus-within/agent:opacity-100"),"aria-label":`Open actions for ${n.name}`,children:(0,t.jsx)(Ri,{className:"h-3.5 w-3.5"})})}),(0,t.jsxs)(Zr,{align:"end",className:"w-48",children:[x?(0,t.jsxs)(t.Fragment,{children:[(0,t.jsxs)(ls,{onClick:r(()=>{b||x(n,!f)},"onClick"),disabled:b,children:[b?(0,t.jsx)(rt,{className:"size-4 motion-safe:animate-spin"}):(0,t.jsx)(yp,{className:W("size-4",f&&"fill-amber-500 text-amber-500")}),(0,t.jsx)("span",{children:f?"Remove from starred":"Star agent"})]}),(0,t.jsx)(ni,{})]}):null,(0,t.jsx)(ls,{asChild:!0,children:(0,t.jsxs)(Ke,{to:N,onClick:r(()=>{i&&h(!1)},"onClick"),children:[(0,t.jsx)(gc,{className:"size-4"}),(0,t.jsx)("span",{children:"Edit agent"})]})}),(0,t.jsx)(ni,{}),(0,t.jsxs)(ls,{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)(VI,{className:"size-4"}):(0,t.jsx)(Rd,{className:"size-4"}),(0,t.jsx)("span",{children:T})]}),(0,t.jsx)(ni,{}),(0,t.jsxs)(ls,{onClick:r(()=>{o||l(n)},"onClick"),disabled:o,children:[o?(0,t.jsx)(rt,{className:"size-4 motion-safe:animate-spin"}):(0,t.jsx)(Tp,{className:"size-4"}),(0,t.jsx)("span",{children:o?"Leaving...":"Leave agent"})]})]})]})]})}r(plt,"SidebarAgentItem");function flt({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=Dt(),{selectedCompanyId:u}=ps(),{openNewAgent:h}=Qo(),{isMobile:p,setSidebarOpen:f,collapsed:x,peeking:b}=qa(),v=x&&!b,{pushToast:j}=da(),N=na(),{data:w}=Z({queryKey:P.agents.list(u),queryFn:r(()=>$t.list(u),"queryFn"),enabled:!!u}),{data:k}=Z({queryKey:P.instance.experimentalSettings,queryFn:r(()=>Nr.getExperimental(),"queryFn"),enabled:!!u}),S=k?.enableBuiltInAgents===!0,{data:C}=Z({queryKey:P.builtInAgents.list(u),queryFn:r(()=>Zh.list(u),"queryFn"),enabled:!!u&&S}),I=(0,m.useMemo)(()=>{const be=new Map;if(!S)return be;for(const Ie of C??[])Ie.agentId&&be.set(Ie.agentId,Ie.status);return be},[C,S]),{data:R}=Z({queryKey:P.auth.session,queryFn:r(()=>Oa.getSession(),"queryFn")}),T=Qf(u),A=Ag(u),D=P.liveRuns(u),M=No({companyId:u,resourceKey:"live-runs",queryKey:D,enabled:!!u,refetchInterval:!1,leaderOnly:!0}),{data:B,dataUpdatedAt:E}=Z({queryKey:D,queryFn:r(()=>sa.liveRunsForCompany(u),"queryFn"),enabled:M.enabled,refetchInterval:M.refetchInterval});So(M,B,E);const z=(0,m.useMemo)(()=>{const be=new Map;for(const Ie of B??[])be.set(Ie.agentId,(be.get(Ie.agentId)??0)+1);return be},[B]),$=(0,m.useMemo)(()=>{const be=new Set;for(const[Ie,Ue]of z)Ue>0&&be.add(Ie);return be},[z]),q=(0,m.useMemo)(()=>(w??[]).filter(be=>be.status!=="terminated"&&(!T.isSuccess||$f(T.data,"agent",be.id)!=="left")),[w,T.data,T.isSuccess]),U=R?.user?.id??R?.session?.userId??null,O=(0,m.useMemo)(()=>u?pye(u,U):null,[U,u]),[K,H]=(0,m.useState)(()=>O?mk(O):"top"),{orderedAgents:ee}=gye({agents:q,companyId:u,userId:U}),se=(0,m.useMemo)(()=>_se(ee,K),[ee,K]),ne=(0,m.useMemo)(()=>new Set(se.map(be=>be.id)),[se]);(0,m.useEffect)(()=>{const be=Date.now();for(const Ie of $)c.current.set(Ie,be);for(const Ie of c.current.keys())ne.has(Ie)||c.current.delete(Ie)},[$,ne]);const fe=(0,m.useMemo)(()=>{const be=Date.now(),Ie=c.current;return se.filter(Ue=>{if((z.get(Ue.id)??0)>0)return!0;const at=Ie.get(Ue.id);return at!==void 0&&be-at<=Cse})},[z,o,se]),X=fe.length>0,re=e?X?fe:se.slice(0,ult):se,oe=e&&se.length>0,G=N.pathname.match(/^\/(?:[^/]+\/)?agents\/([^/]+)(?:\/([^/]+))?/),Y=G?.[1]??null,Q=G?.[2]??null;(0,m.useEffect)(()=>{if(!O){H("top");return}H(mk(O))},[O]),(0,m.useEffect)(()=>{if(!O)return;const be=r(Ue=>{Ue.key===O&&H(mk(O))},"onStorage"),Ie=r(Ue=>{const at=Ue.detail;!at||at.storageKey!==O||H(at.sortMode)},"onCustomEvent");return window.addEventListener("storage",be),window.addEventListener(g_,Ie),()=>{window.removeEventListener("storage",be),window.removeEventListener(g_,Ie)}},[O]),(0,m.useEffect)(()=>{if(!e)return;const be=Date.now();let Ie=null;for(const at of se){if((z.get(at.id)??0)>0)continue;const dt=c.current.get(at.id);if(dt===void 0)continue;const de=dt+Cse;de<be||(Ie=Ie===null?de:Math.min(Ie,de))}if(Ie===null)return;const Ue=window.setTimeout(()=>{l(at=>at+1)},Math.max(0,Ie-be+1));return()=>{window.clearTimeout(Ue)}},[e,se,z,o]);const te=(0,m.useCallback)(be=>{const Ie=be==="alphabetical"||be==="recent"?be:"top";H(Ie),O&&xye(O,Ie)},[O]),ae=je({mutationFn:r(({agent:be,action:Ie})=>Ie==="pause"?$t.pause(be.id,u??void 0):$t.resume(be.id,u??void 0),"mutationFn"),onMutate:r(({agent:be})=>{i(Ie=>{const Ue=new Set(Ie);return Ue.add(be.id),Ue})},"onMutate"),onSuccess:r(async(be,{agent:Ie,action:Ue})=>{u&&await Promise.all([d.invalidateQueries({queryKey:P.agents.list(u)}),d.invalidateQueries({queryKey:P.liveRuns(u)}),d.invalidateQueries({queryKey:P.dashboard(u)})]),await Promise.all([d.invalidateQueries({queryKey:P.agents.detail(Ie.id)}),d.invalidateQueries({queryKey:P.agents.detail(Xl(Ie))})]),j({title:Ue==="pause"?"Agent paused":"Agent resumed",body:Ie.name,tone:"success"})},"onSuccess"),onError:r((be,{agent:Ie,action:Ue})=>{j({title:Ue==="pause"?"Could not pause agent":"Could not resume agent",body:be instanceof Error?be.message:Ie.name,tone:"error"})},"onError"),onSettled:r((be,Ie,{agent:Ue})=>{i(at=>{const dt=new Set(at);return dt.delete(Ue.id),dt})},"onSettled")}),le=(0,m.useCallback)(be=>A.mutate({resourceType:"agent",resourceId:be.id,resourceName:be.name,state:"left"}),[A]),he=(0,m.useCallback)(be=>A.isPending&&A.variables?.resourceType==="agent"&&A.variables.resourceId===be.id,[A.isPending,A.variables]),ce=(0,m.useCallback)((be,Ie)=>A.mutate({resourceType:"agent",resourceId:be.id,resourceName:be.name,starred:Ie}),[A]),ge=(0,m.useCallback)(be=>A.isPending&&A.variables?.resourceType==="agent"&&A.variables.resourceId===be.id&&A.variables.starred!==void 0,[A.isPending,A.variables]),me=(0,m.useMemo)(()=>new Set(PM(T.data,"agent")),[T.data]),ie=(0,m.useMemo)(()=>_se(q.filter(be=>me.has(be.id)),"alphabetical"),[q,me]),ue=(0,m.useMemo)(()=>re.filter(be=>!me.has(be.id)),[re,me]),ke=r((be,Ie)=>(0,t.jsx)(plt,{activeAgentId:Y,activeTab:Q,agent:be,disabled:a.has(be.id),isMobile:p,leaving:he(be),onLeaveAgent:le,onPauseResume:r((Ue,at)=>ae.mutate({agent:Ue,action:at}),"onPauseResume"),rail:v,runCount:z.get(be.id)??0,setSidebarOpen:f,builtInStatus:I.get(be.id),starred:Ie||xb(T.data,"agent",be.id),onToggleStar:ce,starPending:ge(be)},be.id),"renderAgentRow");return(0,t.jsxs)(eg,{label:"Agents",collapsible:{open:s,onOpenChange:n},headerAction:{ariaLabel:"New agent",icon:yn,onClick:h},menu:{ariaLabel:"Agents section actions",actions:[{type:"item",label:"Browse agents",icon:Vo,href:"/agents/all"},{type:"separator"}],radioLabel:"Agent sort",radioChoices:mlt,radioValue:K,onRadioValueChange:te},children:[ie.map(be=>ke(be,!0)),ue.map(be=>ke(be,!1)),oe&&(()=>{const be=(0,t.jsxs)(Ke,{to:"/agents/all",state:Gf,"aria-label":v?"See all agents":void 0,onClick:r(()=>{p&&f(!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)(Vo,{className:"shrink-0 h-4 w-4"}),(0,t.jsx)("span",{className:v?"block w-0 min-w-0 overflow-hidden whitespace-nowrap text-transparent select-none":void 0,children:"See all agents"})]});return v?(0,t.jsxs)(zn,{children:[(0,t.jsx)(qn,{asChild:!0,children:be}),(0,t.jsx)(Un,{side:"right",children:"See all agents"})]}):be})()]})}r(flt,"SidebarAgents");var xlt="opacity-0 transition-opacity group-hover/starred-project:opacity-100 group-focus-within/starred-project:opacity-100";function glt(){const{selectedCompanyId:e}=ps(),{isMobile:s,setSidebarOpen:n,collapsed:a,peeking:i}=qa(),o=a&&!i,l=na(),{data:c}=Z({queryKey:P.projects.list(e),queryFn:r(()=>pa.list(e),"queryFn"),enabled:!!e}),d=Qf(e),u=Ag(e),h=l.pathname.match(/^\/(?:[^/]+\/)?projects\/([^/]+)/)?.[1]??null,p=(0,m.useMemo)(()=>{if(!d.isSuccess)return[];const v=new Set(PM(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=lg(v),N=h===j||h===v.id,w=b(v),k=w&&u.variables?.starred===!1,S=w&&u.variables?.state==="left",C=xb(d.data,"project",v.id),I=(0,t.jsxs)(ub,{to:`/projects/${j}/issues`,state:Gf,onClick:r(()=>{s&&n(!1)},"onClick"),className:W("flex min-w-0 flex-1 items-center gap-2.5 mx-2 rounded-lg px-2 py-1.5 pointer-coarse:py-1 pr-8 text-(length:--text-compact) font-medium transition-colors",!o&&"pl-6",N?"bg-accent text-foreground":"text-foreground/80 hover:bg-accent/50 hover:text-foreground"),children:[(0,t.jsx)(Em,{color:v.color??null,icon:v.icon??null,size:"xs"}),(0,t.jsx)("span",{className:o?By:"flex-1 truncate",children:v.name}),!o&&v.pauseReason==="budget"?(0,t.jsx)(JI,{title:"Project paused by budget"}):null]});return(0,t.jsxs)("div",{className:"group/starred-project relative flex items-center",children:[o?(0,t.jsxs)(zn,{children:[(0,t.jsx)(qn,{asChild:!0,children:(0,t.jsx)("div",{className:"min-w-0 flex-1",children:I})}),(0,t.jsx)(Un,{side:"right",children:v.name})]}):I,!o&&!s?(0,t.jsx)("span",{className:"absolute right-3 top-1/2 -translate-y-1/2",children:(0,t.jsx)(gb,{size:"row",quiet:!0,starred:C,pending:k,resourceName:v.name,onToggle:r(()=>f(v),"onToggle"),revealClassName:xlt})}):null,!o&&s?(0,t.jsxs)(Xr,{children:[(0,t.jsx)(Jr,{asChild:!0,children:(0,t.jsx)(L,{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)(Ri,{className:"h-3.5 w-3.5"})})}),(0,t.jsxs)(Zr,{align:"end",className:"w-48",children:[(0,t.jsxs)(ls,{onClick:r(()=>{w||f(v)},"onClick"),disabled:w,children:[k?(0,t.jsx)(rt,{className:"size-4 motion-safe:animate-spin"}):(0,t.jsx)(yp,{className:"size-4 fill-amber-500 text-amber-500"}),(0,t.jsx)("span",{children:"Remove from starred"})]}),(0,t.jsx)(ni,{}),(0,t.jsxs)(ls,{onClick:r(()=>{w||x(v)},"onClick"),disabled:w,children:[S?(0,t.jsx)(rt,{className:"size-4 motion-safe:animate-spin"}):(0,t.jsx)(Tp,{className:"size-4"}),(0,t.jsx)("span",{children:"Leave project"})]})]})]}):null]},v.id)})})}r(glt,"SidebarStarredProjects");var blt="size-5 shrink-0 rounded-md text-(length:--text-micro)",vlt="size-(--organization-popover-avatar-size) shrink-0 rounded-lg text-(length:--text-micro)",ylt="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",sO="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 zCe({company:e,inPopover:s=!1}){return(0,t.jsx)(eS,{companyName:e.name,logoUrl:e.logoUrl,className:s?vlt:blt})}r(zCe,"WorkspaceIcon");function jlt({company:e,isEditing:s,isSelected:n,onSelect:a}){const{attributes:i,listeners:o,setActivatorNodeRef:l,setNodeRef:c,transform:d,transition:u,isDragging:h}=qN({id:e.id,disabled:!s});return(0,t.jsxs)(ls,{ref:c,style:{transform:DN.Transform.toString(d),transition:u,zIndex:h?10:void 0},onSelect:r(p=>{if(s){p.preventDefault();return}a(e)},"onSelect"),className:W(ylt,s&&"cursor-grab",h&&"opacity-80"),children:[(0,t.jsx)(zCe,{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)(SM,{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)(gs,{className:"size-4 text-foreground"}):null})]})}r(jlt,"SortableCompanyItem");function wlt(e={}){return(0,t.jsx)(uje,{...e,children:(0,t.jsx)(klt,{...e})})}r(wlt,"SidebarCompanyMenu");function klt({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}=Qo(),{isMobile:f,setSidebarOpen:x,collapsed:b,peeking:v}=qa(),j=b&&!v,N=na(),w=Mn(),k=e??n,S=s??a,C=FN(Pf(l7,{activationConstraint:{distance:8}}),Pf(Pfe,{activationConstraint:{delay:180,tolerance:6}})),I=(0,m.useMemo)(()=>l.filter(ne=>ne.status!=="archived"),[l]),{data:R}=Z({queryKey:P.auth.session,queryFn:r(()=>Oa.getSession(),"queryFn"),retry:!1}),T=R?.user?.id??R?.session?.userId??null,{orderedCompanies:A,persistOrder:D}=dje({companies:I,userId:T}),{hidden:M,loaded:B}=eu(),E=B&&!cg(M,"company.members")&&!cg(M,"company.invites"),z="company",$=c?.name??null,q=!!$c(),U=ZN({onSignedOut:K});function O(ne){ne||o(!1),S(ne)}r(O,"handleOpenChange");function K(){S(!1),o(!1),f&&x(!1)}r(K,"closeNavigationChrome");function H(ne){const fe=N.pathname.split("/")[1]?.toUpperCase(),X=I.some(oe=>oe.issuePrefix.toUpperCase()===fe),re=ne.id!==c?.id&&(N.pathname.startsWith("/instance/")||X);d(ne.id),S(!1),f&&x(!1),re&&w(`/${ne.issuePrefix}/dashboard`)}r(H,"selectCompany");function ee(){q||(S(!1),f&&x(!1),p({initialStep:1}))}r(ee,"addCompany");const se=(0,m.useCallback)(ne=>{const{active:fe,over:X}=ne;if(!X||fe.id===X.id)return;const re=A.map(Y=>Y.id),oe=re.indexOf(fe.id),G=re.indexOf(X.id);oe===-1||G===-1||D(pM(re,oe,G))},[A,D]);return(0,t.jsxs)(Xr,{open:k,onOpenChange:O,children:[(0,t.jsx)(Jr,{asChild:!0,children:(0,t.jsxs)(L,{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":$?`Open ${$} ${z} switcher`:`Open ${z} switcher`,children:[(0,t.jsxs)("span",{className:"flex min-w-0 flex-1 items-center gap-2",children:[c?(0,t.jsx)(zCe,{company:c}):null,(0,t.jsx)("span",{className:W("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:$??void 0,children:$??`Select ${z}`})]}),!j&&(0,t.jsx)(bM,{className:"size-3.5 shrink-0 text-muted-foreground"})]})}),(0,t.jsxs)(Zr,{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)(mb,{className:"p-0 text-(length:--text-compact) font-semibold text-foreground",children:"Organizations"}),(0,t.jsx)("button",{type:"button",onClick:r(ne=>{ne.preventDefault(),ne.stopPropagation(),o(fe=>!fe)},"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)(ON,{sensors:C,collisionDetection:PI,onDragEnd:se,children:(0,t.jsx)(BN,{items:A.map(ne=>ne.id),strategy:LI,children:A.map(ne=>(0,t.jsx)(jlt,{company:ne,isEditing:i,isSelected:ne.id===c?.id,onSelect:H},ne.id))})}),A.length===0?u?(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)(ls,{disabled:!0,children:"Couldn't load companies"}),(0,t.jsxs)(ls,{onSelect:r(ne=>{ne.preventDefault(),h()},"onSelect"),children:[(0,t.jsx)(_i,{className:"h-4 w-4 mr-2"}),"Try again"]})]}):(0,t.jsx)(ls,{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:[!q&&(0,t.jsxs)(ls,{onClick:ee,className:sO,disabled:i,children:[(0,t.jsx)("span",{className:"flex size-5 shrink-0 items-center justify-center text-muted-foreground",children:(0,t.jsx)(yn,{className:"size-4"})}),(0,t.jsx)("span",{className:"min-w-0 flex-1 truncate",children:"Create organization"})]}),E?(0,t.jsx)(ls,{asChild:!0,disabled:i,className:sO,children:(0,t.jsxs)(Ke,{to:"/company/settings/invites",onClick:r(ne=>{if(i){ne.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)(Hf,{className:"size-4"})}),(0,t.jsx)("span",{className:"min-w-0 flex-1 truncate",children:$?`Invite people to ${$}`:"Invite people"})]})}):null,R?.session?(0,t.jsxs)(ls,{className:sO,onClick:r(()=>U.mutate(),"onClick"),disabled:i||U.isPending,children:[(0,t.jsx)("span",{className:"flex size-5 shrink-0 items-center justify-center text-muted-foreground",children:(0,t.jsx)(Tp,{className:"size-4"})}),(0,t.jsx)("span",{className:"min-w-0 flex-1 truncate",children:U.isPending?"Signing out...":"Sign out"})]}):null]})]})]})}r(klt,"BuiltinCompanyMenu");function Ise(){const{openNewIssue:e}=Qo(),[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=$M(o),{data:p,isFetched:f}=Z({queryKey:P.instance.experimentalSettings,queryFn:r(()=>Nr.getExperimental(),"queryFn")}),x=P.liveRuns(o),b=No({companyId:o,resourceKey:"live-runs",queryKey:x,enabled:!!o,refetchInterval:!1,leaderOnly:!0}),{data:v,dataUpdatedAt:j}=Z({queryKey:x,queryFn:r(()=>sa.liveRunsForCompany(o),"queryFn"),enabled:b.enabled,refetchInterval:b.refetchInterval});So(b,v,j);const N=v?.length??0,w=p?.enableIsolatedWorkspaces===!0,k=p?.enableApps===!0,S=p?.enablePipelines===!0,C=p?.enableStatusCards===!0,I=!f,R=p?.enableGoalsSidebarLink===!0,T=p?.enableDecisions===!0,{data:A}=Z({queryKey:P.attention(o),queryFn:r(()=>YN.list(o),"queryFn"),enabled:!!o&&T,refetchInterval:6e4}),D=Bye(A),M=p?.enableCases===!0,B=!0,E=p?.enableConferenceRoomChat===!0,z={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)(wlt,{})}),(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 $=(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)(p_,{className:"h-4 w-4 shrink-0"}),(0,t.jsx)("span",{className:u?By:"truncate",children:"New Task"})]});return u?(0,t.jsxs)(zn,{children:[(0,t.jsx)(qn,{asChild:!0,children:$}),(0,t.jsx)(Un,{side:"right",children:"New Task"})]}):$})(),(0,t.jsx)(si,{to:"/search",label:"Search",icon:oa}),(0,t.jsx)(si,{to:"/dashboard",label:"Dashboard",icon:Zx,liveCount:N}),(0,t.jsx)(si,{to:"/inbox",label:"Inbox",icon:hd,badge:h.inbox,badgeLabel:"unread",badgeTone:h.failedRuns>0?"danger":"default",alert:h.failedRuns>0}),T?(0,t.jsx)(si,{to:"/decisions",label:"Decisions",icon:Hy,badge:D,badgeLabel:"decisions"}):null,C?(0,t.jsx)(si,{to:"/status",label:"Status",icon:GN,textBadge:"beta"}):null,E?(0,t.jsx)(si,{to:"/board-chat",label:"Conference Room",icon:rbe}):null]}),(0,t.jsxs)(eg,{label:"Work",collapsible:{open:s,onOpenChange:n},children:[(0,t.jsx)(si,{to:"/issues",label:"Tasks",icon:Cu}),M?(0,t.jsx)(si,{to:"/cases",label:"Cases",icon:zl,textBadge:"beta"}):null,(0,t.jsx)(si,{to:"/routines",label:"Routines",icon:Tu}),S?(0,t.jsx)(si,{to:"/pipelines",label:"Pipelines",icon:io}):null,R?(0,t.jsx)(si,{to:"/goals",label:"Goals",icon:vp}):I?(0,t.jsx)("div",{"data-testid":"sidebar-goals-placeholder",className:"h-8 pointer-coarse:h-7","aria-hidden":"true"}):null,(0,t.jsx)(si,{to:"/artifacts",label:"Artifacts",icon:Th}),(0,t.jsx)(si,{to:"/skills",label:"Skills",icon:xc}),w?(0,t.jsx)(si,{to:"/workspaces",label:"Workspaces",icon:io}):null,(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)(si,{to:"/projects",label:"Projects",icon:Ho}),(0,t.jsx)(glt,{})]}),(0,t.jsx)(Sp,{slotTypes:["sidebar"],context:z,className:"flex flex-col gap-0.5",itemClassName:"text-(length:--text-compact) font-medium",missingBehavior:"placeholder"}),(0,t.jsx)(XN,{placementZones:["sidebar"],context:z,className:"flex flex-col gap-0.5",itemClassName:"text-(length:--text-compact) font-medium"})]}),null,(0,t.jsx)(flt,{streamlined:B}),(0,t.jsxs)(eg,{label:"Company",collapsible:{open:a,onOpenChange:i},children:[(0,t.jsx)(si,{to:"/org",label:"Org",icon:hy}),k?(0,t.jsx)(si,{to:"/apps",label:"Connectors",icon:K3}):null,(0,t.jsx)(si,{to:"/timeline",label:"Timeline",icon:x0}),(0,t.jsx)(si,{to:"/costs",label:"Costs",icon:mp}),(0,t.jsx)(si,{to:"/activity",label:"Activity",icon:Zl}),(0,t.jsx)(si,{to:"/company/settings",label:"Settings",icon:Jd})]}),(0,t.jsx)(Sp,{slotTypes:["sidebarPanel"],context:z,className:"flex flex-col gap-3",itemClassName:"rounded-lg border border-border p-3",missingBehavior:"placeholder"})]})]})}r(Ise,"Sidebar");function Nlt(e){const s=e.manifestJson.environmentDrivers??[];return s.length===0?!1:s.every(n=>n.kind==="sandbox_provider")}r(Nlt,"isSandboxProviderOnly");function Slt(){const{selectedCompany:e,selectedCompanyId:s}=ps(),{isMobile:n,setSidebarOpen:a}=qa(),{hidden:i}=eu(),o=r(f=>!i.has(f),"showPage"),l=o("instance.plugins"),c=!!$c(),{slots:d}=bd({slotTypes:["companySettingsPage"],companyId:s,enabled:!!s}),{data:u}=Z({queryKey:s?P.sidebarBadges(s):["sidebar-badges","__disabled__"],queryFn:r(async()=>{try{return await l9.get(s)}catch(f){if(f instanceof dn&&(f.status===401||f.status===403))return null;throw f}},"queryFn"),enabled:!!s,retry:!1,refetchInterval:15e3}),{data:h}=Z({queryKey:P.plugins.all,queryFn:r(()=>Al.list(),"queryFn"),enabled:l}),p=(h??[]).filter(f=>!Nlt(f));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)(Ke,{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)(Uu,{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)(si,{to:"/company/settings",label:"General",icon:Ku,end:!0}),o("instance.profile")&&(0,t.jsx)(si,{to:"/company/settings/instance/profile",label:"Profile",icon:AM,end:!0}),o("company.members")&&(0,t.jsx)(si,{to:"/company/settings/members",label:"Members",icon:Vo,badge:u?.joinRequests??0,end:!0}),d.filter(f=>f.routePath).map(f=>(0,t.jsx)(si,{to:`/company/settings/${f.routePath}`,label:f.displayName,icon:Xx,end:!0},`${f.pluginKey}:${f.id}`)),o("company.invites")&&(0,t.jsx)(si,{to:"/company/settings/invites",label:"Invites",icon:cqe,end:!0}),o("company.secrets")&&(0,t.jsx)(si,{to:"/company/settings/secrets",label:"Secrets",icon:Si,end:!0}),o("instance.environments")&&(0,t.jsx)(si,{to:"/company/settings/instance/environments",label:"Environments",icon:cbe,end:!0}),o("instance.access")&&(0,t.jsx)(si,{to:"/company/settings/instance/access",label:"Access",icon:RI,end:!0}),o("instance.heartbeats")&&(0,t.jsx)(si,{to:"/company/settings/instance/heartbeats",label:"Heartbeats",icon:Yd,end:!0}),o("company.export")&&(0,t.jsx)(si,{to:"/company/export",label:"Export",icon:po}),!c&&o("company.import")&&(0,t.jsx)(si,{to:"/company/import",label:"Import",icon:py,end:!0}),o("instance.experimental")&&(0,t.jsx)(si,{to:"/company/settings/instance/experimental",label:"Experimental",icon:Dm}),l&&(0,t.jsx)(si,{to:"/company/settings/instance/plugins",label:"Plugins",icon:Xx}),l&&p.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:p.map(f=>(0,t.jsx)(ub,{to:`${ep}/plugins/${f.id}`,state:Gf,className:r(({isActive:x})=>["rounded-md px-2 py-1.5 text-xs transition-colors",x?"bg-accent text-foreground":"text-muted-foreground hover:bg-accent/50 hover:text-foreground"].join(" "),"className"),children:f.manifestJson.displayName??f.packageName},f.id))}):null,o("instance.adapters")&&(0,t.jsx)(si,{to:"/company/settings/instance/adapters",label:"Adapters",icon:ym})]})})]})}r(Slt,"CompanySettingsSidebar");function Clt(){const{pathname:e}=na(),{selectedCompany:s}=ps(),{isMobile:n,setSidebarOpen:a}=qa(),i=yje(),{enabled:o}=OM(),l=h9.filter(d=>!vje(d.key)||o);if(e.endsWith("/apps/chat/connect"))return(0,t.jsx)(W7,{});const c=e.match(/\/apps\/chat\/([^/]+)(?:\/(?:settings|access|reviews|conversations|activity|approvals|audit))?\/?$/);return c?(0,t.jsx)(bje,{endpointId:c[1],NavItem:si}):(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)(Ke,{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)(Uu,{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)(aX,{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)(si,{to:"/apps",label:"Browse",icon:f_,end:!0}),(0,t.jsx)(si,{to:"/apps/review",label:"Review",icon:QN,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)(si,{to:"/apps/connections",label:"Connections",icon:aX,end:!0}),l.map(d=>(0,t.jsx)(si,{to:L0(d.key),label:d.label,icon:d.icon,end:!0},d.key))]})]})]})}r(Clt,"AppsSidebar");function Ase(e){const{selectedCompanyId:s}=ps(),{isMobile:n,setSidebarOpen:a}=qa(),i=Z({queryKey:P.tools.connection(e.kind==="connection"?e.connectionId:"__none__"),queryFn:r(()=>Zt.getConnection(e.kind==="connection"?e.connectionId:""),"queryFn"),enabled:e.kind==="connection"&&!!e.connectionId}),o=Z({queryKey:P.tools.applications(s??"__none__"),queryFn:r(()=>Zt.listApplications(s),"queryFn"),enabled:e.kind==="application"&&!!s}),l=Z({queryKey:P.tools.connections(s??"__none__"),queryFn:r(()=>Zt.listConnections(s),"queryFn"),enabled:e.kind==="application"&&!!s}),c=Z({queryKey:P.apps.gallery(s??"__none__"),queryFn:r(()=>Zt.listGallery(s),"queryFn"),enabled:!!s}),d=Z({queryKey:P.apps.attention(s??"__none__"),queryFn:r(()=>Zt.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=Alt(e.kind==="application"?(l.data?.connections??[]).filter(N=>N.applicationId===e.applicationId):[]),f=u?Lf(u):h?.name??"App",x=Ilt(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)(Ke,{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)(Uu,{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)(al,{name:f,logoUrl:tA(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:FM.map(N=>(0,t.jsx)(si,{to:_lt(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(Ase,"AppDetailSidebar");function _lt(e,s){return e.kind==="connection"?vm(e.connectionId,s):S1(e.applicationId,s)}r(_lt,"tabHref");function Ilt(e,s,n){if(n?.applicationKey){const i=e.find(o=>mc(o)===n.applicationKey);if(i)return i}const a=(s?.name??n?.name)?.toLowerCase();return a?e.find(i=>tg(i).toLowerCase()===a)??e.find(i=>mc(i)===a)??null:null}r(Ilt,"galleryEntryFor$1");function Alt(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(Alt,"latestArchivedConnection$1");function nO({identifier:e}){return e?(0,t.jsx)("span",{className:"shrink-0 font-mono text-muted-foreground",children:e}):null}r(nO,"CrumbIdentifier");function Tlt({context:e}){const{slots:s}=bd({slotTypes:["globalToolbarButton"],companyId:e.companyId}),{launchers:n}=d9({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)(Sp,{slotTypes:["globalToolbarButton"],context:e,className:"flex items-center gap-1"}):null,n.length>0?(0,t.jsx)(XN,{placementZones:["globalToolbarButton"],context:e,className:"flex items-center gap-1"}):null]})}r(Tlt,"GlobalToolbar");function Rlt(){const{breadcrumbs:e,mobileToolbar:s}=Bn(),{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)(Tlt,{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)(L,{variant:"ghost",size:"icon-sm",className:"mr-2 shrink-0",onClick:n,"aria-label":"Open sidebar",children:(0,t.jsx)(Q0e,{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)(nO,{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)(p9,{className:"min-w-0 overflow-hidden",children:(0,t.jsx)(f9,{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)(t5,{}),(0,t.jsx)(C1,{className:p?"min-w-0":"shrink-0",children:p||!u.href?u.leading||u.identifier?(0,t.jsxs)(w_,{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)(nO,{identifier:u.identifier}),(0,t.jsx)("span",{className:"truncate",children:u.label})]}):(0,t.jsx)(w_,{className:"truncate",children:u.label}):(0,t.jsx)(e5,{asChild:!0,children:u.leading||u.identifier?(0,t.jsxs)(Ke,{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)(nO,{identifier:u.identifier}),(0,t.jsx)("span",{className:"truncate",children:u.label})]}):(0,t.jsx)(Ke,{to:u.href,onClick:u.onClick,children:u.label})})})]},h)})})})}),c]})}r(Rlt,"BreadcrumbBar");var Z2=240,j6=208,w6=420,Tse=16;function B5(e){return Math.min(w6,Math.max(j6,e))}r(B5,"clampSidebarWidth");function Rse(e){if(typeof window>"u")return Z2;try{const s=window.localStorage.getItem(e);if(!s)return Z2;const n=Number.parseInt(s,10);return Number.isFinite(n)?B5(n):Z2}catch{return Z2}}r(Rse,"readStoredSidebarWidth");function Ese(e,s){if(!(typeof window>"u"))try{window.localStorage.setItem(e,String(B5(s)))}catch{}}r(Ese,"writeStoredSidebarWidth");function Elt({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)(()=>Rse(o)),[x,b]=(0,m.useState)(!1),v=(0,m.useRef)(p),j=(0,m.useRef)(null);(0,m.useEffect)(()=>{const E=Rse(o);v.current=E,f(E)},[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,I=(0,m.useMemo)(()=>({width:`${w}px`}),[w]),R=(0,m.useMemo)(()=>({width:`${k}px`}),[k]),T=(0,m.useCallback)(E=>{const z=B5(E);v.current=z,f(z),Ese(o,z)},[o]),A=(0,m.useCallback)(E=>{C&&(E.preventDefault(),E.currentTarget.setPointerCapture(E.pointerId),j.current={startX:E.clientX,startWidth:v.current},b(!0))},[C]),D=(0,m.useCallback)(E=>{if(!j.current)return;const z=B5(j.current.startWidth+E.clientX-j.current.startX);v.current=z,f(z)},[]),M=(0,m.useCallback)(()=>{j.current&&(j.current=null,b(!1),Ese(o,v.current))},[o]),B=(0,m.useCallback)(E=>{C&&(E.key==="ArrowLeft"?(E.preventDefault(),T(p-Tse)):E.key==="ArrowRight"?(E.preventDefault(),T(p+Tse)):E.key==="Home"?(E.preventDefault(),T(j6)):E.key==="End"&&(E.preventDefault(),T(w6)))},[C,T,p]);return(0,t.jsx)("div",{className:W("relative h-full shrink-0",l),style:I,children:(0,t.jsxs)("div",{className:W("absolute inset-y-0 left-0 flex flex-col overflow-hidden",S?"z-30 border-r border-border bg-background shadow-lg":"z-0"),style:R,"data-sidebar-overlay":S?"":void 0,onMouseEnter:c,onMouseLeave:d,onFocusCapture:u,onBlurCapture:h,children:[e,C?(0,t.jsx)("div",{role:"separator","aria-label":"Resize sidebar","aria-orientation":"vertical","aria-valuemin":j6,"aria-valuemax":w6,"aria-valuenow":p,tabIndex:0,className:W("absolute inset-y-0 right-0 z-20 w-3 cursor-col-resize touch-none outline-none","before:absolute before:inset-y-0 before:left-1/2 before:w-px before:-translate-x-1/2 before:bg-transparent before:transition-colors","hover:before:bg-border focus-visible:before:bg-ring",x&&"before:bg-ring"),onPointerDown:A,onPointerMove:D,onPointerUp:M,onPointerCancel:M,onLostPointerCapture:M,onKeyDown:B}):null]})})}r(Elt,"SidebarShell");function Plt({children:e,className:s}){return(0,t.jsx)("div",{"data-secondary-sidebar":"",className:W("h-full w-60 shrink-0 overflow-y-auto border-r border-border bg-background",s),children:(0,t.jsx)(clt,{children:e})})}r(Plt,"SecondarySidebar");var Mlt="/company/settings/members?tab=invites",Dlt="https://docs.paperclip.ing/",Llt="https://paperclip.ing/feedback";function $lt(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($lt,"deriveInitials$1");function Pse({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)(Ke,{to:i,className:c,onClick:a,children:d}):(0,t.jsx)("button",{type:"button",className:c,onClick:a,children:d})}r(Pse,"MenuAction");function Mse({deploymentMode:e,open:s,onOpenChange:n}){const i=!!$c(),{hidden:o,loaded:l}=eu(),c=wCe(),d=kCe(!i),u=i?c:d?Mlt:null,h=l&&u!==null&&!cg(o,"company.members")&&!cg(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=NCe(w),S=n??f,{data:C}=Z({queryKey:P.auth.session,queryFn:r(()=>Oa.getSession(),"queryFn"),retry:!1}),I=ZN({onSignedOut:M}),R=C?.user.name?.trim()||"Board",T=C?.user.email?.trim()||(e==="authenticated"?"Signed in":"Local workspace board"),A=$lt(R),D=SCe(C?.user);function M(){S(!1),x&&b(!1)}r(M,"closeNavigationChrome");function B(){I.mutate()}return r(B,"handleSignOut"),(0,t.jsx)("div",{className:"border-t border-r border-border bg-background px-3 py-2",children:(0,t.jsxs)("div",{className:W("flex items-center gap-0.5",!N&&"px-2"),children:[(0,t.jsxs)(gr,{open:w,onOpenChange:S,children:[(0,t.jsx)(Sr,{asChild:!0,children:(0,t.jsxs)("button",{type:"button",className:W("flex min-w-0 items-center gap-2.5 rounded-lg text-left text-(length:--text-compact) font-medium text-foreground/80 transition-colors hover:bg-accent/50 hover:text-foreground",N?"w-full px-3 py-2":"flex-1 px-2 py-1.5"),"aria-label":"Open account menu",children:[(0,t.jsxs)(Mo,{size:"sm",children:[C?.user.image?(0,t.jsx)(xd,{src:C.user.image,alt:R}):null,(0,t.jsx)(Do,{children:A})]}),(0,t.jsx)("span",{className:W("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)(dr,{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)(Ke,{to:D,"aria-label":"View profile",onClick:M,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)(Mo,{size:"lg",children:[C?.user.image?(0,t.jsx)(xd,{src:C.user.image,alt:R}):null,(0,t.jsx)(Do,{children:A})]})}),(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:T}),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)(Pse,{label:"Invite",description:"Invite people to your organization.",icon:Hf,href:u,topLevel:i,onClick:M}):null,(0,t.jsx)(Pse,{label:"Documentation",description:"Open Paperclip docs in a new tab.",icon:HN,href:Dlt,external:!0,onClick:r(()=>S(!1),"onClick")}),(0,t.jsx)(yk,{variant:"menu-action",onAfterToggle:r(()=>S(!1),"onAfterToggle")}),(0,t.jsx)(ICe,{variant:"menu-action",onAfterAction:r(()=>S(!1),"onAfterAction")}),e==="authenticated"?(0,t.jsxs)("button",{type:"button",className:W("flex w-full items-start gap-3 rounded-xl px-3 py-3 text-left transition-colors hover:bg-destructive/10",I.isPending&&"cursor-not-allowed opacity-60"),onClick:B,disabled:I.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)(Tp,{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:I.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)(ACe,{})]})]})]})]}),!N&&!i?(0,t.jsxs)(zn,{children:[(0,t.jsx)(qn,{asChild:!0,children:(0,t.jsx)("a",{href:Llt,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)(Cg,{className:"h-4 w-4","aria-hidden":"true"})})}),(0,t.jsx)(Un,{side:"top",children:"Share feedback"})]}):null]})})}r(Mse,"SidebarAccountMenu");function Olt(e,s){return qCe(e,s)[0]?.toLowerCase()??null}r(Olt,"getCompanyRouteSegment");function qCe(e,s){if(!s)return[];const n=e.split("/").filter(Boolean);return n.length<2?[]:n[0]?.toUpperCase()!==s.toUpperCase()?[]:n.slice(1)}r(qCe,"getCompanyPathSegments");var Flt=new Set(["browse","connections","connect","chat","review","attention","gateways","advanced","app"]);function Blt(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(Blt,"isSkillsStoreRoute");function zlt(){const{sidebarOpen:e,setSidebarOpen:s,toggleSidebar:n,collapsed:a,peeking:i,setPeeking:o,isMobile:l,setForceCollapsed:c}=qa(),{openNewIssue:d,openOnboarding:u}=Qo(),{togglePanelVisible:h}=Yf(),p=Xc()?.pushToast??null,{companies:f,loading:x,selectedCompany:b,selectedCompanyId:v,selectionSource:j,setSelectedCompanyId:N}=ps(),{companyPrefix:w,pluginRoutePath:k}=va(),S=Mn(),C=na(),I=dM(),R=pje(C.pathname,w).isTaskDetail,T=["/company/settings","/company/export","/company/import"].some(vt=>C.pathname.includes(vt)),A=qCe(C.pathname,w),D=A[0]?.toLowerCase()==="tools",M=A[0]?.toLowerCase()==="apps",B=M&&A[1]&&!Flt.has(A[1].toLowerCase())?A[1]:null,E=M&&A[1]?.toLowerCase()==="app"&&A[2]?A[2]:null,z=Blt(C.pathname,w),$=(0,m.useRef)(!1),q=(0,m.useRef)(null),U=(0,m.useRef)(null),O=(0,m.useRef)(new rye),K=(0,m.useRef)(C.key),H=DCe(l&&!R,C.pathname),[ee,se]=(0,m.useState)(!1),ne=(0,m.useMemo)(()=>{if(!w)return null;const vt=w.toUpperCase();return f.find(Le=>Le.issuePrefix.toUpperCase()===vt)??null},[f,w]),fe=!!w&&!x&&f.length>0&&!ne,X=(0,m.useMemo)(()=>k?.toLowerCase()??Olt(C.pathname,w),[w,C.pathname,k]),re=ne?.id??null,oe=ne?.issuePrefix??null,{slots:G}=bd({slotTypes:["page","routeSidebar"],companyId:re,enabled:!!(re&&X)}),Y=(0,m.useMemo)(()=>s9(G,X),[X,G]),Q=(0,m.useMemo)(()=>({companyId:re,companyPrefix:oe}),[re,oe]),te=T?(0,t.jsx)(Slt,{}):B?(0,t.jsx)(Ase,{kind:"connection",connectionId:B}):E?(0,t.jsx)(Ase,{kind:"application",applicationId:E}):M||D?(0,t.jsx)(Clt,{}):Y?(0,t.jsx)(Wu,{slot:Y,context:Q,className:"h-full w-full",missingBehavior:"placeholder"}):null,ae=te!=null,{data:le}=Z({queryKey:P.health,queryFn:r(()=>tu.get(),"queryFn"),retry:!1,refetchInterval:r(vt=>vt.state.data?.devServer?.enabled?2e3:!1,"refetchInterval"),refetchIntervalInBackground:!1}),he=ae||z;(0,m.useLayoutEffect)(()=>(c(he),()=>c(!1)),[he,c]),(0,m.useEffect)(()=>{x||$.current||le?.deploymentMode!=="authenticated"&&(le?.cloud||f.length===0&&($.current=!0,u()))},[f,x,u,le?.cloud,le?.deploymentMode]),(0,m.useEffect)(()=>{if(!w||x||f.length===0)return;if(!ne){const Le=(v?f.find(Qe=>Qe.id===v):null)??f[0]??null;Le&&v!==Le.id&&N(Le.id,{source:"route_sync"});return}if(w!==ne.issuePrefix){const Le=C.pathname.replace(/^\/[^/]+/,"");S(`/${ne.issuePrefix}${Le}${C.search}`,{replace:!0});return}const vt=LCe({matchedCompany:ne,selectedCompanyId:v,companies:f});if(vt){p?.({title:`${ne.name} is archived`,body:`Switched to ${vt.name}.`,tone:"info",dedupeKey:`archived-company-bounce:${ne.id}`}),N(vt.id,{source:"route_sync"}),S(`/${vt.issuePrefix}/dashboard`,{replace:!0});return}$Ce({selectionSource:j,selectedCompanyId:v,routeCompanyId:ne.id})&&N(ne.id,{source:"route_sync"})},[w,f,x,ne,C.pathname,C.search,S,p,j,v,N]);const ce=h,ge=(0,m.useCallback)(()=>{document.dispatchEvent(new KeyboardEvent("keydown",{key:"k",metaKey:!0,bubbles:!0,cancelable:!0}))},[]),me=(0,m.useRef)(null),ie=(0,m.useRef)(!1),ue=(0,m.useRef)(!1),ke=(0,m.useCallback)(()=>{me.current!==null&&(window.clearTimeout(me.current),me.current=null)},[]),be=(0,m.useCallback)(()=>{ke(),me.current=window.setTimeout(()=>o(!0),50)},[ke,o]),Ie=(0,m.useCallback)(()=>{ke(),o(!0)},[ke,o]),Ue=(0,m.useCallback)(()=>{ke(),me.current=window.setTimeout(()=>o(!1),120)},[ke,o]),at=(0,m.useCallback)(()=>{ie.current=!0,a&&!ue.current&&be()},[a,be]),dt=(0,m.useCallback)(()=>{ie.current=!1,ue.current=!1,Ue()},[Ue]),de=(0,m.useCallback)(()=>{ue.current||Ie()},[Ie]),Be=(0,m.useCallback)(()=>{ie.current||Ue()},[Ue]);(0,m.useEffect)(()=>ke,[ke]);const pt=(0,m.useRef)(a);return(0,m.useEffect)(()=>{a!==pt.current&&(a?(ke(),o(!1),ue.current=ie.current):ue.current=!1,pt.current=a)},[a,ke,o]),(0,m.useEffect)(()=>{if(!i)return;const vt=r(Le=>{Le.key==="Escape"&&(ke(),o(!1))},"onKeyDown");return window.addEventListener("keydown",vt),()=>window.removeEventListener("keydown",vt)},[i,ke,o]),MCe(),TCe({onNewIssue:r(()=>d(),"onNewIssue"),onSearch:ge,onToggleSidebar:n,onTogglePanel:ce,onShowShortcuts:r(()=>se(!0),"onShowShortcuts"),onGoToInbox:r(()=>S("/inbox"),"onGoToInbox")}),(0,m.useEffect)(()=>{if(!l)return;const vt=30,Le=50,Qe=75;let ut=0,Ye=0;const it=r(tt=>{const Pe=tt.touches[0];ut=Pe.clientX,Ye=Pe.clientY},"onTouchStart"),kt=r(tt=>{const Pe=tt.changedTouches[0],Ce=Pe.clientX-ut;if(!(Math.abs(Pe.clientY-Ye)>Qe)){if(!e&&ut<vt&&Ce>Le){s(!0);return}e&&Ce<-50&&s(!1)}},"onTouchEnd");return document.addEventListener("touchstart",it,{passive:!0}),document.addEventListener("touchend",kt,{passive:!0}),()=>{document.removeEventListener("touchstart",it),document.removeEventListener("touchend",kt)}},[l,e,s]),(0,m.useEffect)(()=>{const vt=document.body.style.overflow;return document.body.style.overflow=l?"visible":"clip",()=>{document.body.style.overflow=vt}},[l]),(0,m.useEffect)(()=>{if(!l)return FCe()},[l]),(0,m.useEffect)(()=>{if(typeof document>"u")return;const vt=U.current;return OCe(vt)},[C.pathname]),(0,m.useEffect)(()=>{const vt=U.current;if(!vt)return;const Le=r(()=>{O.current.remember(K.current,vt.scrollTop)},"recordScroll");return vt.addEventListener("scroll",Le,{passive:!0}),()=>vt.removeEventListener("scroll",Le)},[]),(0,m.useLayoutEffect)(()=>{const vt=U.current,Le=nye({previousPathname:q.current,pathname:C.pathname,navigationType:I,state:C.state});q.current=C.pathname;const Qe=I==="POP",ut=Qe?O.current.recall(C.key):0;if(K.current=C.key,Qe){V3(vt,ut);const Ye=requestAnimationFrame(()=>V3(vt,ut));return()=>cancelAnimationFrame(Ye)}Le&&aye(vt)},[C.key,C.pathname,C.state,I]),(0,t.jsx)(sye,{children:(0,t.jsxs)("div",{className:W("bg-background text-foreground pt-(--sz-safe-top)",l?"min-h-dvh overflow-x-clip":"flex h-dvh flex-col overflow-clip"),children:[(0,t.jsx)("a",{href:"#main-content",className:"sr-only focus:not-sr-only focus:fixed focus:left-3 focus:top-3 focus:z-(--z-200) focus:rounded-md focus:bg-background focus:px-3 focus:py-2 focus:text-sm focus:font-medium focus:shadow-lg focus:outline-none focus-visible:ring-2 focus-visible:ring-ring",children:"Skip to Main Content"}),(0,t.jsx)(cCe,{}),(0,t.jsx)(dCe,{devServer:le?.devServer}),(0,t.jsxs)("div",{className:W("min-h-0 flex-1",l?"w-full":"flex overflow-clip"),children:[l&&e&&(0,t.jsx)("button",{type:"button",className:"fixed inset-0 z-40 bg-black/50",onClick:r(()=>s(!1),"onClick"),"aria-label":"Close sidebar"}),l?(0,t.jsxs)("div",{className:W("fixed inset-y-0 left-0 z-50 flex flex-col overflow-hidden pt-(--sz-safe-top) transition-transform duration-100 ease-out",e?"translate-x-0":"-translate-x-full"),children:[(0,t.jsx)("div",{className:"flex flex-1 min-h-0 overflow-hidden",children:(0,t.jsx)("div",{className:"w-60 shrink-0 overflow-hidden",children:ae?te:(0,t.jsx)(Ise,{})})}),(0,t.jsx)(Mse,{deploymentMode:le?.deploymentMode})]}):(0,t.jsxs)(Elt,{open:e,collapsed:a,peeking:i,resizable:!0,onPanelMouseEnter:at,onPanelMouseLeave:dt,onPanelFocusCapture:a?de:void 0,onPanelBlurCapture:a?Be:void 0,children:[(0,t.jsx)("div",{className:"flex flex-1 min-h-0",children:(0,t.jsx)(Ise,{})}),(0,t.jsx)(Mse,{deploymentMode:le?.deploymentMode})]}),!l&&ae?(0,t.jsx)(Plt,{children:te}):null,(0,t.jsxs)("div",{className:W("flex min-w-0 flex-col",l?"w-full":"h-full flex-1"),children:[(0,t.jsxs)("div",{className:W(l&&"sticky top-0 z-20 bg-background/95 backdrop-blur supports-[backdrop-filter]:bg-background/85"),children:[(0,t.jsx)(f6,{mobile:l,onNavigateHome:r(()=>S("/dashboard"),"onNavigateHome")}),(0,t.jsx)(Rlt,{}),l&&T?(0,t.jsx)("div",{className:"border-b border-border px-4 pb-3",children:(0,t.jsx)(gje,{})}):null]}),(0,t.jsxs)("div",{className:W(l?"block":"flex flex-1 min-h-0"),children:[(0,t.jsx)("main",{id:"main-content",ref:U,tabIndex:-1,style:l?{"--tc-composer-bottom":"var(--sz-calc-14)"}:void 0,className:W("flex-1 p-4 outline-none md:p-6",l?"overflow-visible pb-(--sz-calc-14)":"overflow-auto [scrollbar-gutter:stable]"),children:fe?(0,t.jsx)(Pu,{scope:"invalid_company_prefix",requestedPrefix:w??b?.issuePrefix}):(0,t.jsx)(pCe,{children:(0,t.jsx)(db,{})})}),(0,t.jsx)(Aje,{})]})]})]}),l&&(0,t.jsx)(lCe,{visible:H}),(0,t.jsx)(Tje,{}),(0,t.jsx)(dwe,{}),(0,t.jsx)(eCe,{}),(0,t.jsx)(nCe,{}),(0,t.jsx)(rCe,{}),(0,t.jsx)(aCe,{open:ee,onOpenChange:se}),(0,t.jsx)(iCe,{}),(0,t.jsx)(oCe,{localTrusted:le?.deploymentMode==="local_trusted"})]})})}r(zlt,"Layout");var Dse=null;function qlt(){return Dse??=new zN,Dse}r(qlt,"getDetachedClient");function Ult(){const e=(0,m.useContext)(SI),{data:s,isFetched:n}=Z({queryKey:P.instance.experimentalSettings,queryFn:r(()=>Nr.getExperimental(),"queryFn"),enabled:e!=null},e??qlt());return e?{enabled:s?.enableConferenceRoomChat===!0,loaded:n}:{enabled:!1,loaded:!0}}r(Ult,"useConferenceRoomChatEnabled");function Klt(){const{enabled:e,loaded:s}=Ult();return s?e?(0,t.jsx)(db,{}):(0,t.jsx)(kn,{to:"/dashboard",replace:!0}):null}r(Klt,"ConferenceRoomChatGate");var Wlt=["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"],Vlt={"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 }"}},Als=Wlt.map(e=>Vlt[e]);function UCe({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)(Ap,{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)(L,{variant:"ghost",size:"sm",onClick:r(()=>n(e.id),"onClick"),children:a?"View session":"Open browser"})]})}r(UCe,"TaskBrowserActivity");function KCe({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)(sqe,{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)(Ke,{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)(io,{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(KCe,"TaskChatProjectCreatedCard");function Hlt({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)(Ef,{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(Hlt,"TaskChatSkillCreatedCard");function Glt(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(Glt,"McpIcon");var Qlt=new Set(["tool","tool call","tool_call","acp_tool"]);function Hd(e){const s=(e??"").trim().toLowerCase().replace(/\s*\((?:pending|in[_ -]?progress|completed|failed|cancelled|canceled)\)$/,"");return!s||Qlt.has(s)}r(Hd,"isGenericToolName");function WW(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(WW,"mcpToolIdentity");function VW(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(VW,"identifierWords");function WCe(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(WCe,"sentenceCase");function jk(e){const s=(e??"").trim();return Hd(s)?"Unnamed tool":WCe(VW(WW(s)?.name??s))}r(jk,"humanizeToolName");var Sd=r((e,s,n)=>({key:e,singular:s,plural:n}),"group"),Ylt={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:Sd("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:Sd("task_operation","task operation","task operations")},task_create:{action:"create",running:"Creating a task",completed:"Created a task",family:"plan",group:Sd("task_operation","task operation","task operations")},task_update:{action:"update",running:"Updating a task",completed:"Updated a task",family:"plan",group:Sd("task_operation","task operation","task operations")},task_list:{action:"list",running:"Listing tasks",completed:"Listed tasks",family:"plan",group:Sd("task_operation","task operation","task operations")},task_get:{action:"read",running:"Reading a task",completed:"Read a task",family:"plan",group:Sd("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:Sd("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"}},Jlt={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:[]},Xlt={read:"read",edit:"update",delete:"delete",move:"move",search:"search",list:"list",execute:"run",think:"think",fetch:"fetch",switch_mode:"switch"};function Zlt(e){return VW(e).join("_")}r(Zlt,"normalizedKey");function ect(e){const s=e[0];if(!s)return null;for(const[n,a]of Object.entries(Jlt))if(a.includes(s))return n;return null}r(ect,"inferredAction");function tct(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(tct,"actionFamily");var sct={terminal:mg,grep:jqe,search:oa,read:HN,edit:kM,web:Kze,plan:Hy,question:Pc,agent:hy,safety:Di,image:GI,wait:Yd,mcp:Glt,other:Ef};function nct(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(nct,"actionCopy");function rct(e){switch(e){case"run":return Sd("command","command","commands");case"read":case"list":return Sd("read","read","reads");case"search":return Sd("search","search","searches");case"update":case"create":case"delete":case"move":return Sd("file_change","file change","file changes");case"start":case"stop":return Sd("delegation","delegation","delegations");case"wait":return Sd("wait","wait","waits");default:return Sd("tool_action","tool action","tool actions")}}r(rct,"defaultSummaryGroup");function act(e){return e==="read"||e==="list"?Sd("paperclip_read","Paperclip read","Paperclip reads"):Sd("task_operation","task operation","task operations")}r(act,"paperclipSummaryGroup");function wy(e){const s=(e.name??"").trim(),n=WW(s),a=(e.namespace??n?.namespace??"").trim(),i=(n?"mcp":e.transport??"builtin").toLowerCase(),o=(n?.name??s).trim(),l=VW(o),c=Zlt(o),d=Ylt[c],u=Xlt[(e.operation??"").trim().toLowerCase()],h=ect(l),p=d?.action??u??h??"other",f=d?"exact":u?"kind":h?"inferred":Hd(o)?"unnamed":"fallback",x=Hd(o)?"Unnamed tool":jk(o),b=/^[A-Za-z][A-Za-z0-9_.:-]*$/.test(o),v=h&&b&&l.length>1?l.slice(1):[],j=v.length?WCe(v).replace(/^./,I=>I.toLowerCase()):void 0,N=d?.running&&d.completed?{running:d.running,completed:d.completed}:p==="other"?Hd(o)?{running:"Running an unnamed tool",completed:"Ran an unnamed tool"}:{running:`Running ${x}`,completed:`Ran ${x}`}:nct(p,d?void 0:j),w=d?.family??tct(p),k=i==="mcp"?"mcp":w,S=a?jk(a):i==="mcp"?"MCP":void 0,C=a.toLowerCase()==="paperclip"?act(p):d?.group??rct(p);return{icon:sct[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(wy,"toolActivityPresentation");function m4(e){const s=wy({name:e});return{family:s.family,icon:s.icon,verbLabel:s.runningLabel}}r(m4,"toolTaxonomy");function ict(e){const s=(e??"").trim().toLowerCase();return s==="thinking"?Jx:s==="responding"||s.startsWith("responding (")?dqe:null}r(ict,"statusLabelIcon");var rO=["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"],aO=["Brewing","Tinkering","Distilling","Deliberating"],Lse=(()=>{const e=[],s=Math.max(rO.length,aO.length);for(let n=0;n<s;n++)n<rO.length&&e.push(rO[n]),n<aO.length&&e.push(aO[n]);return e})(),oct=1e4;function lct(e){const s=(e??"").trim().toLowerCase();return s==="running"||s==="working"}r(lct,"isGenericStatusLabel");function cct(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(cct,"fnv1a");function dct(e,s=0){const n=Math.floor(Math.max(0,s)/oct);return Lse[(cct(e)+n)%Lse.length]}r(dct,"whimsyWord");var uct=[{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}],Tls=Array.from(new Set(uct.map(e=>e.group)));function VCe(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(VCe,"parseCssTimeMs");function mct(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(mct,"elapsedLabel");function hct(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(hct,"liveElapsedLabel");function pct(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(pct,"useLiveElapsedMs");function fct(e,s){return!Number.isFinite(e)||!Number.isFinite(s)||s<=0?0:Math.max(0,Math.round(e/s)-1)}r(fct,"lineScrollOffset");function wE(e){const s=getComputedStyle(document.documentElement).getPropertyValue(e),n=VCe(s);return Number.isFinite(n)?n:0}r(wE,"motionTokenMs");function xct({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(fct(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),wE("--motion-line-scroll"));return()=>{cancelAnimationFrame(p),window.clearTimeout(f)}},[]);const h=l?n?-1:s?-i:0:1;return(0,t.jsx)("span",{className:"tc-line-scroll min-w-0 flex-1","data-testid":"task-chat-live-self-talk","data-streaming":s||void 0,"data-leaving":n||void 0,children:(0,t.jsx)("span",{ref:a,className:W("tc-line-scroll-inner block",!s&&"truncate"),style:{transform:h!==0?`translateY(calc(${h} * 1lh))`:void 0,transition:d&&!n?"none":void 0},children:e})})}r(xct,"LiveSelfTalkLine");function gct(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)},wE("--motion-line-scroll")))},wE("--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=wE("--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(gct,"useHeldSelfTalk");var bct={running:{Icon:rt,spin:!0,tone:"text-(--status-agent-running)"},working:{Icon:rt,spin:!0,tone:"text-(--status-agent-running)"},awaiting_approval:{Icon:QN,spin:!1,tone:"text-primary"},interrupted:{Icon:M7,spin:!1,tone:"text-destructive"},refused:{Icon:jm,spin:!1,tone:"text-destructive"},truncated:{Icon:yqe,spin:!1,tone:"text-(--status-agent-paused)"}};function HCe({item:e,onApprovalDecision:s,chevronOpen:n,onToggle:a}){const{Icon:i,spin:o,tone:l}=bct[e.status],c=e.status==="awaiting_approval",d=e.status==="running"||e.status==="working",u=pct(e.startedAtMs,d),h=gct(d?e.selfTalk:void 0,d),p=mct(e.elapsedMs);if(d){const f=hct(u??e.elapsedMs),x=e.selfTalk!=null,b=e.toolName?m4(e.toolName).icon:x?null:ict(e.label),v=x||lct(e.label)?dct(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)(Rn,{className:W("h-3 w-3 transition-transform",n?"rotate-90":null),"aria-hidden":!0})}):null,(0,t.jsx)("span",{className:"flex h-3.5 w-3.5 shrink-0 items-center justify-center","data-testid":"task-chat-status-dot-slot",children:(0,t.jsx)("span",{"aria-hidden":!0,className:"h-2 w-2 animate-pulse rounded-full bg-(--status-agent-running)"})}),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)(xct,{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:W("tc-enter-status flex flex-col gap-2 rounded-lg border px-3 py-2 text-sm",c?"tc-approval border-primary/40 bg-primary/5":"border-border bg-muted/40"),children:[(0,t.jsxs)("div",{className:"flex min-w-0 items-center gap-2",children:[(0,t.jsx)(i,{className:W("h-4 w-4 shrink-0",l,o&&"animate-spin")}),(0,t.jsx)("span",{className:"min-w-0 truncate font-medium",children:e.label}),(0,t.jsxs)("span",{className:"ml-auto flex shrink-0 items-center gap-2 text-xs text-muted-foreground",children:[p?(0,t.jsx)("span",{children:p}):null,e.tokens?(0,t.jsxs)("span",{children:[e.tokens.used.toLocaleString(),"/",e.tokens.size.toLocaleString()," ctx"]}):null]})]}),e.detail?(0,t.jsx)("p",{className:"text-xs text-muted-foreground",children:e.detail}):null,c&&e.approval?(0,t.jsx)("div",{className:"flex flex-wrap justify-end gap-2 pt-1",children:e.approval.options.map(f=>{const x=f.kind.startsWith("reject");return(0,t.jsx)("button",{type:"button",onClick:r(()=>s?.(f.id),"onClick"),className:W("rounded-md border px-2.5 py-1 text-xs font-medium transition-colors",x?"border-border text-muted-foreground hover:bg-accent/50 hover:text-foreground":"border-primary bg-primary text-primary-foreground hover:bg-primary/90"),children:f.label},f.id)})}):null]})}r(HCe,"TaskChatStatusPill");var Tg=(0,m.createContext)(null);function tj(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(tj,"formatBytes$4");var z5=new Set(["application/octet-stream","binary/octet-stream","application/x-binary"]),vct=[".mp4",".m4v",".webm",".mov",".qt",".quicktime"],yct=[".png",".jpg",".jpeg",".gif",".webp",".avif",".bmp",".ico"],jct=new Set(["application/wasm"]),wct=new Set(["application/zip","application/x-zip","application/x-zip-compressed"]),GCe=new Set(["text/markdown","text/x-markdown","application/markdown","application/x-markdown"]),kct=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"]),Nct=[".csv",".css",".graphql",".htm",".html",".js",".json",".jsx",".log",".markdown",".md",".mdx",".php",".py",".sh",".sql",".toml",".ts",".tsx",".txt",".xml",".yaml",".yml"];function pA(e){return(e??"").toLowerCase().split(";")[0]?.trim()??""}r(pA,"normalizeOutputContentType");function Sct(e){const s=(e??"").trim().toLowerCase();return s?Nct.some(n=>s.endsWith(n)):!1}r(Sct,"hasDocumentLikeFilename");function QCe(e){return wct.has(e)||e.endsWith("+zip")}r(QCe,"isZipContentType");function Cct(e){return e?!!(e.startsWith("text/")||GCe.has(e)||kct.has(e)||e.startsWith("application/")&&(e.endsWith("+json")||e.endsWith("+xml"))):!1}r(Cct,"isDocumentLikeOutputContentType");function _ct(e,s){const n=pA(e);return!n||Cct(n)||z5.has(n)&&Sct(s)?!1:n.startsWith("video/")||n.startsWith("image/")||n==="application/pdf"||jct.has(n)||QCe(n)||z5.has(n)}r(_ct,"isOutputEligibleContentType");function Ict(e){const s=pA(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"}:QCe(s)?{label:"ZIP",tone:"zip"}:s.startsWith("image/")?{label:"IMG",tone:"image"}:GCe.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(Ict,"getOutputFileGlyph");function Vu(e,s){const n=pA(e);if(n.startsWith("video/"))return!0;if(!z5.has(n))return!1;const a=(s??"").trim().toLowerCase();return vct.some(i=>a.endsWith(i))}r(Vu,"isVideoLikeOutput");function ky(e){const s=pA(e);return s.startsWith("image/")&&s!=="image/svg+xml"}r(ky,"isImageContentType");function h4(e,s){const n=pA(e);if(ky(n))return!0;if(n&&!z5.has(n))return!1;const a=(s??"").trim().toLowerCase();return yct.some(i=>a.endsWith(i))}r(h4,"isImageLikeOutput");function $se(e){const s=new Date(e).getTime();return Number.isNaN(s)?0:s}r($se,"toTime");function p4(e){const s=(e??[]).filter(n=>n.type==="artifact"&&n.provider==="paperclip").flatMap(n=>{const a=i$e.safeParse(n.metadata);return a.success&&!_ct(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:$se(a.createdAt)-$se(n.createdAt)),{items:s,primary:s[0]??null,rest:s.slice(1),count:s.length}}r(p4,"getIssueOutputs");function HW(e){return e.metadata?.originalFilename||e.title||"output"}r(HW,"outputFilename");function YCe(e){return new Set(p4(e).items.flatMap(s=>{const n=s.metadata?.attachmentId;return n?[n]:[]}))}r(YCe,"getPromotedOutputAttachmentIds");function Act(e){return e.contentType.toLowerCase().split(";")[0]?.trim()??""}r(Act,"normalizedContentType");function bg(e){return e.originalFilename??e.id}r(bg,"attachmentFilename");function f4(e){return e.openPath??e.contentPath}r(f4,"attachmentOpenPath");function oS(e){return e.downloadPath??`${e.contentPath}?download=1`}r(oS,"attachmentDownloadPath");function JCe(e){const s=Act(e);return h4(s,e.originalFilename)&&!/^image\/hei[cf](?:-sequence)?$/.test(s)}r(JCe,"isImageAttachment$1");function XCe(e){return Vu(e.contentType,e.originalFilename)}r(XCe,"isVideoAttachment");function ZCe(e){return Wpe(e)}r(ZCe,"isMarkdownAttachment");function sj(e){const s=e.contentType.toLowerCase().split(";")[0].trim();return Wpe(e)||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(sj,"isTextAttachment");function e1e(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(e1e,"downloadBlob$1");function Tct(e,s,n){e1e(e,new Blob([s],{type:`${n};charset=utf-8`}))}r(Tct,"downloadTextFile");var iO="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 t1e({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}=Cp(),v=(0,m.useRef)(void 0);(0,m.useEffect)(()=>()=>clearTimeout(v.current),[]);const j=(0,m.useCallback)(async(I,R)=>{c(I),p(null);try{await R(),u(I)}catch(T){u(null),p(T instanceof Error?T.message:"Export failed")}finally{c(null)}clearTimeout(v.current),v.current=setTimeout(()=>{u(null),p(null)},2e3)},[]),N=(0,m.useCallback)(async()=>i??(await Ct.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(I){p(I instanceof Error?I.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:W("flex items-center gap-0.5",o),"data-testid":"document-export-actions",children:[(0,t.jsx)("button",{type:"button",className:iO,disabled:l!==null,"aria-label":"Copy full content",title:k,"data-testid":"document-export-copy",onClick:r(I=>{I.preventDefault(),I.stopPropagation(),w()},"onClick"),children:x?(0,t.jsx)(gs,{"aria-hidden":"true",className:"h-3.5 w-3.5"}):(0,t.jsx)(Ir,{"aria-hidden":"true",className:"h-3.5 w-3.5"})}),(0,t.jsx)("button",{type:"button",className:iO,disabled:l!==null,"aria-label":"Download source",title:S,"data-testid":"document-export-download",onClick:r(I=>{I.preventDefault(),I.stopPropagation(),j("download",async()=>{const R=kBe(a);Tct(eX(n,R),await N(),R==="md"?"text/markdown":"text/plain")})},"onClick"),children:(0,t.jsx)(po,{"aria-hidden":"true",className:"h-3.5 w-3.5"})}),(0,t.jsx)("button",{type:"button",className:iO,disabled:l!==null,"aria-label":"Export to PDF",title:C,"data-testid":"document-export-pdf",onClick:r(I=>{I.preventDefault(),I.stopPropagation(),j("pdf",async()=>{e1e(eX(n,"pdf"),await Ct.getDocumentPdf(e,s))})},"onClick"),children:(0,t.jsx)(eqe,{"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(t1e,"DocumentExportActions");function U_({children:e,className:s}){return(0,t.jsx)("div",{className:W("relative aspect-video w-full overflow-hidden bg-accent/20",s),children:e})}r(U_,"PreviewFrame");function q5({label:e}){return(0,t.jsx)(U_,{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)(Dc,{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(q5,"PlaceholderPreview");function Rct({artifact:e}){const[s,n]=(0,m.useState)(!1);return s||!e.contentPath?(0,t.jsx)(q5,{label:"Image"}):(0,t.jsx)(U_,{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(Rct,"ImagePreview");function Ect({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)(U_,{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)(oo,{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)(U_,{className:"bg-black",children:[(0,t.jsx)("video",{src:e.contentPath,preload:"metadata",muted:!0,playsInline:!0,"data-frame-ready":a?"true":"false",className:W("h-full w-full object-contain transition-opacity",a?"opacity-100":"opacity-0"),onLoadedMetadata:u,onLoadedData:h,onSeeked:c,onError:r(()=>n(!0),"onError")}),(0,t.jsx)("div",{className:"pointer-events-none absolute inset-0 flex items-center justify-center",children:(0,t.jsx)("div",{className:"flex h-11 w-11 items-center justify-center rounded-full bg-black/55",children:(0,t.jsx)(oo,{className:"h-5 w-5 translate-x-0.5 text-white","aria-hidden":"true"})})})]})}r(Ect,"VideoPreview");function Pct({artifact:e}){const s=e.previewText?.trim();return s?(0,t.jsxs)(U_,{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)(q5,{label:e.source==="document"?"Document":"Text"})}r(Pct,"TextPreview");function fA({artifact:e}){switch(e.mediaKind){case"image":return(0,t.jsx)(Rct,{artifact:e},e.contentPath);case"video":return(0,t.jsx)(Ect,{artifact:e},e.contentPath);case"text":case"document":return(0,t.jsx)(Pct,{artifact:e});case"file":return(0,t.jsx)(q5,{label:"File"});default:return(0,t.jsx)(q5,{})}}r(fA,"ArtifactPreview");function Ose({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(Ose,"SecondaryAction");function Mct({artifact:e}){return(0,t.jsxs)(Ke,{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)(fA,{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)(t1e,{issueId:e.issue.id,documentKey:e.documentKey,title:e.title}):null,e.openPath?(0,t.jsx)(Ose,{href:e.openPath,title:"Open file in new tab",children:(0,t.jsx)(Vn,{className:"h-3.5 w-3.5"})}):null,e.downloadPath?(0,t.jsx)(Ose,{href:e.downloadPath,download:!0,title:"Download file",children:(0,t.jsx)(po,{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 ",Ad(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(Mct,"ArtifactCard");var Ql={credentials:r(e=>Te.get(`/companies/${e}/email/connections`),"credentials"),checkAddress:r((e,s,n,a)=>Te.post(`/companies/${e}/email/connections/${s}/check-address`,n,{signal:a}),"checkAddress"),connect:r((e,s)=>Te.post(`/companies/${e}/email/connections`,s),"connect"),inspectSaved:r((e,s)=>Te.post(`/companies/${e}/email/connections/${s}/inspect`,{}),"inspectSaved"),list:r(e=>Te.get(`/companies/${e}/email/inboxes`),"list"),setup:r((e,s)=>Te.post(`/companies/${e}/email/inboxes`,s),"setup"),inspect:r((e,s)=>Te.post(`/companies/${e}/email/inspect`,{apiKey:s}),"inspect"),control:r((e,s)=>Te.post(`/email/inboxes/${e}/control`,{action:s}),"control"),reconnect:r((e,s,n)=>Te.post(`/email/inboxes/${e}/reconnect`,{apiKey:s,receiveMode:n}),"reconnect"),resolve:r((e,s,n,a)=>Te.post(`/companies/${e}/email/deliveries/${s}/resolve`,{outcome:n,providerMessageId:a}),"resolve"),thread:r((e,s)=>Te.get(`/companies/${e}/email/tasks/${s}`),"thread"),send:r((e,s)=>Te.post(`/companies/${e}/email/send`,s),"send")};function s1e(e,s){return Z({queryKey:["email-thread",e,s],queryFn:r(()=>Ql.thread(e,s),"queryFn"),enabled:!!(e&&s)&&!s.startsWith("chat:"),refetchInterval:r(n=>n.state.data===null?!1:3e3,"refetchInterval")})}r(s1e,"useEmailThread");var n1e=(0,m.createContext)(null);function Dct({companyId:e,issueId:s,children:n}){const a=s1e(e,s);return(0,t.jsx)(n1e.Provider,{value:a.data??null,children:n})}r(Dct,"EmailThreadProvider");function r1e(e){const s=(0,m.useContext)(n1e),n=s?.messages.find(a=>a.commentId===e);return n&&s?(0,t.jsx)(a1e,{message:n,publication:s.publications.find(a=>a.providerMessageId===n.providerMessageId),issueId:s.issueId}):null}r(r1e,"useEmailComment");function a1e({message:e,publication:s,issueId:n}){const a=Z({queryKey:["email-attachments",n],queryFn:r(()=>Ct.listAttachments(n),"queryFn"),enabled:e.attachmentIds.length>0});return(0,t.jsxs)("article",{"aria-label":e.direction==="inbound"?"Email received":"Email sent",className:"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)(a7,{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(i=>{const o=a.data?.find(l=>l.id===i);return(0,t.jsxs)("a",{href:`/api/attachments/${i}/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)(Dc,{className:"size-3.5"}),o?.originalFilename??"Open attachment"]},i)})}),(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}`:""]}),a.error&&(0,t.jsx)("p",{role:"alert",className:"text-xs text-destructive",children:"Attachments could not be loaded."})]})}r(a1e,"EmailMessageCard");var Jv=(0,m.createContext)(null);function nj({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=bg(p),x=Vu(p.contentType,p.originalFilename);return(0,t.jsx)(jFe,{open:n,onOpenChange:a,children:(0,t.jsxs)(vFe,{children:[(0,t.jsx)(yFe,{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)(SFe,{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:oS(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)(po,{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)(Fn,{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)(Uu,{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)(Rn,{className:"h-7 w-7"})})})]}),(0,t.jsx)("div",{className:"h-6 shrink-0"})]})]})})}r(nj,"ImageGalleryModal");var GW=(0,m.createContext)(null);function Lct({value:e,children:s}){return(0,t.jsx)(GW.Provider,{value:e,children:s})}r(Lct,"DispositionRecoveryProvider");function $ct(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($ct,"readDispositionRecoverySnapshot");function i1e(e){return $ct(e,(0,m.useContext)(GW)?.issue.activeRecoveryAction)}r(i1e,"useDispositionRecoverySnapshot");function Oct(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(Oct,"dispositionRetryUnavailableReason");function Fct(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(Fct,"descriptionFor");function QW({snapshot:e,createdAt:s,defaultExpanded:n=!1}){const a=(0,m.useContext)(GW),[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=Oct(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?gs:Es;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:W("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}.`:Fct(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)(L,{size:"xs",variant:"outline",disabled:l||!!j,"aria-describedby":j?v:void 0,onClick:r(()=>{S()},"onClick"),children:[l?(0,t.jsx)(rt,{"aria-hidden":"true",className:"size-3 animate-spin motion-reduce:animate-none"}):(0,t.jsx)(Ci,{"aria-hidden":"true",className:"size-3"}),l?"Requesting retry…":"Retry agent"]}):null,(0,t.jsxs)(L,{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:W("size-3",i&&"rotate-180")})]}),s?(0,t.jsx)("time",{dateTime:s,className:"font-mono text-xs text-muted-foreground sm:ml-auto",children:ro(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(QW,"DispositionRecoveryNotice");var o1e={neutral:{container:"border-border bg-muted/35 dark:bg-muted/20",iconWrap:"bg-muted text-foreground/70",icon:Mf,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:Mf,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:ca,iconClass:"text-emerald-700 dark:text-emerald-300",label:"text-emerald-800 dark:text-emerald-200",divider:"border-emerald-300/50 dark:border-emerald-500/30"},warning:{container:"border-amber-300/70 bg-amber-50/80 dark:border-amber-500/30 dark:bg-amber-500/10",iconWrap:"bg-amber-100 text-amber-800 dark:bg-amber-500/20 dark:text-amber-200",icon:Es,iconClass:"text-amber-700 dark:text-amber-300",label:"text-amber-900 dark:text-amber-200",divider:"border-amber-300/60 dark:border-amber-500/30"},danger:{container:"border-red-400/60 bg-red-50/80 dark:border-red-500/35 dark:bg-red-500/10",iconWrap:"bg-red-100 text-red-700 dark:bg-red-500/20 dark:text-red-200",icon:Hk,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 Bct(e){try{return new Date(e).toLocaleString(void 0,{month:"short",day:"numeric",hour:"numeric",minute:"2-digit"})}catch{return e}}r(Bct,"formatTimestamp$1");function zct({row:e,tone:s}){return(0,t.jsxs)("div",{className:"grid grid-cols-(--gtc-8) gap-x-3 gap-y-0.5 px-3 py-1.5 text-xs",children:[(0,t.jsx)("div",{className:"truncate text-(length:--text-micro) font-medium uppercase tracking-(--tracking-label) text-muted-foreground",children:e.label}),(0,t.jsx)("div",{className:"min-w-0 break-words text-foreground/90",children:(()=>{switch(e.kind){case"text":return(0,t.jsx)("span",{children:e.value});case"code":return(0,t.jsx)("code",{className:"rounded bg-muted px-1.5 py-0.5 font-mono text-(length:--text-micro) text-foreground/80",children:e.value});case"issue":{const n=(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)("span",{children:e.identifier}),e.title?(0,t.jsxs)("span",{className:"text-muted-foreground",children:["— ",e.title]}):null]});return e.href?(0,t.jsx)("a",{href:e.href,className:W("inline-flex items-center gap-1 rounded-sm font-medium underline-offset-2 hover:underline",s.label),children:n}):(0,t.jsx)("span",{className:W("inline-flex items-center gap-1 font-medium",s.label),children:n})}case"agent":return e.href?(0,t.jsx)("a",{href:e.href,className:W("inline-flex items-center gap-1 rounded-sm font-medium underline-offset-2 hover:underline",s.label),children:e.name}):(0,t.jsx)("span",{className:W("font-medium",s.label),children:e.name});case"run":{const n=e.runId.length>12?`${e.runId.slice(0,8)}…`:e.runId,a=(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)("code",{className:"rounded bg-muted px-1.5 py-0.5 text-foreground/80",children:n}),e.status?(0,t.jsx)("span",{className:W("font-sans",s.label),children:e.status}):null]});return e.href?(0,t.jsx)("a",{href:e.href,className:"inline-flex items-center gap-2 rounded-sm font-mono text-(length:--text-micro) underline-offset-2 hover:underline",children:a}):(0,t.jsx)("span",{className:"inline-flex items-center gap-2 font-mono text-(length:--text-micro)",children:a})}}})()})]})}r(zct,"MetadataRow$1");function l1e({sections:e,tone:s="neutral"}){const n=o1e[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)(zct,{row:o,tone:n},l))})]},i))})}r(l1e,"SystemNoticeMetadataSections");function YW({tone:e="neutral",label:s,body:n,source:a,metadata:i,detailsDefaultOpen:o=!1,timestamp:l,className:c}){const d=o1e[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:W("relative w-full overflow-hidden rounded-lg border text-sm shadow-(--shadow-extract-8)",d.container,c),children:[(0,t.jsxs)("header",{className:"flex items-start gap-3 px-3 py-2.5 sm:px-4",children:[(0,t.jsx)("span",{className:W("mt-0.5 flex h-7 w-7 shrink-0 items-center justify-center rounded-md",d.iconWrap),"aria-hidden":!0,children:(0,t.jsx)(u,{className:W("h-4 w-4",d.iconClass)})}),(0,t.jsxs)("div",{className:"min-w-0 flex-1",children:[(0,t.jsxs)("div",{className:"flex flex-wrap items-center gap-x-2 gap-y-0.5 text-(length:--text-micro) font-semibold uppercase tracking-(--tracking-eyebrow)",children:[(0,t.jsx)("span",{className:d.label,children: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:Bct(l)})]}):null]}),(0,t.jsx)("div",{className:"mt-1 break-words text-sm leading-6 text-foreground",children:n})]}),x?(0,t.jsxs)("button",{type:"button",onClick:r(()=>p(v=>!v),"onClick"),"aria-expanded":h,"aria-controls":f,className:W("ml-1 inline-flex h-7 shrink-0 items-center gap-1 rounded-md border border-transparent px-2 text-(length:--text-micro) font-medium uppercase tracking-(--tracking-eyebrow) text-muted-foreground transition-(--tp-background-color-border-color-color)","hover:border-border/70 hover:bg-background/70 hover:text-foreground","focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring/50"),children:[(0,t.jsx)("span",{children:h?"Hide details":"Details"}),(0,t.jsx)(nn,{className:W("h-3.5 w-3.5 transition-transform duration-150",h&&"rotate-180")})]}):null]}),x&&h?(0,t.jsx)("div",{id:f,className:W("border-t bg-background/50 dark:bg-background/30",d.divider),children:(0,t.jsx)(l1e,{sections:i,tone:e})}):null]})}r(YW,"SystemNotice");var qct="System update",Uct=80;function Kct(e){const s=e.match(/Latest retry failure: `([^`]+)`/);return s?s[1]:null}r(Kct,"retryFailureCode");function Wct(e){const s=e.match(/Recovery owner: \[([^\]]+)\]\(/)?.[1]?.trim();return s&&s.length>0?s:null}r(Wct,"recoveryOwnerName");function Vct(e){const s=e.split(`
355
+ `)}`:void 0}r(bot,"sanitizeComponentStack");function mCe(){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(mCe,"readBrowserErrorState");function vot(e){const s=bot(e.componentStack);return{tags:{react_error_boundary:e.boundary},contexts:{react:s?{componentStack:s}:{},browser_state:mCe()}}}r(vot,"buildBrowserErrorContext");var vse=Promise.resolve();function KW(e){const s=vse.then(e);return vse=s.catch(()=>{}),s}r(KW,"enqueue");var mN=null;function yot(e,s){return KW(async()=>{if(!mN)try{const n=await Jc(()=>import("./prod-COP_vZWu.js"),__vite__mapDeps([4,5]));n.init(wot(e,s)),mN=n}catch{}})}r(yot,"initBrowserErrorMonitoring");function jot(){return KW(async()=>{const e=mN;if(mN=null,!e)return;const s=e.getClient();try{e.getCurrentScope().setClient(void 0)}catch{}try{await s?.close(2e3)}catch{}})}r(jot,"teardownBrowserErrorMonitoring");function hCe(e,s){let n;try{s&&(n=vot(s))}catch{}KW(async()=>{try{n?mN?.captureException(e,n):mN?.captureException(e)}catch{}})}r(hCe,"captureBrowserException");function wot(e,s){return{dsn:e,environment:s??void 0,release:"06af6befe670a29bf7d5ad8691bae46e2f81c83b",tracesSampleRate:0,sendDefaultPii:!1,beforeSend:r((n,a)=>{try{if(n.contexts={...n.contexts,browser_state:n.contexts?.browser_state??mCe()},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(wot,"buildBrowserSentryInitOptions");var kot=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){hCe(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)(L,{variant:"outline",size:"sm",onClick:this.props.onReset,children:"Go back"}),(0,t.jsx)(L,{size:"sm",onClick:r(()=>window.location.reload(),"onClick"),children:"Reload page"})]})]}):this.props.children}};function pCe({children:e}){const s=na(),n=Mn(),a=`${s.pathname}${s.search}`;return(0,t.jsx)(kot,{resetKey:a,onReset:r(()=>n(-1),"onReset"),children:e})}r(pCe,"RouteErrorBoundary");var yse={bot:so,cpu:ym,brain:Jx,zap:C3,rocket:C$e,code:fxe,terminal:mg,shield:RI,eye:Pd,search:oa,wrench:Ef,hammer:cM,lightbulb:TI,sparkles:Np,star:yp,heart:OC,flame:X$e,bug:Uv,cog:dfe,database:EI,globe:Ap,lock:pd,mail:a7,"message-square":Yx,"file-code":Ll,"git-branch":io,package:Th,puzzle:Xx,target:vp,wand:z7,atom:V$e,"circuit-board":Hze,radar:N$e,swords:_qe,telescope:E$e,microscope:uqe,crown:cfe,gem:xxe,hexagon:Td,pentagon:fqe,fingerprint:Lz},Not="bot";function Sot(e){return e&&PLe.includes(e)?yse[e]:yse[Not]}r(Sot,"getAgentIcon");function L5({icon:e,className:s}){const n=Sot(e);return(0,t.jsx)(n,{className:s})}r(L5,"AgentIcon");function fCe({open:e,onOpenChange:s,...n}){return(0,t.jsx)(Qs,{open:e,onOpenChange:s,children:(0,t.jsxs)(Js,{"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)(Xs,{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)(Cot,{...n,onComplete:r(()=>s(!1),"onComplete")},String(e))]})})}r(fCe,"AgentChatPicker");function Cot({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)($I,{children:[(0,t.jsx)(WN,{"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)(L,{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)(KN,{children:[(0,t.jsx)(UN,{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)(L,{variant:"ghost",size:"sm",onClick:r(()=>p(""),"onClick"),children:"Clear search"})]}):(0,t.jsx)("span",{className:"text-xs text-muted-foreground",children:"Create an agent from the Agents page to start chatting."})]})}),(0,t.jsx)(ju,{children:e.map(N=>(0,t.jsxs)(Ko,{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)(L5,{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(Cot,"AgentChatPickerResults");function jE({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=Mn(),[j,N]=(0,m.useState)(!1),[w,k]=(0,m.useState)(d),S=(0,m.useRef)(null),C=(0,m.useId)(),I=w.trim().toLocaleLowerCase(),R=e.filter(A=>`${A.name} ${A.title??""} ${A.role}`.toLocaleLowerCase().includes(I));function T(){k(""),S.current?.focus()}return r(T,"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)(L,{variant:"outline",size:"icon-sm","aria-label":"Add chat",title:"Add chat",onClick:r(()=>N(!0),"onClick"),children:(0,t.jsx)(yn,{className:"size-4"})})]}),(0,t.jsxs)("div",{className:"relative",children:[(0,t.jsx)(oa,{"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)(ht,{ref:S,"aria-label":"Search agents",placeholder:"Find an agent",value:w,onChange:r(A=>k(A.target.value),"onChange"),onKeyDown:r(A=>{A.key==="Escape"&&(A.stopPropagation(),k(""))},"onKeyDown"),className:"h-8 pl-8 pr-8 text-xs md:text-xs"}),w&&(0,t.jsx)(L,{variant:"ghost",size:"icon-xs","aria-label":"Clear search",className:"absolute right-1 top-1/2 -translate-y-1/2",onClick:T,children:(0,t.jsx)(Fn,{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:I?"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)(L,{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)(L,{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(A=>(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"})]})]},A))}):R.length?(0,t.jsx)("nav",{"aria-label":"Agent conversations",className:"flex flex-col gap-1",children:R.map(A=>(0,t.jsxs)(Ke,{to:`/chats/${encodeURIComponent(A.status==="terminated"?A.id:Xl(A))}`,"aria-current":a===A.id?"page":void 0,title:`${A.name}${A.title?` · ${A.title}`:""}`,onClick:r(D=>{u&&(D.preventDefault(),u(A))},"onClick"),className:W("flex min-w-0 items-center gap-3 rounded-md px-2 py-3 text-left transition-colors hover:bg-accent/60 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-ring",a===A.id&&"bg-accent text-accent-foreground"),children:[(0,t.jsx)(kr,{agent:A,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:A.name}),(0,t.jsx)("span",{className:"truncate text-xs text-muted-foreground",children:A.status==="terminated"?"Terminated":A.status==="paused"?"Paused":i[A.id]??A.title??"Start a conversation"})]})]},A.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)(L,{variant:"outline",size:"sm",onClick:r(()=>N(!0),"onClick"),children:"Choose an agent"}),e.length>0&&(0,t.jsx)(L,{variant:"outline",size:"sm",onClick:T,children:"Clear search"})]})]}),(0,t.jsx)("div",{className:"shrink-0 px-3 py-4",children:(0,t.jsx)(L,{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)(Vo,{className:"size-4"}),"Browse all agents"]}):(0,t.jsxs)(Ke,{to:"/agents/all",children:[(0,t.jsx)(Vo,{className:"size-4"}),"Browse all agents"]})})}),(0,t.jsx)(fCe,{agents:n,open:j,onOpenChange:N,existingChatAgentIds:s??e.map(A=>A.id),loading:o,error:l,onRetry:c,renderAgentIcon:r(A=>(0,t.jsx)(kr,{agent:A,size:32}),"renderAgentIcon"),onSelect:r(async(A,D)=>{p?await p(A,D):u?await u(A,D):v(`/chats/${encodeURIComponent(Xl(A))}`),D?.aborted||k("")},"onSelect")})]})}r(jE,"AgentConversationSidebar");var $5={list:r(e=>Te.get(`/companies/${e}/chats`),"list"),get:r((e,s)=>Te.get(`/companies/${e}/chats/${encodeURIComponent(s)}`),"get"),ensure:r((e,s)=>Te.post(`/companies/${e}/chats/${encodeURIComponent(s)}`,{}),"ensure")};function xCe(){const{selectedCompanyId:e}=ps(),{enabled:s,loaded:n}=Yy(),a=Z({queryKey:P.auth.session,queryFn:r(()=>Oa.getSession(),"queryFn")}),i=a.data?.user?.id??a.data?.session?.userId??null;return{companyId:e,userId:i,enabled:s,loaded:n,agents:Z({queryKey:P.agents.list(e),queryFn:r(()=>$t.list(e),"queryFn"),enabled:s&&!!e}),chats:Z({queryKey:P.agentChats.list(e,i),queryFn:r(()=>$5.list(e),"queryFn"),enabled:s&&!!e&&a.isSuccess}),session:a}}r(xCe,"useAgentChatNavigation");function gCe(e,s){const n=Dt(),a=Mn(),{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 $5.ensure(e,c.id);n.setQueryData(P.agentChats.detail(e,s,c.id),h),n.setQueryData(P.issues.detail(h.id),h),n.setQueryData(P.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(Xl(c))}`),i&&o(!1))},[n,e,s,a,i,o])}r(gCe,"useOpenAgentChat");function _ot(){const{companyId:e,userId:s,agents:n,chats:a,session:i}=xCe(),o=gCe(e,s),l=Mn(),c=Qf(e),{isMobile:d,setSidebarOpen:u}=qa(),{pathname:h}=na(),p=h.split("/chats/")[1]?.split("/")[0],f=n.data??[],x=n.isSuccess?[...new Set((a.data??[]).flatMap(C=>C.conversationAgentId&&!f.some(I=>I.id===C.conversationAgentId)?[C.conversationAgentId]:[]))]:[],b=Rh({queries:x.map(C=>({queryKey:P.agents.detail(C),queryFn:r(()=>$t.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(Xl(C))===p),N=(a.data??[]).flatMap(C=>{const I=C.conversationAgentId?v.get(C.conversationAgentId):void 0;return I?[I]:[]});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||$f(c.data,"agent",C.id)!=="left")).sort((C,I)=>C.name.localeCompare(I.name,void 0,{sensitivity:"base"})),S=Object.fromEntries((a.data??[]).filter(C=>C.conversationState==="active").map(C=>[C.conversationAgentId,"Working…"]));return(0,t.jsx)(jE,{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:Xl(C))}`),d&&u(!1)},"onSelect")},`${e}:${s}`)}r(_ot,"AgentConversationsSidebar");var J2=240,x6=208,g6=420,jse=16;function O5(e){return Math.min(g6,Math.max(x6,e))}r(O5,"clampSidebarWidth$1");function wse(e){if(typeof window>"u")return J2;try{const s=window.localStorage.getItem(e);if(!s)return J2;const n=Number.parseInt(s,10);return Number.isFinite(n)?O5(n):J2}catch{return J2}}r(wse,"readStoredSidebarWidth$1");function kse(e,s){if(!(typeof window>"u"))try{window.localStorage.setItem(e,String(O5(s)))}catch{}}r(kse,"writeStoredSidebarWidth$1");function Iot({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)(()=>wse(o)),[x,b]=(0,m.useState)(!1),v=(0,m.useRef)(p),j=(0,m.useRef)(null);(0,m.useEffect)(()=>{const E=wse(o);v.current=E,f(E)},[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,I=(0,m.useMemo)(()=>({width:`${w}px`}),[w]),R=(0,m.useMemo)(()=>({width:`${k}px`}),[k]),T=(0,m.useCallback)(E=>{const z=O5(E);v.current=z,f(z),kse(o,z)},[o]),A=(0,m.useCallback)(E=>{C&&(E.preventDefault(),E.currentTarget.setPointerCapture(E.pointerId),j.current={startX:E.clientX,startWidth:v.current},b(!0))},[C]),D=(0,m.useCallback)(E=>{if(!j.current)return;const z=O5(j.current.startWidth+E.clientX-j.current.startX);v.current=z,f(z)},[]),M=(0,m.useCallback)(()=>{j.current&&(j.current=null,b(!1),kse(o,v.current))},[o]),B=(0,m.useCallback)(E=>{C&&(E.key==="ArrowLeft"?(E.preventDefault(),T(p-jse)):E.key==="ArrowRight"?(E.preventDefault(),T(p+jse)):E.key==="Home"?(E.preventDefault(),T(x6)):E.key==="End"&&(E.preventDefault(),T(g6)))},[C,T,p]);return(0,t.jsxs)("div",{className:W("relative h-full shrink-0",l),style:I,children:[(0,t.jsx)("div",{className:W("absolute inset-y-0 left-0 flex flex-col overflow-hidden",S?"z-30 border-r border-border bg-background shadow-lg":"z-0"),style:R,"data-sidebar-overlay":S?"":void 0,onMouseEnter:c,onMouseLeave:d,onFocusCapture:u,onBlurCapture:h,children:e}),C?(0,t.jsx)("div",{role:"separator","aria-label":"Resize sidebar","aria-orientation":"vertical","aria-valuemin":x6,"aria-valuemax":g6,"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:A,onPointerMove:D,onPointerUp:M,onPointerCancel:M,onLostPointerCapture:M,onKeyDown:B,children:(0,t.jsx)("div",{className:W("mx-auto h-full w-0.5 transition-colors",x?"bg-ring":"bg-transparent group-hover:bg-ring group-focus-visible:bg-ring")})}):null]})}r(Iot,"SidebarShell$1");function X2({children:e,className:s}){return(0,t.jsx)("div",{"data-secondary-sidebar":"",className:W("h-full w-full min-w-0 overflow-hidden",s),children:(0,t.jsx)(oye,{children:e})})}r(X2,"SecondarySidebar$1");var bCe={listStacks:r(()=>Te.get("/cloud/stacks"),"listStacks")};function u4(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(u4,"cloudAppUrl");function vCe(e){return u4(e,"/stacks/new")}r(vCe,"cloudStackCreateUrl");function yCe(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(yCe,"tenantSignInReturnPath");function Aot(e,s,n){const a=s?.trim();if(!a)return null;const i=u4(e,`/v1/stacks/${encodeURIComponent(a)}/entry-redirect`);if(!i)return null;const o=new URL(i);return o.searchParams.set("returnTo",yCe(n)),o.toString()}r(Aot,"cloudStackEntryUrl");function jCe(e,s){const n=s?.trim();return n?u4(e,`/workspaces/${encodeURIComponent(n)}/settings?section=people`):null}r(jCe,"cloudStackInviteUrl");function Tot(e){return u4(e,"/orgs?manage=1")}r(Tot,"cloudPortfolioManageUrl");function wCe(){const e=$c(),s=!!e,n=Z({queryKey:P.cloud.stacks,queryFn:r(()=>bCe.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:jCe(e.cloudBaseUrl,a.stackSlug)}r(wCe,"useCloudInviteUrl");function Rot(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"}r(Rot,"canInviteCompanyMembers");function kCe(e=!0){const s=XDe(),n=Z({queryKey:P.access.currentBoardAccess,queryFn:r(()=>pr.getCurrentBoardAccess(),"queryFn"),enabled:e,retry:!1,staleTime:3e4});return e&&Rot(s?.selectedCompanyId,n.data)}r(kCe,"useCanInviteCompanyMembers");function NCe(e){const s=window.location.hostname.endsWith(".staging.paperclip.app"),{data:n,isError:a}=Z({queryKey:P.stagingCommit,queryFn:r(()=>tu.get(),"queryFn"),enabled:s&&e,staleTime:0,retry:!1});return s&&!a?n?.commit??null:null}r(NCe,"useStagingCommit");function Eot(e){return e?.trim().toLowerCase().replace(/['"]/g,"").replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")||null}r(Eot,"slugifyUserPart");function SCe(e){const s=[e?.id,e?.name,e?.email?.split("@")[0],e?.email];for(const n of s){const a=Eot(n);if(a)return`/u/${a}`}return"/u/me"}r(SCe,"userProfilePath");var Pot="Toggle the app appearance.";function yk({className:e,variant:s="icon",onAfterToggle:n}){const{theme:a,toggleTheme:i}=XFe(),o=a==="dark",l=o?"Switch to light mode":"Switch to dark mode",c=o?hve:mbe;function d(){i(),n?.()}return r(d,"handleClick"),s==="compact-menu-action"?(0,t.jsxs)("button",{type:"button",className:W("flex h-(--profile-popover-row-height) w-full items-center gap-(--profile-popover-row-gap) rounded-lg px-2.5 text-left text-(length:--text-compact) font-medium leading-(--profile-popover-label-line-height) text-foreground transition-colors hover:bg-accent",e),onClick:d,"aria-label":l,children:[(0,t.jsx)("span",{className:"flex size-5 shrink-0 items-center justify-center text-muted-foreground",children:(0,t.jsx)(c,{className:"size-4"})}),(0,t.jsx)("span",{className:"min-w-0 flex-1 truncate",children:l})]}):s==="menu-action"?(0,t.jsxs)("button",{type:"button",className:W("flex w-full items-start gap-3 rounded-xl px-3 py-3 text-left transition-colors hover:bg-accent/60",e),onClick:d,"aria-label":l,children:[(0,t.jsx)("span",{className:"mt-0.5 rounded-lg border border-border bg-background/70 p-2 text-muted-foreground",children:(0,t.jsx)(c,{className:"size-4"})}),(0,t.jsxs)("span",{className:"min-w-0 flex-1",children:[(0,t.jsx)("span",{className:"block text-sm font-medium text-foreground",children:l}),(0,t.jsx)("span",{className:"block text-xs text-muted-foreground",children:Pot})]})]}):(0,t.jsx)(L,{type:"button",variant:"ghost",size:"icon-sm",onClick:d,"aria-label":l,title:l,className:W("text-muted-foreground",e),children:(0,t.jsx)(c,{})})}r(yk,"ThemeToggle");var q_=null,CCe=!1,b6=!1,v6=new Set;function F5(){for(const e of v6)e()}r(F5,"emit");function Mot(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(Mot,"isIosSafariLike");function Dot(e=window){const s=r(a=>{a.preventDefault(),q_=a,F5()},"onPrompt"),n=r(()=>{q_=null,CCe=!0,F5()},"onInstalled");return e.addEventListener("beforeinstallprompt",s),e.addEventListener("appinstalled",n),()=>{e.removeEventListener("beforeinstallprompt",s),e.removeEventListener("appinstalled",n)}}r(Dot,"captureInstallPrompt");function Lot(){return CCe||p6()?"installed":q_?"prompt":Mot()?"ios-manual":"unavailable"}r(Lot,"installAvailability");async function $ot(){const e=q_;if(!e)return"unavailable";q_=null,F5(),await e.prompt();const{outcome:s}=await e.userChoice;return s}r($ot,"promptInstall");function y6(e){b6!==e&&(b6=e,F5())}r(y6,"setIosInstallHelpOpen");function Oot(){return b6}r(Oot,"iosInstallHelpOpen");function Fot(){return(0,m.useSyncExternalStore)(_Ce,Oot,()=>!1)}r(Fot,"useIosInstallHelpOpen");function _Ce(e){return v6.add(e),()=>{v6.delete(e)}}r(_Ce,"subscribe$1");function Bot(){return(0,m.useSyncExternalStore)(_Ce,Lot,()=>"unavailable")}r(Bot,"useInstallAvailability");var Nse="Install app",zot="Add Paperclip to your home screen or dock.";function ICe({variant:e,onAfterAction:s}){const n=Bot();if(n==="installed"||n==="unavailable")return null;const a=r(()=>{n==="ios-manual"?y6(!0):$ot(),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)(po,{className:"size-4"})}),(0,t.jsx)("span",{className:"min-w-0 flex-1 truncate",children:Nse})]}):(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)(po,{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:Nse}),(0,t.jsx)("span",{className:"block text-xs text-muted-foreground",children:zot})]})]})}r(ICe,"InstallAppMenuAction");function qot(){const e=Fot();return(0,t.jsx)(Qs,{open:e,onOpenChange:y6,children:(0,t.jsxs)(Js,{children:[(0,t.jsxs)(hn,{children:[(0,t.jsx)(Xs,{children:"Install Paperclip"}),(0,t.jsx)(jn,{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)(Z$,{index:1,icon:(0,t.jsx)(Nqe,{className:"size-4"}),children:["Tap ",(0,t.jsx)("strong",{children:"Share"})," in the Safari toolbar."]}),(0,t.jsxs)(Z$,{index:2,icon:(0,t.jsx)(Cqe,{className:"size-4"}),children:["Choose ",(0,t.jsx)("strong",{children:"Add to Home Screen"}),"."]}),(0,t.jsxs)(Z$,{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)(hr,{children:(0,t.jsx)(L,{type:"button",onClick:r(()=>y6(!1),"onClick"),children:"Done"})})]})})}r(qot,"IosInstallHelpDialog");function Z$({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(Z$,"InstallStep");function Uot(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(Uot,"formatTimestamp$2");function Kot(e){return!!e&&!Number.isNaN(new Date(e).getTime())}r(Kot,"isValidTimestamp");function Wot(e){return e?.devServer?.lastRestartAt??e?.serverInfo?.processStartedAt??null}r(Wot,"restartTimestamp");function Vot(e){const s=e?.serverInfo?.git;return s?.available?`${s.shortSha} · ${s.subject}`:"Commit unavailable"}r(Vot,"commitLabel");function Hot(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(Hot,"localChangesLabel");function eO({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(eO,"ServerInfoRow");function ACe(){const e=Z({queryKey:P.instance.experimentalSettings,queryFn:r(()=>Nr.getExperimental(),"queryFn")}).data?.enableServerInfoDebugView===!0,s=Z({queryKey:P.health,queryFn:r(()=>tu.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=Wot(n),l=Kot(o),c=i?"Health unavailable":a?"Loading...":Uot(o),d=i?"Health unavailable":a?"Loading...":Vot(n),u=i?"Health unavailable":a?"Loading...":Hot(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)(eO,{icon:Yd,label:"Last restarted",value:c,dateTime:!i&&!a&&l?o:null}),(0,t.jsx)(eO,{icon:T7,label:"Running commit",value:d}),(0,t.jsx)(eO,{icon:Zze,label:"Checkout state",value:u})]})}r(ACe,"SidebarServerInfo");var Got="/company/settings/members?tab=invites",Qot="https://docs.paperclip.ing/",Yot="https://paperclip.ing/feedback";function Jot(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(Jot,"deriveInitials$2");function tO({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)(Ke,{to:a,className:l,onClick:n,children:c}):(0,t.jsx)("button",{type:"button",className:l,onClick:n,children:c})}r(tO,"MenuAction$1");function Sse({deploymentMode:e,open:s,onOpenChange:n,forceExpanded:a=!1}){const o=!!$c(),{hidden:l,loaded:c}=eu(),d=wCe(),u=kCe(!o),h=o?d:u?Got:null,p=c&&h!==null&&!cg(l,"company.members")&&!cg(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=NCe(k),C=n??x,{data:I}=Z({queryKey:P.auth.session,queryFn:r(()=>Oa.getSession(),"queryFn"),retry:!1}),R=ZN({onSignedOut:B}),T=I?.user.name?.trim()||"Board",A=I?.user.email?.trim()||(e==="authenticated"?"Signed in":"Local workspace board"),D=Jot(T),M=SCe(I?.user);function B(){C(!1),b&&v(!1)}r(B,"closeNavigationChrome");function E(){R.mutate()}return r(E,"handleSignOut"),(0,t.jsx)("div",{className:"bg-border/50 px-3 py-2 dark:bg-muted",children:(0,t.jsxs)("div",{className:W("flex items-center gap-0.5",!w&&"px-2"),children:[(0,t.jsxs)(gr,{open:k,onOpenChange:C,children:[(0,t.jsx)(Sr,{asChild:!0,children:(0,t.jsxs)("button",{type:"button",className:W("flex min-w-0 items-center gap-2.5 rounded-lg text-left text-(length:--text-compact) font-medium text-foreground/80 transition-colors hover:bg-sidebar-accent hover:text-sidebar-accent-foreground",w?"w-full px-3 py-2":"flex-1 px-2 py-1.5"),"aria-label":"Open account menu",children:[(0,t.jsxs)(Mo,{size:"sm",children:[I?.user.image?(0,t.jsx)(xd,{src:I.user.image,alt:T}):null,(0,t.jsx)(Do,{children:D})]}),(0,t.jsx)("span",{className:W("min-w-0 flex-1 truncate",w&&"block w-0 min-w-0 overflow-hidden whitespace-nowrap text-transparent select-none"),children:T})]})}),(0,t.jsxs)(dr,{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)(Ke,{to:M,"aria-label":"View profile",onClick:B,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)(Mo,{className:"pointer-events-none relative size-9",children:[I?.user.image?(0,t.jsx)(xd,{src:I.user.image,alt:T}):null,(0,t.jsx)(Do,{className:"text-xs text-foreground",children:D})]}),(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:T}),(0,t.jsx)("p",{className:"truncate text-(length:--text-micro) leading-(--profile-popover-meta-line-height) text-muted-foreground",children:A}),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)(tO,{label:"Settings",icon:Jd,href:"/company/settings",onClick:B}),p&&h?(0,t.jsx)(tO,{label:"Invite",icon:Hf,href:h,topLevel:o,onClick:B}):null,(0,t.jsx)(tO,{label:"Documentation",icon:HN,href:Qot,external:!0,onClick:r(()=>C(!1),"onClick")}),(0,t.jsx)(yk,{variant:"compact-menu-action",onAfterToggle:r(()=>C(!1),"onAfterToggle")}),(0,t.jsx)(ICe,{variant:"compact-menu-action",onAfterAction:r(()=>C(!1),"onAfterAction")}),e==="authenticated"?(0,t.jsxs)("button",{type:"button",className:W("flex h-(--profile-popover-row-height) w-full items-center gap-(--profile-popover-row-gap) rounded-lg px-2.5 text-left text-(length:--text-compact) font-medium leading-(--profile-popover-label-line-height) text-foreground transition-colors hover:bg-destructive/10",R.isPending&&"cursor-not-allowed opacity-60"),onClick:E,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)(Tp,{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)(ACe,{})]})]})]}),!w&&!o?(0,t.jsxs)(zn,{children:[(0,t.jsx)(qn,{asChild:!0,children:(0,t.jsx)("a",{href:Yot,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)(Cg,{className:"h-4 w-4","aria-hidden":"true"})})}),(0,t.jsx)(Un,{side:"top",children:"Share feedback"})]}):null]})})}r(Sse,"SidebarAccountMenu$1");function TCe({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=qfe({armed:l,defaultPrevented:b.defaultPrevented,key:b.key,metaKey:b.metaKey,ctrlKey:b.ctrlKey,altKey:b.altKey,target:b.target,hasOpenDialog:wp()});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(!DI(b.target)&&!wp()){if(b.key==="/"&&!b.metaKey&&!b.ctrlKey&&!b.altKey){b.preventDefault(),VOe()||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(TCe,"useKeyboardShortcuts");var Xot=new Set(["auth","invite","board-claim","cli-auth","docs","s"]);function RCe(e){const s=(e.split("?")[0]??"").split("/").filter(Boolean);if(s.length===0)return!0;const[n]=s;return!Xot.has(n)}r(RCe,"isRememberableCompanyPath");function Zot(e){const s=ly(e.companyPrefix);return e.companies.find(n=>ly(n.issuePrefix)===s)??null}r(Zot,"findCompanyByPrefix");function elt(e){const s=i7(e.pathname);return s?Zot({companies:e.companies,companyPrefix:s})?.id??null:e.fallbackCompanyId}r(elt,"getRememberedPathOwnerCompanyId");function tlt(e){const s=e.path?uM(e.path):"/dashboard";if(!RCe(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&&ly(i[1]??"")!==ly(e.companyPrefix))return"/dashboard"}return s}r(tlt,"sanitizeRememberedPathForCompany");var ECe="paperclip.companyPaths";function PCe(){try{const e=localStorage.getItem(ECe);if(e)return JSON.parse(e)}catch{}return{}}r(PCe,"getCompanyPaths");function slt(e,s){const n=PCe();n[e]=s,localStorage.setItem(ECe,JSON.stringify(n))}r(slt,"saveCompanyPath");function MCe(){const{companies:e,selectedCompanyId:s,selectedCompany:n,selectionSource:a}=ps(),i=na(),o=Mn(),l=(0,m.useRef)(s),c=(0,m.useMemo)(()=>elt({companies:e,pathname:i.pathname,fallbackCompanyId:l.current}),[e,i.pathname]),d=i.pathname+i.search;(0,m.useEffect)(()=>{const u=c,h=uM(d);u&&RCe(h)&&slt(u,h)},[d,c]),(0,m.useEffect)(()=>{if(s){if(l.current!==null&&s!==l.current&&a!=="route_sync"&&n){const u=PCe(),h=tlt({path:u[s],companyPrefix:n.issuePrefix});o(`/${n.issuePrefix}${h}`,{replace:!0})}l.current=s}},[n,s,a,o])}r(MCe,"useCompanyPageMemory");var nlt=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 DCe(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 nlt({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(DCe,"useMobileNavVisibility");function LCe(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(LCe,"resolveArchivedCompanyBounce");function rlt(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(rlt,"resolveCompanyArchiveDeparture");function $Ce(e){const{selectionSource:s,selectedCompanyId:n,routeCompanyId:a}=e;return!(n===a||s==="manual"&&n)}r($Ce,"shouldSyncCompanySelectionFromRoute");function alt(e,s){return e instanceof HTMLElement?!(s instanceof HTMLElement)||!document.contains(s)||s===document.body||s===document.documentElement?!0:!e.contains(s):!1}r(alt,"shouldFocusMainContentAfterNavigation");function OCe(e){if(!(e instanceof HTMLElement))return()=>{};const s=window.requestAnimationFrame(()=>{alt(e,document.activeElement)&&e.focus({preventScroll:!0})});return()=>window.cancelAnimationFrame(s)}r(OCe,"scheduleMainContentFocus");function FCe(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(FCe,"pinDocumentScrollToZero");function Pu({scope:e="global",requestedPrefix:s}){const n=na(),{setBreadcrumbs:a}=Bn(),{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)(rn,{className:"block p-6",children:[(0,t.jsxs)("div",{className:"flex items-center gap-3",children:[(0,t.jsx)("div",{className:"rounded-md border border-destructive/20 bg-destructive/10 p-2",children:(0,t.jsx)(Es,{className:"h-5 w-5 text-destructive"})}),(0,t.jsxs)("div",{children:[(0,t.jsx)("h1",{className:"text-xl font-semibold",children:h}),(0,t.jsx)("p",{className:"text-sm text-muted-foreground",children:p})]})]}),(0,t.jsxs)("div",{className:"mt-4 rounded-md border border-border bg-muted/20 px-3 py-2 text-xs text-muted-foreground",children:["Requested path: ",(0,t.jsx)("code",{className:"font-mono",children:d})]}),(0,t.jsxs)("div",{className:"mt-5 flex flex-wrap gap-2",children:[(0,t.jsx)(L,{asChild:!0,children:(0,t.jsxs)(Ke,{to:c,children:[(0,t.jsx)(N3,{className:"mr-1.5 h-4 w-4"}),"Open dashboard"]})}),(0,t.jsx)(L,{variant:"outline",asChild:!0,children:(0,t.jsx)(Ke,{to:"/",children:"Go home"})})]})]})})}r(Pu,"NotFoundPage");function ilt(e,s){return hje(e,s)[0]?.toLowerCase()??null}r(ilt,"getCompanyRouteSegment$1");var olt=new Set(["browse","connections","connect","chat","vercel-connect","review","attention","gateways","advanced","app"]);function llt({sidebarSections:e}){const{sidebarOpen:s,setSidebarOpen:n,toggleSidebar:a,collapsed:i,peeking:o,setPeeking:l,isMobile:c,setForceCollapsed:d}=qa(),{openNewIssue:u,openOnboarding:h}=Qo(),{togglePanelVisible:p}=Yf(),f=Xc()?.pushToast??null,{companies:x,loading:b,selectedCompany:v,selectedCompanyId:j,selectionSource:N,setSelectedCompanyId:w}=ps(),{companyPrefix:k,pluginRoutePath:S,agentId:C,routineId:I}=va(),R=Mn(),T=na(),A=dM(),{enabled:D}=yc(),M=pje(T.pathname,k),B=M.builtInContextualSurface==="settings",E=M.companySegments,z=M.isTaskDetail,{enabled:$}=Yy(),q=$&&E[0]?.toLowerCase()==="chats",U=D&&(z||q),O=E[0]?.toLowerCase()==="tools",K=E[0]?.toLowerCase()==="apps",H=K&&E[1]&&!olt.has(E[1].toLowerCase())?E[1]:null,ee=K&&E[1]?.toLowerCase()==="app"&&E[2]?E[2]:null,se=(0,m.useRef)(!1),ne=(0,m.useRef)(null),fe=(0,m.useRef)(null),X=(0,m.useRef)(new rye),re=(0,m.useRef)(T.key),oe=DCe(c&&!z,T.pathname),[G,Y]=(0,m.useState)(!1),Q=(0,m.useMemo)(()=>{if(!k)return null;const lt=k.toUpperCase();return x.find(Ee=>Ee.issuePrefix.toUpperCase()===lt)??null},[x,k]),te=!!k&&!b&&x.length>0&&!Q,ae=(0,m.useMemo)(()=>S?.toLowerCase()??ilt(T.pathname,k),[k,T.pathname,S]),le=Q?.id??null,he=Q?.issuePrefix??null,{slots:ce}=bd({slotTypes:["page","routeSidebar"],companyId:le,enabled:!!(le&&ae)}),ge=(0,m.useMemo)(()=>s9(ce,ae),[ae,ce]),me=(0,m.useMemo)(()=>({companyId:le,companyPrefix:he}),[le,he]),ie=B?(0,t.jsx)(I9e,{}):!D&&M.builtInContextualSurface==="skills"?(0,t.jsx)(oZ,{}):H?(0,t.jsx)(aZ,{kind:"connection",connectionId:H}):ee?(0,t.jsx)(aZ,{kind:"application",applicationId:ee}):K||O?(0,t.jsx)(L9e,{}):ge?D?(0,t.jsx)(eA,{surface:`plugin:${ge.id}`,title:ge.displayName,children:(0,t.jsx)(Wu,{slot:ge,context:me,className:"min-h-0 flex-1",missingBehavior:"placeholder"})}):(0,t.jsx)(Wu,{slot:ge,context:me,className:"h-full w-full",missingBehavior:"placeholder"}):null,ue=q?(0,t.jsx)(_ot,{}):M.builtInContextualSurface==="agent"&&C?(0,t.jsx)(Y9e,{agentRef:C}):D&&M.builtInContextualSurface==="routine"&&I?(0,t.jsx)(cKe,{children:(0,t.jsx)(Z9e,{routineId:I})}):D&&M.builtInContextualSurface==="skills"?(0,t.jsx)(oZ,{}):ie,ke=ue!=null,be=D&&ke&&(q||M.builtInContextualSurface==="skills"||M.builtInContextualSurface==="agent"||M.builtInContextualSurface==="routine"||K||O),Ie=D&&ke&&!be,Ue=ke&&(!D||be),at=!D||!ke?null:ge&&!M.builtInContextualSurface?`plugin:${ge.id}`:M.builtInContextualSurface,dt=(0,m.useRef)(null),{data:de}=Z({queryKey:P.health,queryFn:r(()=>tu.get(),"queryFn"),retry:!1,refetchInterval:r(lt=>lt.state.data?.devServer?.enabled?2e3:!1,"refetchInterval"),refetchIntervalInBackground:!1});(0,m.useLayoutEffect)(()=>(d(!D&&ke),()=>d(!1)),[ke,d,D]),(0,m.useEffect)(()=>{const lt=dt.current;at&&k&&lt&&lt.surface!==at&&lt.pathname!==T.pathname&&S9e({surface:at,companyPrefix:k,previousPathname:lt.pathname}),dt.current={pathname:T.pathname,surface:at}},[k,at,T.pathname]),(0,m.useEffect)(()=>{b||se.current||de?.deploymentMode!=="authenticated"&&(de?.cloud||x.length===0&&(se.current=!0,h()))},[x,b,h,de?.cloud,de?.deploymentMode]),(0,m.useEffect)(()=>{if(!k||b||x.length===0)return;if(!Q){const Ee=(j?x.find(Xe=>Xe.id===j):null)??x[0]??null;Ee&&j!==Ee.id&&w(Ee.id,{source:"route_sync"});return}if(k!==Q.issuePrefix){const Ee=T.pathname.replace(/^\/[^/]+/,"");R(`/${Q.issuePrefix}${Ee}${T.search}`,{replace:!0});return}const lt=LCe({matchedCompany:Q,selectedCompanyId:j,companies:x});if(lt){f?.({title:`${Q.name} is archived`,body:`Switched to ${lt.name}.`,tone:"info",dedupeKey:`archived-company-bounce:${Q.id}`}),w(lt.id,{source:"route_sync"}),R(`/${lt.issuePrefix}/dashboard`,{replace:!0});return}$Ce({selectionSource:N,selectedCompanyId:j,routeCompanyId:Q.id})&&w(Q.id,{source:"route_sync"})},[k,x,b,Q,T.pathname,T.search,R,f,N,j,w]);const Be=p,pt=(0,m.useCallback)(()=>{document.dispatchEvent(new KeyboardEvent("keydown",{key:"k",metaKey:!0,bubbles:!0,cancelable:!0}))},[]),vt=(0,m.useRef)(null),Le=(0,m.useRef)(!1),Qe=(0,m.useRef)(!1),ut=(0,m.useCallback)(()=>{vt.current!==null&&(window.clearTimeout(vt.current),vt.current=null)},[]),Ye=(0,m.useCallback)(()=>{ut(),vt.current=window.setTimeout(()=>l(!0),50)},[ut,l]),it=(0,m.useCallback)(()=>{ut(),l(!0)},[ut,l]),kt=(0,m.useCallback)(()=>{ut(),vt.current=window.setTimeout(()=>l(!1),120)},[ut,l]),tt=(0,m.useCallback)(()=>{Le.current=!0,i&&!Qe.current&&Ye()},[i,Ye]),Pe=(0,m.useCallback)(()=>{Le.current=!1,Qe.current=!1,kt()},[kt]),Ce=(0,m.useCallback)(()=>{Qe.current||it()},[it]),He=(0,m.useCallback)(()=>{Le.current||kt()},[kt]);(0,m.useEffect)(()=>ut,[ut]);const Je=(0,m.useRef)(i);return(0,m.useEffect)(()=>{i!==Je.current&&(i?(ut(),l(!1),Qe.current=Le.current):Qe.current=!1,Je.current=i)},[i,ut,l]),(0,m.useEffect)(()=>{if(!o)return;const lt=r(Ee=>{Ee.key==="Escape"&&(ut(),l(!1))},"onKeyDown");return window.addEventListener("keydown",lt),()=>window.removeEventListener("keydown",lt)},[o,ut,l]),MCe(),TCe({onNewIssue:r(()=>u(),"onNewIssue"),onSearch:pt,onToggleSidebar:a,onTogglePanel:Be,onShowShortcuts:r(()=>Y(!0),"onShowShortcuts"),onGoToInbox:r(()=>R("/inbox"),"onGoToInbox")}),(0,m.useEffect)(()=>{if(!c)return;const lt=30,Ee=50,Xe=75;let Ae=0,De=0;const _t=r(gt=>{const We=gt.touches[0];Ae=We.clientX,De=We.clientY},"onTouchStart"),ye=r(gt=>{const We=gt.changedTouches[0],Ot=We.clientX-Ae;if(!(Math.abs(We.clientY-De)>Xe)){if(!s&&Ae<lt&&Ot>Ee){n(!0);return}s&&Ot<-50&&n(!1)}},"onTouchEnd");return document.addEventListener("touchstart",_t,{passive:!0}),document.addEventListener("touchend",ye,{passive:!0}),()=>{document.removeEventListener("touchstart",_t),document.removeEventListener("touchend",ye)}},[c,s,n]),(0,m.useEffect)(()=>{const lt=document.body.style.overflow;return document.body.style.overflow=c?"visible":"clip",()=>{document.body.style.overflow=lt}},[c]),(0,m.useEffect)(()=>{if(!c)return FCe()},[c]),(0,m.useEffect)(()=>{if(typeof document>"u")return;const lt=fe.current;return OCe(lt)},[T.pathname]),(0,m.useEffect)(()=>{const lt=fe.current;if(!lt)return;const Ee=r(()=>{X.current.remember(re.current,lt.scrollTop)},"recordScroll");return lt.addEventListener("scroll",Ee,{passive:!0}),()=>lt.removeEventListener("scroll",Ee)},[]),(0,m.useLayoutEffect)(()=>{const lt=fe.current,Ee=nye({previousPathname:ne.current,pathname:T.pathname,navigationType:A,state:T.state});ne.current=T.pathname;const Xe=A==="POP",Ae=Xe?X.current.recall(T.key):0;if(re.current=T.key,Xe){V3(lt,Ae);const De=requestAnimationFrame(()=>V3(lt,Ae));return()=>cancelAnimationFrame(De)}Ee&&aye(lt)},[T.key,T.pathname,T.state,A]),(0,t.jsx)(sye,{children:(0,t.jsxs)("div",{className:W("bg-background text-foreground pt-(--sz-safe-top)",c?"min-h-dvh overflow-x-clip":"flex h-dvh flex-col overflow-clip"),children:[(0,t.jsx)("a",{href:"#main-content",className:"sr-only focus:not-sr-only focus:fixed focus:left-3 focus:top-3 focus:z-(--z-200) focus:rounded-md focus:bg-background focus:px-3 focus:py-2 focus:text-sm focus:font-medium focus:shadow-lg focus:outline-none focus-visible:ring-2 focus-visible:ring-ring",children:"Skip to Main Content"}),(0,t.jsx)(cCe,{}),(0,t.jsx)(dCe,{devServer:de?.devServer}),(0,t.jsxs)("div",{className:W("min-h-0 flex-1",c?"w-full":"flex overflow-clip"),children:[c&&s&&(0,t.jsx)("button",{type:"button",className:"fixed inset-0 z-40 bg-black/50",onClick:r(()=>n(!1),"onClick"),"aria-label":"Close sidebar"}),c?(0,t.jsxs)("div",{className:W("fixed inset-y-0 left-0 z-50 flex flex-col overflow-hidden pt-(--sz-safe-top) transition-transform duration-100 ease-out",s?"translate-x-0":"-translate-x-full"),children:[(0,t.jsx)("div",{className:"flex flex-1 min-h-0 overflow-hidden",children:(0,t.jsx)("div",{className:"w-60 shrink-0 overflow-hidden",children:ke?(0,t.jsx)(X2,{children:ue}):(0,t.jsx)(tZ,{children:e})})}),(0,t.jsx)(Sse,{deploymentMode:de?.deploymentMode,forceExpanded:Ie})]}):(0,t.jsxs)(Iot,{open:s,collapsed:Ie?!1:i,peeking:Ie?!1:o,resizable:!0,onPanelMouseEnter:Ie?void 0:tt,onPanelMouseLeave:Ie?void 0:Pe,onPanelFocusCapture:!Ie&&i?Ce:void 0,onPanelBlurCapture:!Ie&&i?He:void 0,children:[(0,t.jsx)("div",{className:"flex flex-1 min-h-0",children:Ie?(0,t.jsx)(X2,{children:ue}):(0,t.jsx)(tZ,{children:e})}),(0,t.jsx)(Sse,{deploymentMode:de?.deploymentMode,forceExpanded:Ie})]}),!c&&Ue&&!be?(0,t.jsx)(X2,{className:"w-60 shrink-0",children:ue}):null,(0,t.jsxs)("div",{className:W("flex min-w-0 flex-col",c?"w-full":"h-full flex-1"),children:[(0,t.jsxs)("div",{"data-slot":c?"mobile-topbar":void 0,className:W(!c&&U&&"hidden",c&&"sticky top-0 z-20 bg-background/95 backdrop-blur supports-[backdrop-filter]:bg-background/85"),children:[(0,t.jsx)(f6,{mobile:c,onNavigateHome:r(()=>R("/dashboard"),"onNavigateHome")}),(0,t.jsx)(cZ,{}),c&&B?(0,t.jsx)("div",{className:"border-b border-border px-4 pb-3",children:(0,t.jsx)(gje,{})}):null]}),(0,t.jsxs)("div",{className:W(c?"block":"flex flex-1 min-h-0",!c&&U&&"streamlined-task-detail-surface"),children:[!c&&be?(0,t.jsx)(X2,{className:"w-60 shrink-0 bg-background",children:ue}):null,(0,t.jsxs)("div",{className:W(!c&&U?"flex min-w-0 flex-1 flex-col":"contents"),children:[!c&&U?(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)(f6,{mobile:!1,onNavigateHome:r(()=>R("/dashboard"),"onNavigateHome")}),(0,t.jsx)(cZ,{taskDetailLayout:!0})]}):null,(0,t.jsx)("main",{id:"main-content",ref:fe,tabIndex:-1,style:c?{"--tc-composer-bottom":"var(--sz-calc-14)"}:void 0,className:W("flex-1 p-4 outline-none md:p-6",!c&&U&&"pt-0 md:pt-0",c?"overflow-visible pb-(--sz-calc-14)":"overflow-auto [scrollbar-gutter:stable]"),children:te?(0,t.jsx)(Pu,{scope:"invalid_company_prefix",requestedPrefix:k??v?.issuePrefix}):(0,t.jsx)(pCe,{children:(0,t.jsx)(db,{})})})]}),(0,t.jsx)(Aje,{taskDetailLayout:!c&&U})]})]})]}),c&&(0,t.jsx)(lCe,{visible:oe}),(0,t.jsx)(Tje,{}),(0,t.jsx)(dwe,{}),(0,t.jsx)(eCe,{}),(0,t.jsx)(nCe,{}),(0,t.jsx)(rCe,{}),(0,t.jsx)(aCe,{open:G,onOpenChange:Y}),(0,t.jsx)(iCe,{}),(0,t.jsx)(Jit,{health:de}),(0,t.jsx)(oCe,{localTrusted:de?.deploymentMode==="local_trusted"})]})})}r(llt,"Layout$1");var BCe=(0,m.createContext)(!1);function clt({children:e}){return(0,t.jsx)(BCe.Provider,{value:!0,children:e})}r(clt,"SidebarNavExpandedProvider");function dlt(){return(0,m.useContext)(BCe)}r(dlt,"useSidebarNavExpanded");function si({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(),I=dlt(),R=S&&!C&&!I,T=c!=null&&c>0,A=x!=null&&x>0,D=A?`${x} live`:T?`${c}${u?` ${u}`:""}`:f?"attention needed":void 0,M=!R||!D&&!j?void 0:`${s}${D?`, ${D}`:""}${j?`, ${j}`:""}`,B=(0,t.jsxs)(ub,{to:e,state:Gf,end:i,"aria-label":M,onClick:r(()=>{w&&k(!1)},"onClick"),className:r(({isActive:E})=>W("flex items-center gap-2.5 mx-2 rounded-lg px-2 py-1.5 pointer-coarse:py-1 text-(length:--text-compact) font-medium transition-colors",b??E?"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&&A&&(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&&!A&&T&&(0,t.jsx)("span",{className:W("absolute -right-0.5 -top-0.5 h-2 w-2 rounded-full shadow-(--shadow-extract-12)",d==="danger"?"bg-red-600":d==="warning"?"bg-amber-500":"bg-primary"),"aria-hidden":"true"})]}),(0,t.jsx)("span",{className:R?By:W("min-w-0 flex-1 truncate",l),children:s}),!R&&v,!R&&h&&(0,t.jsx)(ct,{variant:"ghost",className:W("ml-auto px-1.5 text-(length:--text-nano) leading-none",p==="amber"?"bg-amber-100 text-amber-800 dark:bg-amber-900/30 dark:text-amber-400":"bg-muted text-muted-foreground"),children:h}),!R&&(A||N)&&(0,t.jsxs)("span",{className:"ml-auto flex items-center gap-1.5",children:[N,A&&(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&&T&&(0,t.jsx)(ct,{variant:"ghost",className:W("ml-auto px-1.5 leading-none",d==="danger"?"bg-red-600/90 text-red-50":d==="warning"?"bg-amber-500/90 text-amber-50":"bg-primary text-primary-foreground"),children:c})]});return R?(0,t.jsxs)(zn,{children:[(0,t.jsx)(qn,{asChild:!0,children:(0,t.jsx)("div",{children:B})}),(0,t.jsx)(Un,{side:"right",children:s})]}):B}r(si,"SidebarNavItem");var ult=3,Cse=12e4,mlt=[{value:"top",label:"Top"},{value:"alphabetical",label:"Alphabetical"},{value:"recent",label:"Recent"}];function Yj(e,s){const n=e[s];if(!n)return 0;const a=new Date(n).getTime();return Number.isFinite(a)?a:0}r(Yj,"agentTimestamp");function _se(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=Yj(i,"lastHeartbeatAt")-Yj(a,"lastHeartbeatAt");if(o!==0)return o;const l=Yj(i,"updatedAt")-Yj(a,"updatedAt");if(l!==0)return l;const c=Yj(i,"createdAt")-Yj(a,"createdAt");return c!==0?c:a.name.localeCompare(i.name,void 0,{sensitivity:"base"})}),n)}r(_se,"sortAgents");var hlt="opacity-0 transition-opacity group-hover/agent:opacity-100 group-focus-within/agent:opacity-100";function plt({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=Xl(n),j=s?`${Cm(n)}/${s}`:Cm(n),N=`${Cm(n)}/configuration`,w=e===v,k=n.status==="paused",S=k&&n.pauseReason==="budget",C=n.orgChainHealth?.status==="invalid_org_chain",I=k?"Resume agent":"Pause agent",R=a||n.status==="pending_approval"||S||k&&C,T=a?"Updating...":S?"Budget paused":k&&C?"Invalid org chain":I,A=p==="needs_setup"||p==="pending_approval",D=[A?`Built-in agent ${p.replace(/_/g," ")}`:null,C?"Invalid reporting chain":null].filter(Boolean).join(", ")||void 0,M=(0,t.jsx)(si,{to:j,label:n.name,iconNode:(0,t.jsx)(kr,{agent:n,size:16,className:"shrink-0 h-4 w-4"}),active:w,liveCount:u,labelClassName:A?"min-w-(--sz-4_5rem) flex-initial":void 0,className:W("min-w-0 flex-1",f&&!i?"pr-14":"pr-8"),trailing:A||C?(0,t.jsxs)("span",{className:"ml-1 flex shrink-0 items-center gap-1",children:[A?(0,t.jsx)(uk,{status:p,compact:!0}):null,C?(0,t.jsx)(Es,{className:"h-3.5 w-3.5 shrink-0 text-amber-500","aria-label":"Invalid reporting chain"}):null]}):void 0,trailingLabel:D,liveAccessory:n.pauseReason==="budget"?(0,t.jsx)(JI,{title:"Agent paused by budget"}):void 0});return d?M:(0,t.jsxs)("div",{className:"group/agent relative flex items-center",children:[M,f&&!i&&x?(0,t.jsx)("span",{className:"absolute right-10 top-1/2 -translate-y-1/2",children:(0,t.jsx)(gb,{size:"row",quiet:!0,starred:!0,pending:b,resourceName:n.name,onToggle:r(()=>x(n,!1),"onToggle"),revealClassName:hlt})}):null,(0,t.jsxs)(Xr,{children:[(0,t.jsx)(Jr,{asChild:!0,children:(0,t.jsx)(L,{variant:"ghost",size:"icon-xs",className:W("absolute right-3 top-1/2 h-6 w-6 -translate-y-1/2 transition-opacity data-[state=open]:pointer-events-auto data-[state=open]:opacity-100",i?"opacity-100":"pointer-events-none opacity-0 group-hover/agent:pointer-events-auto group-hover/agent:opacity-100 group-focus-within/agent:pointer-events-auto group-focus-within/agent:opacity-100"),"aria-label":`Open actions for ${n.name}`,children:(0,t.jsx)(Ri,{className:"h-3.5 w-3.5"})})}),(0,t.jsxs)(Zr,{align:"end",className:"w-48",children:[x?(0,t.jsxs)(t.Fragment,{children:[(0,t.jsxs)(ls,{onClick:r(()=>{b||x(n,!f)},"onClick"),disabled:b,children:[b?(0,t.jsx)(rt,{className:"size-4 motion-safe:animate-spin"}):(0,t.jsx)(yp,{className:W("size-4",f&&"fill-amber-500 text-amber-500")}),(0,t.jsx)("span",{children:f?"Remove from starred":"Star agent"})]}),(0,t.jsx)(ni,{})]}):null,(0,t.jsx)(ls,{asChild:!0,children:(0,t.jsxs)(Ke,{to:N,onClick:r(()=>{i&&h(!1)},"onClick"),children:[(0,t.jsx)(gc,{className:"size-4"}),(0,t.jsx)("span",{children:"Edit agent"})]})}),(0,t.jsx)(ni,{}),(0,t.jsxs)(ls,{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)(VI,{className:"size-4"}):(0,t.jsx)(Rd,{className:"size-4"}),(0,t.jsx)("span",{children:T})]}),(0,t.jsx)(ni,{}),(0,t.jsxs)(ls,{onClick:r(()=>{o||l(n)},"onClick"),disabled:o,children:[o?(0,t.jsx)(rt,{className:"size-4 motion-safe:animate-spin"}):(0,t.jsx)(Tp,{className:"size-4"}),(0,t.jsx)("span",{children:o?"Leaving...":"Leave agent"})]})]})]})]})}r(plt,"SidebarAgentItem");function flt({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=Dt(),{selectedCompanyId:u}=ps(),{openNewAgent:h}=Qo(),{isMobile:p,setSidebarOpen:f,collapsed:x,peeking:b}=qa(),v=x&&!b,{pushToast:j}=da(),N=na(),{data:w}=Z({queryKey:P.agents.list(u),queryFn:r(()=>$t.list(u),"queryFn"),enabled:!!u}),{data:k}=Z({queryKey:P.instance.experimentalSettings,queryFn:r(()=>Nr.getExperimental(),"queryFn"),enabled:!!u}),S=k?.enableBuiltInAgents===!0,{data:C}=Z({queryKey:P.builtInAgents.list(u),queryFn:r(()=>Zh.list(u),"queryFn"),enabled:!!u&&S}),I=(0,m.useMemo)(()=>{const be=new Map;if(!S)return be;for(const Ie of C??[])Ie.agentId&&be.set(Ie.agentId,Ie.status);return be},[C,S]),{data:R}=Z({queryKey:P.auth.session,queryFn:r(()=>Oa.getSession(),"queryFn")}),T=Qf(u),A=Ag(u),D=P.liveRuns(u),M=No({companyId:u,resourceKey:"live-runs",queryKey:D,enabled:!!u,refetchInterval:!1,leaderOnly:!0}),{data:B,dataUpdatedAt:E}=Z({queryKey:D,queryFn:r(()=>sa.liveRunsForCompany(u),"queryFn"),enabled:M.enabled,refetchInterval:M.refetchInterval});So(M,B,E);const z=(0,m.useMemo)(()=>{const be=new Map;for(const Ie of B??[])be.set(Ie.agentId,(be.get(Ie.agentId)??0)+1);return be},[B]),$=(0,m.useMemo)(()=>{const be=new Set;for(const[Ie,Ue]of z)Ue>0&&be.add(Ie);return be},[z]),q=(0,m.useMemo)(()=>(w??[]).filter(be=>be.status!=="terminated"&&(!T.isSuccess||$f(T.data,"agent",be.id)!=="left")),[w,T.data,T.isSuccess]),U=R?.user?.id??R?.session?.userId??null,O=(0,m.useMemo)(()=>u?pye(u,U):null,[U,u]),[K,H]=(0,m.useState)(()=>O?mk(O):"top"),{orderedAgents:ee}=gye({agents:q,companyId:u,userId:U}),se=(0,m.useMemo)(()=>_se(ee,K),[ee,K]),ne=(0,m.useMemo)(()=>new Set(se.map(be=>be.id)),[se]);(0,m.useEffect)(()=>{const be=Date.now();for(const Ie of $)c.current.set(Ie,be);for(const Ie of c.current.keys())ne.has(Ie)||c.current.delete(Ie)},[$,ne]);const fe=(0,m.useMemo)(()=>{const be=Date.now(),Ie=c.current;return se.filter(Ue=>{if((z.get(Ue.id)??0)>0)return!0;const at=Ie.get(Ue.id);return at!==void 0&&be-at<=Cse})},[z,o,se]),X=fe.length>0,re=e?X?fe:se.slice(0,ult):se,oe=e&&se.length>0,G=N.pathname.match(/^\/(?:[^/]+\/)?agents\/([^/]+)(?:\/([^/]+))?/),Y=G?.[1]??null,Q=G?.[2]??null;(0,m.useEffect)(()=>{if(!O){H("top");return}H(mk(O))},[O]),(0,m.useEffect)(()=>{if(!O)return;const be=r(Ue=>{Ue.key===O&&H(mk(O))},"onStorage"),Ie=r(Ue=>{const at=Ue.detail;!at||at.storageKey!==O||H(at.sortMode)},"onCustomEvent");return window.addEventListener("storage",be),window.addEventListener(g_,Ie),()=>{window.removeEventListener("storage",be),window.removeEventListener(g_,Ie)}},[O]),(0,m.useEffect)(()=>{if(!e)return;const be=Date.now();let Ie=null;for(const at of se){if((z.get(at.id)??0)>0)continue;const dt=c.current.get(at.id);if(dt===void 0)continue;const de=dt+Cse;de<be||(Ie=Ie===null?de:Math.min(Ie,de))}if(Ie===null)return;const Ue=window.setTimeout(()=>{l(at=>at+1)},Math.max(0,Ie-be+1));return()=>{window.clearTimeout(Ue)}},[e,se,z,o]);const te=(0,m.useCallback)(be=>{const Ie=be==="alphabetical"||be==="recent"?be:"top";H(Ie),O&&xye(O,Ie)},[O]),ae=je({mutationFn:r(({agent:be,action:Ie})=>Ie==="pause"?$t.pause(be.id,u??void 0):$t.resume(be.id,u??void 0),"mutationFn"),onMutate:r(({agent:be})=>{i(Ie=>{const Ue=new Set(Ie);return Ue.add(be.id),Ue})},"onMutate"),onSuccess:r(async(be,{agent:Ie,action:Ue})=>{u&&await Promise.all([d.invalidateQueries({queryKey:P.agents.list(u)}),d.invalidateQueries({queryKey:P.liveRuns(u)}),d.invalidateQueries({queryKey:P.dashboard(u)})]),await Promise.all([d.invalidateQueries({queryKey:P.agents.detail(Ie.id)}),d.invalidateQueries({queryKey:P.agents.detail(Xl(Ie))})]),j({title:Ue==="pause"?"Agent paused":"Agent resumed",body:Ie.name,tone:"success"})},"onSuccess"),onError:r((be,{agent:Ie,action:Ue})=>{j({title:Ue==="pause"?"Could not pause agent":"Could not resume agent",body:be instanceof Error?be.message:Ie.name,tone:"error"})},"onError"),onSettled:r((be,Ie,{agent:Ue})=>{i(at=>{const dt=new Set(at);return dt.delete(Ue.id),dt})},"onSettled")}),le=(0,m.useCallback)(be=>A.mutate({resourceType:"agent",resourceId:be.id,resourceName:be.name,state:"left"}),[A]),he=(0,m.useCallback)(be=>A.isPending&&A.variables?.resourceType==="agent"&&A.variables.resourceId===be.id,[A.isPending,A.variables]),ce=(0,m.useCallback)((be,Ie)=>A.mutate({resourceType:"agent",resourceId:be.id,resourceName:be.name,starred:Ie}),[A]),ge=(0,m.useCallback)(be=>A.isPending&&A.variables?.resourceType==="agent"&&A.variables.resourceId===be.id&&A.variables.starred!==void 0,[A.isPending,A.variables]),me=(0,m.useMemo)(()=>new Set(PM(T.data,"agent")),[T.data]),ie=(0,m.useMemo)(()=>_se(q.filter(be=>me.has(be.id)),"alphabetical"),[q,me]),ue=(0,m.useMemo)(()=>re.filter(be=>!me.has(be.id)),[re,me]),ke=r((be,Ie)=>(0,t.jsx)(plt,{activeAgentId:Y,activeTab:Q,agent:be,disabled:a.has(be.id),isMobile:p,leaving:he(be),onLeaveAgent:le,onPauseResume:r((Ue,at)=>ae.mutate({agent:Ue,action:at}),"onPauseResume"),rail:v,runCount:z.get(be.id)??0,setSidebarOpen:f,builtInStatus:I.get(be.id),starred:Ie||xb(T.data,"agent",be.id),onToggleStar:ce,starPending:ge(be)},be.id),"renderAgentRow");return(0,t.jsxs)(eg,{label:"Agents",collapsible:{open:s,onOpenChange:n},headerAction:{ariaLabel:"New agent",icon:yn,onClick:h},menu:{ariaLabel:"Agents section actions",actions:[{type:"item",label:"Browse agents",icon:Vo,href:"/agents/all"},{type:"separator"}],radioLabel:"Agent sort",radioChoices:mlt,radioValue:K,onRadioValueChange:te},children:[ie.map(be=>ke(be,!0)),ue.map(be=>ke(be,!1)),oe&&(()=>{const be=(0,t.jsxs)(Ke,{to:"/agents/all",state:Gf,"aria-label":v?"See all agents":void 0,onClick:r(()=>{p&&f(!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)(Vo,{className:"shrink-0 h-4 w-4"}),(0,t.jsx)("span",{className:v?"block w-0 min-w-0 overflow-hidden whitespace-nowrap text-transparent select-none":void 0,children:"See all agents"})]});return v?(0,t.jsxs)(zn,{children:[(0,t.jsx)(qn,{asChild:!0,children:be}),(0,t.jsx)(Un,{side:"right",children:"See all agents"})]}):be})()]})}r(flt,"SidebarAgents");var xlt="opacity-0 transition-opacity group-hover/starred-project:opacity-100 group-focus-within/starred-project:opacity-100";function glt(){const{selectedCompanyId:e}=ps(),{isMobile:s,setSidebarOpen:n,collapsed:a,peeking:i}=qa(),o=a&&!i,l=na(),{data:c}=Z({queryKey:P.projects.list(e),queryFn:r(()=>pa.list(e),"queryFn"),enabled:!!e}),d=Qf(e),u=Ag(e),h=l.pathname.match(/^\/(?:[^/]+\/)?projects\/([^/]+)/)?.[1]??null,p=(0,m.useMemo)(()=>{if(!d.isSuccess)return[];const v=new Set(PM(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=lg(v),N=h===j||h===v.id,w=b(v),k=w&&u.variables?.starred===!1,S=w&&u.variables?.state==="left",C=xb(d.data,"project",v.id),I=(0,t.jsxs)(ub,{to:`/projects/${j}/issues`,state:Gf,onClick:r(()=>{s&&n(!1)},"onClick"),className:W("flex min-w-0 flex-1 items-center gap-2.5 mx-2 rounded-lg px-2 py-1.5 pointer-coarse:py-1 pr-8 text-(length:--text-compact) font-medium transition-colors",!o&&"pl-6",N?"bg-accent text-foreground":"text-foreground/80 hover:bg-accent/50 hover:text-foreground"),children:[(0,t.jsx)(Em,{color:v.color??null,icon:v.icon??null,size:"xs"}),(0,t.jsx)("span",{className:o?By:"flex-1 truncate",children:v.name}),!o&&v.pauseReason==="budget"?(0,t.jsx)(JI,{title:"Project paused by budget"}):null]});return(0,t.jsxs)("div",{className:"group/starred-project relative flex items-center",children:[o?(0,t.jsxs)(zn,{children:[(0,t.jsx)(qn,{asChild:!0,children:(0,t.jsx)("div",{className:"min-w-0 flex-1",children:I})}),(0,t.jsx)(Un,{side:"right",children:v.name})]}):I,!o&&!s?(0,t.jsx)("span",{className:"absolute right-3 top-1/2 -translate-y-1/2",children:(0,t.jsx)(gb,{size:"row",quiet:!0,starred:C,pending:k,resourceName:v.name,onToggle:r(()=>f(v),"onToggle"),revealClassName:xlt})}):null,!o&&s?(0,t.jsxs)(Xr,{children:[(0,t.jsx)(Jr,{asChild:!0,children:(0,t.jsx)(L,{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)(Ri,{className:"h-3.5 w-3.5"})})}),(0,t.jsxs)(Zr,{align:"end",className:"w-48",children:[(0,t.jsxs)(ls,{onClick:r(()=>{w||f(v)},"onClick"),disabled:w,children:[k?(0,t.jsx)(rt,{className:"size-4 motion-safe:animate-spin"}):(0,t.jsx)(yp,{className:"size-4 fill-amber-500 text-amber-500"}),(0,t.jsx)("span",{children:"Remove from starred"})]}),(0,t.jsx)(ni,{}),(0,t.jsxs)(ls,{onClick:r(()=>{w||x(v)},"onClick"),disabled:w,children:[S?(0,t.jsx)(rt,{className:"size-4 motion-safe:animate-spin"}):(0,t.jsx)(Tp,{className:"size-4"}),(0,t.jsx)("span",{children:"Leave project"})]})]})]}):null]},v.id)})})}r(glt,"SidebarStarredProjects");var blt="size-5 shrink-0 rounded-md text-(length:--text-micro)",vlt="size-(--organization-popover-avatar-size) shrink-0 rounded-lg text-(length:--text-micro)",ylt="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",sO="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 zCe({company:e,inPopover:s=!1}){return(0,t.jsx)(eS,{companyName:e.name,logoUrl:e.logoUrl,className:s?vlt:blt})}r(zCe,"WorkspaceIcon");function jlt({company:e,isEditing:s,isSelected:n,onSelect:a}){const{attributes:i,listeners:o,setActivatorNodeRef:l,setNodeRef:c,transform:d,transition:u,isDragging:h}=qN({id:e.id,disabled:!s});return(0,t.jsxs)(ls,{ref:c,style:{transform:DN.Transform.toString(d),transition:u,zIndex:h?10:void 0},onSelect:r(p=>{if(s){p.preventDefault();return}a(e)},"onSelect"),className:W(ylt,s&&"cursor-grab",h&&"opacity-80"),children:[(0,t.jsx)(zCe,{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)(SM,{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)(gs,{className:"size-4 text-foreground"}):null})]})}r(jlt,"SortableCompanyItem");function wlt(e={}){return(0,t.jsx)(uje,{...e,children:(0,t.jsx)(klt,{...e})})}r(wlt,"SidebarCompanyMenu");function klt({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}=Qo(),{isMobile:f,setSidebarOpen:x,collapsed:b,peeking:v}=qa(),j=b&&!v,N=na(),w=Mn(),k=e??n,S=s??a,C=FN(Pf(l7,{activationConstraint:{distance:8}}),Pf(Pfe,{activationConstraint:{delay:180,tolerance:6}})),I=(0,m.useMemo)(()=>l.filter(ne=>ne.status!=="archived"),[l]),{data:R}=Z({queryKey:P.auth.session,queryFn:r(()=>Oa.getSession(),"queryFn"),retry:!1}),T=R?.user?.id??R?.session?.userId??null,{orderedCompanies:A,persistOrder:D}=dje({companies:I,userId:T}),{hidden:M,loaded:B}=eu(),E=B&&!cg(M,"company.members")&&!cg(M,"company.invites"),z="company",$=c?.name??null,q=!!$c(),U=ZN({onSignedOut:K});function O(ne){ne||o(!1),S(ne)}r(O,"handleOpenChange");function K(){S(!1),o(!1),f&&x(!1)}r(K,"closeNavigationChrome");function H(ne){const fe=N.pathname.split("/")[1]?.toUpperCase(),X=I.some(oe=>oe.issuePrefix.toUpperCase()===fe),re=ne.id!==c?.id&&(N.pathname.startsWith("/instance/")||X);d(ne.id),S(!1),f&&x(!1),re&&w(`/${ne.issuePrefix}/dashboard`)}r(H,"selectCompany");function ee(){q||(S(!1),f&&x(!1),p({initialStep:1}))}r(ee,"addCompany");const se=(0,m.useCallback)(ne=>{const{active:fe,over:X}=ne;if(!X||fe.id===X.id)return;const re=A.map(Y=>Y.id),oe=re.indexOf(fe.id),G=re.indexOf(X.id);oe===-1||G===-1||D(pM(re,oe,G))},[A,D]);return(0,t.jsxs)(Xr,{open:k,onOpenChange:O,children:[(0,t.jsx)(Jr,{asChild:!0,children:(0,t.jsxs)(L,{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":$?`Open ${$} ${z} switcher`:`Open ${z} switcher`,children:[(0,t.jsxs)("span",{className:"flex min-w-0 flex-1 items-center gap-2",children:[c?(0,t.jsx)(zCe,{company:c}):null,(0,t.jsx)("span",{className:W("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:$??void 0,children:$??`Select ${z}`})]}),!j&&(0,t.jsx)(bM,{className:"size-3.5 shrink-0 text-muted-foreground"})]})}),(0,t.jsxs)(Zr,{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)(mb,{className:"p-0 text-(length:--text-compact) font-semibold text-foreground",children:"Organizations"}),(0,t.jsx)("button",{type:"button",onClick:r(ne=>{ne.preventDefault(),ne.stopPropagation(),o(fe=>!fe)},"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)(ON,{sensors:C,collisionDetection:PI,onDragEnd:se,children:(0,t.jsx)(BN,{items:A.map(ne=>ne.id),strategy:LI,children:A.map(ne=>(0,t.jsx)(jlt,{company:ne,isEditing:i,isSelected:ne.id===c?.id,onSelect:H},ne.id))})}),A.length===0?u?(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)(ls,{disabled:!0,children:"Couldn't load companies"}),(0,t.jsxs)(ls,{onSelect:r(ne=>{ne.preventDefault(),h()},"onSelect"),children:[(0,t.jsx)(_i,{className:"h-4 w-4 mr-2"}),"Try again"]})]}):(0,t.jsx)(ls,{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:[!q&&(0,t.jsxs)(ls,{onClick:ee,className:sO,disabled:i,children:[(0,t.jsx)("span",{className:"flex size-5 shrink-0 items-center justify-center text-muted-foreground",children:(0,t.jsx)(yn,{className:"size-4"})}),(0,t.jsx)("span",{className:"min-w-0 flex-1 truncate",children:"Create organization"})]}),E?(0,t.jsx)(ls,{asChild:!0,disabled:i,className:sO,children:(0,t.jsxs)(Ke,{to:"/company/settings/invites",onClick:r(ne=>{if(i){ne.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)(Hf,{className:"size-4"})}),(0,t.jsx)("span",{className:"min-w-0 flex-1 truncate",children:$?`Invite people to ${$}`:"Invite people"})]})}):null,R?.session?(0,t.jsxs)(ls,{className:sO,onClick:r(()=>U.mutate(),"onClick"),disabled:i||U.isPending,children:[(0,t.jsx)("span",{className:"flex size-5 shrink-0 items-center justify-center text-muted-foreground",children:(0,t.jsx)(Tp,{className:"size-4"})}),(0,t.jsx)("span",{className:"min-w-0 flex-1 truncate",children:U.isPending?"Signing out...":"Sign out"})]}):null]})]})]})}r(klt,"BuiltinCompanyMenu");function Ise(){const{openNewIssue:e}=Qo(),[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=$M(o),{data:p,isFetched:f}=Z({queryKey:P.instance.experimentalSettings,queryFn:r(()=>Nr.getExperimental(),"queryFn")}),x=P.liveRuns(o),b=No({companyId:o,resourceKey:"live-runs",queryKey:x,enabled:!!o,refetchInterval:!1,leaderOnly:!0}),{data:v,dataUpdatedAt:j}=Z({queryKey:x,queryFn:r(()=>sa.liveRunsForCompany(o),"queryFn"),enabled:b.enabled,refetchInterval:b.refetchInterval});So(b,v,j);const N=v?.length??0,w=p?.enableIsolatedWorkspaces===!0,k=p?.enableApps===!0,S=p?.enablePipelines===!0,C=p?.enableStatusCards===!0,I=!f,R=p?.enableGoalsSidebarLink===!0,T=p?.enableDecisions===!0,{data:A}=Z({queryKey:P.attention(o),queryFn:r(()=>YN.list(o),"queryFn"),enabled:!!o&&T,refetchInterval:6e4}),D=Bye(A),M=p?.enableCases===!0,B=!0,E=p?.enableConferenceRoomChat===!0,z={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)(wlt,{})}),(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 $=(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)(p_,{className:"h-4 w-4 shrink-0"}),(0,t.jsx)("span",{className:u?By:"truncate",children:"New Task"})]});return u?(0,t.jsxs)(zn,{children:[(0,t.jsx)(qn,{asChild:!0,children:$}),(0,t.jsx)(Un,{side:"right",children:"New Task"})]}):$})(),(0,t.jsx)(si,{to:"/search",label:"Search",icon:oa}),(0,t.jsx)(si,{to:"/dashboard",label:"Dashboard",icon:Zx,liveCount:N}),(0,t.jsx)(si,{to:"/inbox",label:"Inbox",icon:hd,badge:h.inbox,badgeLabel:"unread",badgeTone:h.failedRuns>0?"danger":"default",alert:h.failedRuns>0}),T?(0,t.jsx)(si,{to:"/decisions",label:"Decisions",icon:Hy,badge:D,badgeLabel:"decisions"}):null,C?(0,t.jsx)(si,{to:"/status",label:"Status",icon:GN,textBadge:"beta"}):null,E?(0,t.jsx)(si,{to:"/board-chat",label:"Conference Room",icon:rbe}):null]}),(0,t.jsxs)(eg,{label:"Work",collapsible:{open:s,onOpenChange:n},children:[(0,t.jsx)(si,{to:"/issues",label:"Tasks",icon:Cu}),M?(0,t.jsx)(si,{to:"/cases",label:"Cases",icon:zl,textBadge:"beta"}):null,(0,t.jsx)(si,{to:"/routines",label:"Routines",icon:Tu}),S?(0,t.jsx)(si,{to:"/pipelines",label:"Pipelines",icon:io}):null,R?(0,t.jsx)(si,{to:"/goals",label:"Goals",icon:vp}):I?(0,t.jsx)("div",{"data-testid":"sidebar-goals-placeholder",className:"h-8 pointer-coarse:h-7","aria-hidden":"true"}):null,(0,t.jsx)(si,{to:"/artifacts",label:"Artifacts",icon:Th}),(0,t.jsx)(si,{to:"/skills",label:"Skills",icon:xc}),w?(0,t.jsx)(si,{to:"/workspaces",label:"Workspaces",icon:io}):null,(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)(si,{to:"/projects",label:"Projects",icon:Ho}),(0,t.jsx)(glt,{})]}),(0,t.jsx)(Sp,{slotTypes:["sidebar"],context:z,className:"flex flex-col gap-0.5",itemClassName:"text-(length:--text-compact) font-medium",missingBehavior:"placeholder"}),(0,t.jsx)(XN,{placementZones:["sidebar"],context:z,className:"flex flex-col gap-0.5",itemClassName:"text-(length:--text-compact) font-medium"})]}),null,(0,t.jsx)(flt,{streamlined:B}),(0,t.jsxs)(eg,{label:"Company",collapsible:{open:a,onOpenChange:i},children:[(0,t.jsx)(si,{to:"/org",label:"Org",icon:hy}),k?(0,t.jsx)(si,{to:"/apps",label:"Connectors",icon:K3}):null,(0,t.jsx)(si,{to:"/timeline",label:"Timeline",icon:x0}),(0,t.jsx)(si,{to:"/costs",label:"Costs",icon:mp}),(0,t.jsx)(si,{to:"/activity",label:"Activity",icon:Zl}),(0,t.jsx)(si,{to:"/company/settings",label:"Settings",icon:Jd})]}),(0,t.jsx)(Sp,{slotTypes:["sidebarPanel"],context:z,className:"flex flex-col gap-3",itemClassName:"rounded-lg border border-border p-3",missingBehavior:"placeholder"})]})]})}r(Ise,"Sidebar");function Nlt(e){const s=e.manifestJson.environmentDrivers??[];return s.length===0?!1:s.every(n=>n.kind==="sandbox_provider")}r(Nlt,"isSandboxProviderOnly");function Slt(){const{selectedCompany:e,selectedCompanyId:s}=ps(),{isMobile:n,setSidebarOpen:a}=qa(),{hidden:i}=eu(),o=r(f=>!i.has(f),"showPage"),l=o("instance.plugins"),c=!!$c(),{slots:d}=bd({slotTypes:["companySettingsPage"],companyId:s,enabled:!!s}),{data:u}=Z({queryKey:s?P.sidebarBadges(s):["sidebar-badges","__disabled__"],queryFn:r(async()=>{try{return await l9.get(s)}catch(f){if(f instanceof dn&&(f.status===401||f.status===403))return null;throw f}},"queryFn"),enabled:!!s,retry:!1,refetchInterval:15e3}),{data:h}=Z({queryKey:P.plugins.all,queryFn:r(()=>Al.list(),"queryFn"),enabled:l}),p=(h??[]).filter(f=>!Nlt(f));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)(Ke,{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)(Uu,{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)(si,{to:"/company/settings",label:"General",icon:Ku,end:!0}),o("instance.profile")&&(0,t.jsx)(si,{to:"/company/settings/instance/profile",label:"Profile",icon:AM,end:!0}),o("company.members")&&(0,t.jsx)(si,{to:"/company/settings/members",label:"Members",icon:Vo,badge:u?.joinRequests??0,end:!0}),d.filter(f=>f.routePath).map(f=>(0,t.jsx)(si,{to:`/company/settings/${f.routePath}`,label:f.displayName,icon:Xx,end:!0},`${f.pluginKey}:${f.id}`)),o("company.invites")&&(0,t.jsx)(si,{to:"/company/settings/invites",label:"Invites",icon:cqe,end:!0}),o("company.secrets")&&(0,t.jsx)(si,{to:"/company/settings/secrets",label:"Secrets",icon:Si,end:!0}),o("instance.environments")&&(0,t.jsx)(si,{to:"/company/settings/instance/environments",label:"Environments",icon:cbe,end:!0}),o("instance.access")&&(0,t.jsx)(si,{to:"/company/settings/instance/access",label:"Access",icon:RI,end:!0}),o("instance.heartbeats")&&(0,t.jsx)(si,{to:"/company/settings/instance/heartbeats",label:"Heartbeats",icon:Yd,end:!0}),o("company.export")&&(0,t.jsx)(si,{to:"/company/export",label:"Export",icon:po}),!c&&o("company.import")&&(0,t.jsx)(si,{to:"/company/import",label:"Import",icon:py,end:!0}),o("instance.experimental")&&(0,t.jsx)(si,{to:"/company/settings/instance/experimental",label:"Experimental",icon:Dm}),l&&(0,t.jsx)(si,{to:"/company/settings/instance/plugins",label:"Plugins",icon:Xx}),l&&p.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:p.map(f=>(0,t.jsx)(ub,{to:`${ep}/plugins/${f.id}`,state:Gf,className:r(({isActive:x})=>["rounded-md px-2 py-1.5 text-xs transition-colors",x?"bg-accent text-foreground":"text-muted-foreground hover:bg-accent/50 hover:text-foreground"].join(" "),"className"),children:f.manifestJson.displayName??f.packageName},f.id))}):null,o("instance.adapters")&&(0,t.jsx)(si,{to:"/company/settings/instance/adapters",label:"Adapters",icon:ym})]})})]})}r(Slt,"CompanySettingsSidebar");function Clt(){const{pathname:e}=na(),{selectedCompany:s}=ps(),{isMobile:n,setSidebarOpen:a}=qa(),i=yje(),{enabled:o}=OM(),l=h9.filter(d=>!vje(d.key)||o);if(e.endsWith("/apps/chat/connect"))return(0,t.jsx)(W7,{});const c=e.match(/\/apps\/chat\/([^/]+)(?:\/(?:settings|access|reviews|conversations|activity|approvals|audit))?\/?$/);return c?(0,t.jsx)(bje,{endpointId:c[1],NavItem:si}):(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)(Ke,{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)(Uu,{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)(aX,{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)(si,{to:"/apps",label:"Browse",icon:f_,end:!0}),(0,t.jsx)(si,{to:"/apps/review",label:"Review",icon:QN,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)(si,{to:"/apps/connections",label:"Connections",icon:aX,end:!0}),l.map(d=>(0,t.jsx)(si,{to:L0(d.key),label:d.label,icon:d.icon,end:!0},d.key))]})]})]})}r(Clt,"AppsSidebar");function Ase(e){const{selectedCompanyId:s}=ps(),{isMobile:n,setSidebarOpen:a}=qa(),i=Z({queryKey:P.tools.connection(e.kind==="connection"?e.connectionId:"__none__"),queryFn:r(()=>Zt.getConnection(e.kind==="connection"?e.connectionId:""),"queryFn"),enabled:e.kind==="connection"&&!!e.connectionId}),o=Z({queryKey:P.tools.applications(s??"__none__"),queryFn:r(()=>Zt.listApplications(s),"queryFn"),enabled:e.kind==="application"&&!!s}),l=Z({queryKey:P.tools.connections(s??"__none__"),queryFn:r(()=>Zt.listConnections(s),"queryFn"),enabled:e.kind==="application"&&!!s}),c=Z({queryKey:P.apps.gallery(s??"__none__"),queryFn:r(()=>Zt.listGallery(s),"queryFn"),enabled:!!s}),d=Z({queryKey:P.apps.attention(s??"__none__"),queryFn:r(()=>Zt.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=Alt(e.kind==="application"?(l.data?.connections??[]).filter(N=>N.applicationId===e.applicationId):[]),f=u?Lf(u):h?.name??"App",x=Ilt(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)(Ke,{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)(Uu,{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)(al,{name:f,logoUrl:tA(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:FM.map(N=>(0,t.jsx)(si,{to:_lt(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(Ase,"AppDetailSidebar");function _lt(e,s){return e.kind==="connection"?vm(e.connectionId,s):S1(e.applicationId,s)}r(_lt,"tabHref");function Ilt(e,s,n){if(n?.applicationKey){const i=e.find(o=>mc(o)===n.applicationKey);if(i)return i}const a=(s?.name??n?.name)?.toLowerCase();return a?e.find(i=>tg(i).toLowerCase()===a)??e.find(i=>mc(i)===a)??null:null}r(Ilt,"galleryEntryFor$1");function Alt(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(Alt,"latestArchivedConnection$1");function nO({identifier:e}){return e?(0,t.jsx)("span",{className:"shrink-0 font-mono text-muted-foreground",children:e}):null}r(nO,"CrumbIdentifier");function Tlt({context:e}){const{slots:s}=bd({slotTypes:["globalToolbarButton"],companyId:e.companyId}),{launchers:n}=d9({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)(Sp,{slotTypes:["globalToolbarButton"],context:e,className:"flex items-center gap-1"}):null,n.length>0?(0,t.jsx)(XN,{placementZones:["globalToolbarButton"],context:e,className:"flex items-center gap-1"}):null]})}r(Tlt,"GlobalToolbar");function Rlt(){const{breadcrumbs:e,mobileToolbar:s}=Bn(),{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)(Tlt,{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)(L,{variant:"ghost",size:"icon-sm",className:"mr-2 shrink-0",onClick:n,"aria-label":"Open sidebar",children:(0,t.jsx)(Q0e,{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)(nO,{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)(p9,{className:"min-w-0 overflow-hidden",children:(0,t.jsx)(f9,{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)(t5,{}),(0,t.jsx)(C1,{className:p?"min-w-0":"shrink-0",children:p||!u.href?u.leading||u.identifier?(0,t.jsxs)(w_,{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)(nO,{identifier:u.identifier}),(0,t.jsx)("span",{className:"truncate",children:u.label})]}):(0,t.jsx)(w_,{className:"truncate",children:u.label}):(0,t.jsx)(e5,{asChild:!0,children:u.leading||u.identifier?(0,t.jsxs)(Ke,{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)(nO,{identifier:u.identifier}),(0,t.jsx)("span",{className:"truncate",children:u.label})]}):(0,t.jsx)(Ke,{to:u.href,onClick:u.onClick,children:u.label})})})]},h)})})})}),c]})}r(Rlt,"BreadcrumbBar");var Z2=240,j6=208,w6=420,Tse=16;function B5(e){return Math.min(w6,Math.max(j6,e))}r(B5,"clampSidebarWidth");function Rse(e){if(typeof window>"u")return Z2;try{const s=window.localStorage.getItem(e);if(!s)return Z2;const n=Number.parseInt(s,10);return Number.isFinite(n)?B5(n):Z2}catch{return Z2}}r(Rse,"readStoredSidebarWidth");function Ese(e,s){if(!(typeof window>"u"))try{window.localStorage.setItem(e,String(B5(s)))}catch{}}r(Ese,"writeStoredSidebarWidth");function Elt({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)(()=>Rse(o)),[x,b]=(0,m.useState)(!1),v=(0,m.useRef)(p),j=(0,m.useRef)(null);(0,m.useEffect)(()=>{const E=Rse(o);v.current=E,f(E)},[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,I=(0,m.useMemo)(()=>({width:`${w}px`}),[w]),R=(0,m.useMemo)(()=>({width:`${k}px`}),[k]),T=(0,m.useCallback)(E=>{const z=B5(E);v.current=z,f(z),Ese(o,z)},[o]),A=(0,m.useCallback)(E=>{C&&(E.preventDefault(),E.currentTarget.setPointerCapture(E.pointerId),j.current={startX:E.clientX,startWidth:v.current},b(!0))},[C]),D=(0,m.useCallback)(E=>{if(!j.current)return;const z=B5(j.current.startWidth+E.clientX-j.current.startX);v.current=z,f(z)},[]),M=(0,m.useCallback)(()=>{j.current&&(j.current=null,b(!1),Ese(o,v.current))},[o]),B=(0,m.useCallback)(E=>{C&&(E.key==="ArrowLeft"?(E.preventDefault(),T(p-Tse)):E.key==="ArrowRight"?(E.preventDefault(),T(p+Tse)):E.key==="Home"?(E.preventDefault(),T(j6)):E.key==="End"&&(E.preventDefault(),T(w6)))},[C,T,p]);return(0,t.jsx)("div",{className:W("relative h-full shrink-0",l),style:I,children:(0,t.jsxs)("div",{className:W("absolute inset-y-0 left-0 flex flex-col overflow-hidden",S?"z-30 border-r border-border bg-background shadow-lg":"z-0"),style:R,"data-sidebar-overlay":S?"":void 0,onMouseEnter:c,onMouseLeave:d,onFocusCapture:u,onBlurCapture:h,children:[e,C?(0,t.jsx)("div",{role:"separator","aria-label":"Resize sidebar","aria-orientation":"vertical","aria-valuemin":j6,"aria-valuemax":w6,"aria-valuenow":p,tabIndex:0,className:W("absolute inset-y-0 right-0 z-20 w-3 cursor-col-resize touch-none outline-none","before:absolute before:inset-y-0 before:left-1/2 before:w-px before:-translate-x-1/2 before:bg-transparent before:transition-colors","hover:before:bg-border focus-visible:before:bg-ring",x&&"before:bg-ring"),onPointerDown:A,onPointerMove:D,onPointerUp:M,onPointerCancel:M,onLostPointerCapture:M,onKeyDown:B}):null]})})}r(Elt,"SidebarShell");function Plt({children:e,className:s}){return(0,t.jsx)("div",{"data-secondary-sidebar":"",className:W("h-full w-60 shrink-0 overflow-y-auto border-r border-border bg-background",s),children:(0,t.jsx)(clt,{children:e})})}r(Plt,"SecondarySidebar");var Mlt="/company/settings/members?tab=invites",Dlt="https://docs.paperclip.ing/",Llt="https://paperclip.ing/feedback";function $lt(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($lt,"deriveInitials$1");function Pse({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)(Ke,{to:i,className:c,onClick:a,children:d}):(0,t.jsx)("button",{type:"button",className:c,onClick:a,children:d})}r(Pse,"MenuAction");function Mse({deploymentMode:e,open:s,onOpenChange:n}){const i=!!$c(),{hidden:o,loaded:l}=eu(),c=wCe(),d=kCe(!i),u=i?c:d?Mlt:null,h=l&&u!==null&&!cg(o,"company.members")&&!cg(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=NCe(w),S=n??f,{data:C}=Z({queryKey:P.auth.session,queryFn:r(()=>Oa.getSession(),"queryFn"),retry:!1}),I=ZN({onSignedOut:M}),R=C?.user.name?.trim()||"Board",T=C?.user.email?.trim()||(e==="authenticated"?"Signed in":"Local workspace board"),A=$lt(R),D=SCe(C?.user);function M(){S(!1),x&&b(!1)}r(M,"closeNavigationChrome");function B(){I.mutate()}return r(B,"handleSignOut"),(0,t.jsx)("div",{className:"border-t border-r border-border bg-background px-3 py-2",children:(0,t.jsxs)("div",{className:W("flex items-center gap-0.5",!N&&"px-2"),children:[(0,t.jsxs)(gr,{open:w,onOpenChange:S,children:[(0,t.jsx)(Sr,{asChild:!0,children:(0,t.jsxs)("button",{type:"button",className:W("flex min-w-0 items-center gap-2.5 rounded-lg text-left text-(length:--text-compact) font-medium text-foreground/80 transition-colors hover:bg-accent/50 hover:text-foreground",N?"w-full px-3 py-2":"flex-1 px-2 py-1.5"),"aria-label":"Open account menu",children:[(0,t.jsxs)(Mo,{size:"sm",children:[C?.user.image?(0,t.jsx)(xd,{src:C.user.image,alt:R}):null,(0,t.jsx)(Do,{children:A})]}),(0,t.jsx)("span",{className:W("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)(dr,{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)(Ke,{to:D,"aria-label":"View profile",onClick:M,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)(Mo,{size:"lg",children:[C?.user.image?(0,t.jsx)(xd,{src:C.user.image,alt:R}):null,(0,t.jsx)(Do,{children:A})]})}),(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:T}),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)(Pse,{label:"Invite",description:"Invite people to your organization.",icon:Hf,href:u,topLevel:i,onClick:M}):null,(0,t.jsx)(Pse,{label:"Documentation",description:"Open Paperclip docs in a new tab.",icon:HN,href:Dlt,external:!0,onClick:r(()=>S(!1),"onClick")}),(0,t.jsx)(yk,{variant:"menu-action",onAfterToggle:r(()=>S(!1),"onAfterToggle")}),(0,t.jsx)(ICe,{variant:"menu-action",onAfterAction:r(()=>S(!1),"onAfterAction")}),e==="authenticated"?(0,t.jsxs)("button",{type:"button",className:W("flex w-full items-start gap-3 rounded-xl px-3 py-3 text-left transition-colors hover:bg-destructive/10",I.isPending&&"cursor-not-allowed opacity-60"),onClick:B,disabled:I.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)(Tp,{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:I.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)(ACe,{})]})]})]})]}),!N&&!i?(0,t.jsxs)(zn,{children:[(0,t.jsx)(qn,{asChild:!0,children:(0,t.jsx)("a",{href:Llt,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)(Cg,{className:"h-4 w-4","aria-hidden":"true"})})}),(0,t.jsx)(Un,{side:"top",children:"Share feedback"})]}):null]})})}r(Mse,"SidebarAccountMenu");function Olt(e,s){return qCe(e,s)[0]?.toLowerCase()??null}r(Olt,"getCompanyRouteSegment");function qCe(e,s){if(!s)return[];const n=e.split("/").filter(Boolean);return n.length<2?[]:n[0]?.toUpperCase()!==s.toUpperCase()?[]:n.slice(1)}r(qCe,"getCompanyPathSegments");var Flt=new Set(["browse","connections","connect","chat","review","attention","gateways","advanced","app"]);function Blt(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(Blt,"isSkillsStoreRoute");function zlt(){const{sidebarOpen:e,setSidebarOpen:s,toggleSidebar:n,collapsed:a,peeking:i,setPeeking:o,isMobile:l,setForceCollapsed:c}=qa(),{openNewIssue:d,openOnboarding:u}=Qo(),{togglePanelVisible:h}=Yf(),p=Xc()?.pushToast??null,{companies:f,loading:x,selectedCompany:b,selectedCompanyId:v,selectionSource:j,setSelectedCompanyId:N}=ps(),{companyPrefix:w,pluginRoutePath:k}=va(),S=Mn(),C=na(),I=dM(),R=pje(C.pathname,w).isTaskDetail,T=["/company/settings","/company/export","/company/import"].some(vt=>C.pathname.includes(vt)),A=qCe(C.pathname,w),D=A[0]?.toLowerCase()==="tools",M=A[0]?.toLowerCase()==="apps",B=M&&A[1]&&!Flt.has(A[1].toLowerCase())?A[1]:null,E=M&&A[1]?.toLowerCase()==="app"&&A[2]?A[2]:null,z=Blt(C.pathname,w),$=(0,m.useRef)(!1),q=(0,m.useRef)(null),U=(0,m.useRef)(null),O=(0,m.useRef)(new rye),K=(0,m.useRef)(C.key),H=DCe(l&&!R,C.pathname),[ee,se]=(0,m.useState)(!1),ne=(0,m.useMemo)(()=>{if(!w)return null;const vt=w.toUpperCase();return f.find(Le=>Le.issuePrefix.toUpperCase()===vt)??null},[f,w]),fe=!!w&&!x&&f.length>0&&!ne,X=(0,m.useMemo)(()=>k?.toLowerCase()??Olt(C.pathname,w),[w,C.pathname,k]),re=ne?.id??null,oe=ne?.issuePrefix??null,{slots:G}=bd({slotTypes:["page","routeSidebar"],companyId:re,enabled:!!(re&&X)}),Y=(0,m.useMemo)(()=>s9(G,X),[X,G]),Q=(0,m.useMemo)(()=>({companyId:re,companyPrefix:oe}),[re,oe]),te=T?(0,t.jsx)(Slt,{}):B?(0,t.jsx)(Ase,{kind:"connection",connectionId:B}):E?(0,t.jsx)(Ase,{kind:"application",applicationId:E}):M||D?(0,t.jsx)(Clt,{}):Y?(0,t.jsx)(Wu,{slot:Y,context:Q,className:"h-full w-full",missingBehavior:"placeholder"}):null,ae=te!=null,{data:le}=Z({queryKey:P.health,queryFn:r(()=>tu.get(),"queryFn"),retry:!1,refetchInterval:r(vt=>vt.state.data?.devServer?.enabled?2e3:!1,"refetchInterval"),refetchIntervalInBackground:!1}),he=ae||z;(0,m.useLayoutEffect)(()=>(c(he),()=>c(!1)),[he,c]),(0,m.useEffect)(()=>{x||$.current||le?.deploymentMode!=="authenticated"&&(le?.cloud||f.length===0&&($.current=!0,u()))},[f,x,u,le?.cloud,le?.deploymentMode]),(0,m.useEffect)(()=>{if(!w||x||f.length===0)return;if(!ne){const Le=(v?f.find(Qe=>Qe.id===v):null)??f[0]??null;Le&&v!==Le.id&&N(Le.id,{source:"route_sync"});return}if(w!==ne.issuePrefix){const Le=C.pathname.replace(/^\/[^/]+/,"");S(`/${ne.issuePrefix}${Le}${C.search}`,{replace:!0});return}const vt=LCe({matchedCompany:ne,selectedCompanyId:v,companies:f});if(vt){p?.({title:`${ne.name} is archived`,body:`Switched to ${vt.name}.`,tone:"info",dedupeKey:`archived-company-bounce:${ne.id}`}),N(vt.id,{source:"route_sync"}),S(`/${vt.issuePrefix}/dashboard`,{replace:!0});return}$Ce({selectionSource:j,selectedCompanyId:v,routeCompanyId:ne.id})&&N(ne.id,{source:"route_sync"})},[w,f,x,ne,C.pathname,C.search,S,p,j,v,N]);const ce=h,ge=(0,m.useCallback)(()=>{document.dispatchEvent(new KeyboardEvent("keydown",{key:"k",metaKey:!0,bubbles:!0,cancelable:!0}))},[]),me=(0,m.useRef)(null),ie=(0,m.useRef)(!1),ue=(0,m.useRef)(!1),ke=(0,m.useCallback)(()=>{me.current!==null&&(window.clearTimeout(me.current),me.current=null)},[]),be=(0,m.useCallback)(()=>{ke(),me.current=window.setTimeout(()=>o(!0),50)},[ke,o]),Ie=(0,m.useCallback)(()=>{ke(),o(!0)},[ke,o]),Ue=(0,m.useCallback)(()=>{ke(),me.current=window.setTimeout(()=>o(!1),120)},[ke,o]),at=(0,m.useCallback)(()=>{ie.current=!0,a&&!ue.current&&be()},[a,be]),dt=(0,m.useCallback)(()=>{ie.current=!1,ue.current=!1,Ue()},[Ue]),de=(0,m.useCallback)(()=>{ue.current||Ie()},[Ie]),Be=(0,m.useCallback)(()=>{ie.current||Ue()},[Ue]);(0,m.useEffect)(()=>ke,[ke]);const pt=(0,m.useRef)(a);return(0,m.useEffect)(()=>{a!==pt.current&&(a?(ke(),o(!1),ue.current=ie.current):ue.current=!1,pt.current=a)},[a,ke,o]),(0,m.useEffect)(()=>{if(!i)return;const vt=r(Le=>{Le.key==="Escape"&&(ke(),o(!1))},"onKeyDown");return window.addEventListener("keydown",vt),()=>window.removeEventListener("keydown",vt)},[i,ke,o]),MCe(),TCe({onNewIssue:r(()=>d(),"onNewIssue"),onSearch:ge,onToggleSidebar:n,onTogglePanel:ce,onShowShortcuts:r(()=>se(!0),"onShowShortcuts"),onGoToInbox:r(()=>S("/inbox"),"onGoToInbox")}),(0,m.useEffect)(()=>{if(!l)return;const vt=30,Le=50,Qe=75;let ut=0,Ye=0;const it=r(tt=>{const Pe=tt.touches[0];ut=Pe.clientX,Ye=Pe.clientY},"onTouchStart"),kt=r(tt=>{const Pe=tt.changedTouches[0],Ce=Pe.clientX-ut;if(!(Math.abs(Pe.clientY-Ye)>Qe)){if(!e&&ut<vt&&Ce>Le){s(!0);return}e&&Ce<-50&&s(!1)}},"onTouchEnd");return document.addEventListener("touchstart",it,{passive:!0}),document.addEventListener("touchend",kt,{passive:!0}),()=>{document.removeEventListener("touchstart",it),document.removeEventListener("touchend",kt)}},[l,e,s]),(0,m.useEffect)(()=>{const vt=document.body.style.overflow;return document.body.style.overflow=l?"visible":"clip",()=>{document.body.style.overflow=vt}},[l]),(0,m.useEffect)(()=>{if(!l)return FCe()},[l]),(0,m.useEffect)(()=>{if(typeof document>"u")return;const vt=U.current;return OCe(vt)},[C.pathname]),(0,m.useEffect)(()=>{const vt=U.current;if(!vt)return;const Le=r(()=>{O.current.remember(K.current,vt.scrollTop)},"recordScroll");return vt.addEventListener("scroll",Le,{passive:!0}),()=>vt.removeEventListener("scroll",Le)},[]),(0,m.useLayoutEffect)(()=>{const vt=U.current,Le=nye({previousPathname:q.current,pathname:C.pathname,navigationType:I,state:C.state});q.current=C.pathname;const Qe=I==="POP",ut=Qe?O.current.recall(C.key):0;if(K.current=C.key,Qe){V3(vt,ut);const Ye=requestAnimationFrame(()=>V3(vt,ut));return()=>cancelAnimationFrame(Ye)}Le&&aye(vt)},[C.key,C.pathname,C.state,I]),(0,t.jsx)(sye,{children:(0,t.jsxs)("div",{className:W("bg-background text-foreground pt-(--sz-safe-top)",l?"min-h-dvh overflow-x-clip":"flex h-dvh flex-col overflow-clip"),children:[(0,t.jsx)("a",{href:"#main-content",className:"sr-only focus:not-sr-only focus:fixed focus:left-3 focus:top-3 focus:z-(--z-200) focus:rounded-md focus:bg-background focus:px-3 focus:py-2 focus:text-sm focus:font-medium focus:shadow-lg focus:outline-none focus-visible:ring-2 focus-visible:ring-ring",children:"Skip to Main Content"}),(0,t.jsx)(cCe,{}),(0,t.jsx)(dCe,{devServer:le?.devServer}),(0,t.jsxs)("div",{className:W("min-h-0 flex-1",l?"w-full":"flex overflow-clip"),children:[l&&e&&(0,t.jsx)("button",{type:"button",className:"fixed inset-0 z-40 bg-black/50",onClick:r(()=>s(!1),"onClick"),"aria-label":"Close sidebar"}),l?(0,t.jsxs)("div",{className:W("fixed inset-y-0 left-0 z-50 flex flex-col overflow-hidden pt-(--sz-safe-top) transition-transform duration-100 ease-out",e?"translate-x-0":"-translate-x-full"),children:[(0,t.jsx)("div",{className:"flex flex-1 min-h-0 overflow-hidden",children:(0,t.jsx)("div",{className:"w-60 shrink-0 overflow-hidden",children:ae?te:(0,t.jsx)(Ise,{})})}),(0,t.jsx)(Mse,{deploymentMode:le?.deploymentMode})]}):(0,t.jsxs)(Elt,{open:e,collapsed:a,peeking:i,resizable:!0,onPanelMouseEnter:at,onPanelMouseLeave:dt,onPanelFocusCapture:a?de:void 0,onPanelBlurCapture:a?Be:void 0,children:[(0,t.jsx)("div",{className:"flex flex-1 min-h-0",children:(0,t.jsx)(Ise,{})}),(0,t.jsx)(Mse,{deploymentMode:le?.deploymentMode})]}),!l&&ae?(0,t.jsx)(Plt,{children:te}):null,(0,t.jsxs)("div",{className:W("flex min-w-0 flex-col",l?"w-full":"h-full flex-1"),children:[(0,t.jsxs)("div",{className:W(l&&"sticky top-0 z-20 bg-background/95 backdrop-blur supports-[backdrop-filter]:bg-background/85"),children:[(0,t.jsx)(f6,{mobile:l,onNavigateHome:r(()=>S("/dashboard"),"onNavigateHome")}),(0,t.jsx)(Rlt,{}),l&&T?(0,t.jsx)("div",{className:"border-b border-border px-4 pb-3",children:(0,t.jsx)(gje,{})}):null]}),(0,t.jsxs)("div",{className:W(l?"block":"flex flex-1 min-h-0"),children:[(0,t.jsx)("main",{id:"main-content",ref:U,tabIndex:-1,style:l?{"--tc-composer-bottom":"var(--sz-calc-14)"}:void 0,className:W("flex-1 p-4 outline-none md:p-6",l?"overflow-visible pb-(--sz-calc-14)":"overflow-auto [scrollbar-gutter:stable]"),children:fe?(0,t.jsx)(Pu,{scope:"invalid_company_prefix",requestedPrefix:w??b?.issuePrefix}):(0,t.jsx)(pCe,{children:(0,t.jsx)(db,{})})}),(0,t.jsx)(Aje,{})]})]})]}),l&&(0,t.jsx)(lCe,{visible:H}),(0,t.jsx)(Tje,{}),(0,t.jsx)(dwe,{}),(0,t.jsx)(eCe,{}),(0,t.jsx)(nCe,{}),(0,t.jsx)(rCe,{}),(0,t.jsx)(aCe,{open:ee,onOpenChange:se}),(0,t.jsx)(iCe,{}),(0,t.jsx)(oCe,{localTrusted:le?.deploymentMode==="local_trusted"})]})})}r(zlt,"Layout");var Dse=null;function qlt(){return Dse??=new zN,Dse}r(qlt,"getDetachedClient");function Ult(){const e=(0,m.useContext)(SI),{data:s,isFetched:n}=Z({queryKey:P.instance.experimentalSettings,queryFn:r(()=>Nr.getExperimental(),"queryFn"),enabled:e!=null},e??qlt());return e?{enabled:s?.enableConferenceRoomChat===!0,loaded:n}:{enabled:!1,loaded:!0}}r(Ult,"useConferenceRoomChatEnabled");function Klt(){const{enabled:e,loaded:s}=Ult();return s?e?(0,t.jsx)(db,{}):(0,t.jsx)(kn,{to:"/dashboard",replace:!0}):null}r(Klt,"ConferenceRoomChatGate");var Wlt=["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"],Vlt={"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 }"}},Als=Wlt.map(e=>Vlt[e]);function UCe({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)(Ap,{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)(L,{variant:"ghost",size:"sm",onClick:r(()=>n(e.id),"onClick"),children:a?"View session":"Open browser"})]})}r(UCe,"TaskBrowserActivity");function KCe({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)(sqe,{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)(Ke,{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)(io,{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(KCe,"TaskChatProjectCreatedCard");function Hlt({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)(Ef,{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(Hlt,"TaskChatSkillCreatedCard");function Glt(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(Glt,"McpIcon");var Qlt=new Set(["tool","tool call","tool_call","acp_tool"]);function Hd(e){const s=(e??"").trim().toLowerCase().replace(/\s*\((?:pending|in[_ -]?progress|completed|failed|cancelled|canceled)\)$/,"");return!s||Qlt.has(s)}r(Hd,"isGenericToolName");function WW(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(WW,"mcpToolIdentity");function VW(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(VW,"identifierWords");function WCe(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(WCe,"sentenceCase");function jk(e){const s=(e??"").trim();return Hd(s)?"Unnamed tool":WCe(VW(WW(s)?.name??s))}r(jk,"humanizeToolName");var Sd=r((e,s,n)=>({key:e,singular:s,plural:n}),"group"),Ylt={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:Sd("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:Sd("task_operation","task operation","task operations")},task_create:{action:"create",running:"Creating a task",completed:"Created a task",family:"plan",group:Sd("task_operation","task operation","task operations")},task_update:{action:"update",running:"Updating a task",completed:"Updated a task",family:"plan",group:Sd("task_operation","task operation","task operations")},task_list:{action:"list",running:"Listing tasks",completed:"Listed tasks",family:"plan",group:Sd("task_operation","task operation","task operations")},task_get:{action:"read",running:"Reading a task",completed:"Read a task",family:"plan",group:Sd("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:Sd("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"}},Jlt={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:[]},Xlt={read:"read",edit:"update",delete:"delete",move:"move",search:"search",list:"list",execute:"run",think:"think",fetch:"fetch",switch_mode:"switch"};function Zlt(e){return VW(e).join("_")}r(Zlt,"normalizedKey");function ect(e){const s=e[0];if(!s)return null;for(const[n,a]of Object.entries(Jlt))if(a.includes(s))return n;return null}r(ect,"inferredAction");function tct(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(tct,"actionFamily");var sct={terminal:mg,grep:jqe,search:oa,read:HN,edit:kM,web:Kze,plan:Hy,question:Pc,agent:hy,safety:Di,image:GI,wait:Yd,mcp:Glt,other:Ef};function nct(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(nct,"actionCopy");function rct(e){switch(e){case"run":return Sd("command","command","commands");case"read":case"list":return Sd("read","read","reads");case"search":return Sd("search","search","searches");case"update":case"create":case"delete":case"move":return Sd("file_change","file change","file changes");case"start":case"stop":return Sd("delegation","delegation","delegations");case"wait":return Sd("wait","wait","waits");default:return Sd("tool_action","tool action","tool actions")}}r(rct,"defaultSummaryGroup");function act(e){return e==="read"||e==="list"?Sd("paperclip_read","Paperclip read","Paperclip reads"):Sd("task_operation","task operation","task operations")}r(act,"paperclipSummaryGroup");function wy(e){const s=(e.name??"").trim(),n=WW(s),a=(e.namespace??n?.namespace??"").trim(),i=(n?"mcp":e.transport??"builtin").toLowerCase(),o=(n?.name??s).trim(),l=VW(o),c=Zlt(o),d=Ylt[c],u=Xlt[(e.operation??"").trim().toLowerCase()],h=ect(l),p=d?.action??u??h??"other",f=d?"exact":u?"kind":h?"inferred":Hd(o)?"unnamed":"fallback",x=Hd(o)?"Unnamed tool":jk(o),b=/^[A-Za-z][A-Za-z0-9_.:-]*$/.test(o),v=h&&b&&l.length>1?l.slice(1):[],j=v.length?WCe(v).replace(/^./,I=>I.toLowerCase()):void 0,N=d?.running&&d.completed?{running:d.running,completed:d.completed}:p==="other"?Hd(o)?{running:"Running an unnamed tool",completed:"Ran an unnamed tool"}:{running:`Running ${x}`,completed:`Ran ${x}`}:nct(p,d?void 0:j),w=d?.family??tct(p),k=i==="mcp"?"mcp":w,S=a?jk(a):i==="mcp"?"MCP":void 0,C=a.toLowerCase()==="paperclip"?act(p):d?.group??rct(p);return{icon:sct[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(wy,"toolActivityPresentation");function m4(e){const s=wy({name:e});return{family:s.family,icon:s.icon,verbLabel:s.runningLabel}}r(m4,"toolTaxonomy");function ict(e){const s=(e??"").trim().toLowerCase();return s==="thinking"?Jx:s==="responding"||s.startsWith("responding (")?dqe:null}r(ict,"statusLabelIcon");var rO=["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"],aO=["Brewing","Tinkering","Distilling","Deliberating"],Lse=(()=>{const e=[],s=Math.max(rO.length,aO.length);for(let n=0;n<s;n++)n<rO.length&&e.push(rO[n]),n<aO.length&&e.push(aO[n]);return e})(),oct=1e4;function lct(e){const s=(e??"").trim().toLowerCase();return s==="running"||s==="working"}r(lct,"isGenericStatusLabel");function cct(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(cct,"fnv1a");function dct(e,s=0){const n=Math.floor(Math.max(0,s)/oct);return Lse[(cct(e)+n)%Lse.length]}r(dct,"whimsyWord");var uct=[{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}],Tls=Array.from(new Set(uct.map(e=>e.group)));function VCe(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(VCe,"parseCssTimeMs");function mct(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(mct,"elapsedLabel");function hct(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(hct,"liveElapsedLabel");function pct(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(pct,"useLiveElapsedMs");function fct(e,s){return!Number.isFinite(e)||!Number.isFinite(s)||s<=0?0:Math.max(0,Math.round(e/s)-1)}r(fct,"lineScrollOffset");function wE(e){const s=getComputedStyle(document.documentElement).getPropertyValue(e),n=VCe(s);return Number.isFinite(n)?n:0}r(wE,"motionTokenMs");function xct({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(fct(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),wE("--motion-line-scroll"));return()=>{cancelAnimationFrame(p),window.clearTimeout(f)}},[]);const h=l?n?-1:s?-i:0:1;return(0,t.jsx)("span",{className:"tc-line-scroll min-w-0 flex-1","data-testid":"task-chat-live-self-talk","data-streaming":s||void 0,"data-leaving":n||void 0,children:(0,t.jsx)("span",{ref:a,className:W("tc-line-scroll-inner block",!s&&"truncate"),style:{transform:h!==0?`translateY(calc(${h} * 1lh))`:void 0,transition:d&&!n?"none":void 0},children:e})})}r(xct,"LiveSelfTalkLine");function gct(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)},wE("--motion-line-scroll")))},wE("--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=wE("--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(gct,"useHeldSelfTalk");var bct={running:{Icon:rt,spin:!0,tone:"text-(--status-agent-running)"},working:{Icon:rt,spin:!0,tone:"text-(--status-agent-running)"},awaiting_approval:{Icon:QN,spin:!1,tone:"text-primary"},interrupted:{Icon:M7,spin:!1,tone:"text-destructive"},refused:{Icon:jm,spin:!1,tone:"text-destructive"},truncated:{Icon:yqe,spin:!1,tone:"text-(--status-agent-paused)"}};function HCe({item:e,onApprovalDecision:s,chevronOpen:n,onToggle:a}){const{Icon:i,spin:o,tone:l}=bct[e.status],c=e.status==="awaiting_approval",d=e.status==="running"||e.status==="working",u=pct(e.startedAtMs,d),h=gct(d?e.selfTalk:void 0,d),p=mct(e.elapsedMs);if(d){const f=hct(u??e.elapsedMs),x=e.selfTalk!=null,b=e.toolName?m4(e.toolName).icon:x?null:ict(e.label),v=x||lct(e.label)?dct(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)(Rn,{className:W("h-3 w-3 transition-transform",n?"rotate-90":null),"aria-hidden":!0})}):null,(0,t.jsx)("span",{className:"flex h-3.5 w-3.5 shrink-0 items-center justify-center","data-testid":"task-chat-status-dot-slot",children:(0,t.jsx)("span",{"aria-hidden":!0,className:"h-2 w-2 animate-pulse rounded-full bg-(--status-agent-running)"})}),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)(xct,{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:W("tc-enter-status flex flex-col gap-2 rounded-lg border px-3 py-2 text-sm",c?"tc-approval border-primary/40 bg-primary/5":"border-border bg-muted/40"),children:[(0,t.jsxs)("div",{className:"flex min-w-0 items-center gap-2",children:[(0,t.jsx)(i,{className:W("h-4 w-4 shrink-0",l,o&&"animate-spin")}),(0,t.jsx)("span",{className:"min-w-0 truncate font-medium",children:e.label}),(0,t.jsxs)("span",{className:"ml-auto flex shrink-0 items-center gap-2 text-xs text-muted-foreground",children:[p?(0,t.jsx)("span",{children:p}):null,e.tokens?(0,t.jsxs)("span",{children:[e.tokens.used.toLocaleString(),"/",e.tokens.size.toLocaleString()," ctx"]}):null]})]}),e.detail?(0,t.jsx)("p",{className:"text-xs text-muted-foreground",children:e.detail}):null,c&&e.approval?(0,t.jsx)("div",{className:"flex flex-wrap justify-end gap-2 pt-1",children:e.approval.options.map(f=>{const x=f.kind.startsWith("reject");return(0,t.jsx)("button",{type:"button",onClick:r(()=>s?.(f.id),"onClick"),className:W("rounded-md border px-2.5 py-1 text-xs font-medium transition-colors",x?"border-border text-muted-foreground hover:bg-accent/50 hover:text-foreground":"border-primary bg-primary text-primary-foreground hover:bg-primary/90"),children:f.label},f.id)})}):null]})}r(HCe,"TaskChatStatusPill");var Tg=(0,m.createContext)(null);function tj(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(tj,"formatBytes$4");var z5=new Set(["application/octet-stream","binary/octet-stream","application/x-binary"]),vct=[".mp4",".m4v",".webm",".mov",".qt",".quicktime"],yct=[".png",".jpg",".jpeg",".gif",".webp",".avif",".bmp",".ico"],jct=new Set(["application/wasm"]),wct=new Set(["application/zip","application/x-zip","application/x-zip-compressed"]),GCe=new Set(["text/markdown","text/x-markdown","application/markdown","application/x-markdown"]),kct=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"]),Nct=[".csv",".css",".graphql",".htm",".html",".js",".json",".jsx",".log",".markdown",".md",".mdx",".php",".py",".sh",".sql",".toml",".ts",".tsx",".txt",".xml",".yaml",".yml"];function pA(e){return(e??"").toLowerCase().split(";")[0]?.trim()??""}r(pA,"normalizeOutputContentType");function Sct(e){const s=(e??"").trim().toLowerCase();return s?Nct.some(n=>s.endsWith(n)):!1}r(Sct,"hasDocumentLikeFilename");function QCe(e){return wct.has(e)||e.endsWith("+zip")}r(QCe,"isZipContentType");function Cct(e){return e?!!(e.startsWith("text/")||GCe.has(e)||kct.has(e)||e.startsWith("application/")&&(e.endsWith("+json")||e.endsWith("+xml"))):!1}r(Cct,"isDocumentLikeOutputContentType");function _ct(e,s){const n=pA(e);return!n||Cct(n)||z5.has(n)&&Sct(s)?!1:n.startsWith("video/")||n.startsWith("image/")||n==="application/pdf"||jct.has(n)||QCe(n)||z5.has(n)}r(_ct,"isOutputEligibleContentType");function Ict(e){const s=pA(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"}:QCe(s)?{label:"ZIP",tone:"zip"}:s.startsWith("image/")?{label:"IMG",tone:"image"}:GCe.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(Ict,"getOutputFileGlyph");function Vu(e,s){const n=pA(e);if(n.startsWith("video/"))return!0;if(!z5.has(n))return!1;const a=(s??"").trim().toLowerCase();return vct.some(i=>a.endsWith(i))}r(Vu,"isVideoLikeOutput");function ky(e){const s=pA(e);return s.startsWith("image/")&&s!=="image/svg+xml"}r(ky,"isImageContentType");function h4(e,s){const n=pA(e);if(ky(n))return!0;if(n&&!z5.has(n))return!1;const a=(s??"").trim().toLowerCase();return yct.some(i=>a.endsWith(i))}r(h4,"isImageLikeOutput");function $se(e){const s=new Date(e).getTime();return Number.isNaN(s)?0:s}r($se,"toTime");function p4(e){const s=(e??[]).filter(n=>n.type==="artifact"&&n.provider==="paperclip").flatMap(n=>{const a=i$e.safeParse(n.metadata);return a.success&&!_ct(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:$se(a.createdAt)-$se(n.createdAt)),{items:s,primary:s[0]??null,rest:s.slice(1),count:s.length}}r(p4,"getIssueOutputs");function HW(e){return e.metadata?.originalFilename||e.title||"output"}r(HW,"outputFilename");function YCe(e){return new Set(p4(e).items.flatMap(s=>{const n=s.metadata?.attachmentId;return n?[n]:[]}))}r(YCe,"getPromotedOutputAttachmentIds");function Act(e){return e.contentType.toLowerCase().split(";")[0]?.trim()??""}r(Act,"normalizedContentType");function bg(e){return e.originalFilename??e.id}r(bg,"attachmentFilename");function f4(e){return e.openPath??e.contentPath}r(f4,"attachmentOpenPath");function oS(e){return e.downloadPath??`${e.contentPath}?download=1`}r(oS,"attachmentDownloadPath");function JCe(e){const s=Act(e);return h4(s,e.originalFilename)&&!/^image\/hei[cf](?:-sequence)?$/.test(s)}r(JCe,"isImageAttachment$1");function XCe(e){return Vu(e.contentType,e.originalFilename)}r(XCe,"isVideoAttachment");function ZCe(e){return Wpe(e)}r(ZCe,"isMarkdownAttachment");function sj(e){const s=e.contentType.toLowerCase().split(";")[0].trim();return Wpe(e)||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(sj,"isTextAttachment");function e1e(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(e1e,"downloadBlob$1");function Tct(e,s,n){e1e(e,new Blob([s],{type:`${n};charset=utf-8`}))}r(Tct,"downloadTextFile");var iO="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 t1e({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}=Cp(),v=(0,m.useRef)(void 0);(0,m.useEffect)(()=>()=>clearTimeout(v.current),[]);const j=(0,m.useCallback)(async(I,R)=>{c(I),p(null);try{await R(),u(I)}catch(T){u(null),p(T instanceof Error?T.message:"Export failed")}finally{c(null)}clearTimeout(v.current),v.current=setTimeout(()=>{u(null),p(null)},2e3)},[]),N=(0,m.useCallback)(async()=>i??(await Ct.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(I){p(I instanceof Error?I.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:W("flex items-center gap-0.5",o),"data-testid":"document-export-actions",children:[(0,t.jsx)("button",{type:"button",className:iO,disabled:l!==null,"aria-label":"Copy full content",title:k,"data-testid":"document-export-copy",onClick:r(I=>{I.preventDefault(),I.stopPropagation(),w()},"onClick"),children:x?(0,t.jsx)(gs,{"aria-hidden":"true",className:"h-3.5 w-3.5"}):(0,t.jsx)(Ir,{"aria-hidden":"true",className:"h-3.5 w-3.5"})}),(0,t.jsx)("button",{type:"button",className:iO,disabled:l!==null,"aria-label":"Download source",title:S,"data-testid":"document-export-download",onClick:r(I=>{I.preventDefault(),I.stopPropagation(),j("download",async()=>{const R=kBe(a);Tct(eX(n,R),await N(),R==="md"?"text/markdown":"text/plain")})},"onClick"),children:(0,t.jsx)(po,{"aria-hidden":"true",className:"h-3.5 w-3.5"})}),(0,t.jsx)("button",{type:"button",className:iO,disabled:l!==null,"aria-label":"Export to PDF",title:C,"data-testid":"document-export-pdf",onClick:r(I=>{I.preventDefault(),I.stopPropagation(),j("pdf",async()=>{e1e(eX(n,"pdf"),await Ct.getDocumentPdf(e,s))})},"onClick"),children:(0,t.jsx)(eqe,{"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(t1e,"DocumentExportActions");function U_({children:e,className:s}){return(0,t.jsx)("div",{className:W("relative aspect-video w-full overflow-hidden bg-accent/20",s),children:e})}r(U_,"PreviewFrame");function q5({label:e}){return(0,t.jsx)(U_,{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)(Dc,{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(q5,"PlaceholderPreview");function Rct({artifact:e}){const[s,n]=(0,m.useState)(!1);return s||!e.contentPath?(0,t.jsx)(q5,{label:"Image"}):(0,t.jsx)(U_,{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(Rct,"ImagePreview");function Ect({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)(U_,{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)(oo,{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)(U_,{className:"bg-black",children:[(0,t.jsx)("video",{src:e.contentPath,preload:"metadata",muted:!0,playsInline:!0,"data-frame-ready":a?"true":"false",className:W("h-full w-full object-contain transition-opacity",a?"opacity-100":"opacity-0"),onLoadedMetadata:u,onLoadedData:h,onSeeked:c,onError:r(()=>n(!0),"onError")}),(0,t.jsx)("div",{className:"pointer-events-none absolute inset-0 flex items-center justify-center",children:(0,t.jsx)("div",{className:"flex h-11 w-11 items-center justify-center rounded-full bg-black/55",children:(0,t.jsx)(oo,{className:"h-5 w-5 translate-x-0.5 text-white","aria-hidden":"true"})})})]})}r(Ect,"VideoPreview");function Pct({artifact:e}){const s=e.previewText?.trim();return s?(0,t.jsxs)(U_,{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)(q5,{label:e.source==="document"?"Document":"Text"})}r(Pct,"TextPreview");function fA({artifact:e}){switch(e.mediaKind){case"image":return(0,t.jsx)(Rct,{artifact:e},e.contentPath);case"video":return(0,t.jsx)(Ect,{artifact:e},e.contentPath);case"text":case"document":return(0,t.jsx)(Pct,{artifact:e});case"file":return(0,t.jsx)(q5,{label:"File"});default:return(0,t.jsx)(q5,{})}}r(fA,"ArtifactPreview");function Ose({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(Ose,"SecondaryAction");function Mct({artifact:e}){return(0,t.jsxs)(Ke,{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)(fA,{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)(t1e,{issueId:e.issue.id,documentKey:e.documentKey,title:e.title}):null,e.openPath?(0,t.jsx)(Ose,{href:e.openPath,title:"Open file in new tab",children:(0,t.jsx)(Vn,{className:"h-3.5 w-3.5"})}):null,e.downloadPath?(0,t.jsx)(Ose,{href:e.downloadPath,download:!0,title:"Download file",children:(0,t.jsx)(po,{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 ",Ad(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(Mct,"ArtifactCard");var Ql={credentials:r(e=>Te.get(`/companies/${e}/email/connections`),"credentials"),checkAddress:r((e,s,n,a)=>Te.post(`/companies/${e}/email/connections/${s}/check-address`,n,{signal:a}),"checkAddress"),connect:r((e,s)=>Te.post(`/companies/${e}/email/connections`,s),"connect"),inspectSaved:r((e,s)=>Te.post(`/companies/${e}/email/connections/${s}/inspect`,{}),"inspectSaved"),list:r(e=>Te.get(`/companies/${e}/email/inboxes`),"list"),setup:r((e,s)=>Te.post(`/companies/${e}/email/inboxes`,s),"setup"),inspect:r((e,s)=>Te.post(`/companies/${e}/email/inspect`,{apiKey:s}),"inspect"),control:r((e,s)=>Te.post(`/email/inboxes/${e}/control`,{action:s}),"control"),reconnect:r((e,s,n)=>Te.post(`/email/inboxes/${e}/reconnect`,{apiKey:s,receiveMode:n}),"reconnect"),resolve:r((e,s,n,a)=>Te.post(`/companies/${e}/email/deliveries/${s}/resolve`,{outcome:n,providerMessageId:a}),"resolve"),thread:r((e,s)=>Te.get(`/companies/${e}/email/tasks/${s}`),"thread"),send:r((e,s)=>Te.post(`/companies/${e}/email/send`,s),"send")};function s1e(e,s){return Z({queryKey:["email-thread",e,s],queryFn:r(()=>Ql.thread(e,s),"queryFn"),enabled:!!(e&&s)&&!s.startsWith("chat:"),refetchInterval:r(n=>n.state.data===null?!1:3e3,"refetchInterval")})}r(s1e,"useEmailThread");var n1e=(0,m.createContext)(null);function Dct({companyId:e,issueId:s,children:n}){const a=s1e(e,s);return(0,t.jsx)(n1e.Provider,{value:a.data??null,children:n})}r(Dct,"EmailThreadProvider");function r1e(e){const s=(0,m.useContext)(n1e),n=s?.messages.find(a=>a.commentId===e);return n&&s?(0,t.jsx)(a1e,{message:n,publication:s.publications.find(a=>a.providerMessageId===n.providerMessageId),issueId:s.issueId}):null}r(r1e,"useEmailComment");function a1e({message:e,publication:s,issueId:n}){const a=Z({queryKey:["email-attachments",n],queryFn:r(()=>Ct.listAttachments(n),"queryFn"),enabled:e.attachmentIds.length>0});return(0,t.jsxs)("article",{"aria-label":e.direction==="inbound"?"Email received":"Email sent",className:"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)(a7,{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(i=>{const o=a.data?.find(l=>l.id===i);return(0,t.jsxs)("a",{href:`/api/attachments/${i}/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)(Dc,{className:"size-3.5"}),o?.originalFilename??"Open attachment"]},i)})}),(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}`:""]}),a.error&&(0,t.jsx)("p",{role:"alert",className:"text-xs text-destructive",children:"Attachments could not be loaded."})]})}r(a1e,"EmailMessageCard");var Jv=(0,m.createContext)(null);function nj({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=bg(p),x=Vu(p.contentType,p.originalFilename);return(0,t.jsx)(jFe,{open:n,onOpenChange:a,children:(0,t.jsxs)(vFe,{children:[(0,t.jsx)(yFe,{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)(SFe,{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:oS(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)(po,{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)(Fn,{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)(Uu,{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)(Rn,{className:"h-7 w-7"})})})]}),(0,t.jsx)("div",{className:"h-6 shrink-0"})]})]})})}r(nj,"ImageGalleryModal");var GW=(0,m.createContext)(null);function Lct({value:e,children:s}){return(0,t.jsx)(GW.Provider,{value:e,children:s})}r(Lct,"DispositionRecoveryProvider");function $ct(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($ct,"readDispositionRecoverySnapshot");function i1e(e){return $ct(e,(0,m.useContext)(GW)?.issue.activeRecoveryAction)}r(i1e,"useDispositionRecoverySnapshot");function Oct(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(Oct,"dispositionRetryUnavailableReason");function Fct(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(Fct,"descriptionFor");function QW({snapshot:e,createdAt:s,defaultExpanded:n=!1}){const a=(0,m.useContext)(GW),[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=Oct(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?gs:Es;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:W("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}.`:Fct(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)(L,{size:"xs",variant:"outline",disabled:l||!!j,"aria-describedby":j?v:void 0,onClick:r(()=>{S()},"onClick"),children:[l?(0,t.jsx)(rt,{"aria-hidden":"true",className:"size-3 animate-spin motion-reduce:animate-none"}):(0,t.jsx)(Ci,{"aria-hidden":"true",className:"size-3"}),l?"Requesting retry…":"Retry agent"]}):null,(0,t.jsxs)(L,{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:W("size-3",i&&"rotate-180")})]}),s?(0,t.jsx)("time",{dateTime:s,className:"font-mono text-xs text-muted-foreground sm:ml-auto",children:ro(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(QW,"DispositionRecoveryNotice");var o1e={neutral:{container:"border-border bg-muted/35 dark:bg-muted/20",iconWrap:"bg-muted text-foreground/70",icon:Mf,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:Mf,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:ca,iconClass:"text-emerald-700 dark:text-emerald-300",label:"text-emerald-800 dark:text-emerald-200",divider:"border-emerald-300/50 dark:border-emerald-500/30"},warning:{container:"border-amber-300/70 bg-amber-50/80 dark:border-amber-500/30 dark:bg-amber-500/10",iconWrap:"bg-amber-100 text-amber-800 dark:bg-amber-500/20 dark:text-amber-200",icon:Es,iconClass:"text-amber-700 dark:text-amber-300",label:"text-amber-900 dark:text-amber-200",divider:"border-amber-300/60 dark:border-amber-500/30"},danger:{container:"border-red-400/60 bg-red-50/80 dark:border-red-500/35 dark:bg-red-500/10",iconWrap:"bg-red-100 text-red-700 dark:bg-red-500/20 dark:text-red-200",icon:Hk,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 Bct(e){try{return new Date(e).toLocaleString(void 0,{month:"short",day:"numeric",hour:"numeric",minute:"2-digit"})}catch{return e}}r(Bct,"formatTimestamp$1");function zct({row:e,tone:s}){return(0,t.jsxs)("div",{className:"grid grid-cols-(--gtc-8) gap-x-3 gap-y-0.5 px-3 py-1.5 text-xs",children:[(0,t.jsx)("div",{className:"truncate text-(length:--text-micro) font-medium uppercase tracking-(--tracking-label) text-muted-foreground",children:e.label}),(0,t.jsx)("div",{className:"min-w-0 break-words text-foreground/90",children:(()=>{switch(e.kind){case"text":return(0,t.jsx)("span",{children:e.value});case"code":return(0,t.jsx)("code",{className:"rounded bg-muted px-1.5 py-0.5 font-mono text-(length:--text-micro) text-foreground/80",children:e.value});case"issue":{const n=(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)("span",{children:e.identifier}),e.title?(0,t.jsxs)("span",{className:"text-muted-foreground",children:["— ",e.title]}):null]});return e.href?(0,t.jsx)("a",{href:e.href,className:W("inline-flex items-center gap-1 rounded-sm font-medium underline-offset-2 hover:underline",s.label),children:n}):(0,t.jsx)("span",{className:W("inline-flex items-center gap-1 font-medium",s.label),children:n})}case"agent":return e.href?(0,t.jsx)("a",{href:e.href,className:W("inline-flex items-center gap-1 rounded-sm font-medium underline-offset-2 hover:underline",s.label),children:e.name}):(0,t.jsx)("span",{className:W("font-medium",s.label),children:e.name});case"run":{const n=e.runId.length>12?`${e.runId.slice(0,8)}…`:e.runId,a=(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)("code",{className:"rounded bg-muted px-1.5 py-0.5 text-foreground/80",children:n}),e.status?(0,t.jsx)("span",{className:W("font-sans",s.label),children:e.status}):null]});return e.href?(0,t.jsx)("a",{href:e.href,className:"inline-flex items-center gap-2 rounded-sm font-mono text-(length:--text-micro) underline-offset-2 hover:underline",children:a}):(0,t.jsx)("span",{className:"inline-flex items-center gap-2 font-mono text-(length:--text-micro)",children:a})}}})()})]})}r(zct,"MetadataRow$1");function l1e({sections:e,tone:s="neutral"}){const n=o1e[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)(zct,{row:o,tone:n},l))})]},i))})}r(l1e,"SystemNoticeMetadataSections");function YW({tone:e="neutral",label:s,body:n,source:a,metadata:i,detailsDefaultOpen:o=!1,timestamp:l,className:c}){const d=o1e[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:W("relative w-full overflow-hidden rounded-lg border text-sm shadow-(--shadow-extract-8)",d.container,c),children:[(0,t.jsxs)("header",{className:"flex items-start gap-3 px-3 py-2.5 sm:px-4",children:[(0,t.jsx)("span",{className:W("mt-0.5 flex h-7 w-7 shrink-0 items-center justify-center rounded-md",d.iconWrap),"aria-hidden":!0,children:(0,t.jsx)(u,{className:W("h-4 w-4",d.iconClass)})}),(0,t.jsxs)("div",{className:"min-w-0 flex-1",children:[(0,t.jsxs)("div",{className:"flex flex-wrap items-center gap-x-2 gap-y-0.5 text-(length:--text-micro) font-semibold uppercase tracking-(--tracking-eyebrow)",children:[(0,t.jsx)("span",{className:d.label,children: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:Bct(l)})]}):null]}),(0,t.jsx)("div",{className:"mt-1 break-words text-sm leading-6 text-foreground",children:n})]}),x?(0,t.jsxs)("button",{type:"button",onClick:r(()=>p(v=>!v),"onClick"),"aria-expanded":h,"aria-controls":f,className:W("ml-1 inline-flex h-7 shrink-0 items-center gap-1 rounded-md border border-transparent px-2 text-(length:--text-micro) font-medium uppercase tracking-(--tracking-eyebrow) text-muted-foreground transition-(--tp-background-color-border-color-color)","hover:border-border/70 hover:bg-background/70 hover:text-foreground","focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring/50"),children:[(0,t.jsx)("span",{children:h?"Hide details":"Details"}),(0,t.jsx)(nn,{className:W("h-3.5 w-3.5 transition-transform duration-150",h&&"rotate-180")})]}):null]}),x&&h?(0,t.jsx)("div",{id:f,className:W("border-t bg-background/50 dark:bg-background/30",d.divider),children:(0,t.jsx)(l1e,{sections:i,tone:e})}):null]})}r(YW,"SystemNotice");var qct="System update",Uct=80;function Kct(e){const s=e.match(/Latest retry failure: `([^`]+)`/);return s?s[1]:null}r(Kct,"retryFailureCode");function Wct(e){const s=e.match(/Recovery owner: \[([^\]]+)\]\(/)?.[1]?.trim();return s&&s.length>0?s:null}r(Wct,"recoveryOwnerName");function Vct(e){const s=e.split(`
356
356
  `).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<=Uct?a:`${a.slice(0,79).trimEnd()}…`}r(Vct,"firstSentence");function Hct(e){const s=e.presentation?.title?.trim(),n=e.presentation?.tone;if(s)return{title:s,tone:n??"neutral"};const a=e.body??"",i=Kct(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=Wct(a);return{title:o?`Task paused — waiting on ${o}`:"Task paused — waiting on a recovery owner",tone:n??"warning"}}return{title:qct,tone:n??"neutral",detail:Vct(a)}}r(Hct,"humanizeSystemNotice");var Gct={neutral:"System notice",info:"System notice",success:"System notice",warning:"System warning",danger:"System alert"};function Jj(e,s){const n=e.label?.trim();return n&&n.length>0?n:s}r(Jj,"metadataRowText");function Qct(e,s){switch(e.type){case"text":return{kind:"text",label:Jj(e,"Detail"),value:e.text};case"code":return{kind:"code",label:Jj(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:Jj(e,"Task"),identifier:n,href:`/issues/${n}`,title:e.title??void 0}:{kind:"text",label:Jj(e,"Task"),value:e.title??"unknown"}}case"agent_link":{const n=e.name?.trim()||e.agentId.slice(0,8);return{kind:"agent",label:Jj(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:Jj(e,"Run"),runId:e.runId,href:a,status:e.title??void 0}}default:return null}}r(Qct,"mapMetadataRow");function JW(e,s={}){return!e||!Array.isArray(e.sections)?[]:e.sections.map(n=>{const a=n.rows.map(o=>Qct(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(JW,"mapCommentMetadataToSystemNoticeSections");function c1e(e,s){const n=s?.trim();return n&&n.length>0?n:Gct[e]}r(c1e,"systemNoticeLabelForTone");function Yct(e){const s=e.presentation?.tone??"neutral",n=c1e(s,e.presentation?.title),a=!!e.presentation?.detailsDefaultOpen,i=JW(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(Yct,"buildSystemNoticeProps");var Jct={neutral:Mf,info:Mf,success:ca,warning:Es,danger:Hk},Xct={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 Zct({item:e,onTryAgainNoLiveExecutionPath:s,tryAgainNoLiveExecutionPathPending:n=!1}){const a=i1e(e.metadata),i=Rp(),[o,l]=(0,m.useState)(!!e.presentation?.detailsDefaultOpen),c=(0,m.useId)(),{title:d,tone:u,detail:h}=Hct({body:e.text,presentation:e.presentation}),p=JW(e.metadata,{runAgentId:e.runAgentId}),f=!(e.presentation?.kind==="system_notice"&&e.presentation.title?.trim().toLowerCase().startsWith("workspace ready")===!0&&p.some(N=>N.title?.trim().toLowerCase()==="workspace")),x=Jct[u],b=e.createdAtIso?ro(e.createdAtIso):void 0,v=!!s&&(e.presentation?.title?.trim()==="No live execution path"||e.text.toLowerCase().includes("no live execution path")),j=r(()=>{Promise.resolve().then(()=>s?.()).catch(()=>{})},"handleTryAgain");return e.author==="system"&&a?(0,t.jsx)(QW,{snapshot:a,createdAt:e.createdAtIso,defaultExpanded:e.presentation?.detailsDefaultOpen}):(0,t.jsxs)("div",{className:W("tc-enter-bubble flex flex-col items-start",i?"py-0.5":"py-1"),"data-testid":"task-chat-system-notice","data-tone":i?u:void 0,role:i?"group":void 0,"aria-label":i?`System update: ${d}`: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(()=>l(N=>!N),"onClick"),"aria-expanded":o,"aria-controls":c,className:W("flex min-w-0 items-center gap-1.5 rounded-md px-2 py-0.5 text-xs text-muted-foreground","hover:bg-muted/50 hover:text-foreground","focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring/50"),children:[(0,t.jsx)(x,{className:W("h-3.5 w-3.5 shrink-0",Xct[u]),"aria-hidden":!0}),(0,t.jsx)("span",{className:"truncate font-medium",children:d}),h?(0,t.jsxs)("span",{className:"hidden truncate sm:inline",children:["· ",h]}):null,b?(0,t.jsxs)("span",{className:"shrink-0 text-muted-foreground/70",children:["· ",b]}):null,(0,t.jsx)(nn,{className:W("tc-notice-chevron h-3.5 w-3.5 shrink-0 transition-transform",o&&"rotate-180"),"aria-hidden":!0})]}),v&&!o?(0,t.jsx)(L,{type:"button",variant:"outline",size:"xs",onClick:j,disabled:n,"data-testid":"task-chat-no-live-path-try-again",children:n?"Trying again...":"Try again"}):null]}),o?(0,t.jsxs)("div",{id:c,"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:[f?(0,t.jsx)("div",{className:"px-3 py-2.5 text-foreground/90",children:(0,t.jsx)(Sn,{softBreaks:!0,linkIssueReferences:!0,children:e.text})}):null,p.length>0?(0,t.jsx)("div",{className:W("bg-background/50 dark:bg-background/30",f&&"border-t border-border/70"),children:(0,t.jsx)(l1e,{sections:p,tone:u})}):null,v?(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)(L,{type:"button",size:"xs",onClick:j,disabled:n,"data-testid":"task-chat-no-live-path-try-again",children:n?"Trying again...":"Try again"})}):null]}):null]})}r(Zct,"TaskChatSystemNotice");function XW({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)(kr,{agent:n,name:e,size:24})}),(0,t.jsx)("span",{className:"text-sm font-semibold text-foreground",children:e})]})}r(XW,"TaskChatAgentIdentity");function Fse(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(Fse,"galleryItemForMedia");function Bse(e){return e.filter((s,n)=>e.findIndex(a=>s.id&&a.id===s.id||a.url===s.url)===n)}r(Bse,"uniqueAttachmentRefs");function d1e(e){return r1e(e.item.id)??(0,t.jsx)(edt,{...e})}r(d1e,"TaskChatBubble");function edt({item:e,animateEntry:s=!0,queuedAction:n,attachedTurn:a,beforeTurn:i,hideAgentIdentity:o=!1,actions:l,attachments:c=[],onTryAgainNoLiveExecutionPath:d,tryAgainNoLiveExecutionPathPending:u}){const h=Rp(),p=(0,m.useContext)(Tg),f=(0,m.useContext)(Jv),[x,b]=(0,m.useState)(null),v=(0,m.useCallback)(z=>{f?.(z)||b(z)},[f]);if(e.interstitial)return null;if(e.author==="system")return(0,t.jsx)(Zct,{item:e,onTryAgainNoLiveExecutionPath:d,tryAgainNoLiveExecutionPathPending:u});const j=e.author==="human",N=j&&e.sourceChannel==="imessage-photon",{refs:w,text:k}=MVe(e.text),S=EVe(k),C=PVe(k),I=SZ(w,c),R=SZ(S,c),T=c.filter(z=>z.issueCommentId===e.id).map(z=>({id:z.id,name:z.originalFilename?.trim()||"attachment",url:z.contentPath,contentType:z.contentType,byteSize:z.byteSize,openPath:z.openPath,downloadPath:z.downloadPath})),A=Bse([...R,...I.filter(M2),...T.filter(M2)]),D=Bse([...I.filter(z=>!M2(z)),...T.filter(z=>!M2(z))]),M=[...A,...D.filter(z=>Vu(z.contentType,z.name))],B=x!==null&&!M.some(z=>z.url===x)?[Fse(x)]:M.map(z=>Fse(z.url,z.name,z)),E=x===null?-1:Math.max(0,M.findIndex(z=>z.url===x));return(0,t.jsxs)("div",{className:W("flex w-full flex-col gap-1",s&&"tc-enter-bubble",j?"items-end":"items-start"),children:[i?(0,t.jsx)("div",{className:"w-full pb-1",children:i}):null,!j&&e.authorName&&!o?(0,t.jsx)(XW,{agentName:e.authorName,agentIcon:e.agentIcon,agent:e.agent}):null,C.length>0?(0,t.jsx)("div",{"data-testid":j?"task-chat-human-bubble":"task-chat-agent-bubble",className:W("break-words py-2 text-sm",j?"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)(Sn,{className:j?"paperclip-markdown-on-accent":void 0,softBreaks:!0,linkIssueReferences:!0,onImageClick:v,children:C})}):null,A.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 · ",A.length]}),(0,t.jsxs)("div",{className:"grid grid-cols-4 gap-2",children:[A.slice(0,A.length>4?3:4).map((z,$)=>(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 ${z.name||`image ${$+1}`}`,onClick:r(()=>v(z.url),"onClick"),children:(0,t.jsx)("img",{src:z.openPath??z.url,alt:z.name,loading:"lazy",className:"h-full w-full object-cover transition-transform group-hover:scale-(--s-1_02)"})},z.url)),A.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 ${A.length-3} more screenshots`,onClick:r(()=>v(A[3].url),"onClick"),children:["+",A.length-3]}):null]}),(0,t.jsx)("span",{className:"truncate text-xs text-muted-foreground",children:A.map(z=>z.name||"image").join(" · ")})]}):null,D.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 · ",D.length]}),(0,t.jsx)(A9,{"data-testid":"task-chat-bubble-attachments",children:D.map(z=>{const $=Xje(z),q=$.icon,U=T9(z.byteSize),O=Vu(z.contentType,z.name);return(0,t.jsxs)(N9,{size:"sm",children:[(0,t.jsx)(S9,{className:O?"aspect-video group-data-[size=sm]/attachment:w-20":void 0,children:O?(0,t.jsx)(fA,{artifact:{title:z.name,contentPath:z.openPath??z.url,mediaKind:"video"}}):(0,t.jsx)(q,{"aria-hidden":!0})}),(0,t.jsxs)(C9,{children:[(0,t.jsx)(_9,{className:"max-w-48",children:z.name}),(0,t.jsx)(I9,{className:"max-w-48",children:U?`${$.label} · ${U}`:$.label})]}),(0,t.jsx)(Gje,{"aria-label":`Open ${z.name}`,onClick:O?()=>v(z.url):void 0,render:O?(0,t.jsx)("button",{type:"button"}):(0,t.jsx)("a",{href:z.openPath??z.url,onClick:r(K=>{p&&z.id&&sj({contentType:z.contentType??"",originalFilename:z.name})&&!K.metaKey&&!K.ctrlKey&&!K.shiftKey&&!K.altKey&&(K.preventDefault(),p(z.id,z.name))},"onClick"),target:"_blank",rel:"noreferrer"})})]},z.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((z,$)=>(0,t.jsxs)("li",{children:[(0,t.jsx)("span",{className:"font-mono text-foreground",children:z.commandOrCheck}),z.reasonCode?` · ${z.reasonCode.replaceAll("_"," ")}`:"",z.detail?(0,t.jsx)("span",{className:"block",children:z.detail}):null]},`${z.commandOrCheck}:${$}`))})]}):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||N?(0,t.jsxs)("span",{className:"text-(length:--text-micro) text-muted-foreground",children:[N?"Sent from iMessage":null,N&&e.timestamp?" · ":null,e.timestamp]}):null,l]}):(0,t.jsxs)("div",{className:"flex items-center gap-1",children:[l,e.timestamp||N?(0,t.jsxs)("span",{className:"px-1 text-(length:--text-micro) text-muted-foreground",children:[N?"Sent from iMessage":null,N&&e.timestamp?" · ":null,e.timestamp]}):null]}):e.timestamp||N?(0,t.jsxs)("span",{className:"px-1 text-(length:--text-micro) text-muted-foreground",children:[N?"Sent from iMessage":null,N&&e.timestamp?" · ":null,e.timestamp]}):null,x!==null&&E>=0?(0,t.jsx)(nj,{items:B,initialIndex:E,open:!0,onOpenChange:r(z=>{z||b(null)},"onOpenChange")}):null]})}r(edt,"TaskChatBubbleContent");function zse(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(zse,"turnSummaryMetrics");function qse({item:e,renderChild:s,timestampPrefix:n,leading:a}){const i=Rp(),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)(XW,{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)(Sn,{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?Fn:gs,S=e.settled&&(!e.historical||N)?(0,t.jsxs)("button",{type:"button",onClick:r(()=>h(C=>!C),"onClick"),"aria-expanded":u,className:W("group flex w-full items-center gap-2 px-1 text-muted-foreground transition-colors hover:text-foreground",e.standaloneHeader?"border-b border-border/70 py-2 text-sm":"py-0.5 text-xs",i&&"min-w-0"),"data-testid":"task-chat-turn-summary",children:[n?(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)("span",{className:"text-(length:--text-micro)",children:n}),(0,t.jsx)("span",{"aria-hidden":!0,className:"text-(length:--text-micro)",children:"·"})]}):null,!e.standaloneHeader&&!e.historical?(0,t.jsx)(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&&zse(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:zse(e.summary)})}):null,(0,t.jsx)(Rn,{className:W("h-3 w-3 shrink-0 transition-transform",e.standaloneHeader&&"ml-auto",u?"rotate-90":null),"aria-hidden":!0})]}):o?(0,t.jsx)(HCe,{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(qse,"TaskChatTurn");var tdt={session_start:Cu,interrupted:M7,turn_boundary:Cg};function u1e({item:e,onTryAgain:s,tryAgainPending:n=!1}){const[a,i]=(0,m.useState)(!1),o=(0,m.useId)(),l=Rp(),c=e.tone==="neutral"?fb:tdt[e.variant],d=e.variant==="interrupted"&&e.tone!=="neutral",u=e.createdAtIso?ro(e.createdAtIso):void 0,h=r(()=>{Promise.resolve().then(()=>s?.()).catch(()=>{})},"handleTryAgain");return e.collapsible?(0,t.jsxs)("div",{className:"tc-enter-marker flex flex-col items-start py-1 text-xs text-muted-foreground","data-testid":"task-chat-collapsible-marker",children:[(0,t.jsxs)("div",{className:"flex max-w-(--pct-85) items-center gap-1.5",children:[(0,t.jsxs)("button",{type:"button",onClick:r(()=>i(p=>!p),"onClick"),"aria-expanded":a,"aria-controls":o,className:W("flex min-w-0 items-center gap-1.5 rounded-md px-2 py-0.5",d?"text-destructive":"text-muted-foreground","hover:bg-muted/50 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring/50"),children:[(0,t.jsx)(c,{className:"h-3.5 w-3.5 shrink-0","aria-hidden":!0}),(0,t.jsx)("span",{className:"truncate font-medium",children:e.label}),u?(0,t.jsxs)("span",{className:"shrink-0 text-muted-foreground/70",children:["· ",u]}):null,(0,t.jsx)(nn,{className:W("tc-notice-chevron h-3.5 w-3.5 shrink-0 transition-transform",a&&"rotate-180"),"aria-hidden":!0})]}),s&&!a?(0,t.jsx)(L,{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)(L,{asChild:!0,variant:"ghost",size:"xs",children:(0,t.jsx)(Ke,{to:e.planHref,children:"View saved plan"})}):null,e.runHref?(0,t.jsx)(L,{asChild:!0,variant:"ghost",size:"xs",children:(0,t.jsx)(Ke,{to:e.runHref,children:"View run"})}):null,s?(0,t.jsx)(L,{type:"button",size:"xs",onClick:h,disabled:n,"data-testid":"task-chat-run-failed-try-again",children:n?"Trying again...":"Try again"}):null]}):null]}):null]}):(0,t.jsxs)("div",{className:"tc-enter-marker flex items-center gap-2 py-1 text-xs text-muted-foreground",role:l?"separator":void 0,"aria-label":l?e.label:void 0,children:[(0,t.jsx)("span",{className:W("h-px flex-1",d?"border-t border-dashed border-destructive/50":"bg-border")}),(0,t.jsxs)("span",{className:W("flex items-center gap-1.5",d&&"text-destructive"),children:[(0,t.jsx)(c,{className:"h-3.5 w-3.5"}),(0,t.jsx)("span",{className:"font-medium",children:e.label}),e.detail?(0,t.jsxs)("span",{className:"text-muted-foreground",children:["· ",e.detail]}):null,s?(0,t.jsx)(L,{type:"button",variant:"outline",size:"xs",onClick:h,disabled:n,"data-testid":"task-chat-run-failed-try-again",children:n?"Trying again...":"Try again"}):null]}),(0,t.jsx)("span",{className:W("h-px flex-1",d?"border-t border-dashed border-destructive/50":"bg-border")})]})}r(u1e,"TaskChatMarker");var m1e=(0,m.createContext)(null);function ZW(e,s){const n=(0,m.useContext)(m1e),[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(ZW,"useTaskChatExpansion");var sdt={pending:{Icon:rt,spin:!1,tone:"text-muted-foreground"},in_progress:{Icon:rt,spin:!0,tone:"text-(--status-agent-running)"},completed:{Icon:gs,spin:!1,tone:"text-muted-foreground"},failed:{Icon:Fn,spin:!1,tone:"text-destructive"},interrupted:{Icon:Fn,spin:!1,tone:"text-muted-foreground"}};function h1e({item:e}){const{Icon:s,spin:n,tone:a}=sdt[e.status],i=m4(e.rawName??e.name).icon,[o,l]=ZW(e.id,!1),c=!!(e.target||e.detail||e.diff);return(0,t.jsxs)("div",{"data-testid":"task-chat-tool-card",className:"flex min-w-0 max-w-full flex-col text-xs",children:[(0,t.jsxs)("button",{type:"button",onClick:c?()=>l(d=>!d):void 0,"aria-expanded":c?o:void 0,className:W("group/tool -mx-1.5 flex min-h-6 w-full min-w-0 max-w-full items-center gap-2 overflow-hidden rounded-sm px-1.5 py-1 text-left leading-none text-muted-foreground",c?"cursor-pointer transition-colors hover:bg-muted/60 hover:text-foreground":"cursor-default"),children:[(0,t.jsx)("span",{className:"flex w-5 shrink-0 items-center justify-center",children:(0,t.jsx)(i,{className:"h-3.5 w-3.5 shrink-0","aria-hidden":!0,"data-testid":"task-chat-tool-icon"})}),(0,t.jsxs)("span",{className:"flex min-w-0 flex-1 items-baseline gap-2 overflow-hidden",children:[(0,t.jsx)("span",{className:"shrink-0 font-medium leading-4",children:e.name}),e.target?(0,t.jsx)("span",{className:"task-chat-collapsed-line-fade min-w-0 flex-1 font-mono text-(length:--text-micro) leading-4",children:e.target}):null]}),(0,t.jsxs)("span",{className:"ml-auto flex shrink-0 items-center gap-2",children:[e.decision?(0,t.jsxs)("span",{className:W("flex items-center gap-1 text-(length:--text-micro)",e.decision==="allowed"?"text-(--status-task-icon-done)":"text-destructive"),children:[e.decision==="allowed"?(0,t.jsx)(Di,{className:"h-3 w-3"}):(0,t.jsx)(F7,{className:"h-3 w-3"}),e.decision]}):null,c?(0,t.jsx)(Rn,{className:W("h-3 w-3 opacity-0 transition-[opacity,transform] group-hover/tool:opacity-80",o?"rotate-90":null),"aria-hidden":!0}):null,(0,t.jsx)(s,{className:W("h-3.5 w-3.5",a,n&&"animate-spin"),"aria-hidden":!0}),e.status==="interrupted"?(0,t.jsx)("span",{className:"text-(length:--text-micro) text-muted-foreground",children:"Interrupted"}):null]})]}),e.target&&o?(0,t.jsx)("div",{className:"task-chat-expanded-line-wrap ml-1.5 mt-0.5 min-w-0 max-w-full overflow-hidden border-l-2 border-border py-1 pl-2.5 font-mono text-(length:--text-micro) leading-relaxed text-muted-foreground","data-testid":"task-chat-tool-target-detail",children:e.target}):null,e.detail&&o?(0,t.jsx)("pre",{className:"task-chat-expanded-line-wrap ml-1.5 mt-0.5 min-w-0 max-w-full overflow-hidden whitespace-pre-wrap border-l-2 border-border py-1 pl-2.5 font-mono text-(length:--text-micro) leading-relaxed text-muted-foreground",children:e.detail}):null,e.diff&&o?(0,t.jsx)("div",{className:"ml-1.5 mt-0.5 border-l-2 border-border py-1 pl-2.5","data-testid":"task-chat-tool-change-summary",children:(0,t.jsxs)("div",{className:"flex min-w-0 items-center gap-2 text-(length:--text-micro) text-muted-foreground",children:[(0,t.jsx)("span",{className:"shrink-0",children:"Changed"}),e.diff.path?(0,t.jsx)("span",{className:"min-w-0 truncate font-mono text-foreground",children:e.diff.path}):null,(0,t.jsxs)("span",{className:"ml-auto shrink-0 font-mono",children:["+",e.diff.added," −",e.diff.removed]})]})}):null]})}r(h1e,"TaskChatToolCard");function eV({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)(A7,{className:"h-3 w-3"}),e.label?(0,t.jsx)("span",{className:"font-medium",children:e.label}):null,l?(0,t.jsxs)("span",{children:[s.toLocaleString(),"/",l.toLocaleString()," ctx (",c,"%)"]}):null,a!=null||i!=null?(0,t.jsxs)("span",{children:["· ↑",(a??0).toLocaleString()," ↓",(i??0).toLocaleString()]}):null,o!=null?(0,t.jsxs)("span",{children:["· $",o.toFixed(4)]}):null]}),e.detail?(0,t.jsx)("div",{children:e.detail}):null,l?(0,t.jsx)("div",{className:"h-1 w-full overflow-hidden rounded-full bg-border",children:(0,t.jsx)("div",{className:W("h-full rounded-full bg-(--status-agent-running)"),style:{width:`${c}%`}})}):null]})}r(eV,"TaskChatUsageReadout");function Up(e,...s){return e.details.find(n=>s.includes(n.label))?.value}r(Up,"providerDetail");function oO(e){if(!(!e||Hd(e)||/^tool(?:\s+|_)call\b/i.test(e)))return e}r(oO,"meaningfulToolDetail");function ndt(e){const s=e.summary??Up(e,"Query","URL","Target","Name","Reference","Reason","Summary");switch(e.family){case"research":{const n=Up(e,"Action")?.toLowerCase();return n==="open_page"?{icon:oa,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:oa,runningLabel:"Searching the page",completedLabel:"Searched the page",failedLabel:"Page search failed",interruptedLabel:"Page search stopped",detail:s}:{icon:oa,runningLabel:"Searching the web",completedLabel:"Searched the web",failedLabel:"Web search failed",interruptedLabel:"Web search stopped",detail:s}}case"tool_execution":{const n=Up(e,"Name"),a=Up(e,"Target"),i=Up(e,"Progress"),o=wy({name:n,transport:Up(e,"Transport"),namespace:Up(e,"Namespace"),operation:Up(e,"Operation"),target:a,progress:i}),l=oO(e.summary)??oO(i)??oO(a),c=!!(l&&n&&jk(l)===jk(n)),d=n?WW(n)?.name??n:o.displayName,u=o.sourceLabel?`${o.sourceLabel} · ${d}`:n&&!Hd(n)&&jk(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:Hy,runningLabel:"Updating the plan",completedLabel:"Updated the plan",failedLabel:"Plan update failed",interruptedLabel:"Plan update stopped",detail:s};case"delegation":{const n=Up(e,"Action")?.toLowerCase();return n==="message"?{icon:Vo,runningLabel:"Messaging a subagent",completedLabel:"Messaged a subagent",failedLabel:"Subagent message failed",interruptedLabel:"Subagent message stopped",detail:s}:n==="resume"?{icon:Vo,runningLabel:"Resuming a subagent",completedLabel:"Resumed a subagent",failedLabel:"Couldn’t resume the subagent",interruptedLabel:"Subagent resume stopped",detail:s}:n==="close"?{icon:Vo,runningLabel:"Closing a subagent",completedLabel:"Closed a subagent",failedLabel:"Couldn’t close the subagent",interruptedLabel:"Subagent close stopped",detail:s}:n==="wait"?{icon:Vo,runningLabel:"Waiting for subagents",completedLabel:"Finished waiting for subagents",failedLabel:"Subagent wait failed",interruptedLabel:"Stopped waiting for subagents",detail:s}:{icon:Vo,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:so,runningLabel:"Switching models",completedLabel:"Switched models",failedLabel:"Model switch failed",interruptedLabel:"Model switch stopped",detail:s}:{icon:so,runningLabel:"Verifying the model",completedLabel:"Verified the model",failedLabel:"Model verification failed",interruptedLabel:"Model verification stopped",detail:s};case"context":return{icon:EI,runningLabel:"Compacting context",completedLabel:"Compacted context",failedLabel:"Context compaction failed",interruptedLabel:"Context compaction stopped",detail:s};case"artifact":return e.eventType==="artifact.viewed"?{icon:r_,runningLabel:"Viewing an artifact",completedLabel:"Viewed an artifact",failedLabel:"Couldn’t view the artifact",interruptedLabel:"Artifact view stopped",detail:s}:{icon:r_,runningLabel:"Generating an artifact",completedLabel:"Generated an artifact",failedLabel:"Artifact generation failed",interruptedLabel:"Artifact generation stopped",detail:s};case"review":return Up(e,"State")?.toLowerCase()==="exited"?{icon:oX,runningLabel:"Leaving review mode",completedLabel:"Left review mode",failedLabel:"Couldn’t leave review mode",interruptedLabel:"Review-mode change stopped",detail:s}:{icon:oX,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:io,runningLabel:"Running a hook",completedLabel:"Ran a hook",failedLabel:"Hook failed",interruptedLabel:"Hook stopped",detail:s};case"memory":return{icon:HN,runningLabel:"Checking memory",completedLabel:"Referenced memory",failedLabel:"Memory lookup failed",interruptedLabel:"Memory lookup stopped",detail:s};case"safety":return{icon:Di,runningLabel:"Reviewing safety",completedLabel:"Reviewed safety",failedLabel:"Safety review failed",interruptedLabel:"Safety review stopped",detail:s};case"terminal":return{icon:pg,runningLabel:"Sending terminal input",completedLabel:"Sent terminal input",failedLabel:"Terminal input failed",interruptedLabel:"Terminal input stopped",detail:s};case"wait":return{icon:Yd,runningLabel:"Waiting",completedLabel:"Finished waiting",failedLabel:"Wait failed",interruptedLabel:"Wait stopped",detail:s};case"provider_notice":return{icon:Es,runningLabel:"Provider notice",completedLabel:"Provider notice",failedLabel:"Provider error",interruptedLabel:"Provider notice",detail:s}}}r(ndt,"providerActivityPresentation$1");function rdt(e){const s=e.totals.files||e.files.length,n=s>0?`${s} ${s===1?"file":"files"}`:void 0;return{icon:kM,runningLabel:"Editing files",completedLabel:"Edited files",detail:n}}r(rdt,"workspaceChangePresentation");function adt(e){return{icon:Ha,runningLabel:"Referencing a file",completedLabel:"Referenced a file",detail:e.line==null?e.path:`${e.path}:${e.line}`}}r(adt,"workspaceFilePresentation");function idt(e){return{icon:e.resourceKind==="document"?Ha:Gk,runningLabel:"Saving a resource",completedLabel:e.resourceKind==="document"?"Added a document":"Added a deliverable",detail:e.title}}r(idt,"resourcePresentation");function p1e(e){switch(e.surface){case"provider_activity":return ndt(e);case"workspace_change":return rdt(e);case"workspace_file":return adt(e);case"resource":return idt(e);case"runtime_request":case"run_result":case"run_terminal":return null}}r(p1e,"protocolActivityPresentation");function f1e(e){return e.surface==="provider_activity"?e.status==="running":e.surface==="workspace_change"?!e.complete:!1}r(f1e,"protocolActivityIsRunning");function odt(e,s){return e.surface!=="provider_activity"?f1e(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(odt,"protocolActivityLabel");var ldt={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 cdt(e){const s=new Map,n=r((d,u,h=0)=>{const p=s.get(d);(!p||h<p.order)&&s.set(d,{label:d,icon:u,order:h})},"add"),a=[];for(const[d,u]of e.entries())if(u.kind==="tool"){const h=wy({name:u.rawName??u.name,target:u.target});a.push({...h,order:d,completed:u.status==="completed"})}else if(u.kind==="protocol")if(u.surface==="provider_activity"&&u.family==="tool_execution"){const h=r(f=>u.details.find(x=>x.label===f)?.value,"value"),p=wy({name:h("Name"),operation:h("Operation"),transport:h("Transport"),namespace:h("Namespace"),target:h("Target")});a.push({...p,order:d,completed:u.status==="completed"})}else{const h=p1e(u);if(!h)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",provider_notice:"Received a provider update",workspace_change:"Worked on files",workspace_file:"Referenced files",resource:"Added resources"}[u.surface==="provider_activity"?u.family:u.surface]??"Used tools",h.icon,d)}const i=new Set(a.filter(d=>d.completed).map(d=>d.family));for(const d of a){const u=i.has(d.family);n(d.family==="read"&&!u?"Checked files":d.family==="edit"&&!u?"Worked on files":ldt[d.family],d.icon,d.order)}s.size||(e.some(d=>d.kind==="thinking")?n("Thought through the task",Jx):e.some(d=>d.kind==="marker")?n("Activity stopped",Rd):n("Recorded usage",A7));const o=[...s.values()].sort((d,u)=>d.order-u.order),l=r(d=>d.map((u,h)=>h?u.charAt(0).toLowerCase()+u.slice(1):u).join(", "),"join"),c=l(o.map(d=>d.label));return{label:o.length>3?`${l(o.slice(0,2).map(d=>d.label))}, and more`:c,fullLabel:c,icon:o.length===1?o[0].icon:zl}}r(cdt,"completedActivitySummary");var Use=5,ddt=8;function udt(e,s=!1){return s&&(e==="blocked"||e==="failed")?(0,t.jsx)(hg,{className:"h-3 w-3 text-muted-foreground","aria-hidden":!0}):e==="in_progress"?(0,t.jsx)(rt,{className:"h-3 w-3 animate-spin text-(--status-agent-running)","aria-hidden":!0}):e==="completed"?(0,t.jsx)(gs,{className:"h-3 w-3 text-(--status-task-icon-done)","aria-hidden":!0}):e==="blocked"||e==="failed"?(0,t.jsx)(Fn,{className:"h-3 w-3 text-destructive","aria-hidden":!0}):(0,t.jsx)(hg,{className:"h-3 w-3 text-muted-foreground","aria-hidden":!0})}r(udt,"stepStatusIcon");function x1e({details:e}){return e.length===0?null:(0,t.jsx)("dl",{className:"flex min-w-0 flex-col gap-1.5","data-testid":"task-chat-provider-detail-list",children:e.map(s=>(0,t.jsxs)("div",{className:"grid min-w-0 grid-cols-1 gap-0.5 sm:grid-cols-(--gtc-task-chat-details) sm:gap-3",children:[(0,t.jsx)("dt",{className:"text-muted-foreground",children:s.label}),(0,t.jsx)("dd",{className:W("min-w-0 break-words text-foreground",s.mono&&"font-mono"),children:s.value})]},`${s.label}:${s.value}`))})}r(x1e,"DetailList");function mdt(e){try{return new URL(e).hostname.replace(/^www\./,"")}catch{return e}}r(mdt,"sourceHostname");function hdt({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,Use),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)(Vn,{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:mdt(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>Use?(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)(x1e,{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(hdt,"ResearchDetails");function pdt({item:e,neutral:s=!1}){return e.family==="research"?(0,t.jsx)(hdt,{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:udt(n.status,s)}),(0,t.jsx)("span",{className:W("min-w-0",n.status==="completed"&&"text-muted-foreground line-through"),children:n.label})]},n.id))}):null,e.links.length>0?(0,t.jsx)("ul",{className:"flex flex-col gap-1.5","aria-label":"Research sources",children:e.links.map(n=>(0,t.jsxs)("li",{children:[(0,t.jsxs)("a",{className:"inline-flex min-w-0 items-center gap-1 font-medium text-primary hover:underline",href:n.href,target:"_blank",rel:"noreferrer",children:[(0,t.jsx)("span",{className:"truncate",children:n.label}),(0,t.jsx)(Vn,{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)(x1e,{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(pdt,"ProviderDetails");function fdt({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,ddt),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(fdt,"WorkspaceChangeDetails");function xdt({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)(Axe,{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)(Sn,{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(xdt,"WorkspaceFileDetails");function g1e(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)(pdt,{item:e,neutral:s}):null;case"workspace_change":return(0,t.jsx)(fdt,{item:e});case"workspace_file":return(0,t.jsx)(xdt,{item:e});case"resource":case"runtime_request":case"run_result":case"run_terminal":return null}}r(g1e,"detailContent");function b1e(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(b1e,"safeActivityHref");function gdt(e){return e.surface==="resource"?!!b1e(e.href):g1e(e)!==null||e.surface==="provider_activity"&&!!e.summary?.trim()}r(gdt,"hasTaskChatProtocolActivityDetails");function bdt({item:e,neutral:s=!1}){const n=g1e(e,s);if(e.surface==="resource"){const a=b1e(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(bdt,"TaskChatProtocolActivityDetails");function v1e(e,s){if(e.kind==="tool"){const d=wy({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:Jx,label:d?"Thinking":"Thought",target:e.lines.filter(u=>u.trim()).at(-1)?.trim(),mono:!1,running:d}}if(e.kind==="protocol"){const d=p1e(e);return d?{icon:d.icon,label:odt(e,d),target:d.detail,mono:!0,running:s&&f1e(e)}:null}if(e.kind==="marker")return{icon:Rd,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:A7,label:e.label??"Token usage",target:c||e.detail,mono:!1,running:!1}}r(v1e,"presentation");function k6({item:e,active:s}){const n=v1e(e,s);if(!n)return null;const a=n.icon;return(0,t.jsxs)("span",{className:"flex min-w-0 flex-1 items-center gap-2","data-activity-row":e.id,"data-activity-family":e.kind==="protocol"?e.surface==="provider_activity"?e.family:e.surface:void 0,children:[(0,t.jsx)("span",{className:"flex size-5 shrink-0 items-center justify-center","data-activity-icon":!0,children:(0,t.jsx)(a,{className:"size-3.5","aria-hidden":"true"})}),(0,t.jsxs)("span",{className:"flex min-w-0 flex-1 items-center gap-2 overflow-hidden whitespace-nowrap",children:[(0,t.jsx)("span",{className:W("max-w-full shrink-0 truncate text-xs",n.running&&"text-foreground"),children:n.label}),n.target?(0,t.jsx)("span",{title:n.target,className:W("truncate text-xs text-muted-foreground",n.mono&&"font-mono"),children:n.target}):null]})]})}r(k6,"ActivityContent");function vdt({item:e,active:s}){const n=xNe(),[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)(k6,{item:a.previous,active:!1})},`exit-${e.id}`):null,(0,t.jsx)("span",{className:W("relative flex w-full min-w-0 items-center",a.previous&&!n&&"runner-activity-roll-in"),children:(0,t.jsx)(k6,{item:e,active:s})},e.id)]})}r(vdt,"RollingActivity");function ydt({item:e}){return e.kind==="thinking"?(0,t.jsx)(Sn,{softBreaks:!0,children:e.lines.join(`
357
357
  `)}):e.kind==="usage"?(0,t.jsx)(eV,{item:e}):e.kind==="protocol"?(0,t.jsx)(bdt,{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(ydt,"ActivityDetails");function jdt(e){return e.kind==="protocol"?gdt(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(jdt,"hasActivityDetails");function wdt({item:e,active:s}){const[n,a]=ZW(`runner-detail:${e.id}`,!1),i=(0,m.useId)(),o=jdt(e),l=(0,t.jsx)(k6,{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)(Rn,{className:W("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)(ydt,{item:e})}):null]})}r(wdt,"ExpandedActivity");function K_({item:e,defaultExpanded:s=!1}){const[n,a]=ZW(e.id,s),i=(0,m.useId)(),o=e.items.filter(h=>v1e(h,!1)!==null),l=o.at(-1),c=cdt(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)(Sn,{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)(vdt,{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)(Rn,{className:W("size-3.5",n&&"rotate-90"),"aria-hidden":"true"})]})]}),n?(0,t.jsx)("ol",{id:i,className:"flex min-w-0 flex-col gap-1","aria-label":"Activity history","data-testid":"task-chat-runner-activity-list",children:o.map((h,p)=>(0,t.jsx)(wdt,{item:h,active:e.active&&p===o.length-1},h.id))}):null]}):null]})}r(K_,"TaskChatRunnerActivityGroup");var kdt=new Set(["failed","timed_out","cancelled","interrupted","succeeded"]);function Xv(e){return e!=null&&kdt.has(e)}r(Xv,"isTerminalRunStatus$1");function Kse(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(Kse,"splitTranscriptAtAnchors");function Ndt(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(Ndt,"flattenSelfTalk");function Sdt(e){return e==="add"?"add":e==="remove"?"remove":"context"}r(Sdt,"diffKind");var Cdt=["file_path","path","notebook_path","command","pattern","query","url","prompt","description","skill","subject"],QC=96;function w0(e,s){const n=e.replace(/\s+/g," ").trim();return n.length>s?`${n.slice(0,s-1)}…`:n}r(w0,"clip");function _dt(e){if(e==null)return;if(typeof e=="string")return e.trim()?w0(e,QC):void 0;if(typeof e!="object")return w0(String(e),QC);const s=e;for(const a of Cdt){const i=s[a];if(typeof i=="string"&&i.trim())return w0(i,QC)}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 w0(n.map(([a,i])=>`${a}: ${String(i)}`).join(", "),QC)}r(_dt,"summarizeToolInput$2");function lO(e){const s=(e??"").trim();return Hd(s)?"Unnamed tool":jk(s)}r(lO,"toolDisplayName");function Idt(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(Idt,"thoughtDurationLabel");function Adt(e,s,n){const a=s.split(`
358
358
  `);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(Adt,"appendThinkingText");var Wse=600,D1=8192;function eT(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)?e:{}}r(eT,"objectRecord");function zc(e){return typeof e=="string"&&e.trim().length>0?e.trim():void 0}r(zc,"stringValue");function Tdt(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(Tdt,"scalarValue");function Rdt(e){return e.replace(/([a-z0-9])([A-Z])/g,"$1 $2").replaceAll("_"," ").replace(/\b\w/g,s=>s.toUpperCase())}r(Rdt,"titleCaseKey$1");function Edt(e){const s=zc(e);if(!s)return null;try{const n=new URL(s);return n.protocol==="http:"||n.protocol==="https:"?s:null}catch{return null}}r(Edt,"safeHttpHref");var Pdt={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 y1e(e){for(const s of["planId","executionId","researchId","delegationId","routeId","verificationId","compactionId","artifactId","reviewId","hookId","citationId","waitId","noticeId"]){const n=zc(e.payload[s]);if(n)return`${e.family}:${n}`}return`${e.family}:${e.eventType}:${e.ts}`}r(y1e,"providerActivityKey");function Mdt(e,s,n){const a=[];for(const h of Pdt[e.family]){const p=Tdt(e.payload[h]);p&&(e.family==="tool_execution"&&h==="name"&&Hd(p)||e.family==="tool_execution"&&h==="progress"&&!N6(p)||a.push({label:Rdt(h),value:w0(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=eT(h);typeof p.name=="string"&&typeof p.value=="string"&&a.push({label:w0(p.name,160),value:w0(p.value,4e3),mono:!1})}const i=e.family==="plan"&&Array.isArray(e.payload.steps)?e.payload.steps.map(eT).slice(0,256).map((h,p)=>{const f=zc(h.status),x=f==="in_progress"||f==="completed"||f==="blocked"?f:"pending";return{id:zc(h.stepId)??`${s}:plan-step:${p}`,label:zc(h.body)??"Plan step",status:x}}):[],o=e.family==="research"&&Array.isArray(e.payload.sources)?e.payload.sources.map(eT).slice(0,64).flatMap(h=>{const p=Edt(h.url);return p?[{label:zc(h.title)??p,href:p,description:zc(h.snippet)}]:[]}):[],l=e.family==="delegation"&&Array.isArray(e.payload.children)?e.payload.children.map(eT).slice(0,64).map((h,p)=>({id:zc(h.childId)??`${s}:delegation:${p}`,title:zc(h.role)??"Subagent",status:zc(h.status)??"unknown",metadata:[zc(h.model),zc(h.activitySummary)].filter(Boolean).join(" · ")||void 0,summary:zc(h.summary)})):[],c=e.family==="tool_execution"?zc(e.payload.output):void 0,d=e.payload.outputTruncated===!0||!!(c&&c.length>D1),u=e.summary&&e.summary!==e.eventType?e.summary:zc(e.payload.explanation)??zc(e.payload.progress)??zc(e.payload.message)??zc(e.payload.summary);return{id:`${s}:provider:${y1e(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,D1):void 0,outputTruncated:d,transcriptIndex:n}}r(Mdt,"providerActivityItem");function Ud(e,s){return e.details.find(n=>n.label===s)?.value}r(Ud,"providerItemDetail");function N6(e){return!!(e&&!Hd(e)&&!/^tool(?:\s+|_)call\b/i.test(e))}r(N6,"meaningfulProviderToolSummary");function Ddt(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=Ud(s,"Name"),i=Hd(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"&&!N6(l.value)&&n.has("Progress")||n.set(l.label,l);return{...s,id:e.id,summary:N6(s.summary)?s.summary:e.summary,details:[...n.values()]}}r(Ddt,"mergeProviderActivityItem");function Ldt(e){if(e==null)return;const s=(typeof e=="string"?e:String(e)).trim();if(s)return s.length>Wse?`${s.slice(0,Wse)}
@@ -770,7 +770,7 @@ Last resolved: user values resolve per member`;return(0,t.jsxs)("div",{role:"row
770
770
 
771
771
  Review the **original** file.`,markdown:!0,downloadUrl:"data:text/markdown,%23%20Project%20notes"}),(0,t.jsx)(KU,{title:"notes.txt",text:"Plain text stays literal: <example>",markdown:!1,downloadUrl:"data:text/plain,Plain%20text"})]})]}),(0,t.jsxs)(xr,{title:"Connection recovery",children:[(0,t.jsx)(Yn,{title:"Waiting for server",children:(0,t.jsx)(_E,{temporary:!0,retrying:!1,onRetry:r(()=>{},"onRetry")})}),(0,t.jsx)(Yn,{title:"Checking connection",children:(0,t.jsx)(_E,{temporary:!0,retrying:!0,onRetry:r(()=>{},"onRetry")})}),(0,t.jsx)(Yn,{title:"Access check failed",children:(0,t.jsx)(_E,{temporary:!1,retrying:!1,onRetry:r(()=>{},"onRetry")})})]}),(0,t.jsxs)(xr,{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(B=>(0,t.jsx)(Yn,{title:B==="closing-soon"?"Closing soon":B,children:(0,t.jsx)(aEe,{browser:{id:"design-browser",sessionId:"design-session",issueId:"design-task",status:B==="closing-soon"?"idle":B,runStatus:"completed",progress:null,error:null,costCents:15,idleDeadline:new Date(B==="closing-soon"?282e3:6e5).toISOString(),expiresAt:null,createdAt:new Date(0).toISOString()},now:0,onControl:r(()=>{},"onControl"),onReconnect:r(()=>{},"onReconnect"),onResize:r(()=>{},"onResize")})},B))]}),(0,t.jsxs)(xr,{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(B=>(0,t.jsx)(Yn,{title:B,children:(0,t.jsx)(UCe,{browser:{id:`design-${B}`,sessionId:`design-${B}`,issueId:"design-task",status:B,runStatus:"completed",progress:null,error:null,costCents:0,idleDeadline:null,expiresAt:null,createdAt:new Date(0).toISOString()},onOpen:r(()=>{},"onOpen")})},B))]}),(0,t.jsxs)(xr,{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)(A6,{id:"design-image",title:"Launch artwork",contentPath:"/announcement-preview.svg",contentType:"image/svg+xml",originalFilename:"launch.svg",detail:"Image"}),(0,t.jsx)(A6,{id:"design-video",title:"Video preview unavailable",contentPath:"",contentType:"video/mp4",originalFilename:"preview.mp4",detail:"Video"})]})]}),(0,t.jsx)(xr,{title:"AI Connections",children:(0,t.jsx)(mrs,{})}),(0,t.jsxs)(xr,{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)(uk,{status:"needs_setup"}),(0,t.jsx)(uk,{status:"pending_approval"}),(0,t.jsx)(uk,{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(Xrs,"DesignGuide");function Zrs(){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)(NMe,{candidates:e,selected:s,excludedFolders:a,onChange:r((o,l)=>{n(o),i(l)},"onChange")})}r(Zrs,"SkillSourceTreeShowcase");function eas(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(eas,"resolveWorktreeRunExecutionDisplayState");function tas(e){const s=new Date(e);return Number.isNaN(s.getTime())?e:s.toLocaleString(void 0,{dateStyle:"medium",timeStyle:"short"})}r(tas,"formatActivationTimestamp");function g4e(){return(0,t.jsxs)(ct,{variant:"outline",className:"text-muted-foreground",children:[(0,t.jsx)(pd,{"aria-hidden":"true"}),"Managed by Paperclip Cloud"]})}r(g4e,"ManagedByCloudBadge");function vo({title:e,description:s,footnote:n,checked:a,onCheckedChange:i,disabled:o,settingKey:l,managed:c,ariaLabel:d}){const{hidden:u}=eu(),h=c?.managed===!0;return u.has(Hpe(l))?null:(0,t.jsx)(rn,{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)(g4e,{}):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)(ci,{checked:a,onCheckedChange:r(p=>{h||i(p)},"onCheckedChange"),disabled:o||h,"aria-label":d})]})})}r(vo,"ExperimentalToggleCard");function sas(){const{setBreadcrumbs:e}=Bn(),s=Dt(),{hidden:n}=eu(),[a,i]=(0,m.useState)(null);(0,m.useEffect)(()=>{e([{label:"Settings",href:"/company/settings"},{label:"Experimental"}])},[e]);const o=Z({queryKey:P.instance.experimentalSettings,queryFn:r(()=>Nr.getExperimental(),"queryFn")}),l=je({mutationFn:r(async G=>Nr.updateExperimental(G),"mutationFn"),onMutate:r(async G=>{await s.cancelQueries({queryKey:P.instance.experimentalSettings});const Y=s.getQueryData(P.instance.experimentalSettings);return Y&&s.setQueryData(P.instance.experimentalSettings,{...Y,...G}),{previousSettings:Y}},"onMutate"),onSuccess:r(async G=>{i(null),s.setQueryData(P.instance.experimentalSettings,G),await Promise.all([s.invalidateQueries({queryKey:P.instance.experimentalSettings}),s.invalidateQueries({queryKey:P.adapters.all}),s.invalidateQueries({queryKey:["built-in-agents"]}),s.invalidateQueries({queryKey:P.health}),s.invalidateQueries({queryKey:["apps"]})])},"onSuccess"),onError:r((G,Y,Q)=>{Q?.previousSettings&&s.setQueryData(P.instance.experimentalSettings,Q.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=iot(),d=o.data?.managedKeys??{},u=o.data?.enableWorktreeRunExecution===!0,h=d.enableWorktreeRunExecution?.managed===!0,p=eas(o.data,oot()),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,I=o.data?.enableExternalObjects===!0,R=o.data?.enableBuiltInAgents===!0,T=o.data?.enableBetaSkills===!0,A=o.data?.enableSummaries===!0,D=o.data?.enableStatusCards===!0,M=d.enableSummaries?.managed===!0,B=d.enableStatusCards?.managed===!0,E=M&&!A,z=B&&D,$=o.data?.enableDecisions===!0,q=o.data?.enableGoalsSidebarLink===!0,U=o.data?.enableCases===!0,O=o.data?.enableServerInfoDebugView===!0,K=o.data?.enablePaperclipDeveloperMode===!0,H=o.data?.enableSimplifiedEnglishInteractions===!0,ee=o.data?.enableFirstTaskPlanProposal===!0,se=o.data?.enableSmokeLab===!0,ne=o.data?.autoRestartDevServerWhenIdle===!0,fe=r(G=>!n.has(Hpe(G)),"isVisible"),X=c&&fe("enableWorktreeRunExecution"),re=X||["autoRestartDevServerWhenIdle","enableManagedSandboxOnly","enablePaperclipDeveloperMode","enableServerInfoDebugView","enableSmokeLab","enableIssuePlanDecompositions"].some(fe),oe=fe("enableClassicTaskInterface")||fe("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)(Dm,{className:"h-5 w-5 text-muted-foreground"}),(0,t.jsx)("h1",{className:"text-lg font-semibold",children:"Experimental"})]}),(0,t.jsx)("p",{className:"text-sm text-muted-foreground",children:"Opt into features that are still being evaluated before they become default behavior."})]}),(0,t.jsx)("div",{role:"alert",className:"rounded-lg border border-amber-500/30 bg-amber-500/5 px-4 py-3",children:(0,t.jsxs)("div",{className:"flex items-start gap-3",children:[(0,t.jsx)(Es,{className:"mt-0.5 h-4 w-4 shrink-0 text-amber-700"}),(0,t.jsxs)("div",{className:"space-y-1 text-sm",children:[(0,t.jsx)("p",{className:"font-medium text-foreground",children:"Experimental features may break at any time."}),(0,t.jsx)("p",{className:"text-muted-foreground",children:"These features are opt-in and come with no compatibility guarantees. They may change, break, or be removed without notice. Avoid relying on them for critical or production workflows."})]})]})}),a&&(0,t.jsx)("div",{className:"rounded-md border border-destructive/40 bg-destructive/5 px-3 py-2 text-sm text-destructive",children:a}),(0,t.jsxs)("section",{className:"space-y-3","aria-labelledby":"experimental-features-heading",children:[(0,t.jsxs)("div",{className:"space-y-1",children:[(0,t.jsx)("h2",{id:"experimental-features-heading",className:"text-sm font-semibold",children:"Experimental features"}),(0,t.jsx)("p",{className:"text-sm text-muted-foreground",children:"Optional product features that are still being evaluated."})]}),(0,t.jsx)(vo,{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)(vo,{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:T,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)(vo,{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)(vo,{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:U,onCheckedChange:r(G=>l.mutate({enableCases:G}),"onCheckedChange"),disabled:l.isPending,settingKey:"enableCases",managed:d.enableCases,ariaLabel:"Toggle cases experimental setting"}),(0,t.jsx)(vo,{title:"Chat connectors",description:"Connect agents to Slack, GitHub, 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 tools, and other tool connectors stay available.",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)(vo,{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)(vo,{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:$,onCheckedChange:r(G=>l.mutate({enableDecisions:G}),"onCheckedChange"),disabled:l.isPending,settingKey:"enableDecisions",managed:d.enableDecisions,ariaLabel:"Toggle decisions experimental setting"}),(0,t.jsx)(vo,{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)(vo,{title:"Enable External Objects",description:"Detect external URLs in issues and show resolved status for pull requests, tickets, and other referenced work objects.",checked:I,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)(vo,{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)(vo,{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)(vo,{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:ee,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)(vo,{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)(vo,{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)(vo,{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)(vo,{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:H,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)(vo,{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:D,onCheckedChange:r(G=>l.mutate(G?{enableSummaries:!0,enableStatusCards:!0}:{enableStatusCards:!1}),"onCheckedChange"),disabled:l.isPending||E,settingKey:"enableStatusCards",managed:d.enableStatusCards,ariaLabel:"Toggle status cards experimental setting"}),(0,t.jsx)(vo,{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)(vo,{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:A,onCheckedChange:r(G=>l.mutate(G||!D?{enableSummaries:G}:{enableSummaries:!1,enableStatusCards:!1}),"onCheckedChange"),disabled:l.isPending||z,settingKey:"enableSummaries",managed:d.enableSummaries,ariaLabel:"Toggle summaries experimental setting"}),j&&(0,t.jsx)(vo,{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"})]}),re?(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)(vo,{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:ne,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)(vo,{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)(vo,{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)(rn,{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)(g4e,{}):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)(ci,{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)(oo,{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:tas(p.activatedAt)}),"."]})]}):null,p.kind==="fail_closed"?(0,t.jsxs)("div",{className:"flex items-start gap-2 rounded-md border border-amber-500/30 bg-amber-500/5 px-3 py-2 text-sm",children:[(0,t.jsx)(Es,{className:"mt-0.5 h-4 w-4 shrink-0 text-amber-700"}),(0,t.jsxs)("div",{className:"space-y-0.5",children:[(0,t.jsx)("p",{className:"font-medium text-foreground",children:"Execution is suppressed — effectively off."}),(0,t.jsxs)("p",{className:"text-muted-foreground",children:[p.reason==="instance_mismatch"?"This setting was armed in a different instance and copied here, so no tasks run automatically.":"This setting is missing its activation cutoff, so no tasks run automatically."," ","Toggle it off and back on to arm execution for tasks created here."]})]})]}):null]})}):null,(0,t.jsx)(vo,{title:"Server Info Debug View",description:'Show a "Server" section in the account drawer with the current server restart time and running commit.',checked:O,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)(vo,{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:se,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)(vo,{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)(vo,{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)(vo,{title:"Goals Sidebar Link",description:"Restore the Goals item in the main sidebar while the goals surface is being evaluated.",checked:q,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(sas,"InstanceExperimentalSettings");function nas(){const{userId:e,settled:s}=Vf(),{setBreadcrumbs:n}=Bn(),{pushToast:a}=xi(),i=Dt(),[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=Z({queryKey:P.access.adminUsers(o),queryFn:r(()=>pr.searchAdminUsers(o),"queryFn")}),f=Z({...iLe(e),enabled:s&&p.isSuccess}),x=f.data??[],b=(0,m.useMemo)(()=>p.data?.find(w=>w.id===c)??null,[c,p.data]),v=Z({queryKey:P.access.userCompanyAccess(c??""),queryFn:r(()=>pr.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=je({mutationFn:r(()=>pr.setUserCompanyAccess(c,[...u]),"mutationFn"),onSuccess:r(async()=>{await i.invalidateQueries({queryKey:P.access.userCompanyAccess(c)}),await i.invalidateQueries({queryKey:P.access.adminUsers(o)}),await i.invalidateQueries({queryKey:P.companies.all}),a({title:"Organization access updated",tone:"success"})},"onSuccess")}),N=je({mutationFn:r(async w=>{if(!c)throw new Error("No user selected");return w?pr.promoteInstanceAdmin(c):pr.demoteInstanceAdmin(c)},"mutationFn"),onSuccess:r(async()=>{await i.invalidateQueries({queryKey:P.access.adminUsers(o)}),c&&await i.invalidateQueries({queryKey:P.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 dn&&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)(L,{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)(RI,{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)(rn,{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)(Di,{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)(rn,{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)(L,{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)(pi,{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)(L,{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(nas,"InstanceAccess");var Xhe={getMine:r(e=>Te.get(`/companies/${e}/users/me/inbox-agent-policy`),"getMine"),updateMine:r((e,s)=>Te.put(`/companies/${e}/users/me/inbox-agent-policy`,s),"updateMine")},ras=[{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 UR(e,s){return`${e}:${[...s].sort().join(",")}`}r(UR,"policyKey");function aas({companyId:e}){const s=Dt(),[n,a]=(0,m.useState)(null),i=(0,m.useRef)(null),o=Z({queryKey:e?P.inboxAgentPolicy.mine(e):["inbox-agent-policy","none"],queryFn:r(()=>Xhe.getMine(e),"queryFn"),enabled:!!e}),l=o.data,c=Z({queryKey:e?P.agents.list(e):["agents","none"],queryFn:r(()=>$t.list(e),"queryFn"),enabled:!!e}),d=(0,m.useMemo)(()=>(c.data??[]).filter(Df),[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=UR(l.mode,l.allowedAgentIds);a(b=>b===null||UR(b.mode,b.allowedAgentIds)===i.current?{mode:l.mode,allowedAgentIds:l.allowedAgentIds}:b),i.current=x},[l]);const p=je({mutationFn:r(x=>Xhe.updateMine(e,{mode:x.mode,allowedAgentIds:x.mode==="allowlist"?x.allowedAgentIds:[]}),"mutationFn"),onSuccess:r(x=>{s.setQueryData(P.inboxAgentPolicy.mine(e),x)},"onSuccess")}),f=!!(n&&l&&UR(n.mode,n.allowedAgentIds)!==UR(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)(hd,{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)(wm,{ariaLabel:"Inbox agent archiving policy",value:n.mode,onValueChange:r(x=>a(b=>b&&{...b,mode:x}),"onValueChange"),options:ras,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)(Zy,{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)(L,{type:"button",disabled:!f||p.isPending,onClick:r(()=>n&&p.mutate(n),"onClick"),children:[p.isPending?(0,t.jsx)(rt,{className:"size-4 animate-spin"}):(0,t.jsx)(Sf,{className:"size-4"}),p.isPending?"Saving…":"Save"]})]})]})}r(aas,"InboxAgentPolicyControl");var ias={granted:"Allowed",denied:"Blocked in browser settings",default:"Not requested yet",unsupported:"Not supported in this browser"},Zhe={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 oas(){const[e,s]=(0,m.useState)({});return(0,m.useEffect)(()=>{let n=!1;const a=r(()=>{Promise.all(AI.map(async o=>[o,(await DTe(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=PTe(a);return()=>{n=!0,i()}},[]),e}r(oas,"useCustomSoundNames");function las({kind:e,customName:s,disabled:n,onError:a}){const i=VTe(),o=i.kinds[e],l=(0,m.useId)(),[c,d]=(0,m.useState)(!1),u=OAt[e];async function h(x){const b=RTe(x);if(!b.ok){a(`${u}: ${b.error}`);return}d(!0);try{await DAt(e,x),FT(e,{soundId:hie}),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 LAt(e),jg().kinds[e].soundId==="custom"&&FT(e,{soundId:vP[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)(ci,{checked:o.enabled,onCheckedChange:r(x=>FT(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)($a,{value:o.soundId,onValueChange:r(x=>FT(e,{soundId:x}),"onValueChange"),disabled:f,children:[(0,t.jsx)(La,{className:"min-w-0 flex-1 sm:w-(--sz-170px) sm:flex-none","aria-label":`${u} sound`,children:(0,t.jsx)(Ma,{})}),(0,t.jsxs)(Da,{children:[LTe.map(x=>(0,t.jsx)(Nn,{value:x.id,children:x.label},x.id)),s?(0,t.jsxs)(Nn,{value:hie,children:["Custom: ",s]}):null,(0,t.jsx)(Nn,{value:$At,children:"No sound"})]})]}),(0,t.jsx)(L,{type:"button",variant:"outline",size:"icon-sm","aria-label":`Preview ${u} sound`,disabled:f||o.soundId==="none",onClick:r(()=>{zTe(e,o.soundId,i.volume)},"onClick"),children:(0,t.jsx)(oo,{})}),(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)(L,{type:"button",variant:"outline",size:"sm",disabled:f||c,onClick:r(()=>document.getElementById(l)?.click(),"onClick"),children:[c?(0,t.jsx)(rt,{className:"animate-spin"}):(0,t.jsx)(py,{}),s?"Replace":"Custom"]}),s?(0,t.jsx)(L,{type:"button",variant:"ghost",size:"icon-sm","aria-label":`Remove custom ${u} sound`,disabled:c,onClick:r(()=>{p()},"onClick"),children:(0,t.jsx)(la,{})}):null]})]})}r(las,"KindRow");function cas({userId:e}){const s=VTe(),n=QAt(),a=oas(),[i,o]=(0,m.useState)(()=>W1()),[l,c]=(0,m.useState)(null),[d,u]=(0,m.useState)(null),[h,p]=(0,m.useState)(!1),f=ITe(),x=n.status==="active",b=(0,m.useCallback)(()=>{e&&$U(jg(),e)},[e]);async function v(){const S=await kAt();return o(S),S==="granted"&&b(),S}r(v,"askPermission");async function j(S){DE(C=>({...C,enabled:S})),S&&W1()==="default"&&await v()}r(j,"setEnabled");async function N(S){DE(C=>({...C,pushEnabled:S})),S&&W1()==="default"&&await v()}r(N,"setPushEnabled");async function w(){p(!0),c(null),u(null);try{const S=await jP.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)(Fze,{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)(ci,{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:ias[i]})]}),i==="default"?(0,t.jsx)(L,{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?Zhe[n.status]:Zhe.unsupported,n.error?`: ${n.error}`:""]})]}),(0,t.jsx)(ci,{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,NAt()?(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=>DE(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:AI.map(S=>(0,t.jsx)(las,{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)(L,{type:"button",variant:"secondary",onClick:r(()=>{w()},"onClick"),disabled:h||k,children:[h?(0,t.jsx)(rt,{className:"animate-spin"}):(0,t.jsx)(QI,{}),"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(cas,"NotificationSettingsSection");function das(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(das,"deriveInitials");function uas(){const{setBreadcrumbs:e}=Bn(),{selectedCompanyId:s,selectedCompany:n}=ps(),a=Dt(),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=Z({queryKey:P.auth.session,queryFn:r(()=>Oa.getSession(),"queryFn"),retry:!1});(0,m.useEffect)(()=>{e([{label:"Settings",href:"/company/settings"},{label:"Profile"}])},[e]),(0,m.useEffect)(()=>{const T=f.data;T&&(c(T.user.name??""),u(T.user.image??""))},[f.data]);function x(T){a.setQueryData(P.auth.session,A=>A&&{...A,user:{...A.user,...T}})}r(x,"syncSessionProfile");async function b(T){const A=await Oa.updateProfile(T);return x(A),A}r(b,"persistProfile");function v(){return l.trim()||f.data?.user.name||"Board"}r(v,"resolveProfileName");const j=je({mutationFn:r(T=>b(T),"mutationFn"),onSuccess:r(T=>{p(null),c(T.name??""),u(T.image??"")},"onSuccess"),onError:r(T=>{p(T instanceof Error?T.message:"Failed to update profile.")},"onError")}),N=je({mutationFn:r(async T=>{if(!s)throw new Error("Select an organization before uploading a profile avatar.");const A=await bb.uploadImage(s,T,`profiles/${f.data?.user.id??"board-user"}`);return b({name:v(),image:A.contentPath})},"mutationFn"),onSuccess:r(T=>{p(null),c(T.name??""),u(T.image??"")},"onSuccess"),onError:r(T=>{p(T instanceof Error?T.message:"Failed to upload avatar.")},"onError")}),w=je({mutationFn:r(()=>b({name:v(),image:null}),"mutationFn"),onSuccess:r(T=>{p(null),c(T.name??""),u(T.image??"")},"onSuccess"),onError:r(T=>{p(T instanceof Error?T.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=das(k),I=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)(AM,{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)(rn,{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||I,onChange:r(T=>{const A=T.target.files?.[0];A&&(N.mutate(A),T.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)(rt,{className:"size-4 animate-spin"}):(0,t.jsx)(iX,{className:"size-4"})}),(0,t.jsxs)(Mo,{size:"lg",className:"data-[size=lg]:size-24 ring-4 ring-background shadow-xl",children:[S?(0,t.jsx)(xd,{src:S,alt:k}):null,(0,t.jsx)(Do,{children:C})]})]}),(0,t.jsxs)("div",{className:"flex flex-wrap items-center gap-2",children:[(0,t.jsxs)(L,{type:"button",variant:"secondary",onClick:r(()=>o.current?.click(),"onClick"),disabled:!s||I,children:[N.isPending?(0,t.jsx)(rt,{className:"size-4 animate-spin"}):(0,t.jsx)(iX,{className:"size-4"}),S?"Change photo":"Upload photo"]}),S?(0,t.jsxs)(L,{type:"button",variant:"outline",onClick:r(()=>w.mutate(),"onClick"),disabled:I,children:[w.isPending?(0,t.jsx)(rt,{className:"size-4 animate-spin"}):(0,t.jsx)(la,{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(T=>{T.preventDefault(),j.mutate({name:v(),image:d.trim()||null})},"onSubmit"),children:[(0,t.jsxs)("div",{className:"space-y-2",children:[(0,t.jsx)(Gs,{htmlFor:"profile-name",children:"Display name"}),(0,t.jsx)(ht,{id:"profile-name",value:l,onChange:r(T=>c(T.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)(Gs,{htmlFor:"profile-email",children:"Email"}),(0,t.jsx)(ht,{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)(L,{type:"submit",disabled:I||!l.trim(),children:[j.isPending?(0,t.jsx)(rt,{className:"size-4 animate-spin"}):(0,t.jsx)(Sf,{className:"size-4"}),j.isPending?"Saving...":"Save profile"]})})]}),(0,t.jsx)(aas,{companyId:s}),(0,t.jsx)(cas,{userId:f.data.user.id??null})]})]})}r(uas,"ProfileSettings");function mas(e){return e?e.split(/\r?\n/).map(s=>s.trim()).find(Boolean)??null:null}r(mas,"firstNonEmptyLine");function epe(e){return mas(e.lastError)??"Plugin entered an error state without a stored error message."}r(epe,"getPluginErrorSummary");function tpe(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(tpe,"isExperimentalPluginIdentity");function spe(){return(0,t.jsx)(ct,{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(spe,"ExperimentalBadge");function has(){const{selectedCompany:e}=ps(),{setBreadcrumbs:s}=Bn(),n=Dt(),{pushToast:a}=da(),[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}=Z({queryKey:P.plugins.all,queryFn:r(()=>Al.list(),"queryFn")}),N=Z({queryKey:P.plugins.examples,queryFn:r(()=>Al.listBundled(),"queryFn")}),w=r(()=>{n.invalidateQueries({queryKey:P.plugins.all}),n.invalidateQueries({queryKey:P.plugins.examples}),n.invalidateQueries({queryKey:P.plugins.uiContributions})},"invalidatePluginQueries"),k=je({mutationFn:r(E=>Al.install(E),"mutationFn"),onSuccess:r(()=>{w(),c(!1),o(""),a({title:"Plugin installed successfully",tone:"success"})},"onSuccess"),onError:r(E=>{a({title:"Failed to install plugin",body:E.message,tone:"error"})},"onError")}),S=je({mutationFn:r(E=>Al.uninstall(E),"mutationFn"),onSuccess:r(()=>{w(),a({title:"Plugin uninstalled successfully",tone:"success"})},"onSuccess"),onError:r(E=>{a({title:"Failed to uninstall plugin",body:E.message,tone:"error"})},"onError")}),C=je({mutationFn:r(E=>Al.enable(E),"mutationFn"),onSuccess:r(()=>{w(),a({title:"Plugin enabled",tone:"success"})},"onSuccess"),onError:r(E=>{a({title:"Failed to enable plugin",body:E.message,tone:"error"})},"onError")}),I=je({mutationFn:r(E=>Al.disable(E),"mutationFn"),onSuccess:r(()=>{w(),a({title:"Plugin disabled",tone:"info"})},"onSuccess"),onError:r(E=>{a({title:"Failed to disable plugin",body:E.message,tone:"error"})},"onError")}),R=b??[],T=N.data??[],A=new Map(R.map(E=>[E.packageName,E])),D=new Map(T.map(E=>[E.packageName,E])),M=k.variables?.isLocalPath?k.error?.message??null:null,B=(0,m.useMemo)(()=>new Map(R.map(E=>[E.id,epe(E)])),[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)(Xx,{className:"h-6 w-6 text-muted-foreground"}),(0,t.jsx)("h1",{className:"text-xl font-semibold",children:"Plugin Manager"})]}),(0,t.jsxs)(Qs,{open:l,onOpenChange:c,children:[(0,t.jsx)(Uy,{asChild:!0,children:(0,t.jsxs)(L,{size:"sm",className:"gap-2",children:[(0,t.jsx)(yn,{className:"h-4 w-4"}),"Install Plugin"]})}),(0,t.jsxs)(Js,{children:[(0,t.jsxs)(hn,{children:[(0,t.jsx)(Xs,{children:"Install Plugin"}),(0,t.jsx)(jn,{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)(Gs,{htmlFor:"packageName",children:"npm Package Name"}),(0,t.jsx)(ht,{id:"packageName",placeholder:"@tickernelz/paperclip-pro-plugin-example",value:i,onChange:r(E=>o(E.target.value),"onChange")})]})}),(0,t.jsxs)(hr,{children:[(0,t.jsx)(L,{variant:"outline",onClick:r(()=>c(!1),"onClick"),children:"Cancel"}),(0,t.jsx)(L,{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)(Es,{className:"mt-0.5 h-4 w-4 shrink-0 text-amber-700"}),(0,t.jsxs)("div",{className:"space-y-1 text-sm",children:[(0,t.jsx)("p",{className:"font-medium text-foreground",children:"Plugins are alpha."}),(0,t.jsx)("p",{className:"text-muted-foreground",children:"The plugin runtime and API surface are still changing. Expect breaking changes while this feature settles."})]})]})}),(0,t.jsxs)("section",{className:"space-y-3",children:[(0,t.jsxs)("div",{className:"flex items-center gap-2",children:[(0,t.jsx)(Dm,{className:"h-5 w-5 text-muted-foreground"}),(0,t.jsx)("h2",{className:"text-base font-semibold",children:"Available Plugins"}),(0,t.jsx)(ct,{variant:"outline",children:"Bundled"})]}),M&&(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:M}),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."}):T.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)(rn,{className:"block py-0",children:(0,t.jsx)("ul",{className:"divide-y",children:T.map(E=>{const z=A.get(E.packageName),$=k.isPending&&k.variables?.isLocalPath&&k.variables.packageName===E.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:E.displayName}),(0,t.jsx)(ct,{variant:"outline",children:E.tag==="first-party"?"First-party":"Example"}),tpe({packageName:E.packageName,packagePath:E.localPath,bundledExperimental:E.experimental})&&(0,t.jsx)(spe,{}),z?(0,t.jsx)(ct,{variant:z.status==="ready"?"default":"secondary",className:z.status==="ready"?"bg-green-600 hover:bg-green-700":"",children:z.status}):(0,t.jsx)(ct,{variant:"secondary",children:"Not installed"})]}),(0,t.jsx)("p",{className:"mt-1 text-sm text-muted-foreground",children:E.description}),(0,t.jsx)("p",{className:"mt-1 text-xs text-muted-foreground",children:E.packageName}),$&&!E.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:z?(0,t.jsxs)(t.Fragment,{children:[z.status!=="ready"&&(0,t.jsx)(L,{variant:"outline",size:"sm",disabled:C.isPending,onClick:r(()=>C.mutate(z.id),"onClick"),children:"Enable"}),(0,t.jsx)(L,{variant:"outline",size:"sm",asChild:!0,children:(0,t.jsx)(Ke,{to:`/company/settings/instance/plugins/${z.id}`,children:z.status==="ready"?"Open Settings":"Review"})})]}):(0,t.jsx)(L,{size:"sm",disabled:$||k.isPending,onClick:r(()=>k.mutate({packageName:E.localPath,isLocalPath:!0}),"onClick"),children:$?"Installing...":"Install"})})]})},E.packageName)})})})]}),(0,t.jsxs)("section",{className:"space-y-3",children:[(0,t.jsxs)("div",{className:"flex items-center gap-2",children:[(0,t.jsx)(Xx,{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)(rn,{className:"block py-0",children:(0,t.jsx)("ul",{className:"divide-y",children:R.map(E=>(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)(Ke,{to:`/company/settings/instance/plugins/${E.id}`,className:"font-medium hover:underline truncate block",title:E.manifestJson.displayName??E.packageName,children:E.manifestJson.displayName??E.packageName}),D.has(E.packageName)&&(0,t.jsx)(ct,{variant:"outline",children:D.get(E.packageName)?.tag==="first-party"?"First-party":"Example"}),tpe({packageName:E.packageName,packagePath:E.packagePath,manifestJson:E.manifestJson,bundledExperimental:D.get(E.packageName)?.experimental})&&(0,t.jsx)(spe,{})]}),(0,t.jsx)("div",{children:(0,t.jsxs)("p",{className:"text-xs text-muted-foreground mt-0.5 truncate",title:E.packageName,children:[E.packageName," · v",E.manifestJson.version??E.version]})}),(0,t.jsx)("p",{className:"text-sm text-muted-foreground truncate mt-0.5",title:E.manifestJson.description,children:E.manifestJson.description||"No description provided."}),E.status==="error"&&(0,t.jsx)("div",{className:"mt-3 rounded-md border border-red-500/25 bg-red-500/[0.06] px-3 py-2",children:(0,t.jsxs)("div",{className:"flex flex-wrap items-start gap-3",children:[(0,t.jsxs)("div",{className:"min-w-0 flex-1",children:[(0,t.jsxs)("div",{className:"flex items-center gap-2 text-sm font-medium text-red-700 dark:text-red-300",children:[(0,t.jsx)(Es,{className:"h-4 w-4 shrink-0"}),(0,t.jsx)("span",{children:"Plugin error"})]}),(0,t.jsx)("p",{className:"mt-1 text-sm text-red-700/90 dark:text-red-200/90 break-words",title:E.lastError??void 0,children:B.get(E.id)})]}),(0,t.jsx)(L,{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(E),"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)(ct,{variant:E.status==="ready"?"default":E.status==="error"?"destructive":"secondary",className:W("shrink-0",E.status==="ready"?"bg-green-600 hover:bg-green-700":""),children:E.status}),(0,t.jsx)(L,{variant:"outline",size:"icon-sm",className:"h-8 w-8",title:E.status==="ready"?"Disable":"Enable",onClick:r(()=>{E.status==="ready"?I.mutate(E.id):C.mutate(E.id)},"onClick"),disabled:C.isPending||I.isPending,children:(0,t.jsx)(D7,{className:W("h-4 w-4",E.status==="ready"?"text-green-600":"")})}),(0,t.jsx)(L,{variant:"outline",size:"icon-sm",className:"h-8 w-8 text-destructive hover:text-destructive",title:"Uninstall",onClick:r(()=>{u(E.id),p(E.manifestJson.displayName??E.packageName)},"onClick"),disabled:S.isPending,children:(0,t.jsx)(la,{className:"h-4 w-4"})})]}),(0,t.jsx)(L,{variant:"outline",size:"sm",className:"mt-2 h-8",asChild:!0,children:(0,t.jsxs)(Ke,{to:`/company/settings/instance/plugins/${E.id}`,children:[(0,t.jsx)(Jd,{className:"h-4 w-4"}),"Configure"]})})]})})]})},E.id))})}):(0,t.jsx)(rn,{className:"bg-muted/30",children:(0,t.jsxs)(Xa,{className:"flex flex-col items-center justify-center py-10",children:[(0,t.jsx)(Xx,{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)(Qs,{open:d!==null,onOpenChange:r(E=>{E||u(null)},"onOpenChange"),children:(0,t.jsxs)(Js,{children:[(0,t.jsxs)(hn,{children:[(0,t.jsx)(Xs,{children:"Uninstall Plugin"}),(0,t.jsxs)(jn,{children:["Are you sure you want to uninstall ",(0,t.jsx)("strong",{children:h}),"? This action cannot be undone."]})]}),(0,t.jsxs)(hr,{children:[(0,t.jsx)(L,{variant:"outline",onClick:r(()=>u(null),"onClick"),children:"Cancel"}),(0,t.jsx)(L,{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)(Qs,{open:f!==null,onOpenChange:r(E=>{E||x(null)},"onOpenChange"),children:(0,t.jsxs)(Js,{className:"sm:max-w-2xl",children:[(0,t.jsxs)(hn,{children:[(0,t.jsx)(Xs,{children:"Error Details"}),(0,t.jsxs)(jn,{children:[f?.manifestJson.displayName??f?.packageName??"Plugin"," hit an error state."]})]}),(0,t.jsxs)("div",{className:"space-y-4",children:[(0,t.jsx)("div",{className:"rounded-md border border-red-500/25 bg-red-500/[0.06] px-4 py-3",children:(0,t.jsxs)("div",{className:"flex items-start gap-3",children:[(0,t.jsx)(Es,{className:"mt-0.5 h-4 w-4 shrink-0 text-red-700 dark:text-red-300"}),(0,t.jsxs)("div",{className:"space-y-1 text-sm",children:[(0,t.jsx)("p",{className:"font-medium text-red-700 dark:text-red-300",children:"What errored"}),(0,t.jsx)("p",{className:"text-red-700/90 dark:text-red-200/90 break-words",children:f?epe(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)(hr,{children:(0,t.jsx)(L,{variant:"outline",onClick:r(()=>x(null),"onClick"),children:"Close"})})]})})]})}r(has,"PluginManager");function pas(){const{selectedCompany:e,selectedCompanyId:s}=ps(),{setBreadcrumbs:n}=Bn(),{companyPrefix:a,pluginId:i}=va(),{hideHostPaths:o}=vA(),[l,c]=(0,m.useState)("configuration"),{data:d,isLoading:u}=Z({queryKey:P.plugins.detail(i),queryFn:r(()=>Al.get(i),"queryFn"),enabled:!!i}),{data:h,isLoading:p}=Z({queryKey:P.plugins.health(i),queryFn:r(()=>Al.health(i),"queryFn"),enabled:!!i&&d?.status==="ready",refetchInterval:3e4}),{data:f}=Z({queryKey:P.plugins.dashboard(i),queryFn:r(()=>Al.dashboard(i),"queryFn"),enabled:!!i,refetchInterval:3e4}),{data:x}=Z({queryKey:P.plugins.logs(i),queryFn:r(()=>Al.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?P.plugins.config(i,s):["plugins",i??"__missing_plugin__","companies","__missing_company__","config"],{data:N,isLoading:w}=Z({queryKey:j,queryFn:r(()=>Al.getConfig(i,s),"queryFn"),enabled:!!i&&!!v&&!!s}),{slots:k}=bd({slotTypes:["settingsPage"],companyId:s,enabled:!!s}),S=k.filter(z=>z.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)(kn,{to:"/company/settings/instance/plugins",replace:!0});const I=d.status,R=d.status==="ready"?"default":d.status==="error"?"destructive":"secondary",T=d.manifestJson.description||"No description provided.",A=d.manifestJson.capabilities??[],D=d.manifestJson.environmentDrivers??[],M=d.manifestJson.localFolders??[],B=M.length>0&&!o,E=D.map(z=>z.displayName?.trim()||z.driverKey).filter((z,$,q)=>q.indexOf(z)===$).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)(Ke,{to:"/company/settings/instance/plugins",children:(0,t.jsx)(L,{variant:"outline",size:"icon",className:"h-8 w-8",children:(0,t.jsx)(Tl,{className:"h-4 w-4"})})}),(0,t.jsxs)("div",{className:"flex items-center gap-2",children:[(0,t.jsx)(Xx,{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)(ct,{variant:R,className:"ml-2",children:I}),(0,t.jsxs)(ct,{variant:"outline",className:"ml-1",children:["v",d.manifestJson.version??d.version]})]})]}),(0,t.jsxs)(Ti,{value:l,onValueChange:r(z=>c(z),"onValueChange"),className:"space-y-6",children:[(0,t.jsx)(Mc,{align:"start",items:[{value:"configuration",label:"Configuration"},{value:"status",label:"Status"}],value:l,onValueChange:r(z=>c(z),"onValueChange")}),(0,t.jsx)(ba,{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:T})]}),(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(z=>(0,t.jsx)(ct,{variant:"outline",className:"capitalize",children:z},z)):(0,t.jsx)("span",{className:"text-foreground",children:"None"})})]})]})]})]}),(0,t.jsx)(Bl,{}),(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"})}),B?(0,t.jsx)(fas,{pluginId:i,companyId:s,declarations:M}):null,C?(0,t.jsx)("div",{className:"space-y-3",children:S.map(z=>(0,t.jsx)(Wu,{slot:z,context:{companyId:s,companyPrefix:a??null},missingBehavior:"placeholder"},`${z.pluginKey}:${z.id}`))}):v?(0,t.jsx)(yas,{pluginId:i,companyId:s,schema:b,initialValues:N?.configJson,isLoading:w,pluginStatus:d.status,supportsConfigTest:d.supportsConfigTest===!0}):D.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:[E||"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)(Ke,{to:"/company/settings/instance/environments",children:(0,t.jsx)(L,{variant:"outline",size:"sm",children:"Open Environments"})})})]}):B?null:(0,t.jsx)("p",{className:"text-sm text-muted-foreground",children:"This plugin does not require any settings."})]})]})}),(0,t.jsx)(ba,{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)(rn,{children:[(0,t.jsxs)(no,{children:[(0,t.jsxs)(ko,{className:"text-base flex items-center gap-1.5",children:[(0,t.jsx)(ym,{className:"h-4 w-4"}),"Runtime Dashboard"]}),(0,t.jsx)(Fl,{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)(ym,{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)(ct,{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:jas(f.worker.uptime)})]}),(0,t.jsxs)("div",{className:"flex justify-between",children:[(0,t.jsx)("span",{className:"text-muted-foreground",children:"Pending RPCs"}),(0,t.jsx)("span",{className:"text-xs",children:f.worker.pendingRequests})]}),f.worker.totalCrashes>0&&(0,t.jsxs)(t.Fragment,{children:[(0,t.jsxs)("div",{className:"flex justify-between col-span-2",children:[(0,t.jsxs)("span",{className:"text-muted-foreground flex items-center gap-1",children:[(0,t.jsx)(Es,{className:"h-3 w-3 text-amber-500"}),"Crashes"]}),(0,t.jsxs)("span",{className:"text-xs",children:[f.worker.consecutiveCrashes," consecutive / ",f.worker.totalCrashes," total"]})]}),f.worker.lastCrashAt&&(0,t.jsxs)("div",{className:"flex justify-between col-span-2",children:[(0,t.jsx)("span",{className:"text-muted-foreground",children:"Last Crash"}),(0,t.jsx)("span",{className:"text-xs",children:was(f.worker.lastCrashAt)})]})]})]}):(0,t.jsx)("p",{className:"text-sm text-muted-foreground italic",children:"No worker process registered."})]}),(0,t.jsx)(Bl,{}),(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)(Y0,{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(z=>(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)(kas,{status:z.status}),(0,t.jsx)("span",{className:"truncate font-mono text-xs",title:z.jobKey??z.jobId,children:z.jobKey??z.jobId.slice(0,8)}),(0,t.jsx)(ct,{variant:"outline",className:"px-1 py-0 text-(length:--text-nano)",children:z.trigger})]}),(0,t.jsxs)("div",{className:"flex shrink-0 items-center gap-2 text-xs text-muted-foreground",children:[z.durationMs!=null?(0,t.jsx)("span",{children:rpe(z.durationMs)}):null,(0,t.jsx)("span",{title:z.createdAt,children:ape(z.createdAt)})]})]},z.id))}):(0,t.jsx)("p",{className:"text-sm text-muted-foreground italic",children:"No job runs recorded yet."})]}),(0,t.jsx)(Bl,{}),(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)(q7,{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(z=>(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)(Nas,{status:z.status}),(0,t.jsx)("span",{className:"truncate font-mono text-xs",title:z.webhookKey,children:z.webhookKey})]}),(0,t.jsxs)("div",{className:"flex shrink-0 items-center gap-2 text-xs text-muted-foreground",children:[z.durationMs!=null?(0,t.jsx)("span",{children:rpe(z.durationMs)}):null,(0,t.jsx)("span",{title:z.createdAt,children:ape(z.createdAt)})]})]},z.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)(ho,{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)(rn,{children:[(0,t.jsxs)(no,{children:[(0,t.jsxs)(ko,{className:"text-base flex items-center gap-1.5",children:[(0,t.jsx)(cX,{className:"h-4 w-4"}),"Recent Logs"]}),(0,t.jsxs)(Fl,{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(z=>(0,t.jsxs)("div",{className:`flex gap-2 py-0.5 ${z.level==="error"?"text-destructive":z.level==="warn"?"text-yellow-600 dark:text-yellow-400":z.level==="debug"?"text-muted-foreground/60":"text-muted-foreground"}`,children:[(0,t.jsx)("span",{className:"shrink-0 text-muted-foreground/50",children:new Date(z.createdAt).toLocaleTimeString()}),(0,t.jsx)(ct,{variant:"outline",className:"h-4 shrink-0 px-1 text-(length:--text-nano)",children:z.level}),(0,t.jsx)("span",{className:"truncate",title:z.message,children:z.message})]},z.id))})})]}):null]}),(0,t.jsxs)("div",{className:"space-y-6",children:[(0,t.jsxs)(rn,{children:[(0,t.jsx)(no,{children:(0,t.jsxs)(ko,{className:"text-base flex items-center gap-1.5",children:[(0,t.jsx)(cX,{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)(ct,{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((z,$)=>(0,t.jsxs)("div",{className:"flex items-start justify-between gap-2",children:[(0,t.jsx)("span",{className:"truncate text-muted-foreground",title:z.name,children:z.name}),z.passed?(0,t.jsx)(Wze,{className:"h-4 w-4 shrink-0 text-green-500"}):(0,t.jsx)(Ec,{className:"h-4 w-4 shrink-0 text-destructive"})]},$))}):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)(ct,{variant:R,children:I})]}),(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)(rn,{children:[(0,t.jsx)(no,{children:(0,t.jsx)(ko,{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)(rn,{children:[(0,t.jsx)(no,{children:(0,t.jsxs)(ko,{className:"text-base flex items-center gap-1.5",children:[(0,t.jsx)(bc,{className:"h-4 w-4"}),"Permissions"]})}),(0,t.jsx)(Xa,{children:A.length>0?(0,t.jsx)("ul",{className:"space-y-2 text-sm text-muted-foreground",children:A.map(z=>(0,t.jsx)("li",{className:"rounded-md bg-muted/40 px-2.5 py-2 font-mono text-xs text-foreground/85",children:z},z))}):(0,t.jsx)("p",{className:"text-sm text-muted-foreground italic",children:"No special permissions requested."})})]})]})]})})]})]})}r(pas,"PluginSettings");function fas({pluginId:e,companyId:s,declarations:n}){const{data:a,isLoading:i,error:o}=Z({queryKey:s?P.plugins.localFolders(e,s):["plugins",e,"companies","none","local-folders"],queryFn:r(()=>Al.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)(Ho,{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)(rt,{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)(xas,{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(fas,"PluginLocalFoldersSettings");function xas({pluginId:e,companyId:s,declaration:n,status:a}){const i=Dt(),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=je({mutationFn:r(v=>Al.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:P.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(!vas(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)(ct,{variant:"outline",className:"font-mono text-(length:--text-nano)",children:n.folderKey}),(0,t.jsx)(ct,{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)(ct,{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)(hz,{label:"Configured",value:a?.configured?"Yes":"No",ok:!!a?.configured}),(0,t.jsx)(hz,{label:"Readable",value:a?.readable?"Yes":"No",ok:!!a?.readable}),(0,t.jsx)(hz,{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)(Dd,{className:"h-8"}),(0,t.jsxs)(L,{size:"sm",onClick:b,disabled:h.isPending||!f||!s,children:[h.isPending?(0,t.jsx)(rt,{className:"h-3.5 w-3.5 animate-spin"}):(0,t.jsx)(Sf,{className:"h-3.5 w-3.5"}),"Save"]})]})]}),(0,t.jsx)(gas,{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(xas,"PluginLocalFolderRow");function hz({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)(ct,{variant:n?"default":"secondary",children:s})]})}r(hz,"FolderStatusMetric");function gas({status:e,declaration:s}){const n=e?.requiredDirectories??s.requiredDirectories??[],a=e?.requiredFiles??s.requiredFiles??[],i=e?.missingDirectories??n,o=e?.missingFiles??a,l=bas(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)(npe,{title:"Required directories",items:n,missingItems:i,missingLabel:"Missing directories",inspectionUnavailable:l}),(0,t.jsx)(npe,{title:"Required files",items:a,missingItems:o,missingLabel:"Missing files",inspectionUnavailable:l})]})}r(gas,"FolderRequirements");function bas(e){return!e?.configured||e.readable?!1:e.problems.some(s=>s.code==="missing"||s.code==="not_readable"||s.code==="not_directory")}r(bas,"isRootNotInspected");function npe({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)(ct,{variant:"secondary",className:"text-(length:--text-nano)",children:"Not inspected"}):n.length>0?(0,t.jsxs)(ct,{variant:"destructive",className:"text-(length:--text-nano)",children:[n.length," missing"]}):(0,t.jsx)(ct,{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(npe,"RequirementList");function vas(e){return e.startsWith("/")||/^[A-Za-z]:[\\/]/.test(e)||e.startsWith("\\\\")}r(vas,"isLikelyAbsolutePath");function yas({pluginId:e,companyId:s,schema:n,initialValues:a,isLoading:i,pluginStatus:o,supportsConfigTest:l}){const c=Dt(),[d,u]=(0,m.useState)(()=>({...bf(n),...a??{}})),h=(0,m.useRef)(!1);(0,m.useEffect)(()=>{h.current=!1,u(bf(n))},[s,e,n]),(0,m.useEffect)(()=>{a&&!h.current&&(h.current=!0,u({...bf(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({...bf(n),...a??{}}),w=je({mutationFn:r(R=>{if(!s)throw new Error("Select an organization before saving plugin configuration.");return Al.saveConfig(e,s,R)},"mutationFn"),onSuccess:r(()=>{b({type:"success",text:"Configuration saved."}),j(null),s&&c.invalidateQueries({queryKey:P.plugins.config(e,s)}),setTimeout(()=>b(null),3e3)},"onSuccess"),onError:r(R=>{b({type:"error",text:R.message||"Failed to save configuration."})},"onError")}),k=je({mutationFn:r(R=>{if(!s)throw new Error("Select an organization before testing plugin configuration.");return Al.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=by(n,d);if(Object.keys(R).length>0){f(R);return}f({}),w.mutate(d)},[n,d,w]),I=(0,m.useCallback)(()=>{const R=by(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)(rt,{className:"h-4 w-4 animate-spin"}),"Loading configuration..."]}):(0,t.jsxs)("div",{className:"space-y-4",children:[(0,t.jsx)(iA,{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)(L,{onClick:C,disabled:w.isPending||!N,size:"sm",children:w.isPending?(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)(rt,{className:"h-3.5 w-3.5 animate-spin"}),"Saving..."]}):"Save Configuration"}),o==="ready"&&l&&(0,t.jsx)(L,{variant:"outline",onClick:I,disabled:k.isPending||!s,size:"sm",children:k.isPending?(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)(rt,{className:"h-3.5 w-3.5 animate-spin"}),"Testing..."]}):"Test Configuration"})]})]})}r(yas,"PluginConfigForm");function jas(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(jas,"formatUptime");function rpe(e){return e<1e3?`${e}ms`:e<6e4?`${(e/1e3).toFixed(1)}s`:`${(e/6e4).toFixed(1)}m`}r(rpe,"formatDuration");function ape(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(ape,"formatRelativeTime");function was(e){return new Date(e).toLocaleString()}r(was,"formatTimestamp");function kas({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(kas,"JobStatusDot");function Nas({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(Nas,"DeliveryStatusDot");function pz({adapter:e,canRemove:s,onToggle:n,onRemove:a,onReload:i,onReinstall:o,isToggling:l,isReloading:c,isReinstalling:d,overriddenBy:u,toggleTitleEnabled:h,toggleTitleDisabled:p,disabledBadgeLabel:f}){return(0,t.jsx)("li",{children:(0,t.jsxs)("div",{className:"flex items-center gap-4 px-4 py-3",children:[(0,t.jsxs)("div",{className:"min-w-0 flex-1",children:[(0,t.jsxs)("div",{className:"flex flex-wrap items-center gap-2",children:[(0,t.jsx)("span",{className:W("font-medium",e.disabled&&"text-muted-foreground line-through"),children:e.label&&e.label!==e.type?e.label:Ff(e.type)}),(0,t.jsx)(ct,{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)(Ho,{className:"h-4 w-4 text-amber-500"})}):(0,t.jsx)("span",{title:"Installed from npm",children:(0,t.jsx)(Th,{className:"h-4 w-4 text-red-500"})})),e.version&&(0,t.jsxs)(ct,{variant:"secondary",className:"font-mono text-(length:--text-nano)",children:["v",e.version]}),e.overriddenBuiltin&&(0,t.jsx)(ct,{variant:"secondary",className:"text-blue-600 border-blue-400",children:"Overrides built-in"}),u&&(0,t.jsxs)(ct,{variant:"secondary",className:"text-blue-600 border-blue-400",children:["Overridden by ",u]}),e.disabled&&(0,t.jsx)(ct,{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)(L,{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)(po,{className:W("h-4 w-4",d&&"animate-bounce")})}),i&&(0,t.jsx)(L,{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)(_i,{className:W("h-4 w-4",c&&"animate-spin")})}),(0,t.jsx)(L,{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)(D7,{className:W("h-4 w-4",e.disabled?"text-muted-foreground":"text-green-600")})}),s&&(0,t.jsx)(L,{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)(la,{className:"h-4 w-4"})})]})]})})}r(pz,"AdapterRow");function Sas(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(Sas,"fetchNpmLatestVersion");function Cas({adapter:e,open:s,isReinstalling:n,onConfirm:a,onCancel:i}){const{data:o,isLoading:l}=Z({queryKey:["npm-latest-version",e?.packageName],queryFn:r(()=>e?.packageName?Sas(e.packageName):null,"queryFn"),enabled:s&&!!e?.packageName,staleTime:6e4}),c=e?.version&&o&&e.version===o;return(0,t.jsx)(Qs,{open:s,onOpenChange:r(d=>{d||i()},"onOpenChange"),children:(0,t.jsxs)(Js,{children:[(0,t.jsxs)(hn,{children:[(0,t.jsx)(Xs,{children:"Reinstall Adapter"}),(0,t.jsxs)(jn,{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)(hr,{children:[(0,t.jsx)(L,{variant:"outline",onClick:i,disabled:n,children:"Cancel"}),(0,t.jsx)(L,{disabled:n,onClick:a,children:n?"Reinstalling...":"Reinstall"})]})]})})}r(Cas,"ReinstallDialog");function ipe(){const{selectedCompany:e}=ps(),{setBreadcrumbs:s}=Bn(),n=Dt(),{pushToast:a}=da(),[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}=Z({queryKey:P.adapters.all,queryFn:r(()=>uh.list(),"queryFn")}),w=r(()=>{n.invalidateQueries({queryKey:P.adapters.all})},"invalidate"),k=je({mutationFn:r(E=>uh.install(E),"mutationFn"),onSuccess:r(E=>{w(),p(!1),o(""),c(""),u(!1),a({title:"Adapter installed",body:`Type "${E.type}" registered successfully.${E.version?` (v${E.version})`:""}`,tone:"success"})},"onSuccess"),onError:r(E=>{a({title:"Install failed",body:E.message,tone:"error"})},"onError")}),S=je({mutationFn:r(E=>uh.remove(E),"mutationFn"),onSuccess:r(()=>{w(),a({title:"Adapter removed",tone:"success"})},"onSuccess"),onError:r(E=>{a({title:"Removal failed",body:E.message,tone:"error"})},"onError")}),C=je({mutationFn:r(({type:E,disabled:z})=>uh.setDisabled(E,z),"mutationFn"),onSuccess:r(()=>{w()},"onSuccess"),onError:r(E=>{a({title:"Toggle failed",body:E.message,tone:"error"})},"onError")}),I=je({mutationFn:r(({type:E,paused:z})=>uh.setOverridePaused(E,z),"mutationFn"),onSuccess:r(()=>{w()},"onSuccess"),onError:r(E=>{a({title:"Override toggle failed",body:E.message,tone:"error"})},"onError")}),R=je({mutationFn:r(E=>uh.reload(E),"mutationFn"),onSuccess:r(E=>{w(),Yq(E.type),cte(E.type),a({title:"Adapter reloaded",body:`Type "${E.type}" reloaded.${E.version?` (v${E.version})`:""}`,tone:"success"})},"onSuccess"),onError:r(E=>{a({title:"Reload failed",body:E.message,tone:"error"})},"onError")}),T=je({mutationFn:r(E=>uh.reinstall(E),"mutationFn"),onSuccess:r(E=>{w(),Yq(E.type),cte(E.type),a({title:"Adapter reinstalled",body:`Type "${E.type}" updated from npm.${E.version?` (v${E.version})`:""}`,tone:"success"})},"onSuccess"),onError:r(E=>{a({title:"Reinstall failed",body:E.message,tone:"error"})},"onError")}),A=(j??[]).filter(E=>E.source==="builtin"),D=(j??[]).filter(E=>E.source==="external"),M=(j??[]).filter(E=>E.source==="external"&&E.overriddenBuiltin).filter(E=>!A.some(z=>z.type===E.type)).map(E=>({type:E.type,label:Ff(E.type),overriddenBy:[E.packageName,E.version?`v${E.version}`:void 0].filter(Boolean).join(" "),overridePaused:!!E.overridePaused,menuDisabled:!!E.disabled}));if(N)return(0,t.jsx)("div",{className:"p-4 text-sm text-muted-foreground",children:"Loading adapters..."});const B=k.isPending||S.isPending||C.isPending||I.isPending||R.isPending||T.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)(ym,{className:"h-6 w-6 text-muted-foreground"}),(0,t.jsx)("h1",{className:"text-xl font-semibold",children:"Adapters"}),(0,t.jsx)(ct,{variant:"outline",className:"text-amber-600 border-amber-400",children:"Alpha"})]}),(0,t.jsxs)(Qs,{open:h,onOpenChange:p,children:[(0,t.jsx)(Uy,{asChild:!0,children:(0,t.jsxs)(L,{size:"sm",className:"gap-2",children:[(0,t.jsx)(yn,{className:"h-4 w-4"}),"Install Adapter"]})}),(0,t.jsxs)(Js,{children:[(0,t.jsxs)(hn,{children:[(0,t.jsx)(Xs,{children:"Install External Adapter"}),(0,t.jsxs)(jn,{children:["Add an adapter from npm or a local path. The adapter package must export ",(0,t.jsx)("code",{className:"text-xs bg-muted px-1 py-0.5 rounded",children:"createServerAdapter()"}),"."]})]}),(0,t.jsxs)("div",{className:"grid gap-4 py-4",children:[(0,t.jsxs)("div",{className:"flex items-center gap-2",children:[(0,t.jsxs)("button",{type:"button",className:W("inline-flex items-center gap-1.5 rounded-md border px-3 py-1.5 text-xs transition-colors",d?"border-border text-muted-foreground hover:text-foreground hover:bg-accent/50":"border-foreground bg-accent text-foreground"),onClick:r(()=>u(!1),"onClick"),children:[(0,t.jsx)(Th,{className:"h-3.5 w-3.5"}),"npm package"]}),(0,t.jsxs)("button",{type:"button",className:W("inline-flex items-center gap-1.5 rounded-md border px-3 py-1.5 text-xs transition-colors",d?"border-foreground bg-accent text-foreground":"border-border text-muted-foreground hover:text-foreground hover:bg-accent/50"),onClick:r(()=>u(!0),"onClick"),children:[(0,t.jsx)(Ho,{className:"h-3.5 w-3.5"}),"Local path"]})]}),d?(0,t.jsxs)("div",{className:"grid gap-2",children:[(0,t.jsx)(Gs,{htmlFor:"adapterLocalPath",children:"Path to adapter package"}),(0,t.jsxs)("div",{className:"flex gap-2",children:[(0,t.jsx)(ht,{id:"adapterLocalPath",className:"flex-1 font-mono text-xs",placeholder:"/mnt/e/Projects/my-adapter or E:\\Projects\\my-adapter",value:i,onChange:r(E=>o(E.target.value),"onChange")}),(0,t.jsx)(Dd,{})]}),(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)(Gs,{htmlFor:"adapterPackageName",children:"Package Name"}),(0,t.jsx)(ht,{id:"adapterPackageName",placeholder:"my-paperclip-adapter",value:i,onChange:r(E=>o(E.target.value),"onChange")})]}),(0,t.jsxs)("div",{className:"grid gap-2",children:[(0,t.jsx)(Gs,{htmlFor:"adapterVersion",children:"Version (optional)"}),(0,t.jsx)(ht,{id:"adapterVersion",placeholder:"latest",value:l,onChange:r(E=>c(E.target.value),"onChange")})]})]})]}),(0,t.jsxs)(hr,{children:[(0,t.jsx)(L,{variant:"outline",onClick:r(()=>p(!1),"onClick"),children:"Cancel"}),(0,t.jsx)(L,{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)(Es,{className:"mt-0.5 h-4 w-4 shrink-0 text-amber-700"}),(0,t.jsxs)("div",{className:"space-y-1 text-sm",children:[(0,t.jsx)("p",{className:"font-medium text-foreground",children:"External adapters are alpha."}),(0,t.jsx)("p",{className:"text-muted-foreground",children:"The adapter plugin system is under active development. APIs and storage format may change. Use the power icon to hide adapters from agent menus without removing them."})]})]})}),(0,t.jsxs)("section",{className:"space-y-3",children:[(0,t.jsxs)("div",{className:"flex items-center gap-2",children:[(0,t.jsx)(ym,{className:"h-5 w-5 text-muted-foreground"}),(0,t.jsx)("h2",{className:"text-base font-semibold",children:"External Adapters"})]}),D.length===0?(0,t.jsx)(rn,{className:"bg-muted/30",children:(0,t.jsxs)(Xa,{className:"flex flex-col items-center justify-center py-10",children:[(0,t.jsx)(ym,{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)(rn,{className:"block py-0",children:(0,t.jsx)("ul",{className:"divide-y",children:D.map(E=>{const z=E.overriddenBuiltin,$=z&&!!E.overridePaused,q=z?{...E,disabled:$??!1}:E;return(0,t.jsx)(pz,{adapter:q,canRemove:!0,onToggle:z?(U,O)=>I.mutate({type:U,paused:O}):(U,O)=>C.mutate({type:U,disabled:O}),onRemove:r(U=>x(U),"onRemove"),onReload:r(U=>R.mutate(U),"onReload"),onReinstall:E.isLocalPath?void 0:U=>v(E),isToggling:z?I.isPending:C.isPending,isReloading:R.isPending,isReinstalling:T.isPending,toggleTitleDisabled:z?"Pause external override":void 0,toggleTitleEnabled:z?"Resume external override":void 0,disabledBadgeLabel:z?"Override paused":void 0},E.type)})})})]}),(0,t.jsxs)("section",{className:"space-y-3",children:[(0,t.jsxs)("div",{className:"flex items-center gap-2",children:[(0,t.jsx)(ym,{className:"h-5 w-5 text-muted-foreground"}),(0,t.jsx)("h2",{className:"text-base font-semibold",children:"Built-in Adapters"})]}),A.length===0&&M.length===0?(0,t.jsx)("div",{className:"text-sm text-muted-foreground",children:"No built-in adapters found."}):(0,t.jsx)(rn,{className:"block py-0",children:(0,t.jsxs)("ul",{className:"divide-y",children:[A.map(E=>(0,t.jsx)(pz,{adapter:E,canRemove:!1,onToggle:r((z,$)=>C.mutate({type:z,disabled:$}),"onToggle"),onRemove:r(()=>{},"onRemove"),isToggling:B},E.type)),M.map(E=>(0,t.jsx)(pz,{adapter:{type:E.type,label:E.label,source:"builtin",modelsCount:0,loaded:!0,disabled:E.menuDisabled,capabilities:{supportsInstructionsBundle:!1,supportsSkills:!1,supportsLocalAgentJwt:!1,requiresMaterializedRuntimeSkills:!1,supportsAcp:!1}},canRemove:!1,onToggle:r((z,$)=>C.mutate({type:z,disabled:$}),"onToggle"),onRemove:r(()=>{},"onRemove"),isToggling:B,overriddenBy:E.overridePaused?void 0:E.overriddenBy},E.type))]})})]}),(0,t.jsx)(Qs,{open:f!==null,onOpenChange:r(E=>{E||x(null)},"onOpenChange"),children:(0,t.jsxs)(Js,{children:[(0,t.jsxs)(hn,{children:[(0,t.jsx)(Xs,{children:"Remove Adapter"}),(0,t.jsxs)(jn,{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(E=>E.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)(hr,{children:[(0,t.jsx)(L,{variant:"outline",onClick:r(()=>x(null),"onClick"),children:"Cancel"}),(0,t.jsx)(L,{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)(Cas,{adapter:b,open:b!==null,isReinstalling:T.isPending,onConfirm:r(()=>{b&&T.mutate(b.type,{onSettled:r(()=>v(null),"onSettled")})},"onConfirm"),onCancel:r(()=>v(null),"onCancel")})]})}r(ipe,"AdapterManager");function ope(){const e=va(),{companyPrefix:s,pluginId:n,pluginRoutePath:a}=e,i=e["*"],{companies:o,selectedCompanyId:l}=ps(),{setBreadcrumbs:c}=Bn(),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}=Z({queryKey:P.plugins.uiContributions,queryFn:r(()=>Al.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 s9(j,a)!==null},[f,a]);if((0,m.useEffect)(()=>{if(x){if(v){c([{label:_as(x,i)}]);return}c([{label:"Plugins",href:"/company/settings/instance/plugins"},{label:x.pluginDisplayName}])}},[x,i,c,v]),!h)return u?(0,t.jsx)(Pu,{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)(Pu,{scope:"board"});const j=n?`/company/settings/instance/plugins/${n}`:"/company/settings/instance/plugins";return(0,t.jsx)(kn,{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)(L,{variant:"ghost",size:"sm",asChild:!0,children:(0,t.jsxs)(Ke,{to:p?`/${p}/dashboard`:"/dashboard",children:[(0,t.jsx)(Tl,{className:"h-4 w-4 mr-1"}),"Back"]})})}),(0,t.jsx)(Wu,{slot:x,context:b,className:"min-h-(--sz-200px)",missingBehavior:"placeholder"})]})}r(ope,"PluginPage");function _as(e,s){return Ias(s)??e.displayName??e.pluginDisplayName}r(_as,"resolveRouteSidebarPageTitle");function Ias(e){const s=(e??"").split("/").filter(Boolean).map(Aas);return s.length===0?null:s[0]==="page"&&s.length>1?lpe(s.slice(1).join("/"),{preserveCase:!0}):lpe(s[0]??null)}r(Ias,"titleFromRouteSplat");function lpe(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(lpe,"titleFromPath");function Aas(e){try{return decodeURIComponent(e)}catch{return e}}r(Aas,"decodeRouteSegment");var LC="w-full rounded-md border border-border bg-background px-2.5 py-1.5 text-sm leading-5 outline-none focus-visible:ring-2 focus-visible:ring-ring",cpe=r(e=>e.status==="fail"||e.checks.some(s=>s.code==="adapter_auth_missing"),"blocking");function Tas(){const{selectedCompanyId:e}=ps(),[s]=fi();return e?(0,t.jsx)(Ras,{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(Tas,"NewAgentSetup");function Ras({companyId:e,name:s,adapterType:n,runnerProvider:a,createdAgentId:i}){const o=Mn(),l=Dt(),{openNewIssue:c}=Qo(),d=$Se(`${e}:new-agent`),u=n==="paperclip_runner",h=u?a==="grok"?"grok_local":a==="claude"?"claude_local":a==="opencode"?"opencode_local":"codex_local":n,p=h==="claude_local"||h==="codex_local"||h==="grok_local"?h:null,f=h==="opencode_local"||h==="pi_local",x=DZe(h),b=f||h==="hermes_local",v=b||!!ate[n],j=!["cursor_cloud","hermes_gateway"].includes(n),[N,w]=(0,m.useState)(""),[k,S]=(0,m.useState)(""),[C,I]=(0,m.useState)(""),[R,T]=(0,m.useState)("kimi"),[A,D]=(0,m.useState)(i?"saved":p?"connect":"runtime"),[M,B]=(0,m.useState)(""),E=u?[]:S5(n,M),[z,$]=(0,m.useState)(""),[q,U]=(0,m.useState)(!1),[O,K]=(0,m.useState)(""),[H,ee]=(0,m.useState)("openrouter"),[se,ne]=(0,m.useState)(""),[fe,X]=(0,m.useState)(null),[re,oe]=(0,m.useState)(()=>h==="opencode_local"?{provider:"openrouter",method:"api_key",mode:"responsible_user"}:void 0),[G,Y]=(0,m.useState)(null),Q=re??G?.aiConnection,[te,ae]=(0,m.useState)(""),[le,he]=(0,m.useState)(""),[ce,ge]=(0,m.useState)(null),me=Z({queryKey:P.agents.detail(i??"new"),queryFn:r(()=>$t.get(i,e),"queryFn"),enabled:!!i,retry:!1}),ie=ce??(me.data?.companyId===e?me.data:null),[ue,ke]=(0,m.useState)(!1),[be,Ie]=(0,m.useState)("idle"),[Ue,at]=(0,m.useState)(null),[dt,de]=(0,m.useState)(null),Be=(0,m.useRef)(0),pt=(0,m.useRef)(!1);(0,m.useEffect)(()=>()=>{Be.current++},[]);const vt=r(()=>{Be.current++,at(null),Ie("idle"),de(null)},"resetTest"),Le=Z({queryKey:P.adapters.all,queryFn:uh.list}),Qe=Z({queryKey:P.agents.list(e),queryFn:r(()=>$t.list(e),"queryFn")}),ut=Z({queryKey:P.environments.list(e),queryFn:r(()=>Pi.list(e),"queryFn")}),Ye=Z({queryKey:P.instance.settings,queryFn:Nr.get}),it=Z({queryKey:P.instance.experimentalSettings,queryFn:Nr.getExperimental}),kt=Z({queryKey:P.instance.generalSettings,queryFn:Nr.getGeneral}),tt=Z({queryKey:P.environments.capabilities(e),queryFn:r(()=>Pi.capabilities(e),"queryFn")}),Pe=Z({queryKey:P.agents.adapterModels(e,h,null,Q?.provider),queryFn:r(()=>$t.adapterModels(e,h,{provider:Q?.provider}),"queryFn"),enabled:!!h&&j,retry:!1}),Ce=Z({queryKey:P.secrets.list(e),queryFn:r(()=>vr.list(e),"queryFn"),enabled:v&&n!=="cursor_cloud"}),He=Z({queryKey:P.secrets.myUserSecrets(e),queryFn:r(()=>vr.listMyUserSecrets(e),"queryFn"),enabled:v&&n!=="cursor_cloud",retry:!1}),Je=DW(kt.data?.executionMode,ut.data??[]),lt=it.data?.enableManagedSandboxOnly===!0;let Ee=null,Xe=null;try{Ee=Je.forced?Je.kubernetesEnvironment?.id??null:iN({agentDefaultEnvironmentId:O||null,instanceDefaultEnvironmentId:Ye.data?.defaultEnvironmentId??null,localDefaultEnvironmentId:lN(ut.data??[]),managedSandboxOnly:lt,managedSandboxEnvironmentId:oN(ut.data??[]),visibleEnvironmentIds:(ut.data??[]).map(Fe=>Fe.id)})}catch(Fe){Xe=Fe instanceof Error?Fe.message:"Could not resolve the environment."}const Ae=ut.data?.find(Fe=>Fe.id===Ee),De=typeof Ae?.config?.provider=="string"?Ae.config.provider:"",_t=Ae?.driver==="sandbox"&&tt.data?.sandboxProviders?.[De]?.supportsLoginPty===!0,ye=ate[n]??x[H]??"API_KEY",gt=He.data?.find(Fe=>Fe.definition.key===ye&&Fe.secret),We=Ce.data?.find(Fe=>Fe.key===ye&&Fe.status==="active"),Ot=n==="cursor_cloud"?null:fe??(We?{type:"secret_ref",secretId:We.id,version:"latest"}:gt?{type:"user_secret_ref",key:ye,version:"latest"}:null),zt=n==="kimi_local"&&!!(se.trim()||Ot),Cs=!!$c(),ze=OSe(n,{cloud:Cs,nativeRunnerEnabled:it.data?.enableNativeRunner===!0})&&Le.data?.some(Fe=>Fe.type===n&&Fe.loaded&&!Fe.disabled&&!Ch(n).comingSoon),ft=!!(ze&&!Xe&&!ut.isPending&&!Ye.isPending&&!it.isPending&&!kt.isPending&&!Qe.isPending&&!tt.isPending&&!ut.error&&!Ye.error&&!it.error&&!kt.error&&!Qe.error&&!tt.error&&(!(lt||Je.forced)||Ee)),Ut=be==="running"||ue;function Ns(Fe=G,st=Ot){const xt={...nb,adapterType:n,model:M||(h==="codex_local"?nN:""),thinkingEffort:z,dangerouslyBypassSandbox:n==="codex_local",envBindings:Fe?.env??{},...u?{adapterSchemaValues:{provider:a==="claude"||a==="grok"?"acpx":a,...a==="claude"||a==="grok"?{acpxAgent:a}:{}}}:{}},Oe=aS(n).buildAdapterConfig(xt);return u&&Object.assign(Oe,{provider:a==="claude"||a==="grok"?"acpx":a,...a==="claude"||a==="grok"?{acpxAgent:a}:{},...M?{model:M}:{}}),!Q&&!Fe?.aiConnection&&v&&st&&(n==="hermes_gateway"?Oe.apiKey=st:Oe.env={...Oe.env??{},[ye]:st}),n==="cursor_cloud"&&Object.assign(Oe,{repoUrl:te.trim(),...le.trim()?{repoStartingRef:le.trim()}:{}}),n==="hermes_gateway"&&(Oe.apiBaseUrl=N.trim()),zt&&(delete Oe.model,Oe.env={...Oe.env??{},KIMI_MODEL_NAME:{type:"plain",value:k.trim()},KIMI_MODEL_PROVIDER_TYPE:{type:"plain",value:R},...C.trim()?{KIMI_MODEL_BASE_URL:{type:"plain",value:C.trim()}}:{}}),Oe}r(Ns,"buildConfig");function Is(Fe=G){if(f&&(!M.trim()||!M.includes("/")))throw new Error("Choose or enter a model in provider/model format.");if(n==="cursor_cloud"&&!/^https:\/\/github\.com\/[^/]+\/[^/]+/.test(te.trim()))throw new Error("Enter a GitHub repository URL.");if(["cursor_cloud","hermes_gateway"].includes(n)&&!se.trim()&&!Ot)throw new Error(n==="cursor_cloud"?"Enter a Cursor API key.":`Enter ${ye} or select an organization secret.`);if(n==="hermes_gateway")try{const st=new URL(N.trim());if(!["https:","http:"].includes(st.protocol))throw new Error}catch{throw new Error("Enter the Hermes API base URL.")}if(zt&&!k.trim())throw new Error("Enter the Kimi API model name.");return Ns(Fe)}r(Is,"preparedConfig");function St(Fe=G){return Q||Fe?.aiConnection?{}:{...Fe?.credentials,...v&&se.trim()?{[ye]:se.trim()}:{}}}r(St,"pendingCredentials");async function ds(Fe=G){if(!ft)return!1;const st=++Be.current;Ie("running"),at(null),de(null);try{const xt=await Is(Fe),Oe=await jNe({companyId:e,adapterType:n,providerAdapter:h,adapterConfig:xt,testCredentials:St(Fe),aiConnection:re??Fe?.aiConnection,environmentId:Ee});return st!==Be.current?!1:(at(Oe),Ie(cpe(Oe)?"fail":Oe.status),!cpe(Oe)&&(!p||Oe.checks.some(Bt=>Bt.code.endsWith("hello_probe_passed"))))}catch(xt){return st===Be.current&&(de(xt instanceof Error?xt.message:"Could not test the agent."),Ie("fail")),!1}}r(ds,"runTest");async function $e(){if(pt.current||i||ie||!ft||!s.trim()||be==="running"||be==="fail"||p&&!G)return;pt.current=!0,ke(!0),de(null);const Fe=[];let st=!1;try{const xt=Is(),Oe=St();if(Object.keys(Oe).length&&!await ds())return;for(const[Yt,hs]of Object.entries(Oe)){const Ts=await(p?ENe:PZe)(e,Yt,hs);Fe.push(Ts),n==="hermes_gateway"&&Yt==="API_SERVER_KEY"?xt.apiKey=Ts.binding:xt.env={...xt.env??{},[Yt]:Ts.binding}}const Bt=Qe.data??[],wt=Bt.find(Yt=>Yt.role==="ceo"&&Yt.status!=="terminated"),Xt=await $t.hire(e,{name:s.trim(),appearance:d.appearance,role:Bt.length?"general":"ceo",...wt?{reportsTo:wt.id}:{},adapterType:n,adapterConfig:xt,defaultEnvironmentId:O||(Je.forced||lt?Ee:null),runtimeConfig:{...C_e({heartbeatEnabled:!1}),...Q?{aiConnection:Q}:{}},budgetMonthlyCents:0,...G?.storedSessionId?{storedSessionId:G.storedSessionId}:{},...G?.applyStoredClaudeLogin?{applyStoredClaudeLogin:!0}:{}});st=!0,ne(""),Y(null),ge(Xt.agent),d.clear(),D("saved"),o(`/agents/new?${new URLSearchParams({name:Xt.agent.name,adapterType:n,runnerProvider:a,createdAgentId:Xt.agent.id})}`,{replace:!0}),l.setQueryData(P.agents.detail(Xt.agent.id),Xt.agent),await Promise.all([l.invalidateQueries({queryKey:P.agents.list(e)}),l.invalidateQueries({queryKey:P.approvals.list(e)})])}catch(xt){de(xt instanceof Error?xt.message:"Could not create the agent.")}finally{if(!st)try{await Promise.all(Fe.map(xt=>xt.remove()))}catch{de(xt=>`${xt?`${xt} `:""}Could not remove an unused setup credential. Remove it from Secrets before retrying.`)}l.invalidateQueries({queryKey:P.secrets.myUserSecrets(e)}),l.invalidateQueries({queryKey:P.secrets.list(e)}),pt.current=!1,ke(!1)}}if(r($e,"finish"),i&&!ie)return(0,t.jsx)("p",{role:me.error?"alert":"status",className:"text-sm text-muted-foreground",children:me.error?"Could not load the created agent. Return to Agents to view it.":"Loading your agent…"});if(!s||!n)return(0,t.jsx)(FSe,{open:!0,initialAdapter:n,onClose:r(()=>o("/agents/all"),"onClose"),onContinue:r(Fe=>o(`/agents/new?${new URLSearchParams(Fe)}`,{replace:!0}),"onContinue")});const xe=[...p?["connect"]:[],"runtime","saved"],Qt={connect:"Connect",runtime:"Configure",saved:"Confirmation"},Mt=ie?.defaultEnvironmentId?ut.data?.find(Fe=>Fe.id===ie.defaultEnvironmentId):Ae,rs=ie?.adapterConfig?.env?.KIMI_MODEL_NAME,ws=ie?.adapterConfig?.model||(typeof rs=="string"?rs:rs?.value)||M||"Default",Bs=n==="cursor_cloud"?"Cursor Cloud":n==="hermes_gateway"?"Hermes Gateway":Mt?Qv(Mt):"Local machine",er=Le.error??ut.error??Ye.error??it.error??kt.error??Qe.error??tt.error;return(0,t.jsx)(iNe,{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)(F_,{appearance:ie?.appearance??d.appearance,size:256,className:"size-48",trackingScope:"page",state:ie||be==="pass"?"success":be==="running"?"loading":"sleepy",muted:!ie&&be!=="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)(OW,{type:h}),(0,t.jsx)("span",{children:Ch(h).label}),u&&(0,t.jsxs)("span",{children:["·"," ",a==="codex"?"Native app server runner":"Paperclip Runner"]})]})]})]}),Xe&&!ut.isPending&&(0,t.jsx)("p",{role:"alert",className:"text-sm text-destructive",children:Xe}),er&&(0,t.jsx)("p",{role:"alert",className:"text-sm text-destructive",children:er.message}),Le.data&&!ze&&(0,t.jsx)("p",{role:"alert",className:"text-sm text-destructive",children:"This adapter is unavailable. Choose an enabled adapter."}),(lt||Je.forced)&&!ut.isPending&&!Ee&&(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:xe.map((Fe,st)=>(0,t.jsx)("li",{children:(0,t.jsxs)("button",{type:"button","aria-current":Fe===A?"step":void 0,disabled:Ut||!!ie||st>xe.indexOf(A),onClick:r(()=>D(Fe),"onClick"),className:W("flex w-full items-center gap-3 rounded-md px-3 py-3 text-left text-sm",Fe===A?"bg-accent font-medium":"text-muted-foreground"),children:[(0,t.jsx)("span",{className:W("flex size-6 shrink-0 items-center justify-center rounded-full border text-xs",Fe===A?"border-foreground bg-foreground text-background":"border-border"),children:st+1}),Qt[Fe]]})},Fe))})}),(0,t.jsx)("div",{className:"min-w-0 flex-1",children:(0,t.jsx)(rS,{mode:"wait",initial:!1,children:(0,t.jsx)(Il.div,{...JZe,children:A==="connect"&&p?(0,t.jsxs)(Kpt,{className:"mx-auto",children:[(0,t.jsx)("div",{className:"mb-8",children:(0,t.jsx)(__e,{title:"Connect a model",lede:`Connect ${s} to ${p==="claude_local"?"Claude":p==="grok_local"?"Grok":"OpenAI"}.`,center:!0})}),(0,t.jsx)("div",{className:"mb-5",children:(0,t.jsx)(Ss,{label:"Environment",children:(0,t.jsxs)("select",{"aria-label":"Environment",className:LC,value:O,disabled:Ut||Je.forced,onChange:r(Fe=>{K(Fe.target.value),Y(null),vt()},"onChange"),children:[(0,t.jsxs)("option",{value:"",children:["Default: ",Bs]}),(ut.data??[]).filter(Fe=>Fe.status==="active"&&(!lt||Fe.driver!=="local")).map(Fe=>(0,t.jsx)("option",{value:Fe.id,children:Qv(Fe)},Fe.id))]})})}),(0,t.jsx)(USe,{companyId:e,adapterType:p,environmentId:Ee,canLogin:_t,localEnvironment:Ae?.driver==="local",onBack:r(()=>o("/agents/all"),"onBack"),testConnection:ds,testError:dt??(Ue?.checks.find(Fe=>Fe.level==="error")??Ue?.checks.find(Fe=>Fe.code.includes("hello_probe")&&Fe.level==="warn"))?.message,onConnected:r(Fe=>{Y(Fe),vt(),D("runtime")},"onConnected")},Ee??"local")]}):A==="saved"&&ie?(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)(gs,{className:"size-5"}),ie.status==="pending_approval"?"Agent submitted for approval":"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:Ch(n).label}),j&&(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(ws)})]}),(0,t.jsx)("dt",{className:"text-muted-foreground",children:"Environment"}),(0,t.jsx)("dd",{children:Bs})]}),(0,t.jsx)("p",{className:"text-sm text-muted-foreground",children:ie.status==="pending_approval"?"An organization administrator must approve this agent before it can 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)(L,{variant:"outline",onClick:r(()=>o(`${Cm(ie)}/runtime`),"onClick"),children:[(0,t.jsx)($7,{className:"size-4"}),"Edit configuration"]}),(0,t.jsxs)(L,{disabled:ie.status==="pending_approval",onClick:r(()=>c({assigneeAgentId:ie.id,status:"todo"}),"onClick"),children:["Assign ",ie.name," a Task",(0,t.jsx)(pl,{className:"size-4"})]})]})]}):(0,t.jsxs)("form",{className:"space-y-8",onSubmit:r(Fe=>{Fe.preventDefault(),$e()},"onSubmit"),children:[(0,t.jsx)("h2",{className:"text-xl font-semibold",children:"Configure your agent"}),(0,t.jsxs)("fieldset",{disabled:Ut,className:"space-y-8",children:[(0,t.jsxs)("section",{className:"space-y-5",children:[(0,t.jsx)("h3",{className:"text-sm font-semibold",children:"Runtime"}),vW(h)&&(G&&!Q?(0,t.jsxs)("div",{className:"space-y-3",children:[(0,t.jsx)("p",{className:"text-sm text-muted-foreground",children:"Using the connection selected in the Connect step."}),(0,t.jsx)(L,{type:"button",variant:"outline",onClick:r(()=>D("connect"),"onClick"),children:"Change connection"})]}):(0,t.jsx)(yNe,{companyId:e,agentName:s,adapterType:h,model:M,environmentId:Ee??void 0,value:Q,onChange:r(Fe=>{Fe.mode!=="router"&&oe(Fe),vt()},"onChange")})),Pe.error&&(0,t.jsx)("p",{role:"alert",className:"text-sm text-destructive",children:"Could not load models. Retry or enter a model ID manually."}),(j&&!zt||E.length>0)&&(0,t.jsxs)("div",{className:"grid items-start gap-5 sm:grid-cols-2",children:[j&&!zt&&(0,t.jsx)($W,{models:Pe.data??[],value:M,onChange:r(Fe=>{B(Fe),z&&!S5(n,Fe).includes(z)&&$("");const st=Fe.split("/")[0];f&&RNe[st]&&st!==H&&(ee(st),ne(""),X(null)),vt()},"onChange"),open:q,onOpenChange:U,allowDefault:!f,required:f,creatable:!0,groupByProvider:f,preserveOrder:_W(h)}),E.length>0&&(0,t.jsx)(Ss,{label:"Thinking effort",children:(0,t.jsxs)("select",{"aria-label":"Thinking effort",className:LC,value:z,onChange:r(Fe=>{$(Fe.target.value),vt()},"onChange"),children:[(0,t.jsx)("option",{value:"",children:"Auto"}),E.map(Fe=>(0,t.jsx)("option",{value:Fe,children:Fe},Fe))]})})]}),ite[n]&&(0,t.jsx)("p",{className:"text-sm text-muted-foreground",children:ite[n]}),j&&Pe.error&&(0,t.jsx)("p",{className:"text-xs text-muted-foreground",children:"Couldn’t load models. You can enter a model ID manually."}),v&&!Q&&(0,t.jsxs)("div",{className:"grid gap-5 sm:grid-cols-2",children:[b&&(0,t.jsx)(Ss,{label:"API key provider",children:(0,t.jsx)("select",{"aria-label":"API key provider",className:LC,value:H,onChange:r(Fe=>{ee(Fe.target.value),B(""),ne(""),X(null),vt()},"onChange"),children:Object.keys(x).map(Fe=>(0,t.jsx)("option",{value:Fe,children:Fe==="openrouter"?"OpenRouter":Fe==="openai"?"OpenAI":Fe==="anthropic"?"Anthropic":{google:"Google",xai:"xAI",groq:"Groq",opencode:"OpenCode"}[Fe]??Fe},Fe))})}),(0,t.jsx)("div",{className:n==="cursor_cloud"?"sm:col-span-2":void 0,children:(0,t.jsx)(Ss,{label:ye,children:(0,t.jsxs)("div",{className:"flex items-center gap-3",children:[(0,t.jsx)(ht,{"aria-label":ye,type:"password",autoComplete:"off",value:se,onChange:r(Fe=>{ne(Fe.target.value),X(null),vt()},"onChange"),placeholder:Ot?"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:b?"sm:col-span-2":void 0,children:(0,t.jsx)(Ss,{label:"Or use an organization secret",children:(0,t.jsx)(TW,{secretId:Ot&&typeof Ot=="object"&&Ot.type==="secret_ref"?Ot.secretId:"",secrets:Ce.data??[],disabled:Ut,onSelect:r(Fe=>{X({type:"secret_ref",secretId:Fe,version:"latest"}),ne(""),vt()},"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.",f&&` Use a ${H}/model ID.`]})]}),n==="hermes_gateway"&&(0,t.jsx)(Ss,{label:"Hermes API base URL",children:(0,t.jsx)(ht,{"aria-label":"Hermes API base URL",value:N,onChange:r(Fe=>{w(Fe.target.value),vt()},"onChange"),placeholder:"https://hermes.example.com"})}),zt&&(0,t.jsxs)("div",{className:"grid gap-5 sm:grid-cols-2",children:[(0,t.jsx)(Ss,{label:"Kimi API model name",children:(0,t.jsx)(ht,{"aria-label":"Kimi API model name",value:k,onChange:r(Fe=>{S(Fe.target.value),vt()},"onChange"),placeholder:"kimi-for-coding"})}),(0,t.jsx)(Ss,{label:"Kimi API protocol",children:(0,t.jsx)("select",{"aria-label":"Kimi API protocol",className:LC,value:R,onChange:r(Fe=>{T(Fe.target.value),vt()},"onChange"),children:["kimi","anthropic","openai"].map(Fe=>(0,t.jsx)("option",{children:Fe},Fe))})}),(0,t.jsx)(Ss,{label:"Kimi API base URL",hint:"Optional override for your provider endpoint.",children:(0,t.jsx)(ht,{"aria-label":"Kimi API base URL",value:C,onChange:r(Fe=>{I(Fe.target.value),vt()},"onChange"),placeholder:"Provider default"})})]}),n==="cursor_cloud"&&(0,t.jsxs)("div",{className:"grid gap-5 sm:grid-cols-2",children:[(0,t.jsx)(Ss,{label:"GitHub repository",children:(0,t.jsx)(ht,{"aria-label":"GitHub repository",value:te,onChange:r(Fe=>{ae(Fe.target.value),vt()},"onChange"),placeholder:"https://github.com/your-org/repo"})}),(0,t.jsx)(Ss,{label:"Branch",children:(0,t.jsx)(ht,{"aria-label":"Branch",placeholder:"Repository default",value:le,onChange:r(Fe=>{he(Fe.target.value),vt()},"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:LC,value:O,disabled:Je.forced,onChange:r(Fe=>{K(Fe.target.value),Y(null),vt(),p&&D("connect")},"onChange"),children:[(0,t.jsxs)("option",{value:"",children:["Default: ",Bs]}),(ut.data??[]).filter(Fe=>Fe.status==="active"&&(!lt||Fe.driver!=="local")).map(Fe=>(0,t.jsx)("option",{value:Fe.id,children:Qv(Fe)},Fe.id))]})]})]}),(0,t.jsx)(PNe,{state:be,result:Ue,error:dt,disabled:!ft||Ut,onTest:r(()=>{ds()},"onTest")}),dt&&be!=="fail"&&(0,t.jsx)("p",{role:"alert",className:"text-sm text-destructive",children:dt}),(0,t.jsxs)("div",{className:"flex justify-between border-t border-border py-5",children:[p?(0,t.jsxs)(L,{type:"button",variant:"ghost",disabled:Ut,onClick:r(()=>D("connect"),"onClick"),children:[(0,t.jsx)(Tl,{className:"size-4"}),"Connection"]}):(0,t.jsx)("span",{}),(0,t.jsxs)(L,{type:"submit",disabled:!ft||Ut||be==="fail"||!!(p&&!G),children:[ue?"Creating…":"Finish setup",(0,t.jsx)(gs,{className:"size-4"})]})]})]})},A)})})]})]})})}r(Ras,"Setup");function Eas(){const{setBreadcrumbs:e}=Bn();return(0,m.useEffect)(()=>{e([{label:"Agents",href:"/agents"},{label:"New agent"}])},[e]),(0,t.jsx)(Tas,{})}r(Eas,"NewAgent");var nM="paperclip:pending-invite-token";function qG(){return typeof window<"u"&&typeof window.localStorage<"u"}r(qG,"canUseStorage");function dpe(e){const s=e.trim();if(!(!s||!qG()))try{window.localStorage.setItem(nM,s)}catch{}}r(dpe,"rememberPendingInviteToken");function KR(e){if(qG())try{const s=window.localStorage.getItem(nM);if(e&&s!==e.trim())return;window.localStorage.removeItem(nM)}catch{}}r(KR,"clearPendingInviteToken");function Pas(){if(!qG())return null;try{const e=window.localStorage.getItem(nM)?.trim();return e?`/invite/${e}`:null}catch{return null}}r(Pas,"getRememberedInvitePath");var upe=[" ",".","·","▪","▫","○"],Mas=1e3/24,WR=[[" ╭────╮ "," ╭╯╭──╮│ "," │ │ ││ "," │ │ ││ "," │ │ ││ "," │ │ ││ "," │ ╰──╯│ "," ╰─────╯ "],[" ╭─────╮ "," │╭──╮╰╮ "," ││ │ │ "," ││ │ │ "," ││ │ │ "," ││ │ │ "," │╰──╯ │ "," ╰────╯ "]];function mpe(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(mpe,"measureChar");function Das(e){let s=0;for(const n of e)s=Math.max(s,n.length);return{width:s,height:e.length}}r(Das,"spriteSize");function Las(){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(E){const z=Math.floor(Math.max(0,Math.min(.999,E))*upe.length);return upe[z]??" "}r(w,"toGlyph");function k(){const E=Math.max(0,Math.ceil(n.clientWidth/Math.max(1,h))),z=Math.max(0,Math.ceil(n.clientHeight/Math.max(1,p)));if(E===d&&z===u)return;d=E,u=z;const $=d*u;f=new Float32Array($),x=new Float32Array(d),b=new Float32Array(u),v=new Uint16Array($),j=j.filter(q=>q.x>-q.width-2&&q.x<d+2&&q.y>-q.height-2&&q.y<u+2),N=""}r(k,"rebuildGrid");function S(){if(d<=0||u<=0){n.textContent="";return}const E=Array.from({length:u},()=>Array.from({length:d},()=>" "));for(let U=0;U<u;U++)for(let O=0;O<d;O++){const K=(Math.sin(O*.11+U*.04)+Math.cos(U*.08-O*.02))*.18+.22;E[U][O]=w(K)}const z=18,$=13;for(let U=1;U<u-9;U+=$){const O=Math.floor(U/$)%2===0?2:10;for(let K=O;K<d-10;K+=z){const H=WR[(K+U)%WR.length];for(let ee=0;ee<H.length;ee++){const se=H[ee];for(let ne=0;ne<se.length;ne++){const fe=se[ne]??" ";if(fe===" ")continue;const X=U+ee,re=K+ne;X<0||X>=u||re<0||re>=d||(E[X][re]=fe)}}}}const q=E.map(U=>U.join("")).join(`
772
772
  `);n.textContent=q,N=q}r(S,"drawStaticFrame");function C(){const E=WR[Math.floor(Math.random()*WR.length)],z=Das(E),$=Math.random();let q=0,U=0,O=0,K=0;$<.68?(q=Math.random()<.5?-z.width-1:d+1,U=Math.random()*Math.max(1,u-z.height),O=q<0?.04+Math.random()*.05:-(.04+Math.random()*.05),K=(Math.random()-.5)*.014):(q=Math.random()*Math.max(1,d-z.width),U=Math.random()<.5?-z.height-1:u+1,O=(Math.random()-.5)*.014,K=U<0?.028+Math.random()*.034:-(.028+Math.random()*.034)),j.push({x:q,y:U,vx:O,vy:K,life:0,maxLife:260+Math.random()*220,drift:(Math.random()-.5)*1.2,sprite:E,width:z.width,height:z.height})}r(C,"spawnClip");function I(E,z){const $=Math.round(E.x),q=Math.round(E.y);for(let U=0;U<E.sprite.length;U++){const O=E.sprite[U],K=q+U;if(!(K<0||K>=u))for(let H=0;H<O.length;H++){const ee=O[H]??" ";if(ee===" ")continue;const se=$+H;if(se<0||se>=d)continue;const ne=K*d+se,fe=ee==="│"||ee==="─"?.8:.92;f[ne]=Math.max(f[ne]??0,z*fe),v[ne]=ee.charCodeAt(0)}}}r(I,"stampClip");function R(E){if(!o||(s.current=requestAnimationFrame(R),E-l<Mas||d<=0||u<=0))return;const z=Math.min(2,l===0?1:(E-l)/16.6667);l=E,c+=z;const $=d*u,q=Math.max(3,Math.floor($/2200));for(;j.length<q;)C();for(let O=0;O<f.length;O++)f[O]*=.92;v.fill(0);for(let O=j.length-1;O>=0;O--){const K=j[O];K.life+=z;const H=Math.sin((K.y+K.drift+c*.12)*.09)*.0018,ee=Math.cos((K.x-K.drift-c*.09)*.08)*.0014;if(K.vx=(K.vx+H)*.998,K.vy=(K.vy+ee)*.998,K.x+=K.vx*z,K.y+=K.vy*z,K.life>=K.maxLife||K.x<-K.width-2||K.x>d+2||K.y<-K.height-2||K.y>u+2){j.splice(O,1);continue}const se=K.life/K.maxLife;I(K,se<.12?se/.12:se>.88?(1-se)/.12:1)}for(let O=0;O<d;O++)x[O]=Math.sin(O*.08+c*.06);for(let O=0;O<u;O++)b[O]=Math.cos(O*.1-c*.05);let U="";for(let O=0;O<u;O++){for(let K=0;K<d;K++){const H=O*d+K,ee=v[H];if(ee>0){U+=String.fromCharCode(ee);continue}const se=(x[K]+b[O])*.08+.1,ne=Math.max(f[H]??0,se*.45);U+=w(ne)}O<u-1&&(U+=`
773
- `)}U!==N&&(n.textContent=U,N=U)}r(R,"step");function T(){const E=d>0&&u>0;if(a.matches){o&&(o=!1,s.current!==null&&cancelAnimationFrame(s.current),s.current=null),E&&S();return}if(!i||!E){o&&(o=!1,s.current!==null&&cancelAnimationFrame(s.current),s.current=null);return}o||(o=!0,l=0,s.current=requestAnimationFrame(R))}r(T,"syncLoop");const A=new ResizeObserver(()=>{const E=mpe(n);h=E.w,p=E.h,k(),T()});A.observe(n);const D=r(()=>{i=document.visibilityState!=="hidden",T()},"onVisibilityChange");document.addEventListener("visibilitychange",D);const M=r(()=>{T()},"onMotionChange");a.addEventListener("change",M);const B=mpe(n);return h=B.w,p=B.h,k(),T(),()=>{o=!1,s.current!==null&&cancelAnimationFrame(s.current),A.disconnect(),document.removeEventListener("visibilitychange",D),a.removeEventListener("change",M)}},[]),(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(Las,"AsciiArtAnimation");function $as({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($as,"PaperclipLockup");function Oas(){const e=Dt(),s=Mn(),[n]=fi(),[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)(()=>yCe(n.get("next")||Pas()||"/"),[n]),v=Z({queryKey:P.health,queryFn:r(()=>tu.get(),"queryFn"),retry:!1}),{data:j,isLoading:N,error:w}=Z({queryKey:P.auth.session,queryFn:r(()=>Oa.getSession(),"queryFn"),retry:!1});(0,m.useEffect)(()=>{j&&(gV(),s(b,{replace:!0}))},[j,s,b]);const k=je({mutationFn:r(async()=>{if(a==="sign_in"){await Oa.signInEmail({email:c.trim(),password:u});return}await Oa.signUpEmail({name:o.trim(),email:c.trim(),password:u})},"mutationFn"),onSuccess:r(async()=>{f(null),await e.invalidateQueries({queryKey:P.auth.session}),await e.invalidateQueries({queryKey:P.health}),await e.resetQueries({queryKey:P.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)($m,{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)(bV,{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)(yk,{})}),(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)($as,{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)(L,{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)(Las,{})})]})}r(Oas,"AuthPage");function Fas(){const e=Dt(),s=va(),[n]=fi(),a=(s.token??"").trim(),i=(n.get("code")??"").trim(),o=(0,m.useMemo)(()=>`/board-claim/${encodeURIComponent(a)}${i?`?code=${encodeURIComponent(i)}`:""}`,[a,i]),l=Z({queryKey:P.auth.session,queryFn:r(()=>Oa.getSession(),"queryFn"),retry:!1}),c=Z({queryKey:["board-claim",a,i],queryFn:r(()=>pr.getBoardClaimStatus(a,i),"queryFn"),enabled:a.length>0&&i.length>0,retry:!1}),d=je({mutationFn:r(()=>pr.claimBoard(a,i),"mutationFn"),onSuccess:r(async()=>{await e.invalidateQueries({queryKey:P.auth.session}),await e.invalidateQueries({queryKey:P.health}),await e.invalidateQueries({queryKey:P.companies.all}),await e.invalidateQueries({queryKey:P.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)(rn,{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)(rn,{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)(L,{asChild:!0,className:"mt-4",children:(0,t.jsx)(Ke,{to:"/",children:"Open board"})})]})}):l.data?(0,t.jsx)("div",{className:"mx-auto max-w-xl py-10",children:(0,t.jsxs)(rn,{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)(L,{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)(rn,{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)(L,{asChild:!0,className:"mt-4",children:(0,t.jsx)(Ke,{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(Fas,"BoardClaimPage");function Bas(){const e=Dt(),s=va(),[n]=fi(),a=(s.id??"").trim(),i=(n.get("token")??"").trim(),o=(0,m.useMemo)(()=>`/cli-auth/${encodeURIComponent(a)}${i?`?token=${encodeURIComponent(i)}`:""}`,[a,i]),l=Z({queryKey:P.auth.session,queryFn:r(()=>Oa.getSession(),"queryFn"),retry:!1}),c=Z({queryKey:["cli-auth-challenge",a,i],queryFn:r(()=>pr.getCliAuthChallenge(a,i),"queryFn"),enabled:a.length>0&&i.length>0,retry:!1}),d=je({mutationFn:r(()=>pr.approveCliAuthChallenge(a,i),"mutationFn"),onSuccess:r(async()=>{await e.invalidateQueries({queryKey:P.auth.session}),await c.refetch()},"onSuccess")}),u=je({mutationFn:r(()=>pr.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)(rn,{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)(rn,{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)(rn,{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)(rn,{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)(L,{asChild:!0,className:"mt-4",children:(0,t.jsx)(Ke,{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)(rn,{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)(L,{onClick:r(()=>d.mutate(),"onClick"),disabled:!h.canApprove||d.isPending||u.isPending,children:d.isPending?"Approving...":"Approve CLI access"}),(0,t.jsx)(L,{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(Bas,"CliAuthPage");var zas=VLe.filter(e=>e!=="paperclip_runner"),hpe=new Set(["claude_local","codex_local","gemini_local","kimi_local","opencode_local","pi_local","cursor"]);function qas(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(qas,"readNestedString");var Sw="w-full border border-zinc-800 bg-zinc-950 px-3 py-2 text-sm text-zinc-100 outline-none focus:border-zinc-500",ppe="border border-zinc-800 bg-zinc-950/95 p-6",fpe="flex-1 border px-3 py-2 text-sm transition-colors";function Uas(e){return e?e.charAt(0).toUpperCase()+e.slice(1):null}r(Uas,"formatHumanRole");function b4e(e){if(!e||typeof e!="object")return null;const s=e.code;return typeof s=="string"&&s.trim().length>0?s:null}r(b4e,"getAuthErrorCode");function Kas(e){if(!(e instanceof Error))return null;const s=e.message.trim();return s.length>0?s:null}r(Kas,"getAuthErrorMessage");function Was(e,s,n){const a=b4e(e),i=Kas(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(Was,"mapInviteAuthFeedback");function xpe(e){return!!(e&&typeof e=="object"&&"bootstrapAccepted"in e)}r(xpe,"isBootstrapAcceptancePayload");function Vas(e,s){return!e||typeof e!="object"||s?!1:e.status==="approved"}r(Vas,"isApprovedHumanJoinPayload");function V8({companyDisplayName:e,companyLogoUrl:s,className:n}){return(0,t.jsx)(eS,{companyName:e,logoUrl:s,logoFit:"contain",className:n})}r(V8,"InviteCompanyLogo");function gpe({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)(V8,{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(gpe,"AwaitingJoinApprovalPanel");function Has(){const e=Dt(),s=Mn(),{setSelectedCompanyId:n}=ps(),a=(va().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),[I,R]=(0,m.useState)(null),[T,A]=(0,m.useState)(!1),D="invite-auth-error",M=Z({queryKey:P.health,queryFn:r(()=>tu.get(),"queryFn"),retry:!1}),B=Z({queryKey:P.auth.session,queryFn:r(()=>Oa.getSession(),"queryFn"),retry:!1}),E=Z({queryKey:P.access.invite(a),queryFn:r(()=>pr.getInvite(a),"queryFn"),enabled:a.length>0,retry:!1}),z=e7({enabled:!!B.data&&!!E.data?.companyId,staleTime:0}),$=M.data?.deploymentMode!=="local_trusted"?z.isFetchedAfterMount:!0,q=$?z.data?.companies??[]:[];(0,m.useEffect)(()=>{a&&dpe(a)},[a]),(0,m.useEffect)(()=>{A(!1)},[a]),(0,m.useEffect)(()=>{if(!$)return;const ge=z.data?.companies;!ge||!E.data?.companyId||ge.some(me=>me.id===E.data.companyId)&&KR(a)},[z.data,E.data,$,a]);const U=E.data,O=!!B.data&&!!U?.companyId&&!$,K=!!U?.companyId&&q.some(ge=>ge.id===U?.companyId),H=U?.companyName?.trim()||"this Paperclip company",ee=U?.companyLogoUrl?.trim()||null,se=U?.invitedByUserName?.trim()||null,ne=U?.inviteMessage?.trim()||null,fe=Uas(U?.humanRole),X=U?.joinRequestStatus??null,re=U?.joinRequestType??null,oe=re==="human"&&(X==="pending_approval"||X==="approved"),G=M.data?.deploymentMode==="authenticated"&&!B.data&&U?.allowedJoinTypes!=="agent",Y=U?.inviteType!=="bootstrap_ceo"&&U?.allowedJoinTypes==="agent",Q=!!B.data&&!Y&&U?.inviteType!=="bootstrap_ceo"&&(!X||oe)&&!O&&!K&&!w&&S===null,te=B.data?.user.name?.trim()||B.data?.user.email?.trim()||"this account",ae=d.trim().length>0&&h.trim().length>0&&(i==="sign_in"||l.trim().length>0&&h.trim().length>=8),le=je({mutationFn:r(async()=>{if(!U)throw new Error("Invite not found");if(O)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 U.inviteType==="bootstrap_ceo"||U.allowedJoinTypes!=="agent"?pr.acceptInvite(a,{requestType:"human"}):pr.acceptInvite(a,{requestType:"agent",agentName:f.trim(),adapterType:b,capabilities:j.trim()||null})},"mutationFn"),onSuccess:r(async ge=>{C(null),KR(a);const me=xpe(ge);k({kind:me?"bootstrap":"join",payload:ge}),await e.invalidateQueries({queryKey:P.auth.session}),await e.invalidateQueries({queryKey:P.access.currentBoardAccess}),await e.invalidateQueries({queryKey:P.companies.all}),U?.companyId&&Vas(ge,Y)&&(n(U.companyId,{source:"manual"}),s("/",{replace:!0}))},"onSuccess"),onError:r(ge=>{C(ge instanceof Error?ge.message:"Failed to accept invite")},"onError")});(0,m.useEffect)(()=>{!Q||T||le.isPending||(A(!0),C(null),le.mutate())},[le,T,Q]);const he=je({mutationFn:r(async()=>{if(i==="sign_in"){await Oa.signInEmail({email:d.trim(),password:h});return}await Oa.signUpEmail({name:l.trim(),email:d.trim(),password:h})},"mutationFn"),onSuccess:r(async()=>{R(null),dpe(a),await e.invalidateQueries({queryKey:P.auth.session}),await e.invalidateQueries({queryKey:P.health}),await e.invalidateQueries({queryKey:P.access.currentBoardAccess});const{companies:ge}=await l$e(e);if(U?.companyId&&ge.some(me=>me.id===U.companyId)){KR(a),n(U.companyId,{source:"manual"}),s("/",{replace:!0});return}if(!(!U||U.inviteType!=="bootstrap_ceo"))try{xpe(await le.mutateAsync())&&s("/",{replace:!0})}catch{return}},"onSuccess"),onError:r(ge=>{const me=Was(ge,i,d);b4e(ge)==="USER_ALREADY_EXISTS_USE_ANOTHER_EMAIL"&&(o("sign_in"),p("")),R(me)},"onError")}),ce=(0,m.useMemo)(()=>U?K?"Open organization":U.inviteType==="bootstrap_ceo"?"Accept invite":Y?"Submit request":B.data?"Accept invite":"Continue":"Continue",[U,K,B.data,Y]);if(!a)return(0,t.jsx)("div",{className:"mx-auto max-w-xl py-10 text-sm text-destructive",children:"Invalid invite token."});if(E.isLoading||M.isLoading||B.isLoading)return(0,t.jsx)("div",{className:"mx-auto max-w-xl py-10 text-sm text-muted-foreground",children:"Loading invite..."});if(O)return(0,t.jsx)("div",{className:"mx-auto max-w-xl py-10 text-sm text-muted-foreground",children:"Checking your access..."});if(E.error||!U)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"&&re==="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)(gpe,{companyDisplayName:H,companyLogoUrl:ee,invitedByUserName:se});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)(L,{asChild:!0,className:"rounded-none",children:(0,t.jsx)(Ke,{to:"/",children:"Open board"})})})]})});if(w?.kind==="join"){const ge=w.payload,me=typeof ge.claimSecret=="string"?ge.claimSecret:null,ie=typeof ge.claimApiKeyPath=="string"?ge.claimApiKeyPath:null,ue=qas(ge.onboarding,["textInstructions","url"]);return!Y&&ge.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)(V8,{companyDisplayName:H,companyLogoUrl:ee,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)(L,{asChild:!0,className:"w-full rounded-none",children:(0,t.jsx)(Ke,{to:"/",children:"Open board"})})})]})}):(0,t.jsx)(gpe,{companyDisplayName:H,companyLogoUrl:ee,invitedByUserName:se,claimSecret:me,claimApiKeyPath:ie,onboardingTextUrl:ue})}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:`${ppe} space-y-6`,children:[(0,t.jsxs)("div",{className:"flex items-start gap-4",children:[(0,t.jsx)(V8,{companyDisplayName:H,companyLogoUrl:ee,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:U.inviteType==="bootstrap_ceo"?"Set up Paperclip":`Join ${H}`}),(0,t.jsx)("p",{className:"mt-2 max-w-2xl text-sm leading-6 text-zinc-300",children:Y?"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:H})]}),(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:se??"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:Y?"Agent join request":fe??"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:Ad(U.expiresAt)})]})]}),ne?(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:ne})]}):null,B.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:te}),"."]}):null]}),(0,t.jsx)("section",{className:`${ppe} h-fit`,children:Y?(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 ",H,"."]})]}),(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:Sw,value:f,onChange:r(ge=>x(ge.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:Sw,value:b,onChange:r(ge=>v(ge.target.value),"onChange"),children:zas.map(ge=>(0,t.jsxs)("option",{value:ge,disabled:!hpe.has(ge),children:[Ff(ge),hpe.has(ge)?"":" (Coming soon)"]},ge))})]}),(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:Sw,rows:4,value:j,onChange:r(ge=>N(ge.target.value),"onChange")})]}),S?(0,t.jsx)("p",{className:"text-xs text-red-400",children:S}):null,(0,t.jsx)(L,{className:"w-full rounded-none",disabled:le.isPending||f.trim().length===0,onClick:r(()=>le.mutate(),"onClick"),children:le.isPending?"Working...":ce})]}):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 ${H}.`:"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:`${fpe} ${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:`${fpe} ${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(ge=>{if(ge.preventDefault(),!he.isPending){if(!ae){R({tone:"error",message:"Please fill in all required fields."});return}he.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:Sw,value:l,onChange:r(ge=>{c(ge.target.value),R(null)},"onChange"),autoComplete:"name",required:!0,"aria-required":"true","aria-invalid":I?.tone==="error"?!0:void 0,"aria-describedby":I?D: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:Sw,value:d,onChange:r(ge=>{u(ge.target.value),R(null)},"onChange"),autoComplete:"username",required:!0,"aria-required":"true","aria-invalid":I?.tone==="error"?!0:void 0,"aria-describedby":I?D: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:Sw,value:h,onChange:r(ge=>{p(ge.target.value),R(null)},"onChange"),autoComplete:i==="sign_in"?"current-password":"new-password",required:!0,"aria-required":"true","aria-invalid":I?.tone==="error"?!0:void 0,"aria-describedby":I?D:void 0})]}),I?(0,t.jsx)("p",{id:D,role:"alert",className:`text-xs ${I.tone==="info"?"text-amber-300":"text-red-400"}`,children:I.message}):null,(0,t.jsx)(L,{type:"submit",className:"w-full rounded-none",disabled:he.isPending,"aria-disabled":!ae||he.isPending,children:he.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":Q?"Completing organization access":U.inviteType==="bootstrap_ceo"?"Accept bootstrap invite":"Accept organization invite"}),(0,t.jsx)("p",{className:"mt-1 text-sm text-zinc-400",children:Q?`Granting your access to ${H}.`:K?`This account already belongs to ${H}.`:`This will ${U.inviteType==="bootstrap_ceo"?"finish setting up Paperclip":`grant or complete your access to ${H}`}.`})]}),S?(0,t.jsx)("p",{className:"text-xs text-red-400",children:S}):null,Q?(0,t.jsx)("div",{className:"text-sm text-zinc-400",children:le.isPending?"Submitting request...":"Finishing sign-in..."}):(0,t.jsx)(L,{className:"w-full rounded-none",disabled:le.isPending,onClick:r(()=>{if(K&&U.companyId){KR(a),n(U.companyId,{source:"manual"}),s("/",{replace:!0});return}le.mutate()},"onClick"),children:le.isPending?"Working...":ce})]})})]})})})}r(Has,"InviteLandingPage");var Gas=15e3,Qas={parent:"Parent task",child:"Sub-task",blocked_by:"Blocked by",blocks:"Blocks"};function Yas(){(0,m.useEffect)(()=>{const e=document.createElement("meta");return e.name="robots",e.content="noindex",document.head.appendChild(e),()=>e.remove()},[])}r(Yas,"useNoIndexMeta");function H8(e,s){const n=`/s/${encodeURIComponent(e)}`;return s?`${n}/issues/${encodeURIComponent(s)}`:n}r(H8,"sharePath");var Jas=/^(?:https?:\/\/[^/]+)?\/api\/attachments\/([^/?#]+)\/content(?:[?#].*)?$/i;function Xas(e,s){const n=Jas.exec(s.trim());return n?`/api/public/share/${encodeURIComponent(e)}/attachments/${n[1]}/content`:null}r(Xas,"publicShareImageSrc");function $C({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($C,"Section");function G8({actor:e}){return(0,t.jsx)(Hl,{name:e.name,avatarUrl:e.iconUrl,size:"sm"})}r(G8,"ActorIdentity");function Q8({value:e}){return(0,t.jsx)("time",{dateTime:e,title:Rr(e),className:"text-xs text-muted-foreground",children:cr(e)})}r(Q8,"Timestamp");function Zas({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(Zas,"ActiveRunPill");function v4e({attachments:e}){return(0,t.jsx)(A9,{children:e.map(s=>{const n=Xje({name:s.filename,url:s.url,contentType:s.contentType,byteSize:s.byteSize}),a=n.icon,i=T9(s.byteSize);return(0,t.jsxs)(N9,{size:"sm",children:[(0,t.jsx)(S9,{children:(0,t.jsx)(a,{"aria-hidden":!0})}),(0,t.jsxs)(C9,{children:[(0,t.jsx)(_9,{className:"max-w-48",children:s.filename}),(0,t.jsx)(I9,{className:"max-w-48",children:i?`${n.label} · ${i}`:n.label})]}),(0,t.jsx)(Gje,{"aria-label":`Download ${s.filename}`,render:(0,t.jsx)("a",{href:s.url,download:s.filename,rel:"noreferrer"})})]},s.id)})})}r(v4e,"AttachmentList");function eis({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)(Xi,{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:Qas[e.relation]}),e.navigable?(0,t.jsx)(ld,{to:n?H8(s,e.id):H8(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(eis,"RelatedIssueRow");function tis({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)(G8,{actor:e.author}),(0,t.jsx)(Q8,{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)(G8,{actor:e.author}),(0,t.jsx)(Q8,{value:e.createdAt})]}),(0,t.jsx)(Sn,{className:"text-sm",softBreaks:!0,linkIssueReferences:!1,resolveImageSrc:s,children:e.body}),e.attachments.length>0?(0,t.jsx)(v4e,{attachments:e.attachments}):null]})}r(tis,"TimelineEntry");function sis({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)(Ha,{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)(Q8,{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)(po,{className:"h-3.5 w-3.5","aria-hidden":!0}),"Download PDF"]}),(0,t.jsx)(Sn,{className:"text-sm",linkIssueReferences:!1,resolveImageSrc:s,children:e.body})]})]})}r(sis,"DocumentCard");function nis({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)(Vn,{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)(po,{className:"h-3.5 w-3.5","aria-hidden":!0}),"Download"]}):null]})}r(nis,"WorkProductRow");function bpe({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(bpe,"CenteredNotice");function ris({view:e,token:s}){const{company:n,issue:a}=e,i=(0,m.useCallback)(o=>Xas(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)(eS,{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)(ld,{to:H8(s),className:"inline-flex items-center gap-1.5 text-sm text-muted-foreground hover:text-foreground",children:[(0,t.jsx)(Tl,{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)(sp,{status:a.status}),(0,t.jsx)(Bfe,{priority:a.priority,showLabel:!0}),a.assignee?(0,t.jsx)(G8,{actor:a.assignee}):null,e.activeRun?(0,t.jsx)(Zas,{agentName:e.activeRun.agentName}):null]}),(0,t.jsxs)("p",{className:"text-xs text-muted-foreground",children:["Created ",Rr(a.createdAt)," · Updated ",cr(a.updatedAt),a.completedAt?` · Completed ${Rr(a.completedAt)}`:""]})]}),a.description?(0,t.jsx)(Sn,{className:"text-sm",softBreaks:!0,linkIssueReferences:!1,resolveImageSrc:i,children:a.description}):null,e.related.length>0?(0,t.jsx)($C,{title:"Related tasks",children:(0,t.jsx)("ul",{className:"space-y-2",children:e.related.map(o=>(0,t.jsx)(eis,{related:o,token:s,isSharedRoot:e.isSharedRoot},`${o.relation}:${o.id}`))})}):null,e.documents.length>0?(0,t.jsx)($C,{title:"Documents",children:(0,t.jsx)("div",{className:"space-y-2",children:e.documents.map(o=>(0,t.jsx)(sis,{document:o,resolveImageSrc:i},o.key))})}):null,e.attachments.length>0?(0,t.jsx)($C,{title:"Attachments",children:(0,t.jsx)(v4e,{attachments:e.attachments})}):null,e.workProducts.length>0?(0,t.jsx)($C,{title:"Work products",children:(0,t.jsx)("ul",{className:"space-y-2",children:e.workProducts.map(o=>(0,t.jsx)(nis,{product:o},o.id))})}):null,(0,t.jsx)($C,{title:"Activity",children:e.comments.length>0?(0,t.jsx)("ol",{className:"space-y-3",children:e.comments.map(o=>(0,t.jsx)(tis,{comment:o,resolveImageSrc:i},o.id))}):(0,t.jsx)("p",{className:"text-sm text-muted-foreground",children:"No updates yet."})})]})]})}r(ris,"PublicIssueShareContent");function vpe(){const{token:e="",issueId:s}=va();Yas();const n=dze.test(e),a=Z({queryKey:P.publicShare.view(e,s??null),queryFn:r(()=>s?Dk.getPublicShareIssue(e,s):Dk.getPublicShare(e),"queryFn"),enabled:n,retry:!1,refetchOnWindowFocus:!0,refetchInterval:r(i=>i.state.data?.activeRun?Gas:!1,"refetchInterval")});return!n||a.data===null?(0,t.jsx)(bpe,{title:"This link is not available",body:"It may have been revoked, or the address is incomplete."}):a.data?(0,t.jsx)(ris,{view:a.data,token:e}):a.isError?(0,t.jsx)(bpe,{title:"Couldn't load this page",body:"Check your connection and try again.",action:(0,t.jsx)(L,{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)(vn,{className:"h-6 w-1/2"}),(0,t.jsx)(vn,{className:"h-4 w-1/3"}),(0,t.jsx)(vn,{className:"h-24 w-full"})]})})}r(vpe,"PublicIssueSharePage");function ais(){const{selectedCompany:e,selectedCompanyId:s}=ps(),{setBreadcrumbs:n}=Bn(),{pushToast:a}=xi(),i=Dt(),[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=Z({queryKey:P.access.joinRequests(s??"",`${o}:${c}`),queryFn:r(()=>pr.listJoinRequests(s,o,c==="all"?void 0:c),"queryFn"),enabled:!!s}),h=je({mutationFn:r(f=>pr.approveJoinRequest(s,f),"mutationFn"),onSuccess:r(async()=>{await i.invalidateQueries({queryKey:P.access.joinRequests(s,`${o}:${c}`)}),await i.invalidateQueries({queryKey:P.access.companyMembers(s)}),await i.invalidateQueries({queryKey:P.access.companyUserDirectory(s)}),a({title:"Join request approved",tone:"success"})},"onSuccess")}),p=je({mutationFn:r(f=>pr.rejectJoinRequest(s,f),"mutationFn"),onSuccess:r(async()=>{await i.invalidateQueries({queryKey:P.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 dn&&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)(Lqe,{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)(rn,{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)(rn,{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)(ct,{variant:f.status==="pending_approval"?"secondary":f.status==="approved"?"outline":"destructive",children:f.status.replace("_"," ")}),(0,t.jsx)(ct,{variant:"outline",children:f.requestType}),f.adapterType?(0,t.jsx)(ct,{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)(L,{variant:"outline",onClick:r(()=>p.mutate(f.id),"onClick"),disabled:p.isPending,children:"Reject"}),(0,t.jsx)(L,{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(ais,"JoinRequestQueue");var iis=(0,m.lazy)(()=>Jc(()=>import("./CompanyExport-DZXwSqbC.js").then(e=>({default:e.CompanyExport})),__vite__mapDeps([6,5,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24]))),ois=(0,m.lazy)(()=>Jc(()=>import("./Agents.production-DC72vjFS.js").then(e=>({default:e.Agents})),__vite__mapDeps([25,5,7,9,8,10,11,12,13,26,27,28,29,30,31,32,33,23,24]))),lis=(0,m.lazy)(()=>Jc(()=>import("./Routines.production-DQbPhKWQ.js").then(e=>({default:e.Routines})),__vite__mapDeps([34,5,7,8,9,10,11,12,13,35,14,36,37,28,26,38,39,40,20,41,42,15,16,17,18,29,43,44,30,45,46,22,31,47,33,48,49,50,51,23,24,27]))),ype=(0,m.lazy)(()=>Jc(()=>import("./RoutineDetail.production-f4dz9CbP.js").then(e=>({default:e.RoutineDetail})),__vite__mapDeps([52,5,7,8,9,10,11,12,13,35,14,36,37,28,26,38,39,40,20,41,42,15,16,17,18,29,43,44,30,45,46,22,31,47,33,48,49,50,51,23,24,53]))),cis=(0,m.lazy)(()=>Jc(()=>import("./CompanySkills.production-Ctn-8voB.js").then(e=>({default:e.CompanySkills})),__vite__mapDeps([54,5,7,8,9,10,11,12,13,14,36,37,28,26,38,39,40,20,41,27,15,16,17,18,55,53,31,44,21,19,56,47,48,50,23,24]))),dis=(0,m.lazy)(()=>Jc(()=>import("./CompanyActivity.production-Clf5BH9f.js").then(e=>({default:e.CompanyActivity})),__vite__mapDeps([57,5,7,8,9,10,11,12,13,26,27,28,43,37,20,44,48,49,51]))),uis=(0,m.lazy)(()=>Jc(()=>import("./Costs.production-C3x7Atp8.js").then(e=>({default:e.Costs})),__vite__mapDeps([58,5,7,27,28,13,12,44,41,50,26,51,23,24]))),mis=(0,m.lazy)(()=>Jc(()=>import("./OrgChart.production-DbBXNgXD.js").then(e=>({default:e.OrgChart})),__vite__mapDeps([59,5,7,8,9,10,11,12,13,26,45,46,51,23,24])));function u0({children:e}){return(0,t.jsx)(m.Suspense,{fallback:(0,t.jsx)($m,{}),children:e})}r(u0,"ProductionSurface");function his(e,s){const n=e&&s;return(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)(nt,{index:!0,element:(0,t.jsx)(kn,{to:"dashboard",replace:!0})}),(0,t.jsx)(nt,{path:"dashboard",element:(0,t.jsx)(pSt,{})}),(0,t.jsx)(nt,{path:"dashboard/live",element:(0,t.jsx)(fSt,{})}),(0,t.jsx)(nt,{path:"timeline",element:e?(0,t.jsx)(Yp,{to:"/activity/timeline"}):(0,t.jsx)(O2e,{})}),(0,t.jsx)(nt,{path:"onboarding",element:(0,t.jsx)(w4e,{})}),(0,t.jsx)(nt,{path:"companies",element:(0,t.jsx)(tCt,{})}),(0,t.jsx)(nt,{path:"company/settings",element:(0,t.jsx)(s7t,{})}),(0,t.jsx)(nt,{path:"company/settings/environments",element:(0,t.jsx)(kn,{to:"/company/settings/instance/environments",replace:!0})}),(0,t.jsx)(nt,{path:"company/settings/cloud-upstream",element:(0,t.jsx)(kn,{to:"/company/export",replace:!0})}),(0,t.jsxs)(nt,{element:(0,t.jsx)(Hh,{pageKey:"company.members"}),children:[(0,t.jsx)(nt,{path:"company/settings/members",element:(0,t.jsx)(NHt,{})}),(0,t.jsx)(nt,{path:"company/settings/access",element:(0,t.jsx)(SHt,{})})]}),(0,t.jsx)(nt,{element:(0,t.jsx)(Hh,{pageKey:"company.invites"}),children:(0,t.jsx)(nt,{path:"company/settings/invites",element:(0,t.jsx)(kn,{to:"/company/settings/members?tab=invites",replace:!0})})}),(0,t.jsx)(nt,{element:(0,t.jsx)(Hh,{pageKey:"company.export"}),children:(0,t.jsx)(nt,{path:"company/export/*",element:(0,t.jsx)(m.Suspense,{fallback:(0,t.jsx)($m,{}),children:(0,t.jsx)(iis,{})})})}),(0,t.jsx)(nt,{element:(0,t.jsx)(Cut,{}),children:(0,t.jsx)(nt,{element:(0,t.jsx)(Hh,{pageKey:"company.import"}),children:(0,t.jsx)(nt,{path:"company/import",element:(0,t.jsx)(ars,{})})})}),(0,t.jsx)(nt,{element:(0,t.jsx)(Hh,{pageKey:"company.secrets"}),children:(0,t.jsx)(nt,{path:"company/settings/secrets",element:(0,t.jsx)(ens,{})})}),(0,t.jsx)(nt,{path:"company/settings/tools",element:(0,t.jsx)(kpe,{})}),(0,t.jsx)(nt,{path:"company/settings/tools/:tab",element:(0,t.jsx)(kpe,{})}),(0,t.jsx)(nt,{path:"tools",element:(0,t.jsx)(Npe,{})}),(0,t.jsx)(nt,{path:"tools/:tab",element:(0,t.jsx)(Npe,{})}),(0,t.jsx)(nt,{path:"apps",element:(0,t.jsx)(bQt,{})}),(0,t.jsx)(nt,{path:"apps/browse",element:(0,t.jsx)(kn,{to:"/apps",replace:!0})}),(0,t.jsx)(nt,{path:"apps/connections",element:(0,t.jsx)(kn,{to:"/apps",replace:!0})}),(0,t.jsx)(nt,{path:"apps/byo",element:(0,t.jsx)(KPe,{byoOnly:!0})}),(0,t.jsx)(nt,{path:"apps/vercel-connect",element:(0,t.jsx)(jpe,{credentialSource:"vercel_connect"})}),(0,t.jsx)(nt,{path:"apps/connect",element:(0,t.jsx)(jpe,{})}),(0,t.jsx)(nt,{path:"apps/chat/connect",element:(0,t.jsx)(KB,{children:(0,t.jsx)(RYt,{})})}),(0,t.jsx)(nt,{path:"apps/chat/:endpointId",element:(0,t.jsx)(KB,{children:(0,t.jsx)(kn,{to:"settings",replace:!0})})}),(0,t.jsx)(nt,{path:"apps/chat/:endpointId/:tab",element:(0,t.jsx)(KB,{children:(0,t.jsx)(OJt,{})})}),(0,t.jsx)(nt,{path:"apps/connect/:appKey",element:(0,t.jsx)(kn,{to:"/apps",replace:!0})}),(0,t.jsx)(nt,{path:"apps/connect/:appKey/:stage",element:(0,t.jsx)(kn,{to:"/apps",replace:!0})}),(0,t.jsx)(nt,{path:"apps/review",element:(0,t.jsx)(VJt,{})}),(0,t.jsx)(nt,{path:"apps/attention",element:(0,t.jsx)(kn,{to:"/apps",replace:!0})}),(0,t.jsx)(nt,{path:"apps/gateways",element:(0,t.jsx)(Nme,{})}),(0,t.jsx)(nt,{path:"apps/gateways/:gatewayId",element:(0,t.jsx)(kn,{to:"overview",replace:!0})}),(0,t.jsx)(nt,{path:"apps/gateways/:gatewayId/:tab",element:(0,t.jsx)(wXt,{})}),(0,t.jsx)(nt,{path:"apps/advanced",element:(0,t.jsx)(Gue,{})}),(0,t.jsx)(nt,{path:"apps/advanced/gateways",element:(0,t.jsx)(Nme,{})}),(0,t.jsx)(nt,{path:"apps/advanced/profiles/new",element:(0,t.jsx)(Zue,{mode:"new"})}),(0,t.jsx)(nt,{path:"apps/advanced/profiles/:profileId/edit",element:(0,t.jsx)(Zue,{mode:"edit"})}),(0,t.jsx)(nt,{path:"apps/advanced/profiles/:profileId",element:(0,t.jsx)(KGt,{})}),(0,t.jsx)(nt,{path:"apps/advanced/audit",element:(0,t.jsx)(kn,{to:"/apps",replace:!0})}),(0,t.jsx)(nt,{path:"apps/advanced/run-your-own",element:(0,t.jsx)(kn,{to:"/apps",replace:!0})}),(0,t.jsx)(nt,{path:"apps/advanced/:tab",element:(0,t.jsx)(Gue,{})}),(0,t.jsx)(nt,{path:"apps/app/:applicationId",element:(0,t.jsx)(jme,{})}),(0,t.jsx)(nt,{path:"apps/app/:applicationId/:tab",element:(0,t.jsx)(jme,{})}),(0,t.jsx)(nt,{path:"apps/:connectionId",element:(0,t.jsx)(kn,{to:"permissions",replace:!0})}),(0,t.jsx)(nt,{path:"apps/:connectionId/:tab",element:(0,t.jsx)(WQt,{})}),(0,t.jsx)(nt,{path:"company/settings/instance",element:(0,t.jsx)(kn,{to:"/company/settings",replace:!0})}),(0,t.jsx)(nt,{element:(0,t.jsx)(Hh,{pageKey:"instance.profile"}),children:(0,t.jsx)(nt,{path:"company/settings/instance/profile",element:(0,t.jsx)(uas,{})})}),(0,t.jsx)(nt,{path:"company/settings/instance/general",element:(0,t.jsx)(kn,{to:"/company/settings",replace:!0})}),(0,t.jsx)(nt,{path:"company/settings/instance/heartbeats",element:(0,t.jsx)(kn,{to:"/company/settings",replace:!0})}),(0,t.jsxs)(nt,{element:(0,t.jsx)(Hh,{pageKey:"instance.environments"}),children:[(0,t.jsx)(nt,{path:"company/settings/instance/environments",element:(0,t.jsx)(RB,{})}),(0,t.jsx)(nt,{path:"company/settings/instance/environments/new",element:(0,t.jsx)(RB,{mode:"create"})}),(0,t.jsx)(nt,{path:"company/settings/instance/environments/:environmentId/edit",element:(0,t.jsx)(RB,{mode:"edit"})})]}),(0,t.jsx)(nt,{element:(0,t.jsx)(Hh,{pageKey:"instance.access"}),children:(0,t.jsx)(nt,{path:"company/settings/instance/access",element:(0,t.jsx)(nas,{})})}),(0,t.jsx)(nt,{element:(0,t.jsx)(Hh,{pageKey:"instance.experimental"}),children:(0,t.jsx)(nt,{path:"company/settings/instance/experimental",element:(0,t.jsx)(sas,{})})}),(0,t.jsxs)(nt,{element:(0,t.jsx)(Hh,{pageKey:"instance.plugins"}),children:[(0,t.jsx)(nt,{path:"company/settings/instance/plugins",element:(0,t.jsx)(has,{})}),(0,t.jsx)(nt,{path:"company/settings/instance/plugins/:pluginId",element:(0,t.jsx)(pas,{})})]}),(0,t.jsx)(nt,{element:(0,t.jsx)(Hh,{pageKey:"instance.adapters"}),children:(0,t.jsx)(nt,{path:"company/settings/instance/adapters",element:(0,t.jsx)(ipe,{})})}),(0,t.jsx)(nt,{path:"company/settings/:settingsRoutePath/*",element:(0,t.jsx)(gHt,{})}),(0,t.jsx)(nt,{path:"skills/sources",element:(0,t.jsx)(Yme,{})}),(0,t.jsx)(nt,{path:"skills/sources/:sourceId",element:(0,t.jsx)(Yme,{})}),(0,t.jsx)(nt,{path:"skills/studio",element:(0,t.jsx)(nz,{})}),(0,t.jsx)(nt,{path:"skills/studio/new",element:(0,t.jsx)(nz,{})}),(0,t.jsx)(nt,{path:"skills/studio/:skillId",element:(0,t.jsx)(nz,{})}),(0,t.jsx)(nt,{path:"skills/:skillId/studio",element:(0,t.jsx)(y4e,{})}),(0,t.jsx)(nt,{path:"skills/*",element:e?(0,t.jsx)($Zt,{}):(0,t.jsx)(u0,{children:(0,t.jsx)(cis,{})})}),(0,t.jsx)(nt,{path:"settings",element:(0,t.jsx)(Tv,{})}),(0,t.jsx)(nt,{path:"settings/*",element:(0,t.jsx)(Tv,{})}),(0,t.jsx)(nt,{path:"plugins/:pluginId",element:(0,t.jsx)(ope,{})}),(0,t.jsx)(nt,{path:"org",element:e?(0,t.jsx)(kn,{to:"/agents/all",replace:!0}):(0,t.jsx)(u0,{children:(0,t.jsx)(mis,{})})}),(0,t.jsx)(nt,{path:"agents",element:(0,t.jsx)(kn,{to:"/agents/all",replace:!0})}),iH.map(a=>(0,t.jsx)(nt,{path:`agents/${a}`,element:e?(0,t.jsx)(ICt,{}):(0,t.jsx)(u0,{children:(0,t.jsx)(ois,{})})},a)),(0,t.jsx)(nt,{path:"agents/new",element:(0,t.jsx)(Eas,{})}),(0,t.jsx)(nt,{path:"agents/:agentId",element:(0,t.jsx)(iF,{})}),(0,t.jsx)(nt,{path:"agents/:agentId/:tab",element:(0,t.jsx)(iF,{})}),(0,t.jsx)(nt,{path:"agents/:agentId/runs/:runId",element:(0,t.jsx)(iF,{})}),(0,t.jsx)(nt,{path:"projects",element:(0,t.jsx)(qIt,{})}),(0,t.jsx)(nt,{path:"projects/:projectId",element:(0,t.jsx)(Jb,{})}),(0,t.jsx)(nt,{path:"projects/:projectId/overview",element:(0,t.jsx)(Jb,{})}),(0,t.jsx)(nt,{path:"projects/:projectId/issues",element:(0,t.jsx)(Jb,{})}),(0,t.jsx)(nt,{path:"projects/:projectId/issues/:filter",element:(0,t.jsx)(Jb,{})}),(0,t.jsx)(nt,{element:(0,t.jsx)(dO,{}),children:(0,t.jsx)(nt,{path:"projects/:projectId/workspaces/:workspaceId",element:(0,t.jsx)(ETt,{})})}),(0,t.jsx)(nt,{path:"projects/:projectId/workspaces",element:(0,t.jsx)(Jb,{})}),(0,t.jsx)(nt,{path:"projects/:projectId/configuration",element:(0,t.jsx)(Jb,{})}),(0,t.jsx)(nt,{path:"projects/:projectId/budget",element:(0,t.jsx)(Jb,{})}),(0,t.jsx)(nt,{element:(0,t.jsx)(dO,{}),children:(0,t.jsx)(nt,{path:"workspaces",element:(0,t.jsx)(DTt,{})})}),(0,t.jsx)(nt,{path:"issues",element:(0,t.jsx)(GRt,{})}),(0,t.jsx)(nt,{path:"tasks",element:(0,t.jsx)(kn,{to:"/issues",replace:!0})}),(0,t.jsx)(nt,{path:"search",element:(0,t.jsx)(pEt,{})}),n?(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)(nt,{path:"issues/all",element:(0,t.jsx)(oh,{view:"all"})}),(0,t.jsx)(nt,{path:"issues/active",element:(0,t.jsx)(oh,{view:"active"})}),(0,t.jsx)(nt,{path:"issues/backlog",element:(0,t.jsx)(oh,{view:"backlog"})}),(0,t.jsx)(nt,{path:"issues/done",element:(0,t.jsx)(oh,{view:"done"})}),(0,t.jsx)(nt,{path:"issues/recent",element:(0,t.jsx)(oh,{view:"recent"})})]}):(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)(nt,{path:"issues/all",element:(0,t.jsx)(kn,{to:"/issues",replace:!0})}),(0,t.jsx)(nt,{path:"issues/active",element:(0,t.jsx)(kn,{to:"/issues",replace:!0})}),(0,t.jsx)(nt,{path:"issues/backlog",element:(0,t.jsx)(kn,{to:"/issues",replace:!0})}),(0,t.jsx)(nt,{path:"issues/done",element:(0,t.jsx)(kn,{to:"/issues",replace:!0})}),(0,t.jsx)(nt,{path:"issues/recent",element:(0,t.jsx)(kn,{to:"/issues",replace:!0})})]}),(0,t.jsx)(nt,{path:"chats",element:(0,t.jsx)(m4t,{})}),(0,t.jsx)(nt,{path:"chats/:agentRef",element:(0,t.jsx)(p4t,{})}),(0,t.jsx)(nt,{path:"issues/:issueId",element:(0,t.jsx)(o4t,{})}),null,(0,t.jsx)(nt,{path:"routines",element:e?(0,t.jsx)(H4t,{}):(0,t.jsx)(u0,{children:(0,t.jsx)(lis,{})})}),(0,t.jsx)(nt,{path:"cases",element:(0,t.jsx)(Xse,{children:(0,t.jsx)(Vut,{})})}),(0,t.jsx)(nt,{path:"cases/:caseIdentifier",element:(0,t.jsx)(Xse,{children:(0,t.jsx)(Apt,{})})}),(0,t.jsx)(nt,{path:"pixels-office",element:(0,t.jsx)(Sut,{children:(0,t.jsx)(Nqt,{})})}),(0,t.jsx)(nt,{path:"status",element:(0,t.jsx)(Zse,{children:(0,t.jsx)(Vle,{})})}),(0,t.jsx)(nt,{path:"status/:cardId",element:(0,t.jsx)(Zse,{children:(0,t.jsx)(Vle,{})})}),(0,t.jsx)(nt,{path:"status-cards",element:(0,t.jsx)(Spe,{})}),(0,t.jsx)(nt,{path:"status-cards/:cardId",element:(0,t.jsx)(Spe,{})}),(0,t.jsx)(nt,{path:"review-queue",element:(0,t.jsx)(e0,{children:(0,t.jsx)(u$t,{})})}),(0,t.jsx)(nt,{path:"learnings",element:(0,t.jsx)(e0,{children:(0,t.jsx)(h$t,{})})}),(0,t.jsx)(nt,{path:"pipelines",element:(0,t.jsx)(e0,{children:(0,t.jsx)(HF,{})})}),(0,t.jsx)(nt,{path:"pipelines/:pipelineId",element:(0,t.jsx)(e0,{children:(0,t.jsx)(HF,{})})}),(0,t.jsx)(nt,{path:"pipelines/:pipelineId/add",element:(0,t.jsx)(e0,{children:(0,t.jsx)(HF,{})})}),(0,t.jsx)(nt,{path:"pipelines/:pipelineId/settings",element:(0,t.jsx)(e0,{children:(0,t.jsx)(iOt,{})})}),(0,t.jsx)(nt,{path:"pipelines/:pipelineId/items/:caseId",element:(0,t.jsx)(e0,{children:(0,t.jsx)(RLt,{})})}),(0,t.jsx)(nt,{path:"pipelines/:pipelineId/cases/:caseId",element:(0,t.jsx)(e0,{children:(0,t.jsx)(ILt,{})})}),(0,t.jsx)(nt,{path:"routines/:routineId",element:e?(0,t.jsx)(Gce,{}):(0,t.jsx)(u0,{children:(0,t.jsx)(ype,{})})}),(0,t.jsx)(nt,{path:"routines/:routineId/:section",element:e?(0,t.jsx)(Gce,{}):(0,t.jsx)(u0,{children:(0,t.jsx)(ype,{})})}),(0,t.jsx)(nt,{element:(0,t.jsx)(dO,{}),children:(0,t.jsxs)(nt,{element:(0,t.jsx)(Iut,{}),children:[(0,t.jsx)(nt,{path:"execution-workspaces/:workspaceId",element:(0,t.jsx)(vw,{})}),(0,t.jsx)(nt,{path:"execution-workspaces/:workspaceId/services",element:(0,t.jsx)(vw,{})}),(0,t.jsx)(nt,{path:"execution-workspaces/:workspaceId/configuration",element:(0,t.jsx)(vw,{})}),(0,t.jsx)(nt,{path:"execution-workspaces/:workspaceId/runtime-logs",element:(0,t.jsx)(vw,{})}),(0,t.jsx)(nt,{path:"execution-workspaces/:workspaceId/issues",element:(0,t.jsx)(vw,{})}),(0,t.jsx)(nt,{path:"execution-workspaces/:workspaceId/routines",element:(0,t.jsx)(vw,{})})]})}),(0,t.jsx)(nt,{path:"goals",element:(0,t.jsx)(yUt,{})}),(0,t.jsx)(nt,{path:"goals/:goalId",element:(0,t.jsx)(RUt,{})}),(0,t.jsx)(nt,{path:"artifacts",element:(0,t.jsx)(Xce,{})}),(0,t.jsx)(nt,{path:"approvals",element:(0,t.jsx)(kn,{to:"/approvals/pending",replace:!0})}),(0,t.jsx)(nt,{path:"approvals/pending",element:(0,t.jsx)(ede,{})}),(0,t.jsx)(nt,{path:"approvals/all",element:(0,t.jsx)(ede,{})}),(0,t.jsx)(nt,{path:"approvals/:approvalId",element:(0,t.jsx)(EUt,{})}),(0,t.jsx)(nt,{path:"activity",element:e?(0,t.jsx)(vKt,{}):(0,t.jsx)(u0,{children:(0,t.jsx)(dis,{})})}),e?(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)(nt,{path:"activity/runs",element:(0,t.jsx)(a1,{section:"runs"})}),(0,t.jsx)(nt,{path:"activity/costs",element:(0,t.jsx)(a1,{section:"costs"})}),(0,t.jsx)(nt,{path:"activity/budgets",element:(0,t.jsx)(a1,{section:"budgets"})}),(0,t.jsx)(nt,{path:"activity/timeline",element:(0,t.jsx)(a1,{section:"timeline"})}),(0,t.jsx)(nt,{path:"audit",element:(0,t.jsx)(Yp,{to:"/activity",forceAgentMode:!0})}),(0,t.jsx)(nt,{path:"audit/activity",element:(0,t.jsx)(Yp,{to:"/activity"})}),(0,t.jsx)(nt,{path:"audit/runs",element:(0,t.jsx)(Yp,{to:"/activity/runs"})}),(0,t.jsx)(nt,{path:"audit/costs",element:(0,t.jsx)(Yp,{to:"/activity/costs"})}),(0,t.jsx)(nt,{path:"audit/budgets",element:(0,t.jsx)(Yp,{to:"/activity/budgets"})}),(0,t.jsx)(nt,{path:"audit/timeline",element:(0,t.jsx)(Yp,{to:"/activity/timeline"})}),(0,t.jsx)(nt,{path:"runs",element:(0,t.jsx)(Yp,{to:"/activity/runs"})}),(0,t.jsx)(nt,{path:"costs",element:(0,t.jsx)(Yp,{to:"/activity/costs"})}),(0,t.jsx)(nt,{path:"budgets",element:(0,t.jsx)(Yp,{to:"/activity/budgets"})})]}):(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)(nt,{path:"costs",element:(0,t.jsx)(u0,{children:(0,t.jsx)(uis,{})})}),(0,t.jsx)(nt,{path:"audit",element:(0,t.jsx)(kn,{to:"/activity?mode=agents",replace:!0})})]}),(0,t.jsxs)(nt,{element:(0,t.jsx)(Klt,{}),children:[(0,t.jsx)(nt,{path:"board-chat",element:(0,t.jsx)(D8t,{})}),(0,t.jsx)(nt,{path:"artifacts",element:(0,t.jsx)(Xce,{})})]}),null,(0,t.jsx)(nt,{path:"decisions",element:(0,t.jsx)(i8t,{})}),(0,t.jsx)(nt,{path:"decisions/queues/:key",element:(0,t.jsx)(d8t,{})}),n?(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)(nt,{path:"inbox",element:(0,t.jsx)(wpe,{})}),(0,t.jsx)(nt,{path:"inbox/mine",element:(0,t.jsx)(oh,{view:"mine"})}),(0,t.jsx)(nt,{path:"inbox/recent",element:(0,t.jsx)(oh,{view:"recent"})}),(0,t.jsx)(nt,{path:"inbox/unread",element:(0,t.jsx)(oh,{view:"unread"})}),(0,t.jsx)(nt,{path:"inbox/blocked",element:(0,t.jsx)(oh,{view:"blocked"})}),(0,t.jsx)(nt,{path:"inbox/all",element:(0,t.jsx)(oh,{view:"everything"})}),(0,t.jsx)(nt,{path:"inbox/new",element:(0,t.jsx)(oh,{view:"mine"})})]}):(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)(nt,{path:"inbox",element:(0,t.jsx)(wpe,{})}),(0,t.jsx)(nt,{path:"inbox/mine",element:(0,t.jsx)(Pw,{})}),(0,t.jsx)(nt,{path:"inbox/recent",element:(0,t.jsx)(Pw,{})}),(0,t.jsx)(nt,{path:"inbox/unread",element:(0,t.jsx)(Pw,{})}),(0,t.jsx)(nt,{path:"inbox/blocked",element:(0,t.jsx)(Pw,{})}),(0,t.jsx)(nt,{path:"inbox/all",element:(0,t.jsx)(Pw,{})}),(0,t.jsx)(nt,{path:"inbox/new",element:(0,t.jsx)(kn,{to:"/inbox/mine",replace:!0})})]}),(0,t.jsx)(nt,{path:"inbox/requests",element:(0,t.jsx)(ais,{})}),(0,t.jsx)(nt,{path:"u/:userSlug",element:(0,t.jsx)(G6t,{})}),(0,t.jsx)(nt,{path:"design-guide",element:(0,t.jsx)(Xrs,{})}),(0,t.jsx)(nt,{path:"instance/settings/adapters",element:(0,t.jsx)(ipe,{})}),(0,t.jsx)(nt,{path:":pluginRoutePath/*",element:(0,t.jsx)(ope,{})}),(0,t.jsx)(nt,{path:"*",element:(0,t.jsx)(Pu,{scope:"board"})})]})}r(his,"boardRoutes");function jpe({credentialSource:e="paperclip_vault"}={}){const s=na(),n=new URLSearchParams(s.search),{enabled:a}=iS();return Jat(n,{chatConnectorsEnabled:a})?(0,t.jsx)(KPe,{credentialSource:e}):(0,t.jsx)(kn,{to:"/apps",replace:!0})}r(jpe,"AppsConnectEntryRoute");function wpe(){const{enabled:e}=yc(),{enabled:s}=sA();return e&&s?(0,t.jsx)(oh,{view:z$e(KJ())}):(0,t.jsx)(kn,{to:`/inbox/${KJ()}`,replace:!0})}r(wpe,"InboxRootRedirect");function oh({view:e}){const s=na(),n=new URLSearchParams(s.search);return n.set(GR,e),(0,t.jsx)(kn,{to:`/issues?${n.toString()}${s.hash}`,replace:!0})}r(oh,"TaskViewRedirect");function y4e(){const e=na(),{companies:s,selectedCompany:n,loading:a}=ps(),{companyPrefix:i,skillId:o}=va();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)(kn,{to:"/skills/studio",replace:!0}):(0,t.jsx)(kn,{to:`/${l.issuePrefix}/skills/studio/${encodeURIComponent(o)}${e.search}${e.hash}`,replace:!0})}r(y4e,"LegacySkillStudioRedirect");function Tv(){const e=na(),{companies:s,selectedCompany:n,loading:a}=ps(),{companyPrefix:i}=va(),{hidden:o}=eu();if(a)return(0,t.jsx)($m,{});const l=(i?s.find(d=>d.issuePrefix.toUpperCase()===i.toUpperCase()):null)??n??s[0]??null;if(!l)return UW({pathname:e.pathname,hasCompanies:!1})?(0,t.jsx)(kn,{to:"/onboarding",replace:!0}):(0,t.jsx)(UG,{});const c=p8e(Cye(`${e.pathname}${e.search}${e.hash}`),o);return(0,t.jsx)(kn,{to:`/${l.issuePrefix}${c}`,replace:!0})}r(Tv,"LegacySettingsRedirect");function kpe(){const{tab:e}=va();return(0,t.jsx)(kn,{to:j4e(e),replace:!0})}r(kpe,"LegacyToolsSettingsRedirect");function Npe(){const{tab:e}=va();return(0,t.jsx)(kn,{to:j4e(e),replace:!0})}r(Npe,"LegacyToolsRedirect");function j4e(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(j4e,"legacyToolsRedirectTarget");function w4e(){const{companies:e}=ps(),{openOnboarding:s}=Qo(),{t:n}=eye(),a=$c(),i=vCe(a?.cloudBaseUrl??null),{onboardingOpen:o,onboardingRouteDismissed:l}=yM(),{companyPrefix:c}=va(),d=c?e.find(p=>p.issuePrefix.toUpperCase()===c.toUpperCase())??null:null;if(sot({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)(L,{onClick:r(()=>d?s({initialStep:D5(),companyId:d.id}):a&&i?Lm(i):s(),"onClick"),children:d?"Add Agent":"Start Onboarding"})})]})})}r(w4e,"OnboardingRoutePage");function pis(){const{companies:e,selectedCompany:s,loading:n}=ps(),a=na();if(n)return(0,t.jsx)($m,{});const i=s??e[0]??null;return i?(0,t.jsx)(kn,{to:`/${i.issuePrefix}/dashboard`,replace:!0}):UW({pathname:a.pathname,hasCompanies:!1})?(0,t.jsx)(kn,{to:"/onboarding",replace:!0}):(0,t.jsx)(UG,{})}r(pis,"CompanyRootRedirect");function Spe(){const{cardId:e}=va(),s=B$e(),n=s?`/${s}`:"";return(0,t.jsx)(kn,{to:`${n}/status${e?`/${e}`:""}`,replace:!0})}r(Spe,"StatusCardsLegacyRedirect");function Yp({to:e,forceAgentMode:s=!1}){const n=na(),a=new URLSearchParams(n.search);s&&a.set("mode","agents");const i=a.toString();return(0,t.jsx)(kn,{to:`${e}${i?`?${i}`:""}${n.hash}`,replace:!0})}r(Yp,"AuditCompatibilityRedirect");function wa(){const e=na(),{companies:s,selectedCompany:n,loading:a}=ps();if(a)return(0,t.jsx)($m,{});const i=n??s[0]??null;return i?(0,t.jsx)(kn,{to:`/${i.issuePrefix}${e.pathname}${e.search}${e.hash}`,replace:!0}):UW({pathname:e.pathname,hasCompanies:!1})?(0,t.jsx)(kn,{to:"/onboarding",replace:!0}):(0,t.jsx)(UG,{})}r(wa,"UnprefixedBoardRedirect");function UG(){const{openOnboarding:e}=Qo(),{t:s}=eye(),n=$c(),a=vCe(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)(L,{onClick:r(()=>n&&a?Lm(a):e(),"onClick"),children:s("app.noCompanies.newCompany",{defaultValue:"New Organization"})})})]})})}r(UG,"NoCompaniesStartPage");function fis(){const{enabled:e,loaded:s}=yc(),{enabled:n}=sA();return(0,t.jsxs)(t.Fragment,{children:[(0,t.jsxs)(I$e,{children:[(0,t.jsx)(nt,{path:"oauth-handoff",element:(0,t.jsx)(eXt,{})}),(0,t.jsx)(nt,{path:"auth",element:(0,t.jsx)(Oas,{})}),(0,t.jsx)(nt,{path:"board-claim/:token",element:(0,t.jsx)(Fas,{})}),(0,t.jsx)(nt,{path:"cli-auth/:id",element:(0,t.jsx)(Bas,{})}),(0,t.jsx)(nt,{path:"invite/:token",element:(0,t.jsx)(Has,{})}),(0,t.jsx)(nt,{path:"s/:token",element:(0,t.jsx)(vpe,{})}),(0,t.jsx)(nt,{path:"s/:token/issues/:issueId",element:(0,t.jsx)(vpe,{})}),(0,t.jsx)(nt,{element:s?(0,t.jsx)(Vne,{allowMembershipRequest:!0}):(0,t.jsx)($m,{}),children:(0,t.jsx)(nt,{path:"chat-identity/confirm",element:(0,t.jsx)(KJt,{})})}),(0,t.jsx)(nt,{path:"tests/perf/long-thread",element:(0,t.jsx)(S4t,{})}),(0,t.jsx)(nt,{path:"ux-lab/bootstrap-setup",element:(0,t.jsx)(hHt,{})}),(0,t.jsx)(nt,{path:"ux-lab/responsible-user-denial",element:(0,t.jsx)(pHt,{})}),(0,t.jsx)(nt,{path:"ux-lab/cross-issue-collaboration",element:(0,t.jsx)(xHt,{})}),(0,t.jsxs)(nt,{element:s?(0,t.jsx)(Vne,{}):(0,t.jsx)($m,{}),children:[(0,t.jsx)(nt,{index:!0,element:(0,t.jsx)(pis,{})}),(0,t.jsx)(nt,{path:"onboarding",element:(0,t.jsx)(w4e,{})}),(0,t.jsx)(nt,{path:"instance",element:(0,t.jsx)(Tv,{})}),(0,t.jsx)(nt,{path:"instance/settings",element:(0,t.jsx)(Tv,{})}),(0,t.jsx)(nt,{path:"instance/settings/*",element:(0,t.jsx)(Tv,{})}),(0,t.jsx)(nt,{path:"companies",element:(0,t.jsx)(wa,{})}),(0,t.jsx)(nt,{path:"dashboard",element:(0,t.jsx)(wa,{})}),(0,t.jsx)(nt,{path:"inbox/*",element:(0,t.jsx)(wa,{})}),(0,t.jsx)(nt,{path:"issues",element:(0,t.jsx)(wa,{})}),(0,t.jsx)(nt,{path:"tasks",element:(0,t.jsx)(wa,{})}),(0,t.jsx)(nt,{path:"issues/:issueId",element:(0,t.jsx)(wa,{})}),(0,t.jsx)(nt,{path:"routines",element:(0,t.jsx)(wa,{})}),(0,t.jsx)(nt,{path:"routines/:routineId",element:(0,t.jsx)(wa,{})}),(0,t.jsx)(nt,{path:"review-queue",element:(0,t.jsx)(wa,{})}),(0,t.jsx)(nt,{path:"learnings",element:(0,t.jsx)(wa,{})}),(0,t.jsx)(nt,{path:"cases",element:(0,t.jsx)(wa,{})}),(0,t.jsx)(nt,{path:"cases/:caseIdentifier",element:(0,t.jsx)(wa,{})}),(0,t.jsx)(nt,{path:"pixels-office",element:(0,t.jsx)(wa,{})}),(0,t.jsx)(nt,{path:"status",element:(0,t.jsx)(wa,{})}),(0,t.jsx)(nt,{path:"status/:cardId",element:(0,t.jsx)(wa,{})}),(0,t.jsx)(nt,{path:"status-cards",element:(0,t.jsx)(wa,{})}),(0,t.jsx)(nt,{path:"status-cards/:cardId",element:(0,t.jsx)(wa,{})}),(0,t.jsx)(nt,{path:"pipelines",element:(0,t.jsx)(wa,{})}),(0,t.jsx)(nt,{path:"pipelines/:pipelineId",element:(0,t.jsx)(wa,{})}),(0,t.jsx)(nt,{path:"pipelines/:pipelineId/add",element:(0,t.jsx)(wa,{})}),(0,t.jsx)(nt,{path:"pipelines/:pipelineId/settings",element:(0,t.jsx)(wa,{})}),(0,t.jsx)(nt,{path:"pipelines/:pipelineId/items/:caseId",element:(0,t.jsx)(wa,{})}),(0,t.jsx)(nt,{path:"pipelines/:pipelineId/cases/:caseId",element:(0,t.jsx)(wa,{})}),(0,t.jsx)(nt,{path:"artifacts",element:(0,t.jsx)(wa,{})}),(0,t.jsx)(nt,{path:"audit",element:(0,t.jsx)(wa,{})}),e?(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)(nt,{path:"audit/*",element:(0,t.jsx)(wa,{})}),(0,t.jsx)(nt,{path:"activity",element:(0,t.jsx)(wa,{})}),(0,t.jsx)(nt,{path:"activity/*",element:(0,t.jsx)(wa,{})}),(0,t.jsx)(nt,{path:"runs",element:(0,t.jsx)(wa,{})}),(0,t.jsx)(nt,{path:"costs",element:(0,t.jsx)(wa,{})}),(0,t.jsx)(nt,{path:"budgets",element:(0,t.jsx)(wa,{})})]}):null,(0,t.jsx)(nt,{path:"decisions",element:(0,t.jsx)(wa,{})}),(0,t.jsx)(nt,{path:"u/:userSlug",element:(0,t.jsx)(wa,{})}),(0,t.jsx)(nt,{path:"skills/studio",element:(0,t.jsx)(wa,{})}),(0,t.jsx)(nt,{path:"skills/studio/new",element:(0,t.jsx)(wa,{})}),(0,t.jsx)(nt,{path:"skills/studio/:skillId",element:(0,t.jsx)(wa,{})}),(0,t.jsx)(nt,{path:"skills/:skillId/studio",element:(0,t.jsx)(y4e,{})}),(0,t.jsx)(nt,{path:"skills/*",element:(0,t.jsx)(wa,{})}),(0,t.jsx)(nt,{path:"settings",element:(0,t.jsx)(Tv,{})}),(0,t.jsx)(nt,{path:"settings/*",element:(0,t.jsx)(Tv,{})}),(0,t.jsx)(nt,{path:"agents",element:(0,t.jsx)(wa,{})}),iH.map(a=>(0,t.jsx)(nt,{path:`agents/${a}`,element:(0,t.jsx)(wa,{})},a)),(0,t.jsx)(nt,{path:"agents/new",element:(0,t.jsx)(wa,{})}),(0,t.jsx)(nt,{path:"agents/:agentId",element:(0,t.jsx)(wa,{})}),(0,t.jsx)(nt,{path:"agents/:agentId/:tab",element:(0,t.jsx)(wa,{})}),(0,t.jsx)(nt,{path:"agents/:agentId/runs/:runId",element:(0,t.jsx)(wa,{})}),(0,t.jsx)(nt,{path:"projects",element:(0,t.jsx)(wa,{})}),(0,t.jsx)(nt,{path:"projects/:projectId",element:(0,t.jsx)(wa,{})}),(0,t.jsx)(nt,{path:"projects/:projectId/overview",element:(0,t.jsx)(wa,{})}),(0,t.jsx)(nt,{path:"projects/:projectId/issues",element:(0,t.jsx)(wa,{})}),(0,t.jsx)(nt,{path:"projects/:projectId/issues/:filter",element:(0,t.jsx)(wa,{})}),(0,t.jsx)(nt,{path:"projects/:projectId/workspaces",element:(0,t.jsx)(wa,{})}),(0,t.jsx)(nt,{path:"projects/:projectId/workspaces/:workspaceId",element:(0,t.jsx)(wa,{})}),(0,t.jsx)(nt,{path:"projects/:projectId/configuration",element:(0,t.jsx)(wa,{})}),(0,t.jsx)(nt,{path:"workspaces",element:(0,t.jsx)(wa,{})}),(0,t.jsx)(nt,{path:"execution-workspaces/:workspaceId",element:(0,t.jsx)(Zj,{})}),(0,t.jsx)(nt,{path:"execution-workspaces/:workspaceId/services",element:(0,t.jsx)(Zj,{})}),(0,t.jsx)(nt,{path:"execution-workspaces/:workspaceId/configuration",element:(0,t.jsx)(Zj,{})}),(0,t.jsx)(nt,{path:"execution-workspaces/:workspaceId/runtime-logs",element:(0,t.jsx)(Zj,{})}),(0,t.jsx)(nt,{path:"execution-workspaces/:workspaceId/issues",element:(0,t.jsx)(Zj,{})}),(0,t.jsx)(nt,{path:"execution-workspaces/:workspaceId/routines",element:(0,t.jsx)(Zj,{})}),(0,t.jsx)(nt,{path:":companyPrefix",element:e?(0,t.jsx)(llt,{}):(0,t.jsx)(zlt,{}),children:his(e,n)}),(0,t.jsx)(nt,{path:"*",element:(0,t.jsx)(Pu,{scope:"global"})})]})]}),(0,t.jsx)(rft,{}),(0,t.jsx)(qot,{})]})}r(fis,"App");var xis=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){hCe(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 gis(){const{data:e}=Z({queryKey:P.auth.session,queryFn:r(()=>Oa.getSession(),"queryFn"),retry:!1}),s=e?.sentryDsn,n=e?.sentryEnvironment??void 0;return(0,m.useEffect)(()=>{if(s)return yot(s,n),()=>{jot()}},[s,n]),null}r(gis,"SentryGate");function bis(e){let s=jg();gie(s),$U(s,e.userId);const n=WTe(()=>{const o=jg();o!==s&&(s=o,gie(o),$U(o,e.userId))}),a=typeof navigator<"u"&&"serviceWorker"in navigator?navigator.serviceWorker:null,i=r(o=>{const l=r2t(o.data);l&&(l.type==="navigate"?e.navigate(l.url):s2t(l.notification))},"onMessage");return a?.addEventListener("message",i),a?.startMessages(),()=>{n(),a?.removeEventListener("message",i)}}r(bis,"startNotificationRuntime");function vis(){const e=Mn(),s=(0,m.useRef)(e),{data:n}=Z({queryKey:P.auth.session,queryFn:r(()=>Oa.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 bis({userId:a,navigate:r(i=>s.current(i),"navigate")})},[a]),null}r(vis,"NotificationRuntime");function yis(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(yis,"managedRoutineToRow");function jis({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=yis(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)(_Ee,{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(I=>{I.preventDefault(),I.stopPropagation()},"onClick"),children:[(0,t.jsx)("span",{children:w.length?`Missing ${w.map(I=>`${I.resourceKind}:${I.resourceKey}`).join(", ")}`:"Routine defaults can be repaired."}),(0,t.jsxs)("span",{className:"flex items-center gap-2",children:[p?(0,t.jsx)(L,{size:"sm",variant:"ghost",disabled:c===v.key,onClick:r(()=>p(v),"onClick"),children:c===v.key?"Reconciling...":"Reconcile"}):null,f?(0,t.jsx)(L,{size:"sm",variant:"ghost",disabled:d===v.key,onClick:r(()=>f(v),"onClick"),children:d===v.key?"Resetting...":"Reset"}):null]})]}):null]},v.key)})})}r(jis,"ManagedRoutinesList");function Cpe(e){return new Set(e??[])}r(Cpe,"toPathSet");function wis({expandedPaths:e,checkedPaths:s,selectedFile:n=null,showCheckboxes:a=!1,onToggleDir:i,onSelectFile:o,...l}){return(0,m.createElement)(hj,{...l,selectedFile:n,expandedDirs:Cpe(e),checkedFiles:s?Cpe(s):void 0,showCheckboxes:a,onToggleDir:i??(()=>{}),onSelectFile:o??(()=>{})})}r(wis,"PluginSdkFileTree");function kis(e){const[s,n]=(0,m.useState)(null);return(0,m.useEffect)(()=>{let a=!1;return Jc(()=>import("./MarkdownEditor-DIHDyI6k.js").then(i=>i.n).then(i=>{a||n(()=>i.MarkdownEditor)}),__vite__mapDeps([36,5,7,9,14,37,28,10,26,38])),()=>{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(kis,"PluginSdkMarkdownEditor");function Nis(e){return Object.fromEntries(Object.entries(e).filter(([,s])=>s!=null&&s!==""&&s!==!1))}r(Nis,"compactIssueFilters");function Sis({companyId:e,projectId:s=null,filters:n,viewStateKey:a="paperclip:plugin-issues-view",initialSearch:i,createIssueLabel:o,searchWithinLoadedIssues:l=!0}){const c=Dt(),d=(0,m.useMemo)(()=>Nis({...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}=Z({queryKey:P.agents.list(e??"__no-company__"),queryFn:r(()=>$t.list(e),"queryFn"),enabled:!!e}),{data:x}=Z({queryKey:P.projects.list(e??"__no-company__",{includeArchived:!0}),queryFn:r(()=>pa.list(e,{includeArchived:!0}),"queryFn"),enabled:!!e}),b=P.liveRuns(e??"__no-company__"),v=No({companyId:e,resourceKey:"live-runs",queryKey:b,enabled:!!e,refetchInterval:!1,leaderOnly:!0}),{data:j,dataUpdatedAt:N}=Z({queryKey:b,queryFn:r(()=>sa.liveRunsForCompany(e),"queryFn"),enabled:v.enabled,refetchInterval:v.refetchInterval});So(v,j,N);const{data:w,isLoading:k,error:S}=Z({queryKey:p,queryFn:r(()=>Ct.list(e,d),"queryFn"),enabled:!!e}),C=(0,m.useMemo)(()=>Ng(j,w),[w,j]),I=je({mutationFn:r(({id:R,data:T})=>Ct.update(R,T),"mutationFn"),onSuccess:r(()=>{e&&(c.invalidateQueries({queryKey:["plugins","sdk-ui","issues-list",e]}),c.invalidateQueries({queryKey:P.issues.list(e)}),h&&(c.invalidateQueries({queryKey:P.issues.listByProject(e,h)}),u&&c.invalidateQueries({queryKey:P.issues.listPluginOperationsByProject(e,h,u)})))},"onSuccess")});return e?(0,m.createElement)(ug,{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,T)=>I.mutate({id:R,data:T}),"onUpdateIssue")}):(0,m.createElement)("div",{className:"text-sm text-muted-foreground"},"Select an organization to view tasks.")}r(Sis,"PluginSdkIssuesList");function Cis({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=t9(),f=e??p.companyId??null,{data:x}=Z({queryKey:P.auth.session,queryFn:r(()=>Oa.getSession(),"queryFn"),enabled:c}),b=x?.user?.id??x?.session?.userId??null,{data:v}=Z({queryKey:P.agents.list(f??"__no-company__"),queryFn:r(()=>$t.list(f),"queryFn"),enabled:!!f}),{data:j}=Z({queryKey:P.access.companyUserDirectory(f??"__no-company__"),queryFn:r(()=>pr.listUserDirectory(f),"queryFn"),enabled:!!f&&c}),N=(0,m.useMemo)(()=>vz(),[]),w=(0,m.useMemo)(()=>N.map(R=>R.startsWith("agent:")?R.slice(6):null).filter(R=>!!R),[N]),k=(0,m.useMemo)(()=>uy((v??[]).filter(R=>d||R.status!=="terminated"),w),[v,d,w]),S=(0,m.useMemo)(()=>[...c?Wfe(b):[],...c?VN(j?.users,{excludeUserIds:[b]}):[],...k.map(R=>({id:xh({assigneeAgentId:R.id}),label:R.name,searchText:`${R.name} ${R.role} ${R.title??""}`}))],[j?.users,b,c,k]),C=qv(s),I=C.assigneeAgentId?k.find(R=>R.id===C.assigneeAgentId):null;return(0,m.createElement)(Au,{value:s,options:S,recentOptionIds:N,placeholder:a,noneLabel:i,searchPlaceholder:o,emptyMessage:l,className:u,onConfirm:h,onChange:r(R=>{const T=qv(R);T.assigneeAgentId&&dy(T.assigneeAgentId),T.assigneeUserId&&a_(T.assigneeUserId),n(R,T)},"onChange"),renderTriggerValue:r(R=>R?I?(0,m.createElement)(rM,null,(0,m.createElement)(L5,{icon:I.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 T=qv(R.id),A=T.assigneeAgentId?k.find(D=>D.id===T.assigneeAgentId):null;return(0,m.createElement)(rM,null,A?(0,m.createElement)(L5,{icon:A.icon,className:"h-3.5 w-3.5 shrink-0 text-muted-foreground"}):(0,m.createElement)(Qc,{className:"h-3.5 w-3.5 shrink-0 text-muted-foreground"}),(0,m.createElement)("span",{className:"truncate"},R.label))},"renderOption")})}r(Cis,"PluginSdkAssigneePicker");function _is({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=t9(),p=e??h.companyId??null,{data:f}=Z({queryKey:P.auth.session,queryFn:r(()=>Oa.getSession(),"queryFn")}),x=f?.user?.id??f?.session?.userId??null,{data:b}=Z({queryKey:P.projects.list(p??"__no-company__",{includeArchived:c}),queryFn:r(()=>pa.list(p,{includeArchived:c}),"queryFn"),enabled:!!p}),v=(0,m.useMemo)(()=>(b??[]).filter(S=>c||!S.archivedAt),[c,b]),{orderedProjects:j}=Qy({projects:v,companyId:p,userId:x}),N=(0,m.useMemo)(()=>cy(),[]),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)(Au,{value:s,options:w,recentOptionIds:N,placeholder:a,noneLabel:i,searchPlaceholder:o,emptyMessage:l,className:d,onConfirm:u,onChange:r(S=>{S&&Q0(S),n(S)},"onChange"),renderTriggerValue:r(S=>!S||!k?(0,m.createElement)("span",{className:"text-muted-foreground"},a):(0,m.createElement)(rM,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(I=>I.id===S.id);return(0,m.createElement)(rM,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(_is,"PluginSdkProjectPicker");function rM({children:e}){return(0,m.createElement)("span",{className:"contents"},e)}r(rM,"FragmentSafe");function Iis({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(Iis,"PluginSdkStatusBadge");function Ais({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(Ais,"PluginSdkDataTable");function Tis({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(Tis,"PluginSdkKeyValueList");function Ris({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(Ris,"PluginSdkMetricCard");function Eis({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(Eis,"PluginSdkJsonTree");function Pis({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(Pis,"PluginSdkSpinner");var Mis=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 Dis(e,s){globalThis.__paperclipPluginBridge__={react:e,reactJsxRuntime:t,reactDom:s,sdkUi:{usePluginData:k8e,usePluginAction:N8e,useHostContext:t9,useHostLocation:C8e,useHostNavigation:S8e,usePluginStream:I8e,usePluginToast:_8e,copyTextToClipboard:fa,MarkdownBlock:r(({content:n,className:a,enableWikiLinks:i,wikiLinkRoot:o,resolveWikiLinkHref:l})=>(0,m.createElement)(Sn,{className:a,softBreaks:!1,enableWikiLinks:i,wikiLinkRoot:o,resolveWikiLinkHref:l,children:n}),"MarkdownBlock"),MetricCard:Ris,StatusBadge:Iis,DataTable:Ais,KeyValueList:Tis,JsonTree:Eis,Spinner:Pis,ErrorBoundary:Mis,MarkdownEditor:kis,FileTree:wis,IssuesList:Sis,AssigneePicker:Cis,ProjectPicker:_is,ManagedRoutinesList:jis}}}r(Dis,"initPluginBridge");var Lis=1e4;function $is(e=Lis){if(typeof performance>"u"||typeof performance.clearMeasures!="function")return()=>{};const n=setInterval(r(()=>{globalThis.__paperclipKeepPerfMeasures||performance.clearMeasures()},"reap"),e);return()=>clearInterval(n)}r($is,"startPerfMeasureReaper");var Ois=Fy((e=>{function s(q,U){var O=q.length;q.push(U);e:for(;0<O;){var K=O-1>>>1,H=q[K];if(0<i(H,U))q[K]=U,q[O]=H,O=K;else break e}}r(s,"push");function n(q){return q.length===0?null:q[0]}r(n,"peek");function a(q){if(q.length===0)return null;var U=q[0],O=q.pop();if(O!==U){q[0]=O;e:for(var K=0,H=q.length,ee=H>>>1;K<ee;){var se=2*(K+1)-1,ne=q[se],fe=se+1,X=q[fe];if(0>i(ne,O))fe<H&&0>i(X,ne)?(q[K]=X,q[fe]=O,K=fe):(q[K]=ne,q[se]=O,K=se);else if(fe<H&&0>i(X,O))q[K]=X,q[fe]=O,K=fe;else break e}}return U}r(a,"pop");function i(q,U){var O=q.sortIndex-U.sortIndex;return O!==0?O:q.id-U.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(q){for(var U=n(u);U!==null;){if(U.callback===null)a(u);else if(U.startTime<=q)a(u),U.sortIndex=U.expirationTime,s(d,U);else break;U=n(u)}}r(S,"advanceTimers");function C(q){if(v=!1,S(q),!b)if(n(d)!==null)b=!0,I||(I=!0,B());else{var U=n(u);U!==null&&$(C,U.startTime-q)}}r(C,"handleTimeout");var I=!1,R=-1,T=5,A=-1;function D(){return j?!0:!(e.unstable_now()-A<T)}r(D,"shouldYieldToHost");function M(){if(j=!1,I){var q=e.unstable_now();A=q;var U=!0;try{e:{b=!1,v&&(v=!1,w(R),R=-1),x=!0;var O=f;try{t:{for(S(q),p=n(d);p!==null&&!(p.expirationTime>q&&D());){var K=p.callback;if(typeof K=="function"){p.callback=null,f=p.priorityLevel;var H=K(p.expirationTime<=q);if(q=e.unstable_now(),typeof H=="function"){p.callback=H,S(q),U=!0;break t}p===n(d)&&a(d),S(q)}else a(d);p=n(d)}if(p!==null)U=!0;else{var ee=n(u);ee!==null&&$(C,ee.startTime-q),U=!1}}break e}finally{p=null,f=O,x=!1}U=void 0}}finally{U?B():I=!1}}}r(M,"performWorkUntilDeadline");var B;if(typeof k=="function")B=r(function(){k(M)},"schedulePerformWorkUntilDeadline");else if(typeof MessageChannel<"u"){var E=new MessageChannel,z=E.port2;E.port1.onmessage=M,B=r(function(){z.postMessage(null)},"schedulePerformWorkUntilDeadline")}else B=r(function(){N(M,0)},"schedulePerformWorkUntilDeadline");function $(q,U){R=N(function(){q(e.unstable_now())},U)}r($,"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(q){q.callback=null},e.unstable_forceFrameRate=function(q){0>q||125<q||(T=0<q?Math.floor(1e3/q):5)},e.unstable_getCurrentPriorityLevel=function(){return f},e.unstable_next=function(q){switch(f){case 1:case 2:case 3:var U=3;break;default:U=f}var O=f;f=U;try{return q()}finally{f=O}},e.unstable_requestPaint=function(){j=!0},e.unstable_runWithPriority=function(q,U){switch(q){case 1:case 2:case 3:case 4:case 5:break;default:q=3}var O=f;f=q;try{return U()}finally{f=O}},e.unstable_scheduleCallback=function(q,U,O){var K=e.unstable_now();switch(typeof O=="object"&&O!==null?(O=O.delay,O=typeof O=="number"&&0<O?K+O:K):O=K,q){case 1:var H=-1;break;case 2:H=250;break;case 5:H=1073741823;break;case 4:H=1e4;break;default:H=5e3}return H=O+H,q={id:h++,callback:U,priorityLevel:q,startTime:O,expirationTime:H,sortIndex:-1},O>K?(q.sortIndex=O,s(u,q),n(d)===null&&q===n(u)&&(v?(w(R),R=-1):v=!0,$(C,O-K))):(q.sortIndex=H,s(d,q),b||x||(b=!0,I||(I=!0,B()))),q},e.unstable_shouldYield=D,e.unstable_wrapCallback=function(q){var U=f;return function(){var O=f;f=U;try{return q.apply(this,arguments)}finally{f=O}}}})),Fis=Fy(((e,s)=>{s.exports=Ois()})),Bis=Fy((e=>{var s=Fis(),n=X8(),a=Ppe();function i(g){var y="https://react.dev/errors/"+g;if(1<arguments.length){y+="?args[]="+encodeURIComponent(arguments[1]);for(var _=2;_<arguments.length;_++)y+="&args[]="+encodeURIComponent(arguments[_])}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,_=g;if(g.alternate)for(;y.return;)y=y.return;else{g=y;do y=g,(y.flags&4098)!==0&&(_=y.return),g=y.return;while(g)}return y.tag===3?_: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 _=g,F=y;;){var V=_.return;if(V===null)break;var J=V.alternate;if(J===null){if(F=V.return,F!==null){_=F;continue}break}if(V.child===J.child){for(J=V.child;J;){if(J===_)return u(V),g;if(J===F)return u(V),y;J=J.sibling}throw Error(i(188))}if(_.return!==F.return)_=V,F=J;else{for(var ve=!1,qe=V.child;qe;){if(qe===_){ve=!0,_=V,F=J;break}if(qe===F){ve=!0,F=V,_=J;break}qe=qe.sibling}if(!ve){for(qe=J.child;qe;){if(qe===_){ve=!0,_=J,F=V;break}if(qe===F){ve=!0,F=J,_=V;break}qe=qe.sibling}if(!ve)throw Error(i(189))}}if(_.alternate!==F)throw Error(i(190))}if(_.tag!==3)throw Error(i(188));return _.stateNode.current===_?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"),I=Symbol.for("react.suspense"),R=Symbol.for("react.suspense_list"),T=Symbol.for("react.memo"),A=Symbol.for("react.lazy"),D=Symbol.for("react.activity"),M=Symbol.for("react.memo_cache_sentinel"),B=Symbol.iterator;function E(g){return g===null||typeof g!="object"?null:(g=B&&g[B]||g["@@iterator"],typeof g=="function"?g:null)}r(E,"getIteratorFn");var z=Symbol.for("react.client.reference");function $(g){if(g==null)return null;if(typeof g=="function")return g.$$typeof===z?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 I:return"Suspense";case R:return"SuspenseList";case D: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 T:return y=g.displayName||null,y!==null?y:$(g.type)||"Memo";case A:y=g._payload,g=g._init;try{return $(g(y))}catch{}}return null}r($,"getComponentNameFromType");var q=Array.isArray,U=n.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE,O=a.__DOM_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE,K={pending:!1,data:null,method:null,action:null},H=[],ee=-1;function se(g){return{current:g}}r(se,"createCursor");function ne(g){0>ee||(g.current=H[ee],H[ee]=null,ee--)}r(ne,"pop");function fe(g,y){ee++,H[ee]=g.current,g.current=y}r(fe,"push");var X=se(null),re=se(null),oe=se(null),G=se(null);function Y(g,y){switch(fe(oe,y),fe(re,g),fe(X,null),y.nodeType){case 9:case 11:g=(g=y.documentElement)&&(g=g.namespaceURI)?VY(g):0;break;default:if(g=y.tagName,y=y.namespaceURI)y=VY(y),g=HY(y,g);else switch(g){case"svg":g=1;break;case"math":g=2;break;default:g=0}}ne(X),fe(X,g)}r(Y,"pushHostContainer");function Q(){ne(X),ne(re),ne(oe)}r(Q,"popHostContainer");function te(g){g.memoizedState!==null&&fe(G,g);var y=X.current,_=HY(y,g.type);y!==_&&(fe(re,g),fe(X,_))}r(te,"pushHostContext");function ae(g){re.current===g&&(ne(X),ne(re)),G.current===g&&(ne(G),qS._currentValue=K)}r(ae,"popHostContext");var le,he;function ce(g){if(le===void 0)try{throw Error()}catch(_){var y=_.stack.trim().match(/\n( *(at )?)/);le=y&&y[1]||"",he=-1<_.stack.indexOf(`
773
+ `)}U!==N&&(n.textContent=U,N=U)}r(R,"step");function T(){const E=d>0&&u>0;if(a.matches){o&&(o=!1,s.current!==null&&cancelAnimationFrame(s.current),s.current=null),E&&S();return}if(!i||!E){o&&(o=!1,s.current!==null&&cancelAnimationFrame(s.current),s.current=null);return}o||(o=!0,l=0,s.current=requestAnimationFrame(R))}r(T,"syncLoop");const A=new ResizeObserver(()=>{const E=mpe(n);h=E.w,p=E.h,k(),T()});A.observe(n);const D=r(()=>{i=document.visibilityState!=="hidden",T()},"onVisibilityChange");document.addEventListener("visibilitychange",D);const M=r(()=>{T()},"onMotionChange");a.addEventListener("change",M);const B=mpe(n);return h=B.w,p=B.h,k(),T(),()=>{o=!1,s.current!==null&&cancelAnimationFrame(s.current),A.disconnect(),document.removeEventListener("visibilitychange",D),a.removeEventListener("change",M)}},[]),(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(Las,"AsciiArtAnimation");function $as({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($as,"PaperclipLockup");function Oas(){const e=Dt(),s=Mn(),[n]=fi(),[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)(()=>yCe(n.get("next")||Pas()||"/"),[n]),v=Z({queryKey:P.health,queryFn:r(()=>tu.get(),"queryFn"),retry:!1}),{data:j,isLoading:N,error:w}=Z({queryKey:P.auth.session,queryFn:r(()=>Oa.getSession(),"queryFn"),retry:!1});(0,m.useEffect)(()=>{j&&(gV(),s(b,{replace:!0}))},[j,s,b]);const k=je({mutationFn:r(async()=>{if(a==="sign_in"){await Oa.signInEmail({email:c.trim(),password:u});return}await Oa.signUpEmail({name:o.trim(),email:c.trim(),password:u})},"mutationFn"),onSuccess:r(async()=>{f(null),await e.invalidateQueries({queryKey:P.auth.session}),await e.invalidateQueries({queryKey:P.health}),await e.resetQueries({queryKey:P.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)($m,{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)(bV,{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)(yk,{})}),(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)($as,{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)(L,{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)(Las,{})})]})}r(Oas,"AuthPage");function Fas(){const e=Dt(),s=va(),[n]=fi(),a=(s.token??"").trim(),i=(n.get("code")??"").trim(),o=(0,m.useMemo)(()=>`/board-claim/${encodeURIComponent(a)}${i?`?code=${encodeURIComponent(i)}`:""}`,[a,i]),l=Z({queryKey:P.auth.session,queryFn:r(()=>Oa.getSession(),"queryFn"),retry:!1}),c=Z({queryKey:["board-claim",a,i],queryFn:r(()=>pr.getBoardClaimStatus(a,i),"queryFn"),enabled:a.length>0&&i.length>0,retry:!1}),d=je({mutationFn:r(()=>pr.claimBoard(a,i),"mutationFn"),onSuccess:r(async()=>{await e.invalidateQueries({queryKey:P.auth.session}),await e.invalidateQueries({queryKey:P.health}),await e.invalidateQueries({queryKey:P.companies.all}),await e.invalidateQueries({queryKey:P.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)(rn,{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)(rn,{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)(L,{asChild:!0,className:"mt-4",children:(0,t.jsx)(Ke,{to:"/",children:"Open board"})})]})}):l.data?(0,t.jsx)("div",{className:"mx-auto max-w-xl py-10",children:(0,t.jsxs)(rn,{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)(L,{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)(rn,{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)(L,{asChild:!0,className:"mt-4",children:(0,t.jsx)(Ke,{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(Fas,"BoardClaimPage");function Bas(){const e=Dt(),s=va(),[n]=fi(),a=(s.id??"").trim(),i=(n.get("token")??"").trim(),o=(0,m.useMemo)(()=>`/cli-auth/${encodeURIComponent(a)}${i?`?token=${encodeURIComponent(i)}`:""}`,[a,i]),l=Z({queryKey:P.auth.session,queryFn:r(()=>Oa.getSession(),"queryFn"),retry:!1}),c=Z({queryKey:["cli-auth-challenge",a,i],queryFn:r(()=>pr.getCliAuthChallenge(a,i),"queryFn"),enabled:a.length>0&&i.length>0,retry:!1}),d=je({mutationFn:r(()=>pr.approveCliAuthChallenge(a,i),"mutationFn"),onSuccess:r(async()=>{await e.invalidateQueries({queryKey:P.auth.session}),await c.refetch()},"onSuccess")}),u=je({mutationFn:r(()=>pr.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)(rn,{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)(rn,{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)(rn,{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)(rn,{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)(L,{asChild:!0,className:"mt-4",children:(0,t.jsx)(Ke,{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)(rn,{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)(L,{onClick:r(()=>d.mutate(),"onClick"),disabled:!h.canApprove||d.isPending||u.isPending,children:d.isPending?"Approving...":"Approve CLI access"}),(0,t.jsx)(L,{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(Bas,"CliAuthPage");var zas=VLe.filter(e=>e!=="paperclip_runner"),hpe=new Set(["claude_local","codex_local","gemini_local","kimi_local","opencode_local","pi_local","cursor"]);function qas(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(qas,"readNestedString");var Sw="w-full border border-zinc-800 bg-zinc-950 px-3 py-2 text-sm text-zinc-100 outline-none focus:border-zinc-500",ppe="border border-zinc-800 bg-zinc-950/95 p-6",fpe="flex-1 border px-3 py-2 text-sm transition-colors";function Uas(e){return e?e.charAt(0).toUpperCase()+e.slice(1):null}r(Uas,"formatHumanRole");function b4e(e){if(!e||typeof e!="object")return null;const s=e.code;return typeof s=="string"&&s.trim().length>0?s:null}r(b4e,"getAuthErrorCode");function Kas(e){if(!(e instanceof Error))return null;const s=e.message.trim();return s.length>0?s:null}r(Kas,"getAuthErrorMessage");function Was(e,s,n){const a=b4e(e),i=Kas(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(Was,"mapInviteAuthFeedback");function xpe(e){return!!(e&&typeof e=="object"&&"bootstrapAccepted"in e)}r(xpe,"isBootstrapAcceptancePayload");function Vas(e,s){return!e||typeof e!="object"||s?!1:e.status==="approved"}r(Vas,"isApprovedHumanJoinPayload");function V8({companyDisplayName:e,companyLogoUrl:s,className:n}){return(0,t.jsx)(eS,{companyName:e,logoUrl:s,logoFit:"contain",className:n})}r(V8,"InviteCompanyLogo");function gpe({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)(V8,{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(gpe,"AwaitingJoinApprovalPanel");function Has(){const e=Dt(),s=Mn(),{setSelectedCompanyId:n}=ps(),a=(va().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),[I,R]=(0,m.useState)(null),[T,A]=(0,m.useState)(!1),D="invite-auth-error",M=Z({queryKey:P.health,queryFn:r(()=>tu.get(),"queryFn"),retry:!1}),B=Z({queryKey:P.auth.session,queryFn:r(()=>Oa.getSession(),"queryFn"),retry:!1}),E=Z({queryKey:P.access.invite(a),queryFn:r(()=>pr.getInvite(a),"queryFn"),enabled:a.length>0,retry:!1}),z=e7({enabled:!!B.data&&!!E.data?.companyId,staleTime:0}),$=M.data?.deploymentMode!=="local_trusted"?z.isFetchedAfterMount:!0,q=$?z.data?.companies??[]:[];(0,m.useEffect)(()=>{a&&dpe(a)},[a]),(0,m.useEffect)(()=>{A(!1)},[a]),(0,m.useEffect)(()=>{if(!$)return;const ge=z.data?.companies;!ge||!E.data?.companyId||ge.some(me=>me.id===E.data.companyId)&&KR(a)},[z.data,E.data,$,a]);const U=E.data,O=!!B.data&&!!U?.companyId&&!$,K=!!U?.companyId&&q.some(ge=>ge.id===U?.companyId),H=U?.companyName?.trim()||"this Paperclip company",ee=U?.companyLogoUrl?.trim()||null,se=U?.invitedByUserName?.trim()||null,ne=U?.inviteMessage?.trim()||null,fe=Uas(U?.humanRole),X=U?.joinRequestStatus??null,re=U?.joinRequestType??null,oe=re==="human"&&(X==="pending_approval"||X==="approved"),G=M.data?.deploymentMode==="authenticated"&&!B.data&&U?.allowedJoinTypes!=="agent",Y=U?.inviteType!=="bootstrap_ceo"&&U?.allowedJoinTypes==="agent",Q=!!B.data&&!Y&&U?.inviteType!=="bootstrap_ceo"&&(!X||oe)&&!O&&!K&&!w&&S===null,te=B.data?.user.name?.trim()||B.data?.user.email?.trim()||"this account",ae=d.trim().length>0&&h.trim().length>0&&(i==="sign_in"||l.trim().length>0&&h.trim().length>=8),le=je({mutationFn:r(async()=>{if(!U)throw new Error("Invite not found");if(O)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 U.inviteType==="bootstrap_ceo"||U.allowedJoinTypes!=="agent"?pr.acceptInvite(a,{requestType:"human"}):pr.acceptInvite(a,{requestType:"agent",agentName:f.trim(),adapterType:b,capabilities:j.trim()||null})},"mutationFn"),onSuccess:r(async ge=>{C(null),KR(a);const me=xpe(ge);k({kind:me?"bootstrap":"join",payload:ge}),await e.invalidateQueries({queryKey:P.auth.session}),await e.invalidateQueries({queryKey:P.access.currentBoardAccess}),await e.invalidateQueries({queryKey:P.companies.all}),U?.companyId&&Vas(ge,Y)&&(n(U.companyId,{source:"manual"}),s("/",{replace:!0}))},"onSuccess"),onError:r(ge=>{C(ge instanceof Error?ge.message:"Failed to accept invite")},"onError")});(0,m.useEffect)(()=>{!Q||T||le.isPending||(A(!0),C(null),le.mutate())},[le,T,Q]);const he=je({mutationFn:r(async()=>{if(i==="sign_in"){await Oa.signInEmail({email:d.trim(),password:h});return}await Oa.signUpEmail({name:l.trim(),email:d.trim(),password:h})},"mutationFn"),onSuccess:r(async()=>{R(null),dpe(a),await e.invalidateQueries({queryKey:P.auth.session}),await e.invalidateQueries({queryKey:P.health}),await e.invalidateQueries({queryKey:P.access.currentBoardAccess});const{companies:ge}=await l$e(e);if(U?.companyId&&ge.some(me=>me.id===U.companyId)){KR(a),n(U.companyId,{source:"manual"}),s("/",{replace:!0});return}if(!(!U||U.inviteType!=="bootstrap_ceo"))try{xpe(await le.mutateAsync())&&s("/",{replace:!0})}catch{return}},"onSuccess"),onError:r(ge=>{const me=Was(ge,i,d);b4e(ge)==="USER_ALREADY_EXISTS_USE_ANOTHER_EMAIL"&&(o("sign_in"),p("")),R(me)},"onError")}),ce=(0,m.useMemo)(()=>U?K?"Open organization":U.inviteType==="bootstrap_ceo"?"Accept invite":Y?"Submit request":B.data?"Accept invite":"Continue":"Continue",[U,K,B.data,Y]);if(!a)return(0,t.jsx)("div",{className:"mx-auto max-w-xl py-10 text-sm text-destructive",children:"Invalid invite token."});if(E.isLoading||M.isLoading||B.isLoading)return(0,t.jsx)("div",{className:"mx-auto max-w-xl py-10 text-sm text-muted-foreground",children:"Loading invite..."});if(O)return(0,t.jsx)("div",{className:"mx-auto max-w-xl py-10 text-sm text-muted-foreground",children:"Checking your access..."});if(E.error||!U)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"&&re==="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)(gpe,{companyDisplayName:H,companyLogoUrl:ee,invitedByUserName:se});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)(L,{asChild:!0,className:"rounded-none",children:(0,t.jsx)(Ke,{to:"/",children:"Open board"})})})]})});if(w?.kind==="join"){const ge=w.payload,me=typeof ge.claimSecret=="string"?ge.claimSecret:null,ie=typeof ge.claimApiKeyPath=="string"?ge.claimApiKeyPath:null,ue=qas(ge.onboarding,["textInstructions","url"]);return!Y&&ge.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)(V8,{companyDisplayName:H,companyLogoUrl:ee,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)(L,{asChild:!0,className:"w-full rounded-none",children:(0,t.jsx)(Ke,{to:"/",children:"Open board"})})})]})}):(0,t.jsx)(gpe,{companyDisplayName:H,companyLogoUrl:ee,invitedByUserName:se,claimSecret:me,claimApiKeyPath:ie,onboardingTextUrl:ue})}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:`${ppe} space-y-6`,children:[(0,t.jsxs)("div",{className:"flex items-start gap-4",children:[(0,t.jsx)(V8,{companyDisplayName:H,companyLogoUrl:ee,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:U.inviteType==="bootstrap_ceo"?"Set up Paperclip":`Join ${H}`}),(0,t.jsx)("p",{className:"mt-2 max-w-2xl text-sm leading-6 text-zinc-300",children:Y?"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:H})]}),(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:se??"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:Y?"Agent join request":fe??"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:Ad(U.expiresAt)})]})]}),ne?(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:ne})]}):null,B.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:te}),"."]}):null]}),(0,t.jsx)("section",{className:`${ppe} h-fit`,children:Y?(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 ",H,"."]})]}),(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:Sw,value:f,onChange:r(ge=>x(ge.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:Sw,value:b,onChange:r(ge=>v(ge.target.value),"onChange"),children:zas.map(ge=>(0,t.jsxs)("option",{value:ge,disabled:!hpe.has(ge),children:[Ff(ge),hpe.has(ge)?"":" (Coming soon)"]},ge))})]}),(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:Sw,rows:4,value:j,onChange:r(ge=>N(ge.target.value),"onChange")})]}),S?(0,t.jsx)("p",{className:"text-xs text-red-400",children:S}):null,(0,t.jsx)(L,{className:"w-full rounded-none",disabled:le.isPending||f.trim().length===0,onClick:r(()=>le.mutate(),"onClick"),children:le.isPending?"Working...":ce})]}):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 ${H}.`:"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:`${fpe} ${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:`${fpe} ${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(ge=>{if(ge.preventDefault(),!he.isPending){if(!ae){R({tone:"error",message:"Please fill in all required fields."});return}he.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:Sw,value:l,onChange:r(ge=>{c(ge.target.value),R(null)},"onChange"),autoComplete:"name",required:!0,"aria-required":"true","aria-invalid":I?.tone==="error"?!0:void 0,"aria-describedby":I?D: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:Sw,value:d,onChange:r(ge=>{u(ge.target.value),R(null)},"onChange"),autoComplete:"username",required:!0,"aria-required":"true","aria-invalid":I?.tone==="error"?!0:void 0,"aria-describedby":I?D: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:Sw,value:h,onChange:r(ge=>{p(ge.target.value),R(null)},"onChange"),autoComplete:i==="sign_in"?"current-password":"new-password",required:!0,"aria-required":"true","aria-invalid":I?.tone==="error"?!0:void 0,"aria-describedby":I?D:void 0})]}),I?(0,t.jsx)("p",{id:D,role:"alert",className:`text-xs ${I.tone==="info"?"text-amber-300":"text-red-400"}`,children:I.message}):null,(0,t.jsx)(L,{type:"submit",className:"w-full rounded-none",disabled:he.isPending,"aria-disabled":!ae||he.isPending,children:he.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":Q?"Completing organization access":U.inviteType==="bootstrap_ceo"?"Accept bootstrap invite":"Accept organization invite"}),(0,t.jsx)("p",{className:"mt-1 text-sm text-zinc-400",children:Q?`Granting your access to ${H}.`:K?`This account already belongs to ${H}.`:`This will ${U.inviteType==="bootstrap_ceo"?"finish setting up Paperclip":`grant or complete your access to ${H}`}.`})]}),S?(0,t.jsx)("p",{className:"text-xs text-red-400",children:S}):null,Q?(0,t.jsx)("div",{className:"text-sm text-zinc-400",children:le.isPending?"Submitting request...":"Finishing sign-in..."}):(0,t.jsx)(L,{className:"w-full rounded-none",disabled:le.isPending,onClick:r(()=>{if(K&&U.companyId){KR(a),n(U.companyId,{source:"manual"}),s("/",{replace:!0});return}le.mutate()},"onClick"),children:le.isPending?"Working...":ce})]})})]})})})}r(Has,"InviteLandingPage");var Gas=15e3,Qas={parent:"Parent task",child:"Sub-task",blocked_by:"Blocked by",blocks:"Blocks"};function Yas(){(0,m.useEffect)(()=>{const e=document.createElement("meta");return e.name="robots",e.content="noindex",document.head.appendChild(e),()=>e.remove()},[])}r(Yas,"useNoIndexMeta");function H8(e,s){const n=`/s/${encodeURIComponent(e)}`;return s?`${n}/issues/${encodeURIComponent(s)}`:n}r(H8,"sharePath");var Jas=/^(?:https?:\/\/[^/]+)?\/api\/attachments\/([^/?#]+)\/content(?:[?#].*)?$/i;function Xas(e,s){const n=Jas.exec(s.trim());return n?`/api/public/share/${encodeURIComponent(e)}/attachments/${n[1]}/content`:null}r(Xas,"publicShareImageSrc");function $C({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($C,"Section");function G8({actor:e}){return(0,t.jsx)(Hl,{name:e.name,avatarUrl:e.iconUrl,size:"sm"})}r(G8,"ActorIdentity");function Q8({value:e}){return(0,t.jsx)("time",{dateTime:e,title:Rr(e),className:"text-xs text-muted-foreground",children:cr(e)})}r(Q8,"Timestamp");function Zas({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(Zas,"ActiveRunPill");function v4e({attachments:e}){return(0,t.jsx)(A9,{children:e.map(s=>{const n=Xje({name:s.filename,url:s.url,contentType:s.contentType,byteSize:s.byteSize}),a=n.icon,i=T9(s.byteSize);return(0,t.jsxs)(N9,{size:"sm",children:[(0,t.jsx)(S9,{children:(0,t.jsx)(a,{"aria-hidden":!0})}),(0,t.jsxs)(C9,{children:[(0,t.jsx)(_9,{className:"max-w-48",children:s.filename}),(0,t.jsx)(I9,{className:"max-w-48",children:i?`${n.label} · ${i}`:n.label})]}),(0,t.jsx)(Gje,{"aria-label":`Download ${s.filename}`,render:(0,t.jsx)("a",{href:s.url,download:s.filename,rel:"noreferrer"})})]},s.id)})})}r(v4e,"AttachmentList");function eis({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)(Xi,{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:Qas[e.relation]}),e.navigable?(0,t.jsx)(ld,{to:n?H8(s,e.id):H8(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(eis,"RelatedIssueRow");function tis({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)(G8,{actor:e.author}),(0,t.jsx)(Q8,{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)(G8,{actor:e.author}),(0,t.jsx)(Q8,{value:e.createdAt})]}),(0,t.jsx)(Sn,{className:"text-sm",softBreaks:!0,linkIssueReferences:!1,resolveImageSrc:s,children:e.body}),e.attachments.length>0?(0,t.jsx)(v4e,{attachments:e.attachments}):null]})}r(tis,"TimelineEntry");function sis({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)(Ha,{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)(Q8,{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)(po,{className:"h-3.5 w-3.5","aria-hidden":!0}),"Download PDF"]}),(0,t.jsx)(Sn,{className:"text-sm",linkIssueReferences:!1,resolveImageSrc:s,children:e.body})]})]})}r(sis,"DocumentCard");function nis({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)(Vn,{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)(po,{className:"h-3.5 w-3.5","aria-hidden":!0}),"Download"]}):null]})}r(nis,"WorkProductRow");function bpe({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(bpe,"CenteredNotice");function ris({view:e,token:s}){const{company:n,issue:a}=e,i=(0,m.useCallback)(o=>Xas(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)(eS,{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)(ld,{to:H8(s),className:"inline-flex items-center gap-1.5 text-sm text-muted-foreground hover:text-foreground",children:[(0,t.jsx)(Tl,{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)(sp,{status:a.status}),(0,t.jsx)(Bfe,{priority:a.priority,showLabel:!0}),a.assignee?(0,t.jsx)(G8,{actor:a.assignee}):null,e.activeRun?(0,t.jsx)(Zas,{agentName:e.activeRun.agentName}):null]}),(0,t.jsxs)("p",{className:"text-xs text-muted-foreground",children:["Created ",Rr(a.createdAt)," · Updated ",cr(a.updatedAt),a.completedAt?` · Completed ${Rr(a.completedAt)}`:""]})]}),a.description?(0,t.jsx)(Sn,{className:"text-sm",softBreaks:!0,linkIssueReferences:!1,resolveImageSrc:i,children:a.description}):null,e.related.length>0?(0,t.jsx)($C,{title:"Related tasks",children:(0,t.jsx)("ul",{className:"space-y-2",children:e.related.map(o=>(0,t.jsx)(eis,{related:o,token:s,isSharedRoot:e.isSharedRoot},`${o.relation}:${o.id}`))})}):null,e.documents.length>0?(0,t.jsx)($C,{title:"Documents",children:(0,t.jsx)("div",{className:"space-y-2",children:e.documents.map(o=>(0,t.jsx)(sis,{document:o,resolveImageSrc:i},o.key))})}):null,e.attachments.length>0?(0,t.jsx)($C,{title:"Attachments",children:(0,t.jsx)(v4e,{attachments:e.attachments})}):null,e.workProducts.length>0?(0,t.jsx)($C,{title:"Work products",children:(0,t.jsx)("ul",{className:"space-y-2",children:e.workProducts.map(o=>(0,t.jsx)(nis,{product:o},o.id))})}):null,(0,t.jsx)($C,{title:"Activity",children:e.comments.length>0?(0,t.jsx)("ol",{className:"space-y-3",children:e.comments.map(o=>(0,t.jsx)(tis,{comment:o,resolveImageSrc:i},o.id))}):(0,t.jsx)("p",{className:"text-sm text-muted-foreground",children:"No updates yet."})})]})]})}r(ris,"PublicIssueShareContent");function vpe(){const{token:e="",issueId:s}=va();Yas();const n=dze.test(e),a=Z({queryKey:P.publicShare.view(e,s??null),queryFn:r(()=>s?Dk.getPublicShareIssue(e,s):Dk.getPublicShare(e),"queryFn"),enabled:n,retry:!1,refetchOnWindowFocus:!0,refetchInterval:r(i=>i.state.data?.activeRun?Gas:!1,"refetchInterval")});return!n||a.data===null?(0,t.jsx)(bpe,{title:"This link is not available",body:"It may have been revoked, or the address is incomplete."}):a.data?(0,t.jsx)(ris,{view:a.data,token:e}):a.isError?(0,t.jsx)(bpe,{title:"Couldn't load this page",body:"Check your connection and try again.",action:(0,t.jsx)(L,{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)(vn,{className:"h-6 w-1/2"}),(0,t.jsx)(vn,{className:"h-4 w-1/3"}),(0,t.jsx)(vn,{className:"h-24 w-full"})]})})}r(vpe,"PublicIssueSharePage");function ais(){const{selectedCompany:e,selectedCompanyId:s}=ps(),{setBreadcrumbs:n}=Bn(),{pushToast:a}=xi(),i=Dt(),[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=Z({queryKey:P.access.joinRequests(s??"",`${o}:${c}`),queryFn:r(()=>pr.listJoinRequests(s,o,c==="all"?void 0:c),"queryFn"),enabled:!!s}),h=je({mutationFn:r(f=>pr.approveJoinRequest(s,f),"mutationFn"),onSuccess:r(async()=>{await i.invalidateQueries({queryKey:P.access.joinRequests(s,`${o}:${c}`)}),await i.invalidateQueries({queryKey:P.access.companyMembers(s)}),await i.invalidateQueries({queryKey:P.access.companyUserDirectory(s)}),a({title:"Join request approved",tone:"success"})},"onSuccess")}),p=je({mutationFn:r(f=>pr.rejectJoinRequest(s,f),"mutationFn"),onSuccess:r(async()=>{await i.invalidateQueries({queryKey:P.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 dn&&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)(Lqe,{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)(rn,{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)(rn,{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)(ct,{variant:f.status==="pending_approval"?"secondary":f.status==="approved"?"outline":"destructive",children:f.status.replace("_"," ")}),(0,t.jsx)(ct,{variant:"outline",children:f.requestType}),f.adapterType?(0,t.jsx)(ct,{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)(L,{variant:"outline",onClick:r(()=>p.mutate(f.id),"onClick"),disabled:p.isPending,children:"Reject"}),(0,t.jsx)(L,{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(ais,"JoinRequestQueue");var iis=(0,m.lazy)(()=>Jc(()=>import("./CompanyExport-Csbe_I4o.js").then(e=>({default:e.CompanyExport})),__vite__mapDeps([6,5,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24]))),ois=(0,m.lazy)(()=>Jc(()=>import("./Agents.production-koHgVDEu.js").then(e=>({default:e.Agents})),__vite__mapDeps([25,5,7,9,8,10,11,12,13,26,27,28,29,30,31,32,33,23,24]))),lis=(0,m.lazy)(()=>Jc(()=>import("./Routines.production-CCosQxj4.js").then(e=>({default:e.Routines})),__vite__mapDeps([34,5,7,8,9,10,11,12,13,35,14,36,37,28,26,38,39,40,20,41,42,15,16,17,18,29,43,44,30,45,46,22,31,47,33,48,49,50,51,23,24,27]))),ype=(0,m.lazy)(()=>Jc(()=>import("./RoutineDetail.production-tvnkma9I.js").then(e=>({default:e.RoutineDetail})),__vite__mapDeps([52,5,7,8,9,10,11,12,13,35,14,36,37,28,26,38,39,40,20,41,42,15,16,17,18,29,43,44,30,45,46,22,31,47,33,48,49,50,51,23,24,53]))),cis=(0,m.lazy)(()=>Jc(()=>import("./CompanySkills.production-Dfki-nUi.js").then(e=>({default:e.CompanySkills})),__vite__mapDeps([54,5,7,8,9,10,11,12,13,14,36,37,28,26,38,39,40,20,41,27,15,16,17,18,55,53,31,44,21,19,56,47,48,50,23,24]))),dis=(0,m.lazy)(()=>Jc(()=>import("./CompanyActivity.production-B7l2pgBy.js").then(e=>({default:e.CompanyActivity})),__vite__mapDeps([57,5,7,8,9,10,11,12,13,26,27,28,43,37,20,44,48,49,51]))),uis=(0,m.lazy)(()=>Jc(()=>import("./Costs.production-CBHHLCW0.js").then(e=>({default:e.Costs})),__vite__mapDeps([58,5,7,27,28,13,12,44,41,50,26,51,23,24]))),mis=(0,m.lazy)(()=>Jc(()=>import("./OrgChart.production-DzZWjZTS.js").then(e=>({default:e.OrgChart})),__vite__mapDeps([59,5,7,8,9,10,11,12,13,26,45,46,51,23,24])));function u0({children:e}){return(0,t.jsx)(m.Suspense,{fallback:(0,t.jsx)($m,{}),children:e})}r(u0,"ProductionSurface");function his(e,s){const n=e&&s;return(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)(nt,{index:!0,element:(0,t.jsx)(kn,{to:"dashboard",replace:!0})}),(0,t.jsx)(nt,{path:"dashboard",element:(0,t.jsx)(pSt,{})}),(0,t.jsx)(nt,{path:"dashboard/live",element:(0,t.jsx)(fSt,{})}),(0,t.jsx)(nt,{path:"timeline",element:e?(0,t.jsx)(Yp,{to:"/activity/timeline"}):(0,t.jsx)(O2e,{})}),(0,t.jsx)(nt,{path:"onboarding",element:(0,t.jsx)(w4e,{})}),(0,t.jsx)(nt,{path:"companies",element:(0,t.jsx)(tCt,{})}),(0,t.jsx)(nt,{path:"company/settings",element:(0,t.jsx)(s7t,{})}),(0,t.jsx)(nt,{path:"company/settings/environments",element:(0,t.jsx)(kn,{to:"/company/settings/instance/environments",replace:!0})}),(0,t.jsx)(nt,{path:"company/settings/cloud-upstream",element:(0,t.jsx)(kn,{to:"/company/export",replace:!0})}),(0,t.jsxs)(nt,{element:(0,t.jsx)(Hh,{pageKey:"company.members"}),children:[(0,t.jsx)(nt,{path:"company/settings/members",element:(0,t.jsx)(NHt,{})}),(0,t.jsx)(nt,{path:"company/settings/access",element:(0,t.jsx)(SHt,{})})]}),(0,t.jsx)(nt,{element:(0,t.jsx)(Hh,{pageKey:"company.invites"}),children:(0,t.jsx)(nt,{path:"company/settings/invites",element:(0,t.jsx)(kn,{to:"/company/settings/members?tab=invites",replace:!0})})}),(0,t.jsx)(nt,{element:(0,t.jsx)(Hh,{pageKey:"company.export"}),children:(0,t.jsx)(nt,{path:"company/export/*",element:(0,t.jsx)(m.Suspense,{fallback:(0,t.jsx)($m,{}),children:(0,t.jsx)(iis,{})})})}),(0,t.jsx)(nt,{element:(0,t.jsx)(Cut,{}),children:(0,t.jsx)(nt,{element:(0,t.jsx)(Hh,{pageKey:"company.import"}),children:(0,t.jsx)(nt,{path:"company/import",element:(0,t.jsx)(ars,{})})})}),(0,t.jsx)(nt,{element:(0,t.jsx)(Hh,{pageKey:"company.secrets"}),children:(0,t.jsx)(nt,{path:"company/settings/secrets",element:(0,t.jsx)(ens,{})})}),(0,t.jsx)(nt,{path:"company/settings/tools",element:(0,t.jsx)(kpe,{})}),(0,t.jsx)(nt,{path:"company/settings/tools/:tab",element:(0,t.jsx)(kpe,{})}),(0,t.jsx)(nt,{path:"tools",element:(0,t.jsx)(Npe,{})}),(0,t.jsx)(nt,{path:"tools/:tab",element:(0,t.jsx)(Npe,{})}),(0,t.jsx)(nt,{path:"apps",element:(0,t.jsx)(bQt,{})}),(0,t.jsx)(nt,{path:"apps/browse",element:(0,t.jsx)(kn,{to:"/apps",replace:!0})}),(0,t.jsx)(nt,{path:"apps/connections",element:(0,t.jsx)(kn,{to:"/apps",replace:!0})}),(0,t.jsx)(nt,{path:"apps/byo",element:(0,t.jsx)(KPe,{byoOnly:!0})}),(0,t.jsx)(nt,{path:"apps/vercel-connect",element:(0,t.jsx)(jpe,{credentialSource:"vercel_connect"})}),(0,t.jsx)(nt,{path:"apps/connect",element:(0,t.jsx)(jpe,{})}),(0,t.jsx)(nt,{path:"apps/chat/connect",element:(0,t.jsx)(KB,{children:(0,t.jsx)(RYt,{})})}),(0,t.jsx)(nt,{path:"apps/chat/:endpointId",element:(0,t.jsx)(KB,{children:(0,t.jsx)(kn,{to:"settings",replace:!0})})}),(0,t.jsx)(nt,{path:"apps/chat/:endpointId/:tab",element:(0,t.jsx)(KB,{children:(0,t.jsx)(OJt,{})})}),(0,t.jsx)(nt,{path:"apps/connect/:appKey",element:(0,t.jsx)(kn,{to:"/apps",replace:!0})}),(0,t.jsx)(nt,{path:"apps/connect/:appKey/:stage",element:(0,t.jsx)(kn,{to:"/apps",replace:!0})}),(0,t.jsx)(nt,{path:"apps/review",element:(0,t.jsx)(VJt,{})}),(0,t.jsx)(nt,{path:"apps/attention",element:(0,t.jsx)(kn,{to:"/apps",replace:!0})}),(0,t.jsx)(nt,{path:"apps/gateways",element:(0,t.jsx)(Nme,{})}),(0,t.jsx)(nt,{path:"apps/gateways/:gatewayId",element:(0,t.jsx)(kn,{to:"overview",replace:!0})}),(0,t.jsx)(nt,{path:"apps/gateways/:gatewayId/:tab",element:(0,t.jsx)(wXt,{})}),(0,t.jsx)(nt,{path:"apps/advanced",element:(0,t.jsx)(Gue,{})}),(0,t.jsx)(nt,{path:"apps/advanced/gateways",element:(0,t.jsx)(Nme,{})}),(0,t.jsx)(nt,{path:"apps/advanced/profiles/new",element:(0,t.jsx)(Zue,{mode:"new"})}),(0,t.jsx)(nt,{path:"apps/advanced/profiles/:profileId/edit",element:(0,t.jsx)(Zue,{mode:"edit"})}),(0,t.jsx)(nt,{path:"apps/advanced/profiles/:profileId",element:(0,t.jsx)(KGt,{})}),(0,t.jsx)(nt,{path:"apps/advanced/audit",element:(0,t.jsx)(kn,{to:"/apps",replace:!0})}),(0,t.jsx)(nt,{path:"apps/advanced/run-your-own",element:(0,t.jsx)(kn,{to:"/apps",replace:!0})}),(0,t.jsx)(nt,{path:"apps/advanced/:tab",element:(0,t.jsx)(Gue,{})}),(0,t.jsx)(nt,{path:"apps/app/:applicationId",element:(0,t.jsx)(jme,{})}),(0,t.jsx)(nt,{path:"apps/app/:applicationId/:tab",element:(0,t.jsx)(jme,{})}),(0,t.jsx)(nt,{path:"apps/:connectionId",element:(0,t.jsx)(kn,{to:"permissions",replace:!0})}),(0,t.jsx)(nt,{path:"apps/:connectionId/:tab",element:(0,t.jsx)(WQt,{})}),(0,t.jsx)(nt,{path:"company/settings/instance",element:(0,t.jsx)(kn,{to:"/company/settings",replace:!0})}),(0,t.jsx)(nt,{element:(0,t.jsx)(Hh,{pageKey:"instance.profile"}),children:(0,t.jsx)(nt,{path:"company/settings/instance/profile",element:(0,t.jsx)(uas,{})})}),(0,t.jsx)(nt,{path:"company/settings/instance/general",element:(0,t.jsx)(kn,{to:"/company/settings",replace:!0})}),(0,t.jsx)(nt,{path:"company/settings/instance/heartbeats",element:(0,t.jsx)(kn,{to:"/company/settings",replace:!0})}),(0,t.jsxs)(nt,{element:(0,t.jsx)(Hh,{pageKey:"instance.environments"}),children:[(0,t.jsx)(nt,{path:"company/settings/instance/environments",element:(0,t.jsx)(RB,{})}),(0,t.jsx)(nt,{path:"company/settings/instance/environments/new",element:(0,t.jsx)(RB,{mode:"create"})}),(0,t.jsx)(nt,{path:"company/settings/instance/environments/:environmentId/edit",element:(0,t.jsx)(RB,{mode:"edit"})})]}),(0,t.jsx)(nt,{element:(0,t.jsx)(Hh,{pageKey:"instance.access"}),children:(0,t.jsx)(nt,{path:"company/settings/instance/access",element:(0,t.jsx)(nas,{})})}),(0,t.jsx)(nt,{element:(0,t.jsx)(Hh,{pageKey:"instance.experimental"}),children:(0,t.jsx)(nt,{path:"company/settings/instance/experimental",element:(0,t.jsx)(sas,{})})}),(0,t.jsxs)(nt,{element:(0,t.jsx)(Hh,{pageKey:"instance.plugins"}),children:[(0,t.jsx)(nt,{path:"company/settings/instance/plugins",element:(0,t.jsx)(has,{})}),(0,t.jsx)(nt,{path:"company/settings/instance/plugins/:pluginId",element:(0,t.jsx)(pas,{})})]}),(0,t.jsx)(nt,{element:(0,t.jsx)(Hh,{pageKey:"instance.adapters"}),children:(0,t.jsx)(nt,{path:"company/settings/instance/adapters",element:(0,t.jsx)(ipe,{})})}),(0,t.jsx)(nt,{path:"company/settings/:settingsRoutePath/*",element:(0,t.jsx)(gHt,{})}),(0,t.jsx)(nt,{path:"skills/sources",element:(0,t.jsx)(Yme,{})}),(0,t.jsx)(nt,{path:"skills/sources/:sourceId",element:(0,t.jsx)(Yme,{})}),(0,t.jsx)(nt,{path:"skills/studio",element:(0,t.jsx)(nz,{})}),(0,t.jsx)(nt,{path:"skills/studio/new",element:(0,t.jsx)(nz,{})}),(0,t.jsx)(nt,{path:"skills/studio/:skillId",element:(0,t.jsx)(nz,{})}),(0,t.jsx)(nt,{path:"skills/:skillId/studio",element:(0,t.jsx)(y4e,{})}),(0,t.jsx)(nt,{path:"skills/*",element:e?(0,t.jsx)($Zt,{}):(0,t.jsx)(u0,{children:(0,t.jsx)(cis,{})})}),(0,t.jsx)(nt,{path:"settings",element:(0,t.jsx)(Tv,{})}),(0,t.jsx)(nt,{path:"settings/*",element:(0,t.jsx)(Tv,{})}),(0,t.jsx)(nt,{path:"plugins/:pluginId",element:(0,t.jsx)(ope,{})}),(0,t.jsx)(nt,{path:"org",element:e?(0,t.jsx)(kn,{to:"/agents/all",replace:!0}):(0,t.jsx)(u0,{children:(0,t.jsx)(mis,{})})}),(0,t.jsx)(nt,{path:"agents",element:(0,t.jsx)(kn,{to:"/agents/all",replace:!0})}),iH.map(a=>(0,t.jsx)(nt,{path:`agents/${a}`,element:e?(0,t.jsx)(ICt,{}):(0,t.jsx)(u0,{children:(0,t.jsx)(ois,{})})},a)),(0,t.jsx)(nt,{path:"agents/new",element:(0,t.jsx)(Eas,{})}),(0,t.jsx)(nt,{path:"agents/:agentId",element:(0,t.jsx)(iF,{})}),(0,t.jsx)(nt,{path:"agents/:agentId/:tab",element:(0,t.jsx)(iF,{})}),(0,t.jsx)(nt,{path:"agents/:agentId/runs/:runId",element:(0,t.jsx)(iF,{})}),(0,t.jsx)(nt,{path:"projects",element:(0,t.jsx)(qIt,{})}),(0,t.jsx)(nt,{path:"projects/:projectId",element:(0,t.jsx)(Jb,{})}),(0,t.jsx)(nt,{path:"projects/:projectId/overview",element:(0,t.jsx)(Jb,{})}),(0,t.jsx)(nt,{path:"projects/:projectId/issues",element:(0,t.jsx)(Jb,{})}),(0,t.jsx)(nt,{path:"projects/:projectId/issues/:filter",element:(0,t.jsx)(Jb,{})}),(0,t.jsx)(nt,{element:(0,t.jsx)(dO,{}),children:(0,t.jsx)(nt,{path:"projects/:projectId/workspaces/:workspaceId",element:(0,t.jsx)(ETt,{})})}),(0,t.jsx)(nt,{path:"projects/:projectId/workspaces",element:(0,t.jsx)(Jb,{})}),(0,t.jsx)(nt,{path:"projects/:projectId/configuration",element:(0,t.jsx)(Jb,{})}),(0,t.jsx)(nt,{path:"projects/:projectId/budget",element:(0,t.jsx)(Jb,{})}),(0,t.jsx)(nt,{element:(0,t.jsx)(dO,{}),children:(0,t.jsx)(nt,{path:"workspaces",element:(0,t.jsx)(DTt,{})})}),(0,t.jsx)(nt,{path:"issues",element:(0,t.jsx)(GRt,{})}),(0,t.jsx)(nt,{path:"tasks",element:(0,t.jsx)(kn,{to:"/issues",replace:!0})}),(0,t.jsx)(nt,{path:"search",element:(0,t.jsx)(pEt,{})}),n?(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)(nt,{path:"issues/all",element:(0,t.jsx)(oh,{view:"all"})}),(0,t.jsx)(nt,{path:"issues/active",element:(0,t.jsx)(oh,{view:"active"})}),(0,t.jsx)(nt,{path:"issues/backlog",element:(0,t.jsx)(oh,{view:"backlog"})}),(0,t.jsx)(nt,{path:"issues/done",element:(0,t.jsx)(oh,{view:"done"})}),(0,t.jsx)(nt,{path:"issues/recent",element:(0,t.jsx)(oh,{view:"recent"})})]}):(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)(nt,{path:"issues/all",element:(0,t.jsx)(kn,{to:"/issues",replace:!0})}),(0,t.jsx)(nt,{path:"issues/active",element:(0,t.jsx)(kn,{to:"/issues",replace:!0})}),(0,t.jsx)(nt,{path:"issues/backlog",element:(0,t.jsx)(kn,{to:"/issues",replace:!0})}),(0,t.jsx)(nt,{path:"issues/done",element:(0,t.jsx)(kn,{to:"/issues",replace:!0})}),(0,t.jsx)(nt,{path:"issues/recent",element:(0,t.jsx)(kn,{to:"/issues",replace:!0})})]}),(0,t.jsx)(nt,{path:"chats",element:(0,t.jsx)(m4t,{})}),(0,t.jsx)(nt,{path:"chats/:agentRef",element:(0,t.jsx)(p4t,{})}),(0,t.jsx)(nt,{path:"issues/:issueId",element:(0,t.jsx)(o4t,{})}),null,(0,t.jsx)(nt,{path:"routines",element:e?(0,t.jsx)(H4t,{}):(0,t.jsx)(u0,{children:(0,t.jsx)(lis,{})})}),(0,t.jsx)(nt,{path:"cases",element:(0,t.jsx)(Xse,{children:(0,t.jsx)(Vut,{})})}),(0,t.jsx)(nt,{path:"cases/:caseIdentifier",element:(0,t.jsx)(Xse,{children:(0,t.jsx)(Apt,{})})}),(0,t.jsx)(nt,{path:"pixels-office",element:(0,t.jsx)(Sut,{children:(0,t.jsx)(Nqt,{})})}),(0,t.jsx)(nt,{path:"status",element:(0,t.jsx)(Zse,{children:(0,t.jsx)(Vle,{})})}),(0,t.jsx)(nt,{path:"status/:cardId",element:(0,t.jsx)(Zse,{children:(0,t.jsx)(Vle,{})})}),(0,t.jsx)(nt,{path:"status-cards",element:(0,t.jsx)(Spe,{})}),(0,t.jsx)(nt,{path:"status-cards/:cardId",element:(0,t.jsx)(Spe,{})}),(0,t.jsx)(nt,{path:"review-queue",element:(0,t.jsx)(e0,{children:(0,t.jsx)(u$t,{})})}),(0,t.jsx)(nt,{path:"learnings",element:(0,t.jsx)(e0,{children:(0,t.jsx)(h$t,{})})}),(0,t.jsx)(nt,{path:"pipelines",element:(0,t.jsx)(e0,{children:(0,t.jsx)(HF,{})})}),(0,t.jsx)(nt,{path:"pipelines/:pipelineId",element:(0,t.jsx)(e0,{children:(0,t.jsx)(HF,{})})}),(0,t.jsx)(nt,{path:"pipelines/:pipelineId/add",element:(0,t.jsx)(e0,{children:(0,t.jsx)(HF,{})})}),(0,t.jsx)(nt,{path:"pipelines/:pipelineId/settings",element:(0,t.jsx)(e0,{children:(0,t.jsx)(iOt,{})})}),(0,t.jsx)(nt,{path:"pipelines/:pipelineId/items/:caseId",element:(0,t.jsx)(e0,{children:(0,t.jsx)(RLt,{})})}),(0,t.jsx)(nt,{path:"pipelines/:pipelineId/cases/:caseId",element:(0,t.jsx)(e0,{children:(0,t.jsx)(ILt,{})})}),(0,t.jsx)(nt,{path:"routines/:routineId",element:e?(0,t.jsx)(Gce,{}):(0,t.jsx)(u0,{children:(0,t.jsx)(ype,{})})}),(0,t.jsx)(nt,{path:"routines/:routineId/:section",element:e?(0,t.jsx)(Gce,{}):(0,t.jsx)(u0,{children:(0,t.jsx)(ype,{})})}),(0,t.jsx)(nt,{element:(0,t.jsx)(dO,{}),children:(0,t.jsxs)(nt,{element:(0,t.jsx)(Iut,{}),children:[(0,t.jsx)(nt,{path:"execution-workspaces/:workspaceId",element:(0,t.jsx)(vw,{})}),(0,t.jsx)(nt,{path:"execution-workspaces/:workspaceId/services",element:(0,t.jsx)(vw,{})}),(0,t.jsx)(nt,{path:"execution-workspaces/:workspaceId/configuration",element:(0,t.jsx)(vw,{})}),(0,t.jsx)(nt,{path:"execution-workspaces/:workspaceId/runtime-logs",element:(0,t.jsx)(vw,{})}),(0,t.jsx)(nt,{path:"execution-workspaces/:workspaceId/issues",element:(0,t.jsx)(vw,{})}),(0,t.jsx)(nt,{path:"execution-workspaces/:workspaceId/routines",element:(0,t.jsx)(vw,{})})]})}),(0,t.jsx)(nt,{path:"goals",element:(0,t.jsx)(yUt,{})}),(0,t.jsx)(nt,{path:"goals/:goalId",element:(0,t.jsx)(RUt,{})}),(0,t.jsx)(nt,{path:"artifacts",element:(0,t.jsx)(Xce,{})}),(0,t.jsx)(nt,{path:"approvals",element:(0,t.jsx)(kn,{to:"/approvals/pending",replace:!0})}),(0,t.jsx)(nt,{path:"approvals/pending",element:(0,t.jsx)(ede,{})}),(0,t.jsx)(nt,{path:"approvals/all",element:(0,t.jsx)(ede,{})}),(0,t.jsx)(nt,{path:"approvals/:approvalId",element:(0,t.jsx)(EUt,{})}),(0,t.jsx)(nt,{path:"activity",element:e?(0,t.jsx)(vKt,{}):(0,t.jsx)(u0,{children:(0,t.jsx)(dis,{})})}),e?(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)(nt,{path:"activity/runs",element:(0,t.jsx)(a1,{section:"runs"})}),(0,t.jsx)(nt,{path:"activity/costs",element:(0,t.jsx)(a1,{section:"costs"})}),(0,t.jsx)(nt,{path:"activity/budgets",element:(0,t.jsx)(a1,{section:"budgets"})}),(0,t.jsx)(nt,{path:"activity/timeline",element:(0,t.jsx)(a1,{section:"timeline"})}),(0,t.jsx)(nt,{path:"audit",element:(0,t.jsx)(Yp,{to:"/activity",forceAgentMode:!0})}),(0,t.jsx)(nt,{path:"audit/activity",element:(0,t.jsx)(Yp,{to:"/activity"})}),(0,t.jsx)(nt,{path:"audit/runs",element:(0,t.jsx)(Yp,{to:"/activity/runs"})}),(0,t.jsx)(nt,{path:"audit/costs",element:(0,t.jsx)(Yp,{to:"/activity/costs"})}),(0,t.jsx)(nt,{path:"audit/budgets",element:(0,t.jsx)(Yp,{to:"/activity/budgets"})}),(0,t.jsx)(nt,{path:"audit/timeline",element:(0,t.jsx)(Yp,{to:"/activity/timeline"})}),(0,t.jsx)(nt,{path:"runs",element:(0,t.jsx)(Yp,{to:"/activity/runs"})}),(0,t.jsx)(nt,{path:"costs",element:(0,t.jsx)(Yp,{to:"/activity/costs"})}),(0,t.jsx)(nt,{path:"budgets",element:(0,t.jsx)(Yp,{to:"/activity/budgets"})})]}):(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)(nt,{path:"costs",element:(0,t.jsx)(u0,{children:(0,t.jsx)(uis,{})})}),(0,t.jsx)(nt,{path:"audit",element:(0,t.jsx)(kn,{to:"/activity?mode=agents",replace:!0})})]}),(0,t.jsxs)(nt,{element:(0,t.jsx)(Klt,{}),children:[(0,t.jsx)(nt,{path:"board-chat",element:(0,t.jsx)(D8t,{})}),(0,t.jsx)(nt,{path:"artifacts",element:(0,t.jsx)(Xce,{})})]}),null,(0,t.jsx)(nt,{path:"decisions",element:(0,t.jsx)(i8t,{})}),(0,t.jsx)(nt,{path:"decisions/queues/:key",element:(0,t.jsx)(d8t,{})}),n?(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)(nt,{path:"inbox",element:(0,t.jsx)(wpe,{})}),(0,t.jsx)(nt,{path:"inbox/mine",element:(0,t.jsx)(oh,{view:"mine"})}),(0,t.jsx)(nt,{path:"inbox/recent",element:(0,t.jsx)(oh,{view:"recent"})}),(0,t.jsx)(nt,{path:"inbox/unread",element:(0,t.jsx)(oh,{view:"unread"})}),(0,t.jsx)(nt,{path:"inbox/blocked",element:(0,t.jsx)(oh,{view:"blocked"})}),(0,t.jsx)(nt,{path:"inbox/all",element:(0,t.jsx)(oh,{view:"everything"})}),(0,t.jsx)(nt,{path:"inbox/new",element:(0,t.jsx)(oh,{view:"mine"})})]}):(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)(nt,{path:"inbox",element:(0,t.jsx)(wpe,{})}),(0,t.jsx)(nt,{path:"inbox/mine",element:(0,t.jsx)(Pw,{})}),(0,t.jsx)(nt,{path:"inbox/recent",element:(0,t.jsx)(Pw,{})}),(0,t.jsx)(nt,{path:"inbox/unread",element:(0,t.jsx)(Pw,{})}),(0,t.jsx)(nt,{path:"inbox/blocked",element:(0,t.jsx)(Pw,{})}),(0,t.jsx)(nt,{path:"inbox/all",element:(0,t.jsx)(Pw,{})}),(0,t.jsx)(nt,{path:"inbox/new",element:(0,t.jsx)(kn,{to:"/inbox/mine",replace:!0})})]}),(0,t.jsx)(nt,{path:"inbox/requests",element:(0,t.jsx)(ais,{})}),(0,t.jsx)(nt,{path:"u/:userSlug",element:(0,t.jsx)(G6t,{})}),(0,t.jsx)(nt,{path:"design-guide",element:(0,t.jsx)(Xrs,{})}),(0,t.jsx)(nt,{path:"instance/settings/adapters",element:(0,t.jsx)(ipe,{})}),(0,t.jsx)(nt,{path:":pluginRoutePath/*",element:(0,t.jsx)(ope,{})}),(0,t.jsx)(nt,{path:"*",element:(0,t.jsx)(Pu,{scope:"board"})})]})}r(his,"boardRoutes");function jpe({credentialSource:e="paperclip_vault"}={}){const s=na(),n=new URLSearchParams(s.search),{enabled:a}=iS();return Jat(n,{chatConnectorsEnabled:a})?(0,t.jsx)(KPe,{credentialSource:e}):(0,t.jsx)(kn,{to:"/apps",replace:!0})}r(jpe,"AppsConnectEntryRoute");function wpe(){const{enabled:e}=yc(),{enabled:s}=sA();return e&&s?(0,t.jsx)(oh,{view:z$e(KJ())}):(0,t.jsx)(kn,{to:`/inbox/${KJ()}`,replace:!0})}r(wpe,"InboxRootRedirect");function oh({view:e}){const s=na(),n=new URLSearchParams(s.search);return n.set(GR,e),(0,t.jsx)(kn,{to:`/issues?${n.toString()}${s.hash}`,replace:!0})}r(oh,"TaskViewRedirect");function y4e(){const e=na(),{companies:s,selectedCompany:n,loading:a}=ps(),{companyPrefix:i,skillId:o}=va();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)(kn,{to:"/skills/studio",replace:!0}):(0,t.jsx)(kn,{to:`/${l.issuePrefix}/skills/studio/${encodeURIComponent(o)}${e.search}${e.hash}`,replace:!0})}r(y4e,"LegacySkillStudioRedirect");function Tv(){const e=na(),{companies:s,selectedCompany:n,loading:a}=ps(),{companyPrefix:i}=va(),{hidden:o}=eu();if(a)return(0,t.jsx)($m,{});const l=(i?s.find(d=>d.issuePrefix.toUpperCase()===i.toUpperCase()):null)??n??s[0]??null;if(!l)return UW({pathname:e.pathname,hasCompanies:!1})?(0,t.jsx)(kn,{to:"/onboarding",replace:!0}):(0,t.jsx)(UG,{});const c=p8e(Cye(`${e.pathname}${e.search}${e.hash}`),o);return(0,t.jsx)(kn,{to:`/${l.issuePrefix}${c}`,replace:!0})}r(Tv,"LegacySettingsRedirect");function kpe(){const{tab:e}=va();return(0,t.jsx)(kn,{to:j4e(e),replace:!0})}r(kpe,"LegacyToolsSettingsRedirect");function Npe(){const{tab:e}=va();return(0,t.jsx)(kn,{to:j4e(e),replace:!0})}r(Npe,"LegacyToolsRedirect");function j4e(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(j4e,"legacyToolsRedirectTarget");function w4e(){const{companies:e}=ps(),{openOnboarding:s}=Qo(),{t:n}=eye(),a=$c(),i=vCe(a?.cloudBaseUrl??null),{onboardingOpen:o,onboardingRouteDismissed:l}=yM(),{companyPrefix:c}=va(),d=c?e.find(p=>p.issuePrefix.toUpperCase()===c.toUpperCase())??null:null;if(sot({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)(L,{onClick:r(()=>d?s({initialStep:D5(),companyId:d.id}):a&&i?Lm(i):s(),"onClick"),children:d?"Add Agent":"Start Onboarding"})})]})})}r(w4e,"OnboardingRoutePage");function pis(){const{companies:e,selectedCompany:s,loading:n}=ps(),a=na();if(n)return(0,t.jsx)($m,{});const i=s??e[0]??null;return i?(0,t.jsx)(kn,{to:`/${i.issuePrefix}/dashboard`,replace:!0}):UW({pathname:a.pathname,hasCompanies:!1})?(0,t.jsx)(kn,{to:"/onboarding",replace:!0}):(0,t.jsx)(UG,{})}r(pis,"CompanyRootRedirect");function Spe(){const{cardId:e}=va(),s=B$e(),n=s?`/${s}`:"";return(0,t.jsx)(kn,{to:`${n}/status${e?`/${e}`:""}`,replace:!0})}r(Spe,"StatusCardsLegacyRedirect");function Yp({to:e,forceAgentMode:s=!1}){const n=na(),a=new URLSearchParams(n.search);s&&a.set("mode","agents");const i=a.toString();return(0,t.jsx)(kn,{to:`${e}${i?`?${i}`:""}${n.hash}`,replace:!0})}r(Yp,"AuditCompatibilityRedirect");function wa(){const e=na(),{companies:s,selectedCompany:n,loading:a}=ps();if(a)return(0,t.jsx)($m,{});const i=n??s[0]??null;return i?(0,t.jsx)(kn,{to:`/${i.issuePrefix}${e.pathname}${e.search}${e.hash}`,replace:!0}):UW({pathname:e.pathname,hasCompanies:!1})?(0,t.jsx)(kn,{to:"/onboarding",replace:!0}):(0,t.jsx)(UG,{})}r(wa,"UnprefixedBoardRedirect");function UG(){const{openOnboarding:e}=Qo(),{t:s}=eye(),n=$c(),a=vCe(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)(L,{onClick:r(()=>n&&a?Lm(a):e(),"onClick"),children:s("app.noCompanies.newCompany",{defaultValue:"New Organization"})})})]})})}r(UG,"NoCompaniesStartPage");function fis(){const{enabled:e,loaded:s}=yc(),{enabled:n}=sA();return(0,t.jsxs)(t.Fragment,{children:[(0,t.jsxs)(I$e,{children:[(0,t.jsx)(nt,{path:"oauth-handoff",element:(0,t.jsx)(eXt,{})}),(0,t.jsx)(nt,{path:"auth",element:(0,t.jsx)(Oas,{})}),(0,t.jsx)(nt,{path:"board-claim/:token",element:(0,t.jsx)(Fas,{})}),(0,t.jsx)(nt,{path:"cli-auth/:id",element:(0,t.jsx)(Bas,{})}),(0,t.jsx)(nt,{path:"invite/:token",element:(0,t.jsx)(Has,{})}),(0,t.jsx)(nt,{path:"s/:token",element:(0,t.jsx)(vpe,{})}),(0,t.jsx)(nt,{path:"s/:token/issues/:issueId",element:(0,t.jsx)(vpe,{})}),(0,t.jsx)(nt,{element:s?(0,t.jsx)(Vne,{allowMembershipRequest:!0}):(0,t.jsx)($m,{}),children:(0,t.jsx)(nt,{path:"chat-identity/confirm",element:(0,t.jsx)(KJt,{})})}),(0,t.jsx)(nt,{path:"tests/perf/long-thread",element:(0,t.jsx)(S4t,{})}),(0,t.jsx)(nt,{path:"ux-lab/bootstrap-setup",element:(0,t.jsx)(hHt,{})}),(0,t.jsx)(nt,{path:"ux-lab/responsible-user-denial",element:(0,t.jsx)(pHt,{})}),(0,t.jsx)(nt,{path:"ux-lab/cross-issue-collaboration",element:(0,t.jsx)(xHt,{})}),(0,t.jsxs)(nt,{element:s?(0,t.jsx)(Vne,{}):(0,t.jsx)($m,{}),children:[(0,t.jsx)(nt,{index:!0,element:(0,t.jsx)(pis,{})}),(0,t.jsx)(nt,{path:"onboarding",element:(0,t.jsx)(w4e,{})}),(0,t.jsx)(nt,{path:"instance",element:(0,t.jsx)(Tv,{})}),(0,t.jsx)(nt,{path:"instance/settings",element:(0,t.jsx)(Tv,{})}),(0,t.jsx)(nt,{path:"instance/settings/*",element:(0,t.jsx)(Tv,{})}),(0,t.jsx)(nt,{path:"companies",element:(0,t.jsx)(wa,{})}),(0,t.jsx)(nt,{path:"dashboard",element:(0,t.jsx)(wa,{})}),(0,t.jsx)(nt,{path:"inbox/*",element:(0,t.jsx)(wa,{})}),(0,t.jsx)(nt,{path:"issues",element:(0,t.jsx)(wa,{})}),(0,t.jsx)(nt,{path:"tasks",element:(0,t.jsx)(wa,{})}),(0,t.jsx)(nt,{path:"issues/:issueId",element:(0,t.jsx)(wa,{})}),(0,t.jsx)(nt,{path:"routines",element:(0,t.jsx)(wa,{})}),(0,t.jsx)(nt,{path:"routines/:routineId",element:(0,t.jsx)(wa,{})}),(0,t.jsx)(nt,{path:"review-queue",element:(0,t.jsx)(wa,{})}),(0,t.jsx)(nt,{path:"learnings",element:(0,t.jsx)(wa,{})}),(0,t.jsx)(nt,{path:"cases",element:(0,t.jsx)(wa,{})}),(0,t.jsx)(nt,{path:"cases/:caseIdentifier",element:(0,t.jsx)(wa,{})}),(0,t.jsx)(nt,{path:"pixels-office",element:(0,t.jsx)(wa,{})}),(0,t.jsx)(nt,{path:"status",element:(0,t.jsx)(wa,{})}),(0,t.jsx)(nt,{path:"status/:cardId",element:(0,t.jsx)(wa,{})}),(0,t.jsx)(nt,{path:"status-cards",element:(0,t.jsx)(wa,{})}),(0,t.jsx)(nt,{path:"status-cards/:cardId",element:(0,t.jsx)(wa,{})}),(0,t.jsx)(nt,{path:"pipelines",element:(0,t.jsx)(wa,{})}),(0,t.jsx)(nt,{path:"pipelines/:pipelineId",element:(0,t.jsx)(wa,{})}),(0,t.jsx)(nt,{path:"pipelines/:pipelineId/add",element:(0,t.jsx)(wa,{})}),(0,t.jsx)(nt,{path:"pipelines/:pipelineId/settings",element:(0,t.jsx)(wa,{})}),(0,t.jsx)(nt,{path:"pipelines/:pipelineId/items/:caseId",element:(0,t.jsx)(wa,{})}),(0,t.jsx)(nt,{path:"pipelines/:pipelineId/cases/:caseId",element:(0,t.jsx)(wa,{})}),(0,t.jsx)(nt,{path:"artifacts",element:(0,t.jsx)(wa,{})}),(0,t.jsx)(nt,{path:"audit",element:(0,t.jsx)(wa,{})}),e?(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)(nt,{path:"audit/*",element:(0,t.jsx)(wa,{})}),(0,t.jsx)(nt,{path:"activity",element:(0,t.jsx)(wa,{})}),(0,t.jsx)(nt,{path:"activity/*",element:(0,t.jsx)(wa,{})}),(0,t.jsx)(nt,{path:"runs",element:(0,t.jsx)(wa,{})}),(0,t.jsx)(nt,{path:"costs",element:(0,t.jsx)(wa,{})}),(0,t.jsx)(nt,{path:"budgets",element:(0,t.jsx)(wa,{})})]}):null,(0,t.jsx)(nt,{path:"decisions",element:(0,t.jsx)(wa,{})}),(0,t.jsx)(nt,{path:"u/:userSlug",element:(0,t.jsx)(wa,{})}),(0,t.jsx)(nt,{path:"skills/studio",element:(0,t.jsx)(wa,{})}),(0,t.jsx)(nt,{path:"skills/studio/new",element:(0,t.jsx)(wa,{})}),(0,t.jsx)(nt,{path:"skills/studio/:skillId",element:(0,t.jsx)(wa,{})}),(0,t.jsx)(nt,{path:"skills/:skillId/studio",element:(0,t.jsx)(y4e,{})}),(0,t.jsx)(nt,{path:"skills/*",element:(0,t.jsx)(wa,{})}),(0,t.jsx)(nt,{path:"settings",element:(0,t.jsx)(Tv,{})}),(0,t.jsx)(nt,{path:"settings/*",element:(0,t.jsx)(Tv,{})}),(0,t.jsx)(nt,{path:"agents",element:(0,t.jsx)(wa,{})}),iH.map(a=>(0,t.jsx)(nt,{path:`agents/${a}`,element:(0,t.jsx)(wa,{})},a)),(0,t.jsx)(nt,{path:"agents/new",element:(0,t.jsx)(wa,{})}),(0,t.jsx)(nt,{path:"agents/:agentId",element:(0,t.jsx)(wa,{})}),(0,t.jsx)(nt,{path:"agents/:agentId/:tab",element:(0,t.jsx)(wa,{})}),(0,t.jsx)(nt,{path:"agents/:agentId/runs/:runId",element:(0,t.jsx)(wa,{})}),(0,t.jsx)(nt,{path:"projects",element:(0,t.jsx)(wa,{})}),(0,t.jsx)(nt,{path:"projects/:projectId",element:(0,t.jsx)(wa,{})}),(0,t.jsx)(nt,{path:"projects/:projectId/overview",element:(0,t.jsx)(wa,{})}),(0,t.jsx)(nt,{path:"projects/:projectId/issues",element:(0,t.jsx)(wa,{})}),(0,t.jsx)(nt,{path:"projects/:projectId/issues/:filter",element:(0,t.jsx)(wa,{})}),(0,t.jsx)(nt,{path:"projects/:projectId/workspaces",element:(0,t.jsx)(wa,{})}),(0,t.jsx)(nt,{path:"projects/:projectId/workspaces/:workspaceId",element:(0,t.jsx)(wa,{})}),(0,t.jsx)(nt,{path:"projects/:projectId/configuration",element:(0,t.jsx)(wa,{})}),(0,t.jsx)(nt,{path:"workspaces",element:(0,t.jsx)(wa,{})}),(0,t.jsx)(nt,{path:"execution-workspaces/:workspaceId",element:(0,t.jsx)(Zj,{})}),(0,t.jsx)(nt,{path:"execution-workspaces/:workspaceId/services",element:(0,t.jsx)(Zj,{})}),(0,t.jsx)(nt,{path:"execution-workspaces/:workspaceId/configuration",element:(0,t.jsx)(Zj,{})}),(0,t.jsx)(nt,{path:"execution-workspaces/:workspaceId/runtime-logs",element:(0,t.jsx)(Zj,{})}),(0,t.jsx)(nt,{path:"execution-workspaces/:workspaceId/issues",element:(0,t.jsx)(Zj,{})}),(0,t.jsx)(nt,{path:"execution-workspaces/:workspaceId/routines",element:(0,t.jsx)(Zj,{})}),(0,t.jsx)(nt,{path:":companyPrefix",element:e?(0,t.jsx)(llt,{}):(0,t.jsx)(zlt,{}),children:his(e,n)}),(0,t.jsx)(nt,{path:"*",element:(0,t.jsx)(Pu,{scope:"global"})})]})]}),(0,t.jsx)(rft,{}),(0,t.jsx)(qot,{})]})}r(fis,"App");var xis=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){hCe(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 gis(){const{data:e}=Z({queryKey:P.auth.session,queryFn:r(()=>Oa.getSession(),"queryFn"),retry:!1}),s=e?.sentryDsn,n=e?.sentryEnvironment??void 0;return(0,m.useEffect)(()=>{if(s)return yot(s,n),()=>{jot()}},[s,n]),null}r(gis,"SentryGate");function bis(e){let s=jg();gie(s),$U(s,e.userId);const n=WTe(()=>{const o=jg();o!==s&&(s=o,gie(o),$U(o,e.userId))}),a=typeof navigator<"u"&&"serviceWorker"in navigator?navigator.serviceWorker:null,i=r(o=>{const l=r2t(o.data);l&&(l.type==="navigate"?e.navigate(l.url):s2t(l.notification))},"onMessage");return a?.addEventListener("message",i),a?.startMessages(),()=>{n(),a?.removeEventListener("message",i)}}r(bis,"startNotificationRuntime");function vis(){const e=Mn(),s=(0,m.useRef)(e),{data:n}=Z({queryKey:P.auth.session,queryFn:r(()=>Oa.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 bis({userId:a,navigate:r(i=>s.current(i),"navigate")})},[a]),null}r(vis,"NotificationRuntime");function yis(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(yis,"managedRoutineToRow");function jis({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=yis(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)(_Ee,{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(I=>{I.preventDefault(),I.stopPropagation()},"onClick"),children:[(0,t.jsx)("span",{children:w.length?`Missing ${w.map(I=>`${I.resourceKind}:${I.resourceKey}`).join(", ")}`:"Routine defaults can be repaired."}),(0,t.jsxs)("span",{className:"flex items-center gap-2",children:[p?(0,t.jsx)(L,{size:"sm",variant:"ghost",disabled:c===v.key,onClick:r(()=>p(v),"onClick"),children:c===v.key?"Reconciling...":"Reconcile"}):null,f?(0,t.jsx)(L,{size:"sm",variant:"ghost",disabled:d===v.key,onClick:r(()=>f(v),"onClick"),children:d===v.key?"Resetting...":"Reset"}):null]})]}):null]},v.key)})})}r(jis,"ManagedRoutinesList");function Cpe(e){return new Set(e??[])}r(Cpe,"toPathSet");function wis({expandedPaths:e,checkedPaths:s,selectedFile:n=null,showCheckboxes:a=!1,onToggleDir:i,onSelectFile:o,...l}){return(0,m.createElement)(hj,{...l,selectedFile:n,expandedDirs:Cpe(e),checkedFiles:s?Cpe(s):void 0,showCheckboxes:a,onToggleDir:i??(()=>{}),onSelectFile:o??(()=>{})})}r(wis,"PluginSdkFileTree");function kis(e){const[s,n]=(0,m.useState)(null);return(0,m.useEffect)(()=>{let a=!1;return Jc(()=>import("./MarkdownEditor-DIHDyI6k.js").then(i=>i.n).then(i=>{a||n(()=>i.MarkdownEditor)}),__vite__mapDeps([36,5,7,9,14,37,28,10,26,38])),()=>{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(kis,"PluginSdkMarkdownEditor");function Nis(e){return Object.fromEntries(Object.entries(e).filter(([,s])=>s!=null&&s!==""&&s!==!1))}r(Nis,"compactIssueFilters");function Sis({companyId:e,projectId:s=null,filters:n,viewStateKey:a="paperclip:plugin-issues-view",initialSearch:i,createIssueLabel:o,searchWithinLoadedIssues:l=!0}){const c=Dt(),d=(0,m.useMemo)(()=>Nis({...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}=Z({queryKey:P.agents.list(e??"__no-company__"),queryFn:r(()=>$t.list(e),"queryFn"),enabled:!!e}),{data:x}=Z({queryKey:P.projects.list(e??"__no-company__",{includeArchived:!0}),queryFn:r(()=>pa.list(e,{includeArchived:!0}),"queryFn"),enabled:!!e}),b=P.liveRuns(e??"__no-company__"),v=No({companyId:e,resourceKey:"live-runs",queryKey:b,enabled:!!e,refetchInterval:!1,leaderOnly:!0}),{data:j,dataUpdatedAt:N}=Z({queryKey:b,queryFn:r(()=>sa.liveRunsForCompany(e),"queryFn"),enabled:v.enabled,refetchInterval:v.refetchInterval});So(v,j,N);const{data:w,isLoading:k,error:S}=Z({queryKey:p,queryFn:r(()=>Ct.list(e,d),"queryFn"),enabled:!!e}),C=(0,m.useMemo)(()=>Ng(j,w),[w,j]),I=je({mutationFn:r(({id:R,data:T})=>Ct.update(R,T),"mutationFn"),onSuccess:r(()=>{e&&(c.invalidateQueries({queryKey:["plugins","sdk-ui","issues-list",e]}),c.invalidateQueries({queryKey:P.issues.list(e)}),h&&(c.invalidateQueries({queryKey:P.issues.listByProject(e,h)}),u&&c.invalidateQueries({queryKey:P.issues.listPluginOperationsByProject(e,h,u)})))},"onSuccess")});return e?(0,m.createElement)(ug,{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,T)=>I.mutate({id:R,data:T}),"onUpdateIssue")}):(0,m.createElement)("div",{className:"text-sm text-muted-foreground"},"Select an organization to view tasks.")}r(Sis,"PluginSdkIssuesList");function Cis({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=t9(),f=e??p.companyId??null,{data:x}=Z({queryKey:P.auth.session,queryFn:r(()=>Oa.getSession(),"queryFn"),enabled:c}),b=x?.user?.id??x?.session?.userId??null,{data:v}=Z({queryKey:P.agents.list(f??"__no-company__"),queryFn:r(()=>$t.list(f),"queryFn"),enabled:!!f}),{data:j}=Z({queryKey:P.access.companyUserDirectory(f??"__no-company__"),queryFn:r(()=>pr.listUserDirectory(f),"queryFn"),enabled:!!f&&c}),N=(0,m.useMemo)(()=>vz(),[]),w=(0,m.useMemo)(()=>N.map(R=>R.startsWith("agent:")?R.slice(6):null).filter(R=>!!R),[N]),k=(0,m.useMemo)(()=>uy((v??[]).filter(R=>d||R.status!=="terminated"),w),[v,d,w]),S=(0,m.useMemo)(()=>[...c?Wfe(b):[],...c?VN(j?.users,{excludeUserIds:[b]}):[],...k.map(R=>({id:xh({assigneeAgentId:R.id}),label:R.name,searchText:`${R.name} ${R.role} ${R.title??""}`}))],[j?.users,b,c,k]),C=qv(s),I=C.assigneeAgentId?k.find(R=>R.id===C.assigneeAgentId):null;return(0,m.createElement)(Au,{value:s,options:S,recentOptionIds:N,placeholder:a,noneLabel:i,searchPlaceholder:o,emptyMessage:l,className:u,onConfirm:h,onChange:r(R=>{const T=qv(R);T.assigneeAgentId&&dy(T.assigneeAgentId),T.assigneeUserId&&a_(T.assigneeUserId),n(R,T)},"onChange"),renderTriggerValue:r(R=>R?I?(0,m.createElement)(rM,null,(0,m.createElement)(L5,{icon:I.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 T=qv(R.id),A=T.assigneeAgentId?k.find(D=>D.id===T.assigneeAgentId):null;return(0,m.createElement)(rM,null,A?(0,m.createElement)(L5,{icon:A.icon,className:"h-3.5 w-3.5 shrink-0 text-muted-foreground"}):(0,m.createElement)(Qc,{className:"h-3.5 w-3.5 shrink-0 text-muted-foreground"}),(0,m.createElement)("span",{className:"truncate"},R.label))},"renderOption")})}r(Cis,"PluginSdkAssigneePicker");function _is({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=t9(),p=e??h.companyId??null,{data:f}=Z({queryKey:P.auth.session,queryFn:r(()=>Oa.getSession(),"queryFn")}),x=f?.user?.id??f?.session?.userId??null,{data:b}=Z({queryKey:P.projects.list(p??"__no-company__",{includeArchived:c}),queryFn:r(()=>pa.list(p,{includeArchived:c}),"queryFn"),enabled:!!p}),v=(0,m.useMemo)(()=>(b??[]).filter(S=>c||!S.archivedAt),[c,b]),{orderedProjects:j}=Qy({projects:v,companyId:p,userId:x}),N=(0,m.useMemo)(()=>cy(),[]),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)(Au,{value:s,options:w,recentOptionIds:N,placeholder:a,noneLabel:i,searchPlaceholder:o,emptyMessage:l,className:d,onConfirm:u,onChange:r(S=>{S&&Q0(S),n(S)},"onChange"),renderTriggerValue:r(S=>!S||!k?(0,m.createElement)("span",{className:"text-muted-foreground"},a):(0,m.createElement)(rM,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(I=>I.id===S.id);return(0,m.createElement)(rM,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(_is,"PluginSdkProjectPicker");function rM({children:e}){return(0,m.createElement)("span",{className:"contents"},e)}r(rM,"FragmentSafe");function Iis({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(Iis,"PluginSdkStatusBadge");function Ais({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(Ais,"PluginSdkDataTable");function Tis({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(Tis,"PluginSdkKeyValueList");function Ris({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(Ris,"PluginSdkMetricCard");function Eis({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(Eis,"PluginSdkJsonTree");function Pis({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(Pis,"PluginSdkSpinner");var Mis=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 Dis(e,s){globalThis.__paperclipPluginBridge__={react:e,reactJsxRuntime:t,reactDom:s,sdkUi:{usePluginData:k8e,usePluginAction:N8e,useHostContext:t9,useHostLocation:C8e,useHostNavigation:S8e,usePluginStream:I8e,usePluginToast:_8e,copyTextToClipboard:fa,MarkdownBlock:r(({content:n,className:a,enableWikiLinks:i,wikiLinkRoot:o,resolveWikiLinkHref:l})=>(0,m.createElement)(Sn,{className:a,softBreaks:!1,enableWikiLinks:i,wikiLinkRoot:o,resolveWikiLinkHref:l,children:n}),"MarkdownBlock"),MetricCard:Ris,StatusBadge:Iis,DataTable:Ais,KeyValueList:Tis,JsonTree:Eis,Spinner:Pis,ErrorBoundary:Mis,MarkdownEditor:kis,FileTree:wis,IssuesList:Sis,AssigneePicker:Cis,ProjectPicker:_is,ManagedRoutinesList:jis}}}r(Dis,"initPluginBridge");var Lis=1e4;function $is(e=Lis){if(typeof performance>"u"||typeof performance.clearMeasures!="function")return()=>{};const n=setInterval(r(()=>{globalThis.__paperclipKeepPerfMeasures||performance.clearMeasures()},"reap"),e);return()=>clearInterval(n)}r($is,"startPerfMeasureReaper");var Ois=Fy((e=>{function s(q,U){var O=q.length;q.push(U);e:for(;0<O;){var K=O-1>>>1,H=q[K];if(0<i(H,U))q[K]=U,q[O]=H,O=K;else break e}}r(s,"push");function n(q){return q.length===0?null:q[0]}r(n,"peek");function a(q){if(q.length===0)return null;var U=q[0],O=q.pop();if(O!==U){q[0]=O;e:for(var K=0,H=q.length,ee=H>>>1;K<ee;){var se=2*(K+1)-1,ne=q[se],fe=se+1,X=q[fe];if(0>i(ne,O))fe<H&&0>i(X,ne)?(q[K]=X,q[fe]=O,K=fe):(q[K]=ne,q[se]=O,K=se);else if(fe<H&&0>i(X,O))q[K]=X,q[fe]=O,K=fe;else break e}}return U}r(a,"pop");function i(q,U){var O=q.sortIndex-U.sortIndex;return O!==0?O:q.id-U.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(q){for(var U=n(u);U!==null;){if(U.callback===null)a(u);else if(U.startTime<=q)a(u),U.sortIndex=U.expirationTime,s(d,U);else break;U=n(u)}}r(S,"advanceTimers");function C(q){if(v=!1,S(q),!b)if(n(d)!==null)b=!0,I||(I=!0,B());else{var U=n(u);U!==null&&$(C,U.startTime-q)}}r(C,"handleTimeout");var I=!1,R=-1,T=5,A=-1;function D(){return j?!0:!(e.unstable_now()-A<T)}r(D,"shouldYieldToHost");function M(){if(j=!1,I){var q=e.unstable_now();A=q;var U=!0;try{e:{b=!1,v&&(v=!1,w(R),R=-1),x=!0;var O=f;try{t:{for(S(q),p=n(d);p!==null&&!(p.expirationTime>q&&D());){var K=p.callback;if(typeof K=="function"){p.callback=null,f=p.priorityLevel;var H=K(p.expirationTime<=q);if(q=e.unstable_now(),typeof H=="function"){p.callback=H,S(q),U=!0;break t}p===n(d)&&a(d),S(q)}else a(d);p=n(d)}if(p!==null)U=!0;else{var ee=n(u);ee!==null&&$(C,ee.startTime-q),U=!1}}break e}finally{p=null,f=O,x=!1}U=void 0}}finally{U?B():I=!1}}}r(M,"performWorkUntilDeadline");var B;if(typeof k=="function")B=r(function(){k(M)},"schedulePerformWorkUntilDeadline");else if(typeof MessageChannel<"u"){var E=new MessageChannel,z=E.port2;E.port1.onmessage=M,B=r(function(){z.postMessage(null)},"schedulePerformWorkUntilDeadline")}else B=r(function(){N(M,0)},"schedulePerformWorkUntilDeadline");function $(q,U){R=N(function(){q(e.unstable_now())},U)}r($,"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(q){q.callback=null},e.unstable_forceFrameRate=function(q){0>q||125<q||(T=0<q?Math.floor(1e3/q):5)},e.unstable_getCurrentPriorityLevel=function(){return f},e.unstable_next=function(q){switch(f){case 1:case 2:case 3:var U=3;break;default:U=f}var O=f;f=U;try{return q()}finally{f=O}},e.unstable_requestPaint=function(){j=!0},e.unstable_runWithPriority=function(q,U){switch(q){case 1:case 2:case 3:case 4:case 5:break;default:q=3}var O=f;f=q;try{return U()}finally{f=O}},e.unstable_scheduleCallback=function(q,U,O){var K=e.unstable_now();switch(typeof O=="object"&&O!==null?(O=O.delay,O=typeof O=="number"&&0<O?K+O:K):O=K,q){case 1:var H=-1;break;case 2:H=250;break;case 5:H=1073741823;break;case 4:H=1e4;break;default:H=5e3}return H=O+H,q={id:h++,callback:U,priorityLevel:q,startTime:O,expirationTime:H,sortIndex:-1},O>K?(q.sortIndex=O,s(u,q),n(d)===null&&q===n(u)&&(v?(w(R),R=-1):v=!0,$(C,O-K))):(q.sortIndex=H,s(d,q),b||x||(b=!0,I||(I=!0,B()))),q},e.unstable_shouldYield=D,e.unstable_wrapCallback=function(q){var U=f;return function(){var O=f;f=U;try{return q.apply(this,arguments)}finally{f=O}}}})),Fis=Fy(((e,s)=>{s.exports=Ois()})),Bis=Fy((e=>{var s=Fis(),n=X8(),a=Ppe();function i(g){var y="https://react.dev/errors/"+g;if(1<arguments.length){y+="?args[]="+encodeURIComponent(arguments[1]);for(var _=2;_<arguments.length;_++)y+="&args[]="+encodeURIComponent(arguments[_])}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,_=g;if(g.alternate)for(;y.return;)y=y.return;else{g=y;do y=g,(y.flags&4098)!==0&&(_=y.return),g=y.return;while(g)}return y.tag===3?_: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 _=g,F=y;;){var V=_.return;if(V===null)break;var J=V.alternate;if(J===null){if(F=V.return,F!==null){_=F;continue}break}if(V.child===J.child){for(J=V.child;J;){if(J===_)return u(V),g;if(J===F)return u(V),y;J=J.sibling}throw Error(i(188))}if(_.return!==F.return)_=V,F=J;else{for(var ve=!1,qe=V.child;qe;){if(qe===_){ve=!0,_=V,F=J;break}if(qe===F){ve=!0,F=V,_=J;break}qe=qe.sibling}if(!ve){for(qe=J.child;qe;){if(qe===_){ve=!0,_=J,F=V;break}if(qe===F){ve=!0,F=J,_=V;break}qe=qe.sibling}if(!ve)throw Error(i(189))}}if(_.alternate!==F)throw Error(i(190))}if(_.tag!==3)throw Error(i(188));return _.stateNode.current===_?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"),I=Symbol.for("react.suspense"),R=Symbol.for("react.suspense_list"),T=Symbol.for("react.memo"),A=Symbol.for("react.lazy"),D=Symbol.for("react.activity"),M=Symbol.for("react.memo_cache_sentinel"),B=Symbol.iterator;function E(g){return g===null||typeof g!="object"?null:(g=B&&g[B]||g["@@iterator"],typeof g=="function"?g:null)}r(E,"getIteratorFn");var z=Symbol.for("react.client.reference");function $(g){if(g==null)return null;if(typeof g=="function")return g.$$typeof===z?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 I:return"Suspense";case R:return"SuspenseList";case D: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 T:return y=g.displayName||null,y!==null?y:$(g.type)||"Memo";case A:y=g._payload,g=g._init;try{return $(g(y))}catch{}}return null}r($,"getComponentNameFromType");var q=Array.isArray,U=n.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE,O=a.__DOM_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE,K={pending:!1,data:null,method:null,action:null},H=[],ee=-1;function se(g){return{current:g}}r(se,"createCursor");function ne(g){0>ee||(g.current=H[ee],H[ee]=null,ee--)}r(ne,"pop");function fe(g,y){ee++,H[ee]=g.current,g.current=y}r(fe,"push");var X=se(null),re=se(null),oe=se(null),G=se(null);function Y(g,y){switch(fe(oe,y),fe(re,g),fe(X,null),y.nodeType){case 9:case 11:g=(g=y.documentElement)&&(g=g.namespaceURI)?VY(g):0;break;default:if(g=y.tagName,y=y.namespaceURI)y=VY(y),g=HY(y,g);else switch(g){case"svg":g=1;break;case"math":g=2;break;default:g=0}}ne(X),fe(X,g)}r(Y,"pushHostContainer");function Q(){ne(X),ne(re),ne(oe)}r(Q,"popHostContainer");function te(g){g.memoizedState!==null&&fe(G,g);var y=X.current,_=HY(y,g.type);y!==_&&(fe(re,g),fe(X,_))}r(te,"pushHostContext");function ae(g){re.current===g&&(ne(X),ne(re)),G.current===g&&(ne(G),qS._currentValue=K)}r(ae,"popHostContext");var le,he;function ce(g){if(le===void 0)try{throw Error()}catch(_){var y=_.stack.trim().match(/\n( *(at )?)/);le=y&&y[1]||"",he=-1<_.stack.indexOf(`
774
774
  at`)?" (<anonymous>)":-1<_.stack.indexOf("@")?"@unknown:0:0":""}return`
775
775
  `+le+g+he}r(ce,"describeBuiltInComponentFrame");var ge=!1;function me(g,y){if(!g||ge)return"";ge=!0;var _=Error.prepareStackTrace;Error.prepareStackTrace=void 0;try{var F={DetermineComponentFrameRoot:r(function(){try{if(y){var Os=r(function(){throw Error()},"Fake");if(Object.defineProperty(Os.prototype,"props",{set:r(function(){throw Error()},"set")}),typeof Reflect=="object"&&Reflect.construct){try{Reflect.construct(Os,[])}catch(ms){var ns=ms}Reflect.construct(g,[],Os)}else{try{Os.call()}catch(ms){ns=ms}g.call(Os.prototype)}}else{try{throw Error()}catch(ms){ns=ms}(Os=g())&&typeof Os.catch=="function"&&Os.catch(function(){})}}catch(ms){if(ms&&ns&&typeof ms.stack=="string")return[ms.stack,ns.stack]}return[null,null]},"DetermineComponentFrameRoot")};F.DetermineComponentFrameRoot.displayName="DetermineComponentFrameRoot";var V=Object.getOwnPropertyDescriptor(F.DetermineComponentFrameRoot,"name");V&&V.configurable&&Object.defineProperty(F.DetermineComponentFrameRoot,"name",{value:"DetermineComponentFrameRoot"});var J=F.DetermineComponentFrameRoot(),ve=J[0],qe=J[1];if(ve&&qe){var jt=ve.split(`
776
776
  `),ts=qe.split(`