@tickernelz/paperclip-pro-ui 2026.1027.0 → 2026.1104.0

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-DokS0JQS.js","assets/character-CguPM7IG.js","assets/prod-COP_vZWu.js","assets/rolldown-runtime-ZpX3ckPj.js","assets/CompanyExport-Bir35u83.js","assets/boxes-Bpd3vwBa.js","assets/BreadcrumbContext-DP0mgUIg.js","assets/preload-helper-CceJXRIF.js","assets/StatusIcon-C_7wHYAC.js","assets/usePrefersReducedMotion-CT6hiLGt.js","assets/badge-_pdOC0PF.js","assets/MarkdownBody-N2K7JfY-.js","assets/mention-chips-1XYhZxbY.js","assets/agent-avatar-url-BgdXoMNW.js","assets/check-2BJzr5lo.js","assets/clipboard-B6GwC8zN.js","assets/external-link-CDJwwbV8.js","assets/agents-BXUtBaur.js","assets/rotate-ccw-MDZCGMRv.js","assets/x-BYvg7sTI.js","assets/ToastContext-YqYQB596.js","assets/EmptyState-BN5HM6-K.js","assets/PageSkeleton-BiXcKvFW.js","assets/skeleton-BXdcfOZv.js","assets/Agents.production-BJetnIZc.js","assets/alert-dialog-BGWR1eHm.js","assets/dist-BNyB3Sjo.js","assets/dist-G1LZKTxg.js","assets/dist-Cwi5N9Q2.js","assets/AgentAvatar-D4YQ4myL.js","assets/tabs-D69nzsXS.js","assets/dist-f8T_RDWp.js","assets/bot-B09KshQK.js","assets/heartbeats-CpU47ZZC.js","assets/instanceSettings-CIY4sDga.js","assets/environments-C7g5xojw.js","assets/Routines.production-BMVUHtz-.js","assets/SearchableSelect-CyZJenSa.js","assets/dialog-aW5qVpwP.js","assets/RoutineRunVariablesDialog-CrC88u8T.js","assets/checkbox-DhPd8h_U.js","assets/label-CRFTGD7I.js","assets/MarkdownEditor-DHz7g42W.js","assets/dist-rAdi5Ixy.js","assets/dist-BhxPxuMy.js","assets/select-CV4NIBut.js","assets/chevron-down-C8ZdH7h9.js","assets/sheet-gHOCLZNA.js","assets/useHiddenSettings-DUdQI3FV.js","assets/health-Za7wEC5p.js","assets/input-CfcFr-x-.js","assets/access-CspWWirX.js","assets/company-members-Duugb3uG.js","assets/card-B_2b5Riw.js","assets/RoutineDetail.production-KK-EpmNd.js","assets/arrow-right-QtlfoJHE.js","assets/save-BDLuZ_1b.js","assets/CompanySkills.production-D_mQ9MQl.js","assets/use-adapter-capabilities--7ZiaS5B.js","assets/file-text-HU_olDIx.js","assets/CompanyActivity.production-DiqCOCXP.js","assets/Terminal-mFtKN-ON.js","assets/OrgChart.production-Cfzs62Ia.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-CKRv2OQh.js","assets/character-CguPM7IG.js","assets/prod-COP_vZWu.js","assets/rolldown-runtime-ZpX3ckPj.js","assets/CompanyExport-DrqpQn4r.js","assets/boxes-Bpd3vwBa.js","assets/BreadcrumbContext-DP0mgUIg.js","assets/preload-helper-CceJXRIF.js","assets/StatusIcon-C_7wHYAC.js","assets/usePrefersReducedMotion-CT6hiLGt.js","assets/badge-_pdOC0PF.js","assets/MarkdownBody-N2K7JfY-.js","assets/mention-chips-1XYhZxbY.js","assets/agent-avatar-url-BgdXoMNW.js","assets/check-2BJzr5lo.js","assets/clipboard-B6GwC8zN.js","assets/external-link-CDJwwbV8.js","assets/agents-BXUtBaur.js","assets/rotate-ccw-MDZCGMRv.js","assets/x-BYvg7sTI.js","assets/ToastContext-YqYQB596.js","assets/EmptyState-BN5HM6-K.js","assets/PageSkeleton-BiXcKvFW.js","assets/skeleton-BXdcfOZv.js","assets/Agents.production-B1mPIEb7.js","assets/alert-dialog-BGWR1eHm.js","assets/dist-BNyB3Sjo.js","assets/dist-G1LZKTxg.js","assets/dist-Cwi5N9Q2.js","assets/AgentAvatar-D4YQ4myL.js","assets/tabs-D69nzsXS.js","assets/dist-f8T_RDWp.js","assets/bot-B09KshQK.js","assets/heartbeats-CpU47ZZC.js","assets/instanceSettings-CIY4sDga.js","assets/environments-C7g5xojw.js","assets/Routines.production-DPgOqbb-.js","assets/SearchableSelect-CyZJenSa.js","assets/dialog-aW5qVpwP.js","assets/RoutineRunVariablesDialog-CrC88u8T.js","assets/checkbox-DhPd8h_U.js","assets/label-CRFTGD7I.js","assets/MarkdownEditor-DHz7g42W.js","assets/dist-rAdi5Ixy.js","assets/dist-BhxPxuMy.js","assets/select-CV4NIBut.js","assets/chevron-down-C8ZdH7h9.js","assets/sheet-gHOCLZNA.js","assets/useHiddenSettings-DUdQI3FV.js","assets/health-Za7wEC5p.js","assets/input-CfcFr-x-.js","assets/access-CspWWirX.js","assets/company-members-Duugb3uG.js","assets/card-B_2b5Riw.js","assets/RoutineDetail.production-CmuV9Cac.js","assets/arrow-right-QtlfoJHE.js","assets/save-BDLuZ_1b.js","assets/CompanySkills.production-DJUAhDX_.js","assets/use-adapter-capabilities--7ZiaS5B.js","assets/file-text-HU_olDIx.js","assets/CompanyActivity.production-DOfFPFa0.js","assets/Terminal-wWKDl4EU.js","assets/OrgChart.production-Ser8k3BP.js"])))=>i.map(i=>d[i]);
2
2
  var B$e=Object.defineProperty;var r=(e,s)=>B$e(e,"name",{value:s,configurable:!0});import{i as v8,n as F$e,t as Hj}from"./rolldown-runtime-ZpX3ckPj.js";import{$ as eF,$a as nbe,$i as z$e,$n as q$e,$r as ZN,$t as U$e,A as Bh,Ai as rbe,An as iv,Ar as Pee,At as m3,B as sm,Ba as Dee,Bi as K$e,Bn as Q$e,Br as W$e,Bt as abe,Ci as H$e,Cn as $ee,Cr as ibe,Ct as Ma,D as y8,Di as V$e,Dn as G$e,Dr as Y$e,Dt as Z$e,Ei as J$e,En as j8,Er as obe,Et as X$e,Fi as eOe,Fn as tOe,Fr as sOe,Ft as nOe,G as W,Gi as rOe,Gn as aOe,Gr as iOe,Gt as lbe,H as Oee,Hn as cbe,Hr as oOe,Ii as tF,In as lOe,Ir as sF,It as MQ,J as sa,Ji as cOe,Jn as dOe,Jr as gk,Jt as dbe,K as uOe,Ki as g6,Kn as mOe,Kr as ube,Kt as S2,L as JN,Li as mbe,Ln as hOe,Lr as hbe,Lt as pOe,M as XN,Ma as fOe,Mi as Bee,Mn as pbe,Mr as xOe,Mt as gOe,Ni as b6,Nn as bOe,Nr as PQ,O as vOe,Oi as yOe,On as jOe,Or as wOe,Ot as Fee,P as kOe,Pi as NOe,Pn as v6,Pr as iN,Pt as SOe,Q as COe,Qa as _Oe,Qi as fbe,Qn as AOe,Qr as y6,Qt as IOe,R as Vj,Ri as TOe,Rn as ROe,Rr as EOe,Rt as LOe,Si as xbe,Sn as DQ,Sr as MOe,St as M,T as Sy,Ti as POe,Tn as gbe,Tr as j6,Tt as zee,U as qee,Ui as w6,Un as DOe,Ur as $Oe,Ut as Uee,V as OOe,Vi as BOe,Vn as FOe,Vr as zOe,Vt as w8,W as $Q,Wi as Kee,Wn as qOe,Wr as UOe,Wt as Qee,X as Gd,Xa as KOe,Xi as bk,Xn as Wee,Xr as A0,Xt as bbe,Y as vbe,Ya as h3,Yi as t9,Yn as OQ,Yr as QOe,Yt as WOe,Z as yr,Za as kt,Zi as Hee,Zn as HOe,Zr as ybe,Zt as VOe,_a as je,_i as GOe,_n as BQ,_r as s_,_t as YOe,aa as ZOe,ai as jbe,an as wbe,ar as JOe,at as Vx,bi as XOe,bn as eBe,br as nF,bt as Af,ci as Vee,cn as tBe,cr as sBe,ct as lm,da as k6,di as kbe,dn as Gee,dr as nBe,dt as Nbe,ea as FQ,ei as Sbe,eo as zQ,er as rBe,et as Wi,fi as Yee,fn as aBe,fr as iBe,ft as Cbe,ga as oBe,gi as lBe,gn as _be,gr as cBe,gt as Abe,ha as ov,hi as s9,hn as F_,hr as Zee,ht as ps,ia as we,ii as dBe,in as uBe,ir as Ibe,it as N6,j as Tbe,ja as mBe,ji as Rbe,jn as rF,jr as hBe,jt as nf,k as pBe,ka as fBe,ki as eS,kn as WT,kr as Jee,kt as rf,la as Bv,li as Ebe,ln as p3,lr as Lbe,lt as qQ,ma as oN,mi as xBe,mn as Fm,mr as gBe,mt as bBe,n as zt,na as Ul,ni as fj,nn as vBe,nr as yBe,nt as Om,oa as Xee,oi as Hp,on as Gx,or as Mbe,ot as z_,pa as jBe,pi as wBe,pn as Hh,pr as kBe,q as Pbe,qi as NBe,qn as Dbe,qr as SBe,qt as $be,ra as sn,ri as UQ,rn as CBe,rr as _Be,rt as ka,sa as ABe,si as Obe,sn as ete,sr as IBe,st as n_,t as _c,ta as TBe,ti as Bbe,tn as RBe,tr as EBe,tt as LBe,ua as MBe,ui as PBe,un as Fbe,ur as zbe,ut as xr,va as te,vi as DBe,vn as q_,vr as HT,vt as $Be,wi as OBe,wn as BBe,wr as FBe,wt as qbe,xi as k8,xn as tS,xr as aF,xt as KQ,ya as zBe,yi as N8,yn as tte,yr as ste,yt as qBe,z as Vl,zi as QQ,zn as UBe,zr as lv,zt as KBe}from"./boxes-Bpd3vwBa.js";import{t as fd}from"./preload-helper-CceJXRIF.js";import{$ as K0,$t as QBe,A as WBe,An as HBe,At as Gj,Bn as hi,Bt as iF,C as Zm,Cn as VBe,Ct as f3,Dn as Ube,Dt as Kbe,E as GBe,En as YBe,Et as S6,F as oF,Fn as ZBe,Ft as $x,G as lF,Ht as JBe,In as ua,It as U_,Jt as Qbe,Kt as XBe,L as eFe,Ln as Wbe,Lt as zm,M as tFe,Mn as cv,Mt as S8,Nn as nt,Nt as xa,O as sFe,On as nFe,Ot as Hbe,Pn as rFe,Pt as Yy,Q as aFe,Qt as nte,Rn as C8,Rt as iFe,S as oFe,Sn as VT,St as ql,T as x3,Tn as lFe,Tt as qm,Ut as cFe,V as dFe,Vt as sr,Wt as wr,X as hf,Xt as uFe,Y as C6,Yt as rte,Z as pf,Zt as mFe,_ as xj,_n as ate,_t as gm,a as WQ,an as Vbe,at as hFe,b as pFe,bn as fFe,bt as Wl,c as _n,cn as P1,ct as Xh,d as Yn,dn as _6,dt as Ao,en as xFe,et as Q0,fn as sS,ft as g3,g as gFe,gn as n9,gt as b3,h as HQ,hn as bFe,ht as jC,i as GT,in as ite,it as vFe,j as pb,jn as Md,jt as Ju,kn as Hi,kt as ff,l as yFe,ln as jt,lt as D0,m as jFe,mn as ote,mt as Yd,n as Wn,nn as wFe,nt as v3,o as Ke,on as kFe,ot as Ox,pn as pl,pt as Gl,q as NFe,qt as A6,r as $,rn as gI,rt as Jr,s as dv,sn as SFe,st as gn,t as CFe,tn as Gbe,tt as W0,u as nS,un as I6,ut as VQ,v as _8,vn as Yx,vt as to,w as _Fe,wn as AFe,wt as A8,x as IFe,xn as TFe,xt as RFe,y as Ybe,yn as Zx,yt as Zbe,z as Jbe,zn as ga,zt as dr}from"./BreadcrumbContext-DP0mgUIg.js";import{S as rS,_ as tl,a as I8,b as ho,c as y3,d as Hu,f as aS,g as EFe,h as yx,i as LFe,l as MFe,m as iS,n as PFe,o as DFe,p as Xo,s as oi,t as mg,u as oS,v as sl,x as T8,y as Dl}from"./SearchableSelect-CyZJenSa.js";import{$ as $Fe,$n as Xbe,$t as OFe,A as GQ,An as lte,Ar as lS,At as BFe,B as FFe,Bn as T6,Br as R8,Bt as zFe,C as qFe,Cn as vk,Cr as eve,Ct as cF,D as dF,Dn as tve,Dr as j3,Dt as sve,E as nve,En as yk,Er as rve,Et as UFe,Fn as cte,Fr as ave,Ft as gj,G as cS,Gn as KFe,Gt as dS,H as ive,Hn as R6,Ht as jx,In as dte,Ir as QFe,It as bj,J as WFe,Jn as E6,Jt as HFe,K as Yj,Kn as VFe,Kt as GFe,L as ove,Ln as lve,Lr as YFe,Lt as K_,M as ZFe,Mn as JFe,Mr as ute,Mt as qb,N as XFe,Nn as cve,Nr as nm,Nt as w3,O as eze,On as L6,Or as tze,Ot as sze,P as nze,Pn as dve,Pr as hg,Pt as uF,Q as rze,Qn as uve,Qt as mte,R as aze,Rn as YQ,Rr as H0,Rt as ize,S as oze,Sn as Rx,Sr as lze,St as mF,T as M6,Tn as Q_,Tr as ZQ,Tt as cze,U as Ub,Un as P6,Ut as mve,V as pg,Vn as hve,Vr as cm,Vt as jk,W as hF,Wn as dze,Wt as Cc,X as uze,Xn as hte,Xt as wk,Y as pve,Yn as fve,Yt as mze,Z as hze,Zn as xve,Zt as pze,_ as fze,_n as gve,_r as xze,_t as k3,a as gze,an as bze,ar as bve,at as vze,b as vve,bn as D6,br as N3,bt as yve,c as pte,cn as lN,cr as jve,ct as wve,d as kve,dr as yze,dt as jze,en as wze,er as $h,et as kze,f as Nve,fn as kk,fr as Sve,ft as JQ,g as $6,gn as Nze,gr as E8,gt as V0,h as Cve,hn as _ve,hr as uS,ht as Sze,i as Cze,in as XQ,ir as Zy,it as _ze,j as Aze,jn as fte,jr as mS,jt as vj,k as Ize,kn as O6,kr as xf,kt as Tze,l as r9,ln as Rze,lr as B6,lt as xte,m as Ave,mn as Ive,mr as Eze,mt as Zj,n as Lze,nn as Mze,nr as Wm,nt as Pze,o as Dze,on as Rc,or as cN,ot as Tve,p as W_,pn as $ze,pr as Oze,pt as Rve,q as Bze,qn as Eve,qt as Fze,r as Jx,rn as gte,rr as pF,rt as Lve,s as zze,sn as Mve,sr as eW,st as F6,t as tW,tn as H_,tr as Pve,tt as qze,u as Uze,un as Kze,ur as Qze,ut as Dve,v as Wze,vn as $ve,vr as Ove,vt as Hze,w as sW,wn as Bve,wr as nW,wt as rm,x as a9,xn as Fve,xr as hS,xt as zve,y as bte,yn as qve,yr as pS,yt as Vze,z as Gze,zn as Uve,zr as V_,zt as Yze}from"./RoutineRunVariablesDialog-CrC88u8T.js";import{$ as Kve,a as Zze,at as Jze,it as Xze,o as eqe,s as tqe}from"./mention-chips-1XYhZxbY.js";import{i as sqe}from"./dist-f8T_RDWp.js";import{a as nqe,o as rqe,r as aqe,t as iqe}from"./dist-BNyB3Sjo.js";import{a as rc,c as ac,d as $n,f as Yc,i as ic,l as S3,m as Es,n as Tc,o as oc,p as On,r as lc,s as cc,t as dc,u as Bn}from"./alert-dialog-BGWR1eHm.js";import{a as ko,c as oqe,i as uv,l as Zc,n as lqe,o as No,r as So,s as Qve,t as lr}from"./AgentAvatar-D4YQ4myL.js";import{a as Ci,i as Jd,n as Qn,r as Ai,t as ri}from"./checkbox-DhPd8h_U.js";import{A as Wve,C as ha,D as cqe,E as dqe,O as uqe,S as ra,T as mqe,_ as ii,a as cr,b as rW,c as Qs,d as aW,f as aa,g as Fh,h as Ab,i as mn,k as hqe,l as Xx,m as mv,n as pqe,o as ln,p as ls,r as Ws,s as fqe,t as qs,u as ia,v as xqe,w as gqe,x as iW,y as oW}from"./dialog-aW5qVpwP.js";import{n as L8,r as fS,t as Ds}from"./label-CRFTGD7I.js";import{g as bqe}from"./dist-rAdi5Ixy.js";import{a as lW,c as da,d as pd,f as Hve,h as vqe,i as yqe,l as wi,m as Kb,o as jqe,p as fg,r as wqe,s as Vve,t as Jc,u as dm}from"./MarkdownEditor-DHz7g42W.js";import{i as Ba,n as fa,r as xd,t as Pi}from"./tabs-D69nzsXS.js";import{_ as dN,a as cW,b as gd,c as Gve,d as z6,f as Yve,h as oa,i as Zve,l as Jve,p as sc,t as ao,u as Xve,v as dW,x as Xu,y as kqe}from"./StatusIcon-C_7wHYAC.js";import{a as ma,c as e0,i as C3,l as Jm,n as Ph,o as qi,r as Jj,s as Ml,t as Xj,u as wl}from"./use-adapter-capabilities--7ZiaS5B.js";import{t as fl}from"./arrow-right-QtlfoJHE.js";import{t as io}from"./bot-B09KshQK.js";import{t as cs}from"./check-2BJzr5lo.js";import{t as rn}from"./chevron-down-C8ZdH7h9.js";import{a as An,i as gr,n as eye,r as Nqe,t as wa}from"./clipboard-B6GwC8zN.js";import{a as un,c as Na,d as Sqe,f as hv,i as Cqe,l as Sa,n as Ca,o as _qe,r as _a,s as tye,t as uW,u as Aqe}from"./select-CV4NIBut.js";import{n as eo,t as af}from"./save-BDLuZ_1b.js";import{n as Ac,t as Dn}from"./external-link-CDJwwbV8.js";import{i as Io,n as Ni,r as nl,t as mW}from"./usePrefersReducedMotion-CT6hiLGt.js";import{C as Iqe,E as s0,S as Tqe,T as Rqe,_ as Eqe,a as Lqe,b as yj,c as Mqe,d as sye,f as Pqe,g as vte,h as Dqe,i as $qe,l as Oqe,m as nye,n as hW,o as rye,p as aye,r as Bqe,s as Fqe,t as Sn,u as zqe,v as of,w as qqe,x as Qb,y as Uqe}from"./MarkdownBody-N2K7JfY-.js";import{t as ei}from"./file-text-HU_olDIx.js";import{a as iye,c as oye,d as M8,i as G_,l as Xd,n as Kqe,o as G0,r as n0,s as Xm,t as r0,u as nc}from"./sheet-gHOCLZNA.js";import{a as P8,i as al,n as Qqe,o as lye,r as _3,t as na}from"./heartbeats-CpU47ZZC.js";import{n as Wqe,r as st,t as it}from"./badge-_pdOC0PF.js";import{n as A3,t as Au}from"./useHiddenSettings-DUdQI3FV.js";import{t as _i}from"./rotate-ccw-MDZCGMRv.js";import{t as En}from"./x-BYvg7sTI.js";import{n as Hqe,r as Wa,t as jr}from"./instanceSettings-CIY4sDga.js";import"./agent-avatar-url-BgdXoMNW.js";import{a as Xr,i as Ii,n as bd,o as Vqe,r as Gqe,t as Yqe}from"./ToastContext-YqYQB596.js";import{t as _t}from"./agents-BXUtBaur.js";import{t as dt}from"./input-CfcFr-x-.js";import{t as ir}from"./access-CspWWirX.js";import{t as Iu}from"./health-Za7wEC5p.js";import{t as wn}from"./skeleton-BXdcfOZv.js";import{a as gf,i as I3,n as T3,r as xg,t as xS}from"./company-members-Duugb3uG.js";import{t as Fi}from"./environments-C7g5xojw.js";import{a as Zqe,i as Hc,n as Jqe,o as mo,r as ni,s as Oo,t as nn}from"./card-B_2b5Riw.js";import{t as Kn}from"./EmptyState-BN5HM6-K.js";import{t as Fa}from"./PageSkeleton-BiXcKvFW.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 Xqe=class extends fBe{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:mBe(s,n.data),hasPreviousPage:fOe(s,n.data),isFetchNextPageError:u,isFetchingNextPage:h,isFetchPreviousPageError:p,isFetchingPreviousPage:f,isRefetchError:c&&!u&&!p,isRefetching:o&&!h&&!f}}};function gg(e,s){return zBe(e,Xqe,s)}r(gg,"useInfiniteQuery");var eUe="adapter_auth_missing",tUe="document",sUe=80,nUe={markdown:"md",html:"html",json:"json",text:"txt"};function rUe(e){return e.normalize("NFKD").replace(/[\u0300-\u036f]/g,"").toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,sUe).replace(/-+$/g,"")||tUe}r(rUe,"documentExportSlug");function aUe(e){return nUe[(e??"").trim().toLowerCase()]??"md"}r(aUe,"documentExportExtension");function yte(e,s){const n=s.replace(/^\.+/,"").toLowerCase()||"md";return`${rUe(e)}.${n}`}r(yte,"documentExportFileName");function fF(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(fF,"decisionEffectTargetIssueIds");var iUe=new Set(["terminated","pending_approval","paused"]),oUe=new Set(["active","idle","running","error"]);function lUe(e){return oUe.has(e)&&!iUe.has(e)}r(lUe,"isAgentStatusInvokable");function C2(e){return e==="done"||e==="cancelled"}r(C2,"isPipelineTerminalStageKind");function cye(e){const s={};for(const n of e)(s[n.stageId]??=[]).push(n);return s}r(cye,"groupWarningsByStage");function dye(e){return e==="RESPONSIBLE_USER_UNAUTHORIZED"||e==="RESPONSIBLE_USER_UNAVAILABLE"}r(dye,"isResponsibleUserDenialCode");function R3(e){const s=e?.trim();return s&&s.length>0?s:"the responsible user"}r(R3,"responsibleUserLabel");function xF(e,s={}){const n=R3(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(xF,"describeResponsibleUserDenial");var cUe=["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 dUe(e){const s=e?.trim();return s&&s.length>0?s:"this task"}r(dUe,"issueLabel$2");function uUe(e){const s=e?.trim();return s&&s.length>0?s:"the current assignee"}r(uUe,"assigneeLabel");function mUe(e){const s=e?.trim();return s&&s.length>0?s:"this agent"}r(mUe,"actorLabel$1");var hUe="create a child issue with the request in its description (issue creation is a separate, open write path) and let its assignee act";function pUe(e,s={}){const n=dUe(s.issueIdentifier),a=mUe(s.actorLabel),i=uUe(s.assigneeLabel),o=R3(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 ${hUe}.`};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=xF("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=xF("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(pUe,"describeIssueWriteDenial");function uye(e){return(typeof e=="string"?e:e?.name??"").trim()}r(uye,"rawNameOf");function mye(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(mye,"looksLikeNetworkAddress");function gF(e){return e.split(/[\s._-]+/).filter(Boolean).map(s=>s.charAt(0).toUpperCase()+s.slice(1).toLowerCase()).join(" ")}r(gF,"titleCaseIdentifier");function fUe(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,""),gF(n)||"Custom app"}r(fUe,"pluginPackageLabel");function bf(e,s={}){const n=s.title?.trim();if(n)return n;const a=uye(e);if(!a||mye(a))return"Custom app";const i=fUe(a);if(i)return i;if(a.includes(":")&&!a.includes("://")){const o=a.slice(a.lastIndexOf(":")+1).trim();if(o)return gF(o)}return/\s/.test(a)||/[A-Z]/.test(a)?a:/[._-]/.test(a)?gF(a):a}r(bf,"humanizeConnectionDisplayName");function jte(e){const s=uye(e);return s&&mye(s)?`hosted at ${s}`:null}r(jte,"connectionDisplaySecondaryHint");var wte=`I want to connect an MCP (Model Context Protocol) server to Paperclip, and I need a paste-ready config.
3
3
 
4
4
  Target server: <name the server, or ask me if I have not said>
@@ -327,7 +327,7 @@ self.onmessage = function (e) {
327
327
  }
328
328
 
329
329
  };
330
- `;function $dt(){const e=new Blob([Ddt],{type:"application/javascript"}),s=URL.createObjectURL(e);try{return new Worker(s)}finally{URL.revokeObjectURL(s)}}r($dt,"createSandboxedWorker");var Tz=new Map,IE=new Map,fR=new Set,xR=new Map,k_e=null;function Odt(e){k_e=e}r(Odt,"setDynamicParserResultNotifier");function N_e(e,s){e.worker.postMessage(s)}r(N_e,"sendToWorker");function Bdt(e){return e.nextId++}r(Bdt,"nextRequestId");function Fdt(e,s){return`${s}\0${e}`}r(Fdt,"lineCacheKey");function zdt(){k_e?.()}r(zdt,"notifyResultReady");function qdt(e,s,n){return new Promise(a=>{const i=Bdt(e);e.pendingResolves.set(i,a),N_e(e,{type:"parse",id:i,line:s,ts:n})})}r(qdt,"parseLineAsync");function TC(e){for(const s of e.pendingResolves.values())s([]);e.pendingResolves.clear()}r(TC,"drainPendingRequests");function Udt(e){return new Promise((s,n)=>{const a=$dt(),i={worker:a,ready:!1,nextId:1,pendingResolves:new Map},o=setTimeout(()=>{TC(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"&&TC(i)},s(i);return}if(c.type==="error"){clearTimeout(o),TC(i),a.terminate(),n(new Error(c.message));return}},a.onerror=l=>{clearTimeout(o),TC(i),a.terminate(),n(new Error(`Worker error: ${l.message}`))},N_e(i,{type:"init",source:e})})}r(Udt,"initSandboxedWorker");function Kdt(e){const s=new Map,n=new Set;return{parseStdoutLine:r((i,o)=>{const l=Fdt(i,o),c=s.get(l);return c?c.slice():(n.has(l)||(n.add(l),qdt(e,i,o).then(d=>{n.delete(l),s.set(l,d),zdt()})),[])},"parseStdoutLine")}}r(Kdt,"buildParserModule");async function Rz(e){const s=IE.get(e);if(s)return s;if(fR.has(e))return null;const n=xR.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 fR.add(e),null;const o=await Udt(await i.text());Tz.set(e,o);const l=Kdt(o);return IE.set(e,l),l}catch{return fR.add(e),null}finally{xR.delete(e)}})();return xR.set(e,a),a}r(Rz,"loadDynamicParser");function Ez(e){const s=IE.has(e);IE.delete(e),fR.delete(e),xR.delete(e);const n=Tz.get(e);return n&&(TC(n),n.worker.terminate(),Tz.delete(e)),s}r(Ez,"invalidateDynamicParser");var gR=[],AM=new Map,Lz=new Set,S_e=new Map,iD=new Set,LI=new Map,Mz=new Set;function C_e(e){return Mz.add(e),()=>Mz.delete(e)}r(C_e,"onAdapterChange");function __e(){for(const e of Mz)e()}r(__e,"notifyAdapterChange");Odt(__e);function Qdt(){for(const e of[Cot,qot,llt,plt,$lt,Ylt,lct,gct,Act,Oct,ldt,tdt,_lt,Ndt,AE,Pdt])Lz.add(e.type),S_e.set(e.type,e),Ay(e)}r(Qdt,"registerBuiltInUIAdapters");function Ay(e){const s=gR.findIndex(n=>n.type===e.type);s>=0?gR.splice(s,1,e):gR.push(e),AM.set(e.type,e),__e()}r(Ay,"registerUIAdapter");function A_e(e){return AM.get(e)??null}r(A_e,"findUIAdapter");Qdt();function RS(e){const s=AM.get(e);if(!s){let n=!1;return{type:e,label:e,parseStdoutLine:r((a,i)=>(n||(n=!0,Rz(e).then(o=>{o&&Ay({type:e,label:e,parseStdoutLine:o.parseStdoutLine,createStdoutParser:o.createStdoutParser,ConfigFields:_j,buildAdapterConfig:Aj})})),AE.parseStdoutLine(a,i)),"parseStdoutLine"),ConfigFields:_j,buildAdapterConfig:Aj}}return s}r(RS,"getUIAdapter");function Wdt(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 Lz){const i=S_e.get(a);if(!i)continue;const o=n.has(a),l=s.has(a),c=iD.has(a);if(o&&l&&!c){iD.add(a);const d=(LI.get(a)??0)+1;LI.set(a,d);let u=!1;const h=i.parseStdoutLine,p=e.find(f=>f.type===a)?.label??a;Ay({type:a,label:p,parseStdoutLine:r((f,x)=>(u||(u=!0,Rz(a).then(g=>{g&&LI.get(a)===d&&Ay({type:a,label:p,parseStdoutLine:g.parseStdoutLine,createStdoutParser:g.createStdoutParser,ConfigFields:i.ConfigFields,buildAdapterConfig:i.buildAdapterConfig})})),h(f,x)),"parseStdoutLine"),ConfigFields:i.ConfigFields,buildAdapterConfig:i.buildAdapterConfig})}else(!o||!l)&&c&&(iD.delete(a),LI.delete(a),Ez(a),Ay(i))}for(const{type:a,label:i}of e){if(Lz.has(a))continue;const o=AM.get(a);if(o&&o!==AE)continue;let l=!1;const c=o?.parseStdoutLine??AE.parseStdoutLine;Ay({type:a,label:i,parseStdoutLine:r((d,u)=>(l||(l=!0,Rz(a).then(h=>{h&&Ay({type:a,label:i,parseStdoutLine:h.parseStdoutLine,createStdoutParser:h.createStdoutParser,ConfigFields:o?.ConfigFields??_j,buildAdapterConfig:o?.buildAdapterConfig??Aj})})),c(d,u)),"parseStdoutLine"),ConfigFields:o?.ConfigFields??_j,buildAdapterConfig:o?.buildAdapterConfig??Aj})}}r(Wdt,"syncExternalAdapters");function CV(){return[...gR]}r(CV,"listUIAdapters");function Pz(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(Pz,"resolveStdoutParser");function I_e(e,s){if((s.kind==="thinking"||s.kind==="assistant")&&s.delta){const n=e[e.length-1];if(n&&n.kind===s.kind&&n.delta&&n.channel===s.channel){n.text+=s.text,n.ts=s.ts;return}}e.push(s)}r(I_e,"appendTranscriptEntry");function Hdt(e,s){for(const n of s)I_e(e,n)}r(Hdt,"appendTranscriptEntries");function Vdt(e,s=160){return e.length<=s?e:`${e.slice(0,s-3)}...`}r(Vdt,"truncateTranscriptLine");function Gdt(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(Gdt,"formatTranscriptParserError");function Ydt(e,s,n,a){const i=Gdt(n)||"unknown parser error",o=Vdt(e);return{kind:"result",ts:s,text:$m(`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(Ydt,"createTranscriptParseErrorEntry");function _V(e){const{entries:s,line:n,ts:a,parseLine:i,reset:o,redactionOptions:l}=e;try{Hdt(s,i(n,a).map(c=>qat(c,l)))}catch(c){o?.(),I_e(s,Ydt(n,a,c,l))}}r(_V,"appendParsedTranscriptLine");function T_e(e){const{entries:s,chunks:n,from:a,parseLine:i,reset:o,redactionOptions:l}=e;let c=e.stdoutBuffer;for(let d=a;d<n.length;d+=1){const u=n[d];if(u.stream==="stderr"){s.push({kind:"stderr",ts:u.ts,text:$m(u.chunk,l)});continue}if(u.stream==="system"){s.push({kind:"system",ts:u.ts,text:$m(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&&_V({entries:s,line:f,ts:u.ts,parseLine:i,reset:o,redactionOptions:l})}}return c}r(T_e,"foldTranscriptChunks");function R_e(e,s,n){const a=[],i={enabled:n?.censorUsernameInLogs??!1},{parseLine:o,reset:l}=Pz(s),c=T_e({entries:a,chunks:e,from:0,stdoutBuffer:"",parseLine:o,reset:l,redactionOptions:i}).trim();return c&&_V({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(R_e,"buildTranscript");var Vre=[];function Zdt(e,s){const n={enabled:s?.censorUsernameInLogs??!1},a=typeof e!="function"&&typeof e.createStdoutParser=="function";let i=Pz(e),o=[],l="",c=Vre,d=[];const u=r(()=>{i=Pz(e),o=[],l="",c=Vre},"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 R_e(f,e,s);const g=o.slice(),v=g.length-1;return v>=0&&(g[v]={...g[v]}),x&&_V({entries:g,line:x,ts:f.length>0?f[f.length-1].ts:new Date().toISOString(),parseLine:i.parseLine,reset:i.reset,redactionOptions:n}),g},"publish");return{update(f){return f===c||(h(f)||u(),l=T_e({entries:o,chunks:f,from:c.length,stdoutBuffer:l,parseLine:i.parseLine,reset:i.reset,redactionOptions:n}),c=f,d=p(f)),d}}}r(Zdt,"createIncrementalTranscript");function Jdt({agents:e,value:s,onChange:n,disabled:a=!1,excludeAgentIds:i=[],disabledEmptyLabel:o="Reports to: N/A (CEO)",chooseLabel:l="Reports to..."}){const[c,d]=(0,m.useState)(!1),u=new Set(i),h=e.filter(g=>g.status!=="terminated"&&!u.has(g.id)),p=s?e.find(g=>g.id===s):null,f=p?.status==="terminated",x=!!(s&&!p);return(0,t.jsxs)(dr,{open:c,onOpenChange:d,children:[(0,t.jsx)(wr,{asChild:!0,children:(0,t.jsx)("button",{type:"button",className:W("inline-flex max-w-full min-w-0 items-center gap-1.5 overflow-hidden rounded-md border border-border px-2 py-1 text-xs hover:bg-accent/50 transition-colors",f&&"border-amber-600/45 bg-amber-500/5",a&&"opacity-60 cursor-not-allowed"),disabled:a,children:x?(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)(pd,{className:"h-3 w-3 shrink-0 text-muted-foreground"}),(0,t.jsx)("span",{className:"min-w-0 truncate text-muted-foreground",children:"Unknown manager (stale ID)"})]}):p?(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)(lr,{agent:p,size:16,className:"h-3 w-3 shrink-0 text-muted-foreground"}),(0,t.jsx)("span",{className:W("min-w-0 truncate",f&&"text-amber-900 dark:text-amber-200"),children:`Reports to ${p.name}${f?" (terminated)":""}`})]}):(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)(pd,{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)(sr,{className:"w-48 p-1",align:"start",children:[(0,t.jsx)("button",{type:"button",className:W("flex items-center gap-2 w-full px-2 py-1.5 text-xs rounded hover:bg-accent/50",s===null&&"bg-accent"),onClick:r(()=>{n(null),d(!1)},"onClick"),children:"No manager"}),f&&(0,t.jsxs)("div",{className:"flex min-w-0 items-center gap-2 overflow-hidden px-2 py-1.5 text-xs text-muted-foreground border-b border-border mb-0.5",children:[(0,t.jsx)(lr,{agent:p,size:16,className:"shrink-0 h-3 w-3"}),(0,t.jsxs)("span",{className:"min-w-0 truncate",children:["Current: ",p.name," (terminated)"]})]}),x&&(0,t.jsx)("div",{className:"px-2 py-1.5 text-xs text-muted-foreground border-b border-border mb-0.5",children:"Saved manager is missing from this organization. Choose a new manager or clear."}),h.map(g=>(0,t.jsxs)("button",{type:"button",className:W("flex items-center gap-2 w-full min-w-0 px-2 py-1.5 text-xs rounded hover:bg-accent/50 overflow-hidden",g.id===s&&"bg-accent"),onClick:r(()=>{n(g.id),d(!1)},"onClick"),children:[(0,t.jsx)(lr,{agent:g,size:16,className:"shrink-0 h-3 w-3 text-muted-foreground"}),(0,t.jsx)("span",{className:"min-w-0 truncate",children:g.name}),(0,t.jsx)("span",{className:"text-muted-foreground ml-auto shrink-0",children:ZCe[g.role]??g.role})]},g.id))]})]})}r(Jdt,"ReportsToPicker");var Xdt="__secret_folder__:";function eut(e){return!e||e==="active"?null:(0,t.jsx)(it,{variant:"outline",className:"ml-auto text-(length:--text-nano) font-normal text-muted-foreground",children:e})}r(eut,"statusBadge");function E_e(e){return e.split("/").filter(s=>s.length>0)}r(E_e,"splitSecretPath$1");function bR(e){return e.join("/")}r(bR,"pathKey$1");function E2(e){return e.length>0?`/${e.join("/")}`:"/"}r(E2,"pathLabel");function tut(e,s){return e.length<s.length?!1:s.every((n,a)=>e[a]===n)}r(tut,"pathStartsWith");function Gre(e){return`${Xdt}${bR(e)}`}r(Gre,"folderValue");function sut(e,s,n){const a=s.length,i=new Map,o=[];for(const c of e){const d=E_e(c.name);if(tut(d,s)){if(d.length>a+1){const u=d.slice(0,a+1),h=bR(u);if(!i.has(h)){const p=u[u.length-1]??"/",f=E2(u);i.set(h,{key:`folder-${h||"root"}`,value:Gre(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-${bR(s)}`,value:Gre(c),label:"Up one folder",title:E2(c),searchText:E2(c),kind:"back",folderPath:bR(c),pathHint:E2(c)})}return l.push(...i.values(),...o),{id:"browse-secrets",label:s.length>0?E2(s):"Browse secrets",options:l}}r(sut,"buildFolderGroup");function AV({secretId:e,secrets:s,recentlyUsedSecrets:n,disabled:a,onSelect:i,onCreateNew:o,triggerClassName:l,disablePortal:c}){const[d,u]=(0,m.useState)(""),h=(0,m.useMemo)(()=>s.find(y=>y.id===e)??null,[s,e]),p=!!e&&!h,f=(0,m.useMemo)(()=>d?d.split("/"):[],[d]),x=(0,m.useMemo)(()=>s.some(y=>E_e(y.name).length>1),[s]),g=(0,m.useMemo)(()=>{const y=[];p&&y.push({id:"current-missing",label:"Current",options:[{key:`missing-${e}`,value:e,label:`Missing secret (${e.slice(0,8)}…)`,title:`Missing secret (${e})`,missing:!0,disabled:!0}]});const k=(n??[]).filter(w=>w.status==="active"&&w.id!==e);return k.length>0&&y.push({id:"recently-used",label:"Recently used",options:k.map(w=>({key:`recent-${w.id}`,value:w.id,label:w.name,title:w.name,searchText:`${w.key} ${w.name}`,secret:w,status:w.status,kind:"secret"}))}),y.push({id:"all-secrets",label:k.length>0?"All secrets":void 0,options:s.map(w=>({key:`all-${w.id}`,value:w.id,label:w.name,title:w.name,searchText:`${w.key} ${w.name}`,secret:w,status:w.status,kind:"secret",disabled:w.status!=="active"&&w.id!==e}))}),y},[p,n,e,s]),v=(0,m.useCallback)((y,k)=>{if(!x||PFe(y))return k;const w=sut(s,f,e),N=k.filter(S=>S.id==="current-missing"||S.id==="recently-used");return w.options.length>0?[...N,w]:N},[f,x,e,s]);return(0,t.jsx)(mg,{value:e||"",groups:g,onValueChange:r((y,k)=>{if(k.folderPath!==void 0)return u(k.folderPath),!1;u(""),i(y)},"onValueChange"),deriveGroups:v,disabled:a,disablePortal:c,placeholder:"Select secret…",searchPlaceholder:"Search secrets…",emptyMessage:"No matching secrets",triggerClassName:W("h-(--sz-34px) min-h-(--sz-34px) font-mono text-sm",p&&"border-destructive text-destructive",h&&h.status!=="active"&&"border-amber-500/60",l),renderValue:r(y=>{if(!y)return(0,t.jsx)("span",{className:"text-muted-foreground",children:"Select secret…"});if(y.missing)return(0,t.jsxs)("span",{className:"flex w-full min-w-0 items-center gap-1.5 text-destructive",children:[(0,t.jsx)(Ni,{className:"size-3.5 shrink-0"}),(0,t.jsx)("span",{className:"min-w-0 flex-1 truncate",children:y.label})]});const k=y.status&&y.status!=="active";return(0,t.jsxs)("span",{className:"flex w-full min-w-0 items-center gap-1.5",title:y.title,children:[(0,t.jsx)(Ni,{className:W("size-3.5 shrink-0",k?"text-amber-600":"text-muted-foreground")}),(0,t.jsx)("span",{className:"min-w-0 flex-1 truncate",children:y.label}),k?(0,t.jsxs)("span",{className:"text-amber-600",children:["(",y.status,")"]}):null]})},"renderValue"),renderOption:r((y,{selected:k})=>{if(y.kind==="folder"||y.kind==="back"){const w=y.kind==="back"?tQe:Wl;return(0,t.jsxs)("span",{className:"flex min-w-0 flex-1 items-center gap-1.5",title:y.title??y.label,children:[(0,t.jsx)(w,{className:"size-3.5 shrink-0 text-muted-foreground"}),(0,t.jsxs)("span",{className:"flex min-w-0 flex-col",children:[(0,t.jsx)("span",{className:W("truncate text-sm",k&&"font-medium"),children:y.label}),y.pathHint?(0,t.jsx)("span",{className:"truncate font-mono text-(length:--text-micro) text-muted-foreground",children:y.pathHint}):null]})]})}return(0,t.jsxs)("span",{className:W("flex min-w-0 flex-1 items-center gap-1.5",y.disabled&&"opacity-60"),title:y.title??y.label,children:[(0,t.jsx)(Ni,{className:"size-3.5 shrink-0 text-muted-foreground"}),(0,t.jsxs)("span",{className:"flex min-w-0 flex-col",children:[(0,t.jsx)("span",{className:W("min-w-0 truncate font-mono text-sm",k&&"font-medium"),children:y.label}),y.pathHint&&y.pathHint!==y.label?(0,t.jsx)("span",{className:"truncate font-mono text-(length:--text-micro) text-muted-foreground",children:y.pathHint}):null]}),eut(y.status)]})},"renderOption"),createItem:o?{render:r(y=>(0,t.jsxs)("span",{className:"flex items-center gap-1.5 text-sm",children:[(0,t.jsx)(gn,{className:"size-3.5 shrink-0"}),y.trim()?(0,t.jsxs)("span",{children:["Create secret ",(0,t.jsxs)("span",{className:"font-mono",children:["“",y.trim(),"”"]}),"…"]}):(0,t.jsx)("span",{children:"Create new secret…"})]}),"render"),onSelect:r(y=>o(y),"onSelect")}:void 0})}r(AV,"SecretPicker");var nut=/^[a-z][a-z0-9_]*$/,Yre="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 L_e({mode:e,initialName:s,initialValue:n,existingSecretNames:a,onCancel:i,onSubmit:o}){const[l,c]=(0,m.useState)(s),[d,u]=(0,m.useState)(n),[h,p]=(0,m.useState)(!1),[f,x]=(0,m.useState)(!1),[g,v]=(0,m.useState)(null),[y,k]=(0,m.useState)(!1),w=l.trim(),N=w?nut.test(w)?a?.some(I=>I.toLowerCase()===w)?"A secret with this name already exists":null:"Use lowercase letters, digits and _":y?"Name is required":null,S=d.length===0&&y?"Value is required":null,C=!f&&w.length>0&&d.length>0&&!N;async function _(){if(k(!0),!!C){x(!0),v(null);try{await o(w,d)}catch(I){v(I instanceof Error?I.message:"Failed to create secret"),x(!1)}}}r(_,"handleSubmit");const R=e==="create"?"Create & bind":"Store & bind";return(0,t.jsxs)("div",{className:"w-72 space-y-3",children:[(0,t.jsxs)("div",{className:"space-y-1",children:[(0,t.jsx)(cFe,{className:"text-sm font-medium",children:e==="create"?"Create secret":"Store value as secret"}),e==="store"?(0,t.jsxs)(JBe,{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(Yre,N&&"border-destructive focus-visible:ring-destructive/40"),value:l,autoFocus:!0,spellCheck:!1,placeholder:"secret_name","aria-label":"Secret name","aria-invalid":N?!0:void 0,onChange:r(I=>c(I.target.value),"onChange"),onBlur:r(()=>k(!0),"onBlur"),onKeyDown:r(I=>{I.key==="Enter"&&(I.preventDefault(),_())},"onKeyDown")}),N?(0,t.jsx)("span",{className:"block text-(length:--text-micro) text-destructive",children:N}):null]}),(0,t.jsxs)("label",{className:"block space-y-1",children:[(0,t.jsx)("span",{className:"text-(length:--text-micro) font-medium text-muted-foreground",children:"Value"}),(0,t.jsxs)("div",{className:"relative",children:[(0,t.jsx)("input",{className:W(Yre,"pr-8",S&&"border-destructive focus-visible:ring-destructive/40"),type:h?"text":"password",value:d,readOnly:e==="store",spellCheck:!1,placeholder:e==="create"?"value":void 0,"aria-label":"Secret value","aria-invalid":S?!0:void 0,onChange:e==="create"?I=>u(I.target.value):void 0}),(0,t.jsx)("button",{type:"button",className:"absolute right-1.5 top-1/2 -translate-y-1/2 rounded p-1 text-muted-foreground hover:text-foreground","aria-label":h?"Hide value":"Show value",onClick:r(()=>p(I=>!I),"onClick"),children:h?(0,t.jsx)(eh,{className:"h-3.5 w-3.5"}):(0,t.jsx)(Jd,{className:"h-3.5 w-3.5"})})]}),S?(0,t.jsx)("span",{className:"block text-(length:--text-micro) text-destructive",children:S}):null]}),g?(0,t.jsx)("p",{className:"text-(length:--text-micro) text-destructive",children:g}):null,(0,t.jsxs)("div",{className:"flex items-center justify-end gap-2 pt-0.5",children:[(0,t.jsx)($,{type:"button",variant:"ghost",size:"sm",onClick:i,disabled:f,children:"Cancel"}),(0,t.jsxs)($,{type:"button",size:"sm",onClick:r(()=>{_()},"onClick"),disabled:!C,children:[f?(0,t.jsx)(st,{className:"h-3.5 w-3.5 animate-spin"}):null,R]})]})]})}r(L_e,"SecretPopoverForm");function M_e(e){return(0,t.jsx)(L_e,{mode:"create",...e})}r(M_e,"CreateSecretPopover");function rut(e){return(0,t.jsx)(L_e,{mode:"store",...e})}r(rut,"ConvertToSecretPopover");var aut=/(api[-_]?key|access[-_]?token|auth(?:_?token)?|authorization|bearer|secret|passwd|password|credential|jwt|private[-_]?key|cookie|connectionstring)/i,iut=[/^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 out(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(out,"looksHighEntropy");function lut(e,s){return s?aut.test(e)||iut.some(n=>n.test(s))?!0:out(s):!1}r(lut,"isSensitiveEnv");var Zre=0;function cut(){return Zre+=1,`env-row-${Zre}`}r(cut,"nextRowId");function Sx(e="text"){return{id:cut(),name:"",source:e,textValue:"",secretId:"",userSecretKey:"",required:!0,version:"latest"}}r(Sx,"emptyRow");function dut(e){return typeof e=="object"&&e!==null&&"type"in e&&e.type==="secret_ref"}r(dut,"isSecretRef");function uut(e){return typeof e=="object"&&e!==null&&"type"in e&&e.type==="plain"}r(uut,"isPlainObj");function mut(e){return typeof e=="object"&&e!==null&&"type"in e&&e.type==="user_secret_ref"}r(mut,"isUserSecretRef");function oD(e){return!e||typeof e!="object"?[]:Object.entries(e).map(([s,n])=>{if(typeof n=="string")return{...Sx(),name:s,textValue:n};if(dut(n)){const a=typeof n.version=="number"?n.version:"latest";return{...Sx(),name:s,source:"secret",secretId:typeof n.secretId=="string"?n.secretId:"",version:a}}if(mut(n)){const a=typeof n.version=="number"?n.version:"latest";return{...Sx(),name:s,source:"user_secret",userSecretKey:typeof n.key=="string"?n.key:"",required:n.required!==!1,version:a}}return uut(n)?{...Sx(),name:s,source:"text",textValue:typeof n.value=="string"?n.value:""}:{...Sx(),name:s}})}r(oD,"rowsFromValue");function vR(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(vR,"valueFromRows");var Jre="CLAUDE_CODE_OAUTH_TOKEN";function nk(){return vR([{...Sx("user_secret"),name:"CLAUDE_CODE_OAUTH_TOKEN",userSecretKey:"CLAUDE_CODE_OAUTH_TOKEN",required:!0,version:"latest"}])??{}}r(nk,"buildFixedClaudeOAuthBinding");var hut=/^[A-Za-z_][A-Za-z0-9_]*$/;function put(e,s,n){const a=e.trim();if(!a)return null;if(!hut.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(put,"validateName");function fut(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(fut,"computeDuplicateNames");function xut(e,s){return s===e.source?{kind:"noop"}:s==="secret"?e.textValue.trim()?{kind:"open-store",name:TE(e.name)||"secret",value:e.textValue}:{kind:"to-secret"}:{kind:"to-text",undoFrom:e.secretId?{...e}:null}}r(xut,"planSourceSwitch");function P_e(e,s){if(e.source!=="secret"||!e.secretId)return null;const n=s.find(a=>a.id===e.secretId);return n?n.status!=="active"?{level:"warn",kind:"disabled",message:"Runs will fail until re-enabled or rebound."}:null:{level:"error",kind:"missing",message:"This secret no longer exists — runs will fail until you rebind."}}r(P_e,"computeRowHealth");function D_e(e,s){if(e.source!=="user_secret"||!e.userSecretKey||!s?.length)return null;const n=s.find(a=>a.key===e.userSecretKey);return n?n.status!=="active"?{level:"warn",kind:"disabled",message:"Runs will fail until this user secret definition is re-enabled or rebound."}:null:{level:"error",kind:"missing",message:"This user secret definition no longer exists — runs will fail until you rebind."}}r(D_e,"computeUserSecretRowHealth");function TE(e){return e.trim().toLowerCase().replace(/[^a-z0-9_]+/g,"_").replace(/^_+|_+$/g,"").slice(0,64)}r(TE,"secretNameFromKey");function f_(e){return e.trim().toUpperCase().replace(/[^A-Z0-9_]+/g,"_").replace(/^_+|_+$/g,"").slice(0,64)}r(f_,"envKeyFromSecretName");var gut="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",Xre="min-w-0 flex-1 bg-transparent px-2 py-1.5 text-sm font-mono outline-none placeholder:text-muted-foreground/40";function but({row:e,isLast:s,secrets:n,userSecretDefinitions:a,recentlyUsedSecrets:i,disabled:o,nameIssue:l,showNameIssue:c,dirtyFields:d,onPatch:u,onRemove:h,onNameBlur:p,onNamePaste:f,onEnterInValueLast:x,onCreateSecret:g,onToast:v,focusRequest:y,onFocusConsumed:k}){const w=(0,m.useRef)(null),N=(0,m.useRef)(null),S=(0,m.useRef)(null),[C,_]=(0,m.useState)(null),[R,I]=(0,m.useState)(!1),[T,E]=(0,m.useState)(null),L=P_e(e,n)??D_e(e,a),O=e.source==="secret"?n.find(J=>J.id===e.secretId)??null:null,P=(a?.length??0)>0,Q=e.source==="text"&&!e.sensitiveDismissed&&lut(e.name,e.textValue);(0,m.useEffect)(()=>{y&&(y==="name"?w.current?.focus():e.source==="text"?N.current?.focus():e.source==="secret"?S.current?.querySelector("[role=combobox]")?.focus():S.current?.querySelector("select,input")?.focus(),k())},[y,k,e.source]),(0,m.useEffect)(()=>{if(!T)return;const J=window.setTimeout(()=>E(null),5e3);return()=>window.clearTimeout(J)},[T]);function D(J){if(J==="user_secret"){if(e.source==="user_secret")return;u({source:"user_secret",secretId:"",version:"latest"}),window.setTimeout(()=>S.current?.querySelector("select,input")?.focus(),0);return}const re=xut(e,J);switch(re.kind){case"noop":return;case"open-store":{const{name:oe,value:V}=re;window.setTimeout(()=>_({mode:"store",name:oe,value:V}),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&&E(re.undoFrom),u({source:"text",secretId:"",userSecretKey:"",required:!0,version:"latest"}),window.setTimeout(()=>N.current?.focus(),0);return}}r(D,"switchSource");async function F(J,re){const oe=await g(J,re);u({source:"secret",secretId:oe.id,userSecretKey:"",required:!0,version:"latest",textValue:""}),v(`Secret ${oe.name} created`),_(null)}r(F,"submitSecretPopover");function z(){const J=TE(e.name)||"secret",{textValue:re}=e;window.setTimeout(()=>_({mode:"store",name:J,value:re}),0)}r(z,"openStoreAsSecret");const K=e.source==="text"?"Text value":e.source==="secret"?"Organization secret reference":"User secret reference",U=`${e.id}-name-error`,q=`${e.id}-health`,G=d.name||d.value,se=O?Math.max(0,O.latestVersion):0,Z=e.version==="latest"?"latest":`v${e.version}`,ie=e.version!=="latest";return(0,t.jsxs)("div",{className:W("group/row grid grid-cols-(--gtc-13) items-start gap-x-1.5 gap-y-1 rounded-md px-1 py-1","@[40rem]/env:grid-cols-(--gtc-14) @[40rem]/env:items-center",G&&"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(gut,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?U:void 0,onChange:r(J=>u({name:J.target.value}),"onChange"),onBlur:p,onPaste:r(J=>{e.name||f(J.clipboardData.getData("text"))&&J.preventDefault()},"onPaste"),onKeyDown:r(J=>{J.key==="Enter"&&(J.preventDefault(),e.source==="text"?N.current?.focus():S.current?.querySelector("[role=combobox],select,input")?.focus())},"onKeyDown")})}),(0,t.jsxs)("div",{className:"col-span-2 col-start-1 row-start-2 min-w-0 @[40rem]/env:col-span-1 @[40rem]/env:col-start-2 @[40rem]/env:row-start-1",children:[(0,t.jsxs)(dr,{open:C!==null,onOpenChange:r(J=>{J||_(null)},"onOpenChange"),children:[(0,t.jsx)(iF,{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)(ia,{children:[(0,t.jsxs)(Bn,{children:[(0,t.jsx)(On,{asChild:!0,children:(0,t.jsx)(ra,{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)(BQe,{className:"size-3.5"}):e.source==="secret"?(0,t.jsx)(Ni,{className:"size-3.5"}):(0,t.jsx)(th,{className:"size-3.5"}),(0,t.jsx)(rn,{className:"size-3 opacity-60"})]})})}),(0,t.jsx)($n,{side:"top",children:K})]}),(0,t.jsxs)(aa,{align:"start",className:"w-56",children:[(0,t.jsxs)(ls,{className:"flex-col items-start gap-0.5",onSelect:r(()=>D("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(()=>D("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(()=>D("user_secret"),"onSelect"),children:[(0,t.jsx)("span",{className:"text-sm",children:"User secret"}),(0,t.jsx)("span",{className:"text-(length:--text-micro) text-muted-foreground",children:"Resolve the responsible user's own value at run start."})]})]})]}),e.source==="text"?(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)("input",{ref:N,className:Xre,placeholder:"value",value:e.textValue,type:Q?"password":"text",spellCheck:!1,disabled:o,"aria-label":"Variable value",onChange:r(J=>u({textValue:J.target.value}),"onChange"),onKeyDown:r(J=>{J.key==="Enter"&&s&&(J.preventDefault(),x())},"onKeyDown")}),Q?(0,t.jsxs)("div",{className:"flex shrink-0 items-stretch border-l border-border",children:[(0,t.jsxs)("button",{type:"button",onClick:z,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)(Ic,{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)(En,{className:"size-3"})})]}):null]}):e.source==="secret"?(0,t.jsxs)("div",{className:"relative min-w-0 flex-1",children:[(0,t.jsx)(AV,{secretId:e.secretId,secrets:n,recentlyUsedSecrets:i,disabled:o,onSelect:r(J=>u({secretId:J,version:"latest"}),"onSelect"),onCreateNew:r(J=>_({mode:"create",name:TE(J)||J.trim(),value:""}),"onCreateNew"),triggerClassName:W("rounded-none border-0 bg-transparent shadow-none focus-visible:ring-0",O&&O.status==="active"&&"pr-24 has-[>svg]:!pr-24")}),O&&O.status==="active"?(0,t.jsxs)(dr,{open:R,onOpenChange:I,children:[(0,t.jsx)(iF,{asChild:!0,children:(0,t.jsx)("button",{type:"button",disabled:o,onClick:r(J=>{J.preventDefault(),J.stopPropagation(),I(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",ie?"bg-amber-500/15 text-amber-700 dark:text-amber-400":"text-muted-foreground hover:bg-accent"),children:Z})}),(0,t.jsxs)(sr,{align:"end",className:"w-44 p-1",role:"radiogroup","aria-label":"Secret version",children:[(0,t.jsxs)("button",{type:"button",role:"radio","aria-checked":e.version==="latest",onClick:r(()=>{u({version:"latest"}),I(!1)},"onClick"),className:W("flex w-full items-center justify-between rounded px-2 py-1.5 text-sm hover:bg-accent",e.version==="latest"&&"font-medium"),children:["latest ",(0,t.jsx)("span",{className:"text-(length:--text-micro) text-muted-foreground",children:"(recommended)"})]}),Array.from({length:se},(J,re)=>se-re).filter(J=>J>0).map(J=>(0,t.jsxs)("button",{type:"button",role:"radio","aria-checked":e.version===J,onClick:r(()=>{u({version:J}),I(!1)},"onClick"),className:W("flex w-full items-center rounded px-2 py-1.5 text-sm hover:bg-accent",e.version===J&&"font-medium text-amber-700 dark:text-amber-400"),children:["v",J]},J))]})]}):null]}):(0,t.jsxs)("div",{className:"grid min-w-0 flex-1 grid-cols-(--gtc-13)",children:[P?(0,t.jsxs)("select",{"aria-label":"User secret",value:e.userSecretKey,disabled:o,onChange:r(J=>{const re=J.target.value,oe=a?.find(V=>V.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(J=>J.key===e.userSecretKey)?(0,t.jsxs)("option",{value:e.userSecretKey,children:["Unknown (",e.userSecretKey,")"]}):null,(a??[]).map(J=>(0,t.jsxs)("option",{value:J.key,children:[J.name,J.status!=="active"?` (${J.status})`:""]},J.id))]}):(0,t.jsx)("input",{className:Xre,placeholder:"user-secret key",value:e.userSecretKey,spellCheck:!1,disabled:o,"aria-label":"User secret key",onChange:r(J=>u({userSecretKey:J.target.value}),"onChange")}),(0,t.jsxs)("select",{"aria-label":"Requirement",value:e.required?"required":"optional",disabled:o,onChange:r(J=>u({required:J.target.value==="required"}),"onChange"),className:"border-l border-border bg-transparent px-2 py-1.5 text-xs font-medium text-muted-foreground outline-none disabled:pointer-events-none",children:[(0,t.jsx)("option",{value:"required",children:"Required"}),(0,t.jsx)("option",{value:"optional",children:"Optional"})]})]})]})}),(0,t.jsx)(sr,{align:"start",className:"w-auto p-3",onInteractOutside:r(J=>{const re=J.detail.originalEvent.target;re&&S.current?.contains(re)&&J.preventDefault()},"onInteractOutside"),children:C?.mode==="store"?(0,t.jsx)(rut,{initialName:C.name,initialValue:C.value,existingSecretNames:n.map(J=>J.name),onCancel:r(()=>_(null),"onCancel"),onSubmit:F}):C?.mode==="create"?(0,t.jsx)(M_e,{initialName:C.name,initialValue:C.value,existingSecretNames:n.map(J=>J.name),onCancel:r(()=>_(null),"onCancel"),onSubmit:F}):null})]}),L?(0,t.jsx)("p",{id:q,role:"status",className:W("mt-0.5 text-(length:--text-micro)",L.level==="error"?"text-destructive":"text-amber-600 dark:text-amber-400"),children:L.message}):null,T?(0,t.jsxs)("p",{className:"mt-0.5 inline-flex items-center gap-2 text-(length:--text-micro) text-muted-foreground",children:["Reverted to text —"," ",(0,t.jsx)("button",{type:"button",className:"font-medium text-foreground underline underline-offset-2 hover:text-primary",onClick:r(()=>{u({source:"secret",secretId:T.secretId,version:T.version,textValue:""}),E(null)},"onClick"),children:"Undo"})]}):null]}),c&&l?(0,t.jsx)("p",{id:U,className:W("col-span-2 col-start-1 row-start-3 min-w-0 text-(length:--text-micro) @[40rem]/env:col-span-2 @[40rem]/env:row-start-2",l.level==="error"?"text-destructive":"text-amber-600 dark:text-amber-400"),children:l.message}):null,(0,t.jsxs)("div",{className:"col-start-2 row-start-1 flex items-center justify-end gap-0.5 self-start @[40rem]/env:col-start-3 @[40rem]/env:self-center",children:[e.source==="text"&&!Q&&(e.name.trim()||e.textValue)?(0,t.jsxs)(ia,{children:[(0,t.jsx)(ra,{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)(Ci,{className:"size-4"})})}),(0,t.jsx)(aa,{align:"end",children:(0,t.jsx)(ls,{onSelect:r(()=>{window.setTimeout(z,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)(En,{className:"size-4"})})]})]})}r(but,"EnvironmentVariableRow");var vut=/^\s*(?:export\s+)?([A-Za-z_][A-Za-z0-9_]*)\s*=(.*)$/;function yut(e){const s=e.indexOf(" #");return s>=0?e.slice(0,s):e}r(yut,"stripInlineComment");function jut(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 yut(s).trim()}r(jut,"unquote");function wut(e){const s=[];for(const n of e.split(/\r?\n/)){const a=n.trim();if(!a||a.startsWith("#"))continue;const i=vut.exec(a);if(!i)continue;const o=i[1],l=jut(i[2]);s.push({key:o,value:l})}return s}r(wut,"parseDotenv");var kut=["PAPERCLIP_"],Nut="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 Dz(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(Dz,"normalizedEnvEntries");function L2(e){return JSON.stringify(Dz(e))}r(L2,"normalizedEnvKey");var lD=3;function cD(e){const s=e.slice(0,lD).join(", ");return e.length>lD?`${s} +${e.length-lD} more`:s}r(cD,"formatChangedNames");function eae(e){return e.map(s=>({...s}))}r(eae,"cloneRows");function Sut(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(Sut,"rowDirtyFields");var Ij=(0,m.forwardRef)(r(function({value:s,onChange:n,secrets:a,userSecretDefinitions:i,onCreateSecret:o,recentlyUsedSecrets:l,disabled:c,reservedPrefixes:d=kut,footerHint:u,onDirtyChange:h,hideDraftActions:p=!1},f){const x=bd(),g=(0,m.useRef)(null),[v,y]=(0,m.useState)(()=>oD(s)),k=(0,m.useRef)(v),[w,N]=(0,m.useState)(()=>eae(v)),S=(0,m.useMemo)(()=>L2(s),[]),C=(0,m.useRef)(S),_=(0,m.useRef)(S),R=(0,m.useRef)(null),[I,T]=(0,m.useState)(S),[E,L]=(0,m.useState)(()=>new Set(oD(s).map(de=>de.name.trim()).filter(Boolean))),[O,P]=(0,m.useState)(null);(0,m.useEffect)(()=>{k.current=v},[v]);function Q(de,Ne=k.current){C.current=de,T(de),N(eae(Ne))}r(Q,"markCommitted");function D(de){L(Ne=>{const le=new Set(Ne);for(const Le of de){const Ie=Le.name.trim();Ie&&le.add(Ie)}return le})}r(D,"touchCommittedNames");function F(de){const Ne=oD(de);return y(Ne),D(Ne),Ne}r(F,"adoptExternalValue"),(0,m.useEffect)(()=>{const de=L2(s);if(de===_.current)return;_.current=de;const Ne=L2(vR(k.current)),le=Ne!==C.current,Le=R.current===de;if(Le&&(R.current=null),!le){Q(de,F(s));return}(Le||Ne===de)&&(D(k.current),Q(de))},[s]);const z=(0,m.useMemo)(()=>vR(v),[v]),K=(0,m.useMemo)(()=>L2(z),[z]),U=K!==I;(0,m.useEffect)(()=>{h?.(!c&&U)},[c,U,h]);const q=(0,m.useMemo)(()=>{const de=new Map(Dz(vR(w)).map(([Ie,ye])=>[Ie,JSON.stringify(ye)])),Ne=new Map(Dz(z).map(([Ie,ye])=>[Ie,JSON.stringify(ye)])),le=[],Le=[];for(const[Ie,ye]of Ne)de.has(Ie)?de.get(Ie)!==ye&&Le.push(Ie):le.push(Ie);return{added:le,changed:Le,removed:[...de.keys()].filter(Ie=>!Ne.has(Ie))}},[w,z]),G=(0,m.useMemo)(()=>{const de=[];return q.added.length>0&&de.push(`New: ${cD(q.added)}`),q.changed.length>0&&de.push(`Edited: ${cD(q.changed)}`),q.removed.length>0&&de.push(`Removed: ${cD(q.removed)}`),de.join(" · ")},[q]);(0,m.useEffect)(()=>{if(c||!U)return;function de(Ne){Ne.preventDefault(),Ne.returnValue=""}return r(de,"handleBeforeUnload"),window.addEventListener("beforeunload",de),()=>window.removeEventListener("beforeunload",de)},[c,U]);const se=(0,m.useCallback)(()=>c||!U?null:(R.current=K,(0,Vh.flushSync)(()=>{n(z)}),z??{}),[c,z,K,U,n]);(0,m.useImperativeHandle)(f,()=>({flushPendingDraft:se}),[se]),(0,m.useEffect)(()=>{const de=g.current?.closest("form");if(!de)return;function Ne(){se()}return r(Ne,"handleSubmit"),de.addEventListener("submit",Ne,!0),()=>de.removeEventListener("submit",Ne,!0)},[se]),(0,m.useEffect)(()=>{const de=g.current;if(!de)return;const Ne=de;function le(Le){const Ie=Le.target;if(!(Ie instanceof Element)||Ne.contains(Ie))return;const ye=Ie.closest("button");if(!ye||ye.disabled)return;const Ae=`${ye.getAttribute("aria-label")??""} ${ye.textContent??""}`;(ye.type==="submit"||/\b(save|create|update|test|import)\b/i.test(Ae))&&se()}return r(le,"handleDocumentClick"),document.addEventListener("click",le,!0),()=>document.removeEventListener("click",le,!0)},[se]);function Z(de){y(de)}r(Z,"updateDraft");function ie(de,Ne){Z(v.map(le=>le.id===de?{...le,...Ne}:le))}r(ie,"patchRow");function J(de){Z(v.filter(Ne=>Ne.id!==de))}r(J,"removeRow");function re(){const de=Sx();y([...v,de]),P({rowId:de.id,field:"name"})}r(re,"addRow");function oe(de){const Ne=v.find(le=>le.id===de)?.name.trim();Ne&&L(le=>{if(le.has(Ne))return le;const Le=new Set(le);return Le.add(Ne),Le})}r(oe,"markTouched");function V(de,Ne){const le=wut(de);if(le.length===0)return!1;const Le=v.filter(Ie=>Ie.id!==Ne).map(Ie=>({...Ie}));for(const{key:Ie,value:ye}of le){const Ae=Le.find(Qe=>Qe.name.trim()===Ie);Ae?(Ae.name=Ie,Ae.source="text",Ae.textValue=ye,Ae.secretId="",Ae.sensitiveDismissed=!1,Ae.userSecretKey="",Ae.required=!0):Le.push({...Sx(),name:Ie,textValue:ye})}return Z(Le),x?.pushToast({title:`Imported ${le.length} variable${le.length===1?"":"s"}`,tone:"success"}),!0}r(V,"bulkImport");function X(de){const Ne=v.map(Ie=>({...Ie})),le=Ne[Ne.length-1];let Le;le&&!le.name&&!le.textValue&&!le.secretId&&!le.userSecretKey?Le=le:(Le=Sx(),Ne.push(Le)),Le.source="secret",Le.secretId=de.id,Le.version="latest",Le.name||(Le.name=f_(de.name)),Z(Ne)}r(X,"bindRecentSecret");function Y(){U&&(R.current=K,n(z))}r(Y,"saveDraft");function ae(){R.current=null,_.current=L2(s);const de=F(s);Q(_.current,de)}r(ae,"revertDraft");const ne=(0,m.useMemo)(()=>fut(v),[v]),ce=(0,m.useMemo)(()=>v.reduce((de,Ne)=>P_e(Ne,a)||D_e(Ne,i)?de+1:de,0),[v,a,i]),he=(0,m.useMemo)(()=>{const de=new Set(v.filter(Ne=>Ne.source==="secret"&&Ne.secretId).map(Ne=>Ne.secretId));return(l??[]).filter(Ne=>Ne.status==="active"&&!de.has(Ne.id)).slice(0,8)},[l,v]),pe=v.length>0,ge=u===void 0?Nut:u,Ee=(0,m.useMemo)(()=>new Map(w.map(de=>[de.id,de])),[w]);return(0,t.jsx)(Yc,{children:(0,t.jsxs)("div",{ref:g,className:"@container/env space-y-2",children:[ce>1?(0,t.jsxs)("p",{className:"inline-flex items-center gap-1.5 text-(length:--text-micro) font-medium text-amber-700 dark:text-amber-400",children:[(0,t.jsx)(eo,{className:"size-3.5"}),ce," bindings need attention"]}):null,pe?(0,t.jsxs)(t.Fragment,{children:[(0,t.jsxs)("div",{className:"hidden gap-x-1.5 @[40rem]/env:grid @[40rem]/env:grid-cols-(--gtc-14)",children:[(0,t.jsx)("span",{className:"text-(length:--text-micro) font-medium uppercase tracking-wide text-muted-foreground",children:"Name"}),(0,t.jsx)("span",{className:"text-(length:--text-micro) font-medium uppercase tracking-wide text-muted-foreground",children:"Value"}),(0,t.jsx)("span",{})]}),v.map((de,Ne)=>{const le=put(de.name,ne,d),Le=E.has(de.name.trim());return(0,t.jsx)(but,{row:de,isLast:Ne===v.length-1,secrets:a,userSecretDefinitions:i,recentlyUsedSecrets:l,disabled:c,nameIssue:le,showNameIssue:Le,dirtyFields:Sut(de,Ee.get(de.id)),onPatch:r(Ie=>ie(de.id,Ie),"onPatch"),onRemove:r(()=>J(de.id),"onRemove"),onNameBlur:r(()=>oe(de.id),"onNameBlur"),onNamePaste:r(Ie=>V(Ie,de.id),"onNamePaste"),onEnterInValueLast:re,onCreateSecret:o,onToast:r(Ie=>x?.pushToast({title:Ie,tone:"success"}),"onToast"),focusRequest:O?.rowId===de.id?O.field:null,onFocusConsumed:r(()=>P(null),"onFocusConsumed")},de.id)})]}):(0,t.jsx)("p",{className:"text-sm text-muted-foreground",children:"No environment variables"}),(0,t.jsxs)("div",{className:"flex flex-wrap items-center justify-between gap-2 pt-1",children:[(0,t.jsxs)("button",{type:"button",onClick: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)(gn,{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)(Ni,{className:"size-3"}),"Recently used:"]}),he.map(de=>(0,t.jsxs)("button",{type:"button",onClick:r(()=>X(de),"onClick"),className:"inline-flex items-center gap-1 rounded-full border border-border px-2 py-0.5 font-mono text-(length:--text-micro) text-muted-foreground transition-colors hover:bg-accent/50 hover:text-foreground",title:`Bind ${de.name}`,children:["+ ",de.name]},de.id))]}):null]}),U&&!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"})]}),G?(0,t.jsx)("p",{className:"min-w-0 truncate pl-4 text-xs text-amber-950/80 dark:text-amber-100/80",title:G,children:G}):null]}),(0,t.jsxs)("div",{className:"flex items-center gap-2",children:[(0,t.jsxs)("button",{type:"button",onClick:ae,className:"inline-flex h-9 items-center gap-1.5 rounded-md border border-amber-500/30 bg-background px-3 text-sm font-medium text-foreground transition-colors hover:bg-amber-500/10 dark:bg-background/80",children:[(0,t.jsx)(_i,{className:"size-4"}),"Revert"]}),(0,t.jsxs)("button",{type:"button",onClick:Y,className:"inline-flex h-9 items-center gap-1.5 rounded-md bg-primary px-4 text-sm font-medium text-primary-foreground transition-colors hover:bg-primary/90",children:[(0,t.jsx)(af,{className:"size-4"}),"Save"]})]})]}):null,ge?(0,t.jsx)("p",{className:"text-(length:--text-micro) text-muted-foreground/70",children:ge}):null,v.some(de=>de.source==="user_secret"&&de.userSecretKey)?(0,t.jsxs)("p",{className:"inline-flex items-start gap-1 text-(length:--text-micro) text-muted-foreground/70",children:[(0,t.jsx)(th,{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")),Cut="env.",tA="access.",$z=/^[A-Za-z_][A-Za-z0-9_]*$/;function $_e(e){return e?e.startsWith("access.")?"api":e.startsWith("env.")?"env":"config":"config"}r($_e,"deliveryModeForConfigPath");function O_e(e){switch(e){case"env":return"Env var";case"api":return"API access";default:return"Config"}}r(O_e,"deliveryModeLabel");function _ut(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(_ut,"deliveryModeDescription");function B_e(e){return e?e.startsWith("access.")?e.slice(7):e.startsWith("env.")?e.slice(4):e:""}r(B_e,"aliasFromConfigPath");function Aut(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(Aut,"consumerTypeLabel");var Iut={numeric:!0,sensitivity:"base"};function RC(e){return e.kind==="company"?e.secret.name:e.definition.name}r(RC,"getSecretPathRowName");function CN(e){return e.split("/").filter(s=>s.length>0)}r(CN,"splitSecretPath");function dD(e){return CN(e).join("/")}r(dD,"normalizeSecretPath");function tae(e,s){return s.every((n,a)=>e[a]===n)}r(tae,"startsWithSegments");function sae(e,s){return e.localeCompare(s,void 0,Iut)}r(sae,"compareNames");function Tut(e,s){const n=CN(s),a=e.map(c=>({row:c,name:RC(c),segments:CN(RC(c))})),i=new Set,o=[];for(const c of a){if(!tae(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(!tae(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)=>sae(c.name,d.name)),o.sort((c,d)=>sae(RC(c),RC(d))),{folders:l,secrets:o}}r(Tut,"buildSecretPathListing");function Rut(e){const s=CN(e);return s.map((n,a)=>({name:n,path:s.slice(0,a+1).join("/")}))}r(Rut,"buildSecretPathBreadcrumbs");function Eut(e){return e.trim()?e.includes("/")?"Folder name cannot contain slashes.":null:"Folder name is required."}r(Eut,"validateSecretFolderSegment");function k5({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(k5,"SecretPathName");function Lut(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(Lut,"fingerprintLabel");function F_e({fingerprint:e,length:s,className:n}){const{pushToast:a}=Xr(),i=Lut(e,s);if(!e)return(0,t.jsxs)("span",{className:W("inline-flex items-center gap-1 font-mono",n),children:[(0,t.jsx)(kF,{className:"size-3 shrink-0"}),i]});const o=`sha256:${e}`;return(0,t.jsxs)("button",{type:"button",onClick:r(()=>{wa(o).then(()=>a({title:"Fingerprint copied",tone:"success"})).catch(()=>a({title:"Couldn’t copy fingerprint",tone:"error"}))},"onClick"),title:`Copy full digest — ${o}`,className:W("inline-flex items-center gap-1 font-mono hover:text-foreground",n),children:[(0,t.jsx)(kF,{className:"size-3 shrink-0"}),i,(0,t.jsx)(gr,{className:"size-3 shrink-0 opacity-60"})]})}r(F_e,"FingerprintChip");function IV({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(IV,"ProposalJustification");function N5({agent:e,className:s}){return(0,t.jsxs)("span",{className:W("inline-flex min-w-0 items-center gap-1",s),children:[(0,t.jsx)(lr,{agent:e,size:16,className:"h-3.5 w-3.5 shrink-0 text-muted-foreground"}),(0,t.jsx)("span",{className:"min-w-0 truncate",children:e.name})]})}r(N5,"AgentRefChip");function TV({configPath:e}){const s=$_e(e),n=s==="env",a=s==="api";return(0,t.jsxs)(it,{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)(gke,{className:"size-3"}):a?(0,t.jsx)(q8,{className:"size-3"}):null,O_e(s)]})}r(TV,"DeliveryBadge$1");function RV({className:e}){return(0,t.jsxs)(it,{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)(Ic,{className:"size-3"})," Proposed"]})}r(RV,"ProposedBadge");function IM(e){return B_e(e.configPath)}r(IM,"bindingEnvKey");function EV(e){return e.secretProposalId?{name:e.secretProposalName??"proposed secret",pending:!0}:{name:e.secretName??"secret",pending:!1}}r(EV,"bindingSecretLabel");function nae(e){return e instanceof sn?e.message||`Request failed: ${e.status}`:e instanceof Error?e.message:"Something went wrong. Try again."}r(nae,"readableError");function z_e(e,s=[]){const n=kt(),{pushToast:a}=Xr(),[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:M.secrets.list(e)}))},[e,n]),x=je({mutationFn:r(w=>{const{proposal:N}=w;if(N.kind==="secret"){const S=w.folder.trim()?`${w.folder.trim().replace(/\/+$/,"")}/${w.leaf.trim()}`:w.leaf.trim();return Tr.approveProposal(e,N.id,{overrides:{name:S,description:w.description.trim()||null,providerConfigId:w.providerConfigId||null}})}return Tr.approveProposal(e,N.id,{cascade:w.cascade||void 0})},"mutationFn"),onSuccess:r(w=>{a({title:w.kind==="secret"?"Secret approved":"Binding approved",body:w.kind==="secret"?w.proposedName??"Secret created":`${w.target?.name??"Agent"} · ${IM(w)||"binding"}`,tone:"success"}),o(null),p(null),f()},"onSuccess"),onError:r(w=>p(nae(w)),"onError")}),g=je({mutationFn:r(({proposal:w,reason:N})=>Tr.rejectProposal(e,w.id,{reason:N.trim()}),"mutationFn"),onSuccess:r(w=>{a({title:"Proposal rejected",body:w.kind==="secret"?w.proposedName??void 0:void 0,tone:"info"}),c(null),u(""),p(null),f()},"onSuccess"),onError:r(w=>p(nae(w)),"onError")}),v=(0,m.useCallback)(w=>{p(null);const N=(w.proposedName??"").split("/"),S=N.pop()??"";o({proposal:w,folder:N.join("/"),leaf:S,description:w.proposedDescription??"",providerConfigId:s.find(C=>C.provider==="local_encrypted"&&C.isDefault)?.id??"",cascade:!!w.secretProposalId})},[s]),y=(0,m.useCallback)(w=>{p(null),u(""),c(w)},[]),k=(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)(Mut,{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)(Dut,{proposal:l,reason:d,error:h,pending:g.isPending,onReasonChange:u,onCancel:r(()=>{c(null),u(""),p(null)},"onCancel"),onConfirm:r(()=>l&&g.mutate({proposal:l,reason:d}),"onConfirm")})]});return{requestApprove:v,requestReject:y,isBusy:x.isPending||g.isPending,dialogs:k}}r(z_e,"useProposalReview");function Mut({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)(Ws,{className:"sm:max-w-lg",children:e?(0,t.jsxs)(t.Fragment,{children:[(0,t.jsxs)(ln,{children:[(0,t.jsx)(Qs,{children:c?"Approve & create secret":"Approve binding"}),(0,t.jsx)(mn,{children:c?"The value is created as the proposing agent recorded it. Re-folder or rename it before it lands.":"Grant the target agent access to this secret. This runs with your permissions."})]}),(0,t.jsxs)("div",{className:"space-y-1.5 rounded-md border border-border bg-muted/30 p-2.5 text-xs",children:[(0,t.jsxs)("div",{className:"flex items-center gap-1.5 text-muted-foreground",children:[(0,t.jsx)("span",{children:"Proposed by"}),(0,t.jsx)(N5,{agent:e.proposal.proposedBy,className:"font-medium text-foreground"})]}),(0,t.jsx)(IV,{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)(Ds,{htmlFor:"approve-folder",children:"Folder"}),(0,t.jsx)(dt,{id:"approve-folder",value:e.folder,onChange:r(p=>i({...e,folder:p.target.value}),"onChange"),placeholder:"dev/github",className:"font-mono text-xs"})]}),(0,t.jsxs)("div",{className:"space-y-1",children:[(0,t.jsx)(Ds,{htmlFor:"approve-name",children:"Name"}),(0,t.jsx)(dt,{id:"approve-name",value:e.leaf,onChange:r(p=>i({...e,leaf:p.target.value}),"onChange"),placeholder:"client-secret",autoFocus:!0,"aria-invalid":!e.leaf.trim(),className:"font-mono text-xs"})]})]}),(0,t.jsxs)("p",{className:"text-(length:--text-micro) text-muted-foreground",children:["Lands as"," ",d?(0,t.jsx)(k5,{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)(Ds,{htmlFor:"approve-description",children:"Description"}),(0,t.jsx)(dt,{id:"approve-description",value:e.description,onChange:r(p=>i({...e,description:p.target.value}),"onChange"),placeholder:"Optional"})]}),u.length>0?(0,t.jsxs)("div",{className:"space-y-1",children:[(0,t.jsx)(Ds,{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)(F_e,{fingerprint:e.proposal.valueFingerprintSha256,length:e.proposal.valueLength})})]}):(0,t.jsx)(Put,{draft:e,onChange:i}),s?(0,t.jsx)("p",{className:"text-xs text-destructive",role:"alert",children:s}):null,(0,t.jsxs)(cr,{children:[(0,t.jsx)($,{variant:"ghost",onClick:o,disabled:n,children:"Cancel"}),(0,t.jsx)($,{onClick:l,disabled:n||!h,children:n?"Approving…":c?"Approve & create":e.cascade?"Approve secret & bind":"Approve binding"})]})]}):null})})}r(Mut,"ApproveDialog");function Put({draft:e,onChange:s}){const{proposal:n}=e,a=EV(n),i=IM(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)(N5,{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)(TV,{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)(Ni,{className:"size-3.5 text-muted-foreground"}),(0,t.jsx)("span",{className:"font-medium",children:a.name}),a.pending?(0,t.jsx)(RV,{}):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)(ri,{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(Put,"BindingApproveBody");function Dut({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)(Ws,{className:"sm:max-w-md",children:e?(0,t.jsxs)(t.Fragment,{children:[(0,t.jsxs)(ln,{children:[(0,t.jsx)(Qs,{children:"Reject proposal"}),(0,t.jsxs)(mn,{children:["The reason is sent back to"," ",(0,t.jsx)(N5,{agent:e.proposedBy,className:"text-foreground"}),". Dependent bindings are rejected too."]})]}),(0,t.jsxs)("div",{className:"space-y-1",children:[(0,t.jsx)(Ds,{htmlFor:"reject-reason",children:"Reason"}),(0,t.jsx)(Qn,{id:"reject-reason",value:s,onChange:r(d=>i(d.target.value),"onChange"),rows:3,autoFocus:!0,placeholder:"Why is this being rejected?"})]}),n?(0,t.jsx)("p",{className:"text-xs text-destructive",role:"alert",children:n}):null,(0,t.jsxs)(cr,{children:[(0,t.jsx)($,{variant:"ghost",onClick:o,disabled:a,children:"Cancel"}),(0,t.jsx)($,{variant:"destructive",onClick:l,disabled:a||!c,children:a?"Rejecting…":"Reject"})]})]}):null})})}r(Dut,"RejectDialog");function q_e({proposal:e,onApprove:s,onReject:n,disabled:a,size:i="sm"}){const o=!e.viewerCanApprove,l=i==="xs"?"h-7 px-2 text-xs":"",c=(0,t.jsx)($,{size:"sm",className:l,disabled:a||o,onClick:r(()=>s(e),"onClick"),children:"Approve"});return(0,t.jsxs)("div",{className:"flex items-center gap-1.5",children:[o?(0,t.jsx)(Yc,{children:(0,t.jsxs)(Bn,{children:[(0,t.jsx)(On,{asChild:!0,children:(0,t.jsx)("span",{tabIndex:0,children:c})}),(0,t.jsx)($n,{className:"max-w-72",children:e.approveBlockReason??"You don’t have permission to approve this."})]})}):c,(0,t.jsx)($,{size:"sm",variant:"outline",className:l,disabled:a,onClick:r(()=>n(e),"onClick"),children:"Reject"})]})}r(q_e,"ProposalActions");function U_e(e){return typeof e!="object"||e===null||Array.isArray(e)?null:e}r(U_e,"asRecord$16");function K_e(e){const s=U_e(e);if(!s||s.type!=="secret_ref")return null;const n=typeof s.secretId=="string"?s.secretId:"";return n?{secretId:n,version:typeof s.version=="number"?s.version:"latest"}:null}r(K_e,"readSecretRef");function $ut(e){const s=U_e(e?.env);if(!s)return[];const n=[];for(const[a,i]of Object.entries(s)){const o=K_e(i);o&&n.push({name:a,...o})}return n}r($ut,"parseEnvSecretRefs");function Out(e){if(!e)return[];const s=[];for(const[n,a]of Object.entries(e)){if(!n.startsWith("access."))continue;const i=K_e(a);i&&s.push({name:n.slice(tA.length),...i})}return s}r(Out,"parseAccessGrants");function But(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(But,"summarizeAgentBindings");var rae=0;function Q_e(){return rae+=1,`access-row-${rae}`}r(Q_e,"nextAccessRowId");function uD(e){return e.map(s=>({id:Q_e(),alias:s.name,secretId:s.secretId,version:s.version}))}r(uD,"entriesToRows");function aae(e){const s={};for(const n of e){const a=n.alias.trim();!a||!$z.test(a)||!n.secretId||(s[a]={type:"secret_ref",secretId:n.secretId,version:n.version})}return s}r(aae,"rowsToAccessMap");function iae(e){return JSON.stringify(Object.keys(e).sort().map(s=>{const n=e[s];return[s,n.secretId,n.version??"latest"]}))}r(iae,"normalizeAccessMapKey");function oae({mode:e}){return e==="env"?(0,t.jsxs)(it,{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)(gke,{className:"size-3"})," Env var"]}):(0,t.jsxs)(it,{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)(q8,{className:"size-3"})," API access"]})}r(oae,"DeliveryBadge");function Fut({config:e,secrets:s,onChange:n,onCreateSecret:a,disabled:i,proposals:o,onApproveProposal:l,onRejectProposal:c}){const d=(0,m.useMemo)(()=>(o??[]).filter(O=>O.kind==="binding"),[o]),u=(0,m.useMemo)(()=>$ut(e),[e]),h=(0,m.useMemo)(()=>Out(e),[e]),p=(0,m.useMemo)(()=>But(u,h),[u,h]),f=(0,m.useMemo)(()=>aae(uD(h)),[h]),x=(0,m.useMemo)(()=>iae(f),[f]),[g,v]=(0,m.useState)(()=>uD(h)),[y,k]=(0,m.useState)(null),w=(0,m.useRef)(new Map),N=(0,m.useRef)(x),S=(0,m.useRef)(x);(0,m.useEffect)(()=>{x!==S.current&&(S.current=x,x!==N.current&&v(uD(h)))},[x,h]);const C=r(O=>s.find(P=>P.id===O)?.name??`${O.slice(0,8)}…`,"secretName");function _(O){v(O);const P=aae(O);N.current=iae(P),n(P)}r(_,"emit");function R(O,P){_(g.map(Q=>Q.id===O?{...Q,...P}:Q))}r(R,"patchRow");function I(O){_(g.filter(P=>P.id!==O))}r(I,"removeRow");function T(){v(O=>[...O,{id:Q_e(),alias:"",secretId:"",version:"latest"}])}r(T,"addRow");const E=(0,m.useMemo)(()=>{const O=new Map;for(const P of g){const Q=P.alias.trim();Q&&O.set(Q,(O.get(Q)??0)+1)}return O},[g]),L=p.length>0;return(0,t.jsxs)("div",{className:"space-y-3",children:[L?(0,t.jsx)("div",{className:"space-y-1.5",children:p.map(O=>(0,t.jsxs)("div",{className:"flex flex-wrap items-center gap-x-2 gap-y-1 rounded-md border border-border bg-muted/30 px-2.5 py-1.5 text-xs",children:[(0,t.jsx)(Ni,{className:"size-3.5 shrink-0 text-muted-foreground"}),(0,t.jsx)("span",{className:"font-medium",children:C(O.secretId)}),O.envKeys.length>0?(0,t.jsx)(oae,{mode:"env"}):null,O.apiAliases.length>0?(0,t.jsx)(oae,{mode:"api"}):null,(0,t.jsx)("span",{className:"min-w-0 truncate font-mono text-(length:--text-micro) text-muted-foreground",children:[...O.envKeys.map(P=>`${Cut}${P}`),...O.apiAliases.map(P=>`${tA}${P}`)].join(" · ")})]},O.secretId))}):(0,t.jsx)("p",{className:"text-sm text-muted-foreground",children:"No secrets are bound to this agent yet."}),d.length>0&&l&&c?(0,t.jsxs)("div",{className:"space-y-2",children:[(0,t.jsx)("div",{className:"text-(length:--text-micro) font-medium uppercase tracking-wide text-muted-foreground",children:"Proposed access"}),d.map(O=>{const P=EV(O),Q=IM(O);return(0,t.jsxs)("div",{className:"flex flex-col gap-2 rounded-md border border-amber-500/30 bg-amber-500/5 px-2.5 py-2 text-xs sm:flex-row sm:items-center",children:[(0,t.jsxs)("div",{className:"min-w-0 flex-1 space-y-1",children:[(0,t.jsxs)("div",{className:"flex min-w-0 flex-wrap items-center gap-1.5",children:[(0,t.jsx)(TV,{configPath:O.configPath}),(0,t.jsx)("code",{className:"font-mono",children:Q||O.configPath}),(0,t.jsx)("span",{className:"text-muted-foreground",children:"→"}),(0,t.jsx)(Ni,{className:"size-3 text-muted-foreground"}),(0,t.jsx)("span",{className:"font-medium",children:P.name}),P.pending?(0,t.jsx)(RV,{}):null]}),(0,t.jsxs)("p",{className:"flex flex-wrap items-center gap-1 text-muted-foreground",children:[(0,t.jsxs)("span",{children:["proposed by ",O.proposedBy.name]}),(0,t.jsx)("span",{"aria-hidden":"true",children:"·"}),(0,t.jsxs)("span",{className:"truncate italic",children:["“",O.justification,"”"]})]})]}),(0,t.jsx)(q_e,{proposal:O,onApprove:l,onReject:c,disabled:i,size:"xs"})]},O.id)})]}):null,(0,t.jsxs)("div",{className:"space-y-2",children:[(0,t.jsx)("div",{className:"text-(length:--text-micro) font-medium uppercase tracking-wide text-muted-foreground",children:"API access (no env var)"}),g.length>0?(0,t.jsx)("div",{className:"space-y-2",children:g.map(O=>{const P=O.alias.trim(),Q=!!P&&!$z.test(P),D=!!P&&(E.get(P)??0)>1,F=s.find(z=>z.id===O.secretId)??null;return(0,t.jsxs)("div",{className:"space-y-1",children:[(0,t.jsxs)("div",{className:"grid grid-cols-(--gtc-65) items-start gap-1.5",children:[(0,t.jsx)("div",{children:(0,t.jsx)(dt,{value:O.alias,onChange:r(z=>R(O.id,{alias:z.target.value}),"onChange"),onBlur:r(z=>{const K=z.target.value.trim();if(K&&!$z.test(K)){const U=f_(K);U&&U!==K&&R(O.id,{alias:U})}},"onBlur"),placeholder:"ALIAS","aria-label":"Access alias",disabled:i,className:W("h-9 font-mono text-sm",(Q||D)&&"border-destructive text-destructive")})}),(0,t.jsxs)("div",{className:"flex min-w-0 items-start gap-1.5",children:[(0,t.jsxs)(dr,{open:y?.rowId===O.id,onOpenChange:r(z=>{!z&&y?.rowId===O.id&&k(null)},"onOpenChange"),children:[(0,t.jsx)(iF,{asChild:!0,children:(0,t.jsx)("div",{ref:r(z=>{z?w.current.set(O.id,z):w.current.delete(O.id)},"ref"),className:"min-w-0 flex-1",children:(0,t.jsx)(AV,{secretId:O.secretId,secrets:s,onSelect:r(z=>R(O.id,{secretId:z,version:"latest",alias:!O.alias.trim()&&z?f_(C(z)):O.alias}),"onSelect"),onCreateNew:a?z=>{window.setTimeout(()=>{k({rowId:O.id,name:TE(z)||z.trim()})},0)}:void 0,disabled:i,triggerClassName:"h-9 min-h-9"})})}),(0,t.jsx)(sr,{align:"start",className:"w-auto p-3",onInteractOutside:r(z=>{const K=z.detail.originalEvent.target;K&&w.current.get(O.id)?.contains(K)&&z.preventDefault()},"onInteractOutside"),children:y?.rowId===O.id&&a?(0,t.jsx)(M_e,{initialName:y.name,initialValue:"",existingSecretNames:s.map(z=>z.name),onCancel:r(()=>k(null),"onCancel"),onSubmit:r(async(z,K)=>{const U=await a(z,K);R(O.id,{secretId:U.id,version:"latest",alias:O.alias.trim()||f_(U.name)}),k(null)},"onSubmit")}):null})]}),(0,t.jsxs)("select",{className:"h-9 shrink-0 rounded-md border border-border bg-background px-2 text-xs outline-none disabled:cursor-not-allowed disabled:opacity-60",value:O.version===void 0?"latest":String(O.version),onChange:r(z=>{const K=z.target.value;R(O.id,{version:K==="latest"?"latest":Number.parseInt(K,10)})},"onChange"),disabled:i||!F,"aria-label":"Version",children:[(0,t.jsx)("option",{value:"latest",children:"latest"}),F?Array.from({length:Math.max(0,F.latestVersion)},(z,K)=>{const U=F.latestVersion-K;return U<=0?null:(0,t.jsxs)("option",{value:U,children:["v",U]},U)}):null]})]}),(0,t.jsx)("button",{type:"button",onClick:r(()=>I(O.id),"onClick"),disabled:i,"aria-label":"Remove API access",className:"mt-1 inline-flex size-7 shrink-0 items-center justify-center rounded-md text-muted-foreground transition-colors hover:bg-accent hover:text-foreground disabled:pointer-events-none disabled:opacity-50",children:(0,t.jsx)(ha,{className:"size-3.5"})})]}),Q?(0,t.jsx)("p",{className:"pl-0.5 text-(length:--text-micro) text-destructive",children:"Invalid alias — use letters, digits and _"}):D?(0,t.jsx)("p",{className:"pl-0.5 text-(length:--text-micro) text-destructive",children:"Duplicate alias"}):null]},O.id)})}):null,(0,t.jsxs)("button",{type:"button",onClick:T,disabled:i,className:"inline-flex items-center gap-1 rounded-md px-2 py-1 text-xs font-medium text-muted-foreground transition-colors hover:bg-accent hover:text-foreground disabled:pointer-events-none disabled:opacity-50",children:[(0,t.jsx)(gn,{className:"size-3.5"}),"Add API access"]})]}),(0,t.jsxs)("p",{className:"text-(length:--text-micro) text-muted-foreground/70",children:[_ut("api")," The agent reads them by alias through ",(0,t.jsx)("code",{children:"GET /agents/me/secrets"}),"."]})]})}r(Fut,"AgentSecretAccessEditor");function zut(e){if(typeof e!="string")return null;const s=e.trim();return s.length>0?s:null}r(zut,"asNonEmptyString$3");function qut(e){return zut(e)!==null}r(qut,"hasLegacyWorkingDirectory");function Uut(e){return e.isCreate?!1:qut(e.adapterConfig?.cwd)}r(Uut,"shouldShowLegacyWorkingDirectoryField");var W_e=new Set;function Kut(e){return W_e.has(e)}r(Kut,"isAdapterTypeHidden");function Qut(e){W_e=new Set(e)}r(Qut,"setDisabledAdapterTypes");function Wut(e){return!Gm(e).hideFromVisualSelection}r(Wut,"isVisualAdapterChoice");function H_e(e,s=CV()){const n=e??wf;return s.map(a=>({value:a.type,label:n(a.type),comingSoon:!!Gm(a.type).comingSoon,hidden:Kut(a.type),experimental:!!Gm(a.type).experimental}))}r(H_e,"listAdapterOptions");function V_e(e={}){const s=e.enabled??!0,{data:n}=te({queryKey:M.adapters.all,queryFn:r(()=>Ph.list(),"queryFn"),enabled:s,staleTime:3e5});return n&&Wdt(n.filter(a=>a.source==="external").map(a=>({type:a.type,label:a.label,disabled:a.disabled,overrideDisabled:a.overridePaused}))),(0,m.useEffect)(()=>{n&&Qut(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(V_e,"useDisabledAdaptersSync");function Hut(e={}){const s=e.enabled??!0,{data:n}=te({queryKey:M.adapters.all,queryFn:r(()=>Ph.list(),"queryFn"),enabled:s,staleTime:3e5});return n!==void 0}r(Hut,"useAdapterRegistryLoaded");function RE(e){return Object.fromEntries(Object.entries(e).filter(([,s])=>s!==void 0))}r(RE,"omitUndefinedEntries");function MI(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=RE(s.adapterType!==void 0?{...Object.fromEntries(POe.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=RE({...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(MI,"buildAgentUpdatePatch");var Vut="kubernetes";function Gut(e){return e.driver!=="sandbox"?!1:e.config?.provider===Vut}r(Gut,"isKubernetesSandboxEnvironment");function LV(e,s){return e!=="kubernetes"?{forced:!1,kubernetesEnvironment:null}:{forced:!0,kubernetesEnvironment:s.find(n=>Gut(n))??null}}r(LV,"resolveForcedKubernetesEnvironment");var mD={identity:{},adapterConfig:{},heartbeat:{},debug:{},runtime:{}},M2={};function Yut(e){return e==="claude_local"||e==="codex_local"||e==="paperclip_runner"||e==="opencode_local"}r(Yut,"supportsAdapterModelRefresh");function Zut(e,s){return BCe(e,s).model}r(Zut,"resolvePaperclipRunnerTransitionModel");function lae(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(lae,"isOverlayDirty");function Oz(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)=>Oz(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&&Oz(o,a[i]))}return!1}r(Oz,"overlayValuesEqual");function Jut(e,s){const n=r((a,i)=>Object.fromEntries(Object.entries(a).filter(([o,l])=>!(o in i)||!Oz(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(Jut,"subtractPersistedOverlay");var kh="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 Xut(e){return e.split(",").map(s=>s.trim()).filter(Boolean)}r(Xut,"parseCommaArgs");function emt(e){return Array.isArray(e)?e.filter(s=>typeof s=="string").join(", "):typeof e=="string"?e:""}r(emt,"formatArgList");var tmt=[{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"}],smt=[{id:"",label:"Auto"},{id:"plan",label:"Plan"},{id:"ask",label:"Ask"}],nmt=[{id:"",label:"Auto"},{id:"low",label:"Low"},{id:"medium",label:"Medium"},{id:"high",label:"High"}],rmt=[{id:"",label:"Auto"},{id:"low",label:"Low"},{id:"high",label:"High"},{id:"max",label:"Max"}],amt=2,cae=10,imt=1,G_e=300;function yR(e,s,n){return Math.max(s,Math.min(n,Math.floor(e)))}r(yR,"clampInteger");function omt(e){return yR(e,0,G_e)*1e3}r(omt,"clampDelayMsFromSeconds");function lmt({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(lmt,"ConfigSections");function Y_e(e){const{mode:s,adapterModels:n}=e,a=s==="create",i=e.sectionLayout==="cards",o=e.showAdapterTypeField??!0,l=e.showAdapterTestEnvironmentButton??!0,c=l&&!e.onTestActionChange&&!e.compactTestFeedback,d=!e.onTestFeedbackChange,u=e.showCreateRunPolicySection??!0,h=e.hideInstructionsFile??!1,p=e.canConfigureProviderTrace===!0,{selectedCompanyId:f}=ps(),x=kt(),g=(0,m.useRef)(null),v=V_e(),{data:y=[]}=te({queryKey:f?M.secrets.list(f):["secrets","none"],queryFn:r(()=>Tr.list(f),"queryFn"),enabled:!!f}),{data:k=[]}=te({queryKey:f?M.secrets.userDefinitions(f):["user-secret-definitions","none"],queryFn:r(()=>Tr.listUserSecretDefinitions(f),"queryFn"),enabled:!!f,retry:!1}),w=a?null:e.agent.id,{data:N=[]}=te({queryKey:f?M.secrets.proposals(f,"pending"):["secret-proposals","none"],queryFn:r(()=>Tr.listProposals(f,"pending"),"queryFn"),enabled:!!f&&!a,retry:!1}),S=(0,m.useMemo)(()=>N.filter(mt=>mt.kind==="binding"&&mt.target?.id===w),[N,w]),C=z_e(f,[]),{data:_}=te({queryKey:M.instance.experimentalSettings,queryFn:r(()=>jr.getExperimental(),"queryFn"),retry:!1}),R=(0,m.useMemo)(()=>{const mt=new Set(v);return _?.enableNativeRunner!==!0&&mt.add("paperclip_runner"),(_?.enableOpenAiDot!==!0||v.has("paperclip_runner"))&&mt.add("openai_dot"),mt},[v,_?.enableNativeRunner,_?.enableOpenAiDot]),I=_?.enableEnvironments===!0,T=_?.enableManagedSandboxOnly===!0,E=_===void 0||T,{data:L}=te({queryKey:M.instance.generalSettings,queryFn:r(()=>jr.getGeneral(),"queryFn"),retry:!1}),{data:O}=te({queryKey:M.instance.settings,queryFn:r(()=>jr.get(),"queryFn"),retry:!1}),{data:P=[]}=te({queryKey:f?M.environments.list(f):["environments","none"],queryFn:r(()=>Fi.list(f),"queryFn"),enabled:!!f&&(I||L?.executionMode==="kubernetes")}),{forced:Q,kubernetesEnvironment:D}=(0,m.useMemo)(()=>LV(L?.executionMode,P),[L?.executionMode,P]),F=je({mutationFn:r(mt=>{if(!f)throw new Error("Select an organization to create secrets");return Tr.create(f,mt)},"mutationFn"),onSuccess:r(()=>{f&&x.invalidateQueries({queryKey:M.secrets.list(f)})},"onSuccess")}),z=je({mutationFn:r(async({file:mt,namespace:As})=>{if(!f)throw new Error("Select an organization to upload images");return fv.uploadImage(f,mt,As)},"mutationFn")}),[K,U]=(0,m.useState)(mD),[q,G]=(0,m.useState)(!1),[se,Z]=(0,m.useState)(0),ie=(0,m.useRef)(null),J=(0,m.useRef)(null),re=(0,m.useRef)(!1);(0,m.useEffect)(()=>{if(!a){if(ie.current!==null&&e.agent!==ie.current&&!re.current){const mt=J.current;J.current=null,U(As=>mt?Jut(As,mt):{...mD})}ie.current=e.agent}},[a,a?void 0:e.agent]);const oe=!a&&(lae(K)||q);function V(mt,As,pn){const Cn=K[mt];return As in Cn?Cn[As]:pn}r(V,"eff");function X(mt,As,pn){U(Cn=>({...Cn,[mt]:{...Cn[mt],[As]:pn}}))}r(X,"mark");function Y(){return g.current?.flushPendingDraft()??null}r(Y,"flushEnvironmentDraft");const ae=(0,m.useCallback)(mt=>{a||U(As=>{const pn={...e.agent.adapterConfig??{},...As.adapterConfig},Cn={...As.adapterConfig};for(const[pr,Nr]of Object.entries(mt))Cn[`${tA}${pr}`]=Nr;for(const pr of Object.keys(pn))pr.startsWith("access.")&&(pr.slice(7)in mt||(Cn[pr]=void 0));return{...As,adapterConfig:Cn}})},[a,a?void 0:e.agent]),ne=(0,m.useCallback)(()=>{U({...mD}),G(!1),Z(mt=>mt+1)},[]),ce=(0,m.useCallback)(async()=>{if(a)return;const mt=Y(),As=mt?{...K,adapterConfig:{...K.adapterConfig,env:mt}}:K;lae(As)&&await e.onSave(MI(e.agent,As))},[a,oe,K,e]);(0,m.useEffect)(()=>{a||(e.onDirtyChange?.(oe),e.onSaveActionChange?.(ce),e.onCancelActionChange?.(ne))},[a,oe,e.onDirtyChange,e.onSaveActionChange,e.onCancelActionChange,ce,ne]),(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??{},pe=a?{}:e.agent.runtimeConfig??{},ge=a?{}:pe.heartbeat??{},Ee=a?{}:pe.debug??{},de=a?e.values.adapterType:K.adapterType??e.agent.adapterType,Ne=Xj(),le=Ne(de),Le=de==="paperclip_runner"&&(a?e.values.adapterSchemaValues?.provider:V("adapterConfig","provider",he.provider))==="openai_dot",Ie=!Le&&(le.supportsInstructionsBundle||le.supportsSkills||le.supportsLocalAgentJwt),ye=Ie&&!E&&Uut({isCreate:a,adapterConfig:he}),Ae=(0,m.useMemo)(()=>RS(de),[de]),Qe=(0,m.useMemo)(()=>new Set(QUe(de)),[de]),ue=a?e.values:null,Be=a?mt=>e.onChange(mt):null;a&&ue.claudeStoredSessionId;const ft=r(()=>{f&&x.invalidateQueries({queryKey:M.secrets.userDefinitions(f)})},"invalidateUserSecretDefinitions"),gt=r(mt=>{if(!a||!Be)return;const As=ue.envBindings??{};Be({envBindings:{...As,...nk()},claudeStoredSessionId:mt}),ft()},"handleClaudeLoginStored"),Xe=r(async()=>{if(a)return;const mt={...Y()??V("adapterConfig","env",he.env??M2),...nk()},As={...K,adapterConfig:{...K.adapterConfig,env:mt}};U(As),await e.onSave({...MI(e.agent,As),applyStoredClaudeLogin:!0}),ft()},"handleClaudeLoginStoredEdit"),Fe=r(async mt=>{if(a||!mt.companyIdentityDiffers)return;const As={...Y()??V("adapterConfig","env",he.env??M2),CODEX_HOME:{type:"secret_ref",secretId:mt.secretId,version:"latest"}},pn={...K,adapterConfig:{...K.adapterConfig,env:As}};U(pn),J.current=pn,re.current=!0;try{await e.onSave(MI(e.agent,pn))}catch(Cn){throw J.current=null,Cn}finally{re.current=!1}ft()},"handleCodexAccountBindingEdit"),at=r(()=>{if(!a||!Be)return;const mt=ue.envBindings??{};Be({envBindings:{...mt,...nk()},claudeApplyStoredLogin:!0}),ft()},"handleApplyStoredClaudeLogin"),Tt=r(async()=>{if(a)return;const mt={...Y()??V("adapterConfig","env",he.env??M2),...nk()},As={...K,adapterConfig:{...K.adapterConfig,env:mt}};U(As),await e.onSave({...MI(e.agent,As),applyStoredClaudeLogin:!0}),ft()},"handleApplyStoredClaudeLoginEdit"),Dt=a?ue.defaultEnvironmentId??"":V("identity","defaultEnvironmentId",e.agent.defaultEnvironmentId??""),Ot=(0,m.useMemo)(()=>Dt?(P.find(mt=>mt.id===Dt)??null)?.driver==="local"?"":Dt:"",[P,Dt]),rt=(0,m.useMemo)(()=>P.find(mt=>mt.id===Ot)??null,[Ot,P]),Pe=(0,m.useMemo)(()=>{const mt=O?.defaultEnvironmentId??null;return mt?(P.find(As=>As.id===mt)??null)?.driver==="local"?"":mt:""},[P,O?.defaultEnvironmentId]),De=(0,m.useMemo)(()=>P.find(mt=>mt.id===Pe)??null,[P,Pe]),ht=(0,m.useMemo)(()=>{try{return wN({agentDefaultEnvironmentId:Dt||null,instanceDefaultEnvironmentId:O?.defaultEnvironmentId??null,localDefaultEnvironmentId:NN(P),managedSandboxOnly:_?.enableManagedSandboxOnly===!0,managedSandboxEnvironmentId:kN(P),visibleEnvironmentIds:P.map(mt=>mt.id)})}catch{return null}},[Dt,O?.defaultEnvironmentId,P,_?.enableManagedSandboxOnly]),Ft=(0,m.useMemo)(()=>P.find(mt=>mt.id===ht)??null,[P,ht]),{data:Et}=te({queryKey:f?M.environments.capabilities(f):["environment-capabilities","none"],queryFn:r(()=>Fi.capabilities(f),"queryFn"),enabled:!!f&&le.login!=null});(0,m.useEffect)(()=>{!a||!Be||!Q||!D||Ot!==D.id&&Be({defaultEnvironmentId:D.id})},[a,Be,Q,D,Ot]);const ct=(0,m.useMemo)(()=>P.filter(mt=>{if(!Qe.has(mt.driver)||mt.driver==="local")return!1;if(mt.driver!=="sandbox")return!0;const As=typeof mt.config?.provider=="string"?mt.config.provider:null;return As!==null&&As!=="fake"}),[P,Qe]),qe=(0,m.useMemo)(()=>!rt||ct.some(mt=>mt.id===rt.id)?ct:[...ct,rt],[rt,ct]),Oe=I&&(Q||Ot.length>0||ct.length>=1),Re=De?SN(De):T?"Paperclip Computer":"Local",Ve=de==="paperclip_runner"?String(a?e.values.adapterSchemaValues?.provider??"codex":V("adapterConfig","provider",he.provider==="acpx"&&he.acpxAgent==="codex"?"codex":he.provider??"codex")):void 0,xe=de==="opencode_local"&&nF.safeParse(K.runtime.runtimeConfig?.aiConnection??pe.aiConnection).data?.provider==="openrouter"?"openrouter":Ve,Ge=LCe(f,a?void 0:nF.safeParse(K.runtime.runtimeConfig?.aiConnection??pe.aiConnection).data,Jee(de,Ve,V("adapterConfig","acpxAgent",he.acpxAgent))),vt=f?M.agents.adapterModels(f,de,Ot||null,xe):["agents","none","adapter-models",de],{data:Ss,error:lt,isLoading:zs}=te({queryKey:vt,queryFn:r(()=>_t.adapterModels(f,de,{environmentId:Ot||null,provider:xe}),"queryFn"),enabled:!!f&&!Ge}),[We,fe]=(0,m.useState)(null),[Ye,bt]=(0,m.useState)(!1),Wt=Ge?.models??Ss??n??[],ut=Ge?Ge.error:lt,$t="command",{data:$e,refetch:pt}=te({queryKey:f?M.agents.detectModel(f,de):["agents","none","detect-model",de],queryFn:r(()=>{if(!f)throw new Error("Select an organization to detect the model");return _t.detectModel(f,de)},"queryFn"),enabled:!!(f&&Ie&&de!=="opencode_local"&&de!=="paperclip_runner")}),Gt=$e?.model??null;$e?.candidates;const{data:be=[]}=te({queryKey:f?M.agents.list(f):["agents","none","list"],queryFn:r(()=>_t.list(f),"queryFn"),enabled:!!(!a&&f)}),fs={companyId:f??void 0,agentId:a?void 0:e.agent.id,mode:s,isCreate:a,adapterType:de,values:a?e.values:null,set:a?mt=>e.onChange(mt):null,config:he,eff:V,mark:X,models:Wt,hideInstructionsFile:h||E||Le,managedSandboxOnly:E||Le,openAiDotEnabled:_?.enableOpenAiDot===!0},[vn,Ls]=(0,m.useState)(!1),[Bs,kr]=(0,m.useState)(!1),ds=vV(de),os=r(mt=>(0,t.jsxs)(t.Fragment,{children:[de==="claude_local"&&(0,t.jsx)(Sot,{...fs,section:mt}),(0,t.jsx)(Ae.ConfigFields,{...fs,section:mt,hideModel:Ie})]}),"renderAdapterFields"),[Se,St]=(0,m.useState)(!1),[ze,At]=(0,m.useState)(!1);function Ut(mt){if(a){const pn=Ae.buildAdapterConfig(ue);return mt&&Object.assign(pn,mt),RE(pn)}const As={...he,...K.adapterConfig};return mt&&Object.assign(As,mt),RE(As)}r(Ut,"buildAdapterConfigForTest");const It=je({mutationFn:r(async()=>{if(!f)throw new Error("Select an organization to test adapter environment");const mt=Y(),As=mt?{env:mt}:void 0;let pn=O,Cn=P,pr=_?.enableManagedSandboxOnly===!0;if(!Dt)try{const[an,_r,Jn]=await Promise.all([x.ensureQueryData({queryKey:M.instance.settings,queryFn:r(()=>jr.get(),"queryFn")}),x.ensureQueryData({queryKey:M.environments.list(f),queryFn:r(()=>Fi.list(f),"queryFn")}),x.ensureQueryData({queryKey:M.instance.experimentalSettings,queryFn:r(()=>jr.getExperimental(),"queryFn")})]);pn=an,Cn=_r,pr=Jn?.enableManagedSandboxOnly===!0}catch{throw new Error("Could not load environment settings to determine which environment to test in. Retry the test.")}const Nr=wN({agentDefaultEnvironmentId:Dt||null,instanceDefaultEnvironmentId:pn?.defaultEnvironmentId??null,localDefaultEnvironmentId:NN(Cn),managedSandboxOnly:pr,managedSandboxEnvironmentId:kN(Cn),visibleEnvironmentIds:Cn.map(an=>an.id)}),mr=Ut(As),Ra=a?void 0:e.agent.id,vs=a?void 0:$ee.safeParse(K.runtime.runtimeConfig?.aiConnection??e.agent.runtimeConfig.aiConnection).data;if(e.compactTestFeedback){const an=de==="paperclip_runner"?mr.provider==="codex"?"codex_local":mr.provider==="acpx"&&mr.acpxAgent==="grok"?"grok_local":mr.provider==="acpx"&&mr.acpxAgent==="claude"?"claude_local":de:de;return MCe({companyId:f,adapterType:de,providerAdapter:an,adapterConfig:mr,agentId:Ra,aiConnection:vs,environmentId:Nr})}return _t.testEnvironment(f,de,{adapterConfig:mr,agentId:Ra,aiConnection:vs,environmentId:Nr})},"mutationFn")}),[rs,bs]=(0,m.useState)(!1),[$s,Os]=(0,m.useState)(null),Tn="Test",ks=!a&&!!e.isSaving,Hn=rs||ks||!f,Jt=(0,m.useRef)(It.reset);Jt.current=It.reset;const Vs=(0,m.useRef)(()=>{});Vs.current=()=>{if(!a||!Be)return;const mt=ue.envBindings??{},As=ue.claudeStoredSessionId!=null||ue.claudeApplyStoredLogin===!0,pn=Jre in mt;if(!As&&!pn)return;const Cn={...mt};delete Cn[Jre],Be({envBindings:Cn,claudeStoredSessionId:null,claudeApplyStoredLogin:!1})},(0,m.useEffect)(()=>{Jt.current(),Os(null),Vs.current()},[de,ht]);const Nn=le.login!=null,Pt=It.data,Xt=Pt!=null&&Ne(Pt.adapterType).login!=null,Zs=Pt&&Xt?Pt.checks.find(mt=>mt.code==="adapter_auth_missing")??null:null,Ns=typeof Ft?.config?.provider=="string"?Ft.config.provider:null,Js=Ns!=null&&Et?.sandboxProviders?.[Ns]?.supportsLoginPty===!0,cn=le.login!=null,hr=(a||!(K.runtime.runtimeConfig?.aiConnection??pe.aiConnection))&&Nn&&Ft?.driver==="sandbox"&&!!ht&&!!f&&!!Zs&&(!cn||Js),Vn=(0,m.useCallback)(async()=>{if(!f)throw new Error("Select an organization to test adapter environment");bs(!0),Os(null),It.reset();try{return await It.mutateAsync()}catch(mt){throw Os(mt instanceof Error?mt.message:"Environment test failed"),mt}finally{bs(!1)}},[f,It]),Kr=(0,m.useRef)(()=>{});(0,m.useEffect)(()=>{Kr.current=()=>{Hn||Vn().catch(()=>{})}},[Vn,Hn]);const Er=(0,m.useCallback)(()=>{Kr.current()},[]);(0,m.useEffect)(()=>{if(!(!l||!e.onTestActionChange))return e.onTestActionChange(Er),()=>{e.onTestActionChange?.(null)}},[l,e.onTestActionChange,Er]),(0,m.useEffect)(()=>{if(!(!l||!e.onTestActionStateChange))return e.onTestActionStateChange({disabled:Hn,pending:rs}),()=>{e.onTestActionStateChange?.({disabled:!0,pending:!1})}},[l,e.onTestActionStateChange,Hn,rs]),(0,m.useEffect)(()=>{if(e.onTestFeedbackChange)return e.onTestFeedbackChange({errorMessage:$s??(It.error instanceof Error?It.error.message:It.error?"Environment test failed":null),result:It.data??null,login:hr&&f&&ht?{companyId:f,adapterType:de,environmentId:ht}:null}),()=>{e.onTestFeedbackChange?.({errorMessage:null,result:null,login:null})}},[e.onTestFeedbackChange,$s,It.data,It.error,hr,f,de,ht]);const Cr=a?ue.model??"":V("adapterConfig","model",String(he.model??"")),Ln=typeof Cr=="string"?Cr:"";async function ur(){if(f){bt(!0),fe(null);try{const mt=await _t.adapterModels(f,de,{refresh:!0,environmentId:Ot||null,provider:xe});x.setQueryData(vt,mt)}catch(mt){fe(mt instanceof Error?mt.message:"Failed to refresh adapter models.")}finally{bt(!1)}}}r(ur,"handleRefreshModels");const Or=de==="codex_local"?"modelReasoningEffort":de==="cursor"?"mode":de==="opencode_local"?"variant":de==="grok_local"?"reasoningEffort":de==="pi_local"||de==="omp_local"?"thinking":"effort",Qr=de==="codex_local"?fV(Ln,"Auto").map(mt=>({id:mt.value,label:mt.label})):de==="cursor"?smt:de==="opencode_local"?tmt:de==="kimi_local"?rmt:de==="pi_local"?[{id:"",label:"Auto"},...["off","minimal","low","medium","high","xhigh"].map(mt=>({id:mt,label:mt}))]:de==="claude_local"||de==="grok_local"?[{id:"",label:"Auto"},...NE(de,Ln).map(mt=>({id:mt,label:mt==="xhigh"?"X-High":mt[0].toUpperCase()+mt.slice(1)}))]:nmt,ea=de==="omp_local",or=a?ea?String(ue.adapterSchemaValues?.thinking??""):ue.thinkingEffort:de==="codex_local"?V("adapterConfig","modelReasoningEffort",String(he.modelReasoningEffort??he.reasoningEffort??"")):de==="cursor"?V("adapterConfig","mode",String(he.mode??"")):de==="opencode_local"?V("adapterConfig","variant",String(he.variant??"")):V("adapterConfig",Or,String(he[Or]??"")),Ir=de!=="gemini_local"&&de!=="cursor_cloud"&&de!=="paperclip_runner"&&!ea,xt=r(mt=>{if(a){Be(ea?{adapterSchemaValues:{...ue.adapterSchemaValues,thinking:mt??void 0}}:{thinkingEffort:mt??""});return}X("adapterConfig",Or,mt||void 0)},"setThinkingEffort"),Ze=de==="codex_local"?a?!!ue.search:V("adapterConfig","search",!!he.search):!1,es=(0,m.useMemo)(()=>{if(a)return{heartbeat:{enabled:ue.heartbeatEnabled,intervalSec:ue.intervalSec}};const mt={...pe.heartbeat&&typeof pe.heartbeat=="object"?pe.heartbeat:{},...K.heartbeat};return{...pe,heartbeat:mt}},[a,K.heartbeat,pe,ue]),ms=qee(es.heartbeat),Is=qee(ms.maxTurnContinuation),ss=OOe(Is.enabled,!0),ws=yR(Oee(Is.maxAttempts,amt),0,cae),yn=yR(Oee(Is.delayMs,imt*1e3)/1e3,0,G_e);function Rn(mt){X("heartbeat","maxTurnContinuation",{...Is,...mt})}r(Rn,"updateMaxTurnContinuation");const nr=(0,t.jsx)(Ij,{ref:g,onDirtyChange:G,hideDraftActions:!a&&e.hideInlineSave,value:a?ue.envBindings??M2:V("adapterConfig","env",he.env??M2),secrets:y,userSecretDefinitions:k,onCreateSecret:r(async(mt,As)=>await F.mutateAsync({name:mt,value:As}),"onCreateSecret"),onChange:r(mt=>a?Be({envBindings:mt??{},envVars:""}):X("adapterConfig","env",mt),"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)($,{size:"sm",onClick:ce,disabled:e.isSaving,children:e.isSaving?"Saving...":"Save"})]})}),e.environmentVariablesPlacement==="secrets"&&(0,t.jsxs)("div",{"data-config-section":"environment-variables",className:W(!i&&"border-b border-border"),children:[i?(0,t.jsx)("h3",{className:"mb-3 text-sm font-medium",children:"Environment variables"}):(0,t.jsx)("div",{className:"px-4 py-2 text-xs font-medium text-muted-foreground",children:"Environment variables"}),(0,t.jsx)("div",{className:W(i?"rounded-lg border border-border p-4":"px-4 pb-3"),children:nr})]}),(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:ji.secretAccess}),(0,t.jsx)(Fut,{config:{...he,...K.adapterConfig},secrets:y,onChange:ae,onCreateSecret:r((mt,As)=>F.mutateAsync({name:mt,value:As}),"onCreateSecret"),proposals:S,onApproveProposal:C.requestApprove,onRejectProposal:C.requestReject}),C.dialogs]})]})]}):(0,t.jsxs)(lmt,{order:e.sectionOrder,className:W("relative",i&&"space-y-6"),children:[oe&&!e.hideInlineSave&&(0,t.jsx)("div",{className:"sticky top-0 z-10 flex items-center justify-end px-4 py-2 bg-background/90 backdrop-blur-sm border-b border-primary/20",children:(0,t.jsxs)("div",{className:"flex items-center gap-3",children:[(0,t.jsx)("span",{className:"text-xs text-muted-foreground",children:"Unsaved changes"}),(0,t.jsx)($,{size:"sm",onClick:ce,disabled:!a&&e.isSaving,children:!a&&e.isSaving?"Saving...":"Save"})]})}),!a&&(0,t.jsxs)("div",{"data-config-section":"identity",className:W(!i&&"border-b border-border"),children:[i?(0,t.jsx)("h3",{className:"text-sm font-medium mb-3",children:e.sectionTitles?.identity??"Identity"}):(0,t.jsx)("div",{className:"px-4 py-2 text-xs font-medium text-muted-foreground",children:"Identity"}),(0,t.jsxs)("div",{className:W(i?"border border-border rounded-lg p-4 space-y-3":"px-4 pb-3 space-y-3"),children:[(0,t.jsx)(_s,{label:"Name",hint:ji.name,children:(0,t.jsx)(Ga,{value:V("identity","name",e.agent.name),onCommit:r(mt=>X("identity","name",mt),"onCommit"),immediate:!0,className:kh,placeholder:"Agent name"})}),(0,t.jsx)(_s,{label:"Title",hint:ji.title,children:(0,t.jsx)(Ga,{value:V("identity","title",e.agent.title??""),onCommit:r(mt=>X("identity","title",mt||null),"onCommit"),immediate:!0,className:kh,placeholder:"e.g. VP of Engineering"})}),(0,t.jsx)(_s,{label:"Reports to",hint:ji.reportsTo,children:(0,t.jsx)(Jdt,{agents:be,value:V("identity","reportsTo",e.agent.reportsTo??null),onChange:r(mt=>X("identity","reportsTo",mt),"onChange"),excludeAgentIds:[e.agent.id],chooseLabel:"Choose manager…"})}),Ie&&!e.hidePromptTemplate&&(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)(_s,{label:"Prompt Template",hint:ji.promptTemplate,children:(0,t.jsx)(Jc,{value:V("adapterConfig","promptTemplate",String(he.promptTemplate??"")),onChange:r(mt=>X("adapterConfig","promptTemplate",mt??""),"onChange"),placeholder:"You are agent {{ agent.name }}. Your role is {{ agent.role }}...",contentClassName:"min-h-(--sz-88px) text-sm font-mono",imageUploadHandler:r(async mt=>{const As=`agents/${e.agent.id}/prompt-template`;return(await z.mutateAsync({file:mt,namespace:As})).contentPath},"imageUploadHandler")})}),(0,t.jsx)("div",{className:"rounded-md border border-amber-500/25 bg-amber-500/10 px-3 py-2 text-xs text-amber-900 dark:text-amber-100",children:"Prompt template is replayed on every heartbeat. Keep it compact and dynamic to avoid recurring token cost and cache churn."})]})]})]}),Q?(0,t.jsxs)("div",{"data-config-section":"environment",className:W(!i&&(a?"border-t border-border":"border-b border-border")),children:[i?(0,t.jsx)("h3",{className:"text-sm font-medium mb-3",children:"Environment"}):(0,t.jsx)("div",{className:"px-4 py-2 text-xs font-medium text-muted-foreground",children:"Environment"}),(0,t.jsx)("div",{className:W(i?"border border-border rounded-lg p-4 space-y-3":"px-4 pb-3 space-y-3"),children:(0,t.jsx)(_s,{label:"Default environment",hint:"This instance runs all agents in the Kubernetes sandbox. Local execution is disabled.",children:D?(0,t.jsxs)("div",{className:W(kh,"flex items-center text-muted-foreground"),children:[D.name," · Kubernetes sandbox"]}):(0,t.jsx)("div",{className:"rounded-md border border-amber-500/25 bg-amber-500/10 px-3 py-2 text-xs text-amber-800 dark:text-amber-200",children:"This instance requires the Kubernetes sandbox, but no managed Kubernetes environment is available for this organization yet. Configure one before creating agents; execution will not fall back to local."})})})]}):Oe?(0,t.jsxs)("div",{"data-config-section":"environment",className:W(!i&&(a?"border-t border-border":"border-b border-border")),children:[i?(0,t.jsx)("h3",{className:"text-sm font-medium mb-3",children:"Environment"}):(0,t.jsx)("div",{className:"px-4 py-2 text-xs font-medium text-muted-foreground",children:"Environment"}),(0,t.jsx)("div",{className:W(i?"border border-border rounded-lg p-4 space-y-3":"px-4 pb-3 space-y-3"),children:(0,t.jsx)(_s,{label:"Environment override",children:(0,t.jsx)("div",{className:"space-y-2",children:(0,t.jsxs)("select",{className:kh,value:Ot,onChange:r(mt=>{const As=mt.target.value;if(a){Be({defaultEnvironmentId:As});return}X("identity","defaultEnvironmentId",As||null)},"onChange"),children:[(0,t.jsxs)("option",{value:"",children:["Default: ",Re]}),qe.map(mt=>(0,t.jsx)("option",{value:mt.id,children:SN(mt)},mt.id))]})})})})]}):null,(0,t.jsxs)("div",{"data-config-section":"adapter",className:W(!i&&(a?"border-t border-border":"border-b border-border")),children:[(0,t.jsxs)("div",{className:W(i?"flex items-center justify-between mb-3":"px-4 py-2 flex items-center justify-between gap-2"),children:[i?(0,t.jsx)("h3",{className:"text-sm font-medium",children:e.sectionTitles?.adapter??"Adapter"}):(0,t.jsx)("span",{className:"text-xs font-medium text-muted-foreground",children:"Adapter"}),c&&(0,t.jsx)($,{type:"button",variant:"outline",size:"sm",className:"h-7 px-2.5 text-xs",onClick:Er,disabled:Hn,children:rs?`${Tn}...`:Tn})]}),(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)(_s,{label:"Adapter type",hint:ji.adapterType,children:(0,t.jsx)(J_e,{value:Le?"openai_dot":de,disabledTypes:R,openAiDotEnabled:_?.enableOpenAiDot===!0,onChange:r(mt=>{const As=mt==="openai_dot",pn=As?"paperclip_runner":mt;if(a){const{adapterType:Cn,...pr}=Eb,Nr={...pr,adapterType:pn};pn==="codex_local"?Nr.dangerouslyBypassSandbox=!0:pn==="gemini_local"?Nr.model="auto":pn==="kimi_local"?Nr.model="kimi-code/kimi-for-coding":pn==="cursor"?Nr.model="auto":pn==="opencode_local"?Nr.model="openai/gpt-5.2-codex":pn==="paperclip_runner"&&(Nr.model=jN),As&&(Nr.model="",Nr.adapterSchemaValues={provider:"openai_dot"}),Be(Nr)}else U(Cn=>({...Cn,adapterType:pn,adapterConfig:{model:pn==="gemini_local"?"auto":pn==="kimi_local"?"kimi-code/kimi-for-coding":pn==="opencode_local"?"openai/gpt-5.2-codex":pn==="cursor"?"auto":As?"":pn==="paperclip_runner"?Zut(de,he.model):"",effort:"",modelReasoningEffort:"",variant:"",mode:"",...pn==="codex_local"?{dangerouslyBypassApprovalsAndSandbox:!0}:As?{provider:"openai_dot",lifecycleMode:"per_turn",allowUnmeteredProvider:!1,dotAttachmentAccess:!1,dotWorkspaceAccess:!1}:pn==="paperclip_runner"?{...BCe(de,V("adapterConfig","model",he.model))}:{}}}))},"onChange")})}),!Le&&!a&&f&&(0,t.jsx)(vz,{companyId:f,agentId:e.agent.id,agentName:e.agent.name,adapterType:Jee(de,V("adapterConfig","provider",he.provider),V("adapterConfig","acpxAgent",he.acpxAgent)),routerAdapterType:de,value:$ee.safeParse(K.runtime.runtimeConfig?.aiConnection??pe.aiConnection).data,model:String(V("adapterConfig","model",he.model)??""),environmentId:Ot||void 0,legacy:!0,onChange:r(mt=>X("runtime","runtimeConfig",{...pe,aiConnection:mt}),"onChange")}),d&&!e.compactTestFeedback&&($s||It.error)&&(0,t.jsx)("div",{className:"rounded-md border border-destructive/30 bg-destructive/10 px-3 py-2 text-xs text-destructive",children:$s??(It.error instanceof Error?It.error.message:"Environment test failed")}),d&&!e.compactTestFeedback&&It.data&&(0,t.jsx)(fmt,{result:It.data}),d&&hr&&(0,t.jsx)(MV,{companyId:f,adapterType:de,environmentId:ht,onStored:a?gt:Xe,onApplyStored:a?at:Tt,onAccountBinding:a?void 0:Fe},`${de}:${ht}`),ye&&(0,t.jsx)(_s,{label:"Working directory (deprecated)",hint:ji.cwd,children:(0,t.jsxs)("div",{className:"flex items-center gap-2 rounded-md border border-border px-2.5 py-1.5",children:[(0,t.jsx)(nl,{className:"h-3.5 w-3.5 text-muted-foreground shrink-0"}),(0,t.jsx)(Ga,{value:a?ue.cwd:V("adapterConfig","cwd",String(he.cwd??"")),onCommit:r(mt=>a?Be({cwd:mt}):X("adapterConfig","cwd",mt||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)(tu,{})]})}),os("adapter"),Ie&&(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)(PV,{models:Wt,loadingModels:Ge?.isLoading??zs,value:Ln,effort:ea?{value:or||null,onChange:xt}:void 0,onChange:r(mt=>{ea&&!yM(or,mt,Wt.map(Cn=>Tk(Cn,!1)))&&xt(null);const As=NE(de,mt),pn=["codex_local","claude_local","grok_local"].includes(de)&&!!or&&!As.includes(String(or));if(a){Be({model:mt,...pn?{thinkingEffort:""}:{}});return}X("adapterConfig","model",Ge?.resolveModel(mt)||mt||void 0),pn&&(X("adapterConfig",Or,void 0),X("adapterConfig","reasoningEffort",void 0))},"onChange"),open:Se,onOpenChange:St,defaultLabel:de==="claude_local"?"Default (claude-opus-5)":void 0,allowDefault:de!=="opencode_local"&&de!=="pi_local"&&de!=="paperclip_runner",required:de==="opencode_local"||de==="pi_local",groupByProvider:!Ge&&(de==="opencode_local"||de==="pi_local"),preserveOrder:!!Ge||gV(de),creatable:!0,detectedModel:Ge?void 0:Gt,detectedModelCandidates:[],onDetectModel:Ge||de==="opencode_local"||de==="paperclip_runner"?void 0:async()=>(await pt()).data?.model??null,onRefreshModels:Ge?Ge.refreshModels:Yut(de)?ur:void 0,refreshingModels:Ge?.refreshing??Ye,detectModelLabel:"Detect model",emptyDetectHint:"No model detected. Select or enter one manually."}),(We||ut)&&(0,t.jsx)("p",{className:"text-xs text-destructive",children:We??(ut instanceof Error?ut.message:"Failed to load adapter models.")}),de==="opencode_local"&&!Ge&&rt&&rt.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 ",rt.name,"."]}),Ir&&(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)(xmt,{value:or,options:Qr,onChange:r(mt=>a?Be({thinkingEffort:mt}):X("adapterConfig",Or,mt||void 0),"onChange"),open:ze,onOpenChange:At}),de==="codex_local"&&Ze&&or==="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)(_s,{label:"Bootstrap prompt (legacy)",hint:ji.bootstrapPrompt,children:(0,t.jsx)(Jc,{value:V("adapterConfig","bootstrapPromptTemplate",String(he.bootstrapPromptTemplate??"")),onChange:r(mt=>X("adapterConfig","bootstrapPromptTemplate",mt||void 0),"onChange"),placeholder:"Optional initial setup prompt for the first run",contentClassName:"min-h-(--sz-44px) text-sm font-mono",imageUploadHandler:r(async mt=>{const As=`agents/${e.agent.id}/bootstrap-prompt`;return(await z.mutateAsync({file:mt,namespace:As})).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."})]}),os("configuration"),(Ie||de==="process"||ds?.fields.some(mt=>kz(mt.key)==="advanced"))&&(0,t.jsx)(hR,{title:"Advanced",open:Bs,onToggle:r(()=>kr(!Bs),"onToggle"),children:(0,t.jsxs)("div",{className:"space-y-3",children:[Ie&&(0,t.jsxs)(t.Fragment,{children:[" ",!E&&(0,t.jsx)(_s,{label:"Command",hint:ji.localCommand,children:(0,t.jsx)(Ga,{value:a?ue.command:V("adapterConfig",$t,String(he.command??"")),onCommit:r(mt=>a?Be({command:mt}):X("adapterConfig",$t,mt||null),"onCommit"),immediate:!0,className:kh,placeholder:{claude_local:"claude",codex_local:"codex",gemini_local:"gemini",kimi_local:"kimi",pi_local:"pi",cursor:"agent",opencode_local:"opencode"}[de]??de.replace(/_local$/,"")})}),(0,t.jsx)(_s,{label:"Extra args (comma-separated)",hint:ji.extraArgs,children:(0,t.jsx)(Ga,{value:a?ue.extraArgs:V("adapterConfig","extraArgs",emt(he.extraArgs)),onCommit:r(mt=>a?Be({extraArgs:mt}):X("adapterConfig","extraArgs",mt?.trim()?Xut(mt):null),"onCommit"),className:kh,placeholder:"e.g. --verbose, --foo=bar"})})]}),os("advanced")]})})]})]}),e.environmentVariablesPlacement!=="secrets"&&(Ie||ds?.fields.some(mt=>kz(mt.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:Ie?nr:os("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)(jC,{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)(jC,{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)(Nre,{label:"Heartbeat on interval",hint:ji.heartbeatInterval,checked:ue.heartbeatEnabled,onCheckedChange:r(mt=>Be({heartbeatEnabled:mt}),"onCheckedChange"),number:ue.intervalSec,onNumberChange:r(mt=>Be({intervalSec:mt}),"onNumberChange"),numberLabel:"sec",numberPrefix:"Run heartbeat every",numberHint:ji.intervalSec,showNumber:ue.heartbeatEnabled}),(0,t.jsx)(hR,{title:"Advanced Run Policy",open:vn,onToggle:r(()=>Ls(!vn),"onToggle"),children:(0,t.jsx)("div",{className:"space-y-3",children:os("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)(jC,{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)(jC,{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)(Nre,{label:"Heartbeat on interval",hint:ji.heartbeatInterval,checked:V("heartbeat","enabled",ge.enabled===!0),onCheckedChange:r(mt=>X("heartbeat","enabled",mt),"onCheckedChange"),number:V("heartbeat","intervalSec",Number(ge.intervalSec??300)),onNumberChange:r(mt=>X("heartbeat","intervalSec",mt),"onNumberChange"),numberLabel:"sec",numberPrefix:"Run heartbeat every",numberHint:ji.intervalSec,showNumber:V("heartbeat","enabled",ge.enabled===!0)})}),(0,t.jsx)(hR,{title:"Advanced Run Policy",bordered:i,open:vn,onToggle:r(()=>Ls(!vn),"onToggle"),children:(0,t.jsxs)("div",{className:"space-y-3",children:[os("runPolicy"),Ie&&(0,t.jsx)(t.Fragment,{children:!a&&(0,t.jsxs)(t.Fragment,{children:[!ds?.fields.some(mt=>mt.key==="timeoutSec")&&(0,t.jsx)(_s,{label:"Timeout (sec)",hint:ji.timeoutSec,children:(0,t.jsx)(Qc,{value:V("adapterConfig","timeoutSec",Number(he.timeoutSec??0)),onCommit:r(mt=>X("adapterConfig","timeoutSec",mt),"onCommit"),immediate:!0,className:kh})}),!ds?.fields.some(mt=>mt.key==="graceSec")&&(0,t.jsx)(_s,{label:"Interrupt grace period (sec)",hint:ji.graceSec,children:(0,t.jsx)(Qc,{value:V("adapterConfig","graceSec",Number(he.graceSec??15)),onCommit:r(mt=>X("adapterConfig","graceSec",mt),"onCommit"),immediate:!0,className:kh})})]})}),(0,t.jsx)(yl,{label:"Wake on demand",hint:ji.wakeOnDemand,checked:V("heartbeat","wakeOnDemand",ge.wakeOnDemand!==!1),onChange:r(mt=>X("heartbeat","wakeOnDemand",mt),"onChange")}),(0,t.jsx)(_s,{label:"Cooldown (sec)",hint:ji.cooldownSec,children:(0,t.jsx)(Qc,{value:V("heartbeat","cooldownSec",Number(ge.cooldownSec??10)),onCommit:r(mt=>X("heartbeat","cooldownSec",mt),"onCommit"),immediate:!0,className:kh})}),(0,t.jsx)(_s,{label:"Max concurrent runs",hint:ji.maxConcurrentRuns,children:(0,t.jsx)(Qc,{value:V("heartbeat","maxConcurrentRuns",Number(ge.maxConcurrentRuns??20)),onCommit:r(mt=>X("heartbeat","maxConcurrentRuns",mt),"onCommit"),immediate:!0,className:kh})}),(0,t.jsxs)("div",{className:"rounded-md border border-border/70 px-3 py-2",children:[(0,t.jsx)(yl,{label:"Continue after max-turn stop",hint:ji.maxTurnContinuationEnabled,checked:ss,onChange:r(mt=>Rn({enabled:mt}),"onChange")}),ss?(0,t.jsxs)("div",{className:"mt-3 grid gap-3 sm:grid-cols-2",children:[(0,t.jsx)(_s,{label:"Continuation attempts",hint:ji.maxTurnContinuationMaxAttempts,children:(0,t.jsx)(Qc,{value:ws,onCommit:r(mt=>Rn({maxAttempts:yR(mt,0,cae)}),"onCommit"),immediate:!0,className:kh})}),(0,t.jsx)(_s,{label:"Continuation delay (sec)",hint:ji.maxTurnContinuationDelaySec,children:(0,t.jsx)(Qc,{value:yn,onCommit:r(mt=>Rn({delayMs:omt(mt)}),"onCommit"),immediate:!0,className:kh})})]}):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)(Yy,{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)(Yy,{className:"h-3 w-3"})," Debugging"]}),(0,t.jsxs)("div",{className:W("border-border bg-accent/30",i?"rounded-lg border p-4":"mx-4 mb-4 rounded-md border px-3 py-3"),children:[(0,t.jsx)(yl,{label:"Capture raw provider traces",hint:"Stores exact provider traffic for every future run until disabled. Traces may contain sensitive prompts and tool arguments, are administrator-only, and expire after 24 hours.",checked:V("debug","providerTrace",Ee.providerTrace)==="raw",onChange:r(mt=>X("debug","providerTrace",mt?"raw":void 0),"onChange")}),V("debug","providerTrace",Ee.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)(Yy,{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)(WCe,{variant:Le?"prerequisites":"connection",state:rs?"running":$s||It.error?"fail":Pt?.status??"idle",result:Pt??null,error:$s??(It.error instanceof Error?It.error.message:null),onTest:Er,disabled:Hn})]})}r(Y_e,"AgentConfigForm");var Bz=new Set(["authenticated","failed","timed_out","cancelled"]),Fz=2e3;function zz({value:e,label:s}){const[n,a]=(0,m.useState)(!1),i=(0,m.useRef)(null);return(0,m.useEffect)(()=>()=>{i.current&&clearTimeout(i.current)},[]),(0,t.jsx)($,{type:"button",variant:"ghost",size:"icon-xs","aria-label":s,title:s,className:"text-muted-foreground hover:text-foreground",onClick:r(async()=>{try{await wa(e),a(!0)}catch{a(!1)}i.current&&clearTimeout(i.current),i.current=setTimeout(()=>a(!1),1500)},"onClick"),children:n?(0,t.jsx)(cs,{className:"size-3"}):(0,t.jsx)(gr,{className:"size-3"})})}r(zz,"AdapterLoginCopyButton");function cmt({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)(cs,{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(cmt,"AdapterLoginTerminalState");var dmt={claude_local:"Anthropic",codex_local:"OpenAI"};function Z_e(e){const s=dmt[e];return s?`Sign in to ${s}`:"Sign in to the environment"}r(Z_e,"adapterLoginTitle");function MV(e){return Xj()(e.adapterType).login?.panelMode==="submitted_browser_code"?(0,t.jsx)(pmt,{...e}):(0,t.jsx)(umt,{...e})}r(MV,"AdapterLoginPanel");var hD=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 umt({companyId:e,adapterType:s,environmentId:n,autoStart:a,onConnected:i,onAccountBinding:o,chrome:l="panel",aiConnection:c,onPromptReady:d}){const[u,h]=(0,m.useState)(null),[p,f]=(0,m.useState)(null),[x,g]=(0,m.useState)(null),[v,y]=(0,m.useState)("idle"),k=(0,m.useRef)(!1),w=je({mutationFn:r(()=>_t.startAdapterAuthLogin(e,s,{environmentId:n,aiConnection:c}),"mutationFn"),onSuccess:r(re=>{k.current=!1,f(null),g(null),y("idle"),h(re.sessionId)},"onSuccess"),onError:r(re=>{f(re instanceof Error?re.message:"Could not start the login.")},"onError")}),N=(0,m.useCallback)(()=>{k.current=!1,h(null),g(null),f(null)},[]),S=je({mutationFn:r(()=>_t.cancelAdapterAuthLogin(e,s,u),"mutationFn"),onSuccess:N,onError:r(re=>{f(re instanceof Error?re.message:"Could not cancel the login.")},"onError")}),C=te({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 hD(re.sessionId);return re}catch(re){if(re instanceof sn&&re.status===404)return null;throw re}},"queryFn"),retry:!1,gcTime:0,staleTime:0}),[_,R]=(0,m.useState)(!1),I=te({queryKey:["adapter-login-status",e,s,u],queryFn:r(()=>_t.getAdapterAuthLoginStatus(e,s,u),"queryFn"),enabled:!!u&&!_,retry:r((re,oe)=>oe instanceof sn&&oe.status===404?!1:re<3,"retry"),refetchInterval:r(re=>{const oe=re.state.data?.status;return oe&&Bz.has(oe)?!1:Fz},"refetchInterval")});(0,m.useEffect)(()=>{const re=I.data?.prompt??null;re&&g(re)},[I.data]);const T=I.data??w.data??null,E=T?.status??null,L=x,O=E?Bz.has(E):!1,P=!!u&&!O,Q=w.isPending||P||v==="saving",D=(0,m.useRef)(!1);(0,m.useEffect)(()=>{if(D.current||!C.isFetched)return;D.current=!0;const re=C.data;re&&(k.current=!0,f(null),g(re.prompt??null),h(re.sessionId))},[C.isFetched,C.data]),(0,m.useEffect)(()=>{const re=I.error;if(!(re instanceof sn&&re.status===404)||!k.current||_)return;R(!0);const oe=u;(async()=>(oe&&await _t.cancelAdapterAuthLogin(e,s,oe).catch(()=>{}),R(!1),N()))()},[I.error,_,u,e,s,N]);const F=(0,m.useRef)(!1),z=je({mutationFn:r(async()=>{const re=C.error;re instanceof hD&&await _t.cancelAdapterAuthLogin(e,s,re.sessionId)},"mutationFn"),onSuccess:r(async()=>{F.current=!1,D.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")}),K=(0,m.useRef)(w.mutate);K.current=w.mutate,(0,m.useEffect)(()=>{if(!(!a||F.current)){if(C.isError){F.current=!0,f(C.error instanceof Error?C.error.message:"Could not check for an active login.");return}C.isSuccess&&(F.current=!0,!C.data&&K.current())}},[a,C.isSuccess,C.isError,C.data,C.error]);const U=(0,m.useRef)(!1),q=(0,m.useRef)(i);q.current=i,(0,m.useEffect)(()=>{E!=="authenticated"||U.current||(U.current=!0,q.current?.(u??void 0))},[E]);const G=(0,m.useRef)(null),se=(0,m.useRef)(o);se.current=o;const Z=I.data?.codexAccountBinding??null,ie=(0,m.useCallback)(async re=>{const oe=se.current;if(oe){y("saving");try{await oe(re),y("bound")}catch{y("failed")}}},[]);(0,m.useEffect)(()=>{E!=="authenticated"||!u||G.current!==u&&(!Z||!Z.companyIdentityDiffers||!se.current||(G.current=u,ie(Z)))},[E,u,Z,ie]);const J=(0,m.useRef)(d);if(J.current=d,(0,m.useEffect)(()=>{J.current?.(L?.url??null)},[L]),l==="onboarding"){const re=O&&E&&E!=="authenticated";return(0,t.jsx)(NV,{loading:!L&&!p&&!re,providerName:kV(s),authorizationUrl:L?.url,mode:"displayed_code",children:p?(0,t.jsxs)("div",{children:[(0,t.jsx)("p",{role:"alert",className:"pl-2 text-xs text-destructive",children:p}),C.error instanceof hD&&(0,t.jsx)($,{type:"button",variant:"outline",disabled:z.isPending,onClick:r(()=>z.mutate(),"onClick"),children:"Cancel previous sign-in and retry"})]}):re?(0,t.jsx)("p",{role:"alert",className:"pl-2 text-xs text-destructive",children:E==="timed_out"?"The login timed out. Start it again.":E==="cancelled"?"The login was cancelled.":"The login did not finish. Start it again."}):(0,t.jsx)(r_e,{code:L?.code??"",autoCopy:!0})})}return(0,t.jsxs)("div",{className:"rounded-md border border-border bg-muted/40 px-3 py-2 flex flex-col gap-2",children:[(0,t.jsxs)("div",{className:"flex items-center justify-between gap-2",children:[(0,t.jsx)("span",{className:"text-xs font-medium text-foreground",children:Z_e(s)}),(0,t.jsxs)("div",{className:"flex items-center gap-1.5",children:[P&&(0,t.jsx)($,{type:"button",variant:"ghost",size:"sm",className:"h-7 px-2.5 text-xs text-muted-foreground hover:text-foreground",disabled:S.isPending,onClick:r(()=>S.mutate(),"onClick"),children:"Cancel"}),(0,t.jsx)($,{type:"button",variant:"outline",size:"sm",className:"h-7 px-2.5 text-xs",disabled:Q,onClick:r(()=>w.mutate(),"onClick"),children:"Sign in"})]})]}),p&&(0,t.jsx)("div",{role:"alert",className:"text-(length:--text-micro) text-destructive",children:p}),(0,t.jsxs)("div",{role:"status","aria-live":"polite",className:"space-y-2 empty:hidden",children:[P&&!L&&(0,t.jsxs)("div",{className:"flex items-center gap-2 text-(length:--text-micro) text-muted-foreground",children:[(0,t.jsx)(st,{className:"size-3 animate-spin shrink-0"}),(0,t.jsx)("span",{children:"Preparing..."})]}),P&&L&&(0,t.jsxs)("div",{className:"space-y-2",children:[(0,t.jsx)("div",{className:"text-(length:--text-micro) text-muted-foreground",children:"Copy the code, then open the authentication page."}),(0,t.jsxs)("div",{className:"flex items-center justify-between gap-2",children:[(0,t.jsxs)("div",{className:"min-w-0",children:[(0,t.jsx)("div",{className:"text-(length:--text-micro) uppercase tracking-wide text-muted-foreground",children:"1. Code"}),(0,t.jsx)("span",{className:"font-mono text-xs text-foreground break-all",children:L.code})]}),(0,t.jsx)(zz,{value:L.code,label:"Copy code"})]}),(0,t.jsxs)("div",{className:"flex items-center justify-between gap-2",children:[(0,t.jsxs)("div",{className:"min-w-0",children:[(0,t.jsx)("div",{className:"text-(length:--text-micro) uppercase tracking-wide text-muted-foreground",children:"2. Authentication URL"}),(0,t.jsx)("span",{className:"font-mono text-xs text-foreground break-all",children:L.url})]}),(0,t.jsxs)("div",{className:"flex items-center",children:[(0,t.jsx)(zz,{value:L.url,label:"Copy URL"}),(0,t.jsx)($,{asChild:!0,type:"button",variant:"ghost",size:"icon-xs","aria-label":"Open the authentication page",title:"Open the authentication page",className:"text-muted-foreground hover:text-foreground",children:(0,t.jsx)("a",{href:L.url,target:"_blank",rel:"noreferrer noopener",children:(0,t.jsx)(Dn,{className:"size-3"})})})]})]})]}),O&&E&&(0,t.jsx)(cmt,{status:E,message:T?.failure?.message??null}),E==="authenticated"&&v==="saving"&&(0,t.jsxs)("div",{className:"flex items-center gap-2 text-(length:--text-micro) text-muted-foreground",children:[(0,t.jsx)(st,{className:"size-3 animate-spin shrink-0"}),(0,t.jsx)("span",{children:"Binding this agent to the signed-in account..."})]}),E==="authenticated"&&v==="bound"&&(0,t.jsxs)("div",{className:"flex items-center gap-2 text-(length:--text-micro) text-foreground",children:[(0,t.jsx)(cs,{className:"size-3 shrink-0"}),(0,t.jsx)("span",{children:"Agent bound to the signed-in account."})]}),E==="authenticated"&&v==="failed"&&(0,t.jsxs)("div",{className:"flex items-center gap-2 text-(length:--text-micro)",children:[(0,t.jsx)(Es,{className:"size-3 shrink-0 text-destructive"}),(0,t.jsx)("span",{className:"text-destructive",children:"Could not bind this agent to the signed-in account."}),(0,t.jsx)($,{type:"button",variant:"outline",size:"sm",className:"h-6 px-2 text-xs",onClick:r(()=>{Z&&ie(Z)},"onClick"),children:"Retry"})]})]})]})}r(umt,"DisplayedCodeLoginPanel");var mmt=new Set(["failed","timed_out","cancelled"]),dae="The login did not finish. Start the login again.",hmt=9e5,uae="The login timed out. Start the login again.";function pmt({companyId:e,adapterType:s,environmentId:n,onStored:a,onApplyStored:i,autoStart:o,onConnected:l,onCodeSubmitted:c,onSubmitFailed:d,chrome:u="panel",aiConnection:h,onPromptReady:p}){const[f,x]=(0,m.useState)(null),[g,v]=(0,m.useState)(null),[y,k]=(0,m.useState)(null),[w,N]=(0,m.useState)(!1),[S,C]=(0,m.useState)(""),[_,R]=(0,m.useState)(null),[I,T]=(0,m.useState)(!1),[E,L]=(0,m.useState)(!1),[O,P]=(0,m.useState)(!1),[Q,D]=(0,m.useState)(!1),F=(0,m.useRef)(!1),[z,K]=(0,m.useState)(!1),U=(0,m.useRef)(!1),q=r(()=>{v(null),k(null),N(!1),C(""),R(null),T(!1),L(!1),D(!1),P(!1),F.current=!1},"resetLocalState"),G=te({queryKey:["claude-oauth-token-status",e],queryFn:r(async()=>{try{return await _t.getClaudeOAuthTokenStatus(e)}catch(rt){if(rt instanceof sn&&rt.status===404)return null;throw rt}},"queryFn"),retry:r((rt,Pe)=>Pe instanceof sn&&Pe.status===404?!1:rt<2,"retry")}).data??null,se=je({mutationFn:r(()=>_t.startClaudeSetupTokenLogin(e,{environmentId:n,aiConnection:h,...G&&!h?{overwrite:{expectedSecretId:G.secretId,expectedLatestVersion:G.latestVersion}}:{}}),"mutationFn"),onSuccess:r(rt=>{U.current=!1,q(),x(rt.sessionId)},"onSuccess"),onError:r(rt=>{v(rt instanceof Error?rt.message:"Could not start the login.")},"onError")}),Z=r(()=>{U.current=!1,x(null),q()},"clearActiveSession"),ie=je({mutationFn:r(()=>_t.cancelClaudeSetupTokenLogin(e,f),"mutationFn"),onSuccess:r(()=>{Z()},"onSuccess"),onError:r(rt=>{if(rt instanceof sn&&rt.status===404){Z();return}v(rt instanceof Error?rt.message:"Could not cancel the login.")},"onError")}),J=(0,m.useCallback)(rt=>{_t.cancelClaudeSetupTokenLogin(e,rt).catch(()=>{})},[e]),re=te({queryKey:["claude-setup-token-active-session",e],queryFn:r(async()=>{try{const rt=await _t.getActiveClaudeSetupTokenLoginSession(e);if(!rt)return null;if(h&&rt.environmentId!==n||!!rt.aiConnection!=!!h||h&&(rt.aiConnection?.provider!==h.provider||rt.aiConnection?.method!==h.method||rt.aiConnection?.connectionId!==h.connectionId||rt.aiConnection?.ownership!==h.ownership||rt.aiConnection?.allAgents!==h.allAgents||JSON.stringify(rt.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 rt}catch(rt){if(rt instanceof sn&&rt.status===404)return null;throw rt}},"queryFn"),retry:!1,gcTime:0,staleTime:0}),[oe,V]=(0,m.useState)(!1),X=!!f&&!E&&!Q&&!oe,Y=te({queryKey:["claude-setup-token-status",e,f],queryFn:r(()=>_t.getClaudeSetupTokenLoginStatus(e,f),"queryFn"),enabled:X,retry:r((rt,Pe)=>Pe instanceof sn&&Pe.status===404?!1:rt<3,"retry"),refetchInterval:r(rt=>{if(E||Q)return!1;const Pe=rt.state.data?.status;return Pe&&Bz.has(Pe)?!1:Fz},"refetchInterval")});(0,m.useEffect)(()=>{const rt=Y.error;if(rt instanceof sn&&rt.status===404){if(U.current){if(oe)return;V(!0);const Pe=f;(async()=>(Pe&&await _t.cancelClaudeSetupTokenLogin(e,Pe).catch(()=>{}),V(!1),Z()))();return}D(!0)}},[Y.error,oe,f,e]);const ae=(0,m.useRef)(!1);(0,m.useEffect)(()=>{if(ae.current||!re.isFetched)return;ae.current=!0;const rt=re.data;rt&&(U.current=!0,q(),x(rt.sessionId),rt.prompt&&(k(rt.prompt.authorizationUrl),rt.prompt.transportAdvisory&&N(!0)))},[re.isFetched,re.data]);const ne=te({queryKey:["claude-setup-token-prompt",e,f],enabled:X&&!y,queryFn:r(async()=>{try{return await _t.getClaudeSetupTokenLoginPrompt(e,f)}catch(rt){if(rt instanceof sn&&rt.status===404)return null;throw rt}},"queryFn"),refetchInterval:r(rt=>E||rt.state.data?.authorizationUrl?!1:Fz,"refetchInterval")});(0,m.useEffect)(()=>{const rt=ne.data?.authorizationUrl??null;rt&&k(rt),ne.data?.transportAdvisory&&N(!0)},[ne.data]);const ce=je({mutationFn:r(rt=>_t.submitClaudeSetupTokenBrowserCode(e,f,rt),"mutationFn"),onError:r(rt=>{v(rt instanceof Error?rt.message:"Could not submit the browser code.")},"onError")}),he=je({mutationFn:r(()=>_t.completeClaudeSetupTokenLogin(e,f),"mutationFn"),onSuccess:r(rt=>{R(rt.storedSessionId),a?.(rt.storedSessionId)},"onSuccess"),onError:r(()=>{T(!0)},"onError")}),pe=Y.data?.status??se.data?.status??null,ge=Y.data?.expiresAt??se.data?.expiresAt??null,Ee=(0,m.useRef)(he.mutate);Ee.current=he.mutate,(0,m.useEffect)(()=>{pe==="authenticated"&&!F.current&&(F.current=!0,Ee.current())},[pe]);const de=_!==null,Ne=I||Q||!!(pe&&mmt.has(pe)),le=pe==="authenticated"&&!de&&!I,Le=!!f&&!de&&!Ne&&!E,Ie=se.isPending||Le;(0,m.useEffect)(()=>{if(!Le)return;const rt=ge!==null?new Date(ge).getTime():NaN,Pe=Number.isFinite(rt)?Math.max(0,rt-Date.now()):hmt,De=setTimeout(()=>{f&&J(f),L(!0)},Pe);return()=>clearTimeout(De)},[Le,ge,f,J]);const ye=S.trim(),Ae=Le&&!!y&&!le&&bOe(ye)&&!ce.isPending&&!O,Qe=(0,m.useRef)(c);Qe.current=c;const ue=(0,m.useRef)(d);ue.current=d;const Be=r(()=>{Ae&&(v(null),ce.mutate(ye),P(!0),Qe.current?.(),u!=="onboarding"&&C(""))},"handleSubmit"),ft=(0,m.useRef)(!1),gt=(0,m.useRef)(se.mutate);gt.current=se.mutate,(0,m.useEffect)(()=>{if(!(!o||ft.current)){if(re.isError){ft.current=!0,v(re.error instanceof Error?re.error.message:"Could not check for an active login.");return}re.isSuccess&&(ft.current=!0,!re.data&&gt.current())}},[o,re.isSuccess,re.isError,re.data,re.error]);const Xe=(0,m.useRef)(Be);Xe.current=Be;const Fe=u==="onboarding",at=(0,m.useRef)(!1);(0,m.useEffect)(()=>{!Fe||!at.current||(at.current=!1,Ae&&Xe.current())},[Fe,Ae,S]);const Tt=(0,m.useRef)(!1),Dt=(0,m.useRef)(l);Dt.current=l,(0,m.useEffect)(()=>{!de||Tt.current||(Tt.current=!0,Dt.current?.(f??void 0))},[de]),(0,m.useEffect)(()=>{O&&(!g&&!Ne&&!E||(P(!1),ue.current?.()))},[O,g,Ne,E]);const Ot=(0,m.useRef)(p);if(Ot.current=p,(0,m.useEffect)(()=>{Ot.current?.(y)},[y]),u==="onboarding"){const rt=Ne||E;return(0,t.jsxs)(NV,{loading:!y&&!g&&!rt,providerName:kV(s),authorizationUrl:y??void 0,mode:"submitted_code",children:[w&&(0,t.jsxs)("p",{className:"flex items-start gap-2 pl-2 text-xs text-amber-700 dark:text-amber-200",children:[(0,t.jsx)(Es,{className:"mt-0.5 size-3 shrink-0"}),"This connection is not encrypted. The login code travels in clear text on this network. Continue only on a network you trust."]}),g?(0,t.jsx)("p",{role:"alert",className:"pl-2 text-xs text-destructive",children:g}):rt?(0,t.jsx)("p",{role:"alert",className:"pl-2 text-xs text-destructive",children:E&&!Ne?uae:dae}):(0,t.jsx)(X3,{value:S,onChange:C,onSubmit:Be,onPaste:r(()=>{at.current=!0},"onPaste"),masked:!0,disabled:ce.isPending||le||O})]})}return(0,t.jsxs)("div",{className:"rounded-md border border-border bg-muted/40 px-3 py-2 flex flex-col gap-2",children:[(0,t.jsxs)("div",{className:"flex items-center justify-between gap-2",children:[(0,t.jsx)("span",{className:"text-xs font-medium text-foreground",children:Z_e(s)}),(0,t.jsxs)("div",{className:"flex items-center gap-1.5",children:[Le&&(0,t.jsx)($,{type:"button",variant:"ghost",size:"sm",className:"h-7 px-2.5 text-xs text-muted-foreground hover:text-foreground",disabled:ie.isPending,onClick:r(()=>ie.mutate(),"onClick"),children:"Cancel"}),i&&G&&!Le&&!de&&!z&&(0,t.jsx)($,{type:"button",variant:"default",size:"sm",className:"h-7 px-2.5 text-xs",onClick:r(()=>{i(),K(!0)},"onClick"),children:"Use saved login"}),(0,t.jsx)($,{type:"button",variant:"outline",size:"sm",className:"h-7 px-2.5 text-xs",disabled:Ie,onClick:r(()=>se.mutate(),"onClick"),children:G&&!Le&&!de?"Sign in to replace":"Sign in"})]})]}),G&&!Le&&!de&&!z&&(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."}),z&&(0,t.jsxs)("div",{className:"flex items-center gap-2 text-(length:--text-micro) text-foreground",children:[(0,t.jsx)(cs,{className:"size-3 shrink-0"}),(0,t.jsx)("span",{children:"The saved Claude login is bound to this agent now."})]}),g&&(0,t.jsx)("div",{role:"alert",className:"text-(length:--text-micro) text-destructive",children:g}),(0,t.jsxs)("div",{role:"status","aria-live":"polite",className:"space-y-2 empty:hidden",children:[Le&&!y&&!le&&(0,t.jsxs)("div",{className:"flex items-center gap-2 text-(length:--text-micro) text-muted-foreground",children:[(0,t.jsx)(st,{className:"size-3 animate-spin shrink-0"}),(0,t.jsx)("span",{children:"Preparing..."})]}),Le&&y&&!le&&(0,t.jsxs)("div",{className:"space-y-2",children:[w&&(0,t.jsxs)("div",{className:"flex items-start gap-2 rounded-md border border-amber-300 bg-amber-50 px-2 py-1.5 text-(length:--text-micro) text-amber-800 dark:border-amber-500/40 dark:bg-amber-500/10 dark:text-amber-200",children:[(0,t.jsx)(Es,{className:"size-3 shrink-0 mt-0.5"}),(0,t.jsx)("span",{children:"This connection is not encrypted. The login code travels in clear text on this network. Continue only on a network you trust."})]}),(0,t.jsx)("div",{className:"text-(length:--text-micro) text-muted-foreground",children:"Open the authorization page, then enter the browser code it shows."}),(0,t.jsxs)("div",{className:"flex items-center justify-between gap-2",children:[(0,t.jsxs)("div",{className:"min-w-0",children:[(0,t.jsx)("div",{className:"text-(length:--text-micro) uppercase tracking-wide text-muted-foreground",children:"1. Authorization URL"}),(0,t.jsx)("span",{className:"font-mono text-xs text-foreground break-all",children:y})]}),(0,t.jsxs)("div",{className:"flex items-center",children:[(0,t.jsx)(zz,{value:y,label:"Copy URL"}),(0,t.jsx)($,{asChild:!0,type:"button",variant:"ghost",size:"icon-xs","aria-label":"Open the authorization page",title:"Open the authorization page",className:"text-muted-foreground hover:text-foreground",children:(0,t.jsx)("a",{href:y,target:"_blank",rel:"noreferrer noopener",children:(0,t.jsx)(Dn,{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(rt=>C(rt.target.value),"onChange"),onKeyDown:r(rt=>{rt.key==="Enter"&&(rt.preventDefault(),Be())},"onKeyDown"),className:"flex-1 min-w-0 rounded-md border border-border bg-background px-2 py-1 font-mono text-xs text-foreground"}),(0,t.jsx)($,{type:"button",variant:"outline",size:"sm",className:"h-7 px-2.5 text-xs",disabled:!Ae,onClick:Be,children:"Submit"})]})]})]}),le&&(0,t.jsxs)("div",{className:"flex items-center gap-2 text-(length:--text-micro) text-muted-foreground",children:[(0,t.jsx)(st,{className:"size-3 animate-spin shrink-0"}),(0,t.jsx)("span",{children:"Completing the login…"})]}),de&&(0,t.jsxs)("div",{className:"flex items-center gap-2 text-(length:--text-micro) text-foreground",children:[(0,t.jsx)(cs,{className:"size-3 shrink-0"}),(0,t.jsx)("span",{children:"Authenticated. The environment has credentials now."})]}),Ne&&(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:dae})]}),E&&!Ne&&!de&&(0,t.jsxs)("div",{className:"flex items-start gap-2 text-(length:--text-micro) text-destructive",children:[(0,t.jsx)(Es,{className:"size-3 shrink-0"}),(0,t.jsx)("span",{children:uae})]})]})]})}r(pmt,"SubmittedBrowserCodeLoginPanel");function fmt({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(fmt,"AdapterEnvironmentResult$1");function J_e({value:e,onChange:s,disabledTypes:n,openAiDotEnabled:a=!1}){const[i,o]=(0,m.useState)(!1),l=Gm(e),c=(0,m.useMemo)(()=>[...H_e(d=>b5[d]??wf(d)),...a?[{value:"openai_dot",label:"OpenAI Dot",experimental:!0,comingSoon:!1}]:[]].filter(d=>!n.has(d.value)),[n,a]);return(0,t.jsxs)(dr,{open:i,onOpenChange:o,children:[(0,t.jsx)(wr,{asChild:!0,children:(0,t.jsxs)("button",{type:"button","data-size":"default",className:W(Sqe,"w-full"),children:[(0,t.jsxs)("span",{className:"inline-flex min-w-0 items-center gap-1.5",children:[(0,t.jsx)("span",{"aria-hidden":"true",className:"inline-flex shrink-0",children:(0,t.jsx)(B0,{type:e,className:"size-4"})}),(0,t.jsx)("span",{className:"truncate",children:b5[e]??wf(e)}),l.experimental&&(0,t.jsx)(mae,{})]}),(0,t.jsx)(rn,{className:"size-4 opacity-50"})]})}),(0,t.jsx)(sr,{className:"w-(--radix-popover-trigger-width) p-1",align:"start",children:c.map(d=>(0,t.jsxs)("button",{type:"button",disabled:d.comingSoon,className:W("flex items-center justify-between w-full px-2 py-1.5 text-sm rounded",d.comingSoon?"opacity-40 cursor-not-allowed":"hover:bg-accent/50",d.value===e&&!d.comingSoon&&"bg-accent"),onClick:r(()=>{d.comingSoon||(s(d.value),o(!1))},"onClick"),children:[(0,t.jsxs)("span",{className:"inline-flex items-center gap-1.5",children:[(0,t.jsx)("span",{"aria-hidden":"true",className:"inline-flex shrink-0",children:(0,t.jsx)(B0,{type:d.value,className:"size-4"})}),(0,t.jsx)("span",{children:d.label}),d.experimental&&(0,t.jsx)(mae,{})]}),d.comingSoon&&(0,t.jsx)("span",{className:"text-(length:--text-nano) text-muted-foreground",children:"Coming soon"})]},d.value))})]})}r(J_e,"AdapterTypeDropdown");function mae(){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(mae,"ExperimentalBadge$1");function PV({models:e,value:s,onChange:n,open:a,onOpenChange:i,allowDefault:o,required:l,groupByProvider:c,preserveOrder:d,creatable:u,detectedModel:h,detectedModelCandidates:p,onDetectModel:f,onRefreshModels:x,refreshingModels:g,loadingModels:v,detectModelLabel:y,emptyDetectHint:k,defaultLabel:w,presentation:N="searchable",effort:S}){const[C,_]=(0,m.useState)(""),[R,I]=(0,m.useState)(!1),[T,E]=(0,m.useState)(!1),L=C.trim(),O=!!(u&&L&&!e.some(U=>U.id.toLowerCase()===L.toLowerCase())),P=(0,m.useMemo)(()=>{const U=new Set;h&&U.add(h);for(const q of p??[])q&&U.add(q);return U},[h,p]),Q=(0,m.useMemo)(()=>e.filter(U=>{if(P.has(U.id))return!1;const q=CE(U.id);return nM({...Tk(U,c),...q&&!U.provider?{group:q}:{}},C)}),[e,C,P,c]),D=(0,m.useMemo)(()=>new Map(e.map(U=>[U.id,Tk(U,c)])),[e,c]),F=s?eu(s,[...D.values()]):null,z=(0,m.useMemo)(()=>{if(!c&&Q.some(q=>q.provider)){const q=new Map;for(const G of Q){const se=G.provider??"other";q.set(se,[...q.get(se)??[],G])}return Array.from(q.entries()).map(([G,se])=>({provider:G,entries:se}))}if(!c)return[{provider:null,entries:d?Q:[...Q].sort((q,G)=>q.id.localeCompare(G.id))}];const U=new Map;for(const q of Q){const G=CE(q.id)??"other",se=U.get(G)??[];se.push(q),U.set(G,se)}return Array.from(U.entries()).sort(([q],[G])=>q.localeCompare(G)).map(([q,G])=>({provider:q,entries:[...G].sort((se,Z)=>se.id.localeCompare(Z.id))}))},[Q,c,d]);async function K(){if(f){E(!0);try{const U=await f();U&&(n(U),i(!1),_(""))}finally{E(!1)}}}if(r(K,"handleDetectModel"),N==="native"){const U="__paperclip_custom_model__",q=[...new Set([s,...P])].filter(G=>!!G&&(!e.some(se=>se.id===G)||P.has(G)));return(0,t.jsxs)(_s,{label:"Model",hint:ji.model,children:[(0,t.jsxs)(uW,{"aria-label":"Model","aria-busy":v||g,value:R?U:s,required:l&&!R,onChange:r(G=>{const se=G.target.value;I(se===U),se!==U&&n(se)},"onChange"),children:[(0,t.jsx)("option",{value:"",disabled:!o,children:o?w??"Default":v?"Loading models…":l?"Select model (required)":"Select model"}),q.map(G=>(0,t.jsx)("option",{value:G,children:e.find(se=>se.id===G)?.label??G},G)),z.map(({provider:G,entries:se})=>c?(0,t.jsx)("optgroup",{label:G??void 0,children:se.map(Z=>(0,t.jsx)("option",{value:Z.id,children:Z.label},Z.id))},G):se.map(Z=>(0,t.jsx)("option",{value:Z.id,children:Z.label},Z.id))),u&&(0,t.jsx)("option",{value:U,children:"Enter custom model…"})]}),R&&(0,t.jsxs)("label",{className:"mt-3 block space-y-1 text-xs text-muted-foreground",children:["Model ID",(0,t.jsx)(dt,{"aria-label":"Model ID",value:s,onChange:r(G=>n(G.target.value),"onChange"),placeholder:"Enter model ID or alias",autoFocus:!0,required:l})]}),v&&(0,t.jsx)("p",{role:"status",className:"mt-2 text-xs text-muted-foreground",children:"Loading models…"}),x&&(0,t.jsx)($,{type:"button",variant:"ghost",size:"sm",disabled:g,onClick:r(()=>{x()},"onClick"),children:g?"Refreshing…":"Refresh models"})]})}return(0,t.jsx)(_s,{label:"Model",hint:ji.model,children:(0,t.jsxs)(dr,{open:a,onOpenChange:r(U=>{i(U),U||_("")},"onOpenChange"),children:[(0,t.jsx)(wr,{asChild:!0,children:(0,t.jsxs)("button",{type:"button","aria-label":"Model",className:"flex w-full min-w-0 items-center gap-2 rounded-md border border-border px-2.5 py-1.5 text-left text-sm transition-colors hover:bg-accent/50","data-testid":"model-dropdown-trigger",children:[F?(0,t.jsx)(yf,{display:F,layout:"inline",className:"min-w-0 flex-1"}):(0,t.jsx)("span",{className:"min-w-0 flex-1 truncate text-muted-foreground",children:o?w??"Default":l?"Select model (required)":"Select model"}),S&&s&&Cj(S.value,s,[...D.values()])?(0,t.jsxs)("span",{className:W("shrink-0 text-xs",S.value?"text-foreground":"text-muted-foreground"),"data-testid":"model-dropdown-effort-value",children:["· ",S.value??"Auto effort"]}):null,(0,t.jsx)(rn,{className:"size-4 shrink-0 text-muted-foreground"})]})}),(0,t.jsxs)(sr,{className:"w-(--radix-popover-trigger-width) p-1",align:"start",children:[S&&s&&Cj(S.value,s,[...D.values()])?(0,t.jsxs)("div",{className:"-mx-1 -mt-1 mb-1 space-y-1.5 border-b border-border px-2.5 py-2",children:[(0,t.jsx)("span",{className:"block text-xs font-medium text-muted-foreground",children:"Thinking effort"}),(0,t.jsx)(jM,{levels:ng(s,[...D.values()]),value:S.value,onChange:r(U=>{S.onChange(U),i(!1)},"onChange"),defaultLabel:"Auto",label:"Thinking effort",testId:"model-dropdown-effort"})]}):null,(0,t.jsxs)("div",{className:"relative -mx-1 -mt-1 mb-1 border-b border-border",children:[(0,t.jsx)(Jr,{className:"pointer-events-none absolute left-2.5 top-1/2 size-4 -translate-y-1/2 text-muted-foreground","aria-hidden":"true"}),(0,t.jsx)("input",{"aria-label":"Search models",className:"h-9 w-full bg-transparent pl-8 pr-7 text-sm outline-none placeholder:text-muted-foreground",placeholder:u?TS:"Search models",value:C,onChange:r(U=>_(U.target.value),"onChange"),autoFocus:!0}),C&&(0,t.jsx)("button",{type:"button","aria-label":"Clear search",className:"absolute right-2.5 top-1/2 -translate-y-1/2 text-muted-foreground hover:text-foreground",onClick:r(()=>_(""),"onClick"),children:(0,t.jsxs)("svg",{"aria-hidden":"true",focusable:"false",className:"h-3 w-3",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,t.jsx)("line",{x1:"18",y1:"6",x2:"6",y2:"18"}),(0,t.jsx)("line",{x1:"6",y1:"6",x2:"18",y2:"18"})]})})]}),f&&!C.trim()&&(0,t.jsxs)("button",{type:"button",className:"flex items-center gap-1.5 w-full px-2 py-1.5 text-xs rounded hover:bg-accent/50 text-muted-foreground",onClick:r(()=>{K()},"onClick"),disabled:T,children:[(0,t.jsxs)("svg",{"aria-hidden":"true",focusable:"false",className:"h-3 w-3",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,t.jsx)("path",{d:"M21 12a9 9 0 0 0-9-9 9.75 9.75 0 0 0-6.74 2.74L3 8"}),(0,t.jsx)("path",{d:"M3 3v5h5"})]}),T?"Detecting...":h?y?.replace(/^Detect\b/,"Re-detect")??"Re-detect from config":y??"Detect from config"]}),x&&!C.trim()&&(0,t.jsxs)("button",{type:"button",className:"flex items-center gap-1.5 w-full px-2 py-1.5 text-xs rounded hover:bg-accent/50 text-muted-foreground",onClick:r(()=>{x()},"onClick"),disabled:g,children:[(0,t.jsxs)("svg",{"aria-hidden":"true",focusable:"false",className:"h-3 w-3",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,t.jsx)("path",{d:"M3 12a9 9 0 0 1 15.28-6.36L21 8"}),(0,t.jsx)("path",{d:"M21 3v5h-5"}),(0,t.jsx)("path",{d:"M21 12a9 9 0 0 1-15.28 6.36L3 16"}),(0,t.jsx)("path",{d:"M8 16H3v5"})]}),g?"Refreshing...":"Refresh models"]}),s&&(!e.some(U=>U.id===s)||P.has(s))&&(0,t.jsxs)("button",{type:"button",className:W("flex items-center w-full px-2 py-1.5 text-sm rounded bg-accent/50"),onClick:r(()=>{i(!1)},"onClick"),children:[F?(0,t.jsx)(yf,{display:F,layout:"inline",className:"flex-1"}):null,(0,t.jsx)(it,{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(U=>U.id===h)?.label??h}),(0,t.jsx)(it,{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(U=>U&&U!==h&&U!==s).map(U=>{const q=e.find(G=>G.id===U);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(U),i(!1)},"onClick"),children:[(0,t.jsx)("span",{className:"block w-full text-left truncate font-mono text-xs",title:U,children:q?.label??U}),(0,t.jsx)(it,{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-${U}`)}),(0,t.jsxs)("div",{className:"max-h-(--sz-240px) overflow-y-auto",children:[o&&(0,t.jsx)("button",{type:"button",className:W("flex items-center gap-2 w-full px-2 py-1.5 text-sm rounded hover:bg-accent/50",!s&&"bg-accent"),onClick:r(()=>{n(""),i(!1)},"onClick"),children:"Default"}),O&&(0,t.jsxs)("button",{type:"button",className:"flex items-center justify-between gap-2 w-full px-2 py-1.5 text-sm rounded hover:bg-accent/50",onClick:r(()=>{n(L),i(!1),_("")},"onClick"),children:[(0,t.jsx)("span",{children:"Use manual model"}),(0,t.jsx)("span",{className:"text-xs font-mono text-muted-foreground",children:L})]}),z.map(U=>(0,t.jsxs)("div",{className:"mb-1 last:mb-0",children:[U.provider&&(0,t.jsx)(aM,{provider:U.provider,testId:`model-dropdown-group-${U.provider}`}),U.entries.map(q=>(0,t.jsxs)("button",{type:"button",className:W("flex items-center gap-2 w-full px-2 py-1.5 text-left text-sm rounded hover:bg-accent/50",q.id===s&&"bg-accent"),onClick:r(()=>{n(q.id),S&&ng(q.id,[...D.values()]).length>0||i(!1)},"onClick"),children:[(0,t.jsx)(rM,{option:D.get(q.id)??Tk(q,c)}),q.id===s?(0,t.jsx)(cs,{className:"size-4 shrink-0","aria-hidden":"true"}):null]},q.id))]},U.provider??"")),Q.length===0&&!O&&P.size===0&&(0,t.jsx)("div",{className:"px-2 py-2 space-y-2",children:(0,t.jsx)("p",{className:"text-xs text-muted-foreground",children:v?"Loading models…":f?k??"No model detected yet. Enter a provider/model manually.":"No models found."})})]})]})]})})}r(PV,"ModelDropdown");function xmt({value:e,options:s,onChange:n,open:a,onOpenChange:i}){const o=s.find(l=>l.id===e)??s[0];return(0,t.jsx)(_s,{label:"Thinking effort",hint:ji.thinkingEffort,children:(0,t.jsxs)(dr,{open:a,onOpenChange:i,children:[(0,t.jsx)(wr,{asChild:!0,children:(0,t.jsxs)("button",{className:"inline-flex items-center gap-1.5 rounded-md border border-border px-2.5 py-1.5 text-sm hover:bg-accent/50 transition-colors w-full justify-between",children:[(0,t.jsx)("span",{className:W(!e&&"text-muted-foreground"),children:o?.label??"Auto"}),(0,t.jsx)(rn,{className:"h-3 w-3 text-muted-foreground"})]})}),(0,t.jsx)(sr,{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(xmt,"ThinkingEffortDropdown");function X_e(e){const s=`paperclip.agent-appearance.${e}`;function n(){try{const l=gbe.safeParse(JSON.parse(sessionStorage.getItem(s)??"null"));if(l.success)return l.data}catch{}const o=WT();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(X_e,"useAgentAppearanceDraft");var P2=null,PI=new Set,D2={subscribe(e){return PI.add(e),()=>{PI.delete(e)}},getSnapshot(){return P2},acquire(e){if(P2)return!1;P2=e;for(const s of PI)s();return!0},release(e){if(P2===e){P2=null;for(const s of PI)s()}}};function _N({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)(()=>iv(s??e?.appearance,e?.id),[s,e?.appearance,e?.id]),g=(0,m.useRef)(null),v=(0,m.useRef)(null),y=(0,m.useRef)(null),k=(0,m.useRef)(Symbol("agent-character")),w=(0,m.useSyncExternalStore)(D2.subscribe,D2.getSnapshot,()=>null),[N,S]=(0,m.useState)(!1),[C,_]=(0,m.useState)(!0),[R,I]=(0,m.useState)(!1),[T,E]=(0,m.useState)(!1),L=!x.customAvatarAssetId&&N&&!C&&!R&&o==="auto"&&a!=="rest";return(0,m.useEffect)(()=>{if(typeof matchMedia!="function"||typeof IntersectionObserver!="function")return;const O=matchMedia("(prefers-reduced-motion: reduce)"),P=r(()=>_(O.matches),"change");P(),O.addEventListener("change",P);const Q=new IntersectionObserver(D=>S(D[0]?.isIntersecting??!1));return g.current&&Q.observe(g.current),()=>{Q.disconnect(),O.removeEventListener("change",P)}},[]),(0,m.useEffect)(()=>{L&&w===null&&D2.acquire(k.current),L||D2.release(k.current)},[L,w]),(0,m.useEffect)(()=>()=>D2.release(k.current),[]),(0,m.useEffect)(()=>{if(!L||w!==k.current)return;let O=!1;return E(!1),Promise.all([fd(()=>import("./runtime-IAg0vdY9.js"),__vite__mapDeps([0,1])),fd(()=>import("./definition-DokS0JQS.js"),__vite__mapDeps([2,3,1]))]).then(([P,Q])=>{O||!v.current||(y.current=P.createCharacter(v.current,Q.characterDefinition(x,i),{animation:Q.animationId(a),trackingRegion:l?.current??g.current??void 0,followCursor:d,followRotation:u,trackingScope:c,displaySize:n,onError:r(()=>I(!0),"onError")}),E(!0))}).catch(()=>{O||I(!0)}),()=>{O=!0,y.current?.destroy(),y.current=null,E(!1)}},[L,w,l,c,n,d,u]),(0,m.useEffect)(()=>{y.current&&fd(()=>import("./definition-DokS0JQS.js").then(O=>{y.current?.setDefinition(O.characterDefinition(x,i)),y.current?.setAnimation(O.animationId(a))}),__vite__mapDeps([2,3,1]))},[x,i,a,T]),(0,t.jsxs)("span",{ref:g,role:p?"img":void 0,"aria-label":p,"aria-hidden":p?void 0:!0,className:W("relative inline-block shrink-0",lqe[n],h),children:[(0,t.jsx)(lr,{agent:e,appearance:x,size:n<256?256:n,name:f,pose:a,muted:i,className:W("size-full",T&&!x.customAvatarAssetId&&"invisible")}),(0,t.jsx)("span",{ref:v,className:"absolute inset-0"})]})}r(_N,"AgentCharacter");var gmt=new Set(["claude_local","codex_local","opencode_local","grok_local"]);function e5e(e,{cloud:s,nativeRunnerEnabled:n,openAiDotEnabled:a=!1,runnerProvider:i}){return e==="openai_dot"||e==="paperclip_runner"&&i==="openai_dot"?a:e==="paperclip_runner"?n:s?gmt.has(e):!0}r(e5e,"isNewAgentAdapterAllowed");function bmt(){const{selectedCompanyId:e}=ps(),{appearance:s}=X_e(`${e}:new-agent`);return(0,t.jsx)(_N,{appearance:s,state:"sleepy",muted:!0,size:256,className:"size-48",trackingScope:"page"})}r(bmt,"AgentBasicsCharacter");function t5e({open:e,onClose:s,onContinue:n,initialAdapter:a="",onInvite:i}){const o=(0,m.useId)(),l=!!ed(),c=te({queryKey:M.instance.experimentalSettings,queryFn:jr.getExperimental,enabled:e,retry:!1}),[d,u]=(0,m.useState)(""),[h,p]=(0,m.useState)(a),[f,x]=(0,m.useState)("codex"),[g,v]=(0,m.useState)("name"),{data:y,isPending:k,error:w}=te({queryKey:M.adapters.all,queryFn:Ph.list,enabled:e}),N=(y??[]).filter(C=>C.loaded&&!C.disabled&&e5e(C.type,{cloud:l,nativeRunnerEnabled:c.data?.enableNativeRunner===!0})&&!["process","http"].includes(C.type)&&!Gm(C.type).comingSoon),S=N.some(C=>C.type===h);return(0,t.jsx)(qs,{open:e,onOpenChange:r(C=>{C||s()},"onOpenChange"),children:(0,t.jsxs)(Ws,{className:W("flex max-h-(--sz-calc-18) flex-col gap-0 overflow-hidden p-0 sm:max-w-(--sz-640px)",g==="name"&&"sm:max-w-(--sz-560px)"),children:[(0,t.jsxs)("div",{className:"flex items-center gap-2 px-6 py-5 text-xs text-muted-foreground","aria-label":"New agent progress",children:[(0,t.jsx)("span",{className:W(g==="name"&&"font-medium text-foreground"),children:"1. Name"}),(0,t.jsx)(An,{className:"size-3"}),(0,t.jsx)("span",{className:W(g==="adapter"&&"font-medium text-foreground"),children:"2. Adapter"})]}),(0,t.jsxs)("form",{className:"flex min-h-0 flex-col",onSubmit:r(C=>{C.preventDefault(),d.trim()&&(g==="name"?v("adapter"):S&&n({name:d.trim(),adapterType:h==="openai_dot"?"paperclip_runner":h,runnerProvider:h==="openai_dot"?"openai_dot":f}))},"onSubmit"),children:[(0,t.jsxs)("div",{className:"flex min-h-0 flex-col gap-7 overflow-y-auto px-6 pb-8 sm:px-10",children:[(0,t.jsxs)("div",{className:"flex flex-col items-center gap-4 text-center",children:[e&&(0,t.jsx)(bmt,{}),(0,t.jsxs)("div",{className:"space-y-2",children:[(0,t.jsx)(Qs,{className:"text-3xl font-semibold tracking-tight",children:g==="name"?"Meet your next agent":"Choose an adapter"}),(0,t.jsx)(mn,{className:"text-base",children:g==="name"?"Start with a name. Make them your own.":`How should ${d.trim()} work?`})]})]}),g==="name"?(0,t.jsxs)("div",{className:"space-y-2",children:[(0,t.jsx)("label",{htmlFor:o,className:"text-sm font-medium",children:"Agent name"}),(0,t.jsx)(dt,{id:o,autoFocus:!0,maxLength:100,placeholder:"e.g. Darnold",value:d,onChange:r(C=>u(C.target.value),"onChange"),className:"h-12 text-base"}),i&&(0,t.jsx)($,{type:"button",variant:"link",className:"px-0 text-muted-foreground",onClick:i,children:"Invite an external agent"})]}):(0,t.jsxs)("fieldset",{className:"space-y-4",children:[(0,t.jsx)("legend",{className:"sr-only",children:"Adapter"}),k&&(0,t.jsx)("p",{role:"status",className:"text-sm text-muted-foreground",children:"Loading adapters…"}),w&&(0,t.jsx)("p",{role:"alert",className:"text-sm text-destructive",children:w.message}),(0,t.jsx)("div",{className:W("grid grid-cols-2 gap-3",N.length!==4&&"sm:grid-cols-3"),children:N.map(C=>{const _=Gm(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)(B0,{type:C.type}),(0,t.jsx)("span",{className:"text-sm font-medium",children:_.label}),h===C.type&&(0,t.jsx)(cs,{className:"absolute right-2 top-2 size-3.5"})]})]},C.type)})}),S&&h==="paperclip_runner"&&(0,t.jsxs)("label",{className:"flex flex-col gap-2 text-sm font-medium",children:["Runner",(0,t.jsxs)("select",{className:"rounded-md border border-border bg-background px-3 py-2",value:f,onChange:r(C=>x(C.target.value),"onChange"),children:[(0,t.jsx)("option",{value:"codex",children:"Codex (app server)"}),(0,t.jsx)("option",{value:"claude",children:"Claude (ACPX)"}),(0,t.jsx)("option",{value:"grok",children:"Grok Build (ACPX)"}),(0,t.jsx)("option",{value:"opencode",children:"OpenCode"})]})]})]})]}),(0,t.jsxs)("div",{className:"flex justify-between gap-4 border-t border-border px-6 py-4",children:[(0,t.jsx)($,{type:"button",variant:"ghost",onClick:r(()=>g==="name"?s():v("name"),"onClick"),children:g==="name"?"Cancel":(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)(wl,{className:"size-4"}),"Back"]})}),(0,t.jsxs)($,{type:"submit",disabled:!d.trim()||g==="adapter"&&!S,children:[g==="name"?"Choose adapter":"Configure agent",(0,t.jsx)(fl,{className:"size-4"})]})]})]})]})})}r(t5e,"AgentBasicsDialog");var vmt={subscription:"Subscription",api:"API key",advanced:"Custom Gateway"};function ymt({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)(IS,{initial:!1,mode:"sync",children:(0,t.jsx)(Rl.span,{className:"absolute inset-0 flex items-center justify-center whitespace-nowrap",initial:{opacity:0,y:_re},animate:{opacity:1,y:0,transition:Kit},exit:{opacity:0,y:_re,transition:Qit},children:vmt[e]},e)})})}r(ymt,"CredentialTag");function jmt({source:e,mode:s,selected:n,onSelect:a,buttonRef:i,settling:o}){return(0,t.jsxs)("button",{ref:i,type:"button",role:"radio","aria-checked":n,onClick:a,className:W("flex min-w-0 flex-1 cursor-pointer flex-col items-center gap-1.5 self-stretch rounded-md border p-3","transition-(--tp-border-color-background-color) ease-(--motion-ease-standard)",o?"duration-(--motion-duration-slow)":"duration-(--motion-duration-fast)","outline-none focus-visible:ring-ring/50 focus-visible:ring-(length:--rad-3)",n?"border-foreground/40 bg-accent":"border-border bg-card hover:bg-accent/40"),children:[(0,t.jsx)("span",{className:"flex size-(--sz-30px) shrink-0 items-center justify-center",children:e.icon}),(0,t.jsx)("span",{className:"text-(length:--text-compact) font-medium text-foreground",children:e.label}),s?(0,t.jsx)(ymt,{mode:s}):(0,t.jsx)("span",{"aria-hidden":!0,className:"h-4"})]})}r(jmt,"ModelSourceTile");function s5e({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)(IS,{initial:!1,mode:"popLayout",children:u.map(h=>(0,t.jsx)(Rl.div,{layout:!0,transition:s_e,exit:{opacity:0,transition:tot},className:W("flex min-w-0",o?"w-(--sz-source-tile-two-up)":"flex-1"),children:(0,t.jsx)(jmt,{source:h,mode:h.credentialMode===void 0?s:h.credentialMode,selected:h.id===n,onSelect:r(()=>a(h.id),"onSelect"),settling:l,buttonRef:r(p=>{p?c.current.set(h.id,p):c.current.delete(h.id)},"buttonRef")})},h.id))})})}r(s5e,"ModelSourceTiles");var pD={subscription:"Use subscription instead",api:"Use API key instead"},wmt=["subscription","api"],hae={subscription:"api",api:"subscription"};function n5e({mode:e,onChange:s}){return(0,t.jsx)(kmt,{destination:hae[e],onClick:r(()=>s(hae[e]),"onClick"),modes:wmt})}r(n5e,"CredentialModeLink");function kmt({destination:e,onClick:s,modes:n}){return(0,t.jsxs)("button",{type:"button","aria-label":pD[e],onClick:s,className:W("group grid cursor-pointer px-3 py-2 text-left text-sm font-medium","rounded-md outline-none focus-visible:ring-ring/50 focus-visible:ring-(length:--rad-3)"),children:[n.map(a=>(0,t.jsx)("span",{"aria-hidden":!0,className:"invisible col-start-1 row-start-1 whitespace-nowrap",children:pD[a]},a)),(0,t.jsx)(IS,{initial:!1,mode:"sync",children:(0,t.jsx)(Rl.span,{className:W("col-start-1 row-start-1 justify-self-start whitespace-nowrap","underline decoration-muted-foreground/40 underline-offset-4","text-muted-foreground transition-colors","group-hover:text-foreground group-hover:decoration-foreground/40"),initial:{opacity:0},animate:{opacity:1,transition:wV},exit:{opacity:0,transition:Wit},children:pD[e]},e)})]})}r(kmt,"ModeLink");function qz({onBack:e,primaryLabel:s,primaryDisabled:n,loading:a,loadingLabel:i,primaryIcon:o,onPrimary:l}){const c=a&&i?i:s,d=o??(a?"spinner":"arrow");return(0,t.jsxs)("div",{className:"flex items-center justify-between pt-9",children:[e?(0,t.jsxs)($,{variant:"ghost",size:"lg",className:"rounded-full has-[>svg]:pl-4 has-[>svg]:pr-5",onClick:e,disabled:a,children:[(0,t.jsx)(wl,{className:"mr-1 size-3.5"}),"Back"]}):(0,t.jsx)("span",{}),(0,t.jsx)(Rl.div,{layout:!0,transition:Git,className:"min-w-0",children:(0,t.jsx)($,{size:"lg",className:"w-full rounded-full px-6",onClick:l,disabled:n||a,children:(0,t.jsxs)(Rl.span,{className:"flex items-center whitespace-nowrap",initial:{opacity:0},animate:{opacity:1},transition:Yit,children:[d==="spinner"?(0,t.jsx)(st,{className:"mr-1 size-4 animate-spin"}):null,c,d==="arrow"?(0,t.jsx)(fl,{className:"ml-1 size-3.5"}):null]},`${c}:${d}`)})})]})}r(qz,"FooterNav");function r5e({companyId:e,adapterType:s,environmentId:n,canLogin:a,localEnvironment:i=!1,onConnected:o,onDraftChanged:l,onBack:c,testConnection:d,testError:u,managedAccount:h,advancedConnection:p}){const f=te({queryKey:M.health,queryFn:Iu.get,enabled:i}),x=i&&(f.data?.localAiLoginSupported??f.data?.deploymentMode==="local_trusted"),g=(0,m.useRef)(0);(0,m.useEffect)(()=>()=>{g.current++},[]);const v=r(()=>{g.current++,Q(!1),C(!1),R(null),T("preparing")},"cancel"),[y,k]=(0,m.useState)(h?.initialMethod==="api_key"?"api":h?"subscription":null),[w,N]=(0,m.useState)(!1),[S,C]=(0,m.useState)(!!(p||h)),[_,R]=(0,m.useState)(null),[I,T]=(0,m.useState)("preparing"),E=(0,m.useRef)("ready"),[L,O]=(0,m.useState)(""),[P,Q]=(0,m.useState)(!1),[D,F]=(0,m.useState)(null),[z,K]=(0,m.useState)(null),U=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",G=s==="claude_local"?"anthropic":s==="grok_local"?"xai":"openai",se=ECe(e,q),Z=h?{...se,options:[],subscriptions:[],loading:!1}:se,[ie,J]=(0,m.useState)(null),re=Z.subscriptions.length?Z.subscriptions.find(Le=>Le.id===(ie??Z.subscriptions[0]?.id)):void 0,[oe,V]=(0,m.useState)(null),X=Z.options.find(Le=>Le.id===(oe??Z.options[0]?.id)),Y=h?{...Z.storedLogin,data:void 0,isPending:!1,isError:!1}:Z.storedLogin,ae=(0,m.useRef)(null),ne=y??(Z.subscriptions.length>0||s==="claude_local"&&!re&&Y.data?"subscription":Z.options.length?"api":"subscription"),ce=ne==="api"?"api_key":"subscription",he=h?.intent.connectionId&&(h.fixedMethod!==!1||h.initialMethod===ce),pe=h?{...h.intent,connectionId:he?h.intent.connectionId:void 0,name:he?h.intent.name:h.nameForMethod?.(ce)??h.intent.name}:void 0,ge=ZSe(e,pe??{provider:G,method:"subscription",name:`My ${U} subscription`,ownership:"personal",agentIds:[],allAgents:!0},!w&&x&&ne==="subscription"&&!re&&!Y.data),Ee=te({queryKey:M.agents.authSignal(e,s,n),queryFn:r(()=>_t.getAdapterAuthSignal(e,s,n??void 0),"queryFn"),retry:!1,enabled:!h&&!w});async function de(){if(P||h?.disabled)return;const Le=++g.current;Q(!0),F(null);try{if(h&&pe){if(ne==="subscription"&&!x)return;const Ae=ae.current??await(ne==="api"?Ll.create(e,{...pe,method:"api_key",apiKey:L.trim()}):ge.connect(pe));ae.current=Ae,O(""),Le===g.current&&h.onComplete({...Ae,method:ne==="api"?"api_key":"subscription"});return}let Ie=ne==="api"?X?X.aiConnection?{env:{},aiConnection:X.aiConnection}:{env:{[q]:X.binding}}:z??{env:{},credentials:{[q]:L.trim()}}:{...re?.aiConnection?{aiConnection:re.aiConnection}:{},env:re?.binding?{CODEX_HOME:re.binding}:{},...s==="claude_local"&&!re&&Y.data?{env:nk(),applyStoredClaudeLogin:!0}:{}};if(ne==="subscription"&&x&&!re&&!Y.data&&(ae.current??=await ge.connect(),Ie={env:{},aiConnection:{provider:G,method:"subscription",mode:"responsible_user"}}),Ie.credentials&&(await Ll.create(e,{provider:G,method:"api_key",name:`My ${U} API`,ownership:"personal",apiKey:Ie.credentials[q],agentIds:[],allAgents:!0}),Ie={env:{},aiConnection:{provider:G,method:"api_key",mode:"responsible_user"}}),Le!==g.current)return;ne==="api"&&(O(""),X||K(Ie));const ye=await d(Ie);if(Le!==g.current)return;ye?o(Ie):F("The provider did not respond. Check the connection and try again.")}catch(Ie){if(Le!==g.current)return;h&&O(""),F(Ie instanceof Error?Ie.message:"Could not connect to the provider.")}finally{Le===g.current&&Q(!1)}}r(de,"connect");const Ne=ne==="subscription"&&a&&n&&!re&&!Z.loading&&!Y.data&&(!!h||Ee.data?.status!=="present"||ie===""),le=r(Le=>{p&&Le===(w?"advanced":ne)||(l?.(),v(),N(Le==="advanced"),C(p?!0:S),ae.current=null,Le!=="advanced"&&k(Le),O(""),K(null),F(null))},"switchMode");return(0,t.jsxs)("div",{className:"min-w-0 max-w-full",children:[(0,t.jsx)(s5e,{label:p?"Connection type":"Connect your model provider",sources:p?[{id:"subscription",label:U,icon:(0,t.jsx)(B0,{type:s}),credentialMode:"subscription"},{id:"api",label:U,icon:(0,t.jsx)(B0,{type:s}),credentialMode:"api"},{id:"advanced",label:"Advanced",icon:(0,t.jsx)(WKe,{className:"size-6 text-muted-foreground"}),credentialMode:"advanced"}]:[{id:s,label:U,icon:(0,t.jsx)(B0,{type:s})}],mode:w?"advanced":ne,selectedId:p?w?"advanced":ne:S?s:null,collapsed:!p&&S,onSelect:r(Le=>{h?.disabled||(p?le(Le):C(!0))},"onSelect")}),!p&&(!S||h)&&!h?.fixedMethod&&(0,t.jsx)("div",{className:"-ml-3 mt-1",children:(0,t.jsx)(n5e,{mode:ne,onChange:le})}),w&&p?(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)("div",{className:"pt-5",children:p.content}),(0,t.jsx)(qz,{onBack:c,primaryLabel:"Use connection",primaryDisabled:!p.value,onPrimary:r(()=>{p.value&&o({env:{},aiConnection:p.value})},"onPrimary")})]}):(0,t.jsxs)(t.Fragment,{children:[!S&&Z.options.length>0&&(0,t.jsxs)("p",{className:"mt-2 text-sm text-muted-foreground",children:[Z.options.length," saved API"," ",Z.options.length===1?"key available":"keys available","."]}),ne==="subscription"&&Z.subscriptions.length>0&&(0,t.jsx)("div",{className:p?"pt-5":void 0,children:(0,t.jsx)(Ik,{options:Z.subscriptions,value:re?.id??"",onChange:r(Le=>{l?.(),J(Le)},"onChange"),loading:!1,error:!1,kind:"subscription",disabled:P})}),(0,t.jsx)(Rl.div,{initial:!1,animate:{height:S?"auto":0,opacity:S?1:0},transition:{height:Vd,opacity:NM},className:"overflow-hidden",children:S&&(0,t.jsx)("div",{className:"pt-5",children:ne==="api"?(0,t.jsxs)(SM,{instruction:Z.options.length?"Choose a saved API key or enter a new one":`Provide your ${U} API key to connect`,children:[(0,t.jsx)(Ik,{...Z,value:X?.id??"",disabled:P,onChange:r(Le=>{l?.(),V(Le),O(""),K(null),F(null)},"onChange")}),!X&&(0,t.jsx)(X3,{label:"API key",masked:!0,autoFocus:!0,value:L,placeholder:z?"Key entered. Retry the connection.":"Enter API key here",onChange:r(Le=>{l?.(),V(""),O(Le),K(null)},"onChange"),onSubmit:r(()=>{de()},"onSubmit"),disabled:P})]}):Ne?(0,t.jsx)(MV,{companyId:e,adapterType:s,environmentId:n,chrome:"onboarding",aiConnection:pe??{provider:G,method:"subscription",name:`My ${U} subscription`,ownership:"personal",agentIds:[],allAgents:!0},autoStart:!0,onStored:r(()=>{},"onStored"),onPromptReady:r(Le=>{R(Le),T(Ie=>Le?Ie==="preparing"?"ready":Ie:"preparing")},"onPromptReady"),onCodeSubmitted:r(()=>{E.current=I==="waiting"?"waiting":"ready",T("connecting")},"onCodeSubmitted"),onSubmitFailed:r(()=>{T(Le=>Le==="connecting"?E.current:Le)},"onSubmitFailed"),onConnected:r(Le=>{if(h){if(!Le){F("The login did not return a saved connection. Try again.");return}const ye=g.current;T("connecting"),Ll.loginResult(e,Le).then(Ae=>{ye===g.current&&h.onComplete({...Ae,method:"subscription"})}).catch(()=>{ye===g.current&&(T("ready"),F("Could not retrieve the saved connection. Go back and retry."))});return}const Ie={env:{},aiConnection:{provider:G,method:"subscription",mode:"responsible_user"}};K(Ie),o(Ie)},"onConnected")}):re?null:x&&!Y.data?(0,t.jsx)(SV,{adapterType:s,login:{...ge,retry:r(()=>{F(null),ge.retry()},"retry")}}):(0,t.jsx)("p",{className:"text-sm text-muted-foreground",children:Y.data?"Use your saved Claude subscription for this agent.":a?"Use the existing provider connection for this environment.":"This environment does not support browser sign-in. Choose a sign-in environment or connect with an API key."})})}),ne==="subscription"&&Y.isError&&(0,t.jsx)("p",{role:"alert",className:"mt-4 text-sm text-destructive",children:"Could not check your saved Claude subscription. Try again."}),D&&(0,t.jsx)("p",{role:"alert",className:"mt-4 text-sm text-destructive",children:u??D}),i&&f.isError&&(0,t.jsx)("p",{role:"alert",className:"mt-4 text-sm text-destructive",children:"Could not prepare sign-in. Reload this page to try again."}),(0,t.jsx)(qz,{onBack:r(()=>{S&&!p?v():c()},"onBack"),primaryLabel:S&&Ne?I==="waiting"?"Waiting for code":I==="connecting"?"Connecting":`Sign in to ${U}`:P?"Connecting":ne==="subscription"&&(Y.data||re)?"Use saved subscription":ne==="api"&&X?"Use saved API key":"Connect",primaryDisabled:h?.disabled||!!h&&ne==="subscription"&&!a&&!x||i&&f.isPending||ge.preparing||!!ge.error||ne==="subscription"&&x&&!re&&!Y.data&&ge.status!=="ready"||!h&&Ee.isPending||Z.loading||s==="claude_local"&&Y.isPending||!S&&!(ne==="subscription"&&re)||!!Ne&&(!_||I!=="ready")||ne==="api"&&!L.trim()&&!z&&!X,loading:P,primaryIcon:S&&Ne?I==="ready"?"none":"spinner":void 0,onPrimary:r(()=>{if(Ne){if(!_||I!=="ready")return;window.open(_,"_blank","noreferrer,noopener"),T("waiting")}else de()},"onPrimary")})]})]})}r(r5e,"AgentProviderConnection");function S5(e){return e.provider==="openrouter"||e.provider==="google"?(0,t.jsx)(Smt,{...e}):(0,t.jsx)(Nmt,{...e})}r(S5,"AiConnectionCredentialStep");function Nmt({companyId:e,provider:s,initialMethod:n,fixedMethod:a,connectionId:i,name:o,hideName:l,nameForMethod:c,ownership:d,agentIds:u,allAgents:h,environmentId:p,onComplete:f,onCancel:x,defaults:g,disabled:v}){const[y,k]=(0,m.useState)(o),[w,N]=(0,m.useState)(),S=kt(),C=te({queryKey:M.environments.list(e),queryFn:r(()=>Fi.list(e),"queryFn")}),_=te({queryKey:M.environments.capabilities(e),queryFn:r(()=>Fi.capabilities(e),"queryFn")}),R=te({queryKey:M.instance.settings,queryFn:jr.get}),I=te({queryKey:M.instance.experimentalSettings,queryFn:jr.getExperimental}),T=te({queryKey:M.instance.generalSettings,queryFn:jr.getGeneral}),E=LV(T.data?.executionMode,C.data??[]);let L=null,O;try{L=E.forced?E.kubernetesEnvironment?.id??null:wN({agentDefaultEnvironmentId:p??w,instanceDefaultEnvironmentId:R.data?.defaultEnvironmentId,localDefaultEnvironmentId:NN(C.data),managedSandboxOnly:I.data?.enableManagedSandboxOnly,managedSandboxEnvironmentId:kN(C.data),visibleEnvironmentIds:C.data?.map(q=>q.id)})}catch(q){O=q instanceof Error?q.message:"Could not resolve the sign-in environment."}const P=(C.data??[]).filter(q=>q.status==="active"&&(q.driver==="local"||q.driver==="sandbox"&&typeof q.config.provider=="string"&&_.data?.sandboxProviders?.[q.config.provider]?.supportsLoginPty===!0));!E.forced&&!p&&!w&&!P.some(q=>q.id===L)&&(L=P[0]?.id??null);const Q=C.data?.find(q=>q.id===L),D=typeof Q?.config.provider=="string"?Q.config.provider:"",F=Q?.driver==="sandbox"&&_.data?.sandboxProviders?.[D]?.supportsLoginPty===!0,z=[C,_,R,I,T].some(q=>q.isPending),K=O??[C,_,R,I,T].find(q=>q.error)?.error?.message,U={provider:s,method:"subscription",name:y,ownership:d,agentIds:u,allAgents:h,connectionId:i};return(0,t.jsxs)("div",{className:"mx-auto w-full min-w-0 max-w-xl space-y-6",children:[!l&&(0,t.jsxs)("label",{className:"block space-y-2 text-sm",children:["Connection name",(0,t.jsx)(dt,{value:y,onChange:r(q=>k(q.target.value),"onChange"),disabled:!!i})]}),!p&&!E.forced&&P.length>1&&(0,t.jsxs)(Ca,{value:L??"",onValueChange:N,children:[(0,t.jsx)(Na,{"aria-label":"Sign-in environment",children:(0,t.jsx)(Sa,{placeholder:"Sign-in environment"})}),(0,t.jsx)(_a,{children:P.map(q=>(0,t.jsx)(un,{value:q.id,children:q.name},q.id))})]}),K&&(0,t.jsx)("p",{role:"alert",className:"text-sm text-destructive",children:K}),g,z?(0,t.jsx)("p",{role:"status",className:"text-sm text-muted-foreground",children:"Preparing sign-in…"}):(0,t.jsx)(r5e,{companyId:e,adapterType:s==="anthropic"?"claude_local":s==="xai"?"grok_local":"codex_local",environmentId:L,canLogin:F,localEnvironment:Q?.driver==="local",onBack:x,onConnected:r(()=>{},"onConnected"),testConnection:r(async()=>!1,"testConnection"),managedAccount:{intent:U,nameForMethod:c,initialMethod:n,fixedMethod:a??!!i,disabled:v||z||!!K||!y.trim(),onComplete:r(q=>{S.invalidateQueries({queryKey:["ai-connections",e]}),S.invalidateQueries({queryKey:["tools"]}),f(q)},"onComplete")}},L??"local")]})}r(Nmt,"SubscriptionConnectionStep");function Smt({companyId:e,provider:s,connectionId:n,name:a,hideName:i,nameForMethod:o,ownership:l,agentIds:c,allAgents:d,onComplete:u,onCancel:h,defaults:p,disabled:f}){const[x,g]=(0,m.useState)(a),[v,y]=(0,m.useState)(""),k=kt(),w=je({mutationFn:r(()=>Ll.create(e,{provider:s,method:"api_key",name:n?x:o?.("api_key")??x,ownership:l,agentIds:c,allAgents:d,connectionId:n,apiKey:v}),"mutationFn"),onSuccess:r(N=>{k.invalidateQueries({queryKey:["ai-connections",e]}),k.invalidateQueries({queryKey:["tools"]}),u({...N,method:"api_key"})},"onSuccess"),onSettled:r(()=>y(""),"onSettled")});return(0,t.jsxs)("div",{className:"mx-auto w-full min-w-0 max-w-xl space-y-4",children:[!i&&(0,t.jsxs)("label",{className:"block space-y-2 text-sm",children:["Connection name",(0,t.jsx)(dt,{value:x,onChange:r(N=>g(N.target.value),"onChange"),disabled:!!n})]}),w.error&&(0,t.jsx)("p",{role:"alert",className:"text-sm text-destructive",children:w.error.message}),(0,t.jsx)(a_e,{providerName:s==="google"?"Google":"OpenRouter",value:v,onChange:y,onSubmit:r(()=>w.mutate(),"onSubmit"),disabled:f||w.isPending,placeholder:"Enter API key here",autoFocus:!0}),p,(0,t.jsxs)("div",{className:"flex justify-between gap-2",children:[(0,t.jsx)($,{variant:"ghost",onClick:h,children:"Cancel"}),(0,t.jsx)($,{disabled:f||!x.trim()||!v.trim()||w.isPending,onClick:r(()=>w.mutate(),"onClick"),children:w.isPending?"Connecting…":"Connect"})]})]})}r(Smt,"ApiKeyConnectionStep");var Cmt=null;function cw(){const e=(0,m.useContext)(h3),{data:s,isFetched:n,isError:a}=te({queryKey:M.instance.experimentalSettings,queryFn:r(()=>jr.getExperimental(),"queryFn"),enabled:e!=null},e??(Cmt??=new rS));return e?{enabled:!a&&s?.enableChatConnectors===!0,githubEnabled:!a&&s?.enableGitHubReviewBots===!0,loaded:n}:{enabled:!1,githubEnabled:!1,loaded:!0}}r(cw,"useChatConnectorsEnabled");function Zp(e,s,n){return e==="agentmail"||(e==="github"||e==="github-code-review-bot"?n:s)}r(Zp,"chatProviderVisible");var _mt=new RegExp(`\\b(${["mcp","server","profile","policy","gateway","transport","stdio","endpoint"].join("|")})s?\\b`,"gi");function a5e(e){return e.replace(_mt,"").replace(/\s{2,}/g," ").replace(/\s+([.,])/g,"$1").trim()}r(a5e,"sanitizeProsumerCopy");var Amt={zapier:{tagline:"Reach 9,000+ apps your team already uses.",short:"Reach 9,000+ apps from your agents."},github:{tagline:"Read code and pull requests, comment on issues.",short:"Read code and pull requests, comment on issues."},slack:{tagline:"Send and read messages in your team's channels.",short:"Send and read messages in your channels."},notion:{tagline:"Read and update pages in your workspace.",short:"Read and update pages in your workspace."},railway:{tagline:"Inspect services, read logs, and manage deployments.",short:"Connect Railway for deployments, logs, and container access."},posthog:{tagline:"Explore product usage, errors, flags, and experiments.",short:"Sign in with PostHog. Project pinning and access controls are optional."},gauge:{tagline:"Track your brand in AI answers and run content workflows.",short:"Sign in with Gauge and pick an organization. API keys are optional."},neon:{tagline:"Manage Postgres projects, branches, and queries.",short:"Sign in with Neon. Project pinning and read-only mode are optional."},superagent:{tagline:"Review security findings and run red-team checks.",short:"Connect with a Superagent API key. Billable and destructive tools stay under action policies."},linear:{tagline:"Create, update and read tickets.",short:"Create, update and read tickets."},"google-sheets":{tagline:"Read and update selected spreadsheets.",short:"Read spreadsheets or update the files you choose."},gmail:{tagline:"Read mail and create drafts for your review.",short:"Read mail and create drafts for your review."},"google-drive":{tagline:"Find, read, and create files in Drive.",short:"Find, read, and create files in Drive."},"google-docs":{tagline:"Read and update documents.",short:"Read and update documents."},"google-slides":{tagline:"Read and update presentations.",short:"Read and update presentations."},"google-calendar":{tagline:"Review calendars and manage events.",short:"Review calendars and manage events."},"google-chat":{tagline:"Read conversations and send messages.",short:"Read conversations and send messages."},"google-people":{tagline:"Look up contacts and people in your directory.",short:"Look up contacts and people in your directory."},"google-workspace-search":{tagline:"Search across your Google workspace.",short:"Search across your Google workspace."},hubspot:{tagline:"Look up contacts and update deal stages.",short:"Look up contacts and update deal stages."},intercom:{tagline:"Read and reply to customer conversations.",short:"Read and reply to customer conversations."},figma:{tagline:"Read files and post comments on frames.",short:"Read files and post comments on frames."},stripe:{tagline:"Read customers, invoices, and payouts.",short:"Read customers, invoices, and payouts."},context7:{tagline:"Look up up-to-date docs for your libraries.",short:"Look up up-to-date docs for your libraries."}},Imt={tagline:"Give your agents access to this app.",short:"Give your agents access to this app."};function i5e(e,s){const n=Amt[e];if(n)return n;if(s){const a=a5e(s);if(a)return{tagline:a,short:a}}return Imt}r(i5e,"appCopyFor");function pae(e,s,n){return n<=1?`Your ${e} key`:a5e(s)||`Your ${e} key`}r(pae,"credentialFieldLabel");var Tmt=1500;function Z0(e=Tmt){const[s,n]=(0,m.useState)("idle"),a=(0,m.useRef)(null),i=(0,m.useRef)(0);(0,m.useEffect)(()=>()=>{a.current!==null&&window.clearTimeout(a.current)},[]);const o=(0,m.useCallback)(async l=>{const c=++i.current;let d="copied";try{await wa(l)}catch{d="failed"}return i.current!==c||(n(d),a.current!==null&&window.clearTimeout(a.current),a.current=window.setTimeout(()=>{i.current===c&&(n("idle"),a.current=null)},e)),d},[e]);return{status:s,copied:s==="copied",failed:s==="failed",copy:o}}r(Z0,"useCopyAction");function TM(){const e=bd()?.pushToast;return(0,m.useCallback)(async(s,n="Copied")=>{try{return await wa(s),e?.({title:n,tone:"success",dedupeKey:`copy:${n}`}),!0}catch{return e?.({title:"Couldn’t copy to clipboard",body:"Select and copy the value manually.",tone:"error",dedupeKey:"copy-failed"}),!1}},[e])}r(TM,"useCopyToast");var Rmt="/cloud/connections/handoff",Emt="/cloud/connections/reauth",EE="paperclip.cloud-oauth-handoff.v1",Ux=class extends Error{static{r(this,"OAuthHandoffError")}code;constructor(e,s){super(e),this.code=s,this.name="OAuthHandoffError"}};function DV(e){if(e===void 0)return null;if(!e||typeof e!="object"||Array.isArray(e))throw new Ux("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 Ux("Paperclip Cloud returned an invalid sign-in handoff.","invalid_handoff");return{kind:"paperclip_cloud",session:s.session}}r(DV,"parseHandoff");function Lmt(e,s){return e===404||s==="SESSION_NOT_AVAILABLE"?new Ux("This sign-in expired. Start the connection again.","expired"):e===401||e===403?new Ux("Paperclip Cloud could not authorize this connection for your account.","forbidden"):new Ux("Paperclip Cloud couldn’t prepare secure sign-in. Try again.","unavailable")}r(Lmt,"handoffFailure");async function Mmt(e,s){const n=s.request??fetch;let a,i;for(let o=0;o<2;o+=1)try{if(a=await n(Rmt,{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 Ux(i instanceof Error?i.message:"Paperclip Cloud couldn’t prepare secure sign-in. Try again.","unavailable")}r(Mmt,"postCloudHandoff");function Pmt(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!==Emt||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(Pmt,"exactReauthenticationTarget");async function AN(e,s={}){const n=DV(e.handoff);if(!n){const l=iE(e.authorizationUrl);if(!l.ok)throw new Ux(l.message,"invalid_handoff");return{kind:"authorization",url:l.url,host:l.host}}const a=await Mmt(n.session,s),i=await a.json().catch(()=>null);if(!a.ok){if(i?.error==="RECENT_LOGIN_REQUIRED"){const l=Pmt(i.reauthenticationUrl,n.session);if(l)return l}throw Lmt(a.status,i?.error)}const o=iE(typeof i?.authorizationUrl=="string"?i.authorizationUrl:void 0);if(!o.ok)throw new Ux("Paperclip Cloud returned an invalid provider sign-in address.","invalid_handoff");return{kind:"authorization",url:o.url,host:o.host}}r(AN,"prepareOAuthNavigation");function C5(e,s=window.sessionStorage){const n=DV({kind:"paperclip_cloud",session:e});if(!n)throw new Ux("Paperclip Cloud returned an invalid sign-in handoff.","invalid_handoff");const a={version:1,session:n.session,savedAt:Date.now()};s.setItem(EE,JSON.stringify(a))}r(C5,"savePendingCloudHandoff");function Dmt(e=window.sessionStorage){const s=e.getItem(EE);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 DV({kind:"paperclip_cloud",session:n.session})}catch{return e.removeItem(EE),null}}r(Dmt,"readPendingCloudHandoff");function fae(e=window.sessionStorage){e.removeItem(EE)}r(fae,"clearPendingCloudHandoff");function RM(e){return!!(e&&ube({...e,methods:e.methods.filter(s=>(s.purpose??"tool")!=="channel"&&s.transport!=="chat_sdk")}))}r(RM,"appSupportsToolCatalogSetup");var $mt=UOe.filter(e=>Bbe(e).some(s=>A0(s))).map(e=>e.slug);function Omt(e){return $mt.some(s=>s===e)}r(Omt,"isMcpDirectOAuthConnectSlug");function _5(e,s){const n=new URLSearchParams({source:e});return s&&n.set("intent",s),`/apps/connect?${n.toString()}`}r(_5,"appSourceConnectHref");function xae(e,s){return`/apps/connect?${new URLSearchParams({source:e,resume:s}).toString()}`}r(xae,"appSourceResumeHref");function fD(e){return e?`/apps/vercel-connect?${new URLSearchParams({source:e}).toString()}`:"/apps/vercel-connect"}r(fD,"vercelConnectSourceHref");function Bmt(e){return e.serviceSlug??e.appKey??e.sourceSlug??void 0}r(Bmt,"resolveAppsConnectRouteKey");function Fmt(e,{chatConnectorsEnabled:s=!1,githubReviewBotsEnabled:n=!1}={}){if(e.get("byo")==="1")return!!(e.get("reconnect")?.trim()&&e.get("applicationId")?.trim()&&e.get("link")?.trim());const a=e.get("source")??"";if(["google-ai","gateway"].includes(a)||/^ai-router-(?:[a-f0-9]{2})+$/.test(a))return!0;const i=ZN(a),o=a==="github-code-review-bot"?n:s;return!o&&i?.methods.some(l=>l.transport==="chat_sdk")&&!i.methods.some(l=>(l.purpose??"tool")!=="channel"&&l.transport!=="chat_sdk")?!1:fj(a)&&(e.get("reconnect")?.trim()||e.get("resume")?.trim())?!0:a==="agentmail"||o?ube(i):RM(i)}r(Fmt,"canEnterAppsConnect");var xD=" for the organization",zmt=" for the company";function gae(e,s){const n=e.trim();if(s!=="organization")return n;const a=n.toLocaleLowerCase();return a.endsWith(xD)?n:a.endsWith(zmt)?`${n.slice(0,n.length-16).trimEnd()}${xD}`:`${n}${xD}`}r(gae,"connectionNameForGrantKind");function qmt(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(qmt,"grantStatusLabel");function Umt(e){switch(e){case"active":return"connected";case"needs_reauthorization":case"expired":return"attention";case"revoked":return"inactive";default:return"missing"}}r(Umt,"grantStatusTone");function Kmt(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(Kmt,"grantAccountLabel");function Qmt(e){return new Set((e?.members??[]).filter(s=>s.subjectType==="user").map(s=>s.subjectId))}r(Qmt,"audienceUserIds");function Wmt(e){return e.find(s=>s.kind==="organization"&&s.isDefault)??e.find(s=>s.kind==="organization")??null}r(Wmt,"organizationGrant");function Hmt(e,s){return s?e.find(n=>n.kind==="user"&&n.subjectUserId===s)??null:null}r(Hmt,"personalGrantFor");function Vmt(e,s){if(!s)return null;const n=e.find(a=>a.userId===s);return n&&(n.name?.trim()||n.email?.trim())||null}r(Vmt,"memberLabel");var bae=0;function Uz(){return bae+=1,{id:`header-${bae}`,name:"",value:""}}r(Uz,"newCustomHeaderRow");function x_(e){try{return new URL(e).host||null}catch{return null}}r(x_,"endpointHost");function Gmt(e=window.location.origin,s){if(s)return s;const n=new URL("/api/tools/oauth/callback",e),a=n.hostname.toLowerCase().replace(/^\[|\]$/g,"");return n.protocol==="http:"&&(a==="127.0.0.1"||a==="::1")&&(n.hostname="localhost"),n.toString()}r(Gmt,"oauthCallbackUrlForBrowser");function gD(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(gD,"defaultGenericMcpName");function vae(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(vae,"genericConnectGuidance");function o5e(e){const s=new Set;for(const n of e){const a=n.name.trim();if(!a&&!n.value.trim())continue;const i=kBe(a);if(!i.ok)return Zee(a,i.reason);const o=gBe(n.value);if(!o.ok)return Zee(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(o5e,"customHeaderError");function Ymt(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(Ymt,"genericConnectPayload");function Zmt(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&&o5e(e.headers)===null:!0:!1}r(Zmt,"canSubmitGenericConnect");function IN(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(IN,"installStateFrom");function l5e(e,s){return e.onAll||e.agentIds.has(s)}r(l5e,"isAgentInstalled");function c5e(e,s){return s.onAll?[{targetType:"company",targetId:e}]:[...s.agentIds].map(n=>({targetType:"agent",targetId:n}))}r(c5e,"installPayload");var Jmt="Has access — tick to load its tools into this agent's context.";function d5e(e){return`paperclip.connector-enrollment-access:${e}`}r(d5e,"enrollmentAccessStorageKey");function Xmt(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(Xmt,"validEnrollmentAccessState");function eht(e,s,n){try{window.sessionStorage.setItem(d5e(s),JSON.stringify({...n,companyId:e}))}catch{}}r(eht,"saveEnrollmentAccessState");function tht(e){const s=d5e(e);try{const n=window.sessionStorage.getItem(s);if(window.sessionStorage.removeItem(s),!n)return null;const a=JSON.parse(n);return Xmt(a)?a:null}catch{return null}}r(tht,"consumeEnrollmentAccessState");function yae(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(yae,"githubRecoveryUrl");function jae(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(jae,"oauthCallbackErrorMessage");var sht={key:"setup",success:"complete"};function wae(e){return e.requestedAppKey||e.hasPrefilledLink||e.zapierSource?"key":"gallery"}r(wae,"requestedConnectionInitialStep");function nht(e){const s=e.galleryApps.find(a=>a.slug===e.requestedAppKey);if(s)return s;if(u5e({requestedAppKey:e.requestedAppKey,resumeConnection:e.resumeConnection,resumeApplication:e.resumeApplication,completedResumeConnectionId:e.completedResumeConnectionId}))return fj(e.requestedAppKey);if(!e.reconnectConnection)return null;const n=e.applications.find(a=>a.id===e.reconnectConnection?.applicationId);return vf(n)!==e.requestedAppKey?null:fj(e.requestedAppKey)}r(nht,"requestedConnectionEntry");function u5e(e){const{requestedAppKey:s,resumeConnection:n,resumeApplication:a,completedResumeConnectionId:i}=e;return!!(n&&(n.status==="draft"||n.status==="active"&&n.id===i)&&a&&n.applicationId===a.id&&n.companyId===a.companyId&&vf(a)===s&&pu(n)===s)}r(u5e,"retainedResumeMatches");function rht(e){return!e.reconnectConnection||!e.reconnectApplication||e.reconnectConnection.applicationId!==e.reconnectApplication.id?!1:e.requestedAppKey?vf(e.reconnectApplication)===e.requestedAppKey:e.byo&&e.applicationId===e.reconnectApplication.id}r(rht,"retainedReconnectMatches");function aht(e){return e.credentialSource==="vercel_connect"&&!e.available&&!e.retainedReconnectMatches}r(aht,"isVercelConnectUnavailable");function iht(e){return e.available===!1&&!(e.reconnectConnectionId&&e.reconnectSourceMatches)}r(iht,"isConnectionDefinitionUnavailable");function oht(e){return!e.hasRequestedEntry||e.supportedMethodCount===0||e.unsupportedOAuth||e.vercelUnavailable||e.definitionUnavailable?e.reconnectConnectionId?"reconnect_unavailable":"fallback":"ready"}r(oht,"requestedConnectionSetupResolution");function kae(e,s,n,a){const i=sht[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(kae,"appConnectHref");function DI(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(DI,"withConnectionIntent");var Nae=["Pick app","Add your key"],Sae={gallery:0,key:1},lht={key:0},cht=["Add MCP URL"],dht=["Sign in"];function bD(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(bD,"defaultGrantKindFor");function uht(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(uht,"configuredAgentIdentity");function EC(e,s){const n=typeof s=="string"?s:s?.key;return e?.slug==="google-sheets"&&n==="local"}r(EC,"isGoogleSheetsRobotMethod");function $2(e){return e?Object.fromEntries([...e.tenantFields??[],...e.extensionFields??[]].filter(s=>s.defaultValue!==void 0).map(s=>[s.key,s.defaultValue])):{}}r($2,"defaultMethodConfig");function O1(e,s){if(!e)return[];const n=sA(e);return s==="vercel_connect"?n.filter(a=>!!a.credentialSources?.vercelConnect):n}r(O1,"connectionMethodsForCredentialSource");function sA(e){return Bbe(e).filter(s=>(s.purpose??"tool")!=="channel")}r(sA,"availableToolConnectionMethods");function $I(e,s){const n=sA(e);return s?n.find(a=>a.key===s)??null:UQ(n)}r($I,"availableToolConnectionMethod");function Ek(e){return UQ(e)}r(Ek,"recommendedSetupConnectionMethod");function Cae(e){return Ek(e?e.methods.filter(s=>(s.purpose??"tool")==="tool"&&(s.oauthStrategy==="paperclip_cloud_connector"||s.oauthStrategy==="paperclip_id_connector")):[])}r(Cae,"recommendedManagedConnectorMethod");function _ae(e){if(!e)return!1;const s=sA(e),n=s.length===1?s[0]:null;return!!(n&&A0(n)&&!QOe(n))}r(_ae,"canUseAutomaticOAuthFastPath");function Aae(e){if(!e)return null;const s=sA(e),n=s.length===1?s[0]:null;return n&&A0(n)?n:null}r(Aae,"automaticOAuthMethod");function mht(e){const s=e.metadata;if(!s)return null;const n=s.sourceTemplateKey??s.galleryKey;return typeof n=="string"?n:null}r(mht,"appSourceSlug");function hht(e){const s=e.config?.sourceTemplateKey??e.transportConfig.sourceTemplateKey;return typeof s=="string"?s:null}r(hht,"connectionSourceSlug");function Iae(e,s,n,a={}){if(!e)return null;const i=new Set(s.filter(o=>o.status!=="archived"&&mht(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)||hht(o)===e;return o.status!=="archived"&&(!a.draftOnly||o.status==="draft")&&o.authKind==="oauth"&&l})??null}r(Iae,"reusableOAuthConnection");function m5e(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(m5e,"readConnectionIntentOAuthOutcome");function ES(e={}){const[s]=hi(),n=ga(),{selectedCompanyId:a}=ps(),i=MH(),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&&s_(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||s_(l)||q6(l))),h=te({queryKey:["tools","connection",d],queryFn:r(()=>ts.getConnection(d),"queryFn"),enabled:u}),p=l||h.data?.config?.sourceTemplateKey,f=s.get("method")||h.data?.config?.connectionMethodKey;if(u&&h.isPending)return(0,t.jsx)("p",{className:"p-6 text-sm text-muted-foreground",children:"Loading connection…"});if(u&&h.isError)return(0,t.jsxs)("div",{role:"alert",className:"space-y-3 p-6",children:[(0,t.jsx)("p",{children:"Could not load this connection. Your saved access and credentials have not changed."}),(0,t.jsx)($,{variant:"outline",onClick:r(()=>{h.refetch()},"onClick"),children:"Try again"})]});if(q6(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"&&s_(p)&&(!f||HT(p,f))){const x=$be(p,s.get("targetToolkit"));return(0,t.jsx)(Let,{...e,upstreamServiceName:e.upstreamServiceName??x?.name,interactionId:o,providerId:p,connection:h.data},`${o||"page"}:${p}`)}return(0,t.jsx)(pht,{...e})}r(ES,"ConnectionSetupFlow");function pht({additionalSettings:e,connectionSettings:s,additionalSettingsValid:n=!0,byoOnly:a=!1,credentialSource:i="paperclip_vault",host:o="page",serviceSlug:l,requestedAgentId:c,interactionId:d,forceNewConnection:u=!1,existingConnections:h=[],configuredConnection:p,onUseExisting:f,onComplete:x,onOAuthDeclined:g,aiConnection:v,requiredAiOwnership:y,onPhaseChange:k,onCancel:w,renderCredentialStep:N}={}){const S=kt(),C=Yn(),_=(0,m.useCallback)((ot,ys)=>{o==="page"&&(ys?C(ot,ys):C(ot))},[o,C]),R=ga(),{selectedCompany:I,selectedCompanyId:T}=ps(),{enabled:E,githubEnabled:L}=cw(),{enabled:O}=MH(),{setBreadcrumbs:P}=Wn(),{pushToast:Q}=Ii(),[D]=hi(),F=d?.trim()||D.get("intent")?.trim()||null,z=R.appKey??D.get("appKey")??void 0,K=D.get("source")?.trim()||null,U=u||D.get("new")==="1",q=D.get("stage")?.trim()||null,G=D.get("method")?.trim()||null,se=D.get("resume")?.trim()||null,Z=D.get("oauth"),ie=D.get("code"),J=yae(D.get("installation_url")),re=yae(D.get("management_url")),oe=p?.id??(D.get("reconnect")?.trim()||null),V=D.get("identity")==="user"?"user":D.get("identity")==="organization"?"organization":null,X=i==="vercel_connect",Y=l??K,ae=i==="paperclip_vault"&&Omt(Y)?Y:null,ne=Bmt({serviceSlug:l,appKey:z,sourceSlug:K}),ce=(l??K??z)==="zapier",he=ce?void 0:ne,pe=!!p||o==="page"&&(a||D.get("byo")==="1"),[ge]=(0,m.useState)(()=>o==="page"&&D.get("cloud_connector")==="enrolled"&&he?tht(he):null),[Ee]=(0,m.useState)(()=>{const ot=D.get("link")?.trim()??"";return{link:/^https?:\/\//i.test(ot)?ot:"",name:p?.name??D.get("name")?.trim()??"",applicationId:p?.applicationId??(D.get("applicationId")?.trim()||void 0)}}),[de,Ne]=(0,m.useState)(()=>wae({requestedAppKey:he,routeStage:q,resumeConnectionId:se,hasPrefilledLink:!!Ee.link,zapierSource:ce})),[le,Le]=(0,m.useState)(null),[Ie,ye]=(0,m.useState)(""),[Ae,Qe]=(0,m.useState)(Ee.link),[ue,Be]=(0,m.useState)(Ee.name||(ce?"Zapier":"")),[ft,gt]=(0,m.useState)(!1),[Xe,Fe]=(0,m.useState)(""),[at,Tt]=(0,m.useState)("auto"),[Dt,Ot]=(0,m.useState)(()=>[Uz()]),[rt,Pe]=(0,m.useState)(""),[De,ht]=(0,m.useState)(""),[Ft,Et]=(0,m.useState)(!1),[ct,qe]=(0,m.useState)(null),[Oe,Re]=(0,m.useState)(!1),[Ve,xe]=(0,m.useState)({}),[Ge,vt]=(0,m.useState)(""),[Ss,lt]=(0,m.useState)(""),[zs,We]=(0,m.useState)(""),[fe,Ye]=(0,m.useState)(v&&v.mode!=="responsible_user"?`ai-${v.method}`:""),[bt,Wt]=(0,m.useState)(null),[ut,$t]=(0,m.useState)({}),[$e,pt]=(0,m.useState)(""),[Gt,be]=(0,m.useState)(null),[fs,vn]=(0,m.useState)(null),[Ls,Bs]=(0,m.useState)({}),[kr,ds]=(0,m.useState)("all"),[os,Se]=(0,m.useState)(new Set),[St,ze]=(0,m.useState)(()=>new Set(ge?.agentIds??(c?[c]:[]))),[At,Ut]=(0,m.useState)(ge?.grantKind??V??(c?"user":"organization")),[It,rs]=(0,m.useState)(ge?.installChoice??(c?"specific":"all")),bs=!!(se&&(Z==="failed"||Z==="denied")),[$s,Os]=(0,m.useState)(bs?"error":"entry"),[Tn,ks]=(0,m.useState)(()=>bs?jae(Z,ie):null),[Hn,Jt]=(0,m.useState)(null),Vs=(0,m.useRef)(!1),Nn=(0,m.useRef)(!1),Pt=(0,m.useRef)(null),Xt=(0,m.useRef)(null),[Zs,Ns]=(0,m.useState)(null),[Js,cn]=(0,m.useState)(null),hr=(0,m.useRef)(null),[Vn,Kr]=(0,m.useState)(null),[Er,Cr]=(0,m.useState)(null),Ln=(0,m.useRef)(null),[ur,Or]=(0,m.useState)(h.length>0&&!!f),[Qr,ea]=(0,m.useState)(null),[or,Ir]=(0,m.useState)(null),[xt,Ze]=(0,m.useState)(null),es=(0,m.useCallback)(()=>{o!=="dialog"||hr.current?.closed===!1||(hr.current=window.open("about:blank","paperclip-connection-oauth","popup,width=720,height=760,resizable=yes,scrollbars=yes"))},[o]),ms=(0,m.useCallback)(ot=>{if(o!=="dialog"){sh(ot);return}Cr(ot);const ys=hr.current;if(!ys||ys.closed){Os("error"),ks("Paperclip couldn’t open the sign-in window. Open sign-in in a new tab to continue."),k?.("needs_retry");return}ys.location.assign(ot),ys.focus()},[o,k]),Is=(0,m.useCallback)(()=>{hr.current=null,ks(null),Os("redirecting"),k?.("authorizing")},[k]);(0,m.useEffect)(()=>{if(o!=="dialog"||$s!=="redirecting")return;const ot=window.setInterval(()=>{hr.current?.closed&&(Os("error"),ks("The sign-in window closed. If authorization did not finish, try again."),Cr(null),k?.("needs_retry"))},1e3);return()=>window.clearInterval(ot)},[o,$s,k]);const ss=(0,m.useCallback)(async ot=>{Ln.current?.abort();const ys=new AbortController;Ln.current=ys;try{const kn=await AN(ot,{signal:ys.signal});if(kn.kind==="reauthentication"){const In=o==="dialog"?hr.current:window;if(!In||In.closed||!ot.handoff)throw new Error("Paperclip couldn’t preserve this sign-in while refreshing your account.");C5(ot.handoff.session,In.sessionStorage),Os("starting")}else Jt(kn.host),Os("redirecting");ms(kn.url)}catch(kn){if(ys.signal.aborted)return;Os("error"),ks(kn instanceof Error?kn.message:"Paperclip couldn’t start secure sign-in. Try again."),k?.("needs_retry")}finally{Ln.current===ys&&(Ln.current=null)}},[o,k,ms]);(0,m.useEffect)(()=>()=>Ln.current?.abort(),[]),(0,m.useEffect)(()=>{if(o!=="dialog"||!F)return;const ot=r(ys=>{const kn=m5e(ys,window.location.origin,F);if(kn==="connected"){Os("entry"),Cr(null),x?.({resolvedByCallback:!0});return}if(kn==="declined"){Os("error"),ks("Authorization was cancelled. You can try again."),k?.("needs_retry");return}kn==="failed"&&(Os("error"),ks("Authorization did not complete. Try again when you’re ready."))},"receiveOAuthOutcome");return window.addEventListener("message",ot),()=>window.removeEventListener("message",ot)},[F,o,x,g]),(0,m.useEffect)(()=>{if(o!=="dialog"||F||!Vn)return;let ot=!1,ys=!1;const kn=window.setInterval(async()=>{if(ys||ot)return;const In=hr.current;if(!In||In.closed){Kr(null),Os("error"),ks("The sign-in window closed. Try again to finish connecting GitHub.");return}let ar;try{ar=new URL(In.location.href)}catch{return}if(!(ar.origin!==window.location.origin||!ar.pathname.includes(Vn))){if(ar.searchParams.has("oauth")){Kr(null),Os("error"),ks("Authorization did not complete. Finish setup in the sign-in window or try again.");return}if(ar.searchParams.get("success")==="1"){ys=!0;try{const en=await ts.getConnection(Vn);!ot&&en.status==="active"&&(Kr(null),In.close(),x?.({connectionId:en.id}))}catch{ot||(Kr(null),Os("error"),ks("Could not confirm the connection. Try again."))}finally{ys=!1}}}},1e3);return()=>{ot=!0,window.clearInterval(kn)}},[F,Vn,o,x]);const ws=r(()=>{Tt("auto"),Ot([Uz()]),Pe(""),ht(""),Et(!1),qe(null),Re(!1)},"resetGenericAuthState"),yn=r(ot=>{if(o==="page"&&!F&&i==="paperclip_vault"&&s_(ot.slug)){_(`/apps/connect?source=${ot.slug}`);return}if(ot.slug==="zapier"){Le(null),ye(""),Qe(""),Be("Zapier"),gt(!1),Fe(""),ws(),xe({}),vn(null),Ne("key"),_(DI("/apps/connect?source=zapier",F));return}if(i==="paperclip_vault"&&_ae(ot)){_(_5(ot.slug,F));return}Le(ot),ye(ot.name),Qe(""),Be(""),gt(!1),Fe(""),ws(),xe({}),vt(""),lt(""),We("");const ys=Ek(O1(ot,i));Ye(ys?.key??""),$t($2(ys)),pt(""),be(null),vn(null),ze(new Set(c?[c]:[])),rs(c?"specific":"all"),Ut(Me??bD(ys,!!c)),Ne("key"),_(i==="vercel_connect"?DI(fD(ot.slug),F):_5(ot.slug,F))},"useMatchedGalleryEntry"),Rn=r(()=>{Ne("gallery"),_(DI(i==="vercel_connect"?fD():a?"/apps/byo":"/apps",F))},"backToGallery");(0,m.useEffect)(()=>{if(o==="page")return P([{label:"Connectors",href:"/apps"},{label:X?"Vercel Connect":a?"Connect your own tool":"Connect an app"}]),()=>P([])},[a,o,P,X]);const nr=te({queryKey:M.apps.gallery(T??"__none__"),queryFn:r(()=>ts.listGallery(T),"queryFn"),select:(0,m.useCallback)(ot=>F||v?{...ot,apps:ot.apps.map(ys=>({...ys,methods:ys.methods.filter(kn=>v?kn.ai?.provider===v.provider&&(v.mode==="responsible_user"||kn.ai.method===v.method):kn.transport!=="runtime_auth")})).filter(ys=>ys.methods.length>0)}:ot,[F,v?.provider,v?.method,v?.mode]),enabled:!!T}),mt=Gmt(window.location.origin,nr.data?.oauthCallbackUrl),As=(0,m.useMemo)(()=>(nr.data?.apps??[]).filter(ot=>O||!q6(ot.slug)).filter(ot=>Zp(ot.slug,E,L)||!ot.methods.some(ys=>ys.transport==="chat_sdk")||RM(ot)),[nr.data,E,L,O]),pn=he?fj(he):null,Cn=pn?.methods.find(ot=>gk(ot)&&!A0(ot)),pr=!(Cn&&fe===Cn.key)&&!!pn?.methods.some(ot=>ot.oauthStrategy==="paperclip_cloud_connector"||ot.oauthStrategy==="paperclip_id_connector"),Nr=!!le?.methods.some(ot=>ot.oauthStrategy==="paperclip_cloud_connector"||ot.oauthStrategy==="paperclip_id_connector"),mr=le&&pr&&!Nr?Cae(pn):null,[Ra,vs]=(0,m.useState)(null),an=te({queryKey:["cloud-connector","enrollment"],queryFn:r(()=>ts.getCloudConnectorEnrollment(),"queryFn"),refetchInterval:Ra?2e3:!1,enabled:!!(T&&pr&&!Nr)}),[_r,Jn]=(0,m.useState)(null),Un=(0,m.useCallback)(()=>{hr.current?.close(),hr.current=null,vs(null)},[]),ta=(0,m.useCallback)(()=>{!T||!he||eht(T,he,{grantKind:At,installChoice:It,agentIds:It==="specific"?[...St]:[]})},[At,St,It,he,T]),Ms=(0,m.useCallback)(ot=>{const ys=iE(ot);if(!ys.ok){Un(),Jn(ys.message);return}if(o==="dialog"){vs(ys.url);const kn=hr.current;kn&&!kn.closed?(kn.location.assign(ys.url),kn.focus()):Jn("Open authorization in a new tab to continue.");return}sh(ys.url)},[o,Un]);(0,m.useEffect)(()=>{!Ra||an.data?.status!=="active"||(Un(),Jn(null),nr.refetch())},[Ra,an.data?.status,nr.refetch,Un]);const Mn=je({mutationFn:r(()=>ts.startCloudConnectorEnrollment(T,I?.name,he?kae(he,"key",i,{resumeConnectionId:se,reconnectConnectionId:oe,interactionId:F})+(o==="dialog"?"&enrollment_host=dialog":""):void 0),"mutationFn"),onSuccess:r(ot=>{if(!ot.verificationUrl){Un(),Jn("Paperclip Cloud did not return an enrollment link. Try again.");return}Ms(ot.verificationUrl)},"onSuccess"),onError:r(ot=>{Un(),Jn(ot instanceof Error?ot.message:"Paperclip couldn’t reach Paperclip Cloud. Try again.")},"onError")}),Fn=te({queryKey:M.tools.applications(T??"__none__"),queryFn:r(()=>ts.listApplications(T),"queryFn"),enabled:!!T&&(!!ae||!!se||!!oe),refetchOnMount:"always"}),Ts=te({queryKey:M.tools.connections(T??"__none__"),queryFn:r(()=>ts.listConnections(T),"queryFn"),enabled:!!T&&(!!ae||!!se||!!oe),refetchOnMount:"always"}),er=(0,m.useMemo)(()=>u?null:Iae(ae,Fn.data?.applications??[],Ts.data?.connections??[],U?{applicationId:Ee.applicationId,draftOnly:!0}:{}),[Fn.data,Ts.data,U,ae,Ee.applicationId,u]),fn=(0,m.useMemo)(()=>oe?(Ts.data?.connections??[]).find(ot=>ot.id===oe)??null:null,[Ts.data,oe]),la=(0,m.useRef)(null);(0,m.useEffect)(()=>{if(!p||!Ts.isFetchedAfterMount||!fn||la.current===fn.id)return;const ot=fn.config?.url??fn.transportConfig?.url??fn.transportConfig?.serverUrl??fn.config?.serverUrl;typeof ot!="string"||!/^https?:\/\//i.test(ot)||(la.current=fn.id,Qe(ys=>ys||ot))},[p,Ts.isFetchedAfterMount,fn]);const Te=(0,m.useMemo)(()=>fn?(Fn.data?.applications??[]).find(ot=>ot.id===fn.applicationId)??null:null,[Fn.data,fn]),Zt=rht({requestedAppKey:he,byo:pe,applicationId:Ee.applicationId,reconnectConnection:fn,reconnectApplication:Te}),hn=(0,m.useMemo)(()=>se?(Ts.data?.connections??[]).find(ot=>ot.id===se)??null:null,[Ts.data,se]),Br=(0,m.useMemo)(()=>hn?(Fn.data?.applications??[]).find(ot=>ot.id===hn.applicationId)??null:null,[Fn.data,hn]),Aa=q==="complete"&&hn?.status==="active"?hn.id:null,za=he?u5e({requestedAppKey:he,resumeConnection:hn,resumeApplication:Br,completedResumeConnectionId:Js??Aa}):!1,us=hn??fn,Me=us?us.credentialPolicy==="per_user"?"user":us.credentialPolicy==="per_agent"?"agent":"organization":V,Ht=hn?.authKind==="oauth"?hn:er,Qt=er?er.credentialPolicy==="per_user"?"user":er.credentialPolicy==="per_agent"?"agent":"organization":null,Hs=Me??Qt??(y==="shared"?"organization":null);(0,m.useEffect)(()=>{Hs&&Ut(Hs)},[Hs]);const xn=(0,m.useMemo)(()=>Ae&&!le?y6(Ae,As):null,[le,As,Ae]),Lr=le?$I(le,fe||null):null,ui=Lr&&A0(Lr)?Lr:Aae(le),Ea=i==="paperclip_vault"&&ui?le:null,Pa=i==="paperclip_vault"&&_ae(le)?le:null,Wr=!!ae&&(!Fn.isFetchedAfterMount||!Ts.isFetchedAfterMount),Ya=r(ot=>{Ne(ot),le&&_(kae(le.slug,ot,i,{connectionMethodKey:le.methods.find(ys=>ys.key===fe)?.ai?fe:void 0,resumeConnectionId:se,reconnectConnectionId:oe,interactionId:F}))},"setAppStep"),zr=hn??fn??Ht,Ti=le?.agentInstructions,Gn=le&&Ti?bt?.slug===le.slug?bt.value:zr?zr.agentInstructions??{...iN(Ti),enabled:!1}:iN(Ti):null,Gi=!Gn||!!Gn.text.trim(),il=je({mutationFn:r(async ot=>(Gn&&JSON.stringify(Gn)!==JSON.stringify(ot.agentInstructions)&&await ts.updateConnection(ot.id,{agentInstructions:Gn}),ts.startOAuth(ot.id,{asCurrentUser:ot.credentialPolicy==="per_user",...ot.credentialPolicy==="per_agent"?{asAgentId:uht(ot)??[...St][0]}:{},...F?{interactionId:F}:{}})),"mutationFn"),onSuccess:r(ot=>{ss(ot)},"onSuccess"),onError:r(ot=>{const ys=ot instanceof sn&&ot.body&&typeof ot.body=="object"?ot.body.details:null;Os("error"),k?.("needs_retry"),ks(ys?.code==="invalid_grant"?"Your authorization expired or was revoked. Reconnect to continue.":ot instanceof Error?ot.message:"Paperclip couldn’t start secure sign-in. Try again.")},"onError")}),Yo=il.mutate,po=(0,m.useCallback)(ot=>{k?.("authorizing"),es(),o==="dialog"&&!F&&Kr(ot.id),Yo(ot)},[Yo,k,es,o,F]),ve=r(async ot=>{if(c)return;const ys=c5e(T,(Hs??At)!=="agent"&&It==="all"?{onAll:!0,agentIds:new Set}:{onAll:!1,agentIds:St});await ts.putConnectionInstalls(ot,ys)},"applyAccessInstalls"),Nt=Hs??At,hs=je({mutationFn:r(async ot=>{const ys=ot??le;let kn;if(ys){const In=Hs??At,ar=$I(ys,fe||null),en=EC(ys,ar)?WF($e).ids:[],rr=Ie.trim(),Da=gae(rr||ys.name,In);kn=await ts.connectApp(T,{galleryKey:ys.slug,...Gn?{agentInstructions:Gn}:{},...fe?{connectionMethodKey:fe}:{},name:Da,credentialSource:i,...i==="paperclip_vault"?{credentialValues:Ve}:{},...i==="vercel_connect"?{vercelConnect:{connector:zs.trim()}}:{},...Ge.trim()?{oauthClient:{clientId:Ge.trim(),...Ss?{clientSecret:Ss}:{}}}:{},configValues:EC(ys,ar)?{allowedSpreadsheetIds:en}:Object.keys(ut).length>0?ut:void 0,applicationId:Ee.applicationId,...se??Pt.current?{resumeConnectionId:se??Pt.current}:oe?{reconnectConnectionId:oe}:{},...In!=="organization"?{grantKind:In}:{},...In==="agent"?{subjectAgentId:[...St][0]}:{}}),Pt.current=null}else{const In=Ymt({link:Ae,name:ue,authMode:at,needsKey:ft,keyValue:Xe,headers:Dt,oauthClientId:rt,oauthClientSecret:De}),ar=gae(In.name??gD(Ae)??"Custom app",Nt);kn=await ts.connectApp(T,{...In,...oe?{reconnectConnectionId:oe}:{},...ce||xn?.slug==="zapier"?{galleryKey:"zapier",connectionMethodKey:"generated-url"}:{},name:ar,applicationId:Ee.applicationId,...Nt!=="organization"?{grantKind:Nt}:{},...Nt==="agent"?{subjectAgentId:[...St][0]}:{}})}return kn.auth?.kind==="oauth"&&!se&&!oe&&await ve(kn.connectionId),kn},"mutationFn"),onSuccess:r(ot=>{if(ot.auth?.kind==="oauth"){if(vn(ot),ot.auth.manualClientRequired){qe(vae("oauth_manual_client_required",null)),Tt("oauth"),Et(!0),Re(!1);return}if(o==="dialog"||F){Os("starting"),Re(!le),po(ot.connection);return}const kn=ot.auth.startUrl?.trim();if(!kn){Os("starting"),Re(!0),po(ot.connection);return}Re(!0),ss({authorizationUrl:kn,handoff:ot.auth.handoff});return}qe(null),vn(ot);const ys={};for(const kn of ot.actions.readOnly)ys[kn.catalogEntryId]=!0;for(const kn of ot.actions.canMakeChanges)ys[kn.catalogEntryId]=!0;Bs(ys),Ha.mutate({result:ot,enabled:ys})},"onSuccess"),onError:r(ot=>{const ys=ot instanceof sn&&ot.body&&typeof ot.body=="object"?ot.body.details:null;if(Ea){Os("error"),k?.("needs_retry"),ks(ys?.code==="invalid_grant"?"Your authorization expired or was revoked. Reconnect to continue.":ot instanceof Error?ot.message:"Paperclip couldn’t start secure sign-in. Try again.");return}if(!le&&Ae){const kn=typeof ys?.code=="string"?ys.code:null,In=vae(kn,ot instanceof Error?ot.message:null);qe(In),Re(!1),In.focus==="credentials"&&(gt(!0),Et(!0));return}Q({title:"Couldn’t connect",body:ot instanceof Error?ot.message:"Please check your key and try again.",tone:"error"})},"onError")}),bn=hs.mutate,Ar=(0,m.useCallback)(ot=>{const ys=ot??le;(ys?$I(ys,fe||null):null)?.auth==="oauth"&&es(),bn(ot)},[fe,le,bn,es]);(0,m.useEffect)(()=>{if(!he||nr.isLoading||!nr.data||(se||oe)&&(!Ts.isFetchedAfterMount||!Fn.isFetchedAfterMount))return;if(se&&q==="complete"&&hn?.status==="active"&&Js!==se&&za){_(`/apps/${hn.id}/permissions`,{replace:!0});return}if(se&&!za)return;const ot=nht({requestedAppKey:he,galleryApps:nr.data.apps,reconnectConnection:fn,resumeConnection:hn,resumeApplication:Br,completedResumeConnectionId:Js,applications:Fn.data?.applications??[]}),ys=!!ot?.methods.some(Ce=>Ce.oauthStrategy==="paperclip_cloud_connector"||Ce.oauthStrategy==="paperclip_id_connector");if(pr&&!ys&&an.isLoading)return;const kn=O1(ot,i),In=v??(fn?.connectionPurpose==="ai"?aF.safeParse(fn.config?.ai).data:void 0),ar=kn.find(Ce=>In?Ce.ai?.provider===In.provider&&(!("mode"in In)||In.mode!=="responsible_user")&&Ce.ai.method===In.method:Ce.key===G)??(pr&&!ys?Cae(pn):null)??Ek(kn),en=kn.length===1?kn[0]:null,rr=i==="paperclip_vault"&&!!Aae(ot),Da=aht({credentialSource:i,available:nr.data.credentialSources?.vercelConnect.available===!0,retainedReconnectMatches:!!(oe&&Zt)}),Je=kn.length===1&&en?.auth==="oauth"&&!A0(en)&&!gk(en),Bt=iht({available:ot?.availability?.available,reconnectConnectionId:oe,reconnectSourceMatches:Zt}),Us=oht({reconnectConnectionId:oe,hasRequestedEntry:!!ot,supportedMethodCount:kn.length,unsupportedOAuth:Je,vercelUnavailable:Da,definitionUnavailable:Bt});if(Us!=="ready"){if(Le(null),Ne("gallery"),Us==="reconnect_unavailable"&&oe){Ze(oe);return}_(DI(i==="vercel_connect"?fD():"/apps/connect",F),{replace:!0});return}if(Ze(null),!!ot){if(le?.slug!==ot.slug){Le(ot),ye(ot.name),Qe(""),Be(""),gt(!1),Fe(""),xe({}),vt(""),lt(""),We(""),Ye(ar?.key??""),$t($2(ar)),pt(""),be(null),vn(null);const Ce=ge?.companyId===T?ge:null;Ut(Me??Ce?.grantKind??bD(ar,!!c)),ze(new Set(Ce?.agentIds??(c?[c]:[]))),rs(Ce?.installChoice??(c?"specific":"all")),Ne(wae({requestedAppKey:he,routeStage:q,resumeConnectionId:se,hasPrefilledLink:!!Ee.link,zapierSource:ce}))}else Nr!==ys&&(Le(ot),Ye(ar?.key??""),$t($2(ar)));if(!(rr&&(!Fn.isFetchedAfterMount||!Ts.isFetchedAfterMount))&&!(rr&&Nn.current)&&rr&&(Fn.isError||Ts.isError)){Os("error"),ks("Paperclip couldn’t check for an existing connection. Try again."),Ne("key");return}}},[v,G,Fn.isError,Fn.isFetchedAfterMount,Fn.data,Ts.isError,Ts.isFetchedAfterMount,an.data?.configured,an.isLoading,fe,i,le?.slug,Nr,nr.data,nr.isLoading,_,Me,fn,oe,Zt,hn,Br,za,Js,Aa,q,se,pn,he,c,ge,q,ce]),(0,m.useEffect)(()=>{Xt.current=null,Ns(null)},[se]),(0,m.useEffect)(()=>{const ot=hn??fn;if(!ot||!le||Xt.current===ot.id)return;const ys=PQ(ot),kn=typeof ys.sourceTemplateKey=="string"?ys.sourceTemplateKey:null;if(kn&&kn!==le.slug)return;const In=typeof ys.connectionMethodKey=="string"?ys.connectionMethodKey:null,ar=In?O1(le,i).find(rr=>rr.key===In)??null:null;if(ye(ot.name||le.name),ar){Ye(ar.key);const rr=ys.methodConfig&&typeof ys.methodConfig=="object"?ys.methodConfig:{};$t({...$2(ar),...Object.fromEntries(Object.entries(rr).filter(Da=>typeof Da[1]=="string"||typeof Da[1]=="boolean"))})}const en=ys.oauth&&typeof ys.oauth=="object"?ys.oauth:null;en?.clientRegistrationSource==="manual"&&typeof en.clientId=="string"&&vt(en.clientId),Z==="failed"||Z==="denied"?(Os("error"),ks(jae(Z,ie))):(Os("entry"),ks(null)),Ne("key"),Xt.current=ot.id,Ns(ot.id)},[i,le,ie,Z,hn,fn]);const Ha=je({mutationFn:r(async ot=>{const{result:ys,enabled:kn}=ot,In=Object.entries(kn).filter(([,Da])=>Da).map(([Da])=>Da),ar=ASe(ys,Da=>!!kn[Da]),en=It==="all"?"all_agents":{agentIds:Array.from(St)},rr=await ts.finishApp(T,ys.connectionId,{enabledCatalogEntryIds:In,askFirstCatalogEntryIds:ar,...Gn?{agentInstructions:Gn}:{},access:en,...c?{preserveExistingAccess:!0}:{}});return await ve(ys.connectionId),rr},"mutationFn"),onSuccess:r(async(ot,ys)=>{se&&ys.result.connectionId===se&&cn(se),await S.invalidateQueries({queryKey:["tools"]}),await S.invalidateQueries({queryKey:M.apps.attention(T)}),Ya("success"),x?.({connectionId:ys.result.connectionId})},"onSuccess"),onError:r(ot=>{Ya("key"),Q({title:"Couldn’t finish setup",body:ot instanceof Error?ot.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((se||oe)&&(Ts.isError||Fn.isError))return(0,t.jsxs)("div",{className:"mx-auto max-w-xl rounded-xl border border-border bg-card p-6",children:[(0,t.jsx)("h2",{className:"text-lg font-semibold text-foreground",children:"Couldn’t load connection setup"}),(0,t.jsx)("p",{className:"mt-2 text-sm text-muted-foreground",children:"Paperclip couldn’t check the retained connection. The retained connection was not changed."}),(0,t.jsxs)("div",{className:"mt-5 flex flex-wrap gap-2",children:[(0,t.jsx)($,{type:"button",onClick:r(async()=>{const[ot,ys]=await Promise.all([Ts.refetch(),Fn.refetch()]);!ot.isError&&!ys.isError&&(ks(null),Os("entry"))},"onClick"),children:"Try again"}),(0,t.jsx)($,{type:"button",variant:"outline",onClick:r(()=>_("/apps"),"onClick"),children:"Back to apps"})]})]});if(se&&Ts.isFetchedAfterMount&&!hn)return(0,t.jsxs)("div",{className:"mx-auto max-w-xl rounded-xl border border-border bg-card p-6",children:[(0,t.jsx)("h2",{className:"text-lg font-semibold text-foreground",children:"This setup can’t be resumed"}),(0,t.jsx)("p",{className:"mt-2 text-sm text-muted-foreground",children:"The saved connection no longer exists or is not available to this organization."}),(0,t.jsx)($,{type:"button",variant:"outline",className:"mt-5",onClick:r(()=>_("/apps"),"onClick"),children:"Back to apps"})]});if(se&&Ts.isFetchedAfterMount&&Fn.isFetchedAfterMount&&hn&&!za)return(0,t.jsxs)("div",{className:"mx-auto max-w-xl rounded-xl border border-border bg-card p-6",children:[(0,t.jsx)("h2",{className:"text-lg font-semibold text-foreground",children:"This setup can’t be resumed"}),(0,t.jsx)("p",{className:"mt-2 text-sm text-muted-foreground",children:"This saved draft does not match the requested provider. The connection was not changed."}),(0,t.jsx)($,{type:"button",variant:"outline",className:"mt-5",onClick:r(()=>_("/apps"),"onClick"),children:"Back to apps"})]});if(oe&&Ts.isFetchedAfterMount&&Fn.isFetchedAfterMount&&(!fn||!Zt))return(0,t.jsxs)("div",{className:"mx-auto max-w-xl rounded-xl border border-border bg-card p-6",children:[(0,t.jsx)("h2",{className:"text-lg font-semibold text-foreground",children:"This connection can’t be reconnected"}),(0,t.jsx)("p",{className:"mt-2 text-sm text-muted-foreground",children:fn?"This reconnect link does not match the retained connection's provider.":"The retained connection no longer exists or is not available to this organization."}),(0,t.jsx)($,{type:"button",variant:"outline",className:"mt-5",onClick:r(()=>_("/apps"),"onClick"),children:"Back to apps"})]});if((se||oe)&&nr.isError)return(0,t.jsxs)("div",{className:"mx-auto max-w-xl rounded-xl border border-border bg-card p-6",children:[(0,t.jsx)("h2",{className:"text-lg font-semibold text-foreground",children:"Couldn’t load connection setup"}),(0,t.jsx)("p",{className:"mt-2 text-sm text-muted-foreground",children:"Paperclip couldn’t load the provider details needed to restore this connection. The retained connection was not changed."}),(0,t.jsxs)("div",{className:"mt-5 flex flex-wrap gap-2",children:[(0,t.jsx)($,{type:"button",onClick:r(()=>{nr.refetch()},"onClick"),children:"Try again"}),(0,t.jsx)($,{type:"button",variant:"outline",onClick:r(()=>_("/apps"),"onClick"),children:"Back to apps"})]})]});if(oe&&xt===oe)return(0,t.jsxs)("div",{className:"mx-auto max-w-xl rounded-xl border border-border bg-card p-6",children:[(0,t.jsx)("h2",{className:"text-lg font-semibold text-foreground",children:"This connection can’t be reconnected"}),(0,t.jsx)("p",{className:"mt-2 text-sm text-muted-foreground",children:"Paperclip no longer has a supported setup method for this retained connection. The retained connection was not changed."}),(0,t.jsx)($,{type:"button",variant:"outline",className:"mt-5",onClick:r(()=>_("/apps"),"onClick"),children:"Back to apps"})]});if(se&&(!Ts.isFetchedAfterMount||nr.isLoading||!le||Zs!==hn?.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)(wn,{className:"h-8 w-48"}),(0,t.jsx)(wn,{className:"h-40 w-full rounded-xl"})]});if(oe&&(!Ts.isFetchedAfterMount||!Fn.isFetchedAfterMount||nr.isLoading||he&&!le))return(0,t.jsxs)("div",{className:"mx-auto max-w-xl space-y-4","aria-label":"Loading retained connection setup",children:[(0,t.jsx)(wn,{className:"h-8 w-48"}),(0,t.jsx)(wn,{className:"h-40 w-full rounded-xl"})]});if(ur&&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 ",he?"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)(xv,{choices:h.map(ot=>({id:ot.id,name:ot.name,description:ot.status==="active"&&ot.enabled?"Ready to use":"Setup needs attention"})),pendingId:Qr,onSelect:r(async ot=>{ea(ot),Ir(null);try{await f(ot)}catch(ys){Ir(ys instanceof Error?ys.message:"Couldn’t use this connection."),ea(null)}},"onSelect")}),or?(0,t.jsx)(ma,{tone:"danger",className:"mt-4",children:or}):null,(0,t.jsxs)("div",{className:"mt-5 flex flex-wrap gap-2",children:[(0,t.jsx)($,{type:"button",variant:"outline",onClick:r(()=>Or(!1),"onClick"),children:p?"Review connection setup":"Connect new"}),w?(0,t.jsx)($,{type:"button",variant:"ghost",onClick:w,children:"Cancel"}):null]})]});const Ri=O1(le,i),ti=mr?[mr]:Ri,si=le?fe?ti.find(ot=>ot.key===fe)??null:ti[0]??null:null,Rr=le?si?.auth??"none":at==="none"?"none":at==="oauth"?"oauth":"api_key",Za=de==="key"?((ot,ys)=>(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)(OV,{extra:ot,forceOpen:ys,companyId:T,sentence:LE({grantKind:Nt,authKind:Rr,installChoice:It,installCount:St.size,lockedAgentId:c??null,preserveAgentAccess:!!(Ea&&(Ht||fn))}),notice:[nr.data?.capabilities?.canCreateOrganizationGrant===!1?nr.data.capabilities.organizationGrantReason??"Only a connection manager can share this credential with the organization.":null,nr.data?.capabilities?.canSetCompanyInstall===!1?nr.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(kn=>!!kn),authKind:Rr,grantKinds:Hs?[Hs]:si?.grantKinds,grantKind:Nt,setGrantKind:Ut,installChoice:It,setInstallChoice:rs,installAgentIds:St,setInstallAgentIds:ze,lockedAgentId:c,capabilities:nr.data?.capabilities,githubIdentity:le?.slug==="github",identityLoading:!!Ea&&Wr,preserveAgentAccess:!!(Ea&&(Ht||fn)),disabled:hs.isPending||il.isPending},"connection-defaults"),le&&Ti&&Gn&&(0,t.jsx)("div",{className:"mt-6",children:(0,t.jsx)(RH,{provider:le.name,template:Ti,value:Gn,onChange:r(kn=>Wt({slug:le.slug,value:kn}),"onChange"),disabled:hs.isPending||il.isPending})}),e&&(0,t.jsx)("div",{className:"mt-6",children:e})]})):null,so=Ea&&ui&&gk(ui)?ui:null,fo=so&&Ea?(0,t.jsx)(Wz,{entry:Ea,method:so,callbackUrl:mt,clientId:Ge,onClientIdChange:vt,clientSecret:Ss,onClientSecretChange:lt,required:!1}):null,Va=Za?.()??null,fi=fo?Za?.(fo,$s==="error"||Ge.trim().length>0)??null:Va,ol=!!(Ea&&de==="key"&&(Pa||$s!=="entry")),vd=!!(de==="key"&&le&&pr&&!Nr&&an.data?.configured===!0),mc=!!(de==="key"&&le&&pr&&!Nr&&(an.isLoading||an.isError||an.data?.configured!==!0));if(ol&&Ea)return(0,t.jsx)(Kz,{entry:Ea,resuming:!!se,phase:$s,error:Tn,recoveryActions:ie==="github_installation_required"?{installationUrl:J,managementUrl:re}:void 0,authorizationHost:Hn,authorizationUrl:Er,guidance:le?.slug==="railway"&&si?(0,t.jsxs)("div",{className:"space-y-3 text-sm text-muted-foreground",children:[(0,t.jsx)("p",{children:si.guidanceMd}),(0,t.jsx)("ul",{className:"list-disc space-y-2 pl-5",children:si.warnings?.map(ot=>(0,t.jsx)("li",{children:ot},ot))})]}):null,defaults:fi,settingsValid:n&&Gi,onOpenAuthorization:Is,onRetry:r(async()=>{const ot=!Vs.current;Vs.current=!0,ks(null),Os("starting");const ys=fs?.connection??Ht;if(ys&&fo&&Ge.trim()){Pt.current=ys.id,Ar(Ea);return}if(ys){po(ys);return}if(ot&&!se&&!Fn.isError&&!Ts.isError){Ar(Ea);return}Nn.current=!0;try{const[kn,In]=await Promise.all([Fn.refetch(),Ts.refetch()]);if(kn.isError||In.isError){Os("error"),ks("Paperclip couldn’t check for an existing connection. Try again.");return}const ar=(se?(In.data?.connections??[]).find(en=>en.id===se&&en.authKind==="oauth")??null:null)??Iae(ae,kn.data?.applications??[],In.data?.connections??[],U?{applicationId:Ee.applicationId,draftOnly:!0}:{});ar&&!se&&Ut(ar.credentialPolicy==="per_user"?"user":ar.credentialPolicy==="per_agent"?"agent":"organization"),ar?po(ar):hs.mutate(Ea)}finally{Nn.current=!1}},"onRetry"),onBack:r(()=>{Ln.current?.abort(),Os("entry"),ks(null),Rn()},"onBack"),onCancel:r(()=>{Ln.current?.abort(),(w??(()=>_("/apps")))()},"onCancel")});if(Oe&&!le&&Ae&&de==="key")return(0,t.jsx)(Kz,{identity:{name:ue.trim()||x_(Ae)||"this server",unverifiedHost:x_(Ae)},steps:{labels:Nae,activeIndex:Sae.key},phase:$s,error:Tn,authorizationHost:Hn,authorizationUrl:Er,defaults:Va,onOpenAuthorization:Is,onRetry:r(()=>{ks(null);const ot=fs?.connection;if(ot){Os("starting"),po(ot);return}Re(!1),Os("entry")},"onRetry"),onBack:r(()=>{Ln.current?.abort(),Re(!1),Os("entry"),ks(null)},"onBack"),onCancel:r(()=>{Ln.current?.abort(),(w??(()=>_("/apps")))()},"onCancel")});const Ue=fs?.application.name??le?.name??(ue.trim()||gD(Ae)||"this app"),Rt=X?As.filter(ot=>O1(ot,i).length>0):As,qt=ce?nr.data?.apps.find(ot=>ot.slug==="zapier")??null:null,Fs=(fn?.connectionPurpose==="ai"?aF.safeParse(fn.config?.ai).data:void 0)??le?.methods.find(ot=>ot.key===fe)?.ai??(!fe&&le?.methods.every(ot=>ot.ai)?le.methods[0]?.ai:void 0),dn=le?N?.({app:le,name:Ie||le.name,grantKind:Nt,agentIds:[...St],allAgents:It==="all",onBack:r(()=>Rn(),"onBack")})??(Fs&&T?(0,t.jsx)(t.Fragment,{children:(0,t.jsx)(S5,{defaults:fn?void 0:Va,companyId:T,provider:Fs.provider,fixedMethod:!!(v&&v.mode!=="responsible_user"),initialMethod:fn?.connectionPurpose==="ai"?(fn.config?.ai).method:Fs.method,connectionId:fn?.connectionPurpose==="ai"?fn.id:void 0,name:fn?.connectionPurpose==="ai"?fn.name:Ie||`My ${le.name} ${Fs.method==="subscription"?"subscription":"API"}`,ownership:(fn?.connectionPurpose==="ai"?fn.credentialPolicy==="shared":Nt==="organization")?"shared":"personal",agentIds:[...St],allAgents:It==="all",onCancel:r(()=>w?w():_("/apps"),"onCancel"),onComplete:r(ot=>{x?.({connectionId:ot.connectionId}),x||_(`/apps/${ot.connectionId}/permissions`)},"onComplete")})}):void 0):void 0,ci=fn?.connectionPurpose==="ai"?["Reconnect account"]:dn!==void 0?["Connect account"]:ce?cht:le&&ti.length>1?["Choose connection"]:le&&ti[0]?.auth==="oauth"?["Sign in"]:EC(le,fe)?["Share sheet"]:le?["Add your key"]:Nae,qa=fn?.connectionPurpose==="ai"?0:(ce||le)&&de!=="gallery"&&de!=="success"?lht[de]:de==="success"?ci.length:Sae[de];return(0,t.jsxs)("div",{className:"max-w-5xl",children:[de!=="success"&&!(a&&de==="gallery")&&(0,t.jsx)(cM,{subtitle:de==="gallery"?X?"Choose a reviewed app to connect through Vercel.":"Pick the app you want your agents to use.":ci.length<=1?void 0:`Step ${qa+1} of ${ci.length}`,step:de,activeIndex:qa,labels:ci,appIdentity:ce?{name:"Zapier",logoUrl:qt?.branding.logoUrl??null,darkLogoUrl:qt?.branding.darkLogoUrl??null}:le&&de!=="gallery"?{name:le.name,logoUrl:le.branding.logoUrl,darkLogoUrl:le.branding.darkLogoUrl??null}:void 0,unverifiedHost:!le&&!ce&&de!=="gallery"?x_(Ae):null,onCancel:w??(()=>_("/apps"))}),de==="key"&&s&&(0,t.jsx)("div",{className:"mx-auto mb-6 max-w-xl",children:s}),de==="gallery"&&(0,t.jsx)(xht,{loading:nr.isLoading,initialLink:Ae,apps:Rt,vercelConnect:X,vercelConnectAvailability:nr.data?.credentialSources?.vercelConnect??null,byo:pe,byoOnly:a,source:D.get("source"),onPick:yn,onUseLink:r(ot=>{const ys=y6(ot,As);Le(null),ye(""),Qe(ot),Be(ys?.name??gD(ot)??""),gt(!1),Fe(""),xe({}),pt(""),be(null),ze(new Set(c?[c]:[])),rs(c?"specific":"all"),Ut(Me??(c?"user":"organization")),Ne("key")},"onUseLink")}),vd&&le?(0,t.jsxs)("div",{className:"mx-auto max-w-xl rounded-xl border border-border bg-card p-6",children:[(0,t.jsxs)("h2",{className:"text-lg font-semibold text-foreground",children:[le.name," sign-in is unavailable"]}),(0,t.jsxs)("p",{className:"mt-2 text-sm text-muted-foreground",children:["This instance is connected to Paperclip, but ",le.name," sign-in is not currently available. Try again shortly or contact your instance administrator."]}),Cn?(0,t.jsxs)($,{type:"button",variant:"link",className:"mt-4 h-auto p-0 text-xs",onClick:r(()=>Ye(Cn.key),"onClick"),children:["Use your own ",le.name," OAuth app"]}):null,(0,t.jsxs)("div",{className:"mt-6 flex items-center justify-between gap-3",children:[(0,t.jsx)($,{type:"button",variant:"ghost",onClick:Rn,children:"Back"}),(0,t.jsxs)($,{type:"button",disabled:nr.isFetching,onClick:r(()=>{nr.refetch()},"onClick"),children:[nr.isFetching?(0,t.jsx)(st,{className:"h-4 w-4 animate-spin"}):null,"Try again"]})]})]}):de==="key"&&le&&mc?(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)(Wb,{className:"h-5 w-5"})}),(0,t.jsxs)("div",{className:"min-w-0",children:[(0,t.jsx)("h2",{className:"text-lg font-semibold text-foreground",children:"Connect with Paperclip"}),(0,t.jsxs)("p",{className:"mt-2 text-sm text-muted-foreground",children:["You must connect this instance to Paperclip to connect to ",le.name," (you only need to do this once)."]})]})]}),Cn?(0,t.jsxs)($,{type:"button",variant:"link",className:"mt-4 h-auto p-0 text-xs",onClick:r(()=>Ye(Cn.key),"onClick"),children:["Use your own ",le.name," OAuth app"]}):null,an.isError||_r?(0,t.jsx)(ma,{tone:"danger",className:"mt-4",children:_r??"Paperclip couldn’t check Cloud registration. Try again."}):null,Ra?(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:Ra,target:"_blank",rel:"noopener noreferrer",children:"Open authorization in a new tab"})]}):null,Va,(0,t.jsxs)("div",{className:"mt-6 flex items-center justify-between gap-3",children:[(0,t.jsx)($,{type:"button",variant:"ghost",onClick:Rn,children:"Back"}),(0,t.jsxs)($,{type:"button",disabled:an.isLoading||Mn.isPending,onClick:r(()=>{Jn(null),es(),ta(),Mn.mutate()},"onClick"),children:[Mn.isPending?(0,t.jsx)(st,{className:"h-4 w-4 animate-spin"}):null,an.data?.status==="pending"?"Continue":"Connect with Paperclip"]})]})]})}):de==="key"&&le&&dn!==void 0?dn:de==="key"&&le?(0,t.jsx)(vht,{settingsValid:n&&Gi,entry:le,error:hs.isError?hs.error instanceof Error?hs.error.message:"Please check your key and try again.":null,values:Ve,onChange:xe,oauthClientId:Ge,onOAuthClientIdChange:vt,oauthClientSecret:Ss,oauthCallbackUrl:mt,canReuseOAuthClientSecret:!!(us?.config?.oauth&&us.config.oauth.clientId===Ge.trim()&&us.hasSavedOAuthClientSecret),onOAuthClientSecretChange:lt,credentialSource:i,vercelConnector:zs,onVercelConnectorChange:We,vercelConnectAvailability:nr.data?.credentialSources?.vercelConnect??null,methodKey:fe,onMethodChange:r(ot=>{Ye(ot?.key??""),!Me&&ot?.grantKinds&&!ot.grantKinds.includes(At)&&Ut(bD(ot,!!c)),xe({}),vt(""),lt(""),We(""),$t($2(ot))},"onMethodChange"),configValues:ut,onConfigChange:$t,googleSheetsLinks:$e,googleSheetsError:Gt,onGoogleSheetsLinksChange:r(ot=>{pt(ot),be(null)},"onGoogleSheetsLinksChange"),submitting:hs.isPending,renderDefaults:Za??void 0,onBack:Rn,onConnect:r(()=>{if(EC(le,fe)){const kn=WF($e);if(kn.invalidCount>0){be("That doesn't look like a Google Sheets link.");return}if(kn.ids.length===0){be("Paste at least one Google Sheets link.");return}}const ot=$I(le,fe||null),ys=!!(ot?.credentialFields?.length||ot?.tenantFields?.some(kn=>!kn.hidden)||ot?.extensionFields?.some(kn=>!kn.hidden));if(ot&&A0(ot)&&Ht&&!ys&&!Ge.trim()){Vs.current=!0,ks(null),Os("starting"),po(Ht);return}ot&&A0(ot)&&(Vs.current=!0,ks(null),Os("starting")),Ar()},"onConnect")}):null,de==="key"&&!le&&!Ae&&!ce&&he&&(0,t.jsxs)("div",{className:"mx-auto max-w-xl","aria-busy":"true","aria-label":`Loading ${he} setup`,children:[(0,t.jsx)(wn,{className:"h-6 w-2/3 rounded-md"}),(0,t.jsx)(wn,{className:"mt-3 h-4 w-full rounded-md"}),(0,t.jsx)(wn,{className:"mt-8 h-11 w-40 rounded-md"})]}),de==="key"&&!le&&Ae&&!ce&&(0,t.jsx)(ght,{link:Ae,name:ue,needsKey:ft,keyValue:Xe,onKeyChange:Fe,authMode:at,onAuthModeChange:r(ot=>{Tt(ot),qe(null),ot!=="auto"&&gt(!1),ot!=="bearer"&&ot!=="auto"&&Fe("")},"onAuthModeChange"),headers:Dt,onHeadersChange:r(ot=>{Ot(ot),qe(null)},"onHeadersChange"),oauthClientId:rt,onOAuthClientIdChange:Pe,oauthClientSecret:De,onOAuthClientSecretChange:ht,advancedOpen:Ft,onAdvancedOpenChange:Et,guidance:ct,matchedEntry:xn,onUseMatchedEntry:xn?()=>yn(xn):void 0,submitting:hs.isPending||Oe,defaults:Va,onBack:Rn,onConnect:r(()=>{qe(null),hs.mutate(void 0)},"onConnect")}),de==="key"&&!le&&ce&&(0,t.jsx)(fht,{link:Ae,onLinkChange:Qe,submitting:hs.isPending,defaults:Va,onBack:Rn,onConnect:r(()=>hs.mutate(void 0),"onConnect")}),de==="success"&&(0,t.jsx)(kht,{appName:Ue,logoUrl:le?.branding.logoUrl,darkLogoUrl:le?.branding.darkLogoUrl,summary:wht({grantKind:Nt,authKind:Rr,installChoice:It,installCount:St.size,enabledCount:Object.values(Ls).filter(Boolean).length}),statedDefault:LE({grantKind:Nt,authKind:Rr,installChoice:It,installCount:St.size,lockedAgentId:c??null}),onDone:w??(()=>_(o==="page"&&fs?.connectionId?`/apps/${fs.connectionId}/permissions`:"/apps"))})]})}r(pht,"StandardConnectionSetupFlow");function Kz({entry:e,identity:s,resuming:n=!1,phase:a,error:i,recoveryActions:o,authorizationHost:l,authorizationUrl:c,steps:d={labels:dht,activeIndex:0},guidance:u,defaults:h,onRetry:p,settingsValid:f=!0,onOpenAuthorization:x,onBack:g,onCancel:v}){const y=e?.name??s?.name??"this server",k=e?null:s?.unverifiedHost??null,w=a==="entry"?{title:n?`Finish connecting ${y}`:`Connect ${y} to Paperclip`,body:n?`Your connection is saved. Continue in ${y} to approve access; its identity and agent access will stay the same.`:`Paperclip will open ${y} so you can choose a workspace and approve access.`}:a==="starting"?{title:"Preparing secure sign-in",body:`Paperclip is creating a secure ${y} connection.`}:a==="redirecting"?{title:`Opening ${y}`,body:l?`Continue at ${l} to choose a workspace and approve access. Only approve access if you recognize that address.`:`Continue in ${y} to choose a workspace and approve access.`}:{title:`${y} couldn’t connect`,body:i??"Paperclip couldn’t start secure sign-in. Try again."};return(0,t.jsxs)("div",{className:"max-w-5xl",children:[(0,t.jsx)(cM,{subtitle:"Secure MCP sign-in",step:"key",activeIndex:d.activeIndex,labels:d.labels,appIdentity:e?{name:e.name,logoUrl:e.branding.logoUrl,darkLogoUrl:e.branding.darkLogoUrl}:void 0,unverifiedHost:k,onCancel:v}),(0,t.jsxs)("div",{className:"mx-auto max-w-xl",children:[(0,t.jsxs)("div",{className:"flex items-start gap-3",children:[(0,t.jsx)("span",{className:"mt-1 inline-flex h-10 w-10 shrink-0 items-center justify-center rounded-lg border border-border bg-background",children:a==="error"?(0,t.jsx)(Ml,{className:"h-5 w-5 text-destructive"}):a==="entry"?(0,t.jsx)(Ao,{className:"h-5 w-5 text-muted-foreground"}):(0,t.jsx)(st,{className:"h-5 w-5 animate-spin text-muted-foreground"})}),(0,t.jsxs)("div",{className:"min-w-0",children:[(0,t.jsx)("h2",{className:"text-xl font-bold tracking-tight",children:w.title}),(0,t.jsx)("p",{className:"mt-1 text-sm text-muted-foreground",children:w.body}),k?(0,t.jsx)(lM,{host:k,className:"mt-2"}):null]})]}),a==="entry"&&u?(0,t.jsx)("div",{className:"mt-4",children:u}):null,a==="entry"||a==="error"?h:null,a==="error"&&o&&(o.installationUrl||o.managementUrl)?(0,t.jsxs)("div",{className:"mt-4 flex flex-wrap gap-2",children:[o.installationUrl?(0,t.jsx)($,{type:"button",variant:"outline",asChild:!0,children:(0,t.jsxs)("a",{href:o.installationUrl,target:"_blank",rel:"noreferrer",children:["Install Paperclip on GitHub",(0,t.jsx)(oo,{className:"ml-1.5 h-3.5 w-3.5"})]})}):null,o.managementUrl?(0,t.jsx)($,{type:"button",variant:"ghost",asChild:!0,children:(0,t.jsx)("a",{href:o.managementUrl,target:"_blank",rel:"noreferrer",children:"Manage repositories on GitHub"})}):null]}):null,(0,t.jsxs)("div",{className:"mt-6 flex items-center gap-2",children:[a==="error"||a==="entry"?(0,t.jsxs)($,{type:"button",onClick:p,disabled:!f,children:[a==="entry"?n?`Finish with ${y}`:`Continue to ${y}`:"Try again",a==="entry"?(0,t.jsx)(oo,{className:"h-4 w-4","aria-hidden":"true"}):null]}):(0,t.jsx)($,{type:"button",disabled:!0,children:a==="redirecting"?`Opening ${y}…`:"Preparing…"}),c?(0,t.jsx)($,{variant:"outline",asChild:!0,children:(0,t.jsx)("a",{href:c,target:"_blank",rel:"noopener noreferrer",onClick:x,children:"Open sign-in in a new tab"})}):null,(0,t.jsx)($,{type:"button",variant:"ghost",onClick:g,children:"Back"})]})]})]})}r(Kz,"OAuthConnectStateScreen");function fht({link:e,onLinkChange:s,submitting:n,defaults:a,onBack:i,onConnect:o}){const l=Qz(e),c=l?new URL(l).hostname:"",d=c==="zapier.com"||c.endsWith(".zapier.com");return(0,t.jsxs)("div",{className:"mx-auto max-w-xl",children:[(0,t.jsxs)("div",{children:[(0,t.jsx)("label",{className:"text-sm font-medium text-foreground",children:"Zapier MCP URL"}),(0,t.jsx)(dt,{type:"password",autoComplete:"off",spellCheck:!1,value:e,onChange:r(u=>s(u.target.value),"onChange"),onKeyDown:r(u=>{u.key==="Enter"&&d&&!n&&o()},"onKeyDown"),placeholder:"https://mcp.zapier.com/api/v1/connect?token=…",className:"mt-2 h-11",autoFocus:!0}),e.trim()&&!d&&(0,t.jsx)("p",{className:"mt-2 text-xs text-destructive",children:"Paste a valid Zapier URL to continue."})]}),a,(0,t.jsxs)("div",{className:"mt-6 flex items-center justify-between",children:[(0,t.jsx)($,{variant:"ghost",onClick:i,disabled:n,children:"Back"}),(0,t.jsxs)($,{onClick:o,disabled:n||!d,children:[n&&(0,t.jsx)(st,{className:"mr-2 h-4 w-4 animate-spin"}),n?"Checking…":"Check link"]})]})]})}r(fht,"ZapierConnectStep");function xht({loading:e,initialLink:s="",apps:n,byo:a=!1,byoOnly:i=!1,vercelConnect:o=!1,vercelConnectAvailability:l=null,source:c=null,onPick:d,onUseLink:u}){const[h,p]=(0,m.useState)(""),[f,x]=(0,m.useState)(s),g=(0,m.useRef)(!1);(0,m.useEffect)(()=>{g.current||x(s)},[s]);const[v,y]=(0,m.useState)(null),k=(0,m.useRef)(null),w=(0,m.useRef)(null),N=(0,m.useRef)(!1);(0,m.useEffect)(()=>{!a||e&&!i||N.current||(i||k.current?.scrollIntoView?.({block:"center"}),w.current?.focus(),w.current?.select(),N.current=!0)},[a,i,e]);const S=(0,m.useMemo)(()=>{const T=h.trim().toLowerCase();return n.filter(E=>!T||E.name.toLowerCase().includes(T))},[n,h]),C=Qz(f),_=C?y6(C,n):null,R=c==="zapier",I=r(()=>{const T=Qz(f);if(!T){y("Paste a full http or https link.");return}y(null),u(T)},"continueWithLink");return e&&!i?(0,t.jsx)("div",{className:"grid grid-cols-2 gap-4 sm:grid-cols-3 lg:grid-cols-4",children:Array.from({length:8}).map((T,E)=>(0,t.jsx)(wn,{className:"h-32 w-full rounded-xl"},E))}):(0,t.jsxs)("div",{className:"space-y-6",children:[o?(0,t.jsxs)("div",{className:"rounded-xl border border-border bg-card p-5",children:[(0,t.jsxs)("div",{className:"flex flex-col gap-3 sm:flex-row sm:items-start sm:justify-between",children:[(0,t.jsxs)("div",{children:[(0,t.jsx)("h2",{className:"text-lg font-bold tracking-tight",children:"Connect through Vercel"}),(0,t.jsx)("p",{className:"mt-1 max-w-2xl text-sm text-muted-foreground",children:"Create and manage the provider connector in Vercel. Paperclip stores its reference and applies agent access, policy, approval, and audit controls here."})]}),l?(0,t.jsx)($,{asChild:!0,variant:"outline",size:"sm",className:"shrink-0",children:(0,t.jsxs)("a",{href:l.manageUrl,target:"_blank",rel:"noreferrer",children:["Open Vercel Connect",(0,t.jsx)(oo,{className:"ml-2 h-3.5 w-3.5"})]})}):null]}),l?.available===!1?(0,t.jsx)(ma,{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)(Jr,{className:"pointer-events-none absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground"}),(0,t.jsx)(dt,{value:h,onChange:r(T=>p(T.target.value),"onChange"),placeholder:"Search apps…",className:"h-11 pl-9"})]}),(0,t.jsx)("div",{className:"grid grid-cols-2 gap-4 sm:grid-cols-3 lg:grid-cols-4",children:S.map(T=>{const E=i5e(T.slug,T.description),L=sA(T),O=L.length===0||L.every(Q=>Q.auth==="oauth"&&!A0(Q)&&!gk(Q)),P=T.availability?.available===!1||o&&l?.available!==!0;return(0,t.jsxs)("button",{type:"button",disabled:O||P,title:P?T.availability?.reason??l?.reason??void 0:void 0,onClick:r(()=>d(T),"onClick"),className:W("flex flex-col rounded-xl border border-border bg-card p-4 text-left transition-colors",O||P?"cursor-not-allowed opacity-60":"hover:border-foreground/30 hover:bg-accent/40"),children:[(0,t.jsx)(Vi,{name:T.name,logoUrl:T.branding.logoUrl,darkLogoUrl:T.branding.darkLogoUrl,size:36}),(0,t.jsx)("div",{className:"mt-3 text-sm font-bold text-foreground",children:T.name}),(0,t.jsx)("div",{className:"mt-1 line-clamp-2 text-xs text-muted-foreground",children:E.tagline}),(0,t.jsx)("div",{className:"mt-3 text-xs font-semibold text-foreground",children:P?(0,t.jsx)("span",{className:"text-muted-foreground",children:T.availability?.reason??l?.reason??"Unavailable on this instance."}):O?(0,t.jsx)("span",{className:"text-muted-foreground",children:"Unavailable"}):(0,t.jsx)("span",{children:"Connect →"})})]},T.slug)})}),S.length===0&&(0,t.jsxs)("div",{className:"py-10 text-center text-sm text-muted-foreground",children:["No apps match “",h,"”."]})]}),o?null:(0,t.jsxs)("div",{ref:k,className:W("grid gap-4 border-t border-border pt-5 md:grid-cols-(--gtc-13)",a&&"-mx-3 rounded-xl border border-primary/40 bg-primary/[0.04] px-3 pb-4 md:mx-0"),children:[(0,t.jsxs)("div",{children:[(0,t.jsxs)("div",{className:"flex items-center gap-2 text-sm font-semibold text-foreground",children:[(0,t.jsx)(Ml,{className:"h-4 w-4 text-muted-foreground"}),R?"Connect Zapier":a?"Connect your own MCP server":"Connect with a link"]}),(0,t.jsx)("p",{className:"mt-1 text-xs text-muted-foreground",children:R?"Paste the complete MCP URL Zapier gives you, including its token.":a?"Paste your MCP server’s URL and every discovered tool will be available immediately.":"Paste a setup link from an app that is not listed here."}),!R&&(0,t.jsxs)("p",{className:"mt-1 text-xs text-muted-foreground",children:["Any remote tool URL works here — including a local MCP server like"," ",(0,t.jsx)("code",{className:"rounded bg-muted px-1 py-0.5 text-xs",children:"http://127.0.0.1:8848/mcp"}),"."]}),_&&(0,t.jsxs)("div",{className:"mt-3 flex items-center justify-between gap-3 rounded-lg border border-border bg-muted/40 px-3 py-2",children:[(0,t.jsxs)("div",{className:"flex min-w-0 items-center gap-2 text-sm",children:[(0,t.jsx)(Vi,{name:_.name,logoUrl:_.branding.logoUrl,darkLogoUrl:_.branding.darkLogoUrl,size:24}),(0,t.jsxs)("span",{className:"truncate",children:["This looks like ",_.name,"."]})]}),(0,t.jsx)($,{type:"button",size:"sm",variant:"outline",disabled:_.availability?.available===!1,onClick:r(()=>{if(y(null),_.slug==="zapier"){I();return}d(_)},"onClick"),children:_.availability?.available===!1?"Not available":_.slug==="zapier"?"Continue":`Use ${_.name}`})]})]}),(0,t.jsxs)("div",{className:"flex min-w-0 flex-col gap-2 sm:min-w-(--sz-360px)",children:[(0,t.jsxs)("div",{className:"flex gap-2",children:[(0,t.jsx)(dt,{ref:w,type:R||_?.slug==="zapier"?"password":"url",autoComplete:"off",spellCheck:!1,"aria-label":"MCP server URL",value:f,onChange:r(T=>{g.current=!0,x(T.target.value),y(null)},"onChange"),onKeyDown:r(T=>{T.key==="Enter"&&I()},"onKeyDown"),placeholder:R?"https://mcp.zapier.com/api/v1/connect?token=…":"https://example.com/actions",className:"h-10"}),(0,t.jsx)($,{type:"button",variant:"outline",onClick:I,children:"Continue"})]}),v&&(0,t.jsx)("div",{className:"text-xs text-destructive",children:v})]})]})]})}r(xht,"GalleryStep");function Qz(e){try{const s=new URL(e.trim());return s.protocol!=="http:"&&s.protocol!=="https:"?null:s.toString()}catch{return null}}r(Qz,"normalizeAppLink");function ght({link:e,name:s,needsKey:n,keyValue:a,onKeyChange:i,authMode:o,onAuthModeChange:l,headers:c,onHeadersChange:d,oauthClientId:u,onOAuthClientIdChange:h,oauthClientSecret:p,onOAuthClientSecretChange:f,advancedOpen:x,onAdvancedOpenChange:g,guidance:v,matchedEntry:y,onUseMatchedEntry:k,submitting:w,defaults:N,onBack:S,onConnect:C}){const _=x_(e),R=o==="custom_headers"?o5e(c):null,I=Zmt({link:e,name:s,authMode:o,needsKey:n,keyValue:a,headers:c,oauthClientId:u,oauthClientSecret:p}),T=o==="auto"&&n||o==="bearer",E=y?.slug==="zapier"?qbe(e):e,L=r((O,P)=>{d(c.map(Q=>Q.id===O?{...Q,...P}:Q))},"updateHeader");return(0,t.jsxs)("div",{className:"mx-auto max-w-xl",children:[(0,t.jsxs)("div",{className:"flex items-center justify-between gap-3",children:[(0,t.jsx)("p",{className:"min-w-0 truncate font-mono text-sm text-muted-foreground",title:E,children:E}),(0,t.jsx)(lM,{host:_})]}),y&&k?(0,t.jsxs)("div",{className:"mt-6 flex flex-wrap items-center justify-between gap-3 rounded-lg border border-border bg-muted/40 px-3 py-2",children:[(0,t.jsxs)("div",{className:"flex min-w-0 items-center gap-2 text-sm",children:[(0,t.jsx)(Vi,{name:y.name,logoUrl:y.branding.logoUrl,darkLogoUrl:y.branding.darkLogoUrl,size:24}),(0,t.jsxs)("span",{className:"truncate",children:["Paperclip has a guided setup for ",y.name,"."]})]}),(0,t.jsxs)($,{type:"button",size:"sm",variant:"outline",onClick:k,children:["Use ",y.name]})]}):null,v?(0,t.jsx)("div",{className:"mt-6",children:(0,t.jsx)(ma,{tone:"warning",title:v.title,children:v.body})}):null,(0,t.jsxs)("div",{className:"mt-6 space-y-6",children:[T?(0,t.jsx)("div",{className:"space-y-4",children:(0,t.jsxs)("div",{children:[(0,t.jsx)("label",{className:"text-sm font-medium text-foreground",htmlFor:"generic-mcp-key",children:"App key"}),(0,t.jsx)(dt,{id:"generic-mcp-key",type:"password",autoComplete:"off",value:a,onChange:r(O=>i(O.target.value),"onChange"),placeholder:"••••••••••••••••",className:"mt-2 h-11 font-mono"}),(0,t.jsx)("p",{className:"mt-2 text-xs text-muted-foreground",children:"Grant this key read and write access to the resources your agents need. Paperclip cannot increase its permissions."})]})}):null,(0,t.jsxs)(tl,{open:x,onOpenChange:g,children:[(0,t.jsxs)(Dl,{className:"flex w-full items-center justify-between rounded-lg border border-border bg-background px-3 py-2 text-left text-sm font-medium text-foreground hover:bg-accent/40",children:["Advanced authentication",(0,t.jsx)(rn,{className:W("h-4 w-4 text-muted-foreground transition-transform",x&&"rotate-180")})]}),(0,t.jsxs)(sl,{className:"space-y-5 pt-4",children:[(0,t.jsx)("p",{className:"text-xs text-muted-foreground",children:"Only needed when the server's docs are specific about how to authenticate."}),(0,t.jsx)("div",{className:"flex flex-wrap gap-2",children:Tae.map(O=>(0,t.jsx)(bht,{label:O.label,selected:o===O.mode,onClick:r(()=>l(O.mode),"onClick")},O.mode))}),(0,t.jsx)("p",{className:"text-xs text-muted-foreground",children:Tae.find(O=>O.mode===o)?.hint}),o==="custom_headers"?(0,t.jsxs)("div",{className:"space-y-3",children:[c.map(O=>(0,t.jsxs)("div",{className:"flex items-start gap-2",children:[(0,t.jsx)(dt,{value:O.name,onChange:r(P=>L(O.id,{name:P.target.value}),"onChange"),placeholder:"Header name","aria-label":"Header name",className:"h-10 font-mono"}),(0,t.jsx)(dt,{type:"password",autoComplete:"off",value:O.value,onChange:r(P=>L(O.id,{value:P.target.value}),"onChange"),placeholder:"Value","aria-label":O.name.trim()?`Value for ${O.name.trim()}`:"Header value",className:"h-10 font-mono"}),(0,t.jsx)($,{type:"button",variant:"ghost",size:"sm",className:"h-10 shrink-0",onClick:r(()=>d(c.filter(P=>P.id!==O.id)),"onClick"),disabled:c.length===1,children:"Remove"})]},O.id)),(0,t.jsx)($,{type:"button",variant:"outline",size:"sm",onClick:r(()=>d([...c,Uz()]),"onClick"),children:"Add another header"}),R?(0,t.jsx)("p",{className:"text-xs text-destructive",children:R}):null]}):null,o==="oauth"?(0,t.jsxs)("div",{className:"space-y-4",children:[(0,t.jsx)("p",{className:"text-xs text-muted-foreground",children:"Paperclip sets sign-in up on its own whenever the server allows it. Only fill these in when the server's docs tell you to register Paperclip yourself first."}),(0,t.jsxs)("div",{children:[(0,t.jsx)("label",{className:"text-sm font-medium text-foreground",htmlFor:"generic-mcp-client-id",children:"Client ID"}),(0,t.jsx)(dt,{id:"generic-mcp-client-id",value:u,onChange:r(O=>h(O.target.value),"onChange"),autoComplete:"off",placeholder:"Optional",className:"mt-2 h-11 font-mono"})]}),(0,t.jsxs)("div",{children:[(0,t.jsx)("label",{className:"text-sm font-medium text-foreground",htmlFor:"generic-mcp-client-secret",children:"Client secret"}),(0,t.jsx)(dt,{id:"generic-mcp-client-secret",type:"password",autoComplete:"off",value:p,onChange:r(O=>f(O.target.value),"onChange"),placeholder:"Optional",className:"mt-2 h-11 font-mono"})]})]}):null]})]})]}),N,(0,t.jsxs)("div",{className:"mt-8 flex items-center justify-between",children:[(0,t.jsx)($,{variant:"ghost",onClick:S,disabled:w,children:"Back"}),(0,t.jsxs)($,{onClick:C,disabled:w||!I||!!R,children:[w&&(0,t.jsx)(st,{className:"mr-2 h-4 w-4 animate-spin"}),w?"Checking…":"Check link"]})]})]})}r(ght,"LinkConnectStep");var Tae=[{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 bht({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(bht,"SegmentedOption");function vht({settingsValid:e=!0,entry:s,error:n,values:a,onChange:i,oauthClientId:o,onOAuthClientIdChange:l,oauthClientSecret:c,oauthCallbackUrl:d,canReuseOAuthClientSecret:u,onOAuthClientSecretChange:h,credentialSource:p,vercelConnector:f,onVercelConnectorChange:x,vercelConnectAvailability:g,methodKey:v,onMethodChange:y,configValues:k,onConfigChange:w,googleSheetsLinks:N,googleSheetsError:S,onGoogleSheetsLinksChange:C,submitting:_,renderDefaults:R,onBack:I,onConnect:T}){const E=(0,m.useMemo)(()=>O1(s,p),[p,s]),L=v?E.find(Fe=>Fe.key===v)??null:Ek(E),O=(0,m.useMemo)(()=>E.some(Fe=>Fe.capabilityProfile)?Array.from(E.reduce((Fe,at)=>{const Tt=at.capabilityProfile.key,Dt=Fe.get(Tt);return Dt?Dt.methods.push(at):Fe.set(Tt,{key:Tt,label:at.capabilityProfile?.label??at.label??at.key,description:at.capabilityProfile?.description??at.whenToUse,methods:[at]}),Fe},new Map)).map(([,Fe])=>Fe):[],[E]),P=L?.capabilityProfile?.key??L?.key??"",Q=O.map(Fe=>Fe.key).join("|"),[D,F]=(0,m.useState)(P||Ek(E)?.capabilityProfile?.key||(O.length===1?O[0].key:""));(0,m.useEffect)(()=>{if(P){F(P);return}F(Fe=>O.some(at=>at.key===Fe)?Fe:Ek(E)?.capabilityProfile?.key||(O.length===1?O[0].key:""))},[Q,O,E,P]);const z=O.length>1?O.find(Fe=>Fe.key===D)?.methods??[]:E,K=(L?.credentialFields??[]).map(Fe=>({...Fe,configPath:ybe(Fe,L),helpUrl:L?.consoleLinks?.keys??L?.consoleLinks?.docs??""})),U=L?.credentialSources?.vercelConnect??null,q=p==="vercel_connect",G=q||K.every(Fe=>Fe.required===!1||(a[Fe.configPath]?.trim().length??0)>0),se=gk(L),Z=se&&!A0(L),ie=q||!Z||o.trim().length>0&&(!L?.oauthClientSecretRequired||u||c.trim().length>0),J=!q||f.trim().length>0,re=L?.auth==="oauth"&&se?d:null,oe=[...L?.tenantFields??[],...L?.extensionFields??[]],V=oe.filter(Fe=>!Fe.hidden),X=V.filter(Fe=>Fe.advanced!==!0),Y=V.filter(Fe=>Fe.advanced===!0),ae=oe.every(Fe=>{if(!Fe.required)return!0;const at=k[Fe.key];return typeof at=="boolean"||typeof at=="string"&&at.trim().length>0}),ne=L?.configRequirements?.atLeastOneOf??[],ce=ne.length===0||ne.some(Fe=>{const at=k[Fe];return typeof at=="string"&&at.trim().length>0}),he=(O.length<=1||!!D)&&(z.length<=1?!!L:!!v),pe=s.availability?.robotEmail??null,ge=s.availability?.available===!1,Ee=!q&&se&&!Z,de=O.length>1||z.length>1,Ne=O.length>1?(0,t.jsxs)("div",{children:[(0,t.jsx)("label",{className:"text-sm font-medium text-foreground",children:"What should Paperclip be able to do?"}),(0,t.jsx)(em,{ariaLabel:`Access level for ${s.name}`,className:"mt-2",value:D,onValueChange:r(Fe=>{const at=O.find(Tt=>Tt.key===Fe);at&&(F(Fe),y(UQ(at.methods)))},"onValueChange"),options:O.map(Fe=>({value:Fe.key,title:Fe.label,description:Fe.description}))}),!D&&(0,t.jsx)("p",{className:"mt-2 text-xs text-muted-foreground",children:"Choose an access level to continue."})]}):null,le=z.find(Fe=>Fe.oauthStrategy==="paperclip_cloud_connector"),Le=le&&z.find(Fe=>gk(Fe)&&!A0(Fe)),Ie=L?.key===Le?.key,ye=(0,m.useId)(),Ae=le&&Le&&z.length===2?(0,t.jsx)($,{type:"button",variant:"link",className:"h-auto p-0 text-xs text-muted-foreground underline underline-offset-2 hover:text-foreground","aria-expanded":Ie,"aria-controls":ye,disabled:_,onClick:r(()=>y(Ie?le:Le),"onClick"),children:Ie?"Use Paperclip instead":`Use your own ${oOe(le.connectorProfile??"")?"Google":s.name} OAuth app`}):z.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)(em,{ariaLabel:`How to connect ${s.name}`,className:"mt-2",value:v,onValueChange:r(Fe=>{const at=z.find(Tt=>Tt.key===Fe);at&&y(at)},"onValueChange"),options:z.map(Fe=>({value:Fe.key,title:Fe.label??(Fe.auth==="oauth"?`Sign in with ${s.name}`:"Use an API key")}))}),!L&&(0,t.jsx)("p",{className:"mt-2 text-xs text-muted-foreground",children:"Choose a connection method to continue."})]}):null,Qe=Y.length>0||Ee||de,ue=Ie||!he,Be=Qe?(0,t.jsxs)("div",{className:"space-y-6",children:[Ne,Ae,Y.map(Fe=>(0,t.jsx)(Rae,{field:Fe,value:k[Fe.key],onChange:r(at=>w({...k,[Fe.key]:at}),"onChange")},Fe.key)),Ee?(0,t.jsx)(Wz,{entry:s,method:L,callbackUrl:re,clientId:o,onClientIdChange:l,clientSecret:c,onClientSecretChange:h,required:!1}):null]}):null,ft=R?.(Be,ue)??null;if(EC(s,L)){const Fe=WF(N),at=e&&!ge&&!!pe&&N.trim().length>0;return(0,t.jsxs)("div",{className:"mx-auto max-w-xl",children:[(0,t.jsxs)("div",{className:"space-y-6",children:[Ne,pe?(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:pe,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:pe}),(0,t.jsx)(h5e,{value:pe,ariaLabel:"Copy sharing email"})]}),(0,t.jsx)("p",{className:"mt-2 text-xs text-muted-foreground",children:"In Google Sheets, click Share and add this email as an Editor. Then paste the sheet links below."})]}):(0,t.jsx)("div",{className:"rounded-lg bg-muted/50 p-4 text-sm text-muted-foreground",children:"Google Sheets is not available on this instance yet."}),(0,t.jsxs)("div",{children:[(0,t.jsx)("label",{className:"text-sm font-medium text-foreground",children:"Paste links to the sheets you shared"}),(0,t.jsx)(Qn,{value:N,onChange:r(Tt=>C(Tt.target.value),"onChange"),placeholder:"https://docs.google.com/spreadsheets/d/...",className:"mt-2 min-h-28"}),(0,t.jsx)("div",{className:"mt-2 text-xs text-muted-foreground",children:Fe.ids.length>0?`${Fe.ids.length} ${Fe.ids.length===1?"sheet":"sheets"} ready to connect.`:"Paste one link per line. Both .../edit and .../edit#gid=... links work."}),S&&(0,t.jsx)("div",{className:"mt-2 text-xs text-destructive",children:S})]})]}),ft,(0,t.jsxs)("div",{className:"mt-8 flex items-center justify-between",children:[(0,t.jsx)($,{variant:"ghost",onClick:I,disabled:_,children:"Back"}),(0,t.jsxs)($,{onClick:T,disabled:_||!at,children:[_&&(0,t.jsx)(st,{className:"mr-2 h-4 w-4 animate-spin"}),_?"Checking…":"Connect"]})]})]})}const gt=L?.connectorProfile==="asana.mcp",Xe=gt?null:L?.consoleLinks?.docs??s.docsUrl;return(0,t.jsxs)("div",{className:"mx-auto max-w-xl",children:[Xe?(0,t.jsx)("div",{className:"mb-4 flex justify-end",children:(0,t.jsxs)("a",{href:Xe,target:"_blank",rel:"noreferrer",className:"inline-flex items-center gap-1 text-xs font-medium text-muted-foreground underline underline-offset-2 hover:text-foreground",children:["Review requirements",(0,t.jsx)(oo,{className:"h-3 w-3"})]})}):null,(0,t.jsxs)("div",{className:"space-y-6",children:[gt?(0,t.jsx)("p",{className:"text-sm text-muted-foreground",children:"Sign in with Asana to choose your workspace and connect it to Paperclip."}):null,L?.capabilityProfile&&(0,t.jsxs)("p",{className:"text-sm text-muted-foreground",children:[L.capabilityProfile.label,": ",L.capabilityProfile.description]}),q&&U&&g?(0,t.jsxs)("div",{className:"space-y-4 rounded-lg border border-border p-4",children:[(0,t.jsxs)("div",{children:[(0,t.jsx)("div",{className:"text-sm font-medium text-foreground",children:"Create or attach the connector in Vercel"}),(0,t.jsx)("p",{className:"mt-1 text-xs text-muted-foreground",children:"Paperclip does not copy Vercel’s setup forms. Finish connector setup there, then paste its UID below."}),(0,t.jsxs)("a",{href:g.manageUrl,target:"_blank",rel:"noreferrer",className:"mt-2 inline-flex items-center gap-1 text-xs font-semibold text-foreground underline underline-offset-2",children:["Open Vercel Connect",(0,t.jsx)(oo,{className:"h-3 w-3"})]})]}),(0,t.jsxs)("div",{children:[(0,t.jsx)("label",{className:"text-sm font-medium text-foreground",htmlFor:"vercel-connect-connector",children:"Connector UID or ID"}),(0,t.jsx)(dt,{id:"vercel-connect-connector",value:f,onChange:r(Fe=>x(Fe.target.value),"onChange"),autoComplete:"off",placeholder:"service/my-connector or scl_…",className:"mt-2 h-11 font-mono"}),(0,t.jsx)("p",{className:"mt-2 text-xs text-muted-foreground",children:"Paperclip validates the connector and stores only its reference and redacted verification metadata."})]})]}):null,n?(0,t.jsx)("div",{role:"alert",children:(0,t.jsx)(ma,{tone:"danger",children:n})}):null,X.map(Fe=>(0,t.jsx)(Rae,{field:Fe,value:k[Fe.key],onChange:r(at=>w({...k,[Fe.key]:at}),"onChange")},Fe.key)),!q&&L?.auth==="oauth"&&Z?(0,t.jsx)("div",{id:ye,role:"region","aria-label":"Your OAuth app",children:(0,t.jsx)(Wz,{entry:s,method:L,callbackUrl:re,clientId:o,onClientIdChange:l,clientSecret:c,onClientSecretChange:h,required:!0})}):null,q||!L||K.length===0?null:K.map(Fe=>(0,t.jsxs)("div",{children:[(0,t.jsx)("label",{className:"text-sm font-medium text-foreground",children:pae(s.name,Fe.label,K.length)}),(0,t.jsx)(dt,{type:Fe.type==="text"&&Fe.secret===!1?"text":"password","aria-label":pae(s.name,Fe.label,K.length),autoComplete:"off",value:a[Fe.configPath]??"",onChange:r(at=>i({...a,[Fe.configPath]:at.target.value}),"onChange"),placeholder:Fe.type==="text"&&Fe.secret===!1?Fe.placeholder:"••••••••••••••••",className:"mt-2 h-11 font-mono"}),Fe.helperMd&&(0,t.jsx)("p",{className:"mt-2 text-xs text-muted-foreground",children:Fe.helperMd}),Fe.helpUrl&&(0,t.jsxs)("a",{href:Fe.helpUrl,target:"_blank",rel:"noreferrer",className:"mt-2 inline-flex items-center gap-1 text-xs font-semibold text-foreground underline underline-offset-2",children:["Where do I find this?",(0,t.jsx)(oo,{className:"h-3 w-3"})]})]},Fe.configPath))]}),ft,(0,t.jsxs)("div",{className:"mt-8 flex items-center justify-between",children:[(0,t.jsx)($,{variant:"ghost",onClick:I,disabled:_,children:"Back"}),(0,t.jsxs)($,{onClick:T,disabled:_||!e||!he||!G||!ie||!J||!ae||!ce,children:[_&&(0,t.jsx)(st,{className:"mr-2 h-4 w-4 animate-spin"}),_?"Checking…":q?L?.auth==="oauth"?"Validate and continue":"Validate and connect":L?.auth==="oauth"?s.slug==="github"?"Continue to GitHub":"Continue to sign in":"Connect"]})]})]})}r(vht,"KeyStep");function h5e({value:e,ariaLabel:s}){const{copied:n,failed:a,copy:i}=Z0();return(0,t.jsxs)($,{type:"button",variant:"outline",className:"shrink-0","aria-label":s,onClick:r(()=>{i(e)},"onClick"),children:[n?(0,t.jsx)(cs,{className:"mr-2 h-4 w-4"}):(0,t.jsx)(gr,{className:"mr-2 h-4 w-4"}),n?"Copied":a?"Copy failed":"Copy"]})}r(h5e,"CopyValueButton");function Wz({entry:e,method:s,callbackUrl:n,clientId:a,onClientIdChange:i,clientSecret:o,onClientSecretChange:l,required:c}){return(0,t.jsxs)("div",{className:"space-y-4 rounded-lg border border-border p-4",children:[(0,t.jsxs)("div",{children:[(0,t.jsx)("div",{className:"text-sm font-medium text-foreground",children:c?s.oauthClientSecretRequired?"Your OAuth app":`${e.name} needs its own OAuth app`:"Use your own OAuth app"}),(0,t.jsx)("p",{className:"mt-1 text-xs text-muted-foreground",children:s.oauthClientSecretRequired?s.guidanceMd:c?`${e.name} does not let Paperclip register itself automatically, so this connector needs an OAuth app you create. Add the callback URL below in ${e.name}, then paste the client details back here.`:`Register Paperclip's callback URI in ${e.name}, then enter the customer-owned client details.`}),s.consoleLinks?.register?(0,t.jsxs)("a",{href:s.consoleLinks.register,target:"_blank",rel:"noreferrer",className:"mt-2 inline-flex items-center gap-1 text-xs font-semibold text-foreground underline underline-offset-2",children:["Open ",e.name," app settings",(0,t.jsx)(oo,{className:"h-3 w-3"})]}):null]}),n?(0,t.jsxs)("div",{children:[(0,t.jsx)("label",{className:"text-sm font-medium text-foreground",children:"Paperclip callback URL"}),(0,t.jsxs)("div",{className:"mt-2 flex min-w-0 flex-col gap-2 sm:flex-row",children:[(0,t.jsx)("div",{title:n,className:"min-h-11 min-w-0 flex-1 rounded-md border border-input bg-muted/40 px-3 py-2.5 font-mono text-xs leading-tight text-foreground break-all",children:n}),(0,t.jsx)(h5e,{value:n,ariaLabel:"Copy callback URL"})]}),(0,t.jsxs)("p",{className:"mt-2 text-xs text-muted-foreground",children:["Add this exact URL to ",e.name," before continuing. It must match the authorization request."]})]}):null,(0,t.jsxs)("div",{children:[(0,t.jsx)("label",{className:"text-sm font-medium text-foreground",htmlFor:"curated-oauth-client-id",children:"Client ID"}),(0,t.jsx)(dt,{id:"curated-oauth-client-id",value:a,onChange:r(d=>i(d.target.value),"onChange"),autoComplete:"off",placeholder:c?"Required":"Optional",className:"mt-2 h-11 font-mono"})]}),(0,t.jsxs)("div",{children:[(0,t.jsx)("label",{className:"text-sm font-medium text-foreground",htmlFor:"curated-oauth-client-secret",children:"Client secret"}),(0,t.jsx)(dt,{id:"curated-oauth-client-secret",type:"password",value:o,onChange:r(d=>l(d.target.value),"onChange"),autoComplete:"off",placeholder:s.oauthClientSecretRequired?"Required":"Optional for public clients",className:"mt-2 h-11 font-mono"})]})]})}r(Wz,"OAuthClientFields");function Rae({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)(oi,{checked:s===!0,onCheckedChange:n})]}):(0,t.jsxs)("div",{children:[(0,t.jsx)("label",{className:"text-sm font-medium text-foreground",children:e.label}),e.type==="textarea"?(0,t.jsx)(Qn,{value:typeof s=="string"?s:"",onChange:r(a=>n(a.target.value),"onChange"),placeholder:e.placeholder,className:"mt-2 min-h-24"}):e.type==="select"?(0,t.jsxs)("select",{value:typeof s=="string"?s:"",onChange:r(a=>n(a.target.value),"onChange"),className:"mt-2 h-11 w-full rounded-md border border-input bg-background px-3 text-sm text-foreground outline-none focus-visible:border-ring focus-visible:ring-3 focus-visible:ring-ring/30",children:[(0,t.jsx)("option",{value:"",disabled:!0,children:"Select an option"}),(e.options??[]).map(a=>(0,t.jsx)("option",{value:a.value,children:a.label},a.value))]}):(0,t.jsx)(dt,{value:typeof s=="string"?s:"",onChange:r(a=>n(a.target.value),"onChange"),placeholder:e.placeholder,"aria-label":e.label,maxLength:e.validation?.maxLength,className:"mt-2 h-11"}),e.required&&(typeof s!="string"||!s.trim())&&(0,t.jsxs)("p",{className:"mt-2 text-xs text-muted-foreground",children:[e.label," is required."]}),e.helperMd&&(0,t.jsx)("p",{className:"mt-2 text-xs text-muted-foreground",children:e.helperMd})]})}r(Rae,"MethodConfigField");function yht({companyId:e,...s}){const n=te({queryKey:M.agents.list(e),queryFn:r(()=>_t.list(e),"queryFn")});return(0,t.jsx)($V,{...s,agents:(n.data??[]).filter(a=>a.status!=="terminated"),agentsLoading:n.isLoading})}r(yht,"AccessStep");function $V({agents:e,agentsLoading:s=!1,authKind:n,grantKinds:a,grantKind:i,setGrantKind:o,installChoice:l,setInstallChoice:c,installAgentIds:d,setInstallAgentIds:u,lockedAgentId:h,capabilities:p,githubIdentity:f=!1,submitLabel:x,continuesToProvider:g=!1,identityLoading:v=!1,preserveAgentAccess:y=!1,pending:k=!1,hideFooter:w=!1,bare:N=!1,onBack:S,onContinue:C}){const _=p?.editableAgentIds,R=_?e.filter(z=>_.includes(z.id)):e,I=p?.canSetCompanyInstall??!0,T=p?.canCreateOrganizationGrant??!0,E=n!=="none",L=a??["user","organization"],O=(!E||i==="user"||i==="agent"||T)&&(y?!0:h?d.has(h):i==="agent"?l==="specific"&&d.size===1:l==="all"?I:d.size>0),P=h?e.find(z=>z.id===h)?.name??"the requesting agent":null,Q=f?"Connect GitHub as":"Which humans can use this credential?",D=i==="agent"?"Which agent owns this GitHub account?":f&&i==="user"?"Which agents may use your GitHub when you’re responsible?":f?"Which agents may use the shared GitHub account?":"Which agents can use this connection?",F=f?D:"Which agents can use this connection?";return(0,t.jsxs)("div",{className:N?"":"mx-auto max-w-2xl",children:[(0,t.jsx)("div",{className:"overflow-hidden rounded-xl border border-border bg-background",children:(0,t.jsxs)("div",{className:"divide-y divide-border",children:[(0,t.jsxs)("section",{className:"p-6",children:[(0,t.jsx)("h2",{className:"text-sm font-semibold text-foreground",children:Q}),f&&i==="agent"?(0,t.jsx)("p",{className:"mt-2 text-sm text-muted-foreground",children:"This agent uses this GitHub account for everyone’s work, instead of the person giving instructions."}):null,v?(0,t.jsxs)("div",{className:"mt-4 grid gap-2 sm:grid-cols-2","aria-label":"Loading connection identity",children:[(0,t.jsx)(wn,{className:"h-20 w-full rounded-md"}),(0,t.jsx)(wn,{className:"h-20 w-full rounded-md"})]}):E&&L.length===1?(0,t.jsxs)("div",{className:"mt-4 flex items-center gap-3 rounded-md border border-border p-4",children:[L[0]==="user"?(0,t.jsx)(th,{className:"h-4 w-4 shrink-0 text-muted-foreground","aria-hidden":"true"}):L[0]==="agent"?(0,t.jsx)(io,{className:"h-4 w-4 shrink-0 text-muted-foreground","aria-hidden":"true"}):(0,t.jsx)(Nk,{className:"h-4 w-4 shrink-0 text-muted-foreground","aria-hidden":"true"}),(0,t.jsxs)("div",{children:[(0,t.jsx)("div",{className:"text-sm font-medium text-foreground",children:L[0]==="user"?f?"My GitHub account":"Just me":L[0]==="agent"?"A dedicated account for an agent":f?"Shared organization GitHub account (advanced)":"Any human in the organization"}),f?(0,t.jsx)("p",{className:"mt-1 text-xs text-muted-foreground",children:L[0]==="user"?"Agents use it only for runs where you are the responsible person.":L[0]==="agent"?"That agent always uses this account, regardless of who starts the run.":"Eligible agents use one shared credential, regardless of who starts the run."}):null]})]}):E?(0,t.jsx)(em,{ariaLabel:f?Q:"Which humans can use this credential?",className:"mt-4 sm:grid-cols-2",value:i,onValueChange:r(z=>{const K=z;o(K),K==="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)(th,{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)(io,{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)(Nk,{className:"h-4 w-4","aria-hidden":"true"}),accessibleLabel:T?f?"Shared organization GitHub account (advanced)":"Any human in the organization":`${f?"Shared organization GitHub account (advanced)":"Any human in the organization"}. Unavailable: ${p?.organizationGrantReason??"Only a connection manager can share this credential with the organization."}`,tooltip:T?void 0:p?.organizationGrantReason??"Only a connection manager can share this credential with the organization.",disabled:!T}].filter(z=>L.includes(z.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:D}),y?(0,t.jsxs)("div",{className:"mt-4 flex items-start gap-3 rounded-md border border-border bg-muted/40 p-4",children:[(0,t.jsx)(Nk,{className:"mt-0.5 h-4 w-4 shrink-0 text-primary","aria-hidden":"true"}),(0,t.jsxs)("div",{children:[(0,t.jsx)("div",{className:"text-sm font-medium text-foreground",children:"Existing agent access stays the same"}),(0,t.jsx)("p",{className:"mt-1 text-xs text-muted-foreground",children:"Reconnecting replaces the credential without changing which agents can use it."})]})]}):h?(0,t.jsxs)("p",{className:"mt-2 text-sm text-muted-foreground",children:["This task grants access only to ",(0,t.jsx)("span",{className:"font-medium text-foreground",children:P}),". Existing connection access is left unchanged."]}):i==="agent"?(0,t.jsx)("p",{className:"mt-2 text-sm text-muted-foreground",children:"Choose exactly one agent. This identity cannot be shared with other agents."}):(0,t.jsx)(em,{ariaLabel:F,className:"mt-4 sm:grid-cols-2",value:l,onValueChange:r(z=>c(z),"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)(io,{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)(jht,{}),accessibleLabel:I?"Any agent":`Any agent. Unavailable: ${p?.companyInstallReason??"Only someone who can configure this connection can choose this."}`,tooltip:I?void 0:p?.companyInstallReason??"Only someone who can configure this connection can choose this.",disabled:!I}]}),!y&&!h&&l==="specific"?(0,t.jsx)("div",{className:"mt-3",children:(0,t.jsx)(Jj,{agents:R,selectedAgentIds:d,onChange:r(z=>u(i==="agent"&&z.size>1?new Set([[...z].at(-1)]):z),"onChange"),loading:s,emptyMessage:"You cannot edit any agents yet.",showSelectionPreview:!1})}):null]})]})}),w?null:(0,t.jsxs)("div",{className:"mt-6 flex flex-col-reverse gap-2 sm:flex-row sm:items-center sm:justify-between",children:[(0,t.jsx)($,{variant:"ghost",className:"w-full sm:w-auto",onClick:S,disabled:k,children:"Back"}),(0,t.jsxs)($,{className:"w-full sm:w-auto",onClick:C,disabled:!O||v||k,children:[k?(0,t.jsx)(st,{className:"h-4 w-4 animate-spin","aria-hidden":"true"}):null,x,!k&&g?(0,t.jsx)(oo,{className:"h-4 w-4","aria-hidden":"true"}):null]})]})]})}r($V,"AccessStepContent");function LE(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(LE,"connectionDefaultSummarySentence");function OV({companyId:e,agents:s,sentence:n,notice:a,extra:i,forceOpen:o=!1,disabled:l=!1,...c}){const[d,u]=(0,m.useState)(!1);return(0,t.jsxs)(tl,{open:d||o,onOpenChange:u,className:"mt-6 rounded-lg border border-border bg-muted/30 px-4 py-3",children:[(0,t.jsxs)("div",{className:"flex flex-wrap items-baseline justify-between gap-x-3 gap-y-1",children:[(0,t.jsx)("p",{className:"text-sm text-muted-foreground",children:n}),(0,t.jsx)(Dl,{asChild:!0,children:(0,t.jsx)($,{type:"button",variant:"link",className:"h-auto p-0 text-xs font-semibold underline underline-offset-2",disabled:l,children:"Change"})})]}),(a??[]).map(h=>(0,t.jsx)("p",{className:"mt-2 text-xs text-muted-foreground",children:h},h)),(0,t.jsx)(sl,{children:(0,t.jsxs)("div",{className:"mt-3 space-y-6",children:[i,s?(0,t.jsx)($V,{...c,agents:s,bare:!0,hideFooter:!0,submitLabel:"",onBack:r(()=>{},"onBack"),onContinue:r(()=>{},"onContinue")}):(0,t.jsx)(yht,{...c,companyId:e,bare:!0,hideFooter:!0,submitLabel:"",onBack:r(()=>{},"onBack"),onContinue:r(()=>{},"onContinue")})]})})]})}r(OV,"ConnectionAccessDefaults");function jht(){return(0,t.jsxs)("span",{className:"relative block h-4 w-5","aria-hidden":"true",children:[(0,t.jsx)(io,{className:"absolute left-0 top-0 h-3.5 w-3.5"}),(0,t.jsx)(io,{className:"absolute bottom-0 right-0 h-3.5 w-3.5"})]})}r(jht,"BotGroupIcon");function wht(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(wht,"accessSummaryLines");function kht({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)(cs,{className:"h-9 w-9 text-emerald-600 dark:text-emerald-400"})}),(0,t.jsxs)("div",{className:"mt-6 flex items-center justify-center gap-2",children:[(0,t.jsx)(Vi,{name:e,logoUrl:s,darkLogoUrl:n,size:28}),(0,t.jsxs)("h2",{className:"text-2xl font-bold tracking-tight",children:[e," is ready."]})]}),i?(0,t.jsx)("p",{className:"mt-3 text-sm text-muted-foreground",children:i}):null,(0,t.jsx)("dl",{className:"mx-auto mt-6 max-w-xs space-y-1 text-left",children:a.map(l=>(0,t.jsxs)("div",{className:"flex items-baseline justify-between gap-4",children:[(0,t.jsx)("dt",{className:"text-xs font-medium text-muted-foreground",children:l.label}),(0,t.jsx)("dd",{className:"text-sm text-foreground",children:l.value})]},l.label))}),(0,t.jsx)("div",{className:"mt-8",children:(0,t.jsx)($,{size:"lg",className:"px-10",onClick:o,children:"View connection"})})]})}r(kht,"ConnectionSetupCompletionScreen");function p5e(){const{newProjectOpen:e,closeNewProject:s}=_3(),{selectedCompanyId:n}=ps();return n&&e?(0,t.jsx)(Nht,{companyId:n,onClose:s},n):null}r(p5e,"NewProjectDialog");function Nht({companyId:e,onClose:s}){const n=kt(),[a,i]=(0,m.useState)(""),[o]=(0,m.useState)(()=>g6[Math.floor(Math.random()*g6.length)]),[l,c]=(0,m.useState)([]),[d,u]=(0,m.useState)(!1),h=(0,m.useRef)(null),p=je({mutationFn:r(()=>oa.create(e,{name:a.trim(),color:o,status:"planned",repositoryIds:l.map(f=>f.id)}),"mutationFn"),onSuccess:r(f=>{qb(f.id,e),n.invalidateQueries({queryKey:M.projects.all(e)}),s()},"onSuccess")});return(0,t.jsx)(qs,{open:!0,onOpenChange:r(f=>{!f&&!p.isPending&&s()},"onOpenChange"),children:(0,t.jsx)(Ws,{showCloseButton:!1,"aria-describedby":void 0,className:"flex max-h-(--sz-calc-18) flex-col gap-0 overflow-hidden p-0 shadow-sm sm:max-w-lg",onOpenAutoFocus:r(f=>{f.preventDefault(),h.current?.focus()},"onOpenAutoFocus"),children:d?(0,t.jsxs)("div",{className:"min-h-0 overflow-y-auto p-5",children:[(0,t.jsx)(Qs,{className:"sr-only",children:"Connect GitHub"}),(0,t.jsx)(ES,{host:"dialog",serviceSlug:"github",forceNewConnection:!0,onCancel:r(()=>u(!1),"onCancel"),onComplete:r(()=>{n.invalidateQueries({queryKey:TH(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)(Qs,{className:"text-lg font-semibold",children:"Create project"}),(0,t.jsx)($,{type:"button",variant:"ghost",size:"icon-sm",disabled:p.isPending,"aria-label":"Close new project",onClick:s,children:(0,t.jsx)(En,{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)(Zm,{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)(_Se,{companyId:e,selected:l,onChange:c,onConnect:r(()=>u(!0),"onConnect"),disabled:p.isPending})}),p.isError&&(0,t.jsx)("p",{role:"alert",className:"px-5 pt-3 text-sm text-destructive",children:p.error.message}),(0,t.jsxs)("div",{className:"flex shrink-0 justify-end gap-2 px-5 py-5",children:[(0,t.jsx)($,{type:"button",variant:"ghost",disabled:p.isPending,onClick:s,children:"Cancel"}),(0,t.jsx)($,{type:"submit",disabled:!a.trim()||p.isPending,children:p.isPending?"Creating…":"Create project"})]})]})})})}r(Nht,"NewProjectForm");var Kx={list:r(e=>we.get(`/companies/${e}/goals`),"list"),get:r(e=>we.get(`/goals/${e}`),"get"),create:r((e,s)=>we.post(`/companies/${e}/goals`,s),"create"),update:r((e,s)=>we.patch(`/goals/${e}`,s),"update"),remove:r(e=>we.delete(`/goals/${e}`),"remove")};function f5e(e){return{"--sc":`var(${e})`}}r(f5e,"scStyle");function Sht(e){const s=e.replace(/_/g," ");return s.charAt(0).toUpperCase()+s.slice(1)}r(Sht,"sentenceCaseStatus");function li({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",lF[e]??"bg-muted text-muted-foreground"),children:s??e.replace(/[_-]/g," ")})}r(li,"StatusBadge$5");function x5e({status:e}){const s=sFe[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:f5e(s),children:n.replace(/_/g," ")})}r(x5e,"AgentStatusBadge");function C0({status:e,externalConversationState:s}){const n=e==="in_review"&&s==="waiting"?"idle":e,a=NFe[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:f5e(a),children:[(0,t.jsx)(x3,{status:n,size:"sm"}),Sht(n)]})}r(C0,"IssueStatusBadge");var Eae={company:"Organization",team:"Team",agent:"Agent",task:"Task"};function g5e(){const{newGoalOpen:e,newGoalDefaults:s,closeNewGoal:n}=_3(),{selectedCompanyId:a,selectedCompany:i}=ps(),o=kt(),[l,c]=(0,m.useState)(""),[d,u]=(0,m.useState)(""),[h,p]=(0,m.useState)("planned"),[f,x]=(0,m.useState)("task"),[g,v]=(0,m.useState)(""),[y,k]=(0,m.useState)(!1),[w,N]=(0,m.useState)(!1),[S,C]=(0,m.useState)(!1),[_,R]=(0,m.useState)(!1),I=(0,m.useRef)(null),T=g||s.parentId||"",{data:E}=te({queryKey:M.goals.list(a),queryFn:r(()=>Kx.list(a),"queryFn"),enabled:!!a&&e}),L=je({mutationFn:r(z=>Kx.create(a,z),"mutationFn"),onSuccess:r(()=>{o.invalidateQueries({queryKey:M.goals.list(a)}),P(),n()},"onSuccess")}),O=je({mutationFn:r(async z=>{if(!a)throw new Error("No organization selected");return fv.uploadImage(a,z,"goals/drafts")},"mutationFn")});function P(){c(""),u(""),p("planned"),x("task"),v(""),k(!1)}r(P,"reset");function Q(){!a||!l.trim()||L.mutate({title:l.trim(),description:d.trim()||void 0,status:h,level:f,...T?{parentId:T}:{}})}r(Q,"handleSubmit");function D(z){z.key==="Enter"&&(z.metaKey||z.ctrlKey)&&(z.preventDefault(),Q())}r(D,"handleKeyDown");const F=(E??[]).find(z=>z.id===T);return(0,t.jsx)(qs,{open:e,onOpenChange:r(z=>{z||(P(),n())},"onOpenChange"),children:(0,t.jsxs)(Ws,{showCloseButton:!1,className:W("p-0 gap-0",y?"sm:max-w-2xl":"sm:max-w-lg"),onKeyDown:D,children:[(0,t.jsxs)("div",{className:"flex items-center justify-between px-4 py-2.5 border-b border-border",children:[(0,t.jsxs)("div",{className:"flex items-center gap-2 text-sm text-muted-foreground",children:[i&&(0,t.jsx)("span",{className:"bg-muted px-1.5 py-0.5 rounded text-xs font-medium",children:i.issuePrefix}),(0,t.jsx)("span",{className:"text-muted-foreground/60",children:"›"}),(0,t.jsx)("span",{children:s.parentId?"New sub-goal":"New goal"})]}),(0,t.jsxs)("div",{className:"flex items-center gap-1",children:[(0,t.jsx)($,{variant:"ghost",size:"icon-xs",className:"text-muted-foreground",onClick:r(()=>k(!y),"onClick"),children:y?(0,t.jsx)(Owe,{className:"h-3.5 w-3.5"}):(0,t.jsx)(tw,{className:"h-3.5 w-3.5"})}),(0,t.jsx)($,{variant:"ghost",size:"icon-xs",className:"text-muted-foreground",onClick:r(()=>{P(),n()},"onClick"),children:(0,t.jsx)("span",{className:"text-lg leading-none",children:"×"})})]})]}),(0,t.jsx)("div",{className:"px-4 pt-4 pb-2 shrink-0",children:(0,t.jsx)("input",{className:"w-full text-lg font-semibold bg-transparent outline-none placeholder:text-muted-foreground/50",placeholder:"Goal title",value:l,onChange:r(z=>c(z.target.value),"onChange"),onKeyDown:r(z=>{z.key==="Tab"&&!z.shiftKey&&(z.preventDefault(),I.current?.focus())},"onKeyDown"),autoFocus:!0})}),(0,t.jsx)("div",{className:"px-4 pb-2 overflow-y-auto max-h-(--sz-50vh)",children:(0,t.jsx)(Jc,{ref:I,value:d,onChange:u,placeholder:"Add description...",bordered:!1,contentClassName:W("text-sm text-muted-foreground",y?"min-h-(--sz-220px)":"min-h-(--sz-120px)"),imageUploadHandler:r(async z=>(await O.mutateAsync(z)).contentPath,"imageUploadHandler")})}),(0,t.jsxs)("div",{className:"flex items-center gap-1.5 px-4 py-2 border-t border-border flex-wrap",children:[(0,t.jsxs)(dr,{open:w,onOpenChange:N,children:[(0,t.jsx)(wr,{asChild:!0,children:(0,t.jsx)("button",{className:"inline-flex items-center gap-1.5 rounded-md border border-border px-2 py-1 text-xs hover:bg-accent/50 transition-colors",children:(0,t.jsx)(li,{status:h})})}),(0,t.jsx)(sr,{className:"w-40 p-1",align:"start",children:Rbe.map(z=>(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",z===h&&"bg-accent"),onClick:r(()=>{p(z),N(!1)},"onClick"),children:z},z))})]}),(0,t.jsxs)(dr,{open:S,onOpenChange:C,children:[(0,t.jsx)(wr,{asChild:!0,children:(0,t.jsxs)("button",{className:"inline-flex items-center gap-1.5 rounded-md border border-border px-2 py-1 text-xs hover:bg-accent/50 transition-colors",children:[(0,t.jsx)(Gl,{className:"h-3 w-3 text-muted-foreground"}),Eae[f]??f]})}),(0,t.jsx)(sr,{className:"w-40 p-1",align:"start",children:rbe.map(z=>(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",z===f&&"bg-accent"),onClick:r(()=>{x(z),C(!1)},"onClick"),children:Eae[z]??z},z))})]}),(0,t.jsxs)(dr,{open:_,onOpenChange:R,children:[(0,t.jsx)(wr,{asChild:!0,children:(0,t.jsxs)("button",{className:"inline-flex items-center gap-1.5 rounded-md border border-border px-2 py-1 text-xs hover:bg-accent/50 transition-colors",children:[(0,t.jsx)(K0,{className:"h-3 w-3 text-muted-foreground"}),F?F.title:"Parent goal"]})}),(0,t.jsxs)(sr,{className:"w-48 p-1",align:"start",children:[(0,t.jsx)("button",{className:W("flex items-center gap-2 w-full px-2 py-1.5 text-xs rounded hover:bg-accent/50",!T&&"bg-accent"),onClick:r(()=>{v(""),R(!1)},"onClick"),children:"No parent"}),(E??[]).map(z=>(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",z.id===T&&"bg-accent"),onClick:r(()=>{v(z.id),R(!1)},"onClick"),children:z.title},z.id))]})]})]}),(0,t.jsx)("div",{className:"flex items-center justify-end px-4 py-2.5 border-t border-border",children:(0,t.jsx)($,{size:"sm",disabled:!l.trim()||L.isPending,onClick:Q,children:L.isPending?"Creating…":s.parentId?"Create sub-goal":"Create goal"})})]})})}r(g5e,"NewGoalDialog");var vD=r((e,s)=>`/companies/${e}/agents/${s}/dot-binding`,"path"),OI={create:r(e=>we.post(`/companies/${e}/dot-invitations`,{}),"create"),connection:r((e,s,n)=>we.get(vD(e,s),{signal:n}),"connection"),pair:r((e,s,n)=>we.post(vD(e,s),{replaceBindingId:n}),"pair"),retry:r((e,s,n)=>we.post(vD(e,s)+"/event-test",{bindingId:n}),"retry")};function Cht(e){const s=_ht(e),n=Aht(e);return`You're invited to join a Paperclip company as an agent.
330
+ `;function $dt(){const e=new Blob([Ddt],{type:"application/javascript"}),s=URL.createObjectURL(e);try{return new Worker(s)}finally{URL.revokeObjectURL(s)}}r($dt,"createSandboxedWorker");var Tz=new Map,IE=new Map,fR=new Set,xR=new Map,k_e=null;function Odt(e){k_e=e}r(Odt,"setDynamicParserResultNotifier");function N_e(e,s){e.worker.postMessage(s)}r(N_e,"sendToWorker");function Bdt(e){return e.nextId++}r(Bdt,"nextRequestId");function Fdt(e,s){return`${s}\0${e}`}r(Fdt,"lineCacheKey");function zdt(){k_e?.()}r(zdt,"notifyResultReady");function qdt(e,s,n){return new Promise(a=>{const i=Bdt(e);e.pendingResolves.set(i,a),N_e(e,{type:"parse",id:i,line:s,ts:n})})}r(qdt,"parseLineAsync");function TC(e){for(const s of e.pendingResolves.values())s([]);e.pendingResolves.clear()}r(TC,"drainPendingRequests");function Udt(e){return new Promise((s,n)=>{const a=$dt(),i={worker:a,ready:!1,nextId:1,pendingResolves:new Map},o=setTimeout(()=>{TC(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"&&TC(i)},s(i);return}if(c.type==="error"){clearTimeout(o),TC(i),a.terminate(),n(new Error(c.message));return}},a.onerror=l=>{clearTimeout(o),TC(i),a.terminate(),n(new Error(`Worker error: ${l.message}`))},N_e(i,{type:"init",source:e})})}r(Udt,"initSandboxedWorker");function Kdt(e){const s=new Map,n=new Set;return{parseStdoutLine:r((i,o)=>{const l=Fdt(i,o),c=s.get(l);return c?c.slice():(n.has(l)||(n.add(l),qdt(e,i,o).then(d=>{n.delete(l),s.set(l,d),zdt()})),[])},"parseStdoutLine")}}r(Kdt,"buildParserModule");async function Rz(e){const s=IE.get(e);if(s)return s;if(fR.has(e))return null;const n=xR.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 fR.add(e),null;const o=await Udt(await i.text());Tz.set(e,o);const l=Kdt(o);return IE.set(e,l),l}catch{return fR.add(e),null}finally{xR.delete(e)}})();return xR.set(e,a),a}r(Rz,"loadDynamicParser");function Ez(e){const s=IE.has(e);IE.delete(e),fR.delete(e),xR.delete(e);const n=Tz.get(e);return n&&(TC(n),n.worker.terminate(),Tz.delete(e)),s}r(Ez,"invalidateDynamicParser");var gR=[],AM=new Map,Lz=new Set,S_e=new Map,iD=new Set,LI=new Map,Mz=new Set;function C_e(e){return Mz.add(e),()=>Mz.delete(e)}r(C_e,"onAdapterChange");function __e(){for(const e of Mz)e()}r(__e,"notifyAdapterChange");Odt(__e);function Qdt(){for(const e of[Cot,qot,llt,plt,$lt,Ylt,lct,gct,Act,Oct,ldt,tdt,_lt,Ndt,AE,Pdt])Lz.add(e.type),S_e.set(e.type,e),Ay(e)}r(Qdt,"registerBuiltInUIAdapters");function Ay(e){const s=gR.findIndex(n=>n.type===e.type);s>=0?gR.splice(s,1,e):gR.push(e),AM.set(e.type,e),__e()}r(Ay,"registerUIAdapter");function A_e(e){return AM.get(e)??null}r(A_e,"findUIAdapter");Qdt();function RS(e){const s=AM.get(e);if(!s){let n=!1;return{type:e,label:e,parseStdoutLine:r((a,i)=>(n||(n=!0,Rz(e).then(o=>{o&&Ay({type:e,label:e,parseStdoutLine:o.parseStdoutLine,createStdoutParser:o.createStdoutParser,ConfigFields:_j,buildAdapterConfig:Aj})})),AE.parseStdoutLine(a,i)),"parseStdoutLine"),ConfigFields:_j,buildAdapterConfig:Aj}}return s}r(RS,"getUIAdapter");function Wdt(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 Lz){const i=S_e.get(a);if(!i)continue;const o=n.has(a),l=s.has(a),c=iD.has(a);if(o&&l&&!c){iD.add(a);const d=(LI.get(a)??0)+1;LI.set(a,d);let u=!1;const h=i.parseStdoutLine,p=e.find(f=>f.type===a)?.label??a;Ay({type:a,label:p,parseStdoutLine:r((f,x)=>(u||(u=!0,Rz(a).then(g=>{g&&LI.get(a)===d&&Ay({type:a,label:p,parseStdoutLine:g.parseStdoutLine,createStdoutParser:g.createStdoutParser,ConfigFields:i.ConfigFields,buildAdapterConfig:i.buildAdapterConfig})})),h(f,x)),"parseStdoutLine"),ConfigFields:i.ConfigFields,buildAdapterConfig:i.buildAdapterConfig})}else(!o||!l)&&c&&(iD.delete(a),LI.delete(a),Ez(a),Ay(i))}for(const{type:a,label:i}of e){if(Lz.has(a))continue;const o=AM.get(a);if(o&&o!==AE)continue;let l=!1;const c=o?.parseStdoutLine??AE.parseStdoutLine;Ay({type:a,label:i,parseStdoutLine:r((d,u)=>(l||(l=!0,Rz(a).then(h=>{h&&Ay({type:a,label:i,parseStdoutLine:h.parseStdoutLine,createStdoutParser:h.createStdoutParser,ConfigFields:o?.ConfigFields??_j,buildAdapterConfig:o?.buildAdapterConfig??Aj})})),c(d,u)),"parseStdoutLine"),ConfigFields:o?.ConfigFields??_j,buildAdapterConfig:o?.buildAdapterConfig??Aj})}}r(Wdt,"syncExternalAdapters");function CV(){return[...gR]}r(CV,"listUIAdapters");function Pz(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(Pz,"resolveStdoutParser");function I_e(e,s){if((s.kind==="thinking"||s.kind==="assistant")&&s.delta){const n=e[e.length-1];if(n&&n.kind===s.kind&&n.delta&&n.channel===s.channel){n.text+=s.text,n.ts=s.ts;return}}e.push(s)}r(I_e,"appendTranscriptEntry");function Hdt(e,s){for(const n of s)I_e(e,n)}r(Hdt,"appendTranscriptEntries");function Vdt(e,s=160){return e.length<=s?e:`${e.slice(0,s-3)}...`}r(Vdt,"truncateTranscriptLine");function Gdt(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(Gdt,"formatTranscriptParserError");function Ydt(e,s,n,a){const i=Gdt(n)||"unknown parser error",o=Vdt(e);return{kind:"result",ts:s,text:$m(`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(Ydt,"createTranscriptParseErrorEntry");function _V(e){const{entries:s,line:n,ts:a,parseLine:i,reset:o,redactionOptions:l}=e;try{Hdt(s,i(n,a).map(c=>qat(c,l)))}catch(c){o?.(),I_e(s,Ydt(n,a,c,l))}}r(_V,"appendParsedTranscriptLine");function T_e(e){const{entries:s,chunks:n,from:a,parseLine:i,reset:o,redactionOptions:l}=e;let c=e.stdoutBuffer;for(let d=a;d<n.length;d+=1){const u=n[d];if(u.stream==="stderr"){s.push({kind:"stderr",ts:u.ts,text:$m(u.chunk,l)});continue}if(u.stream==="system"){s.push({kind:"system",ts:u.ts,text:$m(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&&_V({entries:s,line:f,ts:u.ts,parseLine:i,reset:o,redactionOptions:l})}}return c}r(T_e,"foldTranscriptChunks");function R_e(e,s,n){const a=[],i={enabled:n?.censorUsernameInLogs??!1},{parseLine:o,reset:l}=Pz(s),c=T_e({entries:a,chunks:e,from:0,stdoutBuffer:"",parseLine:o,reset:l,redactionOptions:i}).trim();return c&&_V({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(R_e,"buildTranscript");var Vre=[];function Zdt(e,s){const n={enabled:s?.censorUsernameInLogs??!1},a=typeof e!="function"&&typeof e.createStdoutParser=="function";let i=Pz(e),o=[],l="",c=Vre,d=[];const u=r(()=>{i=Pz(e),o=[],l="",c=Vre},"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 R_e(f,e,s);const g=o.slice(),v=g.length-1;return v>=0&&(g[v]={...g[v]}),x&&_V({entries:g,line:x,ts:f.length>0?f[f.length-1].ts:new Date().toISOString(),parseLine:i.parseLine,reset:i.reset,redactionOptions:n}),g},"publish");return{update(f){return f===c||(h(f)||u(),l=T_e({entries:o,chunks:f,from:c.length,stdoutBuffer:l,parseLine:i.parseLine,reset:i.reset,redactionOptions:n}),c=f,d=p(f)),d}}}r(Zdt,"createIncrementalTranscript");function Jdt({agents:e,value:s,onChange:n,disabled:a=!1,excludeAgentIds:i=[],disabledEmptyLabel:o="Reports to: N/A (CEO)",chooseLabel:l="Reports to..."}){const[c,d]=(0,m.useState)(!1),u=new Set(i),h=e.filter(g=>g.status!=="terminated"&&!u.has(g.id)),p=s?e.find(g=>g.id===s):null,f=p?.status==="terminated",x=!!(s&&!p);return(0,t.jsxs)(dr,{open:c,onOpenChange:d,children:[(0,t.jsx)(wr,{asChild:!0,children:(0,t.jsx)("button",{type:"button",className:W("inline-flex max-w-full min-w-0 items-center gap-1.5 overflow-hidden rounded-md border border-border px-2 py-1 text-xs hover:bg-accent/50 transition-colors",f&&"border-amber-600/45 bg-amber-500/5",a&&"opacity-60 cursor-not-allowed"),disabled:a,children:x?(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)(pd,{className:"h-3 w-3 shrink-0 text-muted-foreground"}),(0,t.jsx)("span",{className:"min-w-0 truncate text-muted-foreground",children:"Unknown manager (stale ID)"})]}):p?(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)(lr,{agent:p,size:16,className:"h-3 w-3 shrink-0 text-muted-foreground"}),(0,t.jsx)("span",{className:W("min-w-0 truncate",f&&"text-amber-900 dark:text-amber-200"),children:`Reports to ${p.name}${f?" (terminated)":""}`})]}):(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)(pd,{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)(sr,{className:"w-48 p-1",align:"start",children:[(0,t.jsx)("button",{type:"button",className:W("flex items-center gap-2 w-full px-2 py-1.5 text-xs rounded hover:bg-accent/50",s===null&&"bg-accent"),onClick:r(()=>{n(null),d(!1)},"onClick"),children:"No manager"}),f&&(0,t.jsxs)("div",{className:"flex min-w-0 items-center gap-2 overflow-hidden px-2 py-1.5 text-xs text-muted-foreground border-b border-border mb-0.5",children:[(0,t.jsx)(lr,{agent:p,size:16,className:"shrink-0 h-3 w-3"}),(0,t.jsxs)("span",{className:"min-w-0 truncate",children:["Current: ",p.name," (terminated)"]})]}),x&&(0,t.jsx)("div",{className:"px-2 py-1.5 text-xs text-muted-foreground border-b border-border mb-0.5",children:"Saved manager is missing from this organization. Choose a new manager or clear."}),h.map(g=>(0,t.jsxs)("button",{type:"button",className:W("flex items-center gap-2 w-full min-w-0 px-2 py-1.5 text-xs rounded hover:bg-accent/50 overflow-hidden",g.id===s&&"bg-accent"),onClick:r(()=>{n(g.id),d(!1)},"onClick"),children:[(0,t.jsx)(lr,{agent:g,size:16,className:"shrink-0 h-3 w-3 text-muted-foreground"}),(0,t.jsx)("span",{className:"min-w-0 truncate",children:g.name}),(0,t.jsx)("span",{className:"text-muted-foreground ml-auto shrink-0",children:ZCe[g.role]??g.role})]},g.id))]})]})}r(Jdt,"ReportsToPicker");var Xdt="__secret_folder__:";function eut(e){return!e||e==="active"?null:(0,t.jsx)(it,{variant:"outline",className:"ml-auto text-(length:--text-nano) font-normal text-muted-foreground",children:e})}r(eut,"statusBadge");function E_e(e){return e.split("/").filter(s=>s.length>0)}r(E_e,"splitSecretPath$1");function bR(e){return e.join("/")}r(bR,"pathKey$1");function E2(e){return e.length>0?`/${e.join("/")}`:"/"}r(E2,"pathLabel");function tut(e,s){return e.length<s.length?!1:s.every((n,a)=>e[a]===n)}r(tut,"pathStartsWith");function Gre(e){return`${Xdt}${bR(e)}`}r(Gre,"folderValue");function sut(e,s,n){const a=s.length,i=new Map,o=[];for(const c of e){const d=E_e(c.name);if(tut(d,s)){if(d.length>a+1){const u=d.slice(0,a+1),h=bR(u);if(!i.has(h)){const p=u[u.length-1]??"/",f=E2(u);i.set(h,{key:`folder-${h||"root"}`,value:Gre(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-${bR(s)}`,value:Gre(c),label:"Up one folder",title:E2(c),searchText:E2(c),kind:"back",folderPath:bR(c),pathHint:E2(c)})}return l.push(...i.values(),...o),{id:"browse-secrets",label:s.length>0?E2(s):"Browse secrets",options:l}}r(sut,"buildFolderGroup");function AV({secretId:e,secrets:s,recentlyUsedSecrets:n,disabled:a,onSelect:i,onCreateNew:o,triggerClassName:l,disablePortal:c}){const[d,u]=(0,m.useState)(""),h=(0,m.useMemo)(()=>s.find(y=>y.id===e)??null,[s,e]),p=!!e&&!h,f=(0,m.useMemo)(()=>d?d.split("/"):[],[d]),x=(0,m.useMemo)(()=>s.some(y=>E_e(y.name).length>1),[s]),g=(0,m.useMemo)(()=>{const y=[];p&&y.push({id:"current-missing",label:"Current",options:[{key:`missing-${e}`,value:e,label:`Missing secret (${e.slice(0,8)}…)`,title:`Missing secret (${e})`,missing:!0,disabled:!0}]});const k=(n??[]).filter(w=>w.status==="active"&&w.id!==e);return k.length>0&&y.push({id:"recently-used",label:"Recently used",options:k.map(w=>({key:`recent-${w.id}`,value:w.id,label:w.name,title:w.name,searchText:`${w.key} ${w.name}`,secret:w,status:w.status,kind:"secret"}))}),y.push({id:"all-secrets",label:k.length>0?"All secrets":void 0,options:s.map(w=>({key:`all-${w.id}`,value:w.id,label:w.name,title:w.name,searchText:`${w.key} ${w.name}`,secret:w,status:w.status,kind:"secret",disabled:w.status!=="active"&&w.id!==e}))}),y},[p,n,e,s]),v=(0,m.useCallback)((y,k)=>{if(!x||PFe(y))return k;const w=sut(s,f,e),N=k.filter(S=>S.id==="current-missing"||S.id==="recently-used");return w.options.length>0?[...N,w]:N},[f,x,e,s]);return(0,t.jsx)(mg,{value:e||"",groups:g,onValueChange:r((y,k)=>{if(k.folderPath!==void 0)return u(k.folderPath),!1;u(""),i(y)},"onValueChange"),deriveGroups:v,disabled:a,disablePortal:c,placeholder:"Select secret…",searchPlaceholder:"Search secrets…",emptyMessage:"No matching secrets",triggerClassName:W("h-(--sz-34px) min-h-(--sz-34px) font-mono text-sm",p&&"border-destructive text-destructive",h&&h.status!=="active"&&"border-amber-500/60",l),renderValue:r(y=>{if(!y)return(0,t.jsx)("span",{className:"text-muted-foreground",children:"Select secret…"});if(y.missing)return(0,t.jsxs)("span",{className:"flex w-full min-w-0 items-center gap-1.5 text-destructive",children:[(0,t.jsx)(Ni,{className:"size-3.5 shrink-0"}),(0,t.jsx)("span",{className:"min-w-0 flex-1 truncate",children:y.label})]});const k=y.status&&y.status!=="active";return(0,t.jsxs)("span",{className:"flex w-full min-w-0 items-center gap-1.5",title:y.title,children:[(0,t.jsx)(Ni,{className:W("size-3.5 shrink-0",k?"text-amber-600":"text-muted-foreground")}),(0,t.jsx)("span",{className:"min-w-0 flex-1 truncate",children:y.label}),k?(0,t.jsxs)("span",{className:"text-amber-600",children:["(",y.status,")"]}):null]})},"renderValue"),renderOption:r((y,{selected:k})=>{if(y.kind==="folder"||y.kind==="back"){const w=y.kind==="back"?tQe:Wl;return(0,t.jsxs)("span",{className:"flex min-w-0 flex-1 items-center gap-1.5",title:y.title??y.label,children:[(0,t.jsx)(w,{className:"size-3.5 shrink-0 text-muted-foreground"}),(0,t.jsxs)("span",{className:"flex min-w-0 flex-col",children:[(0,t.jsx)("span",{className:W("truncate text-sm",k&&"font-medium"),children:y.label}),y.pathHint?(0,t.jsx)("span",{className:"truncate font-mono text-(length:--text-micro) text-muted-foreground",children:y.pathHint}):null]})]})}return(0,t.jsxs)("span",{className:W("flex min-w-0 flex-1 items-center gap-1.5",y.disabled&&"opacity-60"),title:y.title??y.label,children:[(0,t.jsx)(Ni,{className:"size-3.5 shrink-0 text-muted-foreground"}),(0,t.jsxs)("span",{className:"flex min-w-0 flex-col",children:[(0,t.jsx)("span",{className:W("min-w-0 truncate font-mono text-sm",k&&"font-medium"),children:y.label}),y.pathHint&&y.pathHint!==y.label?(0,t.jsx)("span",{className:"truncate font-mono text-(length:--text-micro) text-muted-foreground",children:y.pathHint}):null]}),eut(y.status)]})},"renderOption"),createItem:o?{render:r(y=>(0,t.jsxs)("span",{className:"flex items-center gap-1.5 text-sm",children:[(0,t.jsx)(gn,{className:"size-3.5 shrink-0"}),y.trim()?(0,t.jsxs)("span",{children:["Create secret ",(0,t.jsxs)("span",{className:"font-mono",children:["“",y.trim(),"”"]}),"…"]}):(0,t.jsx)("span",{children:"Create new secret…"})]}),"render"),onSelect:r(y=>o(y),"onSelect")}:void 0})}r(AV,"SecretPicker");var nut=/^[a-z][a-z0-9_]*$/,Yre="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 L_e({mode:e,initialName:s,initialValue:n,existingSecretNames:a,onCancel:i,onSubmit:o}){const[l,c]=(0,m.useState)(s),[d,u]=(0,m.useState)(n),[h,p]=(0,m.useState)(!1),[f,x]=(0,m.useState)(!1),[g,v]=(0,m.useState)(null),[y,k]=(0,m.useState)(!1),w=l.trim(),N=w?nut.test(w)?a?.some(I=>I.toLowerCase()===w)?"A secret with this name already exists":null:"Use lowercase letters, digits and _":y?"Name is required":null,S=d.length===0&&y?"Value is required":null,C=!f&&w.length>0&&d.length>0&&!N;async function _(){if(k(!0),!!C){x(!0),v(null);try{await o(w,d)}catch(I){v(I instanceof Error?I.message:"Failed to create secret"),x(!1)}}}r(_,"handleSubmit");const R=e==="create"?"Create & bind":"Store & bind";return(0,t.jsxs)("div",{className:"w-72 space-y-3",children:[(0,t.jsxs)("div",{className:"space-y-1",children:[(0,t.jsx)(cFe,{className:"text-sm font-medium",children:e==="create"?"Create secret":"Store value as secret"}),e==="store"?(0,t.jsxs)(JBe,{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(Yre,N&&"border-destructive focus-visible:ring-destructive/40"),value:l,autoFocus:!0,spellCheck:!1,placeholder:"secret_name","aria-label":"Secret name","aria-invalid":N?!0:void 0,onChange:r(I=>c(I.target.value),"onChange"),onBlur:r(()=>k(!0),"onBlur"),onKeyDown:r(I=>{I.key==="Enter"&&(I.preventDefault(),_())},"onKeyDown")}),N?(0,t.jsx)("span",{className:"block text-(length:--text-micro) text-destructive",children:N}):null]}),(0,t.jsxs)("label",{className:"block space-y-1",children:[(0,t.jsx)("span",{className:"text-(length:--text-micro) font-medium text-muted-foreground",children:"Value"}),(0,t.jsxs)("div",{className:"relative",children:[(0,t.jsx)("input",{className:W(Yre,"pr-8",S&&"border-destructive focus-visible:ring-destructive/40"),type:h?"text":"password",value:d,readOnly:e==="store",spellCheck:!1,placeholder:e==="create"?"value":void 0,"aria-label":"Secret value","aria-invalid":S?!0:void 0,onChange:e==="create"?I=>u(I.target.value):void 0}),(0,t.jsx)("button",{type:"button",className:"absolute right-1.5 top-1/2 -translate-y-1/2 rounded p-1 text-muted-foreground hover:text-foreground","aria-label":h?"Hide value":"Show value",onClick:r(()=>p(I=>!I),"onClick"),children:h?(0,t.jsx)(eh,{className:"h-3.5 w-3.5"}):(0,t.jsx)(Jd,{className:"h-3.5 w-3.5"})})]}),S?(0,t.jsx)("span",{className:"block text-(length:--text-micro) text-destructive",children:S}):null]}),g?(0,t.jsx)("p",{className:"text-(length:--text-micro) text-destructive",children:g}):null,(0,t.jsxs)("div",{className:"flex items-center justify-end gap-2 pt-0.5",children:[(0,t.jsx)($,{type:"button",variant:"ghost",size:"sm",onClick:i,disabled:f,children:"Cancel"}),(0,t.jsxs)($,{type:"button",size:"sm",onClick:r(()=>{_()},"onClick"),disabled:!C,children:[f?(0,t.jsx)(st,{className:"h-3.5 w-3.5 animate-spin"}):null,R]})]})]})}r(L_e,"SecretPopoverForm");function M_e(e){return(0,t.jsx)(L_e,{mode:"create",...e})}r(M_e,"CreateSecretPopover");function rut(e){return(0,t.jsx)(L_e,{mode:"store",...e})}r(rut,"ConvertToSecretPopover");var aut=/(api[-_]?key|access[-_]?token|auth(?:_?token)?|authorization|bearer|secret|passwd|password|credential|jwt|private[-_]?key|cookie|connectionstring)/i,iut=[/^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 out(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(out,"looksHighEntropy");function lut(e,s){return s?aut.test(e)||iut.some(n=>n.test(s))?!0:out(s):!1}r(lut,"isSensitiveEnv");var Zre=0;function cut(){return Zre+=1,`env-row-${Zre}`}r(cut,"nextRowId");function Sx(e="text"){return{id:cut(),name:"",source:e,textValue:"",secretId:"",userSecretKey:"",required:!0,version:"latest"}}r(Sx,"emptyRow");function dut(e){return typeof e=="object"&&e!==null&&"type"in e&&e.type==="secret_ref"}r(dut,"isSecretRef");function uut(e){return typeof e=="object"&&e!==null&&"type"in e&&e.type==="plain"}r(uut,"isPlainObj");function mut(e){return typeof e=="object"&&e!==null&&"type"in e&&e.type==="user_secret_ref"}r(mut,"isUserSecretRef");function oD(e){return!e||typeof e!="object"?[]:Object.entries(e).map(([s,n])=>{if(typeof n=="string")return{...Sx(),name:s,textValue:n};if(dut(n)){const a=typeof n.version=="number"?n.version:"latest";return{...Sx(),name:s,source:"secret",secretId:typeof n.secretId=="string"?n.secretId:"",version:a}}if(mut(n)){const a=typeof n.version=="number"?n.version:"latest";return{...Sx(),name:s,source:"user_secret",userSecretKey:typeof n.key=="string"?n.key:"",required:n.required!==!1,version:a}}return uut(n)?{...Sx(),name:s,source:"text",textValue:typeof n.value=="string"?n.value:""}:{...Sx(),name:s}})}r(oD,"rowsFromValue");function vR(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(vR,"valueFromRows");var Jre="CLAUDE_CODE_OAUTH_TOKEN";function nk(){return vR([{...Sx("user_secret"),name:"CLAUDE_CODE_OAUTH_TOKEN",userSecretKey:"CLAUDE_CODE_OAUTH_TOKEN",required:!0,version:"latest"}])??{}}r(nk,"buildFixedClaudeOAuthBinding");var hut=/^[A-Za-z_][A-Za-z0-9_]*$/;function put(e,s,n){const a=e.trim();if(!a)return null;if(!hut.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(put,"validateName");function fut(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(fut,"computeDuplicateNames");function xut(e,s){return s===e.source?{kind:"noop"}:s==="secret"?e.textValue.trim()?{kind:"open-store",name:TE(e.name)||"secret",value:e.textValue}:{kind:"to-secret"}:{kind:"to-text",undoFrom:e.secretId?{...e}:null}}r(xut,"planSourceSwitch");function P_e(e,s){if(e.source!=="secret"||!e.secretId)return null;const n=s.find(a=>a.id===e.secretId);return n?n.status!=="active"?{level:"warn",kind:"disabled",message:"Runs will fail until re-enabled or rebound."}:null:{level:"error",kind:"missing",message:"This secret no longer exists — runs will fail until you rebind."}}r(P_e,"computeRowHealth");function D_e(e,s){if(e.source!=="user_secret"||!e.userSecretKey||!s?.length)return null;const n=s.find(a=>a.key===e.userSecretKey);return n?n.status!=="active"?{level:"warn",kind:"disabled",message:"Runs will fail until this user secret definition is re-enabled or rebound."}:null:{level:"error",kind:"missing",message:"This user secret definition no longer exists — runs will fail until you rebind."}}r(D_e,"computeUserSecretRowHealth");function TE(e){return e.trim().toLowerCase().replace(/[^a-z0-9_]+/g,"_").replace(/^_+|_+$/g,"").slice(0,64)}r(TE,"secretNameFromKey");function f_(e){return e.trim().toUpperCase().replace(/[^A-Z0-9_]+/g,"_").replace(/^_+|_+$/g,"").slice(0,64)}r(f_,"envKeyFromSecretName");var gut="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",Xre="min-w-0 flex-1 bg-transparent px-2 py-1.5 text-sm font-mono outline-none placeholder:text-muted-foreground/40";function but({row:e,isLast:s,secrets:n,userSecretDefinitions:a,recentlyUsedSecrets:i,disabled:o,nameIssue:l,showNameIssue:c,dirtyFields:d,onPatch:u,onRemove:h,onNameBlur:p,onNamePaste:f,onEnterInValueLast:x,onCreateSecret:g,onToast:v,focusRequest:y,onFocusConsumed:k}){const w=(0,m.useRef)(null),N=(0,m.useRef)(null),S=(0,m.useRef)(null),[C,_]=(0,m.useState)(null),[R,I]=(0,m.useState)(!1),[T,E]=(0,m.useState)(null),L=P_e(e,n)??D_e(e,a),O=e.source==="secret"?n.find(J=>J.id===e.secretId)??null:null,P=(a?.length??0)>0,Q=e.source==="text"&&!e.sensitiveDismissed&&lut(e.name,e.textValue);(0,m.useEffect)(()=>{y&&(y==="name"?w.current?.focus():e.source==="text"?N.current?.focus():e.source==="secret"?S.current?.querySelector("[role=combobox]")?.focus():S.current?.querySelector("select,input")?.focus(),k())},[y,k,e.source]),(0,m.useEffect)(()=>{if(!T)return;const J=window.setTimeout(()=>E(null),5e3);return()=>window.clearTimeout(J)},[T]);function D(J){if(J==="user_secret"){if(e.source==="user_secret")return;u({source:"user_secret",secretId:"",version:"latest"}),window.setTimeout(()=>S.current?.querySelector("select,input")?.focus(),0);return}const re=xut(e,J);switch(re.kind){case"noop":return;case"open-store":{const{name:oe,value:V}=re;window.setTimeout(()=>_({mode:"store",name:oe,value:V}),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&&E(re.undoFrom),u({source:"text",secretId:"",userSecretKey:"",required:!0,version:"latest"}),window.setTimeout(()=>N.current?.focus(),0);return}}r(D,"switchSource");async function F(J,re){const oe=await g(J,re);u({source:"secret",secretId:oe.id,userSecretKey:"",required:!0,version:"latest",textValue:""}),v(`Secret ${oe.name} created`),_(null)}r(F,"submitSecretPopover");function z(){const J=TE(e.name)||"secret",{textValue:re}=e;window.setTimeout(()=>_({mode:"store",name:J,value:re}),0)}r(z,"openStoreAsSecret");const K=e.source==="text"?"Text value":e.source==="secret"?"Organization secret reference":"User secret reference",U=`${e.id}-name-error`,q=`${e.id}-health`,G=d.name||d.value,se=O?Math.max(0,O.latestVersion):0,Z=e.version==="latest"?"latest":`v${e.version}`,ie=e.version!=="latest";return(0,t.jsxs)("div",{className:W("group/row grid grid-cols-(--gtc-13) items-start gap-x-1.5 gap-y-1 rounded-md px-1 py-1","@[40rem]/env:grid-cols-(--gtc-14) @[40rem]/env:items-center",G&&"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(gut,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?U:void 0,onChange:r(J=>u({name:J.target.value}),"onChange"),onBlur:p,onPaste:r(J=>{e.name||f(J.clipboardData.getData("text"))&&J.preventDefault()},"onPaste"),onKeyDown:r(J=>{J.key==="Enter"&&(J.preventDefault(),e.source==="text"?N.current?.focus():S.current?.querySelector("[role=combobox],select,input")?.focus())},"onKeyDown")})}),(0,t.jsxs)("div",{className:"col-span-2 col-start-1 row-start-2 min-w-0 @[40rem]/env:col-span-1 @[40rem]/env:col-start-2 @[40rem]/env:row-start-1",children:[(0,t.jsxs)(dr,{open:C!==null,onOpenChange:r(J=>{J||_(null)},"onOpenChange"),children:[(0,t.jsx)(iF,{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)(ia,{children:[(0,t.jsxs)(Bn,{children:[(0,t.jsx)(On,{asChild:!0,children:(0,t.jsx)(ra,{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)(BQe,{className:"size-3.5"}):e.source==="secret"?(0,t.jsx)(Ni,{className:"size-3.5"}):(0,t.jsx)(th,{className:"size-3.5"}),(0,t.jsx)(rn,{className:"size-3 opacity-60"})]})})}),(0,t.jsx)($n,{side:"top",children:K})]}),(0,t.jsxs)(aa,{align:"start",className:"w-56",children:[(0,t.jsxs)(ls,{className:"flex-col items-start gap-0.5",onSelect:r(()=>D("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(()=>D("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(()=>D("user_secret"),"onSelect"),children:[(0,t.jsx)("span",{className:"text-sm",children:"User secret"}),(0,t.jsx)("span",{className:"text-(length:--text-micro) text-muted-foreground",children:"Resolve the responsible user's own value at run start."})]})]})]}),e.source==="text"?(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)("input",{ref:N,className:Xre,placeholder:"value",value:e.textValue,type:Q?"password":"text",spellCheck:!1,disabled:o,"aria-label":"Variable value",onChange:r(J=>u({textValue:J.target.value}),"onChange"),onKeyDown:r(J=>{J.key==="Enter"&&s&&(J.preventDefault(),x())},"onKeyDown")}),Q?(0,t.jsxs)("div",{className:"flex shrink-0 items-stretch border-l border-border",children:[(0,t.jsxs)("button",{type:"button",onClick:z,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)(Ic,{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)(En,{className:"size-3"})})]}):null]}):e.source==="secret"?(0,t.jsxs)("div",{className:"relative min-w-0 flex-1",children:[(0,t.jsx)(AV,{secretId:e.secretId,secrets:n,recentlyUsedSecrets:i,disabled:o,onSelect:r(J=>u({secretId:J,version:"latest"}),"onSelect"),onCreateNew:r(J=>_({mode:"create",name:TE(J)||J.trim(),value:""}),"onCreateNew"),triggerClassName:W("rounded-none border-0 bg-transparent shadow-none focus-visible:ring-0",O&&O.status==="active"&&"pr-24 has-[>svg]:!pr-24")}),O&&O.status==="active"?(0,t.jsxs)(dr,{open:R,onOpenChange:I,children:[(0,t.jsx)(iF,{asChild:!0,children:(0,t.jsx)("button",{type:"button",disabled:o,onClick:r(J=>{J.preventDefault(),J.stopPropagation(),I(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",ie?"bg-amber-500/15 text-amber-700 dark:text-amber-400":"text-muted-foreground hover:bg-accent"),children:Z})}),(0,t.jsxs)(sr,{align:"end",className:"w-44 p-1",role:"radiogroup","aria-label":"Secret version",children:[(0,t.jsxs)("button",{type:"button",role:"radio","aria-checked":e.version==="latest",onClick:r(()=>{u({version:"latest"}),I(!1)},"onClick"),className:W("flex w-full items-center justify-between rounded px-2 py-1.5 text-sm hover:bg-accent",e.version==="latest"&&"font-medium"),children:["latest ",(0,t.jsx)("span",{className:"text-(length:--text-micro) text-muted-foreground",children:"(recommended)"})]}),Array.from({length:se},(J,re)=>se-re).filter(J=>J>0).map(J=>(0,t.jsxs)("button",{type:"button",role:"radio","aria-checked":e.version===J,onClick:r(()=>{u({version:J}),I(!1)},"onClick"),className:W("flex w-full items-center rounded px-2 py-1.5 text-sm hover:bg-accent",e.version===J&&"font-medium text-amber-700 dark:text-amber-400"),children:["v",J]},J))]})]}):null]}):(0,t.jsxs)("div",{className:"grid min-w-0 flex-1 grid-cols-(--gtc-13)",children:[P?(0,t.jsxs)("select",{"aria-label":"User secret",value:e.userSecretKey,disabled:o,onChange:r(J=>{const re=J.target.value,oe=a?.find(V=>V.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(J=>J.key===e.userSecretKey)?(0,t.jsxs)("option",{value:e.userSecretKey,children:["Unknown (",e.userSecretKey,")"]}):null,(a??[]).map(J=>(0,t.jsxs)("option",{value:J.key,children:[J.name,J.status!=="active"?` (${J.status})`:""]},J.id))]}):(0,t.jsx)("input",{className:Xre,placeholder:"user-secret key",value:e.userSecretKey,spellCheck:!1,disabled:o,"aria-label":"User secret key",onChange:r(J=>u({userSecretKey:J.target.value}),"onChange")}),(0,t.jsxs)("select",{"aria-label":"Requirement",value:e.required?"required":"optional",disabled:o,onChange:r(J=>u({required:J.target.value==="required"}),"onChange"),className:"border-l border-border bg-transparent px-2 py-1.5 text-xs font-medium text-muted-foreground outline-none disabled:pointer-events-none",children:[(0,t.jsx)("option",{value:"required",children:"Required"}),(0,t.jsx)("option",{value:"optional",children:"Optional"})]})]})]})}),(0,t.jsx)(sr,{align:"start",className:"w-auto p-3",onInteractOutside:r(J=>{const re=J.detail.originalEvent.target;re&&S.current?.contains(re)&&J.preventDefault()},"onInteractOutside"),children:C?.mode==="store"?(0,t.jsx)(rut,{initialName:C.name,initialValue:C.value,existingSecretNames:n.map(J=>J.name),onCancel:r(()=>_(null),"onCancel"),onSubmit:F}):C?.mode==="create"?(0,t.jsx)(M_e,{initialName:C.name,initialValue:C.value,existingSecretNames:n.map(J=>J.name),onCancel:r(()=>_(null),"onCancel"),onSubmit:F}):null})]}),L?(0,t.jsx)("p",{id:q,role:"status",className:W("mt-0.5 text-(length:--text-micro)",L.level==="error"?"text-destructive":"text-amber-600 dark:text-amber-400"),children:L.message}):null,T?(0,t.jsxs)("p",{className:"mt-0.5 inline-flex items-center gap-2 text-(length:--text-micro) text-muted-foreground",children:["Reverted to text —"," ",(0,t.jsx)("button",{type:"button",className:"font-medium text-foreground underline underline-offset-2 hover:text-primary",onClick:r(()=>{u({source:"secret",secretId:T.secretId,version:T.version,textValue:""}),E(null)},"onClick"),children:"Undo"})]}):null]}),c&&l?(0,t.jsx)("p",{id:U,className:W("col-span-2 col-start-1 row-start-3 min-w-0 text-(length:--text-micro) @[40rem]/env:col-span-2 @[40rem]/env:row-start-2",l.level==="error"?"text-destructive":"text-amber-600 dark:text-amber-400"),children:l.message}):null,(0,t.jsxs)("div",{className:"col-start-2 row-start-1 flex items-center justify-end gap-0.5 self-start @[40rem]/env:col-start-3 @[40rem]/env:self-center",children:[e.source==="text"&&!Q&&(e.name.trim()||e.textValue)?(0,t.jsxs)(ia,{children:[(0,t.jsx)(ra,{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)(Ci,{className:"size-4"})})}),(0,t.jsx)(aa,{align:"end",children:(0,t.jsx)(ls,{onSelect:r(()=>{window.setTimeout(z,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)(En,{className:"size-4"})})]})]})}r(but,"EnvironmentVariableRow");var vut=/^\s*(?:export\s+)?([A-Za-z_][A-Za-z0-9_]*)\s*=(.*)$/;function yut(e){const s=e.indexOf(" #");return s>=0?e.slice(0,s):e}r(yut,"stripInlineComment");function jut(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 yut(s).trim()}r(jut,"unquote");function wut(e){const s=[];for(const n of e.split(/\r?\n/)){const a=n.trim();if(!a||a.startsWith("#"))continue;const i=vut.exec(a);if(!i)continue;const o=i[1],l=jut(i[2]);s.push({key:o,value:l})}return s}r(wut,"parseDotenv");var kut=["PAPERCLIP_"],Nut="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 Dz(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(Dz,"normalizedEnvEntries");function L2(e){return JSON.stringify(Dz(e))}r(L2,"normalizedEnvKey");var lD=3;function cD(e){const s=e.slice(0,lD).join(", ");return e.length>lD?`${s} +${e.length-lD} more`:s}r(cD,"formatChangedNames");function eae(e){return e.map(s=>({...s}))}r(eae,"cloneRows");function Sut(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(Sut,"rowDirtyFields");var Ij=(0,m.forwardRef)(r(function({value:s,onChange:n,secrets:a,userSecretDefinitions:i,onCreateSecret:o,recentlyUsedSecrets:l,disabled:c,reservedPrefixes:d=kut,footerHint:u,onDirtyChange:h,hideDraftActions:p=!1},f){const x=bd(),g=(0,m.useRef)(null),[v,y]=(0,m.useState)(()=>oD(s)),k=(0,m.useRef)(v),[w,N]=(0,m.useState)(()=>eae(v)),S=(0,m.useMemo)(()=>L2(s),[]),C=(0,m.useRef)(S),_=(0,m.useRef)(S),R=(0,m.useRef)(null),[I,T]=(0,m.useState)(S),[E,L]=(0,m.useState)(()=>new Set(oD(s).map(de=>de.name.trim()).filter(Boolean))),[O,P]=(0,m.useState)(null);(0,m.useEffect)(()=>{k.current=v},[v]);function Q(de,Ne=k.current){C.current=de,T(de),N(eae(Ne))}r(Q,"markCommitted");function D(de){L(Ne=>{const le=new Set(Ne);for(const Le of de){const Ie=Le.name.trim();Ie&&le.add(Ie)}return le})}r(D,"touchCommittedNames");function F(de){const Ne=oD(de);return y(Ne),D(Ne),Ne}r(F,"adoptExternalValue"),(0,m.useEffect)(()=>{const de=L2(s);if(de===_.current)return;_.current=de;const Ne=L2(vR(k.current)),le=Ne!==C.current,Le=R.current===de;if(Le&&(R.current=null),!le){Q(de,F(s));return}(Le||Ne===de)&&(D(k.current),Q(de))},[s]);const z=(0,m.useMemo)(()=>vR(v),[v]),K=(0,m.useMemo)(()=>L2(z),[z]),U=K!==I;(0,m.useEffect)(()=>{h?.(!c&&U)},[c,U,h]);const q=(0,m.useMemo)(()=>{const de=new Map(Dz(vR(w)).map(([Ie,ye])=>[Ie,JSON.stringify(ye)])),Ne=new Map(Dz(z).map(([Ie,ye])=>[Ie,JSON.stringify(ye)])),le=[],Le=[];for(const[Ie,ye]of Ne)de.has(Ie)?de.get(Ie)!==ye&&Le.push(Ie):le.push(Ie);return{added:le,changed:Le,removed:[...de.keys()].filter(Ie=>!Ne.has(Ie))}},[w,z]),G=(0,m.useMemo)(()=>{const de=[];return q.added.length>0&&de.push(`New: ${cD(q.added)}`),q.changed.length>0&&de.push(`Edited: ${cD(q.changed)}`),q.removed.length>0&&de.push(`Removed: ${cD(q.removed)}`),de.join(" · ")},[q]);(0,m.useEffect)(()=>{if(c||!U)return;function de(Ne){Ne.preventDefault(),Ne.returnValue=""}return r(de,"handleBeforeUnload"),window.addEventListener("beforeunload",de),()=>window.removeEventListener("beforeunload",de)},[c,U]);const se=(0,m.useCallback)(()=>c||!U?null:(R.current=K,(0,Vh.flushSync)(()=>{n(z)}),z??{}),[c,z,K,U,n]);(0,m.useImperativeHandle)(f,()=>({flushPendingDraft:se}),[se]),(0,m.useEffect)(()=>{const de=g.current?.closest("form");if(!de)return;function Ne(){se()}return r(Ne,"handleSubmit"),de.addEventListener("submit",Ne,!0),()=>de.removeEventListener("submit",Ne,!0)},[se]),(0,m.useEffect)(()=>{const de=g.current;if(!de)return;const Ne=de;function le(Le){const Ie=Le.target;if(!(Ie instanceof Element)||Ne.contains(Ie))return;const ye=Ie.closest("button");if(!ye||ye.disabled)return;const Ae=`${ye.getAttribute("aria-label")??""} ${ye.textContent??""}`;(ye.type==="submit"||/\b(save|create|update|test|import)\b/i.test(Ae))&&se()}return r(le,"handleDocumentClick"),document.addEventListener("click",le,!0),()=>document.removeEventListener("click",le,!0)},[se]);function Z(de){y(de)}r(Z,"updateDraft");function ie(de,Ne){Z(v.map(le=>le.id===de?{...le,...Ne}:le))}r(ie,"patchRow");function J(de){Z(v.filter(Ne=>Ne.id!==de))}r(J,"removeRow");function re(){const de=Sx();y([...v,de]),P({rowId:de.id,field:"name"})}r(re,"addRow");function oe(de){const Ne=v.find(le=>le.id===de)?.name.trim();Ne&&L(le=>{if(le.has(Ne))return le;const Le=new Set(le);return Le.add(Ne),Le})}r(oe,"markTouched");function V(de,Ne){const le=wut(de);if(le.length===0)return!1;const Le=v.filter(Ie=>Ie.id!==Ne).map(Ie=>({...Ie}));for(const{key:Ie,value:ye}of le){const Ae=Le.find(Qe=>Qe.name.trim()===Ie);Ae?(Ae.name=Ie,Ae.source="text",Ae.textValue=ye,Ae.secretId="",Ae.sensitiveDismissed=!1,Ae.userSecretKey="",Ae.required=!0):Le.push({...Sx(),name:Ie,textValue:ye})}return Z(Le),x?.pushToast({title:`Imported ${le.length} variable${le.length===1?"":"s"}`,tone:"success"}),!0}r(V,"bulkImport");function X(de){const Ne=v.map(Ie=>({...Ie})),le=Ne[Ne.length-1];let Le;le&&!le.name&&!le.textValue&&!le.secretId&&!le.userSecretKey?Le=le:(Le=Sx(),Ne.push(Le)),Le.source="secret",Le.secretId=de.id,Le.version="latest",Le.name||(Le.name=f_(de.name)),Z(Ne)}r(X,"bindRecentSecret");function Y(){U&&(R.current=K,n(z))}r(Y,"saveDraft");function ae(){R.current=null,_.current=L2(s);const de=F(s);Q(_.current,de)}r(ae,"revertDraft");const ne=(0,m.useMemo)(()=>fut(v),[v]),ce=(0,m.useMemo)(()=>v.reduce((de,Ne)=>P_e(Ne,a)||D_e(Ne,i)?de+1:de,0),[v,a,i]),he=(0,m.useMemo)(()=>{const de=new Set(v.filter(Ne=>Ne.source==="secret"&&Ne.secretId).map(Ne=>Ne.secretId));return(l??[]).filter(Ne=>Ne.status==="active"&&!de.has(Ne.id)).slice(0,8)},[l,v]),pe=v.length>0,ge=u===void 0?Nut:u,Ee=(0,m.useMemo)(()=>new Map(w.map(de=>[de.id,de])),[w]);return(0,t.jsx)(Yc,{children:(0,t.jsxs)("div",{ref:g,className:"@container/env space-y-2",children:[ce>1?(0,t.jsxs)("p",{className:"inline-flex items-center gap-1.5 text-(length:--text-micro) font-medium text-amber-700 dark:text-amber-400",children:[(0,t.jsx)(eo,{className:"size-3.5"}),ce," bindings need attention"]}):null,pe?(0,t.jsxs)(t.Fragment,{children:[(0,t.jsxs)("div",{className:"hidden gap-x-1.5 @[40rem]/env:grid @[40rem]/env:grid-cols-(--gtc-14)",children:[(0,t.jsx)("span",{className:"text-(length:--text-micro) font-medium uppercase tracking-wide text-muted-foreground",children:"Name"}),(0,t.jsx)("span",{className:"text-(length:--text-micro) font-medium uppercase tracking-wide text-muted-foreground",children:"Value"}),(0,t.jsx)("span",{})]}),v.map((de,Ne)=>{const le=put(de.name,ne,d),Le=E.has(de.name.trim());return(0,t.jsx)(but,{row:de,isLast:Ne===v.length-1,secrets:a,userSecretDefinitions:i,recentlyUsedSecrets:l,disabled:c,nameIssue:le,showNameIssue:Le,dirtyFields:Sut(de,Ee.get(de.id)),onPatch:r(Ie=>ie(de.id,Ie),"onPatch"),onRemove:r(()=>J(de.id),"onRemove"),onNameBlur:r(()=>oe(de.id),"onNameBlur"),onNamePaste:r(Ie=>V(Ie,de.id),"onNamePaste"),onEnterInValueLast:re,onCreateSecret:o,onToast:r(Ie=>x?.pushToast({title:Ie,tone:"success"}),"onToast"),focusRequest:O?.rowId===de.id?O.field:null,onFocusConsumed:r(()=>P(null),"onFocusConsumed")},de.id)})]}):(0,t.jsx)("p",{className:"text-sm text-muted-foreground",children:"No environment variables"}),(0,t.jsxs)("div",{className:"flex flex-wrap items-center justify-between gap-2 pt-1",children:[(0,t.jsxs)("button",{type:"button",onClick: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)(gn,{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)(Ni,{className:"size-3"}),"Recently used:"]}),he.map(de=>(0,t.jsxs)("button",{type:"button",onClick:r(()=>X(de),"onClick"),className:"inline-flex items-center gap-1 rounded-full border border-border px-2 py-0.5 font-mono text-(length:--text-micro) text-muted-foreground transition-colors hover:bg-accent/50 hover:text-foreground",title:`Bind ${de.name}`,children:["+ ",de.name]},de.id))]}):null]}),U&&!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"})]}),G?(0,t.jsx)("p",{className:"min-w-0 truncate pl-4 text-xs text-amber-950/80 dark:text-amber-100/80",title:G,children:G}):null]}),(0,t.jsxs)("div",{className:"flex items-center gap-2",children:[(0,t.jsxs)("button",{type:"button",onClick:ae,className:"inline-flex h-9 items-center gap-1.5 rounded-md border border-amber-500/30 bg-background px-3 text-sm font-medium text-foreground transition-colors hover:bg-amber-500/10 dark:bg-background/80",children:[(0,t.jsx)(_i,{className:"size-4"}),"Revert"]}),(0,t.jsxs)("button",{type:"button",onClick:Y,className:"inline-flex h-9 items-center gap-1.5 rounded-md bg-primary px-4 text-sm font-medium text-primary-foreground transition-colors hover:bg-primary/90",children:[(0,t.jsx)(af,{className:"size-4"}),"Save"]})]})]}):null,ge?(0,t.jsx)("p",{className:"text-(length:--text-micro) text-muted-foreground/70",children:ge}):null,v.some(de=>de.source==="user_secret"&&de.userSecretKey)?(0,t.jsxs)("p",{className:"inline-flex items-start gap-1 text-(length:--text-micro) text-muted-foreground/70",children:[(0,t.jsx)(th,{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")),Cut="env.",tA="access.",$z=/^[A-Za-z_][A-Za-z0-9_]*$/;function $_e(e){return e?e.startsWith("access.")?"api":e.startsWith("env.")?"env":"config":"config"}r($_e,"deliveryModeForConfigPath");function O_e(e){switch(e){case"env":return"Env var";case"api":return"API access";default:return"Config"}}r(O_e,"deliveryModeLabel");function _ut(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(_ut,"deliveryModeDescription");function B_e(e){return e?e.startsWith("access.")?e.slice(7):e.startsWith("env.")?e.slice(4):e:""}r(B_e,"aliasFromConfigPath");function Aut(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(Aut,"consumerTypeLabel");var Iut={numeric:!0,sensitivity:"base"};function RC(e){return e.kind==="company"?e.secret.name:e.definition.name}r(RC,"getSecretPathRowName");function CN(e){return e.split("/").filter(s=>s.length>0)}r(CN,"splitSecretPath");function dD(e){return CN(e).join("/")}r(dD,"normalizeSecretPath");function tae(e,s){return s.every((n,a)=>e[a]===n)}r(tae,"startsWithSegments");function sae(e,s){return e.localeCompare(s,void 0,Iut)}r(sae,"compareNames");function Tut(e,s){const n=CN(s),a=e.map(c=>({row:c,name:RC(c),segments:CN(RC(c))})),i=new Set,o=[];for(const c of a){if(!tae(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(!tae(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)=>sae(c.name,d.name)),o.sort((c,d)=>sae(RC(c),RC(d))),{folders:l,secrets:o}}r(Tut,"buildSecretPathListing");function Rut(e){const s=CN(e);return s.map((n,a)=>({name:n,path:s.slice(0,a+1).join("/")}))}r(Rut,"buildSecretPathBreadcrumbs");function Eut(e){return e.trim()?e.includes("/")?"Folder name cannot contain slashes.":null:"Folder name is required."}r(Eut,"validateSecretFolderSegment");function k5({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(k5,"SecretPathName");function Lut(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(Lut,"fingerprintLabel");function F_e({fingerprint:e,length:s,className:n}){const{pushToast:a}=Xr(),i=Lut(e,s);if(!e)return(0,t.jsxs)("span",{className:W("inline-flex items-center gap-1 font-mono",n),children:[(0,t.jsx)(kF,{className:"size-3 shrink-0"}),i]});const o=`sha256:${e}`;return(0,t.jsxs)("button",{type:"button",onClick:r(()=>{wa(o).then(()=>a({title:"Fingerprint copied",tone:"success"})).catch(()=>a({title:"Couldn’t copy fingerprint",tone:"error"}))},"onClick"),title:`Copy full digest — ${o}`,className:W("inline-flex items-center gap-1 font-mono hover:text-foreground",n),children:[(0,t.jsx)(kF,{className:"size-3 shrink-0"}),i,(0,t.jsx)(gr,{className:"size-3 shrink-0 opacity-60"})]})}r(F_e,"FingerprintChip");function IV({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(IV,"ProposalJustification");function N5({agent:e,className:s}){return(0,t.jsxs)("span",{className:W("inline-flex min-w-0 items-center gap-1",s),children:[(0,t.jsx)(lr,{agent:e,size:16,className:"h-3.5 w-3.5 shrink-0 text-muted-foreground"}),(0,t.jsx)("span",{className:"min-w-0 truncate",children:e.name})]})}r(N5,"AgentRefChip");function TV({configPath:e}){const s=$_e(e),n=s==="env",a=s==="api";return(0,t.jsxs)(it,{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)(gke,{className:"size-3"}):a?(0,t.jsx)(q8,{className:"size-3"}):null,O_e(s)]})}r(TV,"DeliveryBadge$1");function RV({className:e}){return(0,t.jsxs)(it,{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)(Ic,{className:"size-3"})," Proposed"]})}r(RV,"ProposedBadge");function IM(e){return B_e(e.configPath)}r(IM,"bindingEnvKey");function EV(e){return e.secretProposalId?{name:e.secretProposalName??"proposed secret",pending:!0}:{name:e.secretName??"secret",pending:!1}}r(EV,"bindingSecretLabel");function nae(e){return e instanceof sn?e.message||`Request failed: ${e.status}`:e instanceof Error?e.message:"Something went wrong. Try again."}r(nae,"readableError");function z_e(e,s=[]){const n=kt(),{pushToast:a}=Xr(),[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:M.secrets.list(e)}))},[e,n]),x=je({mutationFn:r(w=>{const{proposal:N}=w;if(N.kind==="secret"){const S=w.folder.trim()?`${w.folder.trim().replace(/\/+$/,"")}/${w.leaf.trim()}`:w.leaf.trim();return Tr.approveProposal(e,N.id,{overrides:{name:S,description:w.description.trim()||null,providerConfigId:w.providerConfigId||null}})}return Tr.approveProposal(e,N.id,{cascade:w.cascade||void 0})},"mutationFn"),onSuccess:r(w=>{a({title:w.kind==="secret"?"Secret approved":"Binding approved",body:w.kind==="secret"?w.proposedName??"Secret created":`${w.target?.name??"Agent"} · ${IM(w)||"binding"}`,tone:"success"}),o(null),p(null),f()},"onSuccess"),onError:r(w=>p(nae(w)),"onError")}),g=je({mutationFn:r(({proposal:w,reason:N})=>Tr.rejectProposal(e,w.id,{reason:N.trim()}),"mutationFn"),onSuccess:r(w=>{a({title:"Proposal rejected",body:w.kind==="secret"?w.proposedName??void 0:void 0,tone:"info"}),c(null),u(""),p(null),f()},"onSuccess"),onError:r(w=>p(nae(w)),"onError")}),v=(0,m.useCallback)(w=>{p(null);const N=(w.proposedName??"").split("/"),S=N.pop()??"";o({proposal:w,folder:N.join("/"),leaf:S,description:w.proposedDescription??"",providerConfigId:s.find(C=>C.provider==="local_encrypted"&&C.isDefault)?.id??"",cascade:!!w.secretProposalId})},[s]),y=(0,m.useCallback)(w=>{p(null),u(""),c(w)},[]),k=(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)(Mut,{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)(Dut,{proposal:l,reason:d,error:h,pending:g.isPending,onReasonChange:u,onCancel:r(()=>{c(null),u(""),p(null)},"onCancel"),onConfirm:r(()=>l&&g.mutate({proposal:l,reason:d}),"onConfirm")})]});return{requestApprove:v,requestReject:y,isBusy:x.isPending||g.isPending,dialogs:k}}r(z_e,"useProposalReview");function Mut({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)(Ws,{className:"sm:max-w-lg",children:e?(0,t.jsxs)(t.Fragment,{children:[(0,t.jsxs)(ln,{children:[(0,t.jsx)(Qs,{children:c?"Approve & create secret":"Approve binding"}),(0,t.jsx)(mn,{children:c?"The value is created as the proposing agent recorded it. Re-folder or rename it before it lands.":"Grant the target agent access to this secret. This runs with your permissions."})]}),(0,t.jsxs)("div",{className:"space-y-1.5 rounded-md border border-border bg-muted/30 p-2.5 text-xs",children:[(0,t.jsxs)("div",{className:"flex items-center gap-1.5 text-muted-foreground",children:[(0,t.jsx)("span",{children:"Proposed by"}),(0,t.jsx)(N5,{agent:e.proposal.proposedBy,className:"font-medium text-foreground"})]}),(0,t.jsx)(IV,{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)(Ds,{htmlFor:"approve-folder",children:"Folder"}),(0,t.jsx)(dt,{id:"approve-folder",value:e.folder,onChange:r(p=>i({...e,folder:p.target.value}),"onChange"),placeholder:"dev/github",className:"font-mono text-xs"})]}),(0,t.jsxs)("div",{className:"space-y-1",children:[(0,t.jsx)(Ds,{htmlFor:"approve-name",children:"Name"}),(0,t.jsx)(dt,{id:"approve-name",value:e.leaf,onChange:r(p=>i({...e,leaf:p.target.value}),"onChange"),placeholder:"client-secret",autoFocus:!0,"aria-invalid":!e.leaf.trim(),className:"font-mono text-xs"})]})]}),(0,t.jsxs)("p",{className:"text-(length:--text-micro) text-muted-foreground",children:["Lands as"," ",d?(0,t.jsx)(k5,{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)(Ds,{htmlFor:"approve-description",children:"Description"}),(0,t.jsx)(dt,{id:"approve-description",value:e.description,onChange:r(p=>i({...e,description:p.target.value}),"onChange"),placeholder:"Optional"})]}),u.length>0?(0,t.jsxs)("div",{className:"space-y-1",children:[(0,t.jsx)(Ds,{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)(F_e,{fingerprint:e.proposal.valueFingerprintSha256,length:e.proposal.valueLength})})]}):(0,t.jsx)(Put,{draft:e,onChange:i}),s?(0,t.jsx)("p",{className:"text-xs text-destructive",role:"alert",children:s}):null,(0,t.jsxs)(cr,{children:[(0,t.jsx)($,{variant:"ghost",onClick:o,disabled:n,children:"Cancel"}),(0,t.jsx)($,{onClick:l,disabled:n||!h,children:n?"Approving…":c?"Approve & create":e.cascade?"Approve secret & bind":"Approve binding"})]})]}):null})})}r(Mut,"ApproveDialog");function Put({draft:e,onChange:s}){const{proposal:n}=e,a=EV(n),i=IM(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)(N5,{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)(TV,{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)(Ni,{className:"size-3.5 text-muted-foreground"}),(0,t.jsx)("span",{className:"font-medium",children:a.name}),a.pending?(0,t.jsx)(RV,{}):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)(ri,{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(Put,"BindingApproveBody");function Dut({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)(Ws,{className:"sm:max-w-md",children:e?(0,t.jsxs)(t.Fragment,{children:[(0,t.jsxs)(ln,{children:[(0,t.jsx)(Qs,{children:"Reject proposal"}),(0,t.jsxs)(mn,{children:["The reason is sent back to"," ",(0,t.jsx)(N5,{agent:e.proposedBy,className:"text-foreground"}),". Dependent bindings are rejected too."]})]}),(0,t.jsxs)("div",{className:"space-y-1",children:[(0,t.jsx)(Ds,{htmlFor:"reject-reason",children:"Reason"}),(0,t.jsx)(Qn,{id:"reject-reason",value:s,onChange:r(d=>i(d.target.value),"onChange"),rows:3,autoFocus:!0,placeholder:"Why is this being rejected?"})]}),n?(0,t.jsx)("p",{className:"text-xs text-destructive",role:"alert",children:n}):null,(0,t.jsxs)(cr,{children:[(0,t.jsx)($,{variant:"ghost",onClick:o,disabled:a,children:"Cancel"}),(0,t.jsx)($,{variant:"destructive",onClick:l,disabled:a||!c,children:a?"Rejecting…":"Reject"})]})]}):null})})}r(Dut,"RejectDialog");function q_e({proposal:e,onApprove:s,onReject:n,disabled:a,size:i="sm"}){const o=!e.viewerCanApprove,l=i==="xs"?"h-7 px-2 text-xs":"",c=(0,t.jsx)($,{size:"sm",className:l,disabled:a||o,onClick:r(()=>s(e),"onClick"),children:"Approve"});return(0,t.jsxs)("div",{className:"flex items-center gap-1.5",children:[o?(0,t.jsx)(Yc,{children:(0,t.jsxs)(Bn,{children:[(0,t.jsx)(On,{asChild:!0,children:(0,t.jsx)("span",{tabIndex:0,children:c})}),(0,t.jsx)($n,{className:"max-w-72",children:e.approveBlockReason??"You don’t have permission to approve this."})]})}):c,(0,t.jsx)($,{size:"sm",variant:"outline",className:l,disabled:a,onClick:r(()=>n(e),"onClick"),children:"Reject"})]})}r(q_e,"ProposalActions");function U_e(e){return typeof e!="object"||e===null||Array.isArray(e)?null:e}r(U_e,"asRecord$16");function K_e(e){const s=U_e(e);if(!s||s.type!=="secret_ref")return null;const n=typeof s.secretId=="string"?s.secretId:"";return n?{secretId:n,version:typeof s.version=="number"?s.version:"latest"}:null}r(K_e,"readSecretRef");function $ut(e){const s=U_e(e?.env);if(!s)return[];const n=[];for(const[a,i]of Object.entries(s)){const o=K_e(i);o&&n.push({name:a,...o})}return n}r($ut,"parseEnvSecretRefs");function Out(e){if(!e)return[];const s=[];for(const[n,a]of Object.entries(e)){if(!n.startsWith("access."))continue;const i=K_e(a);i&&s.push({name:n.slice(tA.length),...i})}return s}r(Out,"parseAccessGrants");function But(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(But,"summarizeAgentBindings");var rae=0;function Q_e(){return rae+=1,`access-row-${rae}`}r(Q_e,"nextAccessRowId");function uD(e){return e.map(s=>({id:Q_e(),alias:s.name,secretId:s.secretId,version:s.version}))}r(uD,"entriesToRows");function aae(e){const s={};for(const n of e){const a=n.alias.trim();!a||!$z.test(a)||!n.secretId||(s[a]={type:"secret_ref",secretId:n.secretId,version:n.version})}return s}r(aae,"rowsToAccessMap");function iae(e){return JSON.stringify(Object.keys(e).sort().map(s=>{const n=e[s];return[s,n.secretId,n.version??"latest"]}))}r(iae,"normalizeAccessMapKey");function oae({mode:e}){return e==="env"?(0,t.jsxs)(it,{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)(gke,{className:"size-3"})," Env var"]}):(0,t.jsxs)(it,{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)(q8,{className:"size-3"})," API access"]})}r(oae,"DeliveryBadge");function Fut({config:e,secrets:s,onChange:n,onCreateSecret:a,disabled:i,proposals:o,onApproveProposal:l,onRejectProposal:c}){const d=(0,m.useMemo)(()=>(o??[]).filter(O=>O.kind==="binding"),[o]),u=(0,m.useMemo)(()=>$ut(e),[e]),h=(0,m.useMemo)(()=>Out(e),[e]),p=(0,m.useMemo)(()=>But(u,h),[u,h]),f=(0,m.useMemo)(()=>aae(uD(h)),[h]),x=(0,m.useMemo)(()=>iae(f),[f]),[g,v]=(0,m.useState)(()=>uD(h)),[y,k]=(0,m.useState)(null),w=(0,m.useRef)(new Map),N=(0,m.useRef)(x),S=(0,m.useRef)(x);(0,m.useEffect)(()=>{x!==S.current&&(S.current=x,x!==N.current&&v(uD(h)))},[x,h]);const C=r(O=>s.find(P=>P.id===O)?.name??`${O.slice(0,8)}…`,"secretName");function _(O){v(O);const P=aae(O);N.current=iae(P),n(P)}r(_,"emit");function R(O,P){_(g.map(Q=>Q.id===O?{...Q,...P}:Q))}r(R,"patchRow");function I(O){_(g.filter(P=>P.id!==O))}r(I,"removeRow");function T(){v(O=>[...O,{id:Q_e(),alias:"",secretId:"",version:"latest"}])}r(T,"addRow");const E=(0,m.useMemo)(()=>{const O=new Map;for(const P of g){const Q=P.alias.trim();Q&&O.set(Q,(O.get(Q)??0)+1)}return O},[g]),L=p.length>0;return(0,t.jsxs)("div",{className:"space-y-3",children:[L?(0,t.jsx)("div",{className:"space-y-1.5",children:p.map(O=>(0,t.jsxs)("div",{className:"flex flex-wrap items-center gap-x-2 gap-y-1 rounded-md border border-border bg-muted/30 px-2.5 py-1.5 text-xs",children:[(0,t.jsx)(Ni,{className:"size-3.5 shrink-0 text-muted-foreground"}),(0,t.jsx)("span",{className:"font-medium",children:C(O.secretId)}),O.envKeys.length>0?(0,t.jsx)(oae,{mode:"env"}):null,O.apiAliases.length>0?(0,t.jsx)(oae,{mode:"api"}):null,(0,t.jsx)("span",{className:"min-w-0 truncate font-mono text-(length:--text-micro) text-muted-foreground",children:[...O.envKeys.map(P=>`${Cut}${P}`),...O.apiAliases.map(P=>`${tA}${P}`)].join(" · ")})]},O.secretId))}):(0,t.jsx)("p",{className:"text-sm text-muted-foreground",children:"No secrets are bound to this agent yet."}),d.length>0&&l&&c?(0,t.jsxs)("div",{className:"space-y-2",children:[(0,t.jsx)("div",{className:"text-(length:--text-micro) font-medium uppercase tracking-wide text-muted-foreground",children:"Proposed access"}),d.map(O=>{const P=EV(O),Q=IM(O);return(0,t.jsxs)("div",{className:"flex flex-col gap-2 rounded-md border border-amber-500/30 bg-amber-500/5 px-2.5 py-2 text-xs sm:flex-row sm:items-center",children:[(0,t.jsxs)("div",{className:"min-w-0 flex-1 space-y-1",children:[(0,t.jsxs)("div",{className:"flex min-w-0 flex-wrap items-center gap-1.5",children:[(0,t.jsx)(TV,{configPath:O.configPath}),(0,t.jsx)("code",{className:"font-mono",children:Q||O.configPath}),(0,t.jsx)("span",{className:"text-muted-foreground",children:"→"}),(0,t.jsx)(Ni,{className:"size-3 text-muted-foreground"}),(0,t.jsx)("span",{className:"font-medium",children:P.name}),P.pending?(0,t.jsx)(RV,{}):null]}),(0,t.jsxs)("p",{className:"flex flex-wrap items-center gap-1 text-muted-foreground",children:[(0,t.jsxs)("span",{children:["proposed by ",O.proposedBy.name]}),(0,t.jsx)("span",{"aria-hidden":"true",children:"·"}),(0,t.jsxs)("span",{className:"truncate italic",children:["“",O.justification,"”"]})]})]}),(0,t.jsx)(q_e,{proposal:O,onApprove:l,onReject:c,disabled:i,size:"xs"})]},O.id)})]}):null,(0,t.jsxs)("div",{className:"space-y-2",children:[(0,t.jsx)("div",{className:"text-(length:--text-micro) font-medium uppercase tracking-wide text-muted-foreground",children:"API access (no env var)"}),g.length>0?(0,t.jsx)("div",{className:"space-y-2",children:g.map(O=>{const P=O.alias.trim(),Q=!!P&&!$z.test(P),D=!!P&&(E.get(P)??0)>1,F=s.find(z=>z.id===O.secretId)??null;return(0,t.jsxs)("div",{className:"space-y-1",children:[(0,t.jsxs)("div",{className:"grid grid-cols-(--gtc-65) items-start gap-1.5",children:[(0,t.jsx)("div",{children:(0,t.jsx)(dt,{value:O.alias,onChange:r(z=>R(O.id,{alias:z.target.value}),"onChange"),onBlur:r(z=>{const K=z.target.value.trim();if(K&&!$z.test(K)){const U=f_(K);U&&U!==K&&R(O.id,{alias:U})}},"onBlur"),placeholder:"ALIAS","aria-label":"Access alias",disabled:i,className:W("h-9 font-mono text-sm",(Q||D)&&"border-destructive text-destructive")})}),(0,t.jsxs)("div",{className:"flex min-w-0 items-start gap-1.5",children:[(0,t.jsxs)(dr,{open:y?.rowId===O.id,onOpenChange:r(z=>{!z&&y?.rowId===O.id&&k(null)},"onOpenChange"),children:[(0,t.jsx)(iF,{asChild:!0,children:(0,t.jsx)("div",{ref:r(z=>{z?w.current.set(O.id,z):w.current.delete(O.id)},"ref"),className:"min-w-0 flex-1",children:(0,t.jsx)(AV,{secretId:O.secretId,secrets:s,onSelect:r(z=>R(O.id,{secretId:z,version:"latest",alias:!O.alias.trim()&&z?f_(C(z)):O.alias}),"onSelect"),onCreateNew:a?z=>{window.setTimeout(()=>{k({rowId:O.id,name:TE(z)||z.trim()})},0)}:void 0,disabled:i,triggerClassName:"h-9 min-h-9"})})}),(0,t.jsx)(sr,{align:"start",className:"w-auto p-3",onInteractOutside:r(z=>{const K=z.detail.originalEvent.target;K&&w.current.get(O.id)?.contains(K)&&z.preventDefault()},"onInteractOutside"),children:y?.rowId===O.id&&a?(0,t.jsx)(M_e,{initialName:y.name,initialValue:"",existingSecretNames:s.map(z=>z.name),onCancel:r(()=>k(null),"onCancel"),onSubmit:r(async(z,K)=>{const U=await a(z,K);R(O.id,{secretId:U.id,version:"latest",alias:O.alias.trim()||f_(U.name)}),k(null)},"onSubmit")}):null})]}),(0,t.jsxs)("select",{className:"h-9 shrink-0 rounded-md border border-border bg-background px-2 text-xs outline-none disabled:cursor-not-allowed disabled:opacity-60",value:O.version===void 0?"latest":String(O.version),onChange:r(z=>{const K=z.target.value;R(O.id,{version:K==="latest"?"latest":Number.parseInt(K,10)})},"onChange"),disabled:i||!F,"aria-label":"Version",children:[(0,t.jsx)("option",{value:"latest",children:"latest"}),F?Array.from({length:Math.max(0,F.latestVersion)},(z,K)=>{const U=F.latestVersion-K;return U<=0?null:(0,t.jsxs)("option",{value:U,children:["v",U]},U)}):null]})]}),(0,t.jsx)("button",{type:"button",onClick:r(()=>I(O.id),"onClick"),disabled:i,"aria-label":"Remove API access",className:"mt-1 inline-flex size-7 shrink-0 items-center justify-center rounded-md text-muted-foreground transition-colors hover:bg-accent hover:text-foreground disabled:pointer-events-none disabled:opacity-50",children:(0,t.jsx)(ha,{className:"size-3.5"})})]}),Q?(0,t.jsx)("p",{className:"pl-0.5 text-(length:--text-micro) text-destructive",children:"Invalid alias — use letters, digits and _"}):D?(0,t.jsx)("p",{className:"pl-0.5 text-(length:--text-micro) text-destructive",children:"Duplicate alias"}):null]},O.id)})}):null,(0,t.jsxs)("button",{type:"button",onClick:T,disabled:i,className:"inline-flex items-center gap-1 rounded-md px-2 py-1 text-xs font-medium text-muted-foreground transition-colors hover:bg-accent hover:text-foreground disabled:pointer-events-none disabled:opacity-50",children:[(0,t.jsx)(gn,{className:"size-3.5"}),"Add API access"]})]}),(0,t.jsxs)("p",{className:"text-(length:--text-micro) text-muted-foreground/70",children:[_ut("api")," The agent reads them by alias through ",(0,t.jsx)("code",{children:"GET /agents/me/secrets"}),"."]})]})}r(Fut,"AgentSecretAccessEditor");function zut(e){if(typeof e!="string")return null;const s=e.trim();return s.length>0?s:null}r(zut,"asNonEmptyString$3");function qut(e){return zut(e)!==null}r(qut,"hasLegacyWorkingDirectory");function Uut(e){return e.isCreate?!1:qut(e.adapterConfig?.cwd)}r(Uut,"shouldShowLegacyWorkingDirectoryField");var W_e=new Set;function Kut(e){return W_e.has(e)}r(Kut,"isAdapterTypeHidden");function Qut(e){W_e=new Set(e)}r(Qut,"setDisabledAdapterTypes");function Wut(e){return!Gm(e).hideFromVisualSelection}r(Wut,"isVisualAdapterChoice");function H_e(e,s=CV()){const n=e??wf;return s.map(a=>({value:a.type,label:n(a.type),comingSoon:!!Gm(a.type).comingSoon,hidden:Kut(a.type),experimental:!!Gm(a.type).experimental}))}r(H_e,"listAdapterOptions");function V_e(e={}){const s=e.enabled??!0,{data:n}=te({queryKey:M.adapters.all,queryFn:r(()=>Ph.list(),"queryFn"),enabled:s,staleTime:3e5});return n&&Wdt(n.filter(a=>a.source==="external").map(a=>({type:a.type,label:a.label,disabled:a.disabled,overrideDisabled:a.overridePaused}))),(0,m.useEffect)(()=>{n&&Qut(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(V_e,"useDisabledAdaptersSync");function Hut(e={}){const s=e.enabled??!0,{data:n}=te({queryKey:M.adapters.all,queryFn:r(()=>Ph.list(),"queryFn"),enabled:s,staleTime:3e5});return n!==void 0}r(Hut,"useAdapterRegistryLoaded");function RE(e){return Object.fromEntries(Object.entries(e).filter(([,s])=>s!==void 0))}r(RE,"omitUndefinedEntries");function MI(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=RE(s.adapterType!==void 0?{...Object.fromEntries(POe.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=RE({...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(MI,"buildAgentUpdatePatch");var Vut="kubernetes";function Gut(e){return e.driver!=="sandbox"?!1:e.config?.provider===Vut}r(Gut,"isKubernetesSandboxEnvironment");function LV(e,s){return e!=="kubernetes"?{forced:!1,kubernetesEnvironment:null}:{forced:!0,kubernetesEnvironment:s.find(n=>Gut(n))??null}}r(LV,"resolveForcedKubernetesEnvironment");var mD={identity:{},adapterConfig:{},heartbeat:{},debug:{},runtime:{}},M2={};function Yut(e){return e==="claude_local"||e==="codex_local"||e==="paperclip_runner"||e==="opencode_local"}r(Yut,"supportsAdapterModelRefresh");function Zut(e,s){return BCe(e,s).model}r(Zut,"resolvePaperclipRunnerTransitionModel");function lae(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(lae,"isOverlayDirty");function Oz(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)=>Oz(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&&Oz(o,a[i]))}return!1}r(Oz,"overlayValuesEqual");function Jut(e,s){const n=r((a,i)=>Object.fromEntries(Object.entries(a).filter(([o,l])=>!(o in i)||!Oz(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(Jut,"subtractPersistedOverlay");var kh="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 Xut(e){return e.split(",").map(s=>s.trim()).filter(Boolean)}r(Xut,"parseCommaArgs");function emt(e){return Array.isArray(e)?e.filter(s=>typeof s=="string").join(", "):typeof e=="string"?e:""}r(emt,"formatArgList");var tmt=[{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"}],smt=[{id:"",label:"Auto"},{id:"plan",label:"Plan"},{id:"ask",label:"Ask"}],nmt=[{id:"",label:"Auto"},{id:"low",label:"Low"},{id:"medium",label:"Medium"},{id:"high",label:"High"}],rmt=[{id:"",label:"Auto"},{id:"low",label:"Low"},{id:"high",label:"High"},{id:"max",label:"Max"}],amt=2,cae=10,imt=1,G_e=300;function yR(e,s,n){return Math.max(s,Math.min(n,Math.floor(e)))}r(yR,"clampInteger");function omt(e){return yR(e,0,G_e)*1e3}r(omt,"clampDelayMsFromSeconds");function lmt({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(lmt,"ConfigSections");function Y_e(e){const{mode:s,adapterModels:n}=e,a=s==="create",i=e.sectionLayout==="cards",o=e.showAdapterTypeField??!0,l=e.showAdapterTestEnvironmentButton??!0,c=l&&!e.onTestActionChange&&!e.compactTestFeedback,d=!e.onTestFeedbackChange,u=e.showCreateRunPolicySection??!0,h=e.hideInstructionsFile??!1,p=e.canConfigureProviderTrace===!0,{selectedCompanyId:f}=ps(),x=kt(),g=(0,m.useRef)(null),v=V_e(),{data:y=[]}=te({queryKey:f?M.secrets.list(f):["secrets","none"],queryFn:r(()=>Tr.list(f),"queryFn"),enabled:!!f}),{data:k=[]}=te({queryKey:f?M.secrets.userDefinitions(f):["user-secret-definitions","none"],queryFn:r(()=>Tr.listUserSecretDefinitions(f),"queryFn"),enabled:!!f,retry:!1}),w=a?null:e.agent.id,{data:N=[]}=te({queryKey:f?M.secrets.proposals(f,"pending"):["secret-proposals","none"],queryFn:r(()=>Tr.listProposals(f,"pending"),"queryFn"),enabled:!!f&&!a,retry:!1}),S=(0,m.useMemo)(()=>N.filter(mt=>mt.kind==="binding"&&mt.target?.id===w),[N,w]),C=z_e(f,[]),{data:_}=te({queryKey:M.instance.experimentalSettings,queryFn:r(()=>jr.getExperimental(),"queryFn"),retry:!1}),R=(0,m.useMemo)(()=>{const mt=new Set(v);return _?.enableNativeRunner!==!0&&mt.add("paperclip_runner"),(_?.enableOpenAiDot!==!0||v.has("paperclip_runner"))&&mt.add("openai_dot"),mt},[v,_?.enableNativeRunner,_?.enableOpenAiDot]),I=_?.enableEnvironments===!0,T=_?.enableManagedSandboxOnly===!0,E=_===void 0||T,{data:L}=te({queryKey:M.instance.generalSettings,queryFn:r(()=>jr.getGeneral(),"queryFn"),retry:!1}),{data:O}=te({queryKey:M.instance.settings,queryFn:r(()=>jr.get(),"queryFn"),retry:!1}),{data:P=[]}=te({queryKey:f?M.environments.list(f):["environments","none"],queryFn:r(()=>Fi.list(f),"queryFn"),enabled:!!f&&(I||L?.executionMode==="kubernetes")}),{forced:Q,kubernetesEnvironment:D}=(0,m.useMemo)(()=>LV(L?.executionMode,P),[L?.executionMode,P]),F=je({mutationFn:r(mt=>{if(!f)throw new Error("Select an organization to create secrets");return Tr.create(f,mt)},"mutationFn"),onSuccess:r(()=>{f&&x.invalidateQueries({queryKey:M.secrets.list(f)})},"onSuccess")}),z=je({mutationFn:r(async({file:mt,namespace:As})=>{if(!f)throw new Error("Select an organization to upload images");return fv.uploadImage(f,mt,As)},"mutationFn")}),[K,U]=(0,m.useState)(mD),[q,G]=(0,m.useState)(!1),[se,Z]=(0,m.useState)(0),ie=(0,m.useRef)(null),J=(0,m.useRef)(null),re=(0,m.useRef)(!1);(0,m.useEffect)(()=>{if(!a){if(ie.current!==null&&e.agent!==ie.current&&!re.current){const mt=J.current;J.current=null,U(As=>mt?Jut(As,mt):{...mD})}ie.current=e.agent}},[a,a?void 0:e.agent]);const oe=!a&&(lae(K)||q);function V(mt,As,pn){const Cn=K[mt];return As in Cn?Cn[As]:pn}r(V,"eff");function X(mt,As,pn){U(Cn=>({...Cn,[mt]:{...Cn[mt],[As]:pn}}))}r(X,"mark");function Y(){return g.current?.flushPendingDraft()??null}r(Y,"flushEnvironmentDraft");const ae=(0,m.useCallback)(mt=>{a||U(As=>{const pn={...e.agent.adapterConfig??{},...As.adapterConfig},Cn={...As.adapterConfig};for(const[pr,Nr]of Object.entries(mt))Cn[`${tA}${pr}`]=Nr;for(const pr of Object.keys(pn))pr.startsWith("access.")&&(pr.slice(7)in mt||(Cn[pr]=void 0));return{...As,adapterConfig:Cn}})},[a,a?void 0:e.agent]),ne=(0,m.useCallback)(()=>{U({...mD}),G(!1),Z(mt=>mt+1)},[]),ce=(0,m.useCallback)(async()=>{if(a)return;const mt=Y(),As=mt?{...K,adapterConfig:{...K.adapterConfig,env:mt}}:K;lae(As)&&await e.onSave(MI(e.agent,As))},[a,oe,K,e]);(0,m.useEffect)(()=>{a||(e.onDirtyChange?.(oe),e.onSaveActionChange?.(ce),e.onCancelActionChange?.(ne))},[a,oe,e.onDirtyChange,e.onSaveActionChange,e.onCancelActionChange,ce,ne]),(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??{},pe=a?{}:e.agent.runtimeConfig??{},ge=a?{}:pe.heartbeat??{},Ee=a?{}:pe.debug??{},de=a?e.values.adapterType:K.adapterType??e.agent.adapterType,Ne=Xj(),le=Ne(de),Le=de==="paperclip_runner"&&(a?e.values.adapterSchemaValues?.provider:V("adapterConfig","provider",he.provider))==="openai_dot",Ie=!Le&&(le.supportsInstructionsBundle||le.supportsSkills||le.supportsLocalAgentJwt),ye=Ie&&!E&&Uut({isCreate:a,adapterConfig:he}),Ae=(0,m.useMemo)(()=>RS(de),[de]),Qe=(0,m.useMemo)(()=>new Set(QUe(de)),[de]),ue=a?e.values:null,Be=a?mt=>e.onChange(mt):null;a&&ue.claudeStoredSessionId;const ft=r(()=>{f&&x.invalidateQueries({queryKey:M.secrets.userDefinitions(f)})},"invalidateUserSecretDefinitions"),gt=r(mt=>{if(!a||!Be)return;const As=ue.envBindings??{};Be({envBindings:{...As,...nk()},claudeStoredSessionId:mt}),ft()},"handleClaudeLoginStored"),Xe=r(async()=>{if(a)return;const mt={...Y()??V("adapterConfig","env",he.env??M2),...nk()},As={...K,adapterConfig:{...K.adapterConfig,env:mt}};U(As),await e.onSave({...MI(e.agent,As),applyStoredClaudeLogin:!0}),ft()},"handleClaudeLoginStoredEdit"),Fe=r(async mt=>{if(a||!mt.companyIdentityDiffers)return;const As={...Y()??V("adapterConfig","env",he.env??M2),CODEX_HOME:{type:"secret_ref",secretId:mt.secretId,version:"latest"}},pn={...K,adapterConfig:{...K.adapterConfig,env:As}};U(pn),J.current=pn,re.current=!0;try{await e.onSave(MI(e.agent,pn))}catch(Cn){throw J.current=null,Cn}finally{re.current=!1}ft()},"handleCodexAccountBindingEdit"),at=r(()=>{if(!a||!Be)return;const mt=ue.envBindings??{};Be({envBindings:{...mt,...nk()},claudeApplyStoredLogin:!0}),ft()},"handleApplyStoredClaudeLogin"),Tt=r(async()=>{if(a)return;const mt={...Y()??V("adapterConfig","env",he.env??M2),...nk()},As={...K,adapterConfig:{...K.adapterConfig,env:mt}};U(As),await e.onSave({...MI(e.agent,As),applyStoredClaudeLogin:!0}),ft()},"handleApplyStoredClaudeLoginEdit"),Dt=a?ue.defaultEnvironmentId??"":V("identity","defaultEnvironmentId",e.agent.defaultEnvironmentId??""),Ot=(0,m.useMemo)(()=>Dt?(P.find(mt=>mt.id===Dt)??null)?.driver==="local"?"":Dt:"",[P,Dt]),rt=(0,m.useMemo)(()=>P.find(mt=>mt.id===Ot)??null,[Ot,P]),Pe=(0,m.useMemo)(()=>{const mt=O?.defaultEnvironmentId??null;return mt?(P.find(As=>As.id===mt)??null)?.driver==="local"?"":mt:""},[P,O?.defaultEnvironmentId]),De=(0,m.useMemo)(()=>P.find(mt=>mt.id===Pe)??null,[P,Pe]),ht=(0,m.useMemo)(()=>{try{return wN({agentDefaultEnvironmentId:Dt||null,instanceDefaultEnvironmentId:O?.defaultEnvironmentId??null,localDefaultEnvironmentId:NN(P),managedSandboxOnly:_?.enableManagedSandboxOnly===!0,managedSandboxEnvironmentId:kN(P),visibleEnvironmentIds:P.map(mt=>mt.id)})}catch{return null}},[Dt,O?.defaultEnvironmentId,P,_?.enableManagedSandboxOnly]),Ft=(0,m.useMemo)(()=>P.find(mt=>mt.id===ht)??null,[P,ht]),{data:Et}=te({queryKey:f?M.environments.capabilities(f):["environment-capabilities","none"],queryFn:r(()=>Fi.capabilities(f),"queryFn"),enabled:!!f&&le.login!=null});(0,m.useEffect)(()=>{!a||!Be||!Q||!D||Ot!==D.id&&Be({defaultEnvironmentId:D.id})},[a,Be,Q,D,Ot]);const ct=(0,m.useMemo)(()=>P.filter(mt=>{if(!Qe.has(mt.driver)||mt.driver==="local")return!1;if(mt.driver!=="sandbox")return!0;const As=typeof mt.config?.provider=="string"?mt.config.provider:null;return As!==null&&As!=="fake"}),[P,Qe]),qe=(0,m.useMemo)(()=>!rt||ct.some(mt=>mt.id===rt.id)?ct:[...ct,rt],[rt,ct]),Oe=I&&(Q||Ot.length>0||ct.length>=1),Re=De?SN(De):T?"Paperclip Computer":"Local",Ve=de==="paperclip_runner"?String(a?e.values.adapterSchemaValues?.provider??"codex":V("adapterConfig","provider",he.provider==="acpx"&&he.acpxAgent==="codex"?"codex":he.provider??"codex")):void 0,xe=de==="opencode_local"&&nF.safeParse(K.runtime.runtimeConfig?.aiConnection??pe.aiConnection).data?.provider==="openrouter"?"openrouter":Ve,Ge=LCe(f,a?void 0:nF.safeParse(K.runtime.runtimeConfig?.aiConnection??pe.aiConnection).data,Jee(de,Ve,V("adapterConfig","acpxAgent",he.acpxAgent))),vt=f?M.agents.adapterModels(f,de,Ot||null,xe):["agents","none","adapter-models",de],{data:Ss,error:lt,isLoading:zs}=te({queryKey:vt,queryFn:r(()=>_t.adapterModels(f,de,{environmentId:Ot||null,provider:xe}),"queryFn"),enabled:!!f&&!Ge}),[We,fe]=(0,m.useState)(null),[Ye,bt]=(0,m.useState)(!1),Wt=Ge?.models??Ss??n??[],ut=Ge?Ge.error:lt,$t="command",{data:$e,refetch:pt}=te({queryKey:f?M.agents.detectModel(f,de):["agents","none","detect-model",de],queryFn:r(()=>{if(!f)throw new Error("Select an organization to detect the model");return _t.detectModel(f,de)},"queryFn"),enabled:!!(f&&Ie&&de!=="opencode_local"&&de!=="paperclip_runner")}),Gt=$e?.model??null;$e?.candidates;const{data:be=[]}=te({queryKey:f?M.agents.list(f):["agents","none","list"],queryFn:r(()=>_t.list(f),"queryFn"),enabled:!!(!a&&f)}),fs={companyId:f??void 0,agentId:a?void 0:e.agent.id,mode:s,isCreate:a,adapterType:de,values:a?e.values:null,set:a?mt=>e.onChange(mt):null,config:he,eff:V,mark:X,models:Wt,hideInstructionsFile:h||E||Le,managedSandboxOnly:E||Le,openAiDotEnabled:_?.enableOpenAiDot===!0},[vn,Ls]=(0,m.useState)(!1),[Bs,kr]=(0,m.useState)(!1),ds=vV(de),os=r(mt=>(0,t.jsxs)(t.Fragment,{children:[de==="claude_local"&&(0,t.jsx)(Sot,{...fs,section:mt}),(0,t.jsx)(Ae.ConfigFields,{...fs,section:mt,hideModel:Ie})]}),"renderAdapterFields"),[Se,St]=(0,m.useState)(!1),[ze,At]=(0,m.useState)(!1);function Ut(mt){if(a){const pn=Ae.buildAdapterConfig(ue);return mt&&Object.assign(pn,mt),RE(pn)}const As={...he,...K.adapterConfig};return mt&&Object.assign(As,mt),RE(As)}r(Ut,"buildAdapterConfigForTest");const It=je({mutationFn:r(async()=>{if(!f)throw new Error("Select an organization to test adapter environment");const mt=Y(),As=mt?{env:mt}:void 0;let pn=O,Cn=P,pr=_?.enableManagedSandboxOnly===!0;if(!Dt)try{const[an,_r,Jn]=await Promise.all([x.ensureQueryData({queryKey:M.instance.settings,queryFn:r(()=>jr.get(),"queryFn")}),x.ensureQueryData({queryKey:M.environments.list(f),queryFn:r(()=>Fi.list(f),"queryFn")}),x.ensureQueryData({queryKey:M.instance.experimentalSettings,queryFn:r(()=>jr.getExperimental(),"queryFn")})]);pn=an,Cn=_r,pr=Jn?.enableManagedSandboxOnly===!0}catch{throw new Error("Could not load environment settings to determine which environment to test in. Retry the test.")}const Nr=wN({agentDefaultEnvironmentId:Dt||null,instanceDefaultEnvironmentId:pn?.defaultEnvironmentId??null,localDefaultEnvironmentId:NN(Cn),managedSandboxOnly:pr,managedSandboxEnvironmentId:kN(Cn),visibleEnvironmentIds:Cn.map(an=>an.id)}),mr=Ut(As),Ra=a?void 0:e.agent.id,vs=a?void 0:$ee.safeParse(K.runtime.runtimeConfig?.aiConnection??e.agent.runtimeConfig.aiConnection).data;if(e.compactTestFeedback){const an=de==="paperclip_runner"?mr.provider==="codex"?"codex_local":mr.provider==="acpx"&&mr.acpxAgent==="grok"?"grok_local":mr.provider==="acpx"&&mr.acpxAgent==="claude"?"claude_local":de:de;return MCe({companyId:f,adapterType:de,providerAdapter:an,adapterConfig:mr,agentId:Ra,aiConnection:vs,environmentId:Nr})}return _t.testEnvironment(f,de,{adapterConfig:mr,agentId:Ra,aiConnection:vs,environmentId:Nr})},"mutationFn")}),[rs,bs]=(0,m.useState)(!1),[$s,Os]=(0,m.useState)(null),Tn="Test",ks=!a&&!!e.isSaving,Hn=rs||ks||!f,Jt=(0,m.useRef)(It.reset);Jt.current=It.reset;const Vs=(0,m.useRef)(()=>{});Vs.current=()=>{if(!a||!Be)return;const mt=ue.envBindings??{},As=ue.claudeStoredSessionId!=null||ue.claudeApplyStoredLogin===!0,pn=Jre in mt;if(!As&&!pn)return;const Cn={...mt};delete Cn[Jre],Be({envBindings:Cn,claudeStoredSessionId:null,claudeApplyStoredLogin:!1})},(0,m.useEffect)(()=>{Jt.current(),Os(null),Vs.current()},[de,ht]);const Nn=le.login!=null,Pt=It.data,Xt=Pt!=null&&Ne(Pt.adapterType).login!=null,Zs=Pt&&Xt?Pt.checks.find(mt=>mt.code==="adapter_auth_missing")??null:null,Ns=typeof Ft?.config?.provider=="string"?Ft.config.provider:null,Js=Ns!=null&&Et?.sandboxProviders?.[Ns]?.supportsLoginPty===!0,cn=le.login!=null,hr=(a||!(K.runtime.runtimeConfig?.aiConnection??pe.aiConnection))&&Nn&&Ft?.driver==="sandbox"&&!!ht&&!!f&&!!Zs&&(!cn||Js),Vn=(0,m.useCallback)(async()=>{if(!f)throw new Error("Select an organization to test adapter environment");bs(!0),Os(null),It.reset();try{return await It.mutateAsync()}catch(mt){throw Os(mt instanceof Error?mt.message:"Environment test failed"),mt}finally{bs(!1)}},[f,It]),Kr=(0,m.useRef)(()=>{});(0,m.useEffect)(()=>{Kr.current=()=>{Hn||Vn().catch(()=>{})}},[Vn,Hn]);const Er=(0,m.useCallback)(()=>{Kr.current()},[]);(0,m.useEffect)(()=>{if(!(!l||!e.onTestActionChange))return e.onTestActionChange(Er),()=>{e.onTestActionChange?.(null)}},[l,e.onTestActionChange,Er]),(0,m.useEffect)(()=>{if(!(!l||!e.onTestActionStateChange))return e.onTestActionStateChange({disabled:Hn,pending:rs}),()=>{e.onTestActionStateChange?.({disabled:!0,pending:!1})}},[l,e.onTestActionStateChange,Hn,rs]),(0,m.useEffect)(()=>{if(e.onTestFeedbackChange)return e.onTestFeedbackChange({errorMessage:$s??(It.error instanceof Error?It.error.message:It.error?"Environment test failed":null),result:It.data??null,login:hr&&f&&ht?{companyId:f,adapterType:de,environmentId:ht}:null}),()=>{e.onTestFeedbackChange?.({errorMessage:null,result:null,login:null})}},[e.onTestFeedbackChange,$s,It.data,It.error,hr,f,de,ht]);const Cr=a?ue.model??"":V("adapterConfig","model",String(he.model??"")),Ln=typeof Cr=="string"?Cr:"";async function ur(){if(f){bt(!0),fe(null);try{const mt=await _t.adapterModels(f,de,{refresh:!0,environmentId:Ot||null,provider:xe});x.setQueryData(vt,mt)}catch(mt){fe(mt instanceof Error?mt.message:"Failed to refresh adapter models.")}finally{bt(!1)}}}r(ur,"handleRefreshModels");const Or=de==="codex_local"?"modelReasoningEffort":de==="cursor"?"mode":de==="opencode_local"?"variant":de==="grok_local"?"reasoningEffort":de==="pi_local"||de==="omp_local"?"thinking":"effort",Qr=de==="codex_local"?fV(Ln,"Auto").map(mt=>({id:mt.value,label:mt.label})):de==="cursor"?smt:de==="opencode_local"?tmt:de==="kimi_local"?rmt:de==="pi_local"?[{id:"",label:"Auto"},...["off","minimal","low","medium","high","xhigh"].map(mt=>({id:mt,label:mt}))]:de==="claude_local"||de==="grok_local"?[{id:"",label:"Auto"},...NE(de,Ln).map(mt=>({id:mt,label:mt==="xhigh"?"X-High":mt[0].toUpperCase()+mt.slice(1)}))]:nmt,ea=de==="omp_local",or=a?ea?String(ue.adapterSchemaValues?.thinking??""):ue.thinkingEffort:de==="codex_local"?V("adapterConfig","modelReasoningEffort",String(he.modelReasoningEffort??he.reasoningEffort??"")):de==="cursor"?V("adapterConfig","mode",String(he.mode??"")):de==="opencode_local"?V("adapterConfig","variant",String(he.variant??"")):V("adapterConfig",Or,String(he[Or]??"")),Ir=de!=="gemini_local"&&de!=="cursor_cloud"&&de!=="paperclip_runner"&&!ea,xt=r(mt=>{if(a){Be(ea?{adapterSchemaValues:{...ue.adapterSchemaValues,thinking:mt??void 0}}:{thinkingEffort:mt??""});return}X("adapterConfig",Or,mt||void 0)},"setThinkingEffort"),Ze=de==="codex_local"?a?!!ue.search:V("adapterConfig","search",!!he.search):!1,es=(0,m.useMemo)(()=>{if(a)return{heartbeat:{enabled:ue.heartbeatEnabled,intervalSec:ue.intervalSec}};const mt={...pe.heartbeat&&typeof pe.heartbeat=="object"?pe.heartbeat:{},...K.heartbeat};return{...pe,heartbeat:mt}},[a,K.heartbeat,pe,ue]),ms=qee(es.heartbeat),Is=qee(ms.maxTurnContinuation),ss=OOe(Is.enabled,!0),ws=yR(Oee(Is.maxAttempts,amt),0,cae),yn=yR(Oee(Is.delayMs,imt*1e3)/1e3,0,G_e);function Rn(mt){X("heartbeat","maxTurnContinuation",{...Is,...mt})}r(Rn,"updateMaxTurnContinuation");const nr=(0,t.jsx)(Ij,{ref:g,onDirtyChange:G,hideDraftActions:!a&&e.hideInlineSave,value:a?ue.envBindings??M2:V("adapterConfig","env",he.env??M2),secrets:y,userSecretDefinitions:k,onCreateSecret:r(async(mt,As)=>await F.mutateAsync({name:mt,value:As}),"onCreateSecret"),onChange:r(mt=>a?Be({envBindings:mt??{},envVars:""}):X("adapterConfig","env",mt),"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)($,{size:"sm",onClick:ce,disabled:e.isSaving,children:e.isSaving?"Saving...":"Save"})]})}),e.environmentVariablesPlacement==="secrets"&&(0,t.jsxs)("div",{"data-config-section":"environment-variables",className:W(!i&&"border-b border-border"),children:[i?(0,t.jsx)("h3",{className:"mb-3 text-sm font-medium",children:"Environment variables"}):(0,t.jsx)("div",{className:"px-4 py-2 text-xs font-medium text-muted-foreground",children:"Environment variables"}),(0,t.jsx)("div",{className:W(i?"rounded-lg border border-border p-4":"px-4 pb-3"),children:nr})]}),(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:ji.secretAccess}),(0,t.jsx)(Fut,{config:{...he,...K.adapterConfig},secrets:y,onChange:ae,onCreateSecret:r((mt,As)=>F.mutateAsync({name:mt,value:As}),"onCreateSecret"),proposals:S,onApproveProposal:C.requestApprove,onRejectProposal:C.requestReject}),C.dialogs]})]})]}):(0,t.jsxs)(lmt,{order:e.sectionOrder,className:W("relative",i&&"space-y-6"),children:[oe&&!e.hideInlineSave&&(0,t.jsx)("div",{className:"sticky top-0 z-10 flex items-center justify-end px-4 py-2 bg-background/90 backdrop-blur-sm border-b border-primary/20",children:(0,t.jsxs)("div",{className:"flex items-center gap-3",children:[(0,t.jsx)("span",{className:"text-xs text-muted-foreground",children:"Unsaved changes"}),(0,t.jsx)($,{size:"sm",onClick:ce,disabled:!a&&e.isSaving,children:!a&&e.isSaving?"Saving...":"Save"})]})}),!a&&(0,t.jsxs)("div",{"data-config-section":"identity",className:W(!i&&"border-b border-border"),children:[i?(0,t.jsx)("h3",{className:"text-sm font-medium mb-3",children:e.sectionTitles?.identity??"Identity"}):(0,t.jsx)("div",{className:"px-4 py-2 text-xs font-medium text-muted-foreground",children:"Identity"}),(0,t.jsxs)("div",{className:W(i?"border border-border rounded-lg p-4 space-y-3":"px-4 pb-3 space-y-3"),children:[(0,t.jsx)(_s,{label:"Name",hint:ji.name,children:(0,t.jsx)(Ga,{value:V("identity","name",e.agent.name),onCommit:r(mt=>X("identity","name",mt),"onCommit"),immediate:!0,className:kh,placeholder:"Agent name"})}),(0,t.jsx)(_s,{label:"Title",hint:ji.title,children:(0,t.jsx)(Ga,{value:V("identity","title",e.agent.title??""),onCommit:r(mt=>X("identity","title",mt||null),"onCommit"),immediate:!0,className:kh,placeholder:"e.g. VP of Engineering"})}),(0,t.jsx)(_s,{label:"Reports to",hint:ji.reportsTo,children:(0,t.jsx)(Jdt,{agents:be,value:V("identity","reportsTo",e.agent.reportsTo??null),onChange:r(mt=>X("identity","reportsTo",mt),"onChange"),excludeAgentIds:[e.agent.id],chooseLabel:"Choose manager…"})}),Ie&&!e.hidePromptTemplate&&(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)(_s,{label:"Prompt Template",hint:ji.promptTemplate,children:(0,t.jsx)(Jc,{value:V("adapterConfig","promptTemplate",String(he.promptTemplate??"")),onChange:r(mt=>X("adapterConfig","promptTemplate",mt??""),"onChange"),placeholder:"You are agent {{ agent.name }}. Your role is {{ agent.role }}...",contentClassName:"min-h-(--sz-88px) text-sm font-mono",imageUploadHandler:r(async mt=>{const As=`agents/${e.agent.id}/prompt-template`;return(await z.mutateAsync({file:mt,namespace:As})).contentPath},"imageUploadHandler")})}),(0,t.jsx)("div",{className:"rounded-md border border-amber-500/25 bg-amber-500/10 px-3 py-2 text-xs text-amber-900 dark:text-amber-100",children:"Prompt template is replayed on every heartbeat. Keep it compact and dynamic to avoid recurring token cost and cache churn."})]})]})]}),Q?(0,t.jsxs)("div",{"data-config-section":"environment",className:W(!i&&(a?"border-t border-border":"border-b border-border")),children:[i?(0,t.jsx)("h3",{className:"text-sm font-medium mb-3",children:"Environment"}):(0,t.jsx)("div",{className:"px-4 py-2 text-xs font-medium text-muted-foreground",children:"Environment"}),(0,t.jsx)("div",{className:W(i?"border border-border rounded-lg p-4 space-y-3":"px-4 pb-3 space-y-3"),children:(0,t.jsx)(_s,{label:"Default environment",hint:"This instance runs all agents in the Kubernetes sandbox. Local execution is disabled.",children:D?(0,t.jsxs)("div",{className:W(kh,"flex items-center text-muted-foreground"),children:[D.name," · Kubernetes sandbox"]}):(0,t.jsx)("div",{className:"rounded-md border border-amber-500/25 bg-amber-500/10 px-3 py-2 text-xs text-amber-800 dark:text-amber-200",children:"This instance requires the Kubernetes sandbox, but no managed Kubernetes environment is available for this organization yet. Configure one before creating agents; execution will not fall back to local."})})})]}):Oe?(0,t.jsxs)("div",{"data-config-section":"environment",className:W(!i&&(a?"border-t border-border":"border-b border-border")),children:[i?(0,t.jsx)("h3",{className:"text-sm font-medium mb-3",children:"Environment"}):(0,t.jsx)("div",{className:"px-4 py-2 text-xs font-medium text-muted-foreground",children:"Environment"}),(0,t.jsx)("div",{className:W(i?"border border-border rounded-lg p-4 space-y-3":"px-4 pb-3 space-y-3"),children:(0,t.jsx)(_s,{label:"Environment override",children:(0,t.jsx)("div",{className:"space-y-2",children:(0,t.jsxs)("select",{className:kh,value:Ot,onChange:r(mt=>{const As=mt.target.value;if(a){Be({defaultEnvironmentId:As});return}X("identity","defaultEnvironmentId",As||null)},"onChange"),children:[(0,t.jsxs)("option",{value:"",children:["Default: ",Re]}),qe.map(mt=>(0,t.jsx)("option",{value:mt.id,children:SN(mt)},mt.id))]})})})})]}):null,(0,t.jsxs)("div",{"data-config-section":"adapter",className:W(!i&&(a?"border-t border-border":"border-b border-border")),children:[(0,t.jsxs)("div",{className:W(i?"flex items-center justify-between mb-3":"px-4 py-2 flex items-center justify-between gap-2"),children:[i?(0,t.jsx)("h3",{className:"text-sm font-medium",children:e.sectionTitles?.adapter??"Adapter"}):(0,t.jsx)("span",{className:"text-xs font-medium text-muted-foreground",children:"Adapter"}),c&&(0,t.jsx)($,{type:"button",variant:"outline",size:"sm",className:"h-7 px-2.5 text-xs",onClick:Er,disabled:Hn,children:rs?`${Tn}...`:Tn})]}),(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)(_s,{label:"Adapter type",hint:ji.adapterType,children:(0,t.jsx)(J_e,{value:Le?"openai_dot":de,disabledTypes:R,openAiDotEnabled:_?.enableOpenAiDot===!0,onChange:r(mt=>{const As=mt==="openai_dot",pn=As?"paperclip_runner":mt;if(a){const{adapterType:Cn,...pr}=Eb,Nr={...pr,adapterType:pn};pn==="codex_local"?Nr.dangerouslyBypassSandbox=!0:pn==="gemini_local"?Nr.model="auto":pn==="kimi_local"?Nr.model="kimi-code/kimi-for-coding":pn==="cursor"?Nr.model="auto":pn==="opencode_local"?Nr.model="openai/gpt-5.2-codex":pn==="paperclip_runner"&&(Nr.model=jN),As&&(Nr.model="",Nr.adapterSchemaValues={provider:"openai_dot"}),Be(Nr)}else U(Cn=>({...Cn,adapterType:pn,adapterConfig:{model:pn==="gemini_local"?"auto":pn==="kimi_local"?"kimi-code/kimi-for-coding":pn==="opencode_local"?"openai/gpt-5.2-codex":pn==="cursor"?"auto":As?"":pn==="paperclip_runner"?Zut(de,he.model):"",effort:"",modelReasoningEffort:"",variant:"",mode:"",...pn==="codex_local"?{dangerouslyBypassApprovalsAndSandbox:!0}:As?{provider:"openai_dot",lifecycleMode:"per_turn",allowUnmeteredProvider:!1,dotAttachmentAccess:!1,dotWorkspaceAccess:!1}:pn==="paperclip_runner"?{...BCe(de,V("adapterConfig","model",he.model))}:{}}}))},"onChange")})}),!Le&&!a&&f&&(0,t.jsx)(vz,{companyId:f,agentId:e.agent.id,agentName:e.agent.name,adapterType:Jee(de,V("adapterConfig","provider",he.provider),V("adapterConfig","acpxAgent",he.acpxAgent)),routerAdapterType:de,value:$ee.safeParse(K.runtime.runtimeConfig?.aiConnection??pe.aiConnection).data,model:String(V("adapterConfig","model",he.model)??""),environmentId:Ot||void 0,legacy:!0,onChange:r(mt=>X("runtime","runtimeConfig",{...pe,aiConnection:mt}),"onChange")}),d&&!e.compactTestFeedback&&($s||It.error)&&(0,t.jsx)("div",{className:"rounded-md border border-destructive/30 bg-destructive/10 px-3 py-2 text-xs text-destructive",children:$s??(It.error instanceof Error?It.error.message:"Environment test failed")}),d&&!e.compactTestFeedback&&It.data&&(0,t.jsx)(fmt,{result:It.data}),d&&hr&&(0,t.jsx)(MV,{companyId:f,adapterType:de,environmentId:ht,onStored:a?gt:Xe,onApplyStored:a?at:Tt,onAccountBinding:a?void 0:Fe},`${de}:${ht}`),ye&&(0,t.jsx)(_s,{label:"Working directory (deprecated)",hint:ji.cwd,children:(0,t.jsxs)("div",{className:"flex items-center gap-2 rounded-md border border-border px-2.5 py-1.5",children:[(0,t.jsx)(nl,{className:"h-3.5 w-3.5 text-muted-foreground shrink-0"}),(0,t.jsx)(Ga,{value:a?ue.cwd:V("adapterConfig","cwd",String(he.cwd??"")),onCommit:r(mt=>a?Be({cwd:mt}):X("adapterConfig","cwd",mt||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)(tu,{})]})}),os("adapter"),Ie&&(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)(PV,{models:Wt,loadingModels:Ge?.isLoading??zs,value:Ln,effort:ea?{value:or||null,onChange:xt}:void 0,onChange:r(mt=>{ea&&!yM(or,mt,Wt.map(Cn=>Tk(Cn,!1)))&&xt(null);const As=NE(de,mt),pn=["codex_local","claude_local","grok_local"].includes(de)&&!!or&&!As.includes(String(or));if(a){Be({model:mt,...pn?{thinkingEffort:""}:{}});return}X("adapterConfig","model",Ge?.resolveModel(mt)||mt||void 0),pn&&(X("adapterConfig",Or,void 0),X("adapterConfig","reasoningEffort",void 0))},"onChange"),open:Se,onOpenChange:St,defaultLabel:de==="claude_local"?"Default (claude-opus-5)":void 0,allowDefault:de!=="opencode_local"&&de!=="pi_local"&&de!=="paperclip_runner",required:de==="opencode_local"||de==="pi_local",groupByProvider:!Ge&&(de==="opencode_local"||de==="pi_local"),preserveOrder:!!Ge||gV(de),creatable:!0,detectedModel:Ge?void 0:Gt,detectedModelCandidates:[],onDetectModel:Ge||de==="opencode_local"||de==="paperclip_runner"?void 0:async()=>(await pt()).data?.model??null,onRefreshModels:Ge?Ge.refreshModels:Yut(de)?ur:void 0,refreshingModels:Ge?.refreshing??Ye,detectModelLabel:"Detect model",emptyDetectHint:"No model detected. Select or enter one manually."}),(We||ut)&&(0,t.jsx)("p",{className:"text-xs text-destructive",children:We??(ut instanceof Error?ut.message:"Failed to load adapter models.")}),de==="opencode_local"&&!Ge&&rt&&rt.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 ",rt.name,"."]}),Ir&&(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)(xmt,{value:or,options:Qr,onChange:r(mt=>a?Be({thinkingEffort:mt}):X("adapterConfig",Or,mt||void 0),"onChange"),open:ze,onOpenChange:At}),de==="codex_local"&&Ze&&or==="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)(_s,{label:"Bootstrap prompt (legacy)",hint:ji.bootstrapPrompt,children:(0,t.jsx)(Jc,{value:V("adapterConfig","bootstrapPromptTemplate",String(he.bootstrapPromptTemplate??"")),onChange:r(mt=>X("adapterConfig","bootstrapPromptTemplate",mt||void 0),"onChange"),placeholder:"Optional initial setup prompt for the first run",contentClassName:"min-h-(--sz-44px) text-sm font-mono",imageUploadHandler:r(async mt=>{const As=`agents/${e.agent.id}/bootstrap-prompt`;return(await z.mutateAsync({file:mt,namespace:As})).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."})]}),os("configuration"),(Ie||de==="process"||ds?.fields.some(mt=>kz(mt.key)==="advanced"))&&(0,t.jsx)(hR,{title:"Advanced",open:Bs,onToggle:r(()=>kr(!Bs),"onToggle"),children:(0,t.jsxs)("div",{className:"space-y-3",children:[Ie&&(0,t.jsxs)(t.Fragment,{children:[" ",!E&&(0,t.jsx)(_s,{label:"Command",hint:ji.localCommand,children:(0,t.jsx)(Ga,{value:a?ue.command:V("adapterConfig",$t,String(he.command??"")),onCommit:r(mt=>a?Be({command:mt}):X("adapterConfig",$t,mt||null),"onCommit"),immediate:!0,className:kh,placeholder:{claude_local:"claude",codex_local:"codex",gemini_local:"gemini",kimi_local:"kimi",pi_local:"pi",cursor:"agent",opencode_local:"opencode"}[de]??de.replace(/_local$/,"")})}),(0,t.jsx)(_s,{label:"Extra args (comma-separated)",hint:ji.extraArgs,children:(0,t.jsx)(Ga,{value:a?ue.extraArgs:V("adapterConfig","extraArgs",emt(he.extraArgs)),onCommit:r(mt=>a?Be({extraArgs:mt}):X("adapterConfig","extraArgs",mt?.trim()?Xut(mt):null),"onCommit"),className:kh,placeholder:"e.g. --verbose, --foo=bar"})})]}),os("advanced")]})})]})]}),e.environmentVariablesPlacement!=="secrets"&&(Ie||ds?.fields.some(mt=>kz(mt.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:Ie?nr:os("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)(jC,{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)(jC,{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)(Nre,{label:"Heartbeat on interval",hint:ji.heartbeatInterval,checked:ue.heartbeatEnabled,onCheckedChange:r(mt=>Be({heartbeatEnabled:mt}),"onCheckedChange"),number:ue.intervalSec,onNumberChange:r(mt=>Be({intervalSec:mt}),"onNumberChange"),numberLabel:"sec",numberPrefix:"Run heartbeat every",numberHint:ji.intervalSec,showNumber:ue.heartbeatEnabled}),(0,t.jsx)(hR,{title:"Advanced Run Policy",open:vn,onToggle:r(()=>Ls(!vn),"onToggle"),children:(0,t.jsx)("div",{className:"space-y-3",children:os("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)(jC,{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)(jC,{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)(Nre,{label:"Heartbeat on interval",hint:ji.heartbeatInterval,checked:V("heartbeat","enabled",ge.enabled===!0),onCheckedChange:r(mt=>X("heartbeat","enabled",mt),"onCheckedChange"),number:V("heartbeat","intervalSec",Number(ge.intervalSec??300)),onNumberChange:r(mt=>X("heartbeat","intervalSec",mt),"onNumberChange"),numberLabel:"sec",numberPrefix:"Run heartbeat every",numberHint:ji.intervalSec,showNumber:V("heartbeat","enabled",ge.enabled===!0)})}),(0,t.jsx)(hR,{title:"Advanced Run Policy",bordered:i,open:vn,onToggle:r(()=>Ls(!vn),"onToggle"),children:(0,t.jsxs)("div",{className:"space-y-3",children:[os("runPolicy"),Ie&&(0,t.jsx)(t.Fragment,{children:!a&&(0,t.jsxs)(t.Fragment,{children:[!ds?.fields.some(mt=>mt.key==="timeoutSec")&&(0,t.jsx)(_s,{label:"Timeout (sec)",hint:ji.timeoutSec,children:(0,t.jsx)(Qc,{value:V("adapterConfig","timeoutSec",Number(he.timeoutSec??0)),onCommit:r(mt=>X("adapterConfig","timeoutSec",mt),"onCommit"),immediate:!0,className:kh})}),!ds?.fields.some(mt=>mt.key==="graceSec")&&(0,t.jsx)(_s,{label:"Interrupt grace period (sec)",hint:ji.graceSec,children:(0,t.jsx)(Qc,{value:V("adapterConfig","graceSec",Number(he.graceSec??15)),onCommit:r(mt=>X("adapterConfig","graceSec",mt),"onCommit"),immediate:!0,className:kh})})]})}),(0,t.jsx)(yl,{label:"Wake on demand",hint:ji.wakeOnDemand,checked:V("heartbeat","wakeOnDemand",ge.wakeOnDemand!==!1),onChange:r(mt=>X("heartbeat","wakeOnDemand",mt),"onChange")}),(0,t.jsx)(_s,{label:"Cooldown (sec)",hint:ji.cooldownSec,children:(0,t.jsx)(Qc,{value:V("heartbeat","cooldownSec",Number(ge.cooldownSec??10)),onCommit:r(mt=>X("heartbeat","cooldownSec",mt),"onCommit"),immediate:!0,className:kh})}),(0,t.jsx)(_s,{label:"Max concurrent runs",hint:ji.maxConcurrentRuns,children:(0,t.jsx)(Qc,{value:V("heartbeat","maxConcurrentRuns",Number(ge.maxConcurrentRuns??20)),onCommit:r(mt=>X("heartbeat","maxConcurrentRuns",mt),"onCommit"),immediate:!0,className:kh})}),(0,t.jsxs)("div",{className:"rounded-md border border-border/70 px-3 py-2",children:[(0,t.jsx)(yl,{label:"Continue after max-turn stop",hint:ji.maxTurnContinuationEnabled,checked:ss,onChange:r(mt=>Rn({enabled:mt}),"onChange")}),ss?(0,t.jsxs)("div",{className:"mt-3 grid gap-3 sm:grid-cols-2",children:[(0,t.jsx)(_s,{label:"Continuation attempts",hint:ji.maxTurnContinuationMaxAttempts,children:(0,t.jsx)(Qc,{value:ws,onCommit:r(mt=>Rn({maxAttempts:yR(mt,0,cae)}),"onCommit"),immediate:!0,className:kh})}),(0,t.jsx)(_s,{label:"Continuation delay (sec)",hint:ji.maxTurnContinuationDelaySec,children:(0,t.jsx)(Qc,{value:yn,onCommit:r(mt=>Rn({delayMs:omt(mt)}),"onCommit"),immediate:!0,className:kh})})]}):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)(Yy,{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)(Yy,{className:"h-3 w-3"})," Debugging"]}),(0,t.jsxs)("div",{className:W("border-border bg-accent/30",i?"rounded-lg border p-4":"mx-4 mb-4 rounded-md border px-3 py-3"),children:[(0,t.jsx)(yl,{label:"Capture raw provider traces",hint:"Stores exact provider traffic for every future run until disabled. Traces may contain sensitive prompts and tool arguments, are administrator-only, and expire after 24 hours.",checked:V("debug","providerTrace",Ee.providerTrace)==="raw",onChange:r(mt=>X("debug","providerTrace",mt?"raw":void 0),"onChange")}),V("debug","providerTrace",Ee.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)(Yy,{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)(WCe,{variant:Le?"prerequisites":"connection",state:rs?"running":$s||It.error?"fail":Pt?.status??"idle",result:Pt??null,error:$s??(It.error instanceof Error?It.error.message:null),onTest:Er,disabled:Hn})]})}r(Y_e,"AgentConfigForm");var Bz=new Set(["authenticated","failed","timed_out","cancelled"]),Fz=2e3;function zz({value:e,label:s}){const[n,a]=(0,m.useState)(!1),i=(0,m.useRef)(null);return(0,m.useEffect)(()=>()=>{i.current&&clearTimeout(i.current)},[]),(0,t.jsx)($,{type:"button",variant:"ghost",size:"icon-xs","aria-label":s,title:s,className:"text-muted-foreground hover:text-foreground",onClick:r(async()=>{try{await wa(e),a(!0)}catch{a(!1)}i.current&&clearTimeout(i.current),i.current=setTimeout(()=>a(!1),1500)},"onClick"),children:n?(0,t.jsx)(cs,{className:"size-3"}):(0,t.jsx)(gr,{className:"size-3"})})}r(zz,"AdapterLoginCopyButton");function cmt({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)(cs,{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(cmt,"AdapterLoginTerminalState");var dmt={claude_local:"Anthropic",codex_local:"OpenAI"};function Z_e(e){const s=dmt[e];return s?`Sign in to ${s}`:"Sign in to the environment"}r(Z_e,"adapterLoginTitle");function MV(e){return Xj()(e.adapterType).login?.panelMode==="submitted_browser_code"?(0,t.jsx)(pmt,{...e}):(0,t.jsx)(umt,{...e})}r(MV,"AdapterLoginPanel");var hD=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 umt({companyId:e,adapterType:s,environmentId:n,autoStart:a,onConnected:i,onAccountBinding:o,chrome:l="panel",aiConnection:c,onPromptReady:d}){const[u,h]=(0,m.useState)(null),[p,f]=(0,m.useState)(null),[x,g]=(0,m.useState)(null),[v,y]=(0,m.useState)("idle"),k=(0,m.useRef)(!1),w=je({mutationFn:r(()=>_t.startAdapterAuthLogin(e,s,{environmentId:n,aiConnection:c}),"mutationFn"),onSuccess:r(re=>{k.current=!1,f(null),g(null),y("idle"),h(re.sessionId)},"onSuccess"),onError:r(re=>{f(re instanceof Error?re.message:"Could not start the login.")},"onError")}),N=(0,m.useCallback)(()=>{k.current=!1,h(null),g(null),f(null)},[]),S=je({mutationFn:r(()=>_t.cancelAdapterAuthLogin(e,s,u),"mutationFn"),onSuccess:N,onError:r(re=>{f(re instanceof Error?re.message:"Could not cancel the login.")},"onError")}),C=te({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 hD(re.sessionId);return re}catch(re){if(re instanceof sn&&re.status===404)return null;throw re}},"queryFn"),retry:!1,gcTime:0,staleTime:0}),[_,R]=(0,m.useState)(!1),I=te({queryKey:["adapter-login-status",e,s,u],queryFn:r(()=>_t.getAdapterAuthLoginStatus(e,s,u),"queryFn"),enabled:!!u&&!_,retry:r((re,oe)=>oe instanceof sn&&oe.status===404?!1:re<3,"retry"),refetchInterval:r(re=>{const oe=re.state.data?.status;return oe&&Bz.has(oe)?!1:Fz},"refetchInterval")});(0,m.useEffect)(()=>{const re=I.data?.prompt??null;re&&g(re)},[I.data]);const T=I.data??w.data??null,E=T?.status??null,L=x,O=E?Bz.has(E):!1,P=!!u&&!O,Q=w.isPending||P||v==="saving",D=(0,m.useRef)(!1);(0,m.useEffect)(()=>{if(D.current||!C.isFetched)return;D.current=!0;const re=C.data;re&&(k.current=!0,f(null),g(re.prompt??null),h(re.sessionId))},[C.isFetched,C.data]),(0,m.useEffect)(()=>{const re=I.error;if(!(re instanceof sn&&re.status===404)||!k.current||_)return;R(!0);const oe=u;(async()=>(oe&&await _t.cancelAdapterAuthLogin(e,s,oe).catch(()=>{}),R(!1),N()))()},[I.error,_,u,e,s,N]);const F=(0,m.useRef)(!1),z=je({mutationFn:r(async()=>{const re=C.error;re instanceof hD&&await _t.cancelAdapterAuthLogin(e,s,re.sessionId)},"mutationFn"),onSuccess:r(async()=>{F.current=!1,D.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")}),K=(0,m.useRef)(w.mutate);K.current=w.mutate,(0,m.useEffect)(()=>{if(!(!a||F.current)){if(C.isError){F.current=!0,f(C.error instanceof Error?C.error.message:"Could not check for an active login.");return}C.isSuccess&&(F.current=!0,!C.data&&K.current())}},[a,C.isSuccess,C.isError,C.data,C.error]);const U=(0,m.useRef)(!1),q=(0,m.useRef)(i);q.current=i,(0,m.useEffect)(()=>{E!=="authenticated"||U.current||(U.current=!0,q.current?.(u??void 0))},[E]);const G=(0,m.useRef)(null),se=(0,m.useRef)(o);se.current=o;const Z=I.data?.codexAccountBinding??null,ie=(0,m.useCallback)(async re=>{const oe=se.current;if(oe){y("saving");try{await oe(re),y("bound")}catch{y("failed")}}},[]);(0,m.useEffect)(()=>{E!=="authenticated"||!u||G.current!==u&&(!Z||!Z.companyIdentityDiffers||!se.current||(G.current=u,ie(Z)))},[E,u,Z,ie]);const J=(0,m.useRef)(d);if(J.current=d,(0,m.useEffect)(()=>{J.current?.(L?.url??null)},[L]),l==="onboarding"){const re=O&&E&&E!=="authenticated";return(0,t.jsx)(NV,{loading:!L&&!p&&!re,providerName:kV(s),authorizationUrl:L?.url,mode:"displayed_code",children:p?(0,t.jsxs)("div",{children:[(0,t.jsx)("p",{role:"alert",className:"pl-2 text-xs text-destructive",children:p}),C.error instanceof hD&&(0,t.jsx)($,{type:"button",variant:"outline",disabled:z.isPending,onClick:r(()=>z.mutate(),"onClick"),children:"Cancel previous sign-in and retry"})]}):re?(0,t.jsx)("p",{role:"alert",className:"pl-2 text-xs text-destructive",children:E==="timed_out"?"The login timed out. Start it again.":E==="cancelled"?"The login was cancelled.":"The login did not finish. Start it again."}):(0,t.jsx)(r_e,{code:L?.code??"",autoCopy:!0})})}return(0,t.jsxs)("div",{className:"rounded-md border border-border bg-muted/40 px-3 py-2 flex flex-col gap-2",children:[(0,t.jsxs)("div",{className:"flex items-center justify-between gap-2",children:[(0,t.jsx)("span",{className:"text-xs font-medium text-foreground",children:Z_e(s)}),(0,t.jsxs)("div",{className:"flex items-center gap-1.5",children:[P&&(0,t.jsx)($,{type:"button",variant:"ghost",size:"sm",className:"h-7 px-2.5 text-xs text-muted-foreground hover:text-foreground",disabled:S.isPending,onClick:r(()=>S.mutate(),"onClick"),children:"Cancel"}),(0,t.jsx)($,{type:"button",variant:"outline",size:"sm",className:"h-7 px-2.5 text-xs",disabled:Q,onClick:r(()=>w.mutate(),"onClick"),children:"Sign in"})]})]}),p&&(0,t.jsx)("div",{role:"alert",className:"text-(length:--text-micro) text-destructive",children:p}),(0,t.jsxs)("div",{role:"status","aria-live":"polite",className:"space-y-2 empty:hidden",children:[P&&!L&&(0,t.jsxs)("div",{className:"flex items-center gap-2 text-(length:--text-micro) text-muted-foreground",children:[(0,t.jsx)(st,{className:"size-3 animate-spin shrink-0"}),(0,t.jsx)("span",{children:"Preparing..."})]}),P&&L&&(0,t.jsxs)("div",{className:"space-y-2",children:[(0,t.jsx)("div",{className:"text-(length:--text-micro) text-muted-foreground",children:"Copy the code, then open the authentication page."}),(0,t.jsxs)("div",{className:"flex items-center justify-between gap-2",children:[(0,t.jsxs)("div",{className:"min-w-0",children:[(0,t.jsx)("div",{className:"text-(length:--text-micro) uppercase tracking-wide text-muted-foreground",children:"1. Code"}),(0,t.jsx)("span",{className:"font-mono text-xs text-foreground break-all",children:L.code})]}),(0,t.jsx)(zz,{value:L.code,label:"Copy code"})]}),(0,t.jsxs)("div",{className:"flex items-center justify-between gap-2",children:[(0,t.jsxs)("div",{className:"min-w-0",children:[(0,t.jsx)("div",{className:"text-(length:--text-micro) uppercase tracking-wide text-muted-foreground",children:"2. Authentication URL"}),(0,t.jsx)("span",{className:"font-mono text-xs text-foreground break-all",children:L.url})]}),(0,t.jsxs)("div",{className:"flex items-center",children:[(0,t.jsx)(zz,{value:L.url,label:"Copy URL"}),(0,t.jsx)($,{asChild:!0,type:"button",variant:"ghost",size:"icon-xs","aria-label":"Open the authentication page",title:"Open the authentication page",className:"text-muted-foreground hover:text-foreground",children:(0,t.jsx)("a",{href:L.url,target:"_blank",rel:"noreferrer noopener",children:(0,t.jsx)(Dn,{className:"size-3"})})})]})]})]}),O&&E&&(0,t.jsx)(cmt,{status:E,message:T?.failure?.message??null}),E==="authenticated"&&v==="saving"&&(0,t.jsxs)("div",{className:"flex items-center gap-2 text-(length:--text-micro) text-muted-foreground",children:[(0,t.jsx)(st,{className:"size-3 animate-spin shrink-0"}),(0,t.jsx)("span",{children:"Binding this agent to the signed-in account..."})]}),E==="authenticated"&&v==="bound"&&(0,t.jsxs)("div",{className:"flex items-center gap-2 text-(length:--text-micro) text-foreground",children:[(0,t.jsx)(cs,{className:"size-3 shrink-0"}),(0,t.jsx)("span",{children:"Agent bound to the signed-in account."})]}),E==="authenticated"&&v==="failed"&&(0,t.jsxs)("div",{className:"flex items-center gap-2 text-(length:--text-micro)",children:[(0,t.jsx)(Es,{className:"size-3 shrink-0 text-destructive"}),(0,t.jsx)("span",{className:"text-destructive",children:"Could not bind this agent to the signed-in account."}),(0,t.jsx)($,{type:"button",variant:"outline",size:"sm",className:"h-6 px-2 text-xs",onClick:r(()=>{Z&&ie(Z)},"onClick"),children:"Retry"})]})]})]})}r(umt,"DisplayedCodeLoginPanel");var mmt=new Set(["failed","timed_out","cancelled"]),dae="The login did not finish. Start the login again.",hmt=9e5,uae="The login timed out. Start the login again.";function pmt({companyId:e,adapterType:s,environmentId:n,onStored:a,onApplyStored:i,autoStart:o,onConnected:l,onCodeSubmitted:c,onSubmitFailed:d,chrome:u="panel",aiConnection:h,onPromptReady:p}){const[f,x]=(0,m.useState)(null),[g,v]=(0,m.useState)(null),[y,k]=(0,m.useState)(null),[w,N]=(0,m.useState)(!1),[S,C]=(0,m.useState)(""),[_,R]=(0,m.useState)(null),[I,T]=(0,m.useState)(!1),[E,L]=(0,m.useState)(!1),[O,P]=(0,m.useState)(!1),[Q,D]=(0,m.useState)(!1),F=(0,m.useRef)(!1),[z,K]=(0,m.useState)(!1),U=(0,m.useRef)(!1),q=r(()=>{v(null),k(null),N(!1),C(""),R(null),T(!1),L(!1),D(!1),P(!1),F.current=!1},"resetLocalState"),G=te({queryKey:["claude-oauth-token-status",e],queryFn:r(async()=>{try{return await _t.getClaudeOAuthTokenStatus(e)}catch(rt){if(rt instanceof sn&&rt.status===404)return null;throw rt}},"queryFn"),retry:r((rt,Pe)=>Pe instanceof sn&&Pe.status===404?!1:rt<2,"retry")}).data??null,se=je({mutationFn:r(()=>_t.startClaudeSetupTokenLogin(e,{environmentId:n,aiConnection:h,...G&&!h?{overwrite:{expectedSecretId:G.secretId,expectedLatestVersion:G.latestVersion}}:{}}),"mutationFn"),onSuccess:r(rt=>{U.current=!1,q(),x(rt.sessionId)},"onSuccess"),onError:r(rt=>{v(rt instanceof Error?rt.message:"Could not start the login.")},"onError")}),Z=r(()=>{U.current=!1,x(null),q()},"clearActiveSession"),ie=je({mutationFn:r(()=>_t.cancelClaudeSetupTokenLogin(e,f),"mutationFn"),onSuccess:r(()=>{Z()},"onSuccess"),onError:r(rt=>{if(rt instanceof sn&&rt.status===404){Z();return}v(rt instanceof Error?rt.message:"Could not cancel the login.")},"onError")}),J=(0,m.useCallback)(rt=>{_t.cancelClaudeSetupTokenLogin(e,rt).catch(()=>{})},[e]),re=te({queryKey:["claude-setup-token-active-session",e],queryFn:r(async()=>{try{const rt=await _t.getActiveClaudeSetupTokenLoginSession(e);if(!rt)return null;if(h&&rt.environmentId!==n||!!rt.aiConnection!=!!h||h&&(rt.aiConnection?.provider!==h.provider||rt.aiConnection?.method!==h.method||rt.aiConnection?.connectionId!==h.connectionId||rt.aiConnection?.ownership!==h.ownership||rt.aiConnection?.allAgents!==h.allAgents||JSON.stringify(rt.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 rt}catch(rt){if(rt instanceof sn&&rt.status===404)return null;throw rt}},"queryFn"),retry:!1,gcTime:0,staleTime:0}),[oe,V]=(0,m.useState)(!1),X=!!f&&!E&&!Q&&!oe,Y=te({queryKey:["claude-setup-token-status",e,f],queryFn:r(()=>_t.getClaudeSetupTokenLoginStatus(e,f),"queryFn"),enabled:X,retry:r((rt,Pe)=>Pe instanceof sn&&Pe.status===404?!1:rt<3,"retry"),refetchInterval:r(rt=>{if(E||Q)return!1;const Pe=rt.state.data?.status;return Pe&&Bz.has(Pe)?!1:Fz},"refetchInterval")});(0,m.useEffect)(()=>{const rt=Y.error;if(rt instanceof sn&&rt.status===404){if(U.current){if(oe)return;V(!0);const Pe=f;(async()=>(Pe&&await _t.cancelClaudeSetupTokenLogin(e,Pe).catch(()=>{}),V(!1),Z()))();return}D(!0)}},[Y.error,oe,f,e]);const ae=(0,m.useRef)(!1);(0,m.useEffect)(()=>{if(ae.current||!re.isFetched)return;ae.current=!0;const rt=re.data;rt&&(U.current=!0,q(),x(rt.sessionId),rt.prompt&&(k(rt.prompt.authorizationUrl),rt.prompt.transportAdvisory&&N(!0)))},[re.isFetched,re.data]);const ne=te({queryKey:["claude-setup-token-prompt",e,f],enabled:X&&!y,queryFn:r(async()=>{try{return await _t.getClaudeSetupTokenLoginPrompt(e,f)}catch(rt){if(rt instanceof sn&&rt.status===404)return null;throw rt}},"queryFn"),refetchInterval:r(rt=>E||rt.state.data?.authorizationUrl?!1:Fz,"refetchInterval")});(0,m.useEffect)(()=>{const rt=ne.data?.authorizationUrl??null;rt&&k(rt),ne.data?.transportAdvisory&&N(!0)},[ne.data]);const ce=je({mutationFn:r(rt=>_t.submitClaudeSetupTokenBrowserCode(e,f,rt),"mutationFn"),onError:r(rt=>{v(rt instanceof Error?rt.message:"Could not submit the browser code.")},"onError")}),he=je({mutationFn:r(()=>_t.completeClaudeSetupTokenLogin(e,f),"mutationFn"),onSuccess:r(rt=>{R(rt.storedSessionId),a?.(rt.storedSessionId)},"onSuccess"),onError:r(()=>{T(!0)},"onError")}),pe=Y.data?.status??se.data?.status??null,ge=Y.data?.expiresAt??se.data?.expiresAt??null,Ee=(0,m.useRef)(he.mutate);Ee.current=he.mutate,(0,m.useEffect)(()=>{pe==="authenticated"&&!F.current&&(F.current=!0,Ee.current())},[pe]);const de=_!==null,Ne=I||Q||!!(pe&&mmt.has(pe)),le=pe==="authenticated"&&!de&&!I,Le=!!f&&!de&&!Ne&&!E,Ie=se.isPending||Le;(0,m.useEffect)(()=>{if(!Le)return;const rt=ge!==null?new Date(ge).getTime():NaN,Pe=Number.isFinite(rt)?Math.max(0,rt-Date.now()):hmt,De=setTimeout(()=>{f&&J(f),L(!0)},Pe);return()=>clearTimeout(De)},[Le,ge,f,J]);const ye=S.trim(),Ae=Le&&!!y&&!le&&bOe(ye)&&!ce.isPending&&!O,Qe=(0,m.useRef)(c);Qe.current=c;const ue=(0,m.useRef)(d);ue.current=d;const Be=r(()=>{Ae&&(v(null),ce.mutate(ye),P(!0),Qe.current?.(),u!=="onboarding"&&C(""))},"handleSubmit"),ft=(0,m.useRef)(!1),gt=(0,m.useRef)(se.mutate);gt.current=se.mutate,(0,m.useEffect)(()=>{if(!(!o||ft.current)){if(re.isError){ft.current=!0,v(re.error instanceof Error?re.error.message:"Could not check for an active login.");return}re.isSuccess&&(ft.current=!0,!re.data&&gt.current())}},[o,re.isSuccess,re.isError,re.data,re.error]);const Xe=(0,m.useRef)(Be);Xe.current=Be;const Fe=u==="onboarding",at=(0,m.useRef)(!1);(0,m.useEffect)(()=>{!Fe||!at.current||(at.current=!1,Ae&&Xe.current())},[Fe,Ae,S]);const Tt=(0,m.useRef)(!1),Dt=(0,m.useRef)(l);Dt.current=l,(0,m.useEffect)(()=>{!de||Tt.current||(Tt.current=!0,Dt.current?.(f??void 0))},[de]),(0,m.useEffect)(()=>{O&&(!g&&!Ne&&!E||(P(!1),ue.current?.()))},[O,g,Ne,E]);const Ot=(0,m.useRef)(p);if(Ot.current=p,(0,m.useEffect)(()=>{Ot.current?.(y)},[y]),u==="onboarding"){const rt=Ne||E;return(0,t.jsxs)(NV,{loading:!y&&!g&&!rt,providerName:kV(s),authorizationUrl:y??void 0,mode:"submitted_code",children:[w&&(0,t.jsxs)("p",{className:"flex items-start gap-2 pl-2 text-xs text-amber-700 dark:text-amber-200",children:[(0,t.jsx)(Es,{className:"mt-0.5 size-3 shrink-0"}),"This connection is not encrypted. The login code travels in clear text on this network. Continue only on a network you trust."]}),g?(0,t.jsx)("p",{role:"alert",className:"pl-2 text-xs text-destructive",children:g}):rt?(0,t.jsx)("p",{role:"alert",className:"pl-2 text-xs text-destructive",children:E&&!Ne?uae:dae}):(0,t.jsx)(X3,{value:S,onChange:C,onSubmit:Be,onPaste:r(()=>{at.current=!0},"onPaste"),masked:!0,disabled:ce.isPending||le||O})]})}return(0,t.jsxs)("div",{className:"rounded-md border border-border bg-muted/40 px-3 py-2 flex flex-col gap-2",children:[(0,t.jsxs)("div",{className:"flex items-center justify-between gap-2",children:[(0,t.jsx)("span",{className:"text-xs font-medium text-foreground",children:Z_e(s)}),(0,t.jsxs)("div",{className:"flex items-center gap-1.5",children:[Le&&(0,t.jsx)($,{type:"button",variant:"ghost",size:"sm",className:"h-7 px-2.5 text-xs text-muted-foreground hover:text-foreground",disabled:ie.isPending,onClick:r(()=>ie.mutate(),"onClick"),children:"Cancel"}),i&&G&&!Le&&!de&&!z&&(0,t.jsx)($,{type:"button",variant:"default",size:"sm",className:"h-7 px-2.5 text-xs",onClick:r(()=>{i(),K(!0)},"onClick"),children:"Use saved login"}),(0,t.jsx)($,{type:"button",variant:"outline",size:"sm",className:"h-7 px-2.5 text-xs",disabled:Ie,onClick:r(()=>se.mutate(),"onClick"),children:G&&!Le&&!de?"Sign in to replace":"Sign in"})]})]}),G&&!Le&&!de&&!z&&(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."}),z&&(0,t.jsxs)("div",{className:"flex items-center gap-2 text-(length:--text-micro) text-foreground",children:[(0,t.jsx)(cs,{className:"size-3 shrink-0"}),(0,t.jsx)("span",{children:"The saved Claude login is bound to this agent now."})]}),g&&(0,t.jsx)("div",{role:"alert",className:"text-(length:--text-micro) text-destructive",children:g}),(0,t.jsxs)("div",{role:"status","aria-live":"polite",className:"space-y-2 empty:hidden",children:[Le&&!y&&!le&&(0,t.jsxs)("div",{className:"flex items-center gap-2 text-(length:--text-micro) text-muted-foreground",children:[(0,t.jsx)(st,{className:"size-3 animate-spin shrink-0"}),(0,t.jsx)("span",{children:"Preparing..."})]}),Le&&y&&!le&&(0,t.jsxs)("div",{className:"space-y-2",children:[w&&(0,t.jsxs)("div",{className:"flex items-start gap-2 rounded-md border border-amber-300 bg-amber-50 px-2 py-1.5 text-(length:--text-micro) text-amber-800 dark:border-amber-500/40 dark:bg-amber-500/10 dark:text-amber-200",children:[(0,t.jsx)(Es,{className:"size-3 shrink-0 mt-0.5"}),(0,t.jsx)("span",{children:"This connection is not encrypted. The login code travels in clear text on this network. Continue only on a network you trust."})]}),(0,t.jsx)("div",{className:"text-(length:--text-micro) text-muted-foreground",children:"Open the authorization page, then enter the browser code it shows."}),(0,t.jsxs)("div",{className:"flex items-center justify-between gap-2",children:[(0,t.jsxs)("div",{className:"min-w-0",children:[(0,t.jsx)("div",{className:"text-(length:--text-micro) uppercase tracking-wide text-muted-foreground",children:"1. Authorization URL"}),(0,t.jsx)("span",{className:"font-mono text-xs text-foreground break-all",children:y})]}),(0,t.jsxs)("div",{className:"flex items-center",children:[(0,t.jsx)(zz,{value:y,label:"Copy URL"}),(0,t.jsx)($,{asChild:!0,type:"button",variant:"ghost",size:"icon-xs","aria-label":"Open the authorization page",title:"Open the authorization page",className:"text-muted-foreground hover:text-foreground",children:(0,t.jsx)("a",{href:y,target:"_blank",rel:"noreferrer noopener",children:(0,t.jsx)(Dn,{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(rt=>C(rt.target.value),"onChange"),onKeyDown:r(rt=>{rt.key==="Enter"&&(rt.preventDefault(),Be())},"onKeyDown"),className:"flex-1 min-w-0 rounded-md border border-border bg-background px-2 py-1 font-mono text-xs text-foreground"}),(0,t.jsx)($,{type:"button",variant:"outline",size:"sm",className:"h-7 px-2.5 text-xs",disabled:!Ae,onClick:Be,children:"Submit"})]})]})]}),le&&(0,t.jsxs)("div",{className:"flex items-center gap-2 text-(length:--text-micro) text-muted-foreground",children:[(0,t.jsx)(st,{className:"size-3 animate-spin shrink-0"}),(0,t.jsx)("span",{children:"Completing the login…"})]}),de&&(0,t.jsxs)("div",{className:"flex items-center gap-2 text-(length:--text-micro) text-foreground",children:[(0,t.jsx)(cs,{className:"size-3 shrink-0"}),(0,t.jsx)("span",{children:"Authenticated. The environment has credentials now."})]}),Ne&&(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:dae})]}),E&&!Ne&&!de&&(0,t.jsxs)("div",{className:"flex items-start gap-2 text-(length:--text-micro) text-destructive",children:[(0,t.jsx)(Es,{className:"size-3 shrink-0"}),(0,t.jsx)("span",{children:uae})]})]})]})}r(pmt,"SubmittedBrowserCodeLoginPanel");function fmt({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(fmt,"AdapterEnvironmentResult$1");function J_e({value:e,onChange:s,disabledTypes:n,openAiDotEnabled:a=!1}){const[i,o]=(0,m.useState)(!1),l=Gm(e),c=(0,m.useMemo)(()=>[...H_e(d=>b5[d]??wf(d)),...a?[{value:"openai_dot",label:"OpenAI Dot",experimental:!0,comingSoon:!1}]:[]].filter(d=>!n.has(d.value)),[n,a]);return(0,t.jsxs)(dr,{open:i,onOpenChange:o,children:[(0,t.jsx)(wr,{asChild:!0,children:(0,t.jsxs)("button",{type:"button","data-size":"default",className:W(Sqe,"w-full"),children:[(0,t.jsxs)("span",{className:"inline-flex min-w-0 items-center gap-1.5",children:[(0,t.jsx)("span",{"aria-hidden":"true",className:"inline-flex shrink-0",children:(0,t.jsx)(B0,{type:e,className:"size-4"})}),(0,t.jsx)("span",{className:"truncate",children:b5[e]??wf(e)}),l.experimental&&(0,t.jsx)(mae,{})]}),(0,t.jsx)(rn,{className:"size-4 opacity-50"})]})}),(0,t.jsx)(sr,{className:"w-(--radix-popover-trigger-width) p-1",align:"start",children:c.map(d=>(0,t.jsxs)("button",{type:"button",disabled:d.comingSoon,className:W("flex items-center justify-between w-full px-2 py-1.5 text-sm rounded",d.comingSoon?"opacity-40 cursor-not-allowed":"hover:bg-accent/50",d.value===e&&!d.comingSoon&&"bg-accent"),onClick:r(()=>{d.comingSoon||(s(d.value),o(!1))},"onClick"),children:[(0,t.jsxs)("span",{className:"inline-flex items-center gap-1.5",children:[(0,t.jsx)("span",{"aria-hidden":"true",className:"inline-flex shrink-0",children:(0,t.jsx)(B0,{type:d.value,className:"size-4"})}),(0,t.jsx)("span",{children:d.label}),d.experimental&&(0,t.jsx)(mae,{})]}),d.comingSoon&&(0,t.jsx)("span",{className:"text-(length:--text-nano) text-muted-foreground",children:"Coming soon"})]},d.value))})]})}r(J_e,"AdapterTypeDropdown");function mae(){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(mae,"ExperimentalBadge$1");function PV({models:e,value:s,onChange:n,open:a,onOpenChange:i,allowDefault:o,required:l,groupByProvider:c,preserveOrder:d,creatable:u,detectedModel:h,detectedModelCandidates:p,onDetectModel:f,onRefreshModels:x,refreshingModels:g,loadingModels:v,detectModelLabel:y,emptyDetectHint:k,defaultLabel:w,presentation:N="searchable",effort:S}){const[C,_]=(0,m.useState)(""),[R,I]=(0,m.useState)(!1),[T,E]=(0,m.useState)(!1),L=C.trim(),O=!!(u&&L&&!e.some(U=>U.id.toLowerCase()===L.toLowerCase())),P=(0,m.useMemo)(()=>{const U=new Set;h&&U.add(h);for(const q of p??[])q&&U.add(q);return U},[h,p]),Q=(0,m.useMemo)(()=>e.filter(U=>{if(P.has(U.id))return!1;const q=CE(U.id);return nM({...Tk(U,c),...q&&!U.provider?{group:q}:{}},C)}),[e,C,P,c]),D=(0,m.useMemo)(()=>new Map(e.map(U=>[U.id,Tk(U,c)])),[e,c]),F=s?eu(s,[...D.values()]):null,z=(0,m.useMemo)(()=>{if(!c&&Q.some(q=>q.provider)){const q=new Map;for(const G of Q){const se=G.provider??"other";q.set(se,[...q.get(se)??[],G])}return Array.from(q.entries()).map(([G,se])=>({provider:G,entries:se}))}if(!c)return[{provider:null,entries:d?Q:[...Q].sort((q,G)=>q.id.localeCompare(G.id))}];const U=new Map;for(const q of Q){const G=CE(q.id)??"other",se=U.get(G)??[];se.push(q),U.set(G,se)}return Array.from(U.entries()).sort(([q],[G])=>q.localeCompare(G)).map(([q,G])=>({provider:q,entries:[...G].sort((se,Z)=>se.id.localeCompare(Z.id))}))},[Q,c,d]);async function K(){if(f){E(!0);try{const U=await f();U&&(n(U),i(!1),_(""))}finally{E(!1)}}}if(r(K,"handleDetectModel"),N==="native"){const U="__paperclip_custom_model__",q=[...new Set([s,...P])].filter(G=>!!G&&(!e.some(se=>se.id===G)||P.has(G)));return(0,t.jsxs)(_s,{label:"Model",hint:ji.model,children:[(0,t.jsxs)(uW,{"aria-label":"Model","aria-busy":v||g,value:R?U:s,required:l&&!R,onChange:r(G=>{const se=G.target.value;I(se===U),se!==U&&n(se)},"onChange"),children:[(0,t.jsx)("option",{value:"",disabled:!o,children:o?w??"Default":v?"Loading models…":l?"Select model (required)":"Select model"}),q.map(G=>(0,t.jsx)("option",{value:G,children:e.find(se=>se.id===G)?.label??G},G)),z.map(({provider:G,entries:se})=>c?(0,t.jsx)("optgroup",{label:G??void 0,children:se.map(Z=>(0,t.jsx)("option",{value:Z.id,children:Z.label},Z.id))},G):se.map(Z=>(0,t.jsx)("option",{value:Z.id,children:Z.label},Z.id))),u&&(0,t.jsx)("option",{value:U,children:"Enter custom model…"})]}),R&&(0,t.jsxs)("label",{className:"mt-3 block space-y-1 text-xs text-muted-foreground",children:["Model ID",(0,t.jsx)(dt,{"aria-label":"Model ID",value:s,onChange:r(G=>n(G.target.value),"onChange"),placeholder:"Enter model ID or alias",autoFocus:!0,required:l})]}),v&&(0,t.jsx)("p",{role:"status",className:"mt-2 text-xs text-muted-foreground",children:"Loading models…"}),x&&(0,t.jsx)($,{type:"button",variant:"ghost",size:"sm",disabled:g,onClick:r(()=>{x()},"onClick"),children:g?"Refreshing…":"Refresh models"})]})}return(0,t.jsx)(_s,{label:"Model",hint:ji.model,children:(0,t.jsxs)(dr,{open:a,onOpenChange:r(U=>{i(U),U||_("")},"onOpenChange"),children:[(0,t.jsx)(wr,{asChild:!0,children:(0,t.jsxs)("button",{type:"button","aria-label":"Model",className:"flex w-full min-w-0 items-center gap-2 rounded-md border border-border px-2.5 py-1.5 text-left text-sm transition-colors hover:bg-accent/50","data-testid":"model-dropdown-trigger",children:[F?(0,t.jsx)(yf,{display:F,layout:"inline",className:"min-w-0 flex-1"}):(0,t.jsx)("span",{className:"min-w-0 flex-1 truncate text-muted-foreground",children:o?w??"Default":l?"Select model (required)":"Select model"}),S&&s&&Cj(S.value,s,[...D.values()])?(0,t.jsxs)("span",{className:W("shrink-0 text-xs",S.value?"text-foreground":"text-muted-foreground"),"data-testid":"model-dropdown-effort-value",children:["· ",S.value??"Auto effort"]}):null,(0,t.jsx)(rn,{className:"size-4 shrink-0 text-muted-foreground"})]})}),(0,t.jsxs)(sr,{className:"w-(--radix-popover-trigger-width) p-1",align:"start",children:[S&&s&&Cj(S.value,s,[...D.values()])?(0,t.jsxs)("div",{className:"-mx-1 -mt-1 mb-1 space-y-1.5 border-b border-border px-2.5 py-2",children:[(0,t.jsx)("span",{className:"block text-xs font-medium text-muted-foreground",children:"Thinking effort"}),(0,t.jsx)(jM,{levels:ng(s,[...D.values()]),value:S.value,onChange:r(U=>{S.onChange(U),i(!1)},"onChange"),defaultLabel:"Auto",label:"Thinking effort",testId:"model-dropdown-effort"})]}):null,(0,t.jsxs)("div",{className:"relative -mx-1 -mt-1 mb-1 border-b border-border",children:[(0,t.jsx)(Jr,{className:"pointer-events-none absolute left-2.5 top-1/2 size-4 -translate-y-1/2 text-muted-foreground","aria-hidden":"true"}),(0,t.jsx)("input",{"aria-label":"Search models",className:"h-9 w-full bg-transparent pl-8 pr-7 text-sm outline-none placeholder:text-muted-foreground",placeholder:u?TS:"Search models",value:C,onChange:r(U=>_(U.target.value),"onChange"),autoFocus:!0}),C&&(0,t.jsx)("button",{type:"button","aria-label":"Clear search",className:"absolute right-2.5 top-1/2 -translate-y-1/2 text-muted-foreground hover:text-foreground",onClick:r(()=>_(""),"onClick"),children:(0,t.jsxs)("svg",{"aria-hidden":"true",focusable:"false",className:"h-3 w-3",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,t.jsx)("line",{x1:"18",y1:"6",x2:"6",y2:"18"}),(0,t.jsx)("line",{x1:"6",y1:"6",x2:"18",y2:"18"})]})})]}),f&&!C.trim()&&(0,t.jsxs)("button",{type:"button",className:"flex items-center gap-1.5 w-full px-2 py-1.5 text-xs rounded hover:bg-accent/50 text-muted-foreground",onClick:r(()=>{K()},"onClick"),disabled:T,children:[(0,t.jsxs)("svg",{"aria-hidden":"true",focusable:"false",className:"h-3 w-3",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,t.jsx)("path",{d:"M21 12a9 9 0 0 0-9-9 9.75 9.75 0 0 0-6.74 2.74L3 8"}),(0,t.jsx)("path",{d:"M3 3v5h5"})]}),T?"Detecting...":h?y?.replace(/^Detect\b/,"Re-detect")??"Re-detect from config":y??"Detect from config"]}),x&&!C.trim()&&(0,t.jsxs)("button",{type:"button",className:"flex items-center gap-1.5 w-full px-2 py-1.5 text-xs rounded hover:bg-accent/50 text-muted-foreground",onClick:r(()=>{x()},"onClick"),disabled:g,children:[(0,t.jsxs)("svg",{"aria-hidden":"true",focusable:"false",className:"h-3 w-3",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,t.jsx)("path",{d:"M3 12a9 9 0 0 1 15.28-6.36L21 8"}),(0,t.jsx)("path",{d:"M21 3v5h-5"}),(0,t.jsx)("path",{d:"M21 12a9 9 0 0 1-15.28 6.36L3 16"}),(0,t.jsx)("path",{d:"M8 16H3v5"})]}),g?"Refreshing...":"Refresh models"]}),s&&(!e.some(U=>U.id===s)||P.has(s))&&(0,t.jsxs)("button",{type:"button",className:W("flex items-center w-full px-2 py-1.5 text-sm rounded bg-accent/50"),onClick:r(()=>{i(!1)},"onClick"),children:[F?(0,t.jsx)(yf,{display:F,layout:"inline",className:"flex-1"}):null,(0,t.jsx)(it,{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(U=>U.id===h)?.label??h}),(0,t.jsx)(it,{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(U=>U&&U!==h&&U!==s).map(U=>{const q=e.find(G=>G.id===U);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(U),i(!1)},"onClick"),children:[(0,t.jsx)("span",{className:"block w-full text-left truncate font-mono text-xs",title:U,children:q?.label??U}),(0,t.jsx)(it,{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-${U}`)}),(0,t.jsxs)("div",{className:"max-h-(--sz-240px) overflow-y-auto",children:[o&&(0,t.jsx)("button",{type:"button",className:W("flex items-center gap-2 w-full px-2 py-1.5 text-sm rounded hover:bg-accent/50",!s&&"bg-accent"),onClick:r(()=>{n(""),i(!1)},"onClick"),children:"Default"}),O&&(0,t.jsxs)("button",{type:"button",className:"flex items-center justify-between gap-2 w-full px-2 py-1.5 text-sm rounded hover:bg-accent/50",onClick:r(()=>{n(L),i(!1),_("")},"onClick"),children:[(0,t.jsx)("span",{children:"Use manual model"}),(0,t.jsx)("span",{className:"text-xs font-mono text-muted-foreground",children:L})]}),z.map(U=>(0,t.jsxs)("div",{className:"mb-1 last:mb-0",children:[U.provider&&(0,t.jsx)(aM,{provider:U.provider,testId:`model-dropdown-group-${U.provider}`}),U.entries.map(q=>(0,t.jsxs)("button",{type:"button",className:W("flex items-center gap-2 w-full px-2 py-1.5 text-left text-sm rounded hover:bg-accent/50",q.id===s&&"bg-accent"),onClick:r(()=>{n(q.id),S&&ng(q.id,[...D.values()]).length>0||i(!1)},"onClick"),children:[(0,t.jsx)(rM,{option:D.get(q.id)??Tk(q,c)}),q.id===s?(0,t.jsx)(cs,{className:"size-4 shrink-0","aria-hidden":"true"}):null]},q.id))]},U.provider??"")),Q.length===0&&!O&&P.size===0&&(0,t.jsx)("div",{className:"px-2 py-2 space-y-2",children:(0,t.jsx)("p",{className:"text-xs text-muted-foreground",children:v?"Loading models…":f?k??"No model detected yet. Enter a provider/model manually.":"No models found."})})]})]})]})})}r(PV,"ModelDropdown");function xmt({value:e,options:s,onChange:n,open:a,onOpenChange:i}){const o=s.find(l=>l.id===e)??s[0];return(0,t.jsx)(_s,{label:"Thinking effort",hint:ji.thinkingEffort,children:(0,t.jsxs)(dr,{open:a,onOpenChange:i,children:[(0,t.jsx)(wr,{asChild:!0,children:(0,t.jsxs)("button",{className:"inline-flex items-center gap-1.5 rounded-md border border-border px-2.5 py-1.5 text-sm hover:bg-accent/50 transition-colors w-full justify-between",children:[(0,t.jsx)("span",{className:W(!e&&"text-muted-foreground"),children:o?.label??"Auto"}),(0,t.jsx)(rn,{className:"h-3 w-3 text-muted-foreground"})]})}),(0,t.jsx)(sr,{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(xmt,"ThinkingEffortDropdown");function X_e(e){const s=`paperclip.agent-appearance.${e}`;function n(){try{const l=gbe.safeParse(JSON.parse(sessionStorage.getItem(s)??"null"));if(l.success)return l.data}catch{}const o=WT();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(X_e,"useAgentAppearanceDraft");var P2=null,PI=new Set,D2={subscribe(e){return PI.add(e),()=>{PI.delete(e)}},getSnapshot(){return P2},acquire(e){if(P2)return!1;P2=e;for(const s of PI)s();return!0},release(e){if(P2===e){P2=null;for(const s of PI)s()}}};function _N({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)(()=>iv(s??e?.appearance,e?.id),[s,e?.appearance,e?.id]),g=(0,m.useRef)(null),v=(0,m.useRef)(null),y=(0,m.useRef)(null),k=(0,m.useRef)(Symbol("agent-character")),w=(0,m.useSyncExternalStore)(D2.subscribe,D2.getSnapshot,()=>null),[N,S]=(0,m.useState)(!1),[C,_]=(0,m.useState)(!0),[R,I]=(0,m.useState)(!1),[T,E]=(0,m.useState)(!1),L=!x.customAvatarAssetId&&N&&!C&&!R&&o==="auto"&&a!=="rest";return(0,m.useEffect)(()=>{if(typeof matchMedia!="function"||typeof IntersectionObserver!="function")return;const O=matchMedia("(prefers-reduced-motion: reduce)"),P=r(()=>_(O.matches),"change");P(),O.addEventListener("change",P);const Q=new IntersectionObserver(D=>S(D[0]?.isIntersecting??!1));return g.current&&Q.observe(g.current),()=>{Q.disconnect(),O.removeEventListener("change",P)}},[]),(0,m.useEffect)(()=>{L&&w===null&&D2.acquire(k.current),L||D2.release(k.current)},[L,w]),(0,m.useEffect)(()=>()=>D2.release(k.current),[]),(0,m.useEffect)(()=>{if(!L||w!==k.current)return;let O=!1;return E(!1),Promise.all([fd(()=>import("./runtime-IAg0vdY9.js"),__vite__mapDeps([0,1])),fd(()=>import("./definition-CKRv2OQh.js"),__vite__mapDeps([2,3,1]))]).then(([P,Q])=>{O||!v.current||(y.current=P.createCharacter(v.current,Q.characterDefinition(x,i),{animation:Q.animationId(a),trackingRegion:l?.current??g.current??void 0,followCursor:d,followRotation:u,trackingScope:c,displaySize:n,onError:r(()=>I(!0),"onError")}),E(!0))}).catch(()=>{O||I(!0)}),()=>{O=!0,y.current?.destroy(),y.current=null,E(!1)}},[L,w,l,c,n,d,u]),(0,m.useEffect)(()=>{y.current&&fd(()=>import("./definition-CKRv2OQh.js").then(O=>{y.current?.setDefinition(O.characterDefinition(x,i)),y.current?.setAnimation(O.animationId(a))}),__vite__mapDeps([2,3,1]))},[x,i,a,T]),(0,t.jsxs)("span",{ref:g,role:p?"img":void 0,"aria-label":p,"aria-hidden":p?void 0:!0,className:W("relative inline-block shrink-0",lqe[n],h),children:[(0,t.jsx)(lr,{agent:e,appearance:x,size:n<256?256:n,name:f,pose:a,muted:i,className:W("size-full",T&&!x.customAvatarAssetId&&"invisible")}),(0,t.jsx)("span",{ref:v,className:"absolute inset-0"})]})}r(_N,"AgentCharacter");var gmt=new Set(["claude_local","codex_local","opencode_local","grok_local"]);function e5e(e,{cloud:s,nativeRunnerEnabled:n,openAiDotEnabled:a=!1,runnerProvider:i}){return e==="openai_dot"||e==="paperclip_runner"&&i==="openai_dot"?a:e==="paperclip_runner"?n:s?gmt.has(e):!0}r(e5e,"isNewAgentAdapterAllowed");function bmt(){const{selectedCompanyId:e}=ps(),{appearance:s}=X_e(`${e}:new-agent`);return(0,t.jsx)(_N,{appearance:s,state:"sleepy",muted:!0,size:256,className:"size-48",trackingScope:"page"})}r(bmt,"AgentBasicsCharacter");function t5e({open:e,onClose:s,onContinue:n,initialAdapter:a="",onInvite:i}){const o=(0,m.useId)(),l=!!ed(),c=te({queryKey:M.instance.experimentalSettings,queryFn:jr.getExperimental,enabled:e,retry:!1}),[d,u]=(0,m.useState)(""),[h,p]=(0,m.useState)(a),[f,x]=(0,m.useState)("codex"),[g,v]=(0,m.useState)("name"),{data:y,isPending:k,error:w}=te({queryKey:M.adapters.all,queryFn:Ph.list,enabled:e}),N=(y??[]).filter(C=>C.loaded&&!C.disabled&&e5e(C.type,{cloud:l,nativeRunnerEnabled:c.data?.enableNativeRunner===!0})&&!["process","http"].includes(C.type)&&!Gm(C.type).comingSoon),S=N.some(C=>C.type===h);return(0,t.jsx)(qs,{open:e,onOpenChange:r(C=>{C||s()},"onOpenChange"),children:(0,t.jsxs)(Ws,{className:W("flex max-h-(--sz-calc-18) flex-col gap-0 overflow-hidden p-0 sm:max-w-(--sz-640px)",g==="name"&&"sm:max-w-(--sz-560px)"),children:[(0,t.jsxs)("div",{className:"flex items-center gap-2 px-6 py-5 text-xs text-muted-foreground","aria-label":"New agent progress",children:[(0,t.jsx)("span",{className:W(g==="name"&&"font-medium text-foreground"),children:"1. Name"}),(0,t.jsx)(An,{className:"size-3"}),(0,t.jsx)("span",{className:W(g==="adapter"&&"font-medium text-foreground"),children:"2. Adapter"})]}),(0,t.jsxs)("form",{className:"flex min-h-0 flex-col",onSubmit:r(C=>{C.preventDefault(),d.trim()&&(g==="name"?v("adapter"):S&&n({name:d.trim(),adapterType:h==="openai_dot"?"paperclip_runner":h,runnerProvider:h==="openai_dot"?"openai_dot":f}))},"onSubmit"),children:[(0,t.jsxs)("div",{className:"flex min-h-0 flex-col gap-7 overflow-y-auto px-6 pb-8 sm:px-10",children:[(0,t.jsxs)("div",{className:"flex flex-col items-center gap-4 text-center",children:[e&&(0,t.jsx)(bmt,{}),(0,t.jsxs)("div",{className:"space-y-2",children:[(0,t.jsx)(Qs,{className:"text-3xl font-semibold tracking-tight",children:g==="name"?"Meet your next agent":"Choose an adapter"}),(0,t.jsx)(mn,{className:"text-base",children:g==="name"?"Start with a name. Make them your own.":`How should ${d.trim()} work?`})]})]}),g==="name"?(0,t.jsxs)("div",{className:"space-y-2",children:[(0,t.jsx)("label",{htmlFor:o,className:"text-sm font-medium",children:"Agent name"}),(0,t.jsx)(dt,{id:o,autoFocus:!0,maxLength:100,placeholder:"e.g. Darnold",value:d,onChange:r(C=>u(C.target.value),"onChange"),className:"h-12 text-base"}),i&&(0,t.jsx)($,{type:"button",variant:"link",className:"px-0 text-muted-foreground",onClick:i,children:"Invite an external agent"})]}):(0,t.jsxs)("fieldset",{className:"space-y-4",children:[(0,t.jsx)("legend",{className:"sr-only",children:"Adapter"}),k&&(0,t.jsx)("p",{role:"status",className:"text-sm text-muted-foreground",children:"Loading adapters…"}),w&&(0,t.jsx)("p",{role:"alert",className:"text-sm text-destructive",children:w.message}),(0,t.jsx)("div",{className:W("grid grid-cols-2 gap-3",N.length!==4&&"sm:grid-cols-3"),children:N.map(C=>{const _=Gm(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)(B0,{type:C.type}),(0,t.jsx)("span",{className:"text-sm font-medium",children:_.label}),h===C.type&&(0,t.jsx)(cs,{className:"absolute right-2 top-2 size-3.5"})]})]},C.type)})}),S&&h==="paperclip_runner"&&(0,t.jsxs)("label",{className:"flex flex-col gap-2 text-sm font-medium",children:["Runner",(0,t.jsxs)("select",{className:"rounded-md border border-border bg-background px-3 py-2",value:f,onChange:r(C=>x(C.target.value),"onChange"),children:[(0,t.jsx)("option",{value:"codex",children:"Codex (app server)"}),(0,t.jsx)("option",{value:"claude",children:"Claude (ACPX)"}),(0,t.jsx)("option",{value:"grok",children:"Grok Build (ACPX)"}),(0,t.jsx)("option",{value:"opencode",children:"OpenCode"})]})]})]})]}),(0,t.jsxs)("div",{className:"flex justify-between gap-4 border-t border-border px-6 py-4",children:[(0,t.jsx)($,{type:"button",variant:"ghost",onClick:r(()=>g==="name"?s():v("name"),"onClick"),children:g==="name"?"Cancel":(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)(wl,{className:"size-4"}),"Back"]})}),(0,t.jsxs)($,{type:"submit",disabled:!d.trim()||g==="adapter"&&!S,children:[g==="name"?"Choose adapter":"Configure agent",(0,t.jsx)(fl,{className:"size-4"})]})]})]})]})})}r(t5e,"AgentBasicsDialog");var vmt={subscription:"Subscription",api:"API key",advanced:"Custom Gateway"};function ymt({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)(IS,{initial:!1,mode:"sync",children:(0,t.jsx)(Rl.span,{className:"absolute inset-0 flex items-center justify-center whitespace-nowrap",initial:{opacity:0,y:_re},animate:{opacity:1,y:0,transition:Kit},exit:{opacity:0,y:_re,transition:Qit},children:vmt[e]},e)})})}r(ymt,"CredentialTag");function jmt({source:e,mode:s,selected:n,onSelect:a,buttonRef:i,settling:o}){return(0,t.jsxs)("button",{ref:i,type:"button",role:"radio","aria-checked":n,onClick:a,className:W("flex min-w-0 flex-1 cursor-pointer flex-col items-center gap-1.5 self-stretch rounded-md border p-3","transition-(--tp-border-color-background-color) ease-(--motion-ease-standard)",o?"duration-(--motion-duration-slow)":"duration-(--motion-duration-fast)","outline-none focus-visible:ring-ring/50 focus-visible:ring-(length:--rad-3)",n?"border-foreground/40 bg-accent":"border-border bg-card hover:bg-accent/40"),children:[(0,t.jsx)("span",{className:"flex size-(--sz-30px) shrink-0 items-center justify-center",children:e.icon}),(0,t.jsx)("span",{className:"text-(length:--text-compact) font-medium text-foreground",children:e.label}),s?(0,t.jsx)(ymt,{mode:s}):(0,t.jsx)("span",{"aria-hidden":!0,className:"h-4"})]})}r(jmt,"ModelSourceTile");function s5e({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)(IS,{initial:!1,mode:"popLayout",children:u.map(h=>(0,t.jsx)(Rl.div,{layout:!0,transition:s_e,exit:{opacity:0,transition:tot},className:W("flex min-w-0",o?"w-(--sz-source-tile-two-up)":"flex-1"),children:(0,t.jsx)(jmt,{source:h,mode:h.credentialMode===void 0?s:h.credentialMode,selected:h.id===n,onSelect:r(()=>a(h.id),"onSelect"),settling:l,buttonRef:r(p=>{p?c.current.set(h.id,p):c.current.delete(h.id)},"buttonRef")})},h.id))})})}r(s5e,"ModelSourceTiles");var pD={subscription:"Use subscription instead",api:"Use API key instead"},wmt=["subscription","api"],hae={subscription:"api",api:"subscription"};function n5e({mode:e,onChange:s}){return(0,t.jsx)(kmt,{destination:hae[e],onClick:r(()=>s(hae[e]),"onClick"),modes:wmt})}r(n5e,"CredentialModeLink");function kmt({destination:e,onClick:s,modes:n}){return(0,t.jsxs)("button",{type:"button","aria-label":pD[e],onClick:s,className:W("group grid cursor-pointer px-3 py-2 text-left text-sm font-medium","rounded-md outline-none focus-visible:ring-ring/50 focus-visible:ring-(length:--rad-3)"),children:[n.map(a=>(0,t.jsx)("span",{"aria-hidden":!0,className:"invisible col-start-1 row-start-1 whitespace-nowrap",children:pD[a]},a)),(0,t.jsx)(IS,{initial:!1,mode:"sync",children:(0,t.jsx)(Rl.span,{className:W("col-start-1 row-start-1 justify-self-start whitespace-nowrap","underline decoration-muted-foreground/40 underline-offset-4","text-muted-foreground transition-colors","group-hover:text-foreground group-hover:decoration-foreground/40"),initial:{opacity:0},animate:{opacity:1,transition:wV},exit:{opacity:0,transition:Wit},children:pD[e]},e)})]})}r(kmt,"ModeLink");function qz({onBack:e,primaryLabel:s,primaryDisabled:n,loading:a,loadingLabel:i,primaryIcon:o,onPrimary:l}){const c=a&&i?i:s,d=o??(a?"spinner":"arrow");return(0,t.jsxs)("div",{className:"flex items-center justify-between pt-9",children:[e?(0,t.jsxs)($,{variant:"ghost",size:"lg",className:"rounded-full has-[>svg]:pl-4 has-[>svg]:pr-5",onClick:e,disabled:a,children:[(0,t.jsx)(wl,{className:"mr-1 size-3.5"}),"Back"]}):(0,t.jsx)("span",{}),(0,t.jsx)(Rl.div,{layout:!0,transition:Git,className:"min-w-0",children:(0,t.jsx)($,{size:"lg",className:"w-full rounded-full px-6",onClick:l,disabled:n||a,children:(0,t.jsxs)(Rl.span,{className:"flex items-center whitespace-nowrap",initial:{opacity:0},animate:{opacity:1},transition:Yit,children:[d==="spinner"?(0,t.jsx)(st,{className:"mr-1 size-4 animate-spin"}):null,c,d==="arrow"?(0,t.jsx)(fl,{className:"ml-1 size-3.5"}):null]},`${c}:${d}`)})})]})}r(qz,"FooterNav");function r5e({companyId:e,adapterType:s,environmentId:n,canLogin:a,localEnvironment:i=!1,onConnected:o,onDraftChanged:l,onBack:c,testConnection:d,testError:u,managedAccount:h,advancedConnection:p}){const f=te({queryKey:M.health,queryFn:Iu.get,enabled:i}),x=i&&(f.data?.localAiLoginSupported??f.data?.deploymentMode==="local_trusted"),g=(0,m.useRef)(0);(0,m.useEffect)(()=>()=>{g.current++},[]);const v=r(()=>{g.current++,Q(!1),C(!1),R(null),T("preparing")},"cancel"),[y,k]=(0,m.useState)(h?.initialMethod==="api_key"?"api":h?"subscription":null),[w,N]=(0,m.useState)(!1),[S,C]=(0,m.useState)(!!(p||h)),[_,R]=(0,m.useState)(null),[I,T]=(0,m.useState)("preparing"),E=(0,m.useRef)("ready"),[L,O]=(0,m.useState)(""),[P,Q]=(0,m.useState)(!1),[D,F]=(0,m.useState)(null),[z,K]=(0,m.useState)(null),U=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",G=s==="claude_local"?"anthropic":s==="grok_local"?"xai":"openai",se=ECe(e,q),Z=h?{...se,options:[],subscriptions:[],loading:!1}:se,[ie,J]=(0,m.useState)(null),re=Z.subscriptions.length?Z.subscriptions.find(Le=>Le.id===(ie??Z.subscriptions[0]?.id)):void 0,[oe,V]=(0,m.useState)(null),X=Z.options.find(Le=>Le.id===(oe??Z.options[0]?.id)),Y=h?{...Z.storedLogin,data:void 0,isPending:!1,isError:!1}:Z.storedLogin,ae=(0,m.useRef)(null),ne=y??(Z.subscriptions.length>0||s==="claude_local"&&!re&&Y.data?"subscription":Z.options.length?"api":"subscription"),ce=ne==="api"?"api_key":"subscription",he=h?.intent.connectionId&&(h.fixedMethod!==!1||h.initialMethod===ce),pe=h?{...h.intent,connectionId:he?h.intent.connectionId:void 0,name:he?h.intent.name:h.nameForMethod?.(ce)??h.intent.name}:void 0,ge=ZSe(e,pe??{provider:G,method:"subscription",name:`My ${U} subscription`,ownership:"personal",agentIds:[],allAgents:!0},!w&&x&&ne==="subscription"&&!re&&!Y.data),Ee=te({queryKey:M.agents.authSignal(e,s,n),queryFn:r(()=>_t.getAdapterAuthSignal(e,s,n??void 0),"queryFn"),retry:!1,enabled:!h&&!w});async function de(){if(P||h?.disabled)return;const Le=++g.current;Q(!0),F(null);try{if(h&&pe){if(ne==="subscription"&&!x)return;const Ae=ae.current??await(ne==="api"?Ll.create(e,{...pe,method:"api_key",apiKey:L.trim()}):ge.connect(pe));ae.current=Ae,O(""),Le===g.current&&h.onComplete({...Ae,method:ne==="api"?"api_key":"subscription"});return}let Ie=ne==="api"?X?X.aiConnection?{env:{},aiConnection:X.aiConnection}:{env:{[q]:X.binding}}:z??{env:{},credentials:{[q]:L.trim()}}:{...re?.aiConnection?{aiConnection:re.aiConnection}:{},env:re?.binding?{CODEX_HOME:re.binding}:{},...s==="claude_local"&&!re&&Y.data?{env:nk(),applyStoredClaudeLogin:!0}:{}};if(ne==="subscription"&&x&&!re&&!Y.data&&(ae.current??=await ge.connect(),Ie={env:{},aiConnection:{provider:G,method:"subscription",mode:"responsible_user"}}),Ie.credentials&&(await Ll.create(e,{provider:G,method:"api_key",name:`My ${U} API`,ownership:"personal",apiKey:Ie.credentials[q],agentIds:[],allAgents:!0}),Ie={env:{},aiConnection:{provider:G,method:"api_key",mode:"responsible_user"}}),Le!==g.current)return;ne==="api"&&(O(""),X||K(Ie));const ye=await d(Ie);if(Le!==g.current)return;ye?o(Ie):F("The provider did not respond. Check the connection and try again.")}catch(Ie){if(Le!==g.current)return;h&&O(""),F(Ie instanceof Error?Ie.message:"Could not connect to the provider.")}finally{Le===g.current&&Q(!1)}}r(de,"connect");const Ne=ne==="subscription"&&a&&n&&!re&&!Z.loading&&!Y.data&&(!!h||Ee.data?.status!=="present"||ie===""),le=r(Le=>{p&&Le===(w?"advanced":ne)||(l?.(),v(),N(Le==="advanced"),C(p?!0:S),ae.current=null,Le!=="advanced"&&k(Le),O(""),K(null),F(null))},"switchMode");return(0,t.jsxs)("div",{className:"min-w-0 max-w-full",children:[(0,t.jsx)(s5e,{label:p?"Connection type":"Connect your model provider",sources:p?[{id:"subscription",label:U,icon:(0,t.jsx)(B0,{type:s}),credentialMode:"subscription"},{id:"api",label:U,icon:(0,t.jsx)(B0,{type:s}),credentialMode:"api"},{id:"advanced",label:"Advanced",icon:(0,t.jsx)(WKe,{className:"size-6 text-muted-foreground"}),credentialMode:"advanced"}]:[{id:s,label:U,icon:(0,t.jsx)(B0,{type:s})}],mode:w?"advanced":ne,selectedId:p?w?"advanced":ne:S?s:null,collapsed:!p&&S,onSelect:r(Le=>{h?.disabled||(p?le(Le):C(!0))},"onSelect")}),!p&&(!S||h)&&!h?.fixedMethod&&(0,t.jsx)("div",{className:"-ml-3 mt-1",children:(0,t.jsx)(n5e,{mode:ne,onChange:le})}),w&&p?(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)("div",{className:"pt-5",children:p.content}),(0,t.jsx)(qz,{onBack:c,primaryLabel:"Use connection",primaryDisabled:!p.value,onPrimary:r(()=>{p.value&&o({env:{},aiConnection:p.value})},"onPrimary")})]}):(0,t.jsxs)(t.Fragment,{children:[!S&&Z.options.length>0&&(0,t.jsxs)("p",{className:"mt-2 text-sm text-muted-foreground",children:[Z.options.length," saved API"," ",Z.options.length===1?"key available":"keys available","."]}),ne==="subscription"&&Z.subscriptions.length>0&&(0,t.jsx)("div",{className:p?"pt-5":void 0,children:(0,t.jsx)(Ik,{options:Z.subscriptions,value:re?.id??"",onChange:r(Le=>{l?.(),J(Le)},"onChange"),loading:!1,error:!1,kind:"subscription",disabled:P})}),(0,t.jsx)(Rl.div,{initial:!1,animate:{height:S?"auto":0,opacity:S?1:0},transition:{height:Vd,opacity:NM},className:"overflow-hidden",children:S&&(0,t.jsx)("div",{className:"pt-5",children:ne==="api"?(0,t.jsxs)(SM,{instruction:Z.options.length?"Choose a saved API key or enter a new one":`Provide your ${U} API key to connect`,children:[(0,t.jsx)(Ik,{...Z,value:X?.id??"",disabled:P,onChange:r(Le=>{l?.(),V(Le),O(""),K(null),F(null)},"onChange")}),!X&&(0,t.jsx)(X3,{label:"API key",masked:!0,autoFocus:!0,value:L,placeholder:z?"Key entered. Retry the connection.":"Enter API key here",onChange:r(Le=>{l?.(),V(""),O(Le),K(null)},"onChange"),onSubmit:r(()=>{de()},"onSubmit"),disabled:P})]}):Ne?(0,t.jsx)(MV,{companyId:e,adapterType:s,environmentId:n,chrome:"onboarding",aiConnection:pe??{provider:G,method:"subscription",name:`My ${U} subscription`,ownership:"personal",agentIds:[],allAgents:!0},autoStart:!0,onStored:r(()=>{},"onStored"),onPromptReady:r(Le=>{R(Le),T(Ie=>Le?Ie==="preparing"?"ready":Ie:"preparing")},"onPromptReady"),onCodeSubmitted:r(()=>{E.current=I==="waiting"?"waiting":"ready",T("connecting")},"onCodeSubmitted"),onSubmitFailed:r(()=>{T(Le=>Le==="connecting"?E.current:Le)},"onSubmitFailed"),onConnected:r(Le=>{if(h){if(!Le){F("The login did not return a saved connection. Try again.");return}const ye=g.current;T("connecting"),Ll.loginResult(e,Le).then(Ae=>{ye===g.current&&h.onComplete({...Ae,method:"subscription"})}).catch(()=>{ye===g.current&&(T("ready"),F("Could not retrieve the saved connection. Go back and retry."))});return}const Ie={env:{},aiConnection:{provider:G,method:"subscription",mode:"responsible_user"}};K(Ie),o(Ie)},"onConnected")}):re?null:x&&!Y.data?(0,t.jsx)(SV,{adapterType:s,login:{...ge,retry:r(()=>{F(null),ge.retry()},"retry")}}):(0,t.jsx)("p",{className:"text-sm text-muted-foreground",children:Y.data?"Use your saved Claude subscription for this agent.":a?"Use the existing provider connection for this environment.":"This environment does not support browser sign-in. Choose a sign-in environment or connect with an API key."})})}),ne==="subscription"&&Y.isError&&(0,t.jsx)("p",{role:"alert",className:"mt-4 text-sm text-destructive",children:"Could not check your saved Claude subscription. Try again."}),D&&(0,t.jsx)("p",{role:"alert",className:"mt-4 text-sm text-destructive",children:u??D}),i&&f.isError&&(0,t.jsx)("p",{role:"alert",className:"mt-4 text-sm text-destructive",children:"Could not prepare sign-in. Reload this page to try again."}),(0,t.jsx)(qz,{onBack:r(()=>{S&&!p?v():c()},"onBack"),primaryLabel:S&&Ne?I==="waiting"?"Waiting for code":I==="connecting"?"Connecting":`Sign in to ${U}`:P?"Connecting":ne==="subscription"&&(Y.data||re)?"Use saved subscription":ne==="api"&&X?"Use saved API key":"Connect",primaryDisabled:h?.disabled||!!h&&ne==="subscription"&&!a&&!x||i&&f.isPending||ge.preparing||!!ge.error||ne==="subscription"&&x&&!re&&!Y.data&&ge.status!=="ready"||!h&&Ee.isPending||Z.loading||s==="claude_local"&&Y.isPending||!S&&!(ne==="subscription"&&re)||!!Ne&&(!_||I!=="ready")||ne==="api"&&!L.trim()&&!z&&!X,loading:P,primaryIcon:S&&Ne?I==="ready"?"none":"spinner":void 0,onPrimary:r(()=>{if(Ne){if(!_||I!=="ready")return;window.open(_,"_blank","noreferrer,noopener"),T("waiting")}else de()},"onPrimary")})]})]})}r(r5e,"AgentProviderConnection");function S5(e){return e.provider==="openrouter"||e.provider==="google"?(0,t.jsx)(Smt,{...e}):(0,t.jsx)(Nmt,{...e})}r(S5,"AiConnectionCredentialStep");function Nmt({companyId:e,provider:s,initialMethod:n,fixedMethod:a,connectionId:i,name:o,hideName:l,nameForMethod:c,ownership:d,agentIds:u,allAgents:h,environmentId:p,onComplete:f,onCancel:x,defaults:g,disabled:v}){const[y,k]=(0,m.useState)(o),[w,N]=(0,m.useState)(),S=kt(),C=te({queryKey:M.environments.list(e),queryFn:r(()=>Fi.list(e),"queryFn")}),_=te({queryKey:M.environments.capabilities(e),queryFn:r(()=>Fi.capabilities(e),"queryFn")}),R=te({queryKey:M.instance.settings,queryFn:jr.get}),I=te({queryKey:M.instance.experimentalSettings,queryFn:jr.getExperimental}),T=te({queryKey:M.instance.generalSettings,queryFn:jr.getGeneral}),E=LV(T.data?.executionMode,C.data??[]);let L=null,O;try{L=E.forced?E.kubernetesEnvironment?.id??null:wN({agentDefaultEnvironmentId:p??w,instanceDefaultEnvironmentId:R.data?.defaultEnvironmentId,localDefaultEnvironmentId:NN(C.data),managedSandboxOnly:I.data?.enableManagedSandboxOnly,managedSandboxEnvironmentId:kN(C.data),visibleEnvironmentIds:C.data?.map(q=>q.id)})}catch(q){O=q instanceof Error?q.message:"Could not resolve the sign-in environment."}const P=(C.data??[]).filter(q=>q.status==="active"&&(q.driver==="local"||q.driver==="sandbox"&&typeof q.config.provider=="string"&&_.data?.sandboxProviders?.[q.config.provider]?.supportsLoginPty===!0));!E.forced&&!p&&!w&&!P.some(q=>q.id===L)&&(L=P[0]?.id??null);const Q=C.data?.find(q=>q.id===L),D=typeof Q?.config.provider=="string"?Q.config.provider:"",F=Q?.driver==="sandbox"&&_.data?.sandboxProviders?.[D]?.supportsLoginPty===!0,z=[C,_,R,I,T].some(q=>q.isPending),K=O??[C,_,R,I,T].find(q=>q.error)?.error?.message,U={provider:s,method:"subscription",name:y,ownership:d,agentIds:u,allAgents:h,connectionId:i};return(0,t.jsxs)("div",{className:"mx-auto w-full min-w-0 max-w-xl space-y-6",children:[!l&&(0,t.jsxs)("label",{className:"block space-y-2 text-sm",children:["Connection name",(0,t.jsx)(dt,{value:y,onChange:r(q=>k(q.target.value),"onChange"),disabled:!!i})]}),!p&&!E.forced&&P.length>1&&(0,t.jsxs)(Ca,{value:L??"",onValueChange:N,children:[(0,t.jsx)(Na,{"aria-label":"Sign-in environment",children:(0,t.jsx)(Sa,{placeholder:"Sign-in environment"})}),(0,t.jsx)(_a,{children:P.map(q=>(0,t.jsx)(un,{value:q.id,children:q.name},q.id))})]}),K&&(0,t.jsx)("p",{role:"alert",className:"text-sm text-destructive",children:K}),g,z?(0,t.jsx)("p",{role:"status",className:"text-sm text-muted-foreground",children:"Preparing sign-in…"}):(0,t.jsx)(r5e,{companyId:e,adapterType:s==="anthropic"?"claude_local":s==="xai"?"grok_local":"codex_local",environmentId:L,canLogin:F,localEnvironment:Q?.driver==="local",onBack:x,onConnected:r(()=>{},"onConnected"),testConnection:r(async()=>!1,"testConnection"),managedAccount:{intent:U,nameForMethod:c,initialMethod:n,fixedMethod:a??!!i,disabled:v||z||!!K||!y.trim(),onComplete:r(q=>{S.invalidateQueries({queryKey:["ai-connections",e]}),S.invalidateQueries({queryKey:["tools"]}),f(q)},"onComplete")}},L??"local")]})}r(Nmt,"SubscriptionConnectionStep");function Smt({companyId:e,provider:s,connectionId:n,name:a,hideName:i,nameForMethod:o,ownership:l,agentIds:c,allAgents:d,onComplete:u,onCancel:h,defaults:p,disabled:f}){const[x,g]=(0,m.useState)(a),[v,y]=(0,m.useState)(""),k=kt(),w=je({mutationFn:r(()=>Ll.create(e,{provider:s,method:"api_key",name:n?x:o?.("api_key")??x,ownership:l,agentIds:c,allAgents:d,connectionId:n,apiKey:v}),"mutationFn"),onSuccess:r(N=>{k.invalidateQueries({queryKey:["ai-connections",e]}),k.invalidateQueries({queryKey:["tools"]}),u({...N,method:"api_key"})},"onSuccess"),onSettled:r(()=>y(""),"onSettled")});return(0,t.jsxs)("div",{className:"mx-auto w-full min-w-0 max-w-xl space-y-4",children:[!i&&(0,t.jsxs)("label",{className:"block space-y-2 text-sm",children:["Connection name",(0,t.jsx)(dt,{value:x,onChange:r(N=>g(N.target.value),"onChange"),disabled:!!n})]}),w.error&&(0,t.jsx)("p",{role:"alert",className:"text-sm text-destructive",children:w.error.message}),(0,t.jsx)(a_e,{providerName:s==="google"?"Google":"OpenRouter",value:v,onChange:y,onSubmit:r(()=>w.mutate(),"onSubmit"),disabled:f||w.isPending,placeholder:"Enter API key here",autoFocus:!0}),p,(0,t.jsxs)("div",{className:"flex justify-between gap-2",children:[(0,t.jsx)($,{variant:"ghost",onClick:h,children:"Cancel"}),(0,t.jsx)($,{disabled:f||!x.trim()||!v.trim()||w.isPending,onClick:r(()=>w.mutate(),"onClick"),children:w.isPending?"Connecting…":"Connect"})]})]})}r(Smt,"ApiKeyConnectionStep");var Cmt=null;function cw(){const e=(0,m.useContext)(h3),{data:s,isFetched:n,isError:a}=te({queryKey:M.instance.experimentalSettings,queryFn:r(()=>jr.getExperimental(),"queryFn"),enabled:e!=null},e??(Cmt??=new rS));return e?{enabled:!a&&s?.enableChatConnectors===!0,githubEnabled:!a&&s?.enableGitHubReviewBots===!0,loaded:n}:{enabled:!1,githubEnabled:!1,loaded:!0}}r(cw,"useChatConnectorsEnabled");function Zp(e,s,n){return e==="agentmail"||(e==="github"||e==="github-code-review-bot"?n:s)}r(Zp,"chatProviderVisible");var _mt=new RegExp(`\\b(${["mcp","server","profile","policy","gateway","transport","stdio","endpoint"].join("|")})s?\\b`,"gi");function a5e(e){return e.replace(_mt,"").replace(/\s{2,}/g," ").replace(/\s+([.,])/g,"$1").trim()}r(a5e,"sanitizeProsumerCopy");var Amt={zapier:{tagline:"Reach 9,000+ apps your team already uses.",short:"Reach 9,000+ apps from your agents."},github:{tagline:"Read code and pull requests, comment on issues.",short:"Read code and pull requests, comment on issues."},slack:{tagline:"Send and read messages in your team's channels.",short:"Send and read messages in your channels."},notion:{tagline:"Read and update pages in your workspace.",short:"Read and update pages in your workspace."},railway:{tagline:"Inspect services, read logs, and manage deployments.",short:"Connect Railway for deployments, logs, and container access."},posthog:{tagline:"Explore product usage, errors, flags, and experiments.",short:"Sign in with PostHog. Project pinning and access controls are optional."},gauge:{tagline:"Track your brand in AI answers and run content workflows.",short:"Sign in with Gauge and pick an organization. API keys are optional."},neon:{tagline:"Manage Postgres projects, branches, and queries.",short:"Sign in with Neon. Project pinning and read-only mode are optional."},superagent:{tagline:"Review security findings and run red-team checks.",short:"Connect with a Superagent API key. Billable and destructive tools stay under action policies."},linear:{tagline:"Create, update and read tickets.",short:"Create, update and read tickets."},"google-sheets":{tagline:"Read and update selected spreadsheets.",short:"Read spreadsheets or update the files you choose."},gmail:{tagline:"Read mail and create drafts for your review.",short:"Read mail and create drafts for your review."},"google-drive":{tagline:"Find, read, and create files in Drive.",short:"Find, read, and create files in Drive."},"google-docs":{tagline:"Read and update documents.",short:"Read and update documents."},"google-slides":{tagline:"Read and update presentations.",short:"Read and update presentations."},"google-calendar":{tagline:"Review calendars and manage events.",short:"Review calendars and manage events."},"google-chat":{tagline:"Read conversations and send messages.",short:"Read conversations and send messages."},"google-people":{tagline:"Look up contacts and people in your directory.",short:"Look up contacts and people in your directory."},"google-workspace-search":{tagline:"Search across your Google workspace.",short:"Search across your Google workspace."},hubspot:{tagline:"Look up contacts and update deal stages.",short:"Look up contacts and update deal stages."},intercom:{tagline:"Read and reply to customer conversations.",short:"Read and reply to customer conversations."},figma:{tagline:"Read files and post comments on frames.",short:"Read files and post comments on frames."},stripe:{tagline:"Read customers, invoices, and payouts.",short:"Read customers, invoices, and payouts."},context7:{tagline:"Look up up-to-date docs for your libraries.",short:"Look up up-to-date docs for your libraries."}},Imt={tagline:"Give your agents access to this app.",short:"Give your agents access to this app."};function i5e(e,s){const n=Amt[e];if(n)return n;if(s){const a=a5e(s);if(a)return{tagline:a,short:a}}return Imt}r(i5e,"appCopyFor");function pae(e,s,n){return n<=1?`Your ${e} key`:a5e(s)||`Your ${e} key`}r(pae,"credentialFieldLabel");var Tmt=1500;function Z0(e=Tmt){const[s,n]=(0,m.useState)("idle"),a=(0,m.useRef)(null),i=(0,m.useRef)(0);(0,m.useEffect)(()=>()=>{a.current!==null&&window.clearTimeout(a.current)},[]);const o=(0,m.useCallback)(async l=>{const c=++i.current;let d="copied";try{await wa(l)}catch{d="failed"}return i.current!==c||(n(d),a.current!==null&&window.clearTimeout(a.current),a.current=window.setTimeout(()=>{i.current===c&&(n("idle"),a.current=null)},e)),d},[e]);return{status:s,copied:s==="copied",failed:s==="failed",copy:o}}r(Z0,"useCopyAction");function TM(){const e=bd()?.pushToast;return(0,m.useCallback)(async(s,n="Copied")=>{try{return await wa(s),e?.({title:n,tone:"success",dedupeKey:`copy:${n}`}),!0}catch{return e?.({title:"Couldn’t copy to clipboard",body:"Select and copy the value manually.",tone:"error",dedupeKey:"copy-failed"}),!1}},[e])}r(TM,"useCopyToast");var Rmt="/cloud/connections/handoff",Emt="/cloud/connections/reauth",EE="paperclip.cloud-oauth-handoff.v1",Ux=class extends Error{static{r(this,"OAuthHandoffError")}code;constructor(e,s){super(e),this.code=s,this.name="OAuthHandoffError"}};function DV(e){if(e===void 0)return null;if(!e||typeof e!="object"||Array.isArray(e))throw new Ux("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 Ux("Paperclip Cloud returned an invalid sign-in handoff.","invalid_handoff");return{kind:"paperclip_cloud",session:s.session}}r(DV,"parseHandoff");function Lmt(e,s){return e===404||s==="SESSION_NOT_AVAILABLE"?new Ux("This sign-in expired. Start the connection again.","expired"):e===401||e===403?new Ux("Paperclip Cloud could not authorize this connection for your account.","forbidden"):new Ux("Paperclip Cloud couldn’t prepare secure sign-in. Try again.","unavailable")}r(Lmt,"handoffFailure");async function Mmt(e,s){const n=s.request??fetch;let a,i;for(let o=0;o<2;o+=1)try{if(a=await n(Rmt,{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 Ux(i instanceof Error?i.message:"Paperclip Cloud couldn’t prepare secure sign-in. Try again.","unavailable")}r(Mmt,"postCloudHandoff");function Pmt(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!==Emt||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(Pmt,"exactReauthenticationTarget");async function AN(e,s={}){const n=DV(e.handoff);if(!n){const l=iE(e.authorizationUrl);if(!l.ok)throw new Ux(l.message,"invalid_handoff");return{kind:"authorization",url:l.url,host:l.host}}const a=await Mmt(n.session,s),i=await a.json().catch(()=>null);if(!a.ok){if(i?.error==="RECENT_LOGIN_REQUIRED"){const l=Pmt(i.reauthenticationUrl,n.session);if(l)return l}throw Lmt(a.status,i?.error)}const o=iE(typeof i?.authorizationUrl=="string"?i.authorizationUrl:void 0);if(!o.ok)throw new Ux("Paperclip Cloud returned an invalid provider sign-in address.","invalid_handoff");return{kind:"authorization",url:o.url,host:o.host}}r(AN,"prepareOAuthNavigation");function C5(e,s=window.sessionStorage){const n=DV({kind:"paperclip_cloud",session:e});if(!n)throw new Ux("Paperclip Cloud returned an invalid sign-in handoff.","invalid_handoff");const a={version:1,session:n.session,savedAt:Date.now()};s.setItem(EE,JSON.stringify(a))}r(C5,"savePendingCloudHandoff");function Dmt(e=window.sessionStorage){const s=e.getItem(EE);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 DV({kind:"paperclip_cloud",session:n.session})}catch{return e.removeItem(EE),null}}r(Dmt,"readPendingCloudHandoff");function fae(e=window.sessionStorage){e.removeItem(EE)}r(fae,"clearPendingCloudHandoff");function RM(e){return!!(e&&ube({...e,methods:e.methods.filter(s=>(s.purpose??"tool")!=="channel"&&s.transport!=="chat_sdk")}))}r(RM,"appSupportsToolCatalogSetup");var $mt=UOe.filter(e=>Bbe(e).some(s=>A0(s))).map(e=>e.slug);function Omt(e){return $mt.some(s=>s===e)}r(Omt,"isMcpDirectOAuthConnectSlug");function _5(e,s){const n=new URLSearchParams({source:e});return s&&n.set("intent",s),`/apps/connect?${n.toString()}`}r(_5,"appSourceConnectHref");function xae(e,s){return`/apps/connect?${new URLSearchParams({source:e,resume:s}).toString()}`}r(xae,"appSourceResumeHref");function fD(e){return e?`/apps/vercel-connect?${new URLSearchParams({source:e}).toString()}`:"/apps/vercel-connect"}r(fD,"vercelConnectSourceHref");function Bmt(e){return e.serviceSlug??e.appKey??e.sourceSlug??void 0}r(Bmt,"resolveAppsConnectRouteKey");function Fmt(e,{chatConnectorsEnabled:s=!1,githubReviewBotsEnabled:n=!1}={}){if(e.get("byo")==="1")return!!(e.get("reconnect")?.trim()&&e.get("applicationId")?.trim()&&e.get("link")?.trim());const a=e.get("source")??"";if(["google-ai","gateway"].includes(a)||/^ai-router-(?:[a-f0-9]{2})+$/.test(a))return!0;const i=ZN(a),o=a==="github-code-review-bot"?n:s;return!o&&i?.methods.some(l=>l.transport==="chat_sdk")&&!i.methods.some(l=>(l.purpose??"tool")!=="channel"&&l.transport!=="chat_sdk")?!1:fj(a)&&(e.get("reconnect")?.trim()||e.get("resume")?.trim())?!0:a==="agentmail"||o?ube(i):RM(i)}r(Fmt,"canEnterAppsConnect");var xD=" for the organization",zmt=" for the company";function gae(e,s){const n=e.trim();if(s!=="organization")return n;const a=n.toLocaleLowerCase();return a.endsWith(xD)?n:a.endsWith(zmt)?`${n.slice(0,n.length-16).trimEnd()}${xD}`:`${n}${xD}`}r(gae,"connectionNameForGrantKind");function qmt(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(qmt,"grantStatusLabel");function Umt(e){switch(e){case"active":return"connected";case"needs_reauthorization":case"expired":return"attention";case"revoked":return"inactive";default:return"missing"}}r(Umt,"grantStatusTone");function Kmt(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(Kmt,"grantAccountLabel");function Qmt(e){return new Set((e?.members??[]).filter(s=>s.subjectType==="user").map(s=>s.subjectId))}r(Qmt,"audienceUserIds");function Wmt(e){return e.find(s=>s.kind==="organization"&&s.isDefault)??e.find(s=>s.kind==="organization")??null}r(Wmt,"organizationGrant");function Hmt(e,s){return s?e.find(n=>n.kind==="user"&&n.subjectUserId===s)??null:null}r(Hmt,"personalGrantFor");function Vmt(e,s){if(!s)return null;const n=e.find(a=>a.userId===s);return n&&(n.name?.trim()||n.email?.trim())||null}r(Vmt,"memberLabel");var bae=0;function Uz(){return bae+=1,{id:`header-${bae}`,name:"",value:""}}r(Uz,"newCustomHeaderRow");function x_(e){try{return new URL(e).host||null}catch{return null}}r(x_,"endpointHost");function Gmt(e=window.location.origin,s){if(s)return s;const n=new URL("/api/tools/oauth/callback",e),a=n.hostname.toLowerCase().replace(/^\[|\]$/g,"");return n.protocol==="http:"&&(a==="127.0.0.1"||a==="::1")&&(n.hostname="localhost"),n.toString()}r(Gmt,"oauthCallbackUrlForBrowser");function gD(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(gD,"defaultGenericMcpName");function vae(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(vae,"genericConnectGuidance");function o5e(e){const s=new Set;for(const n of e){const a=n.name.trim();if(!a&&!n.value.trim())continue;const i=kBe(a);if(!i.ok)return Zee(a,i.reason);const o=gBe(n.value);if(!o.ok)return Zee(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(o5e,"customHeaderError");function Ymt(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(Ymt,"genericConnectPayload");function Zmt(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&&o5e(e.headers)===null:!0:!1}r(Zmt,"canSubmitGenericConnect");function IN(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(IN,"installStateFrom");function l5e(e,s){return e.onAll||e.agentIds.has(s)}r(l5e,"isAgentInstalled");function c5e(e,s){return s.onAll?[{targetType:"company",targetId:e}]:[...s.agentIds].map(n=>({targetType:"agent",targetId:n}))}r(c5e,"installPayload");var Jmt="Has access — tick to load its tools into this agent's context.";function d5e(e){return`paperclip.connector-enrollment-access:${e}`}r(d5e,"enrollmentAccessStorageKey");function Xmt(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(Xmt,"validEnrollmentAccessState");function eht(e,s,n){try{window.sessionStorage.setItem(d5e(s),JSON.stringify({...n,companyId:e}))}catch{}}r(eht,"saveEnrollmentAccessState");function tht(e){const s=d5e(e);try{const n=window.sessionStorage.getItem(s);if(window.sessionStorage.removeItem(s),!n)return null;const a=JSON.parse(n);return Xmt(a)?a:null}catch{return null}}r(tht,"consumeEnrollmentAccessState");function yae(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(yae,"githubRecoveryUrl");function jae(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(jae,"oauthCallbackErrorMessage");var sht={key:"setup",success:"complete"};function wae(e){return e.requestedAppKey||e.hasPrefilledLink||e.zapierSource?"key":"gallery"}r(wae,"requestedConnectionInitialStep");function nht(e){const s=e.galleryApps.find(a=>a.slug===e.requestedAppKey);if(s)return s;if(u5e({requestedAppKey:e.requestedAppKey,resumeConnection:e.resumeConnection,resumeApplication:e.resumeApplication,completedResumeConnectionId:e.completedResumeConnectionId}))return fj(e.requestedAppKey);if(!e.reconnectConnection)return null;const n=e.applications.find(a=>a.id===e.reconnectConnection?.applicationId);return vf(n)!==e.requestedAppKey?null:fj(e.requestedAppKey)}r(nht,"requestedConnectionEntry");function u5e(e){const{requestedAppKey:s,resumeConnection:n,resumeApplication:a,completedResumeConnectionId:i}=e;return!!(n&&(n.status==="draft"||n.status==="active"&&n.id===i)&&a&&n.applicationId===a.id&&n.companyId===a.companyId&&vf(a)===s&&pu(n)===s)}r(u5e,"retainedResumeMatches");function rht(e){return!e.reconnectConnection||!e.reconnectApplication||e.reconnectConnection.applicationId!==e.reconnectApplication.id?!1:e.requestedAppKey?vf(e.reconnectApplication)===e.requestedAppKey:e.byo&&e.applicationId===e.reconnectApplication.id}r(rht,"retainedReconnectMatches");function aht(e){return e.credentialSource==="vercel_connect"&&!e.available&&!e.retainedReconnectMatches}r(aht,"isVercelConnectUnavailable");function iht(e){return e.available===!1&&!(e.reconnectConnectionId&&e.reconnectSourceMatches)}r(iht,"isConnectionDefinitionUnavailable");function oht(e){return!e.hasRequestedEntry||e.supportedMethodCount===0||e.unsupportedOAuth||e.vercelUnavailable||e.definitionUnavailable?e.reconnectConnectionId?"reconnect_unavailable":"fallback":"ready"}r(oht,"requestedConnectionSetupResolution");function kae(e,s,n,a){const i=sht[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(kae,"appConnectHref");function DI(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(DI,"withConnectionIntent");var Nae=["Pick app","Add your key"],Sae={gallery:0,key:1},lht={key:0},cht=["Add MCP URL"],dht=["Sign in"];function bD(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(bD,"defaultGrantKindFor");function uht(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(uht,"configuredAgentIdentity");function EC(e,s){const n=typeof s=="string"?s:s?.key;return e?.slug==="google-sheets"&&n==="local"}r(EC,"isGoogleSheetsRobotMethod");function $2(e){return e?Object.fromEntries([...e.tenantFields??[],...e.extensionFields??[]].filter(s=>s.defaultValue!==void 0).map(s=>[s.key,s.defaultValue])):{}}r($2,"defaultMethodConfig");function O1(e,s){if(!e)return[];const n=sA(e);return s==="vercel_connect"?n.filter(a=>!!a.credentialSources?.vercelConnect):n}r(O1,"connectionMethodsForCredentialSource");function sA(e){return Bbe(e).filter(s=>(s.purpose??"tool")!=="channel")}r(sA,"availableToolConnectionMethods");function $I(e,s){const n=sA(e);return s?n.find(a=>a.key===s)??null:UQ(n)}r($I,"availableToolConnectionMethod");function Ek(e){return UQ(e)}r(Ek,"recommendedSetupConnectionMethod");function Cae(e){return Ek(e?e.methods.filter(s=>(s.purpose??"tool")==="tool"&&(s.oauthStrategy==="paperclip_cloud_connector"||s.oauthStrategy==="paperclip_id_connector")):[])}r(Cae,"recommendedManagedConnectorMethod");function _ae(e){if(!e)return!1;const s=sA(e),n=s.length===1?s[0]:null;return!!(n&&A0(n)&&!QOe(n))}r(_ae,"canUseAutomaticOAuthFastPath");function Aae(e){if(!e)return null;const s=sA(e),n=s.length===1?s[0]:null;return n&&A0(n)?n:null}r(Aae,"automaticOAuthMethod");function mht(e){const s=e.metadata;if(!s)return null;const n=s.sourceTemplateKey??s.galleryKey;return typeof n=="string"?n:null}r(mht,"appSourceSlug");function hht(e){const s=e.config?.sourceTemplateKey??e.transportConfig.sourceTemplateKey;return typeof s=="string"?s:null}r(hht,"connectionSourceSlug");function Iae(e,s,n,a={}){if(!e)return null;const i=new Set(s.filter(o=>o.status!=="archived"&&mht(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)||hht(o)===e;return o.status!=="archived"&&(!a.draftOnly||o.status==="draft")&&o.authKind==="oauth"&&l})??null}r(Iae,"reusableOAuthConnection");function m5e(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(m5e,"readConnectionIntentOAuthOutcome");function ES(e={}){const[s]=hi(),n=ga(),{selectedCompanyId:a}=ps(),i=MH(),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&&s_(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||s_(l)||q6(l))),h=te({queryKey:["tools","connection",d],queryFn:r(()=>ts.getConnection(d),"queryFn"),enabled:u}),p=l||h.data?.config?.sourceTemplateKey,f=s.get("method")||h.data?.config?.connectionMethodKey;if(u&&h.isPending)return(0,t.jsx)("p",{className:"p-6 text-sm text-muted-foreground",children:"Loading connection…"});if(u&&h.isError)return(0,t.jsxs)("div",{role:"alert",className:"space-y-3 p-6",children:[(0,t.jsx)("p",{children:"Could not load this connection. Your saved access and credentials have not changed."}),(0,t.jsx)($,{variant:"outline",onClick:r(()=>{h.refetch()},"onClick"),children:"Try again"})]});if(q6(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"&&s_(p)&&(!f||HT(p,f))){const x=$be(p,s.get("targetToolkit"));return(0,t.jsx)(Let,{...e,upstreamServiceName:e.upstreamServiceName??x?.name,interactionId:o,providerId:p,connection:h.data},`${o||"page"}:${p}`)}return(0,t.jsx)(pht,{...e})}r(ES,"ConnectionSetupFlow");function pht({additionalSettings:e,connectionSettings:s,additionalSettingsValid:n=!0,byoOnly:a=!1,credentialSource:i="paperclip_vault",host:o="page",serviceSlug:l,requestedAgentId:c,interactionId:d,forceNewConnection:u=!1,existingConnections:h=[],configuredConnection:p,onUseExisting:f,onComplete:x,onOAuthDeclined:g,aiConnection:v,requiredAiOwnership:y,onPhaseChange:k,onCancel:w,renderCredentialStep:N}={}){const S=kt(),C=Yn(),_=(0,m.useCallback)((ot,ys)=>{o==="page"&&(ys?C(ot,ys):C(ot))},[o,C]),R=ga(),{selectedCompany:I,selectedCompanyId:T}=ps(),{enabled:E,githubEnabled:L}=cw(),{enabled:O}=MH(),{setBreadcrumbs:P}=Wn(),{pushToast:Q}=Ii(),[D]=hi(),F=d?.trim()||D.get("intent")?.trim()||null,z=R.appKey??D.get("appKey")??void 0,K=D.get("source")?.trim()||null,U=u||D.get("new")==="1",q=D.get("stage")?.trim()||null,G=D.get("method")?.trim()||null,se=D.get("resume")?.trim()||null,Z=D.get("oauth"),ie=D.get("code"),J=yae(D.get("installation_url")),re=yae(D.get("management_url")),oe=p?.id??(D.get("reconnect")?.trim()||null),V=D.get("identity")==="user"?"user":D.get("identity")==="organization"?"organization":null,X=i==="vercel_connect",Y=l??K,ae=i==="paperclip_vault"&&Omt(Y)?Y:null,ne=Bmt({serviceSlug:l,appKey:z,sourceSlug:K}),ce=(l??K??z)==="zapier",he=ce?void 0:ne,pe=!!p||o==="page"&&(a||D.get("byo")==="1"),[ge]=(0,m.useState)(()=>o==="page"&&D.get("cloud_connector")==="enrolled"&&he?tht(he):null),[Ee]=(0,m.useState)(()=>{const ot=D.get("link")?.trim()??"";return{link:/^https?:\/\//i.test(ot)?ot:"",name:p?.name??D.get("name")?.trim()??"",applicationId:p?.applicationId??(D.get("applicationId")?.trim()||void 0)}}),[de,Ne]=(0,m.useState)(()=>wae({requestedAppKey:he,routeStage:q,resumeConnectionId:se,hasPrefilledLink:!!Ee.link,zapierSource:ce})),[le,Le]=(0,m.useState)(null),[Ie,ye]=(0,m.useState)(""),[Ae,Qe]=(0,m.useState)(Ee.link),[ue,Be]=(0,m.useState)(Ee.name||(ce?"Zapier":"")),[ft,gt]=(0,m.useState)(!1),[Xe,Fe]=(0,m.useState)(""),[at,Tt]=(0,m.useState)("auto"),[Dt,Ot]=(0,m.useState)(()=>[Uz()]),[rt,Pe]=(0,m.useState)(""),[De,ht]=(0,m.useState)(""),[Ft,Et]=(0,m.useState)(!1),[ct,qe]=(0,m.useState)(null),[Oe,Re]=(0,m.useState)(!1),[Ve,xe]=(0,m.useState)({}),[Ge,vt]=(0,m.useState)(""),[Ss,lt]=(0,m.useState)(""),[zs,We]=(0,m.useState)(""),[fe,Ye]=(0,m.useState)(v&&v.mode!=="responsible_user"?`ai-${v.method}`:""),[bt,Wt]=(0,m.useState)(null),[ut,$t]=(0,m.useState)({}),[$e,pt]=(0,m.useState)(""),[Gt,be]=(0,m.useState)(null),[fs,vn]=(0,m.useState)(null),[Ls,Bs]=(0,m.useState)({}),[kr,ds]=(0,m.useState)("all"),[os,Se]=(0,m.useState)(new Set),[St,ze]=(0,m.useState)(()=>new Set(ge?.agentIds??(c?[c]:[]))),[At,Ut]=(0,m.useState)(ge?.grantKind??V??(c?"user":"organization")),[It,rs]=(0,m.useState)(ge?.installChoice??(c?"specific":"all")),bs=!!(se&&(Z==="failed"||Z==="denied")),[$s,Os]=(0,m.useState)(bs?"error":"entry"),[Tn,ks]=(0,m.useState)(()=>bs?jae(Z,ie):null),[Hn,Jt]=(0,m.useState)(null),Vs=(0,m.useRef)(!1),Nn=(0,m.useRef)(!1),Pt=(0,m.useRef)(null),Xt=(0,m.useRef)(null),[Zs,Ns]=(0,m.useState)(null),[Js,cn]=(0,m.useState)(null),hr=(0,m.useRef)(null),[Vn,Kr]=(0,m.useState)(null),[Er,Cr]=(0,m.useState)(null),Ln=(0,m.useRef)(null),[ur,Or]=(0,m.useState)(h.length>0&&!!f),[Qr,ea]=(0,m.useState)(null),[or,Ir]=(0,m.useState)(null),[xt,Ze]=(0,m.useState)(null),es=(0,m.useCallback)(()=>{o!=="dialog"||hr.current?.closed===!1||(hr.current=window.open("about:blank","paperclip-connection-oauth","popup,width=720,height=760,resizable=yes,scrollbars=yes"))},[o]),ms=(0,m.useCallback)(ot=>{if(o!=="dialog"){sh(ot);return}Cr(ot);const ys=hr.current;if(!ys||ys.closed){Os("error"),ks("Paperclip couldn’t open the sign-in window. Open sign-in in a new tab to continue."),k?.("needs_retry");return}ys.location.assign(ot),ys.focus()},[o,k]),Is=(0,m.useCallback)(()=>{hr.current=null,ks(null),Os("redirecting"),k?.("authorizing")},[k]);(0,m.useEffect)(()=>{if(o!=="dialog"||$s!=="redirecting")return;const ot=window.setInterval(()=>{hr.current?.closed&&(Os("error"),ks("The sign-in window closed. If authorization did not finish, try again."),Cr(null),k?.("needs_retry"))},1e3);return()=>window.clearInterval(ot)},[o,$s,k]);const ss=(0,m.useCallback)(async ot=>{Ln.current?.abort();const ys=new AbortController;Ln.current=ys;try{const kn=await AN(ot,{signal:ys.signal});if(kn.kind==="reauthentication"){const In=o==="dialog"?hr.current:window;if(!In||In.closed||!ot.handoff)throw new Error("Paperclip couldn’t preserve this sign-in while refreshing your account.");C5(ot.handoff.session,In.sessionStorage),Os("starting")}else Jt(kn.host),Os("redirecting");ms(kn.url)}catch(kn){if(ys.signal.aborted)return;Os("error"),ks(kn instanceof Error?kn.message:"Paperclip couldn’t start secure sign-in. Try again."),k?.("needs_retry")}finally{Ln.current===ys&&(Ln.current=null)}},[o,k,ms]);(0,m.useEffect)(()=>()=>Ln.current?.abort(),[]),(0,m.useEffect)(()=>{if(o!=="dialog"||!F)return;const ot=r(ys=>{const kn=m5e(ys,window.location.origin,F);if(kn==="connected"){Os("entry"),Cr(null),x?.({resolvedByCallback:!0});return}if(kn==="declined"){Os("error"),ks("Authorization was cancelled. You can try again."),k?.("needs_retry");return}kn==="failed"&&(Os("error"),ks("Authorization did not complete. Try again when you’re ready."))},"receiveOAuthOutcome");return window.addEventListener("message",ot),()=>window.removeEventListener("message",ot)},[F,o,x,g]),(0,m.useEffect)(()=>{if(o!=="dialog"||F||!Vn)return;let ot=!1,ys=!1;const kn=window.setInterval(async()=>{if(ys||ot)return;const In=hr.current;if(!In||In.closed){Kr(null),Os("error"),ks("The sign-in window closed. Try again to finish connecting GitHub.");return}let ar;try{ar=new URL(In.location.href)}catch{return}if(!(ar.origin!==window.location.origin||!ar.pathname.includes(Vn))){if(ar.searchParams.has("oauth")){Kr(null),Os("error"),ks("Authorization did not complete. Finish setup in the sign-in window or try again.");return}if(ar.searchParams.get("success")==="1"){ys=!0;try{const en=await ts.getConnection(Vn);!ot&&en.status==="active"&&(Kr(null),In.close(),x?.({connectionId:en.id}))}catch{ot||(Kr(null),Os("error"),ks("Could not confirm the connection. Try again."))}finally{ys=!1}}}},1e3);return()=>{ot=!0,window.clearInterval(kn)}},[F,Vn,o,x]);const ws=r(()=>{Tt("auto"),Ot([Uz()]),Pe(""),ht(""),Et(!1),qe(null),Re(!1)},"resetGenericAuthState"),yn=r(ot=>{if(o==="page"&&!F&&i==="paperclip_vault"&&s_(ot.slug)){_(`/apps/connect?source=${ot.slug}`);return}if(ot.slug==="zapier"){Le(null),ye(""),Qe(""),Be("Zapier"),gt(!1),Fe(""),ws(),xe({}),vn(null),Ne("key"),_(DI("/apps/connect?source=zapier",F));return}if(i==="paperclip_vault"&&_ae(ot)){_(_5(ot.slug,F));return}Le(ot),ye(ot.name),Qe(""),Be(""),gt(!1),Fe(""),ws(),xe({}),vt(""),lt(""),We("");const ys=Ek(O1(ot,i));Ye(ys?.key??""),$t($2(ys)),pt(""),be(null),vn(null),ze(new Set(c?[c]:[])),rs(c?"specific":"all"),Ut(Me??bD(ys,!!c)),Ne("key"),_(i==="vercel_connect"?DI(fD(ot.slug),F):_5(ot.slug,F))},"useMatchedGalleryEntry"),Rn=r(()=>{Ne("gallery"),_(DI(i==="vercel_connect"?fD():a?"/apps/byo":"/apps",F))},"backToGallery");(0,m.useEffect)(()=>{if(o==="page")return P([{label:"Connectors",href:"/apps"},{label:X?"Vercel Connect":a?"Connect your own tool":"Connect an app"}]),()=>P([])},[a,o,P,X]);const nr=te({queryKey:M.apps.gallery(T??"__none__"),queryFn:r(()=>ts.listGallery(T),"queryFn"),select:(0,m.useCallback)(ot=>F||v?{...ot,apps:ot.apps.map(ys=>({...ys,methods:ys.methods.filter(kn=>v?kn.ai?.provider===v.provider&&(v.mode==="responsible_user"||kn.ai.method===v.method):kn.transport!=="runtime_auth")})).filter(ys=>ys.methods.length>0)}:ot,[F,v?.provider,v?.method,v?.mode]),enabled:!!T}),mt=Gmt(window.location.origin,nr.data?.oauthCallbackUrl),As=(0,m.useMemo)(()=>(nr.data?.apps??[]).filter(ot=>O||!q6(ot.slug)).filter(ot=>Zp(ot.slug,E,L)||!ot.methods.some(ys=>ys.transport==="chat_sdk")||RM(ot)),[nr.data,E,L,O]),pn=he?fj(he):null,Cn=pn?.methods.find(ot=>gk(ot)&&!A0(ot)),pr=!(Cn&&fe===Cn.key)&&!!pn?.methods.some(ot=>ot.oauthStrategy==="paperclip_cloud_connector"||ot.oauthStrategy==="paperclip_id_connector"),Nr=!!le?.methods.some(ot=>ot.oauthStrategy==="paperclip_cloud_connector"||ot.oauthStrategy==="paperclip_id_connector"),mr=le&&pr&&!Nr?Cae(pn):null,[Ra,vs]=(0,m.useState)(null),an=te({queryKey:["cloud-connector","enrollment"],queryFn:r(()=>ts.getCloudConnectorEnrollment(),"queryFn"),refetchInterval:Ra?2e3:!1,enabled:!!(T&&pr&&!Nr)}),[_r,Jn]=(0,m.useState)(null),Un=(0,m.useCallback)(()=>{hr.current?.close(),hr.current=null,vs(null)},[]),ta=(0,m.useCallback)(()=>{!T||!he||eht(T,he,{grantKind:At,installChoice:It,agentIds:It==="specific"?[...St]:[]})},[At,St,It,he,T]),Ms=(0,m.useCallback)(ot=>{const ys=iE(ot);if(!ys.ok){Un(),Jn(ys.message);return}if(o==="dialog"){vs(ys.url);const kn=hr.current;kn&&!kn.closed?(kn.location.assign(ys.url),kn.focus()):Jn("Open authorization in a new tab to continue.");return}sh(ys.url)},[o,Un]);(0,m.useEffect)(()=>{!Ra||an.data?.status!=="active"||(Un(),Jn(null),nr.refetch())},[Ra,an.data?.status,nr.refetch,Un]);const Mn=je({mutationFn:r(()=>ts.startCloudConnectorEnrollment(T,I?.name,he?kae(he,"key",i,{resumeConnectionId:se,reconnectConnectionId:oe,interactionId:F})+(o==="dialog"?"&enrollment_host=dialog":""):void 0),"mutationFn"),onSuccess:r(ot=>{if(!ot.verificationUrl){Un(),Jn("Paperclip Cloud did not return an enrollment link. Try again.");return}Ms(ot.verificationUrl)},"onSuccess"),onError:r(ot=>{Un(),Jn(ot instanceof Error?ot.message:"Paperclip couldn’t reach Paperclip Cloud. Try again.")},"onError")}),Fn=te({queryKey:M.tools.applications(T??"__none__"),queryFn:r(()=>ts.listApplications(T),"queryFn"),enabled:!!T&&(!!ae||!!se||!!oe),refetchOnMount:"always"}),Ts=te({queryKey:M.tools.connections(T??"__none__"),queryFn:r(()=>ts.listConnections(T),"queryFn"),enabled:!!T&&(!!ae||!!se||!!oe),refetchOnMount:"always"}),er=(0,m.useMemo)(()=>u?null:Iae(ae,Fn.data?.applications??[],Ts.data?.connections??[],U?{applicationId:Ee.applicationId,draftOnly:!0}:{}),[Fn.data,Ts.data,U,ae,Ee.applicationId,u]),fn=(0,m.useMemo)(()=>oe?(Ts.data?.connections??[]).find(ot=>ot.id===oe)??null:null,[Ts.data,oe]),la=(0,m.useRef)(null);(0,m.useEffect)(()=>{if(!p||!Ts.isFetchedAfterMount||!fn||la.current===fn.id)return;const ot=fn.config?.url??fn.transportConfig?.url??fn.transportConfig?.serverUrl??fn.config?.serverUrl;typeof ot!="string"||!/^https?:\/\//i.test(ot)||(la.current=fn.id,Qe(ys=>ys||ot))},[p,Ts.isFetchedAfterMount,fn]);const Te=(0,m.useMemo)(()=>fn?(Fn.data?.applications??[]).find(ot=>ot.id===fn.applicationId)??null:null,[Fn.data,fn]),Zt=rht({requestedAppKey:he,byo:pe,applicationId:Ee.applicationId,reconnectConnection:fn,reconnectApplication:Te}),hn=(0,m.useMemo)(()=>se?(Ts.data?.connections??[]).find(ot=>ot.id===se)??null:null,[Ts.data,se]),Br=(0,m.useMemo)(()=>hn?(Fn.data?.applications??[]).find(ot=>ot.id===hn.applicationId)??null:null,[Fn.data,hn]),Aa=q==="complete"&&hn?.status==="active"?hn.id:null,za=he?u5e({requestedAppKey:he,resumeConnection:hn,resumeApplication:Br,completedResumeConnectionId:Js??Aa}):!1,us=hn??fn,Me=us?us.credentialPolicy==="per_user"?"user":us.credentialPolicy==="per_agent"?"agent":"organization":V,Ht=hn?.authKind==="oauth"?hn:er,Qt=er?er.credentialPolicy==="per_user"?"user":er.credentialPolicy==="per_agent"?"agent":"organization":null,Hs=Me??Qt??(y==="shared"?"organization":null);(0,m.useEffect)(()=>{Hs&&Ut(Hs)},[Hs]);const xn=(0,m.useMemo)(()=>Ae&&!le?y6(Ae,As):null,[le,As,Ae]),Lr=le?$I(le,fe||null):null,ui=Lr&&A0(Lr)?Lr:Aae(le),Ea=i==="paperclip_vault"&&ui?le:null,Pa=i==="paperclip_vault"&&_ae(le)?le:null,Wr=!!ae&&(!Fn.isFetchedAfterMount||!Ts.isFetchedAfterMount),Ya=r(ot=>{Ne(ot),le&&_(kae(le.slug,ot,i,{connectionMethodKey:le.methods.find(ys=>ys.key===fe)?.ai?fe:void 0,resumeConnectionId:se,reconnectConnectionId:oe,interactionId:F}))},"setAppStep"),zr=hn??fn??Ht,Ti=le?.agentInstructions,Gn=le&&Ti?bt?.slug===le.slug?bt.value:zr?zr.agentInstructions??{...iN(Ti),enabled:!1}:iN(Ti):null,Gi=!Gn||!!Gn.text.trim(),il=je({mutationFn:r(async ot=>(Gn&&JSON.stringify(Gn)!==JSON.stringify(ot.agentInstructions)&&await ts.updateConnection(ot.id,{agentInstructions:Gn}),ts.startOAuth(ot.id,{asCurrentUser:ot.credentialPolicy==="per_user",...ot.credentialPolicy==="per_agent"?{asAgentId:uht(ot)??[...St][0]}:{},...F?{interactionId:F}:{}})),"mutationFn"),onSuccess:r(ot=>{ss(ot)},"onSuccess"),onError:r(ot=>{const ys=ot instanceof sn&&ot.body&&typeof ot.body=="object"?ot.body.details:null;Os("error"),k?.("needs_retry"),ks(ys?.code==="invalid_grant"?"Your authorization expired or was revoked. Reconnect to continue.":ot instanceof Error?ot.message:"Paperclip couldn’t start secure sign-in. Try again.")},"onError")}),Yo=il.mutate,po=(0,m.useCallback)(ot=>{k?.("authorizing"),es(),o==="dialog"&&!F&&Kr(ot.id),Yo(ot)},[Yo,k,es,o,F]),ve=r(async ot=>{if(c)return;const ys=c5e(T,(Hs??At)!=="agent"&&It==="all"?{onAll:!0,agentIds:new Set}:{onAll:!1,agentIds:St});await ts.putConnectionInstalls(ot,ys)},"applyAccessInstalls"),Nt=Hs??At,hs=je({mutationFn:r(async ot=>{const ys=ot??le;let kn;if(ys){const In=Hs??At,ar=$I(ys,fe||null),en=EC(ys,ar)?WF($e).ids:[],rr=Ie.trim(),Da=gae(rr||ys.name,In);kn=await ts.connectApp(T,{galleryKey:ys.slug,...Gn?{agentInstructions:Gn}:{},...fe?{connectionMethodKey:fe}:{},name:Da,credentialSource:i,...i==="paperclip_vault"?{credentialValues:Ve}:{},...i==="vercel_connect"?{vercelConnect:{connector:zs.trim()}}:{},...Ge.trim()?{oauthClient:{clientId:Ge.trim(),...Ss?{clientSecret:Ss}:{}}}:{},configValues:EC(ys,ar)?{allowedSpreadsheetIds:en}:Object.keys(ut).length>0?ut:void 0,applicationId:Ee.applicationId,...se??Pt.current?{resumeConnectionId:se??Pt.current}:oe?{reconnectConnectionId:oe}:{},...In!=="organization"?{grantKind:In}:{},...In==="agent"?{subjectAgentId:[...St][0]}:{}}),Pt.current=null}else{const In=Ymt({link:Ae,name:ue,authMode:at,needsKey:ft,keyValue:Xe,headers:Dt,oauthClientId:rt,oauthClientSecret:De}),ar=gae(In.name??gD(Ae)??"Custom app",Nt);kn=await ts.connectApp(T,{...In,...oe?{reconnectConnectionId:oe}:{},...ce||xn?.slug==="zapier"?{galleryKey:"zapier",connectionMethodKey:"generated-url"}:{},name:ar,applicationId:Ee.applicationId,...Nt!=="organization"?{grantKind:Nt}:{},...Nt==="agent"?{subjectAgentId:[...St][0]}:{}})}return kn.auth?.kind==="oauth"&&!se&&!oe&&await ve(kn.connectionId),kn},"mutationFn"),onSuccess:r(ot=>{if(ot.auth?.kind==="oauth"){if(vn(ot),ot.auth.manualClientRequired){qe(vae("oauth_manual_client_required",null)),Tt("oauth"),Et(!0),Re(!1);return}if(o==="dialog"||F){Os("starting"),Re(!le),po(ot.connection);return}const kn=ot.auth.startUrl?.trim();if(!kn){Os("starting"),Re(!0),po(ot.connection);return}Re(!0),ss({authorizationUrl:kn,handoff:ot.auth.handoff});return}qe(null),vn(ot);const ys={};for(const kn of ot.actions.readOnly)ys[kn.catalogEntryId]=!0;for(const kn of ot.actions.canMakeChanges)ys[kn.catalogEntryId]=!0;Bs(ys),Ha.mutate({result:ot,enabled:ys})},"onSuccess"),onError:r(ot=>{const ys=ot instanceof sn&&ot.body&&typeof ot.body=="object"?ot.body.details:null;if(Ea){Os("error"),k?.("needs_retry"),ks(ys?.code==="invalid_grant"?"Your authorization expired or was revoked. Reconnect to continue.":ot instanceof Error?ot.message:"Paperclip couldn’t start secure sign-in. Try again.");return}if(!le&&Ae){const kn=typeof ys?.code=="string"?ys.code:null,In=vae(kn,ot instanceof Error?ot.message:null);qe(In),Re(!1),In.focus==="credentials"&&(gt(!0),Et(!0));return}Q({title:"Couldn’t connect",body:ot instanceof Error?ot.message:"Please check your key and try again.",tone:"error"})},"onError")}),bn=hs.mutate,Ar=(0,m.useCallback)(ot=>{const ys=ot??le;(ys?$I(ys,fe||null):null)?.auth==="oauth"&&es(),bn(ot)},[fe,le,bn,es]);(0,m.useEffect)(()=>{if(!he||nr.isLoading||!nr.data||(se||oe)&&(!Ts.isFetchedAfterMount||!Fn.isFetchedAfterMount))return;if(se&&q==="complete"&&hn?.status==="active"&&Js!==se&&za){_(`/apps/${hn.id}/permissions`,{replace:!0});return}if(se&&!za)return;const ot=nht({requestedAppKey:he,galleryApps:nr.data.apps,reconnectConnection:fn,resumeConnection:hn,resumeApplication:Br,completedResumeConnectionId:Js,applications:Fn.data?.applications??[]}),ys=!!ot?.methods.some(Ce=>Ce.oauthStrategy==="paperclip_cloud_connector"||Ce.oauthStrategy==="paperclip_id_connector");if(pr&&!ys&&an.isLoading)return;const kn=O1(ot,i),In=v??(fn?.connectionPurpose==="ai"?aF.safeParse(fn.config?.ai).data:void 0),ar=kn.find(Ce=>In?Ce.ai?.provider===In.provider&&(!("mode"in In)||In.mode!=="responsible_user")&&Ce.ai.method===In.method:Ce.key===G)??(pr&&!ys?Cae(pn):null)??Ek(kn),en=kn.length===1?kn[0]:null,rr=i==="paperclip_vault"&&!!Aae(ot),Da=aht({credentialSource:i,available:nr.data.credentialSources?.vercelConnect.available===!0,retainedReconnectMatches:!!(oe&&Zt)}),Je=kn.length===1&&en?.auth==="oauth"&&!A0(en)&&!gk(en),Bt=iht({available:ot?.availability?.available,reconnectConnectionId:oe,reconnectSourceMatches:Zt}),Us=oht({reconnectConnectionId:oe,hasRequestedEntry:!!ot,supportedMethodCount:kn.length,unsupportedOAuth:Je,vercelUnavailable:Da,definitionUnavailable:Bt});if(Us!=="ready"){if(Le(null),Ne("gallery"),Us==="reconnect_unavailable"&&oe){Ze(oe);return}_(DI(i==="vercel_connect"?fD():"/apps/connect",F),{replace:!0});return}if(Ze(null),!!ot){if(le?.slug!==ot.slug){Le(ot),ye(ot.name),Qe(""),Be(""),gt(!1),Fe(""),xe({}),vt(""),lt(""),We(""),Ye(ar?.key??""),$t($2(ar)),pt(""),be(null),vn(null);const Ce=ge?.companyId===T?ge:null;Ut(Me??Ce?.grantKind??bD(ar,!!c)),ze(new Set(Ce?.agentIds??(c?[c]:[]))),rs(Ce?.installChoice??(c?"specific":"all")),Ne(wae({requestedAppKey:he,routeStage:q,resumeConnectionId:se,hasPrefilledLink:!!Ee.link,zapierSource:ce}))}else Nr!==ys&&(Le(ot),Ye(ar?.key??""),$t($2(ar)));if(!(rr&&(!Fn.isFetchedAfterMount||!Ts.isFetchedAfterMount))&&!(rr&&Nn.current)&&rr&&(Fn.isError||Ts.isError)){Os("error"),ks("Paperclip couldn’t check for an existing connection. Try again."),Ne("key");return}}},[v,G,Fn.isError,Fn.isFetchedAfterMount,Fn.data,Ts.isError,Ts.isFetchedAfterMount,an.data?.configured,an.isLoading,fe,i,le?.slug,Nr,nr.data,nr.isLoading,_,Me,fn,oe,Zt,hn,Br,za,Js,Aa,q,se,pn,he,c,ge,q,ce]),(0,m.useEffect)(()=>{Xt.current=null,Ns(null)},[se]),(0,m.useEffect)(()=>{const ot=hn??fn;if(!ot||!le||Xt.current===ot.id)return;const ys=PQ(ot),kn=typeof ys.sourceTemplateKey=="string"?ys.sourceTemplateKey:null;if(kn&&kn!==le.slug)return;const In=typeof ys.connectionMethodKey=="string"?ys.connectionMethodKey:null,ar=In?O1(le,i).find(rr=>rr.key===In)??null:null;if(ye(ot.name||le.name),ar){Ye(ar.key);const rr=ys.methodConfig&&typeof ys.methodConfig=="object"?ys.methodConfig:{};$t({...$2(ar),...Object.fromEntries(Object.entries(rr).filter(Da=>typeof Da[1]=="string"||typeof Da[1]=="boolean"))})}const en=ys.oauth&&typeof ys.oauth=="object"?ys.oauth:null;en?.clientRegistrationSource==="manual"&&typeof en.clientId=="string"&&vt(en.clientId),Z==="failed"||Z==="denied"?(Os("error"),ks(jae(Z,ie))):(Os("entry"),ks(null)),Ne("key"),Xt.current=ot.id,Ns(ot.id)},[i,le,ie,Z,hn,fn]);const Ha=je({mutationFn:r(async ot=>{const{result:ys,enabled:kn}=ot,In=Object.entries(kn).filter(([,Da])=>Da).map(([Da])=>Da),ar=ASe(ys,Da=>!!kn[Da]),en=It==="all"?"all_agents":{agentIds:Array.from(St)},rr=await ts.finishApp(T,ys.connectionId,{enabledCatalogEntryIds:In,askFirstCatalogEntryIds:ar,...Gn?{agentInstructions:Gn}:{},access:en,...c?{preserveExistingAccess:!0}:{}});return await ve(ys.connectionId),rr},"mutationFn"),onSuccess:r(async(ot,ys)=>{se&&ys.result.connectionId===se&&cn(se),await S.invalidateQueries({queryKey:["tools"]}),await S.invalidateQueries({queryKey:M.apps.attention(T)}),Ya("success"),x?.({connectionId:ys.result.connectionId})},"onSuccess"),onError:r(ot=>{Ya("key"),Q({title:"Couldn’t finish setup",body:ot instanceof Error?ot.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((se||oe)&&(Ts.isError||Fn.isError))return(0,t.jsxs)("div",{className:"mx-auto max-w-xl rounded-xl border border-border bg-card p-6",children:[(0,t.jsx)("h2",{className:"text-lg font-semibold text-foreground",children:"Couldn’t load connection setup"}),(0,t.jsx)("p",{className:"mt-2 text-sm text-muted-foreground",children:"Paperclip couldn’t check the retained connection. The retained connection was not changed."}),(0,t.jsxs)("div",{className:"mt-5 flex flex-wrap gap-2",children:[(0,t.jsx)($,{type:"button",onClick:r(async()=>{const[ot,ys]=await Promise.all([Ts.refetch(),Fn.refetch()]);!ot.isError&&!ys.isError&&(ks(null),Os("entry"))},"onClick"),children:"Try again"}),(0,t.jsx)($,{type:"button",variant:"outline",onClick:r(()=>_("/apps"),"onClick"),children:"Back to apps"})]})]});if(se&&Ts.isFetchedAfterMount&&!hn)return(0,t.jsxs)("div",{className:"mx-auto max-w-xl rounded-xl border border-border bg-card p-6",children:[(0,t.jsx)("h2",{className:"text-lg font-semibold text-foreground",children:"This setup can’t be resumed"}),(0,t.jsx)("p",{className:"mt-2 text-sm text-muted-foreground",children:"The saved connection no longer exists or is not available to this organization."}),(0,t.jsx)($,{type:"button",variant:"outline",className:"mt-5",onClick:r(()=>_("/apps"),"onClick"),children:"Back to apps"})]});if(se&&Ts.isFetchedAfterMount&&Fn.isFetchedAfterMount&&hn&&!za)return(0,t.jsxs)("div",{className:"mx-auto max-w-xl rounded-xl border border-border bg-card p-6",children:[(0,t.jsx)("h2",{className:"text-lg font-semibold text-foreground",children:"This setup can’t be resumed"}),(0,t.jsx)("p",{className:"mt-2 text-sm text-muted-foreground",children:"This saved draft does not match the requested provider. The connection was not changed."}),(0,t.jsx)($,{type:"button",variant:"outline",className:"mt-5",onClick:r(()=>_("/apps"),"onClick"),children:"Back to apps"})]});if(oe&&Ts.isFetchedAfterMount&&Fn.isFetchedAfterMount&&(!fn||!Zt))return(0,t.jsxs)("div",{className:"mx-auto max-w-xl rounded-xl border border-border bg-card p-6",children:[(0,t.jsx)("h2",{className:"text-lg font-semibold text-foreground",children:"This connection can’t be reconnected"}),(0,t.jsx)("p",{className:"mt-2 text-sm text-muted-foreground",children:fn?"This reconnect link does not match the retained connection's provider.":"The retained connection no longer exists or is not available to this organization."}),(0,t.jsx)($,{type:"button",variant:"outline",className:"mt-5",onClick:r(()=>_("/apps"),"onClick"),children:"Back to apps"})]});if((se||oe)&&nr.isError)return(0,t.jsxs)("div",{className:"mx-auto max-w-xl rounded-xl border border-border bg-card p-6",children:[(0,t.jsx)("h2",{className:"text-lg font-semibold text-foreground",children:"Couldn’t load connection setup"}),(0,t.jsx)("p",{className:"mt-2 text-sm text-muted-foreground",children:"Paperclip couldn’t load the provider details needed to restore this connection. The retained connection was not changed."}),(0,t.jsxs)("div",{className:"mt-5 flex flex-wrap gap-2",children:[(0,t.jsx)($,{type:"button",onClick:r(()=>{nr.refetch()},"onClick"),children:"Try again"}),(0,t.jsx)($,{type:"button",variant:"outline",onClick:r(()=>_("/apps"),"onClick"),children:"Back to apps"})]})]});if(oe&&xt===oe)return(0,t.jsxs)("div",{className:"mx-auto max-w-xl rounded-xl border border-border bg-card p-6",children:[(0,t.jsx)("h2",{className:"text-lg font-semibold text-foreground",children:"This connection can’t be reconnected"}),(0,t.jsx)("p",{className:"mt-2 text-sm text-muted-foreground",children:"Paperclip no longer has a supported setup method for this retained connection. The retained connection was not changed."}),(0,t.jsx)($,{type:"button",variant:"outline",className:"mt-5",onClick:r(()=>_("/apps"),"onClick"),children:"Back to apps"})]});if(se&&(!Ts.isFetchedAfterMount||nr.isLoading||!le||Zs!==hn?.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)(wn,{className:"h-8 w-48"}),(0,t.jsx)(wn,{className:"h-40 w-full rounded-xl"})]});if(oe&&(!Ts.isFetchedAfterMount||!Fn.isFetchedAfterMount||nr.isLoading||he&&!le))return(0,t.jsxs)("div",{className:"mx-auto max-w-xl space-y-4","aria-label":"Loading retained connection setup",children:[(0,t.jsx)(wn,{className:"h-8 w-48"}),(0,t.jsx)(wn,{className:"h-40 w-full rounded-xl"})]});if(ur&&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 ",he?"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)(xv,{choices:h.map(ot=>({id:ot.id,name:ot.name,description:ot.status==="active"&&ot.enabled?"Ready to use":"Setup needs attention"})),pendingId:Qr,onSelect:r(async ot=>{ea(ot),Ir(null);try{await f(ot)}catch(ys){Ir(ys instanceof Error?ys.message:"Couldn’t use this connection."),ea(null)}},"onSelect")}),or?(0,t.jsx)(ma,{tone:"danger",className:"mt-4",children:or}):null,(0,t.jsxs)("div",{className:"mt-5 flex flex-wrap gap-2",children:[(0,t.jsx)($,{type:"button",variant:"outline",onClick:r(()=>Or(!1),"onClick"),children:p?"Review connection setup":"Connect new"}),w?(0,t.jsx)($,{type:"button",variant:"ghost",onClick:w,children:"Cancel"}):null]})]});const Ri=O1(le,i),ti=mr?[mr]:Ri,si=le?fe?ti.find(ot=>ot.key===fe)??null:ti[0]??null:null,Rr=le?si?.auth??"none":at==="none"?"none":at==="oauth"?"oauth":"api_key",Za=de==="key"?((ot,ys)=>(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)(OV,{extra:ot,forceOpen:ys,companyId:T,sentence:LE({grantKind:Nt,authKind:Rr,installChoice:It,installCount:St.size,lockedAgentId:c??null,preserveAgentAccess:!!(Ea&&(Ht||fn))}),notice:[nr.data?.capabilities?.canCreateOrganizationGrant===!1?nr.data.capabilities.organizationGrantReason??"Only a connection manager can share this credential with the organization.":null,nr.data?.capabilities?.canSetCompanyInstall===!1?nr.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(kn=>!!kn),authKind:Rr,grantKinds:Hs?[Hs]:si?.grantKinds,grantKind:Nt,setGrantKind:Ut,installChoice:It,setInstallChoice:rs,installAgentIds:St,setInstallAgentIds:ze,lockedAgentId:c,capabilities:nr.data?.capabilities,githubIdentity:le?.slug==="github",identityLoading:!!Ea&&Wr,preserveAgentAccess:!!(Ea&&(Ht||fn)),disabled:hs.isPending||il.isPending},"connection-defaults"),le&&Ti&&Gn&&(0,t.jsx)("div",{className:"mt-6",children:(0,t.jsx)(RH,{provider:le.name,template:Ti,value:Gn,onChange:r(kn=>Wt({slug:le.slug,value:kn}),"onChange"),disabled:hs.isPending||il.isPending})}),e&&(0,t.jsx)("div",{className:"mt-6",children:e})]})):null,so=Ea&&ui&&gk(ui)?ui:null,fo=so&&Ea?(0,t.jsx)(Wz,{entry:Ea,method:so,callbackUrl:mt,clientId:Ge,onClientIdChange:vt,clientSecret:Ss,onClientSecretChange:lt,required:!1}):null,Va=Za?.()??null,fi=fo?Za?.(fo,$s==="error"||Ge.trim().length>0)??null:Va,ol=!!(Ea&&de==="key"&&(Pa||$s!=="entry")),vd=!!(de==="key"&&le&&pr&&!Nr&&an.data?.configured===!0),mc=!!(de==="key"&&le&&pr&&!Nr&&(an.isLoading||an.isError||an.data?.configured!==!0));if(ol&&Ea)return(0,t.jsx)(Kz,{entry:Ea,resuming:!!se,phase:$s,error:Tn,recoveryActions:ie==="github_installation_required"?{installationUrl:J,managementUrl:re}:void 0,authorizationHost:Hn,authorizationUrl:Er,guidance:le?.slug==="railway"&&si?(0,t.jsxs)("div",{className:"space-y-3 text-sm text-muted-foreground",children:[(0,t.jsx)("p",{children:si.guidanceMd}),(0,t.jsx)("ul",{className:"list-disc space-y-2 pl-5",children:si.warnings?.map(ot=>(0,t.jsx)("li",{children:ot},ot))})]}):null,defaults:fi,settingsValid:n&&Gi,onOpenAuthorization:Is,onRetry:r(async()=>{const ot=!Vs.current;Vs.current=!0,ks(null),Os("starting");const ys=fs?.connection??Ht;if(ys&&fo&&Ge.trim()){Pt.current=ys.id,Ar(Ea);return}if(ys){po(ys);return}if(ot&&!se&&!Fn.isError&&!Ts.isError){Ar(Ea);return}Nn.current=!0;try{const[kn,In]=await Promise.all([Fn.refetch(),Ts.refetch()]);if(kn.isError||In.isError){Os("error"),ks("Paperclip couldn’t check for an existing connection. Try again.");return}const ar=(se?(In.data?.connections??[]).find(en=>en.id===se&&en.authKind==="oauth")??null:null)??Iae(ae,kn.data?.applications??[],In.data?.connections??[],U?{applicationId:Ee.applicationId,draftOnly:!0}:{});ar&&!se&&Ut(ar.credentialPolicy==="per_user"?"user":ar.credentialPolicy==="per_agent"?"agent":"organization"),ar?po(ar):hs.mutate(Ea)}finally{Nn.current=!1}},"onRetry"),onBack:r(()=>{Ln.current?.abort(),Os("entry"),ks(null),Rn()},"onBack"),onCancel:r(()=>{Ln.current?.abort(),(w??(()=>_("/apps")))()},"onCancel")});if(Oe&&!le&&Ae&&de==="key")return(0,t.jsx)(Kz,{identity:{name:ue.trim()||x_(Ae)||"this server",unverifiedHost:x_(Ae)},steps:{labels:Nae,activeIndex:Sae.key},phase:$s,error:Tn,authorizationHost:Hn,authorizationUrl:Er,defaults:Va,onOpenAuthorization:Is,onRetry:r(()=>{ks(null);const ot=fs?.connection;if(ot){Os("starting"),po(ot);return}Re(!1),Os("entry")},"onRetry"),onBack:r(()=>{Ln.current?.abort(),Re(!1),Os("entry"),ks(null)},"onBack"),onCancel:r(()=>{Ln.current?.abort(),(w??(()=>_("/apps")))()},"onCancel")});const Ue=fs?.application.name??le?.name??(ue.trim()||gD(Ae)||"this app"),Rt=X?As.filter(ot=>O1(ot,i).length>0):As,qt=ce?nr.data?.apps.find(ot=>ot.slug==="zapier")??null:null,Fs=(fn?.connectionPurpose==="ai"?aF.safeParse(fn.config?.ai).data:void 0)??le?.methods.find(ot=>ot.key===fe)?.ai??(!fe&&le?.methods.every(ot=>ot.ai)?le.methods[0]?.ai:void 0),dn=le?N?.({app:le,name:Ie||le.name,grantKind:Nt,agentIds:[...St],allAgents:It==="all",onBack:r(()=>Rn(),"onBack")})??(Fs&&T?(0,t.jsx)(t.Fragment,{children:(0,t.jsx)(S5,{defaults:fn?void 0:Va,companyId:T,provider:Fs.provider,fixedMethod:!!(v&&v.mode!=="responsible_user"),initialMethod:fn?.connectionPurpose==="ai"?(fn.config?.ai).method:Fs.method,connectionId:fn?.connectionPurpose==="ai"?fn.id:void 0,name:fn?.connectionPurpose==="ai"?fn.name:Ie||`My ${le.name} ${Fs.method==="subscription"?"subscription":"API"}`,ownership:(fn?.connectionPurpose==="ai"?fn.credentialPolicy==="shared":Nt==="organization")?"shared":"personal",agentIds:[...St],allAgents:It==="all",onCancel:r(()=>w?w():_("/apps"),"onCancel"),onComplete:r(ot=>{x?.({connectionId:ot.connectionId}),x||_(`/apps/${ot.connectionId}/permissions`)},"onComplete")})}):void 0):void 0,ci=fn?.connectionPurpose==="ai"?["Reconnect account"]:dn!==void 0?["Connect account"]:ce?cht:le&&ti.length>1?["Choose connection"]:le&&ti[0]?.auth==="oauth"?["Sign in"]:EC(le,fe)?["Share sheet"]:le?["Add your key"]:Nae,qa=fn?.connectionPurpose==="ai"?0:(ce||le)&&de!=="gallery"&&de!=="success"?lht[de]:de==="success"?ci.length:Sae[de];return(0,t.jsxs)("div",{className:"max-w-5xl",children:[de!=="success"&&!(a&&de==="gallery")&&(0,t.jsx)(cM,{subtitle:de==="gallery"?X?"Choose a reviewed app to connect through Vercel.":"Pick the app you want your agents to use.":ci.length<=1?void 0:`Step ${qa+1} of ${ci.length}`,step:de,activeIndex:qa,labels:ci,appIdentity:ce?{name:"Zapier",logoUrl:qt?.branding.logoUrl??null,darkLogoUrl:qt?.branding.darkLogoUrl??null}:le&&de!=="gallery"?{name:le.name,logoUrl:le.branding.logoUrl,darkLogoUrl:le.branding.darkLogoUrl??null}:void 0,unverifiedHost:!le&&!ce&&de!=="gallery"?x_(Ae):null,onCancel:w??(()=>_("/apps"))}),de==="key"&&s&&(0,t.jsx)("div",{className:"mx-auto mb-6 max-w-xl",children:s}),de==="gallery"&&(0,t.jsx)(xht,{loading:nr.isLoading,initialLink:Ae,apps:Rt,vercelConnect:X,vercelConnectAvailability:nr.data?.credentialSources?.vercelConnect??null,byo:pe,byoOnly:a,source:D.get("source"),onPick:yn,onUseLink:r(ot=>{const ys=y6(ot,As);Le(null),ye(""),Qe(ot),Be(ys?.name??gD(ot)??""),gt(!1),Fe(""),xe({}),pt(""),be(null),ze(new Set(c?[c]:[])),rs(c?"specific":"all"),Ut(Me??(c?"user":"organization")),Ne("key")},"onUseLink")}),vd&&le?(0,t.jsxs)("div",{className:"mx-auto max-w-xl rounded-xl border border-border bg-card p-6",children:[(0,t.jsxs)("h2",{className:"text-lg font-semibold text-foreground",children:[le.name," sign-in is unavailable"]}),(0,t.jsxs)("p",{className:"mt-2 text-sm text-muted-foreground",children:["This instance is connected to Paperclip, but ",le.name," sign-in is not currently available. Try again shortly or contact your instance administrator."]}),Cn?(0,t.jsxs)($,{type:"button",variant:"link",className:"mt-4 h-auto p-0 text-xs",onClick:r(()=>Ye(Cn.key),"onClick"),children:["Use your own ",le.name," OAuth app"]}):null,(0,t.jsxs)("div",{className:"mt-6 flex items-center justify-between gap-3",children:[(0,t.jsx)($,{type:"button",variant:"ghost",onClick:Rn,children:"Back"}),(0,t.jsxs)($,{type:"button",disabled:nr.isFetching,onClick:r(()=>{nr.refetch()},"onClick"),children:[nr.isFetching?(0,t.jsx)(st,{className:"h-4 w-4 animate-spin"}):null,"Try again"]})]})]}):de==="key"&&le&&mc?(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)(Wb,{className:"h-5 w-5"})}),(0,t.jsxs)("div",{className:"min-w-0",children:[(0,t.jsx)("h2",{className:"text-lg font-semibold text-foreground",children:"Connect with Paperclip"}),(0,t.jsxs)("p",{className:"mt-2 text-sm text-muted-foreground",children:["You must connect this instance to Paperclip to connect to ",le.name," (you only need to do this once)."]})]})]}),Cn?(0,t.jsxs)($,{type:"button",variant:"link",className:"mt-4 h-auto p-0 text-xs",onClick:r(()=>Ye(Cn.key),"onClick"),children:["Use your own ",le.name," OAuth app"]}):null,an.isError||_r?(0,t.jsx)(ma,{tone:"danger",className:"mt-4",children:_r??"Paperclip couldn’t check Cloud registration. Try again."}):null,Ra?(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:Ra,target:"_blank",rel:"noopener noreferrer",children:"Open authorization in a new tab"})]}):null,Va,(0,t.jsxs)("div",{className:"mt-6 flex items-center justify-between gap-3",children:[(0,t.jsx)($,{type:"button",variant:"ghost",onClick:Rn,children:"Back"}),(0,t.jsxs)($,{type:"button",disabled:an.isLoading||Mn.isPending,onClick:r(()=>{Jn(null),es(),ta(),Mn.mutate()},"onClick"),children:[Mn.isPending?(0,t.jsx)(st,{className:"h-4 w-4 animate-spin"}):null,an.data?.status==="pending"?"Continue":"Connect with Paperclip"]})]})]})}):de==="key"&&le&&dn!==void 0?dn:de==="key"&&le?(0,t.jsx)(vht,{settingsValid:n&&Gi,entry:le,error:hs.isError?hs.error instanceof Error?hs.error.message:"Please check your key and try again.":null,values:Ve,onChange:xe,oauthClientId:Ge,onOAuthClientIdChange:vt,oauthClientSecret:Ss,oauthCallbackUrl:mt,canReuseOAuthClientSecret:!!(us?.config?.oauth&&us.config.oauth.clientId===Ge.trim()&&us.hasSavedOAuthClientSecret),onOAuthClientSecretChange:lt,credentialSource:i,vercelConnector:zs,onVercelConnectorChange:We,vercelConnectAvailability:nr.data?.credentialSources?.vercelConnect??null,methodKey:fe,onMethodChange:r(ot=>{Ye(ot?.key??""),!Me&&ot?.grantKinds&&!ot.grantKinds.includes(At)&&Ut(bD(ot,!!c)),xe({}),vt(""),lt(""),We(""),$t($2(ot))},"onMethodChange"),configValues:ut,onConfigChange:$t,googleSheetsLinks:$e,googleSheetsError:Gt,onGoogleSheetsLinksChange:r(ot=>{pt(ot),be(null)},"onGoogleSheetsLinksChange"),submitting:hs.isPending,renderDefaults:Za??void 0,onBack:Rn,onConnect:r(()=>{if(EC(le,fe)){const kn=WF($e);if(kn.invalidCount>0){be("That doesn't look like a Google Sheets link.");return}if(kn.ids.length===0){be("Paste at least one Google Sheets link.");return}}const ot=$I(le,fe||null),ys=!!(ot?.credentialFields?.length||ot?.tenantFields?.some(kn=>!kn.hidden)||ot?.extensionFields?.some(kn=>!kn.hidden));if(ot&&A0(ot)&&Ht&&!ys&&!Ge.trim()){Vs.current=!0,ks(null),Os("starting"),po(Ht);return}ot&&A0(ot)&&(Vs.current=!0,ks(null),Os("starting")),Ar()},"onConnect")}):null,de==="key"&&!le&&!Ae&&!ce&&he&&(0,t.jsxs)("div",{className:"mx-auto max-w-xl","aria-busy":"true","aria-label":`Loading ${he} setup`,children:[(0,t.jsx)(wn,{className:"h-6 w-2/3 rounded-md"}),(0,t.jsx)(wn,{className:"mt-3 h-4 w-full rounded-md"}),(0,t.jsx)(wn,{className:"mt-8 h-11 w-40 rounded-md"})]}),de==="key"&&!le&&Ae&&!ce&&(0,t.jsx)(ght,{link:Ae,name:ue,needsKey:ft,keyValue:Xe,onKeyChange:Fe,authMode:at,onAuthModeChange:r(ot=>{Tt(ot),qe(null),ot!=="auto"&&gt(!1),ot!=="bearer"&&ot!=="auto"&&Fe("")},"onAuthModeChange"),headers:Dt,onHeadersChange:r(ot=>{Ot(ot),qe(null)},"onHeadersChange"),oauthClientId:rt,onOAuthClientIdChange:Pe,oauthClientSecret:De,onOAuthClientSecretChange:ht,advancedOpen:Ft,onAdvancedOpenChange:Et,guidance:ct,matchedEntry:xn,onUseMatchedEntry:xn?()=>yn(xn):void 0,submitting:hs.isPending||Oe,defaults:Va,onBack:Rn,onConnect:r(()=>{qe(null),hs.mutate(void 0)},"onConnect")}),de==="key"&&!le&&ce&&(0,t.jsx)(fht,{link:Ae,onLinkChange:Qe,submitting:hs.isPending,defaults:Va,onBack:Rn,onConnect:r(()=>hs.mutate(void 0),"onConnect")}),de==="success"&&(0,t.jsx)(kht,{appName:Ue,logoUrl:le?.branding.logoUrl,darkLogoUrl:le?.branding.darkLogoUrl,summary:wht({grantKind:Nt,authKind:Rr,installChoice:It,installCount:St.size,enabledCount:Object.values(Ls).filter(Boolean).length}),statedDefault:LE({grantKind:Nt,authKind:Rr,installChoice:It,installCount:St.size,lockedAgentId:c??null}),onDone:w??(()=>_(o==="page"&&fs?.connectionId?`/apps/${fs.connectionId}/permissions`:"/apps"))})]})}r(pht,"StandardConnectionSetupFlow");function Kz({entry:e,identity:s,resuming:n=!1,phase:a,error:i,recoveryActions:o,authorizationHost:l,authorizationUrl:c,steps:d={labels:dht,activeIndex:0},guidance:u,defaults:h,onRetry:p,settingsValid:f=!0,onOpenAuthorization:x,onBack:g,onCancel:v}){const y=e?.name??s?.name??"this server",k=e?null:s?.unverifiedHost??null,w=a==="entry"?{title:n?`Finish connecting ${y}`:`Connect ${y} to Paperclip`,body:n?`Your connection is saved. Continue in ${y} to approve access; its identity and agent access will stay the same.`:`Paperclip will open ${y} so you can choose a workspace and approve access.`}:a==="starting"?{title:"Preparing secure sign-in",body:`Paperclip is creating a secure ${y} connection.`}:a==="redirecting"?{title:`Opening ${y}`,body:l?`Continue at ${l} to choose a workspace and approve access. Only approve access if you recognize that address.`:`Continue in ${y} to choose a workspace and approve access.`}:{title:`${y} couldn’t connect`,body:i??"Paperclip couldn’t start secure sign-in. Try again."};return(0,t.jsxs)("div",{className:"max-w-5xl",children:[(0,t.jsx)(cM,{subtitle:"Secure MCP sign-in",step:"key",activeIndex:d.activeIndex,labels:d.labels,appIdentity:e?{name:e.name,logoUrl:e.branding.logoUrl,darkLogoUrl:e.branding.darkLogoUrl}:void 0,unverifiedHost:k,onCancel:v}),(0,t.jsxs)("div",{className:"mx-auto max-w-xl",children:[(0,t.jsxs)("div",{className:"flex items-start gap-3",children:[(0,t.jsx)("span",{className:"mt-1 inline-flex h-10 w-10 shrink-0 items-center justify-center rounded-lg border border-border bg-background",children:a==="error"?(0,t.jsx)(Ml,{className:"h-5 w-5 text-destructive"}):a==="entry"?(0,t.jsx)(Ao,{className:"h-5 w-5 text-muted-foreground"}):(0,t.jsx)(st,{className:"h-5 w-5 animate-spin text-muted-foreground"})}),(0,t.jsxs)("div",{className:"min-w-0",children:[(0,t.jsx)("h2",{className:"text-xl font-bold tracking-tight",children:w.title}),(0,t.jsx)("p",{className:"mt-1 text-sm text-muted-foreground",children:w.body}),k?(0,t.jsx)(lM,{host:k,className:"mt-2"}):null]})]}),a==="entry"&&u?(0,t.jsx)("div",{className:"mt-4",children:u}):null,a==="entry"||a==="error"?h:null,a==="error"&&o&&(o.installationUrl||o.managementUrl)?(0,t.jsxs)("div",{className:"mt-4 flex flex-wrap gap-2",children:[o.installationUrl?(0,t.jsx)($,{type:"button",variant:"outline",asChild:!0,children:(0,t.jsxs)("a",{href:o.installationUrl,target:"_blank",rel:"noreferrer",children:["Install Paperclip on GitHub",(0,t.jsx)(oo,{className:"ml-1.5 h-3.5 w-3.5"})]})}):null,o.managementUrl?(0,t.jsx)($,{type:"button",variant:"ghost",asChild:!0,children:(0,t.jsx)("a",{href:o.managementUrl,target:"_blank",rel:"noreferrer",children:"Manage repositories on GitHub"})}):null]}):null,(0,t.jsxs)("div",{className:"mt-6 flex items-center gap-2",children:[a==="error"||a==="entry"?(0,t.jsxs)($,{type:"button",onClick:p,disabled:!f,children:[a==="entry"?n?`Finish with ${y}`:`Continue to ${y}`:"Try again",a==="entry"?(0,t.jsx)(oo,{className:"h-4 w-4","aria-hidden":"true"}):null]}):(0,t.jsx)($,{type:"button",disabled:!0,children:a==="redirecting"?`Opening ${y}…`:"Preparing…"}),c?(0,t.jsx)($,{variant:"outline",asChild:!0,children:(0,t.jsx)("a",{href:c,target:"_blank",rel:"noopener noreferrer",onClick:x,children:"Open sign-in in a new tab"})}):null,(0,t.jsx)($,{type:"button",variant:"ghost",onClick:g,children:"Back"})]})]})]})}r(Kz,"OAuthConnectStateScreen");function fht({link:e,onLinkChange:s,submitting:n,defaults:a,onBack:i,onConnect:o}){const l=Qz(e),c=l?new URL(l).hostname:"",d=c==="zapier.com"||c.endsWith(".zapier.com");return(0,t.jsxs)("div",{className:"mx-auto max-w-xl",children:[(0,t.jsxs)("div",{children:[(0,t.jsx)("label",{className:"text-sm font-medium text-foreground",children:"Zapier MCP URL"}),(0,t.jsx)(dt,{type:"password",autoComplete:"off",spellCheck:!1,value:e,onChange:r(u=>s(u.target.value),"onChange"),onKeyDown:r(u=>{u.key==="Enter"&&d&&!n&&o()},"onKeyDown"),placeholder:"https://mcp.zapier.com/api/v1/connect?token=…",className:"mt-2 h-11",autoFocus:!0}),e.trim()&&!d&&(0,t.jsx)("p",{className:"mt-2 text-xs text-destructive",children:"Paste a valid Zapier URL to continue."})]}),a,(0,t.jsxs)("div",{className:"mt-6 flex items-center justify-between",children:[(0,t.jsx)($,{variant:"ghost",onClick:i,disabled:n,children:"Back"}),(0,t.jsxs)($,{onClick:o,disabled:n||!d,children:[n&&(0,t.jsx)(st,{className:"mr-2 h-4 w-4 animate-spin"}),n?"Checking…":"Check link"]})]})]})}r(fht,"ZapierConnectStep");function xht({loading:e,initialLink:s="",apps:n,byo:a=!1,byoOnly:i=!1,vercelConnect:o=!1,vercelConnectAvailability:l=null,source:c=null,onPick:d,onUseLink:u}){const[h,p]=(0,m.useState)(""),[f,x]=(0,m.useState)(s),g=(0,m.useRef)(!1);(0,m.useEffect)(()=>{g.current||x(s)},[s]);const[v,y]=(0,m.useState)(null),k=(0,m.useRef)(null),w=(0,m.useRef)(null),N=(0,m.useRef)(!1);(0,m.useEffect)(()=>{!a||e&&!i||N.current||(i||k.current?.scrollIntoView?.({block:"center"}),w.current?.focus(),w.current?.select(),N.current=!0)},[a,i,e]);const S=(0,m.useMemo)(()=>{const T=h.trim().toLowerCase();return n.filter(E=>!T||E.name.toLowerCase().includes(T))},[n,h]),C=Qz(f),_=C?y6(C,n):null,R=c==="zapier",I=r(()=>{const T=Qz(f);if(!T){y("Paste a full http or https link.");return}y(null),u(T)},"continueWithLink");return e&&!i?(0,t.jsx)("div",{className:"grid grid-cols-2 gap-4 sm:grid-cols-3 lg:grid-cols-4",children:Array.from({length:8}).map((T,E)=>(0,t.jsx)(wn,{className:"h-32 w-full rounded-xl"},E))}):(0,t.jsxs)("div",{className:"space-y-6",children:[o?(0,t.jsxs)("div",{className:"rounded-xl border border-border bg-card p-5",children:[(0,t.jsxs)("div",{className:"flex flex-col gap-3 sm:flex-row sm:items-start sm:justify-between",children:[(0,t.jsxs)("div",{children:[(0,t.jsx)("h2",{className:"text-lg font-bold tracking-tight",children:"Connect through Vercel"}),(0,t.jsx)("p",{className:"mt-1 max-w-2xl text-sm text-muted-foreground",children:"Create and manage the provider connector in Vercel. Paperclip stores its reference and applies agent access, policy, approval, and audit controls here."})]}),l?(0,t.jsx)($,{asChild:!0,variant:"outline",size:"sm",className:"shrink-0",children:(0,t.jsxs)("a",{href:l.manageUrl,target:"_blank",rel:"noreferrer",children:["Open Vercel Connect",(0,t.jsx)(oo,{className:"ml-2 h-3.5 w-3.5"})]})}):null]}),l?.available===!1?(0,t.jsx)(ma,{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)(Jr,{className:"pointer-events-none absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground"}),(0,t.jsx)(dt,{value:h,onChange:r(T=>p(T.target.value),"onChange"),placeholder:"Search apps…",className:"h-11 pl-9"})]}),(0,t.jsx)("div",{className:"grid grid-cols-2 gap-4 sm:grid-cols-3 lg:grid-cols-4",children:S.map(T=>{const E=i5e(T.slug,T.description),L=sA(T),O=L.length===0||L.every(Q=>Q.auth==="oauth"&&!A0(Q)&&!gk(Q)),P=T.availability?.available===!1||o&&l?.available!==!0;return(0,t.jsxs)("button",{type:"button",disabled:O||P,title:P?T.availability?.reason??l?.reason??void 0:void 0,onClick:r(()=>d(T),"onClick"),className:W("flex flex-col rounded-xl border border-border bg-card p-4 text-left transition-colors",O||P?"cursor-not-allowed opacity-60":"hover:border-foreground/30 hover:bg-accent/40"),children:[(0,t.jsx)(Vi,{name:T.name,logoUrl:T.branding.logoUrl,darkLogoUrl:T.branding.darkLogoUrl,size:36}),(0,t.jsx)("div",{className:"mt-3 text-sm font-bold text-foreground",children:T.name}),(0,t.jsx)("div",{className:"mt-1 line-clamp-2 text-xs text-muted-foreground",children:E.tagline}),(0,t.jsx)("div",{className:"mt-3 text-xs font-semibold text-foreground",children:P?(0,t.jsx)("span",{className:"text-muted-foreground",children:T.availability?.reason??l?.reason??"Unavailable on this instance."}):O?(0,t.jsx)("span",{className:"text-muted-foreground",children:"Unavailable"}):(0,t.jsx)("span",{children:"Connect →"})})]},T.slug)})}),S.length===0&&(0,t.jsxs)("div",{className:"py-10 text-center text-sm text-muted-foreground",children:["No apps match “",h,"”."]})]}),o?null:(0,t.jsxs)("div",{ref:k,className:W("grid gap-4 border-t border-border pt-5 md:grid-cols-(--gtc-13)",a&&"-mx-3 rounded-xl border border-primary/40 bg-primary/[0.04] px-3 pb-4 md:mx-0"),children:[(0,t.jsxs)("div",{children:[(0,t.jsxs)("div",{className:"flex items-center gap-2 text-sm font-semibold text-foreground",children:[(0,t.jsx)(Ml,{className:"h-4 w-4 text-muted-foreground"}),R?"Connect Zapier":a?"Connect your own MCP server":"Connect with a link"]}),(0,t.jsx)("p",{className:"mt-1 text-xs text-muted-foreground",children:R?"Paste the complete MCP URL Zapier gives you, including its token.":a?"Paste your MCP server’s URL and every discovered tool will be available immediately.":"Paste a setup link from an app that is not listed here."}),!R&&(0,t.jsxs)("p",{className:"mt-1 text-xs text-muted-foreground",children:["Any remote tool URL works here — including a local MCP server like"," ",(0,t.jsx)("code",{className:"rounded bg-muted px-1 py-0.5 text-xs",children:"http://127.0.0.1:8848/mcp"}),"."]}),_&&(0,t.jsxs)("div",{className:"mt-3 flex items-center justify-between gap-3 rounded-lg border border-border bg-muted/40 px-3 py-2",children:[(0,t.jsxs)("div",{className:"flex min-w-0 items-center gap-2 text-sm",children:[(0,t.jsx)(Vi,{name:_.name,logoUrl:_.branding.logoUrl,darkLogoUrl:_.branding.darkLogoUrl,size:24}),(0,t.jsxs)("span",{className:"truncate",children:["This looks like ",_.name,"."]})]}),(0,t.jsx)($,{type:"button",size:"sm",variant:"outline",disabled:_.availability?.available===!1,onClick:r(()=>{if(y(null),_.slug==="zapier"){I();return}d(_)},"onClick"),children:_.availability?.available===!1?"Not available":_.slug==="zapier"?"Continue":`Use ${_.name}`})]})]}),(0,t.jsxs)("div",{className:"flex min-w-0 flex-col gap-2 sm:min-w-(--sz-360px)",children:[(0,t.jsxs)("div",{className:"flex gap-2",children:[(0,t.jsx)(dt,{ref:w,type:R||_?.slug==="zapier"?"password":"url",autoComplete:"off",spellCheck:!1,"aria-label":"MCP server URL",value:f,onChange:r(T=>{g.current=!0,x(T.target.value),y(null)},"onChange"),onKeyDown:r(T=>{T.key==="Enter"&&I()},"onKeyDown"),placeholder:R?"https://mcp.zapier.com/api/v1/connect?token=…":"https://example.com/actions",className:"h-10"}),(0,t.jsx)($,{type:"button",variant:"outline",onClick:I,children:"Continue"})]}),v&&(0,t.jsx)("div",{className:"text-xs text-destructive",children:v})]})]})]})}r(xht,"GalleryStep");function Qz(e){try{const s=new URL(e.trim());return s.protocol!=="http:"&&s.protocol!=="https:"?null:s.toString()}catch{return null}}r(Qz,"normalizeAppLink");function ght({link:e,name:s,needsKey:n,keyValue:a,onKeyChange:i,authMode:o,onAuthModeChange:l,headers:c,onHeadersChange:d,oauthClientId:u,onOAuthClientIdChange:h,oauthClientSecret:p,onOAuthClientSecretChange:f,advancedOpen:x,onAdvancedOpenChange:g,guidance:v,matchedEntry:y,onUseMatchedEntry:k,submitting:w,defaults:N,onBack:S,onConnect:C}){const _=x_(e),R=o==="custom_headers"?o5e(c):null,I=Zmt({link:e,name:s,authMode:o,needsKey:n,keyValue:a,headers:c,oauthClientId:u,oauthClientSecret:p}),T=o==="auto"&&n||o==="bearer",E=y?.slug==="zapier"?qbe(e):e,L=r((O,P)=>{d(c.map(Q=>Q.id===O?{...Q,...P}:Q))},"updateHeader");return(0,t.jsxs)("div",{className:"mx-auto max-w-xl",children:[(0,t.jsxs)("div",{className:"flex items-center justify-between gap-3",children:[(0,t.jsx)("p",{className:"min-w-0 truncate font-mono text-sm text-muted-foreground",title:E,children:E}),(0,t.jsx)(lM,{host:_})]}),y&&k?(0,t.jsxs)("div",{className:"mt-6 flex flex-wrap items-center justify-between gap-3 rounded-lg border border-border bg-muted/40 px-3 py-2",children:[(0,t.jsxs)("div",{className:"flex min-w-0 items-center gap-2 text-sm",children:[(0,t.jsx)(Vi,{name:y.name,logoUrl:y.branding.logoUrl,darkLogoUrl:y.branding.darkLogoUrl,size:24}),(0,t.jsxs)("span",{className:"truncate",children:["Paperclip has a guided setup for ",y.name,"."]})]}),(0,t.jsxs)($,{type:"button",size:"sm",variant:"outline",onClick:k,children:["Use ",y.name]})]}):null,v?(0,t.jsx)("div",{className:"mt-6",children:(0,t.jsx)(ma,{tone:"warning",title:v.title,children:v.body})}):null,(0,t.jsxs)("div",{className:"mt-6 space-y-6",children:[T?(0,t.jsx)("div",{className:"space-y-4",children:(0,t.jsxs)("div",{children:[(0,t.jsx)("label",{className:"text-sm font-medium text-foreground",htmlFor:"generic-mcp-key",children:"App key"}),(0,t.jsx)(dt,{id:"generic-mcp-key",type:"password",autoComplete:"off",value:a,onChange:r(O=>i(O.target.value),"onChange"),placeholder:"••••••••••••••••",className:"mt-2 h-11 font-mono"}),(0,t.jsx)("p",{className:"mt-2 text-xs text-muted-foreground",children:"Grant this key read and write access to the resources your agents need. Paperclip cannot increase its permissions."})]})}):null,(0,t.jsxs)(tl,{open:x,onOpenChange:g,children:[(0,t.jsxs)(Dl,{className:"flex w-full items-center justify-between rounded-lg border border-border bg-background px-3 py-2 text-left text-sm font-medium text-foreground hover:bg-accent/40",children:["Advanced authentication",(0,t.jsx)(rn,{className:W("h-4 w-4 text-muted-foreground transition-transform",x&&"rotate-180")})]}),(0,t.jsxs)(sl,{className:"space-y-5 pt-4",children:[(0,t.jsx)("p",{className:"text-xs text-muted-foreground",children:"Only needed when the server's docs are specific about how to authenticate."}),(0,t.jsx)("div",{className:"flex flex-wrap gap-2",children:Tae.map(O=>(0,t.jsx)(bht,{label:O.label,selected:o===O.mode,onClick:r(()=>l(O.mode),"onClick")},O.mode))}),(0,t.jsx)("p",{className:"text-xs text-muted-foreground",children:Tae.find(O=>O.mode===o)?.hint}),o==="custom_headers"?(0,t.jsxs)("div",{className:"space-y-3",children:[c.map(O=>(0,t.jsxs)("div",{className:"flex items-start gap-2",children:[(0,t.jsx)(dt,{value:O.name,onChange:r(P=>L(O.id,{name:P.target.value}),"onChange"),placeholder:"Header name","aria-label":"Header name",className:"h-10 font-mono"}),(0,t.jsx)(dt,{type:"password",autoComplete:"off",value:O.value,onChange:r(P=>L(O.id,{value:P.target.value}),"onChange"),placeholder:"Value","aria-label":O.name.trim()?`Value for ${O.name.trim()}`:"Header value",className:"h-10 font-mono"}),(0,t.jsx)($,{type:"button",variant:"ghost",size:"sm",className:"h-10 shrink-0",onClick:r(()=>d(c.filter(P=>P.id!==O.id)),"onClick"),disabled:c.length===1,children:"Remove"})]},O.id)),(0,t.jsx)($,{type:"button",variant:"outline",size:"sm",onClick:r(()=>d([...c,Uz()]),"onClick"),children:"Add another header"}),R?(0,t.jsx)("p",{className:"text-xs text-destructive",children:R}):null]}):null,o==="oauth"?(0,t.jsxs)("div",{className:"space-y-4",children:[(0,t.jsx)("p",{className:"text-xs text-muted-foreground",children:"Paperclip sets sign-in up on its own whenever the server allows it. Only fill these in when the server's docs tell you to register Paperclip yourself first."}),(0,t.jsxs)("div",{children:[(0,t.jsx)("label",{className:"text-sm font-medium text-foreground",htmlFor:"generic-mcp-client-id",children:"Client ID"}),(0,t.jsx)(dt,{id:"generic-mcp-client-id",value:u,onChange:r(O=>h(O.target.value),"onChange"),autoComplete:"off",placeholder:"Optional",className:"mt-2 h-11 font-mono"})]}),(0,t.jsxs)("div",{children:[(0,t.jsx)("label",{className:"text-sm font-medium text-foreground",htmlFor:"generic-mcp-client-secret",children:"Client secret"}),(0,t.jsx)(dt,{id:"generic-mcp-client-secret",type:"password",autoComplete:"off",value:p,onChange:r(O=>f(O.target.value),"onChange"),placeholder:"Optional",className:"mt-2 h-11 font-mono"})]})]}):null]})]})]}),N,(0,t.jsxs)("div",{className:"mt-8 flex items-center justify-between",children:[(0,t.jsx)($,{variant:"ghost",onClick:S,disabled:w,children:"Back"}),(0,t.jsxs)($,{onClick:C,disabled:w||!I||!!R,children:[w&&(0,t.jsx)(st,{className:"mr-2 h-4 w-4 animate-spin"}),w?"Checking…":"Check link"]})]})]})}r(ght,"LinkConnectStep");var Tae=[{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 bht({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(bht,"SegmentedOption");function vht({settingsValid:e=!0,entry:s,error:n,values:a,onChange:i,oauthClientId:o,onOAuthClientIdChange:l,oauthClientSecret:c,oauthCallbackUrl:d,canReuseOAuthClientSecret:u,onOAuthClientSecretChange:h,credentialSource:p,vercelConnector:f,onVercelConnectorChange:x,vercelConnectAvailability:g,methodKey:v,onMethodChange:y,configValues:k,onConfigChange:w,googleSheetsLinks:N,googleSheetsError:S,onGoogleSheetsLinksChange:C,submitting:_,renderDefaults:R,onBack:I,onConnect:T}){const E=(0,m.useMemo)(()=>O1(s,p),[p,s]),L=v?E.find(Fe=>Fe.key===v)??null:Ek(E),O=(0,m.useMemo)(()=>E.some(Fe=>Fe.capabilityProfile)?Array.from(E.reduce((Fe,at)=>{const Tt=at.capabilityProfile.key,Dt=Fe.get(Tt);return Dt?Dt.methods.push(at):Fe.set(Tt,{key:Tt,label:at.capabilityProfile?.label??at.label??at.key,description:at.capabilityProfile?.description??at.whenToUse,methods:[at]}),Fe},new Map)).map(([,Fe])=>Fe):[],[E]),P=L?.capabilityProfile?.key??L?.key??"",Q=O.map(Fe=>Fe.key).join("|"),[D,F]=(0,m.useState)(P||Ek(E)?.capabilityProfile?.key||(O.length===1?O[0].key:""));(0,m.useEffect)(()=>{if(P){F(P);return}F(Fe=>O.some(at=>at.key===Fe)?Fe:Ek(E)?.capabilityProfile?.key||(O.length===1?O[0].key:""))},[Q,O,E,P]);const z=O.length>1?O.find(Fe=>Fe.key===D)?.methods??[]:E,K=(L?.credentialFields??[]).map(Fe=>({...Fe,configPath:ybe(Fe,L),helpUrl:L?.consoleLinks?.keys??L?.consoleLinks?.docs??""})),U=L?.credentialSources?.vercelConnect??null,q=p==="vercel_connect",G=q||K.every(Fe=>Fe.required===!1||(a[Fe.configPath]?.trim().length??0)>0),se=gk(L),Z=se&&!A0(L),ie=q||!Z||o.trim().length>0&&(!L?.oauthClientSecretRequired||u||c.trim().length>0),J=!q||f.trim().length>0,re=L?.auth==="oauth"&&se?d:null,oe=[...L?.tenantFields??[],...L?.extensionFields??[]],V=oe.filter(Fe=>!Fe.hidden),X=V.filter(Fe=>Fe.advanced!==!0),Y=V.filter(Fe=>Fe.advanced===!0),ae=oe.every(Fe=>{if(!Fe.required)return!0;const at=k[Fe.key];return typeof at=="boolean"||typeof at=="string"&&at.trim().length>0}),ne=L?.configRequirements?.atLeastOneOf??[],ce=ne.length===0||ne.some(Fe=>{const at=k[Fe];return typeof at=="string"&&at.trim().length>0}),he=(O.length<=1||!!D)&&(z.length<=1?!!L:!!v),pe=s.availability?.robotEmail??null,ge=s.availability?.available===!1,Ee=!q&&se&&!Z,de=O.length>1||z.length>1,Ne=O.length>1?(0,t.jsxs)("div",{children:[(0,t.jsx)("label",{className:"text-sm font-medium text-foreground",children:"What should Paperclip be able to do?"}),(0,t.jsx)(em,{ariaLabel:`Access level for ${s.name}`,className:"mt-2",value:D,onValueChange:r(Fe=>{const at=O.find(Tt=>Tt.key===Fe);at&&(F(Fe),y(UQ(at.methods)))},"onValueChange"),options:O.map(Fe=>({value:Fe.key,title:Fe.label,description:Fe.description}))}),!D&&(0,t.jsx)("p",{className:"mt-2 text-xs text-muted-foreground",children:"Choose an access level to continue."})]}):null,le=z.find(Fe=>Fe.oauthStrategy==="paperclip_cloud_connector"),Le=le&&z.find(Fe=>gk(Fe)&&!A0(Fe)),Ie=L?.key===Le?.key,ye=(0,m.useId)(),Ae=le&&Le&&z.length===2?(0,t.jsx)($,{type:"button",variant:"link",className:"h-auto p-0 text-xs text-muted-foreground underline underline-offset-2 hover:text-foreground","aria-expanded":Ie,"aria-controls":ye,disabled:_,onClick:r(()=>y(Ie?le:Le),"onClick"),children:Ie?"Use Paperclip instead":`Use your own ${oOe(le.connectorProfile??"")?"Google":s.name} OAuth app`}):z.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)(em,{ariaLabel:`How to connect ${s.name}`,className:"mt-2",value:v,onValueChange:r(Fe=>{const at=z.find(Tt=>Tt.key===Fe);at&&y(at)},"onValueChange"),options:z.map(Fe=>({value:Fe.key,title:Fe.label??(Fe.auth==="oauth"?`Sign in with ${s.name}`:"Use an API key")}))}),!L&&(0,t.jsx)("p",{className:"mt-2 text-xs text-muted-foreground",children:"Choose a connection method to continue."})]}):null,Qe=Y.length>0||Ee||de,ue=Ie||!he,Be=Qe?(0,t.jsxs)("div",{className:"space-y-6",children:[Ne,Ae,Y.map(Fe=>(0,t.jsx)(Rae,{field:Fe,value:k[Fe.key],onChange:r(at=>w({...k,[Fe.key]:at}),"onChange")},Fe.key)),Ee?(0,t.jsx)(Wz,{entry:s,method:L,callbackUrl:re,clientId:o,onClientIdChange:l,clientSecret:c,onClientSecretChange:h,required:!1}):null]}):null,ft=R?.(Be,ue)??null;if(EC(s,L)){const Fe=WF(N),at=e&&!ge&&!!pe&&N.trim().length>0;return(0,t.jsxs)("div",{className:"mx-auto max-w-xl",children:[(0,t.jsxs)("div",{className:"space-y-6",children:[Ne,pe?(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:pe,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:pe}),(0,t.jsx)(h5e,{value:pe,ariaLabel:"Copy sharing email"})]}),(0,t.jsx)("p",{className:"mt-2 text-xs text-muted-foreground",children:"In Google Sheets, click Share and add this email as an Editor. Then paste the sheet links below."})]}):(0,t.jsx)("div",{className:"rounded-lg bg-muted/50 p-4 text-sm text-muted-foreground",children:"Google Sheets is not available on this instance yet."}),(0,t.jsxs)("div",{children:[(0,t.jsx)("label",{className:"text-sm font-medium text-foreground",children:"Paste links to the sheets you shared"}),(0,t.jsx)(Qn,{value:N,onChange:r(Tt=>C(Tt.target.value),"onChange"),placeholder:"https://docs.google.com/spreadsheets/d/...",className:"mt-2 min-h-28"}),(0,t.jsx)("div",{className:"mt-2 text-xs text-muted-foreground",children:Fe.ids.length>0?`${Fe.ids.length} ${Fe.ids.length===1?"sheet":"sheets"} ready to connect.`:"Paste one link per line. Both .../edit and .../edit#gid=... links work."}),S&&(0,t.jsx)("div",{className:"mt-2 text-xs text-destructive",children:S})]})]}),ft,(0,t.jsxs)("div",{className:"mt-8 flex items-center justify-between",children:[(0,t.jsx)($,{variant:"ghost",onClick:I,disabled:_,children:"Back"}),(0,t.jsxs)($,{onClick:T,disabled:_||!at,children:[_&&(0,t.jsx)(st,{className:"mr-2 h-4 w-4 animate-spin"}),_?"Checking…":"Connect"]})]})]})}const gt=L?.connectorProfile==="asana.mcp",Xe=gt?null:L?.consoleLinks?.docs??s.docsUrl;return(0,t.jsxs)("div",{className:"mx-auto max-w-xl",children:[Xe?(0,t.jsx)("div",{className:"mb-4 flex justify-end",children:(0,t.jsxs)("a",{href:Xe,target:"_blank",rel:"noreferrer",className:"inline-flex items-center gap-1 text-xs font-medium text-muted-foreground underline underline-offset-2 hover:text-foreground",children:["Review requirements",(0,t.jsx)(oo,{className:"h-3 w-3"})]})}):null,(0,t.jsxs)("div",{className:"space-y-6",children:[gt?(0,t.jsx)("p",{className:"text-sm text-muted-foreground",children:"Sign in with Asana to choose your workspace and connect it to Paperclip."}):null,L?.capabilityProfile&&(0,t.jsxs)("p",{className:"text-sm text-muted-foreground",children:[L.capabilityProfile.label,": ",L.capabilityProfile.description]}),q&&U&&g?(0,t.jsxs)("div",{className:"space-y-4 rounded-lg border border-border p-4",children:[(0,t.jsxs)("div",{children:[(0,t.jsx)("div",{className:"text-sm font-medium text-foreground",children:"Create or attach the connector in Vercel"}),(0,t.jsx)("p",{className:"mt-1 text-xs text-muted-foreground",children:"Paperclip does not copy Vercel’s setup forms. Finish connector setup there, then paste its UID below."}),(0,t.jsxs)("a",{href:g.manageUrl,target:"_blank",rel:"noreferrer",className:"mt-2 inline-flex items-center gap-1 text-xs font-semibold text-foreground underline underline-offset-2",children:["Open Vercel Connect",(0,t.jsx)(oo,{className:"h-3 w-3"})]})]}),(0,t.jsxs)("div",{children:[(0,t.jsx)("label",{className:"text-sm font-medium text-foreground",htmlFor:"vercel-connect-connector",children:"Connector UID or ID"}),(0,t.jsx)(dt,{id:"vercel-connect-connector",value:f,onChange:r(Fe=>x(Fe.target.value),"onChange"),autoComplete:"off",placeholder:"service/my-connector or scl_…",className:"mt-2 h-11 font-mono"}),(0,t.jsx)("p",{className:"mt-2 text-xs text-muted-foreground",children:"Paperclip validates the connector and stores only its reference and redacted verification metadata."})]})]}):null,n?(0,t.jsx)("div",{role:"alert",children:(0,t.jsx)(ma,{tone:"danger",children:n})}):null,X.map(Fe=>(0,t.jsx)(Rae,{field:Fe,value:k[Fe.key],onChange:r(at=>w({...k,[Fe.key]:at}),"onChange")},Fe.key)),!q&&L?.auth==="oauth"&&Z?(0,t.jsx)("div",{id:ye,role:"region","aria-label":"Your OAuth app",children:(0,t.jsx)(Wz,{entry:s,method:L,callbackUrl:re,clientId:o,onClientIdChange:l,clientSecret:c,onClientSecretChange:h,required:!0})}):null,q||!L||K.length===0?null:K.map(Fe=>(0,t.jsxs)("div",{children:[(0,t.jsx)("label",{className:"text-sm font-medium text-foreground",children:pae(s.name,Fe.label,K.length)}),(0,t.jsx)(dt,{type:Fe.type==="text"&&Fe.secret===!1?"text":"password","aria-label":pae(s.name,Fe.label,K.length),autoComplete:"off",value:a[Fe.configPath]??"",onChange:r(at=>i({...a,[Fe.configPath]:at.target.value}),"onChange"),placeholder:Fe.type==="text"&&Fe.secret===!1?Fe.placeholder:"••••••••••••••••",className:"mt-2 h-11 font-mono"}),Fe.helperMd&&(0,t.jsx)("p",{className:"mt-2 text-xs text-muted-foreground",children:Fe.helperMd}),Fe.helpUrl&&(0,t.jsxs)("a",{href:Fe.helpUrl,target:"_blank",rel:"noreferrer",className:"mt-2 inline-flex items-center gap-1 text-xs font-semibold text-foreground underline underline-offset-2",children:["Where do I find this?",(0,t.jsx)(oo,{className:"h-3 w-3"})]})]},Fe.configPath))]}),ft,(0,t.jsxs)("div",{className:"mt-8 flex items-center justify-between",children:[(0,t.jsx)($,{variant:"ghost",onClick:I,disabled:_,children:"Back"}),(0,t.jsxs)($,{onClick:T,disabled:_||!e||!he||!G||!ie||!J||!ae||!ce,children:[_&&(0,t.jsx)(st,{className:"mr-2 h-4 w-4 animate-spin"}),_?"Checking…":q?L?.auth==="oauth"?"Validate and continue":"Validate and connect":L?.auth==="oauth"?s.slug==="github"?"Continue to GitHub":"Continue to sign in":"Connect"]})]})]})}r(vht,"KeyStep");function h5e({value:e,ariaLabel:s}){const{copied:n,failed:a,copy:i}=Z0();return(0,t.jsxs)($,{type:"button",variant:"outline",className:"shrink-0","aria-label":s,onClick:r(()=>{i(e)},"onClick"),children:[n?(0,t.jsx)(cs,{className:"mr-2 h-4 w-4"}):(0,t.jsx)(gr,{className:"mr-2 h-4 w-4"}),n?"Copied":a?"Copy failed":"Copy"]})}r(h5e,"CopyValueButton");function Wz({entry:e,method:s,callbackUrl:n,clientId:a,onClientIdChange:i,clientSecret:o,onClientSecretChange:l,required:c}){return(0,t.jsxs)("div",{className:"space-y-4 rounded-lg border border-border p-4",children:[(0,t.jsxs)("div",{children:[(0,t.jsx)("div",{className:"text-sm font-medium text-foreground",children:c?s.oauthClientSecretRequired?"Your OAuth app":`${e.name} needs its own OAuth app`:"Use your own OAuth app"}),(0,t.jsx)("p",{className:"mt-1 text-xs text-muted-foreground",children:s.oauthClientSecretRequired?s.guidanceMd:c?`${e.name} does not let Paperclip register itself automatically, so this connector needs an OAuth app you create. Add the callback URL below in ${e.name}, then paste the client details back here.`:`Register Paperclip's callback URI in ${e.name}, then enter the customer-owned client details.`}),s.consoleLinks?.register?(0,t.jsxs)("a",{href:s.consoleLinks.register,target:"_blank",rel:"noreferrer",className:"mt-2 inline-flex items-center gap-1 text-xs font-semibold text-foreground underline underline-offset-2",children:["Open ",e.name," app settings",(0,t.jsx)(oo,{className:"h-3 w-3"})]}):null]}),n?(0,t.jsxs)("div",{children:[(0,t.jsx)("label",{className:"text-sm font-medium text-foreground",children:"Paperclip callback URL"}),(0,t.jsxs)("div",{className:"mt-2 flex min-w-0 flex-col gap-2 sm:flex-row",children:[(0,t.jsx)("div",{title:n,className:"min-h-11 min-w-0 flex-1 rounded-md border border-input bg-muted/40 px-3 py-2.5 font-mono text-xs leading-tight text-foreground break-all",children:n}),(0,t.jsx)(h5e,{value:n,ariaLabel:"Copy callback URL"})]}),(0,t.jsxs)("p",{className:"mt-2 text-xs text-muted-foreground",children:["Add this exact URL to ",e.name," before continuing. It must match the authorization request."]})]}):null,(0,t.jsxs)("div",{children:[(0,t.jsx)("label",{className:"text-sm font-medium text-foreground",htmlFor:"curated-oauth-client-id",children:"Client ID"}),(0,t.jsx)(dt,{id:"curated-oauth-client-id",value:a,onChange:r(d=>i(d.target.value),"onChange"),autoComplete:"off",placeholder:c?"Required":"Optional",className:"mt-2 h-11 font-mono"})]}),(0,t.jsxs)("div",{children:[(0,t.jsx)("label",{className:"text-sm font-medium text-foreground",htmlFor:"curated-oauth-client-secret",children:"Client secret"}),(0,t.jsx)(dt,{id:"curated-oauth-client-secret",type:"password",value:o,onChange:r(d=>l(d.target.value),"onChange"),autoComplete:"off",placeholder:s.oauthClientSecretRequired?"Required":"Optional for public clients",className:"mt-2 h-11 font-mono"})]})]})}r(Wz,"OAuthClientFields");function Rae({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)(oi,{checked:s===!0,onCheckedChange:n})]}):(0,t.jsxs)("div",{children:[(0,t.jsx)("label",{className:"text-sm font-medium text-foreground",children:e.label}),e.type==="textarea"?(0,t.jsx)(Qn,{value:typeof s=="string"?s:"",onChange:r(a=>n(a.target.value),"onChange"),placeholder:e.placeholder,className:"mt-2 min-h-24"}):e.type==="select"?(0,t.jsxs)("select",{value:typeof s=="string"?s:"",onChange:r(a=>n(a.target.value),"onChange"),className:"mt-2 h-11 w-full rounded-md border border-input bg-background px-3 text-sm text-foreground outline-none focus-visible:border-ring focus-visible:ring-3 focus-visible:ring-ring/30",children:[(0,t.jsx)("option",{value:"",disabled:!0,children:"Select an option"}),(e.options??[]).map(a=>(0,t.jsx)("option",{value:a.value,children:a.label},a.value))]}):(0,t.jsx)(dt,{value:typeof s=="string"?s:"",onChange:r(a=>n(a.target.value),"onChange"),placeholder:e.placeholder,"aria-label":e.label,maxLength:e.validation?.maxLength,className:"mt-2 h-11"}),e.required&&(typeof s!="string"||!s.trim())&&(0,t.jsxs)("p",{className:"mt-2 text-xs text-muted-foreground",children:[e.label," is required."]}),e.helperMd&&(0,t.jsx)("p",{className:"mt-2 text-xs text-muted-foreground",children:e.helperMd})]})}r(Rae,"MethodConfigField");function yht({companyId:e,...s}){const n=te({queryKey:M.agents.list(e),queryFn:r(()=>_t.list(e),"queryFn")});return(0,t.jsx)($V,{...s,agents:(n.data??[]).filter(a=>a.status!=="terminated"),agentsLoading:n.isLoading})}r(yht,"AccessStep");function $V({agents:e,agentsLoading:s=!1,authKind:n,grantKinds:a,grantKind:i,setGrantKind:o,installChoice:l,setInstallChoice:c,installAgentIds:d,setInstallAgentIds:u,lockedAgentId:h,capabilities:p,githubIdentity:f=!1,submitLabel:x,continuesToProvider:g=!1,identityLoading:v=!1,preserveAgentAccess:y=!1,pending:k=!1,hideFooter:w=!1,bare:N=!1,onBack:S,onContinue:C}){const _=p?.editableAgentIds,R=_?e.filter(z=>_.includes(z.id)):e,I=p?.canSetCompanyInstall??!0,T=p?.canCreateOrganizationGrant??!0,E=n!=="none",L=a??["user","organization"],O=(!E||i==="user"||i==="agent"||T)&&(y?!0:h?d.has(h):i==="agent"?l==="specific"&&d.size===1:l==="all"?I:d.size>0),P=h?e.find(z=>z.id===h)?.name??"the requesting agent":null,Q=f?"Connect GitHub as":"Which humans can use this credential?",D=i==="agent"?"Which agent owns this GitHub account?":f&&i==="user"?"Which agents may use your GitHub when you’re responsible?":f?"Which agents may use the shared GitHub account?":"Which agents can use this connection?",F=f?D:"Which agents can use this connection?";return(0,t.jsxs)("div",{className:N?"":"mx-auto max-w-2xl",children:[(0,t.jsx)("div",{className:"overflow-hidden rounded-xl border border-border bg-background",children:(0,t.jsxs)("div",{className:"divide-y divide-border",children:[(0,t.jsxs)("section",{className:"p-6",children:[(0,t.jsx)("h2",{className:"text-sm font-semibold text-foreground",children:Q}),f&&i==="agent"?(0,t.jsx)("p",{className:"mt-2 text-sm text-muted-foreground",children:"This agent uses this GitHub account for everyone’s work, instead of the person giving instructions."}):null,v?(0,t.jsxs)("div",{className:"mt-4 grid gap-2 sm:grid-cols-2","aria-label":"Loading connection identity",children:[(0,t.jsx)(wn,{className:"h-20 w-full rounded-md"}),(0,t.jsx)(wn,{className:"h-20 w-full rounded-md"})]}):E&&L.length===1?(0,t.jsxs)("div",{className:"mt-4 flex items-center gap-3 rounded-md border border-border p-4",children:[L[0]==="user"?(0,t.jsx)(th,{className:"h-4 w-4 shrink-0 text-muted-foreground","aria-hidden":"true"}):L[0]==="agent"?(0,t.jsx)(io,{className:"h-4 w-4 shrink-0 text-muted-foreground","aria-hidden":"true"}):(0,t.jsx)(Nk,{className:"h-4 w-4 shrink-0 text-muted-foreground","aria-hidden":"true"}),(0,t.jsxs)("div",{children:[(0,t.jsx)("div",{className:"text-sm font-medium text-foreground",children:L[0]==="user"?f?"My GitHub account":"Just me":L[0]==="agent"?"A dedicated account for an agent":f?"Shared organization GitHub account (advanced)":"Any human in the organization"}),f?(0,t.jsx)("p",{className:"mt-1 text-xs text-muted-foreground",children:L[0]==="user"?"Agents use it only for runs where you are the responsible person.":L[0]==="agent"?"That agent always uses this account, regardless of who starts the run.":"Eligible agents use one shared credential, regardless of who starts the run."}):null]})]}):E?(0,t.jsx)(em,{ariaLabel:f?Q:"Which humans can use this credential?",className:"mt-4 sm:grid-cols-2",value:i,onValueChange:r(z=>{const K=z;o(K),K==="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)(th,{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)(io,{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)(Nk,{className:"h-4 w-4","aria-hidden":"true"}),accessibleLabel:T?f?"Shared organization GitHub account (advanced)":"Any human in the organization":`${f?"Shared organization GitHub account (advanced)":"Any human in the organization"}. Unavailable: ${p?.organizationGrantReason??"Only a connection manager can share this credential with the organization."}`,tooltip:T?void 0:p?.organizationGrantReason??"Only a connection manager can share this credential with the organization.",disabled:!T}].filter(z=>L.includes(z.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:D}),y?(0,t.jsxs)("div",{className:"mt-4 flex items-start gap-3 rounded-md border border-border bg-muted/40 p-4",children:[(0,t.jsx)(Nk,{className:"mt-0.5 h-4 w-4 shrink-0 text-primary","aria-hidden":"true"}),(0,t.jsxs)("div",{children:[(0,t.jsx)("div",{className:"text-sm font-medium text-foreground",children:"Existing agent access stays the same"}),(0,t.jsx)("p",{className:"mt-1 text-xs text-muted-foreground",children:"Reconnecting replaces the credential without changing which agents can use it."})]})]}):h?(0,t.jsxs)("p",{className:"mt-2 text-sm text-muted-foreground",children:["This task grants access only to ",(0,t.jsx)("span",{className:"font-medium text-foreground",children:P}),". Existing connection access is left unchanged."]}):i==="agent"?(0,t.jsx)("p",{className:"mt-2 text-sm text-muted-foreground",children:"Choose exactly one agent. This identity cannot be shared with other agents."}):(0,t.jsx)(em,{ariaLabel:F,className:"mt-4 sm:grid-cols-2",value:l,onValueChange:r(z=>c(z),"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)(io,{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)(jht,{}),accessibleLabel:I?"Any agent":`Any agent. Unavailable: ${p?.companyInstallReason??"Only someone who can configure this connection can choose this."}`,tooltip:I?void 0:p?.companyInstallReason??"Only someone who can configure this connection can choose this.",disabled:!I}]}),!y&&!h&&l==="specific"?(0,t.jsx)("div",{className:"mt-3",children:(0,t.jsx)(Jj,{agents:R,selectedAgentIds:d,onChange:r(z=>u(i==="agent"&&z.size>1?new Set([[...z].at(-1)]):z),"onChange"),loading:s,emptyMessage:"You cannot edit any agents yet.",showSelectionPreview:!1})}):null]})]})}),w?null:(0,t.jsxs)("div",{className:"mt-6 flex flex-col-reverse gap-2 sm:flex-row sm:items-center sm:justify-between",children:[(0,t.jsx)($,{variant:"ghost",className:"w-full sm:w-auto",onClick:S,disabled:k,children:"Back"}),(0,t.jsxs)($,{className:"w-full sm:w-auto",onClick:C,disabled:!O||v||k,children:[k?(0,t.jsx)(st,{className:"h-4 w-4 animate-spin","aria-hidden":"true"}):null,x,!k&&g?(0,t.jsx)(oo,{className:"h-4 w-4","aria-hidden":"true"}):null]})]})]})}r($V,"AccessStepContent");function LE(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(LE,"connectionDefaultSummarySentence");function OV({companyId:e,agents:s,sentence:n,notice:a,extra:i,forceOpen:o=!1,disabled:l=!1,...c}){const[d,u]=(0,m.useState)(!1);return(0,t.jsxs)(tl,{open:d||o,onOpenChange:u,className:"mt-6 rounded-lg border border-border bg-muted/30 px-4 py-3",children:[(0,t.jsxs)("div",{className:"flex flex-wrap items-baseline justify-between gap-x-3 gap-y-1",children:[(0,t.jsx)("p",{className:"text-sm text-muted-foreground",children:n}),(0,t.jsx)(Dl,{asChild:!0,children:(0,t.jsx)($,{type:"button",variant:"link",className:"h-auto p-0 text-xs font-semibold underline underline-offset-2",disabled:l,children:"Change"})})]}),(a??[]).map(h=>(0,t.jsx)("p",{className:"mt-2 text-xs text-muted-foreground",children:h},h)),(0,t.jsx)(sl,{children:(0,t.jsxs)("div",{className:"mt-3 space-y-6",children:[i,s?(0,t.jsx)($V,{...c,agents:s,bare:!0,hideFooter:!0,submitLabel:"",onBack:r(()=>{},"onBack"),onContinue:r(()=>{},"onContinue")}):(0,t.jsx)(yht,{...c,companyId:e,bare:!0,hideFooter:!0,submitLabel:"",onBack:r(()=>{},"onBack"),onContinue:r(()=>{},"onContinue")})]})})]})}r(OV,"ConnectionAccessDefaults");function jht(){return(0,t.jsxs)("span",{className:"relative block h-4 w-5","aria-hidden":"true",children:[(0,t.jsx)(io,{className:"absolute left-0 top-0 h-3.5 w-3.5"}),(0,t.jsx)(io,{className:"absolute bottom-0 right-0 h-3.5 w-3.5"})]})}r(jht,"BotGroupIcon");function wht(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(wht,"accessSummaryLines");function kht({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)(cs,{className:"h-9 w-9 text-emerald-600 dark:text-emerald-400"})}),(0,t.jsxs)("div",{className:"mt-6 flex items-center justify-center gap-2",children:[(0,t.jsx)(Vi,{name:e,logoUrl:s,darkLogoUrl:n,size:28}),(0,t.jsxs)("h2",{className:"text-2xl font-bold tracking-tight",children:[e," is ready."]})]}),i?(0,t.jsx)("p",{className:"mt-3 text-sm text-muted-foreground",children:i}):null,(0,t.jsx)("dl",{className:"mx-auto mt-6 max-w-xs space-y-1 text-left",children:a.map(l=>(0,t.jsxs)("div",{className:"flex items-baseline justify-between gap-4",children:[(0,t.jsx)("dt",{className:"text-xs font-medium text-muted-foreground",children:l.label}),(0,t.jsx)("dd",{className:"text-sm text-foreground",children:l.value})]},l.label))}),(0,t.jsx)("div",{className:"mt-8",children:(0,t.jsx)($,{size:"lg",className:"px-10",onClick:o,children:"View connection"})})]})}r(kht,"ConnectionSetupCompletionScreen");function p5e(){const{newProjectOpen:e,closeNewProject:s}=_3(),{selectedCompanyId:n}=ps();return n&&e?(0,t.jsx)(Nht,{companyId:n,onClose:s},n):null}r(p5e,"NewProjectDialog");function Nht({companyId:e,onClose:s}){const n=kt(),[a,i]=(0,m.useState)(""),[o]=(0,m.useState)(()=>g6[Math.floor(Math.random()*g6.length)]),[l,c]=(0,m.useState)([]),[d,u]=(0,m.useState)(!1),h=(0,m.useRef)(null),p=je({mutationFn:r(()=>oa.create(e,{name:a.trim(),color:o,status:"planned",repositoryIds:l.map(f=>f.id)}),"mutationFn"),onSuccess:r(f=>{qb(f.id,e),n.invalidateQueries({queryKey:M.projects.all(e)}),s()},"onSuccess")});return(0,t.jsx)(qs,{open:!0,onOpenChange:r(f=>{!f&&!p.isPending&&s()},"onOpenChange"),children:(0,t.jsx)(Ws,{showCloseButton:!1,"aria-describedby":void 0,className:"flex max-h-(--sz-calc-18) flex-col gap-0 overflow-hidden p-0 shadow-sm sm:max-w-lg",onOpenAutoFocus:r(f=>{f.preventDefault(),h.current?.focus()},"onOpenAutoFocus"),children:d?(0,t.jsxs)("div",{className:"min-h-0 overflow-y-auto p-5",children:[(0,t.jsx)(Qs,{className:"sr-only",children:"Connect GitHub"}),(0,t.jsx)(ES,{host:"dialog",serviceSlug:"github",forceNewConnection:!0,onCancel:r(()=>u(!1),"onCancel"),onComplete:r(()=>{n.invalidateQueries({queryKey:TH(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)(Qs,{className:"text-lg font-semibold",children:"Create project"}),(0,t.jsx)($,{type:"button",variant:"ghost",size:"icon-sm",disabled:p.isPending,"aria-label":"Close new project",onClick:s,children:(0,t.jsx)(En,{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)(Zm,{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)(_Se,{companyId:e,selected:l,onChange:c,onConnect:r(()=>u(!0),"onConnect"),disabled:p.isPending})}),p.isError&&(0,t.jsx)("p",{role:"alert",className:"px-5 pt-3 text-sm text-destructive",children:p.error.message}),(0,t.jsxs)("div",{className:"flex shrink-0 justify-end gap-2 px-5 py-5",children:[(0,t.jsx)($,{type:"button",variant:"ghost",disabled:p.isPending,onClick:s,children:"Cancel"}),(0,t.jsx)($,{type:"submit",disabled:!a.trim()||p.isPending,children:p.isPending?"Creating…":"Create project"})]})]})})})}r(Nht,"NewProjectForm");var Kx={list:r(e=>we.get(`/companies/${e}/goals`),"list"),get:r(e=>we.get(`/goals/${e}`),"get"),create:r((e,s)=>we.post(`/companies/${e}/goals`,s),"create"),update:r((e,s)=>we.patch(`/goals/${e}`,s),"update"),remove:r(e=>we.delete(`/goals/${e}`),"remove")};function f5e(e){return{"--sc":`var(${e})`}}r(f5e,"scStyle");function Sht(e){const s=e.replace(/_/g," ");return s.charAt(0).toUpperCase()+s.slice(1)}r(Sht,"sentenceCaseStatus");function li({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",lF[e]??"bg-muted text-muted-foreground"),children:s??e.replace(/[_-]/g," ")})}r(li,"StatusBadge$5");function x5e({status:e}){const s=sFe[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:f5e(s),children:n.replace(/_/g," ")})}r(x5e,"AgentStatusBadge");function C0({status:e,externalConversationState:s}){const n=e==="in_review"&&s==="waiting"?"idle":e,a=NFe[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:f5e(a),children:[(0,t.jsx)(x3,{status:n,size:"sm"}),Sht(n)]})}r(C0,"IssueStatusBadge");var Eae={company:"Organization",team:"Team",agent:"Agent",task:"Task"};function g5e(){const{newGoalOpen:e,newGoalDefaults:s,closeNewGoal:n}=_3(),{selectedCompanyId:a,selectedCompany:i}=ps(),o=kt(),[l,c]=(0,m.useState)(""),[d,u]=(0,m.useState)(""),[h,p]=(0,m.useState)("planned"),[f,x]=(0,m.useState)("task"),[g,v]=(0,m.useState)(""),[y,k]=(0,m.useState)(!1),[w,N]=(0,m.useState)(!1),[S,C]=(0,m.useState)(!1),[_,R]=(0,m.useState)(!1),I=(0,m.useRef)(null),T=g||s.parentId||"",{data:E}=te({queryKey:M.goals.list(a),queryFn:r(()=>Kx.list(a),"queryFn"),enabled:!!a&&e}),L=je({mutationFn:r(z=>Kx.create(a,z),"mutationFn"),onSuccess:r(()=>{o.invalidateQueries({queryKey:M.goals.list(a)}),P(),n()},"onSuccess")}),O=je({mutationFn:r(async z=>{if(!a)throw new Error("No organization selected");return fv.uploadImage(a,z,"goals/drafts")},"mutationFn")});function P(){c(""),u(""),p("planned"),x("task"),v(""),k(!1)}r(P,"reset");function Q(){!a||!l.trim()||L.mutate({title:l.trim(),description:d.trim()||void 0,status:h,level:f,...T?{parentId:T}:{}})}r(Q,"handleSubmit");function D(z){z.key==="Enter"&&(z.metaKey||z.ctrlKey)&&(z.preventDefault(),Q())}r(D,"handleKeyDown");const F=(E??[]).find(z=>z.id===T);return(0,t.jsx)(qs,{open:e,onOpenChange:r(z=>{z||(P(),n())},"onOpenChange"),children:(0,t.jsxs)(Ws,{showCloseButton:!1,className:W("p-0 gap-0",y?"sm:max-w-2xl":"sm:max-w-lg"),onKeyDown:D,children:[(0,t.jsxs)("div",{className:"flex items-center justify-between px-4 py-2.5 border-b border-border",children:[(0,t.jsxs)("div",{className:"flex items-center gap-2 text-sm text-muted-foreground",children:[i&&(0,t.jsx)("span",{className:"bg-muted px-1.5 py-0.5 rounded text-xs font-medium",children:i.issuePrefix}),(0,t.jsx)("span",{className:"text-muted-foreground/60",children:"›"}),(0,t.jsx)("span",{children:s.parentId?"New sub-goal":"New goal"})]}),(0,t.jsxs)("div",{className:"flex items-center gap-1",children:[(0,t.jsx)($,{variant:"ghost",size:"icon-xs",className:"text-muted-foreground",onClick:r(()=>k(!y),"onClick"),children:y?(0,t.jsx)(Owe,{className:"h-3.5 w-3.5"}):(0,t.jsx)(tw,{className:"h-3.5 w-3.5"})}),(0,t.jsx)($,{variant:"ghost",size:"icon-xs",className:"text-muted-foreground",onClick:r(()=>{P(),n()},"onClick"),children:(0,t.jsx)("span",{className:"text-lg leading-none",children:"×"})})]})]}),(0,t.jsx)("div",{className:"px-4 pt-4 pb-2 shrink-0",children:(0,t.jsx)("input",{className:"w-full text-lg font-semibold bg-transparent outline-none placeholder:text-muted-foreground/50",placeholder:"Goal title",value:l,onChange:r(z=>c(z.target.value),"onChange"),onKeyDown:r(z=>{z.key==="Tab"&&!z.shiftKey&&(z.preventDefault(),I.current?.focus())},"onKeyDown"),autoFocus:!0})}),(0,t.jsx)("div",{className:"px-4 pb-2 overflow-y-auto max-h-(--sz-50vh)",children:(0,t.jsx)(Jc,{ref:I,value:d,onChange:u,placeholder:"Add description...",bordered:!1,contentClassName:W("text-sm text-muted-foreground",y?"min-h-(--sz-220px)":"min-h-(--sz-120px)"),imageUploadHandler:r(async z=>(await O.mutateAsync(z)).contentPath,"imageUploadHandler")})}),(0,t.jsxs)("div",{className:"flex items-center gap-1.5 px-4 py-2 border-t border-border flex-wrap",children:[(0,t.jsxs)(dr,{open:w,onOpenChange:N,children:[(0,t.jsx)(wr,{asChild:!0,children:(0,t.jsx)("button",{className:"inline-flex items-center gap-1.5 rounded-md border border-border px-2 py-1 text-xs hover:bg-accent/50 transition-colors",children:(0,t.jsx)(li,{status:h})})}),(0,t.jsx)(sr,{className:"w-40 p-1",align:"start",children:Rbe.map(z=>(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",z===h&&"bg-accent"),onClick:r(()=>{p(z),N(!1)},"onClick"),children:z},z))})]}),(0,t.jsxs)(dr,{open:S,onOpenChange:C,children:[(0,t.jsx)(wr,{asChild:!0,children:(0,t.jsxs)("button",{className:"inline-flex items-center gap-1.5 rounded-md border border-border px-2 py-1 text-xs hover:bg-accent/50 transition-colors",children:[(0,t.jsx)(Gl,{className:"h-3 w-3 text-muted-foreground"}),Eae[f]??f]})}),(0,t.jsx)(sr,{className:"w-40 p-1",align:"start",children:rbe.map(z=>(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",z===f&&"bg-accent"),onClick:r(()=>{x(z),C(!1)},"onClick"),children:Eae[z]??z},z))})]}),(0,t.jsxs)(dr,{open:_,onOpenChange:R,children:[(0,t.jsx)(wr,{asChild:!0,children:(0,t.jsxs)("button",{className:"inline-flex items-center gap-1.5 rounded-md border border-border px-2 py-1 text-xs hover:bg-accent/50 transition-colors",children:[(0,t.jsx)(K0,{className:"h-3 w-3 text-muted-foreground"}),F?F.title:"Parent goal"]})}),(0,t.jsxs)(sr,{className:"w-48 p-1",align:"start",children:[(0,t.jsx)("button",{className:W("flex items-center gap-2 w-full px-2 py-1.5 text-xs rounded hover:bg-accent/50",!T&&"bg-accent"),onClick:r(()=>{v(""),R(!1)},"onClick"),children:"No parent"}),(E??[]).map(z=>(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",z.id===T&&"bg-accent"),onClick:r(()=>{v(z.id),R(!1)},"onClick"),children:z.title},z.id))]})]})]}),(0,t.jsx)("div",{className:"flex items-center justify-end px-4 py-2.5 border-t border-border",children:(0,t.jsx)($,{size:"sm",disabled:!l.trim()||L.isPending,onClick:Q,children:L.isPending?"Creating…":s.parentId?"Create sub-goal":"Create goal"})})]})})}r(g5e,"NewGoalDialog");var vD=r((e,s)=>`/companies/${e}/agents/${s}/dot-binding`,"path"),OI={create:r(e=>we.post(`/companies/${e}/dot-invitations`,{}),"create"),connection:r((e,s,n)=>we.get(vD(e,s),{signal:n}),"connection"),pair:r((e,s,n)=>we.post(vD(e,s),{replaceBindingId:n}),"pair"),retry:r((e,s,n)=>we.post(vD(e,s)+"/event-test",{bindingId:n}),"retry")};function Cht(e){const s=_ht(e),n=Aht(e);return`You're invited to join a Paperclip company as an agent.
331
331
 
332
332
  First, respond to your user that you understand the request and are going to onboard into Paperclip. Then work through the steps below.
333
333
 
@@ -379,7 +379,7 @@ ${Z$e}
379
379
  `}r(Cht,"buildAgentOnboardingPrompt");function _ht(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(_ht,"buildCandidateOnboardingUrls");function Aht(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(Aht,"buildResolutionTestUrl");function b5e({children:e,className:s,...n}){const[a,i]=(0,m.useState)(null),o=(0,m.useRef)(null),l=mW();return(0,m.useLayoutEffect)(()=>{const c=a,d=o.current;if(!c||!d||typeof ResizeObserver>"u")return;let u,h;const p=new ResizeObserver(()=>{const f=getComputedStyle(c),x=d.getBoundingClientRect().height+parseFloat(f.borderTopWidth)+parseFloat(f.borderBottomWidth);if(x===u)return;const g=h?.playState==="running"?c.getBoundingClientRect().height:u;if(h?.cancel(),u=x,g===void 0||l||typeof c.animate!="function")return;const v=jV("--motion-ease-out-expo");h=c.animate([{height:`${g}px`},{height:`${x}px`}],{duration:j5("--onboarding-motion-step"),easing:Array.isArray(v)?`cubic-bezier(${v.join(",")})`:v})});return p.observe(d),()=>{p.disconnect(),h?.cancel()}},[a,l]),(0,t.jsx)(Ws,{...n,ref:i,className:W("overflow-hidden p-0",s),children:(0,t.jsx)("div",{ref:o,className:"flex max-h-(--sz-calc-18) shrink-0 flex-col",children:e})})}r(b5e,"AnimatedDialogContent");var v5e=[{id:"dot",name:"Dot",adapter:"openai_dot",description:"Your Dot in ChatGPT"},{id:"hermes",name:"Hermes",adapter:"hermes_gateway",description:"An existing Hermes agent"},{id:"other",name:"Other",adapter:"http",description:"Any agent that can connect to Paperclip"}];function Hz({onSelect:e,dotDisabledReason:s}){return(0,t.jsx)("div",{className:"grid grid-cols-2 gap-3 sm:grid-cols-3",children:v5e.map(n=>(0,t.jsxs)("button",{type:"button",onClick:r(()=>e(n.id),"onClick"),disabled:n.id==="dot"&&!!s,title:n.id==="dot"?s:void 0,className:"flex aspect-square flex-col items-center justify-center gap-3 rounded-lg border border-border bg-card px-3 py-4 text-center transition-colors disabled:opacity-50 hover:bg-accent/40 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring",children:[(0,t.jsx)(B0,{type:n.adapter,className:"size-8"}),(0,t.jsx)("span",{className:"text-sm font-medium",children:n.name}),(0,t.jsx)("span",{className:"sr-only",children:n.description})]},n.id))})}r(Hz,"ExternalAgentPresetPicker");var Iht=[{title:"Connected to Paperclip",description:"Your Dot has connected to this agent."},{title:"Task updates enabled",description:"Your Dot is subscribed to new assignments and messages."},{title:"Test event confirmed",description:"Your Dot received our test and replied to Paperclip."}];function y5e({state:e}){const s={waiting:0,connected:1,subscribed:2,testing:2,finishing:3,ready:3}[e.phase],n=e.problem==="agent_unavailable"?"Connection checks passed, but this agent cannot receive tasks. Resolve the agent’s setup blocker in Paperclip.":e.problem==="offline"?"Connection updates paused. Reconnect to check the latest status.":e.problem==="prompt_unavailable"?"This setup prompt was replaced in another window. Create a fresh prompt to continue.":e.problem==="event_timeout"?"Your Dot connected, but hasn’t confirmed the test event. Ask it to check Paperclip, then retry.":e.phase==="finishing"?"Your Dot confirmed the test event. Paperclip is finishing agent setup.":e.phase==="ready"?"Your Dot is ready for tasks. Messages can travel both ways.":e.phase==="waiting"?"Watching for your Dot. Updates will appear here automatically.":e.phase==="connected"?"Your Dot connected. Waiting for it to enable task updates.":"Waiting for your Dot to confirm a test event. No task will be created.";return(0,t.jsxs)("section",{"aria-label":"Dot connection checks",className:"space-y-4",children:[(0,t.jsx)("ol",{className:"space-y-4",children:Iht.map((a,i)=>{const o=i<s,l=i===s&&e.problem==="event_timeout",c=i===s&&!e.problem,d=o?cs:l?eo:c?st:ff;return(0,t.jsxs)("li",{className:"flex items-start gap-3","aria-current":c?"step":void 0,children:[(0,t.jsx)("span",{className:W("flex size-6 shrink-0 items-center justify-center rounded-full",o?"bg-accent text-foreground":l?"text-destructive":"text-muted-foreground"),children:(0,t.jsx)(d,{className:W("size-4",c&&"animate-spin motion-reduce:animate-none")})}),(0,t.jsxs)("div",{className:"min-w-0 pt-0.5",children:[(0,t.jsxs)("p",{className:W("text-sm",o||c||l?"font-medium":"text-muted-foreground"),children:[a.title,(0,t.jsx)("span",{className:"sr-only",children:o?": complete":l?": needs attention":c?": in progress":": waiting"})]}),o&&(0,t.jsx)("p",{className:"mt-1 text-xs leading-relaxed text-muted-foreground",children:a.description})]})]},a.title)})}),(0,t.jsx)("p",{role:e.problem&&e.problem!=="prompt_unavailable"?"alert":"status","aria-live":"polite",className:W("text-sm leading-relaxed",e.problem&&e.problem!=="prompt_unavailable"?"text-destructive":"text-muted-foreground"),children:n})]})}r(y5e,"DotConnectionChecks");function Tht({preset:e,prompt:s,companyName:n,connection:a,onSelect:i,onBack:o,onClose:l,onCopied:c,onRetry:d,onNewPrompt:u,dotDisabledReason:h,busy:p=!1,error:f,approvalHref:x}){const g=v5e.find(N=>N.id===e),v=e==="dot",y=v&&a.phase==="ready"&&!a.problem,k=v&&a.phase!=="waiting",w=a.problem==="agent_unavailable"?"Agent unavailable":a.problem==="offline"?"Updates paused":a.problem==="event_timeout"?"Needs attention":a.phase==="finishing"?"Finishing setup…":a.phase==="connected"?"Connecting…":"Confirming connection…";return(0,t.jsxs)(t.Fragment,{children:[(0,t.jsxs)("div",{className:"min-h-0 space-y-6 overflow-y-auto px-6 pb-6 pt-8 sm:px-8",children:[(0,t.jsxs)("div",{className:"space-y-3 pr-5",children:[g&&(0,t.jsx)(B0,{type:g.adapter,className:"size-10"}),(0,t.jsxs)("div",{className:"space-y-2",children:[(0,t.jsx)(Qs,{className:"text-xl font-semibold tracking-tight",children:g?v?y?"Your Dot is connected":"Connect your Dot":e==="hermes"?"Invite your Hermes agent":"Invite your agent":"Invite an external agent"}),(0,t.jsx)(mn,{className:"text-sm leading-relaxed",children:g?y?`Your Dot can now receive assignments and work with ${n}.`:a.problem==="agent_unavailable"?"Your Dot is connected. This agent must be available in Paperclip before it can receive assignments.":a.phase==="finishing"?"Your Dot has connected and confirmed task updates. Paperclip is preparing it for assignments.":k?"Your Dot has connected. We’re checking that task updates can travel both ways.":v?"Copy the setup prompt and send it to your Dot in ChatGPT. Your Dot will connect itself; we’ll watch for it here.":`Copy the invitation prompt and send it to your ${e==="hermes"?"Hermes ":""}agent. Approve its join request in Paperclip when it’s ready.`:`Bring an agent you already use into ${n}.`})]})]}),f&&(0,t.jsxs)("div",{role:"alert",className:"space-y-3 text-sm text-destructive",children:[(0,t.jsx)("p",{children:f}),(0,t.jsx)($,{variant:"outline",disabled:p,onClick:d,children:"Try again"})]}),g?x?(0,t.jsx)("p",{className:"text-sm text-muted-foreground",children:"An organization admin needs to approve this agent before Dot can connect. This page will update after approval."}):p&&!s&&a.phase==="waiting"?(0,t.jsx)("p",{role:"status",className:"text-sm text-muted-foreground",children:"Preparing your invitation…"}):v?(0,t.jsxs)(t.Fragment,{children:[(0,t.jsxs)("div",{className:"border-t pt-6",children:[(0,t.jsx)(y5e,{state:a}),a.phase==="waiting"&&(0,t.jsx)("p",{className:"mt-4 text-xs text-muted-foreground",children:"Dot uses your OpenAI account. Provider usage and cost aren’t reported to Paperclip."})]}),a.problem==="event_timeout"&&(0,t.jsx)($,{variant:"outline",disabled:p,onClick:d,children:"Retry test event"}),a.problem==="offline"&&(0,t.jsx)($,{variant:"outline",disabled:p,onClick:d,children:"Reconnect updates"})]}):(0,t.jsxs)("p",{className:"text-sm leading-relaxed text-muted-foreground",children:["The invitation includes everything your agent needs to join ",n,". You can review its request before granting access."]}):(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)(Hz,{onSelect:i,dotDisabledReason:h}),h&&(0,t.jsx)("p",{className:"text-sm text-muted-foreground",children:h})]})]}),(0,t.jsxs)("div",{className:"flex items-center justify-between gap-3 border-t px-6 py-4 sm:px-8",children:[(0,t.jsxs)($,{variant:"ghost",onClick:g?o:l,children:[g&&(0,t.jsx)(wl,{className:"size-4"}),g?"Back":"Cancel"]}),g&&(x?(0,t.jsx)($,{asChild:!0,children:(0,t.jsx)(Ke,{to:x,onClick:l,children:"Review approval"})}):y?(0,t.jsx)($,{onClick:l,children:"Done"}):k?(0,t.jsxs)($,{disabled:!0,"aria-live":"polite",children:[!a.problem&&(0,t.jsx)(st,{className:"size-4 animate-spin motion-reduce:animate-none","aria-hidden":"true"}),w]}):v&&a.problem==="prompt_unavailable"?(0,t.jsx)($,{disabled:p,onClick:u,children:"Create a new prompt"}):!s||p?(0,t.jsx)($,{disabled:!0,children:p?"Preparing…":"Waiting for Dot…"}):(0,t.jsx)(tv,{prompt:s,label:v?"Copy setup prompt":"Copy invitation prompt",title:v?"Connect your Dot":"Invite your agent",description:v?"Send this whole prompt to your Dot in ChatGPT.":"Send this whole prompt to your agent.",agent:v?{name:"Dot",src:"/brands/adapters/openai-dot.svg"}:void 0,align:"end",className:"min-w-0 shrink",onCopied:c},e))]})]})}r(Tht,"ExternalAgentInviteContent");function Rht({companyId:e,onClose:s,onBack:n}){const a=kt(),{selectedCompany:i}=ps(),[o,l]=(0,m.useState)(null),[c,d]=(0,m.useState)(null),[u,h]=(0,m.useState)(null),[p,f]=(0,m.useState)(null),[x,g]=(0,m.useState)(""),v=(0,m.useRef)(!1),y=te({queryKey:M.instance.experimentalSettings,queryFn:jr.getExperimental}),k=y.isPending?"Loading available agents…":y.error?"Unable to load experimental settings. Try again after refreshing.":!y.data?.enableOpenAiDot||!y.data.enablePublicMcp?"Enable OpenAI Dot and Assistant connections (MCP) in experimental settings.":void 0,w=["dot-binding",e,c?.agent.id],N=te({queryKey:w,queryFn:r(({signal:U})=>OI.connection(e,c.agent.id,U),"queryFn"),enabled:o==="dot"&&!!c,retry:!1,staleTime:0,refetchInterval:r(U=>U.state.error||U.state.data?.agentLifecycleState==="ready"&&U.state.data.canConfigureConnection&&U.state.data.binding?.status==="ready"&&U.state.data.binding.subscriptionVerified?!1:2500,"refetchInterval")}),S=je({mutationFn:r(async U=>{if(U==="dot"){const Z=await OI.create(e);d(Z),await a.invalidateQueries({queryKey:M.agents.list(e)});return}const q=await ir.createCompanyInvite(e,{allowedJoinTypes:"agent",humanRole:null,agentMessage:null});a.invalidateQueries({queryKey:M.access.invites(e,"all",5)});const G=q.onboardingTextUrl??q.onboardingTextPath??`/api/invites/${q.token}/onboarding.txt`,se=await ir.getInviteOnboarding(q.token).catch(()=>null);g(Cht({onboardingTextUrl:new URL(G,window.location.origin).href,connectionCandidates:se?.onboarding.connectivity?.connectionCandidates??null,testResolutionUrl:se?.onboarding.connectivity?.testResolutionEndpoint?.url??null}))},"mutationFn"),gcTime:0}),C=je({mutationFn:r(async U=>{const q=await OI.pair(e,c.agent.id,U);h(q),f(null)},"mutationFn"),onSuccess:r(()=>{a.invalidateQueries({queryKey:w})},"onSuccess"),onError:r(()=>{N.refetch()},"onError"),gcTime:0}),_=je({mutationFn:r(()=>OI.retry(e,c.agent.id,N.data.binding.id),"mutationFn"),onSuccess:r(()=>{a.invalidateQueries({queryKey:w})},"onSuccess")}),R=N.data?.binding,I=o==="dot"&&N.data?.enabled&&!!N.data.resourceUrl&&N.data.canConfigureConnection&&(!R||R.status==="pairing")&&!u&&!N.error&&!C.isError&&!v.current&&(!p||R?.id===p);(0,m.useEffect)(()=>{I&&N.isFetchedAfterMount&&!N.isFetching&&!C.isPending&&(v.current=!0,C.mutate(R?.id))},[I,N.isFetchedAfterMount,N.isFetching,C.isPending,C.mutate,R?.id]),(0,m.useEffect)(()=>{if(!u)return;const U=window.setTimeout(()=>{v.current=!1,f(u.bindingId),h(null)},Math.max(0,Date.parse(u.expiresAt)-Date.now()));return()=>window.clearTimeout(U)},[u]);const T=R?.status==="ready"&&R.subscriptionVerified,E=N.data?.agentLifecycleState==="ready"&&N.data.canConfigureConnection,L=["preparing","verifying"].includes(N.data?.agentLifecycleState??"")&&N.data?.canConfigureConnection,O={phase:T?E?"ready":L?"finishing":"ready":R?.hasPendingChallenge?"testing":R?.subscriptionVerified?"subscribed":R?.connected?"connected":"waiting",problem:N.error?"offline":T&&!E&&!L?"agent_unavailable":R?.status==="pairing"&&!I&&!C.isPending&&!N.isFetching&&!C.isError&&u?.bindingId!==R.id?"prompt_unavailable":R?.challengeExpiresAt&&!R.hasPendingChallenge&&R.status!=="ready"?"event_timeout":void 0},P=(N.data?.agentStatus??c?.agent.status)==="pending_approval",Q=N.data&&!N.data.canConfigureConnection&&!P,D=o==="dot"?u&&u.bindingId===R?.id&&N.data?.resourceUrl&&c?c_e({companyId:e,agentId:c.agent.id,resourceUrl:N.data.resourceUrl,...u}):"":x,F=(S.variables===o?S.error:null)??(o==="dot"?(R?.connected?null:C.error)??_.error:null),z=S.isPending||C.isPending||_.isPending||I||o==="dot"&&!!c&&(N.isPending||!D&&N.isFetching),K=r(()=>{if(Q){N.refetch();return}if(N.error){N.refetch();return}if(S.error||!c){o&&S.mutate(o);return}if(C.error&&!R?.connected){C.mutate(R?.status==="pairing"?R.id:void 0);return}_.mutate()},"retry");return(0,t.jsx)(qs,{open:!0,onOpenChange:r(U=>{U||s()},"onOpenChange"),children:(0,t.jsx)(b5e,{className:"sm:max-w-(--sz-560px)",children:(0,t.jsx)(Tht,{preset:o,prompt:D,companyName:i?.name??"your organization",connection:O,dotDisabledReason:k,busy:z,error:F?.message??(Q?N.data?.agentLifecycleState==="terminated"?"This agent was terminated. Invite another agent to connect Dot.":"Resume this agent before connecting Dot.":void 0),approvalHref:P&&c?.approvalId?`/approvals/${c.approvalId}`:void 0,onSelect:r(U=>{l(U),(U==="dot"?!c:!x)&&S.mutate(U)},"onSelect"),onBack:r(()=>l(null),"onBack"),onClose:o?s:n,onCopied:r(()=>{o==="dot"&&N.refetch()},"onCopied"),onRetry:K,onNewPrompt:r(()=>C.mutate(R?.id),"onNewPrompt")})})})}r(Rht,"ExternalAgentInviteDialog");function j5e(){const{newAgentOpen:e,closeNewAgent:s}=_3(),{selectedCompanyId:n}=ps();return e?(0,t.jsx)(Eht,{companyId:n,onClose:s},n):null}r(j5e,"NewAgentDialog");function Eht({companyId:e,onClose:s}){const n=Yn(),[a,i]=(0,m.useState)(!1);return a&&e?(0,t.jsx)(Rht,{companyId:e,onClose:s,onBack:r(()=>i(!1),"onBack")}):(0,t.jsx)(t5e,{open:!0,onClose:s,onInvite:e?()=>i(!0):void 0,onContinue:r(o=>{s(),n(`/agents/new?${new URLSearchParams(o)}`)},"onContinue")})}r(Eht,"NewAgentDialogContent");var Lht=[{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 Lae({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(Lae,"KeyCap");function Mht(){return(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)("div",{className:"divide-y divide-border border-t border-border",children:Lht.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)(Lae,{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)(Lae,{children:"Esc"})," to close · Shortcuts are disabled in text fields"]})})]})}r(Mht,"KeyboardShortcutsCheatsheetContent");function w5e({open:e,onOpenChange:s}){return(0,t.jsx)(qs,{open:e,onOpenChange:s,children:(0,t.jsxs)(Ws,{className:"sm:max-w-md gap-0 p-0 overflow-hidden",showCloseButton:!1,children:[(0,t.jsx)(ln,{className:"px-5 pt-5 pb-3",children:(0,t.jsx)(Qs,{className:"text-base",children:"Keyboard shortcuts"})}),(0,t.jsx)(Mht,{})]})})}r(w5e,"KeyboardShortcutsCheatsheet");var Pht={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"},Dht={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 $ht({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",Pht[e.tone]),children:(0,t.jsxs)("div",{className:"flex items-start gap-3 px-3 py-2.5",children:[e.actor?.type==="agent"?(0,t.jsx)(lr,{agent:{id:e.actor.id,name:e.actor.name,appearance:e.actor.appearance},size:24}):e.actor?.type==="user"?(0,t.jsxs)(ko,{size:"sm","aria-hidden":"true",children:[e.actor.image&&(0,t.jsx)(Zc,{src:e.actor.image,alt:""}),(0,t.jsx)(No,{children:uv(e.actor.name)})]}):(0,t.jsx)("span",{className:W("mt-1 h-2 w-2 shrink-0 rounded-full",Dht[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)(En,{className:"h-3.5 w-3.5"})})]})})}r($ht,"AnimatedToast");function k5e(){const e=Vqe(),{dismissToast:s}=Xr();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)($ht,{toast:n,onDismiss:s},n.id))})})}r(k5e,"ToastViewport");function qv(e,s){return`${e}?${new URLSearchParams({companyId:s}).toString()}`}r(qv,"scoped$1");function Mae(e,s=""){return`/local-browser/sessions/${encodeURIComponent(e)}${s}`}r(Mae,"sessionPath");var lb={startPairing:r((e,s={})=>we.post(qv("/local-browser/pairing",e),s),"startPairing"),pairingStatus:r((e,s)=>we.get(qv(`/local-browser/pairing/${encodeURIComponent(s)}`,e),{cache:"no-store"}),"pairingStatus"),sessions:r(e=>we.get(qv("/local-browser/sessions",e),{cache:"no-store"}),"sessions"),disconnect:r((e,s)=>we.delete(qv(Mae(s),e)),"disconnect"),openPermissions:r((e,s)=>we.post(qv(Mae(s,"/open-permissions"),e),{}),"openPermissions"),settings:r(e=>we.get(qv("/local-browser/settings",e),{cache:"no-store"}),"settings"),saveSettings:r((e,s)=>we.post(qv("/local-browser/settings",e),s),"saveSettings")};function Oht(){let e;return{promise:new Promise(s=>{e=s}),resolve:e}}r(Oht,"createDeferred");function Bht(e,s=300){const n=new Map;let a=null,i=null;const o=r(async()=>{a!==null&&(clearTimeout(a),a=null);const d=i;if(i=null,n.size===0){d?.resolve();return}const u=[...n.values()];n.clear();try{await Promise.all(u.map(h=>e.invalidateQueries(oN().visible?h:{...h,refetchType:"none"})))}finally{d?.resolve()}},"flush");return{schedule:r(d=>(n.set(Fht(d),d),i===null&&(i=Oht()),a===null&&(a=setTimeout(()=>{o()},s)),i.promise),"schedule"),flush:o,dispose:r(()=>{a!==null&&(clearTimeout(a),a=null),n.clear(),i?.resolve(),i=null},"dispose")}}r(Bht,"createInvalidationBatcher");var Pae=0;function Fht(e){if(typeof e.predicate=="function")return`__predicate__:${Pae+=1}`;try{return JSON.stringify([e.queryKey??null,e.refetchType??null,e.exact??null,e.type??null])}catch{return`__nonserializable__:${Pae+=1}`}}r(Fht,"serializeFilters");function zht(e,s){return new Proxy(e,{get(n,a){if(a==="invalidateQueries")return o=>s.schedule(o??{});const i=Reflect.get(n,a,n);return typeof i=="function"?i.bind(n):i}})}r(zht,"createCoalescingQueryClient");function qht(e,s){if(!e)return e;const n=e.filter(a=>a.id!==s);return n.length===e.length?e:n}r(qht,"removeRunFromList");function Uht(e,s,n){if(!e)return{next:e,present:!1};let a=!1,i=!1;const o=e.map(l=>l.id!==s||(a=!0,l.status===n)?l:(i=!0,{...l,status:n}));return{next:i?o:e,present:a}}r(Uht,"patchRunStatusInList");function Kht(e,s){if(!e)return e;const n=e.filter(a=>a.id!==s);return n.length===e.length?e:n}r(Kht,"removeLiveRunById");function Qht(e,s){return!e||e.executionRunId!==s?e:{...e,executionRunId:null,executionAgentNameKey:null,executionLockedAt:null}}r(Qht,"clearIssueExecutionRun");var Wht=3e4,Hht=["status","priority","title","assigneeAgentId","assigneeUserId","projectId","parentId"],Vht=new Set(["issue.read_marked","issue.read_unmarked","issue.inbox_archived","issue.inbox_unarchived"]);function Vz(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}r(Vz,"isRecord$1");function BV(e){return Vz(e)&&Array.isArray(e.pages)}r(BV,"isInfiniteIssueData");function Ght(e){return Array.isArray(e)?e.length:BV(e)?e.pages.reduce((s,n)=>s+(Array.isArray(n)?n.length:0),0):0}r(Ght,"issueListRowCount");function Yht(e){const s=e.state.data;return BV(s)||Ght(s)>=100}r(Yht,"isLargeIssueListQuery");function Zht(e,s,n){const a={},i=Vz(s?.changes)?s.changes:null;if(e==="issue.updated"&&i)for(const o of Hht){const l=i[o];!Vz(l)||l.updated===!0||!("to"in l)||(a[o]=l.to)}return n&&e&&!Vht.has(e)&&!Number.isNaN(Date.parse(n))&&(a.lastActivityAt=n),a}r(Zht,"readIssueListPatchFromActivity");function Jht(e,s){let n=null;for(const[a,i]of Object.entries(s)){if(a==="lastActivityAt"){const o=e.lastActivityAt?new Date(e.lastActivityAt).getTime():0;if(new Date(i).getTime()<=o)continue}else if(!(a in e)||e[a]===i)continue;n??={...e},n[a]=i}return n??e}r(Jht,"patchIssueRow");function Dae(e,s,n){const a=e.findIndex(l=>l?.id===s);if(a<0)return e;const i=Jht(e[a],n);if(i===e[a])return e;const o=e.slice();return o[a]=i,o}r(Dae,"patchIssueRows");function Xht(e,s,n){if(Array.isArray(e))return Dae(e,s,n);if(!BV(e))return e;let a=!1;const i=e.pages.map(o=>{if(!Array.isArray(o))return o;const l=Dae(o,s,n);return l!==o&&(a=!0),l});return a?{...e,pages:i}:e}r(Xht,"patchIssueListData");function e0t(e,s,n,a){if(Object.keys(a).length===0)return 0;let i=0;for(const[o,l]of e.getQueriesData({queryKey:M.issues.list(s)})){const c=Xht(l,n,a);c!==l&&(e.setQueryData(o,c),i+=1)}return i}r(e0t,"patchIssueInListCaches");function t0t(e,s){for(const n of e.getQueryCache().findAll({queryKey:M.issues.list(s)}))e.invalidateQueries({queryKey:n.queryKey,exact:!0,...Yht(n)?{refetchType:"none"}:{}})}r(t0t,"invalidateIssueListsForActivity");function s0t(e,s){const n=r(a=>a.state.isInvalidated,"predicate");return Promise.all([e.refetchQueries({queryKey:M.issues.list(s),type:"active",predicate:n}),e.refetchQueries({queryKey:M.heartbeats(s),type:"active",predicate:n})])}r(s0t,"refreshInvalidatedLiveLists");function rk(e){return typeof e=="string"&&e.length>0?e:null}r(rk,"readString$7");function n0t(e){return e.length===3&&e[0]==="issues"&&e[2]==="agent-todo"}r(n0t,"isAgentTodoQueryKey");function r0t(e){if(e.type!=="heartbeat.run.event")return null;const s=e.payload??{};if(s.eventType!=="agent.todo")return null;const n=rk(s.runId),a=rk(s.agentId),i=rk(s.issueId),o=s.seq;if(!n||!a||!i||typeof o!="number"||!Number.isInteger(o))return null;const l=uBe(s.payload);return l?{...l,runId:n,agentId:a,issueId:i,seq:o,createdAt:rk(s.lastEventAt)??e.createdAt,runStatus:"running"}:null}r(r0t,"readAgentTodoSnapshotFromLiveEvent");function $ae(e,s){if(s.type==="heartbeat.run.status"){const a=s.payload??{},i=rk(a.runId),o=rk(a.status);if(!i||!o)return;e.setQueriesData({predicate:r(l=>n0t(l.queryKey),"predicate")},l=>l&&l.runId===i&&l.runStatus!==o?{...l,runStatus:o}:l);return}const n=r0t(s);n&&e.setQueryData(M.issues.agentTodo(n.issueId),a=>a&&a.runId===n.runId&&a.seq>=n.seq?a:n)}r($ae,"applyAgentTodoLiveEvent");function a0t(e){const s=e.trim().toLowerCase();return s==="0.0.0.0"||s==="::"||s==="[::]"}r(a0t,"isWildcardHost");function i0t(e=window.location){return a0t(e.hostname)?e.port?`localhost:${e.port}`:"localhost":e.host}r(i0t,"browserReachableHost");function nA(e,s=window.location){const n=s.protocol==="https:"?"wss":"ws",a=e.startsWith("/")?e:`/${e}`;return`${n}://${i0t(s)}${a}`}r(nA,"buildSameOriginWebSocketUrl");function FV(e){try{return new WebSocket(e)}catch{return null}}r(FV,"tryCreateWebSocket");var o0t="/pwa-192x192.png",l0t="/pwa-monochrome-512x512.png";function N5e(){return typeof window<"u"&&"Notification"in window}r(N5e,"notificationsSupported");function g_(){return N5e()?Notification.permission:"unsupported"}r(g_,"notificationPermission");async function c0t(){return N5e()?Notification.permission!=="default"?Notification.permission:Notification.requestPermission():"unsupported"}r(c0t,"requestNotificationPermission");function S5e(){return typeof navigator<"u"&&"serviceWorker"in navigator&&typeof window<"u"&&"PushManager"in window}r(S5e,"pushSupported");function d0t(e=typeof navigator>"u"?void 0:navigator){return e?(/iPad|iPhone|iPod/.test(e.userAgent)||e.platform==="MacIntel"&&(e.maxTouchPoints??0)>1)&&e.standalone!==!0:!1}r(d0t,"isIosWithoutHomeScreenInstall");async function C5e(){if(typeof navigator>"u"||!("serviceWorker"in navigator))return null;try{return await navigator.serviceWorker.getRegistration()??null}catch{return null}}r(C5e,"getServiceWorkerRegistration");var _5e="paperclip.notifications.seen.v1",u0t="paperclip.notifications.claim",m0t=6e5,h0t=200,p0t=new Map;function f0t(){let e=null;try{e=typeof localStorage>"u"?null:localStorage}catch{e=null}const s=typeof navigator<"u"&&navigator.locks?{request:r((n,a)=>navigator.locks.request(n,a),"request")}:null;return{storage:e,locks:s,now:r(()=>Date.now(),"now"),memory:p0t}}r(f0t,"defaultEnv");function x0t(e){const s=e.storage?.getItem(_5e);if(!s)return new Map(e.memory);try{const n=JSON.parse(s),a=new Map(e.memory);for(const[i,o]of Object.entries(n))typeof o=="number"&&a.set(i,o);return a}catch{return new Map(e.memory)}}r(x0t,"readSeen");function yD(e,s){const n=s.now(),a=x0t(s);for(const[o,l]of a)n-l>m0t&&a.delete(o);if(a.has(e))return!1;a.set(e,n);const i=[...a.entries()].sort((o,l)=>l[1]-o[1]).slice(0,h0t);s.memory.clear();for(const[o,l]of i)s.memory.set(o,l);return g0t(s,i),!0}r(yD,"claimInsideLock");function g0t(e,s){try{e.storage?.setItem(_5e,JSON.stringify(Object.fromEntries(s)))}catch{return}}r(g0t,"writeSeen");async function b0t(e,s=f0t()){if(!s.locks)return yD(e,s);try{return await s.locks.request(u0t,()=>yD(e,s))}catch{return yD(e,s)}}r(b0t,"claimNotificationKey");var v0t="paperclip-notifications",ME="custom-sounds";function A5e(e){return e.type.startsWith("audio/")?e.size<=0?{ok:!1,error:"The audio file is empty."}:e.size>524288?{ok:!1,error:"Custom sounds must be 512 KB or smaller."}:{ok:!0}:{ok:!1,error:"Choose an audio file."}}r(A5e,"validateCustomSoundFile");function I5e(e){return new Promise((s,n)=>{e.onsuccess=()=>s(e.result),e.onerror=()=>n(e.error)})}r(I5e,"requestResult");var BI=null;function y0t(){if(typeof indexedDB>"u")return Promise.reject(new Error("IndexedDB is unavailable."));if(!BI){const e=indexedDB.open(v0t,1);e.onupgradeneeded=()=>{e.result.objectStoreNames.contains(ME)||e.result.createObjectStore(ME,{keyPath:"kind"})},BI=I5e(e).catch(s=>{throw BI=null,s})}return BI}r(y0t,"openDb");async function zV(e,s){return I5e(s((await y0t()).transaction(ME,e).objectStore(ME)))}r(zV,"withStore");var Gz=new Set;function T5e(e){return Gz.add(e),()=>Gz.delete(e)}r(T5e,"subscribeCustomSounds");function R5e(){for(const e of Gz)e()}r(R5e,"notifyCustomSoundsChanged");async function j0t(e,s){const n=A5e(s);if(!n.ok)throw new Error(n.error);const a={kind:e,name:s.name,type:s.type,size:s.size,blob:s,updatedAt:new Date().toISOString()};return await zV("readwrite",i=>i.put(a)),R5e(),a}r(j0t,"saveCustomSound");async function E5e(e){try{return await zV("readonly",s=>s.get(e))??null}catch{return null}}r(E5e,"loadCustomSound");async function w0t(e){await zV("readwrite",s=>s.delete(e)),R5e()}r(w0t,"removeCustomSound");var L5e=[{id:"confirmation",label:"Confirmation"},{id:"question",label:"Question"},{id:"glass",label:"Glass"},{id:"bong",label:"Bong"},{id:"maximize",label:"Rise"},{id:"pluck",label:"Pluck"},{id:"error",label:"Alert"},{id:"drop",label:"Drop"},{id:"select",label:"Select"},{id:"open",label:"Open"}],Oae="custom",k0t="none",PE={approval:"confirmation",question:"question",comment:"pluck",assignment:"maximize",review:"glass",run_failed:"error",join_request:"bong"},N0t={approval:"Approvals",question:"Agent questions",comment:"Comments",assignment:"Assignments",review:"Ready for review",run_failed:"Failed runs",join_request:"Join requests"},M5e=new Set(L5e.map(e=>e.id));function S0t(e){return typeof e=="string"&&(M5e.has(e)||e==="custom"||e==="none")}r(S0t,"isKnownSoundId");function C0t(e){return M5e.has(e)}r(C0t,"isLibrarySoundId");function Bae(e,s){return`/sounds/${e}.${s}`}r(Bae,"librarySoundUrl");var Yz=new Map,DE=new Map,Fae=!1,FI=null;function P5e(){return typeof Audio<"u"}r(P5e,"audioSupported");function zae(){return FI||(FI=new Audio().canPlayType('audio/ogg; codecs="vorbis"')?"ogg":"mp3",FI)}r(zae,"libraryFormat");function D5e(e){let s=Yz.get(e);return s||(s=new Audio,s.preload="auto",s.src=e,Yz.set(e,s)),s}r(D5e,"audioFor");function _0t(){for(const e of DE.values())e.then(s=>{s&&(Yz.delete(s),URL.revokeObjectURL(s))});DE.clear()}r(_0t,"revokeCustomSounds");function A0t(e){Fae||(Fae=!0,T5e(_0t));let s=DE.get(e);return s||(s=E5e(e).then(n=>n?URL.createObjectURL(n.blob):null),DE.set(e,s)),s}r(A0t,"customSoundUrl");async function $5e(e,s){if(s==="none")return null;if(s==="custom"){const n=await A0t(e);return n||Bae(PE[e],zae())}return Bae(C0t(s)?s:PE[e],zae())}r($5e,"resolveSoundUrl");async function O5e(e,s,n){if(!P5e())return!1;const a=await $5e(e,s);if(!a)return!1;const i=D5e(a);i.volume=Math.min(1,Math.max(0,n)),i.currentTime=0;try{return await i.play(),!0}catch{return!1}}r(O5e,"playSound");function I0t(e,s){return O5e(e,s.kinds[e].soundId,s.volume)}r(I0t,"playKindSound");function qae(e){if(!(!P5e()||!e.enabled))for(const[s,n]of Object.entries(e.kinds))n.enabled&&$5e(s,n.soundId).then(a=>{a&&D5e(a)})}r(qae,"preloadNotificationSounds");var $E={getWebPushConfig:r(()=>we.get("/notifications/web-push/config"),"getWebPushConfig"),upsertWebPushSubscription:r(e=>we.put("/notifications/web-push/subscription",e),"upsertWebPushSubscription"),deleteWebPushSubscription:r(e=>we.deleteWithBody("/notifications/web-push/subscription",e),"deleteWebPushSubscription"),sendWebPushTest:r(()=>we.post("/notifications/web-push/test",{}),"sendWebPushTest")},B5e="paperclip.notifications.v1",T0t=.6;function Zz(){const e={};for(const s of p3)e[s]={enabled:!0,soundId:PE[s]};return{enabled:!0,volume:T0t,pushEnabled:!0,kinds:e}}r(Zz,"defaultNotificationSettings");function jD(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:null}r(jD,"asRecord$15");function F5e(e){const s=Zz(),n=jD(e);if(!n)return s;const a=typeof n.volume=="number"&&Number.isFinite(n.volume)?Math.min(1,Math.max(0,n.volume)):s.volume,i=jD(n.kinds)??{},o={...s.kinds};for(const l of p3){const c=jD(i[l]);c&&(o[l]={enabled:typeof c.enabled=="boolean"?c.enabled:s.kinds[l].enabled,soundId:S0t(c.soundId)?c.soundId:s.kinds[l].soundId})}return{enabled:typeof n.enabled=="boolean"?n.enabled:s.enabled,volume:a,pushEnabled:typeof n.pushEnabled=="boolean"?n.pushEnabled:s.pushEnabled,kinds:o}}r(F5e,"normalizeNotificationSettings");function OE(){try{return typeof localStorage>"u"?null:localStorage}catch{return null}}r(OE,"storage$1");function R0t(){const e=OE()?.getItem(B5e);if(!e)return Zz();try{return F5e(JSON.parse(e))}catch{return Zz()}}r(R0t,"readStored");var BE,LC=null,jR=new Set,zI=!1;function ig(){const e=OE()?.getItem("paperclip.notifications.v1")??null;return LC&&e===BE||(BE=e,LC=R0t()),LC}r(ig,"getNotificationSettings");function z5e(){for(const e of jR)e()}r(z5e,"notify");function wR(e){const s=F5e(typeof e=="function"?e(ig()):e);try{OE()?.setItem(B5e,JSON.stringify(s))}catch{BE=void 0}return LC=s,BE=OE()?.getItem("paperclip.notifications.v1")??null,z5e(),s}r(wR,"setNotificationSettings");function qI(e,s){return wR(n=>({...n,kinds:{...n.kinds,[e]:{...n.kinds[e],...s}}}))}r(qI,"updateKindSettings");function E0t(e){return e.enabled?p3.filter(s=>e.kinds[s].enabled):[]}r(E0t,"enabledNotificationKinds");function Uae(e){e.key!==null&&e.key!=="paperclip.notifications.v1"||z5e()}r(Uae,"onStorage");function q5e(e){return jR.add(e),!zI&&typeof window<"u"&&(zI=!0,window.addEventListener("storage",Uae)),()=>{jR.delete(e),jR.size===0&&zI&&typeof window<"u"&&(zI=!1,window.removeEventListener("storage",Uae))}}r(q5e,"subscribeNotificationSettings");function U5e(){return(0,m.useSyncExternalStore)(q5e,ig,ig)}r(U5e,"useNotificationSettings");var b_={status:"unknown",error:null},Jz=new Set,Xz=null,Kae=Promise.resolve();function Qae(e){if(!(e.status===b_.status&&e.error===b_.error)){b_=e;for(const s of Jz)s()}}r(Qae,"setPushState");function Wae(){return b_}r(Wae,"getPushState");function L0t(){return b_.status==="active"}r(L0t,"hasActivePushSubscription");function M0t(e){return Jz.add(e),()=>Jz.delete(e)}r(M0t,"subscribePushState");function P0t(){return(0,m.useSyncExternalStore)(M0t,Wae,Wae)}r(P0t,"usePushState");function K5e(e){const s=e.padEnd(e.length+(4-e.length%4)%4,"=").replace(/-/g,"+").replace(/_/g,"/"),n=atob(s),a=new Uint8Array(new ArrayBuffer(n.length));for(let i=0;i<n.length;i+=1)a[i]=n.charCodeAt(i);return a}r(K5e,"urlBase64ToUint8Array");function D0t(e,s){const n=e.options?.applicationServerKey;if(!n)return!0;const a=K5e(s),i=new Uint8Array(n);return i.length===a.length&&i.every((o,l)=>o===a[l])}r(D0t,"sameApplicationServerKey");async function Hae(e){await $E.deleteWebPushSubscription({endpoint:e.endpoint}).catch(()=>{}),await e.unsubscribe().catch(()=>!1),Xz=null}r(Hae,"forgetSubscription");async function $0t(e,s){if(!S5e())return{status:"unsupported",error:null};const n=await C5e();if(!n)return{status:"unsupported",error:null};let a=await n.pushManager.getSubscription();if(!(e.enabled&&e.pushEnabled))return a&&await Hae(a),{status:"off",error:null};if(g_()!=="granted")return{status:"permission",error:null};const i=await $E.getWebPushConfig();if(!i.enabled||!i.publicKey)return{status:"server-disabled",error:null};a&&!D0t(a,i.publicKey)&&(await Hae(a),a=null),a||(a=await n.pushManager.subscribe({userVisibleOnly:!0,applicationServerKey:K5e(i.publicKey)}));const o=a.toJSON(),l=o.keys?.p256dh,c=o.keys?.auth;if(!l||!c)return{status:"error",error:"The browser returned an incomplete push subscription."};const d=E0t(e),u=[s,a.endpoint,...d].join("|");return u!==Xz&&(await $E.upsertWebPushSubscription({endpoint:a.endpoint,keys:{p256dh:l,auth:c},kinds:d}),Xz=u),{status:"active",error:null}}r($0t,"reconcile");function eq(e,s){const n=Kae.then(async()=>{try{const a=await $0t(e,s);return Qae(a),a}catch(a){const i={status:"error",error:a instanceof Error?a.message:"Push subscription failed."};return Qae(i),i}});return Kae=n.catch(()=>{}),n}r(eq,"syncPushSubscription");function Q5e(e,s){return s.enabled&&s.kinds[e.kind]?.enabled===!0}r(Q5e,"kindEnabled");function O0t(e){const{payload:s,userId:n,settings:a}=e;return!n||!s.recipientUserIds.includes(n)||!Q5e(s.notification,a)?"none":e.visible?"sound":e.pushActive?"none":"os"}r(O0t,"decideLiveNotification");function B0t(e){return!e.visible||!Q5e(e.notification,e.settings)?"none":"sound"}r(B0t,"decideServiceWorkerNotification");async function F0t(e){if(g_()!=="granted")return;const s={body:e.body,tag:e.key,data:{url:e.url},icon:o0t,badge:l0t},n=await C5e();if(n){await n.showNotification(e.title,s);return}new Notification(e.title,s)}r(F0t,"showOsNotification");var W5e={claim:r(e=>b0t(e),"claim"),playSound:r((e,s)=>I0t(e.kind,s),"playSound"),showOsNotification:F0t};async function H5e(e,s,n,a){return e==="none"?e:await a.claim(s.key)?(e==="sound"?await a.playSound(s,n):await a.showOsNotification(s),e):"none"}r(H5e,"perform");function z0t(e,s,n=W5e,a={}){const i=a.settings??ig();return H5e(O0t({payload:e,userId:s,settings:i,visible:a.visible??oN().visible,pushActive:a.pushActive??L0t()}),e.notification,i,n)}r(z0t,"deliverLiveNotification");function q0t(e,s=W5e,n={}){const a=n.settings??ig();return H5e(B0t({notification:e,settings:a,visible:n.visible??oN().visible}),e,a,s)}r(q0t,"deliverServiceWorkerNotification");function V5e(e){if(!e||typeof e!="object")return null;const s=e;return typeof s.key=="string"&&typeof s.kind=="string"&&typeof s.title=="string"?s:null}r(V5e,"readNotification");function U0t(e){if(!e||typeof e!="object")return null;const s=e,n=V5e(s.notification);return!n||!Array.isArray(s.recipientUserIds)?null:{notification:n,recipientUserIds:s.recipientUserIds.filter(a=>typeof a=="string")}}r(U0t,"readNotificationCreatedPayload");function K0t(e){if(!e||typeof e!="object")return null;const s=e;if(s.type==="paperclip.notification"){const n=V5e(s.notification);return n?{type:"notification",notification:n}:null}return s.type==="paperclip.navigate"&&typeof s.url=="string"&&s.url.startsWith("/")?{type:"navigate",url:s.url}:null}r(K0t,"readServiceWorkerMessage");var Q0t=1e4,W0t=3,H0t=2e3,V0t=3e5,G0t=2e3,Y0t=15e3,Z0t=0,J0t=1,A5=new Set(["succeeded","interrupted","failed","cancelled","timed_out"]),G5e=(0,m.createContext)(null);function X0t(e,s,n){if(n.companyId===s)for(const a of Array.from(e))try{a(n)}catch{}}r(X0t,"dispatchLiveEventToSubscribers");function TN(e){const s=(0,m.useContext)(G5e),n=(0,m.useRef)(e);(0,m.useEffect)(()=>{n.current=e}),(0,m.useEffect)(()=>{if(s)return s.subscribe(a=>{n.current(a)})},[s])}r(TN,"useCompanyLiveEvent");function Ys(e){return typeof e=="string"&&e.length>0?e:null}r(Ys,"readString$6");function dw(e){return typeof e!="object"||e===null||Array.isArray(e)?null:e}r(dw,"readRecord$3");function FE(e){return e.slice(0,8)}r(FE,"shortId$2");function Y5e(e,s,n){const a=e.getQueryData(M.agents.list(s))?.find(i=>i.id===n);return a?.name?a.name:e.getQueryData(M.agents.detail(n))?.name??null}r(Y5e,"resolveAgentName$1");function ept(e,s,n){const a=e.getQueryData(M.access.companyUserDirectory(s));if(!a)return null;const i=a.users.find(o=>o.principalId===n);return i?.user?.name?.trim()||i?.user?.email?.trim()||null}r(ept,"resolveUserName");function Iy(e,s){return e.length<=s?e:e.slice(0,s-1)+"…"}r(Iy,"truncate$5");function tpt(e,s,n,a){return n==="agent"&&a?Y5e(e,s,a)??`Agent ${FE(a)}`:n==="system"?"System":n==="user"&&a?ept(e,s,a)??(a==="board"||a==="local-board"?"Board":`User ${FE(a)}`):n==="plugin"?"Plugin":"Unknown actor"}r(tpt,"resolveActorLabel$1");function qV(e,s,n,a){const i=new Set([n]),o=e.getQueryData(M.issues.detail(n)),l=e.getQueryData(M.issues.list(s)),c=Ys(a?.identifier)??Ys(a?.issueIdentifier);c&&i.add(c),o?.id&&i.add(o.id),o?.identifier&&i.add(o.identifier);const d=l?.find(u=>!!(u.id===n||u.identifier&&u.identifier===n||c&&u.identifier===c));return d?.id&&i.add(d.id),d?.identifier&&i.add(d.identifier),Array.from(i)}r(qV,"resolveIssueQueryRefs");function spt(e,s,n,a){const i=qV(e,s,n,a),o=i.map(h=>e.getQueryData(M.issues.detail(h))).find(h=>!!h),l=e.getQueryData(M.issues.list(s))?.find(h=>i.some(p=>h.id===p||h.identifier===p)),c=o??l??null,d=Ys(a?.identifier)??Ys(a?.issueIdentifier)??c?.identifier??`Task ${FE(n)}`,u=Ys(a?.title)??Ys(a?.issueTitle)??c?.title??null;return{ref:d,title:u,label:u?`${d} - ${Iy(u,72)}`:d,href:`/issues/${c?.identifier??n}`}}r(spt,"resolveIssueToastContext");function Z5e(){return!(typeof document>"u"||document.visibilityState!=="visible"||typeof document.hasFocus=="function"&&!document.hasFocus())}r(Z5e,"isPageForegrounded");function vv(e,s,n){if(!(n?.isForegrounded??Z5e()))return null;const a=_8(s).split("/").filter(Boolean);if(!["issues","chats"].includes(a[0])||!a[1])return null;let i=decodeURIComponent(a[1]);if(a[0]==="chats"){const f=e.getQueryData(M.auth.session),x=f?.user?.id??f?.session?.userId??null,g=HQ(s),v=e.getQueryData(M.companies.list(x))?.companies.find(w=>w.issuePrefix.toUpperCase()===g?.toUpperCase());if(!v)return null;const y=e.getQueryData(M.agents.list(v.id))?.find(w=>w.id===i||Vl(w)===i);if(!y)return null;const k=e.getQueryData(M.agentChats.detail(v.id,x,y.id));if(!k)return null;i=k.id}const o=e.getQueryData(M.issues.detail(i))??null,l=new Set([i]);o?.id&&l.add(o.id),o?.identifier&&l.add(o.identifier);function c(f,x){const g=e.getQueryData(M.issues.activeRun(f)),v=e.getQueryData(M.issues.liveRuns(f))??[],y=e.getQueryData(M.issues.runs(f))??[];g?.id&&x.add(g.id);for(const k of v)k.id&&x.add(k.id);for(const k of y)k.runId&&x.add(k.runId)}r(c,"collectCachedIssueRunIds");const d=new Set;for(const f of l)c(f,d);const u=new Set(l),h=new Set,p=new Set(d);if(o?.companyId&&o.id){const f=e.getQueryData(M.issues.listByDescendantRoot(o.companyId,o.id))??[];for(const x of f)u.add(x.id),x.identifier&&u.add(x.identifier),x.assigneeAgentId&&h.add(x.assigneeAgentId),x.executionRunId&&p.add(x.executionRunId),c(x.id,p),x.identifier&&c(x.identifier,p)}if(o?.companyId){const f=e.getQueryData(M.liveRuns(o.companyId))??[];for(const x of f)x.issueId&&u.has(x.issueId)&&p.add(x.id)}return{routeIssueRef:i,issueRefs:l,assigneeAgentId:o?.assigneeAgentId??null,runIds:d,subtreeIssueRefs:u,subtreeAgentIds:h,subtreeRunIds:p}}r(vv,"resolveVisibleIssueRouteContext");function EM(e,s){const n=new Set([e]),a=Ys(s?.identifier)??Ys(s?.issueIdentifier);return a&&n.add(a),n}r(EM,"buildIssueRefsForPayload");function LM(e,s){for(const n of e)if(s.has(n))return!0;return!1}r(LM,"overlaps");function npt(e,s,n,a){const i=Ys(n.entityType),o=Ys(n.entityId);if(i!=="issue"||!o)return!1;const l=vv(e,s,a);return l?LM(l.subtreeIssueRefs,EM(o,dw(n.details))):!1}r(npt,"shouldSuppressActivityToastForVisibleIssue");function rpt(e,s,n,a){if(!(a?.isForegrounded??Z5e()))return!1;const i=_8(s).match(/^\/agents\/[^/]+\/runs\/([^/]+)/)?.[1];if(i&&decodeURIComponent(i)===Ys(n.runId))return!0;const o=vv(e,s,a);if(!o)return!1;const l=Ys(n.issueId);if(l)return o.subtreeIssueRefs.has(l);const c=Ys(n.runId);if(c)return o.subtreeRunIds.has(c);const d=Ys(n.agentId);return!!d&&(d===o.assigneeAgentId||o.subtreeAgentIds.has(d))}r(rpt,"shouldSuppressRunStatusToastForVisibleIssue");function Vae(e,s,n,a){const i=vv(e,s,a);if(!i)return!1;const o=Ys(n.runId),l=Ys(n.agentId);if(!(o!==null&&i.runIds.has(o)||l&&i.assigneeAgentId&&l===i.assigneeAgentId))return!1;const c=Ys(n.status);if(o&&c&&A5.has(c))for(const h of i.issueRefs)e.invalidateQueries({queryKey:M.issues.comments(h)}),e.setQueryData(M.issues.liveRuns(h),p=>Kht(p,o)),e.setQueryData(M.issues.activeRun(h),p=>p?.id===o?null:p),e.setQueryData(M.issues.detail(h),p=>Qht(p,o));const d=!!c&&A5.has(c),u=!d&&(a?.liveStatusAlreadyPatched??!1);for(const h of i.issueRefs)e.invalidateQueries({queryKey:M.issues.detail(h)}),e.invalidateQueries({queryKey:M.issues.activity(h)}),e.invalidateQueries({queryKey:M.issues.runs(h)}),a?.runLifecycleEvent&&e.invalidateQueries({queryKey:M.issues.queuedComments(h)}),u||(e.invalidateQueries({queryKey:M.issues.liveRuns(h)}),e.invalidateQueries({queryKey:M.issues.activeRun(h)})),d&&(e.invalidateQueries({queryKey:M.issues.comments(h)}),e.invalidateQueries({queryKey:M.issues.attachments(h)}),e.invalidateQueries({queryKey:M.issues.workProducts(h)}),e.invalidateQueries({queryKey:M.issues.workProductPullRequestRefresh(h)}),e.invalidateQueries({queryKey:["issues","tree-control-state",h]}));return!0}r(Vae,"invalidateVisibleIssueRunQueries");function O2(e,s){return Object.prototype.hasOwnProperty.call(e,s)}r(O2,"hasPatchKey");function J5e(e,s){return e.id!==s.runId?e:{...e,...O2(s,"message")?{currentStatusMessage:s.message}:{},...O2(s,"updatedAt")?{currentStatusUpdatedAt:s.updatedAt}:{},...O2(s,"currentToolName")?{currentToolName:s.currentToolName}:{},...O2(s,"lastAssistantSnippet")?{lastAssistantSnippet:s.lastAssistantSnippet}:{},...O2(s,"lastEventAt")?{lastEventAt:s.lastEventAt}:{}}}r(J5e,"applyRunLiveStatusPatch");function Gae(e,s){if(!e)return e;let n=!1;const a=e.map(i=>i.id!==s.runId?i:(n=!0,J5e(i,s)));return n?a:e}r(Gae,"applyRunLiveStatusPatchToArray");function apt(e,s,n){const a=Ys(e.runId);if(!a)return null;const i={runId:a,agentId:Ys(e.agentId),issueId:Ys(e.issueId)};if(n==="heartbeat.run.progress")return i.message=Ys(e.message),i.updatedAt=Ys(e.updatedAt)??s,i.currentToolName=Ys(e.currentToolName),i.lastAssistantSnippet=Ys(e.lastAssistantSnippet),i.lastEventAt=Ys(e.lastEventAt)??i.updatedAt,i;if(n==="heartbeat.run.log")return i.lastEventAt=Ys(e.ts)??s,i;if(n==="heartbeat.run.event"){const o=Ys(e.message);o&&(i.message=o),i.updatedAt=Ys(e.updatedAt)??s;const l=Ys(e.currentToolName);l&&(i.currentToolName=l);const c=Ys(e.lastAssistantSnippet);return c&&(i.lastAssistantSnippet=c),i.lastEventAt=Ys(e.lastEventAt)??s,i}return null}r(apt,"readRunLiveStatusPatchFromPayload");var ipt=1e3;function opt(e=ipt){const s=new Map,n=new Map,a=r(i=>{const o=s.get(i);if(!o){n.delete(i);return}s.delete(i),n.set(i,setTimeout(()=>a(i),e)),o.apply(o.patch)},"release");return{submit:r((i,o)=>{if(n.has(i.runId)){s.set(i.runId,{patch:i,apply:o});return}n.set(i.runId,setTimeout(()=>a(i.runId),e)),o(i)},"submit"),dispose:r(()=>{for(const i of n.values())clearTimeout(i);n.clear(),s.clear()},"dispose")}}r(opt,"createRunLogPatchThrottle");function lpt(e,s,n,a,i){let o=!1;e.setQueryData(M.liveRuns(s),d=>{const u=Gae(d,a);return u!==d&&(o=!0),u});const l=new Set;if(a.issueId)for(const d of qV(e,s,a.issueId,null))l.add(d);const c=vv(e,n,i);if(c&&(c.runIds.has(a.runId)||a.issueId&&c.issueRefs.has(a.issueId)||a.agentId&&c.assigneeAgentId&&a.agentId===c.assigneeAgentId))for(const d of c.issueRefs)l.add(d);for(const d of l)e.setQueryData(M.issues.activeRun(d),u=>!u||u.id!==a.runId?u:(o=!0,J5e(u,a))),e.setQueryData(M.issues.liveRuns(d),u=>{const h=Gae(u,a);return h!==u&&(o=!0),h});return o}r(lpt,"applyRunLiveStatusPatchToCaches");function cpt(e,s,n,a){const i=vv(e,s,a);if(!i)return!1;const o=Ys(n.agentId);return!!o&&(o===i.assigneeAgentId||i.subtreeAgentIds.has(o))}r(cpt,"shouldSuppressAgentStatusToastForVisibleIssue");function dpt(e,s,n,a){const i=Ys(n.entityType),o=Ys(n.entityId),l=Ys(n.actorType),c=Ys(n.action),d=dw(n.details);if(i!=="issue"||!o||l!=="agent"&&l!=="system"||c!=="issue.updated"||Ys(d?.source)==="comment")return!1;const u=vv(e,s,a);return u?LM(u.issueRefs,EM(o,d)):!1}r(dpt,"shouldDeferIssueRefetchForVisibleAgentActivity");function X5e(e,s,n,a){const i=Ys(n.entityType),o=Ys(n.entityId),l=Ys(n.action),c=dw(n.details);if(i!=="issue"||!o||l!=="issue.comment_added")return!1;const d=vv(e,s,a);return d?LM(d.issueRefs,EM(o,c)):!1}r(X5e,"shouldDeferVisibleIssueCommentActivity");async function upt(e,s,n,a){const i=Ys(n.entityType),o=Ys(n.action),l=dw(n.details),c=Ys(l?.commentId);if(i!=="issue"||o!=="issue.comment_added"||!c)return!1;const d=vv(e,s,a);if(!d)return!1;const u=Ys(n.entityId);if(!u||!LM(d.issueRefs,EM(u,l)))return!1;try{const h=await jt.getComment(d.routeIssueRef,c);for(const p of d.issueRefs)e.setQueryData(M.issues.comments(p),f=>f?{...f,pages:P1(f.pages,h)}:{pages:[[h]],pageParams:[null]});return!0}catch{for(const h of d.issueRefs)e.invalidateQueries({queryKey:M.issues.comments(h)});return!1}}r(upt,"hydrateVisibleIssueComment");var mpt=new Set(["issue.created","issue.updated","issue.comment_added"]),Yae=new Set(["issue.document_created","issue.document_updated","issue.document_restored","issue.document_deleted"]),hpt=new Set(["issue.document_annotation_thread_created","issue.document_annotation_comment_added","issue.document_annotation_thread_resolved","issue.document_annotation_thread_reopened","issue.document_annotation_remapped"]),ppt=new Set(["routine.document_annotation_thread_created","routine.document_annotation_comment_added","routine.document_annotation_thread_resolved","routine.document_annotation_thread_reopened","routine.document_annotation_remapped"]),fpt=new Set(["case.document_annotation_thread_created","case.document_annotation_comment_added","case.document_annotation_thread_resolved","case.document_annotation_thread_reopened","case.document_annotation_remapped"]),xpt=new Set(["error"]),gpt=new Set(["failed","timed_out","cancelled"]);function bpt(e){if(!e)return null;const s=[];if(typeof e.status=="string"&&s.push(`status -> ${e.status.replace(/_/g," ")}`),typeof e.priority=="string"&&s.push(`priority -> ${e.priority}`),typeof e.assigneeAgentId=="string"||typeof e.assigneeUserId=="string"?s.push("reassigned"):(e.assigneeAgentId===null||e.assigneeUserId===null)&&s.push("unassigned"),e.reopened===!0){const n=Ys(e.reopenedFrom);s.push(n?`reopened from ${n.replace(/_/g," ")}`:"reopened")}return typeof e.title=="string"&&s.push("title changed"),typeof e.description=="string"&&s.push("description changed"),s.length>0?s.join(", "):null}r(bpt,"describeIssueUpdate");function vpt(e,s,n,a){const i=Ys(n.entityType),o=Ys(n.entityId),l=Ys(n.action),c=dw(n.details),d=Ys(n.actorId),u=Ys(n.actorType);if(i!=="issue"||!o||!l||!mpt.has(l))return null;const h=spt(e,s,o,c),p=Ys(Ys(n.actorName)?.trim())??tpt(e,s,u,d),f=u==="agent"&&d?e.getQueryData(M.agents.list(s))?.find(R=>R.id===d)??e.getQueryData(M.agents.detail(d)):void 0,x=u==="user"&&d?e.getQueryData(M.access.companyUserDirectory(s))?.users.find(R=>R.principalId===d)?.user:void 0,g=d&&(u==="user"||u==="agent")?{type:u,id:d,name:p,image:n.actorImage!==void 0?Ys(n.actorImage):x?.image,appearance:u==="agent"?iv(n.actorAppearance!==void 0?n.actorAppearance:f?.appearance,d):void 0}:void 0;if(u==="user"&&a.userId&&d===a.userId||u==="agent"&&a.agentId&&d===a.agentId)return null;if(l==="issue.created")return{actor:g,title:`${p} created ${h.ref}`,body:h.title?Iy(h.title,96):void 0,tone:"success",action:{label:`View ${h.ref}`,href:h.href},dedupeKey:`activity:${l}:${o}`};if(l==="issue.updated"){if(Ys(c?.source)==="comment")return null;const R=bpt(c),I=R?h.title?`${Iy(h.title,64)} - ${R}`:R:h.title?Iy(h.title,96):h.label;return{actor:g,title:`${p} updated ${h.ref}`,body:Iy(I,100),tone:"info",action:{label:`View ${h.ref}`,href:h.href},dedupeKey:`activity:${l}:${o}`}}const v=Ys(c?.commentId),y=Ys(c?.bodySnippet),k=c?.reopened===!0,w=c?.updated===!0,N=Ys(c?.reopenedFrom),S=k?N?`reopened from ${N.replace(/_/g," ")}`:"reopened":null,C=k?`${p} reopened and commented on ${h.ref}`:w?`${p} commented and updated ${h.ref}`:`${p} commented on ${h.ref}`,_=y?S?`${S} - ${y.replace(/^#+\s*/m,"").replace(/\n/g," ")}`:y.replace(/^#+\s*/m,"").replace(/\n/g," "):S?h.title?`${S} - ${h.title}`:S:h.title??void 0;return{actor:g,title:C,body:_?Iy(_,96):void 0,tone:"info",action:{label:`View ${h.ref}`,href:h.href},dedupeKey:`activity:${l}:${o}:${v??"na"}`}}r(vpt,"buildActivityToast");function ypt(e){const s=Ys(e.entityType),n=Ys(e.action),a=Ys(e.entityId),i=dw(e.details);return s!=="join_request"||!n||!a||n!=="join.requested"&&n!=="join.request_replayed"?null:{title:`${Ys(i?.requestType)==="agent"?"Agent":"Someone"} wants to join`,body:"A new join request is waiting for approval.",tone:"info",action:{label:"View inbox",href:"/inbox/mine"},dedupeKey:`join-request:${a}`}}r(ypt,"buildJoinRequestToast");function jpt(e,s,n,a){const i=Ys(e.agentId),o=Ys(e.status);if(!i||!o||!xpt.has(o))return null;const l=o==="error"?"error":"info",c=s(i)??`Agent ${FE(i)}`;return{title:o==="running"?`${c} started`:`${c} errored`,body:n.getQueryData(M.agents.list(a))?.find(d=>d.id===i)?.title??void 0,tone:l,action:{label:"View agent",href:`/agents/${i}`},dedupeKey:`agent-status:${i}:${o}`}}r(jpt,"buildAgentStatusToast");function wpt(e,s){const n=Ys(e.runId),a=Ys(e.agentId),i=Ys(e.status);if(!n||!a||!i||!gpt.has(i))return null;const o=Ys(e.error),l=Ys(e.errorCode);if(l==="operator_interrupted"||l==="workspace_busy")return null;const c=Ys(e.contextSource),d=Ys(e.triggerDetail),u=s(a)??"Agent";if(i==="failed"&&l==="low_trust_isolation_unavailable"&&c?.startsWith("chat:"))return{title:`${u} couldn't start this chat`,body:"This external chat identity isn't linked, and isolated guest workspaces are disabled. Link the identity in Connectors or enable isolated workspaces, then start a new task.",tone:"warn",ttlMs:1e4,action:{label:"Open chat connections",href:"/apps"},dedupeKey:`run-status:${n}:${i}`};const h=i==="succeeded"?"success":i==="cancelled"?"info":"error",p=`${u} run ${i==="succeeded"?"succeeded":i==="failed"?"failed":i==="timed_out"?"timed out":"cancelled"}`;let f;return o?f=Iy(o,100):d&&(f=`Trigger: ${d}`),{title:p,body:f,tone:h,ttlMs:i==="succeeded"?5e3:7e3,action:{label:"View run",href:`/agents/${a}/runs/${n}`},dedupeKey:`run-status:${n}:${i}`}}r(wpt,"buildRunStatusToast");function kpt(e,s,n){const a=Ys(n.runId),i=Ys(n.status);if(!a||!i)return!1;if(e.setQueryData(M.runDetail(a),l=>{if(!l)return l;const c=r(d=>Object.prototype.hasOwnProperty.call(n,d),"has");return{...l,status:i,...c("invocationSource")?{invocationSource:Ys(n.invocationSource)??l.invocationSource}:{},...c("triggerDetail")?{triggerDetail:Ys(n.triggerDetail)}:{},...c("error")?{error:Ys(n.error)}:{},...c("errorCode")?{errorCode:Ys(n.errorCode)}:{},...c("startedAt")?{startedAt:Ys(n.startedAt)}:{},...c("finishedAt")?{finishedAt:Ys(n.finishedAt)}:{}}}),A5.has(i))return e.setQueryData(M.liveRuns(s),l=>qht(l,a)),!0;let o=!1;return e.setQueryData(M.liveRuns(s),l=>{const c=Uht(l,a,i);return o=c.present,c.next}),o}r(kpt,"applyRunLifecycleToCompanyLiveRuns");function Npt(e,s,n){const a=Ys(n.status);a&&A5.has(a)&&e.invalidateQueries({queryKey:M.heartbeats(s),refetchType:"none"}),e.invalidateQueries({queryKey:M.agents.list(s)}),e.invalidateQueries({queryKey:M.dashboard(s)}),e.invalidateQueries({queryKey:["costs",s]}),e.invalidateQueries({queryKey:M.sidebarBadges(s)});const i=Ys(n.agentId);i&&(e.invalidateQueries({queryKey:M.agents.detail(i)}),e.invalidateQueries({queryKey:M.heartbeats(s,i)}));const o=Ys(n.runId);o&&e.invalidateQueries({queryKey:M.runDetail(o)})}r(Npt,"invalidateHeartbeatQueries");function Spt(e,s,n){const a=Ys(n.agentId);a&&e.invalidateQueries({queryKey:M.agents.detail(a)})}r(Spt,"invalidateHeartbeatProgressQueries");var Cpt=new Set(["approval","attention_source","budget_incident","decision","decision_queue","issue_recovery_action","join_request"]),_pt=["issue.blockers_","issue.dependency_recovery_","issue.disposition_repair_","issue.execution_recovery_","issue.interaction_","issue.recovery_action_","issue.stalled_review_","issue.thread_interaction_"],Apt=new Set(["failed","timed_out"]);function Ipt(e,s,n){return s?.startsWith("inbox.")||e&&Cpt.has(e)?!0:e!=="issue"||!s?!1:_pt.some(a=>s.startsWith(a))||s==="issue.reviewers_updated"||s==="issue.status_decision_recorded"?!0:(s==="issue.created"||s==="issue.updated")&&(n?.status!==void 0||n?.blockedByIssueIds!==void 0)}r(Ipt,"activityChangesAttention");function Zae(e,s,n,a){return e.getQueriesData({queryKey:M.attention(s)}).some(([,i])=>i?"items"in i?Array.isArray(i.items)&&i.items.some(n):"count"in i&&a(i):!1)}r(Zae,"cachedAttentionIncludes");function tq(e,s){e.invalidateQueries({queryKey:M.attention(s)})}r(tq,"invalidateAttentionQueries");function Tpt(e,s,n,a,i){e.invalidateQueries({queryKey:M.activity(s)}),e.invalidateQueries({queryKey:M.dashboard(s)}),e.invalidateQueries({queryKey:M.sidebarBadges(s)});const o=Ys(n.entityType),l=Ys(n.entityId),c=Ys(n.action),d=Ys(n.actorType),u=Ys(n.actorId),h=dw(n.details),p=d==="user"&&!!a.userId&&u===a.userId||d==="agent"&&!!a.agentId&&u===a.agentId;if(Ipt(o,c,h)&&tq(e,s),o==="decision"&&(e.invalidateQueries({queryKey:["decisions",s]}),l&&e.invalidateQueries({queryKey:M.decisions.detail(l)})),(c?.startsWith("ai_connection.")||c?.startsWith("connection_grant."))&&e.invalidateQueries({queryKey:["ai-connections",s]}),(c?.startsWith("primary_agent.")||c?.startsWith("agent.")||c?.startsWith("resource_membership."))&&e.invalidateQueries({queryKey:["primary-agent",s]}),c?.startsWith("resource_membership.")||c?.startsWith("primary_agent.")){const f=Ys(h?.userId);(!f||f===a.userId)&&e.invalidateQueries({queryKey:M.resourceMemberships.mine(s)})}if(o==="issue"){const f=M.agentChats.list(s,a.userId);if((l&&e.getQueryData(f)?.some(x=>x.id===l)||c==="issue.conversation_opened"&&p)&&e.invalidateQueries({queryKey:f}),(c==="issue.tree_hold_created"||c==="issue.tree_hold_released"||c==="issue.updated")&&e.invalidateQueries({queryKey:["issues","tree-control-state"]}),l&&e0t(e,s,l,Zht(c,h,i?.occurredAt??null)),t0t(e,s),Rqe(e,s,n),l){const x=(c==="issue.comment_added"||c==="issue.updated"&&Ys(h?.source)==="comment")&&(d==="user"&&!!a.userId&&u===a.userId||d==="agent"&&!!a.agentId&&u===a.agentId),g=!!i?.pathname&&dpt(e,i.pathname,n,{isForegrounded:i.isForegrounded}),v=!!i?.pathname&&X5e(e,i.pathname,n,{isForegrounded:i.isForegrounded}),y=qV(e,s,l,h);for(const k of y){const w=x||g||v?{refetchType:"inactive"}:void 0;if(e.invalidateQueries({queryKey:M.issues.detail(k),...w}),e.invalidateQueries({queryKey:M.issues.activity(k),...w}),(c==="issue.comment_added"||c==="issue.conversation_session_started")&&e.invalidateQueries({queryKey:M.issues.comments(k),...w}),(c==="issue.comment_added"||c?.startsWith("issue.queued_comment"))&&e.invalidateQueries({queryKey:M.issues.queuedComments(k)}),(c?.startsWith("issue.attachment_")||c?.startsWith("issue.work_product_"))&&(e.invalidateQueries({queryKey:M.issues.attachments(k)}),e.invalidateQueries({queryKey:M.issues.workProducts(k)})),c==="issue.conversation_session_started"&&(e.invalidateQueries({queryKey:["issues","tree-control-state",k]}),e.invalidateQueries({queryKey:M.issues.interactions(k)})),c&&Yae.has(c)){const N=Ys(h?.key);e.invalidateQueries({queryKey:M.issues.documents(k),...w}),N?(e.invalidateQueries({queryKey:M.issues.document(k,N),...w}),e.invalidateQueries({queryKey:M.issues.documentRevisions(k,N),...w})):(e.invalidateQueries({queryKey:["issues","document",k],...w}),e.invalidateQueries({queryKey:["issues","document-revisions",k],...w}))}if(c&&(Yae.has(c)||hpt.has(c))){const N=Ys(h?.key)??Ys(h?.documentKey);e.invalidateQueries({queryKey:N?["issues","document-annotations",k,N]:["issues","document-annotations",k],...w})}(c?.startsWith("issue.thread_interaction_")||(c==="issue.updated"||c==="issue.status_decision_recorded")&&Ys(h?.source)==="native_status_decision")&&(e.invalidateQueries({queryKey:M.issues.interactions(k)}),e.invalidateQueries({queryKey:M.tools.actionRequests(s,"pending")}),e.invalidateQueries({queryKey:M.apps.attention(s)}),e.invalidateQueries({queryKey:M.tools.trustRules(s)}))}}return}if(o==="agent"){e.invalidateQueries({queryKey:M.agents.list(s)}),e.invalidateQueries({queryKey:M.org(s)}),l&&(e.invalidateQueries({queryKey:M.agents.detail(l)}),e.invalidateQueries({queryKey:M.heartbeats(s,l)}));return}if(o==="project"){const f=Ys(n.details?.sourceIssueId);f&&e.invalidateQueries({queryKey:M.issues.activity(f)}),e.invalidateQueries({queryKey:M.projects.all(s)}),l&&e.invalidateQueries({queryKey:M.projects.detail(l)});return}if(o==="company_skill"){const f=Ys(n.details?.sourceIssueId);f&&e.invalidateQueries({queryKey:M.issues.activity(f)}),l&&e.invalidateQueries({queryKey:M.companySkills.detail(s,l)}),e.invalidateQueries({queryKey:M.companySkills.list(s)});return}if(o==="goal"){e.invalidateQueries({queryKey:M.goals.list(s)}),l&&e.invalidateQueries({queryKey:M.goals.detail(l)});return}if(o==="approval"){e.invalidateQueries({queryKey:M.approvals.list(s)});return}if(o==="join_request"){e.invalidateQueries({queryKey:M.access.joinRequests(s)});return}if(o==="cost_event"){e.invalidateQueries({queryKey:["costs",s]}),e.invalidateQueries({queryKey:["usage-by-provider",s]}),e.invalidateQueries({queryKey:["usage-by-biller",s]}),e.invalidateQueries({queryKey:M.usageWindowSpend(s)});return}if(o==="routine"||o==="routine_trigger"||o==="routine_run"){if(e.invalidateQueries({queryKey:["routines"]}),o==="routine"&&c&&ppt.has(c)&&l){const f=Ys(h?.key)??Ys(h?.documentKey)??"description",x=p?{refetchType:"inactive"}:void 0;e.invalidateQueries({queryKey:["routines","document-annotations",l,f],...x})}return}if(o==="case"){if(e.invalidateQueries({queryKey:M.cases.list(s)}),l&&(e.invalidateQueries({queryKey:M.cases.detail(l)}),e.invalidateQueries({queryKey:M.cases.events(l)}),c&&fpt.has(c))){const f=Ys(h?.key)??Ys(h?.documentKey),x=p?{refetchType:"inactive"}:void 0;e.invalidateQueries({queryKey:f?["cases","document-annotations",l,f]:["cases","document-annotations",l],...x})}return}if(o==="summary_slot"){const f=Ys(h?.scopeKind),x=Ys(h?.slotKey),g=Ys(h?.scopeId);f&&x&&(e.invalidateQueries({queryKey:M.summarySlots.detail(s,f,x,g)}),e.invalidateQueries({queryKey:M.summarySlots.revisions(s,f,x,g)}));return}o==="company"&&e.invalidateQueries({queryKey:M.companies.all})}r(Tpt,"invalidateActivityQueries");function Rpt(e,s){const n=s.payload??{},a=Ys(n.runId),i=Ys(n.status);if(!a||!i||!A5.has(i))return!1;const o=`${s.companyId}:${a}:${i}`,l=e.observedRunOutcomes.has(o);e.observedRunOutcomes.delete(o),e.observedRunOutcomes.add(o),e.observedRunOutcomes.size>G0t&&e.observedRunOutcomes.delete(e.observedRunOutcomes.values().next().value);const c=Date.parse(Ys(n.finishedAt)??""),d=Date.parse(s.createdAt);return l||d-c>V0t}r(Rpt,"observeRunOutcome");function Ept(e,s){const n=Date.now();if(n<e.suppressUntil)return!0;const a=e.cooldownHits.get(s);if(!a)return!1;const i=a.filter(o=>n-o<Q0t);return e.cooldownHits.set(s,i),i.length>=W0t}r(Ept,"shouldSuppressToast");function Lpt(e,s){const n=Date.now(),a=e.cooldownHits.get(s)??[];a.push(n),e.cooldownHits.set(s,a)}r(Lpt,"recordToastHit");function wD(e,s,n,a){Ept(e,n)||s(a)!==null&&Lpt(e,n)}r(wD,"gatedPushToast");function Mpt(e,s,n,a,i,o,l,c){if(a.companyId!==s)return;const d=r(x=>Y5e(e,s,x),"nameOf"),u=a.payload??{},h=a.type==="heartbeat.run.status"&&(Rpt(o,a)||rpt(e,n,u)),p=apt(u,a.createdAt,a.type);let f=!1;if(p){const x=r(g=>{f=lpt(e,s,n,g)},"applyPatch");a.type==="heartbeat.run.log"&&c?c.submit(p,x):x(p)}if(a.type!=="heartbeat.run.log"){if(a.type==="heartbeat.run.queued"||a.type==="heartbeat.run.status"){const x=kpt(e,s,u);if(Npt(e,s,u),$ae(e,a),x||e.invalidateQueries({queryKey:M.liveRuns(s)}),Vae(e,n,u,{runLifecycleEvent:!0}),(a.type==="heartbeat.run.status"&&Apt.has(Ys(u.status)??"")||a.type==="heartbeat.run.queued"&&Zae(e,s,g=>g.sourceKind==="failed_run",g=>(g.countsBySourceKind?.failed_run??0)>0))&&tq(e,s),a.type==="heartbeat.run.status"){const g=wpt(u,d);g&&!h&&wD(o,i,"run-status",g)}return}if(a.type==="heartbeat.run.progress"){Spt(e,s,u),Vae(e,n,u,{liveStatusAlreadyPatched:f});return}if(a.type==="heartbeat.run.event"){$ae(e,a);return}if(a.type==="agent.status"){e.invalidateQueries({queryKey:M.agents.list(s)}),e.invalidateQueries({queryKey:M.dashboard(s)}),e.invalidateQueries({queryKey:M.org(s)});const x=Ys(u.agentId);x&&e.invalidateQueries({queryKey:M.agents.detail(x)}),(Ys(u.status)==="error"||x&&Zae(e,s,v=>v.sourceKind==="agent_error_alert"&&v.subject?.id===x,v=>v.errorAgentIds?.includes(x)===!0))&&tq(e,s);const g=jpt(u,d,e,s);g&&!cpt(e,n,u)&&wD(o,i,"agent-status",g);return}if(a.type==="activity.logged"){Tpt(e,s,u,l,{pathname:n,occurredAt:a.createdAt??null}),X5e(e,n,u)&&upt(e,n,u);const x=Ys(u.action),g=vpt(e,s,u,l)??ypt(u);g&&!npt(e,n,u)&&wD(o,i,`activity:${x??"unknown"}`,g)}}}r(Mpt,"handleLiveEvent");function Ppt(e,s){return e&&e===s?e:null}r(Ppt,"resolveLiveCompanyId");function Jae(e){e.onopen=null,e.onmessage=null,e.onerror=null,e.onclose=null}r(Jae,"resetSocketHandlers");function Xae(e,s){if(e){if(e.readyState===Z0t){e.onopen=()=>{Jae(e),e.close(1e3,s)},e.onmessage=null,e.onerror=()=>{},e.onclose=null;return}Jae(e),e.readyState===J0t&&e.close(1e3,s)}}r(Xae,"closeSocketQuietly");function Dpt(e,s,n){return e==="success"&&(s||n==="local_trusted")}r(Dpt,"canUseLiveSession");function $pt({children:e}){const{visible:s}=ov(),n=(0,m.useRef)(!s),{selectedCompanyId:a,selectedCompany:i}=ps(),o=kt(),{pushToast:l}=Xr(),c=ua(),d=(0,m.useRef)({cooldownHits:new Map,suppressUntil:0,observedRunOutcomes:new Set}),u=(0,m.useRef)(c.pathname),{data:h,status:p}=te({queryKey:M.auth.session,queryFn:r(()=>Ma.getSession(),"queryFn"),retry:!1}),{data:f}=te({queryKey:M.health,queryFn:Iu.get}),x=h?.user?.id??h?.session?.userId??(f?.deploymentMode==="local_trusted"?"local-board":null),g=h?.session?.id??x??"signed_out",v=Ppt(a,i?.id??null),y=Dpt(p,h!=null,f?.deploymentMode)&&v!==null,k=(0,m.useRef)({userId:x,agentId:null}),w=(0,m.useRef)(new Set),N=(0,m.useCallback)(I=>(w.current.add(I),()=>{w.current.delete(I)}),[]),S=(0,m.useMemo)(()=>({subscribe:N}),[N]),C=(0,m.useMemo)(()=>Bht(o),[o]),_=(0,m.useMemo)(()=>zht(o,C),[o,C]),R=(0,m.useMemo)(()=>opt(),[]);return(0,m.useEffect)(()=>()=>{C.dispose(),R.dispose()},[C,R]),(0,m.useEffect)(()=>{u.current=c.pathname},[c.pathname]),(0,m.useEffect)(()=>{k.current={userId:x,agentId:null}},[x]),(0,m.useEffect)(()=>{if(!s||!y||!v)return;const I=window.setInterval(()=>{s0t(o,v)},Wht);return()=>window.clearInterval(I)},[y,v,o,s]),(0,m.useEffect)(()=>{if(!s){n.current=!0,C.dispose(),R.dispose();return}if(!y||!v)return;n.current&&(n.current=!1,o.invalidateQueries({type:"active"},{cancelRefetch:!1}));let I=!1,T=0,E=null,L=null,O=null;const P=r(()=>{E!==null&&(window.clearTimeout(E),E=null)},"clearReconnect"),Q=r(()=>{L!==null&&(window.clearInterval(L),L=null)},"stopPolling"),D=r(()=>{I||L!==null||(L=window.setInterval(()=>{o.invalidateQueries({type:"active"},{cancelRefetch:!1})},Y0t))},"startPolling"),F=r(()=>{if(I||E!==null)return;T+=1;const U=Math.min(15e3,1e3*2**Math.min(T-1,4));E=window.setTimeout(()=>{E=null,z()},U)},"scheduleReconnect"),z=r(()=>{if(I)return;const U=nA(`/api/companies/${encodeURIComponent(v)}/events/ws`),q=FV(U);if(!q){D(),F();return}O=q,q.onopen=()=>{if(I||O!==q){Xae(q,"stale_connection");return}Q(),T>0&&(d.current.suppressUntil=Date.now()+H0t),o.invalidateQueries({type:"active"},{cancelRefetch:!1}),T=0},q.onmessage=G=>{if(!oN().visible)return;const se=typeof G.data=="string"?G.data:"";if(se)try{const Z=JSON.parse(se);if(Mpt(_,v,u.current,Z,l,d.current,{userId:k.current.userId,agentId:k.current.agentId},R),X0t(w.current,v,Z),Z.type==="notification.created"){const ie=U0t(Z.payload);ie&&z0t(ie,k.current.userId)}}catch{}},q.onerror=()=>{},q.onclose=()=>{O===q&&(O=null,!I&&(D(),F()))}},"connect"),K=window.setTimeout(z,0);return()=>{I=!0,window.clearTimeout(K),P(),Q();const U=O;O=null,Xae(U,"provider_unmount")}},[s,C,R,o,_,v,l,y,g]),(0,t.jsx)(G5e.Provider,{value:S,children:e})}r($pt,"LiveUpdatesProvider");var Opt=15e3;function Bpt(e,s){return s?`${e}?${new URLSearchParams({companyId:s}).toString()}`:e}r(Bpt,"scoped");function Fpt(e,s,n){const a=`/api/local-browser/sessions/${encodeURIComponent(e)}/viewer`,i=new URLSearchParams;s&&i.set("companyId",s),typeof n=="number"&&i.set("tabId",String(n));const o=i.toString();return o?`${a}?${o}`:a}r(Fpt,"localBrowserViewerUrl");function zpt(e,s){return Bpt(`/api/local-browser/sessions/${encodeURIComponent(e)}/input`,s)}r(zpt,"localBrowserInputUrl");async function qpt(e,s,n){const a=await fetch(zpt(e,n),{method:"POST",credentials:"include",headers:{"Content-Type":"application/json"},body:JSON.stringify(s)});if(!a.ok)throw new Error(`Browser input was rejected (${a.status}).`)}r(qpt,"postLocalBrowserInput");function kD(e){return e===1?"middle":e===2?"right":"left"}r(kD,"mouseButtonOf");function UI(e,s,n,a,i){return e==="move"||!i?{kind:"mouse",action:e,x:s,y:n,button:a}:{kind:"mouse",action:e,x:s,y:n,button:a,clickCount:Math.min(Math.max(i,1),3)}}r(UI,"mouseInput");function Upt(e,s,n,a){return{kind:"wheel",deltaX:e,deltaY:s,x:n,y:a}}r(Upt,"wheelInput");function ND(e,s){const n=s.key.slice(0,64);if(!n)return null;const a={kind:"key",action:e,key:n},i=s.code?.slice(0,64);return i&&(a.code=i),s.alt&&(a.alt=!0),s.ctrl&&(a.ctrl=!0),s.meta&&(a.meta=!0),s.shift&&(a.shift=!0),e==="down"&&n.length===1&&!s.ctrl&&!s.meta&&!s.alt&&(a.text=n),a}r(ND,"keyInput");function Kpt(e){let s;try{s=JSON.parse(e)}catch{return null}const n=KBe.safeParse(s);return n.success?n.data:null}r(Kpt,"parseLocalBrowserViewerEvent");var Qpt=500,zE=4,Wpt=3;function Hpt(e,s,n){return!e||e.button!==s.button||n-e.at>Qpt||Math.abs(s.cssX-e.cssX)>zE||Math.abs(s.cssY-e.cssY)>zE||e.count>=Wpt?1:e.count+1}r(Hpt,"clickCountOf");function eie(e){return e instanceof Error?e.message:String(e)}r(eie,"messageOf");function tie(e){return e.code||e.key}r(tie,"keyIdOf");function Vpt(e,s,n){const[a,i]=(0,m.useState)(null),[o,l]=(0,m.useState)("connecting"),[c,d]=(0,m.useState)(null),[u,h]=(0,m.useState)(null),[p,f]=(0,m.useState)(null),[x,g]=(0,m.useState)(!1),v=(0,m.useRef)(new Map),y=(0,m.useRef)(null),k=(0,m.useRef)(null),w=(0,m.useRef)(null),N=(0,m.useRef)(null),S=(0,m.useRef)("");(0,m.useEffect)(()=>{if(i(null),d(null),h(null),f(null),g(!1),l("connecting"),!e){l("error"),d("No browser session is selected.");return}if(typeof EventSource>"u"){l("error"),d("This browser cannot show the live view.");return}const F=Fpt(e,s,n);let z=!1,K=null,U=0,q=null;function G(){U+=1;const Z=U>5;l(Z?"error":"reconnecting"),Z&&d("The live view keeps dropping. Still retrying in the background.");const ie=Math.min(500*2**(U-1),Opt);q=setTimeout(se,ie)}r(G,"retry");function se(){if(z)return;let Z;try{Z=new EventSource(F,{withCredentials:!0})}catch(ie){d(eie(ie)),G();return}K=Z,Z.onopen=()=>{z||(U=0,l("live"),d(null))},Z.onmessage=ie=>{if(z)return;const J=Kpt(ie.data);if(J){if(J.type==="frame"){i(J);return}h(J.state),f(J.message??null)}},Z.onerror=()=>{z||(Z.close(),K===Z&&(K=null),G())}}return r(se,"connect"),se(),()=>{z=!0,q&&clearTimeout(q),K?.close(),K=null}},[e,s,n]),(0,m.useEffect)(()=>{S.current="",w.current=null,y.current=null,k.current=null,v.current.clear()},[e,s]),(0,m.useEffect)(()=>{if(typeof window>"u")return;const F=r(()=>{k.current=null},"resetRun");return window.addEventListener("blur",F),()=>window.removeEventListener("blur",F)},[]),(0,m.useEffect)(()=>()=>{N.current!==null&&(cancelAnimationFrame(N.current),N.current=null)},[]);const C=(0,m.useCallback)(F=>{!e||!F||qpt(e,F,s).catch(z=>{d(eie(z))})},[e,s]),_=(0,m.useCallback)(()=>{N.current=null;const F=w.current;if(w.current=null,!F)return;const z=`${F.x}:${F.y}:${F.button}`;z!==S.current&&(S.current=z,C(UI("move",F.x,F.y,F.button)))},[C]),R=(0,m.useCallback)(F=>{const z=k.current;z&&(Math.abs(F.cssX-z.cssX)>zE||Math.abs(F.cssY-z.cssY)>zE)&&(k.current=null),w.current=F,N.current===null&&(N.current=requestAnimationFrame(_))},[_]),I=(0,m.useCallback)(F=>{const z=Date.now(),K=Hpt(k.current,F,z);k.current={button:F.button,cssX:F.cssX,cssY:F.cssY,at:z,count:K},y.current={point:F,released:!1,clickCount:K},S.current=`${F.x}:${F.y}:${F.button}`,C(UI("down",F.x,F.y,F.button,K))},[C]),T=(0,m.useCallback)(F=>{const z=y.current;y.current=null,!z?.released&&C(UI("up",F.x,F.y,F.button,z?.clickCount??1))},[C]),E=(0,m.useCallback)(()=>{const F=y.current;!F||F.released||(F.released=!0,C(UI("up",F.point.x,F.point.y,F.point.button,F.clickCount)))},[C]),L=(0,m.useCallback)((F,z,K,U)=>{C(Upt(F,z,K,U))},[C]),O=(0,m.useCallback)(F=>{v.current.set(tie(F),F),C(ND("down",F))},[C]),P=(0,m.useCallback)(F=>{v.current.delete(tie(F)),C(ND("up",F))},[C]),Q=(0,m.useCallback)(()=>{const F=Array.from(v.current.values());v.current.clear(),E();for(const z of F)C(ND("up",z))},[E,C]),D=(0,m.useRef)(Q);return(0,m.useEffect)(()=>{D.current=Q},[Q]),(0,m.useEffect)(()=>()=>{D.current(),k.current=null},[e]),{frame:a,status:o,error:c,viewerState:u,viewerMessage:p,controlledByViewer:x,setControlledByViewer:(0,m.useCallback)(F=>{F||Q(),g(F)},[Q]),pressPointer:I,releasePointer:T,cancelPointer:E,queuePointerMove:R,sendWheel:L,pressKey:O,releaseKey:P,flushHeldInput:Q}}r(Vpt,"useLocalBrowserViewer");var Gpt={connecting:"Connecting to the live view",live:"Live",reconnecting:"Reconnecting",error:"Live view unavailable"},Ypt="Waiting for the first frame from the browser",Zpt=.02;function Jpt(e,s){const n=s.width/s.height,a=e.width/e.height;if(!Number.isFinite(a)||a<=0)return{left:e.left,top:e.top,width:e.width,height:e.height};if(a>n){const o=e.height*n;return{left:e.left+(e.width-o)/2,top:e.top,width:o,height:e.height}}const i=e.width/n;return{left:e.left,top:e.top+(e.height-i)/2,width:e.width,height:i}}r(Jpt,"contentBoxOf");function Xpt(e,s,n){const a=s.width/s.height,i=`${e.left}:${e.top}:${e.width}:${e.height}`;return n&&n.rectKey===i&&Math.abs(a-n.frameRatio)/n.frameRatio<=Zpt?n:{frameRatio:a,rectKey:i,box:Jpt(e,s)}}r(Xpt,"letterboxOf");function sie(e,s){return Number.isFinite(e)?Math.min(Math.max(Math.round(e),0),Math.max(s-1,0)):0}r(sie,"clampToFrame");function eft(e,s){if(typeof e.setPointerCapture=="function")try{e.setPointerCapture(s)}catch{return}}r(eft,"capturePointer");function nie(e,s){if(typeof e.releasePointerCapture=="function")try{e.releasePointerCapture(s)}catch{return}}r(nie,"dropPointerCapture");function rie(e){return{key:e.key,code:e.code,alt:e.altKey,ctrl:e.ctrlKey,meta:e.metaKey,shift:e.shiftKey}}r(rie,"keyDescriptorOf");function e3e({sessionId:e,companyId:s,tabId:n,className:a}){const{frame:i,status:o,error:l,viewerState:c,viewerMessage:d,controlledByViewer:u,setControlledByViewer:h,pressPointer:p,releasePointer:f,cancelPointer:x,queuePointerMove:g,sendWheel:v,pressKey:y,releaseKey:k}=Vpt(e,s,n),w=(0,m.useRef)(null),N=(0,m.useRef)(null),S=(0,m.useId)();(0,m.useEffect)(()=>{if(!u)return;const F=w.current?.ownerDocument??document,z=r(K=>{K.key==="Escape"&&(K.preventDefault(),h(!1))},"onKeyDown");return F.addEventListener("keydown",z),()=>F.removeEventListener("keydown",z)},[u,h]);const C=(0,m.useCallback)(F=>{const z=w.current;if(!z||!i)return null;const K=Xpt(z.getBoundingClientRect(),i,N.current);N.current=K;const{box:U}=K;return U.width<=0||U.height<=0?null:{x:sie((F.clientX-U.left)/U.width*i.width,i.width),y:sie((F.clientY-U.top)/U.height*i.height,i.height),cssX:F.clientX,cssY:F.clientY}},[i]),_=r(F=>{if(!u)return;const z=C(F);z&&(F.preventDefault(),eft(F.currentTarget,F.pointerId),F.currentTarget.focus(),p({...z,button:kD(F.button)}))},"handlePointerDown"),R=r(F=>{if(!u)return;const z=C(F);z&&(nie(F.currentTarget,F.pointerId),f({...z,button:kD(F.button)}))},"handlePointerUp"),I=r(F=>{u&&(nie(F.currentTarget,F.pointerId),x())},"handlePointerCancel"),T=r(F=>{if(!u)return;const z=C(F);z&&g({...z,button:kD(F.button)})},"handlePointerMove"),E=r(F=>{if(!u)return;const z=C(F);z&&v(F.deltaX,F.deltaY,z.x,z.y)},"handleWheel"),L=r(F=>{!u||F.key==="Escape"||(F.preventDefault(),y(rie(F)))},"handleKeyDown"),O=r(F=>{!u||F.key==="Escape"||(F.preventDefault(),k(rie(F)))},"handleKeyUp"),P=r(F=>{u&&F.preventDefault()},"handleContextMenu"),Q=l?{tone:"error",text:l}:c==="viewer_unavailable"?{tone:"error",text:d??"The browser cannot be shown right now."}:c==="disconnected"?{tone:"info",text:d??"The browser disconnected. The live view reconnects when it returns."}:c==="agent_idle"?{tone:"info",text:d??"The agent is idle in this tab."}:c==="agent_streaming"?{tone:"info",text:d??"The agent is working in this tab."}:null,D=Q??{tone:"info",text:Ypt};return(0,t.jsxs)("div",{className:W("flex w-full flex-col gap-3",a),children:[(0,t.jsxs)("div",{className:"flex flex-wrap items-center justify-between gap-2",children:[(0,t.jsx)("span",{className:"text-xs font-medium text-muted-foreground","data-testid":"local-browser-status",children:Gpt[o]}),(0,t.jsx)($,{type:"button",size:"sm",variant:u?"outline":"default","aria-pressed":u,onClick:r(()=>h(!u),"onClick"),children:u?"Release":"Take over"})]}),(0,t.jsxs)("div",{ref:w,role:"region","aria-label":"Browser live view","aria-describedby":S,tabIndex:0,"data-testid":"local-browser-surface",className:W("relative w-full overflow-hidden rounded-md border bg-muted outline-none focus-visible:ring-2 focus-visible:ring-ring",u?"cursor-crosshair":"cursor-default"),style:{aspectRatio:i?`${i.width} / ${i.height}`:"16 / 9"},onPointerDown:_,onPointerUp:R,onPointerCancel:I,onPointerMove:T,onWheel:E,onKeyDown:L,onKeyUp:O,onContextMenu:P,children:[i?(0,t.jsx)("img",{src:i.dataUrl,alt:"",draggable:!1,className:"size-full select-none object-contain","data-testid":"local-browser-frame"}):(0,t.jsx)("div",{className:"flex size-full flex-col items-center justify-center gap-1 px-4 text-center",children:(0,t.jsx)("p",{className:W("text-sm",D.tone==="error"?"text-destructive":"text-muted-foreground"),children:D.text})}),i&&!u?(0,t.jsx)("div",{className:"pointer-events-none absolute inset-x-0 bottom-0 bg-background/90 px-3 py-2",children:(0,t.jsx)("p",{className:"text-xs text-muted-foreground",children:"The agent has control of this tab. Take over to use the mouse and keyboard."})}):null]}),i&&Q?(0,t.jsx)("p",{role:Q.tone==="error"?"alert":"status",className:W("text-xs",Q.tone==="error"?"text-destructive":"text-muted-foreground"),children:Q.text}):null,(0,t.jsx)("p",{id:S,className:"text-xs text-muted-foreground",children:"Press Escape to release control back to the agent."})]})}r(e3e,"LocalBrowserViewer");var aie=480,iie=400,tft="paperclip-local-browser",sft="data-local-browser-float-root";function nft(){const e=window.documentPictureInPicture;return typeof e?.requestWindow=="function"?e:null}r(nft,"pictureInPictureApi");function rft(e){return e.head&&e.body?Promise.resolve(!0):new Promise(s=>{const n=r(()=>{!e.head||!e.body||(e.removeEventListener("DOMContentLoaded",n),s(!0))},"onReady");e.addEventListener("DOMContentLoaded",n),n()})}r(rft,"documentReady");function aft(e,s){s.head.replaceChildren(),s.body.replaceChildren();for(const a of e.head.querySelectorAll('style, link[rel~="stylesheet"]'))s.head.appendChild(a.cloneNode(!0));for(const a of Array.from(s.documentElement.attributes))a.name!=="xmlns"&&s.documentElement.removeAttribute(a.name);for(const a of Array.from(e.documentElement.attributes))s.documentElement.setAttribute(a.name,a.value);s.title=e.title,s.body.className=e.body.className,s.body.style.margin="0",s.body.style.minHeight="100vh";const n=s.createElement("div");return n.setAttribute(sft,""),s.body.appendChild(n),n}r(aft,"prepareDocument");function ift(){const e=nft();if(e)return{mode:"pip",child:e.requestWindow({width:aie,height:iie}).catch(()=>null)};let s=null;try{s=window.open("",tft,`popup,width=${aie},height=${iie}`)}catch{s=null}return{mode:"popup",child:Promise.resolve(s)}}r(ift,"acquireWindow");function oft(e){const[s,n]=(0,m.useState)(null),a=(0,m.useRef)(null),i=(0,m.useRef)(null),o=(0,m.useRef)(0),l=(0,m.useRef)(e);(0,m.useEffect)(()=>{l.current=e});const c=(0,m.useCallback)(h=>{const p=a.current,f=i.current;if(a.current=null,i.current=null,p&&f&&p.removeEventListener("pagehide",f),h&&p&&!p.closed)try{p.close()}catch{return}},[]),d=(0,m.useCallback)(()=>{o.current+=1,c(!0),n(null)},[c]),u=(0,m.useCallback)(async()=>{o.current+=1;const h=o.current;if(c(!0),n(null),typeof window>"u")return null;const p=ift(),f=await p.child;if(!f)return null;const x=r(()=>{if(!f.closed)try{f.close()}catch{return}},"discard");if(o.current!==h)return x(),null;try{if(!await rft(f.document)||o.current!==h||f.closed)return x(),null;const g=aft(document,f.document),v=r(()=>{o.current!==h||a.current!==f||(c(!1),n(null),l.current?.())},"pageHide");a.current=f,i.current=v,f.addEventListener("pagehide",v),n({mode:p.mode,container:g});try{f.focus()}catch{}return p.mode}catch{return x(),null}},[c]);return(0,m.useEffect)(()=>{const h=r(()=>c(!0),"onUnload");return window.addEventListener("pagehide",h),()=>{window.removeEventListener("pagehide",h),o.current+=1,c(!0)}},[c]),{target:s,open:u,close:d}}r(oft,"useLocalBrowserFloatWindow");function B2(e){return e.sessionId+":"+e.tabId}r(B2,"watchKey");function lft(e){try{return new URL(e).host}catch{return e}}r(lft,"hostOf");function t3e(e,s){return!e.ownerUserId||e.ownerUserId===s}r(t3e,"viewableBy");function cft(e,s){for(const n of e){const a=n.agentActivity;if(!(!a||a.state!=="operating"||a.tabId===null)&&t3e(n,s)&&n.tabs.some(i=>i.tabId===a.tabId))return{sessionId:n.sessionId,tabId:a.tabId}}return null}r(cft,"operatedWatch");function dft(){const[e,s]=(0,m.useState)(()=>typeof document>"u"||document.visibilityState!=="hidden");return(0,m.useEffect)(()=>{const n=r(()=>s(document.visibilityState!=="hidden"),"onChange");return document.addEventListener("visibilitychange",n),()=>document.removeEventListener("visibilitychange",n)},[]),e}r(dft,"useDocumentVisible");function s3e({companyId:e}){const s=kt(),n=(0,m.useMemo)(()=>["local-browser-sessions",e],[e]),[a,i]=(0,m.useState)(null),o=(0,m.useRef)(null);o.current=a;const l=(0,m.useRef)(null),c=(0,m.useRef)(!1),d=dft(),u=te({queryKey:M.auth.session,queryFn:r(()=>Ma.getSession(),"queryFn"),retry:!1}),h=u.data?.user?.id??u.data?.session?.userId??null,p=(0,m.useRef)(h);p.current=h;const f=(0,m.useCallback)(()=>{o.current&&(l.current=B2(o.current)),i(null)},[]),x=oft(f),{open:g,close:v}=x,y=te({queryKey:n,queryFn:r(()=>lb.sessions(e),"queryFn"),enabled:!!e,refetchOnWindowFocus:!0});(0,m.useEffect)(()=>{if(a||!y.data)return;const N=cft(y.data.sessions,h);!N||l.current===B2(N)||(l.current=null,i(N))},[y.data,a,h]),TN((0,m.useCallback)(N=>{if(N.type!=="local_browser.activity")return;const S=pOe.safeParse(N.payload);if(!S.success)return;const{sessionId:C,state:_,tabId:R,at:I}=S.data;if(_==="closed"){l.current=null,i(L=>L&&L.sessionId===C?null:L),s.invalidateQueries({queryKey:n});return}const T=s.getQueryData(n)?.sessions.find(L=>L.sessionId===C);if((!T||R!==null&&!T.tabs.some(L=>L.tabId===R))&&s.invalidateQueries({queryKey:n}),!T||(s.setQueryData(n,L=>L&&{...L,sessions:L.sessions.map(O=>O.sessionId===C?{...O,agentActivity:{state:_,tabId:R,at:I}}:O)}),R===null||!t3e(T,p.current)))return;const E={sessionId:C,tabId:R};l.current!==B2(E)&&(l.current=null,i(L=>L&&B2(L)===B2(E)?L:E))},[s,n])),(0,m.useEffect)(()=>{a||(c.current=!1,v())},[a,v]),(0,m.useEffect)(()=>{!a||c.current||(c.current=!0,typeof navigator<"u"&&navigator.userActivation?.isActive&&g())},[a,g]);const k=(0,m.useMemo)(()=>{if(!a)return"";const N=y.data?.sessions.find(S=>S.sessionId===a.sessionId)?.tabs.find(S=>S.tabId===a.tabId);return N?N.title||lft(N.url):"Browser tab"},[y.data,a]);if(!a)return null;const w=x.target||d?(0,t.jsx)(e3e,{sessionId:a.sessionId,companyId:e??void 0,tabId:a.tabId}):null;return x.target?(0,Vh.createPortal)((0,t.jsxs)("div",{className:"flex min-h-screen flex-col gap-2 bg-background p-3 text-foreground","data-testid":"local-browser-float-window",children:[(0,t.jsx)("p",{className:"truncate text-xs font-medium text-muted-foreground",children:k}),w]}),x.target.container):(0,t.jsxs)("aside",{"aria-label":"Agent browser","data-testid":"local-browser-float-panel",className:"fixed bottom-4 right-4 z-50 flex w-(--sz-22rem) max-w-(--sz-calc-4) flex-col gap-2 rounded-lg border bg-background p-3 shadow-xl",children:[(0,t.jsxs)("div",{className:"flex items-center justify-between gap-2",children:[(0,t.jsx)("p",{className:"min-w-0 truncate text-xs font-medium",children:k}),(0,t.jsxs)("div",{className:"flex shrink-0 gap-1",children:[(0,t.jsx)($,{type:"button",size:"sm",variant:"outline",onClick:r(()=>{g()},"onClick"),children:"Pop out"}),(0,t.jsx)($,{type:"button",size:"sm",variant:"ghost","aria-label":"Close agent browser",onClick:f,children:"Close"})]})]}),w]})}r(s3e,"LocalBrowserFloatHost");async function oie(e,s){const n=await fetch(`/api/announcements/${e}`,{credentials:"same-origin",cache:"no-store",...s});if(!n.ok)throw new sn("Announcement request failed",n.status,null);return n}r(oie,"request");var lie={async current(e){const s=await(await oie("current",{signal:e})).json();return s===null?null:VOe.parse(s)},async dismiss(e,s,n){await oie(`${encodeURIComponent(e)}/dismiss`,{method:"POST",signal:n,headers:{"Content-Type":"application/json"},body:JSON.stringify({companyId:s})})}},sq=new Map;function UV(e){return`paperclip.announcement-dismissals.v1:${encodeURIComponent(e)}:`}r(UV,"announcementStoragePrefix");function KI(e){const s=UV(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);bbe.safeParse(o).success&&(l==="pending"||l==="synced")&&sq.set(i,l==="pending")}}catch{}for(const[a,i]of sq)a.startsWith(s)&&n.set(a.slice(s.length),i);return n}r(KI,"readAnnouncementDismissals");function SD(e,s,n){const a=`${UV(e)}${s}`;sq.set(a,n);try{return localStorage.setItem(a,n?"pending":"synced"),!0}catch{return!1}}r(SD,"saveAnnouncementDismissal");var uft=3e3;function mft(e){const{userId:s,enabled:n}=e,a=(0,m.useRef)(e);a.current=e;const[i,o]=(0,m.useState)(null),l=(0,m.useRef)(()=>{});(0,m.useEffect)(()=>{if(o(null),!s||!n)return;let d=!1,u=0,h=null,p;const f=new Map,x=new Set,g=UV(s);let v=null;try{v=new BroadcastChannel(g)}catch{}const y=r(()=>!d&&a.current.userId===s&&a.current.enabled,"active");async function k(T,E=!0){if(!y()||f.has(T)||!a.current.companyId)return;const L=new AbortController;f.set(T,L);const O=setTimeout(()=>L.abort(),1e4);try{await lie.dismiss(T,a.current.companyId,L.signal),y()&&SD(s,T,!1)}catch{y()&&!x.has(T)&&(x.add(T),a.current.onSaveFailure(E))}finally{clearTimeout(O),f.delete(T)}}r(k,"sync");async function w(){for(const[T,E]of KI(s)){if(!y())return;E&&await k(T)}}r(w,"flush");function N(){u++,clearTimeout(p),h?.abort(),h=null,o(null)}r(N,"suspend");function S(){if(!y()||document.visibilityState==="hidden")return;N();const T=u,E=new AbortController;h=E;const L=r(()=>y()&&u===T&&!E.signal.aborted,"stillCurrent");let O=!1,P=!1,Q=null;const D=r(()=>{!L()||!O||!P||Q&&!KI(s).has(Q.id)&&(!Q.expiresAt||Date.parse(Q.expiresAt)>Date.now())&&o({userId:s,announcement:Q})},"show");p=setTimeout(()=>{O=!0,D()},uft),w(),lie.current(E.signal).then(F=>{Q=F,P=!0,D()}).catch(()=>{})}r(S,"resume");function C(){const T=KI(s);o(E=>E?.userId===s&&T.has(E.announcement.id)?null:E)}r(C,"receive");function _(T){T.key?.startsWith(g)&&C()}r(_,"onStorage");function R(){document.visibilityState==="hidden"?N():S()}r(R,"onVisibility");function I(){w()}return r(I,"onOnline"),v&&(v.onmessage=T=>{const E=bbe.safeParse(T.data);E.success&&(KI(s).has(E.data)||SD(s,E.data,!0),C())}),l.current=T=>{if(!y())return;const E=SD(s,T,!0);o(null),u++,h?.abort();try{v?.postMessage(T)}catch{}k(T,E)},document.addEventListener("visibilitychange",R),window.addEventListener("online",I),window.addEventListener("storage",_),S(),()=>{d=!0,u++,clearTimeout(p),h?.abort();for(const T of f.values())T.abort();v?.close(),document.removeEventListener("visibilitychange",R),window.removeEventListener("online",I),window.removeEventListener("storage",_),l.current=()=>{}}},[s,n]);const c=n&&i?.userId===s?i.announcement:null;return(0,m.useEffect)(()=>{if(!c?.expiresAt)return;let d;const u=r(()=>{const h=Date.parse(c.expiresAt)-Date.now();h<=0?o(null):d=setTimeout(u,Math.min(h,2147483647))},"check");return u(),()=>clearTimeout(d)},[c]),{announcement:c,dismiss:(0,m.useCallback)(d=>l.current(d),[])}}r(mft,"useAnnouncement");function hft(e,s){const n=mW(),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="${WOe}">${p}`})}catch{}finally{clearTimeout(u)}})(),()=>{d.abort(),clearTimeout(u)}},[c,i,a]),c&&o?.key===i?o.document:null}r(hft,"useAnnouncementAnimation");function cie({action:e,primary:s,onClick:n}){const a=(0,t.jsxs)(t.Fragment,{children:[e.label,!s&&e.kind==="external"&&(0,t.jsx)(oo,{className:"size-3.5 shrink-0","aria-hidden":"true"})]}),i=r(o=>{o.button===1&&n()},"onAuxClick");return(0,t.jsx)($,{asChild:!0,variant:s?"default":"ghost",size:"sm",className:"h-auto min-h-9 min-w-0 whitespace-normal py-2 text-left",children:e.kind==="external"?(0,t.jsx)("a",{href:e.url,target:"_blank",rel:"noopener noreferrer",onClick:n,onAuxClick:i,children:a}):(0,t.jsx)(Ke,{to:e.path,onClick:n,onAuxClick:i,children:a})})}r(cie,"Action");function kR({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=hft(e,a),p=!!h;return(0,t.jsxs)(nn,{role:"region","aria-labelledby":o,className:W("relative w-full max-w-(--announcement-width) gap-0 overflow-hidden rounded-xl p-0 shadow-sm",i),onKeyDown:r(f=>{f.key==="Escape"&&(f.preventDefault(),f.stopPropagation(),s())},"onKeyDown"),children:[(u||h)&&(0,t.jsxs)("div",{className:"relative h-(--announcement-image-mobile-height) w-full shrink-0 overflow-hidden bg-muted md:h-(--announcement-image-height)",children:[u&&(0,t.jsx)("img",{src:d,alt:p?"":e.image.alt,referrerPolicy:"no-referrer",onError:r(()=>c(d),"onError"),className:"h-full w-full object-cover"}),p&&(0,t.jsx)("div",{role:"img","aria-label":e.animation.alt,className:"pointer-events-none absolute inset-0",children:(0,t.jsx)("iframe",{title:e.animation.alt,"aria-hidden":"true",tabIndex:-1,sandbox:"",referrerPolicy:"no-referrer",srcDoc:h,className:"h-full w-full border-0"})})]}),(0,t.jsx)($,{variant:"secondary",size:"icon","aria-label":"Dismiss announcement",onClick:s,className:"absolute right-2 top-2 z-10 size-8 rounded-full shadow-sm",children:(0,t.jsx)(En,{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)(cie,{action:e.secondaryLink,onClick:s}),(0,t.jsx)("div",{className:"ml-auto min-w-0 max-w-full",children:(0,t.jsx)(cie,{action:e.primaryAction,primary:!0,onClick:s})})]})]})}r(kR,"AnnouncementCard");var pft='[role="dialog"][data-state="open"], [role="alertdialog"][data-state="open"], [aria-modal="true"]:not([data-state="closed"]), dialog[open]';function fft(e){const[s,n]=(0,m.useState)(!1);return(0,m.useEffect)(()=>{if(!e)return;const a=r(()=>n(!!document.querySelector(pft)),"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(fft,"useModalOpen");function xft({health:e}){const{userId:s,settled:n}=Af(),{selectedCompanyId:a,loading:i}=ps(),{onboardingOpen:o}=P8(),l=bd(),c=Gqe(),d=e?.deploymentMode==="local_trusted"?"local-board":n?s:null,{announcement:u,dismiss:h}=mft({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=fft(!!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)(kR,{announcement:u,onDismiss:r(()=>h(u.id),"onDismiss")},u.id)})}r(xft,"AnnouncementWell");function MM(e){const s=e.split("/").filter(Boolean);return s.length===1?s[0]?.toLowerCase()==="onboarding":s.length===2?s[1]?.toLowerCase()==="onboarding":!1}r(MM,"isOnboardingPath");function gft(e){const s=e.split("/").filter(Boolean);if(s.length===2&&s[1]?.toLowerCase()==="onboarding")return s[0]}r(gft,"companyPrefixFromOnboardingPath");function qE(){return 3}r(qE,"onboardingStepForCompany");function bft(e){const{pathname:s,companyPrefix:n,companies:a,cloudManaged:i}=e;if(!MM(s))return null;const o=r(()=>a.length===1?{initialStep:qE(),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:qE(),companyId:l.id}:i?o():{initialStep:1}}r(bft,"resolveRouteOnboardingOptions");function vft(e){return!e.agentsLoaded||e.agentsRefreshing||e.agentCount>0?!1:!MM(e.pathname)}r(vft,"shouldRouteAgentlessCompanyToOnboarding");function yft(e){return e.currentStep>1&&e.currentStep>e.entryStep}r(yft,"canGoBackFromOnboardingStep");function die(e){return e.targetStep<e.currentStep&&e.targetStep>=e.entryStep}r(die,"canJumpToOnboardingStep");function KV(e){return!e.hasCompanies&&!MM(e.pathname)}r(KV,"shouldRedirectCompanylessRouteToOnboarding");function jft(e){return e.onboardingOpen||!e.routeDismissed}r(jft,"isOnboardingWizardActive");function wft({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)(pm,{slot:a,context:e,className:"plugin-app-shell-overlay"},`${a.pluginId}:${a.pluginVersion}:${a.id}`))})}r(wft,"AppShellEntries");function n3e({localTrusted:e=!1}){const{userId:s,settled:n}=Af(),{selectedCompanyId:a,selectedCompany:i,loading:o}=ps(),{onboardingOpen:l,onboardingRouteDismissed:c}=P8(),{pathname:d}=ua(),u=n?s??(e?"local-board":null):null,h=l||!c&&MM(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)(wft,{context:p},JSON.stringify([u,a]))}r(n3e,"PluginAppShellOverlays");function r3e({visible:e}){const s=ua(),{selectedCompanyId:n}=ps(),{openNewIssue:a}=al(),i=J8(n),{enabled:o}=aw(),{enabled:l}=Q3(),c=(0,m.useMemo)(()=>!o&&!l?[{type:"link",to:"/dashboard",label:"Home",icon:NF},{type:"link",to:"/issues",label:"Tasks",icon:xa},{type:"action",label:"New Task",icon:t5,onClick:r(()=>a(),"onClick")},{type:"link",to:"/agents/all",label:"Agents",icon:Ho},{type:"link",to:"/inbox",label:"Inbox",icon:Od,badge:i.inbox}]:[{type:"link",to:"/dashboard",label:"Home",icon:NF},...o?[{type:"link",to:"/chats",label:"Chat",icon:X_}]:[],{type:"action",label:"New Task",icon:t5,onClick:r(()=>a(),"onClick")},{type:"link",to:"/issues",label:"Tasks",icon:xa,badge:l?i.inbox:void 0},{type:"link",to:"/agents/all",label:"Agents",icon:Ho},...l?[]:[{type:"link",to:"/inbox",label:"Inbox",icon:Od,badge:i.inbox}]],[a,i.inbox,o,l]);return(0,t.jsx)("nav",{className:W("mobile-bottom-nav fixed bottom-0 left-0 right-0 z-30 bg-muted md:hidden pb-(--sz-safe-bottom)"),"data-visible":e,inert:!e,"aria-label":"Mobile navigation",children:(0,t.jsx)("div",{className:"grid h-16 px-1",style:{gridTemplateColumns:`repeat(${c.length}, minmax(0, 1fr))`},children:c.map(d=>{if(d.type==="action"){const h=d.icon,p=/\/issues\/new(?:\/|$)/.test(s.pathname);return(0,t.jsxs)("button",{type:"button",onClick:d.onClick,className:W("relative flex min-w-0 flex-col items-center justify-center gap-1 rounded-md text-(length:--text-nano) font-medium transition-colors",p?"text-foreground":"text-muted-foreground hover:text-foreground"),children:[(0,t.jsx)(h,{className:"h-(--sz-18px) w-(--sz-18px)"}),(0,t.jsx)("span",{className:"truncate",children:d.label})]},d.label)}const u=d.icon;return(0,t.jsx)(dv,{to:d.to,state:If,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)(it,{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(r3e,"MobileBottomNav");function ak(e){if(typeof document>"u")return null;const s=document.querySelector(`meta[name="${e}"]`)?.getAttribute("content")?.trim();return s||null}r(ak,"readMetaContent");function nq(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(nq,"normalizeHexColor");function kft(e){const s=nq(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(kft,"hexToRgb");function CD(e){const s=e/255;return s<=.03928?s/12.92:((s+.055)/1.055)**2.4}r(CD,"relativeLuminanceChannel");function Nft(e){const{r:s,g:n,b:a}=kft(e),i=.2126*CD(s)+.7152*CD(n)+.0722*CD(a);return 1.05/(i+.05)>=(i+.05)/.05?eqe:Zze}r(Nft,"pickReadableTextColor");function Sft(){return ak("paperclip-worktree-enabled")==="true"}r(Sft,"isWorktreeRuntime");function Cft(){return ak("paperclip-instance-id")}r(Cft,"getWorktreeInstanceId");function _ft(){if(ak("paperclip-worktree-enabled")!=="true")return null;const e=ak("paperclip-worktree-name"),s=nq(ak("paperclip-worktree-color"));return!e||!s?null:{enabled:!0,name:e,color:s,textColor:nq(ak("paperclip-worktree-text-color"))??Nft(s)}}r(_ft,"getWorktreeUiBranding");function a3e(){const e=_ft(),{copied:s,failed:n,copy:a}=Z0(),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(a3e,"WorktreeBanner");var Aft=3e4;function Ift(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(Ift,"formatRelativeTimestamp");function Tft(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(Tft,"describeReason");function i3e({devServer:e}){const[s,n]=(0,m.useState)(!1);if((0,m.useEffect)(()=>{if(!s)return;const d=window.setTimeout(()=>{n(!1)},Aft);return()=>window.clearTimeout(d)},[s]),!e?.enabled||!e.restartRequired)return null;const a=e,i=Ift(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 Iu.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)(it,{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:[Tft(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)($Qe,{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)(_i,{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)(_i,{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)(_i,{className:"h-3.5 w-3.5"}),(0,t.jsx)("span",{children:s?"Restart requested":"Restart now"})]})]})]})})}r(i3e,"DevRestartBanner");var o3e=["standalone","fullscreen","window-controls-overlay"];function Rft(e){return`(display-mode: ${e})`}r(Rft,"displayModeQuery");function Eft(){if(!(typeof window>"u"||typeof window.matchMedia!="function"))return window.matchMedia.bind(window)}r(Eft,"defaultMatchMedia");function rq(e=Eft(),s=typeof navigator>"u"?void 0:navigator.standalone){return s===!0?!0:e?o3e.some(n=>e(Rft(n)).matches):!1}r(rq,"isChromelessDisplayMode");function QI({label:e,children:s,onClick:n}){return(0,t.jsxs)(Bn,{children:[(0,t.jsx)(On,{asChild:!0,children:(0,t.jsx)($,{type:"button",variant:"ghost",size:"icon-sm",className:"size-8 text-muted-foreground hover:text-foreground","aria-label":e,onClick:r(()=>{n()},"onClick"),children:s})}),(0,t.jsx)($n,{children:e})]})}r(QI,"ControlButton");function Lft(e=typeof window>"u"?null:window.history.state){const s=e?.idx;return typeof s=="number"&&s>0}r(Lft,"hasInAppHistory");function Mft(){const[e,s]=(0,m.useState)(()=>typeof window<"u"?rq():!1);return(0,m.useEffect)(()=>{if(typeof window>"u")return;const n=r(()=>s(rq()),"update");if(n(),typeof window.matchMedia!="function")return;const a=o3e.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(Mft,"useChromeless");function aq({mobile:e,onNavigateHome:s}){const n=Mft(),a=bd(),i=(0,m.useCallback)(()=>{if(Lft()){window.history.back();return}s?s():window.location.assign("/dashboard")},[s]),o=(0,m.useCallback)(()=>{window.location.reload()},[]),l=(0,m.useCallback)(async()=>{const d=window.location.href;try{if(navigator.share){await navigator.share({title:document.title||"Paperclip",url:d});return}await wa(d),a?.pushToast({title:"Link copied",tone:"success"})}catch(u){if(u instanceof DOMException&&u.name==="AbortError")return;a?.pushToast({title:"Share failed",body:"Try opening the page in your browser.",tone:"error"})}},[a]),c=(0,m.useCallback)(()=>{window.open(window.location.href,"_blank","noopener,noreferrer")},[]);return n?(0,t.jsxs)("div",{className:W("flex items-center gap-1",e?"h-10 border-b border-border bg-background/95 px-3 backdrop-blur supports-[backdrop-filter]:bg-background/85":"h-9 border-b border-border px-2"),children:[(0,t.jsx)(QI,{label:"Back",onClick:i,children:(0,t.jsx)(wl,{className:"h-4 w-4"})}),(0,t.jsx)("div",{className:"flex-1"}),(0,t.jsx)(QI,{label:"Refresh",onClick:o,children:(0,t.jsx)(Ai,{className:"h-4 w-4"})}),(0,t.jsx)(QI,{label:"Share",onClick:l,children:(0,t.jsx)(MW,{className:"h-4 w-4"})}),(0,t.jsx)(QI,{label:"Open in Browser",onClick:c,children:(0,t.jsx)(Dn,{className:"h-4 w-4"})})]}):null}r(aq,"StandaloneBrowserControls");var Pft=16384,Dft=40;function $ft(e){if(!e)return;const s=[];for(const n of e.slice(0,Pft).split(`
380
380
  `).slice(0,41)){const a=/^\s*(?:at|in) ([A-Za-z_$][\w$.-]{0,99})(?:\s|$)/.exec(n)?.[1]??/^([A-Za-z_$][\w$.-]{0,99})@/.exec(n)?.[1];if(a&&s.push(` at ${a}`),s.length===Dft)break}return s.length?`
381
381
  ${s.join(`
382
- `)}`:void 0}r($ft,"sanitizeComponentStack");function l3e(){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(l3e,"readBrowserErrorState");function Oft(e){const s=$ft(e.componentStack);return{tags:{react_error_boundary:e.boundary},contexts:{react:s?{componentStack:s}:{},browser_state:l3e()}}}r(Oft,"buildBrowserErrorContext");var uie=Promise.resolve();function QV(e){const s=uie.then(e);return uie=s.catch(()=>{}),s}r(QV,"enqueue");var RN=null;function Bft(e,s){return QV(async()=>{if(!RN)try{const n=await fd(()=>import("./prod-COP_vZWu.js"),__vite__mapDeps([4,5]));n.init(zft(e,s)),RN=n}catch{}})}r(Bft,"initBrowserErrorMonitoring");function Fft(){return QV(async()=>{const e=RN;if(RN=null,!e)return;const s=e.getClient();try{e.getCurrentScope().setClient(void 0)}catch{}try{await s?.close(2e3)}catch{}})}r(Fft,"teardownBrowserErrorMonitoring");function WV(e,s){let n;try{s&&(n=Oft(s))}catch{}QV(async()=>{try{n?RN?.captureException(e,n):RN?.captureException(e)}catch{}})}r(WV,"captureBrowserException");function zft(e,s){return{dsn:e,environment:s??void 0,release:"d9031b084c3ce8a0f3aa86345ab1b0523b4a5914",tracesSampleRate:0,sendDefaultPii:!1,beforeSend:r((n,a)=>{try{if(n.contexts={...n.contexts,browser_state:n.contexts?.browser_state??l3e()},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(zft,"buildBrowserSentryInitOptions");var qft=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){WV(e,{boundary:"route",componentStack:s.componentStack})}componentDidUpdate(e){this.state.error&&e.resetKey!==this.props.resetKey&&this.setState({error:null})}render(){const{error:e}=this.state;return e?(0,t.jsxs)("div",{className:"mx-auto max-w-2xl space-y-4 px-4 py-10",children:[(0,t.jsxs)("div",{children:[(0,t.jsx)("h1",{className:"text-lg font-semibold",children:"This page hit an error"}),(0,t.jsx)("p",{className:"mt-1 text-sm text-muted-foreground",children:"Something went wrong while rendering this page. You can go back and try again, or reload."})]}),(0,t.jsx)("pre",{className:"overflow-auto rounded-md border border-destructive/30 bg-destructive/10 px-3 py-2 text-xs text-destructive whitespace-pre-wrap",children:e.message}),(0,t.jsxs)("div",{className:"flex items-center gap-2",children:[(0,t.jsx)($,{variant:"outline",size:"sm",onClick:this.props.onReset,children:"Go back"}),(0,t.jsx)($,{size:"sm",onClick:r(()=>window.location.reload(),"onClick"),children:"Reload page"})]})]}):this.props.children}};function c3e({children:e}){const s=ua(),n=Yn(),a=`${s.pathname}${s.search}`;return(0,t.jsx)(qft,{resetKey:a,onReset:r(()=>n(-1),"onReset"),children:e})}r(c3e,"RouteErrorBoundary");var mie={bot:io,cpu:qm,brain:$x,zap:C6,rocket:vFe,code:Hbe,terminal:pf,shield:v3,eye:Jd,search:Jr,wrench:hf,hammer:b3,lightbulb:g3,sparkles:W0,star:Q0,heart:jC,flame:RFe,bug:Yy,cog:Kbe,database:f3,globe:gm,lock:Ao,mail:VQ,"message-square":D0,"file-code":ql,"git-branch":to,package:Xh,puzzle:Ox,target:K0,wand:$W,atom:iFe,"circuit-board":JKe,radar:hFe,swords:PQe,telescope:aFe,microscope:bQe,crown:A8,gem:Zbe,hexagon:Yd,pentagon:wQe,fingerprint:kF},Uft="bot";function Kft(e){return e&&V$e.includes(e)?mie[e]:mie[Uft]}r(Kft,"getAgentIcon");function UE({icon:e,className:s}){const n=Kft(e);return(0,t.jsx)(n,{className:s})}r(UE,"AgentIcon");function d3e({open:e,onOpenChange:s,...n}){return(0,t.jsx)(qs,{open:e,onOpenChange:s,children:(0,t.jsxs)(Ws,{"aria-describedby":void 0,className:"gap-0 overflow-hidden p-0 sm:max-w-md",children:[(0,t.jsxs)("div",{className:"px-4 pt-4 pb-3",children:[(0,t.jsx)(Qs,{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)(Qft,{...n,onComplete:r(()=>s(!1),"onComplete")},String(e))]})})}r(d3e,"AgentChatPicker");function Qft({agents:e,onSelect:s,onComplete:n,loading:a,error:i,onRetry:o,existingChatAgentIds:l,renderAgentIcon:c}){const d=(0,m.useRef)(!1),u=(0,m.useRef)(null);(0,m.useEffect)(()=>(d.current=!0,()=>{d.current=!1,u.current?.abort()}),[]);const[h,p]=(0,m.useState)(""),[f,x]=(0,m.useState)(null),[g,v]=(0,m.useState)(null);async function y(k){if(f)return;x(k.id),v(null);const w=new AbortController;u.current=w;try{await s(k,w.signal),d.current&&n()}catch(N){v(N instanceof Error?N.message:"Couldn’t open chat. Try again.")}finally{x(null)}}return r(y,"selectAgent"),(0,t.jsxs)(y3,{children:[(0,t.jsx)(aS,{"aria-label":"Search agents by name or role",placeholder:"Search by name or role…",value:h,onValueChange:p}),g&&(0,t.jsx)("p",{role:"alert",className:"px-4 py-3 text-sm text-destructive",children:g}),f&&(0,t.jsx)("p",{role:"status",className:"sr-only",children:"Opening conversation…"}),i?(0,t.jsxs)("div",{role:"alert",className:"flex flex-col items-start gap-2 p-4 text-sm",children:[(0,t.jsx)("p",{children:"Couldn’t load agents. Try again."}),o&&(0,t.jsx)($,{variant:"outline",size:"sm",onClick:o,children:"Retry"})]}):a?(0,t.jsx)("p",{role:"status",className:"p-4 text-sm text-muted-foreground",children:"Loading agents…"}):(0,t.jsxs)(iS,{children:[(0,t.jsx)(oS,{children:(0,t.jsxs)("div",{className:"flex flex-col items-center gap-2 px-4",children:[(0,t.jsx)("span",{children:e.length?`No agents match “${h}”`:"No agents yet."}),e.length?(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)("span",{className:"text-xs text-muted-foreground",children:"Try another name or role."}),(0,t.jsx)($,{variant:"ghost",size:"sm",onClick:r(()=>p(""),"onClick"),children:"Clear search"})]}):(0,t.jsx)("span",{className:"text-xs text-muted-foreground",children:"Create an agent from the Agents page to start chatting."})]})}),(0,t.jsx)(Hu,{children:e.map(k=>(0,t.jsxs)(Xo,{value:k.id,keywords:[k.name,k.title??"",k.role],onSelect:r(()=>{y(k)},"onSelect"),disabled:f!==null,className:"gap-3 px-3 py-3",children:[c?c(k):(0,t.jsx)(UE,{icon:k.icon,className:"size-4 shrink-0"}),(0,t.jsxs)("span",{className:"flex min-w-0 flex-1 flex-col gap-0.5",children:[(0,t.jsx)("span",{className:"truncate font-medium",children:k.name}),(0,t.jsx)("span",{className:"truncate text-xs text-muted-foreground",children:k.title??k.role})]}),l&&(0,t.jsx)("span",{className:"shrink-0 text-xs text-muted-foreground",children:l.includes(k.id)?"Open chat":"New chat"}),k.status==="paused"&&(0,t.jsx)("span",{className:"text-xs text-(--status-agent-paused)",children:"Paused"}),k.status==="terminated"&&(0,t.jsx)("span",{className:"text-xs text-muted-foreground",children:"Terminated"}),k.status==="pending_approval"&&(0,t.jsx)("span",{className:"text-xs text-muted-foreground",children:"Awaiting approval"})]},k.id))})]})]})}r(Qft,"AgentChatPickerResults");function NR({agents:e,existingChatAgentIds:s,availableAgents:n=e,activeId:a,previews:i={},loading:o=!1,error:l,onRetry:c,initialSearch:d="",onSelect:u,onBrowse:h,onAddChat:p,historyLoading:f,historyError:x,onRetryHistory:g}){const v=Yn(),[y,k]=(0,m.useState)(!1),[w,N]=(0,m.useState)(d),S=(0,m.useRef)(null),C=(0,m.useId)(),_=w.trim().toLocaleLowerCase(),R=e.filter(T=>`${T.name} ${T.title??""} ${T.role}`.toLocaleLowerCase().includes(_));function I(){N(""),S.current?.focus()}return r(I,"focusSearch"),(0,t.jsxs)("aside",{"aria-labelledby":C,className:"flex h-full min-h-0 flex-col border-r border-border bg-background",children:[(0,t.jsxs)("div",{className:"flex shrink-0 flex-col gap-4 px-3 pb-4 pt-4",children:[(0,t.jsxs)("div",{className:"flex items-center justify-between gap-2",children:[(0,t.jsx)("h2",{id:C,className:"text-sm font-semibold",children:"Chat"}),(0,t.jsx)($,{variant:"outline",size:"icon-sm","aria-label":"Add chat",title:"Add chat",onClick:r(()=>k(!0),"onClick"),children:(0,t.jsx)(gn,{className:"size-4"})})]}),(0,t.jsxs)("div",{className:"relative",children:[(0,t.jsx)(Jr,{"aria-hidden":"true",className:"pointer-events-none absolute left-3 top-1/2 size-3.5 -translate-y-1/2 text-muted-foreground"}),(0,t.jsx)(dt,{ref:S,"aria-label":"Search agents",placeholder:"Find an agent",value:w,onChange:r(T=>N(T.target.value),"onChange"),onKeyDown:r(T=>{T.key==="Escape"&&(T.stopPropagation(),N(""))},"onKeyDown"),className:"h-8 pl-8 pr-8 text-xs md:text-xs"}),w&&(0,t.jsx)($,{variant:"ghost",size:"icon-xs","aria-label":"Clear search",className:"absolute right-1 top-1/2 -translate-y-1/2",onClick:I,children:(0,t.jsx)(En,{className:"size-3"})})]})]}),(0,t.jsxs)("div",{className:"flex min-h-0 flex-1 flex-col gap-2 overflow-y-auto px-3 pb-3 scrollbar-auto-hide",children:[(0,t.jsx)("p",{className:"px-2 text-(length:--text-micro) font-medium uppercase tracking-widest text-muted-foreground",children:_?"Search results":"Teammates"}),(0,t.jsx)("span",{role:"status",className:"sr-only",children:o?"Loading agents":`${R.length} ${R.length===1?"agent":"agents"}`}),f&&(0,t.jsx)("p",{role:"status",className:"px-2 text-xs text-muted-foreground",children:"Loading chat history…"}),x&&(0,t.jsxs)("div",{role:"alert",className:"flex flex-col items-start gap-2 px-2 py-3",children:[(0,t.jsx)("p",{className:"text-xs text-muted-foreground",children:"Some chat history couldn’t load."}),(0,t.jsx)($,{variant:"outline",size:"sm",onClick:g,children:"Retry chat history"})]}),l?(0,t.jsxs)("div",{role:"alert",className:"flex flex-col items-start gap-2 px-2 py-6",children:[(0,t.jsx)("p",{className:"text-sm",children:"Couldn’t load your chats."}),(0,t.jsx)($,{variant:"outline",size:"sm",onClick:c,children:"Try again"})]}):o?(0,t.jsx)("div",{"aria-hidden":"true",className:"flex flex-col gap-1",children:[0,1,2,3].map(T=>(0,t.jsxs)("div",{className:"flex items-center gap-3 rounded-md px-2 py-3 motion-safe:animate-pulse",children:[(0,t.jsx)("div",{className:"size-8 shrink-0 rounded-lg bg-muted"}),(0,t.jsxs)("div",{className:"flex flex-1 flex-col gap-2",children:[(0,t.jsx)("div",{className:"h-3 w-2/3 rounded-sm bg-muted"}),(0,t.jsx)("div",{className:"h-2 w-full rounded-sm bg-muted"})]})]},T))}):R.length?(0,t.jsx)("nav",{"aria-label":"Agent conversations",className:"flex flex-col gap-1",children:R.map(T=>(0,t.jsxs)(Ke,{to:`/chats/${encodeURIComponent(T.status==="terminated"?T.id:Vl(T))}`,"aria-current":a===T.id?"page":void 0,title:`${T.name}${T.title?` · ${T.title}`:""}`,onClick:r(E=>{u&&(E.preventDefault(),u(T))},"onClick"),className:W("flex min-w-0 items-center gap-3 rounded-md px-2 py-3 text-left transition-colors hover:bg-accent/60 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-ring",a===T.id&&"bg-accent text-accent-foreground"),children:[(0,t.jsx)(lr,{agent:T,size:32}),(0,t.jsxs)("span",{className:"flex min-w-0 flex-1 flex-col gap-0.5",children:[(0,t.jsx)("span",{className:"truncate text-sm font-medium",children:T.name}),(0,t.jsx)("span",{className:"truncate text-xs text-muted-foreground",children:T.status==="terminated"?"Terminated":T.status==="paused"?"Paused":i[T.id]??T.title??"Start a conversation"})]})]},T.id))}):!e.length&&(f||x)?null:(0,t.jsxs)("div",{className:"flex flex-col items-start gap-2 px-2 py-6",children:[(0,t.jsx)("p",{className:"text-sm font-medium",children:e.length?"No agents found":"No chats yet"}),(0,t.jsx)("p",{className:"text-xs leading-relaxed text-muted-foreground",children:e.length?"Try another name or role.":"Choose an agent to start a conversation."}),!e.length&&(0,t.jsx)($,{variant:"outline",size:"sm",onClick:r(()=>k(!0),"onClick"),children:"Choose an agent"}),e.length>0&&(0,t.jsx)($,{variant:"outline",size:"sm",onClick:I,children:"Clear search"})]})]}),(0,t.jsx)("div",{className:"shrink-0 px-3 py-4",children:(0,t.jsx)($,{variant:"ghost",size:"sm",className:"w-full justify-start gap-2 px-2 text-muted-foreground",asChild:!h,onClick:h,children:h?(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)(Ho,{className:"size-4"}),"Browse all agents"]}):(0,t.jsxs)(Ke,{to:"/agents/all",children:[(0,t.jsx)(Ho,{className:"size-4"}),"Browse all agents"]})})}),(0,t.jsx)(d3e,{agents:n,open:y,onOpenChange:k,existingChatAgentIds:s??e.map(T=>T.id),loading:o,error:l,onRetry:c,renderAgentIcon:r(T=>(0,t.jsx)(lr,{agent:T,size:32}),"renderAgentIcon"),onSelect:r(async(T,E)=>{p?await p(T,E):u?await u(T,E):v(`/chats/${encodeURIComponent(Vl(T))}`),E?.aborted||N("")},"onSelect")})]})}r(NR,"AgentConversationSidebar");var KE={list:r(e=>we.get(`/companies/${e}/chats`),"list"),get:r((e,s)=>we.get(`/companies/${e}/chats/${encodeURIComponent(s)}`),"get"),ensure:r((e,s)=>we.post(`/companies/${e}/chats/${encodeURIComponent(s)}`,{}),"ensure")};function u3e(){const{selectedCompanyId:e}=ps(),{enabled:s,loaded:n}=aw(),a=te({queryKey:M.auth.session,queryFn:r(()=>Ma.getSession(),"queryFn")}),i=a.data?.user?.id??a.data?.session?.userId??null;return{companyId:e,userId:i,enabled:s,loaded:n,agents:te({queryKey:M.agents.list(e),queryFn:r(()=>_t.list(e),"queryFn"),enabled:s&&!!e}),chats:te({queryKey:M.agentChats.list(e,i),queryFn:r(()=>KE.list(e),"queryFn"),enabled:s&&!!e&&a.isSuccess}),session:a}}r(u3e,"useAgentChatNavigation");function m3e(e,s){const n=kt(),a=Yn(),{isMobile:i,setSidebarOpen:o}=Wa(),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 KE.ensure(e,c.id);n.setQueryData(M.agentChats.detail(e,s,c.id),h),n.setQueryData(M.issues.detail(h.id),h),n.setQueryData(M.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(Vl(c))}`),i&&o(!1))},[n,e,s,a,i,o])}r(m3e,"useOpenAgentChat");function Wft(){const{companyId:e,userId:s,agents:n,chats:a,session:i}=u3e(),o=m3e(e,s),l=Yn(),c=Tf(e),{isMobile:d,setSidebarOpen:u}=Wa(),{pathname:h}=ua(),p=h.split("/chats/")[1]?.split("/")[0],f=n.data??[],x=n.isSuccess?[...new Set((a.data??[]).flatMap(C=>C.conversationAgentId&&!f.some(_=>_.id===C.conversationAgentId)?[C.conversationAgentId]:[]))]:[],g=cm({queries:x.map(C=>({queryKey:M.agents.detail(C),queryFn:r(()=>_t.get(C,e),"queryFn")}))}),v=new Map(f.map(C=>[C.id,C]));for(const C of g)C.data&&v.set(C.data.id,C.data);const y=[...v.values()].find(C=>C.id===p||C.status!=="terminated"&&encodeURIComponent(Vl(C))===p),k=(a.data??[]).flatMap(C=>{const _=C.conversationAgentId?v.get(C.conversationAgentId):void 0;return _?[_]:[]});y&&!k.some(C=>C.id===y.id)&&k.unshift(y);const w=new Set(k.map(C=>C.id)),N=f.filter(C=>!w.has(C.id)&&C.status!=="terminated"&&(!c.isSuccess||eg(c.data,"agent",C.id)!=="left")).sort((C,_)=>C.name.localeCompare(_.name,void 0,{sensitivity:"base"})),S=Object.fromEntries((a.data??[]).filter(C=>C.conversationState==="active").map(C=>[C.conversationAgentId,"Working…"]));return(0,t.jsx)(NR,{agents:[...k,...N],availableAgents:f,existingChatAgentIds:k.map(C=>C.id),activeId:y?.id,previews:S,loading:n.isPending||a.isPending||i.isPending,error:n.error??a.error??i.error,onRetry:r(()=>{n.refetch(),a.refetch(),i.refetch()},"onRetry"),historyLoading:g.some(C=>C.isPending),historyError:g.find(C=>C.error)?.error,onRetryHistory:r(()=>{g.filter(C=>C.isError).forEach(C=>{C.refetch()})},"onRetryHistory"),onAddChat:o,onSelect:r(C=>{l(`/chats/${encodeURIComponent(C.status==="terminated"?C.id:Vl(C))}`),d&&u(!1)},"onSelect")},`${e}:${s}`)}r(Wft,"AgentConversationsSidebar");var WI=240,iq=208,oq=420,hie=16;function QE(e){return Math.min(oq,Math.max(iq,e))}r(QE,"clampSidebarWidth$1");function pie(e){if(typeof window>"u")return WI;try{const s=window.localStorage.getItem(e);if(!s)return WI;const n=Number.parseInt(s,10);return Number.isFinite(n)?QE(n):WI}catch{return WI}}r(pie,"readStoredSidebarWidth$1");function fie(e,s){if(!(typeof window>"u"))try{window.localStorage.setItem(e,String(QE(s)))}catch{}}r(fie,"writeStoredSidebarWidth$1");function Hft({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)(()=>pie(o)),[x,g]=(0,m.useState)(!1),v=(0,m.useRef)(p),y=(0,m.useRef)(null);(0,m.useEffect)(()=>{const P=pie(o);v.current=P,f(P)},[o]);const k=s?p:0,w=s?n?64:k:0,N=s?n&&!a?64:k:0,S=N>w,C=i&&s&&!n,_=(0,m.useMemo)(()=>({width:`${w}px`}),[w]),R=(0,m.useMemo)(()=>({width:`${N}px`}),[N]),I=(0,m.useCallback)(P=>{const Q=QE(P);v.current=Q,f(Q),fie(o,Q)},[o]),T=(0,m.useCallback)(P=>{C&&(P.preventDefault(),P.currentTarget.setPointerCapture(P.pointerId),y.current={startX:P.clientX,startWidth:v.current},g(!0))},[C]),E=(0,m.useCallback)(P=>{if(!y.current)return;const Q=QE(y.current.startWidth+P.clientX-y.current.startX);v.current=Q,f(Q)},[]),L=(0,m.useCallback)(()=>{y.current&&(y.current=null,g(!1),fie(o,v.current))},[o]),O=(0,m.useCallback)(P=>{C&&(P.key==="ArrowLeft"?(P.preventDefault(),I(p-hie)):P.key==="ArrowRight"?(P.preventDefault(),I(p+hie)):P.key==="Home"?(P.preventDefault(),I(iq)):P.key==="End"&&(P.preventDefault(),I(oq)))},[C,I,p]);return(0,t.jsxs)("div",{className:W("relative h-full shrink-0",l),style:_,children:[(0,t.jsx)("div",{className:W("absolute inset-y-0 left-0 flex flex-col overflow-hidden",S?"z-30 border-r border-border bg-background shadow-lg":"z-0"),style:R,"data-sidebar-overlay":S?"":void 0,onMouseEnter:c,onMouseLeave:d,onFocusCapture:u,onBlurCapture:h,children:e}),C?(0,t.jsx)("div",{role:"separator","aria-label":"Resize sidebar","aria-orientation":"vertical","aria-valuemin":iq,"aria-valuemax":oq,"aria-valuenow":p,tabIndex:0,"data-dragging":x?"":void 0,className:"group absolute inset-y-0 z-20 cursor-col-resize touch-none outline-none",style:{right:-4,width:8},onPointerDown:T,onPointerMove:E,onPointerUp:L,onPointerCancel:L,onLostPointerCapture:L,onKeyDown:O,children:(0,t.jsx)("div",{className: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(Hft,"SidebarShell$1");function HI({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)(Bke,{children:e})})}r(HI,"SecondarySidebar$1");var h3e={listStacks:r(()=>we.get("/cloud/stacks"),"listStacks")};function PM(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(PM,"cloudAppUrl");function p3e(e){return PM(e,"/stacks/new")}r(p3e,"cloudStackCreateUrl");function f3e(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(f3e,"tenantSignInReturnPath");function Vft(e,s,n){const a=s?.trim();if(!a)return null;const i=PM(e,`/v1/stacks/${encodeURIComponent(a)}/entry-redirect`);if(!i)return null;const o=new URL(i);return o.searchParams.set("returnTo",f3e(n)),o.toString()}r(Vft,"cloudStackEntryUrl");function x3e(e,s){const n=s?.trim();return n?PM(e,`/workspaces/${encodeURIComponent(n)}/settings?section=people`):null}r(x3e,"cloudStackInviteUrl");function Gft(e){return PM(e,"/orgs?manage=1")}r(Gft,"cloudPortfolioManageUrl");function g3e(){const e=ed(),s=!!e,n=te({queryKey:M.cloud.stacks,queryFn:r(()=>h3e.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:x3e(e.cloudBaseUrl,a.stackSlug)}r(g3e,"useCloudInviteUrl");function Yft(e,s){if(!s)return!1;if(s.source==="local_implicit"||s.isInstanceAdmin)return!0;if(!e)return!1;const n=s.memberships?.find(a=>a.companyId===e&&a.status==="active");return n?.membershipRole==="owner"||n?.membershipRole==="admin"||n?.membershipRole==="operator"||n?.membershipRole==="member"}r(Yft,"canInviteCompanyMembers");function b3e(e=!0){const s=Abe(),n=te({queryKey:M.access.currentBoardAccess,queryFn:r(()=>ir.getCurrentBoardAccess(),"queryFn"),enabled:e,retry:!1,staleTime:3e4});return e&&Yft(s?.selectedCompanyId,n.data)}r(b3e,"useCanInviteCompanyMembers");function v3e(e){const s=window.location.hostname.endsWith(".staging.paperclip.app"),{data:n,isError:a}=te({queryKey:M.stagingCommit,queryFn:r(()=>Iu.get(),"queryFn"),enabled:s&&e,staleTime:0,retry:!1});return s&&!a?n?.commit??null:null}r(v3e,"useStagingCommit");function Zft(e){return e?.trim().toLowerCase().replace(/['"]/g,"").replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")||null}r(Zft,"slugifyUserPart");function y3e(e){const s=[e?.id,e?.name,e?.email?.split("@")[0],e?.email];for(const n of s){const a=Zft(n);if(a)return`/u/${a}`}return"/u/me"}r(y3e,"userProfilePath");var Jft="Toggle the app appearance.";function Lk({className:e,variant:s="icon",onAfterToggle:n}){const{theme:a,toggleTheme:i}=qqe(),o=a==="dark",l=o?"Switch to light mode":"Switch to dark mode",c=o?K1e:Uwe;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:Jft})]})]}):(0,t.jsx)($,{type:"button",variant:"ghost",size:"icon-sm",onClick:d,"aria-label":l,title:l,className:W("text-muted-foreground",e),children:(0,t.jsx)(c,{})})}r(Lk,"ThemeToggle");var I5=null,j3e=!1,lq=!1,cq=new Set;function WE(){for(const e of cq)e()}r(WE,"emit");function Xft(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(Xft,"isIosSafariLike");function ext(e=window){const s=r(a=>{a.preventDefault(),I5=a,WE()},"onPrompt"),n=r(()=>{I5=null,j3e=!0,WE()},"onInstalled");return e.addEventListener("beforeinstallprompt",s),e.addEventListener("appinstalled",n),()=>{e.removeEventListener("beforeinstallprompt",s),e.removeEventListener("appinstalled",n)}}r(ext,"captureInstallPrompt");function txt(){return j3e||rq()?"installed":I5?"prompt":Xft()?"ios-manual":"unavailable"}r(txt,"installAvailability");async function sxt(){const e=I5;if(!e)return"unavailable";I5=null,WE(),await e.prompt();const{outcome:s}=await e.userChoice;return s}r(sxt,"promptInstall");function dq(e){lq!==e&&(lq=e,WE())}r(dq,"setIosInstallHelpOpen");function nxt(){return lq}r(nxt,"iosInstallHelpOpen");function rxt(){return(0,m.useSyncExternalStore)(w3e,nxt,()=>!1)}r(rxt,"useIosInstallHelpOpen");function w3e(e){return cq.add(e),()=>{cq.delete(e)}}r(w3e,"subscribe$1");function axt(){return(0,m.useSyncExternalStore)(w3e,txt,()=>"unavailable")}r(axt,"useInstallAvailability");var xie="Install app",ixt="Add Paperclip to your home screen or dock.";function k3e({variant:e,onAfterAction:s}){const n=axt();if(n==="installed"||n==="unavailable")return null;const a=r(()=>{n==="ios-manual"?dq(!0):sxt(),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)(Ui,{className:"size-4"})}),(0,t.jsx)("span",{className:"min-w-0 flex-1 truncate",children:xie})]}):(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)(Ui,{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:xie}),(0,t.jsx)("span",{className:"block text-xs text-muted-foreground",children:ixt})]})]})}r(k3e,"InstallAppMenuAction");function oxt(){const e=rxt();return(0,t.jsx)(qs,{open:e,onOpenChange:dq,children:(0,t.jsxs)(Ws,{children:[(0,t.jsxs)(ln,{children:[(0,t.jsx)(Qs,{children:"Install Paperclip"}),(0,t.jsx)(mn,{children:"Add Paperclip to your Home Screen from Safari."})]}),(0,t.jsxs)("ol",{className:"space-y-3 text-sm text-foreground",children:[(0,t.jsxs)(_D,{index:1,icon:(0,t.jsx)(RQe,{className:"size-4"}),children:["Tap ",(0,t.jsx)("strong",{children:"Share"})," in the Safari toolbar."]}),(0,t.jsxs)(_D,{index:2,icon:(0,t.jsx)(MQe,{className:"size-4"}),children:["Choose ",(0,t.jsx)("strong",{children:"Add to Home Screen"}),"."]}),(0,t.jsxs)(_D,{index:3,children:["Keep ",(0,t.jsx)("strong",{children:"Open as Web App"})," on, then tap ",(0,t.jsx)("strong",{children:"Add"}),"."]})]}),(0,t.jsx)(cr,{children:(0,t.jsx)($,{type:"button",onClick:r(()=>dq(!1),"onClick"),children:"Done"})})]})})}r(oxt,"IosInstallHelpDialog");function _D({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(_D,"InstallStep");function lxt(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(lxt,"formatTimestamp$2");function cxt(e){return!!e&&!Number.isNaN(new Date(e).getTime())}r(cxt,"isValidTimestamp");function dxt(e){return e?.devServer?.lastRestartAt??e?.serverInfo?.processStartedAt??null}r(dxt,"restartTimestamp");function uxt(e){const s=e?.serverInfo?.git;return s?.available?`${s.shortSha} · ${s.subject}`:"Commit unavailable"}r(uxt,"commitLabel");function mxt(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(mxt,"localChangesLabel");function AD({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(AD,"ServerInfoRow");function N3e(){const e=te({queryKey:M.instance.experimentalSettings,queryFn:r(()=>jr.getExperimental(),"queryFn")}).data?.enableServerInfoDebugView===!0,s=te({queryKey:M.health,queryFn:r(()=>Iu.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=dxt(n),l=cxt(o),c=i?"Health unavailable":a?"Loading...":lxt(o),d=i?"Health unavailable":a?"Loading...":uxt(n),u=i?"Health unavailable":a?"Loading...":mxt(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)(AD,{icon:Nu,label:"Last restarted",value:c,dateTime:!i&&!a&&l?o:null}),(0,t.jsx)(AD,{icon:SW,label:"Running commit",value:d}),(0,t.jsx)(AD,{icon:aQe,label:"Checkout state",value:u})]})}r(N3e,"SidebarServerInfo");var hxt="/company/settings/members?tab=invites",pxt="https://docs.paperclip.ing/",fxt="https://paperclip.ing/feedback";function xxt(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(xxt,"deriveInitials$2");function ID({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(ID,"MenuAction$1");function gie({deploymentMode:e,open:s,onOpenChange:n,forceExpanded:a=!1}){const o=!!ed(),{hidden:l,loaded:c}=Au(),d=g3e(),u=b3e(!o),h=o?d:u?hxt:null,p=c&&h!==null&&!Gx(l,"company.members")&&!Gx(l,"company.invites"),[f,x]=(0,m.useState)(!1),{isMobile:g,setSidebarOpen:v,collapsed:y,peeking:k}=Wa(),w=y&&!k&&!a,N=s??f,S=v3e(N),C=n??x,{data:_}=te({queryKey:M.auth.session,queryFn:r(()=>Ma.getSession(),"queryFn"),retry:!1}),R=SS({onSignedOut:O}),I=_?.user.name?.trim()||"Board",T=_?.user.email?.trim()||(e==="authenticated"?"Signed in":"Local workspace board"),E=xxt(I),L=y3e(_?.user);function O(){C(!1),g&&v(!1)}r(O,"closeNavigationChrome");function P(){R.mutate()}return r(P,"handleSignOut"),(0,t.jsx)("div",{className:"bg-border/50 px-3 py-2 dark:bg-muted",children:(0,t.jsxs)("div",{className:W("flex items-center gap-0.5",!w&&"px-2"),children:[(0,t.jsxs)(dr,{open:N,onOpenChange:C,children:[(0,t.jsx)(wr,{asChild:!0,children:(0,t.jsxs)("button",{type:"button",className:W("flex min-w-0 items-center gap-2.5 rounded-lg text-left text-(length:--text-compact) font-medium text-foreground/80 transition-colors hover:bg-sidebar-accent hover:text-sidebar-accent-foreground",w?"w-full px-3 py-2":"flex-1 px-2 py-1.5"),"aria-label":"Open account menu",children:[(0,t.jsxs)(ko,{size:"sm",children:[_?.user.image?(0,t.jsx)(Zc,{src:_.user.image,alt:I}):null,(0,t.jsx)(No,{children:E})]}),(0,t.jsx)("span",{className:W("min-w-0 flex-1 truncate",w&&"block w-0 min-w-0 overflow-hidden whitespace-nowrap text-transparent select-none"),children:I})]})}),(0,t.jsxs)(sr,{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:L,"aria-label":"View profile",onClick:O,className:"absolute inset-0 transition-colors hover:bg-accent focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-ring"}),(0,t.jsxs)(ko,{className:"pointer-events-none relative size-9",children:[_?.user.image?(0,t.jsx)(Zc,{src:_.user.image,alt:I}):null,(0,t.jsx)(No,{className:"text-xs text-foreground",children:E})]}),(0,t.jsxs)("div",{className:"pointer-events-none relative min-w-0 flex-1",children:[(0,t.jsx)("h2",{className:"truncate text-sm font-semibold leading-(--profile-popover-label-line-height) text-foreground",children:I}),(0,t.jsx)("p",{className:"truncate text-(length:--text-micro) leading-(--profile-popover-meta-line-height) text-muted-foreground",children:T}),S?(0,t.jsxs)("a",{className:"pointer-events-auto block truncate font-mono text-(length:--text-micro) leading-(--profile-popover-meta-line-height) text-muted-foreground hover:underline focus-visible:underline",href:`https://github.com/paperclipai/paperclip/commit/${S}`,target:"_blank",rel:"noreferrer","aria-label":`View commit ${S} on GitHub`,title:S,children:["SHA ",S.slice(0,7)]}):null]})]}),(0,t.jsxs)("div",{className:"flex flex-1 flex-col gap-0.5 border-t border-border px-2.5 pb-2.5 pt-2",children:[(0,t.jsx)(ID,{label:"Settings",icon:Su,href:"/company/settings",onClick:O}),p&&h?(0,t.jsx)(ID,{label:"Invite",icon:oh,href:h,topLevel:o,onClick:O}):null,(0,t.jsx)(ID,{label:"Documentation",icon:bS,href:pxt,external:!0,onClick:r(()=>C(!1),"onClick")}),(0,t.jsx)(Lk,{variant:"compact-menu-action",onAfterToggle:r(()=>C(!1),"onAfterToggle")}),(0,t.jsx)(k3e,{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:P,disabled:R.isPending,children:[(0,t.jsx)("span",{className:"flex size-5 shrink-0 items-center justify-center text-muted-foreground",children:(0,t.jsx)(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)(N3e,{})]})]})]}),!w&&!o?(0,t.jsxs)(Bn,{children:[(0,t.jsx)(On,{asChild:!0,children:(0,t.jsx)("a",{href:fxt,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)(fg,{className:"h-4 w-4","aria-hidden":"true"})})}),(0,t.jsx)($n,{side:"top",children:"Share feedback"})]}):null]})})}r(gie,"SidebarAccountMenu$1");function S3e({onNewIssue:e,onSearch:s,onToggleSidebar:n,onTogglePanel:a,onShowShortcuts:i,onGoToInbox:o}){(0,m.useEffect)(()=>{let l=!1,c=null;const d=r(()=>{c!==null&&(window.clearTimeout(c),c=null)},"clearGoChordTimeout"),u=r(()=>{l=!1,d()},"disarmGoChord"),h=r(()=>{l=!0,d(),c=window.setTimeout(()=>{l=!1,c=null},1200)},"armGoChord");function p(g){if(g.defaultPrevented){u();return}if(o){const v=zve({armed:l,defaultPrevented:g.defaultPrevented,key:g.key,metaKey:g.metaKey,ctrlKey:g.ctrlKey,altKey:g.altKey,target:g.target,hasOpenDialog:V0()});if(v==="arm"){h();return}if(v==="navigate_inbox"){u(),g.preventDefault(),o();return}if(v==="focus_comment"||v==="open_file_viewer"){u(),g.preventDefault();return}v==="disarm"&&u()}if(!k3(g.target)&&!V0()){if(g.key==="/"&&!g.metaKey&&!g.ctrlKey&&!g.altKey){g.preventDefault(),Sze()||s?.();return}if(g.key==="?"&&!g.metaKey&&!g.ctrlKey&&!g.altKey){g.preventDefault(),i?.();return}g.key==="c"&&!g.metaKey&&!g.ctrlKey&&!g.altKey&&(g.preventDefault(),e?.()),g.key==="["&&!g.metaKey&&!g.ctrlKey&&(g.preventDefault(),n?.()),g.key==="]"&&!g.metaKey&&!g.ctrlKey&&(g.preventDefault(),a?.())}}r(p,"handleKeyDown");const f=r(()=>u(),"handlePointerDown"),x=r(g=>{g.target instanceof HTMLElement&&g.target!==document.body&&u()},"handleFocusIn");return document.addEventListener("pointerdown",f,!0),document.addEventListener("focusin",x,!0),document.addEventListener("keydown",p),()=>{u(),document.removeEventListener("pointerdown",f,!0),document.removeEventListener("focusin",x,!0),document.removeEventListener("keydown",p)}},[e,s,n,a,i,o])}r(S3e,"useKeyboardShortcuts");var gxt=new Set(["auth","invite","board-claim","cli-auth","docs","s"]);function C3e(e){const s=(e.split("?")[0]??"").split("/").filter(Boolean);if(s.length===0)return!0;const[n]=s;return!gxt.has(n)}r(C3e,"isRememberableCompanyPath");function bxt(e){const s=xj(e.companyPrefix);return e.companies.find(n=>xj(n.issuePrefix)===s)??null}r(bxt,"findCompanyByPrefix");function vxt(e){const s=HQ(e.pathname);return s?bxt({companies:e.companies,companyPrefix:s})?.id??null:e.fallbackCompanyId}r(vxt,"getRememberedPathOwnerCompanyId");function yxt(e){const s=e.path?_8(e.path):"/dashboard";if(!C3e(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&&xj(i[1]??"")!==xj(e.companyPrefix))return"/dashboard"}return s}r(yxt,"sanitizeRememberedPathForCompany");var _3e="paperclip.companyPaths";function A3e(){try{const e=localStorage.getItem(_3e);if(e)return JSON.parse(e)}catch{}return{}}r(A3e,"getCompanyPaths");function jxt(e,s){const n=A3e();n[e]=s,localStorage.setItem(_3e,JSON.stringify(n))}r(jxt,"saveCompanyPath");function I3e(){const{companies:e,selectedCompanyId:s,selectedCompany:n,selectionSource:a}=ps(),i=ua(),o=Yn(),l=(0,m.useRef)(s),c=(0,m.useMemo)(()=>vxt({companies:e,pathname:i.pathname,fallbackCompanyId:l.current}),[e,i.pathname]),d=i.pathname+i.search;(0,m.useEffect)(()=>{const u=c,h=_8(d);u&&C3e(h)&&jxt(u,h)},[d,c]),(0,m.useEffect)(()=>{if(s){if(l.current!==null&&s!==l.current&&a!=="route_sync"&&n){const u=A3e(),h=yxt({path:u[s],companyPrefix:n.issuePrefix});o(`/${n.issuePrefix}${h}`,{replace:!0})}l.current=s}},[n,s,a,o])}r(I3e,"useCompanyPageMemory");var wxt=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 T3e(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 wxt({topZone:o("--mobile-nav-scroll-top-zone"),hideDistance:o("--mobile-nav-scroll-hide-distance"),showDistance:o("--mobile-nav-scroll-show-distance")},c.top,c.max);let u=null;const h=r(()=>{u===null&&(u=requestAnimationFrame(()=>{u=null;const{top:p,max:f}=l(),x=d.visible,g=d.update(p,f);g!==x&&a(g)}))},"onScroll");return window.addEventListener("scroll",h,{passive:!0}),()=>{window.removeEventListener("scroll",h),u!==null&&cancelAnimationFrame(u)}},[e,s]),n}r(T3e,"useMobileNavVisibility");function R3e(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(R3e,"resolveArchivedCompanyBounce");function kxt(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(kxt,"resolveCompanyArchiveDeparture");function E3e(e){const{selectionSource:s,selectedCompanyId:n,routeCompanyId:a}=e;return!(n===a||s==="manual"&&n)}r(E3e,"shouldSyncCompanySelectionFromRoute");function Nxt(e,s){return e instanceof HTMLElement?!(s instanceof HTMLElement)||!document.contains(s)||s===document.body||s===document.documentElement?!0:!e.contains(s):!1}r(Nxt,"shouldFocusMainContentAfterNavigation");function L3e(e){if(!(e instanceof HTMLElement))return()=>{};const s=window.requestAnimationFrame(()=>{Nxt(e,document.activeElement)&&e.focus({preventScroll:!0})});return()=>window.cancelAnimationFrame(s)}r(L3e,"scheduleMainContentFocus");function M3e(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(M3e,"pinDocumentScrollToZero");function om({scope:e="global",requestedPrefix:s}){const n=ua(),{setBreadcrumbs:a}=Wn(),{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)(nn,{className:"block p-6",children:[(0,t.jsxs)("div",{className:"flex items-center gap-3",children:[(0,t.jsx)("div",{className:"rounded-md border border-destructive/20 bg-destructive/10 p-2",children:(0,t.jsx)(Es,{className:"h-5 w-5 text-destructive"})}),(0,t.jsxs)("div",{children:[(0,t.jsx)("h1",{className:"text-xl font-semibold",children:h}),(0,t.jsx)("p",{className:"text-sm text-muted-foreground",children:p})]})]}),(0,t.jsxs)("div",{className:"mt-4 rounded-md border border-border bg-muted/20 px-3 py-2 text-xs text-muted-foreground",children:["Requested path: ",(0,t.jsx)("code",{className:"font-mono",children:d})]}),(0,t.jsxs)("div",{className:"mt-5 flex flex-wrap gap-2",children:[(0,t.jsx)($,{asChild:!0,children:(0,t.jsxs)(Ke,{to:c,children:[(0,t.jsx)(S6,{className:"mr-1.5 h-4 w-4"}),"Open dashboard"]})}),(0,t.jsx)($,{variant:"outline",asChild:!0,children:(0,t.jsx)(Ke,{to:"/",children:"Go home"})})]})]})})}r(om,"NotFoundPage");function Sxt(e,s){return SNe(e,s)[0]?.toLowerCase()??null}r(Sxt,"getCompanyRouteSegment$1");var Cxt=new Set(["browse","connections","assistant-connection","connect","chat","vercel-connect","review","attention","gateways","advanced","app"]);function _xt({sidebarSections:e}){const{sidebarOpen:s,setSidebarOpen:n,toggleSidebar:a,collapsed:i,peeking:o,setPeeking:l,isMobile:c,setForceCollapsed:d}=Wa(),{openNewIssue:u,openOnboarding:h}=al(),{togglePanelVisible:p}=Rf(),f=bd()?.pushToast??null,{companies:x,loading:g,selectedCompany:v,selectedCompanyId:y,selectionSource:k,setSelectedCompanyId:w}=ps(),{companyPrefix:N,pluginRoutePath:S,agentId:C,routineId:_}=ga(),R=Yn(),I=ua(),T=C8(),{enabled:E}=Rc(),L=CNe(I.pathname,N),O=L.builtInContextualSurface==="settings",P=L.companySegments,Q=L.isTaskDetail,{enabled:D}=aw(),F=D&&P[0]?.toLowerCase()==="chats",z=E&&(Q||F),K=P[0]?.toLowerCase()==="tools",U=P[0]?.toLowerCase()==="apps",q=U&&P[1]&&!Cxt.has(P[1].toLowerCase())?P[1]:null,G=U&&P[1]?.toLowerCase()==="app"&&P[2]?P[2]:null,se=(0,m.useRef)(!1),Z=(0,m.useRef)(null),ie=(0,m.useRef)(null),J=(0,m.useRef)(new Dke),re=(0,m.useRef)(I.key),oe=T3e(c&&!Q,I.pathname),[V,X]=(0,m.useState)(!1),Y=(0,m.useMemo)(()=>{if(!N)return null;const Et=N.toUpperCase();return x.find(ct=>ct.issuePrefix.toUpperCase()===Et)??null},[x,N]),ae=!!N&&!g&&x.length>0&&!Y,ne=(0,m.useMemo)(()=>S?.toLowerCase()??Sxt(I.pathname,N),[N,I.pathname,S]),ce=Y?.id??null,he=Y?.issuePrefix??null,{slots:pe}=Bd({slotTypes:["page","routeSidebar"],companyId:ce,enabled:!!(ce&&ne)}),ge=(0,m.useMemo)(()=>GW(pe,ne),[ne,pe]),Ee=(0,m.useMemo)(()=>({companyId:ce,companyPrefix:he}),[ce,he]),de=O?(0,t.jsx)(sZe,{}):!E&&L.builtInContextualSurface==="skills"?(0,t.jsx)(kse,{}):q?(0,t.jsx)(jse,{kind:"connection",connectionId:q}):G?(0,t.jsx)(jse,{kind:"application",applicationId:G}):U||K?(0,t.jsx)(dZe,{}):ge?E?(0,t.jsx)(U3,{surface:`plugin:${ge.id}`,title:ge.displayName,children:(0,t.jsx)(pm,{slot:ge,context:Ee,className:"min-h-0 flex-1",missingBehavior:"placeholder"})}):(0,t.jsx)(pm,{slot:ge,context:Ee,className:"h-full w-full",missingBehavior:"placeholder"}):null,Ne=F?(0,t.jsx)(Wft,{}):L.builtInContextualSurface==="agent"&&C?(0,t.jsx)(NZe,{agentRef:C}):E&&L.builtInContextualSurface==="routine"&&_?(0,t.jsx)(gVe,{children:(0,t.jsx)(_Ze,{routineId:_})}):E&&L.builtInContextualSurface==="skills"?(0,t.jsx)(kse,{}):de,le=Ne!=null,Le=E&&le&&(F||L.builtInContextualSurface==="skills"||L.builtInContextualSurface==="agent"||L.builtInContextualSurface==="routine"||U||K),Ie=E&&le&&!Le,ye=le&&(!E||Le),Ae=!E||!le?null:ge&&!L.builtInContextualSurface?`plugin:${ge.id}`:L.builtInContextualSurface,Qe=(0,m.useRef)(null),{data:ue}=te({queryKey:M.health,queryFn:r(()=>Iu.get(),"queryFn"),retry:!1,refetchInterval:r(Et=>Et.state.data?.devServer?.enabled?2e3:!1,"refetchInterval"),refetchIntervalInBackground:!1});(0,m.useLayoutEffect)(()=>(d(!E&&le),()=>d(!1)),[le,d,E]),(0,m.useEffect)(()=>{const Et=Qe.current;Ae&&N&&Et&&Et.surface!==Ae&&Et.pathname!==I.pathname&&XYe({surface:Ae,companyPrefix:N,previousPathname:Et.pathname}),Qe.current={pathname:I.pathname,surface:Ae}},[N,Ae,I.pathname]),(0,m.useEffect)(()=>{g||se.current||ue?.deploymentMode!=="authenticated"&&(ue?.cloud||x.length===0&&(se.current=!0,h()))},[x,g,h,ue?.cloud,ue?.deploymentMode]),(0,m.useEffect)(()=>{if(!N||g||x.length===0)return;if(!Y){const ct=(y?x.find(qe=>qe.id===y):null)??x[0]??null;ct&&y!==ct.id&&w(ct.id,{source:"route_sync"});return}if(N!==Y.issuePrefix){const ct=I.pathname.replace(/^\/[^/]+/,"");R(`/${Y.issuePrefix}${ct}${I.search}`,{replace:!0});return}const Et=R3e({matchedCompany:Y,selectedCompanyId:y,companies:x});if(Et){f?.({title:`${Y.name} is archived`,body:`Switched to ${Et.name}.`,tone:"info",dedupeKey:`archived-company-bounce:${Y.id}`}),w(Et.id,{source:"route_sync"}),R(`/${Et.issuePrefix}/dashboard`,{replace:!0});return}E3e({selectionSource:k,selectedCompanyId:y,routeCompanyId:Y.id})&&w(Y.id,{source:"route_sync"})},[N,x,g,Y,I.pathname,I.search,R,f,k,y,w]);const Be=p,ft=(0,m.useCallback)(()=>{document.dispatchEvent(new KeyboardEvent("keydown",{key:"k",metaKey:!0,bubbles:!0,cancelable:!0}))},[]),gt=(0,m.useRef)(null),Xe=(0,m.useRef)(!1),Fe=(0,m.useRef)(!1),at=(0,m.useCallback)(()=>{gt.current!==null&&(window.clearTimeout(gt.current),gt.current=null)},[]),Tt=(0,m.useCallback)(()=>{at(),gt.current=window.setTimeout(()=>l(!0),50)},[at,l]),Dt=(0,m.useCallback)(()=>{at(),l(!0)},[at,l]),Ot=(0,m.useCallback)(()=>{at(),gt.current=window.setTimeout(()=>l(!1),120)},[at,l]),rt=(0,m.useCallback)(()=>{Xe.current=!0,i&&!Fe.current&&Tt()},[i,Tt]),Pe=(0,m.useCallback)(()=>{Xe.current=!1,Fe.current=!1,Ot()},[Ot]),De=(0,m.useCallback)(()=>{Fe.current||Dt()},[Dt]),ht=(0,m.useCallback)(()=>{Xe.current||Ot()},[Ot]);(0,m.useEffect)(()=>at,[at]);const Ft=(0,m.useRef)(i);return(0,m.useEffect)(()=>{i!==Ft.current&&(i?(at(),l(!1),Fe.current=Xe.current):Fe.current=!1,Ft.current=i)},[i,at,l]),(0,m.useEffect)(()=>{if(!o)return;const Et=r(ct=>{ct.key==="Escape"&&(at(),l(!1))},"onKeyDown");return window.addEventListener("keydown",Et),()=>window.removeEventListener("keydown",Et)},[o,at,l]),I3e(),S3e({onNewIssue:r(()=>u(),"onNewIssue"),onSearch:ft,onToggleSidebar:a,onTogglePanel:Be,onShowShortcuts:r(()=>X(!0),"onShowShortcuts"),onGoToInbox:r(()=>R("/inbox"),"onGoToInbox")}),(0,m.useEffect)(()=>{if(!c)return;const Et=30,ct=50,qe=75;let Oe=0,Re=0;const Ve=r(Ge=>{const vt=Ge.touches[0];Oe=vt.clientX,Re=vt.clientY},"onTouchStart"),xe=r(Ge=>{const vt=Ge.changedTouches[0],Ss=vt.clientX-Oe;if(!(Math.abs(vt.clientY-Re)>qe)){if(!s&&Oe<Et&&Ss>ct){n(!0);return}s&&Ss<-50&&n(!1)}},"onTouchEnd");return document.addEventListener("touchstart",Ve,{passive:!0}),document.addEventListener("touchend",xe,{passive:!0}),()=>{document.removeEventListener("touchstart",Ve),document.removeEventListener("touchend",xe)}},[c,s,n]),(0,m.useEffect)(()=>{const Et=document.body.style.overflow;return document.body.style.overflow=c?"visible":"clip",()=>{document.body.style.overflow=Et}},[c]),(0,m.useEffect)(()=>{if(!c)return M3e()},[c]),(0,m.useEffect)(()=>{if(typeof document>"u")return;const Et=ie.current;return L3e(Et)},[I.pathname]),(0,m.useEffect)(()=>{const Et=ie.current;if(!Et)return;const ct=r(()=>{J.current.remember(re.current,Et.scrollTop)},"recordScroll");return Et.addEventListener("scroll",ct,{passive:!0}),()=>Et.removeEventListener("scroll",ct)},[]),(0,m.useLayoutEffect)(()=>{const Et=ie.current,ct=Pke({previousPathname:Z.current,pathname:I.pathname,navigationType:T,state:I.state});Z.current=I.pathname;const qe=T==="POP",Oe=qe?J.current.recall(I.key):0;if(re.current=I.key,qe){W6(Et,Oe);const Re=requestAnimationFrame(()=>W6(Et,Oe));return()=>cancelAnimationFrame(Re)}ct&&$ke(Et)},[I.key,I.pathname,I.state,T]),(0,t.jsx)(Lke,{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)(a3e,{}),(0,t.jsx)(i3e,{devServer:ue?.devServer}),(0,t.jsxs)("div",{className:W("min-h-0 flex-1",c?"w-full":"flex overflow-clip"),children:[c&&s&&(0,t.jsx)("button",{type:"button",className:"fixed inset-0 z-40 bg-black/50",onClick:r(()=>n(!1),"onClick"),"aria-label":"Close sidebar"}),c?(0,t.jsxs)("div",{className:W("fixed inset-y-0 left-0 z-50 flex flex-col overflow-hidden pt-(--sz-safe-top) transition-transform duration-100 ease-out",s?"translate-x-0":"-translate-x-full"),children:[(0,t.jsx)("div",{className:"flex flex-1 min-h-0 overflow-hidden",children:(0,t.jsx)("div",{className:"w-60 shrink-0 overflow-hidden",children:le?(0,t.jsx)(HI,{children:Ne}):(0,t.jsx)(gse,{children:e})})}),(0,t.jsx)(gie,{deploymentMode:ue?.deploymentMode,forceExpanded:Ie})]}):(0,t.jsxs)(Hft,{open:s,collapsed:Ie?!1:i,peeking:Ie?!1:o,resizable:!0,onPanelMouseEnter:Ie?void 0:rt,onPanelMouseLeave:Ie?void 0:Pe,onPanelFocusCapture:!Ie&&i?De:void 0,onPanelBlurCapture:!Ie&&i?ht:void 0,children:[(0,t.jsx)("div",{className:"flex flex-1 min-h-0",children:Ie?(0,t.jsx)(HI,{children:Ne}):(0,t.jsx)(gse,{children:e})}),(0,t.jsx)(gie,{deploymentMode:ue?.deploymentMode,forceExpanded:Ie})]}),!c&&ye&&!Le?(0,t.jsx)(HI,{className:"w-60 shrink-0",children:Ne}):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&&z&&"hidden",c&&"sticky top-0 z-20 bg-background/95 backdrop-blur supports-[backdrop-filter]:bg-background/85"),children:[(0,t.jsx)(aq,{mobile:c,onNavigateHome:r(()=>R("/dashboard"),"onNavigateHome")}),(0,t.jsx)(Sse,{}),c&&O?(0,t.jsx)("div",{className:"border-b border-border px-4 pb-3",children:(0,t.jsx)(INe,{})}):null]}),(0,t.jsxs)("div",{className:W(c?"block":"flex flex-1 min-h-0",!c&&z&&"streamlined-task-detail-surface"),children:[!c&&Le?(0,t.jsx)(HI,{className:"w-60 shrink-0 bg-background",children:Ne}):null,(0,t.jsxs)("div",{className:W(!c&&z?"flex min-w-0 flex-1 flex-col":"contents"),children:[!c&&z?(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)(aq,{mobile:!1,onNavigateHome:r(()=>R("/dashboard"),"onNavigateHome")}),(0,t.jsx)(Sse,{taskDetailLayout:!0})]}):null,(0,t.jsx)("main",{id:"main-content",ref:ie,tabIndex:-1,style:c?{"--tc-composer-bottom":"var(--sz-calc-14)"}:void 0,className:W("flex-1 p-4 outline-none md:p-6",!c&&z&&"pt-0 md:pt-0",c?"overflow-visible pb-(--sz-calc-14)":"overflow-auto [scrollbar-gutter:stable]"),children:ae?(0,t.jsx)(om,{scope:"invalid_company_prefix",requestedPrefix:N??v?.issuePrefix}):(0,t.jsx)(c3e,{children:(0,t.jsx)(cv,{})})})]}),(0,t.jsx)(zNe,{taskDetailLayout:!c&&z})]})]})]}),c&&(0,t.jsx)(r3e,{visible:oe}),(0,t.jsx)(qNe,{}),(0,t.jsx)(CSe,{}),(0,t.jsx)(p5e,{}),(0,t.jsx)(g5e,{}),(0,t.jsx)(j5e,{}),(0,t.jsx)(w5e,{open:V,onOpenChange:X}),(0,t.jsx)(k5e,{}),(0,t.jsx)(s3e,{companyId:y}),(0,t.jsx)(xft,{health:ue}),(0,t.jsx)(n3e,{localTrusted:ue?.deploymentMode==="local_trusted"})]})})}r(_xt,"Layout$1");var P3e=(0,m.createContext)(!1);function Axt({children:e}){return(0,t.jsx)(P3e.Provider,{value:!0,children:e})}r(Axt,"SidebarNavExpandedProvider");function Ixt(){return(0,m.useContext)(P3e)}r(Ixt,"useSidebarNavExpanded");function Xa({to:e,label:s,icon:n,iconNode:a,end:i,className:o,labelClassName:l,badge:c,badgeTone:d="default",badgeLabel:u,textBadge:h,textBadgeTone:p="default",alert:f=!1,liveCount:x,active:g,trailing:v,trailingLabel:y,liveAccessory:k}){const{isMobile:w,setSidebarOpen:N,collapsed:S,peeking:C}=Wa(),_=Ixt(),R=S&&!C&&!_,I=c!=null&&c>0,T=x!=null&&x>0,E=T?`${x} live`:I?`${c}${u?` ${u}`:""}`:f?"attention needed":void 0,L=!R||!E&&!y?void 0:`${s}${E?`, ${E}`:""}${y?`, ${y}`:""}`,O=(0,t.jsxs)(dv,{to:e,state:If,end:i,"aria-label":L,onClick:r(()=>{w&&N(!1)},"onClick"),className:r(({isActive:P})=>W("flex items-center gap-2.5 mx-2 rounded-lg px-2 py-1.5 pointer-coarse:py-1 text-(length:--text-compact) font-medium transition-colors",g??P?"bg-accent text-foreground":"text-foreground/80 hover:bg-accent/50 hover:text-foreground",o),"className"),children:[(0,t.jsxs)("span",{className:"relative shrink-0",children:[a??(n?(0,t.jsx)(n,{className:"h-4 w-4"}):null),f&&(0,t.jsx)("span",{className:"absolute -right-0.5 -top-0.5 h-2 w-2 rounded-full bg-red-500 shadow-(--shadow-extract-12)","aria-hidden":"true"}),R&&!f&&T&&(0,t.jsxs)("span",{className:"absolute -right-0.5 -top-0.5 flex h-2 w-2","aria-hidden":"true",children:[(0,t.jsx)("span",{className:"animate-pulse absolute inline-flex h-full w-full rounded-full bg-blue-600 dark:bg-blue-400 opacity-75"}),(0,t.jsx)("span",{className:"relative inline-flex h-2 w-2 rounded-full bg-blue-600 dark:bg-blue-400 shadow-(--shadow-extract-12)"})]}),R&&!f&&!T&&I&&(0,t.jsx)("span",{className:W("absolute -right-0.5 -top-0.5 h-2 w-2 rounded-full shadow-(--shadow-extract-12)",d==="danger"?"bg-red-600":d==="warning"?"bg-amber-500":"bg-primary"),"aria-hidden":"true"})]}),(0,t.jsx)("span",{className:R?Vj:W("min-w-0 flex-1 truncate",l),children:s}),!R&&v,!R&&h&&(0,t.jsx)(it,{variant:"ghost",className:W("ml-auto px-1.5 text-(length:--text-nano) leading-none",p==="amber"?"bg-amber-100 text-amber-800 dark:bg-amber-900/30 dark:text-amber-400":"bg-muted text-muted-foreground"),children:h}),!R&&(T||k)&&(0,t.jsxs)("span",{className:"ml-auto flex items-center gap-1.5",children:[k,T&&(0,t.jsxs)(t.Fragment,{children:[(0,t.jsxs)("span",{className:"relative flex h-2 w-2",children:[(0,t.jsx)("span",{className:"animate-pulse absolute inline-flex h-full w-full rounded-full bg-blue-600 dark:bg-blue-400 opacity-75"}),(0,t.jsx)("span",{className:"relative inline-flex rounded-full h-2 w-2 bg-blue-600 dark:bg-blue-400"})]}),(0,t.jsxs)("span",{className:"text-(length:--text-micro) font-medium text-blue-600 dark:text-blue-400",children:[x," live"]})]})]}),!R&&I&&(0,t.jsx)(it,{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)(Bn,{children:[(0,t.jsx)(On,{asChild:!0,children:(0,t.jsx)("div",{children:O})}),(0,t.jsx)($n,{side:"right",children:s})]}):O}r(Xa,"SidebarNavItem");var Txt=3,bie=12e4,Rxt=[{value:"top",label:"Top"},{value:"alphabetical",label:"Alphabetical"},{value:"recent",label:"Recent"}];function t1(e,s){const n=e[s];if(!n)return 0;const a=new Date(n).getTime();return Number.isFinite(a)?a:0}r(t1,"agentTimestamp");function vie(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=t1(i,"lastHeartbeatAt")-t1(a,"lastHeartbeatAt");if(o!==0)return o;const l=t1(i,"updatedAt")-t1(a,"updatedAt");if(l!==0)return l;const c=t1(i,"createdAt")-t1(a,"createdAt");return c!==0?c:a.name.localeCompare(i.name,void 0,{sensitivity:"base"})}),n)}r(vie,"sortAgents");var Ext="opacity-0 transition-opacity group-hover/agent:opacity-100 group-focus-within/agent:opacity-100";function Lxt({activeAgentId:e,activeTab:s,agent:n,disabled:a,isMobile:i,leaving:o,onLeaveAgent:l,onPauseResume:c,rail:d,runCount:u,setSidebarOpen:h,builtInStatus:p,starred:f=!1,onToggleStar:x,starPending:g=!1}){const v=Vl(n),y=s?`${sm(n)}/${s}`:sm(n),k=`${sm(n)}/configuration`,w=e===v,N=n.status==="paused",S=N&&n.pauseReason==="budget",C=n.orgChainHealth?.status==="invalid_org_chain",_=N?"Resume agent":"Pause agent",R=a||n.status==="pending_approval"||S||N&&C,I=a?"Updating...":S?"Budget paused":N&&C?"Invalid org chain":_,T=p==="needs_setup"||p==="pending_approval",E=[T?`Built-in agent ${p.replace(/_/g," ")}`:null,C?"Invalid reporting chain":null].filter(Boolean).join(", ")||void 0,L=(0,t.jsx)(Xa,{to:y,label:n.name,iconNode:(0,t.jsx)(lr,{agent:n,size:16,className:"shrink-0 h-4 w-4"}),active:w,liveCount:u,labelClassName:T?"min-w-(--sz-4_5rem) flex-initial":void 0,className:W("min-w-0 flex-1",f&&!i?"pr-14":"pr-8"),trailing:T||C?(0,t.jsxs)("span",{className:"ml-1 flex shrink-0 items-center gap-1",children:[T?(0,t.jsx)(Ck,{status:p,compact:!0}):null,C?(0,t.jsx)(Es,{className:"h-3.5 w-3.5 shrink-0 text-amber-500","aria-label":"Invalid reporting chain"}):null]}):void 0,trailingLabel:E,liveAccessory:n.pauseReason==="budget"?(0,t.jsx)(F3,{title:"Agent paused by budget"}):void 0});return d?L:(0,t.jsxs)("div",{className:"group/agent relative flex items-center",children:[L,f&&!i&&x?(0,t.jsx)("span",{className:"absolute right-10 top-1/2 -translate-y-1/2",children:(0,t.jsx)(nw,{size:"row",quiet:!0,starred:!0,pending:g,resourceName:n.name,onToggle:r(()=>x(n,!1),"onToggle"),revealClassName:Ext})}):null,(0,t.jsxs)(ia,{children:[(0,t.jsx)(ra,{asChild:!0,children:(0,t.jsx)($,{variant:"ghost",size:"icon-xs",className:W("absolute right-3 top-1/2 h-6 w-6 -translate-y-1/2 transition-opacity data-[state=open]:pointer-events-auto data-[state=open]:opacity-100",i?"opacity-100":"pointer-events-none opacity-0 group-hover/agent:pointer-events-auto group-hover/agent:opacity-100 group-focus-within/agent:pointer-events-auto group-focus-within/agent:opacity-100"),"aria-label":`Open actions for ${n.name}`,children:(0,t.jsx)(Ci,{className:"h-3.5 w-3.5"})})}),(0,t.jsxs)(aa,{align:"end",className:"w-48",children:[x?(0,t.jsxs)(t.Fragment,{children:[(0,t.jsxs)(ls,{onClick:r(()=>{g||x(n,!f)},"onClick"),disabled:g,children:[g?(0,t.jsx)(st,{className:"size-4 motion-safe:animate-spin"}):(0,t.jsx)(Q0,{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)(ii,{})]}):null,(0,t.jsx)(ls,{asChild:!0,children:(0,t.jsxs)(Ke,{to:k,onClick:r(()=>{i&&h(!1)},"onClick"),children:[(0,t.jsx)(nc,{className:"size-4"}),(0,t.jsx)("span",{children:"Edit agent"})]})}),(0,t.jsx)(ii,{}),(0,t.jsxs)(ls,{onClick:r(()=>{R||c(n,N?"resume":"pause")},"onClick"),disabled:R,title:S?"Agent was paused by budget limits":void 0,children:[N?(0,t.jsx)(M3,{className:"size-4"}):(0,t.jsx)(Zd,{className:"size-4"}),(0,t.jsx)("span",{children:I})]}),(0,t.jsx)(ii,{}),(0,t.jsxs)(ls,{onClick:r(()=>{o||l(n)},"onClick"),disabled:o,children:[o?(0,t.jsx)(st,{className:"size-4 motion-safe:animate-spin"}):(0,t.jsx)(tp,{className:"size-4"}),(0,t.jsx)("span",{children:o?"Leaving...":"Leave agent"})]})]})]})]})}r(Lxt,"SidebarAgentItem");function Mxt({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=kt(),{selectedCompanyId:u}=ps(),h=jS(u),{openNewAgent:p}=al(),{isMobile:f,setSidebarOpen:x,collapsed:g,peeking:v}=Wa(),y=g&&!v,{pushToast:k}=Xr(),w=ua(),{data:N}=te({queryKey:M.agents.list(u),queryFn:r(()=>_t.list(u),"queryFn"),enabled:!!u}),{data:S}=te({queryKey:M.instance.experimentalSettings,queryFn:r(()=>jr.getExperimental(),"queryFn"),enabled:!!u}),C=S?.enableBuiltInAgents===!0,{data:_}=te({queryKey:M.builtInAgents.list(u),queryFn:r(()=>k0.list(u),"queryFn"),enabled:!!u&&C}),R=(0,m.useMemo)(()=>{const ye=new Map;if(!C)return ye;for(const Ae of _??[])Ae.agentId&&ye.set(Ae.agentId,Ae.status);return ye},[_,C]),{data:I}=te({queryKey:M.auth.session,queryFn:r(()=>Ma.getSession(),"queryFn")}),T=Tf(u),E=pv(u),L=M.liveRuns(u),O=Co({companyId:u,resourceKey:"live-runs",queryKey:L,enabled:!!u,refetchInterval:!1,leaderOnly:!0}),{data:P,dataUpdatedAt:Q}=te({queryKey:L,queryFn:r(()=>na.liveRunsForCompany(u),"queryFn"),enabled:O.enabled,refetchInterval:O.refetchInterval});_o(O,P,Q);const D=(0,m.useMemo)(()=>{const ye=new Map;for(const Ae of P??[])ye.set(Ae.agentId,(ye.get(Ae.agentId)??0)+1);return ye},[P]),F=(0,m.useMemo)(()=>{const ye=new Set;for(const[Ae,Qe]of D)Qe>0&&ye.add(Ae);return ye},[D]),z=(0,m.useMemo)(()=>(N??[]).filter(ye=>ye.status!=="terminated"&&(!T.isSuccess||eg(T.data,"agent",ye.id)!=="left")),[N,T.data,T.isSuccess]),K=I?.user?.id??I?.session?.userId??null,U=(0,m.useMemo)(()=>u?Hke(u,K):null,[K,u]),[q,G]=(0,m.useState)(()=>U?_k(U):"top"),{orderedAgents:se}=Yke({agents:z,companyId:u,userId:K}),Z=(0,m.useMemo)(()=>vie(se,q),[se,q]),ie=(0,m.useMemo)(()=>new Set(Z.map(ye=>ye.id)),[Z]);(0,m.useEffect)(()=>{const ye=Date.now();for(const Ae of F)c.current.set(Ae,ye);for(const Ae of c.current.keys())ie.has(Ae)||c.current.delete(Ae)},[F,ie]);const J=(0,m.useMemo)(()=>{const ye=Date.now(),Ae=c.current;return Z.filter(Qe=>{if((D.get(Qe.id)??0)>0)return!0;const ue=Ae.get(Qe.id);return ue!==void 0&&ye-ue<=bie})},[D,o,Z]),re=J.length>0,oe=e?re?J:Z.slice(0,Txt):Z,V=e&&Z.length>0,X=w.pathname.match(/^\/(?:[^/]+\/)?agents\/([^/]+)(?:\/([^/]+))?/),Y=X?.[1]??null,ae=X?.[2]??null;(0,m.useEffect)(()=>{if(!U){G("top");return}G(_k(U))},[U]),(0,m.useEffect)(()=>{if(!U)return;const ye=r(Qe=>{Qe.key===U&&G(_k(U))},"onStorage"),Ae=r(Qe=>{const ue=Qe.detail;!ue||ue.storageKey!==U||G(ue.sortMode)},"onCustomEvent");return window.addEventListener("storage",ye),window.addEventListener(r5,Ae),()=>{window.removeEventListener("storage",ye),window.removeEventListener(r5,Ae)}},[U]),(0,m.useEffect)(()=>{if(!e)return;const ye=Date.now();let Ae=null;for(const ue of Z){if((D.get(ue.id)??0)>0)continue;const Be=c.current.get(ue.id);if(Be===void 0)continue;const ft=Be+bie;ft<ye||(Ae=Ae===null?ft:Math.min(Ae,ft))}if(Ae===null)return;const Qe=window.setTimeout(()=>{l(ue=>ue+1)},Math.max(0,Ae-ye+1));return()=>{window.clearTimeout(Qe)}},[e,Z,D,o]);const ne=(0,m.useCallback)(ye=>{const Ae=ye==="alphabetical"||ye==="recent"?ye:"top";G(Ae),U&&Gke(U,Ae)},[U]),ce=je({mutationFn:r(({agent:ye,action:Ae})=>Ae==="pause"?_t.pause(ye.id,u??void 0):_t.resume(ye.id,u??void 0),"mutationFn"),onMutate:r(({agent:ye})=>{i(Ae=>{const Qe=new Set(Ae);return Qe.add(ye.id),Qe})},"onMutate"),onSuccess:r(async(ye,{agent:Ae,action:Qe})=>{u&&await Promise.all([d.invalidateQueries({queryKey:M.agents.list(u)}),d.invalidateQueries({queryKey:M.liveRuns(u)}),d.invalidateQueries({queryKey:M.dashboard(u)})]),await Promise.all([d.invalidateQueries({queryKey:M.agents.detail(Ae.id)}),d.invalidateQueries({queryKey:M.agents.detail(Vl(Ae))})]),k({title:Qe==="pause"?"Agent paused":"Agent resumed",body:Ae.name,tone:"success"})},"onSuccess"),onError:r((ye,{agent:Ae,action:Qe})=>{k({title:Qe==="pause"?"Could not pause agent":"Could not resume agent",body:ye instanceof Error?ye.message:Ae.name,tone:"error"})},"onError"),onSettled:r((ye,Ae,{agent:Qe})=>{i(ue=>{const Be=new Set(ue);return Be.delete(Qe.id),Be})},"onSettled")}),he=(0,m.useCallback)(ye=>E.mutate({resourceType:"agent",resourceId:ye.id,resourceName:ye.name,state:"left"}),[E]),pe=(0,m.useCallback)(ye=>E.isPending&&E.variables?.resourceType==="agent"&&E.variables.resourceId===ye.id,[E.isPending,E.variables]),ge=(0,m.useCallback)((ye,Ae)=>E.mutate({resourceType:"agent",resourceId:ye.id,resourceName:ye.name,starred:Ae}),[E]),Ee=(0,m.useCallback)(ye=>E.isPending&&E.variables?.resourceType==="agent"&&E.variables.resourceId===ye.id&&E.variables.starred!==void 0,[E.isPending,E.variables]),de=(0,m.useMemo)(()=>new Set(V8(T.data,"agent")),[T.data]),Ne=(0,m.useMemo)(()=>vie(z.filter(ye=>de.has(ye.id)),"alphabetical"),[z,de]),le=(0,m.useMemo)(()=>oe.filter(ye=>!de.has(ye.id)),[oe,de]),Le=h&&!h.loading?z.find(ye=>ye.id===h.primaryAgentId):void 0,Ie=r((ye,Ae)=>(0,t.jsx)(Lxt,{activeAgentId:Y,activeTab:ae,agent:ye,disabled:a.has(ye.id),isMobile:f,leaving:pe(ye),onLeaveAgent:he,onPauseResume:r((Qe,ue)=>ce.mutate({agent:Qe,action:ue}),"onPauseResume"),rail:y,runCount:D.get(ye.id)??0,setSidebarOpen:x,builtInStatus:R.get(ye.id),starred:Ae||sw(T.data,"agent",ye.id),onToggleStar:ge,starPending:Ee(ye)},ye.id),"renderAgentRow");return(0,t.jsxs)(zx,{label:"Agents",collapsible:{open:s,onOpenChange:n},headerAction:{ariaLabel:"New agent",icon:gn,onClick:p},menu:{ariaLabel:"Agents section actions",actions:[{type:"item",label:"Browse agents",icon:Ho,href:"/agents/all"},{type:"separator"}],radioLabel:"Agent sort",radioChoices:Rxt,radioValue:q,onRadioValueChange:ne},children:[[...Le?[Le]:[],...Ne.filter(ye=>ye.id!==Le?.id),...le.filter(ye=>ye.id!==Le?.id)].map(ye=>Ie(ye,de.has(ye.id))),V&&(()=>{const ye=(0,t.jsxs)(Ke,{to:"/agents/all",state:If,"aria-label":y?"See all agents":void 0,onClick:r(()=>{f&&x(!1)},"onClick"),className:"flex items-center gap-2.5 mx-2 rounded-lg px-2 py-1.5 pointer-coarse:py-1 text-(length:--text-compact) font-medium text-muted-foreground transition-colors hover:bg-accent/50 hover:text-foreground",children:[(0,t.jsx)(Ho,{className:"shrink-0 h-4 w-4"}),(0,t.jsx)("span",{className:y?"block w-0 min-w-0 overflow-hidden whitespace-nowrap text-transparent select-none":void 0,children:"See all agents"})]});return y?(0,t.jsxs)(Bn,{children:[(0,t.jsx)(On,{asChild:!0,children:ye}),(0,t.jsx)($n,{side:"right",children:"See all agents"})]}):ye})()]})}r(Mxt,"SidebarAgents");var Pxt="opacity-0 transition-opacity group-hover/starred-project:opacity-100 group-focus-within/starred-project:opacity-100";function Dxt(){const{selectedCompanyId:e}=ps(),{isMobile:s,setSidebarOpen:n,collapsed:a,peeking:i}=Wa(),o=a&&!i,l=ua(),{data:c}=te({queryKey:M.projects.list(e),queryFn:r(()=>oa.list(e),"queryFn"),enabled:!!e}),d=Tf(e),u=pv(e),h=l.pathname.match(/^\/(?:[^/]+\/)?projects\/([^/]+)/)?.[1]??null,p=(0,m.useMemo)(()=>{if(!d.isSuccess)return[];const v=new Set(V8(d.data,"project"));if(v.size===0)return[];const y=new Map((c??[]).map(k=>[k.id,k]));return Array.from(v).map(k=>y.get(k)).filter(k=>!!k).sort((k,w)=>k.name.localeCompare(w.name,void 0,{sensitivity:"base"}))},[d.data,d.isSuccess,c]),f=(0,m.useCallback)(v=>u.mutate({resourceType:"project",resourceId:v.id,resourceName:v.name,starred:!1}),[u]),x=(0,m.useCallback)(v=>u.mutate({resourceType:"project",resourceId:v.id,resourceName:v.name,state:"left"}),[u]),g=(0,m.useCallback)(v=>u.isPending&&u.variables?.resourceType==="project"&&u.variables.resourceId===v.id,[u.isPending,u.variables]);return!d.isSuccess||p.length===0?null:(0,t.jsx)("div",{className:"flex flex-col gap-0.5","aria-label":"Starred projects",children:p.map(v=>{const y=Vx(v),k=h===y||h===v.id,w=g(v),N=w&&u.variables?.starred===!1,S=w&&u.variables?.state==="left",C=sw(d.data,"project",v.id),_=(0,t.jsxs)(dv,{to:`/projects/${y}/issues`,state:If,onClick:r(()=>{s&&n(!1)},"onClick"),className:W("flex min-w-0 flex-1 items-center gap-2.5 mx-2 rounded-lg px-2 py-1.5 pointer-coarse:py-1 pr-8 text-(length:--text-compact) font-medium transition-colors",!o&&"pl-6",k?"bg-accent text-foreground":"text-foreground/80 hover:bg-accent/50 hover:text-foreground"),children:[(0,t.jsx)(Zm,{color:v.color??null,icon:v.icon??null,size:"xs"}),(0,t.jsx)("span",{className:o?Vj:"flex-1 truncate",children:v.name}),!o&&v.visibility==="private"?(0,t.jsx)(Ao,{className:"size-3.5 shrink-0 text-muted-foreground","aria-label":"Private project"}):null,!o&&v.pauseReason==="budget"?(0,t.jsx)(F3,{title:"Project paused by budget"}):null]});return(0,t.jsxs)("div",{className:"group/starred-project relative flex items-center",children:[o?(0,t.jsxs)(Bn,{children:[(0,t.jsx)(On,{asChild:!0,children:(0,t.jsx)("div",{className:"min-w-0 flex-1",children:_})}),(0,t.jsx)($n,{side:"right",children:v.name})]}):_,!o&&!s?(0,t.jsx)("span",{className:"absolute right-3 top-1/2 -translate-y-1/2",children:(0,t.jsx)(nw,{size:"row",quiet:!0,starred:C,pending:N,resourceName:v.name,onToggle:r(()=>f(v),"onToggle"),revealClassName:Pxt})}):null,!o&&s?(0,t.jsxs)(ia,{children:[(0,t.jsx)(ra,{asChild:!0,children:(0,t.jsx)($,{variant:"ghost",size:"icon-xs",className:"absolute right-3 top-1/2 h-6 w-6 -translate-y-1/2 opacity-100","aria-label":`Open actions for ${v.name}`,children:(0,t.jsx)(Ci,{className:"h-3.5 w-3.5"})})}),(0,t.jsxs)(aa,{align:"end",className:"w-48",children:[(0,t.jsxs)(ls,{onClick:r(()=>{w||f(v)},"onClick"),disabled:w,children:[N?(0,t.jsx)(st,{className:"size-4 motion-safe:animate-spin"}):(0,t.jsx)(Q0,{className:"size-4 fill-amber-500 text-amber-500"}),(0,t.jsx)("span",{children:"Remove from starred"})]}),(0,t.jsx)(ii,{}),(0,t.jsxs)(ls,{onClick:r(()=>{w||x(v)},"onClick"),disabled:w,children:[S?(0,t.jsx)(st,{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(Dxt,"SidebarStarredProjects");var $xt="size-5 shrink-0 rounded-md text-(length:--text-micro)",Oxt="size-(--organization-popover-avatar-size) shrink-0 rounded-lg text-(length:--text-micro)",Bxt="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",TD="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 D3e({company:e,inPopover:s=!1}){return(0,t.jsx)(tg,{companyName:e.name,logoUrl:e.logoUrl,className:s?Oxt:$xt})}r(D3e,"WorkspaceIcon");function Fxt({company:e,isEditing:s,isSelected:n,onSelect:a}){const{attributes:i,listeners:o,setActivatorNodeRef:l,setNodeRef:c,transform:d,transition:u,isDragging:h}=pS({id:e.id,disabled:!s});return(0,t.jsxs)(ls,{ref:c,style:{transform:mS.Transform.toString(d),transition:u,zIndex:h?10:void 0},onSelect:r(p=>{if(s){p.preventDefault();return}a(e)},"onSelect"),className:W(Bxt,s&&"cursor-grab",h&&"opacity-80"),children:[(0,t.jsx)(D3e,{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)(F8,{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)(cs,{className:"size-4 text-foreground"}):null})]})}r(Fxt,"SortableCompanyItem");function zxt(e={}){return(0,t.jsx)(kNe,{...e,children:(0,t.jsx)(qxt,{...e})})}r(zxt,"SidebarCompanyMenu");function qxt({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}=al(),{isMobile:f,setSidebarOpen:x,collapsed:g,peeking:v}=Wa(),y=g&&!v,k=ua(),w=Yn(),N=e??n,S=s??a,C=lS(xf(nW,{activationConstraint:{distance:8}}),xf(rve,{activationConstraint:{delay:180,tolerance:6}})),_=(0,m.useMemo)(()=>l.filter(Z=>Z.status!=="archived"),[l]),{data:R}=te({queryKey:M.auth.session,queryFn:r(()=>Ma.getSession(),"queryFn"),retry:!1}),I=R?.user?.id??R?.session?.userId??null,{orderedCompanies:T,persistOrder:E}=wNe({companies:_,userId:I}),{hidden:L,loaded:O}=Au(),P=O&&!Gx(L,"company.members")&&!Gx(L,"company.invites"),Q="company",D=c?.name??null,F=!!ed(),z=SS({onSignedOut:U});function K(Z){Z||o(!1),S(Z)}r(K,"handleOpenChange");function U(){S(!1),o(!1),f&&x(!1)}r(U,"closeNavigationChrome");function q(Z){const ie=k.pathname.split("/")[1]?.toUpperCase(),J=_.some(oe=>oe.issuePrefix.toUpperCase()===ie),re=Z.id!==c?.id&&(k.pathname.startsWith("/instance/")||J);d(Z.id),S(!1),f&&x(!1),re&&w(`/${Z.issuePrefix}/dashboard`)}r(q,"selectCompany");function G(){F||(S(!1),f&&x(!1),p({initialStep:1}))}r(G,"addCompany");const se=(0,m.useCallback)(Z=>{const{active:ie,over:J}=Z;if(!J||ie.id===J.id)return;const re=T.map(X=>X.id),oe=re.indexOf(ie.id),V=re.indexOf(J.id);oe===-1||V===-1||E(E8(re,oe,V))},[T,E]);return(0,t.jsxs)(ia,{open:N,onOpenChange:K,children:[(0,t.jsx)(ra,{asChild:!0,children:(0,t.jsxs)($,{variant:"ghost",className:"h-9 min-w-0 flex-1 justify-start gap-2 px-4 text-left hover:bg-accent/50 hover:text-foreground has-[>svg]:px-4 dark:hover:bg-accent/50","aria-label":D?`Open ${D} ${Q} switcher`:`Open ${Q} switcher`,children:[(0,t.jsxs)("span",{className:"flex min-w-0 flex-1 items-center gap-2",children:[c?(0,t.jsx)(D3e,{company:c}):null,(0,t.jsx)("span",{className:W("min-w-0 truncate text-sm font-bold text-foreground",y&&"block w-0 min-w-0 overflow-hidden whitespace-nowrap text-transparent select-none"),title:D??void 0,children:D??`Select ${Q}`})]}),!y&&(0,t.jsx)(T8,{className:"size-3.5 shrink-0 text-muted-foreground"})]})}),(0,t.jsxs)(aa,{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)(mv,{className:"p-0 text-(length:--text-compact) font-semibold text-foreground",children:"Organizations"}),(0,t.jsx)("button",{type:"button",onClick:r(Z=>{Z.preventDefault(),Z.stopPropagation(),o(ie=>!ie)},"onClick"),className:"rounded px-1.5 py-0.5 text-xs font-medium text-muted-foreground transition-colors hover:bg-accent hover:text-foreground",children:i?"Done":"Edit"})]}),(0,t.jsxs)("div",{className:"flex max-h-96 flex-col gap-0.5 overflow-y-auto px-2.5 pb-2 pt-1",children:[(0,t.jsx)(hS,{sensors:C,collisionDetection:j3,onDragEnd:se,children:(0,t.jsx)(uS,{items:T.map(Z=>Z.id),strategy:N3,children:T.map(Z=>(0,t.jsx)(Fxt,{company:Z,isEditing:i,isSelected:Z.id===c?.id,onSelect:q},Z.id))})}),T.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(Z=>{Z.preventDefault(),h()},"onSelect"),children:[(0,t.jsx)(Ai,{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:[!F&&(0,t.jsxs)(ls,{onClick:G,className:TD,disabled:i,children:[(0,t.jsx)("span",{className:"flex size-5 shrink-0 items-center justify-center text-muted-foreground",children:(0,t.jsx)(gn,{className:"size-4"})}),(0,t.jsx)("span",{className:"min-w-0 flex-1 truncate",children:"Create organization"})]}),P?(0,t.jsx)(ls,{asChild:!0,disabled:i,className:TD,children:(0,t.jsxs)(Ke,{to:"/company/settings/invites",onClick:r(Z=>{if(i){Z.preventDefault();return}U()},"onClick"),children:[(0,t.jsx)("span",{className:"flex size-5 shrink-0 items-center justify-center text-muted-foreground",children:(0,t.jsx)(oh,{className:"size-4"})}),(0,t.jsx)("span",{className:"min-w-0 flex-1 truncate",children:D?`Invite people to ${D}`:"Invite people"})]})}):null,R?.session?(0,t.jsxs)(ls,{className:TD,onClick:r(()=>z.mutate(),"onClick"),disabled:i||z.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:z.isPending?"Signing out...":"Sign out"})]}):null]})]})]})}r(qxt,"BuiltinCompanyMenu");function yie(){const{openNewIssue:e}=al(),[s,n]=(0,m.useState)(!0),[a,i]=(0,m.useState)(!0),{selectedCompanyId:o,selectedCompany:l}=ps(),{collapsed:c,peeking:d}=Wa(),u=c&&!d,h=J8(o),{data:p,isFetched:f}=te({queryKey:M.instance.experimentalSettings,queryFn:r(()=>jr.getExperimental(),"queryFn")}),x=M.liveRuns(o),g=Co({companyId:o,resourceKey:"live-runs",queryKey:x,enabled:!!o,refetchInterval:!1,leaderOnly:!0}),{data:v,dataUpdatedAt:y}=te({queryKey:x,queryFn:r(()=>na.liveRunsForCompany(o),"queryFn"),enabled:g.enabled,refetchInterval:g.refetchInterval});_o(g,v,y);const k=v?.length??0,w=p?.enableIsolatedWorkspaces===!0,N=p?.enableApps===!0,S=p?.enablePipelines===!0,C=p?.enableStatusCards===!0,_=!f,R=p?.enableGoalsSidebarLink===!0,I=p?.enableDecisions===!0,{data:T}=te({queryKey:M.attentionCount(o),queryFn:r(()=>wS.count(o),"queryFn"),enabled:!!o&&I,refetchInterval:6e4}),E=T?.count??0,L=p?.enableCases===!0,O=!0,P=p?.enableConferenceRoomChat===!0,Q={companyId:o,companyPrefix:l?.issuePrefix??null};return(0,t.jsxs)("aside",{className:"w-full h-full min-h-0 border-r border-border bg-background flex flex-col",children:[(0,t.jsx)("div",{className:"flex items-center gap-1 px-3 h-12 shrink-0",children:(0,t.jsx)(zxt,{})}),(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 D=(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)(t5,{className:"h-4 w-4 shrink-0"}),(0,t.jsx)("span",{className:u?Vj:"truncate",children:"New Task"})]});return u?(0,t.jsxs)(Bn,{children:[(0,t.jsx)(On,{asChild:!0,children:D}),(0,t.jsx)($n,{side:"right",children:"New Task"})]}):D})(),(0,t.jsx)(Xa,{to:"/search",label:"Search",icon:Jr}),(0,t.jsx)(Xa,{to:"/dashboard",label:"Dashboard",icon:Fx,liveCount:k}),(0,t.jsx)(Xa,{to:"/inbox",label:"Inbox",icon:Od,badge:h.inbox,badgeLabel:"unread",badgeTone:h.failedRuns>0?"danger":"default",alert:h.failedRuns>0}),I?(0,t.jsx)(Xa,{to:"/decisions",label:"Decisions",icon:ew,badge:E,badgeLabel:"decisions"}):null,C?(0,t.jsx)(Xa,{to:"/status",label:"Status",icon:vS,textBadge:"beta"}):null,P?(0,t.jsx)(Xa,{to:"/board-chat",label:"Conference Room",icon:Pwe}):null]}),(0,t.jsxs)(zx,{label:"Work",collapsible:{open:s,onOpenChange:n},children:[(0,t.jsx)(Xa,{to:"/issues",label:"Tasks",icon:Ju}),L?(0,t.jsx)(Xa,{to:"/cases",label:"Cases",icon:Gl,textBadge:"beta"}):null,(0,t.jsx)(Xa,{to:"/routines",label:"Routines",icon:nm}),S?(0,t.jsx)(Xa,{to:"/pipelines",label:"Pipelines",icon:to}):null,R?(0,t.jsx)(Xa,{to:"/goals",label:"Goals",icon:K0}):_?(0,t.jsx)("div",{"data-testid":"sidebar-goals-placeholder",className:"h-8 pointer-coarse:h-7","aria-hidden":"true"}):null,(0,t.jsx)(Xa,{to:"/artifacts",label:"Artifacts",icon:Xh}),(0,t.jsx)(Xa,{to:"/skills",label:"Skills",icon:_c}),w?(0,t.jsx)(Xa,{to:"/workspaces",label:"Workspaces",icon:to}):null,(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)(Xa,{to:"/projects",label:"Projects",icon:nl}),(0,t.jsx)(Dxt,{})]}),(0,t.jsx)(Y0,{errorBehavior:"hidden",slotTypes:["sidebar"],context:Q,className:"flex flex-col gap-0.5",itemClassName:"text-(length:--text-compact) font-medium",missingBehavior:"placeholder"}),(0,t.jsx)(NS,{errorBehavior:"hidden",placementZones:["sidebar"],context:Q,className:"flex flex-col gap-0.5",itemClassName:"text-(length:--text-compact) font-medium"})]}),null,(0,t.jsx)(Mxt,{streamlined:O}),(0,t.jsxs)(zx,{label:"Company",collapsible:{open:a,onOpenChange:i},children:[(0,t.jsx)(Xa,{to:"/org",label:"Org",icon:Vb}),N?(0,t.jsx)(Xa,{to:"/apps",label:"Connectors",icon:K6}):null,(0,t.jsx)(Xa,{to:"/timeline",label:"Timeline",icon:ub}),(0,t.jsx)(Xa,{to:"/costs",label:"Costs",icon:$0}),(0,t.jsx)(Xa,{to:"/activity",label:"Activity",icon:uc}),(0,t.jsx)(Xa,{to:"/company/settings",label:"Settings",icon:Su})]}),(0,t.jsx)(Y0,{errorBehavior:"hidden",slotTypes:["sidebarPanel"],context:Q,className:"flex flex-col gap-3",itemClassName:"rounded-lg border border-border p-3",missingBehavior:"placeholder"})]})]})}r(yie,"Sidebar");function Uxt(e){const s=e.manifestJson.environmentDrivers??[];return s.length===0?!1:s.every(n=>n.kind==="sandbox_provider")}r(Uxt,"isSandboxProviderOnly");function Kxt(){const{selectedCompany:e,selectedCompanyId:s}=ps(),{isMobile:n,setSidebarOpen:a}=Wa(),{hidden:i}=Au(),{enabled:o}=iw(),l=r(x=>!i.has(x),"showPage"),c=l("instance.plugins"),d=!!ed(),{slots:u}=Bd({slotTypes:["companySettingsPage"],companyId:s,enabled:!!s}),{data:h}=te({queryKey:s?M.sidebarBadges(s):["sidebar-badges","__disabled__"],queryFn:r(async()=>{try{return await JW.get(s)}catch(x){if(x instanceof sn&&(x.status===401||x.status===403))return null;throw x}},"queryFn"),enabled:!!s,retry:!1,refetchInterval:15e3}),{data:p}=te({queryKey:M.plugins.all,queryFn:r(()=>El.list(),"queryFn"),enabled:c}),f=(p??[]).filter(x=>!Uxt(x));return(0,t.jsxs)("aside",{className:"w-full h-full min-h-0 border-r border-border bg-background flex flex-col",children:[(0,t.jsx)("div",{className:"flex flex-col gap-1 px-3 py-3 shrink-0",children:(0,t.jsxs)(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)(um,{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)(Xa,{to:"/company/settings",label:"General",icon:mm,end:!0}),l("instance.profile")&&(0,t.jsx)(Xa,{to:"/company/settings/instance/profile",label:"Profile",icon:K8,end:!0}),l("company.members")&&(0,t.jsx)(Xa,{to:"/company/settings/members",label:"Members",icon:Ho,badge:h?.joinRequests??0,end:!0}),u.filter(x=>x.routePath).map(x=>(0,t.jsx)(Xa,{to:`/company/settings/${x.routePath}`,label:x.displayName,icon:Ox,end:!0},`${x.pluginKey}:${x.id}`)),l("company.invites")&&(0,t.jsx)(Xa,{to:"/company/settings/invites",label:"Invites",icon:xQe,end:!0}),l("company.secrets")&&(0,t.jsx)(Xa,{to:"/company/settings/secrets",label:"Secrets",icon:Ni,end:!0}),l("instance.environments")&&(0,t.jsx)(Xa,{to:"/company/settings/instance/environments",label:"Environments",icon:Fwe,end:!0}),o&&(0,t.jsx)(Xa,{to:"/company/settings/connections",label:"Connections",icon:Ml,end:!0}),l("instance.access")&&(0,t.jsx)(Xa,{to:"/company/settings/instance/access",label:"Access",icon:v3,end:!0}),l("instance.heartbeats")&&(0,t.jsx)(Xa,{to:"/company/settings/instance/heartbeats",label:"Heartbeats",icon:Nu,end:!0}),l("company.export")&&(0,t.jsx)(Xa,{to:"/company/export",label:"Export",icon:Ui}),!d&&l("company.import")&&(0,t.jsx)(Xa,{to:"/company/import",label:"Import",icon:Gb,end:!0}),l("instance.experimental")&&(0,t.jsx)(Xa,{to:"/company/settings/instance/experimental",label:"Experimental",icon:Jm}),c&&(0,t.jsx)(Xa,{to:"/company/settings/instance/plugins",label:"Plugins",icon:Ox}),c&&f.length>0?(0,t.jsx)("div",{className:"ml-4 mt-1 flex flex-col gap-0.5 border-l border-border/70 pl-3",children:f.map(x=>(0,t.jsx)(dv,{to:`${N0}/plugins/${x.id}`,state:If,className:r(({isActive:g})=>["rounded-md px-2 py-1.5 text-xs transition-colors",g?"bg-accent text-foreground":"text-muted-foreground hover:bg-accent/50 hover:text-foreground"].join(" "),"className"),children:x.manifestJson.displayName??x.packageName},x.id))}):null,l("instance.adapters")&&(0,t.jsx)(Xa,{to:"/company/settings/instance/adapters",label:"Adapters",icon:qm})]})})]})}r(Kxt,"CompanySettingsSidebar");function Qxt(){const{pathname:e}=ua(),{selectedCompany:s}=ps(),{isMobile:n,setSidebarOpen:a}=Wa(),i=ENe(),{enabled:o}=X8(),l=rH.filter(d=>!RNe(d.key)||o);if(e.endsWith("/apps/chat/connect"))return(0,t.jsx)(TNe,{NavItem:Xa});const c=e.match(/\/apps\/chat\/([^/]+)(?:\/(?:settings|access|conversations|activity|approvals|audit)|\/reviews(?:\/[^/]+)?)?\/?$/);return c?(0,t.jsx)(tH,{endpointId:c[1],NavItem:Xa}):(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)(um,{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)(Ste,{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)(Xa,{to:"/apps",label:"Browse",icon:s5,end:!0}),(0,t.jsx)(Xa,{to:"/apps/review",label:"Review",icon:yS,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)(Xa,{to:"/apps/connections",label:"Connections",icon:Ste,end:!0}),l.map(d=>(0,t.jsx)(Xa,{to:Ib(d.key),label:d.label,icon:d.icon,end:!0},d.key))]})]})]})}r(Qxt,"AppsSidebar");function jie(e){const{selectedCompanyId:s}=ps(),{isMobile:n,setSidebarOpen:a}=Wa(),i=te({queryKey:M.tools.connection(e.kind==="connection"?e.connectionId:"__none__"),queryFn:r(()=>ts.getConnection(e.kind==="connection"?e.connectionId:""),"queryFn"),enabled:e.kind==="connection"&&!!e.connectionId}),o=te({queryKey:M.tools.applications(s??"__none__"),queryFn:r(()=>ts.listApplications(s),"queryFn"),enabled:e.kind==="application"&&!!s}),l=te({queryKey:M.tools.connections(s??"__none__"),queryFn:r(()=>ts.listConnections(s),"queryFn"),enabled:e.kind==="application"&&!!s}),c=te({queryKey:M.apps.gallery(s??"__none__"),queryFn:r(()=>ts.listGallery(s),"queryFn"),enabled:!!s}),d=te({queryKey:M.apps.attention(s??"__none__"),queryFn:r(()=>ts.listAppsAttention(s),"queryFn"),enabled:!!s,refetchInterval:3e4}),u=i.data,h=e.kind==="application"?(o.data?.applications??[]).find(k=>k.id===e.applicationId):null,p=Vxt(e.kind==="application"?(l.data?.connections??[]).filter(k=>k.applicationId===e.applicationId):[]),f=u?bf(u):h?.name??"App",x=Hxt(c.data?.apps??[],u,h??void 0),g=u?.id??p?.id??null,v=g?d.data?.apps.find(k=>k.connection.id===g):null,y=(v?.pendingActionRequestCount??0)+((v?.quarantinedCatalogEntryCount??0)>0?1:0);return(0,t.jsxs)("aside",{className:"flex h-full min-h-0 w-full flex-col border-r border-border bg-background",children:[(0,t.jsxs)("div",{className:"flex shrink-0 flex-col gap-3 px-3 py-3",children:[(0,t.jsxs)(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)(um,{className:"h-3.5 w-3.5 shrink-0"}),(0,t.jsx)("span",{className:"truncate",children:"All apps"})]}),(0,t.jsxs)("div",{className:"flex min-w-0 items-center gap-2 px-2 py-1",children:[(0,t.jsx)(Vi,{name:f,logoUrl:K3(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:eM.map(k=>(0,t.jsx)(Xa,{to:Wxt(e,k.key),label:k.label,icon:k.icon,end:!0,badge:k.key==="review"&&y>0?y:void 0,badgeTone:"danger",badgeLabel:"needing review"},k.key))})})]})}r(jie,"AppDetailSidebar");function Wxt(e,s){return e.kind==="connection"?Bm(e.connectionId,s):l_(e.applicationId,s)}r(Wxt,"tabHref");function Hxt(e,s,n){if(n?.applicationKey){const i=e.find(o=>wc(o)===n.applicationKey);if(i)return i}const a=(s?.name??n?.name)?.toLowerCase();return a?e.find(i=>qx(i).toLowerCase()===a)??e.find(i=>wc(i)===a)??null:null}r(Hxt,"galleryEntryFor$1");function Vxt(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(Vxt,"latestArchivedConnection$1");function RD({identifier:e}){return e?(0,t.jsx)("span",{className:"shrink-0 font-mono text-muted-foreground",children:e}):null}r(RD,"CrumbIdentifier");function Gxt({context:e}){const{slots:s}=Bd({slotTypes:["globalToolbarButton"],companyId:e.companyId}),{launchers:n}=eH({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)(Y0,{slotTypes:["globalToolbarButton"],context:e,className:"flex items-center gap-1"}):null,n.length>0?(0,t.jsx)(NS,{placementZones:["globalToolbarButton"],context:e,className:"flex items-center gap-1"}):null]})}r(Gxt,"GlobalToolbar");function Yxt(){const{breadcrumbs:e,mobileToolbar:s}=Wn(),{toggleSidebar:n,isMobile:a}=Wa(),{selectedCompanyId:i,selectedCompany:o}=ps(),l=(0,m.useMemo)(()=>({companyId:i??null,companyPrefix:o?.issuePrefix??null}),[i,o?.issuePrefix]),c=(0,t.jsx)(Gxt,{context:l});if(a&&s)return(0,t.jsx)("div",{className:"border-b border-border px-2 h-12 shrink-0 flex items-center",children:s});if(e.length===0)return(0,t.jsx)("div",{className:"border-b border-border px-4 md:px-6 h-12 shrink-0 flex items-center justify-end",children:c});const d=a&&(0,t.jsx)($,{variant:"ghost",size:"icon-sm",className:"mr-2 shrink-0",onClick:n,"aria-label":"Open sidebar",children:(0,t.jsx)(Cwe,{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)(RD,{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)(aH,{className:"min-w-0 overflow-hidden",children:(0,t.jsx)(iH,{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)(eE,{}),(0,t.jsx)(c_,{className:p?"min-w-0":"shrink-0",children:p||!u.href?u.leading||u.identifier?(0,t.jsxs)(l5,{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)(RD,{identifier:u.identifier}),(0,t.jsx)("span",{className:"truncate",children:u.label})]}):(0,t.jsx)(l5,{className:"truncate",children:u.label}):(0,t.jsx)(X6,{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)(RD,{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(Yxt,"BreadcrumbBar");var VI=240,uq=208,mq=420,wie=16;function HE(e){return Math.min(mq,Math.max(uq,e))}r(HE,"clampSidebarWidth");function kie(e){if(typeof window>"u")return VI;try{const s=window.localStorage.getItem(e);if(!s)return VI;const n=Number.parseInt(s,10);return Number.isFinite(n)?HE(n):VI}catch{return VI}}r(kie,"readStoredSidebarWidth");function Nie(e,s){if(!(typeof window>"u"))try{window.localStorage.setItem(e,String(HE(s)))}catch{}}r(Nie,"writeStoredSidebarWidth");function Zxt({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)(()=>kie(o)),[x,g]=(0,m.useState)(!1),v=(0,m.useRef)(p),y=(0,m.useRef)(null);(0,m.useEffect)(()=>{const P=kie(o);v.current=P,f(P)},[o]);const k=s?p:0,w=s?n?64:k:0,N=s?n&&!a?64:k:0,S=N>w,C=i&&s&&!n,_=(0,m.useMemo)(()=>({width:`${w}px`}),[w]),R=(0,m.useMemo)(()=>({width:`${N}px`}),[N]),I=(0,m.useCallback)(P=>{const Q=HE(P);v.current=Q,f(Q),Nie(o,Q)},[o]),T=(0,m.useCallback)(P=>{C&&(P.preventDefault(),P.currentTarget.setPointerCapture(P.pointerId),y.current={startX:P.clientX,startWidth:v.current},g(!0))},[C]),E=(0,m.useCallback)(P=>{if(!y.current)return;const Q=HE(y.current.startWidth+P.clientX-y.current.startX);v.current=Q,f(Q)},[]),L=(0,m.useCallback)(()=>{y.current&&(y.current=null,g(!1),Nie(o,v.current))},[o]),O=(0,m.useCallback)(P=>{C&&(P.key==="ArrowLeft"?(P.preventDefault(),I(p-wie)):P.key==="ArrowRight"?(P.preventDefault(),I(p+wie)):P.key==="Home"?(P.preventDefault(),I(uq)):P.key==="End"&&(P.preventDefault(),I(mq)))},[C,I,p]);return(0,t.jsx)("div",{className:W("relative h-full shrink-0",l),style:_,children:(0,t.jsxs)("div",{className:W("absolute inset-y-0 left-0 flex flex-col overflow-hidden",S?"z-30 border-r border-border bg-background shadow-lg":"z-0"),style:R,"data-sidebar-overlay":S?"":void 0,onMouseEnter:c,onMouseLeave:d,onFocusCapture:u,onBlurCapture:h,children:[e,C?(0,t.jsx)("div",{role:"separator","aria-label":"Resize sidebar","aria-orientation":"vertical","aria-valuemin":uq,"aria-valuemax":mq,"aria-valuenow":p,tabIndex:0,className:W("absolute inset-y-0 right-0 z-20 w-3 cursor-col-resize touch-none outline-none","before:absolute before:inset-y-0 before:left-1/2 before:w-px before:-translate-x-1/2 before:bg-transparent before:transition-colors","hover:before:bg-border focus-visible:before:bg-ring",x&&"before:bg-ring"),onPointerDown:T,onPointerMove:E,onPointerUp:L,onPointerCancel:L,onLostPointerCapture:L,onKeyDown:O}):null]})})}r(Zxt,"SidebarShell");function Jxt({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)(Axt,{children:e})})}r(Jxt,"SecondarySidebar");var Xxt="/company/settings/members?tab=invites",egt="https://docs.paperclip.ing/",tgt="https://paperclip.ing/feedback";function sgt(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(sgt,"deriveInitials$1");function Sie({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(Sie,"MenuAction");function Cie({deploymentMode:e,open:s,onOpenChange:n}){const i=!!ed(),{hidden:o,loaded:l}=Au(),c=g3e(),d=b3e(!i),u=i?c:d?Xxt:null,h=l&&u!==null&&!Gx(o,"company.members")&&!Gx(o,"company.invites"),[p,f]=(0,m.useState)(!1),{isMobile:x,setSidebarOpen:g,collapsed:v,peeking:y}=Wa(),k=v&&!y,w=s??p,N=v3e(w),S=n??f,{data:C}=te({queryKey:M.auth.session,queryFn:r(()=>Ma.getSession(),"queryFn"),retry:!1}),_=SS({onSignedOut:L}),R=C?.user.name?.trim()||"Board",I=C?.user.email?.trim()||(e==="authenticated"?"Signed in":"Local workspace board"),T=sgt(R),E=y3e(C?.user);function L(){S(!1),x&&g(!1)}r(L,"closeNavigationChrome");function O(){_.mutate()}return r(O,"handleSignOut"),(0,t.jsx)("div",{className:"border-t border-r border-border bg-background px-3 py-2",children:(0,t.jsxs)("div",{className:W("flex items-center gap-0.5",!k&&"px-2"),children:[(0,t.jsxs)(dr,{open:w,onOpenChange:S,children:[(0,t.jsx)(wr,{asChild:!0,children:(0,t.jsxs)("button",{type:"button",className:W("flex min-w-0 items-center gap-2.5 rounded-lg text-left text-(length:--text-compact) font-medium text-foreground/80 transition-colors hover:bg-accent/50 hover:text-foreground",k?"w-full px-3 py-2":"flex-1 px-2 py-1.5"),"aria-label":"Open account menu",children:[(0,t.jsxs)(ko,{size:"sm",children:[C?.user.image?(0,t.jsx)(Zc,{src:C.user.image,alt:R}):null,(0,t.jsx)(No,{children:T})]}),(0,t.jsx)("span",{className:W("min-w-0 flex-1 truncate",k&&"block w-0 min-w-0 overflow-hidden whitespace-nowrap text-transparent select-none"),children:R})]})}),(0,t.jsxs)(sr,{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:E,"aria-label":"View profile",onClick:L,className:"absolute inset-0 rounded-xl transition-colors hover:bg-accent/60 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"}),(0,t.jsx)("div",{className:"pointer-events-none relative rounded-2xl border-4 border-popover bg-popover p-0.5 shadow-sm",children:(0,t.jsxs)(ko,{size:"lg",children:[C?.user.image?(0,t.jsx)(Zc,{src:C.user.image,alt:R}):null,(0,t.jsx)(No,{children:T})]})}),(0,t.jsxs)("div",{className:"pointer-events-none relative min-w-0 flex-1 pt-1",children:[(0,t.jsx)("h2",{className:"truncate text-base font-semibold text-foreground",children:R}),(0,t.jsx)("p",{className:"truncate text-sm text-muted-foreground",children:I}),N?(0,t.jsxs)("a",{className:"pointer-events-auto block truncate font-mono text-(length:--text-micro) leading-(--profile-popover-meta-line-height) text-muted-foreground hover:underline focus-visible:underline",href:`https://github.com/paperclipai/paperclip/commit/${N}`,target:"_blank",rel:"noreferrer","aria-label":`View commit ${N} on GitHub`,title:N,children:["SHA ",N.slice(0,7)]}):null]})]}),(0,t.jsxs)("div",{className:"mt-4 space-y-1",children:[h&&u?(0,t.jsx)(Sie,{label:"Invite",description:"Invite people to your organization.",icon:oh,href:u,topLevel:i,onClick:L}):null,(0,t.jsx)(Sie,{label:"Documentation",description:"Open Paperclip docs in a new tab.",icon:bS,href:egt,external:!0,onClick:r(()=>S(!1),"onClick")}),(0,t.jsx)(Lk,{variant:"menu-action",onAfterToggle:r(()=>S(!1),"onAfterToggle")}),(0,t.jsx)(k3e,{variant:"menu-action",onAfterAction:r(()=>S(!1),"onAfterAction")}),e==="authenticated"?(0,t.jsxs)("button",{type:"button",className:W("flex w-full items-start gap-3 rounded-xl px-3 py-3 text-left transition-colors hover:bg-destructive/10",_.isPending&&"cursor-not-allowed opacity-60"),onClick:O,disabled:_.isPending,children:[(0,t.jsx)("span",{className:"mt-0.5 rounded-lg border border-border bg-background/70 p-2 text-muted-foreground",children:(0,t.jsx)(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:_.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)(N3e,{})]})]})]})]}),!k&&!i?(0,t.jsxs)(Bn,{children:[(0,t.jsx)(On,{asChild:!0,children:(0,t.jsx)("a",{href:tgt,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)(fg,{className:"h-4 w-4","aria-hidden":"true"})})}),(0,t.jsx)($n,{side:"top",children:"Share feedback"})]}):null]})})}r(Cie,"SidebarAccountMenu");function ngt(e,s){return $3e(e,s)[0]?.toLowerCase()??null}r(ngt,"getCompanyRouteSegment");function $3e(e,s){if(!s)return[];const n=e.split("/").filter(Boolean);return n.length<2?[]:n[0]?.toUpperCase()!==s.toUpperCase()?[]:n.slice(1)}r($3e,"getCompanyPathSegments");var rgt=new Set(["browse","connections","connect","chat","review","attention","gateways","advanced","app"]);function agt(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(agt,"isSkillsStoreRoute");function igt(){const{sidebarOpen:e,setSidebarOpen:s,toggleSidebar:n,collapsed:a,peeking:i,setPeeking:o,isMobile:l,setForceCollapsed:c}=Wa(),{openNewIssue:d,openOnboarding:u}=al(),{togglePanelVisible:h}=Rf(),p=bd()?.pushToast??null,{companies:f,loading:x,selectedCompany:g,selectedCompanyId:v,selectionSource:y,setSelectedCompanyId:k}=ps(),{companyPrefix:w,pluginRoutePath:N}=ga(),S=Yn(),C=ua(),_=C8(),R=CNe(C.pathname,w).isTaskDetail,I=["/company/settings","/company/export","/company/import"].some(gt=>C.pathname.includes(gt)),T=$3e(C.pathname,w),E=T[0]?.toLowerCase()==="tools",L=T[0]?.toLowerCase()==="apps",O=L&&T[1]&&!rgt.has(T[1].toLowerCase())?T[1]:null,P=L&&T[1]?.toLowerCase()==="app"&&T[2]?T[2]:null,Q=agt(C.pathname,w),D=(0,m.useRef)(!1),F=(0,m.useRef)(null),z=(0,m.useRef)(null),K=(0,m.useRef)(new Dke),U=(0,m.useRef)(C.key),q=T3e(l&&!R,C.pathname),[G,se]=(0,m.useState)(!1),Z=(0,m.useMemo)(()=>{if(!w)return null;const gt=w.toUpperCase();return f.find(Xe=>Xe.issuePrefix.toUpperCase()===gt)??null},[f,w]),ie=!!w&&!x&&f.length>0&&!Z,J=(0,m.useMemo)(()=>N?.toLowerCase()??ngt(C.pathname,w),[w,C.pathname,N]),re=Z?.id??null,oe=Z?.issuePrefix??null,{slots:V}=Bd({slotTypes:["page","routeSidebar"],companyId:re,enabled:!!(re&&J)}),X=(0,m.useMemo)(()=>GW(V,J),[J,V]),Y=(0,m.useMemo)(()=>({companyId:re,companyPrefix:oe}),[re,oe]),ae=I?(0,t.jsx)(Kxt,{}):O?(0,t.jsx)(jie,{kind:"connection",connectionId:O}):P?(0,t.jsx)(jie,{kind:"application",applicationId:P}):L||E?(0,t.jsx)(Qxt,{}):X?(0,t.jsx)(pm,{slot:X,context:Y,className:"h-full w-full",missingBehavior:"placeholder"}):null,ne=ae!=null,{data:ce}=te({queryKey:M.health,queryFn:r(()=>Iu.get(),"queryFn"),retry:!1,refetchInterval:r(gt=>gt.state.data?.devServer?.enabled?2e3:!1,"refetchInterval"),refetchIntervalInBackground:!1}),he=ne||Q;(0,m.useLayoutEffect)(()=>(c(he),()=>c(!1)),[he,c]),(0,m.useEffect)(()=>{x||D.current||ce?.deploymentMode!=="authenticated"&&(ce?.cloud||f.length===0&&(D.current=!0,u()))},[f,x,u,ce?.cloud,ce?.deploymentMode]),(0,m.useEffect)(()=>{if(!w||x||f.length===0)return;if(!Z){const Xe=(v?f.find(Fe=>Fe.id===v):null)??f[0]??null;Xe&&v!==Xe.id&&k(Xe.id,{source:"route_sync"});return}if(w!==Z.issuePrefix){const Xe=C.pathname.replace(/^\/[^/]+/,"");S(`/${Z.issuePrefix}${Xe}${C.search}`,{replace:!0});return}const gt=R3e({matchedCompany:Z,selectedCompanyId:v,companies:f});if(gt){p?.({title:`${Z.name} is archived`,body:`Switched to ${gt.name}.`,tone:"info",dedupeKey:`archived-company-bounce:${Z.id}`}),k(gt.id,{source:"route_sync"}),S(`/${gt.issuePrefix}/dashboard`,{replace:!0});return}E3e({selectionSource:y,selectedCompanyId:v,routeCompanyId:Z.id})&&k(Z.id,{source:"route_sync"})},[w,f,x,Z,C.pathname,C.search,S,p,y,v,k]);const pe=h,ge=(0,m.useCallback)(()=>{document.dispatchEvent(new KeyboardEvent("keydown",{key:"k",metaKey:!0,bubbles:!0,cancelable:!0}))},[]),Ee=(0,m.useRef)(null),de=(0,m.useRef)(!1),Ne=(0,m.useRef)(!1),le=(0,m.useCallback)(()=>{Ee.current!==null&&(window.clearTimeout(Ee.current),Ee.current=null)},[]),Le=(0,m.useCallback)(()=>{le(),Ee.current=window.setTimeout(()=>o(!0),50)},[le,o]),Ie=(0,m.useCallback)(()=>{le(),o(!0)},[le,o]),ye=(0,m.useCallback)(()=>{le(),Ee.current=window.setTimeout(()=>o(!1),120)},[le,o]),Ae=(0,m.useCallback)(()=>{de.current=!0,a&&!Ne.current&&Le()},[a,Le]),Qe=(0,m.useCallback)(()=>{de.current=!1,Ne.current=!1,ye()},[ye]),ue=(0,m.useCallback)(()=>{Ne.current||Ie()},[Ie]),Be=(0,m.useCallback)(()=>{de.current||ye()},[ye]);(0,m.useEffect)(()=>le,[le]);const ft=(0,m.useRef)(a);return(0,m.useEffect)(()=>{a!==ft.current&&(a?(le(),o(!1),Ne.current=de.current):Ne.current=!1,ft.current=a)},[a,le,o]),(0,m.useEffect)(()=>{if(!i)return;const gt=r(Xe=>{Xe.key==="Escape"&&(le(),o(!1))},"onKeyDown");return window.addEventListener("keydown",gt),()=>window.removeEventListener("keydown",gt)},[i,le,o]),I3e(),S3e({onNewIssue:r(()=>d(),"onNewIssue"),onSearch:ge,onToggleSidebar:n,onTogglePanel:pe,onShowShortcuts:r(()=>se(!0),"onShowShortcuts"),onGoToInbox:r(()=>S("/inbox"),"onGoToInbox")}),(0,m.useEffect)(()=>{if(!l)return;const gt=30,Xe=50,Fe=75;let at=0,Tt=0;const Dt=r(rt=>{const Pe=rt.touches[0];at=Pe.clientX,Tt=Pe.clientY},"onTouchStart"),Ot=r(rt=>{const Pe=rt.changedTouches[0],De=Pe.clientX-at;if(!(Math.abs(Pe.clientY-Tt)>Fe)){if(!e&&at<gt&&De>Xe){s(!0);return}e&&De<-50&&s(!1)}},"onTouchEnd");return document.addEventListener("touchstart",Dt,{passive:!0}),document.addEventListener("touchend",Ot,{passive:!0}),()=>{document.removeEventListener("touchstart",Dt),document.removeEventListener("touchend",Ot)}},[l,e,s]),(0,m.useEffect)(()=>{const gt=document.body.style.overflow;return document.body.style.overflow=l?"visible":"clip",()=>{document.body.style.overflow=gt}},[l]),(0,m.useEffect)(()=>{if(!l)return M3e()},[l]),(0,m.useEffect)(()=>{if(typeof document>"u")return;const gt=z.current;return L3e(gt)},[C.pathname]),(0,m.useEffect)(()=>{const gt=z.current;if(!gt)return;const Xe=r(()=>{K.current.remember(U.current,gt.scrollTop)},"recordScroll");return gt.addEventListener("scroll",Xe,{passive:!0}),()=>gt.removeEventListener("scroll",Xe)},[]),(0,m.useLayoutEffect)(()=>{const gt=z.current,Xe=Pke({previousPathname:F.current,pathname:C.pathname,navigationType:_,state:C.state});F.current=C.pathname;const Fe=_==="POP",at=Fe?K.current.recall(C.key):0;if(U.current=C.key,Fe){W6(gt,at);const Tt=requestAnimationFrame(()=>W6(gt,at));return()=>cancelAnimationFrame(Tt)}Xe&&$ke(gt)},[C.key,C.pathname,C.state,_]),(0,t.jsx)(Lke,{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)(a3e,{}),(0,t.jsx)(i3e,{devServer:ce?.devServer}),(0,t.jsxs)("div",{className:W("min-h-0 flex-1",l?"w-full":"flex overflow-clip"),children:[l&&e&&(0,t.jsx)("button",{type:"button",className:"fixed inset-0 z-40 bg-black/50",onClick:r(()=>s(!1),"onClick"),"aria-label":"Close sidebar"}),l?(0,t.jsxs)("div",{className:W("fixed inset-y-0 left-0 z-50 flex flex-col overflow-hidden pt-(--sz-safe-top) transition-transform duration-100 ease-out",e?"translate-x-0":"-translate-x-full"),children:[(0,t.jsx)("div",{className:"flex flex-1 min-h-0 overflow-hidden",children:(0,t.jsx)("div",{className:"w-60 shrink-0 overflow-hidden",children:ne?ae:(0,t.jsx)(yie,{})})}),(0,t.jsx)(Cie,{deploymentMode:ce?.deploymentMode})]}):(0,t.jsxs)(Zxt,{open:e,collapsed:a,peeking:i,resizable:!0,onPanelMouseEnter:Ae,onPanelMouseLeave:Qe,onPanelFocusCapture:a?ue:void 0,onPanelBlurCapture:a?Be:void 0,children:[(0,t.jsx)("div",{className:"flex flex-1 min-h-0",children:(0,t.jsx)(yie,{})}),(0,t.jsx)(Cie,{deploymentMode:ce?.deploymentMode})]}),!l&&ne?(0,t.jsx)(Jxt,{children:ae}):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)(aq,{mobile:l,onNavigateHome:r(()=>S("/dashboard"),"onNavigateHome")}),(0,t.jsx)(Yxt,{}),l&&I?(0,t.jsx)("div",{className:"border-b border-border px-4 pb-3",children:(0,t.jsx)(INe,{})}):null]}),(0,t.jsxs)("div",{className:W(l?"block":"flex flex-1 min-h-0"),children:[(0,t.jsx)("main",{id:"main-content",ref:z,tabIndex:-1,style:l?{"--tc-composer-bottom":"var(--sz-calc-14)"}:void 0,className:W("flex-1 p-4 outline-none md:p-6",l?"overflow-visible pb-(--sz-calc-14)":"overflow-auto [scrollbar-gutter:stable]"),children:ie?(0,t.jsx)(om,{scope:"invalid_company_prefix",requestedPrefix:w??g?.issuePrefix}):(0,t.jsx)(c3e,{children:(0,t.jsx)(cv,{})})}),(0,t.jsx)(zNe,{})]})]})]}),l&&(0,t.jsx)(r3e,{visible:q}),(0,t.jsx)(qNe,{}),(0,t.jsx)(CSe,{}),(0,t.jsx)(p5e,{}),(0,t.jsx)(g5e,{}),(0,t.jsx)(j5e,{}),(0,t.jsx)(w5e,{open:G,onOpenChange:se}),(0,t.jsx)(k5e,{}),(0,t.jsx)(s3e,{companyId:v}),(0,t.jsx)(n3e,{localTrusted:ce?.deploymentMode==="local_trusted"})]})})}r(igt,"Layout");var _ie=null;function ogt(){return _ie??=new rS,_ie}r(ogt,"getDetachedClient");function lgt(){const e=(0,m.useContext)(h3),{data:s,isFetched:n}=te({queryKey:M.instance.experimentalSettings,queryFn:r(()=>jr.getExperimental(),"queryFn"),enabled:e!=null},e??ogt());return e?{enabled:s?.enableConferenceRoomChat===!0,loaded:n}:{enabled:!1,loaded:!0}}r(lgt,"useConferenceRoomChatEnabled");function cgt(){const{enabled:e,loaded:s}=lgt();return s?e?(0,t.jsx)(cv,{}):(0,t.jsx)(_n,{to:"/dashboard",replace:!0}):null}r(cgt,"ConferenceRoomChatGate");var dgt=["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"],ugt={"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 }"}},eys=dgt.map(e=>ugt[e]);function O3e({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)(gm,{className:"size-4 shrink-0 text-muted-foreground","aria-hidden":!0}),(0,t.jsx)("span",{children:s}),(0,t.jsxs)("span",{className:"text-muted-foreground",children:["· ",e.status]}),n&&(0,t.jsx)($,{variant:"ghost",size:"sm",onClick:r(()=>n(e.id),"onClick"),children:a?"View session":"Open browser"})]})}r(O3e,"TaskBrowserActivity");function B3e({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)(lQe,{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)(to,{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(B3e,"TaskChatProjectCreatedCard");function mgt({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)(hf,{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(mgt,"TaskChatSkillCreatedCard");function hgt(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(hgt,"McpIcon");var pgt=new Set(["tool","tool call","tool_call","acp_tool"]);function ju(e){const s=(e??"").trim().toLowerCase().replace(/\s*\((?:pending|in[_ -]?progress|completed|failed|cancelled|canceled)\)$/,"");return!s||pgt.has(s)}r(ju,"isGenericToolName");function HV(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(HV,"mcpToolIdentity");function VV(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(VV,"identifierWords");function F3e(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(F3e,"sentenceCase");function Mk(e){const s=(e??"").trim();return ju(s)?"Unnamed tool":F3e(VV(HV(s)?.name??s))}r(Mk,"humanizeToolName");var Wd=r((e,s,n)=>({key:e,singular:s,plural:n}),"group"),fgt={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:Wd("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:Wd("task_operation","task operation","task operations")},task_create:{action:"create",running:"Creating a task",completed:"Created a task",family:"plan",group:Wd("task_operation","task operation","task operations")},task_update:{action:"update",running:"Updating a task",completed:"Updated a task",family:"plan",group:Wd("task_operation","task operation","task operations")},task_list:{action:"list",running:"Listing tasks",completed:"Listed tasks",family:"plan",group:Wd("task_operation","task operation","task operations")},task_get:{action:"read",running:"Reading a task",completed:"Read a task",family:"plan",group:Wd("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:Wd("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"}},xgt={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:[]},ggt={read:"read",edit:"update",delete:"delete",move:"move",search:"search",list:"list",execute:"run",think:"think",fetch:"fetch",switch_mode:"switch"};function bgt(e){return VV(e).join("_")}r(bgt,"normalizedKey");function vgt(e){const s=e[0];if(!s)return null;for(const[n,a]of Object.entries(xgt))if(a.includes(s))return n;return null}r(vgt,"inferredAction");function ygt(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(ygt,"actionFamily");var jgt={terminal:pf,grep:AQe,search:Jr,read:bS,edit:O8,web:GKe,plan:ew,question:Ac,agent:Vb,safety:qi,image:D3,wait:Nu,mcp:hgt,other:hf};function wgt(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(wgt,"actionCopy");function kgt(e){switch(e){case"run":return Wd("command","command","commands");case"read":case"list":return Wd("read","read","reads");case"search":return Wd("search","search","searches");case"update":case"create":case"delete":case"move":return Wd("file_change","file change","file changes");case"start":case"stop":return Wd("delegation","delegation","delegations");case"wait":return Wd("wait","wait","waits");default:return Wd("tool_action","tool action","tool actions")}}r(kgt,"defaultSummaryGroup");function Ngt(e){return e==="read"||e==="list"?Wd("paperclip_read","Paperclip read","Paperclip reads"):Wd("task_operation","task operation","task operations")}r(Ngt,"paperclipSummaryGroup");function Tj(e){const s=(e.name??"").trim(),n=HV(s),a=(e.namespace??n?.namespace??"").trim(),i=(n?"mcp":e.transport??"builtin").toLowerCase(),o=(n?.name??s).trim(),l=VV(o),c=bgt(o),d=fgt[c],u=ggt[(e.operation??"").trim().toLowerCase()],h=vgt(l),p=d?.action??u??h??"other",f=d?"exact":u?"kind":h?"inferred":ju(o)?"unnamed":"fallback",x=ju(o)?"Unnamed tool":Mk(o),g=/^[A-Za-z][A-Za-z0-9_.:-]*$/.test(o),v=h&&g&&l.length>1?l.slice(1):[],y=v.length?F3e(v).replace(/^./,_=>_.toLowerCase()):void 0,k=d?.running&&d.completed?{running:d.running,completed:d.completed}:p==="other"?ju(o)?{running:"Running an unnamed tool",completed:"Ran an unnamed tool"}:{running:`Running ${x}`,completed:`Ran ${x}`}:wgt(p,d?void 0:y),w=d?.family??ygt(p),N=i==="mcp"?"mcp":w,S=a?Mk(a):i==="mcp"?"MCP":void 0,C=a.toLowerCase()==="paperclip"?Ngt(p):d?.group??kgt(p);return{icon:jgt[N],family:N,runningLabel:k.running,completedLabel:k.completed,failedLabel:`${k.completed} · failed`,interruptedLabel:`${k.running} · stopped`,displayName:x,sourceLabel:S,technicalName:s||void 0,confidence:f,summaryGroup:C}}r(Tj,"toolActivityPresentation");function EN(e){const s=Tj({name:e});return{family:s.family,icon:s.icon,verbLabel:s.runningLabel}}r(EN,"toolTaxonomy");function z3e(e){const s=(e??"").trim().toLowerCase();return s==="thinking"?$x:s==="responding"||s.startsWith("responding (")?gQe:null}r(z3e,"statusLabelIcon");var ED=["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"],LD=["Brewing","Tinkering","Distilling","Deliberating"],Aie=(()=>{const e=[],s=Math.max(ED.length,LD.length);for(let n=0;n<s;n++)n<ED.length&&e.push(ED[n]),n<LD.length&&e.push(LD[n]);return e})(),Sgt=1e4;function Cgt(e){const s=(e??"").trim().toLowerCase();return s==="running"||s==="working"}r(Cgt,"isGenericStatusLabel");function _gt(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(_gt,"fnv1a");function Agt(e,s=0){const n=Math.floor(Math.max(0,s)/Sgt);return Aie[(_gt(e)+n)%Aie.length]}r(Agt,"whimsyWord");var Igt=[{name:"--motion-ease-out-expo",group:"Easing",kind:"easing"},{name:"--motion-ease-standard",group:"Easing",kind:"easing"},{name:"--motion-ease-out",group:"Easing",kind:"easing"},{name:"--motion-ease-scroll-pill-in",group:"Easing",kind:"easing"},{name:"--motion-ease-scroll-pill-out",group:"Easing",kind:"easing"},{name:"--motion-ease-in",group:"Easing",kind:"easing"},{name:"--motion-duration-instant",group:"Durations",kind:"time",min:0,max:1e3,step:10},{name:"--motion-duration-fast",group:"Durations",kind:"time",min:0,max:1e3,step:10},{name:"--motion-duration-base",group:"Durations",kind:"time",min:0,max:1e3,step:10},{name:"--motion-duration-slow",group:"Durations",kind:"time",min:0,max:1500,step:10},{name:"--motion-duration-deliberate",group:"Durations",kind:"time",min:0,max:2e3,step:10},{name:"--motion-duration-enter",group:"Durations",kind:"time",min:0,max:1e3,step:10},{name:"--motion-duration-exit",group:"Durations",kind:"time",min:0,max:1e3,step:10},{name:"--motion-duration-swap",group:"Durations",kind:"time",min:0,max:1e3,step:10},{name:"--motion-marker-enter",group:"States",kind:"time",min:0,max:1500,step:10},{name:"--motion-bubble-enter",group:"States",kind:"time",min:0,max:1500,step:10},{name:"--motion-cot-line-stagger",group:"States",kind:"time",min:0,max:300,step:5},{name:"--motion-cot-collapse",group:"States",kind:"time",min:0,max:1500,step:10},{name:"--motion-tool-enter",group:"States",kind:"time",min:0,max:1500,step:10},{name:"--motion-diff-reveal",group:"States",kind:"time",min:0,max:1500,step:10},{name:"--motion-status-enter",group:"States",kind:"time",min:0,max:1500,step:10},{name:"--motion-status-exit",group:"States",kind:"time",min:0,max:1500,step:10},{name:"--motion-approval-pulse",group:"States",kind:"time",min:0,max:3e3,step:20},{name:"--motion-plan-entry-stagger",group:"States",kind:"time",min:0,max:300,step:5},{name:"--motion-plan-check",group:"States",kind:"time",min:0,max:1500,step:10},{name:"--motion-question-page-enter",group:"States",kind:"time",min:0,max:1e3,step:10},{name:"--motion-count-tween",group:"States",kind:"time",min:0,max:1500,step:10},{name:"--motion-streaming-cursor-blink",group:"States",kind:"time",min:0,max:3e3,step:20},{name:"--motion-turn-fold",group:"States",kind:"time",min:0,max:1500,step:10},{name:"--motion-turn-meta",group:"States",kind:"time",min:0,max:1500,step:10},{name:"--motion-line-scroll",group:"States",kind:"time",min:0,max:1500,step:10},{name:"--motion-interstitial-dwell",group:"States",kind:"time",min:0,max:1e4,step:100},{name:"--motion-scroll-pill-enter",group:"States",kind:"time",min:0,max:1500,step:10},{name:"--motion-scroll-pill-exit",group:"States",kind:"time",min:0,max:1500,step:10},{name:"--motion-mobile-nav-enter",group:"States",kind:"time",min:0,max:1500,step:10},{name:"--motion-mobile-nav-exit",group:"States",kind:"time",min:0,max:1500,step:10},{name:"--motion-scrollbar-idle-delay",group:"States",kind:"time",min:0,max:2e3,step:10},{name:"--motion-pane-glide",group:"States",kind:"time",min:0,max:1500,step:10},{name:"--motion-side-panel-tab",group:"States",kind:"time",min:0,max:1500,step:10},{name:"--motion-live-now-sweep",group:"States",kind:"time",min:0,max:5e3,step:100},{name:"--motion-live-now-breathe",group:"States",kind:"time",min:0,max:5e3,step:100}],tys=Array.from(new Set(Igt.map(e=>e.group)));function q3e(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(q3e,"parseCssTimeMs");function Tgt(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(Tgt,"elapsedLabel");function Rgt(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(Rgt,"liveElapsedLabel");function Egt(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(Egt,"useLiveElapsedMs");function Lgt(e,s){return!Number.isFinite(e)||!Number.isFinite(s)||s<=0?0:Math.max(0,Math.round(e/s)-1)}r(Lgt,"lineScrollOffset");function SR(e){const s=getComputedStyle(document.documentElement).getPropertyValue(e),n=q3e(s);return Number.isFinite(n)?n:0}r(SR,"motionTokenMs");function Mgt({text:e,streaming:s,leaving:n}){const a=(0,m.useRef)(null),[i,o]=(0,m.useState)(0),[l,c]=(0,m.useState)(!1),[d,u]=(0,m.useState)(!1);(0,m.useLayoutEffect)(()=>{const p=a.current;if(!p)return;const f=r(()=>{const g=parseFloat(window.getComputedStyle(p).lineHeight);o(Lgt(p.scrollHeight,g))},"measure");if(f(),typeof ResizeObserver>"u")return;const x=new ResizeObserver(f);return x.observe(p),()=>x.disconnect()},[e,s]),(0,m.useEffect)(()=>{const p=requestAnimationFrame(()=>c(!0)),f=window.setTimeout(()=>u(!0),SR("--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(Mgt,"LiveSelfTalkLine");function Pgt(e,s){const[n,a]=(0,m.useState)(null),i=(0,m.useRef)(n),o=(0,m.useRef)(null),l=(0,m.useRef)(e),c=(0,m.useRef)(0),d=(0,m.useRef)(null),u=(0,m.useRef)(null),h=(0,m.useRef)(null);return l.current=e,(0,m.useEffect)(()=>{const p=r(y=>{y.current!=null&&(window.clearTimeout(y.current),y.current=null)},"clear"),f=r(y=>{i.current=y,a(y)},"show"),x=r(()=>{p(u),p(h),u.current=window.setTimeout(()=>{if(u.current=null,o.current!=null)return;const y=i.current;y==null||y.streaming||(f({...y,leaving:!0}),h.current=window.setTimeout(()=>{h.current=null,i.current?.leaving&&f(null)},SR("--motion-line-scroll")))},SR("--motion-interstitial-dwell"))},"scheduleLeave"),g=r((y,k)=>{p(u),p(h),c.current=Date.now(),f({text:y,streaming:k,swapKey:(i.current?.swapKey??0)+1}),k||x()},"swapIn");if(!s){p(d),p(u),p(h),o.current=null,i.current&&f(null);return}const v=i.current;if(e==null){v?.streaming&&(f({...v,streaming:!1}),x());return}if(v==null){g(e,!0);return}if(v.streaming){v.text!==e&&f({...v,text:e});return}if(o.current=e,d.current==null){const y=SR("--motion-interstitial-dwell"),k=Math.max(0,c.current+y-Date.now());d.current=window.setTimeout(()=>{d.current=null;const w=o.current;o.current=null,w!=null&&g(w,l.current!=null)},k)}},[e,s]),(0,m.useEffect)(()=>()=>{d.current!=null&&window.clearTimeout(d.current),u.current!=null&&window.clearTimeout(u.current),h.current!=null&&window.clearTimeout(h.current)},[]),n}r(Pgt,"useHeldSelfTalk");var Dgt={running:{Icon:st,spin:!0,tone:"text-(--status-agent-running)"},working:{Icon:st,spin:!0,tone:"text-(--status-agent-running)"},awaiting_approval:{Icon:yS,spin:!1,tone:"text-primary"},interrupted:{Icon:AW,spin:!1,tone:"text-destructive"},refused:{Icon:zm,spin:!1,tone:"text-destructive"},truncated:{Icon:_Qe,spin:!1,tone:"text-(--status-agent-paused)"}};function U3e({item:e,onApprovalDecision:s,chevronOpen:n,onToggle:a}){const{Icon:i,spin:o,tone:l}=Dgt[e.status],c=e.status==="awaiting_approval",d=e.status==="running"||e.status==="working",u=Egt(e.startedAtMs,d),h=Pgt(d?e.selfTalk:void 0,d),p=Tgt(e.elapsedMs);if(d){const f=Rgt(u??e.elapsedMs),x=e.selfTalk!=null,g=e.toolName?EN(e.toolName).icon:x?null:z3e(e.label),v=x||Cgt(e.label)?Agt(e.id,u??e.elapsedMs??0):e.label,y=(0,t.jsxs)("div",{className:"tc-enter-status flex items-center gap-2 py-0.5 text-xs text-muted-foreground",children:[n!==void 0?(0,t.jsx)("span",{className:"flex h-3.5 w-3.5 shrink-0 items-center justify-center","data-testid":"task-chat-status-caret-slot",children:(0,t.jsx)(An,{className:W("h-3 w-3 transition-transform",n?"rotate-90":null),"aria-hidden":!0})}):null,(0,t.jsx)("span",{className:"flex h-3.5 w-3.5 shrink-0 items-center justify-center","data-testid":"task-chat-status-dot-slot",children:(0,t.jsx)("span",{"aria-hidden":!0,className:"h-2 w-2 animate-pulse rounded-full bg-(--status-agent-running)"})}),g?(0,t.jsx)(g,{className:"h-3.5 w-3.5 shrink-0","aria-hidden":!0}):null,(0,t.jsxs)("span",{className:"flex min-w-0 flex-1 items-baseline gap-2",children:[(0,t.jsxs)("span",{className:"shimmer-text shimmer-text-muted shrink-0 font-medium",children:[v,"…"]}),f?(0,t.jsx)("span",{className:"shrink-0 font-mono tabular-nums text-(length:--text-micro)",children:f}):null,e.detail?(0,t.jsx)("span",{className:"min-w-0 truncate font-mono text-(length:--text-micro)",children:e.detail}):null,e.tokens?(0,t.jsxs)("span",{className:"ml-auto shrink-0 font-mono text-(length:--text-micro)",children:[e.tokens.used.toLocaleString(),"/",e.tokens.size.toLocaleString()," ctx"]}):null]})]});return(0,t.jsxs)("div",{className:"flex flex-col",children:[(0,t.jsxs)("div",{className:"flex items-center gap-2 py-0.5 text-xs text-muted-foreground","data-testid":"task-chat-interstitial-row",children:[(0,t.jsx)("span",{"aria-hidden":!0,className:"h-3.5 w-3.5 shrink-0"}),h?(0,t.jsx)(Mgt,{text:h.text,streaming:h.streaming,leaving:h.leaving},h.swapKey):(0,t.jsx)("span",{"aria-hidden":!0,className:"tc-line-scroll min-w-0 flex-1"})]}),a?(0,t.jsx)("button",{type:"button",onClick:a,"aria-expanded":n,className:"-mx-1.5 block w-full rounded-sm px-1.5 text-left transition-colors hover:bg-muted/60","data-testid":"task-chat-live-turn",children:y}):y]})}return(0,t.jsxs)("div",{className:W("tc-enter-status flex flex-col gap-2 rounded-lg border px-3 py-2 text-sm",c?"tc-approval border-primary/40 bg-primary/5":"border-border bg-muted/40"),children:[(0,t.jsxs)("div",{className:"flex min-w-0 items-center gap-2",children:[(0,t.jsx)(i,{className:W("h-4 w-4 shrink-0",l,o&&"animate-spin")}),(0,t.jsx)("span",{className:"min-w-0 truncate font-medium",children:e.label}),(0,t.jsxs)("span",{className:"ml-auto flex shrink-0 items-center gap-2 text-xs text-muted-foreground",children:[p?(0,t.jsx)("span",{children:p}):null,e.tokens?(0,t.jsxs)("span",{children:[e.tokens.used.toLocaleString(),"/",e.tokens.size.toLocaleString()," ctx"]}):null]})]}),e.detail?(0,t.jsx)("p",{className:"text-xs text-muted-foreground",children:e.detail}):null,c&&e.approval?(0,t.jsx)("div",{className:"flex flex-wrap justify-end gap-2 pt-1",children:e.approval.options.map(f=>{const x=f.kind.startsWith("reject");return(0,t.jsx)("button",{type:"button",onClick:r(()=>s?.(f.id),"onClick"),className:W("rounded-md border px-2.5 py-1 text-xs font-medium transition-colors",x?"border-border text-muted-foreground hover:bg-accent/50 hover:text-foreground":"border-primary bg-primary text-primary-foreground hover:bg-primary/90"),children:f.label},f.id)})}):null]})}r(U3e,"TaskChatStatusPill");var jg=(0,m.createContext)(null);function uw(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(uw,"formatBytes$4");var VE=new Set(["application/octet-stream","binary/octet-stream","application/x-binary"]),$gt=[".mp4",".m4v",".webm",".mov",".qt",".quicktime"],Ogt=[".png",".jpg",".jpeg",".gif",".webp",".avif",".bmp",".ico"],Bgt=new Set(["application/wasm"]),Fgt=new Set(["application/zip","application/x-zip","application/x-zip-compressed"]),K3e=new Set(["text/markdown","text/x-markdown","application/markdown","application/x-markdown"]),zgt=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"]),qgt=[".csv",".css",".graphql",".htm",".html",".js",".json",".jsx",".log",".markdown",".md",".mdx",".php",".py",".sh",".sql",".toml",".ts",".tsx",".txt",".xml",".yaml",".yml"];function rA(e){return(e??"").toLowerCase().split(";")[0]?.trim()??""}r(rA,"normalizeOutputContentType");function Ugt(e){const s=(e??"").trim().toLowerCase();return s?qgt.some(n=>s.endsWith(n)):!1}r(Ugt,"hasDocumentLikeFilename");function Q3e(e){return Fgt.has(e)||e.endsWith("+zip")}r(Q3e,"isZipContentType");function Kgt(e){return e?!!(e.startsWith("text/")||K3e.has(e)||zgt.has(e)||e.startsWith("application/")&&(e.endsWith("+json")||e.endsWith("+xml"))):!1}r(Kgt,"isDocumentLikeOutputContentType");function Qgt(e,s){const n=rA(e);return!n||Kgt(n)||VE.has(n)&&Ugt(s)?!1:n.startsWith("video/")||n.startsWith("image/")||n==="application/pdf"||Bgt.has(n)||Q3e(n)||VE.has(n)}r(Qgt,"isOutputEligibleContentType");function Wgt(e){const s=rA(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"}:Q3e(s)?{label:"ZIP",tone:"zip"}:s.startsWith("image/")?{label:"IMG",tone:"image"}:K3e.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(Wgt,"getOutputFileGlyph");function fm(e,s){const n=rA(e);if(n.startsWith("video/"))return!0;if(!VE.has(n))return!1;const a=(s??"").trim().toLowerCase();return $gt.some(i=>a.endsWith(i))}r(fm,"isVideoLikeOutput");function Rj(e){const s=rA(e);return s.startsWith("image/")&&s!=="image/svg+xml"}r(Rj,"isImageContentType");function DM(e,s){const n=rA(e);if(Rj(n))return!0;if(n&&!VE.has(n))return!1;const a=(s??"").trim().toLowerCase();return Ogt.some(i=>a.endsWith(i))}r(DM,"isImageLikeOutput");function Iie(e){const s=new Date(e).getTime();return Number.isNaN(s)?0:s}r(Iie,"toTime");function $M(e){const s=(e??[]).filter(n=>n.type==="artifact"&&n.provider==="paperclip").flatMap(n=>{const a=H$e.safeParse(n.metadata);return a.success&&!Qgt(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:Iie(a.createdAt)-Iie(n.createdAt)),{items:s,primary:s[0]??null,rest:s.slice(1),count:s.length}}r($M,"getIssueOutputs");function GV(e){return e.metadata?.originalFilename||e.title||"output"}r(GV,"outputFilename");function W3e(e){return new Set($M(e).items.flatMap(s=>{const n=s.metadata?.attachmentId;return n?[n]:[]}))}r(W3e,"getPromotedOutputAttachmentIds");function aA(e,s){const n=e?.toLowerCase().split(";")[0].trim();return n==="text/html"||n==="application/xhtml+xml"||/\.html?$/i.test(s??"")}r(aA,"isHtmlPreview");var Hgt=["default-src 'none'","script-src 'unsafe-inline'","style-src 'unsafe-inline'","img-src data:","font-src data:","media-src data:","connect-src 'none'","frame-src 'none'","object-src 'none'","base-uri 'none'","form-action 'none'"].join("; ");function Vgt(e){return`<!doctype html><html><head><meta charset="utf-8"><meta http-equiv="Content-Security-Policy" content="${Hgt}"><meta name="referrer" content="no-referrer"></head><body>${e}</body></html>`}r(Vgt,"htmlPreviewDocument");function Ggt(e){return e.contentType.toLowerCase().split(";")[0]?.trim()??""}r(Ggt,"normalizedContentType");function og(e){return e.originalFilename??e.id}r(og,"attachmentFilename");function OM(e){return e.openPath??e.contentPath}r(OM,"attachmentOpenPath");function LS(e){return e.downloadPath??`${e.contentPath}?download=1`}r(LS,"attachmentDownloadPath");function H3e(e){const s=Ggt(e);return DM(s,e.originalFilename)&&!/^image\/hei[cf](?:-sequence)?$/.test(s)}r(H3e,"isImageAttachment$1");function V3e(e){return fm(e.contentType,e.originalFilename)}r(V3e,"isVideoAttachment");function G3e(e){return xbe(e)}r(G3e,"isMarkdownAttachment");function mw(e){const s=e.contentType.toLowerCase().split(";")[0].trim();return xbe(e)||aA(s,e.originalFilename)||s.startsWith("text/")||/^(application\/(json|xml|javascript|x-yaml|yaml)|application\/[\w.-]+\+json)$/.test(s)||["","application/octet-stream"].includes(s)&&/\.(txt|log|csv|json|yaml|yml|toml|ini|sh|ts|tsx|js|jsx|py|css|html)$/i.test(e.originalFilename??"")}r(mw,"isTextAttachment");function Y3e(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(Y3e,"downloadBlob$1");function Ygt(e,s,n){Y3e(e,new Blob([s],{type:`${n};charset=utf-8`}))}r(Ygt,"downloadTextFile");var MD="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 Z3e({issueId:e,documentKey:s,title:n,format:a,body:i,className:o}){const[l,c]=(0,m.useState)(null),[d,u]=(0,m.useState)(null),[h,p]=(0,m.useState)(null),{copy:f,copied:x,failed:g}=Z0(),v=(0,m.useRef)(void 0);(0,m.useEffect)(()=>()=>clearTimeout(v.current),[]);const y=(0,m.useCallback)(async(_,R)=>{c(_),p(null);try{await R(),u(_)}catch(I){u(null),p(I instanceof Error?I.message:"Export failed")}finally{c(null)}clearTimeout(v.current),v.current=setTimeout(()=>{u(null),p(null)},2e3)},[]),k=(0,m.useCallback)(async()=>i??(await jt.getDocument(e,s)).body,[i,s,e]),w=(0,m.useCallback)(()=>{c("copy"),p(null),(async()=>{try{await f(await k())==="failed"&&p("Copy failed")}catch(_){p(_ instanceof Error?_.message:"Copy failed")}finally{c(null)}})()},[f,k]),N=g||h==="Copy failed"?"Copy failed":x?"Copied!":"Copy full content",S=d==="download"?"Downloaded!":"Download source",C=d==="pdf"?"Downloaded!":"Export to PDF";return(0,t.jsxs)("div",{className:W("flex items-center gap-0.5",o),"data-testid":"document-export-actions",children:[(0,t.jsx)("button",{type:"button",className:MD,disabled:l!==null,"aria-label":"Copy full content",title:N,"data-testid":"document-export-copy",onClick:r(_=>{_.preventDefault(),_.stopPropagation(),w()},"onClick"),children:x?(0,t.jsx)(cs,{"aria-hidden":"true",className:"h-3.5 w-3.5"}):(0,t.jsx)(gr,{"aria-hidden":"true",className:"h-3.5 w-3.5"})}),(0,t.jsx)("button",{type:"button",className:MD,disabled:l!==null,"aria-label":"Download source",title:S,"data-testid":"document-export-download",onClick:r(_=>{_.preventDefault(),_.stopPropagation(),y("download",async()=>{const R=aUe(a);Ygt(yte(n,R),await k(),R==="md"?"text/markdown":"text/plain")})},"onClick"),children:(0,t.jsx)(Ui,{"aria-hidden":"true",className:"h-3.5 w-3.5"})}),(0,t.jsx)("button",{type:"button",className:MD,disabled:l!==null,"aria-label":"Export to PDF",title:C,"data-testid":"document-export-pdf",onClick:r(_=>{_.preventDefault(),_.stopPropagation(),y("pdf",async()=>{Y3e(yte(n,"pdf"),await jt.getDocumentPdf(e,s))})},"onClick"),children:(0,t.jsx)(iQe,{"aria-hidden":"true",className:"h-3.5 w-3.5"})}),(0,t.jsx)("span",{className:"sr-only",role:"status","aria-live":"polite",children:h??(x?"Copied!":g?"Copy failed":d?"Downloaded!":"")})]})}r(Z3e,"DocumentExportActions");function T5({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(T5,"PreviewFrame");function GE({label:e}){return(0,t.jsx)(T5,{className:"flex items-center justify-center",children:(0,t.jsxs)("div",{className:"flex flex-col items-center gap-1.5 text-muted-foreground/50",children:[(0,t.jsx)(kl,{className:"h-7 w-7","aria-hidden":"true"}),e?(0,t.jsx)("span",{className:"text-(length:--text-micro) font-medium uppercase tracking-wide",children:e}):null]})})}r(GE,"PlaceholderPreview");function Zgt({artifact:e}){const[s,n]=(0,m.useState)(!1);return s||!e.contentPath?(0,t.jsx)(GE,{label:"Image"}):(0,t.jsx)(T5,{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(Zgt,"ImagePreview");function Jgt({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)(T5,{className:"flex items-center justify-center bg-black/80",children:(0,t.jsx)("div",{className:"flex h-11 w-11 items-center justify-center rounded-full bg-white/15",children:(0,t.jsx)(ho,{className:"h-5 w-5 translate-x-0.5 text-white","aria-hidden":"true"})})});const c=r(()=>{l.current!==null&&(window.clearTimeout(l.current),l.current=null),i(!0)},"markFrameReady"),d=r(()=>{l.current!==null&&window.clearTimeout(l.current),l.current=window.setTimeout(c,3e3)},"scheduleFrameReadyFallback"),u=r(p=>{if(o.current)return;o.current=!0;const f=p.currentTarget,x=Number.isFinite(f.duration)&&f.duration>0?f.duration:0,g=x>0?Math.min(1,x/4):.05;try{Math.abs(f.currentTime-g)>.001?(f.currentTime=g,d()):c()}catch{c()}},"loadThumbnailFrame"),h=r(p=>{(o.current||p.currentTarget.currentTime>0)&&c()},"handleLoadedData");return(0,t.jsxs)(T5,{className:"bg-black",children:[(0,t.jsx)("video",{src:e.contentPath,preload:"metadata",muted:!0,playsInline:!0,"data-frame-ready":a?"true":"false",className:W("h-full w-full object-contain transition-opacity",a?"opacity-100":"opacity-0"),onLoadedMetadata:u,onLoadedData:h,onSeeked:c,onError:r(()=>n(!0),"onError")}),(0,t.jsx)("div",{className:"pointer-events-none absolute inset-0 flex items-center justify-center",children:(0,t.jsx)("div",{className:"flex h-11 w-11 items-center justify-center rounded-full bg-black/55",children:(0,t.jsx)(ho,{className:"h-5 w-5 translate-x-0.5 text-white","aria-hidden":"true"})})})]})}r(Jgt,"VideoPreview");function Xgt({artifact:e}){const s=e.previewText?.trim();return s?(0,t.jsxs)(T5,{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)(GE,{label:e.source==="document"?"Document":"Text"})}r(Xgt,"TextPreview");function iA({artifact:e}){switch(e.mediaKind){case"image":return(0,t.jsx)(Zgt,{artifact:e},e.contentPath);case"video":return(0,t.jsx)(Jgt,{artifact:e},e.contentPath);case"text":case"document":return(0,t.jsx)(Xgt,{artifact:e});case"file":return(0,t.jsx)(GE,{label:"File"});default:return(0,t.jsx)(GE,{})}}r(iA,"ArtifactPreview");function Tie({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(Tie,"SecondaryAction");function ebt({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)(iA,{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)(Z3e,{issueId:e.issue.id,documentKey:e.documentKey,title:e.title}):null,e.openPath?(0,t.jsx)(Tie,{href:e.openPath,title:"Open file in new tab",children:(0,t.jsx)(Dn,{className:"h-3.5 w-3.5"})}):null,e.downloadPath?(0,t.jsx)(Tie,{href:e.downloadPath,download:!0,title:"Download file",children:(0,t.jsx)(Ui,{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 ",Gd(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(ebt,"ArtifactCard");function tbt(e){return e&&/^\/api\/assets\/[^/?#]+\/content$/.test(e)?e:null}r(tbt,"paperclipHumanAvatarUrl");function J3e(e){const{authorName:s,authorUserId:n,currentUserId:a,userProfileMap:i}=e,o=n?i?.get(n):null,l=!!(n&&a&&n===a);return{isCurrentUser:l,authorName:o?.label?.trim()||s?.trim()||(n==="local-board"?"Board":l?"You":"User"),avatarUrl:o?.image??null}}r(J3e,"resolveIssueChatHumanAuthor");var tc={credentials:r(e=>we.get(`/companies/${e}/email/connections`),"credentials"),checkAddress:r((e,s,n,a)=>we.post(`/companies/${e}/email/connections/${s}/check-address`,n,{signal:a}),"checkAddress"),connect:r((e,s)=>we.post(`/companies/${e}/email/connections`,s),"connect"),inspectSaved:r((e,s)=>we.post(`/companies/${e}/email/connections/${s}/inspect`,{}),"inspectSaved"),list:r(e=>we.get(`/companies/${e}/email/inboxes`),"list"),setup:r((e,s)=>we.post(`/companies/${e}/email/inboxes`,s),"setup"),inspect:r((e,s)=>we.post(`/companies/${e}/email/inspect`,{apiKey:s}),"inspect"),control:r((e,s)=>we.post(`/email/inboxes/${e}/control`,{action:s}),"control"),reconnect:r((e,s,n)=>we.post(`/email/inboxes/${e}/reconnect`,{apiKey:s,receiveMode:n}),"reconnect"),resolve:r((e,s,n,a)=>we.post(`/companies/${e}/email/deliveries/${s}/resolve`,{outcome:n,providerMessageId:a}),"resolve"),thread:r((e,s)=>we.get(`/companies/${e}/email/tasks/${s}`),"thread"),send:r((e,s)=>we.post(`/companies/${e}/email/send`,s),"send")};function X3e(e,s){return te({queryKey:["email-thread",e,s],queryFn:r(()=>tc.thread(e,s),"queryFn"),enabled:!!(e&&s)&&!s.startsWith("chat:"),refetchInterval:r(n=>n.state.data===null?!1:3e3,"refetchInterval")})}r(X3e,"useEmailThread");var eAe=(0,m.createContext)(null);function sbt({companyId:e,issueId:s,children:n}){const a=X3e(e,s);return(0,t.jsx)(eAe.Provider,{value:a.data??null,children:n})}r(sbt,"EmailThreadProvider");function tAe(e){const s=(0,m.useContext)(eAe),n=s?.messages.find(a=>a.commentId===e);return n&&s?(0,t.jsx)(sAe,{message:n,publication:s.publications.find(a=>a.providerMessageId===n.providerMessageId),issueId:s.issueId}):null}r(tAe,"useEmailComment");function sAe({message:e,publication:s,issueId:n,contextNotice:a=!1}){const i=te({queryKey:["email-attachments",n],queryFn:r(()=>jt.listAttachments(n),"queryFn"),enabled:e.attachmentIds.length>0});return(0,t.jsxs)("article",{"aria-label":e.direction==="inbound"?"Email received":"Email sent",className:a?"task-context-notice space-y-3":"space-y-4 rounded-xl border border-border bg-card p-5",children:[(0,t.jsxs)("div",{className:"flex flex-wrap items-center justify-between gap-2",children:[(0,t.jsxs)("span",{className:"flex items-center gap-2 text-sm font-semibold",children:[(0,t.jsx)(VQ,{className:"size-4"}),e.direction==="inbound"?"Email received":"Email sent"]}),(0,t.jsx)("span",{className:"text-xs text-muted-foreground",children:new Date(e.timestamp).toLocaleString()})]}),(0,t.jsxs)("div",{className:"space-y-1",children:[(0,t.jsxs)("p",{className:"text-sm font-medium",children:[e.from,e.direction==="inbound"&&(0,t.jsx)("span",{className:"ml-2 rounded-md bg-muted px-2 py-1 text-xs text-muted-foreground",children:"External"})]}),(0,t.jsxs)("p",{className:"break-words text-xs text-muted-foreground",children:["To: ",e.to.join(", ")]}),!!e.cc?.length&&(0,t.jsxs)("p",{className:"break-words text-xs text-muted-foreground",children:["Cc: ",e.cc.join(", ")]}),(0,t.jsx)("p",{className:"text-sm font-semibold",children:e.subject})]}),(0,t.jsx)("div",{className:"whitespace-pre-wrap break-words text-sm",children:e.text||"(No text body)"}),!!e.attachmentIds.length&&(0,t.jsx)("div",{className:"flex flex-wrap gap-2",children:e.attachmentIds.map(o=>{const l=i.data?.find(c=>c.id===o);return(0,t.jsxs)("a",{href:`/api/attachments/${o}/content`,target:"_blank",rel:"noreferrer",className:"flex items-center gap-2 rounded-md border border-border px-3 py-2 text-xs",children:[(0,t.jsx)(kl,{className:"size-3.5"}),l?.originalFilename??"Open attachment"]},o)})}),(0,t.jsxs)("details",{className:"text-xs text-muted-foreground",children:[(0,t.jsx)("summary",{className:"cursor-pointer",children:"Email details"}),(0,t.jsxs)("div",{className:"space-y-2 pt-3",children:[!!e.bcc?.length&&(0,t.jsxs)("p",{children:["Bcc: ",e.bcc.join(", ")]}),(0,t.jsxs)("p",{className:"break-all",children:["Message ID: ",e.providerMessageId]}),e.fullText!==e.text&&(0,t.jsx)("div",{className:"whitespace-pre-wrap break-words",children:e.fullText})]})]}),s&&(0,t.jsxs)("p",{className:"border-t border-border pt-3 text-xs text-muted-foreground",children:[s.outcome==="delivered"?"Delivered":s.outcome==="failed"?"Delivery failed":s.outcome==="uncertain"?"Delivery uncertain":s.outcome==="queued"?"Queued":"Sent",s.error?` · ${s.error}`:""]}),i.error&&(0,t.jsx)("p",{role:"alert",className:"text-xs text-destructive",children:"Attachments could not be loaded."})]})}r(sAe,"EmailMessageCard");var rj=(0,m.createContext)(null);function hw({items:e,initialIndex:s,open:n,onOpenChange:a}){const[i,o]=(0,m.useState)(s),l=(0,m.useRef)(null),c=(0,m.useCallback)(g=>{l.current=g},[]);(0,m.useEffect)(()=>{n&&o(s)},[n,s]);const d=(0,m.useCallback)(()=>{o(g=>(g+1)%e.length)},[e.length]),u=(0,m.useCallback)(()=>{o(g=>(g-1+e.length)%e.length)},[e.length]);(0,m.useEffect)(()=>{i<e.length||o(0)},[i,e.length]),(0,m.useEffect)(()=>{if(!n)return;const g=r(v=>{v.key==="ArrowRight"?d():v.key==="ArrowLeft"?u():v.key==="Escape"&&a(!1)},"handler");return window.addEventListener("keydown",g),()=>window.removeEventListener("keydown",g)},[n,d,u,a]);const h=(0,m.useCallback)(g=>{const v=g.target;v.closest("button")||v.closest("a")||v===l.current||a(!1)},[a]);if(e.length===0)return null;const p=e[i];if(!p)return null;const f=og(p),x=fm(p.contentType,p.originalFilename);return(0,t.jsx)(iqe,{open:n,onOpenChange:a,children:(0,t.jsxs)(rqe,{children:[(0,t.jsx)(nqe,{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)(aqe,{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:LS(p),download:f,className:"text-white/50 hover:text-white transition-colors",title:"Download","aria-label":`Download ${f}`,onClick:r(g=>g.stopPropagation(),"onClick"),children:(0,t.jsx)(Ui,{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)(En,{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)(um,{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)(An,{className:"h-7 w-7"})})})]}),(0,t.jsx)("div",{className:"h-6 shrink-0"})]})]})})}r(hw,"ImageGalleryModal");function Uv(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:{}}r(Uv,"record$7");var nAe=(0,m.createContext)(null);function rAe(e){const s=(0,m.useContext)(nAe);return s&&e?.sourceRunId===s.runId&&e.sections.some(n=>n.rows.some(a=>a.type==="key_value"&&a.value===s.actionId))?s:null}r(rAe,"useWorkspaceBaseRefRecovery");function nbt({issue:e,agentMap:s,unavailableReason:n,onRepaired:a,children:i}){const o=e.activeRecoveryAction,l=o?.cause==="configuration_incomplete"&&typeof o.evidence.latestRunId=="string"?o.evidence.latestRunId:null,{data:c}=te({queryKey:["workspace-base-ref-recovery",e.companyId,e.id,l],queryFn:r(()=>na.get(l),"queryFn"),enabled:!!l,staleTime:1/0,retry:!1}),d=Uv(Uv(c?.resultJson).configurationIncomplete);let u=null;if(o&&l&&c?.companyId===e.companyId&&Uv(c.contextSnapshot).issueId===e.id&&d.reason==="workspace_base_ref_unresolved"&&typeof d.requestedRef=="string"){const h=e.assigneeAgentId?s.get(e.assigneeAgentId):void 0,p=d.requestedRef,f=e.project?.workspaces?.find(y=>y.id===e.projectWorkspaceId)??e.project?.primaryWorkspace;let x="The task’s repository";if(f?.repoUrl)try{const y=new URL(f.repoUrl);(y.protocol==="https:"||y.protocol==="http:")&&(x=`${y.hostname}${y.pathname.replace(/\.git$/,"")}`)}catch{}const g=Uv(Uv(e.executionWorkspaceSettings).workspaceStrategy).baseRef,v=o.status!=="active"||e.status!=="blocked"||e.assigneeAgentId!==o.returnOwnerAgentId||c.agentId!==e.assigneeAgentId||typeof g=="string"&&g.trim()&&g!==p?"This repair no longer matches the task. Refresh to review its current state.":n??(e.executionRunId||e.checkoutRunId?"Wait for the current run to finish.":null)??(h?.status==="paused"||h?.status==="terminated"?"The assigned agent is unavailable.":null)??(e.executionState?.status==="pending"?"Complete the pending review or approval before retrying.":null)??(e.blockedBy?.some(y=>y.status!=="done"&&y.status!=="cancelled")?"Resolve the task’s blockers before retrying.":null);u={actionId:o.id,runId:l,props:{requestedRef:p,repository:x,taskOverride:g===p,defaultBranch:typeof d.defaultBranch=="string"?d.defaultBranch:null,agentName:h?.name??"The assigned agent",unavailableReason:v,failureKind:typeof d.fetchError=="string"&&d.fetchError.includes(`couldn't find remote ref refs/heads/${p}`)?"missing_branch":"unresolved_ref",onRepair:r(async y=>{try{const k=await jt.resolveRecoveryAction(e.id,{actionId:o.id,outcome:"restored",sourceIssueStatus:"todo",workspaceBaseRef:{requestedRef:p,branch:y}});if(k.issue.status!=="todo"||k.issue.assigneeAgentId!==e.assigneeAgentId||Uv(Uv(k.issue.executionWorkspaceSettings).workspaceStrategy).baseRef!==y)throw new Error("The task changed while saving. Refresh to check its current state.")}finally{a()}},"onRepair")}}}return(0,t.jsx)(nAe.Provider,{value:u,children:i})}r(nbt,"WorkspaceBaseRefRecoveryProvider");var aAe={neutral:{container:"border-border bg-muted/35 dark:bg-muted/20",iconWrap:"bg-muted text-foreground/70",icon:e0,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:e0,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:xa,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:dN,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 rbt(e){try{return new Date(e).toLocaleString(void 0,{month:"short",day:"numeric",hour:"numeric",minute:"2-digit"})}catch{return e}}r(rbt,"formatTimestamp$1");function abt({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(abt,"MetadataRow$1");function YV({sections:e,tone:s="neutral"}){const n=aAe[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)(abt,{row:o,tone:n},l))})]},i))})}r(YV,"SystemNoticeMetadataSections");function ZV({tone:e="neutral",label:s,body:n,source:a,metadata:i,detailsDefaultOpen:o=!1,timestamp:l,className:c}){const d=aAe[e],u=d.icon,[h,p]=(0,m.useState)(o),f=(0,m.useId)(),x=!!(i&&i.length>0),g=s??{neutral:"System notice",info:"System notice",success:"System notice",warning:"System warning",danger:"System alert"}[e];return(0,t.jsxs)("section",{role:"status","aria-label":g,className:W("relative w-full overflow-hidden rounded-lg border text-sm shadow-(--shadow-extract-8)",d.container,c),children:[(0,t.jsxs)("header",{className:"flex items-start gap-3 px-3 py-2.5 sm:px-4",children:[(0,t.jsx)("span",{className:W("mt-0.5 flex h-7 w-7 shrink-0 items-center justify-center rounded-md",d.iconWrap),"aria-hidden":!0,children:(0,t.jsx)(u,{className:W("h-4 w-4",d.iconClass)})}),(0,t.jsxs)("div",{className:"min-w-0 flex-1",children:[(0,t.jsxs)("div",{className:"flex flex-wrap items-center gap-x-2 gap-y-0.5 text-(length:--text-micro) font-semibold uppercase tracking-(--tracking-eyebrow)",children:[(0,t.jsx)("span",{className:d.label,children:g}),a?(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)("span",{className:"text-muted-foreground/60","aria-hidden":!0,children:"·"}),a.href?(0,t.jsx)("a",{href:a.href,className:"rounded-sm font-medium normal-case tracking-normal text-muted-foreground underline-offset-2 hover:text-foreground hover:underline",children:a.label}):(0,t.jsx)("span",{className:"font-medium normal-case tracking-normal text-muted-foreground",children:a.label})]}):null,l?(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)("span",{className:"text-muted-foreground/60","aria-hidden":!0,children:"·"}),(0,t.jsx)("span",{className:"font-medium normal-case tracking-normal text-muted-foreground",children:rbt(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)(rn,{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)(YV,{sections:i,tone:e})}):null]})}r(ZV,"SystemNotice");function iAe({requestedRef:e,repository:s,defaultBranch:n,agentName:a,configuredBy:i,taskOverride:o=!0,failureKind:l="unresolved_ref",unavailableReason:c,onRepair:d}){const u=(0,m.useId)(),[h,p]=(0,m.useState)(!n),[f,x]=(0,m.useState)(n??""),[g,v]=(0,m.useState)(!1),[y,k]=(0,m.useState)(!1),[w,N]=(0,m.useState)(null),[S,C]=(0,m.useState)(null),_=(0,m.useRef)(!1),R=f.trim().length>0&&f.trim()!==e;async function I(T){const E=T.trim();if(!(!E||E===e||c||_.current||S)){if(!nBe(E)){N("Enter a valid branch name, such as master or release/next.");return}_.current=!0,k(!0),N(null);try{await d(E),C(E)}catch(L){N(L instanceof Error?L.message:"Refresh the task to check its current state, then try again.")}finally{_.current=!1,k(!1)}}}return r(I,"repair"),(0,t.jsxs)("section",{"aria-labelledby":`${u}-title`,className:"flex min-w-0 gap-3 rounded-lg border border-border bg-muted/20 p-4","data-testid":"workspace-base-ref-recovery",children:[S?(0,t.jsx)(cs,{"aria-hidden":!0,className:"mt-0.5 size-4 shrink-0 text-(--status-task-icon-done)"}):(0,t.jsx)(Es,{"aria-hidden":!0,className:"mt-0.5 size-4 shrink-0 text-(--status-task-icon-blocked)"}),(0,t.jsxs)("div",{className:"flex min-w-0 flex-1 flex-col gap-3",children:[(0,t.jsxs)("div",{className:"flex flex-col gap-1",role:"status","aria-live":"polite",children:[(0,t.jsx)("h2",{id:`${u}-title`,className:"break-words text-sm font-semibold",children:S?"Branch updated · retry requested":l==="missing_branch"?(0,t.jsxs)(t.Fragment,{children:["Branch ",(0,t.jsx)("code",{className:"font-mono",children:e})," was not found"]}):(0,t.jsxs)(t.Fragment,{children:["Couldn’t use branch ",(0,t.jsx)("code",{className:"font-mono",children:e})]})}),(0,t.jsx)("p",{className:"text-sm leading-relaxed text-muted-foreground",children:S?(0,t.jsxs)(t.Fragment,{children:["This task now starts from ",(0,t.jsx)("code",{className:"font-mono text-foreground",children:S}),". A retry has been requested for ",a,"."]}):(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)("span",{className:"break-all text-foreground",children:s}),l==="missing_branch"?(0,t.jsxs)(t.Fragment,{children:[" has no branch named ",(0,t.jsx)("code",{className:"font-mono text-foreground",children:e}),"."]}):" could not resolve the starting branch. Check the branch name and repository access."," ",a," hasn’t started."]})})]}),!S&&(0,t.jsxs)(t.Fragment,{children:[n&&!h&&(0,t.jsxs)("p",{className:"flex flex-wrap items-center gap-1.5 text-sm",children:[(0,t.jsx)(to,{"aria-hidden":!0,className:"size-4 text-muted-foreground"}),(0,t.jsx)("code",{className:"font-mono",children:n}),(0,t.jsx)("span",{className:"text-muted-foreground",children:"is the repository’s default branch."})]}),(0,t.jsx)("p",{className:"text-xs text-muted-foreground",children:"Changes only this task’s starting branch."}),c&&(0,t.jsx)("p",{id:`${u}-unavailable`,className:"text-sm text-muted-foreground",children:c}),w&&(0,t.jsxs)("p",{role:"alert",id:`${u}-error`,className:"text-sm text-destructive",children:["Couldn’t confirm the repair. ",w]}),h?(0,t.jsxs)("form",{className:"flex flex-col gap-3",onSubmit:r(T=>{T.preventDefault(),I(f)},"onSubmit"),children:[(0,t.jsxs)("div",{className:"flex flex-col gap-1.5",children:[(0,t.jsx)(Ds,{htmlFor:`${u}-branch`,children:"Starting branch"}),(0,t.jsx)(dt,{id:`${u}-branch`,autoFocus:!0,value:f,disabled:y||!!c,onChange:r(T=>x(T.target.value),"onChange"),placeholder:"Branch name",className:"font-mono","aria-describedby":w?`${u}-error`:void 0,autoComplete:"off",spellCheck:!1})]}),(0,t.jsxs)("div",{className:"flex flex-wrap items-center justify-between gap-2",children:[n?(0,t.jsx)($,{type:"button",variant:"ghost",size:"sm",disabled:y,onClick:r(()=>{p(!1),N(null)},"onClick"),children:"Cancel"}):(0,t.jsx)("span",{}),(0,t.jsxs)($,{type:"submit",size:"sm",disabled:y||!R||!!c,"aria-describedby":c?`${u}-unavailable`:void 0,children:[y&&(0,t.jsx)(st,{"aria-hidden":!0,className:"size-3.5 animate-spin motion-reduce:animate-none"}),y?"Saving & requesting retry…":"Save branch & retry"]})]})]}):(0,t.jsxs)("div",{className:"flex flex-wrap items-center justify-between gap-2",children:[(0,t.jsx)($,{type:"button",variant:"ghost",size:"sm",disabled:y||!!c,onClick:r(()=>p(!0),"onClick"),children:"Choose another branch"}),(0,t.jsxs)($,{type:"button",size:"sm",disabled:y||!!c||n===e,"aria-describedby":c?`${u}-unavailable`:void 0,onClick:r(()=>{I(n)},"onClick"),children:[y&&(0,t.jsx)(st,{"aria-hidden":!0,className:"size-3.5 animate-spin motion-reduce:animate-none"}),y?"Saving & requesting retry…":`Use ${n} & retry`]})]})]}),(0,t.jsxs)("div",{children:[(0,t.jsxs)($,{type:"button",variant:"ghost",size:"xs",className:"text-muted-foreground","aria-expanded":g,"aria-controls":`${u}-details`,onClick:r(()=>v(T=>!T),"onClick"),children:[g?"Hide details":"Why did this happen?",(0,t.jsx)(rn,{"aria-hidden":!0,className:W("size-3",g&&"rotate-180")})]}),g&&(0,t.jsx)("div",{id:`${u}-details`,className:"mt-2 rounded-md border border-border bg-background",children:(0,t.jsx)(YV,{tone:"neutral",sections:[{rows:[{kind:"text",label:"Setting",value:o?"Task-specific starting branch":"Workspace starting branch"},{kind:"code",label:"Requested branch",value:e},...i?[{kind:"text",label:"Set by",value:i}]:[],{kind:"text",label:"Why it stopped",value:o?"An explicit task branch overrides the repository default. Paperclip does not silently switch branches.":"The configured starting branch must resolve before the agent can start. This repair overrides it for this task."}]}]})})]})]})]})}r(iAe,"WorkspaceBaseRefRecoveryNotice");var JV=(0,m.createContext)(null);function ibt({value:e,children:s}){return(0,t.jsx)(JV.Provider,{value:e,children:s})}r(ibt,"DispositionRecoveryProvider");function obt(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(obt,"readDispositionRecoverySnapshot");function oAe(e){return obt(e,(0,m.useContext)(JV)?.issue.activeRecoveryAction)}r(oAe,"useDispositionRecoverySnapshot");function lbt(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(lbt,"dispositionRetryUnavailableReason");function cbt(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(cbt,"descriptionFor");function XV({snapshot:e,createdAt:s,defaultExpanded:n=!1}){const a=(0,m.useContext)(JV),[i,o]=(0,m.useState)(n),[l,c]=(0,m.useState)(!1),[d,u]=(0,m.useState)(!1),[h,p]=(0,m.useState)(null),f=(0,m.useRef)(!1),x=(0,m.useId)(),g=(0,m.useId)(),v=(0,m.useId)(),y=lbt(e,a),k=!!(a&&a.issue.activeRecoveryAction?.id!==e.actionId),w=e.assigneeAgentId&&a?.agentMap?.get(e.assigneeAgentId)?.name||"the assigned agent",N=d||k?cs:Es;async function S(){if(!(!a||y||f.current)){f.current=!0,c(!0),p(null);try{await a.onRetry(e.actionId),u(!0)}catch(C){p(C instanceof Error?C.message:"Refresh the task to check its current state, then try again.")}finally{f.current=!1,c(!1)}}}return r(S,"retry"),(0,t.jsxs)("section",{"aria-labelledby":g,className:"flex min-w-0 gap-2.5 py-3","data-testid":"disposition-recovery-notice",children:[(0,t.jsx)(N,{"aria-hidden":"true",className:W("mt-0.5 size-4 shrink-0",d||k?"text-muted-foreground":"text-(--status-task-icon-todo)")}),(0,t.jsxs)("div",{className:"flex min-w-0 flex-1 flex-col gap-2",children:[(0,t.jsxs)("div",{className:"flex flex-col gap-1",role:"status","aria-live":"polite",children:[(0,t.jsx)("h2",{id:g,className:"break-words text-sm font-medium text-foreground",children:d?"Retry requested":k?"Agent needed attention":"Agent needs attention"}),(0,t.jsx)("p",{className:"text-sm leading-relaxed text-muted-foreground",children:d?`The task was returned to To do for ${w}.`:cbt(e)})]}),y&&!d?(0,t.jsxs)("p",{id:v,className:"text-xs leading-relaxed text-muted-foreground",children:[!k&&(0,t.jsx)("span",{className:"font-medium text-foreground",children:"Retry unavailable. "}),y]}):null,h?(0,t.jsxs)("p",{role:"alert",className:"text-sm text-destructive",children:["Couldn’t confirm the retry. ",h]}):null,(0,t.jsxs)("div",{className:"flex flex-wrap items-center gap-2",children:[!d&&!k?(0,t.jsxs)($,{size:"xs",variant:"outline",disabled:l||!!y,"aria-describedby":y?v:void 0,onClick:r(()=>{S()},"onClick"),children:[l?(0,t.jsx)(st,{"aria-hidden":"true",className:"size-3 animate-spin motion-reduce:animate-none"}):(0,t.jsx)(_i,{"aria-hidden":"true",className:"size-3"}),l?"Requesting retry…":"Retry agent"]}):null,(0,t.jsxs)($,{size:"xs",variant:"ghost",className:"text-muted-foreground","aria-expanded":i,"aria-controls":x,onClick:r(()=>o(C=>!C),"onClick"),children:[i?"Hide details":"View details",(0,t.jsx)(rn,{"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:Hi(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(XV,"DispositionRecoveryNotice");var dbt="System update",ubt=80;function mbt(e){const s=e.match(/Latest retry failure: `([^`]+)`/);return s?s[1]:null}r(mbt,"retryFailureCode");function hbt(e){const s=e.match(/Recovery owner: \[([^\]]+)\]\(/)?.[1]?.trim();return s&&s.length>0?s:null}r(hbt,"recoveryOwnerName");function pbt(e){const s=e.split(`
382
+ `)}`:void 0}r($ft,"sanitizeComponentStack");function l3e(){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(l3e,"readBrowserErrorState");function Oft(e){const s=$ft(e.componentStack);return{tags:{react_error_boundary:e.boundary},contexts:{react:s?{componentStack:s}:{},browser_state:l3e()}}}r(Oft,"buildBrowserErrorContext");var uie=Promise.resolve();function QV(e){const s=uie.then(e);return uie=s.catch(()=>{}),s}r(QV,"enqueue");var RN=null;function Bft(e,s){return QV(async()=>{if(!RN)try{const n=await fd(()=>import("./prod-COP_vZWu.js"),__vite__mapDeps([4,5]));n.init(zft(e,s)),RN=n}catch{}})}r(Bft,"initBrowserErrorMonitoring");function Fft(){return QV(async()=>{const e=RN;if(RN=null,!e)return;const s=e.getClient();try{e.getCurrentScope().setClient(void 0)}catch{}try{await s?.close(2e3)}catch{}})}r(Fft,"teardownBrowserErrorMonitoring");function WV(e,s){let n;try{s&&(n=Oft(s))}catch{}QV(async()=>{try{n?RN?.captureException(e,n):RN?.captureException(e)}catch{}})}r(WV,"captureBrowserException");function zft(e,s){return{dsn:e,environment:s??void 0,release:"826d324372d22cac806213e42aa3aec83ca1d7d7",tracesSampleRate:0,sendDefaultPii:!1,beforeSend:r((n,a)=>{try{if(n.contexts={...n.contexts,browser_state:n.contexts?.browser_state??l3e()},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(zft,"buildBrowserSentryInitOptions");var qft=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){WV(e,{boundary:"route",componentStack:s.componentStack})}componentDidUpdate(e){this.state.error&&e.resetKey!==this.props.resetKey&&this.setState({error:null})}render(){const{error:e}=this.state;return e?(0,t.jsxs)("div",{className:"mx-auto max-w-2xl space-y-4 px-4 py-10",children:[(0,t.jsxs)("div",{children:[(0,t.jsx)("h1",{className:"text-lg font-semibold",children:"This page hit an error"}),(0,t.jsx)("p",{className:"mt-1 text-sm text-muted-foreground",children:"Something went wrong while rendering this page. You can go back and try again, or reload."})]}),(0,t.jsx)("pre",{className:"overflow-auto rounded-md border border-destructive/30 bg-destructive/10 px-3 py-2 text-xs text-destructive whitespace-pre-wrap",children:e.message}),(0,t.jsxs)("div",{className:"flex items-center gap-2",children:[(0,t.jsx)($,{variant:"outline",size:"sm",onClick:this.props.onReset,children:"Go back"}),(0,t.jsx)($,{size:"sm",onClick:r(()=>window.location.reload(),"onClick"),children:"Reload page"})]})]}):this.props.children}};function c3e({children:e}){const s=ua(),n=Yn(),a=`${s.pathname}${s.search}`;return(0,t.jsx)(qft,{resetKey:a,onReset:r(()=>n(-1),"onReset"),children:e})}r(c3e,"RouteErrorBoundary");var mie={bot:io,cpu:qm,brain:$x,zap:C6,rocket:vFe,code:Hbe,terminal:pf,shield:v3,eye:Jd,search:Jr,wrench:hf,hammer:b3,lightbulb:g3,sparkles:W0,star:Q0,heart:jC,flame:RFe,bug:Yy,cog:Kbe,database:f3,globe:gm,lock:Ao,mail:VQ,"message-square":D0,"file-code":ql,"git-branch":to,package:Xh,puzzle:Ox,target:K0,wand:$W,atom:iFe,"circuit-board":JKe,radar:hFe,swords:PQe,telescope:aFe,microscope:bQe,crown:A8,gem:Zbe,hexagon:Yd,pentagon:wQe,fingerprint:kF},Uft="bot";function Kft(e){return e&&V$e.includes(e)?mie[e]:mie[Uft]}r(Kft,"getAgentIcon");function UE({icon:e,className:s}){const n=Kft(e);return(0,t.jsx)(n,{className:s})}r(UE,"AgentIcon");function d3e({open:e,onOpenChange:s,...n}){return(0,t.jsx)(qs,{open:e,onOpenChange:s,children:(0,t.jsxs)(Ws,{"aria-describedby":void 0,className:"gap-0 overflow-hidden p-0 sm:max-w-md",children:[(0,t.jsxs)("div",{className:"px-4 pt-4 pb-3",children:[(0,t.jsx)(Qs,{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)(Qft,{...n,onComplete:r(()=>s(!1),"onComplete")},String(e))]})})}r(d3e,"AgentChatPicker");function Qft({agents:e,onSelect:s,onComplete:n,loading:a,error:i,onRetry:o,existingChatAgentIds:l,renderAgentIcon:c}){const d=(0,m.useRef)(!1),u=(0,m.useRef)(null);(0,m.useEffect)(()=>(d.current=!0,()=>{d.current=!1,u.current?.abort()}),[]);const[h,p]=(0,m.useState)(""),[f,x]=(0,m.useState)(null),[g,v]=(0,m.useState)(null);async function y(k){if(f)return;x(k.id),v(null);const w=new AbortController;u.current=w;try{await s(k,w.signal),d.current&&n()}catch(N){v(N instanceof Error?N.message:"Couldn’t open chat. Try again.")}finally{x(null)}}return r(y,"selectAgent"),(0,t.jsxs)(y3,{children:[(0,t.jsx)(aS,{"aria-label":"Search agents by name or role",placeholder:"Search by name or role…",value:h,onValueChange:p}),g&&(0,t.jsx)("p",{role:"alert",className:"px-4 py-3 text-sm text-destructive",children:g}),f&&(0,t.jsx)("p",{role:"status",className:"sr-only",children:"Opening conversation…"}),i?(0,t.jsxs)("div",{role:"alert",className:"flex flex-col items-start gap-2 p-4 text-sm",children:[(0,t.jsx)("p",{children:"Couldn’t load agents. Try again."}),o&&(0,t.jsx)($,{variant:"outline",size:"sm",onClick:o,children:"Retry"})]}):a?(0,t.jsx)("p",{role:"status",className:"p-4 text-sm text-muted-foreground",children:"Loading agents…"}):(0,t.jsxs)(iS,{children:[(0,t.jsx)(oS,{children:(0,t.jsxs)("div",{className:"flex flex-col items-center gap-2 px-4",children:[(0,t.jsx)("span",{children:e.length?`No agents match “${h}”`:"No agents yet."}),e.length?(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)("span",{className:"text-xs text-muted-foreground",children:"Try another name or role."}),(0,t.jsx)($,{variant:"ghost",size:"sm",onClick:r(()=>p(""),"onClick"),children:"Clear search"})]}):(0,t.jsx)("span",{className:"text-xs text-muted-foreground",children:"Create an agent from the Agents page to start chatting."})]})}),(0,t.jsx)(Hu,{children:e.map(k=>(0,t.jsxs)(Xo,{value:k.id,keywords:[k.name,k.title??"",k.role],onSelect:r(()=>{y(k)},"onSelect"),disabled:f!==null,className:"gap-3 px-3 py-3",children:[c?c(k):(0,t.jsx)(UE,{icon:k.icon,className:"size-4 shrink-0"}),(0,t.jsxs)("span",{className:"flex min-w-0 flex-1 flex-col gap-0.5",children:[(0,t.jsx)("span",{className:"truncate font-medium",children:k.name}),(0,t.jsx)("span",{className:"truncate text-xs text-muted-foreground",children:k.title??k.role})]}),l&&(0,t.jsx)("span",{className:"shrink-0 text-xs text-muted-foreground",children:l.includes(k.id)?"Open chat":"New chat"}),k.status==="paused"&&(0,t.jsx)("span",{className:"text-xs text-(--status-agent-paused)",children:"Paused"}),k.status==="terminated"&&(0,t.jsx)("span",{className:"text-xs text-muted-foreground",children:"Terminated"}),k.status==="pending_approval"&&(0,t.jsx)("span",{className:"text-xs text-muted-foreground",children:"Awaiting approval"})]},k.id))})]})]})}r(Qft,"AgentChatPickerResults");function NR({agents:e,existingChatAgentIds:s,availableAgents:n=e,activeId:a,previews:i={},loading:o=!1,error:l,onRetry:c,initialSearch:d="",onSelect:u,onBrowse:h,onAddChat:p,historyLoading:f,historyError:x,onRetryHistory:g}){const v=Yn(),[y,k]=(0,m.useState)(!1),[w,N]=(0,m.useState)(d),S=(0,m.useRef)(null),C=(0,m.useId)(),_=w.trim().toLocaleLowerCase(),R=e.filter(T=>`${T.name} ${T.title??""} ${T.role}`.toLocaleLowerCase().includes(_));function I(){N(""),S.current?.focus()}return r(I,"focusSearch"),(0,t.jsxs)("aside",{"aria-labelledby":C,className:"flex h-full min-h-0 flex-col border-r border-border bg-background",children:[(0,t.jsxs)("div",{className:"flex shrink-0 flex-col gap-4 px-3 pb-4 pt-4",children:[(0,t.jsxs)("div",{className:"flex items-center justify-between gap-2",children:[(0,t.jsx)("h2",{id:C,className:"text-sm font-semibold",children:"Chat"}),(0,t.jsx)($,{variant:"outline",size:"icon-sm","aria-label":"Add chat",title:"Add chat",onClick:r(()=>k(!0),"onClick"),children:(0,t.jsx)(gn,{className:"size-4"})})]}),(0,t.jsxs)("div",{className:"relative",children:[(0,t.jsx)(Jr,{"aria-hidden":"true",className:"pointer-events-none absolute left-3 top-1/2 size-3.5 -translate-y-1/2 text-muted-foreground"}),(0,t.jsx)(dt,{ref:S,"aria-label":"Search agents",placeholder:"Find an agent",value:w,onChange:r(T=>N(T.target.value),"onChange"),onKeyDown:r(T=>{T.key==="Escape"&&(T.stopPropagation(),N(""))},"onKeyDown"),className:"h-8 pl-8 pr-8 text-xs md:text-xs"}),w&&(0,t.jsx)($,{variant:"ghost",size:"icon-xs","aria-label":"Clear search",className:"absolute right-1 top-1/2 -translate-y-1/2",onClick:I,children:(0,t.jsx)(En,{className:"size-3"})})]})]}),(0,t.jsxs)("div",{className:"flex min-h-0 flex-1 flex-col gap-2 overflow-y-auto px-3 pb-3 scrollbar-auto-hide",children:[(0,t.jsx)("p",{className:"px-2 text-(length:--text-micro) font-medium uppercase tracking-widest text-muted-foreground",children:_?"Search results":"Teammates"}),(0,t.jsx)("span",{role:"status",className:"sr-only",children:o?"Loading agents":`${R.length} ${R.length===1?"agent":"agents"}`}),f&&(0,t.jsx)("p",{role:"status",className:"px-2 text-xs text-muted-foreground",children:"Loading chat history…"}),x&&(0,t.jsxs)("div",{role:"alert",className:"flex flex-col items-start gap-2 px-2 py-3",children:[(0,t.jsx)("p",{className:"text-xs text-muted-foreground",children:"Some chat history couldn’t load."}),(0,t.jsx)($,{variant:"outline",size:"sm",onClick:g,children:"Retry chat history"})]}),l?(0,t.jsxs)("div",{role:"alert",className:"flex flex-col items-start gap-2 px-2 py-6",children:[(0,t.jsx)("p",{className:"text-sm",children:"Couldn’t load your chats."}),(0,t.jsx)($,{variant:"outline",size:"sm",onClick:c,children:"Try again"})]}):o?(0,t.jsx)("div",{"aria-hidden":"true",className:"flex flex-col gap-1",children:[0,1,2,3].map(T=>(0,t.jsxs)("div",{className:"flex items-center gap-3 rounded-md px-2 py-3 motion-safe:animate-pulse",children:[(0,t.jsx)("div",{className:"size-8 shrink-0 rounded-lg bg-muted"}),(0,t.jsxs)("div",{className:"flex flex-1 flex-col gap-2",children:[(0,t.jsx)("div",{className:"h-3 w-2/3 rounded-sm bg-muted"}),(0,t.jsx)("div",{className:"h-2 w-full rounded-sm bg-muted"})]})]},T))}):R.length?(0,t.jsx)("nav",{"aria-label":"Agent conversations",className:"flex flex-col gap-1",children:R.map(T=>(0,t.jsxs)(Ke,{to:`/chats/${encodeURIComponent(T.status==="terminated"?T.id:Vl(T))}`,"aria-current":a===T.id?"page":void 0,title:`${T.name}${T.title?` · ${T.title}`:""}`,onClick:r(E=>{u&&(E.preventDefault(),u(T))},"onClick"),className:W("flex min-w-0 items-center gap-3 rounded-md px-2 py-3 text-left transition-colors hover:bg-accent/60 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-ring",a===T.id&&"bg-accent text-accent-foreground"),children:[(0,t.jsx)(lr,{agent:T,size:32}),(0,t.jsxs)("span",{className:"flex min-w-0 flex-1 flex-col gap-0.5",children:[(0,t.jsx)("span",{className:"truncate text-sm font-medium",children:T.name}),(0,t.jsx)("span",{className:"truncate text-xs text-muted-foreground",children:T.status==="terminated"?"Terminated":T.status==="paused"?"Paused":i[T.id]??T.title??"Start a conversation"})]})]},T.id))}):!e.length&&(f||x)?null:(0,t.jsxs)("div",{className:"flex flex-col items-start gap-2 px-2 py-6",children:[(0,t.jsx)("p",{className:"text-sm font-medium",children:e.length?"No agents found":"No chats yet"}),(0,t.jsx)("p",{className:"text-xs leading-relaxed text-muted-foreground",children:e.length?"Try another name or role.":"Choose an agent to start a conversation."}),!e.length&&(0,t.jsx)($,{variant:"outline",size:"sm",onClick:r(()=>k(!0),"onClick"),children:"Choose an agent"}),e.length>0&&(0,t.jsx)($,{variant:"outline",size:"sm",onClick:I,children:"Clear search"})]})]}),(0,t.jsx)("div",{className:"shrink-0 px-3 py-4",children:(0,t.jsx)($,{variant:"ghost",size:"sm",className:"w-full justify-start gap-2 px-2 text-muted-foreground",asChild:!h,onClick:h,children:h?(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)(Ho,{className:"size-4"}),"Browse all agents"]}):(0,t.jsxs)(Ke,{to:"/agents/all",children:[(0,t.jsx)(Ho,{className:"size-4"}),"Browse all agents"]})})}),(0,t.jsx)(d3e,{agents:n,open:y,onOpenChange:k,existingChatAgentIds:s??e.map(T=>T.id),loading:o,error:l,onRetry:c,renderAgentIcon:r(T=>(0,t.jsx)(lr,{agent:T,size:32}),"renderAgentIcon"),onSelect:r(async(T,E)=>{p?await p(T,E):u?await u(T,E):v(`/chats/${encodeURIComponent(Vl(T))}`),E?.aborted||N("")},"onSelect")})]})}r(NR,"AgentConversationSidebar");var KE={list:r(e=>we.get(`/companies/${e}/chats`),"list"),get:r((e,s)=>we.get(`/companies/${e}/chats/${encodeURIComponent(s)}`),"get"),ensure:r((e,s)=>we.post(`/companies/${e}/chats/${encodeURIComponent(s)}`,{}),"ensure")};function u3e(){const{selectedCompanyId:e}=ps(),{enabled:s,loaded:n}=aw(),a=te({queryKey:M.auth.session,queryFn:r(()=>Ma.getSession(),"queryFn")}),i=a.data?.user?.id??a.data?.session?.userId??null;return{companyId:e,userId:i,enabled:s,loaded:n,agents:te({queryKey:M.agents.list(e),queryFn:r(()=>_t.list(e),"queryFn"),enabled:s&&!!e}),chats:te({queryKey:M.agentChats.list(e,i),queryFn:r(()=>KE.list(e),"queryFn"),enabled:s&&!!e&&a.isSuccess}),session:a}}r(u3e,"useAgentChatNavigation");function m3e(e,s){const n=kt(),a=Yn(),{isMobile:i,setSidebarOpen:o}=Wa(),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 KE.ensure(e,c.id);n.setQueryData(M.agentChats.detail(e,s,c.id),h),n.setQueryData(M.issues.detail(h.id),h),n.setQueryData(M.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(Vl(c))}`),i&&o(!1))},[n,e,s,a,i,o])}r(m3e,"useOpenAgentChat");function Wft(){const{companyId:e,userId:s,agents:n,chats:a,session:i}=u3e(),o=m3e(e,s),l=Yn(),c=Tf(e),{isMobile:d,setSidebarOpen:u}=Wa(),{pathname:h}=ua(),p=h.split("/chats/")[1]?.split("/")[0],f=n.data??[],x=n.isSuccess?[...new Set((a.data??[]).flatMap(C=>C.conversationAgentId&&!f.some(_=>_.id===C.conversationAgentId)?[C.conversationAgentId]:[]))]:[],g=cm({queries:x.map(C=>({queryKey:M.agents.detail(C),queryFn:r(()=>_t.get(C,e),"queryFn")}))}),v=new Map(f.map(C=>[C.id,C]));for(const C of g)C.data&&v.set(C.data.id,C.data);const y=[...v.values()].find(C=>C.id===p||C.status!=="terminated"&&encodeURIComponent(Vl(C))===p),k=(a.data??[]).flatMap(C=>{const _=C.conversationAgentId?v.get(C.conversationAgentId):void 0;return _?[_]:[]});y&&!k.some(C=>C.id===y.id)&&k.unshift(y);const w=new Set(k.map(C=>C.id)),N=f.filter(C=>!w.has(C.id)&&C.status!=="terminated"&&(!c.isSuccess||eg(c.data,"agent",C.id)!=="left")).sort((C,_)=>C.name.localeCompare(_.name,void 0,{sensitivity:"base"})),S=Object.fromEntries((a.data??[]).filter(C=>C.conversationState==="active").map(C=>[C.conversationAgentId,"Working…"]));return(0,t.jsx)(NR,{agents:[...k,...N],availableAgents:f,existingChatAgentIds:k.map(C=>C.id),activeId:y?.id,previews:S,loading:n.isPending||a.isPending||i.isPending,error:n.error??a.error??i.error,onRetry:r(()=>{n.refetch(),a.refetch(),i.refetch()},"onRetry"),historyLoading:g.some(C=>C.isPending),historyError:g.find(C=>C.error)?.error,onRetryHistory:r(()=>{g.filter(C=>C.isError).forEach(C=>{C.refetch()})},"onRetryHistory"),onAddChat:o,onSelect:r(C=>{l(`/chats/${encodeURIComponent(C.status==="terminated"?C.id:Vl(C))}`),d&&u(!1)},"onSelect")},`${e}:${s}`)}r(Wft,"AgentConversationsSidebar");var WI=240,iq=208,oq=420,hie=16;function QE(e){return Math.min(oq,Math.max(iq,e))}r(QE,"clampSidebarWidth$1");function pie(e){if(typeof window>"u")return WI;try{const s=window.localStorage.getItem(e);if(!s)return WI;const n=Number.parseInt(s,10);return Number.isFinite(n)?QE(n):WI}catch{return WI}}r(pie,"readStoredSidebarWidth$1");function fie(e,s){if(!(typeof window>"u"))try{window.localStorage.setItem(e,String(QE(s)))}catch{}}r(fie,"writeStoredSidebarWidth$1");function Hft({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)(()=>pie(o)),[x,g]=(0,m.useState)(!1),v=(0,m.useRef)(p),y=(0,m.useRef)(null);(0,m.useEffect)(()=>{const P=pie(o);v.current=P,f(P)},[o]);const k=s?p:0,w=s?n?64:k:0,N=s?n&&!a?64:k:0,S=N>w,C=i&&s&&!n,_=(0,m.useMemo)(()=>({width:`${w}px`}),[w]),R=(0,m.useMemo)(()=>({width:`${N}px`}),[N]),I=(0,m.useCallback)(P=>{const Q=QE(P);v.current=Q,f(Q),fie(o,Q)},[o]),T=(0,m.useCallback)(P=>{C&&(P.preventDefault(),P.currentTarget.setPointerCapture(P.pointerId),y.current={startX:P.clientX,startWidth:v.current},g(!0))},[C]),E=(0,m.useCallback)(P=>{if(!y.current)return;const Q=QE(y.current.startWidth+P.clientX-y.current.startX);v.current=Q,f(Q)},[]),L=(0,m.useCallback)(()=>{y.current&&(y.current=null,g(!1),fie(o,v.current))},[o]),O=(0,m.useCallback)(P=>{C&&(P.key==="ArrowLeft"?(P.preventDefault(),I(p-hie)):P.key==="ArrowRight"?(P.preventDefault(),I(p+hie)):P.key==="Home"?(P.preventDefault(),I(iq)):P.key==="End"&&(P.preventDefault(),I(oq)))},[C,I,p]);return(0,t.jsxs)("div",{className:W("relative h-full shrink-0",l),style:_,children:[(0,t.jsx)("div",{className:W("absolute inset-y-0 left-0 flex flex-col overflow-hidden",S?"z-30 border-r border-border bg-background shadow-lg":"z-0"),style:R,"data-sidebar-overlay":S?"":void 0,onMouseEnter:c,onMouseLeave:d,onFocusCapture:u,onBlurCapture:h,children:e}),C?(0,t.jsx)("div",{role:"separator","aria-label":"Resize sidebar","aria-orientation":"vertical","aria-valuemin":iq,"aria-valuemax":oq,"aria-valuenow":p,tabIndex:0,"data-dragging":x?"":void 0,className:"group absolute inset-y-0 z-20 cursor-col-resize touch-none outline-none",style:{right:-4,width:8},onPointerDown:T,onPointerMove:E,onPointerUp:L,onPointerCancel:L,onLostPointerCapture:L,onKeyDown:O,children:(0,t.jsx)("div",{className: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(Hft,"SidebarShell$1");function HI({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)(Bke,{children:e})})}r(HI,"SecondarySidebar$1");var h3e={listStacks:r(()=>we.get("/cloud/stacks"),"listStacks")};function PM(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(PM,"cloudAppUrl");function p3e(e){return PM(e,"/stacks/new")}r(p3e,"cloudStackCreateUrl");function f3e(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(f3e,"tenantSignInReturnPath");function Vft(e,s,n){const a=s?.trim();if(!a)return null;const i=PM(e,`/v1/stacks/${encodeURIComponent(a)}/entry-redirect`);if(!i)return null;const o=new URL(i);return o.searchParams.set("returnTo",f3e(n)),o.toString()}r(Vft,"cloudStackEntryUrl");function x3e(e,s){const n=s?.trim();return n?PM(e,`/workspaces/${encodeURIComponent(n)}/settings?section=people`):null}r(x3e,"cloudStackInviteUrl");function Gft(e){return PM(e,"/orgs?manage=1")}r(Gft,"cloudPortfolioManageUrl");function g3e(){const e=ed(),s=!!e,n=te({queryKey:M.cloud.stacks,queryFn:r(()=>h3e.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:x3e(e.cloudBaseUrl,a.stackSlug)}r(g3e,"useCloudInviteUrl");function Yft(e,s){if(!s)return!1;if(s.source==="local_implicit"||s.isInstanceAdmin)return!0;if(!e)return!1;const n=s.memberships?.find(a=>a.companyId===e&&a.status==="active");return n?.membershipRole==="owner"||n?.membershipRole==="admin"||n?.membershipRole==="operator"||n?.membershipRole==="member"}r(Yft,"canInviteCompanyMembers");function b3e(e=!0){const s=Abe(),n=te({queryKey:M.access.currentBoardAccess,queryFn:r(()=>ir.getCurrentBoardAccess(),"queryFn"),enabled:e,retry:!1,staleTime:3e4});return e&&Yft(s?.selectedCompanyId,n.data)}r(b3e,"useCanInviteCompanyMembers");function v3e(e){const s=window.location.hostname.endsWith(".staging.paperclip.app"),{data:n,isError:a}=te({queryKey:M.stagingCommit,queryFn:r(()=>Iu.get(),"queryFn"),enabled:s&&e,staleTime:0,retry:!1});return s&&!a?n?.commit??null:null}r(v3e,"useStagingCommit");function Zft(e){return e?.trim().toLowerCase().replace(/['"]/g,"").replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")||null}r(Zft,"slugifyUserPart");function y3e(e){const s=[e?.id,e?.name,e?.email?.split("@")[0],e?.email];for(const n of s){const a=Zft(n);if(a)return`/u/${a}`}return"/u/me"}r(y3e,"userProfilePath");var Jft="Toggle the app appearance.";function Lk({className:e,variant:s="icon",onAfterToggle:n}){const{theme:a,toggleTheme:i}=qqe(),o=a==="dark",l=o?"Switch to light mode":"Switch to dark mode",c=o?K1e:Uwe;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:Jft})]})]}):(0,t.jsx)($,{type:"button",variant:"ghost",size:"icon-sm",onClick:d,"aria-label":l,title:l,className:W("text-muted-foreground",e),children:(0,t.jsx)(c,{})})}r(Lk,"ThemeToggle");var I5=null,j3e=!1,lq=!1,cq=new Set;function WE(){for(const e of cq)e()}r(WE,"emit");function Xft(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(Xft,"isIosSafariLike");function ext(e=window){const s=r(a=>{a.preventDefault(),I5=a,WE()},"onPrompt"),n=r(()=>{I5=null,j3e=!0,WE()},"onInstalled");return e.addEventListener("beforeinstallprompt",s),e.addEventListener("appinstalled",n),()=>{e.removeEventListener("beforeinstallprompt",s),e.removeEventListener("appinstalled",n)}}r(ext,"captureInstallPrompt");function txt(){return j3e||rq()?"installed":I5?"prompt":Xft()?"ios-manual":"unavailable"}r(txt,"installAvailability");async function sxt(){const e=I5;if(!e)return"unavailable";I5=null,WE(),await e.prompt();const{outcome:s}=await e.userChoice;return s}r(sxt,"promptInstall");function dq(e){lq!==e&&(lq=e,WE())}r(dq,"setIosInstallHelpOpen");function nxt(){return lq}r(nxt,"iosInstallHelpOpen");function rxt(){return(0,m.useSyncExternalStore)(w3e,nxt,()=>!1)}r(rxt,"useIosInstallHelpOpen");function w3e(e){return cq.add(e),()=>{cq.delete(e)}}r(w3e,"subscribe$1");function axt(){return(0,m.useSyncExternalStore)(w3e,txt,()=>"unavailable")}r(axt,"useInstallAvailability");var xie="Install app",ixt="Add Paperclip to your home screen or dock.";function k3e({variant:e,onAfterAction:s}){const n=axt();if(n==="installed"||n==="unavailable")return null;const a=r(()=>{n==="ios-manual"?dq(!0):sxt(),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)(Ui,{className:"size-4"})}),(0,t.jsx)("span",{className:"min-w-0 flex-1 truncate",children:xie})]}):(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)(Ui,{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:xie}),(0,t.jsx)("span",{className:"block text-xs text-muted-foreground",children:ixt})]})]})}r(k3e,"InstallAppMenuAction");function oxt(){const e=rxt();return(0,t.jsx)(qs,{open:e,onOpenChange:dq,children:(0,t.jsxs)(Ws,{children:[(0,t.jsxs)(ln,{children:[(0,t.jsx)(Qs,{children:"Install Paperclip"}),(0,t.jsx)(mn,{children:"Add Paperclip to your Home Screen from Safari."})]}),(0,t.jsxs)("ol",{className:"space-y-3 text-sm text-foreground",children:[(0,t.jsxs)(_D,{index:1,icon:(0,t.jsx)(RQe,{className:"size-4"}),children:["Tap ",(0,t.jsx)("strong",{children:"Share"})," in the Safari toolbar."]}),(0,t.jsxs)(_D,{index:2,icon:(0,t.jsx)(MQe,{className:"size-4"}),children:["Choose ",(0,t.jsx)("strong",{children:"Add to Home Screen"}),"."]}),(0,t.jsxs)(_D,{index:3,children:["Keep ",(0,t.jsx)("strong",{children:"Open as Web App"})," on, then tap ",(0,t.jsx)("strong",{children:"Add"}),"."]})]}),(0,t.jsx)(cr,{children:(0,t.jsx)($,{type:"button",onClick:r(()=>dq(!1),"onClick"),children:"Done"})})]})})}r(oxt,"IosInstallHelpDialog");function _D({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(_D,"InstallStep");function lxt(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(lxt,"formatTimestamp$2");function cxt(e){return!!e&&!Number.isNaN(new Date(e).getTime())}r(cxt,"isValidTimestamp");function dxt(e){return e?.devServer?.lastRestartAt??e?.serverInfo?.processStartedAt??null}r(dxt,"restartTimestamp");function uxt(e){const s=e?.serverInfo?.git;return s?.available?`${s.shortSha} · ${s.subject}`:"Commit unavailable"}r(uxt,"commitLabel");function mxt(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(mxt,"localChangesLabel");function AD({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(AD,"ServerInfoRow");function N3e(){const e=te({queryKey:M.instance.experimentalSettings,queryFn:r(()=>jr.getExperimental(),"queryFn")}).data?.enableServerInfoDebugView===!0,s=te({queryKey:M.health,queryFn:r(()=>Iu.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=dxt(n),l=cxt(o),c=i?"Health unavailable":a?"Loading...":lxt(o),d=i?"Health unavailable":a?"Loading...":uxt(n),u=i?"Health unavailable":a?"Loading...":mxt(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)(AD,{icon:Nu,label:"Last restarted",value:c,dateTime:!i&&!a&&l?o:null}),(0,t.jsx)(AD,{icon:SW,label:"Running commit",value:d}),(0,t.jsx)(AD,{icon:aQe,label:"Checkout state",value:u})]})}r(N3e,"SidebarServerInfo");var hxt="/company/settings/members?tab=invites",pxt="https://docs.paperclip.ing/",fxt="https://paperclip.ing/feedback";function xxt(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(xxt,"deriveInitials$2");function ID({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(ID,"MenuAction$1");function gie({deploymentMode:e,open:s,onOpenChange:n,forceExpanded:a=!1}){const o=!!ed(),{hidden:l,loaded:c}=Au(),d=g3e(),u=b3e(!o),h=o?d:u?hxt:null,p=c&&h!==null&&!Gx(l,"company.members")&&!Gx(l,"company.invites"),[f,x]=(0,m.useState)(!1),{isMobile:g,setSidebarOpen:v,collapsed:y,peeking:k}=Wa(),w=y&&!k&&!a,N=s??f,S=v3e(N),C=n??x,{data:_}=te({queryKey:M.auth.session,queryFn:r(()=>Ma.getSession(),"queryFn"),retry:!1}),R=SS({onSignedOut:O}),I=_?.user.name?.trim()||"Board",T=_?.user.email?.trim()||(e==="authenticated"?"Signed in":"Local workspace board"),E=xxt(I),L=y3e(_?.user);function O(){C(!1),g&&v(!1)}r(O,"closeNavigationChrome");function P(){R.mutate()}return r(P,"handleSignOut"),(0,t.jsx)("div",{className:"bg-border/50 px-3 py-2 dark:bg-muted",children:(0,t.jsxs)("div",{className:W("flex items-center gap-0.5",!w&&"px-2"),children:[(0,t.jsxs)(dr,{open:N,onOpenChange:C,children:[(0,t.jsx)(wr,{asChild:!0,children:(0,t.jsxs)("button",{type:"button",className:W("flex min-w-0 items-center gap-2.5 rounded-lg text-left text-(length:--text-compact) font-medium text-foreground/80 transition-colors hover:bg-sidebar-accent hover:text-sidebar-accent-foreground",w?"w-full px-3 py-2":"flex-1 px-2 py-1.5"),"aria-label":"Open account menu",children:[(0,t.jsxs)(ko,{size:"sm",children:[_?.user.image?(0,t.jsx)(Zc,{src:_.user.image,alt:I}):null,(0,t.jsx)(No,{children:E})]}),(0,t.jsx)("span",{className:W("min-w-0 flex-1 truncate",w&&"block w-0 min-w-0 overflow-hidden whitespace-nowrap text-transparent select-none"),children:I})]})}),(0,t.jsxs)(sr,{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:L,"aria-label":"View profile",onClick:O,className:"absolute inset-0 transition-colors hover:bg-accent focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-ring"}),(0,t.jsxs)(ko,{className:"pointer-events-none relative size-9",children:[_?.user.image?(0,t.jsx)(Zc,{src:_.user.image,alt:I}):null,(0,t.jsx)(No,{className:"text-xs text-foreground",children:E})]}),(0,t.jsxs)("div",{className:"pointer-events-none relative min-w-0 flex-1",children:[(0,t.jsx)("h2",{className:"truncate text-sm font-semibold leading-(--profile-popover-label-line-height) text-foreground",children:I}),(0,t.jsx)("p",{className:"truncate text-(length:--text-micro) leading-(--profile-popover-meta-line-height) text-muted-foreground",children:T}),S?(0,t.jsxs)("a",{className:"pointer-events-auto block truncate font-mono text-(length:--text-micro) leading-(--profile-popover-meta-line-height) text-muted-foreground hover:underline focus-visible:underline",href:`https://github.com/paperclipai/paperclip/commit/${S}`,target:"_blank",rel:"noreferrer","aria-label":`View commit ${S} on GitHub`,title:S,children:["SHA ",S.slice(0,7)]}):null]})]}),(0,t.jsxs)("div",{className:"flex flex-1 flex-col gap-0.5 border-t border-border px-2.5 pb-2.5 pt-2",children:[(0,t.jsx)(ID,{label:"Settings",icon:Su,href:"/company/settings",onClick:O}),p&&h?(0,t.jsx)(ID,{label:"Invite",icon:oh,href:h,topLevel:o,onClick:O}):null,(0,t.jsx)(ID,{label:"Documentation",icon:bS,href:pxt,external:!0,onClick:r(()=>C(!1),"onClick")}),(0,t.jsx)(Lk,{variant:"compact-menu-action",onAfterToggle:r(()=>C(!1),"onAfterToggle")}),(0,t.jsx)(k3e,{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:P,disabled:R.isPending,children:[(0,t.jsx)("span",{className:"flex size-5 shrink-0 items-center justify-center text-muted-foreground",children:(0,t.jsx)(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)(N3e,{})]})]})]}),!w&&!o?(0,t.jsxs)(Bn,{children:[(0,t.jsx)(On,{asChild:!0,children:(0,t.jsx)("a",{href:fxt,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)(fg,{className:"h-4 w-4","aria-hidden":"true"})})}),(0,t.jsx)($n,{side:"top",children:"Share feedback"})]}):null]})})}r(gie,"SidebarAccountMenu$1");function S3e({onNewIssue:e,onSearch:s,onToggleSidebar:n,onTogglePanel:a,onShowShortcuts:i,onGoToInbox:o}){(0,m.useEffect)(()=>{let l=!1,c=null;const d=r(()=>{c!==null&&(window.clearTimeout(c),c=null)},"clearGoChordTimeout"),u=r(()=>{l=!1,d()},"disarmGoChord"),h=r(()=>{l=!0,d(),c=window.setTimeout(()=>{l=!1,c=null},1200)},"armGoChord");function p(g){if(g.defaultPrevented){u();return}if(o){const v=zve({armed:l,defaultPrevented:g.defaultPrevented,key:g.key,metaKey:g.metaKey,ctrlKey:g.ctrlKey,altKey:g.altKey,target:g.target,hasOpenDialog:V0()});if(v==="arm"){h();return}if(v==="navigate_inbox"){u(),g.preventDefault(),o();return}if(v==="focus_comment"||v==="open_file_viewer"){u(),g.preventDefault();return}v==="disarm"&&u()}if(!k3(g.target)&&!V0()){if(g.key==="/"&&!g.metaKey&&!g.ctrlKey&&!g.altKey){g.preventDefault(),Sze()||s?.();return}if(g.key==="?"&&!g.metaKey&&!g.ctrlKey&&!g.altKey){g.preventDefault(),i?.();return}g.key==="c"&&!g.metaKey&&!g.ctrlKey&&!g.altKey&&(g.preventDefault(),e?.()),g.key==="["&&!g.metaKey&&!g.ctrlKey&&(g.preventDefault(),n?.()),g.key==="]"&&!g.metaKey&&!g.ctrlKey&&(g.preventDefault(),a?.())}}r(p,"handleKeyDown");const f=r(()=>u(),"handlePointerDown"),x=r(g=>{g.target instanceof HTMLElement&&g.target!==document.body&&u()},"handleFocusIn");return document.addEventListener("pointerdown",f,!0),document.addEventListener("focusin",x,!0),document.addEventListener("keydown",p),()=>{u(),document.removeEventListener("pointerdown",f,!0),document.removeEventListener("focusin",x,!0),document.removeEventListener("keydown",p)}},[e,s,n,a,i,o])}r(S3e,"useKeyboardShortcuts");var gxt=new Set(["auth","invite","board-claim","cli-auth","docs","s"]);function C3e(e){const s=(e.split("?")[0]??"").split("/").filter(Boolean);if(s.length===0)return!0;const[n]=s;return!gxt.has(n)}r(C3e,"isRememberableCompanyPath");function bxt(e){const s=xj(e.companyPrefix);return e.companies.find(n=>xj(n.issuePrefix)===s)??null}r(bxt,"findCompanyByPrefix");function vxt(e){const s=HQ(e.pathname);return s?bxt({companies:e.companies,companyPrefix:s})?.id??null:e.fallbackCompanyId}r(vxt,"getRememberedPathOwnerCompanyId");function yxt(e){const s=e.path?_8(e.path):"/dashboard";if(!C3e(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&&xj(i[1]??"")!==xj(e.companyPrefix))return"/dashboard"}return s}r(yxt,"sanitizeRememberedPathForCompany");var _3e="paperclip.companyPaths";function A3e(){try{const e=localStorage.getItem(_3e);if(e)return JSON.parse(e)}catch{}return{}}r(A3e,"getCompanyPaths");function jxt(e,s){const n=A3e();n[e]=s,localStorage.setItem(_3e,JSON.stringify(n))}r(jxt,"saveCompanyPath");function I3e(){const{companies:e,selectedCompanyId:s,selectedCompany:n,selectionSource:a}=ps(),i=ua(),o=Yn(),l=(0,m.useRef)(s),c=(0,m.useMemo)(()=>vxt({companies:e,pathname:i.pathname,fallbackCompanyId:l.current}),[e,i.pathname]),d=i.pathname+i.search;(0,m.useEffect)(()=>{const u=c,h=_8(d);u&&C3e(h)&&jxt(u,h)},[d,c]),(0,m.useEffect)(()=>{if(s){if(l.current!==null&&s!==l.current&&a!=="route_sync"&&n){const u=A3e(),h=yxt({path:u[s],companyPrefix:n.issuePrefix});o(`/${n.issuePrefix}${h}`,{replace:!0})}l.current=s}},[n,s,a,o])}r(I3e,"useCompanyPageMemory");var wxt=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 T3e(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 wxt({topZone:o("--mobile-nav-scroll-top-zone"),hideDistance:o("--mobile-nav-scroll-hide-distance"),showDistance:o("--mobile-nav-scroll-show-distance")},c.top,c.max);let u=null;const h=r(()=>{u===null&&(u=requestAnimationFrame(()=>{u=null;const{top:p,max:f}=l(),x=d.visible,g=d.update(p,f);g!==x&&a(g)}))},"onScroll");return window.addEventListener("scroll",h,{passive:!0}),()=>{window.removeEventListener("scroll",h),u!==null&&cancelAnimationFrame(u)}},[e,s]),n}r(T3e,"useMobileNavVisibility");function R3e(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(R3e,"resolveArchivedCompanyBounce");function kxt(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(kxt,"resolveCompanyArchiveDeparture");function E3e(e){const{selectionSource:s,selectedCompanyId:n,routeCompanyId:a}=e;return!(n===a||s==="manual"&&n)}r(E3e,"shouldSyncCompanySelectionFromRoute");function Nxt(e,s){return e instanceof HTMLElement?!(s instanceof HTMLElement)||!document.contains(s)||s===document.body||s===document.documentElement?!0:!e.contains(s):!1}r(Nxt,"shouldFocusMainContentAfterNavigation");function L3e(e){if(!(e instanceof HTMLElement))return()=>{};const s=window.requestAnimationFrame(()=>{Nxt(e,document.activeElement)&&e.focus({preventScroll:!0})});return()=>window.cancelAnimationFrame(s)}r(L3e,"scheduleMainContentFocus");function M3e(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(M3e,"pinDocumentScrollToZero");function om({scope:e="global",requestedPrefix:s}){const n=ua(),{setBreadcrumbs:a}=Wn(),{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)(nn,{className:"block p-6",children:[(0,t.jsxs)("div",{className:"flex items-center gap-3",children:[(0,t.jsx)("div",{className:"rounded-md border border-destructive/20 bg-destructive/10 p-2",children:(0,t.jsx)(Es,{className:"h-5 w-5 text-destructive"})}),(0,t.jsxs)("div",{children:[(0,t.jsx)("h1",{className:"text-xl font-semibold",children:h}),(0,t.jsx)("p",{className:"text-sm text-muted-foreground",children:p})]})]}),(0,t.jsxs)("div",{className:"mt-4 rounded-md border border-border bg-muted/20 px-3 py-2 text-xs text-muted-foreground",children:["Requested path: ",(0,t.jsx)("code",{className:"font-mono",children:d})]}),(0,t.jsxs)("div",{className:"mt-5 flex flex-wrap gap-2",children:[(0,t.jsx)($,{asChild:!0,children:(0,t.jsxs)(Ke,{to:c,children:[(0,t.jsx)(S6,{className:"mr-1.5 h-4 w-4"}),"Open dashboard"]})}),(0,t.jsx)($,{variant:"outline",asChild:!0,children:(0,t.jsx)(Ke,{to:"/",children:"Go home"})})]})]})})}r(om,"NotFoundPage");function Sxt(e,s){return SNe(e,s)[0]?.toLowerCase()??null}r(Sxt,"getCompanyRouteSegment$1");var Cxt=new Set(["browse","connections","assistant-connection","connect","chat","vercel-connect","review","attention","gateways","advanced","app"]);function _xt({sidebarSections:e}){const{sidebarOpen:s,setSidebarOpen:n,toggleSidebar:a,collapsed:i,peeking:o,setPeeking:l,isMobile:c,setForceCollapsed:d}=Wa(),{openNewIssue:u,openOnboarding:h}=al(),{togglePanelVisible:p}=Rf(),f=bd()?.pushToast??null,{companies:x,loading:g,selectedCompany:v,selectedCompanyId:y,selectionSource:k,setSelectedCompanyId:w}=ps(),{companyPrefix:N,pluginRoutePath:S,agentId:C,routineId:_}=ga(),R=Yn(),I=ua(),T=C8(),{enabled:E}=Rc(),L=CNe(I.pathname,N),O=L.builtInContextualSurface==="settings",P=L.companySegments,Q=L.isTaskDetail,{enabled:D}=aw(),F=D&&P[0]?.toLowerCase()==="chats",z=E&&(Q||F),K=P[0]?.toLowerCase()==="tools",U=P[0]?.toLowerCase()==="apps",q=U&&P[1]&&!Cxt.has(P[1].toLowerCase())?P[1]:null,G=U&&P[1]?.toLowerCase()==="app"&&P[2]?P[2]:null,se=(0,m.useRef)(!1),Z=(0,m.useRef)(null),ie=(0,m.useRef)(null),J=(0,m.useRef)(new Dke),re=(0,m.useRef)(I.key),oe=T3e(c&&!Q,I.pathname),[V,X]=(0,m.useState)(!1),Y=(0,m.useMemo)(()=>{if(!N)return null;const Et=N.toUpperCase();return x.find(ct=>ct.issuePrefix.toUpperCase()===Et)??null},[x,N]),ae=!!N&&!g&&x.length>0&&!Y,ne=(0,m.useMemo)(()=>S?.toLowerCase()??Sxt(I.pathname,N),[N,I.pathname,S]),ce=Y?.id??null,he=Y?.issuePrefix??null,{slots:pe}=Bd({slotTypes:["page","routeSidebar"],companyId:ce,enabled:!!(ce&&ne)}),ge=(0,m.useMemo)(()=>GW(pe,ne),[ne,pe]),Ee=(0,m.useMemo)(()=>({companyId:ce,companyPrefix:he}),[ce,he]),de=O?(0,t.jsx)(sZe,{}):!E&&L.builtInContextualSurface==="skills"?(0,t.jsx)(kse,{}):q?(0,t.jsx)(jse,{kind:"connection",connectionId:q}):G?(0,t.jsx)(jse,{kind:"application",applicationId:G}):U||K?(0,t.jsx)(dZe,{}):ge?E?(0,t.jsx)(U3,{surface:`plugin:${ge.id}`,title:ge.displayName,children:(0,t.jsx)(pm,{slot:ge,context:Ee,className:"min-h-0 flex-1",missingBehavior:"placeholder"})}):(0,t.jsx)(pm,{slot:ge,context:Ee,className:"h-full w-full",missingBehavior:"placeholder"}):null,Ne=F?(0,t.jsx)(Wft,{}):L.builtInContextualSurface==="agent"&&C?(0,t.jsx)(NZe,{agentRef:C}):E&&L.builtInContextualSurface==="routine"&&_?(0,t.jsx)(gVe,{children:(0,t.jsx)(_Ze,{routineId:_})}):E&&L.builtInContextualSurface==="skills"?(0,t.jsx)(kse,{}):de,le=Ne!=null,Le=E&&le&&(F||L.builtInContextualSurface==="skills"||L.builtInContextualSurface==="agent"||L.builtInContextualSurface==="routine"||U||K),Ie=E&&le&&!Le,ye=le&&(!E||Le),Ae=!E||!le?null:ge&&!L.builtInContextualSurface?`plugin:${ge.id}`:L.builtInContextualSurface,Qe=(0,m.useRef)(null),{data:ue}=te({queryKey:M.health,queryFn:r(()=>Iu.get(),"queryFn"),retry:!1,refetchInterval:r(Et=>Et.state.data?.devServer?.enabled?2e3:!1,"refetchInterval"),refetchIntervalInBackground:!1});(0,m.useLayoutEffect)(()=>(d(!E&&le),()=>d(!1)),[le,d,E]),(0,m.useEffect)(()=>{const Et=Qe.current;Ae&&N&&Et&&Et.surface!==Ae&&Et.pathname!==I.pathname&&XYe({surface:Ae,companyPrefix:N,previousPathname:Et.pathname}),Qe.current={pathname:I.pathname,surface:Ae}},[N,Ae,I.pathname]),(0,m.useEffect)(()=>{g||se.current||ue?.deploymentMode!=="authenticated"&&(ue?.cloud||x.length===0&&(se.current=!0,h()))},[x,g,h,ue?.cloud,ue?.deploymentMode]),(0,m.useEffect)(()=>{if(!N||g||x.length===0)return;if(!Y){const ct=(y?x.find(qe=>qe.id===y):null)??x[0]??null;ct&&y!==ct.id&&w(ct.id,{source:"route_sync"});return}if(N!==Y.issuePrefix){const ct=I.pathname.replace(/^\/[^/]+/,"");R(`/${Y.issuePrefix}${ct}${I.search}`,{replace:!0});return}const Et=R3e({matchedCompany:Y,selectedCompanyId:y,companies:x});if(Et){f?.({title:`${Y.name} is archived`,body:`Switched to ${Et.name}.`,tone:"info",dedupeKey:`archived-company-bounce:${Y.id}`}),w(Et.id,{source:"route_sync"}),R(`/${Et.issuePrefix}/dashboard`,{replace:!0});return}E3e({selectionSource:k,selectedCompanyId:y,routeCompanyId:Y.id})&&w(Y.id,{source:"route_sync"})},[N,x,g,Y,I.pathname,I.search,R,f,k,y,w]);const Be=p,ft=(0,m.useCallback)(()=>{document.dispatchEvent(new KeyboardEvent("keydown",{key:"k",metaKey:!0,bubbles:!0,cancelable:!0}))},[]),gt=(0,m.useRef)(null),Xe=(0,m.useRef)(!1),Fe=(0,m.useRef)(!1),at=(0,m.useCallback)(()=>{gt.current!==null&&(window.clearTimeout(gt.current),gt.current=null)},[]),Tt=(0,m.useCallback)(()=>{at(),gt.current=window.setTimeout(()=>l(!0),50)},[at,l]),Dt=(0,m.useCallback)(()=>{at(),l(!0)},[at,l]),Ot=(0,m.useCallback)(()=>{at(),gt.current=window.setTimeout(()=>l(!1),120)},[at,l]),rt=(0,m.useCallback)(()=>{Xe.current=!0,i&&!Fe.current&&Tt()},[i,Tt]),Pe=(0,m.useCallback)(()=>{Xe.current=!1,Fe.current=!1,Ot()},[Ot]),De=(0,m.useCallback)(()=>{Fe.current||Dt()},[Dt]),ht=(0,m.useCallback)(()=>{Xe.current||Ot()},[Ot]);(0,m.useEffect)(()=>at,[at]);const Ft=(0,m.useRef)(i);return(0,m.useEffect)(()=>{i!==Ft.current&&(i?(at(),l(!1),Fe.current=Xe.current):Fe.current=!1,Ft.current=i)},[i,at,l]),(0,m.useEffect)(()=>{if(!o)return;const Et=r(ct=>{ct.key==="Escape"&&(at(),l(!1))},"onKeyDown");return window.addEventListener("keydown",Et),()=>window.removeEventListener("keydown",Et)},[o,at,l]),I3e(),S3e({onNewIssue:r(()=>u(),"onNewIssue"),onSearch:ft,onToggleSidebar:a,onTogglePanel:Be,onShowShortcuts:r(()=>X(!0),"onShowShortcuts"),onGoToInbox:r(()=>R("/inbox"),"onGoToInbox")}),(0,m.useEffect)(()=>{if(!c)return;const Et=30,ct=50,qe=75;let Oe=0,Re=0;const Ve=r(Ge=>{const vt=Ge.touches[0];Oe=vt.clientX,Re=vt.clientY},"onTouchStart"),xe=r(Ge=>{const vt=Ge.changedTouches[0],Ss=vt.clientX-Oe;if(!(Math.abs(vt.clientY-Re)>qe)){if(!s&&Oe<Et&&Ss>ct){n(!0);return}s&&Ss<-50&&n(!1)}},"onTouchEnd");return document.addEventListener("touchstart",Ve,{passive:!0}),document.addEventListener("touchend",xe,{passive:!0}),()=>{document.removeEventListener("touchstart",Ve),document.removeEventListener("touchend",xe)}},[c,s,n]),(0,m.useEffect)(()=>{const Et=document.body.style.overflow;return document.body.style.overflow=c?"visible":"clip",()=>{document.body.style.overflow=Et}},[c]),(0,m.useEffect)(()=>{if(!c)return M3e()},[c]),(0,m.useEffect)(()=>{if(typeof document>"u")return;const Et=ie.current;return L3e(Et)},[I.pathname]),(0,m.useEffect)(()=>{const Et=ie.current;if(!Et)return;const ct=r(()=>{J.current.remember(re.current,Et.scrollTop)},"recordScroll");return Et.addEventListener("scroll",ct,{passive:!0}),()=>Et.removeEventListener("scroll",ct)},[]),(0,m.useLayoutEffect)(()=>{const Et=ie.current,ct=Pke({previousPathname:Z.current,pathname:I.pathname,navigationType:T,state:I.state});Z.current=I.pathname;const qe=T==="POP",Oe=qe?J.current.recall(I.key):0;if(re.current=I.key,qe){W6(Et,Oe);const Re=requestAnimationFrame(()=>W6(Et,Oe));return()=>cancelAnimationFrame(Re)}ct&&$ke(Et)},[I.key,I.pathname,I.state,T]),(0,t.jsx)(Lke,{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)(a3e,{}),(0,t.jsx)(i3e,{devServer:ue?.devServer}),(0,t.jsxs)("div",{className:W("min-h-0 flex-1",c?"w-full":"flex overflow-clip"),children:[c&&s&&(0,t.jsx)("button",{type:"button",className:"fixed inset-0 z-40 bg-black/50",onClick:r(()=>n(!1),"onClick"),"aria-label":"Close sidebar"}),c?(0,t.jsxs)("div",{className:W("fixed inset-y-0 left-0 z-50 flex flex-col overflow-hidden pt-(--sz-safe-top) transition-transform duration-100 ease-out",s?"translate-x-0":"-translate-x-full"),children:[(0,t.jsx)("div",{className:"flex flex-1 min-h-0 overflow-hidden",children:(0,t.jsx)("div",{className:"w-60 shrink-0 overflow-hidden",children:le?(0,t.jsx)(HI,{children:Ne}):(0,t.jsx)(gse,{children:e})})}),(0,t.jsx)(gie,{deploymentMode:ue?.deploymentMode,forceExpanded:Ie})]}):(0,t.jsxs)(Hft,{open:s,collapsed:Ie?!1:i,peeking:Ie?!1:o,resizable:!0,onPanelMouseEnter:Ie?void 0:rt,onPanelMouseLeave:Ie?void 0:Pe,onPanelFocusCapture:!Ie&&i?De:void 0,onPanelBlurCapture:!Ie&&i?ht:void 0,children:[(0,t.jsx)("div",{className:"flex flex-1 min-h-0",children:Ie?(0,t.jsx)(HI,{children:Ne}):(0,t.jsx)(gse,{children:e})}),(0,t.jsx)(gie,{deploymentMode:ue?.deploymentMode,forceExpanded:Ie})]}),!c&&ye&&!Le?(0,t.jsx)(HI,{className:"w-60 shrink-0",children:Ne}):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&&z&&"hidden",c&&"sticky top-0 z-20 bg-background/95 backdrop-blur supports-[backdrop-filter]:bg-background/85"),children:[(0,t.jsx)(aq,{mobile:c,onNavigateHome:r(()=>R("/dashboard"),"onNavigateHome")}),(0,t.jsx)(Sse,{}),c&&O?(0,t.jsx)("div",{className:"border-b border-border px-4 pb-3",children:(0,t.jsx)(INe,{})}):null]}),(0,t.jsxs)("div",{className:W(c?"block":"flex flex-1 min-h-0",!c&&z&&"streamlined-task-detail-surface"),children:[!c&&Le?(0,t.jsx)(HI,{className:"w-60 shrink-0 bg-background",children:Ne}):null,(0,t.jsxs)("div",{className:W(!c&&z?"flex min-w-0 flex-1 flex-col":"contents"),children:[!c&&z?(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)(aq,{mobile:!1,onNavigateHome:r(()=>R("/dashboard"),"onNavigateHome")}),(0,t.jsx)(Sse,{taskDetailLayout:!0})]}):null,(0,t.jsx)("main",{id:"main-content",ref:ie,tabIndex:-1,style:c?{"--tc-composer-bottom":"var(--sz-calc-14)"}:void 0,className:W("flex-1 p-4 outline-none md:p-6",!c&&z&&"pt-0 md:pt-0",c?"overflow-visible pb-(--sz-calc-14)":"overflow-auto [scrollbar-gutter:stable]"),children:ae?(0,t.jsx)(om,{scope:"invalid_company_prefix",requestedPrefix:N??v?.issuePrefix}):(0,t.jsx)(c3e,{children:(0,t.jsx)(cv,{})})})]}),(0,t.jsx)(zNe,{taskDetailLayout:!c&&z})]})]})]}),c&&(0,t.jsx)(r3e,{visible:oe}),(0,t.jsx)(qNe,{}),(0,t.jsx)(CSe,{}),(0,t.jsx)(p5e,{}),(0,t.jsx)(g5e,{}),(0,t.jsx)(j5e,{}),(0,t.jsx)(w5e,{open:V,onOpenChange:X}),(0,t.jsx)(k5e,{}),(0,t.jsx)(s3e,{companyId:y}),(0,t.jsx)(xft,{health:ue}),(0,t.jsx)(n3e,{localTrusted:ue?.deploymentMode==="local_trusted"})]})})}r(_xt,"Layout$1");var P3e=(0,m.createContext)(!1);function Axt({children:e}){return(0,t.jsx)(P3e.Provider,{value:!0,children:e})}r(Axt,"SidebarNavExpandedProvider");function Ixt(){return(0,m.useContext)(P3e)}r(Ixt,"useSidebarNavExpanded");function Xa({to:e,label:s,icon:n,iconNode:a,end:i,className:o,labelClassName:l,badge:c,badgeTone:d="default",badgeLabel:u,textBadge:h,textBadgeTone:p="default",alert:f=!1,liveCount:x,active:g,trailing:v,trailingLabel:y,liveAccessory:k}){const{isMobile:w,setSidebarOpen:N,collapsed:S,peeking:C}=Wa(),_=Ixt(),R=S&&!C&&!_,I=c!=null&&c>0,T=x!=null&&x>0,E=T?`${x} live`:I?`${c}${u?` ${u}`:""}`:f?"attention needed":void 0,L=!R||!E&&!y?void 0:`${s}${E?`, ${E}`:""}${y?`, ${y}`:""}`,O=(0,t.jsxs)(dv,{to:e,state:If,end:i,"aria-label":L,onClick:r(()=>{w&&N(!1)},"onClick"),className:r(({isActive:P})=>W("flex items-center gap-2.5 mx-2 rounded-lg px-2 py-1.5 pointer-coarse:py-1 text-(length:--text-compact) font-medium transition-colors",g??P?"bg-accent text-foreground":"text-foreground/80 hover:bg-accent/50 hover:text-foreground",o),"className"),children:[(0,t.jsxs)("span",{className:"relative shrink-0",children:[a??(n?(0,t.jsx)(n,{className:"h-4 w-4"}):null),f&&(0,t.jsx)("span",{className:"absolute -right-0.5 -top-0.5 h-2 w-2 rounded-full bg-red-500 shadow-(--shadow-extract-12)","aria-hidden":"true"}),R&&!f&&T&&(0,t.jsxs)("span",{className:"absolute -right-0.5 -top-0.5 flex h-2 w-2","aria-hidden":"true",children:[(0,t.jsx)("span",{className:"animate-pulse absolute inline-flex h-full w-full rounded-full bg-blue-600 dark:bg-blue-400 opacity-75"}),(0,t.jsx)("span",{className:"relative inline-flex h-2 w-2 rounded-full bg-blue-600 dark:bg-blue-400 shadow-(--shadow-extract-12)"})]}),R&&!f&&!T&&I&&(0,t.jsx)("span",{className:W("absolute -right-0.5 -top-0.5 h-2 w-2 rounded-full shadow-(--shadow-extract-12)",d==="danger"?"bg-red-600":d==="warning"?"bg-amber-500":"bg-primary"),"aria-hidden":"true"})]}),(0,t.jsx)("span",{className:R?Vj:W("min-w-0 flex-1 truncate",l),children:s}),!R&&v,!R&&h&&(0,t.jsx)(it,{variant:"ghost",className:W("ml-auto px-1.5 text-(length:--text-nano) leading-none",p==="amber"?"bg-amber-100 text-amber-800 dark:bg-amber-900/30 dark:text-amber-400":"bg-muted text-muted-foreground"),children:h}),!R&&(T||k)&&(0,t.jsxs)("span",{className:"ml-auto flex items-center gap-1.5",children:[k,T&&(0,t.jsxs)(t.Fragment,{children:[(0,t.jsxs)("span",{className:"relative flex h-2 w-2",children:[(0,t.jsx)("span",{className:"animate-pulse absolute inline-flex h-full w-full rounded-full bg-blue-600 dark:bg-blue-400 opacity-75"}),(0,t.jsx)("span",{className:"relative inline-flex rounded-full h-2 w-2 bg-blue-600 dark:bg-blue-400"})]}),(0,t.jsxs)("span",{className:"text-(length:--text-micro) font-medium text-blue-600 dark:text-blue-400",children:[x," live"]})]})]}),!R&&I&&(0,t.jsx)(it,{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)(Bn,{children:[(0,t.jsx)(On,{asChild:!0,children:(0,t.jsx)("div",{children:O})}),(0,t.jsx)($n,{side:"right",children:s})]}):O}r(Xa,"SidebarNavItem");var Txt=3,bie=12e4,Rxt=[{value:"top",label:"Top"},{value:"alphabetical",label:"Alphabetical"},{value:"recent",label:"Recent"}];function t1(e,s){const n=e[s];if(!n)return 0;const a=new Date(n).getTime();return Number.isFinite(a)?a:0}r(t1,"agentTimestamp");function vie(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=t1(i,"lastHeartbeatAt")-t1(a,"lastHeartbeatAt");if(o!==0)return o;const l=t1(i,"updatedAt")-t1(a,"updatedAt");if(l!==0)return l;const c=t1(i,"createdAt")-t1(a,"createdAt");return c!==0?c:a.name.localeCompare(i.name,void 0,{sensitivity:"base"})}),n)}r(vie,"sortAgents");var Ext="opacity-0 transition-opacity group-hover/agent:opacity-100 group-focus-within/agent:opacity-100";function Lxt({activeAgentId:e,activeTab:s,agent:n,disabled:a,isMobile:i,leaving:o,onLeaveAgent:l,onPauseResume:c,rail:d,runCount:u,setSidebarOpen:h,builtInStatus:p,starred:f=!1,onToggleStar:x,starPending:g=!1}){const v=Vl(n),y=s?`${sm(n)}/${s}`:sm(n),k=`${sm(n)}/configuration`,w=e===v,N=n.status==="paused",S=N&&n.pauseReason==="budget",C=n.orgChainHealth?.status==="invalid_org_chain",_=N?"Resume agent":"Pause agent",R=a||n.status==="pending_approval"||S||N&&C,I=a?"Updating...":S?"Budget paused":N&&C?"Invalid org chain":_,T=p==="needs_setup"||p==="pending_approval",E=[T?`Built-in agent ${p.replace(/_/g," ")}`:null,C?"Invalid reporting chain":null].filter(Boolean).join(", ")||void 0,L=(0,t.jsx)(Xa,{to:y,label:n.name,iconNode:(0,t.jsx)(lr,{agent:n,size:16,className:"shrink-0 h-4 w-4"}),active:w,liveCount:u,labelClassName:T?"min-w-(--sz-4_5rem) flex-initial":void 0,className:W("min-w-0 flex-1",f&&!i?"pr-14":"pr-8"),trailing:T||C?(0,t.jsxs)("span",{className:"ml-1 flex shrink-0 items-center gap-1",children:[T?(0,t.jsx)(Ck,{status:p,compact:!0}):null,C?(0,t.jsx)(Es,{className:"h-3.5 w-3.5 shrink-0 text-amber-500","aria-label":"Invalid reporting chain"}):null]}):void 0,trailingLabel:E,liveAccessory:n.pauseReason==="budget"?(0,t.jsx)(F3,{title:"Agent paused by budget"}):void 0});return d?L:(0,t.jsxs)("div",{className:"group/agent relative flex items-center",children:[L,f&&!i&&x?(0,t.jsx)("span",{className:"absolute right-10 top-1/2 -translate-y-1/2",children:(0,t.jsx)(nw,{size:"row",quiet:!0,starred:!0,pending:g,resourceName:n.name,onToggle:r(()=>x(n,!1),"onToggle"),revealClassName:Ext})}):null,(0,t.jsxs)(ia,{children:[(0,t.jsx)(ra,{asChild:!0,children:(0,t.jsx)($,{variant:"ghost",size:"icon-xs",className:W("absolute right-3 top-1/2 h-6 w-6 -translate-y-1/2 transition-opacity data-[state=open]:pointer-events-auto data-[state=open]:opacity-100",i?"opacity-100":"pointer-events-none opacity-0 group-hover/agent:pointer-events-auto group-hover/agent:opacity-100 group-focus-within/agent:pointer-events-auto group-focus-within/agent:opacity-100"),"aria-label":`Open actions for ${n.name}`,children:(0,t.jsx)(Ci,{className:"h-3.5 w-3.5"})})}),(0,t.jsxs)(aa,{align:"end",className:"w-48",children:[x?(0,t.jsxs)(t.Fragment,{children:[(0,t.jsxs)(ls,{onClick:r(()=>{g||x(n,!f)},"onClick"),disabled:g,children:[g?(0,t.jsx)(st,{className:"size-4 motion-safe:animate-spin"}):(0,t.jsx)(Q0,{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)(ii,{})]}):null,(0,t.jsx)(ls,{asChild:!0,children:(0,t.jsxs)(Ke,{to:k,onClick:r(()=>{i&&h(!1)},"onClick"),children:[(0,t.jsx)(nc,{className:"size-4"}),(0,t.jsx)("span",{children:"Edit agent"})]})}),(0,t.jsx)(ii,{}),(0,t.jsxs)(ls,{onClick:r(()=>{R||c(n,N?"resume":"pause")},"onClick"),disabled:R,title:S?"Agent was paused by budget limits":void 0,children:[N?(0,t.jsx)(M3,{className:"size-4"}):(0,t.jsx)(Zd,{className:"size-4"}),(0,t.jsx)("span",{children:I})]}),(0,t.jsx)(ii,{}),(0,t.jsxs)(ls,{onClick:r(()=>{o||l(n)},"onClick"),disabled:o,children:[o?(0,t.jsx)(st,{className:"size-4 motion-safe:animate-spin"}):(0,t.jsx)(tp,{className:"size-4"}),(0,t.jsx)("span",{children:o?"Leaving...":"Leave agent"})]})]})]})]})}r(Lxt,"SidebarAgentItem");function Mxt({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=kt(),{selectedCompanyId:u}=ps(),h=jS(u),{openNewAgent:p}=al(),{isMobile:f,setSidebarOpen:x,collapsed:g,peeking:v}=Wa(),y=g&&!v,{pushToast:k}=Xr(),w=ua(),{data:N}=te({queryKey:M.agents.list(u),queryFn:r(()=>_t.list(u),"queryFn"),enabled:!!u}),{data:S}=te({queryKey:M.instance.experimentalSettings,queryFn:r(()=>jr.getExperimental(),"queryFn"),enabled:!!u}),C=S?.enableBuiltInAgents===!0,{data:_}=te({queryKey:M.builtInAgents.list(u),queryFn:r(()=>k0.list(u),"queryFn"),enabled:!!u&&C}),R=(0,m.useMemo)(()=>{const ye=new Map;if(!C)return ye;for(const Ae of _??[])Ae.agentId&&ye.set(Ae.agentId,Ae.status);return ye},[_,C]),{data:I}=te({queryKey:M.auth.session,queryFn:r(()=>Ma.getSession(),"queryFn")}),T=Tf(u),E=pv(u),L=M.liveRuns(u),O=Co({companyId:u,resourceKey:"live-runs",queryKey:L,enabled:!!u,refetchInterval:!1,leaderOnly:!0}),{data:P,dataUpdatedAt:Q}=te({queryKey:L,queryFn:r(()=>na.liveRunsForCompany(u),"queryFn"),enabled:O.enabled,refetchInterval:O.refetchInterval});_o(O,P,Q);const D=(0,m.useMemo)(()=>{const ye=new Map;for(const Ae of P??[])ye.set(Ae.agentId,(ye.get(Ae.agentId)??0)+1);return ye},[P]),F=(0,m.useMemo)(()=>{const ye=new Set;for(const[Ae,Qe]of D)Qe>0&&ye.add(Ae);return ye},[D]),z=(0,m.useMemo)(()=>(N??[]).filter(ye=>ye.status!=="terminated"&&(!T.isSuccess||eg(T.data,"agent",ye.id)!=="left")),[N,T.data,T.isSuccess]),K=I?.user?.id??I?.session?.userId??null,U=(0,m.useMemo)(()=>u?Hke(u,K):null,[K,u]),[q,G]=(0,m.useState)(()=>U?_k(U):"top"),{orderedAgents:se}=Yke({agents:z,companyId:u,userId:K}),Z=(0,m.useMemo)(()=>vie(se,q),[se,q]),ie=(0,m.useMemo)(()=>new Set(Z.map(ye=>ye.id)),[Z]);(0,m.useEffect)(()=>{const ye=Date.now();for(const Ae of F)c.current.set(Ae,ye);for(const Ae of c.current.keys())ie.has(Ae)||c.current.delete(Ae)},[F,ie]);const J=(0,m.useMemo)(()=>{const ye=Date.now(),Ae=c.current;return Z.filter(Qe=>{if((D.get(Qe.id)??0)>0)return!0;const ue=Ae.get(Qe.id);return ue!==void 0&&ye-ue<=bie})},[D,o,Z]),re=J.length>0,oe=e?re?J:Z.slice(0,Txt):Z,V=e&&Z.length>0,X=w.pathname.match(/^\/(?:[^/]+\/)?agents\/([^/]+)(?:\/([^/]+))?/),Y=X?.[1]??null,ae=X?.[2]??null;(0,m.useEffect)(()=>{if(!U){G("top");return}G(_k(U))},[U]),(0,m.useEffect)(()=>{if(!U)return;const ye=r(Qe=>{Qe.key===U&&G(_k(U))},"onStorage"),Ae=r(Qe=>{const ue=Qe.detail;!ue||ue.storageKey!==U||G(ue.sortMode)},"onCustomEvent");return window.addEventListener("storage",ye),window.addEventListener(r5,Ae),()=>{window.removeEventListener("storage",ye),window.removeEventListener(r5,Ae)}},[U]),(0,m.useEffect)(()=>{if(!e)return;const ye=Date.now();let Ae=null;for(const ue of Z){if((D.get(ue.id)??0)>0)continue;const Be=c.current.get(ue.id);if(Be===void 0)continue;const ft=Be+bie;ft<ye||(Ae=Ae===null?ft:Math.min(Ae,ft))}if(Ae===null)return;const Qe=window.setTimeout(()=>{l(ue=>ue+1)},Math.max(0,Ae-ye+1));return()=>{window.clearTimeout(Qe)}},[e,Z,D,o]);const ne=(0,m.useCallback)(ye=>{const Ae=ye==="alphabetical"||ye==="recent"?ye:"top";G(Ae),U&&Gke(U,Ae)},[U]),ce=je({mutationFn:r(({agent:ye,action:Ae})=>Ae==="pause"?_t.pause(ye.id,u??void 0):_t.resume(ye.id,u??void 0),"mutationFn"),onMutate:r(({agent:ye})=>{i(Ae=>{const Qe=new Set(Ae);return Qe.add(ye.id),Qe})},"onMutate"),onSuccess:r(async(ye,{agent:Ae,action:Qe})=>{u&&await Promise.all([d.invalidateQueries({queryKey:M.agents.list(u)}),d.invalidateQueries({queryKey:M.liveRuns(u)}),d.invalidateQueries({queryKey:M.dashboard(u)})]),await Promise.all([d.invalidateQueries({queryKey:M.agents.detail(Ae.id)}),d.invalidateQueries({queryKey:M.agents.detail(Vl(Ae))})]),k({title:Qe==="pause"?"Agent paused":"Agent resumed",body:Ae.name,tone:"success"})},"onSuccess"),onError:r((ye,{agent:Ae,action:Qe})=>{k({title:Qe==="pause"?"Could not pause agent":"Could not resume agent",body:ye instanceof Error?ye.message:Ae.name,tone:"error"})},"onError"),onSettled:r((ye,Ae,{agent:Qe})=>{i(ue=>{const Be=new Set(ue);return Be.delete(Qe.id),Be})},"onSettled")}),he=(0,m.useCallback)(ye=>E.mutate({resourceType:"agent",resourceId:ye.id,resourceName:ye.name,state:"left"}),[E]),pe=(0,m.useCallback)(ye=>E.isPending&&E.variables?.resourceType==="agent"&&E.variables.resourceId===ye.id,[E.isPending,E.variables]),ge=(0,m.useCallback)((ye,Ae)=>E.mutate({resourceType:"agent",resourceId:ye.id,resourceName:ye.name,starred:Ae}),[E]),Ee=(0,m.useCallback)(ye=>E.isPending&&E.variables?.resourceType==="agent"&&E.variables.resourceId===ye.id&&E.variables.starred!==void 0,[E.isPending,E.variables]),de=(0,m.useMemo)(()=>new Set(V8(T.data,"agent")),[T.data]),Ne=(0,m.useMemo)(()=>vie(z.filter(ye=>de.has(ye.id)),"alphabetical"),[z,de]),le=(0,m.useMemo)(()=>oe.filter(ye=>!de.has(ye.id)),[oe,de]),Le=h&&!h.loading?z.find(ye=>ye.id===h.primaryAgentId):void 0,Ie=r((ye,Ae)=>(0,t.jsx)(Lxt,{activeAgentId:Y,activeTab:ae,agent:ye,disabled:a.has(ye.id),isMobile:f,leaving:pe(ye),onLeaveAgent:he,onPauseResume:r((Qe,ue)=>ce.mutate({agent:Qe,action:ue}),"onPauseResume"),rail:y,runCount:D.get(ye.id)??0,setSidebarOpen:x,builtInStatus:R.get(ye.id),starred:Ae||sw(T.data,"agent",ye.id),onToggleStar:ge,starPending:Ee(ye)},ye.id),"renderAgentRow");return(0,t.jsxs)(zx,{label:"Agents",collapsible:{open:s,onOpenChange:n},headerAction:{ariaLabel:"New agent",icon:gn,onClick:p},menu:{ariaLabel:"Agents section actions",actions:[{type:"item",label:"Browse agents",icon:Ho,href:"/agents/all"},{type:"separator"}],radioLabel:"Agent sort",radioChoices:Rxt,radioValue:q,onRadioValueChange:ne},children:[[...Le?[Le]:[],...Ne.filter(ye=>ye.id!==Le?.id),...le.filter(ye=>ye.id!==Le?.id)].map(ye=>Ie(ye,de.has(ye.id))),V&&(()=>{const ye=(0,t.jsxs)(Ke,{to:"/agents/all",state:If,"aria-label":y?"See all agents":void 0,onClick:r(()=>{f&&x(!1)},"onClick"),className:"flex items-center gap-2.5 mx-2 rounded-lg px-2 py-1.5 pointer-coarse:py-1 text-(length:--text-compact) font-medium text-muted-foreground transition-colors hover:bg-accent/50 hover:text-foreground",children:[(0,t.jsx)(Ho,{className:"shrink-0 h-4 w-4"}),(0,t.jsx)("span",{className:y?"block w-0 min-w-0 overflow-hidden whitespace-nowrap text-transparent select-none":void 0,children:"See all agents"})]});return y?(0,t.jsxs)(Bn,{children:[(0,t.jsx)(On,{asChild:!0,children:ye}),(0,t.jsx)($n,{side:"right",children:"See all agents"})]}):ye})()]})}r(Mxt,"SidebarAgents");var Pxt="opacity-0 transition-opacity group-hover/starred-project:opacity-100 group-focus-within/starred-project:opacity-100";function Dxt(){const{selectedCompanyId:e}=ps(),{isMobile:s,setSidebarOpen:n,collapsed:a,peeking:i}=Wa(),o=a&&!i,l=ua(),{data:c}=te({queryKey:M.projects.list(e),queryFn:r(()=>oa.list(e),"queryFn"),enabled:!!e}),d=Tf(e),u=pv(e),h=l.pathname.match(/^\/(?:[^/]+\/)?projects\/([^/]+)/)?.[1]??null,p=(0,m.useMemo)(()=>{if(!d.isSuccess)return[];const v=new Set(V8(d.data,"project"));if(v.size===0)return[];const y=new Map((c??[]).map(k=>[k.id,k]));return Array.from(v).map(k=>y.get(k)).filter(k=>!!k).sort((k,w)=>k.name.localeCompare(w.name,void 0,{sensitivity:"base"}))},[d.data,d.isSuccess,c]),f=(0,m.useCallback)(v=>u.mutate({resourceType:"project",resourceId:v.id,resourceName:v.name,starred:!1}),[u]),x=(0,m.useCallback)(v=>u.mutate({resourceType:"project",resourceId:v.id,resourceName:v.name,state:"left"}),[u]),g=(0,m.useCallback)(v=>u.isPending&&u.variables?.resourceType==="project"&&u.variables.resourceId===v.id,[u.isPending,u.variables]);return!d.isSuccess||p.length===0?null:(0,t.jsx)("div",{className:"flex flex-col gap-0.5","aria-label":"Starred projects",children:p.map(v=>{const y=Vx(v),k=h===y||h===v.id,w=g(v),N=w&&u.variables?.starred===!1,S=w&&u.variables?.state==="left",C=sw(d.data,"project",v.id),_=(0,t.jsxs)(dv,{to:`/projects/${y}/issues`,state:If,onClick:r(()=>{s&&n(!1)},"onClick"),className:W("flex min-w-0 flex-1 items-center gap-2.5 mx-2 rounded-lg px-2 py-1.5 pointer-coarse:py-1 pr-8 text-(length:--text-compact) font-medium transition-colors",!o&&"pl-6",k?"bg-accent text-foreground":"text-foreground/80 hover:bg-accent/50 hover:text-foreground"),children:[(0,t.jsx)(Zm,{color:v.color??null,icon:v.icon??null,size:"xs"}),(0,t.jsx)("span",{className:o?Vj:"flex-1 truncate",children:v.name}),!o&&v.visibility==="private"?(0,t.jsx)(Ao,{className:"size-3.5 shrink-0 text-muted-foreground","aria-label":"Private project"}):null,!o&&v.pauseReason==="budget"?(0,t.jsx)(F3,{title:"Project paused by budget"}):null]});return(0,t.jsxs)("div",{className:"group/starred-project relative flex items-center",children:[o?(0,t.jsxs)(Bn,{children:[(0,t.jsx)(On,{asChild:!0,children:(0,t.jsx)("div",{className:"min-w-0 flex-1",children:_})}),(0,t.jsx)($n,{side:"right",children:v.name})]}):_,!o&&!s?(0,t.jsx)("span",{className:"absolute right-3 top-1/2 -translate-y-1/2",children:(0,t.jsx)(nw,{size:"row",quiet:!0,starred:C,pending:N,resourceName:v.name,onToggle:r(()=>f(v),"onToggle"),revealClassName:Pxt})}):null,!o&&s?(0,t.jsxs)(ia,{children:[(0,t.jsx)(ra,{asChild:!0,children:(0,t.jsx)($,{variant:"ghost",size:"icon-xs",className:"absolute right-3 top-1/2 h-6 w-6 -translate-y-1/2 opacity-100","aria-label":`Open actions for ${v.name}`,children:(0,t.jsx)(Ci,{className:"h-3.5 w-3.5"})})}),(0,t.jsxs)(aa,{align:"end",className:"w-48",children:[(0,t.jsxs)(ls,{onClick:r(()=>{w||f(v)},"onClick"),disabled:w,children:[N?(0,t.jsx)(st,{className:"size-4 motion-safe:animate-spin"}):(0,t.jsx)(Q0,{className:"size-4 fill-amber-500 text-amber-500"}),(0,t.jsx)("span",{children:"Remove from starred"})]}),(0,t.jsx)(ii,{}),(0,t.jsxs)(ls,{onClick:r(()=>{w||x(v)},"onClick"),disabled:w,children:[S?(0,t.jsx)(st,{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(Dxt,"SidebarStarredProjects");var $xt="size-5 shrink-0 rounded-md text-(length:--text-micro)",Oxt="size-(--organization-popover-avatar-size) shrink-0 rounded-lg text-(length:--text-micro)",Bxt="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",TD="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 D3e({company:e,inPopover:s=!1}){return(0,t.jsx)(tg,{companyName:e.name,logoUrl:e.logoUrl,className:s?Oxt:$xt})}r(D3e,"WorkspaceIcon");function Fxt({company:e,isEditing:s,isSelected:n,onSelect:a}){const{attributes:i,listeners:o,setActivatorNodeRef:l,setNodeRef:c,transform:d,transition:u,isDragging:h}=pS({id:e.id,disabled:!s});return(0,t.jsxs)(ls,{ref:c,style:{transform:mS.Transform.toString(d),transition:u,zIndex:h?10:void 0},onSelect:r(p=>{if(s){p.preventDefault();return}a(e)},"onSelect"),className:W(Bxt,s&&"cursor-grab",h&&"opacity-80"),children:[(0,t.jsx)(D3e,{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)(F8,{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)(cs,{className:"size-4 text-foreground"}):null})]})}r(Fxt,"SortableCompanyItem");function zxt(e={}){return(0,t.jsx)(kNe,{...e,children:(0,t.jsx)(qxt,{...e})})}r(zxt,"SidebarCompanyMenu");function qxt({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}=al(),{isMobile:f,setSidebarOpen:x,collapsed:g,peeking:v}=Wa(),y=g&&!v,k=ua(),w=Yn(),N=e??n,S=s??a,C=lS(xf(nW,{activationConstraint:{distance:8}}),xf(rve,{activationConstraint:{delay:180,tolerance:6}})),_=(0,m.useMemo)(()=>l.filter(Z=>Z.status!=="archived"),[l]),{data:R}=te({queryKey:M.auth.session,queryFn:r(()=>Ma.getSession(),"queryFn"),retry:!1}),I=R?.user?.id??R?.session?.userId??null,{orderedCompanies:T,persistOrder:E}=wNe({companies:_,userId:I}),{hidden:L,loaded:O}=Au(),P=O&&!Gx(L,"company.members")&&!Gx(L,"company.invites"),Q="company",D=c?.name??null,F=!!ed(),z=SS({onSignedOut:U});function K(Z){Z||o(!1),S(Z)}r(K,"handleOpenChange");function U(){S(!1),o(!1),f&&x(!1)}r(U,"closeNavigationChrome");function q(Z){const ie=k.pathname.split("/")[1]?.toUpperCase(),J=_.some(oe=>oe.issuePrefix.toUpperCase()===ie),re=Z.id!==c?.id&&(k.pathname.startsWith("/instance/")||J);d(Z.id),S(!1),f&&x(!1),re&&w(`/${Z.issuePrefix}/dashboard`)}r(q,"selectCompany");function G(){F||(S(!1),f&&x(!1),p({initialStep:1}))}r(G,"addCompany");const se=(0,m.useCallback)(Z=>{const{active:ie,over:J}=Z;if(!J||ie.id===J.id)return;const re=T.map(X=>X.id),oe=re.indexOf(ie.id),V=re.indexOf(J.id);oe===-1||V===-1||E(E8(re,oe,V))},[T,E]);return(0,t.jsxs)(ia,{open:N,onOpenChange:K,children:[(0,t.jsx)(ra,{asChild:!0,children:(0,t.jsxs)($,{variant:"ghost",className:"h-9 min-w-0 flex-1 justify-start gap-2 px-4 text-left hover:bg-accent/50 hover:text-foreground has-[>svg]:px-4 dark:hover:bg-accent/50","aria-label":D?`Open ${D} ${Q} switcher`:`Open ${Q} switcher`,children:[(0,t.jsxs)("span",{className:"flex min-w-0 flex-1 items-center gap-2",children:[c?(0,t.jsx)(D3e,{company:c}):null,(0,t.jsx)("span",{className:W("min-w-0 truncate text-sm font-bold text-foreground",y&&"block w-0 min-w-0 overflow-hidden whitespace-nowrap text-transparent select-none"),title:D??void 0,children:D??`Select ${Q}`})]}),!y&&(0,t.jsx)(T8,{className:"size-3.5 shrink-0 text-muted-foreground"})]})}),(0,t.jsxs)(aa,{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)(mv,{className:"p-0 text-(length:--text-compact) font-semibold text-foreground",children:"Organizations"}),(0,t.jsx)("button",{type:"button",onClick:r(Z=>{Z.preventDefault(),Z.stopPropagation(),o(ie=>!ie)},"onClick"),className:"rounded px-1.5 py-0.5 text-xs font-medium text-muted-foreground transition-colors hover:bg-accent hover:text-foreground",children:i?"Done":"Edit"})]}),(0,t.jsxs)("div",{className:"flex max-h-96 flex-col gap-0.5 overflow-y-auto px-2.5 pb-2 pt-1",children:[(0,t.jsx)(hS,{sensors:C,collisionDetection:j3,onDragEnd:se,children:(0,t.jsx)(uS,{items:T.map(Z=>Z.id),strategy:N3,children:T.map(Z=>(0,t.jsx)(Fxt,{company:Z,isEditing:i,isSelected:Z.id===c?.id,onSelect:q},Z.id))})}),T.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(Z=>{Z.preventDefault(),h()},"onSelect"),children:[(0,t.jsx)(Ai,{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:[!F&&(0,t.jsxs)(ls,{onClick:G,className:TD,disabled:i,children:[(0,t.jsx)("span",{className:"flex size-5 shrink-0 items-center justify-center text-muted-foreground",children:(0,t.jsx)(gn,{className:"size-4"})}),(0,t.jsx)("span",{className:"min-w-0 flex-1 truncate",children:"Create organization"})]}),P?(0,t.jsx)(ls,{asChild:!0,disabled:i,className:TD,children:(0,t.jsxs)(Ke,{to:"/company/settings/invites",onClick:r(Z=>{if(i){Z.preventDefault();return}U()},"onClick"),children:[(0,t.jsx)("span",{className:"flex size-5 shrink-0 items-center justify-center text-muted-foreground",children:(0,t.jsx)(oh,{className:"size-4"})}),(0,t.jsx)("span",{className:"min-w-0 flex-1 truncate",children:D?`Invite people to ${D}`:"Invite people"})]})}):null,R?.session?(0,t.jsxs)(ls,{className:TD,onClick:r(()=>z.mutate(),"onClick"),disabled:i||z.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:z.isPending?"Signing out...":"Sign out"})]}):null]})]})]})}r(qxt,"BuiltinCompanyMenu");function yie(){const{openNewIssue:e}=al(),[s,n]=(0,m.useState)(!0),[a,i]=(0,m.useState)(!0),{selectedCompanyId:o,selectedCompany:l}=ps(),{collapsed:c,peeking:d}=Wa(),u=c&&!d,h=J8(o),{data:p,isFetched:f}=te({queryKey:M.instance.experimentalSettings,queryFn:r(()=>jr.getExperimental(),"queryFn")}),x=M.liveRuns(o),g=Co({companyId:o,resourceKey:"live-runs",queryKey:x,enabled:!!o,refetchInterval:!1,leaderOnly:!0}),{data:v,dataUpdatedAt:y}=te({queryKey:x,queryFn:r(()=>na.liveRunsForCompany(o),"queryFn"),enabled:g.enabled,refetchInterval:g.refetchInterval});_o(g,v,y);const k=v?.length??0,w=p?.enableIsolatedWorkspaces===!0,N=p?.enableApps===!0,S=p?.enablePipelines===!0,C=p?.enableStatusCards===!0,_=!f,R=p?.enableGoalsSidebarLink===!0,I=p?.enableDecisions===!0,{data:T}=te({queryKey:M.attentionCount(o),queryFn:r(()=>wS.count(o),"queryFn"),enabled:!!o&&I,refetchInterval:6e4}),E=T?.count??0,L=p?.enableCases===!0,O=!0,P=p?.enableConferenceRoomChat===!0,Q={companyId:o,companyPrefix:l?.issuePrefix??null};return(0,t.jsxs)("aside",{className:"w-full h-full min-h-0 border-r border-border bg-background flex flex-col",children:[(0,t.jsx)("div",{className:"flex items-center gap-1 px-3 h-12 shrink-0",children:(0,t.jsx)(zxt,{})}),(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 D=(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)(t5,{className:"h-4 w-4 shrink-0"}),(0,t.jsx)("span",{className:u?Vj:"truncate",children:"New Task"})]});return u?(0,t.jsxs)(Bn,{children:[(0,t.jsx)(On,{asChild:!0,children:D}),(0,t.jsx)($n,{side:"right",children:"New Task"})]}):D})(),(0,t.jsx)(Xa,{to:"/search",label:"Search",icon:Jr}),(0,t.jsx)(Xa,{to:"/dashboard",label:"Dashboard",icon:Fx,liveCount:k}),(0,t.jsx)(Xa,{to:"/inbox",label:"Inbox",icon:Od,badge:h.inbox,badgeLabel:"unread",badgeTone:h.failedRuns>0?"danger":"default",alert:h.failedRuns>0}),I?(0,t.jsx)(Xa,{to:"/decisions",label:"Decisions",icon:ew,badge:E,badgeLabel:"decisions"}):null,C?(0,t.jsx)(Xa,{to:"/status",label:"Status",icon:vS,textBadge:"beta"}):null,P?(0,t.jsx)(Xa,{to:"/board-chat",label:"Conference Room",icon:Pwe}):null]}),(0,t.jsxs)(zx,{label:"Work",collapsible:{open:s,onOpenChange:n},children:[(0,t.jsx)(Xa,{to:"/issues",label:"Tasks",icon:Ju}),L?(0,t.jsx)(Xa,{to:"/cases",label:"Cases",icon:Gl,textBadge:"beta"}):null,(0,t.jsx)(Xa,{to:"/routines",label:"Routines",icon:nm}),S?(0,t.jsx)(Xa,{to:"/pipelines",label:"Pipelines",icon:to}):null,R?(0,t.jsx)(Xa,{to:"/goals",label:"Goals",icon:K0}):_?(0,t.jsx)("div",{"data-testid":"sidebar-goals-placeholder",className:"h-8 pointer-coarse:h-7","aria-hidden":"true"}):null,(0,t.jsx)(Xa,{to:"/artifacts",label:"Artifacts",icon:Xh}),(0,t.jsx)(Xa,{to:"/skills",label:"Skills",icon:_c}),w?(0,t.jsx)(Xa,{to:"/workspaces",label:"Workspaces",icon:to}):null,(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)(Xa,{to:"/projects",label:"Projects",icon:nl}),(0,t.jsx)(Dxt,{})]}),(0,t.jsx)(Y0,{errorBehavior:"hidden",slotTypes:["sidebar"],context:Q,className:"flex flex-col gap-0.5",itemClassName:"text-(length:--text-compact) font-medium",missingBehavior:"placeholder"}),(0,t.jsx)(NS,{errorBehavior:"hidden",placementZones:["sidebar"],context:Q,className:"flex flex-col gap-0.5",itemClassName:"text-(length:--text-compact) font-medium"})]}),null,(0,t.jsx)(Mxt,{streamlined:O}),(0,t.jsxs)(zx,{label:"Company",collapsible:{open:a,onOpenChange:i},children:[(0,t.jsx)(Xa,{to:"/org",label:"Org",icon:Vb}),N?(0,t.jsx)(Xa,{to:"/apps",label:"Connectors",icon:K6}):null,(0,t.jsx)(Xa,{to:"/timeline",label:"Timeline",icon:ub}),(0,t.jsx)(Xa,{to:"/costs",label:"Costs",icon:$0}),(0,t.jsx)(Xa,{to:"/activity",label:"Activity",icon:uc}),(0,t.jsx)(Xa,{to:"/company/settings",label:"Settings",icon:Su})]}),(0,t.jsx)(Y0,{errorBehavior:"hidden",slotTypes:["sidebarPanel"],context:Q,className:"flex flex-col gap-3",itemClassName:"rounded-lg border border-border p-3",missingBehavior:"placeholder"})]})]})}r(yie,"Sidebar");function Uxt(e){const s=e.manifestJson.environmentDrivers??[];return s.length===0?!1:s.every(n=>n.kind==="sandbox_provider")}r(Uxt,"isSandboxProviderOnly");function Kxt(){const{selectedCompany:e,selectedCompanyId:s}=ps(),{isMobile:n,setSidebarOpen:a}=Wa(),{hidden:i}=Au(),{enabled:o}=iw(),l=r(x=>!i.has(x),"showPage"),c=l("instance.plugins"),d=!!ed(),{slots:u}=Bd({slotTypes:["companySettingsPage"],companyId:s,enabled:!!s}),{data:h}=te({queryKey:s?M.sidebarBadges(s):["sidebar-badges","__disabled__"],queryFn:r(async()=>{try{return await JW.get(s)}catch(x){if(x instanceof sn&&(x.status===401||x.status===403))return null;throw x}},"queryFn"),enabled:!!s,retry:!1,refetchInterval:15e3}),{data:p}=te({queryKey:M.plugins.all,queryFn:r(()=>El.list(),"queryFn"),enabled:c}),f=(p??[]).filter(x=>!Uxt(x));return(0,t.jsxs)("aside",{className:"w-full h-full min-h-0 border-r border-border bg-background flex flex-col",children:[(0,t.jsx)("div",{className:"flex flex-col gap-1 px-3 py-3 shrink-0",children:(0,t.jsxs)(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)(um,{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)(Xa,{to:"/company/settings",label:"General",icon:mm,end:!0}),l("instance.profile")&&(0,t.jsx)(Xa,{to:"/company/settings/instance/profile",label:"Profile",icon:K8,end:!0}),l("company.members")&&(0,t.jsx)(Xa,{to:"/company/settings/members",label:"Members",icon:Ho,badge:h?.joinRequests??0,end:!0}),u.filter(x=>x.routePath).map(x=>(0,t.jsx)(Xa,{to:`/company/settings/${x.routePath}`,label:x.displayName,icon:Ox,end:!0},`${x.pluginKey}:${x.id}`)),l("company.invites")&&(0,t.jsx)(Xa,{to:"/company/settings/invites",label:"Invites",icon:xQe,end:!0}),l("company.secrets")&&(0,t.jsx)(Xa,{to:"/company/settings/secrets",label:"Secrets",icon:Ni,end:!0}),l("instance.environments")&&(0,t.jsx)(Xa,{to:"/company/settings/instance/environments",label:"Environments",icon:Fwe,end:!0}),o&&(0,t.jsx)(Xa,{to:"/company/settings/connections",label:"Connections",icon:Ml,end:!0}),l("instance.access")&&(0,t.jsx)(Xa,{to:"/company/settings/instance/access",label:"Access",icon:v3,end:!0}),l("instance.heartbeats")&&(0,t.jsx)(Xa,{to:"/company/settings/instance/heartbeats",label:"Heartbeats",icon:Nu,end:!0}),l("company.export")&&(0,t.jsx)(Xa,{to:"/company/export",label:"Export",icon:Ui}),!d&&l("company.import")&&(0,t.jsx)(Xa,{to:"/company/import",label:"Import",icon:Gb,end:!0}),l("instance.experimental")&&(0,t.jsx)(Xa,{to:"/company/settings/instance/experimental",label:"Experimental",icon:Jm}),c&&(0,t.jsx)(Xa,{to:"/company/settings/instance/plugins",label:"Plugins",icon:Ox}),c&&f.length>0?(0,t.jsx)("div",{className:"ml-4 mt-1 flex flex-col gap-0.5 border-l border-border/70 pl-3",children:f.map(x=>(0,t.jsx)(dv,{to:`${N0}/plugins/${x.id}`,state:If,className:r(({isActive:g})=>["rounded-md px-2 py-1.5 text-xs transition-colors",g?"bg-accent text-foreground":"text-muted-foreground hover:bg-accent/50 hover:text-foreground"].join(" "),"className"),children:x.manifestJson.displayName??x.packageName},x.id))}):null,l("instance.adapters")&&(0,t.jsx)(Xa,{to:"/company/settings/instance/adapters",label:"Adapters",icon:qm})]})})]})}r(Kxt,"CompanySettingsSidebar");function Qxt(){const{pathname:e}=ua(),{selectedCompany:s}=ps(),{isMobile:n,setSidebarOpen:a}=Wa(),i=ENe(),{enabled:o}=X8(),l=rH.filter(d=>!RNe(d.key)||o);if(e.endsWith("/apps/chat/connect"))return(0,t.jsx)(TNe,{NavItem:Xa});const c=e.match(/\/apps\/chat\/([^/]+)(?:\/(?:settings|access|conversations|activity|approvals|audit)|\/reviews(?:\/[^/]+)?)?\/?$/);return c?(0,t.jsx)(tH,{endpointId:c[1],NavItem:Xa}):(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)(um,{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)(Ste,{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)(Xa,{to:"/apps",label:"Browse",icon:s5,end:!0}),(0,t.jsx)(Xa,{to:"/apps/review",label:"Review",icon:yS,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)(Xa,{to:"/apps/connections",label:"Connections",icon:Ste,end:!0}),l.map(d=>(0,t.jsx)(Xa,{to:Ib(d.key),label:d.label,icon:d.icon,end:!0},d.key))]})]})]})}r(Qxt,"AppsSidebar");function jie(e){const{selectedCompanyId:s}=ps(),{isMobile:n,setSidebarOpen:a}=Wa(),i=te({queryKey:M.tools.connection(e.kind==="connection"?e.connectionId:"__none__"),queryFn:r(()=>ts.getConnection(e.kind==="connection"?e.connectionId:""),"queryFn"),enabled:e.kind==="connection"&&!!e.connectionId}),o=te({queryKey:M.tools.applications(s??"__none__"),queryFn:r(()=>ts.listApplications(s),"queryFn"),enabled:e.kind==="application"&&!!s}),l=te({queryKey:M.tools.connections(s??"__none__"),queryFn:r(()=>ts.listConnections(s),"queryFn"),enabled:e.kind==="application"&&!!s}),c=te({queryKey:M.apps.gallery(s??"__none__"),queryFn:r(()=>ts.listGallery(s),"queryFn"),enabled:!!s}),d=te({queryKey:M.apps.attention(s??"__none__"),queryFn:r(()=>ts.listAppsAttention(s),"queryFn"),enabled:!!s,refetchInterval:3e4}),u=i.data,h=e.kind==="application"?(o.data?.applications??[]).find(k=>k.id===e.applicationId):null,p=Vxt(e.kind==="application"?(l.data?.connections??[]).filter(k=>k.applicationId===e.applicationId):[]),f=u?bf(u):h?.name??"App",x=Hxt(c.data?.apps??[],u,h??void 0),g=u?.id??p?.id??null,v=g?d.data?.apps.find(k=>k.connection.id===g):null,y=(v?.pendingActionRequestCount??0)+((v?.quarantinedCatalogEntryCount??0)>0?1:0);return(0,t.jsxs)("aside",{className:"flex h-full min-h-0 w-full flex-col border-r border-border bg-background",children:[(0,t.jsxs)("div",{className:"flex shrink-0 flex-col gap-3 px-3 py-3",children:[(0,t.jsxs)(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)(um,{className:"h-3.5 w-3.5 shrink-0"}),(0,t.jsx)("span",{className:"truncate",children:"All apps"})]}),(0,t.jsxs)("div",{className:"flex min-w-0 items-center gap-2 px-2 py-1",children:[(0,t.jsx)(Vi,{name:f,logoUrl:K3(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:eM.map(k=>(0,t.jsx)(Xa,{to:Wxt(e,k.key),label:k.label,icon:k.icon,end:!0,badge:k.key==="review"&&y>0?y:void 0,badgeTone:"danger",badgeLabel:"needing review"},k.key))})})]})}r(jie,"AppDetailSidebar");function Wxt(e,s){return e.kind==="connection"?Bm(e.connectionId,s):l_(e.applicationId,s)}r(Wxt,"tabHref");function Hxt(e,s,n){if(n?.applicationKey){const i=e.find(o=>wc(o)===n.applicationKey);if(i)return i}const a=(s?.name??n?.name)?.toLowerCase();return a?e.find(i=>qx(i).toLowerCase()===a)??e.find(i=>wc(i)===a)??null:null}r(Hxt,"galleryEntryFor$1");function Vxt(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(Vxt,"latestArchivedConnection$1");function RD({identifier:e}){return e?(0,t.jsx)("span",{className:"shrink-0 font-mono text-muted-foreground",children:e}):null}r(RD,"CrumbIdentifier");function Gxt({context:e}){const{slots:s}=Bd({slotTypes:["globalToolbarButton"],companyId:e.companyId}),{launchers:n}=eH({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)(Y0,{slotTypes:["globalToolbarButton"],context:e,className:"flex items-center gap-1"}):null,n.length>0?(0,t.jsx)(NS,{placementZones:["globalToolbarButton"],context:e,className:"flex items-center gap-1"}):null]})}r(Gxt,"GlobalToolbar");function Yxt(){const{breadcrumbs:e,mobileToolbar:s}=Wn(),{toggleSidebar:n,isMobile:a}=Wa(),{selectedCompanyId:i,selectedCompany:o}=ps(),l=(0,m.useMemo)(()=>({companyId:i??null,companyPrefix:o?.issuePrefix??null}),[i,o?.issuePrefix]),c=(0,t.jsx)(Gxt,{context:l});if(a&&s)return(0,t.jsx)("div",{className:"border-b border-border px-2 h-12 shrink-0 flex items-center",children:s});if(e.length===0)return(0,t.jsx)("div",{className:"border-b border-border px-4 md:px-6 h-12 shrink-0 flex items-center justify-end",children:c});const d=a&&(0,t.jsx)($,{variant:"ghost",size:"icon-sm",className:"mr-2 shrink-0",onClick:n,"aria-label":"Open sidebar",children:(0,t.jsx)(Cwe,{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)(RD,{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)(aH,{className:"min-w-0 overflow-hidden",children:(0,t.jsx)(iH,{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)(eE,{}),(0,t.jsx)(c_,{className:p?"min-w-0":"shrink-0",children:p||!u.href?u.leading||u.identifier?(0,t.jsxs)(l5,{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)(RD,{identifier:u.identifier}),(0,t.jsx)("span",{className:"truncate",children:u.label})]}):(0,t.jsx)(l5,{className:"truncate",children:u.label}):(0,t.jsx)(X6,{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)(RD,{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(Yxt,"BreadcrumbBar");var VI=240,uq=208,mq=420,wie=16;function HE(e){return Math.min(mq,Math.max(uq,e))}r(HE,"clampSidebarWidth");function kie(e){if(typeof window>"u")return VI;try{const s=window.localStorage.getItem(e);if(!s)return VI;const n=Number.parseInt(s,10);return Number.isFinite(n)?HE(n):VI}catch{return VI}}r(kie,"readStoredSidebarWidth");function Nie(e,s){if(!(typeof window>"u"))try{window.localStorage.setItem(e,String(HE(s)))}catch{}}r(Nie,"writeStoredSidebarWidth");function Zxt({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)(()=>kie(o)),[x,g]=(0,m.useState)(!1),v=(0,m.useRef)(p),y=(0,m.useRef)(null);(0,m.useEffect)(()=>{const P=kie(o);v.current=P,f(P)},[o]);const k=s?p:0,w=s?n?64:k:0,N=s?n&&!a?64:k:0,S=N>w,C=i&&s&&!n,_=(0,m.useMemo)(()=>({width:`${w}px`}),[w]),R=(0,m.useMemo)(()=>({width:`${N}px`}),[N]),I=(0,m.useCallback)(P=>{const Q=HE(P);v.current=Q,f(Q),Nie(o,Q)},[o]),T=(0,m.useCallback)(P=>{C&&(P.preventDefault(),P.currentTarget.setPointerCapture(P.pointerId),y.current={startX:P.clientX,startWidth:v.current},g(!0))},[C]),E=(0,m.useCallback)(P=>{if(!y.current)return;const Q=HE(y.current.startWidth+P.clientX-y.current.startX);v.current=Q,f(Q)},[]),L=(0,m.useCallback)(()=>{y.current&&(y.current=null,g(!1),Nie(o,v.current))},[o]),O=(0,m.useCallback)(P=>{C&&(P.key==="ArrowLeft"?(P.preventDefault(),I(p-wie)):P.key==="ArrowRight"?(P.preventDefault(),I(p+wie)):P.key==="Home"?(P.preventDefault(),I(uq)):P.key==="End"&&(P.preventDefault(),I(mq)))},[C,I,p]);return(0,t.jsx)("div",{className:W("relative h-full shrink-0",l),style:_,children:(0,t.jsxs)("div",{className:W("absolute inset-y-0 left-0 flex flex-col overflow-hidden",S?"z-30 border-r border-border bg-background shadow-lg":"z-0"),style:R,"data-sidebar-overlay":S?"":void 0,onMouseEnter:c,onMouseLeave:d,onFocusCapture:u,onBlurCapture:h,children:[e,C?(0,t.jsx)("div",{role:"separator","aria-label":"Resize sidebar","aria-orientation":"vertical","aria-valuemin":uq,"aria-valuemax":mq,"aria-valuenow":p,tabIndex:0,className:W("absolute inset-y-0 right-0 z-20 w-3 cursor-col-resize touch-none outline-none","before:absolute before:inset-y-0 before:left-1/2 before:w-px before:-translate-x-1/2 before:bg-transparent before:transition-colors","hover:before:bg-border focus-visible:before:bg-ring",x&&"before:bg-ring"),onPointerDown:T,onPointerMove:E,onPointerUp:L,onPointerCancel:L,onLostPointerCapture:L,onKeyDown:O}):null]})})}r(Zxt,"SidebarShell");function Jxt({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)(Axt,{children:e})})}r(Jxt,"SecondarySidebar");var Xxt="/company/settings/members?tab=invites",egt="https://docs.paperclip.ing/",tgt="https://paperclip.ing/feedback";function sgt(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(sgt,"deriveInitials$1");function Sie({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(Sie,"MenuAction");function Cie({deploymentMode:e,open:s,onOpenChange:n}){const i=!!ed(),{hidden:o,loaded:l}=Au(),c=g3e(),d=b3e(!i),u=i?c:d?Xxt:null,h=l&&u!==null&&!Gx(o,"company.members")&&!Gx(o,"company.invites"),[p,f]=(0,m.useState)(!1),{isMobile:x,setSidebarOpen:g,collapsed:v,peeking:y}=Wa(),k=v&&!y,w=s??p,N=v3e(w),S=n??f,{data:C}=te({queryKey:M.auth.session,queryFn:r(()=>Ma.getSession(),"queryFn"),retry:!1}),_=SS({onSignedOut:L}),R=C?.user.name?.trim()||"Board",I=C?.user.email?.trim()||(e==="authenticated"?"Signed in":"Local workspace board"),T=sgt(R),E=y3e(C?.user);function L(){S(!1),x&&g(!1)}r(L,"closeNavigationChrome");function O(){_.mutate()}return r(O,"handleSignOut"),(0,t.jsx)("div",{className:"border-t border-r border-border bg-background px-3 py-2",children:(0,t.jsxs)("div",{className:W("flex items-center gap-0.5",!k&&"px-2"),children:[(0,t.jsxs)(dr,{open:w,onOpenChange:S,children:[(0,t.jsx)(wr,{asChild:!0,children:(0,t.jsxs)("button",{type:"button",className:W("flex min-w-0 items-center gap-2.5 rounded-lg text-left text-(length:--text-compact) font-medium text-foreground/80 transition-colors hover:bg-accent/50 hover:text-foreground",k?"w-full px-3 py-2":"flex-1 px-2 py-1.5"),"aria-label":"Open account menu",children:[(0,t.jsxs)(ko,{size:"sm",children:[C?.user.image?(0,t.jsx)(Zc,{src:C.user.image,alt:R}):null,(0,t.jsx)(No,{children:T})]}),(0,t.jsx)("span",{className:W("min-w-0 flex-1 truncate",k&&"block w-0 min-w-0 overflow-hidden whitespace-nowrap text-transparent select-none"),children:R})]})}),(0,t.jsxs)(sr,{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:E,"aria-label":"View profile",onClick:L,className:"absolute inset-0 rounded-xl transition-colors hover:bg-accent/60 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"}),(0,t.jsx)("div",{className:"pointer-events-none relative rounded-2xl border-4 border-popover bg-popover p-0.5 shadow-sm",children:(0,t.jsxs)(ko,{size:"lg",children:[C?.user.image?(0,t.jsx)(Zc,{src:C.user.image,alt:R}):null,(0,t.jsx)(No,{children:T})]})}),(0,t.jsxs)("div",{className:"pointer-events-none relative min-w-0 flex-1 pt-1",children:[(0,t.jsx)("h2",{className:"truncate text-base font-semibold text-foreground",children:R}),(0,t.jsx)("p",{className:"truncate text-sm text-muted-foreground",children:I}),N?(0,t.jsxs)("a",{className:"pointer-events-auto block truncate font-mono text-(length:--text-micro) leading-(--profile-popover-meta-line-height) text-muted-foreground hover:underline focus-visible:underline",href:`https://github.com/paperclipai/paperclip/commit/${N}`,target:"_blank",rel:"noreferrer","aria-label":`View commit ${N} on GitHub`,title:N,children:["SHA ",N.slice(0,7)]}):null]})]}),(0,t.jsxs)("div",{className:"mt-4 space-y-1",children:[h&&u?(0,t.jsx)(Sie,{label:"Invite",description:"Invite people to your organization.",icon:oh,href:u,topLevel:i,onClick:L}):null,(0,t.jsx)(Sie,{label:"Documentation",description:"Open Paperclip docs in a new tab.",icon:bS,href:egt,external:!0,onClick:r(()=>S(!1),"onClick")}),(0,t.jsx)(Lk,{variant:"menu-action",onAfterToggle:r(()=>S(!1),"onAfterToggle")}),(0,t.jsx)(k3e,{variant:"menu-action",onAfterAction:r(()=>S(!1),"onAfterAction")}),e==="authenticated"?(0,t.jsxs)("button",{type:"button",className:W("flex w-full items-start gap-3 rounded-xl px-3 py-3 text-left transition-colors hover:bg-destructive/10",_.isPending&&"cursor-not-allowed opacity-60"),onClick:O,disabled:_.isPending,children:[(0,t.jsx)("span",{className:"mt-0.5 rounded-lg border border-border bg-background/70 p-2 text-muted-foreground",children:(0,t.jsx)(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:_.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)(N3e,{})]})]})]})]}),!k&&!i?(0,t.jsxs)(Bn,{children:[(0,t.jsx)(On,{asChild:!0,children:(0,t.jsx)("a",{href:tgt,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)(fg,{className:"h-4 w-4","aria-hidden":"true"})})}),(0,t.jsx)($n,{side:"top",children:"Share feedback"})]}):null]})})}r(Cie,"SidebarAccountMenu");function ngt(e,s){return $3e(e,s)[0]?.toLowerCase()??null}r(ngt,"getCompanyRouteSegment");function $3e(e,s){if(!s)return[];const n=e.split("/").filter(Boolean);return n.length<2?[]:n[0]?.toUpperCase()!==s.toUpperCase()?[]:n.slice(1)}r($3e,"getCompanyPathSegments");var rgt=new Set(["browse","connections","connect","chat","review","attention","gateways","advanced","app"]);function agt(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(agt,"isSkillsStoreRoute");function igt(){const{sidebarOpen:e,setSidebarOpen:s,toggleSidebar:n,collapsed:a,peeking:i,setPeeking:o,isMobile:l,setForceCollapsed:c}=Wa(),{openNewIssue:d,openOnboarding:u}=al(),{togglePanelVisible:h}=Rf(),p=bd()?.pushToast??null,{companies:f,loading:x,selectedCompany:g,selectedCompanyId:v,selectionSource:y,setSelectedCompanyId:k}=ps(),{companyPrefix:w,pluginRoutePath:N}=ga(),S=Yn(),C=ua(),_=C8(),R=CNe(C.pathname,w).isTaskDetail,I=["/company/settings","/company/export","/company/import"].some(gt=>C.pathname.includes(gt)),T=$3e(C.pathname,w),E=T[0]?.toLowerCase()==="tools",L=T[0]?.toLowerCase()==="apps",O=L&&T[1]&&!rgt.has(T[1].toLowerCase())?T[1]:null,P=L&&T[1]?.toLowerCase()==="app"&&T[2]?T[2]:null,Q=agt(C.pathname,w),D=(0,m.useRef)(!1),F=(0,m.useRef)(null),z=(0,m.useRef)(null),K=(0,m.useRef)(new Dke),U=(0,m.useRef)(C.key),q=T3e(l&&!R,C.pathname),[G,se]=(0,m.useState)(!1),Z=(0,m.useMemo)(()=>{if(!w)return null;const gt=w.toUpperCase();return f.find(Xe=>Xe.issuePrefix.toUpperCase()===gt)??null},[f,w]),ie=!!w&&!x&&f.length>0&&!Z,J=(0,m.useMemo)(()=>N?.toLowerCase()??ngt(C.pathname,w),[w,C.pathname,N]),re=Z?.id??null,oe=Z?.issuePrefix??null,{slots:V}=Bd({slotTypes:["page","routeSidebar"],companyId:re,enabled:!!(re&&J)}),X=(0,m.useMemo)(()=>GW(V,J),[J,V]),Y=(0,m.useMemo)(()=>({companyId:re,companyPrefix:oe}),[re,oe]),ae=I?(0,t.jsx)(Kxt,{}):O?(0,t.jsx)(jie,{kind:"connection",connectionId:O}):P?(0,t.jsx)(jie,{kind:"application",applicationId:P}):L||E?(0,t.jsx)(Qxt,{}):X?(0,t.jsx)(pm,{slot:X,context:Y,className:"h-full w-full",missingBehavior:"placeholder"}):null,ne=ae!=null,{data:ce}=te({queryKey:M.health,queryFn:r(()=>Iu.get(),"queryFn"),retry:!1,refetchInterval:r(gt=>gt.state.data?.devServer?.enabled?2e3:!1,"refetchInterval"),refetchIntervalInBackground:!1}),he=ne||Q;(0,m.useLayoutEffect)(()=>(c(he),()=>c(!1)),[he,c]),(0,m.useEffect)(()=>{x||D.current||ce?.deploymentMode!=="authenticated"&&(ce?.cloud||f.length===0&&(D.current=!0,u()))},[f,x,u,ce?.cloud,ce?.deploymentMode]),(0,m.useEffect)(()=>{if(!w||x||f.length===0)return;if(!Z){const Xe=(v?f.find(Fe=>Fe.id===v):null)??f[0]??null;Xe&&v!==Xe.id&&k(Xe.id,{source:"route_sync"});return}if(w!==Z.issuePrefix){const Xe=C.pathname.replace(/^\/[^/]+/,"");S(`/${Z.issuePrefix}${Xe}${C.search}`,{replace:!0});return}const gt=R3e({matchedCompany:Z,selectedCompanyId:v,companies:f});if(gt){p?.({title:`${Z.name} is archived`,body:`Switched to ${gt.name}.`,tone:"info",dedupeKey:`archived-company-bounce:${Z.id}`}),k(gt.id,{source:"route_sync"}),S(`/${gt.issuePrefix}/dashboard`,{replace:!0});return}E3e({selectionSource:y,selectedCompanyId:v,routeCompanyId:Z.id})&&k(Z.id,{source:"route_sync"})},[w,f,x,Z,C.pathname,C.search,S,p,y,v,k]);const pe=h,ge=(0,m.useCallback)(()=>{document.dispatchEvent(new KeyboardEvent("keydown",{key:"k",metaKey:!0,bubbles:!0,cancelable:!0}))},[]),Ee=(0,m.useRef)(null),de=(0,m.useRef)(!1),Ne=(0,m.useRef)(!1),le=(0,m.useCallback)(()=>{Ee.current!==null&&(window.clearTimeout(Ee.current),Ee.current=null)},[]),Le=(0,m.useCallback)(()=>{le(),Ee.current=window.setTimeout(()=>o(!0),50)},[le,o]),Ie=(0,m.useCallback)(()=>{le(),o(!0)},[le,o]),ye=(0,m.useCallback)(()=>{le(),Ee.current=window.setTimeout(()=>o(!1),120)},[le,o]),Ae=(0,m.useCallback)(()=>{de.current=!0,a&&!Ne.current&&Le()},[a,Le]),Qe=(0,m.useCallback)(()=>{de.current=!1,Ne.current=!1,ye()},[ye]),ue=(0,m.useCallback)(()=>{Ne.current||Ie()},[Ie]),Be=(0,m.useCallback)(()=>{de.current||ye()},[ye]);(0,m.useEffect)(()=>le,[le]);const ft=(0,m.useRef)(a);return(0,m.useEffect)(()=>{a!==ft.current&&(a?(le(),o(!1),Ne.current=de.current):Ne.current=!1,ft.current=a)},[a,le,o]),(0,m.useEffect)(()=>{if(!i)return;const gt=r(Xe=>{Xe.key==="Escape"&&(le(),o(!1))},"onKeyDown");return window.addEventListener("keydown",gt),()=>window.removeEventListener("keydown",gt)},[i,le,o]),I3e(),S3e({onNewIssue:r(()=>d(),"onNewIssue"),onSearch:ge,onToggleSidebar:n,onTogglePanel:pe,onShowShortcuts:r(()=>se(!0),"onShowShortcuts"),onGoToInbox:r(()=>S("/inbox"),"onGoToInbox")}),(0,m.useEffect)(()=>{if(!l)return;const gt=30,Xe=50,Fe=75;let at=0,Tt=0;const Dt=r(rt=>{const Pe=rt.touches[0];at=Pe.clientX,Tt=Pe.clientY},"onTouchStart"),Ot=r(rt=>{const Pe=rt.changedTouches[0],De=Pe.clientX-at;if(!(Math.abs(Pe.clientY-Tt)>Fe)){if(!e&&at<gt&&De>Xe){s(!0);return}e&&De<-50&&s(!1)}},"onTouchEnd");return document.addEventListener("touchstart",Dt,{passive:!0}),document.addEventListener("touchend",Ot,{passive:!0}),()=>{document.removeEventListener("touchstart",Dt),document.removeEventListener("touchend",Ot)}},[l,e,s]),(0,m.useEffect)(()=>{const gt=document.body.style.overflow;return document.body.style.overflow=l?"visible":"clip",()=>{document.body.style.overflow=gt}},[l]),(0,m.useEffect)(()=>{if(!l)return M3e()},[l]),(0,m.useEffect)(()=>{if(typeof document>"u")return;const gt=z.current;return L3e(gt)},[C.pathname]),(0,m.useEffect)(()=>{const gt=z.current;if(!gt)return;const Xe=r(()=>{K.current.remember(U.current,gt.scrollTop)},"recordScroll");return gt.addEventListener("scroll",Xe,{passive:!0}),()=>gt.removeEventListener("scroll",Xe)},[]),(0,m.useLayoutEffect)(()=>{const gt=z.current,Xe=Pke({previousPathname:F.current,pathname:C.pathname,navigationType:_,state:C.state});F.current=C.pathname;const Fe=_==="POP",at=Fe?K.current.recall(C.key):0;if(U.current=C.key,Fe){W6(gt,at);const Tt=requestAnimationFrame(()=>W6(gt,at));return()=>cancelAnimationFrame(Tt)}Xe&&$ke(gt)},[C.key,C.pathname,C.state,_]),(0,t.jsx)(Lke,{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)(a3e,{}),(0,t.jsx)(i3e,{devServer:ce?.devServer}),(0,t.jsxs)("div",{className:W("min-h-0 flex-1",l?"w-full":"flex overflow-clip"),children:[l&&e&&(0,t.jsx)("button",{type:"button",className:"fixed inset-0 z-40 bg-black/50",onClick:r(()=>s(!1),"onClick"),"aria-label":"Close sidebar"}),l?(0,t.jsxs)("div",{className:W("fixed inset-y-0 left-0 z-50 flex flex-col overflow-hidden pt-(--sz-safe-top) transition-transform duration-100 ease-out",e?"translate-x-0":"-translate-x-full"),children:[(0,t.jsx)("div",{className:"flex flex-1 min-h-0 overflow-hidden",children:(0,t.jsx)("div",{className:"w-60 shrink-0 overflow-hidden",children:ne?ae:(0,t.jsx)(yie,{})})}),(0,t.jsx)(Cie,{deploymentMode:ce?.deploymentMode})]}):(0,t.jsxs)(Zxt,{open:e,collapsed:a,peeking:i,resizable:!0,onPanelMouseEnter:Ae,onPanelMouseLeave:Qe,onPanelFocusCapture:a?ue:void 0,onPanelBlurCapture:a?Be:void 0,children:[(0,t.jsx)("div",{className:"flex flex-1 min-h-0",children:(0,t.jsx)(yie,{})}),(0,t.jsx)(Cie,{deploymentMode:ce?.deploymentMode})]}),!l&&ne?(0,t.jsx)(Jxt,{children:ae}):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)(aq,{mobile:l,onNavigateHome:r(()=>S("/dashboard"),"onNavigateHome")}),(0,t.jsx)(Yxt,{}),l&&I?(0,t.jsx)("div",{className:"border-b border-border px-4 pb-3",children:(0,t.jsx)(INe,{})}):null]}),(0,t.jsxs)("div",{className:W(l?"block":"flex flex-1 min-h-0"),children:[(0,t.jsx)("main",{id:"main-content",ref:z,tabIndex:-1,style:l?{"--tc-composer-bottom":"var(--sz-calc-14)"}:void 0,className:W("flex-1 p-4 outline-none md:p-6",l?"overflow-visible pb-(--sz-calc-14)":"overflow-auto [scrollbar-gutter:stable]"),children:ie?(0,t.jsx)(om,{scope:"invalid_company_prefix",requestedPrefix:w??g?.issuePrefix}):(0,t.jsx)(c3e,{children:(0,t.jsx)(cv,{})})}),(0,t.jsx)(zNe,{})]})]})]}),l&&(0,t.jsx)(r3e,{visible:q}),(0,t.jsx)(qNe,{}),(0,t.jsx)(CSe,{}),(0,t.jsx)(p5e,{}),(0,t.jsx)(g5e,{}),(0,t.jsx)(j5e,{}),(0,t.jsx)(w5e,{open:G,onOpenChange:se}),(0,t.jsx)(k5e,{}),(0,t.jsx)(s3e,{companyId:v}),(0,t.jsx)(n3e,{localTrusted:ce?.deploymentMode==="local_trusted"})]})})}r(igt,"Layout");var _ie=null;function ogt(){return _ie??=new rS,_ie}r(ogt,"getDetachedClient");function lgt(){const e=(0,m.useContext)(h3),{data:s,isFetched:n}=te({queryKey:M.instance.experimentalSettings,queryFn:r(()=>jr.getExperimental(),"queryFn"),enabled:e!=null},e??ogt());return e?{enabled:s?.enableConferenceRoomChat===!0,loaded:n}:{enabled:!1,loaded:!0}}r(lgt,"useConferenceRoomChatEnabled");function cgt(){const{enabled:e,loaded:s}=lgt();return s?e?(0,t.jsx)(cv,{}):(0,t.jsx)(_n,{to:"/dashboard",replace:!0}):null}r(cgt,"ConferenceRoomChatGate");var dgt=["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"],ugt={"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 }"}},eys=dgt.map(e=>ugt[e]);function O3e({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)(gm,{className:"size-4 shrink-0 text-muted-foreground","aria-hidden":!0}),(0,t.jsx)("span",{children:s}),(0,t.jsxs)("span",{className:"text-muted-foreground",children:["· ",e.status]}),n&&(0,t.jsx)($,{variant:"ghost",size:"sm",onClick:r(()=>n(e.id),"onClick"),children:a?"View session":"Open browser"})]})}r(O3e,"TaskBrowserActivity");function B3e({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)(lQe,{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)(to,{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(B3e,"TaskChatProjectCreatedCard");function mgt({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)(hf,{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(mgt,"TaskChatSkillCreatedCard");function hgt(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(hgt,"McpIcon");var pgt=new Set(["tool","tool call","tool_call","acp_tool"]);function ju(e){const s=(e??"").trim().toLowerCase().replace(/\s*\((?:pending|in[_ -]?progress|completed|failed|cancelled|canceled)\)$/,"");return!s||pgt.has(s)}r(ju,"isGenericToolName");function HV(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(HV,"mcpToolIdentity");function VV(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(VV,"identifierWords");function F3e(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(F3e,"sentenceCase");function Mk(e){const s=(e??"").trim();return ju(s)?"Unnamed tool":F3e(VV(HV(s)?.name??s))}r(Mk,"humanizeToolName");var Wd=r((e,s,n)=>({key:e,singular:s,plural:n}),"group"),fgt={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:Wd("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:Wd("task_operation","task operation","task operations")},task_create:{action:"create",running:"Creating a task",completed:"Created a task",family:"plan",group:Wd("task_operation","task operation","task operations")},task_update:{action:"update",running:"Updating a task",completed:"Updated a task",family:"plan",group:Wd("task_operation","task operation","task operations")},task_list:{action:"list",running:"Listing tasks",completed:"Listed tasks",family:"plan",group:Wd("task_operation","task operation","task operations")},task_get:{action:"read",running:"Reading a task",completed:"Read a task",family:"plan",group:Wd("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:Wd("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"}},xgt={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:[]},ggt={read:"read",edit:"update",delete:"delete",move:"move",search:"search",list:"list",execute:"run",think:"think",fetch:"fetch",switch_mode:"switch"};function bgt(e){return VV(e).join("_")}r(bgt,"normalizedKey");function vgt(e){const s=e[0];if(!s)return null;for(const[n,a]of Object.entries(xgt))if(a.includes(s))return n;return null}r(vgt,"inferredAction");function ygt(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(ygt,"actionFamily");var jgt={terminal:pf,grep:AQe,search:Jr,read:bS,edit:O8,web:GKe,plan:ew,question:Ac,agent:Vb,safety:qi,image:D3,wait:Nu,mcp:hgt,other:hf};function wgt(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(wgt,"actionCopy");function kgt(e){switch(e){case"run":return Wd("command","command","commands");case"read":case"list":return Wd("read","read","reads");case"search":return Wd("search","search","searches");case"update":case"create":case"delete":case"move":return Wd("file_change","file change","file changes");case"start":case"stop":return Wd("delegation","delegation","delegations");case"wait":return Wd("wait","wait","waits");default:return Wd("tool_action","tool action","tool actions")}}r(kgt,"defaultSummaryGroup");function Ngt(e){return e==="read"||e==="list"?Wd("paperclip_read","Paperclip read","Paperclip reads"):Wd("task_operation","task operation","task operations")}r(Ngt,"paperclipSummaryGroup");function Tj(e){const s=(e.name??"").trim(),n=HV(s),a=(e.namespace??n?.namespace??"").trim(),i=(n?"mcp":e.transport??"builtin").toLowerCase(),o=(n?.name??s).trim(),l=VV(o),c=bgt(o),d=fgt[c],u=ggt[(e.operation??"").trim().toLowerCase()],h=vgt(l),p=d?.action??u??h??"other",f=d?"exact":u?"kind":h?"inferred":ju(o)?"unnamed":"fallback",x=ju(o)?"Unnamed tool":Mk(o),g=/^[A-Za-z][A-Za-z0-9_.:-]*$/.test(o),v=h&&g&&l.length>1?l.slice(1):[],y=v.length?F3e(v).replace(/^./,_=>_.toLowerCase()):void 0,k=d?.running&&d.completed?{running:d.running,completed:d.completed}:p==="other"?ju(o)?{running:"Running an unnamed tool",completed:"Ran an unnamed tool"}:{running:`Running ${x}`,completed:`Ran ${x}`}:wgt(p,d?void 0:y),w=d?.family??ygt(p),N=i==="mcp"?"mcp":w,S=a?Mk(a):i==="mcp"?"MCP":void 0,C=a.toLowerCase()==="paperclip"?Ngt(p):d?.group??kgt(p);return{icon:jgt[N],family:N,runningLabel:k.running,completedLabel:k.completed,failedLabel:`${k.completed} · failed`,interruptedLabel:`${k.running} · stopped`,displayName:x,sourceLabel:S,technicalName:s||void 0,confidence:f,summaryGroup:C}}r(Tj,"toolActivityPresentation");function EN(e){const s=Tj({name:e});return{family:s.family,icon:s.icon,verbLabel:s.runningLabel}}r(EN,"toolTaxonomy");function z3e(e){const s=(e??"").trim().toLowerCase();return s==="thinking"?$x:s==="responding"||s.startsWith("responding (")?gQe:null}r(z3e,"statusLabelIcon");var ED=["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"],LD=["Brewing","Tinkering","Distilling","Deliberating"],Aie=(()=>{const e=[],s=Math.max(ED.length,LD.length);for(let n=0;n<s;n++)n<ED.length&&e.push(ED[n]),n<LD.length&&e.push(LD[n]);return e})(),Sgt=1e4;function Cgt(e){const s=(e??"").trim().toLowerCase();return s==="running"||s==="working"}r(Cgt,"isGenericStatusLabel");function _gt(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(_gt,"fnv1a");function Agt(e,s=0){const n=Math.floor(Math.max(0,s)/Sgt);return Aie[(_gt(e)+n)%Aie.length]}r(Agt,"whimsyWord");var Igt=[{name:"--motion-ease-out-expo",group:"Easing",kind:"easing"},{name:"--motion-ease-standard",group:"Easing",kind:"easing"},{name:"--motion-ease-out",group:"Easing",kind:"easing"},{name:"--motion-ease-scroll-pill-in",group:"Easing",kind:"easing"},{name:"--motion-ease-scroll-pill-out",group:"Easing",kind:"easing"},{name:"--motion-ease-in",group:"Easing",kind:"easing"},{name:"--motion-duration-instant",group:"Durations",kind:"time",min:0,max:1e3,step:10},{name:"--motion-duration-fast",group:"Durations",kind:"time",min:0,max:1e3,step:10},{name:"--motion-duration-base",group:"Durations",kind:"time",min:0,max:1e3,step:10},{name:"--motion-duration-slow",group:"Durations",kind:"time",min:0,max:1500,step:10},{name:"--motion-duration-deliberate",group:"Durations",kind:"time",min:0,max:2e3,step:10},{name:"--motion-duration-enter",group:"Durations",kind:"time",min:0,max:1e3,step:10},{name:"--motion-duration-exit",group:"Durations",kind:"time",min:0,max:1e3,step:10},{name:"--motion-duration-swap",group:"Durations",kind:"time",min:0,max:1e3,step:10},{name:"--motion-marker-enter",group:"States",kind:"time",min:0,max:1500,step:10},{name:"--motion-bubble-enter",group:"States",kind:"time",min:0,max:1500,step:10},{name:"--motion-cot-line-stagger",group:"States",kind:"time",min:0,max:300,step:5},{name:"--motion-cot-collapse",group:"States",kind:"time",min:0,max:1500,step:10},{name:"--motion-tool-enter",group:"States",kind:"time",min:0,max:1500,step:10},{name:"--motion-diff-reveal",group:"States",kind:"time",min:0,max:1500,step:10},{name:"--motion-status-enter",group:"States",kind:"time",min:0,max:1500,step:10},{name:"--motion-status-exit",group:"States",kind:"time",min:0,max:1500,step:10},{name:"--motion-approval-pulse",group:"States",kind:"time",min:0,max:3e3,step:20},{name:"--motion-plan-entry-stagger",group:"States",kind:"time",min:0,max:300,step:5},{name:"--motion-plan-check",group:"States",kind:"time",min:0,max:1500,step:10},{name:"--motion-question-page-enter",group:"States",kind:"time",min:0,max:1e3,step:10},{name:"--motion-count-tween",group:"States",kind:"time",min:0,max:1500,step:10},{name:"--motion-streaming-cursor-blink",group:"States",kind:"time",min:0,max:3e3,step:20},{name:"--motion-turn-fold",group:"States",kind:"time",min:0,max:1500,step:10},{name:"--motion-turn-meta",group:"States",kind:"time",min:0,max:1500,step:10},{name:"--motion-line-scroll",group:"States",kind:"time",min:0,max:1500,step:10},{name:"--motion-interstitial-dwell",group:"States",kind:"time",min:0,max:1e4,step:100},{name:"--motion-scroll-pill-enter",group:"States",kind:"time",min:0,max:1500,step:10},{name:"--motion-scroll-pill-exit",group:"States",kind:"time",min:0,max:1500,step:10},{name:"--motion-mobile-nav-enter",group:"States",kind:"time",min:0,max:1500,step:10},{name:"--motion-mobile-nav-exit",group:"States",kind:"time",min:0,max:1500,step:10},{name:"--motion-scrollbar-idle-delay",group:"States",kind:"time",min:0,max:2e3,step:10},{name:"--motion-pane-glide",group:"States",kind:"time",min:0,max:1500,step:10},{name:"--motion-side-panel-tab",group:"States",kind:"time",min:0,max:1500,step:10},{name:"--motion-live-now-sweep",group:"States",kind:"time",min:0,max:5e3,step:100},{name:"--motion-live-now-breathe",group:"States",kind:"time",min:0,max:5e3,step:100}],tys=Array.from(new Set(Igt.map(e=>e.group)));function q3e(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(q3e,"parseCssTimeMs");function Tgt(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(Tgt,"elapsedLabel");function Rgt(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(Rgt,"liveElapsedLabel");function Egt(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(Egt,"useLiveElapsedMs");function Lgt(e,s){return!Number.isFinite(e)||!Number.isFinite(s)||s<=0?0:Math.max(0,Math.round(e/s)-1)}r(Lgt,"lineScrollOffset");function SR(e){const s=getComputedStyle(document.documentElement).getPropertyValue(e),n=q3e(s);return Number.isFinite(n)?n:0}r(SR,"motionTokenMs");function Mgt({text:e,streaming:s,leaving:n}){const a=(0,m.useRef)(null),[i,o]=(0,m.useState)(0),[l,c]=(0,m.useState)(!1),[d,u]=(0,m.useState)(!1);(0,m.useLayoutEffect)(()=>{const p=a.current;if(!p)return;const f=r(()=>{const g=parseFloat(window.getComputedStyle(p).lineHeight);o(Lgt(p.scrollHeight,g))},"measure");if(f(),typeof ResizeObserver>"u")return;const x=new ResizeObserver(f);return x.observe(p),()=>x.disconnect()},[e,s]),(0,m.useEffect)(()=>{const p=requestAnimationFrame(()=>c(!0)),f=window.setTimeout(()=>u(!0),SR("--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(Mgt,"LiveSelfTalkLine");function Pgt(e,s){const[n,a]=(0,m.useState)(null),i=(0,m.useRef)(n),o=(0,m.useRef)(null),l=(0,m.useRef)(e),c=(0,m.useRef)(0),d=(0,m.useRef)(null),u=(0,m.useRef)(null),h=(0,m.useRef)(null);return l.current=e,(0,m.useEffect)(()=>{const p=r(y=>{y.current!=null&&(window.clearTimeout(y.current),y.current=null)},"clear"),f=r(y=>{i.current=y,a(y)},"show"),x=r(()=>{p(u),p(h),u.current=window.setTimeout(()=>{if(u.current=null,o.current!=null)return;const y=i.current;y==null||y.streaming||(f({...y,leaving:!0}),h.current=window.setTimeout(()=>{h.current=null,i.current?.leaving&&f(null)},SR("--motion-line-scroll")))},SR("--motion-interstitial-dwell"))},"scheduleLeave"),g=r((y,k)=>{p(u),p(h),c.current=Date.now(),f({text:y,streaming:k,swapKey:(i.current?.swapKey??0)+1}),k||x()},"swapIn");if(!s){p(d),p(u),p(h),o.current=null,i.current&&f(null);return}const v=i.current;if(e==null){v?.streaming&&(f({...v,streaming:!1}),x());return}if(v==null){g(e,!0);return}if(v.streaming){v.text!==e&&f({...v,text:e});return}if(o.current=e,d.current==null){const y=SR("--motion-interstitial-dwell"),k=Math.max(0,c.current+y-Date.now());d.current=window.setTimeout(()=>{d.current=null;const w=o.current;o.current=null,w!=null&&g(w,l.current!=null)},k)}},[e,s]),(0,m.useEffect)(()=>()=>{d.current!=null&&window.clearTimeout(d.current),u.current!=null&&window.clearTimeout(u.current),h.current!=null&&window.clearTimeout(h.current)},[]),n}r(Pgt,"useHeldSelfTalk");var Dgt={running:{Icon:st,spin:!0,tone:"text-(--status-agent-running)"},working:{Icon:st,spin:!0,tone:"text-(--status-agent-running)"},awaiting_approval:{Icon:yS,spin:!1,tone:"text-primary"},interrupted:{Icon:AW,spin:!1,tone:"text-destructive"},refused:{Icon:zm,spin:!1,tone:"text-destructive"},truncated:{Icon:_Qe,spin:!1,tone:"text-(--status-agent-paused)"}};function U3e({item:e,onApprovalDecision:s,chevronOpen:n,onToggle:a}){const{Icon:i,spin:o,tone:l}=Dgt[e.status],c=e.status==="awaiting_approval",d=e.status==="running"||e.status==="working",u=Egt(e.startedAtMs,d),h=Pgt(d?e.selfTalk:void 0,d),p=Tgt(e.elapsedMs);if(d){const f=Rgt(u??e.elapsedMs),x=e.selfTalk!=null,g=e.toolName?EN(e.toolName).icon:x?null:z3e(e.label),v=x||Cgt(e.label)?Agt(e.id,u??e.elapsedMs??0):e.label,y=(0,t.jsxs)("div",{className:"tc-enter-status flex items-center gap-2 py-0.5 text-xs text-muted-foreground",children:[n!==void 0?(0,t.jsx)("span",{className:"flex h-3.5 w-3.5 shrink-0 items-center justify-center","data-testid":"task-chat-status-caret-slot",children:(0,t.jsx)(An,{className:W("h-3 w-3 transition-transform",n?"rotate-90":null),"aria-hidden":!0})}):null,(0,t.jsx)("span",{className:"flex h-3.5 w-3.5 shrink-0 items-center justify-center","data-testid":"task-chat-status-dot-slot",children:(0,t.jsx)("span",{"aria-hidden":!0,className:"h-2 w-2 animate-pulse rounded-full bg-(--status-agent-running)"})}),g?(0,t.jsx)(g,{className:"h-3.5 w-3.5 shrink-0","aria-hidden":!0}):null,(0,t.jsxs)("span",{className:"flex min-w-0 flex-1 items-baseline gap-2",children:[(0,t.jsxs)("span",{className:"shimmer-text shimmer-text-muted shrink-0 font-medium",children:[v,"…"]}),f?(0,t.jsx)("span",{className:"shrink-0 font-mono tabular-nums text-(length:--text-micro)",children:f}):null,e.detail?(0,t.jsx)("span",{className:"min-w-0 truncate font-mono text-(length:--text-micro)",children:e.detail}):null,e.tokens?(0,t.jsxs)("span",{className:"ml-auto shrink-0 font-mono text-(length:--text-micro)",children:[e.tokens.used.toLocaleString(),"/",e.tokens.size.toLocaleString()," ctx"]}):null]})]});return(0,t.jsxs)("div",{className:"flex flex-col",children:[(0,t.jsxs)("div",{className:"flex items-center gap-2 py-0.5 text-xs text-muted-foreground","data-testid":"task-chat-interstitial-row",children:[(0,t.jsx)("span",{"aria-hidden":!0,className:"h-3.5 w-3.5 shrink-0"}),h?(0,t.jsx)(Mgt,{text:h.text,streaming:h.streaming,leaving:h.leaving},h.swapKey):(0,t.jsx)("span",{"aria-hidden":!0,className:"tc-line-scroll min-w-0 flex-1"})]}),a?(0,t.jsx)("button",{type:"button",onClick:a,"aria-expanded":n,className:"-mx-1.5 block w-full rounded-sm px-1.5 text-left transition-colors hover:bg-muted/60","data-testid":"task-chat-live-turn",children:y}):y]})}return(0,t.jsxs)("div",{className:W("tc-enter-status flex flex-col gap-2 rounded-lg border px-3 py-2 text-sm",c?"tc-approval border-primary/40 bg-primary/5":"border-border bg-muted/40"),children:[(0,t.jsxs)("div",{className:"flex min-w-0 items-center gap-2",children:[(0,t.jsx)(i,{className:W("h-4 w-4 shrink-0",l,o&&"animate-spin")}),(0,t.jsx)("span",{className:"min-w-0 truncate font-medium",children:e.label}),(0,t.jsxs)("span",{className:"ml-auto flex shrink-0 items-center gap-2 text-xs text-muted-foreground",children:[p?(0,t.jsx)("span",{children:p}):null,e.tokens?(0,t.jsxs)("span",{children:[e.tokens.used.toLocaleString(),"/",e.tokens.size.toLocaleString()," ctx"]}):null]})]}),e.detail?(0,t.jsx)("p",{className:"text-xs text-muted-foreground",children:e.detail}):null,c&&e.approval?(0,t.jsx)("div",{className:"flex flex-wrap justify-end gap-2 pt-1",children:e.approval.options.map(f=>{const x=f.kind.startsWith("reject");return(0,t.jsx)("button",{type:"button",onClick:r(()=>s?.(f.id),"onClick"),className:W("rounded-md border px-2.5 py-1 text-xs font-medium transition-colors",x?"border-border text-muted-foreground hover:bg-accent/50 hover:text-foreground":"border-primary bg-primary text-primary-foreground hover:bg-primary/90"),children:f.label},f.id)})}):null]})}r(U3e,"TaskChatStatusPill");var jg=(0,m.createContext)(null);function uw(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(uw,"formatBytes$4");var VE=new Set(["application/octet-stream","binary/octet-stream","application/x-binary"]),$gt=[".mp4",".m4v",".webm",".mov",".qt",".quicktime"],Ogt=[".png",".jpg",".jpeg",".gif",".webp",".avif",".bmp",".ico"],Bgt=new Set(["application/wasm"]),Fgt=new Set(["application/zip","application/x-zip","application/x-zip-compressed"]),K3e=new Set(["text/markdown","text/x-markdown","application/markdown","application/x-markdown"]),zgt=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"]),qgt=[".csv",".css",".graphql",".htm",".html",".js",".json",".jsx",".log",".markdown",".md",".mdx",".php",".py",".sh",".sql",".toml",".ts",".tsx",".txt",".xml",".yaml",".yml"];function rA(e){return(e??"").toLowerCase().split(";")[0]?.trim()??""}r(rA,"normalizeOutputContentType");function Ugt(e){const s=(e??"").trim().toLowerCase();return s?qgt.some(n=>s.endsWith(n)):!1}r(Ugt,"hasDocumentLikeFilename");function Q3e(e){return Fgt.has(e)||e.endsWith("+zip")}r(Q3e,"isZipContentType");function Kgt(e){return e?!!(e.startsWith("text/")||K3e.has(e)||zgt.has(e)||e.startsWith("application/")&&(e.endsWith("+json")||e.endsWith("+xml"))):!1}r(Kgt,"isDocumentLikeOutputContentType");function Qgt(e,s){const n=rA(e);return!n||Kgt(n)||VE.has(n)&&Ugt(s)?!1:n.startsWith("video/")||n.startsWith("image/")||n==="application/pdf"||Bgt.has(n)||Q3e(n)||VE.has(n)}r(Qgt,"isOutputEligibleContentType");function Wgt(e){const s=rA(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"}:Q3e(s)?{label:"ZIP",tone:"zip"}:s.startsWith("image/")?{label:"IMG",tone:"image"}:K3e.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(Wgt,"getOutputFileGlyph");function fm(e,s){const n=rA(e);if(n.startsWith("video/"))return!0;if(!VE.has(n))return!1;const a=(s??"").trim().toLowerCase();return $gt.some(i=>a.endsWith(i))}r(fm,"isVideoLikeOutput");function Rj(e){const s=rA(e);return s.startsWith("image/")&&s!=="image/svg+xml"}r(Rj,"isImageContentType");function DM(e,s){const n=rA(e);if(Rj(n))return!0;if(n&&!VE.has(n))return!1;const a=(s??"").trim().toLowerCase();return Ogt.some(i=>a.endsWith(i))}r(DM,"isImageLikeOutput");function Iie(e){const s=new Date(e).getTime();return Number.isNaN(s)?0:s}r(Iie,"toTime");function $M(e){const s=(e??[]).filter(n=>n.type==="artifact"&&n.provider==="paperclip").flatMap(n=>{const a=H$e.safeParse(n.metadata);return a.success&&!Qgt(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:Iie(a.createdAt)-Iie(n.createdAt)),{items:s,primary:s[0]??null,rest:s.slice(1),count:s.length}}r($M,"getIssueOutputs");function GV(e){return e.metadata?.originalFilename||e.title||"output"}r(GV,"outputFilename");function W3e(e){return new Set($M(e).items.flatMap(s=>{const n=s.metadata?.attachmentId;return n?[n]:[]}))}r(W3e,"getPromotedOutputAttachmentIds");function aA(e,s){const n=e?.toLowerCase().split(";")[0].trim();return n==="text/html"||n==="application/xhtml+xml"||/\.html?$/i.test(s??"")}r(aA,"isHtmlPreview");var Hgt=["default-src 'none'","script-src 'unsafe-inline'","style-src 'unsafe-inline'","img-src data:","font-src data:","media-src data:","connect-src 'none'","frame-src 'none'","object-src 'none'","base-uri 'none'","form-action 'none'"].join("; ");function Vgt(e){return`<!doctype html><html><head><meta charset="utf-8"><meta http-equiv="Content-Security-Policy" content="${Hgt}"><meta name="referrer" content="no-referrer"></head><body>${e}</body></html>`}r(Vgt,"htmlPreviewDocument");function Ggt(e){return e.contentType.toLowerCase().split(";")[0]?.trim()??""}r(Ggt,"normalizedContentType");function og(e){return e.originalFilename??e.id}r(og,"attachmentFilename");function OM(e){return e.openPath??e.contentPath}r(OM,"attachmentOpenPath");function LS(e){return e.downloadPath??`${e.contentPath}?download=1`}r(LS,"attachmentDownloadPath");function H3e(e){const s=Ggt(e);return DM(s,e.originalFilename)&&!/^image\/hei[cf](?:-sequence)?$/.test(s)}r(H3e,"isImageAttachment$1");function V3e(e){return fm(e.contentType,e.originalFilename)}r(V3e,"isVideoAttachment");function G3e(e){return xbe(e)}r(G3e,"isMarkdownAttachment");function mw(e){const s=e.contentType.toLowerCase().split(";")[0].trim();return xbe(e)||aA(s,e.originalFilename)||s.startsWith("text/")||/^(application\/(json|xml|javascript|x-yaml|yaml)|application\/[\w.-]+\+json)$/.test(s)||["","application/octet-stream"].includes(s)&&/\.(txt|log|csv|json|yaml|yml|toml|ini|sh|ts|tsx|js|jsx|py|css|html)$/i.test(e.originalFilename??"")}r(mw,"isTextAttachment");function Y3e(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(Y3e,"downloadBlob$1");function Ygt(e,s,n){Y3e(e,new Blob([s],{type:`${n};charset=utf-8`}))}r(Ygt,"downloadTextFile");var MD="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 Z3e({issueId:e,documentKey:s,title:n,format:a,body:i,className:o}){const[l,c]=(0,m.useState)(null),[d,u]=(0,m.useState)(null),[h,p]=(0,m.useState)(null),{copy:f,copied:x,failed:g}=Z0(),v=(0,m.useRef)(void 0);(0,m.useEffect)(()=>()=>clearTimeout(v.current),[]);const y=(0,m.useCallback)(async(_,R)=>{c(_),p(null);try{await R(),u(_)}catch(I){u(null),p(I instanceof Error?I.message:"Export failed")}finally{c(null)}clearTimeout(v.current),v.current=setTimeout(()=>{u(null),p(null)},2e3)},[]),k=(0,m.useCallback)(async()=>i??(await jt.getDocument(e,s)).body,[i,s,e]),w=(0,m.useCallback)(()=>{c("copy"),p(null),(async()=>{try{await f(await k())==="failed"&&p("Copy failed")}catch(_){p(_ instanceof Error?_.message:"Copy failed")}finally{c(null)}})()},[f,k]),N=g||h==="Copy failed"?"Copy failed":x?"Copied!":"Copy full content",S=d==="download"?"Downloaded!":"Download source",C=d==="pdf"?"Downloaded!":"Export to PDF";return(0,t.jsxs)("div",{className:W("flex items-center gap-0.5",o),"data-testid":"document-export-actions",children:[(0,t.jsx)("button",{type:"button",className:MD,disabled:l!==null,"aria-label":"Copy full content",title:N,"data-testid":"document-export-copy",onClick:r(_=>{_.preventDefault(),_.stopPropagation(),w()},"onClick"),children:x?(0,t.jsx)(cs,{"aria-hidden":"true",className:"h-3.5 w-3.5"}):(0,t.jsx)(gr,{"aria-hidden":"true",className:"h-3.5 w-3.5"})}),(0,t.jsx)("button",{type:"button",className:MD,disabled:l!==null,"aria-label":"Download source",title:S,"data-testid":"document-export-download",onClick:r(_=>{_.preventDefault(),_.stopPropagation(),y("download",async()=>{const R=aUe(a);Ygt(yte(n,R),await k(),R==="md"?"text/markdown":"text/plain")})},"onClick"),children:(0,t.jsx)(Ui,{"aria-hidden":"true",className:"h-3.5 w-3.5"})}),(0,t.jsx)("button",{type:"button",className:MD,disabled:l!==null,"aria-label":"Export to PDF",title:C,"data-testid":"document-export-pdf",onClick:r(_=>{_.preventDefault(),_.stopPropagation(),y("pdf",async()=>{Y3e(yte(n,"pdf"),await jt.getDocumentPdf(e,s))})},"onClick"),children:(0,t.jsx)(iQe,{"aria-hidden":"true",className:"h-3.5 w-3.5"})}),(0,t.jsx)("span",{className:"sr-only",role:"status","aria-live":"polite",children:h??(x?"Copied!":g?"Copy failed":d?"Downloaded!":"")})]})}r(Z3e,"DocumentExportActions");function T5({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(T5,"PreviewFrame");function GE({label:e}){return(0,t.jsx)(T5,{className:"flex items-center justify-center",children:(0,t.jsxs)("div",{className:"flex flex-col items-center gap-1.5 text-muted-foreground/50",children:[(0,t.jsx)(kl,{className:"h-7 w-7","aria-hidden":"true"}),e?(0,t.jsx)("span",{className:"text-(length:--text-micro) font-medium uppercase tracking-wide",children:e}):null]})})}r(GE,"PlaceholderPreview");function Zgt({artifact:e}){const[s,n]=(0,m.useState)(!1);return s||!e.contentPath?(0,t.jsx)(GE,{label:"Image"}):(0,t.jsx)(T5,{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(Zgt,"ImagePreview");function Jgt({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)(T5,{className:"flex items-center justify-center bg-black/80",children:(0,t.jsx)("div",{className:"flex h-11 w-11 items-center justify-center rounded-full bg-white/15",children:(0,t.jsx)(ho,{className:"h-5 w-5 translate-x-0.5 text-white","aria-hidden":"true"})})});const c=r(()=>{l.current!==null&&(window.clearTimeout(l.current),l.current=null),i(!0)},"markFrameReady"),d=r(()=>{l.current!==null&&window.clearTimeout(l.current),l.current=window.setTimeout(c,3e3)},"scheduleFrameReadyFallback"),u=r(p=>{if(o.current)return;o.current=!0;const f=p.currentTarget,x=Number.isFinite(f.duration)&&f.duration>0?f.duration:0,g=x>0?Math.min(1,x/4):.05;try{Math.abs(f.currentTime-g)>.001?(f.currentTime=g,d()):c()}catch{c()}},"loadThumbnailFrame"),h=r(p=>{(o.current||p.currentTarget.currentTime>0)&&c()},"handleLoadedData");return(0,t.jsxs)(T5,{className:"bg-black",children:[(0,t.jsx)("video",{src:e.contentPath,preload:"metadata",muted:!0,playsInline:!0,"data-frame-ready":a?"true":"false",className:W("h-full w-full object-contain transition-opacity",a?"opacity-100":"opacity-0"),onLoadedMetadata:u,onLoadedData:h,onSeeked:c,onError:r(()=>n(!0),"onError")}),(0,t.jsx)("div",{className:"pointer-events-none absolute inset-0 flex items-center justify-center",children:(0,t.jsx)("div",{className:"flex h-11 w-11 items-center justify-center rounded-full bg-black/55",children:(0,t.jsx)(ho,{className:"h-5 w-5 translate-x-0.5 text-white","aria-hidden":"true"})})})]})}r(Jgt,"VideoPreview");function Xgt({artifact:e}){const s=e.previewText?.trim();return s?(0,t.jsxs)(T5,{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)(GE,{label:e.source==="document"?"Document":"Text"})}r(Xgt,"TextPreview");function iA({artifact:e}){switch(e.mediaKind){case"image":return(0,t.jsx)(Zgt,{artifact:e},e.contentPath);case"video":return(0,t.jsx)(Jgt,{artifact:e},e.contentPath);case"text":case"document":return(0,t.jsx)(Xgt,{artifact:e});case"file":return(0,t.jsx)(GE,{label:"File"});default:return(0,t.jsx)(GE,{})}}r(iA,"ArtifactPreview");function Tie({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(Tie,"SecondaryAction");function ebt({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)(iA,{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)(Z3e,{issueId:e.issue.id,documentKey:e.documentKey,title:e.title}):null,e.openPath?(0,t.jsx)(Tie,{href:e.openPath,title:"Open file in new tab",children:(0,t.jsx)(Dn,{className:"h-3.5 w-3.5"})}):null,e.downloadPath?(0,t.jsx)(Tie,{href:e.downloadPath,download:!0,title:"Download file",children:(0,t.jsx)(Ui,{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 ",Gd(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(ebt,"ArtifactCard");function tbt(e){return e&&/^\/api\/assets\/[^/?#]+\/content$/.test(e)?e:null}r(tbt,"paperclipHumanAvatarUrl");function J3e(e){const{authorName:s,authorUserId:n,currentUserId:a,userProfileMap:i}=e,o=n?i?.get(n):null,l=!!(n&&a&&n===a);return{isCurrentUser:l,authorName:o?.label?.trim()||s?.trim()||(n==="local-board"?"Board":l?"You":"User"),avatarUrl:o?.image??null}}r(J3e,"resolveIssueChatHumanAuthor");var tc={credentials:r(e=>we.get(`/companies/${e}/email/connections`),"credentials"),checkAddress:r((e,s,n,a)=>we.post(`/companies/${e}/email/connections/${s}/check-address`,n,{signal:a}),"checkAddress"),connect:r((e,s)=>we.post(`/companies/${e}/email/connections`,s),"connect"),inspectSaved:r((e,s)=>we.post(`/companies/${e}/email/connections/${s}/inspect`,{}),"inspectSaved"),list:r(e=>we.get(`/companies/${e}/email/inboxes`),"list"),setup:r((e,s)=>we.post(`/companies/${e}/email/inboxes`,s),"setup"),inspect:r((e,s)=>we.post(`/companies/${e}/email/inspect`,{apiKey:s}),"inspect"),control:r((e,s)=>we.post(`/email/inboxes/${e}/control`,{action:s}),"control"),reconnect:r((e,s,n)=>we.post(`/email/inboxes/${e}/reconnect`,{apiKey:s,receiveMode:n}),"reconnect"),resolve:r((e,s,n,a)=>we.post(`/companies/${e}/email/deliveries/${s}/resolve`,{outcome:n,providerMessageId:a}),"resolve"),thread:r((e,s)=>we.get(`/companies/${e}/email/tasks/${s}`),"thread"),send:r((e,s)=>we.post(`/companies/${e}/email/send`,s),"send")};function X3e(e,s){return te({queryKey:["email-thread",e,s],queryFn:r(()=>tc.thread(e,s),"queryFn"),enabled:!!(e&&s)&&!s.startsWith("chat:"),refetchInterval:r(n=>n.state.data===null?!1:3e3,"refetchInterval")})}r(X3e,"useEmailThread");var eAe=(0,m.createContext)(null);function sbt({companyId:e,issueId:s,children:n}){const a=X3e(e,s);return(0,t.jsx)(eAe.Provider,{value:a.data??null,children:n})}r(sbt,"EmailThreadProvider");function tAe(e){const s=(0,m.useContext)(eAe),n=s?.messages.find(a=>a.commentId===e);return n&&s?(0,t.jsx)(sAe,{message:n,publication:s.publications.find(a=>a.providerMessageId===n.providerMessageId),issueId:s.issueId}):null}r(tAe,"useEmailComment");function sAe({message:e,publication:s,issueId:n,contextNotice:a=!1}){const i=te({queryKey:["email-attachments",n],queryFn:r(()=>jt.listAttachments(n),"queryFn"),enabled:e.attachmentIds.length>0});return(0,t.jsxs)("article",{"aria-label":e.direction==="inbound"?"Email received":"Email sent",className:a?"task-context-notice space-y-3":"space-y-4 rounded-xl border border-border bg-card p-5",children:[(0,t.jsxs)("div",{className:"flex flex-wrap items-center justify-between gap-2",children:[(0,t.jsxs)("span",{className:"flex items-center gap-2 text-sm font-semibold",children:[(0,t.jsx)(VQ,{className:"size-4"}),e.direction==="inbound"?"Email received":"Email sent"]}),(0,t.jsx)("span",{className:"text-xs text-muted-foreground",children:new Date(e.timestamp).toLocaleString()})]}),(0,t.jsxs)("div",{className:"space-y-1",children:[(0,t.jsxs)("p",{className:"text-sm font-medium",children:[e.from,e.direction==="inbound"&&(0,t.jsx)("span",{className:"ml-2 rounded-md bg-muted px-2 py-1 text-xs text-muted-foreground",children:"External"})]}),(0,t.jsxs)("p",{className:"break-words text-xs text-muted-foreground",children:["To: ",e.to.join(", ")]}),!!e.cc?.length&&(0,t.jsxs)("p",{className:"break-words text-xs text-muted-foreground",children:["Cc: ",e.cc.join(", ")]}),(0,t.jsx)("p",{className:"text-sm font-semibold",children:e.subject})]}),(0,t.jsx)("div",{className:"whitespace-pre-wrap break-words text-sm",children:e.text||"(No text body)"}),!!e.attachmentIds.length&&(0,t.jsx)("div",{className:"flex flex-wrap gap-2",children:e.attachmentIds.map(o=>{const l=i.data?.find(c=>c.id===o);return(0,t.jsxs)("a",{href:`/api/attachments/${o}/content`,target:"_blank",rel:"noreferrer",className:"flex items-center gap-2 rounded-md border border-border px-3 py-2 text-xs",children:[(0,t.jsx)(kl,{className:"size-3.5"}),l?.originalFilename??"Open attachment"]},o)})}),(0,t.jsxs)("details",{className:"text-xs text-muted-foreground",children:[(0,t.jsx)("summary",{className:"cursor-pointer",children:"Email details"}),(0,t.jsxs)("div",{className:"space-y-2 pt-3",children:[!!e.bcc?.length&&(0,t.jsxs)("p",{children:["Bcc: ",e.bcc.join(", ")]}),(0,t.jsxs)("p",{className:"break-all",children:["Message ID: ",e.providerMessageId]}),e.fullText!==e.text&&(0,t.jsx)("div",{className:"whitespace-pre-wrap break-words",children:e.fullText})]})]}),s&&(0,t.jsxs)("p",{className:"border-t border-border pt-3 text-xs text-muted-foreground",children:[s.outcome==="delivered"?"Delivered":s.outcome==="failed"?"Delivery failed":s.outcome==="uncertain"?"Delivery uncertain":s.outcome==="queued"?"Queued":"Sent",s.error?` · ${s.error}`:""]}),i.error&&(0,t.jsx)("p",{role:"alert",className:"text-xs text-destructive",children:"Attachments could not be loaded."})]})}r(sAe,"EmailMessageCard");var rj=(0,m.createContext)(null);function hw({items:e,initialIndex:s,open:n,onOpenChange:a}){const[i,o]=(0,m.useState)(s),l=(0,m.useRef)(null),c=(0,m.useCallback)(g=>{l.current=g},[]);(0,m.useEffect)(()=>{n&&o(s)},[n,s]);const d=(0,m.useCallback)(()=>{o(g=>(g+1)%e.length)},[e.length]),u=(0,m.useCallback)(()=>{o(g=>(g-1+e.length)%e.length)},[e.length]);(0,m.useEffect)(()=>{i<e.length||o(0)},[i,e.length]),(0,m.useEffect)(()=>{if(!n)return;const g=r(v=>{v.key==="ArrowRight"?d():v.key==="ArrowLeft"?u():v.key==="Escape"&&a(!1)},"handler");return window.addEventListener("keydown",g),()=>window.removeEventListener("keydown",g)},[n,d,u,a]);const h=(0,m.useCallback)(g=>{const v=g.target;v.closest("button")||v.closest("a")||v===l.current||a(!1)},[a]);if(e.length===0)return null;const p=e[i];if(!p)return null;const f=og(p),x=fm(p.contentType,p.originalFilename);return(0,t.jsx)(iqe,{open:n,onOpenChange:a,children:(0,t.jsxs)(rqe,{children:[(0,t.jsx)(nqe,{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)(aqe,{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:LS(p),download:f,className:"text-white/50 hover:text-white transition-colors",title:"Download","aria-label":`Download ${f}`,onClick:r(g=>g.stopPropagation(),"onClick"),children:(0,t.jsx)(Ui,{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)(En,{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)(um,{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)(An,{className:"h-7 w-7"})})})]}),(0,t.jsx)("div",{className:"h-6 shrink-0"})]})]})})}r(hw,"ImageGalleryModal");function Uv(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:{}}r(Uv,"record$7");var nAe=(0,m.createContext)(null);function rAe(e){const s=(0,m.useContext)(nAe);return s&&e?.sourceRunId===s.runId&&e.sections.some(n=>n.rows.some(a=>a.type==="key_value"&&a.value===s.actionId))?s:null}r(rAe,"useWorkspaceBaseRefRecovery");function nbt({issue:e,agentMap:s,unavailableReason:n,onRepaired:a,children:i}){const o=e.activeRecoveryAction,l=o?.cause==="configuration_incomplete"&&typeof o.evidence.latestRunId=="string"?o.evidence.latestRunId:null,{data:c}=te({queryKey:["workspace-base-ref-recovery",e.companyId,e.id,l],queryFn:r(()=>na.get(l),"queryFn"),enabled:!!l,staleTime:1/0,retry:!1}),d=Uv(Uv(c?.resultJson).configurationIncomplete);let u=null;if(o&&l&&c?.companyId===e.companyId&&Uv(c.contextSnapshot).issueId===e.id&&d.reason==="workspace_base_ref_unresolved"&&typeof d.requestedRef=="string"){const h=e.assigneeAgentId?s.get(e.assigneeAgentId):void 0,p=d.requestedRef,f=e.project?.workspaces?.find(y=>y.id===e.projectWorkspaceId)??e.project?.primaryWorkspace;let x="The task’s repository";if(f?.repoUrl)try{const y=new URL(f.repoUrl);(y.protocol==="https:"||y.protocol==="http:")&&(x=`${y.hostname}${y.pathname.replace(/\.git$/,"")}`)}catch{}const g=Uv(Uv(e.executionWorkspaceSettings).workspaceStrategy).baseRef,v=o.status!=="active"||e.status!=="blocked"||e.assigneeAgentId!==o.returnOwnerAgentId||c.agentId!==e.assigneeAgentId||typeof g=="string"&&g.trim()&&g!==p?"This repair no longer matches the task. Refresh to review its current state.":n??(e.executionRunId||e.checkoutRunId?"Wait for the current run to finish.":null)??(h?.status==="paused"||h?.status==="terminated"?"The assigned agent is unavailable.":null)??(e.executionState?.status==="pending"?"Complete the pending review or approval before retrying.":null)??(e.blockedBy?.some(y=>y.status!=="done"&&y.status!=="cancelled")?"Resolve the task’s blockers before retrying.":null);u={actionId:o.id,runId:l,props:{requestedRef:p,repository:x,taskOverride:g===p,defaultBranch:typeof d.defaultBranch=="string"?d.defaultBranch:null,agentName:h?.name??"The assigned agent",unavailableReason:v,failureKind:typeof d.fetchError=="string"&&d.fetchError.includes(`couldn't find remote ref refs/heads/${p}`)?"missing_branch":"unresolved_ref",onRepair:r(async y=>{try{const k=await jt.resolveRecoveryAction(e.id,{actionId:o.id,outcome:"restored",sourceIssueStatus:"todo",workspaceBaseRef:{requestedRef:p,branch:y}});if(k.issue.status!=="todo"||k.issue.assigneeAgentId!==e.assigneeAgentId||Uv(Uv(k.issue.executionWorkspaceSettings).workspaceStrategy).baseRef!==y)throw new Error("The task changed while saving. Refresh to check its current state.")}finally{a()}},"onRepair")}}}return(0,t.jsx)(nAe.Provider,{value:u,children:i})}r(nbt,"WorkspaceBaseRefRecoveryProvider");var aAe={neutral:{container:"border-border bg-muted/35 dark:bg-muted/20",iconWrap:"bg-muted text-foreground/70",icon:e0,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:e0,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:xa,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:dN,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 rbt(e){try{return new Date(e).toLocaleString(void 0,{month:"short",day:"numeric",hour:"numeric",minute:"2-digit"})}catch{return e}}r(rbt,"formatTimestamp$1");function abt({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(abt,"MetadataRow$1");function YV({sections:e,tone:s="neutral"}){const n=aAe[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)(abt,{row:o,tone:n},l))})]},i))})}r(YV,"SystemNoticeMetadataSections");function ZV({tone:e="neutral",label:s,body:n,source:a,metadata:i,detailsDefaultOpen:o=!1,timestamp:l,className:c}){const d=aAe[e],u=d.icon,[h,p]=(0,m.useState)(o),f=(0,m.useId)(),x=!!(i&&i.length>0),g=s??{neutral:"System notice",info:"System notice",success:"System notice",warning:"System warning",danger:"System alert"}[e];return(0,t.jsxs)("section",{role:"status","aria-label":g,className:W("relative w-full overflow-hidden rounded-lg border text-sm shadow-(--shadow-extract-8)",d.container,c),children:[(0,t.jsxs)("header",{className:"flex items-start gap-3 px-3 py-2.5 sm:px-4",children:[(0,t.jsx)("span",{className:W("mt-0.5 flex h-7 w-7 shrink-0 items-center justify-center rounded-md",d.iconWrap),"aria-hidden":!0,children:(0,t.jsx)(u,{className:W("h-4 w-4",d.iconClass)})}),(0,t.jsxs)("div",{className:"min-w-0 flex-1",children:[(0,t.jsxs)("div",{className:"flex flex-wrap items-center gap-x-2 gap-y-0.5 text-(length:--text-micro) font-semibold uppercase tracking-(--tracking-eyebrow)",children:[(0,t.jsx)("span",{className:d.label,children:g}),a?(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)("span",{className:"text-muted-foreground/60","aria-hidden":!0,children:"·"}),a.href?(0,t.jsx)("a",{href:a.href,className:"rounded-sm font-medium normal-case tracking-normal text-muted-foreground underline-offset-2 hover:text-foreground hover:underline",children:a.label}):(0,t.jsx)("span",{className:"font-medium normal-case tracking-normal text-muted-foreground",children:a.label})]}):null,l?(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)("span",{className:"text-muted-foreground/60","aria-hidden":!0,children:"·"}),(0,t.jsx)("span",{className:"font-medium normal-case tracking-normal text-muted-foreground",children:rbt(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)(rn,{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)(YV,{sections:i,tone:e})}):null]})}r(ZV,"SystemNotice");function iAe({requestedRef:e,repository:s,defaultBranch:n,agentName:a,configuredBy:i,taskOverride:o=!0,failureKind:l="unresolved_ref",unavailableReason:c,onRepair:d}){const u=(0,m.useId)(),[h,p]=(0,m.useState)(!n),[f,x]=(0,m.useState)(n??""),[g,v]=(0,m.useState)(!1),[y,k]=(0,m.useState)(!1),[w,N]=(0,m.useState)(null),[S,C]=(0,m.useState)(null),_=(0,m.useRef)(!1),R=f.trim().length>0&&f.trim()!==e;async function I(T){const E=T.trim();if(!(!E||E===e||c||_.current||S)){if(!nBe(E)){N("Enter a valid branch name, such as master or release/next.");return}_.current=!0,k(!0),N(null);try{await d(E),C(E)}catch(L){N(L instanceof Error?L.message:"Refresh the task to check its current state, then try again.")}finally{_.current=!1,k(!1)}}}return r(I,"repair"),(0,t.jsxs)("section",{"aria-labelledby":`${u}-title`,className:"flex min-w-0 gap-3 rounded-lg border border-border bg-muted/20 p-4","data-testid":"workspace-base-ref-recovery",children:[S?(0,t.jsx)(cs,{"aria-hidden":!0,className:"mt-0.5 size-4 shrink-0 text-(--status-task-icon-done)"}):(0,t.jsx)(Es,{"aria-hidden":!0,className:"mt-0.5 size-4 shrink-0 text-(--status-task-icon-blocked)"}),(0,t.jsxs)("div",{className:"flex min-w-0 flex-1 flex-col gap-3",children:[(0,t.jsxs)("div",{className:"flex flex-col gap-1",role:"status","aria-live":"polite",children:[(0,t.jsx)("h2",{id:`${u}-title`,className:"break-words text-sm font-semibold",children:S?"Branch updated · retry requested":l==="missing_branch"?(0,t.jsxs)(t.Fragment,{children:["Branch ",(0,t.jsx)("code",{className:"font-mono",children:e})," was not found"]}):(0,t.jsxs)(t.Fragment,{children:["Couldn’t use branch ",(0,t.jsx)("code",{className:"font-mono",children:e})]})}),(0,t.jsx)("p",{className:"text-sm leading-relaxed text-muted-foreground",children:S?(0,t.jsxs)(t.Fragment,{children:["This task now starts from ",(0,t.jsx)("code",{className:"font-mono text-foreground",children:S}),". A retry has been requested for ",a,"."]}):(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)("span",{className:"break-all text-foreground",children:s}),l==="missing_branch"?(0,t.jsxs)(t.Fragment,{children:[" has no branch named ",(0,t.jsx)("code",{className:"font-mono text-foreground",children:e}),"."]}):" could not resolve the starting branch. Check the branch name and repository access."," ",a," hasn’t started."]})})]}),!S&&(0,t.jsxs)(t.Fragment,{children:[n&&!h&&(0,t.jsxs)("p",{className:"flex flex-wrap items-center gap-1.5 text-sm",children:[(0,t.jsx)(to,{"aria-hidden":!0,className:"size-4 text-muted-foreground"}),(0,t.jsx)("code",{className:"font-mono",children:n}),(0,t.jsx)("span",{className:"text-muted-foreground",children:"is the repository’s default branch."})]}),(0,t.jsx)("p",{className:"text-xs text-muted-foreground",children:"Changes only this task’s starting branch."}),c&&(0,t.jsx)("p",{id:`${u}-unavailable`,className:"text-sm text-muted-foreground",children:c}),w&&(0,t.jsxs)("p",{role:"alert",id:`${u}-error`,className:"text-sm text-destructive",children:["Couldn’t confirm the repair. ",w]}),h?(0,t.jsxs)("form",{className:"flex flex-col gap-3",onSubmit:r(T=>{T.preventDefault(),I(f)},"onSubmit"),children:[(0,t.jsxs)("div",{className:"flex flex-col gap-1.5",children:[(0,t.jsx)(Ds,{htmlFor:`${u}-branch`,children:"Starting branch"}),(0,t.jsx)(dt,{id:`${u}-branch`,autoFocus:!0,value:f,disabled:y||!!c,onChange:r(T=>x(T.target.value),"onChange"),placeholder:"Branch name",className:"font-mono","aria-describedby":w?`${u}-error`:void 0,autoComplete:"off",spellCheck:!1})]}),(0,t.jsxs)("div",{className:"flex flex-wrap items-center justify-between gap-2",children:[n?(0,t.jsx)($,{type:"button",variant:"ghost",size:"sm",disabled:y,onClick:r(()=>{p(!1),N(null)},"onClick"),children:"Cancel"}):(0,t.jsx)("span",{}),(0,t.jsxs)($,{type:"submit",size:"sm",disabled:y||!R||!!c,"aria-describedby":c?`${u}-unavailable`:void 0,children:[y&&(0,t.jsx)(st,{"aria-hidden":!0,className:"size-3.5 animate-spin motion-reduce:animate-none"}),y?"Saving & requesting retry…":"Save branch & retry"]})]})]}):(0,t.jsxs)("div",{className:"flex flex-wrap items-center justify-between gap-2",children:[(0,t.jsx)($,{type:"button",variant:"ghost",size:"sm",disabled:y||!!c,onClick:r(()=>p(!0),"onClick"),children:"Choose another branch"}),(0,t.jsxs)($,{type:"button",size:"sm",disabled:y||!!c||n===e,"aria-describedby":c?`${u}-unavailable`:void 0,onClick:r(()=>{I(n)},"onClick"),children:[y&&(0,t.jsx)(st,{"aria-hidden":!0,className:"size-3.5 animate-spin motion-reduce:animate-none"}),y?"Saving & requesting retry…":`Use ${n} & retry`]})]})]}),(0,t.jsxs)("div",{children:[(0,t.jsxs)($,{type:"button",variant:"ghost",size:"xs",className:"text-muted-foreground","aria-expanded":g,"aria-controls":`${u}-details`,onClick:r(()=>v(T=>!T),"onClick"),children:[g?"Hide details":"Why did this happen?",(0,t.jsx)(rn,{"aria-hidden":!0,className:W("size-3",g&&"rotate-180")})]}),g&&(0,t.jsx)("div",{id:`${u}-details`,className:"mt-2 rounded-md border border-border bg-background",children:(0,t.jsx)(YV,{tone:"neutral",sections:[{rows:[{kind:"text",label:"Setting",value:o?"Task-specific starting branch":"Workspace starting branch"},{kind:"code",label:"Requested branch",value:e},...i?[{kind:"text",label:"Set by",value:i}]:[],{kind:"text",label:"Why it stopped",value:o?"An explicit task branch overrides the repository default. Paperclip does not silently switch branches.":"The configured starting branch must resolve before the agent can start. This repair overrides it for this task."}]}]})})]})]})]})}r(iAe,"WorkspaceBaseRefRecoveryNotice");var JV=(0,m.createContext)(null);function ibt({value:e,children:s}){return(0,t.jsx)(JV.Provider,{value:e,children:s})}r(ibt,"DispositionRecoveryProvider");function obt(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(obt,"readDispositionRecoverySnapshot");function oAe(e){return obt(e,(0,m.useContext)(JV)?.issue.activeRecoveryAction)}r(oAe,"useDispositionRecoverySnapshot");function lbt(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(lbt,"dispositionRetryUnavailableReason");function cbt(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(cbt,"descriptionFor");function XV({snapshot:e,createdAt:s,defaultExpanded:n=!1}){const a=(0,m.useContext)(JV),[i,o]=(0,m.useState)(n),[l,c]=(0,m.useState)(!1),[d,u]=(0,m.useState)(!1),[h,p]=(0,m.useState)(null),f=(0,m.useRef)(!1),x=(0,m.useId)(),g=(0,m.useId)(),v=(0,m.useId)(),y=lbt(e,a),k=!!(a&&a.issue.activeRecoveryAction?.id!==e.actionId),w=e.assigneeAgentId&&a?.agentMap?.get(e.assigneeAgentId)?.name||"the assigned agent",N=d||k?cs:Es;async function S(){if(!(!a||y||f.current)){f.current=!0,c(!0),p(null);try{await a.onRetry(e.actionId),u(!0)}catch(C){p(C instanceof Error?C.message:"Refresh the task to check its current state, then try again.")}finally{f.current=!1,c(!1)}}}return r(S,"retry"),(0,t.jsxs)("section",{"aria-labelledby":g,className:"flex min-w-0 gap-2.5 py-3","data-testid":"disposition-recovery-notice",children:[(0,t.jsx)(N,{"aria-hidden":"true",className:W("mt-0.5 size-4 shrink-0",d||k?"text-muted-foreground":"text-(--status-task-icon-todo)")}),(0,t.jsxs)("div",{className:"flex min-w-0 flex-1 flex-col gap-2",children:[(0,t.jsxs)("div",{className:"flex flex-col gap-1",role:"status","aria-live":"polite",children:[(0,t.jsx)("h2",{id:g,className:"break-words text-sm font-medium text-foreground",children:d?"Retry requested":k?"Agent needed attention":"Agent needs attention"}),(0,t.jsx)("p",{className:"text-sm leading-relaxed text-muted-foreground",children:d?`The task was returned to To do for ${w}.`:cbt(e)})]}),y&&!d?(0,t.jsxs)("p",{id:v,className:"text-xs leading-relaxed text-muted-foreground",children:[!k&&(0,t.jsx)("span",{className:"font-medium text-foreground",children:"Retry unavailable. "}),y]}):null,h?(0,t.jsxs)("p",{role:"alert",className:"text-sm text-destructive",children:["Couldn’t confirm the retry. ",h]}):null,(0,t.jsxs)("div",{className:"flex flex-wrap items-center gap-2",children:[!d&&!k?(0,t.jsxs)($,{size:"xs",variant:"outline",disabled:l||!!y,"aria-describedby":y?v:void 0,onClick:r(()=>{S()},"onClick"),children:[l?(0,t.jsx)(st,{"aria-hidden":"true",className:"size-3 animate-spin motion-reduce:animate-none"}):(0,t.jsx)(_i,{"aria-hidden":"true",className:"size-3"}),l?"Requesting retry…":"Retry agent"]}):null,(0,t.jsxs)($,{size:"xs",variant:"ghost",className:"text-muted-foreground","aria-expanded":i,"aria-controls":x,onClick:r(()=>o(C=>!C),"onClick"),children:[i?"Hide details":"View details",(0,t.jsx)(rn,{"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:Hi(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(XV,"DispositionRecoveryNotice");var dbt="System update",ubt=80;function mbt(e){const s=e.match(/Latest retry failure: `([^`]+)`/);return s?s[1]:null}r(mbt,"retryFailureCode");function hbt(e){const s=e.match(/Recovery owner: \[([^\]]+)\]\(/)?.[1]?.trim();return s&&s.length>0?s:null}r(hbt,"recoveryOwnerName");function pbt(e){const s=e.split(`
383
383
  `).map(i=>i.trim()).find(i=>i.length>0);if(!s)return;const n=s.search(/[.!?](\s|$)/),a=n>=0?s.slice(0,n+1):s;return a.length<=ubt?a:`${a.slice(0,79).trimEnd()}…`}r(pbt,"firstSentence");function fbt(e){const s=e.presentation?.title?.trim(),n=e.presentation?.tone;if(s)return{title:s,tone:n??"neutral"};const a=e.body??"",i=mbt(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=hbt(a);return{title:o?`Task paused — waiting on ${o}`:"Task paused — waiting on a recovery owner",tone:n??"warning"}}return{title:dbt,tone:n??"neutral",detail:pbt(a)}}r(fbt,"humanizeSystemNotice");var xbt={neutral:"System notice",info:"System notice",success:"System notice",warning:"System warning",danger:"System alert"};function s1(e,s){const n=e.label?.trim();return n&&n.length>0?n:s}r(s1,"metadataRowText");function gbt(e,s){switch(e.type){case"text":return{kind:"text",label:s1(e,"Detail"),value:e.text};case"code":return{kind:"code",label:s1(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:s1(e,"Task"),identifier:n,href:`/issues/${n}`,title:e.title??void 0}:{kind:"text",label:s1(e,"Task"),value:e.title??"unknown"}}case"agent_link":{const n=e.name?.trim()||e.agentId.slice(0,8);return{kind:"agent",label:s1(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:s1(e,"Run"),runId:e.runId,href:a,status:e.title??void 0}}default:return null}}r(gbt,"mapMetadataRow");function eG(e,s={}){return!e||!Array.isArray(e.sections)?[]:e.sections.map(n=>{const a=n.rows.map(o=>gbt(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(eG,"mapCommentMetadataToSystemNoticeSections");function lAe(e,s){const n=s?.trim();return n&&n.length>0?n:xbt[e]}r(lAe,"systemNoticeLabelForTone");function bbt(e){const s=e.presentation?.tone??"neutral",n=lAe(s,e.presentation?.title),a=!!e.presentation?.detailsDefaultOpen,i=eG(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(bbt,"buildSystemNoticeProps");var vbt={neutral:e0,info:e0,success:xa,warning:Es,danger:dN},ybt={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 jbt({item:e,onTryAgainNoLiveExecutionPath:s,tryAgainNoLiveExecutionPathPending:n=!1}){const a=oAe(e.metadata),i=rAe(e.metadata),o=sp(),[l,c]=(0,m.useState)(!!e.presentation?.detailsDefaultOpen),d=(0,m.useId)(),{title:u,tone:h,detail:p}=fbt({body:e.text,presentation:e.presentation}),f=eG(e.metadata,{runAgentId:e.runAgentId}),x=!(e.presentation?.kind==="system_notice"&&e.presentation.title?.trim().toLowerCase().startsWith("workspace ready")===!0&&f.some(w=>w.title?.trim().toLowerCase()==="workspace")),g=vbt[h],v=e.createdAtIso?Hi(e.createdAtIso):void 0,y=!!s&&(e.presentation?.title?.trim()==="No live execution path"||e.text.toLowerCase().includes("no live execution path")),k=r(()=>{Promise.resolve().then(()=>s?.()).catch(()=>{})},"handleTryAgain");return e.author==="system"&&i?(0,t.jsx)(iAe,{...i.props},`${i.actionId}:${i.runId}`):e.author==="system"&&a?(0,t.jsx)(XV,{snapshot:a,createdAt:e.createdAtIso,defaultExpanded:e.presentation?.detailsDefaultOpen}):(0,t.jsxs)("div",{className:W("tc-enter-bubble flex flex-col items-start",o?"py-0.5":"py-1"),"data-testid":"task-chat-system-notice","data-tone":o?h:void 0,role:o?"group":void 0,"aria-label":o?`System update: ${u}`:void 0,children:[(0,t.jsxs)("div",{className:"flex max-w-(--pct-85) items-center gap-1.5",children:[(0,t.jsxs)("button",{type:"button",onClick:r(()=>c(w=>!w),"onClick"),"aria-expanded":l,"aria-controls":d,className:W("flex min-w-0 items-center gap-1.5 rounded-md px-2 py-0.5 text-xs text-muted-foreground","hover:bg-muted/50 hover:text-foreground","focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring/50"),children:[(0,t.jsx)(g,{className:W("h-3.5 w-3.5 shrink-0",ybt[h]),"aria-hidden":!0}),(0,t.jsx)("span",{className:"truncate font-medium",children:u}),p?(0,t.jsxs)("span",{className:"hidden truncate sm:inline",children:["· ",p]}):null,v?(0,t.jsxs)("span",{className:"shrink-0 text-muted-foreground/70",children:["· ",v]}):null,(0,t.jsx)(rn,{className:W("tc-notice-chevron h-3.5 w-3.5 shrink-0 transition-transform",l&&"rotate-180"),"aria-hidden":!0})]}),y&&!l?(0,t.jsx)($,{type:"button",variant:"outline",size:"xs",onClick:k,disabled:n,"data-testid":"task-chat-no-live-path-try-again",children:n?"Trying again...":"Try again"}):null]}),l?(0,t.jsxs)("div",{id:d,"data-testid":"task-chat-system-notice-details",className:"mt-1 w-full max-w-(--pct-85) overflow-hidden rounded-lg border border-border bg-muted/25 text-left text-sm dark:bg-muted/15",children:[x?(0,t.jsx)("div",{className:"px-3 py-2.5 text-foreground/90",children:(0,t.jsx)(Sn,{softBreaks:!0,linkIssueReferences:!0,children:e.text})}):null,f.length>0?(0,t.jsx)("div",{className:W("bg-background/50 dark:bg-background/30",x&&"border-t border-border/70"),children:(0,t.jsx)(YV,{sections:f,tone:h})}):null,y?(0,t.jsx)("div",{className:"flex justify-end border-t border-border/70 bg-background/50 px-3 py-2 dark:bg-background/30",children:(0,t.jsx)($,{type:"button",size:"xs",onClick:k,disabled:n,"data-testid":"task-chat-no-live-path-try-again",children:n?"Trying again...":"Try again"})}):null]}):null]})}r(jbt,"TaskChatSystemNotice");function tG({agentName:e,agentIcon:s,agent:n}){return(0,t.jsxs)("span",{className:"flex items-center gap-2 px-1","data-testid":"task-chat-agent-identity",children:[(0,t.jsx)("span",{"data-testid":"task-chat-agent-avatar",children:(0,t.jsx)(lr,{agent:n,name:e,size:24})}),(0,t.jsx)("span",{className:"text-sm font-semibold text-foreground",children:e})]})}r(tG,"TaskChatAgentIdentity");function Rie(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(Rie,"galleryItemForMedia");function Eie(e){return e.filter((s,n)=>e.findIndex(a=>s.id&&a.id===s.id||a.url===s.url)===n)}r(Eie,"uniqueAttachmentRefs");function cAe(e){return tAe(e.item.id)??(0,t.jsx)(wbt,{...e})}r(cAe,"TaskChatBubble");function wbt({item:e,animateEntry:s=!0,queuedAction:n,attachedTurn:a,beforeTurn:i,hideAgentIdentity:o=!1,actions:l,attachments:c=[],onTryAgainNoLiveExecutionPath:d,tryAgainNoLiveExecutionPathPending:u}){const h=sp(),p=(0,m.useContext)(jg),f=(0,m.useContext)(rj),[x,g]=(0,m.useState)(null),v=(0,m.useCallback)(D=>{f?.(D)||g(D)},[f]);if(e.interstitial)return null;if(e.author==="system")return(0,t.jsx)(jbt,{item:e,onTryAgainNoLiveExecutionPath:d,tryAgainNoLiveExecutionPathPending:u});const y=e.author==="human",k=y&&e.isCurrentUser===!0,w=y&&e.sourceChannel==="imessage-photon",{refs:N,text:S}=cXe(e.text),C=oXe(S),_=lXe(S),R=zse(N,c),I=zse(C,c),T=c.filter(D=>D.issueCommentId===e.id).map(D=>({id:D.id,name:D.originalFilename?.trim()||"attachment",url:D.contentPath,contentType:D.contentType,byteSize:D.byteSize,openPath:D.openPath,downloadPath:D.downloadPath})),E=Eie([...I,...R.filter(kI),...T.filter(kI)]),L=Eie([...R.filter(D=>!kI(D)),...T.filter(D=>!kI(D))]),O=[...E,...L.filter(D=>fm(D.contentType,D.name))],P=x!==null&&!O.some(D=>D.url===x)?[Rie(x)]:O.map(D=>Rie(D.url,D.name,D)),Q=x===null?-1:Math.max(0,O.findIndex(D=>D.url===x));return(0,t.jsxs)("div",{className:W("flex w-full flex-col gap-1",s&&"tc-enter-bubble",k?"items-end":"items-start"),children:[i?(0,t.jsx)("div",{className:"w-full pb-1",children:i}):null,y&&!e.isCurrentUser&&e.authorName?(0,t.jsx)("span",{className:"px-1 text-sm font-semibold text-foreground","data-testid":"task-chat-human-identity","data-author-user-id":e.authorUserId,children:(0,t.jsx)(So,{name:e.authorName,avatarUrl:tbt(e.authorAvatarUrl),size:"default",className:"gap-2"})}):null,!y&&e.authorName&&!o?(0,t.jsx)(tG,{agentName:e.authorName,agentIcon:e.agentIcon,agent:e.agent}):null,_.length>0?(0,t.jsx)("div",{"data-testid":y?"task-chat-human-bubble":"task-chat-agent-bubble",className:W("break-words py-2 text-sm",k?"max-w-(--pct-85) rounded-2xl rounded-br-sm bg-(--liveness-blue) px-3.5 text-white":"w-full bg-transparent px-1 text-foreground"),children:(0,t.jsx)(Sn,{className:k?"paperclip-markdown-on-accent":void 0,softBreaks:!0,linkIssueReferences:!0,onImageClick:v,children:_})}):null,E.length>0?(0,t.jsxs)("div",{className:"flex max-w-(--pct-85) flex-col gap-2","data-testid":"task-chat-bubble-media",children:[(0,t.jsxs)("span",{className:"text-xs text-muted-foreground",children:["Images · ",E.length]}),(0,t.jsxs)("div",{className:"grid grid-cols-4 gap-2",children:[E.slice(0,E.length>4?3:4).map((D,F)=>(0,t.jsx)("button",{type:"button",className:"group aspect-video min-w-0 overflow-hidden rounded-md bg-muted outline-none focus-visible:ring-2 focus-visible:ring-ring","aria-label":`Open ${D.name||`image ${F+1}`}`,onClick:r(()=>v(D.url),"onClick"),children:(0,t.jsx)("img",{src:D.openPath??D.url,alt:D.name,loading:"lazy",className:"h-full w-full object-cover transition-transform group-hover:scale-(--s-1_02)"})},D.url)),E.length>4?(0,t.jsxs)("button",{type:"button",className:"aspect-video min-w-0 rounded-md bg-muted text-sm font-semibold text-foreground outline-none focus-visible:ring-2 focus-visible:ring-ring","aria-label":`Open ${E.length-3} more screenshots`,onClick:r(()=>v(E[3].url),"onClick"),children:["+",E.length-3]}):null]}),(0,t.jsx)("span",{className:"truncate text-xs text-muted-foreground",children:E.map(D=>D.name||"image").join(" · ")})]}):null,L.length>0?(0,t.jsxs)("div",{className:"flex max-w-(--pct-85) flex-col gap-2",children:[(0,t.jsxs)("span",{className:"text-xs text-muted-foreground",children:["Files · ",L.length]}),(0,t.jsx)(jH,{"data-testid":"task-chat-bubble-attachments",children:L.map(D=>{const F=dSe(D),z=F.icon,K=wH(D.byteSize),U=fm(D.contentType,D.name);return(0,t.jsxs)(xH,{size:"sm",children:[(0,t.jsx)(gH,{className:U?"aspect-video group-data-[size=sm]/attachment:w-20":void 0,children:U?(0,t.jsx)(iA,{artifact:{title:D.name,contentPath:D.openPath??D.url,mediaKind:"video"}}):(0,t.jsx)(z,{"aria-hidden":!0})}),(0,t.jsxs)(bH,{children:[(0,t.jsx)(vH,{className:"max-w-48",children:D.name}),(0,t.jsx)(yH,{className:"max-w-48",children:K?`${F.label} · ${K}`:F.label})]}),(0,t.jsx)(iSe,{"aria-label":`Open ${D.name}`,onClick:U?()=>v(D.url):void 0,render:U?(0,t.jsx)("button",{type:"button"}):(0,t.jsx)("a",{href:D.openPath??D.url,onClick:r(q=>{p&&D.id&&mw({contentType:D.contentType??"",originalFilename:D.name})&&!q.metaKey&&!q.ctrlKey&&!q.shiftKey&&!q.altKey&&(q.preventDefault(),p(D.id,D.name))},"onClick"),target:"_blank",rel:"noreferrer"})})]},D.url)})})]}):null,!y&&e.verificationCaveats?.length?(0,t.jsxs)("div",{className:"mx-1 w-(--sz-calc-7) rounded-md border border-amber-500/25 bg-amber-500/5 px-3 py-2 text-xs","data-testid":"task-chat-verification-caveats",children:[(0,t.jsx)("p",{className:"font-medium text-amber-800 dark:text-amber-200",children:"Verification caveat"}),(0,t.jsx)("ul",{className:"mt-1 space-y-1 text-muted-foreground",children:e.verificationCaveats.map((D,F)=>(0,t.jsxs)("li",{children:[(0,t.jsx)("span",{className:"font-mono text-foreground",children:D.commandOrCheck}),D.reasonCode?` · ${D.reasonCode.replaceAll("_"," ")}`:"",D.detail?(0,t.jsx)("span",{className:"block",children:D.detail}):null]},`${D.commandOrCheck}:${F}`))})]}):null,e.optimistic?(0,t.jsxs)("span",{className:"flex items-center gap-1 px-1 text-(length:--text-micro) text-muted-foreground",children:[(0,t.jsx)("span",{children:e.optimistic==="queued"?"Queued":"Sending…"}),e.optimistic==="queued"?n:null]}):a?(0,t.jsx)("div",{className:"self-stretch","data-testid":"task-chat-bubble-attached-turn",children:a}):l?h?(0,t.jsxs)("div",{className:"flex w-full items-center justify-between gap-2 px-1",children:[e.timestamp||w?(0,t.jsxs)("span",{className:"text-(length:--text-micro) text-muted-foreground",children:[w?"Sent from iMessage":null,w&&e.timestamp?" · ":null,e.timestamp]}):null,l]}):(0,t.jsxs)("div",{className:"flex items-center gap-1",children:[l,e.timestamp||w?(0,t.jsxs)("span",{className:"px-1 text-(length:--text-micro) text-muted-foreground",children:[w?"Sent from iMessage":null,w&&e.timestamp?" · ":null,e.timestamp]}):null]}):e.timestamp||w?(0,t.jsxs)("span",{className:"px-1 text-(length:--text-micro) text-muted-foreground",children:[w?"Sent from iMessage":null,w&&e.timestamp?" · ":null,e.timestamp]}):null,x!==null&&Q>=0?(0,t.jsx)(hw,{items:P,initialIndex:Q,open:!0,onOpenChange:r(D=>{D||g(null)},"onOpenChange")}):null]})}r(wbt,"TaskChatBubbleContent");function Lie(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(Lie,"turnSummaryMetrics");function Mie({item:e,renderChild:s,timestampPrefix:n,leading:a}){const i=sp(),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)(tG,{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,g]=(0,m.useState)(e.settled),[v,y]=(0,m.useState)(o);o&&!v&&y(!0),e.settled!==x&&(g(e.settled),e.settled&&!v&&h(!1));const k=d.length>0,w=(e.settled||o)&&!u,N=e.summary.failed?En:cs,S=e.settled&&(!e.historical||k)?(0,t.jsxs)("button",{type:"button",onClick:r(()=>h(C=>!C),"onClick"),"aria-expanded":u,className:W("group flex w-full items-center gap-2 px-1 text-muted-foreground transition-colors hover:text-foreground",e.standaloneHeader?"border-b border-border/70 py-2 text-sm":"py-0.5 text-xs",i&&"min-w-0"),"data-testid":"task-chat-turn-summary",children:[n?(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)("span",{className:"text-(length:--text-micro)",children:n}),(0,t.jsx)("span",{"aria-hidden":!0,className:"text-(length:--text-micro)",children:"·"})]}):null,!e.standaloneHeader&&!e.historical?(0,t.jsx)(N,{className:"h-3.5 w-3.5 shrink-0"}):null,(0,t.jsx)("span",{children:e.historical?"Activity":e.standaloneHeader&&e.summary.durationLabel?`${e.summary.failed?"Stopped":"Worked"} for ${e.summary.durationLabel}`:e.summary.failed?"Stopped":"Worked"}),!e.standaloneHeader&&Lie(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:Lie(e.summary)})}):null,(0,t.jsx)(An,{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)(U3e,{item:e.liveStatus,chevronOpen:k?u:void 0,onToggle:k?()=>h(C=>!C):void 0}):null;return(0,t.jsxs)("div",{"data-testid":"task-chat-turn","data-settled":e.settled?"true":"false",children:[a?i?(0,t.jsxs)("div",{className:"flex w-full items-center justify-between gap-2",children:[(0,t.jsx)("div",{className:"min-w-0",children:S}),(0,t.jsx)("div",{className:"shrink-0",children:a})]}):(0,t.jsxs)("div",{className:"flex items-center gap-1",children:[a,S]}):S,(0,t.jsx)("div",{className:"tc-turn-fold","data-folded":w?"true":"false","aria-hidden":w,children:(0,t.jsx)("div",{children:(0,t.jsx)("div",{className:"flex flex-col gap-2 pt-1",children:p&&d.map(C=>(0,t.jsx)("div",{children:s(C)},C.id))})})}),l.length>0?(0,t.jsx)("div",{className:"flex flex-col gap-2 pt-2","data-testid":"task-chat-turn-persistent-history",children:l.map(C=>(0,t.jsx)("div",{children:s(C)},C.id))}):null]})}r(Mie,"TaskChatTurn");var kbt={session_start:Ju,interrupted:AW,turn_boundary:fg};function dAe({item:e,onTryAgain:s,tryAgainPending:n=!1}){const[a,i]=(0,m.useState)(!1),o=(0,m.useId)(),l=sp(),c=e.tone==="neutral"?vg:kbt[e.variant],d=e.variant==="interrupted"&&e.tone!=="neutral",u=e.createdAtIso?Hi(e.createdAtIso):void 0,h=r(()=>{Promise.resolve().then(()=>s?.()).catch(()=>{})},"handleTryAgain");if(e.credentialAccess){const{agentName:p,credentialName:f,deniedUser:x,settingsHref:g}=e.credentialAccess;return(0,t.jsxs)("div",{role:"alert","data-testid":"task-chat-credential-access-notice",className:"tc-enter-marker flex w-full items-start gap-3 rounded-lg border border-destructive/40 bg-destructive/10 p-4 text-sm",children:[(0,t.jsx)(Ni,{className:"mt-0.5 size-5 shrink-0 text-destructive","aria-hidden":!0}),(0,t.jsxs)("div",{className:"flex min-w-0 flex-1 flex-col gap-2",children:[(0,t.jsxs)("p",{className:"font-semibold text-destructive",children:[p," couldn’t start"]}),(0,t.jsxs)("p",{className:"break-words font-medium text-foreground",children:[p," is configured to use ",f||"an AI credential",", but ",x==="you"?"you don’t":`${x} doesn’t`," have access to that credential."]}),(0,t.jsxs)("p",{className:"text-muted-foreground",children:["Choose an AI connection ",x==="you"?"you can":`${x} can`," use, or ask an administrator to update ",p,"’s connection. Then try again."]}),(0,t.jsxs)("div",{className:"flex flex-wrap items-center gap-2 pt-1",children:[(0,t.jsx)($,{asChild:!0,variant:"outline",size:"sm",children:(0,t.jsx)(Ke,{to:g,children:"Change AI connection"})}),e.runHref&&(0,t.jsx)($,{asChild:!0,variant:"ghost",size:"sm",children:(0,t.jsx)(Ke,{to:e.runHref,children:"View run"})})]})]})]})}return e.collapsible?(0,t.jsxs)("div",{className:"tc-enter-marker flex flex-col items-start py-1 text-xs text-muted-foreground","data-testid":"task-chat-collapsible-marker",children:[(0,t.jsxs)("div",{className:"flex max-w-(--pct-85) items-center gap-1.5",children:[(0,t.jsxs)("button",{type:"button",onClick:r(()=>i(p=>!p),"onClick"),"aria-expanded":a,"aria-controls":o,className:W("flex min-w-0 items-center gap-1.5 rounded-md px-2 py-0.5",d?"text-destructive":"text-muted-foreground","hover:bg-muted/50 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring/50"),children:[(0,t.jsx)(c,{className:"h-3.5 w-3.5 shrink-0","aria-hidden":!0}),(0,t.jsx)("span",{className:"truncate font-medium",children:e.label}),u?(0,t.jsxs)("span",{className:"shrink-0 text-muted-foreground/70",children:["· ",u]}):null,(0,t.jsx)(rn,{className:W("tc-notice-chevron h-3.5 w-3.5 shrink-0 transition-transform",a&&"rotate-180"),"aria-hidden":!0})]}),s&&!a?(0,t.jsx)($,{type:"button",variant:"outline",size:"xs",onClick:h,disabled:n,"data-testid":"task-chat-run-failed-try-again",children:n?"Trying again...":"Try again"}):null]}),a?(0,t.jsxs)("div",{id:o,"data-testid":"task-chat-collapsible-marker-details",className:"mt-1 w-full max-w-(--pct-85) overflow-hidden rounded-lg border border-border bg-muted/25 text-left text-sm dark:bg-muted/15",children:[e.detail?(0,t.jsx)("div",{className:"px-3 py-2.5 text-foreground/90",children:e.detail}):null,e.runHref||e.planHref||s?(0,t.jsxs)("div",{className:"flex items-center justify-end gap-2 border-t border-border/70 bg-background/50 px-3 py-2 dark:bg-background/30",children:[e.planHref?(0,t.jsx)($,{asChild:!0,variant:"ghost",size:"xs",children:(0,t.jsx)(Ke,{to:e.planHref,children:"View saved plan"})}):null,e.runHref?(0,t.jsx)($,{asChild:!0,variant:"ghost",size:"xs",children:(0,t.jsx)(Ke,{to:e.runHref,children:"View run"})}):null,s?(0,t.jsx)($,{type:"button",size:"xs",onClick:h,disabled:n,"data-testid":"task-chat-run-failed-try-again",children:n?"Trying again...":"Try again"}):null]}):null]}):null]}):(0,t.jsxs)("div",{className:"tc-enter-marker flex items-center gap-2 py-1 text-xs text-muted-foreground",role:l?"separator":void 0,"aria-label":l?e.label:void 0,children:[(0,t.jsx)("span",{className:W("h-px flex-1",d?"border-t border-dashed border-destructive/50":"bg-border")}),(0,t.jsxs)("span",{className:W("flex items-center gap-1.5",d&&"text-destructive"),children:[(0,t.jsx)(c,{className:"h-3.5 w-3.5"}),(0,t.jsx)("span",{className:"font-medium",children:e.label}),e.detail?(0,t.jsxs)("span",{className:"text-muted-foreground",children:["· ",e.detail]}):null,s?(0,t.jsx)($,{type:"button",variant:"outline",size:"xs",onClick:h,disabled:n,"data-testid":"task-chat-run-failed-try-again",children:n?"Trying again...":"Try again"}):null]}),(0,t.jsx)("span",{className:W("h-px flex-1",d?"border-t border-dashed border-destructive/50":"bg-border")})]})}r(dAe,"TaskChatMarker");var uAe=(0,m.createContext)(null);function Nbt(e){const[s,n]=(0,m.useState)(()=>({issueId:e,memory:new Map}));if(s.issueId===e)return s.memory;const a={issueId:e,memory:new Map};return n(a),a.memory}r(Nbt,"useIssueExpansionMemory");function BM(e,s){const n=(0,m.useContext)(uAe),[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(BM,"useTaskChatExpansion");var Sbt={pending:{Icon:st,spin:!1,tone:"text-muted-foreground"},in_progress:{Icon:st,spin:!0,tone:"text-(--status-agent-running)"},completed:{Icon:cs,spin:!1,tone:"text-muted-foreground"},failed:{Icon:En,spin:!1,tone:"text-destructive"},interrupted:{Icon:En,spin:!1,tone:"text-muted-foreground"}};function mAe({item:e}){const{Icon:s,spin:n,tone:a}=Sbt[e.status],i=EN(e.rawName??e.name).icon,[o,l]=BM(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)(qi,{className:"h-3 w-3"}):(0,t.jsx)(PW,{className:"h-3 w-3"}),e.decision]}):null,c?(0,t.jsx)(An,{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(mAe,"TaskChatToolCard");function sG({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)(NW,{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(sG,"TaskChatUsageReadout");function hAe(e){const s=e.details.find(n=>n.label==="Severity")?.value;return e.status==="failed"||s==="error"?"error":s==="info"?"info":"warning"}r(hAe,"providerNoticeSeverity");function fp(e,...s){return e.details.find(n=>s.includes(n.label))?.value}r(fp,"providerDetail");function PD(e){if(!(!e||ju(e)||/^tool(?:\s+|_)call\b/i.test(e)))return e}r(PD,"meaningfulToolDetail");function Cbt(e){const s=e.summary??fp(e,"Query","URL","Target","Name","Reference","Reason","Summary");switch(e.family){case"research":{const n=fp(e,"Action")?.toLowerCase();return n==="open_page"?{icon:Jr,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:Jr,runningLabel:"Searching the page",completedLabel:"Searched the page",failedLabel:"Page search failed",interruptedLabel:"Page search stopped",detail:s}:{icon:Jr,runningLabel:"Searching the web",completedLabel:"Searched the web",failedLabel:"Web search failed",interruptedLabel:"Web search stopped",detail:s}}case"tool_execution":{const n=fp(e,"Name"),a=fp(e,"Target"),i=fp(e,"Progress"),o=Tj({name:n,transport:fp(e,"Transport"),namespace:fp(e,"Namespace"),operation:fp(e,"Operation"),target:a,progress:i}),l=PD(e.summary)??PD(i)??PD(a),c=!!(l&&n&&Mk(l)===Mk(n)),d=n?HV(n)?.name??n:o.displayName,u=o.sourceLabel?`${o.sourceLabel} · ${d}`:n&&!ju(n)&&Mk(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:ew,runningLabel:"Updating the plan",completedLabel:"Updated the plan",failedLabel:"Plan update failed",interruptedLabel:"Plan update stopped",detail:s};case"delegation":{const n=fp(e,"Action")?.toLowerCase();return n==="message"?{icon:Ho,runningLabel:"Messaging a subagent",completedLabel:"Messaged a subagent",failedLabel:"Subagent message failed",interruptedLabel:"Subagent message stopped",detail:s}:n==="resume"?{icon:Ho,runningLabel:"Resuming a subagent",completedLabel:"Resumed a subagent",failedLabel:"Couldn’t resume the subagent",interruptedLabel:"Subagent resume stopped",detail:s}:n==="close"?{icon:Ho,runningLabel:"Closing a subagent",completedLabel:"Closed a subagent",failedLabel:"Couldn’t close the subagent",interruptedLabel:"Subagent close stopped",detail:s}:n==="wait"?{icon:Ho,runningLabel:"Waiting for subagents",completedLabel:"Finished waiting for subagents",failedLabel:"Subagent wait failed",interruptedLabel:"Stopped waiting for subagents",detail:s}:{icon:Ho,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:io,runningLabel:"Switching models",completedLabel:"Switched models",failedLabel:"Model switch failed",interruptedLabel:"Model switch stopped",detail:s}:{icon:io,runningLabel:"Verifying the model",completedLabel:"Verified the model",failedLabel:"Model verification failed",interruptedLabel:"Model verification stopped",detail:s};case"context":return{icon:f3,runningLabel:"Compacting context",completedLabel:"Compacted context",failedLabel:"Context compaction failed",interruptedLabel:"Context compaction stopped",detail:s};case"artifact":return e.eventType==="artifact.viewed"?{icon:U_,runningLabel:"Viewing an artifact",completedLabel:"Viewed an artifact",failedLabel:"Couldn’t view the artifact",interruptedLabel:"Artifact view stopped",detail:s}:{icon:U_,runningLabel:"Generating an artifact",completedLabel:"Generated an artifact",failedLabel:"Artifact generation failed",interruptedLabel:"Artifact generation stopped",detail:s};case"review":return fp(e,"State")?.toLowerCase()==="exited"?{icon:_te,runningLabel:"Leaving review mode",completedLabel:"Left review mode",failedLabel:"Couldn’t leave review mode",interruptedLabel:"Review-mode change stopped",detail:s}:{icon:_te,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:to,runningLabel:"Running a hook",completedLabel:"Ran a hook",failedLabel:"Hook failed",interruptedLabel:"Hook stopped",detail:s};case"memory":return{icon:bS,runningLabel:"Checking memory",completedLabel:"Referenced memory",failedLabel:"Memory lookup failed",interruptedLabel:"Memory lookup stopped",detail:s};case"safety":return{icon:qi,runningLabel:"Reviewing safety",completedLabel:"Reviewed safety",failedLabel:"Safety review failed",interruptedLabel:"Safety review stopped",detail:s};case"terminal":return{icon:hm,runningLabel:"Sending terminal input",completedLabel:"Sent terminal input",failedLabel:"Terminal input failed",interruptedLabel:"Terminal input stopped",detail:s};case"wait":return{icon:Nu,runningLabel:"Waiting",completedLabel:"Finished waiting",failedLabel:"Wait failed",interruptedLabel:"Wait stopped",detail:s};case"provider_notice":return{icon:hAe(e)==="info"?e0:Es,runningLabel:"Provider notice",completedLabel:"Provider notice",failedLabel:"Provider error",interruptedLabel:"Provider notice",detail:s}}}r(Cbt,"providerActivityPresentation$1");function _bt(e){const s=e.totals.files||e.files.length,n=s>0?`${s} ${s===1?"file":"files"}`:void 0;return{icon:O8,runningLabel:"Editing files",completedLabel:"Edited files",detail:n}}r(_bt,"workspaceChangePresentation");function Abt(e){return{icon:ei,runningLabel:"Referencing a file",completedLabel:"Referenced a file",detail:e.line==null?e.path:`${e.path}:${e.line}`}}r(Abt,"workspaceFilePresentation");function Ibt(e){return{icon:e.resourceKind==="document"?ei:uN,runningLabel:"Saving a resource",completedLabel:e.resourceKind==="document"?"Added a document":"Added a deliverable",detail:e.title}}r(Ibt,"resourcePresentation");function pAe(e){switch(e.surface){case"provider_activity":return Cbt(e);case"workspace_change":return _bt(e);case"workspace_file":return Abt(e);case"resource":return Ibt(e);case"runtime_request":case"run_result":case"run_terminal":return null}}r(pAe,"protocolActivityPresentation");function fAe(e){return e.surface==="provider_activity"?e.status==="running":e.surface==="workspace_change"?!e.complete:!1}r(fAe,"protocolActivityIsRunning");function Tbt(e,s){return e.surface!=="provider_activity"?fAe(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(Tbt,"protocolActivityLabel");var Rbt={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 Ebt(e){const s=new Map,n=r((u,h,p=0)=>{const f=s.get(u);(!f||p<f.order)&&s.set(u,{label:u,icon:h,order:p})},"add"),a=[],i=[];for(const[u,h]of e.entries())if(h.kind==="tool"){const p=Tj({name:h.rawName??h.name,target:h.target});a.push({...p,order:u,completed:h.status==="completed"})}else if(h.kind==="protocol")if(h.surface==="provider_activity"&&h.family==="tool_execution"){const p=r(x=>h.details.find(g=>g.label===x)?.value,"value"),f=Tj({name:p("Name"),operation:p("Operation"),transport:p("Transport"),namespace:p("Namespace"),target:p("Target")});a.push({...f,order:u,completed:h.status==="completed"})}else{const p=pAe(h);if(!p)continue;if(h.surface==="provider_activity"&&h.family==="provider_notice"){const f=h.summary?.trim()||h.details.find(x=>x.label==="Summary")?.value.trim();i.push({summary:f,severity:hAe(h),icon:p.icon,order:u});continue}n({research:"Searched the web",plan:"Worked on a plan",delegation:"Worked with agents",artifact:"Worked with artifacts",context:"Managed context",memory:"Checked memory",model_identity:"Checked model settings",review:"Worked in review mode",hook:"Ran hooks",safety:"Reviewed safety",terminal:"Ran commands",wait:"Waited",workspace_change:"Worked on files",workspace_file:"Referenced files",resource:"Added resources"}[h.surface==="provider_activity"?h.family:h.surface]??"Used tools",p.icon,u)}if(i.length){const u=i.find(h=>h.severity==="error")??i.find(h=>h.severity==="warning")??i[0];n(i.length===1?u.summary||"Received a provider update":u.severity==="error"?"Provider error reported":u.severity==="warning"?"Provider warning reported":"Received provider updates",u.icon,u.severity==="info"?i[0].order:-1)}const o=new Set(a.filter(u=>u.completed).map(u=>u.family));for(const u of a){const h=o.has(u.family);n(u.family==="read"&&!h?"Checked files":u.family==="edit"&&!h?"Worked on files":Rbt[u.family],u.icon,u.order)}s.size||(e.some(u=>u.kind==="thinking")?n("Thought through the task",$x):e.some(u=>u.kind==="marker")?n("Activity stopped",Zd):n("Recorded usage",NW));const l=[...s.values()].sort((u,h)=>u.order-h.order),c=r(u=>u.map((h,p)=>p?h.charAt(0).toLowerCase()+h.slice(1):h).join(", "),"join"),d=c(l.map(u=>u.label));return{label:l.length>3?`${c(l.slice(0,2).map(u=>u.label))}, and more`:d,fullLabel:d,icon:l.length===1?l[0].icon:Gl}}r(Ebt,"completedActivitySummary");var Pie=5,Lbt=8;function Mbt(e,s=!1){return s&&(e==="blocked"||e==="failed")?(0,t.jsx)(ff,{className:"h-3 w-3 text-muted-foreground","aria-hidden":!0}):e==="in_progress"?(0,t.jsx)(st,{className:"h-3 w-3 animate-spin text-(--status-agent-running)","aria-hidden":!0}):e==="completed"?(0,t.jsx)(cs,{className:"h-3 w-3 text-(--status-task-icon-done)","aria-hidden":!0}):e==="blocked"||e==="failed"?(0,t.jsx)(En,{className:"h-3 w-3 text-destructive","aria-hidden":!0}):(0,t.jsx)(ff,{className:"h-3 w-3 text-muted-foreground","aria-hidden":!0})}r(Mbt,"stepStatusIcon");function xAe({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(xAe,"DetailList");function Pbt(e){try{return new URL(e).hostname.replace(/^www\./,"")}catch{return e}}r(Pbt,"sourceHostname");function Dbt({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,Pie),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)(Dn,{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:Pbt(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>Pie?(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)(xAe,{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(Dbt,"ResearchDetails");function $bt({item:e,neutral:s=!1}){return e.family==="research"?(0,t.jsx)(Dbt,{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:Mbt(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)(Dn,{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)(xAe,{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($bt,"ProviderDetails");function Obt({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,Lbt),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(Obt,"WorkspaceChangeDetails");function Bbt({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)(rye,{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(Bbt,"WorkspaceFileDetails");function gAe(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)($bt,{item:e,neutral:s}):null;case"workspace_change":return(0,t.jsx)(Obt,{item:e});case"workspace_file":return(0,t.jsx)(Bbt,{item:e});case"resource":case"runtime_request":case"run_result":case"run_terminal":return null}}r(gAe,"detailContent");function bAe(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(bAe,"safeActivityHref");function Fbt(e){return e.surface==="resource"?!!bAe(e.href):gAe(e)!==null||e.surface==="provider_activity"&&!!e.summary?.trim()}r(Fbt,"hasTaskChatProtocolActivityDetails");function zbt({item:e,neutral:s=!1}){const n=gAe(e,s);if(e.surface==="resource"){const a=bAe(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(zbt,"TaskChatProtocolActivityDetails");function vAe(e,s){if(e.kind==="tool"){const d=Tj({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:$x,label:d?"Thinking":"Thought",target:e.lines.filter(u=>u.trim()).at(-1)?.trim(),mono:!1,running:d}}if(e.kind==="protocol"){const d=pAe(e);return d?{icon:d.icon,label:Tbt(e,d),target:d.detail,mono:!0,running:s&&fAe(e)}:null}if(e.kind==="marker")return{icon:Zd,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:NW,label:e.label??"Token usage",target:c||e.detail,mono:!1,running:!1}}r(vAe,"presentation");function qbt({item:e,active:s}){const n=vAe(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(qbt,"ActivityContent");function Ubt({item:e}){return e.kind==="thinking"?(0,t.jsx)(Sn,{softBreaks:!0,children:e.lines.join(`
384
384
  `)}):e.kind==="usage"?(0,t.jsx)(sG,{item:e}):e.kind==="protocol"?(0,t.jsx)(zbt,{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(Ubt,"ActivityDetails");function Kbt(e){return e.kind==="protocol"?Fbt(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(Kbt,"hasActivityDetails");var Qbt=24;function Wbt(e){const s=(0,m.useRef)(null),n=(0,m.useRef)(e),a=(0,m.useRef)(0),i=(0,m.useCallback)(()=>{const l=s.current;l&&(n.current=!0,l.scrollTop=l.scrollHeight,a.current=l.scrollTop)},[]),o=(0,m.useCallback)(()=>{const l=s.current;if(!l)return;const c=l.scrollTop,d=c-a.current;if(a.current=c,d<-24){n.current=!1;return}d>0&&l.scrollHeight-c-l.clientHeight<=Qbt&&(n.current=!0)},[]);return(0,m.useLayoutEffect)(()=>{e&&i()},[e,i]),(0,m.useEffect)(()=>{const l=s.current;if(!l||typeof ResizeObserver>"u")return;const c=new ResizeObserver(()=>{n.current&&(l.scrollTop=l.scrollHeight,a.current=l.scrollTop)});for(const d of l.children)c.observe(d);return()=>c.disconnect()},[]),{ref:s,onScroll:o}}r(Wbt,"useFollowDetailBottom");var Hbt=new Set;function yAe(e){return e.items.filter(s=>vAe(s,!1)!==null)}r(yAe,"visibleActivities");function nG(e){const s=e.flatMap(n=>yAe(n).map(a=>a.id));return new Set(s.slice(-3))}r(nG,"newestActivityIds");function jAe({item:e,active:s,auto:n,current:a=!1}){const[i,o]=BM(`runner-detail:${e.id}`,n),[l,c]=(0,m.useState)(i),d=Wbt(i&&a===!0);i&&!l&&c(!0);const u=(0,m.useId)(),h=Kbt(e),p=(0,t.jsx)(qbt,{item:e,active:s});return(0,t.jsxs)("li",{className:"min-w-0","data-activity-item-id":e.id,"data-activity-open":h?i:void 0,"data-testid":a?"task-chat-activity-current":void 0,children:[h?(0,t.jsxs)("button",{type:"button",className:"flex h-8 w-full min-w-0 items-center gap-2 rounded-sm text-left text-muted-foreground hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring",onClick:r(()=>o(!i),"onClick"),"aria-expanded":i,"aria-controls":l?u:void 0,children:[p,(0,t.jsx)(An,{className:W("size-3.5 shrink-0",i&&"rotate-90"),"aria-hidden":"true"})]}):(0,t.jsx)("div",{className:"flex h-8 w-full min-w-0 items-center gap-2 text-muted-foreground",children:p}),h&&l?(0,t.jsx)("div",{id:u,hidden:!i,ref:d.ref,onScroll:d.onScroll,className:"flex max-h-(--sz-64) min-w-0 flex-col gap-2 overflow-y-auto rounded-md bg-muted/40 p-3 text-xs leading-relaxed text-muted-foreground [&>*]:shrink-0","data-testid":"task-chat-runner-activity-detail",children:(0,t.jsx)("div",{className:"flex min-w-0 flex-col gap-2","data-testid":"task-chat-runner-activity-body",children:(0,t.jsx)(Ubt,{item:e})})}):null]})}r(jAe,"ExpandedActivity");function Vbt({phaseId:e,activities:s,openIds:n,active:a}){const[i,o]=BM(`runner-earlier:${e}`,!1),l=(0,m.useId)(),c=s.at(-1),d=s.filter(h=>!n.has(h.id)).length,u=s.filter(h=>i||n.has(h.id));return(0,t.jsxs)("div",{className:"flex min-w-0 flex-col gap-1",children:[d>0?(0,t.jsxs)("button",{type:"button",className:"flex h-8 w-full min-w-0 items-center gap-2 rounded-sm text-left text-xs text-muted-foreground hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring","data-testid":"task-chat-activity-earlier-toggle",onClick:r(()=>o(!i),"onClick"),"aria-expanded":i,"aria-controls":l,children:[(0,t.jsx)("span",{className:"flex size-5 shrink-0 items-center justify-center",children:(0,t.jsx)(An,{className:W("size-3.5",i&&"rotate-90"),"aria-hidden":"true"})}),(0,t.jsx)("span",{children:i?`Hide ${d} earlier`:`+${d} earlier`})]}):null,(0,t.jsx)("ol",{id:l,className:"flex min-w-0 flex-col gap-1","aria-label":"Activity history","data-testid":"task-chat-runner-activity-list",children:u.map(h=>(0,t.jsx)(jAe,{item:h,active:a&&h===c,auto:n.has(h.id),current:h===c},h.id))})]})}r(Vbt,"LiveActivities");function Gbt({phaseId:e,activities:s}){const[n,a]=BM(e,!1),i=(0,m.useId)(),o=Ebt(s),l=o.icon,c=`${s.length} ${s.length===1?"activity":"activities"}`;return(0,t.jsxs)("div",{className:"min-w-0",children:[(0,t.jsxs)("button",{type:"button",className:"flex min-h-8 w-full min-w-0 items-center gap-2 rounded-sm text-left text-muted-foreground hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring","data-testid":"task-chat-activity-phase-toggle",onClick:r(()=>a(!n),"onClick"),"aria-expanded":n,"aria-controls":n?i:void 0,"aria-label":`${n?"Collapse":"Expand"} ${o.fullLabel.toLowerCase()} (${c})`,children:[(0,t.jsxs)("span",{className:"flex h-8 min-w-0 flex-1 items-center gap-2 text-xs","data-completed-summary":!0,children:[(0,t.jsx)("span",{className:"flex size-5 shrink-0 items-center justify-center",children:(0,t.jsx)(l,{className:"size-3.5","aria-hidden":"true"})}),(0,t.jsx)("span",{className:"truncate",title:o.fullLabel,children:o.label})]}),(0,t.jsxs)("span",{className:"flex shrink-0 items-center gap-1 text-xs",children:[n?c:null,(0,t.jsx)(An,{className:W("size-3.5",n&&"rotate-90"),"aria-hidden":"true"})]})]}),n?(0,t.jsx)("ol",{id:i,className:"flex min-w-0 flex-col gap-1","aria-label":"Activity history","data-testid":"task-chat-runner-activity-list",children:s.map(d=>(0,t.jsx)(jAe,{item:d,active:!1,auto:!1},d.id))}):null]})}r(Gbt,"SettledActivities");function R5({item:e,openActivityIds:s}){const n=yAe(e),a=s??(e.active?nG([e]):Hbt),i=n.some(o=>a.has(o.id));return(0,t.jsxs)("section",{className:"flex min-w-0 flex-col gap-2","data-testid":"task-chat-activity-phase","data-activity-group":e.id,"data-activity-mode":i?"live":"settled",children:[e.interstitial?(0,t.jsx)("div",{className:"min-w-0 px-1 text-sm text-foreground/90","data-testid":"task-chat-phase-interstitial",children:(0,t.jsx)(Sn,{softBreaks:!0,linkIssueReferences:!0,children:e.interstitial.text})}):null,i?(0,t.jsx)(Vbt,{phaseId:e.id,activities:n,openIds:a,active:e.active}):n.length>0?(0,t.jsx)(Gbt,{phaseId:e.id,activities:n}):null]})}r(R5,"TaskChatRunnerActivityGroup");var Ybt=80,Zbt=500;function FM(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)?e:null}r(FM,"record$6");function hq(e){if(typeof e=="string"&&e.trim())return e.trim();const s=FM(e)?.content;return typeof s=="string"&&s.trim()?s.trim():void 0}r(hq,"text$2");function Die(e){if(Array.isArray(e))for(const s of e){const n=hq(s);if(n)return n}}r(Die,"firstText");function wAe(e){const s=e.replace(/\s+/g," ").trim();return s.length>Ybt?`${s.slice(0,79)}…`:s}r(wAe,"clipSubject");function Jbt(e){if(!e)return;const s=hq(e.task);return s||(Die(e.items)??(Array.isArray(e.list)?e.list.map(n=>Die(FM(n)?.items)).find(Boolean):void 0)??hq(e.phase))}r(Jbt,"subjectFromArgs");function Xbt(e,s){return e?.trim().toLowerCase()==="todo"&&typeof FM(s)?.op=="string"}r(Xbt,"isAgentTodoCall");function evt(e,s){const n=FM(s),a=Jbt(n);return{id:e,kind:"todo",op:typeof n?.op=="string"&&n.op.trim()?n.op.trim():null,status:"in_progress",...a?{subject:wAe(a)}:{}}}r(evt,"todoItemFromCall");function tvt(e,s){e.status=s.delta?"in_progress":s.isError?"failed":"completed";const n=s.isError&&!s.delta?s.content?.trim():void 0;n&&(e.error=n.length>Zbt?`${n.slice(0,499)}…`:n);const a=CBe(s.details);if(a&&(e.op??=a.op,e.counts={completed:a.counts.completed,total:a.counts.total},!e.subject)){const i=RBe(a);i&&(e.subject=wAe(i))}}r(tvt,"applyTodoResult");function svt(e){const s=["Todo"],n=e.subject?` "${e.subject}"`:"";return s.push(e.status==="failed"?`${e.op??"update"} failed${n}`:`${vBe(e.op)}${n}`),e.counts&&e.status!=="failed"&&s.push(`${e.counts.completed}/${e.counts.total}`),s.join(" · ")}r(svt,"todoRowText");var nvt=new Set(["failed","timed_out","cancelled","interrupted","succeeded"]);function aj(e){return e!=null&&nvt.has(e)}r(aj,"isTerminalRunStatus$1");function $ie(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($ie,"splitTranscriptAtAnchors");function rvt(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(rvt,"flattenSelfTalk");function avt(e){return e==="add"?"add":e==="remove"?"remove":"context"}r(avt,"diffKind");var ivt=["file_path","path","notebook_path","command","pattern","query","url","prompt","description","skill","subject"],MC=96,ovt=/^xd:\/\/([A-Za-z0-9_]+)$/,lvt={resolve:!0,reject:!0,propose:!0,report_issue:!0};function cvt(e){if(typeof e!="string")return null;const s=ovt.exec(e.trim());return s?s[1]in lvt?null:s[1]:null}r(cvt,"xdDeviceFromPath");function dvt(e,s){if(e?.trim()!=="write"||s==null||typeof s!="object")return null;const n=s,a=cvt(n.path);return a||(typeof n.path=="string"||!("content"in n)?null:mvt(n.content))}r(dvt,"xdDeviceToolName");var uvt=/"code"\s*:\s*"[\s\S]{0,400}?omp\./;function mvt(e){return typeof e!="string"?null:uvt.test(e)?"fabric_exec":null}r(mvt,"fabricDeviceFromPayload");function gb(e,s){const n=e.replace(/\s+/g," ").trim();return n.length>s?`${n.slice(0,s-1)}…`:n}r(gb,"clip");function hvt(e){if(e==null)return;if(typeof e=="string")return e.trim()?gb(e,MC):void 0;if(typeof e!="object")return gb(String(e),MC);const s=e;for(const a of ivt){const i=s[a];if(typeof i=="string"&&i.trim())return gb(i,MC)}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 gb(n.map(([a,i])=>`${a}: ${String(i)}`).join(", "),MC)}r(hvt,"summarizeToolInput$2");function DD(e){const s=(e??"").trim();return ju(s)?"Unnamed tool":Mk(s)}r(DD,"toolDisplayName");function pvt(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(pvt,"thoughtDurationLabel");function fvt(e,s,n){const a=s.split(`
385
385
  `);if(!n||e.length===0){e.push(...a);return}e[e.length-1]=`${e[e.length-1]??""}${a[0]??""}`,e.push(...a.slice(1))}r(fvt,"appendThinkingText");var Oie=600,v_=8192;function GI(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)?e:{}}r(GI,"objectRecord");function rd(e){return typeof e=="string"&&e.trim().length>0?e.trim():void 0}r(rd,"stringValue");function xvt(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(xvt,"scalarValue");function gvt(e){return e.replace(/([a-z0-9])([A-Z])/g,"$1 $2").replaceAll("_"," ").replace(/\b\w/g,s=>s.toUpperCase())}r(gvt,"titleCaseKey$1");function bvt(e){const s=rd(e);if(!s)return null;try{const n=new URL(s);return n.protocol==="http:"||n.protocol==="https:"?s:null}catch{return null}}r(bvt,"safeHttpHref");var vvt={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 kAe(e){for(const s of["planId","executionId","researchId","delegationId","routeId","verificationId","compactionId","artifactId","reviewId","hookId","citationId","waitId","noticeId"]){const n=rd(e.payload[s]);if(n)return`${e.family}:${n}`}return`${e.family}:${e.eventType}:${e.ts}`}r(kAe,"providerActivityKey");function yvt(e,s,n){const a=[];for(const h of vvt[e.family]){const p=xvt(e.payload[h]);p&&(e.family==="tool_execution"&&h==="name"&&ju(p)||e.family==="tool_execution"&&h==="progress"&&!pq(p)||a.push({label:gvt(h),value:gb(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=GI(h);typeof p.name=="string"&&typeof p.value=="string"&&a.push({label:gb(p.name,160),value:gb(p.value,4e3),mono:!1})}const i=e.family==="plan"&&Array.isArray(e.payload.steps)?e.payload.steps.map(GI).slice(0,256).map((h,p)=>{const f=rd(h.status),x=f==="in_progress"||f==="completed"||f==="blocked"?f:"pending";return{id:rd(h.stepId)??`${s}:plan-step:${p}`,label:rd(h.body)??"Plan step",status:x}}):[],o=e.family==="research"&&Array.isArray(e.payload.sources)?e.payload.sources.map(GI).slice(0,64).flatMap(h=>{const p=bvt(h.url);return p?[{label:rd(h.title)??p,href:p,description:rd(h.snippet)}]:[]}):[],l=e.family==="delegation"&&Array.isArray(e.payload.children)?e.payload.children.map(GI).slice(0,64).map((h,p)=>({id:rd(h.childId)??`${s}:delegation:${p}`,title:rd(h.role)??"Subagent",status:rd(h.status)??"unknown",metadata:[rd(h.model),rd(h.activitySummary)].filter(Boolean).join(" · ")||void 0,summary:rd(h.summary)})):[],c=e.family==="tool_execution"?rd(e.payload.output):void 0,d=e.payload.outputTruncated===!0||!!(c&&c.length>v_),u=e.summary&&e.summary!==e.eventType?e.summary:rd(e.payload.explanation)??rd(e.payload.progress)??rd(e.payload.message)??rd(e.payload.summary);return{id:`${s}:provider:${kAe(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,v_):void 0,outputTruncated:d,transcriptIndex:n}}r(yvt,"providerActivityItem");function xu(e,s){return e.details.find(n=>n.label===s)?.value}r(xu,"providerItemDetail");function pq(e){return!!(e&&!ju(e)&&!/^tool(?:\s+|_)call\b/i.test(e))}r(pq,"meaningfulProviderToolSummary");function jvt(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=xu(s,"Name"),i=ju(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"&&!pq(l.value)&&n.has("Progress")||n.set(l.label,l);return{...s,id:e.id,summary:pq(s.summary)?s.summary:e.summary,details:[...n.values()]}}r(jvt,"mergeProviderActivityItem");function wvt(e){if(e==null)return;const s=(typeof e=="string"?e:String(e)).trim();if(s)return s.length>Oie?`${s.slice(0,Oie)}
@@ -703,7 +703,7 @@ Last resolved: user values resolve per member`;return(0,t.jsxs)("div",{role:"row
703
703
 
704
704
  Review the **original** file.`,markdown:!0,downloadUrl:"data:text/markdown,%23%20Project%20notes"}),(0,t.jsx)(IU,{title:"notes.txt",text:"Plain text stays literal: <example>",markdown:!1,downloadUrl:"data:text/plain,Plain%20text"})]})]}),(0,t.jsxs)(Sr,{title:"Connection recovery",children:[(0,t.jsx)(Xn,{title:"Waiting for server",children:(0,t.jsx)(TR,{temporary:!0,retrying:!1,onRetry:r(()=>{},"onRetry")})}),(0,t.jsx)(Xn,{title:"Checking connection",children:(0,t.jsx)(TR,{temporary:!0,retrying:!0,onRetry:r(()=>{},"onRetry")})}),(0,t.jsx)(Xn,{title:"Access check failed",children:(0,t.jsx)(TR,{temporary:!1,retrying:!1,onRetry:r(()=>{},"onRetry")})})]}),(0,t.jsxs)(Sr,{title:"Browser session footer",children:[(0,t.jsx)("p",{className:"text-sm text-muted-foreground",children:"Fit to pane follows the visible panel. Fixed viewport presets and session actions live in the footer menu. Costs stay in task reporting. The idle countdown appears only in the final five minutes. Full panel, activity, and settings states are in Storybook under Browser Use."}),["running","idle","closing-soon","closed"].map(O=>(0,t.jsx)(Xn,{title:O==="closing-soon"?"Closing soon":O,children:(0,t.jsx)(hLe,{browser:{id:"design-browser",sessionId:"design-session",issueId:"design-task",status:O==="closing-soon"?"idle":O,runStatus:"completed",progress:null,error:null,costCents:15,idleDeadline:new Date(O==="closing-soon"?282e3:6e5).toISOString(),expiresAt:null,createdAt:new Date(0).toISOString()},now:0,onControl:r(()=>{},"onControl"),onReconnect:r(()=>{},"onReconnect"),onResize:r(()=>{},"onResize")})},O))]}),(0,t.jsxs)(Sr,{title:"Browser activity in the task feed",children:[(0,t.jsx)("p",{className:"text-sm text-muted-foreground",children:"Each browser appears once at its opening time among the task messages. Its status updates in place; the action opens its side-panel tab."}),["starting","running","idle","closed","failed"].map(O=>(0,t.jsx)(Xn,{title:O,children:(0,t.jsx)(O3e,{browser:{id:`design-${O}`,sessionId:`design-${O}`,issueId:"design-task",status:O,runStatus:"completed",progress:null,error:null,costCents:0,idleDeadline:null,expiresAt:null,createdAt:new Date(0).toISOString()},onOpen:r(()=>{},"onOpen")})},O))]}),(0,t.jsxs)(Sr,{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)(bq,{id:"design-image",title:"Launch artwork",contentPath:"/announcement-preview.svg",contentType:"image/svg+xml",originalFilename:"launch.svg",detail:"Image"}),(0,t.jsx)(bq,{id:"design-video",title:"Video preview unavailable",contentPath:"",contentType:"video/mp4",originalFilename:"preview.mp4",detail:"Video"})]})]}),(0,t.jsx)(Sr,{title:"AI Connections",children:(0,t.jsx)(_fs,{})}),(0,t.jsxs)(Sr,{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)(Ck,{status:"needs_setup"}),(0,t.jsx)(Ck,{status:"pending_approval"}),(0,t.jsx)(Ck,{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(hxs,"DesignGuide");function pxs(){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)(w9e,{candidates:e,selected:s,excludedFolders:a,onChange:r((o,l)=>{n(o),i(l)},"onChange")})}r(pxs,"SkillSourceTreeShowcase");function fxs(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(fxs,"resolveWorktreeRunExecutionDisplayState");function xxs(e){const s=new Date(e);return Number.isNaN(s.getTime())?e:s.toLocaleString(void 0,{dateStyle:"medium",timeStyle:"short"})}r(xxs,"formatActivationTimestamp");function fDe(){return(0,t.jsxs)(it,{variant:"outline",className:"text-muted-foreground",children:[(0,t.jsx)(Ao,{"aria-hidden":"true"}),"Managed by Paperclip Cloud"]})}r(fDe,"ManagedByCloudBadge");function Xi({title:e,description:s,footnote:n,checked:a,onCheckedChange:i,disabled:o,settingKey:l,managed:c,ariaLabel:d}){const{hidden:u}=Au(),h=c?.managed===!0;return u.has(wbe(l))?null:(0,t.jsx)(nn,{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)(fDe,{}):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)(oi,{checked:a,onCheckedChange:r(p=>{h||i(p)},"onCheckedChange"),disabled:o||h,"aria-label":d})]})})}r(Xi,"ExperimentalToggleCard");function gxs(){const{setBreadcrumbs:e}=Wn(),s=kt(),{hidden:n}=Au(),[a,i]=(0,m.useState)(null);(0,m.useEffect)(()=>{e([{label:"Settings",href:"/company/settings"},{label:"Experimental"}])},[e]);const o=te({queryKey:M.instance.experimentalSettings,queryFn:r(()=>jr.getExperimental(),"queryFn")}),l=je({mutationFn:r(async V=>jr.updateExperimental(V),"mutationFn"),onMutate:r(async V=>{await s.cancelQueries({queryKey:M.instance.experimentalSettings});const X=s.getQueryData(M.instance.experimentalSettings);return X&&s.setQueryData(M.instance.experimentalSettings,{...X,...V}),{previousSettings:X}},"onMutate"),onSuccess:r(async V=>{i(null),s.setQueryData(M.instance.experimentalSettings,V),await Promise.all([s.invalidateQueries({queryKey:M.instance.experimentalSettings}),s.invalidateQueries({queryKey:M.adapters.all}),s.invalidateQueries({queryKey:["built-in-agents"]}),s.invalidateQueries({queryKey:M.health}),s.invalidateQueries({queryKey:["apps"]})])},"onSuccess"),onError:r((V,X,Y)=>{Y?.previousSettings&&s.setQueryData(M.instance.experimentalSettings,Y.previousSettings),i(V instanceof Error?V.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=Sft(),d=o.data?.managedKeys??{},u=o.data?.enableWorktreeRunExecution===!0,h=d.enableWorktreeRunExecution?.managed===!0,p=fxs(o.data,Cft()),f=o.data?.enableEnvironments===!0,x=o.data?.enableNativeRunner===!0,g=o.data?.enableChatConnectors===!0,v=o.data?.enableManagedSandboxOnly===!0,y=o.data?.enableIsolatedWorkspaces===!0,k=o.data?.enableIsolatedWorkspacesByDefault===!0,w=o.data?.enableStreamlinedUi!==!1;o.data?.enableConferenceRoomChat;const N=o.data?.enableClassicTaskInterface===!0,S=o.data?.enableIssuePlanDecompositions===!0,C=o.data?.enableExperimentalFileViewer===!0,_=o.data?.enableExternalObjects===!0,R=o.data?.enableBuiltInAgents===!0,I=o.data?.enableBetaSkills===!0,T=o.data?.enableSummaries===!0,E=o.data?.enableStatusCards===!0,L=d.enableSummaries?.managed===!0,O=d.enableStatusCards?.managed===!0,P=L&&!T,Q=O&&E,D=o.data?.enableDecisions===!0,F=o.data?.enableGoalsSidebarLink===!0,z=o.data?.enableCases===!0,K=o.data?.enableServerInfoDebugView===!0,U=o.data?.enablePaperclipDeveloperMode===!0,q=o.data?.enableSimplifiedEnglishInteractions===!0,G=o.data?.enableFirstTaskPlanProposal===!0,se=o.data?.enableSmokeLab===!0,Z=o.data?.autoRestartDevServerWhenIdle===!0,ie=r(V=>!n.has(wbe(V)),"isVisible"),J=c&&ie("enableWorktreeRunExecution"),re=J||["autoRestartDevServerWhenIdle","enableManagedSandboxOnly","enablePaperclipDeveloperMode","enableServerInfoDebugView","enableSmokeLab","enableIssuePlanDecompositions"].some(ie),oe=ie("enableClassicTaskInterface")||ie("enableGoalsSidebarLink");return(0,t.jsxs)("div",{className:"max-w-6xl space-y-6",children:[(0,t.jsxs)("div",{className:"space-y-2",children:[(0,t.jsxs)("div",{className:"flex items-center gap-2",children:[(0,t.jsx)(Jm,{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)(Xi,{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(V=>l.mutate({enableAgentChat:V}),"onCheckedChange"),disabled:l.isPending,settingKey:"enableAgentChat",managed:d.enableAgentChat,ariaLabel:"Toggle agent chat experimental setting"}),(0,t.jsx)(Xi,{title:"Assistant connections (MCP)",description:"Connect Codex, Claude, and other assistants to your Paperclip organization. People sign in, select an organization once, and approve access to review work, delegate tasks, and add feedback.",footnote:(0,t.jsxs)(t.Fragment,{children:["Requires an authenticated instance with a configured public URL. Takes effect immediately. Turning this off blocks assistant calls and event delivery; work already delegated continues.",o.data?.enablePublicMcp&&(0,t.jsxs)(t.Fragment,{children:[" ",(0,t.jsx)(Ke,{className:"underline",to:"/apps/assistant-connection",children:"Set up an assistant connection"})]})]}),checked:o.data?.enablePublicMcp===!0,onCheckedChange:r(V=>l.mutate({enablePublicMcp:V}),"onCheckedChange"),disabled:l.isPending,settingKey:"enablePublicMcp",managed:d.enablePublicMcp,ariaLabel:"Toggle assistant connections experimental setting"}),(0,t.jsx)(Xi,{title:"Beta skills",description:"Allow agents to pin beta releases of the Paperclip core skill. Disabling this returns every agent to the default live skill without removing saved pins.",checked:I,onCheckedChange:r(V=>l.mutate({enableBetaSkills:V}),"onCheckedChange"),disabled:l.isPending,settingKey:"enableBetaSkills",managed:d.enableBetaSkills,ariaLabel:"Toggle beta skills experimental setting"}),(0,t.jsx)(Xi,{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(V=>l.mutate({enableBuiltInAgents:V}),"onCheckedChange"),disabled:l.isPending,settingKey:"enableBuiltInAgents",managed:d.enableBuiltInAgents,ariaLabel:"Toggle built-in agents experimental setting"}),(0,t.jsx)(Xi,{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:z,onCheckedChange:r(V=>l.mutate({enableCases:V}),"onCheckedChange"),disabled:l.isPending,settingKey:"enableCases",managed:d.enableCases,ariaLabel:"Toggle cases experimental setting"}),(0,t.jsx)(Xi,{title:"Chat connectors",description:"Connect agents to Slack, Discord, Microsoft Teams, and Telegram conversations.",footnote:"Turning this off hides experimental chat setup and connected-task controls. Existing chat connections keep running. AgentMail, GitHub review bots, and tool connectors are controlled separately.",checked:g,onCheckedChange:r(V=>l.mutate({enableChatConnectors:V}),"onCheckedChange"),disabled:l.isPending,settingKey:"enableChatConnectors",managed:d.enableChatConnectors,ariaLabel:"Toggle chat connectors experimental setting"}),(0,t.jsx)(Xi,{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(V=>l.mutate({enableCombinedInboxTasks:V}),"onCheckedChange"),disabled:l.isPending,settingKey:"enableCombinedInboxTasks",managed:d.enableCombinedInboxTasks,ariaLabel:"Toggle combined inbox and task list experimental setting"}),null,(0,t.jsx)(Xi,{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:D,onCheckedChange:r(V=>l.mutate({enableDecisions:V}),"onCheckedChange"),disabled:l.isPending,settingKey:"enableDecisions",managed:d.enableDecisions,ariaLabel:"Toggle decisions experimental setting"}),(0,t.jsx)(Xi,{title:"Enable Environments",description:"Show environment management in company settings and allow project and agent environment assignment controls.",checked:f,onCheckedChange:r(V=>l.mutate({enableEnvironments:V}),"onCheckedChange"),disabled:l.isPending,settingKey:"enableEnvironments",managed:d.enableEnvironments,ariaLabel:"Toggle environments experimental setting"}),(0,t.jsx)(Xi,{title:"Enable External Objects",description:"Detect external URLs in issues and show resolved status for pull requests, tickets, and other referenced work objects.",checked:_,onCheckedChange:r(V=>l.mutate({enableExternalObjects:V}),"onCheckedChange"),disabled:l.isPending,settingKey:"enableExternalObjects",managed:d.enableExternalObjects,ariaLabel:"Toggle external objects experimental setting"}),(0,t.jsx)(Xi,{title:"Enable Isolated Workspaces",description:"Show execution workspace controls in project configuration and allow isolated workspace behavior for new and existing task runs.",checked:y,onCheckedChange:r(V=>l.mutate({enableIsolatedWorkspaces:V}),"onCheckedChange"),disabled:l.isPending,settingKey:"enableIsolatedWorkspaces",managed:d.enableIsolatedWorkspaces,ariaLabel:"Toggle isolated workspaces experimental setting"}),(0,t.jsx)(Xi,{title:"Experimental fast responses",description:"Show Connections in company settings and allow short acknowledgements while agents begin work.",checked:o.data?.enableFastResponses??!1,onCheckedChange:r(V=>l.mutate({enableFastResponses:V}),"onCheckedChange"),disabled:l.isPending,settingKey:"enableFastResponses",managed:d.enableFastResponses,ariaLabel:"Toggle fast responses experimental setting"}),(0,t.jsx)(Xi,{title:"Experimental File Viewer",description:"Show task detail controls for browsing and previewing workspace files relative to a task.",checked:C,onCheckedChange:r(V=>l.mutate({enableExperimentalFileViewer:V}),"onCheckedChange"),disabled:l.isPending,settingKey:"enableExperimentalFileViewer",managed:d.enableExperimentalFileViewer,ariaLabel:"Toggle experimental file viewer setting"}),(0,t.jsx)(Xi,{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:G,onCheckedChange:r(V=>l.mutate({enableFirstTaskPlanProposal:V}),"onCheckedChange"),disabled:l.isPending,settingKey:"enableFirstTaskPlanProposal",managed:d.enableFirstTaskPlanProposal,ariaLabel:"Toggle first task plan proposal experimental setting"}),(0,t.jsx)(Xi,{title:"GitHub review bots",description:"Connect agents to GitHub with their own App identity to review pull requests and respond to issues.",footnote:"Independent of Chat connectors. Turning this off hides setup and management; existing bots keep running. GitHub tool connections stay available.",checked:o.data?.enableGitHubReviewBots===!0,onCheckedChange:r(V=>l.mutate({enableGitHubReviewBots:V}),"onCheckedChange"),disabled:l.isPending,settingKey:"enableGitHubReviewBots",managed:d.enableGitHubReviewBots,ariaLabel:"Toggle GitHub review bots experimental setting"}),(0,t.jsx)(Xi,{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(V=>l.mutate({enableMemoryConnectors:V}),"onCheckedChange"),disabled:l.isPending,settingKey:"enableMemoryConnectors",managed:d.enableMemoryConnectors,ariaLabel:"Toggle memory connectors experimental setting"}),(0,t.jsx)(Xi,{title:"OpenAI Dot",description:"Add OpenAI Dot as a standalone agent choice. Pair your Dot and verify event delivery before assigning work.",footnote:"Requires Assistant connections (MCP) and an authenticated instance with a public HTTPS URL. Turning this off blocks Dot calls and new work; saved connections are kept.",checked:o.data?.enableOpenAiDot===!0,onCheckedChange:r(V=>l.mutate({enableOpenAiDot:V}),"onCheckedChange"),disabled:l.isPending,settingKey:"enableOpenAiDot",managed:d.enableOpenAiDot,ariaLabel:"Toggle OpenAI Dot experimental setting"}),(0,t.jsx)(Xi,{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(V=>l.mutate({enableNativeRunner:V}),"onCheckedChange"),disabled:l.isPending,settingKey:"enableNativeRunner",managed:d.enableNativeRunner,ariaLabel:"Toggle Paperclip Runner experimental setting"}),(0,t.jsx)(Xi,{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(V=>l.mutate({enablePixelsOffice:V}),"onCheckedChange"),disabled:l.isPending,settingKey:"enablePixelsOffice",managed:d.enablePixelsOffice,ariaLabel:"Toggle Pixels Office experimental setting"}),(0,t.jsx)(Xi,{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:q,onCheckedChange:r(V=>l.mutate({enableSimplifiedEnglishInteractions:V}),"onCheckedChange"),disabled:l.isPending,settingKey:"enableSimplifiedEnglishInteractions",managed:d.enableSimplifiedEnglishInteractions,ariaLabel:"Toggle simplified english interactions experimental setting"}),(0,t.jsx)(Xi,{title:"Status Cards",description:"Enable the experimental shared status-card board and its gated API. Existing card data is kept when this is disabled.",footnote:"Enabling Status Cards also enables Summaries.",checked:E,onCheckedChange:r(V=>l.mutate(V?{enableSummaries:!0,enableStatusCards:!0}:{enableStatusCards:!1}),"onCheckedChange"),disabled:l.isPending||P,settingKey:"enableStatusCards",managed:d.enableStatusCards,ariaLabel:"Toggle status cards experimental setting"}),(0,t.jsx)(Xi,{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(V=>l.mutate({enableStreamlinedUi:V}),"onCheckedChange"),disabled:l.isPending,settingKey:"enableStreamlinedUi",managed:d.enableStreamlinedUi,ariaLabel:"Toggle Streamlined UI experimental setting"}),(0,t.jsx)(Xi,{title:"Summaries",description:"Show Summarizer-generated status slots on project and workspace pages, with on-demand refresh and revision history. Existing summary data is kept when this is disabled.",footnote:"Status Cards requires Summaries. Disabling Summaries also disables Status Cards.",checked:T,onCheckedChange:r(V=>l.mutate(V||!E?{enableSummaries:V}:{enableSummaries:!1,enableStatusCards:!1}),"onCheckedChange"),disabled:l.isPending||Q,settingKey:"enableSummaries",managed:d.enableSummaries,ariaLabel:"Toggle summaries experimental setting"}),y&&(0,t.jsx)(Xi,{title:"Use Isolated Workspaces By Default",description:"Treat a project that has no execution workspace policy of its own as if it selected isolated workspaces, so its tasks get a per-task worktree instead of sharing the project checkout. A project that carries its own policy keeps it.",checked:k,onCheckedChange:r(V=>l.mutate({enableIsolatedWorkspacesByDefault:V}),"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)(Xi,{title:"Auto-Restart Dev Server When Idle",description:"In `pnpm dev:once`, wait for all queued and running local agent runs to finish, then restart the server automatically when backend changes or migrations make the current boot stale.",checked:Z,onCheckedChange:r(V=>l.mutate({autoRestartDevServerWhenIdle:V}),"onCheckedChange"),disabled:l.isPending,settingKey:"autoRestartDevServerWhenIdle",managed:d.autoRestartDevServerWhenIdle,ariaLabel:"Toggle guarded dev-server auto-restart"}),(0,t.jsx)(Xi,{title:"Managed Environment Only",description:"Hide the local environment and run all agents in the platform-managed environment.",checked:v,onCheckedChange:r(V=>l.mutate({enableManagedSandboxOnly:V}),"onCheckedChange"),disabled:l.isPending,settingKey:"enableManagedSandboxOnly",managed:d.enableManagedSandboxOnly,ariaLabel:"Toggle managed environment only experimental setting"}),(0,t.jsx)(Xi,{title:"Paperclip Developer Mode",description:"Show internal Paperclip maintainer tools and observability links, including Honeycomb trace queries on run pages.",checked:U,onCheckedChange:r(V=>l.mutate({enablePaperclipDeveloperMode:V}),"onCheckedChange"),disabled:l.isPending,settingKey:"enablePaperclipDeveloperMode",managed:d.enablePaperclipDeveloperMode,ariaLabel:"Toggle Paperclip developer mode experimental setting"}),J?(0,t.jsx)(nn,{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)(fDe,{}):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)(oi,{checked:u,onCheckedChange:r(V=>{h||l.mutate({enableWorktreeRunExecution:V})},"onCheckedChange"),disabled:l.isPending||h,"aria-label":"Toggle worktree run execution setting"})]}),p.kind==="armed"?(0,t.jsxs)("div",{className:"flex items-center gap-2 rounded-md border border-emerald-500/30 bg-emerald-500/5 px-3 py-2 text-sm text-foreground",children:[(0,t.jsx)(ho,{className:"h-4 w-4 shrink-0 text-emerald-600"}),(0,t.jsxs)("span",{children:["Running tasks created after"," ",(0,t.jsx)("span",{className:"font-medium",children:xxs(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)(Xi,{title:"Server Info Debug View",description:'Show a "Server" section in the account drawer with the current server restart time and running commit.',checked:K,onCheckedChange:r(V=>l.mutate({enableServerInfoDebugView:V}),"onCheckedChange"),disabled:l.isPending,settingKey:"enableServerInfoDebugView",managed:d.enableServerInfoDebugView,ariaLabel:"Toggle server info debug view experimental setting"}),(0,t.jsx)(Xi,{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(V=>l.mutate({enableSmokeLab:V}),"onCheckedChange"),disabled:l.isPending,settingKey:"enableSmokeLab",managed:d.enableSmokeLab,ariaLabel:"Toggle smoke lab experimental setting"}),(0,t.jsx)(Xi,{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(V=>l.mutate({enableIssuePlanDecompositions:V}),"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)(Xi,{title:"Classic Task Interface",description:"Restores the previous task detail page: the page-level header with inline description editing, the plain comment thread, and the fixed Properties sidebar. Chat-only features — streaming activity folding, inline plan and question cards, the three-mode composer — are unavailable in the classic view.",footnote:"Switching takes effect immediately. No task data is affected.",checked:N,onCheckedChange:r(V=>l.mutate({enableClassicTaskInterface:V}),"onCheckedChange"),disabled:l.isPending,settingKey:"enableClassicTaskInterface",managed:d.enableClassicTaskInterface,ariaLabel:"Toggle classic task interface experimental setting"}),(0,t.jsx)(Xi,{title:"Goals Sidebar Link",description:"Restore the Goals item in the main sidebar while the goals surface is being evaluated.",checked:F,onCheckedChange:r(V=>l.mutate({enableGoalsSidebarLink:V}),"onCheckedChange"),disabled:l.isPending,settingKey:"enableGoalsSidebarLink",managed:d.enableGoalsSidebarLink,ariaLabel:"Toggle goals sidebar link experimental setting"})]}):null]})}r(gxs,"InstanceExperimentalSettings");function bxs(){const{userId:e,settled:s}=Af(),{setBreadcrumbs:n}=Wn(),{pushToast:a}=Ii(),i=kt(),[o,l]=(0,m.useState)(""),[c,d]=(0,m.useState)(null),[u,h]=(0,m.useState)(new Set);(0,m.useEffect)(()=>{n([{label:"Settings",href:"/company/settings"},{label:"Instance settings",href:"/company/settings/instance/general"},{label:"Access"}])},[n]);const p=te({queryKey:M.access.adminUsers(o),queryFn:r(()=>ir.searchAdminUsers(o),"queryFn")}),f=te({...YOe(e),enabled:s&&p.isSuccess}),x=f.data??[],g=(0,m.useMemo)(()=>p.data?.find(w=>w.id===c)??null,[c,p.data]),v=te({queryKey:M.access.userCompanyAccess(c??""),queryFn:r(()=>ir.getUserCompanyAccess(c),"queryFn"),enabled:!!c});(0,m.useEffect)(()=>{!c&&p.data?.[0]&&d(p.data[0].id)},[c,p.data]),(0,m.useEffect)(()=>{v.data&&h(new Set(v.data.companyAccess.filter(w=>w.status==="active").map(w=>w.companyId)))},[v.data]);const y=je({mutationFn:r(()=>ir.setUserCompanyAccess(c,[...u]),"mutationFn"),onSuccess:r(async()=>{await i.invalidateQueries({queryKey:M.access.userCompanyAccess(c)}),await i.invalidateQueries({queryKey:M.access.adminUsers(o)}),await i.invalidateQueries({queryKey:M.companies.all}),a({title:"Organization access updated",tone:"success"})},"onSuccess")}),k=je({mutationFn:r(async w=>{if(!c)throw new Error("No user selected");return w?ir.promoteInstanceAdmin(c):ir.demoteInstanceAdmin(c)},"mutationFn"),onSuccess:r(async()=>{await i.invalidateQueries({queryKey:M.access.adminUsers(o)}),c&&await i.invalidateQueries({queryKey:M.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 sn&&p.error.status===403?"Instance admin access is required to manage users.":p.error instanceof Error?p.error.message:"Failed to load users.";return(0,t.jsx)("div",{className:"text-sm text-destructive",children:w})}return f.error?(0,t.jsxs)("div",{className:"space-y-3",children:[(0,t.jsx)("p",{className:"text-sm text-destructive",children:"Failed to load organizations. Try again before changing access."}),(0,t.jsx)($,{onClick:r(()=>{f.refetch()},"onClick"),children:"Try again"})]}):(0,t.jsxs)("div",{className:"max-w-6xl space-y-6",children:[(0,t.jsxs)("div",{className:"space-y-3",children:[(0,t.jsxs)("div",{className:"flex items-center gap-2",children:[(0,t.jsx)(v3,{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)(nn,{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)(qi,{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)(nn,{className:"block space-y-4 p-5",children:c?v.isLoading?(0,t.jsx)("div",{className:"text-sm text-muted-foreground",children:"Loading user access…"}):v.error?(0,t.jsx)("div",{className:"text-sm text-destructive",children:v.error instanceof Error?v.error.message:"Failed to load user access."}):(0,t.jsxs)(t.Fragment,{children:[(0,t.jsxs)("div",{className:"flex flex-wrap items-start justify-between gap-4",children:[(0,t.jsxs)("div",{children:[(0,t.jsx)("div",{className:"text-lg font-semibold",children:g?.name||g?.email||c}),(0,t.jsx)("div",{className:"text-sm text-muted-foreground",children:g?.email||c})]}),(0,t.jsx)($,{variant:g?.isInstanceAdmin?"outline":"default",onClick:r(()=>k.mutate(!(g?.isInstanceAdmin??!1)),"onClick"),disabled:k.isPending,children:g?.isInstanceAdmin?"Remove instance admin":"Promote to instance admin"})]}),(0,t.jsxs)("div",{className:"space-y-3",children:[(0,t.jsxs)("div",{children:[(0,t.jsx)("h2",{className:"text-sm font-semibold",children:"Organization access"}),(0,t.jsx)("p",{className:"text-sm text-muted-foreground",children:"Toggle organization membership for this user. New access defaults to an active operator membership."})]}),(0,t.jsx)("div",{className:"grid gap-3 md:grid-cols-2",children:x.map(w=>(0,t.jsxs)("label",{className:"flex items-start gap-3 rounded-lg border border-border px-3 py-3",children:[(0,t.jsx)(ri,{checked:u.has(w.id),onCheckedChange:r(N=>{h(S=>{const C=new Set(S);return N?C.add(w.id):C.delete(w.id),C})},"onCheckedChange")}),(0,t.jsxs)("span",{className:"space-y-1",children:[(0,t.jsx)("span",{className:"block text-sm font-medium",children:w.name}),(0,t.jsx)("span",{className:"block text-xs text-muted-foreground",children:w.issuePrefix})]})]},w.id))}),(0,t.jsx)("div",{className:"flex justify-end",children:(0,t.jsx)($,{onClick:r(()=>y.mutate(),"onClick"),disabled:y.isPending,children:y.isPending?"Saving…":"Save organization access"})})]}),(0,t.jsxs)("div",{className:"space-y-2",children:[(0,t.jsx)("h2",{className:"text-sm font-semibold",children:"Current memberships"}),(0,t.jsx)("div",{className:"space-y-2",children:(v.data?.companyAccess??[]).map(w=>(0,t.jsxs)("div",{className:"flex items-center justify-between rounded-lg border border-border px-3 py-2 text-sm",children:[(0,t.jsxs)("div",{children:[(0,t.jsx)("div",{className:"font-medium",children:w.companyName||w.companyId}),(0,t.jsxs)("div",{className:"text-muted-foreground",children:[w.membershipRole||"unset"," • ",w.status]})]}),(0,t.jsx)("div",{className:"text-xs text-muted-foreground",children:new Date(w.updatedAt).toLocaleDateString()})]},w.id))})]})]}):(0,t.jsx)("div",{className:"text-sm text-muted-foreground",children:"Select a user to inspect instance access."})})]})]})}r(bxs,"InstanceAccess");var Cge={getMine:r(e=>we.get(`/companies/${e}/users/me/inbox-agent-policy`),"getMine"),updateMine:r((e,s)=>we.put(`/companies/${e}/users/me/inbox-agent-policy`,s),"updateMine")},vxs=[{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 UT(e,s){return`${e}:${[...s].sort().join(",")}`}r(UT,"policyKey");function yxs({companyId:e}){const s=kt(),[n,a]=(0,m.useState)(null),i=(0,m.useRef)(null),o=te({queryKey:e?M.inboxAgentPolicy.mine(e):["inbox-agent-policy","none"],queryFn:r(()=>Cge.getMine(e),"queryFn"),enabled:!!e}),l=o.data,c=te({queryKey:e?M.agents.list(e):["agents","none"],queryFn:r(()=>_t.list(e),"queryFn"),enabled:!!e}),d=(0,m.useMemo)(()=>(c.data??[]).filter(gf),[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=UT(l.mode,l.allowedAgentIds);a(g=>g===null||UT(g.mode,g.allowedAgentIds)===i.current?{mode:l.mode,allowedAgentIds:l.allowedAgentIds}:g),i.current=x},[l]);const p=je({mutationFn:r(x=>Cge.updateMine(e,{mode:x.mode,allowedAgentIds:x.mode==="allowlist"?x.allowedAgentIds:[]}),"mutationFn"),onSuccess:r(x=>{s.setQueryData(M.inboxAgentPolicy.mine(e),x)},"onSuccess")}),f=!!(n&&l&&UT(n.mode,n.allowedAgentIds)!==UT(l.mode,l.allowedAgentIds));return o.error?(0,t.jsx)("div",{className:"text-sm text-destructive",children:o.error instanceof Error?o.error.message:"Failed to load inbox agent policy."}):o.isLoading||!n?(0,t.jsx)("div",{className:"text-sm text-muted-foreground",children:"Loading inbox agent policy…"}):(0,t.jsxs)("section",{className:"space-y-4","aria-label":"Let agents tidy my inbox",children:[(0,t.jsxs)("div",{className:"space-y-1",children:[(0,t.jsxs)("div",{className:"flex items-center gap-2",children:[(0,t.jsx)(Od,{className:"h-5 w-5 text-muted-foreground"}),(0,t.jsx)("h2",{className:"text-base font-semibold",children:"Let agents tidy my inbox"})]}),(0,t.jsx)("p",{className:"max-w-2xl text-sm text-muted-foreground",children:"Choose whether the agents you manage may archive tasks out of your inbox on your behalf. You can undo any archive, and every agent archive is attributed in the task's properties."})]}),(0,t.jsx)(em,{ariaLabel:"Inbox agent archiving policy",value:n.mode,onValueChange:r(x=>a(g=>g&&{...g,mode:x}),"onValueChange"),options:vxs,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)(Jj,{agents:u,selectedAgentIds:h,onChange:r(x=>a(g=>g&&{...g,allowedAgentIds:[...x]}),"onChange"),triggerLabel:h.size===0?"Select agents":`${h.size} ${h.size===1?"agent":"agents"} selected`,triggerFullWidth:!1,showSelectionPreview:!1,emptyMessage:"You don’t manage any agents yet."})]}):null,p.error?(0,t.jsx)("div",{className:"max-w-2xl rounded-md border border-destructive/40 bg-destructive/5 px-3 py-2 text-sm text-destructive",children:p.error instanceof Error?p.error.message:"Failed to save inbox agent policy."}):null,(0,t.jsxs)("div",{className:"flex max-w-2xl items-center justify-end gap-3",children:[p.isSuccess&&!f?(0,t.jsx)("span",{className:"text-xs text-muted-foreground",role:"status",children:"Saved"}):null,(0,t.jsxs)($,{type:"button",disabled:!f||p.isPending,onClick:r(()=>n&&p.mutate(n),"onClick"),children:[p.isPending?(0,t.jsx)(st,{className:"size-4 animate-spin"}):(0,t.jsx)(af,{className:"size-4"}),p.isPending?"Saving…":"Save"]})]})]})}r(yxs,"InboxAgentPolicyControl");var jxs={granted:"Allowed",denied:"Blocked in browser settings",default:"Not requested yet",unsupported:"Not supported in this browser"},_ge={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 wxs(){const[e,s]=(0,m.useState)({});return(0,m.useEffect)(()=>{let n=!1;const a=r(()=>{Promise.all(p3.map(async o=>[o,(await E5e(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=T5e(a);return()=>{n=!0,i()}},[]),e}r(wxs,"useCustomSoundNames");function kxs({kind:e,customName:s,disabled:n,onError:a}){const i=U5e(),o=i.kinds[e],l=(0,m.useId)(),[c,d]=(0,m.useState)(!1),u=N0t[e];async function h(x){const g=A5e(x);if(!g.ok){a(`${u}: ${g.error}`);return}d(!0);try{await j0t(e,x),qI(e,{soundId:Oae}),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 w0t(e),ig().kinds[e].soundId==="custom"&&qI(e,{soundId:PE[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)(oi,{checked:o.enabled,onCheckedChange:r(x=>qI(e,{enabled:x}),"onCheckedChange"),disabled:n,"aria-label":`${u} notifications`}),(0,t.jsx)("div",{className:"min-w-0 flex-1 truncate text-sm font-medium",title:u,children:u})]}),(0,t.jsxs)("div",{className:"flex min-w-0 flex-wrap items-center gap-2 sm:flex-1 sm:flex-nowrap",children:[(0,t.jsxs)(Ca,{value:o.soundId,onValueChange:r(x=>qI(e,{soundId:x}),"onValueChange"),disabled:f,children:[(0,t.jsx)(Na,{className:"min-w-0 flex-1 sm:w-(--sz-170px) sm:flex-none","aria-label":`${u} sound`,children:(0,t.jsx)(Sa,{})}),(0,t.jsxs)(_a,{children:[L5e.map(x=>(0,t.jsx)(un,{value:x.id,children:x.label},x.id)),s?(0,t.jsxs)(un,{value:Oae,children:["Custom: ",s]}):null,(0,t.jsx)(un,{value:k0t,children:"No sound"})]})]}),(0,t.jsx)($,{type:"button",variant:"outline",size:"icon-sm","aria-label":`Preview ${u} sound`,disabled:f||o.soundId==="none",onClick:r(()=>{O5e(e,o.soundId,i.volume)},"onClick"),children:(0,t.jsx)(ho,{})}),(0,t.jsx)("input",{id:l,type:"file",accept:"audio/*",className:"sr-only",disabled:f||c,onChange:r(x=>{const g=x.target.files?.[0];x.target.value="",g&&h(g)},"onChange")}),(0,t.jsxs)($,{type:"button",variant:"outline",size:"sm",disabled:f||c,onClick:r(()=>document.getElementById(l)?.click(),"onClick"),children:[c?(0,t.jsx)(st,{className:"animate-spin"}):(0,t.jsx)(Gb,{}),s?"Replace":"Custom"]}),s?(0,t.jsx)($,{type:"button",variant:"ghost",size:"icon-sm","aria-label":`Remove custom ${u} sound`,disabled:c,onClick:r(()=>{p()},"onClick"),children:(0,t.jsx)(ha,{})}):null]})]})}r(kxs,"KindRow");function Nxs({userId:e}){const s=U5e(),n=P0t(),a=wxs(),[i,o]=(0,m.useState)(()=>g_()),[l,c]=(0,m.useState)(null),[d,u]=(0,m.useState)(null),[h,p]=(0,m.useState)(!1),f=S5e(),x=n.status==="active",g=(0,m.useCallback)(()=>{e&&eq(ig(),e)},[e]);async function v(){const S=await c0t();return o(S),S==="granted"&&g(),S}r(v,"askPermission");async function y(S){wR(C=>({...C,enabled:S})),S&&g_()==="default"&&await v()}r(y,"setEnabled");async function k(S){wR(C=>({...C,pushEnabled:S})),S&&g_()==="default"&&await v()}r(k,"setPushEnabled");async function w(){p(!0),c(null),u(null);try{const S=await $E.sendWebPushTest();c(S.sent>0?`Test sent to ${S.sent} device${S.sent===1?"":"s"}.`:"No device has push turned on for your account yet.")}catch(S){u(S instanceof Error?S.message:"Could not send the test notification.")}finally{p(!1)}}r(w,"sendTest");const N=!s.enabled;return(0,t.jsxs)("section",{className:"space-y-4","aria-label":"Notifications",children:[(0,t.jsxs)("div",{className:"space-y-1",children:[(0,t.jsxs)("div",{className:"flex items-center gap-2",children:[(0,t.jsx)(UKe,{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)(oi,{checked:s.enabled,onCheckedChange:r(S=>{y(S)},"onCheckedChange"),"aria-label":"Notifications on this device"})]}),(0,t.jsxs)("div",{className:"flex items-center justify-between gap-4",children:[(0,t.jsxs)("div",{className:"min-w-0",children:[(0,t.jsx)("div",{className:"text-sm font-medium",children:"Browser permission"}),(0,t.jsx)("div",{className:"text-xs text-muted-foreground",children:jxs[i]})]}),i==="default"?(0,t.jsx)($,{type:"button",variant:"outline",size:"sm",className:"shrink-0",onClick:r(()=>{v()},"onClick"),children:"Allow notifications"}):null]}),(0,t.jsxs)("div",{className:"flex items-center justify-between gap-4",children:[(0,t.jsxs)("div",{className:"min-w-0",children:[(0,t.jsx)("div",{className:"text-sm font-medium",children:"Push when Paperclip is closed"}),(0,t.jsxs)("div",{className:"text-xs text-muted-foreground",children:[f?_ge[n.status]:_ge.unsupported,n.error?`: ${n.error}`:""]})]}),(0,t.jsx)(oi,{checked:s.pushEnabled,onCheckedChange:r(S=>{k(S)},"onCheckedChange"),disabled:N||!f,"aria-label":"Push when Paperclip is closed"})]}),s.enabled&&!x?(0,t.jsx)("p",{className:"rounded-md bg-muted px-3 py-2 text-xs text-muted-foreground",children:"Push is off on this device, so background alerts only work while a Paperclip tab is visible."}):null,d0t()?(0,t.jsx)("p",{className:"rounded-md bg-muted px-3 py-2 text-xs text-muted-foreground",children:"On iPhone and iPad, push notifications need Paperclip added to the Home Screen (Share, then Add to Home Screen) and opened from there."}):null,(0,t.jsxs)("div",{className:"flex items-center gap-4",children:[(0,t.jsx)("label",{htmlFor:"notification-volume",className:"text-sm font-medium",children:"Volume"}),(0,t.jsx)("input",{id:"notification-volume",type:"range",min:0,max:100,step:5,value:Math.round(s.volume*100),disabled:N,onChange:r(S=>wR(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:p3.map(S=>(0,t.jsx)(kxs,{kind:S,customName:a[S],disabled:N,onError:u},S))}),(0,t.jsx)("p",{className:"text-xs text-muted-foreground",children:"Custom sounds must be audio files of 512 KB or less. They play only while Paperclip is open; push notifications use your system sound."}),(0,t.jsxs)("div",{className:"flex flex-wrap items-center gap-3",children:[(0,t.jsxs)($,{type:"button",variant:"secondary",onClick:r(()=>{w()},"onClick"),disabled:h||N,children:[h?(0,t.jsx)(st,{className:"animate-spin"}):(0,t.jsx)(O3,{}),"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(Nxs,"NotificationSettingsSection");function Sxs(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(Sxs,"deriveInitials");function Cxs(){const{setBreadcrumbs:e}=Wn(),{selectedCompanyId:s,selectedCompany:n}=ps(),a=kt(),i=(0,m.useId)(),o=(0,m.useRef)(null),[l,c]=(0,m.useState)(""),[d,u]=(0,m.useState)(""),[h,p]=(0,m.useState)(null),f=te({queryKey:M.auth.session,queryFn:r(()=>Ma.getSession(),"queryFn"),retry:!1});(0,m.useEffect)(()=>{e([{label:"Settings",href:"/company/settings"},{label:"Profile"}])},[e]),(0,m.useEffect)(()=>{const I=f.data;I&&(c(I.user.name??""),u(I.user.image??""))},[f.data]);function x(I){a.setQueryData(M.auth.session,T=>T&&{...T,user:{...T.user,...I}})}r(x,"syncSessionProfile");async function g(I){const T=await Ma.updateProfile(I);return x(T),T}r(g,"persistProfile");function v(){return l.trim()||f.data?.user.name||"Board"}r(v,"resolveProfileName");const y=je({mutationFn:r(I=>g(I),"mutationFn"),onSuccess:r(I=>{p(null),c(I.name??""),u(I.image??"")},"onSuccess"),onError:r(I=>{p(I instanceof Error?I.message:"Failed to update profile.")},"onError")}),k=je({mutationFn:r(async I=>{if(!s)throw new Error("Select an organization before uploading a profile avatar.");const T=await fv.uploadImage(s,I,`profiles/${f.data?.user.id??"board-user"}`);return g({name:v(),image:T.contentPath})},"mutationFn"),onSuccess:r(I=>{p(null),c(I.name??""),u(I.image??"")},"onSuccess"),onError:r(I=>{p(I instanceof Error?I.message:"Failed to upload avatar.")},"onError")}),w=je({mutationFn:r(()=>g({name:v(),image:null}),"mutationFn"),onSuccess:r(I=>{p(null),c(I.name??""),u(I.image??"")},"onSuccess"),onError:r(I=>{p(I instanceof Error?I.message:"Failed to remove avatar.")},"onError")});if(f.isLoading)return(0,t.jsx)("div",{className:"text-sm text-muted-foreground",children:"Loading profile..."});if(f.error||!f.data)return(0,t.jsx)("div",{className:"text-sm text-destructive",children:f.error instanceof Error?f.error.message:"Failed to load profile."});const N=l.trim()||f.data.user.name||"Board",S=d.trim()||null,C=Sxs(N),_=y.isPending||k.isPending||w.isPending,R=n?`Stored in Paperclip file storage for ${n.name}.`:"Select an organization to upload an avatar into Paperclip storage.";return(0,t.jsxs)("div",{className:"max-w-6xl space-y-6",children:[(0,t.jsxs)("div",{className:"space-y-2",children:[(0,t.jsxs)("div",{className:"flex items-center gap-2",children:[(0,t.jsx)(K8,{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)(nn,{className:"block relative overflow-hidden rounded-(--rad-28) border-border/70",children:[(0,t.jsx)("div",{className:"absolute inset-x-0 top-0 h-32 bg-(image:--gradient-extract-26)"}),(0,t.jsx)("div",{className:"absolute inset-0 bg-(image:--gradient-extract-7)"}),(0,t.jsx)("div",{className:"relative p-6 pt-10",children:(0,t.jsxs)("div",{className:"flex flex-wrap items-end gap-5 rounded-(--rad-24) border border-border/70 bg-background/92 p-5 shadow-(--shadow-extract-18) backdrop-blur-sm",children:[(0,t.jsxs)("div",{className:"space-y-3",children:[(0,t.jsxs)("label",{htmlFor:i,className:"group relative block cursor-pointer rounded-full focus-within:outline-none focus-within:ring-2 focus-within:ring-ring focus-within:ring-offset-2 focus-within:ring-offset-background",children:[(0,t.jsx)("input",{ref:o,id:i,type:"file",accept:"image/*",className:"sr-only",disabled:!s||_,onChange:r(I=>{const T=I.target.files?.[0];T&&(k.mutate(T),I.target.value="")},"onChange")}),(0,t.jsx)("span",{className:"absolute inset-0 z-10 rounded-full bg-black/0 transition-colors group-hover:bg-black/14 group-focus-within:bg-black/14"}),(0,t.jsx)("span",{className:"absolute bottom-1 right-1 z-20 flex size-9 items-center justify-center rounded-full border border-background bg-primary text-primary-foreground shadow-sm",children:k.isPending?(0,t.jsx)(st,{className:"size-4 animate-spin"}):(0,t.jsx)(Cte,{className:"size-4"})}),(0,t.jsxs)(ko,{size:"lg",className:"data-[size=lg]:size-24 ring-4 ring-background shadow-xl",children:[S?(0,t.jsx)(Zc,{src:S,alt:N}):null,(0,t.jsx)(No,{children:C})]})]}),(0,t.jsxs)("div",{className:"flex flex-wrap items-center gap-2",children:[(0,t.jsxs)($,{type:"button",variant:"secondary",onClick:r(()=>o.current?.click(),"onClick"),disabled:!s||_,children:[k.isPending?(0,t.jsx)(st,{className:"size-4 animate-spin"}):(0,t.jsx)(Cte,{className:"size-4"}),S?"Change photo":"Upload photo"]}),S?(0,t.jsxs)($,{type:"button",variant:"outline",onClick:r(()=>w.mutate(),"onClick"),disabled:_,children:[w.isPending?(0,t.jsx)(st,{className:"size-4 animate-spin"}):(0,t.jsx)(ha,{className:"size-4"}),"Remove"]}):null]})]}),(0,t.jsxs)("div",{className:"min-w-0 flex-1 space-y-2 pb-1",children:[(0,t.jsxs)("div",{children:[(0,t.jsx)("h2",{className:"truncate text-2xl font-semibold text-foreground",children:N}),(0,t.jsx)("p",{className:"truncate text-sm text-muted-foreground",children:f.data.user.email??"No email"})]}),(0,t.jsxs)("p",{className:"max-w-2xl text-sm leading-6 text-muted-foreground",children:["Click the avatar to upload a new image. ",R]})]})]})})]}),(0,t.jsxs)("form",{className:"grid gap-6 md:grid-cols-2",onSubmit:r(I=>{I.preventDefault(),y.mutate({name:v(),image:d.trim()||null})},"onSubmit"),children:[(0,t.jsxs)("div",{className:"space-y-2",children:[(0,t.jsx)(Ds,{htmlFor:"profile-name",children:"Display name"}),(0,t.jsx)(dt,{id:"profile-name",value:l,onChange:r(I=>c(I.target.value),"onChange"),maxLength:120,placeholder:"Board"}),(0,t.jsx)("p",{className:"text-xs text-muted-foreground",children:"Shown in the sidebar account footer and comment author surfaces."})]}),(0,t.jsxs)("div",{className:"space-y-2",children:[(0,t.jsx)(Ds,{htmlFor:"profile-email",children:"Email"}),(0,t.jsx)(dt,{id:"profile-email",value:f.data.user.email??"",readOnly:!0,disabled:!0}),(0,t.jsx)("p",{className:"text-xs text-muted-foreground",children:"Email is managed by your auth session and is read-only here."})]}),(0,t.jsx)("div",{className:"md:col-span-2 flex justify-end",children:(0,t.jsxs)($,{type:"submit",disabled:_||!l.trim(),children:[y.isPending?(0,t.jsx)(st,{className:"size-4 animate-spin"}):(0,t.jsx)(af,{className:"size-4"}),y.isPending?"Saving...":"Save profile"]})})]}),(0,t.jsx)(yxs,{companyId:s}),(0,t.jsx)(Nxs,{userId:f.data.user.id??null})]})]})}r(Cxs,"ProfileSettings");function _xs(e){return e?e.split(/\r?\n/).map(s=>s.trim()).find(Boolean)??null:null}r(_xs,"firstNonEmptyLine");function Age(e){return _xs(e.lastError)??"Plugin entered an error state without a stored error message."}r(Age,"getPluginErrorSummary");function Ige(e){if(e.bundledExperimental)return!0;const s=e.packageName??"",n=e.packagePath??"";return s.includes("sandbox")||n.includes("sandbox")?!0:e.manifestJson?.environmentDrivers?.some(a=>a.kind==="sandbox_provider")===!0}r(Ige,"isExperimentalPluginIdentity");function Tge(){return(0,t.jsx)(it,{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(Tge,"ExperimentalBadge");function Axs(){const{selectedCompany:e}=ps(),{setBreadcrumbs:s}=Wn(),n=kt(),{pushToast:a}=Xr(),[i,o]=(0,m.useState)(""),[l,c]=(0,m.useState)(!1),[d,u]=(0,m.useState)(null),[h,p]=(0,m.useState)(""),[f,x]=(0,m.useState)(null);(0,m.useEffect)(()=>{s([{label:e?.name??"Organization",href:"/dashboard"},{label:"Settings",href:"/company/settings"},{label:"Plugins"}])},[e?.name,s]);const{data:g,isLoading:v,error:y}=te({queryKey:M.plugins.all,queryFn:r(()=>El.list(),"queryFn")}),k=te({queryKey:M.plugins.examples,queryFn:r(()=>El.listBundled(),"queryFn")}),w=r(()=>{n.invalidateQueries({queryKey:M.plugins.all}),n.invalidateQueries({queryKey:M.plugins.examples}),n.invalidateQueries({queryKey:M.plugins.uiContributions})},"invalidatePluginQueries"),N=je({mutationFn:r(P=>El.install(P),"mutationFn"),onSuccess:r(()=>{w(),c(!1),o(""),a({title:"Plugin installed successfully",tone:"success"})},"onSuccess"),onError:r(P=>{a({title:"Failed to install plugin",body:P.message,tone:"error"})},"onError")}),S=je({mutationFn:r(P=>El.uninstall(P),"mutationFn"),onSuccess:r(()=>{w(),a({title:"Plugin uninstalled successfully",tone:"success"})},"onSuccess"),onError:r(P=>{a({title:"Failed to uninstall plugin",body:P.message,tone:"error"})},"onError")}),C=je({mutationFn:r(P=>El.enable(P),"mutationFn"),onSuccess:r(()=>{w(),a({title:"Plugin enabled",tone:"success"})},"onSuccess"),onError:r(P=>{a({title:"Failed to enable plugin",body:P.message,tone:"error"})},"onError")}),_=je({mutationFn:r(P=>El.disable(P),"mutationFn"),onSuccess:r(()=>{w(),a({title:"Plugin disabled",tone:"info"})},"onSuccess"),onError:r(P=>{a({title:"Failed to disable plugin",body:P.message,tone:"error"})},"onError")}),R=g??[],I=k.data??[],T=new Map(R.map(P=>[P.packageName,P])),E=new Map(I.map(P=>[P.packageName,P])),L=N.variables?.isLocalPath?N.error?.message??null:null,O=(0,m.useMemo)(()=>new Map(R.map(P=>[P.id,Age(P)])),[R]);return v?(0,t.jsx)("div",{className:"p-4 text-sm text-muted-foreground",children:"Loading plugins..."}):y?(0,t.jsx)("div",{className:"p-4 text-sm text-destructive",children:"Failed to load plugins."}):(0,t.jsxs)("div",{className:"max-w-6xl space-y-6",children:[(0,t.jsxs)("div",{className:"flex items-center justify-between",children:[(0,t.jsxs)("div",{className:"flex items-center gap-2",children:[(0,t.jsx)(Ox,{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)(Xx,{asChild:!0,children:(0,t.jsxs)($,{size:"sm",className:"gap-2",children:[(0,t.jsx)(gn,{className:"h-4 w-4"}),"Install Plugin"]})}),(0,t.jsxs)(Ws,{children:[(0,t.jsxs)(ln,{children:[(0,t.jsx)(Qs,{children:"Install Plugin"}),(0,t.jsx)(mn,{children:"Enter the npm package name of the plugin you wish to install."})]}),(0,t.jsx)("div",{className:"grid gap-4 py-4",children:(0,t.jsxs)("div",{className:"grid gap-2",children:[(0,t.jsx)(Ds,{htmlFor:"packageName",children:"npm Package Name"}),(0,t.jsx)(dt,{id:"packageName",placeholder:"@tickernelz/paperclip-pro-plugin-example",value:i,onChange:r(P=>o(P.target.value),"onChange")})]})}),(0,t.jsxs)(cr,{children:[(0,t.jsx)($,{variant:"outline",onClick:r(()=>c(!1),"onClick"),children:"Cancel"}),(0,t.jsx)($,{onClick:r(()=>N.mutate({packageName:i}),"onClick"),disabled:!i||N.isPending,children:N.isPending?"Installing...":"Install"})]})]})]})]}),(0,t.jsx)("div",{className:"rounded-lg border border-amber-500/30 bg-amber-500/5 px-4 py-3",children:(0,t.jsxs)("div",{className:"flex items-start gap-3",children:[(0,t.jsx)(Es,{className:"mt-0.5 h-4 w-4 shrink-0 text-amber-700"}),(0,t.jsxs)("div",{className:"space-y-1 text-sm",children:[(0,t.jsx)("p",{className:"font-medium text-foreground",children:"Plugins are alpha."}),(0,t.jsx)("p",{className:"text-muted-foreground",children:"The plugin runtime and API surface are still changing. Expect breaking changes while this feature settles."})]})]})}),(0,t.jsxs)("section",{className:"space-y-3",children:[(0,t.jsxs)("div",{className:"flex items-center gap-2",children:[(0,t.jsx)(Jm,{className:"h-5 w-5 text-muted-foreground"}),(0,t.jsx)("h2",{className:"text-base font-semibold",children:"Available Plugins"}),(0,t.jsx)(it,{variant:"outline",children:"Bundled"})]}),L&&(0,t.jsx)("div",{className:"rounded-md border border-destructive/25 bg-destructive/[0.06] px-4 py-3 text-sm text-destructive whitespace-pre-wrap break-words",children:L}),k.isLoading?(0,t.jsx)("div",{className:"text-sm text-muted-foreground",children:"Loading bundled plugins..."}):k.error?(0,t.jsx)("div",{className:"text-sm text-destructive",children:"Failed to load bundled plugins."}):I.length===0?(0,t.jsx)("div",{className:"rounded-md border border-dashed px-4 py-3 text-sm text-muted-foreground",children:"No bundled plugins were found in this checkout."}):(0,t.jsx)(nn,{className:"block py-0",children:(0,t.jsx)("ul",{className:"divide-y",children:I.map(P=>{const Q=T.get(P.packageName),D=N.isPending&&N.variables?.isLocalPath&&N.variables.packageName===P.localPath;return(0,t.jsx)("li",{children:(0,t.jsxs)("div",{className:"flex items-center gap-4 px-4 py-3",children:[(0,t.jsxs)("div",{className:"min-w-0 flex-1",children:[(0,t.jsxs)("div",{className:"flex flex-wrap items-center gap-2",children:[(0,t.jsx)("span",{className:"font-medium",children:P.displayName}),(0,t.jsx)(it,{variant:"outline",children:P.tag==="first-party"?"First-party":"Example"}),Ige({packageName:P.packageName,packagePath:P.localPath,bundledExperimental:P.experimental})&&(0,t.jsx)(Tge,{}),Q?(0,t.jsx)(it,{variant:Q.status==="ready"?"default":"secondary",className:Q.status==="ready"?"bg-green-600 hover:bg-green-700":"",children:Q.status}):(0,t.jsx)(it,{variant:"secondary",children:"Not installed"})]}),(0,t.jsx)("p",{className:"mt-1 text-sm text-muted-foreground",children:P.description}),(0,t.jsx)("p",{className:"mt-1 text-xs text-muted-foreground",children:P.packageName}),D&&!P.hasBuiltEntrypoints&&(0,t.jsx)("p",{className:"mt-2 text-xs text-muted-foreground",children:"Building plugin..."})]}),(0,t.jsx)("div",{className:"flex items-center gap-2 shrink-0",children:Q?(0,t.jsxs)(t.Fragment,{children:[Q.status!=="ready"&&(0,t.jsx)($,{variant:"outline",size:"sm",disabled:C.isPending,onClick:r(()=>C.mutate(Q.id),"onClick"),children:"Enable"}),(0,t.jsx)($,{variant:"outline",size:"sm",asChild:!0,children:(0,t.jsx)(Ke,{to:`/company/settings/instance/plugins/${Q.id}`,children:Q.status==="ready"?"Open Settings":"Review"})})]}):(0,t.jsx)($,{size:"sm",disabled:D||N.isPending,onClick:r(()=>N.mutate({packageName:P.localPath,isLocalPath:!0}),"onClick"),children:D?"Installing...":"Install"})})]})},P.packageName)})})})]}),(0,t.jsxs)("section",{className:"space-y-3",children:[(0,t.jsxs)("div",{className:"flex items-center gap-2",children:[(0,t.jsx)(Ox,{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)(nn,{className:"block py-0",children:(0,t.jsx)("ul",{className:"divide-y",children:R.map(P=>(0,t.jsx)("li",{children:(0,t.jsxs)("div",{className:"flex items-start gap-4 px-4 py-3",children:[(0,t.jsxs)("div",{className:"min-w-0 flex-1",children:[(0,t.jsxs)("div",{className:"flex flex-wrap items-center gap-2",children:[(0,t.jsx)(Ke,{to:`/company/settings/instance/plugins/${P.id}`,className:"font-medium hover:underline truncate block",title:P.manifestJson.displayName??P.packageName,children:P.manifestJson.displayName??P.packageName}),E.has(P.packageName)&&(0,t.jsx)(it,{variant:"outline",children:E.get(P.packageName)?.tag==="first-party"?"First-party":"Example"}),Ige({packageName:P.packageName,packagePath:P.packagePath,manifestJson:P.manifestJson,bundledExperimental:E.get(P.packageName)?.experimental})&&(0,t.jsx)(Tge,{})]}),(0,t.jsx)("div",{children:(0,t.jsxs)("p",{className:"text-xs text-muted-foreground mt-0.5 truncate",title:P.packageName,children:[P.packageName," · v",P.manifestJson.version??P.version]})}),(0,t.jsx)("p",{className:"text-sm text-muted-foreground truncate mt-0.5",title:P.manifestJson.description,children:P.manifestJson.description||"No description provided."}),P.status==="error"&&(0,t.jsx)("div",{className:"mt-3 rounded-md border border-red-500/25 bg-red-500/[0.06] px-3 py-2",children:(0,t.jsxs)("div",{className:"flex flex-wrap items-start gap-3",children:[(0,t.jsxs)("div",{className:"min-w-0 flex-1",children:[(0,t.jsxs)("div",{className:"flex items-center gap-2 text-sm font-medium text-red-700 dark:text-red-300",children:[(0,t.jsx)(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:P.lastError??void 0,children:O.get(P.id)})]}),(0,t.jsx)($,{variant:"outline",size:"sm",className:"border-red-500/30 bg-background/60 text-red-700 hover:bg-red-500/10 hover:text-red-800 dark:text-red-200 dark:hover:text-red-100",onClick:r(()=>x(P),"onClick"),children:"View full error"})]})})]}),(0,t.jsx)("div",{className:"flex shrink-0 self-center",children:(0,t.jsxs)("div",{className:"flex flex-col items-end gap-2",children:[(0,t.jsxs)("div",{className:"flex items-center gap-2",children:[(0,t.jsx)(it,{variant:P.status==="ready"?"default":P.status==="error"?"destructive":"secondary",className:W("shrink-0",P.status==="ready"?"bg-green-600 hover:bg-green-700":""),children:P.status}),(0,t.jsx)($,{variant:"outline",size:"icon-sm",className:"h-8 w-8",title:P.status==="ready"?"Disable":"Enable",onClick:r(()=>{P.status==="ready"?_.mutate(P.id):C.mutate(P.id)},"onClick"),disabled:C.isPending||_.isPending,children:(0,t.jsx)(TW,{className:W("h-4 w-4",P.status==="ready"?"text-green-600":"")})}),(0,t.jsx)($,{variant:"outline",size:"icon-sm",className:"h-8 w-8 text-destructive hover:text-destructive",title:"Uninstall",onClick:r(()=>{u(P.id),p(P.manifestJson.displayName??P.packageName)},"onClick"),disabled:S.isPending,children:(0,t.jsx)(ha,{className:"h-4 w-4"})})]}),(0,t.jsx)($,{variant:"outline",size:"sm",className:"mt-2 h-8",asChild:!0,children:(0,t.jsxs)(Ke,{to:`/company/settings/instance/plugins/${P.id}`,children:[(0,t.jsx)(Su,{className:"h-4 w-4"}),"Configure"]})})]})})]})},P.id))})}):(0,t.jsx)(nn,{className:"bg-muted/30",children:(0,t.jsxs)(ni,{className:"flex flex-col items-center justify-center py-10",children:[(0,t.jsx)(Ox,{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(P=>{P||u(null)},"onOpenChange"),children:(0,t.jsxs)(Ws,{children:[(0,t.jsxs)(ln,{children:[(0,t.jsx)(Qs,{children:"Uninstall Plugin"}),(0,t.jsxs)(mn,{children:["Are you sure you want to uninstall ",(0,t.jsx)("strong",{children:h}),"? This action cannot be undone."]})]}),(0,t.jsxs)(cr,{children:[(0,t.jsx)($,{variant:"outline",onClick:r(()=>u(null),"onClick"),children:"Cancel"}),(0,t.jsx)($,{variant:"destructive",disabled:S.isPending,onClick:r(()=>{d&&S.mutate(d,{onSettled:r(()=>u(null),"onSettled")})},"onClick"),children:S.isPending?"Uninstalling...":"Uninstall"})]})]})}),(0,t.jsx)(qs,{open:f!==null,onOpenChange:r(P=>{P||x(null)},"onOpenChange"),children:(0,t.jsxs)(Ws,{className:"sm:max-w-2xl",children:[(0,t.jsxs)(ln,{children:[(0,t.jsx)(Qs,{children:"Error Details"}),(0,t.jsxs)(mn,{children:[f?.manifestJson.displayName??f?.packageName??"Plugin"," hit an error state."]})]}),(0,t.jsxs)("div",{className:"space-y-4",children:[(0,t.jsx)("div",{className:"rounded-md border border-red-500/25 bg-red-500/[0.06] px-4 py-3",children:(0,t.jsxs)("div",{className:"flex items-start gap-3",children:[(0,t.jsx)(Es,{className:"mt-0.5 h-4 w-4 shrink-0 text-red-700 dark:text-red-300"}),(0,t.jsxs)("div",{className:"space-y-1 text-sm",children:[(0,t.jsx)("p",{className:"font-medium text-red-700 dark:text-red-300",children:"What errored"}),(0,t.jsx)("p",{className:"text-red-700/90 dark:text-red-200/90 break-words",children:f?Age(f):"No error summary available."})]})]})}),(0,t.jsxs)("div",{className:"space-y-2",children:[(0,t.jsx)("p",{className:"text-sm font-medium",children:"Full error output"}),(0,t.jsx)("pre",{className:"max-h-(--sz-50vh) overflow-auto rounded-md border bg-muted/40 p-3 text-xs leading-5 whitespace-pre-wrap break-words",children:f?.lastError??"No stored error message."})]})]}),(0,t.jsx)(cr,{children:(0,t.jsx)($,{variant:"outline",onClick:r(()=>x(null),"onClick"),children:"Close"})})]})})]})}r(Axs,"PluginManager");function Ixs(){const{selectedCompany:e,selectedCompanyId:s}=ps(),{setBreadcrumbs:n}=Wn(),{companyPrefix:a,pluginId:i}=ga(),{hideHostPaths:o}=dA(),[l,c]=(0,m.useState)("configuration"),{data:d,isLoading:u}=te({queryKey:M.plugins.detail(i),queryFn:r(()=>El.get(i),"queryFn"),enabled:!!i}),{data:h,isLoading:p}=te({queryKey:M.plugins.health(i),queryFn:r(()=>El.health(i),"queryFn"),enabled:!!i&&d?.status==="ready",refetchInterval:3e4}),{data:f}=te({queryKey:M.plugins.dashboard(i),queryFn:r(()=>El.dashboard(i),"queryFn"),enabled:!!i,refetchInterval:3e4}),{data:x}=te({queryKey:M.plugins.logs(i),queryFn:r(()=>El.logs(i,{limit:50}),"queryFn"),enabled:!!i&&d?.status==="ready",refetchInterval:3e4}),g=d?.manifestJson?.instanceConfigSchema,v=g&&g.properties&&Object.keys(g.properties).length>0,y=i&&s?M.plugins.config(i,s):["plugins",i??"__missing_plugin__","companies","__missing_company__","config"],{data:k,isLoading:w}=te({queryKey:y,queryFn:r(()=>El.getConfig(i,s),"queryFn"),enabled:!!i&&!!v&&!!s}),{slots:N}=Bd({slotTypes:["settingsPage"],companyId:s,enabled:!!s}),S=N.filter(Q=>Q.pluginId===i),C=S.length>0;if((0,m.useEffect)(()=>{n([{label:e?.name??"Organization",href:"/dashboard"},{label:"Settings",href:"/company/settings"},{label:"Plugins",href:"/company/settings/instance/plugins"},{label:d?.manifestJson?.displayName??d?.packageName??"Plugin Details"}])},[e?.name,n,a,d]),(0,m.useEffect)(()=>{c("configuration")},[i]),u)return(0,t.jsx)("div",{className:"p-4 text-sm text-muted-foreground",children:"Loading plugin details..."});if(!d)return(0,t.jsx)(_n,{to:"/company/settings/instance/plugins",replace:!0});const _=d.status,R=d.status==="ready"?"default":d.status==="error"?"destructive":"secondary",I=d.manifestJson.description||"No description provided.",T=d.manifestJson.capabilities??[],E=d.manifestJson.environmentDrivers??[],L=d.manifestJson.localFolders??[],O=L.length>0&&!o,P=E.map(Q=>Q.displayName?.trim()||Q.driverKey).filter((Q,D,F)=>F.indexOf(Q)===D).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)($,{variant:"outline",size:"icon",className:"h-8 w-8",children:(0,t.jsx)(wl,{className:"h-4 w-4"})})}),(0,t.jsxs)("div",{className:"flex items-center gap-2",children:[(0,t.jsx)(Ox,{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)(it,{variant:R,className:"ml-2",children:_}),(0,t.jsxs)(it,{variant:"outline",className:"ml-1",children:["v",d.manifestJson.version??d.version]})]})]}),(0,t.jsxs)(Pi,{value:l,onValueChange:r(Q=>c(Q),"onValueChange"),className:"space-y-6",children:[(0,t.jsx)(Gc,{align:"start",items:[{value:"configuration",label:"Configuration"},{value:"status",label:"Status"}],value:l,onValueChange:r(Q=>c(Q),"onValueChange")}),(0,t.jsx)(fa,{value:"configuration",className:"space-y-6",children:(0,t.jsxs)("div",{className:"space-y-8",children:[(0,t.jsxs)("section",{className:"space-y-5",children:[(0,t.jsx)("h2",{className:"text-base font-semibold",children:"About"}),(0,t.jsxs)("div",{className:"grid gap-8 lg:grid-cols-(--gtc-52)",children:[(0,t.jsxs)("div",{className:"space-y-2",children:[(0,t.jsx)("h3",{className:"text-sm font-medium text-muted-foreground",children:"Description"}),(0,t.jsx)("p",{className:"text-sm leading-6 text-foreground/90",children:I})]}),(0,t.jsxs)("div",{className:"space-y-4 text-sm",children:[(0,t.jsxs)("div",{className:"space-y-1.5",children:[(0,t.jsx)("h3",{className:"font-medium text-muted-foreground",children:"Author"}),(0,t.jsx)("p",{className:"text-foreground",children:d.manifestJson.author})]}),(0,t.jsxs)("div",{className:"space-y-2",children:[(0,t.jsx)("h3",{className:"font-medium text-muted-foreground",children:"Categories"}),(0,t.jsx)("div",{className:"flex flex-wrap gap-2",children:d.categories.length>0?d.categories.map(Q=>(0,t.jsx)(it,{variant:"outline",className:"capitalize",children:Q},Q)):(0,t.jsx)("span",{className:"text-foreground",children:"None"})})]})]})]})]}),(0,t.jsx)(Hl,{}),(0,t.jsxs)("section",{className:"space-y-4",children:[(0,t.jsx)("div",{className:"space-y-1",children:(0,t.jsx)("h2",{className:"text-base font-semibold",children:"Settings"})}),O?(0,t.jsx)(Txs,{pluginId:i,companyId:s,declarations:L}):null,C?(0,t.jsx)("div",{className:"space-y-3",children:S.map(Q=>(0,t.jsx)(pm,{slot:Q,context:{companyId:s,companyPrefix:a??null},missingBehavior:"placeholder"},`${Q.pluginKey}:${Q.id}`))}):v?(0,t.jsx)(Pxs,{pluginId:i,companyId:s,schema:g,initialValues:k?.configJson,isLoading:w,pluginStatus:d.status,supportsConfigTest:d.supportsConfigTest===!0}):E.length>0?(0,t.jsxs)("div",{className:"rounded-md border border-border/60 bg-muted/20 px-4 py-3 text-sm",children:[(0,t.jsx)("p",{className:"font-medium text-foreground",children:"Configure this plugin from Settings → Environments."}),(0,t.jsxs)("p",{className:"mt-1 text-muted-foreground",children:[P||"This plugin"," registers environment runtime settings there so the execution target stays instance-scoped while secret bindings still resolve through the selected organization context."]}),(0,t.jsx)("div",{className:"mt-3",children:(0,t.jsx)(Ke,{to:"/company/settings/instance/environments",children:(0,t.jsx)($,{variant:"outline",size:"sm",children:"Open Environments"})})})]}):O?null:(0,t.jsx)("p",{className:"text-sm text-muted-foreground",children:"This plugin does not require any settings."})]})]})}),(0,t.jsx)(fa,{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)(nn,{children:[(0,t.jsxs)(mo,{children:[(0,t.jsxs)(Oo,{className:"text-base flex items-center gap-1.5",children:[(0,t.jsx)(qm,{className:"h-4 w-4"}),"Runtime Dashboard"]}),(0,t.jsx)(Hc,{children:"Worker process, scheduled jobs, and webhook deliveries"})]}),(0,t.jsx)(ni,{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)(qm,{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)(it,{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:Dxs(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:$xs(f.worker.lastCrashAt)})]})]})]}):(0,t.jsx)("p",{className:"text-sm text-muted-foreground italic",children:"No worker process registered."})]}),(0,t.jsx)(Hl,{}),(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)(Kb,{className:"h-3.5 w-3.5 text-muted-foreground"}),"Recent Job Runs"]}),f.recentJobRuns.length>0?(0,t.jsx)("div",{className:"space-y-2",children:f.recentJobRuns.map(Q=>(0,t.jsxs)("div",{className:"flex items-center justify-between gap-2 rounded-md bg-muted/50 px-2 py-1.5 text-sm",children:[(0,t.jsxs)("div",{className:"flex min-w-0 items-center gap-2",children:[(0,t.jsx)(Oxs,{status:Q.status}),(0,t.jsx)("span",{className:"truncate font-mono text-xs",title:Q.jobKey??Q.jobId,children:Q.jobKey??Q.jobId.slice(0,8)}),(0,t.jsx)(it,{variant:"outline",className:"px-1 py-0 text-(length:--text-nano)",children:Q.trigger})]}),(0,t.jsxs)("div",{className:"flex shrink-0 items-center gap-2 text-xs text-muted-foreground",children:[Q.durationMs!=null?(0,t.jsx)("span",{children:Ege(Q.durationMs)}):null,(0,t.jsx)("span",{title:Q.createdAt,children:Lge(Q.createdAt)})]})]},Q.id))}):(0,t.jsx)("p",{className:"text-sm text-muted-foreground italic",children:"No job runs recorded yet."})]}),(0,t.jsx)(Hl,{}),(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)(OW,{className:"h-3.5 w-3.5 text-muted-foreground"}),"Recent Webhook Deliveries"]}),f.recentWebhookDeliveries.length>0?(0,t.jsx)("div",{className:"space-y-2",children:f.recentWebhookDeliveries.map(Q=>(0,t.jsxs)("div",{className:"flex items-center justify-between gap-2 rounded-md bg-muted/50 px-2 py-1.5 text-sm",children:[(0,t.jsxs)("div",{className:"flex min-w-0 items-center gap-2",children:[(0,t.jsx)(Bxs,{status:Q.status}),(0,t.jsx)("span",{className:"truncate font-mono text-xs",title:Q.webhookKey,children:Q.webhookKey})]}),(0,t.jsxs)("div",{className:"flex shrink-0 items-center gap-2 text-xs text-muted-foreground",children:[Q.durationMs!=null?(0,t.jsx)("span",{children:Ege(Q.durationMs)}):null,(0,t.jsx)("span",{title:Q.createdAt,children:Lge(Q.createdAt)})]})]},Q.id))}):(0,t.jsx)("p",{className:"text-sm text-muted-foreground italic",children:"No webhook deliveries recorded yet."})]}),(0,t.jsxs)("div",{className:"flex items-center gap-1.5 border-t border-border/50 pt-2 text-xs text-muted-foreground",children:[(0,t.jsx)(Io,{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)(nn,{children:[(0,t.jsxs)(mo,{children:[(0,t.jsxs)(Oo,{className:"text-base flex items-center gap-1.5",children:[(0,t.jsx)(Ate,{className:"h-4 w-4"}),"Recent Logs"]}),(0,t.jsxs)(Hc,{children:["Last ",x.length," log entries"]})]}),(0,t.jsx)(ni,{children:(0,t.jsx)("div",{className:"max-h-64 space-y-1 overflow-y-auto font-mono text-xs",children:x.map(Q=>(0,t.jsxs)("div",{className:`flex gap-2 py-0.5 ${Q.level==="error"?"text-destructive":Q.level==="warn"?"text-yellow-600 dark:text-yellow-400":Q.level==="debug"?"text-muted-foreground/60":"text-muted-foreground"}`,children:[(0,t.jsx)("span",{className:"shrink-0 text-muted-foreground/50",children:new Date(Q.createdAt).toLocaleTimeString()}),(0,t.jsx)(it,{variant:"outline",className:"h-4 shrink-0 px-1 text-(length:--text-nano)",children:Q.level}),(0,t.jsx)("span",{className:"truncate",title:Q.message,children:Q.message})]},Q.id))})})]}):null]}),(0,t.jsxs)("div",{className:"space-y-6",children:[(0,t.jsxs)(nn,{children:[(0,t.jsx)(mo,{children:(0,t.jsxs)(Oo,{className:"text-base flex items-center gap-1.5",children:[(0,t.jsx)(Ate,{className:"h-4 w-4"}),"Health Status"]})}),(0,t.jsx)(ni,{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)(it,{variant:h.healthy?"default":"destructive",children:h.status})]}),h.checks.length>0?(0,t.jsx)("div",{className:"space-y-2 border-t border-border/50 pt-2",children:h.checks.map((Q,D)=>(0,t.jsxs)("div",{className:"flex items-start justify-between gap-2",children:[(0,t.jsx)("span",{className:"truncate text-muted-foreground",title:Q.name,children:Q.name}),Q.passed?(0,t.jsx)(YKe,{className:"h-4 w-4 shrink-0 text-green-500"}):(0,t.jsx)(gd,{className:"h-4 w-4 shrink-0 text-destructive"})]},D))}):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)(it,{variant:R,children:_})]}),(0,t.jsx)("p",{children:"Health checks run once the plugin is ready."}),d.lastError?(0,t.jsx)("div",{className:"break-words rounded border border-destructive/20 bg-destructive/10 p-2 text-xs text-destructive",children:d.lastError}):null]})})]}),(0,t.jsxs)(nn,{children:[(0,t.jsx)(mo,{children:(0,t.jsx)(Oo,{className:"text-base",children:"Details"})}),(0,t.jsxs)(ni,{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)(nn,{children:[(0,t.jsx)(mo,{children:(0,t.jsxs)(Oo,{className:"text-base flex items-center gap-1.5",children:[(0,t.jsx)(Ic,{className:"h-4 w-4"}),"Permissions"]})}),(0,t.jsx)(ni,{children:T.length>0?(0,t.jsx)("ul",{className:"space-y-2 text-sm text-muted-foreground",children:T.map(Q=>(0,t.jsx)("li",{className:"rounded-md bg-muted/40 px-2.5 py-2 font-mono text-xs text-foreground/85",children:Q},Q))}):(0,t.jsx)("p",{className:"text-sm text-muted-foreground italic",children:"No special permissions requested."})})]})]})]})})]})]})}r(Ixs,"PluginSettings");function Txs({pluginId:e,companyId:s,declarations:n}){const{data:a,isLoading:i,error:o}=te({queryKey:s?M.plugins.localFolders(e,s):["plugins",e,"companies","none","local-folders"],queryFn:r(()=>El.listLocalFolders(e,s),"queryFn"),enabled:!!s}),l=new Map((a?.folders??[]).map(c=>[c.folderKey,c]));return s?(0,t.jsxs)("div",{className:"space-y-3",children:[(0,t.jsxs)("div",{className:"flex items-center gap-2",children:[(0,t.jsx)(nl,{className:"h-4 w-4 text-muted-foreground"}),(0,t.jsx)("h3",{className:"text-sm font-medium",children:"Local folders"})]}),o?(0,t.jsx)("div",{className:"rounded-md border border-destructive/20 bg-destructive/10 px-3 py-2 text-sm text-destructive",children:o.message||"Failed to load local folder settings."}):null,i?(0,t.jsxs)("div",{className:"flex items-center gap-2 py-3 text-sm text-muted-foreground",children:[(0,t.jsx)(st,{className:"h-4 w-4 animate-spin"}),"Loading local folders..."]}):(0,t.jsx)("div",{className:"space-y-3",children:n.map(c=>(0,t.jsx)(Rxs,{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(Txs,"PluginLocalFoldersSettings");function Rxs({pluginId:e,companyId:s,declaration:n,status:a}){const i=kt(),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=>El.configureLocalFolder(e,s,n.folderKey,{path:v,access:n.access,requiredDirectories:n.requiredDirectories,requiredFiles:n.requiredFiles}),"mutationFn"),onSuccess:r(v=>{u({type:v.healthy?"success":"error",text:v.healthy?"Local folder saved.":"Local folder saved, but validation still needs attention."}),i.invalidateQueries({queryKey:M.plugins.localFolders(e,s)})},"onSuccess"),onError:r(v=>{u({type:"error",text:v.message||"Failed to save local folder."})},"onError")}),p=l.trim(),f=p!==o,x=a?.access??n.access??"readWrite",g=(0,m.useCallback)(()=>{if(!p){u({type:"error",text:"Local folder path is required."});return}if(!Mxs(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)(it,{variant:"outline",className:"font-mono text-(length:--text-nano)",children:n.folderKey}),(0,t.jsx)(it,{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)(it,{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)(ZB,{label:"Configured",value:a?.configured?"Yes":"No",ok:!!a?.configured}),(0,t.jsx)(ZB,{label:"Readable",value:a?.readable?"Yes":"No",ok:!!a?.readable}),(0,t.jsx)(ZB,{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)(tu,{className:"h-8"}),(0,t.jsxs)($,{size:"sm",onClick:g,disabled:h.isPending||!f||!s,children:[h.isPending?(0,t.jsx)(st,{className:"h-3.5 w-3.5 animate-spin"}):(0,t.jsx)(af,{className:"h-3.5 w-3.5"}),"Save"]})]})]}),(0,t.jsx)(Exs,{status:a,declaration:n}),a?.problems?.length?(0,t.jsxs)("div",{className:"space-y-2 rounded-md border border-destructive/20 bg-destructive/10 px-3 py-2 text-sm text-destructive",children:[(0,t.jsx)("div",{className:"font-medium",children:"Validation problems"}),(0,t.jsx)("ul",{className:"space-y-1",children:a.problems.map((v,y)=>(0,t.jsxs)("li",{children:[v.message,v.path?(0,t.jsxs)("span",{className:"font-mono",children:[" ",v.path]}):null]},`${v.code}:${v.path??""}:${y}`))})]}):null,d?(0,t.jsx)("div",{className:`rounded-md border px-3 py-2 text-sm ${d.type==="success"?"border-green-200 bg-green-50 text-green-700 dark:border-green-900 dark:bg-green-950/30 dark:text-green-400":"border-destructive/20 bg-destructive/10 text-destructive"}`,children:d.text}):null]})}r(Rxs,"PluginLocalFolderRow");function ZB({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)(it,{variant:n?"default":"secondary",children:s})]})}r(ZB,"FolderStatusMetric");function Exs({status:e,declaration:s}){const n=e?.requiredDirectories??s.requiredDirectories??[],a=e?.requiredFiles??s.requiredFiles??[],i=e?.missingDirectories??n,o=e?.missingFiles??a,l=Lxs(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)(Rge,{title:"Required directories",items:n,missingItems:i,missingLabel:"Missing directories",inspectionUnavailable:l}),(0,t.jsx)(Rge,{title:"Required files",items:a,missingItems:o,missingLabel:"Missing files",inspectionUnavailable:l})]})}r(Exs,"FolderRequirements");function Lxs(e){return!e?.configured||e.readable?!1:e.problems.some(s=>s.code==="missing"||s.code==="not_readable"||s.code==="not_directory")}r(Lxs,"isRootNotInspected");function Rge({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)(it,{variant:"secondary",className:"text-(length:--text-nano)",children:"Not inspected"}):n.length>0?(0,t.jsxs)(it,{variant:"destructive",className:"text-(length:--text-nano)",children:[n.length," missing"]}):(0,t.jsx)(it,{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(Rge,"RequirementList");function Mxs(e){return e.startsWith("/")||/^[A-Za-z]:[\\/]/.test(e)||e.startsWith("\\\\")}r(Mxs,"isLikelyAbsolutePath");function Pxs({pluginId:e,companyId:s,schema:n,initialValues:a,isLoading:i,pluginStatus:o,supportsConfigTest:l}){const c=kt(),[d,u]=(0,m.useState)(()=>({...Yp(n),...a??{}})),h=(0,m.useRef)(!1);(0,m.useEffect)(()=>{h.current=!1,u(Yp(n))},[s,e,n]),(0,m.useEffect)(()=>{a&&!h.current&&(h.current=!0,u({...Yp(n),...a}))},[a,n]);const[p,f]=(0,m.useState)({}),[x,g]=(0,m.useState)(null),[v,y]=(0,m.useState)(null),k=JSON.stringify(d)!==JSON.stringify({...Yp(n),...a??{}}),w=je({mutationFn:r(R=>{if(!s)throw new Error("Select an organization before saving plugin configuration.");return El.saveConfig(e,s,R)},"mutationFn"),onSuccess:r(()=>{g({type:"success",text:"Configuration saved."}),y(null),s&&c.invalidateQueries({queryKey:M.plugins.config(e,s)}),setTimeout(()=>g(null),3e3)},"onSuccess"),onError:r(R=>{g({type:"error",text:R.message||"Failed to save configuration."})},"onError")}),N=je({mutationFn:r(R=>{if(!s)throw new Error("Select an organization before testing plugin configuration.");return El.testConfig(e,s,R)},"mutationFn"),onSuccess:r(R=>{R.valid?y({type:"success",text:"Configuration test passed."}):y({type:"error",text:R.message||"Configuration test failed."})},"onSuccess"),onError:r(R=>{y({type:"error",text:R.message||"Configuration test failed."})},"onError")}),S=(0,m.useCallback)(R=>{u(R),f({}),g(null)},[]),C=(0,m.useCallback)(()=>{const R=Nj(n,d);if(Object.keys(R).length>0){f(R);return}f({}),w.mutate(d)},[n,d,w]),_=(0,m.useCallback)(()=>{const R=Nj(n,d);if(Object.keys(R).length>0){f(R);return}f({}),y(null),N.mutate(d)},[n,d,N]);return i?(0,t.jsxs)("div",{className:"flex items-center gap-2 text-sm text-muted-foreground py-4",children:[(0,t.jsx)(st,{className:"h-4 w-4 animate-spin"}),"Loading configuration..."]}):(0,t.jsxs)("div",{className:"space-y-4",children:[(0,t.jsx)(V3,{schema:n,values:d,onChange:S,errors:p,disabled:w.isPending}),x&&(0,t.jsx)("div",{className:`text-sm p-2 rounded border ${x.type==="success"?"text-green-700 bg-green-50 border-green-200 dark:text-green-400 dark:bg-green-950/30 dark:border-green-900":"text-destructive bg-destructive/10 border-destructive/20"}`,children:x.text}),v&&(0,t.jsx)("div",{className:`text-sm p-2 rounded border ${v.type==="success"?"text-green-700 bg-green-50 border-green-200 dark:text-green-400 dark:bg-green-950/30 dark:border-green-900":"text-destructive bg-destructive/10 border-destructive/20"}`,children:v.text}),(0,t.jsxs)("div",{className:"flex items-center gap-2 pt-2",children:[(0,t.jsx)($,{onClick:C,disabled:w.isPending||!k,size:"sm",children:w.isPending?(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)(st,{className:"h-3.5 w-3.5 animate-spin"}),"Saving..."]}):"Save Configuration"}),o==="ready"&&l&&(0,t.jsx)($,{variant:"outline",onClick:_,disabled:N.isPending||!s,size:"sm",children:N.isPending?(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)(st,{className:"h-3.5 w-3.5 animate-spin"}),"Testing..."]}):"Test Configuration"})]})]})}r(Pxs,"PluginConfigForm");function Dxs(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(Dxs,"formatUptime");function Ege(e){return e<1e3?`${e}ms`:e<6e4?`${(e/1e3).toFixed(1)}s`:`${(e/6e4).toFixed(1)}m`}r(Ege,"formatDuration");function Lge(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(Lge,"formatRelativeTime");function $xs(e){return new Date(e).toLocaleString()}r($xs,"formatTimestamp");function Oxs({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(Oxs,"JobStatusDot");function Bxs({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(Bxs,"DeliveryStatusDot");function JB({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:wf(e.type)}),(0,t.jsx)(it,{variant:"outline",children:e.source==="external"?"External":"Built-in"}),e.source==="external"&&(e.isLocalPath?(0,t.jsx)("span",{title:"Installed from local path",children:(0,t.jsx)(nl,{className:"h-4 w-4 text-amber-500"})}):(0,t.jsx)("span",{title:"Installed from npm",children:(0,t.jsx)(Xh,{className:"h-4 w-4 text-red-500"})})),e.version&&(0,t.jsxs)(it,{variant:"secondary",className:"font-mono text-(length:--text-nano)",children:["v",e.version]}),e.overriddenBuiltin&&(0,t.jsx)(it,{variant:"secondary",className:"text-blue-600 border-blue-400",children:"Overrides built-in"}),u&&(0,t.jsxs)(it,{variant:"secondary",className:"text-blue-600 border-blue-400",children:["Overridden by ",u]}),e.disabled&&(0,t.jsx)(it,{variant:"secondary",className:"text-amber-600 border-amber-400",children:f??"Hidden from menus"})]}),(0,t.jsxs)("p",{className:"text-xs text-muted-foreground mt-0.5",children:[e.type,e.packageName&&e.packageName!==e.type&&(0,t.jsxs)(t.Fragment,{children:[" · ",e.packageName]})," · ",e.modelsCount," models"]})]}),(0,t.jsxs)("div",{className:"flex items-center gap-2 shrink-0",children:[o&&(0,t.jsx)($,{variant:"outline",size:"icon-sm",className:"h-8 w-8",title:"Reinstall adapter (pull latest from npm)",disabled:d,onClick:r(()=>o(e.type),"onClick"),children:(0,t.jsx)(Ui,{className:W("h-4 w-4",d&&"animate-bounce")})}),i&&(0,t.jsx)($,{variant:"outline",size:"icon-sm",className:"h-8 w-8",title:"Reload adapter (hot-swap)",disabled:c,onClick:r(()=>i(e.type),"onClick"),children:(0,t.jsx)(Ai,{className:W("h-4 w-4",c&&"animate-spin")})}),(0,t.jsx)($,{variant:"outline",size:"icon-sm",className:"h-8 w-8",title:e.disabled?h??"Show in agent menus":p??"Hide from agent menus",disabled:l,onClick:r(()=>n(e.type,!e.disabled),"onClick"),children:(0,t.jsx)(TW,{className:W("h-4 w-4",e.disabled?"text-muted-foreground":"text-green-600")})}),s&&(0,t.jsx)($,{variant:"outline",size:"icon-sm",className:"h-8 w-8 text-destructive hover:text-destructive",title:"Remove adapter",onClick:r(()=>a(e.type),"onClick"),children:(0,t.jsx)(ha,{className:"h-4 w-4"})})]})]})})}r(JB,"AdapterRow");function Fxs(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(Fxs,"fetchNpmLatestVersion");function zxs({adapter:e,open:s,isReinstalling:n,onConfirm:a,onCancel:i}){const{data:o,isLoading:l}=te({queryKey:["npm-latest-version",e?.packageName],queryFn:r(()=>e?.packageName?Fxs(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)(Ws,{children:[(0,t.jsxs)(ln,{children:[(0,t.jsx)(Qs,{children:"Reinstall Adapter"}),(0,t.jsxs)(mn,{children:["This will pull the latest version of"," ",(0,t.jsx)("strong",{children:e?.packageName})," from npm and hot-swap the running adapter module. Existing agents will use the new version on their next run."]})]}),(0,t.jsxs)("div",{className:"rounded-md border bg-muted/50 px-4 py-3 text-sm space-y-1",children:[(0,t.jsxs)("div",{className:"flex items-center justify-between",children:[(0,t.jsx)("span",{className:"text-muted-foreground",children:"Package"}),(0,t.jsx)("span",{className:"font-mono",children:e?.packageName})]}),(0,t.jsxs)("div",{className:"flex items-center justify-between",children:[(0,t.jsx)("span",{className:"text-muted-foreground",children:"Current"}),(0,t.jsx)("span",{className:"font-mono",children:e?.version?`v${e.version}`:"unknown"})]}),(0,t.jsxs)("div",{className:"flex items-center justify-between",children:[(0,t.jsx)("span",{className:"text-muted-foreground",children:"Latest on npm"}),(0,t.jsx)("span",{className:"font-mono",children:l?"checking...":o?`v${o}`:"unavailable"})]}),c&&(0,t.jsx)("p",{className:"text-xs text-muted-foreground pt-1",children:"Already on the latest version."})]}),(0,t.jsxs)(cr,{children:[(0,t.jsx)($,{variant:"outline",onClick:i,disabled:n,children:"Cancel"}),(0,t.jsx)($,{disabled:n,onClick:a,children:n?"Reinstalling...":"Reinstall"})]})]})})}r(zxs,"ReinstallDialog");function Mge(){const{selectedCompany:e}=ps(),{setBreadcrumbs:s}=Wn(),n=kt(),{pushToast:a}=Xr(),[i,o]=(0,m.useState)(""),[l,c]=(0,m.useState)(""),[d,u]=(0,m.useState)(!1),[h,p]=(0,m.useState)(!1),[f,x]=(0,m.useState)(null),[g,v]=(0,m.useState)(null);(0,m.useEffect)(()=>{s([{label:e?.name??"Organization",href:"/dashboard"},{label:"Settings",href:"/company/settings"},{label:"Adapters"}])},[e?.name,s]);const{data:y,isLoading:k}=te({queryKey:M.adapters.all,queryFn:r(()=>Ph.list(),"queryFn")}),w=r(()=>{n.invalidateQueries({queryKey:M.adapters.all})},"invalidate"),N=je({mutationFn:r(P=>Ph.install(P),"mutationFn"),onSuccess:r(P=>{w(),p(!1),o(""),c(""),u(!1),a({title:"Adapter installed",body:`Type "${P.type}" registered successfully.${P.version?` (v${P.version})`:""}`,tone:"success"})},"onSuccess"),onError:r(P=>{a({title:"Install failed",body:P.message,tone:"error"})},"onError")}),S=je({mutationFn:r(P=>Ph.remove(P),"mutationFn"),onSuccess:r(()=>{w(),a({title:"Adapter removed",tone:"success"})},"onSuccess"),onError:r(P=>{a({title:"Removal failed",body:P.message,tone:"error"})},"onError")}),C=je({mutationFn:r(({type:P,disabled:Q})=>Ph.setDisabled(P,Q),"mutationFn"),onSuccess:r(()=>{w()},"onSuccess"),onError:r(P=>{a({title:"Toggle failed",body:P.message,tone:"error"})},"onError")}),_=je({mutationFn:r(({type:P,paused:Q})=>Ph.setOverridePaused(P,Q),"mutationFn"),onSuccess:r(()=>{w()},"onSuccess"),onError:r(P=>{a({title:"Override toggle failed",body:P.message,tone:"error"})},"onError")}),R=je({mutationFn:r(P=>Ph.reload(P),"mutationFn"),onSuccess:r(P=>{w(),Ez(P.type),Cre(P.type),a({title:"Adapter reloaded",body:`Type "${P.type}" reloaded.${P.version?` (v${P.version})`:""}`,tone:"success"})},"onSuccess"),onError:r(P=>{a({title:"Reload failed",body:P.message,tone:"error"})},"onError")}),I=je({mutationFn:r(P=>Ph.reinstall(P),"mutationFn"),onSuccess:r(P=>{w(),Ez(P.type),Cre(P.type),a({title:"Adapter reinstalled",body:`Type "${P.type}" updated from npm.${P.version?` (v${P.version})`:""}`,tone:"success"})},"onSuccess"),onError:r(P=>{a({title:"Reinstall failed",body:P.message,tone:"error"})},"onError")}),T=(y??[]).filter(P=>P.source==="builtin"),E=(y??[]).filter(P=>P.source==="external"),L=(y??[]).filter(P=>P.source==="external"&&P.overriddenBuiltin).filter(P=>!T.some(Q=>Q.type===P.type)).map(P=>({type:P.type,label:wf(P.type),overriddenBy:[P.packageName,P.version?`v${P.version}`:void 0].filter(Boolean).join(" "),overridePaused:!!P.overridePaused,menuDisabled:!!P.disabled}));if(k)return(0,t.jsx)("div",{className:"p-4 text-sm text-muted-foreground",children:"Loading adapters..."});const O=N.isPending||S.isPending||C.isPending||_.isPending||R.isPending||I.isPending;return(0,t.jsxs)("div",{className:"max-w-6xl space-y-6",children:[(0,t.jsxs)("div",{className:"flex items-center justify-between",children:[(0,t.jsxs)("div",{className:"flex items-center gap-2",children:[(0,t.jsx)(qm,{className:"h-6 w-6 text-muted-foreground"}),(0,t.jsx)("h1",{className:"text-xl font-semibold",children:"Adapters"}),(0,t.jsx)(it,{variant:"outline",className:"text-amber-600 border-amber-400",children:"Alpha"})]}),(0,t.jsxs)(qs,{open:h,onOpenChange:p,children:[(0,t.jsx)(Xx,{asChild:!0,children:(0,t.jsxs)($,{size:"sm",className:"gap-2",children:[(0,t.jsx)(gn,{className:"h-4 w-4"}),"Install Adapter"]})}),(0,t.jsxs)(Ws,{children:[(0,t.jsxs)(ln,{children:[(0,t.jsx)(Qs,{children:"Install External Adapter"}),(0,t.jsxs)(mn,{children:["Add an adapter from npm or a local path. The adapter package must export ",(0,t.jsx)("code",{className:"text-xs bg-muted px-1 py-0.5 rounded",children:"createServerAdapter()"}),"."]})]}),(0,t.jsxs)("div",{className:"grid gap-4 py-4",children:[(0,t.jsxs)("div",{className:"flex items-center gap-2",children:[(0,t.jsxs)("button",{type:"button",className:W("inline-flex items-center gap-1.5 rounded-md border px-3 py-1.5 text-xs transition-colors",d?"border-border text-muted-foreground hover:text-foreground hover:bg-accent/50":"border-foreground bg-accent text-foreground"),onClick:r(()=>u(!1),"onClick"),children:[(0,t.jsx)(Xh,{className:"h-3.5 w-3.5"}),"npm package"]}),(0,t.jsxs)("button",{type:"button",className:W("inline-flex items-center gap-1.5 rounded-md border px-3 py-1.5 text-xs transition-colors",d?"border-foreground bg-accent text-foreground":"border-border text-muted-foreground hover:text-foreground hover:bg-accent/50"),onClick:r(()=>u(!0),"onClick"),children:[(0,t.jsx)(nl,{className:"h-3.5 w-3.5"}),"Local path"]})]}),d?(0,t.jsxs)("div",{className:"grid gap-2",children:[(0,t.jsx)(Ds,{htmlFor:"adapterLocalPath",children:"Path to adapter package"}),(0,t.jsxs)("div",{className:"flex gap-2",children:[(0,t.jsx)(dt,{id:"adapterLocalPath",className:"flex-1 font-mono text-xs",placeholder:"/mnt/e/Projects/my-adapter or E:\\Projects\\my-adapter",value:i,onChange:r(P=>o(P.target.value),"onChange")}),(0,t.jsx)(tu,{})]}),(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)(Ds,{htmlFor:"adapterPackageName",children:"Package Name"}),(0,t.jsx)(dt,{id:"adapterPackageName",placeholder:"my-paperclip-adapter",value:i,onChange:r(P=>o(P.target.value),"onChange")})]}),(0,t.jsxs)("div",{className:"grid gap-2",children:[(0,t.jsx)(Ds,{htmlFor:"adapterVersion",children:"Version (optional)"}),(0,t.jsx)(dt,{id:"adapterVersion",placeholder:"latest",value:l,onChange:r(P=>c(P.target.value),"onChange")})]})]})]}),(0,t.jsxs)(cr,{children:[(0,t.jsx)($,{variant:"outline",onClick:r(()=>p(!1),"onClick"),children:"Cancel"}),(0,t.jsx)($,{onClick:r(()=>N.mutate({packageName:i,version:l||void 0,isLocalPath:d}),"onClick"),disabled:!i||N.isPending,children:N.isPending?"Installing...":"Install"})]})]})]})]}),(0,t.jsx)("div",{className:"rounded-lg border border-amber-500/30 bg-amber-500/5 px-4 py-3",children:(0,t.jsxs)("div",{className:"flex items-start gap-3",children:[(0,t.jsx)(Es,{className:"mt-0.5 h-4 w-4 shrink-0 text-amber-700"}),(0,t.jsxs)("div",{className:"space-y-1 text-sm",children:[(0,t.jsx)("p",{className:"font-medium text-foreground",children:"External adapters are alpha."}),(0,t.jsx)("p",{className:"text-muted-foreground",children:"The adapter plugin system is under active development. APIs and storage format may change. Use the power icon to hide adapters from agent menus without removing them."})]})]})}),(0,t.jsxs)("section",{className:"space-y-3",children:[(0,t.jsxs)("div",{className:"flex items-center gap-2",children:[(0,t.jsx)(qm,{className:"h-5 w-5 text-muted-foreground"}),(0,t.jsx)("h2",{className:"text-base font-semibold",children:"External Adapters"})]}),E.length===0?(0,t.jsx)(nn,{className:"bg-muted/30",children:(0,t.jsxs)(ni,{className:"flex flex-col items-center justify-center py-10",children:[(0,t.jsx)(qm,{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)(nn,{className:"block py-0",children:(0,t.jsx)("ul",{className:"divide-y",children:E.map(P=>{const Q=P.overriddenBuiltin,D=Q&&!!P.overridePaused,F=Q?{...P,disabled:D??!1}:P;return(0,t.jsx)(JB,{adapter:F,canRemove:!0,onToggle:Q?(z,K)=>_.mutate({type:z,paused:K}):(z,K)=>C.mutate({type:z,disabled:K}),onRemove:r(z=>x(z),"onRemove"),onReload:r(z=>R.mutate(z),"onReload"),onReinstall:P.isLocalPath?void 0:z=>v(P),isToggling:Q?_.isPending:C.isPending,isReloading:R.isPending,isReinstalling:I.isPending,toggleTitleDisabled:Q?"Pause external override":void 0,toggleTitleEnabled:Q?"Resume external override":void 0,disabledBadgeLabel:Q?"Override paused":void 0},P.type)})})})]}),(0,t.jsxs)("section",{className:"space-y-3",children:[(0,t.jsxs)("div",{className:"flex items-center gap-2",children:[(0,t.jsx)(qm,{className:"h-5 w-5 text-muted-foreground"}),(0,t.jsx)("h2",{className:"text-base font-semibold",children:"Built-in Adapters"})]}),T.length===0&&L.length===0?(0,t.jsx)("div",{className:"text-sm text-muted-foreground",children:"No built-in adapters found."}):(0,t.jsx)(nn,{className:"block py-0",children:(0,t.jsxs)("ul",{className:"divide-y",children:[T.map(P=>(0,t.jsx)(JB,{adapter:P,canRemove:!1,onToggle:r((Q,D)=>C.mutate({type:Q,disabled:D}),"onToggle"),onRemove:r(()=>{},"onRemove"),isToggling:O},P.type)),L.map(P=>(0,t.jsx)(JB,{adapter:{type:P.type,label:P.label,source:"builtin",modelsCount:0,loaded:!0,disabled:P.menuDisabled,capabilities:{supportsInstructionsBundle:!1,supportsSkills:!1,supportsLocalAgentJwt:!1,requiresMaterializedRuntimeSkills:!1,supportsAcp:!1}},canRemove:!1,onToggle:r((Q,D)=>C.mutate({type:Q,disabled:D}),"onToggle"),onRemove:r(()=>{},"onRemove"),isToggling:O,overriddenBy:P.overridePaused?void 0:P.overriddenBy},P.type))]})})]}),(0,t.jsx)(qs,{open:f!==null,onOpenChange:r(P=>{P||x(null)},"onOpenChange"),children:(0,t.jsxs)(Ws,{children:[(0,t.jsxs)(ln,{children:[(0,t.jsx)(Qs,{children:"Remove Adapter"}),(0,t.jsxs)(mn,{children:["Are you sure you want to remove the ",(0,t.jsx)("strong",{children:f})," adapter? It will be unregistered and removed from the adapter store.",f&&y?.find(P=>P.type===f)?.packageName&&(0,t.jsx)(t.Fragment,{children:" npm packages will be cleaned up from disk."})," ","This action cannot be undone."]})]}),(0,t.jsxs)(cr,{children:[(0,t.jsx)($,{variant:"outline",onClick:r(()=>x(null),"onClick"),children:"Cancel"}),(0,t.jsx)($,{variant:"destructive",disabled:S.isPending,onClick:r(()=>{f&&S.mutate(f,{onSettled:r(()=>x(null),"onSettled")})},"onClick"),children:S.isPending?"Removing...":"Remove"})]})]})}),(0,t.jsx)(zxs,{adapter:g,open:g!==null,isReinstalling:I.isPending,onConfirm:r(()=>{g&&I.mutate(g.type,{onSettled:r(()=>v(null),"onSettled")})},"onConfirm"),onCancel:r(()=>v(null),"onCancel")})]})}r(Mge,"AdapterManager");function Pge(){const e=ga(),{companyPrefix:s,pluginId:n,pluginRoutePath:a}=e,i=e["*"],{companies:o,selectedCompanyId:l}=ps(),{setBreadcrumbs:c}=Wn(),d=(0,m.useMemo)(()=>{if(!s)return null;const y=s.toUpperCase();return o.find(k=>k.issuePrefix.toUpperCase()===y)??null},[o,s]),u=!!s&&!d,h=(0,m.useMemo)(()=>d?d.id:s?null:l??null,[d,s,l]),p=(0,m.useMemo)(()=>h?o.find(y=>y.id===h)?.issuePrefix??null:null,[o,h]),{data:f}=te({queryKey:M.plugins.uiContributions,queryFn:r(()=>El.listUiContributions(),"queryFn"),enabled:!!h&&(!!n||!!a)}),x=(0,m.useMemo)(()=>{if(!f)return null;if(n){const k=f.find(N=>N.pluginId===n);if(!k)return null;const w=k.slots.find(N=>N.type==="page");return w?{...w,pluginId:k.pluginId,pluginKey:k.pluginKey,pluginDisplayName:k.displayName,pluginVersion:k.version}:null}if(!a)return null;const y=f.flatMap(k=>{const w=k.slots.find(N=>N.type==="page"&&N.routePath===a);return w?[{...w,pluginId:k.pluginId,pluginKey:k.pluginKey,pluginDisplayName:k.displayName,pluginVersion:k.version}]:[]});return y.length!==1?null:y[0]??null},[n,a,f]),g=(0,m.useMemo)(()=>({companyId:h??null,companyPrefix:p}),[h,p]),v=(0,m.useMemo)(()=>{if(!a||!f)return!1;const y=f.flatMap(k=>k.slots.map(w=>({...w,pluginId:k.pluginId,pluginKey:k.pluginKey,pluginDisplayName:k.displayName,pluginVersion:k.version})));return GW(y,a)!==null},[f,a]);if((0,m.useEffect)(()=>{if(x){if(v){c([{label:qxs(x,i)}]);return}c([{label:"Plugins",href:"/company/settings/instance/plugins"},{label:x.pluginDisplayName}])}},[x,i,c,v]),!h)return u?(0,t.jsx)(om,{scope:"invalid_company_prefix",requestedPrefix:s}):(0,t.jsx)("div",{className:"space-y-4",children:(0,t.jsx)("p",{className:"text-sm text-muted-foreground",children:"Select an organization to view this page."})});if(!f)return(0,t.jsx)("div",{className:"text-sm text-muted-foreground",children:"Loading…"});if(!n&&a&&f.filter(y=>y.slots.some(k=>k.type==="page"&&k.routePath===a)).length>1)return(0,t.jsxs)("div",{className:"rounded-md border border-destructive/30 bg-destructive/5 px-3 py-2 text-sm text-destructive",children:["Multiple plugins declare the route ",(0,t.jsx)("code",{children:a}),". Use the plugin-id route until the conflict is resolved."]});if(!x){if(a)return(0,t.jsx)(om,{scope:"board"});const y=n?`/company/settings/instance/plugins/${n}`:"/company/settings/instance/plugins";return(0,t.jsx)(_n,{to:y,replace:!0})}return(0,t.jsxs)("div",{className:"space-y-4",children:[!v&&(0,t.jsx)("div",{className:"flex items-center gap-2",children:(0,t.jsx)($,{variant:"ghost",size:"sm",asChild:!0,children:(0,t.jsxs)(Ke,{to:p?`/${p}/dashboard`:"/dashboard",children:[(0,t.jsx)(wl,{className:"h-4 w-4 mr-1"}),"Back"]})})}),(0,t.jsx)(pm,{slot:x,context:g,className:"min-h-(--sz-200px)",missingBehavior:"placeholder"})]})}r(Pge,"PluginPage");function qxs(e,s){return Uxs(s)??e.displayName??e.pluginDisplayName}r(qxs,"resolveRouteSidebarPageTitle");function Uxs(e){const s=(e??"").split("/").filter(Boolean).map(Kxs);return s.length===0?null:s[0]==="page"&&s.length>1?Dge(s.slice(1).join("/"),{preserveCase:!0}):Dge(s[0]??null)}r(Uxs,"titleFromRouteSplat");function Dge(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(Dge,"titleFromPath");function Kxs(e){try{return decodeURIComponent(e)}catch{return e}}r(Kxs,"decodeRouteSegment");var XB=Aqe,$ge=r(e=>e.status==="fail"||e.checks.some(s=>s.code==="adapter_auth_missing"),"blocking");function Qxs(){const{selectedCompanyId:e}=ps(),[s]=hi();return e?(0,t.jsx)(Wxs,{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(Qxs,"NewAgentSetup");function Wxs({companyId:e,name:s,adapterType:n,runnerProvider:a,createdAgentId:i}){const o=Yn(),l=kt(),{openNewIssue:c}=al(),d=X_e(`${e}:new-agent`),u=n==="paperclip_runner",h=u&&a==="openai_dot",p=h?"openai_dot":u?a==="grok"?"grok_local":a==="claude"?"claude_local":a==="opencode"?"opencode_local":"codex_local":n,f=p==="claude_local"||p==="codex_local"||p==="grok_local"?p:null,x=p==="opencode_local"||p==="pi_local",g=yit(p),v=x||p==="hermes_local",y=v||!!wre[n],k=!h&&!["cursor_cloud","hermes_gateway"].includes(n),[w,N]=(0,m.useState)(!1),[S,C]=(0,m.useState)(""),[_,R]=(0,m.useState)(""),[I,T]=(0,m.useState)(""),[E,L]=(0,m.useState)("kimi"),[O,P]=(0,m.useState)(i?"saved":f?"connect":"runtime"),[Q,D]=(0,m.useState)(""),F=u?[]:NE(n,Q),[z,K]=(0,m.useState)(""),[U,q]=(0,m.useState)(!1),[G,se]=(0,m.useState)(""),[Z,ie]=(0,m.useState)("openrouter"),[J,re]=(0,m.useState)(""),[oe,V]=(0,m.useState)(null),[X,Y]=(0,m.useState)(()=>p==="opencode_local"?{provider:"openrouter",method:"api_key",mode:"responsible_user"}:void 0),[ae,ne]=(0,m.useState)(null),ce=X??ae?.aiConnection,he=LCe(e,ce,p),[pe,ge]=(0,m.useState)(""),[Ee,de]=(0,m.useState)(""),[Ne,le]=(0,m.useState)(null),Le=te({queryKey:M.agents.detail(i??"new"),queryFn:r(()=>_t.get(i,e),"queryFn"),enabled:!!i,retry:!1}),Ie=Ne??(Le.data?.companyId===e?Le.data:null),[ye,Ae]=(0,m.useState)(!1),[Qe,ue]=(0,m.useState)("idle"),[Be,ft]=(0,m.useState)(null),[gt,Xe]=(0,m.useState)(null),Fe=(0,m.useRef)(0),at=(0,m.useRef)(!1);(0,m.useEffect)(()=>()=>{Fe.current++},[]);const Tt=r(()=>{Fe.current++,ft(null),ue("idle"),Xe(null)},"resetTest"),Dt=r(()=>{ne(null),Y(void 0),Tt(),P("connect")},"editConnection"),Ot=te({queryKey:M.adapters.all,queryFn:Ph.list}),rt=te({queryKey:M.agents.list(e),queryFn:r(()=>_t.list(e),"queryFn")}),Pe=te({queryKey:M.environments.list(e),queryFn:r(()=>Fi.list(e),"queryFn")}),De=te({queryKey:M.instance.settings,queryFn:jr.get}),ht=te({queryKey:M.instance.experimentalSettings,queryFn:jr.getExperimental}),Ft=te({queryKey:M.instance.generalSettings,queryFn:jr.getGeneral}),Et=te({queryKey:M.environments.capabilities(e),queryFn:r(()=>Fi.capabilities(e),"queryFn")}),ct=te({queryKey:M.agents.adapterModels(e,p,null,ce?.provider),queryFn:r(()=>_t.adapterModels(e,p,{provider:ce?.provider}),"queryFn"),enabled:!!p&&k&&!he,retry:!1}),qe=te({queryKey:M.secrets.list(e),queryFn:r(()=>Tr.list(e),"queryFn"),enabled:y&&n!=="cursor_cloud"}),Oe=te({queryKey:M.secrets.myUserSecrets(e),queryFn:r(()=>Tr.listMyUserSecrets(e),"queryFn"),enabled:y&&n!=="cursor_cloud",retry:!1}),Re=LV(Ft.data?.executionMode,Pe.data??[]),Ve=ht.data?.enableManagedSandboxOnly===!0;let xe=null,Ge=null;try{xe=Re.forced?Re.kubernetesEnvironment?.id??null:wN({agentDefaultEnvironmentId:G||null,instanceDefaultEnvironmentId:De.data?.defaultEnvironmentId??null,localDefaultEnvironmentId:NN(Pe.data??[]),managedSandboxOnly:Ve,managedSandboxEnvironmentId:kN(Pe.data??[]),visibleEnvironmentIds:(Pe.data??[]).map(ze=>ze.id)})}catch(ze){Ge=ze instanceof Error?ze.message:"Could not resolve the environment."}const vt=Pe.data?.find(ze=>ze.id===xe),Ss=typeof vt?.config?.provider=="string"?vt.config.provider:"",lt=vt?.driver==="sandbox"&&Et.data?.sandboxProviders?.[Ss]?.supportsLoginPty===!0,zs=wre[n]??g[Z]??"API_KEY",We=Oe.data?.find(ze=>ze.definition.key===zs&&ze.secret),fe=qe.data?.find(ze=>ze.key===zs&&ze.status==="active"),Ye=n==="cursor_cloud"?null:oe??(fe?{type:"secret_ref",secretId:fe.id,version:"latest"}:We?{type:"user_secret_ref",key:zs,version:"latest"}:null),bt=n==="kimi_local"&&!!(J.trim()||Ye),Wt=!!ed(),ut=e5e(n,{cloud:Wt,nativeRunnerEnabled:ht.data?.enableNativeRunner===!0,openAiDotEnabled:ht.data?.enableOpenAiDot===!0,runnerProvider:a})&&Ot.data?.some(ze=>ze.type===n&&ze.loaded&&!ze.disabled&&!Gm(n).comingSoon),$t=!!(ut&&!Ge&&!Pe.isPending&&!De.isPending&&!ht.isPending&&!Ft.isPending&&!rt.isPending&&!Et.isPending&&!Pe.error&&!De.error&&!ht.error&&!Ft.error&&!rt.error&&!Et.error&&(!(Ve||Re.forced)||xe)),$e=Qe==="running"||ye;function pt(ze=ae,At=Ye){const Ut={...Eb,adapterType:n,model:Q||(p==="codex_local"?jN:""),thinkingEffort:z,dangerouslyBypassSandbox:n==="codex_local",envBindings:ze?.env??{},...u?{adapterSchemaValues:{provider:a==="claude"||a==="grok"?"acpx":a,...h?{allowUnmeteredProvider:w}:{},...a==="claude"||a==="grok"?{acpxAgent:a}:{}}}:{}},It=RS(n).buildAdapterConfig(Ut);return n==="omp_local"&&(delete It.thinkingEffort,z&&(It.thinking=z)),u&&Object.assign(It,{provider:a==="claude"||a==="grok"?"acpx":a,...a==="claude"||a==="grok"?{acpxAgent:a}:{},...Q?{model:Q}:{}}),!ce&&!ze?.aiConnection&&y&&At&&(n==="hermes_gateway"?It.apiKey=At:It.env={...It.env??{},[zs]:At}),n==="cursor_cloud"&&Object.assign(It,{repoUrl:pe.trim(),...Ee.trim()?{repoStartingRef:Ee.trim()}:{}}),n==="hermes_gateway"&&(It.apiBaseUrl=S.trim()),bt&&(delete It.model,It.env={...It.env??{},KIMI_MODEL_NAME:{type:"plain",value:_.trim()},KIMI_MODEL_PROVIDER_TYPE:{type:"plain",value:E},...I.trim()?{KIMI_MODEL_BASE_URL:{type:"plain",value:I.trim()}}:{}}),It}r(pt,"buildConfig");function Gt(ze=ae){if(h&&!w)throw new Error("Acknowledge external provider billing before creating your Dot agent.");if(x&&(!Q.trim()||!Q.includes("/")))throw new Error("Choose or enter a model in provider/model format.");if(n==="cursor_cloud"&&!/^https:\/\/github\.com\/[^/]+\/[^/]+/.test(pe.trim()))throw new Error("Enter a GitHub repository URL.");if(["cursor_cloud","hermes_gateway"].includes(n)&&!J.trim()&&!Ye)throw new Error(n==="cursor_cloud"?"Enter a Cursor API key.":`Enter ${zs} or select an organization secret.`);if(n==="hermes_gateway")try{const At=new URL(S.trim());if(!["https:","http:"].includes(At.protocol))throw new Error}catch{throw new Error("Enter the Hermes API base URL.")}if(bt&&!_.trim())throw new Error("Enter the Kimi API model name.");return pt(ze)}r(Gt,"preparedConfig");function be(ze=ae){return ce||ze?.aiConnection?{}:{...ze?.credentials,...y&&J.trim()?{[zs]:J.trim()}:{}}}r(be,"pendingCredentials");async function fs(ze=ae){if(!$t)return!1;const At=++Fe.current;ue("running"),ft(null),Xe(null);try{const Ut=await Gt(ze),It=await MCe({companyId:e,adapterType:n,providerAdapter:p,adapterConfig:Ut,testCredentials:be(ze),aiConnection:X??ze?.aiConnection,environmentId:xe});return At!==Fe.current?!1:(ft(It),ue($ge(It)?"fail":It.status),!$ge(It)&&(!f||It.checks.some(rs=>rs.code.endsWith("hello_probe_passed"))))}catch(Ut){return At===Fe.current&&(Xe(Ut instanceof Error?Ut.message:"Could not test the agent."),ue("fail")),!1}}r(fs,"runTest");async function vn(){if(at.current||i||Ie||!$t||!s.trim()||Qe==="running"||Qe==="fail"||f&&!ae)return;at.current=!0,Ae(!0),Xe(null);const ze=[];let At=!1;try{const Ut=Gt(),It=be();if(Object.keys(It).length&&!await fs())return;for(const[Os,Tn]of Object.entries(It)){const ks=await(f?QCe:bit)(e,Os,Tn);ze.push(ks),n==="hermes_gateway"&&Os==="API_SERVER_KEY"?Ut.apiKey=ks.binding:Ut.env={...Ut.env??{},[Os]:ks.binding}}const rs=rt.data??[],bs=rs.find(Os=>Os.role==="ceo"&&Os.status!=="terminated"),$s=await _t.hire(e,{name:s.trim(),appearance:d.appearance,role:rs.length?"general":"ceo",...bs?{reportsTo:bs.id}:{},adapterType:n,adapterConfig:Ut,defaultEnvironmentId:G||(Re.forced||Ve?xe:null),runtimeConfig:{...AIe({heartbeatEnabled:!1}),...ce?{aiConnection:ce}:{}},budgetMonthlyCents:0,...ae?.storedSessionId?{storedSessionId:ae.storedSessionId}:{},...ae?.applyStoredClaudeLogin?{applyStoredClaudeLogin:!0}:{}});At=!0,re(""),ne(null),le($s.agent),d.clear(),P("saved"),o(`/agents/new?${new URLSearchParams({name:$s.agent.name,adapterType:n,runnerProvider:a,createdAgentId:$s.agent.id})}`,{replace:!0}),l.setQueryData(M.agents.detail($s.agent.id),$s.agent),await Promise.all([l.invalidateQueries({queryKey:M.agents.list(e)}),l.invalidateQueries({queryKey:M.approvals.list(e)})])}catch(Ut){Xe(Ut instanceof Error?Ut.message:"Could not create the agent.")}finally{if(!At)try{await Promise.all(ze.map(Ut=>Ut.remove()))}catch{Xe(Ut=>`${Ut?`${Ut} `:""}Could not remove an unused setup credential. Remove it from Secrets before retrying.`)}l.invalidateQueries({queryKey:M.secrets.myUserSecrets(e)}),l.invalidateQueries({queryKey:M.secrets.list(e)}),at.current=!1,Ae(!1)}}if(r(vn,"finish"),i&&!Ie)return(0,t.jsx)("p",{role:Le.error?"alert":"status",className:"text-sm text-muted-foreground",children:Le.error?"Could not load the created agent. Return to Agents to view it.":"Loading your agent…"});if(!s||!n)return(0,t.jsx)(t5e,{open:!0,initialAdapter:n,onClose:r(()=>o("/agents/all"),"onClose"),onContinue:r(ze=>o(`/agents/new?${new URLSearchParams(ze)}`,{replace:!0}),"onContinue")});const Ls=[...f?["connect"]:[],"runtime","saved"],Bs={connect:"Connect",runtime:"Configure",saved:"Confirmation"},kr=Ie?.defaultEnvironmentId?Pe.data?.find(ze=>ze.id===Ie.defaultEnvironmentId):vt,ds=Ie?.adapterConfig?.env?.KIMI_MODEL_NAME,os=Ie?.adapterConfig?.model||(typeof ds=="string"?ds:ds?.value)||Q||"Default",Se=n==="cursor_cloud"?"Cursor Cloud":n==="hermes_gateway"?"Hermes Gateway":kr?SN(kr):"Local machine",St=Ot.error??Pe.error??De.error??ht.error??Ft.error??rt.error??Et.error;return(0,t.jsx)(wCe,{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)(_N,{appearance:Ie?.appearance??d.appearance,size:256,className:"size-48",trackingScope:"page",state:Ie||Qe==="pass"?"success":Qe==="running"?"loading":"sleepy",muted:!Ie&&Qe!=="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)(B0,{type:p}),(0,t.jsx)("span",{children:Gm(p).label}),u&&!h&&(0,t.jsxs)("span",{children:["·"," ",a==="codex"?"Native app server runner":"Paperclip Runner"]})]})]})]}),Ge&&!Pe.isPending&&(0,t.jsx)("p",{role:"alert",className:"text-sm text-destructive",children:Ge}),St&&(0,t.jsx)("p",{role:"alert",className:"text-sm text-destructive",children:St.message}),Ot.data&&!ut&&(0,t.jsx)("p",{role:"alert",className:"text-sm text-destructive",children:"This adapter is unavailable. Choose an enabled adapter."}),(Ve||Re.forced)&&!Pe.isPending&&!xe&&(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:Ls.map((ze,At)=>(0,t.jsx)("li",{children:(0,t.jsxs)("button",{type:"button","aria-current":ze===O?"step":void 0,disabled:$e||!!Ie||ze==="saved",onClick:r(()=>ze==="connect"&&O!=="connect"?Dt():P(ze),"onClick"),className:W("flex w-full items-center gap-3 rounded-md px-3 py-3 text-left text-sm",ze===O?"bg-accent font-medium":"text-muted-foreground"),children:[(0,t.jsx)("span",{className:W("flex size-6 shrink-0 items-center justify-center rounded-full border text-xs",ze===O?"border-foreground bg-foreground text-background":"border-border"),children:At+1}),Bs[ze]]})},ze))})}),(0,t.jsx)("div",{className:"min-w-0 flex-1",children:(0,t.jsx)(IS,{mode:"wait",initial:!1,children:(0,t.jsx)(Rl.div,{...qit,children:O==="connect"&&f?(0,t.jsxs)(M1t,{className:"mx-auto",children:[(0,t.jsx)("div",{className:"mb-8",children:(0,t.jsx)(IIe,{title:"Connect a model",center:!0})}),$t?(0,t.jsx)(r5e,{companyId:e,adapterType:f,environmentId:xe,canLogin:lt,localEnvironment:vt?.driver==="local",advancedConnection:{value:ce,content:(0,t.jsx)(vz,{companyId:e,agentName:s,adapterType:p,model:Q,environmentId:xe??void 0,value:ce,preferAdvanced:!0,onChange:r(ze=>{ze.mode!=="router"&&(ne(null),Y(ze),Tt())},"onChange")})},onBack:r(()=>o("/agents/all"),"onBack"),onDraftChanged:r(()=>{ne(null),Y(void 0),Tt()},"onDraftChanged"),testConnection:fs,testError:gt??(Be?.checks.find(ze=>ze.level==="error")??Be?.checks.find(ze=>ze.code.includes("hello_probe")&&ze.level==="warn"))?.message,onConnected:r(ze=>{ne(ze),Y(void 0),Tt(),P("runtime")},"onConnected")},xe??"local"):(0,t.jsx)("p",{role:"status",className:"text-sm text-muted-foreground",children:"Loading connection settings…"})]}):O==="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)(cs,{className:"size-5"}),Ie.status==="pending_approval"?"Agent submitted for approval":h?"Your Dot agent has been created":"Your agent is ready"]}),(0,t.jsxs)("dl",{className:"grid grid-cols-2 gap-4 text-sm",children:[(0,t.jsx)("dt",{className:"text-muted-foreground",children:"Adapter"}),(0,t.jsx)("dd",{children:Gm(h?"openai_dot":n).label}),k&&(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)("dt",{className:"text-muted-foreground",children:"Model"}),(0,t.jsx)("dd",{className:"break-all",children:String(os)})]}),(0,t.jsx)("dt",{className:"text-muted-foreground",children:"Environment"}),(0,t.jsx)("dd",{children:Se})]}),(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.":h?"Pair your Dot and test event delivery in configuration before assigning work.":"Assign a task when you’re ready for this agent to work."})]}),(0,t.jsxs)("div",{className:"flex flex-wrap justify-between gap-3",children:[(0,t.jsxs)($,{variant:"outline",onClick:r(()=>o(h?"/agents/all":`${sm(Ie)}/runtime`),"onClick"),children:[(0,t.jsx)(LW,{className:"size-4"}),h?"Back to Agents":"Edit configuration"]}),(0,t.jsxs)($,{disabled:Ie.status==="pending_approval",onClick:r(()=>h?o(`${sm(Ie)}/runtime`):c({assigneeAgentId:Ie.id,status:"todo"}),"onClick"),children:[h?"Pair Dot":`Assign ${Ie.name} a Task`,(0,t.jsx)(fl,{className:"size-4"})]})]})]}):(0,t.jsxs)("form",{className:"space-y-8",onSubmit:r(ze=>{ze.preventDefault(),vn()},"onSubmit"),children:[(0,t.jsx)("h2",{className:"text-xl font-semibold",children:"Configure your agent"}),(0,t.jsxs)("fieldset",{disabled:$e,className:"space-y-8",children:[(0,t.jsxs)("section",{className:"space-y-5",children:[h&&(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)("p",{className:"text-sm text-muted-foreground",children:"Create this agent, then copy its pairing prompt to your Dot."}),ht.data?.enablePublicMcp!==!0&&(0,t.jsx)("p",{className:"text-sm text-muted-foreground",children:"Enable Assistant connections (MCP) in Experimental settings before pairing."}),(0,t.jsx)(yl,{label:"Allow externally billed provider",hint:"Dot does not report token usage or cost. Paperclip cannot enforce a provider spend ceiling; known company and agent budget limits still apply.",checked:w,onChange:r(ze=>{N(ze),Tt()},"onChange")})]}),!f&&hV(p)&&(0,t.jsx)(vz,{companyId:e,agentName:s,adapterType:p,model:Q,environmentId:xe??void 0,value:ce,onChange:r(ze=>{ze.mode!=="router"&&Y(ze),Tt()},"onChange")}),(he?he.error:ct.error)&&(0,t.jsx)("p",{role:"alert",className:"text-sm text-destructive",children:"Could not load models. Retry or enter a model ID manually."}),(k&&!bt||F.length>0)&&(0,t.jsxs)("div",{className:"grid items-start gap-5 sm:grid-cols-2",children:[k&&!bt&&(0,t.jsx)(PV,{models:he?.models??ct.data??[],onRefreshModels:he?.refreshModels,refreshingModels:he?.refreshing,value:Q,onChange:r(ze=>{D(he?.resolveModel(ze)??ze),(n==="omp_local"?!yM(z,ze,(ct.data??[]).map(Ut=>Tk(Ut,!1))):z&&!NE(n,ze).includes(z))&&K("");const At=ze.split("/")[0];x&&KCe[At]&&At!==Z&&(ie(At),re(""),V(null)),Tt()},"onChange"),open:U,onOpenChange:q,allowDefault:!x,required:x,creatable:!0,groupByProvider:x&&!he,preserveOrder:!!he||gV(p),effort:n==="omp_local"?{value:z||null,onChange:r(ze=>{K(ze??""),Tt()},"onChange")}:void 0}),F.length>0&&n!=="omp_local"&&(0,t.jsx)(_s,{label:"Thinking effort",children:(0,t.jsxs)(uW,{"aria-label":"Thinking effort",value:z,onChange:r(ze=>{K(ze.target.value),Tt()},"onChange"),children:[(0,t.jsx)("option",{value:"",children:"Auto"}),F.map(ze=>(0,t.jsx)("option",{value:ze,children:ze},ze))]})})]}),!ce&&kre[n]&&(0,t.jsx)("p",{className:"text-sm text-muted-foreground",children:kre[n]}),y&&!ce&&(0,t.jsxs)("div",{className:"grid gap-5 sm:grid-cols-2",children:[v&&(0,t.jsx)(_s,{label:"API key provider",children:(0,t.jsx)("select",{"aria-label":"API key provider",className:XB,value:Z,onChange:r(ze=>{ie(ze.target.value),D(""),re(""),V(null),Tt()},"onChange"),children:Object.keys(g).map(ze=>(0,t.jsx)("option",{value:ze,children:ze==="openrouter"?"OpenRouter":ze==="openai"?"OpenAI":ze==="anthropic"?"Anthropic":{google:"Google",xai:"xAI",groq:"Groq",opencode:"OpenCode"}[ze]??ze},ze))})}),(0,t.jsx)("div",{className:n==="cursor_cloud"?"sm:col-span-2":void 0,children:(0,t.jsx)(_s,{label:zs,children:(0,t.jsxs)("div",{className:"flex items-center gap-3",children:[(0,t.jsx)(dt,{"aria-label":zs,type:"password",autoComplete:"off",value:J,onChange:r(ze=>{re(ze.target.value),V(null),Tt()},"onChange"),placeholder:Ye?"Using saved key":["cursor_cloud","hermes_gateway"].includes(n)?"Required":"Optional if already configured"}),n==="cursor_cloud"&&(0,t.jsx)("a",{href:"https://cursor.com/dashboard/api?section=user-keys#user-api-keys",target:"_blank",rel:"noopener noreferrer",className:"shrink-0 text-xs text-muted-foreground underline underline-offset-4 hover:text-foreground",children:"get api key"})]})})}),n!=="cursor_cloud"&&(0,t.jsx)("div",{className:v?"sm:col-span-2":void 0,children:(0,t.jsx)(_s,{label:"Or use an organization secret",children:(0,t.jsx)(AV,{secretId:Ye&&typeof Ye=="object"&&Ye.type==="secret_ref"?Ye.secretId:"",secrets:qe.data??[],disabled:$e,onSelect:r(ze=>{V({type:"secret_ref",secretId:ze,version:"latest"}),re(""),Tt()},"onSelect")})})}),(0,t.jsxs)("p",{className:"text-xs text-muted-foreground sm:col-span-2",children:["New keys are saved as organization secrets when you finish setup.",x&&` Use a ${Z}/model ID.`]})]}),n==="hermes_gateway"&&(0,t.jsx)(_s,{label:"Hermes API base URL",children:(0,t.jsx)(dt,{"aria-label":"Hermes API base URL",value:S,onChange:r(ze=>{C(ze.target.value),Tt()},"onChange"),placeholder:"https://hermes.example.com"})}),bt&&(0,t.jsxs)("div",{className:"grid gap-5 sm:grid-cols-2",children:[(0,t.jsx)(_s,{label:"Kimi API model name",children:(0,t.jsx)(dt,{"aria-label":"Kimi API model name",value:_,onChange:r(ze=>{R(ze.target.value),Tt()},"onChange"),placeholder:"kimi-for-coding"})}),(0,t.jsx)(_s,{label:"Kimi API protocol",children:(0,t.jsx)("select",{"aria-label":"Kimi API protocol",className:XB,value:E,onChange:r(ze=>{L(ze.target.value),Tt()},"onChange"),children:["kimi","anthropic","openai"].map(ze=>(0,t.jsx)("option",{children:ze},ze))})}),(0,t.jsx)(_s,{label:"Kimi API base URL",hint:"Optional override for your provider endpoint.",children:(0,t.jsx)(dt,{"aria-label":"Kimi API base URL",value:I,onChange:r(ze=>{T(ze.target.value),Tt()},"onChange"),placeholder:"Provider default"})})]}),n==="cursor_cloud"&&(0,t.jsxs)("div",{className:"grid gap-5 sm:grid-cols-2",children:[(0,t.jsx)(_s,{label:"GitHub repository",children:(0,t.jsx)(dt,{"aria-label":"GitHub repository",value:pe,onChange:r(ze=>{ge(ze.target.value),Tt()},"onChange"),placeholder:"https://github.com/your-org/repo"})}),(0,t.jsx)(_s,{label:"Branch",children:(0,t.jsx)(dt,{"aria-label":"Branch",placeholder:"Repository default",value:Ee,onChange:r(ze=>{de(ze.target.value),Tt()},"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:XB,value:G,disabled:Re.forced,onChange:r(ze=>{se(ze.target.value),ne(null),Tt(),f&&P("connect")},"onChange"),children:[(0,t.jsxs)("option",{value:"",children:["Default: ",Se]}),(Pe.data??[]).filter(ze=>ze.status==="active"&&(!Ve||ze.driver!=="local")).map(ze=>(0,t.jsx)("option",{value:ze.id,children:SN(ze)},ze.id))]})]})]}),(0,t.jsx)(WCe,{variant:h?"prerequisites":"connection",state:Qe,result:Be,error:gt,disabled:!$t||$e||!!(f&&!ae),onTest:r(()=>{fs()},"onTest")}),gt&&Qe!=="fail"&&(0,t.jsx)("p",{role:"alert",className:"text-sm text-destructive",children:gt}),(0,t.jsxs)("div",{className:"flex justify-between border-t border-border py-5",children:[f?(0,t.jsxs)($,{type:"button",variant:"ghost",disabled:$e,onClick:Dt,children:[(0,t.jsx)(wl,{className:"size-4"}),"Connection"]}):(0,t.jsx)("span",{}),f&&!ae?(0,t.jsxs)($,{type:"button",disabled:!$t||$e,onClick:r(()=>P("connect"),"onClick"),children:["Connect model",(0,t.jsx)(fl,{className:"size-4"})]}):(0,t.jsxs)($,{type:"submit",disabled:!$t||$e||Qe==="fail"||!!(f&&!ae),children:[ye?"Creating…":"Finish setup",(0,t.jsx)(cs,{className:"size-4"})]})]})]})},O)})})]})]})})}r(Wxs,"Setup");function Hxs(){const{setBreadcrumbs:e}=Wn();return(0,m.useEffect)(()=>{e([{label:"Agents",href:"/agents"},{label:"New agent"}])},[e]),(0,t.jsx)(Qxs,{})}r(Hxs,"NewAgent");var g8="paperclip:pending-invite-token";function rJ(){return typeof window<"u"&&typeof window.localStorage<"u"}r(rJ,"canUseStorage");function Oge(e){const s=e.trim();if(!(!s||!rJ()))try{window.localStorage.setItem(g8,s)}catch{}}r(Oge,"rememberPendingInviteToken");function KT(e){if(rJ())try{const s=window.localStorage.getItem(g8);if(e&&s!==e.trim())return;window.localStorage.removeItem(g8)}catch{}}r(KT,"clearPendingInviteToken");function Vxs(){if(!rJ())return null;try{const e=window.localStorage.getItem(g8)?.trim();return e?`/invite/${e}`:null}catch{return null}}r(Vxs,"getRememberedInvitePath");var Bge=[" ",".","·","▪","▫","○"],Gxs=1e3/24,QT=[[" ╭────╮ "," ╭╯╭──╮│ "," │ │ ││ "," │ │ ││ "," │ │ ││ "," │ │ ││ "," │ ╰──╯│ "," ╰─────╯ "],[" ╭─────╮ "," │╭──╮╰╮ "," ││ │ │ "," ││ │ │ "," ││ │ │ "," ││ │ │ "," │╰──╯ │ "," ╰────╯ "]];function Fge(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(Fge,"measureChar");function Yxs(e){let s=0;for(const n of e)s=Math.max(s,n.length);return{width:s,height:e.length}}r(Yxs,"spriteSize");function Zxs(){const e=(0,m.useRef)(null),s=(0,m.useRef)(null);return(0,m.useEffect)(()=>{if(!e.current)return;const n=e.current,a=window.matchMedia("(prefers-reduced-motion: reduce)");let i=document.visibilityState!=="hidden",o=!1,l=0,c=0,d=0,u=0,h=7,p=11,f=new Float32Array(0),x=new Float32Array(0),g=new Float32Array(0),v=new Uint16Array(0),y=[],k="";function w(P){const Q=Math.floor(Math.max(0,Math.min(.999,P))*Bge.length);return Bge[Q]??" "}r(w,"toGlyph");function N(){const P=Math.max(0,Math.ceil(n.clientWidth/Math.max(1,h))),Q=Math.max(0,Math.ceil(n.clientHeight/Math.max(1,p)));if(P===d&&Q===u)return;d=P,u=Q;const D=d*u;f=new Float32Array(D),x=new Float32Array(d),g=new Float32Array(u),v=new Uint16Array(D),y=y.filter(F=>F.x>-F.width-2&&F.x<d+2&&F.y>-F.height-2&&F.y<u+2),k=""}r(N,"rebuildGrid");function S(){if(d<=0||u<=0){n.textContent="";return}const P=Array.from({length:u},()=>Array.from({length:d},()=>" "));for(let z=0;z<u;z++)for(let K=0;K<d;K++){const U=(Math.sin(K*.11+z*.04)+Math.cos(z*.08-K*.02))*.18+.22;P[z][K]=w(U)}const Q=18,D=13;for(let z=1;z<u-9;z+=D){const K=Math.floor(z/D)%2===0?2:10;for(let U=K;U<d-10;U+=Q){const q=QT[(U+z)%QT.length];for(let G=0;G<q.length;G++){const se=q[G];for(let Z=0;Z<se.length;Z++){const ie=se[Z]??" ";if(ie===" ")continue;const J=z+G,re=U+Z;J<0||J>=u||re<0||re>=d||(P[J][re]=ie)}}}}const F=P.map(z=>z.join("")).join(`
705
705
  `);n.textContent=F,k=F}r(S,"drawStaticFrame");function C(){const P=QT[Math.floor(Math.random()*QT.length)],Q=Yxs(P),D=Math.random();let F=0,z=0,K=0,U=0;D<.68?(F=Math.random()<.5?-Q.width-1:d+1,z=Math.random()*Math.max(1,u-Q.height),K=F<0?.04+Math.random()*.05:-(.04+Math.random()*.05),U=(Math.random()-.5)*.014):(F=Math.random()*Math.max(1,d-Q.width),z=Math.random()<.5?-Q.height-1:u+1,K=(Math.random()-.5)*.014,U=z<0?.028+Math.random()*.034:-(.028+Math.random()*.034)),y.push({x:F,y:z,vx:K,vy:U,life:0,maxLife:260+Math.random()*220,drift:(Math.random()-.5)*1.2,sprite:P,width:Q.width,height:Q.height})}r(C,"spawnClip");function _(P,Q){const D=Math.round(P.x),F=Math.round(P.y);for(let z=0;z<P.sprite.length;z++){const K=P.sprite[z],U=F+z;if(!(U<0||U>=u))for(let q=0;q<K.length;q++){const G=K[q]??" ";if(G===" ")continue;const se=D+q;if(se<0||se>=d)continue;const Z=U*d+se,ie=G==="│"||G==="─"?.8:.92;f[Z]=Math.max(f[Z]??0,Q*ie),v[Z]=G.charCodeAt(0)}}}r(_,"stampClip");function R(P){if(!o||(s.current=requestAnimationFrame(R),P-l<Gxs||d<=0||u<=0))return;const Q=Math.min(2,l===0?1:(P-l)/16.6667);l=P,c+=Q;const D=d*u,F=Math.max(3,Math.floor(D/2200));for(;y.length<F;)C();for(let K=0;K<f.length;K++)f[K]*=.92;v.fill(0);for(let K=y.length-1;K>=0;K--){const U=y[K];U.life+=Q;const q=Math.sin((U.y+U.drift+c*.12)*.09)*.0018,G=Math.cos((U.x-U.drift-c*.09)*.08)*.0014;if(U.vx=(U.vx+q)*.998,U.vy=(U.vy+G)*.998,U.x+=U.vx*Q,U.y+=U.vy*Q,U.life>=U.maxLife||U.x<-U.width-2||U.x>d+2||U.y<-U.height-2||U.y>u+2){y.splice(K,1);continue}const se=U.life/U.maxLife;_(U,se<.12?se/.12:se>.88?(1-se)/.12:1)}for(let K=0;K<d;K++)x[K]=Math.sin(K*.08+c*.06);for(let K=0;K<u;K++)g[K]=Math.cos(K*.1-c*.05);let z="";for(let K=0;K<u;K++){for(let U=0;U<d;U++){const q=K*d+U,G=v[q];if(G>0){z+=String.fromCharCode(G);continue}const se=(x[U]+g[K])*.08+.1,Z=Math.max(f[q]??0,se*.45);z+=w(Z)}K<u-1&&(z+=`
706
- `)}z!==k&&(n.textContent=z,k=z)}r(R,"step");function I(){const P=d>0&&u>0;if(a.matches){o&&(o=!1,s.current!==null&&cancelAnimationFrame(s.current),s.current=null),P&&S();return}if(!i||!P){o&&(o=!1,s.current!==null&&cancelAnimationFrame(s.current),s.current=null);return}o||(o=!0,l=0,s.current=requestAnimationFrame(R))}r(I,"syncLoop");const T=new ResizeObserver(()=>{const P=Fge(n);h=P.w,p=P.h,N(),I()});T.observe(n);const E=r(()=>{i=document.visibilityState!=="hidden",I()},"onVisibilityChange");document.addEventListener("visibilitychange",E);const L=r(()=>{I()},"onMotionChange");a.addEventListener("change",L);const O=Fge(n);return h=O.w,p=O.h,N(),I(),()=>{o=!1,s.current!==null&&cancelAnimationFrame(s.current),T.disconnect(),document.removeEventListener("visibilitychange",E),a.removeEventListener("change",L)}},[]),(0,t.jsx)("pre",{ref:e,className:"w-full h-full m-0 p-0 overflow-hidden text-muted-foreground/60 select-none leading-none",style:{fontSize:"var(--text-micro)",fontFamily:"monospace"},"aria-hidden":"true"})}r(Zxs,"AsciiArtAnimation");function Jxs({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(Jxs,"PaperclipLockup");function Xxs(){const e=kt(),s=Yn(),[n]=hi(),[a,i]=(0,m.useState)("sign_in"),[o,l]=(0,m.useState)(""),[c,d]=(0,m.useState)(""),[u,h]=(0,m.useState)(""),[p,f]=(0,m.useState)(null),x="auth-error",g=(0,m.useMemo)(()=>f3e(n.get("next")||Vxs()||"/"),[n]),v=te({queryKey:M.health,queryFn:r(()=>Iu.get(),"queryFn"),retry:!1}),{data:y,isLoading:k,error:w}=te({queryKey:M.auth.session,queryFn:r(()=>Ma.getSession(),"queryFn"),retry:!1});(0,m.useEffect)(()=>{y&&(CG(),s(g,{replace:!0}))},[y,s,g]);const N=je({mutationFn:r(async()=>{if(a==="sign_in"){await Ma.signInEmail({email:c.trim(),password:u});return}await Ma.signUpEmail({name:o.trim(),email:c.trim(),password:u})},"mutationFn"),onSuccess:r(async()=>{f(null),await e.invalidateQueries({queryKey:M.auth.session}),await e.invalidateQueries({queryKey:M.health}),await e.resetQueries({queryKey:M.companies.all}),s(g,{replace:!0})},"onSuccess"),onError:r(C=>{f(C instanceof Error?C.message:"Authentication failed")},"onError")}),S=c.trim().length>0&&u.trim().length>0&&(a==="sign_in"||o.trim().length>0&&u.trim().length>=8);return v.isLoading||k||y?(0,t.jsx)("div",{className:"fixed inset-0 flex items-center justify-center",children:(0,t.jsx)(nh,{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)(_G,{cloud:v.data.cloud,returnTo:g}):(0,t.jsxs)("div",{className:"fixed inset-0 flex bg-background",children:[(0,t.jsx)("div",{className:"absolute top-4 right-4 z-10",children:(0,t.jsx)(Lk,{})}),(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)(Jxs,{className:"h-5 w-auto"})}),(0,t.jsx)("h1",{className:"text-xl font-semibold",children:a==="sign_in"?"Sign in to Paperclip":"Create your Paperclip account"}),(0,t.jsx)("p",{className:"mt-1 text-sm text-muted-foreground",children:a==="sign_in"?"Use your email and password to access this instance.":"Create an account for this instance. Email confirmation is not required in v1."}),(0,t.jsxs)("form",{className:"mt-6 space-y-4",method:"post",action:a==="sign_up"?"/api/auth/sign-up/email":"/api/auth/sign-in/email",onSubmit:r(C=>{if(C.preventDefault(),!N.isPending){if(!S){f("Please fill in all required fields.");return}N.mutate()}},"onSubmit"),children:[a==="sign_up"&&(0,t.jsxs)("div",{children:[(0,t.jsx)("label",{htmlFor:"name",className:"text-xs text-muted-foreground mb-1 block",children:"Name"}),(0,t.jsx)("input",{id:"name",name:"name",className:"w-full rounded-md border border-border bg-transparent px-3 py-2 text-sm outline-none focus:ring-1 focus:ring-ring placeholder:text-muted-foreground/50",value:o,onChange:r(C=>l(C.target.value),"onChange"),autoComplete:"name",required:!0,"aria-required":"true","aria-invalid":p?!0:void 0,"aria-describedby":p?x:void 0,autoFocus:!0})]}),(0,t.jsxs)("div",{children:[(0,t.jsx)("label",{htmlFor:"email",className:"text-xs text-muted-foreground mb-1 block",children:"Email"}),(0,t.jsx)("input",{id:"email",name:"email",className:"w-full rounded-md border border-border bg-transparent px-3 py-2 text-sm outline-none focus:ring-1 focus:ring-ring placeholder:text-muted-foreground/50",type:"email",value:c,onChange:r(C=>d(C.target.value),"onChange"),autoComplete:"username",required:!0,"aria-required":"true","aria-invalid":p?!0:void 0,"aria-describedby":p?x:void 0,autoFocus:a==="sign_in"})]}),(0,t.jsxs)("div",{children:[(0,t.jsx)("label",{htmlFor:"password",className:"text-xs text-muted-foreground mb-1 block",children:"Password"}),(0,t.jsx)("input",{id:"password",name:"password",className:"w-full rounded-md border border-border bg-transparent px-3 py-2 text-sm outline-none focus:ring-1 focus:ring-ring placeholder:text-muted-foreground/50",type:"password",value:u,onChange:r(C=>h(C.target.value),"onChange"),autoComplete:a==="sign_in"?"current-password":"new-password",required:!0,"aria-required":"true","aria-invalid":p?!0:void 0,"aria-describedby":p?x:void 0})]}),p&&(0,t.jsx)("p",{id:x,role:"alert",className:"text-xs text-destructive",children:p}),(0,t.jsx)($,{type:"submit",disabled:N.isPending,"aria-disabled":!S||N.isPending,className:`w-full ${!S&&!N.isPending?"opacity-50":""}`,children:N.isPending?"Working…":a==="sign_in"?"Sign In":"Create Account"})]}),(0,t.jsxs)("div",{className:"mt-5 text-sm text-muted-foreground",children:[a==="sign_in"?"Need an account?":"Already have an account?"," ",(0,t.jsx)("button",{type:"button",className:"font-medium text-foreground underline underline-offset-2",onClick:r(()=>{f(null),i(a==="sign_in"?"sign_up":"sign_in")},"onClick"),children:a==="sign_in"?"Create one":"Sign in"})]})]})}),(0,t.jsx)("div",{className:"hidden md:block w-1/2 overflow-hidden",children:(0,t.jsx)(Zxs,{})})]})}r(Xxs,"AuthPage");function egs(){const e=kt(),s=ga(),[n]=hi(),a=(s.token??"").trim(),i=(n.get("code")??"").trim(),o=(0,m.useMemo)(()=>`/board-claim/${encodeURIComponent(a)}${i?`?code=${encodeURIComponent(i)}`:""}`,[a,i]),l=te({queryKey:M.auth.session,queryFn:r(()=>Ma.getSession(),"queryFn"),retry:!1}),c=te({queryKey:["board-claim",a,i],queryFn:r(()=>ir.getBoardClaimStatus(a,i),"queryFn"),enabled:a.length>0&&i.length>0,retry:!1}),d=je({mutationFn:r(()=>ir.claimBoard(a,i),"mutationFn"),onSuccess:r(async()=>{await e.invalidateQueries({queryKey:M.auth.session}),await e.invalidateQueries({queryKey:M.health}),await e.invalidateQueries({queryKey:M.companies.all}),await e.invalidateQueries({queryKey:M.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)(nn,{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)(nn,{className:"block p-6",children:[(0,t.jsx)("h1",{className:"text-lg font-semibold",children:"Board ownership claimed"}),(0,t.jsx)("p",{className:"mt-2 text-sm text-muted-foreground",children:"This instance is now linked to your authenticated user."}),(0,t.jsx)($,{asChild:!0,className:"mt-4",children:(0,t.jsx)(Ke,{to:"/",children:"Open board"})})]})}):l.data?(0,t.jsx)("div",{className:"mx-auto max-w-xl py-10",children:(0,t.jsxs)(nn,{className:"block p-6",children:[(0,t.jsx)("h1",{className:"text-xl font-semibold",children:"Claim Board ownership"}),(0,t.jsx)("p",{className:"mt-2 text-sm text-muted-foreground",children:"This will promote your user to instance admin and migrate organization ownership access from local trusted mode."}),d.error&&(0,t.jsx)("p",{className:"mt-3 text-sm text-destructive",children:d.error instanceof Error?d.error.message:"Failed to claim board ownership"}),(0,t.jsx)($,{className:"mt-5",onClick:r(()=>d.mutate(),"onClick"),disabled:d.isPending,children:d.isPending?"Claiming…":"Claim ownership"})]})}):(0,t.jsx)("div",{className:"mx-auto max-w-xl py-10",children:(0,t.jsxs)(nn,{className:"block p-6",children:[(0,t.jsx)("h1",{className:"text-lg font-semibold",children:"Sign in required"}),(0,t.jsx)("p",{className:"mt-2 text-sm text-muted-foreground",children:"Sign in or create an account, then return to this page to claim Board ownership."}),(0,t.jsx)($,{asChild:!0,className:"mt-4",children:(0,t.jsx)(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(egs,"BoardClaimPage");function zge({origin:e}){const[s,n]=(0,m.useState)(!1);let a;try{const i=new URL(e);i.origin==="https://claude.ai"?a="/brands/claude-color.svg":["https://chatgpt.com","https://chat.openai.com","https://openai.com"].includes(i.origin)&&(a="/brands/codex-color.svg")}catch{}return(0,t.jsxs)("div",{className:"flex items-center gap-2 text-sm text-muted-foreground",children:[a&&!s?(0,t.jsx)("img",{src:a,alt:"",className:"size-4 shrink-0 object-contain",referrerPolicy:"no-referrer",crossOrigin:"anonymous",onError:r(()=>n(!0),"onError")}):(0,t.jsx)(gm,{className:"size-4 shrink-0","aria-hidden":"true"}),(0,t.jsx)("bdi",{className:"min-w-0 break-all",children:e})]})}r(zge,"ClientOrigin");function qge({agentPairingOnly:e=!1}={}){const{id:s=""}=ga();return(0,t.jsx)(xDe,{id:s,agentPairingOnly:e},s)}r(qge,"McpConnectPage");function tgs({initialCode:e}={}){const[s,n]=(0,m.useState)(e??new URLSearchParams(window.location.search).get("user_code")??""),[a,i]=(0,m.useState)(s);return a?(0,t.jsx)(xDe,{id:a,device:!0,onEditCode:r(()=>i(""),"onEditCode")},a):(0,t.jsx)("div",{className:"mx-auto max-w-xl py-10",children:(0,t.jsxs)(nn,{className:"space-y-4 p-6",children:[(0,t.jsxs)("div",{className:"flex items-center gap-3",children:[(0,t.jsx)(kl,{className:"size-8 shrink-0"}),(0,t.jsx)("h1",{className:"min-w-0 text-xl font-semibold",children:"Connect your assistant to Paperclip"})]}),(0,t.jsxs)("form",{className:"space-y-4",onSubmit:r(o=>{o.preventDefault(),i(s.trim())},"onSubmit"),children:[(0,t.jsx)("label",{htmlFor:"device-code",className:"text-sm",children:"Enter the code shown by your assistant"}),(0,t.jsx)(dt,{id:"device-code",autoComplete:"off",value:s,onChange:r(o=>n(o.target.value),"onChange"),required:!0,maxLength:12}),(0,t.jsx)("div",{className:"flex justify-end",children:(0,t.jsx)($,{type:"submit",children:"Continue"})})]})]})})}r(tgs,"McpDevicePage");function xDe({id:e,device:s=!1,agentPairingOnly:n=!1,onEditCode:a}){const i=n?"/dot-mcp/requests":"/mcp/requests",[o,l]=(0,m.useState)(""),[c,d]=(0,m.useState)(""),[u,h]=(0,m.useState)(null),[p,f]=(0,m.useState)(""),[x,g]=(0,m.useState)(!0),[v,y]=(0,m.useState)(null),k=te({queryKey:[s?"mcp-device":n?"dot-mcp-request":"mcp-request",e],queryFn:r(()=>we.get(s?`/mcp/device?user_code=${encodeURIComponent(e)}`:`${i}/${encodeURIComponent(e)}`),"queryFn"),retry:!1}),w=k.data;(0,m.useEffect)(()=>{if(h(null),f(""),!w?.agentConnection||s||!/^[A-Za-z0-9_-]{32}$/.test(c.trim()))return;let Q=!0;return we.post(`${i}/${encodeURIComponent(e)}/dot-pairing/preview`,{pairingCode:c.trim()}).then(D=>{Q&&h(D)}).catch(D=>{Q&&f(D instanceof Error?D.message:"Unable to verify this pairing code.")}),()=>{Q=!1}},[e,s,i,w?.agentConnection,c]);const N=w?.requestedCompanyId??(o||w?.companies[0]?.id||"");(0,m.useEffect)(()=>{!o&&!w?.requestedCompanyId&&w?.companies[0]&&l(w.companies[0].id)},[o,w]);const S=w?.clientName.trim(),C=S&&!/^(assistant|mcp client)$/i.test(S)?S:"your assistant",_=w?.clientOrigin||w?.redirectOrigin,R=w?.companies.find(Q=>Q.id===N),I=!!(!w?.agentConnection&&R?.canWrite&&x),T=!!(w?.requestedWrite&&I),E=!!(w?.requestedConfigure&&I),L=je({mutationFn:r(Q=>we.post(s?"/mcp/device/consent":`/mcp/requests/${encodeURIComponent(e)}/consent`,{decision:Q,companyId:N||void 0,allowWrites:Q==="approve"&&T,allowConfiguration:Q==="approve"&&E,...s?{userCode:e}:{}}),"mutationFn"),onSuccess:r(({redirectUrl:Q,status:D})=>{s&&D?y(D):Q&&window.location.assign(Q)},"onSuccess")}),O=je({mutationFn:r(()=>we.post(`${i}/${encodeURIComponent(e)}/dot-pairing`,{pairingCode:c.trim()}),"mutationFn"),onSuccess:r(({redirectUrl:Q})=>{d(""),window.location.assign(Q)},"onSuccess")});if(v)return(0,t.jsx)("div",{className:"mx-auto max-w-xl py-10",children:(0,t.jsxs)(nn,{className:"block space-y-4 p-6",children:[(0,t.jsx)(kl,{className:"size-8"}),(0,t.jsx)("h1",{className:"text-xl font-semibold",children:v==="approved"?"Access approved":"Connection declined"}),(0,t.jsx)("p",{className:"text-sm",children:v==="approved"?"Return to your assistant. It will finish connecting automatically.":"No access was granted. You can start a new connection from your assistant."}),(0,t.jsx)($,{variant:"outline",asChild:!0,children:(0,t.jsx)(Ke,{to:"/",children:"Back to Paperclip"})})]})});const P=s?`/mcp-device?user_code=${encodeURIComponent(e)}`:`${n?"/dot-connect":"/mcp-connect"}/${e}`;return(0,t.jsx)("div",{className:"mx-auto max-w-xl py-10",children:(0,t.jsxs)(nn,{className:"block space-y-4 p-6",children:[(0,t.jsxs)("div",{className:"flex items-center gap-3",children:[(0,t.jsx)(kl,{className:"size-8 shrink-0 text-foreground",role:"img","aria-label":"Paperclip"}),(0,t.jsxs)("h1",{className:"min-w-0 break-words text-xl font-semibold",children:["Connect ",(0,t.jsx)("bdi",{children:C})," to Paperclip"]})]}),_&&(0,t.jsx)(zge,{origin:_},_),!s&&w?.redirectOrigin&&w.redirectOrigin!==_&&(0,t.jsx)(zge,{origin:w.redirectOrigin},w.redirectOrigin),s&&(0,t.jsxs)("p",{className:"text-sm",children:["Confirm this matches the code shown by your assistant: ",(0,t.jsx)("strong",{className:"font-mono",children:e.toUpperCase()})]}),k.isPending&&(0,t.jsx)("p",{className:"text-sm text-muted-foreground",children:"Loading connection request…"}),k.error&&(0,t.jsxs)("p",{className:"text-sm text-destructive",children:[k.error.message," Start a new connection from your assistant."]}),s&&k.error&&(0,t.jsx)($,{variant:"outline",onClick:a,children:"Enter a different code"}),w?.agentConnection&&!s&&(0,t.jsxs)("form",{className:"space-y-3",onSubmit:r(Q=>{Q.preventDefault(),O.mutate()},"onSubmit"),children:[(0,t.jsx)("p",{className:"text-sm",children:"Enter the one-use code from your Dot setup prompt to review this agent’s access. Access is granted when you click “Connect Dot with pairing code”."}),(0,t.jsx)("label",{htmlFor:"dot-pairing-code",className:"text-sm",children:"Pairing code"}),(0,t.jsx)(dt,{id:"dot-pairing-code",type:"password",autoComplete:"off",value:c,onChange:r(Q=>{h(null),f(""),d(Q.target.value)},"onChange"),required:!0,maxLength:32}),u&&(0,t.jsxs)("dl",{className:"space-y-2 rounded-md border border-border p-3 text-sm",children:[(0,t.jsxs)("div",{children:[(0,t.jsx)("dt",{className:"text-muted-foreground",children:"Company"}),(0,t.jsxs)("dd",{children:[u.company.name," ",(0,t.jsxs)("span",{className:"text-xs text-muted-foreground",children:["(",u.company.id,")"]})]})]}),(0,t.jsxs)("div",{children:[(0,t.jsx)("dt",{className:"text-muted-foreground",children:"Agent"}),(0,t.jsxs)("dd",{children:[u.agent.name," ",(0,t.jsxs)("span",{className:"text-xs text-muted-foreground",children:["(",u.agent.id,")"]})]})]}),(0,t.jsxs)("div",{children:[(0,t.jsx)("dt",{className:"text-muted-foreground",children:"Permissions"}),(0,t.jsx)("dd",{children:u.permissions})]}),(0,t.jsxs)("div",{children:[(0,t.jsx)("dt",{className:"text-muted-foreground",children:"Access duration"}),(0,t.jsx)("dd",{children:u.accessDuration})]})]}),p&&(0,t.jsx)("p",{role:"alert",className:"text-sm text-destructive",children:p}),O.error&&(0,t.jsx)("p",{role:"alert",className:"text-sm text-destructive",children:O.error.message}),(0,t.jsx)("div",{className:"flex justify-end",children:(0,t.jsx)($,{type:"submit",disabled:!u||!/^[A-Za-z0-9_-]{32}$/.test(c.trim())||O.isPending,children:O.isPending?"Connecting…":"Connect Dot with pairing code"})})]}),w&&(0,t.jsx)(t.Fragment,{children:w.requiresSignIn?(0,t.jsx)($,{asChild:!0,children:(0,t.jsx)(Ke,{to:`/auth?next=${encodeURIComponent(P)}`,children:"Sign in / Create account"})}):(0,t.jsxs)(t.Fragment,{children:[w.requestedCompanyId?(0,t.jsxs)("div",{className:"flex items-center gap-4 rounded-md border border-border p-4",children:[R&&(0,t.jsx)(tg,{companyName:R.name,logoUrl:R.logoUrl,className:"size-14 shrink-0 rounded-lg text-xl"}),(0,t.jsxs)("div",{className:"min-w-0 space-y-1",children:[(0,t.jsx)("p",{className:"text-xs text-muted-foreground",children:"Organization"}),R?(0,t.jsx)("p",{className:"break-words text-lg font-semibold",children:R.name}):(0,t.jsx)("p",{className:"text-sm text-destructive",children:"The selected organization is no longer available to this account. Cancel and reconnect from your assistant to choose an organization you can access."})]})]}):(0,t.jsxs)("fieldset",{className:"space-y-2",disabled:L.isPending,children:[(0,t.jsx)("legend",{className:"mb-2 text-sm font-medium",children:"Organization"}),w.companies.map(Q=>(0,t.jsxs)("label",{className:"flex items-center gap-3 rounded-md border border-border p-3 text-sm",children:[(0,t.jsx)("input",{type:"radio",name:"company","aria-label":Q.name,value:Q.id,checked:N===Q.id,onChange:r(()=>l(Q.id),"onChange")}),(0,t.jsx)(tg,{companyName:Q.name,logoUrl:Q.logoUrl,className:"size-12 shrink-0 rounded-lg"}),(0,t.jsx)("span",{className:"min-w-0 break-words font-medium",children:Q.name})]},Q.id)),!w.companies.length&&(0,t.jsx)("p",{className:"text-sm text-muted-foreground",children:"This account has no available organizations. Ask an organization owner to add you, then reconnect from your assistant."})]}),(0,t.jsx)("p",{className:"text-sm",children:w.agentConnection?"Connect Dot as a Paperclip agent. Pair it with an agent after connecting; assigned work uses that agent’s permissions.":"Read all of your Paperclip data"}),(w.requestedWrite||w.requestedConfigure)&&!w.agentConnection&&(0,t.jsxs)("label",{htmlFor:"mcp-allow-writes",className:"flex items-start gap-3 text-sm leading-6",children:[(0,t.jsx)("span",{className:"flex h-6 shrink-0 items-center",children:(0,t.jsx)(ri,{id:"mcp-allow-writes",checked:I,disabled:!R?.canWrite||L.isPending,onCheckedChange:r(Q=>g(Q===!0),"onCheckedChange")})}),(0,t.jsx)("span",{children:"Write all of your Paperclip data"})]}),R&&!R.canWrite&&(0,t.jsx)("p",{className:"text-sm text-muted-foreground",children:"Your role in this organization is read-only."}),L.error&&(0,t.jsx)("p",{className:"text-sm text-destructive",children:L.error.message}),(0,t.jsxs)("div",{className:"flex items-center justify-between gap-3",children:[(0,t.jsx)($,{variant:"outline",disabled:L.isPending,onClick:r(()=>L.mutate("deny"),"onClick"),children:"Cancel"}),(0,t.jsx)($,{className:"h-auto min-h-10 min-w-0 shrink whitespace-normal",disabled:!R||w.agentConnection&&!R.canWrite||L.isPending,onClick:r(()=>L.mutate("approve"),"onClick"),children:L.isPending?"Connecting…":w.agentConnection?"Connect Dot agent":"Connect organization"})]})]})})]})})}r(xDe,"McpConnectRequest");function sgs(){const e=kt(),s=te({queryKey:["mcp-connections"],queryFn:r(()=>we.get("/mcp/connections"),"queryFn"),retry:!1}),n=s.data?.filter(i=>!i.revokedAt),a=je({mutationFn:r(i=>we.delete(`/mcp/connections/${i}`),"mutationFn"),onSuccess:r((i,o)=>(e.setQueryData(["mcp-connections"],l=>l?.filter(c=>c.id!==o)),e.invalidateQueries({queryKey:["mcp-connections"]})),"onSuccess")});return(0,t.jsxs)("div",{className:"mx-auto max-w-xl space-y-4 py-10",children:[(0,t.jsx)("h1",{className:"text-xl font-semibold",children:"Assistant connections"}),(0,t.jsx)("p",{className:"text-sm text-muted-foreground",children:"Revoking a connection stops its future tool calls. Work already delegated continues under your organization’s normal controls."}),s.isPending&&(0,t.jsx)("p",{className:"text-sm",children:"Loading connections…"}),(s.error||a.error)&&(0,t.jsx)("p",{className:"text-sm text-destructive",children:(s.error??a.error)?.message}),n?.length===0&&(0,t.jsx)("p",{className:"text-sm",children:"No assistant connections."}),n?.map(i=>(0,t.jsxs)(nn,{className:"block space-y-2 p-4",children:[(0,t.jsx)("h2",{className:"font-medium",children:(0,t.jsx)(So,{name:r8(i),avatarUrl:i.user?.image,initials:uv(i.user?.name??"You")})}),(0,t.jsxs)("p",{className:"text-sm text-muted-foreground",children:["Organization: ",i.companyName]}),(0,t.jsx)("p",{className:"text-sm",children:i.scopes.includes("paperclip:agent")?"Dot agent connection":i.scopes.includes("paperclip:write")?"Read and edit work":"Read only"}),i.scopes.includes("paperclip:configure")&&(0,t.jsx)("p",{className:"text-sm",children:"Configure agents, projects and skills"}),(0,t.jsx)($,{variant:"outline",disabled:a.isPending,onClick:r(()=>a.mutate(i.id),"onClick"),children:"Revoke connection"})]},i.id)),(0,t.jsx)(Ke,{className:"text-sm underline",to:"/",children:"Back to Paperclip"})]})}r(sgs,"AssistantConnectionsPage");function ngs(){const e=kt(),s=ga(),[n]=hi(),a=(s.id??"").trim(),i=(n.get("token")??"").trim(),o=(0,m.useMemo)(()=>`/cli-auth/${encodeURIComponent(a)}${i?`?token=${encodeURIComponent(i)}`:""}`,[a,i]),l=te({queryKey:M.auth.session,queryFn:r(()=>Ma.getSession(),"queryFn"),retry:!1}),c=te({queryKey:["cli-auth-challenge",a,i],queryFn:r(()=>ir.getCliAuthChallenge(a,i),"queryFn"),enabled:a.length>0&&i.length>0,retry:!1}),d=je({mutationFn:r(()=>ir.approveCliAuthChallenge(a,i),"mutationFn"),onSuccess:r(async()=>{await e.invalidateQueries({queryKey:M.auth.session}),await c.refetch()},"onSuccess")}),u=je({mutationFn:r(()=>ir.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)(nn,{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)(nn,{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)(nn,{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)(nn,{className:"block p-6",children:[(0,t.jsx)("h1",{className:"text-xl font-semibold",children:"Sign in required"}),(0,t.jsx)("p",{className:"mt-2 text-sm text-muted-foreground",children:"Sign in or create an account, then return to this page to approve the CLI access request."}),(0,t.jsx)($,{asChild:!0,className:"mt-4",children:(0,t.jsx)(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)(nn,{className:"block p-6",children:[(0,t.jsx)("h1",{className:"text-xl font-semibold",children:"Approve Paperclip CLI access"}),(0,t.jsx)("p",{className:"mt-2 text-sm text-muted-foreground",children:"A local Paperclip CLI process is requesting board access to this instance."}),(0,t.jsxs)("div",{className:"mt-5 space-y-3 text-sm",children:[(0,t.jsxs)("div",{children:[(0,t.jsx)("div",{className:"text-muted-foreground",children:"Command"}),(0,t.jsx)("div",{className:"font-mono text-foreground",children:h.command})]}),(0,t.jsxs)("div",{children:[(0,t.jsx)("div",{className:"text-muted-foreground",children:"Client"}),(0,t.jsx)("div",{className:"text-foreground",children:h.clientName??"paperclip-pro cli"})]}),(0,t.jsxs)("div",{children:[(0,t.jsx)("div",{className:"text-muted-foreground",children:"Requested access"}),(0,t.jsx)("div",{className:"text-foreground",children:h.requestedAccess==="instance_admin_required"?"Instance admin":"Board"})]}),h.requestedCompanyName&&(0,t.jsxs)("div",{children:[(0,t.jsx)("div",{className:"text-muted-foreground",children:"Requested organization"}),(0,t.jsx)("div",{className:"text-foreground",children:h.requestedCompanyName})]})]}),(d.error||u.error)&&(0,t.jsx)("p",{className:"mt-4 text-sm text-destructive",children:(d.error??u.error)instanceof Error?(d.error??u.error).message:"Failed to update CLI auth challenge"}),!h.canApprove&&(0,t.jsx)("p",{className:"mt-4 text-sm text-destructive",children:"This challenge requires instance-admin access. Sign in with an instance admin account to approve it."}),(0,t.jsxs)("div",{className:"mt-5 flex gap-3",children:[(0,t.jsx)($,{onClick:r(()=>d.mutate(),"onClick"),disabled:!h.canApprove||d.isPending||u.isPending,children:d.isPending?"Approving...":"Approve CLI access"}),(0,t.jsx)($,{type:"button",variant:"outline",onClick:r(()=>u.mutate(),"onClick"),disabled:d.isPending||u.isPending,children:u.isPending?"Cancelling...":"Cancel"})]})]})}):(0,t.jsx)("div",{className:"mx-auto max-w-xl py-10 text-sm text-destructive",children:"CLI auth challenge unavailable."})}r(ngs,"CliAuthPage");var rgs=J$e.filter(e=>e!=="paperclip_runner"),Uge=new Set(["claude_local","codex_local","gemini_local","kimi_local","opencode_local","pi_local","cursor"]);function ags(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(ags,"readNestedString");var M1="w-full border border-zinc-800 bg-zinc-950 px-3 py-2 text-sm text-zinc-100 outline-none focus:border-zinc-500",Kge="border border-zinc-800 bg-zinc-950/95 p-6",Qge="flex-1 border px-3 py-2 text-sm transition-colors";function igs(e){return e?e.charAt(0).toUpperCase()+e.slice(1):null}r(igs,"formatHumanRole");function gDe(e){if(!e||typeof e!="object")return null;const s=e.code;return typeof s=="string"&&s.trim().length>0?s:null}r(gDe,"getAuthErrorCode");function ogs(e){if(!(e instanceof Error))return null;const s=e.message.trim();return s.length>0?s:null}r(ogs,"getAuthErrorMessage");function lgs(e,s,n){const a=gDe(e),i=ogs(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(lgs,"mapInviteAuthFeedback");function Wge(e){return!!(e&&typeof e=="object"&&"bootstrapAccepted"in e)}r(Wge,"isBootstrapAcceptancePayload");function cgs(e,s){return!e||typeof e!="object"||s?!1:e.status==="approved"}r(cgs,"isApprovedHumanJoinPayload");function TQ({companyDisplayName:e,companyLogoUrl:s,className:n}){return(0,t.jsx)(tg,{companyName:e,logoUrl:s,logoFit:"contain",className:n})}r(TQ,"InviteCompanyLogo");function Hge({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)(TQ,{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(Hge,"AwaitingJoinApprovalPanel");function dgs(){const e=kt(),s=Yn(),{setSelectedCompanyId:n}=ps(),a=(ga().token??"").trim(),[i,o]=(0,m.useState)("sign_up"),[l,c]=(0,m.useState)(""),[d,u]=(0,m.useState)(""),[h,p]=(0,m.useState)(""),[f,x]=(0,m.useState)(""),[g,v]=(0,m.useState)("claude_local"),[y,k]=(0,m.useState)(""),[w,N]=(0,m.useState)(null),[S,C]=(0,m.useState)(null),[_,R]=(0,m.useState)(null),[I,T]=(0,m.useState)(!1),E="invite-auth-error",L=te({queryKey:M.health,queryFn:r(()=>Iu.get(),"queryFn"),retry:!1}),O=te({queryKey:M.auth.session,queryFn:r(()=>Ma.getSession(),"queryFn"),retry:!1}),P=te({queryKey:M.access.invite(a),queryFn:r(()=>ir.getInvite(a),"queryFn"),enabled:a.length>0,retry:!1}),Q=KQ({enabled:!!O.data&&!!P.data?.companyId,staleTime:0}),D=L.data?.deploymentMode!=="local_trusted"?Q.isFetchedAfterMount:!0,F=D?Q.data?.companies??[]:[];(0,m.useEffect)(()=>{a&&Oge(a)},[a]),(0,m.useEffect)(()=>{T(!1)},[a]),(0,m.useEffect)(()=>{if(!D)return;const ge=Q.data?.companies;!ge||!P.data?.companyId||ge.some(Ee=>Ee.id===P.data.companyId)&&KT(a)},[Q.data,P.data,D,a]);const z=P.data,K=!!O.data&&!!z?.companyId&&!D,U=!!z?.companyId&&F.some(ge=>ge.id===z?.companyId),q=z?.companyName?.trim()||"this Paperclip company",G=z?.companyLogoUrl?.trim()||null,se=z?.invitedByUserName?.trim()||null,Z=z?.inviteMessage?.trim()||null,ie=igs(z?.humanRole),J=z?.joinRequestStatus??null,re=z?.joinRequestType??null,oe=re==="human"&&(J==="pending_approval"||J==="approved"),V=L.data?.deploymentMode==="authenticated"&&!O.data&&z?.allowedJoinTypes!=="agent",X=z?.inviteType!=="bootstrap_ceo"&&z?.allowedJoinTypes==="agent",Y=!!O.data&&!X&&z?.inviteType!=="bootstrap_ceo"&&(!J||oe)&&!K&&!U&&!w&&S===null,ae=O.data?.user.name?.trim()||O.data?.user.email?.trim()||"this account",ne=d.trim().length>0&&h.trim().length>0&&(i==="sign_in"||l.trim().length>0&&h.trim().length>=8),ce=je({mutationFn:r(async()=>{if(!z)throw new Error("Invite not found");if(K)throw new Error("Checking your organization access. Try again in a moment.");if(U)throw new Error("This account already belongs to the organization.");return z.inviteType==="bootstrap_ceo"||z.allowedJoinTypes!=="agent"?ir.acceptInvite(a,{requestType:"human"}):ir.acceptInvite(a,{requestType:"agent",agentName:f.trim(),adapterType:g,capabilities:y.trim()||null})},"mutationFn"),onSuccess:r(async ge=>{C(null),KT(a);const Ee=Wge(ge);N({kind:Ee?"bootstrap":"join",payload:ge}),await e.invalidateQueries({queryKey:M.auth.session}),await e.invalidateQueries({queryKey:M.access.currentBoardAccess}),await e.invalidateQueries({queryKey:M.companies.all}),z?.companyId&&cgs(ge,X)&&(n(z.companyId,{source:"manual"}),s("/",{replace:!0}))},"onSuccess"),onError:r(ge=>{C(ge instanceof Error?ge.message:"Failed to accept invite")},"onError")});(0,m.useEffect)(()=>{!Y||I||ce.isPending||(T(!0),C(null),ce.mutate())},[ce,I,Y]);const he=je({mutationFn:r(async()=>{if(i==="sign_in"){await Ma.signInEmail({email:d.trim(),password:h});return}await Ma.signUpEmail({name:l.trim(),email:d.trim(),password:h})},"mutationFn"),onSuccess:r(async()=>{R(null),Oge(a),await e.invalidateQueries({queryKey:M.auth.session}),await e.invalidateQueries({queryKey:M.health}),await e.invalidateQueries({queryKey:M.access.currentBoardAccess});const{companies:ge}=await $Be(e);if(z?.companyId&&ge.some(Ee=>Ee.id===z.companyId)){KT(a),n(z.companyId,{source:"manual"}),s("/",{replace:!0});return}if(!(!z||z.inviteType!=="bootstrap_ceo"))try{Wge(await ce.mutateAsync())&&s("/",{replace:!0})}catch{return}},"onSuccess"),onError:r(ge=>{const Ee=lgs(ge,i,d);gDe(ge)==="USER_ALREADY_EXISTS_USE_ANOTHER_EMAIL"&&(o("sign_in"),p("")),R(Ee)},"onError")}),pe=(0,m.useMemo)(()=>z?U?"Open organization":z.inviteType==="bootstrap_ceo"?"Accept invite":X?"Submit request":O.data?"Accept invite":"Continue":"Continue",[z,U,O.data,X]);if(!a)return(0,t.jsx)("div",{className:"mx-auto max-w-xl py-10 text-sm text-destructive",children:"Invalid invite token."});if(P.isLoading||L.isLoading||O.isLoading)return(0,t.jsx)("div",{className:"mx-auto max-w-xl py-10 text-sm text-muted-foreground",children:"Loading invite..."});if(K)return(0,t.jsx)("div",{className:"mx-auto max-w-xl py-10 text-sm text-muted-foreground",children:"Checking your access..."});if(P.error||!z)return(0,t.jsx)("div",{className:"mx-auto max-w-xl py-10",children:(0,t.jsxs)("div",{className:"border border-border bg-card p-6","data-testid":"invite-error",children:[(0,t.jsx)("h1",{className:"text-lg font-semibold",children:"Invite not available"}),(0,t.jsx)("p",{className:"mt-2 text-sm text-muted-foreground",children:"This invite may be expired, revoked, or already used."})]})});if(J==="approved"&&re==="human"&&U)return(0,t.jsx)("div",{className:"mx-auto max-w-xl py-10 text-sm text-muted-foreground",children:"Opening organization..."});if(J==="pending_approval"&&!oe)return(0,t.jsx)(Hge,{companyDisplayName:q,companyLogoUrl:G,invitedByUserName:se});if(J&&!oe)return(0,t.jsx)("div",{className:"mx-auto max-w-xl py-10",children:(0,t.jsxs)("div",{className:"border border-border bg-card p-6","data-testid":"invite-error",children:[(0,t.jsx)("h1",{className:"text-lg font-semibold",children:"Invite not available"}),(0,t.jsx)("p",{className:"mt-2 text-sm text-muted-foreground",children:J==="rejected"?"This join request was not approved.":"This invite has already been used."})]})});if(w?.kind==="bootstrap")return(0,t.jsx)("div",{className:"min-h-screen bg-zinc-950 px-6 py-12 text-zinc-100",children:(0,t.jsxs)("div",{className:"mx-auto max-w-md border border-zinc-800 bg-zinc-950 p-6",children:[(0,t.jsx)("h1",{className:"text-lg font-semibold",children:"Bootstrap complete"}),(0,t.jsx)("div",{className:"mt-4",children:(0,t.jsx)($,{asChild:!0,className:"rounded-none",children:(0,t.jsx)(Ke,{to:"/",children:"Open board"})})})]})});if(w?.kind==="join"){const ge=w.payload,Ee=typeof ge.claimSecret=="string"?ge.claimSecret:null,de=typeof ge.claimApiKeyPath=="string"?ge.claimApiKeyPath:null,Ne=ags(ge.onboarding,["textInstructions","url"]);return!X&&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)(TQ,{companyDisplayName:q,companyLogoUrl:G,className:"h-12 w-12 border border-zinc-800 rounded-none"}),(0,t.jsx)("h1",{className:"text-lg font-semibold",children:"You joined the organization"})]}),(0,t.jsx)("div",{className:"mt-4",children:(0,t.jsx)($,{asChild:!0,className:"w-full rounded-none",children:(0,t.jsx)(Ke,{to:"/",children:"Open board"})})})]})}):(0,t.jsx)(Hge,{companyDisplayName:q,companyLogoUrl:G,invitedByUserName:se,claimSecret:Ee,claimApiKeyPath:de,onboardingTextUrl:Ne})}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:`${Kge} space-y-6`,children:[(0,t.jsxs)("div",{className:"flex items-start gap-4",children:[(0,t.jsx)(TQ,{companyDisplayName:q,companyLogoUrl:G,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:z.inviteType==="bootstrap_ceo"?"Set up Paperclip":`Join ${q}`}),(0,t.jsx)("p",{className:"mt-2 max-w-2xl text-sm leading-6 text-zinc-300",children:X?"Review the invite details, then submit the agent information below to start the join request.":V?"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:q})]}),(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:X?"Agent join request":ie??"Organization access"})]}),(0,t.jsxs)("div",{className:"border border-zinc-800 p-3",children:[(0,t.jsx)("div",{className:"text-xs uppercase tracking-(--tracking-caps) text-zinc-500",children:"Invite expires"}),(0,t.jsx)("div",{className:"mt-1 text-sm text-zinc-100",children:Gd(z.expiresAt)})]})]}),Z?(0,t.jsxs)("div",{className:"border border-amber-500/40 bg-amber-500/10 p-4",children:[(0,t.jsx)("div",{className:"text-xs uppercase tracking-(--tracking-caps) text-amber-200/80",children:"Message from inviter"}),(0,t.jsx)("p",{className:"mt-2 text-sm leading-6 text-amber-50",children:Z})]}):null,O.data?(0,t.jsxs)("div",{className:"border border-emerald-500/40 bg-emerald-500/10 p-4 text-sm text-emerald-50",children:["Signed in as ",(0,t.jsx)("span",{className:"font-medium",children:ae}),"."]}):null]}),(0,t.jsx)("section",{className:`${Kge} h-fit`,children:X?(0,t.jsxs)("div",{className:"space-y-4",children:[(0,t.jsxs)("div",{children:[(0,t.jsx)("h2",{className:"text-lg font-semibold",children:"Submit agent details"}),(0,t.jsxs)("p",{className:"mt-1 text-sm text-zinc-400",children:["This invite will create an approval request for a new agent in ",q,"."]})]}),(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:M1,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:M1,value:g,onChange:r(ge=>v(ge.target.value),"onChange"),children:rgs.map(ge=>(0,t.jsxs)("option",{value:ge,disabled:!Uge.has(ge),children:[wf(ge),Uge.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:M1,rows:4,value:y,onChange:r(ge=>k(ge.target.value),"onChange")})]}),S?(0,t.jsx)("p",{className:"text-xs text-red-400",children:S}):null,(0,t.jsx)($,{className:"w-full rounded-none",disabled:ce.isPending||f.trim().length===0,onClick:r(()=>ce.mutate(),"onClick"),children:ce.isPending?"Working...":pe})]}):V?(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 ${q}.`:"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:`${Qge} ${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:`${Qge} ${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(!ne){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:M1,value:l,onChange:r(ge=>{c(ge.target.value),R(null)},"onChange"),autoComplete:"name",required:!0,"aria-required":"true","aria-invalid":_?.tone==="error"?!0:void 0,"aria-describedby":_?E:void 0,autoFocus:!0})]}):null,(0,t.jsxs)("label",{className:"block text-sm",htmlFor:"invite-email",children:[(0,t.jsx)("span",{className:"mb-1 block text-zinc-400",children:"Email"}),(0,t.jsx)("input",{id:"invite-email",name:"email",type:"email",className:M1,value:d,onChange:r(ge=>{u(ge.target.value),R(null)},"onChange"),autoComplete:"username",required:!0,"aria-required":"true","aria-invalid":_?.tone==="error"?!0:void 0,"aria-describedby":_?E:void 0,autoFocus:i==="sign_in"})]}),(0,t.jsxs)("label",{className:"block text-sm",htmlFor:"invite-password",children:[(0,t.jsx)("span",{className:"mb-1 block text-zinc-400",children:"Password"}),(0,t.jsx)("input",{id:"invite-password",name:"password",type:"password",className:M1,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":_?.tone==="error"?!0:void 0,"aria-describedby":_?E:void 0})]}),_?(0,t.jsx)("p",{id:E,role:"alert",className:`text-xs ${_.tone==="info"?"text-amber-300":"text-red-400"}`,children:_.message}):null,(0,t.jsx)($,{type:"submit",className:"w-full rounded-none",disabled:he.isPending,"aria-disabled":!ne||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:U?"Already in this organization":Y?"Completing organization access":z.inviteType==="bootstrap_ceo"?"Accept bootstrap invite":"Accept organization invite"}),(0,t.jsx)("p",{className:"mt-1 text-sm text-zinc-400",children:Y?`Granting your access to ${q}.`:U?`This account already belongs to ${q}.`:`This will ${z.inviteType==="bootstrap_ceo"?"finish setting up Paperclip":`grant or complete your access to ${q}`}.`})]}),S?(0,t.jsx)("p",{className:"text-xs text-red-400",children:S}):null,Y?(0,t.jsx)("div",{className:"text-sm text-zinc-400",children:ce.isPending?"Submitting request...":"Finishing sign-in..."}):(0,t.jsx)($,{className:"w-full rounded-none",disabled:ce.isPending,onClick:r(()=>{if(U&&z.companyId){KT(a),n(z.companyId,{source:"manual"}),s("/",{replace:!0});return}ce.mutate()},"onClick"),children:ce.isPending?"Working...":pe})]})})]})})})}r(dgs,"InviteLandingPage");var ugs=15e3,mgs={parent:"Parent task",child:"Sub-task",blocked_by:"Blocked by",blocks:"Blocks"};function hgs(){(0,m.useEffect)(()=>{const e=document.createElement("meta");return e.name="robots",e.content="noindex",document.head.appendChild(e),()=>e.remove()},[])}r(hgs,"useNoIndexMeta");function RQ(e,s){const n=`/s/${encodeURIComponent(e)}`;return s?`${n}/issues/${encodeURIComponent(s)}`:n}r(RQ,"sharePath");var pgs=/^(?:https?:\/\/[^/]+)?\/api\/attachments\/([^/?#]+)\/content(?:[?#].*)?$/i;function fgs(e,s){const n=pgs.exec(s.trim());return n?`/api/public/share/${encodeURIComponent(e)}/attachments/${n[1]}/content`:null}r(fgs,"publicShareImageSrc");function yC({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(yC,"Section");function EQ({actor:e}){return(0,t.jsx)(So,{name:e.name,avatarUrl:e.iconUrl,size:"sm"})}r(EQ,"ActorIdentity");function LQ({value:e}){return(0,t.jsx)("time",{dateTime:e,title:yr(e),className:"text-xs text-muted-foreground",children:xr(e)})}r(LQ,"Timestamp");function xgs({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(xgs,"ActiveRunPill");function bDe({attachments:e}){return(0,t.jsx)(jH,{children:e.map(s=>{const n=dSe({name:s.filename,url:s.url,contentType:s.contentType,byteSize:s.byteSize}),a=n.icon,i=wH(s.byteSize);return(0,t.jsxs)(xH,{size:"sm",children:[(0,t.jsx)(gH,{children:(0,t.jsx)(a,{"aria-hidden":!0})}),(0,t.jsxs)(bH,{children:[(0,t.jsx)(vH,{className:"max-w-48",children:s.filename}),(0,t.jsx)(yH,{className:"max-w-48",children:i?`${n.label} · ${i}`:n.label})]}),(0,t.jsx)(iSe,{"aria-label":`Download ${s.filename}`,render:(0,t.jsx)("a",{href:s.url,download:s.filename,rel:"noreferrer"})})]},s.id)})})}r(bDe,"AttachmentList");function ggs({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)(ao,{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:mgs[e.relation]}),e.navigable?(0,t.jsx)(Md,{to:n?RQ(s,e.id):RQ(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(ggs,"RelatedIssueRow");function bgs({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)(EQ,{actor:e.author}),(0,t.jsx)(LQ,{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)(EQ,{actor:e.author}),(0,t.jsx)(LQ,{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)(bDe,{attachments:e.attachments}):null]})}r(bgs,"TimelineEntry");function vgs({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)(ei,{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)(LQ,{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)(Ui,{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(vgs,"DocumentCard");function ygs({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)(Dn,{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)(Ui,{className:"h-3.5 w-3.5","aria-hidden":!0}),"Download"]}):null]})}r(ygs,"WorkProductRow");function Vge({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(Vge,"CenteredNotice");function jgs({view:e,token:s}){const{company:n,issue:a}=e,i=(0,m.useCallback)(o=>fgs(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)(tg,{companyName:n.name,logoUrl:n.logoUrl,logoFit:"contain",className:"h-8 w-8 shrink-0 rounded-md"}),(0,t.jsx)("span",{className:"min-w-0 truncate text-sm font-medium",children:n.name}),(0,t.jsx)("span",{className:"ml-auto shrink-0 text-xs text-muted-foreground",children:"Read-only view"})]})}),(0,t.jsxs)("main",{className:"mx-auto max-w-3xl space-y-8 px-4 py-5",children:[e.isSharedRoot?null:(0,t.jsxs)(Md,{to:RQ(s),className:"inline-flex items-center gap-1.5 text-sm text-muted-foreground hover:text-foreground",children:[(0,t.jsx)(wl,{className:"h-4 w-4","aria-hidden":!0}),"Back to main task"]}),(0,t.jsxs)("section",{className:"space-y-3",children:[(0,t.jsxs)("div",{className:"flex flex-wrap items-center gap-x-2 text-xs text-muted-foreground",children:[a.identifier?(0,t.jsx)("span",{children:a.identifier}):null,a.projectName?(0,t.jsx)("span",{children:a.projectName}):null]}),(0,t.jsx)("h1",{className:"break-words text-xl font-semibold",children:a.title}),(0,t.jsxs)("div",{className:"flex flex-wrap items-center gap-3",children:[(0,t.jsx)(C0,{status:a.status}),(0,t.jsx)(Tve,{priority:a.priority,showLabel:!0}),a.assignee?(0,t.jsx)(EQ,{actor:a.assignee}):null,e.activeRun?(0,t.jsx)(xgs,{agentName:e.activeRun.agentName}):null]}),(0,t.jsxs)("p",{className:"text-xs text-muted-foreground",children:["Created ",yr(a.createdAt)," · Updated ",xr(a.updatedAt),a.completedAt?` · Completed ${yr(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)(yC,{title:"Related tasks",children:(0,t.jsx)("ul",{className:"space-y-2",children:e.related.map(o=>(0,t.jsx)(ggs,{related:o,token:s,isSharedRoot:e.isSharedRoot},`${o.relation}:${o.id}`))})}):null,e.documents.length>0?(0,t.jsx)(yC,{title:"Documents",children:(0,t.jsx)("div",{className:"space-y-2",children:e.documents.map(o=>(0,t.jsx)(vgs,{document:o,resolveImageSrc:i},o.key))})}):null,e.attachments.length>0?(0,t.jsx)(yC,{title:"Attachments",children:(0,t.jsx)(bDe,{attachments:e.attachments})}):null,e.workProducts.length>0?(0,t.jsx)(yC,{title:"Work products",children:(0,t.jsx)("ul",{className:"space-y-2",children:e.workProducts.map(o=>(0,t.jsx)(ygs,{product:o},o.id))})}):null,(0,t.jsx)(yC,{title:"Activity",children:e.comments.length>0?(0,t.jsx)("ol",{className:"space-y-3",children:e.comments.map(o=>(0,t.jsx)(bgs,{comment:o,resolveImageSrc:i},o.id))}):(0,t.jsx)("p",{className:"text-sm text-muted-foreground",children:"No updates yet."})})]})]})}r(jgs,"PublicIssueShareContent");function Gge(){const{token:e="",issueId:s}=ga();hgs();const n=WUe.test(e),a=te({queryKey:M.publicShare.view(e,s??null),queryFn:r(()=>s?Yk.getPublicShareIssue(e,s):Yk.getPublicShare(e),"queryFn"),enabled:n,retry:!1,refetchOnWindowFocus:!0,refetchInterval:r(i=>i.state.data?.activeRun?ugs:!1,"refetchInterval")});return!n||a.data===null?(0,t.jsx)(Vge,{title:"This link is not available",body:"It may have been revoked, or the address is incomplete."}):a.data?(0,t.jsx)(jgs,{view:a.data,token:e}):a.isError?(0,t.jsx)(Vge,{title:"Couldn't load this page",body:"Check your connection and try again.",action:(0,t.jsx)($,{variant:"outline",size:"sm",className:"mt-2",onClick:r(()=>{a.refetch()},"onClick"),children:"Try again"})}):(0,t.jsx)("div",{className:"h-dvh overflow-y-auto px-4 py-6","aria-busy":"true",children:(0,t.jsxs)("div",{className:"mx-auto max-w-3xl space-y-4",children:[(0,t.jsx)(wn,{className:"h-6 w-1/2"}),(0,t.jsx)(wn,{className:"h-4 w-1/3"}),(0,t.jsx)(wn,{className:"h-24 w-full"})]})})}r(Gge,"PublicIssueSharePage");function wgs(){const{selectedCompany:e,selectedCompanyId:s}=ps(),{setBreadcrumbs:n}=Wn(),{pushToast:a}=Ii(),i=kt(),[o,l]=(0,m.useState)("pending_approval"),[c,d]=(0,m.useState)("all");(0,m.useEffect)(()=>{n([{label:e?.name??"Organization",href:"/dashboard"},{label:"Inbox",href:"/inbox"},{label:"Join Requests"}])},[e?.name,n]);const u=te({queryKey:M.access.joinRequests(s??"",`${o}:${c}`),queryFn:r(()=>ir.listJoinRequests(s,o,c==="all"?void 0:c),"queryFn"),enabled:!!s}),h=je({mutationFn:r(f=>ir.approveJoinRequest(s,f),"mutationFn"),onSuccess:r(async()=>{await i.invalidateQueries({queryKey:M.access.joinRequests(s,`${o}:${c}`)}),await i.invalidateQueries({queryKey:M.access.companyMembers(s)}),await i.invalidateQueries({queryKey:M.access.companyUserDirectory(s)}),a({title:"Join request approved",tone:"success"})},"onSuccess")}),p=je({mutationFn:r(f=>ir.rejectJoinRequest(s,f),"mutationFn"),onSuccess:r(async()=>{await i.invalidateQueries({queryKey:M.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 sn&&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)(KQe,{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)(nn,{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)(nn,{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)(it,{variant:f.status==="pending_approval"?"secondary":f.status==="approved"?"outline":"destructive",children:f.status.replace("_"," ")}),(0,t.jsx)(it,{variant:"outline",children:f.requestType}),f.adapterType?(0,t.jsx)(it,{variant:"outline",children:f.adapterType}):null]}),(0,t.jsxs)("div",{children:[(0,t.jsx)("div",{className:"text-base font-medium",children:f.requestType==="human"?f.requesterUser?.name||f.requestEmailSnapshot||f.requestingUserId||"Unknown human requester":f.agentName||"Unknown agent requester"}),(0,t.jsx)("div",{className:"text-sm text-muted-foreground",children:f.requestType==="human"?f.requesterUser?.email||f.requestEmailSnapshot||f.requestingUserId:f.capabilities||f.requestIp})]})]}),f.status==="pending_approval"?(0,t.jsxs)("div",{className:"flex gap-2",children:[(0,t.jsx)($,{variant:"outline",onClick:r(()=>p.mutate(f.id),"onClick"),disabled:p.isPending,children:"Reject"}),(0,t.jsx)($,{onClick:r(()=>h.mutate(f.id),"onClick"),disabled:h.isPending,children:"Approve"})]}):null]}),(0,t.jsxs)("div",{className:"mt-4 grid gap-3 text-sm text-muted-foreground md:grid-cols-2",children:[(0,t.jsxs)("div",{className:"rounded-lg border border-border bg-background px-3 py-2",children:[(0,t.jsx)("div",{className:"text-xs font-medium uppercase tracking-wide",children:"Invite context"}),(0,t.jsx)("div",{className:"mt-2",children:f.invite?`${f.invite.allowedJoinTypes} join invite${f.invite.humanRole?` • default role ${f.invite.humanRole}`:""}`:"Invite metadata unavailable"}),f.invite?.inviteMessage?(0,t.jsx)("div",{className:"mt-2 text-foreground",children:f.invite.inviteMessage}):null]}),(0,t.jsxs)("div",{className:"rounded-lg border border-border bg-background px-3 py-2",children:[(0,t.jsx)("div",{className:"text-xs font-medium uppercase tracking-wide",children:"Request details"}),(0,t.jsxs)("div",{className:"mt-2",children:["Submitted ",new Date(f.createdAt).toLocaleString()]}),(0,t.jsxs)("div",{children:["Source IP ",f.requestIp]}),f.requestType==="agent"&&f.capabilities?(0,t.jsx)("div",{children:f.capabilities}):null]})]})]},f.id))})]})}r(wgs,"JoinRequestQueue");var kgs=(0,m.lazy)(()=>fd(()=>import("./CompanyExport-Bir35u83.js").then(e=>({default:e.CompanyExport})),__vite__mapDeps([6,5,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25]))),Ngs=(0,m.lazy)(()=>fd(()=>import("./Agents.production-BJetnIZc.js").then(e=>({default:e.Agents})),__vite__mapDeps([26,5,7,9,8,27,28,29,30,31,15,32,33,34,35,36,19,37,23,24,25]))),Sgs=(0,m.lazy)(()=>fd(()=>import("./Routines.production-BMVUHtz-.js").then(e=>({default:e.Routines})),__vite__mapDeps([38,5,7,8,9,39,28,40,33,16,17,21,41,14,15,27,29,30,31,42,43,44,45,46,10,11,12,34,47,48,49,35,50,51,20,36,52,53,54,37,55,23,24,25,32,22,19]))),Yge=(0,m.lazy)(()=>fd(()=>import("./RoutineDetail.production-KK-EpmNd.js").then(e=>({default:e.RoutineDetail})),__vite__mapDeps([56,5,7,8,9,39,28,40,33,16,17,21,41,14,15,27,29,30,31,42,43,44,45,46,10,11,12,34,47,48,49,35,50,51,20,36,52,53,54,37,55,23,24,25,57,58,22,19]))),Cgs=(0,m.lazy)(()=>fd(()=>import("./CompanySkills.production-D_mQ9MQl.js").then(e=>({default:e.CompanySkills})),__vite__mapDeps([59,5,7,8,9,27,28,29,30,31,15,42,16,40,33,17,21,44,14,45,46,32,10,11,12,60,58,52,25,48,18,13,19,61,49,22,23,24]))),_gs=(0,m.lazy)(()=>fd(()=>import("./CompanyActivity.production-DiqCOCXP.js").then(e=>({default:e.CompanyActivity})),__vite__mapDeps([62,5,7,8,9,31,15,32,33,47,45,30,16,48,22,19,52,53,54,55,23]))),Ags=(0,m.lazy)(()=>fd(()=>import("./Terminal-mFtKN-ON.js").then(e=>({default:e.Terminal})),__vite__mapDeps([63,5,7,8,9,40,33,28,16,17,21,43,52,53,37]))),Igs=(0,m.lazy)(()=>fd(()=>import("./OrgChart.production-Cfzs62Ia.js").then(e=>({default:e.OrgChart})),__vite__mapDeps([64,5,7,8,9,31,15,50,51,19,55,23,24,25])));function sb({children:e}){return(0,t.jsx)(m.Suspense,{fallback:(0,t.jsx)(nh,{}),children:e})}r(sb,"ProductionSurface");function Tgs(e,s){const n=e&&s;return(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)(nt,{index:!0,element:(0,t.jsx)(_n,{to:"dashboard",replace:!0})}),(0,t.jsx)(nt,{path:"dashboard",element:(0,t.jsx)(NTt,{})}),(0,t.jsx)(nt,{path:"dashboard/live",element:(0,t.jsx)(STt,{})}),(0,t.jsx)(nt,{path:"timeline",element:e?(0,t.jsx)(Cp,{to:"/activity/timeline"}):(0,t.jsx)(s6e,{})}),(0,t.jsx)(nt,{path:"onboarding",element:(0,t.jsx)(jDe,{})}),(0,t.jsx)(nt,{path:"companies",element:(0,t.jsx)(uRt,{})}),(0,t.jsx)(nt,{path:"company/settings",element:(0,t.jsx)(prs,{})}),(0,t.jsx)(nt,{path:"company/settings/connections",element:(0,t.jsx)(grs,{})}),(0,t.jsx)(nt,{path:"company/settings/environments",element:(0,t.jsx)(_n,{to:"/company/settings/instance/environments",replace:!0})}),(0,t.jsx)(nt,{path:"company/settings/cloud-upstream",element:(0,t.jsx)(_n,{to:"/company/export",replace:!0})}),(0,t.jsxs)(nt,{element:(0,t.jsx)(b0,{pageKey:"company.members"}),children:[(0,t.jsx)(nt,{path:"company/settings/members",element:(0,t.jsx)(ias,{})}),(0,t.jsx)(nt,{path:"company/settings/access",element:(0,t.jsx)(oas,{})})]}),(0,t.jsx)(nt,{element:(0,t.jsx)(b0,{pageKey:"company.invites"}),children:(0,t.jsx)(nt,{path:"company/settings/invites",element:(0,t.jsx)(_n,{to:"/company/settings/members?tab=invites",replace:!0})})}),(0,t.jsx)(nt,{element:(0,t.jsx)(b0,{pageKey:"company.export"}),children:(0,t.jsx)(nt,{path:"company/export/*",element:(0,t.jsx)(m.Suspense,{fallback:(0,t.jsx)(nh,{}),children:(0,t.jsx)(kgs,{})})})}),(0,t.jsx)(nt,{element:(0,t.jsx)(pyt,{}),children:(0,t.jsx)(nt,{element:(0,t.jsx)(b0,{pageKey:"company.import"}),children:(0,t.jsx)(nt,{path:"company/import",element:(0,t.jsx)(vfs,{})})})}),(0,t.jsx)(nt,{element:(0,t.jsx)(b0,{pageKey:"company.secrets"}),children:(0,t.jsx)(nt,{path:"company/settings/secrets",element:(0,t.jsx)(pps,{})})}),(0,t.jsx)(nt,{path:"company/settings/tools",element:(0,t.jsx)(Xge,{})}),(0,t.jsx)(nt,{path:"company/settings/tools/:tab",element:(0,t.jsx)(Xge,{})}),(0,t.jsx)(nt,{path:"tools",element:(0,t.jsx)(ebe,{})}),(0,t.jsx)(nt,{path:"tools/:tab",element:(0,t.jsx)(ebe,{})}),(0,t.jsx)(nt,{path:"apps",element:(0,t.jsx)(sos,{})}),(0,t.jsx)(nt,{path:"apps/assistant-connection",element:(0,t.jsx)(Ois,{})}),(0,t.jsx)(nt,{path:"apps/browse",element:(0,t.jsx)(_n,{to:"/apps",replace:!0})}),(0,t.jsx)(nt,{path:"apps/connections",element:(0,t.jsx)(_n,{to:"/apps",replace:!0})}),(0,t.jsx)(nt,{path:"apps/byo",element:(0,t.jsx)(q7e,{byoOnly:!0})}),(0,t.jsx)(nt,{path:"apps/vercel-connect",element:(0,t.jsx)(Zge,{credentialSource:"vercel_connect"})}),(0,t.jsx)(nt,{path:"apps/connect",element:(0,t.jsx)(Zge,{})}),(0,t.jsx)(nt,{path:"apps/chat/connect",element:(0,t.jsx)(AT,{children:(0,t.jsx)(jls,{})})}),(0,t.jsx)(nt,{path:"apps/chat/:endpointId",element:(0,t.jsx)(AT,{children:(0,t.jsx)(_n,{to:"settings",replace:!0})})}),(0,t.jsx)(nt,{path:"apps/chat/:endpointId/reviews/:reviewId",element:(0,t.jsx)(AT,{children:(0,t.jsx)(Hfe,{})})}),(0,t.jsx)(nt,{path:"apps/chat/:endpointId/:tab",element:(0,t.jsx)(AT,{children:(0,t.jsx)(Hfe,{})})}),(0,t.jsx)(nt,{path:"apps/connect/:appKey",element:(0,t.jsx)(_n,{to:"/apps",replace:!0})}),(0,t.jsx)(nt,{path:"apps/connect/:appKey/:stage",element:(0,t.jsx)(_n,{to:"/apps",replace:!0})}),(0,t.jsx)(nt,{path:"apps/review",element:(0,t.jsx)(ids,{})}),(0,t.jsx)(nt,{path:"apps/attention",element:(0,t.jsx)(_n,{to:"/apps",replace:!0})}),(0,t.jsx)(nt,{path:"apps/gateways",element:(0,t.jsx)(Jfe,{})}),(0,t.jsx)(nt,{path:"apps/gateways/:gatewayId",element:(0,t.jsx)(_n,{to:"overview",replace:!0})}),(0,t.jsx)(nt,{path:"apps/gateways/:gatewayId/:tab",element:(0,t.jsx)(Dds,{})}),(0,t.jsx)(nt,{path:"apps/advanced",element:(0,t.jsx)(ffe,{})}),(0,t.jsx)(nt,{path:"apps/advanced/gateways",element:(0,t.jsx)(Jfe,{})}),(0,t.jsx)(nt,{path:"apps/advanced/profiles/new",element:(0,t.jsx)(yfe,{mode:"new"})}),(0,t.jsx)(nt,{path:"apps/advanced/profiles/:profileId/edit",element:(0,t.jsx)(yfe,{mode:"edit"})}),(0,t.jsx)(nt,{path:"apps/advanced/profiles/:profileId",element:(0,t.jsx)(Cis,{})}),(0,t.jsx)(nt,{path:"apps/advanced/audit",element:(0,t.jsx)(_n,{to:"/apps",replace:!0})}),(0,t.jsx)(nt,{path:"apps/advanced/run-your-own",element:(0,t.jsx)(_n,{to:"/apps",replace:!0})}),(0,t.jsx)(nt,{path:"apps/advanced/:tab",element:(0,t.jsx)(ffe,{})}),(0,t.jsx)(nt,{path:"apps/app/:applicationId",element:(0,t.jsx)(Gfe,{})}),(0,t.jsx)(nt,{path:"apps/app/:applicationId/:tab",element:(0,t.jsx)(Gfe,{})}),(0,t.jsx)(nt,{path:"apps/:connectionId",element:(0,t.jsx)(_n,{to:"permissions",replace:!0})}),(0,t.jsx)(nt,{path:"apps/:connectionId/:tab",element:(0,t.jsx)(qos,{})}),(0,t.jsx)(nt,{path:"company/settings/instance",element:(0,t.jsx)(_n,{to:"/company/settings",replace:!0})}),(0,t.jsx)(nt,{element:(0,t.jsx)(b0,{pageKey:"instance.profile"}),children:(0,t.jsx)(nt,{path:"company/settings/instance/profile",element:(0,t.jsx)(Cxs,{})})}),(0,t.jsx)(nt,{path:"company/settings/instance/general",element:(0,t.jsx)(_n,{to:"/company/settings",replace:!0})}),(0,t.jsx)(nt,{path:"company/settings/instance/heartbeats",element:(0,t.jsx)(_n,{to:"/company/settings",replace:!0})}),(0,t.jsxs)(nt,{element:(0,t.jsx)(b0,{pageKey:"instance.environments"}),children:[(0,t.jsx)(nt,{path:"company/settings/instance/environments",element:(0,t.jsx)(xB,{})}),(0,t.jsx)(nt,{path:"company/settings/instance/environments/new",element:(0,t.jsx)(xB,{mode:"create"})}),(0,t.jsx)(nt,{path:"company/settings/instance/environments/:environmentId/edit",element:(0,t.jsx)(xB,{mode:"edit"})})]}),(0,t.jsx)(nt,{element:(0,t.jsx)(b0,{pageKey:"instance.access"}),children:(0,t.jsx)(nt,{path:"company/settings/instance/access",element:(0,t.jsx)(bxs,{})})}),(0,t.jsx)(nt,{element:(0,t.jsx)(b0,{pageKey:"instance.experimental"}),children:(0,t.jsx)(nt,{path:"company/settings/instance/experimental",element:(0,t.jsx)(gxs,{})})}),(0,t.jsxs)(nt,{element:(0,t.jsx)(b0,{pageKey:"instance.plugins"}),children:[(0,t.jsx)(nt,{path:"company/settings/instance/plugins",element:(0,t.jsx)(Axs,{})}),(0,t.jsx)(nt,{path:"company/settings/instance/plugins/:pluginId",element:(0,t.jsx)(Ixs,{})})]}),(0,t.jsx)(nt,{element:(0,t.jsx)(b0,{pageKey:"instance.adapters"}),children:(0,t.jsx)(nt,{path:"company/settings/instance/adapters",element:(0,t.jsx)(Mge,{})})}),(0,t.jsx)(nt,{path:"company/settings/:settingsRoutePath/*",element:(0,t.jsx)(Xrs,{})}),(0,t.jsx)(nt,{path:"skills/sources",element:(0,t.jsx)(Nxe,{})}),(0,t.jsx)(nt,{path:"skills/sources/:sourceId",element:(0,t.jsx)(Nxe,{})}),(0,t.jsx)(nt,{path:"skills/studio",element:(0,t.jsx)(zB,{})}),(0,t.jsx)(nt,{path:"skills/studio/new",element:(0,t.jsx)(zB,{})}),(0,t.jsx)(nt,{path:"skills/studio/:skillId",element:(0,t.jsx)(zB,{})}),(0,t.jsx)(nt,{path:"skills/:skillId/studio",element:(0,t.jsx)(vDe,{})}),(0,t.jsx)(nt,{path:"skills/*",element:e?(0,t.jsx)(Zus,{}):(0,t.jsx)(sb,{children:(0,t.jsx)(Cgs,{})})}),(0,t.jsx)(nt,{path:"settings",element:(0,t.jsx)($y,{})}),(0,t.jsx)(nt,{path:"settings/*",element:(0,t.jsx)($y,{})}),(0,t.jsx)(nt,{path:"plugins/:pluginId",element:(0,t.jsx)(Pge,{})}),(0,t.jsx)(nt,{path:"org",element:e?(0,t.jsx)(_n,{to:"/agents/all",replace:!0}):(0,t.jsx)(sb,{children:(0,t.jsx)(Igs,{})})}),(0,t.jsx)(nt,{path:"agents",element:(0,t.jsx)(_n,{to:"/agents/all",replace:!0})}),fY.map(a=>(0,t.jsx)(nt,{path:`agents/${a}`,element:e?(0,t.jsx)(a6t,{}):(0,t.jsx)(sb,{children:(0,t.jsx)(Ngs,{})})},a)),(0,t.jsx)(nt,{path:"agents/new",element:(0,t.jsx)(Hxs,{})}),(0,t.jsx)(nt,{path:"agents/:agentId",element:(0,t.jsx)($$,{})}),(0,t.jsx)(nt,{path:"agents/:agentId/:tab",element:(0,t.jsx)($$,{})}),(0,t.jsx)(nt,{path:"agents/:agentId/runs/:runId",element:(0,t.jsx)($$,{})}),(0,t.jsx)(nt,{path:"projects",element:(0,t.jsx)(C8t,{})}),(0,t.jsx)(nt,{path:"projects/:projectId",element:(0,t.jsx)(Xv,{})}),(0,t.jsx)(nt,{path:"projects/:projectId/overview",element:(0,t.jsx)(Xv,{})}),(0,t.jsx)(nt,{path:"projects/:projectId/issues",element:(0,t.jsx)(Xv,{})}),(0,t.jsx)(nt,{path:"projects/:projectId/issues/:filter",element:(0,t.jsx)(Xv,{})}),(0,t.jsx)(nt,{element:(0,t.jsx)(FD,{}),children:(0,t.jsx)(nt,{path:"projects/:projectId/workspaces/:workspaceId",element:(0,t.jsx)(_Mt,{})})}),(0,t.jsx)(nt,{path:"projects/:projectId/workspaces",element:(0,t.jsx)(Xv,{})}),(0,t.jsx)(nt,{path:"projects/:projectId/configuration",element:(0,t.jsx)(Xv,{})}),(0,t.jsx)(nt,{path:"projects/:projectId/budget",element:(0,t.jsx)(Xv,{})}),(0,t.jsx)(nt,{element:(0,t.jsx)(FD,{}),children:(0,t.jsx)(nt,{path:"workspaces",element:(0,t.jsx)(TMt,{})})}),(0,t.jsx)(nt,{path:"terminal",element:(0,t.jsx)(sb,{children:(0,t.jsx)(Ags,{})})}),(0,t.jsx)(nt,{path:"issues",element:(0,t.jsx)(e7t,{})}),(0,t.jsx)(nt,{path:"tasks",element:(0,t.jsx)(_n,{to:"/issues",replace:!0})}),(0,t.jsx)(nt,{path:"search",element:(0,t.jsx)(y7t,{})}),n?(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)(nt,{path:"issues/all",element:(0,t.jsx)(Th,{view:"all"})}),(0,t.jsx)(nt,{path:"issues/active",element:(0,t.jsx)(Th,{view:"active"})}),(0,t.jsx)(nt,{path:"issues/backlog",element:(0,t.jsx)(Th,{view:"backlog"})}),(0,t.jsx)(nt,{path:"issues/done",element:(0,t.jsx)(Th,{view:"done"})}),(0,t.jsx)(nt,{path:"issues/recent",element:(0,t.jsx)(Th,{view:"recent"})})]}):(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)(nt,{path:"issues/all",element:(0,t.jsx)(_n,{to:"/issues",replace:!0})}),(0,t.jsx)(nt,{path:"issues/active",element:(0,t.jsx)(_n,{to:"/issues",replace:!0})}),(0,t.jsx)(nt,{path:"issues/backlog",element:(0,t.jsx)(_n,{to:"/issues",replace:!0})}),(0,t.jsx)(nt,{path:"issues/done",element:(0,t.jsx)(_n,{to:"/issues",replace:!0})}),(0,t.jsx)(nt,{path:"issues/recent",element:(0,t.jsx)(_n,{to:"/issues",replace:!0})})]}),(0,t.jsx)(nt,{path:"chats",element:(0,t.jsx)(EKt,{})}),(0,t.jsx)(nt,{path:"chats/:agentRef",element:(0,t.jsx)(MKt,{})}),(0,t.jsx)(nt,{path:"issues/:issueId",element:(0,t.jsx)(_Kt,{})}),null,(0,t.jsx)(nt,{path:"routines",element:e?(0,t.jsx)(hQt,{}):(0,t.jsx)(sb,{children:(0,t.jsx)(Sgs,{})})}),(0,t.jsx)(nt,{path:"cases",element:(0,t.jsx)(Qie,{children:(0,t.jsx)(Myt,{})})}),(0,t.jsx)(nt,{path:"cases/:caseIdentifier",element:(0,t.jsx)(Qie,{children:(0,t.jsx)(v1t,{})})}),(0,t.jsx)(nt,{path:"pixels-office",element:(0,t.jsx)(hyt,{children:(0,t.jsx)(KJt,{})})}),(0,t.jsx)(nt,{path:"status",element:(0,t.jsx)(Wie,{children:(0,t.jsx)(r0e,{})})}),(0,t.jsx)(nt,{path:"status/:cardId",element:(0,t.jsx)(Wie,{children:(0,t.jsx)(r0e,{})})}),(0,t.jsx)(nt,{path:"status-cards",element:(0,t.jsx)(tbe,{})}),(0,t.jsx)(nt,{path:"status-cards/:cardId",element:(0,t.jsx)(tbe,{})}),(0,t.jsx)(nt,{path:"review-queue",element:(0,t.jsx)(Vg,{children:(0,t.jsx)(RHt,{})})}),(0,t.jsx)(nt,{path:"learnings",element:(0,t.jsx)(Vg,{children:(0,t.jsx)(LHt,{})})}),(0,t.jsx)(nt,{path:"pipelines",element:(0,t.jsx)(Vg,{children:(0,t.jsx)(UO,{})})}),(0,t.jsx)(nt,{path:"pipelines/:pipelineId",element:(0,t.jsx)(Vg,{children:(0,t.jsx)(UO,{})})}),(0,t.jsx)(nt,{path:"pipelines/:pipelineId/add",element:(0,t.jsx)(Vg,{children:(0,t.jsx)(UO,{})})}),(0,t.jsx)(nt,{path:"pipelines/:pipelineId/settings",element:(0,t.jsx)(Vg,{children:(0,t.jsx)(CVt,{})})}),(0,t.jsx)(nt,{path:"pipelines/:pipelineId/items/:caseId",element:(0,t.jsx)(Vg,{children:(0,t.jsx)(ZWt,{})})}),(0,t.jsx)(nt,{path:"pipelines/:pipelineId/cases/:caseId",element:(0,t.jsx)(Vg,{children:(0,t.jsx)(VWt,{})})}),(0,t.jsx)(nt,{path:"routines/:routineId",element:e?(0,t.jsx)(ipe,{}):(0,t.jsx)(sb,{children:(0,t.jsx)(Yge,{})})}),(0,t.jsx)(nt,{path:"routines/:routineId/:section",element:e?(0,t.jsx)(ipe,{}):(0,t.jsx)(sb,{children:(0,t.jsx)(Yge,{})})}),(0,t.jsx)(nt,{element:(0,t.jsx)(FD,{}),children:(0,t.jsxs)(nt,{element:(0,t.jsx)(xyt,{}),children:[(0,t.jsx)(nt,{path:"execution-workspaces/:workspaceId",element:(0,t.jsx)(_1,{})}),(0,t.jsx)(nt,{path:"execution-workspaces/:workspaceId/services",element:(0,t.jsx)(_1,{})}),(0,t.jsx)(nt,{path:"execution-workspaces/:workspaceId/configuration",element:(0,t.jsx)(_1,{})}),(0,t.jsx)(nt,{path:"execution-workspaces/:workspaceId/runtime-logs",element:(0,t.jsx)(_1,{})}),(0,t.jsx)(nt,{path:"execution-workspaces/:workspaceId/issues",element:(0,t.jsx)(_1,{})}),(0,t.jsx)(nt,{path:"execution-workspaces/:workspaceId/routines",element:(0,t.jsx)(_1,{})})]})}),(0,t.jsx)(nt,{path:"goals",element:(0,t.jsx)(qes,{})}),(0,t.jsx)(nt,{path:"goals/:goalId",element:(0,t.jsx)(Xes,{})}),(0,t.jsx)(nt,{path:"artifacts",element:(0,t.jsx)(dpe,{})}),(0,t.jsx)(nt,{path:"approvals",element:(0,t.jsx)(_n,{to:"/approvals/pending",replace:!0})}),(0,t.jsx)(nt,{path:"approvals/pending",element:(0,t.jsx)(mpe,{})}),(0,t.jsx)(nt,{path:"approvals/all",element:(0,t.jsx)(mpe,{})}),(0,t.jsx)(nt,{path:"approvals/:approvalId",element:(0,t.jsx)(ets,{})}),(0,t.jsx)(nt,{path:"activity",element:e?(0,t.jsx)(Yts,{}):(0,t.jsx)(sb,{children:(0,t.jsx)(_gs,{})})}),e?(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)(nt,{path:"activity/runs",element:(0,t.jsx)(VC,{section:"runs"})}),(0,t.jsx)(nt,{path:"activity/costs",element:(0,t.jsx)(VC,{section:"costs"})}),(0,t.jsx)(nt,{path:"activity/budgets",element:(0,t.jsx)(VC,{section:"budgets"})}),(0,t.jsx)(nt,{path:"activity/timeline",element:(0,t.jsx)(VC,{section:"timeline"})}),(0,t.jsx)(nt,{path:"audit",element:(0,t.jsx)(Cp,{to:"/activity",forceAgentMode:!0})}),(0,t.jsx)(nt,{path:"audit/activity",element:(0,t.jsx)(Cp,{to:"/activity"})}),(0,t.jsx)(nt,{path:"audit/runs",element:(0,t.jsx)(Cp,{to:"/activity/runs"})}),(0,t.jsx)(nt,{path:"audit/costs",element:(0,t.jsx)(Cp,{to:"/activity/costs"})}),(0,t.jsx)(nt,{path:"audit/budgets",element:(0,t.jsx)(Cp,{to:"/activity/budgets"})}),(0,t.jsx)(nt,{path:"audit/timeline",element:(0,t.jsx)(Cp,{to:"/activity/timeline"})}),(0,t.jsx)(nt,{path:"runs",element:(0,t.jsx)(Cp,{to:"/activity/runs"})}),(0,t.jsx)(nt,{path:"costs",element:(0,t.jsx)(Cp,{to:"/activity/costs"})}),(0,t.jsx)(nt,{path:"budgets",element:(0,t.jsx)(Cp,{to:"/activity/budgets"})})]}):(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)(nt,{path:"costs",element:(0,t.jsx)(HK,{})}),(0,t.jsx)(nt,{path:"audit",element:(0,t.jsx)(_n,{to:"/activity?mode=agents",replace:!0})})]}),(0,t.jsxs)(nt,{element:(0,t.jsx)(cgt,{}),children:[(0,t.jsx)(nt,{path:"board-chat",element:(0,t.jsx)(zns,{})}),(0,t.jsx)(nt,{path:"artifacts",element:(0,t.jsx)(dpe,{})})]}),null,(0,t.jsx)(nt,{path:"decisions",element:(0,t.jsx)(mns,{})}),(0,t.jsx)(nt,{path:"decisions/queues/:key",element:(0,t.jsx)(xns,{})}),n?(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)(nt,{path:"inbox",element:(0,t.jsx)(Jge,{})}),(0,t.jsx)(nt,{path:"inbox/mine",element:(0,t.jsx)(Th,{view:"mine"})}),(0,t.jsx)(nt,{path:"inbox/recent",element:(0,t.jsx)(Th,{view:"recent"})}),(0,t.jsx)(nt,{path:"inbox/unread",element:(0,t.jsx)(Th,{view:"unread"})}),(0,t.jsx)(nt,{path:"inbox/blocked",element:(0,t.jsx)(Th,{view:"blocked"})}),(0,t.jsx)(nt,{path:"inbox/all",element:(0,t.jsx)(Th,{view:"everything"})}),(0,t.jsx)(nt,{path:"inbox/new",element:(0,t.jsx)(Th,{view:"mine"})})]}):(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)(nt,{path:"inbox",element:(0,t.jsx)(Jge,{})}),(0,t.jsx)(nt,{path:"inbox/mine",element:(0,t.jsx)(K1,{})}),(0,t.jsx)(nt,{path:"inbox/recent",element:(0,t.jsx)(K1,{})}),(0,t.jsx)(nt,{path:"inbox/unread",element:(0,t.jsx)(K1,{})}),(0,t.jsx)(nt,{path:"inbox/blocked",element:(0,t.jsx)(K1,{})}),(0,t.jsx)(nt,{path:"inbox/all",element:(0,t.jsx)(K1,{})}),(0,t.jsx)(nt,{path:"inbox/new",element:(0,t.jsx)(_n,{to:"/inbox/mine",replace:!0})})]}),(0,t.jsx)(nt,{path:"inbox/requests",element:(0,t.jsx)(wgs,{})}),(0,t.jsx)(nt,{path:"u/:userSlug",element:(0,t.jsx)(xes,{})}),(0,t.jsx)(nt,{path:"design-guide",element:(0,t.jsx)(hxs,{})}),(0,t.jsx)(nt,{path:"instance/settings/adapters",element:(0,t.jsx)(Mge,{})}),(0,t.jsx)(nt,{path:":pluginRoutePath/*",element:(0,t.jsx)(Pge,{})}),(0,t.jsx)(nt,{path:"*",element:(0,t.jsx)(om,{scope:"board"})})]})}r(Tgs,"boardRoutes");function Zge({credentialSource:e="paperclip_vault"}={}){const s=ua(),n=new URLSearchParams(s.search),{enabled:a,githubEnabled:i}=cw();return Fmt(n,{chatConnectorsEnabled:a,githubReviewBotsEnabled:i})?(0,t.jsx)(q7e,{credentialSource:e}):(0,t.jsx)(_n,{to:"/apps",replace:!0})}r(Zge,"AppsConnectEntryRoute");function Jge(){const{enabled:e}=Rc(),{enabled:s}=Q3();return e&&s?(0,t.jsx)(Th,{view:nFe(cte())}):(0,t.jsx)(_n,{to:`/inbox/${cte()}`,replace:!0})}r(Jge,"InboxRootRedirect");function Th({view:e}){const s=ua(),n=new URLSearchParams(s.search);return n.set(VT,e),(0,t.jsx)(_n,{to:`/issues?${n.toString()}${s.hash}`,replace:!0})}r(Th,"TaskViewRedirect");function vDe(){const e=ua(),{companies:s,selectedCompany:n,loading:a}=ps(),{companyPrefix:i,skillId:o}=ga();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)(_n,{to:"/skills/studio",replace:!0}):(0,t.jsx)(_n,{to:`/${l.issuePrefix}/skills/studio/${encodeURIComponent(o)}${e.search}${e.hash}`,replace:!0})}r(vDe,"LegacySkillStudioRedirect");function $y(){const e=ua(),{companies:s,selectedCompany:n,loading:a}=ps(),{companyPrefix:i}=ga(),{hidden:o}=Au();if(a)return(0,t.jsx)(nh,{});const l=(i?s.find(d=>d.issuePrefix.toUpperCase()===i.toUpperCase()):null)??n??s[0]??null;if(!l)return KV({pathname:e.pathname,hasCompanies:!1})?(0,t.jsx)(_n,{to:"/onboarding",replace:!0}):(0,t.jsx)(aJ,{});const c=hGe(aNe(`${e.pathname}${e.search}${e.hash}`),o);return(0,t.jsx)(_n,{to:`/${l.issuePrefix}${c}`,replace:!0})}r($y,"LegacySettingsRedirect");function Xge(){const{tab:e}=ga();return(0,t.jsx)(_n,{to:yDe(e),replace:!0})}r(Xge,"LegacyToolsSettingsRedirect");function ebe(){const{tab:e}=ga();return(0,t.jsx)(_n,{to:yDe(e),replace:!0})}r(ebe,"LegacyToolsRedirect");function yDe(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(yDe,"legacyToolsRedirectTarget");function jDe(){const{companies:e}=ps(),{openOnboarding:s}=al(),{t:n}=Rke(),a=ed(),i=p3e(a?.cloudBaseUrl??null),{onboardingOpen:o,onboardingRouteDismissed:l}=P8(),{companyPrefix:c}=ga(),d=c?e.find(p=>p.issuePrefix.toUpperCase()===c.toUpperCase())??null:null;if(jft({onboardingOpen:o,routeDismissed:l}))return null;const u=d?`Add another agent to ${d.name}`:e.length>0?"Create another organization":"Create your first organization",h=d?"Run onboarding again to add an agent and a starter task for this organization.":e.length>0?"Run onboarding again to create another organization and seed its first agent.":"Get started by creating an organization and your first agent.";return(0,t.jsx)("div",{className:"mx-auto max-w-xl py-10",children:(0,t.jsxs)("div",{className:"rounded-lg border border-border bg-card p-6",children:[(0,t.jsx)("h1",{className:"text-xl font-semibold",children:u}),(0,t.jsx)("p",{className:"mt-2 text-sm text-muted-foreground",children:h}),(0,t.jsx)("div",{className:"mt-4",children:!d&&a&&!i?(0,t.jsx)("p",{className:"text-sm text-muted-foreground",children:n("app.cloudCreateUnavailable",{defaultValue:"Organizations are created in Paperclip Cloud. This instance can't reach it right now — try again from your Cloud portfolio."})}):(0,t.jsx)($,{onClick:r(()=>d?s({initialStep:qE(),companyId:d.id}):a&&i?sh(i):s(),"onClick"),children:d?"Add Agent":"Start Onboarding"})})]})})}r(jDe,"OnboardingRoutePage");function Rgs(){const{companies:e,selectedCompany:s,loading:n}=ps(),a=ua();if(n)return(0,t.jsx)(nh,{});const i=s??e[0]??null;return i?(0,t.jsx)(_n,{to:`/${i.issuePrefix}/dashboard`,replace:!0}):KV({pathname:a.pathname,hasCompanies:!1})?(0,t.jsx)(_n,{to:"/onboarding",replace:!0}):(0,t.jsx)(aJ,{})}r(Rgs,"CompanyRootRedirect");function tbe(){const{cardId:e}=ga(),s=yFe(),n=s?`/${s}`:"";return(0,t.jsx)(_n,{to:`${n}/status${e?`/${e}`:""}`,replace:!0})}r(tbe,"StatusCardsLegacyRedirect");function Cp({to:e,forceAgentMode:s=!1}){const n=ua(),a=new URLSearchParams(n.search);s&&a.set("mode","agents");const i=a.toString();return(0,t.jsx)(_n,{to:`${e}${i?`?${i}`:""}${n.hash}`,replace:!0})}r(Cp,"AuditCompatibilityRedirect");function ya(){const e=ua(),{companies:s,selectedCompany:n,loading:a}=ps();if(a)return(0,t.jsx)(nh,{});const i=n??s[0]??null;return i?(0,t.jsx)(_n,{to:`/${i.issuePrefix}${e.pathname}${e.search}${e.hash}`,replace:!0}):KV({pathname:e.pathname,hasCompanies:!1})?(0,t.jsx)(_n,{to:"/onboarding",replace:!0}):(0,t.jsx)(aJ,{})}r(ya,"UnprefixedBoardRedirect");function aJ(){const{openOnboarding:e}=al(),{t:s}=Rke(),n=ed(),a=p3e(n?.cloudBaseUrl??null);return(0,t.jsx)("div",{className:"mx-auto max-w-xl py-10",children:(0,t.jsxs)("div",{className:"rounded-lg border border-border bg-card p-6",children:[(0,t.jsx)("h1",{className:"text-xl font-semibold",children:s("app.noCompanies.title",{defaultValue:"Create your first organization"})}),(0,t.jsx)("p",{className:"mt-2 text-sm text-muted-foreground",children:s("app.noCompanies.description",{defaultValue:"Get started by creating an organization."})}),(0,t.jsx)("div",{className:"mt-4",children:n&&!a?(0,t.jsx)("p",{className:"text-sm text-muted-foreground",children:s("app.cloudCreateUnavailable",{defaultValue:"Organizations are created in Paperclip Cloud. This instance can't reach it right now — try again from your Cloud portfolio."})}):(0,t.jsx)($,{onClick:r(()=>n&&a?sh(a):e(),"onClick"),children:s("app.noCompanies.newCompany",{defaultValue:"New Organization"})})})]})})}r(aJ,"NoCompaniesStartPage");function Egs(){const{enabled:e,loaded:s}=Rc(),{enabled:n}=Q3();return(0,t.jsxs)(t.Fragment,{children:[(0,t.jsxs)(rFe,{children:[(0,t.jsx)(nt,{path:"oauth-handoff",element:(0,t.jsx)(pds,{})}),(0,t.jsx)(nt,{path:"auth",element:(0,t.jsx)(Xxs,{})}),(0,t.jsx)(nt,{path:"board-claim/:token",element:(0,t.jsx)(egs,{})}),(0,t.jsx)(nt,{path:"mcp-connect/:id",element:(0,t.jsx)(qge,{})}),(0,t.jsx)(nt,{path:"dot-connect/:id",element:(0,t.jsx)(qge,{agentPairingOnly:!0})}),(0,t.jsx)(nt,{path:"mcp-device",element:(0,t.jsx)(tgs,{})}),(0,t.jsx)(nt,{path:"assistant-connections",element:(0,t.jsx)(sgs,{})}),(0,t.jsx)(nt,{path:"cli-auth/:id",element:(0,t.jsx)(ngs,{})}),(0,t.jsx)(nt,{path:"invite/:token",element:(0,t.jsx)(dgs,{})}),(0,t.jsx)(nt,{path:"s/:token",element:(0,t.jsx)(Gge,{})}),(0,t.jsx)(nt,{path:"s/:token/issues/:issueId",element:(0,t.jsx)(Gge,{})}),(0,t.jsx)(nt,{element:s?(0,t.jsx)(zoe,{allowMembershipRequest:!0}):(0,t.jsx)(nh,{}),children:(0,t.jsx)(nt,{path:"chat-identity/confirm",element:(0,t.jsx)(rds,{})})}),(0,t.jsx)(nt,{path:"tests/perf/long-thread",element:(0,t.jsx)(QKt,{})}),(0,t.jsx)(nt,{path:"ux-lab/bootstrap-setup",element:(0,t.jsx)(Grs,{})}),(0,t.jsx)(nt,{path:"ux-lab/responsible-user-denial",element:(0,t.jsx)(Yrs,{})}),(0,t.jsx)(nt,{path:"ux-lab/cross-issue-collaboration",element:(0,t.jsx)(Jrs,{})}),(0,t.jsxs)(nt,{element:s?(0,t.jsx)(zoe,{}):(0,t.jsx)(nh,{}),children:[(0,t.jsx)(nt,{index:!0,element:(0,t.jsx)(Rgs,{})}),(0,t.jsx)(nt,{path:"onboarding",element:(0,t.jsx)(jDe,{})}),(0,t.jsx)(nt,{path:"instance",element:(0,t.jsx)($y,{})}),(0,t.jsx)(nt,{path:"instance/settings",element:(0,t.jsx)($y,{})}),(0,t.jsx)(nt,{path:"instance/settings/*",element:(0,t.jsx)($y,{})}),(0,t.jsx)(nt,{path:"companies",element:(0,t.jsx)(ya,{})}),(0,t.jsx)(nt,{path:"dashboard",element:(0,t.jsx)(ya,{})}),(0,t.jsx)(nt,{path:"inbox/*",element:(0,t.jsx)(ya,{})}),(0,t.jsx)(nt,{path:"issues",element:(0,t.jsx)(ya,{})}),(0,t.jsx)(nt,{path:"tasks",element:(0,t.jsx)(ya,{})}),(0,t.jsx)(nt,{path:"issues/:issueId",element:(0,t.jsx)(ya,{})}),(0,t.jsx)(nt,{path:"routines",element:(0,t.jsx)(ya,{})}),(0,t.jsx)(nt,{path:"routines/:routineId",element:(0,t.jsx)(ya,{})}),(0,t.jsx)(nt,{path:"review-queue",element:(0,t.jsx)(ya,{})}),(0,t.jsx)(nt,{path:"learnings",element:(0,t.jsx)(ya,{})}),(0,t.jsx)(nt,{path:"cases",element:(0,t.jsx)(ya,{})}),(0,t.jsx)(nt,{path:"cases/:caseIdentifier",element:(0,t.jsx)(ya,{})}),(0,t.jsx)(nt,{path:"pixels-office",element:(0,t.jsx)(ya,{})}),(0,t.jsx)(nt,{path:"status",element:(0,t.jsx)(ya,{})}),(0,t.jsx)(nt,{path:"status/:cardId",element:(0,t.jsx)(ya,{})}),(0,t.jsx)(nt,{path:"status-cards",element:(0,t.jsx)(ya,{})}),(0,t.jsx)(nt,{path:"status-cards/:cardId",element:(0,t.jsx)(ya,{})}),(0,t.jsx)(nt,{path:"pipelines",element:(0,t.jsx)(ya,{})}),(0,t.jsx)(nt,{path:"pipelines/:pipelineId",element:(0,t.jsx)(ya,{})}),(0,t.jsx)(nt,{path:"pipelines/:pipelineId/add",element:(0,t.jsx)(ya,{})}),(0,t.jsx)(nt,{path:"pipelines/:pipelineId/settings",element:(0,t.jsx)(ya,{})}),(0,t.jsx)(nt,{path:"pipelines/:pipelineId/items/:caseId",element:(0,t.jsx)(ya,{})}),(0,t.jsx)(nt,{path:"pipelines/:pipelineId/cases/:caseId",element:(0,t.jsx)(ya,{})}),(0,t.jsx)(nt,{path:"artifacts",element:(0,t.jsx)(ya,{})}),(0,t.jsx)(nt,{path:"audit",element:(0,t.jsx)(ya,{})}),e?(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)(nt,{path:"audit/*",element:(0,t.jsx)(ya,{})}),(0,t.jsx)(nt,{path:"activity",element:(0,t.jsx)(ya,{})}),(0,t.jsx)(nt,{path:"activity/*",element:(0,t.jsx)(ya,{})}),(0,t.jsx)(nt,{path:"runs",element:(0,t.jsx)(ya,{})}),(0,t.jsx)(nt,{path:"costs",element:(0,t.jsx)(ya,{})}),(0,t.jsx)(nt,{path:"budgets",element:(0,t.jsx)(ya,{})})]}):null,(0,t.jsx)(nt,{path:"decisions",element:(0,t.jsx)(ya,{})}),(0,t.jsx)(nt,{path:"u/:userSlug",element:(0,t.jsx)(ya,{})}),(0,t.jsx)(nt,{path:"skills/studio",element:(0,t.jsx)(ya,{})}),(0,t.jsx)(nt,{path:"skills/studio/new",element:(0,t.jsx)(ya,{})}),(0,t.jsx)(nt,{path:"skills/studio/:skillId",element:(0,t.jsx)(ya,{})}),(0,t.jsx)(nt,{path:"skills/:skillId/studio",element:(0,t.jsx)(vDe,{})}),(0,t.jsx)(nt,{path:"skills/*",element:(0,t.jsx)(ya,{})}),(0,t.jsx)(nt,{path:"settings",element:(0,t.jsx)($y,{})}),(0,t.jsx)(nt,{path:"settings/*",element:(0,t.jsx)($y,{})}),(0,t.jsx)(nt,{path:"agents",element:(0,t.jsx)(ya,{})}),fY.map(a=>(0,t.jsx)(nt,{path:`agents/${a}`,element:(0,t.jsx)(ya,{})},a)),(0,t.jsx)(nt,{path:"agents/new",element:(0,t.jsx)(ya,{})}),(0,t.jsx)(nt,{path:"agents/:agentId",element:(0,t.jsx)(ya,{})}),(0,t.jsx)(nt,{path:"agents/:agentId/:tab",element:(0,t.jsx)(ya,{})}),(0,t.jsx)(nt,{path:"agents/:agentId/runs/:runId",element:(0,t.jsx)(ya,{})}),(0,t.jsx)(nt,{path:"projects",element:(0,t.jsx)(ya,{})}),(0,t.jsx)(nt,{path:"projects/:projectId",element:(0,t.jsx)(ya,{})}),(0,t.jsx)(nt,{path:"projects/:projectId/overview",element:(0,t.jsx)(ya,{})}),(0,t.jsx)(nt,{path:"projects/:projectId/issues",element:(0,t.jsx)(ya,{})}),(0,t.jsx)(nt,{path:"projects/:projectId/issues/:filter",element:(0,t.jsx)(ya,{})}),(0,t.jsx)(nt,{path:"projects/:projectId/workspaces",element:(0,t.jsx)(ya,{})}),(0,t.jsx)(nt,{path:"projects/:projectId/workspaces/:workspaceId",element:(0,t.jsx)(ya,{})}),(0,t.jsx)(nt,{path:"projects/:projectId/configuration",element:(0,t.jsx)(ya,{})}),(0,t.jsx)(nt,{path:"workspaces",element:(0,t.jsx)(ya,{})}),(0,t.jsx)(nt,{path:"terminal",element:(0,t.jsx)(ya,{})}),(0,t.jsx)(nt,{path:"execution-workspaces/:workspaceId",element:(0,t.jsx)(r1,{})}),(0,t.jsx)(nt,{path:"execution-workspaces/:workspaceId/services",element:(0,t.jsx)(r1,{})}),(0,t.jsx)(nt,{path:"execution-workspaces/:workspaceId/configuration",element:(0,t.jsx)(r1,{})}),(0,t.jsx)(nt,{path:"execution-workspaces/:workspaceId/runtime-logs",element:(0,t.jsx)(r1,{})}),(0,t.jsx)(nt,{path:"execution-workspaces/:workspaceId/issues",element:(0,t.jsx)(r1,{})}),(0,t.jsx)(nt,{path:"execution-workspaces/:workspaceId/routines",element:(0,t.jsx)(r1,{})}),(0,t.jsx)(nt,{path:":companyPrefix",element:e?(0,t.jsx)(_xt,{}):(0,t.jsx)(igt,{}),children:Tgs(e,n)}),(0,t.jsx)(nt,{path:"*",element:(0,t.jsx)(om,{scope:"global"})})]})]}),(0,t.jsx)(okt,{}),(0,t.jsx)(oxt,{})]})}r(Egs,"App");var Lgs=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){WV(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 Mgs(){const{data:e}=te({queryKey:M.auth.session,queryFn:r(()=>Ma.getSession(),"queryFn"),retry:!1}),s=e?.sentryDsn,n=e?.sentryEnvironment??void 0;return(0,m.useEffect)(()=>{if(s)return Bft(s,n),()=>{Fft()}},[s,n]),null}r(Mgs,"SentryGate");function Pgs(e){let s=ig();qae(s),eq(s,e.userId);const n=q5e(()=>{const o=ig();o!==s&&(s=o,qae(o),eq(o,e.userId))}),a=typeof navigator<"u"&&"serviceWorker"in navigator?navigator.serviceWorker:null,i=r(o=>{const l=K0t(o.data);l&&(l.type==="navigate"?e.navigate(l.url):q0t(l.notification))},"onMessage");return a?.addEventListener("message",i),a?.startMessages(),()=>{n(),a?.removeEventListener("message",i)}}r(Pgs,"startNotificationRuntime");function Dgs(){const e=Yn(),s=(0,m.useRef)(e),{data:n}=te({queryKey:M.auth.session,queryFn:r(()=>Ma.getSession(),"queryFn"),retry:!1}),a=n?.user?.id??n?.session?.userId??null;return(0,m.useEffect)(()=>{s.current=e},[e]),(0,m.useEffect)(()=>{if(a)return Pgs({userId:a,navigate:r(i=>s.current(i),"navigate")})},[a]),null}r(Dgs,"NotificationRuntime");var wDe={get:r(e=>we.get(`/companies/${e}/primary-agent/me`),"get"),set:r((e,s)=>we.put(`/companies/${e}/primary-agent/me`,s),"set")};function $gs(e){const s=te({queryKey:M.auth.session,queryFn:r(()=>Ma.getSession(),"queryFn")}),n=s.data?.user?.id??s.data?.session?.userId??"local-board",a=te({queryKey:M.primaryAgent.mine(e??"__none__",n),queryFn:r(()=>wDe.get(e),"queryFn"),enabled:!!e&&s.isSuccess});return{...a,userId:n,loading:!!e&&(s.isPending||a.isPending&&!s.error),error:s.error??a.error,retry:r(()=>s.isError?s.refetch():a.refetch(),"retry")}}r($gs,"usePrimaryAgent");function Ogs({children:e}){const{selectedCompanyId:s}=ps(),n=$gs(s),a=kt(),{pushToast:i}=Xr(),o=(0,m.useRef)({companyId:s,userId:n.userId});o.current={companyId:s,userId:n.userId};const l=r(f=>M.primaryAgent.mine(f.companyId,f.userId),"keyFor"),c=r(f=>f.companyId===o.current.companyId&&f.userId===o.current.userId,"isCurrentScope"),d=te({queryKey:M.agents.list(s),queryFn:r(()=>_t.list(s),"queryFn"),enabled:!!s}),u=je({mutationFn:r(f=>wDe.set(f.companyId,{primaryAgentId:f.agentId}),"mutationFn"),onMutate:r(async f=>{const x=l(f);await a.cancelQueries({queryKey:x});const g=a.getQueryData(x);return a.setQueryData(x,{companyId:f.companyId,userId:f.userId,primaryAgentId:f.agentId,initialized:!0}),{previous:g}},"onMutate"),onError:r((f,x,g)=>{a.setQueryData(l(x),g?.previous),c(x)&&i({title:"Couldn't change your primary agent.",body:f.message,tone:"error",action:{label:"Retry",onClick:r(()=>{c(x)&&u.mutate(x)},"onClick")}})},"onError"),onSuccess:r((f,x)=>a.setQueryData(l(x),f),"onSuccess"),onSettled:r((f,x,g)=>{a.invalidateQueries({queryKey:l(g)}),a.invalidateQueries({queryKey:M.resourceMemberships.mine(g.companyId)})},"onSettled")}),h=d.data?.find(f=>f.id===n.data?.primaryAgentId&&f.status!=="terminated")??null,p=n.error??d.error;return(0,t.jsx)(jVe,{value:s?{companyId:s,primaryAgentId:h?.id??null,primaryAgent:h,loading:n.loading||d.isPending,error:p?.message,onRetry:r(()=>{n.retry(),d.refetch()},"onRetry"),pendingAgentId:u.isPending&&c(u.variables)?u.variables.agentId:null,onChange:r(f=>u.mutate({companyId:s,userId:n.userId,agentId:f}),"onChange")}:null,children:e})}r(Ogs,"PrimaryAgentProvider");function Bgs(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(Bgs,"managedRoutineToRow");function Fgs({routines:e,agents:s=[],projects:n=[],pluginDisplayName:a=null,emptyMessage:i="No managed routines.",runningRoutineKey:o=null,statusMutationRoutineKey:l=null,reconcilingRoutineKey:c=null,resettingRoutineKey:d=null,onRunNow:u,onToggleEnabled:h,onReconcile:p,onReset:f}){const x=new Map(s.map(v=>[v.id,v])),g=new Map(n.map(v=>[v.id,{name:v.name,color:v.color}]));return e.length===0?(0,t.jsx)("div",{className:"rounded-lg border border-border px-3 py-8 text-center text-sm text-muted-foreground",children:i}):(0,t.jsx)("div",{className:"rounded-lg border border-border",children:e.map(v=>{const y=Bgs(v),k=v.href??(v.routineId?`/routines/${v.routineId}`:"/routines"),w=v.missingRefs??[],N=!!(v.routineId&&v.resourceKey&&w.length===0),S=v.managedByPluginDisplayName??a,C=!!(p||f);return(0,t.jsxs)("div",{className:"last:[&_a]:border-b-0",children:[(0,t.jsx)(V8e,{routine:y,projectById:g,agentById:x,runningRoutineId:o,statusMutationRoutineId:l,href:k,configureLabel:"Configure",managedByLabel:S?`Managed by ${S}`:null,runNowButton:!0,hideArchiveAction:!0,disableRunNow:!N,disableToggle:!N,secondaryDetails:(0,t.jsxs)("span",{className:"flex flex-wrap items-center gap-x-3 gap-y-1",children:[v.resourceKey?(0,t.jsx)("span",{children:v.resourceKey}):null,v.cronExpression?(0,t.jsxs)("span",{children:["Schedule ",v.cronExpression]}):null]}),onRunNow:r(()=>u?.(v),"onRunNow"),onToggleEnabled:r(()=>h?.(v,y.status==="active"),"onToggleEnabled")}),C?(0,t.jsxs)("div",{className:"flex flex-wrap items-center justify-between gap-2 border-b border-border px-3 pb-3 text-xs text-muted-foreground last:border-b-0",onClick:r(_=>{_.preventDefault(),_.stopPropagation()},"onClick"),children:[(0,t.jsx)("span",{children:w.length?`Missing ${w.map(_=>`${_.resourceKind}:${_.resourceKey}`).join(", ")}`:"Routine defaults can be repaired."}),(0,t.jsxs)("span",{className:"flex items-center gap-2",children:[p?(0,t.jsx)($,{size:"sm",variant:"ghost",disabled:c===v.key,onClick:r(()=>p(v),"onClick"),children:c===v.key?"Reconciling...":"Reconcile"}):null,f?(0,t.jsx)($,{size:"sm",variant:"ghost",disabled:d===v.key,onClick:r(()=>f(v),"onClick"),children:d===v.key?"Resetting...":"Reset"}):null]})]}):null]},v.key)})})}r(Fgs,"ManagedRoutinesList");function sbe(e){return new Set(e??[])}r(sbe,"toPathSet");function zgs({expandedPaths:e,checkedPaths:s,selectedFile:n=null,showCheckboxes:a=!1,onToggleDir:i,onSelectFile:o,...l}){return(0,m.createElement)(kw,{...l,selectedFile:n,expandedDirs:sbe(e),checkedFiles:s?sbe(s):void 0,showCheckboxes:a,onToggleDir:i??(()=>{}),onSelectFile:o??(()=>{})})}r(zgs,"PluginSdkFileTree");function qgs(e){const[s,n]=(0,m.useState)(null);return(0,m.useEffect)(()=>{let a=!1;return fd(()=>import("./MarkdownEditor-DHz7g42W.js").then(i=>i.n).then(i=>{a||n(()=>i.MarkdownEditor)}),__vite__mapDeps([44,5,7,9,14,15,33,28,31,45,30,29,21,46])),()=>{a=!0}},[]),s?(0,m.createElement)(s,e):(0,m.createElement)("textarea",{className:e.className,value:e.value,placeholder:e.placeholder,readOnly:e.readOnly,onBlur:e.onBlur,onChange:r(a=>e.onChange(a.currentTarget.value),"onChange")})}r(qgs,"PluginSdkMarkdownEditor");function Ugs(e){return Object.fromEntries(Object.entries(e).filter(([,s])=>s!=null&&s!==""&&s!==!1))}r(Ugs,"compactIssueFilters");function Kgs({companyId:e,projectId:s=null,filters:n,viewStateKey:a="paperclip:plugin-issues-view",initialSearch:i,createIssueLabel:o,searchWithinLoadedIssues:l=!0}){const c=kt(),d=(0,m.useMemo)(()=>Ugs({...n??{},projectId:n?.projectId??s??void 0}),[n,s]),u=d.originKindPrefix??null,h=d.projectId??s??null,p=(0,m.useMemo)(()=>["plugins","sdk-ui","issues-list",e??"__no-company__",d],[e,d]),{data:f}=te({queryKey:M.agents.list(e??"__no-company__"),queryFn:r(()=>_t.list(e),"queryFn"),enabled:!!e}),{data:x}=te({queryKey:M.projects.list(e??"__no-company__",{includeArchived:!0}),queryFn:r(()=>oa.list(e,{includeArchived:!0}),"queryFn"),enabled:!!e}),g=M.liveRuns(e??"__no-company__"),v=Co({companyId:e,resourceKey:"live-runs",queryKey:g,enabled:!!e,refetchInterval:!1,leaderOnly:!0}),{data:y,dataUpdatedAt:k}=te({queryKey:g,queryFn:r(()=>na.liveRunsForCompany(e),"queryFn"),enabled:v.enabled,refetchInterval:v.refetchInterval});_o(v,y,k);const{data:w,isLoading:N,error:S}=te({queryKey:p,queryFn:r(()=>jt.list(e,d),"queryFn"),enabled:!!e}),C=(0,m.useMemo)(()=>pg(y,w),[w,y]),_=je({mutationFn:r(({id:R,data:I})=>jt.update(R,I),"mutationFn"),onSuccess:r(()=>{e&&(c.invalidateQueries({queryKey:["plugins","sdk-ui","issues-list",e]}),c.invalidateQueries({queryKey:M.issues.list(e)}),h&&(c.invalidateQueries({queryKey:M.issues.listByProject(e,h)}),u&&c.invalidateQueries({queryKey:M.issues.listPluginOperationsByProject(e,h,u)})))},"onSuccess")});return e?(0,m.createElement)(Jx,{issues:w??[],isLoading:N,error:S,agents:f,projects:x,liveIssueIds:C,projectId:h??void 0,viewStateKey:a,initialSearch:i,createIssueLabel:o,searchWithinLoadedIssues:l,onUpdateIssue:r((R,I)=>_.mutate({id:R,data:I}),"onUpdateIssue")}):(0,m.createElement)("div",{className:"text-sm text-muted-foreground"},"Select an organization to view tasks.")}r(Kgs,"PluginSdkIssuesList");function Qgs({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=VW(),f=e??p.companyId??null,{data:x}=te({queryKey:M.auth.session,queryFn:r(()=>Ma.getSession(),"queryFn"),enabled:c}),g=x?.user?.id??x?.session?.userId??null,{data:v}=te({queryKey:M.agents.list(f??"__no-company__"),queryFn:r(()=>_t.list(f),"queryFn"),enabled:!!f}),{data:y}=te({queryKey:M.access.companyUserDirectory(f??"__no-company__"),queryFn:r(()=>ir.listUserDirectory(f),"queryFn"),enabled:!!f&&c}),k=(0,m.useMemo)(()=>uF(),[]),w=(0,m.useMemo)(()=>k.map(R=>R.startsWith("agent:")?R.slice(6):null).filter(R=>!!R),[k]),N=(0,m.useMemo)(()=>gj((v??[]).filter(R=>d||R.status!=="terminated"),w),[v,d,w]),S=(0,m.useMemo)(()=>[...c?Pve(g):[],...c?xS(y?.users,{excludeUserIds:[g]}):[],...N.map(R=>({id:$h({assigneeAgentId:R.id}),label:R.name,searchText:`${R.name} ${R.role} ${R.title??""}`}))],[y?.users,g,c,N]),C=Zy(s),_=C.assigneeAgentId?N.find(R=>R.id===C.assigneeAgentId):null;return(0,m.createElement)(rm,{value:s,options:S,recentOptionIds:k,placeholder:a,noneLabel:i,searchPlaceholder:o,emptyMessage:l,className:u,onConfirm:h,onChange:r(R=>{const I=Zy(R);I.assigneeAgentId&&bj(I.assigneeAgentId),I.assigneeUserId&&K_(I.assigneeUserId),n(R,I)},"onChange"),renderTriggerValue:r(R=>R?_?(0,m.createElement)(b8,null,(0,m.createElement)(UE,{icon:_.icon,className:"h-3.5 w-3.5 shrink-0 text-muted-foreground"}),(0,m.createElement)("span",{className:"truncate"},R.label)):(0,m.createElement)("span",{className:"truncate"},R.label):(0,m.createElement)("span",{className:"text-muted-foreground"},a),"renderTriggerValue"),renderOption:r(R=>{if(!R.id)return(0,m.createElement)("span",{className:"truncate"},R.label);const I=Zy(R.id),T=I.assigneeAgentId?N.find(E=>E.id===I.assigneeAgentId):null;return(0,m.createElement)(b8,null,T?(0,m.createElement)(UE,{icon:T.icon,className:"h-3.5 w-3.5 shrink-0 text-muted-foreground"}):(0,m.createElement)(pd,{className:"h-3.5 w-3.5 shrink-0 text-muted-foreground"}),(0,m.createElement)("span",{className:"truncate"},R.label))},"renderOption")})}r(Qgs,"PluginSdkAssigneePicker");function Wgs({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=VW(),p=e??h.companyId??null,{data:f}=te({queryKey:M.auth.session,queryFn:r(()=>Ma.getSession(),"queryFn")}),x=f?.user?.id??f?.session?.userId??null,{data:g}=te({queryKey:M.projects.list(p??"__no-company__",{includeArchived:c}),queryFn:r(()=>oa.list(p,{includeArchived:c}),"queryFn"),enabled:!!p}),v=(0,m.useMemo)(()=>(g??[]).filter(S=>c||!S.archivedAt),[c,g]),{orderedProjects:y}=rw({projects:v,companyId:p,userId:x}),k=(0,m.useMemo)(()=>vj(),[]),w=(0,m.useMemo)(()=>y.map(S=>({id:S.id,label:S.name,searchText:S.description??""})),[y]),N=y.find(S=>S.id===s)??null;return(0,m.createElement)(rm,{value:s,options:w,recentOptionIds:k,placeholder:a,noneLabel:i,searchPlaceholder:o,emptyMessage:l,className:d,onConfirm:u,onChange:r(S=>{S&&qb(S),n(S)},"onChange"),renderTriggerValue:r(S=>!S||!N?(0,m.createElement)("span",{className:"text-muted-foreground"},a):(0,m.createElement)(b8,null,(0,m.createElement)("span",{className:"h-3.5 w-3.5 shrink-0 rounded-sm",style:{backgroundColor:N.color??"#6366f1"}}),(0,m.createElement)("span",{className:"truncate"},S.label)),"renderTriggerValue"),renderOption:r(S=>{if(!S.id)return(0,m.createElement)("span",{className:"truncate"},S.label);const C=y.find(_=>_.id===S.id);return(0,m.createElement)(b8,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(Wgs,"PluginSdkProjectPicker");function b8({children:e}){return(0,m.createElement)("span",{className:"contents"},e)}r(b8,"FragmentSafe");function Hgs({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(Hgs,"PluginSdkStatusBadge");function Vgs({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(Vgs,"PluginSdkDataTable");function Ggs({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(Ggs,"PluginSdkKeyValueList");function Ygs({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(Ygs,"PluginSdkMetricCard");function Zgs({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(Zgs,"PluginSdkJsonTree");function Jgs({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(Jgs,"PluginSdkSpinner");var Xgs=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 ebs(e,s){globalThis.__paperclipPluginBridge__={react:e,reactJsxRuntime:t,reactDom:s,sdkUi:{usePluginData:wGe,usePluginAction:kGe,useHostContext:VW,useHostLocation:SGe,useHostNavigation:NGe,usePluginStream:_Ge,usePluginToast:CGe,copyTextToClipboard:wa,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:Ygs,StatusBadge:Hgs,DataTable:Vgs,KeyValueList:Ggs,JsonTree:Zgs,Spinner:Jgs,ErrorBoundary:Xgs,MarkdownEditor:qgs,FileTree:zgs,IssuesList:Kgs,AssigneePicker:Qgs,ProjectPicker:Wgs,ManagedRoutinesList:Fgs}}}r(ebs,"initPluginBridge");var tbs=1e4;function sbs(e=tbs){if(typeof performance>"u"||typeof performance.clearMeasures!="function")return()=>{};const n=setInterval(r(()=>{globalThis.__paperclipKeepPerfMeasures||performance.clearMeasures()},"reap"),e);return()=>clearInterval(n)}r(sbs,"startPerfMeasureReaper");var nbs=Hj((e=>{function s(F,z){var K=F.length;F.push(z);e:for(;0<K;){var U=K-1>>>1,q=F[U];if(0<i(q,z))F[U]=z,F[K]=q,K=U;else break e}}r(s,"push");function n(F){return F.length===0?null:F[0]}r(n,"peek");function a(F){if(F.length===0)return null;var z=F[0],K=F.pop();if(K!==z){F[0]=K;e:for(var U=0,q=F.length,G=q>>>1;U<G;){var se=2*(U+1)-1,Z=F[se],ie=se+1,J=F[ie];if(0>i(Z,K))ie<q&&0>i(J,Z)?(F[U]=J,F[ie]=K,U=ie):(F[U]=Z,F[se]=K,U=se);else if(ie<q&&0>i(J,K))F[U]=J,F[ie]=K,U=ie;else break e}}return z}r(a,"pop");function i(F,z){var K=F.sortIndex-z.sortIndex;return K!==0?K:F.id-z.id}if(r(i,"compare"),e.unstable_now=void 0,typeof performance=="object"&&typeof performance.now=="function"){var o=performance;e.unstable_now=function(){return o.now()}}else{var l=Date,c=l.now();e.unstable_now=function(){return l.now()-c}}var d=[],u=[],h=1,p=null,f=3,x=!1,g=!1,v=!1,y=!1,k=typeof setTimeout=="function"?setTimeout:null,w=typeof clearTimeout=="function"?clearTimeout:null,N=typeof setImmediate<"u"?setImmediate:null;function S(F){for(var z=n(u);z!==null;){if(z.callback===null)a(u);else if(z.startTime<=F)a(u),z.sortIndex=z.expirationTime,s(d,z);else break;z=n(u)}}r(S,"advanceTimers");function C(F){if(v=!1,S(F),!g)if(n(d)!==null)g=!0,_||(_=!0,O());else{var z=n(u);z!==null&&D(C,z.startTime-F)}}r(C,"handleTimeout");var _=!1,R=-1,I=5,T=-1;function E(){return y?!0:!(e.unstable_now()-T<I)}r(E,"shouldYieldToHost");function L(){if(y=!1,_){var F=e.unstable_now();T=F;var z=!0;try{e:{g=!1,v&&(v=!1,w(R),R=-1),x=!0;var K=f;try{t:{for(S(F),p=n(d);p!==null&&!(p.expirationTime>F&&E());){var U=p.callback;if(typeof U=="function"){p.callback=null,f=p.priorityLevel;var q=U(p.expirationTime<=F);if(F=e.unstable_now(),typeof q=="function"){p.callback=q,S(F),z=!0;break t}p===n(d)&&a(d),S(F)}else a(d);p=n(d)}if(p!==null)z=!0;else{var G=n(u);G!==null&&D(C,G.startTime-F),z=!1}}break e}finally{p=null,f=K,x=!1}z=void 0}}finally{z?O():_=!1}}}r(L,"performWorkUntilDeadline");var O;if(typeof N=="function")O=r(function(){N(L)},"schedulePerformWorkUntilDeadline");else if(typeof MessageChannel<"u"){var P=new MessageChannel,Q=P.port2;P.port1.onmessage=L,O=r(function(){Q.postMessage(null)},"schedulePerformWorkUntilDeadline")}else O=r(function(){k(L,0)},"schedulePerformWorkUntilDeadline");function D(F,z){R=k(function(){F(e.unstable_now())},z)}r(D,"requestHostTimeout"),e.unstable_IdlePriority=5,e.unstable_ImmediatePriority=1,e.unstable_LowPriority=4,e.unstable_NormalPriority=3,e.unstable_Profiling=null,e.unstable_UserBlockingPriority=2,e.unstable_cancelCallback=function(F){F.callback=null},e.unstable_forceFrameRate=function(F){0>F||125<F||(I=0<F?Math.floor(1e3/F):5)},e.unstable_getCurrentPriorityLevel=function(){return f},e.unstable_next=function(F){switch(f){case 1:case 2:case 3:var z=3;break;default:z=f}var K=f;f=z;try{return F()}finally{f=K}},e.unstable_requestPaint=function(){y=!0},e.unstable_runWithPriority=function(F,z){switch(F){case 1:case 2:case 3:case 4:case 5:break;default:F=3}var K=f;f=F;try{return z()}finally{f=K}},e.unstable_scheduleCallback=function(F,z,K){var U=e.unstable_now();switch(typeof K=="object"&&K!==null?(K=K.delay,K=typeof K=="number"&&0<K?U+K:U):K=U,F){case 1:var q=-1;break;case 2:q=250;break;case 5:q=1073741823;break;case 4:q=1e4;break;default:q=5e3}return q=K+q,F={id:h++,callback:z,priorityLevel:F,startTime:K,expirationTime:q,sortIndex:-1},K>U?(F.sortIndex=K,s(u,F),n(d)===null&&F===n(u)&&(v?(w(R),R=-1):v=!0,D(C,K-U))):(F.sortIndex=q,s(d,F),g||x||(g=!0,_||(_=!0,O()))),F},e.unstable_shouldYield=E,e.unstable_wrapCallback=function(F){var z=f;return function(){var K=f;f=z;try{return F.apply(this,arguments)}finally{f=K}}}})),rbs=Hj(((e,s)=>{s.exports=nbs()})),abs=Hj((e=>{var s=rbs(),n=zQ(),a=nbe();function i(b){var j="https://react.dev/errors/"+b;if(1<arguments.length){j+="?args[]="+encodeURIComponent(arguments[1]);for(var A=2;A<arguments.length;A++)j+="&args[]="+encodeURIComponent(arguments[A])}return"Minified React error #"+b+"; visit "+j+" for the full message or use the non-minified dev environment for full errors and additional helpful warnings."}r(i,"formatProdErrorMessage");function o(b){return!(!b||b.nodeType!==1&&b.nodeType!==9&&b.nodeType!==11)}r(o,"isValidContainer");function l(b){var j=b,A=b;if(b.alternate)for(;j.return;)j=j.return;else{b=j;do j=b,(j.flags&4098)!==0&&(A=j.return),b=j.return;while(b)}return j.tag===3?A:null}r(l,"getNearestMountedFiber");function c(b){if(b.tag===13){var j=b.memoizedState;if(j===null&&(b=b.alternate,b!==null&&(j=b.memoizedState)),j!==null)return j.dehydrated}return null}r(c,"getSuspenseInstanceFromFiber");function d(b){if(b.tag===31){var j=b.memoizedState;if(j===null&&(b=b.alternate,b!==null&&(j=b.memoizedState)),j!==null)return j.dehydrated}return null}r(d,"getActivityInstanceFromFiber");function u(b){if(l(b)!==b)throw Error(i(188))}r(u,"assertIsMounted");function h(b){var j=b.alternate;if(!j){if(j=l(b),j===null)throw Error(i(188));return j!==b?null:b}for(var A=b,B=j;;){var H=A.return;if(H===null)break;var ee=H.alternate;if(ee===null){if(B=H.return,B!==null){A=B;continue}break}if(H.child===ee.child){for(ee=H.child;ee;){if(ee===A)return u(H),b;if(ee===B)return u(H),j;ee=ee.sibling}throw Error(i(188))}if(A.return!==B.return)A=H,B=ee;else{for(var ke=!1,He=H.child;He;){if(He===A){ke=!0,A=H,B=ee;break}if(He===B){ke=!0,B=H,A=ee;break}He=He.sibling}if(!ke){for(He=ee.child;He;){if(He===A){ke=!0,A=ee,B=H;break}if(He===B){ke=!0,B=ee,A=H;break}He=He.sibling}if(!ke)throw Error(i(189))}}if(A.alternate!==B)throw Error(i(190))}if(A.tag!==3)throw Error(i(188));return A.stateNode.current===A?b:j}r(h,"findCurrentFiberUsingSlowPath");function p(b){var j=b.tag;if(j===5||j===26||j===27||j===6)return b;for(b=b.child;b!==null;){if(j=p(b),j!==null)return j;b=b.sibling}return null}r(p,"findCurrentHostFiberImpl");var f=Object.assign,x=Symbol.for("react.element"),g=Symbol.for("react.transitional.element"),v=Symbol.for("react.portal"),y=Symbol.for("react.fragment"),k=Symbol.for("react.strict_mode"),w=Symbol.for("react.profiler"),N=Symbol.for("react.consumer"),S=Symbol.for("react.context"),C=Symbol.for("react.forward_ref"),_=Symbol.for("react.suspense"),R=Symbol.for("react.suspense_list"),I=Symbol.for("react.memo"),T=Symbol.for("react.lazy"),E=Symbol.for("react.activity"),L=Symbol.for("react.memo_cache_sentinel"),O=Symbol.iterator;function P(b){return b===null||typeof b!="object"?null:(b=O&&b[O]||b["@@iterator"],typeof b=="function"?b:null)}r(P,"getIteratorFn");var Q=Symbol.for("react.client.reference");function D(b){if(b==null)return null;if(typeof b=="function")return b.$$typeof===Q?null:b.displayName||b.name||null;if(typeof b=="string")return b;switch(b){case y:return"Fragment";case w:return"Profiler";case k:return"StrictMode";case _:return"Suspense";case R:return"SuspenseList";case E:return"Activity"}if(typeof b=="object")switch(b.$$typeof){case v:return"Portal";case S:return b.displayName||"Context";case N:return(b._context.displayName||"Context")+".Consumer";case C:var j=b.render;return b=b.displayName,b||(b=j.displayName||j.name||"",b=b!==""?"ForwardRef("+b+")":"ForwardRef"),b;case I:return j=b.displayName||null,j!==null?j:D(b.type)||"Memo";case T:j=b._payload,b=b._init;try{return D(b(j))}catch{}}return null}r(D,"getComponentNameFromType");var F=Array.isArray,z=n.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE,K=a.__DOM_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE,U={pending:!1,data:null,method:null,action:null},q=[],G=-1;function se(b){return{current:b}}r(se,"createCursor");function Z(b){0>G||(b.current=q[G],q[G]=null,G--)}r(Z,"pop");function ie(b,j){G++,q[G]=b.current,b.current=j}r(ie,"push");var J=se(null),re=se(null),oe=se(null),V=se(null);function X(b,j){switch(ie(oe,j),ie(re,b),ie(J,null),j.nodeType){case 9:case 11:b=(b=j.documentElement)&&(b=b.namespaceURI)?oee(b):0;break;default:if(b=j.tagName,j=j.namespaceURI)j=oee(j),b=lee(j,b);else switch(b){case"svg":b=1;break;case"math":b=2;break;default:b=0}}Z(J),ie(J,b)}r(X,"pushHostContainer");function Y(){Z(J),Z(re),Z(oe)}r(Y,"popHostContainer");function ae(b){b.memoizedState!==null&&ie(V,b);var j=J.current,A=lee(j,b.type);j!==A&&(ie(re,b),ie(J,A))}r(ae,"pushHostContext");function ne(b){re.current===b&&(Z(J),Z(re)),V.current===b&&(Z(V),j2._currentValue=U)}r(ne,"popHostContext");var ce,he;function pe(b){if(ce===void 0)try{throw Error()}catch(A){var j=A.stack.trim().match(/\n( *(at )?)/);ce=j&&j[1]||"",he=-1<A.stack.indexOf(`
706
+ `)}z!==k&&(n.textContent=z,k=z)}r(R,"step");function I(){const P=d>0&&u>0;if(a.matches){o&&(o=!1,s.current!==null&&cancelAnimationFrame(s.current),s.current=null),P&&S();return}if(!i||!P){o&&(o=!1,s.current!==null&&cancelAnimationFrame(s.current),s.current=null);return}o||(o=!0,l=0,s.current=requestAnimationFrame(R))}r(I,"syncLoop");const T=new ResizeObserver(()=>{const P=Fge(n);h=P.w,p=P.h,N(),I()});T.observe(n);const E=r(()=>{i=document.visibilityState!=="hidden",I()},"onVisibilityChange");document.addEventListener("visibilitychange",E);const L=r(()=>{I()},"onMotionChange");a.addEventListener("change",L);const O=Fge(n);return h=O.w,p=O.h,N(),I(),()=>{o=!1,s.current!==null&&cancelAnimationFrame(s.current),T.disconnect(),document.removeEventListener("visibilitychange",E),a.removeEventListener("change",L)}},[]),(0,t.jsx)("pre",{ref:e,className:"w-full h-full m-0 p-0 overflow-hidden text-muted-foreground/60 select-none leading-none",style:{fontSize:"var(--text-micro)",fontFamily:"monospace"},"aria-hidden":"true"})}r(Zxs,"AsciiArtAnimation");function Jxs({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(Jxs,"PaperclipLockup");function Xxs(){const e=kt(),s=Yn(),[n]=hi(),[a,i]=(0,m.useState)("sign_in"),[o,l]=(0,m.useState)(""),[c,d]=(0,m.useState)(""),[u,h]=(0,m.useState)(""),[p,f]=(0,m.useState)(null),x="auth-error",g=(0,m.useMemo)(()=>f3e(n.get("next")||Vxs()||"/"),[n]),v=te({queryKey:M.health,queryFn:r(()=>Iu.get(),"queryFn"),retry:!1}),{data:y,isLoading:k,error:w}=te({queryKey:M.auth.session,queryFn:r(()=>Ma.getSession(),"queryFn"),retry:!1});(0,m.useEffect)(()=>{y&&(CG(),s(g,{replace:!0}))},[y,s,g]);const N=je({mutationFn:r(async()=>{if(a==="sign_in"){await Ma.signInEmail({email:c.trim(),password:u});return}await Ma.signUpEmail({name:o.trim(),email:c.trim(),password:u})},"mutationFn"),onSuccess:r(async()=>{f(null),await e.invalidateQueries({queryKey:M.auth.session}),await e.invalidateQueries({queryKey:M.health}),await e.resetQueries({queryKey:M.companies.all}),s(g,{replace:!0})},"onSuccess"),onError:r(C=>{f(C instanceof Error?C.message:"Authentication failed")},"onError")}),S=c.trim().length>0&&u.trim().length>0&&(a==="sign_in"||o.trim().length>0&&u.trim().length>=8);return v.isLoading||k||y?(0,t.jsx)("div",{className:"fixed inset-0 flex items-center justify-center",children:(0,t.jsx)(nh,{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)(_G,{cloud:v.data.cloud,returnTo:g}):(0,t.jsxs)("div",{className:"fixed inset-0 flex bg-background",children:[(0,t.jsx)("div",{className:"absolute top-4 right-4 z-10",children:(0,t.jsx)(Lk,{})}),(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)(Jxs,{className:"h-5 w-auto"})}),(0,t.jsx)("h1",{className:"text-xl font-semibold",children:a==="sign_in"?"Sign in to Paperclip":"Create your Paperclip account"}),(0,t.jsx)("p",{className:"mt-1 text-sm text-muted-foreground",children:a==="sign_in"?"Use your email and password to access this instance.":"Create an account for this instance. Email confirmation is not required in v1."}),(0,t.jsxs)("form",{className:"mt-6 space-y-4",method:"post",action:a==="sign_up"?"/api/auth/sign-up/email":"/api/auth/sign-in/email",onSubmit:r(C=>{if(C.preventDefault(),!N.isPending){if(!S){f("Please fill in all required fields.");return}N.mutate()}},"onSubmit"),children:[a==="sign_up"&&(0,t.jsxs)("div",{children:[(0,t.jsx)("label",{htmlFor:"name",className:"text-xs text-muted-foreground mb-1 block",children:"Name"}),(0,t.jsx)("input",{id:"name",name:"name",className:"w-full rounded-md border border-border bg-transparent px-3 py-2 text-sm outline-none focus:ring-1 focus:ring-ring placeholder:text-muted-foreground/50",value:o,onChange:r(C=>l(C.target.value),"onChange"),autoComplete:"name",required:!0,"aria-required":"true","aria-invalid":p?!0:void 0,"aria-describedby":p?x:void 0,autoFocus:!0})]}),(0,t.jsxs)("div",{children:[(0,t.jsx)("label",{htmlFor:"email",className:"text-xs text-muted-foreground mb-1 block",children:"Email"}),(0,t.jsx)("input",{id:"email",name:"email",className:"w-full rounded-md border border-border bg-transparent px-3 py-2 text-sm outline-none focus:ring-1 focus:ring-ring placeholder:text-muted-foreground/50",type:"email",value:c,onChange:r(C=>d(C.target.value),"onChange"),autoComplete:"username",required:!0,"aria-required":"true","aria-invalid":p?!0:void 0,"aria-describedby":p?x:void 0,autoFocus:a==="sign_in"})]}),(0,t.jsxs)("div",{children:[(0,t.jsx)("label",{htmlFor:"password",className:"text-xs text-muted-foreground mb-1 block",children:"Password"}),(0,t.jsx)("input",{id:"password",name:"password",className:"w-full rounded-md border border-border bg-transparent px-3 py-2 text-sm outline-none focus:ring-1 focus:ring-ring placeholder:text-muted-foreground/50",type:"password",value:u,onChange:r(C=>h(C.target.value),"onChange"),autoComplete:a==="sign_in"?"current-password":"new-password",required:!0,"aria-required":"true","aria-invalid":p?!0:void 0,"aria-describedby":p?x:void 0})]}),p&&(0,t.jsx)("p",{id:x,role:"alert",className:"text-xs text-destructive",children:p}),(0,t.jsx)($,{type:"submit",disabled:N.isPending,"aria-disabled":!S||N.isPending,className:`w-full ${!S&&!N.isPending?"opacity-50":""}`,children:N.isPending?"Working…":a==="sign_in"?"Sign In":"Create Account"})]}),(0,t.jsxs)("div",{className:"mt-5 text-sm text-muted-foreground",children:[a==="sign_in"?"Need an account?":"Already have an account?"," ",(0,t.jsx)("button",{type:"button",className:"font-medium text-foreground underline underline-offset-2",onClick:r(()=>{f(null),i(a==="sign_in"?"sign_up":"sign_in")},"onClick"),children:a==="sign_in"?"Create one":"Sign in"})]})]})}),(0,t.jsx)("div",{className:"hidden md:block w-1/2 overflow-hidden",children:(0,t.jsx)(Zxs,{})})]})}r(Xxs,"AuthPage");function egs(){const e=kt(),s=ga(),[n]=hi(),a=(s.token??"").trim(),i=(n.get("code")??"").trim(),o=(0,m.useMemo)(()=>`/board-claim/${encodeURIComponent(a)}${i?`?code=${encodeURIComponent(i)}`:""}`,[a,i]),l=te({queryKey:M.auth.session,queryFn:r(()=>Ma.getSession(),"queryFn"),retry:!1}),c=te({queryKey:["board-claim",a,i],queryFn:r(()=>ir.getBoardClaimStatus(a,i),"queryFn"),enabled:a.length>0&&i.length>0,retry:!1}),d=je({mutationFn:r(()=>ir.claimBoard(a,i),"mutationFn"),onSuccess:r(async()=>{await e.invalidateQueries({queryKey:M.auth.session}),await e.invalidateQueries({queryKey:M.health}),await e.invalidateQueries({queryKey:M.companies.all}),await e.invalidateQueries({queryKey:M.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)(nn,{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)(nn,{className:"block p-6",children:[(0,t.jsx)("h1",{className:"text-lg font-semibold",children:"Board ownership claimed"}),(0,t.jsx)("p",{className:"mt-2 text-sm text-muted-foreground",children:"This instance is now linked to your authenticated user."}),(0,t.jsx)($,{asChild:!0,className:"mt-4",children:(0,t.jsx)(Ke,{to:"/",children:"Open board"})})]})}):l.data?(0,t.jsx)("div",{className:"mx-auto max-w-xl py-10",children:(0,t.jsxs)(nn,{className:"block p-6",children:[(0,t.jsx)("h1",{className:"text-xl font-semibold",children:"Claim Board ownership"}),(0,t.jsx)("p",{className:"mt-2 text-sm text-muted-foreground",children:"This will promote your user to instance admin and migrate organization ownership access from local trusted mode."}),d.error&&(0,t.jsx)("p",{className:"mt-3 text-sm text-destructive",children:d.error instanceof Error?d.error.message:"Failed to claim board ownership"}),(0,t.jsx)($,{className:"mt-5",onClick:r(()=>d.mutate(),"onClick"),disabled:d.isPending,children:d.isPending?"Claiming…":"Claim ownership"})]})}):(0,t.jsx)("div",{className:"mx-auto max-w-xl py-10",children:(0,t.jsxs)(nn,{className:"block p-6",children:[(0,t.jsx)("h1",{className:"text-lg font-semibold",children:"Sign in required"}),(0,t.jsx)("p",{className:"mt-2 text-sm text-muted-foreground",children:"Sign in or create an account, then return to this page to claim Board ownership."}),(0,t.jsx)($,{asChild:!0,className:"mt-4",children:(0,t.jsx)(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(egs,"BoardClaimPage");function zge({origin:e}){const[s,n]=(0,m.useState)(!1);let a;try{const i=new URL(e);i.origin==="https://claude.ai"?a="/brands/claude-color.svg":["https://chatgpt.com","https://chat.openai.com","https://openai.com"].includes(i.origin)&&(a="/brands/codex-color.svg")}catch{}return(0,t.jsxs)("div",{className:"flex items-center gap-2 text-sm text-muted-foreground",children:[a&&!s?(0,t.jsx)("img",{src:a,alt:"",className:"size-4 shrink-0 object-contain",referrerPolicy:"no-referrer",crossOrigin:"anonymous",onError:r(()=>n(!0),"onError")}):(0,t.jsx)(gm,{className:"size-4 shrink-0","aria-hidden":"true"}),(0,t.jsx)("bdi",{className:"min-w-0 break-all",children:e})]})}r(zge,"ClientOrigin");function qge({agentPairingOnly:e=!1}={}){const{id:s=""}=ga();return(0,t.jsx)(xDe,{id:s,agentPairingOnly:e},s)}r(qge,"McpConnectPage");function tgs({initialCode:e}={}){const[s,n]=(0,m.useState)(e??new URLSearchParams(window.location.search).get("user_code")??""),[a,i]=(0,m.useState)(s);return a?(0,t.jsx)(xDe,{id:a,device:!0,onEditCode:r(()=>i(""),"onEditCode")},a):(0,t.jsx)("div",{className:"mx-auto max-w-xl py-10",children:(0,t.jsxs)(nn,{className:"space-y-4 p-6",children:[(0,t.jsxs)("div",{className:"flex items-center gap-3",children:[(0,t.jsx)(kl,{className:"size-8 shrink-0"}),(0,t.jsx)("h1",{className:"min-w-0 text-xl font-semibold",children:"Connect your assistant to Paperclip"})]}),(0,t.jsxs)("form",{className:"space-y-4",onSubmit:r(o=>{o.preventDefault(),i(s.trim())},"onSubmit"),children:[(0,t.jsx)("label",{htmlFor:"device-code",className:"text-sm",children:"Enter the code shown by your assistant"}),(0,t.jsx)(dt,{id:"device-code",autoComplete:"off",value:s,onChange:r(o=>n(o.target.value),"onChange"),required:!0,maxLength:12}),(0,t.jsx)("div",{className:"flex justify-end",children:(0,t.jsx)($,{type:"submit",children:"Continue"})})]})]})})}r(tgs,"McpDevicePage");function xDe({id:e,device:s=!1,agentPairingOnly:n=!1,onEditCode:a}){const i=n?"/dot-mcp/requests":"/mcp/requests",[o,l]=(0,m.useState)(""),[c,d]=(0,m.useState)(""),[u,h]=(0,m.useState)(null),[p,f]=(0,m.useState)(""),[x,g]=(0,m.useState)(!0),[v,y]=(0,m.useState)(null),k=te({queryKey:[s?"mcp-device":n?"dot-mcp-request":"mcp-request",e],queryFn:r(()=>we.get(s?`/mcp/device?user_code=${encodeURIComponent(e)}`:`${i}/${encodeURIComponent(e)}`),"queryFn"),retry:!1}),w=k.data;(0,m.useEffect)(()=>{if(h(null),f(""),!w?.agentConnection||s||!/^[A-Za-z0-9_-]{32}$/.test(c.trim()))return;let Q=!0;return we.post(`${i}/${encodeURIComponent(e)}/dot-pairing/preview`,{pairingCode:c.trim()}).then(D=>{Q&&h(D)}).catch(D=>{Q&&f(D instanceof Error?D.message:"Unable to verify this pairing code.")}),()=>{Q=!1}},[e,s,i,w?.agentConnection,c]);const N=w?.requestedCompanyId??(o||w?.companies[0]?.id||"");(0,m.useEffect)(()=>{!o&&!w?.requestedCompanyId&&w?.companies[0]&&l(w.companies[0].id)},[o,w]);const S=w?.clientName.trim(),C=S&&!/^(assistant|mcp client)$/i.test(S)?S:"your assistant",_=w?.clientOrigin||w?.redirectOrigin,R=w?.companies.find(Q=>Q.id===N),I=!!(!w?.agentConnection&&R?.canWrite&&x),T=!!(w?.requestedWrite&&I),E=!!(w?.requestedConfigure&&I),L=je({mutationFn:r(Q=>we.post(s?"/mcp/device/consent":`/mcp/requests/${encodeURIComponent(e)}/consent`,{decision:Q,companyId:N||void 0,allowWrites:Q==="approve"&&T,allowConfiguration:Q==="approve"&&E,...s?{userCode:e}:{}}),"mutationFn"),onSuccess:r(({redirectUrl:Q,status:D})=>{s&&D?y(D):Q&&window.location.assign(Q)},"onSuccess")}),O=je({mutationFn:r(()=>we.post(`${i}/${encodeURIComponent(e)}/dot-pairing`,{pairingCode:c.trim()}),"mutationFn"),onSuccess:r(({redirectUrl:Q})=>{d(""),window.location.assign(Q)},"onSuccess")});if(v)return(0,t.jsx)("div",{className:"mx-auto max-w-xl py-10",children:(0,t.jsxs)(nn,{className:"block space-y-4 p-6",children:[(0,t.jsx)(kl,{className:"size-8"}),(0,t.jsx)("h1",{className:"text-xl font-semibold",children:v==="approved"?"Access approved":"Connection declined"}),(0,t.jsx)("p",{className:"text-sm",children:v==="approved"?"Return to your assistant. It will finish connecting automatically.":"No access was granted. You can start a new connection from your assistant."}),(0,t.jsx)($,{variant:"outline",asChild:!0,children:(0,t.jsx)(Ke,{to:"/",children:"Back to Paperclip"})})]})});const P=s?`/mcp-device?user_code=${encodeURIComponent(e)}`:`${n?"/dot-connect":"/mcp-connect"}/${e}`;return(0,t.jsx)("div",{className:"mx-auto max-w-xl py-10",children:(0,t.jsxs)(nn,{className:"block space-y-4 p-6",children:[(0,t.jsxs)("div",{className:"flex items-center gap-3",children:[(0,t.jsx)(kl,{className:"size-8 shrink-0 text-foreground",role:"img","aria-label":"Paperclip"}),(0,t.jsxs)("h1",{className:"min-w-0 break-words text-xl font-semibold",children:["Connect ",(0,t.jsx)("bdi",{children:C})," to Paperclip"]})]}),_&&(0,t.jsx)(zge,{origin:_},_),!s&&w?.redirectOrigin&&w.redirectOrigin!==_&&(0,t.jsx)(zge,{origin:w.redirectOrigin},w.redirectOrigin),s&&(0,t.jsxs)("p",{className:"text-sm",children:["Confirm this matches the code shown by your assistant: ",(0,t.jsx)("strong",{className:"font-mono",children:e.toUpperCase()})]}),k.isPending&&(0,t.jsx)("p",{className:"text-sm text-muted-foreground",children:"Loading connection request…"}),k.error&&(0,t.jsxs)("p",{className:"text-sm text-destructive",children:[k.error.message," Start a new connection from your assistant."]}),s&&k.error&&(0,t.jsx)($,{variant:"outline",onClick:a,children:"Enter a different code"}),w?.agentConnection&&!s&&(0,t.jsxs)("form",{className:"space-y-3",onSubmit:r(Q=>{Q.preventDefault(),O.mutate()},"onSubmit"),children:[(0,t.jsx)("p",{className:"text-sm",children:"Enter the one-use code from your Dot setup prompt to review this agent’s access. Access is granted when you click “Connect Dot with pairing code”."}),(0,t.jsx)("label",{htmlFor:"dot-pairing-code",className:"text-sm",children:"Pairing code"}),(0,t.jsx)(dt,{id:"dot-pairing-code",type:"password",autoComplete:"off",value:c,onChange:r(Q=>{h(null),f(""),d(Q.target.value)},"onChange"),required:!0,maxLength:32}),u&&(0,t.jsxs)("dl",{className:"space-y-2 rounded-md border border-border p-3 text-sm",children:[(0,t.jsxs)("div",{children:[(0,t.jsx)("dt",{className:"text-muted-foreground",children:"Company"}),(0,t.jsxs)("dd",{children:[u.company.name," ",(0,t.jsxs)("span",{className:"text-xs text-muted-foreground",children:["(",u.company.id,")"]})]})]}),(0,t.jsxs)("div",{children:[(0,t.jsx)("dt",{className:"text-muted-foreground",children:"Agent"}),(0,t.jsxs)("dd",{children:[u.agent.name," ",(0,t.jsxs)("span",{className:"text-xs text-muted-foreground",children:["(",u.agent.id,")"]})]})]}),(0,t.jsxs)("div",{children:[(0,t.jsx)("dt",{className:"text-muted-foreground",children:"Permissions"}),(0,t.jsx)("dd",{children:u.permissions})]}),(0,t.jsxs)("div",{children:[(0,t.jsx)("dt",{className:"text-muted-foreground",children:"Access duration"}),(0,t.jsx)("dd",{children:u.accessDuration})]})]}),p&&(0,t.jsx)("p",{role:"alert",className:"text-sm text-destructive",children:p}),O.error&&(0,t.jsx)("p",{role:"alert",className:"text-sm text-destructive",children:O.error.message}),(0,t.jsx)("div",{className:"flex justify-end",children:(0,t.jsx)($,{type:"submit",disabled:!u||!/^[A-Za-z0-9_-]{32}$/.test(c.trim())||O.isPending,children:O.isPending?"Connecting…":"Connect Dot with pairing code"})})]}),w&&(0,t.jsx)(t.Fragment,{children:w.requiresSignIn?(0,t.jsx)($,{asChild:!0,children:(0,t.jsx)(Ke,{to:`/auth?next=${encodeURIComponent(P)}`,children:"Sign in / Create account"})}):(0,t.jsxs)(t.Fragment,{children:[w.requestedCompanyId?(0,t.jsxs)("div",{className:"flex items-center gap-4 rounded-md border border-border p-4",children:[R&&(0,t.jsx)(tg,{companyName:R.name,logoUrl:R.logoUrl,className:"size-14 shrink-0 rounded-lg text-xl"}),(0,t.jsxs)("div",{className:"min-w-0 space-y-1",children:[(0,t.jsx)("p",{className:"text-xs text-muted-foreground",children:"Organization"}),R?(0,t.jsx)("p",{className:"break-words text-lg font-semibold",children:R.name}):(0,t.jsx)("p",{className:"text-sm text-destructive",children:"The selected organization is no longer available to this account. Cancel and reconnect from your assistant to choose an organization you can access."})]})]}):(0,t.jsxs)("fieldset",{className:"space-y-2",disabled:L.isPending,children:[(0,t.jsx)("legend",{className:"mb-2 text-sm font-medium",children:"Organization"}),w.companies.map(Q=>(0,t.jsxs)("label",{className:"flex items-center gap-3 rounded-md border border-border p-3 text-sm",children:[(0,t.jsx)("input",{type:"radio",name:"company","aria-label":Q.name,value:Q.id,checked:N===Q.id,onChange:r(()=>l(Q.id),"onChange")}),(0,t.jsx)(tg,{companyName:Q.name,logoUrl:Q.logoUrl,className:"size-12 shrink-0 rounded-lg"}),(0,t.jsx)("span",{className:"min-w-0 break-words font-medium",children:Q.name})]},Q.id)),!w.companies.length&&(0,t.jsx)("p",{className:"text-sm text-muted-foreground",children:"This account has no available organizations. Ask an organization owner to add you, then reconnect from your assistant."})]}),(0,t.jsx)("p",{className:"text-sm",children:w.agentConnection?"Connect Dot as a Paperclip agent. Pair it with an agent after connecting; assigned work uses that agent’s permissions.":"Read all of your Paperclip data"}),(w.requestedWrite||w.requestedConfigure)&&!w.agentConnection&&(0,t.jsxs)("label",{htmlFor:"mcp-allow-writes",className:"flex items-start gap-3 text-sm leading-6",children:[(0,t.jsx)("span",{className:"flex h-6 shrink-0 items-center",children:(0,t.jsx)(ri,{id:"mcp-allow-writes",checked:I,disabled:!R?.canWrite||L.isPending,onCheckedChange:r(Q=>g(Q===!0),"onCheckedChange")})}),(0,t.jsx)("span",{children:"Write all of your Paperclip data"})]}),R&&!R.canWrite&&(0,t.jsx)("p",{className:"text-sm text-muted-foreground",children:"Your role in this organization is read-only."}),L.error&&(0,t.jsx)("p",{className:"text-sm text-destructive",children:L.error.message}),(0,t.jsxs)("div",{className:"flex items-center justify-between gap-3",children:[(0,t.jsx)($,{variant:"outline",disabled:L.isPending,onClick:r(()=>L.mutate("deny"),"onClick"),children:"Cancel"}),(0,t.jsx)($,{className:"h-auto min-h-10 min-w-0 shrink whitespace-normal",disabled:!R||w.agentConnection&&!R.canWrite||L.isPending,onClick:r(()=>L.mutate("approve"),"onClick"),children:L.isPending?"Connecting…":w.agentConnection?"Connect Dot agent":"Connect organization"})]})]})})]})})}r(xDe,"McpConnectRequest");function sgs(){const e=kt(),s=te({queryKey:["mcp-connections"],queryFn:r(()=>we.get("/mcp/connections"),"queryFn"),retry:!1}),n=s.data?.filter(i=>!i.revokedAt),a=je({mutationFn:r(i=>we.delete(`/mcp/connections/${i}`),"mutationFn"),onSuccess:r((i,o)=>(e.setQueryData(["mcp-connections"],l=>l?.filter(c=>c.id!==o)),e.invalidateQueries({queryKey:["mcp-connections"]})),"onSuccess")});return(0,t.jsxs)("div",{className:"mx-auto max-w-xl space-y-4 py-10",children:[(0,t.jsx)("h1",{className:"text-xl font-semibold",children:"Assistant connections"}),(0,t.jsx)("p",{className:"text-sm text-muted-foreground",children:"Revoking a connection stops its future tool calls. Work already delegated continues under your organization’s normal controls."}),s.isPending&&(0,t.jsx)("p",{className:"text-sm",children:"Loading connections…"}),(s.error||a.error)&&(0,t.jsx)("p",{className:"text-sm text-destructive",children:(s.error??a.error)?.message}),n?.length===0&&(0,t.jsx)("p",{className:"text-sm",children:"No assistant connections."}),n?.map(i=>(0,t.jsxs)(nn,{className:"block space-y-2 p-4",children:[(0,t.jsx)("h2",{className:"font-medium",children:(0,t.jsx)(So,{name:r8(i),avatarUrl:i.user?.image,initials:uv(i.user?.name??"You")})}),(0,t.jsxs)("p",{className:"text-sm text-muted-foreground",children:["Organization: ",i.companyName]}),(0,t.jsx)("p",{className:"text-sm",children:i.scopes.includes("paperclip:agent")?"Dot agent connection":i.scopes.includes("paperclip:write")?"Read and edit work":"Read only"}),i.scopes.includes("paperclip:configure")&&(0,t.jsx)("p",{className:"text-sm",children:"Configure agents, projects and skills"}),(0,t.jsx)($,{variant:"outline",disabled:a.isPending,onClick:r(()=>a.mutate(i.id),"onClick"),children:"Revoke connection"})]},i.id)),(0,t.jsx)(Ke,{className:"text-sm underline",to:"/",children:"Back to Paperclip"})]})}r(sgs,"AssistantConnectionsPage");function ngs(){const e=kt(),s=ga(),[n]=hi(),a=(s.id??"").trim(),i=(n.get("token")??"").trim(),o=(0,m.useMemo)(()=>`/cli-auth/${encodeURIComponent(a)}${i?`?token=${encodeURIComponent(i)}`:""}`,[a,i]),l=te({queryKey:M.auth.session,queryFn:r(()=>Ma.getSession(),"queryFn"),retry:!1}),c=te({queryKey:["cli-auth-challenge",a,i],queryFn:r(()=>ir.getCliAuthChallenge(a,i),"queryFn"),enabled:a.length>0&&i.length>0,retry:!1}),d=je({mutationFn:r(()=>ir.approveCliAuthChallenge(a,i),"mutationFn"),onSuccess:r(async()=>{await e.invalidateQueries({queryKey:M.auth.session}),await c.refetch()},"onSuccess")}),u=je({mutationFn:r(()=>ir.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)(nn,{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)(nn,{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)(nn,{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)(nn,{className:"block p-6",children:[(0,t.jsx)("h1",{className:"text-xl font-semibold",children:"Sign in required"}),(0,t.jsx)("p",{className:"mt-2 text-sm text-muted-foreground",children:"Sign in or create an account, then return to this page to approve the CLI access request."}),(0,t.jsx)($,{asChild:!0,className:"mt-4",children:(0,t.jsx)(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)(nn,{className:"block p-6",children:[(0,t.jsx)("h1",{className:"text-xl font-semibold",children:"Approve Paperclip CLI access"}),(0,t.jsx)("p",{className:"mt-2 text-sm text-muted-foreground",children:"A local Paperclip CLI process is requesting board access to this instance."}),(0,t.jsxs)("div",{className:"mt-5 space-y-3 text-sm",children:[(0,t.jsxs)("div",{children:[(0,t.jsx)("div",{className:"text-muted-foreground",children:"Command"}),(0,t.jsx)("div",{className:"font-mono text-foreground",children:h.command})]}),(0,t.jsxs)("div",{children:[(0,t.jsx)("div",{className:"text-muted-foreground",children:"Client"}),(0,t.jsx)("div",{className:"text-foreground",children:h.clientName??"paperclip-pro cli"})]}),(0,t.jsxs)("div",{children:[(0,t.jsx)("div",{className:"text-muted-foreground",children:"Requested access"}),(0,t.jsx)("div",{className:"text-foreground",children:h.requestedAccess==="instance_admin_required"?"Instance admin":"Board"})]}),h.requestedCompanyName&&(0,t.jsxs)("div",{children:[(0,t.jsx)("div",{className:"text-muted-foreground",children:"Requested organization"}),(0,t.jsx)("div",{className:"text-foreground",children:h.requestedCompanyName})]})]}),(d.error||u.error)&&(0,t.jsx)("p",{className:"mt-4 text-sm text-destructive",children:(d.error??u.error)instanceof Error?(d.error??u.error).message:"Failed to update CLI auth challenge"}),!h.canApprove&&(0,t.jsx)("p",{className:"mt-4 text-sm text-destructive",children:"This challenge requires instance-admin access. Sign in with an instance admin account to approve it."}),(0,t.jsxs)("div",{className:"mt-5 flex gap-3",children:[(0,t.jsx)($,{onClick:r(()=>d.mutate(),"onClick"),disabled:!h.canApprove||d.isPending||u.isPending,children:d.isPending?"Approving...":"Approve CLI access"}),(0,t.jsx)($,{type:"button",variant:"outline",onClick:r(()=>u.mutate(),"onClick"),disabled:d.isPending||u.isPending,children:u.isPending?"Cancelling...":"Cancel"})]})]})}):(0,t.jsx)("div",{className:"mx-auto max-w-xl py-10 text-sm text-destructive",children:"CLI auth challenge unavailable."})}r(ngs,"CliAuthPage");var rgs=J$e.filter(e=>e!=="paperclip_runner"),Uge=new Set(["claude_local","codex_local","gemini_local","kimi_local","opencode_local","pi_local","cursor"]);function ags(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(ags,"readNestedString");var M1="w-full border border-zinc-800 bg-zinc-950 px-3 py-2 text-sm text-zinc-100 outline-none focus:border-zinc-500",Kge="border border-zinc-800 bg-zinc-950/95 p-6",Qge="flex-1 border px-3 py-2 text-sm transition-colors";function igs(e){return e?e.charAt(0).toUpperCase()+e.slice(1):null}r(igs,"formatHumanRole");function gDe(e){if(!e||typeof e!="object")return null;const s=e.code;return typeof s=="string"&&s.trim().length>0?s:null}r(gDe,"getAuthErrorCode");function ogs(e){if(!(e instanceof Error))return null;const s=e.message.trim();return s.length>0?s:null}r(ogs,"getAuthErrorMessage");function lgs(e,s,n){const a=gDe(e),i=ogs(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(lgs,"mapInviteAuthFeedback");function Wge(e){return!!(e&&typeof e=="object"&&"bootstrapAccepted"in e)}r(Wge,"isBootstrapAcceptancePayload");function cgs(e,s){return!e||typeof e!="object"||s?!1:e.status==="approved"}r(cgs,"isApprovedHumanJoinPayload");function TQ({companyDisplayName:e,companyLogoUrl:s,className:n}){return(0,t.jsx)(tg,{companyName:e,logoUrl:s,logoFit:"contain",className:n})}r(TQ,"InviteCompanyLogo");function Hge({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)(TQ,{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(Hge,"AwaitingJoinApprovalPanel");function dgs(){const e=kt(),s=Yn(),{setSelectedCompanyId:n}=ps(),a=(ga().token??"").trim(),[i,o]=(0,m.useState)("sign_up"),[l,c]=(0,m.useState)(""),[d,u]=(0,m.useState)(""),[h,p]=(0,m.useState)(""),[f,x]=(0,m.useState)(""),[g,v]=(0,m.useState)("claude_local"),[y,k]=(0,m.useState)(""),[w,N]=(0,m.useState)(null),[S,C]=(0,m.useState)(null),[_,R]=(0,m.useState)(null),[I,T]=(0,m.useState)(!1),E="invite-auth-error",L=te({queryKey:M.health,queryFn:r(()=>Iu.get(),"queryFn"),retry:!1}),O=te({queryKey:M.auth.session,queryFn:r(()=>Ma.getSession(),"queryFn"),retry:!1}),P=te({queryKey:M.access.invite(a),queryFn:r(()=>ir.getInvite(a),"queryFn"),enabled:a.length>0,retry:!1}),Q=KQ({enabled:!!O.data&&!!P.data?.companyId,staleTime:0}),D=L.data?.deploymentMode!=="local_trusted"?Q.isFetchedAfterMount:!0,F=D?Q.data?.companies??[]:[];(0,m.useEffect)(()=>{a&&Oge(a)},[a]),(0,m.useEffect)(()=>{T(!1)},[a]),(0,m.useEffect)(()=>{if(!D)return;const ge=Q.data?.companies;!ge||!P.data?.companyId||ge.some(Ee=>Ee.id===P.data.companyId)&&KT(a)},[Q.data,P.data,D,a]);const z=P.data,K=!!O.data&&!!z?.companyId&&!D,U=!!z?.companyId&&F.some(ge=>ge.id===z?.companyId),q=z?.companyName?.trim()||"this Paperclip company",G=z?.companyLogoUrl?.trim()||null,se=z?.invitedByUserName?.trim()||null,Z=z?.inviteMessage?.trim()||null,ie=igs(z?.humanRole),J=z?.joinRequestStatus??null,re=z?.joinRequestType??null,oe=re==="human"&&(J==="pending_approval"||J==="approved"),V=L.data?.deploymentMode==="authenticated"&&!O.data&&z?.allowedJoinTypes!=="agent",X=z?.inviteType!=="bootstrap_ceo"&&z?.allowedJoinTypes==="agent",Y=!!O.data&&!X&&z?.inviteType!=="bootstrap_ceo"&&(!J||oe)&&!K&&!U&&!w&&S===null,ae=O.data?.user.name?.trim()||O.data?.user.email?.trim()||"this account",ne=d.trim().length>0&&h.trim().length>0&&(i==="sign_in"||l.trim().length>0&&h.trim().length>=8),ce=je({mutationFn:r(async()=>{if(!z)throw new Error("Invite not found");if(K)throw new Error("Checking your organization access. Try again in a moment.");if(U)throw new Error("This account already belongs to the organization.");return z.inviteType==="bootstrap_ceo"||z.allowedJoinTypes!=="agent"?ir.acceptInvite(a,{requestType:"human"}):ir.acceptInvite(a,{requestType:"agent",agentName:f.trim(),adapterType:g,capabilities:y.trim()||null})},"mutationFn"),onSuccess:r(async ge=>{C(null),KT(a);const Ee=Wge(ge);N({kind:Ee?"bootstrap":"join",payload:ge}),await e.invalidateQueries({queryKey:M.auth.session}),await e.invalidateQueries({queryKey:M.access.currentBoardAccess}),await e.invalidateQueries({queryKey:M.companies.all}),z?.companyId&&cgs(ge,X)&&(n(z.companyId,{source:"manual"}),s("/",{replace:!0}))},"onSuccess"),onError:r(ge=>{C(ge instanceof Error?ge.message:"Failed to accept invite")},"onError")});(0,m.useEffect)(()=>{!Y||I||ce.isPending||(T(!0),C(null),ce.mutate())},[ce,I,Y]);const he=je({mutationFn:r(async()=>{if(i==="sign_in"){await Ma.signInEmail({email:d.trim(),password:h});return}await Ma.signUpEmail({name:l.trim(),email:d.trim(),password:h})},"mutationFn"),onSuccess:r(async()=>{R(null),Oge(a),await e.invalidateQueries({queryKey:M.auth.session}),await e.invalidateQueries({queryKey:M.health}),await e.invalidateQueries({queryKey:M.access.currentBoardAccess});const{companies:ge}=await $Be(e);if(z?.companyId&&ge.some(Ee=>Ee.id===z.companyId)){KT(a),n(z.companyId,{source:"manual"}),s("/",{replace:!0});return}if(!(!z||z.inviteType!=="bootstrap_ceo"))try{Wge(await ce.mutateAsync())&&s("/",{replace:!0})}catch{return}},"onSuccess"),onError:r(ge=>{const Ee=lgs(ge,i,d);gDe(ge)==="USER_ALREADY_EXISTS_USE_ANOTHER_EMAIL"&&(o("sign_in"),p("")),R(Ee)},"onError")}),pe=(0,m.useMemo)(()=>z?U?"Open organization":z.inviteType==="bootstrap_ceo"?"Accept invite":X?"Submit request":O.data?"Accept invite":"Continue":"Continue",[z,U,O.data,X]);if(!a)return(0,t.jsx)("div",{className:"mx-auto max-w-xl py-10 text-sm text-destructive",children:"Invalid invite token."});if(P.isLoading||L.isLoading||O.isLoading)return(0,t.jsx)("div",{className:"mx-auto max-w-xl py-10 text-sm text-muted-foreground",children:"Loading invite..."});if(K)return(0,t.jsx)("div",{className:"mx-auto max-w-xl py-10 text-sm text-muted-foreground",children:"Checking your access..."});if(P.error||!z)return(0,t.jsx)("div",{className:"mx-auto max-w-xl py-10",children:(0,t.jsxs)("div",{className:"border border-border bg-card p-6","data-testid":"invite-error",children:[(0,t.jsx)("h1",{className:"text-lg font-semibold",children:"Invite not available"}),(0,t.jsx)("p",{className:"mt-2 text-sm text-muted-foreground",children:"This invite may be expired, revoked, or already used."})]})});if(J==="approved"&&re==="human"&&U)return(0,t.jsx)("div",{className:"mx-auto max-w-xl py-10 text-sm text-muted-foreground",children:"Opening organization..."});if(J==="pending_approval"&&!oe)return(0,t.jsx)(Hge,{companyDisplayName:q,companyLogoUrl:G,invitedByUserName:se});if(J&&!oe)return(0,t.jsx)("div",{className:"mx-auto max-w-xl py-10",children:(0,t.jsxs)("div",{className:"border border-border bg-card p-6","data-testid":"invite-error",children:[(0,t.jsx)("h1",{className:"text-lg font-semibold",children:"Invite not available"}),(0,t.jsx)("p",{className:"mt-2 text-sm text-muted-foreground",children:J==="rejected"?"This join request was not approved.":"This invite has already been used."})]})});if(w?.kind==="bootstrap")return(0,t.jsx)("div",{className:"min-h-screen bg-zinc-950 px-6 py-12 text-zinc-100",children:(0,t.jsxs)("div",{className:"mx-auto max-w-md border border-zinc-800 bg-zinc-950 p-6",children:[(0,t.jsx)("h1",{className:"text-lg font-semibold",children:"Bootstrap complete"}),(0,t.jsx)("div",{className:"mt-4",children:(0,t.jsx)($,{asChild:!0,className:"rounded-none",children:(0,t.jsx)(Ke,{to:"/",children:"Open board"})})})]})});if(w?.kind==="join"){const ge=w.payload,Ee=typeof ge.claimSecret=="string"?ge.claimSecret:null,de=typeof ge.claimApiKeyPath=="string"?ge.claimApiKeyPath:null,Ne=ags(ge.onboarding,["textInstructions","url"]);return!X&&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)(TQ,{companyDisplayName:q,companyLogoUrl:G,className:"h-12 w-12 border border-zinc-800 rounded-none"}),(0,t.jsx)("h1",{className:"text-lg font-semibold",children:"You joined the organization"})]}),(0,t.jsx)("div",{className:"mt-4",children:(0,t.jsx)($,{asChild:!0,className:"w-full rounded-none",children:(0,t.jsx)(Ke,{to:"/",children:"Open board"})})})]})}):(0,t.jsx)(Hge,{companyDisplayName:q,companyLogoUrl:G,invitedByUserName:se,claimSecret:Ee,claimApiKeyPath:de,onboardingTextUrl:Ne})}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:`${Kge} space-y-6`,children:[(0,t.jsxs)("div",{className:"flex items-start gap-4",children:[(0,t.jsx)(TQ,{companyDisplayName:q,companyLogoUrl:G,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:z.inviteType==="bootstrap_ceo"?"Set up Paperclip":`Join ${q}`}),(0,t.jsx)("p",{className:"mt-2 max-w-2xl text-sm leading-6 text-zinc-300",children:X?"Review the invite details, then submit the agent information below to start the join request.":V?"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:q})]}),(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:X?"Agent join request":ie??"Organization access"})]}),(0,t.jsxs)("div",{className:"border border-zinc-800 p-3",children:[(0,t.jsx)("div",{className:"text-xs uppercase tracking-(--tracking-caps) text-zinc-500",children:"Invite expires"}),(0,t.jsx)("div",{className:"mt-1 text-sm text-zinc-100",children:Gd(z.expiresAt)})]})]}),Z?(0,t.jsxs)("div",{className:"border border-amber-500/40 bg-amber-500/10 p-4",children:[(0,t.jsx)("div",{className:"text-xs uppercase tracking-(--tracking-caps) text-amber-200/80",children:"Message from inviter"}),(0,t.jsx)("p",{className:"mt-2 text-sm leading-6 text-amber-50",children:Z})]}):null,O.data?(0,t.jsxs)("div",{className:"border border-emerald-500/40 bg-emerald-500/10 p-4 text-sm text-emerald-50",children:["Signed in as ",(0,t.jsx)("span",{className:"font-medium",children:ae}),"."]}):null]}),(0,t.jsx)("section",{className:`${Kge} h-fit`,children:X?(0,t.jsxs)("div",{className:"space-y-4",children:[(0,t.jsxs)("div",{children:[(0,t.jsx)("h2",{className:"text-lg font-semibold",children:"Submit agent details"}),(0,t.jsxs)("p",{className:"mt-1 text-sm text-zinc-400",children:["This invite will create an approval request for a new agent in ",q,"."]})]}),(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:M1,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:M1,value:g,onChange:r(ge=>v(ge.target.value),"onChange"),children:rgs.map(ge=>(0,t.jsxs)("option",{value:ge,disabled:!Uge.has(ge),children:[wf(ge),Uge.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:M1,rows:4,value:y,onChange:r(ge=>k(ge.target.value),"onChange")})]}),S?(0,t.jsx)("p",{className:"text-xs text-red-400",children:S}):null,(0,t.jsx)($,{className:"w-full rounded-none",disabled:ce.isPending||f.trim().length===0,onClick:r(()=>ce.mutate(),"onClick"),children:ce.isPending?"Working...":pe})]}):V?(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 ${q}.`:"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:`${Qge} ${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:`${Qge} ${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(!ne){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:M1,value:l,onChange:r(ge=>{c(ge.target.value),R(null)},"onChange"),autoComplete:"name",required:!0,"aria-required":"true","aria-invalid":_?.tone==="error"?!0:void 0,"aria-describedby":_?E:void 0,autoFocus:!0})]}):null,(0,t.jsxs)("label",{className:"block text-sm",htmlFor:"invite-email",children:[(0,t.jsx)("span",{className:"mb-1 block text-zinc-400",children:"Email"}),(0,t.jsx)("input",{id:"invite-email",name:"email",type:"email",className:M1,value:d,onChange:r(ge=>{u(ge.target.value),R(null)},"onChange"),autoComplete:"username",required:!0,"aria-required":"true","aria-invalid":_?.tone==="error"?!0:void 0,"aria-describedby":_?E:void 0,autoFocus:i==="sign_in"})]}),(0,t.jsxs)("label",{className:"block text-sm",htmlFor:"invite-password",children:[(0,t.jsx)("span",{className:"mb-1 block text-zinc-400",children:"Password"}),(0,t.jsx)("input",{id:"invite-password",name:"password",type:"password",className:M1,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":_?.tone==="error"?!0:void 0,"aria-describedby":_?E:void 0})]}),_?(0,t.jsx)("p",{id:E,role:"alert",className:`text-xs ${_.tone==="info"?"text-amber-300":"text-red-400"}`,children:_.message}):null,(0,t.jsx)($,{type:"submit",className:"w-full rounded-none",disabled:he.isPending,"aria-disabled":!ne||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:U?"Already in this organization":Y?"Completing organization access":z.inviteType==="bootstrap_ceo"?"Accept bootstrap invite":"Accept organization invite"}),(0,t.jsx)("p",{className:"mt-1 text-sm text-zinc-400",children:Y?`Granting your access to ${q}.`:U?`This account already belongs to ${q}.`:`This will ${z.inviteType==="bootstrap_ceo"?"finish setting up Paperclip":`grant or complete your access to ${q}`}.`})]}),S?(0,t.jsx)("p",{className:"text-xs text-red-400",children:S}):null,Y?(0,t.jsx)("div",{className:"text-sm text-zinc-400",children:ce.isPending?"Submitting request...":"Finishing sign-in..."}):(0,t.jsx)($,{className:"w-full rounded-none",disabled:ce.isPending,onClick:r(()=>{if(U&&z.companyId){KT(a),n(z.companyId,{source:"manual"}),s("/",{replace:!0});return}ce.mutate()},"onClick"),children:ce.isPending?"Working...":pe})]})})]})})})}r(dgs,"InviteLandingPage");var ugs=15e3,mgs={parent:"Parent task",child:"Sub-task",blocked_by:"Blocked by",blocks:"Blocks"};function hgs(){(0,m.useEffect)(()=>{const e=document.createElement("meta");return e.name="robots",e.content="noindex",document.head.appendChild(e),()=>e.remove()},[])}r(hgs,"useNoIndexMeta");function RQ(e,s){const n=`/s/${encodeURIComponent(e)}`;return s?`${n}/issues/${encodeURIComponent(s)}`:n}r(RQ,"sharePath");var pgs=/^(?:https?:\/\/[^/]+)?\/api\/attachments\/([^/?#]+)\/content(?:[?#].*)?$/i;function fgs(e,s){const n=pgs.exec(s.trim());return n?`/api/public/share/${encodeURIComponent(e)}/attachments/${n[1]}/content`:null}r(fgs,"publicShareImageSrc");function yC({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(yC,"Section");function EQ({actor:e}){return(0,t.jsx)(So,{name:e.name,avatarUrl:e.iconUrl,size:"sm"})}r(EQ,"ActorIdentity");function LQ({value:e}){return(0,t.jsx)("time",{dateTime:e,title:yr(e),className:"text-xs text-muted-foreground",children:xr(e)})}r(LQ,"Timestamp");function xgs({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(xgs,"ActiveRunPill");function bDe({attachments:e}){return(0,t.jsx)(jH,{children:e.map(s=>{const n=dSe({name:s.filename,url:s.url,contentType:s.contentType,byteSize:s.byteSize}),a=n.icon,i=wH(s.byteSize);return(0,t.jsxs)(xH,{size:"sm",children:[(0,t.jsx)(gH,{children:(0,t.jsx)(a,{"aria-hidden":!0})}),(0,t.jsxs)(bH,{children:[(0,t.jsx)(vH,{className:"max-w-48",children:s.filename}),(0,t.jsx)(yH,{className:"max-w-48",children:i?`${n.label} · ${i}`:n.label})]}),(0,t.jsx)(iSe,{"aria-label":`Download ${s.filename}`,render:(0,t.jsx)("a",{href:s.url,download:s.filename,rel:"noreferrer"})})]},s.id)})})}r(bDe,"AttachmentList");function ggs({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)(ao,{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:mgs[e.relation]}),e.navigable?(0,t.jsx)(Md,{to:n?RQ(s,e.id):RQ(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(ggs,"RelatedIssueRow");function bgs({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)(EQ,{actor:e.author}),(0,t.jsx)(LQ,{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)(EQ,{actor:e.author}),(0,t.jsx)(LQ,{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)(bDe,{attachments:e.attachments}):null]})}r(bgs,"TimelineEntry");function vgs({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)(ei,{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)(LQ,{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)(Ui,{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(vgs,"DocumentCard");function ygs({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)(Dn,{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)(Ui,{className:"h-3.5 w-3.5","aria-hidden":!0}),"Download"]}):null]})}r(ygs,"WorkProductRow");function Vge({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(Vge,"CenteredNotice");function jgs({view:e,token:s}){const{company:n,issue:a}=e,i=(0,m.useCallback)(o=>fgs(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)(tg,{companyName:n.name,logoUrl:n.logoUrl,logoFit:"contain",className:"h-8 w-8 shrink-0 rounded-md"}),(0,t.jsx)("span",{className:"min-w-0 truncate text-sm font-medium",children:n.name}),(0,t.jsx)("span",{className:"ml-auto shrink-0 text-xs text-muted-foreground",children:"Read-only view"})]})}),(0,t.jsxs)("main",{className:"mx-auto max-w-3xl space-y-8 px-4 py-5",children:[e.isSharedRoot?null:(0,t.jsxs)(Md,{to:RQ(s),className:"inline-flex items-center gap-1.5 text-sm text-muted-foreground hover:text-foreground",children:[(0,t.jsx)(wl,{className:"h-4 w-4","aria-hidden":!0}),"Back to main task"]}),(0,t.jsxs)("section",{className:"space-y-3",children:[(0,t.jsxs)("div",{className:"flex flex-wrap items-center gap-x-2 text-xs text-muted-foreground",children:[a.identifier?(0,t.jsx)("span",{children:a.identifier}):null,a.projectName?(0,t.jsx)("span",{children:a.projectName}):null]}),(0,t.jsx)("h1",{className:"break-words text-xl font-semibold",children:a.title}),(0,t.jsxs)("div",{className:"flex flex-wrap items-center gap-3",children:[(0,t.jsx)(C0,{status:a.status}),(0,t.jsx)(Tve,{priority:a.priority,showLabel:!0}),a.assignee?(0,t.jsx)(EQ,{actor:a.assignee}):null,e.activeRun?(0,t.jsx)(xgs,{agentName:e.activeRun.agentName}):null]}),(0,t.jsxs)("p",{className:"text-xs text-muted-foreground",children:["Created ",yr(a.createdAt)," · Updated ",xr(a.updatedAt),a.completedAt?` · Completed ${yr(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)(yC,{title:"Related tasks",children:(0,t.jsx)("ul",{className:"space-y-2",children:e.related.map(o=>(0,t.jsx)(ggs,{related:o,token:s,isSharedRoot:e.isSharedRoot},`${o.relation}:${o.id}`))})}):null,e.documents.length>0?(0,t.jsx)(yC,{title:"Documents",children:(0,t.jsx)("div",{className:"space-y-2",children:e.documents.map(o=>(0,t.jsx)(vgs,{document:o,resolveImageSrc:i},o.key))})}):null,e.attachments.length>0?(0,t.jsx)(yC,{title:"Attachments",children:(0,t.jsx)(bDe,{attachments:e.attachments})}):null,e.workProducts.length>0?(0,t.jsx)(yC,{title:"Work products",children:(0,t.jsx)("ul",{className:"space-y-2",children:e.workProducts.map(o=>(0,t.jsx)(ygs,{product:o},o.id))})}):null,(0,t.jsx)(yC,{title:"Activity",children:e.comments.length>0?(0,t.jsx)("ol",{className:"space-y-3",children:e.comments.map(o=>(0,t.jsx)(bgs,{comment:o,resolveImageSrc:i},o.id))}):(0,t.jsx)("p",{className:"text-sm text-muted-foreground",children:"No updates yet."})})]})]})}r(jgs,"PublicIssueShareContent");function Gge(){const{token:e="",issueId:s}=ga();hgs();const n=WUe.test(e),a=te({queryKey:M.publicShare.view(e,s??null),queryFn:r(()=>s?Yk.getPublicShareIssue(e,s):Yk.getPublicShare(e),"queryFn"),enabled:n,retry:!1,refetchOnWindowFocus:!0,refetchInterval:r(i=>i.state.data?.activeRun?ugs:!1,"refetchInterval")});return!n||a.data===null?(0,t.jsx)(Vge,{title:"This link is not available",body:"It may have been revoked, or the address is incomplete."}):a.data?(0,t.jsx)(jgs,{view:a.data,token:e}):a.isError?(0,t.jsx)(Vge,{title:"Couldn't load this page",body:"Check your connection and try again.",action:(0,t.jsx)($,{variant:"outline",size:"sm",className:"mt-2",onClick:r(()=>{a.refetch()},"onClick"),children:"Try again"})}):(0,t.jsx)("div",{className:"h-dvh overflow-y-auto px-4 py-6","aria-busy":"true",children:(0,t.jsxs)("div",{className:"mx-auto max-w-3xl space-y-4",children:[(0,t.jsx)(wn,{className:"h-6 w-1/2"}),(0,t.jsx)(wn,{className:"h-4 w-1/3"}),(0,t.jsx)(wn,{className:"h-24 w-full"})]})})}r(Gge,"PublicIssueSharePage");function wgs(){const{selectedCompany:e,selectedCompanyId:s}=ps(),{setBreadcrumbs:n}=Wn(),{pushToast:a}=Ii(),i=kt(),[o,l]=(0,m.useState)("pending_approval"),[c,d]=(0,m.useState)("all");(0,m.useEffect)(()=>{n([{label:e?.name??"Organization",href:"/dashboard"},{label:"Inbox",href:"/inbox"},{label:"Join Requests"}])},[e?.name,n]);const u=te({queryKey:M.access.joinRequests(s??"",`${o}:${c}`),queryFn:r(()=>ir.listJoinRequests(s,o,c==="all"?void 0:c),"queryFn"),enabled:!!s}),h=je({mutationFn:r(f=>ir.approveJoinRequest(s,f),"mutationFn"),onSuccess:r(async()=>{await i.invalidateQueries({queryKey:M.access.joinRequests(s,`${o}:${c}`)}),await i.invalidateQueries({queryKey:M.access.companyMembers(s)}),await i.invalidateQueries({queryKey:M.access.companyUserDirectory(s)}),a({title:"Join request approved",tone:"success"})},"onSuccess")}),p=je({mutationFn:r(f=>ir.rejectJoinRequest(s,f),"mutationFn"),onSuccess:r(async()=>{await i.invalidateQueries({queryKey:M.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 sn&&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)(KQe,{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)(nn,{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)(nn,{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)(it,{variant:f.status==="pending_approval"?"secondary":f.status==="approved"?"outline":"destructive",children:f.status.replace("_"," ")}),(0,t.jsx)(it,{variant:"outline",children:f.requestType}),f.adapterType?(0,t.jsx)(it,{variant:"outline",children:f.adapterType}):null]}),(0,t.jsxs)("div",{children:[(0,t.jsx)("div",{className:"text-base font-medium",children:f.requestType==="human"?f.requesterUser?.name||f.requestEmailSnapshot||f.requestingUserId||"Unknown human requester":f.agentName||"Unknown agent requester"}),(0,t.jsx)("div",{className:"text-sm text-muted-foreground",children:f.requestType==="human"?f.requesterUser?.email||f.requestEmailSnapshot||f.requestingUserId:f.capabilities||f.requestIp})]})]}),f.status==="pending_approval"?(0,t.jsxs)("div",{className:"flex gap-2",children:[(0,t.jsx)($,{variant:"outline",onClick:r(()=>p.mutate(f.id),"onClick"),disabled:p.isPending,children:"Reject"}),(0,t.jsx)($,{onClick:r(()=>h.mutate(f.id),"onClick"),disabled:h.isPending,children:"Approve"})]}):null]}),(0,t.jsxs)("div",{className:"mt-4 grid gap-3 text-sm text-muted-foreground md:grid-cols-2",children:[(0,t.jsxs)("div",{className:"rounded-lg border border-border bg-background px-3 py-2",children:[(0,t.jsx)("div",{className:"text-xs font-medium uppercase tracking-wide",children:"Invite context"}),(0,t.jsx)("div",{className:"mt-2",children:f.invite?`${f.invite.allowedJoinTypes} join invite${f.invite.humanRole?` • default role ${f.invite.humanRole}`:""}`:"Invite metadata unavailable"}),f.invite?.inviteMessage?(0,t.jsx)("div",{className:"mt-2 text-foreground",children:f.invite.inviteMessage}):null]}),(0,t.jsxs)("div",{className:"rounded-lg border border-border bg-background px-3 py-2",children:[(0,t.jsx)("div",{className:"text-xs font-medium uppercase tracking-wide",children:"Request details"}),(0,t.jsxs)("div",{className:"mt-2",children:["Submitted ",new Date(f.createdAt).toLocaleString()]}),(0,t.jsxs)("div",{children:["Source IP ",f.requestIp]}),f.requestType==="agent"&&f.capabilities?(0,t.jsx)("div",{children:f.capabilities}):null]})]})]},f.id))})]})}r(wgs,"JoinRequestQueue");var kgs=(0,m.lazy)(()=>fd(()=>import("./CompanyExport-DrqpQn4r.js").then(e=>({default:e.CompanyExport})),__vite__mapDeps([6,5,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25]))),Ngs=(0,m.lazy)(()=>fd(()=>import("./Agents.production-B1mPIEb7.js").then(e=>({default:e.Agents})),__vite__mapDeps([26,5,7,9,8,27,28,29,30,31,15,32,33,34,35,36,19,37,23,24,25]))),Sgs=(0,m.lazy)(()=>fd(()=>import("./Routines.production-DPgOqbb-.js").then(e=>({default:e.Routines})),__vite__mapDeps([38,5,7,8,9,39,28,40,33,16,17,21,41,14,15,27,29,30,31,42,43,44,45,46,10,11,12,34,47,48,49,35,50,51,20,36,52,53,54,37,55,23,24,25,32,22,19]))),Yge=(0,m.lazy)(()=>fd(()=>import("./RoutineDetail.production-CmuV9Cac.js").then(e=>({default:e.RoutineDetail})),__vite__mapDeps([56,5,7,8,9,39,28,40,33,16,17,21,41,14,15,27,29,30,31,42,43,44,45,46,10,11,12,34,47,48,49,35,50,51,20,36,52,53,54,37,55,23,24,25,57,58,22,19]))),Cgs=(0,m.lazy)(()=>fd(()=>import("./CompanySkills.production-DJUAhDX_.js").then(e=>({default:e.CompanySkills})),__vite__mapDeps([59,5,7,8,9,27,28,29,30,31,15,42,16,40,33,17,21,44,14,45,46,32,10,11,12,60,58,52,25,48,18,13,19,61,49,22,23,24]))),_gs=(0,m.lazy)(()=>fd(()=>import("./CompanyActivity.production-DOfFPFa0.js").then(e=>({default:e.CompanyActivity})),__vite__mapDeps([62,5,7,8,9,31,15,32,33,47,45,30,16,48,22,19,52,53,54,55,23]))),Ags=(0,m.lazy)(()=>fd(()=>import("./Terminal-wWKDl4EU.js").then(e=>({default:e.Terminal})),__vite__mapDeps([63,5,7,8,9,40,33,28,16,17,21,43,52,53,37]))),Igs=(0,m.lazy)(()=>fd(()=>import("./OrgChart.production-Ser8k3BP.js").then(e=>({default:e.OrgChart})),__vite__mapDeps([64,5,7,8,9,31,15,50,51,19,55,23,24,25])));function sb({children:e}){return(0,t.jsx)(m.Suspense,{fallback:(0,t.jsx)(nh,{}),children:e})}r(sb,"ProductionSurface");function Tgs(e,s){const n=e&&s;return(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)(nt,{index:!0,element:(0,t.jsx)(_n,{to:"dashboard",replace:!0})}),(0,t.jsx)(nt,{path:"dashboard",element:(0,t.jsx)(NTt,{})}),(0,t.jsx)(nt,{path:"dashboard/live",element:(0,t.jsx)(STt,{})}),(0,t.jsx)(nt,{path:"timeline",element:e?(0,t.jsx)(Cp,{to:"/activity/timeline"}):(0,t.jsx)(s6e,{})}),(0,t.jsx)(nt,{path:"onboarding",element:(0,t.jsx)(jDe,{})}),(0,t.jsx)(nt,{path:"companies",element:(0,t.jsx)(uRt,{})}),(0,t.jsx)(nt,{path:"company/settings",element:(0,t.jsx)(prs,{})}),(0,t.jsx)(nt,{path:"company/settings/connections",element:(0,t.jsx)(grs,{})}),(0,t.jsx)(nt,{path:"company/settings/environments",element:(0,t.jsx)(_n,{to:"/company/settings/instance/environments",replace:!0})}),(0,t.jsx)(nt,{path:"company/settings/cloud-upstream",element:(0,t.jsx)(_n,{to:"/company/export",replace:!0})}),(0,t.jsxs)(nt,{element:(0,t.jsx)(b0,{pageKey:"company.members"}),children:[(0,t.jsx)(nt,{path:"company/settings/members",element:(0,t.jsx)(ias,{})}),(0,t.jsx)(nt,{path:"company/settings/access",element:(0,t.jsx)(oas,{})})]}),(0,t.jsx)(nt,{element:(0,t.jsx)(b0,{pageKey:"company.invites"}),children:(0,t.jsx)(nt,{path:"company/settings/invites",element:(0,t.jsx)(_n,{to:"/company/settings/members?tab=invites",replace:!0})})}),(0,t.jsx)(nt,{element:(0,t.jsx)(b0,{pageKey:"company.export"}),children:(0,t.jsx)(nt,{path:"company/export/*",element:(0,t.jsx)(m.Suspense,{fallback:(0,t.jsx)(nh,{}),children:(0,t.jsx)(kgs,{})})})}),(0,t.jsx)(nt,{element:(0,t.jsx)(pyt,{}),children:(0,t.jsx)(nt,{element:(0,t.jsx)(b0,{pageKey:"company.import"}),children:(0,t.jsx)(nt,{path:"company/import",element:(0,t.jsx)(vfs,{})})})}),(0,t.jsx)(nt,{element:(0,t.jsx)(b0,{pageKey:"company.secrets"}),children:(0,t.jsx)(nt,{path:"company/settings/secrets",element:(0,t.jsx)(pps,{})})}),(0,t.jsx)(nt,{path:"company/settings/tools",element:(0,t.jsx)(Xge,{})}),(0,t.jsx)(nt,{path:"company/settings/tools/:tab",element:(0,t.jsx)(Xge,{})}),(0,t.jsx)(nt,{path:"tools",element:(0,t.jsx)(ebe,{})}),(0,t.jsx)(nt,{path:"tools/:tab",element:(0,t.jsx)(ebe,{})}),(0,t.jsx)(nt,{path:"apps",element:(0,t.jsx)(sos,{})}),(0,t.jsx)(nt,{path:"apps/assistant-connection",element:(0,t.jsx)(Ois,{})}),(0,t.jsx)(nt,{path:"apps/browse",element:(0,t.jsx)(_n,{to:"/apps",replace:!0})}),(0,t.jsx)(nt,{path:"apps/connections",element:(0,t.jsx)(_n,{to:"/apps",replace:!0})}),(0,t.jsx)(nt,{path:"apps/byo",element:(0,t.jsx)(q7e,{byoOnly:!0})}),(0,t.jsx)(nt,{path:"apps/vercel-connect",element:(0,t.jsx)(Zge,{credentialSource:"vercel_connect"})}),(0,t.jsx)(nt,{path:"apps/connect",element:(0,t.jsx)(Zge,{})}),(0,t.jsx)(nt,{path:"apps/chat/connect",element:(0,t.jsx)(AT,{children:(0,t.jsx)(jls,{})})}),(0,t.jsx)(nt,{path:"apps/chat/:endpointId",element:(0,t.jsx)(AT,{children:(0,t.jsx)(_n,{to:"settings",replace:!0})})}),(0,t.jsx)(nt,{path:"apps/chat/:endpointId/reviews/:reviewId",element:(0,t.jsx)(AT,{children:(0,t.jsx)(Hfe,{})})}),(0,t.jsx)(nt,{path:"apps/chat/:endpointId/:tab",element:(0,t.jsx)(AT,{children:(0,t.jsx)(Hfe,{})})}),(0,t.jsx)(nt,{path:"apps/connect/:appKey",element:(0,t.jsx)(_n,{to:"/apps",replace:!0})}),(0,t.jsx)(nt,{path:"apps/connect/:appKey/:stage",element:(0,t.jsx)(_n,{to:"/apps",replace:!0})}),(0,t.jsx)(nt,{path:"apps/review",element:(0,t.jsx)(ids,{})}),(0,t.jsx)(nt,{path:"apps/attention",element:(0,t.jsx)(_n,{to:"/apps",replace:!0})}),(0,t.jsx)(nt,{path:"apps/gateways",element:(0,t.jsx)(Jfe,{})}),(0,t.jsx)(nt,{path:"apps/gateways/:gatewayId",element:(0,t.jsx)(_n,{to:"overview",replace:!0})}),(0,t.jsx)(nt,{path:"apps/gateways/:gatewayId/:tab",element:(0,t.jsx)(Dds,{})}),(0,t.jsx)(nt,{path:"apps/advanced",element:(0,t.jsx)(ffe,{})}),(0,t.jsx)(nt,{path:"apps/advanced/gateways",element:(0,t.jsx)(Jfe,{})}),(0,t.jsx)(nt,{path:"apps/advanced/profiles/new",element:(0,t.jsx)(yfe,{mode:"new"})}),(0,t.jsx)(nt,{path:"apps/advanced/profiles/:profileId/edit",element:(0,t.jsx)(yfe,{mode:"edit"})}),(0,t.jsx)(nt,{path:"apps/advanced/profiles/:profileId",element:(0,t.jsx)(Cis,{})}),(0,t.jsx)(nt,{path:"apps/advanced/audit",element:(0,t.jsx)(_n,{to:"/apps",replace:!0})}),(0,t.jsx)(nt,{path:"apps/advanced/run-your-own",element:(0,t.jsx)(_n,{to:"/apps",replace:!0})}),(0,t.jsx)(nt,{path:"apps/advanced/:tab",element:(0,t.jsx)(ffe,{})}),(0,t.jsx)(nt,{path:"apps/app/:applicationId",element:(0,t.jsx)(Gfe,{})}),(0,t.jsx)(nt,{path:"apps/app/:applicationId/:tab",element:(0,t.jsx)(Gfe,{})}),(0,t.jsx)(nt,{path:"apps/:connectionId",element:(0,t.jsx)(_n,{to:"permissions",replace:!0})}),(0,t.jsx)(nt,{path:"apps/:connectionId/:tab",element:(0,t.jsx)(qos,{})}),(0,t.jsx)(nt,{path:"company/settings/instance",element:(0,t.jsx)(_n,{to:"/company/settings",replace:!0})}),(0,t.jsx)(nt,{element:(0,t.jsx)(b0,{pageKey:"instance.profile"}),children:(0,t.jsx)(nt,{path:"company/settings/instance/profile",element:(0,t.jsx)(Cxs,{})})}),(0,t.jsx)(nt,{path:"company/settings/instance/general",element:(0,t.jsx)(_n,{to:"/company/settings",replace:!0})}),(0,t.jsx)(nt,{path:"company/settings/instance/heartbeats",element:(0,t.jsx)(_n,{to:"/company/settings",replace:!0})}),(0,t.jsxs)(nt,{element:(0,t.jsx)(b0,{pageKey:"instance.environments"}),children:[(0,t.jsx)(nt,{path:"company/settings/instance/environments",element:(0,t.jsx)(xB,{})}),(0,t.jsx)(nt,{path:"company/settings/instance/environments/new",element:(0,t.jsx)(xB,{mode:"create"})}),(0,t.jsx)(nt,{path:"company/settings/instance/environments/:environmentId/edit",element:(0,t.jsx)(xB,{mode:"edit"})})]}),(0,t.jsx)(nt,{element:(0,t.jsx)(b0,{pageKey:"instance.access"}),children:(0,t.jsx)(nt,{path:"company/settings/instance/access",element:(0,t.jsx)(bxs,{})})}),(0,t.jsx)(nt,{element:(0,t.jsx)(b0,{pageKey:"instance.experimental"}),children:(0,t.jsx)(nt,{path:"company/settings/instance/experimental",element:(0,t.jsx)(gxs,{})})}),(0,t.jsxs)(nt,{element:(0,t.jsx)(b0,{pageKey:"instance.plugins"}),children:[(0,t.jsx)(nt,{path:"company/settings/instance/plugins",element:(0,t.jsx)(Axs,{})}),(0,t.jsx)(nt,{path:"company/settings/instance/plugins/:pluginId",element:(0,t.jsx)(Ixs,{})})]}),(0,t.jsx)(nt,{element:(0,t.jsx)(b0,{pageKey:"instance.adapters"}),children:(0,t.jsx)(nt,{path:"company/settings/instance/adapters",element:(0,t.jsx)(Mge,{})})}),(0,t.jsx)(nt,{path:"company/settings/:settingsRoutePath/*",element:(0,t.jsx)(Xrs,{})}),(0,t.jsx)(nt,{path:"skills/sources",element:(0,t.jsx)(Nxe,{})}),(0,t.jsx)(nt,{path:"skills/sources/:sourceId",element:(0,t.jsx)(Nxe,{})}),(0,t.jsx)(nt,{path:"skills/studio",element:(0,t.jsx)(zB,{})}),(0,t.jsx)(nt,{path:"skills/studio/new",element:(0,t.jsx)(zB,{})}),(0,t.jsx)(nt,{path:"skills/studio/:skillId",element:(0,t.jsx)(zB,{})}),(0,t.jsx)(nt,{path:"skills/:skillId/studio",element:(0,t.jsx)(vDe,{})}),(0,t.jsx)(nt,{path:"skills/*",element:e?(0,t.jsx)(Zus,{}):(0,t.jsx)(sb,{children:(0,t.jsx)(Cgs,{})})}),(0,t.jsx)(nt,{path:"settings",element:(0,t.jsx)($y,{})}),(0,t.jsx)(nt,{path:"settings/*",element:(0,t.jsx)($y,{})}),(0,t.jsx)(nt,{path:"plugins/:pluginId",element:(0,t.jsx)(Pge,{})}),(0,t.jsx)(nt,{path:"org",element:e?(0,t.jsx)(_n,{to:"/agents/all",replace:!0}):(0,t.jsx)(sb,{children:(0,t.jsx)(Igs,{})})}),(0,t.jsx)(nt,{path:"agents",element:(0,t.jsx)(_n,{to:"/agents/all",replace:!0})}),fY.map(a=>(0,t.jsx)(nt,{path:`agents/${a}`,element:e?(0,t.jsx)(a6t,{}):(0,t.jsx)(sb,{children:(0,t.jsx)(Ngs,{})})},a)),(0,t.jsx)(nt,{path:"agents/new",element:(0,t.jsx)(Hxs,{})}),(0,t.jsx)(nt,{path:"agents/:agentId",element:(0,t.jsx)($$,{})}),(0,t.jsx)(nt,{path:"agents/:agentId/:tab",element:(0,t.jsx)($$,{})}),(0,t.jsx)(nt,{path:"agents/:agentId/runs/:runId",element:(0,t.jsx)($$,{})}),(0,t.jsx)(nt,{path:"projects",element:(0,t.jsx)(C8t,{})}),(0,t.jsx)(nt,{path:"projects/:projectId",element:(0,t.jsx)(Xv,{})}),(0,t.jsx)(nt,{path:"projects/:projectId/overview",element:(0,t.jsx)(Xv,{})}),(0,t.jsx)(nt,{path:"projects/:projectId/issues",element:(0,t.jsx)(Xv,{})}),(0,t.jsx)(nt,{path:"projects/:projectId/issues/:filter",element:(0,t.jsx)(Xv,{})}),(0,t.jsx)(nt,{element:(0,t.jsx)(FD,{}),children:(0,t.jsx)(nt,{path:"projects/:projectId/workspaces/:workspaceId",element:(0,t.jsx)(_Mt,{})})}),(0,t.jsx)(nt,{path:"projects/:projectId/workspaces",element:(0,t.jsx)(Xv,{})}),(0,t.jsx)(nt,{path:"projects/:projectId/configuration",element:(0,t.jsx)(Xv,{})}),(0,t.jsx)(nt,{path:"projects/:projectId/budget",element:(0,t.jsx)(Xv,{})}),(0,t.jsx)(nt,{element:(0,t.jsx)(FD,{}),children:(0,t.jsx)(nt,{path:"workspaces",element:(0,t.jsx)(TMt,{})})}),(0,t.jsx)(nt,{path:"terminal",element:(0,t.jsx)(sb,{children:(0,t.jsx)(Ags,{})})}),(0,t.jsx)(nt,{path:"issues",element:(0,t.jsx)(e7t,{})}),(0,t.jsx)(nt,{path:"tasks",element:(0,t.jsx)(_n,{to:"/issues",replace:!0})}),(0,t.jsx)(nt,{path:"search",element:(0,t.jsx)(y7t,{})}),n?(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)(nt,{path:"issues/all",element:(0,t.jsx)(Th,{view:"all"})}),(0,t.jsx)(nt,{path:"issues/active",element:(0,t.jsx)(Th,{view:"active"})}),(0,t.jsx)(nt,{path:"issues/backlog",element:(0,t.jsx)(Th,{view:"backlog"})}),(0,t.jsx)(nt,{path:"issues/done",element:(0,t.jsx)(Th,{view:"done"})}),(0,t.jsx)(nt,{path:"issues/recent",element:(0,t.jsx)(Th,{view:"recent"})})]}):(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)(nt,{path:"issues/all",element:(0,t.jsx)(_n,{to:"/issues",replace:!0})}),(0,t.jsx)(nt,{path:"issues/active",element:(0,t.jsx)(_n,{to:"/issues",replace:!0})}),(0,t.jsx)(nt,{path:"issues/backlog",element:(0,t.jsx)(_n,{to:"/issues",replace:!0})}),(0,t.jsx)(nt,{path:"issues/done",element:(0,t.jsx)(_n,{to:"/issues",replace:!0})}),(0,t.jsx)(nt,{path:"issues/recent",element:(0,t.jsx)(_n,{to:"/issues",replace:!0})})]}),(0,t.jsx)(nt,{path:"chats",element:(0,t.jsx)(EKt,{})}),(0,t.jsx)(nt,{path:"chats/:agentRef",element:(0,t.jsx)(MKt,{})}),(0,t.jsx)(nt,{path:"issues/:issueId",element:(0,t.jsx)(_Kt,{})}),null,(0,t.jsx)(nt,{path:"routines",element:e?(0,t.jsx)(hQt,{}):(0,t.jsx)(sb,{children:(0,t.jsx)(Sgs,{})})}),(0,t.jsx)(nt,{path:"cases",element:(0,t.jsx)(Qie,{children:(0,t.jsx)(Myt,{})})}),(0,t.jsx)(nt,{path:"cases/:caseIdentifier",element:(0,t.jsx)(Qie,{children:(0,t.jsx)(v1t,{})})}),(0,t.jsx)(nt,{path:"pixels-office",element:(0,t.jsx)(hyt,{children:(0,t.jsx)(KJt,{})})}),(0,t.jsx)(nt,{path:"status",element:(0,t.jsx)(Wie,{children:(0,t.jsx)(r0e,{})})}),(0,t.jsx)(nt,{path:"status/:cardId",element:(0,t.jsx)(Wie,{children:(0,t.jsx)(r0e,{})})}),(0,t.jsx)(nt,{path:"status-cards",element:(0,t.jsx)(tbe,{})}),(0,t.jsx)(nt,{path:"status-cards/:cardId",element:(0,t.jsx)(tbe,{})}),(0,t.jsx)(nt,{path:"review-queue",element:(0,t.jsx)(Vg,{children:(0,t.jsx)(RHt,{})})}),(0,t.jsx)(nt,{path:"learnings",element:(0,t.jsx)(Vg,{children:(0,t.jsx)(LHt,{})})}),(0,t.jsx)(nt,{path:"pipelines",element:(0,t.jsx)(Vg,{children:(0,t.jsx)(UO,{})})}),(0,t.jsx)(nt,{path:"pipelines/:pipelineId",element:(0,t.jsx)(Vg,{children:(0,t.jsx)(UO,{})})}),(0,t.jsx)(nt,{path:"pipelines/:pipelineId/add",element:(0,t.jsx)(Vg,{children:(0,t.jsx)(UO,{})})}),(0,t.jsx)(nt,{path:"pipelines/:pipelineId/settings",element:(0,t.jsx)(Vg,{children:(0,t.jsx)(CVt,{})})}),(0,t.jsx)(nt,{path:"pipelines/:pipelineId/items/:caseId",element:(0,t.jsx)(Vg,{children:(0,t.jsx)(ZWt,{})})}),(0,t.jsx)(nt,{path:"pipelines/:pipelineId/cases/:caseId",element:(0,t.jsx)(Vg,{children:(0,t.jsx)(VWt,{})})}),(0,t.jsx)(nt,{path:"routines/:routineId",element:e?(0,t.jsx)(ipe,{}):(0,t.jsx)(sb,{children:(0,t.jsx)(Yge,{})})}),(0,t.jsx)(nt,{path:"routines/:routineId/:section",element:e?(0,t.jsx)(ipe,{}):(0,t.jsx)(sb,{children:(0,t.jsx)(Yge,{})})}),(0,t.jsx)(nt,{element:(0,t.jsx)(FD,{}),children:(0,t.jsxs)(nt,{element:(0,t.jsx)(xyt,{}),children:[(0,t.jsx)(nt,{path:"execution-workspaces/:workspaceId",element:(0,t.jsx)(_1,{})}),(0,t.jsx)(nt,{path:"execution-workspaces/:workspaceId/services",element:(0,t.jsx)(_1,{})}),(0,t.jsx)(nt,{path:"execution-workspaces/:workspaceId/configuration",element:(0,t.jsx)(_1,{})}),(0,t.jsx)(nt,{path:"execution-workspaces/:workspaceId/runtime-logs",element:(0,t.jsx)(_1,{})}),(0,t.jsx)(nt,{path:"execution-workspaces/:workspaceId/issues",element:(0,t.jsx)(_1,{})}),(0,t.jsx)(nt,{path:"execution-workspaces/:workspaceId/routines",element:(0,t.jsx)(_1,{})})]})}),(0,t.jsx)(nt,{path:"goals",element:(0,t.jsx)(qes,{})}),(0,t.jsx)(nt,{path:"goals/:goalId",element:(0,t.jsx)(Xes,{})}),(0,t.jsx)(nt,{path:"artifacts",element:(0,t.jsx)(dpe,{})}),(0,t.jsx)(nt,{path:"approvals",element:(0,t.jsx)(_n,{to:"/approvals/pending",replace:!0})}),(0,t.jsx)(nt,{path:"approvals/pending",element:(0,t.jsx)(mpe,{})}),(0,t.jsx)(nt,{path:"approvals/all",element:(0,t.jsx)(mpe,{})}),(0,t.jsx)(nt,{path:"approvals/:approvalId",element:(0,t.jsx)(ets,{})}),(0,t.jsx)(nt,{path:"activity",element:e?(0,t.jsx)(Yts,{}):(0,t.jsx)(sb,{children:(0,t.jsx)(_gs,{})})}),e?(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)(nt,{path:"activity/runs",element:(0,t.jsx)(VC,{section:"runs"})}),(0,t.jsx)(nt,{path:"activity/costs",element:(0,t.jsx)(VC,{section:"costs"})}),(0,t.jsx)(nt,{path:"activity/budgets",element:(0,t.jsx)(VC,{section:"budgets"})}),(0,t.jsx)(nt,{path:"activity/timeline",element:(0,t.jsx)(VC,{section:"timeline"})}),(0,t.jsx)(nt,{path:"audit",element:(0,t.jsx)(Cp,{to:"/activity",forceAgentMode:!0})}),(0,t.jsx)(nt,{path:"audit/activity",element:(0,t.jsx)(Cp,{to:"/activity"})}),(0,t.jsx)(nt,{path:"audit/runs",element:(0,t.jsx)(Cp,{to:"/activity/runs"})}),(0,t.jsx)(nt,{path:"audit/costs",element:(0,t.jsx)(Cp,{to:"/activity/costs"})}),(0,t.jsx)(nt,{path:"audit/budgets",element:(0,t.jsx)(Cp,{to:"/activity/budgets"})}),(0,t.jsx)(nt,{path:"audit/timeline",element:(0,t.jsx)(Cp,{to:"/activity/timeline"})}),(0,t.jsx)(nt,{path:"runs",element:(0,t.jsx)(Cp,{to:"/activity/runs"})}),(0,t.jsx)(nt,{path:"costs",element:(0,t.jsx)(Cp,{to:"/activity/costs"})}),(0,t.jsx)(nt,{path:"budgets",element:(0,t.jsx)(Cp,{to:"/activity/budgets"})})]}):(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)(nt,{path:"costs",element:(0,t.jsx)(HK,{})}),(0,t.jsx)(nt,{path:"audit",element:(0,t.jsx)(_n,{to:"/activity?mode=agents",replace:!0})})]}),(0,t.jsxs)(nt,{element:(0,t.jsx)(cgt,{}),children:[(0,t.jsx)(nt,{path:"board-chat",element:(0,t.jsx)(zns,{})}),(0,t.jsx)(nt,{path:"artifacts",element:(0,t.jsx)(dpe,{})})]}),null,(0,t.jsx)(nt,{path:"decisions",element:(0,t.jsx)(mns,{})}),(0,t.jsx)(nt,{path:"decisions/queues/:key",element:(0,t.jsx)(xns,{})}),n?(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)(nt,{path:"inbox",element:(0,t.jsx)(Jge,{})}),(0,t.jsx)(nt,{path:"inbox/mine",element:(0,t.jsx)(Th,{view:"mine"})}),(0,t.jsx)(nt,{path:"inbox/recent",element:(0,t.jsx)(Th,{view:"recent"})}),(0,t.jsx)(nt,{path:"inbox/unread",element:(0,t.jsx)(Th,{view:"unread"})}),(0,t.jsx)(nt,{path:"inbox/blocked",element:(0,t.jsx)(Th,{view:"blocked"})}),(0,t.jsx)(nt,{path:"inbox/all",element:(0,t.jsx)(Th,{view:"everything"})}),(0,t.jsx)(nt,{path:"inbox/new",element:(0,t.jsx)(Th,{view:"mine"})})]}):(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)(nt,{path:"inbox",element:(0,t.jsx)(Jge,{})}),(0,t.jsx)(nt,{path:"inbox/mine",element:(0,t.jsx)(K1,{})}),(0,t.jsx)(nt,{path:"inbox/recent",element:(0,t.jsx)(K1,{})}),(0,t.jsx)(nt,{path:"inbox/unread",element:(0,t.jsx)(K1,{})}),(0,t.jsx)(nt,{path:"inbox/blocked",element:(0,t.jsx)(K1,{})}),(0,t.jsx)(nt,{path:"inbox/all",element:(0,t.jsx)(K1,{})}),(0,t.jsx)(nt,{path:"inbox/new",element:(0,t.jsx)(_n,{to:"/inbox/mine",replace:!0})})]}),(0,t.jsx)(nt,{path:"inbox/requests",element:(0,t.jsx)(wgs,{})}),(0,t.jsx)(nt,{path:"u/:userSlug",element:(0,t.jsx)(xes,{})}),(0,t.jsx)(nt,{path:"design-guide",element:(0,t.jsx)(hxs,{})}),(0,t.jsx)(nt,{path:"instance/settings/adapters",element:(0,t.jsx)(Mge,{})}),(0,t.jsx)(nt,{path:":pluginRoutePath/*",element:(0,t.jsx)(Pge,{})}),(0,t.jsx)(nt,{path:"*",element:(0,t.jsx)(om,{scope:"board"})})]})}r(Tgs,"boardRoutes");function Zge({credentialSource:e="paperclip_vault"}={}){const s=ua(),n=new URLSearchParams(s.search),{enabled:a,githubEnabled:i}=cw();return Fmt(n,{chatConnectorsEnabled:a,githubReviewBotsEnabled:i})?(0,t.jsx)(q7e,{credentialSource:e}):(0,t.jsx)(_n,{to:"/apps",replace:!0})}r(Zge,"AppsConnectEntryRoute");function Jge(){const{enabled:e}=Rc(),{enabled:s}=Q3();return e&&s?(0,t.jsx)(Th,{view:nFe(cte())}):(0,t.jsx)(_n,{to:`/inbox/${cte()}`,replace:!0})}r(Jge,"InboxRootRedirect");function Th({view:e}){const s=ua(),n=new URLSearchParams(s.search);return n.set(VT,e),(0,t.jsx)(_n,{to:`/issues?${n.toString()}${s.hash}`,replace:!0})}r(Th,"TaskViewRedirect");function vDe(){const e=ua(),{companies:s,selectedCompany:n,loading:a}=ps(),{companyPrefix:i,skillId:o}=ga();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)(_n,{to:"/skills/studio",replace:!0}):(0,t.jsx)(_n,{to:`/${l.issuePrefix}/skills/studio/${encodeURIComponent(o)}${e.search}${e.hash}`,replace:!0})}r(vDe,"LegacySkillStudioRedirect");function $y(){const e=ua(),{companies:s,selectedCompany:n,loading:a}=ps(),{companyPrefix:i}=ga(),{hidden:o}=Au();if(a)return(0,t.jsx)(nh,{});const l=(i?s.find(d=>d.issuePrefix.toUpperCase()===i.toUpperCase()):null)??n??s[0]??null;if(!l)return KV({pathname:e.pathname,hasCompanies:!1})?(0,t.jsx)(_n,{to:"/onboarding",replace:!0}):(0,t.jsx)(aJ,{});const c=hGe(aNe(`${e.pathname}${e.search}${e.hash}`),o);return(0,t.jsx)(_n,{to:`/${l.issuePrefix}${c}`,replace:!0})}r($y,"LegacySettingsRedirect");function Xge(){const{tab:e}=ga();return(0,t.jsx)(_n,{to:yDe(e),replace:!0})}r(Xge,"LegacyToolsSettingsRedirect");function ebe(){const{tab:e}=ga();return(0,t.jsx)(_n,{to:yDe(e),replace:!0})}r(ebe,"LegacyToolsRedirect");function yDe(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(yDe,"legacyToolsRedirectTarget");function jDe(){const{companies:e}=ps(),{openOnboarding:s}=al(),{t:n}=Rke(),a=ed(),i=p3e(a?.cloudBaseUrl??null),{onboardingOpen:o,onboardingRouteDismissed:l}=P8(),{companyPrefix:c}=ga(),d=c?e.find(p=>p.issuePrefix.toUpperCase()===c.toUpperCase())??null:null;if(jft({onboardingOpen:o,routeDismissed:l}))return null;const u=d?`Add another agent to ${d.name}`:e.length>0?"Create another organization":"Create your first organization",h=d?"Run onboarding again to add an agent and a starter task for this organization.":e.length>0?"Run onboarding again to create another organization and seed its first agent.":"Get started by creating an organization and your first agent.";return(0,t.jsx)("div",{className:"mx-auto max-w-xl py-10",children:(0,t.jsxs)("div",{className:"rounded-lg border border-border bg-card p-6",children:[(0,t.jsx)("h1",{className:"text-xl font-semibold",children:u}),(0,t.jsx)("p",{className:"mt-2 text-sm text-muted-foreground",children:h}),(0,t.jsx)("div",{className:"mt-4",children:!d&&a&&!i?(0,t.jsx)("p",{className:"text-sm text-muted-foreground",children:n("app.cloudCreateUnavailable",{defaultValue:"Organizations are created in Paperclip Cloud. This instance can't reach it right now — try again from your Cloud portfolio."})}):(0,t.jsx)($,{onClick:r(()=>d?s({initialStep:qE(),companyId:d.id}):a&&i?sh(i):s(),"onClick"),children:d?"Add Agent":"Start Onboarding"})})]})})}r(jDe,"OnboardingRoutePage");function Rgs(){const{companies:e,selectedCompany:s,loading:n}=ps(),a=ua();if(n)return(0,t.jsx)(nh,{});const i=s??e[0]??null;return i?(0,t.jsx)(_n,{to:`/${i.issuePrefix}/dashboard`,replace:!0}):KV({pathname:a.pathname,hasCompanies:!1})?(0,t.jsx)(_n,{to:"/onboarding",replace:!0}):(0,t.jsx)(aJ,{})}r(Rgs,"CompanyRootRedirect");function tbe(){const{cardId:e}=ga(),s=yFe(),n=s?`/${s}`:"";return(0,t.jsx)(_n,{to:`${n}/status${e?`/${e}`:""}`,replace:!0})}r(tbe,"StatusCardsLegacyRedirect");function Cp({to:e,forceAgentMode:s=!1}){const n=ua(),a=new URLSearchParams(n.search);s&&a.set("mode","agents");const i=a.toString();return(0,t.jsx)(_n,{to:`${e}${i?`?${i}`:""}${n.hash}`,replace:!0})}r(Cp,"AuditCompatibilityRedirect");function ya(){const e=ua(),{companies:s,selectedCompany:n,loading:a}=ps();if(a)return(0,t.jsx)(nh,{});const i=n??s[0]??null;return i?(0,t.jsx)(_n,{to:`/${i.issuePrefix}${e.pathname}${e.search}${e.hash}`,replace:!0}):KV({pathname:e.pathname,hasCompanies:!1})?(0,t.jsx)(_n,{to:"/onboarding",replace:!0}):(0,t.jsx)(aJ,{})}r(ya,"UnprefixedBoardRedirect");function aJ(){const{openOnboarding:e}=al(),{t:s}=Rke(),n=ed(),a=p3e(n?.cloudBaseUrl??null);return(0,t.jsx)("div",{className:"mx-auto max-w-xl py-10",children:(0,t.jsxs)("div",{className:"rounded-lg border border-border bg-card p-6",children:[(0,t.jsx)("h1",{className:"text-xl font-semibold",children:s("app.noCompanies.title",{defaultValue:"Create your first organization"})}),(0,t.jsx)("p",{className:"mt-2 text-sm text-muted-foreground",children:s("app.noCompanies.description",{defaultValue:"Get started by creating an organization."})}),(0,t.jsx)("div",{className:"mt-4",children:n&&!a?(0,t.jsx)("p",{className:"text-sm text-muted-foreground",children:s("app.cloudCreateUnavailable",{defaultValue:"Organizations are created in Paperclip Cloud. This instance can't reach it right now — try again from your Cloud portfolio."})}):(0,t.jsx)($,{onClick:r(()=>n&&a?sh(a):e(),"onClick"),children:s("app.noCompanies.newCompany",{defaultValue:"New Organization"})})})]})})}r(aJ,"NoCompaniesStartPage");function Egs(){const{enabled:e,loaded:s}=Rc(),{enabled:n}=Q3();return(0,t.jsxs)(t.Fragment,{children:[(0,t.jsxs)(rFe,{children:[(0,t.jsx)(nt,{path:"oauth-handoff",element:(0,t.jsx)(pds,{})}),(0,t.jsx)(nt,{path:"auth",element:(0,t.jsx)(Xxs,{})}),(0,t.jsx)(nt,{path:"board-claim/:token",element:(0,t.jsx)(egs,{})}),(0,t.jsx)(nt,{path:"mcp-connect/:id",element:(0,t.jsx)(qge,{})}),(0,t.jsx)(nt,{path:"dot-connect/:id",element:(0,t.jsx)(qge,{agentPairingOnly:!0})}),(0,t.jsx)(nt,{path:"mcp-device",element:(0,t.jsx)(tgs,{})}),(0,t.jsx)(nt,{path:"assistant-connections",element:(0,t.jsx)(sgs,{})}),(0,t.jsx)(nt,{path:"cli-auth/:id",element:(0,t.jsx)(ngs,{})}),(0,t.jsx)(nt,{path:"invite/:token",element:(0,t.jsx)(dgs,{})}),(0,t.jsx)(nt,{path:"s/:token",element:(0,t.jsx)(Gge,{})}),(0,t.jsx)(nt,{path:"s/:token/issues/:issueId",element:(0,t.jsx)(Gge,{})}),(0,t.jsx)(nt,{element:s?(0,t.jsx)(zoe,{allowMembershipRequest:!0}):(0,t.jsx)(nh,{}),children:(0,t.jsx)(nt,{path:"chat-identity/confirm",element:(0,t.jsx)(rds,{})})}),(0,t.jsx)(nt,{path:"tests/perf/long-thread",element:(0,t.jsx)(QKt,{})}),(0,t.jsx)(nt,{path:"ux-lab/bootstrap-setup",element:(0,t.jsx)(Grs,{})}),(0,t.jsx)(nt,{path:"ux-lab/responsible-user-denial",element:(0,t.jsx)(Yrs,{})}),(0,t.jsx)(nt,{path:"ux-lab/cross-issue-collaboration",element:(0,t.jsx)(Jrs,{})}),(0,t.jsxs)(nt,{element:s?(0,t.jsx)(zoe,{}):(0,t.jsx)(nh,{}),children:[(0,t.jsx)(nt,{index:!0,element:(0,t.jsx)(Rgs,{})}),(0,t.jsx)(nt,{path:"onboarding",element:(0,t.jsx)(jDe,{})}),(0,t.jsx)(nt,{path:"instance",element:(0,t.jsx)($y,{})}),(0,t.jsx)(nt,{path:"instance/settings",element:(0,t.jsx)($y,{})}),(0,t.jsx)(nt,{path:"instance/settings/*",element:(0,t.jsx)($y,{})}),(0,t.jsx)(nt,{path:"companies",element:(0,t.jsx)(ya,{})}),(0,t.jsx)(nt,{path:"dashboard",element:(0,t.jsx)(ya,{})}),(0,t.jsx)(nt,{path:"inbox/*",element:(0,t.jsx)(ya,{})}),(0,t.jsx)(nt,{path:"issues",element:(0,t.jsx)(ya,{})}),(0,t.jsx)(nt,{path:"tasks",element:(0,t.jsx)(ya,{})}),(0,t.jsx)(nt,{path:"issues/:issueId",element:(0,t.jsx)(ya,{})}),(0,t.jsx)(nt,{path:"routines",element:(0,t.jsx)(ya,{})}),(0,t.jsx)(nt,{path:"routines/:routineId",element:(0,t.jsx)(ya,{})}),(0,t.jsx)(nt,{path:"review-queue",element:(0,t.jsx)(ya,{})}),(0,t.jsx)(nt,{path:"learnings",element:(0,t.jsx)(ya,{})}),(0,t.jsx)(nt,{path:"cases",element:(0,t.jsx)(ya,{})}),(0,t.jsx)(nt,{path:"cases/:caseIdentifier",element:(0,t.jsx)(ya,{})}),(0,t.jsx)(nt,{path:"pixels-office",element:(0,t.jsx)(ya,{})}),(0,t.jsx)(nt,{path:"status",element:(0,t.jsx)(ya,{})}),(0,t.jsx)(nt,{path:"status/:cardId",element:(0,t.jsx)(ya,{})}),(0,t.jsx)(nt,{path:"status-cards",element:(0,t.jsx)(ya,{})}),(0,t.jsx)(nt,{path:"status-cards/:cardId",element:(0,t.jsx)(ya,{})}),(0,t.jsx)(nt,{path:"pipelines",element:(0,t.jsx)(ya,{})}),(0,t.jsx)(nt,{path:"pipelines/:pipelineId",element:(0,t.jsx)(ya,{})}),(0,t.jsx)(nt,{path:"pipelines/:pipelineId/add",element:(0,t.jsx)(ya,{})}),(0,t.jsx)(nt,{path:"pipelines/:pipelineId/settings",element:(0,t.jsx)(ya,{})}),(0,t.jsx)(nt,{path:"pipelines/:pipelineId/items/:caseId",element:(0,t.jsx)(ya,{})}),(0,t.jsx)(nt,{path:"pipelines/:pipelineId/cases/:caseId",element:(0,t.jsx)(ya,{})}),(0,t.jsx)(nt,{path:"artifacts",element:(0,t.jsx)(ya,{})}),(0,t.jsx)(nt,{path:"audit",element:(0,t.jsx)(ya,{})}),e?(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)(nt,{path:"audit/*",element:(0,t.jsx)(ya,{})}),(0,t.jsx)(nt,{path:"activity",element:(0,t.jsx)(ya,{})}),(0,t.jsx)(nt,{path:"activity/*",element:(0,t.jsx)(ya,{})}),(0,t.jsx)(nt,{path:"runs",element:(0,t.jsx)(ya,{})}),(0,t.jsx)(nt,{path:"costs",element:(0,t.jsx)(ya,{})}),(0,t.jsx)(nt,{path:"budgets",element:(0,t.jsx)(ya,{})})]}):null,(0,t.jsx)(nt,{path:"decisions",element:(0,t.jsx)(ya,{})}),(0,t.jsx)(nt,{path:"u/:userSlug",element:(0,t.jsx)(ya,{})}),(0,t.jsx)(nt,{path:"skills/studio",element:(0,t.jsx)(ya,{})}),(0,t.jsx)(nt,{path:"skills/studio/new",element:(0,t.jsx)(ya,{})}),(0,t.jsx)(nt,{path:"skills/studio/:skillId",element:(0,t.jsx)(ya,{})}),(0,t.jsx)(nt,{path:"skills/:skillId/studio",element:(0,t.jsx)(vDe,{})}),(0,t.jsx)(nt,{path:"skills/*",element:(0,t.jsx)(ya,{})}),(0,t.jsx)(nt,{path:"settings",element:(0,t.jsx)($y,{})}),(0,t.jsx)(nt,{path:"settings/*",element:(0,t.jsx)($y,{})}),(0,t.jsx)(nt,{path:"agents",element:(0,t.jsx)(ya,{})}),fY.map(a=>(0,t.jsx)(nt,{path:`agents/${a}`,element:(0,t.jsx)(ya,{})},a)),(0,t.jsx)(nt,{path:"agents/new",element:(0,t.jsx)(ya,{})}),(0,t.jsx)(nt,{path:"agents/:agentId",element:(0,t.jsx)(ya,{})}),(0,t.jsx)(nt,{path:"agents/:agentId/:tab",element:(0,t.jsx)(ya,{})}),(0,t.jsx)(nt,{path:"agents/:agentId/runs/:runId",element:(0,t.jsx)(ya,{})}),(0,t.jsx)(nt,{path:"projects",element:(0,t.jsx)(ya,{})}),(0,t.jsx)(nt,{path:"projects/:projectId",element:(0,t.jsx)(ya,{})}),(0,t.jsx)(nt,{path:"projects/:projectId/overview",element:(0,t.jsx)(ya,{})}),(0,t.jsx)(nt,{path:"projects/:projectId/issues",element:(0,t.jsx)(ya,{})}),(0,t.jsx)(nt,{path:"projects/:projectId/issues/:filter",element:(0,t.jsx)(ya,{})}),(0,t.jsx)(nt,{path:"projects/:projectId/workspaces",element:(0,t.jsx)(ya,{})}),(0,t.jsx)(nt,{path:"projects/:projectId/workspaces/:workspaceId",element:(0,t.jsx)(ya,{})}),(0,t.jsx)(nt,{path:"projects/:projectId/configuration",element:(0,t.jsx)(ya,{})}),(0,t.jsx)(nt,{path:"workspaces",element:(0,t.jsx)(ya,{})}),(0,t.jsx)(nt,{path:"terminal",element:(0,t.jsx)(ya,{})}),(0,t.jsx)(nt,{path:"execution-workspaces/:workspaceId",element:(0,t.jsx)(r1,{})}),(0,t.jsx)(nt,{path:"execution-workspaces/:workspaceId/services",element:(0,t.jsx)(r1,{})}),(0,t.jsx)(nt,{path:"execution-workspaces/:workspaceId/configuration",element:(0,t.jsx)(r1,{})}),(0,t.jsx)(nt,{path:"execution-workspaces/:workspaceId/runtime-logs",element:(0,t.jsx)(r1,{})}),(0,t.jsx)(nt,{path:"execution-workspaces/:workspaceId/issues",element:(0,t.jsx)(r1,{})}),(0,t.jsx)(nt,{path:"execution-workspaces/:workspaceId/routines",element:(0,t.jsx)(r1,{})}),(0,t.jsx)(nt,{path:":companyPrefix",element:e?(0,t.jsx)(_xt,{}):(0,t.jsx)(igt,{}),children:Tgs(e,n)}),(0,t.jsx)(nt,{path:"*",element:(0,t.jsx)(om,{scope:"global"})})]})]}),(0,t.jsx)(okt,{}),(0,t.jsx)(oxt,{})]})}r(Egs,"App");var Lgs=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){WV(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 Mgs(){const{data:e}=te({queryKey:M.auth.session,queryFn:r(()=>Ma.getSession(),"queryFn"),retry:!1}),s=e?.sentryDsn,n=e?.sentryEnvironment??void 0;return(0,m.useEffect)(()=>{if(s)return Bft(s,n),()=>{Fft()}},[s,n]),null}r(Mgs,"SentryGate");function Pgs(e){let s=ig();qae(s),eq(s,e.userId);const n=q5e(()=>{const o=ig();o!==s&&(s=o,qae(o),eq(o,e.userId))}),a=typeof navigator<"u"&&"serviceWorker"in navigator?navigator.serviceWorker:null,i=r(o=>{const l=K0t(o.data);l&&(l.type==="navigate"?e.navigate(l.url):q0t(l.notification))},"onMessage");return a?.addEventListener("message",i),a?.startMessages(),()=>{n(),a?.removeEventListener("message",i)}}r(Pgs,"startNotificationRuntime");function Dgs(){const e=Yn(),s=(0,m.useRef)(e),{data:n}=te({queryKey:M.auth.session,queryFn:r(()=>Ma.getSession(),"queryFn"),retry:!1}),a=n?.user?.id??n?.session?.userId??null;return(0,m.useEffect)(()=>{s.current=e},[e]),(0,m.useEffect)(()=>{if(a)return Pgs({userId:a,navigate:r(i=>s.current(i),"navigate")})},[a]),null}r(Dgs,"NotificationRuntime");var wDe={get:r(e=>we.get(`/companies/${e}/primary-agent/me`),"get"),set:r((e,s)=>we.put(`/companies/${e}/primary-agent/me`,s),"set")};function $gs(e){const s=te({queryKey:M.auth.session,queryFn:r(()=>Ma.getSession(),"queryFn")}),n=s.data?.user?.id??s.data?.session?.userId??"local-board",a=te({queryKey:M.primaryAgent.mine(e??"__none__",n),queryFn:r(()=>wDe.get(e),"queryFn"),enabled:!!e&&s.isSuccess});return{...a,userId:n,loading:!!e&&(s.isPending||a.isPending&&!s.error),error:s.error??a.error,retry:r(()=>s.isError?s.refetch():a.refetch(),"retry")}}r($gs,"usePrimaryAgent");function Ogs({children:e}){const{selectedCompanyId:s}=ps(),n=$gs(s),a=kt(),{pushToast:i}=Xr(),o=(0,m.useRef)({companyId:s,userId:n.userId});o.current={companyId:s,userId:n.userId};const l=r(f=>M.primaryAgent.mine(f.companyId,f.userId),"keyFor"),c=r(f=>f.companyId===o.current.companyId&&f.userId===o.current.userId,"isCurrentScope"),d=te({queryKey:M.agents.list(s),queryFn:r(()=>_t.list(s),"queryFn"),enabled:!!s}),u=je({mutationFn:r(f=>wDe.set(f.companyId,{primaryAgentId:f.agentId}),"mutationFn"),onMutate:r(async f=>{const x=l(f);await a.cancelQueries({queryKey:x});const g=a.getQueryData(x);return a.setQueryData(x,{companyId:f.companyId,userId:f.userId,primaryAgentId:f.agentId,initialized:!0}),{previous:g}},"onMutate"),onError:r((f,x,g)=>{a.setQueryData(l(x),g?.previous),c(x)&&i({title:"Couldn't change your primary agent.",body:f.message,tone:"error",action:{label:"Retry",onClick:r(()=>{c(x)&&u.mutate(x)},"onClick")}})},"onError"),onSuccess:r((f,x)=>a.setQueryData(l(x),f),"onSuccess"),onSettled:r((f,x,g)=>{a.invalidateQueries({queryKey:l(g)}),a.invalidateQueries({queryKey:M.resourceMemberships.mine(g.companyId)})},"onSettled")}),h=d.data?.find(f=>f.id===n.data?.primaryAgentId&&f.status!=="terminated")??null,p=n.error??d.error;return(0,t.jsx)(jVe,{value:s?{companyId:s,primaryAgentId:h?.id??null,primaryAgent:h,loading:n.loading||d.isPending,error:p?.message,onRetry:r(()=>{n.retry(),d.refetch()},"onRetry"),pendingAgentId:u.isPending&&c(u.variables)?u.variables.agentId:null,onChange:r(f=>u.mutate({companyId:s,userId:n.userId,agentId:f}),"onChange")}:null,children:e})}r(Ogs,"PrimaryAgentProvider");function Bgs(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(Bgs,"managedRoutineToRow");function Fgs({routines:e,agents:s=[],projects:n=[],pluginDisplayName:a=null,emptyMessage:i="No managed routines.",runningRoutineKey:o=null,statusMutationRoutineKey:l=null,reconcilingRoutineKey:c=null,resettingRoutineKey:d=null,onRunNow:u,onToggleEnabled:h,onReconcile:p,onReset:f}){const x=new Map(s.map(v=>[v.id,v])),g=new Map(n.map(v=>[v.id,{name:v.name,color:v.color}]));return e.length===0?(0,t.jsx)("div",{className:"rounded-lg border border-border px-3 py-8 text-center text-sm text-muted-foreground",children:i}):(0,t.jsx)("div",{className:"rounded-lg border border-border",children:e.map(v=>{const y=Bgs(v),k=v.href??(v.routineId?`/routines/${v.routineId}`:"/routines"),w=v.missingRefs??[],N=!!(v.routineId&&v.resourceKey&&w.length===0),S=v.managedByPluginDisplayName??a,C=!!(p||f);return(0,t.jsxs)("div",{className:"last:[&_a]:border-b-0",children:[(0,t.jsx)(V8e,{routine:y,projectById:g,agentById:x,runningRoutineId:o,statusMutationRoutineId:l,href:k,configureLabel:"Configure",managedByLabel:S?`Managed by ${S}`:null,runNowButton:!0,hideArchiveAction:!0,disableRunNow:!N,disableToggle:!N,secondaryDetails:(0,t.jsxs)("span",{className:"flex flex-wrap items-center gap-x-3 gap-y-1",children:[v.resourceKey?(0,t.jsx)("span",{children:v.resourceKey}):null,v.cronExpression?(0,t.jsxs)("span",{children:["Schedule ",v.cronExpression]}):null]}),onRunNow:r(()=>u?.(v),"onRunNow"),onToggleEnabled:r(()=>h?.(v,y.status==="active"),"onToggleEnabled")}),C?(0,t.jsxs)("div",{className:"flex flex-wrap items-center justify-between gap-2 border-b border-border px-3 pb-3 text-xs text-muted-foreground last:border-b-0",onClick:r(_=>{_.preventDefault(),_.stopPropagation()},"onClick"),children:[(0,t.jsx)("span",{children:w.length?`Missing ${w.map(_=>`${_.resourceKind}:${_.resourceKey}`).join(", ")}`:"Routine defaults can be repaired."}),(0,t.jsxs)("span",{className:"flex items-center gap-2",children:[p?(0,t.jsx)($,{size:"sm",variant:"ghost",disabled:c===v.key,onClick:r(()=>p(v),"onClick"),children:c===v.key?"Reconciling...":"Reconcile"}):null,f?(0,t.jsx)($,{size:"sm",variant:"ghost",disabled:d===v.key,onClick:r(()=>f(v),"onClick"),children:d===v.key?"Resetting...":"Reset"}):null]})]}):null]},v.key)})})}r(Fgs,"ManagedRoutinesList");function sbe(e){return new Set(e??[])}r(sbe,"toPathSet");function zgs({expandedPaths:e,checkedPaths:s,selectedFile:n=null,showCheckboxes:a=!1,onToggleDir:i,onSelectFile:o,...l}){return(0,m.createElement)(kw,{...l,selectedFile:n,expandedDirs:sbe(e),checkedFiles:s?sbe(s):void 0,showCheckboxes:a,onToggleDir:i??(()=>{}),onSelectFile:o??(()=>{})})}r(zgs,"PluginSdkFileTree");function qgs(e){const[s,n]=(0,m.useState)(null);return(0,m.useEffect)(()=>{let a=!1;return fd(()=>import("./MarkdownEditor-DHz7g42W.js").then(i=>i.n).then(i=>{a||n(()=>i.MarkdownEditor)}),__vite__mapDeps([44,5,7,9,14,15,33,28,31,45,30,29,21,46])),()=>{a=!0}},[]),s?(0,m.createElement)(s,e):(0,m.createElement)("textarea",{className:e.className,value:e.value,placeholder:e.placeholder,readOnly:e.readOnly,onBlur:e.onBlur,onChange:r(a=>e.onChange(a.currentTarget.value),"onChange")})}r(qgs,"PluginSdkMarkdownEditor");function Ugs(e){return Object.fromEntries(Object.entries(e).filter(([,s])=>s!=null&&s!==""&&s!==!1))}r(Ugs,"compactIssueFilters");function Kgs({companyId:e,projectId:s=null,filters:n,viewStateKey:a="paperclip:plugin-issues-view",initialSearch:i,createIssueLabel:o,searchWithinLoadedIssues:l=!0}){const c=kt(),d=(0,m.useMemo)(()=>Ugs({...n??{},projectId:n?.projectId??s??void 0}),[n,s]),u=d.originKindPrefix??null,h=d.projectId??s??null,p=(0,m.useMemo)(()=>["plugins","sdk-ui","issues-list",e??"__no-company__",d],[e,d]),{data:f}=te({queryKey:M.agents.list(e??"__no-company__"),queryFn:r(()=>_t.list(e),"queryFn"),enabled:!!e}),{data:x}=te({queryKey:M.projects.list(e??"__no-company__",{includeArchived:!0}),queryFn:r(()=>oa.list(e,{includeArchived:!0}),"queryFn"),enabled:!!e}),g=M.liveRuns(e??"__no-company__"),v=Co({companyId:e,resourceKey:"live-runs",queryKey:g,enabled:!!e,refetchInterval:!1,leaderOnly:!0}),{data:y,dataUpdatedAt:k}=te({queryKey:g,queryFn:r(()=>na.liveRunsForCompany(e),"queryFn"),enabled:v.enabled,refetchInterval:v.refetchInterval});_o(v,y,k);const{data:w,isLoading:N,error:S}=te({queryKey:p,queryFn:r(()=>jt.list(e,d),"queryFn"),enabled:!!e}),C=(0,m.useMemo)(()=>pg(y,w),[w,y]),_=je({mutationFn:r(({id:R,data:I})=>jt.update(R,I),"mutationFn"),onSuccess:r(()=>{e&&(c.invalidateQueries({queryKey:["plugins","sdk-ui","issues-list",e]}),c.invalidateQueries({queryKey:M.issues.list(e)}),h&&(c.invalidateQueries({queryKey:M.issues.listByProject(e,h)}),u&&c.invalidateQueries({queryKey:M.issues.listPluginOperationsByProject(e,h,u)})))},"onSuccess")});return e?(0,m.createElement)(Jx,{issues:w??[],isLoading:N,error:S,agents:f,projects:x,liveIssueIds:C,projectId:h??void 0,viewStateKey:a,initialSearch:i,createIssueLabel:o,searchWithinLoadedIssues:l,onUpdateIssue:r((R,I)=>_.mutate({id:R,data:I}),"onUpdateIssue")}):(0,m.createElement)("div",{className:"text-sm text-muted-foreground"},"Select an organization to view tasks.")}r(Kgs,"PluginSdkIssuesList");function Qgs({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=VW(),f=e??p.companyId??null,{data:x}=te({queryKey:M.auth.session,queryFn:r(()=>Ma.getSession(),"queryFn"),enabled:c}),g=x?.user?.id??x?.session?.userId??null,{data:v}=te({queryKey:M.agents.list(f??"__no-company__"),queryFn:r(()=>_t.list(f),"queryFn"),enabled:!!f}),{data:y}=te({queryKey:M.access.companyUserDirectory(f??"__no-company__"),queryFn:r(()=>ir.listUserDirectory(f),"queryFn"),enabled:!!f&&c}),k=(0,m.useMemo)(()=>uF(),[]),w=(0,m.useMemo)(()=>k.map(R=>R.startsWith("agent:")?R.slice(6):null).filter(R=>!!R),[k]),N=(0,m.useMemo)(()=>gj((v??[]).filter(R=>d||R.status!=="terminated"),w),[v,d,w]),S=(0,m.useMemo)(()=>[...c?Pve(g):[],...c?xS(y?.users,{excludeUserIds:[g]}):[],...N.map(R=>({id:$h({assigneeAgentId:R.id}),label:R.name,searchText:`${R.name} ${R.role} ${R.title??""}`}))],[y?.users,g,c,N]),C=Zy(s),_=C.assigneeAgentId?N.find(R=>R.id===C.assigneeAgentId):null;return(0,m.createElement)(rm,{value:s,options:S,recentOptionIds:k,placeholder:a,noneLabel:i,searchPlaceholder:o,emptyMessage:l,className:u,onConfirm:h,onChange:r(R=>{const I=Zy(R);I.assigneeAgentId&&bj(I.assigneeAgentId),I.assigneeUserId&&K_(I.assigneeUserId),n(R,I)},"onChange"),renderTriggerValue:r(R=>R?_?(0,m.createElement)(b8,null,(0,m.createElement)(UE,{icon:_.icon,className:"h-3.5 w-3.5 shrink-0 text-muted-foreground"}),(0,m.createElement)("span",{className:"truncate"},R.label)):(0,m.createElement)("span",{className:"truncate"},R.label):(0,m.createElement)("span",{className:"text-muted-foreground"},a),"renderTriggerValue"),renderOption:r(R=>{if(!R.id)return(0,m.createElement)("span",{className:"truncate"},R.label);const I=Zy(R.id),T=I.assigneeAgentId?N.find(E=>E.id===I.assigneeAgentId):null;return(0,m.createElement)(b8,null,T?(0,m.createElement)(UE,{icon:T.icon,className:"h-3.5 w-3.5 shrink-0 text-muted-foreground"}):(0,m.createElement)(pd,{className:"h-3.5 w-3.5 shrink-0 text-muted-foreground"}),(0,m.createElement)("span",{className:"truncate"},R.label))},"renderOption")})}r(Qgs,"PluginSdkAssigneePicker");function Wgs({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=VW(),p=e??h.companyId??null,{data:f}=te({queryKey:M.auth.session,queryFn:r(()=>Ma.getSession(),"queryFn")}),x=f?.user?.id??f?.session?.userId??null,{data:g}=te({queryKey:M.projects.list(p??"__no-company__",{includeArchived:c}),queryFn:r(()=>oa.list(p,{includeArchived:c}),"queryFn"),enabled:!!p}),v=(0,m.useMemo)(()=>(g??[]).filter(S=>c||!S.archivedAt),[c,g]),{orderedProjects:y}=rw({projects:v,companyId:p,userId:x}),k=(0,m.useMemo)(()=>vj(),[]),w=(0,m.useMemo)(()=>y.map(S=>({id:S.id,label:S.name,searchText:S.description??""})),[y]),N=y.find(S=>S.id===s)??null;return(0,m.createElement)(rm,{value:s,options:w,recentOptionIds:k,placeholder:a,noneLabel:i,searchPlaceholder:o,emptyMessage:l,className:d,onConfirm:u,onChange:r(S=>{S&&qb(S),n(S)},"onChange"),renderTriggerValue:r(S=>!S||!N?(0,m.createElement)("span",{className:"text-muted-foreground"},a):(0,m.createElement)(b8,null,(0,m.createElement)("span",{className:"h-3.5 w-3.5 shrink-0 rounded-sm",style:{backgroundColor:N.color??"#6366f1"}}),(0,m.createElement)("span",{className:"truncate"},S.label)),"renderTriggerValue"),renderOption:r(S=>{if(!S.id)return(0,m.createElement)("span",{className:"truncate"},S.label);const C=y.find(_=>_.id===S.id);return(0,m.createElement)(b8,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(Wgs,"PluginSdkProjectPicker");function b8({children:e}){return(0,m.createElement)("span",{className:"contents"},e)}r(b8,"FragmentSafe");function Hgs({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(Hgs,"PluginSdkStatusBadge");function Vgs({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(Vgs,"PluginSdkDataTable");function Ggs({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(Ggs,"PluginSdkKeyValueList");function Ygs({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(Ygs,"PluginSdkMetricCard");function Zgs({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(Zgs,"PluginSdkJsonTree");function Jgs({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(Jgs,"PluginSdkSpinner");var Xgs=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 ebs(e,s){globalThis.__paperclipPluginBridge__={react:e,reactJsxRuntime:t,reactDom:s,sdkUi:{usePluginData:wGe,usePluginAction:kGe,useHostContext:VW,useHostLocation:SGe,useHostNavigation:NGe,usePluginStream:_Ge,usePluginToast:CGe,copyTextToClipboard:wa,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:Ygs,StatusBadge:Hgs,DataTable:Vgs,KeyValueList:Ggs,JsonTree:Zgs,Spinner:Jgs,ErrorBoundary:Xgs,MarkdownEditor:qgs,FileTree:zgs,IssuesList:Kgs,AssigneePicker:Qgs,ProjectPicker:Wgs,ManagedRoutinesList:Fgs}}}r(ebs,"initPluginBridge");var tbs=1e4;function sbs(e=tbs){if(typeof performance>"u"||typeof performance.clearMeasures!="function")return()=>{};const n=setInterval(r(()=>{globalThis.__paperclipKeepPerfMeasures||performance.clearMeasures()},"reap"),e);return()=>clearInterval(n)}r(sbs,"startPerfMeasureReaper");var nbs=Hj((e=>{function s(F,z){var K=F.length;F.push(z);e:for(;0<K;){var U=K-1>>>1,q=F[U];if(0<i(q,z))F[U]=z,F[K]=q,K=U;else break e}}r(s,"push");function n(F){return F.length===0?null:F[0]}r(n,"peek");function a(F){if(F.length===0)return null;var z=F[0],K=F.pop();if(K!==z){F[0]=K;e:for(var U=0,q=F.length,G=q>>>1;U<G;){var se=2*(U+1)-1,Z=F[se],ie=se+1,J=F[ie];if(0>i(Z,K))ie<q&&0>i(J,Z)?(F[U]=J,F[ie]=K,U=ie):(F[U]=Z,F[se]=K,U=se);else if(ie<q&&0>i(J,K))F[U]=J,F[ie]=K,U=ie;else break e}}return z}r(a,"pop");function i(F,z){var K=F.sortIndex-z.sortIndex;return K!==0?K:F.id-z.id}if(r(i,"compare"),e.unstable_now=void 0,typeof performance=="object"&&typeof performance.now=="function"){var o=performance;e.unstable_now=function(){return o.now()}}else{var l=Date,c=l.now();e.unstable_now=function(){return l.now()-c}}var d=[],u=[],h=1,p=null,f=3,x=!1,g=!1,v=!1,y=!1,k=typeof setTimeout=="function"?setTimeout:null,w=typeof clearTimeout=="function"?clearTimeout:null,N=typeof setImmediate<"u"?setImmediate:null;function S(F){for(var z=n(u);z!==null;){if(z.callback===null)a(u);else if(z.startTime<=F)a(u),z.sortIndex=z.expirationTime,s(d,z);else break;z=n(u)}}r(S,"advanceTimers");function C(F){if(v=!1,S(F),!g)if(n(d)!==null)g=!0,_||(_=!0,O());else{var z=n(u);z!==null&&D(C,z.startTime-F)}}r(C,"handleTimeout");var _=!1,R=-1,I=5,T=-1;function E(){return y?!0:!(e.unstable_now()-T<I)}r(E,"shouldYieldToHost");function L(){if(y=!1,_){var F=e.unstable_now();T=F;var z=!0;try{e:{g=!1,v&&(v=!1,w(R),R=-1),x=!0;var K=f;try{t:{for(S(F),p=n(d);p!==null&&!(p.expirationTime>F&&E());){var U=p.callback;if(typeof U=="function"){p.callback=null,f=p.priorityLevel;var q=U(p.expirationTime<=F);if(F=e.unstable_now(),typeof q=="function"){p.callback=q,S(F),z=!0;break t}p===n(d)&&a(d),S(F)}else a(d);p=n(d)}if(p!==null)z=!0;else{var G=n(u);G!==null&&D(C,G.startTime-F),z=!1}}break e}finally{p=null,f=K,x=!1}z=void 0}}finally{z?O():_=!1}}}r(L,"performWorkUntilDeadline");var O;if(typeof N=="function")O=r(function(){N(L)},"schedulePerformWorkUntilDeadline");else if(typeof MessageChannel<"u"){var P=new MessageChannel,Q=P.port2;P.port1.onmessage=L,O=r(function(){Q.postMessage(null)},"schedulePerformWorkUntilDeadline")}else O=r(function(){k(L,0)},"schedulePerformWorkUntilDeadline");function D(F,z){R=k(function(){F(e.unstable_now())},z)}r(D,"requestHostTimeout"),e.unstable_IdlePriority=5,e.unstable_ImmediatePriority=1,e.unstable_LowPriority=4,e.unstable_NormalPriority=3,e.unstable_Profiling=null,e.unstable_UserBlockingPriority=2,e.unstable_cancelCallback=function(F){F.callback=null},e.unstable_forceFrameRate=function(F){0>F||125<F||(I=0<F?Math.floor(1e3/F):5)},e.unstable_getCurrentPriorityLevel=function(){return f},e.unstable_next=function(F){switch(f){case 1:case 2:case 3:var z=3;break;default:z=f}var K=f;f=z;try{return F()}finally{f=K}},e.unstable_requestPaint=function(){y=!0},e.unstable_runWithPriority=function(F,z){switch(F){case 1:case 2:case 3:case 4:case 5:break;default:F=3}var K=f;f=F;try{return z()}finally{f=K}},e.unstable_scheduleCallback=function(F,z,K){var U=e.unstable_now();switch(typeof K=="object"&&K!==null?(K=K.delay,K=typeof K=="number"&&0<K?U+K:U):K=U,F){case 1:var q=-1;break;case 2:q=250;break;case 5:q=1073741823;break;case 4:q=1e4;break;default:q=5e3}return q=K+q,F={id:h++,callback:z,priorityLevel:F,startTime:K,expirationTime:q,sortIndex:-1},K>U?(F.sortIndex=K,s(u,F),n(d)===null&&F===n(u)&&(v?(w(R),R=-1):v=!0,D(C,K-U))):(F.sortIndex=q,s(d,F),g||x||(g=!0,_||(_=!0,O()))),F},e.unstable_shouldYield=E,e.unstable_wrapCallback=function(F){var z=f;return function(){var K=f;f=z;try{return F.apply(this,arguments)}finally{f=K}}}})),rbs=Hj(((e,s)=>{s.exports=nbs()})),abs=Hj((e=>{var s=rbs(),n=zQ(),a=nbe();function i(b){var j="https://react.dev/errors/"+b;if(1<arguments.length){j+="?args[]="+encodeURIComponent(arguments[1]);for(var A=2;A<arguments.length;A++)j+="&args[]="+encodeURIComponent(arguments[A])}return"Minified React error #"+b+"; visit "+j+" for the full message or use the non-minified dev environment for full errors and additional helpful warnings."}r(i,"formatProdErrorMessage");function o(b){return!(!b||b.nodeType!==1&&b.nodeType!==9&&b.nodeType!==11)}r(o,"isValidContainer");function l(b){var j=b,A=b;if(b.alternate)for(;j.return;)j=j.return;else{b=j;do j=b,(j.flags&4098)!==0&&(A=j.return),b=j.return;while(b)}return j.tag===3?A:null}r(l,"getNearestMountedFiber");function c(b){if(b.tag===13){var j=b.memoizedState;if(j===null&&(b=b.alternate,b!==null&&(j=b.memoizedState)),j!==null)return j.dehydrated}return null}r(c,"getSuspenseInstanceFromFiber");function d(b){if(b.tag===31){var j=b.memoizedState;if(j===null&&(b=b.alternate,b!==null&&(j=b.memoizedState)),j!==null)return j.dehydrated}return null}r(d,"getActivityInstanceFromFiber");function u(b){if(l(b)!==b)throw Error(i(188))}r(u,"assertIsMounted");function h(b){var j=b.alternate;if(!j){if(j=l(b),j===null)throw Error(i(188));return j!==b?null:b}for(var A=b,B=j;;){var H=A.return;if(H===null)break;var ee=H.alternate;if(ee===null){if(B=H.return,B!==null){A=B;continue}break}if(H.child===ee.child){for(ee=H.child;ee;){if(ee===A)return u(H),b;if(ee===B)return u(H),j;ee=ee.sibling}throw Error(i(188))}if(A.return!==B.return)A=H,B=ee;else{for(var ke=!1,He=H.child;He;){if(He===A){ke=!0,A=H,B=ee;break}if(He===B){ke=!0,B=H,A=ee;break}He=He.sibling}if(!ke){for(He=ee.child;He;){if(He===A){ke=!0,A=ee,B=H;break}if(He===B){ke=!0,B=ee,A=H;break}He=He.sibling}if(!ke)throw Error(i(189))}}if(A.alternate!==B)throw Error(i(190))}if(A.tag!==3)throw Error(i(188));return A.stateNode.current===A?b:j}r(h,"findCurrentFiberUsingSlowPath");function p(b){var j=b.tag;if(j===5||j===26||j===27||j===6)return b;for(b=b.child;b!==null;){if(j=p(b),j!==null)return j;b=b.sibling}return null}r(p,"findCurrentHostFiberImpl");var f=Object.assign,x=Symbol.for("react.element"),g=Symbol.for("react.transitional.element"),v=Symbol.for("react.portal"),y=Symbol.for("react.fragment"),k=Symbol.for("react.strict_mode"),w=Symbol.for("react.profiler"),N=Symbol.for("react.consumer"),S=Symbol.for("react.context"),C=Symbol.for("react.forward_ref"),_=Symbol.for("react.suspense"),R=Symbol.for("react.suspense_list"),I=Symbol.for("react.memo"),T=Symbol.for("react.lazy"),E=Symbol.for("react.activity"),L=Symbol.for("react.memo_cache_sentinel"),O=Symbol.iterator;function P(b){return b===null||typeof b!="object"?null:(b=O&&b[O]||b["@@iterator"],typeof b=="function"?b:null)}r(P,"getIteratorFn");var Q=Symbol.for("react.client.reference");function D(b){if(b==null)return null;if(typeof b=="function")return b.$$typeof===Q?null:b.displayName||b.name||null;if(typeof b=="string")return b;switch(b){case y:return"Fragment";case w:return"Profiler";case k:return"StrictMode";case _:return"Suspense";case R:return"SuspenseList";case E:return"Activity"}if(typeof b=="object")switch(b.$$typeof){case v:return"Portal";case S:return b.displayName||"Context";case N:return(b._context.displayName||"Context")+".Consumer";case C:var j=b.render;return b=b.displayName,b||(b=j.displayName||j.name||"",b=b!==""?"ForwardRef("+b+")":"ForwardRef"),b;case I:return j=b.displayName||null,j!==null?j:D(b.type)||"Memo";case T:j=b._payload,b=b._init;try{return D(b(j))}catch{}}return null}r(D,"getComponentNameFromType");var F=Array.isArray,z=n.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE,K=a.__DOM_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE,U={pending:!1,data:null,method:null,action:null},q=[],G=-1;function se(b){return{current:b}}r(se,"createCursor");function Z(b){0>G||(b.current=q[G],q[G]=null,G--)}r(Z,"pop");function ie(b,j){G++,q[G]=b.current,b.current=j}r(ie,"push");var J=se(null),re=se(null),oe=se(null),V=se(null);function X(b,j){switch(ie(oe,j),ie(re,b),ie(J,null),j.nodeType){case 9:case 11:b=(b=j.documentElement)&&(b=b.namespaceURI)?oee(b):0;break;default:if(b=j.tagName,j=j.namespaceURI)j=oee(j),b=lee(j,b);else switch(b){case"svg":b=1;break;case"math":b=2;break;default:b=0}}Z(J),ie(J,b)}r(X,"pushHostContainer");function Y(){Z(J),Z(re),Z(oe)}r(Y,"popHostContainer");function ae(b){b.memoizedState!==null&&ie(V,b);var j=J.current,A=lee(j,b.type);j!==A&&(ie(re,b),ie(J,A))}r(ae,"pushHostContext");function ne(b){re.current===b&&(Z(J),Z(re)),V.current===b&&(Z(V),j2._currentValue=U)}r(ne,"popHostContext");var ce,he;function pe(b){if(ce===void 0)try{throw Error()}catch(A){var j=A.stack.trim().match(/\n( *(at )?)/);ce=j&&j[1]||"",he=-1<A.stack.indexOf(`
707
707
  at`)?" (<anonymous>)":-1<A.stack.indexOf("@")?"@unknown:0:0":""}return`
708
708
  `+ce+b+he}r(pe,"describeBuiltInComponentFrame");var ge=!1;function Ee(b,j){if(!b||ge)return"";ge=!0;var A=Error.prepareStackTrace;Error.prepareStackTrace=void 0;try{var B={DetermineComponentFrameRoot:r(function(){try{if(j){var Ks=r(function(){throw Error()},"Fake");if(Object.defineProperty(Ks.prototype,"props",{set:r(function(){throw Error()},"set")}),typeof Reflect=="object"&&Reflect.construct){try{Reflect.construct(Ks,[])}catch(xs){var is=xs}Reflect.construct(b,[],Ks)}else{try{Ks.call()}catch(xs){is=xs}b.call(Ks.prototype)}}else{try{throw Error()}catch(xs){is=xs}(Ks=b())&&typeof Ks.catch=="function"&&Ks.catch(function(){})}}catch(xs){if(xs&&is&&typeof xs.stack=="string")return[xs.stack,is.stack]}return[null,null]},"DetermineComponentFrameRoot")};B.DetermineComponentFrameRoot.displayName="DetermineComponentFrameRoot";var H=Object.getOwnPropertyDescriptor(B.DetermineComponentFrameRoot,"name");H&&H.configurable&&Object.defineProperty(B.DetermineComponentFrameRoot,"name",{value:"DetermineComponentFrameRoot"});var ee=B.DetermineComponentFrameRoot(),ke=ee[0],He=ee[1];if(ke&&He){var yt=ke.split(`
709
709
  `),as=He.split(`